-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcli.ts
More file actions
3307 lines (3084 loc) · 152 KB
/
Copy pathcli.ts
File metadata and controls
3307 lines (3084 loc) · 152 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
#!/usr/bin/env node
import { Buffer } from "node:buffer";
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import net from "node:net";
import path from "node:path";
import YAML from "yaml";
import { type JsonRpcHandler, type JsonRpcId, type JsonRpcRequest } from "./jsonrpc";
import { isAdeMcpNamedPipePath } from "../../desktop/src/shared/adeMcpIpc";
type JsonObject = Record<string, unknown>;
type GlobalOptions = {
projectRoot: string | null;
workspaceRoot: string | null;
role: "cto" | "orchestrator" | "agent" | "external" | "evaluator";
headless: boolean;
requireSocket: boolean;
pretty: boolean;
text: boolean;
timeoutMs: number;
};
type ParsedCli = {
options: GlobalOptions;
command: string[];
};
type InvocationStep = {
key: string;
method: string;
params?: JsonObject;
unwrapToolResult?: boolean;
optional?: boolean;
};
type FormatterId =
| "status"
| "doctor"
| "auth"
| "lanes"
| "lane-detail"
| "git-status"
| "diff-summary"
| "file-read"
| "files-tree"
| "files-search"
| "prs-list"
| "pr-detail"
| "pr-checks"
| "pr-comments"
| "run-defs"
| "run-runtime"
| "chat-list"
| "tests-runs"
| "proof-list"
| "actions-list"
| "action-result";
type CliPlan =
| { kind: "help"; text: string }
| { kind: "execute"; label: string; steps: InvocationStep[]; visualizer?: "lanes"; summary?: "status" | "doctor" | "auth"; formatter?: FormatterId; preferHeadless?: boolean };
type CliConnection = {
mode: "desktop-socket" | "headless";
projectRoot: string;
workspaceRoot: string;
socketPath: string;
request: (method: string, params?: JsonObject) => Promise<unknown>;
close: () => Promise<void> | void;
};
class CliUsageError extends Error {}
class CliToolError extends Error {
details: unknown;
constructor(message: string, details: unknown) {
super(message);
this.details = details;
}
}
class CliExecutionError extends Error {
details: JsonObject;
constructor(message: string, details: JsonObject) {
super(message);
this.details = details;
}
}
type ReadinessCheck = {
ready: boolean;
status: "ready" | "warning" | "missing" | "unavailable";
message: string;
nextAction?: string;
details?: JsonObject;
};
const VERSION = "0.0.0";
const PROTOCOL_VERSION = "2025-06-18";
const SOURCE_FALLBACK_ENV = "ADE_CLI_SOURCE_FALLBACK_ACTIVE";
const CLI_ENTRY_PATH = typeof process.argv[1] === "string" ? path.resolve(process.argv[1]) : "";
const CLI_PACKAGE_ROOT = resolveCliPackageRoot(CLI_ENTRY_PATH);
const CLI_DIST_PATH = path.join(CLI_PACKAGE_ROOT, "dist", "cli.cjs");
function resolveCliPackageRoot(entryPath: string): string {
const seen = new Set<string>();
const starts = [
entryPath ? path.dirname(entryPath) : null,
process.cwd(),
];
for (const start of starts) {
if (!start) continue;
let cursor = path.resolve(start);
while (!seen.has(cursor)) {
seen.add(cursor);
const packageJson = path.join(cursor, "package.json");
const srcCli = path.join(cursor, "src", "cli.ts");
if (fs.existsSync(packageJson) && fs.existsSync(srcCli)) {
return cursor;
}
const parent = path.dirname(cursor);
if (parent === cursor) break;
cursor = parent;
}
}
return path.resolve(process.cwd(), "apps", "ade-cli");
}
function isSourceCliEntryPath(modulePath: string): boolean {
return /[/\\]src[/\\]cli\.ts$/i.test(modulePath);
}
function isSourceRuntimeInteropError(value: unknown): boolean {
const message = typeof value === "string"
? value
: value instanceof Error
? value.message
: "";
if (!message.length) return false;
const lower = message.toLowerCase();
return lower.includes("__filename is not defined in es module scope")
|| lower.includes("__filename is not defined")
|| lower.includes("__dirname is not defined");
}
function formatSpawnFailure(result: ReturnType<typeof spawnSync>, fallbackCommand: string): string {
if (result.error) {
return result.error.message;
}
const status = typeof result.status === "number" ? result.status : "unknown";
const stderr = typeof result.stderr === "string" ? result.stderr.trim() : "";
const stdout = typeof result.stdout === "string" ? result.stdout.trim() : "";
const detail = stderr || stdout || "No output captured.";
return `${fallbackCommand} exited with status ${status}: ${detail}`;
}
function latestMtimeMs(root: string): number {
let latest = 0;
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch {
return latest;
}
for (const entry of entries) {
const fullPath = path.join(root, entry.name);
if (entry.isDirectory()) {
latest = Math.max(latest, latestMtimeMs(fullPath));
continue;
}
if (!entry.isFile()) continue;
try {
latest = Math.max(latest, fs.statSync(fullPath).mtimeMs);
} catch {
// Ignore files that disappear while checking freshness.
}
}
return latest;
}
function isBuiltCliFresh(): boolean {
try {
const distMtime = fs.statSync(CLI_DIST_PATH).mtimeMs;
const sourceMtime = latestMtimeMs(path.join(CLI_PACKAGE_ROOT, "src"));
return distMtime >= sourceMtime;
} catch {
return false;
}
}
function maybeRunBuiltCliFallback(error: unknown, argv: string[]): { stdout: string; stderr: string; exitCode: number } | null {
if (!(error instanceof CliExecutionError)) return null;
if (process.env[SOURCE_FALLBACK_ENV] === "1") return null;
if (!isSourceCliEntryPath(CLI_ENTRY_PATH)) return null;
if (!isSourceRuntimeInteropError(asString(error.details.cause) ?? error.message)) return null;
if (!isBuiltCliFresh()) {
const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
const buildResult = spawnSync(npmCommand, ["run", "build", "--silent"], {
cwd: CLI_PACKAGE_ROOT,
env: process.env,
encoding: "utf8",
});
if (buildResult.error || buildResult.status !== 0 || !isBuiltCliFresh()) {
error.details.nextAction = "Run `npm --prefix apps/ade-cli run build` and retry the command.";
error.details.fallback = formatSpawnFailure(buildResult, "npm run build --silent");
return null;
}
}
const rerun = spawnSync(process.execPath, [CLI_DIST_PATH, ...argv], {
cwd: process.cwd(),
env: {
...process.env,
[SOURCE_FALLBACK_ENV]: "1",
},
encoding: "utf8",
});
if (rerun.error) {
error.details.nextAction = "Run `node apps/ade-cli/dist/cli.cjs ...` directly to inspect the runtime failure.";
error.details.fallback = rerun.error.message;
return null;
}
return {
stdout: typeof rerun.stdout === "string" ? rerun.stdout : "",
stderr: typeof rerun.stderr === "string" ? rerun.stderr : "",
exitCode: rerun.status ?? 1,
};
}
const ADE_BANNER = String.raw`
_ ____ _____
/ \ | _ \| ____|
/ _ \ | | | | _|
/ ___ \| |_| | |___
/_/ \_\____/|_____|
`;
const TOP_LEVEL_HELP = `${ADE_BANNER}
Agent-focused command-line interface for ADE.
ADE CLI commands operate on the same project database and live desktop socket
used by the ADE app. By default the CLI connects to the app socket when it is
running; otherwise it falls back to a headless runtime for local-safe actions.
$ ade help <command...> Display help for a command
$ ade auth status Check local ADE CLI readiness
$ ade doctor Inspect project, socket, runtime, and tool availability
$ ade lanes list | show | create | child Work with lanes and lane stacks
$ ade git status | commit | push | stash Run ADE-aware git operations
$ ade diff changes | file Inspect lane diffs
$ ade files tree | read | write | search Read and edit lane workspaces
$ ade prs list | create | path-to-merge Manage PRs, queues, and Path to Merge repair rounds
$ ade run defs | ps | start | logs Manage Run tab process definitions and runtime
$ ade shell start | write | resize | close Launch and control tracked shell sessions
$ ade chat list | create | send | interrupt Work with ADE agent chats
$ ade agent spawn --lane <id> --prompt <text> Launch an agent session in ADE
$ ade cto state | chats Operate CTO state and Work chats
$ ade linear workflows | run | sync Operate Linear routing and sync workflows
$ ade automations list | create | run | runs Manage automation rules
$ ade coordinator <tool> Call coordinator runtime tools
$ ade tests list | run | stop | runs | logs Run configured test suites
$ ade proof status | list | screenshot | record Manage proof and computer-use artifacts
$ ade memory add | search | pin Use ADE memory
$ ade settings action <method> Call project config actions
$ ade actions list | run | status Escape hatch for every ADE service action
Global options:
--project-root <path> ADE project root. Inside .ade/worktrees/<lane>, this resolves to the parent project.
--workspace-root <path> Lane/worktree to treat as the active workspace.
--headless Skip the desktop socket and run an in-process ADE runtime.
--socket Require the desktop socket; fail instead of falling back to headless.
--json Print machine-readable JSON. This is the default output mode.
--text Print a compact human-readable summary when a formatter exists.
--timeout-ms <ms> Per-request timeout. Long agent/PR workflows may need several minutes.
Common agent flows:
$ ade doctor --text
$ ade lanes list --text
$ ade lanes create --name fix-login --description "Repair login redirect"
$ ade git status --lane <lane> --text
$ ade git stage --lane <lane> src/index.ts
$ ade git commit --lane <lane> -m "Fix login redirect"
$ ade prs create --lane <lane> --base main --draft
$ ade prs path-to-merge <pr-id-or-number-or-url> --model <model> --max-rounds 3 --no-auto-merge
$ ade proof record --seconds 20
Generic ADE action JSON contract:
Object-shaped call:
$ ade actions run git.push --input-json '{"laneId":"lane-1","setUpstream":true}'
$ ade actions run git.push --arg laneId=lane-1 --arg setUpstream=true
JSON value fields:
$ ade actions run pr.setLabels --arg prId=123 --arg-json 'labels=["ready","ship"]'
Multi-parameter service call:
$ ade actions run issue_inventory.savePipelineSettings --args-list-json '["pr-1",{"maxRounds":3}]'
Single scalar parameter:
$ ade actions run mission.get --scalar mission-1
$ ade actions list --text
$ ade actions list --domain pr --text
$ ade actions run <domain.action> --input-json '{"key":"value"}'
Start with: ade doctor --text
`;
const HELP_BY_COMMAND: Record<string, string> = {
lanes: `${ADE_BANNER}
Lanes
Lanes are ADE-managed worktrees and branches. Most commands accept either
--lane <lane-id> or a positional lane id.
$ ade lanes list --text Show lane stack graph and branch names
$ ade lanes show <lane> --text Inspect one lane status
$ ade lanes create --name <name> Create a lane from the current project context
$ ade lanes child --lane <parent> --name <name> Create a child lane under a parent
$ ade lanes import --branch <branch> Register an existing branch/worktree
$ ade lanes archive <lane> Archive a lane in ADE
$ ade lanes unarchive <lane> Restore an archived lane
$ ade lanes attach --path <worktree> --name <n> Attach an external worktree
$ ade lanes actions --text List callable lane service methods
`,
git: `${ADE_BANNER}
Git
Git commands run in the lane worktree and record ADE operations so the app can
refresh lane state. Use --lane for anything other than the active workspace.
$ ade git status --lane <lane> --text Show ADE-aware sync status
$ ade git stage --lane <lane> src/file.ts Stage one file
$ ade git stage-all --lane <lane> Stage all current changes
$ ade git unstage --lane <lane> src/file.ts Unstage one file
$ ade git commit --lane <lane> [-m <message>] Commit, generating a message when omitted
$ ade git push --lane <lane> --set-upstream Push through ADE
$ ade git stash push|list|apply|pop Use ADE lane stash actions
$ ade git rebase --lane <lane> --ai Rebase with ADE conflict support
$ ade diff changes --lane <lane> --text Inspect changed files
`,
diff: `${ADE_BANNER}
Diffs
$ ade diff changes --lane <lane> --text Summarize staged/unstaged file changes
$ ade diff file --lane <lane> <path> --text Show one file diff
$ ade diff file --mode staged <path> Inspect staged diff for one file
$ ade diff actions --text List diff service actions
`,
prs: `${ADE_BANNER}
Pull requests
PR identifiers may be ADE PR ids, GitHub PR numbers, #numbers, or full PR URLs.
Creating or linking a PR persists the lane mapping in ADE so the PR tab tracks it.
$ ade prs list --text List PRs known to ADE
$ ade prs create --lane <lane> --base main Open and map a GitHub PR from a lane
$ ade prs link --lane <lane> --url <pr-url> Map an existing GitHub PR to a lane
$ ade prs checks <pr> --text Show check status
$ ade prs comments <pr> --text Show unresolved review work
$ ade prs inventory <pr> Refresh ADE issue inventory
$ ade prs path-to-merge <pr> --model <model> --max-rounds 3 --no-auto-merge
$ ade prs resolve-thread <pr> --thread <id> Resolve a review thread
$ ade prs labels set <pr> ready-to-merge Replace labels
$ ade prs reviewers request <pr> alice bob Request reviewers
`,
run: `${ADE_BANNER}
Run tab
Run tab commands mirror ADE desktop process definitions and runtime state.
They require the desktop socket when live process state is needed.
$ ade run defs --text List configured run commands
$ ade run ps --lane <lane> --text List process runtime state
$ ade run start <process> --lane <lane> Start a process in a lane
$ ade run stop <process> --lane <lane> Stop a process in a lane
$ ade run logs <process> --run <run> --text Tail process logs
$ ade run stack start --stack <id> --lane <lane> Start a process stack
$ ade run start-all --lane <lane> Start all configured processes
`,
shell: `${ADE_BANNER}
Shell sessions
Shell commands create tracked PTY sessions that ADE can display and audit.
$ ade shell start --lane <lane> -- npm test Start a tracked shell session
$ ade shell start --lane <lane> -c "npm test" Start with a command string
$ ade shell write <pty-id> --data "q" Write data to a PTY
$ ade shell resize <pty-id> --cols 120 --rows 36
$ ade shell close <pty-id> Dispose a PTY
`,
files: `${ADE_BANNER}
Files
File commands operate inside an ADE workspace id, usually a lane id.
$ ade files workspaces --text List workspace roots
$ ade files tree --workspace <lane> --path src Show a workspace tree
$ ade files read --workspace <lane> <path> --text Read a file
$ ade files write --workspace <lane> <path> --stdin
$ ade files write --workspace <lane> <path> --text "new content"
$ ade files create --workspace <lane> <path> --text "content"
$ ade files mkdir --workspace <lane> src/new
$ ade files search --workspace <lane> -q <text> Search text in a workspace
$ ade files quick-open --workspace <lane> -q app
`,
chat: `${ADE_BANNER}
Work chats
Chat commands use ADE agent chat sessions. Live provider-backed chat normally
requires the desktop socket because the app owns provider/session state.
$ ade chat list --text List chat sessions
$ ade chat create --lane <lane> --provider codex --model <model>
$ ade chat send <session> --text "next step" Send a message
$ ade chat interrupt <session> Stop an active turn
$ ade chat resume <session> Resume a session
$ ade agent spawn --lane <lane> --prompt "fix" Start a new agent work session
`,
agent: `${ADE_BANNER}
Agent sessions
$ ade agent spawn --lane <lane> --prompt "Fix the failing test"
$ ade agent spawn --lane <lane> --provider codex --model <model> --permissions workspace-write
$ ade agent spawn --lane <lane> --context-file docs/context.md --prompt "continue"
$ ade agent spawn --lane <lane> --tool=git --tool=files --prompt "review changes"
`,
proof: `${ADE_BANNER}
Proof and computer use
Proof commands capture or ingest reviewer-visible evidence for ADE work.
Prefer screenshots/images, screen recordings, and browser captures/traces.
Console logs are supporting diagnostics, not a replacement for visual proof.
Local screenshot/video fallback is macOS-only and runs headless by default
unless --socket is explicitly requested. Desktop socket mode has the best
parity for UI-owned proof state.
$ ade proof status --text Show proof backend capabilities
$ ade proof list --text List captured artifacts
$ ade proof capture --caption "Done" Capture a screenshot artifact
$ ade proof attach /tmp/proof.png --caption "Done" Attach an existing image/video
$ ade proof record --seconds 20 Capture a short video proof
$ ade proof launch --app "ADE" Launch an app for proof capture
$ ade proof ingest --input-json '{"artifacts":[]}' Ingest external visual proof artifacts
`,
tests: `${ADE_BANNER}
Tests
$ ade tests list --text List configured test suites
$ ade tests run --lane <lane> --suite unit Run a configured suite
$ ade tests run --lane <lane> --command "npm test" --wait
$ ade tests runs --lane <lane> --text List recent test runs
$ ade tests logs <run-id> --text Tail a test run log
$ ade tests stop <run-id> Stop an active test run
`,
memory: `${ADE_BANNER}
Memory
$ ade memory add --category fact --content "User prefers concise summaries"
$ ade memory search -q "release process" --text
$ ade memory pin <memory-id>
$ ade memory core --arg projectSummary="Current focus"
`,
cto: `${ADE_BANNER}
CTO and Work state
$ ade cto state --text Read CTO identity, core memory, and recent sessions
$ ade cto chats list --text List CTO work chats
$ ade cto chats spawn --lane <lane> --prompt "plan this"
$ ade cto chats send <session> --text "continue"
$ ade actions run cto_state.updateCoreMemory --input-json '{"projectSummary":"..."}'
$ ade actions run worker_agent.listAgents --input-json '{"includeDeleted":false}'
`,
linear: `${ADE_BANNER}
Linear workflows
$ ade linear workflows --text List configured workflows
$ ade linear sync dashboard --text Show sync dashboard
$ ade linear sync run Trigger a sync run
$ ade linear sync queue --text List sync queue items
$ ade linear sync resolve --queue-item <id> --action approve
$ ade linear route worker --input-json '{"issueId":"LIN-123","workerId":"worker-1"}'
`,
flow: `${ADE_BANNER}
Flow policy
$ ade flow policy get --text Read current workflow policy
$ ade flow policy validate --input-json '{...}' Validate policy JSON
$ ade flow policy save --input-json '{...}' Save policy JSON
$ ade flow policy revisions --text List saved revisions
$ ade flow policy rollback <revision-id> Restore a prior revision
`,
coordinator: `${ADE_BANNER}
Coordinator runtime tools
Coordinator tools expose orchestration operations used by mission agents.
List tool names with:
$ ade actions call list_ade_actions --input-json '{"domain":"orchestrator_core"}'
$ ade coordinator <tool-name> --input-json '{"key":"value"}'
`,
actions: `${ADE_BANNER}
ADE actions
Escape hatch for any exposed ADE service method. Use typed commands first
when they exist; use actions when an agent needs exact service coverage.
Argument shapes:
Object args become one object parameter:
$ ade actions run git.push --input-json '{"laneId":"lane-1","setUpstream":true}'
$ ade actions run git.push --arg laneId=lane-1 --arg setUpstream=true
--arg parses true/false/null/numbers; --arg-json parses a JSON value:
$ ade actions run pr.setLabels --arg prId=123 --arg-json 'labels=["ready","ship"]'
argsList is for service methods with multiple positional parameters:
$ ade actions run issue_inventory.savePipelineSettings --args-list-json '["pr-1",{"maxRounds":3}]'
scalar is for one non-object parameter:
$ ade actions run mission.get --scalar mission-1
$ ade actions list --text Domain-grouped action catalog
$ ade actions list --domain git --text Narrow the catalog
$ ade actions run <domain.action> --input-json '{"key":"value"}'
$ ade actions run <domain> <action> --input-json '{"key":"value"}'
$ ade actions status --text Runtime action availability
`,
automations: `${ADE_BANNER}
Automations
$ ade automations list [--json] List automation rules
$ ade automations show <id> [--json] Inspect a rule
$ ade automations create --from-file <path> Create from YAML (also accepts --stdin)
$ ade automations update <id> --from-file <path>
$ ade automations delete <id> Remove a local rule
$ ade automations toggle <id> --enabled true|false
$ ade automations run <id> [--dry-run] Trigger a rule manually
$ ade automations runs [--rule <id>] [--limit 50] [--json]
$ ade automations run-show <runId> [--json] Inspect a run
`,
};
function isRecord(value: unknown): value is JsonObject {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function asString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function parseBooleanEnv(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase();
return normalized === "1" || normalized === "true" || normalized === "yes";
}
function parsePrimitive(value: string): unknown {
const trimmed = value.trim();
if (trimmed === "true") return true;
if (trimmed === "false") return false;
if (trimmed === "null") return null;
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
const parsed = Number(trimmed);
if (Number.isFinite(parsed)) return parsed;
}
return value;
}
function parseJson(value: string, label: string): unknown {
try {
return JSON.parse(value);
} catch (error) {
throw new CliUsageError(`${label} must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
}
function parseObjectJson(value: string, label: string): JsonObject {
const parsed = parseJson(value, label);
if (!isRecord(parsed)) {
throw new CliUsageError(`${label} must be a JSON object.`);
}
return parsed;
}
function parseAssignment(value: string, label: string): { key: string; value: string } {
const index = value.indexOf("=");
if (index <= 0) {
throw new CliUsageError(`${label} must use key=value syntax.`);
}
const key = value.slice(0, index).trim();
if (!key.length) {
throw new CliUsageError(`${label} is missing a key.`);
}
return { key, value: value.slice(index + 1) };
}
const UNSAFE_ARG_PATH_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
function setPath(target: JsonObject, key: string, value: unknown): void {
const parts = key.split(".").map((part) => part.trim()).filter(Boolean);
if (parts.length === 0) {
throw new CliUsageError("Argument key cannot be empty.");
}
const unsafePart = parts.find((part) => UNSAFE_ARG_PATH_SEGMENTS.has(part));
if (unsafePart) {
throw new CliUsageError(`Argument key segment "${unsafePart}" is not allowed.`);
}
let cursor: JsonObject = target;
for (const part of parts.slice(0, -1)) {
const existing = cursor[part];
if (!isRecord(existing)) {
const next: JsonObject = {};
cursor[part] = next;
cursor = next;
continue;
}
cursor = existing;
}
cursor[parts[parts.length - 1]!] = value;
}
function readValue(args: string[], names: string[]): string | null {
for (let index = 0; index < args.length; index += 1) {
const token = args[index];
if (!token) continue;
const matchedName = names.find((name) => token === name || token.startsWith(`${name}=`));
if (!matchedName) continue;
if (token.includes("=")) {
args.splice(index, 1);
return token.slice(token.indexOf("=") + 1);
}
const value = args[index + 1];
if (value == null) {
throw new CliUsageError(`${token} requires a value.`);
}
args.splice(index, 2);
return value;
}
return null;
}
function readFlag(args: string[], names: string[]): boolean {
for (let index = 0; index < args.length; index += 1) {
if (!names.includes(args[index]!)) continue;
args.splice(index, 1);
return true;
}
return false;
}
function firstPositional(args: string[]): string | null {
const index = args.findIndex((arg) => arg !== "--" && !arg.startsWith("-"));
if (index < 0) return null;
const [value] = args.splice(index, 1);
return value ?? null;
}
function collectGenericObjectArgs(args: string[], base: JsonObject = {}): JsonObject {
const input: JsonObject = { ...base };
while (true) {
const inputJson = readValue(args, ["--input-json", "--json-input", "--input"]);
if (inputJson != null) {
Object.assign(input, parseObjectJson(inputJson, "--input-json"));
continue;
}
const rawArg = readValue(args, ["--arg", "--set"]);
if (rawArg != null) {
const { key, value } = parseAssignment(rawArg, "--arg");
setPath(input, key, parsePrimitive(value));
continue;
}
const jsonArg = readValue(args, ["--arg-json", "--set-json"]);
if (jsonArg != null) {
const { key, value } = parseAssignment(jsonArg, "--arg-json");
setPath(input, key, parseJson(value, `--arg-json ${key}`));
continue;
}
break;
}
return input;
}
function readLaneId(args: string[]): string | null {
return readValue(args, ["--lane", "--lane-id"]) ?? null;
}
function readPrId(args: string[]): string | null {
return readValue(args, ["--pr", "--pr-id"]) ?? null;
}
function readIntOption(args: string[], names: string[], fallback?: number): number | undefined {
const value = readValue(args, names);
if (value == null) return fallback;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) {
throw new CliUsageError(`${names[0]} must be an integer.`);
}
return parsed;
}
function readNumberOption(args: string[], names: string[], fallback?: number): number | undefined {
const value = readValue(args, names);
if (value == null) return fallback;
const parsed = Number(value);
if (!Number.isFinite(parsed)) {
throw new CliUsageError(`${names[0]} must be a number.`);
}
return parsed;
}
function requireValue(value: string | null, label: string): string {
if (value && value.trim().length > 0) return value.trim();
throw new CliUsageError(`${label} is required.`);
}
function isCommandTextValue(argv: string[], index: number, command: string[]): boolean {
if (command.length === 0) return false;
const token = argv[index];
if (token?.startsWith("--text=")) return true;
if (token !== "--text") return false;
const next = argv[index + 1];
return Boolean(next && next !== "--" && !next.startsWith("-"));
}
function maybePut(target: JsonObject, key: string, value: unknown): void {
if (value !== undefined && value !== null && value !== "") {
target[key] = value;
}
}
function parseCliArgs(argv: string[]): ParsedCli {
const command: string[] = [];
const options: GlobalOptions = {
projectRoot: null,
workspaceRoot: null,
role: (asString(process.env.ADE_DEFAULT_ROLE) as GlobalOptions["role"] | null) ?? "agent",
headless: parseBooleanEnv(process.env.ADE_CLI_HEADLESS),
requireSocket: false,
pretty: true,
text: false,
timeoutMs: 10 * 60 * 1000,
};
for (let index = 0; index < argv.length; index += 1) {
const token = argv[index]!;
const inGlobalPrefix = command.length === 0;
if (token === "--") {
command.push(token, ...argv.slice(index + 1));
break;
}
if (inGlobalPrefix && token === "--project-root") {
options.projectRoot = path.resolve(requireValue(argv[index + 1] ?? null, "--project-root"));
index += 1;
continue;
}
if (inGlobalPrefix && token.startsWith("--project-root=")) {
options.projectRoot = path.resolve(requireValue(token.slice("--project-root=".length), "--project-root"));
continue;
}
if (inGlobalPrefix && token === "--workspace-root") {
options.workspaceRoot = path.resolve(requireValue(argv[index + 1] ?? null, "--workspace-root"));
index += 1;
continue;
}
if (inGlobalPrefix && token.startsWith("--workspace-root=")) {
options.workspaceRoot = path.resolve(requireValue(token.slice("--workspace-root=".length), "--workspace-root"));
continue;
}
if (inGlobalPrefix && token === "--role") {
options.role = parseRole(requireValue(argv[index + 1] ?? null, "--role"));
index += 1;
continue;
}
if (inGlobalPrefix && token.startsWith("--role=")) {
options.role = parseRole(requireValue(token.slice("--role=".length), "--role"));
continue;
}
if (inGlobalPrefix && (token === "--headless" || token === "--no-socket")) {
options.headless = true;
continue;
}
if (inGlobalPrefix && token === "--socket") {
options.requireSocket = true;
options.headless = false;
continue;
}
if (token === "--compact") {
options.pretty = false;
continue;
}
if (token === "--pretty") {
options.pretty = true;
continue;
}
if (isCommandTextValue(argv, index, command)) {
command.push(token);
continue;
}
if (token === "--text") {
options.text = true;
continue;
}
if (token === "--json") {
options.text = false;
continue;
}
if (inGlobalPrefix && token === "--timeout-ms") {
const parsed = Number.parseInt(requireValue(argv[index + 1] ?? null, "--timeout-ms"), 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new CliUsageError("--timeout-ms must be a positive integer.");
}
options.timeoutMs = parsed;
index += 1;
continue;
}
if (inGlobalPrefix && token.startsWith("--timeout-ms=")) {
const parsed = Number.parseInt(requireValue(token.slice("--timeout-ms=".length), "--timeout-ms"), 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new CliUsageError("--timeout-ms must be a positive integer.");
}
options.timeoutMs = parsed;
continue;
}
command.push(token);
}
return { options, command };
}
function parseRole(value: string): GlobalOptions["role"] {
if (value === "cto" || value === "orchestrator" || value === "agent" || value === "external" || value === "evaluator") {
return value;
}
throw new CliUsageError("--role must be one of cto, orchestrator, agent, external, or evaluator.");
}
function shellEscapeToken(value: string): string {
if (!value.length) return "''";
if (/^[a-zA-Z0-9_./:=@%+-]+$/.test(value)) return value;
return `'${value.replace(/'/g, `'"'"'`)}'`;
}
function actionCallStep(key: string, name: string, args: JsonObject = {}): InvocationStep {
return {
key,
method: "ade/actions/call",
params: { name, arguments: args },
unwrapToolResult: true,
};
}
function actionStep(key: string, domain: string, action: string, args: JsonObject = {}): InvocationStep {
return actionCallStep(key, "run_ade_action", { domain, action, args });
}
function actionArgsListStep(key: string, domain: string, action: string, argsList: unknown[]): InvocationStep {
return actionCallStep(key, "run_ade_action", { domain, action, argsList });
}
function listActionsStep(key: string, domain?: string): InvocationStep {
return actionCallStep(key, "list_ade_actions", domain ? { domain } : {});
}
function buildActionRunStep(args: string[]): InvocationStep {
const target = firstPositional(args);
if (!target) throw new CliUsageError("actions run requires <domain.action> or <domain> <action>.");
let domain: string;
let action: string;
if (target.includes(".")) {
const parts = target.split(".");
domain = requireValue(parts.shift() ?? null, "domain");
action = requireValue(parts.join("."), "action");
} else {
domain = target;
action = requireValue(firstPositional(args), "action");
}
const argsListJson = readValue(args, ["--args-list-json", "--params-json"]);
if (argsListJson != null) {
const argsList = parseJson(argsListJson, "--args-list-json");
if (!Array.isArray(argsList)) throw new CliUsageError("--args-list-json must be a JSON array.");
return actionCallStep("result", "run_ade_action", { domain, action, argsList });
}
const scalarJson = readValue(args, ["--scalar-json", "--arg-value-json"]);
if (scalarJson != null) {
return actionCallStep("result", "run_ade_action", { domain, action, arg: parseJson(scalarJson, "--scalar-json") });
}
const scalar = readValue(args, ["--scalar", "--arg-value"]);
if (scalar != null) {
return actionCallStep("result", "run_ade_action", { domain, action, arg: parsePrimitive(scalar) });
}
return actionStep("result", domain, action, collectGenericObjectArgs(args));
}
function buildLanePlan(args: string[]): CliPlan {
const sub = firstPositional(args) ?? "list";
if (sub === "actions") {
return { kind: "execute", label: "lane actions", steps: [listActionsStep("actions", "lane")] };
}
if (sub === "action") {
return { kind: "execute", label: "lane action", steps: [buildActionRunStep(["lane", ...args])] };
}
if (sub === "list" || sub === "ls") {
const input = collectGenericObjectArgs(args, {
includeArchived: readFlag(args, ["--archived", "--include-archived"]),
});
const visual = readFlag(args, ["--visual", "--graph"]);
const noVisual = readFlag(args, ["--no-visual"]);
return {
kind: "execute",
label: "lanes list",
steps: [actionCallStep("result", "list_lanes", input)],
visualizer: visual || !noVisual ? "lanes" : undefined,
};
}
if (sub === "show" || sub === "status") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane status", steps: [actionCallStep("result", "get_lane_status", { laneId })] };
}
if (sub === "merge") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane merge", steps: [actionCallStep("result", "merge_lane", collectGenericObjectArgs(args, { laneId, message: readValue(args, ["--message", "-m"]), deleteSourceLane: readFlag(args, ["--delete-source-lane", "--delete-source"]) }))] };
}
if (sub === "conflicts") {
const mode = firstPositional(args) ?? "check";
if (mode !== "check") return { kind: "execute", label: `lane conflicts ${mode}`, steps: [actionStep("result", "conflicts", mode, collectGenericObjectArgs(args, { laneId: readLaneId(args) }))] };
const ids = args.filter((entry) => !entry.startsWith("-"));
return { kind: "execute", label: "lane conflicts check", steps: [actionCallStep("result", "check_conflicts", collectGenericObjectArgs(args, { laneId: readLaneId(args), ...(ids.length ? { laneIds: ids } : {}), force: readFlag(args, ["--force"]) }))] };
}
if (sub === "create" || sub === "child") {
const name = readValue(args, ["--name"]) ?? firstPositional(args);
const input: JsonObject = {};
input.name = requireValue(name, "name");
maybePut(input, "description", readValue(args, ["--description", "--desc"]));
maybePut(input, "parentLaneId", readValue(args, ["--parent", "--parent-lane", "--parent-lane-id"]) ?? (sub === "child" ? readLaneId(args) : null));
if (sub === "child" && !input.parentLaneId) throw new CliUsageError("parent lane is required. Use --lane <parent> or --parent <parent>.");
return { kind: "execute", label: "lane create", steps: [actionCallStep("result", "create_lane", collectGenericObjectArgs(args, input))] };
}
if (sub === "children") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane children", steps: [actionArgsListStep("result", "lane", "getChildren", [laneId])] };
}
if (sub === "stack") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane stack", steps: [actionArgsListStep("result", "lane", "getStackChain", [laneId])] };
}
if (sub === "refresh") {
return { kind: "execute", label: "lane refresh", steps: [actionStep("result", "lane", "refreshSnapshots", collectGenericObjectArgs(args, { includeArchived: readFlag(args, ["--archived", "--include-archived"]) }))] };
}
if (sub === "rename") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane rename", steps: [actionStep("result", "lane", "rename", collectGenericObjectArgs(args, { laneId, name: readValue(args, ["--name"]) ?? firstPositional(args) }))] };
}
if (sub === "reparent") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane reparent", steps: [actionStep("result", "lane", "reparent", collectGenericObjectArgs(args, { laneId, newParentLaneId: readValue(args, ["--parent", "--parent-lane", "--parent-lane-id"]) ?? firstPositional(args) }))] };
}
if (sub === "appearance") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane appearance", steps: [actionStep("result", "lane", "updateAppearance", collectGenericObjectArgs(args, { laneId, color: readValue(args, ["--color"]), icon: readValue(args, ["--icon"]) }))] };
}
if (sub === "archive" || sub === "unarchive") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: `lane ${sub}`, steps: [actionStep("result", "lane", sub, collectGenericObjectArgs(args, { laneId }))] };
}
if (sub === "delete" || sub === "rm") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane delete", steps: [actionStep("result", "lane", "delete", collectGenericObjectArgs(args, { laneId, force: readFlag(args, ["--force"]), deleteBranch: readFlag(args, ["--delete-branch"]), deleteRemoteBranch: readFlag(args, ["--delete-remote-branch"]) }))] };
}
if (sub === "attach") {
return { kind: "execute", label: "lane attach", steps: [actionStep("result", "lane", "attach", collectGenericObjectArgs(args, { worktreePath: readValue(args, ["--path"]) ?? firstPositional(args), name: readValue(args, ["--name"]) }))] };
}
if (sub === "adopt-attached") {
const laneId = requireValue(readLaneId(args) ?? firstPositional(args), "laneId");
return { kind: "execute", label: "lane adopt attached", steps: [actionStep("result", "lane", "adoptAttached", collectGenericObjectArgs(args, { laneId }))] };
}
if (sub === "split-unstaged") {
return { kind: "execute", label: "lane split unstaged", steps: [actionStep("result", "lane", "createFromUnstaged", collectGenericObjectArgs(args, { sourceLaneId: readValue(args, ["--source", "--source-lane"]) ?? readLaneId(args), name: readValue(args, ["--name"]) ?? firstPositional(args) }))] };
}
if (sub === "import" || sub === "import-branch") {
const input: JsonObject = {};
input.branchRef = requireValue(readValue(args, ["--branch", "--branch-ref"]) ?? firstPositional(args), "branchRef");
maybePut(input, "name", readValue(args, ["--name"]));
maybePut(input, "description", readValue(args, ["--description", "--desc"]));
maybePut(input, "baseBranch", readValue(args, ["--base", "--base-branch"]));
return { kind: "execute", label: "lane import", steps: [actionCallStep("result", "import_lane", collectGenericObjectArgs(args, input))] };
}
if (sub === "unregistered" || sub === "list-unregistered") {
return { kind: "execute", label: "unregistered lanes", steps: [actionCallStep("result", "list_unregistered_lanes", collectGenericObjectArgs(args))] };
}
return { kind: "execute", label: `lane ${sub}`, steps: [actionStep("result", "lane", sub, collectGenericObjectArgs(args))] };
}
function buildGitPlan(args: string[]): CliPlan {
const sub = firstPositional(args) ?? "status";
if (sub === "actions") {