@cortexkit/opencode-magic-context 0.49.99 → 0.49.100
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 +1 -1
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-z77a2jpx.js → context-k2tdh146.js} +290 -29
- 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/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-0eyxarpb.js} +5 -5
- package/dist/{index-507a56zb.js → index-0tqhr9zs.js} +5 -5
- package/dist/{index-xw608ytx.js → index-3cgh0ght.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-6hjbeeth.js} +3 -3
- package/dist/{index-tyjx0dwz.js → index-jjy4shhy.js} +1 -1
- package/dist/{index-8hhmv0ff.js → index-kjhgxkdx.js} +1 -1
- package/dist/{index-4qc8d9by.js → index-n3tebmah.js} +21 -14
- package/dist/{index-0wj3jr8n.js → index-qjcye18f.js} +3 -3
- package/dist/{index-9eqt7755.js → index-rakm1eay.js} +2 -2
- package/dist/{index-w6kcwhhj.js → index-rjxg7a7m.js} +212 -4
- package/dist/{index-5nf2a14a.js → index-txthzqrm.js} +278 -32
- package/dist/{index-em72jhc0.js → index-z1hc2g06.js} +1 -1
- package/dist/{index-kjdys7e2.js → index-zg5r2syy.js} +1 -1
- package/dist/{index-xbna9akt.js → index-zyb7tndy.js} +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +135 -23
- 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/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-e7n124g0.js} +7 -7
- package/dist/{render-9712q3gp.js → render-argap54x.js} +6 -6
- package/dist/{search-archive-5jr011gc.js → search-archive-ads5mh9s.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/{transform-postprocess-phase-mf5js6cs.js → transform-postprocess-phase-2y0st4gk.js} +8 -8
- 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-v56v40cx.js} +589 -80
- package/dist/v2/hooks/context.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/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-5gkzamy2.js} +6 -6
- package/dist/v2/{render-bzzypsgy.js → render-atxj9eaf.js} +6 -6
- package/dist/v2/{search-ymm2crs3.js → search-51qr14ed.js} +5 -5
- package/dist/v2/{search-archive-4yr4hw2m.js → search-archive-vgwnvdx2.js} +5 -5
- package/dist/v2/{server-1bks09js.js → server-08jh9wew.js} +3 -3
- package/dist/v2/{server-8xgs110k.js → server-606mnrv4.js} +212 -4
- package/dist/v2/{server-zedjjdc5.js → server-8vby30m5.js} +1 -1
- package/dist/v2/{server-7861dnm3.js → server-awth2wsg.js} +1 -1
- 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-e8ybwfv8.js → server-p2wxmjc3.js} +2 -2
- package/dist/v2/{server-6r3b0re0.js → server-rwdp3hw6.js} +5 -5
- package/dist/v2/{server-h95cdc30.js → server-s3m2y97h.js} +1 -1
- package/dist/v2/{server-d0h1gjz2.js → server-wdmcqhv6.js} +3 -3
- package/dist/v2/server.js +2 -2
- package/dist/v2/{storage-tags-8kktww54.js → storage-tags-4t9fb4ch.js} +1 -1
- package/dist/v2/{v2-archive-reader-veyqp15a.js → v2-archive-reader-1wc5wb1a.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-89cg7p41.js → wrapup-orchestrator-ksdn2emb.js} +6 -6
- package/dist/{v2-archive-reader-3s332fn7.js → v2-archive-reader-4pk46nc1.js} +1 -1
- package/dist/{wrapup-orchestrator-41rt7etq.js → wrapup-orchestrator-sc2fsfct.js} +8 -8
- package/package.json +1 -1
|
@@ -247,7 +247,7 @@ import {
|
|
|
247
247
|
startCompartmentAgent,
|
|
248
248
|
setRecompStarting2,
|
|
249
249
|
setRecompTerminal2
|
|
250
|
-
} from "./server-
|
|
250
|
+
} from "./server-rwdp3hw6.js";
|
|
251
251
|
import {
|
|
252
252
|
embedPauseBySession,
|
|
253
253
|
embedRunStateBySession,
|
|
@@ -438,12 +438,12 @@ import {
|
|
|
438
438
|
saveSourceContent,
|
|
439
439
|
replaceSourceContent,
|
|
440
440
|
getSourceContents
|
|
441
|
-
} from "./server-
|
|
441
|
+
} from "./server-8vby30m5.js";
|
|
442
442
|
import {
|
|
443
443
|
cleanSearchText,
|
|
444
444
|
matchedSearchSnippet,
|
|
445
445
|
getLastIndexedOrdinal
|
|
446
|
-
} from "./server-
|
|
446
|
+
} from "./server-c1vcbszm.js";
|
|
447
447
|
import {
|
|
448
448
|
ensureSessionMetaRow,
|
|
449
449
|
clearCachedM0M1,
|
|
@@ -460,6 +460,7 @@ import {
|
|
|
460
460
|
isRecord,
|
|
461
461
|
contentTagOwnerMessageId,
|
|
462
462
|
estimateImageTokensFromDataUrl,
|
|
463
|
+
estimateImageTokensFromBase64,
|
|
463
464
|
estimateToolAttachmentImageTokens,
|
|
464
465
|
providerVisiblePart,
|
|
465
466
|
CLEARED_TODO_STATE_JSON,
|
|
@@ -595,6 +596,8 @@ import {
|
|
|
595
596
|
detectLatestTurnThinkingMismatch,
|
|
596
597
|
isPrefixBoundThinkingModel,
|
|
597
598
|
detectOverflow,
|
|
599
|
+
isMeasuredRefusalStatusVeto,
|
|
600
|
+
isProviderSizeRefusal,
|
|
598
601
|
overflowLimitToStore,
|
|
599
602
|
isProviderRateLimit,
|
|
600
603
|
modelAcceptsEmptyContent,
|
|
@@ -643,10 +646,12 @@ import {
|
|
|
643
646
|
estimateMessageTokens,
|
|
644
647
|
wireContentBytes,
|
|
645
648
|
createFinalWireUsageTracker,
|
|
649
|
+
estimateFrozenRequestInputTokens,
|
|
646
650
|
estimateFinalWireInputTokens,
|
|
647
651
|
estimateAppendedWireTokens,
|
|
648
652
|
estimateEmergencyDropReclaimTokens,
|
|
649
653
|
planEmergencyDrop,
|
|
654
|
+
tagsInEmergencyDropOrder,
|
|
650
655
|
measureEmergencyTag,
|
|
651
656
|
snapshotEmergencyServedMass,
|
|
652
657
|
tagsSinceReading,
|
|
@@ -702,7 +707,7 @@ import {
|
|
|
702
707
|
adoptNullOwnerToolTag2,
|
|
703
708
|
getCandidateToolOwners2,
|
|
704
709
|
pickNearestPriorOwner2
|
|
705
|
-
} from "./server-
|
|
710
|
+
} from "./server-606mnrv4.js";
|
|
706
711
|
import {
|
|
707
712
|
BoundedSessionMap,
|
|
708
713
|
getTableColumnNames,
|
|
@@ -816,7 +821,7 @@ import {
|
|
|
816
821
|
readRawSessionMessageOrdinalById2,
|
|
817
822
|
readSessionChunk2,
|
|
818
823
|
readRawSessionSeedTail2
|
|
819
|
-
} from "./server-
|
|
824
|
+
} from "./server-awth2wsg.js";
|
|
820
825
|
import {
|
|
821
826
|
getMessageIndexEpoch,
|
|
822
827
|
isMessageIndexSearchable,
|
|
@@ -842,7 +847,7 @@ import {
|
|
|
842
847
|
resolveMemoriesByIdsForSearch2,
|
|
843
848
|
unifiedSearch2,
|
|
844
849
|
formatSearchResults2
|
|
845
|
-
} from "./server-
|
|
850
|
+
} from "./server-d2a639dg.js";
|
|
846
851
|
import {
|
|
847
852
|
startBootDeadline,
|
|
848
853
|
getUnconfirmedMigrationHolders,
|
|
@@ -858,7 +863,7 @@ import {
|
|
|
858
863
|
openDatabaseAsync,
|
|
859
864
|
isDatabasePersisted,
|
|
860
865
|
getDatabasePersistenceError
|
|
861
|
-
} from "./server-
|
|
866
|
+
} from "./server-b25nvm9c.js";
|
|
862
867
|
import {
|
|
863
868
|
V2_MEMORY_CATEGORIES,
|
|
864
869
|
CATEGORY_PRIORITY
|
|
@@ -1055,15 +1060,15 @@ import {
|
|
|
1055
1060
|
renderMessageByOrdinal2,
|
|
1056
1061
|
renderVerboseRangeForTool2,
|
|
1057
1062
|
renderItemByTag2
|
|
1058
|
-
} from "./server-
|
|
1059
|
-
import"./server-
|
|
1063
|
+
} from "./server-p2wxmjc3.js";
|
|
1064
|
+
import"./server-s3m2y97h.js";
|
|
1060
1065
|
import {
|
|
1061
1066
|
readV2ArchiveOffThread2
|
|
1062
|
-
} from "./server-
|
|
1067
|
+
} from "./server-08jh9wew.js";
|
|
1063
1068
|
import {
|
|
1064
1069
|
unresolvedLiveTailRefusal2,
|
|
1065
1070
|
renderSearchArchiveOffThread2
|
|
1066
|
-
} from "./server-
|
|
1071
|
+
} from "./server-wdmcqhv6.js";
|
|
1067
1072
|
import {
|
|
1068
1073
|
markHostInstructionRow,
|
|
1069
1074
|
hostInstructionRow,
|
|
@@ -1804,7 +1809,7 @@ __export(exports_coerce, {
|
|
|
1804
1809
|
});
|
|
1805
1810
|
|
|
1806
1811
|
// src/v2/hooks/context.ts
|
|
1807
|
-
import { AsyncLocalStorage as
|
|
1812
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
1808
1813
|
import { setTimeout as delay } from "node:timers/promises";
|
|
1809
1814
|
|
|
1810
1815
|
// src/config/dependency-notes.ts
|
|
@@ -8222,6 +8227,235 @@ function createModuleToolBackends(options) {
|
|
|
8222
8227
|
};
|
|
8223
8228
|
}
|
|
8224
8229
|
|
|
8230
|
+
// src/hooks/magic-context/provider-refusal-count.ts
|
|
8231
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8232
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
8233
|
+
var RUN_END_GRACE_MS = 5000;
|
|
8234
|
+
|
|
8235
|
+
class ProviderRefusalCounts {
|
|
8236
|
+
requests = new BoundedSessionMap(1000);
|
|
8237
|
+
begin(session, startedAt, priorAssistantMessageID) {
|
|
8238
|
+
const previous = this.requests.get(session);
|
|
8239
|
+
let pending = previous?.refused;
|
|
8240
|
+
let refusedDigests = pending === undefined ? undefined : previous?.digests;
|
|
8241
|
+
if (previous)
|
|
8242
|
+
this.settle(session);
|
|
8243
|
+
let historyMatches = false;
|
|
8244
|
+
const request = {
|
|
8245
|
+
startedAt,
|
|
8246
|
+
priorAssistantMessageID,
|
|
8247
|
+
pass: {
|
|
8248
|
+
take: (model) => {
|
|
8249
|
+
const count = pending;
|
|
8250
|
+
pending = undefined;
|
|
8251
|
+
return this.requests.get(session) === request && historyMatches && count?.model === model ? count?.tokens : undefined;
|
|
8252
|
+
},
|
|
8253
|
+
save: (model, tokens) => {
|
|
8254
|
+
if (this.requests.get(session) !== request || request.ambiguousOutcome)
|
|
8255
|
+
return;
|
|
8256
|
+
request.prepared = makeCount(model, tokens);
|
|
8257
|
+
},
|
|
8258
|
+
freeze: (model, measure) => {
|
|
8259
|
+
if (this.requests.get(session) === request && !request.ambiguousOutcome && !request.settled)
|
|
8260
|
+
request.prepared = { model, measure };
|
|
8261
|
+
},
|
|
8262
|
+
observeHistory: (history) => {
|
|
8263
|
+
if (request.settled)
|
|
8264
|
+
return;
|
|
8265
|
+
request.snapshot = history;
|
|
8266
|
+
if (pending !== undefined) {
|
|
8267
|
+
historyMatches = refusedDigests !== undefined && startsWithDigests(history, refusedDigests);
|
|
8268
|
+
if (!historyMatches)
|
|
8269
|
+
pending = undefined;
|
|
8270
|
+
}
|
|
8271
|
+
refusedDigests = undefined;
|
|
8272
|
+
}
|
|
8273
|
+
}
|
|
8274
|
+
};
|
|
8275
|
+
this.requests.set(session, request);
|
|
8276
|
+
return request.pass;
|
|
8277
|
+
}
|
|
8278
|
+
latest(session, replyStartedAt) {
|
|
8279
|
+
const request = this.requests.get(session);
|
|
8280
|
+
if (request?.ambiguousOutcome)
|
|
8281
|
+
return;
|
|
8282
|
+
if (replyStartedAt !== undefined && (!Number.isFinite(replyStartedAt) || request?.startedAt !== undefined && replyStartedAt < request.startedAt))
|
|
8283
|
+
return;
|
|
8284
|
+
return request?.pass;
|
|
8285
|
+
}
|
|
8286
|
+
latestForTerminalFailure(session, assistantMessageID) {
|
|
8287
|
+
const request = this.requests.get(session);
|
|
8288
|
+
if (assistantMessageID !== undefined && assistantMessageID === request?.priorAssistantMessageID)
|
|
8289
|
+
return;
|
|
8290
|
+
return this.latest(session);
|
|
8291
|
+
}
|
|
8292
|
+
forget(session) {
|
|
8293
|
+
this.settle(session);
|
|
8294
|
+
this.requests.delete(session);
|
|
8295
|
+
}
|
|
8296
|
+
retainsHistorySnapshot(session) {
|
|
8297
|
+
return this.requests.get(session)?.snapshot !== undefined;
|
|
8298
|
+
}
|
|
8299
|
+
retainsFrozenDraft(session) {
|
|
8300
|
+
const prepared = this.requests.get(session)?.prepared;
|
|
8301
|
+
return prepared !== undefined && "measure" in prepared;
|
|
8302
|
+
}
|
|
8303
|
+
endRun(session, releaseTransport) {
|
|
8304
|
+
const request = this.requests.get(session);
|
|
8305
|
+
if (!request || request.settled || request.runEndTimer)
|
|
8306
|
+
return;
|
|
8307
|
+
const timer = setTimeout(() => {
|
|
8308
|
+
if (this.requests.peek(session)?.runEndTimer === timer)
|
|
8309
|
+
this.settle(session);
|
|
8310
|
+
releaseTransport?.();
|
|
8311
|
+
}, RUN_END_GRACE_MS);
|
|
8312
|
+
timer.unref();
|
|
8313
|
+
request.runEndTimer = timer;
|
|
8314
|
+
}
|
|
8315
|
+
settle(session) {
|
|
8316
|
+
const request = this.requests.get(session);
|
|
8317
|
+
if (!request)
|
|
8318
|
+
return;
|
|
8319
|
+
clearTimeout(request.runEndTimer);
|
|
8320
|
+
request.runEndTimer = undefined;
|
|
8321
|
+
request.settled = true;
|
|
8322
|
+
request.prepared = undefined;
|
|
8323
|
+
request.snapshot = undefined;
|
|
8324
|
+
}
|
|
8325
|
+
markOutcomeAmbiguous(session) {
|
|
8326
|
+
const request = this.requests.get(session);
|
|
8327
|
+
if (!request)
|
|
8328
|
+
return;
|
|
8329
|
+
request.ambiguousOutcome = true;
|
|
8330
|
+
request.prepared = undefined;
|
|
8331
|
+
request.snapshot = undefined;
|
|
8332
|
+
}
|
|
8333
|
+
discardDraft(session, pass) {
|
|
8334
|
+
const request = this.requests.get(session);
|
|
8335
|
+
if (request?.pass !== pass)
|
|
8336
|
+
return;
|
|
8337
|
+
request.prepared = undefined;
|
|
8338
|
+
request.refused = undefined;
|
|
8339
|
+
}
|
|
8340
|
+
discardPreparation(session, pass) {
|
|
8341
|
+
const request = this.requests.get(session);
|
|
8342
|
+
if (request?.pass !== pass)
|
|
8343
|
+
return;
|
|
8344
|
+
request.prepared = undefined;
|
|
8345
|
+
request.snapshot = undefined;
|
|
8346
|
+
}
|
|
8347
|
+
refusal(session, model, pass, tokens) {
|
|
8348
|
+
const request = this.requests.get(session);
|
|
8349
|
+
if (!request || request.settled || request.ambiguousOutcome || pass !== undefined && request.pass !== pass)
|
|
8350
|
+
return;
|
|
8351
|
+
const exact = pass && makeCount(model, tokens);
|
|
8352
|
+
if (exact) {
|
|
8353
|
+
request.refused = exact;
|
|
8354
|
+
armHistory(request);
|
|
8355
|
+
return;
|
|
8356
|
+
}
|
|
8357
|
+
if (request.refused || model !== undefined && request.prepared?.model !== model)
|
|
8358
|
+
return;
|
|
8359
|
+
const prepared = request.prepared;
|
|
8360
|
+
if (prepared && "measure" in prepared) {
|
|
8361
|
+
request.prepared = undefined;
|
|
8362
|
+
try {
|
|
8363
|
+
request.refused = makeCount(prepared.model, prepared.measure());
|
|
8364
|
+
} catch {}
|
|
8365
|
+
} else
|
|
8366
|
+
request.refused = prepared;
|
|
8367
|
+
armHistory(request);
|
|
8368
|
+
}
|
|
8369
|
+
}
|
|
8370
|
+
function makeCount(model, tokens) {
|
|
8371
|
+
return model && tokens !== undefined && Number.isFinite(tokens) && tokens > 0 ? { model, tokens } : undefined;
|
|
8372
|
+
}
|
|
8373
|
+
function armHistory(request) {
|
|
8374
|
+
if (!request.refused)
|
|
8375
|
+
return;
|
|
8376
|
+
const snapshot = request.snapshot;
|
|
8377
|
+
request.snapshot = undefined;
|
|
8378
|
+
if (request.digests || !snapshot)
|
|
8379
|
+
return;
|
|
8380
|
+
try {
|
|
8381
|
+
const digests = [];
|
|
8382
|
+
for (let index = 0;index < snapshot.ends.length; index++)
|
|
8383
|
+
digests.push(digestMessage(snapshot, index));
|
|
8384
|
+
request.digests = digests;
|
|
8385
|
+
} catch {}
|
|
8386
|
+
}
|
|
8387
|
+
var refusalHistoryDigest = {
|
|
8388
|
+
serialize: (values) => JSON.stringify(values),
|
|
8389
|
+
hash: (text) => createHash3("sha256").update(text).digest("base64")
|
|
8390
|
+
};
|
|
8391
|
+
function digestMessage(history, index) {
|
|
8392
|
+
const start = index === 0 ? 0 : history.ends[index - 1];
|
|
8393
|
+
return refusalHistoryDigest.hash(refusalHistoryDigest.serialize(history.values.slice(start, history.ends[index])));
|
|
8394
|
+
}
|
|
8395
|
+
function startsWithDigests(history, digests) {
|
|
8396
|
+
if (history.ends.length < digests.length)
|
|
8397
|
+
return false;
|
|
8398
|
+
try {
|
|
8399
|
+
for (let index = 0;index < digests.length; index++)
|
|
8400
|
+
if (digestMessage(history, index) !== digests[index])
|
|
8401
|
+
return false;
|
|
8402
|
+
} catch {
|
|
8403
|
+
return false;
|
|
8404
|
+
}
|
|
8405
|
+
return true;
|
|
8406
|
+
}
|
|
8407
|
+
function snapshotRefusalHistory(rows, read) {
|
|
8408
|
+
const values = [];
|
|
8409
|
+
const ends = new Array(rows.length);
|
|
8410
|
+
for (let index = 0;index < rows.length; index++) {
|
|
8411
|
+
read(rows[index], values);
|
|
8412
|
+
ends[index] = values.length;
|
|
8413
|
+
}
|
|
8414
|
+
return { values, ends };
|
|
8415
|
+
}
|
|
8416
|
+
function pushRefusalFields(record, values, skip) {
|
|
8417
|
+
for (const key in record) {
|
|
8418
|
+
if (key !== skip)
|
|
8419
|
+
values.push(key, record[key]);
|
|
8420
|
+
}
|
|
8421
|
+
}
|
|
8422
|
+
function readOpenCodeRefusalMessage(message, values) {
|
|
8423
|
+
values.push(message.info.role);
|
|
8424
|
+
for (const part of message.parts) {
|
|
8425
|
+
if (part === null || typeof part !== "object") {
|
|
8426
|
+
values.push(part);
|
|
8427
|
+
continue;
|
|
8428
|
+
}
|
|
8429
|
+
const record = part;
|
|
8430
|
+
switch (record.type) {
|
|
8431
|
+
case "text":
|
|
8432
|
+
case "reasoning":
|
|
8433
|
+
values.push(record.type, record.text);
|
|
8434
|
+
break;
|
|
8435
|
+
case "tool": {
|
|
8436
|
+
const state = record.state ?? {};
|
|
8437
|
+
values.push("tool", record.tool, state.status, state.input, state.output, state.error, state.attachments);
|
|
8438
|
+
break;
|
|
8439
|
+
}
|
|
8440
|
+
case "file":
|
|
8441
|
+
values.push("file", record.mime, record.url, record.filename);
|
|
8442
|
+
break;
|
|
8443
|
+
default:
|
|
8444
|
+
pushRefusalFields(record, values);
|
|
8445
|
+
}
|
|
8446
|
+
}
|
|
8447
|
+
}
|
|
8448
|
+
var activePass = new AsyncLocalStorage;
|
|
8449
|
+
function withProviderRefusalPass(session, pass, run) {
|
|
8450
|
+
return activePass.run({ session, pass }, run);
|
|
8451
|
+
}
|
|
8452
|
+
function takeProviderRefusedInputTokens(session, model) {
|
|
8453
|
+
const active = activePass.getStore();
|
|
8454
|
+
if (active?.session !== session)
|
|
8455
|
+
return;
|
|
8456
|
+
return active.pass.take(model);
|
|
8457
|
+
}
|
|
8458
|
+
|
|
8225
8459
|
// src/hooks/magic-context/render-options.ts
|
|
8226
8460
|
function createM0RenderOptions(controls, contextUsage, modelKey, resolvedContextLimit, projectPath) {
|
|
8227
8461
|
return {
|
|
@@ -9177,14 +9411,12 @@ function applyHeuristicCleanup(sessionId, db, targets, messageTagNumbers, config
|
|
|
9177
9411
|
priorInputSample,
|
|
9178
9412
|
hasPriorDrop: priorInputSample > 0,
|
|
9179
9413
|
passAlreadyPriced: emergency.passAlreadyPriced === true,
|
|
9180
|
-
protectedToolTags: protectedTools
|
|
9414
|
+
protectedToolTags: protectedTools,
|
|
9415
|
+
...emergency.refusedInputTokens === undefined ? {} : { refusedInputTokens: emergency.refusedInputTokens }
|
|
9181
9416
|
});
|
|
9182
9417
|
if (plan.shouldDrop) {
|
|
9183
|
-
const toDrop = new Set(plan.tagNumbers);
|
|
9184
9418
|
const newestEmergencyTags = recentTags;
|
|
9185
|
-
for (const tag of tags) {
|
|
9186
|
-
if (!toDrop.has(tag.tagNumber))
|
|
9187
|
-
continue;
|
|
9419
|
+
for (const tag of tagsInEmergencyDropOrder(tags, plan)) {
|
|
9188
9420
|
if (tag.status !== "active" || tag.type !== "tool")
|
|
9189
9421
|
continue;
|
|
9190
9422
|
const target = targets.get(tag.tagNumber);
|
|
@@ -10061,9 +10293,9 @@ function createExistingTagResolver(sessionId, tagger, db) {
|
|
|
10061
10293
|
}
|
|
10062
10294
|
|
|
10063
10295
|
// src/hooks/magic-context/transform-stage-logger.ts
|
|
10064
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10296
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
10065
10297
|
var SLOW_STAGE_MS = 100;
|
|
10066
|
-
var passes2 = new
|
|
10298
|
+
var passes2 = new AsyncLocalStorage2;
|
|
10067
10299
|
async function withTransformTimingSummary(run) {
|
|
10068
10300
|
const pass = {
|
|
10069
10301
|
stages: [],
|
|
@@ -11516,7 +11748,7 @@ async function runPostTransformPhase(args) {
|
|
|
11516
11748
|
let isExplicitFlush = pendingMaterializationAtPassStart;
|
|
11517
11749
|
const deferredMaterializationWasPending = deferredMaterializationAtPassStart;
|
|
11518
11750
|
const alreadyRanThisTurn = heuristicsAlreadyRanThisTurn(args.lastHeuristicsTurnId, args.sessionId, args.currentTurnId);
|
|
11519
|
-
const
|
|
11751
|
+
const readingBands = pressureBands({
|
|
11520
11752
|
percentage: args.contextUsage.percentage,
|
|
11521
11753
|
fromEstimate: args.contextUsageFromEstimate === true,
|
|
11522
11754
|
forceMaterializationPercentage: args.forceMaterializationPercentage,
|
|
@@ -11524,6 +11756,13 @@ async function runPostTransformPhase(args) {
|
|
|
11524
11756
|
fullFeatureMode: args.fullFeatureMode,
|
|
11525
11757
|
schedulerDecision: args.schedulerDecision
|
|
11526
11758
|
});
|
|
11759
|
+
const measuredSizeRefusal = !compactionOff && args.refusedInputTokens !== undefined;
|
|
11760
|
+
const bands = measuredSizeRefusal && !readingBands.forceBandConfirmed ? {
|
|
11761
|
+
...readingBands,
|
|
11762
|
+
emergencyDropEligible: true,
|
|
11763
|
+
forceBandConfirmed: true,
|
|
11764
|
+
executePressureEligible: true
|
|
11765
|
+
} : readingBands;
|
|
11527
11766
|
const {
|
|
11528
11767
|
forceMaterialization,
|
|
11529
11768
|
emergencyDropEligible,
|
|
@@ -11807,7 +12046,7 @@ async function runPostTransformPhase(args) {
|
|
|
11807
12046
|
executeReclaim: false,
|
|
11808
12047
|
subagentExecute: !args.fullFeatureMode && args.schedulerDecision === "execute",
|
|
11809
12048
|
hardFold: rewritingSignedPrefix || foldBustsServedPrefixThisPass || firstRenderBust || hostCheckpointRide,
|
|
11810
|
-
force: forceRide({
|
|
12049
|
+
force: measuredSizeRefusal || forceRide({
|
|
11811
12050
|
bands,
|
|
11812
12051
|
percentage: args.contextUsage.percentage,
|
|
11813
12052
|
fromEstimate: args.contextUsageFromEstimate === true,
|
|
@@ -12129,7 +12368,8 @@ async function runPostTransformPhase(args) {
|
|
|
12129
12368
|
usagePercentage: args.contextUsage.percentage,
|
|
12130
12369
|
passAlreadyPriced: emergencyRewriteAlreadyPriced,
|
|
12131
12370
|
servedBeforePass: servedBeforeRemovals,
|
|
12132
|
-
sinceReading: tagsNewerThanReading
|
|
12371
|
+
sinceReading: tagsNewerThanReading,
|
|
12372
|
+
...args.refusedInputTokens === undefined ? {} : { refusedInputTokens: args.refusedInputTokens }
|
|
12133
12373
|
} : undefined,
|
|
12134
12374
|
routine: routineCleanupApplied,
|
|
12135
12375
|
caveman: cavemanConfig
|
|
@@ -13306,12 +13546,12 @@ function systemPromptDates(prompt, sticky) {
|
|
|
13306
13546
|
}
|
|
13307
13547
|
|
|
13308
13548
|
// src/hooks/magic-context/system-prompt-diagnostics.ts
|
|
13309
|
-
import { createHash as
|
|
13549
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
13310
13550
|
function snapshotSystemPrompt(system, preset) {
|
|
13311
13551
|
return { elements: system.map((element) => Buffer.from(element)), preset };
|
|
13312
13552
|
}
|
|
13313
13553
|
function describeSystemPromptChange(previous, current) {
|
|
13314
|
-
const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${
|
|
13554
|
+
const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${createHash4("md5").update(element).digest("hex")}`;
|
|
13315
13555
|
const elements = [];
|
|
13316
13556
|
for (let index = 0;index < Math.max(previous?.elements.length ?? 0, current.elements.length); index++) {
|
|
13317
13557
|
const before = previous?.elements[index];
|
|
@@ -14204,7 +14444,8 @@ function decideSignedThinkingHold(args) {
|
|
|
14204
14444
|
const ended = readingEndsHold({
|
|
14205
14445
|
usagePercentage: args.usagePercentage,
|
|
14206
14446
|
capPercentage,
|
|
14207
|
-
forceBandPressure: args.forceBandPressure
|
|
14447
|
+
forceBandPressure: args.forceBandPressure,
|
|
14448
|
+
refusedInputTokens: args.refusedInputTokens
|
|
14208
14449
|
});
|
|
14209
14450
|
if (ended !== null)
|
|
14210
14451
|
return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
|
|
@@ -14219,7 +14460,8 @@ function decideSignedThinkingHold(args) {
|
|
|
14219
14460
|
function readingEndsHold(args) {
|
|
14220
14461
|
if (!(args.usagePercentage < args.capPercentage))
|
|
14221
14462
|
return "above_cap";
|
|
14222
|
-
|
|
14463
|
+
const refused = args.refusedInputTokens;
|
|
14464
|
+
return args.forceBandPressure || refused !== undefined && Number.isFinite(refused) && refused > 0 ? "force_band" : null;
|
|
14223
14465
|
}
|
|
14224
14466
|
|
|
14225
14467
|
// src/hooks/magic-context/priced-pass-sizing.ts
|
|
@@ -14554,7 +14796,7 @@ function evaluateRequestToolsRelease(args) {
|
|
|
14554
14796
|
}
|
|
14555
14797
|
|
|
14556
14798
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
14557
|
-
import { createHash as
|
|
14799
|
+
import { createHash as createHash8, randomUUID as randomUUID2 } from "node:crypto";
|
|
14558
14800
|
|
|
14559
14801
|
// src/features/magic-context/memory/single-store-embedding-drain.ts
|
|
14560
14802
|
function isWatermarkRow(row) {
|
|
@@ -14611,7 +14853,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
|
14611
14853
|
}
|
|
14612
14854
|
|
|
14613
14855
|
// src/features/magic-context/mural/source-revision.ts
|
|
14614
|
-
import { createHash as
|
|
14856
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
14615
14857
|
var statements = new WeakMap;
|
|
14616
14858
|
function muralSourceRevision(db, projectPath) {
|
|
14617
14859
|
let statement = statements.get(db);
|
|
@@ -14628,7 +14870,7 @@ function muralSourceRevision(db, projectPath) {
|
|
|
14628
14870
|
statements.set(db, statement);
|
|
14629
14871
|
}
|
|
14630
14872
|
const row = statement.get(projectPath, Date.now());
|
|
14631
|
-
return
|
|
14873
|
+
return createHash5("sha256").update(row.revision).digest("hex");
|
|
14632
14874
|
}
|
|
14633
14875
|
|
|
14634
14876
|
// src/features/magic-context/install-instance-id.ts
|
|
@@ -17005,7 +17247,7 @@ function noteExternalLkgReplay(participant, sessionId, inputMessages, servedMess
|
|
|
17005
17247
|
}
|
|
17006
17248
|
|
|
17007
17249
|
// src/hooks/magic-context/rust-served-raw.ts
|
|
17008
|
-
import { createHash as
|
|
17250
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
17009
17251
|
class RustServedRawConflict extends EmergencyFailClosedError {
|
|
17010
17252
|
reason;
|
|
17011
17253
|
messageIds;
|
|
@@ -17019,7 +17261,7 @@ class RustServedRawConflict extends EmergencyFailClosedError {
|
|
|
17019
17261
|
}
|
|
17020
17262
|
function partDigest(part) {
|
|
17021
17263
|
const serialized = JSON.stringify(part);
|
|
17022
|
-
return
|
|
17264
|
+
return createHash7("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
|
|
17023
17265
|
}
|
|
17024
17266
|
function records(doc) {
|
|
17025
17267
|
if (doc.rustServedRaw === undefined)
|
|
@@ -17571,10 +17813,10 @@ function messageCacheSignature(message) {
|
|
|
17571
17813
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
17572
17814
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
17573
17815
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
17574
|
-
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${
|
|
17816
|
+
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash8("sha256").update(serializedMessage).digest("hex")}`;
|
|
17575
17817
|
}
|
|
17576
17818
|
function advanceWireFingerprint(previous, encoded) {
|
|
17577
|
-
return
|
|
17819
|
+
return createHash8("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
17578
17820
|
}
|
|
17579
17821
|
function buildWireFingerprint(encoded) {
|
|
17580
17822
|
let fingerprint = "rust-wire-v1";
|
|
@@ -19363,7 +19605,7 @@ ${notice}`, {}));
|
|
|
19363
19605
|
const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
|
|
19364
19606
|
const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
|
|
19365
19607
|
if (parts?.length) {
|
|
19366
|
-
todoCalls.set(id,
|
|
19608
|
+
todoCalls.set(id, createHash8("sha256").update(JSON.stringify(parts)).digest("hex"));
|
|
19367
19609
|
} else {
|
|
19368
19610
|
todoCalls.delete(id);
|
|
19369
19611
|
}
|
|
@@ -21654,6 +21896,7 @@ function createTransform(deps) {
|
|
|
21654
21896
|
}
|
|
21655
21897
|
noteServedModel(sessionId, modelForBudget);
|
|
21656
21898
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
21899
|
+
const refusedInputTokens = takeProviderRefusedInputTokens(sessionId, modelForBudget ? `${modelForBudget.providerID}/${modelForBudget.modelID}` : undefined);
|
|
21657
21900
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
21658
21901
|
const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
|
|
21659
21902
|
const canUseEmptySentinels = modelAcceptsEmptyContent(resolvedProviderID);
|
|
@@ -21732,6 +21975,7 @@ function createTransform(deps) {
|
|
|
21732
21975
|
messages,
|
|
21733
21976
|
usagePercentage: contextUsageEarly.percentage,
|
|
21734
21977
|
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
21978
|
+
refusedInputTokens,
|
|
21735
21979
|
forceBandPressure: forceBandConfirmed({
|
|
21736
21980
|
percentage: contextUsageEarly.percentage,
|
|
21737
21981
|
fromEstimate: hostOverWindow,
|
|
@@ -22538,6 +22782,7 @@ ${notice}`, notificationParams));
|
|
|
22538
22782
|
const sizedHoldEnd = activeThinkingPrefixHold && !compactionOff && signedThinkingHold?.held === true ? readingEndsHold({
|
|
22539
22783
|
usagePercentage: contextUsage.percentage,
|
|
22540
22784
|
capPercentage: signedThinkingHold.capPercentage,
|
|
22785
|
+
refusedInputTokens,
|
|
22541
22786
|
forceBandPressure: forceBandConfirmed({
|
|
22542
22787
|
percentage: contextUsage.percentage,
|
|
22543
22788
|
fromEstimate: contextUsageFromEstimate,
|
|
@@ -22654,6 +22899,7 @@ ${notice}`, notificationParams));
|
|
|
22654
22899
|
protectedCutoff,
|
|
22655
22900
|
protectedCount: protectionWindow.status.protectedCount,
|
|
22656
22901
|
emergencyCeilingTokens,
|
|
22902
|
+
...refusedInputTokens === undefined ? {} : { refusedInputTokens },
|
|
22657
22903
|
pendingCompartmentInjection,
|
|
22658
22904
|
prefixTrimSourceOrder,
|
|
22659
22905
|
coveredHostInstructions,
|
|
@@ -23832,12 +24078,23 @@ function createMessagesTransformHandler(args) {
|
|
|
23832
24078
|
const servedSessionId = args.recordServed === false ? null : resolveSessionId2(output);
|
|
23833
24079
|
if (servedSessionId)
|
|
23834
24080
|
beginServedRequest(servedSessionId);
|
|
24081
|
+
const refusalCounts = args.providerRefusalCounts;
|
|
24082
|
+
const pass = servedSessionId && refusalCounts && !resolveRust(servedSessionId) ? refusalCounts.begin(servedSessionId, Date.now()) : undefined;
|
|
24083
|
+
if (pass)
|
|
24084
|
+
pass.observeHistory(snapshotRefusalHistory(output.messages, readOpenCodeRefusalMessage));
|
|
23835
24085
|
let returned = false;
|
|
23836
24086
|
try {
|
|
23837
|
-
const served = await servePass(input, output);
|
|
24087
|
+
const served = await (servedSessionId && pass ? withProviderRefusalPass(servedSessionId, pass, () => servePass(input, output)) : servePass(input, output));
|
|
23838
24088
|
returned = true;
|
|
24089
|
+
if (pass) {
|
|
24090
|
+
try {
|
|
24091
|
+
refusalCounts?.captureMessages(pass, output.messages);
|
|
24092
|
+
} catch {}
|
|
24093
|
+
}
|
|
23839
24094
|
return served;
|
|
23840
24095
|
} catch (error) {
|
|
24096
|
+
if (pass && servedSessionId)
|
|
24097
|
+
refusalCounts?.discardPreparation(servedSessionId, pass);
|
|
23841
24098
|
if (args.onRefusal && isTransformRefusal(error) && !(error instanceof EmergencyFailClosedError && error.noticeHandled)) {
|
|
23842
24099
|
const sessionId = servedSessionId ?? resolveSessionId2(output);
|
|
23843
24100
|
if (sessionId) {
|
|
@@ -25067,7 +25324,7 @@ function setSessionWorkMetricsCarry(db, sessionId, source, carry, metrics) {
|
|
|
25067
25324
|
import { readFileSync, statSync } from "node:fs";
|
|
25068
25325
|
|
|
25069
25326
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
25070
|
-
import { createHash as
|
|
25327
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
25071
25328
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
25072
25329
|
"embedding.api_key",
|
|
25073
25330
|
"embedding.endpoint",
|
|
@@ -25116,7 +25373,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
25116
25373
|
];
|
|
25117
25374
|
var loggedFailureSignatures = new Map;
|
|
25118
25375
|
function sha256Prefix(value, length = 16) {
|
|
25119
|
-
return
|
|
25376
|
+
return createHash9("sha256").update(value).digest("hex").slice(0, length);
|
|
25120
25377
|
}
|
|
25121
25378
|
function warningLooksEmbeddingRelated(message) {
|
|
25122
25379
|
const lower = message.toLowerCase();
|
|
@@ -26654,7 +26911,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26654
26911
|
const db = readDatabase();
|
|
26655
26912
|
if (!db)
|
|
26656
26913
|
return { ok: false, error: "db unavailable" };
|
|
26657
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
26914
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-5gkzamy2.js"));
|
|
26658
26915
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-vtnk598k.js"));
|
|
26659
26916
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
26660
26917
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -26739,7 +26996,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26739
26996
|
const db = readDatabase();
|
|
26740
26997
|
if (!db)
|
|
26741
26998
|
return { ok: false, error: "db unavailable" };
|
|
26742
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
26999
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-ksdn2emb.js"));
|
|
26743
27000
|
const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
|
|
26744
27001
|
const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
|
|
26745
27002
|
if (!window)
|
|
@@ -28178,7 +28435,7 @@ function stageManualBaseline(db, sessionID, render) {
|
|
|
28178
28435
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
28179
28436
|
|
|
28180
28437
|
// src/v2/fold/owner.ts
|
|
28181
|
-
import { createHash as
|
|
28438
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
28182
28439
|
|
|
28183
28440
|
// src/v2/fold/summary.ts
|
|
28184
28441
|
var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
|
|
@@ -28208,7 +28465,7 @@ ${head}
|
|
|
28208
28465
|
}
|
|
28209
28466
|
|
|
28210
28467
|
// src/v2/fold/owner.ts
|
|
28211
|
-
var foldDigest = (value) =>
|
|
28468
|
+
var foldDigest = (value) => createHash10("sha256").update(value).digest("hex");
|
|
28212
28469
|
var boundToCheckpoint = (record) => record.cutSeq !== undefined || record.rendered !== undefined || record.answered !== undefined;
|
|
28213
28470
|
|
|
28214
28471
|
class FoldOwner {
|
|
@@ -33030,11 +33287,11 @@ class DeletedSessionTombstones {
|
|
|
33030
33287
|
}
|
|
33031
33288
|
|
|
33032
33289
|
// src/features/magic-context/dreamer/task-executor.ts
|
|
33033
|
-
import { createHash as
|
|
33290
|
+
import { createHash as createHash18 } from "node:crypto";
|
|
33034
33291
|
import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
|
|
33035
33292
|
|
|
33036
33293
|
// src/features/magic-context/mural/compress-cues.ts
|
|
33037
|
-
import { createHash as
|
|
33294
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
33038
33295
|
|
|
33039
33296
|
// src/features/magic-context/dreamer/lease.ts
|
|
33040
33297
|
var LEASE_DURATION_MS = 2 * 60 * 1000;
|
|
@@ -33740,7 +33997,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
|
|
|
33740
33997
|
log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
|
|
33741
33998
|
}
|
|
33742
33999
|
}
|
|
33743
|
-
const commandId = `mural-cues:${route.moduleCommandId}:${
|
|
34000
|
+
const commandId = `mural-cues:${route.moduleCommandId}:${createHash11("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
33744
34001
|
let response;
|
|
33745
34002
|
try {
|
|
33746
34003
|
response = await route.moduleClient.call({
|
|
@@ -34357,7 +34614,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
|
|
|
34357
34614
|
}
|
|
34358
34615
|
|
|
34359
34616
|
// src/features/magic-context/dreamer/classify.ts
|
|
34360
|
-
import { createHash as
|
|
34617
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
34361
34618
|
|
|
34362
34619
|
// src/plugin/rust-tool-backends.ts
|
|
34363
34620
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -34794,7 +35051,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
|
|
|
34794
35051
|
if (entry.qualifier)
|
|
34795
35052
|
modelVariants[entry.model] = entry.qualifier;
|
|
34796
35053
|
}
|
|
34797
|
-
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
35054
|
+
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash12("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
34798
35055
|
const runTask = (hostCompletion) => args.moduleClient?.call({
|
|
34799
35056
|
sessionId: args.moduleSessionId,
|
|
34800
35057
|
projectRoot: args.moduleProjectRoot,
|
|
@@ -35087,7 +35344,7 @@ function takeCurateSafetyRefusalCount(sessionId) {
|
|
|
35087
35344
|
|
|
35088
35345
|
// src/features/magic-context/dreamer/docs-proposals.ts
|
|
35089
35346
|
import { execFileSync } from "node:child_process";
|
|
35090
|
-
import { createHash as
|
|
35347
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
35091
35348
|
import {
|
|
35092
35349
|
existsSync as existsSync4,
|
|
35093
35350
|
mkdirSync,
|
|
@@ -35102,7 +35359,7 @@ import {
|
|
|
35102
35359
|
import { tmpdir } from "node:os";
|
|
35103
35360
|
import { join as join8 } from "node:path";
|
|
35104
35361
|
var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
35105
|
-
var hash = (text) =>
|
|
35362
|
+
var hash = (text) => createHash13("sha256").update(text).digest("hex");
|
|
35106
35363
|
var proposalDir = (projectDir) => join8(projectDir, ".cortexkit/magic-context/docs-update-proposals");
|
|
35107
35364
|
function docsBaseHashes(projectDir) {
|
|
35108
35365
|
return Object.fromEntries(FILES.map((name) => [
|
|
@@ -35749,7 +36006,7 @@ function throwIfAborted2(signal) {
|
|
|
35749
36006
|
}
|
|
35750
36007
|
|
|
35751
36008
|
// src/features/magic-context/smart-notes/compiler.ts
|
|
35752
|
-
import { createHash as
|
|
36009
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
35753
36010
|
|
|
35754
36011
|
// src/features/magic-context/smart-notes/compiler-prompt.ts
|
|
35755
36012
|
var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
|
|
@@ -36096,7 +36353,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
36096
36353
|
return warnings;
|
|
36097
36354
|
}
|
|
36098
36355
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
36099
|
-
return
|
|
36356
|
+
return createHash14("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
36100
36357
|
}
|
|
36101
36358
|
function extractJsonObject(output) {
|
|
36102
36359
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -36869,7 +37126,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
36869
37126
|
}
|
|
36870
37127
|
|
|
36871
37128
|
// src/features/magic-context/dreamer/map-memories.ts
|
|
36872
|
-
import { createHash as
|
|
37129
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
36873
37130
|
|
|
36874
37131
|
// src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
36875
37132
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -37514,7 +37771,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
|
|
|
37514
37771
|
name: "memory.set_mapping",
|
|
37515
37772
|
arguments: {
|
|
37516
37773
|
memory_project: args.projectIdentity,
|
|
37517
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
37774
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash15("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
37518
37775
|
rows
|
|
37519
37776
|
}
|
|
37520
37777
|
}
|
|
@@ -38848,7 +39105,7 @@ function insertDreamRun(db, run) {
|
|
|
38848
39105
|
}
|
|
38849
39106
|
|
|
38850
39107
|
// src/features/magic-context/dreamer/verify.ts
|
|
38851
|
-
import { createHash as
|
|
39108
|
+
import { createHash as createHash17 } from "node:crypto";
|
|
38852
39109
|
|
|
38853
39110
|
// src/features/magic-context/dreamer/verify-diff.ts
|
|
38854
39111
|
import { execFile as execFile3 } from "node:child_process";
|
|
@@ -38972,7 +39229,7 @@ Read only these changed line ranges if they may affect the claim.`
|
|
|
38972
39229
|
import path6 from "node:path";
|
|
38973
39230
|
|
|
38974
39231
|
// src/features/magic-context/dreamer/verify-state.ts
|
|
38975
|
-
import { createHash as
|
|
39232
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
38976
39233
|
import { readFile, realpath as realpath2 } from "node:fs/promises";
|
|
38977
39234
|
import path5 from "node:path";
|
|
38978
39235
|
function verificationMetadata(memory) {
|
|
@@ -38985,7 +39242,7 @@ function verificationMetadata(memory) {
|
|
|
38985
39242
|
}
|
|
38986
39243
|
async function verificationFilesFingerprint(directory, files) {
|
|
38987
39244
|
const root = await resolveGitTopLevel(directory) ?? path5.resolve(directory);
|
|
38988
|
-
const hash =
|
|
39245
|
+
const hash = createHash16("sha256");
|
|
38989
39246
|
for (const file of [...new Set(files)].sort()) {
|
|
38990
39247
|
const absolute = path5.resolve(root, file);
|
|
38991
39248
|
const withinRoot = (candidate) => {
|
|
@@ -38998,7 +39255,7 @@ async function verificationFilesFingerprint(directory, files) {
|
|
|
38998
39255
|
try {
|
|
38999
39256
|
if (!withinRoot(await realpath2(absolute)))
|
|
39000
39257
|
return null;
|
|
39001
|
-
hash.update(
|
|
39258
|
+
hash.update(createHash16("sha256").update(await readFile(absolute)).digest("hex"));
|
|
39002
39259
|
} catch (error) {
|
|
39003
39260
|
if (error.code !== "ENOENT")
|
|
39004
39261
|
return null;
|
|
@@ -39803,7 +40060,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
|
|
|
39803
40060
|
name: "memory.set_verification",
|
|
39804
40061
|
arguments: {
|
|
39805
40062
|
memory_project: args.projectIdentity,
|
|
39806
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
40063
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash17("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
39807
40064
|
rows
|
|
39808
40065
|
}
|
|
39809
40066
|
}
|
|
@@ -40717,7 +40974,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
40717
40974
|
}
|
|
40718
40975
|
function computeRetrospectiveWindowKey(flagged) {
|
|
40719
40976
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
40720
|
-
return
|
|
40977
|
+
return createHash18("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
40721
40978
|
}
|
|
40722
40979
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
40723
40980
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -42773,10 +43030,10 @@ function readForkHistoryGap(db, openReader, sessionID) {
|
|
|
42773
43030
|
}
|
|
42774
43031
|
|
|
42775
43032
|
// src/v2/hooks/generate.ts
|
|
42776
|
-
import { createHash as
|
|
43033
|
+
import { createHash as createHash19 } from "node:crypto";
|
|
42777
43034
|
var typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
|
|
42778
43035
|
function hostPrefixDigest(messages, end) {
|
|
42779
|
-
const hash =
|
|
43036
|
+
const hash = createHash19("sha256");
|
|
42780
43037
|
const chunks = [];
|
|
42781
43038
|
let pendingCodeUnits = 0;
|
|
42782
43039
|
const batchCodeUnits = 16 * 1024 * 1024;
|
|
@@ -42974,10 +43231,197 @@ function hiddenTerminalError(event) {
|
|
|
42974
43231
|
return;
|
|
42975
43232
|
}
|
|
42976
43233
|
|
|
43234
|
+
// src/v2/hooks/http-refusal-count.ts
|
|
43235
|
+
class V2HttpRefusalCounts {
|
|
43236
|
+
counts;
|
|
43237
|
+
requests = new WeakMap;
|
|
43238
|
+
associated = new WeakSet;
|
|
43239
|
+
inFlight = new Map;
|
|
43240
|
+
constructor(counts) {
|
|
43241
|
+
this.counts = counts;
|
|
43242
|
+
}
|
|
43243
|
+
capture({ sessionID, model, request }) {
|
|
43244
|
+
const pass = this.counts.latest(sessionID);
|
|
43245
|
+
if (!pass)
|
|
43246
|
+
return;
|
|
43247
|
+
this.release(sessionID);
|
|
43248
|
+
this.associated.add(request);
|
|
43249
|
+
if (request.signal.aborted)
|
|
43250
|
+
return;
|
|
43251
|
+
const attempt = { sessionID, model: `${model.providerID}/${model.id}`, pass };
|
|
43252
|
+
this.requests.set(request, attempt);
|
|
43253
|
+
this.inFlight.set(sessionID, request);
|
|
43254
|
+
const abort = () => this.releaseNonSizeAttempt(request);
|
|
43255
|
+
request.signal.addEventListener("abort", abort, { once: true });
|
|
43256
|
+
attempt.detachAbort = () => request.signal.removeEventListener("abort", abort);
|
|
43257
|
+
try {
|
|
43258
|
+
attempt.body = request.clone();
|
|
43259
|
+
} catch {}
|
|
43260
|
+
}
|
|
43261
|
+
async observe(draft, errorBody) {
|
|
43262
|
+
const attempt = this.detach(draft.request);
|
|
43263
|
+
if (!attempt) {
|
|
43264
|
+
if (draft.response.ok)
|
|
43265
|
+
this.accept(draft.sessionID);
|
|
43266
|
+
return this.associated.has(draft.request);
|
|
43267
|
+
}
|
|
43268
|
+
const model = `${draft.model.providerID}/${draft.model.id}`;
|
|
43269
|
+
if (draft.sessionID !== attempt.sessionID || model !== attempt.model) {
|
|
43270
|
+
cancelBody(attempt);
|
|
43271
|
+
return true;
|
|
43272
|
+
}
|
|
43273
|
+
if (draft.response.ok) {
|
|
43274
|
+
cancelBody(attempt);
|
|
43275
|
+
this.accept(draft.sessionID);
|
|
43276
|
+
return true;
|
|
43277
|
+
}
|
|
43278
|
+
if (!isProviderSizeRefusal({ status: draft.response.status, responseBody: errorBody })) {
|
|
43279
|
+
this.counts.discardPreparation(attempt.sessionID, attempt.pass);
|
|
43280
|
+
cancelBody(attempt);
|
|
43281
|
+
return true;
|
|
43282
|
+
}
|
|
43283
|
+
this.counts.discardDraft(attempt.sessionID, attempt.pass);
|
|
43284
|
+
try {
|
|
43285
|
+
const body = await attempt.body?.json();
|
|
43286
|
+
const tokens = countFullRequest(body);
|
|
43287
|
+
if (tokens !== undefined)
|
|
43288
|
+
this.counts.refusal(attempt.sessionID, attempt.model, attempt.pass, tokens);
|
|
43289
|
+
} catch {} finally {
|
|
43290
|
+
cancelBody(attempt);
|
|
43291
|
+
this.counts.discardPreparation(attempt.sessionID, attempt.pass);
|
|
43292
|
+
}
|
|
43293
|
+
return true;
|
|
43294
|
+
}
|
|
43295
|
+
accept(sessionID) {
|
|
43296
|
+
this.counts.forget(sessionID);
|
|
43297
|
+
this.release(sessionID);
|
|
43298
|
+
}
|
|
43299
|
+
endRun(sessionID) {
|
|
43300
|
+
const request = this.inFlight.get(sessionID);
|
|
43301
|
+
this.counts.endRun(sessionID, () => {
|
|
43302
|
+
if (request)
|
|
43303
|
+
this.discard(request);
|
|
43304
|
+
});
|
|
43305
|
+
}
|
|
43306
|
+
release(sessionID, nonSizeFailure = false) {
|
|
43307
|
+
const request = this.inFlight.get(sessionID);
|
|
43308
|
+
if (!request)
|
|
43309
|
+
return;
|
|
43310
|
+
if (nonSizeFailure)
|
|
43311
|
+
this.releaseNonSizeAttempt(request);
|
|
43312
|
+
else
|
|
43313
|
+
this.discard(request);
|
|
43314
|
+
}
|
|
43315
|
+
dispose() {
|
|
43316
|
+
for (const request of this.inFlight.values())
|
|
43317
|
+
this.discard(request);
|
|
43318
|
+
}
|
|
43319
|
+
detach(request) {
|
|
43320
|
+
const attempt = this.requests.get(request);
|
|
43321
|
+
if (!attempt)
|
|
43322
|
+
return;
|
|
43323
|
+
this.requests.delete(request);
|
|
43324
|
+
if (this.inFlight.get(attempt.sessionID) === request)
|
|
43325
|
+
this.inFlight.delete(attempt.sessionID);
|
|
43326
|
+
attempt.detachAbort?.();
|
|
43327
|
+
return attempt;
|
|
43328
|
+
}
|
|
43329
|
+
discard(request) {
|
|
43330
|
+
const attempt = this.detach(request);
|
|
43331
|
+
if (!attempt)
|
|
43332
|
+
return;
|
|
43333
|
+
cancelBody(attempt);
|
|
43334
|
+
}
|
|
43335
|
+
releaseNonSizeAttempt(request) {
|
|
43336
|
+
const attempt = this.detach(request);
|
|
43337
|
+
if (!attempt)
|
|
43338
|
+
return;
|
|
43339
|
+
this.counts.discardPreparation(attempt.sessionID, attempt.pass);
|
|
43340
|
+
cancelBody(attempt);
|
|
43341
|
+
}
|
|
43342
|
+
}
|
|
43343
|
+
function cancelBody(attempt) {
|
|
43344
|
+
const body = attempt?.body?.body;
|
|
43345
|
+
if (body && !body.locked)
|
|
43346
|
+
body.cancel().catch(() => {});
|
|
43347
|
+
}
|
|
43348
|
+
function readOpenCode2RefusalMessage(message, values) {
|
|
43349
|
+
values.push(message.role);
|
|
43350
|
+
for (const part of message.content) {
|
|
43351
|
+
switch (part.type) {
|
|
43352
|
+
case "text":
|
|
43353
|
+
case "reasoning":
|
|
43354
|
+
values.push(part.type, part.text);
|
|
43355
|
+
break;
|
|
43356
|
+
case "tool-call":
|
|
43357
|
+
values.push("tool-call", part.name, part.input);
|
|
43358
|
+
break;
|
|
43359
|
+
case "tool-result":
|
|
43360
|
+
values.push("tool-result", part.name, part.result);
|
|
43361
|
+
break;
|
|
43362
|
+
case "media": {
|
|
43363
|
+
const media = isRecord(part.media) ? part.media : {};
|
|
43364
|
+
const source = isRecord(media.source) ? media.source : {};
|
|
43365
|
+
values.push("media", source.type, source.mediaType, source.data, source.url);
|
|
43366
|
+
break;
|
|
43367
|
+
}
|
|
43368
|
+
default:
|
|
43369
|
+
pushRefusalFields(part, values);
|
|
43370
|
+
}
|
|
43371
|
+
}
|
|
43372
|
+
}
|
|
43373
|
+
function countFullRequest(body) {
|
|
43374
|
+
if (!body || typeof body !== "object")
|
|
43375
|
+
return;
|
|
43376
|
+
const request = body;
|
|
43377
|
+
if (request.previous_response_id || request.conversation || request.cachedContent)
|
|
43378
|
+
return;
|
|
43379
|
+
const transcript = request.messages ?? request.input ?? request.contents;
|
|
43380
|
+
if (!Array.isArray(transcript))
|
|
43381
|
+
return;
|
|
43382
|
+
if (request.tools !== undefined && !Array.isArray(request.tools))
|
|
43383
|
+
return;
|
|
43384
|
+
let images = 0;
|
|
43385
|
+
const text = JSON.stringify({
|
|
43386
|
+
transcript,
|
|
43387
|
+
system: request.system ?? request.instructions ?? request.systemInstruction,
|
|
43388
|
+
tools: request.tools
|
|
43389
|
+
}, (_key, value) => {
|
|
43390
|
+
if (!isRecord(value))
|
|
43391
|
+
return value;
|
|
43392
|
+
const tokens = httpImageTokens(value);
|
|
43393
|
+
if (tokens === undefined)
|
|
43394
|
+
return value;
|
|
43395
|
+
images += tokens;
|
|
43396
|
+
return null;
|
|
43397
|
+
});
|
|
43398
|
+
return estimateTokens(text) + images;
|
|
43399
|
+
}
|
|
43400
|
+
function httpImageTokens(part) {
|
|
43401
|
+
if (part.type === "image" && isRecord(part.source)) {
|
|
43402
|
+
const source = part.source;
|
|
43403
|
+
if (source.type === "base64" && typeof source.media_type === "string" && typeof source.data === "string")
|
|
43404
|
+
return estimateImageTokensFromBase64(source.media_type, source.data);
|
|
43405
|
+
if (source.type === "url" && typeof source.url === "string")
|
|
43406
|
+
return estimateImageTokensFromDataUrl(source.url);
|
|
43407
|
+
}
|
|
43408
|
+
if (part.type === "image_url" || part.type === "input_image") {
|
|
43409
|
+
const url = isRecord(part.image_url) ? part.image_url.url : part.image_url;
|
|
43410
|
+
if (typeof url === "string")
|
|
43411
|
+
return estimateImageTokensFromDataUrl(url);
|
|
43412
|
+
}
|
|
43413
|
+
const inline = part.inlineData ?? part.inline_data;
|
|
43414
|
+
if (isRecord(inline)) {
|
|
43415
|
+
const mime = inline.mimeType ?? inline.mime_type;
|
|
43416
|
+
if (typeof mime === "string" && mime.startsWith("image/") && typeof inline.data === "string")
|
|
43417
|
+
return estimateImageTokensFromBase64(mime, inline.data);
|
|
43418
|
+
}
|
|
43419
|
+
}
|
|
43420
|
+
|
|
42977
43421
|
// src/v2/hooks/lkg-system.ts
|
|
42978
|
-
import { createHash as
|
|
43422
|
+
import { createHash as createHash20 } from "node:crypto";
|
|
42979
43423
|
function identity2(slot) {
|
|
42980
|
-
return
|
|
43424
|
+
return createHash20("sha256").update(JSON.stringify({
|
|
42981
43425
|
capturedAt: slot.capturedAt,
|
|
42982
43426
|
captureSequence: slot.captureSequence,
|
|
42983
43427
|
rowVersion: slot.rowVersion,
|
|
@@ -43106,13 +43550,15 @@ class V2OverflowRecovery {
|
|
|
43106
43550
|
if (error === undefined)
|
|
43107
43551
|
return;
|
|
43108
43552
|
const prior = this.requests.get(sessionID);
|
|
43109
|
-
|
|
43553
|
+
const sizeRefusal = isProviderSizeRefusal(error);
|
|
43554
|
+
if (prior?.observed || isProviderRateLimit(error) || !sizeRefusal && !detectOverflow(error).isOverflow)
|
|
43110
43555
|
return;
|
|
43111
43556
|
const messageID = event.data?.assistantMessageID;
|
|
43112
43557
|
const step = readStep(sessionID, messageID);
|
|
43113
43558
|
if (!step)
|
|
43114
43559
|
return;
|
|
43115
|
-
|
|
43560
|
+
const durable = !!messageID || !!step.error && detectOverflow(step.error).isOverflow;
|
|
43561
|
+
if (!durable && !isProviderSizeRefusal(step.error))
|
|
43116
43562
|
return;
|
|
43117
43563
|
if (!prior && step.model)
|
|
43118
43564
|
this.begin({
|
|
@@ -43128,7 +43574,8 @@ class V2OverflowRecovery {
|
|
|
43128
43574
|
sessionID,
|
|
43129
43575
|
error,
|
|
43130
43576
|
model: step?.model ?? request.model,
|
|
43131
|
-
assistantMessageID: messageID ?? step?.id
|
|
43577
|
+
assistantMessageID: messageID ?? step?.id,
|
|
43578
|
+
durable
|
|
43132
43579
|
});
|
|
43133
43580
|
}
|
|
43134
43581
|
observe(input) {
|
|
@@ -43139,13 +43586,22 @@ class V2OverflowRecovery {
|
|
|
43139
43586
|
return;
|
|
43140
43587
|
if (input.status === 429 || isProviderRateLimit(input.error))
|
|
43141
43588
|
return;
|
|
43142
|
-
const
|
|
43589
|
+
const reportedError = typeof input.error === "string" && input.status !== undefined ? {
|
|
43590
|
+
status: input.status,
|
|
43591
|
+
responseBody: input.error,
|
|
43592
|
+
data: { responseBody: input.error }
|
|
43593
|
+
} : input.error;
|
|
43594
|
+
const modelKey = `${input.model.providerID}/${input.model.id}`;
|
|
43595
|
+
if (!this.deps.compactionOff && !input.skipMeasured && isProviderSizeRefusal(reportedError))
|
|
43596
|
+
this.deps.onProviderRefused?.(input.sessionID, modelKey, input.assistantMessageID);
|
|
43597
|
+
if (input.durable === false)
|
|
43598
|
+
return;
|
|
43599
|
+
const detection = detectOverflow(reportedError);
|
|
43143
43600
|
if (!detection.isOverflow)
|
|
43144
43601
|
return;
|
|
43145
43602
|
const db = this.deps.database();
|
|
43146
43603
|
if (!db)
|
|
43147
43604
|
return;
|
|
43148
|
-
const modelKey = `${input.model.providerID}/${input.model.id}`;
|
|
43149
43605
|
const reportedLimit = resolveOpenCodeOverflowLimit(detection, input.model.providerID, input.model.id, { db, sessionID: input.sessionID });
|
|
43150
43606
|
if (this.deps.compactionOff) {
|
|
43151
43607
|
if (reportedLimit)
|
|
@@ -57422,7 +57878,7 @@ function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
|
|
|
57422
57878
|
return parts.join(" ");
|
|
57423
57879
|
}
|
|
57424
57880
|
// src/tools/ctx-reduce/tools.ts
|
|
57425
|
-
import { createHash as
|
|
57881
|
+
import { createHash as createHash21 } from "node:crypto";
|
|
57426
57882
|
|
|
57427
57883
|
// src/features/magic-context/range-parser.ts
|
|
57428
57884
|
function parseRangeString(input) {
|
|
@@ -57485,11 +57941,11 @@ function createCtxReduceTool(deps) {
|
|
|
57485
57941
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
57486
57942
|
if (Buffer.byteLength(stableId) <= 128)
|
|
57487
57943
|
return stableId;
|
|
57488
|
-
return `oc-${
|
|
57944
|
+
return `oc-${createHash21("sha256").update(stableId).digest("hex")}`;
|
|
57489
57945
|
}
|
|
57490
57946
|
fallbackCommandSequence += 1;
|
|
57491
57947
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
57492
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
57948
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash21("sha256").update(monotonicId).digest("hex")}`;
|
|
57493
57949
|
};
|
|
57494
57950
|
return tool({
|
|
57495
57951
|
description: CTX_REDUCE_DESCRIPTION,
|
|
@@ -58327,7 +58783,14 @@ function restoreNativeCheckpointInput(messages, incoming, restored, reader, sess
|
|
|
58327
58783
|
const at = messages.indexOf(incoming);
|
|
58328
58784
|
return [...messages.slice(0, at), ...hidden, ...messages.slice(at + 1)];
|
|
58329
58785
|
}
|
|
58330
|
-
function
|
|
58786
|
+
function latestDraftAssistantID(messages) {
|
|
58787
|
+
for (let index = messages.length - 1;index >= 0; index--) {
|
|
58788
|
+
const message = messages[index];
|
|
58789
|
+
if (message?.role === "assistant" && message.id)
|
|
58790
|
+
return message.id;
|
|
58791
|
+
}
|
|
58792
|
+
}
|
|
58793
|
+
function checkpointRequestSizingInput(draft) {
|
|
58331
58794
|
let toolDefinitionTokens = 0;
|
|
58332
58795
|
for (const tool of Object.values(draft.tools)) {
|
|
58333
58796
|
const schema = JSON.stringify(tool.input);
|
|
@@ -58339,7 +58802,7 @@ function estimateCheckpointRequest(draft) {
|
|
|
58339
58802
|
...draft,
|
|
58340
58803
|
messages: draft.messages.map((message) => HEAD_IDS.some((id) => message.id === id) ? { ...message, id: undefined } : message)
|
|
58341
58804
|
};
|
|
58342
|
-
return
|
|
58805
|
+
return {
|
|
58343
58806
|
messages: adaptPayload(estimateDraft).messages,
|
|
58344
58807
|
toolDefinitionTokens,
|
|
58345
58808
|
systemPromptTokens: estimateTokens(JSON.stringify(draft.system)),
|
|
@@ -58347,7 +58810,10 @@ function estimateCheckpointRequest(draft) {
|
|
|
58347
58810
|
modelID: draft.model.id,
|
|
58348
58811
|
agentName: draft.agent,
|
|
58349
58812
|
sessionId: draft.sessionID
|
|
58350
|
-
}
|
|
58813
|
+
};
|
|
58814
|
+
}
|
|
58815
|
+
function estimateCheckpointRequest(draft) {
|
|
58816
|
+
return estimateFinalWireInputTokens(checkpointRequestSizingInput(draft));
|
|
58351
58817
|
}
|
|
58352
58818
|
function estimateCheckpointFraming(draft, checkpoint, submitted) {
|
|
58353
58819
|
const framing = structuredClone(checkpoint);
|
|
@@ -58422,7 +58888,7 @@ async function cacheV2SessionDirectory(session, sessionID, directories) {
|
|
|
58422
58888
|
sessionLog2(sessionID, "v2 session directory lookup failed; using the launch directory:", error);
|
|
58423
58889
|
}
|
|
58424
58890
|
}
|
|
58425
|
-
var contextPass = new
|
|
58891
|
+
var contextPass = new AsyncLocalStorage3;
|
|
58426
58892
|
function noteCheckpointWithoutTail(sessionID, cut, incoming, messageCount) {
|
|
58427
58893
|
const pass = contextPass.getStore();
|
|
58428
58894
|
if (pass?.sessionID !== sessionID)
|
|
@@ -58807,11 +59273,18 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
58807
59273
|
}) : undefined;
|
|
58808
59274
|
const hiddenChildHook = new HiddenChildHook;
|
|
58809
59275
|
const usage = new Map;
|
|
59276
|
+
const refusalCounts = new ProviderRefusalCounts;
|
|
59277
|
+
const httpRefusalCounts = new V2HttpRefusalCounts(refusalCounts);
|
|
58810
59278
|
const overflowRecovery = new V2OverflowRecovery({
|
|
58811
59279
|
database: () => db ?? null,
|
|
58812
59280
|
compactionOff,
|
|
58813
59281
|
isHidden: (sessionID) => hiddenChildHook.owns(sessionID),
|
|
58814
59282
|
onOverflow: (sessionID) => notifyV2ProviderOverflow(sessionID, openStoreReader),
|
|
59283
|
+
onProviderRefused: (sessionID, modelKey, assistantMessageID) => {
|
|
59284
|
+
const pass = refusalCounts.latestForTerminalFailure(sessionID, assistantMessageID);
|
|
59285
|
+
if (pass)
|
|
59286
|
+
refusalCounts.refusal(sessionID, modelKey, pass);
|
|
59287
|
+
},
|
|
58815
59288
|
onInputTokens: (sessionID, inputTokens, limit) => usage.set(sessionID, {
|
|
58816
59289
|
usage: { inputTokens, percentage: limit > 0 ? inputTokens / limit * 100 : 100 },
|
|
58817
59290
|
hasUsageTokens: true,
|
|
@@ -58822,6 +59295,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
58822
59295
|
await hiddenChildHook.cacheRequest(draft);
|
|
58823
59296
|
if (draft.kind !== "primary" || hiddenChildHook.owns(draft.sessionID))
|
|
58824
59297
|
return;
|
|
59298
|
+
if (!compactionOff && draft.model)
|
|
59299
|
+
httpRefusalCounts.capture({ ...draft, model: draft.model });
|
|
58825
59300
|
const selectedModel = liveModels.get(draft.sessionID);
|
|
58826
59301
|
if (selectedModel)
|
|
58827
59302
|
overflowRecovery.begin({
|
|
@@ -58834,12 +59309,21 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
58834
59309
|
cleanup.tools = () => tools.dispose();
|
|
58835
59310
|
const generateReplay = new V2GenerateReplay;
|
|
58836
59311
|
await context.session.hook("http.response", async (draft) => {
|
|
58837
|
-
if (!db || draft.kind !== "primary"
|
|
59312
|
+
if (!db || draft.kind !== "primary")
|
|
58838
59313
|
return;
|
|
59314
|
+
if (draft.response.ok) {
|
|
59315
|
+
httpRefusalCounts.accept(draft.sessionID);
|
|
59316
|
+
return;
|
|
59317
|
+
}
|
|
59318
|
+
if (draft.request && isMeasuredRefusalStatusVeto(draft.response.status))
|
|
59319
|
+
httpRefusalCounts.releaseNonSizeAttempt(draft.request);
|
|
59320
|
+
const error = await draft.response.clone().text();
|
|
59321
|
+
const associated = !compactionOff && draft.request !== undefined && await httpRefusalCounts.observe({ ...draft, request: draft.request }, error);
|
|
58839
59322
|
overflowRecovery.observe({
|
|
58840
59323
|
...draft,
|
|
58841
|
-
error
|
|
58842
|
-
status: draft.response.status
|
|
59324
|
+
error,
|
|
59325
|
+
status: draft.response.status,
|
|
59326
|
+
skipMeasured: associated
|
|
58843
59327
|
});
|
|
58844
59328
|
});
|
|
58845
59329
|
await registerHiddenChildAgents(context.agent);
|
|
@@ -59364,7 +59848,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
59364
59848
|
}
|
|
59365
59849
|
};
|
|
59366
59850
|
const usageController = new AbortController;
|
|
59367
|
-
cleanup.abortUsage = () =>
|
|
59851
|
+
cleanup.abortUsage = () => {
|
|
59852
|
+
usageController.abort();
|
|
59853
|
+
httpRefusalCounts.dispose();
|
|
59854
|
+
};
|
|
59368
59855
|
const usageDone = (async () => {
|
|
59369
59856
|
let retry = 0;
|
|
59370
59857
|
while (!usageController.signal.aborted) {
|
|
@@ -59386,6 +59873,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
59386
59873
|
continue;
|
|
59387
59874
|
const sessionID = event.data.sessionID;
|
|
59388
59875
|
observeSyntheticAdmissionEvent(context, event);
|
|
59876
|
+
if (event.type?.startsWith("session.revert.") || event.type === "session.message.removed" || event.type === "session.message.deleted" || event.type === "session.deleted")
|
|
59877
|
+
httpRefusalCounts.accept(sessionID);
|
|
59878
|
+
if ((event.type === "session.step.failed" || event.type === "session.error") && !isProviderSizeRefusal(event.data.error ?? hiddenTerminalError(event)))
|
|
59879
|
+
httpRefusalCounts.release(sessionID, true);
|
|
59389
59880
|
overflowRecovery.observeTerminal(event, (id, messageID) => {
|
|
59390
59881
|
const reader = openStoreReader();
|
|
59391
59882
|
try {
|
|
@@ -59398,6 +59889,13 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
59398
59889
|
reader.close();
|
|
59399
59890
|
}
|
|
59400
59891
|
});
|
|
59892
|
+
if (event.type === "session.step.ended") {
|
|
59893
|
+
const pass = refusalCounts.latestForTerminalFailure(sessionID, event.data.assistantMessageID);
|
|
59894
|
+
if (pass)
|
|
59895
|
+
refusalCounts.discardPreparation(sessionID, pass);
|
|
59896
|
+
}
|
|
59897
|
+
if (event.type === "session.execution.succeeded" || event.type === "session.execution.failed" || event.type === "session.execution.interrupted")
|
|
59898
|
+
httpRefusalCounts.endRun(sessionID);
|
|
59401
59899
|
if (event.type === "session.revert.staged" && db) {
|
|
59402
59900
|
revertMessageCleanup.captureStageProof(sessionID, event.data.revert?.messageID);
|
|
59403
59901
|
}
|
|
@@ -59598,6 +60096,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
59598
60096
|
const running = reader.latestRunningCompaction(draft.sessionID);
|
|
59599
60097
|
const attempt = running && nativeFoldMemory?.admission(draft.sessionID, running.id);
|
|
59600
60098
|
const manual = running?.data.reason === "manual" && !(attempt?.status === "pending" && attempt.owner_token);
|
|
60099
|
+
if (manual)
|
|
60100
|
+
httpRefusalCounts.accept(draft.sessionID);
|
|
59601
60101
|
const moduleBaseline = rustModeModuleClient ? servedModuleM0Text(draft.sessionID) : undefined;
|
|
59602
60102
|
const source = !rustModeModuleClient ? "typescript" : moduleBaseline === null ? "typescript_fallback" : "module";
|
|
59603
60103
|
if (nativeFoldReplay) {
|
|
@@ -59863,7 +60363,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
59863
60363
|
onRustEngineReconnectRefusal: (refusal) => rustRefusalRecovery?.arm(refusal),
|
|
59864
60364
|
...createHostSeams(context, readAllForConversion, pagedRead, liveModels)
|
|
59865
60365
|
});
|
|
59866
|
-
const runManagedContext = async (draft, pass, previousRecovery) => {
|
|
60366
|
+
const runManagedContext = async (draft, pass, previousRecovery, refusalPass) => {
|
|
59867
60367
|
rememberHostMedia(draft.messages);
|
|
59868
60368
|
if (hiddenChildHook.apply(draft))
|
|
59869
60369
|
return "skipped";
|
|
@@ -60320,6 +60820,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
60320
60820
|
nativeFoldReplay.invalidate(draft.sessionID, true);
|
|
60321
60821
|
}
|
|
60322
60822
|
}
|
|
60823
|
+
if (refusalPass)
|
|
60824
|
+
refusalPass.observeHistory(snapshotRefusalHistory(draft.messages, readOpenCode2RefusalMessage));
|
|
60323
60825
|
const mapped = adaptPayload(draft, syntheticIDs, messageTimes, anchorTimesOnly, instructionRows);
|
|
60324
60826
|
bindSystemDateRequestIdentity(mapped, draft);
|
|
60325
60827
|
checkpointPassPermissions.delete(draft.sessionID);
|
|
@@ -60548,12 +61050,15 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
60548
61050
|
const previousRecovery = recoveredInstructions.peek(draft.sessionID);
|
|
60549
61051
|
recoveredInstructions.delete(draft.sessionID);
|
|
60550
61052
|
const hiddenChild = hiddenChildHook.owns(draft.sessionID);
|
|
61053
|
+
if (!compactionOff && !hiddenChild && !rustModeModuleClient)
|
|
61054
|
+
httpRefusalCounts.release(draft.sessionID);
|
|
61055
|
+
const refusalPass = compactionOff || hiddenChild || rustModeModuleClient ? undefined : refusalCounts.begin(draft.sessionID, undefined, latestDraftAssistantID(draft.messages));
|
|
60551
61056
|
const anchor = compactionOff || hiddenChild ? undefined : generateReplayAnchor(draft.messages);
|
|
60552
61057
|
beginServedRequest(draft.sessionID);
|
|
60553
61058
|
let returned = false;
|
|
60554
61059
|
let outcome;
|
|
60555
61060
|
try {
|
|
60556
|
-
outcome = await runManagedContext(draft, pass, previousRecovery);
|
|
61061
|
+
outcome = refusalPass ? await withProviderRefusalPass(draft.sessionID, refusalPass, () => runManagedContext(draft, pass, previousRecovery, refusalPass)) : await runManagedContext(draft, pass, previousRecovery);
|
|
60557
61062
|
if (!pass.refused && pass.storageNoticeWake && draft.messages.at(-1)?.role === "assistant") {
|
|
60558
61063
|
await refuseBeforeProvider(context.session, draft.sessionID, "storage-notice-turn", "request ends with the previous reply");
|
|
60559
61064
|
}
|
|
@@ -60614,6 +61119,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
|
|
|
60614
61119
|
sessionLog2(draft.sessionID, "generate replay capture skipped: compaction-disabled");
|
|
60615
61120
|
else if (!pass.refused && outcome === "managed" && !hiddenChild && !deletedSessions.has(draft.sessionID))
|
|
60616
61121
|
generateReplay.capture(draft, anchor);
|
|
61122
|
+
if (refusalPass && !pass.refused && outcome === "managed" && draft.system.some((part) => part.text)) {
|
|
61123
|
+
const saved = { ...draft };
|
|
61124
|
+
refusalPass.freeze(`${saved.model.providerID}/${saved.model.id}`, () => estimateFrozenRequestInputTokens(checkpointRequestSizingInput(saved)));
|
|
61125
|
+
}
|
|
60617
61126
|
}));
|
|
60618
61127
|
await context.session.hook("generate", async (draft) => {
|
|
60619
61128
|
const managed = !compactionOff && !deletedSessions.has(draft.sessionID);
|