Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
1586 lines (1500 loc) · 68.1 KB
/
Copy pathcli.js
File metadata and controls
1586 lines (1500 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('node:fs');
const path = require('node:path');
const { resolvePiAgentDir, boardDir, displayPath, SESSION_ID_ENV, boardTerminalId } = require('./lib/board-dir');
const { linkUrl } = require('./public/link-url');
const { sessionProjectKey } = require('./public/project-match');
const { dispatchLine, matchDispatches, reportText, WAIT_MAX_MS } = require('./lib/dispatch-reports');
const { THINKING_LEVELS } = require('./lib/pi-agents');
const { PANE_COMPANIONS } = require('./lib/companions');
// Help is auto-generated from this table — keep flags/usage in sync with `run` behavior.
const SESSION_FLAG = '--session <id>';
const SESSION_FLAG_HELP = 'Session, full id or unique prefix (default: $PREVIEW_SESSION, else $PI_KANBAN_SESSION_ID)';
const OR_SESSION_FLAG = '; `--session <id>` works too';
const SESSION_ID_HELP = `Full session id, or a unique prefix${OR_SESSION_FLAG}`;
const COMMANDS = {
doc: {
summary: 'Show documents to the user: link them to a session, or open the preview',
verbs: {
link: {
summary: 'Link a file or URL to a session, with no modal',
usage: 'pi-kanban doc link <file|url> [--session <id>]',
flags: {
'<file|url>': 'Any file type; one the preview cannot render shows a card with its path. An http(s) URL opens in a new tab.',
[SESSION_FLAG]: SESSION_FLAG_HELP,
},
notes: 'The server keeps the link, so it shows when a browser tab opens later. Prefer this over `doc preview` while the user works.',
examples: [
'pi-kanban doc link ./design.md',
'pi-kanban doc link https://github.com/org/repo/pull/12',
],
run: runDocLinkCli,
},
unlink: {
summary: 'Remove a linked file or URL from a session',
usage: 'pi-kanban doc unlink <file|url> [--session <id>]',
flags: {
'<file|url>': 'The linked path or URL; the file need not exist',
[SESSION_FLAG]: SESSION_FLAG_HELP,
},
examples: ['pi-kanban doc unlink ./design.md'],
run: runDocLinkCli,
},
list: {
summary: 'Print the docs linked to a session',
usage: 'pi-kanban doc list [--session <id>] [--json]',
flags: {
[SESSION_FLAG]: SESSION_FLAG_HELP,
'--json': 'Output JSON',
},
run: runDocListCli,
},
preview: {
summary: 'Open a markdown or HTML file in the preview modal on connected browser tabs',
usage: 'pi-kanban doc preview <file.md|file.html|url> [--session <id>]',
flags: {
[SESSION_FLAG]: 'Switch focused session in the browser (does not link the file; default: $PREVIEW_SESSION). For a URL, the session it links to (default: $PREVIEW_SESSION, else $PI_KANBAN_SESSION_ID).',
},
notes: 'The modal opens on the user\'s screen: the only command that does. HTML renders in a sandboxed iframe; local stylesheets, scripts and images are inlined. Relative paths resolve against the current dir. An http(s) URL is linked to the session instead, and the tab on screen shows an Open button.',
examples: [
'pi-kanban doc preview ./notes.md --session $PI_KANBAN_SESSION_ID',
],
run: runPreviewCli,
},
},
},
show: {
summary: 'Show the user a card: a markdown or HTML file you wrote, rendered on the board',
usage: 'pi-kanban show <file> [--title <text>] [--key <name>] [--base <dir>] [--session <id>]',
flags: {
'<file>': 'A markdown, HTML, image or text file (relative paths resolve against the current dir)',
'--title <text>': 'Card title (default: the file name)',
'--key <name>': 'Card name, e.g. latency-chart: a card with the same key is replaced in place',
'--base <dir>': 'Folder that the card\'s path:line links resolve against, usually the repo root (default: the session cwd)',
[SESSION_FLAG]: SESSION_FLAG_HELP,
},
notes: 'From pi in the board terminal, the card opens in the overlay above the terminal. Elsewhere it opens as a background tab of the session, and --key and --base do nothing. The card refreshes on each save of the file. The show skill has the card guide.',
examples: [
'pi-kanban show ./scratch/latency.html --title "p95 latency" --key latency-chart',
'pi-kanban show ./scratch/plan.md',
],
run: runShowCli,
},
pane: {
summary: 'Add live panes (a URL or a local file) to a session\'s view, without switching to them',
verbs: {
add: {
summary: 'Add a pane to a session; it opens as a tab next to Board, in the background',
usage: 'pi-kanban pane add <url|file> | --companion <id> [--title <text>] [--session <id>] [--json]',
flags: {
'<url|file>': 'An http(s) URL, or a local HTML, markdown, text or image file (relative paths resolve against the current dir)',
'--companion <id>': 'pi-cost (the session\'s cost, tokens and models) or pi-inspect (what pi loaded), in place of a target. The board starts the tool; needs the terminal token, like dispatch start.',
'--title <text>': 'Tab title (default: the host, file name or companion)',
[SESSION_FLAG]: SESSION_FLAG_HELP,
'--json': 'Output JSON (the new pane, with frameable: true, false, or null when unknown)',
},
notes: 'The board does not switch to the new pane; the user opens it. Prints the pane id. The same target added again prints the pane it already has. A URL on the board\'s own origin is refused, and a file must be one the board can preview. A site whose headers refuse framing (X-Frame-Options, CSP frame-ancestors) is still added, but its pane shows an "Open in new tab" card, and a note line says so.',
examples: [
'pi-kanban pane add http://localhost:5173',
'pi-kanban pane add ./report.html --title Report',
'pi-kanban pane add --companion pi-cost --session $PI_KANBAN_SESSION_ID',
],
run: runPaneAddCli,
},
rm: {
summary: 'Remove a pane from a session',
usage: 'pi-kanban pane rm <pane-id> [--session <id>]',
flags: {
'<pane-id>': 'The id `pane add` or `pane list` printed',
[SESSION_FLAG]: SESSION_FLAG_HELP,
},
examples: ['pi-kanban pane rm p3'],
run: runPaneRmCli,
},
list: {
summary: 'List the panes of a session, in tab order',
usage: 'pi-kanban pane list [--session <id>] [--json]',
flags: {
[SESSION_FLAG]: SESSION_FLAG_HELP,
'--json': 'Output JSON ({rev, panes: [{id, kind, target, title, addedAt}], updatedAt})',
},
run: runPaneListCli,
},
},
},
session: {
summary: 'List, search, open, inspect and group pi sessions',
verbs: {
list: {
summary: 'List the active sessions, as the sidebar\'s Active view shows them (pinned/sticky always included)',
usage: 'pi-kanban session list [--all] [--days <n>] [--project <name>] [--limit <n|all>] [--no-pins] [--json]',
flags: {
'--all': 'Every session, active or not',
'--days <n>': 'Only sessions modified within the last N days (fractional ok, e.g. 0.5)',
'--project <name>': 'Filter by project: an absolute path selects one project, other text matches a part of the path',
'--limit <n|all>': 'Max rows to display (default: every active row; 20 with --all). Pinned sessions are kept past it.',
'--no-pins': 'Disable always-include and sticky-first ordering for pinned sessions',
'--json': 'Output JSON instead of a table',
},
notes: 'Active: running in the terminal, or with messages and open tasks, live agents, a wait on the user or recent activity. STATUS is idle, active, busy (a task in progress) or wait. When --limit cuts the list, a last line says how many rows it shows of how many (on stderr with --json).',
examples: [
'pi-kanban session list',
'pi-kanban session list --all --days 0.5 --limit 20 --project my-repo',
],
run: runSessionListCli,
},
search: {
summary: 'Find sessions whose name or id contains the text, from any transcript',
usage: 'pi-kanban session search <text> [--limit <n>] [--json]',
flags: {
'<text>': 'At least 3 characters; matched against the session name and id',
'--limit <n>': 'Max rows (default and max: 20)',
'--json': 'Output JSON instead of a table',
},
examples: [
'pi-kanban session search login-redirect',
],
run: runSessionSearchCli,
},
open: {
summary: 'Focus a session in the browser (Active tab)',
usage: 'pi-kanban session open <id>',
flags: {
'<id>': SESSION_ID_HELP,
},
examples: ['pi-kanban session open $PI_KANBAN_SESSION_ID'],
run: runSessionOpenCli,
},
view: {
summary: 'Show full session stats (metadata + context window + cost) and the transcript path',
usage: 'pi-kanban session view <id> [--json]',
flags: {
'<id>': SESSION_ID_HELP,
'--json': 'Output JSON instead of formatted sections',
},
notes: 'To learn what a session did, read its transcript (a .jsonl file, newest lines last).',
examples: ['pi-kanban session view $PI_KANBAN_SESSION_ID'],
run: runSessionViewCli,
},
agents: {
summary: 'List the subagents a session has run, and whether it waits for the user',
usage: 'pi-kanban session agents <id> [--json]',
flags: {
'<id>': SESSION_ID_HELP,
'--json': 'Output JSON ({agents, waitingForUser})',
},
notes: 'The pi-kanban pi package records the runs of pi-subagents. Without both packages in pi, the list is empty.',
examples: ['pi-kanban session agents $PI_KANBAN_SESSION_ID'],
run: runSessionAgentsCli,
},
...Object.fromEntries(PANE_COMPANIONS.map((c) => [c.verb, {
summary: `Open ${c.id} for a session as a board tab: ${c.shows}`,
usage: `pi-kanban session ${c.verb} [<id>]`,
flags: { '<id>': `${SESSION_ID_HELP} (default: $PI_KANBAN_SESSION_ID)` },
notes: 'From pi in the board terminal, the board switches to the tab. Needs the terminal token, like dispatch start.',
companion: c.id,
run: runSessionCompanionCli,
}])),
pin: {
summary: 'Pin (or unpin) a session in the sidebar; every board on this config dir shows it',
usage: 'pi-kanban session pin <id> [--sticky] [--unpin]',
flags: {
'<id>': SESSION_ID_HELP,
'--sticky': 'Set sticky state (always shown in the list)',
'--unpin': 'Clear pin/sticky state',
},
examples: [
'pi-kanban session pin $PI_KANBAN_SESSION_ID --sticky',
'pi-kanban session pin $PI_KANBAN_SESSION_ID --unpin',
],
run: runSessionPinCli,
},
group: {
summary: 'Move a session into a group in the sidebar',
usage: 'pi-kanban session group <id> (<group> | --with <session> | --parent <session>) [--no-parent] [--create] [--json]',
flags: {
'<id>': SESSION_ID_HELP,
'<group>': 'Group name (any case), path from the top (parent/child) or id, from `group list`',
'--with <session>': 'Join the group this other session shows in (id or unique prefix)',
'--parent <session>': 'Show the session under this one, indented, when both are in the same list; alone, it also joins its group',
'--no-parent': 'Show the session on its own again',
'--create': 'Make the group, and the missing parents of a path, when none matches; with --with, it holds both sessions',
'--json': 'Output JSON ({group, name, path, created, left, rev})',
},
notes: 'The session leaves the group it was in. In a group that holds its project, it shows in that project\'s block.',
examples: [
'pi-kanban session group $PI_KANBAN_SESSION_ID "Auth refactor"',
'pi-kanban session group 3fa9c1 auth-refactor/swarm-1 --create',
'pi-kanban session group 3fa9c1 --with $PI_KANBAN_SESSION_ID --create',
'pi-kanban session group 3fa9c1 --parent $PI_KANBAN_SESSION_ID',
],
run: runSessionGroupCli,
},
ungroup: {
summary: 'Take a session out of its group',
usage: 'pi-kanban session ungroup <id> [--json]',
flags: {
'<id>': SESSION_ID_HELP,
'--json': 'Output JSON ({left, rev})',
},
notes: 'A session whose project is in a group still shows there; move the project on the board.',
examples: ['pi-kanban session ungroup $PI_KANBAN_SESSION_ID'],
run: runSessionUngroupCli,
},
},
},
group: {
summary: 'Read and change the session groups in the sidebar',
verbs: {
list: {
summary: 'List the groups in sidebar order, nested groups under their parent, with the members the sidebar\'s Active view shows (active, pinned or sticky)',
usage: 'pi-kanban group list [--all] [--json]',
flags: {
'--all': 'Every member, active or not',
'--json': 'Output JSON ({rev, groups: [{id, name, parent, transient?, visible, total, members}]}); a session member has title, branch, status, pinned and age, or missing: true; a project member has sessions (its shown sessions)',
},
notes: 'A project member shows when it has a session the Active view shows. visible/total counts the members shown. A group marked (transient) goes when the board\'s Active view shows none of its sessions; Keep or a rename on the board, or `group rename`, keeps it. `dispatch start --group` and `group create --transient` make transient groups. Pass a group\'s name, path (parent/child) or id to `session group`.',
examples: ['pi-kanban group list', 'pi-kanban group list --all --json'],
run: runGroupListCli,
},
create: {
summary: 'Make a group, and the missing parents of a path',
usage: 'pi-kanban group create <name|path> [--transient] [--json]',
flags: {
'<name|path>': 'Name of a new top-level group, or a path from the top (parent/child)',
'--transient': 'The groups it makes go when the Active view shows none of their sessions',
'--json': 'Output JSON ({group, name, path, rev})',
},
notes: 'Fails when the group exists.',
examples: ['pi-kanban group create "Auth refactor"', 'pi-kanban group create auth-refactor/swarm-1'],
run: runGroupCreateCli,
},
rename: {
summary: 'Rename a group; it keeps its place, parent and members',
usage: 'pi-kanban group rename <group> <new name> [--json]',
flags: {
'<group>': 'Group name (any case), path from the top (parent/child) or id, from `group list`',
'<new name>': 'The new name',
'--json': 'Output JSON ({group, name, path, rev})',
},
examples: ['pi-kanban group rename auth-refactor "Auth v2"'],
run: runGroupRenameCli,
},
rm: {
summary: 'Remove a group, as Delete on the board does',
usage: 'pi-kanban group rm <group> [--json]',
flags: {
'<group>': 'Group name (any case), path from the top (parent/child) or id, from `group list`',
'--json': 'Output JSON ({removed: {id, name, path}, ungrouped, rev})',
},
notes: 'Its members leave the group and show as with no group: in their project\'s group or the top level. Its child groups move up one level.',
examples: ['pi-kanban group rm presales-cloud'],
run: runGroupRmCli,
},
prune: {
summary: 'Remove every empty group',
usage: 'pi-kanban group prune [--dry-run] [--json]',
flags: {
'--dry-run': 'List the groups it would remove, and remove none',
'--json': 'Output JSON ({removed: [{id, name, path}], dryRun, rev})',
},
notes: 'Empty: no session whose transcript still exists, no project, and no child group that is not empty. It checks every member, not only the ones the Active view shows.',
examples: ['pi-kanban group prune --dry-run', 'pi-kanban group prune'],
run: runGroupPruneCli,
},
},
},
task: {
summary: 'Read the tasks on the board',
verbs: {
list: {
summary: 'List the tasks of a session, a project, or every session',
usage: 'pi-kanban task list (<session> | --project <path> | --all) [--status <s>] [--json]',
flags: {
'<session>': SESSION_ID_HELP,
'--project <path>': 'Every task of the sessions in this project (absolute path, as in `project list`)',
'--all': 'Every task on the board',
'--status <s>': 'Only tasks in this status: pending, in_progress or completed',
'--json': 'Output JSON instead of a table',
},
examples: [
'pi-kanban task list $PI_KANBAN_SESSION_ID',
'pi-kanban task list --all --status in_progress',
],
run: runTaskListCli,
},
},
},
project: {
summary: 'Read the projects the board knows',
verbs: {
list: {
summary: 'List known project paths, newest activity first',
usage: 'pi-kanban project list [--json]',
flags: {
'--json': 'Output JSON instead of a table',
},
notes: 'These are the folders `dispatch start --cwd` accepts.',
run: runProjectListCli,
},
},
},
dispatch: {
summary: 'Start, wait for, list and end pi sessions for tasks in pi-kanban\'s terminal',
verbs: {
start: {
summary: 'Start pi in pi-kanban\'s terminal with a task; prints the session id',
usage: 'pi-kanban dispatch start --cwd <dir> (--spec <text> | --spec-file <path>) [--name <n>] [--group <g>] [--model <m>] [--thinking <level>] [--json] [-- <pi args>...]',
flags: {
'--cwd <dir>': 'Folder to run in (any existing folder, default: current dir)',
'--spec <text>': 'The task, self-contained; sent as the first message',
'--spec-file <path>': 'Read the task from a file',
'--name <n>': 'Session name',
'--group <g>': 'Add it to this group: a name, path or id. The groups it makes are transient (see `help group list`)',
'--model <m>': 'pi model pattern, provider/id (see `pi --list-models`)',
'--thinking <level>': [...THINKING_LEVELS].join(', '),
'--json': 'Output JSON',
'-- <pi args>': 'Passed to pi as they are, e.g. --tools read,bash. No quotes, % or control characters; pi-kanban sets --session-id, --name, --model and --thinking',
},
notes: 'Needs the terminal token, so it runs on the machine of the pi-kanban server. The session gets the dispatch_report tool and reports through the board; read the report with `dispatch wait`. Run `pi-kanban skills get dispatch` for how to write the spec.',
examples: [
'pi-kanban dispatch start --cwd . --spec-file spec.md --name fix-login-redirect --group auth-refactor --thinking high',
'pi-kanban dispatch start --cwd . --spec "Run the tests and report the failures" --model codemie/gpt-6-luna',
],
run: runDispatchStartCli,
},
wait: {
summary: 'Wait for the reports of sessions this session started, and print them',
usage: 'pi-kanban dispatch wait <session id>...',
flags: { '<session id>': `The full id \`dispatch start\` printed; give several to wait for each in turn${OR_SESSION_FLAG}` },
notes: 'Prints a report at once when it is already in, and says so when the session\'s terminal ended without one.',
examples: ['pi-kanban dispatch wait 01a30000-0000-7000-8000-000000000004'],
run: runDispatchWaitCli,
},
list: {
summary: 'List sessions this session started that still run in pi-kanban\'s terminal',
usage: 'pi-kanban dispatch list [--all] [--json]',
flags: {
'--all': 'Every dispatch on this board',
'--json': 'Output JSON',
},
run: runDispatchListCli,
},
end: {
summary: 'End the terminal of a session this session started',
usage: 'pi-kanban dispatch end (<session id or prefix> | --name <n>) [--json]',
flags: {
'<session id or prefix>': `A session from \`dispatch list\`${OR_SESSION_FLAG}`,
'--name <n>': 'The session\'s --name from dispatch start',
'--json': 'Output JSON',
},
notes: 'Needs the terminal token, like dispatch start.',
examples: ['pi-kanban dispatch end --name api-worker'],
run: runDispatchEndCli,
},
},
},
terminal: {
summary: 'Read the terminals running in pi-kanban',
verbs: {
list: {
summary: 'List every terminal in pk: dispatched and opened by hand',
usage: 'pi-kanban terminal list [--json]',
flags: {
'--json': 'Output JSON',
},
notes: 'Read-only. `dispatch end` ends a terminal this session dispatched; the user ends the others from the board.',
run: runTerminalListCli,
},
},
},
skills: {
summary: 'Print a skill bundled with this version',
verbs: {
get: {
summary: 'Print the SKILL.md of a skill',
usage: 'pi-kanban skills get <name>',
flags: { '<name>': 'Skill name, e.g. dispatch' },
examples: ['pi-kanban skills get dispatch'],
run: runSkillsGetCli,
},
},
},
};
for (const [noun, cmd] of Object.entries(COMMANDS)) {
cmd.name = noun;
for (const [verb, v] of Object.entries(cmd.verbs || {})) v.name = `${noun} ${verb}`;
}
function runCli(argv) {
if (argv.includes('--version') || argv.includes('-v')) {
console.log(require('./package.json').version);
process.exit(0);
}
const cli = resolveCliCommand(argv);
if (cli.kind === 'server') return false;
if (cli.kind === 'help') {
const noun = cli.target && Object.hasOwn(COMMANDS, cli.target) ? COMMANDS[cli.target] : null;
const verb = noun?.verbs && cli.verb && Object.hasOwn(noun.verbs, cli.verb) ? noun.verbs[cli.verb] : null;
if (verb) printLeafHelp(verb);
else if (noun) printNounHelp(cli.target);
else printTopHelp();
process.exit(0);
}
if (cli.kind === 'unknown-noun') {
console.error(`Unknown command: ${cli.noun}\n`);
printTopHelp();
process.exit(1);
}
if (cli.kind === 'unknown-verb') {
console.error(`Unknown subcommand: ${cli.noun} ${cli.verb}\n`);
printNounHelp(cli.noun);
process.exit(1);
}
if (cli.kind === 'noun') {
printNounHelp(cli.noun);
process.exit(argv.includes('--help') || argv.includes('-h') ? 0 : 1);
}
if (cli.kind === 'leaf') {
if (cli.args.includes('--help') || cli.args.includes('-h')) {
printLeafHelp(cli.entry);
process.exit(0);
}
cli.entry.run(cli.args, cli.entry)
.then(code => { process.exitCode = code; })
.catch(e => { console.error(e.message); process.exitCode = 1; });
return true;
}
return true;
}
function resolveCliCommand(argv) {
const noun = argv[2] && !argv[2].startsWith('-') ? argv[2] : null;
const hasHelp = (a) => a.includes('--help') || a.includes('-h');
if (!noun) return hasHelp(argv) ? { kind: 'help' } : { kind: 'server' };
if (noun === 'help') return { kind: 'help', target: argv[3], verb: argv[4] };
if (!Object.hasOwn(COMMANDS, noun)) return { kind: 'unknown-noun', noun };
const entry = COMMANDS[noun];
if (!entry.verbs) return { kind: 'leaf', name: noun, entry, args: argv.slice(3) };
const verb = argv[3] && !argv[3].startsWith('-') ? argv[3] : null;
if (!verb) return { kind: 'noun', noun };
if (!Object.hasOwn(entry.verbs, verb)) return { kind: 'unknown-verb', noun, verb };
return { kind: 'leaf', name: `${noun} ${verb}`, entry: entry.verbs[verb], args: argv.slice(4) };
}
// The website's reference/cli.md has the same table; change both.
const SERVER_FLAGS = [
['--port <n>', 'PORT', 'Port (default 3460)'],
['--open', '', 'Open the board in the browser'],
['--dir <path>', 'PI_CODING_AGENT_DIR', 'pi agent dir (default ~/.pi/agent)'],
['--session-dir <dir>', 'PI_CODING_AGENT_SESSION_DIR', 'pi session dir (default: sessionDir in pi settings)'],
['--no-terminal', '', 'Turn off the board terminal'],
['--new-token', '', 'Replace the saved terminal token'],
['--terminal-shell <shell>', 'PK_TERMINAL_SHELL', 'gitbash, a program on PATH, or a path'],
['--host <addr>', 'HOST', 'Listen address (default 127.0.0.1)'],
['--allowed-hosts <list>', 'ALLOWED_HOSTS', 'Extra Host header values, comma-separated'],
];
function topHelp() {
const lines = ['Usage: pi-kanban <command> [args] [--flags]\n', 'Commands:'];
for (const [name, cmd] of Object.entries(COMMANDS)) {
const verbs = cmd.verbs ? ` (${Object.keys(cmd.verbs).join(', ')})` : '';
lines.push(` ${name.padEnd(20)}${cmd.summary}${verbs}`);
}
lines.push(` ${'help'.padEnd(20)}Show help for a command (pi-kanban help <command>)`);
lines.push('\nFlags:');
lines.push(' --help, -h Show help (top-level, noun-level, or leaf-level)');
lines.push(' --version, -v Print version and exit');
lines.push('\nServer (no command; a flag wins over its env var):');
const flagPad = Math.max(...SERVER_FLAGS.map(([flag]) => flag.length)) + 2;
const envPad = Math.max(...SERVER_FLAGS.map(([, env]) => env.length)) + 2;
for (const [flag, env, desc] of SERVER_FLAGS) lines.push(` ${flag.padEnd(flagPad)}${env.padEnd(envPad)}${desc}`);
lines.push('\nCommand env:');
lines.push(' PK_URL Server base URL, e.g. http://127.0.0.1:4795 (wins over PORT)');
lines.push(' PORT Server port (default: the one this config dir\'s server reports, else 3460)');
lines.push(' PI_CODING_AGENT_DIR pi agent dir whose board to use');
lines.push('\nRun `pi-kanban help <command>` for its subcommands, and `help <command> <subcommand>` for flags and examples.');
return lines.join('\n');
}
function printTopHelp() {
console.log(topHelp());
}
function printNounHelp(noun) {
const entry = COMMANDS[noun];
if (!entry.verbs) return printLeafHelp(entry);
console.log(`${entry.summary}\n`);
console.log(`Usage: pi-kanban ${noun} <subcommand> [args] [--flags]\n`);
console.log('Subcommands:');
for (const [vName, v] of Object.entries(entry.verbs)) {
console.log(` ${vName.padEnd(12)}${v.summary}`);
}
console.log(`\nRun \`pi-kanban help ${noun} <subcommand>\` for flags and examples.`);
}
function printLeafHelp(entry) {
console.log(`${entry.summary}\n`);
console.log(`Usage: ${entry.usage}`);
const flags = { ...entry.flags, '--help, -h': 'Show this help' };
const pad = Math.max(...Object.keys(flags).map(f => f.length));
console.log('\nFlags:');
for (const [flag, desc] of Object.entries(flags)) {
console.log(` ${flag.padEnd(pad + 2)}${desc}`);
}
if (entry.notes) console.log(`\n${entry.notes}`);
if (entry.examples?.length) {
console.log('\nExamples:');
for (const ex of entry.examples) console.log(` ${ex}`);
}
}
// For a bad value: the leaf help would bury the one line that says what is wrong.
function usageError(entry, message) {
console.error(message);
console.error(`Run \`pi-kanban help ${entry.name}\` for usage.`);
return 1;
}
function getArgValue(args, name) {
const idx = args.findIndex(a => a === `--${name}` || a.startsWith(`--${name}=`));
if (idx === -1) return null;
const arg = args[idx];
if (arg.includes('=')) return arg.split('=').slice(1).join('=');
return args[idx + 1] && !args[idx + 1].startsWith('--') ? args[idx + 1] : null;
}
// Each agent dir can run its own board on its own port, so 3460 can be another dir's board.
// The server's beacon in this agent dir names the right one; PORT still wins when set.
// A beacon left by a dead server means this dir's board is down: 3460 would be someone else's.
// Returns null in that case.
function beaconPort() {
const beacon = readCckJson('server.json');
if (!beacon) return 3460;
return beacon.port && beacon.pid && isPidAlive(beacon.pid) ? beacon.port : null;
}
let cachedPort;
function cliPort() {
if (process.env.PORT) return process.env.PORT;
if (cachedPort === undefined) cachedPort = beaconPort();
return cachedPort;
}
function cliBaseUrl() {
if (process.env.PK_URL) return process.env.PK_URL.replace(/\/+$/, '');
const port = cliPort();
return port === null ? null : `http://127.0.0.1:${port}`;
}
function cliTargetPort() {
if (!process.env.PK_URL) return cliPort();
try { return new URL(process.env.PK_URL).port; } catch (_) { return ''; }
}
function readCckJson(name) {
try { return JSON.parse(fs.readFileSync(path.join(boardDir(resolvePiAgentDir()), name), 'utf8')); } catch (_) { return null; }
}
// EPERM means the process exists but belongs to someone else.
function isPidAlive(pid) {
try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
}
function unreachable() {
const dir = displayPath(resolvePiAgentDir());
const start = 'Start it first with "pi-kanban".';
if (process.env.PK_URL) return `Cannot reach pi-kanban server for ${dir} at ${cliBaseUrl()} (PK_URL). ${start}`;
const port = cliPort();
if (port === null) return `Cannot reach pi-kanban server for ${dir}: its server.json names a server that is no longer running. ${start}`;
return `Cannot reach pi-kanban server for ${dir} on port ${port}. ${start}`;
}
class CliUnreachable extends Error { constructor() { super(unreachable()); this.code = 'unreachable'; } }
// Windows sometimes fails a loopback connect with ETIMEDOUT after ~300 ms when many
// connects run at once. Nothing reached the server, so even a POST is safe to send again.
const CONNECT_RETRY_MS = [250, 500, 1000, 2000];
const isConnectTimeout = (e) => e.cause?.code === 'ETIMEDOUT' && e.cause?.syscall === 'connect';
// A loopback connection can also be reset after it opens. A GET is safe to send again; a write may have landed.
const isRetryable = (e, init) => isConnectTimeout(e) || (!init?.method && e.cause?.code === 'ECONNRESET');
async function cliFetch(urlPath, init) {
const base = cliBaseUrl();
if (!base) throw new CliUnreachable();
for (let i = 0; ; i++) {
try {
return await fetch(`${base}${urlPath}`, init);
} catch (e) {
if (isRetryable(e, init) && i < CONNECT_RETRY_MS.length) {
await new Promise((r) => setTimeout(r, CONNECT_RETRY_MS[i]));
continue;
}
if (e.cause?.code === 'ECONNREFUSED' || /fetch failed/i.test(e.message)) throw new CliUnreachable();
throw e;
}
}
}
const cliPostJson = (urlPath, body, label, headers) => cliSendJson('POST', urlPath, body, label, headers);
// Every write verb sends JSON and reports failure the same way; `label` names the verb
// in the error line. Returns the parsed response body ({} when empty), or null after
// printing the failure, so callers just return 1.
async function cliSendJson(method, urlPath, body, label, headers = {}) {
const res = await cliFetch(urlPath, {
method,
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body)
});
const text = await res.text();
let parsed = {};
try { parsed = text ? JSON.parse(text) : {}; } catch (_) { /* not JSON */ }
if (res.ok) return parsed;
console.error(`${label} failed (${res.status}): ${parsed.error || text}`);
return null;
}
function reportCliError(e) {
console.error(e.code === 'unreachable' ? e.message : (e.message || String(e)));
}
async function runPreviewCli(args) {
const [filePathArg] = positionals(args, ['--session']);
if (!filePathArg) {
printLeafHelp(COMMANDS.doc.verbs.preview);
return 1;
}
const url = linkUrl(filePathArg);
if (url) return previewUrlCli(url, args);
// No $PI_KANBAN_SESSION_ID fallback: a session here switches the board's focus, and the
// agent must not move the board unless asked.
const sessionArg = getArgValue(args, 'session') || process.env.PREVIEW_SESSION || null;
const resolved = sessionArg && await resolveSessionByIdOrPrefix(sessionArg);
if (sessionArg && !resolved) return 1;
const sessionId = resolved?.id || null;
const abs = cliPath(filePathArg);
try {
if (!await cliPostJson('/api/preview', { path: abs, sessionId }, 'Preview')) return 1;
console.log(`Preview opened: ${abs}${sessionId ? ` (session ${sessionId.slice(0, 8)})` : ''}`);
return 0;
} catch (e) { reportCliError(e); return 1; }
}
// The modal cannot show a web page, so a URL is linked instead and the tab on screen
// offers to open it.
async function previewUrlCli(url, args) {
const resolved = await resolveSessionArg(COMMANDS.doc.verbs.preview, args, 'a URL is linked to the session.');
return resolved ? postDocLink(url, resolved.id, { open: true }) : 1;
}
async function postDocLink(target, sessionId, { unlink = false, open = false } = {}) {
try {
const out = await cliPostJson('/api/document/link', { path: target, sessionId, unlink, open }, 'Link');
if (!out) return 1;
const what = linkUrl(target) ? 'URL' : 'Document';
console.log(`${what} ${unlink ? 'unlinked from' : 'linked to'} session ${sessionId.slice(0, 8)}: ${out.path}`);
if (!unlink && out.tabs === 0) console.log('No browser tab is open; the board shows it when one opens.');
return 0;
} catch (e) { reportCliError(e); return 1; }
}
// Resolved to the full id because the browser keys linked docs by it, so a prefix won't match.
async function resolveSessionArg(entry, args, why) {
const sessionArg = getArgValue(args, 'session') || process.env.PREVIEW_SESSION || process.env[SESSION_ID_ENV];
if (!sessionArg) {
usageError(entry, `--session is required: ${why}`);
return null;
}
return resolveSessionByIdOrPrefix(sessionArg);
}
async function runDocLinkCli(args, entry) {
const [filePathArg] = positionals(args, ['--session']);
if (!filePathArg) {
printLeafHelp(entry);
return 1;
}
const resolved = await resolveSessionArg(entry, args, 'linked docs are stored per session.');
if (!resolved) return 1;
const unlink = entry === COMMANDS.doc.verbs.unlink;
return postDocLink(cliTarget(filePathArg), resolved.id, { unlink });
}
async function runDocListCli(args, entry) {
const resolved = await resolveSessionArg(entry, args, 'linked docs are stored per session.');
return resolved ? printLinkedDocs(resolved.id, args.includes('--json')) : 1;
}
// The server resolves a path against its own cwd, so a relative one is made absolute here.
const cliTarget = (arg) => linkUrl(arg) || cliPath(arg);
const PANES_WHY = 'panes are stored per session.';
const panesPath = (sessionId, paneId) =>
`/api/panes/${encodeURIComponent(sessionId)}${paneId ? `/${encodeURIComponent(paneId)}` : ''}`;
async function runPaneAddCli(args, entry) {
const [target] = positionals(args, ['--session', '--title', '--companion']);
const companion = getArgValue(args, 'companion');
if (!target === !companion) {
printLeafHelp(entry);
return 1;
}
const token = companion && readTerminalToken();
if (companion && !token) return 1;
const resolved = await resolveSessionArg(entry, args, PANES_WHY);
if (!resolved) return 1;
try {
const title = getArgValue(args, 'title') || '';
const out = companion
? await postCompanion(resolved.id, companion, title, token)
: await cliPostJson(panesPath(resolved.id), { target: cliTarget(target), title }, 'Pane add');
if (!out) return 1;
const { pane } = out;
let frameable;
if (pane.kind === 'url' && !pane.companion) {
try {
({ frameable } = await cliGetJson(`${panesPath(resolved.id, pane.id)}/framing`, 'Pane framing'));
} catch {}
}
if (args.includes('--json')) console.log(JSON.stringify({ ...pane, frameable }, null, 2));
else console.log(paneLine(out));
if (frameable === false && !args.includes('--json')) {
console.log(`note: ${new URL(pane.target).host} refuses framing, so the pane shows an "Open in new tab" card. Look for a URL of the same content that allows framing.`);
}
return 0;
} catch (e) { reportCliError(e); return 1; }
}
async function runPaneRmCli(args, entry) {
const [paneId] = positionals(args, ['--session']);
if (!paneId) {
printLeafHelp(entry);
return 1;
}
const resolved = await resolveSessionArg(entry, args, PANES_WHY);
if (!resolved) return 1;
try {
if (!await cliSendJson('DELETE', panesPath(resolved.id, paneId), undefined, 'Pane rm')) return 1;
console.log(`Removed pane ${paneId} from session ${resolved.id.slice(0, 8)}`);
return 0;
} catch (e) { reportCliError(e); return 1; }
}
async function runPaneListCli(args, entry) {
const resolved = await resolveSessionArg(entry, args, PANES_WHY);
if (!resolved) return 1;
try {
const layout = await cliGetJson(panesPath(resolved.id), 'Pane list');
if (args.includes('--json')) console.log(JSON.stringify(layout, null, 2));
else if (!layout.panes.length) console.log(`No panes for session ${resolved.id.slice(0, 8)}.`);
else printTable(['ID', 'KIND', 'TITLE', 'TARGET'], layout.panes.map((p) => [p.id, p.kind, p.title, p.target]));
return 0;
} catch (e) { reportCliError(e); return 1; }
}
const paneLine = (out) => `${out.pane.id} ${out.pane.title}${out.added ? '' : ' (already there)'}`;
// With a board terminal id, the board tab that shows that terminal switches to the pane.
const postCompanion = (sessionId, companion, title, token) =>
cliPostJson(panesPath(sessionId), { companion, title, terminal: boardTerminalId() || undefined }, 'Companion', { 'x-terminal-token': token });
async function runShowCli(args, entry) {
const [file] = positionals(args, ['--session', '--title', '--key', '--base']);
if (!file) {
printLeafHelp(entry);
return 1;
}
const terminal = boardTerminalId();
const token = terminal && readTerminalToken();
if (terminal && !token) return 1;
const resolved = await resolveSessionArg(entry, args, 'a card belongs to a session.');
if (!resolved) return 1;
const abs = cliPath(file);
const title = getArgValue(args, 'title') || path.basename(abs);
const base = getArgValue(args, 'base');
const body = { title, file: abs, key: getArgValue(args, 'key'), base: base && cliPath(base), terminal: terminal || undefined };
try {
const out = await cliPostJson(`/api/sessions/${encodeURIComponent(resolved.id)}/show`, body, 'Show', token ? { 'x-terminal-token': token } : {});
if (!out) return 1;
if (out.shown === 'overlay') {
console.log(`Shown "${out.title}" (${out.key ? `${out.key}, ` : ''}${out.index}/${out.count}). The user sees the rendered card and you do not: in your reply, say what the card shows, and take the render as given.`);
} else {
console.log(out.added
? `Added "${title}" as a background tab of session ${resolved.id.slice(0, 8)} on the board. In your reply, say what the card shows and that it waits there.`
: 'The board already has a tab for this file; it refreshes on each save.');
}
return 0;
} catch (e) { reportCliError(e); return 1; }
}
async function runSessionCompanionCli(args, entry) {
const idArg = sessionPositionals(args)[0] || process.env[SESSION_ID_ENV];
if (!idArg) return usageError(entry, '<id> is required outside a pi session.');
const token = readTerminalToken();
if (!token) return 1;
const resolved = await resolveSessionByIdOrPrefix(idArg);
if (!resolved) return 1;
try {
const out = await postCompanion(resolved.id, entry.companion, undefined, token);
if (!out) return 1;
console.log(paneLine(out));
return 0;
} catch (e) { reportCliError(e); return 1; }
}
async function printLinkedDocs(sessionId, asJson) {
try {
const links = await cliGetJson(`/api/document/links?session=${encodeURIComponent(sessionId)}`, 'Linked docs');
const paths = links[sessionId] || [];
if (asJson) console.log(JSON.stringify(paths, null, 2));
else if (!paths.length) console.log(`No linked docs for session ${sessionId.slice(0, 8)}.`);
else for (const p of paths) console.log(p);
return 0;
} catch (e) { reportCliError(e); return 1; }
}
function sessionTitle(s) {
return s.customTitle || s.name || '';
}
// The board's badge rule (docs/session-states.md). `active` is a wider rule, for which rows show.
function sessionStatus(s) {
if (!(s.hasRecentLog || s.inProgress > 0 || s.hasActiveAgents || s.hasWaitingForUser)) return 'idle';
if (s.hasWaitingForUser) return 'wait';
if (s.inProgress > 0) return 'busy';
return 'active';
}
function parseLimit(args, { fallback, allowAll = false }) {
const raw = getArgValue(args, 'limit');
if (raw === null) return { ok: true, limit: fallback };
if (allowAll && raw === 'all') return { ok: true, limit: null };
const n = parseInt(raw, 10);
if (Number.isNaN(n) || n <= 0) return { ok: false, error: `Invalid --limit value: ${raw}` };
return { ok: true, limit: n };
}
function sessionsListPath({ limit, noPins = false, include = [], project = null, activeOnly = false }) {
const q = limit === null ? 'all' : String(limit);
const pinsQ = noPins ? '&pins=off' : '';
const includeQ = include.length ? `&include=${include.map(encodeURIComponent).join(',')}` : '';
const projectQ = project ? `&project=${encodeURIComponent(project)}` : '';
const filterQ = activeOnly ? '&filter=active' : '';
return `/api/sessions?limit=${q}${pinsQ}${includeQ}${projectQ}${filterQ}`;
}
const fetchSessionsList = (opts, label = 'Session list') => cliGetJson(sessionsListPath(opts), label);
const uniqueById = (list) => [...new Map(list.map((s) => [s.id, s])).values()];
// The server refuses a request line above about 16 KB (431), about 430 ids, so the ids go in batches.
const IDS_PER_REQUEST = 100;
async function fetchSessionsByIds(ids, label) {
const batches = [];
for (let i = 0; i < ids.length; i += IDS_PER_REQUEST) batches.push(ids.slice(i, i + IDS_PER_REQUEST));
const lists = await Promise.all(batches.map((include) => fetchSessionsList({ limit: 1, include }, label)));
return uniqueById(lists.flat());
}
async function resolveSessionByIdOrPrefix(idArg) {
let res;
try {
res = await cliFetch(`/api/session/resolve?id=${encodeURIComponent(idArg)}`);
} catch (e) {
reportCliError(e);
return null;
}
if (res.status === 404) {
console.error(`No session matches: ${idArg}`);
return null;
}
if (res.status === 409) {
const { matches = [] } = await res.json().catch(() => ({}));
console.error(`Ambiguous prefix "${idArg}" matches ${matches.length} sessions:`);
for (const m of matches.slice(0, 10)) console.error(` ${m.id} ${m.customTitle || ''}`);
return null;
}
if (!res.ok) {
console.error(`Resolve failed (${res.status}): ${await res.text()}`);
return null;
}
return res.json();
}
async function runSessionListCli(args) {
const activeOnly = !args.includes('--all');
const noPins = args.includes('--no-pins');
const projectFilter = getArgValue(args, 'project');
const daysArg = getArgValue(args, 'days');
const days = daysArg !== null ? parseFloat(daysArg) : null;
if (daysArg !== null && (Number.isNaN(days) || days <= 0)) {
return usageError(COMMANDS.session.verbs.list, `Invalid --days value: ${daysArg}`);
}
// The Active view is short, so it has no cap. The server reads a whole transcript for some
// fields of each row it sends, so --all keeps one.
const parsed = parseLimit(args, { fallback: activeOnly ? null : 20, allowAll: true });
if (!parsed.ok) return usageError(COMMANDS.session.verbs.list, parsed.error);
const limit = parsed.limit;
const asJson = args.includes('--json');
let list;
let total;
try {
const res = await cliGet(sessionsListPath({ limit: days !== null ? null : limit, noPins, project: projectFilter, activeOnly }), 'Session list');
list = await res.json();
total = Number(res.headers.get('x-total-count')) || list.length;
} catch (e) {
reportCliError(e);
return 1;
}
if (days !== null) {
const cutoff = Date.now() - days * 86_400_000;
list = list.filter(s => s.pin || (s.modifiedAt && new Date(s.modifiedAt).getTime() >= cutoff));
total = list.length;
}
const pinRank = s => s.pin === 'sticky' ? 0 : s.pin === 'pinned' ? 1 : 2;
list.sort((a, b) => {
const r = pinRank(a) - pinRank(b);
if (r !== 0) return r;
return new Date(b.modifiedAt || 0) - new Date(a.modifiedAt || 0);
});
if (limit !== null && list.length > limit) {
const top = list.slice(0, limit);
const topIds = new Set(top.map(s => s.id));
const extraPinned = list.filter(s => s.pin && !topIds.has(s.id));
list = [...top, ...extraPinned];
}
const cut = list.length < total ? `${list.length} of ${total} shown; --limit all shows every row` : null;
if (asJson) {
console.log(JSON.stringify(list.map(({ pin, ...s }) => ({ ...s, pinState: pin || null })), null, 2));
if (cut) console.error(cut);
return 0;
}
if (!list.length) {
console.log('No sessions match.');
return 0;
}
const rows = list.map(s => ({
id: s.id.slice(0, 8),
pin: s.pin || '',
status: sessionStatus(s),
age: s.modifiedAt ? formatAge(Date.now() - new Date(s.modifiedAt).getTime()) : '-',
tasks: `${s.completed}/${s.taskCount}`,
project: path.basename(s.project || ''),
title: sessionTitle(s),
}));
const w = {
id: 8,
pin: Math.max(3, ...rows.map(r => r.pin.length)),
status: Math.max(6, ...rows.map(r => r.status.length)),
age: Math.max(3, ...rows.map(r => r.age.length)),
tasks: Math.max(5, ...rows.map(r => r.tasks.length)),
project: Math.max(7, ...rows.map(r => r.project.length)),
};
console.log(`${'ID'.padEnd(w.id)} ${'PIN'.padEnd(w.pin)} ${'STATUS'.padEnd(w.status)} ${'AGE'.padEnd(w.age)} ${'TASKS'.padEnd(w.tasks)} ${'PROJECT'.padEnd(w.project)} TITLE`);
for (const r of rows) {
console.log(`${r.id.padEnd(w.id)} ${r.pin.padEnd(w.pin)} ${r.status.padEnd(w.status)} ${r.age.padEnd(w.age)} ${r.tasks.padEnd(w.tasks)} ${r.project.padEnd(w.project)} ${r.title}`);
}
if (cut) console.log(cut);
return 0;