@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
@@ -34,6 +34,7 @@ import {
34
34
  type AgentTerminalOwnerContext,
35
35
  type AgentTool,
36
36
  type AgentToolContext,
37
+ type ApiKeyResolution,
37
38
  activeToolForCallName,
38
39
  assertImagePlaceholdersHavePayload,
39
40
  type BeforeToolCallContext,
@@ -110,6 +111,7 @@ import type {
110
111
  Model,
111
112
  ProviderDispatch,
112
113
  ProviderSessionState,
114
+ ResolvedApiKey,
113
115
  ServiceTier,
114
116
  SimpleStreamOptions,
115
117
  StopReason,
@@ -569,6 +571,7 @@ import {
569
571
  FoldCoordinator,
570
572
  type ForegroundFoldOutcome,
571
573
  } from "./fold-coordinator";
574
+ import { reclaimCurrentSession, sessionClaimSetOf } from "./internal/session-claim-set";
572
575
  import type { MemoryGuardRestoreResult } from "./memory-guard-checkpoint-participant";
573
576
  import {
574
577
  type BashExecutionMessage,
@@ -1108,8 +1111,6 @@ export interface AgentSessionLifecycleState {
1108
1111
  export interface AgentSessionConfig {
1109
1112
  agent: Agent;
1110
1113
  sessionManager: SessionManager;
1111
- /** Internal root-TUI experiment only; never inherited by child sessions. */
1112
- rootInteractiveSharedAppend?: boolean;
1113
1114
  settings: Settings;
1114
1115
  /** The session's REQUESTED effective agent directory, independent of the
1115
1116
  * global Settings singleton (which may be reused across sessions). */
@@ -2682,6 +2683,9 @@ const POST_PUBLICATION_ERROR_MAX_BYTES = 512;
2682
2683
  */
2683
2684
  const COORDINATOR_PERSIST_CONTENTION_RETRIES = 3;
2684
2685
  const COORDINATOR_PERSIST_RETRY_DELAY_MS = 2_000;
2686
+ // A shared custom-message append refused as `stale/transcript_moved` committed nothing and is published again
2687
+ // against the relocated transcript; bounded so repeated relocations cannot loop.
2688
+ const SHARED_CUSTOM_APPEND_RELOCATION_RETRIES = 2;
2685
2689
 
2686
2690
  export type WorkerIntegrationOutcome =
2687
2691
  | { status: "completed" }
@@ -4509,6 +4513,12 @@ export class AgentSession {
4509
4513
  message: BashExecutionMessage;
4510
4514
  onPersisted?: () => void;
4511
4515
  appendedToAgent: boolean;
4516
+ /**
4517
+ * Set to `#deferredRefusalSequence` when this row's own save was refused (and
4518
+ * reported), so a transition drops it without a retry. In practice only lease
4519
+ * contention under shared publication refuses one.
4520
+ */
4521
+ refusedAt?: number;
4512
4522
  }> = [];
4513
4523
  /**
4514
4524
  * Set by a fold and consumed once by the pause checkpoint, so a fold ends its
@@ -4581,6 +4591,7 @@ export class AgentSession {
4581
4591
  job,
4582
4592
  durationMs: undefined,
4583
4593
  ownedCompletion,
4594
+ foldReceipt: true,
4584
4595
  });
4585
4596
  } finally {
4586
4597
  manager?.clearParkedDelivery(job.generation);
@@ -4669,7 +4680,17 @@ export class AgentSession {
4669
4680
  message: PythonExecutionMessage;
4670
4681
  onPersisted?: () => void;
4671
4682
  appendedToAgent: boolean;
4683
+ /**
4684
+ * Set to `#deferredRefusalSequence` when this row's own save was refused (and
4685
+ * reported), so a transition drops it without a retry. In practice only lease
4686
+ * contention under shared publication refuses one.
4687
+ */
4688
+ refusedAt?: number;
4672
4689
  }> = [];
4690
+ /** Counts refused deferred command-result saves; see `refusedAt`. */
4691
+ #deferredRefusalSequence = 0;
4692
+ /** `#deferredRefusalSequence` when the current session transition began. */
4693
+ #transitionRefusalFloor = 0;
4673
4694
  /** The one in-flight deferred command-result drain; later drains join it first. */
4674
4695
  #executionMessageDrain: Promise<void> | undefined;
4675
4696
  #activeEvalExecutions = new Set<Promise<unknown>>();
@@ -4759,7 +4780,6 @@ export class AgentSession {
4759
4780
  }
4760
4781
 
4761
4782
  #turnIndex = 0;
4762
- #rootInteractiveSharedAppend = false;
4763
4783
  #workerIntegrationScheduler: WorkerIntegrationRequestScheduler | undefined;
4764
4784
  #workerIntegrationRequestedForTurn = false;
4765
4785
  // First-party internal before-agent-start contributors (not user hooks).
@@ -4928,6 +4948,13 @@ export class AgentSession {
4928
4948
  #ttsrRetryToken = 0;
4929
4949
  #ttsrResumePromise: Promise<void> | undefined = undefined;
4930
4950
  #ttsrResumeResolve: (() => void) | undefined = undefined;
4951
+ /**
4952
+ * SDK terminal of a run a TTSR interrupt aborted, held for the resume that continues it.
4953
+ * Reserved by the agent_end handler while the resume is pending; the owning resume either
4954
+ * hands it to its continuation or releases it, so the original terminal publishes when no
4955
+ * continuation runs.
4956
+ */
4957
+ #ttsrResumeAgentEndHold: { hold: symbol; sdkOwnership: SdkContinuationOwnership } | undefined = undefined;
4931
4958
 
4932
4959
  /** One-shot flag set in InteractiveMode.#approvePlan(compactBeforeExecute=true)
4933
4960
  * before the plan-mode → compaction transition. Consumed inside
@@ -5278,6 +5305,13 @@ export class AgentSession {
5278
5305
  error: unknown;
5279
5306
  }> = [];
5280
5307
  #sessionTransitionCommitted = false;
5308
+ /**
5309
+ * The claim-set transition this session transition holds open (single-owner design §2.5): no claim
5310
+ * is released until it ends, so the predecessor stays claimed until the switch commits, and a
5311
+ * rollback or hook cancel releases the target instead. Kept as a handle, not looked up at the end,
5312
+ * because a bounded fork swaps the manager inside the transition.
5313
+ */
5314
+ #sessionClaimTransition: Disposable | undefined;
5281
5315
  #sessionTransitionCompletion: Promise<void> = Promise.resolve();
5282
5316
  #resolveSessionTransitionCompletion: (() => void) | undefined;
5283
5317
  #queuedDeliveryPendingWhileTransition = false;
@@ -5357,6 +5391,8 @@ export class AgentSession {
5357
5391
  { code: "busy" },
5358
5392
  );
5359
5393
  }
5394
+ // First fallible step, before any side effect: a throw here leaves no transition half begun.
5395
+ const claimTransition = sessionClaimSetOf(this.sessionManager).transition();
5360
5396
  if (["new-session", "switch-session", "clear-context", "fork", "branch", "navigate-tree"].includes(kind)) {
5361
5397
  for (const controller of this.#configurationReloadControllers) controller.abort();
5362
5398
  }
@@ -5366,6 +5402,9 @@ export class AgentSession {
5366
5402
  this.#btwPrefixScopes = new WeakMap();
5367
5403
  this.#sessionTransitionCommitted = false;
5368
5404
  this.#sessionTransitionKind = kind;
5405
+ this.#sessionClaimTransition = claimTransition;
5406
+ // Refusals after this point (the transition's own abort included) bound its settle.
5407
+ this.#transitionRefusalFloor = this.#deferredRefusalSequence;
5369
5408
  const completion = Promise.withResolvers<void>();
5370
5409
  this.#sessionTransitionCompletion = completion.promise;
5371
5410
  this.#resolveSessionTransitionCompletion = completion.resolve;
@@ -5386,6 +5425,80 @@ export class AgentSession {
5386
5425
  await awaitBtwSettlement(this.#joinBtwTurns());
5387
5426
  }
5388
5427
 
5428
+ /**
5429
+ * Settle the predecessor before a history transition mutates its history or
5430
+ * identity: its deferred command results, then its /btw turns. Call only after the
5431
+ * main-agent abort. `/clear` keeps its own background-publication join.
5432
+ */
5433
+ async #settlePredecessorForSessionTransition(): Promise<void> {
5434
+ await this.#settlePredecessorPublicationsForTransition();
5435
+ await this.#settleBtwForSessionTransition();
5436
+ }
5437
+
5438
+ /**
5439
+ * Save the predecessor's deferred `!`/`$` results to the predecessor before a
5440
+ * transition replaces its history or session. The abort only waits for them while
5441
+ * the turn is live; once it has ended, its drain can still be publishing through
5442
+ * the shared lease and would append its later rows to the successor's agent state
5443
+ * and transcript. Join that whole flush (it is one tracked background publication,
5444
+ * both kinds), then publish every queued row whose own save has not been refused,
5445
+ * so each result lands once where it was typed.
5446
+ *
5447
+ * Nothing unsaved stays queued past this point, whether or not the transition then
5448
+ * commits, so no refused row is re-appended behind rows saved now. A row whose own
5449
+ * save was refused showed its notice and is dropped without a retry. A kind refused
5450
+ * since the transition began (by its own abort's flush, or by the drain joined here)
5451
+ * is not attempted again: under a lease
5452
+ * another writer keeps holding, each attempt costs a full lock-wait budget, so this
5453
+ * bounds the settle at one budget per kind. Every other row left unsaved is dropped
5454
+ * with a notice of its own.
5455
+ */
5456
+ async #settlePredecessorPublicationsForTransition(): Promise<void> {
5457
+ await this.#joinBackgroundPublications();
5458
+ const blocked = "an earlier command result could not be saved";
5459
+ const keepUnrefused = <T extends { refusedAt?: number }>(queue: T[]): void => {
5460
+ const refusedSinceTransition = queue.some(pending => (pending.refusedAt ?? 0) > this.#transitionRefusalFloor);
5461
+ const kept = queue.filter(pending => {
5462
+ if (pending.refusedAt !== undefined) return false;
5463
+ if (refusedSinceTransition) this.#reportBackgroundRefusal("deferred command result", blocked);
5464
+ return !refusedSinceTransition;
5465
+ });
5466
+ queue.splice(0, queue.length, ...kept);
5467
+ };
5468
+ keepUnrefused(this.#pendingBashMessages);
5469
+ keepUnrefused(this.#pendingPythonMessages);
5470
+ try {
5471
+ await this.#flushPendingPromptMessages();
5472
+ } catch (error) {
5473
+ logger.warn("Deferred command results were not saved before the session transition", {
5474
+ error: String(error),
5475
+ });
5476
+ } finally {
5477
+ // Rows queued behind a row refused just now were never attempted: report them too.
5478
+ for (const pending of [...this.#pendingBashMessages, ...this.#pendingPythonMessages]) {
5479
+ if (pending.refusedAt === undefined) this.#reportBackgroundRefusal("deferred command result", blocked);
5480
+ }
5481
+ this.#pendingBashMessages.length = 0;
5482
+ this.#pendingPythonMessages.length = 0;
5483
+ }
5484
+ }
5485
+
5486
+ /**
5487
+ * At a transition's commit, drop deferred results still queued for the
5488
+ * predecessor, each with its notice. The settle leaves nothing queued; this only
5489
+ * catches a result recorded between the settle and the commit (an auto-triggered
5490
+ * handoff's prompt lifecycle), which the next prompt would otherwise append to the
5491
+ * successor.
5492
+ */
5493
+ #dropUnsavedDeferredResultsAtCommit(): void {
5494
+ const unsaved = this.#pendingBashMessages.length + this.#pendingPythonMessages.length;
5495
+ for (let row = 0; row < unsaved; row++) {
5496
+ this.#reportBackgroundRefusal("deferred command result", "the session changed before it could be saved");
5497
+ }
5498
+ this.#pendingBashMessages.length = 0;
5499
+ this.#pendingPythonMessages.length = 0;
5500
+ }
5501
+
5389
5502
  #commitSessionTransition(): void {
5390
5503
  if (!this.#sessionTransitionCommitted) {
5391
5504
  this.#sessionTransitionCommitted = true;
@@ -5427,6 +5540,14 @@ export class AgentSession {
5427
5540
  }
5428
5541
 
5429
5542
  #endSessionTransition(): void {
5543
+ const claimTransition = this.#sessionClaimTransition;
5544
+ this.#sessionClaimTransition = undefined;
5545
+ try {
5546
+ claimTransition?.[Symbol.dispose]();
5547
+ } catch (error) {
5548
+ // A failed unlock must not keep the transition lease busy.
5549
+ logger.warn("Session claim settle failed at transition end", { error: String(error) });
5550
+ }
5430
5551
  this.#sessionTransitionKind = undefined;
5431
5552
  this.#sessionTransitionCommitted = false;
5432
5553
  const resolveCompletion = this.#resolveSessionTransitionCompletion;
@@ -6301,7 +6422,16 @@ export class AgentSession {
6301
6422
  return false;
6302
6423
  }
6303
6424
 
6304
- async #flushPendingPromptMessages(): Promise<void> {
6425
+ /**
6426
+ * The whole flush is one tracked background publication, so
6427
+ * {@link #joinBackgroundPublications} covers rows its drain has not reached yet,
6428
+ * not only the row currently at the lease.
6429
+ */
6430
+ #flushPendingPromptMessages(): Promise<void> {
6431
+ return this.#trackBackgroundPublication(this.#drainPendingPromptMessages());
6432
+ }
6433
+
6434
+ async #drainPendingPromptMessages(): Promise<void> {
6305
6435
  const errors: unknown[] = [];
6306
6436
  try {
6307
6437
  await this.#flushPendingBashMessages();
@@ -6566,7 +6696,6 @@ export class AgentSession {
6566
6696
  });
6567
6697
  this.agent.bindRunCancellationDomainBridge(this.#runCancellationDomains, this.#agentSessionClaimKey);
6568
6698
  this.sessionManager = config.sessionManager;
6569
- this.#rootInteractiveSharedAppend = config.rootInteractiveSharedAppend === true;
6570
6699
  this.settings = config.settings;
6571
6700
  this.#requestedAgentDir = config.agentDir ? path.resolve(config.agentDir) : undefined;
6572
6701
  this.sessionManager.setSessionMemoryMode(this.settings.get("sessionMemory.mode"));
@@ -6788,7 +6917,7 @@ export class AgentSession {
6788
6917
  const originalGetApiKey = this.agent.getApiKey;
6789
6918
  if (originalGetApiKey) {
6790
6919
  const invokeOriginalGetApiKey = originalGetApiKey.bind(this.agent);
6791
- const managedGetApiKey = async (provider: string): Promise<string | undefined> => {
6920
+ const managedGetApiKey = async (provider: string): Promise<ApiKeyResolution> => {
6792
6921
  const override = this.#managedFallbackNextCredentialOverride;
6793
6922
  const model = this.model;
6794
6923
  const controller = this.#defaultFallbackController;
@@ -6805,12 +6934,14 @@ export class AgentSession {
6805
6934
  if (shouldCapture && modelKey) this.#managedFallbackActiveCredentialRows.delete(modelKey);
6806
6935
  if (override && model && storageProvider === override.storageProvider && modelKey === override.modelKey) {
6807
6936
  this.#managedFallbackNextCredentialOverride = undefined;
6808
- const apiKey = await this.#modelRegistry.getApiKey(model, this.credentialSessionId, {
6809
- credentialSelector: { kind: "id", value: String(override.rowId) },
6810
- });
6937
+ const { apiKey, credentialRowId } = await this.#modelRegistry.getApiKeyWithCredentialRowId(
6938
+ model,
6939
+ this.credentialSessionId,
6940
+ { credentialSelector: { kind: "id", value: String(override.rowId) } },
6941
+ );
6811
6942
  if (isAuthenticated(apiKey)) {
6812
6943
  if (shouldCapture && model) this.#captureManagedFallbackActiveCredential(model);
6813
- return apiKey;
6944
+ return credentialRowId === undefined ? apiKey : { apiKey, credentialId: credentialRowId };
6814
6945
  }
6815
6946
  // The preselected credential is no longer available; try to resolve another one of the same kind.
6816
6947
  const fallbackApiKey = await this.#resolveManagedFallbackCredentialRow(model, override.credentialKind);
@@ -6820,9 +6951,10 @@ export class AgentSession {
6820
6951
  }
6821
6952
  throw new Error("Selected managed fallback credential is no longer available");
6822
6953
  }
6823
- const apiKey = await invokeOriginalGetApiKey(provider);
6954
+ const resolution = await invokeOriginalGetApiKey(provider);
6955
+ const apiKey = typeof resolution === "string" ? resolution : resolution?.apiKey;
6824
6956
  if (shouldCapture && model && isAuthenticated(apiKey)) this.#captureManagedFallbackActiveCredential(model);
6825
- return apiKey;
6957
+ return resolution;
6826
6958
  };
6827
6959
  this.agent.getApiKey = managedGetApiKey;
6828
6960
  this.#restoreManagedFallbackGetApiKey = () => {
@@ -6945,6 +7077,22 @@ export class AgentSession {
6945
7077
  await awaitPromptInvocationPreflight(this.agent.waitForIdle(), signal);
6946
7078
  if (settleIfDisposing()) return;
6947
7079
  }
7080
+ // An idle delivery starts a turn without #promptWithMessage: the same ownership gate. A
7081
+ // refused delivery is dropped (the yield queue logs the rejection), so say so.
7082
+ const ownershipGate = this.#sessionOwnershipTurnGate();
7083
+ if (ownershipGate) {
7084
+ try {
7085
+ await ownershipGate;
7086
+ } catch (error) {
7087
+ this.emitNotice(
7088
+ "warning",
7089
+ `A background result was not delivered: ${operatorErrorMessage(error)}`,
7090
+ "session-ownership",
7091
+ );
7092
+ throw error;
7093
+ }
7094
+ if (settleIfDisposing()) return;
7095
+ }
6948
7096
  if (survivors.some(message => ownedCompletionResumeAction(message) === "fresh"))
6949
7097
  this.#resumeFromOwnedCompletion();
6950
7098
  if (survivors.length === 1) {
@@ -6988,6 +7136,26 @@ export class AgentSession {
6988
7136
  getIdleFlushSignal: () => this.#postPromptTasksAbortController.signal,
6989
7137
  });
6990
7138
  this.agent.setOnBeforeYield(() => this.yieldQueue.flush("streaming"));
7139
+ // Step-boundary delivery: eligible entries (ordinary async results, MCP
7140
+ // notifications) reach the running turn at its next tool step instead of
7141
+ // waiting for before-yield, which would force an extra iteration after the
7142
+ // final answer. Entries whose ownership classifies "fresh" or "drop" and
7143
+ // fold receipts are ineligible by their dispatcher and keep the
7144
+ // before-yield/idle path above. Transitions, abort unwinds and disposal
7145
+ // leave the queue untouched.
7146
+ this.agent.setStepBoundaryMessageProvider(() => {
7147
+ if (this.#sessionTransitionKind !== undefined || this.#handoffTransitionActive) return [];
7148
+ if (this.#abortUnwind !== undefined || this.#isDisposed || this.#sessionAdmissionClosing) return [];
7149
+ const messages = this.yieldQueue.drainStepBoundary();
7150
+ // This is the delivery boundary for these messages (the loop commits
7151
+ // them synchronously), so settle their terminal owned registrations as
7152
+ // onFollowUpConsumed does; unsettled tuples would fill the bounded
7153
+ // registry until later owned aborts fail closed. No SDK run token or
7154
+ // fresh lineage applies: these entries were never queued as SDK input
7155
+ // and "fresh" entries are not eligible here.
7156
+ this.#settleDeliveredOwnedRegistrations(messages);
7157
+ return messages;
7158
+ });
6991
7159
  // Stop-after-result, never abort: a fold arms this once and the loop ends the
6992
7160
  // turn at its next checkpoint. Consuming the flag here keeps the pause scoped
6993
7161
  // to the folded turn instead of pausing everything that follows. The
@@ -8296,6 +8464,7 @@ export class AgentSession {
8296
8464
  lease: OwnerSubagentShutdownLease,
8297
8465
  ownerId: string,
8298
8466
  predecessorEndpointId: string,
8467
+ predecessorSessionId: string,
8299
8468
  ): void {
8300
8469
  const finalization = (async () => {
8301
8470
  while (!this.#isDisposed) {
@@ -8327,6 +8496,9 @@ export class AgentSession {
8327
8496
  })();
8328
8497
  this.#deferredOwnerShutdownFinalizations.add(finalization);
8329
8498
  void finalization.finally(() => this.#deferredOwnerShutdownFinalizations.delete(finalization));
8499
+ // The predecessor's claim waits for this finalization, at most the cap (design §2.5). Scheduled
8500
+ // inside the switch's open claim-set transition, so the claim is still in the set to hold.
8501
+ sessionClaimSetOf(this.sessionManager).holdUntil(predecessorSessionId, finalization);
8330
8502
  }
8331
8503
 
8332
8504
  #suppressOwnAsyncJobDeliveries(): void {
@@ -8350,13 +8522,21 @@ export class AgentSession {
8350
8522
  // Event Subscription
8351
8523
  // =========================================================================
8352
8524
 
8353
- /** Emit an event to all listeners without letting one subscriber poison lifecycle settlement. */
8525
+ /**
8526
+ * Emit an event to all listeners without letting one subscriber poison lifecycle settlement.
8527
+ * Subscribers run outside this session's admission context: an event emitted inside an
8528
+ * admitted turn (auto_compaction_end from pre-prompt maintenance) must not hand that turn's
8529
+ * admission ownership to subscriber continuations, or a UI replay of input queued during
8530
+ * compaction is refused as same-session reentrancy and stranded.
8531
+ */
8354
8532
  #emit(event: AgentSessionEvent): void {
8355
- for (const listener of this.#eventListenerSnapshot) {
8356
- deliverSessionEvent(listener, event, error => {
8357
- logger.warn("Agent session event subscriber failed", { event: event.type, error: String(error) });
8358
- });
8359
- }
8533
+ this.#sessionAdmissionContext.exit(() => {
8534
+ for (const listener of this.#eventListenerSnapshot) {
8535
+ deliverSessionEvent(listener, event, error => {
8536
+ logger.warn("Agent session event subscriber failed", { event: event.type, error: String(error) });
8537
+ });
8538
+ }
8539
+ });
8360
8540
  }
8361
8541
 
8362
8542
  /** Notify UI projections after a committed session-identity transition. */
@@ -8388,6 +8568,28 @@ export class AgentSession {
8388
8568
  this.#emit({ type: "notice", level, message, source });
8389
8569
  }
8390
8570
 
8571
+ /**
8572
+ * Turn start's ownership gate (single-owner design §2.7, §13.1), before the turn writes anything:
8573
+ * a current session whose claim was not taken (another process held it, or the lock timed out or
8574
+ * failed) is claimed again, with backoff. Under enforce, a turn on a session another process now
8575
+ * holds is refused with its `SessionHeldError`, and the holder keeps the session; a lock that times
8576
+ * out again lets this one turn run unclaimed, with a notice. `undefined`, with nothing awaited, when
8577
+ * there is nothing to re-attempt (off, an exempt child, a claimed session), so ordering is unchanged.
8578
+ */
8579
+ #sessionOwnershipTurnGate(): Promise<void> | undefined {
8580
+ const reclaim = reclaimCurrentSession(this.sessionManager);
8581
+ return reclaim?.then(result => {
8582
+ if (result.refusal) throw result.refusal;
8583
+ const ownership = this.sessionManager.ownershipDecision;
8584
+ if (result.status === "timed_out" && ownership !== "exempt" && ownership.mode === "enforce")
8585
+ this.emitNotice(
8586
+ "warning",
8587
+ "gjc could not check whether another process has this session open (the lock timed out), so this turn runs without a claim. It tries again on a later turn.",
8588
+ "session-ownership",
8589
+ );
8590
+ });
8591
+ }
8592
+
8391
8593
  #queuedExtensionEvents: Promise<void> = Promise.resolve();
8392
8594
 
8393
8595
  #queueExtensionEvent(
@@ -9468,6 +9670,20 @@ export class AgentSession {
9468
9670
  }
9469
9671
 
9470
9672
  await this.#emitSessionEvent(displayEvent, eventLease);
9673
+ // A TTSR interrupt ended this SDK run only to resume it. Hold its terminal for that resume,
9674
+ // like the other continuations, so the SDK prompt is not settled as cancelled while the
9675
+ // agent continues. The owning resume hands the hold to its continuation or releases it.
9676
+ if (
9677
+ event.type === "agent_end" &&
9678
+ ttsrResumePendingAtTerminal &&
9679
+ this.#ttsrAbortPending &&
9680
+ event.stopReason === "cancelled" &&
9681
+ terminalSdkOwnership
9682
+ ) {
9683
+ this.#releaseTtsrResumeAgentEndHold();
9684
+ const hold = this.#reserveDeferredAgentEndForContinuation(attemptScope);
9685
+ if (hold) this.#ttsrResumeAgentEndHold = { hold, sdkOwnership: terminalSdkOwnership };
9686
+ }
9471
9687
  if (event.type === "message_end" && event.message.role === "assistant") {
9472
9688
  this.#assistantAttemptScopes.set(event.message, {
9473
9689
  scope: attemptScope,
@@ -9829,7 +10045,15 @@ export class AgentSession {
9829
10045
  msg.provider === "github-copilot" &&
9830
10046
  msg.errorMessage?.includes("GitHub Copilot authentication failed")
9831
10047
  ) {
9832
- await this.#modelRegistry.authStorage.remove("github-copilot");
10048
+ try {
10049
+ await this.#modelRegistry.authStorage.remove("github-copilot");
10050
+ } catch (error) {
10051
+ // The credential is still stored; the next authentication failure retries the
10052
+ // invalidation. Post-turn handling must still run.
10053
+ logger.warn("Failed to invalidate GitHub Copilot credentials after an auth failure", {
10054
+ error: String(error),
10055
+ });
10056
+ }
9833
10057
  }
9834
10058
 
9835
10059
  if (this.#skipPostTurnMaintenanceAssistantTimestamp === msg.timestamp) {
@@ -10153,6 +10377,19 @@ export class AgentSession {
10153
10377
  this.#ttsrResumePromise = undefined;
10154
10378
  }
10155
10379
 
10380
+ /** Take the held interrupted SDK terminal for the resume that continues it. */
10381
+ #takeTtsrResumeAgentEndHold(): { hold: symbol; sdkOwnership: SdkContinuationOwnership } | undefined {
10382
+ const held = this.#ttsrResumeAgentEndHold;
10383
+ this.#ttsrResumeAgentEndHold = undefined;
10384
+ return held;
10385
+ }
10386
+
10387
+ /** A TTSR resume that will not continue publishes the interrupted terminal it held. */
10388
+ #releaseTtsrResumeAgentEndHold(): void {
10389
+ const held = this.#takeTtsrResumeAgentEndHold();
10390
+ if (held) this.#releaseDeferredAgentEndContinuation(held.hold);
10391
+ }
10392
+
10156
10393
  /**
10157
10394
  * Abort/recovery cleanup: drop queued TTSR follow-up reminders and release
10158
10395
  * reminders bucketed onto tool calls whose results will not be delivered.
@@ -11581,8 +11818,25 @@ export class AgentSession {
11581
11818
  // The resume continues this request. Captured by identity so that whichever way the resume ends, a
11582
11819
  // late cleanup can only end the request it was scheduled for, never a newer admission's.
11583
11820
  const recapRequest = this.#recapRequest;
11821
+ // A throw before the continuation takes over (for example a failed injection marker append)
11822
+ // must not strand the held SDK terminal or leave the interrupt pending.
11823
+ const releaseOnThrow =
11824
+ (task: (signal: AbortSignal) => Promise<void>) =>
11825
+ async (signal: AbortSignal): Promise<void> => {
11826
+ try {
11827
+ await task(signal);
11828
+ } catch (error) {
11829
+ if (this.#ttsrRetryToken === retryToken) {
11830
+ this.#ttsrAbortPending = false;
11831
+ this.#releaseTtsrResumeAgentEndHold();
11832
+ this.#resolveTtsrResume();
11833
+ this.#endSessionRecapRequestIf(recapRequest);
11834
+ }
11835
+ throw error;
11836
+ }
11837
+ };
11584
11838
  this.#schedulePostPromptTask(
11585
- async signal => {
11839
+ releaseOnThrow(async signal => {
11586
11840
  if (this.#ttsrRetryToken !== retryToken) {
11587
11841
  // A newer interrupt owns the resume (and the same request); leave the request to it.
11588
11842
  this.#resolveTtsrResume();
@@ -11592,6 +11846,7 @@ export class AgentSession {
11592
11846
  this.#ttsrAbortPending = false;
11593
11847
  this.#pendingTtsrInjections = [];
11594
11848
  this.#releasePerToolTtsrInjections();
11849
+ this.#releaseTtsrResumeAgentEndHold();
11595
11850
  this.#resolveTtsrResume();
11596
11851
  this.#endSessionRecapRequestIf(recapRequest);
11597
11852
  return;
@@ -11707,6 +11962,7 @@ export class AgentSession {
11707
11962
  if (!ownsRetry()) return;
11708
11963
  this.#ttsrAbortPending = false;
11709
11964
  releaseCarriedTtsr();
11965
+ this.#releaseTtsrResumeAgentEndHold();
11710
11966
  this.#resolveTtsrResume();
11711
11967
  this.#endSessionRecapRequestIf(recapRequest);
11712
11968
  };
@@ -11868,30 +12124,40 @@ export class AgentSession {
11868
12124
  // the still-eligible rule when this session is reopened.
11869
12125
  this.#markTtsrInjected(details.rules, publicationFailure === undefined, ttsrMessageCount);
11870
12126
  }
12127
+ // The continuation inherits the held SDK terminal and its owner, like overflow retry and
12128
+ // auto-retry: the resumed run settles the SDK prompt, and skip or failure releases the
12129
+ // hold so the interrupted terminal still publishes.
12130
+ const heldTerminal = this.#takeTtsrResumeAgentEndHold();
11871
12131
  await this.#scheduleAgentContinue({
11872
12132
  delayMs: 0,
11873
12133
  generation,
12134
+ predecessorAgentEndHold: heldTerminal?.hold,
12135
+ sdkOwnership: heldTerminal?.sdkOwnership,
11874
12136
  // Owner-guarded like the outer onSkip: a newer interrupt may own the resume.
11875
12137
  shouldContinue: () => {
11876
12138
  if (this.#ttsrRetryToken !== retryToken) return false;
11877
12139
  this.#ttsrAbortPending = false;
12140
+ // A terminal reserved after the hold was taken has no continuation to inherit it.
12141
+ this.#releaseTtsrResumeAgentEndHold();
11878
12142
  return true;
11879
12143
  },
11880
12144
  onSkip: () => {
11881
12145
  if (this.#ttsrRetryToken !== retryToken) return;
11882
12146
  this.#ttsrAbortPending = false;
12147
+ this.#releaseTtsrResumeAgentEndHold();
11883
12148
  this.#resolveTtsrResume();
11884
12149
  this.#endSessionRecapRequestIf(recapRequest);
11885
12150
  },
11886
12151
  onError: () => {
11887
12152
  if (this.#ttsrRetryToken !== retryToken) return;
11888
12153
  this.#ttsrAbortPending = false;
12154
+ this.#releaseTtsrResumeAgentEndHold();
11889
12155
  this.#resolveTtsrResume();
11890
12156
  this.#endSessionRecapRequestIf(recapRequest);
11891
12157
  },
11892
12158
  resourceRunId: activePromptHandle,
11893
12159
  });
11894
- },
12160
+ }),
11895
12161
  {
11896
12162
  delayMs: 50,
11897
12163
  resourceRunId: activePromptHandle,
@@ -11900,6 +12166,7 @@ export class AgentSession {
11900
12166
  onSkip: () => {
11901
12167
  if (this.#ttsrRetryToken !== retryToken) return;
11902
12168
  this.#ttsrAbortPending = false;
12169
+ this.#releaseTtsrResumeAgentEndHold();
11903
12170
  this.#resolveTtsrResume();
11904
12171
  this.#endSessionRecapRequestIf(recapRequest);
11905
12172
  },
@@ -13300,6 +13567,7 @@ export class AgentSession {
13300
13567
  this.#drainTerminalOwnedYieldEntries();
13301
13568
 
13302
13569
  this.agent.setOnBeforeYield(undefined);
13570
+ this.agent.setStepBoundaryMessageProvider(undefined);
13303
13571
  try {
13304
13572
  if (this.#extensionRunner?.hasHandlers("session_shutdown")) {
13305
13573
  await awaitDisposeStep(
@@ -16330,7 +16598,10 @@ export class AgentSession {
16330
16598
  }
16331
16599
  await this.#awaitStartupTurnBarrier();
16332
16600
  if (this.#sessionAdmissionClosed || this.#isDisposed) throw this.#sessionAdmissionBusyError();
16333
- await this.#withSessionAdmission("prompt", async () => {});
16601
+ await this.#withSessionAdmission("prompt", async () => {
16602
+ const ownershipGate = this.#sessionOwnershipTurnGate();
16603
+ if (ownershipGate) await ownershipGate;
16604
+ });
16334
16605
  const inFlightPrompt = this.#beginInFlight();
16335
16606
  let hindsightRecall: string | undefined;
16336
16607
  let continuationSdkRunToken: string | undefined;
@@ -17622,14 +17893,40 @@ export class AgentSession {
17622
17893
  observationId,
17623
17894
  );
17624
17895
  }
17625
- const outcome = await this.sessionManager.appendCustomMessageEntrySharingSession(
17626
- customType,
17627
- content,
17628
- display,
17629
- details,
17630
- attribution,
17631
- observationId,
17632
- );
17896
+ const manager = this.sessionManager;
17897
+ const sessionId = manager.getSessionId();
17898
+ const identityGeneration = manager.getSessionIdentityGeneration();
17899
+ const publish = () =>
17900
+ manager.appendCustomMessageEntrySharingSession(
17901
+ customType,
17902
+ content,
17903
+ display,
17904
+ details,
17905
+ attribution,
17906
+ observationId,
17907
+ );
17908
+ let outcome = await publish();
17909
+ // A relocation of this session's transcript (a task child following its parent's session move) between the
17910
+ // append capturing its path and its transaction refuses the append before any write. Nothing was committed, so
17911
+ // it is published again against the relocated transcript; the caller's in-memory message is not touched. Only
17912
+ // for the same manager, session id and identity generation, and outside every session transition: a switch or
17913
+ // copy reports the same reason and must not receive this entry, and while it is being adopted the successor's
17914
+ // transcript can already be in place before the id or generation changes. Every other outcome stays final,
17915
+ // since an `unknown` one may already be committed.
17916
+ for (
17917
+ let retry = 0;
17918
+ retry < SHARED_CUSTOM_APPEND_RELOCATION_RETRIES &&
17919
+ outcome.kind === "stale" &&
17920
+ outcome.reason === "transcript_moved" &&
17921
+ this.#sessionTransitionKind === undefined &&
17922
+ !this.#handoffTransitionActive &&
17923
+ this.sessionManager === manager &&
17924
+ manager.getSessionId() === sessionId &&
17925
+ manager.getSessionIdentityGeneration() === identityGeneration;
17926
+ retry++
17927
+ ) {
17928
+ outcome = await publish();
17929
+ }
17633
17930
  if (outcome.kind !== "committed") {
17634
17931
  throw new Error(
17635
17932
  `Shared custom message append ${outcome.kind}${outcome.kind === "stale" ? `: ${outcome.reason}` : ""}${outcome.kind === "unknown" ? ` (attempted id: ${outcome.id})` : ""}`,
@@ -17842,12 +18139,31 @@ export class AgentSession {
17842
18139
  * the attempted id: the caller must never re-append it under a new id.
17843
18140
  */
17844
18141
  async #persistExecutionMessage(label: string, message: SessionPersistedMessage): Promise<void> {
18142
+ // Every failed save is reported, so a row the caller drops is never dropped silently.
18143
+ const reportThrown = (error: unknown): never => {
18144
+ this.#reportBackgroundRefusal(label, error instanceof Error ? error.message : String(error));
18145
+ throw error;
18146
+ };
17845
18147
  if (!this.#usesSharedSessionPublication()) {
17846
- this.sessionManager.appendMessage(message);
18148
+ try {
18149
+ this.sessionManager.appendMessage(message);
18150
+ } catch (error) {
18151
+ reportThrown(error);
18152
+ }
17847
18153
  return;
17848
18154
  }
17849
- const outcome = await this.#trackBackgroundPublication(this.sessionManager.appendMessageSharingSession(message));
17850
- if (outcome.kind !== "committed") {
18155
+ const outcome = await this.#trackBackgroundPublication(
18156
+ this.sessionManager.appendMessageSharingSession(message),
18157
+ ).catch(reportThrown);
18158
+ if (outcome.kind === "unknown") {
18159
+ // The entry may already be durable: do not report it as unsaved.
18160
+ if (!this.#isDisposed)
18161
+ this.emitNotice(
18162
+ "warning",
18163
+ `The ${label} may not have been saved to this session (outcome unknown).`,
18164
+ "session-publication",
18165
+ );
18166
+ } else if (outcome.kind !== "committed") {
17851
18167
  const cause = describeSharedAppendFailure(outcome);
17852
18168
  this.#reportBackgroundRefusal(label, cause.reason ?? cause.outcome);
17853
18169
  }
@@ -18600,6 +18916,11 @@ export class AgentSession {
18600
18916
  this.#assertNoHandoffTransition();
18601
18917
  if (options?.preflightSignal?.aborted) throw promptPreflightCancelledError();
18602
18918
  await awaitPromptInvocationPreflight(this.#agentEndPublicationPromise, options?.preflightSignal);
18919
+ const ownershipGate = this.#sessionOwnershipTurnGate();
18920
+ if (ownershipGate) {
18921
+ await ownershipGate;
18922
+ if (options?.preflightSignal?.aborted) throw promptPreflightCancelledError();
18923
+ }
18603
18924
  // Re-check after the publication await: a handoff can engage during that
18604
18925
  // window, and #beginInFlight below would otherwise start a turn against the
18605
18926
  // session being handed off.
@@ -22354,6 +22675,8 @@ export class AgentSession {
22354
22675
  if (options?.drop) {
22355
22676
  try {
22356
22677
  this.sessionManager.assertLegacyMutationAllowed("drop session");
22678
+ // On the legacy route, a transcript another process changed is not this opener's to delete.
22679
+ this.sessionManager.assertTranscriptUnchanged();
22357
22680
  } catch (error) {
22358
22681
  return Promise.reject(error);
22359
22682
  }
@@ -22423,7 +22746,7 @@ export class AgentSession {
22423
22746
  await Bun.sleep(10);
22424
22747
  }
22425
22748
  }
22426
- await this.#settleBtwForSessionTransition();
22749
+ await this.#settlePredecessorForSessionTransition();
22427
22750
  this.#cancelOwnAsyncJobs();
22428
22751
  this.#closeAllProviderSessions("new session");
22429
22752
  this.#rebindProviderSessionState(new Map());
@@ -22462,6 +22785,7 @@ export class AgentSession {
22462
22785
  this.#steeringMessages = [];
22463
22786
  this.#followUpMessages = [];
22464
22787
  this.#pendingNextTurnMessages = [];
22788
+ this.#dropUnsavedDeferredResultsAtCommit();
22465
22789
  this.#scheduledHiddenNextTurnGeneration = undefined;
22466
22790
  await this.#initializeNewSessionState(nextDiscoverySessionNonMCPToolNames, previousSessionFile);
22467
22791
  if (options?.drop && previousSessionFile) {
@@ -22508,7 +22832,7 @@ export class AgentSession {
22508
22832
  return false;
22509
22833
  }
22510
22834
 
22511
- await this.#settleBtwForSessionTransition();
22835
+ await this.#settlePredecessorForSessionTransition();
22512
22836
  if (!(await manager.waitForOwnerInFlightDeliveries(ownerId))) {
22513
22837
  throw new Error("Owned async deliveries did not settle before session replacement.");
22514
22838
  }
@@ -22552,6 +22876,7 @@ export class AgentSession {
22552
22876
  this.#steeringMessages = [];
22553
22877
  this.#followUpMessages = [];
22554
22878
  this.#pendingNextTurnMessages = [];
22879
+ this.#dropUnsavedDeferredResultsAtCommit();
22555
22880
  this.#scheduledHiddenNextTurnGeneration = undefined;
22556
22881
  await this.#initializeNewSessionState(nextDiscoverySessionNonMCPToolNames, previousSessionFile);
22557
22882
  if (options?.drop && previousSessionFile) {
@@ -22964,7 +23289,7 @@ export class AgentSession {
22964
23289
  this.#settleTrackedQueuedInputsBeforeAgentDisconnect();
22965
23290
  this.#disconnectFromAgent();
22966
23291
  await this.#settleActivePromptForHistoryTransition();
22967
- await this.#settleBtwForSessionTransition();
23292
+ await this.#settlePredecessorForSessionTransition();
22968
23293
 
22969
23294
  // Flush current session to ensure all entries are written
22970
23295
  await this.sessionManager.flushBeforeLeaving();
@@ -23015,6 +23340,7 @@ export class AgentSession {
23015
23340
  try {
23016
23341
  await forkedManager.close();
23017
23342
  } catch (closeError) {
23343
+ forkedManager.retryCloseInBackground();
23018
23344
  cleanupErrors.push(closeError);
23019
23345
  logger.warn("Bounded fork successor close failed after initialization failure", {
23020
23346
  error: closeError instanceof Error ? closeError.message : String(closeError),
@@ -23043,6 +23369,7 @@ export class AgentSession {
23043
23369
  try {
23044
23370
  await previousManager.close();
23045
23371
  } catch (error) {
23372
+ previousManager.retryCloseInBackground();
23046
23373
  logger.warn("Previous session close failed after bounded fork adoption", {
23047
23374
  error: error instanceof Error ? error.message : String(error),
23048
23375
  });
@@ -28238,7 +28565,7 @@ export class AgentSession {
28238
28565
  }
28239
28566
 
28240
28567
  try {
28241
- await this.#settleBtwForSessionTransition();
28568
+ await this.#settlePredecessorForSessionTransition();
28242
28569
  } catch (error) {
28243
28570
  // Retirement can refuse before the transaction owns rollback. Preserve
28244
28571
  // the generated document without wrapping its unknown-effect error.
@@ -28329,6 +28656,7 @@ export class AgentSession {
28329
28656
  this.#steeringMessages = [];
28330
28657
  this.#followUpMessages = [];
28331
28658
  this.#pendingNextTurnMessages = [];
28659
+ this.#dropUnsavedDeferredResultsAtCommit();
28332
28660
  this.#scheduledHiddenNextTurnGeneration = undefined;
28333
28661
  this.#todoReminderCount = 0;
28334
28662
  this.agent.replaceMessages(sessionContext.messages, { historyRewrite: { reason: "handoff" } });
@@ -31189,7 +31517,7 @@ export class AgentSession {
31189
31517
  model: Model,
31190
31518
  credentialKind: string,
31191
31519
  rowId?: number,
31192
- ): Promise<string | undefined> {
31520
+ ): Promise<ResolvedApiKey | string | undefined> {
31193
31521
  const authStorage = this.#modelRegistry.authStorage;
31194
31522
  const storageProvider = resolveOAuthStorageProvider(model.provider);
31195
31523
  const triedRows = this.#managedFallbackTriedRows(model, credentialKind);
@@ -31204,10 +31532,13 @@ export class AgentSession {
31204
31532
  )
31205
31533
  continue;
31206
31534
  let apiKey: string | undefined;
31535
+ let credentialRowId: number | undefined;
31207
31536
  try {
31208
- apiKey = await this.#modelRegistry.getApiKey(model, this.credentialSessionId, {
31209
- credentialSelector: { kind: "id", value: String(credential.id) },
31210
- });
31537
+ ({ apiKey, credentialRowId } = await this.#modelRegistry.getApiKeyWithCredentialRowId(
31538
+ model,
31539
+ this.credentialSessionId,
31540
+ { credentialSelector: { kind: "id", value: String(credential.id) } },
31541
+ ));
31211
31542
  } catch (error) {
31212
31543
  const currentCredential = inventory.find(row => row.id === credential.id);
31213
31544
  if (!currentCredential?.disabled) throw error;
@@ -31221,7 +31552,9 @@ export class AgentSession {
31221
31552
  currentCredential &&
31222
31553
  !currentCredential.disabled
31223
31554
  )
31224
- return apiKey;
31555
+ // Attribute only when the row itself supplied the key; a runtime or
31556
+ // config override returns early without moving the sticky pointer.
31557
+ return credentialRowId === credential.id ? { apiKey, credentialId: credential.id } : apiKey;
31225
31558
  }
31226
31559
  return undefined;
31227
31560
  }
@@ -33490,15 +33823,14 @@ export class AgentSession {
33490
33823
  }
33491
33824
 
33492
33825
  /**
33493
- * The single eligibility rule for admitted shared publication (#7824):
33494
- * managed destination && (root shared mode || session already requires shared admission).
33826
+ * The single eligibility rule for admitted shared publication (#7824): managed destination &&
33827
+ * session already requires shared admission (a latched bar). Every session, root TUI included,
33828
+ * otherwise writes on the legacy route (single-owner step 10a).
33495
33829
  * Every migrated control and canonical producer routes through this predicate.
33496
33830
  */
33497
33831
  #usesSharedSessionPublication(): boolean {
33498
- return (
33499
- this.sessionManager.isManagedDestination() &&
33500
- (this.#rootInteractiveSharedAppend || this.sessionManager.requiresSharedMutationAdmission())
33501
- );
33832
+ const manager = this.sessionManager;
33833
+ return manager.isManagedDestination() && manager.requiresSharedMutationAdmission();
33502
33834
  }
33503
33835
 
33504
33836
  /**
@@ -34212,7 +34544,7 @@ export class AgentSession {
34212
34544
  * only what the earlier one left queued, behind the entry that failed.
34213
34545
  */
34214
34546
  async #flushPendingExecutionMessages<T extends BashExecutionMessage | PythonExecutionMessage>(
34215
- pendingMessages: Array<{ message: T; onPersisted?: () => void; appendedToAgent: boolean }>,
34547
+ pendingMessages: Array<{ message: T; onPersisted?: () => void; appendedToAgent: boolean; refusedAt?: number }>,
34216
34548
  kind: "bash" | "python",
34217
34549
  ): Promise<void> {
34218
34550
  while (this.#executionMessageDrain) {
@@ -34230,7 +34562,7 @@ export class AgentSession {
34230
34562
  }
34231
34563
 
34232
34564
  async #drainPendingExecutionMessages<T extends BashExecutionMessage | PythonExecutionMessage>(
34233
- pendingMessages: Array<{ message: T; onPersisted?: () => void; appendedToAgent: boolean }>,
34565
+ pendingMessages: Array<{ message: T; onPersisted?: () => void; appendedToAgent: boolean; refusedAt?: number }>,
34234
34566
  kind: "bash" | "python",
34235
34567
  ): Promise<void> {
34236
34568
  const total = pendingMessages.length;
@@ -34277,7 +34609,10 @@ export class AgentSession {
34277
34609
  // session closes below with that receipt instead.
34278
34610
  if (error instanceof SharedControlPublicationError && error.outcome.kind === "unknown")
34279
34611
  unconfirmed.push(...error.outcome.ids);
34280
- else remaining.push(pending);
34612
+ else {
34613
+ pending.refusedAt = ++this.#deferredRefusalSequence;
34614
+ remaining.push(pending);
34615
+ }
34281
34616
  continue;
34282
34617
  }
34283
34618
 
@@ -34299,7 +34634,7 @@ export class AgentSession {
34299
34634
  unconfirmed.length > 0
34300
34635
  ? `Could not confirm ${unconfirmed.length} of ${total} deferred ${kind} execution message${total === 1 ? "" : "s"} (attempted ids: ${unconfirmed.join(", ")}); ${persistedCount} persisted, ${remaining.length} not written; the session was closed to protect its history`
34301
34636
  : persistenceFailureCount > 0
34302
- ? `Failed to persist ${persistenceFailureCount} of ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}; ${persistedCount} persisted, failed messages remain pending for retry`
34637
+ ? `Failed to persist ${persistenceFailureCount} of ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}; ${persistedCount} persisted, failed messages remain pending for retry by the next prompt unless a session transition drops them`
34303
34638
  : `Persisted all ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}`;
34304
34639
  const callbackSummary =
34305
34640
  callbackFailureCount > 0
@@ -35318,6 +35653,7 @@ export class AgentSession {
35318
35653
  * Aborts current operation, loads messages, restores model/thinking.
35319
35654
  * Listeners are preserved and will continue receiving events.
35320
35655
  * @returns true if switch completed, false if cancelled by hook
35656
+ * @throws SessionHeldError under enforce, before any event, for a target another process holds
35321
35657
  */
35322
35658
  async switchSession(
35323
35659
  sessionPath: string,
@@ -35325,6 +35661,19 @@ export class AgentSession {
35325
35661
  transition?: SessionSwitchEvent["transition"];
35326
35662
  onTransitionMutationStarted?: () => void;
35327
35663
  },
35664
+ ): Promise<boolean> {
35665
+ // The admission claim covers the target until the rotation's own claim lands (design §1 row 9).
35666
+ return this.sessionManager.withSwitchTargetAdmission(sessionPath, () =>
35667
+ this.#switchSessionAdmitted(sessionPath, options),
35668
+ );
35669
+ }
35670
+
35671
+ async #switchSessionAdmitted(
35672
+ sessionPath: string,
35673
+ options?: {
35674
+ transition?: SessionSwitchEvent["transition"];
35675
+ onTransitionMutationStarted?: () => void;
35676
+ },
35328
35677
  ): Promise<boolean> {
35329
35678
  let ownerShutdownManager: AsyncJobManager | undefined;
35330
35679
  let ownerShutdownLease: OwnerSubagentShutdownLease | undefined;
@@ -35400,7 +35749,7 @@ export class AgentSession {
35400
35749
  while (this.isCompacting) await Bun.sleep(10);
35401
35750
  }
35402
35751
 
35403
- await this.#settleBtwForSessionTransition();
35752
+ await this.#settlePredecessorForSessionTransition();
35404
35753
  // Flush pending writes before switching so restore snapshots reflect committed state.
35405
35754
  await this.sessionManager.flushBeforeLeaving();
35406
35755
  const previousSessionState = await this.sessionManager.captureRollbackState();
@@ -35794,8 +36143,7 @@ export class AgentSession {
35794
36143
  // Deferred bash and python rows belong to the predecessor file.
35795
36144
  // Leaving them queued lets the next prompt append that command
35796
36145
  // text to the successor transcript.
35797
- this.#pendingBashMessages.length = 0;
35798
- this.#pendingPythonMessages.length = 0;
36146
+ this.#dropUnsavedDeferredResultsAtCommit();
35799
36147
  let ownerShutdownSettled = true;
35800
36148
  if (ownerShutdownManager && ownerShutdownLease && ownerId) {
35801
36149
  try {
@@ -35815,6 +36163,7 @@ export class AgentSession {
35815
36163
  ownerShutdownLease,
35816
36164
  ownerId,
35817
36165
  predecessorEndpointId,
36166
+ previousSessionState.sessionId,
35818
36167
  );
35819
36168
  this.#suppressOwnAsyncJobDeliveries();
35820
36169
  this.emitNotice(
@@ -36172,7 +36521,7 @@ export class AgentSession {
36172
36521
  this.#settleTrackedQueuedInputsBeforeAgentDisconnect();
36173
36522
  this.#disconnectFromAgent();
36174
36523
  await this.#settleActivePromptForHistoryTransition();
36175
- await this.#settleBtwForSessionTransition();
36524
+ await this.#settlePredecessorForSessionTransition();
36176
36525
 
36177
36526
  // Flush pending writes before preparing the successor.
36178
36527
  await this.sessionManager.flushBeforeLeaving();
@@ -36530,7 +36879,11 @@ export class AgentSession {
36530
36879
  if (!targetEntry) {
36531
36880
  throw new Error(`Entry ${targetId} not found`);
36532
36881
  }
36533
- // Collect entries to summarize (from old leaf to common ancestor).
36882
+ // Collect entries to summarize (from old leaf to common ancestor). Deferred `!`/`$`
36883
+ // rows the settle saves onto this branch later are not in it: the settle must follow
36884
+ // the abort below, which must follow the cancellable `session_before_tree` hook, and
36885
+ // that hook receives these entries and may return its own summary from them, so
36886
+ // collecting again after the abort would split what it saw from what is summarized.
36534
36887
  const { entries: collectedEntriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
36535
36888
  this.sessionManager,
36536
36889
  oldLeafId,
@@ -36646,7 +36999,7 @@ export class AgentSession {
36646
36999
  newLeafId = targetId;
36647
37000
  }
36648
37001
 
36649
- await this.#settleBtwForSessionTransition();
37002
+ await this.#settlePredecessorForSessionTransition();
36650
37003
 
36651
37004
  // Switch leaf (with or without summary)
36652
37005
  // Summary is attached at the navigation target position (newLeafId), not the old branch