@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
@@ -58,8 +58,10 @@ import {
58
58
  isSessionDisposalIncompleteError,
59
59
  } from "../session/agent-session";
60
60
  import type { HistoryStorage } from "../session/history-storage";
61
+ import { operatorErrorMessage } from "../session/operator-error-message";
61
62
  import type { SessionContext, SessionManager } from "../session/session-manager";
62
63
  import { getRecentSessions, getSessionMessageEntryId } from "../session/session-manager";
64
+ import { SessionHeldError, type SessionOwnershipError } from "../session/session-ownership";
63
65
  import { createDefaultPaseoAnnounceDependencies, startPaseoAnnouncement } from "../setup/paseo/announce";
64
66
  import type { LspStartupServerInfo } from "../tools";
65
67
  import { formatPhaseDisplayName } from "../tools/todo-write";
@@ -2779,10 +2781,46 @@ export class InteractiveMode implements InteractiveModeContext {
2779
2781
  this.#selectorController.showSessionSelector();
2780
2782
  }
2781
2783
 
2782
- handleResumeSession(sessionPath: string): Promise<void> {
2784
+ handleResumeSession(
2785
+ sessionPath: string,
2786
+ options?: { readonly cancelledStatus?: string; readonly continueHere?: boolean },
2787
+ ): Promise<void> {
2783
2788
  this.#btwController.dispose();
2784
2789
  this.resetObserverRegistry();
2785
- return this.#selectorController.handleResumeSession(sessionPath);
2790
+ return this.#selectorController.handleResumeSession(sessionPath, options);
2791
+ }
2792
+
2793
+ /**
2794
+ * A turn enforce refused before it wrote anything (single-owner design §2.7, §3.1): another
2795
+ * process now holds this session, or gjc could not check. The optimistic message goes and the draft
2796
+ * comes back to the editor, after any text typed since. A held session then gets the held-session
2797
+ * warning, through `/resume`'s flow for this session's own file, with Fork and Cancel only.
2798
+ */
2799
+ handleRefusedSessionTurn(error: SessionHeldError | SessionOwnershipError, input: SubmittedUserInput): void {
2800
+ const restored = !input.customType && (input.text.length > 0 || (input.images?.length ?? 0) > 0);
2801
+ if (restored) {
2802
+ this.rebuildChatFromMessages("reconcile-same-transcript");
2803
+ const typed = this.editor.getText();
2804
+ if (input.text.length > 0) this.editor.setText(typed.length === 0 ? input.text : `${typed}\n${input.text}`);
2805
+ if (input.images?.length) this.pendingImages = [...this.pendingImages, ...input.images];
2806
+ this.updateEditorChrome();
2807
+ this.ui.requestRender();
2808
+ }
2809
+ const sessionFile = this.sessionManager.getSessionFile();
2810
+ if (
2811
+ !(error instanceof SessionHeldError) ||
2812
+ error.sessionId !== this.sessionManager.getSessionId() ||
2813
+ !sessionFile
2814
+ ) {
2815
+ this.showError(operatorErrorMessage(error));
2816
+ return;
2817
+ }
2818
+ void this.handleResumeSession(sessionFile, {
2819
+ continueHere: false,
2820
+ cancelledStatus: restored
2821
+ ? "Not sent: this session is open in another process. Your message is back in the editor."
2822
+ : "Not sent: this session is open in another process.",
2823
+ }).catch(failure => this.showError(operatorErrorMessage(failure)));
2786
2824
  }
2787
2825
 
2788
2826
  handleSessionDeleteCommand(): Promise<void> {
@@ -72,6 +72,6 @@ Use it only for sanctioned GJC workflow CLI persistence or state read/write/cont
72
72
 
73
73
  # Output minimizer
74
74
 
75
- - Bash stdout/stderr may be rewritten before you see it: long output keeps only the last 1 KiB by default to reduce noise and input-token use. Explicit `tools.artifactTailBytes` / `tools.artifactHeadBytes` settings can set the tail budget or retain both ends. Prefer focused commands and dedicated `search`/`find` tools over producing broad output. Test/lint runners (e.g. `bun test`, `cargo test`, ESLint) are also passed through heuristic filters that drop noise and keep failures.
75
+ - Bash stdout/stderr may be rewritten before you see it: long output keeps only the last 1 KiB by default to reduce noise and input-token use. The `tools.bashOutputTailBytes` / `tools.bashOutputHeadBytes` settings set the tail budget or retain both ends. Prefer focused commands and dedicated `search`/`find` tools over producing broad output. Test/lint runners (e.g. `bun test`, `cargo test`, ESLint) are also passed through heuristic filters that drop noise and keep failures.
76
76
  - When the local minimizer changes visible text, successful artifact storage appends a footer containing an `artifact://<id>` reference. Complete artifacts are labeled as full output; hard-capped artifacts report omitted bytes instead. If artifact allocation/storage is unavailable before a writer/save operation is attempted, truncation may have no reference or diagnostic. If an artifact writer/save operation is attempted and fails, a bounded diagnostic is emitted without inventing an artifact URI.
77
77
  - ACP/client-terminal output can arrive already truncated from the beginning. Treat any truncation notice or metadata as evidence that the visible tail is incomplete. Recover omitted output only when an `artifact://` footer or metadata reference is present; truncation evidence without a reference means the visible output is incomplete and no artifact is recoverable. Output with neither truncation evidence nor an artifact reference is the complete emitted output.
@@ -25,7 +25,7 @@ Pick by how many notifications you need:
25
25
 
26
26
  ## Output
27
27
 
28
- Returns `Monitor started · task <task_id>` plus a task entry visible via `job({list: true})`. Persistent notifications contain the latest line and the count of earlier coalesced lines; terminal completion flushes the newest pending line.
28
+ Returns `Monitor started · task <task_id>` plus a task entry visible via `job({list: true})`. Persistent notifications contain the latest line and the count of earlier coalesced lines; terminal completion flushes the newest pending line. A clean exit (status 0) after at least one notification is reported by a monitor notification saying it exited (code 0), in place of the background-job completion result: it rides on the final line when that line is still undelivered, and otherwise arrives as context on your next turn without waking you. A non-zero exit, a timeout, or an exit with no stdout line sends the background-job completion result instead.
29
29
 
30
30
  ## Cancellation
31
31
 
@@ -859,7 +859,11 @@ export class MCPManager {
859
859
  this.#pendingExactControlServers.has(name)
860
860
  )
861
861
  return;
862
- void this.reconnectServer(name);
862
+ void this.reconnectServer(name).catch(error => {
863
+ if (!(error instanceof MCPExpectedFailure)) {
864
+ logger.error("MCP automatic reconnect failed", { path: `mcp:${name}`, error });
865
+ }
866
+ });
863
867
  }),
864
868
  );
865
869
  }
@@ -156,6 +156,8 @@ const ACP_MCP_PRESERVED_LAUNCH_CODES = new Set([
156
156
  "uncertain_after_send",
157
157
  // Attach-only refusal: raised by ensureBroker before any lifecycle request or MCP server.
158
158
  "broker_unavailable",
159
+ // Resume refused before any launch: another process holds the session (single-owner).
160
+ "live_session",
159
161
  ]);
160
162
 
161
163
  /**
@@ -16,6 +16,7 @@ import type { ModelProfileErrorDetails } from "../../config/model-profile-contra
16
16
  import { planLaunchWorktree } from "../../gjc-runtime/launch-worktree";
17
17
  import { readExistingStateForMutation, withWorkflowStateLock } from "../../gjc-runtime/state-writer";
18
18
  import { SessionManager } from "../../session/session-manager";
19
+ import type { SessionOwnerHolderSummary } from "../../session/session-ownership";
19
20
  import type {
20
21
  TaskArtifactOwnerDeletionEvidence,
21
22
  TaskArtifactOwnerRetirementContinuation,
@@ -84,6 +85,7 @@ import {
84
85
  hasSessionLifecycleStartupCommit,
85
86
  isCanonicalSessionId,
86
87
  type LifecycleFailureArtifact,
88
+ markLifecycleRequestReceived,
87
89
  prepareSpawnChildHostLaunch,
88
90
  processIncarnationForBroker,
89
91
  readSessionLifecycleFailure,
@@ -405,6 +407,8 @@ export type BrokerResponse =
405
407
  code: BrokerErrorCode;
406
408
  message: string;
407
409
  details?: ModelProfileErrorDetails | SpawnSubstrateFailure;
410
+ /** `live_session` from `session.resume` or `session.delete`: the process that holds the session (single-owner). */
411
+ holder?: SessionOwnerHolderSummary;
408
412
  endpoint?: "unavailable";
409
413
  cleanup?: BrokerCleanupEvidence;
410
414
  };
@@ -475,6 +479,21 @@ function publicLifecycleLookupInput(
475
479
  if (!target) return error("invalid_input", "session.lookup target must be an object");
476
480
  return { operation: "session.create", target };
477
481
  }
482
+ /**
483
+ * A `session.delete` refusal that leaves its key retryable, when the caller has also seen that the
484
+ * attempt left the ledger row as it found it (every delete effect is preceded by an `effect_started`
485
+ * transition). Before that transition the delete path emits these codes only for a live or held
486
+ * session (`live_session`) and a claim that could not be checked (`unavailable`); its other
487
+ * `unavailable` refusals follow an effect. A fresh request keeps its `accepted` binding. A cleanup
488
+ * replay keeps its pending or uncertain receipt, which resumes once the holder is gone.
489
+ */
490
+ function isRetryableDeleteRefusal(operation: string, response: BrokerResponse): boolean {
491
+ return (
492
+ operation === "session.delete" &&
493
+ !response.ok &&
494
+ (response.error.code === "live_session" || response.error.code === "unavailable")
495
+ );
496
+ }
478
497
  function lifecycleResponseState(response: BrokerResponse): LifecycleState {
479
498
  if (response.ok) return "terminal_ok";
480
499
  if (isCleanupPending(response)) return "effect_started";
@@ -6252,6 +6271,7 @@ export class Broker {
6252
6271
  createHash("sha256")
6253
6272
  .update(canonicalJson({ operation, input: lifecycleRequestIdentity(input) }))
6254
6273
  .digest("hex");
6274
+ markLifecycleRequestReceived(this, input);
6255
6275
  const prev = this.#chains.get(target) ?? Promise.resolve();
6256
6276
  let release!: () => void;
6257
6277
  const current = new Promise<void>(resolve => (release = resolve));
@@ -6309,8 +6329,10 @@ export class Broker {
6309
6329
  }
6310
6330
  return replay;
6311
6331
  }
6332
+ const anchor = this.ledger.get(identity);
6312
6333
  const outcome = await executeLifecycle(this, operation, input, identity, cleanup);
6313
6334
  const response = outcome.response;
6335
+ if (isRetryableDeleteRefusal(operation, response) && this.ledger.get(identity) === anchor) return response;
6314
6336
  const storedResponse = credentialFreeLifecycleResponse(response) as BrokerResponse;
6315
6337
  const recorded = await this.ledger.transition(identity, lifecycleResponseState(response), {
6316
6338
  ...(operation === "session.delete" &&
@@ -6337,8 +6359,10 @@ export class Broker {
6337
6359
  const cleanup = (replay ? cleanupFromResponse(replay) : undefined) ?? reconstructedDeleteCleanup;
6338
6360
  if (!cleanup)
6339
6361
  return replay ?? error("terminal_uncertain", "prior lifecycle operation outcome is uncertain");
6362
+ const anchor = this.ledger.get(identity);
6340
6363
  const outcome = await executeLifecycle(this, operation, input, identity, cleanup);
6341
6364
  const response = outcome.response;
6365
+ if (isRetryableDeleteRefusal(operation, response) && this.ledger.get(identity) === anchor) return response;
6342
6366
  const storedResponse = credentialFreeLifecycleResponse(response) as BrokerResponse;
6343
6367
  const recorded = await this.ledger.transition(identity, lifecycleResponseState(response), {
6344
6368
  ...(pendingCleanupSessionId(response) ? { intendedSessionId: pendingCleanupSessionId(response) } : {}),
@@ -6360,8 +6384,11 @@ export class Broker {
6360
6384
  if (begun.kind === "in_progress") return error("broker_restarting", "lifecycle operation is in progress");
6361
6385
  const outcome = await executeLifecycle(this, operation, input, identity);
6362
6386
  let response = outcome.response;
6363
- if (operation === "session.close" && !response.ok && response.error.code === "busy") {
6364
- await this.ledger.retryCloseRefusal(identity);
6387
+ if (
6388
+ (operation === "session.close" && !response.ok && response.error.code === "busy") ||
6389
+ (isRetryableDeleteRefusal(operation, response) && this.ledger.get(identity)?.state === "accepted")
6390
+ ) {
6391
+ await this.ledger.retryRefusal(identity);
6365
6392
  return response;
6366
6393
  }
6367
6394
  if (operation === "session.close" && input.ifIdle === true && response.ok) {
@@ -1239,15 +1239,17 @@ export class LifecycleLedger {
1239
1239
  if (prior.state === "accepted") return { kind: "new", entry: prior };
1240
1240
  return { kind: "in_progress", entry: prior };
1241
1241
  }
1242
- /** A runtime busy refusal proves no close effect; retain key binding, not a terminal result. */
1243
- async retryCloseRefusal(identity: string): Promise<void> {
1242
+ /**
1243
+ * A refusal that proves no effect keeps its key binding, not a terminal result: a runtime busy
1244
+ * close, or a delete refused while its row is still `accepted` (a live or held session, `unavailable`).
1245
+ */
1246
+ async retryRefusal(identity: string): Promise<void> {
1244
1247
  await this.#mutate(async () => {
1245
1248
  const previous = this.#byIdentity.get(identity);
1246
- if (
1247
- !previous?.operationKey?.startsWith("session.close\u0000") ||
1248
- (previous.state !== "accepted" && previous.state !== "effect_started")
1249
- )
1250
- throw new Error("Cannot retry a settled or non-close lifecycle operation");
1249
+ const retryable = previous?.operationKey?.startsWith("session.close\u0000")
1250
+ ? previous.state === "accepted" || previous.state === "effect_started"
1251
+ : previous?.operationKey?.startsWith("session.delete\u0000") === true && previous.state === "accepted";
1252
+ if (!previous || !retryable) throw new Error("Cannot retry a settled lifecycle operation or one with effects");
1251
1253
  await this.#compact({
1252
1254
  version: previous.version,
1253
1255
  identity,
@@ -50,11 +50,21 @@ import {
50
50
  resolveManagedGcScopeForRead,
51
51
  taskArtifactOwnerStorageContextForScope,
52
52
  } from "../../session/internal/managed-session-scope";
53
+ import { claimsUnder, resolveSessionOwnership, withScopedSessionClaim } from "../../session/internal/session-claim-set";
53
54
  import { captureTaskArtifactOwnerDeletionEvidence } from "../../session/internal/task-artifact-owner-access";
54
55
  import {
55
56
  hasSiblingTaskArtifactOwnerTranscript,
56
57
  taskArtifactOwnerLocatorFromTranscriptBytes,
57
58
  } from "../../session/internal/task-artifact-owner-transcript";
59
+ import {
60
+ probeSessionOwner,
61
+ SessionHeldError,
62
+ type SessionOwnerHolder,
63
+ type SessionOwnerHolderSummary,
64
+ sessionOwnerHolderPhrase,
65
+ sessionOwnerHolderSummary,
66
+ } from "../../session/session-ownership";
67
+ import { liveSessionOwnershipModeFor, type SessionOwnershipMode } from "../../session/session-ownership-mode";
58
68
  import {
59
69
  FileSessionStorage,
60
70
  SessionDeleteVerificationError,
@@ -90,6 +100,7 @@ import type { SessionStorageSnapshot } from "../session-readonly/storage";
90
100
  import {
91
101
  lifecycleKnownSecrets,
92
102
  normalizeSdkStartupFailure,
103
+ SDK_STARTUP_SESSION_HELD_CODE,
93
104
  type SdkStartupFailure,
94
105
  type SdkStartupRollbackResult,
95
106
  sanitizeSdkStartupMessage,
@@ -1450,10 +1461,9 @@ function sameLiveResumeRecord(expected: LiveResumeRecord, current: LiveResumeRec
1450
1461
  );
1451
1462
  }
1452
1463
 
1453
- function liveResumeAuthority(
1454
- sessions: readonly LiveResumeRecord[],
1455
- sessionId: string,
1456
- ): { kind: "none" } | { kind: "ambiguous" } | { kind: "live"; record: LiveResumeRecord } {
1464
+ type LiveResumeAuthority = { kind: "none" } | { kind: "ambiguous" } | { kind: "live"; record: LiveResumeRecord };
1465
+
1466
+ function liveResumeAuthority(sessions: readonly LiveResumeRecord[], sessionId: string): LiveResumeAuthority {
1457
1467
  const indexedCandidates = sessions.filter(session => session.sessionId === sessionId);
1458
1468
  if (indexedCandidates.some(session => !isSessionAuthorityEligible(session))) return { kind: "ambiguous" };
1459
1469
  const liveCandidates = indexedCandidates.filter(session => session.live);
@@ -1462,6 +1472,168 @@ function liveResumeAuthority(
1462
1472
  return record ? { kind: "live", record } : { kind: "none" };
1463
1473
  }
1464
1474
 
1475
+ /** A live row with an endpoint resume can hand out; a generation-0 direct-session row has none. */
1476
+ function hasResumableEndpoint(authority: LiveResumeAuthority, sessionId: string): boolean {
1477
+ return authority.kind === "live" && endpointIncarnation(authority.record, sessionId) !== undefined;
1478
+ }
1479
+
1480
+ /**
1481
+ * Longest a `session.resume` under `enforce` waits for the process that holds the session's claim to
1482
+ * publish its SDK endpoint, before it refuses. An interactive TUI holds the claim before its endpoint
1483
+ * reaches the index, while it starts and right after it switches sessions; that gap measured about
1484
+ * 0.4 s on an idle machine. 8 s leaves 2 s of the SDK client's default 10 s request timeout for the
1485
+ * reply, so a caller that never sized its deadline usually sees the refusal; index refreshes,
1486
+ * heartbeats and a slow probe come before the wait, and resumes of one session queue behind each
1487
+ * other, so it is not a guarantee. Callers that size their deadline with `lifecycleRequestTimeoutMs`
1488
+ * (ACP, the lifecycle service and so the CLI, the SDK MCP server) are well inside it.
1489
+ */
1490
+ const ENFORCE_HELD_ENDPOINT_WAIT_MS = 8_000;
1491
+ /**
1492
+ * Longest a resume under `observe` waits. `observe` never refuses: after the wait it goes
1493
+ * on as before ownership, so for a holder that never publishes an endpoint (an embedding such as the
1494
+ * desktop app) the wait is pure latency added to every resume, and it shortens a later launch's
1495
+ * admission window. 2 s covers the measured TUI startup gap several times over and keeps both small.
1496
+ */
1497
+ const OBSERVE_HELD_ENDPOINT_WAIT_MS = 2_000;
1498
+ const HELD_SESSION_ENDPOINT_POLL_MS = 100;
1499
+
1500
+ /** When the broker received each lifecycle request, before it queued behind its session's chain. */
1501
+ const lifecycleRequestsReceivedAt = new WeakMap<Input, number>();
1502
+
1503
+ /** Record a lifecycle request's arrival, so a resume's wait counts the time it spent queued. */
1504
+ export function markLifecycleRequestReceived(broker: Broker, input: Input): void {
1505
+ lifecycleRequestsReceivedAt.set(input, lifecycleTiming(broker).now());
1506
+ }
1507
+
1508
+ /**
1509
+ * The wait one resume may still spend: the mode's bound, never more than the request's readiness
1510
+ * timeout (the share of the caller's budget a launch may spend queued for admission), less the time
1511
+ * the request already spent queued, so concurrent resumes of one session never stack their waits.
1512
+ */
1513
+ function heldEndpointWaitBudget(broker: Broker, input: Input, mode: SessionOwnershipMode, readiness: number): number {
1514
+ const bound = Math.min(
1515
+ mode === "enforce" ? ENFORCE_HELD_ENDPOINT_WAIT_MS : OBSERVE_HELD_ENDPOINT_WAIT_MS,
1516
+ readiness,
1517
+ );
1518
+ const now = lifecycleTiming(broker).now();
1519
+ return Math.max(0, bound - (now - (lifecycleRequestsReceivedAt.get(input) ?? now)));
1520
+ }
1521
+
1522
+ /**
1523
+ * The broker's ownership mode now: its process mode, lowered by an explicit lower value in the
1524
+ * operator's config file, reread on each call. It is read at the probe and at every poll, so `off`
1525
+ * set during a wait ends it, and `observe` set during a wait stops its refusal.
1526
+ */
1527
+ function resumeOwnershipMode(): SessionOwnershipMode {
1528
+ return liveSessionOwnershipModeFor();
1529
+ }
1530
+
1531
+ /**
1532
+ * Another live process holds the session's claim. Probes, never claims. This process's own claim
1533
+ * (an in-process host or test) is not a writer a launched host would race, and `free` or `unknown`
1534
+ * (an unsupported platform, a stalled probe) keep resume's behaviour from before ownership, as does
1535
+ * `off`.
1536
+ */
1537
+ async function foreignSessionClaim(sessionId: string): Promise<{ holder: SessionOwnerHolder | undefined } | undefined> {
1538
+ if (resumeOwnershipMode() === "off") return undefined;
1539
+ try {
1540
+ const probe = await probeSessionOwner(sessionId);
1541
+ return probe.state === "held" && !probe.self ? { holder: probe.holder } : undefined;
1542
+ } catch (error) {
1543
+ logger.warn("sdk broker: session owner probe failed; resume continues as unheld", { error: String(error) });
1544
+ return undefined;
1545
+ }
1546
+ }
1547
+
1548
+ /**
1549
+ * Under `enforce`, a live generation-0 row of another process counts as a holder even while the
1550
+ * claim is free: a terminal taking the session over with Continue here (design §13 L1) appends it
1551
+ * before the broker closes the host, and claims only once the host has exited. A resume in that gap
1552
+ * waits for the terminal's endpoint instead of refusing the endpointless row or launching a host.
1553
+ */
1554
+ function handoverFence(authority: LiveResumeAuthority): { holder: SessionOwnerHolder | undefined } | undefined {
1555
+ return resumeOwnershipMode() === "enforce" &&
1556
+ authority.kind === "live" &&
1557
+ authority.record.endpointGeneration === 0 &&
1558
+ authority.record.pid !== process.pid
1559
+ ? { holder: undefined }
1560
+ : undefined;
1561
+ }
1562
+
1563
+ /**
1564
+ * The one outcome of a resume refused (under `enforce`) because another process holds the session
1565
+ * and has no endpoint to attach to: the resume wait ran out, or the launched host's claim was refused.
1566
+ * `live_session` is the code resume already uses for a live session it cannot attach to, and every
1567
+ * client already treats it as terminal; `holder` names it by surface and pid only (design §3.4).
1568
+ */
1569
+ function heldSessionResponse(sessionId: string, holder: SessionOwnerHolder | undefined): BrokerResponse {
1570
+ return { ok: false, error: heldSessionError(sessionId, holder) };
1571
+ }
1572
+
1573
+ function heldSessionError(
1574
+ sessionId: string,
1575
+ holder: SessionOwnerHolder | undefined,
1576
+ ): { code: "live_session"; message: string; holder?: SessionOwnerHolderSummary } {
1577
+ const summary = sessionOwnerHolderSummary(holder);
1578
+ return {
1579
+ code: "live_session",
1580
+ message: `Session ${sessionId} is open for writing in ${sessionOwnerHolderPhrase(holder)}, which has not published an SDK endpoint to attach to. Only one process can write a session at a time; try again once it is ready, or fork the session.`,
1581
+ ...(summary ? { holder: summary } : {}),
1582
+ };
1583
+ }
1584
+
1585
+ /**
1586
+ * The held outcome for a launched host whose own claim was refused, on the readiness path and the
1587
+ * reconciled terminal path alike. The holder comes from the host's startup failure, validated on read.
1588
+ */
1589
+ function hostHeldRefusalError(
1590
+ sessionId: string,
1591
+ failure: SdkStartupFailure,
1592
+ ): { code: "live_session"; message: string; holder?: SessionOwnerHolderSummary; endpoint: "unavailable" } {
1593
+ const holder = sessionOwnerHolderSummary((failure.details as { holder?: unknown } | undefined)?.holder);
1594
+ return { ...heldSessionError(sessionId, holder), endpoint: "unavailable" };
1595
+ }
1596
+
1597
+ /**
1598
+ * Resume's attach-or-wait (design §13 H3). Poll the index for up to `waitMs` until the holder's
1599
+ * endpoint is live, the holder lets go, or the authority turns ambiguous, and return the authority
1600
+ * to continue with. When the wait runs out with the holder still there, only `enforce` refuses
1601
+ * with the held outcome; `observe` never refuses, so resume goes on as before ownership (a launch,
1602
+ * whose host counts the conflict).
1603
+ */
1604
+ async function awaitHeldSessionEndpoint(
1605
+ broker: Broker,
1606
+ sessionId: string,
1607
+ holder: SessionOwnerHolder | undefined,
1608
+ waitMs: number,
1609
+ initial: LiveResumeAuthority,
1610
+ ): Promise<{ authority: LiveResumeAuthority; waitedMs: number } | BrokerResponse> {
1611
+ const timing = lifecycleTiming(broker);
1612
+ const startedAt = timing.now();
1613
+ let claim: { holder: SessionOwnerHolder | undefined } | undefined = { holder };
1614
+ let authority = initial;
1615
+ while (claim) {
1616
+ const remaining = startedAt + waitMs - timing.now();
1617
+ if (remaining <= 0) {
1618
+ if (resumeOwnershipMode() === "enforce") return heldSessionResponse(sessionId, claim.holder);
1619
+ break;
1620
+ }
1621
+ await timing.sleep(Math.min(HELD_SESSION_ENDPOINT_POLL_MS, remaining));
1622
+ await broker.index.refreshIfChanged();
1623
+ authority = liveResumeAuthority(broker.index.listSessions().sessions, sessionId);
1624
+ if (authority.kind === "ambiguous" || hasResumableEndpoint(authority, sessionId)) break;
1625
+ claim = (await foreignSessionClaim(sessionId)) ?? handoverFence(authority);
1626
+ }
1627
+ return { authority, waitedMs: timing.now() - startedAt };
1628
+ }
1629
+
1630
+ /** The readiness timeout a startup request asked for, from its deadline tuple or `readinessTimeoutMs`. */
1631
+ function requestedReadinessTimeout(input: Input, now: number): number | BrokerResponse {
1632
+ if (!deadlineFieldsPresent(input)) return readinessTimeout(input);
1633
+ const supplied = lifecycleDeadlines(input, now);
1634
+ return "ok" in supplied ? supplied : supplied.requestedReadinessTimeoutMs;
1635
+ }
1636
+
1465
1637
  type ValidatedTranscript = {
1466
1638
  path: string;
1467
1639
  id: string;
@@ -2594,7 +2766,25 @@ function isSdkStartupFailure(value: unknown): value is SdkStartupFailure {
2594
2766
  )
2595
2767
  return false;
2596
2768
  if (failure.code === undefined && failure.details === undefined) return keys.length === 3;
2597
- return keys.length === 5 && isModelProfileError(failure);
2769
+ return keys.length === 5 && (isModelProfileError(failure) || isSessionHeldStartupFailure(failure));
2770
+ }
2771
+
2772
+ /** A host's refused claim: `details` is `{}` or `{ holder }` with exactly a valid surface and pid. */
2773
+ function isSessionHeldStartupFailure(failure: Record<string, unknown>): boolean {
2774
+ if (failure.code !== SDK_STARTUP_SESSION_HELD_CODE) return false;
2775
+ const details = failure.details;
2776
+ if (typeof details !== "object" || details === null || Array.isArray(details)) return false;
2777
+ const keys = Object.keys(details);
2778
+ if (keys.length === 0) return true;
2779
+ const holder = (details as { holder?: unknown }).holder;
2780
+ return (
2781
+ keys.length === 1 &&
2782
+ keys[0] === "holder" &&
2783
+ typeof holder === "object" &&
2784
+ holder !== null &&
2785
+ Object.keys(holder).length === 2 &&
2786
+ sessionOwnerHolderSummary(holder) !== undefined
2787
+ );
2598
2788
  }
2599
2789
 
2600
2790
  function isLifecycleFailureArtifact(value: unknown): value is LifecycleFailureArtifact {
@@ -7057,6 +7247,7 @@ async function executeLifecycleResponse(
7057
7247
  identity: string,
7058
7248
  cleanup?: CleanupEvidence,
7059
7249
  onIdleHostExited?: (record: IndexedSession) => void,
7250
+ underDeleteClaim = false,
7060
7251
  ): Promise<BrokerResponse> {
7061
7252
  const requestedSessionId = cleanup && operation === "session.delete" ? cleanup.sessionId : sessionId(input);
7062
7253
  if (requestedSessionId !== undefined && !isCanonicalSessionId(requestedSessionId))
@@ -7096,6 +7287,9 @@ async function executeLifecycleResponse(
7096
7287
  // authority before validating the source session below.
7097
7288
  await broker.index.refresh();
7098
7289
  }
7290
+ // Time a resume already spent waiting for a holder's endpoint comes out of its startup
7291
+ // queue wait, so a launch after the holder let go still ends inside the caller's budget.
7292
+ let heldEndpointWaitedMs = 0;
7099
7293
  if (operation === "session.resume") {
7100
7294
  const requestedSessionId = sessionId(input);
7101
7295
  if (
@@ -7104,9 +7298,36 @@ async function executeLifecycleResponse(
7104
7298
  .sessions.some(session => session.sessionId === requestedSessionId && session.ephemeral)
7105
7299
  )
7106
7300
  return fail("ephemeral_unsupported", "Temporary sessions cannot be resumed.");
7107
- const authority = requestedSessionId
7301
+ let authority: LiveResumeAuthority = requestedSessionId
7108
7302
  ? liveResumeAuthority(broker.index.listSessions().sessions, requestedSessionId)
7109
- : { kind: "none" as const };
7303
+ : { kind: "none" };
7304
+ // No endpoint to reuse, and another process holds the session: wait for its endpoint
7305
+ // rather than launch a second writer. The admitted pass of a launch re-probes without
7306
+ // waiting, so under `enforce` a holder that claimed while the launch was queued refuses
7307
+ // it at once; `observe` launches.
7308
+ if (
7309
+ requestedSessionId &&
7310
+ authority.kind !== "ambiguous" &&
7311
+ !hasResumableEndpoint(authority, requestedSessionId)
7312
+ ) {
7313
+ const claim = (await foreignSessionClaim(requestedSessionId)) ?? handoverFence(authority);
7314
+ if (claim) {
7315
+ const readiness = startupAdmittedInputs.has(input)
7316
+ ? 0
7317
+ : requestedReadinessTimeout(input, lifecycleTiming(broker).now());
7318
+ if (typeof readiness !== "number") return readiness;
7319
+ const waited = await awaitHeldSessionEndpoint(
7320
+ broker,
7321
+ requestedSessionId,
7322
+ claim.holder,
7323
+ heldEndpointWaitBudget(broker, input, resumeOwnershipMode(), readiness),
7324
+ authority,
7325
+ );
7326
+ if ("ok" in waited) return waited;
7327
+ authority = waited.authority;
7328
+ heldEndpointWaitedMs = waited.waitedMs;
7329
+ }
7330
+ }
7110
7331
  if (authority.kind === "ambiguous")
7111
7332
  return fail("endpoint_stale", "Session authority is ambiguous and cannot be resumed safely.");
7112
7333
  const existing = authority.kind === "live" ? authority.record : undefined;
@@ -7160,24 +7381,10 @@ async function executeLifecycleResponse(
7160
7381
  const admissionGranted = startupAdmittedInputs.has(input);
7161
7382
  if (!admissionGranted) {
7162
7383
  const startupReceivedAt = timing.now();
7163
- const suppliedDeadlineFields = [
7164
- input.receivedAt,
7165
- input.requestedReadinessTimeoutMs,
7166
- input.semanticReadyDeadlineAt,
7167
- input.terminationStartDeadlineAt,
7168
- input.lifecycleCleanupDeadlineAt,
7169
- ];
7170
- let requestedReadinessTimeoutMs: number;
7171
- if (suppliedDeadlineFields.some(value => value !== undefined)) {
7172
- const supplied = lifecycleDeadlines(input, timing.now());
7173
- if ("ok" in supplied) return supplied;
7174
- requestedReadinessTimeoutMs = supplied.requestedReadinessTimeoutMs;
7175
- } else {
7176
- const timeout = readinessTimeout(input);
7177
- if (typeof timeout !== "number") return timeout;
7178
- requestedReadinessTimeoutMs = timeout;
7179
- }
7180
- const queueWaitMs = startupQueueWaitMs(requestedReadinessTimeoutMs);
7384
+ const callerSuppliedDeadlines = deadlineFieldsPresent(input);
7385
+ const requestedReadinessTimeoutMs = requestedReadinessTimeout(input, timing.now());
7386
+ if (typeof requestedReadinessTimeoutMs !== "number") return requestedReadinessTimeoutMs;
7387
+ const queueWaitMs = Math.max(0, startupQueueWaitMs(requestedReadinessTimeoutMs) - heldEndpointWaitedMs);
7181
7388
  const launch = await launchInput(broker, operation, input);
7182
7389
  if ("ok" in launch) return launch;
7183
7390
  if (launch.worktreePlan && deadlineFieldsPresent(input)) {
@@ -7187,7 +7394,6 @@ async function executeLifecycleResponse(
7187
7394
  );
7188
7395
  }
7189
7396
  const admitted = await broker.runStartup(queueWaitMs, timing, async admittedAt => {
7190
- const callerSuppliedDeadlines = suppliedDeadlineFields.some(value => value !== undefined);
7191
7397
  let admittedInput: Input;
7192
7398
  if (launch.worktreePlan) admittedInput = { ...input, admittedAt, requestedReadinessTimeoutMs };
7193
7399
  else if (callerSuppliedDeadlines) admittedInput = { ...input };
@@ -7667,6 +7873,8 @@ async function executeLifecycleResponse(
7667
7873
  "terminal_uncertain",
7668
7874
  `Session ${launch.id} did not become ready and its spawned process could not be verified dead. ${diagnostic ?? "stage=readiness waiting_for=session_ready child=uncertain exit=not_observed signal=not_observed stderr=none"}`,
7669
7875
  );
7876
+ if (readiness.kind === "startup_failed" && readiness.failure.code === SDK_STARTUP_SESSION_HELD_CODE)
7877
+ return { ok: false, error: hostHeldRefusalError(launch.id, readiness.failure) };
7670
7878
  return readiness.kind === "startup_failed"
7671
7879
  ? fail(
7672
7880
  readiness.failure.code ?? "spawn_failed",
@@ -7675,7 +7883,8 @@ async function executeLifecycleResponse(
7675
7883
  // leaves the broker.
7676
7884
  `${sanitizeSdkStartupMessage(readiness.failure.message, knownSecrets)} ${diagnostic ?? "stage=startup waiting_for=startup completion child=uncertain exit=not_observed signal=not_observed stderr=none"}`,
7677
7885
  undefined,
7678
- readiness.failure.details,
7886
+ // Only a model-profile failure carries details here; a held one returned above.
7887
+ readiness.failure.details as ModelProfileErrorDetails | undefined,
7679
7888
  )
7680
7889
  : readiness.kind === "ready_then_exited"
7681
7890
  ? readyThenExitedResponse(launch.id, child)
@@ -8033,6 +8242,35 @@ async function executeLifecycleResponse(
8033
8242
  if (record && !isSessionAuthorityEligible(record))
8034
8243
  return fail("endpoint_stale", "Session authority is ambiguous and cannot be deleted safely.");
8035
8244
  if (record?.live) return fail("live_session", "Refusing to delete a live session; close it first.");
8245
+ // Scoped claim (single-owner design §1 row 17), held for the whole delete: under enforce a session
8246
+ // another process holds without a live row (a `-p` run, an embedding, a TUI without the SDK) is
8247
+ // refused with the live-row refusal's code, before this request records any cleanup phase. `id` is the
8248
+ // requested id: the header id on a fresh delete (only the managed candidate whose header names it
8249
+ // is deleted) and `cleanup.sessionId` on a replay. Both refusals leave the key retryable
8250
+ // (broker.ts `isRetryableDeleteRefusal`). Lifecycle- and metadata-phase cleanup replays return from
8251
+ // `executeLifecycle` before this point and run without a claim. A host this broker
8252
+ // launched is never the holder here: its live row is refused above, and close waits for its exit.
8253
+ const ownership = resolveSessionOwnership();
8254
+ if (!underDeleteClaim && claimsUnder(ownership)) {
8255
+ let admitted = false;
8256
+ try {
8257
+ return await withScopedSessionClaim(ownership, id, "delete", () => {
8258
+ admitted = true;
8259
+ return executeLifecycleResponse(broker, operation, input, identity, cleanup, onIdleHostExited, true);
8260
+ });
8261
+ } catch (error) {
8262
+ // Only the claim's refusal is thrown before the delete is admitted. A real hold is the
8263
+ // live-row refusal, naming the holder; a claim that could not be checked has nothing to
8264
+ // close, so it is the retryable `unavailable`.
8265
+ if (admitted || !(error instanceof Error)) throw error;
8266
+ if (!(error.cause instanceof SessionHeldError)) return fail("unavailable", error.message);
8267
+ const holder = sessionOwnerHolderSummary(error.cause.holder);
8268
+ return {
8269
+ ok: false,
8270
+ error: { code: "live_session", message: error.message, ...(holder ? { holder } : {}) },
8271
+ };
8272
+ }
8273
+ }
8036
8274
  if (cleanup === undefined) {
8037
8275
  const requestedTranscriptPath = text(input.sessionPath);
8038
8276
  const requestedCwd = lifecycleCwd(input);
@@ -9429,18 +9667,21 @@ export async function executeLifecycle(
9429
9667
  : startupFailure && cleanupProof
9430
9668
  ? {
9431
9669
  ok: false,
9432
- error: startupFailure.code
9433
- ? {
9434
- code: startupFailure.code,
9435
- message: startupFailure.message,
9436
- details: startupFailure.details!,
9437
- endpoint: "unavailable" as const,
9438
- }
9439
- : {
9440
- code: "spawn_failed",
9441
- message: startupFailure.message,
9442
- endpoint: "unavailable" as const,
9443
- },
9670
+ error:
9671
+ startupFailure.code === SDK_STARTUP_SESSION_HELD_CODE
9672
+ ? hostHeldRefusalError(entry.intendedSessionId!, startupFailure)
9673
+ : startupFailure.code
9674
+ ? {
9675
+ code: startupFailure.code,
9676
+ message: startupFailure.message,
9677
+ details: startupFailure.details as ModelProfileErrorDetails,
9678
+ endpoint: "unavailable" as const,
9679
+ }
9680
+ : {
9681
+ code: "spawn_failed",
9682
+ message: startupFailure.message,
9683
+ endpoint: "unavailable" as const,
9684
+ },
9444
9685
  ...(durableEffects ? { durableEffects } : {}),
9445
9686
  startupFailure,
9446
9687
  }