apex-code 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/dist/cli/agent-lifecycle.d.ts +24 -0
  3. package/dist/cli/agent-lifecycle.d.ts.map +1 -0
  4. package/dist/cli/agent-lifecycle.js +126 -0
  5. package/dist/cli/agent-lifecycle.js.map +1 -0
  6. package/dist/cli/args.d.ts +13 -0
  7. package/dist/cli/args.d.ts.map +1 -1
  8. package/dist/cli/args.js +80 -0
  9. package/dist/cli/args.js.map +1 -1
  10. package/dist/core/agent-session.d.ts +160 -0
  11. package/dist/core/agent-session.d.ts.map +1 -1
  12. package/dist/core/agent-session.js +265 -0
  13. package/dist/core/agent-session.js.map +1 -1
  14. package/dist/core/delegation/runtime.d.ts +682 -1
  15. package/dist/core/delegation/runtime.d.ts.map +1 -1
  16. package/dist/core/delegation/runtime.js +1339 -66
  17. package/dist/core/delegation/runtime.js.map +1 -1
  18. package/dist/core/sdk.d.ts +61 -3
  19. package/dist/core/sdk.d.ts.map +1 -1
  20. package/dist/core/sdk.js +316 -22
  21. package/dist/core/sdk.js.map +1 -1
  22. package/dist/core/tools/delegate.d.ts +8 -0
  23. package/dist/core/tools/delegate.d.ts.map +1 -1
  24. package/dist/core/tools/delegate.js +33 -3
  25. package/dist/core/tools/delegate.js.map +1 -1
  26. package/dist/core/workspace/git-observer.d.ts +16 -0
  27. package/dist/core/workspace/git-observer.d.ts.map +1 -1
  28. package/dist/core/workspace/git-observer.js +8 -1
  29. package/dist/core/workspace/git-observer.js.map +1 -1
  30. package/dist/core/workspace/git-worktree-owner.d.ts +89 -0
  31. package/dist/core/workspace/git-worktree-owner.d.ts.map +1 -0
  32. package/dist/core/workspace/git-worktree-owner.js +240 -0
  33. package/dist/core/workspace/git-worktree-owner.js.map +1 -0
  34. package/dist/main.d.ts.map +1 -1
  35. package/dist/main.js +20 -0
  36. package/dist/main.js.map +1 -1
  37. package/dist/modes/acp/server.d.ts +43 -1
  38. package/dist/modes/acp/server.d.ts.map +1 -1
  39. package/dist/modes/acp/server.js +78 -0
  40. package/dist/modes/acp/server.js.map +1 -1
  41. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  42. package/dist/modes/rpc/rpc-mode.js +38 -0
  43. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  44. package/dist/modes/rpc/rpc-types.d.ts +110 -0
  45. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  46. package/dist/modes/rpc/rpc-types.js.map +1 -1
  47. package/npm-shrinkwrap.json +5 -5
  48. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # Apex Code changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.0.6] - 2026-09-11
4
+
5
+ ### Added
6
+
7
+ - Delegated child sessions. An agent can now launch, list, wait on, resume, interrupt, and close child runs, each with its own durable record, attempt history, and workspace. The six operations are exposed identically on the CLI (`agent` subcommands), on RPC, and on ACP, and `agent/spawn` starts a background child that `agent/wait` later collects.
8
+ - Workspace isolation for a child run. A child can be given its own git worktree; the harness creates and cleans it up, refuses a worktree it does not own, and rejects two children whose claimed paths overlap.
9
+ - A root aggregate budget across a run tree. Token and cost usage from every child rolls up into one ledger, with a per-parent cap on how many children run at once.
10
+ - `agent/status` for polling a child without blocking, and `agent/recover` for an explicit recovery of a child whose workspace is missing. Recovery never recreates a workspace silently.
4
11
 
5
12
  ### Removed
6
13
 
@@ -13,6 +20,12 @@
13
20
  merge hygiene; see ADR 0027. If you were importing it, nothing you could
14
21
  have called worked.
15
22
 
23
+ ### Fixed
24
+
25
+ - Fixed overlapping child-workspace ownership claims being accepted on Windows. The overlap check compared resolved paths with forward-slash prefixes, which never matched once `resolve()` produced backslashes, so two children could claim the same directory.
26
+ - Fixed a child path such as `src/..cache/file` being treated as outside `src`. Path containment now compares whole segments, so a directory whose name merely starts with `..` no longer bypasses the ownership check.
27
+ - Fixed `agent/recover` failing with `EPERM` on Windows. It read the worktree's `.git` pointer file directly; it now asks git for the admin entry with `rev-parse --absolute-git-dir`, which was already the authority.
28
+
16
29
  ## [0.0.1-alpha.11] - 2026-08-30
17
30
 
18
31
  ### Changed
@@ -0,0 +1,24 @@
1
+ /**
2
+ * One-shot execution of the `agent <operation>` CLI subcommand family.
3
+ *
4
+ * The loaded session (and the permission gate its children derive authority from)
5
+ * stays the sole owner of the child-run lifecycle: this module only translates a
6
+ * parsed command into session-owned registry calls and prints a bounded report.
7
+ * It never touches the registry directly and never answers a permission ask.
8
+ */
9
+ import type { AgentSession } from "../core/agent-session.ts";
10
+ import type { AgentLifecycleCommand } from "./args.ts";
11
+ export interface AgentLifecycleCommandOptions {
12
+ /** `--mode json` prints one bounded JSON document; otherwise one line of text per result. */
13
+ json: boolean;
14
+ }
15
+ /**
16
+ * Execute one parsed lifecycle operation against the session and return the process
17
+ * exit code: 0 on success, 1 on unknown child id or any operation failure.
18
+ *
19
+ * `send` and `resume` report the observed post-operation status; `wait` retrieves
20
+ * the run's latest settled turn, so after a follow-up or a resume it prints that
21
+ * turn's output rather than the run's initial text.
22
+ */
23
+ export declare function runAgentLifecycleCommand(session: AgentSession, command: AgentLifecycleCommand, options: AgentLifecycleCommandOptions): Promise<number>;
24
+ //# sourceMappingURL=agent-lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-lifecycle.d.ts","sourceRoot":"","sources":["../../src/cli/agent-lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAE7D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAOvD,MAAM,WAAW,4BAA4B;IAC5C,6FAA6F;IAC7F,IAAI,EAAE,OAAO,CAAC;CACd;AAoCD;;;;;;;GAOG;AACH,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,4BAA4B,GACnC,OAAO,CAAC,MAAM,CAAC,CA0EjB","sourcesContent":["/**\n * One-shot execution of the `agent <operation>` CLI subcommand family.\n *\n * The loaded session (and the permission gate its children derive authority from)\n * stays the sole owner of the child-run lifecycle: this module only translates a\n * parsed command into session-owned registry calls and prints a bounded report.\n * It never touches the registry directly and never answers a permission ask.\n */\n\nimport type { AgentSession } from \"../core/agent-session.ts\";\nimport type { ChildSessionStatus } from \"../core/delegation/runtime.ts\";\nimport type { AgentLifecycleCommand } from \"./args.ts\";\n\n/** JSON-mode ceiling for a run result's output text (spec invariant 8: bounded summaries). */\nconst MAX_JSON_OUTPUT_CHARS = 2_000;\n/** Text mode keeps each result to a single terminal line. */\nconst MAX_TEXT_OUTPUT_CHARS = 160;\n\nexport interface AgentLifecycleCommandOptions {\n\t/** `--mode json` prints one bounded JSON document; otherwise one line of text per result. */\n\tjson: boolean;\n}\n\nfunction firstLineOf(text: string): string {\n\tconst newline = text.indexOf(\"\\n\");\n\treturn newline === -1 ? text : text.slice(0, newline);\n}\n\nfunction bound(text: string, max: number): string {\n\treturn text.length <= max ? text : `${text.slice(0, max)}...`;\n}\n\nfunction observedStatus(session: AgentSession, childId: string): ChildSessionStatus | \"unknown\" {\n\treturn session.listChildRuns().find((run) => run.handleId === childId)?.status ?? \"unknown\";\n}\n\nfunction reportStatus(\n\toperation: \"send\" | \"resume\" | \"interrupt\" | \"close\",\n\tchildId: string,\n\tstatus: ChildSessionStatus | \"unknown\",\n\toptions: AgentLifecycleCommandOptions,\n): void {\n\tif (options.json) {\n\t\tprocess.stdout.write(`${JSON.stringify({ operation, childId, status })}\\n`);\n\t\treturn;\n\t}\n\tconst verb =\n\t\toperation === \"send\"\n\t\t\t? \"Sent input to\"\n\t\t\t: operation === \"resume\"\n\t\t\t\t? \"Resumed\"\n\t\t\t\t: operation === \"interrupt\"\n\t\t\t\t\t? \"Interrupted\"\n\t\t\t\t\t: \"Closed\";\n\tprocess.stdout.write(`${verb} child run ${childId}; status: ${status}\\n`);\n}\n\n/**\n * Execute one parsed lifecycle operation against the session and return the process\n * exit code: 0 on success, 1 on unknown child id or any operation failure.\n *\n * `send` and `resume` report the observed post-operation status; `wait` retrieves\n * the run's latest settled turn, so after a follow-up or a resume it prints that\n * turn's output rather than the run's initial text.\n */\nexport async function runAgentLifecycleCommand(\n\tsession: AgentSession,\n\tcommand: AgentLifecycleCommand,\n\toptions: AgentLifecycleCommandOptions,\n): Promise<number> {\n\tconst { operation } = command;\n\tconst childId = command.childId;\n\ttry {\n\t\tswitch (operation) {\n\t\t\tcase \"list\": {\n\t\t\t\tconst agents = session.listChildRuns();\n\t\t\t\tif (options.json) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify({ operation, agents })}\\n`);\n\t\t\t\t} else if (agents.length === 0) {\n\t\t\t\t\tprocess.stdout.write(\"No child runs.\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tfor (const run of agents) {\n\t\t\t\t\t\tprocess.stdout.write(`${run.handleId} ${run.agentType} ${run.status}\\n`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"wait\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent wait\" requires a child run id.');\n\t\t\t\tconst result = await session.waitChildRun(childId);\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconst truncated = result.output.length > MAX_JSON_OUTPUT_CHARS;\n\t\t\t\t\tprocess.stdout.write(\n\t\t\t\t\t\t`${JSON.stringify({\n\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\tchildId,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\thandleId: result.handleId ?? childId,\n\t\t\t\t\t\t\t\tagentType: result.agentType,\n\t\t\t\t\t\t\t\ttask: result.task,\n\t\t\t\t\t\t\t\toutput: truncated ? result.output.slice(0, MAX_JSON_OUTPUT_CHARS) : result.output,\n\t\t\t\t\t\t\t\toutputTruncated: truncated,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})}\\n`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tconst summary = bound(firstLineOf(result.output), MAX_TEXT_OUTPUT_CHARS);\n\t\t\t\t\tprocess.stdout.write(\n\t\t\t\t\t\t`${result.handleId ?? childId} ${result.agentType}${summary ? `: ${summary}` : \"\"}\\n`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"send\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent send\" requires a child run id.');\n\t\t\t\tif (command.input === undefined) throw new Error('\"agent send\" requires input text.');\n\t\t\t\tawait session.sendChildInput(childId, command.input);\n\t\t\t\treportStatus(operation, childId, observedStatus(session, childId), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"resume\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent resume\" requires a child run id.');\n\t\t\t\treportStatus(operation, childId, await session.resumeChildRun(childId, command.input), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"interrupt\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent interrupt\" requires a child run id.');\n\t\t\t\tsession.interruptChildRun(childId);\n\t\t\t\treportStatus(operation, childId, observedStatus(session, childId), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"close\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent close\" requires a child run id.');\n\t\t\t\tsession.closeChildRun(childId);\n\t\t\t\treportStatus(operation, childId, observedStatus(session, childId), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tprocess.stderr.write(`Error: ${message}\\n`);\n\t\treturn 1;\n\t}\n}\n"]}
@@ -0,0 +1,126 @@
1
+ /**
2
+ * One-shot execution of the `agent <operation>` CLI subcommand family.
3
+ *
4
+ * The loaded session (and the permission gate its children derive authority from)
5
+ * stays the sole owner of the child-run lifecycle: this module only translates a
6
+ * parsed command into session-owned registry calls and prints a bounded report.
7
+ * It never touches the registry directly and never answers a permission ask.
8
+ */
9
+ /** JSON-mode ceiling for a run result's output text (spec invariant 8: bounded summaries). */
10
+ const MAX_JSON_OUTPUT_CHARS = 2_000;
11
+ /** Text mode keeps each result to a single terminal line. */
12
+ const MAX_TEXT_OUTPUT_CHARS = 160;
13
+ function firstLineOf(text) {
14
+ const newline = text.indexOf("\n");
15
+ return newline === -1 ? text : text.slice(0, newline);
16
+ }
17
+ function bound(text, max) {
18
+ return text.length <= max ? text : `${text.slice(0, max)}...`;
19
+ }
20
+ function observedStatus(session, childId) {
21
+ return session.listChildRuns().find((run) => run.handleId === childId)?.status ?? "unknown";
22
+ }
23
+ function reportStatus(operation, childId, status, options) {
24
+ if (options.json) {
25
+ process.stdout.write(`${JSON.stringify({ operation, childId, status })}\n`);
26
+ return;
27
+ }
28
+ const verb = operation === "send"
29
+ ? "Sent input to"
30
+ : operation === "resume"
31
+ ? "Resumed"
32
+ : operation === "interrupt"
33
+ ? "Interrupted"
34
+ : "Closed";
35
+ process.stdout.write(`${verb} child run ${childId}; status: ${status}\n`);
36
+ }
37
+ /**
38
+ * Execute one parsed lifecycle operation against the session and return the process
39
+ * exit code: 0 on success, 1 on unknown child id or any operation failure.
40
+ *
41
+ * `send` and `resume` report the observed post-operation status; `wait` retrieves
42
+ * the run's latest settled turn, so after a follow-up or a resume it prints that
43
+ * turn's output rather than the run's initial text.
44
+ */
45
+ export async function runAgentLifecycleCommand(session, command, options) {
46
+ const { operation } = command;
47
+ const childId = command.childId;
48
+ try {
49
+ switch (operation) {
50
+ case "list": {
51
+ const agents = session.listChildRuns();
52
+ if (options.json) {
53
+ process.stdout.write(`${JSON.stringify({ operation, agents })}\n`);
54
+ }
55
+ else if (agents.length === 0) {
56
+ process.stdout.write("No child runs.\n");
57
+ }
58
+ else {
59
+ for (const run of agents) {
60
+ process.stdout.write(`${run.handleId} ${run.agentType} ${run.status}\n`);
61
+ }
62
+ }
63
+ return 0;
64
+ }
65
+ case "wait": {
66
+ if (childId === undefined)
67
+ throw new Error('"agent wait" requires a child run id.');
68
+ const result = await session.waitChildRun(childId);
69
+ if (options.json) {
70
+ const truncated = result.output.length > MAX_JSON_OUTPUT_CHARS;
71
+ process.stdout.write(`${JSON.stringify({
72
+ operation,
73
+ childId,
74
+ result: {
75
+ handleId: result.handleId ?? childId,
76
+ agentType: result.agentType,
77
+ task: result.task,
78
+ output: truncated ? result.output.slice(0, MAX_JSON_OUTPUT_CHARS) : result.output,
79
+ outputTruncated: truncated,
80
+ },
81
+ })}\n`);
82
+ }
83
+ else {
84
+ const summary = bound(firstLineOf(result.output), MAX_TEXT_OUTPUT_CHARS);
85
+ process.stdout.write(`${result.handleId ?? childId} ${result.agentType}${summary ? `: ${summary}` : ""}\n`);
86
+ }
87
+ return 0;
88
+ }
89
+ case "send": {
90
+ if (childId === undefined)
91
+ throw new Error('"agent send" requires a child run id.');
92
+ if (command.input === undefined)
93
+ throw new Error('"agent send" requires input text.');
94
+ await session.sendChildInput(childId, command.input);
95
+ reportStatus(operation, childId, observedStatus(session, childId), options);
96
+ return 0;
97
+ }
98
+ case "resume": {
99
+ if (childId === undefined)
100
+ throw new Error('"agent resume" requires a child run id.');
101
+ reportStatus(operation, childId, await session.resumeChildRun(childId, command.input), options);
102
+ return 0;
103
+ }
104
+ case "interrupt": {
105
+ if (childId === undefined)
106
+ throw new Error('"agent interrupt" requires a child run id.');
107
+ session.interruptChildRun(childId);
108
+ reportStatus(operation, childId, observedStatus(session, childId), options);
109
+ return 0;
110
+ }
111
+ case "close": {
112
+ if (childId === undefined)
113
+ throw new Error('"agent close" requires a child run id.');
114
+ session.closeChildRun(childId);
115
+ reportStatus(operation, childId, observedStatus(session, childId), options);
116
+ return 0;
117
+ }
118
+ }
119
+ }
120
+ catch (error) {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ process.stderr.write(`Error: ${message}\n`);
123
+ return 1;
124
+ }
125
+ }
126
+ //# sourceMappingURL=agent-lifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-lifecycle.js","sourceRoot":"","sources":["../../src/cli/agent-lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,8FAA8F;AAC9F,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,6DAA6D;AAC7D,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAOlC,SAAS,WAAW,CAAC,IAAY,EAAU;IAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AAAA,CACtD;AAED,SAAS,KAAK,CAAC,IAAY,EAAE,GAAW,EAAU;IACjD,OAAO,IAAI,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC;AAAA,CAC9D;AAED,SAAS,cAAc,CAAC,OAAqB,EAAE,OAAe,EAAkC;IAC/F,OAAO,OAAO,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,EAAE,MAAM,IAAI,SAAS,CAAC;AAAA,CAC5F;AAED,SAAS,YAAY,CACpB,SAAoD,EACpD,OAAe,EACf,MAAsC,EACtC,OAAqC,EAC9B;IACP,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC;QAC5E,OAAO;IACR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;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,OAAO,IAAI,CAAC,CAAC;QAC5C,OAAO,CAAC,CAAC;IACV,CAAC;AAAA,CACD","sourcesContent":["/**\n * One-shot execution of the `agent <operation>` CLI subcommand family.\n *\n * The loaded session (and the permission gate its children derive authority from)\n * stays the sole owner of the child-run lifecycle: this module only translates a\n * parsed command into session-owned registry calls and prints a bounded report.\n * It never touches the registry directly and never answers a permission ask.\n */\n\nimport type { AgentSession } from \"../core/agent-session.ts\";\nimport type { ChildSessionStatus } from \"../core/delegation/runtime.ts\";\nimport type { AgentLifecycleCommand } from \"./args.ts\";\n\n/** JSON-mode ceiling for a run result's output text (spec invariant 8: bounded summaries). */\nconst MAX_JSON_OUTPUT_CHARS = 2_000;\n/** Text mode keeps each result to a single terminal line. */\nconst MAX_TEXT_OUTPUT_CHARS = 160;\n\nexport interface AgentLifecycleCommandOptions {\n\t/** `--mode json` prints one bounded JSON document; otherwise one line of text per result. */\n\tjson: boolean;\n}\n\nfunction firstLineOf(text: string): string {\n\tconst newline = text.indexOf(\"\\n\");\n\treturn newline === -1 ? text : text.slice(0, newline);\n}\n\nfunction bound(text: string, max: number): string {\n\treturn text.length <= max ? text : `${text.slice(0, max)}...`;\n}\n\nfunction observedStatus(session: AgentSession, childId: string): ChildSessionStatus | \"unknown\" {\n\treturn session.listChildRuns().find((run) => run.handleId === childId)?.status ?? \"unknown\";\n}\n\nfunction reportStatus(\n\toperation: \"send\" | \"resume\" | \"interrupt\" | \"close\",\n\tchildId: string,\n\tstatus: ChildSessionStatus | \"unknown\",\n\toptions: AgentLifecycleCommandOptions,\n): void {\n\tif (options.json) {\n\t\tprocess.stdout.write(`${JSON.stringify({ operation, childId, status })}\\n`);\n\t\treturn;\n\t}\n\tconst verb =\n\t\toperation === \"send\"\n\t\t\t? \"Sent input to\"\n\t\t\t: operation === \"resume\"\n\t\t\t\t? \"Resumed\"\n\t\t\t\t: operation === \"interrupt\"\n\t\t\t\t\t? \"Interrupted\"\n\t\t\t\t\t: \"Closed\";\n\tprocess.stdout.write(`${verb} child run ${childId}; status: ${status}\\n`);\n}\n\n/**\n * Execute one parsed lifecycle operation against the session and return the process\n * exit code: 0 on success, 1 on unknown child id or any operation failure.\n *\n * `send` and `resume` report the observed post-operation status; `wait` retrieves\n * the run's latest settled turn, so after a follow-up or a resume it prints that\n * turn's output rather than the run's initial text.\n */\nexport async function runAgentLifecycleCommand(\n\tsession: AgentSession,\n\tcommand: AgentLifecycleCommand,\n\toptions: AgentLifecycleCommandOptions,\n): Promise<number> {\n\tconst { operation } = command;\n\tconst childId = command.childId;\n\ttry {\n\t\tswitch (operation) {\n\t\t\tcase \"list\": {\n\t\t\t\tconst agents = session.listChildRuns();\n\t\t\t\tif (options.json) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify({ operation, agents })}\\n`);\n\t\t\t\t} else if (agents.length === 0) {\n\t\t\t\t\tprocess.stdout.write(\"No child runs.\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tfor (const run of agents) {\n\t\t\t\t\t\tprocess.stdout.write(`${run.handleId} ${run.agentType} ${run.status}\\n`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"wait\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent wait\" requires a child run id.');\n\t\t\t\tconst result = await session.waitChildRun(childId);\n\t\t\t\tif (options.json) {\n\t\t\t\t\tconst truncated = result.output.length > MAX_JSON_OUTPUT_CHARS;\n\t\t\t\t\tprocess.stdout.write(\n\t\t\t\t\t\t`${JSON.stringify({\n\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\tchildId,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\thandleId: result.handleId ?? childId,\n\t\t\t\t\t\t\t\tagentType: result.agentType,\n\t\t\t\t\t\t\t\ttask: result.task,\n\t\t\t\t\t\t\t\toutput: truncated ? result.output.slice(0, MAX_JSON_OUTPUT_CHARS) : result.output,\n\t\t\t\t\t\t\t\toutputTruncated: truncated,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})}\\n`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tconst summary = bound(firstLineOf(result.output), MAX_TEXT_OUTPUT_CHARS);\n\t\t\t\t\tprocess.stdout.write(\n\t\t\t\t\t\t`${result.handleId ?? childId} ${result.agentType}${summary ? `: ${summary}` : \"\"}\\n`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"send\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent send\" requires a child run id.');\n\t\t\t\tif (command.input === undefined) throw new Error('\"agent send\" requires input text.');\n\t\t\t\tawait session.sendChildInput(childId, command.input);\n\t\t\t\treportStatus(operation, childId, observedStatus(session, childId), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"resume\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent resume\" requires a child run id.');\n\t\t\t\treportStatus(operation, childId, await session.resumeChildRun(childId, command.input), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"interrupt\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent interrupt\" requires a child run id.');\n\t\t\t\tsession.interruptChildRun(childId);\n\t\t\t\treportStatus(operation, childId, observedStatus(session, childId), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase \"close\": {\n\t\t\t\tif (childId === undefined) throw new Error('\"agent close\" requires a child run id.');\n\t\t\t\tsession.closeChildRun(childId);\n\t\t\t\treportStatus(operation, childId, observedStatus(session, childId), options);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tprocess.stderr.write(`Error: ${message}\\n`);\n\t\treturn 1;\n\t}\n}\n"]}
@@ -6,7 +6,20 @@ import type { ExtensionFlag } from "../core/extensions/types.ts";
6
6
  import { type PermissionMode } from "../core/permissions/store.ts";
7
7
  import type { TuiMode } from "../core/settings-manager.ts";
8
8
  export type Mode = "text" | "json" | "rpc" | "acp";
9
+ /** The one child-lifecycle subcommand family: `apex-code agent <operation> ...`. */
10
+ export declare const AGENT_LIFECYCLE_OPERATIONS: readonly ["list", "wait", "send", "resume", "interrupt", "close"];
11
+ export type AgentLifecycleOperation = (typeof AGENT_LIFECYCLE_OPERATIONS)[number];
12
+ export declare function isAgentLifecycleOperation(value: string): value is AgentLifecycleOperation;
13
+ export interface AgentLifecycleCommand {
14
+ operation: AgentLifecycleOperation;
15
+ /** Target child run id; required for every operation except `list`. */
16
+ childId?: string;
17
+ /** Follow-up text for `send`; an optional prompt override for `resume`. */
18
+ input?: string;
19
+ }
9
20
  export interface Args {
21
+ /** Parsed `agent <operation>` command; executed by the loaded session's own run owner. */
22
+ agent?: AgentLifecycleCommand;
10
23
  provider?: string;
11
24
  model?: string;
12
25
  apiKey?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"args.d.ts","sourceRoot":"","sources":["../../src/cli/args.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAoB,KAAK,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAE3D,MAAM,MAAM,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,CAAC;AAEnD,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EA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AID,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,aAAa,CAE1E;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGtE;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAmOvD;AAED,wBAAgB,SAAS,CAAC,cAAc,CAAC,EAAE,aAAa,EAAE,GAAG,IAAI,CA+MhE","sourcesContent":["/**\n * CLI argument parsing and help display\n */\n\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport chalk from \"chalk\";\nimport { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, ENV_SESSION_DIR } from \"../config.ts\";\nimport type { ExtensionFlag } from \"../core/extensions/types.ts\";\nimport { PERMISSION_MODES, type PermissionMode } from \"../core/permissions/store.ts\";\nimport type { TuiMode } from \"../core/settings-manager.ts\";\n\nexport type Mode = \"text\" | \"json\" | \"rpc\" | \"acp\";\n\nexport interface Args {\n\tprovider?: string;\n\tmodel?: string;\n\tapiKey?: string;\n\tsystemPrompt?: string;\n\tappendSystemPrompt?: string[];\n\tthinking?: ThinkingLevel;\n\tcontinue?: boolean;\n\tresume?: boolean;\n\thelp?: boolean;\n\tversion?: boolean;\n\tmode?: Mode;\n\tname?: string;\n\tnoSession?: boolean;\n\tallowConcurrent?: boolean;\n\t/**\n\t * Extra directories the OS sandbox makes writable, repeatable.\n\t *\n\t * Read only from argv and never from settings: a repository that could name its own\n\t * writable root would be granting itself authority, which ADR 0016 forbids for every\n\t * supervisor policy input.\n\t */\n\taddDir?: string[];\n\t/** OS sandbox posture. `danger-full-access` runs with no boundary at all. */\n\tsandbox?: \"enforced\" | \"danger-full-access\";\n\t/** A named OS-boundary profile from global settings. Never read from project scope. */\n\tpermissionProfile?: string;\n\tsession?: string;\n\tsessionId?: string;\n\tfork?: string;\n\tsessionDir?: string;\n\tmodels?: string[];\n\ttools?: string[];\n\texcludeTools?: string[];\n\tnoTools?: boolean;\n\tnoBuiltinTools?: boolean;\n\textensions?: string[];\n\tnoExtensions?: boolean;\n\tprint?: boolean;\n\texport?: string;\n\tnoSkills?: boolean;\n\tskills?: string[];\n\tpromptTemplates?: string[];\n\tnoPromptTemplates?: boolean;\n\tthemes?: string[];\n\tuseTheme?: string;\n\tnoThemes?: boolean;\n\tnoContextFiles?: boolean;\n\tlistModels?: string | true;\n\toffline?: boolean;\n\ttuiMode?: TuiMode;\n\t/** ADR 0004 permission mode, registered at the `flag` source (outranks project/user config). */\n\tpermissionMode?: PermissionMode;\n\t/** ADR 0004 convenience allowlist, registered at the low-precedence `cliArg` source. */\n\tallowedTools?: string[];\n\tverbose?: boolean;\n\tprojectTrustOverride?: boolean;\n\tmessages: string[];\n\tfileArgs: string[];\n\t/** Unknown flags (potentially extension flags) - map of flag name to value */\n\tunknownFlags: Map<string, boolean | string>;\n\tdiagnostics: Array<{ type: \"warning\" | \"error\"; message: string }>;\n}\n\nexport type ParsedCliCommand =\n\t| { readonly kind: \"host\"; readonly args: Args }\n\t| { readonly kind: \"metadata\"; readonly args: Args }\n\t| { readonly kind: \"session\"; readonly args: Args };\n\nconst HOST_COMMANDS = new Set([\"auth\", \"config\", \"install\", \"remove\", \"uninstall\", \"update\", \"list\"]);\n\n/** Parse argv once, then classify startup behavior from the resulting values. */\nexport function parseCliCommand(argv: readonly string[]): ParsedCliCommand {\n\tconst args = parseArgs(argv);\n\tif (HOST_COMMANDS.has(argv[0] ?? \"\")) return { kind: \"host\", args };\n\tif (args.help || args.version || args.export !== undefined || args.listModels !== undefined) {\n\t\treturn { kind: \"metadata\", args };\n\t}\n\treturn { kind: \"session\", args };\n}\n\nconst VALID_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport function isValidThinkingLevel(level: string): level is ThinkingLevel {\n\treturn VALID_THINKING_LEVELS.includes(level as ThinkingLevel);\n}\n\nexport function normalizeSessionName(value: string): string | undefined {\n\tconst name = value.trim();\n\treturn name.length > 0 ? name : undefined;\n}\n\nexport function parseArgs(args: readonly string[]): Args {\n\tconst result: Args = {\n\t\tmessages: [],\n\t\tfileArgs: [],\n\t\tunknownFlags: new Map(),\n\t\tdiagnostics: [],\n\t};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\n\t\tif (arg === \"--\") {\n\t\t\tfor (const positionalArg of args.slice(i + 1)) {\n\t\t\t\tif (positionalArg.startsWith(\"@\")) {\n\t\t\t\t\tresult.fileArgs.push(positionalArg.slice(1));\n\t\t\t\t} else {\n\t\t\t\t\tresult.messages.push(positionalArg);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\tresult.help = true;\n\t\t} else if (arg === \"--version\" || arg === \"-v\") {\n\t\t\tresult.version = true;\n\t\t} else if (arg === \"--mode\" && i + 1 < args.length) {\n\t\t\tconst mode = args[++i];\n\t\t\tif (mode === \"text\" || mode === \"json\" || mode === \"rpc\" || mode === \"acp\") {\n\t\t\t\tresult.mode = mode;\n\t\t\t}\n\t\t} else if (arg === \"--continue\" || arg === \"-c\") {\n\t\t\tresult.continue = true;\n\t\t} else if (arg === \"--resume\" || arg === \"-r\") {\n\t\t\tresult.resume = true;\n\t\t} else if (arg === \"--provider\" && i + 1 < args.length) {\n\t\t\tresult.provider = args[++i];\n\t\t} else if (arg === \"--model\" && i + 1 < args.length) {\n\t\t\tresult.model = args[++i];\n\t\t} else if (arg === \"--api-key\" && i + 1 < args.length) {\n\t\t\tresult.apiKey = args[++i];\n\t\t} else if (arg === \"--system-prompt\" && i + 1 < args.length) {\n\t\t\tresult.systemPrompt = args[++i];\n\t\t} else if (arg === \"--append-system-prompt\" && i + 1 < args.length) {\n\t\t\tresult.appendSystemPrompt = result.appendSystemPrompt ?? [];\n\t\t\tresult.appendSystemPrompt.push(args[++i]);\n\t\t} else if (arg === \"--name\" || arg === \"-n\") {\n\t\t\tif (i + 1 < args.length) {\n\t\t\t\tresult.name = args[++i];\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--name requires a value\" });\n\t\t\t}\n\t\t} else if (arg === \"--no-session\") {\n\t\t\tresult.noSession = true;\n\t\t} else if (arg === \"--allow-concurrent\") {\n\t\t\tresult.allowConcurrent = true;\n\t\t} else if (arg === \"--add-dir\") {\n\t\t\tif (i + 1 < args.length) {\n\t\t\t\tif (!result.addDir) result.addDir = [];\n\t\t\t\tresult.addDir.push(args[++i]);\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--add-dir requires a value\" });\n\t\t\t}\n\t\t} else if (arg === \"--permission-profile\") {\n\t\t\tif (i + 1 < args.length) {\n\t\t\t\tresult.permissionProfile = args[++i];\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--permission-profile requires a value\" });\n\t\t\t}\n\t\t} else if (arg === \"--sandbox\") {\n\t\t\tconst value = i + 1 < args.length ? args[++i] : undefined;\n\t\t\tif (value === \"enforced\" || value === \"danger-full-access\") {\n\t\t\t\tresult.sandbox = value;\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: \"--sandbox requires one of: enforced, danger-full-access\",\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--session\" && i + 1 < args.length) {\n\t\t\tresult.session = args[++i];\n\t\t} else if (arg === \"--session-id\" && i + 1 < args.length) {\n\t\t\tresult.sessionId = args[++i];\n\t\t} else if (arg === \"--fork\" && i + 1 < args.length) {\n\t\t\tresult.fork = args[++i];\n\t\t} else if (arg === \"--session-dir\" && i + 1 < args.length) {\n\t\t\tresult.sessionDir = args[++i];\n\t\t} else if (arg === \"--models\" && i + 1 < args.length) {\n\t\t\tresult.models = args[++i].split(\",\").map((s) => s.trim());\n\t\t} else if (arg === \"--no-tools\" || arg === \"-nt\") {\n\t\t\tresult.noTools = true;\n\t\t} else if (arg === \"--no-builtin-tools\" || arg === \"-nbt\") {\n\t\t\tresult.noBuiltinTools = true;\n\t\t} else if ((arg === \"--tools\" || arg === \"-t\") && i + 1 < args.length) {\n\t\t\tresult.tools = args[++i]\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter((name) => name.length > 0);\n\t\t} else if ((arg === \"--exclude-tools\" || arg === \"-xt\") && i + 1 < args.length) {\n\t\t\tresult.excludeTools = args[++i]\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter((name) => name.length > 0);\n\t\t} else if (arg === \"--thinking\" && i + 1 < args.length) {\n\t\t\tconst level = args[++i];\n\t\t\tif (isValidThinkingLevel(level)) {\n\t\t\t\tresult.thinking = level;\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `Invalid thinking level \"${level}\". Valid values: ${VALID_THINKING_LEVELS.join(\", \")}`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--print\" || arg === \"-p\") {\n\t\t\tresult.print = true;\n\t\t\tconst next = args[i + 1];\n\t\t\tif (next !== undefined && !next.startsWith(\"@\") && (!next.startsWith(\"-\") || next.startsWith(\"---\"))) {\n\t\t\t\tresult.messages.push(next);\n\t\t\t\ti++;\n\t\t\t}\n\t\t} else if (arg === \"--export\" && i + 1 < args.length) {\n\t\t\tresult.export = args[++i];\n\t\t} else if ((arg === \"--extension\" || arg === \"-e\") && i + 1 < args.length) {\n\t\t\tresult.extensions = result.extensions ?? [];\n\t\t\tresult.extensions.push(args[++i]);\n\t\t} else if (arg === \"--no-extensions\" || arg === \"-ne\") {\n\t\t\tresult.noExtensions = true;\n\t\t} else if (arg === \"--skill\" && i + 1 < args.length) {\n\t\t\tresult.skills = result.skills ?? [];\n\t\t\tresult.skills.push(args[++i]);\n\t\t} else if (arg === \"--prompt-template\" && i + 1 < args.length) {\n\t\t\tresult.promptTemplates = result.promptTemplates ?? [];\n\t\t\tresult.promptTemplates.push(args[++i]);\n\t\t} else if (arg === \"--theme\" && i + 1 < args.length) {\n\t\t\tresult.themes = result.themes ?? [];\n\t\t\tresult.themes.push(args[++i]);\n\t\t} else if (arg === \"--use-theme\") {\n\t\t\tconst themeName = args[i + 1];\n\t\t\tif (themeName === undefined || themeName.startsWith(\"-\")) {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--use-theme requires a theme name\" });\n\t\t\t} else {\n\t\t\t\tresult.useTheme = themeName;\n\t\t\t\ti++;\n\t\t\t}\n\t\t} else if (arg === \"--no-skills\" || arg === \"-ns\") {\n\t\t\tresult.noSkills = true;\n\t\t} else if (arg === \"--no-prompt-templates\" || arg === \"-np\") {\n\t\t\tresult.noPromptTemplates = true;\n\t\t} else if (arg === \"--no-themes\") {\n\t\t\tresult.noThemes = true;\n\t\t} else if (arg === \"--no-context-files\" || arg === \"-nc\") {\n\t\t\tresult.noContextFiles = true;\n\t\t} else if (arg === \"--list-models\") {\n\t\t\t// Check if next arg is a search pattern (not a flag or file arg)\n\t\t\tif (i + 1 < args.length && !args[i + 1].startsWith(\"-\") && !args[i + 1].startsWith(\"@\")) {\n\t\t\t\tresult.listModels = args[++i];\n\t\t\t} else {\n\t\t\t\tresult.listModels = true;\n\t\t\t}\n\t\t} else if (arg === \"--tui-mode\") {\n\t\t\tconst mode = args[i + 1];\n\t\t\tif (mode === \"regular\" || mode === \"fullscreen\") {\n\t\t\t\tresult.tuiMode = mode;\n\t\t\t\ti++;\n\t\t\t} else if (mode === undefined || mode.startsWith(\"-\")) {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--tui-mode requires regular or fullscreen\" });\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Invalid TUI mode \"${mode}\". Valid values: regular, fullscreen`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--allowed-tools\" && i + 1 < args.length) {\n\t\t\tresult.allowedTools = args[++i]\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((name) => name.trim())\n\t\t\t\t.filter((name) => name.length > 0);\n\t\t} else if (arg === \"--allowed-tools\") {\n\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--allowed-tools requires a value\" });\n\t\t} else if (arg === \"--permission-mode\") {\n\t\t\tconst mode = args[i + 1];\n\t\t\tif (mode !== undefined && (PERMISSION_MODES as readonly string[]).includes(mode)) {\n\t\t\t\tresult.permissionMode = mode as PermissionMode;\n\t\t\t\ti++;\n\t\t\t} else if (mode === undefined || mode.startsWith(\"-\")) {\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `--permission-mode requires a value. Valid modes: ${PERMISSION_MODES.join(\", \")}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Invalid permission mode \"${mode}\". Valid modes: ${PERMISSION_MODES.join(\", \")}`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--verbose\") {\n\t\t\tresult.verbose = true;\n\t\t} else if (arg === \"--approve\" || arg === \"-a\") {\n\t\t\tresult.projectTrustOverride = true;\n\t\t} else if (arg === \"--no-approve\" || arg === \"-na\") {\n\t\t\tresult.projectTrustOverride = false;\n\t\t} else if (arg === \"--offline\") {\n\t\t\tresult.offline = true;\n\t\t} else if (arg.startsWith(\"@\")) {\n\t\t\tresult.fileArgs.push(arg.slice(1)); // Remove @ prefix\n\t\t} else if (arg.startsWith(\"--\")) {\n\t\t\tconst eqIndex = arg.indexOf(\"=\");\n\t\t\tif (eqIndex !== -1) {\n\t\t\t\tresult.unknownFlags.set(arg.slice(2, eqIndex), arg.slice(eqIndex + 1));\n\t\t\t} else {\n\t\t\t\tconst flagName = arg.slice(2);\n\t\t\t\tconst next = args[i + 1];\n\t\t\t\tif (next !== undefined && !next.startsWith(\"-\") && !next.startsWith(\"@\")) {\n\t\t\t\t\tresult.unknownFlags.set(flagName, next);\n\t\t\t\t\ti++;\n\t\t\t\t} else {\n\t\t\t\t\tresult.unknownFlags.set(flagName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (arg.startsWith(\"-\") && !arg.startsWith(\"--\")) {\n\t\t\tresult.diagnostics.push({ type: \"error\", message: `Unknown option: ${arg}` });\n\t\t} else if (!arg.startsWith(\"-\")) {\n\t\t\tresult.messages.push(arg);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport function printHelp(extensionFlags?: ExtensionFlag[]): void {\n\tconst extensionFlagsText =\n\t\textensionFlags && extensionFlags.length > 0\n\t\t\t? `\\n${chalk.bold(\"Extension CLI Flags:\")}\\n${extensionFlags\n\t\t\t\t\t.map((flag) => {\n\t\t\t\t\t\tconst value = flag.type === \"string\" ? \" <value>\" : \"\";\n\t\t\t\t\t\tconst description = flag.description ?? `Registered by ${flag.extensionPath}`;\n\t\t\t\t\t\treturn ` --${flag.name}${value}`.padEnd(30) + description;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")}\\n`\n\t\t\t: \"\";\n\tconsole.log(`${chalk.bold(APP_NAME)} - AI coding assistant with read, bash, edit, write tools\n\n${chalk.bold(\"Usage:\")}\n ${APP_NAME} [options] [--] [@files...] [messages...]\n\n${chalk.bold(\"Commands:\")}\n ${APP_NAME} install <source> [-l] Install extension source and add to settings\n ${APP_NAME} remove <source> [-l] Remove extension source from settings\n ${APP_NAME} uninstall <source> [-l] Alias for remove\n ${APP_NAME} update [source|self|pi] Update Apex Code, extensions, or model catalogs\n ${APP_NAME} list List installed extensions from settings\n ${APP_NAME} config [-l] Open TUI to enable/disable package resources (Tab switches scope)\n ${APP_NAME} auth <command> Print credentials or check provider readiness\n ${APP_NAME} mcp auth <server> Authorize an MCP server that requires OAuth\n ${APP_NAME} <command> --help Show help for install/remove/uninstall/update/list/config/auth\n\n${chalk.bold(\"Options:\")}\n --provider <name> Provider name (default: google)\n --model <pattern> Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")\n --api-key <key> API key (defaults to env vars)\n --system-prompt <text> System prompt (default: coding assistant prompt)\n --append-system-prompt <text> Append text or file contents to the system prompt (can be used multiple times)\n --mode <mode> Output mode: text (default), json, or rpc\n --allow-concurrent Start even if another session holds this directory\n --print, -p Non-interactive mode: process prompt and exit\n --permission-mode <mode> default, plan, acceptEdits, bypassPermissions, or dontAsk.\n Required for non-interactive sessions (--print, json, or rpc mode).\n --allowed-tools <tools> Comma-separated permission defaults; project/local policy still wins.\n --continue, -c Continue previous session\n --resume, -r Select a session to resume\n --session <path|id> Use specific session file or partial UUID\n --session-id <id> Use exact project session ID, creating it if missing\n --fork <path|id> Fork specific session file or partial UUID into a new session\n --session-dir <dir> Directory for session storage and lookup\n --no-session Don't save session (ephemeral)\n --name, -n <name> Set session display name\n --models <patterns> Comma-separated model patterns for Ctrl+P cycling\n Supports globs (anthropic/*, *sonnet*) and fuzzy matching\n --no-tools, -nt Disable all tools by default (built-in and extension)\n --no-builtin-tools, -nbt Disable built-in tools by default but keep extension/custom tools enabled\n --tools, -t <tools> Comma-separated allowlist of tool names to enable\n Applies to built-in, extension, and custom tools\n --exclude-tools, -xt <tools> Comma-separated denylist of tool names to disable\n Applies to built-in, extension, and custom tools\n --thinking <level> Set thinking level: off, minimal, low, medium, high, xhigh, max\n --extension, -e <path> Load an extension file (can be used multiple times)\n --no-extensions, -ne Disable extension discovery (explicit -e paths still work)\n --skill <path> Load a skill file or directory (can be used multiple times)\n --no-skills, -ns Disable skills discovery and loading\n --prompt-template <path> Load a prompt template file or directory (can be used multiple times)\n --no-prompt-templates, -np Disable prompt template discovery and loading\n --theme <path> Load a theme file or directory (can be used multiple times)\n --use-theme <name[/name]> Set the initial interactive theme for this run\n --no-themes Disable theme discovery and loading\n --no-context-files, -nc Disable AGENTS.md and CLAUDE.md discovery and loading\n --export <file> Export session file to HTML and exit\n --list-models [search] List available models (with optional fuzzy search)\n --verbose Force verbose startup (overrides quietStartup setting)\n --tui-mode <mode> TUI mode: regular (default) or fullscreen\n --approve, -a Trust project-local files for this run\n --no-approve, -na Ignore project-local files for this run\n --offline Disable startup network operations (same as APEX_CODE_OFFLINE=1)\n -- End option parsing; treat remaining arguments as messages/files\n --help, -h Show this help\n --version, -v Show version number\n\nExtensions can register additional flags (e.g., --plan from plan-mode extension).${extensionFlagsText}\n\n${chalk.bold(\"Examples:\")}\n # Print a provider API key for an external client\n ${APP_NAME} auth print-api-key --provider openai\n\n # Print an OAuth bearer token for an external client (refreshes if expired)\n ${APP_NAME} auth print-bearer-token --provider openai-codex\n\n # Interactive mode\n ${APP_NAME}\n\n # Interactive mode with initial prompt\n ${APP_NAME} \"List all .ts files in src/\"\n\n # Include files in initial message\n ${APP_NAME} @prompt.md @image.png \"What color is the sky?\"\n\n # Non-interactive mode (process and exit)\n ${APP_NAME} -p \"List all .ts files in src/\"\n\n # Prompt beginning with a dash\n ${APP_NAME} -p -- \"- Summarize these points\"\n\n # Multiple messages (interactive)\n ${APP_NAME} \"Read package.json\" \"What dependencies do we have?\"\n\n # Continue previous session\n ${APP_NAME} --continue \"What did we discuss?\"\n\n # Start a named session\n ${APP_NAME} --name \"Refactor auth module\"\n\n # Use different model\n ${APP_NAME} --provider openai --model gpt-4o-mini \"Help me refactor this code\"\n\n # Use model with provider prefix (no --provider needed)\n ${APP_NAME} --model openai/gpt-4o \"Help me refactor this code\"\n\n # Use model with thinking level shorthand\n ${APP_NAME} --model sonnet:high \"Solve this complex problem\"\n\n # Limit model cycling to specific models\n ${APP_NAME} --models claude-sonnet,claude-haiku,gpt-4o\n\n # Limit to a specific provider with glob pattern\n ${APP_NAME} --models \"github-copilot/*\"\n\n # Cycle models with fixed thinking levels\n ${APP_NAME} --models sonnet:high,haiku:low\n\n # Start with a specific thinking level\n ${APP_NAME} --thinking high \"Solve this complex problem\"\n\n # Read-only mode (no file modifications possible)\n ${APP_NAME} --tools read,grep,find,ls -p \"Review the code in src/\"\n\n # Disable one tool while keeping the rest available\n ${APP_NAME} --exclude-tools ask_question\n\n # Export a session file to HTML\n ${APP_NAME} --export ~/${CONFIG_DIR_NAME}/agent/sessions/--path--/session.jsonl\n ${APP_NAME} --export session.jsonl output.html\n\n${chalk.bold(\"Environment Variables:\")}\n ANTHROPIC_AUTH_TOKEN - Anthropic bearer auth token\n ANTHROPIC_API_KEY - Anthropic Claude API key\n ANTHROPIC_OAUTH_TOKEN - Anthropic OAuth token (alternative to API key)\n ANT_LING_API_KEY - Ant Ling API key\n OPENAI_API_KEY - OpenAI GPT API key\n AZURE_OPENAI_API_KEY - Azure OpenAI API key\n AZURE_OPENAI_BASE_URL - Azure OpenAI/Cognitive Services base URL (e.g. https://{resource}.openai.azure.com)\n AZURE_OPENAI_RESOURCE_NAME - Azure OpenAI resource name (alternative to base URL)\n AZURE_OPENAI_API_VERSION - Azure OpenAI API version (default: v1)\n AZURE_OPENAI_DEPLOYMENT_NAME_MAP - Azure OpenAI model=deployment map (comma-separated)\n DEEPSEEK_API_KEY - DeepSeek API key\n NVIDIA_API_KEY - NVIDIA NIM API key\n GEMINI_API_KEY - Google Gemini API key\n GROQ_API_KEY - Groq API key\n CEREBRAS_API_KEY - Cerebras API key\n XAI_API_KEY - xAI Grok API key\n FIREWORKS_API_KEY - Fireworks API key\n TOGETHER_API_KEY - Together AI API key\n BASETEN_API_KEY - Baseten API key\n OPENROUTER_API_KEY - OpenRouter API key\n AI_GATEWAY_API_KEY - Vercel AI Gateway API key\n ZAI_API_KEY - ZAI Coding Plan API key (Global)\n ZAI_CODING_CN_API_KEY - ZAI Coding Plan API key (China)\n MISTRAL_API_KEY - Mistral API key\n MINIMAX_API_KEY - MiniMax API key\n MOONSHOT_API_KEY - Moonshot AI API key\n OPENCODE_API_KEY - OpenCode Zen/OpenCode Go API key\n KIMI_API_KEY - Kimi For Coding API key\n CLOUDFLARE_API_KEY - Cloudflare API token (Workers AI and AI Gateway)\n CLOUDFLARE_ACCOUNT_ID - Cloudflare account id (required for both)\n CLOUDFLARE_GATEWAY_ID - Cloudflare AI Gateway slug (required for AI Gateway)\n QWEN_TOKEN_PLAN_API_KEY - Qwen Token Plan API key (international region)\n QWEN_TOKEN_PLAN_CN_API_KEY - Qwen Token Plan API key (China region)\n XIAOMI_API_KEY - Xiaomi MiMo API key (api.xiaomimimo.com billing)\n XIAOMI_TOKEN_PLAN_CN_API_KEY - Xiaomi MiMo Token Plan API key (China region)\n XIAOMI_TOKEN_PLAN_AMS_API_KEY - Xiaomi MiMo Token Plan API key (Amsterdam region)\n XIAOMI_TOKEN_PLAN_SGP_API_KEY - Xiaomi MiMo Token Plan API key (Singapore region)\n AWS_PROFILE - AWS profile for Amazon Bedrock\n AWS_ACCESS_KEY_ID - AWS access key for Amazon Bedrock\n AWS_SECRET_ACCESS_KEY - AWS secret key for Amazon Bedrock\n AWS_BEARER_TOKEN_BEDROCK - Bedrock API key (bearer token)\n AWS_REGION - AWS region for Amazon Bedrock (e.g., us-east-1)\n ${ENV_AGENT_DIR.padEnd(32)} - Config directory (default: ~/${CONFIG_DIR_NAME}/agent)\n ${ENV_SESSION_DIR.padEnd(32)} - Session storage directory (overridden by --session-dir)\n APEX_CODE_PACKAGE_DIR - Override package directory (for Nix/Guix store paths)\n APEX_CODE_OFFLINE - Disable startup network operations when set to 1/true/yes\n APEX_CODE_SKIP_VERSION_CHECK - Skip the npm prerelease version check\n APEX_CODE_EXPERIMENTAL - Enable experimental features when set to 1\n APEX_CODE_STARTUP_BENCHMARK - Enable startup benchmarking\n APEX_CODE_TIMING - Enable timing diagnostics when set to 1\n APEX_CODE_CLEAR_ON_SHRINK - Clear context on shrink when set to 1\n APEX_CODE_HARDWARE_CURSOR - Show the hardware cursor when set to 1\n APEX_CODE_MODEL_CATALOG_URL - Optional base URL for remote model catalog refreshes\n APEX_CODE_SHARE_VIEWER_URL - Optional base URL for /share preview links\n\n${chalk.bold(\"Built-in Tool Names:\")}\n read - Read file contents\n bash - Execute bash commands\n powershell - Execute PowerShell commands on Windows\n edit - Edit files with find/replace\n write - Write files (creates/overwrites)\n grep - Search file contents (read-only, off by default)\n find - Find files by glob pattern (read-only, off by default)\n ls - List directory contents (read-only, off by default)\n`);\n}\n"]}
1
+ {"version":3,"file":"args.d.ts","sourceRoot":"","sources":["../../src/cli/args.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAoB,KAAK,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAE3D,MAAM,MAAM,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,CAAC;AAEnD,oFAAoF;AACpF,eAAO,MAAM,0BAA0B,mEAAoE,CAAC;AAC5G,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,CAAC;AAElF,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,uBAAuB,CAEzF;AAED,MAAM,WAAW,qBAAqB;IACrC,SAAS,EAAE,uBAAuB,CAAC;IACnC,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,IAAI;IACpB,0FAA0F;IAC1F,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kBAAkB,CAAC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AK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGtE;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAmOvD;AAED,wBAAgB,SAAS,CAAC,cAAc,CAAC,EAAE,aAAa,EAAE,GAAG,IAAI,CAkNhE","sourcesContent":["/**\n * CLI argument parsing and help display\n */\n\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport chalk from \"chalk\";\nimport { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, ENV_SESSION_DIR } from \"../config.ts\";\nimport type { ExtensionFlag } from \"../core/extensions/types.ts\";\nimport { PERMISSION_MODES, type PermissionMode } from \"../core/permissions/store.ts\";\nimport type { TuiMode } from \"../core/settings-manager.ts\";\n\nexport type Mode = \"text\" | \"json\" | \"rpc\" | \"acp\";\n\n/** The one child-lifecycle subcommand family: `apex-code agent <operation> ...`. */\nexport const AGENT_LIFECYCLE_OPERATIONS = [\"list\", \"wait\", \"send\", \"resume\", \"interrupt\", \"close\"] as const;\nexport type AgentLifecycleOperation = (typeof AGENT_LIFECYCLE_OPERATIONS)[number];\n\nexport function isAgentLifecycleOperation(value: string): value is AgentLifecycleOperation {\n\treturn (AGENT_LIFECYCLE_OPERATIONS as readonly string[]).includes(value);\n}\n\nexport interface AgentLifecycleCommand {\n\toperation: AgentLifecycleOperation;\n\t/** Target child run id; required for every operation except `list`. */\n\tchildId?: string;\n\t/** Follow-up text for `send`; an optional prompt override for `resume`. */\n\tinput?: string;\n}\n\nexport interface Args {\n\t/** Parsed `agent <operation>` command; executed by the loaded session's own run owner. */\n\tagent?: AgentLifecycleCommand;\n\tprovider?: string;\n\tmodel?: string;\n\tapiKey?: string;\n\tsystemPrompt?: string;\n\tappendSystemPrompt?: string[];\n\tthinking?: ThinkingLevel;\n\tcontinue?: boolean;\n\tresume?: boolean;\n\thelp?: boolean;\n\tversion?: boolean;\n\tmode?: Mode;\n\tname?: string;\n\tnoSession?: boolean;\n\tallowConcurrent?: boolean;\n\t/**\n\t * Extra directories the OS sandbox makes writable, repeatable.\n\t *\n\t * Read only from argv and never from settings: a repository that could name its own\n\t * writable root would be granting itself authority, which ADR 0016 forbids for every\n\t * supervisor policy input.\n\t */\n\taddDir?: string[];\n\t/** OS sandbox posture. `danger-full-access` runs with no boundary at all. */\n\tsandbox?: \"enforced\" | \"danger-full-access\";\n\t/** A named OS-boundary profile from global settings. Never read from project scope. */\n\tpermissionProfile?: string;\n\tsession?: string;\n\tsessionId?: string;\n\tfork?: string;\n\tsessionDir?: string;\n\tmodels?: string[];\n\ttools?: string[];\n\texcludeTools?: string[];\n\tnoTools?: boolean;\n\tnoBuiltinTools?: boolean;\n\textensions?: string[];\n\tnoExtensions?: boolean;\n\tprint?: boolean;\n\texport?: string;\n\tnoSkills?: boolean;\n\tskills?: string[];\n\tpromptTemplates?: string[];\n\tnoPromptTemplates?: boolean;\n\tthemes?: string[];\n\tuseTheme?: string;\n\tnoThemes?: boolean;\n\tnoContextFiles?: boolean;\n\tlistModels?: string | true;\n\toffline?: boolean;\n\ttuiMode?: TuiMode;\n\t/** ADR 0004 permission mode, registered at the `flag` source (outranks project/user config). */\n\tpermissionMode?: PermissionMode;\n\t/** ADR 0004 convenience allowlist, registered at the low-precedence `cliArg` source. */\n\tallowedTools?: string[];\n\tverbose?: boolean;\n\tprojectTrustOverride?: boolean;\n\tmessages: string[];\n\tfileArgs: string[];\n\t/** Unknown flags (potentially extension flags) - map of flag name to value */\n\tunknownFlags: Map<string, boolean | string>;\n\tdiagnostics: Array<{ type: \"warning\" | \"error\"; message: string }>;\n}\n\nexport type ParsedCliCommand =\n\t| { readonly kind: \"host\"; readonly args: Args }\n\t| { readonly kind: \"metadata\"; readonly args: Args }\n\t| { readonly kind: \"session\"; readonly args: Args };\n\nconst HOST_COMMANDS = new Set([\"auth\", \"config\", \"install\", \"remove\", \"uninstall\", \"update\", \"list\"]);\n\n/**\n * Parse the `agent <operation>` subcommand family out of the first positional token.\n *\n * The subcommand lives under `agent` rather than bare top-level verbs because verbs\n * like `list` already name host commands. It is classified as a session-kind command:\n * child lifecycle operations run against a real loaded session (children derive their\n * authority from its permission gate), so they must take the sandboxed path like any\n * other session startup.\n */\nfunction parseAgentCommand(args: Args): void {\n\targs.messages = args.messages.slice(1);\n\tif (args.fileArgs.length > 0) {\n\t\targs.fileArgs = [];\n\t\targs.diagnostics.push({ type: \"error\", message: '\"agent\" commands do not accept @file arguments' });\n\t\treturn;\n\t}\n\tconst [operation, childId, ...rest] = args.messages;\n\targs.messages = [];\n\tconst usage = `Valid operations: ${AGENT_LIFECYCLE_OPERATIONS.join(\", \")}. A resumable session source is required: --session <path|id> or --continue.`;\n\tif (operation === undefined) {\n\t\targs.diagnostics.push({ type: \"error\", message: `\"agent\" requires an operation. ${usage}` });\n\t\treturn;\n\t}\n\tif (!isAgentLifecycleOperation(operation)) {\n\t\targs.diagnostics.push({ type: \"error\", message: `Unknown agent operation \"${operation}\". ${usage}` });\n\t\treturn;\n\t}\n\tif (operation === \"list\") {\n\t\tif (childId !== undefined) {\n\t\t\targs.diagnostics.push({ type: \"error\", message: `\"agent list\" takes no arguments. ${usage}` });\n\t\t\treturn;\n\t\t}\n\t\targs.agent = { operation };\n\t} else if (operation === \"send\") {\n\t\tif (childId === undefined || rest.length === 0) {\n\t\t\targs.diagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `\"agent send\" requires a child run id followed by input text. ${usage}`,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\targs.agent = { operation, childId, input: rest.join(\" \") };\n\t} else if (operation === \"resume\") {\n\t\tif (childId === undefined) {\n\t\t\targs.diagnostics.push({ type: \"error\", message: `\"agent resume\" requires a child run id. ${usage}` });\n\t\t\treturn;\n\t\t}\n\t\targs.agent = rest.length > 0 ? { operation, childId, input: rest.join(\" \") } : { operation, childId };\n\t} else {\n\t\tif (childId === undefined) {\n\t\t\targs.diagnostics.push({ type: \"error\", message: `\"agent ${operation}\" requires a child run id. ${usage}` });\n\t\t\treturn;\n\t\t}\n\t\tif (rest.length > 0) {\n\t\t\targs.diagnostics.push({ type: \"error\", message: `\"agent ${operation}\" takes only a child run id. ${usage}` });\n\t\t\treturn;\n\t\t}\n\t\targs.agent = { operation, childId };\n\t}\n\tif (args.session === undefined && args.continue !== true) {\n\t\targs.diagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `\"agent ${operation}\" requires a resumable session source: --session <path|id> or --continue.`,\n\t\t});\n\t}\n}\n\n/** Parse argv once, then classify startup behavior from the resulting values. */\nexport function parseCliCommand(argv: readonly string[]): ParsedCliCommand {\n\tconst args = parseArgs(argv);\n\tif (HOST_COMMANDS.has(argv[0] ?? \"\")) return { kind: \"host\", args };\n\tif (args.help || args.version || args.export !== undefined || args.listModels !== undefined) {\n\t\treturn { kind: \"metadata\", args };\n\t}\n\tif (args.messages[0] === \"agent\") {\n\t\tparseAgentCommand(args);\n\t}\n\treturn { kind: \"session\", args };\n}\n\nconst VALID_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport function isValidThinkingLevel(level: string): level is ThinkingLevel {\n\treturn VALID_THINKING_LEVELS.includes(level as ThinkingLevel);\n}\n\nexport function normalizeSessionName(value: string): string | undefined {\n\tconst name = value.trim();\n\treturn name.length > 0 ? name : undefined;\n}\n\nexport function parseArgs(args: readonly string[]): Args {\n\tconst result: Args = {\n\t\tmessages: [],\n\t\tfileArgs: [],\n\t\tunknownFlags: new Map(),\n\t\tdiagnostics: [],\n\t};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\n\t\tif (arg === \"--\") {\n\t\t\tfor (const positionalArg of args.slice(i + 1)) {\n\t\t\t\tif (positionalArg.startsWith(\"@\")) {\n\t\t\t\t\tresult.fileArgs.push(positionalArg.slice(1));\n\t\t\t\t} else {\n\t\t\t\t\tresult.messages.push(positionalArg);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\tresult.help = true;\n\t\t} else if (arg === \"--version\" || arg === \"-v\") {\n\t\t\tresult.version = true;\n\t\t} else if (arg === \"--mode\" && i + 1 < args.length) {\n\t\t\tconst mode = args[++i];\n\t\t\tif (mode === \"text\" || mode === \"json\" || mode === \"rpc\" || mode === \"acp\") {\n\t\t\t\tresult.mode = mode;\n\t\t\t}\n\t\t} else if (arg === \"--continue\" || arg === \"-c\") {\n\t\t\tresult.continue = true;\n\t\t} else if (arg === \"--resume\" || arg === \"-r\") {\n\t\t\tresult.resume = true;\n\t\t} else if (arg === \"--provider\" && i + 1 < args.length) {\n\t\t\tresult.provider = args[++i];\n\t\t} else if (arg === \"--model\" && i + 1 < args.length) {\n\t\t\tresult.model = args[++i];\n\t\t} else if (arg === \"--api-key\" && i + 1 < args.length) {\n\t\t\tresult.apiKey = args[++i];\n\t\t} else if (arg === \"--system-prompt\" && i + 1 < args.length) {\n\t\t\tresult.systemPrompt = args[++i];\n\t\t} else if (arg === \"--append-system-prompt\" && i + 1 < args.length) {\n\t\t\tresult.appendSystemPrompt = result.appendSystemPrompt ?? [];\n\t\t\tresult.appendSystemPrompt.push(args[++i]);\n\t\t} else if (arg === \"--name\" || arg === \"-n\") {\n\t\t\tif (i + 1 < args.length) {\n\t\t\t\tresult.name = args[++i];\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--name requires a value\" });\n\t\t\t}\n\t\t} else if (arg === \"--no-session\") {\n\t\t\tresult.noSession = true;\n\t\t} else if (arg === \"--allow-concurrent\") {\n\t\t\tresult.allowConcurrent = true;\n\t\t} else if (arg === \"--add-dir\") {\n\t\t\tif (i + 1 < args.length) {\n\t\t\t\tif (!result.addDir) result.addDir = [];\n\t\t\t\tresult.addDir.push(args[++i]);\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--add-dir requires a value\" });\n\t\t\t}\n\t\t} else if (arg === \"--permission-profile\") {\n\t\t\tif (i + 1 < args.length) {\n\t\t\t\tresult.permissionProfile = args[++i];\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--permission-profile requires a value\" });\n\t\t\t}\n\t\t} else if (arg === \"--sandbox\") {\n\t\t\tconst value = i + 1 < args.length ? args[++i] : undefined;\n\t\t\tif (value === \"enforced\" || value === \"danger-full-access\") {\n\t\t\t\tresult.sandbox = value;\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: \"--sandbox requires one of: enforced, danger-full-access\",\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--session\" && i + 1 < args.length) {\n\t\t\tresult.session = args[++i];\n\t\t} else if (arg === \"--session-id\" && i + 1 < args.length) {\n\t\t\tresult.sessionId = args[++i];\n\t\t} else if (arg === \"--fork\" && i + 1 < args.length) {\n\t\t\tresult.fork = args[++i];\n\t\t} else if (arg === \"--session-dir\" && i + 1 < args.length) {\n\t\t\tresult.sessionDir = args[++i];\n\t\t} else if (arg === \"--models\" && i + 1 < args.length) {\n\t\t\tresult.models = args[++i].split(\",\").map((s) => s.trim());\n\t\t} else if (arg === \"--no-tools\" || arg === \"-nt\") {\n\t\t\tresult.noTools = true;\n\t\t} else if (arg === \"--no-builtin-tools\" || arg === \"-nbt\") {\n\t\t\tresult.noBuiltinTools = true;\n\t\t} else if ((arg === \"--tools\" || arg === \"-t\") && i + 1 < args.length) {\n\t\t\tresult.tools = args[++i]\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter((name) => name.length > 0);\n\t\t} else if ((arg === \"--exclude-tools\" || arg === \"-xt\") && i + 1 < args.length) {\n\t\t\tresult.excludeTools = args[++i]\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter((name) => name.length > 0);\n\t\t} else if (arg === \"--thinking\" && i + 1 < args.length) {\n\t\t\tconst level = args[++i];\n\t\t\tif (isValidThinkingLevel(level)) {\n\t\t\t\tresult.thinking = level;\n\t\t\t} else {\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `Invalid thinking level \"${level}\". Valid values: ${VALID_THINKING_LEVELS.join(\", \")}`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--print\" || arg === \"-p\") {\n\t\t\tresult.print = true;\n\t\t\tconst next = args[i + 1];\n\t\t\tif (next !== undefined && !next.startsWith(\"@\") && (!next.startsWith(\"-\") || next.startsWith(\"---\"))) {\n\t\t\t\tresult.messages.push(next);\n\t\t\t\ti++;\n\t\t\t}\n\t\t} else if (arg === \"--export\" && i + 1 < args.length) {\n\t\t\tresult.export = args[++i];\n\t\t} else if ((arg === \"--extension\" || arg === \"-e\") && i + 1 < args.length) {\n\t\t\tresult.extensions = result.extensions ?? [];\n\t\t\tresult.extensions.push(args[++i]);\n\t\t} else if (arg === \"--no-extensions\" || arg === \"-ne\") {\n\t\t\tresult.noExtensions = true;\n\t\t} else if (arg === \"--skill\" && i + 1 < args.length) {\n\t\t\tresult.skills = result.skills ?? [];\n\t\t\tresult.skills.push(args[++i]);\n\t\t} else if (arg === \"--prompt-template\" && i + 1 < args.length) {\n\t\t\tresult.promptTemplates = result.promptTemplates ?? [];\n\t\t\tresult.promptTemplates.push(args[++i]);\n\t\t} else if (arg === \"--theme\" && i + 1 < args.length) {\n\t\t\tresult.themes = result.themes ?? [];\n\t\t\tresult.themes.push(args[++i]);\n\t\t} else if (arg === \"--use-theme\") {\n\t\t\tconst themeName = args[i + 1];\n\t\t\tif (themeName === undefined || themeName.startsWith(\"-\")) {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--use-theme requires a theme name\" });\n\t\t\t} else {\n\t\t\t\tresult.useTheme = themeName;\n\t\t\t\ti++;\n\t\t\t}\n\t\t} else if (arg === \"--no-skills\" || arg === \"-ns\") {\n\t\t\tresult.noSkills = true;\n\t\t} else if (arg === \"--no-prompt-templates\" || arg === \"-np\") {\n\t\t\tresult.noPromptTemplates = true;\n\t\t} else if (arg === \"--no-themes\") {\n\t\t\tresult.noThemes = true;\n\t\t} else if (arg === \"--no-context-files\" || arg === \"-nc\") {\n\t\t\tresult.noContextFiles = true;\n\t\t} else if (arg === \"--list-models\") {\n\t\t\t// Check if next arg is a search pattern (not a flag or file arg)\n\t\t\tif (i + 1 < args.length && !args[i + 1].startsWith(\"-\") && !args[i + 1].startsWith(\"@\")) {\n\t\t\t\tresult.listModels = args[++i];\n\t\t\t} else {\n\t\t\t\tresult.listModels = true;\n\t\t\t}\n\t\t} else if (arg === \"--tui-mode\") {\n\t\t\tconst mode = args[i + 1];\n\t\t\tif (mode === \"regular\" || mode === \"fullscreen\") {\n\t\t\t\tresult.tuiMode = mode;\n\t\t\t\ti++;\n\t\t\t} else if (mode === undefined || mode.startsWith(\"-\")) {\n\t\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--tui-mode requires regular or fullscreen\" });\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Invalid TUI mode \"${mode}\". Valid values: regular, fullscreen`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--allowed-tools\" && i + 1 < args.length) {\n\t\t\tresult.allowedTools = args[++i]\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((name) => name.trim())\n\t\t\t\t.filter((name) => name.length > 0);\n\t\t} else if (arg === \"--allowed-tools\") {\n\t\t\tresult.diagnostics.push({ type: \"error\", message: \"--allowed-tools requires a value\" });\n\t\t} else if (arg === \"--permission-mode\") {\n\t\t\tconst mode = args[i + 1];\n\t\t\tif (mode !== undefined && (PERMISSION_MODES as readonly string[]).includes(mode)) {\n\t\t\t\tresult.permissionMode = mode as PermissionMode;\n\t\t\t\ti++;\n\t\t\t} else if (mode === undefined || mode.startsWith(\"-\")) {\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `--permission-mode requires a value. Valid modes: ${PERMISSION_MODES.join(\", \")}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t\tresult.diagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Invalid permission mode \"${mode}\". Valid modes: ${PERMISSION_MODES.join(\", \")}`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (arg === \"--verbose\") {\n\t\t\tresult.verbose = true;\n\t\t} else if (arg === \"--approve\" || arg === \"-a\") {\n\t\t\tresult.projectTrustOverride = true;\n\t\t} else if (arg === \"--no-approve\" || arg === \"-na\") {\n\t\t\tresult.projectTrustOverride = false;\n\t\t} else if (arg === \"--offline\") {\n\t\t\tresult.offline = true;\n\t\t} else if (arg.startsWith(\"@\")) {\n\t\t\tresult.fileArgs.push(arg.slice(1)); // Remove @ prefix\n\t\t} else if (arg.startsWith(\"--\")) {\n\t\t\tconst eqIndex = arg.indexOf(\"=\");\n\t\t\tif (eqIndex !== -1) {\n\t\t\t\tresult.unknownFlags.set(arg.slice(2, eqIndex), arg.slice(eqIndex + 1));\n\t\t\t} else {\n\t\t\t\tconst flagName = arg.slice(2);\n\t\t\t\tconst next = args[i + 1];\n\t\t\t\tif (next !== undefined && !next.startsWith(\"-\") && !next.startsWith(\"@\")) {\n\t\t\t\t\tresult.unknownFlags.set(flagName, next);\n\t\t\t\t\ti++;\n\t\t\t\t} else {\n\t\t\t\t\tresult.unknownFlags.set(flagName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (arg.startsWith(\"-\") && !arg.startsWith(\"--\")) {\n\t\t\tresult.diagnostics.push({ type: \"error\", message: `Unknown option: ${arg}` });\n\t\t} else if (!arg.startsWith(\"-\")) {\n\t\t\tresult.messages.push(arg);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport function printHelp(extensionFlags?: ExtensionFlag[]): void {\n\tconst extensionFlagsText =\n\t\textensionFlags && extensionFlags.length > 0\n\t\t\t? `\\n${chalk.bold(\"Extension CLI Flags:\")}\\n${extensionFlags\n\t\t\t\t\t.map((flag) => {\n\t\t\t\t\t\tconst value = flag.type === \"string\" ? \" <value>\" : \"\";\n\t\t\t\t\t\tconst description = flag.description ?? `Registered by ${flag.extensionPath}`;\n\t\t\t\t\t\treturn ` --${flag.name}${value}`.padEnd(30) + description;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")}\\n`\n\t\t\t: \"\";\n\tconsole.log(`${chalk.bold(APP_NAME)} - AI coding assistant with read, bash, edit, write tools\n\n${chalk.bold(\"Usage:\")}\n ${APP_NAME} [options] [--] [@files...] [messages...]\n\n${chalk.bold(\"Commands:\")}\n ${APP_NAME} install <source> [-l] Install extension source and add to settings\n ${APP_NAME} remove <source> [-l] Remove extension source from settings\n ${APP_NAME} uninstall <source> [-l] Alias for remove\n ${APP_NAME} update [source|self|pi] Update Apex Code, extensions, or model catalogs\n ${APP_NAME} list List installed extensions from settings\n ${APP_NAME} agent <operation> ... Child run lifecycle: list | wait | send | resume | interrupt | close\n Requires --session <path|id> or --continue; needs a permission\n mode like any non-interactive session. Prints JSON with --mode json\n ${APP_NAME} config [-l] Open TUI to enable/disable package resources (Tab switches scope)\n ${APP_NAME} auth <command> Print credentials or check provider readiness\n ${APP_NAME} mcp auth <server> Authorize an MCP server that requires OAuth\n ${APP_NAME} <command> --help Show help for install/remove/uninstall/update/list/config/auth\n\n${chalk.bold(\"Options:\")}\n --provider <name> Provider name (default: google)\n --model <pattern> Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")\n --api-key <key> API key (defaults to env vars)\n --system-prompt <text> System prompt (default: coding assistant prompt)\n --append-system-prompt <text> Append text or file contents to the system prompt (can be used multiple times)\n --mode <mode> Output mode: text (default), json, or rpc\n --allow-concurrent Start even if another session holds this directory\n --print, -p Non-interactive mode: process prompt and exit\n --permission-mode <mode> default, plan, acceptEdits, bypassPermissions, or dontAsk.\n Required for non-interactive sessions (--print, json, or rpc mode).\n --allowed-tools <tools> Comma-separated permission defaults; project/local policy still wins.\n --continue, -c Continue previous session\n --resume, -r Select a session to resume\n --session <path|id> Use specific session file or partial UUID\n --session-id <id> Use exact project session ID, creating it if missing\n --fork <path|id> Fork specific session file or partial UUID into a new session\n --session-dir <dir> Directory for session storage and lookup\n --no-session Don't save session (ephemeral)\n --name, -n <name> Set session display name\n --models <patterns> Comma-separated model patterns for Ctrl+P cycling\n Supports globs (anthropic/*, *sonnet*) and fuzzy matching\n --no-tools, -nt Disable all tools by default (built-in and extension)\n --no-builtin-tools, -nbt Disable built-in tools by default but keep extension/custom tools enabled\n --tools, -t <tools> Comma-separated allowlist of tool names to enable\n Applies to built-in, extension, and custom tools\n --exclude-tools, -xt <tools> Comma-separated denylist of tool names to disable\n Applies to built-in, extension, and custom tools\n --thinking <level> Set thinking level: off, minimal, low, medium, high, xhigh, max\n --extension, -e <path> Load an extension file (can be used multiple times)\n --no-extensions, -ne Disable extension discovery (explicit -e paths still work)\n --skill <path> Load a skill file or directory (can be used multiple times)\n --no-skills, -ns Disable skills discovery and loading\n --prompt-template <path> Load a prompt template file or directory (can be used multiple times)\n --no-prompt-templates, -np Disable prompt template discovery and loading\n --theme <path> Load a theme file or directory (can be used multiple times)\n --use-theme <name[/name]> Set the initial interactive theme for this run\n --no-themes Disable theme discovery and loading\n --no-context-files, -nc Disable AGENTS.md and CLAUDE.md discovery and loading\n --export <file> Export session file to HTML and exit\n --list-models [search] List available models (with optional fuzzy search)\n --verbose Force verbose startup (overrides quietStartup setting)\n --tui-mode <mode> TUI mode: regular (default) or fullscreen\n --approve, -a Trust project-local files for this run\n --no-approve, -na Ignore project-local files for this run\n --offline Disable startup network operations (same as APEX_CODE_OFFLINE=1)\n -- End option parsing; treat remaining arguments as messages/files\n --help, -h Show this help\n --version, -v Show version number\n\nExtensions can register additional flags (e.g., --plan from plan-mode extension).${extensionFlagsText}\n\n${chalk.bold(\"Examples:\")}\n # Print a provider API key for an external client\n ${APP_NAME} auth print-api-key --provider openai\n\n # Print an OAuth bearer token for an external client (refreshes if expired)\n ${APP_NAME} auth print-bearer-token --provider openai-codex\n\n # Interactive mode\n ${APP_NAME}\n\n # Interactive mode with initial prompt\n ${APP_NAME} \"List all .ts files in src/\"\n\n # Include files in initial message\n ${APP_NAME} @prompt.md @image.png \"What color is the sky?\"\n\n # Non-interactive mode (process and exit)\n ${APP_NAME} -p \"List all .ts files in src/\"\n\n # Prompt beginning with a dash\n ${APP_NAME} -p -- \"- Summarize these points\"\n\n # Multiple messages (interactive)\n ${APP_NAME} \"Read package.json\" \"What dependencies do we have?\"\n\n # Continue previous session\n ${APP_NAME} --continue \"What did we discuss?\"\n\n # Start a named session\n ${APP_NAME} --name \"Refactor auth module\"\n\n # Use different model\n ${APP_NAME} --provider openai --model gpt-4o-mini \"Help me refactor this code\"\n\n # Use model with provider prefix (no --provider needed)\n ${APP_NAME} --model openai/gpt-4o \"Help me refactor this code\"\n\n # Use model with thinking level shorthand\n ${APP_NAME} --model sonnet:high \"Solve this complex problem\"\n\n # Limit model cycling to specific models\n ${APP_NAME} --models claude-sonnet,claude-haiku,gpt-4o\n\n # Limit to a specific provider with glob pattern\n ${APP_NAME} --models \"github-copilot/*\"\n\n # Cycle models with fixed thinking levels\n ${APP_NAME} --models sonnet:high,haiku:low\n\n # Start with a specific thinking level\n ${APP_NAME} --thinking high \"Solve this complex problem\"\n\n # Read-only mode (no file modifications possible)\n ${APP_NAME} --tools read,grep,find,ls -p \"Review the code in src/\"\n\n # Disable one tool while keeping the rest available\n ${APP_NAME} --exclude-tools ask_question\n\n # Export a session file to HTML\n ${APP_NAME} --export ~/${CONFIG_DIR_NAME}/agent/sessions/--path--/session.jsonl\n ${APP_NAME} --export session.jsonl output.html\n\n${chalk.bold(\"Environment Variables:\")}\n ANTHROPIC_AUTH_TOKEN - Anthropic bearer auth token\n ANTHROPIC_API_KEY - Anthropic Claude API key\n ANTHROPIC_OAUTH_TOKEN - Anthropic OAuth token (alternative to API key)\n ANT_LING_API_KEY - Ant Ling API key\n OPENAI_API_KEY - OpenAI GPT API key\n AZURE_OPENAI_API_KEY - Azure OpenAI API key\n AZURE_OPENAI_BASE_URL - Azure OpenAI/Cognitive Services base URL (e.g. https://{resource}.openai.azure.com)\n AZURE_OPENAI_RESOURCE_NAME - Azure OpenAI resource name (alternative to base URL)\n AZURE_OPENAI_API_VERSION - Azure OpenAI API version (default: v1)\n AZURE_OPENAI_DEPLOYMENT_NAME_MAP - Azure OpenAI model=deployment map (comma-separated)\n DEEPSEEK_API_KEY - DeepSeek API key\n NVIDIA_API_KEY - NVIDIA NIM API key\n GEMINI_API_KEY - Google Gemini API key\n GROQ_API_KEY - Groq API key\n CEREBRAS_API_KEY - Cerebras API key\n XAI_API_KEY - xAI Grok API key\n FIREWORKS_API_KEY - Fireworks API key\n TOGETHER_API_KEY - Together AI API key\n BASETEN_API_KEY - Baseten API key\n OPENROUTER_API_KEY - OpenRouter API key\n AI_GATEWAY_API_KEY - Vercel AI Gateway API key\n ZAI_API_KEY - ZAI Coding Plan API key (Global)\n ZAI_CODING_CN_API_KEY - ZAI Coding Plan API key (China)\n MISTRAL_API_KEY - Mistral API key\n MINIMAX_API_KEY - MiniMax API key\n MOONSHOT_API_KEY - Moonshot AI API key\n OPENCODE_API_KEY - OpenCode Zen/OpenCode Go API key\n KIMI_API_KEY - Kimi For Coding API key\n CLOUDFLARE_API_KEY - Cloudflare API token (Workers AI and AI Gateway)\n CLOUDFLARE_ACCOUNT_ID - Cloudflare account id (required for both)\n CLOUDFLARE_GATEWAY_ID - Cloudflare AI Gateway slug (required for AI Gateway)\n QWEN_TOKEN_PLAN_API_KEY - Qwen Token Plan API key (international region)\n QWEN_TOKEN_PLAN_CN_API_KEY - Qwen Token Plan API key (China region)\n XIAOMI_API_KEY - Xiaomi MiMo API key (api.xiaomimimo.com billing)\n XIAOMI_TOKEN_PLAN_CN_API_KEY - Xiaomi MiMo Token Plan API key (China region)\n XIAOMI_TOKEN_PLAN_AMS_API_KEY - Xiaomi MiMo Token Plan API key (Amsterdam region)\n XIAOMI_TOKEN_PLAN_SGP_API_KEY - Xiaomi MiMo Token Plan API key (Singapore region)\n AWS_PROFILE - AWS profile for Amazon Bedrock\n AWS_ACCESS_KEY_ID - AWS access key for Amazon Bedrock\n AWS_SECRET_ACCESS_KEY - AWS secret key for Amazon Bedrock\n AWS_BEARER_TOKEN_BEDROCK - Bedrock API key (bearer token)\n AWS_REGION - AWS region for Amazon Bedrock (e.g., us-east-1)\n ${ENV_AGENT_DIR.padEnd(32)} - Config directory (default: ~/${CONFIG_DIR_NAME}/agent)\n ${ENV_SESSION_DIR.padEnd(32)} - Session storage directory (overridden by --session-dir)\n APEX_CODE_PACKAGE_DIR - Override package directory (for Nix/Guix store paths)\n APEX_CODE_OFFLINE - Disable startup network operations when set to 1/true/yes\n APEX_CODE_SKIP_VERSION_CHECK - Skip the npm prerelease version check\n APEX_CODE_EXPERIMENTAL - Enable experimental features when set to 1\n APEX_CODE_STARTUP_BENCHMARK - Enable startup benchmarking\n APEX_CODE_TIMING - Enable timing diagnostics when set to 1\n APEX_CODE_CLEAR_ON_SHRINK - Clear context on shrink when set to 1\n APEX_CODE_HARDWARE_CURSOR - Show the hardware cursor when set to 1\n APEX_CODE_MODEL_CATALOG_URL - Optional base URL for remote model catalog refreshes\n APEX_CODE_SHARE_VIEWER_URL - Optional base URL for /share preview links\n\n${chalk.bold(\"Built-in Tool Names:\")}\n read - Read file contents\n bash - Execute bash commands\n powershell - Execute PowerShell commands on Windows\n edit - Edit files with find/replace\n write - Write files (creates/overwrites)\n grep - Search file contents (read-only, off by default)\n find - Find files by glob pattern (read-only, off by default)\n ls - List directory contents (read-only, off by default)\n`);\n}\n"]}
package/dist/cli/args.js CHANGED
@@ -4,7 +4,81 @@
4
4
  import chalk from "chalk";
5
5
  import { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, ENV_SESSION_DIR } from "../config.js";
6
6
  import { PERMISSION_MODES } from "../core/permissions/store.js";
7
+ /** The one child-lifecycle subcommand family: `apex-code agent <operation> ...`. */
8
+ export const AGENT_LIFECYCLE_OPERATIONS = ["list", "wait", "send", "resume", "interrupt", "close"];
9
+ export function isAgentLifecycleOperation(value) {
10
+ return AGENT_LIFECYCLE_OPERATIONS.includes(value);
11
+ }
7
12
  const HOST_COMMANDS = new Set(["auth", "config", "install", "remove", "uninstall", "update", "list"]);
13
+ /**
14
+ * Parse the `agent <operation>` subcommand family out of the first positional token.
15
+ *
16
+ * The subcommand lives under `agent` rather than bare top-level verbs because verbs
17
+ * like `list` already name host commands. It is classified as a session-kind command:
18
+ * child lifecycle operations run against a real loaded session (children derive their
19
+ * authority from its permission gate), so they must take the sandboxed path like any
20
+ * other session startup.
21
+ */
22
+ function parseAgentCommand(args) {
23
+ args.messages = args.messages.slice(1);
24
+ if (args.fileArgs.length > 0) {
25
+ args.fileArgs = [];
26
+ args.diagnostics.push({ type: "error", message: '"agent" commands do not accept @file arguments' });
27
+ return;
28
+ }
29
+ const [operation, childId, ...rest] = args.messages;
30
+ args.messages = [];
31
+ const usage = `Valid operations: ${AGENT_LIFECYCLE_OPERATIONS.join(", ")}. A resumable session source is required: --session <path|id> or --continue.`;
32
+ if (operation === undefined) {
33
+ args.diagnostics.push({ type: "error", message: `"agent" requires an operation. ${usage}` });
34
+ return;
35
+ }
36
+ if (!isAgentLifecycleOperation(operation)) {
37
+ args.diagnostics.push({ type: "error", message: `Unknown agent operation "${operation}". ${usage}` });
38
+ return;
39
+ }
40
+ if (operation === "list") {
41
+ if (childId !== undefined) {
42
+ args.diagnostics.push({ type: "error", message: `"agent list" takes no arguments. ${usage}` });
43
+ return;
44
+ }
45
+ args.agent = { operation };
46
+ }
47
+ else if (operation === "send") {
48
+ if (childId === undefined || rest.length === 0) {
49
+ args.diagnostics.push({
50
+ type: "error",
51
+ message: `"agent send" requires a child run id followed by input text. ${usage}`,
52
+ });
53
+ return;
54
+ }
55
+ args.agent = { operation, childId, input: rest.join(" ") };
56
+ }
57
+ else if (operation === "resume") {
58
+ if (childId === undefined) {
59
+ args.diagnostics.push({ type: "error", message: `"agent resume" requires a child run id. ${usage}` });
60
+ return;
61
+ }
62
+ args.agent = rest.length > 0 ? { operation, childId, input: rest.join(" ") } : { operation, childId };
63
+ }
64
+ else {
65
+ if (childId === undefined) {
66
+ args.diagnostics.push({ type: "error", message: `"agent ${operation}" requires a child run id. ${usage}` });
67
+ return;
68
+ }
69
+ if (rest.length > 0) {
70
+ args.diagnostics.push({ type: "error", message: `"agent ${operation}" takes only a child run id. ${usage}` });
71
+ return;
72
+ }
73
+ args.agent = { operation, childId };
74
+ }
75
+ if (args.session === undefined && args.continue !== true) {
76
+ args.diagnostics.push({
77
+ type: "error",
78
+ message: `"agent ${operation}" requires a resumable session source: --session <path|id> or --continue.`,
79
+ });
80
+ }
81
+ }
8
82
  /** Parse argv once, then classify startup behavior from the resulting values. */
9
83
  export function parseCliCommand(argv) {
10
84
  const args = parseArgs(argv);
@@ -13,6 +87,9 @@ export function parseCliCommand(argv) {
13
87
  if (args.help || args.version || args.export !== undefined || args.listModels !== undefined) {
14
88
  return { kind: "metadata", args };
15
89
  }
90
+ if (args.messages[0] === "agent") {
91
+ parseAgentCommand(args);
92
+ }
16
93
  return { kind: "session", args };
17
94
  }
18
95
  const VALID_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
@@ -335,6 +412,9 @@ ${chalk.bold("Commands:")}
335
412
  ${APP_NAME} uninstall <source> [-l] Alias for remove
336
413
  ${APP_NAME} update [source|self|pi] Update Apex Code, extensions, or model catalogs
337
414
  ${APP_NAME} list List installed extensions from settings
415
+ ${APP_NAME} agent <operation> ... Child run lifecycle: list | wait | send | resume | interrupt | close
416
+ Requires --session <path|id> or --continue; needs a permission
417
+ mode like any non-interactive session. Prints JSON with --mode json
338
418
  ${APP_NAME} config [-l] Open TUI to enable/disable package resources (Tab switches scope)
339
419
  ${APP_NAME} auth <command> Print credentials or check provider readiness
340
420
  ${APP_NAME} mcp auth <server> Authorize an MCP server that requires OAuth