@cortexkit/opencode-magic-context 0.49.17 → 0.49.19
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/dist/auto-search-worker.js +6 -2
- package/dist/chunk-embedding-write-worker.js +2 -2
- package/dist/{context-yhetp0kn.js → context-j31m2dv7.js} +27 -14
- package/dist/features/magic-context/dreamer/classify.d.ts +3 -0
- package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts +11 -0
- package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/map-memories.d.ts +3 -0
- package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/verify.d.ts +3 -0
- package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
- package/dist/features/magic-context/migrations.d.ts.map +1 -1
- package/dist/features/magic-context/storage-clone.d.ts.map +1 -1
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts +11 -0
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -0
- package/dist/features/magic-context/storage-meta-persisted.d.ts +13 -0
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-worker-evaluation.fixture.d.ts +2 -0
- package/dist/hooks/magic-context/auto-search-worker-evaluation.fixture.d.ts.map +1 -0
- package/dist/hooks/magic-context/cache-busting-signals.d.ts +22 -1
- package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts +4 -2
- package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/file-token-coverage.d.ts +11 -0
- package/dist/hooks/magic-context/file-token-coverage.d.ts.map +1 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +9 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/host-served-rows.d.ts +25 -0
- package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +7 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +13 -0
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/pass-outcome.d.ts +2 -0
- package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts +2 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts +59 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -0
- package/dist/hooks/magic-context/system-date-refresh.d.ts +15 -2
- package/dist/hooks/magic-context/system-date-refresh.d.ts.map +1 -1
- package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-content-primitives.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +6 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts +19 -0
- package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +21 -0
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-aabzay3h.js → index-3esx8tkf.js} +256 -50
- package/dist/{index-v8awdgvd.js → index-3h4dp9wb.js} +1 -1
- package/dist/{index-5a1ex6x8.js → index-4911rn0b.js} +3 -3
- package/dist/{index-qn7xstt2.js → index-63k48rv9.js} +1 -2
- package/dist/{index-p7m7j0cp.js → index-9zcsy3hh.js} +53 -7
- package/dist/{index-nkpmm9q8.js → index-c1p88z1y.js} +3 -3
- package/dist/{index-hqhm3wke.js → index-cf74k5ak.js} +2 -2
- package/dist/{index-vrzjhftj.js → index-dxmq29t1.js} +4 -4
- package/dist/{index-kmdj7dsq.js → index-edmpdxcw.js} +1 -1
- package/dist/{index-4yt7dtf4.js → index-jhghdnsm.js} +113 -44
- package/dist/{index-fb2qxs2y.js → index-jrr131e0.js} +2 -2
- package/dist/{index-a7c4r5re.js → index-rpxdjkm0.js} +216 -40
- package/dist/{index-cwzfcbtq.js → index-se4m2g6w.js} +10 -1
- package/dist/index.js +21 -17
- package/dist/{message-index-bounded-1633vc7f.js → message-index-bounded-zyc8h32y.js} +3 -3
- package/dist/{message-index-dprebmtt.js → message-index-gtpqnj8w.js} +3 -3
- package/dist/migration-worker.js +2 -2
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/plugin/tool-registry.d.ts.map +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-4zp09ejb.js → read-session-chunk-jjb48bt9.js} +2 -2
- package/dist/{recomp-orchestrator-z3ecszx6.js → recomp-orchestrator-999jj4bc.js} +8 -8
- package/dist/{search-archive-znyy44ve.js → search-archive-6vm0e2f5.js} +3 -3
- package/dist/{search-6mee3vty.js → search-xsqk1bj4.js} +6 -6
- package/dist/shared/model-suggestion-retry.d.ts +30 -1
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- package/dist/shared/prompt-async-transport.d.ts.map +1 -1
- package/dist/{storage-tags-8qns3012.js → storage-tags-r7k9tjcv.js} +1 -1
- package/dist/tools/ctx-expand/rust-mode-tag.test-support.d.ts +15 -0
- package/dist/tools/ctx-expand/rust-mode-tag.test-support.d.ts.map +1 -0
- package/dist/tools/ctx-expand/tools.d.ts +11 -0
- package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-3ydzxa62.js → transform-postprocess-phase-jj99r7z2.js} +8 -8
- package/dist/v2/auto-search-worker.js +6 -2
- package/dist/v2/chunk-embedding-write-worker.js +2 -2
- package/dist/v2/{context-jn3zpeqh.js → context-y5yamxak.js} +378 -92
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/payload.d.ts.map +1 -1
- package/dist/v2/hooks/tools.d.ts.map +1 -1
- package/dist/v2/{message-index-pxehjpzx.js → message-index-8vz2pq76.js} +3 -3
- package/dist/v2/{message-index-bounded-hpejqyd8.js → message-index-bounded-spd8r7pj.js} +3 -3
- package/dist/v2/migration-worker.js +2 -2
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-zdppn4bj.js → read-session-chunk-cwkxrmns.js} +2 -2
- package/dist/v2/{recomp-orchestrator-cmqnfpp3.js → recomp-orchestrator-f6m9jr7p.js} +7 -7
- package/dist/v2/{search-archive-gfh11vs0.js → search-archive-wve3tq1k.js} +3 -3
- package/dist/v2/{search-66842dya.js → search-hwg7jfbj.js} +6 -6
- package/dist/v2/{server-zyzawhdw.js → server-27gq4mfz.js} +2 -2
- package/dist/v2/{server-3rhpvy84.js → server-2ar62dyx.js} +10 -1
- package/dist/v2/{server-ec4ca92p.js → server-45q69hkq.js} +1 -1
- package/dist/v2/{server-fw7wrk01.js → server-6vdzn1td.js} +216 -40
- package/dist/v2/{server-kh7dpa1a.js → server-9hx7g5jp.js} +53 -7
- package/dist/v2/{server-gtfhttbr.js → server-bmymkx73.js} +2 -2
- package/dist/v2/{server-vsw8tmm6.js → server-gsxjv2q2.js} +4 -4
- package/dist/v2/{server-my7k4eds.js → server-hm38q7r0.js} +1 -1
- package/dist/v2/{server-gpvay0xz.js → server-xq7dfjke.js} +1 -2
- package/dist/v2/server.js +2 -2
- package/dist/v2/{storage-tags-1h8k6ra9.js → storage-tags-3wdb8zph.js} +1 -1
- package/dist/v2/store-reader.d.ts +6 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{wrapup-orchestrator-xs8redz9.js → wrapup-orchestrator-embdz8gj.js} +7 -7
- package/dist/{wrapup-orchestrator-j7d7ry5b.js → wrapup-orchestrator-whhbjmaz.js} +9 -9
- package/package.json +1 -1
- package/src/shared/model-suggestion-retry.test.ts +166 -0
- package/src/shared/model-suggestion-retry.ts +165 -14
- package/src/shared/prompt-async-transport.test.ts +107 -0
- package/src/shared/prompt-async-transport.ts +39 -0
|
@@ -8,12 +8,15 @@ import {
|
|
|
8
8
|
retreatPastHostUnservedRows,
|
|
9
9
|
snapTerminalCompartmentToServedRow,
|
|
10
10
|
isHostRenderedSystemMessage,
|
|
11
|
+
markCoveredInstructionRow,
|
|
12
|
+
isCoveredInstructionRow,
|
|
11
13
|
completedToolArcCrossesBoundary,
|
|
12
14
|
buildToolArcs,
|
|
13
15
|
fenceBoundaryForCompletedToolArcs,
|
|
14
16
|
fenceBoundaryForToolArcs,
|
|
15
17
|
buildTrueRawTokenIndex,
|
|
16
18
|
computeRawRangeFingerprint,
|
|
19
|
+
isFilePart,
|
|
17
20
|
DreamTokenBudgetExceeded,
|
|
18
21
|
TOKEN_BUDGET_FINALIZE_MESSAGE,
|
|
19
22
|
registerBudgetFinalizeChild,
|
|
@@ -36,6 +39,7 @@ import {
|
|
|
36
39
|
isRustMarkerAdmissionFenced,
|
|
37
40
|
readReplayEnvelope,
|
|
38
41
|
readReplayDocument,
|
|
42
|
+
updateReplayDocument,
|
|
39
43
|
writeReplayDocument,
|
|
40
44
|
describeProtectedTailDrainBudgetSkip,
|
|
41
45
|
loadProtectedTailMeta,
|
|
@@ -66,6 +70,7 @@ import {
|
|
|
66
70
|
serializeStrippedPlaceholderState,
|
|
67
71
|
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
68
72
|
THINKING_BINDING_STRIP_ORDER_END_MARKER,
|
|
73
|
+
COMPACTION_OFF_THINKING_FROZEN_PREFIX,
|
|
69
74
|
getMergedReasoningStrippedIds,
|
|
70
75
|
addMergedReasoningStrippedIds,
|
|
71
76
|
parseProcessedImageMarkers,
|
|
@@ -92,7 +97,7 @@ import {
|
|
|
92
97
|
getRawSessionTagKeysThrough2,
|
|
93
98
|
getLegacyProtectedTailStartOrdinal2,
|
|
94
99
|
readSessionChunk2
|
|
95
|
-
} from "./index-
|
|
100
|
+
} from "./index-9zcsy3hh.js";
|
|
96
101
|
import {
|
|
97
102
|
getHarness2,
|
|
98
103
|
harnessOwnsOpenCodeStore2
|
|
@@ -159,7 +164,7 @@ import {
|
|
|
159
164
|
LATEST_SUPPORTED_VERSION,
|
|
160
165
|
getPersistedSchemaVersion,
|
|
161
166
|
openDatabase
|
|
162
|
-
} from "./index-
|
|
167
|
+
} from "./index-jrr131e0.js";
|
|
163
168
|
import {
|
|
164
169
|
inRootAsyncContext2,
|
|
165
170
|
Database2,
|
|
@@ -191,7 +196,7 @@ import {
|
|
|
191
196
|
resolveStoredPathWorkspaceIdentity,
|
|
192
197
|
sourceNameForMemory,
|
|
193
198
|
computeWorkspaceEpochFingerprint
|
|
194
|
-
} from "./index-
|
|
199
|
+
} from "./index-63k48rv9.js";
|
|
195
200
|
import {
|
|
196
201
|
getTableColumnNames
|
|
197
202
|
} from "./index-bp5083x2.js";
|
|
@@ -244,7 +249,7 @@ import {
|
|
|
244
249
|
toMessageIndexSource2,
|
|
245
250
|
clearIndexedMessagesInTransaction2,
|
|
246
251
|
indexSourcesAfterOrdinal2
|
|
247
|
-
} from "./index-
|
|
252
|
+
} from "./index-se4m2g6w.js";
|
|
248
253
|
import {
|
|
249
254
|
stripWellFormedLeadingTagPrefix,
|
|
250
255
|
stripTagPrefix,
|
|
@@ -257,7 +262,7 @@ import {
|
|
|
257
262
|
foldShrunkPartTags2,
|
|
258
263
|
getTagNumberByMessageId2,
|
|
259
264
|
getActiveTagsBySession2
|
|
260
|
-
} from "./index-
|
|
265
|
+
} from "./index-cf74k5ak.js";
|
|
261
266
|
import {
|
|
262
267
|
openCodeDbExists,
|
|
263
268
|
withReadOnlySessionDb,
|
|
@@ -271,7 +276,7 @@ import {
|
|
|
271
276
|
insertPrimerCandidates,
|
|
272
277
|
promoteSessionFactsDurable,
|
|
273
278
|
embedPromotedFacts
|
|
274
|
-
} from "./index-
|
|
279
|
+
} from "./index-3h4dp9wb.js";
|
|
275
280
|
import {
|
|
276
281
|
pushNotification2
|
|
277
282
|
} from "./index-x8a7jmkh.js";
|
|
@@ -6036,6 +6041,8 @@ function outputMessageIsPostAnchor(message, inputIndexById, anchorIndex) {
|
|
|
6036
6041
|
}
|
|
6037
6042
|
return false;
|
|
6038
6043
|
}
|
|
6044
|
+
if (isCoveredInstructionRow(message.info))
|
|
6045
|
+
return false;
|
|
6039
6046
|
if (!isSyntheticOutput(message))
|
|
6040
6047
|
return null;
|
|
6041
6048
|
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId"].map((key) => recordValue(message.info, key)).find((value) => typeof value === "string");
|
|
@@ -6431,6 +6438,34 @@ function noteLkgCapturedPrefix(sessionId) {
|
|
|
6431
6438
|
if (!sessions.has(sessionId))
|
|
6432
6439
|
sessions.set(sessionId, {});
|
|
6433
6440
|
}
|
|
6441
|
+
function readPersistedLkgUntaggedInputIds(db, sessionId) {
|
|
6442
|
+
try {
|
|
6443
|
+
const saved = readReplayEnvelope(db, sessionId, "read").lkgUntaggedInputIds;
|
|
6444
|
+
return Array.isArray(saved) ? saved.filter((id) => typeof id === "string" && id.length > 0) : [];
|
|
6445
|
+
} catch (error) {
|
|
6446
|
+
sessionLog2(sessionId, "LKG untagged-input record unreadable:", error);
|
|
6447
|
+
return [];
|
|
6448
|
+
}
|
|
6449
|
+
}
|
|
6450
|
+
function persistLkgUntaggedInputIds(db, sessionId, ids) {
|
|
6451
|
+
const next = [...new Set(ids)].sort();
|
|
6452
|
+
try {
|
|
6453
|
+
return updateReplayDocument(db, sessionId, (doc) => {
|
|
6454
|
+
const saved = Array.isArray(doc.lkgUntaggedInputIds) ? doc.lkgUntaggedInputIds : [];
|
|
6455
|
+
if (JSON.stringify(saved) === JSON.stringify(next))
|
|
6456
|
+
return false;
|
|
6457
|
+
doc.version = 2;
|
|
6458
|
+
if (next.length > 0)
|
|
6459
|
+
doc.lkgUntaggedInputIds = next;
|
|
6460
|
+
else
|
|
6461
|
+
delete doc.lkgUntaggedInputIds;
|
|
6462
|
+
return true;
|
|
6463
|
+
});
|
|
6464
|
+
} catch (error) {
|
|
6465
|
+
sessionLog2(sessionId, "LKG untagged-input record write failed:", error);
|
|
6466
|
+
return false;
|
|
6467
|
+
}
|
|
6468
|
+
}
|
|
6434
6469
|
function noteLkgRecoveryPrefix(args) {
|
|
6435
6470
|
const digests = [
|
|
6436
6471
|
...args.entry.entryContentDigests,
|
|
@@ -6441,19 +6476,23 @@ function noteLkgRecoveryPrefix(args) {
|
|
|
6441
6476
|
const ids = args.entry.entryInputIds;
|
|
6442
6477
|
if (ids.some((id) => !id) || new Set(ids).size !== ids.length)
|
|
6443
6478
|
return false;
|
|
6479
|
+
const untaggedInputIds = new Set([
|
|
6480
|
+
...sessions.get(args.sessionId)?.prefix?.untaggedInputIds ?? [],
|
|
6481
|
+
...args.db ? readPersistedLkgUntaggedInputIds(args.db, args.sessionId) : [],
|
|
6482
|
+
...ids.slice(args.entry.anchorIndex + 1)
|
|
6483
|
+
]);
|
|
6444
6484
|
sessions.set(args.sessionId, {
|
|
6445
6485
|
fenceRevision: sessions.get(args.sessionId)?.fenceRevision,
|
|
6446
6486
|
prefix: {
|
|
6447
6487
|
inputs: ids.map((id, index) => ({ id, digest: digests[index] })),
|
|
6448
6488
|
json: JSON.stringify(args.messages),
|
|
6449
|
-
untaggedInputIds
|
|
6450
|
-
...sessions.get(args.sessionId)?.prefix?.untaggedInputIds ?? [],
|
|
6451
|
-
...ids.slice(args.entry.anchorIndex + 1)
|
|
6452
|
-
]),
|
|
6489
|
+
untaggedInputIds,
|
|
6453
6490
|
modelKey: args.modelKey,
|
|
6454
6491
|
providerKey: args.providerKey
|
|
6455
6492
|
}
|
|
6456
6493
|
});
|
|
6494
|
+
if (args.db)
|
|
6495
|
+
persistLkgUntaggedInputIds(args.db, args.sessionId, untaggedInputIds);
|
|
6457
6496
|
return true;
|
|
6458
6497
|
}
|
|
6459
6498
|
function readLkgRecoveryPrefix(sessionId, inputs, messages, db) {
|
|
@@ -6993,10 +7032,11 @@ function dropSlot(sessionId, _reason) {
|
|
|
6993
7032
|
if (pass !== undefined)
|
|
6994
7033
|
hydrationAttemptBySession.set(sessionId, pass);
|
|
6995
7034
|
}
|
|
6996
|
-
function noteEntry(sessionId,
|
|
7035
|
+
function noteEntry(sessionId, input) {
|
|
6997
7036
|
const slot = getSlot(sessionId);
|
|
6998
7037
|
if (!slot)
|
|
6999
7038
|
return null;
|
|
7039
|
+
const messages = input.some((message) => isCoveredInstructionRow(message.info)) ? input.filter((message) => !isCoveredInstructionRow(message.info)) : input;
|
|
7000
7040
|
const entryInputIds = messages.map((message) => {
|
|
7001
7041
|
const id = message.info?.id;
|
|
7002
7042
|
return typeof id === "string" ? id : "";
|
|
@@ -7457,11 +7497,15 @@ function clonePiContentDecisions(raw, filter) {
|
|
|
7457
7497
|
])}`);
|
|
7458
7498
|
continue;
|
|
7459
7499
|
}
|
|
7460
|
-
|
|
7461
|
-
|
|
7500
|
+
const thinkingPrefix = [
|
|
7501
|
+
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
7502
|
+
COMPACTION_OFF_THINKING_FROZEN_PREFIX
|
|
7503
|
+
].find((prefix) => entry.startsWith(prefix));
|
|
7504
|
+
if (thinkingPrefix) {
|
|
7505
|
+
const messageId = entry.slice(thinkingPrefix.length);
|
|
7462
7506
|
if (messageId.length === 0 || !filter.includeMessageId(messageId))
|
|
7463
7507
|
continue;
|
|
7464
|
-
copied.push(`${
|
|
7508
|
+
copied.push(`${thinkingPrefix}${mapMessageId(filter, messageId) ?? messageId}`);
|
|
7465
7509
|
continue;
|
|
7466
7510
|
}
|
|
7467
7511
|
if (entry.startsWith(MERGED_REASONING_PARTS_PREFIX) || entry.startsWith("pi-content-replay-"))
|
|
@@ -8871,9 +8915,33 @@ var promptFailureDetails = new WeakMap;
|
|
|
8871
8915
|
function isHostTimeoutError(error) {
|
|
8872
8916
|
return error !== null && typeof error === "object" && error.name === "TimeoutError";
|
|
8873
8917
|
}
|
|
8918
|
+
|
|
8919
|
+
class ModelProducedNoOutputError extends Error {
|
|
8920
|
+
waitedMs;
|
|
8921
|
+
constructor(waitedMs) {
|
|
8922
|
+
super(`prompt timed out after ${waitedMs}ms with no model output`);
|
|
8923
|
+
this.waitedMs = waitedMs;
|
|
8924
|
+
this.name = "ModelProducedNoOutputError";
|
|
8925
|
+
}
|
|
8926
|
+
}
|
|
8927
|
+
var modelActivityBySignal = new WeakMap;
|
|
8928
|
+
function noteModelActivityMonitored(signal) {
|
|
8929
|
+
const activity = signal ? modelActivityBySignal.get(signal) : undefined;
|
|
8930
|
+
if (activity)
|
|
8931
|
+
activity.monitored = true;
|
|
8932
|
+
}
|
|
8933
|
+
function noteModelOutputReceived(signal) {
|
|
8934
|
+
const activity = signal ? modelActivityBySignal.get(signal) : undefined;
|
|
8935
|
+
if (activity) {
|
|
8936
|
+
activity.monitored = true;
|
|
8937
|
+
activity.received = true;
|
|
8938
|
+
}
|
|
8939
|
+
}
|
|
8874
8940
|
function isPromptTimeoutError(error) {
|
|
8875
8941
|
if (isHostTimeoutError(error))
|
|
8876
8942
|
return true;
|
|
8943
|
+
if (error instanceof ModelProducedNoOutputError)
|
|
8944
|
+
return true;
|
|
8877
8945
|
return error instanceof Error && /^prompt timed out after \d+ms$/.test(error.message);
|
|
8878
8946
|
}
|
|
8879
8947
|
function getPromptFailureDetail(error) {
|
|
@@ -8951,12 +9019,22 @@ function raceWithSignal(work, signal) {
|
|
|
8951
9019
|
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
8952
9020
|
});
|
|
8953
9021
|
}
|
|
8954
|
-
async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
|
|
9022
|
+
async function promptWithTimeout(client, args, timeoutMs, signal, transport, firstOutputTimeoutMs) {
|
|
8955
9023
|
if (signal?.aborted) {
|
|
8956
9024
|
throw new Error(externalAbortMessage(signal));
|
|
8957
9025
|
}
|
|
8958
9026
|
const controller = new AbortController;
|
|
8959
9027
|
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
9028
|
+
const activity = { monitored: false, received: false };
|
|
9029
|
+
modelActivityBySignal.set(controller.signal, activity);
|
|
9030
|
+
let silent = false;
|
|
9031
|
+
const firstOutputTimer = firstOutputTimeoutMs !== undefined && firstOutputTimeoutMs < timeoutMs ? setTimeout(() => {
|
|
9032
|
+
if (!activity.monitored || activity.received)
|
|
9033
|
+
return;
|
|
9034
|
+
silent = true;
|
|
9035
|
+
controller.abort();
|
|
9036
|
+
}, firstOutputTimeoutMs) : undefined;
|
|
9037
|
+
const timeoutError = () => silent && firstOutputTimeoutMs !== undefined ? new ModelProducedNoOutputError(firstOutputTimeoutMs) : new Error(`prompt timed out after ${timeoutMs}ms`);
|
|
8960
9038
|
const onExternalAbort = () => controller.abort();
|
|
8961
9039
|
signal?.addEventListener("abort", onExternalAbort);
|
|
8962
9040
|
try {
|
|
@@ -8979,7 +9057,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
|
|
|
8979
9057
|
if (!transport || transport.childSessionId) {
|
|
8980
9058
|
await abortChildRun(client, transport?.childSessionId ?? args.path.id);
|
|
8981
9059
|
}
|
|
8982
|
-
throw
|
|
9060
|
+
throw timeoutError();
|
|
8983
9061
|
}
|
|
8984
9062
|
if (isHostTimeoutError(error)) {
|
|
8985
9063
|
if (!transport || transport.childSessionId) {
|
|
@@ -8989,13 +9067,15 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
|
|
|
8989
9067
|
throw error;
|
|
8990
9068
|
} finally {
|
|
8991
9069
|
clearTimeout(timeout);
|
|
9070
|
+
if (firstOutputTimer)
|
|
9071
|
+
clearTimeout(firstOutputTimer);
|
|
8992
9072
|
signal?.removeEventListener("abort", onExternalAbort);
|
|
8993
9073
|
}
|
|
8994
9074
|
if (signal?.aborted || controller.signal.aborted) {
|
|
8995
9075
|
if (!transport || transport.childSessionId) {
|
|
8996
9076
|
await abortChildRun(client, transport?.childSessionId ?? args.path.id);
|
|
8997
9077
|
}
|
|
8998
|
-
throw
|
|
9078
|
+
throw signal?.aborted ? new Error(externalAbortMessage(signal)) : timeoutError();
|
|
8999
9079
|
}
|
|
9000
9080
|
}
|
|
9001
9081
|
async function abortChildRun(client, sessionId) {
|
|
@@ -9013,6 +9093,8 @@ async function abortChildRun(client, sessionId) {
|
|
|
9013
9093
|
function isNonRetryable(error, externalSignal) {
|
|
9014
9094
|
if (externalSignal?.aborted || error instanceof HiddenCompletionRefusal && error.terminal || error instanceof HiddenAgentStepLimit || error instanceof DreamTokenBudgetExceeded)
|
|
9015
9095
|
return true;
|
|
9096
|
+
if (error instanceof ModelProducedNoOutputError)
|
|
9097
|
+
return false;
|
|
9016
9098
|
if (error instanceof Error) {
|
|
9017
9099
|
if (error.name === "AbortError")
|
|
9018
9100
|
return true;
|
|
@@ -9044,7 +9126,7 @@ function classifyPromptFailure(error, phase, externalSignal) {
|
|
|
9044
9126
|
if (externalSignal?.aborted || message === "prompt aborted by external signal") {
|
|
9045
9127
|
return "child_aborted";
|
|
9046
9128
|
}
|
|
9047
|
-
if (/^prompt timed out after \d+ms$/.test(message) || isHostTimeoutError(error)) {
|
|
9129
|
+
if (error instanceof ModelProducedNoOutputError || /^prompt timed out after \d+ms$/.test(message) || isHostTimeoutError(error)) {
|
|
9048
9130
|
return "provider_timeout";
|
|
9049
9131
|
}
|
|
9050
9132
|
if (phase === "validation") {
|
|
@@ -9079,11 +9161,11 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, tr
|
|
|
9079
9161
|
});
|
|
9080
9162
|
throw error;
|
|
9081
9163
|
}
|
|
9082
|
-
async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true) {
|
|
9164
|
+
async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true, firstOutputTimeoutMs) {
|
|
9083
9165
|
const originalBody = { ...args.body };
|
|
9084
9166
|
const attemptArgs = copyPromptArgs(args, originalBody);
|
|
9085
9167
|
try {
|
|
9086
|
-
await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport);
|
|
9168
|
+
await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport, firstOutputTimeoutMs);
|
|
9087
9169
|
return;
|
|
9088
9170
|
} catch (error) {
|
|
9089
9171
|
if (isNonRetryable(error, signal) || !allowModelSuggestions)
|
|
@@ -9102,9 +9184,30 @@ async function attemptOnce(client, args, timeoutMs, signal, callContext, label,
|
|
|
9102
9184
|
providerID: suggestion.providerID,
|
|
9103
9185
|
modelID: suggestion.suggestion
|
|
9104
9186
|
}
|
|
9105
|
-
}), timeoutMs, signal, transport);
|
|
9187
|
+
}), timeoutMs, signal, transport, firstOutputTimeoutMs);
|
|
9106
9188
|
}
|
|
9107
9189
|
}
|
|
9190
|
+
function createChainClock(options, timeoutMs) {
|
|
9191
|
+
const fallbacks = options.fallbackModels ?? [];
|
|
9192
|
+
const hasValidFallbackFrom = (index) => fallbacks.slice(index).some((fallback) => {
|
|
9193
|
+
const entry = toModelEntry(fallback);
|
|
9194
|
+
return entry ? parseProviderModel(entry.model) !== null : false;
|
|
9195
|
+
});
|
|
9196
|
+
let silentSpentMs = 0;
|
|
9197
|
+
return {
|
|
9198
|
+
budget(nextFallbackIndex) {
|
|
9199
|
+
const attemptTimeoutMs = Math.max(1, timeoutMs - silentSpentMs);
|
|
9200
|
+
if (options.firstOutputTimeoutMs === undefined || !hasValidFallbackFrom(nextFallbackIndex))
|
|
9201
|
+
return { timeoutMs: attemptTimeoutMs };
|
|
9202
|
+
const bound = Math.min(options.firstOutputTimeoutMs, Math.floor(attemptTimeoutMs / 2));
|
|
9203
|
+
return bound > 0 ? { timeoutMs: attemptTimeoutMs, firstOutputTimeoutMs: bound } : { timeoutMs: attemptTimeoutMs };
|
|
9204
|
+
},
|
|
9205
|
+
settle(error, startedAt) {
|
|
9206
|
+
if (error instanceof ModelProducedNoOutputError)
|
|
9207
|
+
silentSpentMs += Date.now() - startedAt;
|
|
9208
|
+
}
|
|
9209
|
+
};
|
|
9210
|
+
}
|
|
9108
9211
|
async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
9109
9212
|
const timeoutMs = options.timeoutMs ?? 300000;
|
|
9110
9213
|
const callContext = options.callContext ?? "subagent";
|
|
@@ -9113,11 +9216,15 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
9113
9216
|
const baseArgs = copyPromptArgs(args, baseBody);
|
|
9114
9217
|
const explicitPrimaryLabel = baseBody.model?.providerID && baseBody.model.modelID ? `${baseBody.model.providerID}/${baseBody.model.modelID}` : "primary";
|
|
9115
9218
|
let lastError = null;
|
|
9219
|
+
const clock = createChainClock(options, timeoutMs);
|
|
9220
|
+
const primaryStartedAt = Date.now();
|
|
9116
9221
|
try {
|
|
9117
|
-
|
|
9222
|
+
const budget = clock.budget(0);
|
|
9223
|
+
await attemptOnce(client, baseArgs, budget.timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport, options.allowModelSuggestions, budget.firstOutputTimeoutMs);
|
|
9118
9224
|
return;
|
|
9119
9225
|
} catch (error) {
|
|
9120
9226
|
lastError = error;
|
|
9227
|
+
clock.settle(error, primaryStartedAt);
|
|
9121
9228
|
if (isNonRetryable(error, options.signal))
|
|
9122
9229
|
throw error;
|
|
9123
9230
|
if (fallbacks.length === 0) {
|
|
@@ -9139,12 +9246,15 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
9139
9246
|
model: parsed,
|
|
9140
9247
|
...fallback?.qualifier ? { variant: fallback.qualifier } : {}
|
|
9141
9248
|
});
|
|
9249
|
+
const attemptStartedAt = Date.now();
|
|
9142
9250
|
try {
|
|
9143
|
-
|
|
9251
|
+
const budget = clock.budget(i + 1);
|
|
9252
|
+
await attemptOnce(client, attemptArgs, budget.timeoutMs, options.signal, callContext, label, options.transport, options.allowModelSuggestions, budget.firstOutputTimeoutMs);
|
|
9144
9253
|
log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
|
|
9145
9254
|
return;
|
|
9146
9255
|
} catch (error) {
|
|
9147
9256
|
lastError = error;
|
|
9257
|
+
clock.settle(error, attemptStartedAt);
|
|
9148
9258
|
if (isNonRetryable(error, options.signal))
|
|
9149
9259
|
throw error;
|
|
9150
9260
|
const remaining = fallbacks.length - i - 1;
|
|
@@ -9156,9 +9266,9 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
9156
9266
|
log2(`[${callContext}] all models exhausted; tried: ${[explicitPrimaryLabel, ...fallbacks.map((fallback) => toModelEntry(fallback)?.model ?? String(fallback))].join(", ")}; last error: ${shortErr(lastError)}`);
|
|
9157
9267
|
throw lastError ?? new Error("All fallback models failed");
|
|
9158
9268
|
}
|
|
9159
|
-
async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options) {
|
|
9269
|
+
async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options, firstOutputTimeoutMs) {
|
|
9160
9270
|
try {
|
|
9161
|
-
await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions);
|
|
9271
|
+
await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions, firstOutputTimeoutMs);
|
|
9162
9272
|
} catch (error) {
|
|
9163
9273
|
throw {
|
|
9164
9274
|
error,
|
|
@@ -9220,6 +9330,8 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
9220
9330
|
let firstError = null;
|
|
9221
9331
|
let lastError = null;
|
|
9222
9332
|
const cooledPrimary = primaryQuotaFailure(explicitPrimaryLabel);
|
|
9333
|
+
const clock = createChainClock(options, timeoutMs);
|
|
9334
|
+
const primaryStartedAt = Date.now();
|
|
9223
9335
|
try {
|
|
9224
9336
|
if (cooledPrimary)
|
|
9225
9337
|
throw {
|
|
@@ -9234,16 +9346,18 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
9234
9346
|
skipped: true
|
|
9235
9347
|
}
|
|
9236
9348
|
};
|
|
9237
|
-
|
|
9349
|
+
const budget = clock.budget(0);
|
|
9350
|
+
return await attemptAndValidate(client, baseArgs, budget.timeoutMs, options.signal, callContext, {
|
|
9238
9351
|
label: explicitPrimaryLabel,
|
|
9239
9352
|
attemptIndex: 0,
|
|
9240
9353
|
isFallback: false,
|
|
9241
9354
|
totalAttempts,
|
|
9242
9355
|
model: baseBody.model
|
|
9243
|
-
}, options);
|
|
9356
|
+
}, options, budget.firstOutputTimeoutMs);
|
|
9244
9357
|
} catch (caught) {
|
|
9245
9358
|
const failure = caught;
|
|
9246
9359
|
failedAttempts.push(failure);
|
|
9360
|
+
clock.settle(failure.error, primaryStartedAt);
|
|
9247
9361
|
firstError = failure.error;
|
|
9248
9362
|
lastError = failure.error;
|
|
9249
9363
|
if (failure.error instanceof DreamerProviderOutputFailureError && failure.error.quotaResetAt !== undefined)
|
|
@@ -9281,13 +9395,16 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
9281
9395
|
totalAttempts,
|
|
9282
9396
|
model: parsed
|
|
9283
9397
|
};
|
|
9398
|
+
const attemptStartedAt = Date.now();
|
|
9284
9399
|
try {
|
|
9285
|
-
const
|
|
9400
|
+
const budget = clock.budget(i + 1);
|
|
9401
|
+
const result = await attemptAndValidate(client, attemptArgs, budget.timeoutMs, options.signal, callContext, attempt, options, budget.firstOutputTimeoutMs);
|
|
9286
9402
|
log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
|
|
9287
9403
|
return result;
|
|
9288
9404
|
} catch (caught) {
|
|
9289
9405
|
const failure = caught;
|
|
9290
9406
|
failedAttempts.push(failure);
|
|
9407
|
+
clock.settle(failure.error, attemptStartedAt);
|
|
9291
9408
|
lastError = failure.error;
|
|
9292
9409
|
if (isNonRetryable(failure.error, options.signal)) {
|
|
9293
9410
|
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
|
|
@@ -9509,6 +9626,24 @@ function isTerminalAssistant(message) {
|
|
|
9509
9626
|
const info = infoOf(message);
|
|
9510
9627
|
return isSettledAssistant(message) && info.finish !== "tool-calls" && info.finish !== "tool_use" && !(message && typeof message === "object" && Array.isArray(message.parts) && message.parts.some((part) => part.type === "tool"));
|
|
9511
9628
|
}
|
|
9629
|
+
function showsModelOutput(message) {
|
|
9630
|
+
if (infoOf(message).role !== "assistant")
|
|
9631
|
+
return false;
|
|
9632
|
+
const tokens = sumTokensFromChildMessages([message]);
|
|
9633
|
+
if (tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite > 0)
|
|
9634
|
+
return true;
|
|
9635
|
+
const parts = message?.parts;
|
|
9636
|
+
if (!Array.isArray(parts))
|
|
9637
|
+
return false;
|
|
9638
|
+
return parts.some((part) => {
|
|
9639
|
+
if (!part || typeof part !== "object")
|
|
9640
|
+
return false;
|
|
9641
|
+
const { type, text } = part;
|
|
9642
|
+
if (type === "tool")
|
|
9643
|
+
return true;
|
|
9644
|
+
return (type === "text" || type === "reasoning") && typeof text === "string" && text.trim().length > 0;
|
|
9645
|
+
});
|
|
9646
|
+
}
|
|
9512
9647
|
function unwrapData(response) {
|
|
9513
9648
|
if (response && typeof response === "object" && "data" in response) {
|
|
9514
9649
|
return response.data;
|
|
@@ -9606,6 +9741,8 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
|
|
|
9606
9741
|
}
|
|
9607
9742
|
let sentAt = Date.now();
|
|
9608
9743
|
let sawBusy = false;
|
|
9744
|
+
noteModelActivityMonitored(signal);
|
|
9745
|
+
let sawOutput = false;
|
|
9609
9746
|
for (;; ) {
|
|
9610
9747
|
await sleep(pollIntervalMs, signal);
|
|
9611
9748
|
const hostError = activeSessionErrors.get(sessionId);
|
|
@@ -9620,6 +9757,13 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
|
|
|
9620
9757
|
}
|
|
9621
9758
|
const status = await readStatus(session, sessionId, dir, signal);
|
|
9622
9759
|
const messages = await readMessages(session, sessionId, dir, signal);
|
|
9760
|
+
if (!sawOutput && messages.some((message) => {
|
|
9761
|
+
const id = messageId2(message);
|
|
9762
|
+
return id !== null && !initialBaseline.has(id) && showsModelOutput(message);
|
|
9763
|
+
})) {
|
|
9764
|
+
sawOutput = true;
|
|
9765
|
+
noteModelOutputReceived(signal);
|
|
9766
|
+
}
|
|
9623
9767
|
if (budget) {
|
|
9624
9768
|
const latest = messages.at(-1);
|
|
9625
9769
|
const latestId = messageId2(latest);
|
|
@@ -12874,7 +13018,16 @@ function selectHiddenMessagesAtCompactionSeam(messagesBeforeTrim, skippedVisible
|
|
|
12874
13018
|
}
|
|
12875
13019
|
return markerBoundaryIndex < 0 ? [] : trimmed.slice(markerBoundaryIndex + 1);
|
|
12876
13020
|
}
|
|
12877
|
-
function
|
|
13021
|
+
function cutCoveredPrefix(messages, count, coveredInstructions) {
|
|
13022
|
+
const removed = messages.splice(0, count);
|
|
13023
|
+
for (const message of removed) {
|
|
13024
|
+
if (!isHostRenderedSystemMessage(message))
|
|
13025
|
+
continue;
|
|
13026
|
+
markCoveredInstructionRow(message.info);
|
|
13027
|
+
coveredInstructions.push(message);
|
|
13028
|
+
}
|
|
13029
|
+
}
|
|
13030
|
+
function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness) {
|
|
12878
13031
|
const cached = injectionCache.get(sessionId);
|
|
12879
13032
|
if (cached && cached.db !== db) {
|
|
12880
13033
|
clearInjectionCache(sessionId);
|
|
@@ -12891,8 +13044,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
12891
13044
|
if (prepared.compartmentEndMessageId.length > 0) {
|
|
12892
13045
|
const cutoffIndex = findBoundaryIndex(sessionId, messages, prepared.compartmentEndMessageId);
|
|
12893
13046
|
if (cutoffIndex >= 0) {
|
|
12894
|
-
|
|
12895
|
-
messages.splice(0, messages.length, ...remaining);
|
|
13047
|
+
cutCoveredPrefix(messages, cutoffIndex + (isPartialCompartmentEnd(db, sessionId, prepared.compartmentEndMessageId) ? 0 : 1), coveredInstructions);
|
|
12896
13048
|
} else {
|
|
12897
13049
|
sessionLog2(sessionId, `compartment injection: cached boundary ${prepared.compartmentEndMessageId} not in messages (already trimmed), reusing cache`);
|
|
12898
13050
|
}
|
|
@@ -13014,8 +13166,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
13014
13166
|
if (cutoffIndex >= 0) {
|
|
13015
13167
|
clearDegradedRebuild(sessionId);
|
|
13016
13168
|
skippedVisibleMessages = cutoffIndex + (isPartialCompartmentEnd(db, sessionId, trimEndMessageId) ? 0 : 1);
|
|
13017
|
-
|
|
13018
|
-
messages.splice(0, messages.length, ...remaining);
|
|
13169
|
+
cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
|
|
13019
13170
|
resultEndMessageId = trimEndMessageId;
|
|
13020
13171
|
} else {
|
|
13021
13172
|
const degradedCount = noteDegradedRebuild(sessionId);
|
|
@@ -13035,8 +13186,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
13035
13186
|
const reAnchorCutoff = findBoundaryIndex(sessionId, messages, reAnchorCompartment.endMessageId);
|
|
13036
13187
|
if (reAnchorCutoff >= 0) {
|
|
13037
13188
|
skippedVisibleMessages = reAnchorCutoff + (isPartialCompartmentEnd(db, sessionId, reAnchorCompartment.endMessageId) ? 0 : 1);
|
|
13038
|
-
|
|
13039
|
-
messages.splice(0, messages.length, ...remaining);
|
|
13189
|
+
cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
|
|
13040
13190
|
resultEndMessage = reAnchorCompartment.endMessage;
|
|
13041
13191
|
resultEndMessageId = reAnchorCompartment.endMessageId;
|
|
13042
13192
|
reAnchored = true;
|
|
@@ -18789,6 +18939,31 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
18789
18939
|
return saved;
|
|
18790
18940
|
}
|
|
18791
18941
|
|
|
18942
|
+
// src/hooks/magic-context/file-token-coverage.ts
|
|
18943
|
+
function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
|
|
18944
|
+
const filesByMessage = new Map;
|
|
18945
|
+
for (const message of messages) {
|
|
18946
|
+
const count = message.parts.filter(isFilePart).length;
|
|
18947
|
+
if (count > 0 && totals.has(message.id))
|
|
18948
|
+
filesByMessage.set(message.id, count);
|
|
18949
|
+
}
|
|
18950
|
+
if (filesByMessage.size === 0)
|
|
18951
|
+
return totals;
|
|
18952
|
+
const rows = db.prepare(`
|
|
18953
|
+
SELECT o.value AS owner, COUNT(t.id) AS count
|
|
18954
|
+
FROM json_each(?) o LEFT JOIN tags t
|
|
18955
|
+
ON t.session_id = ? AND t.type = 'file'
|
|
18956
|
+
AND t.message_id >= o.value || ':file'
|
|
18957
|
+
AND t.message_id < o.value || ':file;'
|
|
18958
|
+
GROUP BY o.value
|
|
18959
|
+
`).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
|
|
18960
|
+
for (const row of rows) {
|
|
18961
|
+
if (row.count < (filesByMessage.get(row.owner) ?? 0))
|
|
18962
|
+
totals.delete(row.owner);
|
|
18963
|
+
}
|
|
18964
|
+
return totals;
|
|
18965
|
+
}
|
|
18966
|
+
|
|
18792
18967
|
// src/hooks/magic-context/protected-tail-boundary.ts
|
|
18793
18968
|
function describeBoundaryDiagnostics(snapshot) {
|
|
18794
18969
|
return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
|
|
@@ -19014,7 +19189,7 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
19014
19189
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
19015
19190
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
19016
19191
|
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
19017
|
-
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
|
|
19192
|
+
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
|
|
19018
19193
|
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
19019
19194
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
19020
19195
|
cacheNamespace: ctx.cacheNamespace,
|
|
@@ -19257,9 +19432,10 @@ function resolveBoundaryContext(args) {
|
|
|
19257
19432
|
migrationFloorActive = seedResult.seeded;
|
|
19258
19433
|
}
|
|
19259
19434
|
const calibration = sessionDecisionCalibration(args.db, args.sessionId);
|
|
19260
|
-
const storedTokenTotalsForMessages = (messageIds) => {
|
|
19435
|
+
const storedTokenTotalsForMessages = (messageIds, messages = []) => {
|
|
19261
19436
|
try {
|
|
19262
|
-
|
|
19437
|
+
const totals = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds).totals;
|
|
19438
|
+
return omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, totals);
|
|
19263
19439
|
} catch (error) {
|
|
19264
19440
|
sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
|
|
19265
19441
|
return;
|
|
@@ -19294,7 +19470,7 @@ function resolveWrapupProtectedTailBoundary(args) {
|
|
|
19294
19470
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
19295
19471
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
19296
19472
|
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
19297
|
-
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
|
|
19473
|
+
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
|
|
19298
19474
|
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
19299
19475
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
19300
19476
|
cacheNamespace: ctx.cacheNamespace,
|
|
@@ -21340,4 +21516,4 @@ async function executeContextRecomp(deps, options = {}) {
|
|
|
21340
21516
|
return (await executeContextRecompWithResult(deps, options)).message;
|
|
21341
21517
|
}
|
|
21342
21518
|
|
|
21343
|
-
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, queueMemoryMutation, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, failedInvocationStatus, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, prepareCompactionMarkerCandidates, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|
|
21519
|
+
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, queueMemoryMutation, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, failedInvocationStatus, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, prepareCompactionMarkerCandidates, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|
|
@@ -35,7 +35,7 @@ import {
|
|
|
35
35
|
} from "./index-58e3y90n.js";
|
|
36
36
|
import {
|
|
37
37
|
cleanUserText2
|
|
38
|
-
} from "./index-
|
|
38
|
+
} from "./index-9zcsy3hh.js";
|
|
39
39
|
import {
|
|
40
40
|
recordMessageFtsRowid2,
|
|
41
41
|
recordIndexedMessageTime2,
|
|
@@ -1253,6 +1253,15 @@ class V2StoreReader {
|
|
|
1253
1253
|
ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES, throughSeq, limit).map(decode);
|
|
1254
1254
|
});
|
|
1255
1255
|
}
|
|
1256
|
+
instructionRowsThrough(sessionID, throughSeq) {
|
|
1257
|
+
return trackDecodeOperation("instructionRowsThrough", () => {
|
|
1258
|
+
if (!Number.isSafeInteger(throughSeq))
|
|
1259
|
+
throw new Error("Invalid seq upper bound");
|
|
1260
|
+
return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1261
|
+
WHERE session_id = ? AND type = 'system' AND seq <= ?
|
|
1262
|
+
ORDER BY seq ASC`).all(sessionID, throughSeq).map(decode);
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1256
1265
|
sequenceForId(sessionID, id) {
|
|
1257
1266
|
if (!id)
|
|
1258
1267
|
return;
|