@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.
- package/CHANGELOG.md +60 -0
- package/dist/types/config/autorouting-contract.d.ts +4 -4
- package/dist/types/config/autorouting-tier-map.d.ts +1 -1
- package/dist/types/config/keybindings.d.ts +1 -5
- package/dist/types/config/model-profile-activation.d.ts +30 -3
- package/dist/types/config/model-registry.d.ts +2 -0
- package/dist/types/config/models-config-schema.d.ts +8 -0
- package/dist/types/config/settings-schema.d.ts +7 -3
- package/dist/types/coordinator-mcp/canonical-json.d.ts +7 -0
- package/dist/types/extensibility/gjc-plugins/metadata.d.ts +1 -1
- package/dist/types/harness-control-plane/receipts.d.ts +1 -1
- package/dist/types/modes/components/settings-selector.d.ts +5 -2
- package/dist/types/modes/controllers/command-controller.d.ts +1 -1
- package/dist/types/modes/controllers/input-controller.d.ts +12 -0
- package/dist/types/modes/controllers/selector-controller.d.ts +1 -1
- package/dist/types/modes/interactive-mode.d.ts +1 -1
- package/dist/types/modes/shared/agent-wire/workflow-gate-schema.d.ts +1 -1
- package/dist/types/modes/types.d.ts +1 -1
- package/dist/types/session/agent-session.d.ts +101 -6
- package/dist/types/session/session-manager.d.ts +124 -9
- package/dist/types/setup/provider-onboarding.d.ts +55 -2
- package/dist/types/slash-commands/builtin-registry.d.ts +11 -0
- package/dist/types/utils/clipboard.d.ts +18 -0
- package/dist/types/utils/pasted-image-path.d.ts +2 -0
- package/dist/types/web/search/providers/keenable.d.ts +30 -0
- package/dist/types/web/search/types.d.ts +2 -2
- package/package.json +7 -7
- package/scripts/generate-sdk-operation-inventory.ts +28 -0
- package/src/cli/doctor/config-repairs.ts +1 -4
- package/src/cli/local-provider-smoke.ts +1 -4
- package/src/cli/public-command-help.ts +1 -1
- package/src/config/autorouting-contract.ts +5 -8
- package/src/config/autorouting-tier-map.ts +1 -1
- package/src/config/keybindings.ts +1 -2
- package/src/config/model-profile-activation.ts +332 -28
- package/src/config/model-registry.ts +156 -8
- package/src/config/models-config-schema.ts +27 -0
- package/src/config/settings-schema.ts +6 -0
- package/src/coordinator-mcp/canonical-json.ts +15 -0
- package/src/coordinator-mcp/policy.ts +1 -0
- package/src/coordinator-mcp/question-gate-codec.ts +1 -2
- package/src/coordinator-mcp/question-state.ts +2 -12
- package/src/coordinator-mcp/server.ts +1 -10
- package/src/customization/import.ts +1 -5
- package/src/discovery/mcp-compat.ts +1 -5
- package/src/discovery/mcp-json.ts +1 -4
- package/src/edit/notebook.ts +1 -5
- package/src/extensibility/gjc-plugins/lifecycle.ts +1 -3
- package/src/extensibility/gjc-plugins/metadata.ts +2 -5
- package/src/extensibility/gjc-plugins/schema.ts +1 -4
- package/src/gjc-runtime/deep-interview-crystallize.ts +1 -4
- package/src/gjc-runtime/deep-interview-runtime.ts +1 -4
- package/src/gjc-runtime/state-renderer.ts +1 -5
- package/src/gjc-runtime/tmux-owner-isolation.ts +1 -3
- package/src/gjc-runtime/ultragoal-owner-loss-recovery.ts +1 -4
- package/src/gjc-runtime/ultragoal-succession.ts +1 -4
- package/src/goals/continuation-timeout-guard.ts +1 -4
- package/src/harness-control-plane/receipts.ts +1 -1
- package/src/internal-urls/docs-index.generated.ts +4 -4
- package/src/migrate/mcp-mapper.ts +2 -4
- package/src/modes/components/hook-editor.ts +4 -8
- package/src/modes/components/hook-selector.ts +3 -1
- package/src/modes/components/settings-selector.ts +26 -2
- package/src/modes/controllers/command-controller.ts +4 -98
- package/src/modes/controllers/extension-ui-controller.ts +6 -14
- package/src/modes/controllers/goal-mode-controller.ts +4 -4
- package/src/modes/controllers/input-controller.ts +110 -46
- package/src/modes/controllers/plan-mode-controller.ts +6 -10
- package/src/modes/controllers/selector-controller.ts +66 -23
- package/src/modes/controllers/todo-command-controller.ts +2 -2
- package/src/modes/interactive-mode.ts +2 -2
- package/src/modes/prompt-action-autocomplete.ts +1 -1
- package/src/modes/runtime-init.ts +4 -4
- package/src/modes/shared/agent-wire/workflow-gate-schema.ts +1 -1
- package/src/modes/types.ts +1 -1
- package/src/modes/utils/hotkeys-markdown.ts +1 -1
- package/src/runtime-mcp/client.ts +1 -4
- package/src/runtime-mcp/elicitation.ts +1 -5
- package/src/runtime-mcp/protocol.ts +2 -4
- package/src/sdk/broker/lifecycle-ledger.ts +1 -0
- package/src/sdk/broker/lifecycle.ts +1 -0
- package/src/sdk/cli/rows.ts +2 -3
- package/src/sdk/cli/session-cli.ts +2 -8
- package/src/sdk/host/query/cursor.ts +1 -0
- package/src/sdk/host/reverse-leases.ts +1 -0
- package/src/sdk/lifecycle/service.ts +1 -0
- package/src/sdk/protocol/operation-inventory.generated.json +154 -0
- package/src/session/agent-session.ts +1877 -224
- package/src/session/btw-prefix-ledger.ts +1 -4
- package/src/session/internal/managed-gc-retirement-codec.ts +1 -4
- package/src/session/session-manager.ts +732 -224
- package/src/session/task-artifact-owner-codec.ts +1 -4
- package/src/session-import/claude.ts +1 -4
- package/src/session-import/detect.ts +1 -6
- package/src/session-import/provider-codex.ts +1 -6
- package/src/session-import/provider-service.ts +4 -0
- package/src/setup/hermes-setup.ts +1 -4
- package/src/setup/provider-onboarding.ts +514 -26
- package/src/slash-commands/builtin-registry.ts +26 -13
- package/src/slash-commands/helpers/todo.ts +3 -1
- package/src/task/delegation-hint.ts +1 -4
- package/src/task/executor.ts +4 -2
- package/src/task/provider-retry-status.ts +1 -4
- package/src/tools/json-tree.ts +1 -4
- package/src/tools/recipe/runners/pkg.ts +1 -5
- package/src/utils/clipboard.ts +155 -2
- package/src/utils/mac-file-urls.applescript +37 -0
- package/src/utils/pasted-image-path.ts +5 -0
- package/src/web/search/provider.ts +6 -0
- package/src/web/search/providers/keenable.ts +207 -0
- package/src/web/search/types.ts +2 -0
|
@@ -169,7 +169,10 @@ import {
|
|
|
169
169
|
publishManagedFileNoReplaceSync,
|
|
170
170
|
retainManagedDirectoryAuthority,
|
|
171
171
|
} from "./internal/managed-session-storage";
|
|
172
|
-
import {
|
|
172
|
+
import {
|
|
173
|
+
type ManagedSessionTransactionScope,
|
|
174
|
+
withManagedSessionTransaction,
|
|
175
|
+
} from "./internal/managed-session-transaction";
|
|
173
176
|
import { classifyNativePublishOutcome, formatNativePublishDiagnostic } from "./internal/native-publish-outcome";
|
|
174
177
|
import {
|
|
175
178
|
applyReducerDelta,
|
|
@@ -910,6 +913,43 @@ export type ConfiguredModelChain = Pick<
|
|
|
910
913
|
"role" | "entries" | "origin" | "identity" | "explicitHead" | "cleared"
|
|
911
914
|
>;
|
|
912
915
|
|
|
916
|
+
/**
|
|
917
|
+
* One entry of an admitted shared control publication
|
|
918
|
+
* ({@link SessionManager.appendControlEntriesSharingSession}). Controls describe
|
|
919
|
+
* their transcript effect as data so every control shares one admission path.
|
|
920
|
+
*/
|
|
921
|
+
export type SharedControlEntry =
|
|
922
|
+
| { readonly type: "configured_model_chain"; readonly chain: ConfiguredModelChain }
|
|
923
|
+
| {
|
|
924
|
+
readonly type: "model_change";
|
|
925
|
+
readonly model: string;
|
|
926
|
+
readonly role: string;
|
|
927
|
+
readonly metadata?: { previousModel?: string; reason?: string; thinkingLevel?: string | null };
|
|
928
|
+
}
|
|
929
|
+
| { readonly type: "model_role_clear"; readonly role: string }
|
|
930
|
+
| { readonly type: "thinking_level_change"; readonly level: string | undefined; readonly operatorIntent: boolean }
|
|
931
|
+
| { readonly type: "service_tier_change"; readonly serviceTier: ServiceTier | null }
|
|
932
|
+
| { readonly type: "custom"; readonly customType: string; readonly data: unknown }
|
|
933
|
+
/**
|
|
934
|
+
* A parentless `context_clear` root: it starts this opener's fresh active branch. Only
|
|
935
|
+
* valid as the first entry of a publication; later entries descend from it.
|
|
936
|
+
*/
|
|
937
|
+
| { readonly type: "context_clear"; readonly data: Record<string, unknown> | undefined };
|
|
938
|
+
|
|
939
|
+
export interface DefaultModelSelectionEntriesOptions {
|
|
940
|
+
readonly appendThinkingLevel: boolean;
|
|
941
|
+
readonly appendTemporaryModelChange?: boolean;
|
|
942
|
+
readonly configuredDefaultChain?: readonly string[];
|
|
943
|
+
readonly selectionRole?: string;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
export type ModelProfileTranscriptPlan = {
|
|
947
|
+
configuredDefaultChain?: ConfiguredModelChain;
|
|
948
|
+
temporaryModel?: string;
|
|
949
|
+
thinking?: { readonly level: string | undefined };
|
|
950
|
+
resumeDefault?: { readonly selector: string | undefined };
|
|
951
|
+
};
|
|
952
|
+
|
|
913
953
|
export interface ServiceTierChangeEntry extends SessionEntryBase {
|
|
914
954
|
type: "service_tier_change";
|
|
915
955
|
serviceTier: ServiceTier | null;
|
|
@@ -1957,7 +1997,7 @@ export type SharedTitleOutcome =
|
|
|
1957
1997
|
* failures; reconcile it against the transcript before retrying. `rejected` proves
|
|
1958
1998
|
* no append was committed. Lock acquisition failures before staging still throw.
|
|
1959
1999
|
*/
|
|
1960
|
-
export type
|
|
2000
|
+
export type SharedEntriesAppendOutcome =
|
|
1961
2001
|
| { readonly kind: "committed"; readonly ids: readonly string[] }
|
|
1962
2002
|
| { readonly kind: "unknown"; readonly ids: readonly string[]; readonly error: unknown }
|
|
1963
2003
|
| Extract<SharedAppendOutcome, { kind: "stale" | "rejected" }>;
|
|
@@ -7965,8 +8005,33 @@ export class SessionManager {
|
|
|
7965
8005
|
#persistError: Error | undefined;
|
|
7966
8006
|
/** Set while a shared append runs, so no persistence path may escalate to a rewrite. */
|
|
7967
8007
|
#sharedAppendOnly = false;
|
|
7968
|
-
/**
|
|
7969
|
-
|
|
8008
|
+
/**
|
|
8009
|
+
* Permanent legacy-append refusal, set once a canonical shared append adopts a
|
|
8010
|
+
* committed identity whose sibling entries this manager never imported.
|
|
8011
|
+
*
|
|
8012
|
+
* This is refusal policy, not the safety guarantee: the append itself would stay
|
|
8013
|
+
* additive and identity-fenced (a stale predecessor fails with
|
|
8014
|
+
* ManagedAppendIdentityMismatchError), but admitting it would make the partial
|
|
8015
|
+
* resident graph durable. Whole-graph safety is carried by
|
|
8016
|
+
* {@link #sharedRewriteBarSessionIds}; the pinned shared-mutation contract asserts
|
|
8017
|
+
* this bar, which turns a mid-write identity failure into an immediate typed
|
|
8018
|
+
* refusal.
|
|
8019
|
+
*/
|
|
8020
|
+
readonly #sharedAppendBarSessionIds = new Set<string>();
|
|
8021
|
+
/**
|
|
8022
|
+
* Permanent bar on resident-graph and whole-transcript rewrites. Latched once this
|
|
8023
|
+
* manager re-anchors to a committed transcript whose entries it did not import:
|
|
8024
|
+
* every canonical shared append, and a title that adopts an existing transcript.
|
|
8025
|
+
* Enforced at the write funnels (`#writeEntriesAtomicallySync`,
|
|
8026
|
+
* `#rewriteFileContents`, `#rewriteFileSync`), so recovery and close-time
|
|
8027
|
+
* escalations cannot bypass it.
|
|
8028
|
+
*/
|
|
8029
|
+
readonly #sharedRewriteBarSessionIds = new Set<string>();
|
|
8030
|
+
/**
|
|
8031
|
+
* In-flight bar shared by control and one-shot publications. Every append and
|
|
8032
|
+
* rewrite is refused until each concurrent publication has settled.
|
|
8033
|
+
*/
|
|
8034
|
+
readonly #activeSharedMutationSessionCounts = new Map<string, number>();
|
|
7970
8035
|
/** Short-lived durable thinking commits, shared by local managers of the same logical session. */
|
|
7971
8036
|
static readonly #durableThinkingControls = new Map<string, number>();
|
|
7972
8037
|
static readonly #legacyThinkingControls = new Map<string, number>();
|
|
@@ -11161,7 +11226,7 @@ export class SessionManager {
|
|
|
11161
11226
|
const branchPath = this.#getCanonicalBranchClones(leafId);
|
|
11162
11227
|
if (branchPath.length === 0) throw new Error(`Entry ${leafId} not found`);
|
|
11163
11228
|
await this.#closePersistWriter();
|
|
11164
|
-
this.#assertLogicalSessionMutationAllowed(sourceId, "prepare branched session");
|
|
11229
|
+
this.#assertLogicalSessionMutationAllowed(sourceId, "prepare branched session", true);
|
|
11165
11230
|
const timestamp = new Date().toISOString();
|
|
11166
11231
|
const sessionId = createSessionId();
|
|
11167
11232
|
const sessionFile = this.persist
|
|
@@ -11414,10 +11479,10 @@ export class SessionManager {
|
|
|
11414
11479
|
throw new Error("Managed session storage could not be verified; refusing deletion.");
|
|
11415
11480
|
const candidate = listing.owned.find(candidate => path.resolve(candidate.path) === requestedPath);
|
|
11416
11481
|
if (!candidate) throw new Error("Managed session deletion requires exact logical authorization.");
|
|
11417
|
-
this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session");
|
|
11482
|
+
this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session", true);
|
|
11418
11483
|
if (this.#sessionFile && path.resolve(this.#sessionFile) === requestedPath) await this.newSession();
|
|
11419
11484
|
await this.#closePersistWriter();
|
|
11420
|
-
this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session");
|
|
11485
|
+
this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session", true);
|
|
11421
11486
|
const deleted = await deleteManagedSessionCandidate(resolved.scope, candidate);
|
|
11422
11487
|
if (deleted.kind === "error" && deleted.code === "migration_busy") throw new SessionMigrationBusyError();
|
|
11423
11488
|
if (deleted.kind !== "deleted" && deleted.kind !== "already_deleted")
|
|
@@ -11543,10 +11608,10 @@ export class SessionManager {
|
|
|
11543
11608
|
];
|
|
11544
11609
|
const forkSnapshotHook = SessionManagerTestHooks.afterForkSnapshot;
|
|
11545
11610
|
if (forkSnapshotHook) await forkSnapshotHook();
|
|
11546
|
-
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session");
|
|
11611
|
+
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
|
|
11547
11612
|
|
|
11548
11613
|
await this.#closePersistWriter();
|
|
11549
|
-
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session");
|
|
11614
|
+
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
|
|
11550
11615
|
this.#persistChain = Promise.resolve();
|
|
11551
11616
|
this.#persistError = undefined;
|
|
11552
11617
|
this.#closeRetryOriginError = undefined;
|
|
@@ -11555,9 +11620,9 @@ export class SessionManager {
|
|
|
11555
11620
|
let forkTranscriptPublication: ForkTranscriptPublication | undefined;
|
|
11556
11621
|
let transition: PreparedResidentStoreTransition | undefined;
|
|
11557
11622
|
try {
|
|
11558
|
-
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session");
|
|
11623
|
+
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
|
|
11559
11624
|
forkArtifactPublication = await this.copyArtifactsForFork(oldSessionFile, newSessionFile);
|
|
11560
|
-
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session");
|
|
11625
|
+
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
|
|
11561
11626
|
// Publish each already-materialized entry through the staged writer without
|
|
11562
11627
|
// joining the transcript into another whole-file string/Buffer. Retired cold
|
|
11563
11628
|
// history was rehydrated above and is therefore not omitted.
|
|
@@ -11594,7 +11659,7 @@ export class SessionManager {
|
|
|
11594
11659
|
};
|
|
11595
11660
|
}
|
|
11596
11661
|
await SessionManagerTestHooks.afterForkTranscriptPublished?.();
|
|
11597
|
-
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session");
|
|
11662
|
+
this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
|
|
11598
11663
|
if (forkArtifactPublication?.kind === "managed") {
|
|
11599
11664
|
forkArtifactPublication.store.verifyRootSecurity();
|
|
11600
11665
|
forkArtifactPublication.store.assertBound();
|
|
@@ -17290,15 +17355,41 @@ export class SessionManager {
|
|
|
17290
17355
|
return this.persist;
|
|
17291
17356
|
}
|
|
17292
17357
|
|
|
17358
|
+
/**
|
|
17359
|
+
* The additive entries of a concrete default model selection, in the same order
|
|
17360
|
+
* {@link stageDefaultModelSelection} stages them, for admitted shared publication.
|
|
17361
|
+
*/
|
|
17362
|
+
defaultModelSelectionControlEntries(
|
|
17363
|
+
model: string,
|
|
17364
|
+
thinkingLevel: string | undefined,
|
|
17365
|
+
options?: DefaultModelSelectionEntriesOptions,
|
|
17366
|
+
): SharedControlEntry[] {
|
|
17367
|
+
const entries: SharedControlEntry[] = [];
|
|
17368
|
+
if (options?.appendTemporaryModelChange !== false)
|
|
17369
|
+
entries.push({ type: "model_change", model, role: "temporary" });
|
|
17370
|
+
if (options?.appendThinkingLevel)
|
|
17371
|
+
entries.push({ type: "thinking_level_change", level: thinkingLevel, operatorIntent: false });
|
|
17372
|
+
if (options?.configuredDefaultChain)
|
|
17373
|
+
entries.push({
|
|
17374
|
+
type: "configured_model_chain",
|
|
17375
|
+
chain: {
|
|
17376
|
+
role: "default",
|
|
17377
|
+
entries: [...options.configuredDefaultChain],
|
|
17378
|
+
origin: "model_selection",
|
|
17379
|
+
explicitHead: true,
|
|
17380
|
+
cleared: options.configuredDefaultChain.length === 0,
|
|
17381
|
+
},
|
|
17382
|
+
});
|
|
17383
|
+
entries.push({ type: "model_change", model, role: "default" });
|
|
17384
|
+
if (options?.selectionRole && options.selectionRole !== "default")
|
|
17385
|
+
entries.push({ type: "model_change", model, role: options.selectionRole });
|
|
17386
|
+
return entries;
|
|
17387
|
+
}
|
|
17388
|
+
|
|
17293
17389
|
async stageDefaultModelSelection(
|
|
17294
17390
|
model: string,
|
|
17295
17391
|
thinkingLevel: string | undefined,
|
|
17296
|
-
options?:
|
|
17297
|
-
readonly appendThinkingLevel: boolean;
|
|
17298
|
-
readonly appendTemporaryModelChange?: boolean;
|
|
17299
|
-
readonly configuredDefaultChain?: readonly string[];
|
|
17300
|
-
readonly selectionRole?: string;
|
|
17301
|
-
},
|
|
17392
|
+
options?: DefaultModelSelectionEntriesOptions,
|
|
17302
17393
|
): Promise<DefaultModelSelectionStage> {
|
|
17303
17394
|
this.assertLegacyMutationAllowed("stage default model selection");
|
|
17304
17395
|
const sessionFile = this.#sessionFile;
|
|
@@ -18989,10 +19080,25 @@ export class SessionManager {
|
|
|
18989
19080
|
await this.#setLivePickerStar(session, starred);
|
|
18990
19081
|
return;
|
|
18991
19082
|
}
|
|
18992
|
-
await SessionManager
|
|
19083
|
+
await SessionManager.#setPickerCandidateStar(
|
|
18993
19084
|
session,
|
|
18994
19085
|
starred,
|
|
18995
19086
|
this.destination.kind === "explicit" ? this.destination.directory : undefined,
|
|
19087
|
+
this.#publishedSharedSession(session.id),
|
|
19088
|
+
);
|
|
19089
|
+
}
|
|
19090
|
+
|
|
19091
|
+
/**
|
|
19092
|
+
* Whether this manager ever published `sessionId` through shared admission, or has a
|
|
19093
|
+
* shared publication of it in flight. After `/new` such a predecessor may still be
|
|
19094
|
+
* live in a peer, so its star must follow the shared header-patch protocol (#7824).
|
|
19095
|
+
*/
|
|
19096
|
+
#publishedSharedSession(sessionId: string): boolean {
|
|
19097
|
+
return (
|
|
19098
|
+
this.#sharedAppendBarSessionIds.has(sessionId) ||
|
|
19099
|
+
this.#sharedRewriteBarSessionIds.has(sessionId) ||
|
|
19100
|
+
(this.#activeSharedMutationSessionCounts.get(sessionId) ?? 0) > 0 ||
|
|
19101
|
+
(SessionManager.#sharedPublicationsInFlight.get(sessionId) ?? 0) > 0
|
|
18996
19102
|
);
|
|
18997
19103
|
}
|
|
18998
19104
|
|
|
@@ -19105,6 +19211,21 @@ export class SessionManager {
|
|
|
19105
19211
|
session: SessionInfo,
|
|
19106
19212
|
starred: boolean,
|
|
19107
19213
|
explicitSessionDir?: string,
|
|
19214
|
+
): Promise<void> {
|
|
19215
|
+
await SessionManager.#setPickerCandidateStar(session, starred, explicitSessionDir, false);
|
|
19216
|
+
}
|
|
19217
|
+
|
|
19218
|
+
/**
|
|
19219
|
+
* Star a non-live picker candidate. A `shared` candidate (a predecessor this manager
|
|
19220
|
+
* published through shared admission) is patched only by an append under its managed
|
|
19221
|
+
* session transaction lease, like a shared title; a whole-transcript header upgrade
|
|
19222
|
+
* is refused because it would move a live peer's transcript identity.
|
|
19223
|
+
*/
|
|
19224
|
+
static async #setPickerCandidateStar(
|
|
19225
|
+
session: SessionInfo,
|
|
19226
|
+
starred: boolean,
|
|
19227
|
+
explicitSessionDir: string | undefined,
|
|
19228
|
+
shared: boolean,
|
|
19108
19229
|
): Promise<void> {
|
|
19109
19230
|
if (isStagedSessionPath(session.path)) throw new Error("Staged session paths are not resumable");
|
|
19110
19231
|
const directory = await fs.promises.realpath(path.dirname(session.path));
|
|
@@ -19125,6 +19246,23 @@ export class SessionManager {
|
|
|
19125
19246
|
)
|
|
19126
19247
|
throw new Error("Session is not an authorized managed candidate.");
|
|
19127
19248
|
}
|
|
19249
|
+
if (!shared) {
|
|
19250
|
+
SessionManager.#writePickerCandidateStar(session, starred, directory);
|
|
19251
|
+
return;
|
|
19252
|
+
}
|
|
19253
|
+
const locksDirectory = managedSessionTransactionLocksDirectory(directory);
|
|
19254
|
+
fs.mkdirSync(locksDirectory, { recursive: true, mode: 0o700 });
|
|
19255
|
+
await withManagedSessionTransaction({ locksDirectory, sessionId: session.id }, scope =>
|
|
19256
|
+
SessionManager.#writePickerCandidateStar(session, starred, directory, scope),
|
|
19257
|
+
);
|
|
19258
|
+
}
|
|
19259
|
+
|
|
19260
|
+
static #writePickerCandidateStar(
|
|
19261
|
+
session: SessionInfo,
|
|
19262
|
+
starred: boolean,
|
|
19263
|
+
directory: string,
|
|
19264
|
+
sharedScope?: ManagedSessionTransactionScope,
|
|
19265
|
+
): void {
|
|
19128
19266
|
const authority = new ManagedSessionDescendantStore(managedDirectoryRoot(directory), directory);
|
|
19129
19267
|
try {
|
|
19130
19268
|
const relativePath = path.basename(session.path);
|
|
@@ -19149,6 +19287,10 @@ export class SessionManager {
|
|
|
19149
19287
|
|
|
19150
19288
|
const patch = `${JSON.stringify({ type: "header_patch", patch: { starred } })}\n`;
|
|
19151
19289
|
const appendOnly = rawHeader.starredPatchVersion === 1 && Number(rawHeader.version) >= 4;
|
|
19290
|
+
if (sharedScope && !appendOnly)
|
|
19291
|
+
throw new Error(
|
|
19292
|
+
"Selected session is shared; shared session star requires an append-only header patch. Resume it to upgrade its format.",
|
|
19293
|
+
);
|
|
19152
19294
|
let bytes: Uint8Array;
|
|
19153
19295
|
if (appendOnly) {
|
|
19154
19296
|
bytes = Buffer.from(`${content.endsWith("\n") ? "" : "\n"}${patch}`);
|
|
@@ -19160,6 +19302,7 @@ export class SessionManager {
|
|
|
19160
19302
|
`${JSON.stringify(rawHeader)}\n${body}${body && !body.endsWith("\n") ? "\n" : ""}${patch}`,
|
|
19161
19303
|
);
|
|
19162
19304
|
}
|
|
19305
|
+
sharedScope?.assertOwned();
|
|
19163
19306
|
if (appendOnly) authority.appendExpectedIdentitySync(relativePath, bytes, snapshot.identity);
|
|
19164
19307
|
else authority.replaceExpectedIdentitySync(relativePath, bytes, snapshot.identity);
|
|
19165
19308
|
const committedDescriptor = authority.descriptorExpected(relativePath);
|
|
@@ -19318,7 +19461,6 @@ export class SessionManager {
|
|
|
19318
19461
|
this.#refreshManagedTranscriptRelocation();
|
|
19319
19462
|
const sessionFile = this.#sessionFile;
|
|
19320
19463
|
if (!sessionFile) return { kind: "rejected", error: new Error("shared_title_requires_session_file") };
|
|
19321
|
-
this.#sharedMutationSessionIds.add(sessionId);
|
|
19322
19464
|
const current = () =>
|
|
19323
19465
|
this.#sessionId === sessionId &&
|
|
19324
19466
|
this.#committedIdentityGeneration === identityGeneration &&
|
|
@@ -19327,10 +19469,10 @@ export class SessionManager {
|
|
|
19327
19469
|
const predecessor = this.#titleMutationTail;
|
|
19328
19470
|
const completion = Promise.withResolvers<void>();
|
|
19329
19471
|
this.#titleMutationTail = completion.promise;
|
|
19330
|
-
const publications = SessionManager.#sharedPublicationsInFlight;
|
|
19331
|
-
publications.set(sessionId, (publications.get(sessionId) ?? 0) + 1);
|
|
19332
19472
|
let result: SharedTitleOutcome;
|
|
19473
|
+
let releasePublication: (() => void) | undefined;
|
|
19333
19474
|
try {
|
|
19475
|
+
releasePublication = this.#enterSharedPublication(sessionId, { append: false, rewrite: false });
|
|
19334
19476
|
await predecessor;
|
|
19335
19477
|
if (!current()) return { kind: "skipped", reason: "stale" };
|
|
19336
19478
|
this.#assertRecoveryHydrationWritable();
|
|
@@ -19338,6 +19480,7 @@ export class SessionManager {
|
|
|
19338
19480
|
fs.mkdirSync(locksDirectory, { recursive: true, mode: 0o700 });
|
|
19339
19481
|
let attempted = false;
|
|
19340
19482
|
let predecessorIdentity: ManagedFileIdentity | undefined;
|
|
19483
|
+
let priorCommittedDigest: string | undefined;
|
|
19341
19484
|
let receipt: ManagedAppendReceipt | undefined;
|
|
19342
19485
|
let retainedFailure: Error | undefined;
|
|
19343
19486
|
const retainUnknown = (error: unknown): SharedTitleOutcome => {
|
|
@@ -19385,6 +19528,9 @@ export class SessionManager {
|
|
|
19385
19528
|
return { kind: "stale", reason: "unsupported_transcript" };
|
|
19386
19529
|
committedHeader = header;
|
|
19387
19530
|
predecessorIdentity = snapshot.identity;
|
|
19531
|
+
// The digest this manager last committed. Equal to the snapshot digest only
|
|
19532
|
+
// when no other opener advanced this transcript since.
|
|
19533
|
+
priorCommittedDigest = this.#managedPersistExpectedIdentity?.sha256 ?? this.#openCommittedDigest;
|
|
19388
19534
|
} else {
|
|
19389
19535
|
if (
|
|
19390
19536
|
this.#flushed ||
|
|
@@ -19463,6 +19609,18 @@ export class SessionManager {
|
|
|
19463
19609
|
this.#managedPersistExpectedIdentity = receipt.identity;
|
|
19464
19610
|
this.#openCommittedDigest = receipt.identity.sha256;
|
|
19465
19611
|
}
|
|
19612
|
+
// The snapshot branch imported only the header. Rewrite authority stays barred
|
|
19613
|
+
// only when the transcript already held a state this manager never committed:
|
|
19614
|
+
// renaming a transcript this manager wrote itself keeps full authority.
|
|
19615
|
+
//
|
|
19616
|
+
// Invariant behind not latching on the `unknown` outcome below: this latch only
|
|
19617
|
+
// runs after `result.kind === "committed"`. When the patch outcome is `unknown`,
|
|
19618
|
+
// rewrite authority is left open, so safety rests on the expected identity NOT
|
|
19619
|
+
// advancing: a later whole-graph write then fails the identity fence instead of
|
|
19620
|
+
// clobbering the sibling branch. Do not advance
|
|
19621
|
+
// `#managedPersistExpectedIdentity` on a non-committed title outcome.
|
|
19622
|
+
if (predecessorIdentity && predecessorIdentity.sha256 !== priorCommittedDigest)
|
|
19623
|
+
this.#latchSharedRewriteBar(sessionId);
|
|
19466
19624
|
if (!this.#flushed) {
|
|
19467
19625
|
this.#flushed = true;
|
|
19468
19626
|
this.#ensuredOnDisk = true;
|
|
@@ -19476,9 +19634,7 @@ export class SessionManager {
|
|
|
19476
19634
|
}
|
|
19477
19635
|
} finally {
|
|
19478
19636
|
completion.resolve();
|
|
19479
|
-
|
|
19480
|
-
if (remaining === 0) publications.delete(sessionId);
|
|
19481
|
-
else publications.set(sessionId, remaining);
|
|
19637
|
+
releasePublication?.();
|
|
19482
19638
|
}
|
|
19483
19639
|
if (result.kind === "committed") options?.onApplied?.(sanitized);
|
|
19484
19640
|
return result;
|
|
@@ -19803,6 +19959,18 @@ export class SessionManager {
|
|
|
19803
19959
|
this.#needsFullRewriteOnNextPersist = true;
|
|
19804
19960
|
throw nearLimit(liveBytesBefore);
|
|
19805
19961
|
}
|
|
19962
|
+
// A shared session bars the whole-transcript recovery rewrite. The append
|
|
19963
|
+
// cannot fit the cap and its only recovery is refused, which is exactly the
|
|
19964
|
+
// typed near-limit outcome: keep that contract (and its
|
|
19965
|
+
// SESSION_LIMIT_RECOVERY_ACTIONS guidance) instead of degrading into a
|
|
19966
|
+
// generic stale "rewrite required" abort.
|
|
19967
|
+
if (
|
|
19968
|
+
rewriteError instanceof SharedSessionMutationUnsupportedError ||
|
|
19969
|
+
rewriteError instanceof SharedAppendRewriteRequiredError
|
|
19970
|
+
) {
|
|
19971
|
+
this.#needsFullRewriteOnNextPersist = true;
|
|
19972
|
+
throw nearLimit(liveBytesBefore);
|
|
19973
|
+
}
|
|
19806
19974
|
throw rewriteError;
|
|
19807
19975
|
}
|
|
19808
19976
|
if (publishResumeBreadcrumb) writeTerminalBreadcrumb(this.cwd, this.#sessionFile);
|
|
@@ -19869,7 +20037,7 @@ export class SessionManager {
|
|
|
19869
20037
|
// Consume before preparation or callbacks can re-enter an append.
|
|
19870
20038
|
this.#sharedAppendEntryId = undefined;
|
|
19871
20039
|
} else {
|
|
19872
|
-
this.
|
|
20040
|
+
this.assertLegacyAppendAllowed("append entry");
|
|
19873
20041
|
}
|
|
19874
20042
|
this.#assertRecoveryHydrationWritable();
|
|
19875
20043
|
if (this.#sidecarBranchActivationDirty) this.#deactivateColdForBranchMutation();
|
|
@@ -20056,9 +20224,13 @@ export class SessionManager {
|
|
|
20056
20224
|
|
|
20057
20225
|
/** Append a configured fallback chain as child of current leaf, then advance leaf. Returns entry id. */
|
|
20058
20226
|
appendConfiguredModelChain(chain: ConfiguredModelChain): string {
|
|
20227
|
+
return this.#appendConfiguredModelChainWithId(chain, this.#generateEntryId());
|
|
20228
|
+
}
|
|
20229
|
+
|
|
20230
|
+
#appendConfiguredModelChainWithId(chain: ConfiguredModelChain, id: string): string {
|
|
20059
20231
|
const entry: ConfiguredModelChainEntry = {
|
|
20060
20232
|
type: "configured_model_chain",
|
|
20061
|
-
id
|
|
20233
|
+
id,
|
|
20062
20234
|
parentId: this.#leafId,
|
|
20063
20235
|
timestamp: new Date().toISOString(),
|
|
20064
20236
|
role: chain.role,
|
|
@@ -20087,7 +20259,7 @@ export class SessionManager {
|
|
|
20087
20259
|
| PythonExecutionMessage
|
|
20088
20260
|
| FileMentionMessage,
|
|
20089
20261
|
): string {
|
|
20090
|
-
this.
|
|
20262
|
+
this.assertLegacyAppendAllowed("append message");
|
|
20091
20263
|
return this.#appendMessageWithId(message, this.#generateEntryId());
|
|
20092
20264
|
}
|
|
20093
20265
|
|
|
@@ -20362,19 +20534,94 @@ export class SessionManager {
|
|
|
20362
20534
|
}
|
|
20363
20535
|
}
|
|
20364
20536
|
|
|
20537
|
+
/** Whether this logical session must keep using shared mutation admission. */
|
|
20538
|
+
requiresSharedMutationAdmission(): boolean {
|
|
20539
|
+
const sessionId = this.#sessionId;
|
|
20540
|
+
return (
|
|
20541
|
+
this.#sharedAppendBarSessionIds.has(sessionId) ||
|
|
20542
|
+
this.#sharedRewriteBarSessionIds.has(sessionId) ||
|
|
20543
|
+
(this.#activeSharedMutationSessionCounts.get(sessionId) ?? 0) > 0
|
|
20544
|
+
);
|
|
20545
|
+
}
|
|
20546
|
+
|
|
20365
20547
|
/** Refuse before caller-side agent, UI, settings, or external effects. */
|
|
20366
20548
|
assertLegacyMutationAllowed(operation: string): void {
|
|
20367
|
-
this.#assertLogicalSessionMutationAllowed(this.#sessionId, operation);
|
|
20549
|
+
this.#assertLogicalSessionMutationAllowed(this.#sessionId, operation, true);
|
|
20550
|
+
}
|
|
20551
|
+
|
|
20552
|
+
/** Additive legacy appends are safe once a control publication's transaction has settled. */
|
|
20553
|
+
assertLegacyAppendAllowed(operation: string): void {
|
|
20554
|
+
this.#assertLogicalSessionMutationAllowed(this.#sessionId, operation, false);
|
|
20555
|
+
}
|
|
20556
|
+
|
|
20557
|
+
#assertLogicalSessionMutationAllowed(sessionId: string, operation: string, includeRewrite: boolean): void {
|
|
20558
|
+
if ((this.#activeSharedMutationSessionCounts.get(sessionId) ?? 0) > 0)
|
|
20559
|
+
throw new SharedSessionMutationUnsupportedError(operation);
|
|
20560
|
+
if (this.#sharedAppendBarSessionIds.has(sessionId)) throw new SharedSessionMutationUnsupportedError(operation);
|
|
20561
|
+
if (includeRewrite && this.#sharedRewriteBarSessionIds.has(sessionId))
|
|
20562
|
+
throw new SharedSessionMutationUnsupportedError(operation);
|
|
20563
|
+
}
|
|
20564
|
+
|
|
20565
|
+
/**
|
|
20566
|
+
* Acquire one shared publication as a single token: the process-local
|
|
20567
|
+
* publication count, the in-flight mutation fence, and any permanent bars that
|
|
20568
|
+
* this publication must leave latched after it settles.
|
|
20569
|
+
*
|
|
20570
|
+
* Latch matrix:
|
|
20571
|
+
* - Canonical shared appends (`appendMessageSharingSession`,
|
|
20572
|
+
* `appendCustomMessageEntrySharingSession`, `appendCustomEntrySharingSession`,
|
|
20573
|
+
* `appendCompactionSharingSession`) latch the append and rewrite bars: they
|
|
20574
|
+
* publish this opener's own branch into a graph it did not import.
|
|
20575
|
+
* - One-shot control appends (`appendTemporaryModelChangeSharingSession`,
|
|
20576
|
+
* `appendThinkingLevelChangeSharingSession`,
|
|
20577
|
+
* `appendToolSelectionsSharingSession`) latch only rewrite authority: their
|
|
20578
|
+
* additive entries are safe to continue from, but the adopted transcript
|
|
20579
|
+
* identity is not.
|
|
20580
|
+
* - A title arms neither bar at acquisition. It latches rewrite authority from its
|
|
20581
|
+
* commit path (`#latchSharedRewriteBar`) only when it adopted an existing
|
|
20582
|
+
* transcript, because the latch must be deferred until the patch is durable.
|
|
20583
|
+
*
|
|
20584
|
+
* Both bars latch at entry, not at commit: a publication that is later refused
|
|
20585
|
+
* (`stale`, `rejected`, superseded, or a pre-write failure) still leaves its bars
|
|
20586
|
+
* latched for the manager's lifetime. That is deliberate — the bar reasons about
|
|
20587
|
+
* "this manager re-anchored to an identity it does not own", which a refused
|
|
20588
|
+
* attempt cannot rule out, and the in-flight count is what covers the window
|
|
20589
|
+
* before the outcome is known. Over-blocking is the safe direction; no caller may
|
|
20590
|
+
* rely on a refused publication leaving admission open.
|
|
20591
|
+
*/
|
|
20592
|
+
#enterSharedPublication(sessionId: string, latch: { append: boolean; rewrite: boolean }): () => void {
|
|
20593
|
+
const publications = SessionManager.#sharedPublicationsInFlight;
|
|
20594
|
+
publications.set(sessionId, (publications.get(sessionId) ?? 0) + 1);
|
|
20595
|
+
const counts = this.#activeSharedMutationSessionCounts;
|
|
20596
|
+
counts.set(sessionId, (counts.get(sessionId) ?? 0) + 1);
|
|
20597
|
+
if (latch.append) this.#sharedAppendBarSessionIds.add(sessionId);
|
|
20598
|
+
if (latch.rewrite) this.#latchSharedRewriteBar(sessionId);
|
|
20599
|
+
let released = false;
|
|
20600
|
+
return () => {
|
|
20601
|
+
if (released) return;
|
|
20602
|
+
released = true;
|
|
20603
|
+
const remaining = (counts.get(sessionId) ?? 1) - 1;
|
|
20604
|
+
if (remaining === 0) counts.delete(sessionId);
|
|
20605
|
+
else counts.set(sessionId, remaining);
|
|
20606
|
+
const remainingPublications = (publications.get(sessionId) ?? 1) - 1;
|
|
20607
|
+
if (remainingPublications === 0) publications.delete(sessionId);
|
|
20608
|
+
else publications.set(sessionId, remainingPublications);
|
|
20609
|
+
};
|
|
20368
20610
|
}
|
|
20369
20611
|
|
|
20370
|
-
|
|
20371
|
-
|
|
20612
|
+
/**
|
|
20613
|
+
* The only writer of {@link #sharedRewriteBarSessionIds}. Used by
|
|
20614
|
+
* `#enterSharedPublication` for publications that arm before they write, and by a
|
|
20615
|
+
* title's commit path, which must defer the latch until its patch is durable.
|
|
20616
|
+
*/
|
|
20617
|
+
#latchSharedRewriteBar(sessionId: string): void {
|
|
20618
|
+
this.#sharedRewriteBarSessionIds.add(sessionId);
|
|
20372
20619
|
}
|
|
20373
20620
|
|
|
20374
20621
|
#assertPreparedGraphPublicationAllowed(stage: PreparedNewSessionState): void {
|
|
20375
20622
|
const sourceId = this.#preparedGraphSourceIds.get(stage);
|
|
20376
20623
|
if (sourceId !== undefined)
|
|
20377
|
-
this.#assertLogicalSessionMutationAllowed(sourceId, "publish prepared graph successor");
|
|
20624
|
+
this.#assertLogicalSessionMutationAllowed(sourceId, "publish prepared graph successor", true);
|
|
20378
20625
|
}
|
|
20379
20626
|
|
|
20380
20627
|
#assertDiscardTranscriptAllowed(bytes: Buffer): void {
|
|
@@ -20384,7 +20631,7 @@ export class SessionManager {
|
|
|
20384
20631
|
) as Partial<SessionHeader>;
|
|
20385
20632
|
if (header.type !== "session" || typeof header.id !== "string")
|
|
20386
20633
|
throw new Error("Uncommitted session discard requires a valid transcript header.");
|
|
20387
|
-
this.#assertLogicalSessionMutationAllowed(header.id, "discard uncommitted session");
|
|
20634
|
+
this.#assertLogicalSessionMutationAllowed(header.id, "discard uncommitted session", true);
|
|
20388
20635
|
}
|
|
20389
20636
|
|
|
20390
20637
|
/**
|
|
@@ -20427,7 +20674,7 @@ export class SessionManager {
|
|
|
20427
20674
|
model: string,
|
|
20428
20675
|
thinking: { readonly level: string | undefined } | undefined,
|
|
20429
20676
|
isCurrent: () => boolean,
|
|
20430
|
-
): Promise<
|
|
20677
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
20431
20678
|
return this.#publishOwnedEntriesSharingSession(
|
|
20432
20679
|
thinking ? 2 : 1,
|
|
20433
20680
|
(index, id) =>
|
|
@@ -20437,9 +20684,105 @@ export class SessionManager {
|
|
|
20437
20684
|
undefined,
|
|
20438
20685
|
isCurrent,
|
|
20439
20686
|
true,
|
|
20687
|
+
true,
|
|
20440
20688
|
);
|
|
20441
20689
|
}
|
|
20442
20690
|
|
|
20691
|
+
/** Publish ordered profile entries under one managed lease at this opener's branch cursor. */
|
|
20692
|
+
async appendModelProfileActivationSharingSession(
|
|
20693
|
+
plan: ModelProfileTranscriptPlan,
|
|
20694
|
+
isCurrent: () => boolean,
|
|
20695
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
20696
|
+
const entries: SharedControlEntry[] = [];
|
|
20697
|
+
if (plan.configuredDefaultChain !== undefined)
|
|
20698
|
+
entries.push({ type: "configured_model_chain", chain: plan.configuredDefaultChain });
|
|
20699
|
+
if (plan.temporaryModel !== undefined)
|
|
20700
|
+
entries.push({ type: "model_change", model: plan.temporaryModel, role: "temporary" });
|
|
20701
|
+
if (plan.thinking !== undefined)
|
|
20702
|
+
entries.push({ type: "thinking_level_change", level: plan.thinking.level, operatorIntent: false });
|
|
20703
|
+
if (plan.resumeDefault !== undefined) {
|
|
20704
|
+
const selector = plan.resumeDefault.selector;
|
|
20705
|
+
entries.push(
|
|
20706
|
+
selector === undefined
|
|
20707
|
+
? { type: "model_role_clear", role: "default" }
|
|
20708
|
+
: { type: "model_change", model: selector, role: "default" },
|
|
20709
|
+
);
|
|
20710
|
+
}
|
|
20711
|
+
return this.appendControlEntriesSharingSession(entries, isCurrent);
|
|
20712
|
+
}
|
|
20713
|
+
|
|
20714
|
+
/** Publish changed service-tier intent, or validate admission for an unchanged-tier rearm. */
|
|
20715
|
+
async appendServiceTierChangeSharingSession(
|
|
20716
|
+
serviceTier: ServiceTier | null,
|
|
20717
|
+
appendEntry: boolean,
|
|
20718
|
+
isCurrent: () => boolean,
|
|
20719
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
20720
|
+
return this.appendControlEntriesSharingSession(
|
|
20721
|
+
appendEntry ? [{ type: "service_tier_change", serviceTier }] : [],
|
|
20722
|
+
isCurrent,
|
|
20723
|
+
);
|
|
20724
|
+
}
|
|
20725
|
+
|
|
20726
|
+
/**
|
|
20727
|
+
* The common admitted publication for session controls once a session publishes
|
|
20728
|
+
* through the shared transaction (#7823, #7824).
|
|
20729
|
+
*
|
|
20730
|
+
* Every entry is a child of this opener's validated cursor and is written in order
|
|
20731
|
+
* under one managed lease; the transcript is never rewritten and an unseen sibling
|
|
20732
|
+
* branch is never followed. An empty list validates admission and currentness without
|
|
20733
|
+
* writing. Inside {@link withSharedThinkingControl} the active owner is consumed, so
|
|
20734
|
+
* one owned control scope admits exactly one publication.
|
|
20735
|
+
*
|
|
20736
|
+
* Control appends latch only rewrite authority (see {@link #enterSharedPublication}):
|
|
20737
|
+
* their additive entries are safe to continue from, the adopted identity is not.
|
|
20738
|
+
*/
|
|
20739
|
+
async appendControlEntriesSharingSession(
|
|
20740
|
+
entries: readonly SharedControlEntry[],
|
|
20741
|
+
isCurrent: () => boolean,
|
|
20742
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
20743
|
+
const snapshot = entries.map(entry => structuredClone(entry));
|
|
20744
|
+
// A new root mid-publication would orphan the entries before it from the branch.
|
|
20745
|
+
if (snapshot.some((entry, index) => entry.type === "context_clear" && index > 0))
|
|
20746
|
+
return { kind: "rejected", error: new Error("shared_control_context_clear_must_be_first") };
|
|
20747
|
+
const owner = SessionManager.#thinkingControlOwner.getStore();
|
|
20748
|
+
if (owner) {
|
|
20749
|
+
if (!owner.active || owner.used || owner.manager !== this || owner.sessionId !== this.#sessionId)
|
|
20750
|
+
return { kind: "rejected", error: new Error("shared_thinking_control_owner_required") };
|
|
20751
|
+
owner.used = true;
|
|
20752
|
+
}
|
|
20753
|
+
return this.#publishOwnedEntriesSharingSession(
|
|
20754
|
+
snapshot.length,
|
|
20755
|
+
(index, id) => {
|
|
20756
|
+
const entry = snapshot[index];
|
|
20757
|
+
if (!entry) throw new Error("shared_control_invalid_entry_index");
|
|
20758
|
+
return this.#appendSharedControlEntryWithId(entry, id);
|
|
20759
|
+
},
|
|
20760
|
+
owner,
|
|
20761
|
+
isCurrent,
|
|
20762
|
+
true,
|
|
20763
|
+
true,
|
|
20764
|
+
);
|
|
20765
|
+
}
|
|
20766
|
+
|
|
20767
|
+
#appendSharedControlEntryWithId(entry: SharedControlEntry, id: string): string {
|
|
20768
|
+
switch (entry.type) {
|
|
20769
|
+
case "configured_model_chain":
|
|
20770
|
+
return this.#appendConfiguredModelChainWithId(entry.chain, id);
|
|
20771
|
+
case "model_change":
|
|
20772
|
+
return this.#appendModelChangeWithId(entry.model, entry.role, id, entry.metadata);
|
|
20773
|
+
case "model_role_clear":
|
|
20774
|
+
return this.#clearModelRoleWithId(entry.role, id);
|
|
20775
|
+
case "thinking_level_change":
|
|
20776
|
+
return this.#appendThinkingLevelChangeWithId(entry.level, entry.operatorIntent, id);
|
|
20777
|
+
case "service_tier_change":
|
|
20778
|
+
return this.#appendServiceTierChangeWithId(entry.serviceTier, id);
|
|
20779
|
+
case "custom":
|
|
20780
|
+
return this.#appendCustomEntryWithId(entry.customType, entry.data, id);
|
|
20781
|
+
case "context_clear":
|
|
20782
|
+
return this.#appendContextClearRootWithId(entry.data, id);
|
|
20783
|
+
}
|
|
20784
|
+
}
|
|
20785
|
+
|
|
20443
20786
|
/** Publish a compaction at this opener's branch cursor without rewriting peer history. */
|
|
20444
20787
|
async appendCompactionSharingSession<T = unknown>(
|
|
20445
20788
|
payload: Omit<CompactionEntry<T>, "type" | "id" | "parentId" | "timestamp">,
|
|
@@ -20466,6 +20809,7 @@ export class SessionManager {
|
|
|
20466
20809
|
id => this.#appendThinkingLevelChangeWithId(thinkingLevel, operatorIntent, id),
|
|
20467
20810
|
owner,
|
|
20468
20811
|
isCurrent,
|
|
20812
|
+
true,
|
|
20469
20813
|
);
|
|
20470
20814
|
}
|
|
20471
20815
|
|
|
@@ -20473,12 +20817,15 @@ export class SessionManager {
|
|
|
20473
20817
|
appendWithId: (id: string) => string,
|
|
20474
20818
|
thinkingOwner?: { manager: SessionManager; sessionId: string; active: boolean; used: boolean },
|
|
20475
20819
|
isCurrent?: () => boolean,
|
|
20820
|
+
scopedAppendAdmission = false,
|
|
20476
20821
|
): Promise<SharedAppendOutcome> {
|
|
20477
20822
|
const outcome = await this.#publishOwnedEntriesSharingSession(
|
|
20478
20823
|
1,
|
|
20479
20824
|
(_, id) => appendWithId(id),
|
|
20480
20825
|
thinkingOwner,
|
|
20481
20826
|
isCurrent,
|
|
20827
|
+
false,
|
|
20828
|
+
scopedAppendAdmission,
|
|
20482
20829
|
);
|
|
20483
20830
|
if (outcome.kind === "committed") return { kind: "committed", id: outcome.ids[0]! };
|
|
20484
20831
|
if (outcome.kind === "unknown") return { kind: "unknown", id: outcome.ids[0]!, error: outcome.error };
|
|
@@ -20486,12 +20833,13 @@ export class SessionManager {
|
|
|
20486
20833
|
}
|
|
20487
20834
|
|
|
20488
20835
|
async #publishOwnedEntriesSharingSession(
|
|
20489
|
-
count:
|
|
20836
|
+
count: number,
|
|
20490
20837
|
appendWithId: (index: number, id: string) => string,
|
|
20491
20838
|
thinkingOwner?: { manager: SessionManager; sessionId: string; active: boolean; used: boolean },
|
|
20492
20839
|
isCurrent?: () => boolean,
|
|
20493
|
-
|
|
20494
|
-
|
|
20840
|
+
controlOperation = false,
|
|
20841
|
+
scopedAppendAdmission = false,
|
|
20842
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
20495
20843
|
if (this.destination.kind !== "managed")
|
|
20496
20844
|
return { kind: "rejected", error: new Error("shared_append_requires_managed_destination") };
|
|
20497
20845
|
const sessionId = this.#sessionId;
|
|
@@ -20509,8 +20857,6 @@ export class SessionManager {
|
|
|
20509
20857
|
) {
|
|
20510
20858
|
return { kind: "rejected", error: new Error("shared_append_durable_thinking_control_in_flight") };
|
|
20511
20859
|
}
|
|
20512
|
-
const publications = SessionManager.#sharedPublicationsInFlight;
|
|
20513
|
-
publications.set(sessionId, (publications.get(sessionId) ?? 0) + 1);
|
|
20514
20860
|
const ownedPublications = SessionManager.#ownedThinkingPublicationsInFlight;
|
|
20515
20861
|
if (thinkingOwner) ownedPublications.set(sessionId, (ownedPublications.get(sessionId) ?? 0) + 1);
|
|
20516
20862
|
try {
|
|
@@ -20519,12 +20865,10 @@ export class SessionManager {
|
|
|
20519
20865
|
appendWithId,
|
|
20520
20866
|
thinkingOwner,
|
|
20521
20867
|
isCurrent,
|
|
20522
|
-
|
|
20868
|
+
controlOperation,
|
|
20869
|
+
scopedAppendAdmission,
|
|
20523
20870
|
);
|
|
20524
20871
|
} finally {
|
|
20525
|
-
const remaining = publications.get(sessionId)! - 1;
|
|
20526
|
-
if (remaining === 0) publications.delete(sessionId);
|
|
20527
|
-
else publications.set(sessionId, remaining);
|
|
20528
20872
|
if (thinkingOwner) {
|
|
20529
20873
|
const remainingOwned = ownedPublications.get(sessionId)! - 1;
|
|
20530
20874
|
if (remainingOwned === 0) ownedPublications.delete(sessionId);
|
|
@@ -20534,26 +20878,25 @@ export class SessionManager {
|
|
|
20534
20878
|
}
|
|
20535
20879
|
|
|
20536
20880
|
async #appendEntrySharingSession(
|
|
20537
|
-
count:
|
|
20881
|
+
count: number,
|
|
20538
20882
|
appendWithId: (index: number, id: string) => string,
|
|
20539
20883
|
thinkingOwner?: { manager: SessionManager; sessionId: string; active: boolean; used: boolean },
|
|
20540
20884
|
isCurrent?: () => boolean,
|
|
20541
|
-
|
|
20542
|
-
|
|
20885
|
+
controlOperation = false,
|
|
20886
|
+
scopedAppendAdmission = false,
|
|
20887
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
20543
20888
|
this.#refreshManagedTranscriptRelocation();
|
|
20544
20889
|
const sessionFile = this.#sessionFile;
|
|
20545
20890
|
if (!sessionFile) return { kind: "rejected", error: new Error("shared_append_requires_session_file") };
|
|
20546
20891
|
const sessionId = this.#sessionId;
|
|
20547
|
-
// Arm before lease acquisition; waiting callbacks receive no mutation admission.
|
|
20548
|
-
this.#sharedMutationSessionIds.add(sessionId);
|
|
20549
20892
|
const locksDirectory = managedSessionTransactionLocksDirectory(path.dirname(sessionFile));
|
|
20550
|
-
|
|
20893
|
+
let releasePublication: (() => void) | undefined;
|
|
20551
20894
|
let ids: string[] = [];
|
|
20552
20895
|
let attempted = 0;
|
|
20553
|
-
const unknown = (error: unknown):
|
|
20896
|
+
const unknown = (error: unknown): SharedEntriesAppendOutcome => {
|
|
20554
20897
|
const outcome = { kind: "unknown" as const, ids: [...ids], error };
|
|
20555
|
-
if (
|
|
20556
|
-
const retained = new Error("Shared
|
|
20898
|
+
if (controlOperation) {
|
|
20899
|
+
const retained = new Error("Shared control publication outcome is unknown", { cause: outcome });
|
|
20557
20900
|
// A synchronous append may already have latched the raw failure. Retain
|
|
20558
20901
|
// it in the outcome and preserve the full operation receipt on close.
|
|
20559
20902
|
if (this.#persistError) this.#persistError = retained;
|
|
@@ -20569,42 +20912,141 @@ export class SessionManager {
|
|
|
20569
20912
|
ids.push(id);
|
|
20570
20913
|
}
|
|
20571
20914
|
};
|
|
20572
|
-
|
|
20573
|
-
|
|
20574
|
-
|
|
20575
|
-
|
|
20576
|
-
|
|
20577
|
-
|
|
20578
|
-
|
|
20579
|
-
|
|
20580
|
-
|
|
20581
|
-
|
|
20582
|
-
|
|
20583
|
-
|
|
20584
|
-
|
|
20585
|
-
|
|
20586
|
-
|
|
20587
|
-
|
|
20588
|
-
|
|
20589
|
-
|
|
20590
|
-
|
|
20591
|
-
|
|
20592
|
-
|
|
20593
|
-
|
|
20594
|
-
|
|
20595
|
-
|
|
20596
|
-
|
|
20597
|
-
|
|
20598
|
-
|
|
20599
|
-
|
|
20600
|
-
|
|
20601
|
-
if (
|
|
20602
|
-
|
|
20603
|
-
|
|
20604
|
-
|
|
20605
|
-
|
|
20606
|
-
|
|
20607
|
-
if (
|
|
20915
|
+
try {
|
|
20916
|
+
// Arm before lease acquisition; waiting callbacks receive no mutation admission.
|
|
20917
|
+
releasePublication = this.#enterSharedPublication(sessionId, {
|
|
20918
|
+
append: !scopedAppendAdmission,
|
|
20919
|
+
rewrite: true,
|
|
20920
|
+
});
|
|
20921
|
+
fs.mkdirSync(locksDirectory, { recursive: true, mode: 0o700 });
|
|
20922
|
+
const publication = withManagedSessionTransaction<SharedEntriesAppendOutcome>(
|
|
20923
|
+
{ locksDirectory, sessionId: this.#sessionId },
|
|
20924
|
+
async scope => {
|
|
20925
|
+
scope.assertOwned();
|
|
20926
|
+
if (!thinkingOwner && isCurrent?.() === false)
|
|
20927
|
+
return {
|
|
20928
|
+
kind: "rejected",
|
|
20929
|
+
error: new Error(
|
|
20930
|
+
controlOperation ? "shared_model_control_superseded" : "shared_compaction_superseded",
|
|
20931
|
+
),
|
|
20932
|
+
};
|
|
20933
|
+
if (
|
|
20934
|
+
thinkingOwner &&
|
|
20935
|
+
(!thinkingOwner.active ||
|
|
20936
|
+
thinkingOwner.manager !== this ||
|
|
20937
|
+
thinkingOwner.sessionId !== sessionId ||
|
|
20938
|
+
SessionManager.#thinkingControlOwner.getStore() !== thinkingOwner ||
|
|
20939
|
+
!isCurrent?.())
|
|
20940
|
+
)
|
|
20941
|
+
return { kind: "rejected", error: new Error("shared_thinking_control_superseded") };
|
|
20942
|
+
// A latched failure means every later persist throws the same error, so the only
|
|
20943
|
+
// honest answer is that this process has to reopen.
|
|
20944
|
+
if (this.#persistError) return { kind: "stale", reason: "persistence_latched" };
|
|
20945
|
+
this.#refreshManagedTranscriptRelocation();
|
|
20946
|
+
if (this.#sessionFile !== sessionFile || this.#sessionId !== sessionId)
|
|
20947
|
+
return { kind: "stale", reason: "transcript_moved" };
|
|
20948
|
+
// Historical rewrite debt is never first-publication authority.
|
|
20949
|
+
if (this.#needsFullRewriteOnNextPersist) return { kind: "stale", reason: "rewrite_required" };
|
|
20950
|
+
if (!this.#flushed) {
|
|
20951
|
+
if (
|
|
20952
|
+
!this.persist ||
|
|
20953
|
+
this.#readOnlyResume ||
|
|
20954
|
+
this.#ensuredOnDisk ||
|
|
20955
|
+
this.#managedPersistExpectedIdentity
|
|
20956
|
+
)
|
|
20957
|
+
return { kind: "stale", reason: "rewrite_required" };
|
|
20958
|
+
const store = this.#managedTranscriptStore(sessionFile);
|
|
20959
|
+
const name = path.basename(sessionFile);
|
|
20960
|
+
store.assertBound();
|
|
20961
|
+
// Prove absence through retained authority; never adopt an unexpected file.
|
|
20962
|
+
if (store.readExpected(name) !== null) return { kind: "stale", reason: "transcript_moved" };
|
|
20963
|
+
if (isCurrent?.() === false)
|
|
20964
|
+
return {
|
|
20965
|
+
kind: "rejected",
|
|
20966
|
+
error: new Error(
|
|
20967
|
+
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
20968
|
+
),
|
|
20969
|
+
};
|
|
20970
|
+
// An empty control validates admission without publishing pending metadata.
|
|
20971
|
+
if (count === 0) return { kind: "committed", ids: [] };
|
|
20972
|
+
allocateIds();
|
|
20973
|
+
try {
|
|
20974
|
+
// No await from staging through publication: keep the local leaf and
|
|
20975
|
+
// pending metadata together, without changing normal sync append behavior.
|
|
20976
|
+
this.#sharedBootstrapStaging = true;
|
|
20977
|
+
try {
|
|
20978
|
+
for (let index = 0; index < ids.length; index++) {
|
|
20979
|
+
if (isCurrent?.() === false)
|
|
20980
|
+
throw new Error(
|
|
20981
|
+
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
20982
|
+
);
|
|
20983
|
+
this.#sharedAppendEntryId = ids[index];
|
|
20984
|
+
attempted++;
|
|
20985
|
+
appendWithId(index, ids[index]!);
|
|
20986
|
+
}
|
|
20987
|
+
} finally {
|
|
20988
|
+
this.#sharedAppendEntryId = undefined;
|
|
20989
|
+
this.#sharedBootstrapStaging = false;
|
|
20990
|
+
}
|
|
20991
|
+
const entries = materializeResidentEntriesForPersistenceSync(
|
|
20992
|
+
this.#fileEntries,
|
|
20993
|
+
this.#residentBlobStores(),
|
|
20994
|
+
).map(entry => prepareEntryForPersistenceSync(entry, this.#blobStore));
|
|
20995
|
+
const bytes = Buffer.from(`${entries.map(entry => JSON.stringify(entry)).join("\n")}\n`, "utf8");
|
|
20996
|
+
scope.assertOwned();
|
|
20997
|
+
store.assertBound();
|
|
20998
|
+
store.publishNoReplaceSync(name, bytes);
|
|
20999
|
+
const published = store.readExpected(name);
|
|
21000
|
+
if (!published?.bytes.equals(bytes)) throw new Error("durability_unproven");
|
|
21001
|
+
this.#managedPersistExpectedIdentity = published.identity;
|
|
21002
|
+
this.#openCommittedDigest = published.identity.sha256;
|
|
21003
|
+
this.#flushed = true;
|
|
21004
|
+
this.#ensuredOnDisk = true;
|
|
21005
|
+
if (this.#effectiveSessionMemoryMode() !== "off") {
|
|
21006
|
+
this.#buildDisposableSidecars(this.#fileEntries);
|
|
21007
|
+
if (this.#effectiveSessionMemoryMode() === "enabled") this.#retireColdEntries();
|
|
21008
|
+
}
|
|
21009
|
+
return { kind: "committed", ids };
|
|
21010
|
+
} catch (error) {
|
|
21011
|
+
// Retain original identities without retrying or authorizing a rewrite.
|
|
21012
|
+
this.#recordPersistError(error);
|
|
21013
|
+
return unknown(error);
|
|
21014
|
+
}
|
|
21015
|
+
}
|
|
21016
|
+
const read = await this.captureCommittedSnapshot();
|
|
21017
|
+
if (read.kind === "unsupported") return { kind: "stale", reason: "unsupported_transcript" };
|
|
21018
|
+
if (read.kind !== "snapshot" || read.snapshot.sessionId !== this.#sessionId)
|
|
21019
|
+
return { kind: "stale", reason: "transcript_moved" };
|
|
21020
|
+
const cursor = this.#leafId;
|
|
21021
|
+
// The entry this append is a child of has to still be part of the committed graph;
|
|
21022
|
+
// otherwise this process is about to graft onto state nobody else has.
|
|
21023
|
+
if (cursor !== null && !read.snapshot.entryIds.includes(cursor))
|
|
21024
|
+
return { kind: "stale", reason: "cursor_not_committed" };
|
|
21025
|
+
// Adopt the transcript as it stands: another opener may have appended since this
|
|
21026
|
+
// process last wrote, and the append fence compares against this identity.
|
|
21027
|
+
// Bind the fence to the bytes that were just checked, and only those: a writer
|
|
21028
|
+
// outside the lease can replace the file between the read and here.
|
|
21029
|
+
try {
|
|
21030
|
+
const identity = this.#captureManagedPersistIdentity(sessionFile);
|
|
21031
|
+
if (identity.sha256 !== read.snapshot.digest) return { kind: "stale", reason: "transcript_moved" };
|
|
21032
|
+
this.#managedPersistExpectedIdentity = identity;
|
|
21033
|
+
this.#openCommittedDigest ??= read.snapshot.digest;
|
|
21034
|
+
} catch {
|
|
21035
|
+
return { kind: "stale", reason: "transcript_moved" };
|
|
21036
|
+
}
|
|
21037
|
+
allocateIds();
|
|
21038
|
+
// An invalid cold index can hydrate the authoritative transcript while generating
|
|
21039
|
+
// an ID. Hydration adopts its physical tail; shared publication must keep this
|
|
21040
|
+
// opener's already-validated branch cursor instead.
|
|
21041
|
+
if (this.#sessionFile !== sessionFile || this.#sessionId !== sessionId)
|
|
21042
|
+
return { kind: "stale", reason: "transcript_moved" };
|
|
21043
|
+
if (this.#needsFullRewriteOnNextPersist) return { kind: "stale", reason: "rewrite_required" };
|
|
21044
|
+
if (this.#leafId !== cursor) {
|
|
21045
|
+
if (cursor !== null && !this.#byId.has(cursor))
|
|
21046
|
+
return { kind: "stale", reason: "cursor_not_committed" };
|
|
21047
|
+
this.#leafId = cursor;
|
|
21048
|
+
this.#leafRevision++;
|
|
21049
|
+
}
|
|
20608
21050
|
if (isCurrent?.() === false)
|
|
20609
21051
|
return {
|
|
20610
21052
|
kind: "rejected",
|
|
@@ -20612,137 +21054,58 @@ export class SessionManager {
|
|
|
20612
21054
|
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
20613
21055
|
),
|
|
20614
21056
|
};
|
|
20615
|
-
|
|
21057
|
+
// An empty control validates admission and currentness without appending.
|
|
21058
|
+
if (count === 0) return { kind: "committed", ids: [] };
|
|
21059
|
+
this.#sharedAppendOnly = true;
|
|
20616
21060
|
try {
|
|
20617
|
-
|
|
20618
|
-
|
|
20619
|
-
|
|
20620
|
-
|
|
20621
|
-
|
|
20622
|
-
if (
|
|
20623
|
-
|
|
20624
|
-
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
20625
|
-
);
|
|
20626
|
-
this.#sharedAppendEntryId = ids[index];
|
|
20627
|
-
attempted++;
|
|
20628
|
-
appendWithId(index, ids[index]!);
|
|
21061
|
+
for (let index = 0; index < ids.length; index++) {
|
|
21062
|
+
if (isCurrent?.() === false) {
|
|
21063
|
+
const error = new Error(
|
|
21064
|
+
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
21065
|
+
);
|
|
21066
|
+
if (attempted > 0) return unknown(error);
|
|
21067
|
+
return { kind: "rejected", error };
|
|
20629
21068
|
}
|
|
20630
|
-
|
|
20631
|
-
|
|
20632
|
-
|
|
20633
|
-
}
|
|
20634
|
-
const entries = materializeResidentEntriesForPersistenceSync(
|
|
20635
|
-
this.#fileEntries,
|
|
20636
|
-
this.#residentBlobStores(),
|
|
20637
|
-
).map(entry => prepareEntryForPersistenceSync(entry, this.#blobStore));
|
|
20638
|
-
const bytes = Buffer.from(`${entries.map(entry => JSON.stringify(entry)).join("\n")}\n`, "utf8");
|
|
20639
|
-
scope.assertOwned();
|
|
20640
|
-
store.assertBound();
|
|
20641
|
-
store.publishNoReplaceSync(name, bytes);
|
|
20642
|
-
const published = store.readExpected(name);
|
|
20643
|
-
if (!published?.bytes.equals(bytes)) throw new Error("durability_unproven");
|
|
20644
|
-
this.#managedPersistExpectedIdentity = published.identity;
|
|
20645
|
-
this.#openCommittedDigest = published.identity.sha256;
|
|
20646
|
-
this.#flushed = true;
|
|
20647
|
-
this.#ensuredOnDisk = true;
|
|
20648
|
-
if (this.#effectiveSessionMemoryMode() !== "off") {
|
|
20649
|
-
this.#buildDisposableSidecars(this.#fileEntries);
|
|
20650
|
-
if (this.#effectiveSessionMemoryMode() === "enabled") this.#retireColdEntries();
|
|
21069
|
+
this.#sharedAppendEntryId = ids[index];
|
|
21070
|
+
attempted++;
|
|
21071
|
+
appendWithId(index, ids[index]!);
|
|
20651
21072
|
}
|
|
20652
|
-
return { kind: "committed", ids };
|
|
20653
21073
|
} catch (error) {
|
|
20654
|
-
|
|
20655
|
-
|
|
21074
|
+
if (attempted > 1) return unknown(error);
|
|
21075
|
+
if (error instanceof SharedAppendRewriteRequiredError)
|
|
21076
|
+
return { kind: "stale", reason: "rewrite_required" };
|
|
21077
|
+
if (error instanceof ManagedAppendIdentityMismatchError)
|
|
21078
|
+
return { kind: "stale", reason: "transcript_moved" };
|
|
21079
|
+
const outcome = classifyAppendFailure(error);
|
|
21080
|
+
if (outcome.kind === "not_committed") return { kind: "rejected", error };
|
|
20656
21081
|
return unknown(error);
|
|
21082
|
+
} finally {
|
|
21083
|
+
this.#sharedAppendEntryId = undefined;
|
|
21084
|
+
this.#sharedAppendOnly = false;
|
|
20657
21085
|
}
|
|
20658
|
-
|
|
20659
|
-
|
|
20660
|
-
|
|
20661
|
-
|
|
20662
|
-
|
|
20663
|
-
|
|
20664
|
-
|
|
20665
|
-
|
|
20666
|
-
|
|
20667
|
-
|
|
20668
|
-
|
|
20669
|
-
|
|
20670
|
-
|
|
20671
|
-
|
|
20672
|
-
|
|
20673
|
-
|
|
20674
|
-
|
|
20675
|
-
|
|
20676
|
-
|
|
20677
|
-
|
|
20678
|
-
|
|
20679
|
-
|
|
20680
|
-
|
|
20681
|
-
// An invalid cold index can hydrate the authoritative transcript while generating
|
|
20682
|
-
// an ID. Hydration adopts its physical tail; shared publication must keep this
|
|
20683
|
-
// opener's already-validated branch cursor instead.
|
|
20684
|
-
if (this.#sessionFile !== sessionFile || this.#sessionId !== sessionId)
|
|
20685
|
-
return { kind: "stale", reason: "transcript_moved" };
|
|
20686
|
-
if (this.#needsFullRewriteOnNextPersist) return { kind: "stale", reason: "rewrite_required" };
|
|
20687
|
-
if (this.#leafId !== cursor) {
|
|
20688
|
-
if (cursor !== null && !this.#byId.has(cursor)) return { kind: "stale", reason: "cursor_not_committed" };
|
|
20689
|
-
this.#leafId = cursor;
|
|
20690
|
-
this.#leafRevision++;
|
|
20691
|
-
}
|
|
20692
|
-
if (isCurrent?.() === false)
|
|
20693
|
-
return {
|
|
20694
|
-
kind: "rejected",
|
|
20695
|
-
error: new Error(
|
|
20696
|
-
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
20697
|
-
),
|
|
20698
|
-
};
|
|
20699
|
-
this.#sharedAppendOnly = true;
|
|
20700
|
-
try {
|
|
20701
|
-
for (let index = 0; index < ids.length; index++) {
|
|
20702
|
-
if (isCurrent?.() === false) {
|
|
20703
|
-
const error = new Error(
|
|
20704
|
-
thinkingOwner ? "shared_thinking_control_superseded" : "shared_publication_superseded",
|
|
20705
|
-
);
|
|
20706
|
-
if (attempted > 0) return unknown(error);
|
|
20707
|
-
return { kind: "rejected", error };
|
|
20708
|
-
}
|
|
20709
|
-
this.#sharedAppendEntryId = ids[index];
|
|
20710
|
-
attempted++;
|
|
20711
|
-
appendWithId(index, ids[index]!);
|
|
20712
|
-
}
|
|
20713
|
-
} catch (error) {
|
|
20714
|
-
if (attempted > 1) return unknown(error);
|
|
20715
|
-
if (error instanceof SharedAppendRewriteRequiredError)
|
|
20716
|
-
return { kind: "stale", reason: "rewrite_required" };
|
|
20717
|
-
if (error instanceof ManagedAppendIdentityMismatchError)
|
|
20718
|
-
return { kind: "stale", reason: "transcript_moved" };
|
|
20719
|
-
const outcome = classifyAppendFailure(error);
|
|
20720
|
-
if (outcome.kind === "not_committed") return { kind: "rejected", error };
|
|
20721
|
-
return unknown(error);
|
|
20722
|
-
} finally {
|
|
20723
|
-
this.#sharedAppendEntryId = undefined;
|
|
20724
|
-
this.#sharedAppendOnly = false;
|
|
20725
|
-
}
|
|
20726
|
-
// Append-only: this path refuses instead of escalating to a whole-file rewrite.
|
|
20727
|
-
await this.flush();
|
|
20728
|
-
const after = await this.captureCommittedSnapshot();
|
|
20729
|
-
if (
|
|
20730
|
-
after.kind !== "snapshot" ||
|
|
20731
|
-
after.snapshot.sessionId !== this.#sessionId ||
|
|
20732
|
-
!ids.every(id => after.snapshot.entryIds.includes(id))
|
|
20733
|
-
)
|
|
20734
|
-
return unknown(new Error("durability_unproven"));
|
|
20735
|
-
this.#openCommittedDigest = after.snapshot.digest;
|
|
20736
|
-
return { kind: "committed", ids };
|
|
20737
|
-
},
|
|
20738
|
-
);
|
|
20739
|
-
try {
|
|
20740
|
-
return await publication;
|
|
20741
|
-
} catch (error) {
|
|
20742
|
-
// Acquisition and pre-staging failures retain their existing throwing contract.
|
|
20743
|
-
// Once an ID was assigned, even a release failure must carry that identity.
|
|
20744
|
-
if (attempted === 0) throw error;
|
|
20745
|
-
return unknown(error);
|
|
21086
|
+
// Append-only: this path refuses instead of escalating to a whole-file rewrite.
|
|
21087
|
+
await this.flush();
|
|
21088
|
+
const after = await this.captureCommittedSnapshot();
|
|
21089
|
+
if (
|
|
21090
|
+
after.kind !== "snapshot" ||
|
|
21091
|
+
after.snapshot.sessionId !== this.#sessionId ||
|
|
21092
|
+
!ids.every(id => after.snapshot.entryIds.includes(id))
|
|
21093
|
+
)
|
|
21094
|
+
return unknown(new Error("durability_unproven"));
|
|
21095
|
+
this.#openCommittedDigest = after.snapshot.digest;
|
|
21096
|
+
return { kind: "committed", ids };
|
|
21097
|
+
},
|
|
21098
|
+
);
|
|
21099
|
+
try {
|
|
21100
|
+
return await publication;
|
|
21101
|
+
} catch (error) {
|
|
21102
|
+
// Acquisition and pre-staging failures retain their existing throwing contract.
|
|
21103
|
+
// Once an ID was assigned, even a release failure must carry that identity.
|
|
21104
|
+
if (attempted === 0) throw error;
|
|
21105
|
+
return unknown(error);
|
|
21106
|
+
}
|
|
21107
|
+
} finally {
|
|
21108
|
+
releasePublication?.();
|
|
20746
21109
|
}
|
|
20747
21110
|
}
|
|
20748
21111
|
|
|
@@ -20819,9 +21182,13 @@ export class SessionManager {
|
|
|
20819
21182
|
}
|
|
20820
21183
|
|
|
20821
21184
|
appendServiceTierChange(serviceTier: ServiceTier | null): string {
|
|
21185
|
+
return this.#appendServiceTierChangeWithId(serviceTier, this.#generateEntryId());
|
|
21186
|
+
}
|
|
21187
|
+
|
|
21188
|
+
#appendServiceTierChangeWithId(serviceTier: ServiceTier | null, id: string): string {
|
|
20822
21189
|
const entry: ServiceTierChangeEntry = {
|
|
20823
21190
|
type: "service_tier_change",
|
|
20824
|
-
id
|
|
21191
|
+
id,
|
|
20825
21192
|
parentId: this.#leafId,
|
|
20826
21193
|
timestamp: new Date().toISOString(),
|
|
20827
21194
|
serviceTier,
|
|
@@ -20832,9 +21199,23 @@ export class SessionManager {
|
|
|
20832
21199
|
|
|
20833
21200
|
/** Append a mode change as child of current leaf, then advance leaf. Returns entry id. */
|
|
20834
21201
|
appendModeChange(mode: string, data?: Record<string, unknown>): string {
|
|
21202
|
+
return this.#appendModeChangeWithId(mode, data, this.#generateEntryId());
|
|
21203
|
+
}
|
|
21204
|
+
|
|
21205
|
+
/** Publish a mode change at this opener's admitted branch cursor under a shared lease. */
|
|
21206
|
+
async appendModeChangeSharingSession(mode: string, data?: Record<string, unknown>): Promise<SharedAppendOutcome> {
|
|
21207
|
+
return this.#publishOwnedEntrySharingSession(
|
|
21208
|
+
id => this.#appendModeChangeWithId(mode, data, id),
|
|
21209
|
+
undefined,
|
|
21210
|
+
undefined,
|
|
21211
|
+
true,
|
|
21212
|
+
);
|
|
21213
|
+
}
|
|
21214
|
+
|
|
21215
|
+
#appendModeChangeWithId(mode: string, data: Record<string, unknown> | undefined, id: string): string {
|
|
20835
21216
|
const entry: ModeChangeEntry = {
|
|
20836
21217
|
type: "mode_change",
|
|
20837
|
-
id
|
|
21218
|
+
id,
|
|
20838
21219
|
parentId: this.#leafId,
|
|
20839
21220
|
timestamp: new Date().toISOString(),
|
|
20840
21221
|
mode,
|
|
@@ -20880,9 +21261,13 @@ export class SessionManager {
|
|
|
20880
21261
|
|
|
20881
21262
|
/** Append an explicit role-model clear marker, preserving absence during replay. */
|
|
20882
21263
|
clearModelRole(role: string): string {
|
|
21264
|
+
return this.#clearModelRoleWithId(role, this.#generateEntryId());
|
|
21265
|
+
}
|
|
21266
|
+
|
|
21267
|
+
#clearModelRoleWithId(role: string, id: string): string {
|
|
20883
21268
|
const entry: ModelChangeEntry = {
|
|
20884
21269
|
type: "model_change",
|
|
20885
|
-
id
|
|
21270
|
+
id,
|
|
20886
21271
|
parentId: this.#leafId,
|
|
20887
21272
|
timestamp: new Date().toISOString(),
|
|
20888
21273
|
model: "",
|
|
@@ -20997,12 +21382,32 @@ export class SessionManager {
|
|
|
20997
21382
|
* happen in one synchronous step, so no turn can interleave.
|
|
20998
21383
|
*/
|
|
20999
21384
|
appendSessionRecap(input: SessionRecapInput): SessionRecapAppendResult {
|
|
21000
|
-
this.
|
|
21385
|
+
this.assertLegacyAppendAllowed("append session recap");
|
|
21001
21386
|
const plan = planSessionRecapAppend(this.#walkActiveBranchNewestFirst(), input);
|
|
21002
21387
|
if (!plan.ok) return { status: "rejected", reason: plan.reason };
|
|
21003
21388
|
return { status: "appended", entryId: this.appendCustomEntry(SESSION_RECAP_ENTRY, plan.data) };
|
|
21004
21389
|
}
|
|
21005
21390
|
|
|
21391
|
+
/**
|
|
21392
|
+
* Publish a recap at this opener's admitted branch cursor under a shared lease.
|
|
21393
|
+
*
|
|
21394
|
+
* The plan is computed against this manager's own graph before the lease is taken: a
|
|
21395
|
+
* concurrent sibling append can only make the recap's freshness claim stale, and
|
|
21396
|
+
* {@link getSessionRecap} re-validates provenance on every read, so the entry itself
|
|
21397
|
+
* is always additive-safe.
|
|
21398
|
+
*/
|
|
21399
|
+
async appendSessionRecapSharingSession(input: SessionRecapInput): Promise<SessionRecapAppendResult> {
|
|
21400
|
+
this.#assertRecoveryHydrationWritable();
|
|
21401
|
+
const plan = planSessionRecapAppend(this.#walkActiveBranchNewestFirst(), input);
|
|
21402
|
+
if (!plan.ok) return { status: "rejected", reason: plan.reason };
|
|
21403
|
+
const outcome = await this.appendCustomEntrySharingSession(SESSION_RECAP_ENTRY, plan.data);
|
|
21404
|
+
if (outcome.kind === "committed") return { status: "appended", entryId: outcome.id };
|
|
21405
|
+
throw new Error(
|
|
21406
|
+
`Shared session recap append ${outcome.kind}${outcome.kind === "stale" ? `: ${outcome.reason}` : ""}${outcome.kind === "unknown" ? ` (attempted id: ${outcome.id})` : ""}`,
|
|
21407
|
+
{ cause: outcome },
|
|
21408
|
+
);
|
|
21409
|
+
}
|
|
21410
|
+
|
|
21006
21411
|
/**
|
|
21007
21412
|
* Recap of the active branch's last turn, or undefined when there is none or it
|
|
21008
21413
|
* is stale (the conversation advanced past its source entry, the leaf moved to a
|
|
@@ -21044,16 +21449,38 @@ export class SessionManager {
|
|
|
21044
21449
|
*/
|
|
21045
21450
|
appendContextClearEntry(data?: Record<string, unknown>): string {
|
|
21046
21451
|
const ownershipMarker = this.getModelProfileOwnershipMarker();
|
|
21452
|
+
const id = this.#appendContextClearRootWithId(data, this.#generateEntryId());
|
|
21453
|
+
if (ownershipMarker) this.appendModelProfileOwnershipMarker(ownershipMarker);
|
|
21454
|
+
return id;
|
|
21455
|
+
}
|
|
21456
|
+
|
|
21457
|
+
/**
|
|
21458
|
+
* The admitted shared form of {@link appendContextClearEntry}: the parentless root and
|
|
21459
|
+
* the carried-over profile ownership marker, as entries for
|
|
21460
|
+
* {@link appendControlEntriesSharingSession}. The root is appended, never rewritten, so
|
|
21461
|
+
* earlier history and any unseen sibling branch stay in the transcript.
|
|
21462
|
+
*/
|
|
21463
|
+
contextClearControlEntries(data: Record<string, unknown> | undefined): SharedControlEntry[] {
|
|
21464
|
+
const ownershipMarker = this.getModelProfileOwnershipMarker();
|
|
21465
|
+
const entries: SharedControlEntry[] = [{ type: "context_clear", data }];
|
|
21466
|
+
if (ownershipMarker) {
|
|
21467
|
+
const validated = validateModelProfileOwnershipMarker(ownershipMarker);
|
|
21468
|
+
if (!validated) throw new InvalidModelProfileOwnershipError();
|
|
21469
|
+
entries.push({ type: "custom", customType: MODEL_PROFILE_OWNERSHIP_ENTRY, data: validated });
|
|
21470
|
+
}
|
|
21471
|
+
return entries;
|
|
21472
|
+
}
|
|
21473
|
+
|
|
21474
|
+
#appendContextClearRootWithId(data: Record<string, unknown> | undefined, id: string): string {
|
|
21047
21475
|
const entry: CustomEntry = {
|
|
21048
21476
|
type: "custom",
|
|
21049
21477
|
customType: "context_clear",
|
|
21050
21478
|
data,
|
|
21051
|
-
id
|
|
21479
|
+
id,
|
|
21052
21480
|
parentId: null,
|
|
21053
21481
|
timestamp: new Date().toISOString(),
|
|
21054
21482
|
};
|
|
21055
21483
|
this.#appendEntry(entry);
|
|
21056
|
-
if (ownershipMarker) this.appendModelProfileOwnershipMarker(ownershipMarker);
|
|
21057
21484
|
return entry.id;
|
|
21058
21485
|
}
|
|
21059
21486
|
|
|
@@ -21196,7 +21623,45 @@ export class SessionManager {
|
|
|
21196
21623
|
attribution: MessageAttribution = "agent",
|
|
21197
21624
|
observationId?: string,
|
|
21198
21625
|
): string {
|
|
21199
|
-
|
|
21626
|
+
return this.#appendCustomMessageEntryWithId(
|
|
21627
|
+
customType,
|
|
21628
|
+
content,
|
|
21629
|
+
display,
|
|
21630
|
+
details,
|
|
21631
|
+
attribution,
|
|
21632
|
+
observationId,
|
|
21633
|
+
this.#generateEntryId(),
|
|
21634
|
+
);
|
|
21635
|
+
}
|
|
21636
|
+
|
|
21637
|
+
/**
|
|
21638
|
+
* Publish a custom message at the managed branch cursor under a shared lease.
|
|
21639
|
+
* Sessions that publish canonical messages through the shared path must use this
|
|
21640
|
+
* for custom messages too: once shared admission is armed, the legacy append is
|
|
21641
|
+
* refused.
|
|
21642
|
+
*/
|
|
21643
|
+
async appendCustomMessageEntrySharingSession<T = unknown>(
|
|
21644
|
+
customType: string,
|
|
21645
|
+
content: string | (TextContent | ImageContent)[],
|
|
21646
|
+
display: boolean,
|
|
21647
|
+
details?: T,
|
|
21648
|
+
attribution: MessageAttribution = "agent",
|
|
21649
|
+
observationId?: string,
|
|
21650
|
+
): Promise<SharedAppendOutcome> {
|
|
21651
|
+
return this.#publishOwnedEntrySharingSession(id =>
|
|
21652
|
+
this.#appendCustomMessageEntryWithId(customType, content, display, details, attribution, observationId, id),
|
|
21653
|
+
);
|
|
21654
|
+
}
|
|
21655
|
+
|
|
21656
|
+
#appendCustomMessageEntryWithId<T>(
|
|
21657
|
+
customType: string,
|
|
21658
|
+
content: string | (TextContent | ImageContent)[],
|
|
21659
|
+
display: boolean,
|
|
21660
|
+
details: T | undefined,
|
|
21661
|
+
attribution: MessageAttribution,
|
|
21662
|
+
observationId: string | undefined,
|
|
21663
|
+
entryId: string,
|
|
21664
|
+
): string {
|
|
21200
21665
|
const stableObservationId =
|
|
21201
21666
|
observationId ?? (customType.startsWith("irc:") ? `session:${this.#sessionId}:entry:${entryId}` : undefined);
|
|
21202
21667
|
const persistedDetails =
|
|
@@ -21230,7 +21695,7 @@ export class SessionManager {
|
|
|
21230
21695
|
mcpToolNames: string[] | undefined,
|
|
21231
21696
|
builtinToolNames: string[] | undefined,
|
|
21232
21697
|
isCurrent: () => boolean,
|
|
21233
|
-
): Promise<
|
|
21698
|
+
): Promise<SharedEntriesAppendOutcome> {
|
|
21234
21699
|
if (!mcpToolNames && !builtinToolNames)
|
|
21235
21700
|
return { kind: "rejected", error: new Error("shared_tool_selection_requires_change") };
|
|
21236
21701
|
const mcp = mcpToolNames && [...mcpToolNames];
|
|
@@ -21244,6 +21709,9 @@ export class SessionManager {
|
|
|
21244
21709
|
: this.#appendDiscoveredBuiltinToolSelectionWithId(builtin!, correlationId, id),
|
|
21245
21710
|
undefined,
|
|
21246
21711
|
isCurrent,
|
|
21712
|
+
// A control operation: verification and release failures latch persistence.
|
|
21713
|
+
true,
|
|
21714
|
+
true,
|
|
21247
21715
|
);
|
|
21248
21716
|
}
|
|
21249
21717
|
|
|
@@ -21301,9 +21769,36 @@ export class SessionManager {
|
|
|
21301
21769
|
* @returns Entry id
|
|
21302
21770
|
*/
|
|
21303
21771
|
appendTtsrInjection(ruleNames: string[], records?: TtsrInjectionRecord[], ttsrMessageCount?: number): string {
|
|
21772
|
+
return this.#appendTtsrInjectionWithId(ruleNames, records, ttsrMessageCount, this.#generateEntryId());
|
|
21773
|
+
}
|
|
21774
|
+
|
|
21775
|
+
/**
|
|
21776
|
+
* Publish a TTSR injection marker at this opener's admitted branch cursor.
|
|
21777
|
+
* Sessions that publish canonical messages through the shared path must use this for
|
|
21778
|
+
* injection markers too: once shared admission is armed, the legacy append is refused.
|
|
21779
|
+
*/
|
|
21780
|
+
async appendTtsrInjectionSharingSession(
|
|
21781
|
+
ruleNames: string[],
|
|
21782
|
+
records?: TtsrInjectionRecord[],
|
|
21783
|
+
ttsrMessageCount?: number,
|
|
21784
|
+
): Promise<SharedAppendOutcome> {
|
|
21785
|
+
return this.#publishOwnedEntrySharingSession(
|
|
21786
|
+
id => this.#appendTtsrInjectionWithId(ruleNames, records, ttsrMessageCount, id),
|
|
21787
|
+
undefined,
|
|
21788
|
+
undefined,
|
|
21789
|
+
true,
|
|
21790
|
+
);
|
|
21791
|
+
}
|
|
21792
|
+
|
|
21793
|
+
#appendTtsrInjectionWithId(
|
|
21794
|
+
ruleNames: string[],
|
|
21795
|
+
records: TtsrInjectionRecord[] | undefined,
|
|
21796
|
+
ttsrMessageCount: number | undefined,
|
|
21797
|
+
id: string,
|
|
21798
|
+
): string {
|
|
21304
21799
|
const entry: TtsrInjectionEntry = {
|
|
21305
21800
|
type: "ttsr_injection",
|
|
21306
|
-
id
|
|
21801
|
+
id,
|
|
21307
21802
|
parentId: this.#leafId,
|
|
21308
21803
|
timestamp: new Date().toISOString(),
|
|
21309
21804
|
injectedRules: ruleNames,
|
|
@@ -21919,12 +22414,25 @@ export class SessionManager {
|
|
|
21919
22414
|
* Pass undefined or empty string to clear the label.
|
|
21920
22415
|
*/
|
|
21921
22416
|
appendLabelChange(targetId: string, label: string | undefined): string {
|
|
22417
|
+
return this.#appendLabelChangeWithId(targetId, label, this.#generateEntryId());
|
|
22418
|
+
}
|
|
22419
|
+
|
|
22420
|
+
/**
|
|
22421
|
+
* Publish a label change at this opener's admitted branch cursor under a shared lease.
|
|
22422
|
+
* Sessions that publish canonical messages through the shared path must use this for
|
|
22423
|
+
* labels too: once shared admission is armed, the legacy append is refused.
|
|
22424
|
+
*/
|
|
22425
|
+
async appendLabelChangeSharingSession(targetId: string, label: string | undefined): Promise<SharedAppendOutcome> {
|
|
22426
|
+
return this.#publishOwnedEntrySharingSession(id => this.#appendLabelChangeWithId(targetId, label, id));
|
|
22427
|
+
}
|
|
22428
|
+
|
|
22429
|
+
#appendLabelChangeWithId(targetId: string, label: string | undefined, id: string): string {
|
|
21922
22430
|
if (!this.#resolveEntry(targetId)) {
|
|
21923
22431
|
throw new Error(`Entry ${targetId} not found`);
|
|
21924
22432
|
}
|
|
21925
22433
|
const entry: LabelEntry = {
|
|
21926
22434
|
type: "label",
|
|
21927
|
-
id
|
|
22435
|
+
id,
|
|
21928
22436
|
parentId: this.#leafId,
|
|
21929
22437
|
timestamp: new Date().toISOString(),
|
|
21930
22438
|
targetId,
|
|
@@ -25372,7 +25880,7 @@ export class SessionManager {
|
|
|
25372
25880
|
async deleteSessionVerified(target: VerifiedSessionDeleteTarget): Promise<VerifiedSessionDeleteResult> {
|
|
25373
25881
|
// Storage verifies this logical ID against the retained transcript header before
|
|
25374
25882
|
// deletion. A caller-supplied path or the active manager ID is not authority.
|
|
25375
|
-
this.#assertLogicalSessionMutationAllowed(target.sessionId, "delete verified session");
|
|
25883
|
+
this.#assertLogicalSessionMutationAllowed(target.sessionId, "delete verified session", true);
|
|
25376
25884
|
if (!this.#storage.deleteSessionVerified) {
|
|
25377
25885
|
throw new Error("Storage backend does not support verified session deletion");
|
|
25378
25886
|
}
|