@gajae-code/coding-agent 0.22.2 → 0.22.3

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 (122) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/types/cli/append-system-prompt.d.ts +7 -0
  3. package/dist/types/cli/doctor/session-owners.d.ts +8 -2
  4. package/dist/types/cli/public-command-errors.d.ts +1 -0
  5. package/dist/types/cli/session-picker.d.ts +16 -3
  6. package/dist/types/cli/update-cli.d.ts +0 -2
  7. package/dist/types/cli-ordinary.d.ts +1 -1
  8. package/dist/types/commands/sdk.d.ts +2 -0
  9. package/dist/types/config/machine-identity.d.ts +11 -0
  10. package/dist/types/config/model-registry.d.ts +9 -0
  11. package/dist/types/config/settings-schema.d.ts +84 -4
  12. package/dist/types/lsp/client.d.ts +9 -0
  13. package/dist/types/lsp/types.d.ts +2 -0
  14. package/dist/types/main.d.ts +40 -3
  15. package/dist/types/modes/components/session-held-warning.d.ts +27 -0
  16. package/dist/types/modes/components/session-selector.d.ts +32 -1
  17. package/dist/types/modes/controllers/selector-controller.d.ts +8 -1
  18. package/dist/types/modes/interactive-mode.d.ts +12 -1
  19. package/dist/types/sdk/broker/broker.d.ts +3 -0
  20. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -2
  21. package/dist/types/sdk/broker/lifecycle.d.ts +2 -0
  22. package/dist/types/sdk/broker/session-index.d.ts +11 -0
  23. package/dist/types/sdk/bus/index.d.ts +1 -1
  24. package/dist/types/sdk/host/control/dispatch.d.ts +3 -0
  25. package/dist/types/sdk/host/registration-test-hold.d.ts +7 -0
  26. package/dist/types/sdk/index.d.ts +1 -0
  27. package/dist/types/sdk/lifecycle/service.d.ts +3 -0
  28. package/dist/types/sdk/session-api-key.d.ts +11 -4
  29. package/dist/types/sdk/session-readonly/format.d.ts +7 -0
  30. package/dist/types/sdk/session.d.ts +11 -0
  31. package/dist/types/sdk/startup-capability.d.ts +11 -2
  32. package/dist/types/session/agent-session.d.ts +1 -2
  33. package/dist/types/session/internal/managed-session-storage.d.ts +1 -1
  34. package/dist/types/session/internal/session-claim-set.d.ts +168 -13
  35. package/dist/types/session/session-handover.d.ts +62 -0
  36. package/dist/types/session/session-manager.d.ts +75 -15
  37. package/dist/types/session/session-owner-holder.d.ts +77 -0
  38. package/dist/types/session/session-ownership-mode.d.ts +45 -2
  39. package/dist/types/session/session-ownership.d.ts +25 -29
  40. package/dist/types/session/yield-queue.d.ts +13 -0
  41. package/dist/types/tools/bash.d.ts +7 -0
  42. package/dist/types/tools/browser/deferred-profile-cleanup.d.ts +3 -0
  43. package/dist/types/tools/browser/launch.d.ts +24 -1
  44. package/dist/types/tools/index.d.ts +6 -0
  45. package/dist/types/tools/output-meta.d.ts +17 -11
  46. package/dist/types/tools/tool-result.d.ts +1 -0
  47. package/package.json +9 -7
  48. package/scripts/compile-args.ts +6 -3
  49. package/scripts/run-acp-conformance.ts +36 -10
  50. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  51. package/src/cli/append-system-prompt.ts +34 -0
  52. package/src/cli/auth-broker-cli.ts +5 -1
  53. package/src/cli/doctor/session-owners.ts +8 -2
  54. package/src/cli/public-command-errors.ts +4 -0
  55. package/src/cli/session-picker.ts +57 -7
  56. package/src/cli/update-cli.ts +0 -22
  57. package/src/cli-ordinary.ts +2 -17
  58. package/src/commands/sdk.ts +37 -15
  59. package/src/config/machine-identity.ts +31 -2
  60. package/src/config/model-registry.ts +40 -6
  61. package/src/config/settings-schema.ts +50 -6
  62. package/src/config/settings.ts +65 -3
  63. package/src/gjc-runtime/launch-tmux.ts +4 -1
  64. package/src/internal-urls/docs-index.generated.ts +12 -12
  65. package/src/lsp/client.ts +60 -6
  66. package/src/lsp/index.ts +2 -6
  67. package/src/lsp/types.ts +2 -0
  68. package/src/main.ts +364 -93
  69. package/src/modes/DESIGN.md +36 -0
  70. package/src/modes/acp/acp-agent.ts +215 -31
  71. package/src/modes/components/session-held-warning.ts +62 -0
  72. package/src/modes/components/session-selector.ts +234 -11
  73. package/src/modes/controllers/goal-mode-controller.ts +14 -2
  74. package/src/modes/controllers/selector-controller.ts +192 -3
  75. package/src/modes/interactive-mode.ts +40 -2
  76. package/src/prompts/tools/bash.md +1 -1
  77. package/src/prompts/tools/monitor.md +1 -1
  78. package/src/runtime-mcp/manager.ts +5 -1
  79. package/src/sdk/acp/adapter.ts +2 -0
  80. package/src/sdk/broker/broker.ts +29 -2
  81. package/src/sdk/broker/lifecycle-ledger.ts +9 -7
  82. package/src/sdk/broker/lifecycle.ts +280 -39
  83. package/src/sdk/broker/session-index.ts +24 -0
  84. package/src/sdk/bus/index.ts +1 -0
  85. package/src/sdk/bus/lifecycle-commands.ts +4 -0
  86. package/src/sdk/cli/session-cli.ts +8 -0
  87. package/src/sdk/host/control/dispatch.ts +18 -0
  88. package/src/sdk/host/host.ts +5 -0
  89. package/src/sdk/host/registration-test-hold.ts +51 -0
  90. package/src/sdk/host/session-runtime.test.ts +42 -0
  91. package/src/sdk/index.ts +10 -0
  92. package/src/sdk/lifecycle/service.ts +33 -10
  93. package/src/sdk/prompt-failure.ts +4 -0
  94. package/src/sdk/protocol/operation-registry.ts +7 -1
  95. package/src/sdk/session-api-key.ts +31 -16
  96. package/src/sdk/session-readonly/format.ts +10 -0
  97. package/src/sdk/session-readonly/scope.ts +2 -1
  98. package/src/sdk/session.ts +60 -7
  99. package/src/sdk/startup-capability.ts +27 -2
  100. package/src/session/agent-session.ts +411 -58
  101. package/src/session/internal/managed-session-storage.ts +16 -2
  102. package/src/session/internal/session-claim-set.ts +527 -49
  103. package/src/session/session-handover.ts +283 -0
  104. package/src/session/session-manager.ts +907 -148
  105. package/src/session/session-owner-holder.ts +177 -0
  106. package/src/session/session-ownership-mode.ts +84 -12
  107. package/src/session/session-ownership.ts +115 -89
  108. package/src/session/yield-queue.ts +43 -0
  109. package/src/session-import/provider-service.ts +8 -0
  110. package/src/setup/provider-onboarding.ts +5 -5
  111. package/src/task/executor.ts +2 -0
  112. package/src/tools/bash.ts +10 -0
  113. package/src/tools/browser/deferred-profile-cleanup.ts +20 -0
  114. package/src/tools/browser/launch.ts +133 -14
  115. package/src/tools/browser/registry.ts +72 -19
  116. package/src/tools/index.ts +10 -1
  117. package/src/tools/monitor.ts +267 -29
  118. package/src/tools/output-meta.ts +61 -28
  119. package/src/tools/tool-catalog.generated.ts +2 -2
  120. package/src/tools/tool-result.ts +5 -0
  121. package/dist/types/cli/macos-community-app.d.ts +0 -41
  122. package/src/cli/macos-community-app.ts +0 -1449
@@ -14,9 +14,12 @@ export const compileAutoloadDisableFlags = [
14
14
  "--no-compile-autoload-package-json",
15
15
  ];
16
16
 
17
- const compiledDefineFlags = ['process.env.PI_COMPILED="true"'];
18
- const releaseDefineFlags = [...compiledDefineFlags, 'process.env.GJC_BUILD_CHANNEL="release"'];
19
- const devDefineFlags = [...compiledDefineFlags, 'process.env.GJC_BUILD_CHANNEL="dev"'];
17
+ // `bun build --compile` inlines `process.env.NODE_ENV` as "development" when it is not
18
+ // defined, which made every shipped binary run development/test-only branches. Keep it
19
+ // a runtime read: `Bun.env` is not substituted, so the process environment decides.
20
+ const compiledDefineFlags = ['process.env.PI_COMPILED="true"', "process.env.NODE_ENV=Bun.env.NODE_ENV"];
21
+ export const releaseDefineFlags = [...compiledDefineFlags, 'process.env.GJC_BUILD_CHANNEL="release"'];
22
+ export const devDefineFlags = [...compiledDefineFlags, 'process.env.GJC_BUILD_CHANNEL="dev"'];
20
23
 
21
24
  export const releaseEntrypoints = [
22
25
  "./packages/coding-agent/src/cli.ts",
@@ -51,6 +51,16 @@ export type ConformanceReport = {
51
51
  totals: { cases: number; passed: number; failed: number };
52
52
  };
53
53
 
54
+ /**
55
+ * A HOME for the agent command. Unset, the run gives it a temporary HOME and removes it
56
+ * afterwards, so a local run writes no user state (session owners, broker state) to the
57
+ * caller's real home.
58
+ */
59
+ export const AGENT_HOME_ENV = "GJC_ACP_CONFORMANCE_HOME";
60
+
61
+ /** `home` is the HOME the upstream runner and the agent command it spawns run under. */
62
+ export type RunnerOptions = { command: string[]; cwd: string; sessionCwd?: string; home: string };
63
+
54
64
  export interface RunAcpConformanceOptions {
55
65
  agentCommand: string;
56
66
  reportPath: string;
@@ -59,7 +69,7 @@ export interface RunAcpConformanceOptions {
59
69
  profile?: string;
60
70
  fetchMetadata?: () => Promise<AcpxMetadata>;
61
71
  checkout?: () => Promise<AcpxCheckout>;
62
- runRunner?: (options: { command: string[]; cwd: string; sessionCwd?: string }) => Promise<void>;
72
+ runRunner?: (options: RunnerOptions) => Promise<void>;
63
73
  readReport?: (reportPath: string) => Promise<unknown>;
64
74
  writeReport?: (reportPath: string, report: ConformanceReport) => Promise<void>;
65
75
  }
@@ -138,10 +148,26 @@ export async function runAcpConformance(options: RunAcpConformanceOptions): Prom
138
148
  // A failing run still writes its report. Preserve that matrix as CI evidence before
139
149
  // surfacing the failure, so the uploaded artifact explains what actually broke.
140
150
  let runnerFailure: unknown;
151
+ const callerHomeSetting = process.env[AGENT_HOME_ENV]?.trim();
152
+ // Resolved here: the runner's child runs in the acpx checkout, not the caller's cwd.
153
+ const callerHome = callerHomeSetting ? path.resolve(callerHomeSetting) : undefined;
154
+ const home =
155
+ callerHome ?? (await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "gjc-acp-conformance-home-"))));
141
156
  try {
142
- await (options.runRunner ?? runRunner)({ command, cwd: checkout.root, sessionCwd: options.cwd ?? process.cwd() });
157
+ await (options.runRunner ?? runRunner)({
158
+ command,
159
+ cwd: checkout.root,
160
+ sessionCwd: options.cwd ?? process.cwd(),
161
+ home,
162
+ });
143
163
  } catch (error) {
144
164
  runnerFailure = error;
165
+ } finally {
166
+ // Cleanup must never fail the run: lingering session hosts may still be writing logs here.
167
+ if (!callerHome)
168
+ await fs.rm(home, { recursive: true, force: true, maxRetries: 3 }).catch(error => {
169
+ process.stderr.write(`acp conformance: could not remove the agent HOME ${home}: ${String(error)}\n`);
170
+ });
145
171
  }
146
172
  const upstream = await (options.readReport ?? readReport)(upstreamReportPath).catch(() => undefined);
147
173
  if (runnerFailure !== undefined) {
@@ -233,13 +259,13 @@ async function checkoutAcpxSource(): Promise<AcpxCheckout> {
233
259
  return { root, head: await commandOutput(["git", "rev-parse", "HEAD"], root) };
234
260
  }
235
261
 
236
- async function runRunner(options: { command: string[]; cwd: string; sessionCwd?: string }): Promise<void> {
237
- // The fixture seeds the corpus scratch workspace; the runner only creates it.
238
- await commandOutput(
239
- options.command,
240
- options.cwd,
241
- options.sessionCwd ? { GJC_ACP_CONFORMANCE_CWD: options.sessionCwd } : undefined,
242
- );
262
+ async function runRunner(options: RunnerOptions): Promise<void> {
263
+ await commandOutput(options.command, options.cwd, {
264
+ HOME: options.home,
265
+ USERPROFILE: options.home,
266
+ // The fixture seeds the corpus scratch workspace; the runner only creates it.
267
+ ...(options.sessionCwd ? { GJC_ACP_CONFORMANCE_CWD: options.sessionCwd } : {}),
268
+ });
243
269
  }
244
270
  async function readReport(reportPath: string): Promise<unknown> {
245
271
  return await Bun.file(reportPath).json();
@@ -277,7 +303,7 @@ function parseCli(argv: string[]): RunAcpConformanceOptions {
277
303
  }
278
304
  if (!values.agentCommand || !values.reportPath)
279
305
  throw new Error(
280
- "Usage: conformance:run --agent-command <command> --format json --report <path> [--cwd <path>] [--profile acp-core-v1]",
306
+ `Usage: conformance:run --agent-command <command> --format json --report <path> [--cwd <path>] [--profile acp-core-v1]\nThe agent command runs under a temporary HOME; set ${AGENT_HOME_ENV} to choose one.`,
281
307
  );
282
308
  return values as RunAcpConformanceOptions;
283
309
  }
@@ -1784,6 +1784,8 @@ function forbiddenMachineModule(file: string): string | undefined {
1784
1784
  if (file === "packages/coding-agent/src/modes/acp/acp-event-mapper.ts") return undefined;
1785
1785
  // Import-free error-text helper: it formats operator messages and cannot reach session state.
1786
1786
  if (file === "packages/coding-agent/src/session/operator-error-message.ts") return undefined;
1787
+ // Import-free holder text and error: it names who holds a session and cannot reach the claim machinery.
1788
+ if (file === "packages/coding-agent/src/session/session-owner-holder.ts") return undefined;
1787
1789
  if (file === "packages/coding-agent/src/main.ts" || file === "packages/coding-agent/src/modes/interactive-mode.ts")
1788
1790
  return "process bootstrap/main session host";
1789
1791
  if (file === "packages/coding-agent/src/sdk/session.ts") return "direct session mutation module";
@@ -1,3 +1,8 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as path from "node:path";
3
+
4
+ import { getConfigDirs } from "../config";
5
+
1
6
  export interface AppendSystemPromptCandidate {
2
7
  level: "user" | "project";
3
8
  path: string;
@@ -10,3 +15,32 @@ export function selectAppendSystemPromptFile(candidates: readonly AppendSystemPr
10
15
  }
11
16
  return undefined;
12
17
  }
18
+
19
+ /**
20
+ * Reads a discovered append file. Only regular files are read; a missing, unreadable, or
21
+ * non-regular path (FIFO, socket, directory) yields undefined, never the pathname itself.
22
+ */
23
+ export async function readAppendSystemPromptFile(filePath: string | undefined): Promise<string | undefined> {
24
+ if (!filePath) return undefined;
25
+ try {
26
+ if (!(await fs.stat(filePath)).isFile()) return undefined;
27
+ return await fs.readFile(filePath, "utf8");
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ /** User APPEND_SYSTEM.md only. Repository copies are not appended. */
34
+ export async function discoverAppendSystemPromptFile(): Promise<string | undefined> {
35
+ const probed = await Promise.all(
36
+ getConfigDirs("", { existingOnly: false }).map(async entry => {
37
+ const filePath = path.join(entry.path, "APPEND_SYSTEM.md");
38
+ const exists = await fs.access(filePath).then(
39
+ () => true,
40
+ () => false,
41
+ );
42
+ return exists ? [{ level: entry.level, path: filePath }] : [];
43
+ }),
44
+ );
45
+ return selectAppendSystemPromptFile(probed.flat());
46
+ }
@@ -70,6 +70,7 @@ type AuthBrokerCliErrorCode =
70
70
  | "broker_unavailable"
71
71
  | "credential_import_failed"
72
72
  | "credential_migration_failed"
73
+ | "credential_logout_failed"
73
74
  | "auth_broker_command_failed";
74
75
 
75
76
  function stableErrorForAction(action: AuthBrokerAction): { code: AuthBrokerCliErrorCode; message: string } {
@@ -80,6 +81,8 @@ function stableErrorForAction(action: AuthBrokerAction): { code: AuthBrokerCliEr
80
81
  return { code: "credential_import_failed", message: "Credential import failed." };
81
82
  case "migrate":
82
83
  return { code: "credential_migration_failed", message: "Credential migration failed." };
84
+ case "logout":
85
+ return { code: "credential_logout_failed", message: "Credential logout failed." };
83
86
  default:
84
87
  return { code: "auth_broker_command_failed", message: "Auth broker command failed." };
85
88
  }
@@ -276,6 +279,7 @@ async function runLogout(flags: AuthBrokerCommandArgs["flags"]): Promise<void> {
276
279
  const provider = resolveOAuthStorageProvider(providerArg);
277
280
  const store = await SqliteAuthCredentialStore.open(getAgentDbPath());
278
281
  try {
282
+ // A failed write throws before the success line; runAuthBrokerCommand reports it and sets exit code 1.
279
283
  store.deleteAuthCredentialsForProvider(provider, "logged out by user");
280
284
  process.stdout.write(`Logged out of ${provider}\n`);
281
285
  } finally {
@@ -804,7 +808,7 @@ export async function runAuthBrokerCommand(cmd: AuthBrokerCommandArgs): Promise<
804
808
  }
805
809
  }
806
810
  } catch (error) {
807
- if (cmd.action === "status" || cmd.action === "import" || cmd.action === "migrate") {
811
+ if (cmd.action === "status" || cmd.action === "import" || cmd.action === "migrate" || cmd.action === "logout") {
808
812
  writeCommandFailure(cmd.action, cmd.flags, error);
809
813
  return;
810
814
  }
@@ -12,8 +12,14 @@ import { canonicalDigest } from "./ids";
12
12
  import { collectDoctorProbe, type DoctorProbeResult } from "./probe-client";
13
13
  import type { DoctorCheck } from "./types";
14
14
 
15
- /** Above this many sidecars, gc pruning is not keeping up (design §2.9). */
16
- export const SESSION_OWNER_SIDECAR_LIMIT = 10_000;
15
+ /**
16
+ * Above this many sidecars the doctor warns. Sidecar pruning is not implemented yet, so one empty
17
+ * `.session-owner` file per session ever opened accumulates; they are harmless, and must not be
18
+ * deleted by hand while gjc runs (a deleted sidecar lets a second process lock a new one). 100,000
19
+ * is years of heavy use (about 50 sessions a day for five years), so the warning means an outlier
20
+ * worth reporting, not ordinary use; 10,000 fired within a year for heavy users.
21
+ */
22
+ export const SESSION_OWNER_SIDECAR_LIMIT = 100_000;
17
23
 
18
24
  /** The sidecar count, from `readdir` alone, so it stands even when the lock probe times out. */
19
25
  function sidecarCheck(targetId: string, counts: SessionOwnerEntryCounts | { readonly errno?: string }): DoctorCheck {
@@ -140,6 +140,10 @@ export const PUBLIC_COMMAND_DIAGNOSTICS = {
140
140
  // (a required `sessionPath`, for one), and it is never rendered, so the class is named here.
141
141
  lifecycle_input_refused:
142
142
  "The broker refused the request as invalid input. Correct the request payload and reconcile existing lifecycle state before deciding whether another request is safe.",
143
+ // A resume refused with `live_session` naming a holder (under `enforce`): the holder's name rides
144
+ // in the broker message, which is never rendered.
145
+ lifecycle_session_held:
146
+ "Another gjc process holds this session for writing and has not published an SDK endpoint to attach to, so no session host was launched. Try again with a new idempotency key once that process is ready (the same key replays this answer), or fork the session.",
143
147
  // Fixed text only: the lock path and the broker's own message stay out of the
144
148
  // envelope; `gjc sdk broker run` prints them to its own stderr.
145
149
  broker_cleanup_unverified:
@@ -1,26 +1,74 @@
1
1
  import * as path from "node:path";
2
- import { ProcessTerminal, TUI } from "@gajae-code/tui";
2
+ import { ProcessTerminal, Spacer, TUI } from "@gajae-code/tui";
3
3
  import { pathIsWithin } from "@gajae-code/utils";
4
- import { type SessionSelectionResult, SessionSelectorComponent } from "../modes/components/session-selector";
4
+ import {
5
+ createHeldSessionWarning,
6
+ type HeldSessionChoice,
7
+ type HeldSessionWarningOptions,
8
+ } from "../modes/components/session-held-warning";
9
+ import {
10
+ type HeldSessionCheck,
11
+ type SessionSelectionResult,
12
+ SessionSelectorComponent,
13
+ } from "../modes/components/session-selector";
5
14
  import { type SessionInfo, SessionManager } from "../session/session-manager";
6
- import { FileSessionStorage } from "../session/session-storage";
15
+ import type { SessionHeldError } from "../session/session-ownership";
16
+
17
+ /** The bare picker runs before the process surface is set: its scoped claims name the terminal. */
18
+ const PICKER_OWNERSHIP = { surface: "terminal" } as const;
7
19
 
8
20
  export async function deleteSessionPickerCandidate(sessionPath: string, explicitSessionDir?: string): Promise<void> {
9
21
  if (!explicitSessionDir) {
10
- await SessionManager.deleteManagedCandidate(sessionPath);
22
+ await SessionManager.deleteManagedCandidate(sessionPath, PICKER_OWNERSHIP);
11
23
  return;
12
24
  }
13
25
  const root = path.resolve(explicitSessionDir);
14
26
  const target = path.resolve(sessionPath);
15
27
  if (!pathIsWithin(root, target))
16
28
  throw new Error("Explicit session deletion escaped the configured session directory.");
17
- await new FileSessionStorage().deleteSessionWithArtifacts(target);
29
+ await SessionManager.deleteExplicitCandidate(target, PICKER_OWNERSHIP);
30
+ }
31
+
32
+ /**
33
+ * The held-session warning before the TUI starts (design §3.1), as a one-shot TUI like the picker:
34
+ * resolves once Fork, Continue here or Cancel is chosen and the terminal is handed back.
35
+ */
36
+ export async function promptHeldSession(
37
+ error: SessionHeldError,
38
+ options: HeldSessionWarningOptions = {},
39
+ ): Promise<HeldSessionChoice> {
40
+ const { promise, resolve } = Promise.withResolvers<HeldSessionChoice>();
41
+ const ui = new TUI(new ProcessTerminal());
42
+ let settled = false;
43
+ const warning = createHeldSessionWarning(
44
+ error,
45
+ choice => {
46
+ if (settled) return;
47
+ settled = true;
48
+ // As in `selectSession`: finish the stdin dispatch before detaching, then resolve.
49
+ setImmediate(() => {
50
+ ui.stop();
51
+ resolve(choice);
52
+ });
53
+ },
54
+ options,
55
+ );
56
+ // As the picker does: one blank row first, so the frame starts below the launch's `> ` line.
57
+ ui.addChild(new Spacer(1));
58
+ ui.addChild(warning);
59
+ ui.setFocus(warning);
60
+ ui.start();
61
+ return promise;
18
62
  }
19
63
 
20
- /** Show the session picker and return the user's resume consent intent. */
64
+ /**
65
+ * Show the session picker and return the user's resume consent intent. Under enforce, `held` marks
66
+ * the rows other processes hold and choosing one shows the held-session warning (design §1 row 2).
67
+ */
21
68
  export async function selectSession(
22
69
  sessions: SessionInfo[],
23
70
  explicitSessionDir?: string,
71
+ held?: { readonly sessions: ReadonlyMap<string, SessionHeldError>; readonly check: HeldSessionCheck },
24
72
  ): Promise<SessionSelectionResult> {
25
73
  const { promise, resolve } = Promise.withResolvers<SessionSelectionResult>();
26
74
  const ui = new TUI(new ProcessTerminal());
@@ -49,9 +97,11 @@ export async function selectSession(
49
97
  },
50
98
  SessionManager.inspectSessionTailReadOnly,
51
99
  settle,
52
- (session, starred) => SessionManager.setSessionStarredForPicker(session, starred, explicitSessionDir),
100
+ (session, starred) =>
101
+ SessionManager.setSessionStarredForPicker(session, starred, explicitSessionDir, PICKER_OWNERSHIP),
53
102
  );
54
103
  selector.setOnRequestRender(() => ui.requestRender());
104
+ if (held) selector.setHeldSessions(held.sessions, held.check);
55
105
  ui.addChild(selector);
56
106
  ui.setFocus(selector);
57
107
  ui.start();
@@ -49,7 +49,6 @@ import {
49
49
  toNativeIdentity,
50
50
  updateActivationRecordFile,
51
51
  } from "./install-activation";
52
- import { COMMUNITY_APP_REPOSITORY, offerMacosCommunityApp } from "./macos-community-app";
53
52
  import { runNotifyCommand } from "./notify-cli";
54
53
 
55
54
  const PACKAGE = "@gajae-code/coding-agent";
@@ -1937,7 +1936,6 @@ export interface UpdateCommandDependencies {
1937
1936
  recoverNotifications?: (settings: Settings) => Promise<void>;
1938
1937
  runPostUpdateRecovery?: (runtimePath: string) => Promise<void>;
1939
1938
  platform?: NodeJS.Platform;
1940
- offerMacosCommunityApp?: typeof offerMacosCommunityApp;
1941
1939
  recordTelemetryEvent?: (event: TelemetryEventName, details: TelemetryDetails) => unknown;
1942
1940
  exit?: (code: number) => never;
1943
1941
  }
@@ -1946,24 +1944,6 @@ export type PostUpdateRecoverySpawn = (argv: string[]) => Promise<number>;
1946
1944
  export type PostUpdateRecoverySupportCheck = (runtimePath: string) => Promise<boolean>;
1947
1945
  export type LegacyRecoveryDaemonKinds = () => Promise<NotificationProvider[]>;
1948
1946
 
1949
- async function offerCommunityAppAfterUpdate(deps: UpdateCommandDependencies): Promise<void> {
1950
- const platform = deps.platform ?? process.platform;
1951
- if (platform !== "darwin") return;
1952
- try {
1953
- await (deps.offerMacosCommunityApp ?? offerMacosCommunityApp)({
1954
- platform,
1955
- log: message => {
1956
- process.stderr.write(`${message}\n`);
1957
- },
1958
- });
1959
- } catch (error) {
1960
- const reason = sanitizeVerificationOutput(error instanceof Error ? error.message : String(error));
1961
- process.stderr.write(
1962
- `Optional community app offer failed: ${reason ?? "unknown error"}. GJC remains installed. https://github.com/${COMMUNITY_APP_REPOSITORY}\n`,
1963
- );
1964
- }
1965
- }
1966
-
1967
1947
  /**
1968
1948
  * A complete, non-quarantined provider with provider-level desired intent is a
1969
1949
  * durable managed-notify setup. The global switch is deliberately excluded:
@@ -2292,7 +2272,6 @@ export async function runUpdateCommand(
2292
2272
  }
2293
2273
  record("update_install_started", { channel, installMethod: target.method });
2294
2274
  record("update_install_completed", { channel, result: "installed", installMethod: target.method });
2295
- await offerCommunityAppAfterUpdate(deps);
2296
2275
  return;
2297
2276
  }
2298
2277
  }
@@ -2346,7 +2325,6 @@ export async function runUpdateCommand(
2346
2325
  // refreshes opt-in local definitions, avoiding stale-module daemon control.
2347
2326
  await refreshDefaults();
2348
2327
  record("update_install_completed", { channel, result: "installed", installMethod: target.method });
2349
- await offerCommunityAppAfterUpdate(deps);
2350
2328
  }
2351
2329
 
2352
2330
  /**
@@ -4,7 +4,7 @@
4
4
  * bash-shell worker protocol) plus the unchanged ordinary routing order:
5
5
  * bash-shell workers -> darwin malloc re-exec -> internal smoke -> tmux owner
6
6
  * isolation -> managed-owner supervisor/admission/recovery -> broker hop ->
7
- * private sdk stderr drainer -> public family dispatch -> community app -> doctor worker /
7
+ * private sdk stderr drainer -> public family dispatch -> doctor worker /
8
8
  * probe / cli -> full registry. `cli.ts` imports it lazily, only after argv has
9
9
  * been proven not to be a `sdk diagnostics` observation. */
10
10
 
@@ -148,22 +148,7 @@ export async function runOrdinaryCli(argv: string[]): Promise<void> {
148
148
  await dispatchPublicFamily(argv);
149
149
  return;
150
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
- }
151
+
167
152
  if (argv[0] === "--internal-doctor-worker") {
168
153
  // Non-forgeable route: reachable only with the exact per-spawn token env var
169
154
  // AND a non-TTY stdin (isRoutableDoctorWorkerInvocation), so a user's own
@@ -14,6 +14,7 @@ import { getAgentDir, logger, postmortem } from "@gajae-code/utils";
14
14
  import { CliParseError, Command } from "@gajae-code/utils/cli";
15
15
  import { startupProjectEnvSnapshot } from "@gajae-code/utils/env";
16
16
  import { type ProjectEnvSnapshot, projectEnvSnapshot } from "@gajae-code/utils/env-file";
17
+ import { discoverAppendSystemPromptFile, readAppendSystemPromptFile } from "../cli/append-system-prompt";
17
18
  import type { Args as ParsedArgs } from "../cli/args";
18
19
  import { isSafeSdkInternalAgentDir, scanPublicCommand } from "../cli/public-command-entry";
19
20
  import { PublicCommandFailure } from "../cli/public-command-errors";
@@ -93,6 +94,8 @@ import {
93
94
  import { runSdkServe, SdkServeError } from "../sdk/transport/serve-cli";
94
95
  import { type AgentSession, isSessionDisposalIncompleteError } from "../session/agent-session";
95
96
  import { type CapturedSessionTranscriptSnapshot, SessionManager } from "../session/session-manager";
97
+ import { setSessionOwnerSurface } from "../session/session-ownership";
98
+ import { sessionOwnershipModeFor } from "../session/session-ownership-mode";
96
99
 
97
100
  export async function lifecycleArgs(
98
101
  request: SessionLifecycleLaunchRequest,
@@ -491,6 +494,11 @@ export async function openLifecycleSessionManager(
491
494
  throw new Error("Lifecycle launch body is unsupported; use session.revise for prompt edits.");
492
495
  const parsed = await lifecycleArgs(request, cwd, agentDir);
493
496
  const lifecycleSettings = await Settings.loadForScope({ cwd, agentDir });
497
+ // A broker-launched host claims as `sdk-host`, with the mode from the settings it opens under.
498
+ const ownership = {
499
+ surface: "sdk-host" as const,
500
+ mode: sessionOwnershipModeFor(lifecycleSettings.getGlobal("session.ownership.mode")),
501
+ };
494
502
  let sessionManager: SessionManager | undefined;
495
503
  let result: { parsed: ParsedArgs; sessionManager: SessionManager | undefined } | undefined;
496
504
  let operationError: unknown;
@@ -509,7 +517,7 @@ export async function openLifecycleSessionManager(
509
517
  // Ephemeral sessions keep transcripts in memory only
510
518
  sessionManager = SessionManager.inMemory(cwd);
511
519
  } else {
512
- sessionManager = await createSessionManager(parsed, cwd, lifecycleSettings);
520
+ sessionManager = await createSessionManager(parsed, cwd, lifecycleSettings, ownership.surface);
513
521
  }
514
522
  } else {
515
523
  const snapshot = await captureLifecycleTranscript(request, cwd, agentDir, migrationPolicy);
@@ -520,6 +528,7 @@ export async function openLifecycleSessionManager(
520
528
  undefined,
521
529
  migrationPolicy,
522
530
  lifecycleSettings.get("sessionMemory.mode"),
531
+ ownership,
523
532
  );
524
533
  if (opened.kind === "error")
525
534
  throw new Error("Lifecycle saved session authority changed while the session host opened it.");
@@ -533,6 +542,7 @@ export async function openLifecycleSessionManager(
533
542
  migrationPolicy,
534
543
  lifecycleSettings.get("sessionMemory.mode"),
535
544
  request.sourceEntryId,
545
+ ownership,
536
546
  );
537
547
  if (forked.kind === "error")
538
548
  throw new Error("Lifecycle saved session authority changed while the session host forked it.");
@@ -657,11 +667,14 @@ export async function runSessionHost(
657
667
  initializeLifecycleExtensions?: typeof initializeExtensions;
658
668
  openLifecycleSessionManager?: typeof openLifecycleSessionManager;
659
669
  createLifecycleAgentSession?: typeof createLifecycleAgentSession;
670
+ discoverAppendSystemPromptFile?: typeof discoverAppendSystemPromptFile;
660
671
  writeSessionLifecycleReady?: typeof writeSessionLifecycleReady;
661
672
  writeSessionLifecycleStartupCommit?: typeof writeSessionLifecycleStartupCommit;
662
673
  writeMcpConfig?: (filePath: string, contents: string) => Promise<number>;
663
674
  } = {},
664
675
  ): Promise<void> {
676
+ // Factories this host runs without a decision (`createAgentSession`'s lifecycle create) claim as `sdk-host`.
677
+ setSessionOwnerSurface("sdk-host");
665
678
  const now = timing.now ?? Date.now;
666
679
  const sleep = timing.sleep ?? (async ms => await Bun.sleep(ms));
667
680
  const readIncarnation = timing.processIncarnation ?? processIncarnation;
@@ -670,6 +683,7 @@ export async function runSessionHost(
670
683
  const initializeSessionExtensions = timing.initializeLifecycleExtensions ?? initializeExtensions;
671
684
  const openLifecycleSession = timing.openLifecycleSessionManager ?? openLifecycleSessionManager;
672
685
  const createLifecycleSession = timing.createLifecycleAgentSession ?? createLifecycleAgentSession;
686
+ const discoverAppendPromptFile = timing.discoverAppendSystemPromptFile ?? discoverAppendSystemPromptFile;
673
687
  const writeLifecycleReady = timing.writeSessionLifecycleReady ?? writeSessionLifecycleReady;
674
688
  const writeStartupCommit = timing.writeSessionLifecycleStartupCommit ?? writeSessionLifecycleStartupCommit;
675
689
  const writeMcpConfig = timing.writeMcpConfig ?? ((filePath, contents) => Bun.write(filePath, contents));
@@ -1246,23 +1260,31 @@ export async function runSessionHost(
1246
1260
  mcpStartupTimeoutMs = remaining;
1247
1261
  }
1248
1262
 
1263
+ // User-level APPEND_SYSTEM.md, as the CLI appends it. The read stays inside the startup deadline.
1264
+ const resolvedAppendPrompt = await beforeCutoff(
1265
+ async () => await readAppendSystemPromptFile(await discoverAppendPromptFile()),
1266
+ undefined,
1267
+ { processLocalOnly: true },
1268
+ );
1269
+
1249
1270
  created = await beforeCutoff(
1250
1271
  async () => {
1251
1272
  sessionManagerTransferred = true;
1252
- return await createLifecycleSession(
1253
- {
1254
- cwd,
1255
- agentDir,
1256
- ephemeral: request.ephemeral,
1257
- sessionManager: opened?.sessionManager,
1258
- ...(mcpConfigPath ? { mcpConfigPath, lifecycleMcpOrigin: true } : {}),
1259
- ...(mcpStartupTimeoutMs !== undefined ? { mcpStartupTimeoutMs } : {}),
1260
- ...(request.readiness ? { readiness: request.readiness } : {}),
1261
- ...(request.modelId ? { modelId: request.modelId } : {}),
1262
- lifecycleRequestId: effectMarker,
1263
- },
1264
- startupOwner,
1265
- );
1273
+ const sessionOptions: Parameters<typeof createLifecycleSession>[0] = {
1274
+ cwd,
1275
+ agentDir,
1276
+ ephemeral: request.ephemeral,
1277
+ sessionManager: opened?.sessionManager,
1278
+ ...(mcpConfigPath ? { mcpConfigPath, lifecycleMcpOrigin: true } : {}),
1279
+ ...(mcpStartupTimeoutMs !== undefined ? { mcpStartupTimeoutMs } : {}),
1280
+ ...(request.readiness ? { readiness: request.readiness } : {}),
1281
+ ...(request.modelId ? { modelId: request.modelId } : {}),
1282
+ lifecycleRequestId: effectMarker,
1283
+ };
1284
+ if (resolvedAppendPrompt) {
1285
+ sessionOptions.systemPrompt = defaultPrompt => [...defaultPrompt, resolvedAppendPrompt];
1286
+ }
1287
+ return await createLifecycleSession(sessionOptions, startupOwner);
1266
1288
  },
1267
1289
  async late => {
1268
1290
  if ("failure" in late) {
@@ -35,6 +35,30 @@ export function parseMacPlatformUuid(output: string): string | undefined {
35
35
  : undefined;
36
36
  }
37
37
 
38
+ /**
39
+ * Configuration directory creation failed. Thrown when the config root directory
40
+ * (usually ~/.gjc) cannot be created due to filesystem permissions or other issues.
41
+ * The error includes an operator message explaining the failure and suggesting fixes.
42
+ */
43
+ export class ConfigDirectoryError extends Error {
44
+ readonly code = "config_directory_io";
45
+ readonly errno: string | undefined;
46
+ readonly operatorMessage: string;
47
+
48
+ constructor(directory: string, errno: string | undefined, originalError: unknown) {
49
+ super(`Failed to create config directory: ${directory}`);
50
+ this.name = "ConfigDirectoryError";
51
+ this.errno = errno;
52
+ // Provide a path-free operator message that mentions the environment override
53
+ this.operatorMessage =
54
+ `gjc could not create or write to the configuration directory. ` +
55
+ `Check that your home directory is writable, or set the GJC_CONFIG_DIR environment variable ` +
56
+ `to override the default location. ` +
57
+ `Error: ${errno === "EPERM" || errno === "EACCES" ? "Permission denied" : String(errno ?? originalError)}`;
58
+ this.cause = originalError;
59
+ }
60
+ }
61
+
38
62
  async function loadInstallationSecret(deps: MachineIdentityDeps): Promise<string> {
39
63
  const directory = deps.configRootDir ?? getConfigRootDir();
40
64
  const file = path.join(directory, "machine-identity.secret");
@@ -58,8 +82,13 @@ async function loadInstallationSecret(deps: MachineIdentityDeps): Promise<string
58
82
  await handle.close();
59
83
  }
60
84
  };
61
- await fs.mkdir(directory, { recursive: true, mode: 0o700 });
62
- await fs.chmod(directory, 0o700);
85
+ try {
86
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
87
+ await fs.chmod(directory, 0o700);
88
+ } catch (error: unknown) {
89
+ const errno = (error as { code?: unknown } | undefined)?.code;
90
+ throw new ConfigDirectoryError(directory, typeof errno === "string" ? errno : undefined, error);
91
+ }
63
92
  let unsettledReads = 0;
64
93
  for (;;) {
65
94
  try {
@@ -7867,15 +7867,49 @@ export class ModelRegistry {
7867
7867
  signal: options.signal,
7868
7868
  }),
7869
7869
  );
7870
+ this.#applyProviderAuthHeaders(provider, apiKey);
7871
+ return apiKey;
7872
+ }
7873
+
7874
+ /** Get a provider API key together with the stored row that resolved it, when any. */
7875
+ async getApiKeyForProviderWithCredentialRowId(
7876
+ provider: string,
7877
+ sessionId?: string,
7878
+ baseUrl?: string,
7879
+ options: {
7880
+ credentialSelector?: AuthCredentialSelector;
7881
+ preferredCredentialSelector?: AuthCredentialSelector;
7882
+ signal?: AbortSignal;
7883
+ } = {},
7884
+ ): Promise<{ apiKey: string | undefined; credentialRowId: number | undefined }> {
7885
+ this.#refreshRotatingConfigApiKey(provider);
7886
+ let credentialRowId: number | undefined;
7887
+ const apiKey = await this.#getApiKeyOrNoAuth(provider, async () => {
7888
+ const resolved = await this.authStorage.getApiKeyWithCredentialRowId(provider, sessionId, {
7889
+ baseUrl,
7890
+ credentialSelector: options.credentialSelector,
7891
+ preferredCredentialSelector: options.preferredCredentialSelector,
7892
+ owner: this.#authStorageConfigOwner,
7893
+ signal: options.signal,
7894
+ });
7895
+ credentialRowId = isVllmNoAuthToken(provider, resolved.apiKey) ? undefined : resolved.credentialRowId;
7896
+ return resolved.apiKey;
7897
+ });
7898
+ if (apiKey === kNoAuth) credentialRowId = undefined;
7899
+ this.#applyProviderAuthHeaders(provider, apiKey);
7900
+ return { apiKey, credentialRowId };
7901
+ }
7902
+
7903
+ #applyProviderAuthHeaders(provider: string, apiKey: string | undefined): void {
7870
7904
  if (
7871
- this.#runtimeProviderAuthHeaders.get(provider) === true ||
7872
- this.#customProviderAuthHeaders.get(provider) === true
7905
+ this.#runtimeProviderAuthHeaders.get(provider) !== true &&
7906
+ this.#customProviderAuthHeaders.get(provider) !== true
7873
7907
  ) {
7874
- for (const model of this.#models) {
7875
- if (model.provider === provider) this.#applyEffectiveAuthHeader(model, apiKey);
7876
- }
7908
+ return;
7909
+ }
7910
+ for (const model of this.#models) {
7911
+ if (model.provider === provider) this.#applyEffectiveAuthHeader(model, apiKey);
7877
7912
  }
7878
- return apiKey;
7879
7913
  }
7880
7914
 
7881
7915
  /** Check credential availability without resolving keys or refreshing OAuth tokens. */