@rynfar/meridian 1.64.0 → 1.65.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.
@@ -4,14 +4,16 @@ import {
4
4
  choosePriorityProfile,
5
5
  getActiveProfileId,
6
6
  getEffectiveProfiles,
7
+ getPriorityFailbackPolicy,
7
8
  getRoutingMode,
8
9
  listProfiles,
9
10
  resolveCooldownUntil,
10
11
  resolvePriorityOrder,
11
12
  resolveProfile,
12
13
  restoreActiveProfile,
13
- setActiveProfile
14
- } from "./cli-m0p2bc8v.js";
14
+ setActiveProfile,
15
+ shouldPromotePriorityAssignment
16
+ } from "./cli-pdpry6q0.js";
15
17
  import {
16
18
  isTrackedPlugin,
17
19
  recordError,
@@ -69,9 +71,12 @@ import {
69
71
  } from "./cli-vj9cv18n.js";
70
72
  import {
71
73
  LRUMap,
74
+ PRIORITY_ATTESTATION_HEADER,
72
75
  checkPluginConfigured,
73
- notePluginlessOpenCodeRequest
74
- } from "./cli-pbvm9kc2.js";
76
+ init_priorityAttestation,
77
+ notePluginlessOpenCodeRequest,
78
+ verifyPriorityAttestation
79
+ } from "./cli-n8t34zmq.js";
75
80
  import {
76
81
  __commonJS,
77
82
  __esm,
@@ -2304,6 +2309,7 @@ function canonicalizeOpenCodeMessagesForLineage(messages) {
2304
2309
  var openCodeAdapter;
2305
2310
  var init_opencode2 = __esm(() => {
2306
2311
  init_fileChanges();
2312
+ init_priorityAttestation();
2307
2313
  init_messages();
2308
2314
  init_fingerprint();
2309
2315
  init_tools();
@@ -2325,6 +2331,25 @@ var init_opencode2 = __esm(() => {
2325
2331
  getAgentMode(c) {
2326
2332
  return c.req.header("x-opencode-agent-mode");
2327
2333
  },
2334
+ getRoutingTurnIdentity(c) {
2335
+ if (c.req.header("x-meridian-profile") !== undefined)
2336
+ return;
2337
+ const sessionId = c.req.header("x-opencode-session");
2338
+ const agentId = c.req.header("x-opencode-agent-name");
2339
+ if (!sessionId || !agentId || c.req.header("x-opencode-agent-mode") !== "primary") {
2340
+ return;
2341
+ }
2342
+ const attestation = verifyPriorityAttestation(c.req.header(PRIORITY_ATTESTATION_HEADER));
2343
+ if (!attestation || attestation.sessionId !== sessionId || attestation.agentId !== agentId) {
2344
+ return;
2345
+ }
2346
+ return {
2347
+ kind: "human",
2348
+ turnId: attestation.turnId,
2349
+ issuedAt: attestation.issuedAt,
2350
+ generation: attestation.generation === "oc1" ? "opencode-v1" : "opencode-v2-beta-18314"
2351
+ };
2352
+ },
2328
2353
  extractWorkingDirectory(body) {
2329
2354
  return extractClientCwd(body);
2330
2355
  },
@@ -22691,6 +22716,7 @@ var BILLING_SIGNALS = [
22691
22716
  /insufficient (?:credit|funds|balance)/
22692
22717
  ];
22693
22718
  var HIT_YOUR_LIMIT = /hit your (?:[\w-]+ )?limit/;
22719
+ var OUT_OF_USAGE_CREDITS = /^\s*(?:(?:error|api error|claude code returned an error result):\s*)*you(?:'|’)re out of usage credits(?:[.!]\s*)?(?:\/model to switch models\.?)?\s*$/;
22694
22720
  var HTTP_401 = /(?:^|[^0-9a-f])401(?![0-9a-f]|:\d)/;
22695
22721
  var HTTP_429 = /(?:^|[^0-9a-f])429(?![0-9a-f]|:\d)/;
22696
22722
  var HTTP_500 = /(?:^|[^0-9a-f])500(?![0-9a-f]|:\d)/;
@@ -22711,7 +22737,7 @@ function classifyError(errMsg, model) {
22711
22737
  message: "Claude authentication expired or invalid. Run 'claude login' in your terminal to re-authenticate, then restart the proxy."
22712
22738
  };
22713
22739
  }
22714
- if (HTTP_429.test(lower) || lower.includes("rate limit") || lower.includes("too many requests") || HIT_YOUR_LIMIT.test(lower) || lower.includes("usage limit reached")) {
22740
+ if (HTTP_429.test(lower) || lower.includes("rate limit") || lower.includes("too many requests") || HIT_YOUR_LIMIT.test(lower) || lower.includes("usage limit reached") || OUT_OF_USAGE_CREDITS.test(lower)) {
22715
22741
  const hint = lower.includes("1m") || lower.includes("context") ? extendedContextHint(model) : "";
22716
22742
  return {
22717
22743
  status: 429,
@@ -31276,6 +31302,7 @@ function getRecoveryClaimTombstonePath(claimPath, claimToken) {
31276
31302
  // src/proxy/sessionStore.ts
31277
31303
  var STORE_META_KEY = "\x00meridian-session-store";
31278
31304
  var STORE_META_VERSION = 1;
31305
+ var PRIORITY_STORE_META_VERSION = 3;
31279
31306
  function keyDigest(key) {
31280
31307
  return createHash5("sha256").update(key).digest("hex");
31281
31308
  }
@@ -31292,6 +31319,18 @@ function getStoredSessionGeneration(session, key) {
31292
31319
  function keyGeneration(key, session, meta3) {
31293
31320
  return session ? getStoredSessionGeneration(session, key) : absenceGeneration(key, meta3);
31294
31321
  }
31322
+ function priorityGenerationKey(routeKey) {
31323
+ return `priority:${routeKey}`;
31324
+ }
31325
+ function priorityAbsenceGeneration(routeKey, meta3) {
31326
+ return absenceGeneration(priorityGenerationKey(routeKey), meta3);
31327
+ }
31328
+ function getPriorityAssignmentGeneration(assignment, routeKey) {
31329
+ return `r:${keyDigest(priorityGenerationKey(routeKey))}:${assignment.generationId}`;
31330
+ }
31331
+ function priorityAssignmentGeneration(routeKey, assignment, meta3) {
31332
+ return assignment ? getPriorityAssignmentGeneration(assignment, routeKey) : priorityAbsenceGeneration(routeKey, meta3);
31333
+ }
31295
31334
  function advanceKeySlot(key, meta3) {
31296
31335
  const slot = keySlot(key);
31297
31336
  const current = meta3.slots[slot] ?? 0;
@@ -31301,6 +31340,8 @@ function advanceKeySlot(key, meta3) {
31301
31340
  meta3.slots[slot] = current + 1;
31302
31341
  }
31303
31342
  var DEFAULT_MAX_STORED_SESSIONS = 1e4;
31343
+ var DEFAULT_MAX_PRIORITY_ASSIGNMENTS = 5000;
31344
+ var DEFAULT_MAX_PRIORITY_ATTEMPTS = 5000;
31304
31345
  var STALE_LOCK_THRESHOLD_MS = 30000;
31305
31346
  var DEFAULT_LOCK_WAIT_MS = 1e4;
31306
31347
  var LOCK_RETRY_MS = 10;
@@ -31314,6 +31355,24 @@ function getMaxStoredSessionsLimit() {
31314
31355
  return DEFAULT_MAX_STORED_SESSIONS;
31315
31356
  return parsed;
31316
31357
  }
31358
+ function getMaxPriorityAssignmentsLimit() {
31359
+ const raw2 = process.env.MERIDIAN_MAX_PRIORITY_ASSIGNMENTS;
31360
+ if (!raw2)
31361
+ return DEFAULT_MAX_PRIORITY_ASSIGNMENTS;
31362
+ const parsed = Number.parseInt(raw2, 10);
31363
+ if (!Number.isFinite(parsed) || parsed <= 0)
31364
+ return DEFAULT_MAX_PRIORITY_ASSIGNMENTS;
31365
+ return parsed;
31366
+ }
31367
+ function getMaxPriorityAttemptsLimit() {
31368
+ const raw2 = process.env.MERIDIAN_MAX_PRIORITY_ATTEMPTS;
31369
+ if (!raw2)
31370
+ return DEFAULT_MAX_PRIORITY_ATTEMPTS;
31371
+ const parsed = Number.parseInt(raw2, 10);
31372
+ if (!Number.isFinite(parsed) || parsed <= 0)
31373
+ return DEFAULT_MAX_PRIORITY_ATTEMPTS;
31374
+ return parsed;
31375
+ }
31317
31376
  function getLockWaitMs() {
31318
31377
  const raw2 = process.env.MERIDIAN_SESSION_LOCK_TIMEOUT_MS ?? process.env.CLAUDE_PROXY_SESSION_LOCK_TIMEOUT_MS;
31319
31378
  if (!raw2)
@@ -31701,6 +31760,98 @@ function validateStoredSession(key, value) {
31701
31760
  }
31702
31761
  }
31703
31762
  }
31763
+ function hasExactObjectKeys(value, expected) {
31764
+ const actual = Object.keys(value).sort();
31765
+ const wanted = [...expected].sort();
31766
+ return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
31767
+ }
31768
+ var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
31769
+ function validatePriorityAssignment(routeKey, value) {
31770
+ if (!routeKey || routeKey.length > 512 || !value || typeof value !== "object" || Array.isArray(value)) {
31771
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} is invalid`);
31772
+ }
31773
+ const assignment = value;
31774
+ if (!hasExactObjectKeys(assignment, [
31775
+ "profileId",
31776
+ "lastHumanTurnDigest",
31777
+ "lastHumanTurnIssuedAt",
31778
+ "mappingKey",
31779
+ "mappingGeneration",
31780
+ "generationId",
31781
+ "updatedAt"
31782
+ ])) {
31783
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has unknown or missing fields`);
31784
+ }
31785
+ if (typeof assignment.profileId !== "string" || !assignment.profileId || assignment.profileId.length > 128) {
31786
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid profileId`);
31787
+ }
31788
+ if (typeof assignment.lastHumanTurnDigest !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(assignment.lastHumanTurnDigest)) {
31789
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid human-turn digest`);
31790
+ }
31791
+ if (typeof assignment.lastHumanTurnIssuedAt !== "number" || !Number.isSafeInteger(assignment.lastHumanTurnIssuedAt) || assignment.lastHumanTurnIssuedAt < 0) {
31792
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid human-turn issue time`);
31793
+ }
31794
+ if (typeof assignment.mappingKey !== "string" || !assignment.mappingKey || assignment.mappingKey.length > 1024) {
31795
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid mappingKey`);
31796
+ }
31797
+ const expectedMappingPrefix = typeof assignment.mappingKey === "string" ? `p:${keyDigest(assignment.mappingKey)}:` : "";
31798
+ if (typeof assignment.mappingGeneration !== "string" || !assignment.mappingGeneration.startsWith(expectedMappingPrefix) || !UUID_PATTERN2.test(assignment.mappingGeneration.slice(expectedMappingPrefix.length))) {
31799
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid mapping generation`);
31800
+ }
31801
+ if (typeof assignment.generationId !== "string" || !UUID_PATTERN2.test(assignment.generationId)) {
31802
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid generationId`);
31803
+ }
31804
+ if (typeof assignment.updatedAt !== "number" || !Number.isSafeInteger(assignment.updatedAt) || assignment.updatedAt < 0) {
31805
+ throw new Error(`session store priority route ${JSON.stringify(routeKey)} has invalid updatedAt`);
31806
+ }
31807
+ return {
31808
+ profileId: assignment.profileId,
31809
+ lastHumanTurnDigest: assignment.lastHumanTurnDigest,
31810
+ lastHumanTurnIssuedAt: assignment.lastHumanTurnIssuedAt,
31811
+ mappingKey: assignment.mappingKey,
31812
+ mappingGeneration: assignment.mappingGeneration,
31813
+ generationId: assignment.generationId,
31814
+ updatedAt: assignment.updatedAt
31815
+ };
31816
+ }
31817
+ function validatePriorityAttempt(routeKey, value) {
31818
+ if (!routeKey || routeKey.length > 512 || !value || typeof value !== "object" || Array.isArray(value)) {
31819
+ throw new Error(`session store priority attempt ${JSON.stringify(routeKey)} is invalid`);
31820
+ }
31821
+ const attempt = value;
31822
+ if (!hasExactObjectKeys(attempt, [
31823
+ "blocked",
31824
+ "blockedTurnDigest",
31825
+ "blockedTurnIssuedAt",
31826
+ "pendingTurnDigest",
31827
+ "pendingTurnIssuedAt",
31828
+ "ownerToken",
31829
+ "generationId",
31830
+ "updatedAt"
31831
+ ]))
31832
+ throw new Error(`session store priority attempt ${JSON.stringify(routeKey)} has unknown or missing fields`);
31833
+ const validDigest = (digest) => digest === null || typeof digest === "string" && /^[A-Za-z0-9_-]{43}$/.test(digest);
31834
+ const validIssuedAt = (issuedAt) => issuedAt === null || typeof issuedAt === "number" && Number.isSafeInteger(issuedAt) && issuedAt >= 0;
31835
+ if (typeof attempt.blocked !== "boolean" || !validDigest(attempt.blockedTurnDigest) || !validIssuedAt(attempt.blockedTurnIssuedAt) || !validDigest(attempt.pendingTurnDigest) || !validIssuedAt(attempt.pendingTurnIssuedAt) || attempt.blockedTurnDigest === null !== (attempt.blockedTurnIssuedAt === null) || attempt.pendingTurnDigest === null !== (attempt.pendingTurnIssuedAt === null) || attempt.ownerToken !== null && (typeof attempt.ownerToken !== "string" || !UUID_PATTERN2.test(attempt.ownerToken)) || attempt.ownerToken === null && attempt.pendingTurnDigest !== null || !attempt.blocked && attempt.ownerToken === null) {
31836
+ throw new Error(`session store priority attempt ${JSON.stringify(routeKey)} has invalid state`);
31837
+ }
31838
+ if (typeof attempt.generationId !== "string" || !UUID_PATTERN2.test(attempt.generationId)) {
31839
+ throw new Error(`session store priority attempt ${JSON.stringify(routeKey)} has invalid generationId`);
31840
+ }
31841
+ if (typeof attempt.updatedAt !== "number" || !Number.isSafeInteger(attempt.updatedAt) || attempt.updatedAt < 0) {
31842
+ throw new Error(`session store priority attempt ${JSON.stringify(routeKey)} has invalid updatedAt`);
31843
+ }
31844
+ return {
31845
+ blocked: attempt.blocked,
31846
+ blockedTurnDigest: attempt.blockedTurnDigest,
31847
+ blockedTurnIssuedAt: attempt.blockedTurnIssuedAt,
31848
+ pendingTurnDigest: attempt.pendingTurnDigest,
31849
+ pendingTurnIssuedAt: attempt.pendingTurnIssuedAt,
31850
+ ownerToken: attempt.ownerToken,
31851
+ generationId: attempt.generationId,
31852
+ updatedAt: attempt.updatedAt
31853
+ };
31854
+ }
31704
31855
  function emptyStoreDocument() {
31705
31856
  return { sessions: {}, meta: { version: STORE_META_VERSION, slots: {} } };
31706
31857
  }
@@ -31709,7 +31860,7 @@ function validateStoreMeta(value) {
31709
31860
  throw new Error("session store metadata must be an object");
31710
31861
  }
31711
31862
  const meta3 = value;
31712
- if (meta3.version !== STORE_META_VERSION || typeof meta3.slots !== "object" || meta3.slots === null || Array.isArray(meta3.slots)) {
31863
+ if (meta3.version !== STORE_META_VERSION && meta3.version !== PRIORITY_STORE_META_VERSION || typeof meta3.slots !== "object" || meta3.slots === null || Array.isArray(meta3.slots)) {
31713
31864
  throw new Error("session store metadata has an unsupported format");
31714
31865
  }
31715
31866
  for (const [slot, counter] of Object.entries(meta3.slots)) {
@@ -31717,7 +31868,55 @@ function validateStoreMeta(value) {
31717
31868
  throw new Error(`session store metadata has invalid generation slot ${JSON.stringify(slot)}`);
31718
31869
  }
31719
31870
  }
31720
- return { version: STORE_META_VERSION, slots: { ...meta3.slots } };
31871
+ const slots = { ...meta3.slots };
31872
+ if (meta3.version === STORE_META_VERSION) {
31873
+ if (!hasExactObjectKeys(meta3, ["version", "slots"])) {
31874
+ throw new Error("session store v1 metadata has unknown or missing fields");
31875
+ }
31876
+ return { version: STORE_META_VERSION, slots };
31877
+ }
31878
+ if (!hasExactObjectKeys(meta3, ["version", "slots", "priorityAssignments", "priorityAttempts", "priorityRollbackMappings"])) {
31879
+ throw new Error("session store v3 metadata has unknown or missing fields");
31880
+ }
31881
+ if (typeof meta3.priorityAssignments !== "object" || meta3.priorityAssignments === null || Array.isArray(meta3.priorityAssignments))
31882
+ throw new Error("session store v3 metadata has invalid priority assignments");
31883
+ if (typeof meta3.priorityAttempts !== "object" || meta3.priorityAttempts === null || Array.isArray(meta3.priorityAttempts))
31884
+ throw new Error("session store v3 metadata has invalid priority attempts");
31885
+ if (typeof meta3.priorityRollbackMappings !== "object" || meta3.priorityRollbackMappings === null || Array.isArray(meta3.priorityRollbackMappings))
31886
+ throw new Error("session store v3 metadata has invalid priority rollback mappings");
31887
+ const priorityAssignments = {};
31888
+ for (const [routeKey, assignment] of Object.entries(meta3.priorityAssignments)) {
31889
+ priorityAssignments[routeKey] = validatePriorityAssignment(routeKey, assignment);
31890
+ }
31891
+ const priorityAttempts = {};
31892
+ for (const [routeKey, attempt] of Object.entries(meta3.priorityAttempts)) {
31893
+ priorityAttempts[routeKey] = validatePriorityAttempt(routeKey, attempt);
31894
+ }
31895
+ const priorityRollbackMappings = {};
31896
+ for (const [routeKey, value2] of Object.entries(meta3.priorityRollbackMappings)) {
31897
+ if (!priorityAssignments[routeKey] || !value2 || typeof value2 !== "object" || Array.isArray(value2)) {
31898
+ throw new Error(`session store priority rollback ${JSON.stringify(routeKey)} is invalid`);
31899
+ }
31900
+ const rollback = value2;
31901
+ if (!hasExactObjectKeys(rollback, ["mappingKey", "mappingGeneration"]) || typeof rollback.mappingKey !== "string" || !rollback.mappingKey || rollback.mappingKey.length > 1024) {
31902
+ throw new Error(`session store priority rollback ${JSON.stringify(routeKey)} is invalid`);
31903
+ }
31904
+ const expectedMappingPrefix = `p:${keyDigest(rollback.mappingKey)}:`;
31905
+ if (typeof rollback.mappingGeneration !== "string" || !rollback.mappingGeneration.startsWith(expectedMappingPrefix) || !UUID_PATTERN2.test(rollback.mappingGeneration.slice(expectedMappingPrefix.length))) {
31906
+ throw new Error(`session store priority rollback ${JSON.stringify(routeKey)} has invalid mapping generation`);
31907
+ }
31908
+ priorityRollbackMappings[routeKey] = {
31909
+ mappingKey: rollback.mappingKey,
31910
+ mappingGeneration: rollback.mappingGeneration
31911
+ };
31912
+ }
31913
+ return {
31914
+ version: PRIORITY_STORE_META_VERSION,
31915
+ slots,
31916
+ priorityAssignments,
31917
+ priorityAttempts,
31918
+ priorityRollbackMappings
31919
+ };
31721
31920
  }
31722
31921
  function readStoreDocumentStrict(path3) {
31723
31922
  let data;
@@ -31742,6 +31941,21 @@ function readStoreDocumentStrict(path3) {
31742
31941
  validateStoredSession(key, value);
31743
31942
  sessions[key] = value;
31744
31943
  }
31944
+ if (meta3.version === PRIORITY_STORE_META_VERSION) {
31945
+ for (const [routeKey, rollback] of Object.entries(meta3.priorityRollbackMappings)) {
31946
+ const assignment = meta3.priorityAssignments[routeKey];
31947
+ const mapping = sessions[rollback.mappingKey];
31948
+ if (!mapping) {
31949
+ throw new Error(`session store priority rollback ${JSON.stringify(routeKey)} has no retained mapping`);
31950
+ }
31951
+ if (rollback.mappingKey === assignment.mappingKey) {
31952
+ throw new Error(`session store priority rollback ${JSON.stringify(routeKey)} aliases its current mapping`);
31953
+ }
31954
+ if (getStoredSessionGeneration(mapping, rollback.mappingKey) !== rollback.mappingGeneration) {
31955
+ throw new Error(`session store priority rollback ${JSON.stringify(routeKey)} has a stale mapping generation`);
31956
+ }
31957
+ }
31958
+ }
31745
31959
  return { sessions, meta: meta3 };
31746
31960
  }
31747
31961
  function readStoreStrict(path3) {
@@ -31842,6 +32056,19 @@ function lookupSharedSession(key) {
31842
32056
  const result = lookupSharedSessionResult(key);
31843
32057
  return result.status === "found" ? result.session : undefined;
31844
32058
  }
32059
+ function lookupPriorityAssignmentResult(routeKey) {
32060
+ try {
32061
+ const document = readStoreDocumentStrict(getStorePath());
32062
+ const assignment = document.meta.version === PRIORITY_STORE_META_VERSION ? document.meta.priorityAssignments[routeKey] : undefined;
32063
+ const generation = priorityAssignmentGeneration(routeKey, assignment, document.meta);
32064
+ const attempt = document.meta.version === PRIORITY_STORE_META_VERSION ? document.meta.priorityAttempts[routeKey] : undefined;
32065
+ return assignment ? { status: "found", assignment, generation, attempt } : { status: "missing", generation, attempt };
32066
+ } catch (error51) {
32067
+ const normalized = error51 instanceof Error ? error51 : new Error(String(error51));
32068
+ console.error("[sessionStore] priority route read failed:", normalized.message);
32069
+ return { status: "error", error: normalized };
32070
+ }
32071
+ }
31845
32072
  function lookupSharedSessionByClaudeIdResult(claudeSessionId) {
31846
32073
  try {
31847
32074
  const document = readStoreDocumentStrict(getStorePath());
@@ -31876,6 +32103,9 @@ function validateTranscriptLocator(locator, claudeSessionId) {
31876
32103
  throw new Error("currentTranscript.lifecycleGeneration must be non-empty");
31877
32104
  }
31878
32105
  }
32106
+ function isPriorityRollbackMapping(meta3, key) {
32107
+ return meta3.version === PRIORITY_STORE_META_VERSION && Object.values(meta3.priorityRollbackMappings).some((rollback) => rollback.mappingKey === key);
32108
+ }
31879
32109
  function storeSharedSession(key, claudeSessionId, messageCount, lineageHash, messageHashes, sdkMessageUuids, contextUsage, messageBlockHashes, passthroughToolCallAssistantUuid, passthroughToolCallIds, currentTranscript, sourceTranscript, expectedGeneration) {
31880
32110
  if (currentTranscript !== undefined) {
31881
32111
  validateTranscriptLocator(currentTranscript, claudeSessionId);
@@ -31890,6 +32120,8 @@ function storeSharedSession(key, claudeSessionId, messageCount, lineageHash, mes
31890
32120
  }
31891
32121
  let storedGeneration = false;
31892
32122
  mutateStore(({ sessions: store, meta: meta3 }) => {
32123
+ if (isPriorityRollbackMapping(meta3, key))
32124
+ return false;
31893
32125
  const existing = store[key];
31894
32126
  if (expectedGeneration !== undefined) {
31895
32127
  const actual = keyGeneration(key, existing, meta3);
@@ -31926,18 +32158,412 @@ function storeSharedSession(key, claudeSessionId, messageCount, lineageHash, mes
31926
32158
  };
31927
32159
  const maxEntries = getMaxStoredSessionsLimit();
31928
32160
  const keys = Object.keys(store);
31929
- if (keys.length > maxEntries) {
31930
- const sorted = keys.filter((candidate) => candidate !== key).sort((a, b) => (store[a].lastUsedAt || 0) - (store[b].lastUsedAt || 0));
31931
- const toRemove = sorted.slice(0, keys.length - maxEntries);
31932
- for (const candidate of toRemove)
31933
- delete store[candidate];
32161
+ const protectedMappings = meta3.version === PRIORITY_STORE_META_VERSION ? new Set([
32162
+ ...Object.values(meta3.priorityAssignments).map((assignment) => assignment.mappingKey),
32163
+ ...Object.values(meta3.priorityRollbackMappings).map((rollback) => rollback.mappingKey)
32164
+ ]) : new Set;
32165
+ protectedMappings.add(key);
32166
+ const removeCount = Math.max(0, keys.length - maxEntries);
32167
+ const removable = keys.filter((candidate) => !protectedMappings.has(candidate)).sort((a, b) => (store[a].lastUsedAt || 0) - (store[b].lastUsedAt || 0));
32168
+ if (removable.length < removeCount)
32169
+ return false;
32170
+ for (const candidate of removable.slice(0, removeCount)) {
32171
+ delete store[candidate];
32172
+ advanceKeySlot(candidate, meta3);
31934
32173
  }
31935
32174
  advanceKeySlot(key, meta3);
31936
32175
  storedGeneration = getStoredSessionGeneration(store[key], key);
32176
+ if (meta3.version === PRIORITY_STORE_META_VERSION) {
32177
+ for (const [routeKey, assignment] of Object.entries(meta3.priorityAssignments)) {
32178
+ if (assignment.mappingKey !== key)
32179
+ continue;
32180
+ assignment.mappingGeneration = storedGeneration;
32181
+ assignment.generationId = randomUUID2();
32182
+ assignment.updatedAt = Date.now();
32183
+ advanceKeySlot(priorityGenerationKey(routeKey), meta3);
32184
+ }
32185
+ }
31937
32186
  return true;
31938
32187
  });
31939
32188
  return storedGeneration;
31940
32189
  }
32190
+ function validatePriorityAttemptTurn(turn) {
32191
+ if (!turn)
32192
+ return;
32193
+ if (!/^[A-Za-z0-9_-]{43}$/.test(turn.turnId) || !Number.isSafeInteger(turn.issuedAt) || turn.issuedAt < 0) {
32194
+ throw new Error("priority attempt requires a valid trusted turn");
32195
+ }
32196
+ }
32197
+ function claimPriorityAttempt(options) {
32198
+ if (!options.routeKey || options.routeKey.length > 512) {
32199
+ throw new Error("priority attempt requires a bounded route key");
32200
+ }
32201
+ validatePriorityAttemptTurn(options.turn);
32202
+ const ownerToken = randomUUID2();
32203
+ let claimed = false;
32204
+ mutateStore((document) => {
32205
+ const assignment = document.meta.version === PRIORITY_STORE_META_VERSION ? document.meta.priorityAssignments[options.routeKey] : undefined;
32206
+ if (priorityAssignmentGeneration(options.routeKey, assignment, document.meta) !== options.expectedAssignmentGeneration)
32207
+ return false;
32208
+ const existing = document.meta.version === PRIORITY_STORE_META_VERSION ? document.meta.priorityAttempts[options.routeKey] : undefined;
32209
+ if (existing) {
32210
+ const floor = Math.max(assignment?.lastHumanTurnIssuedAt ?? -1, existing.blockedTurnIssuedAt ?? -1, existing.pendingTurnIssuedAt ?? -1);
32211
+ if (!options.turn || options.turn.issuedAt <= floor)
32212
+ return false;
32213
+ } else if (document.meta.version === PRIORITY_STORE_META_VERSION && Object.keys(document.meta.priorityAttempts).length >= getMaxPriorityAttemptsLimit()) {
32214
+ return false;
32215
+ }
32216
+ if (document.meta.version === STORE_META_VERSION) {
32217
+ document.meta = {
32218
+ version: PRIORITY_STORE_META_VERSION,
32219
+ slots: document.meta.slots,
32220
+ priorityAssignments: {},
32221
+ priorityAttempts: {},
32222
+ priorityRollbackMappings: {}
32223
+ };
32224
+ }
32225
+ const previous = document.meta.priorityAttempts[options.routeKey];
32226
+ let blocked = previous?.blocked ?? false;
32227
+ let blockedTurnDigest = previous?.blockedTurnDigest ?? null;
32228
+ let blockedTurnIssuedAt = previous?.blockedTurnIssuedAt ?? null;
32229
+ if (previous?.ownerToken) {
32230
+ blocked = true;
32231
+ if (previous.pendingTurnIssuedAt !== null && (blockedTurnIssuedAt === null || previous.pendingTurnIssuedAt > blockedTurnIssuedAt)) {
32232
+ blockedTurnDigest = previous.pendingTurnDigest;
32233
+ blockedTurnIssuedAt = previous.pendingTurnIssuedAt;
32234
+ }
32235
+ }
32236
+ document.meta.priorityAttempts[options.routeKey] = {
32237
+ blocked,
32238
+ blockedTurnDigest,
32239
+ blockedTurnIssuedAt,
32240
+ pendingTurnDigest: options.turn?.turnId ?? null,
32241
+ pendingTurnIssuedAt: options.turn?.issuedAt ?? null,
32242
+ ownerToken,
32243
+ generationId: randomUUID2(),
32244
+ updatedAt: Date.now()
32245
+ };
32246
+ advanceKeySlot(`priority-attempt:${options.routeKey}`, document.meta);
32247
+ claimed = true;
32248
+ return true;
32249
+ });
32250
+ return claimed ? { ownerToken } : false;
32251
+ }
32252
+ function settlePriorityAttempt(routeKey, ownerToken, disposition) {
32253
+ if (!routeKey || routeKey.length > 512 || !UUID_PATTERN2.test(ownerToken))
32254
+ return false;
32255
+ let settled = false;
32256
+ mutateStore((document) => {
32257
+ if (document.meta.version !== PRIORITY_STORE_META_VERSION)
32258
+ return false;
32259
+ const attempt = document.meta.priorityAttempts[routeKey];
32260
+ if (!attempt || attempt.ownerToken !== ownerToken)
32261
+ return false;
32262
+ if (disposition === "block") {
32263
+ attempt.blocked = true;
32264
+ if (attempt.pendingTurnIssuedAt !== null && (attempt.blockedTurnIssuedAt === null || attempt.pendingTurnIssuedAt > attempt.blockedTurnIssuedAt)) {
32265
+ attempt.blockedTurnDigest = attempt.pendingTurnDigest;
32266
+ attempt.blockedTurnIssuedAt = attempt.pendingTurnIssuedAt;
32267
+ }
32268
+ attempt.pendingTurnDigest = null;
32269
+ attempt.pendingTurnIssuedAt = null;
32270
+ attempt.ownerToken = null;
32271
+ attempt.generationId = randomUUID2();
32272
+ attempt.updatedAt = Date.now();
32273
+ } else if (attempt.blocked) {
32274
+ attempt.pendingTurnDigest = null;
32275
+ attempt.pendingTurnIssuedAt = null;
32276
+ attempt.ownerToken = null;
32277
+ attempt.generationId = randomUUID2();
32278
+ attempt.updatedAt = Date.now();
32279
+ } else {
32280
+ delete document.meta.priorityAttempts[routeKey];
32281
+ }
32282
+ advanceKeySlot(`priority-attempt:${routeKey}`, document.meta);
32283
+ settled = true;
32284
+ return true;
32285
+ });
32286
+ return settled;
32287
+ }
32288
+ function releasePriorityAttempt(routeKey, ownerToken) {
32289
+ return settlePriorityAttempt(routeKey, ownerToken, "release");
32290
+ }
32291
+ function blockPriorityAttempt(routeKey, ownerToken) {
32292
+ return settlePriorityAttempt(routeKey, ownerToken, "block");
32293
+ }
32294
+ function validatePriorityPublicationInput(options) {
32295
+ if (!options.key || options.key.length > 1024)
32296
+ throw new Error("priority publication requires a bounded mapping key");
32297
+ if (!options.priority.routeKey || options.priority.routeKey.length > 512) {
32298
+ throw new Error("priority publication requires a bounded route key");
32299
+ }
32300
+ if (!options.priority.profileId || options.priority.profileId.length > 128) {
32301
+ throw new Error("priority publication requires a bounded profile ID");
32302
+ }
32303
+ if (!/^[A-Za-z0-9_-]{43}$/.test(options.priority.lastHumanTurnDigest)) {
32304
+ throw new Error("priority publication requires a valid human-turn digest");
32305
+ }
32306
+ if (!Number.isSafeInteger(options.priority.lastHumanTurnIssuedAt) || options.priority.lastHumanTurnIssuedAt < 0) {
32307
+ throw new Error("priority publication requires a valid human-turn issue time");
32308
+ }
32309
+ if (options.attemptOwnerToken !== undefined && !UUID_PATTERN2.test(options.attemptOwnerToken)) {
32310
+ throw new Error("priority publication requires a valid attempt owner token");
32311
+ }
32312
+ if (options.currentTranscript !== undefined)
32313
+ validateTranscriptLocator(options.currentTranscript, options.claudeSessionId);
32314
+ if (options.rollbackMappingKey !== undefined && (!options.rollbackMappingKey || options.rollbackMappingKey.length > 1024)) {
32315
+ throw new Error("priority publication requires a bounded rollback mapping key");
32316
+ }
32317
+ if (options.sourceTranscript !== undefined) {
32318
+ if (!isAbsolute4(options.sourceTranscript.configDir)) {
32319
+ throw new Error("sourceTranscript.configDir must be an absolute path");
32320
+ }
32321
+ if (options.sourceTranscript.projectDir !== undefined && !isAbsolute4(options.sourceTranscript.projectDir)) {
32322
+ throw new Error("sourceTranscript.projectDir must be an absolute path");
32323
+ }
32324
+ }
32325
+ }
32326
+ function storeSharedSessionAndPriorityAssignment(options) {
32327
+ validatePriorityPublicationInput(options);
32328
+ let result = false;
32329
+ mutateStore((document) => {
32330
+ const existing = document.sessions[options.key];
32331
+ const actualMappingGeneration = keyGeneration(options.key, existing, document.meta);
32332
+ if (actualMappingGeneration !== options.expectedMappingGeneration)
32333
+ return false;
32334
+ if (document.meta.version === PRIORITY_STORE_META_VERSION) {
32335
+ const markerOwners = Object.entries(document.meta.priorityRollbackMappings).filter(([, rollback]) => rollback.mappingKey === options.key);
32336
+ if (markerOwners.some(([routeKey]) => routeKey !== options.priority.routeKey))
32337
+ return false;
32338
+ const ownMarker = document.meta.priorityRollbackMappings[options.priority.routeKey];
32339
+ if (ownMarker?.mappingKey === options.key && ownMarker.mappingGeneration !== actualMappingGeneration)
32340
+ return false;
32341
+ }
32342
+ const existingAssignments = document.meta.version === PRIORITY_STORE_META_VERSION ? document.meta.priorityAssignments : {};
32343
+ const existingAssignment = existingAssignments[options.priority.routeKey];
32344
+ const actualAssignmentGeneration = priorityAssignmentGeneration(options.priority.routeKey, existingAssignment, document.meta);
32345
+ if (actualAssignmentGeneration !== options.priority.expectedAssignmentGeneration)
32346
+ return false;
32347
+ const existingAttempt = document.meta.version === PRIORITY_STORE_META_VERSION ? document.meta.priorityAttempts[options.priority.routeKey] : undefined;
32348
+ if (options.attemptOwnerToken !== undefined) {
32349
+ if (existingAttempt?.ownerToken !== options.attemptOwnerToken)
32350
+ return false;
32351
+ } else if (existingAttempt) {
32352
+ return false;
32353
+ }
32354
+ const sessionIdChanged = existing !== undefined && existing.claudeSessionId !== options.claudeSessionId;
32355
+ if (options.sourceTranscript !== undefined) {
32356
+ if (!sessionIdChanged || options.sourceTranscript.sessionId !== existing?.claudeSessionId) {
32357
+ throw new Error("sourceTranscript.sessionId must match the replaced claudeSessionId");
32358
+ }
32359
+ }
32360
+ const previousClaudeSessionId = sessionIdChanged ? existing.claudeSessionId : existing?.previousClaudeSessionId;
32361
+ const resolvedCurrentTranscript = sessionIdChanged ? options.currentTranscript : existing?.currentTranscript ?? options.currentTranscript;
32362
+ const previousTranscript = sessionIdChanged ? existing?.currentTranscript ?? options.sourceTranscript : existing?.previousTranscript;
32363
+ const stored = {
32364
+ claudeSessionId: options.claudeSessionId,
32365
+ revision: (existing?.revision ?? 0) + 1,
32366
+ generationId: randomUUID2(),
32367
+ createdAt: existing?.createdAt || Date.now(),
32368
+ lastUsedAt: Date.now(),
32369
+ messageCount: options.messageCount,
32370
+ lineageHash: options.lineageHash,
32371
+ messageHashes: options.messageHashes,
32372
+ messageBlockHashes: options.messageBlockHashes,
32373
+ sdkMessageUuids: options.sdkMessageUuids,
32374
+ passthroughToolCallAssistantUuid: options.passthroughToolCallAssistantUuid ?? undefined,
32375
+ passthroughToolCallIds: options.passthroughToolCallIds ?? undefined,
32376
+ contextUsage: options.contextUsage,
32377
+ ...resolvedCurrentTranscript ? { currentTranscript: resolvedCurrentTranscript } : {},
32378
+ ...previousTranscript ? { previousTranscript } : {},
32379
+ ...previousClaudeSessionId ? { previousClaudeSessionId } : {}
32380
+ };
32381
+ document.sessions[options.key] = stored;
32382
+ advanceKeySlot(options.key, document.meta);
32383
+ const mappingGeneration = getStoredSessionGeneration(stored, options.key);
32384
+ if (document.meta.version === STORE_META_VERSION) {
32385
+ document.meta = {
32386
+ version: PRIORITY_STORE_META_VERSION,
32387
+ slots: document.meta.slots,
32388
+ priorityAssignments: {},
32389
+ priorityAttempts: {},
32390
+ priorityRollbackMappings: {}
32391
+ };
32392
+ }
32393
+ const assignment = {
32394
+ profileId: options.priority.profileId,
32395
+ lastHumanTurnDigest: options.priority.lastHumanTurnDigest,
32396
+ lastHumanTurnIssuedAt: options.priority.lastHumanTurnIssuedAt,
32397
+ mappingKey: options.key,
32398
+ mappingGeneration,
32399
+ generationId: randomUUID2(),
32400
+ updatedAt: Date.now()
32401
+ };
32402
+ const priorityAssignments = document.meta.priorityAssignments;
32403
+ const priorityRollbackMappings = document.meta.priorityRollbackMappings;
32404
+ priorityAssignments[options.priority.routeKey] = assignment;
32405
+ const existingRollback = priorityRollbackMappings[options.priority.routeKey];
32406
+ const rollbackMappingKey = options.rollbackMappingKey ?? existingAssignment?.mappingKey;
32407
+ if (rollbackMappingKey && rollbackMappingKey !== options.key) {
32408
+ const rollbackMapping = document.sessions[rollbackMappingKey];
32409
+ if (!rollbackMapping) {
32410
+ throw new Error("priority rollback mapping disappeared before publication");
32411
+ }
32412
+ const rollbackMappingGeneration = getStoredSessionGeneration(rollbackMapping, rollbackMappingKey);
32413
+ if (existingAssignment?.mappingKey === rollbackMappingKey && existingAssignment.mappingGeneration !== rollbackMappingGeneration)
32414
+ return false;
32415
+ priorityRollbackMappings[options.priority.routeKey] = existingRollback?.mappingKey === rollbackMappingKey ? existingRollback : { mappingKey: rollbackMappingKey, mappingGeneration: rollbackMappingGeneration };
32416
+ } else {
32417
+ delete priorityRollbackMappings[options.priority.routeKey];
32418
+ }
32419
+ advanceKeySlot(priorityGenerationKey(options.priority.routeKey), document.meta);
32420
+ const maxSessions = getMaxStoredSessionsLimit();
32421
+ const maxAssignments = getMaxPriorityAssignmentsLimit();
32422
+ const referencedMappingKeys = () => new Set(Object.values(priorityAssignments).map((candidate) => candidate.mappingKey));
32423
+ const sortedRoutes = Object.keys(priorityAssignments).filter((candidate) => candidate !== options.priority.routeKey && priorityRollbackMappings[candidate] === undefined).sort((left, right) => priorityAssignments[left].updatedAt - priorityAssignments[right].updatedAt);
32424
+ while (Object.keys(priorityAssignments).length > maxAssignments || referencedMappingKeys().size > maxSessions) {
32425
+ const candidate = sortedRoutes.shift();
32426
+ if (!candidate)
32427
+ return false;
32428
+ delete priorityAssignments[candidate];
32429
+ delete priorityRollbackMappings[candidate];
32430
+ advanceKeySlot(priorityGenerationKey(candidate), document.meta);
32431
+ }
32432
+ const protectedMappings = referencedMappingKeys();
32433
+ protectedMappings.add(options.key);
32434
+ for (const rollback of Object.values(priorityRollbackMappings)) {
32435
+ protectedMappings.add(rollback.mappingKey);
32436
+ }
32437
+ const protectedExistingCount = [...protectedMappings].filter((candidate) => document.sessions[candidate] !== undefined).length;
32438
+ const retainedSessionLimit = Math.max(maxSessions, protectedExistingCount);
32439
+ const sortedSessions = Object.keys(document.sessions).filter((candidate) => !protectedMappings.has(candidate)).sort((left, right) => document.sessions[left].lastUsedAt - document.sessions[right].lastUsedAt);
32440
+ while (Object.keys(document.sessions).length > retainedSessionLimit) {
32441
+ const candidate = sortedSessions.shift();
32442
+ if (!candidate)
32443
+ break;
32444
+ delete document.sessions[candidate];
32445
+ advanceKeySlot(candidate, document.meta);
32446
+ }
32447
+ result = {
32448
+ mappingGeneration,
32449
+ assignmentGeneration: getPriorityAssignmentGeneration(assignment, options.priority.routeKey),
32450
+ previousMapping: existing ? structuredClone(existing) : null,
32451
+ previousAssignment: existingAssignment ? structuredClone(existingAssignment) : null
32452
+ };
32453
+ return true;
32454
+ });
32455
+ return result;
32456
+ }
32457
+ function finalizeSharedSessionAndPriorityAssignment(options) {
32458
+ let finalized = false;
32459
+ mutateStore((document) => {
32460
+ if (document.meta.version !== PRIORITY_STORE_META_VERSION)
32461
+ return false;
32462
+ const mapping = document.sessions[options.key];
32463
+ if (keyGeneration(options.key, mapping, document.meta) !== options.expectedMappingGeneration)
32464
+ return false;
32465
+ const assignment = document.meta.priorityAssignments[options.routeKey];
32466
+ if (!assignment || priorityAssignmentGeneration(options.routeKey, assignment, document.meta) !== options.expectedAssignmentGeneration)
32467
+ return false;
32468
+ const rollback = document.meta.priorityRollbackMappings[options.routeKey];
32469
+ if (rollback?.mappingKey !== options.rollbackMappingKey)
32470
+ return false;
32471
+ const attempt = document.meta.priorityAttempts[options.routeKey];
32472
+ if (options.attemptOwnerToken !== undefined) {
32473
+ if (attempt?.ownerToken !== options.attemptOwnerToken)
32474
+ return false;
32475
+ } else if (attempt)
32476
+ return false;
32477
+ delete document.meta.priorityRollbackMappings[options.routeKey];
32478
+ if (options.attemptOwnerToken !== undefined) {
32479
+ delete document.meta.priorityAttempts[options.routeKey];
32480
+ advanceKeySlot(`priority-attempt:${options.routeKey}`, document.meta);
32481
+ }
32482
+ assignment.generationId = randomUUID2();
32483
+ assignment.updatedAt = Date.now();
32484
+ advanceKeySlot(priorityGenerationKey(options.routeKey), document.meta);
32485
+ const protectedMappings = new Set([
32486
+ ...Object.values(document.meta.priorityAssignments).map((candidate) => candidate.mappingKey),
32487
+ ...Object.values(document.meta.priorityRollbackMappings).map((rollback2) => rollback2.mappingKey)
32488
+ ]);
32489
+ const maxSessions = getMaxStoredSessionsLimit();
32490
+ const protectedExistingCount = [...protectedMappings].filter((candidate) => document.sessions[candidate] !== undefined).length;
32491
+ const retainedLimit = Math.max(maxSessions, protectedExistingCount);
32492
+ const removable = Object.keys(document.sessions).filter((candidate) => !protectedMappings.has(candidate)).sort((left, right) => document.sessions[left].lastUsedAt - document.sessions[right].lastUsedAt);
32493
+ while (Object.keys(document.sessions).length > retainedLimit) {
32494
+ const candidate = removable.shift();
32495
+ if (!candidate)
32496
+ break;
32497
+ delete document.sessions[candidate];
32498
+ advanceKeySlot(candidate, document.meta);
32499
+ }
32500
+ finalized = true;
32501
+ return true;
32502
+ });
32503
+ return finalized;
32504
+ }
32505
+ function rollbackSharedSessionAndPriorityAssignment(options) {
32506
+ let result = false;
32507
+ mutateStore((document) => {
32508
+ if (document.meta.version !== PRIORITY_STORE_META_VERSION)
32509
+ return false;
32510
+ const currentMapping = document.sessions[options.key];
32511
+ if (keyGeneration(options.key, currentMapping, document.meta) !== options.expectedMappingGeneration)
32512
+ return false;
32513
+ const currentAssignment = document.meta.priorityAssignments[options.routeKey];
32514
+ if (priorityAssignmentGeneration(options.routeKey, currentAssignment, document.meta) !== options.expectedAssignmentGeneration)
32515
+ return false;
32516
+ const attempt = document.meta.priorityAttempts[options.routeKey];
32517
+ if (options.attemptOwnerToken !== undefined) {
32518
+ if (attempt?.ownerToken !== options.attemptOwnerToken)
32519
+ return false;
32520
+ } else if (attempt)
32521
+ return false;
32522
+ const expectedRollback = options.previousAssignment && options.previousAssignment.mappingKey !== options.key ? {
32523
+ mappingKey: options.previousAssignment.mappingKey,
32524
+ mappingGeneration: options.previousAssignment.mappingGeneration
32525
+ } : undefined;
32526
+ const actualRollback = document.meta.priorityRollbackMappings[options.routeKey];
32527
+ if (actualRollback?.mappingKey !== expectedRollback?.mappingKey || actualRollback?.mappingGeneration !== expectedRollback?.mappingGeneration)
32528
+ return false;
32529
+ let restoredMapping = null;
32530
+ if (options.previousMapping) {
32531
+ restoredMapping = {
32532
+ ...structuredClone(options.previousMapping),
32533
+ revision: (options.previousMapping.revision ?? 0) + 1,
32534
+ generationId: randomUUID2()
32535
+ };
32536
+ document.sessions[options.key] = restoredMapping;
32537
+ } else {
32538
+ delete document.sessions[options.key];
32539
+ }
32540
+ advanceKeySlot(options.key, document.meta);
32541
+ const mappingGeneration = keyGeneration(options.key, restoredMapping ?? undefined, document.meta);
32542
+ let restoredAssignment = null;
32543
+ if (options.previousAssignment) {
32544
+ restoredAssignment = {
32545
+ ...structuredClone(options.previousAssignment),
32546
+ mappingGeneration: options.previousAssignment.mappingKey === options.key ? mappingGeneration : options.previousAssignment.mappingGeneration,
32547
+ generationId: randomUUID2(),
32548
+ updatedAt: Date.now()
32549
+ };
32550
+ document.meta.priorityAssignments[options.routeKey] = restoredAssignment;
32551
+ } else {
32552
+ delete document.meta.priorityAssignments[options.routeKey];
32553
+ }
32554
+ delete document.meta.priorityRollbackMappings[options.routeKey];
32555
+ advanceKeySlot(priorityGenerationKey(options.routeKey), document.meta);
32556
+ const assignmentGeneration = priorityAssignmentGeneration(options.routeKey, restoredAssignment ?? undefined, document.meta);
32557
+ result = {
32558
+ mappingGeneration,
32559
+ assignmentGeneration,
32560
+ restoredMapping,
32561
+ restoredAssignment
32562
+ };
32563
+ return true;
32564
+ });
32565
+ return result;
32566
+ }
31941
32567
  function sameTranscriptLocator(left, right) {
31942
32568
  return left?.sessionId === right.sessionId && left.configDir === right.configDir && left.projectDir === right.projectDir && left.lifecycleGeneration === right.lifecycleGeneration;
31943
32569
  }
@@ -31945,6 +32571,8 @@ function attachSharedTranscriptLocator(key, expectedClaudeSessionId, locator, ex
31945
32571
  validateTranscriptLocator(locator, expectedClaudeSessionId);
31946
32572
  let attachedGeneration = false;
31947
32573
  mutateStore(({ sessions: store, meta: meta3 }) => {
32574
+ if (isPriorityRollbackMapping(meta3, key))
32575
+ return false;
31948
32576
  const existing = store[key];
31949
32577
  if (!existing || existing.claudeSessionId !== expectedClaudeSessionId)
31950
32578
  return false;
@@ -31955,8 +32583,20 @@ function attachSharedTranscriptLocator(key, expectedClaudeSessionId, locator, ex
31955
32583
  existing.revision = (existing.revision ?? 0) + 1;
31956
32584
  existing.generationId = randomUUID2();
31957
32585
  advanceKeySlot(key, meta3);
32586
+ attachedGeneration = getStoredSessionGeneration(existing, key);
32587
+ if (meta3.version === PRIORITY_STORE_META_VERSION) {
32588
+ for (const [routeKey, assignment] of Object.entries(meta3.priorityAssignments)) {
32589
+ if (assignment.mappingKey !== key)
32590
+ continue;
32591
+ assignment.mappingGeneration = attachedGeneration;
32592
+ assignment.generationId = randomUUID2();
32593
+ assignment.updatedAt = Date.now();
32594
+ advanceKeySlot(priorityGenerationKey(routeKey), meta3);
32595
+ }
32596
+ }
32597
+ } else {
32598
+ attachedGeneration = getStoredSessionGeneration(existing, key);
31958
32599
  }
31959
- attachedGeneration = getStoredSessionGeneration(existing, key);
31960
32600
  return true;
31961
32601
  });
31962
32602
  return attachedGeneration;
@@ -31971,6 +32611,8 @@ function evictSharedSession(key, expectedGeneration) {
31971
32611
  }
31972
32612
  if (expectedGeneration !== undefined && getStoredSessionGeneration(existing, key) !== expectedGeneration)
31973
32613
  return false;
32614
+ if (isPriorityRollbackMapping(meta3, key))
32615
+ return false;
31974
32616
  delete store[key];
31975
32617
  advanceKeySlot(key, meta3);
31976
32618
  evicted = true;
@@ -32008,6 +32650,17 @@ function clearSharedSessions() {
32008
32650
  delete store[key];
32009
32651
  advanceKeySlot(key, meta3);
32010
32652
  }
32653
+ if (meta3.version === PRIORITY_STORE_META_VERSION) {
32654
+ for (const routeKey of Object.keys(meta3.priorityAssignments)) {
32655
+ delete meta3.priorityAssignments[routeKey];
32656
+ delete meta3.priorityRollbackMappings[routeKey];
32657
+ advanceKeySlot(priorityGenerationKey(routeKey), meta3);
32658
+ }
32659
+ for (const routeKey of Object.keys(meta3.priorityAttempts)) {
32660
+ delete meta3.priorityAttempts[routeKey];
32661
+ advanceKeySlot(`priority-attempt:${routeKey}`, meta3);
32662
+ }
32663
+ }
32011
32664
  return true;
32012
32665
  });
32013
32666
  }
@@ -32110,6 +32763,56 @@ function stateFromSharedSession(shared) {
32110
32763
  previousTranscript: shared.previousTranscript
32111
32764
  };
32112
32765
  }
32766
+ function finalizePrioritySessionPublication(publication) {
32767
+ const rollback = publication.rollback;
32768
+ if (!rollback)
32769
+ return true;
32770
+ const finalized = finalizeSharedSessionAndPriorityAssignment({
32771
+ key: rollback.key,
32772
+ routeKey: publication.routeKey,
32773
+ expectedMappingGeneration: rollback.publishedMappingGeneration,
32774
+ expectedAssignmentGeneration: rollback.publishedAssignmentGeneration,
32775
+ rollbackMappingKey: rollback.previousAssignment?.mappingKey === rollback.key ? undefined : rollback.previousAssignment?.mappingKey,
32776
+ attemptOwnerToken: publication.attemptOwnerToken
32777
+ });
32778
+ if (!finalized)
32779
+ return false;
32780
+ publication.rollback = undefined;
32781
+ return true;
32782
+ }
32783
+ function rollbackPrioritySessionPublication(sessionId, messages, workingDirectory, publication) {
32784
+ const rollback = publication.rollback;
32785
+ if (!rollback)
32786
+ return false;
32787
+ const restored = rollbackSharedSessionAndPriorityAssignment({
32788
+ key: rollback.key,
32789
+ routeKey: publication.routeKey,
32790
+ expectedMappingGeneration: rollback.publishedMappingGeneration,
32791
+ expectedAssignmentGeneration: rollback.publishedAssignmentGeneration,
32792
+ previousMapping: rollback.previousMapping,
32793
+ previousAssignment: rollback.previousAssignment,
32794
+ attemptOwnerToken: publication.attemptOwnerToken
32795
+ });
32796
+ if (!restored)
32797
+ return false;
32798
+ publication.expectedAssignmentGeneration = restored.assignmentGeneration;
32799
+ publication.rollback = undefined;
32800
+ if (sessionId) {
32801
+ if (restored.restoredMapping)
32802
+ sessionCache.set(sessionId, stateFromSharedSession(restored.restoredMapping));
32803
+ else
32804
+ sessionCache.delete(sessionId);
32805
+ } else {
32806
+ const fingerprint = getConversationFingerprint(messages, workingDirectory);
32807
+ if (fingerprint) {
32808
+ if (restored.restoredMapping)
32809
+ fingerprintCache.set(fingerprint, stateFromSharedSession(restored.restoredMapping));
32810
+ else
32811
+ fingerprintCache.delete(fingerprint);
32812
+ }
32813
+ }
32814
+ return restored.mappingGeneration;
32815
+ }
32113
32816
  function classifyLineage(state, messages, cacheKey2) {
32114
32817
  const result = verifyLineage(state, messages);
32115
32818
  if (result.type === "continuation" && result.resumeContentFrom !== undefined) {
@@ -32187,7 +32890,7 @@ function getSessionByClaudeId(claudeSessionId) {
32187
32890
  }
32188
32891
  return stateFromSharedSession(shared.session);
32189
32892
  }
32190
- function storeSession(sessionId, messages, claudeSessionId, workingDirectory, sdkMessageUuids, contextUsage, passthroughToolCallAssistantUuid, passthroughToolCallIds, currentTranscript, sourceTranscript, expectedGeneration) {
32893
+ function storeSession(sessionId, messages, claudeSessionId, workingDirectory, sdkMessageUuids, contextUsage, passthroughToolCallAssistantUuid, passthroughToolCallIds, currentTranscript, sourceTranscript, expectedGeneration, priorityPublication) {
32191
32894
  if (!claudeSessionId)
32192
32895
  return false;
32193
32896
  const lineageHash = computeLineageHash(messages);
@@ -32211,7 +32914,53 @@ function storeSession(sessionId, messages, claudeSessionId, workingDirectory, sd
32211
32914
  const key = sessionId || fp;
32212
32915
  if (!key)
32213
32916
  return false;
32214
- const storedGeneration = storeSharedSession(key, claudeSessionId, state.messageCount, lineageHash, messageHashes, sdkMessageUuids, contextUsage, messageBlockHashes, passthroughToolCallAssistantUuid ?? null, passthroughToolCallIds ?? null, currentTranscript, sourceTranscript, expectedGeneration);
32917
+ let storedGeneration;
32918
+ if (priorityPublication) {
32919
+ if (expectedGeneration === undefined || expectedGeneration === null) {
32920
+ throw new Error("priority publication requires an exact mapping generation");
32921
+ }
32922
+ const rollback = priorityPublication.rollback;
32923
+ if (rollback && rollback.key !== key) {
32924
+ throw new Error("priority publication changed mapping keys within one request");
32925
+ }
32926
+ const published = storeSharedSessionAndPriorityAssignment({
32927
+ key,
32928
+ claudeSessionId,
32929
+ messageCount: state.messageCount,
32930
+ lineageHash,
32931
+ messageHashes,
32932
+ sdkMessageUuids,
32933
+ contextUsage,
32934
+ messageBlockHashes,
32935
+ passthroughToolCallAssistantUuid: passthroughToolCallAssistantUuid ?? null,
32936
+ passthroughToolCallIds: passthroughToolCallIds ?? null,
32937
+ currentTranscript,
32938
+ sourceTranscript,
32939
+ expectedMappingGeneration: expectedGeneration,
32940
+ rollbackMappingKey: rollback?.previousAssignment?.mappingKey,
32941
+ attemptOwnerToken: priorityPublication.attemptOwnerToken,
32942
+ priority: {
32943
+ routeKey: priorityPublication.routeKey,
32944
+ profileId: priorityPublication.profileId,
32945
+ lastHumanTurnDigest: priorityPublication.lastHumanTurnDigest,
32946
+ lastHumanTurnIssuedAt: priorityPublication.lastHumanTurnIssuedAt,
32947
+ expectedAssignmentGeneration: priorityPublication.expectedAssignmentGeneration
32948
+ }
32949
+ });
32950
+ if (!published)
32951
+ return false;
32952
+ priorityPublication.rollback = {
32953
+ key,
32954
+ previousMapping: rollback?.previousMapping ?? published.previousMapping,
32955
+ previousAssignment: rollback?.previousAssignment ?? published.previousAssignment,
32956
+ publishedMappingGeneration: published.mappingGeneration,
32957
+ publishedAssignmentGeneration: published.assignmentGeneration
32958
+ };
32959
+ priorityPublication.expectedAssignmentGeneration = published.assignmentGeneration;
32960
+ storedGeneration = published.mappingGeneration;
32961
+ } else {
32962
+ storedGeneration = storeSharedSession(key, claudeSessionId, state.messageCount, lineageHash, messageHashes, sdkMessageUuids, contextUsage, messageBlockHashes, passthroughToolCallAssistantUuid ?? null, passthroughToolCallIds ?? null, currentTranscript, sourceTranscript, expectedGeneration);
32963
+ }
32215
32964
  if (!storedGeneration)
32216
32965
  return false;
32217
32966
  if (sessionId)
@@ -32281,6 +33030,15 @@ class SessionTurnCoordinator {
32281
33030
  committedScopes.add(scopeKey);
32282
33031
  state.versions.set(scopeKey, (state.versions.get(scopeKey) ?? 0) + 1);
32283
33032
  },
33033
+ markRolledBack: (scopeKey) => {
33034
+ if (released || !committedScopes.delete(scopeKey))
33035
+ return;
33036
+ const current = state.versions.get(scopeKey) ?? 0;
33037
+ if (current <= 1)
33038
+ state.versions.delete(scopeKey);
33039
+ else
33040
+ state.versions.set(scopeKey, current - 1);
33041
+ },
32284
33042
  release: () => {
32285
33043
  if (released)
32286
33044
  return;
@@ -34853,7 +35611,18 @@ function createProxyServer(config2 = {}) {
34853
35611
  }
34854
35612
  if (failure) {
34855
35613
  await reader.cancel().catch(() => {});
34856
- return { failed: true, errorPayload: failure.payload, errorType: failure.type, response: res };
35614
+ const replay = new ReadableStream({
35615
+ start(ctrl) {
35616
+ for (const chunk of consumed)
35617
+ ctrl.enqueue(chunk);
35618
+ ctrl.close();
35619
+ }
35620
+ });
35621
+ const response2 = new Response(replay, { status: res.status, headers: res.headers });
35622
+ const completion2 = responseCompletions.get(res);
35623
+ if (completion2)
35624
+ responseCompletions.set(response2, completion2);
35625
+ return { failed: true, errorPayload: failure.payload, errorType: failure.type, response: response2 };
34857
35626
  }
34858
35627
  const rest = new ReadableStream({
34859
35628
  start(ctrl) {
@@ -34877,23 +35646,84 @@ function createProxyServer(config2 = {}) {
34877
35646
  responseCompletions.set(response, completion);
34878
35647
  return { failed: false, errorPayload: null, errorType: null, response };
34879
35648
  }
34880
- async function dispatchPriority(c, body, requestMeta, orderedCandidateIds, sessionKey, wantsStream, turnWatchdogSignal) {
35649
+ async function dispatchPriority(options) {
35650
+ let attemptOwnerToken;
35651
+ if (options.durableRoute && options.publicationTurn) {
35652
+ try {
35653
+ const claim = claimPriorityAttempt({
35654
+ routeKey: options.durableRoute.routeKey,
35655
+ expectedAssignmentGeneration: options.durableRoute.expectedGeneration,
35656
+ turn: options.claimTurn
35657
+ });
35658
+ if (!claim) {
35659
+ return options.context.json({
35660
+ type: "error",
35661
+ error: { type: "overloaded_error", message: "Durable priority attempt state is unavailable" }
35662
+ }, 503);
35663
+ }
35664
+ attemptOwnerToken = claim.ownerToken;
35665
+ } catch (error51) {
35666
+ claudeLog("priority.attempt_claim_failed", {
35667
+ routeKey: options.durableRoute.routeKey,
35668
+ error: error51 instanceof Error ? error51.message : String(error51)
35669
+ });
35670
+ return options.context.json({
35671
+ type: "error",
35672
+ error: { type: "overloaded_error", message: "Durable priority attempt state is unavailable" }
35673
+ }, 503);
35674
+ }
35675
+ }
35676
+ const settleAttempt = (disposition) => {
35677
+ if (!attemptOwnerToken || !options.durableRoute)
35678
+ return true;
35679
+ try {
35680
+ return disposition === "block" ? blockPriorityAttempt(options.durableRoute.routeKey, attemptOwnerToken) : releasePriorityAttempt(options.durableRoute.routeKey, attemptOwnerToken);
35681
+ } catch (error51) {
35682
+ claudeLog("priority.attempt_settle_failed", {
35683
+ routeKey: options.durableRoute.routeKey,
35684
+ disposition,
35685
+ error: error51 instanceof Error ? error51.message : String(error51)
35686
+ });
35687
+ return false;
35688
+ }
35689
+ };
35690
+ const unavailableAttemptResponse = () => options.context.json({
35691
+ type: "error",
35692
+ error: { type: "overloaded_error", message: "Durable priority attempt state is unavailable" }
35693
+ }, 503);
34881
35694
  let lastError = null;
34882
35695
  let lastStatus = 429;
34883
35696
  let previous = null;
34884
35697
  let previousReason = "rate_limit_error";
34885
- for (const [attempt, candidate] of orderedCandidateIds.entries()) {
34886
- const inner = await handleMessages(c, forkAttemptMeta(requestMeta, attempt), {
34887
- body,
35698
+ for (const [attempt, candidate] of options.candidateIds.entries()) {
35699
+ const exposure = { committed: false };
35700
+ const priorityPublication = options.durableRoute && options.publicationTurn ? {
35701
+ routeKey: options.durableRoute.routeKey,
35702
+ profileId: candidate,
35703
+ lastHumanTurnDigest: options.publicationTurn.turnId,
35704
+ lastHumanTurnIssuedAt: options.publicationTurn.issuedAt,
35705
+ attemptOwnerToken,
35706
+ expectedAssignmentGeneration: options.durableRoute.expectedGeneration
35707
+ } : undefined;
35708
+ const inner = await handleMessages(options.context, forkAttemptMeta(options.requestMeta, attempt), {
35709
+ body: options.body,
34888
35710
  forcedProfileId: candidate,
34889
- turnWatchdogSignal
35711
+ turnWatchdogSignal: options.turnWatchdogSignal,
35712
+ forceFreshPriorityReplay: priorityPublication !== undefined && (options.durableRoute?.forceFreshReplay === true || options.currentProfileId !== undefined && candidate !== options.currentProfileId),
35713
+ priorityPublication,
35714
+ priorityAttemptExposure: exposure
34890
35715
  });
34891
35716
  const sniffed = await sniffAccountFailure(inner);
34892
35717
  if (!sniffed.failed) {
34893
- if (sessionKey)
34894
- priorityAssignments.set(sessionKey, candidate);
35718
+ if (options.sessionKey && !options.durableRoute) {
35719
+ const previousAssignment = priorityAssignments.get(options.sessionKey);
35720
+ priorityAssignments.set(options.sessionKey, {
35721
+ profileId: candidate,
35722
+ requestId: options.publicationTurn?.turnId ?? previousAssignment?.requestId
35723
+ });
35724
+ }
34895
35725
  if (previous) {
34896
- claudeLog("profile.failover", { from: previous, to: candidate, reason: previousReason, sessionKey });
35726
+ claudeLog("profile.failover", { from: previous, to: candidate, reason: previousReason, sessionKey: options.sessionKey });
34897
35727
  plog(`[PROXY] PRIORITY failover ${previous} -> ${candidate} (${previousReason})`);
34898
35728
  }
34899
35729
  return sniffed.response;
@@ -34910,8 +35740,16 @@ function createProxyServer(config2 = {}) {
34910
35740
  lastStatus = inner.status;
34911
35741
  previous = candidate;
34912
35742
  previousReason = reason;
35743
+ if (exposure.committed) {
35744
+ claudeLog("priority.failover_withheld", { profile: candidate, reason: exposure.reason ?? "attempt_exposed" });
35745
+ if (!settleAttempt("block"))
35746
+ return unavailableAttemptResponse();
35747
+ return sniffed.response;
35748
+ }
34913
35749
  }
34914
- if (wantsStream) {
35750
+ if (!settleAttempt("release"))
35751
+ return unavailableAttemptResponse();
35752
+ if (options.wantsStream) {
34915
35753
  return new Response(`event: error
34916
35754
  data: ${JSON.stringify(lastError)}
34917
35755
 
@@ -34950,18 +35788,85 @@ data: ${JSON.stringify(lastError)}
34950
35788
  }
34951
35789
  };
34952
35790
  let resumedMappingMayBeAdvanced = false;
35791
+ let priorityTerminalCommitted = false;
35792
+ let recoveryPublishedTarget;
35793
+ let priorityRollbackRetirement;
34953
35794
  const evictSession2 = (...args) => {
34954
35795
  try {
35796
+ if (priorityTerminalCommitted && options.priorityPublication)
35797
+ return true;
35798
+ if (options.priorityPublication?.rollback) {
35799
+ const rollbackScopeKey = options.priorityPublication.rollback.key;
35800
+ const restoredGeneration = rollbackPrioritySessionPublication(args[0], args[2] ?? options.body.messages ?? [], args[1], options.priorityPublication);
35801
+ if (!restoredGeneration) {
35802
+ requestMeta.retainSessionTurnFence?.();
35803
+ return false;
35804
+ }
35805
+ requestMeta.sessionTurnLease?.markRolledBack(rollbackScopeKey);
35806
+ resumedMappingMayBeAdvanced = false;
35807
+ const retirements = [];
35808
+ if (managedForkTarget && managedForkPublished) {
35809
+ managedForkPublished = false;
35810
+ retirements.push(abandonManagedFork("priority_publication_rollback"));
35811
+ }
35812
+ if (recoveryPublishedTarget) {
35813
+ const recoveryTarget = recoveryPublishedTarget;
35814
+ recoveryPublishedTarget = undefined;
35815
+ retirements.push(abandonFork(recoveryTarget, sessionGcOptions).catch((error51) => {
35816
+ claudeLog("session.fork_abandon_failed", {
35817
+ reason: "priority_recovery_publication_rollback",
35818
+ error: error51 instanceof Error ? error51.message : String(error51)
35819
+ });
35820
+ }));
35821
+ }
35822
+ if (retirements.length > 0) {
35823
+ const pending = Promise.all(retirements).then(() => {
35824
+ return;
35825
+ });
35826
+ priorityRollbackRetirement = priorityRollbackRetirement ? Promise.all([priorityRollbackRetirement, pending]).then(() => {
35827
+ return;
35828
+ }) : pending;
35829
+ }
35830
+ return true;
35831
+ }
35832
+ if (options.priorityPublication) {
35833
+ return false;
35834
+ }
34955
35835
  const evicted = evictSession(...args);
34956
35836
  if (!evicted && resumedMappingMayBeAdvanced) {
34957
35837
  requestMeta.retainSessionTurnFence?.();
34958
35838
  }
34959
- if (evicted)
35839
+ if (evicted) {
34960
35840
  resumedMappingMayBeAdvanced = false;
35841
+ const retirements = [];
35842
+ if (managedForkTarget && managedForkPublished) {
35843
+ managedForkPublished = false;
35844
+ retirements.push(abandonManagedFork("mapping_evicted_after_publication"));
35845
+ }
35846
+ if (recoveryPublishedTarget) {
35847
+ const recoveryTarget = recoveryPublishedTarget;
35848
+ recoveryPublishedTarget = undefined;
35849
+ retirements.push(abandonFork(recoveryTarget, sessionGcOptions).catch((error51) => {
35850
+ claudeLog("session.fork_abandon_failed", {
35851
+ reason: "recovery_mapping_evicted_after_publication",
35852
+ error: error51 instanceof Error ? error51.message : String(error51)
35853
+ });
35854
+ }));
35855
+ }
35856
+ if (retirements.length > 0) {
35857
+ const pending = Promise.all(retirements).then(() => {
35858
+ return;
35859
+ });
35860
+ priorityRollbackRetirement = priorityRollbackRetirement ? Promise.all([priorityRollbackRetirement, pending]).then(() => {
35861
+ return;
35862
+ }) : pending;
35863
+ }
35864
+ }
34961
35865
  return evicted;
34962
35866
  } catch (error51) {
34963
- if (resumedMappingMayBeAdvanced)
35867
+ if (resumedMappingMayBeAdvanced || options.priorityPublication?.rollback) {
34964
35868
  requestMeta.retainSessionTurnFence?.();
35869
+ }
34965
35870
  throw error51;
34966
35871
  }
34967
35872
  };
@@ -34970,6 +35875,7 @@ data: ${JSON.stringify(lastError)}
34970
35875
  let managedForkCommitted = false;
34971
35876
  let managedForkPublished = false;
34972
35877
  let managedForkAbandoned = false;
35878
+ let managedForkAbandonment;
34973
35879
  let managedForkSuperseded = false;
34974
35880
  let managedFreshTarget = false;
34975
35881
  let unexpectedManagedForkTarget;
@@ -34978,30 +35884,36 @@ data: ${JSON.stringify(lastError)}
34978
35884
  releaseManagedForkPins?.();
34979
35885
  releaseManagedForkPins = undefined;
34980
35886
  };
34981
- const abandonManagedFork = async (reason) => {
34982
- if (unexpectedManagedForkTarget) {
34983
- const unexpected = unexpectedManagedForkTarget;
34984
- unexpectedManagedForkTarget = undefined;
34985
- await registerLiveTranscript(unexpected, sessionGcOptions).then((exact) => abandonFork(exact, sessionGcOptions)).catch((error51) => {
34986
- claudeLog("session.unexpected_fork_track_failed", {
34987
- reason,
34988
- sessionId: unexpected.sessionId,
34989
- error: error51 instanceof Error ? error51.message : String(error51)
35887
+ const abandonManagedFork = (reason) => {
35888
+ if (managedForkAbandonment)
35889
+ return managedForkAbandonment;
35890
+ const pending = (async () => {
35891
+ if (unexpectedManagedForkTarget) {
35892
+ const unexpected = unexpectedManagedForkTarget;
35893
+ unexpectedManagedForkTarget = undefined;
35894
+ await registerLiveTranscript(unexpected, sessionGcOptions).then((exact) => abandonFork(exact, sessionGcOptions)).catch((error51) => {
35895
+ claudeLog("session.unexpected_fork_track_failed", {
35896
+ reason,
35897
+ sessionId: unexpected.sessionId,
35898
+ error: error51 instanceof Error ? error51.message : String(error51)
35899
+ });
34990
35900
  });
35901
+ }
35902
+ if (!managedForkTarget || managedForkPublished || managedForkAbandoned) {
35903
+ if (managedForkPublished || !managedForkTarget)
35904
+ releaseManagedPins();
35905
+ return;
35906
+ }
35907
+ managedForkAbandoned = true;
35908
+ await abandonFork(managedForkTarget, sessionGcOptions).catch((error51) => {
35909
+ const message = error51 instanceof Error ? error51.message : String(error51);
35910
+ claudeLog("session.fork_abandon_failed", { reason, error: message });
34991
35911
  });
34992
- }
34993
- if (!managedForkTarget || managedForkPublished || managedForkAbandoned) {
34994
- if (managedForkPublished || !managedForkTarget)
34995
- releaseManagedPins();
34996
- return;
34997
- }
34998
- managedForkAbandoned = true;
34999
- await abandonFork(managedForkTarget, sessionGcOptions).catch((error51) => {
35000
- const message = error51 instanceof Error ? error51.message : String(error51);
35001
- claudeLog("session.fork_abandon_failed", { reason, error: message });
35002
- });
35003
- releaseManagedPins();
35004
- sweepSessionGc();
35912
+ releaseManagedPins();
35913
+ sweepSessionGc();
35914
+ })();
35915
+ managedForkAbandonment = pending;
35916
+ return pending;
35005
35917
  };
35006
35918
  const commitManagedFork = async () => {
35007
35919
  if (!managedForkTarget || managedForkSuperseded || managedForkCommitted)
@@ -35009,6 +35921,24 @@ data: ${JSON.stringify(lastError)}
35009
35921
  await commitFork(managedForkTarget, sessionGcOptions);
35010
35922
  managedForkCommitted = true;
35011
35923
  };
35924
+ const assertPriorityPublicationReady = () => {
35925
+ if (options.priorityPublication && !options.priorityPublication.rollback) {
35926
+ throw new Error("Durable priority attempt reached terminal without atomic publication");
35927
+ }
35928
+ };
35929
+ const finalizePriorityPublication = () => {
35930
+ assertPriorityPublicationReady();
35931
+ const publication = options.priorityPublication;
35932
+ if (!publication)
35933
+ return;
35934
+ if (requestAbort.controller.signal.aborted || durableWritesRevoked) {
35935
+ throw new Error("Durable priority attempt was revoked before terminal finalization");
35936
+ }
35937
+ if (!finalizePrioritySessionPublication(publication)) {
35938
+ throw new Error("Durable priority attempt changed before terminal finalization");
35939
+ }
35940
+ priorityTerminalCommitted = true;
35941
+ };
35012
35942
  try {
35013
35943
  let makePrompt = function() {
35014
35944
  if (structuredMessages) {
@@ -35021,6 +35951,29 @@ data: ${JSON.stringify(lastError)}
35021
35951
  return textPrompt;
35022
35952
  };
35023
35953
  const body = options.body;
35954
+ const markPriorityAttemptExposure = (reason) => {
35955
+ const exposure = options.priorityAttemptExposure;
35956
+ if (!exposure || exposure.committed)
35957
+ return;
35958
+ exposure.committed = true;
35959
+ exposure.reason = reason;
35960
+ };
35961
+ const observePriorityAttemptMessage = (message) => {
35962
+ if (message?.type === "assistant" && Array.isArray(message.message?.content) && message.message.content.length > 0) {
35963
+ markPriorityAttemptExposure("assistant_content");
35964
+ return;
35965
+ }
35966
+ if (message?.type === "stream_event") {
35967
+ const type = message.event?.type;
35968
+ if (type === "message_start" || type === "content_block_start" || type === "content_block_delta") {
35969
+ markPriorityAttemptExposure("stream_content");
35970
+ return;
35971
+ }
35972
+ }
35973
+ if (message?.type === "result" && message.structured_output !== undefined) {
35974
+ markPriorityAttemptExposure("structured_output");
35975
+ }
35976
+ };
35024
35977
  if (!Array.isArray(body.messages)) {
35025
35978
  return c.json({ type: "error", error: { type: "invalid_request_error", message: "messages: Field required" } }, 400);
35026
35979
  }
@@ -35045,17 +35998,118 @@ data: ${JSON.stringify(lastError)}
35045
35998
  if (unknown2.length > 0)
35046
35999
  claudeLog("priority.unknown_order_ids", { unknown: unknown2 });
35047
36000
  const assignmentCwd = adapter.extractClientWorkingDirectory?.(body) ?? adapter.extractWorkingDirectory(body);
35048
- const sessionKey = getPriorityAssignmentKey(adapter.getSessionId(c, body), lineageMessages, assignmentCwd);
35049
- const assigned = sessionKey ? priorityAssignments.get(sessionKey) : undefined;
35050
- let first;
35051
- if (assigned && order.includes(assigned) && !priorityExhaustion.isExhausted(assigned)) {
35052
- first = assigned;
35053
- } else {
36001
+ const adapterSessionId = adapter.getSessionId(c, body);
36002
+ const sessionKey = getPriorityAssignmentKey(adapterSessionId, lineageMessages, assignmentCwd);
36003
+ const preferred = order[0];
36004
+ if (preferred !== undefined) {
36005
+ const trustedTurn = requestMeta.routingTurnIdentity;
36006
+ let promotionTurn = trustedTurn;
36007
+ let publicationTurn;
36008
+ const failbackPolicy = getPriorityFailbackPolicy(process.env.MERIDIAN_PRIORITY_FAILBACK ?? getSetting("priorityFailback"));
36009
+ let durableRoute;
36010
+ let assignment;
36011
+ let routeMappingIsCurrent = false;
36012
+ if (adapterSessionId) {
36013
+ const routeKey = `${adapter.name}:${adapterSessionId}`;
36014
+ const routeResult = lookupPriorityAssignmentResult(routeKey);
36015
+ if (routeResult.status === "error") {
36016
+ return c.json({
36017
+ type: "error",
36018
+ error: { type: "overloaded_error", message: "Durable priority routing state is unavailable" }
36019
+ }, 503);
36020
+ }
36021
+ if (routeResult.status === "found") {
36022
+ durableRoute = { routeKey, expectedGeneration: routeResult.generation };
36023
+ assignment = {
36024
+ profileId: routeResult.assignment.profileId,
36025
+ requestId: routeResult.assignment.lastHumanTurnDigest
36026
+ };
36027
+ publicationTurn = {
36028
+ turnId: routeResult.assignment.lastHumanTurnDigest,
36029
+ issuedAt: routeResult.assignment.lastHumanTurnIssuedAt
36030
+ };
36031
+ if (trustedTurn) {
36032
+ const sameHumanTurn = trustedTurn.turnId === routeResult.assignment.lastHumanTurnDigest;
36033
+ const strictlyNewer = trustedTurn.issuedAt > routeResult.assignment.lastHumanTurnIssuedAt;
36034
+ if (sameHumanTurn) {
36035
+ publicationTurn = {
36036
+ turnId: trustedTurn.turnId,
36037
+ issuedAt: Math.max(trustedTurn.issuedAt, routeResult.assignment.lastHumanTurnIssuedAt)
36038
+ };
36039
+ } else if (strictlyNewer) {
36040
+ publicationTurn = trustedTurn;
36041
+ } else {
36042
+ promotionTurn = undefined;
36043
+ claudeLog("priority.attestation_replay_withheld", {
36044
+ routeKey,
36045
+ issuedAt: trustedTurn.issuedAt,
36046
+ highWater: routeResult.assignment.lastHumanTurnIssuedAt
36047
+ });
36048
+ }
36049
+ }
36050
+ const mapped = lookupSharedSessionResult(routeResult.assignment.mappingKey);
36051
+ if (mapped.status === "error") {
36052
+ return c.json({
36053
+ type: "error",
36054
+ error: { type: "overloaded_error", message: "Durable priority session state is unavailable" }
36055
+ }, 503);
36056
+ }
36057
+ routeMappingIsCurrent = mapped.status === "found" && mapped.generation === routeResult.assignment.mappingGeneration;
36058
+ if (!routeMappingIsCurrent) {
36059
+ if (!promotionTurn) {
36060
+ return c.json({
36061
+ type: "error",
36062
+ error: { type: "overloaded_error", message: "Durable priority session state is unavailable" }
36063
+ }, 503);
36064
+ }
36065
+ durableRoute = { ...durableRoute, forceFreshReplay: true };
36066
+ }
36067
+ } else if (routeResult.attempt && !trustedTurn) {
36068
+ return c.json({
36069
+ type: "error",
36070
+ error: { type: "overloaded_error", message: "Durable priority attempt state is unavailable" }
36071
+ }, 503);
36072
+ } else if (trustedTurn) {
36073
+ durableRoute = { routeKey, expectedGeneration: routeResult.generation };
36074
+ publicationTurn = trustedTurn;
36075
+ } else if (sessionKey) {
36076
+ assignment = priorityAssignments.get(sessionKey);
36077
+ }
36078
+ } else if (sessionKey) {
36079
+ assignment = priorityAssignments.get(sessionKey);
36080
+ }
36081
+ const shouldPromote = assignment !== undefined && durableRoute !== undefined && routeMappingIsCurrent && assignment.profileId !== preferred && order.includes(assignment.profileId) && !priorityExhaustion.isExhausted(assignment.profileId) && !priorityExhaustion.isExhausted(preferred) && shouldPromotePriorityAssignment({
36082
+ policy: failbackPolicy,
36083
+ assignment,
36084
+ requestId: promotionTurn?.turnId,
36085
+ requestKind: promotionTurn?.kind
36086
+ });
36087
+ const assignedProfile = assignment?.profileId;
36088
+ const assignmentIsHealthy = assignedProfile !== undefined && order.includes(assignedProfile) && !priorityExhaustion.isExhausted(assignedProfile);
36089
+ const retainOnlyProfile = durableRoute && !promotionTurn ? assignedProfile : undefined;
36090
+ if (retainOnlyProfile !== undefined && !order.includes(retainOnlyProfile)) {
36091
+ return c.json({
36092
+ type: "error",
36093
+ error: { type: "overloaded_error", message: "Durable priority routing state is unavailable" }
36094
+ }, 503);
36095
+ }
35054
36096
  const pick2 = choosePriorityProfile(order, (id) => priorityExhaustion.isExhausted(id));
35055
- first = pick2?.id ?? order[0];
36097
+ const first = retainOnlyProfile ?? (shouldPromote ? preferred : assignmentIsHealthy ? assignedProfile : pick2?.id ?? preferred);
36098
+ const candidates = retainOnlyProfile ? [retainOnlyProfile] : [first, ...order.filter((id) => id !== first && !priorityExhaustion.isExhausted(id))];
36099
+ return dispatchPriority({
36100
+ context: c,
36101
+ body,
36102
+ requestMeta,
36103
+ candidateIds: candidates,
36104
+ sessionKey,
36105
+ wantsStream: body.stream === true,
36106
+ currentProfileId: assignedProfile,
36107
+ turnWatchdogSignal: options.turnWatchdogSignal,
36108
+ publicationTurn,
36109
+ claimTurn: trustedTurn,
36110
+ durableRoute
36111
+ });
35056
36112
  }
35057
- const candidates = [first, ...order.filter((id) => id !== first && !priorityExhaustion.isExhausted(id))];
35058
- return dispatchPriority(c, body, requestMeta, candidates, sessionKey, body.stream === true, options.turnWatchdogSignal);
35059
36113
  }
35060
36114
  }
35061
36115
  const profile = resolveProfile(finalConfig.profiles, finalConfig.defaultProfile, options.forcedProfileId || c.req.header("x-meridian-profile") || undefined, routingMode === "sticky" ? { routingMode, stickySessionKey: adapter.getSessionId(c, body) } : undefined);
@@ -35303,6 +36357,12 @@ data: ${JSON.stringify(lastError)}
35303
36357
  headers: { "Content-Type": "application/json" }
35304
36358
  });
35305
36359
  }
36360
+ if (options.forceFreshPriorityReplay) {
36361
+ if (!options.priorityPublication || !agentSessionId || !durableMappingKey) {
36362
+ throw new Error("Fresh priority replay requires trusted keyed durable publication");
36363
+ }
36364
+ lineageResult = { type: "diverged", reason: "priority-failback" };
36365
+ }
35306
36366
  if (pipeline.some((t) => t.onSession)) {
35307
36367
  const mismatch = lineageResult.type === "diverged" ? lineageResult.mismatch : undefined;
35308
36368
  runTransformHook(pipeline, "onSession", {
@@ -35464,6 +36524,7 @@ data: ${JSON.stringify(lastError)}
35464
36524
  managedForkCommitted = false;
35465
36525
  managedForkPublished = false;
35466
36526
  managedForkAbandoned = false;
36527
+ managedForkAbandonment = undefined;
35467
36528
  managedForkSuperseded = false;
35468
36529
  managedFreshTarget = false;
35469
36530
  unexpectedManagedForkTarget = undefined;
@@ -35632,14 +36693,26 @@ data: ${JSON.stringify(lastError)}
35632
36693
  const trackFileChanges = !(process.env.MERIDIAN_NO_FILE_CHANGES ?? process.env.CLAUDE_PROXY_NO_FILE_CHANGES) && pipelineCtx.shouldTrackFileChanges;
35633
36694
  const fileChangeHook = trackFileChanges ? createFileChangeHook(fileChanges, mcpPrefix) : undefined;
35634
36695
  const discoveredTools = new Set;
36696
+ const priorityExposureHook = options.priorityAttemptExposure ? {
36697
+ matcher: "",
36698
+ hooks: [async (input) => {
36699
+ const toolName = input && typeof input === "object" ? Reflect.get(input, "tool_name") : undefined;
36700
+ if (toolName !== "ToolSearch")
36701
+ markPriorityAttemptExposure(toolName === "StructuredOutput" ? "structured_output_tool" : "tool_use");
36702
+ return {};
36703
+ }]
36704
+ } : undefined;
35635
36705
  const sdkHooks = passthrough ? {
35636
36706
  PreToolUse: [{
35637
36707
  matcher: "",
35638
36708
  hooks: [async (input) => {
35639
36709
  if (input.tool_name === "ToolSearch")
35640
36710
  return {};
35641
- if (input.tool_name === "StructuredOutput")
36711
+ if (input.tool_name === "StructuredOutput") {
36712
+ markPriorityAttemptExposure("structured_output_tool");
35642
36713
  return {};
36714
+ }
36715
+ markPriorityAttemptExposure("tool_use");
35643
36716
  const toolName = stripMcpPrefix(input.tool_name);
35644
36717
  if (hasDeferredTools && coreSet && !coreSet.has(toolName.toLowerCase())) {
35645
36718
  discoveredTools.add(toolName);
@@ -35700,6 +36773,12 @@ data: ${JSON.stringify(lastError)}
35700
36773
  }]
35701
36774
  } : {
35702
36775
  ...pipelineCtx.sdkHooks ?? {},
36776
+ ...priorityExposureHook ? {
36777
+ PreToolUse: [
36778
+ priorityExposureHook,
36779
+ ...pipelineCtx.sdkHooks?.PreToolUse ?? []
36780
+ ]
36781
+ } : {},
35703
36782
  ...fileChangeHook ? { PostToolUse: [fileChangeHook] } : {}
35704
36783
  };
35705
36784
  const stderrLines = [];
@@ -35735,6 +36814,11 @@ data: ${JSON.stringify(lastError)}
35735
36814
  mappingInvalidated = true;
35736
36815
  return evicted;
35737
36816
  };
36817
+ const settleInterruptedNonStreamMapping = () => {
36818
+ if (options.priorityPublication && !options.priorityPublication.rollback && managedForkTarget && !managedForkPublished)
36819
+ return true;
36820
+ return invalidateNonStreamMapping();
36821
+ };
35738
36822
  try {
35739
36823
  if (!claudeExecutable) {
35740
36824
  claudeExecutable = await resolveClaudeExecutableAsync();
@@ -35824,7 +36908,7 @@ data: ${JSON.stringify(lastError)}
35824
36908
  } catch (error51) {
35825
36909
  const errMsg = error51 instanceof Error ? error51.message : String(error51);
35826
36910
  releaseHeldDenies("non_stream_attempt_error");
35827
- if (didYieldContent)
36911
+ if (didYieldContent || options.priorityAttemptExposure?.committed)
35828
36912
  throw error51;
35829
36913
  const refusal = classifyResumeRefusal(error51, resumeSessionId ? stderrLines.slice(attemptStderrStart).join(`
35830
36914
  `) : undefined);
@@ -36030,6 +37114,7 @@ data: ${JSON.stringify(lastError)}
36030
37114
  }
36031
37115
  }();
36032
37116
  for await (const message of response) {
37117
+ observePriorityAttemptMessage(message);
36033
37118
  const observedSessionId = message.session_id;
36034
37119
  if (typeof observedSessionId === "string" && observedSessionId) {
36035
37120
  const returnedSessionId = observedSessionId;
@@ -36168,7 +37253,7 @@ data: ${JSON.stringify(lastError)}
36168
37253
  } catch (error51) {
36169
37254
  const failedResumedTurn = isResume && !managedForkTarget && !sawCanonicalResult;
36170
37255
  if ((requestAbort.controller.signal.aborted || durableWritesRevoked || failedResumedTurn) && !isIndependentSession) {
36171
- if (!invalidateNonStreamMapping()) {
37256
+ if (!settleInterruptedNonStreamMapping()) {
36172
37257
  throw new Error("Shared session mapping changed before interrupted non-stream invalidation");
36173
37258
  }
36174
37259
  claudeLog("session.interrupted_mapping_evicted", {
@@ -36178,7 +37263,7 @@ data: ${JSON.stringify(lastError)}
36178
37263
  }
36179
37264
  releaseHeldDenies("non_stream_error");
36180
37265
  if (!isIndependentSession && passthrough && capturedToolUses.length > 0 && !sawCanonicalResult) {
36181
- if (!invalidateNonStreamMapping()) {
37266
+ if (!settleInterruptedNonStreamMapping()) {
36182
37267
  throw new Error("Shared session mapping changed before non-stream recovery invalidation");
36183
37268
  }
36184
37269
  claudeLog("passthrough.noncanonical_session_evicted", { mode: "non_stream", reason: "drain_error" });
@@ -36362,7 +37447,7 @@ Subprocess stderr: ${stderrOutput}`;
36362
37447
  try {
36363
37448
  mappingStored = await publishPinnedTranscript(publicationTranscriptLocator(currentSessionId), () => {
36364
37449
  assertDurableWritesAllowed();
36365
- const stored = storeSession(profileSessionId, lineageMessages, currentSessionId, profileScopedCwd, reconcileReturnedSessionUuids(sdkUuidMap, allMessages.length, currentClientAssistantUuid, resumeSessionId, currentSessionId), lastUsage, earlyStopFired ? nextPassthroughToolCallAssistantUuid : null, earlyStopFired ? nextPassthroughToolCallIds : null, publicationTranscriptLocator(currentSessionId), managedForkTarget?.sessionId === currentSessionId ? managedForkSource : undefined, mappingExpectedGeneration);
37450
+ const stored = storeSession(profileSessionId, lineageMessages, currentSessionId, profileScopedCwd, reconcileReturnedSessionUuids(sdkUuidMap, allMessages.length, currentClientAssistantUuid, resumeSessionId, currentSessionId), lastUsage, earlyStopFired ? nextPassthroughToolCallAssistantUuid : null, earlyStopFired ? nextPassthroughToolCallIds : null, publicationTranscriptLocator(currentSessionId), managedForkTarget?.sessionId === currentSessionId ? managedForkSource : undefined, mappingExpectedGeneration, options.priorityPublication);
36366
37451
  if (stored) {
36367
37452
  mappingExpectedGeneration = stored;
36368
37453
  if (managedForkTarget?.sessionId === currentSessionId)
@@ -36399,6 +37484,7 @@ Subprocess stderr: ${stderrOutput}`;
36399
37484
  }
36400
37485
  }
36401
37486
  }
37487
+ finalizePriorityPublication();
36402
37488
  const responseSessionId = currentSessionId || resumeSessionId || `session_${Date.now()}`;
36403
37489
  return new Response(JSON.stringify({
36404
37490
  id: `msg_${Date.now()}`,
@@ -36603,7 +37689,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
36603
37689
  return;
36604
37690
  } catch (error51) {
36605
37691
  const errMsg = error51 instanceof Error ? error51.message : String(error51);
36606
- if (didYieldClientEvent)
37692
+ if (didYieldClientEvent || options.priorityAttemptExposure?.committed)
36607
37693
  throw error51;
36608
37694
  const refusal = classifyResumeRefusal(error51, resumeSessionId ? stderrLines.slice(attemptStderrStart).join(`
36609
37695
  `) : undefined);
@@ -36843,6 +37929,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
36843
37929
  }));
36844
37930
  try {
36845
37931
  for await (const message of guardedResponse) {
37932
+ observePriorityAttemptMessage(message);
36846
37933
  if (streamClosed && !awaitingEarlyStopDrain) {
36847
37934
  exitedBeforeCanonicalTerminal = true;
36848
37935
  break;
@@ -37194,7 +38281,7 @@ data: ${JSON.stringify({
37194
38281
  await commitManagedFork();
37195
38282
  const mappingStored = await publishPinnedTranscript(publicationTranscriptLocator(currentSessionId), () => {
37196
38283
  assertDurableWritesAllowed();
37197
- const stored = storeSession(profileSessionId, lineageMessages, currentSessionId, profileScopedCwd, reconcileReturnedSessionUuids(sdkUuidMap, allMessages.length, currentClientAssistantUuid, resumeSessionId, currentSessionId), lastUsage, earlyStopFired ? nextPassthroughToolCallAssistantUuid : null, earlyStopFired ? nextPassthroughToolCallIds : null, publicationTranscriptLocator(currentSessionId), managedForkTarget?.sessionId === currentSessionId ? managedForkSource : undefined, mappingExpectedGeneration);
38284
+ const stored = storeSession(profileSessionId, lineageMessages, currentSessionId, profileScopedCwd, reconcileReturnedSessionUuids(sdkUuidMap, allMessages.length, currentClientAssistantUuid, resumeSessionId, currentSessionId), lastUsage, earlyStopFired ? nextPassthroughToolCallAssistantUuid : null, earlyStopFired ? nextPassthroughToolCallIds : null, publicationTranscriptLocator(currentSessionId), managedForkTarget?.sessionId === currentSessionId ? managedForkSource : undefined, mappingExpectedGeneration, options.priorityPublication);
37198
38285
  if (stored) {
37199
38286
  mappingExpectedGeneration = stored;
37200
38287
  if (managedForkTarget?.sessionId === currentSessionId)
@@ -37342,6 +38429,7 @@ data: ${JSON.stringify({
37342
38429
  recoveryForkTarget
37343
38430
  ])) {
37344
38431
  const recoveryMessage = event;
38432
+ observePriorityAttemptMessage(recoveryMessage);
37345
38433
  if (recoveryMessage.session_id) {
37346
38434
  if (recoveryMessage.session_id !== recoveryForkTarget.sessionId) {
37347
38435
  if (recoveryMessage.session_id !== recoveryForkSource?.sessionId) {
@@ -37403,10 +38491,11 @@ data: ${JSON.stringify({
37403
38491
  await commitFork(recoveryForkTarget, sessionGcOptions);
37404
38492
  const recoveryMappingStored = await publishPinnedTranscript(recoveryForkTarget, () => {
37405
38493
  assertDurableWritesAllowed();
37406
- const stored = storeSession(profileSessionId, lineageMessages, recoverySessionId, profileScopedCwd, recoverySdkUuidMap, lastUsage, recoveryToolCallAssistantUuid ?? null, recoveryToolCallAssistantUuid ? [...recoveryEarlyStop.expected] : null, recoveryForkTarget, recoveryForkSource, mappingExpectedGeneration);
38494
+ const stored = storeSession(profileSessionId, lineageMessages, recoverySessionId, profileScopedCwd, recoverySdkUuidMap, lastUsage, recoveryToolCallAssistantUuid ?? null, recoveryToolCallAssistantUuid ? [...recoveryEarlyStop.expected] : null, recoveryForkTarget, recoveryForkSource, mappingExpectedGeneration, options.priorityPublication);
37407
38495
  if (stored) {
37408
38496
  mappingExpectedGeneration = stored;
37409
38497
  recoveryForkPublished = true;
38498
+ recoveryPublishedTarget = recoveryForkTarget;
37410
38499
  }
37411
38500
  return stored;
37412
38501
  }, sessionGcOptions);
@@ -37491,6 +38580,8 @@ data: ${JSON.stringify(lifted.frame)}
37491
38580
  });
37492
38581
  sweepSessionGc();
37493
38582
  }
38583
+ if (priorityRollbackRetirement)
38584
+ await priorityRollbackRetirement;
37494
38585
  releaseRecoveryForkPins?.();
37495
38586
  }
37496
38587
  }
@@ -37563,6 +38654,8 @@ data: ${JSON.stringify({
37563
38654
  claudeLog("response.file_changes", { mode: "stream", count: fileChanges.length });
37564
38655
  }
37565
38656
  }
38657
+ assertPriorityPublicationReady();
38658
+ finalizePriorityPublication();
37566
38659
  if (messageStartEmitted) {
37567
38660
  sendTerminalDelta(streamedToolUseIds.size > 0 ? "tool_use" : undefined);
37568
38661
  safeEnqueue(encoder.encode(`event: message_stop
@@ -37763,7 +38856,7 @@ data: ${JSON.stringify({
37763
38856
  await commitManagedFork();
37764
38857
  const mappingStored = await publishPinnedTranscript(publicationTranscriptLocator(currentSessionId), () => {
37765
38858
  assertDurableWritesAllowed();
37766
- const stored = storeSession(profileSessionId, lineageMessages, currentSessionId, profileScopedCwd, reconcileReturnedSessionUuids(sdkUuidMap, allMessages.length, currentClientAssistantUuid, resumeSessionId, currentSessionId), lastUsage, nextPassthroughToolCallAssistantUuid, nextPassthroughToolCallIds, publicationTranscriptLocator(currentSessionId), managedForkTarget?.sessionId === currentSessionId ? managedForkSource : undefined, mappingExpectedGeneration);
38859
+ const stored = storeSession(profileSessionId, lineageMessages, currentSessionId, profileScopedCwd, reconcileReturnedSessionUuids(sdkUuidMap, allMessages.length, currentClientAssistantUuid, resumeSessionId, currentSessionId), lastUsage, nextPassthroughToolCallAssistantUuid, nextPassthroughToolCallIds, publicationTranscriptLocator(currentSessionId), managedForkTarget?.sessionId === currentSessionId ? managedForkSource : undefined, mappingExpectedGeneration, options.priorityPublication);
37767
38860
  if (stored) {
37768
38861
  mappingExpectedGeneration = stored;
37769
38862
  if (managedForkTarget?.sessionId === currentSessionId)
@@ -37796,6 +38889,8 @@ data: ${JSON.stringify({
37796
38889
  });
37797
38890
  }
37798
38891
  }
38892
+ assertPriorityPublicationReady();
38893
+ finalizePriorityPublication();
37799
38894
  safeEnqueue(encoder.encode(`event: message_delta
37800
38895
  data: ${JSON.stringify({
37801
38896
  type: "message_delta",
@@ -37939,6 +39034,8 @@ data: ${JSON.stringify({
37939
39034
  }
37940
39035
  } finally {
37941
39036
  await abandonManagedFork("stream_complete_without_commit");
39037
+ if (priorityRollbackRetirement)
39038
+ await priorityRollbackRetirement;
37942
39039
  requestAbort.detach();
37943
39040
  }
37944
39041
  })().finally(() => {
@@ -38067,6 +39164,7 @@ data: ${JSON.stringify({
38067
39164
  };
38068
39165
  let body;
38069
39166
  let sharedSessionRevisionsAtArrival;
39167
+ let routingTurnIdentity;
38070
39168
  try {
38071
39169
  try {
38072
39170
  body = await c.req.json();
@@ -38086,6 +39184,7 @@ data: ${JSON.stringify({
38086
39184
  }
38087
39185
  if (Array.isArray(body?.messages)) {
38088
39186
  const adapter = detectAdapter(c);
39187
+ routingTurnIdentity = adapter.getRoutingTurnIdentity?.(c, body);
38089
39188
  const agentSessionId = adapter.getSessionId(c, body);
38090
39189
  if (agentSessionId) {
38091
39190
  const arrivalProfileIds = new Set(getEffectiveProfiles(finalConfig.profiles).map((profile) => profile.id));
@@ -38164,6 +39263,7 @@ data: ${JSON.stringify({
38164
39263
  sdkActiveDurationMs: 0,
38165
39264
  sessionTurnLease,
38166
39265
  sharedSessionRevisionsAtArrival,
39266
+ routingTurnIdentity,
38167
39267
  retainSessionTurnFence: () => {
38168
39268
  retainSessionTurnFence = true;
38169
39269
  }