@gajae-code/coding-agent 0.22.1 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/cli/doctor/probe-types.d.ts +1 -1
  3. package/dist/types/cli/doctor/session-owners-probe.d.ts +7 -0
  4. package/dist/types/cli/doctor/session-owners.d.ts +16 -0
  5. package/dist/types/cli/github-release.d.ts +16 -0
  6. package/dist/types/cli/session-owners-cli.d.ts +13 -0
  7. package/dist/types/cli/update-cli.d.ts +2 -0
  8. package/dist/types/commands/sdk.d.ts +23 -14
  9. package/dist/types/config/settings-schema.d.ts +6 -0
  10. package/dist/types/exec/bash-shell-guardian.d.ts +61 -0
  11. package/dist/types/export/html/html-export-destination.d.ts +16 -0
  12. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  13. package/dist/types/sdk/host/control/runtime-gate.d.ts +7 -0
  14. package/dist/types/session/internal/graph-successor-proof.d.ts +33 -0
  15. package/dist/types/session/internal/managed-session-storage.d.ts +6 -1
  16. package/dist/types/session/internal/session-claim-set.d.ts +69 -0
  17. package/dist/types/session/operator-error-message.d.ts +29 -0
  18. package/dist/types/session/session-manager.d.ts +57 -3
  19. package/dist/types/session/session-owners-layout.d.ts +24 -0
  20. package/dist/types/session/session-ownership-mode.d.ts +45 -0
  21. package/dist/types/session/session-ownership.d.ts +195 -0
  22. package/dist/types/session/session-storage.d.ts +36 -0
  23. package/dist/types/slash-commands/helpers/parse.d.ts +1 -0
  24. package/package.json +12 -8
  25. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  26. package/src/cli/doctor/probe-types.ts +1 -1
  27. package/src/cli/doctor/probe.ts +9 -5
  28. package/src/cli/doctor/runner.ts +6 -1
  29. package/src/cli/doctor/session-owners-probe.ts +69 -0
  30. package/src/cli/doctor/session-owners.ts +106 -0
  31. package/src/cli/github-release.ts +100 -0
  32. package/src/cli/session-owners-cli.ts +118 -0
  33. package/src/cli/stats-cli.ts +19 -1
  34. package/src/cli/update-cli.ts +50 -3
  35. package/src/cli-ordinary.ts +1 -1
  36. package/src/commands/sdk.ts +36 -33
  37. package/src/commands/session.ts +10 -2
  38. package/src/config/settings-schema.ts +18 -0
  39. package/src/config/settings.ts +127 -13
  40. package/src/exec/bash-shell-guardian.ts +181 -12
  41. package/src/exec/isolated-shell.ts +13 -3
  42. package/src/export/html/html-export-destination.ts +47 -2
  43. package/src/export/html/index.ts +161 -13
  44. package/src/internal-urls/docs-index.generated.ts +4 -4
  45. package/src/main.ts +20 -14
  46. package/src/modes/acp/acp-agent.ts +6 -0
  47. package/src/modes/action-registry.ts +4 -1
  48. package/src/modes/controllers/command-controller.ts +12 -5
  49. package/src/modes/controllers/extension-ui-controller.ts +6 -22
  50. package/src/modes/controllers/input-controller.ts +3 -2
  51. package/src/modes/controllers/selector-controller.ts +14 -1
  52. package/src/modes/interactive-mode.ts +6 -3
  53. package/src/modes/print-mode.ts +2 -1
  54. package/src/modes/runtime-init.ts +2 -17
  55. package/src/modes/utils/ui-helpers.ts +5 -3
  56. package/src/sdk/bus/index.ts +22 -0
  57. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  58. package/src/sdk/host/control/dispatch.ts +5 -1
  59. package/src/sdk/host/control/runtime-gate.ts +22 -0
  60. package/src/sdk/host/host.ts +4 -1
  61. package/src/sdk/session-readonly/metadata.ts +24 -18
  62. package/src/sdk/session.ts +2 -0
  63. package/src/session/agent-session.ts +101 -22
  64. package/src/session/internal/graph-successor-proof.ts +108 -0
  65. package/src/session/internal/managed-session-storage.ts +8 -1
  66. package/src/session/internal/session-claim-set.ts +242 -0
  67. package/src/session/operator-error-message.ts +79 -0
  68. package/src/session/session-manager.ts +524 -108
  69. package/src/session/session-owners-layout.ts +52 -0
  70. package/src/session/session-ownership-mode.ts +176 -0
  71. package/src/session/session-ownership.ts +851 -0
  72. package/src/session/session-storage.ts +60 -16
  73. package/src/setup/credential-import.ts +2 -1
  74. package/src/slash-commands/builtin-registry.ts +2 -0
  75. package/src/slash-commands/helpers/parse.ts +3 -1
@@ -151,8 +151,8 @@ import {
151
151
  STREAM_FIRST_EVENT_TIMEOUT_PROVIDER_CODE,
152
152
  } from "@gajae-code/ai/utils/fallback-transport";
153
153
  import { isLoopbackHost } from "@gajae-code/ai/utils/loopback-transport";
154
- import { GEMINI_HEADER_RUNAWAY_ERROR_CODE } from "@gajae-code/ai/utils/thinking-loop";
155
154
  import { REPETITION_GUARD_ERROR_CODE } from "@gajae-code/ai/utils/stream-repetition-guard";
155
+ import { GEMINI_HEADER_RUNAWAY_ERROR_CODE } from "@gajae-code/ai/utils/thinking-loop";
156
156
  import { AttemptRecordStore } from "./attempt-record-store";
157
157
  import {
158
158
  BTW_MAX_ANSWER_UTF8_BYTES,
@@ -584,6 +584,7 @@ import {
584
584
  ttsrPromptFields,
585
585
  wrapUntrustedContent,
586
586
  } from "./messages";
587
+ import { operatorErrorMessage } from "./operator-error-message";
587
588
  import { isLegacyProviderSafetyStopMessage } from "./provider-safety-stop";
588
589
  import type { SessionRecapAppendResult, SessionRecapInput } from "./recap";
589
590
  import { readSdkRunCapability } from "./sdk-run-capability";
@@ -610,6 +611,7 @@ import type {
610
611
  } from "./session-manager";
611
612
  import {
612
613
  createReadonlySessionManager,
614
+ GraphSuccessorUnavailableError,
613
615
  getLatestCompactionEntry,
614
616
  getSessionMessageEntryId,
615
617
  getSessionMessageObservationId,
@@ -5140,6 +5142,36 @@ export class AgentSession {
5140
5142
  });
5141
5143
  }
5142
5144
 
5145
+ /**
5146
+ * Refuse a new turn before any effect once this session's transcript is known to
5147
+ * refuse writes. The manager has latched a persistence failure that its next append
5148
+ * would rethrow before writing: usually {@link ManagedAppendIdentityMismatchError}
5149
+ * after another process changed the transcript, whose operator message names the
5150
+ * recovery (reopen or fork). Without this the turn is admitted, acceptance hooks run
5151
+ * and the first append fails; a hidden custom-message turn even resolved with
5152
+ * unsaved entries in memory. This covers only a session already known to be stuck:
5153
+ * the first turn after a peer write still runs skill resolution, extension and
5154
+ * custom command dispatch and title invalidation, and is refused at its first append.
5155
+ *
5156
+ * The refuse-before-the-model ordering follows the approach in #7843.
5157
+ */
5158
+ #assertTranscriptAcceptsTurn(): void {
5159
+ const latched = this.sessionManager.getLatchedPersistenceFailure();
5160
+ if (latched) throw latched;
5161
+ }
5162
+
5163
+ /**
5164
+ * A peer write detected mid-turn latches the mismatch at the failed append, and
5165
+ * agent-core turns that listener failure into an aborted run. Report the typed
5166
+ * refusal at the public boundary instead of a provider-level abort or a silent
5167
+ * success; the turn's messages stay in memory. Only a latch set during this call is
5168
+ * reported: a command that started no turn on an already-stuck session succeeded.
5169
+ */
5170
+ #throwLatchedAppendRejection(latchedAtEntry: Error | undefined): void {
5171
+ const appendRejection = this.sessionManager.getAppendIdentityMismatch();
5172
+ if (appendRejection && appendRejection !== latchedAtEntry) throw appendRejection;
5173
+ }
5174
+
5143
5175
  #assertSessionAdmissionOpen(): void {
5144
5176
  if (this.#sessionAdmissionClosing || this.#sessionAdmissionClosed || this.#isDisposed) {
5145
5177
  throw this.#sessionAdmissionBusyError();
@@ -11077,7 +11109,6 @@ export class AgentSession {
11077
11109
  if (claims?.size === 0) this.#perToolTtsrClaims.delete(toolCallId);
11078
11110
  }
11079
11111
 
11080
-
11081
11112
  /**
11082
11113
  * `afterToolCall` hook: fold any per-tool TTSR reminders into the result.
11083
11114
  * The claim stays provisional until #settlePerToolTtsrDelivery sees the
@@ -11202,7 +11233,7 @@ export class AgentSession {
11202
11233
  #reconcileTtsrConsumptionFromMessages(): void {
11203
11234
  // A committed reminder can outlive its missing ttsr_injection marker and be compacted out
11204
11235
  // of Agent context. Reconcile consumption without restoring the reminder text (#7838).
11205
- if (!this.#ttsrManager || !this.#ttsrManager.getSettings().enabled) {
11236
+ if (!this.#ttsrManager?.getSettings().enabled) {
11206
11237
  return;
11207
11238
  }
11208
11239
  // Latest published checkpoint per rule. A legacy entry without one only proves the rule
@@ -15822,7 +15853,8 @@ export class AgentSession {
15822
15853
  sessionContext: SessionContext,
15823
15854
  fence?: SessionViewRestoreFence,
15824
15855
  ): Promise<void> {
15825
- if (fence && !fence.isCurrent()) throw Object.assign(new Error("Session view changed."), { code: "resource_gone" });
15856
+ if (fence && !fence.isCurrent())
15857
+ throw Object.assign(new Error("Session view changed."), { code: "resource_gone" });
15826
15858
  this.#resetExplicitMCPToolSelectionAuthority();
15827
15859
  if (!this.#mcpDiscoveryEnabled && this.#resolveEffectiveDiscoveryMode() !== "all") {
15828
15860
  await this.#attachAskToolIfWorkflowActive(fence);
@@ -16288,6 +16320,7 @@ export class AgentSession {
16288
16320
 
16289
16321
  /** Main startup calls this exactly once, after a strict open returned `kind: "opened"`. */
16290
16322
  async continuePersistedHistory(): Promise<void> {
16323
+ this.#assertTranscriptAcceptsTurn();
16291
16324
  this.#assertExternalSessionIngress();
16292
16325
  this.#assertRecoveryHydrationPromoted();
16293
16326
  this.#removeEphemeralCustomMessages();
@@ -16356,6 +16389,7 @@ export class AgentSession {
16356
16389
  continuationSdkRunToken === undefined ? "full" : "publication",
16357
16390
  );
16358
16391
  }
16392
+ this.#throwLatchedAppendRejection(undefined);
16359
16393
  }
16360
16394
 
16361
16395
  buildDisplaySessionContext(): SessionContext {
@@ -16642,6 +16676,8 @@ export class AgentSession {
16642
16676
  "onPreflightAccepted" | "onPreflightAcceptCommit" | "onSkillPrepared" | "preflightSignal" | "sdkRunCapability"
16643
16677
  >,
16644
16678
  ): Promise<{ name: string; path: string; args?: string; lineCount?: number }> {
16679
+ // A skill always starts a turn; refuse before claiming its epoch or running preflight.
16680
+ this.#assertTranscriptAcceptsTurn();
16645
16681
  const internalOptions = {
16646
16682
  ...options,
16647
16683
  sdkRunToken: readSdkRunCapability(options?.sdkRunCapability),
@@ -17937,6 +17973,7 @@ export class AgentSession {
17937
17973
  * @throws Error if no model selected or no API key available (when not streaming)
17938
17974
  */
17939
17975
  async prompt(text: string, options?: PromptOptions): Promise<void> {
17976
+ const latchedAtEntry = this.sessionManager.getAppendIdentityMismatch();
17940
17977
  this.#btwPrefixLedger.clear();
17941
17978
  const releaseStartupPromptWaiter = this.#reserveStartupPromptWaiter();
17942
17979
  const observer = options?.onRunAccepted;
@@ -17972,11 +18009,7 @@ export class AgentSession {
17972
18009
  observer ? { ...options, onRunAccepted: notifyRunAccepted } : options,
17973
18010
  releaseStartupPromptWaiter,
17974
18011
  );
17975
- // Agent-core converts listener failures into an aborted response. Keep a
17976
- // rejected persistence fence typed at the public prompt boundary instead
17977
- // of reporting the misleading provider-level "Request was aborted".
17978
- const appendRejection = this.sessionManager.getAppendIdentityMismatch();
17979
- if (appendRejection) throw appendRejection;
18012
+ this.#throwLatchedAppendRejection(latchedAtEntry);
17980
18013
  } finally {
17981
18014
  if (observedLogicalRunId !== undefined) {
17982
18015
  const observers = this.#promptRunAcceptedObservers.get(observedLogicalRunId);
@@ -18086,6 +18119,11 @@ export class AgentSession {
18086
18119
  }
18087
18120
  }
18088
18121
 
18122
+ // Extension and custom commands that do not start a turn have returned above, so a
18123
+ // stuck session can still run them (status commands, or commands that open another
18124
+ // session). Everything from here on starts a turn: refuse it before admission.
18125
+ this.#assertTranscriptAcceptsTurn();
18126
+
18089
18127
  // Expand file-based prompt templates if requested
18090
18128
  const expandedText = expandPromptTemplates ? expandPromptTemplate(text, [...this.#promptTemplates]) : text;
18091
18129
  const expandedHasUsableImage =
@@ -18433,6 +18471,7 @@ export class AgentSession {
18433
18471
  const internalOptions: InternalCustomMessageOptions | undefined = options
18434
18472
  ? { ...options, ...(sdkRunToken ? { sdkRunToken } : {}) }
18435
18473
  : undefined;
18474
+ this.#assertTranscriptAcceptsTurn();
18436
18475
  this.#assertExternalSessionIngress();
18437
18476
  if (options?.preflightSignal?.aborted) throw promptPreflightCancelledError();
18438
18477
  const textContent =
@@ -18525,6 +18564,7 @@ export class AgentSession {
18525
18564
  },
18526
18565
  options?.preflightSignal,
18527
18566
  );
18567
+ this.#throwLatchedAppendRejection(undefined);
18528
18568
  }
18529
18569
 
18530
18570
  async #promptWithMessage(
@@ -18553,6 +18593,10 @@ export class AgentSession {
18553
18593
  workflowIntentDiff?: WorkflowIntentDiff;
18554
18594
  },
18555
18595
  ): Promise<void> {
18596
+ // Every turn ends up here, including the auto-continue prompt, hidden next-turn
18597
+ // deliveries, sendCustomMessage with triggerTurn and cancelAndSubmit. Refuse a
18598
+ // stuck transcript before the system prompt build, recall and before_agent_start.
18599
+ this.#assertTranscriptAcceptsTurn();
18556
18600
  this.#assertNoHandoffTransition();
18557
18601
  if (options?.preflightSignal?.aborted) throw promptPreflightCancelledError();
18558
18602
  await awaitPromptInvocationPreflight(this.#agentEndPublicationPromise, options?.preflightSignal);
@@ -19072,7 +19116,7 @@ export class AgentSession {
19072
19116
  this.#extensionRunner.emitError({
19073
19117
  extensionPath: `command:${commandName}`,
19074
19118
  event: "command",
19075
- error: err instanceof Error ? err.message : String(err),
19119
+ error: operatorErrorMessage(err, String(err)),
19076
19120
  });
19077
19121
  return true;
19078
19122
  }
@@ -19261,6 +19305,7 @@ export class AgentSession {
19261
19305
  images?.some(image => typeof image?.data === "string" && image.data.trim().length > 0) === true;
19262
19306
  if (typeof text !== "string" || (text.trim().length === 0 && !hasUsableImage))
19263
19307
  throw Object.assign(new Error("Prompt must not be empty."), { code: "invalid_input" });
19308
+ this.#assertTranscriptAcceptsTurn();
19264
19309
  invalidateSessionTitleGeneration(this.sessionManager);
19265
19310
  this.#assertRecoveryHydrationPromoted();
19266
19311
  this.#assertExternalSessionIngress({ allowCancelAndSubmit: true });
@@ -19290,6 +19335,7 @@ export class AgentSession {
19290
19335
  images?.some(image => typeof image?.data === "string" && image.data.trim().length > 0) === true;
19291
19336
  if (typeof text !== "string" || (text.trim().length === 0 && !hasUsableImage))
19292
19337
  throw Object.assign(new Error("Prompt must not be empty."), { code: "invalid_input" });
19338
+ this.#assertTranscriptAcceptsTurn();
19293
19339
  invalidateSessionTitleGeneration(this.sessionManager);
19294
19340
  this.#assertRecoveryHydrationPromoted();
19295
19341
  this.#assertExternalSessionIngress({ allowCancelAndSubmit: true });
@@ -20174,6 +20220,7 @@ export class AgentSession {
20174
20220
  await this.#promptWithMessage(appMessage, this.#getCustomMessageTextContent(appMessage), {
20175
20221
  skipPostPromptRecoveryWait: true,
20176
20222
  });
20223
+ this.#throwLatchedAppendRejection(undefined);
20177
20224
  } finally {
20178
20225
  await this.#syncSkillPromptActiveStateSafely(appMessage, false);
20179
20226
  // The direct idle admission bypasses onFollowUpConsumed:
@@ -20228,6 +20275,7 @@ export class AgentSession {
20228
20275
  await this.#promptWithMessage(appMessage, this.#getCustomMessageTextContent(appMessage), {
20229
20276
  skipPostPromptRecoveryWait: true,
20230
20277
  });
20278
+ this.#throwLatchedAppendRejection(undefined);
20231
20279
  } finally {
20232
20280
  await this.#syncSkillPromptActiveStateSafely(appMessage, false);
20233
20281
  // The direct idle admission bypasses onFollowUpConsumed:
@@ -22381,7 +22429,7 @@ export class AgentSession {
22381
22429
  this.#rebindProviderSessionState(new Map());
22382
22430
  this.#terminalizeQueuedSdkWorkForSessionTransition(this.#queuedMessagesForSessionTransition());
22383
22431
  this.#resetActiveSdkRunOwnership();
22384
- if (!options?.drop) await this.sessionManager.flush();
22432
+ if (!options?.drop) await this.sessionManager.flushBeforeLeaving();
22385
22433
  const noLeasePreviousSessionIdentity = this.sessionManager.getSessionId();
22386
22434
  const noLeasePreviousSessionFile = this.sessionManager.getSessionFile();
22387
22435
  const prepared = await this.sessionManager.prepareNewSession(options);
@@ -22464,7 +22512,7 @@ export class AgentSession {
22464
22512
  if (!(await manager.waitForOwnerInFlightDeliveries(ownerId))) {
22465
22513
  throw new Error("Owned async deliveries did not settle before session replacement.");
22466
22514
  }
22467
- if (!options?.drop) await this.sessionManager.flush();
22515
+ if (!options?.drop) await this.sessionManager.flushBeforeLeaving();
22468
22516
 
22469
22517
  if (!(await manager.cancelAndSettleOwnerJobs(ownerId))) {
22470
22518
  throw new Error("Owned async jobs did not settle before session replacement.");
@@ -22619,6 +22667,9 @@ export class AgentSession {
22619
22667
  // root through the common admitted control publication before resetting anything
22620
22668
  // (#7824); a legacy session keeps the legacy refusal. Adoption while the turn is
22621
22669
  // aborted refuses before the reset rather than switching protocols mid-clear.
22670
+ // A transcript that already refuses writes is refused before the agent reset,
22671
+ // which would otherwise drop the in-memory history and then fail at the flush.
22672
+ this.#assertTranscriptAcceptsTurn();
22622
22673
  const operation = "clear context";
22623
22674
  const assertMode = this.#controlPublicationModeFence(operation);
22624
22675
  const sharedPublication = this.#usesSharedSessionPublication();
@@ -22891,6 +22942,13 @@ export class AgentSession {
22891
22942
  this.#resetActiveSdkRunOwnership();
22892
22943
  };
22893
22944
 
22945
+ // Refuse before the hook and the agent disconnect below. A bounded cold fork
22946
+ // copies through SessionManager.forkFrom, not prepareFork.
22947
+ const forkRefusal = this.sessionManager.getSessionMemoryStats().coldRetirementActive
22948
+ ? undefined
22949
+ : this.sessionManager.graphSuccessorRefusal({ wholeSession: true });
22950
+ if (forkRefusal) throw new GraphSuccessorUnavailableError("prepare fork", forkRefusal);
22951
+
22894
22952
  // Emit session_before_switch event with reason "fork" (can be cancelled)
22895
22953
  if (this.#extensionRunner?.hasHandlers("session_before_switch")) {
22896
22954
  const result = (await this.#extensionRunner.emit({
@@ -22909,7 +22967,7 @@ export class AgentSession {
22909
22967
  await this.#settleBtwForSessionTransition();
22910
22968
 
22911
22969
  // Flush current session to ensure all entries are written
22912
- await this.sessionManager.flush();
22970
+ await this.sessionManager.flushBeforeLeaving();
22913
22971
 
22914
22972
  const boundedColdForkEligible =
22915
22973
  this.sessionManager.getSessionMemoryStats().coldRetirementActive && previousSessionFile !== undefined;
@@ -24815,7 +24873,12 @@ export class AgentSession {
24815
24873
  async #setSharedSessionDefaultModel(
24816
24874
  model: Model,
24817
24875
  thinkingLevel: ThinkingLevel | undefined,
24818
- options: { signal?: AbortSignal; shouldMutate?: () => boolean; onMutationStarted?: () => void; cause?: ModelChangeCause },
24876
+ options: {
24877
+ signal?: AbortSignal;
24878
+ shouldMutate?: () => boolean;
24879
+ onMutationStarted?: () => void;
24880
+ cause?: ModelChangeCause;
24881
+ },
24819
24882
  ): Promise<void> {
24820
24883
  const operation = "set session model";
24821
24884
  const assertMode = this.#controlPublicationModeFence(operation);
@@ -27660,6 +27723,9 @@ export class AgentSession {
27660
27723
  * @param options Optional callbacks for completion/error handling
27661
27724
  */
27662
27725
  async compact(customInstructions?: string, options?: CompactOptions): Promise<CompactionResult> {
27726
+ // Compaction runs hooks and a summarization model before its append; a transcript
27727
+ // that already refuses writes would spend both and then fail.
27728
+ this.#assertTranscriptAcceptsTurn();
27663
27729
  const sharedCompaction = this.#usesSharedSessionPublication();
27664
27730
  const invocationManager = this.sessionManager;
27665
27731
  const invocationSessionId = invocationManager.getSessionId();
@@ -28055,6 +28121,9 @@ export class AgentSession {
28055
28121
  * @returns The handoff document text, or undefined if cancelled/failed
28056
28122
  */
28057
28123
  async handoff(customInstructions?: string, options?: SessionHandoffOptions): Promise<HandoffResult | undefined> {
28124
+ // Handoff generates its document with a model call and then flushes this
28125
+ // transcript; a transcript that already refuses writes would spend the call and fail.
28126
+ this.#assertTranscriptAcceptsTurn();
28058
28127
  const entries = this.sessionManager.getBranch();
28059
28128
  const messageCount = entries.filter(e => e.type === "message").length;
28060
28129
 
@@ -28882,7 +28951,13 @@ export class AgentSession {
28882
28951
  if (contextWindow <= 0) return;
28883
28952
  // F6: non-disableable emergency floor — compact before OOM even when token-based
28884
28953
  // compaction is disabled or its threshold is set too high (weak-hardware protection).
28885
- const emergencyReason = emergencyCompactionReason(this.#resourceSampler());
28954
+ const sample = this.#resourceSampler();
28955
+ // Shared compaction only appends a summary entry and never rewrites the transcript,
28956
+ // so the transcript-size floor cannot shrink the file there: it would add a summary
28957
+ // call and a compaction entry to every prompt and reach the managed cap sooner.
28958
+ const emergencyReason = emergencyCompactionReason(
28959
+ this.#usesSharedSessionPublication() ? { ...sample, transcriptFileBytes: undefined } : sample,
28960
+ );
28886
28961
  if (emergencyReason) {
28887
28962
  logger.warn("Emergency compaction triggered (resource floor exceeded)", { reason: emergencyReason });
28888
28963
  await this.#runAutoCompaction("overflow", false, false, {
@@ -32946,7 +33021,8 @@ export class AgentSession {
32946
33021
  // However, enforce the concurrency Retry-After deadline before allowing
32947
33022
  // same-selector rotation/retry: if a deadline exists for this selector,
32948
33023
  // advance instead of retrying before the deadline.
32949
- const deadlineMs = failedSelector !== undefined ? this.#concurrencyWaitRetryAfterDeadlines.get(failedSelector) : undefined;
33024
+ const deadlineMs =
33025
+ failedSelector !== undefined ? this.#concurrencyWaitRetryAfterDeadlines.get(failedSelector) : undefined;
32950
33026
  if (deadlineMs !== undefined && Date.now() < deadlineMs) {
32951
33027
  // Deadline not yet reached; advance instead of retrying
32952
33028
  outcome = controller.advance() ? "advance" : "exhausted";
@@ -35326,7 +35402,7 @@ export class AgentSession {
35326
35402
 
35327
35403
  await this.#settleBtwForSessionTransition();
35328
35404
  // Flush pending writes before switching so restore snapshots reflect committed state.
35329
- await this.sessionManager.flush();
35405
+ await this.sessionManager.flushBeforeLeaving();
35330
35406
  const previousSessionState = await this.sessionManager.captureRollbackState();
35331
35407
  const previousSessionAgentModelOverrides = this.getSessionAgentModelOverrideState();
35332
35408
  let stagedSessionAgentModelRevision: number | undefined;
@@ -36063,6 +36139,11 @@ export class AgentSession {
36063
36139
  if (selectedEntry?.type !== "message" || selectedEntry.message.role !== "user") {
36064
36140
  throw new Error("Invalid entry ID for branching");
36065
36141
  }
36142
+ // Refuse before the hook, the agent disconnect and the /btw settle below.
36143
+ const branchRefusal = selectedEntry.parentId
36144
+ ? this.sessionManager.graphSuccessorRefusal({ leafId: selectedEntry.parentId })
36145
+ : undefined;
36146
+ if (branchRefusal) throw new GraphSuccessorUnavailableError("prepare branched session", branchRefusal);
36066
36147
  const previousSessionFile = this.sessionFile;
36067
36148
  const previousWorkflowGateSessionId = this.sessionId;
36068
36149
  const previousSessionIdentity = this.sessionManager.getSessionId();
@@ -36094,7 +36175,7 @@ export class AgentSession {
36094
36175
  await this.#settleBtwForSessionTransition();
36095
36176
 
36096
36177
  // Flush pending writes before preparing the successor.
36097
- await this.sessionManager.flush();
36178
+ await this.sessionManager.flushBeforeLeaving();
36098
36179
  const prepared = selectedEntry.parentId
36099
36180
  ? await this.sessionManager.prepareBranchedSession(selectedEntry.parentId)
36100
36181
  : await this.sessionManager.prepareNewSession({ parentSession: previousSessionFile });
@@ -36225,8 +36306,7 @@ export class AgentSession {
36225
36306
  const explicitActiveToolSelectionGeneration = this.#explicitActiveToolSelectionGeneration;
36226
36307
  const previousSelectedMCPToolNames = new Set(this.#selectedMCPToolNames);
36227
36308
  const previousSelectedDiscoveredToolNames = new Set(this.#selectedDiscoveredToolNames);
36228
- const previousHasExplicitActiveToolSelectionForContext =
36229
- this.#committedHasExplicitActiveToolSelectionForContext;
36309
+ const previousHasExplicitActiveToolSelectionForContext = this.#committedHasExplicitActiveToolSelectionForContext;
36230
36310
  const previousExplicitMCPToolSelectionForContext = this.#committedExplicitMCPToolSelectionForContext
36231
36311
  ? [...this.#committedExplicitMCPToolSelectionForContext]
36232
36312
  : undefined;
@@ -36347,8 +36427,7 @@ export class AgentSession {
36347
36427
  if (authorityOurs()) {
36348
36428
  this.#hasExplicitActiveToolSelectionForContext = previousHasExplicitActiveToolSelectionForContext;
36349
36429
  this.#explicitMCPToolSelectionForContext = previousExplicitMCPToolSelectionForContext;
36350
- this.#explicitMCPToolSelectionPersistsForContext =
36351
- previousExplicitMCPToolSelectionPersistsForContext;
36430
+ this.#explicitMCPToolSelectionPersistsForContext = previousExplicitMCPToolSelectionPersistsForContext;
36352
36431
  this.#commitExplicitMCPToolSelectionAuthority();
36353
36432
  }
36354
36433
  // Prompt before tools: the tool observer may publish prompt state of
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Proof that a fork or branch of a shared session can be built from its committed
3
+ * transcript without writing the source. Pure: callers supply the committed bytes, the
4
+ * ids this opener holds, the resident source entries and the legacy serialiser.
5
+ */
6
+ import * as crypto from "node:crypto";
7
+ import { CURRENT_SESSION_VERSION, parseStoredSessionEntries } from "../../sdk/session-readonly/format";
8
+ import { sanitizeRehydratedOpenAIResponsesAssistantMessage } from "../messages";
9
+ import type { FileEntry, SessionEntry } from "../session-manager";
10
+
11
+ /** Why a fork or branch of a shared session cannot be built from its committed transcript. */
12
+ export type GraphSuccessorRefusal =
13
+ | "publication-in-flight"
14
+ | "not-admitted"
15
+ | "unknown-entry"
16
+ | "large-session"
17
+ | "old-format"
18
+ | "unreadable"
19
+ | "foreign-entry"
20
+ | "uncommitted"
21
+ | "content-mismatch"
22
+ | "changed"
23
+ | "busy";
24
+
25
+ const REFUSAL_TEXT: Record<GraphSuccessorRefusal, string> = {
26
+ "publication-in-flight": "a save to this session is still in progress",
27
+ "not-admitted": "this session does not allow it right now",
28
+ "unknown-entry": "the selected message is not in this session",
29
+ "large-session": "this session is too large to fork safely",
30
+ "old-format": "this session file uses an older format",
31
+ unreadable: "the session file could not be read",
32
+ "foreign-entry": "another gjc process has written to this session",
33
+ uncommitted: "part of this branch has not been saved to the session file",
34
+ "content-mismatch": "the saved session file does not match the loaded session",
35
+ changed: "the session file changed while the fork was prepared",
36
+ busy: "another gjc process is writing to this session",
37
+ };
38
+
39
+ /** The user-facing refusal message for `reason`. */
40
+ export function graphSuccessorRefusalMessage(reason: GraphSuccessorRefusal): string {
41
+ return `Cannot fork this session: ${REFUSAL_TEXT[reason]}.`;
42
+ }
43
+
44
+ /** The load-time projection applied to every entry read back from a transcript. */
45
+ export function sanitizeLoadedSessionEntryReplayMetadata(entry: SessionEntry): SessionEntry {
46
+ if (entry.type === "message" && entry.message.role === "assistant") {
47
+ entry.message = sanitizeRehydratedOpenAIResponsesAssistantMessage(entry.message);
48
+ }
49
+ return entry;
50
+ }
51
+
52
+ /**
53
+ * Whether a committed transcript entry and the legacy serialisation of a resident entry
54
+ * are the same entry for a successor: JSON-equal as they stand, or equal once both have
55
+ * had the load-time projection applied. Resume strips OpenAI Responses replay metadata
56
+ * in memory without rewriting a managed transcript; a live session keeps it on both sides.
57
+ */
58
+ export function committedEntryMatchesResident(committed: FileEntry, serializedResident: FileEntry): boolean {
59
+ if (Bun.deepEquals(committed, serializedResident)) return true;
60
+ if (committed.type === "session" || serializedResident.type === "session") return false;
61
+ const project = (entry: SessionEntry) => sanitizeLoadedSessionEntryReplayMetadata(structuredClone(entry));
62
+ return Bun.deepEquals(project(committed), project(serializedResident));
63
+ }
64
+
65
+ /**
66
+ * Prove the committed transcript is this opener's own graph and each source entry is
67
+ * committed as this opener holds it. Requires this session at the current version; no
68
+ * entry id outside `ownIds` (a peer's sibling is foreign; id-less patch lines are
69
+ * applied, not counted); every source entry committed and matching
70
+ * ({@link committedEntryMatchesResident}). Returns the successor's source lines (the
71
+ * legacy serialisation) and the digest of the bytes proven, or the refusal.
72
+ */
73
+ export function proveOwnCommittedGraph(input: {
74
+ bytes: Uint8Array;
75
+ sessionId: string;
76
+ ownIds: ReadonlySet<string>;
77
+ sourceEntries: readonly SessionEntry[];
78
+ serialize: (entry: SessionEntry) => FileEntry;
79
+ onMismatch?: (entryId: string) => void;
80
+ }): { lines: string[]; digest: string } | GraphSuccessorRefusal {
81
+ let committed: FileEntry[];
82
+ try {
83
+ committed = parseStoredSessionEntries<FileEntry>(new TextDecoder("utf-8", { fatal: true }).decode(input.bytes));
84
+ } catch {
85
+ return "unreadable";
86
+ }
87
+ const header = committed[0];
88
+ if (header?.type !== "session" || header.id !== input.sessionId) return "unreadable";
89
+ if (header.version !== CURRENT_SESSION_VERSION) return "old-format";
90
+ const byId = new Map<string, SessionEntry>();
91
+ for (const entry of committed) {
92
+ if (entry.type === "session" || typeof entry.id !== "string") continue;
93
+ if (!input.ownIds.has(entry.id)) return "foreign-entry";
94
+ byId.set(entry.id, entry);
95
+ }
96
+ const lines: string[] = [];
97
+ for (const entry of input.sourceEntries) {
98
+ const line = byId.get(entry.id);
99
+ if (!line) return "uncommitted";
100
+ const serialized = JSON.parse(JSON.stringify(input.serialize(entry))) as FileEntry;
101
+ if (!committedEntryMatchesResident(line, serialized)) {
102
+ input.onMismatch?.(entry.id);
103
+ return "content-mismatch";
104
+ }
105
+ lines.push(JSON.stringify(serialized));
106
+ }
107
+ return { lines, digest: crypto.createHash("sha256").update(input.bytes).digest("hex") };
108
+ }
@@ -73,12 +73,19 @@ const LOCK_LEASE_MS = 60_000;
73
73
  const LOCK_HEARTBEAT_MS = 10_000;
74
74
  const LOCK_WAIT_MS = 5_000;
75
75
 
76
+ /**
77
+ * Operator text for a fence rejection during startup, before this process ran anything
78
+ * in the session: the resume itself did not happen, so there is nothing to recover.
79
+ */
80
+ export const RESUME_REJECTED_OPERATOR_MESSAGE =
81
+ "Session was resumed by another process; this resume did not run. Retry, or resume a different session.";
82
+
76
83
  /** A pre-mutation append fence rejection: no bytes from this append were written. */
77
84
  export class ManagedAppendIdentityMismatchError extends Error {
78
85
  readonly code = "managed_append_identity_mismatch";
79
86
  readonly relativePath: string;
80
87
  readonly operatorMessage =
81
- "Session was resumed by another process; this resume did not run. Retry, or resume a different session.";
88
+ "Another process changed this session's transcript, so this process stopped saving to it. To continue, reopen the session with /resume (or gjc --resume), or fork it with /fork (or gjc --fork).";
82
89
 
83
90
  constructor(relativePath: string) {
84
91
  super("managed_append_identity_mismatch");