@gajae-code/coding-agent 0.18.5 → 0.18.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 (91) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/dist/types/cli-commands.d.ts +10 -0
  3. package/dist/types/cli-ordinary.d.ts +13 -0
  4. package/dist/types/cli.d.ts +12 -3
  5. package/dist/types/commands/contribution-prep.d.ts +0 -3
  6. package/dist/types/commands/sdk.d.ts +3 -0
  7. package/dist/types/commands/update.d.ts +1 -0
  8. package/dist/types/config/model-profile-activation.d.ts +19 -0
  9. package/dist/types/coordinator-mcp/session-reaper.d.ts +5 -0
  10. package/dist/types/edit/modes/replace.d.ts +3 -3
  11. package/dist/types/edit/streaming.d.ts +2 -2
  12. package/dist/types/exec/bash-shell-supervisor.d.ts +12 -0
  13. package/dist/types/sdk/broker/discovery.d.ts +8 -0
  14. package/dist/types/sdk/broker/ensure.d.ts +1 -0
  15. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +4 -0
  16. package/dist/types/sdk/broker/runtime.d.ts +1 -1
  17. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  18. package/dist/types/sdk/bus/telegram-daemon.d.ts +1 -0
  19. package/dist/types/sdk/cli/diagnostics-cli.d.ts +18 -0
  20. package/dist/types/sdk/diagnostics/observe-broker.d.ts +185 -0
  21. package/dist/types/sdk/host/control/operations.d.ts +1 -1
  22. package/dist/types/sdk/index.d.ts +1 -0
  23. package/dist/types/sdk/router/session-router.d.ts +2 -0
  24. package/dist/types/sdk/session.d.ts +13 -0
  25. package/dist/types/session/agent-session.d.ts +5 -1
  26. package/dist/types/tools/ask-contract.d.ts +75 -254
  27. package/dist/types/tools/bash.d.ts +1 -1
  28. package/package.json +7 -7
  29. package/scripts/build-sdk-package-smoke.ts +5 -0
  30. package/src/cli/public-command-entry.ts +5 -0
  31. package/src/cli/ssh-cli.ts +6 -3
  32. package/src/cli/web-search-cli.ts +9 -3
  33. package/src/cli-commands.ts +14 -0
  34. package/src/cli-ordinary.ts +197 -0
  35. package/src/cli.ts +25 -182
  36. package/src/commands/contribution-prep.ts +1 -3
  37. package/src/commands/sdk.ts +59 -0
  38. package/src/commands/update.ts +15 -1
  39. package/src/config/file-lock.ts +91 -2
  40. package/src/config/model-profile-activation.ts +70 -4
  41. package/src/config/model-profile-contract.ts +4 -1
  42. package/src/config/model-profiles.ts +23 -31
  43. package/src/config/model-resolver.ts +9 -1
  44. package/src/coordinator-mcp/event-webhook.ts +19 -14
  45. package/src/coordinator-mcp/policy.ts +14 -4
  46. package/src/coordinator-mcp/server.ts +142 -7
  47. package/src/coordinator-mcp/session-reaper.ts +9 -1
  48. package/src/defaults/gjc/skills/deep-interview/SKILL.md +1 -1
  49. package/src/edit/modes/replace.ts +6 -6
  50. package/src/edit/streaming.ts +15 -15
  51. package/src/exec/bash-shell-supervisor.ts +60 -3
  52. package/src/internal-urls/docs-index.generated.ts +10 -9
  53. package/src/memories/index.ts +8 -2
  54. package/src/modes/acp/acp-agent.ts +649 -367
  55. package/src/modes/components/tool-execution.ts +1 -1
  56. package/src/prompts/tools/ask.md +2 -0
  57. package/src/sdk/broker/broker.ts +46 -0
  58. package/src/sdk/broker/daemon-entry.ts +67 -6
  59. package/src/sdk/broker/discovery.ts +8 -0
  60. package/src/sdk/broker/ensure.ts +156 -20
  61. package/src/sdk/broker/lifecycle-ledger.ts +110 -12
  62. package/src/sdk/broker/lifecycle.ts +225 -341
  63. package/src/sdk/broker/runtime.ts +5 -1
  64. package/src/sdk/broker/transport.ts +5 -1
  65. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  66. package/src/sdk/bus/telegram-daemon-control.ts +15 -12
  67. package/src/sdk/bus/telegram-daemon.ts +34 -1
  68. package/src/sdk/cli/diagnostics-cli.ts +247 -0
  69. package/src/sdk/diagnostics/observe-broker.ts +654 -0
  70. package/src/sdk/host/control/dispatch.ts +52 -4
  71. package/src/sdk/host/control/operations.ts +1 -1
  72. package/src/sdk/host/session-runtime.test.ts +40 -2
  73. package/src/sdk/host/session-runtime.ts +13 -5
  74. package/src/sdk/index.ts +1 -0
  75. package/src/sdk/lifecycle-session.ts +1 -0
  76. package/src/sdk/protocol/operation-registry.ts +1 -1
  77. package/src/sdk/router/session-router.ts +7 -1
  78. package/src/sdk/session.ts +37 -8
  79. package/src/session/agent-session.ts +114 -39
  80. package/src/session/blob-store.ts +78 -33
  81. package/src/session/internal/managed-session-storage.ts +96 -3
  82. package/src/setup/hermes/templates/operator-instructions.v1.md +19 -1
  83. package/src/setup/hermes-setup.ts +4 -1
  84. package/src/slash-commands/builtin-registry.ts +8 -5
  85. package/src/tools/ask-contract.test.ts +76 -1
  86. package/src/tools/ask-contract.ts +57 -6
  87. package/src/tools/ask.ts +16 -7
  88. package/src/tools/bash.ts +38 -29
  89. package/src/tools/descriptors.test.ts +29 -0
  90. package/src/tools/tool-catalog.generated.ts +7 -4
  91. package/src/web/search/index.ts +2 -2
@@ -0,0 +1,197 @@
1
+ /** Ordinary CLI graph: everything the inert entry must not load eagerly.
2
+ *
3
+ * This module owns the effectful bootstrap (startup timing, stderr drainer,
4
+ * bash-shell worker protocol) plus the unchanged ordinary routing order:
5
+ * bash-shell workers -> darwin malloc re-exec -> internal smoke -> tmux owner
6
+ * isolation -> managed-owner supervisor/admission/recovery -> private sdk
7
+ * stderr drainer -> public family dispatch -> community app -> doctor worker /
8
+ * probe / cli -> full registry. `cli.ts` imports it lazily, only after argv has
9
+ * been proven not to be a `sdk diagnostics` observation. */
10
+
11
+ import { APP_NAME, VERSION } from "@gajae-code/utils/cli-metadata";
12
+ import { startTiming } from "@gajae-code/utils/logger";
13
+ import { commands } from "./cli-commands";
14
+ import {
15
+ BASH_SHELL_RUNTIME_ARG,
16
+ BASH_SHELL_SUPERVISOR_ARG,
17
+ BASH_SHELL_WORKER_ARG,
18
+ } from "./exec/bash-shell-worker-protocol";
19
+ import { runSdkStderrDrainerFromArgv } from "./sdk/broker/stderr-drainer";
20
+
21
+ export { commands };
22
+
23
+ const MANAGED_OWNER_SUPERVISOR_ARG = "--internal-managed-owner-supervisor";
24
+ const MANAGED_OWNER_CHILD_TOKEN_ENV = "GJC_MANAGED_OWNER_CHILD_TOKEN";
25
+ const TMUX_OWNER_ISOLATION_ARG = "--internal-tmux-owner-isolation";
26
+
27
+ // Anchor startup timing before the heavy CLI module graph is loaded so the
28
+ // printed tree includes runtime/bootstrap costs as well as dispatch work.
29
+ if (process.env.GJC_TIMING || process.env.PI_TIMING) {
30
+ startTiming();
31
+ }
32
+
33
+ async function installRuntimeGlobals(writeNoFileWarning?: (text: string) => void): Promise<void> {
34
+ // fetch() deliberately stays on HTTP/1.1. Bun's HTTP/2 client (per-request
35
+ // `protocol: "http2"`) wedges a pooled connection while uploading large
36
+ // request bodies (~300KB): every later request on it waits forever for
37
+ // response headers. Do not re-enable HTTP/2 without re-running that probe.
38
+
39
+ const { warnIfMacOSNoFileLimitTooLow } = await import("./cli/nofile-limit");
40
+ warnIfMacOSNoFileLimitTooLow({ writeStderr: writeNoFileWarning });
41
+
42
+ // Secondary in-process scrub of the macOS malloc-stack-logging vars. The real
43
+ // boundary is the darwin re-exec guard at the top of runOrdinaryCli(): Bun snapshots
44
+ // the spawn-default environment at startup, so deleting these here does NOT clean the
45
+ // env children inherit by default — it only tidies `process.env` for code that
46
+ // reads it directly. Kept as belt-and-braces for the rare re-exec-unavailable
47
+ // fallback; managed spawns already use filterProcessEnv and the native PTY lane
48
+ // strips them independently.
49
+ delete process.env.MallocStackLogging;
50
+ delete process.env.MallocStackLoggingNoCompact;
51
+ }
52
+
53
+ async function dispatchPublicFamily(argv: string[]): Promise<void> {
54
+ const family = argv[0];
55
+ if (family !== "sdk" && family !== "daemon") return;
56
+ const { dispatchPublicCommand } = await import("./cli/public-command-entry");
57
+ const load = commands.find(entry => entry.name === family)!.load;
58
+ await dispatchPublicCommand(argv.slice(1), {
59
+ bin: APP_NAME,
60
+ version: VERSION,
61
+ command: family,
62
+ load,
63
+ setup: report => installRuntimeGlobals(text => report({ code: "macos_nofile_limit_low", successStderr: text })),
64
+ });
65
+ }
66
+
67
+ function isDoctorArgv(argv: readonly string[]): boolean {
68
+ return argv[0] === "doctor";
69
+ }
70
+
71
+ async function runDoctor(argv: string[]): Promise<void> {
72
+ const { runDoctorCli } = await import("./cli/doctor-cli");
73
+ await runDoctorCli(argv.slice(1));
74
+ }
75
+
76
+ /** Run every non-diagnostics command with the original admission order. */
77
+ export async function runOrdinaryCli(argv: string[]): Promise<void> {
78
+ if (argv.length === 1 && argv[0] === BASH_SHELL_WORKER_ARG) {
79
+ const { runBashShellGuardian } = await import("./exec/bash-shell-guardian");
80
+ await runBashShellGuardian();
81
+ return;
82
+ }
83
+ if (argv.length === 1 && argv[0] === BASH_SHELL_SUPERVISOR_ARG) {
84
+ const { runBashShellSupervisor } = await import("./exec/bash-shell-supervisor");
85
+ await runBashShellSupervisor();
86
+ return;
87
+ }
88
+ if (argv.length === 1 && argv[0] === BASH_SHELL_RUNTIME_ARG) {
89
+ const { runBashShellWorker } = await import("./exec/bash-shell-worker");
90
+ await runBashShellWorker();
91
+ return;
92
+ }
93
+ if (
94
+ process.platform === "darwin" &&
95
+ process.env.GJC_MALLOC_ENV_REEXEC === undefined &&
96
+ (process.env.MallocStackLogging !== undefined || process.env.MallocStackLoggingNoCompact !== undefined)
97
+ ) {
98
+ const { reexecWithScrubbedMallocEnv } = await import("./cli/malloc-env-guard");
99
+ const code = await reexecWithScrubbedMallocEnv();
100
+ if (code !== null) {
101
+ process.exitCode = code;
102
+ return;
103
+ }
104
+ }
105
+ if (argv.length === 3 && argv[0] === "internal" && argv[1] === "memory-guard-native-smoke" && argv[2] === "--json") {
106
+ const { runMemoryGuardNativeSmoke } = await import("./cli/native-smoke");
107
+ await runMemoryGuardNativeSmoke();
108
+ return;
109
+ }
110
+ if (argv.length === 1 && argv[0] === TMUX_OWNER_ISOLATION_ARG) {
111
+ const { runTmuxOwnerIsolationCliFromStdin } = await import("./gjc-runtime/tmux-owner-isolation-cli");
112
+ await runTmuxOwnerIsolationCliFromStdin();
113
+ return;
114
+ }
115
+ if (argv.length === 1 && argv[0] === MANAGED_OWNER_SUPERVISOR_ARG) {
116
+ const { runManagedOwnerSupervisor } = await import("./gjc-runtime/managed-owner-supervisor");
117
+ await runManagedOwnerSupervisor();
118
+ return;
119
+ }
120
+ if (process.env[MANAGED_OWNER_CHILD_TOKEN_ENV] !== undefined) {
121
+ const { admitManagedOwnerBeforeCli, completeManagedOwnerRecovery } = await import(
122
+ "./gjc-runtime/managed-owner-admission"
123
+ );
124
+ const admission = await admitManagedOwnerBeforeCli();
125
+ if (admission.kind === "blocked") return;
126
+ if (admission.kind === "recovery") {
127
+ await completeManagedOwnerRecovery(admission.context);
128
+ return;
129
+ }
130
+ }
131
+ if (argv[0] === "sdk" && argv[1] === "stderr-drain-internal") {
132
+ // Private lifecycle stderr drainer: must stay ahead of the public sdk family
133
+ // dispatcher, which would otherwise reject the private argv as a usage error.
134
+ try {
135
+ await runSdkStderrDrainerFromArgv(argv.slice(2));
136
+ } catch {
137
+ process.stderr.write("gjc sdk: invalid internal stderr drainer invocation\n");
138
+ process.exitCode = 2;
139
+ }
140
+ return;
141
+ }
142
+ if (argv[0] === "sdk" || argv[0] === "daemon") {
143
+ await dispatchPublicFamily(argv);
144
+ return;
145
+ }
146
+ if (argv.length === 1 && argv[0] === "--supports-macos-community-app") {
147
+ process.stdout.write("macos-community-app-offer\n");
148
+ return;
149
+ }
150
+ if (argv.length === 1 && argv[0] === "--internal-macos-community-app-offer") {
151
+ try {
152
+ const { offerMacosCommunityApp } = await import("./cli/macos-community-app");
153
+ await offerMacosCommunityApp({ log: message => process.stderr.write(`${message}\n`) });
154
+ } catch {
155
+ const { COMMUNITY_APP_REPOSITORY } = await import("./cli/macos-community-app");
156
+ process.stderr.write(
157
+ `Optional community app offer failed; GJC remains installed. https://github.com/${COMMUNITY_APP_REPOSITORY}\n`,
158
+ );
159
+ }
160
+ return;
161
+ }
162
+ if (argv[0] === "--internal-doctor-worker") {
163
+ // Non-forgeable route: reachable only with the exact per-spawn token env var
164
+ // AND a non-TTY stdin (isRoutableDoctorWorkerInvocation), so a user's own
165
+ // interactive terminal can never land on the worker's confirmation-refusal
166
+ // path merely by passing this argv marker.
167
+ const { isRoutableDoctorWorkerInvocation, runDoctorWorker } = await import("./cli/doctor-worker");
168
+ if (argv.length !== 1 || !isRoutableDoctorWorkerInvocation(process.env, process.stdin.isTTY)) {
169
+ process.stderr.write("gjc doctor: invalid internal worker invocation\n");
170
+ process.exitCode = 2;
171
+ return;
172
+ }
173
+ await runDoctorWorker();
174
+ return;
175
+ }
176
+ if (argv[0] === "--internal-doctor-probe") {
177
+ if (argv.length !== 2 || (argv[1] !== "native" && argv[1] !== "projection")) {
178
+ process.stderr.write("gjc doctor: invalid internal probe invocation\n");
179
+ process.exitCode = 2;
180
+ return;
181
+ }
182
+ try {
183
+ const { runDoctorProbe } = await import("./cli/doctor/probe");
184
+ await runDoctorProbe(argv[1]);
185
+ } catch {
186
+ process.stderr.write("gjc doctor: internal probe unavailable\n");
187
+ process.exitCode = 3;
188
+ }
189
+ return;
190
+ }
191
+ if (isDoctorArgv(argv)) {
192
+ await runDoctor(argv);
193
+ return;
194
+ }
195
+ const { runCliAfterAdmission } = await import("./cli-main");
196
+ await runCliAfterAdmission(argv);
197
+ }
package/src/cli.ts CHANGED
@@ -1,26 +1,20 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import type { CommandEntry } from "@gajae-code/utils/cli";
4
- /** Lightweight CLI bootstrap. Heavy command registration is loaded only after
5
- * security admission; `gjc doctor` stays reachable when normal startup breaks. */
6
- import { APP_NAME, formatBunRuntimeError, MIN_BUN_VERSION, VERSION } from "@gajae-code/utils/dirs";
7
- import { startTiming } from "@gajae-code/utils/logger";
8
- import {
9
- BASH_SHELL_RUNTIME_ARG,
10
- BASH_SHELL_SUPERVISOR_ARG,
11
- BASH_SHELL_WORKER_ARG,
12
- } from "./exec/bash-shell-worker-protocol";
13
- import { runSdkStderrDrainerFromArgv } from "./sdk/broker/stderr-drainer";
14
-
15
- const MANAGED_OWNER_SUPERVISOR_ARG = "--internal-managed-owner-supervisor";
16
- const MANAGED_OWNER_CHILD_TOKEN_ENV = "GJC_MANAGED_OWNER_CHILD_TOKEN";
17
- const TMUX_OWNER_ISOLATION_ARG = "--internal-tmux-owner-isolation";
18
-
19
- // Anchor startup timing before the heavy CLI module graph is loaded so the
20
- // printed tree includes runtime/bootstrap costs as well as dispatch work.
21
- if (process.env.GJC_TIMING || process.env.PI_TIMING) {
22
- startTiming();
23
- }
3
+ /** Inert CLI entry.
4
+ *
5
+ * `bin/gjc.js` imports THIS module, so anything statically imported here runs
6
+ * before argv is inspected. Keep it to pure metadata: the read-only
7
+ * `sdk diagnostics` observation route must not be able to resolve directories,
8
+ * consult NSS for a missing/ambiguous HOME, load the native addon, install
9
+ * runtime globals, re-exec for malloc env vars, run managed-owner admission or
10
+ * recovery, or touch the error-evidence store. Everything effectful lives in
11
+ * `./cli-ordinary`, which is imported lazily for every other command with its
12
+ * original ordering and admission semantics. */
13
+
14
+ import { APP_NAME, formatBunRuntimeError, MIN_BUN_VERSION } from "@gajae-code/utils/cli-metadata";
15
+ import { commands } from "./cli-commands";
16
+
17
+ export { commands };
24
18
 
25
19
  if (Bun.semver.order(Bun.version, MIN_BUN_VERSION) < 0) {
26
20
  process.stderr.write(
@@ -30,175 +24,24 @@ if (Bun.semver.order(Bun.version, MIN_BUN_VERSION) < 0) {
30
24
  }
31
25
  process.title = APP_NAME;
32
26
 
33
- /** Public-family hooks kept available for private-worker tests without loading the full registry. */
34
- export const commands: CommandEntry[] = [
35
- { name: "sdk", load: () => import("./commands/sdk").then(module => module.default) },
36
- { name: "daemon", load: () => import("./commands/daemon").then(module => module.default) },
37
- ];
38
-
39
- async function installRuntimeGlobals(writeNoFileWarning?: (text: string) => void): Promise<void> {
40
- // fetch() deliberately stays on HTTP/1.1. Bun's HTTP/2 client (per-request
41
- // `protocol: "http2"`) wedges a pooled connection while uploading large
42
- // request bodies (~300KB): every later request on it waits forever for
43
- // response headers. Do not re-enable HTTP/2 without re-running that probe.
44
- const { warnIfMacOSNoFileLimitTooLow } = await import("./cli/nofile-limit");
45
- warnIfMacOSNoFileLimitTooLow({ writeStderr: writeNoFileWarning });
46
-
47
- // Secondary in-process scrub of the macOS malloc-stack-logging vars. The real
48
- // boundary is the darwin re-exec guard at the top of runCli(): Bun snapshots the
49
- // spawn-default environment at startup, so deleting these here does NOT clean the
50
- // env children inherit by default — it only tidies `process.env` for code that
51
- // reads it directly. Kept as belt-and-braces for the rare re-exec-unavailable
52
- // fallback; managed spawns already use filterProcessEnv and the native PTY lane
53
- // strips them independently.
54
- delete process.env.MallocStackLogging;
55
- delete process.env.MallocStackLoggingNoCompact;
56
- }
57
-
58
- async function dispatchPublicFamily(argv: string[]): Promise<void> {
59
- const family = argv[0];
60
- if (family !== "sdk" && family !== "daemon") return;
61
- const { dispatchPublicCommand } = await import("./cli/public-command-entry");
62
- const load = commands.find(entry => entry.name === family)!.load;
63
- await dispatchPublicCommand(argv.slice(1), {
64
- bin: APP_NAME,
65
- version: VERSION,
66
- command: family,
67
- load,
68
- setup: report => installRuntimeGlobals(text => report({ code: "macos_nofile_limit_low", successStderr: text })),
69
- });
70
- }
71
-
72
- function isDoctorArgv(argv: readonly string[]): boolean {
73
- return argv[0] === "doctor";
74
- }
75
-
76
- async function runDoctor(argv: string[]): Promise<void> {
77
- const { runDoctorCli } = await import("./cli/doctor-cli");
78
- await runDoctorCli(argv.slice(1));
79
- }
80
-
81
27
  /** Run the CLI with argv excluding process.argv prefix. */
82
28
  export async function runCli(argv: string[]): Promise<void> {
83
- if (argv.length === 1 && argv[0] === BASH_SHELL_WORKER_ARG) {
84
- const { runBashShellGuardian } = await import("./exec/bash-shell-guardian");
85
- await runBashShellGuardian();
86
- return;
87
- }
88
- if (argv.length === 1 && argv[0] === BASH_SHELL_SUPERVISOR_ARG) {
89
- const { runBashShellSupervisor } = await import("./exec/bash-shell-supervisor");
90
- await runBashShellSupervisor();
91
- return;
92
- }
93
- if (argv.length === 1 && argv[0] === BASH_SHELL_RUNTIME_ARG) {
94
- const { runBashShellWorker } = await import("./exec/bash-shell-worker");
95
- await runBashShellWorker();
96
- return;
97
- }
98
- if (
99
- process.platform === "darwin" &&
100
- process.env.GJC_MALLOC_ENV_REEXEC === undefined &&
101
- (process.env.MallocStackLogging !== undefined || process.env.MallocStackLoggingNoCompact !== undefined)
102
- ) {
103
- const { reexecWithScrubbedMallocEnv } = await import("./cli/malloc-env-guard");
104
- const code = await reexecWithScrubbedMallocEnv();
105
- if (code !== null) {
106
- process.exitCode = code;
107
- return;
108
- }
109
- }
110
- if (argv.length === 3 && argv[0] === "internal" && argv[1] === "memory-guard-native-smoke" && argv[2] === "--json") {
111
- const { runMemoryGuardNativeSmoke } = await import("./cli/native-smoke");
112
- await runMemoryGuardNativeSmoke();
113
- return;
114
- }
115
- if (argv.length === 1 && argv[0] === TMUX_OWNER_ISOLATION_ARG) {
116
- const { runTmuxOwnerIsolationCliFromStdin } = await import("./gjc-runtime/tmux-owner-isolation-cli");
117
- await runTmuxOwnerIsolationCliFromStdin();
118
- return;
119
- }
120
- if (argv.length === 1 && argv[0] === MANAGED_OWNER_SUPERVISOR_ARG) {
121
- const { runManagedOwnerSupervisor } = await import("./gjc-runtime/managed-owner-supervisor");
122
- await runManagedOwnerSupervisor();
123
- return;
124
- }
125
- if (process.env[MANAGED_OWNER_CHILD_TOKEN_ENV] !== undefined) {
126
- const { admitManagedOwnerBeforeCli, completeManagedOwnerRecovery } = await import(
127
- "./gjc-runtime/managed-owner-admission"
128
- );
129
- const admission = await admitManagedOwnerBeforeCli();
130
- if (admission.kind === "blocked") return;
131
- if (admission.kind === "recovery") {
132
- await completeManagedOwnerRecovery(admission.context);
133
- return;
134
- }
135
- }
136
- if (argv[0] === "sdk" && argv[1] === "stderr-drain-internal") {
137
- // Private lifecycle stderr drainer: must stay ahead of the public sdk family
138
- // dispatcher, which would otherwise reject the private argv as a usage error.
29
+ // Exact-token diagnostics selector, ahead of every effectful branch. A private
30
+ // worker marker AFTER this prefix is a diagnostics usage error, never a worker
31
+ // dispatch; a private marker BEFORE it is not a diagnostics invocation at all
32
+ // and keeps its ordinary admission below.
33
+ if (argv[0] === "sdk" && argv[1] === "diagnostics") {
139
34
  try {
140
- await runSdkStderrDrainerFromArgv(argv.slice(2));
35
+ const { runDiagnosticsCli } = await import("./sdk/cli/diagnostics-cli");
36
+ await runDiagnosticsCli(argv.slice(2));
141
37
  } catch {
142
- process.stderr.write("gjc sdk: invalid internal stderr drainer invocation\n");
38
+ process.stderr.write("gjc sdk diagnostics: observation unavailable\n");
143
39
  process.exitCode = 2;
144
40
  }
145
41
  return;
146
42
  }
147
- if (argv[0] === "sdk" || argv[0] === "daemon") {
148
- await dispatchPublicFamily(argv);
149
- return;
150
- }
151
- if (argv.length === 1 && argv[0] === "--supports-macos-community-app") {
152
- process.stdout.write("macos-community-app-offer\n");
153
- return;
154
- }
155
- if (argv.length === 1 && argv[0] === "--internal-macos-community-app-offer") {
156
- try {
157
- const { offerMacosCommunityApp } = await import("./cli/macos-community-app");
158
- await offerMacosCommunityApp({ log: message => process.stderr.write(`${message}\n`) });
159
- } catch {
160
- const { COMMUNITY_APP_REPOSITORY } = await import("./cli/macos-community-app");
161
- process.stderr.write(
162
- `Optional community app offer failed; GJC remains installed. https://github.com/${COMMUNITY_APP_REPOSITORY}\n`,
163
- );
164
- }
165
- return;
166
- }
167
- if (argv[0] === "--internal-doctor-worker") {
168
- // Non-forgeable route: reachable only with the exact per-spawn token env var
169
- // AND a non-TTY stdin (isRoutableDoctorWorkerInvocation), so a user's own
170
- // interactive terminal can never land on the worker's confirmation-refusal
171
- // path merely by passing this argv marker.
172
- const { isRoutableDoctorWorkerInvocation, runDoctorWorker } = await import("./cli/doctor-worker");
173
- if (argv.length !== 1 || !isRoutableDoctorWorkerInvocation(process.env, process.stdin.isTTY)) {
174
- process.stderr.write("gjc doctor: invalid internal worker invocation\n");
175
- process.exitCode = 2;
176
- return;
177
- }
178
- await runDoctorWorker();
179
- return;
180
- }
181
- if (argv[0] === "--internal-doctor-probe") {
182
- if (argv.length !== 2 || (argv[1] !== "native" && argv[1] !== "projection")) {
183
- process.stderr.write("gjc doctor: invalid internal probe invocation\n");
184
- process.exitCode = 2;
185
- return;
186
- }
187
- try {
188
- const { runDoctorProbe } = await import("./cli/doctor/probe");
189
- await runDoctorProbe(argv[1]);
190
- } catch {
191
- process.stderr.write("gjc doctor: internal probe unavailable\n");
192
- process.exitCode = 3;
193
- }
194
- return;
195
- }
196
- if (isDoctorArgv(argv)) {
197
- await runDoctor(argv);
198
- return;
199
- }
200
- const { runCliAfterAdmission } = await import("./cli-main");
201
- await runCliAfterAdmission(argv);
43
+ const { runOrdinaryCli } = await import("./cli-ordinary");
44
+ await runOrdinaryCli(argv);
202
45
  }
203
46
 
204
47
  if (import.meta.main) await runCli(process.argv.slice(2));
@@ -9,12 +9,11 @@ export default class ContributionPrep extends Command {
9
9
  static strict = false;
10
10
 
11
11
  static flags = {
12
- "no-spawn": Flags.boolean({ description: "Only write artifacts; do not spawn a fresh GJC worker" }),
13
12
  "source-session-id": Flags.string({ description: "Source session id to record in the manifest" }),
14
13
  "artifact-root": Flags.string({ description: "Directory where contribute-pr artifacts are written" }),
15
14
  };
16
15
 
17
- static examples = ["gjc contribute-pr", "gjc contribute-pr --no-spawn"];
16
+ static examples = ["gjc contribute-pr"];
18
17
 
19
18
  async run(): Promise<void> {
20
19
  const { flags } = await this.parse(ContributionPrep);
@@ -27,7 +26,6 @@ export default class ContributionPrep extends Command {
27
26
  messages: [],
28
27
  },
29
28
  {
30
- spawnWorker: !flags["no-spawn"],
31
29
  artifactRoot: flags["artifact-root"],
32
30
  },
33
31
  );
@@ -1,3 +1,4 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
1
2
  import { createHash } from "node:crypto";
2
3
  import * as nodeFs from "node:fs";
3
4
  import * as fs from "node:fs/promises";
@@ -42,6 +43,7 @@ import {
42
43
  writeSessionLifecycleReady,
43
44
  } from "../sdk/broker/lifecycle";
44
45
  import { processIncarnation } from "../sdk/broker/process-incarnation";
46
+ import { resolveSdkInternalSpawnCommand } from "../sdk/broker/runtime";
45
47
  import { writeBrokerStartupFailureMarker } from "../sdk/broker/startup-failure";
46
48
  import { runSdkStderrDrainer } from "../sdk/broker/stderr-drainer";
47
49
  import { renderSdkSearchTable, runSdkSearch, runSdkSessionCli } from "../sdk/cli";
@@ -1441,6 +1443,7 @@ export async function runSessionHost(
1441
1443
 
1442
1444
  export type SdkInternalArgv =
1443
1445
  | { action: "broker-internal"; agentDir: string }
1446
+ | { action: "broker-trampoline-internal"; agentDir: string }
1444
1447
  | { action: "session-host-internal" }
1445
1448
  | { action: "stderr-drain-internal"; logPath: string; maxBytes: number };
1446
1449
 
@@ -1455,6 +1458,14 @@ export function parseSdkInternalArgv(argv: readonly string[]): SdkInternalArgv {
1455
1458
  isSafeSdkInternalAgentDir(argv[2])
1456
1459
  )
1457
1460
  return { action: "broker-internal", agentDir: argv[2] };
1461
+ if (
1462
+ argv[0] === "broker-trampoline-internal" &&
1463
+ argv.length === 3 &&
1464
+ argv[1] === "--agent-dir" &&
1465
+ typeof argv[2] === "string" &&
1466
+ isSafeSdkInternalAgentDir(argv[2])
1467
+ )
1468
+ return { action: "broker-trampoline-internal", agentDir: argv[2] };
1458
1469
  if (
1459
1470
  argv[0] === "stderr-drain-internal" &&
1460
1471
  argv.length === 5 &&
@@ -1494,6 +1505,7 @@ export default class Sdk extends Command {
1494
1505
  async run(): Promise<void> {
1495
1506
  if (
1496
1507
  this.argv[0] !== "broker-internal" &&
1508
+ this.argv[0] !== "broker-trampoline-internal" &&
1497
1509
  this.argv[0] !== "session-host-internal" &&
1498
1510
  this.argv[0] !== "stderr-drain-internal"
1499
1511
  ) {
@@ -1596,6 +1608,53 @@ export default class Sdk extends Command {
1596
1608
  }
1597
1609
 
1598
1610
  const internal = parseSdkInternalArgv(this.argv);
1611
+ if (internal.action === "broker-trampoline-internal") {
1612
+ if (process.platform === "win32") throw new CliParseError("Broker trampoline is unavailable on Windows.");
1613
+ const command = resolveSdkInternalSpawnCommand("broker-internal");
1614
+ let child: ChildProcess;
1615
+ try {
1616
+ child = spawn(command.file, [...command.args, "--agent-dir", internal.agentDir], {
1617
+ detached: true,
1618
+ stdio: ["ignore", "ignore", "inherit"],
1619
+ env: command.env,
1620
+ ...(command.kind === "bun-source" ? { cwd: command.cwd } : {}),
1621
+ });
1622
+ } catch (error) {
1623
+ throw new Error("Broker trampoline could not start broker.", { cause: error });
1624
+ }
1625
+ let spawnError: Error | undefined;
1626
+ child.once("error", error => {
1627
+ spawnError = error;
1628
+ });
1629
+ if (child.pid === undefined) throw new Error("Broker trampoline could not start broker.");
1630
+ const incarnation = processIncarnation(child.pid);
1631
+ if (!incarnation) {
1632
+ try {
1633
+ child.kill("SIGKILL");
1634
+ } catch {
1635
+ // The child may already have exited; either way identity was not established.
1636
+ }
1637
+ throw new Error("Broker trampoline could not observe broker identity.");
1638
+ }
1639
+ if (spawnError) throw new Error("Broker trampoline could not start broker.", { cause: spawnError });
1640
+ const stdoutWrite = Promise.withResolvers<void>();
1641
+ process.stdout.write(`${child.pid}\t${incarnation}\n`, error => {
1642
+ if (error) stdoutWrite.reject(error);
1643
+ else stdoutWrite.resolve();
1644
+ });
1645
+ try {
1646
+ await stdoutWrite.promise;
1647
+ } catch (error) {
1648
+ try {
1649
+ child.kill("SIGKILL");
1650
+ } catch {
1651
+ // The child may already have exited; reporting failure remains authoritative.
1652
+ }
1653
+ throw error;
1654
+ }
1655
+ child.unref();
1656
+ return;
1657
+ }
1599
1658
  if (internal.action === "broker-internal") usePostmortemSignalExitAuthority();
1600
1659
  if (internal.action === "session-host-internal") {
1601
1660
  await runSessionHost();
@@ -13,6 +13,20 @@ import {
13
13
  } from "../config/update-channel";
14
14
  import { initTheme } from "../modes/theme/theme";
15
15
 
16
+ export async function runUpdateRecoveryCommand(
17
+ recover: () => Promise<void> = () => runManagedNotifyRecovery({}),
18
+ ): Promise<void> {
19
+ try {
20
+ await recover();
21
+ } catch (error) {
22
+ const reason = error instanceof Error ? error.message : String(error);
23
+ process.stderr.write(
24
+ `Post-update recovery failed: ${reason}. For each configured notification daemon (telegram, discord, or slack), manually run 'gjc daemon stop <kind> --force' and then 'gjc daemon reload <kind>', then run 'gjc notify recovery'.\n`,
25
+ );
26
+ process.exitCode = 1;
27
+ }
28
+ }
29
+
16
30
  export default class Update extends Command {
17
31
  static description = "Check for and install updates";
18
32
 
@@ -35,7 +49,7 @@ export default class Update extends Command {
35
49
  async run(): Promise<void> {
36
50
  const { args, flags } = await this.parse(Update);
37
51
  if (args.action === "update-recovery") {
38
- await runManagedNotifyRecovery({});
52
+ await runUpdateRecoveryCommand();
39
53
  return;
40
54
  }
41
55
  let channel: UpdateChannel | undefined;