@cortexkit/opencode-magic-context 0.49.99 → 0.49.102
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/agents/dreamer.d.ts +3 -2
- package/dist/agents/dreamer.d.ts.map +1 -1
- package/dist/agents/permissions.d.ts +2 -0
- package/dist/agents/permissions.d.ts.map +1 -1
- package/dist/agents/smart-notes-dreamer-gate.fixture.d.ts +3 -1
- package/dist/agents/smart-notes-dreamer-gate.fixture.d.ts.map +1 -1
- package/dist/auto-search-worker.js +1 -1
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-z77a2jpx.js → context-4fjwzqqa.js} +497 -52
- package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts +1 -0
- package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-prompts.d.ts +7 -1
- package/dist/features/magic-context/dreamer/task-prompts.d.ts.map +1 -1
- package/dist/features/magic-context/overflow-detection.d.ts +7 -0
- package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
- package/dist/hooks/magic-context/emergency-drop.d.ts +8 -1
- package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +4 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts +1 -0
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
- package/dist/hooks/magic-context/host-served-rows.d.ts +7 -0
- package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
- package/dist/hooks/magic-context/image-token-estimate.d.ts +1 -0
- package/dist/hooks/magic-context/image-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/provider-refusal-count.d.ts +84 -0
- package/dist/hooks/magic-context/provider-refusal-count.d.ts.map +1 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts +2 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +1 -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-9q7wzca8.js → index-2b7g81z7.js} +70 -25
- package/dist/{index-xw608ytx.js → index-3cgh0ght.js} +1 -1
- package/dist/{index-mfx7hzyc.js → index-4dywj733.js} +1 -1
- package/dist/{index-dnxnj42p.js → index-634cww4x.js} +4 -4
- package/dist/{index-h1xvt8fw.js → index-63kp05sy.js} +1 -1
- package/dist/{index-5xrj3zp4.js → index-fbg61b3d.js} +3 -3
- package/dist/{index-tyjx0dwz.js → index-jjy4shhy.js} +1 -1
- package/dist/{index-0wj3jr8n.js → index-k4c0majv.js} +3 -3
- package/dist/{index-5nf2a14a.js → index-k7yytqrd.js} +364 -76
- package/dist/{index-ajmy0v5j.js → index-ke0mkz7g.js} +13 -0
- package/dist/{index-8hhmv0ff.js → index-kjhgxkdx.js} +1 -1
- package/dist/{index-4qc8d9by.js → index-mx4j316q.js} +21 -14
- package/dist/{index-9eqt7755.js → index-rakm1eay.js} +2 -2
- package/dist/{index-w6kcwhhj.js → index-rjxg7a7m.js} +212 -4
- package/dist/{index-xbna9akt.js → index-sgsaf60r.js} +5 -5
- package/dist/{index-507a56zb.js → index-tbhbxb09.js} +5 -5
- package/dist/{index-em72jhc0.js → index-y33x200y.js} +2 -2
- package/dist/{index-kjdys7e2.js → index-zg5r2syy.js} +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +154 -41
- package/dist/{message-index-bounded-6y7p974x.js → message-index-bounded-289186ah.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/plugin/messages-transform.d.ts +1 -0
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/plugin/provider-refusal-v1.d.ts +15 -0
- package/dist/plugin/provider-refusal-v1.d.ts.map +1 -0
- package/dist/plugin/subagent-tool-policy.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-9ejnbe07.js → read-session-chunk-frnwxnjg.js} +2 -2
- package/dist/{recomp-orchestrator-9k91tkyx.js → recomp-orchestrator-cvsfmctf.js} +8 -8
- package/dist/{render-9712q3gp.js → render-2a83mgrp.js} +7 -7
- package/dist/{search-archive-5jr011gc.js → search-archive-f5dzec0e.js} +5 -5
- package/dist/{search-yhaxy3e6.js → search-fxtb4844.js} +6 -6
- package/dist/{storage-tags-vd3sgd4s.js → storage-tags-2d2ba8e9.js} +1 -1
- package/dist/{store-reader-01e8t5j0.js → store-reader-c5fwa9qx.js} +1 -1
- package/dist/{store-235fjtsn.js → store-wpx314rk.js} +2 -2
- package/dist/tools/ctx-memory/constants.d.ts +2 -0
- package/dist/tools/ctx-memory/constants.d.ts.map +1 -1
- package/dist/tools/ctx-memory/tools.d.ts +1 -0
- package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-mf5js6cs.js → transform-postprocess-phase-fyw30790.js} +9 -9
- package/dist/v2/auto-search-worker.js +1 -1
- package/dist/v2/chunk-embedding-write-worker.js +1 -1
- package/dist/v2/{context-4fej2dzv.js → context-08pwkj6g.js} +872 -139
- package/dist/v2/fold/instruction-supersession.d.ts +18 -1
- package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts +2 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
- package/dist/v2/hooks/http-refusal-count.d.ts +41 -0
- package/dist/v2/hooks/http-refusal-count.d.ts.map +1 -0
- package/dist/v2/hooks/overflow-recovery.d.ts +3 -0
- package/dist/v2/hooks/overflow-recovery.d.ts.map +1 -1
- package/dist/v2/hooks/revert-message-state.d.ts +6 -0
- package/dist/v2/hooks/revert-message-state.d.ts.map +1 -1
- package/dist/v2/hooks/tools.d.ts.map +1 -1
- package/dist/v2/hooks/types.d.ts +5 -0
- package/dist/v2/hooks/types.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-wj5rs9az.js → message-index-bounded-p69v4wpy.js} +3 -3
- package/dist/v2/migration-worker.js +1 -1
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-89ep8br4.js → read-session-chunk-qzw3vedr.js} +2 -2
- package/dist/v2/{recomp-orchestrator-9wap1z1d.js → recomp-orchestrator-4mrvs5yc.js} +7 -7
- package/dist/v2/{render-bzzypsgy.js → render-r2djh67k.js} +7 -7
- package/dist/v2/{search-ymm2crs3.js → search-51qr14ed.js} +5 -5
- package/dist/v2/{search-archive-4yr4hw2m.js → search-archive-4bq4ff8q.js} +5 -5
- package/dist/v2/{server-8xgs110k.js → server-606mnrv4.js} +212 -4
- package/dist/v2/{server-7861dnm3.js → server-awth2wsg.js} +1 -1
- package/dist/v2/{server-d0h1gjz2.js → server-b25kh28g.js} +3 -3
- package/dist/v2/{server-62t1852h.js → server-b25nvm9c.js} +1 -1
- package/dist/v2/{server-6mq43ear.js → server-c1vcbszm.js} +1 -1
- package/dist/v2/{server-xn7fpv2b.js → server-d2a639dg.js} +3 -3
- package/dist/v2/{server-6r3b0re0.js → server-f49pxtwf.js} +41 -8
- package/dist/v2/{server-e14d7ebh.js → server-mc5t7k8v.js} +1 -1
- package/dist/v2/{server-zedjjdc5.js → server-nbdfv1wx.js} +2 -2
- package/dist/v2/{server-e8ybwfv8.js → server-p2wxmjc3.js} +2 -2
- package/dist/v2/{server-ysg14rv1.js → server-qg8jyfxa.js} +13 -0
- package/dist/v2/{server-h95cdc30.js → server-s3m2y97h.js} +1 -1
- package/dist/v2/{server-1bks09js.js → server-zzwje0mz.js} +5 -5
- package/dist/v2/server.js +2 -2
- package/dist/v2/{storage-tags-8kktww54.js → storage-tags-4t9fb4ch.js} +1 -1
- package/dist/v2/{store-0kjfynwp.js → store-mba47sxn.js} +2 -2
- package/dist/v2/{store-reader-w0srb18d.js → store-reader-w7w8vfsy.js} +1 -1
- package/dist/v2/store-reader.d.ts +7 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{v2-archive-reader-veyqp15a.js → v2-archive-reader-avcf7a5n.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-89cg7p41.js → wrapup-orchestrator-zwpjqymz.js} +7 -7
- package/dist/{v2-archive-reader-3s332fn7.js → v2-archive-reader-cnhvhggz.js} +1 -1
- package/dist/{wrapup-orchestrator-41rt7etq.js → wrapup-orchestrator-g1gnymt3.js} +9 -9
- package/package.json +1 -1
- package/src/agents/dreamer.ts +3 -2
- package/src/agents/hidden-agent-registrations.ts +2 -2
- package/src/agents/permissions.test.ts +89 -3
- package/src/agents/permissions.ts +32 -0
- package/src/agents/smart-notes-dreamer-gate.fixture.ts +27 -4
- package/src/agents/smart-notes-dreamer-gate.test.ts +5 -1
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
|
+
CTX_MEMORY_CURATE_TOOL_NAME,
|
|
3
|
+
DREAMER_ONLY_MEMORY_TOOL_NAMES,
|
|
4
|
+
DREAMER_AGENT,
|
|
2
5
|
getMagicContextBuiltinCommands,
|
|
3
6
|
getProtectedTokensTierOverrides,
|
|
4
7
|
loadPluginConfigDetailed,
|
|
@@ -51,7 +54,7 @@ import {
|
|
|
51
54
|
clearNoteNudgeTriggerOnly,
|
|
52
55
|
nonNarrativeStoredGapRanges,
|
|
53
56
|
getActiveCompartmentRun
|
|
54
|
-
} from "./index-
|
|
57
|
+
} from "./index-2b7g81z7.js";
|
|
55
58
|
import"./index-sd3egckz.js";
|
|
56
59
|
import {
|
|
57
60
|
getHarness2
|
|
@@ -111,6 +114,10 @@ import {
|
|
|
111
114
|
PROVIDER_OVERFLOW_NOTICE,
|
|
112
115
|
noteServedRecoveryForOverflowHint,
|
|
113
116
|
holdOverflowResendHint,
|
|
117
|
+
ProviderRefusalCounts,
|
|
118
|
+
snapshotRefusalHistory,
|
|
119
|
+
pushRefusalFields,
|
|
120
|
+
withProviderRefusalPass,
|
|
114
121
|
createM0RenderOptions,
|
|
115
122
|
lkgReplayLimit,
|
|
116
123
|
measureLkgReplay,
|
|
@@ -137,7 +144,7 @@ import {
|
|
|
137
144
|
storedSubagentMode,
|
|
138
145
|
createCtxExpandTools,
|
|
139
146
|
createCtxMemoryTools,
|
|
140
|
-
|
|
147
|
+
createDreamerMemoryTools,
|
|
141
148
|
CTX_NOTE_DESCRIPTION,
|
|
142
149
|
withoutSmartNoteText,
|
|
143
150
|
createCtxNoteTools,
|
|
@@ -146,7 +153,7 @@ import {
|
|
|
146
153
|
applyJsonSchemaParameterDescriptions,
|
|
147
154
|
MagicContextRpcServer,
|
|
148
155
|
subagentTemperature
|
|
149
|
-
} from "./index-
|
|
156
|
+
} from "./index-k7yytqrd.js";
|
|
150
157
|
import {
|
|
151
158
|
invalidateAutoEmbedSession,
|
|
152
159
|
clearEmbedSessionState
|
|
@@ -212,13 +219,15 @@ import {
|
|
|
212
219
|
getSlot,
|
|
213
220
|
dropSlot,
|
|
214
221
|
copySessionStateForClone
|
|
215
|
-
} from "./index-
|
|
216
|
-
import"./index-
|
|
222
|
+
} from "./index-y33x200y.js";
|
|
223
|
+
import"./index-jjy4shhy.js";
|
|
217
224
|
import {
|
|
218
225
|
stripPersistedAssistantText,
|
|
219
226
|
currentReclaimableToolOutputCount,
|
|
220
227
|
isRecord,
|
|
221
228
|
contentTagOwnerMessageId,
|
|
229
|
+
estimateImageTokensFromDataUrl,
|
|
230
|
+
estimateImageTokensFromBase64,
|
|
222
231
|
isDroppedToolOutput,
|
|
223
232
|
evaluateChannel2,
|
|
224
233
|
buildChannel2Reminder,
|
|
@@ -251,14 +260,17 @@ import {
|
|
|
251
260
|
getObservedEpochFloor,
|
|
252
261
|
isPrefixBoundThinkingModel,
|
|
253
262
|
detectOverflow,
|
|
263
|
+
isMeasuredRefusalStatusVeto,
|
|
264
|
+
isProviderSizeRefusal,
|
|
254
265
|
isProviderRateLimit,
|
|
255
266
|
modelAcceptsEmptyContent,
|
|
256
267
|
markServedShapeRepair,
|
|
257
268
|
getEmptyImageParts,
|
|
269
|
+
estimateFrozenRequestInputTokens,
|
|
258
270
|
estimateFinalWireInputTokens,
|
|
259
271
|
getMaxTagNumberBySession2,
|
|
260
272
|
getTagsBySession2
|
|
261
|
-
} from "./index-
|
|
273
|
+
} from "./index-rjxg7a7m.js";
|
|
262
274
|
import {
|
|
263
275
|
BoundedSessionMap,
|
|
264
276
|
getTableColumnNames,
|
|
@@ -301,10 +313,10 @@ import {
|
|
|
301
313
|
cleanUserText2,
|
|
302
314
|
readRawSessionMessageIdOrdinalsForRange2,
|
|
303
315
|
readRawSessionMessageOrdinalById2
|
|
304
|
-
} from "./index-
|
|
316
|
+
} from "./index-kjhgxkdx.js";
|
|
305
317
|
import {
|
|
306
318
|
scheduleClearAndReindex
|
|
307
|
-
} from "./index-
|
|
319
|
+
} from "./index-63kp05sy.js";
|
|
308
320
|
import {
|
|
309
321
|
startBootDeadline,
|
|
310
322
|
getSchemaFenceRejection,
|
|
@@ -314,7 +326,7 @@ import {
|
|
|
314
326
|
openDatabaseAsync,
|
|
315
327
|
isDatabasePersisted,
|
|
316
328
|
getDatabasePersistenceError
|
|
317
|
-
} from "./index-
|
|
329
|
+
} from "./index-3cgh0ght.js";
|
|
318
330
|
import"./index-fr0wbhdn.js";
|
|
319
331
|
import"./index-hyvxmz3e.js";
|
|
320
332
|
import {
|
|
@@ -322,7 +334,7 @@ import {
|
|
|
322
334
|
RAW_MESSAGE_TYPES2,
|
|
323
335
|
V2StoreReaderPool2,
|
|
324
336
|
V2StoreReader2
|
|
325
|
-
} from "./index-
|
|
337
|
+
} from "./index-ke0mkz7g.js";
|
|
326
338
|
import"./index-fb3zxn06.js";
|
|
327
339
|
import"./index-ab86c21b.js";
|
|
328
340
|
import {
|
|
@@ -344,7 +356,7 @@ import {
|
|
|
344
356
|
servedHeadChanged,
|
|
345
357
|
noteHostCheckpointCommit,
|
|
346
358
|
isSyntheticHeadMessage2
|
|
347
|
-
} from "./index-
|
|
359
|
+
} from "./index-mx4j316q.js";
|
|
348
360
|
import"./index-qxzk5s30.js";
|
|
349
361
|
import"./index-qt1qqasc.js";
|
|
350
362
|
import {
|
|
@@ -366,8 +378,8 @@ import {
|
|
|
366
378
|
} from "./index-y14pawe1.js";
|
|
367
379
|
import"./index-y5f5yg5a.js";
|
|
368
380
|
import"./index-61a853ky.js";
|
|
369
|
-
import"./index-
|
|
370
|
-
import"./index-
|
|
381
|
+
import"./index-634cww4x.js";
|
|
382
|
+
import"./index-fbg61b3d.js";
|
|
371
383
|
import"./index-cayqdwf9.js";
|
|
372
384
|
import {
|
|
373
385
|
detectConflicts
|
|
@@ -397,12 +409,12 @@ import {
|
|
|
397
409
|
readV2RawMessagePagesForConversion2,
|
|
398
410
|
createV2RawMessageReader2,
|
|
399
411
|
createV2RawMessageProvider2
|
|
400
|
-
} from "./index-
|
|
412
|
+
} from "./index-4dywj733.js";
|
|
401
413
|
import"./index-fmsr7v69.js";
|
|
402
|
-
import"./index-
|
|
403
|
-
import"./index-
|
|
404
|
-
import"./index-
|
|
405
|
-
import"./index-
|
|
414
|
+
import"./index-rakm1eay.js";
|
|
415
|
+
import"./index-zg5r2syy.js";
|
|
416
|
+
import"./index-sgsaf60r.js";
|
|
417
|
+
import"./index-k4c0majv.js";
|
|
406
418
|
import {
|
|
407
419
|
markHostInstructionRow,
|
|
408
420
|
hostInstructionRow,
|
|
@@ -1096,6 +1108,82 @@ var coveredOn = (value) => typeof value === "object" && value !== null && value.
|
|
|
1096
1108
|
function retiredLiveInstructionIDs(db, sessionID) {
|
|
1097
1109
|
return decode(readReplayEnvelope(db, sessionID)[namespace]);
|
|
1098
1110
|
}
|
|
1111
|
+
var throughNamespace = "instructionSupersessionThrough";
|
|
1112
|
+
function decodeThrough(value, sessionID) {
|
|
1113
|
+
if (value === undefined)
|
|
1114
|
+
return { kind: "absent" };
|
|
1115
|
+
const { session, through } = value ?? {};
|
|
1116
|
+
if (typeof session !== "string" || session.length === 0 || typeof through !== "number" || !Number.isSafeInteger(through) || through < -1)
|
|
1117
|
+
throw new Error("Invalid instruction supersession replay state");
|
|
1118
|
+
return session === sessionID ? { kind: "own", through } : { kind: "foreign" };
|
|
1119
|
+
}
|
|
1120
|
+
var pendingLowerings = new WeakMap;
|
|
1121
|
+
function pendingLowering(db, sessionID) {
|
|
1122
|
+
return pendingLowerings.get(db)?.get(sessionID);
|
|
1123
|
+
}
|
|
1124
|
+
function setPendingLowering(db, sessionID, through) {
|
|
1125
|
+
let sessions = pendingLowerings.get(db);
|
|
1126
|
+
if (!sessions)
|
|
1127
|
+
pendingLowerings.set(db, sessions = new Map);
|
|
1128
|
+
sessions.set(sessionID, { through });
|
|
1129
|
+
}
|
|
1130
|
+
function clearPendingLowering(db, sessionID, pending) {
|
|
1131
|
+
const sessions = pendingLowerings.get(db);
|
|
1132
|
+
if (sessions?.get(sessionID) === pending)
|
|
1133
|
+
sessions.delete(sessionID);
|
|
1134
|
+
}
|
|
1135
|
+
function readThrough(db, sessionID) {
|
|
1136
|
+
const stored = decodeThrough(readReplayEnvelope(db, sessionID)[throughNamespace], sessionID);
|
|
1137
|
+
const pending = pendingLowering(db, sessionID);
|
|
1138
|
+
return stored.kind === "own" && pending && pending.through < stored.through ? { kind: "own", through: pending.through } : stored;
|
|
1139
|
+
}
|
|
1140
|
+
function isRetiredThrough(row, through) {
|
|
1141
|
+
return row.seq <= through && isMarkedInstructionUpdate(row);
|
|
1142
|
+
}
|
|
1143
|
+
var revertCounts = new WeakMap;
|
|
1144
|
+
function revertCount(db, sessionID) {
|
|
1145
|
+
return revertCounts.get(db)?.get(sessionID) ?? 0;
|
|
1146
|
+
}
|
|
1147
|
+
function lowerRetiredInstructionThrough(db, sessionID, before) {
|
|
1148
|
+
let sessions = revertCounts.get(db);
|
|
1149
|
+
if (!sessions)
|
|
1150
|
+
revertCounts.set(db, sessions = new Map);
|
|
1151
|
+
sessions.set(sessionID, revertCount(db, sessionID) + 1);
|
|
1152
|
+
return saveLowering(db, sessionID, before);
|
|
1153
|
+
}
|
|
1154
|
+
function saveLowering(db, sessionID, before) {
|
|
1155
|
+
const pending = pendingLowering(db, sessionID);
|
|
1156
|
+
const limit = Math.min(before ?? -1, pending?.through ?? Number.POSITIVE_INFINITY);
|
|
1157
|
+
let failure = "the replay document could not be written";
|
|
1158
|
+
let saved = false;
|
|
1159
|
+
try {
|
|
1160
|
+
saved = updateReplayDocument(db, sessionID, (doc) => {
|
|
1161
|
+
const current = decodeThrough(doc[throughNamespace], sessionID);
|
|
1162
|
+
if (current.kind !== "own" || current.through <= limit)
|
|
1163
|
+
return false;
|
|
1164
|
+
doc.version = 2;
|
|
1165
|
+
doc[throughNamespace] = { session: sessionID, through: limit };
|
|
1166
|
+
return true;
|
|
1167
|
+
});
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
failure = error;
|
|
1170
|
+
}
|
|
1171
|
+
if (saved) {
|
|
1172
|
+
if (pending)
|
|
1173
|
+
clearPendingLowering(db, sessionID, pending);
|
|
1174
|
+
return true;
|
|
1175
|
+
}
|
|
1176
|
+
if (pending?.through !== limit) {
|
|
1177
|
+
setPendingLowering(db, sessionID, limit);
|
|
1178
|
+
sessionLog2(sessionID, "committed revert: retired instruction rows kept lowered in memory until saved:", failure);
|
|
1179
|
+
}
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
1182
|
+
function retryRetiredInstructionLowering(db, sessionID) {
|
|
1183
|
+
const pending = pendingLowering(db, sessionID);
|
|
1184
|
+
if (pending)
|
|
1185
|
+
saveLowering(db, sessionID, pending.through);
|
|
1186
|
+
}
|
|
1099
1187
|
function coveredInstructionSupersessionOn(db, sessionID) {
|
|
1100
1188
|
return coveredOn(readReplayEnvelope(db, sessionID)[coveredNamespace]);
|
|
1101
1189
|
}
|
|
@@ -1150,7 +1238,8 @@ function isMarkedInstructionUpdate(row) {
|
|
|
1150
1238
|
const sources = metadata.instructionSources;
|
|
1151
1239
|
return row.type === "system" && "notice" in metadata && metadata.notice === "instructions" && Array.isArray(sources) && sources.length > 0 && sources.every((source) => typeof source === "string" && source.length > 0);
|
|
1152
1240
|
}
|
|
1153
|
-
function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
1241
|
+
function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Map, covered = [], checkpointSequence, checkpointCoveredThrough, localCheckpointSequence) {
|
|
1242
|
+
const builtAfterReverts = revertCount(db, sessionID);
|
|
1154
1243
|
const instructionRows = (list) => list.flatMap((message) => {
|
|
1155
1244
|
const row = hostInstructionRow(message.info);
|
|
1156
1245
|
return row ? [{ message, row }] : [];
|
|
@@ -1158,7 +1247,19 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
1158
1247
|
const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
|
|
1159
1248
|
const rows = [...coveredRows, ...instructionRows(messages)];
|
|
1160
1249
|
const coveredMessages = new Set(coveredRows.map(({ message }) => message));
|
|
1161
|
-
const retired = rows.length ? retiredLiveInstructionIDs(db, sessionID) :
|
|
1250
|
+
const retired = new Set(rows.length ? retiredLiveInstructionIDs(db, sessionID) : []);
|
|
1251
|
+
let stored = { kind: "foreign" };
|
|
1252
|
+
if (rows.length)
|
|
1253
|
+
stored = readThrough(db, sessionID);
|
|
1254
|
+
else if (checkpointSequence !== undefined) {
|
|
1255
|
+
try {
|
|
1256
|
+
stored = readThrough(db, sessionID);
|
|
1257
|
+
} catch {}
|
|
1258
|
+
}
|
|
1259
|
+
const through = stored.kind === "own" ? stored.through : -1;
|
|
1260
|
+
for (const { row } of rows)
|
|
1261
|
+
if (isRetiredThrough(row, through))
|
|
1262
|
+
retired.add(row.id);
|
|
1162
1263
|
const coveredFollowed = rows.length > 0 && (coveredRows.length > 0 || permitted) && coveredInstructionSupersessionOn(db, sessionID);
|
|
1163
1264
|
const switchCovered = permitted && rows.length > 0 && !coveredFollowed && coveredSupersessionEnabled;
|
|
1164
1265
|
const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
|
|
@@ -1171,6 +1272,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
1171
1272
|
const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
|
|
1172
1273
|
const omitted = new Set([...retired, ...newlyRetired]);
|
|
1173
1274
|
const omits = (message, id) => omitted.has(id) && (!coveredMessages.has(message) || coveredFollowed || switchCovered);
|
|
1275
|
+
let servedFrom = Number.POSITIVE_INFINITY;
|
|
1276
|
+
for (const { message, row } of rows) {
|
|
1277
|
+
if (isMarkedInstructionUpdate(row) && !omits(message, row.id))
|
|
1278
|
+
servedFrom = Math.min(servedFrom, row.seq);
|
|
1279
|
+
}
|
|
1280
|
+
const coverable = (seq) => Math.min(seq, servedFrom - 1);
|
|
1281
|
+
const initialThrough = stored.kind === "absent" && localCheckpointSequence !== undefined ? Math.max(-1, coverable(localCheckpointSequence - 1)) : undefined;
|
|
1174
1282
|
const edits = [];
|
|
1175
1283
|
for (const { message, row } of rows) {
|
|
1176
1284
|
if (!omits(message, row.id))
|
|
@@ -1180,33 +1288,81 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
1180
1288
|
edits.push(message);
|
|
1181
1289
|
message.parts = [];
|
|
1182
1290
|
}
|
|
1291
|
+
const decisions = newlyRetired.size > 0 || switchCovered;
|
|
1292
|
+
const pending = pendingLowering(db, sessionID);
|
|
1293
|
+
let wrote;
|
|
1183
1294
|
return {
|
|
1184
1295
|
edits,
|
|
1185
|
-
hasDecisions:
|
|
1296
|
+
hasDecisions: decisions,
|
|
1186
1297
|
record(doc) {
|
|
1187
|
-
if (
|
|
1298
|
+
if (!decisions)
|
|
1188
1299
|
return false;
|
|
1189
1300
|
const current = decode(doc[namespace]);
|
|
1190
1301
|
if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
|
|
1191
1302
|
return false;
|
|
1192
|
-
|
|
1193
|
-
|
|
1303
|
+
const storedNow = decodeThrough(doc[throughNamespace], sessionID);
|
|
1304
|
+
let nextThrough = storedNow.kind === "own" ? Math.min(storedNow.through, pending?.through ?? Number.POSITIVE_INFINITY) : undefined;
|
|
1305
|
+
let dropped = -1;
|
|
1306
|
+
if (revertCount(db, sessionID) === builtAfterReverts) {
|
|
1307
|
+
for (const [id, seq] of folded) {
|
|
1308
|
+
if (current.delete(id) && Number.isFinite(seq))
|
|
1309
|
+
dropped = Math.max(dropped, seq);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1194
1312
|
for (const id of newlyRetired)
|
|
1195
1313
|
current.add(id);
|
|
1314
|
+
if (coverable(dropped) >= 0)
|
|
1315
|
+
nextThrough = Math.max(nextThrough ?? -1, coverable(dropped));
|
|
1196
1316
|
doc.version = 2;
|
|
1197
1317
|
doc[namespace] = [...current];
|
|
1198
1318
|
if (switchCovered)
|
|
1199
1319
|
doc[coveredNamespace] = { on: true };
|
|
1320
|
+
wrote = undefined;
|
|
1321
|
+
if (nextThrough !== undefined && (storedNow.kind !== "own" || nextThrough !== storedNow.through)) {
|
|
1322
|
+
doc[throughNamespace] = { session: sessionID, through: nextThrough };
|
|
1323
|
+
wrote = nextThrough;
|
|
1324
|
+
}
|
|
1200
1325
|
return true;
|
|
1201
1326
|
},
|
|
1202
1327
|
markRetired() {
|
|
1328
|
+
if (pending && wrote !== undefined)
|
|
1329
|
+
clearPendingLowering(db, sessionID, pending);
|
|
1203
1330
|
for (const { message, row } of rows) {
|
|
1204
1331
|
if (omits(message, row.id))
|
|
1205
1332
|
markRetiredInstructionRow(message.info);
|
|
1206
1333
|
}
|
|
1334
|
+
},
|
|
1335
|
+
settle() {
|
|
1336
|
+
if (initialThrough === undefined || revertCount(db, sessionID) !== builtAfterReverts)
|
|
1337
|
+
return;
|
|
1338
|
+
const initial = initialThrough;
|
|
1339
|
+
let failure = "the replay document could not be written";
|
|
1340
|
+
try {
|
|
1341
|
+
const saved = updateReplayDocument(db, sessionID, (doc) => {
|
|
1342
|
+
const now = decodeThrough(doc[throughNamespace], sessionID);
|
|
1343
|
+
const raisable = now.kind === "absent" || now.kind === "own" && wrote !== undefined && now.through === wrote && wrote < initial;
|
|
1344
|
+
if (!raisable)
|
|
1345
|
+
return false;
|
|
1346
|
+
doc.version = 2;
|
|
1347
|
+
doc[throughNamespace] = { session: sessionID, through: initial };
|
|
1348
|
+
return true;
|
|
1349
|
+
});
|
|
1350
|
+
if (saved)
|
|
1351
|
+
return;
|
|
1352
|
+
} catch (error) {
|
|
1353
|
+
failure = error;
|
|
1354
|
+
}
|
|
1355
|
+
let logged = initialFailuresLogged.get(db);
|
|
1356
|
+
if (!logged)
|
|
1357
|
+
initialFailuresLogged.set(db, logged = new Set);
|
|
1358
|
+
if (logged.has(sessionID))
|
|
1359
|
+
return;
|
|
1360
|
+
logged.add(sessionID);
|
|
1361
|
+
sessionLog2(sessionID, "retired instruction rows: value from the checkpoint not saved; a later pass tries again:", failure);
|
|
1207
1362
|
}
|
|
1208
1363
|
};
|
|
1209
1364
|
}
|
|
1365
|
+
var initialFailuresLogged = new WeakMap;
|
|
1210
1366
|
|
|
1211
1367
|
// src/v2/fold/manual-baseline.ts
|
|
1212
1368
|
var text = (value) => value == null ? null : typeof value === "string" ? value : Buffer.from(value).toString("utf8");
|
|
@@ -6549,6 +6705,193 @@ function hiddenTerminalError(event) {
|
|
|
6549
6705
|
return;
|
|
6550
6706
|
}
|
|
6551
6707
|
|
|
6708
|
+
// src/v2/hooks/http-refusal-count.ts
|
|
6709
|
+
class V2HttpRefusalCounts {
|
|
6710
|
+
counts;
|
|
6711
|
+
requests = new WeakMap;
|
|
6712
|
+
associated = new WeakSet;
|
|
6713
|
+
inFlight = new Map;
|
|
6714
|
+
constructor(counts) {
|
|
6715
|
+
this.counts = counts;
|
|
6716
|
+
}
|
|
6717
|
+
capture({ sessionID, model, request }) {
|
|
6718
|
+
const pass = this.counts.latest(sessionID);
|
|
6719
|
+
if (!pass)
|
|
6720
|
+
return;
|
|
6721
|
+
this.release(sessionID);
|
|
6722
|
+
this.associated.add(request);
|
|
6723
|
+
if (request.signal.aborted)
|
|
6724
|
+
return;
|
|
6725
|
+
const attempt = { sessionID, model: `${model.providerID}/${model.id}`, pass };
|
|
6726
|
+
this.requests.set(request, attempt);
|
|
6727
|
+
this.inFlight.set(sessionID, request);
|
|
6728
|
+
const abort = () => this.releaseNonSizeAttempt(request);
|
|
6729
|
+
request.signal.addEventListener("abort", abort, { once: true });
|
|
6730
|
+
attempt.detachAbort = () => request.signal.removeEventListener("abort", abort);
|
|
6731
|
+
try {
|
|
6732
|
+
attempt.body = request.clone();
|
|
6733
|
+
} catch {}
|
|
6734
|
+
}
|
|
6735
|
+
async observe(draft, errorBody) {
|
|
6736
|
+
const attempt = this.detach(draft.request);
|
|
6737
|
+
if (!attempt) {
|
|
6738
|
+
if (draft.response.ok)
|
|
6739
|
+
this.accept(draft.sessionID);
|
|
6740
|
+
return this.associated.has(draft.request);
|
|
6741
|
+
}
|
|
6742
|
+
const model = `${draft.model.providerID}/${draft.model.id}`;
|
|
6743
|
+
if (draft.sessionID !== attempt.sessionID || model !== attempt.model) {
|
|
6744
|
+
cancelBody(attempt);
|
|
6745
|
+
return true;
|
|
6746
|
+
}
|
|
6747
|
+
if (draft.response.ok) {
|
|
6748
|
+
cancelBody(attempt);
|
|
6749
|
+
this.accept(draft.sessionID);
|
|
6750
|
+
return true;
|
|
6751
|
+
}
|
|
6752
|
+
if (!isProviderSizeRefusal({ status: draft.response.status, responseBody: errorBody })) {
|
|
6753
|
+
this.counts.discardPreparation(attempt.sessionID, attempt.pass);
|
|
6754
|
+
cancelBody(attempt);
|
|
6755
|
+
return true;
|
|
6756
|
+
}
|
|
6757
|
+
this.counts.discardDraft(attempt.sessionID, attempt.pass);
|
|
6758
|
+
try {
|
|
6759
|
+
const body = await attempt.body?.json();
|
|
6760
|
+
const tokens = countFullRequest(body);
|
|
6761
|
+
if (tokens !== undefined)
|
|
6762
|
+
this.counts.refusal(attempt.sessionID, attempt.model, attempt.pass, tokens);
|
|
6763
|
+
} catch {} finally {
|
|
6764
|
+
cancelBody(attempt);
|
|
6765
|
+
this.counts.discardPreparation(attempt.sessionID, attempt.pass);
|
|
6766
|
+
}
|
|
6767
|
+
return true;
|
|
6768
|
+
}
|
|
6769
|
+
accept(sessionID) {
|
|
6770
|
+
this.counts.forget(sessionID);
|
|
6771
|
+
this.release(sessionID);
|
|
6772
|
+
}
|
|
6773
|
+
endRun(sessionID) {
|
|
6774
|
+
const request = this.inFlight.get(sessionID);
|
|
6775
|
+
this.counts.endRun(sessionID, () => {
|
|
6776
|
+
if (request)
|
|
6777
|
+
this.discard(request);
|
|
6778
|
+
});
|
|
6779
|
+
}
|
|
6780
|
+
release(sessionID, nonSizeFailure = false) {
|
|
6781
|
+
const request = this.inFlight.get(sessionID);
|
|
6782
|
+
if (!request)
|
|
6783
|
+
return;
|
|
6784
|
+
if (nonSizeFailure)
|
|
6785
|
+
this.releaseNonSizeAttempt(request);
|
|
6786
|
+
else
|
|
6787
|
+
this.discard(request);
|
|
6788
|
+
}
|
|
6789
|
+
dispose() {
|
|
6790
|
+
for (const request of this.inFlight.values())
|
|
6791
|
+
this.discard(request);
|
|
6792
|
+
}
|
|
6793
|
+
detach(request) {
|
|
6794
|
+
const attempt = this.requests.get(request);
|
|
6795
|
+
if (!attempt)
|
|
6796
|
+
return;
|
|
6797
|
+
this.requests.delete(request);
|
|
6798
|
+
if (this.inFlight.get(attempt.sessionID) === request)
|
|
6799
|
+
this.inFlight.delete(attempt.sessionID);
|
|
6800
|
+
attempt.detachAbort?.();
|
|
6801
|
+
return attempt;
|
|
6802
|
+
}
|
|
6803
|
+
discard(request) {
|
|
6804
|
+
const attempt = this.detach(request);
|
|
6805
|
+
if (!attempt)
|
|
6806
|
+
return;
|
|
6807
|
+
cancelBody(attempt);
|
|
6808
|
+
}
|
|
6809
|
+
releaseNonSizeAttempt(request) {
|
|
6810
|
+
const attempt = this.detach(request);
|
|
6811
|
+
if (!attempt)
|
|
6812
|
+
return;
|
|
6813
|
+
this.counts.discardPreparation(attempt.sessionID, attempt.pass);
|
|
6814
|
+
cancelBody(attempt);
|
|
6815
|
+
}
|
|
6816
|
+
}
|
|
6817
|
+
function cancelBody(attempt) {
|
|
6818
|
+
const body = attempt?.body?.body;
|
|
6819
|
+
if (body && !body.locked)
|
|
6820
|
+
body.cancel().catch(() => {});
|
|
6821
|
+
}
|
|
6822
|
+
function readOpenCode2RefusalMessage(message, values) {
|
|
6823
|
+
values.push(message.role);
|
|
6824
|
+
for (const part of message.content) {
|
|
6825
|
+
switch (part.type) {
|
|
6826
|
+
case "text":
|
|
6827
|
+
case "reasoning":
|
|
6828
|
+
values.push(part.type, part.text);
|
|
6829
|
+
break;
|
|
6830
|
+
case "tool-call":
|
|
6831
|
+
values.push("tool-call", part.name, part.input);
|
|
6832
|
+
break;
|
|
6833
|
+
case "tool-result":
|
|
6834
|
+
values.push("tool-result", part.name, part.result);
|
|
6835
|
+
break;
|
|
6836
|
+
case "media": {
|
|
6837
|
+
const media = isRecord(part.media) ? part.media : {};
|
|
6838
|
+
const source = isRecord(media.source) ? media.source : {};
|
|
6839
|
+
values.push("media", source.type, source.mediaType, source.data, source.url);
|
|
6840
|
+
break;
|
|
6841
|
+
}
|
|
6842
|
+
default:
|
|
6843
|
+
pushRefusalFields(part, values);
|
|
6844
|
+
}
|
|
6845
|
+
}
|
|
6846
|
+
}
|
|
6847
|
+
function countFullRequest(body) {
|
|
6848
|
+
if (!body || typeof body !== "object")
|
|
6849
|
+
return;
|
|
6850
|
+
const request = body;
|
|
6851
|
+
if (request.previous_response_id || request.conversation || request.cachedContent)
|
|
6852
|
+
return;
|
|
6853
|
+
const transcript = request.messages ?? request.input ?? request.contents;
|
|
6854
|
+
if (!Array.isArray(transcript))
|
|
6855
|
+
return;
|
|
6856
|
+
if (request.tools !== undefined && !Array.isArray(request.tools))
|
|
6857
|
+
return;
|
|
6858
|
+
let images = 0;
|
|
6859
|
+
const text = JSON.stringify({
|
|
6860
|
+
transcript,
|
|
6861
|
+
system: request.system ?? request.instructions ?? request.systemInstruction,
|
|
6862
|
+
tools: request.tools
|
|
6863
|
+
}, (_key, value) => {
|
|
6864
|
+
if (!isRecord(value))
|
|
6865
|
+
return value;
|
|
6866
|
+
const tokens = httpImageTokens(value);
|
|
6867
|
+
if (tokens === undefined)
|
|
6868
|
+
return value;
|
|
6869
|
+
images += tokens;
|
|
6870
|
+
return null;
|
|
6871
|
+
});
|
|
6872
|
+
return estimateTokens(text) + images;
|
|
6873
|
+
}
|
|
6874
|
+
function httpImageTokens(part) {
|
|
6875
|
+
if (part.type === "image" && isRecord(part.source)) {
|
|
6876
|
+
const source = part.source;
|
|
6877
|
+
if (source.type === "base64" && typeof source.media_type === "string" && typeof source.data === "string")
|
|
6878
|
+
return estimateImageTokensFromBase64(source.media_type, source.data);
|
|
6879
|
+
if (source.type === "url" && typeof source.url === "string")
|
|
6880
|
+
return estimateImageTokensFromDataUrl(source.url);
|
|
6881
|
+
}
|
|
6882
|
+
if (part.type === "image_url" || part.type === "input_image") {
|
|
6883
|
+
const url = isRecord(part.image_url) ? part.image_url.url : part.image_url;
|
|
6884
|
+
if (typeof url === "string")
|
|
6885
|
+
return estimateImageTokensFromDataUrl(url);
|
|
6886
|
+
}
|
|
6887
|
+
const inline = part.inlineData ?? part.inline_data;
|
|
6888
|
+
if (isRecord(inline)) {
|
|
6889
|
+
const mime = inline.mimeType ?? inline.mime_type;
|
|
6890
|
+
if (typeof mime === "string" && mime.startsWith("image/") && typeof inline.data === "string")
|
|
6891
|
+
return estimateImageTokensFromBase64(mime, inline.data);
|
|
6892
|
+
}
|
|
6893
|
+
}
|
|
6894
|
+
|
|
6552
6895
|
// src/v2/hooks/lkg-system.ts
|
|
6553
6896
|
import { createHash as createHash3 } from "node:crypto";
|
|
6554
6897
|
function identity2(slot) {
|
|
@@ -6681,13 +7024,15 @@ class V2OverflowRecovery {
|
|
|
6681
7024
|
if (error === undefined)
|
|
6682
7025
|
return;
|
|
6683
7026
|
const prior = this.requests.get(sessionID);
|
|
6684
|
-
|
|
7027
|
+
const sizeRefusal = isProviderSizeRefusal(error);
|
|
7028
|
+
if (prior?.observed || isProviderRateLimit(error) || !sizeRefusal && !detectOverflow(error).isOverflow)
|
|
6685
7029
|
return;
|
|
6686
7030
|
const messageID = event.data?.assistantMessageID;
|
|
6687
7031
|
const step = readStep(sessionID, messageID);
|
|
6688
7032
|
if (!step)
|
|
6689
7033
|
return;
|
|
6690
|
-
|
|
7034
|
+
const durable = !!messageID || !!step.error && detectOverflow(step.error).isOverflow;
|
|
7035
|
+
if (!durable && !isProviderSizeRefusal(step.error))
|
|
6691
7036
|
return;
|
|
6692
7037
|
if (!prior && step.model)
|
|
6693
7038
|
this.begin({
|
|
@@ -6703,7 +7048,8 @@ class V2OverflowRecovery {
|
|
|
6703
7048
|
sessionID,
|
|
6704
7049
|
error,
|
|
6705
7050
|
model: step?.model ?? request.model,
|
|
6706
|
-
assistantMessageID: messageID ?? step?.id
|
|
7051
|
+
assistantMessageID: messageID ?? step?.id,
|
|
7052
|
+
durable
|
|
6707
7053
|
});
|
|
6708
7054
|
}
|
|
6709
7055
|
observe(input) {
|
|
@@ -6714,13 +7060,22 @@ class V2OverflowRecovery {
|
|
|
6714
7060
|
return;
|
|
6715
7061
|
if (input.status === 429 || isProviderRateLimit(input.error))
|
|
6716
7062
|
return;
|
|
6717
|
-
const
|
|
7063
|
+
const reportedError = typeof input.error === "string" && input.status !== undefined ? {
|
|
7064
|
+
status: input.status,
|
|
7065
|
+
responseBody: input.error,
|
|
7066
|
+
data: { responseBody: input.error }
|
|
7067
|
+
} : input.error;
|
|
7068
|
+
const modelKey = `${input.model.providerID}/${input.model.id}`;
|
|
7069
|
+
if (!this.deps.compactionOff && !input.skipMeasured && isProviderSizeRefusal(reportedError))
|
|
7070
|
+
this.deps.onProviderRefused?.(input.sessionID, modelKey, input.assistantMessageID);
|
|
7071
|
+
if (input.durable === false)
|
|
7072
|
+
return;
|
|
7073
|
+
const detection = detectOverflow(reportedError);
|
|
6718
7074
|
if (!detection.isOverflow)
|
|
6719
7075
|
return;
|
|
6720
7076
|
const db = this.deps.database();
|
|
6721
7077
|
if (!db)
|
|
6722
7078
|
return;
|
|
6723
|
-
const modelKey = `${input.model.providerID}/${input.model.id}`;
|
|
6724
7079
|
const reportedLimit = resolveOpenCodeOverflowLimit(detection, input.model.providerID, input.model.id, { db, sessionID: input.sessionID });
|
|
6725
7080
|
if (this.deps.compactionOff) {
|
|
6726
7081
|
if (reportedLimit)
|
|
@@ -6886,8 +7241,10 @@ class V2RevertMessageCleanup {
|
|
|
6886
7241
|
const reader = this.openStoreReader();
|
|
6887
7242
|
try {
|
|
6888
7243
|
const suffix = reader.revertSuffix(sessionID, cutoff, MAX_STAGED_SUFFIX_ROWS);
|
|
6889
|
-
|
|
7244
|
+
const before = suffix ? suffix.predecessor.seq : reader.sequenceBefore(sessionID, cutoff);
|
|
7245
|
+
this.staged.set(sessionID, suffix ? { cutoff, host: reader.hostIdentity(), suffix, before } : {
|
|
6890
7246
|
cutoff,
|
|
7247
|
+
before,
|
|
6891
7248
|
unavailable: "stage did not prove a bounded suffix and retained predecessor"
|
|
6892
7249
|
});
|
|
6893
7250
|
} finally {
|
|
@@ -6897,6 +7254,10 @@ class V2RevertMessageCleanup {
|
|
|
6897
7254
|
this.staged.set(sessionID, { cutoff, unavailable: "host store read failed at stage" });
|
|
6898
7255
|
}
|
|
6899
7256
|
}
|
|
7257
|
+
stagedPredecessor(sessionID, to) {
|
|
7258
|
+
const staged = this.staged.peek(sessionID);
|
|
7259
|
+
return staged && staged.cutoff === to ? staged.before : undefined;
|
|
7260
|
+
}
|
|
6900
7261
|
discardStageProof(sessionID) {
|
|
6901
7262
|
this.staged.delete(sessionID);
|
|
6902
7263
|
}
|
|
@@ -7200,7 +7561,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
|
|
|
7200
7561
|
...project,
|
|
7201
7562
|
...rustToolBackends ? { rustToolBackends } : {}
|
|
7202
7563
|
}),
|
|
7203
|
-
...
|
|
7564
|
+
...createDreamerMemoryTools({
|
|
7204
7565
|
...project,
|
|
7205
7566
|
...rustToolBackends ? { rustToolBackends } : {}
|
|
7206
7567
|
})
|
|
@@ -7218,7 +7579,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
|
|
|
7218
7579
|
const refusal = subagentToolRefusal(db, name, call.sessionID, isInternalChild);
|
|
7219
7580
|
if (refusal)
|
|
7220
7581
|
return { content: refusal };
|
|
7221
|
-
if (name === "ctx_memory" || name === "ctx_note" || name === "ctx_reduce")
|
|
7582
|
+
if (name === "ctx_memory" || name === "ctx_note" || name === "ctx_reduce" || name === CTX_MEMORY_CURATE_TOOL_NAME && call.agent === DREAMER_AGENT)
|
|
7222
7583
|
await withAsyncPrivilegedWriter2(db, () => {
|
|
7223
7584
|
return;
|
|
7224
7585
|
});
|
|
@@ -7593,7 +7954,14 @@ function restoreNativeCheckpointInput(messages, incoming, restored, reader, sess
|
|
|
7593
7954
|
const at = messages.indexOf(incoming);
|
|
7594
7955
|
return [...messages.slice(0, at), ...hidden, ...messages.slice(at + 1)];
|
|
7595
7956
|
}
|
|
7596
|
-
function
|
|
7957
|
+
function latestDraftAssistantID(messages) {
|
|
7958
|
+
for (let index = messages.length - 1;index >= 0; index--) {
|
|
7959
|
+
const message = messages[index];
|
|
7960
|
+
if (message?.role === "assistant" && message.id)
|
|
7961
|
+
return message.id;
|
|
7962
|
+
}
|
|
7963
|
+
}
|
|
7964
|
+
function checkpointRequestSizingInput(draft) {
|
|
7597
7965
|
let toolDefinitionTokens = 0;
|
|
7598
7966
|
for (const tool of Object.values(draft.tools)) {
|
|
7599
7967
|
const schema = JSON.stringify(tool.input);
|
|
@@ -7605,7 +7973,7 @@ function estimateCheckpointRequest(draft) {
|
|
|
7605
7973
|
...draft,
|
|
7606
7974
|
messages: draft.messages.map((message) => HEAD_IDS.some((id) => message.id === id) ? { ...message, id: undefined } : message)
|
|
7607
7975
|
};
|
|
7608
|
-
return
|
|
7976
|
+
return {
|
|
7609
7977
|
messages: adaptPayload(estimateDraft).messages,
|
|
7610
7978
|
toolDefinitionTokens,
|
|
7611
7979
|
systemPromptTokens: estimateTokens(JSON.stringify(draft.system)),
|
|
@@ -7613,7 +7981,10 @@ function estimateCheckpointRequest(draft) {
|
|
|
7613
7981
|
modelID: draft.model.id,
|
|
7614
7982
|
agentName: draft.agent,
|
|
7615
7983
|
sessionId: draft.sessionID
|
|
7616
|
-
}
|
|
7984
|
+
};
|
|
7985
|
+
}
|
|
7986
|
+
function estimateCheckpointRequest(draft) {
|
|
7987
|
+
return estimateFinalWireInputTokens(checkpointRequestSizingInput(draft));
|
|
7617
7988
|
}
|
|
7618
7989
|
function estimateCheckpointFraming(draft, checkpoint, submitted) {
|
|
7619
7990
|
const framing = structuredClone(checkpoint);
|
|
@@ -7802,9 +8173,11 @@ function catalogModels(listed, draftModel) {
|
|
|
7802
8173
|
}
|
|
7803
8174
|
return models;
|
|
7804
8175
|
}
|
|
7805
|
-
function removeDreamerOnlyTools(draft) {
|
|
7806
|
-
if (draft.tools)
|
|
7807
|
-
|
|
8176
|
+
function removeDreamerOnlyTools(draft, ids = DREAMER_ONLY_MEMORY_TOOL_NAMES) {
|
|
8177
|
+
if (!draft.tools)
|
|
8178
|
+
return;
|
|
8179
|
+
for (const id of ids)
|
|
8180
|
+
delete draft.tools[id];
|
|
7808
8181
|
}
|
|
7809
8182
|
function applyV2PromptSurfaceTools(draft, runtime, config, smartNotesEnabled = true) {
|
|
7810
8183
|
if (!draft.tools)
|
|
@@ -8073,11 +8446,18 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8073
8446
|
}) : undefined;
|
|
8074
8447
|
const hiddenChildHook = new HiddenChildHook;
|
|
8075
8448
|
const usage = new Map;
|
|
8449
|
+
const refusalCounts = new ProviderRefusalCounts;
|
|
8450
|
+
const httpRefusalCounts = new V2HttpRefusalCounts(refusalCounts);
|
|
8076
8451
|
const overflowRecovery = new V2OverflowRecovery({
|
|
8077
8452
|
database: () => db ?? null,
|
|
8078
8453
|
compactionOff,
|
|
8079
8454
|
isHidden: (sessionID) => hiddenChildHook.owns(sessionID),
|
|
8080
8455
|
onOverflow: (sessionID) => notifyV2ProviderOverflow(sessionID, openStoreReader),
|
|
8456
|
+
onProviderRefused: (sessionID, modelKey, assistantMessageID) => {
|
|
8457
|
+
const pass = refusalCounts.latestForTerminalFailure(sessionID, assistantMessageID);
|
|
8458
|
+
if (pass)
|
|
8459
|
+
refusalCounts.refusal(sessionID, modelKey, pass);
|
|
8460
|
+
},
|
|
8081
8461
|
onInputTokens: (sessionID, inputTokens, limit) => usage.set(sessionID, {
|
|
8082
8462
|
usage: { inputTokens, percentage: limit > 0 ? inputTokens / limit * 100 : 100 },
|
|
8083
8463
|
hasUsageTokens: true,
|
|
@@ -8088,6 +8468,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8088
8468
|
await hiddenChildHook.cacheRequest(draft);
|
|
8089
8469
|
if (draft.kind !== "primary" || hiddenChildHook.owns(draft.sessionID))
|
|
8090
8470
|
return;
|
|
8471
|
+
if (!compactionOff && draft.model)
|
|
8472
|
+
httpRefusalCounts.capture({ ...draft, model: draft.model });
|
|
8091
8473
|
const selectedModel = liveModels.get(draft.sessionID);
|
|
8092
8474
|
if (selectedModel)
|
|
8093
8475
|
overflowRecovery.begin({
|
|
@@ -8100,12 +8482,21 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8100
8482
|
cleanup.tools = () => tools.dispose();
|
|
8101
8483
|
const generateReplay = new V2GenerateReplay;
|
|
8102
8484
|
await context.session.hook("http.response", async (draft) => {
|
|
8103
|
-
if (!db || draft.kind !== "primary"
|
|
8485
|
+
if (!db || draft.kind !== "primary")
|
|
8104
8486
|
return;
|
|
8487
|
+
if (draft.response.ok) {
|
|
8488
|
+
httpRefusalCounts.accept(draft.sessionID);
|
|
8489
|
+
return;
|
|
8490
|
+
}
|
|
8491
|
+
if (draft.request && isMeasuredRefusalStatusVeto(draft.response.status))
|
|
8492
|
+
httpRefusalCounts.releaseNonSizeAttempt(draft.request);
|
|
8493
|
+
const error = await draft.response.clone().text();
|
|
8494
|
+
const associated = !compactionOff && draft.request !== undefined && await httpRefusalCounts.observe({ ...draft, request: draft.request }, error);
|
|
8105
8495
|
overflowRecovery.observe({
|
|
8106
8496
|
...draft,
|
|
8107
|
-
error
|
|
8108
|
-
status: draft.response.status
|
|
8497
|
+
error,
|
|
8498
|
+
status: draft.response.status,
|
|
8499
|
+
skipMeasured: associated
|
|
8109
8500
|
});
|
|
8110
8501
|
});
|
|
8111
8502
|
await registerHiddenChildAgents(context.agent);
|
|
@@ -8630,7 +9021,31 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8630
9021
|
}
|
|
8631
9022
|
};
|
|
8632
9023
|
const usageController = new AbortController;
|
|
8633
|
-
|
|
9024
|
+
const lowerRetiredInstructionsOnRevert = (database, sessionID, event) => {
|
|
9025
|
+
try {
|
|
9026
|
+
let before = revertMessageCleanup.stagedPredecessor(sessionID, event.data?.to);
|
|
9027
|
+
const commitSeq = event.durable?.seq;
|
|
9028
|
+
if (before === undefined && event.durable?.aggregateID === sessionID && typeof commitSeq === "number" && Number.isSafeInteger(commitSeq)) {
|
|
9029
|
+
const reader = openStoreReader();
|
|
9030
|
+
try {
|
|
9031
|
+
before = reader.highestSequenceBelow(sessionID, commitSeq);
|
|
9032
|
+
} finally {
|
|
9033
|
+
reader.close();
|
|
9034
|
+
}
|
|
9035
|
+
}
|
|
9036
|
+
if (before === undefined) {
|
|
9037
|
+
sessionLog2(sessionID, "committed revert: last kept row unknown; retired instruction rows left as they are");
|
|
9038
|
+
return;
|
|
9039
|
+
}
|
|
9040
|
+
lowerRetiredInstructionThrough(database, sessionID, before);
|
|
9041
|
+
} catch (error) {
|
|
9042
|
+
sessionLog2(sessionID, "committed revert: retired instruction rows not updated:", error);
|
|
9043
|
+
}
|
|
9044
|
+
};
|
|
9045
|
+
cleanup.abortUsage = () => {
|
|
9046
|
+
usageController.abort();
|
|
9047
|
+
httpRefusalCounts.dispose();
|
|
9048
|
+
};
|
|
8634
9049
|
const usageDone = (async () => {
|
|
8635
9050
|
let retry = 0;
|
|
8636
9051
|
while (!usageController.signal.aborted) {
|
|
@@ -8652,6 +9067,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8652
9067
|
continue;
|
|
8653
9068
|
const sessionID = event.data.sessionID;
|
|
8654
9069
|
observeSyntheticAdmissionEvent(context, event);
|
|
9070
|
+
if (event.type?.startsWith("session.revert.") || event.type === "session.message.removed" || event.type === "session.message.deleted" || event.type === "session.deleted")
|
|
9071
|
+
httpRefusalCounts.accept(sessionID);
|
|
9072
|
+
if ((event.type === "session.step.failed" || event.type === "session.error") && !isProviderSizeRefusal(event.data.error ?? hiddenTerminalError(event)))
|
|
9073
|
+
httpRefusalCounts.release(sessionID, true);
|
|
8655
9074
|
overflowRecovery.observeTerminal(event, (id, messageID) => {
|
|
8656
9075
|
const reader = openStoreReader();
|
|
8657
9076
|
try {
|
|
@@ -8664,6 +9083,13 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8664
9083
|
reader.close();
|
|
8665
9084
|
}
|
|
8666
9085
|
});
|
|
9086
|
+
if (event.type === "session.step.ended") {
|
|
9087
|
+
const pass = refusalCounts.latestForTerminalFailure(sessionID, event.data.assistantMessageID);
|
|
9088
|
+
if (pass)
|
|
9089
|
+
refusalCounts.discardPreparation(sessionID, pass);
|
|
9090
|
+
}
|
|
9091
|
+
if (event.type === "session.execution.succeeded" || event.type === "session.execution.failed" || event.type === "session.execution.interrupted")
|
|
9092
|
+
httpRefusalCounts.endRun(sessionID);
|
|
8667
9093
|
if (event.type === "session.revert.staged" && db) {
|
|
8668
9094
|
revertMessageCleanup.captureStageProof(sessionID, event.data.revert?.messageID);
|
|
8669
9095
|
}
|
|
@@ -8678,6 +9104,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8678
9104
|
const indexDb = db;
|
|
8679
9105
|
withoutSqliteTransformPass2(() => {
|
|
8680
9106
|
scheduleClearAndReindex(indexDb, sessionID, pagedRead);
|
|
9107
|
+
lowerRetiredInstructionsOnRevert(indexDb, sessionID, event);
|
|
8681
9108
|
try {
|
|
8682
9109
|
if (revertMessageCleanup.pruneOnCommit(indexDb, sessionID, event.data?.to, !compactionOff && !rustModeModuleClient)) {
|
|
8683
9110
|
tagger.cleanup(sessionID);
|
|
@@ -8853,8 +9280,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8853
9280
|
draft.result = { summary: hiddenSummary, metadata: { keepID: undefined } };
|
|
8854
9281
|
return;
|
|
8855
9282
|
}
|
|
8856
|
-
if (compactionOff)
|
|
9283
|
+
if (compactionOff) {
|
|
9284
|
+
removeDreamerOnlyTools(draft, [CTX_MEMORY_CURATE_TOOL_NAME]);
|
|
8857
9285
|
return;
|
|
9286
|
+
}
|
|
8858
9287
|
if (nativeFoldReplay)
|
|
8859
9288
|
rememberHostMedia(draft.messages);
|
|
8860
9289
|
const reader = openStoreReader();
|
|
@@ -8864,6 +9293,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8864
9293
|
const running = reader.latestRunningCompaction(draft.sessionID);
|
|
8865
9294
|
const attempt = running && nativeFoldMemory?.admission(draft.sessionID, running.id);
|
|
8866
9295
|
const manual = running?.data.reason === "manual" && !(attempt?.status === "pending" && attempt.owner_token);
|
|
9296
|
+
if (manual)
|
|
9297
|
+
httpRefusalCounts.accept(draft.sessionID);
|
|
8867
9298
|
const moduleBaseline = rustModeModuleClient ? servedModuleM0Text(draft.sessionID) : undefined;
|
|
8868
9299
|
const source = !rustModeModuleClient ? "typescript" : moduleBaseline === null ? "typescript_fallback" : "module";
|
|
8869
9300
|
if (nativeFoldReplay) {
|
|
@@ -8944,11 +9375,13 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
8944
9375
|
if (!recorded)
|
|
8945
9376
|
return messages;
|
|
8946
9377
|
if (db) {
|
|
8947
|
-
|
|
8948
|
-
|
|
8949
|
-
id
|
|
8950
|
-
|
|
8951
|
-
|
|
9378
|
+
const folded = new Map;
|
|
9379
|
+
for (const id of retiredLiveInstructionIDs(db, sessionID)) {
|
|
9380
|
+
const seq = reader.sequenceForId(sessionID, id) ?? Infinity;
|
|
9381
|
+
if (recorded({ type: "system", id, seq }))
|
|
9382
|
+
folded.set(id, seq);
|
|
9383
|
+
}
|
|
9384
|
+
foldedInstructionIDs.set(sessionID, folded);
|
|
8952
9385
|
}
|
|
8953
9386
|
const retired = (row) => recorded(row) || isLeftOutInstruction(leftOut, row);
|
|
8954
9387
|
return messages.filter((message) => {
|
|
@@ -9052,7 +9485,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9052
9485
|
const pass = contextPass.getStore();
|
|
9053
9486
|
if (pass)
|
|
9054
9487
|
pass.legacyCoveredReclaimPermitted = permitted;
|
|
9055
|
-
return reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered, pass?.checkpointSequence, pass?.checkpointCoveredThrough);
|
|
9488
|
+
return reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered, pass?.checkpointSequence, pass?.checkpointCoveredThrough, pass?.localCheckpointSequence);
|
|
9056
9489
|
},
|
|
9057
9490
|
compactionOff,
|
|
9058
9491
|
storeGeneration: "v2",
|
|
@@ -9129,7 +9562,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9129
9562
|
onRustEngineReconnectRefusal: (refusal) => rustRefusalRecovery?.arm(refusal),
|
|
9130
9563
|
...createHostSeams(context, readAllForConversion, pagedRead, liveModels)
|
|
9131
9564
|
});
|
|
9132
|
-
const runManagedContext = async (draft, pass, previousRecovery) => {
|
|
9565
|
+
const runManagedContext = async (draft, pass, previousRecovery, refusalPass) => {
|
|
9133
9566
|
rememberHostMedia(draft.messages);
|
|
9134
9567
|
if (hiddenChildHook.apply(draft))
|
|
9135
9568
|
return "skipped";
|
|
@@ -9444,6 +9877,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9444
9877
|
let messageTimes;
|
|
9445
9878
|
let instructionRows = new Map;
|
|
9446
9879
|
let legacyInstructions;
|
|
9880
|
+
retryRetiredInstructionLowering(db, draft.sessionID);
|
|
9447
9881
|
const reader = openStoreReader();
|
|
9448
9882
|
let checkpoint;
|
|
9449
9883
|
let submitted;
|
|
@@ -9454,8 +9888,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9454
9888
|
try {
|
|
9455
9889
|
syntheticIDs = await readSyntheticProvenance(reader, draft.messages);
|
|
9456
9890
|
const cut = reader.latestCompaction(draft.sessionID);
|
|
9457
|
-
if (!rustModeModuleClient)
|
|
9891
|
+
if (!rustModeModuleClient) {
|
|
9458
9892
|
pass.checkpointSequence = cut?.seq;
|
|
9893
|
+
pass.localCheckpointSequence = cut && isLocalCheckpoint(cut) ? cut.seq : undefined;
|
|
9894
|
+
}
|
|
9459
9895
|
if (nativeFoldReplay)
|
|
9460
9896
|
draftSourceIdentity = await nativeFoldReplay.observeSource(draft.sessionID, reader);
|
|
9461
9897
|
const boundaryRepair = !rustModeModuleClient && db && !compactionOff ? revertMessageCleanup.retireProvenHistory(db, draft.sessionID, reader) ?? checkHistoryBoundary(db, reader, draft.sessionID) : undefined;
|
|
@@ -9586,6 +10022,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9586
10022
|
nativeFoldReplay.invalidate(draft.sessionID, true);
|
|
9587
10023
|
}
|
|
9588
10024
|
}
|
|
10025
|
+
if (refusalPass)
|
|
10026
|
+
refusalPass.observeHistory(snapshotRefusalHistory(draft.messages, readOpenCode2RefusalMessage));
|
|
9589
10027
|
const mapped = adaptPayload(draft, syntheticIDs, messageTimes, anchorTimesOnly, instructionRows);
|
|
9590
10028
|
bindSystemDateRequestIdentity(mapped, draft);
|
|
9591
10029
|
checkpointPassPermissions.delete(draft.sessionID);
|
|
@@ -9814,12 +10252,15 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9814
10252
|
const previousRecovery = recoveredInstructions.peek(draft.sessionID);
|
|
9815
10253
|
recoveredInstructions.delete(draft.sessionID);
|
|
9816
10254
|
const hiddenChild = hiddenChildHook.owns(draft.sessionID);
|
|
10255
|
+
if (!compactionOff && !hiddenChild && !rustModeModuleClient)
|
|
10256
|
+
httpRefusalCounts.release(draft.sessionID);
|
|
10257
|
+
const refusalPass = compactionOff || hiddenChild || rustModeModuleClient ? undefined : refusalCounts.begin(draft.sessionID, undefined, latestDraftAssistantID(draft.messages));
|
|
9817
10258
|
const anchor = compactionOff || hiddenChild ? undefined : generateReplayAnchor(draft.messages);
|
|
9818
10259
|
beginServedRequest(draft.sessionID);
|
|
9819
10260
|
let returned = false;
|
|
9820
10261
|
let outcome;
|
|
9821
10262
|
try {
|
|
9822
|
-
outcome = await runManagedContext(draft, pass, previousRecovery);
|
|
10263
|
+
outcome = refusalPass ? await withProviderRefusalPass(draft.sessionID, refusalPass, () => runManagedContext(draft, pass, previousRecovery, refusalPass)) : await runManagedContext(draft, pass, previousRecovery);
|
|
9823
10264
|
if (!pass.refused && pass.storageNoticeWake && draft.messages.at(-1)?.role === "assistant") {
|
|
9824
10265
|
await refuseBeforeProvider(context.session, draft.sessionID, "storage-notice-turn", "request ends with the previous reply");
|
|
9825
10266
|
}
|
|
@@ -9880,6 +10321,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
9880
10321
|
sessionLog2(draft.sessionID, "generate replay capture skipped: compaction-disabled");
|
|
9881
10322
|
else if (!pass.refused && outcome === "managed" && !hiddenChild && !deletedSessions.has(draft.sessionID))
|
|
9882
10323
|
generateReplay.capture(draft, anchor);
|
|
10324
|
+
if (refusalPass && !pass.refused && outcome === "managed" && draft.system.some((part) => part.text)) {
|
|
10325
|
+
const saved = { ...draft };
|
|
10326
|
+
refusalPass.freeze(`${saved.model.providerID}/${saved.model.id}`, () => estimateFrozenRequestInputTokens(checkpointRequestSizingInput(saved)));
|
|
10327
|
+
}
|
|
9883
10328
|
}));
|
|
9884
10329
|
await context.session.hook("generate", async (draft) => {
|
|
9885
10330
|
const managed = !compactionOff && !deletedSessions.has(draft.sessionID);
|