@gajae-code/coding-agent 0.22.1 → 0.22.2

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 (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/cli/doctor/probe-types.d.ts +1 -1
  3. package/dist/types/cli/doctor/session-owners-probe.d.ts +7 -0
  4. package/dist/types/cli/doctor/session-owners.d.ts +16 -0
  5. package/dist/types/cli/github-release.d.ts +16 -0
  6. package/dist/types/cli/session-owners-cli.d.ts +13 -0
  7. package/dist/types/cli/update-cli.d.ts +2 -0
  8. package/dist/types/commands/sdk.d.ts +23 -14
  9. package/dist/types/config/settings-schema.d.ts +6 -0
  10. package/dist/types/exec/bash-shell-guardian.d.ts +61 -0
  11. package/dist/types/export/html/html-export-destination.d.ts +16 -0
  12. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  13. package/dist/types/sdk/host/control/runtime-gate.d.ts +7 -0
  14. package/dist/types/session/internal/graph-successor-proof.d.ts +33 -0
  15. package/dist/types/session/internal/managed-session-storage.d.ts +6 -1
  16. package/dist/types/session/internal/session-claim-set.d.ts +69 -0
  17. package/dist/types/session/operator-error-message.d.ts +29 -0
  18. package/dist/types/session/session-manager.d.ts +57 -3
  19. package/dist/types/session/session-owners-layout.d.ts +24 -0
  20. package/dist/types/session/session-ownership-mode.d.ts +45 -0
  21. package/dist/types/session/session-ownership.d.ts +195 -0
  22. package/dist/types/session/session-storage.d.ts +36 -0
  23. package/dist/types/slash-commands/helpers/parse.d.ts +1 -0
  24. package/package.json +12 -8
  25. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  26. package/src/cli/doctor/probe-types.ts +1 -1
  27. package/src/cli/doctor/probe.ts +9 -5
  28. package/src/cli/doctor/runner.ts +6 -1
  29. package/src/cli/doctor/session-owners-probe.ts +69 -0
  30. package/src/cli/doctor/session-owners.ts +106 -0
  31. package/src/cli/github-release.ts +100 -0
  32. package/src/cli/session-owners-cli.ts +118 -0
  33. package/src/cli/stats-cli.ts +19 -1
  34. package/src/cli/update-cli.ts +50 -3
  35. package/src/cli-ordinary.ts +1 -1
  36. package/src/commands/sdk.ts +36 -33
  37. package/src/commands/session.ts +10 -2
  38. package/src/config/settings-schema.ts +18 -0
  39. package/src/config/settings.ts +127 -13
  40. package/src/exec/bash-shell-guardian.ts +181 -12
  41. package/src/exec/isolated-shell.ts +13 -3
  42. package/src/export/html/html-export-destination.ts +47 -2
  43. package/src/export/html/index.ts +161 -13
  44. package/src/internal-urls/docs-index.generated.ts +4 -4
  45. package/src/main.ts +20 -14
  46. package/src/modes/acp/acp-agent.ts +6 -0
  47. package/src/modes/action-registry.ts +4 -1
  48. package/src/modes/controllers/command-controller.ts +12 -5
  49. package/src/modes/controllers/extension-ui-controller.ts +6 -22
  50. package/src/modes/controllers/input-controller.ts +3 -2
  51. package/src/modes/controllers/selector-controller.ts +14 -1
  52. package/src/modes/interactive-mode.ts +6 -3
  53. package/src/modes/print-mode.ts +2 -1
  54. package/src/modes/runtime-init.ts +2 -17
  55. package/src/modes/utils/ui-helpers.ts +5 -3
  56. package/src/sdk/bus/index.ts +22 -0
  57. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  58. package/src/sdk/host/control/dispatch.ts +5 -1
  59. package/src/sdk/host/control/runtime-gate.ts +22 -0
  60. package/src/sdk/host/host.ts +4 -1
  61. package/src/sdk/session-readonly/metadata.ts +24 -18
  62. package/src/sdk/session.ts +2 -0
  63. package/src/session/agent-session.ts +101 -22
  64. package/src/session/internal/graph-successor-proof.ts +108 -0
  65. package/src/session/internal/managed-session-storage.ts +8 -1
  66. package/src/session/internal/session-claim-set.ts +242 -0
  67. package/src/session/operator-error-message.ts +79 -0
  68. package/src/session/session-manager.ts +524 -108
  69. package/src/session/session-owners-layout.ts +52 -0
  70. package/src/session/session-ownership-mode.ts +176 -0
  71. package/src/session/session-ownership.ts +851 -0
  72. package/src/session/session-storage.ts +60 -16
  73. package/src/setup/credential-import.ts +2 -1
  74. package/src/slash-commands/builtin-registry.ts +2 -0
  75. package/src/slash-commands/helpers/parse.ts +3 -1
package/src/main.ts CHANGED
@@ -88,8 +88,12 @@ import {
88
88
  } from "./sdk/broker/session-index";
89
89
  import type { ResumeSessionIdentity } from "./sdk/session-readonly/storage";
90
90
  import type { AgentSession } from "./session/agent-session";
91
- import { ManagedAppendIdentityMismatchError } from "./session/internal/managed-session-storage";
91
+ import {
92
+ ManagedAppendIdentityMismatchError,
93
+ RESUME_REJECTED_OPERATOR_MESSAGE,
94
+ } from "./session/internal/managed-session-storage";
92
95
  import { SessionMigrationBusyError } from "./session/internal/session-open-errors";
96
+ import { composeOperatorMessage, operatorErrorMessage } from "./session/operator-error-message";
93
97
  import { setPrimaryControlSurface } from "./session/primary-control-surface";
94
98
  import {
95
99
  resolveResumableSession,
@@ -417,11 +421,11 @@ export async function submitInteractiveInput(
417
421
  agentEnd.promise.then(() => ({ type: "agent_end" as const })),
418
422
  ]);
419
423
  if (result.type === "error") {
420
- const errorMessage = result.error instanceof Error ? result.error.message : "Unknown error occurred";
424
+ const errorMessage = operatorErrorMessage(result.error);
421
425
  mode.showError(errorMessage);
422
426
  } else if (result.type === "agent_end") {
423
427
  void prompt.catch((error: unknown) => {
424
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
428
+ const errorMessage = operatorErrorMessage(error);
425
429
  mode.showError(errorMessage);
426
430
  });
427
431
  }
@@ -429,7 +433,7 @@ export async function submitInteractiveInput(
429
433
  agentEnd.dispose();
430
434
  }
431
435
  } catch (error: unknown) {
432
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
436
+ const errorMessage = operatorErrorMessage(error);
433
437
  mode.showError(errorMessage);
434
438
  } finally {
435
439
  mode.finishPendingSubmission(input);
@@ -773,11 +777,13 @@ export async function applyStartupModelProfiles(args: StartupModelProfileArgs):
773
777
 
774
778
  async function exitForStartupModelProfileError(args: StartupModelProfileArgs, error: unknown): Promise<never> {
775
779
  const message = error instanceof Error ? error.message : String(error);
776
- process.stderr.write(
780
+ // Startup model profiles are applied before anything ran in the resumed session, so
781
+ // a fence rejection here means this resume itself did not happen.
782
+ const operatorMessage =
777
783
  error instanceof ManagedAppendIdentityMismatchError
778
- ? `${error.operatorMessage}\n`
779
- : `${chalk.red(`Error: ${message}`)}\n`,
780
- );
784
+ ? RESUME_REJECTED_OPERATOR_MESSAGE
785
+ : composeOperatorMessage(error);
786
+ process.stderr.write(operatorMessage ? `${operatorMessage}\n` : `${chalk.red(`Error: ${message}`)}\n`);
781
787
  await args.session.dispose();
782
788
  process.exit(1);
783
789
  }
@@ -1163,7 +1169,7 @@ export async function runInteractiveMode(
1163
1169
  try {
1164
1170
  await session.continuePersistedHistory();
1165
1171
  } catch (error: unknown) {
1166
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1172
+ const errorMessage = operatorErrorMessage(error);
1167
1173
  mode.showError(errorMessage);
1168
1174
  }
1169
1175
  }
@@ -1181,7 +1187,7 @@ export async function runInteractiveMode(
1181
1187
  maybeGenerateStartupTitle(initialMessage, initialImages);
1182
1188
  await session.prompt(initialMessage, { images: initialImages });
1183
1189
  } catch (error: unknown) {
1184
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1190
+ const errorMessage = operatorErrorMessage(error);
1185
1191
  mode.showError(errorMessage);
1186
1192
  }
1187
1193
  }
@@ -1218,7 +1224,7 @@ export async function runInteractiveMode(
1218
1224
  await session.prompt(text);
1219
1225
  }
1220
1226
  } catch (error: unknown) {
1221
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1227
+ const errorMessage = operatorErrorMessage(error);
1222
1228
  mode.showError(errorMessage);
1223
1229
  }
1224
1230
  }
@@ -1254,7 +1260,7 @@ export async function runInteractiveMode(
1254
1260
  maybeGenerateStartupTitle(messageToSend, imagesToSend);
1255
1261
  await session.prompt(messageToSend, { images: imagesToSend });
1256
1262
  } catch (error: unknown) {
1257
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1263
+ const errorMessage = operatorErrorMessage(error);
1258
1264
  mode.showError(errorMessage);
1259
1265
  }
1260
1266
  }
@@ -1273,7 +1279,7 @@ export async function runInteractiveMode(
1273
1279
  maybeGenerateStartupTitle(text);
1274
1280
  await session.prompt(text);
1275
1281
  } catch (error: unknown) {
1276
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1282
+ const errorMessage = operatorErrorMessage(error);
1277
1283
  mode.showError(errorMessage);
1278
1284
  }
1279
1285
  }
@@ -1308,7 +1314,7 @@ export async function runInteractiveMode(
1308
1314
  maybeGenerateStartupTitle(text);
1309
1315
  await session.prompt(text);
1310
1316
  } catch (promptError: unknown) {
1311
- const errorMessage = promptError instanceof Error ? promptError.message : "Unknown error occurred";
1317
+ const errorMessage = operatorErrorMessage(promptError);
1312
1318
  mode.showError(errorMessage);
1313
1319
  }
1314
1320
  }
@@ -73,6 +73,7 @@ import { PromptActivity, type PromptWatchdogClock, systemPromptWatchdogClock } f
73
73
  import { validateRequiredPromptText } from "../../sdk/protocol/adapter-validation";
74
74
  import { type SessionAttachment, SessionRouter, type SessionRouterFrame } from "../../sdk/router";
75
75
  import { SessionListTraversalError, sessionListPageFromResponse, traverseSessionList } from "../../sdk/session-list";
76
+ import { findOperatorMessage } from "../../session/operator-error-message";
76
77
  import { MAX_STAGED_PROMPT_IMAGES } from "../../utils/image-limits";
77
78
  import { resolveAcpAbortScope } from "./abort-scope";
78
79
  import {
@@ -1685,6 +1686,11 @@ export function acpRequestFailure(error: unknown): unknown {
1685
1686
  // Same rule as above: `code`/`details` and the JSON-RPC code are untouched, and an abandon
1686
1687
  // that observed no plan adds no keys, so its payload stays byte-identical to before.
1687
1688
  if (error instanceof AcpPromptAbandonedError) Object.assign(data, promptAbandonWireData(error.plan));
1689
+ // A session refusal that carries operator text (for example a transcript another
1690
+ // process changed) publishes it under the same `data.operatorMessage` key prompt
1691
+ // terminals use (#5615). `code`/`details` and the JSON-RPC message are untouched.
1692
+ const operatorMessage = findOperatorMessage(error);
1693
+ if (operatorMessage !== undefined) Object.assign(data, { operatorMessage });
1688
1694
  switch (code) {
1689
1695
  case "authentication_failed":
1690
1696
  return RequestError.authRequired(data, message);
@@ -1,4 +1,5 @@
1
1
  import type { AppKeybinding } from "../config/keybindings";
2
+ import { operatorErrorMessage } from "../session/operator-error-message";
2
3
 
3
4
  export type FocusDomain = "composer" | "selector" | "overlay" | "global";
4
5
 
@@ -109,7 +110,9 @@ export class ActionRegistry<Context> {
109
110
  }
110
111
 
111
112
  #reportError(id: AppKeybinding, phase: "availability" | "execution", error: unknown): void {
112
- const cause = error instanceof Error ? error.message : String(error);
113
+ // Session refusals (for example a transcript another process changed) render
114
+ // their operator message instead of a machine code.
115
+ const cause = operatorErrorMessage(error, String(error));
113
116
  try {
114
117
  this.options.showError(`Action ${id} ${phase} failed: ${cause}`);
115
118
  } catch {
@@ -32,6 +32,7 @@ import { buildToolsMarkdown } from "../../modes/utils/tools-markdown";
32
32
  import type { AsyncJobSnapshotItem } from "../../session/agent-session";
33
33
  import type { AuthStorage } from "../../session/auth-storage";
34
34
  import { computeCacheMissCostSummary, formatCacheMissSummaryLines } from "../../session/cache-economics";
35
+ import { operatorErrorMessage } from "../../session/operator-error-message";
35
36
  import type { NewSessionOptions } from "../../session/session-manager";
36
37
  import { outputMeta } from "../../tools/output-meta";
37
38
  import { resolveToCwd, stripOuterDoubleQuotes } from "../../tools/path-utils";
@@ -1338,6 +1339,13 @@ export class CommandController {
1338
1339
  this.ctx.showError("Usage: /move <path>");
1339
1340
  return;
1340
1341
  }
1342
+ // Refuse before the cwd transition and flush, not from inside them.
1343
+ try {
1344
+ this.ctx.sessionManager.assertLegacyMutationAllowed("move session");
1345
+ } catch (err) {
1346
+ this.ctx.showError(`Move failed: ${err instanceof Error ? err.message : String(err)}`);
1347
+ return;
1348
+ }
1341
1349
 
1342
1350
  const cwd = this.ctx.sessionManager.getCwd();
1343
1351
  const resolvedPath = resolveToCwd(unquoted, cwd);
@@ -1373,7 +1381,7 @@ export class CommandController {
1373
1381
  );
1374
1382
  this.ctx.ui.requestRender();
1375
1383
  } catch (err) {
1376
- this.ctx.showError(`Move failed: ${err instanceof Error ? err.message : String(err)}`);
1384
+ this.ctx.showError(`Move failed: ${operatorErrorMessage(err, String(err))}`);
1377
1385
  }
1378
1386
  }
1379
1387
 
@@ -1563,7 +1571,7 @@ export class CommandController {
1563
1571
  const message = `${body}\n\n---\n\n${metaLines.join("\n")}`;
1564
1572
  await this.ctx.session.prompt(message);
1565
1573
  } catch (err) {
1566
- this.ctx.showError(`Failed to load skill: ${err instanceof Error ? err.message : String(err)}`);
1574
+ this.ctx.showError(`Failed to load skill: ${operatorErrorMessage(err, String(err))}`);
1567
1575
  }
1568
1576
  }
1569
1577
 
@@ -1610,8 +1618,7 @@ export class CommandController {
1610
1618
  if (outcome === "cancelled") {
1611
1619
  this.ctx.showError("Compaction cancelled");
1612
1620
  } else {
1613
- const message = error instanceof Error ? error.message : String(error);
1614
- this.ctx.showError(`Compaction failed: ${message}`);
1621
+ this.ctx.showError(`Compaction failed: ${operatorErrorMessage(error, String(error))}`);
1615
1622
  }
1616
1623
  } finally {
1617
1624
  compactingLoader.stop();
@@ -1688,7 +1695,7 @@ export class CommandController {
1688
1695
  if (message === "Handoff cancelled" || (error instanceof Error && error.name === "AbortError")) {
1689
1696
  this.ctx.showError("Handoff cancelled");
1690
1697
  } else {
1691
- this.ctx.showError(`Handoff failed: ${message}`);
1698
+ this.ctx.showError(`Handoff failed: ${operatorErrorMessage(error, message)}`);
1692
1699
  }
1693
1700
  // The failure is non-destructive: the current session is unchanged. If the
1694
1701
  // document was already generated, preserve it on the clipboard for retry.
@@ -39,9 +39,11 @@ import { isSdkComposerObservationOperation } from "../../sdk/composer-observatio
39
39
 
40
40
  import { isSdkDiffObservationOperation } from "../../sdk/diff-observation";
41
41
  import {
42
+ BROKER_LIFECYCLE_OPERATIONS,
42
43
  BROKER_RUNTIME_REVISE_CAPABILITY_FIELD,
43
44
  hasBrokerRuntimeCloseCapability,
44
45
  hasBrokerRuntimeReviseCapability,
46
+ prohibitBrokerLifecycleOperation,
45
47
  } from "../../sdk/host/control/runtime-gate";
46
48
  import {
47
49
  parseSyntheticModelId,
@@ -57,6 +59,7 @@ import { getSdkClientControlOperations, getSessionClientControls } from "../../s
57
59
  import { isSideConversationOperation } from "../../sdk/side-conversation";
58
60
 
59
61
  import { bashBackgroundControlError } from "../../session/fold-coordinator";
62
+ import { operatorErrorMessage } from "../../session/operator-error-message";
60
63
  import { createReadonlySessionManager } from "../../session/session-manager";
61
64
  import { parseThinkingLevel } from "../../thinking";
62
65
  import type { TodoPhase } from "../../tools/todo-write";
@@ -128,23 +131,6 @@ const EXTENSION_COMMAND_MUTATIONS: ReadonlySet<PropertyKey> = new Set([
128
131
  "switchSession",
129
132
  ]);
130
133
 
131
- const BROKER_LIFECYCLE_OPERATIONS = new Set([
132
- "session.new",
133
- "session.fork",
134
- "session.resume",
135
- "session.close",
136
- "session.switch",
137
- "session.branch",
138
- "session.handoff",
139
- "session.delete",
140
- ]);
141
-
142
- function prohibitBrokerLifecycleOperation(operation: string): never {
143
- throw Object.assign(new Error(`${operation} is available only through the Broker lifecycle service.`), {
144
- code: "operation_prohibited",
145
- });
146
- }
147
-
148
134
  export class ExtensionUiController {
149
135
  #extensionTerminalInputUnsubscribers = new Set<() => void>();
150
136
  #extensionErrorUnsubscribe?: () => void;
@@ -614,9 +600,7 @@ export class ExtensionUiController {
614
600
  })
615
601
  .catch((err: unknown) => {
616
602
  if (this.#isStopped()) return;
617
- this.ctx.showError(
618
- `Extension sendMessage failed: ${err instanceof Error ? err.message : String(err)}`,
619
- );
603
+ this.ctx.showError(`Extension sendMessage failed: ${operatorErrorMessage(err, String(err))}`);
620
604
  });
621
605
  },
622
606
  sendUserMessage: this.#sendExtensionUserMessage,
@@ -852,7 +836,7 @@ export class ExtensionUiController {
852
836
  .sendCustomMessage(message, { ...options, origin: "external" })
853
837
  .then(() => this.#applyCustomMessageDisplay(wasStreaming, message.display))
854
838
  .catch((err: unknown) => {
855
- const errorText = `Extension sendMessage failed: ${err instanceof Error ? err.message : String(err)}`;
839
+ const errorText = `Extension sendMessage failed: ${operatorErrorMessage(err, String(err))}`;
856
840
  if (this.ctx.isBackgrounded) {
857
841
  logger.error(errorText);
858
842
  return;
@@ -1639,7 +1623,7 @@ export class ExtensionUiController {
1639
1623
  applyInjectedUserSubmission(this.ctx, { content, queued });
1640
1624
  void send.catch((err: unknown) => {
1641
1625
  if (this.#isStopped()) return;
1642
- this.ctx.showError(`Extension sendUserMessage failed: ${err instanceof Error ? err.message : String(err)}`);
1626
+ this.ctx.showError(`Extension sendUserMessage failed: ${operatorErrorMessage(err, String(err))}`);
1643
1627
  });
1644
1628
  return send;
1645
1629
  };
@@ -21,6 +21,7 @@ import {
21
21
  } from "../../modes/types";
22
22
  import type { AgentSession, AgentSessionEvent, QueuedMessageEditEntry } from "../../session/agent-session";
23
23
  import { SKILL_PROMPT_MESSAGE_TYPE, type SkillPromptDetails } from "../../session/messages";
24
+ import { operatorErrorMessage } from "../../session/operator-error-message";
24
25
  import { getUserMessageViewportAnchorIds } from "../../session/session-manager";
25
26
  import { executeBuiltinSlashCommand } from "../../slash-commands/builtin-registry";
26
27
  import {
@@ -1047,7 +1048,7 @@ export class InputController {
1047
1048
  }
1048
1049
 
1049
1050
  #reportSubmissionError(error: unknown): void {
1050
- this.ctx.showError(error instanceof Error ? error.message : String(error));
1051
+ this.ctx.showError(operatorErrorMessage(error, String(error)));
1051
1052
  }
1052
1053
 
1053
1054
  async submitText(text: string, composer: ComposerSubmissionOptions): Promise<void> {
@@ -1800,7 +1801,7 @@ export class InputController {
1800
1801
  this.ctx.ui.requestRender();
1801
1802
  }
1802
1803
  } catch (err) {
1803
- this.ctx.showError(`Failed to load skill: ${err instanceof Error ? err.message : String(err)}`);
1804
+ this.ctx.showError(`Failed to load skill: ${operatorErrorMessage(err, String(err))}`);
1804
1805
  }
1805
1806
  return true;
1806
1807
  }
@@ -82,7 +82,7 @@ import {
82
82
  SharedControlPublicationError,
83
83
  } from "../../session/agent-session";
84
84
  import { CREDENTIAL_STORE_UNREADABLE_MESSAGE } from "../../session/credential-store-errors";
85
- import { type SessionInfo, SessionManager } from "../../session/session-manager";
85
+ import { GraphSuccessorUnavailableError, type SessionInfo, SessionManager } from "../../session/session-manager";
86
86
  import { getTreeForInternalRead } from "../../session/session-manager-internal";
87
87
  import { FileSessionStorage } from "../../session/session-storage";
88
88
  import {
@@ -2138,6 +2138,19 @@ export class SelectorController {
2138
2138
  this.ctx.showStatus("No messages to branch from");
2139
2139
  return;
2140
2140
  }
2141
+ // Refuse before goal continuation and the side chat are touched, unless some
2142
+ // prompt starts a fresh session (no parent) and needs no graph successor.
2143
+ // This picker-time probe checks ownership only; branch() proves the selected path.
2144
+ const refusal = this.ctx.sessionManager.graphSuccessorRefusal();
2145
+ if (
2146
+ refusal &&
2147
+ userMessages.every(message => this.ctx.sessionManager.getEntryForFidelity(message.entryId)?.parentId)
2148
+ ) {
2149
+ this.ctx.showError(
2150
+ `Fork failed: ${new GraphSuccessorUnavailableError("prepare branched session", refusal).message}`,
2151
+ );
2152
+ return;
2153
+ }
2141
2154
 
2142
2155
  this.ctx.goalModeController.cancelContinuation();
2143
2156
  // Close the side-chat composer before the picker takes ownership, including
@@ -868,7 +868,9 @@ export class InteractiveMode implements InteractiveModeContext {
868
868
  this.keybindings.setDisplayContext(this.#keyDisplayContext);
869
869
 
870
870
  // Register session manager flush for signal handlers (SIGINT, SIGTERM, SIGHUP)
871
- this.#cleanupUnsubscribe = postmortem.register("session-manager-flush", () => this.sessionManager.flush());
871
+ this.#cleanupUnsubscribe = postmortem.register("session-manager-flush", () =>
872
+ this.sessionManager.flushBeforeLeaving(),
873
+ );
872
874
 
873
875
  // Tear down subprocess-spawning tools (browser Chrome, Python eval kernel) on a
874
876
  // signal kill (SIGINT/SIGTERM/SIGHUP) so they aren't reparented to PID 1 (#698).
@@ -1970,8 +1972,9 @@ export class InteractiveMode implements InteractiveModeContext {
1970
1972
  this.promptSuggestion.clear();
1971
1973
  this.#btwController.dispose();
1972
1974
 
1973
- // Flush pending session writes before shutdown.
1974
- await this.sessionManager.flush();
1975
+ // Flush pending session writes before shutdown. A transcript another process
1976
+ // changed has nothing left to flush and must not turn /quit into a crash.
1977
+ await this.sessionManager.flushBeforeLeaving();
1975
1978
  try {
1976
1979
  await this.sessionManager.saveDraft(draftText);
1977
1980
  } catch (err) {
@@ -12,6 +12,7 @@ import { loadSlashCommands } from "../extensibility/slash-commands";
12
12
  import type { AgentSession } from "../session/agent-session";
13
13
  import { ManagedAppendIdentityMismatchError } from "../session/internal/managed-session-storage";
14
14
  import { isSilentAbort } from "../session/messages";
15
+ import { operatorErrorMessage } from "../session/operator-error-message";
15
16
  import { resolveProviderSafetyStopHint } from "../session/provider-safety-stop-hint";
16
17
  import { executeLocalHeadlessBuiltinSlashCommand } from "../slash-commands/builtin-registry";
17
18
  import { initializeExtensions } from "./runtime-init";
@@ -391,7 +392,7 @@ export async function runPrintMode(session: AgentSession, options: PrintModeOpti
391
392
  } catch (error) {
392
393
  if (error instanceof ManagedAppendIdentityMismatchError) {
393
394
  process.exitCode = 1;
394
- await writeStderrAndQuiesce(`${error.operatorMessage}\n`);
395
+ await writeStderrAndQuiesce(`${operatorErrorMessage(error)}\n`);
395
396
  } else failures.push(error);
396
397
  } finally {
397
398
  // The JSON subscriber remains live while disposal emits its final events.
@@ -19,9 +19,11 @@ import { isSdkComposerObservationOperation } from "../sdk/composer-observation";
19
19
 
20
20
  import { isSdkDiffObservationOperation } from "../sdk/diff-observation";
21
21
  import {
22
+ BROKER_LIFECYCLE_OPERATIONS,
22
23
  BROKER_RUNTIME_REVISE_CAPABILITY_FIELD,
23
24
  hasBrokerRuntimeCloseCapability,
24
25
  hasBrokerRuntimeReviseCapability,
26
+ prohibitBrokerLifecycleOperation,
25
27
  } from "../sdk/host/control/runtime-gate";
26
28
  import {
27
29
  parseSyntheticModelId,
@@ -40,23 +42,6 @@ import { bashBackgroundControlError } from "../session/fold-coordinator";
40
42
  import { parseThinkingLevel } from "../thinking";
41
43
  import type { TodoPhase } from "../tools/todo-write";
42
44
 
43
- const BROKER_LIFECYCLE_OPERATIONS = new Set([
44
- "session.new",
45
- "session.fork",
46
- "session.resume",
47
- "session.close",
48
- "session.switch",
49
- "session.branch",
50
- "session.handoff",
51
- "session.delete",
52
- ]);
53
-
54
- function prohibitBrokerLifecycleOperation(operation: string): never {
55
- throw Object.assign(new Error(`${operation} is available only through the Broker lifecycle service.`), {
56
- code: "operation_prohibited",
57
- });
58
- }
59
-
60
45
  /** Action name for an extension-originated send failure. */
61
46
  export type ExtensionSendAction = "extension_send" | "extension_send_user";
62
47
 
@@ -35,6 +35,7 @@ import {
35
35
  SKILL_PROMPT_MESSAGE_TYPE,
36
36
  type SkillPromptDetails,
37
37
  } from "../../session/messages";
38
+ import { operatorErrorMessage } from "../../session/operator-error-message";
38
39
  import {
39
40
  associateSessionMessageViewportAnchorId,
40
41
  getSessionMessageEntryId,
@@ -1305,9 +1306,10 @@ export class UiHelpers {
1305
1306
  this.ctx.compactionQueuedMessages = queuedMessages;
1306
1307
  this.ctx.updatePendingMessagesDisplay();
1307
1308
  this.ctx.showError(
1308
- `Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${
1309
- error instanceof Error ? error.message : String(error)
1310
- }`,
1309
+ `Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${operatorErrorMessage(
1310
+ error,
1311
+ String(error),
1312
+ )}`,
1311
1313
  );
1312
1314
  };
1313
1315
 
@@ -4685,6 +4685,9 @@ export function createNotificationsExtension(
4685
4685
  // Failed terminal teardown remains fenced from normal runtime lookup while the
4686
4686
  // exact runtime object retains authority for an explicit idempotent retry.
4687
4687
  const cleanupRetries = new Map<string, SessionRuntime>();
4688
+ // The one terminal release in flight for an exact runtime. Concurrent stops
4689
+ // join it instead of running a second release beside it.
4690
+ const terminalReleases = new WeakMap<SessionRuntime, Promise<boolean>>();
4688
4691
  const sessionStartPromises = new Map<string, Promise<SessionStartResult>>();
4689
4692
  const forceIsolatedChatSessions = new Set<string>();
4690
4693
  const branchStartupTasks = new Set<Promise<void>>();
@@ -4979,6 +4982,25 @@ export function createNotificationsExtension(
4979
4982
  rt.pendingInteractive.clear();
4980
4983
  return true;
4981
4984
  }
4985
+ // A shutdown that lands while startup is still pending reaches this release
4986
+ // up to three times for the same runtime: from the shutdown itself, from the
4987
+ // startup that observes its own removal, and from the re-stop deferred behind
4988
+ // the pending start above. Run concurrently, each one published its own
4989
+ // `session_closed` frame and raced the owner releases. Join the release in
4990
+ // flight instead. A settled release clears its entry, so an explicit retry
4991
+ // after a retained owner-release failure still runs a fresh release.
4992
+ const inFlight = terminalReleases.get(rt);
4993
+ if (inFlight) return await inFlight;
4994
+ const release = releaseSessionRuntime(id, rt);
4995
+ terminalReleases.set(rt, release);
4996
+ try {
4997
+ return await release;
4998
+ } finally {
4999
+ if (terminalReleases.get(rt) === release) terminalReleases.delete(rt);
5000
+ }
5001
+ }
5002
+
5003
+ async function releaseSessionRuntime(id: string, rt: SessionRuntime): Promise<boolean> {
4982
5004
  rt.abortBtwQuestions();
4983
5005
  // Keep this exact object authoritative for the full terminal release, including
4984
5006
  // the interval before a failed owner can be recorded for a later retry.
@@ -324,7 +324,7 @@ export const SDK_LIFECYCLE_ROUTER_PROTOCOL_VERSION = 1;
324
324
  * Generation 230 composes that ownership policy with retained replay and
325
325
  * SDK notification-authority bindings.
326
326
  */
327
- export const DAEMON_GENERATION = 236;
327
+ export const DAEMON_GENERATION = 237;
328
328
 
329
329
  /**
330
330
  * Serving-compatibility boundary for daemon lifecycle requests. Epoch 7
@@ -3,6 +3,7 @@ import {
3
3
  DEFAULT_MODEL_SELECTION_RECOVERY_MESSAGE,
4
4
  parseDefaultModelSelectionRecovery,
5
5
  } from "../../../session/default-model-selection";
6
+ import { findOperatorMessage } from "../../../session/operator-error-message";
6
7
  import { MODEL_NOT_SELECTED_CODE, MODEL_NOT_SELECTED_PUBLIC_MESSAGE } from "../../../setup/model-onboarding-guidance";
7
8
  import { validateRequiredPromptText } from "../../protocol/adapter-validation";
8
9
  import { isSecureLocalOperation } from "../../protocol/client-control-contracts";
@@ -492,7 +493,10 @@ function errorResponse(id: string, row: Operation, error: unknown): ControlRespo
492
493
  if (code === "unknown_gate") return failure(id, "resource_gone", message);
493
494
  if (code === "invalid_input" || /invalid input/i.test(message))
494
495
  return failure(id, "invalid_input", message, undefined, details);
495
- return failure(id, "internal", "Control operation failed.", undefined, details);
496
+ // Operator messages are fixed, path-free text that names the recovery (for example a
497
+ // transcript another process changed), so they replace the opaque fallback text
498
+ // while the code stays `internal`.
499
+ return failure(id, "internal", findOperatorMessage(error) ?? "Control operation failed.", undefined, details);
496
500
  }
497
501
 
498
502
  async function execute(surface: ControlSurface, row: Operation, request: ControlRequest): Promise<ControlResponse> {
@@ -24,6 +24,28 @@ export function hasBrokerRuntimeReviseCapability(input: unknown): boolean {
24
24
  record(input)?.[BROKER_RUNTIME_REVISE_CAPABILITY_FIELD] === expected
25
25
  );
26
26
  }
27
+ /**
28
+ * Session lifecycle operations that only the Broker lifecycle service may run. A
29
+ * session's own control surfaces (extension runtime and the interactive extension
30
+ * UI) refuse them with {@link prohibitBrokerLifecycleOperation}.
31
+ */
32
+ export const BROKER_LIFECYCLE_OPERATIONS: ReadonlySet<string> = new Set([
33
+ "session.new",
34
+ "session.fork",
35
+ "session.resume",
36
+ "session.close",
37
+ "session.switch",
38
+ "session.branch",
39
+ "session.handoff",
40
+ "session.delete",
41
+ ]);
42
+
43
+ export function prohibitBrokerLifecycleOperation(operation: string): never {
44
+ throw Object.assign(new Error(`${operation} is available only through the Broker lifecycle service.`), {
45
+ code: "operation_prohibited",
46
+ });
47
+ }
48
+
27
49
  export const BROKER_RUNTIME_CLOSE_CAPABILITY_FIELD = "__gjcBrokerCloseCapability";
28
50
  /** Private field carried only on the Broker-authorized terminal-abort request. */
29
51
  export const BROKER_RUNTIME_ABORT_CAPABILITY_FIELD = "__gjcBrokerAbortCapability";
@@ -1,6 +1,7 @@
1
1
  import { logger } from "@gajae-code/utils";
2
2
  import { AUTOROUTING_INACTIVE_WARNING } from "../../config/autorouting-contract";
3
3
  import { isFileLockAcquireTimeout } from "../../config/file-lock";
4
+ import { findOperatorMessage } from "../../session/operator-error-message";
4
5
  import {
5
6
  SecureLocalGrantReplayFence,
6
7
  secureLocalFrameOperation,
@@ -232,7 +233,9 @@ function errorFrame(connectionId: string, frame: SdkFrame, error: unknown): SdkF
232
233
  : typeof candidate?.code === "string"
233
234
  ? candidate.code
234
235
  : "internal";
235
- const message = typeof candidate?.message === "string" ? candidate.message : "SDK host operation failed.";
236
+ const message =
237
+ findOperatorMessage(error) ??
238
+ (typeof candidate?.message === "string" ? candidate.message : "SDK host operation failed.");
236
239
  if (frame.type === "control_request") {
237
240
  return {
238
241
  type: "control_response",
@@ -112,25 +112,21 @@ export async function readSessionListTrailingPatches(
112
112
  const start = Math.max(0, position - chunkSize);
113
113
  const length = position - start;
114
114
  const { bytesRead } = await handle.read(buffer, 0, length, start);
115
- const combined = Buffer.concat([buffer.subarray(0, bytesRead), trailingFragment]);
116
- let complete = combined;
117
- if (start > 0) {
118
- const firstNewline = combined.indexOf(0x0a);
119
- if (firstNewline === -1) {
120
- trailingFragment = combined;
121
- position = start;
122
- continue;
123
- }
124
- trailingFragment = combined.subarray(0, firstNewline);
125
- complete = combined.subarray(firstNewline + 1);
115
+ const chunk = buffer.subarray(0, bytesRead);
116
+ // The carried fragment directly follows `chunk` in the file and never holds a
117
+ // newline, so the first newline of chunk + fragment is always the chunk's own.
118
+ const firstNewline = start > 0 ? chunk.indexOf(0x0a) : -1;
119
+ if (start > 0 && firstNewline === -1) {
120
+ trailingFragment = Buffer.concat([chunk, trailingFragment]);
121
+ position = start;
122
+ continue;
126
123
  }
127
- // Marker may straddle the discarded partial first line; still parse when
128
- // the raw chunk or carried fragment could hold a header_patch record.
129
- const mayContainPatch =
130
- complete.includes(headerPatchMarker) ||
131
- buffer.subarray(0, bytesRead).includes(headerPatchMarker) ||
132
- trailingFragment.includes(headerPatchMarker);
133
- if (mayContainPatch) {
124
+ // Test chunk + fragment for the marker without joining them: most chunks hold
125
+ // none, and joining every chunk made the walk copy each transcript once more.
126
+ // The seam check catches a marker split between the chunk and the fragment.
127
+ // As before, a marker in the discarded partial first line also opens the gate.
128
+ if (adjacentBytesInclude(chunk, trailingFragment, headerPatchMarker)) {
129
+ const complete = Buffer.concat([chunk.subarray(firstNewline + 1), trailingFragment]);
134
130
  const lines = complete.toString("utf8").split("\n");
135
131
  for (let index = lines.length - 1; index >= 0; index--) {
136
132
  const line = lines[index];
@@ -148,6 +144,8 @@ export async function readSessionListTrailingPatches(
148
144
  }
149
145
  }
150
146
  }
147
+ // Copy the partial first line out: `buffer` is overwritten by the next read.
148
+ if (start > 0) trailingFragment = Buffer.from(chunk.subarray(0, firstNewline));
151
149
  position = start;
152
150
  }
153
151
  return latest.cwd === undefined && latest.title === undefined && latest.starred === undefined ? [] : [latest];
@@ -156,6 +154,14 @@ export async function readSessionListTrailingPatches(
156
154
  }
157
155
  }
158
156
 
157
+ /** Whether `needle` occurs in `head` followed directly by `tail`, without concatenating them. */
158
+ function adjacentBytesInclude(head: Buffer, tail: Buffer, needle: Buffer): boolean {
159
+ if (head.includes(needle) || tail.includes(needle)) return true;
160
+ const overlap = needle.length - 1;
161
+ const seam = Buffer.concat([head.subarray(Math.max(0, head.length - overlap)), tail.subarray(0, overlap)]);
162
+ return seam.includes(needle);
163
+ }
164
+
159
165
  export function applySessionListHeaderPatch(header: SessionListHeader, patch: HeaderPatchRecord["patch"]): void {
160
166
  if (typeof patch.cwd === "string") header.cwd = patch.cwd;
161
167
  if (typeof patch.title === "string") header.title = patch.title;
@@ -3209,6 +3209,8 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
3209
3209
  "Cannot rescope a session with caller-owned MCP authority; recreate the session at the target cwd.",
3210
3210
  );
3211
3211
  }
3212
+ // Refuse before the cwd, capability and plugin rebinding below, not from moveTo.
3213
+ sessionManager.assertLegacyMutationAllowed("move session");
3212
3214
  return sessionManager.runExclusiveCwdMoveTransition(async () => {
3213
3215
  if (moveConsumed) {
3214
3216
  throw new Error(