@gajae-code/coding-agent 0.21.0 → 0.21.1

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 (111) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/config/autorouting-contract.d.ts +4 -4
  3. package/dist/types/config/autorouting-tier-map.d.ts +1 -1
  4. package/dist/types/config/keybindings.d.ts +1 -5
  5. package/dist/types/config/model-profile-activation.d.ts +30 -3
  6. package/dist/types/config/model-registry.d.ts +2 -0
  7. package/dist/types/config/models-config-schema.d.ts +8 -0
  8. package/dist/types/config/settings-schema.d.ts +7 -3
  9. package/dist/types/coordinator-mcp/canonical-json.d.ts +7 -0
  10. package/dist/types/extensibility/gjc-plugins/metadata.d.ts +1 -1
  11. package/dist/types/harness-control-plane/receipts.d.ts +1 -1
  12. package/dist/types/modes/components/settings-selector.d.ts +5 -2
  13. package/dist/types/modes/controllers/command-controller.d.ts +1 -1
  14. package/dist/types/modes/controllers/input-controller.d.ts +12 -0
  15. package/dist/types/modes/controllers/selector-controller.d.ts +1 -1
  16. package/dist/types/modes/interactive-mode.d.ts +1 -1
  17. package/dist/types/modes/shared/agent-wire/workflow-gate-schema.d.ts +1 -1
  18. package/dist/types/modes/types.d.ts +1 -1
  19. package/dist/types/session/agent-session.d.ts +101 -6
  20. package/dist/types/session/session-manager.d.ts +124 -9
  21. package/dist/types/setup/provider-onboarding.d.ts +55 -2
  22. package/dist/types/slash-commands/builtin-registry.d.ts +11 -0
  23. package/dist/types/utils/clipboard.d.ts +18 -0
  24. package/dist/types/utils/pasted-image-path.d.ts +2 -0
  25. package/dist/types/web/search/providers/keenable.d.ts +30 -0
  26. package/dist/types/web/search/types.d.ts +2 -2
  27. package/package.json +7 -7
  28. package/scripts/generate-sdk-operation-inventory.ts +28 -0
  29. package/src/cli/doctor/config-repairs.ts +1 -4
  30. package/src/cli/local-provider-smoke.ts +1 -4
  31. package/src/cli/public-command-help.ts +1 -1
  32. package/src/config/autorouting-contract.ts +5 -8
  33. package/src/config/autorouting-tier-map.ts +1 -1
  34. package/src/config/keybindings.ts +1 -2
  35. package/src/config/model-profile-activation.ts +332 -28
  36. package/src/config/model-registry.ts +156 -8
  37. package/src/config/models-config-schema.ts +27 -0
  38. package/src/config/settings-schema.ts +6 -0
  39. package/src/coordinator-mcp/canonical-json.ts +15 -0
  40. package/src/coordinator-mcp/policy.ts +1 -0
  41. package/src/coordinator-mcp/question-gate-codec.ts +1 -2
  42. package/src/coordinator-mcp/question-state.ts +2 -12
  43. package/src/coordinator-mcp/server.ts +1 -10
  44. package/src/customization/import.ts +1 -5
  45. package/src/discovery/mcp-compat.ts +1 -5
  46. package/src/discovery/mcp-json.ts +1 -4
  47. package/src/edit/notebook.ts +1 -5
  48. package/src/extensibility/gjc-plugins/lifecycle.ts +1 -3
  49. package/src/extensibility/gjc-plugins/metadata.ts +2 -5
  50. package/src/extensibility/gjc-plugins/schema.ts +1 -4
  51. package/src/gjc-runtime/deep-interview-crystallize.ts +1 -4
  52. package/src/gjc-runtime/deep-interview-runtime.ts +1 -4
  53. package/src/gjc-runtime/state-renderer.ts +1 -5
  54. package/src/gjc-runtime/tmux-owner-isolation.ts +1 -3
  55. package/src/gjc-runtime/ultragoal-owner-loss-recovery.ts +1 -4
  56. package/src/gjc-runtime/ultragoal-succession.ts +1 -4
  57. package/src/goals/continuation-timeout-guard.ts +1 -4
  58. package/src/harness-control-plane/receipts.ts +1 -1
  59. package/src/internal-urls/docs-index.generated.ts +4 -4
  60. package/src/migrate/mcp-mapper.ts +2 -4
  61. package/src/modes/components/hook-editor.ts +4 -8
  62. package/src/modes/components/hook-selector.ts +3 -1
  63. package/src/modes/components/settings-selector.ts +26 -2
  64. package/src/modes/controllers/command-controller.ts +4 -98
  65. package/src/modes/controllers/extension-ui-controller.ts +6 -14
  66. package/src/modes/controllers/goal-mode-controller.ts +4 -4
  67. package/src/modes/controllers/input-controller.ts +110 -46
  68. package/src/modes/controllers/plan-mode-controller.ts +6 -10
  69. package/src/modes/controllers/selector-controller.ts +66 -23
  70. package/src/modes/controllers/todo-command-controller.ts +2 -2
  71. package/src/modes/interactive-mode.ts +2 -2
  72. package/src/modes/prompt-action-autocomplete.ts +1 -1
  73. package/src/modes/runtime-init.ts +4 -4
  74. package/src/modes/shared/agent-wire/workflow-gate-schema.ts +1 -1
  75. package/src/modes/types.ts +1 -1
  76. package/src/modes/utils/hotkeys-markdown.ts +1 -1
  77. package/src/runtime-mcp/client.ts +1 -4
  78. package/src/runtime-mcp/elicitation.ts +1 -5
  79. package/src/runtime-mcp/protocol.ts +2 -4
  80. package/src/sdk/broker/lifecycle-ledger.ts +1 -0
  81. package/src/sdk/broker/lifecycle.ts +1 -0
  82. package/src/sdk/cli/rows.ts +2 -3
  83. package/src/sdk/cli/session-cli.ts +2 -8
  84. package/src/sdk/host/query/cursor.ts +1 -0
  85. package/src/sdk/host/reverse-leases.ts +1 -0
  86. package/src/sdk/lifecycle/service.ts +1 -0
  87. package/src/sdk/protocol/operation-inventory.generated.json +154 -0
  88. package/src/session/agent-session.ts +1877 -224
  89. package/src/session/btw-prefix-ledger.ts +1 -4
  90. package/src/session/internal/managed-gc-retirement-codec.ts +1 -4
  91. package/src/session/session-manager.ts +732 -224
  92. package/src/session/task-artifact-owner-codec.ts +1 -4
  93. package/src/session-import/claude.ts +1 -4
  94. package/src/session-import/detect.ts +1 -6
  95. package/src/session-import/provider-codex.ts +1 -6
  96. package/src/session-import/provider-service.ts +4 -0
  97. package/src/setup/hermes-setup.ts +1 -4
  98. package/src/setup/provider-onboarding.ts +514 -26
  99. package/src/slash-commands/builtin-registry.ts +26 -13
  100. package/src/slash-commands/helpers/todo.ts +3 -1
  101. package/src/task/delegation-hint.ts +1 -4
  102. package/src/task/executor.ts +4 -2
  103. package/src/task/provider-retry-status.ts +1 -4
  104. package/src/tools/json-tree.ts +1 -4
  105. package/src/tools/recipe/runners/pkg.ts +1 -5
  106. package/src/utils/clipboard.ts +155 -2
  107. package/src/utils/mac-file-urls.applescript +37 -0
  108. package/src/utils/pasted-image-path.ts +5 -0
  109. package/src/web/search/provider.ts +6 -0
  110. package/src/web/search/providers/keenable.ts +207 -0
  111. package/src/web/search/types.ts +2 -0
@@ -126,15 +126,15 @@ import {
126
126
  getSupportedEfforts,
127
127
  isContextOverflow,
128
128
  isFastModeEffectiveForProvider,
129
+ isImageOnlyModel,
129
130
  isUsageLimitError,
130
131
  modelSupportsMaintenanceCalls,
131
132
  modelSupportsServiceTier,
132
133
  modelsAreEqual,
133
- isImageOnlyModel,
134
134
  resolveOAuthStorageProvider,
135
135
  streamSimple,
136
136
  } from "@gajae-code/ai/core";
137
- import { normalizeAnthropicBaseUrl } from "@gajae-code/ai/providers/anthropic";
137
+ import { clearAnthropicFastModeFallback, normalizeAnthropicBaseUrl } from "@gajae-code/ai/providers/anthropic";
138
138
  import { isExplicitCodexTerminalVeto } from "@gajae-code/ai/providers/openai-codex-responses";
139
139
  import type { AssistantMessageEventStream } from "@gajae-code/ai/utils/event-stream";
140
140
  import {
@@ -251,9 +251,12 @@ import type { ConfigHotReloadCandidate, ConfigHotReloadPaths } from "../config/c
251
251
  import {
252
252
  applyModelProfileRuntimeBindings,
253
253
  applyPreparedModelProfileActivation,
254
+ buildModelProfileTranscriptPlan,
255
+ type CommittedModelProfileSessionPublication,
254
256
  finishPreparedModelProfileActivation,
255
257
  getModelAssignmentPatches,
256
258
  getModelProfileAssignmentMaterializationPatches,
259
+ ModelProfilePublicationError,
257
260
  materializeActiveModelProfileAssignment,
258
261
  type PreparedModelProfileActivation,
259
262
  prepareModelProfileActivation,
@@ -496,12 +499,12 @@ import {
496
499
  notifyWorkflowGateEmitterChanged,
497
500
  } from "../tools/ask-answer-registry";
498
501
  import { assertEditableFile } from "../tools/auto-generated-guard";
499
- import { closePendingAsks } from "../tools/pending-asks";
500
502
  import { releaseTabsForOwner } from "../tools/browser/tab-supervisor";
501
503
  import type { CheckpointState } from "../tools/checkpoint";
502
504
  import { githubPermissionIntent } from "../tools/github-side-effect";
503
505
  import { outputMeta, wrapToolWithMetaNotice } from "../tools/output-meta";
504
506
  import { normalizeLocalScheme, resolveReadPath, resolveToCwd } from "../tools/path-utils";
507
+ import { closePendingAsks } from "../tools/pending-asks";
505
508
  import { registerResourceGcSession } from "../tools/resource-gc";
506
509
  import { getLatestTodoPhasesFromEntries, type TodoItem, type TodoPhase } from "../tools/todo-write";
507
510
  import { ToolAbortError, ToolError } from "../tools/tool-errors";
@@ -577,13 +580,16 @@ import {
577
580
  wrapUntrustedContent,
578
581
  } from "./messages";
579
582
  import { isLegacyProviderSafetyStopMessage } from "./provider-safety-stop";
580
- import type { SessionRecapAppendResult } from "./recap";
583
+ import type { SessionRecapAppendResult, SessionRecapInput } from "./recap";
581
584
  import { readSdkRunCapability } from "./sdk-run-capability";
582
585
  import { formatSessionDumpText } from "./session-dump-format";
583
586
  import type {
584
587
  BranchSummaryEntry,
585
588
  CompactionEntry,
589
+ DefaultModelSelectionEntriesOptions,
590
+ DefaultModelSelectionPromotion,
586
591
  DefaultModelSelectionStage,
592
+ ModelProfileTranscriptPlan,
587
593
  NewSessionOptions,
588
594
  PreparedNewSession,
589
595
  RecoveryHydrationContext,
@@ -594,6 +600,8 @@ import type {
594
600
  SessionManagerCloseOutcome,
595
601
  SessionMemoryStats,
596
602
  SharedAppendOutcome,
603
+ SharedControlEntry,
604
+ SharedEntriesAppendOutcome,
597
605
  } from "./session-manager";
598
606
  import {
599
607
  createReadonlySessionManager,
@@ -628,6 +636,17 @@ import { ToolChoiceQueue } from "./tool-choice-queue";
628
636
  import { pruneSupersededMaintenanceReminders, pruneSupersededVolatileProjectContext } from "./volatile-context-pruning";
629
637
  import { TerminalIdleAdmissionError, YieldQueue } from "./yield-queue";
630
638
 
639
+ /**
640
+ * Message shapes this session persists through the manager. `appendMessageSharingSession` and
641
+ * `appendMessage` accept the same set including hook messages, which this session never writes.
642
+ */
643
+ type SessionPersistedMessage =
644
+ | Message
645
+ | CustomMessage
646
+ | BashExecutionMessage
647
+ | PythonExecutionMessage
648
+ | FileMentionMessage;
649
+
631
650
  /**
632
651
  * #4560: structured workflow recovery projection from canonical durable
633
652
  * Ralplan/Ultragoal state, consumed by the compaction summary context and
@@ -847,6 +866,59 @@ export function ownedCompletionResumeAction(message: AgentMessage): "ordinary" |
847
866
 
848
867
  const PRUNED_ARTIFACT_REF_MAX_CHARS = 64;
849
868
 
869
+ /**
870
+ * A session control could not complete its admitted shared publication (#7823, #7824).
871
+ *
872
+ * `rejected`/`stale` prove nothing was written and nothing live changed. `unknown`
873
+ * and `committed_not_applied` mean the transcript may hold (or holds) the change while
874
+ * this session did not apply it; the session is closed instead of compensating.
875
+ */
876
+ export class SharedControlPublicationError extends Error {
877
+ readonly code: "rejected" | "stale" | "unknown" | "committed_not_applied";
878
+
879
+ constructor(
880
+ readonly operation: string,
881
+ readonly outcome: SharedEntriesAppendOutcome,
882
+ publicationCause?: unknown,
883
+ ) {
884
+ const code = outcome.kind === "committed" ? "committed_not_applied" : outcome.kind;
885
+ super(sharedControlPublicationMessage(operation, outcome), { cause: publicationCause ?? outcome });
886
+ this.name = "SharedControlPublicationError";
887
+ this.code = code;
888
+ }
889
+ }
890
+
891
+ /**
892
+ * Durable session intent a model-selection rollback restores along with the live model:
893
+ * the configured DEFAULT chain and the resume default. Absent fields are left alone.
894
+ */
895
+ export interface ModelSelectionRollbackDurableState {
896
+ readonly defaultChain?: {
897
+ readonly state:
898
+ | {
899
+ readonly entries: readonly string[];
900
+ readonly origin: string;
901
+ readonly identity?: string;
902
+ readonly explicitHead?: boolean;
903
+ }
904
+ | undefined;
905
+ };
906
+ readonly resumeDefault?: { readonly selector: string | undefined };
907
+ }
908
+
909
+ function sharedControlPublicationMessage(operation: string, outcome: SharedEntriesAppendOutcome): string {
910
+ switch (outcome.kind) {
911
+ case "stale":
912
+ return `Could not ${operation}: the shared session changed before the update was written (${outcome.reason}). Nothing was changed; reopen the session and retry.`;
913
+ case "rejected":
914
+ return `Could not ${operation}: the shared session refused the update before writing it. Nothing was changed; retry.`;
915
+ case "unknown":
916
+ return `Could not confirm ${operation} (entries ${outcome.ids.join(", ") || "none"}). The session was closed to protect its history; reopen it to see the result.`;
917
+ case "committed":
918
+ return `The change (${operation}) was saved to the session history but could not be applied here. The session was closed; reopen it to continue.`;
919
+ }
920
+ }
921
+
850
922
  class SharedCompactionPublicationError extends Error {
851
923
  constructor(readonly outcome: Exclude<SharedAppendOutcome, { kind: "committed" }>) {
852
924
  super(
@@ -4343,6 +4415,18 @@ export class AgentSession {
4343
4415
  #retryAttempt = 0;
4344
4416
  #retryPromise: Promise<void> | undefined = undefined;
4345
4417
  #retryResolve: (() => void) | undefined = undefined;
4418
+ #profilePublicationReceipts = new WeakMap<
4419
+ Extract<SharedEntriesAppendOutcome, { kind: "committed" }>,
4420
+ {
4421
+ manager: SessionManager;
4422
+ sessionId: string;
4423
+ identityGeneration: number;
4424
+ leaf: string | null;
4425
+ parent: string | null;
4426
+ ids: readonly string[];
4427
+ plan: ModelProfileTranscriptPlan;
4428
+ }
4429
+ >();
4346
4430
  #defaultFallbackController: FallbackChainController | undefined;
4347
4431
  #activeProfileConfiguredDefaultChain: readonly string[] | undefined;
4348
4432
  #startupRecoveryBindingsRequired = false;
@@ -4546,6 +4630,8 @@ export class AgentSession {
4546
4630
  onPersisted?: () => void;
4547
4631
  appendedToAgent: boolean;
4548
4632
  }> = [];
4633
+ /** The one in-flight deferred command-result drain; later drains join it first. */
4634
+ #executionMessageDrain: Promise<void> | undefined;
4549
4635
  #activeEvalExecutions = new Set<Promise<unknown>>();
4550
4636
  #evalExecutionDisposing = false;
4551
4637
 
@@ -5016,6 +5102,7 @@ export class AgentSession {
5016
5102
  this.#sessionAdmissionQueue.length > 0 ||
5017
5103
  this.#startupPromptWaiters.size > 0 ||
5018
5104
  this.#pendingSelectionFences > 0 ||
5105
+ this.#pendingFastControls.size > 0 ||
5019
5106
  this.#sessionTransitionKind !== undefined ||
5020
5107
  this.#handoffTransitionActive ||
5021
5108
  this.#cancelAndSubmitInProgress ||
@@ -5943,6 +6030,9 @@ export class AgentSession {
5943
6030
 
5944
6031
  #isSessionSettlementPending(ignoreSelectionFenceGeneration?: number): boolean {
5945
6032
  return (
6033
+ [...this.#pendingFastControls.values()].some(
6034
+ generation => ignoreSelectionFenceGeneration === undefined || generation < ignoreSelectionFenceGeneration,
6035
+ ) ||
5946
6036
  this.#livePromptsInFlight() > 0 ||
5947
6037
  this.#agentEventHandlersInFlight > 0 ||
5948
6038
  this.#agentEndPublicationInFlight > 0 ||
@@ -6051,7 +6141,7 @@ export class AgentSession {
6051
6141
  }
6052
6142
  }
6053
6143
 
6054
- #endInFlight(token: symbol): unknown {
6144
+ async #endInFlight(token: symbol): Promise<unknown> {
6055
6145
  const wasAbandoned = this.#abandonedInFlightPrompts.has(token);
6056
6146
  this.#inFlightPromptTokens.delete(token);
6057
6147
  this.#abandonedInFlightPrompts.delete(token);
@@ -6073,7 +6163,10 @@ export class AgentSession {
6073
6163
  // agent state and the session now, not at the next prompt. Until it does,
6074
6164
  // the TUI shows output the transcript lacks and `onPersisted` stays unfired,
6075
6165
  // so a rebuild in that gap drops the only rendering of the execution.
6076
- this.#flushPendingPromptMessages();
6166
+ // Shared sessions publish through the lease, so this flush is asynchronous;
6167
+ // awaiting it here is what keeps the retry/requeue guarantee before the next
6168
+ // prompt rather than after it.
6169
+ await this.#flushPendingPromptMessages();
6077
6170
  } catch (error) {
6078
6171
  flushError = error;
6079
6172
  }
@@ -6085,7 +6178,7 @@ export class AgentSession {
6085
6178
  promptWait?: "publication" | "full",
6086
6179
  sdkPublication?: Promise<void>,
6087
6180
  ): Promise<void> {
6088
- const flushError = this.#endInFlight(token);
6181
+ const flushError = await this.#endInFlight(token);
6089
6182
  const predecessorPromptStillInFlight = this.#livePromptsInFlight() > 0;
6090
6183
  if (promptWait === "publication") {
6091
6184
  await (sdkPublication ?? this.#agentEndPublicationPromise);
@@ -6112,15 +6205,15 @@ export class AgentSession {
6112
6205
  return false;
6113
6206
  }
6114
6207
 
6115
- #flushPendingPromptMessages(): void {
6208
+ async #flushPendingPromptMessages(): Promise<void> {
6116
6209
  const errors: unknown[] = [];
6117
6210
  try {
6118
- this.#flushPendingBashMessages();
6211
+ await this.#flushPendingBashMessages();
6119
6212
  } catch (error) {
6120
6213
  errors.push(error);
6121
6214
  }
6122
6215
  try {
6123
- this.#flushPendingPythonMessages();
6216
+ await this.#flushPendingPythonMessages();
6124
6217
  } catch (error) {
6125
6218
  errors.push(error);
6126
6219
  }
@@ -7117,9 +7210,9 @@ export class AgentSession {
7117
7210
  },
7118
7211
  persist: (mode, state) => {
7119
7212
  if (mode === "none") {
7120
- this.sessionManager.appendModeChange("none");
7213
+ this.appendModeChangeInBackground("none");
7121
7214
  } else if (state) {
7122
- this.sessionManager.appendModeChange(mode, { goal: state.goal });
7215
+ this.appendModeChangeInBackground(mode, { goal: state.goal });
7123
7216
  }
7124
7217
  },
7125
7218
  sendHiddenMessage: async message => {
@@ -8270,14 +8363,20 @@ export class AgentSession {
8270
8363
  }
8271
8364
 
8272
8365
  #canonicalMessageAdmissionTail: CanonicalMessageAdmissionSlot = { promise: Promise.resolve(), released: true };
8273
- #thinkingControlAdmissionGroup: {
8274
- predecessor: CanonicalMessageAdmissionSlot;
8275
- workflowPredecessors: Promise<void>[];
8276
- completion: CanonicalMessageAdmissionSlot;
8277
- release: () => void;
8278
- members: number;
8279
- } | undefined;
8366
+ #thinkingControlAdmissionGroup:
8367
+ | {
8368
+ predecessor: CanonicalMessageAdmissionSlot;
8369
+ workflowPredecessors: Promise<void>[];
8370
+ completion: CanonicalMessageAdmissionSlot;
8371
+ release: () => void;
8372
+ members: number;
8373
+ }
8374
+ | undefined;
8280
8375
  #startedSharedControlPublications = new Set<Promise<void>>();
8376
+ /** Background shared publications that teardown must join before the manager goes away. */
8377
+ #backgroundPublications = new Set<Promise<void>>();
8378
+ #fastControlTail: Promise<void> = Promise.resolve();
8379
+ #pendingFastControls = new Map<Promise<void>, number>();
8281
8380
 
8282
8381
  #reserveCanonicalSchedulingSlot() {
8283
8382
  const predecessor = this.#canonicalMessageAdmissionTail;
@@ -8296,11 +8395,12 @@ export class AgentSession {
8296
8395
  }
8297
8396
 
8298
8397
  async #withThinkingControlScheduling<T>(body: () => Promise<T>): Promise<T> {
8299
- const group = (this.#thinkingControlAdmissionGroup ??= {
8398
+ this.#thinkingControlAdmissionGroup ??= {
8300
8399
  ...this.#reserveCanonicalSchedulingSlot(),
8301
8400
  workflowPredecessors: [...this.#startedSharedControlPublications],
8302
8401
  members: 0,
8303
- });
8402
+ };
8403
+ const group = this.#thinkingControlAdmissionGroup;
8304
8404
  group.members++;
8305
8405
  try {
8306
8406
  if (!group.predecessor.released || group.workflowPredecessors.length)
@@ -9080,7 +9180,7 @@ export class AgentSession {
9080
9180
  const isRosterReminder = event.message.role === "custom" && event.message.customType === "irc-peer-roster";
9081
9181
  if (!isRosterReminder) {
9082
9182
  try {
9083
- this.#appendCustomMessageEntry(
9183
+ await this.#appendCustomMessageEntry(
9084
9184
  event.message.customType,
9085
9185
  event.message.content,
9086
9186
  event.message.display,
@@ -9089,8 +9189,7 @@ export class AgentSession {
9089
9189
  getSessionMessageObservationId(event.message),
9090
9190
  );
9091
9191
  } catch (error) {
9092
- this.agent.abort();
9093
- throw error;
9192
+ this.#abortRunForPublicationFailure("custom message append", error);
9094
9193
  }
9095
9194
  }
9096
9195
  } else if (
@@ -9100,7 +9199,7 @@ export class AgentSession {
9100
9199
  event.message.role === "toolResult" ||
9101
9200
  event.message.role === "fileMention"
9102
9201
  ) {
9103
- const sharedAppend = this.#rootInteractiveSharedAppend && this.sessionManager.isManagedDestination();
9202
+ const sharedAppend = this.#usesSharedSessionPublication();
9104
9203
  try {
9105
9204
  let appendedEntryId: string;
9106
9205
  if (sharedAppend) {
@@ -9119,10 +9218,7 @@ export class AgentSession {
9119
9218
  } catch (error) {
9120
9219
  canonicalAdmission?.fail(error);
9121
9220
  // Shared outcomes cannot pass through the legacy todo recovery/reappend path.
9122
- if (sharedAppend) {
9123
- this.agent.abort();
9124
- throw error;
9125
- }
9221
+ if (sharedAppend) this.#abortRunForPublicationFailure(`canonical ${event.message.role} append`, error);
9126
9222
  // Typed near-limit append (#4566): the transcript hit the managed
9127
9223
  // per-file cap and even the live-entry rewrite could not hold this
9128
9224
  // entry. The edit/effect itself may already be committed; surface a
@@ -9895,7 +9991,7 @@ export class AgentSession {
9895
9991
  if (!current || `${current.provider}/${current.id}` !== modelKey) return;
9896
9992
  let outcome: SessionRecapAppendResult;
9897
9993
  try {
9898
- outcome = this.sessionManager.appendSessionRecap({
9994
+ outcome = await this.appendSessionRecapForSession({
9899
9995
  text: result.text,
9900
9996
  sourceEntryId: snapshot.sourceEntryId,
9901
9997
  requestEntryId: snapshot.requestEntryId,
@@ -10908,11 +11004,20 @@ export class AgentSession {
10908
11004
  const ruleNames = folded.rules.map(r => r.name.trim()).filter(n => n.length > 0);
10909
11005
  if (ruleNames.length > 0) {
10910
11006
  const records = this.#ttsrManager?.getInjectedRecords().filter(record => ruleNames.includes(record.name));
11007
+ const ttsrMessageCount = this.#ttsrManager?.getMessageCount();
11008
+ // A shared session refuses the legacy append; record through the admitted path
11009
+ // like #markTtsrInjected (#7824).
11010
+ if (this.#usesSharedSessionPublication()) {
11011
+ void this.#publishInBackground("ttsr injection", () =>
11012
+ this.sessionManager.appendTtsrInjectionSharingSession(ruleNames, records, ttsrMessageCount),
11013
+ );
11014
+ return;
11015
+ }
10911
11016
  // This runs inside the synchronous agent listener entry: a failed record
10912
11017
  // write must not abort canonical handling of the published result. The
10913
11018
  // reminder was delivered, so the claim stays consumed in memory.
10914
11019
  try {
10915
- this.sessionManager.appendTtsrInjection(ruleNames, records, this.#ttsrManager?.getMessageCount());
11020
+ this.sessionManager.appendTtsrInjection(ruleNames, records, ttsrMessageCount);
10916
11021
  } catch (error) {
10917
11022
  logger.warn("TTSR injection record could not be persisted", {
10918
11023
  rules: ruleNames,
@@ -10943,7 +11048,17 @@ export class AgentSession {
10943
11048
  }
10944
11049
  this.#ttsrManager?.markInjectedByNames(uniqueRuleNames);
10945
11050
  const records = this.#ttsrManager?.getInjectedRecords().filter(record => uniqueRuleNames.includes(record.name));
10946
- this.sessionManager.appendTtsrInjection(uniqueRuleNames, records, this.#ttsrManager?.getMessageCount());
11051
+ const ttsrMessageCount = this.#ttsrManager?.getMessageCount();
11052
+ // A shared session refuses the legacy append once admission is armed, and this runs
11053
+ // inside the message_end handler: publishing through the admitted path keeps a TTSR
11054
+ // match from failing the run (#7815).
11055
+ if (!this.#usesSharedSessionPublication()) {
11056
+ this.sessionManager.appendTtsrInjection(uniqueRuleNames, records, ttsrMessageCount);
11057
+ return;
11058
+ }
11059
+ void this.#publishInBackground("ttsr injection", () =>
11060
+ this.sessionManager.appendTtsrInjectionSharingSession(uniqueRuleNames, records, ttsrMessageCount),
11061
+ );
10947
11062
  }
10948
11063
 
10949
11064
  /** Parse only finalized, tool-provided source digests, before dispatch. */
@@ -12489,6 +12604,7 @@ export class AgentSession {
12489
12604
  }
12490
12605
  await awaitDisposeStep("exact MCP retirement", this.#exactMcpRetirementCompletion ?? Promise.resolve(), true);
12491
12606
  await awaitDisposeStep("MCP manager replacement", this.#mcpManagerReplacement, true);
12607
+ await awaitDisposeStep("background session publications", this.#joinBackgroundPublications(), true);
12492
12608
  await awaitDisposeStep("cwd move admission close", this.sessionManager.closeCwdMoveAdmission());
12493
12609
  await awaitDisposeStep("admitted cwd transition", this.sessionManager.joinCwdTransition(), true);
12494
12610
  await awaitDisposeStep("active cwd readers", this.sessionManager.joinCwdReaders(), true);
@@ -12534,6 +12650,7 @@ export class AgentSession {
12534
12650
  Promise.allSettled([...this.#autoCompactionCompletions]).then(() => {}),
12535
12651
  true,
12536
12652
  );
12653
+ await awaitDisposeStep("fast controls", this.#fastControlTail, true);
12537
12654
  await awaitDisposeStep("agent end publication", this.#agentEndPublicationPromise);
12538
12655
  await awaitDisposeStep("queued extension events", this.#queuedExtensionEvents);
12539
12656
  await awaitDisposeStep("agent end handling", this.#agentEndHandlingPromise);
@@ -12941,9 +13058,17 @@ export class AgentSession {
12941
13058
  async awaitSessionSettlement(): Promise<void> {
12942
13059
  await this.awaitPendingContextTransformations();
12943
13060
  await this.#waitForSessionSettlement();
13061
+ await this.#joinBackgroundPublications();
12944
13062
  await this.sessionManager.flush();
12945
13063
  }
12946
13064
 
13065
+ /** Join in-flight background shared publications so teardown never races one. */
13066
+ async #joinBackgroundPublications(): Promise<void> {
13067
+ while (this.#backgroundPublications.size > 0) {
13068
+ await Promise.all([...this.#backgroundPublications]);
13069
+ }
13070
+ }
13071
+
12947
13072
  /** Test seam: hold prompt admission while bypassing a pending selection fence. */
12948
13073
  runWithPromptAdmissionForTests(body: () => Promise<void>): Promise<void> {
12949
13074
  return this.#withSessionAdmission("prompt", async () => body(), undefined, undefined, {
@@ -13185,6 +13310,28 @@ export class AgentSession {
13185
13310
  previousSelectedDiscoveredBuiltinToolNames,
13186
13311
  nextSelectedDiscoveredBuiltinToolNames,
13187
13312
  );
13313
+ if (!mcpSelectionChanged && !discoveredBuiltinSelectionChanged) return;
13314
+ // Internal refreshes (MCP catalog, /ssh, plugin/subskill tools) are synchronous
13315
+ // producers: in a shared session their selection is published through admitted
13316
+ // background publication instead of the refused legacy append (#7824).
13317
+ if (this.#usesSharedSessionPublication()) {
13318
+ const manager = this.sessionManager;
13319
+ const identityGeneration = manager.getSessionIdentityGeneration();
13320
+ void this.#publishInBackground("tool selection", async () => {
13321
+ const outcome = await manager.appendToolSelectionsSharingSession(
13322
+ mcpSelectionChanged ? nextSelectedMCPToolNames : undefined,
13323
+ discoveredBuiltinSelectionChanged ? nextSelectedDiscoveredBuiltinToolNames : undefined,
13324
+ () =>
13325
+ !this.#isDisposed &&
13326
+ this.sessionManager === manager &&
13327
+ manager.getSessionIdentityGeneration() === identityGeneration,
13328
+ );
13329
+ if (outcome.kind === "committed") return { kind: "committed", id: outcome.ids.at(-1) ?? "" };
13330
+ if (outcome.kind === "unknown") return { kind: "unknown", id: outcome.ids.join(","), error: outcome.error };
13331
+ return outcome;
13332
+ });
13333
+ return;
13334
+ }
13188
13335
  const mutationCorrelationId =
13189
13336
  mcpSelectionChanged && discoveredBuiltinSelectionChanged ? crypto.randomUUID() : undefined;
13190
13337
  if (mcpSelectionChanged) {
@@ -14333,12 +14480,12 @@ export class AgentSession {
14333
14480
  return tool !== undefined && isMCPBridgeTool(tool);
14334
14481
  });
14335
14482
  if (activated.length > 0) {
14336
- if (!this.#usesSharedWorkflowIntentAppend())
14483
+ if (!this.#usesSharedSessionPublication())
14337
14484
  this.sessionManager.assertLegacyMutationAllowed("activate discovered tools");
14338
14485
  const appliedRevision = await this.#applyActiveToolsByName(nextActiveToolNames, {
14339
14486
  previousSelectedMCPToolNames,
14340
14487
  previousSelectedDiscoveredBuiltinToolNames,
14341
- sharedDiscoveredActivation: true,
14488
+ sharedPublication: true,
14342
14489
  nextSelectedDiscoveredBuiltinToolNames: [...nextSelectedDiscoveredBuiltinToolNames],
14343
14490
  persistedMCPToolNames:
14344
14491
  activatedMCPToolNames.length > 0
@@ -14661,7 +14808,7 @@ export class AgentSession {
14661
14808
  toolNames: string[],
14662
14809
  options?: {
14663
14810
  persistMCPSelection?: boolean;
14664
- sharedDiscoveredActivation?: boolean;
14811
+ sharedPublication?: boolean;
14665
14812
  previousSelectedMCPToolNames?: string[];
14666
14813
  previousSelectedDiscoveredBuiltinToolNames?: string[];
14667
14814
  nextSelectedDiscoveredBuiltinToolNames?: string[];
@@ -14671,7 +14818,7 @@ export class AgentSession {
14671
14818
  explicitActiveToolSelectionGeneration?: number;
14672
14819
  },
14673
14820
  ): Promise<number | undefined> {
14674
- const sharedDiscovery = options?.sharedDiscoveredActivation === true && this.#usesSharedWorkflowIntentAppend();
14821
+ const sharedDiscovery = options?.sharedPublication === true && this.#usesSharedSessionPublication();
14675
14822
  const assertControlMutationAllowed = () => {
14676
14823
  if (options?.explicitActiveToolSelectionGeneration !== undefined && !sharedDiscovery) {
14677
14824
  this.sessionManager.assertLegacyMutationAllowed("select active tools");
@@ -14780,10 +14927,12 @@ export class AgentSession {
14780
14927
  if (options?.persistMCPSelection === false || (!mcpChanged && !builtinChanged)) {
14781
14928
  promote();
14782
14929
  } else {
14930
+ const operation = "select active tools";
14783
14931
  let promoted = false;
14932
+ let promotionError: unknown;
14784
14933
  const outcome = await this.#withStartedSharedControlPublication(
14785
14934
  () => {
14786
- if (!current()) throw new Error("Shared discovered-tool activation superseded");
14935
+ if (!current()) throw new Error("Shared tool selection superseded");
14787
14936
  },
14788
14937
  async () => {
14789
14938
  const result = await manager.appendToolSelectionsSharingSession(
@@ -14791,25 +14940,28 @@ export class AgentSession {
14791
14940
  builtinChanged ? selectedBuiltinNames : undefined,
14792
14941
  current,
14793
14942
  );
14943
+ // No await between the committed receipt and live promotion.
14794
14944
  if (result.kind === "committed" && current()) {
14795
14945
  try {
14796
14946
  promote();
14797
14947
  promoted = true;
14798
14948
  } catch (error) {
14799
- throw new AggregateError(
14800
- [error],
14801
- "Shared discovered-tool activation committed but promotion failed",
14802
- { cause: result },
14803
- );
14949
+ promotionError = error;
14804
14950
  }
14805
14951
  }
14806
14952
  return result;
14807
14953
  },
14808
14954
  );
14809
- if (outcome.kind !== "committed")
14810
- throw new Error(`Shared discovered-tool activation ${outcome.kind}`, { cause: outcome });
14955
+ // A possibly durable selection this session did not apply keeps its receipt and
14956
+ // closes the session instead of running on tools its transcript no longer names.
14957
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
14958
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
14811
14959
  if (!promoted)
14812
- throw new Error("Shared discovered-tool activation committed but superseded", { cause: outcome });
14960
+ return this.#failClosedSharedControl(
14961
+ operation,
14962
+ outcome,
14963
+ promotionError ?? new Error("Committed shared tool selection superseded"),
14964
+ );
14813
14965
  }
14814
14966
  return this.#activeToolSelectionRevision;
14815
14967
  }
@@ -14953,7 +15105,10 @@ export class AgentSession {
14953
15105
  toolNames: string[],
14954
15106
  options?: { explicit?: boolean; persistMCPSelection?: boolean; retryOnMcpCatalogChange?: boolean },
14955
15107
  ): Promise<void> {
14956
- this.sessionManager.assertLegacyMutationAllowed("select active tools");
15108
+ // Shared sessions publish the selection and promote prompt/tools together through the
15109
+ // admitted tool-selection path; legacy sessions keep the legacy refusal.
15110
+ const assertPublicationMode = this.#controlPublicationModeFence("select active tools");
15111
+ const sharedPublication = this.#usesSharedSessionPublication();
14957
15112
  const isExplicit = options?.explicit !== false;
14958
15113
  const explicitMCPToolNames = isExplicit ? this.#resolveExplicitMCPToolSelection(toolNames) : undefined;
14959
15114
  const shouldPersistMCPSelectionIfUnchanged =
@@ -14976,6 +15131,7 @@ export class AgentSession {
14976
15131
  sessionTransitionGeneration,
14977
15132
  explicitActiveToolSelectionGeneration,
14978
15133
  persistMCPSelection: options?.persistMCPSelection,
15134
+ sharedPublication,
14979
15135
  });
14980
15136
  if (options?.retryOnMcpCatalogChange && appliedRevision === undefined) {
14981
15137
  if (sessionTransitionGeneration !== this.#sessionTransitionGeneration) {
@@ -15005,6 +15161,7 @@ export class AgentSession {
15005
15161
  sessionTransitionGeneration,
15006
15162
  explicitActiveToolSelectionGeneration,
15007
15163
  persistMCPSelection: options.persistMCPSelection,
15164
+ sharedPublication,
15008
15165
  },
15009
15166
  );
15010
15167
  if (appliedRevision === undefined && retryMcpCatalogGeneration === this.#mcpCatalogGeneration) {
@@ -15019,7 +15176,12 @@ export class AgentSession {
15019
15176
  !sessionContext.hasPersistedMCPToolSelection ||
15020
15177
  !this.#selectedMCPToolNamesMatch(sessionContext.selectedMCPToolNames, selectedMCPToolNames)
15021
15178
  ) {
15022
- this.sessionManager.appendMCPToolSelection(selectedMCPToolNames);
15179
+ if (sharedPublication)
15180
+ await this.#publishSharedMCPToolSelection(selectedMCPToolNames, assertPublicationMode);
15181
+ else {
15182
+ assertPublicationMode();
15183
+ this.sessionManager.appendMCPToolSelection(selectedMCPToolNames);
15184
+ }
15023
15185
  }
15024
15186
  }
15025
15187
  if (isExplicit && explicitActiveToolSelectionGeneration === this.#explicitActiveToolSelectionGeneration) {
@@ -15703,29 +15865,83 @@ export class AgentSession {
15703
15865
  const authStorage = this.#modelRegistry.authStorage;
15704
15866
  const authStorageOwner = this.#modelRegistry.getAuthStorageOwner();
15705
15867
  const target = authStorage.resolveOAuthPinTarget(provider, selector, authStorageOwner);
15706
- authStorage.setSessionCredentialSelector(scopeId, provider, target.canonicalSelector, authStorageOwner);
15707
- if (target.canonicalSelector.kind === "id" && !this.#credentialStoreIdentity) return;
15708
- this.sessionManager.appendCustomEntry("auth-credential-pin", {
15709
- v: 1,
15710
- scopeId,
15711
- provider,
15712
- pin: target.canonicalSelector,
15713
- ...(target.canonicalSelector.kind === "id" && this.#credentialStoreIdentity
15714
- ? { credentialStoreIdentity: this.#credentialStoreIdentity }
15715
- : {}),
15716
- });
15868
+ const apply = () =>
15869
+ authStorage.setSessionCredentialSelector(scopeId, provider, target.canonicalSelector, authStorageOwner);
15870
+ // An id pin without a credential-store identity is process-local and never persisted.
15871
+ if (target.canonicalSelector.kind === "id" && !this.#credentialStoreIdentity) {
15872
+ apply();
15873
+ return;
15874
+ }
15875
+ await this.#publishCredentialIntentThenApply(
15876
+ {
15877
+ v: 1,
15878
+ scopeId,
15879
+ provider,
15880
+ pin: target.canonicalSelector,
15881
+ ...(target.canonicalSelector.kind === "id" && this.#credentialStoreIdentity
15882
+ ? { credentialStoreIdentity: this.#credentialStoreIdentity }
15883
+ : {}),
15884
+ },
15885
+ apply,
15886
+ );
15887
+ }
15888
+
15889
+ /**
15890
+ * Credential intent is durable before it is live (#7824): a refused write leaves
15891
+ * AuthStorage untouched. Shared sessions publish through the admitted control path;
15892
+ * an uncertain or committed-but-unapplied outcome closes the session instead of
15893
+ * compensating.
15894
+ */
15895
+ async #publishCredentialIntentThenApply(data: Record<string, unknown>, apply: () => void): Promise<void> {
15896
+ const operation = "change credential selection";
15897
+ const assertMode = this.#controlPublicationModeFence(operation);
15898
+ if (!this.#usesSharedSessionPublication()) {
15899
+ this.sessionManager.appendCustomEntry("auth-credential-pin", data);
15900
+ apply();
15901
+ return;
15902
+ }
15903
+ const manager = this.sessionManager;
15904
+ const sessionId = manager.getSessionId();
15905
+ const identityGeneration = manager.getSessionIdentityGeneration();
15906
+ const current = () => {
15907
+ try {
15908
+ assertMode();
15909
+ } catch {
15910
+ return false;
15911
+ }
15912
+ return (
15913
+ !this.#isDisposed &&
15914
+ this.sessionManager === manager &&
15915
+ manager.getSessionId() === sessionId &&
15916
+ manager.getSessionIdentityGeneration() === identityGeneration
15917
+ );
15918
+ };
15919
+ const assertCurrent = () => {
15920
+ if (!current())
15921
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
15922
+ };
15923
+ const outcome = await this.#withStartedSharedControlPublication(assertCurrent, () =>
15924
+ manager.appendControlEntriesSharingSession(
15925
+ [{ type: "custom", customType: "auth-credential-pin", data }],
15926
+ current,
15927
+ ),
15928
+ );
15929
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
15930
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
15931
+ try {
15932
+ assertCurrent();
15933
+ apply();
15934
+ } catch (error) {
15935
+ return this.#failClosedSharedControl(operation, outcome, error);
15936
+ }
15717
15937
  }
15718
15938
 
15719
15939
  /** Mask persistent/global selection for this session and restore AUTO ranking. */
15720
15940
  async setCredentialAuto(provider: string): Promise<void> {
15721
15941
  const scopeId = this.credentialSessionId;
15722
- this.#modelRegistry.authStorage.setSessionCredentialAuto(provider, scopeId);
15723
- this.sessionManager.appendCustomEntry("auth-credential-pin", {
15724
- v: 1,
15725
- scopeId,
15726
- provider,
15727
- pin: { auto: true },
15728
- });
15942
+ await this.#publishCredentialIntentThenApply({ v: 1, scopeId, provider, pin: { auto: true } }, () =>
15943
+ this.#modelRegistry.authStorage.setSessionCredentialAuto(provider, scopeId),
15944
+ );
15729
15945
  }
15730
15946
 
15731
15947
  /** Current session display name, if set */
@@ -16699,16 +16915,28 @@ export class AgentSession {
16699
16915
  if (withoutEphemeralMessages.length !== messages.length) this.agent.replaceMessages(withoutEphemeralMessages);
16700
16916
  }
16701
16917
 
16702
- #appendCustomMessageEntry<T = unknown>(
16918
+ async #appendCustomMessageEntry<T = unknown>(
16703
16919
  customType: string,
16704
16920
  content: string | (TextContent | ImageContent)[],
16705
16921
  display: boolean,
16706
16922
  details?: T,
16707
16923
  attribution: MessageAttribution = "agent",
16708
16924
  observationId?: string,
16709
- ): string | undefined {
16925
+ ): Promise<string | undefined> {
16710
16926
  if (this.#isEphemeralCustomMessageType(customType)) return undefined;
16711
- return this.sessionManager.appendCustomMessageEntry(
16927
+ // A session that publishes canonical messages through the shared lease arms
16928
+ // shared admission, which refuses every later legacy append.
16929
+ if (!this.#usesSharedSessionPublication()) {
16930
+ return this.sessionManager.appendCustomMessageEntry(
16931
+ customType,
16932
+ content,
16933
+ display,
16934
+ details,
16935
+ attribution,
16936
+ observationId,
16937
+ );
16938
+ }
16939
+ const outcome = await this.sessionManager.appendCustomMessageEntrySharingSession(
16712
16940
  customType,
16713
16941
  content,
16714
16942
  display,
@@ -16716,6 +16944,221 @@ export class AgentSession {
16716
16944
  attribution,
16717
16945
  observationId,
16718
16946
  );
16947
+ if (outcome.kind !== "committed") {
16948
+ throw new Error(
16949
+ `Shared custom message append ${outcome.kind}${outcome.kind === "stale" ? `: ${outcome.reason}` : ""}${outcome.kind === "unknown" ? ` (attempted id: ${outcome.id})` : ""}`,
16950
+ { cause: outcome },
16951
+ );
16952
+ }
16953
+ return outcome.id;
16954
+ }
16955
+
16956
+ /**
16957
+ * Publish an additive custom entry at this opener's admitted branch cursor.
16958
+ *
16959
+ * A shared-append session refuses legacy appends once a canonical shared publication
16960
+ * adopted an identity this opener did not import, so every in-turn producer publishes
16961
+ * through the shared lease instead (the custom-message path does the same). Throws when
16962
+ * the publication is refused: a silently dropped entry is worse than a loud failure.
16963
+ */
16964
+ async appendCustomEntryForSession<T = unknown>(customType: string, data?: T): Promise<string | undefined> {
16965
+ if (!this.#usesSharedSessionPublication()) return this.sessionManager.appendCustomEntry(customType, data);
16966
+ const outcome = await this.sessionManager.appendCustomEntrySharingSession(customType, data);
16967
+ assertSharedAppendCommitted(`Shared ${customType} entry append`, outcome);
16968
+ return outcome.id;
16969
+ }
16970
+
16971
+ /**
16972
+ * Publish a custom entry from a synchronous call site.
16973
+ *
16974
+ * A shared-append session publishes through its admitted path in the background and
16975
+ * logs a refusal, because such a caller cannot await a transaction and a refusal must
16976
+ * not abort its turn. The legacy form throws inline exactly as before.
16977
+ */
16978
+ appendCustomEntryInBackground<T = unknown>(customType: string, data?: T): Promise<BackgroundPublicationResult> {
16979
+ if (!this.#usesSharedSessionPublication()) {
16980
+ this.sessionManager.appendCustomEntry(customType, data);
16981
+ return Promise.resolve({ committed: true });
16982
+ }
16983
+ return this.#publishInBackground(`custom entry ${customType}`, () =>
16984
+ this.sessionManager.appendCustomEntrySharingSession(customType, data),
16985
+ );
16986
+ }
16987
+
16988
+ /** Publish a message from a synchronous call site. */
16989
+ appendMessageInBackground(message: SessionPersistedMessage): Promise<BackgroundPublicationResult> {
16990
+ return this.#publishMessageInBackground("session message", message);
16991
+ }
16992
+
16993
+ /** Publish a message at this opener's admitted branch cursor. */
16994
+ async appendMessageForSession(message: SessionPersistedMessage): Promise<string> {
16995
+ if (!this.#usesSharedSessionPublication()) return this.sessionManager.appendMessage(message);
16996
+ const outcome = await this.sessionManager.appendMessageSharingSession(message);
16997
+ assertSharedAppendCommitted("Shared message append", outcome);
16998
+ return outcome.id;
16999
+ }
17000
+
17001
+ /** Publish a session recap at this opener's admitted branch cursor. */
17002
+ async appendSessionRecapForSession(input: SessionRecapInput): Promise<SessionRecapAppendResult> {
17003
+ if (!this.#usesSharedSessionPublication()) return this.sessionManager.appendSessionRecap(input);
17004
+ return this.sessionManager.appendSessionRecapSharingSession(input);
17005
+ }
17006
+
17007
+ /** Publish a label change from a synchronous call site. */
17008
+ appendLabelChangeInBackground(targetId: string, label: string | undefined): Promise<BackgroundPublicationResult> {
17009
+ if (!this.#usesSharedSessionPublication()) {
17010
+ this.sessionManager.appendLabelChange(targetId, label);
17011
+ return Promise.resolve({ committed: true });
17012
+ }
17013
+ return this.#publishInBackground("label change", () =>
17014
+ this.sessionManager.appendLabelChangeSharingSession(targetId, label),
17015
+ );
17016
+ }
17017
+
17018
+ /** Publish a mode change from a synchronous call site. */
17019
+ appendModeChangeInBackground(mode: string, data?: Record<string, unknown>): Promise<BackgroundPublicationResult> {
17020
+ if (!this.#usesSharedSessionPublication()) {
17021
+ this.sessionManager.appendModeChange(mode, data);
17022
+ return Promise.resolve({ committed: true });
17023
+ }
17024
+ return this.#publishInBackground("mode change", () =>
17025
+ this.sessionManager.appendModeChangeSharingSession(mode, data),
17026
+ );
17027
+ }
17028
+
17029
+ /**
17030
+ * Run one background publication.
17031
+ *
17032
+ * Returns the real outcome: `false` means nothing was committed, and the caller must
17033
+ * treat the entry as not persisted. A refusal never throws into the turn (a synchronous
17034
+ * producer cannot await a transaction and must not abort the run), so the cause is
17035
+ * logged here with the operation and the promise is registered for settlement joining.
17036
+ */
17037
+ #publishInBackground(
17038
+ operation: string,
17039
+ publish: () => Promise<SharedAppendOutcome>,
17040
+ ): Promise<BackgroundPublicationResult> {
17041
+ const task = publish()
17042
+ .then((outcome): BackgroundPublicationResult => {
17043
+ if (outcome.kind === "committed") return { committed: true };
17044
+ const cause = describeSharedAppendFailure(outcome);
17045
+ logger.warn("Shared session append was refused; the entry was not persisted", { operation, ...cause });
17046
+ this.#reportBackgroundRefusal(operation, cause.reason ?? cause.outcome);
17047
+ return { committed: false, cause: cause.reason };
17048
+ })
17049
+ .catch((error: unknown): BackgroundPublicationResult => {
17050
+ const reason = error instanceof Error ? error.message : String(error);
17051
+ logger.warn("Shared session append failed; the entry was not persisted", { operation, cause: reason });
17052
+ this.#reportBackgroundRefusal(operation, reason);
17053
+ return { committed: false, cause: reason };
17054
+ });
17055
+ return this.#trackBackgroundPublication(task);
17056
+ }
17057
+
17058
+ /**
17059
+ * Surface a refused background publication to the operator.
17060
+ *
17061
+ * A log line alone is not enough: an extension entry, label, todo/goal update, or
17062
+ * command result that never reached the transcript must be visible where the user is
17063
+ * looking, or it silently disappears from the next reload.
17064
+ */
17065
+ #reportBackgroundRefusal(operation: string, reason: string): void {
17066
+ if (this.#isDisposed) return;
17067
+ this.emitNotice("warning", `Could not save the ${operation} to this session: ${reason}`, "session-publication");
17068
+ }
17069
+
17070
+ /** Join a background publication at settlement time; never leaves a rejection unobserved. */
17071
+ #trackBackgroundPublication<T>(task: Promise<T>): Promise<T> {
17072
+ // The removal is part of the tracked promise itself, so awaiting the set is enough
17073
+ // for settlement: `#joinBackgroundPublications` can never re-observe a settled entry
17074
+ // and spin on a deletion that is still queued behind it.
17075
+ let settled: Promise<void>;
17076
+ const remove = () => {
17077
+ this.#backgroundPublications.delete(settled);
17078
+ };
17079
+ settled = task.then(remove, remove);
17080
+ this.#backgroundPublications.add(settled);
17081
+ return task;
17082
+ }
17083
+
17084
+ /**
17085
+ * Persist one message from a synchronous call site.
17086
+ *
17087
+ * The legacy form throws inline as before. The shared form publishes in the background:
17088
+ * the caller cannot await a transaction, and a refusal must not abort the turn, so it
17089
+ * returns the real outcome, keeps the message visible in agent state, and logs the cause.
17090
+ * `onCommitted` fires only when the entry is durable.
17091
+ */
17092
+ #publishMessageInBackground(
17093
+ label: string,
17094
+ message: SessionPersistedMessage,
17095
+ onCommitted?: () => void,
17096
+ ): Promise<BackgroundPublicationResult> {
17097
+ if (!this.#usesSharedSessionPublication()) {
17098
+ this.sessionManager.appendMessage(message);
17099
+ onCommitted?.();
17100
+ return Promise.resolve({ committed: true });
17101
+ }
17102
+ return this.#publishInBackground(label, () => this.sessionManager.appendMessageSharingSession(message)).then(
17103
+ result => {
17104
+ if (result.committed) onCommitted?.();
17105
+ return result;
17106
+ },
17107
+ );
17108
+ }
17109
+
17110
+ /**
17111
+ * Persist one deferred command result and throw when it was not committed.
17112
+ *
17113
+ * The deferred flush must be able to tell "not persisted" apart from "persisted" so it
17114
+ * can keep the entry queued for retry and withhold `onPersisted`. A background publish
17115
+ * cannot express that, so this path awaits the lease and converts every non-committed
17116
+ * outcome into a throw carrying the cause. An `unknown` outcome may already be durable,
17117
+ * so it throws a {@link SharedControlPublicationError} with code `unknown` that carries
17118
+ * the attempted id: the caller must never re-append it under a new id.
17119
+ */
17120
+ async #persistExecutionMessage(label: string, message: SessionPersistedMessage): Promise<void> {
17121
+ if (!this.#usesSharedSessionPublication()) {
17122
+ this.sessionManager.appendMessage(message);
17123
+ return;
17124
+ }
17125
+ const outcome = await this.#trackBackgroundPublication(this.sessionManager.appendMessageSharingSession(message));
17126
+ if (outcome.kind !== "committed") {
17127
+ const cause = describeSharedAppendFailure(outcome);
17128
+ this.#reportBackgroundRefusal(label, cause.reason ?? cause.outcome);
17129
+ }
17130
+ if (outcome.kind === "unknown")
17131
+ throw new SharedControlPublicationError(`record the ${label}`, {
17132
+ kind: "unknown",
17133
+ ids: [outcome.id],
17134
+ error: outcome.error,
17135
+ });
17136
+ assertSharedAppendCommitted(`Shared ${label} append`, outcome);
17137
+ }
17138
+
17139
+ /**
17140
+ * Abort the run for a refused canonical publication.
17141
+ *
17142
+ * The abort carries no reason so the agent's own cancellation path stays silent; the
17143
+ * underlying cause is logged here instead, where the operation that failed is known.
17144
+ */
17145
+ #abortRunForPublicationFailure(operation: string, error: unknown): never {
17146
+ // The thrown wrapper keeps the publication outcome as its cause; surface the
17147
+ // underlying refusal so the log names why the append was rejected.
17148
+ const refusal = error instanceof Error ? error.cause : undefined;
17149
+ const underlying =
17150
+ refusal !== null && typeof refusal === "object" && "error" in refusal
17151
+ ? refusal.error instanceof Error
17152
+ ? refusal.error.message
17153
+ : String(refusal.error)
17154
+ : undefined;
17155
+ logger.warn("Canonical session publication failed; aborting run", {
17156
+ operation,
17157
+ error: error instanceof Error ? error.message : String(error),
17158
+ ...(underlying === undefined ? {} : { cause: underlying }),
17159
+ });
17160
+ this.agent.abort();
17161
+ throw error instanceof Error ? error : new Error(String(error));
16719
17162
  }
16720
17163
 
16721
17164
  #buildUntrustedMcpServerInstructionsMessage(): CustomMessage | undefined {
@@ -16971,13 +17414,15 @@ export class AgentSession {
16971
17414
  let waitedForAbortUnwind = false;
16972
17415
  const busyInputCancellationGeneration = this.#promptPreflightCancellationGeneration;
16973
17416
  const commitBusyWorkflowIntent = async () => {
16974
- if (!workflowIntentDiff || !this.#usesSharedWorkflowIntentAppend()) return;
17417
+ if (!workflowIntentDiff || !this.#usesSharedSessionPublication()) return;
16975
17418
  // A busy predecessor may become idle while publication awaits. Its normal
16976
17419
  // generation change is not cancellation: the queue helpers admit a follow-up
16977
17420
  // against the current state rather than pretending the old run remains live.
16978
17421
  const assertCurrent = () => {
16979
- if (options?.preflightSignal?.aborted ||
16980
- this.#promptPreflightCancellationGeneration !== busyInputCancellationGeneration)
17422
+ if (
17423
+ options?.preflightSignal?.aborted ||
17424
+ this.#promptPreflightCancellationGeneration !== busyInputCancellationGeneration
17425
+ )
16981
17426
  throw promptPreflightCancelledError();
16982
17427
  };
16983
17428
  assertCurrent();
@@ -17003,7 +17448,7 @@ export class AgentSession {
17003
17448
  // Check if this is a steer during a busy turn BEFORE waiting on selection fences (#7613).
17004
17449
  // This ensures steers are injected immediately even when config hot reload is pending.
17005
17450
  // However, steers still wait behind explicit model-selection fences to preserve selection ordering.
17006
- if (options?.streamingBehavior === "steer" && (this.#isLiveTurnBusy() && !waitedForAbortUnwind)) {
17451
+ if (options?.streamingBehavior === "steer" && this.#isLiveTurnBusy() && !waitedForAbortUnwind) {
17007
17452
  // However, do not bypass for steers with an already-aborted preflight signal.
17008
17453
  // The signal abort indicates user cancellation and must be respected.
17009
17454
  if (options?.preflightSignal?.aborted) throw promptPreflightCancelledError();
@@ -17013,12 +17458,12 @@ export class AgentSession {
17013
17458
  await awaitPromptInvocationPreflight(this.#selectionFenceTail, admissionSignal);
17014
17459
  }
17015
17460
  if (this.#eagerDelegationDirty) throw new Error("Session delegation is not ready");
17016
- if (workflowIntentDiff && this.#usesSharedWorkflowIntentAppend()) await commitBusyWorkflowIntent();
17461
+ if (workflowIntentDiff && this.#usesSharedSessionPublication()) await commitBusyWorkflowIntent();
17017
17462
  await this.#queueSteer(expandedText, options?.images, {
17018
17463
  claimsGenuineUserIntent,
17019
17464
  forceOneAtATime: options.steerQueuePolicy === "sequential",
17020
17465
  });
17021
- if (workflowIntentDiff && !this.#usesSharedWorkflowIntentAppend()) {
17466
+ if (workflowIntentDiff && !this.#usesSharedSessionPublication()) {
17022
17467
  this.sessionManager.appendCustomEntry(WORKFLOW_INTENT_DIFF_CUSTOM_TYPE, workflowIntentDiff);
17023
17468
  }
17024
17469
  this.#assertExternalSessionIngress();
@@ -17048,7 +17493,7 @@ export class AgentSession {
17048
17493
  if (!options?.streamingBehavior) {
17049
17494
  throw new AgentBusyError();
17050
17495
  }
17051
- if (workflowIntentDiff && this.#usesSharedWorkflowIntentAppend()) await commitBusyWorkflowIntent();
17496
+ if (workflowIntentDiff && this.#usesSharedSessionPublication()) await commitBusyWorkflowIntent();
17052
17497
  if (options.streamingBehavior === "followUp") {
17053
17498
  await this.#queueFollowUpTextAfterReservation(expandedText, options?.images, {
17054
17499
  forceOneAtATime: options.followUpQueuePolicy === "sequential",
@@ -17060,7 +17505,7 @@ export class AgentSession {
17060
17505
  forceOneAtATime: options.steerQueuePolicy === "sequential",
17061
17506
  });
17062
17507
  }
17063
- if (workflowIntentDiff && !this.#usesSharedWorkflowIntentAppend()) {
17508
+ if (workflowIntentDiff && !this.#usesSharedSessionPublication()) {
17064
17509
  this.sessionManager.appendCustomEntry(WORKFLOW_INTENT_DIFF_CUSTOM_TYPE, workflowIntentDiff);
17065
17510
  }
17066
17511
  this.#assertExternalSessionIngress();
@@ -17083,7 +17528,7 @@ export class AgentSession {
17083
17528
  options.preflightSignal?.aborted !== true &&
17084
17529
  !this.#abortUnwind
17085
17530
  ) {
17086
- if (workflowIntentDiff && this.#usesSharedWorkflowIntentAppend()) await commitBusyWorkflowIntent();
17531
+ if (workflowIntentDiff && this.#usesSharedSessionPublication()) await commitBusyWorkflowIntent();
17087
17532
  admission.release();
17088
17533
  if (options.streamingBehavior === "followUp") {
17089
17534
  await this.#queueFollowUpTextAfterReservation(expandedText, options?.images, {
@@ -17096,7 +17541,7 @@ export class AgentSession {
17096
17541
  forceOneAtATime: options.steerQueuePolicy === "sequential",
17097
17542
  });
17098
17543
  }
17099
- if (workflowIntentDiff && !this.#usesSharedWorkflowIntentAppend()) {
17544
+ if (workflowIntentDiff && !this.#usesSharedSessionPublication()) {
17100
17545
  this.sessionManager.appendCustomEntry(WORKFLOW_INTENT_DIFF_CUSTOM_TYPE, workflowIntentDiff);
17101
17546
  }
17102
17547
  this.#assertExternalSessionIngress();
@@ -17493,7 +17938,7 @@ export class AgentSession {
17493
17938
  this.#throwIfPromptPreflightCancelled(generation, preflightSignal);
17494
17939
  }
17495
17940
  // Retry anything whose previous post-turn persistence failed before the new prompt.
17496
- this.#flushPendingPromptMessages();
17941
+ await this.#flushPendingPromptMessages();
17497
17942
 
17498
17943
  // Reset todo reminder count on new user prompt
17499
17944
  this.#todoReminderCount = 0;
@@ -17838,10 +18283,11 @@ export class AgentSession {
17838
18283
  onAccepted: () => {
17839
18284
  // The shared workflow record must commit before the prompt starts or its
17840
18285
  // canonical user message advances the branch. Other hosts retain sync admission.
17841
- if (options?.workflowIntentDiff && this.#usesSharedWorkflowIntentAppend()) {
18286
+ if (options?.workflowIntentDiff && this.#usesSharedSessionPublication()) {
17842
18287
  return (async () => {
17843
18288
  await this.#appendSharedWorkflowIntentDiff(options.workflowIntentDiff!, () =>
17844
- this.#throwIfPromptPreflightCancelled(generation, preflightSignal));
18289
+ this.#throwIfPromptPreflightCancelled(generation, preflightSignal),
18290
+ );
17845
18291
  this.#throwIfPromptPreflightCancelled(generation, preflightSignal);
17846
18292
  if (options?.resetRetryReplaySafety) this.#admitSessionRecapRequest(promptMessage);
17847
18293
  })();
@@ -19044,7 +19490,7 @@ export class AgentSession {
19044
19490
  return;
19045
19491
  }
19046
19492
  this.agent.appendMessage(appMessage);
19047
- this.#appendCustomMessageEntry(
19493
+ await this.#appendCustomMessageEntry(
19048
19494
  message.customType,
19049
19495
  message.content,
19050
19496
  message.display,
@@ -19101,7 +19547,7 @@ export class AgentSession {
19101
19547
  }
19102
19548
 
19103
19549
  this.agent.appendMessage(appMessage);
19104
- this.#appendCustomMessageEntry(
19550
+ await this.#appendCustomMessageEntry(
19105
19551
  message.customType,
19106
19552
  message.content,
19107
19553
  message.display,
@@ -20133,11 +20579,11 @@ export class AgentSession {
20133
20579
  const hadLivePrompt = this.#livePromptsInFlight() > 0;
20134
20580
  for (const token of this.#inFlightPromptTokens.keys()) this.#abandonedInFlightPrompts.add(token);
20135
20581
  if (hadLivePrompt) this.#releasePowerAssertion();
20136
- try {
20137
- this.#flushPendingPromptMessages();
20138
- } catch (error) {
20582
+ // Recovery must not block on a shared publication; the flush keeps uncommitted
20583
+ // entries queued for a later retry and logs its own failure here instead.
20584
+ void this.#flushPendingPromptMessages().catch(error => {
20139
20585
  logger.warn("Failed to flush deferred prompt messages during forced recovery", { error: String(error) });
20140
- }
20586
+ });
20141
20587
  this.#resolveSessionSettlement();
20142
20588
  const forceAbortLogicalRunId = this.agent.currentManagedLogicalRunId ?? this.#activeLogicalRunId;
20143
20589
  try {
@@ -20897,7 +21343,9 @@ export class AgentSession {
20897
21343
  }
20898
21344
  // Follow-ups bound to the aborted run were discarded at its agent_end; keep
20899
21345
  // the snapshots from handing them back to the replacement run or a rollback.
20900
- const endedFollowUps = runBoundFollowUpsBeforeAbort.filter(entry => !this.#isPromptRunLive(entry.target));
21346
+ const endedFollowUps = runBoundFollowUpsBeforeAbort.filter(
21347
+ entry => !this.#isPromptRunLive(entry.target),
21348
+ );
20901
21349
  if (endedFollowUps.length > 0) {
20902
21350
  const ended = new Set(endedFollowUps.map(entry => entry.message));
20903
21351
  queueSnapshot.followUp.splice(
@@ -21101,6 +21549,16 @@ export class AgentSession {
21101
21549
  */
21102
21550
  newSession(options?: NewSessionOptions): Promise<boolean> {
21103
21551
  if (this.#newSessionTransition) return this.#newSessionTransition;
21552
+ // /drop deletes the predecessor after the successor is live. A shared session's
21553
+ // transcript cannot be deleted by this opener (#7824): refuse before switching
21554
+ // instead of switching and then reporting a drop that never happened.
21555
+ if (options?.drop) {
21556
+ try {
21557
+ this.sessionManager.assertLegacyMutationAllowed("drop session");
21558
+ } catch (error) {
21559
+ return Promise.reject(error);
21560
+ }
21561
+ }
21104
21562
  // Acquire the shared session-transition lease only when starting a fresh transition
21105
21563
  // (the dedup above returns the in-flight promise without re-acquiring).
21106
21564
  this.#beginSessionTransition("new-session");
@@ -21406,6 +21864,13 @@ export class AgentSession {
21406
21864
  * session identity and durable history trail.
21407
21865
  */
21408
21866
  async clearContext(): Promise<boolean> {
21867
+ // A context clear appends a parentless root marker. A shared session publishes that
21868
+ // root through the common admitted control publication before resetting anything
21869
+ // (#7824); a legacy session keeps the legacy refusal. Adoption while the turn is
21870
+ // aborted refuses before the reset rather than switching protocols mid-clear.
21871
+ const operation = "clear context";
21872
+ const assertMode = this.#controlPublicationModeFence(operation);
21873
+ const sharedPublication = this.#usesSharedSessionPublication();
21409
21874
  this.#beginSessionTransition("clear-context");
21410
21875
  try {
21411
21876
  const sessionId = this.sessionId;
@@ -21420,6 +21885,17 @@ export class AgentSession {
21420
21885
  this.#closeAllProviderSessions("context clear");
21421
21886
  this.#terminalizeQueuedSdkWorkForSessionTransition(this.#queuedMessagesForSessionTransition());
21422
21887
  this.#resetActiveSdkRunOwnership();
21888
+ // Shared admission may have latched while the turn was aborted and settled.
21889
+ assertMode();
21890
+ if (sharedPublication) {
21891
+ const committed = await this.#publishSharedContextClear(operation, sessionId, assertMode);
21892
+ try {
21893
+ this.#applyContextClear(sessionId);
21894
+ } catch (error) {
21895
+ return this.#failClosedSharedControl(operation, committed, error);
21896
+ }
21897
+ return true;
21898
+ }
21423
21899
  this.#commitSessionTransition();
21424
21900
  this.agent.reset();
21425
21901
  await this.sessionManager.flush();
@@ -21446,12 +21922,83 @@ export class AgentSession {
21446
21922
  }
21447
21923
  }
21448
21924
 
21925
+ /**
21926
+ * Publish the shared `/clear` root and its carried-over model, thinking, tier and
21927
+ * profile-ownership intent as one admitted append at this opener's cursor. The root
21928
+ * is parentless, so the earlier branch and any unseen sibling stay in the transcript;
21929
+ * nothing is rewritten. Throws before any live reset unless the entries committed.
21930
+ */
21931
+ async #publishSharedContextClear(
21932
+ operation: string,
21933
+ sessionId: string,
21934
+ assertMode: () => void,
21935
+ ): Promise<Extract<SharedEntriesAppendOutcome, { kind: "committed" }>> {
21936
+ // Entries already handed to background publication belong to the cleared branch.
21937
+ await this.#joinBackgroundPublications();
21938
+ assertMode();
21939
+ const manager = this.sessionManager;
21940
+ const identityGeneration = manager.getSessionIdentityGeneration();
21941
+ const model = this.model;
21942
+ const thinkingLevel = this.thinkingLevel;
21943
+ const serviceTier = this.serviceTier ?? null;
21944
+ const entries: SharedControlEntry[] = [
21945
+ ...manager.contextClearControlEntries({ sessionId }),
21946
+ { type: "thinking_level_change", level: thinkingLevel, operatorIntent: false },
21947
+ ];
21948
+ if (model) entries.push({ type: "model_change", model: `${model.provider}/${model.id}`, role: "default" });
21949
+ entries.push({ type: "service_tier_change", serviceTier });
21950
+ const current = () => {
21951
+ try {
21952
+ assertMode();
21953
+ } catch {
21954
+ return false;
21955
+ }
21956
+ return (
21957
+ !this.#isDisposed &&
21958
+ this.sessionManager === manager &&
21959
+ this.sessionId === sessionId &&
21960
+ manager.getSessionId() === sessionId &&
21961
+ manager.getSessionIdentityGeneration() === identityGeneration &&
21962
+ this.model === model &&
21963
+ this.thinkingLevel === thinkingLevel &&
21964
+ (this.serviceTier ?? null) === serviceTier
21965
+ );
21966
+ };
21967
+ const outcome = await this.#withStartedSharedControlPublication(
21968
+ () => {
21969
+ if (!current())
21970
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
21971
+ },
21972
+ () => manager.appendControlEntriesSharingSession(entries, current),
21973
+ );
21974
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
21975
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
21976
+ if (!current()) return this.#failClosedSharedControl(operation, outcome);
21977
+ return outcome;
21978
+ }
21979
+
21980
+ /** The live half of a committed shared `/clear`; its transcript entries are already durable. */
21981
+ #applyContextClear(sessionId: string): void {
21982
+ this.#commitSessionTransition();
21983
+ this.agent.reset();
21984
+ this.setTodoPhases([]);
21985
+ this.#syncAgentSessionId(sessionId);
21986
+ this.#steeringMessages = [];
21987
+ this.#followUpMessages = [];
21988
+ this.#pendingNextTurnMessages = [];
21989
+ this.#scheduledHiddenNextTurnGeneration = undefined;
21990
+ this.#todoReminderCount = 0;
21991
+ this.#planReferenceSent = false;
21992
+ this.#planReferencePath = "local://PLAN.md";
21993
+ }
21994
+
21449
21995
  /**
21450
21996
  * Generate and conditionally apply a title for the first accepted text input.
21451
21997
  * Call independently of prompt delivery, before the first user message is recorded.
21452
21998
  * A host retiring this session must abort signal synchronously before retirement.
21453
21999
  */
21454
22000
  async generateAutoSessionTitle(text: string, options?: { signal?: AbortSignal }): Promise<AutoSessionTitleResult> {
22001
+ const sharedPublication = this.#usesSharedSessionPublication();
21455
22002
  const manager = this.sessionManager;
21456
22003
  const sessionId = this.sessionId;
21457
22004
  const managerId = manager.getSessionId();
@@ -21508,13 +22055,19 @@ export class AgentSession {
21508
22055
  if ($pickenv("GJC_NO_TITLE", "PI_NO_TITLE")) return { kind: "skipped", reason: "disabled" };
21509
22056
  if (!title) return { kind: "skipped", reason: "unavailable" };
21510
22057
  if (manager.getSessionName()) return { kind: "skipped", reason: "named" };
22058
+ if (this.#usesSharedSessionPublication() !== sharedPublication)
22059
+ throw new Error("Session publication protocol changed while generating title");
21511
22060
  let committedTitle = "";
21512
- if (this.#usesSharedWorkflowIntentAppend()) {
22061
+ if (sharedPublication) {
21513
22062
  const outcome = await this.#withStartedSharedControlPublication(
21514
22063
  () => {
21515
22064
  if (stale()) throw new SessionTitlePersistenceStaleError();
21516
22065
  },
21517
- () => manager.setSessionNameSharingSession(title, "auto", { isCurrent: () => !stale(), onlyIfUnnamed: true }),
22066
+ () =>
22067
+ manager.setSessionNameSharingSession(title, "auto", {
22068
+ isCurrent: () => !stale(),
22069
+ onlyIfUnnamed: true,
22070
+ }),
21518
22071
  );
21519
22072
  if (outcome.kind === "committed") return { kind: "applied", title: outcome.title };
21520
22073
  if (outcome.kind === "skipped") return { kind: "skipped", reason: outcome.reason };
@@ -21542,7 +22095,7 @@ export class AgentSession {
21542
22095
  * Set a display name for the current session.
21543
22096
  */
21544
22097
  async setSessionName(name: string, source: "auto" | "user" = "auto"): Promise<boolean> {
21545
- if (!this.#usesSharedWorkflowIntentAppend()) return this.sessionManager.setSessionName(name, source);
22098
+ if (!this.#usesSharedSessionPublication()) return this.sessionManager.setSessionName(name, source);
21546
22099
  const manager = this.sessionManager;
21547
22100
  const sessionId = manager.getSessionId();
21548
22101
  const identityGeneration = manager.getSessionIdentityGeneration();
@@ -21767,7 +22320,8 @@ export class AgentSession {
21767
22320
  recordUsage?: boolean;
21768
22321
  },
21769
22322
  ): Promise<void> {
21770
- this.sessionManager.assertLegacyMutationAllowed("set model");
22323
+ // A default user selection is admitted by setDefaultModelSelection, which publishes
22324
+ // through the shared protocol when the session requires it.
21771
22325
  if (role === "default" && (options?.cause ?? "user-selection") === "user-selection") {
21772
22326
  // The default role has no parent level to inherit. A selector reports `inherit`
21773
22327
  // when the chosen model cannot keep the current level (e.g. a non-reasoning
@@ -21807,6 +22361,11 @@ export class AgentSession {
21807
22361
  );
21808
22362
  return;
21809
22363
  }
22364
+ // Internal role/cause writes have no shared publication protocol: refuse before any
22365
+ // live effect rather than mutate the model and then hit the legacy append guard.
22366
+ if (this.#usesSharedSessionPublication())
22367
+ throw new SharedSessionMutationUnsupportedError(`set ${role} model (${options?.cause ?? "user-selection"})`);
22368
+ this.sessionManager.assertLegacyMutationAllowed("set model");
21810
22369
  const previousEditMode = this.#resolveActiveEditMode();
21811
22370
  const apiKey = await this.#modelRegistry.getApiKey(model, this.credentialSessionId);
21812
22371
  if (!apiKey) {
@@ -22302,6 +22861,28 @@ export class AgentSession {
22302
22861
  return { applied: false, settingsChanged: false, modelsChanged: false, changedSettings: [] };
22303
22862
  }
22304
22863
 
22864
+ // A shared session publishes the profile/live-model transcript entries through the
22865
+ // common admitted control publication before settings, catalog or live model
22866
+ // publication (#7824); a legacy session keeps the synchronous legacy writes.
22867
+ let sharedReload: CommittedModelProfileSessionPublication | undefined;
22868
+ if (prepared || preparedLiveModelSelection) {
22869
+ try {
22870
+ if (this.#usesSharedSessionPublication()) {
22871
+ sharedReload = await this.#publishSharedConfigurationReload(
22872
+ prepared,
22873
+ preparedLiveModelSelection,
22874
+ { preserveDefaultModelSelection, preserveLiveModelSelection },
22875
+ () => stagedModels?.isCurrent() === true && !reloadSignal.aborted,
22876
+ );
22877
+ } else {
22878
+ this.sessionManager.assertLegacyAppendAllowed("reload model profile configuration");
22879
+ }
22880
+ } catch (error) {
22881
+ stagedModels!.rollback();
22882
+ modelRollbackAttempted = true;
22883
+ throw new ConfigurationReloadError("PUBLICATION_FAILED", error);
22884
+ }
22885
+ }
22305
22886
  let publication: SettingsConfigReloadPublication | undefined;
22306
22887
  let modelCommitStarted = false;
22307
22888
  let activationPublicationStarted = false;
@@ -22314,12 +22895,22 @@ export class AgentSession {
22314
22895
  stagedModels!.commit();
22315
22896
  if (prepared) {
22316
22897
  activationPublicationStarted = true;
22317
- publishPreparedModelProfileActivation(prepared, {
22318
- preserveDefaultModelSelection,
22319
- preserveLiveModelSelection,
22320
- });
22898
+ publishPreparedModelProfileActivation(
22899
+ prepared,
22900
+ {
22901
+ preserveDefaultModelSelection,
22902
+ preserveLiveModelSelection,
22903
+ },
22904
+ sharedReload,
22905
+ );
22906
+ } else if (sharedReload) {
22907
+ this.publishCommittedModelProfileSessionState(
22908
+ sharedReload.plan,
22909
+ sharedReload.receipt,
22910
+ sharedReload.selection,
22911
+ );
22321
22912
  }
22322
- if (preparedLiveModelSelection) {
22913
+ if (preparedLiveModelSelection && !sharedReload) {
22323
22914
  this.#assertPreparedProfileModelSelectionCurrent(preparedLiveModelSelection);
22324
22915
  liveModelSelectionCommitted = true;
22325
22916
  this.commitPreparedProfileModelSelection(preparedLiveModelSelection, mutationRevision => {
@@ -22332,6 +22923,34 @@ export class AgentSession {
22332
22923
  publication.finalize();
22333
22924
  modelCommitSucceeded = true;
22334
22925
  } catch (error) {
22926
+ if (sharedReload) {
22927
+ // The transcript already holds the reload's intent: restore only the
22928
+ // process-wide settings and catalog, never compensate the session over its
22929
+ // admitted write. The session is closed instead.
22930
+ const rollbackErrors: unknown[] = [];
22931
+ try {
22932
+ publication?.rollback();
22933
+ } catch (rollbackError) {
22934
+ rollbackErrors.push(rollbackError);
22935
+ }
22936
+ if (modelCommitStarted) {
22937
+ try {
22938
+ stagedModels!.rollback();
22939
+ } catch (rollbackError) {
22940
+ rollbackErrors.push(rollbackError);
22941
+ }
22942
+ modelRollbackAttempted = true;
22943
+ }
22944
+ try {
22945
+ this.#failClosedSharedControl(
22946
+ "reload model profile configuration",
22947
+ sharedReload.receipt,
22948
+ rollbackErrors.length > 0 ? new AggregateError([error, ...rollbackErrors]) : error,
22949
+ );
22950
+ } catch (closed) {
22951
+ throw new ConfigurationReloadError("PUBLICATION_FAILED", closed);
22952
+ }
22953
+ }
22335
22954
  const rollbackErrors: unknown[] = [];
22336
22955
  if (liveModelSelectionCommitted && committedThinkingLevelLiveMutationRevision === undefined) {
22337
22956
  committedThinkingLevelLiveMutationRevision = this.#thinkingLevelLiveMutationRevision;
@@ -22948,7 +23567,8 @@ export class AgentSession {
22948
23567
  onAfterActivation?: () => void;
22949
23568
  },
22950
23569
  ): Promise<{ changed: boolean; id: string }> {
22951
- this.sessionManager.assertLegacyMutationAllowed("select model profile");
23570
+ const sharedPublication = this.usesSharedControlPublication();
23571
+ if (!sharedPublication) this.sessionManager.assertLegacyMutationAllowed("select model profile");
22952
23572
  const owner = this.#sessionAdmissionContext.getStore();
22953
23573
  if (owner && !owner.released) throw this.#sessionAdmissionBusyError();
22954
23574
  this.#assertSessionAdmissionOpen();
@@ -23012,7 +23632,9 @@ export class AgentSession {
23012
23632
  }
23013
23633
  };
23014
23634
  const assertRuntime = () => {
23015
- this.sessionManager.assertLegacyMutationAllowed("select model profile");
23635
+ if (this.usesSharedControlPublication() !== sharedPublication)
23636
+ throw new Error("Session publication protocol changed while selecting profile");
23637
+ if (!sharedPublication) this.sessionManager.assertLegacyMutationAllowed("select model profile");
23016
23638
  assertBound();
23017
23639
  if (!util.isDeepStrictEqual(captureRuntime(), expectedRuntime))
23018
23640
  throw new Error("Session model, thinking, or role intent changed while selecting profile");
@@ -23116,6 +23738,26 @@ export class AgentSession {
23116
23738
  },
23117
23739
  );
23118
23740
  } catch (error) {
23741
+ const sharedOutcome = prepared?.sharedPublicationOutcome;
23742
+ if (sharedOutcome?.kind === "committed" || sharedOutcome?.kind === "unknown") {
23743
+ if (error instanceof ModelProfileApplyCommittedError || error instanceof ModelProfilePublicationError)
23744
+ throw error;
23745
+ try {
23746
+ void this.dispose().catch(disposalError => {
23747
+ logger.warn("Committed profile session teardown failed", { error: String(disposalError) });
23748
+ });
23749
+ } catch (disposalError) {
23750
+ logger.warn("Committed profile session teardown failed", { error: String(disposalError) });
23751
+ }
23752
+ const failure = new ModelProfilePublicationError(sharedOutcome, error);
23753
+ if (prepared?.committedOwnership)
23754
+ throw new ModelProfileApplyCommittedError(
23755
+ prepared.profileName,
23756
+ prepared.committedOwnership.version,
23757
+ failure,
23758
+ );
23759
+ throw failure;
23760
+ }
23119
23761
  if (prepared?.committedOwnership && !(error instanceof ModelProfileApplyCommittedError)) {
23120
23762
  try {
23121
23763
  void this.dispose().catch(disposalError => {
@@ -23201,6 +23843,84 @@ export class AgentSession {
23201
23843
  };
23202
23844
  }
23203
23845
 
23846
+ /**
23847
+ * Refuse before any caller-side effect when {@link setConfiguredModelChain}'s legacy
23848
+ * append would be refused (shared admission latched; #7824).
23849
+ */
23850
+ assertConfiguredModelChainWritable(): void {
23851
+ this.sessionManager.assertLegacyAppendAllowed("set configured model chain");
23852
+ }
23853
+
23854
+ /**
23855
+ * Persist a configured chain on behalf of a control that already committed its durable
23856
+ * settings. A shared session publishes the chain through the common admitted control
23857
+ * publication before the runtime fallback controller changes (#7824); a legacy session
23858
+ * appends it as {@link setConfiguredModelChain} does. `isCurrent` is the caller's own
23859
+ * currentness fence and is re-checked under the publication lease.
23860
+ */
23861
+ async setConfiguredModelChainForControl(
23862
+ role: string,
23863
+ entries: readonly string[],
23864
+ origin: string,
23865
+ identity: string | undefined,
23866
+ explicitHead: boolean,
23867
+ isCurrent: () => boolean,
23868
+ ): Promise<void> {
23869
+ const operation = "set configured model chain";
23870
+ const assertMode = this.#controlPublicationModeFence(operation);
23871
+ if (!this.#usesSharedSessionPublication()) {
23872
+ this.setConfiguredModelChain(role, entries, origin, identity, explicitHead);
23873
+ return;
23874
+ }
23875
+ const manager = this.sessionManager;
23876
+ const sessionId = this.sessionId;
23877
+ const identityGeneration = manager.getSessionIdentityGeneration();
23878
+ const current = () => {
23879
+ try {
23880
+ assertMode();
23881
+ } catch {
23882
+ return false;
23883
+ }
23884
+ return (
23885
+ !this.#isDisposed &&
23886
+ this.sessionManager === manager &&
23887
+ this.sessionId === sessionId &&
23888
+ manager.getSessionIdentityGeneration() === identityGeneration &&
23889
+ isCurrent()
23890
+ );
23891
+ };
23892
+ const outcome = await this.#withStartedSharedControlPublication(
23893
+ () => {
23894
+ if (!current())
23895
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
23896
+ },
23897
+ () =>
23898
+ manager.appendControlEntriesSharingSession(
23899
+ [
23900
+ {
23901
+ type: "configured_model_chain",
23902
+ chain: {
23903
+ role,
23904
+ entries: [...entries],
23905
+ origin,
23906
+ identity,
23907
+ explicitHead,
23908
+ cleared: entries.length === 0,
23909
+ },
23910
+ },
23911
+ ],
23912
+ current,
23913
+ ),
23914
+ );
23915
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
23916
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
23917
+ if (!current()) return this.#failClosedSharedControl(operation, outcome);
23918
+ if (role === "default") {
23919
+ this.#defaultFallbackController = undefined;
23920
+ this.#defaultFallbackExhaustedLastTurn = false;
23921
+ }
23922
+ }
23923
+
23204
23924
  /** Persist the configured fallback selectors for a model role. */
23205
23925
  setConfiguredModelChain(
23206
23926
  role: string,
@@ -23336,6 +24056,126 @@ export class AgentSession {
23336
24056
  this.sessionManager.appendModelChange(selector, "default");
23337
24057
  }
23338
24058
 
24059
+ /**
24060
+ * A user's per-session default model choice (ACP/SDK `model.set`) in a shared session.
24061
+ * The resume default, effective thinking and configured chain are published as one
24062
+ * admitted append before any live model, thinking or profile state changes.
24063
+ */
24064
+ async #setSharedSessionDefaultModel(
24065
+ model: Model,
24066
+ thinkingLevel: ThinkingLevel | undefined,
24067
+ options: { signal?: AbortSignal; shouldMutate?: () => boolean; onMutationStarted?: () => void },
24068
+ ): Promise<void> {
24069
+ const operation = "set session model";
24070
+ const assertMode = this.#controlPublicationModeFence(operation);
24071
+ if (options.signal?.aborted) return;
24072
+ const manager = this.sessionManager;
24073
+ const expectedSessionId = this.sessionId;
24074
+ const identityGeneration = manager.getSessionIdentityGeneration();
24075
+ const expectedMutationRevision = this.#defaultModelSelectionMutationRevision;
24076
+ const thinkingRevision = this.#thinkingLevelMutationRevision;
24077
+ const observedAtRequest = readDurableModelProfileOwnership(this.settings);
24078
+ const previousEditMode = this.#resolveActiveEditMode();
24079
+ const selector = `${model.provider}/${model.id}`;
24080
+ let committedOwnership: DurableModelProfileOwnership | undefined;
24081
+ const current = () => {
24082
+ try {
24083
+ assertMode();
24084
+ } catch {
24085
+ return false;
24086
+ }
24087
+ return (
24088
+ !options.signal?.aborted &&
24089
+ !this.#isDisposed &&
24090
+ this.sessionManager === manager &&
24091
+ this.sessionId === expectedSessionId &&
24092
+ manager.getSessionIdentityGeneration() === identityGeneration &&
24093
+ this.#defaultModelSelectionMutationRevision === expectedMutationRevision &&
24094
+ this.#thinkingLevelMutationRevision === thinkingRevision &&
24095
+ options.shouldMutate?.() !== false &&
24096
+ (!committedOwnership ||
24097
+ util.isDeepStrictEqual(readDurableModelProfileOwnership(this.settings), committedOwnership))
24098
+ );
24099
+ };
24100
+ const assertCurrent = () => {
24101
+ if (!current()) throw new Error("Session changed while selecting model");
24102
+ };
24103
+ const apiKey = await this.#modelRegistry.getApiKey(model, this.credentialSessionId);
24104
+ if (options.signal?.aborted) return;
24105
+ assertCurrent();
24106
+ if (!apiKey) throw new Error(`No API key for ${selector}`);
24107
+ if (options.shouldMutate && !options.shouldMutate()) return;
24108
+ options.onMutationStarted?.();
24109
+ const requestedLevel = thinkingLevel ?? model.thinking?.defaultLevel ?? this.thinkingLevel;
24110
+ const effectiveLevel = resolveThinkingLevelForModel(model, requestedLevel);
24111
+ let materialized = false;
24112
+ if (observedAtRequest.marker.kind === "profile") {
24113
+ const patches = this.#concreteDefaultModelSelectionPatches(model, effectiveLevel);
24114
+ materialized = patches.some(patch => patch.path === "modelRoles");
24115
+ committedOwnership = (
24116
+ await commitDurableModelProfileOwnershipWithResult(
24117
+ this.settings,
24118
+ { kind: "cleared" },
24119
+ patches,
24120
+ assertCurrent,
24121
+ observedAtRequest,
24122
+ )
24123
+ ).ownership;
24124
+ }
24125
+ // A durable ownership winner is never rewound: any later failure closes the session.
24126
+ const failAfterOwnership = (error: unknown): never => {
24127
+ void this.dispose().catch(disposalError =>
24128
+ logger.warn("Committed model teardown failed", { error: String(disposalError) }),
24129
+ );
24130
+ throw new ModelProfileApplyCommittedError(selector, committedOwnership!.version, error);
24131
+ };
24132
+ const entries: SharedControlEntry[] = [{ type: "model_change", model: selector, role: "default" }];
24133
+ if (effectiveLevel !== this.#thinkingLevel)
24134
+ entries.push({ type: "thinking_level_change", level: effectiveLevel, operatorIntent: false });
24135
+ entries.push({
24136
+ type: "configured_model_chain",
24137
+ chain: {
24138
+ role: "default",
24139
+ entries: [formatModelSelectorValue(selector, requestedLevel)],
24140
+ origin: "model_selection",
24141
+ explicitHead: true,
24142
+ cleared: false,
24143
+ },
24144
+ });
24145
+ let outcome: SharedEntriesAppendOutcome;
24146
+ try {
24147
+ outcome = await this.#withStartedSharedControlPublication(assertCurrent, () =>
24148
+ manager.appendControlEntriesSharingSession(entries, current),
24149
+ );
24150
+ } catch (error) {
24151
+ if (committedOwnership) return failAfterOwnership(error);
24152
+ throw error;
24153
+ }
24154
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
24155
+ if (outcome.kind !== "committed") {
24156
+ const error = new SharedControlPublicationError(operation, outcome);
24157
+ if (committedOwnership) return failAfterOwnership(error);
24158
+ throw error;
24159
+ }
24160
+ try {
24161
+ assertCurrent();
24162
+ this.markUserModelSelection();
24163
+ this.#btwPrefixLedger.clear();
24164
+ this.#setModelAuthoritatively(model, "user-selection");
24165
+ this.#unavailableModelProfile = undefined;
24166
+ this.recordModelSelectionUsage(model, this.beginModelSelectionUsage());
24167
+ this.#seedSessionCanonicalVariant(model);
24168
+ this.#recordUserCanonicalVariantSelection();
24169
+ this.#applyThinkingLevel(requestedLevel, false, false, undefined, true);
24170
+ this.#publishConcreteDefaultProfileState(materialized);
24171
+ this.#defaultFallbackController = undefined;
24172
+ this.#defaultFallbackExhaustedLastTurn = false;
24173
+ } catch (error) {
24174
+ return this.#failClosedSharedControl(operation, outcome, error);
24175
+ }
24176
+ await this.#syncEditToolModeAfterModelChange(previousEditMode);
24177
+ }
24178
+
23339
24179
  async #setSharedTemporaryModel(
23340
24180
  model: Model,
23341
24181
  thinkingLevel: ThinkingLevel | undefined,
@@ -23346,7 +24186,7 @@ export class AgentSession {
23346
24186
  shouldMutate?: () => boolean;
23347
24187
  onMutationStarted?: () => void;
23348
24188
  },
23349
- ): Promise<TemporaryProviderSessionScope | void> {
24189
+ ): Promise<TemporaryProviderSessionScope | undefined> {
23350
24190
  const manager = this.sessionManager;
23351
24191
  const sessionId = manager.getSessionId();
23352
24192
  const file = manager.getSessionFile();
@@ -23493,12 +24333,19 @@ export class AgentSession {
23493
24333
  // biome-ignore lint/suspicious/noConfusingVoidType: Existing session adapters return Promise<void>; a scope is optional.
23494
24334
  ): Promise<TemporaryProviderSessionScope | void> {
23495
24335
  if (
23496
- this.#usesSharedWorkflowIntentAppend() &&
24336
+ this.#usesSharedSessionPublication() &&
23497
24337
  !options?.persistAsSessionDefault &&
23498
24338
  (options?.cause === undefined || options.cause === "temporary-operation")
23499
24339
  ) {
23500
24340
  return this.#setSharedTemporaryModel(model, thinkingLevel, options ?? {});
23501
24341
  }
24342
+ if (
24343
+ this.#usesSharedSessionPublication() &&
24344
+ options?.persistAsSessionDefault === true &&
24345
+ options.cause === "user-selection"
24346
+ ) {
24347
+ return this.#setSharedSessionDefaultModel(model, thinkingLevel, options);
24348
+ }
23502
24349
  if (options?.signal?.aborted) return;
23503
24350
  this.sessionManager.assertLegacyMutationAllowed("set temporary model");
23504
24351
  this.#btwPrefixLedger.clear();
@@ -23693,6 +24540,208 @@ export class AgentSession {
23693
24540
  };
23694
24541
  }
23695
24542
 
24543
+ /** All migrated controls and canonical messages share one publication protocol. */
24544
+ usesSharedControlPublication(): boolean {
24545
+ return this.#usesSharedSessionPublication();
24546
+ }
24547
+
24548
+ withModelProfilePublication<T>(assertCurrent: () => void, body: () => Promise<T>): Promise<T> {
24549
+ return this.#withStartedSharedControlPublication(assertCurrent, () =>
24550
+ this.sessionManager.withSharedThinkingControl(async () => {
24551
+ assertCurrent();
24552
+ return body();
24553
+ }),
24554
+ );
24555
+ }
24556
+
24557
+ async appendModelProfileActivationForControl(
24558
+ plan: ModelProfileTranscriptPlan,
24559
+ isCurrent: () => boolean,
24560
+ ): Promise<SharedEntriesAppendOutcome> {
24561
+ const manager = this.sessionManager;
24562
+ const sessionId = this.sessionId;
24563
+ const identityGeneration = manager.getSessionIdentityGeneration();
24564
+ const parent = manager.getLeafId();
24565
+ const snapshot = structuredClone(plan);
24566
+ const outcome = await manager.appendModelProfileActivationSharingSession(
24567
+ snapshot,
24568
+ () =>
24569
+ this.sessionManager === manager &&
24570
+ this.sessionId === sessionId &&
24571
+ manager.getSessionIdentityGeneration() === identityGeneration &&
24572
+ isCurrent(),
24573
+ );
24574
+ if (outcome.kind === "committed") {
24575
+ this.#profilePublicationReceipts.set(outcome, {
24576
+ manager,
24577
+ sessionId,
24578
+ identityGeneration,
24579
+ parent,
24580
+ leaf: outcome.ids.at(-1) ?? parent,
24581
+ ids: [...outcome.ids],
24582
+ plan: snapshot,
24583
+ });
24584
+ }
24585
+ return outcome;
24586
+ }
24587
+
24588
+ /**
24589
+ * Publish a configuration reload's profile and live-model transcript entries as one
24590
+ * admitted append, before any settings, catalog or live model publication (#7824).
24591
+ * The receipt is consumed by the reload's synchronous publication step.
24592
+ */
24593
+ async #publishSharedConfigurationReload(
24594
+ prepared: PreparedModelProfileActivation | undefined,
24595
+ liveSelection: PreparedProfileModelSelection | undefined,
24596
+ options: { preserveDefaultModelSelection: boolean; preserveLiveModelSelection: boolean },
24597
+ isCurrent: () => boolean,
24598
+ ): Promise<CommittedModelProfileSessionPublication> {
24599
+ const operation = "reload model profile configuration";
24600
+ const assertMode = this.#controlPublicationModeFence(operation);
24601
+ const plan: ModelProfileTranscriptPlan = prepared ? buildModelProfileTranscriptPlan(prepared, options) : {};
24602
+ if (liveSelection) {
24603
+ if (plan.temporaryModel !== undefined)
24604
+ throw new Error("Configuration reload prepared both a profile and a live model selection");
24605
+ plan.temporaryModel = `${liveSelection.model.provider}/${liveSelection.model.id}`;
24606
+ plan.thinking = { level: liveSelection.committedThinkingLevel };
24607
+ }
24608
+ // Entries already handed to background publication precede the reload's intent.
24609
+ await this.#joinBackgroundPublications();
24610
+ const manager = this.sessionManager;
24611
+ const sessionId = this.sessionId;
24612
+ const identityGeneration = manager.getSessionIdentityGeneration();
24613
+ const current = () => {
24614
+ try {
24615
+ assertMode();
24616
+ if (liveSelection) this.#assertPreparedProfileModelSelectionCurrent(liveSelection);
24617
+ if (prepared?.preparedDefaultModelSelection && plan.temporaryModel !== undefined)
24618
+ this.#assertPreparedProfileModelSelectionCurrent(prepared.preparedDefaultModelSelection);
24619
+ } catch {
24620
+ return false;
24621
+ }
24622
+ return (
24623
+ !this.#isDisposed &&
24624
+ this.sessionManager === manager &&
24625
+ this.sessionId === sessionId &&
24626
+ manager.getSessionIdentityGeneration() === identityGeneration &&
24627
+ isCurrent()
24628
+ );
24629
+ };
24630
+ const outcome = await this.withModelProfilePublication(
24631
+ () => {
24632
+ if (!current())
24633
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
24634
+ },
24635
+ () => this.appendModelProfileActivationForControl(plan, current),
24636
+ );
24637
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
24638
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
24639
+ if (!current()) return this.#failClosedSharedControl(operation, outcome);
24640
+ return { plan, receipt: outcome, selection: liveSelection };
24641
+ }
24642
+
24643
+ /** Consume only a receipt issued by this session for these exact committed entries. */
24644
+ publishCommittedModelProfileSessionState(
24645
+ plan: ModelProfileTranscriptPlan,
24646
+ receipt: Extract<SharedEntriesAppendOutcome, { kind: "committed" }>,
24647
+ selection?: PreparedProfileModelSelection,
24648
+ ): void {
24649
+ const admitted = this.#profilePublicationReceipts.get(receipt);
24650
+ const manager = this.sessionManager;
24651
+ if (
24652
+ !admitted ||
24653
+ admitted.manager !== manager ||
24654
+ admitted.sessionId !== this.sessionId ||
24655
+ admitted.identityGeneration !== manager.getSessionIdentityGeneration() ||
24656
+ admitted.leaf !== manager.getLeafId() ||
24657
+ !util.isDeepStrictEqual(admitted.plan, plan) ||
24658
+ !util.isDeepStrictEqual(admitted.ids, receipt.ids) ||
24659
+ this.#isDisposed ||
24660
+ this.#sessionTransitionKind !== undefined
24661
+ )
24662
+ throw new Error("Invalid or stale model profile publication receipt");
24663
+ const expected: Array<(entry: SessionEntry) => boolean> = [];
24664
+ if (plan.configuredDefaultChain !== undefined) {
24665
+ const chain = plan.configuredDefaultChain;
24666
+ if (chain.role !== "default") throw new Error("Invalid model profile default chain");
24667
+ expected.push(
24668
+ entry =>
24669
+ entry.type === "configured_model_chain" &&
24670
+ entry.role === chain.role &&
24671
+ util.isDeepStrictEqual(entry.entries, chain.entries) &&
24672
+ entry.origin === chain.origin &&
24673
+ entry.identity === chain.identity &&
24674
+ entry.explicitHead === chain.explicitHead &&
24675
+ entry.cleared === chain.cleared,
24676
+ );
24677
+ }
24678
+ if (plan.temporaryModel !== undefined) {
24679
+ if (
24680
+ !selection ||
24681
+ plan.temporaryModel !== `${selection.model.provider}/${selection.model.id}` ||
24682
+ !plan.thinking ||
24683
+ plan.thinking.level !== selection.committedThinkingLevel
24684
+ )
24685
+ throw new Error("Profile selection does not match committed transcript");
24686
+ expected.push(
24687
+ entry =>
24688
+ entry.type === "model_change" &&
24689
+ entry.role === "temporary" &&
24690
+ entry.model === plan.temporaryModel &&
24691
+ !entry.cleared,
24692
+ );
24693
+ } else if (selection) throw new Error("Profile selection lacks committed model intent");
24694
+ if (plan.thinking !== undefined) {
24695
+ if (
24696
+ resolveThinkingLevelForModel(
24697
+ selection?.model ?? this.model,
24698
+ plan.thinking.level as ThinkingLevel | undefined,
24699
+ ) !== plan.thinking.level
24700
+ )
24701
+ throw new Error("Profile thinking does not match effective model thinking");
24702
+ expected.push(
24703
+ entry =>
24704
+ entry.type === "thinking_level_change" &&
24705
+ entry.thinkingLevel === (plan.thinking!.level ?? null) &&
24706
+ !entry.operatorIntent,
24707
+ );
24708
+ }
24709
+ if (plan.resumeDefault !== undefined) {
24710
+ expected.push(
24711
+ entry =>
24712
+ entry.type === "model_change" &&
24713
+ entry.role === "default" &&
24714
+ (plan.resumeDefault!.selector === undefined
24715
+ ? entry.cleared === true && entry.model === ""
24716
+ : !entry.cleared && entry.model === plan.resumeDefault!.selector),
24717
+ );
24718
+ }
24719
+ if (expected.length !== receipt.ids.length) throw new Error("Incomplete profile publication receipt");
24720
+ for (let index = 0; index < expected.length; index++) {
24721
+ const entry = manager.getEntry(receipt.ids[index]!);
24722
+ if (
24723
+ !entry ||
24724
+ !expected[index]!(entry) ||
24725
+ entry.parentId !== (index === 0 ? admitted.parent : receipt.ids[index - 1])
24726
+ )
24727
+ throw new Error("Profile publication entries do not match receipt");
24728
+ }
24729
+ if (receipt.ids.length > 0 && receipt.ids.at(-1) !== admitted.leaf)
24730
+ throw new Error("Profile publication cursor changed");
24731
+ if (selection) this.#assertPreparedProfileModelSelectionCurrent(selection);
24732
+ this.#profilePublicationReceipts.delete(receipt);
24733
+ if (plan.configuredDefaultChain !== undefined) {
24734
+ this.#defaultFallbackController = undefined;
24735
+ this.#defaultFallbackExhaustedLastTurn = false;
24736
+ }
24737
+ if (selection) {
24738
+ this.#setModelAuthoritatively(selection.model, "profile-activation");
24739
+ this.#syncAppendOnlyContext(selection.model);
24740
+ }
24741
+ if (plan.thinking !== undefined)
24742
+ this.#applyThinkingLevel(plan.thinking.level as ThinkingLevel | undefined, false, false, undefined, true);
24743
+ }
24744
+
23696
24745
  commitPreparedProfileModelSelection(
23697
24746
  prepared: PreparedProfileModelSelection,
23698
24747
  onThinkingLevelApplied?: (mutationRevision: number) => void,
@@ -23756,7 +24805,23 @@ export class AgentSession {
23756
24805
  async restoreModelSelectionForRollback(
23757
24806
  model: Model | undefined,
23758
24807
  thinkingLevel: ThinkingLevel | undefined,
24808
+ durable?: ModelSelectionRollbackDurableState,
23759
24809
  ): Promise<void> {
24810
+ // A shared session compensates through its own admitted publication (#7824).
24811
+ if (this.#usesSharedSessionPublication())
24812
+ return this.#restoreSharedModelSelectionForRollback(model, thinkingLevel, durable);
24813
+ this.sessionManager.assertLegacyAppendAllowed("restore model selection");
24814
+ if (durable?.defaultChain) {
24815
+ const chain = durable.defaultChain.state;
24816
+ this.setConfiguredModelChain(
24817
+ "default",
24818
+ chain?.entries ?? [],
24819
+ chain?.origin ?? "rollback",
24820
+ chain?.identity,
24821
+ chain?.explicitHead ?? true,
24822
+ );
24823
+ }
24824
+ if (durable?.resumeDefault) this.recordResumeDefaultModel(durable.resumeDefault.selector);
23760
24825
  const previousEditMode = this.#resolveActiveEditMode();
23761
24826
  if (model) {
23762
24827
  // Restoring a captured live model is compensation, not a new selection:
@@ -23772,9 +24837,129 @@ export class AgentSession {
23772
24837
  await this.#syncEditToolModeAfterModelChange(previousEditMode);
23773
24838
  }
23774
24839
 
24840
+ /**
24841
+ * Shared-session compensation for a failed selector transaction. It compares the
24842
+ * captured state with the current live and durable state and publishes only the
24843
+ * entries that actually differ, through the common admitted control publication,
24844
+ * before any live change. Nothing that differs means nothing is written or changed.
24845
+ * A refused publication changes nothing; an unknown one closes the session.
24846
+ */
24847
+ async #restoreSharedModelSelectionForRollback(
24848
+ model: Model | undefined,
24849
+ thinkingLevel: ThinkingLevel | undefined,
24850
+ durable: ModelSelectionRollbackDurableState | undefined,
24851
+ ): Promise<void> {
24852
+ const operation = "restore model selection";
24853
+ const assertMode = this.#controlPublicationModeFence(operation);
24854
+ const manager = this.sessionManager;
24855
+ const sessionId = this.sessionId;
24856
+ const identityGeneration = manager.getSessionIdentityGeneration();
24857
+ const liveModel = this.model;
24858
+ const liveThinking = this.#thinkingLevel;
24859
+ const thinkingRevision = this.#thinkingLevelMutationRevision;
24860
+ const entries: SharedControlEntry[] = [];
24861
+ const targetChain = durable?.defaultChain?.state;
24862
+ const chainChanges =
24863
+ durable?.defaultChain !== undefined &&
24864
+ !util.isDeepStrictEqual(
24865
+ targetChain === undefined
24866
+ ? undefined
24867
+ : {
24868
+ entries: [...targetChain.entries],
24869
+ origin: targetChain.origin,
24870
+ identity: targetChain.identity,
24871
+ explicitHead: targetChain.explicitHead ?? true,
24872
+ },
24873
+ this.getConfiguredModelChainState("default"),
24874
+ );
24875
+ if (chainChanges) {
24876
+ const chainEntries = [...(targetChain?.entries ?? [])];
24877
+ entries.push({
24878
+ type: "configured_model_chain",
24879
+ chain: {
24880
+ role: "default",
24881
+ entries: chainEntries,
24882
+ origin: targetChain?.origin ?? "rollback",
24883
+ identity: targetChain?.identity,
24884
+ explicitHead: targetChain?.explicitHead ?? true,
24885
+ cleared: chainEntries.length === 0,
24886
+ },
24887
+ });
24888
+ }
24889
+ const resumeDefault = durable?.resumeDefault;
24890
+ if (resumeDefault && this.getSessionDefaultModelSelector() !== resumeDefault.selector) {
24891
+ entries.push(
24892
+ resumeDefault.selector === undefined
24893
+ ? { type: "model_role_clear", role: "default" }
24894
+ : { type: "model_change", model: resumeDefault.selector, role: "default" },
24895
+ );
24896
+ }
24897
+ const modelChanges = model !== liveModel;
24898
+ if (model && modelChanges)
24899
+ entries.push({ type: "model_change", model: `${model.provider}/${model.id}`, role: "temporary" });
24900
+ const effectiveThinking = resolveThinkingLevelForModel(model, thinkingLevel);
24901
+ if (effectiveThinking !== liveThinking)
24902
+ entries.push({ type: "thinking_level_change", level: effectiveThinking, operatorIntent: false });
24903
+ if (entries.length === 0 && !modelChanges) return;
24904
+ const current = () => {
24905
+ try {
24906
+ assertMode();
24907
+ } catch {
24908
+ return false;
24909
+ }
24910
+ return (
24911
+ !this.#isDisposed &&
24912
+ this.sessionManager === manager &&
24913
+ this.sessionId === sessionId &&
24914
+ manager.getSessionIdentityGeneration() === identityGeneration &&
24915
+ this.model === liveModel &&
24916
+ this.#thinkingLevel === liveThinking &&
24917
+ this.#thinkingLevelMutationRevision === thinkingRevision
24918
+ );
24919
+ };
24920
+ let committed: Extract<SharedEntriesAppendOutcome, { kind: "committed" }> | undefined;
24921
+ if (entries.length > 0) {
24922
+ const outcome = await this.#withStartedSharedControlPublication(
24923
+ () => {
24924
+ if (!current())
24925
+ throw new SharedControlPublicationError(operation, {
24926
+ kind: "rejected",
24927
+ error: new Error("superseded"),
24928
+ });
24929
+ },
24930
+ () => manager.appendControlEntriesSharingSession(entries, current),
24931
+ );
24932
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
24933
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
24934
+ if (!current()) return this.#failClosedSharedControl(operation, outcome);
24935
+ committed = outcome;
24936
+ }
24937
+ const previousEditMode = this.#resolveActiveEditMode();
24938
+ try {
24939
+ if (chainChanges) {
24940
+ this.#defaultFallbackController = undefined;
24941
+ this.#defaultFallbackExhaustedLastTurn = false;
24942
+ }
24943
+ if (model) {
24944
+ if (modelChanges) this.#setModelAuthoritatively(model, "rollback");
24945
+ } else if (modelChanges) {
24946
+ this.#clearActiveRetryFallback();
24947
+ this.#setModelWithProviderSessionReset(undefined);
24948
+ this.#syncAppendOnlyContext(undefined);
24949
+ }
24950
+ this.#applyThinkingLevel(thinkingLevel, false, false, undefined, true);
24951
+ } catch (error) {
24952
+ if (committed) return this.#failClosedSharedControl(operation, committed, error);
24953
+ throw error;
24954
+ }
24955
+ await this.#syncEditToolModeAfterModelChange(previousEditMode);
24956
+ }
24957
+
23775
24958
  async #discardDefaultModelSelectionStage(
23776
- stage: DefaultModelSelectionStage,
24959
+ stage: DefaultModelSelectionStage | undefined,
23777
24960
  ): Promise<{ readonly stage: DefaultModelSelectionRollbackStage; readonly message: string } | undefined> {
24961
+ // A shared selection stages nothing; a refused publication left no transcript write.
24962
+ if (!stage) return undefined;
23778
24963
  try {
23779
24964
  await this.sessionManager.discardDefaultModelSelectionStage(stage);
23780
24965
  return undefined;
@@ -23802,7 +24987,7 @@ export class AgentSession {
23802
24987
 
23803
24988
  async #throwDefaultModelSelectionRecovery(
23804
24989
  error: Error,
23805
- stage: DefaultModelSelectionStage,
24990
+ stage: DefaultModelSelectionStage | undefined,
23806
24991
  commit: DurableModelProfileOwnership,
23807
24992
  roleRollback?: { previous: readonly SettingsAtomicPatch[]; selected: readonly SettingsAtomicPatch[] },
23808
24993
  ): Promise<never> {
@@ -23962,7 +25147,8 @@ export class AgentSession {
23962
25147
  onAfterMutationAdmissionReadyForTests?: () => Promise<void>;
23963
25148
  },
23964
25149
  ): Promise<DefaultModelSelectionResult> {
23965
- this.sessionManager.assertLegacyMutationAllowed("select default model");
25150
+ const assertPublicationMode = this.#controlPublicationModeFence("select default model");
25151
+ const sharedPublication = this.#usesSharedSessionPublication();
23966
25152
  // Reserve the causal selection fence synchronously, before credential
23967
25153
  // probing can yield. Later external prompts wait behind this operation,
23968
25154
  // while an inherited post-prompt continuation may bypass the fence so
@@ -24022,7 +25208,7 @@ export class AgentSession {
24022
25208
  return await this.#withSessionAdmission(
24023
25209
  "selection",
24024
25210
  async () => {
24025
- this.sessionManager.assertLegacyMutationAllowed("select default model");
25211
+ assertPublicationMode();
24026
25212
  options?.onBeforeMutation?.();
24027
25213
  if (this.sessionId !== expectedSessionId) {
24028
25214
  throw new Error("Session changed while selecting model");
@@ -24049,31 +25235,37 @@ export class AgentSession {
24049
25235
  materializedRolesPatch?.op === "set"
24050
25236
  ? (materializedRolesPatch.value as Record<string, ModelSelectorValue>)
24051
25237
  : undefined;
24052
- const stage = await this.sessionManager.stageDefaultModelSelection(
24053
- `${model.provider}/${model.id}`,
24054
- effectiveLevel,
24055
- {
24056
- appendThinkingLevel: true,
24057
- appendTemporaryModelChange:
24058
- options?.roleCycle === undefined && options?.selectionIntent === undefined,
24059
- configuredDefaultChain: options?.roleCycle
24060
- ? normalizeModelSelectorValue(
24061
- materializedRoles?.[options.roleCycle.role] ?? options.roleCycle.chain,
24062
- )
24063
- : (options?.selectionIntent?.chain ??
24064
- (options?.selectionIntent
24065
- ? undefined
24066
- : [formatModelSelectorValue(`${model.provider}/${model.id}`, effectiveLevel)])),
24067
- selectionRole: options?.roleCycle?.role,
24068
- },
24069
- );
25238
+ const selectionEntries: DefaultModelSelectionEntriesOptions = {
25239
+ appendThinkingLevel: true,
25240
+ appendTemporaryModelChange:
25241
+ options?.roleCycle === undefined && options?.selectionIntent === undefined,
25242
+ configuredDefaultChain: options?.roleCycle
25243
+ ? normalizeModelSelectorValue(
25244
+ materializedRoles?.[options.roleCycle.role] ?? options.roleCycle.chain,
25245
+ )
25246
+ : (options?.selectionIntent?.chain ??
25247
+ (options?.selectionIntent
25248
+ ? undefined
25249
+ : [formatModelSelectorValue(`${model.provider}/${model.id}`, effectiveLevel)])),
25250
+ selectionRole: options?.roleCycle?.role,
25251
+ };
25252
+ // Shared sessions publish the same entries additively at this opener's cursor
25253
+ // after the durable settings commit; legacy sessions stage a replacement.
25254
+ const stage = sharedPublication
25255
+ ? undefined
25256
+ : await this.sessionManager.stageDefaultModelSelection(
25257
+ `${model.provider}/${model.id}`,
25258
+ effectiveLevel,
25259
+ selectionEntries,
25260
+ );
24070
25261
  let durableCommit = observedAtRequest;
24071
25262
  let roleRollback:
24072
25263
  | { previous: readonly SettingsAtomicPatch[]; selected: readonly SettingsAtomicPatch[] }
24073
25264
  | undefined;
25265
+ let sharedOutcome: SharedEntriesAppendOutcome | undefined;
24074
25266
  const materialized = materializedRoles !== undefined;
24075
25267
  const assertCurrent = () => {
24076
- this.sessionManager.assertLegacyMutationAllowed("select default model");
25268
+ assertPublicationMode();
24077
25269
  // Disposal drains the already-authorized selection transaction;
24078
25270
  // it rejects new/queued ingress without revoking that owner's lease.
24079
25271
  if (
@@ -24127,6 +25319,7 @@ export class AgentSession {
24127
25319
  });
24128
25320
  }
24129
25321
  } catch (error) {
25322
+ if (!stage) throw error;
24130
25323
  try {
24131
25324
  await this.sessionManager.discardDefaultModelSelectionStage(stage);
24132
25325
  } catch (cleanupError) {
@@ -24141,7 +25334,36 @@ export class AgentSession {
24141
25334
  assertCurrent();
24142
25335
  if (!util.isDeepStrictEqual(readDurableModelProfileOwnership(this.settings), durableCommit))
24143
25336
  throw new Error("Default model selection ownership changed before publication");
24144
- const promotion = this.sessionManager.promoteDefaultModelSelection(stage);
25337
+ const promotion: DefaultModelSelectionPromotion = stage
25338
+ ? this.sessionManager.promoteDefaultModelSelection(stage)
25339
+ : await (async () => {
25340
+ sharedOutcome = await this.sessionManager.appendControlEntriesSharingSession(
25341
+ this.sessionManager.defaultModelSelectionControlEntries(
25342
+ `${model.provider}/${model.id}`,
25343
+ effectiveLevel,
25344
+ selectionEntries,
25345
+ ),
25346
+ () => {
25347
+ try {
25348
+ assertCurrent();
25349
+ return util.isDeepStrictEqual(
25350
+ readDurableModelProfileOwnership(this.settings),
25351
+ durableCommit,
25352
+ );
25353
+ } catch {
25354
+ return false;
25355
+ }
25356
+ },
25357
+ );
25358
+ if (sharedOutcome.kind !== "committed")
25359
+ return {
25360
+ kind: "not_promoted",
25361
+ error: new SharedControlPublicationError("select default model", sharedOutcome),
25362
+ };
25363
+ // The entries are durable; runtime promotion must still be current.
25364
+ assertCurrent();
25365
+ return { kind: "promoted" };
25366
+ })();
24145
25367
  switch (promotion.kind) {
24146
25368
  case "promoted": {
24147
25369
  this.#publishDefaultModelSelection(
@@ -24184,6 +25406,8 @@ export class AgentSession {
24184
25406
  return { provider: model.provider, modelId: model.id, thinkingLevel: effectiveLevel };
24185
25407
  } catch (error) {
24186
25408
  if (roleRollback && error instanceof DefaultModelSelectionRecoveryError) throw error;
25409
+ if (sharedOutcome?.kind === "committed" || sharedOutcome?.kind === "unknown")
25410
+ return this.#failClosedSharedControl("select default model", sharedOutcome, error);
24187
25411
  return this.#throwDefaultModelSelectionRecovery(
24188
25412
  error instanceof Error ? error : new Error(String(error)),
24189
25413
  stage,
@@ -24280,9 +25504,9 @@ export class AgentSession {
24280
25504
  ): Promise<RoleModelCycleResult | undefined> {
24281
25505
  const roleModels = this.#getRoleModelCycleCandidates(roleOrder, this.sessionId);
24282
25506
  if (roleModels.length <= 1) return undefined;
24283
- if (!(options?.temporary && this.#rootInteractiveSharedAppend && this.sessionManager.isManagedDestination())) {
24284
- this.sessionManager.assertLegacyMutationAllowed("cycle role models");
24285
- }
25507
+ // Shared sessions route both temporary and persistent cycles through admitted
25508
+ // publication (setModelTemporary / setDefaultModelSelection).
25509
+ if (!this.#usesSharedSessionPublication()) this.sessionManager.assertLegacyMutationAllowed("cycle role models");
24286
25510
 
24287
25511
  const currentModel = this.model!;
24288
25512
 
@@ -24344,7 +25568,7 @@ export class AgentSession {
24344
25568
 
24345
25569
  async #cycleScopedModel(direction: "forward" | "backward"): Promise<ModelCycleResult | undefined> {
24346
25570
  if (this.#scopedModels.length <= 1) return undefined;
24347
- this.sessionManager.assertLegacyMutationAllowed("cycle models");
25571
+ if (!this.#usesSharedSessionPublication()) this.sessionManager.assertLegacyMutationAllowed("cycle models");
24348
25572
  const observedOwnership = readDurableModelProfileOwnership(this.settings);
24349
25573
  const scopedModels = await this.#getScopedModelsWithApiKey();
24350
25574
  if (scopedModels.length <= 1) return undefined;
@@ -24424,8 +25648,10 @@ export class AgentSession {
24424
25648
  onApplied?: (mutationRevision: number) => void,
24425
25649
  entryAlreadyCommitted = false,
24426
25650
  ): void {
24427
- if (!entryAlreadyCommitted &&
24428
- (persist || operatorIntent || resolveThinkingLevelForModel(this.model, level) !== this.#thinkingLevel)) {
25651
+ if (
25652
+ !entryAlreadyCommitted &&
25653
+ (persist || operatorIntent || resolveThinkingLevelForModel(this.model, level) !== this.#thinkingLevel)
25654
+ ) {
24429
25655
  this.sessionManager.assertLegacyMutationAllowed("set thinking level");
24430
25656
  }
24431
25657
  this.#btwPrefixLedger.clear();
@@ -24457,7 +25683,7 @@ export class AgentSession {
24457
25683
  * Set thinking level from a control surface. Global changes commit before affecting live state.
24458
25684
  */
24459
25685
  async setThinkingLevelForControl(level: ThinkingLevel, persist: boolean): Promise<void> {
24460
- if (this.#rootInteractiveSharedAppend && this.sessionManager.isManagedDestination()) {
25686
+ if (this.#usesSharedSessionPublication()) {
24461
25687
  const run = persist
24462
25688
  ? this.#prepareSharedPersistedThinkingLevelForControl(level)
24463
25689
  : this.#prepareSharedThinkingLevelForControl(level);
@@ -24469,26 +25695,51 @@ export class AgentSession {
24469
25695
  return this.#setThinkingLevelForControl(level, false);
24470
25696
  }
24471
25697
 
24472
- #prepareSharedThinkingLevelForControl(level: ThinkingLevel): () => Promise<void> {
25698
+ /**
25699
+ * Non-operator, session-only thinking change (plan mode model follow). Shared sessions
25700
+ * publish the entry through admitted shared publication before the live change;
25701
+ * other sessions keep the synchronous legacy write.
25702
+ */
25703
+ async setThinkingLevelForSession(level: ThinkingLevel | undefined): Promise<void> {
25704
+ if (
25705
+ level === undefined ||
25706
+ !this.#usesSharedSessionPublication() ||
25707
+ resolveThinkingLevelForModel(
25708
+ this.model,
25709
+ level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : level,
25710
+ ) === this.#thinkingLevel
25711
+ ) {
25712
+ this.setThinkingLevel(level);
25713
+ return;
25714
+ }
25715
+ return this.#withThinkingControlScheduling(this.#prepareSharedThinkingLevelForControl(level, false));
25716
+ }
25717
+
25718
+ #prepareSharedThinkingLevelForControl(
25719
+ level: ThinkingLevel,
25720
+ operatorIntent = level !== ThinkingLevel.Inherit,
25721
+ ): () => Promise<void> {
24473
25722
  const revision = ++this.#thinkingLevelMutationRevision;
24474
25723
  const liveRevision = this.#thinkingLevelLiveMutationRevision;
24475
25724
  const sessionId = this.sessionManager.getSessionId();
24476
25725
  const model = this.model;
24477
25726
  const contextGeneration = this.#reasoningControlContextGeneration;
24478
- const current = () => revision === this.#thinkingLevelMutationRevision &&
25727
+ const current = () =>
25728
+ revision === this.#thinkingLevelMutationRevision &&
24479
25729
  liveRevision === this.#thinkingLevelLiveMutationRevision &&
24480
- sessionId === this.sessionManager.getSessionId() && model === this.model &&
25730
+ sessionId === this.sessionManager.getSessionId() &&
25731
+ model === this.model &&
24481
25732
  contextGeneration === this.#reasoningControlContextGeneration;
24482
25733
  return async () => {
24483
25734
  if (!current()) return;
24484
25735
  return this.sessionManager.withSharedThinkingControl(async () => {
24485
25736
  const selected = level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : level;
24486
25737
  const effective = resolveThinkingLevelForModel(model, selected);
24487
- let outcome;
25738
+ let outcome: SharedAppendOutcome;
24488
25739
  try {
24489
25740
  outcome = await this.sessionManager.appendThinkingLevelChangeSharingSession(
24490
25741
  level === ThinkingLevel.Inherit ? level : effective,
24491
- level !== ThinkingLevel.Inherit,
25742
+ operatorIntent,
24492
25743
  current,
24493
25744
  );
24494
25745
  } catch (error) {
@@ -24498,7 +25749,8 @@ export class AgentSession {
24498
25749
  outcome.kind === "rejected" &&
24499
25750
  outcome.error instanceof Error &&
24500
25751
  outcome.error.message === "shared_thinking_control_superseded"
24501
- ) return;
25752
+ )
25753
+ return;
24502
25754
  if (outcome.kind !== "committed") {
24503
25755
  throw new Error(
24504
25756
  `Session thinking publication ${outcome.kind}${outcome.kind === "unknown" ? ` (attempted id: ${outcome.id})` : ""}${outcome.kind === "stale" ? `: ${outcome.reason}` : ""}`,
@@ -24517,26 +25769,39 @@ export class AgentSession {
24517
25769
  const sessionId = this.sessionManager.getSessionId();
24518
25770
  const model = this.model;
24519
25771
  const contextGeneration = this.#reasoningControlContextGeneration;
24520
- const sameContext = () => contextGeneration === this.#reasoningControlContextGeneration &&
24521
- sessionId === this.sessionManager.getSessionId() && model === this.model;
24522
- const current = () => revision === this.#thinkingLevelMutationRevision &&
24523
- liveRevision === this.#thinkingLevelLiveMutationRevision && sameContext();
25772
+ const sameContext = () =>
25773
+ contextGeneration === this.#reasoningControlContextGeneration &&
25774
+ sessionId === this.sessionManager.getSessionId() &&
25775
+ model === this.model;
25776
+ const current = () =>
25777
+ revision === this.#thinkingLevelMutationRevision &&
25778
+ liveRevision === this.#thinkingLevelLiveMutationRevision &&
25779
+ sameContext();
24524
25780
  return async () => {
24525
25781
  if (!current()) return;
24526
25782
  return this.sessionManager.withSharedThinkingControl(async () => {
24527
- const effective = resolveThinkingLevelForModel(model,
24528
- level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : level);
25783
+ const effective = resolveThinkingLevelForModel(
25784
+ model,
25785
+ level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : level,
25786
+ );
24529
25787
  const persisted = level === ThinkingLevel.Inherit ? getDefault("defaultThinkingLevel") : effective;
24530
25788
  const publish = async (isCurrent: () => boolean) => {
24531
- let outcome;
25789
+ let outcome: SharedAppendOutcome;
24532
25790
  try {
24533
25791
  outcome = await this.sessionManager.appendThinkingLevelChangeSharingSession(
24534
- ThinkingLevel.Inherit, false, isCurrent);
25792
+ ThinkingLevel.Inherit,
25793
+ false,
25794
+ isCurrent,
25795
+ );
24535
25796
  } catch (error) {
24536
25797
  throw new Error("Reasoning settings saved; session thinking publication failed", { cause: error });
24537
25798
  }
24538
- if (outcome.kind === "rejected" && outcome.error instanceof Error &&
24539
- outcome.error.message === "shared_thinking_control_superseded") return false;
25799
+ if (
25800
+ outcome.kind === "rejected" &&
25801
+ outcome.error instanceof Error &&
25802
+ outcome.error.message === "shared_thinking_control_superseded"
25803
+ )
25804
+ return false;
24540
25805
  if (outcome.kind !== "committed") {
24541
25806
  throw new Error(
24542
25807
  `Reasoning settings saved; session thinking publication ${outcome.kind}${outcome.kind === "unknown" ? ` (attempted id: ${outcome.id})` : ""}${outcome.kind === "stale" ? `: ${outcome.reason}` : ""}`,
@@ -24553,11 +25818,20 @@ export class AgentSession {
24553
25818
  if (revision === this.#thinkingLevelMutationRevision && sameContext()) {
24554
25819
  const pending = this.#pendingThinkingLevelControlSuccess;
24555
25820
  this.#pendingThinkingLevelControlSuccess = undefined;
24556
- if (pending && pending.contextGeneration === contextGeneration &&
24557
- pending.sessionId === sessionId && pending.model === model && current()) {
25821
+ if (
25822
+ pending &&
25823
+ pending.contextGeneration === contextGeneration &&
25824
+ pending.sessionId === sessionId &&
25825
+ pending.model === model &&
25826
+ current()
25827
+ ) {
24558
25828
  try {
24559
- if (await publish(current) && current())
24560
- apply(pending.level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : pending.level);
25829
+ if ((await publish(current)) && current())
25830
+ apply(
25831
+ pending.level === ThinkingLevel.Inherit
25832
+ ? this.#getInheritedThinkingLevel()
25833
+ : pending.level,
25834
+ );
24561
25835
  } catch (recoveryError) {
24562
25836
  const detail = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);
24563
25837
  throw new AggregateError(
@@ -24568,34 +25842,47 @@ export class AgentSession {
24568
25842
  }
24569
25843
  } else {
24570
25844
  this.#pendingThinkingLevelControlFailure = {
24571
- mutationRevision: revision, liveMutationRevision: liveRevision,
24572
- sessionId, model, contextGeneration,
25845
+ mutationRevision: revision,
25846
+ liveMutationRevision: liveRevision,
25847
+ sessionId,
25848
+ model,
25849
+ contextGeneration,
24573
25850
  };
24574
25851
  }
24575
25852
  }
24576
25853
  throw new Error("Unable to persist reasoning settings.", { cause: settingsError });
24577
25854
  }
24578
25855
  if (!current()) {
24579
- if (liveRevision === this.#thinkingLevelLiveMutationRevision && sameContext() &&
24580
- (this.#pendingThinkingLevelControlSuccess?.mutationRevision ?? -1) < revision) {
24581
- this.#pendingThinkingLevelControlSuccess = { level, mutationRevision: revision,
24582
- sessionId, model, contextGeneration };
25856
+ if (
25857
+ liveRevision === this.#thinkingLevelLiveMutationRevision &&
25858
+ sameContext() &&
25859
+ (this.#pendingThinkingLevelControlSuccess?.mutationRevision ?? -1) < revision
25860
+ ) {
25861
+ this.#pendingThinkingLevelControlSuccess = {
25862
+ level,
25863
+ mutationRevision: revision,
25864
+ sessionId,
25865
+ model,
25866
+ contextGeneration,
25867
+ };
24583
25868
  const failure = this.#pendingThinkingLevelControlFailure;
24584
- const recoverable = () => failure !== undefined &&
25869
+ const recoverable = () =>
25870
+ failure !== undefined &&
24585
25871
  failure.mutationRevision === this.#thinkingLevelMutationRevision &&
24586
25872
  failure.liveMutationRevision === this.#thinkingLevelLiveMutationRevision &&
24587
- failure.sessionId === this.sessionManager.getSessionId() && failure.model === this.model &&
25873
+ failure.sessionId === this.sessionManager.getSessionId() &&
25874
+ failure.model === this.model &&
24588
25875
  failure.contextGeneration === this.#reasoningControlContextGeneration;
24589
25876
  if (recoverable()) {
24590
25877
  this.#pendingThinkingLevelControlSuccess = undefined;
24591
25878
  this.#pendingThinkingLevelControlFailure = undefined;
24592
- if (await publish(recoverable) && recoverable())
25879
+ if ((await publish(recoverable)) && recoverable())
24593
25880
  apply(level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : effective);
24594
25881
  }
24595
25882
  }
24596
25883
  return;
24597
25884
  }
24598
- if (await publish(current) && current())
25885
+ if ((await publish(current)) && current())
24599
25886
  apply(level === ThinkingLevel.Inherit ? this.#getInheritedThinkingLevel() : effective);
24600
25887
  });
24601
25888
  };
@@ -24935,8 +26222,6 @@ export class AgentSession {
24935
26222
  * never by the transient Q1 auto-disable path.
24936
26223
  */
24937
26224
  #rearmFastMode(): void {
24938
- const { clearAnthropicFastModeFallback } =
24939
- require("@gajae-code/ai/providers/anthropic") as typeof import("@gajae-code/ai/providers/anthropic");
24940
26225
  clearAnthropicFastModeFallback(this.#providerSessionState);
24941
26226
  this.#fastModeAutoDisabledProviderKeys.clear();
24942
26227
  }
@@ -24956,43 +26241,158 @@ export class AgentSession {
24956
26241
  );
24957
26242
  }
24958
26243
 
24959
- setServiceTier(serviceTier: ServiceTier | undefined): void {
24960
- if (this.serviceTier !== serviceTier || serviceTier === "priority" || serviceTier === "claude-only") {
24961
- this.sessionManager.assertLegacyMutationAllowed("set service tier");
26244
+ async setServiceTier(serviceTier: ServiceTier | undefined): Promise<void> {
26245
+ if (this.#usesSharedSessionPublication()) {
26246
+ await this.#enqueueFastControl("set service tier", () => ({
26247
+ serviceTier,
26248
+ rearm: serviceTier === "priority" || serviceTier === "claude-only",
26249
+ }));
26250
+ return;
24962
26251
  }
26252
+ this.#applyLegacyServiceTier(serviceTier);
26253
+ }
26254
+
26255
+ #applyLegacyServiceTier(serviceTier: ServiceTier | undefined): void {
26256
+ const rearm = serviceTier === "priority" || serviceTier === "claude-only";
26257
+ if (this.serviceTier === serviceTier && !rearm) return;
26258
+ this.sessionManager.assertLegacyMutationAllowed("set service tier");
24963
26259
  this.#btwPrefixLedger.clear();
24964
- // Re-arming a priority-granting tier always clears the per-session
24965
- // auto-fallback sticky disable AND the auto-disable markers so the next
24966
- // request carries `speed: "fast"` again — even when the tier is unchanged
24967
- // (re-selecting the same tier is a deliberate re-arm), and before the
24968
- // no-op early-return below.
24969
- if (serviceTier === "priority" || serviceTier === "claude-only") {
24970
- this.#rearmFastMode();
24971
- }
26260
+ if (rearm) this.#rearmFastMode();
24972
26261
  if (this.serviceTier === serviceTier) return;
24973
26262
  this.agent.serviceTier = serviceTier;
24974
26263
  this.sessionManager.appendServiceTierChange(serviceTier ?? null);
24975
26264
  }
24976
26265
 
24977
- setFastMode(enabled: boolean): void {
26266
+ async setFastMode(enabled: boolean): Promise<void> {
26267
+ if (this.#usesSharedSessionPublication()) {
26268
+ await this.#enqueueFastControl("set fast mode", () => this.#resolveFastModeIntent(enabled));
26269
+ return;
26270
+ }
24978
26271
  if (enabled && this.isFastModeEnabled()) {
24979
26272
  this.sessionManager.assertLegacyMutationAllowed("rearm fast mode");
24980
- // Intent already grants fast mode under some scope — keep the user's
24981
- // scoped value but still re-arm, so an explicit `/fast on` after a
24982
- // provider auto-disable actually clears the sticky fallback + markers
24983
- // (otherwise it is a silent no-op). No history append: intent is unchanged.
24984
26273
  this.#rearmFastMode();
24985
26274
  return;
24986
26275
  }
24987
- this.setServiceTier(enabled ? "priority" : undefined);
26276
+ this.#applyLegacyServiceTier(enabled ? "priority" : undefined);
24988
26277
  }
24989
26278
 
24990
- toggleFastMode(): boolean {
26279
+ async toggleFastMode(): Promise<boolean> {
26280
+ if (this.#usesSharedSessionPublication()) {
26281
+ return this.#enqueueFastControl("toggle fast mode", () =>
26282
+ this.#resolveFastModeIntent(!this.isFastModeEnabled()),
26283
+ );
26284
+ }
24991
26285
  const enabled = !this.isFastModeEnabled();
24992
- this.setFastMode(enabled);
26286
+ await this.setFastMode(enabled);
24993
26287
  return enabled;
24994
26288
  }
24995
26289
 
26290
+ #resolveFastModeIntent(enabled: boolean): { serviceTier: ServiceTier | undefined; rearm: boolean } {
26291
+ return {
26292
+ // Resolve at execution, not enqueue: /fast on preserves provider scope,
26293
+ // and two queued toggles are successive intents rather than duplicates.
26294
+ serviceTier: enabled ? (this.isFastModeEnabled() ? this.serviceTier : "priority") : undefined,
26295
+ rearm: enabled,
26296
+ };
26297
+ }
26298
+
26299
+ #enqueueFastControl(
26300
+ operation: SharedControlPublicationError["operation"],
26301
+ resolveIntent: () => { serviceTier: ServiceTier | undefined; rearm: boolean },
26302
+ ): Promise<boolean> {
26303
+ const manager = this.sessionManager;
26304
+ const sessionId = this.sessionId;
26305
+ const managerId = manager.getSessionId();
26306
+ const file = manager.getSessionFile();
26307
+ const identity = manager.getSessionIdentityGeneration();
26308
+ const generation = this.#sessionTransitionGeneration;
26309
+ const abortEpoch = this.#abortAdmissionEpoch;
26310
+ const transitionEpoch = this.#coordinatorPersistGeneration;
26311
+ const current = () =>
26312
+ !this.#isDisposed &&
26313
+ !this.#sessionAdmissionClosing &&
26314
+ !this.#sessionAdmissionClosed &&
26315
+ this.#sessionTransitionKind === undefined &&
26316
+ !this.#handoffTransitionActive &&
26317
+ this.#sessionTransitionGeneration === generation &&
26318
+ this.#coordinatorPersistGeneration === transitionEpoch &&
26319
+ this.#abortAdmissionEpoch === abortEpoch &&
26320
+ this.sessionManager === manager &&
26321
+ this.sessionId === sessionId &&
26322
+ manager.getSessionId() === managerId &&
26323
+ manager.getSessionFile() === file &&
26324
+ manager.getSessionIdentityGeneration() === identity &&
26325
+ this.#usesSharedSessionPublication();
26326
+ const assertCurrent = () => {
26327
+ if (!current())
26328
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
26329
+ };
26330
+ // Only a still-pending fast control is a predecessor: awaiting a settled tail would
26331
+ // yield and let a later grouped control overtake this one (FIFO intent order).
26332
+ const predecessor = this.#pendingFastControls.size > 0 ? this.#fastControlTail : undefined;
26333
+ // Reserve canonical/thinking order at enqueue, but resolve tier intent only
26334
+ // after the preceding fast control settles. Never wait for session idle or
26335
+ // acquire a selection lease inside this group (both can wait on this queue).
26336
+ const result = this.#withThinkingControlScheduling(async () => {
26337
+ if (predecessor) await predecessor;
26338
+ assertCurrent();
26339
+ return manager.withSharedThinkingControl(async () => {
26340
+ assertCurrent();
26341
+ const { serviceTier, rearm } = resolveIntent();
26342
+ const changed = this.serviceTier !== serviceTier;
26343
+ if (!changed && !rearm) return this.isFastModeEnabled();
26344
+ let outcome: SharedEntriesAppendOutcome;
26345
+ try {
26346
+ outcome = await manager.appendServiceTierChangeSharingSession(serviceTier ?? null, changed, current);
26347
+ } catch {
26348
+ throw new SharedControlPublicationError(operation, {
26349
+ kind: "rejected",
26350
+ error: new Error("publication_failed_before_admission"),
26351
+ });
26352
+ }
26353
+ if (outcome.kind !== "committed" || !current()) {
26354
+ if (outcome.kind === "unknown" || outcome.kind === "committed") {
26355
+ // Retain the exact receipt; never compensate or retry a possibly
26356
+ // durable write. Dispose synchronously fences ingress, but joining
26357
+ // teardown here would wait on this control's own completion.
26358
+ void this.dispose().catch(() => {
26359
+ logger.warn("Shared control session teardown failed", { code: "shared_control_teardown_failed" });
26360
+ });
26361
+ }
26362
+ throw new SharedControlPublicationError(operation, outcome);
26363
+ }
26364
+ try {
26365
+ this.#btwPrefixLedger.clear();
26366
+ if (rearm) this.#rearmFastMode();
26367
+ if (changed) this.agent.serviceTier = serviceTier;
26368
+ } catch {
26369
+ void this.dispose().catch(() => {
26370
+ logger.warn("Shared control session teardown failed", { code: "shared_control_teardown_failed" });
26371
+ });
26372
+ throw new SharedControlPublicationError(operation, outcome);
26373
+ }
26374
+ return this.isFastModeEnabled();
26375
+ });
26376
+ }).catch(error => {
26377
+ if (error instanceof SharedControlPublicationError) throw error;
26378
+ throw new SharedControlPublicationError(operation, {
26379
+ kind: "rejected",
26380
+ error: new Error("publication_failed_before_admission"),
26381
+ });
26382
+ });
26383
+ const settled = result.then(
26384
+ () => {},
26385
+ () => {},
26386
+ );
26387
+ this.#pendingFastControls.set(settled, this.#selectionFenceGeneration);
26388
+ this.#fastControlTail = settled;
26389
+ void settled.then(() => {
26390
+ this.#pendingFastControls.delete(settled);
26391
+ this.#resolveSessionSettlement();
26392
+ });
26393
+ return result;
26394
+ }
26395
+
24996
26396
  /**
24997
26397
  * Get available thinking levels for current model.
24998
26398
  */
@@ -25055,7 +26455,7 @@ export class AgentSession {
25055
26455
  options?: { commitGate?: (actual: { prunedCount: number; tokensSaved: number }) => boolean },
25056
26456
  ): Promise<ToolOutputPruneResult | undefined> {
25057
26457
  // Shared branches retain canonical output; threshold maintenance can append a compaction instead.
25058
- if (this.#usesSharedWorkflowIntentAppend()) return undefined;
26458
+ if (this.#usesSharedSessionPublication()) return undefined;
25059
26459
  this.sessionManager.assertLegacyMutationAllowed("prune tool outputs");
25060
26460
  const branchEntries = this.sessionManager.getBranch();
25061
26461
  const artifactManager = await this.sessionManager.ensureArtifactManager();
@@ -25507,7 +26907,7 @@ export class AgentSession {
25507
26907
  * @param options Optional callbacks for completion/error handling
25508
26908
  */
25509
26909
  async compact(customInstructions?: string, options?: CompactOptions): Promise<CompactionResult> {
25510
- const sharedCompaction = this.#usesSharedWorkflowIntentAppend();
26910
+ const sharedCompaction = this.#usesSharedSessionPublication();
25511
26911
  const invocationManager = this.sessionManager;
25512
26912
  const invocationSessionId = invocationManager.getSessionId();
25513
26913
  const invocationIdentityGeneration = invocationManager.getSessionIdentityGeneration();
@@ -26392,6 +27792,11 @@ export class AgentSession {
26392
27792
  // Case 2: Threshold - turn succeeded but context is getting large
26393
27793
  // Skip if this was an error (non-overflow errors don't have usage data)
26394
27794
  if (assistantMessage.stopReason === "error") return false;
27795
+ // Skip if the message is from before the last compaction entry.
27796
+ // This prevents re-triggering compaction with stale usage after a compaction
27797
+ // completes and the user prompts again. The stale message still has pre-compaction
27798
+ // usage stats, which would incorrectly trigger another compaction attempt.
27799
+ if (errorIsFromBeforeCompaction) return false;
26395
27800
  let contextTokens = calculateContextTokens(assistantMessage.usage);
26396
27801
  // Model maxTokens is a capability ceiling, not a per-turn reservation.
26397
27802
  // Auto maintenance should track actual context fullness.
@@ -26890,7 +28295,7 @@ export class AgentSession {
26890
28295
  attribution: "agent",
26891
28296
  timestamp: Date.now(),
26892
28297
  });
26893
- this.sessionManager.appendCustomMessageEntry("rewind-report", report, false, details, "agent");
28298
+ await this.#appendCustomMessageEntry("rewind-report", report, false, details, "agent");
26894
28299
  this.#checkpointState = undefined;
26895
28300
  this.#pendingRewindReport = undefined;
26896
28301
  }
@@ -27108,7 +28513,7 @@ export class AgentSession {
27108
28513
  timestamp: Date.now(),
27109
28514
  };
27110
28515
  this.agent.appendMessage(reminderMessage);
27111
- this.sessionManager.appendMessage(reminderMessage);
28516
+ await this.appendMessageForSession(reminderMessage);
27112
28517
  this.#scheduleAgentContinue({
27113
28518
  generation: agentEndGeneration,
27114
28519
  skipCompactionCheck: true,
@@ -28023,7 +29428,7 @@ export class AgentSession {
28023
29428
  signal: AbortSignal,
28024
29429
  options?: SummaryOptions,
28025
29430
  ): Promise<CompactionResult> {
28026
- if (!this.#usesSharedWorkflowIntentAppend()) this.sessionManager.assertLegacyMutationAllowed("compact session");
29431
+ if (!this.#usesSharedSessionPublication()) this.sessionManager.assertLegacyMutationAllowed("compact session");
28027
29432
  const candidates = this.#getCompactionModelCandidates(this.#modelRegistry.getAvailable(this.credentialSessionId));
28028
29433
  const telemetry = resolveTelemetry(this.agent.telemetry, this.sessionId);
28029
29434
  let previousCandidate: Model | undefined;
@@ -28041,7 +29446,7 @@ export class AgentSession {
28041
29446
  continue;
28042
29447
  }
28043
29448
 
28044
- if (!this.#usesSharedWorkflowIntentAppend()) this.sessionManager.assertLegacyMutationAllowed("compact session");
29449
+ if (!this.#usesSharedSessionPublication()) this.sessionManager.assertLegacyMutationAllowed("compact session");
28045
29450
  try {
28046
29451
  return await compact(preparation, candidate, apiKey, customInstructions, signal, {
28047
29452
  ...options,
@@ -28338,7 +29743,7 @@ export class AgentSession {
28338
29743
  if (autoCompactionSignal.aborted) return await emitAborted();
28339
29744
 
28340
29745
  const pathEntries = this.#withoutEphemeralCustomMessageEntries(this.sessionManager.getBranch());
28341
- const sharedCompaction = this.#usesSharedWorkflowIntentAppend();
29746
+ const sharedCompaction = this.#usesSharedSessionPublication();
28342
29747
  const owner = this.#captureCompactionPublicationOwner(autoCompactionSignal, "auto-compaction");
28343
29748
  const branchIds = new Set(pathEntries.map(entry => entry.id));
28344
29749
 
@@ -29363,20 +30768,106 @@ export class AgentSession {
29363
30768
  },
29364
30769
  );
29365
30770
  const activeIndex = resolutionStart + resolution.activeIndex;
29366
- if (activeIndex > resolutionStart) {
29367
- this.seedDefaultFallbackResolution(activeIndex, [...controller.skips, ...resolution.skips]);
29368
- } else {
29369
- controller.seedResolution(activeIndex, [...controller.skips, ...resolution.skips]);
30771
+ const thinkingLevel = this.#thinkingLevelForResolvedFallback(
30772
+ resolution.explicitThinkingLevel,
30773
+ resolution.thinkingLevel,
30774
+ );
30775
+ const effectiveThinking = resolution.model
30776
+ ? resolveThinkingLevelForModel(resolution.model, thinkingLevel)
30777
+ : this.#thinkingLevel;
30778
+ let committedThinking: Extract<SharedEntriesAppendOutcome, { kind: "committed" }> | undefined;
30779
+ if (resolution.model && effectiveThinking !== this.#thinkingLevel) {
30780
+ // A shared session publishes the thinking entry through admitted shared publication
30781
+ // (#7824); a legacy session keeps its refusal. Either way, before seeding fallback
30782
+ // state or switching the model.
30783
+ if (this.#usesSharedSessionPublication())
30784
+ committedThinking = await this.#publishSharedFallbackThinking(
30785
+ controller,
30786
+ resolutionStart,
30787
+ effectiveThinking,
30788
+ );
30789
+ else this.sessionManager.assertLegacyMutationAllowed("set thinking level");
30790
+ }
30791
+ const applyResolution = (model: Model | undefined): Model => {
30792
+ if (activeIndex > resolutionStart) {
30793
+ this.seedDefaultFallbackResolution(activeIndex, [...controller.skips, ...resolution.skips]);
30794
+ } else {
30795
+ controller.seedResolution(activeIndex, [...controller.skips, ...resolution.skips]);
30796
+ }
30797
+ if (!model) throw new Error(this.#fallbackExhaustionError(controller));
30798
+ return model;
30799
+ };
30800
+ if (!committedThinking) {
30801
+ const model = applyResolution(resolution.model);
30802
+ const previousEditMode = this.#resolveActiveEditMode();
30803
+ this.#setModelAuthoritatively(model, "restore");
30804
+ this.setThinkingLevel(thinkingLevel);
30805
+ await this.#syncEditToolModeAfterModelChange(previousEditMode);
30806
+ return;
29370
30807
  }
29371
- if (!resolution.model) throw new Error(this.#fallbackExhaustionError(controller));
29372
30808
  const previousEditMode = this.#resolveActiveEditMode();
29373
- this.#setModelAuthoritatively(resolution.model, "restore");
29374
- this.setThinkingLevel(
29375
- this.#thinkingLevelForResolvedFallback(resolution.explicitThinkingLevel, resolution.thinkingLevel),
29376
- );
30809
+ try {
30810
+ this.#setModelAuthoritatively(applyResolution(resolution.model), "restore");
30811
+ this.#applyThinkingLevel(thinkingLevel, false, false, undefined, true);
30812
+ } catch (error) {
30813
+ return this.#failClosedSharedControl("set thinking level for default fallback", committedThinking, error);
30814
+ }
29377
30815
  await this.#syncEditToolModeAfterModelChange(previousEditMode);
29378
30816
  }
29379
30817
 
30818
+ /**
30819
+ * Publish the thinking entry a default-fallback switch implies, at this opener's cursor
30820
+ * and before any fallback state or live model changes. Bound to the controller position,
30821
+ * live model, thinking revision and session identity it was resolved against.
30822
+ */
30823
+ async #publishSharedFallbackThinking(
30824
+ controller: FallbackChainController,
30825
+ resolutionStart: number,
30826
+ level: ThinkingLevel | undefined,
30827
+ ): Promise<Extract<SharedEntriesAppendOutcome, { kind: "committed" }>> {
30828
+ const operation = "set thinking level for default fallback";
30829
+ const assertMode = this.#controlPublicationModeFence(operation);
30830
+ const manager = this.sessionManager;
30831
+ const sessionId = this.sessionId;
30832
+ const identityGeneration = manager.getSessionIdentityGeneration();
30833
+ const model = this.model;
30834
+ const thinkingLevel = this.#thinkingLevel;
30835
+ const thinkingRevision = this.#thinkingLevelMutationRevision;
30836
+ const current = () => {
30837
+ try {
30838
+ assertMode();
30839
+ } catch {
30840
+ return false;
30841
+ }
30842
+ return (
30843
+ !this.#isDisposed &&
30844
+ this.sessionManager === manager &&
30845
+ this.sessionId === sessionId &&
30846
+ manager.getSessionIdentityGeneration() === identityGeneration &&
30847
+ this.model === model &&
30848
+ this.#thinkingLevel === thinkingLevel &&
30849
+ this.#thinkingLevelMutationRevision === thinkingRevision &&
30850
+ this.#defaultFallbackController === controller &&
30851
+ controller.activeIndex === resolutionStart
30852
+ );
30853
+ };
30854
+ const outcome = await this.#withStartedSharedControlPublication(
30855
+ () => {
30856
+ if (!current())
30857
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
30858
+ },
30859
+ () =>
30860
+ manager.appendControlEntriesSharingSession(
30861
+ [{ type: "thinking_level_change", level, operatorIntent: false }],
30862
+ current,
30863
+ ),
30864
+ );
30865
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
30866
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
30867
+ if (!current()) return this.#failClosedSharedControl(operation, outcome);
30868
+ return outcome;
30869
+ }
30870
+
29380
30871
  /**
29381
30872
  * Materialize the default controller from the persisted configured-chain
29382
30873
  * metadata. Consumers seed only resolution state; role/origin/identity stay
@@ -31038,8 +32529,82 @@ export class AgentSession {
31038
32529
  this.#resolveRetry();
31039
32530
  }
31040
32531
 
31041
- #usesSharedWorkflowIntentAppend(): boolean {
31042
- return this.#rootInteractiveSharedAppend && this.sessionManager.isManagedDestination();
32532
+ /**
32533
+ * The single eligibility rule for admitted shared publication (#7824):
32534
+ * managed destination && (root shared mode || session already requires shared admission).
32535
+ * Every migrated control and canonical producer routes through this predicate.
32536
+ */
32537
+ #usesSharedSessionPublication(): boolean {
32538
+ return (
32539
+ this.sessionManager.isManagedDestination() &&
32540
+ (this.#rootInteractiveSharedAppend || this.sessionManager.requiresSharedMutationAdmission())
32541
+ );
32542
+ }
32543
+
32544
+ /**
32545
+ * Bind a control to the publication protocol chosen when it started. A legacy control
32546
+ * keeps the legacy refusal; a session that adopts shared admission (or a shared control
32547
+ * that loses it) while the control awaits is refused before effects rather than
32548
+ * switching protocols mid-transaction.
32549
+ */
32550
+ #controlPublicationModeFence(operation: string): () => void {
32551
+ const manager = this.sessionManager;
32552
+ const shared = this.#usesSharedSessionPublication();
32553
+ const assertMode = () => {
32554
+ if (this.sessionManager !== manager || this.#usesSharedSessionPublication() !== shared)
32555
+ throw new SharedControlPublicationError(operation, {
32556
+ kind: "rejected",
32557
+ error: new Error("publication_mode_changed"),
32558
+ });
32559
+ if (!shared) manager.assertLegacyMutationAllowed(operation);
32560
+ };
32561
+ assertMode();
32562
+ return assertMode;
32563
+ }
32564
+
32565
+ /**
32566
+ * A possibly durable shared control write that this session cannot apply: retain the
32567
+ * exact receipt, never retry or compensate, and close the session so it cannot keep
32568
+ * running on state that diverges from its transcript.
32569
+ */
32570
+ /** Make an already-live MCP selection durable in a shared session (no runtime change). */
32571
+ async #publishSharedMCPToolSelection(selected: string[], assertMode: () => void): Promise<void> {
32572
+ const operation = "select active tools";
32573
+ const manager = this.sessionManager;
32574
+ const identityGeneration = manager.getSessionIdentityGeneration();
32575
+ const current = () => {
32576
+ try {
32577
+ assertMode();
32578
+ } catch {
32579
+ return false;
32580
+ }
32581
+ return (
32582
+ !this.#isDisposed &&
32583
+ this.sessionManager === manager &&
32584
+ manager.getSessionIdentityGeneration() === identityGeneration &&
32585
+ this.#selectedMCPToolNamesMatch(this.getSelectedMCPToolNames(), selected)
32586
+ );
32587
+ };
32588
+ const outcome = await this.#withStartedSharedControlPublication(
32589
+ () => {
32590
+ if (!current())
32591
+ throw new SharedControlPublicationError(operation, { kind: "rejected", error: new Error("superseded") });
32592
+ },
32593
+ () => manager.appendToolSelectionsSharingSession(selected, undefined, current),
32594
+ );
32595
+ if (outcome.kind === "unknown") return this.#failClosedSharedControl(operation, outcome);
32596
+ if (outcome.kind !== "committed") throw new SharedControlPublicationError(operation, outcome);
32597
+ }
32598
+
32599
+ #failClosedSharedControl(
32600
+ operation: string,
32601
+ outcome: Extract<SharedEntriesAppendOutcome, { kind: "committed" | "unknown" }>,
32602
+ cause?: unknown,
32603
+ ): never {
32604
+ void this.dispose().catch(() => {
32605
+ logger.warn("Shared control session teardown failed", { code: "shared_control_teardown_failed", operation });
32606
+ });
32607
+ throw new SharedControlPublicationError(operation, outcome, cause);
31043
32608
  }
31044
32609
 
31045
32610
  async #withStartedSharedControlPublication<T>(assertCurrent: () => void, publish: () => Promise<T>): Promise<T> {
@@ -31063,7 +32628,7 @@ export class AgentSession {
31063
32628
 
31064
32629
  async #appendSharedWorkflowIntentDiff(diff: WorkflowIntentDiff, assertCurrent: () => void): Promise<void> {
31065
32630
  await this.#withStartedSharedControlPublication(assertCurrent, async () => {
31066
- let outcome;
32631
+ let outcome: SharedAppendOutcome;
31067
32632
  try {
31068
32633
  outcome = await this.sessionManager.appendCustomEntrySharingSession(WORKFLOW_INTENT_DIFF_CUSTOM_TYPE, diff);
31069
32634
  } catch (error) {
@@ -31397,8 +32962,7 @@ export class AgentSession {
31397
32962
  this.agent.appendMessage(bashMessage);
31398
32963
 
31399
32964
  // Save to session
31400
- this.sessionManager.appendMessage(bashMessage);
31401
- options?.onPersisted?.();
32965
+ void this.#publishMessageInBackground("bash result", bashMessage, options?.onPersisted);
31402
32966
  }
31403
32967
  }
31404
32968
 
@@ -31425,8 +32989,8 @@ export class AgentSession {
31425
32989
  * Flush pending bash messages to agent state and session.
31426
32990
  * Called after agent turn completes to maintain proper message ordering.
31427
32991
  */
31428
- #flushPendingBashMessages(): void {
31429
- this.#flushPendingExecutionMessages(this.#pendingBashMessages, "bash");
32992
+ async #flushPendingBashMessages(): Promise<void> {
32993
+ await this.#flushPendingExecutionMessages(this.#pendingBashMessages, "bash");
31430
32994
  }
31431
32995
 
31432
32996
  // =========================================================================
@@ -31592,7 +33156,7 @@ export class AgentSession {
31592
33156
  });
31593
33157
  } else {
31594
33158
  this.agent.appendMessage(pythonMessage);
31595
- this.sessionManager.appendMessage(pythonMessage);
33159
+ void this.#publishMessageInBackground("python result", pythonMessage);
31596
33160
  if (!this.#cancelAndSubmitInProgress && this.agent.hasQueuedMessages()) {
31597
33161
  this.#scheduleAgentContinue({
31598
33162
  shouldContinue: () => this.#canAutoContinueForFollowUp() && this.agent.hasQueuedMessages(),
@@ -31658,20 +33222,46 @@ export class AgentSession {
31658
33222
  /**
31659
33223
  * Flush pending Python messages to agent state and session.
31660
33224
  */
31661
- #flushPendingPythonMessages(): void {
31662
- this.#flushPendingExecutionMessages(this.#pendingPythonMessages, "python");
33225
+ async #flushPendingPythonMessages(): Promise<void> {
33226
+ await this.#flushPendingExecutionMessages(this.#pendingPythonMessages, "python");
31663
33227
  }
31664
33228
 
31665
- #flushPendingExecutionMessages<T extends BashExecutionMessage | PythonExecutionMessage>(
33229
+ /**
33230
+ * Serialize deferred command-result drains.
33231
+ *
33232
+ * Queue items stay in place while a shared publication awaits, so a second drain
33233
+ * (forced recovery, a replacement prompt, a prompt finalizer) must wait for the
33234
+ * in-flight one instead of publishing the same item again and running its
33235
+ * `onPersisted` twice. Waiting also keeps transcript order: a later drain retries
33236
+ * only what the earlier one left queued, behind the entry that failed.
33237
+ */
33238
+ async #flushPendingExecutionMessages<T extends BashExecutionMessage | PythonExecutionMessage>(
31666
33239
  pendingMessages: Array<{ message: T; onPersisted?: () => void; appendedToAgent: boolean }>,
31667
33240
  kind: "bash" | "python",
31668
- ): void {
33241
+ ): Promise<void> {
33242
+ while (this.#executionMessageDrain) {
33243
+ // The owning caller observes the drain's failure; a joiner only waits for it.
33244
+ await this.#executionMessageDrain.catch(() => {});
33245
+ }
31669
33246
  if (pendingMessages.length === 0) return;
33247
+ const drain = this.#drainPendingExecutionMessages(pendingMessages, kind);
33248
+ this.#executionMessageDrain = drain;
33249
+ try {
33250
+ await drain;
33251
+ } finally {
33252
+ if (this.#executionMessageDrain === drain) this.#executionMessageDrain = undefined;
33253
+ }
33254
+ }
31670
33255
 
33256
+ async #drainPendingExecutionMessages<T extends BashExecutionMessage | PythonExecutionMessage>(
33257
+ pendingMessages: Array<{ message: T; onPersisted?: () => void; appendedToAgent: boolean }>,
33258
+ kind: "bash" | "python",
33259
+ ): Promise<void> {
31671
33260
  const total = pendingMessages.length;
31672
33261
  const remaining: typeof pendingMessages = [];
31673
33262
  const errors: unknown[] = [];
31674
33263
  const persisted: string[] = [];
33264
+ const unconfirmed: string[] = [];
31675
33265
  let callbackFailureCount = 0;
31676
33266
  let persistenceBlocked = false;
31677
33267
  let agentAppendBlocked = false;
@@ -31699,14 +33289,19 @@ export class AgentSession {
31699
33289
  }
31700
33290
 
31701
33291
  try {
31702
- this.sessionManager.appendMessage(pending.message);
33292
+ await this.#persistExecutionMessage("deferred command result", pending.message);
31703
33293
  } catch (error) {
31704
33294
  // Session entries form a leaf-linked transcript. Once one append fails,
31705
33295
  // later entries must remain queued behind it or a retry would append the
31706
33296
  // failed entry after messages that originally followed it.
31707
33297
  persistenceBlocked = true;
31708
- remaining.push(pending);
31709
33298
  errors.push(error);
33299
+ // An unknown outcome may already be durable under its attempted id. It is
33300
+ // never queued for a retry that would append it again under a new id; the
33301
+ // session closes below with that receipt instead.
33302
+ if (error instanceof SharedControlPublicationError && error.outcome.kind === "unknown")
33303
+ unconfirmed.push(...error.outcome.ids);
33304
+ else remaining.push(pending);
31710
33305
  continue;
31711
33306
  }
31712
33307
 
@@ -31722,17 +33317,27 @@ export class AgentSession {
31722
33317
  pendingMessages.splice(0, pendingMessages.length, ...remaining);
31723
33318
  if (errors.length === 0) return;
31724
33319
 
31725
- const persistedCount = total - remaining.length;
31726
- const persistenceFailureCount = remaining.length;
33320
+ const persistedCount = total - remaining.length - unconfirmed.length;
33321
+ const persistenceFailureCount = remaining.length + unconfirmed.length;
31727
33322
  const persistenceSummary =
31728
- persistenceFailureCount > 0
31729
- ? `Failed to persist ${persistenceFailureCount} of ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}; ${persistedCount} persisted, failed messages remain pending for retry`
31730
- : `Persisted all ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}`;
33323
+ unconfirmed.length > 0
33324
+ ? `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`
33325
+ : persistenceFailureCount > 0
33326
+ ? `Failed to persist ${persistenceFailureCount} of ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}; ${persistedCount} persisted, failed messages remain pending for retry`
33327
+ : `Persisted all ${total} deferred ${kind} execution message${total === 1 ? "" : "s"}`;
31731
33328
  const callbackSummary =
31732
33329
  callbackFailureCount > 0
31733
33330
  ? `; ${callbackFailureCount} onPersisted callback${callbackFailureCount === 1 ? "" : "s"} failed`
31734
33331
  : "";
31735
33332
  const pending = remaining.map(item => ("command" in item.message ? item.message.command : item.message.code));
33333
+ if (unconfirmed.length > 0) {
33334
+ void this.dispose().catch(() => {
33335
+ logger.warn("Deferred command result teardown failed", {
33336
+ code: "shared_execution_result_teardown_failed",
33337
+ attemptedIds: unconfirmed,
33338
+ });
33339
+ });
33340
+ }
31736
33341
  throw new AggregateError(
31737
33342
  errors,
31738
33343
  `${persistenceSummary}${callbackSummary}; persisted: ${JSON.stringify(persisted)}; pending: ${JSON.stringify(pending)}`,
@@ -32151,7 +33756,10 @@ export class AgentSession {
32151
33756
  const rosterClaim = callerOwnsRosterClaim ? turnArgs.ircRosterClaim : this.#claimIrcRosterCandidate();
32152
33757
  const execution = this.#runBackgroundTurn(turnArgs, rosterClaim ?? null, callerOwnsRosterClaim);
32153
33758
  // Retain ownership of actual credential and iterator work, not its abort race.
32154
- void execution.then(() => lease.release(), () => lease.release());
33759
+ void execution.then(
33760
+ () => lease.release(),
33761
+ () => lease.release(),
33762
+ );
32155
33763
  try {
32156
33764
  return await awaitEphemeralAbort(execution, signal);
32157
33765
  } finally {
@@ -32296,8 +33904,11 @@ export class AgentSession {
32296
33904
  async #runOwnedBtwTurn(args: Extract<EphemeralTurnArgs, { purpose: "btw" }>): Promise<EphemeralTurnResult> {
32297
33905
  this.#assertExternalSessionIngress();
32298
33906
  const manager = this.sessionManager;
32299
- if (this.#btwCleanupFailures.some(failure =>
32300
- failure.manager === manager && failure.identity === manager.getSessionIdentityGeneration())) {
33907
+ if (
33908
+ this.#btwCleanupFailures.some(
33909
+ failure => failure.manager === manager && failure.identity === manager.getSessionIdentityGeneration(),
33910
+ )
33911
+ ) {
32301
33912
  throw new BtwTurnCleanupError("The /btw provider cleanup failed; effects are unknown.");
32302
33913
  }
32303
33914
  if (this.#eagerDelegationDirty) throw new Error("Session delegation is not ready");
@@ -33712,7 +35323,12 @@ export class AgentSession {
33712
35323
  try {
33713
35324
  const oldLeafId = currentLeafId;
33714
35325
  const leafTarget = targetId === oldLeafId ? this.sessionManager.getEntryForFidelity(targetId) : undefined;
33715
- if (targetId === oldLeafId && (options.includeTarget || options.summarize || !(leafTarget?.type === "message" && leafTarget.message.role === "user")))
35326
+ if (
35327
+ targetId === oldLeafId &&
35328
+ (options.includeTarget ||
35329
+ options.summarize ||
35330
+ !(leafTarget?.type === "message" && leafTarget.message.role === "user"))
35331
+ )
33716
35332
  return { cancelled: false };
33717
35333
  if (options.summarize && !this.model) {
33718
35334
  throw new Error("No model available for summarization");
@@ -33761,12 +35377,14 @@ export class AgentSession {
33761
35377
  }
33762
35378
  }
33763
35379
 
33764
- if (options.summarize && entriesToSummarize.length > 0) this.sessionManager.assertLegacyMutationAllowed("summarize branch");
35380
+ if (options.summarize && entriesToSummarize.length > 0)
35381
+ this.sessionManager.assertLegacyMutationAllowed("summarize branch");
33765
35382
  this.#settleTrackedQueuedInputsBeforeAgentDisconnect();
33766
35383
  this.#disconnectFromAgent();
33767
35384
  await this.#settleActivePromptForHistoryTransition();
33768
35385
 
33769
- if (options.summarize && entriesToSummarize.length > 0) this.sessionManager.assertLegacyMutationAllowed("summarize branch");
35386
+ if (options.summarize && entriesToSummarize.length > 0)
35387
+ this.sessionManager.assertLegacyMutationAllowed("summarize branch");
33770
35388
  // Run default summarizer if needed
33771
35389
  let summaryText: string | undefined;
33772
35390
  let summaryDetails: unknown;
@@ -34637,6 +36255,41 @@ export class AgentSession {
34637
36255
  }
34638
36256
  }
34639
36257
 
36258
+ /** Outcome of a background publication: `false` means nothing reached the transcript. */
36259
+ interface BackgroundPublicationResult {
36260
+ readonly committed: boolean;
36261
+ readonly cause?: string;
36262
+ }
36263
+
36264
+ /** Flatten a non-committed shared outcome into log/report fields. */
36265
+ function describeSharedAppendFailure(outcome: SharedAppendOutcome): { outcome: string; reason?: string } {
36266
+ if (outcome.kind === "stale") return { outcome: outcome.kind, reason: outcome.reason };
36267
+ if (outcome.kind === "rejected")
36268
+ return {
36269
+ outcome: outcome.kind,
36270
+ reason: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
36271
+ };
36272
+ if (outcome.kind === "unknown") return { outcome: outcome.kind, reason: `attempted id ${outcome.id}` };
36273
+ return { outcome: outcome.kind };
36274
+ }
36275
+
36276
+ /**
36277
+ * Narrow a shared publication outcome to `committed` or throw with its cause.
36278
+ *
36279
+ * Used by every AgentSession seam that replaces a legacy append: the refusal must be
36280
+ * loud, because a silently dropped entry is worse than a surfaced failure.
36281
+ */
36282
+ function assertSharedAppendCommitted(
36283
+ operation: string,
36284
+ outcome: SharedAppendOutcome,
36285
+ ): asserts outcome is Extract<SharedAppendOutcome, { kind: "committed" }> {
36286
+ if (outcome.kind === "committed") return;
36287
+ throw new Error(
36288
+ `${operation} ${outcome.kind}${outcome.kind === "stale" ? `: ${outcome.reason}` : ""}${outcome.kind === "unknown" ? ` (attempted id: ${outcome.id})` : ""}`,
36289
+ { cause: outcome },
36290
+ );
36291
+ }
36292
+
34640
36293
  async function awaitBtwSettlement(pending: Promise<void>): Promise<void> {
34641
36294
  const deadline = Promise.withResolvers<never>();
34642
36295
  const timer = setTimeout(