@cortexkit/opencode-magic-context 0.48.0 → 0.49.0
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 +3 -3
- package/dist/{conflict-warning-hook-w8cykrnf.js → conflict-warning-hook-kzx4dmk1.js} +7 -7
- package/dist/{context-m0cy262m.js → context-nj5f293n.js} +96 -43
- package/dist/{derive-budgets-sg0xsq7s.js → derive-budgets-qz5rrr08.js} +2 -2
- package/dist/embedding-backfill-aetxv1vt.js +21 -0
- package/dist/embedding-worker.js +4 -4
- package/dist/features/magic-context/git-commits/search-git-commits.d.ts +2 -0
- package/dist/features/magic-context/git-commits/search-git-commits.d.ts.map +1 -1
- package/dist/features/magic-context/message-index.d.ts.map +1 -1
- package/dist/features/magic-context/pi-content-decisions.d.ts +1 -1
- package/dist/features/magic-context/pi-content-decisions.d.ts.map +1 -1
- package/dist/features/magic-context/search-rerank.d.ts +35 -0
- package/dist/features/magic-context/search-rerank.d.ts.map +1 -0
- package/dist/features/magic-context/search.d.ts +11 -0
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +13 -2
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-session.d.ts +1 -1
- package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta.d.ts +1 -1
- package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
- package/dist/features/magic-context/storage-session-tables.d.ts +2 -0
- package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
- package/dist/features/magic-context/storage-tag-identity-revision.d.ts +29 -9
- package/dist/features/magic-context/storage-tag-identity-revision.d.ts.map +1 -1
- package/dist/features/magic-context/storage-tags.d.ts +9 -0
- package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
- package/dist/features/magic-context/storage.d.ts +1 -1
- package/dist/features/magic-context/storage.d.ts.map +1 -1
- package/dist/features/magic-context/tagger.d.ts +2 -0
- package/dist/features/magic-context/tagger.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts +3 -0
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-deadline.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-replay.fixture.d.ts +24 -0
- package/dist/hooks/magic-context/auto-search-replay.fixture.d.ts.map +1 -0
- package/dist/hooks/magic-context/auto-search-runner.d.ts +1 -1
- package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-worker-client.d.ts +2 -0
- package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
- package/dist/hooks/magic-context/command-handler.d.ts +2 -0
- package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/emergency-fail-closed.d.ts +28 -0
- package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-host-runner.d.ts +8 -0
- package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts +2 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +7 -0
- package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/pass-outcome.d.ts +1 -0
- package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-chunk.d.ts +7 -1
- package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-raw.d.ts +35 -0
- package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +36 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/shared-compartment-boundaries.d.ts +8 -1
- package/dist/hooks/magic-context/shared-compartment-boundaries.d.ts.map +1 -1
- package/dist/hooks/magic-context/strict-thinking-prefix.d.ts +8 -0
- package/dist/hooks/magic-context/strict-thinking-prefix.d.ts.map +1 -0
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +13 -0
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +1 -0
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-db7zwa3v.js → index-1bt88epp.js} +93 -9
- package/dist/{index-f0h6xwqm.js → index-1g30axtz.js} +229 -67
- package/dist/{index-k1xb52kd.js → index-1r0k9js3.js} +5 -5
- package/dist/{index-692jzy0p.js → index-2jcbj7r1.js} +122 -371
- package/dist/{index-bdckkfw6.js → index-2jgwttpt.js} +16 -8
- package/dist/{index-2y0s2hep.js → index-4mjhqadz.js} +1 -1
- package/dist/{index-pdecwzrd.js → index-57mrqed8.js} +1 -1
- package/dist/{index-ty64eqcn.js → index-9qjqq45k.js} +3 -3
- package/dist/{index-yq8n9qcb.js → index-9rt53q79.js} +4 -4
- package/dist/{index-pg50n748.js → index-b7mv1jx3.js} +4 -4
- package/dist/{index-mmyh6d8f.js → index-ezmszwbd.js} +6 -4
- package/dist/{index-fbv1dn35.js → index-gzcmtmar.js} +1 -1
- package/dist/{index-0an7742d.js → index-h2py7207.js} +549 -973
- package/dist/{index-0qhce371.js → index-h2wc01qk.js} +2 -2
- package/dist/{index-dhwzyd54.js → index-h5zfkjyk.js} +160 -25
- package/dist/{index-q2tqeqde.js → index-ha87j7a8.js} +1229 -78
- package/dist/{index-14cjxt20.js → index-hj2q50k0.js} +45 -8
- package/dist/{index-cb7emxgj.js → index-kmpvemph.js} +336 -6
- package/dist/{index-c43kr12f.js → index-kp5qe690.js} +7 -7
- package/dist/{index-bhvjj0ys.js → index-kq57tdf0.js} +2 -2
- package/dist/{index-7mx8v0pw.js → index-nm6a8xpd.js} +4 -4
- package/dist/{index-8j7gqj40.js → index-nsjyysj0.js} +6 -2
- package/dist/{index-k9nnwad5.js → index-nydv6g8r.js} +44 -7
- package/dist/{index-5zygecde.js → index-peshmj6h.js} +4 -4
- package/dist/{index-knh4y330.js → index-pxwp2hjk.js} +7 -2
- package/dist/{index-1qb0z7wa.js → index-qx53vezw.js} +1 -1
- package/dist/{index-q7h7csab.js → index-s4j7t92z.js} +9 -9
- package/dist/{index-z8e0psj8.js → index-stbr4ce6.js} +3 -3
- package/dist/{index-jcbd3znx.js → index-tqf7yg27.js} +1 -1
- package/dist/{index-72nhv486.js → index-vkbqdnkj.js} +2 -2
- package/dist/{index-eeezr5zz.js → index-z1tjp257.js} +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +61 -44
- package/dist/{logger-d3wex3dz.js → logger-ewak5q1s.js} +1 -1
- package/dist/{message-index-bounded-7ezbgddp.js → message-index-bounded-h0mrd4pr.js} +13 -13
- package/dist/{message-time-backfill-brbd63hv.js → message-time-backfill-8x06r9kx.js} +2 -2
- package/dist/migration-worker.js +9 -9
- package/dist/plugin/hooks/create-session-hooks.d.ts +2 -0
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/tool-registry.d.ts.map +1 -1
- package/dist/{project-embedding-registry-7qzptcw7.js → project-embedding-registry-rtt0djyb.js} +9 -9
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-6k83m4fj.js → read-session-chunk-ty89v75e.js} +10 -8
- package/dist/{read-session-raw-3g9qy1xa.js → read-session-raw-8sjbc9h0.js} +5 -3
- package/dist/{recomp-orchestrator-d3fp1cy0.js → recomp-orchestrator-4f1yyd1q.js} +25 -25
- package/dist/{safe-notification-target-5ffqq32m.js → safe-notification-target-q0cyrx3x.js} +2 -2
- package/dist/{search-epax1ecv.js → search-pz4f4wge.js} +20 -20
- package/dist/{send-session-notification-erecz4y4.js → send-session-notification-38cd5dqt.js} +5 -5
- package/dist/shared/auto-search-lifecycle.d.ts +14 -0
- package/dist/shared/auto-search-lifecycle.d.ts.map +1 -1
- package/dist/shared/logger.d.ts.map +1 -1
- package/dist/shared/models-dev-temperature.d.ts +18 -0
- package/dist/shared/models-dev-temperature.d.ts.map +1 -0
- package/dist/shared/project-directory-key.d.ts +16 -0
- package/dist/shared/project-directory-key.d.ts.map +1 -1
- package/dist/shared/subagent-temperature.d.ts +46 -0
- package/dist/shared/subagent-temperature.d.ts.map +1 -0
- package/dist/{storage-tags-d3b0v2ss.js → storage-tags-k0pda32s.js} +6 -4
- package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
- package/dist/tools/ctx-search/tools.d.ts.map +1 -1
- package/dist/tools/ctx-search/types.d.ts +1 -0
- package/dist/tools/ctx-search/types.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-spcy2qre.js → transform-postprocess-phase-tck4g20s.js} +25 -25
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/{context-sf98kstd.js → context-crbt6p1y.js} +809 -1052
- package/dist/v2/{derive-budgets-3vc0y84t.js → derive-budgets-fgej9j46.js} +3 -3
- package/dist/v2/embedding-backfill-ph1qfyn3.js +21 -0
- package/dist/v2/embedding-worker.js +4 -4
- package/dist/v2/hidden-child-native.d.ts.map +1 -1
- package/dist/v2/hidden-completion.d.ts +7 -0
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/dream-trigger.d.ts +4 -1
- package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
- package/dist/v2/hooks/generate.d.ts +9 -2
- package/dist/v2/hooks/generate.d.ts.map +1 -1
- package/dist/v2/{logger-mxd0ym09.js → logger-pj02s7sr.js} +1 -1
- package/dist/v2/{message-index-bounded-dy3s2k1e.js → message-index-bounded-xwqdywxg.js} +13 -13
- package/dist/v2/{message-time-backfill-gtx1pwk1.js → message-time-backfill-cje68egj.js} +2 -2
- package/dist/v2/migration-worker.js +9 -9
- package/dist/v2/{project-embedding-registry-1tgba5dv.js → project-embedding-registry-d6m7tyxr.js} +9 -9
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-rh4khdkv.js → read-session-chunk-8p5mdryx.js} +10 -8
- package/dist/v2/{read-session-raw-bsbmf0vj.js → read-session-raw-j8dvp7f4.js} +5 -3
- package/dist/v2/{recomp-orchestrator-az61rfcg.js → recomp-orchestrator-ckfgt6wq.js} +26 -26
- package/dist/v2/{safe-notification-target-73ax1p5v.js → safe-notification-target-y3p1hce9.js} +2 -2
- package/dist/v2/{search-nzkwrc6n.js → search-ym8rehhz.js} +20 -20
- package/dist/v2/{send-session-notification-6km439kn.js → send-session-notification-5m0yapqx.js} +5 -5
- package/dist/v2/{server-x2g40a71.js → server-19zjmn02.js} +2 -2
- package/dist/v2/{server-sggvvzhb.js → server-1tk82krw.js} +45 -8
- package/dist/v2/{server-vqpf3167.js → server-2s6ayq3t.js} +2 -2
- package/dist/v2/{server-z2037m6z.js → server-2s9qz6n7.js} +2 -2
- package/dist/v2/{server-k228xhjg.js → server-3j4d00kf.js} +1 -1
- package/dist/v2/{server-aan4q8mx.js → server-3t0q2cqx.js} +1 -1
- package/dist/v2/{server-2fbhp79z.js → server-4ez8mntn.js} +16 -8
- package/dist/v2/{server-zxhgvsf9.js → server-676xw7at.js} +1 -1
- package/dist/v2/{server-52awr2mw.js → server-6byqfbqf.js} +93 -9
- package/dist/v2/{server-qye6ykf7.js → server-7ekna9zs.js} +2 -2
- package/dist/v2/{server-g5r0n3b6.js → server-7h861yms.js} +160 -25
- package/dist/v2/{server-v06jcv0w.js → server-8k2agx29.js} +1 -1
- package/dist/v2/{server-686jg6eb.js → server-c5rrgrcd.js} +44 -7
- package/dist/v2/{server-4k748ke6.js → server-hb6xhh9q.js} +2 -2
- package/dist/v2/{server-7wwc2nga.js → server-jvxzm1jy.js} +7 -7
- package/dist/v2/{server-1r6pmz4f.js → server-kzns2hbz.js} +1 -1
- package/dist/v2/{server-xdfwt6kh.js → server-pj4pjv02.js} +2 -2
- package/dist/v2/{server-psqc7e9n.js → server-q4ph9bwn.js} +1227 -78
- package/dist/v2/{server-8pyt7hev.js → server-sa8jvrfc.js} +9 -9
- package/dist/v2/{server-ezhze64f.js → server-ss95ky04.js} +4 -4
- package/dist/v2/{server-5m3dt5r1.js → server-t4k4qexw.js} +6 -2
- package/dist/v2/{server-e0vdaae2.js → server-v4mewb78.js} +4 -4
- package/dist/v2/{server-gjcr4w98.js → server-w32kmdez.js} +4 -4
- package/dist/v2/{server-k8x2rbxc.js → server-x4hscabv.js} +119 -365
- package/dist/v2/{server-yczc713m.js → server-xwz4dqh9.js} +7 -2
- package/dist/v2/{server-xxm59eww.js → server-ycw9qqcy.js} +4 -4
- package/dist/v2/{server-8tqanswc.js → server-zp53y8js.js} +331 -4
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-w4tv77sn.js → storage-tags-8vw924zn.js} +6 -4
- package/dist/v2/store-reader.d.ts +8 -2
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{wrapup-orchestrator-mz7efs7w.js → wrapup-orchestrator-a7efxaax.js} +26 -26
- package/dist/wrapup-orchestrator-barbc6h9.js +44 -0
- package/package.json +1 -1
- package/src/shared/auto-search-lifecycle.ts +43 -0
- package/src/shared/logger.test.ts +38 -0
- package/src/shared/logger.ts +10 -2
- package/src/shared/models-dev-temperature.ts +107 -0
- package/src/shared/project-directory-key.test.ts +59 -0
- package/src/shared/project-directory-key.ts +20 -0
- package/src/shared/subagent-temperature.test.ts +270 -0
- package/src/shared/subagent-temperature.ts +110 -0
- package/dist/embedding-backfill-9rcm1mfy.js +0 -21
- package/dist/v2/embedding-backfill-vn8g1nh1.js +0 -21
- package/dist/wrapup-orchestrator-amzta1t4.js +0 -44
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
resolveLegacyConfigSources,
|
|
10
10
|
getProtectedTokensTierOverrides,
|
|
11
11
|
loadPluginConfigDetailed
|
|
12
|
-
} from "./server-
|
|
12
|
+
} from "./server-19zjmn02.js";
|
|
13
13
|
import {
|
|
14
14
|
getHarness2,
|
|
15
15
|
harnessOwnsOpenCodeStore2
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
log2,
|
|
25
25
|
sessionLog2,
|
|
26
26
|
getLoggerDiagnostics2
|
|
27
|
-
} from "./server-
|
|
27
|
+
} from "./server-t4k4qexw.js";
|
|
28
28
|
import {
|
|
29
29
|
hasTrustedAbsoluteWall,
|
|
30
30
|
applyProvenInputFloor,
|
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
getSdkContextLimit,
|
|
37
37
|
getSdkOutputLimit,
|
|
38
38
|
getModelsDevCacheState
|
|
39
|
-
} from "./server-
|
|
39
|
+
} from "./server-8k2agx29.js";
|
|
40
40
|
import {
|
|
41
41
|
withContentLanguageDirective,
|
|
42
42
|
parseCron,
|
|
@@ -117,7 +117,7 @@ import {
|
|
|
117
117
|
getAutoSearchHintDecisions,
|
|
118
118
|
appendAutoSearchHintDecision,
|
|
119
119
|
pruneNoteNudgeAnchors,
|
|
120
|
-
|
|
120
|
+
flushAutoSearchHintDecisionRetirement,
|
|
121
121
|
getPersistedTodoPermissionDenied,
|
|
122
122
|
setPersistedTodoPermissionDenied,
|
|
123
123
|
getPersistedTodoSyntheticAnchor,
|
|
@@ -193,6 +193,9 @@ import {
|
|
|
193
193
|
copySessionStateForClone,
|
|
194
194
|
queueMemoryMutation,
|
|
195
195
|
getMaxMemoryMutationIdForProjects,
|
|
196
|
+
rememberUnpublishedAutoSearchNoHint,
|
|
197
|
+
getUnpublishedAutoSearchNoHint,
|
|
198
|
+
forgetUnpublishedAutoSearchNoHint,
|
|
196
199
|
registerAutoSearchWork,
|
|
197
200
|
gaDatabasePath,
|
|
198
201
|
RAW_MESSAGE_TYPES,
|
|
@@ -214,13 +217,6 @@ import {
|
|
|
214
217
|
readCoordinateGeneration,
|
|
215
218
|
rebaseSessionCoordinatesAsync,
|
|
216
219
|
HiddenCompletionRefusal,
|
|
217
|
-
USER_FACING_FAILURES,
|
|
218
|
-
renderUserFacingFailure,
|
|
219
|
-
userFacingFailureCode,
|
|
220
|
-
renderCapabilityRefusal,
|
|
221
|
-
renderDreamFailure,
|
|
222
|
-
dreamFailureCode,
|
|
223
|
-
renderEmbeddingFailure,
|
|
224
220
|
getCompartmentEvents,
|
|
225
221
|
USER_MEMORY_CANDIDATE_TTL_MS,
|
|
226
222
|
insertUserMemoryCandidates,
|
|
@@ -332,7 +328,7 @@ import {
|
|
|
332
328
|
startCompartmentAgent,
|
|
333
329
|
setRecompStarting2,
|
|
334
330
|
setRecompTerminal2
|
|
335
|
-
} from "./server-
|
|
331
|
+
} from "./server-x4hscabv.js";
|
|
336
332
|
import {
|
|
337
333
|
CANONICAL_DREAM_TASKS,
|
|
338
334
|
DREAM_TASK_CAPABILITIES,
|
|
@@ -375,8 +371,9 @@ import {
|
|
|
375
371
|
openDatabaseAsync,
|
|
376
372
|
isDatabasePersisted,
|
|
377
373
|
getDatabasePersistenceError
|
|
378
|
-
} from "./server-
|
|
374
|
+
} from "./server-sa8jvrfc.js";
|
|
379
375
|
import {
|
|
376
|
+
sameProjectDirectory,
|
|
380
377
|
canonicalProjectDirectory,
|
|
381
378
|
setHomeProjectPermission,
|
|
382
379
|
shouldSkipHomeProjectMemory,
|
|
@@ -392,7 +389,7 @@ import {
|
|
|
392
389
|
storedPathBelongsToIdentity,
|
|
393
390
|
beginBootQuietPeriod,
|
|
394
391
|
scheduleAfterBootQuiet
|
|
395
|
-
} from "./server-
|
|
392
|
+
} from "./server-xwz4dqh9.js";
|
|
396
393
|
import {
|
|
397
394
|
detectLatestTurnThinkingMismatch,
|
|
398
395
|
isPrefixBoundThinkingModel,
|
|
@@ -449,11 +446,12 @@ import {
|
|
|
449
446
|
getRawSessionStoredMessageCount2,
|
|
450
447
|
readRawSessionMessageIdOrdinalsForRange2,
|
|
451
448
|
readRawSessionMessagePartsById2,
|
|
449
|
+
readRawSessionBoundaryEndpoints2,
|
|
452
450
|
readRawSessionMessageOrdinalById2,
|
|
453
451
|
readRawSessionMessageById2,
|
|
454
452
|
readSessionChunk2,
|
|
455
453
|
readRawSessionSeedTail2
|
|
456
|
-
} from "./server-
|
|
454
|
+
} from "./server-4ez8mntn.js";
|
|
457
455
|
import {
|
|
458
456
|
textMentionsRecentCommit,
|
|
459
457
|
hasMeaningfulUserText2,
|
|
@@ -464,21 +462,15 @@ import {
|
|
|
464
462
|
estimateTokens,
|
|
465
463
|
estimateFixedPromptTokens,
|
|
466
464
|
normalizeText
|
|
467
|
-
} from "./server-
|
|
465
|
+
} from "./server-kzns2hbz.js";
|
|
468
466
|
import {
|
|
469
|
-
Priority,
|
|
470
|
-
AdmissionClass,
|
|
471
|
-
SocketClosedError,
|
|
472
|
-
SocketTimeoutError,
|
|
473
|
-
StaleRouteHandleError,
|
|
474
467
|
SubcClient,
|
|
475
|
-
isConsumerReconnectTransient,
|
|
476
468
|
connectionFileExists,
|
|
477
469
|
SYNAPSE_DEFAULT_MODEL,
|
|
478
470
|
toSynapseLaneDescriptor,
|
|
479
471
|
formatSynapseLaneDescriptor,
|
|
480
472
|
SynapseEmbeddingProvider
|
|
481
|
-
} from "./server-
|
|
473
|
+
} from "./server-hb6xhh9q.js";
|
|
482
474
|
import {
|
|
483
475
|
getTagIdentityWriteGeneration2,
|
|
484
476
|
Database2,
|
|
@@ -492,10 +484,10 @@ import {
|
|
|
492
484
|
SqliteAcquisitionBusyError2,
|
|
493
485
|
withAsyncPrivilegedWriter2
|
|
494
486
|
} from "./server-kb9nn0a0.js";
|
|
495
|
-
import"./server-
|
|
487
|
+
import"./server-3j4d00kf.js";
|
|
496
488
|
import {
|
|
497
489
|
deleteChunkEmbedBackoffForSession
|
|
498
|
-
} from "./server-
|
|
490
|
+
} from "./server-ss95ky04.js";
|
|
499
491
|
import {
|
|
500
492
|
advanceSessionActivity,
|
|
501
493
|
backfillSessionActivity,
|
|
@@ -504,13 +496,14 @@ import {
|
|
|
504
496
|
isMessageIndexReconciledThrough,
|
|
505
497
|
indexMessagesAfterOrdinal,
|
|
506
498
|
sweepOrphanedOpenCodeMessageIndexes
|
|
507
|
-
} from "./server-
|
|
499
|
+
} from "./server-1tk82krw.js";
|
|
508
500
|
import {
|
|
509
501
|
stableStringify,
|
|
510
502
|
getTemporalDecisions,
|
|
511
503
|
observeTemporalDecisions,
|
|
512
|
-
freezeTemporalDecisions
|
|
513
|
-
|
|
504
|
+
freezeTemporalDecisions,
|
|
505
|
+
tagIdentityRevisionKey
|
|
506
|
+
} from "./server-6byqfbqf.js";
|
|
514
507
|
import {
|
|
515
508
|
resolveModelCalibration,
|
|
516
509
|
calibrateBuckets,
|
|
@@ -582,6 +575,7 @@ import {
|
|
|
582
575
|
updateTagStatus2,
|
|
583
576
|
markWhitespaceAssistantTagInert2,
|
|
584
577
|
getInertWhitespaceAssistantTags2,
|
|
578
|
+
getInertWhitespaceAssistantTagsByNumbers2,
|
|
585
579
|
updateTagDropMode2,
|
|
586
580
|
updateCavemanDepth2,
|
|
587
581
|
updateTagMessageId2,
|
|
@@ -603,13 +597,13 @@ import {
|
|
|
603
597
|
adoptNullOwnerToolTag2,
|
|
604
598
|
getCandidateToolOwners2,
|
|
605
599
|
pickNearestPriorOwner2
|
|
606
|
-
} from "./server-
|
|
600
|
+
} from "./server-c5rrgrcd.js";
|
|
607
601
|
import {
|
|
608
602
|
isRawCompactionSummaryInfo2,
|
|
609
603
|
extractInMemoryMessageViews2,
|
|
610
604
|
buildInMemoryTailRawMessages2,
|
|
611
605
|
runSessionWarmupWorker
|
|
612
|
-
} from "./server-
|
|
606
|
+
} from "./server-7h861yms.js";
|
|
613
607
|
import {
|
|
614
608
|
resolveOpenCodeDbPath,
|
|
615
609
|
assertOpenCodeStoreGeneration,
|
|
@@ -624,12 +618,12 @@ import {
|
|
|
624
618
|
latestPersistedMessageForRecovery,
|
|
625
619
|
getMessageTimesFromOpenCodeDb,
|
|
626
620
|
findLastAssistantModelFromOpenCodeDb
|
|
627
|
-
} from "./server-
|
|
621
|
+
} from "./server-pj4pjv02.js";
|
|
628
622
|
import {
|
|
629
623
|
getCurrentToolSetHash,
|
|
630
624
|
recordToolDefinition,
|
|
631
625
|
getMeasuredToolDefinitionTokens
|
|
632
|
-
} from "./server-
|
|
626
|
+
} from "./server-7ekna9zs.js";
|
|
633
627
|
import {
|
|
634
628
|
V2_MEMORY_CATEGORIES,
|
|
635
629
|
CATEGORY_PRIORITY
|
|
@@ -644,7 +638,7 @@ import {
|
|
|
644
638
|
resolveStoredPathWorkspaceIdentity,
|
|
645
639
|
storedPathBelongsToWorkspace,
|
|
646
640
|
computeWorkspaceEpochFingerprint
|
|
647
|
-
} from "./server-
|
|
641
|
+
} from "./server-v4mewb78.js";
|
|
648
642
|
import"./server-fb3zxn06.js";
|
|
649
643
|
import {
|
|
650
644
|
drainBackgroundBatches,
|
|
@@ -673,7 +667,7 @@ import {
|
|
|
673
667
|
drainCommitBacklogForProject2,
|
|
674
668
|
embedSessionCompartmentChunks2,
|
|
675
669
|
getEmbeddingCoverageStatus2
|
|
676
|
-
} from "./server-
|
|
670
|
+
} from "./server-jvxzm1jy.js";
|
|
677
671
|
import {
|
|
678
672
|
SESSION_NOTE_CONDITION_ERROR,
|
|
679
673
|
getNoteByIdInScope,
|
|
@@ -699,6 +693,12 @@ import {
|
|
|
699
693
|
createPrimer,
|
|
700
694
|
updatePrimerSupport,
|
|
701
695
|
updatePrimerAnswer,
|
|
696
|
+
renderUserFacingFailure,
|
|
697
|
+
userFacingFailureCode,
|
|
698
|
+
renderCapabilityRefusal,
|
|
699
|
+
renderDreamFailure,
|
|
700
|
+
dreamFailureCode,
|
|
701
|
+
renderEmbeddingFailure,
|
|
702
702
|
recordMemoryMapping,
|
|
703
703
|
recordMemoryVerifications,
|
|
704
704
|
getUnmappedMemoryIds,
|
|
@@ -710,14 +710,14 @@ import {
|
|
|
710
710
|
readGitFileChangeTimesSince,
|
|
711
711
|
verificationFileExists,
|
|
712
712
|
normalizeVerificationFiles
|
|
713
|
-
} from "./server-
|
|
713
|
+
} from "./server-zp53y8js.js";
|
|
714
714
|
import {
|
|
715
715
|
deriveTriggerBudget2,
|
|
716
716
|
deriveHistorianChunkTokens2,
|
|
717
717
|
resolveKnownHistorianContextLimit2,
|
|
718
718
|
resolveHistorianProducerLimits2,
|
|
719
719
|
resolveHistorianContextLimit2
|
|
720
|
-
} from "./server-
|
|
720
|
+
} from "./server-2s9qz6n7.js";
|
|
721
721
|
import {
|
|
722
722
|
isEmbeddingHostBusy2
|
|
723
723
|
} from "./server-qt1qqasc.js";
|
|
@@ -728,10 +728,10 @@ import {
|
|
|
728
728
|
} from "./server-4dhv7mqz.js";
|
|
729
729
|
import {
|
|
730
730
|
getLocalEmbeddingNativeMemoryStats
|
|
731
|
-
} from "./server-
|
|
731
|
+
} from "./server-2s6ayq3t.js";
|
|
732
732
|
import {
|
|
733
733
|
cosineSimilarity
|
|
734
|
-
} from "./server-
|
|
734
|
+
} from "./server-w32kmdez.js";
|
|
735
735
|
import {
|
|
736
736
|
computeCueContentHash,
|
|
737
737
|
hasMuralCueColumns,
|
|
@@ -764,12 +764,23 @@ import {
|
|
|
764
764
|
drainNotifications2,
|
|
765
765
|
isTuiConnected2
|
|
766
766
|
} from "./server-x8a7jmkh.js";
|
|
767
|
-
import"./server-
|
|
767
|
+
import"./server-676xw7at.js";
|
|
768
768
|
import {
|
|
769
769
|
flushIgnoredMessages2,
|
|
770
770
|
sendStatusNotification2
|
|
771
|
-
} from "./server-
|
|
771
|
+
} from "./server-ycw9qqcy.js";
|
|
772
772
|
import {
|
|
773
|
+
renderSingleStoreMigrationRequiredRefusal,
|
|
774
|
+
SingleStoreMigrationRequiredError,
|
|
775
|
+
singleStoreMigrationRequiredFailure,
|
|
776
|
+
projectNeedsSingleStoreMigration,
|
|
777
|
+
STORE_AHEAD_OF_BINARY_CODE,
|
|
778
|
+
storeAheadOfBinaryFailure,
|
|
779
|
+
TRANSFORM_PAGE_UPLOAD_TIMEOUT_MS,
|
|
780
|
+
transformColdStartExecuteTimeoutMs,
|
|
781
|
+
getDefaultSubcConnectionFile,
|
|
782
|
+
isModuleTransportGenerationChangedResult,
|
|
783
|
+
SubcModuleTransport,
|
|
773
784
|
indexCommitsForProject,
|
|
774
785
|
embedUnembeddedCommits,
|
|
775
786
|
createUnifiedSearchDiagnostics2,
|
|
@@ -777,7 +788,7 @@ import {
|
|
|
777
788
|
resolveMemoriesByIdsForSearch2,
|
|
778
789
|
unifiedSearch2,
|
|
779
790
|
formatSearchResults2
|
|
780
|
-
} from "./server-
|
|
791
|
+
} from "./server-q4ph9bwn.js";
|
|
781
792
|
import {
|
|
782
793
|
resolvePromptContext2
|
|
783
794
|
} from "./server-fmsr7v69.js";
|
|
@@ -813,7 +824,7 @@ import {
|
|
|
813
824
|
} from "./server-8ajstryz.js";
|
|
814
825
|
import {
|
|
815
826
|
logSlowWriteTransaction
|
|
816
|
-
} from "./server-
|
|
827
|
+
} from "./server-3t0q2cqx.js";
|
|
817
828
|
import {
|
|
818
829
|
__toESM,
|
|
819
830
|
__export
|
|
@@ -1329,7 +1340,7 @@ __export(exports_util, {
|
|
|
1329
1340
|
assignProp: () => assignProp,
|
|
1330
1341
|
base64ToUint8Array: () => base64ToUint8Array,
|
|
1331
1342
|
base64urlToUint8Array: () => base64urlToUint8Array,
|
|
1332
|
-
cached: () =>
|
|
1343
|
+
cached: () => cached2,
|
|
1333
1344
|
captureStackTrace: () => captureStackTrace,
|
|
1334
1345
|
cleanEnum: () => cleanEnum,
|
|
1335
1346
|
cleanRegex: () => cleanRegex,
|
|
@@ -1970,7 +1981,9 @@ function makeToolCompositeKey(ownerMsgId, callId) {
|
|
|
1970
1981
|
return `${ownerMsgId}${TOOL_COMPOSITE_KEY_SEP}${callId}`;
|
|
1971
1982
|
}
|
|
1972
1983
|
var GET_COUNTER_SQL = `SELECT counter FROM session_meta WHERE session_id = ?`;
|
|
1973
|
-
var GET_TAGS_VERSION_SQL = `SELECT
|
|
1984
|
+
var GET_TAGS_VERSION_SQL = `SELECT
|
|
1985
|
+
(SELECT tags_version FROM session_meta WHERE session_id = ?) AS tags_version,
|
|
1986
|
+
(SELECT value FROM schema_migrations_meta WHERE key = ?) AS identity_revision`;
|
|
1974
1987
|
var GET_ASSIGNMENTS_SQL = "SELECT message_id, tag_number, type, tool_owner_message_id, byte_size, token_count, input_byte_size, input_token_count FROM tags WHERE session_id = ? ORDER BY tag_number ASC";
|
|
1975
1988
|
var GET_ASSIGNMENTS_SCOPED_SQL = "SELECT message_id, tag_number, type, tool_owner_message_id, byte_size, token_count, input_byte_size, input_token_count FROM tags WHERE session_id = ? AND tag_number >= ? ORDER BY tag_number ASC";
|
|
1976
1989
|
var probeTagsVersionStatements = new WeakMap;
|
|
@@ -2091,10 +2104,16 @@ function createTagger() {
|
|
|
2091
2104
|
const memCounter = heapHolder.counters.get(sessionId) ?? 0;
|
|
2092
2105
|
const dbMax = getMaxTagNumberBySession2(db, sessionId);
|
|
2093
2106
|
const next = Math.max(memCounter, dbMax) + 1;
|
|
2107
|
+
const loaded = heapHolder.loadSignatures.get(sessionId);
|
|
2108
|
+
let ownedInitialIdentity;
|
|
2094
2109
|
try {
|
|
2095
2110
|
db.transaction(() => {
|
|
2111
|
+
const admitted = loaded?.db === db && loaded.identityRevision === null ? probeSignature(sessionId, db) : null;
|
|
2112
|
+
const initializesOwnedEpoch = admitted !== null && loaded !== undefined && admitted.identityRevision === null && admitted.tagsVersion === loaded.tagsVersion;
|
|
2096
2113
|
getUpsertCounterStatement(db).run(sessionId, next, getHarness2());
|
|
2097
2114
|
insertTag2(db, sessionId, messageId, type, byteSize, next, reasoningByteSize, toolName, inputByteSize, toolOwnerMessageId, entryFingerprint, tokenCounts);
|
|
2115
|
+
if (initializesOwnedEpoch)
|
|
2116
|
+
ownedInitialIdentity = probeSignature(sessionId, db).identityRevision;
|
|
2098
2117
|
}).immediate();
|
|
2099
2118
|
} catch (error) {
|
|
2100
2119
|
if (!isUniqueConstraintError(error)) {
|
|
@@ -2115,6 +2134,8 @@ function createTagger() {
|
|
|
2115
2134
|
const signature = heapHolder.loadSignatures.get(sessionId);
|
|
2116
2135
|
if (signature?.db === db) {
|
|
2117
2136
|
signature.tagsVersion += 1;
|
|
2137
|
+
if (signature === loaded && ownedInitialIdentity !== undefined)
|
|
2138
|
+
signature.identityRevision = ownedInitialIdentity;
|
|
2118
2139
|
}
|
|
2119
2140
|
if (type === "tool") {
|
|
2120
2141
|
getSessionToolAccounting(sessionId).set(next, {
|
|
@@ -2217,15 +2238,16 @@ function createTagger() {
|
|
|
2217
2238
|
return heapHolder.counters.get(sessionId) ?? 0;
|
|
2218
2239
|
}
|
|
2219
2240
|
function probeSignature(sessionId, db) {
|
|
2220
|
-
const row = getProbeTagsVersionStatement(db).get(sessionId);
|
|
2241
|
+
const row = getProbeTagsVersionStatement(db).get(sessionId, tagIdentityRevisionKey(sessionId));
|
|
2221
2242
|
return {
|
|
2222
|
-
tagsVersion: row?.tags_version ?? 0
|
|
2243
|
+
tagsVersion: row?.tags_version ?? 0,
|
|
2244
|
+
identityRevision: row?.identity_revision ?? null
|
|
2223
2245
|
};
|
|
2224
2246
|
}
|
|
2225
2247
|
function initFromDb(sessionId, db, floor = 0) {
|
|
2226
2248
|
const probe = probeSignature(sessionId, db);
|
|
2227
2249
|
const cached = heapHolder.loadSignatures.get(sessionId);
|
|
2228
|
-
if (cached !== undefined && cached.db === db && cached.tagsVersion === probe.tagsVersion && cached.floor === floor) {
|
|
2250
|
+
if (cached !== undefined && cached.db === db && cached.tagsVersion === probe.tagsVersion && cached.identityRevision === probe.identityRevision && cached.floor === floor) {
|
|
2229
2251
|
return;
|
|
2230
2252
|
}
|
|
2231
2253
|
const row = db.prepare(GET_COUNTER_SQL).get(sessionId);
|
|
@@ -2258,6 +2280,7 @@ function createTagger() {
|
|
|
2258
2280
|
heapHolder.loadSignatures.set(sessionId, {
|
|
2259
2281
|
db,
|
|
2260
2282
|
tagsVersion: probe.tagsVersion,
|
|
2283
|
+
identityRevision: probe.identityRevision,
|
|
2261
2284
|
floor
|
|
2262
2285
|
});
|
|
2263
2286
|
}
|
|
@@ -2265,6 +2288,10 @@ function createTagger() {
|
|
|
2265
2288
|
const signature = heapHolder.loadSignatures.get(sessionId);
|
|
2266
2289
|
return signature?.db === db ? signature.tagsVersion : undefined;
|
|
2267
2290
|
}
|
|
2291
|
+
function getLoadedTagIdentityRevision(sessionId, db) {
|
|
2292
|
+
const signature = heapHolder.loadSignatures.get(sessionId);
|
|
2293
|
+
return signature?.db === db ? signature.identityRevision : undefined;
|
|
2294
|
+
}
|
|
2268
2295
|
function cleanup(sessionId) {
|
|
2269
2296
|
heapHolder.counters.delete(sessionId);
|
|
2270
2297
|
heapHolder.assignments.delete(sessionId);
|
|
@@ -2307,6 +2334,7 @@ function createTagger() {
|
|
|
2307
2334
|
getCounter,
|
|
2308
2335
|
initFromDb,
|
|
2309
2336
|
getLoadedTagsVersion,
|
|
2337
|
+
getLoadedTagIdentityRevision,
|
|
2310
2338
|
cleanup,
|
|
2311
2339
|
getHeapStats
|
|
2312
2340
|
};
|
|
@@ -2619,11 +2647,15 @@ function degradedPassError(site, error) {
|
|
|
2619
2647
|
|
|
2620
2648
|
// src/hooks/magic-context/emergency-fail-closed.ts
|
|
2621
2649
|
var ENGINE_RECONNECTING_USER_MESSAGE = "Magic Context's engine is reconnecting. Send your message again in a few seconds.";
|
|
2650
|
+
var ENGINE_BUSY_USER_MESSAGE = "Magic Context is still applying the previous context update for this session. Send your message again in a moment.";
|
|
2622
2651
|
var PROTECTED_TOOL_RESULTS_OVER_LIMIT = "The tool results kept by protected_tools are larger than this model's context window, so this turn was not sent. Lower the protected_tools counts.";
|
|
2623
2652
|
var PROTECTED_TOOL_RESULTS_OVER_LIMIT_CODE = "protected_tool_results_over_limit";
|
|
2653
|
+
var SIGNED_TURN_OVER_LIMIT = "This turn's context is larger than the model's context window even after all of its thinking and reclaimable tool output were removed, so it was not sent. Send a new message or start a new session to continue.";
|
|
2654
|
+
var SIGNED_TURN_OVER_LIMIT_CODE = "signed_turn_over_limit";
|
|
2655
|
+
var SIGNED_THINKING_RESET_FENCE_FAILED = "Magic Context could not record a thinking reset for this session, so this turn was not sent. Send your message again.";
|
|
2624
2656
|
function contextRefusalError(message) {
|
|
2625
2657
|
return new EmergencyFailClosedError(message, {
|
|
2626
|
-
code: message === PROTECTED_TOOL_RESULTS_OVER_LIMIT ? PROTECTED_TOOL_RESULTS_OVER_LIMIT_CODE : undefined
|
|
2658
|
+
code: message === PROTECTED_TOOL_RESULTS_OVER_LIMIT ? PROTECTED_TOOL_RESULTS_OVER_LIMIT_CODE : message === SIGNED_TURN_OVER_LIMIT ? SIGNED_TURN_OVER_LIMIT_CODE : undefined
|
|
2627
2659
|
});
|
|
2628
2660
|
}
|
|
2629
2661
|
function protectedToolRefusal(error) {
|
|
@@ -2633,6 +2665,8 @@ function protectedToolRefusal(error) {
|
|
|
2633
2665
|
const current = error;
|
|
2634
2666
|
if (current.code === PROTECTED_TOOL_RESULTS_OVER_LIMIT_CODE)
|
|
2635
2667
|
return contextRefusalError(PROTECTED_TOOL_RESULTS_OVER_LIMIT);
|
|
2668
|
+
if (current.code === SIGNED_TURN_OVER_LIMIT_CODE)
|
|
2669
|
+
return contextRefusalError(SIGNED_TURN_OVER_LIMIT);
|
|
2636
2670
|
error = current.cause;
|
|
2637
2671
|
}
|
|
2638
2672
|
return;
|
|
@@ -2642,6 +2676,11 @@ function outgoingContextRefusal(estimate, limit, protectedToolTokens = 0) {
|
|
|
2642
2676
|
return;
|
|
2643
2677
|
return PROTECTED_TOOL_RESULTS_OVER_LIMIT;
|
|
2644
2678
|
}
|
|
2679
|
+
function signedTurnContextRefusal(estimate, limit) {
|
|
2680
|
+
if (estimate?.refusalGrade !== true || typeof estimate.refusalTokens !== "number" || !Number.isFinite(estimate.refusalTokens) || !limit || !Number.isFinite(limit) || limit <= 0 || estimate.refusalTokens <= limit)
|
|
2681
|
+
return;
|
|
2682
|
+
return SIGNED_TURN_OVER_LIMIT;
|
|
2683
|
+
}
|
|
2645
2684
|
|
|
2646
2685
|
class EmergencyFailClosedError extends Error {
|
|
2647
2686
|
code;
|
|
@@ -3025,6 +3064,8 @@ function persistAutoSearchSkip(db, sessionId, messageId, reason = "timeout") {
|
|
|
3025
3064
|
ok = outcome.ok && outcome.decision.decision === "no-hint";
|
|
3026
3065
|
} catch {}
|
|
3027
3066
|
assertTransformWrite2();
|
|
3067
|
+
if (!ok)
|
|
3068
|
+
rememberUnpublishedAutoSearchNoHint(sessionId, messageId, reason);
|
|
3028
3069
|
const persistence = Promise.resolve(ok);
|
|
3029
3070
|
messages.set(messageId, persistence);
|
|
3030
3071
|
return persistence;
|
|
@@ -3650,7 +3691,36 @@ function queueAutoSearchRegistration(db, projectPath, register) {
|
|
|
3650
3691
|
function persistAutoSearchDecision(db, sessionId, decision, startedAt) {
|
|
3651
3692
|
if (performance.now() - startedAt >= AUTO_SEARCH_TIMEOUT_MS)
|
|
3652
3693
|
return null;
|
|
3653
|
-
|
|
3694
|
+
let outcome;
|
|
3695
|
+
try {
|
|
3696
|
+
outcome = appendAutoSearchHintDecision(db, sessionId, decision);
|
|
3697
|
+
} catch (error) {
|
|
3698
|
+
assertTransformWrite2();
|
|
3699
|
+
rememberUnpublishedAutoSearchNoHint(sessionId, decision.messageId, decision.decision === "no-hint" ? decision.reason : "error");
|
|
3700
|
+
if (!isTransientSqliteError2(error))
|
|
3701
|
+
throw error;
|
|
3702
|
+
log2(`[auto-search] decision save hit a busy store for session ${sessionId}; serving without a hint and retrying the save on a later pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
3703
|
+
return { ok: false, kind: "storage-busy" };
|
|
3704
|
+
}
|
|
3705
|
+
if (!outcome.ok) {
|
|
3706
|
+
assertTransformWrite2();
|
|
3707
|
+
rememberUnpublishedAutoSearchNoHint(sessionId, decision.messageId, decision.decision === "no-hint" ? decision.reason : "error");
|
|
3708
|
+
} else if (outcome.decision.decision === "no-hint") {
|
|
3709
|
+
forgetUnpublishedAutoSearchNoHint(sessionId, decision.messageId);
|
|
3710
|
+
}
|
|
3711
|
+
return outcome;
|
|
3712
|
+
}
|
|
3713
|
+
function retryUnpublishedAutoSearchNoHint(db, sessionId, messageId, startedAt) {
|
|
3714
|
+
const reason = getUnpublishedAutoSearchNoHint(sessionId, messageId);
|
|
3715
|
+
if (reason === undefined)
|
|
3716
|
+
return false;
|
|
3717
|
+
try {
|
|
3718
|
+
persistAutoSearchDecision(db, sessionId, { messageId, decision: "no-hint", reason }, startedAt);
|
|
3719
|
+
} catch (error) {
|
|
3720
|
+
assertTransformWrite2();
|
|
3721
|
+
log2(`[auto-search] frozen omission save still failed for session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3722
|
+
}
|
|
3723
|
+
return true;
|
|
3654
3724
|
}
|
|
3655
3725
|
async function searchAutoHint(db, sessionId, projectPath, query, options, entry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./auto-search-worker.ts" : "./auto-search-worker.js", import.meta.url)) {
|
|
3656
3726
|
return executeAutoSearchWorker(db, sessionId, projectPath, query, options, entry, "search");
|
|
@@ -4038,6 +4108,9 @@ async function runAutoSearchHint(args) {
|
|
|
4038
4108
|
return coalesceAutoSearchTurn(db, sessionId, userMsgId, async (lifecycleSignal) => {
|
|
4039
4109
|
if (lifecycleSignal.aborted)
|
|
4040
4110
|
return AUTO_SEARCH_OK;
|
|
4111
|
+
if (retryUnpublishedAutoSearchNoHint(db, sessionId, userMsgId, startedAt)) {
|
|
4112
|
+
return AUTO_SEARCH_OK;
|
|
4113
|
+
}
|
|
4041
4114
|
if (wasAutoSearchSkipped(db, sessionId, userMsgId))
|
|
4042
4115
|
return AUTO_SEARCH_OK;
|
|
4043
4116
|
const existing = getAutoSearchHintDecisions(db, sessionId);
|
|
@@ -4068,7 +4141,10 @@ async function runAutoSearchHint(args) {
|
|
|
4068
4141
|
return { ok: false, kind: "timeout" };
|
|
4069
4142
|
}
|
|
4070
4143
|
if (!outcome.ok)
|
|
4071
|
-
return {
|
|
4144
|
+
return {
|
|
4145
|
+
ok: false,
|
|
4146
|
+
kind: outcome.kind === "storage-busy" ? "storage-busy" : "cas-exhaustion"
|
|
4147
|
+
};
|
|
4072
4148
|
if (outcome.kind === "already-present" && outcome.decision.decision === "hint") {
|
|
4073
4149
|
appendReminderToUserMessageById(messages, userMsgId, outcome.decision.text);
|
|
4074
4150
|
}
|
|
@@ -4112,8 +4188,11 @@ async function runAutoSearchHint(args) {
|
|
|
4112
4188
|
});
|
|
4113
4189
|
}, startedAt);
|
|
4114
4190
|
} catch (error) {
|
|
4115
|
-
|
|
4116
|
-
|
|
4191
|
+
if (lifecycleSignal.aborted)
|
|
4192
|
+
return AUTO_SEARCH_OK;
|
|
4193
|
+
log2(`[auto-search] unified search failed for session ${sessionId} (no-hint frozen for this turn): ${error instanceof Error ? error.message : String(error)}`);
|
|
4194
|
+
const outcome = await writeNoHintAndReconcile("error");
|
|
4195
|
+
return outcome.ok ? { ok: false, kind: "search-failure" } : outcome;
|
|
4117
4196
|
}
|
|
4118
4197
|
if (lifecycleSignal.aborted)
|
|
4119
4198
|
return AUTO_SEARCH_OK;
|
|
@@ -4148,6 +4227,8 @@ ${hintText}`;
|
|
|
4148
4227
|
return { ok: false, kind: "timeout" };
|
|
4149
4228
|
}
|
|
4150
4229
|
if (!outcome.ok) {
|
|
4230
|
+
if (outcome.kind === "storage-busy")
|
|
4231
|
+
return { ok: false, kind: "storage-busy" };
|
|
4151
4232
|
sessionLog2(sessionId, `auto-search: CAS exhausted for ${userMsgId}; skipping wire append`);
|
|
4152
4233
|
return { ok: false, kind: "cas-exhaustion" };
|
|
4153
4234
|
}
|
|
@@ -4161,6 +4242,8 @@ ${hintText}`;
|
|
|
4161
4242
|
queueAutoSearchBackfill(db, sessionId, options.projectPath, rawPrompt);
|
|
4162
4243
|
}
|
|
4163
4244
|
}, () => {
|
|
4245
|
+
if (getUnpublishedAutoSearchNoHint(sessionId, userMsgId) !== undefined)
|
|
4246
|
+
return;
|
|
4164
4247
|
if (wasAutoSearchSkipped(db, sessionId, userMsgId))
|
|
4165
4248
|
return;
|
|
4166
4249
|
const decision = getAutoSearchHintDecisions(db, sessionId).find((entry) => entry.messageId === userMsgId);
|
|
@@ -6355,765 +6438,6 @@ function captureOpencodeReasoningBudgetStatus(sessionId, messages, budget, prefi
|
|
|
6355
6438
|
// src/hooks/magic-context/maintenance-authority.ts
|
|
6356
6439
|
var RUST_PARTIAL_RECOMP_REFUSAL = renderCapabilityRefusal("partial_history");
|
|
6357
6440
|
|
|
6358
|
-
// src/hooks/magic-context/module-transport.ts
|
|
6359
|
-
import { realpathSync } from "node:fs";
|
|
6360
|
-
import { join } from "node:path";
|
|
6361
|
-
|
|
6362
|
-
// src/hooks/magic-context/reply-pages.ts
|
|
6363
|
-
import { createHash } from "node:crypto";
|
|
6364
|
-
var MAX_REPLY_BYTES = 128 * 1024 * 1024;
|
|
6365
|
-
var MAX_PAGE_BYTES = 512 * 1024;
|
|
6366
|
-
function fail() {
|
|
6367
|
-
throw Object.assign(new Error("Incomplete or invalid module reply; abandon this pass"), {
|
|
6368
|
-
code: "reply_page_invalid"
|
|
6369
|
-
});
|
|
6370
|
-
}
|
|
6371
|
-
async function assembleReplyPages(response, fetchPage) {
|
|
6372
|
-
if (!isRecord(response) || !("reply_page" in response))
|
|
6373
|
-
return response;
|
|
6374
|
-
const first = response.reply_page;
|
|
6375
|
-
if (!isRecord(first))
|
|
6376
|
-
fail();
|
|
6377
|
-
const { id, total, bytes } = first;
|
|
6378
|
-
if (typeof id !== "string" || !/^[a-f0-9]{64}$/.test(id) || typeof total !== "number" || !Number.isSafeInteger(total) || total < 2 || total > 4096 || typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes <= 0 || bytes > MAX_REPLY_BYTES)
|
|
6379
|
-
fail();
|
|
6380
|
-
const chunks = [];
|
|
6381
|
-
let received = 0;
|
|
6382
|
-
for (let index = 0;index < total; index += 1) {
|
|
6383
|
-
const envelope = index === 0 ? response : await fetchPage(id, index);
|
|
6384
|
-
if (!isRecord(envelope) || !isRecord(envelope.reply_page))
|
|
6385
|
-
fail();
|
|
6386
|
-
const page = envelope.reply_page;
|
|
6387
|
-
if (page.id !== id || page.index !== index || page.total !== total || page.bytes !== bytes || typeof page.data !== "string")
|
|
6388
|
-
fail();
|
|
6389
|
-
if (Buffer.byteLength(JSON.stringify(envelope)) > MAX_PAGE_BYTES)
|
|
6390
|
-
fail();
|
|
6391
|
-
const chunk = Buffer.from(page.data, "utf8");
|
|
6392
|
-
received += chunk.length;
|
|
6393
|
-
if (received > bytes)
|
|
6394
|
-
fail();
|
|
6395
|
-
chunks.push(chunk);
|
|
6396
|
-
}
|
|
6397
|
-
if (received !== bytes)
|
|
6398
|
-
fail();
|
|
6399
|
-
const rebuilt = Buffer.concat(chunks, received);
|
|
6400
|
-
if (createHash("sha256").update(rebuilt).digest("hex") !== id)
|
|
6401
|
-
fail();
|
|
6402
|
-
return JSON.parse(rebuilt.toString("utf8"));
|
|
6403
|
-
}
|
|
6404
|
-
|
|
6405
|
-
// src/hooks/magic-context/single-store-refusal.ts
|
|
6406
|
-
var SINGLE_STORE_MIGRATION_REQUIRED_CODE = "single_store_migration_required";
|
|
6407
|
-
function renderSingleStoreMigrationRequiredRefusal() {
|
|
6408
|
-
const failure = USER_FACING_FAILURES.single_store_migration_required;
|
|
6409
|
-
return `${failure.sentence} ${failure.action} (${failure.code})`;
|
|
6410
|
-
}
|
|
6411
|
-
|
|
6412
|
-
class SingleStoreMigrationRequiredError extends Error {
|
|
6413
|
-
code = SINGLE_STORE_MIGRATION_REQUIRED_CODE;
|
|
6414
|
-
constructor(options) {
|
|
6415
|
-
super(renderSingleStoreMigrationRequiredRefusal(), options);
|
|
6416
|
-
this.name = "SingleStoreMigrationRequiredError";
|
|
6417
|
-
}
|
|
6418
|
-
}
|
|
6419
|
-
function singleStoreMigrationRequiredFailure(error) {
|
|
6420
|
-
let current = error;
|
|
6421
|
-
const seen = new Set;
|
|
6422
|
-
while (current !== null && typeof current === "object" && !seen.has(current)) {
|
|
6423
|
-
seen.add(current);
|
|
6424
|
-
if (current instanceof SingleStoreMigrationRequiredError)
|
|
6425
|
-
return current;
|
|
6426
|
-
const frame = current;
|
|
6427
|
-
if (frame.code === SINGLE_STORE_MIGRATION_REQUIRED_CODE || frame.code === "single_store_state_split") {
|
|
6428
|
-
return new SingleStoreMigrationRequiredError({ cause: error });
|
|
6429
|
-
}
|
|
6430
|
-
current = frame.cause;
|
|
6431
|
-
}
|
|
6432
|
-
return null;
|
|
6433
|
-
}
|
|
6434
|
-
function projectNeedsSingleStoreMigration(db, projectPath) {
|
|
6435
|
-
const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'authority_managed'").get();
|
|
6436
|
-
return Boolean(table && db.prepare("SELECT 1 FROM authority_managed WHERE project_path = ?").get(projectPath));
|
|
6437
|
-
}
|
|
6438
|
-
|
|
6439
|
-
// src/hooks/magic-context/store-ahead-refusal.ts
|
|
6440
|
-
var STORE_AHEAD_OF_BINARY_CODE = "store_ahead_of_binary";
|
|
6441
|
-
function renderStoreAheadOfBinaryRefusal(versions) {
|
|
6442
|
-
const failure = USER_FACING_FAILURES.store_ahead_of_binary;
|
|
6443
|
-
const sentence = versions ? `Magic Context refused to start: its store (store.db) is at schema v${versions.dbVersion} but this ck-mc build only knows up to v${versions.binaryMax}.` : failure.sentence;
|
|
6444
|
-
return `${sentence} ${failure.action} (${failure.code})`;
|
|
6445
|
-
}
|
|
6446
|
-
|
|
6447
|
-
class StoreAheadOfBinaryError extends Error {
|
|
6448
|
-
code = STORE_AHEAD_OF_BINARY_CODE;
|
|
6449
|
-
versions;
|
|
6450
|
-
constructor(versions, options) {
|
|
6451
|
-
super(renderStoreAheadOfBinaryRefusal(versions), options);
|
|
6452
|
-
this.name = "StoreAheadOfBinaryError";
|
|
6453
|
-
this.versions = versions;
|
|
6454
|
-
}
|
|
6455
|
-
}
|
|
6456
|
-
function isRecord3(value) {
|
|
6457
|
-
return value !== null && typeof value === "object";
|
|
6458
|
-
}
|
|
6459
|
-
function nonNegativeInteger(value) {
|
|
6460
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
6461
|
-
}
|
|
6462
|
-
function versionsFromDetail(detail) {
|
|
6463
|
-
if (!isRecord3(detail))
|
|
6464
|
-
return null;
|
|
6465
|
-
const dbVersion = nonNegativeInteger(detail.db_version);
|
|
6466
|
-
const binaryMax = nonNegativeInteger(detail.binary_max);
|
|
6467
|
-
return dbVersion !== null && binaryMax !== null ? { dbVersion, binaryMax } : null;
|
|
6468
|
-
}
|
|
6469
|
-
function versionsFromMessage(message) {
|
|
6470
|
-
if (typeof message !== "string")
|
|
6471
|
-
return null;
|
|
6472
|
-
const match = /db_version=(\d+) binary_max=(\d+)/.exec(message) ?? /schema v(\d+) but this ck-mc build only knows up to v(\d+)/.exec(message);
|
|
6473
|
-
if (!match)
|
|
6474
|
-
return null;
|
|
6475
|
-
return { dbVersion: Number(match[1]), binaryMax: Number(match[2]) };
|
|
6476
|
-
}
|
|
6477
|
-
function storeAheadOfBinaryFailure(error) {
|
|
6478
|
-
let current = error;
|
|
6479
|
-
const seen = new Set;
|
|
6480
|
-
while (isRecord3(current) && !seen.has(current)) {
|
|
6481
|
-
seen.add(current);
|
|
6482
|
-
if (current instanceof StoreAheadOfBinaryError)
|
|
6483
|
-
return current;
|
|
6484
|
-
if (current.code === STORE_AHEAD_OF_BINARY_CODE) {
|
|
6485
|
-
const versions = versionsFromDetail(current.detail) ?? versionsFromMessage(current.message);
|
|
6486
|
-
return new StoreAheadOfBinaryError(versions, { cause: error });
|
|
6487
|
-
}
|
|
6488
|
-
current = current.cause;
|
|
6489
|
-
}
|
|
6490
|
-
return null;
|
|
6491
|
-
}
|
|
6492
|
-
|
|
6493
|
-
// src/hooks/magic-context/module-transport.ts
|
|
6494
|
-
var DEFAULT_MODULE_ID = "magic-context";
|
|
6495
|
-
var CONNECT_BACKOFF_INITIAL_MS = 1000;
|
|
6496
|
-
var CONNECT_BACKOFF_MAX_MS = 30000;
|
|
6497
|
-
var CONNECT_BACKOFF_WAIT_BUDGET_MS = 12000;
|
|
6498
|
-
var CONNECT_BACKOFF_WAIT_JITTER_MS = 100;
|
|
6499
|
-
var HANDSHAKE_TIMEOUT_MS = 2000;
|
|
6500
|
-
var MODULE_SEND_TIMEOUT_MS = 15000;
|
|
6501
|
-
var TRANSFORM_PAGE_UPLOAD_TIMEOUT_MS = 5000;
|
|
6502
|
-
var TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MS = 15000;
|
|
6503
|
-
var TRANSFORM_COLD_START_EXECUTE_TIMEOUT_PER_MESSAGE_MS = 2;
|
|
6504
|
-
var TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MAX_MS = 90000;
|
|
6505
|
-
function transformColdStartExecuteTimeoutMs(seedMessageCount) {
|
|
6506
|
-
const messages = Number.isSafeInteger(seedMessageCount) ? Math.max(0, seedMessageCount) : 0;
|
|
6507
|
-
return Math.min(TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MAX_MS, TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MS + messages * TRANSFORM_COLD_START_EXECUTE_TIMEOUT_PER_MESSAGE_MS);
|
|
6508
|
-
}
|
|
6509
|
-
var MAX_WRAPUP_REQUEST_BUDGET_MS = 3800000;
|
|
6510
|
-
var SERIAL_LANE_MAX_WAITERS = 16;
|
|
6511
|
-
var SERIAL_LANE_MAX_WAITERS_PER_SESSION = 8;
|
|
6512
|
-
var SERIAL_LANE_MIN_REMAINING_MS = 25;
|
|
6513
|
-
var CANONICAL_ROOT_CACHE_MAX_ENTRIES = 256;
|
|
6514
|
-
function getDefaultSubcConnectionFile() {
|
|
6515
|
-
return join(getDataDir(), "cortexkit", "run", "subc-connection.json");
|
|
6516
|
-
}
|
|
6517
|
-
function errorChainSome(error, predicate) {
|
|
6518
|
-
let current = error;
|
|
6519
|
-
const seen = new Set;
|
|
6520
|
-
while (isRecord(current) && !seen.has(current)) {
|
|
6521
|
-
seen.add(current);
|
|
6522
|
-
if (predicate(current))
|
|
6523
|
-
return true;
|
|
6524
|
-
current = current.cause;
|
|
6525
|
-
}
|
|
6526
|
-
return false;
|
|
6527
|
-
}
|
|
6528
|
-
function isStaleOrDeadRouteFailure(error) {
|
|
6529
|
-
return errorChainSome(error, (current) => {
|
|
6530
|
-
const code = typeof current.code === "string" ? current.code : "";
|
|
6531
|
-
const name = typeof current.name === "string" ? current.name : "";
|
|
6532
|
-
const message = typeof current.message === "string" ? current.message : "";
|
|
6533
|
-
return [
|
|
6534
|
-
"stale_route_handle",
|
|
6535
|
-
"route_closed",
|
|
6536
|
-
"unknown_channel",
|
|
6537
|
-
"unrecognized_channel",
|
|
6538
|
-
"route_gone"
|
|
6539
|
-
].includes(code) || name === "StaleRouteHandleError" || /route handle \(\d+,\s*\d+\) is not live on the current connection/i.test(message) || /\b(?:unknown|unrecognized) channel\b/i.test(message);
|
|
6540
|
-
});
|
|
6541
|
-
}
|
|
6542
|
-
function isDeadlineFailure(error) {
|
|
6543
|
-
if (error instanceof SocketTimeoutError)
|
|
6544
|
-
return true;
|
|
6545
|
-
return errorChainSome(error, (current) => {
|
|
6546
|
-
const code = typeof current.code === "string" ? current.code : "";
|
|
6547
|
-
return ["ETIMEDOUT", "request_deadline", "deadline_exceeded_no_drop_observed"].includes(code);
|
|
6548
|
-
});
|
|
6549
|
-
}
|
|
6550
|
-
function isConnectionFailure(error) {
|
|
6551
|
-
if (error instanceof SocketClosedError || error instanceof SocketTimeoutError || error instanceof StaleRouteHandleError || isConsumerReconnectTransient(error) || isStaleOrDeadRouteFailure(error)) {
|
|
6552
|
-
return true;
|
|
6553
|
-
}
|
|
6554
|
-
return errorChainSome(error, (current) => {
|
|
6555
|
-
const code = typeof current.code === "string" ? current.code : "";
|
|
6556
|
-
const message = typeof current.message === "string" ? current.message : "";
|
|
6557
|
-
return [
|
|
6558
|
-
"ENOENT",
|
|
6559
|
-
"ECONNREFUSED",
|
|
6560
|
-
"ECONNRESET",
|
|
6561
|
-
"EPIPE",
|
|
6562
|
-
"ETIMEDOUT",
|
|
6563
|
-
"request_deadline",
|
|
6564
|
-
"deadline_exceeded_no_drop_observed",
|
|
6565
|
-
"connection_dropped",
|
|
6566
|
-
"SUBC_CONNECTION_BACKOFF"
|
|
6567
|
-
].includes(code) || /\bclient closed\b|\bconnection closed\b|\bclosed the connection\b/i.test(message);
|
|
6568
|
-
});
|
|
6569
|
-
}
|
|
6570
|
-
function routeOpenWithoutAmbientConsumerIdentity(client, target, identity, options = {}) {
|
|
6571
|
-
return client.routeOpen(target, identity, {
|
|
6572
|
-
...options,
|
|
6573
|
-
consumerIdentity: null
|
|
6574
|
-
});
|
|
6575
|
-
}
|
|
6576
|
-
function isModuleTransportGenerationChangedResult(value) {
|
|
6577
|
-
return isRecord(value) && value.transport_status === "connection_generation_changed" && typeof value.previous_generation === "number" && typeof value.current_generation === "number";
|
|
6578
|
-
}
|
|
6579
|
-
function moduleRequestBody(body, method) {
|
|
6580
|
-
if (!isRecord(body))
|
|
6581
|
-
return body;
|
|
6582
|
-
const facade = typeof body.name === "string" && isRecord(body.arguments);
|
|
6583
|
-
return { ...body, ...facade ? {} : { method }, accept_reply_pages: true };
|
|
6584
|
-
}
|
|
6585
|
-
|
|
6586
|
-
class SubcModuleTransport {
|
|
6587
|
-
connectionFile;
|
|
6588
|
-
moduleId;
|
|
6589
|
-
requestTimeoutMs;
|
|
6590
|
-
routeSessionPrefix;
|
|
6591
|
-
client = null;
|
|
6592
|
-
routes = new Map;
|
|
6593
|
-
routeOpenings = new Map;
|
|
6594
|
-
canonicalRootCache = new Map;
|
|
6595
|
-
sessionLanes = new Map;
|
|
6596
|
-
queuedLaneWaiters = 0;
|
|
6597
|
-
wrapupSessions = new Map;
|
|
6598
|
-
nextProbeMs = 0;
|
|
6599
|
-
connectionPromise = null;
|
|
6600
|
-
backoffMs = CONNECT_BACKOFF_INITIAL_MS;
|
|
6601
|
-
connectionGeneration = 0;
|
|
6602
|
-
stateSyncCapabilityCache = null;
|
|
6603
|
-
getCachedStateSyncCapabilities() {
|
|
6604
|
-
const cached = this.stateSyncCapabilityCache;
|
|
6605
|
-
if (!cached || cached.generation !== this.connectionGeneration)
|
|
6606
|
-
return;
|
|
6607
|
-
return cached.capabilities;
|
|
6608
|
-
}
|
|
6609
|
-
invalidateStateSyncCapabilities() {
|
|
6610
|
-
this.stateSyncCapabilityCache = null;
|
|
6611
|
-
}
|
|
6612
|
-
async stateSyncCapabilities(args) {
|
|
6613
|
-
const cached = this.getCachedStateSyncCapabilities();
|
|
6614
|
-
if (cached)
|
|
6615
|
-
return cached;
|
|
6616
|
-
const response = await this.call({
|
|
6617
|
-
sessionId: args.sessionId,
|
|
6618
|
-
projectRoot: args.projectRoot,
|
|
6619
|
-
method: "session.status",
|
|
6620
|
-
body: { method: "session.status", v: 1, session_id: args.sessionId }
|
|
6621
|
-
});
|
|
6622
|
-
const raw = isRecord(response) ? response : {};
|
|
6623
|
-
const value = isRecord(raw.result) ? raw.result : raw;
|
|
6624
|
-
const epochs = isRecord(value.epochs) ? value.epochs : {};
|
|
6625
|
-
const capabilities = {
|
|
6626
|
-
state_sync_deltas: epochs.state_sync_deltas === true,
|
|
6627
|
-
...epochs.state_sync_resume === true ? { state_sync_resume: true } : {}
|
|
6628
|
-
};
|
|
6629
|
-
this.stateSyncCapabilityCache = { generation: this.connectionGeneration, capabilities };
|
|
6630
|
-
return capabilities;
|
|
6631
|
-
}
|
|
6632
|
-
constructor(connectionFile, moduleId = DEFAULT_MODULE_ID, requestTimeoutMs = MODULE_SEND_TIMEOUT_MS, routeSessionPrefix = "") {
|
|
6633
|
-
this.connectionFile = connectionFile;
|
|
6634
|
-
this.moduleId = moduleId;
|
|
6635
|
-
this.requestTimeoutMs = requestTimeoutMs;
|
|
6636
|
-
this.routeSessionPrefix = routeSessionPrefix;
|
|
6637
|
-
}
|
|
6638
|
-
deadlineError(detail) {
|
|
6639
|
-
const error = new Error(`module transport deadline expired ${detail}`);
|
|
6640
|
-
error.code = "ETIMEDOUT";
|
|
6641
|
-
return error;
|
|
6642
|
-
}
|
|
6643
|
-
laneTimeoutError() {
|
|
6644
|
-
return this.deadlineError("while queued");
|
|
6645
|
-
}
|
|
6646
|
-
connectionChangedError(detail) {
|
|
6647
|
-
const error = new Error(detail);
|
|
6648
|
-
error.code = "ECONNRESET";
|
|
6649
|
-
return error;
|
|
6650
|
-
}
|
|
6651
|
-
async beforeDeadline(operation, deadlineMs, detail) {
|
|
6652
|
-
operation.catch(() => {});
|
|
6653
|
-
const remainingMs = deadlineMs - Date.now();
|
|
6654
|
-
if (remainingMs <= 0)
|
|
6655
|
-
throw this.deadlineError(detail);
|
|
6656
|
-
let timer;
|
|
6657
|
-
try {
|
|
6658
|
-
return await Promise.race([
|
|
6659
|
-
operation,
|
|
6660
|
-
new Promise((_resolve, reject) => {
|
|
6661
|
-
timer = setTimeout(() => reject(this.deadlineError(detail)), remainingMs);
|
|
6662
|
-
})
|
|
6663
|
-
]);
|
|
6664
|
-
} finally {
|
|
6665
|
-
if (timer)
|
|
6666
|
-
clearTimeout(timer);
|
|
6667
|
-
}
|
|
6668
|
-
}
|
|
6669
|
-
cleanupLane(sessionId, lane) {
|
|
6670
|
-
if (!lane.active && lane.waiters.length === 0 && this.sessionLanes.get(sessionId) === lane) {
|
|
6671
|
-
this.sessionLanes.delete(sessionId);
|
|
6672
|
-
}
|
|
6673
|
-
}
|
|
6674
|
-
laneRelease(sessionId, lane) {
|
|
6675
|
-
let released = false;
|
|
6676
|
-
return () => {
|
|
6677
|
-
if (released)
|
|
6678
|
-
return;
|
|
6679
|
-
released = true;
|
|
6680
|
-
lane.active = false;
|
|
6681
|
-
this.dispatchNextLaneWaiter(sessionId, lane);
|
|
6682
|
-
};
|
|
6683
|
-
}
|
|
6684
|
-
dispatchNextLaneWaiter(sessionId, lane) {
|
|
6685
|
-
if (lane.active)
|
|
6686
|
-
return;
|
|
6687
|
-
while (lane.waiters.length > 0) {
|
|
6688
|
-
const waiter = lane.waiters.shift();
|
|
6689
|
-
if (!waiter)
|
|
6690
|
-
continue;
|
|
6691
|
-
this.queuedLaneWaiters = Math.max(0, this.queuedLaneWaiters - 1);
|
|
6692
|
-
if (waiter.settled)
|
|
6693
|
-
continue;
|
|
6694
|
-
waiter.settled = true;
|
|
6695
|
-
clearTimeout(waiter.timer);
|
|
6696
|
-
waiter.signal?.removeEventListener("abort", waiter.onAbort);
|
|
6697
|
-
if (waiter.signal?.aborted) {
|
|
6698
|
-
waiter.reject(waiter.signal.reason ?? new Error("module transport call aborted"));
|
|
6699
|
-
continue;
|
|
6700
|
-
}
|
|
6701
|
-
if (waiter.deadlineMs - Date.now() < SERIAL_LANE_MIN_REMAINING_MS) {
|
|
6702
|
-
waiter.reject(this.laneTimeoutError());
|
|
6703
|
-
continue;
|
|
6704
|
-
}
|
|
6705
|
-
lane.active = true;
|
|
6706
|
-
waiter.resolve(this.laneRelease(sessionId, lane));
|
|
6707
|
-
return;
|
|
6708
|
-
}
|
|
6709
|
-
this.cleanupLane(sessionId, lane);
|
|
6710
|
-
}
|
|
6711
|
-
queueFullError() {
|
|
6712
|
-
const error = new Error("module transport queue is full");
|
|
6713
|
-
error.code = "EBUSY";
|
|
6714
|
-
return error;
|
|
6715
|
-
}
|
|
6716
|
-
acquireCorrectnessLane(sessionId, signal, deadlineMs) {
|
|
6717
|
-
if (signal?.aborted) {
|
|
6718
|
-
return Promise.reject(signal.reason ?? new Error("module transport call aborted"));
|
|
6719
|
-
}
|
|
6720
|
-
if (deadlineMs - Date.now() < SERIAL_LANE_MIN_REMAINING_MS) {
|
|
6721
|
-
return Promise.reject(this.laneTimeoutError());
|
|
6722
|
-
}
|
|
6723
|
-
const lane = this.sessionLanes.get(sessionId) ?? { active: false, waiters: [] };
|
|
6724
|
-
this.sessionLanes.set(sessionId, lane);
|
|
6725
|
-
if (!lane.active && lane.waiters.length === 0) {
|
|
6726
|
-
lane.active = true;
|
|
6727
|
-
return Promise.resolve(this.laneRelease(sessionId, lane));
|
|
6728
|
-
}
|
|
6729
|
-
if (this.queuedLaneWaiters >= SERIAL_LANE_MAX_WAITERS || lane.waiters.length >= SERIAL_LANE_MAX_WAITERS_PER_SESSION) {
|
|
6730
|
-
return Promise.reject(this.queueFullError());
|
|
6731
|
-
}
|
|
6732
|
-
return new Promise((resolve, reject) => {
|
|
6733
|
-
const waiter = {};
|
|
6734
|
-
const removeAndReject = (error) => {
|
|
6735
|
-
if (waiter.settled)
|
|
6736
|
-
return;
|
|
6737
|
-
waiter.settled = true;
|
|
6738
|
-
clearTimeout(waiter.timer);
|
|
6739
|
-
signal?.removeEventListener("abort", waiter.onAbort);
|
|
6740
|
-
const index = lane.waiters.indexOf(waiter);
|
|
6741
|
-
if (index >= 0) {
|
|
6742
|
-
lane.waiters.splice(index, 1);
|
|
6743
|
-
this.queuedLaneWaiters = Math.max(0, this.queuedLaneWaiters - 1);
|
|
6744
|
-
}
|
|
6745
|
-
reject(error);
|
|
6746
|
-
this.cleanupLane(sessionId, lane);
|
|
6747
|
-
};
|
|
6748
|
-
waiter.signal = signal;
|
|
6749
|
-
waiter.deadlineMs = deadlineMs;
|
|
6750
|
-
waiter.resolve = resolve;
|
|
6751
|
-
waiter.reject = reject;
|
|
6752
|
-
waiter.settled = false;
|
|
6753
|
-
waiter.onAbort = () => removeAndReject(signal?.reason ?? new Error("module transport call aborted"));
|
|
6754
|
-
waiter.timer = setTimeout(() => removeAndReject(this.laneTimeoutError()), Math.max(0, deadlineMs - Date.now()));
|
|
6755
|
-
signal?.addEventListener("abort", waiter.onAbort, { once: true });
|
|
6756
|
-
lane.waiters.push(waiter);
|
|
6757
|
-
this.queuedLaneWaiters += 1;
|
|
6758
|
-
});
|
|
6759
|
-
}
|
|
6760
|
-
async call(args) {
|
|
6761
|
-
const callStartedAt = performance.now();
|
|
6762
|
-
const timings = {
|
|
6763
|
-
lane: 0,
|
|
6764
|
-
route: 0,
|
|
6765
|
-
encode: 0,
|
|
6766
|
-
issue: 0,
|
|
6767
|
-
responseWait: 0,
|
|
6768
|
-
settle: 0
|
|
6769
|
-
};
|
|
6770
|
-
const wrapupInFlight = (this.wrapupSessions.get(args.sessionId) ?? 0) > 0;
|
|
6771
|
-
const attemptTimeoutMs = args.timeoutMs ?? (args.method === "session.wrapup" || args.method === "session.status" && wrapupInFlight ? MAX_WRAPUP_REQUEST_BUDGET_MS : args.attemptClass === "transform_series_execute" ? TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MS : args.method === "transform" ? Math.min(this.requestTimeoutMs, TRANSFORM_PAGE_UPLOAD_TIMEOUT_MS) : this.requestTimeoutMs);
|
|
6772
|
-
const tracksWrapup = args.method === "session.wrapup";
|
|
6773
|
-
if (tracksWrapup) {
|
|
6774
|
-
this.wrapupSessions.set(args.sessionId, (this.wrapupSessions.get(args.sessionId) ?? 0) + 1);
|
|
6775
|
-
}
|
|
6776
|
-
const finishWrapupTracking = () => {
|
|
6777
|
-
if (!tracksWrapup)
|
|
6778
|
-
return;
|
|
6779
|
-
const remaining = (this.wrapupSessions.get(args.sessionId) ?? 1) - 1;
|
|
6780
|
-
if (remaining > 0)
|
|
6781
|
-
this.wrapupSessions.set(args.sessionId, remaining);
|
|
6782
|
-
else
|
|
6783
|
-
this.wrapupSessions.delete(args.sessionId);
|
|
6784
|
-
};
|
|
6785
|
-
const laneDeadlineMs = Date.now() + attemptTimeoutMs;
|
|
6786
|
-
let releaseLane = () => {};
|
|
6787
|
-
try {
|
|
6788
|
-
const outsideSessionOrder = args.method.startsWith("historian.");
|
|
6789
|
-
if (!args.bypassSessionLane && !outsideSessionOrder) {
|
|
6790
|
-
releaseLane = await this.acquireCorrectnessLane(args.sessionId, args.signal, laneDeadlineMs);
|
|
6791
|
-
}
|
|
6792
|
-
} catch (error) {
|
|
6793
|
-
finishWrapupTracking();
|
|
6794
|
-
if (args.method === "state_sync" && isDeadlineFailure(error)) {
|
|
6795
|
-
const body = isRecord(args.body) ? args.body : {};
|
|
6796
|
-
throw Object.assign(new Error(`state_sync timeout stage=correctness_lane page=${body.seed_batch_index ?? 0}/${body.seed_batch_total ?? 1} series=${body.seed_id ?? "delta"} budget_ms=${attemptTimeoutMs}`), {
|
|
6797
|
-
code: "state_sync_timeout",
|
|
6798
|
-
stage: "correctness_lane",
|
|
6799
|
-
page: body.seed_batch_index ?? 0,
|
|
6800
|
-
pages: body.seed_batch_total ?? 1,
|
|
6801
|
-
series: body.seed_id ?? null,
|
|
6802
|
-
cause: error
|
|
6803
|
-
});
|
|
6804
|
-
}
|
|
6805
|
-
throw error;
|
|
6806
|
-
}
|
|
6807
|
-
timings.lane = performance.now() - callStartedAt;
|
|
6808
|
-
let rejectAbort;
|
|
6809
|
-
const aborted = new Promise((_resolve, reject) => {
|
|
6810
|
-
rejectAbort = reject;
|
|
6811
|
-
});
|
|
6812
|
-
aborted.catch(() => {});
|
|
6813
|
-
const onAbort = () => rejectAbort(args.signal?.reason ?? new Error("module transport call aborted"));
|
|
6814
|
-
args.signal?.addEventListener("abort", onAbort, { once: true });
|
|
6815
|
-
try {
|
|
6816
|
-
for (let attempt = 0;attempt < 2; attempt += 1) {
|
|
6817
|
-
let ensuredRoute = null;
|
|
6818
|
-
let initialResponseReceived = false;
|
|
6819
|
-
try {
|
|
6820
|
-
if (args.signal?.aborted) {
|
|
6821
|
-
throw args.signal.reason ?? new Error("module transport call aborted");
|
|
6822
|
-
}
|
|
6823
|
-
const attemptDeadlineMs = Date.now() + attemptTimeoutMs;
|
|
6824
|
-
const routeStartedAt = performance.now();
|
|
6825
|
-
ensuredRoute = await this.ensureRoute(args.sessionId, args.projectRoot, attemptDeadlineMs, args.signal);
|
|
6826
|
-
if (args.signal?.aborted) {
|
|
6827
|
-
throw args.signal.reason ?? new Error("module transport call aborted");
|
|
6828
|
-
}
|
|
6829
|
-
timings.route += performance.now() - routeStartedAt;
|
|
6830
|
-
const encodeStartedAt = performance.now();
|
|
6831
|
-
const body = args.body instanceof Uint8Array ? args.body : Buffer.from(JSON.stringify(moduleRequestBody(args.body, args.method)));
|
|
6832
|
-
timings.encode += performance.now() - encodeStartedAt;
|
|
6833
|
-
const issueStartedAt = performance.now();
|
|
6834
|
-
const request = ensuredRoute.client.request(ensuredRoute.route, body, {
|
|
6835
|
-
priority: Priority.Background,
|
|
6836
|
-
admissionClass: AdmissionClass.Normal,
|
|
6837
|
-
timeoutMs: Math.max(1, attemptDeadlineMs - Date.now())
|
|
6838
|
-
});
|
|
6839
|
-
timings.issue += performance.now() - issueStartedAt;
|
|
6840
|
-
const waitStartedAt = performance.now();
|
|
6841
|
-
const response = await this.beforeDeadline(Promise.race([request, aborted]), attemptDeadlineMs, "waiting for the module response");
|
|
6842
|
-
timings.responseWait += performance.now() - waitStartedAt;
|
|
6843
|
-
initialResponseReceived = true;
|
|
6844
|
-
if (this.client !== ensuredRoute.client || this.connectionGeneration !== ensuredRoute.generation) {
|
|
6845
|
-
throw this.connectionChangedError("subc connection changed while awaiting the module response");
|
|
6846
|
-
}
|
|
6847
|
-
const pageRoute = ensuredRoute;
|
|
6848
|
-
const assembled = await assembleReplyPages(response, async (id, index) => {
|
|
6849
|
-
if (args.signal?.aborted)
|
|
6850
|
-
throw args.signal.reason;
|
|
6851
|
-
const page = await this.beforeDeadline(Promise.race([
|
|
6852
|
-
pageRoute.client.request(pageRoute.route, Buffer.from(JSON.stringify({
|
|
6853
|
-
method: "reply.page",
|
|
6854
|
-
reply_page_id: id,
|
|
6855
|
-
reply_page_index: index
|
|
6856
|
-
})), {
|
|
6857
|
-
priority: Priority.Background,
|
|
6858
|
-
admissionClass: AdmissionClass.Normal,
|
|
6859
|
-
timeoutMs: Math.max(1, attemptDeadlineMs - Date.now())
|
|
6860
|
-
}),
|
|
6861
|
-
aborted
|
|
6862
|
-
]), attemptDeadlineMs, "waiting for a module reply page");
|
|
6863
|
-
if (this.client !== pageRoute.client || this.connectionGeneration !== pageRoute.generation) {
|
|
6864
|
-
throw this.connectionChangedError("subc connection changed during reply paging");
|
|
6865
|
-
}
|
|
6866
|
-
return page;
|
|
6867
|
-
});
|
|
6868
|
-
return assembled;
|
|
6869
|
-
} catch (error) {
|
|
6870
|
-
if (args.signal?.aborted)
|
|
6871
|
-
throw args.signal.reason ?? error;
|
|
6872
|
-
const migration = singleStoreMigrationRequiredFailure(error);
|
|
6873
|
-
if (migration)
|
|
6874
|
-
throw migration;
|
|
6875
|
-
const storeAhead = storeAheadOfBinaryFailure(error);
|
|
6876
|
-
if (storeAhead)
|
|
6877
|
-
throw storeAhead;
|
|
6878
|
-
if (args.method === "state_sync" && isDeadlineFailure(error)) {
|
|
6879
|
-
const body = isRecord(args.body) ? args.body : {};
|
|
6880
|
-
throw Object.assign(new Error(`state_sync timeout stage=module_ack page=${body.seed_batch_index ?? 0}/${body.seed_batch_total ?? 1} series=${body.seed_id ?? "delta"} budget_ms=${attemptTimeoutMs}`), {
|
|
6881
|
-
code: "state_sync_timeout",
|
|
6882
|
-
stage: "module_ack",
|
|
6883
|
-
page: body.seed_batch_index ?? 0,
|
|
6884
|
-
pages: body.seed_batch_total ?? 1,
|
|
6885
|
-
series: body.seed_id ?? null,
|
|
6886
|
-
cause: error
|
|
6887
|
-
});
|
|
6888
|
-
}
|
|
6889
|
-
if (args.attemptClass === "transform_series_execute" && isDeadlineFailure(error)) {
|
|
6890
|
-
throw error;
|
|
6891
|
-
}
|
|
6892
|
-
if (isConnectionFailure(error)) {
|
|
6893
|
-
const previousGeneration = ensuredRoute?.generation ?? this.connectionGeneration;
|
|
6894
|
-
if (ensuredRoute) {
|
|
6895
|
-
this.dropRoute(ensuredRoute.routeKey, ensuredRoute.route);
|
|
6896
|
-
this.invalidateConnection(ensuredRoute.client);
|
|
6897
|
-
} else {
|
|
6898
|
-
this.invalidateConnection();
|
|
6899
|
-
}
|
|
6900
|
-
const locallyUnsent = isRecord(error) && error.name === "StaleRouteHandleError" && error.code === "stale_route_handle";
|
|
6901
|
-
if (attempt === 0 && ensuredRoute && !initialResponseReceived && locallyUnsent && !args.generationSensitive) {
|
|
6902
|
-
continue;
|
|
6903
|
-
}
|
|
6904
|
-
if (args.method === "transform") {
|
|
6905
|
-
if (!ensuredRoute)
|
|
6906
|
-
throw error;
|
|
6907
|
-
throw Object.assign(new Error("Transform transport interrupted; abandon this pass"), { code: "transform_transport_interrupted", cause: error });
|
|
6908
|
-
}
|
|
6909
|
-
if (args.generationSensitive && !args.signal?.aborted) {
|
|
6910
|
-
return {
|
|
6911
|
-
transport_status: "connection_generation_changed",
|
|
6912
|
-
previous_generation: previousGeneration,
|
|
6913
|
-
current_generation: this.connectionGeneration
|
|
6914
|
-
};
|
|
6915
|
-
}
|
|
6916
|
-
if (attempt === 0 && !args.signal?.aborted)
|
|
6917
|
-
continue;
|
|
6918
|
-
}
|
|
6919
|
-
throw error;
|
|
6920
|
-
}
|
|
6921
|
-
}
|
|
6922
|
-
throw new Error("module transport route retry exhausted");
|
|
6923
|
-
} finally {
|
|
6924
|
-
args.signal?.removeEventListener("abort", onAbort);
|
|
6925
|
-
finishWrapupTracking();
|
|
6926
|
-
releaseLane();
|
|
6927
|
-
timings.settle = Math.max(0, performance.now() - callStartedAt - timings.lane - timings.route - timings.encode - timings.issue - timings.responseWait);
|
|
6928
|
-
args.onTimings?.(timings);
|
|
6929
|
-
}
|
|
6930
|
-
}
|
|
6931
|
-
async deleteSession(sessionId, projectRoot) {
|
|
6932
|
-
await this.call({
|
|
6933
|
-
sessionId,
|
|
6934
|
-
projectRoot,
|
|
6935
|
-
method: "session.delete",
|
|
6936
|
-
body: { method: "session.delete", v: 1, session_id: sessionId }
|
|
6937
|
-
});
|
|
6938
|
-
}
|
|
6939
|
-
closeSession(sessionId) {
|
|
6940
|
-
const client = this.client;
|
|
6941
|
-
const prefix = `${sessionId}\x00`;
|
|
6942
|
-
const routes = [...this.routes.entries()].filter(([key]) => key.startsWith(prefix));
|
|
6943
|
-
for (const [key, cachedRoute] of routes) {
|
|
6944
|
-
this.routes.delete(key);
|
|
6945
|
-
if (client) {
|
|
6946
|
-
client.closeRoute(cachedRoute.route).catch((error) => {
|
|
6947
|
-
if (this.client === client && isConnectionFailure(error)) {
|
|
6948
|
-
this.invalidateConnection(client);
|
|
6949
|
-
}
|
|
6950
|
-
});
|
|
6951
|
-
}
|
|
6952
|
-
}
|
|
6953
|
-
if (routes.length === 0 && this.sessionLanes.get(sessionId)?.active) {
|
|
6954
|
-
this.invalidateConnection(client);
|
|
6955
|
-
}
|
|
6956
|
-
}
|
|
6957
|
-
async ensureRoute(sessionId, rawProjectRoot, deadlineMs = Date.now() + this.requestTimeoutMs, signal) {
|
|
6958
|
-
const projectRoot = this.canonicalRoot(rawProjectRoot);
|
|
6959
|
-
const routeKey = `${sessionId}\x00${projectRoot}`;
|
|
6960
|
-
const client = await this.ensureConnected(signal);
|
|
6961
|
-
const generation = this.connectionGeneration;
|
|
6962
|
-
const existing = this.routes.get(routeKey);
|
|
6963
|
-
if (existing?.generation === generation) {
|
|
6964
|
-
return { client, route: existing.route, routeKey, generation };
|
|
6965
|
-
}
|
|
6966
|
-
if (existing)
|
|
6967
|
-
this.routes.delete(routeKey);
|
|
6968
|
-
const opening = this.routeOpenings.get(routeKey);
|
|
6969
|
-
if (opening?.client === client && opening.generation === generation) {
|
|
6970
|
-
return await opening.promise;
|
|
6971
|
-
}
|
|
6972
|
-
const promise = (async () => {
|
|
6973
|
-
const target = { kind: "tool_provider", module_id: this.moduleId };
|
|
6974
|
-
const identity = {
|
|
6975
|
-
project_root: projectRoot,
|
|
6976
|
-
harness: getHarness2(),
|
|
6977
|
-
session: `${this.routeSessionPrefix}${sessionId}`
|
|
6978
|
-
};
|
|
6979
|
-
const route = await this.beforeDeadline(routeOpenWithoutAmbientConsumerIdentity(client, target, identity), deadlineMs, "opening the module route");
|
|
6980
|
-
if (this.client !== client || generation !== this.connectionGeneration) {
|
|
6981
|
-
await client.closeRoute(route).catch(() => {
|
|
6982
|
-
return;
|
|
6983
|
-
});
|
|
6984
|
-
throw this.connectionChangedError("subc connection changed while opening module route");
|
|
6985
|
-
}
|
|
6986
|
-
this.routes.set(routeKey, { route, generation });
|
|
6987
|
-
return { client, route, routeKey, generation };
|
|
6988
|
-
})();
|
|
6989
|
-
const routeOpening = { client, generation, promise };
|
|
6990
|
-
this.routeOpenings.set(routeKey, routeOpening);
|
|
6991
|
-
try {
|
|
6992
|
-
return await promise;
|
|
6993
|
-
} finally {
|
|
6994
|
-
if (this.routeOpenings.get(routeKey) === routeOpening) {
|
|
6995
|
-
this.routeOpenings.delete(routeKey);
|
|
6996
|
-
}
|
|
6997
|
-
}
|
|
6998
|
-
}
|
|
6999
|
-
dropRoute(routeKey, route) {
|
|
7000
|
-
const existing = this.routes.get(routeKey);
|
|
7001
|
-
if (!existing || route && existing.route !== route)
|
|
7002
|
-
return;
|
|
7003
|
-
this.routes.delete(routeKey);
|
|
7004
|
-
}
|
|
7005
|
-
canonicalRoot(root) {
|
|
7006
|
-
const cached = this.canonicalRootCache.get(root);
|
|
7007
|
-
if (cached !== undefined) {
|
|
7008
|
-
this.canonicalRootCache.delete(root);
|
|
7009
|
-
this.canonicalRootCache.set(root, cached);
|
|
7010
|
-
return cached;
|
|
7011
|
-
}
|
|
7012
|
-
let resolved = root;
|
|
7013
|
-
try {
|
|
7014
|
-
resolved = realpathSync.native(root);
|
|
7015
|
-
} catch {}
|
|
7016
|
-
this.canonicalRootCache.set(root, resolved);
|
|
7017
|
-
while (this.canonicalRootCache.size > CANONICAL_ROOT_CACHE_MAX_ENTRIES) {
|
|
7018
|
-
const oldestRoot = this.canonicalRootCache.keys().next().value;
|
|
7019
|
-
if (oldestRoot === undefined)
|
|
7020
|
-
break;
|
|
7021
|
-
this.canonicalRootCache.delete(oldestRoot);
|
|
7022
|
-
}
|
|
7023
|
-
return resolved;
|
|
7024
|
-
}
|
|
7025
|
-
connectClient() {
|
|
7026
|
-
return SubcClient.connect({
|
|
7027
|
-
connectionFile: this.connectionFile,
|
|
7028
|
-
handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS
|
|
7029
|
-
});
|
|
7030
|
-
}
|
|
7031
|
-
backoffActiveError() {
|
|
7032
|
-
const error = new Error(`subc connection backoff active until ${this.nextProbeMs}`);
|
|
7033
|
-
error.code = "SUBC_CONNECTION_BACKOFF";
|
|
7034
|
-
return error;
|
|
7035
|
-
}
|
|
7036
|
-
sleepAbortable(durationMs, signal) {
|
|
7037
|
-
return new Promise((resolve, reject) => {
|
|
7038
|
-
if (signal?.aborted) {
|
|
7039
|
-
reject(signal.reason ?? new Error("module transport call aborted"));
|
|
7040
|
-
return;
|
|
7041
|
-
}
|
|
7042
|
-
const onAbort = () => {
|
|
7043
|
-
clearTimeout(timer);
|
|
7044
|
-
signal?.removeEventListener("abort", onAbort);
|
|
7045
|
-
reject(signal?.reason ?? new Error("module transport call aborted"));
|
|
7046
|
-
};
|
|
7047
|
-
const timer = setTimeout(() => {
|
|
7048
|
-
signal?.removeEventListener("abort", onAbort);
|
|
7049
|
-
resolve();
|
|
7050
|
-
}, Math.max(0, durationMs));
|
|
7051
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
7052
|
-
});
|
|
7053
|
-
}
|
|
7054
|
-
async ensureConnected(signal) {
|
|
7055
|
-
if (this.client)
|
|
7056
|
-
return this.client;
|
|
7057
|
-
if (this.connectionPromise)
|
|
7058
|
-
return await this.connectionPromise;
|
|
7059
|
-
let now = Date.now();
|
|
7060
|
-
if (now < this.nextProbeMs) {
|
|
7061
|
-
const remainingMs = this.nextProbeMs - now;
|
|
7062
|
-
if (remainingMs > CONNECT_BACKOFF_WAIT_BUDGET_MS)
|
|
7063
|
-
throw this.backoffActiveError();
|
|
7064
|
-
const jitterMs = Math.floor(Math.random() * CONNECT_BACKOFF_WAIT_JITTER_MS);
|
|
7065
|
-
await this.sleepAbortable(remainingMs + jitterMs, signal);
|
|
7066
|
-
if (this.client)
|
|
7067
|
-
return this.client;
|
|
7068
|
-
if (this.connectionPromise)
|
|
7069
|
-
return await this.connectionPromise;
|
|
7070
|
-
now = Date.now();
|
|
7071
|
-
if (now < this.nextProbeMs)
|
|
7072
|
-
throw this.backoffActiveError();
|
|
7073
|
-
}
|
|
7074
|
-
const generation = this.connectionGeneration;
|
|
7075
|
-
const connecting = (async () => {
|
|
7076
|
-
let candidate = null;
|
|
7077
|
-
try {
|
|
7078
|
-
candidate = await this.connectClient();
|
|
7079
|
-
if (generation !== this.connectionGeneration) {
|
|
7080
|
-
candidate.close();
|
|
7081
|
-
throw this.connectionChangedError("subc connection attempt was superseded");
|
|
7082
|
-
}
|
|
7083
|
-
this.client = candidate;
|
|
7084
|
-
this.routes.clear();
|
|
7085
|
-
this.backoffMs = CONNECT_BACKOFF_INITIAL_MS;
|
|
7086
|
-
this.nextProbeMs = 0;
|
|
7087
|
-
return candidate;
|
|
7088
|
-
} catch (error) {
|
|
7089
|
-
candidate?.close();
|
|
7090
|
-
if (generation === this.connectionGeneration)
|
|
7091
|
-
this.invalidateConnection();
|
|
7092
|
-
this.nextProbeMs = Date.now() + this.backoffMs;
|
|
7093
|
-
this.backoffMs = Math.min(this.backoffMs * 2, CONNECT_BACKOFF_MAX_MS);
|
|
7094
|
-
throw error;
|
|
7095
|
-
}
|
|
7096
|
-
})();
|
|
7097
|
-
this.connectionPromise = connecting;
|
|
7098
|
-
try {
|
|
7099
|
-
return await connecting;
|
|
7100
|
-
} finally {
|
|
7101
|
-
if (this.connectionPromise === connecting)
|
|
7102
|
-
this.connectionPromise = null;
|
|
7103
|
-
}
|
|
7104
|
-
}
|
|
7105
|
-
invalidateConnection(client = this.client) {
|
|
7106
|
-
if (client && this.client !== client)
|
|
7107
|
-
return;
|
|
7108
|
-
this.connectionGeneration += 1;
|
|
7109
|
-
this.invalidateStateSyncCapabilities();
|
|
7110
|
-
this.client = null;
|
|
7111
|
-
this.routes.clear();
|
|
7112
|
-
this.routeOpenings.clear();
|
|
7113
|
-
client?.close();
|
|
7114
|
-
}
|
|
7115
|
-
}
|
|
7116
|
-
|
|
7117
6441
|
// src/hooks/magic-context/command-handler.ts
|
|
7118
6442
|
var recompConfirmationBySession = new Map;
|
|
7119
6443
|
var RECOMP_USAGE = [
|
|
@@ -7736,6 +7060,13 @@ function prepareLatestThinkingRecovery(args) {
|
|
|
7736
7060
|
}
|
|
7737
7061
|
return { restore: true, ended: false };
|
|
7738
7062
|
}
|
|
7063
|
+
function endLatestThinkingRecoveryAfterReset(db, sessionId) {
|
|
7064
|
+
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7065
|
+
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7066
|
+
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, target);
|
|
7067
|
+
}
|
|
7068
|
+
knownRejectedSessions.delete(sessionId);
|
|
7069
|
+
}
|
|
7739
7070
|
function captureOriginalTurn(messages, parts, setParts) {
|
|
7740
7071
|
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
7741
7072
|
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
@@ -8923,6 +8254,39 @@ function postprocessReplaySnapshot(db, sessionId) {
|
|
|
8923
8254
|
};
|
|
8924
8255
|
}
|
|
8925
8256
|
|
|
8257
|
+
// src/hooks/magic-context/strict-thinking-prefix.ts
|
|
8258
|
+
function servedPrefixMatches(args) {
|
|
8259
|
+
const heads = args.messages?.slice(0, 2);
|
|
8260
|
+
if (!heads || heads.length !== 2 || args.m0Text == null || args.m1Text == null)
|
|
8261
|
+
return false;
|
|
8262
|
+
const text = (message) => {
|
|
8263
|
+
if (!isRecord(message))
|
|
8264
|
+
return;
|
|
8265
|
+
if (typeof message.content === "string")
|
|
8266
|
+
return message.content;
|
|
8267
|
+
const parts = Array.isArray(message.parts) ? message.parts : message.content;
|
|
8268
|
+
if (!Array.isArray(parts))
|
|
8269
|
+
return;
|
|
8270
|
+
return parts.filter(isRecord).filter((part) => part.type === "text").map((part) => String(part.text ?? "")).join("");
|
|
8271
|
+
};
|
|
8272
|
+
if (text(heads[0]) !== args.m0Text || text(heads[1]) !== args.m1Text)
|
|
8273
|
+
return false;
|
|
8274
|
+
const head = heads[0];
|
|
8275
|
+
if (!isRecord(head))
|
|
8276
|
+
return false;
|
|
8277
|
+
const parts = Array.isArray(head.parts) ? head.parts : head.content;
|
|
8278
|
+
if (!Array.isArray(parts))
|
|
8279
|
+
return !args.muralDataUrl;
|
|
8280
|
+
const images = parts.filter(isRecord).filter((part) => part.type === "image" || part.type === "file");
|
|
8281
|
+
if (!args.muralDataUrl)
|
|
8282
|
+
return images.length === 0;
|
|
8283
|
+
if (images.length !== 1)
|
|
8284
|
+
return false;
|
|
8285
|
+
const image = images[0];
|
|
8286
|
+
const url = typeof image.url === "string" ? image.url : typeof image.data === "string" && typeof image.mimeType === "string" ? `data:${image.mimeType};base64,${image.data}` : undefined;
|
|
8287
|
+
return url === args.muralDataUrl;
|
|
8288
|
+
}
|
|
8289
|
+
|
|
8926
8290
|
// src/hooks/magic-context/supersession-reclaim.ts
|
|
8927
8291
|
var SUPERSESSION_RECENT_MESSAGE_WINDOW = 20;
|
|
8928
8292
|
function recentSupersessionOwnerMessageIds(db, sessionId) {
|
|
@@ -9235,6 +8599,7 @@ function getCachedInertWhitespaceAssistantTags(db, sessionId, tagger, messages)
|
|
|
9235
8599
|
const messageIds = messages.flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : []);
|
|
9236
8600
|
const ownersKey = JSON.stringify(messageIds);
|
|
9237
8601
|
const tagsVersion = tagger.getLoadedTagsVersion?.(sessionId, db);
|
|
8602
|
+
const identityRevision = tagger.getLoadedTagIdentityRevision?.(sessionId, db);
|
|
9238
8603
|
if (tagsVersion === undefined)
|
|
9239
8604
|
return getInertWhitespaceAssistantTags2(db, sessionId, messageIds);
|
|
9240
8605
|
let bySession = inertWhitespaceCache.get(db);
|
|
@@ -9243,10 +8608,10 @@ function getCachedInertWhitespaceAssistantTags(db, sessionId, tagger, messages)
|
|
|
9243
8608
|
inertWhitespaceCache.set(db, bySession);
|
|
9244
8609
|
}
|
|
9245
8610
|
const cached = bySession.get(sessionId);
|
|
9246
|
-
if (cached?.tagsVersion === tagsVersion && cached.ownersKey === ownersKey)
|
|
8611
|
+
if (cached?.tagsVersion === tagsVersion && cached.identityRevision === identityRevision && cached.ownersKey === ownersKey)
|
|
9247
8612
|
return cached.tags;
|
|
9248
8613
|
const tags = getInertWhitespaceAssistantTags2(db, sessionId, messageIds);
|
|
9249
|
-
bySession.set(sessionId, { tagsVersion, ownersKey, tags });
|
|
8614
|
+
bySession.set(sessionId, { tagsVersion, identityRevision, ownersKey, tags });
|
|
9250
8615
|
return tags;
|
|
9251
8616
|
}
|
|
9252
8617
|
function makeToolOwnerCacheKey(sessionId, callId) {
|
|
@@ -10085,6 +9450,8 @@ function applyRustModeThinkingStrips(args, hostEditBeforeNewestThinking) {
|
|
|
10085
9450
|
const recoveryMessageIds = new Set;
|
|
10086
9451
|
let thinkingBindingRecovery = null;
|
|
10087
9452
|
let proactiveThinkingStrip = null;
|
|
9453
|
+
const signedThinkingReset = args.cacheBustingPass === true && args.moduleSignedThinkingReset === true;
|
|
9454
|
+
const stripProtection = signedThinkingReset ? undefined : args.protectedThinkingMessages;
|
|
10088
9455
|
{
|
|
10089
9456
|
try {
|
|
10090
9457
|
for (const id of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
@@ -10111,26 +9478,31 @@ function applyRustModeThinkingStrips(args, hostEditBeforeNewestThinking) {
|
|
|
10111
9478
|
} catch (error) {
|
|
10112
9479
|
sessionLog2(args.sessionId, "rust thinking binding recovery failed:", error);
|
|
10113
9480
|
}
|
|
10114
|
-
stripReasoningFromAssistantIds(args.messages, args.resolvedProviderID, recoveryMessageIds,
|
|
10115
|
-
const moduleBustStrips = !args.activeThinkingTurn && args.cacheBustingPass === true && (args.moduleReasoningTrimOnly !== true || hostEditBeforeNewestThinking);
|
|
10116
|
-
const stripFrom = args.thinkingBindingRecoveryEnabledForModel === true ? proactiveStripStartIndex({ ...args, cacheBustingPass: moduleBustStrips }) : null;
|
|
9481
|
+
stripReasoningFromAssistantIds(args.messages, args.resolvedProviderID, recoveryMessageIds, stripProtection);
|
|
9482
|
+
const moduleBustStrips = signedThinkingReset || !args.activeThinkingTurn && args.cacheBustingPass === true && (args.moduleReasoningTrimOnly !== true || hostEditBeforeNewestThinking);
|
|
9483
|
+
const stripFrom = args.thinkingBindingRecoveryEnabledForModel === true || signedThinkingReset ? proactiveStripStartIndex({ ...args, cacheBustingPass: moduleBustStrips }) : null;
|
|
10117
9484
|
if (stripFrom !== null) {
|
|
9485
|
+
const stripped = args.messages.slice(stripFrom);
|
|
10118
9486
|
const outcome = freezeReasoningOnBustingPass({
|
|
10119
9487
|
db: args.db,
|
|
10120
9488
|
sessionId: args.sessionId,
|
|
10121
|
-
messages:
|
|
10122
|
-
protectedMessages:
|
|
9489
|
+
messages: stripped,
|
|
9490
|
+
protectedMessages: stripProtection,
|
|
10123
9491
|
alreadyFrozen: recoveryMessageIds
|
|
10124
9492
|
});
|
|
10125
9493
|
if (outcome.strip) {
|
|
10126
9494
|
proactiveThinkingStrip = outcome.strip;
|
|
10127
9495
|
for (const id of outcome.strip.messageIds)
|
|
10128
9496
|
recoveryMessageIds.add(id);
|
|
10129
|
-
|
|
9497
|
+
}
|
|
9498
|
+
const removed = signedThinkingReset ? new Set(findReasoningBearingAssistantIds(stripped)) : new Set(outcome.strip?.messageIds ?? []);
|
|
9499
|
+
if (removed.size > 0) {
|
|
9500
|
+
stripReasoningFromAssistantIds(args.messages, args.resolvedProviderID, removed, stripProtection);
|
|
10130
9501
|
}
|
|
10131
9502
|
}
|
|
10132
9503
|
}
|
|
10133
|
-
|
|
9504
|
+
if (!signedThinkingReset)
|
|
9505
|
+
args.restoreLatestTurnOriginals?.();
|
|
10134
9506
|
return { thinkingBindingRecovery, proactiveThinkingStrip };
|
|
10135
9507
|
}
|
|
10136
9508
|
function runRustModePostprocess(args) {
|
|
@@ -10173,7 +9545,7 @@ function runRustModePostprocess(args) {
|
|
|
10173
9545
|
appendReminderToUserMessageById(args.messages, anchor.messageId, anchor.text);
|
|
10174
9546
|
}
|
|
10175
9547
|
for (const decision of getAutoSearchHintDecisions(args.db, args.sessionId)) {
|
|
10176
|
-
if (decision.decision === "hint") {
|
|
9548
|
+
if (decision.decision === "hint" && getUnpublishedAutoSearchNoHint(args.sessionId, decision.messageId) === undefined) {
|
|
10177
9549
|
appendReminderToUserMessageById(args.messages, decision.messageId, decision.text);
|
|
10178
9550
|
}
|
|
10179
9551
|
}
|
|
@@ -10436,7 +9808,7 @@ async function runPostTransformPhase(args) {
|
|
|
10436
9808
|
const reasoningMutationExemptMessage = findLatestAssistantReasoningMutationExemptMessage(args.messages);
|
|
10437
9809
|
const pendingMaterializationAtPassStart = args.pendingMaterializationSessions.has(args.sessionId);
|
|
10438
9810
|
const deferredMaterializationAtPassStart = args.deferredMaterializationSessions.has(args.sessionId);
|
|
10439
|
-
|
|
9811
|
+
let isExplicitFlush = pendingMaterializationAtPassStart;
|
|
10440
9812
|
const deferredMaterializationWasPending = deferredMaterializationAtPassStart;
|
|
10441
9813
|
const alreadyRanThisTurn = args.currentTurnId !== null && args.lastHeuristicsTurnId.get(args.sessionId) === args.currentTurnId;
|
|
10442
9814
|
const forceMaterialization = args.fullFeatureMode && !compactionOff && args.contextUsage.percentage >= args.forceMaterializationPercentage;
|
|
@@ -10453,8 +9825,8 @@ async function runPostTransformPhase(args) {
|
|
|
10453
9825
|
}
|
|
10454
9826
|
const activeCompartmentRun = args.canRunCompartments ? getActiveCompartmentRun(args.sessionId) : undefined;
|
|
10455
9827
|
const compartmentRunning = args.canRunCompartments && !args.awaitedCompartmentRun && activeCompartmentRun !== undefined;
|
|
10456
|
-
|
|
10457
|
-
|
|
9828
|
+
let deferredMaterialize = args.canConsumeDeferredLate && deferredMaterializationWasPending;
|
|
9829
|
+
let materializationRequested = isExplicitFlush || deferredMaterialize;
|
|
10458
9830
|
const m0M1EnabledForFold = args.m0M1 !== undefined && (!!args.m0M1.projectPath || !!args.m0M1.projectDirectory) && (args.fullFeatureMode || compactionOff);
|
|
10459
9831
|
const frozenThinking = new Set(args.activeThinkingTurn ? getMergedReasoningStrippedIds(args.db, args.sessionId) : []);
|
|
10460
9832
|
const bindingThinking = new Set([...frozenThinking].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)));
|
|
@@ -10466,9 +9838,9 @@ async function runPostTransformPhase(args) {
|
|
|
10466
9838
|
bindingIds: bindingThinking,
|
|
10467
9839
|
removedIds: getReasoningRemovalState(args.db, args.sessionId).messageIds
|
|
10468
9840
|
}) : new Set;
|
|
10469
|
-
|
|
9841
|
+
let activeThinkingTurn = retainedThinking.size > 0;
|
|
10470
9842
|
const protectedThinkingMessages = new Set(args.messages.filter((message) => message.parts.some((part) => retainedThinking.has(part))));
|
|
10471
|
-
|
|
9843
|
+
let newTargets = protectNewTagMutations(args.messages, args.targets, retainedThinking, args.thinkingBindingRecoveryEnabledForModel === true);
|
|
10472
9844
|
let maxReasoningTag = 0;
|
|
10473
9845
|
for (const tag of args.messageTagNumbers.values())
|
|
10474
9846
|
maxReasoningTag = Math.max(maxReasoningTag, tag);
|
|
@@ -10478,7 +9850,28 @@ async function runPostTransformPhase(args) {
|
|
|
10478
9850
|
if (tag && tag > 0)
|
|
10479
9851
|
safeReasoningCutoff = Math.min(safeReasoningCutoff, tag - 1);
|
|
10480
9852
|
}
|
|
10481
|
-
|
|
9853
|
+
let activeThinkingPrefixHold = args.activeThinkingPrefixHold === true || activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel === true;
|
|
9854
|
+
let freezeM0M1 = args.freezeM0M1 === true || activeThinkingPrefixHold;
|
|
9855
|
+
let rewritingSignedPrefix = false;
|
|
9856
|
+
let thinkingReleasedForFit = false;
|
|
9857
|
+
const releaseThinkingForRewrite = (forFit = false) => {
|
|
9858
|
+
const stripped = freezeReasoningOnBustingPass({
|
|
9859
|
+
db: args.db,
|
|
9860
|
+
sessionId: args.sessionId,
|
|
9861
|
+
messages: args.messages,
|
|
9862
|
+
alreadyFrozen: bindingThinking
|
|
9863
|
+
});
|
|
9864
|
+
if (stripped.persistenceFailed)
|
|
9865
|
+
throw new Error("Cannot persist signed thinking omission before prefix rewrite");
|
|
9866
|
+
retainedThinking.clear();
|
|
9867
|
+
protectedThinkingMessages.clear();
|
|
9868
|
+
activeThinkingTurn = false;
|
|
9869
|
+
activeThinkingPrefixHold = false;
|
|
9870
|
+
freezeM0M1 = args.directoryPrefixHold === true;
|
|
9871
|
+
newTargets = args.targets;
|
|
9872
|
+
rewritingSignedPrefix = true;
|
|
9873
|
+
thinkingReleasedForFit ||= forFit;
|
|
9874
|
+
};
|
|
10482
9875
|
const foldDueDecision = m0M1EnabledForFold && args.m0M1 && !freezeM0M1 ? mustMaterialize({
|
|
10483
9876
|
db: args.db,
|
|
10484
9877
|
sessionId: args.sessionId,
|
|
@@ -10498,6 +9891,7 @@ async function runPostTransformPhase(args) {
|
|
|
10498
9891
|
const cachedPrefixBeforePreflight = shouldCaptureCachedPrefix ? prepareCachedM0M1Replay(args.db, args.sessionId) : undefined;
|
|
10499
9892
|
const completeCachedPrefixAvailable = args.sessionMeta.cachedM0Bytes != null && args.sessionMeta.cachedM1Bytes != null || cachedPrefixBeforePreflight !== undefined || m0M1EnabledForFold && !shouldCaptureCachedPrefix && hasCompleteCachedM0M1(args.db, args.sessionId);
|
|
10500
9893
|
const firstRenderBust = m0M1EnabledForFold && !completeCachedPrefixAvailable;
|
|
9894
|
+
const servedBeforeFirstRender = firstRenderBust ? args.readLastServedMessages?.() : null;
|
|
10501
9895
|
let foldExecutedThisPass = false;
|
|
10502
9896
|
let foldBustsServedPrefixThisPass = false;
|
|
10503
9897
|
let publishedM1RefreshedThisPass = false;
|
|
@@ -10515,7 +9909,7 @@ async function runPostTransformPhase(args) {
|
|
|
10515
9909
|
m1Bytes: args.sessionMeta.cachedM1Bytes ?? null,
|
|
10516
9910
|
muralDataUrl: args.sessionMeta.cachedM0MuralDataUrl ?? null
|
|
10517
9911
|
};
|
|
10518
|
-
if ((foldDueDecision.value || softRefreshOpportunity) && m0M1EnabledForFold && args.m0M1) {
|
|
9912
|
+
if ((foldDueDecision.value || softRefreshOpportunity || firstRenderBust && activeThinkingPrefixHold) && m0M1EnabledForFold && args.m0M1) {
|
|
10519
9913
|
let committedFoldBustsServedPrefix;
|
|
10520
9914
|
try {
|
|
10521
9915
|
const previousM1 = args.sessionMeta.cachedM1Bytes?.toString("utf8");
|
|
@@ -10540,7 +9934,12 @@ async function runPostTransformPhase(args) {
|
|
|
10540
9934
|
onFoldPrepare: () => {
|
|
10541
9935
|
const conversions = prepareLegacyToolSkeletonConversions(args.db, args.sessionId, args.targets);
|
|
10542
9936
|
return (db, rendered) => {
|
|
10543
|
-
const bustsPrefix =
|
|
9937
|
+
const bustsPrefix = activeThinkingPrefixHold ? !servedPrefixMatches({
|
|
9938
|
+
messages: servedBeforeFirstRender,
|
|
9939
|
+
m0Text: rendered.m0Bytes.toString(),
|
|
9940
|
+
m1Text: rendered.m1Bytes.toString(),
|
|
9941
|
+
muralDataUrl: rendered.muralDataUrl
|
|
9942
|
+
}) : foldBustsServedPrefix(foldDueDecision.reason, servedPrefixBeforeFold, rendered);
|
|
10544
9943
|
if (bustsPrefix) {
|
|
10545
9944
|
if (!conversions.isCurrent(db)) {
|
|
10546
9945
|
throw new MaterializeContentionError({
|
|
@@ -10557,6 +9956,9 @@ async function runPostTransformPhase(args) {
|
|
|
10557
9956
|
}
|
|
10558
9957
|
});
|
|
10559
9958
|
preparedPrefix = foldResult;
|
|
9959
|
+
if (activeThinkingPrefixHold && firstRenderBust && committedFoldBustsServedPrefix) {
|
|
9960
|
+
releaseThinkingForRewrite();
|
|
9961
|
+
}
|
|
10560
9962
|
prefixPreflightFailed = foldResult.materializationContentionRetryExhausted === true;
|
|
10561
9963
|
foldExecutedThisPass = foldExecutesThisPass(foldDueDecision.value || softRefreshOpportunity, foldResult.m0RematerializedThisPass);
|
|
10562
9964
|
foldBustsServedPrefixThisPass = foldExecutedThisPass && (committedFoldBustsServedPrefix ?? true);
|
|
@@ -10592,6 +9994,15 @@ async function runPostTransformPhase(args) {
|
|
|
10592
9994
|
}
|
|
10593
9995
|
logTransformTiming(args.sessionId, "pp.prefixPreflight", tPostprocessSetup, `foldExecuted=${foldExecutedThisPass} m1Refreshed=${publishedM1RefreshedThisPass}`);
|
|
10594
9996
|
const tPassDecisions = performance.now();
|
|
9997
|
+
const frontToolCandidates = args.tags.filter((tag) => tag.type === "tool" && tag.status === "active" && args.targets.get(tag.tagNumber)?.canDrop?.());
|
|
9998
|
+
if (activeThinkingPrefixHold && (args.forceSignedRebuildForFit || args.contextUsage.percentage >= 95 && frontToolCandidates.length > 0 && frontToolCandidates.every((tag) => newTargets.get(tag.tagNumber)?.thinkingRewriteProtected === true))) {
|
|
9999
|
+
releaseThinkingForRewrite(true);
|
|
10000
|
+
}
|
|
10001
|
+
if (activeThinkingPrefixHold) {
|
|
10002
|
+
isExplicitFlush = false;
|
|
10003
|
+
deferredMaterialize = false;
|
|
10004
|
+
materializationRequested = false;
|
|
10005
|
+
}
|
|
10595
10006
|
const shouldReadPendingOps = !compactionOff && (materializationRequested || publishedM1RefreshedThisPass || args.schedulerDecision === "execute" || forceMaterialization || foldExecutedThisPass || firstRenderBust || compartmentRunning);
|
|
10596
10007
|
const pendingOps = shouldReadPendingOps ? getPendingOps(args.db, args.sessionId) : [];
|
|
10597
10008
|
const hasPendingUserOps = pendingOps.length > 0;
|
|
@@ -10601,7 +10012,8 @@ async function runPostTransformPhase(args) {
|
|
|
10601
10012
|
const depth = getPendingOpsCount(args.db, args.sessionId);
|
|
10602
10013
|
return depth === null ? "not loaded (deferred pass)" : String(depth);
|
|
10603
10014
|
};
|
|
10604
|
-
const
|
|
10015
|
+
const heldIdleExpiryRebuild = activeThinkingPrefixHold && args.m0M1?.hardSignals?.cacheExpired === true;
|
|
10016
|
+
const idleExpiryRebuild = (!freezeM0M1 || activeThinkingPrefixHold) && args.m0M1?.hardSignals?.cacheExpired === true;
|
|
10605
10017
|
const rideSignals = {
|
|
10606
10018
|
subagentExecute: !args.fullFeatureMode && args.schedulerDecision === "execute",
|
|
10607
10019
|
hardFold: foldBustsServedPrefixThisPass || firstRenderBust || idleExpiryRebuild,
|
|
@@ -10609,15 +10021,16 @@ async function runPostTransformPhase(args) {
|
|
|
10609
10021
|
explicitFlush: isExplicitFlush || deferredMaterialize && !prefixPreflightFailed,
|
|
10610
10022
|
publishedHistory: publishedM1RefreshedThisPass || !m0M1EnabledForFold && (args.pendingCompartmentInjection?.compartmentCount ?? 0) > 0 && (args.historyRebuiltThisPass || args.rebuiltHistoryFromInitialPrepare || args.canConsumeDeferredLate && args.deferredHistoryWasPendingAtPassStart)
|
|
10611
10023
|
};
|
|
10612
|
-
const publishedWorkDrainAllowed = !compactionOff && hasReclaimRide(rideSignals);
|
|
10024
|
+
const publishedWorkDrainAllowed = !compactionOff && (!activeThinkingPrefixHold || firstRenderBust || idleExpiryRebuild || emergencyDropEligible) && hasReclaimRide(rideSignals);
|
|
10613
10025
|
const shouldApplyPendingOps = publishedWorkDrainAllowed;
|
|
10614
|
-
const shouldRunHeuristics =
|
|
10026
|
+
const shouldRunHeuristics = publishedWorkDrainAllowed && (rideSignals.publishedHistory || materializationRequested || forceMaterialization || foldBustsServedPrefixThisPass || firstRenderBust || heldIdleExpiryRebuild || emergencyDropEligible || args.schedulerDecision === "execute" && (!alreadyRanThisTurn || !args.fullFeatureMode));
|
|
10615
10027
|
const isCacheBustingPass = publishedWorkDrainAllowed;
|
|
10028
|
+
const canEditWholePrefix = isCacheBustingPass && !activeThinkingPrefixHold;
|
|
10616
10029
|
const previousTemporalDecisions = args.temporalCandidates && !compactionOff ? new Map([
|
|
10617
10030
|
...args.temporalObservedDecisions ?? [],
|
|
10618
10031
|
...getTemporalDecisions(args.db, args.sessionId, args.temporalReplayIds ?? args.temporalCandidates.keys())
|
|
10619
10032
|
]) : undefined;
|
|
10620
|
-
const temporalDecisions = args.temporalCandidates && !compactionOff ?
|
|
10033
|
+
const temporalDecisions = args.temporalCandidates && !compactionOff ? canEditWholePrefix ? new Map([
|
|
10621
10034
|
...previousTemporalDecisions ?? [],
|
|
10622
10035
|
...freezeTemporalDecisions(args.db, args.sessionId, args.temporalCandidates)
|
|
10623
10036
|
]) : previousTemporalDecisions : undefined;
|
|
@@ -10775,7 +10188,7 @@ async function runPostTransformPhase(args) {
|
|
|
10775
10188
|
wordRules: args.cavemanTextCompression.wordRules
|
|
10776
10189
|
} : undefined;
|
|
10777
10190
|
const heuristicTags = shouldApplyPendingOps ? getActiveTagsBySession2(args.db, args.sessionId) : args.tags;
|
|
10778
|
-
const emergencyRewriteAlreadyPriced = pendingOpsDidMutate || foldBustsServedPrefixThisPass || args.historyRebuiltThisPass || args.compartmentInjectionRebuiltFromDb || args.rebuiltHistoryFromInitialPrepare;
|
|
10191
|
+
const emergencyRewriteAlreadyPriced = pendingOpsDidMutate || foldBustsServedPrefixThisPass || firstRenderBust || heldIdleExpiryRebuild || args.historyRebuiltThisPass || args.compartmentInjectionRebuiltFromDb || args.rebuiltHistoryFromInitialPrepare;
|
|
10779
10192
|
if (emergencyDropEligible && emergencyRewriteAlreadyPriced && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
10780
10193
|
clearEmergencyDropSample(args.db, args.sessionId);
|
|
10781
10194
|
}
|
|
@@ -10836,7 +10249,7 @@ async function runPostTransformPhase(args) {
|
|
|
10836
10249
|
}
|
|
10837
10250
|
}
|
|
10838
10251
|
const reasoningEstimates = tryGetReasoningTokenEstimatesByMessage2(args.db, args.sessionId, sessionDecisionCalibration(args.db, args.sessionId).proseRatio);
|
|
10839
|
-
const budgetCutoff = routineCleanupApplied && reasoningEstimates ? Math.min(safeReasoningCutoff, opencodeReasoningBudgetCutoff({
|
|
10252
|
+
const budgetCutoff = routineCleanupApplied && !activeThinkingPrefixHold && reasoningEstimates ? Math.min(safeReasoningCutoff, opencodeReasoningBudgetCutoff({
|
|
10840
10253
|
messages: args.messages,
|
|
10841
10254
|
messageTagNumbers: args.messageTagNumbers,
|
|
10842
10255
|
budget: args.keepReasoningTokens ?? DEFAULT_KEEP_REASONING_TOKENS,
|
|
@@ -10858,7 +10271,7 @@ async function runPostTransformPhase(args) {
|
|
|
10858
10271
|
replayStrippedInlineThinking(args.messages, args.messageTagNumbers, persistedInlineWatermark);
|
|
10859
10272
|
}
|
|
10860
10273
|
let removedReasoningMessages = 0;
|
|
10861
|
-
if (routineCleanupApplied && reasoningRemovalSelectable && reasoningRemovalReadable) {
|
|
10274
|
+
if (routineCleanupApplied && !prefixBoundModel && reasoningRemovalSelectable && reasoningRemovalReadable) {
|
|
10862
10275
|
const newIds = selectReasoningRemovals({
|
|
10863
10276
|
messages: args.messages,
|
|
10864
10277
|
messageTagNumbers: args.messageTagNumbers,
|
|
@@ -10975,7 +10388,7 @@ async function runPostTransformPhase(args) {
|
|
|
10975
10388
|
logTransformTiming(args.sessionId, "toolReclaim.select", tReclaimSelect, `targets=${autoReclaimTargetCount}`);
|
|
10976
10389
|
if (syntheticPendingOps.length > 0) {
|
|
10977
10390
|
const tReclaimApply = performance.now();
|
|
10978
|
-
autoReclaimDidMutate = applyPendingOperations(args.sessionId, args.db,
|
|
10391
|
+
autoReclaimDidMutate = applyPendingOperations(args.sessionId, args.db, newTargets, args.protectedTagIds, undefined, [], syntheticPendingOps, editMarkerTagIds, (reduction) => droppedTokenReductions.push(reduction));
|
|
10979
10392
|
logTransformTiming(args.sessionId, "toolReclaim.apply", tReclaimApply);
|
|
10980
10393
|
if (autoReclaimDidMutate) {
|
|
10981
10394
|
droppedCount += syntheticPendingOps.length;
|
|
@@ -11028,7 +10441,7 @@ async function runPostTransformPhase(args) {
|
|
|
11028
10441
|
const t8 = performance.now();
|
|
11029
10442
|
const frozenStaleReduceIds = replaySnapshot.staleReduceStrippedIds;
|
|
11030
10443
|
const staleReduceResult = dropStaleReduceCalls(args.messages, frozenStaleReduceIds, {
|
|
11031
|
-
detect:
|
|
10444
|
+
detect: canEditWholePrefix,
|
|
11032
10445
|
protectedCount: args.protectedCount,
|
|
11033
10446
|
protectedCallIds: new Set(args.tags.filter((tag) => protectedToolTags.has(tag.tagNumber)).map((tag) => tag.messageId)),
|
|
11034
10447
|
onFirstApplication: recordFirstApplicationAt
|
|
@@ -11047,7 +10460,7 @@ async function runPostTransformPhase(args) {
|
|
|
11047
10460
|
const tImg = performance.now();
|
|
11048
10461
|
const frozenImageIds = replaySnapshot.processedImageStrippedIds;
|
|
11049
10462
|
const imageResult = stripProcessedImages(args.messages, frozenImageIds, {
|
|
11050
|
-
detect:
|
|
10463
|
+
detect: canEditWholePrefix && args.watermark > 0,
|
|
11051
10464
|
watermark: args.watermark,
|
|
11052
10465
|
messageTagNumbers: args.messageTagNumbers,
|
|
11053
10466
|
onFirstApplication: recordFirstApplicationAt
|
|
@@ -11291,7 +10704,7 @@ async function runPostTransformPhase(args) {
|
|
|
11291
10704
|
messages: args.messages,
|
|
11292
10705
|
fullFeatureMode: args.fullFeatureMode,
|
|
11293
10706
|
compactionOff,
|
|
11294
|
-
isCacheBustingPass,
|
|
10707
|
+
isCacheBustingPass: canEditWholePrefix,
|
|
11295
10708
|
sessionMeta: args.sessionMeta,
|
|
11296
10709
|
todowriteAvailability: args.todowriteAvailability,
|
|
11297
10710
|
client: args.client,
|
|
@@ -11358,7 +10771,7 @@ async function runPostTransformPhase(args) {
|
|
|
11358
10771
|
autoSearchHintAppendedThisPass = autoSearchCompletedThisPass && countAutoSearchHints(args.db, args.sessionId) !== autoSearchHintsBefore;
|
|
11359
10772
|
logTransformTiming(args.sessionId, "pp.autoSearchHint", tAutoSearch);
|
|
11360
10773
|
}
|
|
11361
|
-
if (args.fullFeatureMode &&
|
|
10774
|
+
if (args.fullFeatureMode && canEditWholePrefix) {
|
|
11362
10775
|
const visibleIds = new Set;
|
|
11363
10776
|
for (const message of args.messages) {
|
|
11364
10777
|
if (typeof message.info?.id === "string") {
|
|
@@ -11366,15 +10779,15 @@ async function runPostTransformPhase(args) {
|
|
|
11366
10779
|
}
|
|
11367
10780
|
}
|
|
11368
10781
|
const prunedAnchors = pruneNoteNudgeAnchors(args.db, args.sessionId, visibleIds);
|
|
11369
|
-
|
|
11370
|
-
if (prunedAnchors > 0
|
|
11371
|
-
sessionLog2(args.sessionId, `sticky-injection GC: pruned ${prunedAnchors} note-nudge anchor(s)
|
|
10782
|
+
flushAutoSearchHintDecisionRetirement(args.db, args.sessionId, visibleIds);
|
|
10783
|
+
if (prunedAnchors > 0) {
|
|
10784
|
+
sessionLog2(args.sessionId, `sticky-injection GC: pruned ${prunedAnchors} note-nudge anchor(s)`);
|
|
11372
10785
|
}
|
|
11373
10786
|
}
|
|
11374
10787
|
const materializeReason = m0MaterializeReason ?? (explicitMaterializedSuccessfully ? "explicit_flush" : null);
|
|
11375
10788
|
const materialized = m0RematerializedThisPass || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully;
|
|
11376
10789
|
let bustedThisPass = firstApplicationEdits.any || firstRenderBust || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass;
|
|
11377
|
-
const proactiveThinkingStripPermitted = isCacheBustingPass;
|
|
10790
|
+
const proactiveThinkingStripPermitted = isCacheBustingPass && !activeThinkingPrefixHold;
|
|
11378
10791
|
const tFrozenDecisions = performance.now();
|
|
11379
10792
|
if (reasoningMutationTargetUnknown) {
|
|
11380
10793
|
const reasoningCandidates = args.reasoningByMessage.size > 0 ? args.reasoningByMessage.keys() : args.messages;
|
|
@@ -11425,7 +10838,7 @@ async function runPostTransformPhase(args) {
|
|
|
11425
10838
|
sessionLog2(args.sessionId, "thinking binding recovery: persistence failed; leaving the bound blocks intact");
|
|
11426
10839
|
}
|
|
11427
10840
|
}
|
|
11428
|
-
if (canUseEmptySentinels &&
|
|
10841
|
+
if (canUseEmptySentinels && canEditWholePrefix) {
|
|
11429
10842
|
const candidates = findMergedReasoningStripDecisions(args.messages, args.resolvedProviderID, mergedReasoningStrippedIds, {
|
|
11430
10843
|
mutationExemptMessage: reasoningMutationExemptMessage,
|
|
11431
10844
|
protectedMessages: protectedThinkingMessages
|
|
@@ -11471,7 +10884,7 @@ async function runPostTransformPhase(args) {
|
|
|
11471
10884
|
recordFirstApplicationAt(message, partIndex);
|
|
11472
10885
|
}
|
|
11473
10886
|
};
|
|
11474
|
-
if (
|
|
10887
|
+
if (canEditWholePrefix && trailingBlankDecisions.size > 0) {
|
|
11475
10888
|
const visibleMessageIds = new Set(args.messages.flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : []));
|
|
11476
10889
|
const poisonedKeepIds = [];
|
|
11477
10890
|
for (const [id, decision] of trailingBlankDecisions) {
|
|
@@ -11576,7 +10989,7 @@ async function runPostTransformPhase(args) {
|
|
|
11576
10989
|
}
|
|
11577
10990
|
}
|
|
11578
10991
|
}
|
|
11579
|
-
const prefixEditBesidesReasoningTrim = firstRenderBust || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || firstApplicationEdits.beforeNewerThinking;
|
|
10992
|
+
const prefixEditBesidesReasoningTrim = firstRenderBust || heldIdleExpiryRebuild || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || firstApplicationEdits.beforeNewerThinking;
|
|
11580
10993
|
let proactiveThinkingStrip = null;
|
|
11581
10994
|
if (!compactionOff && args.thinkingBindingRecoveryEnabledForModel === true && proactiveThinkingStripPermitted && prefixEditBesidesReasoningTrim) {
|
|
11582
10995
|
const outcome = freezeReasoningOnBustingPass({
|
|
@@ -11623,8 +11036,9 @@ async function runPostTransformPhase(args) {
|
|
|
11623
11036
|
const removedReasoningParts = reasoningRemovalEnabled ? removeReasoningParts(args.messages, removedReasoningIds, args.resolvedProviderID) : 0;
|
|
11624
11037
|
const reasoningStatusRatio = sessionDecisionCalibration(args.db, args.sessionId).proseRatio;
|
|
11625
11038
|
captureOpencodeReasoningBudgetStatus(args.sessionId, args.messages, args.keepReasoningTokens ?? DEFAULT_KEEP_REASONING_TOKENS, prefixBoundModel, reasoningStatusRatio);
|
|
11626
|
-
|
|
11627
|
-
|
|
11039
|
+
if (!rewritingSignedPrefix)
|
|
11040
|
+
args.restoreLatestTurnOriginals?.();
|
|
11041
|
+
if (!rewritingSignedPrefix && args.restoreLatestTurnOriginals) {
|
|
11628
11042
|
refreshReasoningRemovalUnion();
|
|
11629
11043
|
if (replayCommittedVisibleDrops()) {
|
|
11630
11044
|
finalizeMessageRepresentation(args.messages, args.resolvedProviderID, finalizeOptions);
|
|
@@ -11748,7 +11162,8 @@ async function runPostTransformPhase(args) {
|
|
|
11748
11162
|
bustedThisPass,
|
|
11749
11163
|
prefixTrimStatus: deliveredPrefix?.prefixTrimStatus ?? null,
|
|
11750
11164
|
thinkingBindingRecovery,
|
|
11751
|
-
proactiveThinkingStrip
|
|
11165
|
+
proactiveThinkingStrip,
|
|
11166
|
+
thinkingReleasedForFit
|
|
11752
11167
|
};
|
|
11753
11168
|
}
|
|
11754
11169
|
function checkM0MutationDriftAndSignal(args) {
|
|
@@ -11812,7 +11227,7 @@ class StorageBusyRefusalError extends Error {
|
|
|
11812
11227
|
}
|
|
11813
11228
|
|
|
11814
11229
|
// src/hooks/magic-context/system-prompt-hash.ts
|
|
11815
|
-
import { createHash
|
|
11230
|
+
import { createHash } from "node:crypto";
|
|
11816
11231
|
var MAGIC_CONTEXT_MARKER = "## Magic Context";
|
|
11817
11232
|
var SYSTEM_PROMPT_GUIDANCE_SEPARATOR = `
|
|
11818
11233
|
|
|
@@ -11912,7 +11327,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11912
11327
|
}
|
|
11913
11328
|
const stickyDate = stickyDateBySession.get(sessionId);
|
|
11914
11329
|
const stableCandidate = currentDate && stickyDate && currentDate !== stickyDate ? liveSystemContent.replace(DATE_PATTERN_ALL, stickyDate) : liveSystemContent;
|
|
11915
|
-
const stableCandidateHash =
|
|
11330
|
+
const stableCandidateHash = createHash("md5").update(promptSurfaceHashMaterial(stableCandidate, promptSurface.preset)).digest("hex");
|
|
11916
11331
|
const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
|
|
11917
11332
|
const dateMayAdvance = isCacheBusting || idleCacheExpired || contentOrPresetChanged;
|
|
11918
11333
|
if (currentDate && !stickyDate) {
|
|
@@ -11932,7 +11347,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11932
11347
|
`);
|
|
11933
11348
|
if (!availability.frozen || !modelKey)
|
|
11934
11349
|
return;
|
|
11935
|
-
const currentHash =
|
|
11350
|
+
const currentHash = createHash("md5").update(promptSurfaceHashMaterial(systemContent, promptSurface.preset)).digest("hex");
|
|
11936
11351
|
if (!sessionMetaEarly) {
|
|
11937
11352
|
return;
|
|
11938
11353
|
}
|
|
@@ -12053,7 +11468,8 @@ function writeRustTransformDecision(args) {
|
|
|
12053
11468
|
droppedTokens: 0,
|
|
12054
11469
|
droppedCount: 0,
|
|
12055
11470
|
inputTokens: args.inputTokens,
|
|
12056
|
-
bustedThisPass: mapped.bustedThisPass
|
|
11471
|
+
bustedThisPass: mapped.bustedThisPass,
|
|
11472
|
+
lkgFrozenReleaseReason: args.lkgFrozenReleaseReason
|
|
12057
11473
|
});
|
|
12058
11474
|
}
|
|
12059
11475
|
function clearOpenCodePendingTransformDecision(sessionId) {
|
|
@@ -12214,7 +11630,7 @@ function commitCompactionModeRecord(db, sessionId, record) {
|
|
|
12214
11630
|
}
|
|
12215
11631
|
|
|
12216
11632
|
// src/hooks/magic-context/lkg-persist.ts
|
|
12217
|
-
import { createHash as
|
|
11633
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
12218
11634
|
function parseStringArray(value) {
|
|
12219
11635
|
if (typeof value !== "string")
|
|
12220
11636
|
return null;
|
|
@@ -12328,7 +11744,7 @@ function rememberFingerprint(db, sessionId, fingerprint) {
|
|
|
12328
11744
|
saved.set(sessionId, fingerprint);
|
|
12329
11745
|
}
|
|
12330
11746
|
function slotFingerprint(slot) {
|
|
12331
|
-
return
|
|
11747
|
+
return createHash2("sha256").update(JSON.stringify([
|
|
12332
11748
|
slot.jsonPrefix,
|
|
12333
11749
|
slot.inputIdSeq,
|
|
12334
11750
|
slot.inputContentDigests,
|
|
@@ -13141,6 +12557,7 @@ var PASS_DEGRADATION_EFFECTS = {
|
|
|
13141
12557
|
"auto-search-timeout": "served",
|
|
13142
12558
|
"auto-search-search-failure": "served",
|
|
13143
12559
|
"auto-search-cas-exhaustion": "served",
|
|
12560
|
+
"auto-search-storage-busy": "served",
|
|
13144
12561
|
"auto-search-internal-failure": "served",
|
|
13145
12562
|
"thinking-binding-recovery-persistence-failure": "changes-request",
|
|
13146
12563
|
"merged-reasoning-strip-persistence-failure": "changes-request",
|
|
@@ -13180,7 +12597,7 @@ function createPassOutcome() {
|
|
|
13180
12597
|
}
|
|
13181
12598
|
|
|
13182
12599
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
13183
|
-
import { createHash as
|
|
12600
|
+
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
13184
12601
|
|
|
13185
12602
|
// src/features/magic-context/memory/single-store-embedding-drain.ts
|
|
13186
12603
|
function isWatermarkRow(row) {
|
|
@@ -13244,7 +12661,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
|
13244
12661
|
}
|
|
13245
12662
|
|
|
13246
12663
|
// src/features/magic-context/mural/source-revision.ts
|
|
13247
|
-
import { createHash as
|
|
12664
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
13248
12665
|
var statements = new WeakMap;
|
|
13249
12666
|
function muralSourceRevision(db, projectPath) {
|
|
13250
12667
|
let statement = statements.get(db);
|
|
@@ -13261,7 +12678,7 @@ function muralSourceRevision(db, projectPath) {
|
|
|
13261
12678
|
statements.set(db, statement);
|
|
13262
12679
|
}
|
|
13263
12680
|
const row = statement.get(projectPath, Date.now());
|
|
13264
|
-
return
|
|
12681
|
+
return createHash3("sha256").update(row.revision).digest("hex");
|
|
13265
12682
|
}
|
|
13266
12683
|
|
|
13267
12684
|
// src/features/magic-context/install-instance-id.ts
|
|
@@ -13284,11 +12701,11 @@ function ensureInstallInstanceId(db) {
|
|
|
13284
12701
|
var CLAIM_START_MARGIN_MS = 5000;
|
|
13285
12702
|
var IDLE_INTERVAL_MS = 30000;
|
|
13286
12703
|
var IDLE_POLLS_AFTER_PASS = 3;
|
|
13287
|
-
function
|
|
12704
|
+
function isRecord3(value) {
|
|
13288
12705
|
return typeof value === "object" && value !== null;
|
|
13289
12706
|
}
|
|
13290
12707
|
function refusalOf(response) {
|
|
13291
|
-
if (!
|
|
12708
|
+
if (!isRecord3(response))
|
|
13292
12709
|
return "malformed_response";
|
|
13293
12710
|
if (response.ok === true)
|
|
13294
12711
|
return null;
|
|
@@ -13296,11 +12713,11 @@ function refusalOf(response) {
|
|
|
13296
12713
|
return typeof refusal === "string" && refusal.length > 0 ? refusal : "malformed_response";
|
|
13297
12714
|
}
|
|
13298
12715
|
function readPendingRuns(response) {
|
|
13299
|
-
if (!
|
|
12716
|
+
if (!isRecord3(response) || !Array.isArray(response.runs))
|
|
13300
12717
|
return [];
|
|
13301
12718
|
const runs = [];
|
|
13302
12719
|
for (const entry of response.runs) {
|
|
13303
|
-
if (!
|
|
12720
|
+
if (!isRecord3(entry))
|
|
13304
12721
|
continue;
|
|
13305
12722
|
const runId = entry.run_id;
|
|
13306
12723
|
const sessionId = entry.session_id;
|
|
@@ -13317,9 +12734,9 @@ function readPendingRuns(response) {
|
|
|
13317
12734
|
return runs;
|
|
13318
12735
|
}
|
|
13319
12736
|
function readClaim(response) {
|
|
13320
|
-
if (!
|
|
12737
|
+
if (!isRecord3(response) || response.ok !== true)
|
|
13321
12738
|
return null;
|
|
13322
|
-
const prompt =
|
|
12739
|
+
const prompt = isRecord3(response.prompt) ? response.prompt : {};
|
|
13323
12740
|
const runId = response.run_id;
|
|
13324
12741
|
const sessionId = response.session_id;
|
|
13325
12742
|
const token = response.token;
|
|
@@ -13527,17 +12944,19 @@ class HistorianHostRunner {
|
|
|
13527
12944
|
});
|
|
13528
12945
|
}
|
|
13529
12946
|
async execute(claim, abort) {
|
|
12947
|
+
const invocations = [];
|
|
13530
12948
|
const budgetMs = Math.max(1, claim.awaitBudgetMs);
|
|
13531
12949
|
const heartbeat = this.startHeartbeat(claim, abort);
|
|
13532
12950
|
const cancelDeadline = this.schedule(() => {
|
|
13533
12951
|
abort.abort(new Error(`historian host run ${claim.runId} exceeded its await budget`));
|
|
13534
12952
|
}, budgetMs);
|
|
13535
12953
|
try {
|
|
13536
|
-
const completion = await this.runCompletion(claim, budgetMs, abort.signal);
|
|
12954
|
+
const completion = await this.runCompletion(claim, budgetMs, abort.signal, invocations);
|
|
13537
12955
|
if (heartbeat.claimOver)
|
|
13538
12956
|
return;
|
|
13539
12957
|
await this.report(claim, {
|
|
13540
|
-
output: { text: completion.text, length_capped: completion.lengthCapped }
|
|
12958
|
+
output: { text: completion.text, length_capped: completion.lengthCapped },
|
|
12959
|
+
invocations
|
|
13541
12960
|
});
|
|
13542
12961
|
} catch (error) {
|
|
13543
12962
|
if (heartbeat.claimOver) {
|
|
@@ -13552,7 +12971,8 @@ class HistorianHostRunner {
|
|
|
13552
12971
|
error: {
|
|
13553
12972
|
code: failureCode(error, abort.signal.aborted),
|
|
13554
12973
|
message: describeError2(error)
|
|
13555
|
-
}
|
|
12974
|
+
},
|
|
12975
|
+
invocations
|
|
13556
12976
|
});
|
|
13557
12977
|
} finally {
|
|
13558
12978
|
cancelDeadline();
|
|
@@ -13628,7 +13048,7 @@ class HistorianHostRunner {
|
|
|
13628
13048
|
});
|
|
13629
13049
|
return failure ? `${key}: ${failure}` : null;
|
|
13630
13050
|
}
|
|
13631
|
-
async runCompletion(claim, budgetMs, signal) {
|
|
13051
|
+
async runCompletion(claim, budgetMs, signal, invocations) {
|
|
13632
13052
|
const binding = this.deps.openExecutor(claim.sessionId);
|
|
13633
13053
|
if (!binding) {
|
|
13634
13054
|
throw new Error(`no hidden completion carrier for session ${claim.sessionId}`);
|
|
@@ -13655,6 +13075,31 @@ class HistorianHostRunner {
|
|
|
13655
13075
|
});
|
|
13656
13076
|
let promptSettled = false;
|
|
13657
13077
|
let attemptStartedAt = Date.now();
|
|
13078
|
+
const withVariant = (model) => {
|
|
13079
|
+
const qualifier = this.deps.resolveVariant?.(model);
|
|
13080
|
+
return qualifier ? { model, qualifier } : model;
|
|
13081
|
+
};
|
|
13082
|
+
let attemptModel = head;
|
|
13083
|
+
let attemptRecorded = false;
|
|
13084
|
+
const recordAttempt = (completion, error) => {
|
|
13085
|
+
if (attemptRecorded)
|
|
13086
|
+
return;
|
|
13087
|
+
attemptRecorded = true;
|
|
13088
|
+
const split = attemptModel.indexOf("/");
|
|
13089
|
+
const token = (value) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
13090
|
+
invocations.push({
|
|
13091
|
+
provider_id: completion?.providerId ?? (split >= 0 ? attemptModel.slice(0, split) : null),
|
|
13092
|
+
model_id: completion?.modelId ?? (split >= 0 ? attemptModel.slice(split + 1) : attemptModel),
|
|
13093
|
+
started_at: attemptStartedAt,
|
|
13094
|
+
ended_at: Date.now(),
|
|
13095
|
+
status: error ? signal.aborted ? "aborted" : failedInvocationStatus(error) : completion?.text?.trim() ? "completed" : "empty",
|
|
13096
|
+
input_tokens: token(completion?.usage.input),
|
|
13097
|
+
output_tokens: token(completion?.usage.output),
|
|
13098
|
+
cache_read_tokens: token(completion?.usage.cacheRead),
|
|
13099
|
+
cache_write_tokens: token(completion?.usage.cacheWrite),
|
|
13100
|
+
error: error ? describeError2(error) : null
|
|
13101
|
+
});
|
|
13102
|
+
};
|
|
13658
13103
|
try {
|
|
13659
13104
|
if (!handle.id)
|
|
13660
13105
|
throw new Error("hidden completion carrier returned no session id");
|
|
@@ -13664,33 +13109,53 @@ class HistorianHostRunner {
|
|
|
13664
13109
|
body: {
|
|
13665
13110
|
agent: "historian",
|
|
13666
13111
|
system: claim.system,
|
|
13667
|
-
...modelBodyField(head),
|
|
13112
|
+
...modelBodyField(withVariant(head)),
|
|
13668
13113
|
parts: [{ type: "text", text: claim.user, synthetic: true }]
|
|
13669
13114
|
}
|
|
13670
13115
|
}, {
|
|
13671
13116
|
transport: Object.assign((request) => {
|
|
13672
13117
|
const model = request.body?.model;
|
|
13673
13118
|
const key = model?.providerID && model?.modelID ? `${model.providerID}/${model.modelID}` : head;
|
|
13674
|
-
const failure = this.admissionFailure(claim, key);
|
|
13675
|
-
if (failure)
|
|
13676
|
-
throw new Error(failure);
|
|
13677
13119
|
attemptStartedAt = Date.now();
|
|
13678
|
-
|
|
13120
|
+
attemptModel = key;
|
|
13121
|
+
attemptRecorded = false;
|
|
13122
|
+
try {
|
|
13123
|
+
const failure = this.admissionFailure(claim, key);
|
|
13124
|
+
if (failure)
|
|
13125
|
+
throw new Error(failure);
|
|
13126
|
+
return executor.attempt(handle, request).catch((error) => {
|
|
13127
|
+
recordAttempt(undefined, error);
|
|
13128
|
+
throw error;
|
|
13129
|
+
});
|
|
13130
|
+
} catch (error) {
|
|
13131
|
+
recordAttempt(undefined, error);
|
|
13132
|
+
throw error;
|
|
13133
|
+
}
|
|
13679
13134
|
}, { childSessionId: handle.childSessionId }),
|
|
13680
13135
|
timeoutMs: attemptMs,
|
|
13681
13136
|
signal,
|
|
13682
|
-
fallbackModels: rest,
|
|
13137
|
+
fallbackModels: rest.map(withVariant),
|
|
13683
13138
|
callContext: `historian-host:${claim.runId}`,
|
|
13684
|
-
fetchOutput: () => withinAttempt(executor.collect(handle, 50), attemptStartedAt + attemptMs - Date.now(), attemptMs, signal)
|
|
13139
|
+
fetchOutput: () => withinAttempt(executor.collect(handle, 50), attemptStartedAt + attemptMs - Date.now(), attemptMs, signal).catch((error) => {
|
|
13140
|
+
recordAttempt(undefined, error);
|
|
13141
|
+
throw error;
|
|
13142
|
+
}),
|
|
13685
13143
|
validateOutput: (completion) => {
|
|
13686
13144
|
const text = completion.text;
|
|
13687
|
-
if (!text)
|
|
13688
|
-
|
|
13145
|
+
if (!text?.trim()) {
|
|
13146
|
+
const error = new Error("historian host completion returned no output");
|
|
13147
|
+
recordAttempt(completion, error);
|
|
13148
|
+
throw error;
|
|
13149
|
+
}
|
|
13150
|
+
recordAttempt(completion);
|
|
13689
13151
|
return { text, lengthCapped: completion.lengthCapped === true };
|
|
13690
13152
|
}
|
|
13691
13153
|
});
|
|
13692
13154
|
promptSettled = true;
|
|
13693
13155
|
return run.validated;
|
|
13156
|
+
} catch (error) {
|
|
13157
|
+
recordAttempt(undefined, error);
|
|
13158
|
+
throw error;
|
|
13694
13159
|
} finally {
|
|
13695
13160
|
await executor.close(handle, {
|
|
13696
13161
|
promptSettled,
|
|
@@ -13717,7 +13182,7 @@ class HistorianHostRunner {
|
|
|
13717
13182
|
this.log(`report for ${claim.runId} refused: ${refusal}`);
|
|
13718
13183
|
return;
|
|
13719
13184
|
}
|
|
13720
|
-
const publish =
|
|
13185
|
+
const publish = isRecord3(response) && typeof response.publish === "string" ? response.publish : "immediate";
|
|
13721
13186
|
this.log(`report for ${claim.runId} accepted (publish=${publish})`);
|
|
13722
13187
|
}
|
|
13723
13188
|
schedule(callback, delayMs) {
|
|
@@ -13756,6 +13221,7 @@ function createHistorianHostRunner(args) {
|
|
|
13756
13221
|
enabled: args.enabled,
|
|
13757
13222
|
...args.maxOutputTokens !== undefined ? { maxOutputTokens: args.maxOutputTokens } : {},
|
|
13758
13223
|
...args.attemptTimeoutMs ? { attemptTimeoutMs: args.attemptTimeoutMs } : {},
|
|
13224
|
+
...args.resolveVariant ? { resolveVariant: args.resolveVariant } : {},
|
|
13759
13225
|
...args.now ? { now: args.now } : {},
|
|
13760
13226
|
...args.log ? { log: args.log } : {},
|
|
13761
13227
|
...args.idleIntervalMs !== undefined ? { idleIntervalMs: args.idleIntervalMs } : {},
|
|
@@ -14624,17 +14090,41 @@ function resolveSharedCompartmentBoundaries(db, sessionId) {
|
|
|
14624
14090
|
const rows = db.prepare("SELECT sequence, start_message, end_message, COALESCE(start_message_id, '') AS start_message_id, COALESCE(end_message_id, '') AS end_message_id, start_block_index, end_block_index FROM compartments WHERE session_id=? ORDER BY sequence").all(sessionId);
|
|
14625
14091
|
if (rows.every((row) => row.start_block_index !== null && row.end_block_index !== null))
|
|
14626
14092
|
return [];
|
|
14627
|
-
|
|
14628
|
-
const
|
|
14093
|
+
let ordinalBasis;
|
|
14094
|
+
const ordinals = () => {
|
|
14095
|
+
ordinalBasis ??= readRawSessionMessageIdOrdinalsForRange2(sessionId, 1, Number.MAX_SAFE_INTEGER);
|
|
14096
|
+
return ordinalBasis;
|
|
14097
|
+
};
|
|
14098
|
+
const stored = readRawSessionBoundaryEndpoints2(sessionId, rows.flatMap((row) => [row.start_message_id, row.end_message_id]), rows.flatMap((row) => row.end_block_index === null ? [row.end_message_id] : []));
|
|
14099
|
+
const providerRaw = new Map;
|
|
14629
14100
|
const endpoint = (rawId, blockIndex, edge) => {
|
|
14630
|
-
|
|
14631
|
-
|
|
14632
|
-
|
|
14633
|
-
|
|
14634
|
-
|
|
14635
|
-
|
|
14636
|
-
|
|
14637
|
-
|
|
14101
|
+
const needsLastBlock = blockIndex === null && edge === "end";
|
|
14102
|
+
let ordinal;
|
|
14103
|
+
let createdAt;
|
|
14104
|
+
let lastBlockIndex = 0;
|
|
14105
|
+
if (stored === null) {
|
|
14106
|
+
if (!providerRaw.has(rawId))
|
|
14107
|
+
providerRaw.set(rawId, readRawSessionMessagePartsById2(sessionId, rawId));
|
|
14108
|
+
const raw = providerRaw.get(rawId) ?? null;
|
|
14109
|
+
ordinal = raw?.id === rawId ? ordinals().get(rawId) ?? null : null;
|
|
14110
|
+
createdAt = raw?.createdAt;
|
|
14111
|
+
if (needsLastBlock)
|
|
14112
|
+
lastBlockIndex = moduleRawBlockMappings(raw).at(-1)?.blockIndex ?? 0;
|
|
14113
|
+
} else {
|
|
14114
|
+
let read = stored.get(rawId);
|
|
14115
|
+
if (read === undefined || needsLastBlock && read && read.lastBlockIndex === undefined) {
|
|
14116
|
+
read = readRawSessionBoundaryEndpoints2(sessionId, [rawId], needsLastBlock ? [rawId] : [])?.get(rawId) ?? null;
|
|
14117
|
+
stored.set(rawId, read);
|
|
14118
|
+
}
|
|
14119
|
+
ordinal = read?.ordinal ?? null;
|
|
14120
|
+
createdAt = read?.createdAt;
|
|
14121
|
+
if (needsLastBlock)
|
|
14122
|
+
lastBlockIndex = read?.lastBlockIndex ?? 0;
|
|
14123
|
+
}
|
|
14124
|
+
const block = blockIndex !== null ? blockIndex : edge === "start" ? 0 : lastBlockIndex;
|
|
14125
|
+
return { ordinal, id: `${rawId}#${block}`, createdAt };
|
|
14126
|
+
};
|
|
14127
|
+
const idsByOrdinal = rows.some((row) => !row.start_message_id || !row.end_message_id) ? new Map([...ordinals()].map(([id, ordinal]) => [ordinal, id])) : null;
|
|
14638
14128
|
const endpoints = rows.map((row) => ({
|
|
14639
14129
|
start: endpoint(row.start_message_id, row.start_block_index, "start"),
|
|
14640
14130
|
end: endpoint(row.end_message_id, row.end_block_index, "end")
|
|
@@ -14666,9 +14156,9 @@ function resolveSharedCompartmentBoundaries(db, sessionId) {
|
|
|
14666
14156
|
start = resolveMissingId(row.start_message_id, row.start_block_index, startOrdinal, "start");
|
|
14667
14157
|
if (!row.end_message_id)
|
|
14668
14158
|
end = resolveMissingId(row.end_message_id, row.end_block_index, endOrdinal, "end");
|
|
14669
|
-
const dates = typeof start.
|
|
14670
|
-
start_date: formatDate(start.
|
|
14671
|
-
end_date: formatDate(end.
|
|
14159
|
+
const dates = typeof start.createdAt === "number" && typeof end.createdAt === "number" ? {
|
|
14160
|
+
start_date: formatDate(start.createdAt),
|
|
14161
|
+
end_date: formatDate(end.createdAt)
|
|
14672
14162
|
} : { start_date: null, end_date: null };
|
|
14673
14163
|
return {
|
|
14674
14164
|
sequence: row.sequence,
|
|
@@ -15662,6 +15152,9 @@ class FrozenReplayOverProvenLimitRefusal extends Error {
|
|
|
15662
15152
|
}
|
|
15663
15153
|
}
|
|
15664
15154
|
var RUST_FAILURE_PARK_THRESHOLD = 3;
|
|
15155
|
+
var TRANSFORM_FINAL_PAGE_ABANDONED_CODE = "transform_final_page_abandoned";
|
|
15156
|
+
var TRANSFORM_PAGE_IN_PROGRESS_CODE = "authority_transform_page_in_progress";
|
|
15157
|
+
var RUST_IN_PROGRESS_PARK_EXEMPTION_MS = 5 * 60000;
|
|
15665
15158
|
var RUST_PARK_RETRY_INTERVAL = 5;
|
|
15666
15159
|
var RUST_EMERGENCY_WALL_PCT = 95;
|
|
15667
15160
|
var RUST_PARK_PROBE_PRESSURE_BYPASS_PCT = 90;
|
|
@@ -15738,20 +15231,20 @@ function rustWireCacheEstimatedBytes(cache) {
|
|
|
15738
15231
|
}
|
|
15739
15232
|
return bytes;
|
|
15740
15233
|
}
|
|
15741
|
-
function
|
|
15234
|
+
function isRecord4(value) {
|
|
15742
15235
|
return value !== null && typeof value === "object";
|
|
15743
15236
|
}
|
|
15744
15237
|
function moduleFailureCode(error) {
|
|
15745
15238
|
let current = error;
|
|
15746
15239
|
const seen = new Set;
|
|
15747
|
-
while (
|
|
15240
|
+
while (isRecord4(current) && !seen.has(current)) {
|
|
15748
15241
|
seen.add(current);
|
|
15749
15242
|
if (typeof current.code === "string" && current.code.length > 0)
|
|
15750
15243
|
return current.code;
|
|
15751
15244
|
if (typeof current.message === "string") {
|
|
15752
15245
|
try {
|
|
15753
15246
|
const detail = JSON.parse(current.message);
|
|
15754
|
-
if (
|
|
15247
|
+
if (isRecord4(detail) && typeof detail.code === "string")
|
|
15755
15248
|
return detail.code;
|
|
15756
15249
|
} catch {}
|
|
15757
15250
|
}
|
|
@@ -15762,6 +15255,10 @@ function moduleFailureCode(error) {
|
|
|
15762
15255
|
function isNonRetryableStateSyncFailure(error) {
|
|
15763
15256
|
return moduleFailureCode(error) === "state_sync_non_retryable";
|
|
15764
15257
|
}
|
|
15258
|
+
function isModuleBusyWithAbandonedTransform(error) {
|
|
15259
|
+
const code = moduleFailureCode(error);
|
|
15260
|
+
return code === TRANSFORM_FINAL_PAGE_ABANDONED_CODE || code === TRANSFORM_PAGE_IN_PROGRESS_CODE;
|
|
15261
|
+
}
|
|
15765
15262
|
function replaceMessagesInPlace(output, next) {
|
|
15766
15263
|
const target = output.messages;
|
|
15767
15264
|
if (target !== next)
|
|
@@ -15769,9 +15266,9 @@ function replaceMessagesInPlace(output, next) {
|
|
|
15769
15266
|
return target;
|
|
15770
15267
|
}
|
|
15771
15268
|
function messageInfo2(value) {
|
|
15772
|
-
if (!
|
|
15269
|
+
if (!isRecord4(value))
|
|
15773
15270
|
return {};
|
|
15774
|
-
return
|
|
15271
|
+
return isRecord4(value.info) ? value.info : value;
|
|
15775
15272
|
}
|
|
15776
15273
|
function messageIdOf2(message) {
|
|
15777
15274
|
const id = messageInfo2(message).id;
|
|
@@ -15832,10 +15329,10 @@ function messageCacheSignature(message) {
|
|
|
15832
15329
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
15833
15330
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
15834
15331
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
15835
|
-
return `${messageIdOf2(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${
|
|
15332
|
+
return `${messageIdOf2(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash5("sha256").update(serializedMessage).digest("hex")}`;
|
|
15836
15333
|
}
|
|
15837
15334
|
function advanceWireFingerprint(previous, encoded) {
|
|
15838
|
-
return
|
|
15335
|
+
return createHash5("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
15839
15336
|
}
|
|
15840
15337
|
function buildWireFingerprint(encoded) {
|
|
15841
15338
|
let fingerprint = "rust-wire-v1";
|
|
@@ -15941,7 +15438,7 @@ function isSyntheticUserMessage(message) {
|
|
|
15941
15438
|
if (!message || messageInfo2(message).role !== "user" || !Array.isArray(message.parts)) {
|
|
15942
15439
|
return false;
|
|
15943
15440
|
}
|
|
15944
|
-
return message.parts.length > 0 && message.parts.every((part) =>
|
|
15441
|
+
return message.parts.length > 0 && message.parts.every((part) => isRecord4(part) && (part.synthetic === true || part.ignored === true));
|
|
15945
15442
|
}
|
|
15946
15443
|
function observeSyntheticTurn(state, messages) {
|
|
15947
15444
|
const newest = newestUserMessage(messages);
|
|
@@ -15961,25 +15458,25 @@ function observeSyntheticTurn(state, messages) {
|
|
|
15961
15458
|
function assertNativeBoundary(output, sessionId, boundaryId) {
|
|
15962
15459
|
const first = output.find((message) => messageInfo2(message).role !== "system");
|
|
15963
15460
|
const info = messageInfo2(first);
|
|
15964
|
-
const parts =
|
|
15965
|
-
const synthetic = parts.length > 0 && parts.every((part) =>
|
|
15461
|
+
const parts = isRecord4(first) && Array.isArray(first.parts) ? first.parts : [];
|
|
15462
|
+
const synthetic = parts.length > 0 && parts.every((part) => isRecord4(part) && part.synthetic === true);
|
|
15966
15463
|
if (info.role === "user" && info.sessionID === sessionId && synthetic)
|
|
15967
15464
|
return;
|
|
15968
15465
|
const headSummary = output.slice(0, 3).map((message) => {
|
|
15969
15466
|
const mi = messageInfo2(message);
|
|
15970
|
-
const mParts =
|
|
15971
|
-
const partDesc = mParts.slice(0, 5).map((part) =>
|
|
15467
|
+
const mParts = isRecord4(message) && Array.isArray(message.parts) ? message.parts : [];
|
|
15468
|
+
const partDesc = mParts.slice(0, 5).map((part) => isRecord4(part) ? `${String(part.type)}${part.synthetic === true ? "" : "!"}` : "?").join(",");
|
|
15972
15469
|
return `role=${String(mi.role)} sid=${mi.sessionID === sessionId ? "ok" : String(mi.sessionID ?? "absent")} id=${String(mi.id ?? "-").slice(0, 24)} parts=[${partDesc}]`;
|
|
15973
15470
|
});
|
|
15974
15471
|
throw new Error(`rust transform wire invariant failed: boundary=${boundaryId} expected a synthetic m0 user message scoped to session ${sessionId}; head: ${headSummary.join(" | ")}`);
|
|
15975
15472
|
}
|
|
15976
15473
|
function responseValue(response) {
|
|
15977
|
-
if (
|
|
15474
|
+
if (isRecord4(response) && (response.ok === false || response.isError === true || response.error != null)) {
|
|
15978
15475
|
throw new RustTransformProtocolError("rust transform wire invariant failed: error envelope cannot permit host mutations");
|
|
15979
15476
|
}
|
|
15980
|
-
if (
|
|
15477
|
+
if (isRecord4(response) && isRecord4(response.result))
|
|
15981
15478
|
return response.result;
|
|
15982
|
-
if (
|
|
15479
|
+
if (isRecord4(response))
|
|
15983
15480
|
return response;
|
|
15984
15481
|
throw new Error("module transform returned a non-object response");
|
|
15985
15482
|
}
|
|
@@ -16011,7 +15508,7 @@ function stateSyncInputSignature(args) {
|
|
|
16011
15508
|
function isTransformPageAttemptMismatch(error) {
|
|
16012
15509
|
let current = error;
|
|
16013
15510
|
const seen = new Set;
|
|
16014
|
-
while (
|
|
15511
|
+
while (isRecord4(current) && !seen.has(current)) {
|
|
16015
15512
|
seen.add(current);
|
|
16016
15513
|
const code = typeof current.code === "string" ? current.code : "";
|
|
16017
15514
|
const message = typeof current.message === "string" ? current.message : "";
|
|
@@ -16038,7 +15535,7 @@ function mirrorRustRenderedMemoryIds(args) {
|
|
|
16038
15535
|
function modelFromMessages(messages) {
|
|
16039
15536
|
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
16040
15537
|
const info = messages[index]?.info;
|
|
16041
|
-
const model =
|
|
15538
|
+
const model = isRecord4(info?.model) ? info.model : undefined;
|
|
16042
15539
|
if (typeof model?.providerID === "string" && typeof model.modelID === "string") {
|
|
16043
15540
|
return { providerID: model.providerID, modelID: model.modelID };
|
|
16044
15541
|
}
|
|
@@ -16059,6 +15556,7 @@ function ensureState(states, sessionId) {
|
|
|
16059
15556
|
passesSincePark: 0,
|
|
16060
15557
|
warningSent: false,
|
|
16061
15558
|
forceFullWire: false,
|
|
15559
|
+
transformInProgressSinceMs: null,
|
|
16062
15560
|
ordinalMemoAnchor: null,
|
|
16063
15561
|
ordinalMemoStoredCount: null,
|
|
16064
15562
|
ordinalMemoCanonicalCount: 0,
|
|
@@ -16192,8 +15690,8 @@ function shouldDisarmRustEmergencyRecovery(input) {
|
|
|
16192
15690
|
return null;
|
|
16193
15691
|
}
|
|
16194
15692
|
function directiveTextOf(response) {
|
|
16195
|
-
const directives =
|
|
16196
|
-
const channel2 =
|
|
15693
|
+
const directives = isRecord4(response.host_directives) ? response.host_directives : undefined;
|
|
15694
|
+
const channel2 = isRecord4(directives?.channel2_nudge) ? directives.channel2_nudge : undefined;
|
|
16197
15695
|
return typeof channel2?.text === "string" && channel2.text.length > 0 ? channel2.text : undefined;
|
|
16198
15696
|
}
|
|
16199
15697
|
function isNeedFullSync(response) {
|
|
@@ -16203,18 +15701,18 @@ var TODO_HEAD_ANCHOR_ID2 = "__magic_context_todo_head__";
|
|
|
16203
15701
|
function syntheticTodoAnchorFromNative(messages) {
|
|
16204
15702
|
for (let index = 0;index < messages.length; index += 1) {
|
|
16205
15703
|
const message = messages[index];
|
|
16206
|
-
if (!
|
|
15704
|
+
if (!isRecord4(message) || !Array.isArray(message.parts))
|
|
16207
15705
|
continue;
|
|
16208
|
-
const part = message.parts.find((candidate) =>
|
|
16209
|
-
if (!
|
|
15706
|
+
const part = message.parts.find((candidate) => isRecord4(candidate) && candidate.syntheticTodoMarker === true);
|
|
15707
|
+
if (!isRecord4(part) || typeof part.callID !== "string")
|
|
16210
15708
|
continue;
|
|
16211
|
-
const state =
|
|
16212
|
-
const input = state &&
|
|
15709
|
+
const state = isRecord4(part.state) ? part.state : undefined;
|
|
15710
|
+
const input = state && isRecord4(state.input) ? state.input : undefined;
|
|
16213
15711
|
const stateJson = normalizeTodoStateJson(input?.todos);
|
|
16214
15712
|
if (stateJson === null || computeSyntheticCallId(stateJson) !== part.callID)
|
|
16215
15713
|
continue;
|
|
16216
15714
|
const previous = messages[index - 1];
|
|
16217
|
-
const previousInfo =
|
|
15715
|
+
const previousInfo = isRecord4(previous) && isRecord4(previous.info) ? previous.info : undefined;
|
|
16218
15716
|
const messageId = previousInfo && typeof previousInfo.id === "string" && previousInfo.id.length > 0 ? previousInfo.id : TODO_HEAD_ANCHOR_ID2;
|
|
16219
15717
|
return { callId: part.callID, messageId, stateJson };
|
|
16220
15718
|
}
|
|
@@ -16243,7 +15741,7 @@ function hasNativeResponseContent(response) {
|
|
|
16243
15741
|
return true;
|
|
16244
15742
|
}
|
|
16245
15743
|
const delta = response.native_messages_delta;
|
|
16246
|
-
return
|
|
15744
|
+
return isRecord4(delta) && Array.isArray(delta.messages);
|
|
16247
15745
|
}
|
|
16248
15746
|
function applyNativeMessagesVerbatim(output, response, previous) {
|
|
16249
15747
|
const nativeMessages = response.native_messages;
|
|
@@ -16257,7 +15755,7 @@ function applyNativeMessagesVerbatim(output, response, previous) {
|
|
|
16257
15755
|
return replaceMessagesInPlace(output, nativeMessages);
|
|
16258
15756
|
}
|
|
16259
15757
|
const delta = response.native_messages_delta;
|
|
16260
|
-
if (!
|
|
15758
|
+
if (!isRecord4(delta) || !Array.isArray(delta.messages)) {
|
|
16261
15759
|
throw new Error("rust transform response omitted native_messages");
|
|
16262
15760
|
}
|
|
16263
15761
|
const replaceFrom = delta.replace_from;
|
|
@@ -16458,7 +15956,14 @@ function createRustModeTransform(deps, options) {
|
|
|
16458
15956
|
sessionDirectory: (sessionId) => deps.sessionDirectoryBySession?.get(sessionId) ?? deps.directory ?? process.cwd(),
|
|
16459
15957
|
enabled: () => deps.historianHostRunnerEnabled !== false,
|
|
16460
15958
|
...deps.historianMaxOutputTokens !== undefined ? { maxOutputTokens: deps.historianMaxOutputTokens } : {},
|
|
16461
|
-
attemptTimeoutMs: () => deps.resolveHistorianRun?.().timeoutMs ?? deps.historianTimeoutMs
|
|
15959
|
+
attemptTimeoutMs: () => deps.resolveHistorianRun?.().timeoutMs ?? deps.historianTimeoutMs,
|
|
15960
|
+
resolveVariant: (model) => {
|
|
15961
|
+
const run = deps.resolveHistorianRun?.();
|
|
15962
|
+
return resolvedHistorianModelVariants({
|
|
15963
|
+
historianModel: run?.model ?? deps.historianModel,
|
|
15964
|
+
fallbackModels: run?.fallbackModels ?? deps.fallbackModels
|
|
15965
|
+
})[model];
|
|
15966
|
+
}
|
|
16462
15967
|
});
|
|
16463
15968
|
} catch (error) {
|
|
16464
15969
|
hostRunner = undefined;
|
|
@@ -16497,7 +16002,7 @@ function createRustModeTransform(deps, options) {
|
|
|
16497
16002
|
};
|
|
16498
16003
|
const callModule = async (args, attemptTimeoutMs = args.timeoutMs ?? timeoutMs, allowTimeoutRetry = true) => {
|
|
16499
16004
|
const controller = new AbortController;
|
|
16500
|
-
const body =
|
|
16005
|
+
const body = isRecord4(args.body) ? args.body : {};
|
|
16501
16006
|
const timeoutError = args.method === "state_sync" ? Object.assign(new Error(`state_sync timeout stage=module_ack page=${body.seed_batch_index ?? 0}/${body.seed_batch_total ?? 1} series=${body.seed_id ?? "delta"} budget_ms=${attemptTimeoutMs}`), {
|
|
16502
16007
|
code: "state_sync_timeout",
|
|
16503
16008
|
stage: "module_ack",
|
|
@@ -16528,18 +16033,24 @@ function createRustModeTransform(deps, options) {
|
|
|
16528
16033
|
clock.clearTimeout(timer);
|
|
16529
16034
|
sessionLog2(args.sessionId, "rust transform deadline: waiting up to 45000ms for identical final-page completion");
|
|
16530
16035
|
const completionDeadline = clock.now() + 45000;
|
|
16036
|
+
const abandoned = (cause) => Object.assign(new Error(timeoutError.message, { cause }), {
|
|
16037
|
+
code: TRANSFORM_FINAL_PAGE_ABANDONED_CODE
|
|
16038
|
+
});
|
|
16531
16039
|
for (;; ) {
|
|
16532
16040
|
const remaining = completionDeadline - clock.now();
|
|
16533
16041
|
if (remaining <= 0)
|
|
16534
|
-
throw timeoutError;
|
|
16042
|
+
throw abandoned(timeoutError);
|
|
16535
16043
|
try {
|
|
16536
16044
|
return await callModule(args, remaining, false);
|
|
16537
16045
|
} catch (retryError) {
|
|
16538
|
-
if (moduleFailureCode(retryError) !==
|
|
16046
|
+
if (moduleFailureCode(retryError) !== TRANSFORM_PAGE_IN_PROGRESS_CODE) {
|
|
16047
|
+
if (retryError instanceof Error && /timed out|deadline/i.test(retryError.message))
|
|
16048
|
+
throw abandoned(retryError);
|
|
16539
16049
|
throw retryError;
|
|
16050
|
+
}
|
|
16540
16051
|
const wait = Math.min(250, completionDeadline - clock.now());
|
|
16541
16052
|
if (wait <= 0)
|
|
16542
|
-
throw
|
|
16053
|
+
throw abandoned(retryError);
|
|
16543
16054
|
await new Promise((resolve) => clock.setTimeout(resolve, wait));
|
|
16544
16055
|
}
|
|
16545
16056
|
}
|
|
@@ -16557,7 +16068,7 @@ function createRustModeTransform(deps, options) {
|
|
|
16557
16068
|
const probeAfterMs = options.stallProbeAfterMsForTests ?? RUST_STALL_PROBE_AFTER_MS;
|
|
16558
16069
|
const probeTimeoutMs = options.healthProbeTimeoutMsForTests ?? RUST_HEALTH_PROBE_TIMEOUT_MS;
|
|
16559
16070
|
const originalAttemptId = randomUUID2();
|
|
16560
|
-
const originalBody =
|
|
16071
|
+
const originalBody = isRecord4(args.body) ? { ...args.body, attempt_id: originalAttemptId } : args.body;
|
|
16561
16072
|
const original = callModule({ ...args, body: originalBody }, attemptTimeoutMs);
|
|
16562
16073
|
if (attemptTimeoutMs <= probeAfterMs)
|
|
16563
16074
|
return original;
|
|
@@ -16595,7 +16106,24 @@ function createRustModeTransform(deps, options) {
|
|
|
16595
16106
|
sessionLog2(args.sessionId, `rust transform still pending after healthy probe original_attempt=${originalAttemptId} stall_ms=${clock.now() - startedAtMs}; duplicate resend suppressed`);
|
|
16596
16107
|
return original;
|
|
16597
16108
|
};
|
|
16109
|
+
const inProgressRunWithinBound = (state) => state.transformInProgressSinceMs !== null && clock.now() - state.transformInProgressSinceMs <= RUST_IN_PROGRESS_PARK_EXEMPTION_MS;
|
|
16110
|
+
const exemptInProgressRefusal = (state, error) => {
|
|
16111
|
+
if (moduleFailureCode(error) !== TRANSFORM_PAGE_IN_PROGRESS_CODE) {
|
|
16112
|
+
state.transformInProgressSinceMs = null;
|
|
16113
|
+
return false;
|
|
16114
|
+
}
|
|
16115
|
+
state.transformInProgressSinceMs ??= clock.now();
|
|
16116
|
+
return inProgressRunWithinBound(state);
|
|
16117
|
+
};
|
|
16598
16118
|
const markFailure = (sessionId, state, error) => {
|
|
16119
|
+
if (isModuleBusyWithAbandonedTransform(error)) {
|
|
16120
|
+
state.forceFullWire = true;
|
|
16121
|
+
}
|
|
16122
|
+
if (exemptInProgressRefusal(state, error)) {
|
|
16123
|
+
state.failureCount += 1;
|
|
16124
|
+
sessionLog2(sessionId, "rust transform deferred; the module is still applying an earlier transform of this session; attempting LKG replay:", error);
|
|
16125
|
+
return;
|
|
16126
|
+
}
|
|
16599
16127
|
state.consecutiveFailures = isNonRetryableStateSyncFailure(error) ? Math.max(RUST_FAILURE_PARK_THRESHOLD, state.consecutiveFailures + 1) : state.consecutiveFailures + 1;
|
|
16600
16128
|
state.failureCount += 1;
|
|
16601
16129
|
sessionLog2(sessionId, "rust transform failed; attempting LKG replay:", error);
|
|
@@ -16944,6 +16472,7 @@ function createRustModeTransform(deps, options) {
|
|
|
16944
16472
|
let requestInputTokens = 0;
|
|
16945
16473
|
let decision = "error";
|
|
16946
16474
|
let materializeReason = "none";
|
|
16475
|
+
let frozenReleaseReason = null;
|
|
16947
16476
|
let schedulerDecision;
|
|
16948
16477
|
let responseCommitted;
|
|
16949
16478
|
let responsePrefixBustPermitted;
|
|
@@ -17043,6 +16572,9 @@ function createRustModeTransform(deps, options) {
|
|
|
17043
16572
|
if (moduleFailureCode(cause) === "transform_transport_interrupted") {
|
|
17044
16573
|
throw new EmergencyFailClosedError(ENGINE_RECONNECTING_USER_MESSAGE, { cause });
|
|
17045
16574
|
}
|
|
16575
|
+
if (isModuleBusyWithAbandonedTransform(cause)) {
|
|
16576
|
+
throw new EmergencyFailClosedError(moduleFailureCode(cause) === TRANSFORM_PAGE_IN_PROGRESS_CODE ? ENGINE_BUSY_USER_MESSAGE : ENGINE_RECONNECTING_USER_MESSAGE, { cause });
|
|
16577
|
+
}
|
|
17046
16578
|
if (!deps.compactionOff && isTransientSqliteError2(cause)) {
|
|
17047
16579
|
throw new StorageBusyRefusalError(cause, "rust-mode-transform");
|
|
17048
16580
|
}
|
|
@@ -17181,7 +16713,8 @@ function createRustModeTransform(deps, options) {
|
|
|
17181
16713
|
decision,
|
|
17182
16714
|
materializeReason: materializeReason === "none" ? null : materializeReason,
|
|
17183
16715
|
inputTokens: requestInputTokens,
|
|
17184
|
-
tsMs: passObservedAtMs
|
|
16716
|
+
tsMs: passObservedAtMs,
|
|
16717
|
+
lkgFrozenReleaseReason: applied && served ? frozenReleaseReason ?? undefined : undefined
|
|
17185
16718
|
});
|
|
17186
16719
|
}
|
|
17187
16720
|
};
|
|
@@ -17192,12 +16725,12 @@ function createRustModeTransform(deps, options) {
|
|
|
17192
16725
|
servedFrom = typeof response.served_from === "string" ? response.served_from : "unknown";
|
|
17193
16726
|
schedulerDecision = typeof response.scheduler_decision === "string" ? response.scheduler_decision : undefined;
|
|
17194
16727
|
schedulerDeferReason = typeof response.scheduler_defer_reason === "string" ? response.scheduler_defer_reason : undefined;
|
|
17195
|
-
const historian =
|
|
16728
|
+
const historian = isRecord4(response.historian) ? response.historian : undefined;
|
|
17196
16729
|
historianNoFire = typeof historian?.no_fire === "string" ? historian.no_fire : undefined;
|
|
17197
16730
|
historianCanonicalCause = typeof historian?.canonical_cause === "string" ? historian.canonical_cause : undefined;
|
|
17198
16731
|
materializeReason = typeof response.materialize_reason === "string" && response.materialize_reason.length > 0 ? response.materialize_reason : "none";
|
|
17199
16732
|
identityDelta = Array.isArray(response.identity_delta) ? response.identity_delta.filter((component) => typeof component === "string" && component.length > 0) : [];
|
|
17200
|
-
const timings =
|
|
16733
|
+
const timings = isRecord4(response.timings) ? response.timings : undefined;
|
|
17201
16734
|
const applyOnceTotal = timings?.total;
|
|
17202
16735
|
const handlerTotal = timings?.handler_total;
|
|
17203
16736
|
moduleElapsedMs = typeof handlerTotal === "number" && Number.isFinite(handlerTotal) ? handlerTotal : typeof applyOnceTotal === "number" && Number.isFinite(applyOnceTotal) ? applyOnceTotal : 0;
|
|
@@ -17499,9 +17032,9 @@ function createRustModeTransform(deps, options) {
|
|
|
17499
17032
|
const todoCalls = wireDelta ? new Map(state.todoCallSignatures) : new Map;
|
|
17500
17033
|
for (const [offset, message] of todoCandidates.entries()) {
|
|
17501
17034
|
const id = messageIdOf2(message) ?? `index:${todoStart + offset}`;
|
|
17502
|
-
const parts = message.parts?.filter((part) =>
|
|
17035
|
+
const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
|
|
17503
17036
|
if (parts?.length) {
|
|
17504
|
-
todoCalls.set(id,
|
|
17037
|
+
todoCalls.set(id, createHash5("sha256").update(JSON.stringify(parts)).digest("hex"));
|
|
17505
17038
|
} else {
|
|
17506
17039
|
todoCalls.delete(id);
|
|
17507
17040
|
}
|
|
@@ -17672,7 +17205,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17672
17205
|
logStage(sessionId, "wireBuild", wireBuildStartedAt, timings, wireDelta ? `mode=tail_delta input=${encodedInput.length}` : "mode=full");
|
|
17673
17206
|
const sendTransformSeries = async (payload, detail = "") => {
|
|
17674
17207
|
const pagingStartedAt = performance.now();
|
|
17675
|
-
const fullWire = !
|
|
17208
|
+
const fullWire = !isRecord4(payload.tail_delta);
|
|
17676
17209
|
const pages = buildPagedModuleTransformPayloads(payload, options.modulePageMaxBytes, true);
|
|
17677
17210
|
timings.paging += performance.now() - pagingStartedAt;
|
|
17678
17211
|
const seedMessageCount = Array.isArray(payload.input) ? payload.input.length : Array.isArray(payload.messages) ? payload.messages.length : 0;
|
|
@@ -17730,6 +17263,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17730
17263
|
}
|
|
17731
17264
|
if (!response)
|
|
17732
17265
|
throw new Error("rust module returned no transform response");
|
|
17266
|
+
state.transformInProgressSinceMs = null;
|
|
17733
17267
|
return { response };
|
|
17734
17268
|
};
|
|
17735
17269
|
let transformSeriesRestarted = false;
|
|
@@ -17756,7 +17290,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17756
17290
|
body: { method: "session.flush", v: 1, session_id: sessionId },
|
|
17757
17291
|
timeoutMs: options.moduleTimeoutMs
|
|
17758
17292
|
});
|
|
17759
|
-
if (!
|
|
17293
|
+
if (!isRecord4(flushed) || flushed.ok !== true)
|
|
17760
17294
|
throw new RustTransformProtocolError("rust marker admission recovery: module did not acknowledge rebuilding the new cut");
|
|
17761
17295
|
}
|
|
17762
17296
|
let response = await sendTransformSeriesWithSingleRestart(body);
|
|
@@ -17889,6 +17423,20 @@ function createRustModeTransform(deps, options) {
|
|
|
17889
17423
|
if (moduleDecisionBusts && decisionUpper === "SOFT+") {
|
|
17890
17424
|
throw new RustTransformProtocolError("rust transform wire invariant failed: SOFT+ cannot permit a prefix bust");
|
|
17891
17425
|
}
|
|
17426
|
+
const signedThinkingReset = moduleDecisionBusts && response.signed_thinking_reset === true;
|
|
17427
|
+
if (signedThinkingReset) {
|
|
17428
|
+
const fenced = findReasoningBearingAssistantIds(messages);
|
|
17429
|
+
let recorded = false;
|
|
17430
|
+
try {
|
|
17431
|
+
recorded = addMergedReasoningStrippedIds(deps.db, sessionId, fenced.map(thinkingBindingRecoveryFrozenId));
|
|
17432
|
+
} catch (error) {
|
|
17433
|
+
sessionLog2(sessionId, "signed thinking reset fence: persistence threw:", error);
|
|
17434
|
+
}
|
|
17435
|
+
if (!recorded) {
|
|
17436
|
+
throw new EmergencyFailClosedError(SIGNED_THINKING_RESET_FENCE_FAILED);
|
|
17437
|
+
}
|
|
17438
|
+
sessionLog2(sessionId, `signed thinking reset fence: ${fenced.length} assistant(s) [${fenced.join(",")}]`);
|
|
17439
|
+
}
|
|
17892
17440
|
const cacheBustingPass = moduleDecisionBusts;
|
|
17893
17441
|
let frozenReplayReleased = false;
|
|
17894
17442
|
if (markerAdmissionRecovery && !moduleDecisionBusts)
|
|
@@ -17902,7 +17450,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17902
17450
|
timings.todoUnprobedBust += 1;
|
|
17903
17451
|
sessionLog2(sessionId, `todo_permission_probe_miss decision=${decisionUpper} reason=${response.materialize_reason ?? "unknown"} verdict_stale_ok=false`);
|
|
17904
17452
|
}
|
|
17905
|
-
const deferredFirstDivergence =
|
|
17453
|
+
const deferredFirstDivergence = isRecord4(response.first_divergence) ? response.first_divergence : undefined;
|
|
17906
17454
|
const deferredFrozenPrefixDivergence = !cacheBustingPass && [deferredFirstDivergence?.block_id_old, deferredFirstDivergence?.block_id_new].some((blockId) => blockId === "mc_m0#0" || blockId === "mc_m1#0");
|
|
17907
17455
|
if (deferredFrozenPrefixDivergence) {
|
|
17908
17456
|
state.lkgRepresentationFrozen = true;
|
|
@@ -17912,7 +17460,6 @@ function createRustModeTransform(deps, options) {
|
|
|
17912
17460
|
const materializedBoundary = materializedCompactionBoundary(response, moduleDecisionBusts);
|
|
17913
17461
|
let thinkingBindingRecovery = null;
|
|
17914
17462
|
let frozenHealthyPassesAfterApply = null;
|
|
17915
|
-
let frozenReleaseReason = null;
|
|
17916
17463
|
const applyStartedAt = performance.now();
|
|
17917
17464
|
try {
|
|
17918
17465
|
const moduleMessages = applyNativeMessagesVerbatim({ messages: [] }, response, previousWireCache?.nativeOutput ? {
|
|
@@ -18061,6 +17608,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18061
17608
|
cacheBustingPass: moduleDecisionBusts,
|
|
18062
17609
|
prefixPermissionSupported: permissionSupported,
|
|
18063
17610
|
moduleReasoningTrimOnly: response.reasoning_trim_only === true,
|
|
17611
|
+
moduleSignedThinkingReset: response.signed_thinking_reset === true,
|
|
18064
17612
|
...permissionSupported && (passStartedFrozen || frozenReleaseReason || coldStartLastServed) ? { frozenReleaseLastServed } : {},
|
|
18065
17613
|
trailingBlankSourceDecisions,
|
|
18066
17614
|
trailingBlankNewestAssistantId: typeof trailingBlankNewestAssistantId === "string" ? trailingBlankNewestAssistantId : undefined,
|
|
@@ -18095,7 +17643,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18095
17643
|
agentName: deps.getNotificationParams?.(sessionId)?.agent,
|
|
18096
17644
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
18097
17645
|
}, resolvedWindowGeometry?.usableHard ?? resolvedContextLimit);
|
|
18098
|
-
const refusal = outgoingContextRefusal(servedFinalWireEstimate, resolvedWindowGeometry?.usableHard ?? resolvedContextLimit, protectedToolTokenCount(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools, resolveDecisionCalibration(model?.providerID, model?.modelID)));
|
|
17646
|
+
const refusal = outgoingContextRefusal(servedFinalWireEstimate, resolvedWindowGeometry?.usableHard ?? resolvedContextLimit, protectedToolTokenCount(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools, resolveDecisionCalibration(model?.providerID, model?.modelID))) ?? (signedThinkingReset ? signedTurnContextRefusal(servedFinalWireEstimate, resolvedWindowGeometry?.usableHard ?? resolvedContextLimit) : undefined);
|
|
18099
17647
|
if (refusal) {
|
|
18100
17648
|
if (cacheBustingPass) {
|
|
18101
17649
|
dropSlot(sessionId, "lkg_over_limit_replacement");
|
|
@@ -18118,6 +17666,8 @@ function createRustModeTransform(deps, options) {
|
|
|
18118
17666
|
}
|
|
18119
17667
|
const lkgSnapshotStartedAt = performance.now();
|
|
18120
17668
|
const synchronousReplacement = shouldAdoptModuleAfterFreeze(moduleDecisionBusts, frozenReplayReleased) || !permissionSupported;
|
|
17669
|
+
if (signedThinkingReset)
|
|
17670
|
+
options.afterSignedThinkingResetFenceForTests?.(sessionId);
|
|
18121
17671
|
if (synchronousReplacement && !markerDefinitelyNoCut) {
|
|
18122
17672
|
dropSlot(sessionId, "lkg_cache_bust_pending_capture");
|
|
18123
17673
|
state.lkgAcceptedCapture = undefined;
|
|
@@ -18126,6 +17676,11 @@ function createRustModeTransform(deps, options) {
|
|
|
18126
17676
|
let captureMode = "async";
|
|
18127
17677
|
if (capturePlan)
|
|
18128
17678
|
state.lkgLastServedCaptureSequence = capturePlan.captureSequence;
|
|
17679
|
+
const endRecoveryAfterResetCapture = () => {
|
|
17680
|
+
if (signedThinkingReset && thinkingRecovery.restore) {
|
|
17681
|
+
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
17682
|
+
}
|
|
17683
|
+
};
|
|
18129
17684
|
const captureFailed = (mode, error) => {
|
|
18130
17685
|
if (states.get(sessionId) !== state || capturePlan && capturePlan.captureSequence !== state.lkgCaptureSequence) {
|
|
18131
17686
|
return;
|
|
@@ -18146,6 +17701,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18146
17701
|
captureMode = synchronousReplacement ? "sync_priced" : "sync_recovery";
|
|
18147
17702
|
try {
|
|
18148
17703
|
commitRustCapture(state, capturePlan, synchronousReplacement);
|
|
17704
|
+
endRecoveryAfterResetCapture();
|
|
18149
17705
|
} catch (error) {
|
|
18150
17706
|
captureFailed("sync", error);
|
|
18151
17707
|
if (synchronousReplacement)
|
|
@@ -18157,6 +17713,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18157
17713
|
const asyncStartedAt = performance.now();
|
|
18158
17714
|
try {
|
|
18159
17715
|
const result = commitRustCapture(state, capturePlan);
|
|
17716
|
+
endRecoveryAfterResetCapture();
|
|
18160
17717
|
logTransformTiming(sessionId, "rust.lkg_snapshot_async", asyncStartedAt, `result=${result} row_version=${capturePlan.rowVersion}`);
|
|
18161
17718
|
} catch (error) {
|
|
18162
17719
|
captureFailed("async", error);
|
|
@@ -18255,7 +17812,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18255
17812
|
state.todoProbeIdentity = todoProbeIdentity;
|
|
18256
17813
|
state.todoBustIdentity = todoBustIdentity;
|
|
18257
17814
|
}
|
|
18258
|
-
state.todoProbeNextPass = response.reconcile_pending === true ||
|
|
17815
|
+
state.todoProbeNextPass = response.reconcile_pending === true || isRecord4(response.historian) && response.historian.fired === true;
|
|
18259
17816
|
state.lastAppliedAtMs = requestObservedAtMs;
|
|
18260
17817
|
heapHolder.wireCaches.set(sessionId, pendingWireCache);
|
|
18261
17818
|
timings.bookkeeping += performance.now() - bookkeepingStartedAt - timings.delivery;
|
|
@@ -18379,6 +17936,11 @@ function createRustModeTransform(deps, options) {
|
|
|
18379
17936
|
sessionLog2(sessionId, "mc_rust_emergency_refusal before_lkg");
|
|
18380
17937
|
markFailure(sessionId, state, error);
|
|
18381
17938
|
finishPass(false, false);
|
|
17939
|
+
if (moduleFailureCode(error) === TRANSFORM_PAGE_IN_PROGRESS_CODE && inProgressRunWithinBound(state)) {
|
|
17940
|
+
throw new EmergencyFailClosedError(ENGINE_BUSY_USER_MESSAGE, {
|
|
17941
|
+
cause: error
|
|
17942
|
+
});
|
|
17943
|
+
}
|
|
18382
17944
|
const refusedUser = newestUserMessage(messages);
|
|
18383
17945
|
const refusedUserMessageId = refusedUser ? messageIdOf2(refusedUser) : null;
|
|
18384
17946
|
if (refusedUserMessageId) {
|
|
@@ -18938,6 +18500,11 @@ function createTransform(deps) {
|
|
|
18938
18500
|
const finalWireUsage = createFinalWireUsageTracker();
|
|
18939
18501
|
const host = resolveTransformHostSeams(deps);
|
|
18940
18502
|
const loadedSessions = new Set;
|
|
18503
|
+
const prefixHoldLogTurnIds = new Map;
|
|
18504
|
+
const thinkingFitRetries = new Set;
|
|
18505
|
+
const clearSessionLogState = (sessionId) => {
|
|
18506
|
+
prefixHoldLogTurnIds.delete(sessionId);
|
|
18507
|
+
};
|
|
18941
18508
|
const unmanagedOverWindowSessions = new Set;
|
|
18942
18509
|
const rustModeTransform = deps.transformMode === "rust" && deps.rustModeModuleClient ? createRustModeTransform(deps, {
|
|
18943
18510
|
moduleClient: deps.rustModeModuleClient,
|
|
@@ -18967,6 +18534,7 @@ function createTransform(deps) {
|
|
|
18967
18534
|
const startTime = performance.now();
|
|
18968
18535
|
const historianRun = deps.resolveHistorianRun?.();
|
|
18969
18536
|
const messages = output.messages;
|
|
18537
|
+
const originalForThinkingFit = messages.some((message) => message.parts.some((part) => isRecord(part) && ["reasoning", "thinking", "redacted_thinking"].includes(String(part.type)))) ? structuredClone(messages) : null;
|
|
18970
18538
|
const passOutcome = createPassOutcome();
|
|
18971
18539
|
const tSessionId = performance.now();
|
|
18972
18540
|
const sessionId = findSessionId(messages);
|
|
@@ -19154,16 +18722,15 @@ function createTransform(deps) {
|
|
|
19154
18722
|
deps.pendingMaterializationSessions?.add(sessionId);
|
|
19155
18723
|
let restoreLatestTurnOriginals;
|
|
19156
18724
|
let activeThinkingTurn = hasActiveAnthropicThinkingTurn(messages, activeThinkingModel?.providerID, activeThinkingModel?.modelID);
|
|
19157
|
-
|
|
18725
|
+
const unresolvedDirectoryHold = sessionDirectoryFellBack && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null && (() => {
|
|
19158
18726
|
try {
|
|
19159
18727
|
return hasRecordedSessionProjectIdentity(db, sessionId);
|
|
19160
18728
|
} catch {
|
|
19161
18729
|
return true;
|
|
19162
18730
|
}
|
|
19163
18731
|
})();
|
|
19164
|
-
|
|
19165
|
-
|
|
19166
|
-
}
|
|
18732
|
+
let activeThinkingPrefixHold = activeThinkingTurn && isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID);
|
|
18733
|
+
let freezeM0M1 = unresolvedDirectoryHold || activeThinkingPrefixHold;
|
|
19167
18734
|
const compartmentDirectory = sessionDirectory;
|
|
19168
18735
|
const historianRunnable = deps.historianRunnable !== false;
|
|
19169
18736
|
const canRunCompartments = fullFeatureMode && !compactionOff && historianRunnable && (deps.client !== undefined || deps.hiddenCompletionExecutor !== undefined) && compartmentDirectory.length > 0;
|
|
@@ -19291,7 +18858,13 @@ function createTransform(deps) {
|
|
|
19291
18858
|
}
|
|
19292
18859
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
19293
18860
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
19294
|
-
|
|
18861
|
+
activeThinkingPrefixHold ||= activeThinkingTurn && isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID);
|
|
18862
|
+
freezeM0M1 ||= activeThinkingPrefixHold;
|
|
18863
|
+
if (freezeM0M1 && prefixHoldLogTurnIds.get(sessionId) !== currentTurnId) {
|
|
18864
|
+
prefixHoldLogTurnIds.set(sessionId, currentTurnId);
|
|
18865
|
+
const reason = activeThinkingPrefixHold ? "active thinking turn (prefix-bound model)" : "session directory unresolved";
|
|
18866
|
+
sessionLog2(sessionId, `m[0]/m[1] frozen: ${reason}; replaying the frozen prefix and deferring any rebuild`);
|
|
18867
|
+
}
|
|
19295
18868
|
const canUseEmptySentinels = modelAcceptsEmptyContent(resolvedProviderID);
|
|
19296
18869
|
const protectedThinkingMessages = activeThinkingTurn || isAnthropicFamilyRoute(resolvedProviderID, modelForBudget?.modelID) ? latestAssistantTurnMessages(messages) : new Set;
|
|
19297
18870
|
const resolvedContextLimit = modelForBudget ? resolveTrustedContextLimit(modelForBudget.providerID, modelForBudget.modelID, {
|
|
@@ -19822,7 +19395,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19822
19395
|
client: deps.client,
|
|
19823
19396
|
activeAgent,
|
|
19824
19397
|
batch,
|
|
19825
|
-
contextUsage,
|
|
19398
|
+
contextUsage: thinkingFitRetries.has(sessionId) ? { ...contextUsage, percentage: Math.max(95, contextUsage.percentage) } : contextUsage,
|
|
19826
19399
|
usableWindow: resolvedContextLimit ?? 0,
|
|
19827
19400
|
schedulerDecision,
|
|
19828
19401
|
schedulerDeferReason,
|
|
@@ -19837,6 +19410,17 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19837
19410
|
compartmentInProgress,
|
|
19838
19411
|
historyRefreshExplicitBeforePrepare,
|
|
19839
19412
|
freezeM0M1,
|
|
19413
|
+
activeThinkingPrefixHold,
|
|
19414
|
+
directoryPrefixHold: unresolvedDirectoryHold,
|
|
19415
|
+
forceSignedRebuildForFit: thinkingFitRetries.has(sessionId),
|
|
19416
|
+
readLastServedMessages: () => {
|
|
19417
|
+
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
19418
|
+
try {
|
|
19419
|
+
return slot ? JSON.parse(slot.jsonPrefix) : null;
|
|
19420
|
+
} catch {
|
|
19421
|
+
return null;
|
|
19422
|
+
}
|
|
19423
|
+
},
|
|
19840
19424
|
deferredHistoryWasPendingAtPassStart,
|
|
19841
19425
|
compartmentInjectionRebuiltFromDb: pendingCompartmentInjection?.rebuiltFromDb === true,
|
|
19842
19426
|
rebuiltHistoryFromInitialPrepare,
|
|
@@ -19921,6 +19505,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19921
19505
|
if (finalWireEstimate) {
|
|
19922
19506
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=${finalWireEstimate.tokens} trusted=${finalWireEstimate.trusted} conversation=${finalWireEstimate.messageTokens.conversation} tools=${finalWireEstimate.messageTokens.toolCall} system=${finalWireEstimate.systemTokens} toolDefinitions=${finalWireEstimate.toolDefinitionTokens ?? "unknown"} tail=${finalWireTail}`);
|
|
19923
19507
|
}
|
|
19508
|
+
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
19509
|
+
if (!thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && originalForThinkingFit && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID)) {
|
|
19510
|
+
thinkingFitRetries.add(sessionId);
|
|
19511
|
+
deps.pendingMaterializationSessions.add(sessionId);
|
|
19512
|
+
messages.splice(0, messages.length, ...originalForThinkingFit);
|
|
19513
|
+
try {
|
|
19514
|
+
await transform({}, output);
|
|
19515
|
+
} finally {
|
|
19516
|
+
thinkingFitRetries.delete(sessionId);
|
|
19517
|
+
}
|
|
19518
|
+
return;
|
|
19519
|
+
}
|
|
19520
|
+
if (thinkingFitRetries.has(sessionId) || postTransformResult.thinkingReleasedForFit)
|
|
19521
|
+
throw contextRefusalError("The request remains over the model window after stripping signed thinking and reclaiming context");
|
|
19522
|
+
}
|
|
19924
19523
|
if (postTransformResult.prefixTrimStatus === "refused") {
|
|
19925
19524
|
const untrimmed = finalWireEstimate ?? estimateFinalWireInputTokens({
|
|
19926
19525
|
messages,
|
|
@@ -20184,10 +19783,12 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20184
19783
|
});
|
|
20185
19784
|
};
|
|
20186
19785
|
return Object.assign(transform, {
|
|
19786
|
+
clearSessionLogState,
|
|
20187
19787
|
invalidateRustWireState(sessionId) {
|
|
20188
19788
|
rustModeTransform?.invalidateWireState(sessionId);
|
|
20189
19789
|
},
|
|
20190
19790
|
async clearRustSession(sessionId) {
|
|
19791
|
+
clearSessionLogState(sessionId);
|
|
20191
19792
|
await rustModeTransform?.clearSession(sessionId);
|
|
20192
19793
|
},
|
|
20193
19794
|
disposeRust() {
|
|
@@ -20641,7 +20242,7 @@ function truncateError(name, code, message, maxLen = 240) {
|
|
|
20641
20242
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
20642
20243
|
import { once } from "node:events";
|
|
20643
20244
|
import { rmSync } from "node:fs";
|
|
20644
|
-
import { join as
|
|
20245
|
+
import { join as join3 } from "node:path";
|
|
20645
20246
|
|
|
20646
20247
|
// src/features/magic-context/dreamer/tick-failure.ts
|
|
20647
20248
|
var DREAMER_TICK_FAILURE_KEY = "dreamer_tick_last_failure";
|
|
@@ -21723,7 +21324,7 @@ function computeOpenCodeWorkMetricsIncremental(openCodeDb, sessionId, carry) {
|
|
|
21723
21324
|
import { readFileSync, statSync } from "node:fs";
|
|
21724
21325
|
|
|
21725
21326
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
21726
|
-
import { createHash as
|
|
21327
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
21727
21328
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
21728
21329
|
"embedding.api_key",
|
|
21729
21330
|
"embedding.endpoint",
|
|
@@ -21771,7 +21372,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
21771
21372
|
];
|
|
21772
21373
|
var loggedFailureSignatures = new Map;
|
|
21773
21374
|
function sha256Prefix(value, length = 16) {
|
|
21774
|
-
return
|
|
21375
|
+
return createHash6("sha256").update(value).digest("hex").slice(0, length);
|
|
21775
21376
|
}
|
|
21776
21377
|
function warningLooksEmbeddingRelated(message) {
|
|
21777
21378
|
const lower = message.toLowerCase();
|
|
@@ -22312,7 +21913,7 @@ function activeHostLimitations() {
|
|
|
22312
21913
|
|
|
22313
21914
|
// src/shared/plugin-package-version.ts
|
|
22314
21915
|
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
22315
|
-
import { dirname, join as
|
|
21916
|
+
import { dirname, join as join2 } from "node:path";
|
|
22316
21917
|
import { fileURLToPath } from "node:url";
|
|
22317
21918
|
var PACKAGE_NAME = "@cortexkit/opencode-magic-context";
|
|
22318
21919
|
var cachedVersion;
|
|
@@ -22324,7 +21925,7 @@ function pluginPackageVersion(moduleUrl = import.meta.url) {
|
|
|
22324
21925
|
try {
|
|
22325
21926
|
let directory = dirname(fileURLToPath(moduleUrl));
|
|
22326
21927
|
for (let depth = 0;depth < 10; depth++) {
|
|
22327
|
-
const candidate =
|
|
21928
|
+
const candidate = join2(directory, "package.json");
|
|
22328
21929
|
if (existsSync3(candidate)) {
|
|
22329
21930
|
const parsed = JSON.parse(readFileSync3(candidate, "utf8"));
|
|
22330
21931
|
if (typeof parsed === "object" && parsed !== null && "name" in parsed && parsed.name === PACKAGE_NAME && "version" in parsed && typeof parsed.version === "string") {
|
|
@@ -23071,11 +22672,11 @@ async function generateDebugHeapSnapshot(storageDir, memory) {
|
|
|
23071
22672
|
if (rssBytes > maxRssBytes) {
|
|
23072
22673
|
throw new Error(`heap snapshot refused: process rss ${Math.round(rssBytes / (1024 * 1024))} MiB exceeds the ${Math.round(maxRssBytes / (1024 * 1024))} MiB ceiling (MAGIC_CONTEXT_DEBUG_HEAP_SNAPSHOT_MAX_RSS_MB); use debug.memoryUsage instead`);
|
|
23073
22674
|
}
|
|
23074
|
-
const directory =
|
|
22675
|
+
const directory = join3(storageDir, "heap-snapshots");
|
|
23075
22676
|
const enforcePrivatePermissions = shouldEnforcePrivateStoragePermissions();
|
|
23076
22677
|
ensureStorageDirectorySync(directory);
|
|
23077
22678
|
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
23078
|
-
const path =
|
|
22679
|
+
const path = join3(directory, `${timestamp}-${process.pid}.heapsnapshot`);
|
|
23079
22680
|
let format = "jsc";
|
|
23080
22681
|
let snapshotVersion;
|
|
23081
22682
|
let snapshot;
|
|
@@ -23225,7 +22826,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
23225
22826
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
23226
22827
|
});
|
|
23227
22828
|
const buildManagedCtx = async (db) => {
|
|
23228
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
22829
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-fgej9j46.js"));
|
|
23229
22830
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-nx97z3x7.js"));
|
|
23230
22831
|
const { userMemoryCollectionEnabled } = await importPluginModule(() => import("./task-config-x0hq3qfd.js"));
|
|
23231
22832
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -23261,8 +22862,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
23261
22862
|
const db = readDatabase();
|
|
23262
22863
|
if (!db)
|
|
23263
22864
|
return { ok: false, error: "db unavailable" };
|
|
23264
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
23265
|
-
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-
|
|
22865
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-ckfgt6wq.js"));
|
|
22866
|
+
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-5m0yapqx.js"));
|
|
23266
22867
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
23267
22868
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
23268
22869
|
return {
|
|
@@ -23331,7 +22932,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
23331
22932
|
const db = readDatabase();
|
|
23332
22933
|
if (!db)
|
|
23333
22934
|
return { ok: false, error: "db unavailable" };
|
|
23334
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
22935
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-a7efxaax.js"));
|
|
23335
22936
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
23336
22937
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
23337
22938
|
const ctx = {
|
|
@@ -23422,26 +23023,26 @@ function hideSubagentTools(draft, db) {
|
|
|
23422
23023
|
|
|
23423
23024
|
// src/shared/conflict-detector.ts
|
|
23424
23025
|
import { homedir as homedir2 } from "node:os";
|
|
23425
|
-
import { join as
|
|
23026
|
+
import { join as join5 } from "node:path";
|
|
23426
23027
|
|
|
23427
23028
|
// src/shared/opencode-config-dir.ts
|
|
23428
23029
|
import { homedir } from "node:os";
|
|
23429
|
-
import { join as
|
|
23030
|
+
import { join as join4, resolve } from "node:path";
|
|
23430
23031
|
function resolveHomeDir() {
|
|
23431
23032
|
return process.env.HOME?.trim() || homedir();
|
|
23432
23033
|
}
|
|
23433
23034
|
function getOpenCodeGlobalConfigDir() {
|
|
23434
23035
|
if (process.platform === "win32") {
|
|
23435
|
-
return
|
|
23036
|
+
return join4(resolveHomeDir(), ".config", "opencode");
|
|
23436
23037
|
}
|
|
23437
|
-
return
|
|
23038
|
+
return join4(process.env.XDG_CONFIG_HOME || join4(resolveHomeDir(), ".config"), "opencode");
|
|
23438
23039
|
}
|
|
23439
23040
|
function getEnvConfigDir() {
|
|
23440
23041
|
const envConfigDir = process.env.OPENCODE_CONFIG_DIR?.trim();
|
|
23441
23042
|
return envConfigDir ? resolve(envConfigDir) : undefined;
|
|
23442
23043
|
}
|
|
23443
23044
|
function getOpenCodeConfigDirs() {
|
|
23444
|
-
const dirs = [getOpenCodeGlobalConfigDir(),
|
|
23045
|
+
const dirs = [getOpenCodeGlobalConfigDir(), join4(resolveHomeDir(), ".opencode")];
|
|
23445
23046
|
const envDir = getEnvConfigDir();
|
|
23446
23047
|
if (envDir)
|
|
23447
23048
|
dirs.push(envDir);
|
|
@@ -23515,19 +23116,19 @@ function checkCompaction(directory, hostGeneration) {
|
|
|
23515
23116
|
function openCodeConfigFileChain(directory, hostGeneration) {
|
|
23516
23117
|
const globalDir = getOpenCodeGlobalConfigDir();
|
|
23517
23118
|
const wellKnown = [
|
|
23518
|
-
|
|
23519
|
-
|
|
23520
|
-
|
|
23119
|
+
join5(globalDir, "config.json"),
|
|
23120
|
+
join5(globalDir, "opencode.json"),
|
|
23121
|
+
join5(globalDir, "opencode.jsonc")
|
|
23521
23122
|
];
|
|
23522
|
-
const globalSupplementary = getOpenCodeConfigDirs().filter((dir) => dir !== globalDir).flatMap((dir) => [
|
|
23123
|
+
const globalSupplementary = getOpenCodeConfigDirs().filter((dir) => dir !== globalDir).flatMap((dir) => [join5(dir, "opencode.json"), join5(dir, "opencode.jsonc")]);
|
|
23523
23124
|
const explicitConfig = process.env.OPENCODE_CONFIG?.trim();
|
|
23524
23125
|
const explicit = explicitConfig ? [explicitConfig] : [];
|
|
23525
23126
|
const disableProjectConfig = process.env.OPENCODE_DISABLE_PROJECT_CONFIG?.toLowerCase();
|
|
23526
23127
|
const skipProject = hostGeneration === "v1" && (disableProjectConfig === "true" || disableProjectConfig === "1");
|
|
23527
|
-
const direct = skipProject ? [] : [
|
|
23128
|
+
const direct = skipProject ? [] : [join5(directory, "opencode.json"), join5(directory, "opencode.jsonc")];
|
|
23528
23129
|
const projectSupplementary = skipProject ? [] : [
|
|
23529
|
-
|
|
23530
|
-
|
|
23130
|
+
join5(directory, ".opencode", "opencode.json"),
|
|
23131
|
+
join5(directory, ".opencode", "opencode.jsonc")
|
|
23531
23132
|
];
|
|
23532
23133
|
const files = hostGeneration === "v2" ? [
|
|
23533
23134
|
...wellKnown,
|
|
@@ -23615,10 +23216,10 @@ function collectPluginEntries(directory) {
|
|
|
23615
23216
|
}
|
|
23616
23217
|
};
|
|
23617
23218
|
for (const configPath of [
|
|
23618
|
-
|
|
23619
|
-
|
|
23620
|
-
|
|
23621
|
-
|
|
23219
|
+
join5(directory, ".opencode", "opencode.jsonc"),
|
|
23220
|
+
join5(directory, ".opencode", "opencode.json"),
|
|
23221
|
+
join5(directory, "opencode.jsonc"),
|
|
23222
|
+
join5(directory, "opencode.json")
|
|
23622
23223
|
]) {
|
|
23623
23224
|
const config = readJsoncFile(configPath);
|
|
23624
23225
|
pushFrom(config?.plugin);
|
|
@@ -23628,7 +23229,7 @@ function collectPluginEntries(directory) {
|
|
|
23628
23229
|
for (const dir of getOpenCodeConfigDirs()) {
|
|
23629
23230
|
const names = dir === globalDir ? ["config.json", "opencode.json", "opencode.jsonc"] : ["opencode.json", "opencode.jsonc"];
|
|
23630
23231
|
for (const name of names) {
|
|
23631
|
-
const config = readJsoncFile(
|
|
23232
|
+
const config = readJsoncFile(join5(dir, name));
|
|
23632
23233
|
pushFrom(config?.plugin);
|
|
23633
23234
|
}
|
|
23634
23235
|
}
|
|
@@ -23663,7 +23264,7 @@ function readOmoDisabledHooks(directory) {
|
|
|
23663
23264
|
try {
|
|
23664
23265
|
for (const dir of getOpenCodeConfigDirs()) {
|
|
23665
23266
|
for (const name of configNames) {
|
|
23666
|
-
const config = readJsoncFile(
|
|
23267
|
+
const config = readJsoncFile(join5(dir, name));
|
|
23667
23268
|
if (config?.disabled_hooks) {
|
|
23668
23269
|
for (const hook of config.disabled_hooks) {
|
|
23669
23270
|
disabled.add(hook);
|
|
@@ -23673,7 +23274,7 @@ function readOmoDisabledHooks(directory) {
|
|
|
23673
23274
|
}
|
|
23674
23275
|
} catch {}
|
|
23675
23276
|
for (const name of configNames) {
|
|
23676
|
-
const config = readJsoncFile(
|
|
23277
|
+
const config = readJsoncFile(join5(directory, name));
|
|
23677
23278
|
if (config?.disabled_hooks) {
|
|
23678
23279
|
for (const hook of config.disabled_hooks) {
|
|
23679
23280
|
disabled.add(hook);
|
|
@@ -23681,9 +23282,9 @@ function readOmoDisabledHooks(directory) {
|
|
|
23681
23282
|
}
|
|
23682
23283
|
}
|
|
23683
23284
|
const homeDir = process.env.HOME || homedir2();
|
|
23684
|
-
const omoHomeDir =
|
|
23285
|
+
const omoHomeDir = join5(homeDir, ".omo");
|
|
23685
23286
|
for (const name of ["omo.jsonc", "omo.json"]) {
|
|
23686
|
-
const config = readJsoncFile(
|
|
23287
|
+
const config = readJsoncFile(join5(omoHomeDir, name));
|
|
23687
23288
|
if (config?.["[opencode]"]?.disabled_hooks) {
|
|
23688
23289
|
for (const hook of config["[opencode]"].disabled_hooks) {
|
|
23689
23290
|
disabled.add(hook);
|
|
@@ -23691,7 +23292,7 @@ function readOmoDisabledHooks(directory) {
|
|
|
23691
23292
|
}
|
|
23692
23293
|
}
|
|
23693
23294
|
for (const name of ["omo.jsonc", "omo.json"]) {
|
|
23694
|
-
const config = readJsoncFile(
|
|
23295
|
+
const config = readJsoncFile(join5(directory, ".omo", name));
|
|
23695
23296
|
if (config?.["[opencode]"]?.disabled_hooks) {
|
|
23696
23297
|
for (const hook of config["[opencode]"].disabled_hooks) {
|
|
23697
23298
|
disabled.add(hook);
|
|
@@ -24205,9 +23806,9 @@ function trimToRecordedBoundary(db, sessionId, messages) {
|
|
|
24205
23806
|
}
|
|
24206
23807
|
|
|
24207
23808
|
// src/v2/fold/host-media.ts
|
|
24208
|
-
var
|
|
23809
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24209
23810
|
function isClassInstance(value) {
|
|
24210
|
-
if (!
|
|
23811
|
+
if (!isRecord5(value))
|
|
24211
23812
|
return false;
|
|
24212
23813
|
const prototype = Object.getPrototypeOf(value);
|
|
24213
23814
|
return prototype !== Object.prototype && prototype !== null;
|
|
@@ -24226,10 +23827,10 @@ function rememberHostMedia(messages) {
|
|
|
24226
23827
|
if (!Array.isArray(content))
|
|
24227
23828
|
continue;
|
|
24228
23829
|
for (const part of content) {
|
|
24229
|
-
if (!
|
|
23830
|
+
if (!isRecord5(part) || part.type !== "media")
|
|
24230
23831
|
continue;
|
|
24231
23832
|
const media = part.media;
|
|
24232
|
-
if (isClassInstance(media) &&
|
|
23833
|
+
if (isClassInstance(media) && isRecord5(media.source)) {
|
|
24233
23834
|
rememberedAssetClass = Object.getPrototypeOf(media).constructor;
|
|
24234
23835
|
return;
|
|
24235
23836
|
}
|
|
@@ -24286,7 +23887,7 @@ function hostMediaAsset(data, mediaType) {
|
|
|
24286
23887
|
return hostMediaFromEncoded({ source: { type: "base64", data, mediaType } });
|
|
24287
23888
|
}
|
|
24288
23889
|
function hostMediaFromEncoded(value) {
|
|
24289
|
-
if (!
|
|
23890
|
+
if (!isRecord5(value.source))
|
|
24290
23891
|
return "missing Media.Asset source";
|
|
24291
23892
|
const encoded = structuredClone(value);
|
|
24292
23893
|
if (encoded.source.type === "bytes") {
|
|
@@ -24320,8 +23921,8 @@ function hostMediaFromEncoded(value) {
|
|
|
24320
23921
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
24321
23922
|
|
|
24322
23923
|
// src/v2/fold/owner.ts
|
|
24323
|
-
import { createHash as
|
|
24324
|
-
var foldDigest = (value) =>
|
|
23924
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
23925
|
+
var foldDigest = (value) => createHash7("sha256").update(value).digest("hex");
|
|
24325
23926
|
|
|
24326
23927
|
class FoldOwner {
|
|
24327
23928
|
storage;
|
|
@@ -25897,7 +25498,7 @@ function createNativeHiddenChildren(host, removeSession, options) {
|
|
|
25897
25498
|
return;
|
|
25898
25499
|
}
|
|
25899
25500
|
const directory = stored.location?.directory;
|
|
25900
|
-
if (options.directory !== undefined && directory !== undefined && directory
|
|
25501
|
+
if (options.directory !== undefined && directory !== undefined && !sameProjectDirectory(directory, options.directory)) {
|
|
25901
25502
|
throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", `hidden child ${sessionID} is bound to ${directory}, not to this instance's ${options.directory}`, true);
|
|
25902
25503
|
}
|
|
25903
25504
|
if (stored.parentID === parentID || parentDroppedNoted)
|
|
@@ -26014,6 +25615,111 @@ async function cleanupLegacyHiddenChildren(db, remove, note, options = {}) {
|
|
|
26014
25615
|
db.prepare("INSERT OR IGNORE INTO schema_migrations_meta (key, value) VALUES (?, 'true')").run(COMPLETE);
|
|
26015
25616
|
}
|
|
26016
25617
|
|
|
25618
|
+
// src/shared/models-dev-temperature.ts
|
|
25619
|
+
import { readFileSync as readFileSync5, statSync as statSync2 } from "node:fs";
|
|
25620
|
+
import { homedir as homedir3 } from "node:os";
|
|
25621
|
+
import { join as join6 } from "node:path";
|
|
25622
|
+
var CATALOG_PROVIDER_ALIASES = {
|
|
25623
|
+
"google-antigravity": "google",
|
|
25624
|
+
"opencode-zen": "opencode"
|
|
25625
|
+
};
|
|
25626
|
+
var ANTIGRAVITY_MODEL_PREFIX = "antigravity-";
|
|
25627
|
+
var cached;
|
|
25628
|
+
function modelsDevCatalogPath(env = process.env) {
|
|
25629
|
+
if (env.OPENCODE_MODELS_PATH)
|
|
25630
|
+
return env.OPENCODE_MODELS_PATH;
|
|
25631
|
+
return join6(env.XDG_CACHE_HOME || join6(homedir3(), ".cache"), "opencode", "models.json");
|
|
25632
|
+
}
|
|
25633
|
+
function buildIndex(raw) {
|
|
25634
|
+
const index = new Map;
|
|
25635
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
25636
|
+
return index;
|
|
25637
|
+
for (const [providerID, provider] of Object.entries(raw)) {
|
|
25638
|
+
const models = provider?.models;
|
|
25639
|
+
if (!models || typeof models !== "object")
|
|
25640
|
+
continue;
|
|
25641
|
+
for (const [modelID, model] of Object.entries(models)) {
|
|
25642
|
+
const temperature = model?.temperature;
|
|
25643
|
+
if (typeof temperature === "boolean")
|
|
25644
|
+
index.set(`${providerID}/${modelID}`, temperature);
|
|
25645
|
+
}
|
|
25646
|
+
}
|
|
25647
|
+
return index;
|
|
25648
|
+
}
|
|
25649
|
+
function loadIndex() {
|
|
25650
|
+
const path = modelsDevCatalogPath();
|
|
25651
|
+
try {
|
|
25652
|
+
const stat = statSync2(path);
|
|
25653
|
+
if (cached?.path === path && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
|
|
25654
|
+
return cached.index;
|
|
25655
|
+
const index = buildIndex(JSON.parse(readFileSync5(path, "utf8")));
|
|
25656
|
+
cached = { path, mtimeMs: stat.mtimeMs, size: stat.size, index };
|
|
25657
|
+
return index;
|
|
25658
|
+
} catch {
|
|
25659
|
+
return;
|
|
25660
|
+
}
|
|
25661
|
+
}
|
|
25662
|
+
function catalogCandidates(providerID, modelID) {
|
|
25663
|
+
const provider = Object.hasOwn(CATALOG_PROVIDER_ALIASES, providerID) ? CATALOG_PROVIDER_ALIASES[providerID] : providerID;
|
|
25664
|
+
const candidates = [`${provider}/${modelID}`];
|
|
25665
|
+
if (provider === "google" && modelID.startsWith(ANTIGRAVITY_MODEL_PREFIX))
|
|
25666
|
+
candidates.push(`google/${modelID.slice(ANTIGRAVITY_MODEL_PREFIX.length)}`);
|
|
25667
|
+
return candidates;
|
|
25668
|
+
}
|
|
25669
|
+
function catalogTemperature(model) {
|
|
25670
|
+
const slash = model.indexOf("/");
|
|
25671
|
+
if (slash <= 0 || slash === model.length - 1)
|
|
25672
|
+
return;
|
|
25673
|
+
const index = loadIndex();
|
|
25674
|
+
if (!index)
|
|
25675
|
+
return;
|
|
25676
|
+
for (const entry of catalogCandidates(model.slice(0, slash), model.slice(slash + 1))) {
|
|
25677
|
+
const temperature = index.get(entry);
|
|
25678
|
+
if (temperature !== undefined)
|
|
25679
|
+
return { temperature, entry };
|
|
25680
|
+
}
|
|
25681
|
+
return;
|
|
25682
|
+
}
|
|
25683
|
+
|
|
25684
|
+
// src/shared/subagent-temperature.ts
|
|
25685
|
+
var loggedDecisions = new Set;
|
|
25686
|
+
function temperatureCapability(metadata) {
|
|
25687
|
+
if (!metadata || typeof metadata !== "object")
|
|
25688
|
+
return;
|
|
25689
|
+
const model = metadata;
|
|
25690
|
+
const supported = model.capabilities?.temperature ?? model.temperature ?? model.compat?.supportsTemperature ?? model.compat?.supportsSamplingParams;
|
|
25691
|
+
return typeof supported === "boolean" ? supported : undefined;
|
|
25692
|
+
}
|
|
25693
|
+
function resolveTemperatureCapability(model, metadata) {
|
|
25694
|
+
const host = temperatureCapability(metadata);
|
|
25695
|
+
if (host !== undefined)
|
|
25696
|
+
return { supported: host, source: "host" };
|
|
25697
|
+
const catalog = catalogTemperature(model);
|
|
25698
|
+
if (catalog)
|
|
25699
|
+
return { supported: catalog.temperature, source: "catalog", entry: catalog.entry };
|
|
25700
|
+
return { supported: undefined, source: "none" };
|
|
25701
|
+
}
|
|
25702
|
+
function describeTemperatureDecision(model, decision) {
|
|
25703
|
+
const verdict = decision.supported === true ? "sent" : "omitted";
|
|
25704
|
+
const answer = decision.supported === true ? "yes" : "no";
|
|
25705
|
+
const reason = decision.source === "host" ? `host model metadata says ${answer}` : decision.source === "catalog" ? `models.dev cache entry ${decision.entry ?? "unknown"} says ${answer}` : "no host or models.dev metadata";
|
|
25706
|
+
return `Subagent temperature ${verdict} for ${model}: ${reason}`;
|
|
25707
|
+
}
|
|
25708
|
+
function logTemperatureDecision(model, decision, log) {
|
|
25709
|
+
const key = `${model}\x00${decision.source}\x00${decision.supported}\x00${decision.entry ?? ""}`;
|
|
25710
|
+
if (loggedDecisions.has(key))
|
|
25711
|
+
return;
|
|
25712
|
+
loggedDecisions.add(key);
|
|
25713
|
+
log(describeTemperatureDecision(model, decision), decision);
|
|
25714
|
+
}
|
|
25715
|
+
function subagentTemperature(model, metadata, temperature, log) {
|
|
25716
|
+
if (temperature === undefined)
|
|
25717
|
+
return;
|
|
25718
|
+
const decision = resolveTemperatureCapability(model, metadata);
|
|
25719
|
+
logTemperatureDecision(model, decision, log);
|
|
25720
|
+
return decision.supported === true ? temperature : undefined;
|
|
25721
|
+
}
|
|
25722
|
+
|
|
26017
25723
|
// src/v2/hidden-completion.ts
|
|
26018
25724
|
var POLL_INTERVAL_MS = 200;
|
|
26019
25725
|
function modelKey(model) {
|
|
@@ -26368,6 +26074,26 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
26368
26074
|
throw new Error("Hidden completion prompt aborted");
|
|
26369
26075
|
}
|
|
26370
26076
|
const requested = await validateVariant(requestModel(request, run.child.model));
|
|
26077
|
+
if (run.identity.kind !== "dreamer-task" && request.body.temperature === undefined) {
|
|
26078
|
+
const configured = options.historianTemperature?.();
|
|
26079
|
+
if (typeof configured === "number" && Number.isFinite(configured))
|
|
26080
|
+
request = { ...request, body: { ...request.body, temperature: configured } };
|
|
26081
|
+
}
|
|
26082
|
+
if (typeof request.body.temperature === "number") {
|
|
26083
|
+
let metadata;
|
|
26084
|
+
try {
|
|
26085
|
+
const listed = await options.modelCatalog?.();
|
|
26086
|
+
const rows = Array.isArray(listed) ? listed : listed?.data;
|
|
26087
|
+
metadata = rows?.find((row) => row?.providerID === requested.providerID && (row?.id === requested.modelID || row?.modelID === requested.modelID));
|
|
26088
|
+
} catch {}
|
|
26089
|
+
const temperature = subagentTemperature(modelKey(requested), metadata, request.body.temperature, (message) => note(message));
|
|
26090
|
+
const body = { ...request.body };
|
|
26091
|
+
if (temperature === undefined)
|
|
26092
|
+
delete body.temperature;
|
|
26093
|
+
else
|
|
26094
|
+
body.temperature = temperature;
|
|
26095
|
+
request = { ...request, body };
|
|
26096
|
+
}
|
|
26371
26097
|
if (run.retired) {
|
|
26372
26098
|
run.child = await lifecycle.create(run.identity, run.role, requested);
|
|
26373
26099
|
run.failed = false;
|
|
@@ -26783,11 +26509,11 @@ class DeletedSessionTombstones {
|
|
|
26783
26509
|
}
|
|
26784
26510
|
|
|
26785
26511
|
// src/features/magic-context/dreamer/task-executor.ts
|
|
26786
|
-
import { createHash as
|
|
26787
|
-
import { existsSync as existsSync7, readFileSync as
|
|
26512
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
26513
|
+
import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
|
|
26788
26514
|
|
|
26789
26515
|
// src/features/magic-context/mural/compress-cues.ts
|
|
26790
|
-
import { createHash as
|
|
26516
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
26791
26517
|
|
|
26792
26518
|
// src/features/magic-context/dreamer/storage-dream-state.ts
|
|
26793
26519
|
var getDreamStateStatements = new WeakMap;
|
|
@@ -27517,7 +27243,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
|
|
|
27517
27243
|
log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
|
|
27518
27244
|
}
|
|
27519
27245
|
}
|
|
27520
|
-
const commandId = `mural-cues:${route.moduleCommandId}:${
|
|
27246
|
+
const commandId = `mural-cues:${route.moduleCommandId}:${createHash8("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
27521
27247
|
let response;
|
|
27522
27248
|
try {
|
|
27523
27249
|
response = await route.moduleClient.call({
|
|
@@ -28086,7 +27812,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
|
|
|
28086
27812
|
}
|
|
28087
27813
|
|
|
28088
27814
|
// src/features/magic-context/dreamer/classify.ts
|
|
28089
|
-
import { createHash as
|
|
27815
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
28090
27816
|
|
|
28091
27817
|
// src/plugin/rust-tool-backends.ts
|
|
28092
27818
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -28523,7 +28249,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
|
|
|
28523
28249
|
if (entry.qualifier)
|
|
28524
28250
|
modelVariants[entry.model] = entry.qualifier;
|
|
28525
28251
|
}
|
|
28526
|
-
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
28252
|
+
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash9("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
28527
28253
|
const runTask = (hostCompletion) => args.moduleClient?.call({
|
|
28528
28254
|
sessionId: args.moduleSessionId,
|
|
28529
28255
|
projectRoot: args.moduleProjectRoot,
|
|
@@ -28798,14 +28524,14 @@ function takeCurateSafetyRefusalCount(sessionId) {
|
|
|
28798
28524
|
|
|
28799
28525
|
// src/features/magic-context/dreamer/docs-proposals.ts
|
|
28800
28526
|
import { execFileSync } from "node:child_process";
|
|
28801
|
-
import { createHash as
|
|
28527
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
28802
28528
|
import {
|
|
28803
28529
|
existsSync as existsSync4,
|
|
28804
28530
|
mkdirSync,
|
|
28805
28531
|
mkdtempSync,
|
|
28806
28532
|
readdirSync as readdirSync2,
|
|
28807
|
-
readFileSync as
|
|
28808
|
-
realpathSync
|
|
28533
|
+
readFileSync as readFileSync6,
|
|
28534
|
+
realpathSync,
|
|
28809
28535
|
renameSync,
|
|
28810
28536
|
rmSync as rmSync2,
|
|
28811
28537
|
writeFileSync
|
|
@@ -28813,12 +28539,12 @@ import {
|
|
|
28813
28539
|
import { tmpdir } from "node:os";
|
|
28814
28540
|
import { join as join7 } from "node:path";
|
|
28815
28541
|
var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
28816
|
-
var hash = (text) =>
|
|
28542
|
+
var hash = (text) => createHash10("sha256").update(text).digest("hex");
|
|
28817
28543
|
var proposalDir = (projectDir) => join7(projectDir, ".cortexkit/magic-context/docs-update-proposals");
|
|
28818
28544
|
function docsBaseHashes(projectDir) {
|
|
28819
28545
|
return Object.fromEntries(FILES.map((name) => [
|
|
28820
28546
|
name,
|
|
28821
|
-
hash(existsSync4(join7(projectDir, name)) ?
|
|
28547
|
+
hash(existsSync4(join7(projectDir, name)) ? readFileSync6(join7(projectDir, name), "utf8") : "")
|
|
28822
28548
|
]));
|
|
28823
28549
|
}
|
|
28824
28550
|
function listPendingDocsProposals(projectDir) {
|
|
@@ -28827,7 +28553,7 @@ function listPendingDocsProposals(projectDir) {
|
|
|
28827
28553
|
}
|
|
28828
28554
|
function hasCurrentDocsProposal(projectDir) {
|
|
28829
28555
|
const hashes = docsBaseHashes(projectDir);
|
|
28830
|
-
return listPendingDocsProposals(projectDir).some((path) => Object.entries(hashes).every(([name, value]) =>
|
|
28556
|
+
return listPendingDocsProposals(projectDir).some((path) => Object.entries(hashes).every(([name, value]) => readFileSync6(path, "utf8").includes(`Base SHA-256 ${name}: ${value}`)));
|
|
28831
28557
|
}
|
|
28832
28558
|
function git(projectDir, args) {
|
|
28833
28559
|
return execFileSync("git", args, {
|
|
@@ -28855,7 +28581,7 @@ function gitOutputPrefix(projectDir, args) {
|
|
|
28855
28581
|
var MAX_PATHSPEC_BYTES = 256000;
|
|
28856
28582
|
function docsChangeSet(projectDir, storedAnchor) {
|
|
28857
28583
|
try {
|
|
28858
|
-
if (
|
|
28584
|
+
if (realpathSync(git(projectDir, ["rev-parse", "--show-toplevel"])) !== realpathSync(projectDir))
|
|
28859
28585
|
return null;
|
|
28860
28586
|
const head = git(projectDir, ["rev-parse", "HEAD"]);
|
|
28861
28587
|
const recorded = Boolean(storedAnchor);
|
|
@@ -28881,7 +28607,7 @@ function docsChangeSet(projectDir, storedAnchor) {
|
|
|
28881
28607
|
const files = [
|
|
28882
28608
|
...new Set(changed.flat().filter((file) => file !== "ARCHITECTURE.md" && file !== "STRUCTURE.md" && !/(?:^|[./-])(test|spec)(?:[./-]|$)/.test(file) && !file.endsWith(".lock")))
|
|
28883
28609
|
];
|
|
28884
|
-
const docs = FILES.map((file) => existsSync4(join7(projectDir, file)) ?
|
|
28610
|
+
const docs = FILES.map((file) => existsSync4(join7(projectDir, file)) ? readFileSync6(join7(projectDir, file), "utf8") : "").join(`
|
|
28885
28611
|
`);
|
|
28886
28612
|
const relevant = files.some((file) => {
|
|
28887
28613
|
const directory = file.split("/").slice(0, -1).join("/");
|
|
@@ -29037,7 +28763,7 @@ function validateDocsProposal(projectDir, output, budget, expected) {
|
|
|
29037
28763
|
let tokens = 0;
|
|
29038
28764
|
let diffs = "";
|
|
29039
28765
|
for (const file of FILES) {
|
|
29040
|
-
const before = existsSync4(join7(projectDir, file)) ?
|
|
28766
|
+
const before = existsSync4(join7(projectDir, file)) ? readFileSync6(join7(projectDir, file), "utf8") : "";
|
|
29041
28767
|
let after = before;
|
|
29042
28768
|
const seen = new Set;
|
|
29043
28769
|
for (const change of changes.filter((item) => item.file === file)) {
|
|
@@ -29349,7 +29075,7 @@ function throwIfAborted2(signal) {
|
|
|
29349
29075
|
}
|
|
29350
29076
|
|
|
29351
29077
|
// src/features/magic-context/smart-notes/compiler.ts
|
|
29352
|
-
import { createHash as
|
|
29078
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
29353
29079
|
|
|
29354
29080
|
// src/features/magic-context/smart-notes/compiler-prompt.ts
|
|
29355
29081
|
var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
|
|
@@ -29680,7 +29406,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
29680
29406
|
return warnings;
|
|
29681
29407
|
}
|
|
29682
29408
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
29683
|
-
return
|
|
29409
|
+
return createHash11("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
29684
29410
|
}
|
|
29685
29411
|
function extractJsonObject(output) {
|
|
29686
29412
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -30429,7 +30155,7 @@ async function archiveExpiredMemories(args) {
|
|
|
30429
30155
|
}
|
|
30430
30156
|
|
|
30431
30157
|
// src/features/magic-context/dreamer/maintain-docs-protected-enforcement.ts
|
|
30432
|
-
import { existsSync as existsSync5, readFileSync as
|
|
30158
|
+
import { existsSync as existsSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync2 } from "node:fs";
|
|
30433
30159
|
import { join as join9 } from "node:path";
|
|
30434
30160
|
var MAINTAIN_DOCS_SNAPSHOT_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
30435
30161
|
function snapshotMaintainDocsFiles(docsDir) {
|
|
@@ -30438,7 +30164,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
30438
30164
|
const path = join9(docsDir, name);
|
|
30439
30165
|
try {
|
|
30440
30166
|
if (existsSync5(path)) {
|
|
30441
|
-
snapshot.set(name,
|
|
30167
|
+
snapshot.set(name, readFileSync7(path, "utf8"));
|
|
30442
30168
|
}
|
|
30443
30169
|
} catch {}
|
|
30444
30170
|
}
|
|
@@ -30446,10 +30172,10 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
30446
30172
|
}
|
|
30447
30173
|
|
|
30448
30174
|
// src/features/magic-context/dreamer/map-memories.ts
|
|
30449
|
-
import { createHash as
|
|
30175
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
30450
30176
|
|
|
30451
30177
|
// src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
30452
|
-
import { existsSync as existsSync6, statSync as
|
|
30178
|
+
import { existsSync as existsSync6, statSync as statSync3 } from "node:fs";
|
|
30453
30179
|
import path4 from "node:path";
|
|
30454
30180
|
var MAP_MEMORIES_SYSTEM_PROMPT = `You are a memory mapper for the magic-context system. You map project memories to the repository files that back them.
|
|
30455
30181
|
|
|
@@ -30487,7 +30213,7 @@ function extractMemoryCandidatePaths(content, repoDir) {
|
|
|
30487
30213
|
if (!abs.startsWith(`${root}/`))
|
|
30488
30214
|
continue;
|
|
30489
30215
|
try {
|
|
30490
|
-
if (existsSync6(abs) &&
|
|
30216
|
+
if (existsSync6(abs) && statSync3(abs).isFile())
|
|
30491
30217
|
found.add(rel);
|
|
30492
30218
|
} catch {}
|
|
30493
30219
|
if (found.size >= MAX_SEED_PATHS_PER_MEMORY)
|
|
@@ -30919,7 +30645,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
|
|
|
30919
30645
|
name: "memory.set_mapping",
|
|
30920
30646
|
arguments: {
|
|
30921
30647
|
memory_project: args.projectIdentity,
|
|
30922
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
30648
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash12("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
30923
30649
|
rows
|
|
30924
30650
|
}
|
|
30925
30651
|
}
|
|
@@ -32154,7 +31880,7 @@ function insertDreamRun(db, run) {
|
|
|
32154
31880
|
}
|
|
32155
31881
|
|
|
32156
31882
|
// src/features/magic-context/dreamer/verify.ts
|
|
32157
|
-
import { createHash as
|
|
31883
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
32158
31884
|
|
|
32159
31885
|
// src/features/magic-context/dreamer/verify-diff.ts
|
|
32160
31886
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -32898,7 +32624,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
|
|
|
32898
32624
|
name: "memory.set_verification",
|
|
32899
32625
|
arguments: {
|
|
32900
32626
|
memory_project: args.projectIdentity,
|
|
32901
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
32627
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash13("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
32902
32628
|
rows
|
|
32903
32629
|
}
|
|
32904
32630
|
}
|
|
@@ -33704,7 +33430,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
33704
33430
|
}
|
|
33705
33431
|
function computeRetrospectiveWindowKey(flagged) {
|
|
33706
33432
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
33707
|
-
return
|
|
33433
|
+
return createHash14("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
33708
33434
|
}
|
|
33709
33435
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
33710
33436
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -34172,8 +33898,8 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
34172
33898
|
existingDocs,
|
|
34173
33899
|
docsChangeSet: changes?.text,
|
|
34174
33900
|
docsContents: task === "maintain-docs" ? {
|
|
34175
|
-
architecture: existingDocs?.architecture ?
|
|
34176
|
-
structure: existingDocs?.structure ?
|
|
33901
|
+
architecture: existingDocs?.architecture ? readFileSync8(`${docsDir}/ARCHITECTURE.md`, "utf8") : "(missing)",
|
|
33902
|
+
structure: existingDocs?.structure ? readFileSync8(`${docsDir}/STRUCTURE.md`, "utf8") : "(missing)"
|
|
34177
33903
|
} : undefined,
|
|
34178
33904
|
docsBudget: config.docsMaxTokens ?? 12000,
|
|
34179
33905
|
docsCurrentTokens: maintainDocsSnapshot ? Math.ceil([...maintainDocsSnapshot.values()].join("").length / 3.5) : 0,
|
|
@@ -34859,7 +34585,7 @@ async function runManualDreamNow(args) {
|
|
|
34859
34585
|
}
|
|
34860
34586
|
|
|
34861
34587
|
// src/plugin/dream-timer.ts
|
|
34862
|
-
import { statSync as
|
|
34588
|
+
import { statSync as statSync4 } from "node:fs";
|
|
34863
34589
|
|
|
34864
34590
|
// src/features/magic-context/dreamer/retrospective-orphan-sweep.ts
|
|
34865
34591
|
var HISTORIAN_CHILD_TITLE = "magic-context-compartment";
|
|
@@ -35017,7 +34743,7 @@ var startupJitters = new Map;
|
|
|
35017
34743
|
var nextStartupJitterSlot = 0;
|
|
35018
34744
|
function directoryStillExists(directory) {
|
|
35019
34745
|
try {
|
|
35020
|
-
return
|
|
34746
|
+
return statSync4(directory).isDirectory();
|
|
35021
34747
|
} catch {
|
|
35022
34748
|
return false;
|
|
35023
34749
|
}
|
|
@@ -35523,7 +35249,7 @@ async function sessionInThisLocation(context, sessionID) {
|
|
|
35523
35249
|
} catch {
|
|
35524
35250
|
return false;
|
|
35525
35251
|
}
|
|
35526
|
-
return location?.directory
|
|
35252
|
+
return location?.directory !== undefined && sameProjectDirectory(location.directory, context.location.directory) && (location.workspaceID ?? "") === (context.location.workspaceID ?? "");
|
|
35527
35253
|
}
|
|
35528
35254
|
function startDreamTrigger(context, args) {
|
|
35529
35255
|
const controller = new AbortController;
|
|
@@ -35590,13 +35316,28 @@ function startDreamTrigger(context, args) {
|
|
|
35590
35316
|
}
|
|
35591
35317
|
|
|
35592
35318
|
// src/v2/hooks/generate.ts
|
|
35319
|
+
function generateReplayAnchor(messages) {
|
|
35320
|
+
let index = messages.length - 1;
|
|
35321
|
+
while (index >= 0 && !messages[index]?.id)
|
|
35322
|
+
index--;
|
|
35323
|
+
if (index < 0)
|
|
35324
|
+
return;
|
|
35325
|
+
const id = messages.at(index)?.id;
|
|
35326
|
+
if (!id)
|
|
35327
|
+
return;
|
|
35328
|
+
return { id, tail: clonePreservingInstances(messages.slice(index + 1)) };
|
|
35329
|
+
}
|
|
35330
|
+
|
|
35593
35331
|
class V2GenerateReplay {
|
|
35594
35332
|
prefixes = new Map;
|
|
35595
35333
|
capture(draft, anchor) {
|
|
35596
|
-
if (!anchor)
|
|
35334
|
+
if (!anchor) {
|
|
35335
|
+
this.prefixes.delete(draft.sessionID);
|
|
35336
|
+
sessionLog2(draft.sessionID, "generate replay capture skipped: no-anchor");
|
|
35597
35337
|
return;
|
|
35338
|
+
}
|
|
35598
35339
|
this.prefixes.set(draft.sessionID, {
|
|
35599
|
-
anchor,
|
|
35340
|
+
anchor: clonePreservingInstances(anchor),
|
|
35600
35341
|
model: `${draft.model.providerID}/${draft.model.id}`,
|
|
35601
35342
|
agent: draft.agent,
|
|
35602
35343
|
system: clonePreservingInstances(draft.system),
|
|
@@ -35609,12 +35350,23 @@ class V2GenerateReplay {
|
|
|
35609
35350
|
}
|
|
35610
35351
|
apply(draft) {
|
|
35611
35352
|
const prefix = this.prefixes.get(draft.sessionID);
|
|
35612
|
-
|
|
35353
|
+
const skip = (reason) => {
|
|
35354
|
+
sessionLog2(draft.sessionID, `generate replay apply skipped: ${reason}`);
|
|
35613
35355
|
return false;
|
|
35614
|
-
|
|
35356
|
+
};
|
|
35357
|
+
if (!prefix)
|
|
35358
|
+
return skip("no-prefix");
|
|
35359
|
+
if (prefix.model !== `${draft.model.providerID}/${draft.model.id}`)
|
|
35360
|
+
return skip("model-mismatch");
|
|
35361
|
+
if (prefix.agent !== draft.agent)
|
|
35362
|
+
return skip("agent-mismatch");
|
|
35363
|
+
const index = draft.messages.findIndex((message) => message.id === prefix.anchor.id);
|
|
35615
35364
|
if (index < 0)
|
|
35616
|
-
return
|
|
35617
|
-
const
|
|
35365
|
+
return skip("anchor-not-found");
|
|
35366
|
+
const end = index + 1 + prefix.anchor.tail.length;
|
|
35367
|
+
if (JSON.stringify(draft.messages.slice(index + 1, end)) !== JSON.stringify(prefix.anchor.tail))
|
|
35368
|
+
return skip("anchor-tail-mismatch");
|
|
35369
|
+
const tail = draft.messages.slice(end);
|
|
35618
35370
|
draft.messages.splice(0, draft.messages.length, ...clonePreservingInstances(prefix.messages), ...tail);
|
|
35619
35371
|
draft.system.splice(0, draft.system.length, ...clonePreservingInstances(prefix.system));
|
|
35620
35372
|
draft.tools = clonePreservingInstances(prefix.tools);
|
|
@@ -35632,9 +35384,9 @@ function hiddenTerminalError(event) {
|
|
|
35632
35384
|
}
|
|
35633
35385
|
|
|
35634
35386
|
// src/v2/hooks/lkg-system.ts
|
|
35635
|
-
import { createHash as
|
|
35387
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
35636
35388
|
function identity(slot) {
|
|
35637
|
-
return
|
|
35389
|
+
return createHash15("sha256").update(JSON.stringify({
|
|
35638
35390
|
capturedAt: slot.capturedAt,
|
|
35639
35391
|
captureSequence: slot.captureSequence,
|
|
35640
35392
|
rowVersion: slot.rowVersion,
|
|
@@ -36755,7 +36507,7 @@ function jsonStringifyReplacer(_, value) {
|
|
|
36755
36507
|
return value.toString();
|
|
36756
36508
|
return value;
|
|
36757
36509
|
}
|
|
36758
|
-
function
|
|
36510
|
+
function cached2(getter) {
|
|
36759
36511
|
const set = false;
|
|
36760
36512
|
return {
|
|
36761
36513
|
get value() {
|
|
@@ -36866,7 +36618,7 @@ var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace :
|
|
|
36866
36618
|
function isObject(data) {
|
|
36867
36619
|
return typeof data === "object" && data !== null && !Array.isArray(data);
|
|
36868
36620
|
}
|
|
36869
|
-
var allowsEval =
|
|
36621
|
+
var allowsEval = cached2(() => {
|
|
36870
36622
|
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
|
|
36871
36623
|
return false;
|
|
36872
36624
|
}
|
|
@@ -38909,7 +38661,7 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
|
|
|
38909
38661
|
}
|
|
38910
38662
|
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
|
|
38911
38663
|
$ZodType.init(inst, def);
|
|
38912
|
-
const _normalized =
|
|
38664
|
+
const _normalized = cached2(() => normalizeDef(def));
|
|
38913
38665
|
defineLazy(inst._zod, "propValues", () => {
|
|
38914
38666
|
const shape = def.shape;
|
|
38915
38667
|
const propValues = {};
|
|
@@ -38959,7 +38711,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
|
|
|
38959
38711
|
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
|
|
38960
38712
|
$ZodObject.init(inst, def);
|
|
38961
38713
|
const superParse = inst._zod.parse;
|
|
38962
|
-
const _normalized =
|
|
38714
|
+
const _normalized = cached2(() => normalizeDef(def));
|
|
38963
38715
|
const generateFastpass = (shape) => {
|
|
38964
38716
|
const doc = new Doc(["shape", "payload", "ctx"]);
|
|
38965
38717
|
const normalized = _normalized.value;
|
|
@@ -39117,7 +38869,7 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
|
|
|
39117
38869
|
}
|
|
39118
38870
|
return propValues;
|
|
39119
38871
|
});
|
|
39120
|
-
const disc =
|
|
38872
|
+
const disc = cached2(() => {
|
|
39121
38873
|
const opts = def.options;
|
|
39122
38874
|
const map = new Map;
|
|
39123
38875
|
for (const o of opts) {
|
|
@@ -48433,8 +48185,8 @@ function resolveCtxExpandMode(args, domain) {
|
|
|
48433
48185
|
}
|
|
48434
48186
|
|
|
48435
48187
|
// src/tools/ctx-expand/render.ts
|
|
48436
|
-
import { createHash as
|
|
48437
|
-
function
|
|
48188
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
48189
|
+
function isRecord6(value) {
|
|
48438
48190
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
48439
48191
|
}
|
|
48440
48192
|
function roleLabel(role) {
|
|
@@ -48446,7 +48198,7 @@ function roleLabel(role) {
|
|
|
48446
48198
|
}
|
|
48447
48199
|
function verboseRoleLabel(msg) {
|
|
48448
48200
|
if (msg.role === "user" && msg.parts.length > 0 && msg.parts.every((part) => {
|
|
48449
|
-
if (!
|
|
48201
|
+
if (!isRecord6(part))
|
|
48450
48202
|
return false;
|
|
48451
48203
|
if (part.type === "tool_result")
|
|
48452
48204
|
return true;
|
|
@@ -48474,15 +48226,15 @@ function keyArg(input) {
|
|
|
48474
48226
|
function asToolPart(part) {
|
|
48475
48227
|
const type = typeof part.type === "string" ? part.type : "";
|
|
48476
48228
|
if (type === "tool") {
|
|
48477
|
-
const state =
|
|
48229
|
+
const state = isRecord6(part.state) ? part.state : null;
|
|
48478
48230
|
const output = state && typeof state.output === "string" ? state.output : state && state.output != null ? JSON.stringify(state.output) : null;
|
|
48479
|
-
const metadata = state &&
|
|
48231
|
+
const metadata = state && isRecord6(state.metadata) ? state.metadata : null;
|
|
48480
48232
|
const title = state && typeof state.title === "string" && state.title || metadata && typeof metadata.title === "string" && metadata.title || null;
|
|
48481
48233
|
return {
|
|
48482
48234
|
name: typeof part.tool === "string" ? part.tool : "tool",
|
|
48483
48235
|
callId: typeof part.callID === "string" ? part.callID : "",
|
|
48484
48236
|
title,
|
|
48485
|
-
input: state &&
|
|
48237
|
+
input: state && isRecord6(state.input) ? state.input : null,
|
|
48486
48238
|
output
|
|
48487
48239
|
};
|
|
48488
48240
|
}
|
|
@@ -48491,7 +48243,7 @@ function asToolPart(part) {
|
|
|
48491
48243
|
name: typeof part.name === "string" ? part.name : "tool",
|
|
48492
48244
|
callId: typeof part.id === "string" ? part.id : "",
|
|
48493
48245
|
title: null,
|
|
48494
|
-
input:
|
|
48246
|
+
input: isRecord6(part.input) ? part.input : null,
|
|
48495
48247
|
output: null
|
|
48496
48248
|
};
|
|
48497
48249
|
}
|
|
@@ -48520,7 +48272,7 @@ function reasoningOf(part) {
|
|
|
48520
48272
|
return null;
|
|
48521
48273
|
}
|
|
48522
48274
|
function renderPartPreview(part, expandTools) {
|
|
48523
|
-
if (!
|
|
48275
|
+
if (!isRecord6(part))
|
|
48524
48276
|
return null;
|
|
48525
48277
|
const expansion = expandToolPart(part, expandTools, true);
|
|
48526
48278
|
if (expansion !== null)
|
|
@@ -48547,7 +48299,7 @@ function renderPartPreview(part, expandTools) {
|
|
|
48547
48299
|
return ` • [${type}]`;
|
|
48548
48300
|
}
|
|
48549
48301
|
function renderPartFull(part) {
|
|
48550
|
-
if (!
|
|
48302
|
+
if (!isRecord6(part))
|
|
48551
48303
|
return null;
|
|
48552
48304
|
const text = textOf(part);
|
|
48553
48305
|
if (text !== null) {
|
|
@@ -48634,11 +48386,11 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
48634
48386
|
const message = readRawSessionMessageById2(sessionId, owner);
|
|
48635
48387
|
if (!message)
|
|
48636
48388
|
return `Tag ${number}'s original tool owner is no longer in stored history.`;
|
|
48637
|
-
const parts = message?.parts.filter((part) =>
|
|
48638
|
-
if (!parts.some((part) =>
|
|
48389
|
+
const parts = message?.parts.filter((part) => isRecord6(part) && asToolPart(part)?.callId === tag.messageId) ?? [];
|
|
48390
|
+
if (!parts.some((part) => isRecord6(part) && asToolPart(part)?.output !== null)) {
|
|
48639
48391
|
visitRawSessionMessages2(sessionId, message.ordinal + 1, Number.MAX_SAFE_INTEGER, (candidate) => {
|
|
48640
|
-
const matching = candidate.parts.filter((part) =>
|
|
48641
|
-
if (matching.some((part) =>
|
|
48392
|
+
const matching = candidate.parts.filter((part) => isRecord6(part) && asToolPart(part)?.callId === tag.messageId);
|
|
48393
|
+
if (matching.some((part) => isRecord6(part) && part.type === "tool_use"))
|
|
48642
48394
|
return false;
|
|
48643
48395
|
parts.push(...matching);
|
|
48644
48396
|
return matching.length === 0;
|
|
@@ -48655,9 +48407,9 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
48655
48407
|
if (!message)
|
|
48656
48408
|
return `Tag ${number}'s original text is no longer in stored history.`;
|
|
48657
48409
|
const index = scoped ? Number(scoped[2]) : 0;
|
|
48658
|
-
const piText = message.parts.filter((part) =>
|
|
48410
|
+
const piText = message.parts.filter((part) => isRecord6(part) && part.type === "text");
|
|
48659
48411
|
const part = message.parts[index];
|
|
48660
|
-
const matching = derived ? piText.filter((part) =>
|
|
48412
|
+
const matching = derived ? piText.filter((part) => isRecord6(part) && typeof part.text === "string" && createHash16("sha256").update(part.text).digest("hex") === derived[3]) : [];
|
|
48661
48413
|
const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" ? piText[index] : part;
|
|
48662
48414
|
return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
|
|
48663
48415
|
}
|
|
@@ -49408,7 +49160,7 @@ import { isAbsolute as isAbsolute2 } from "node:path";
|
|
|
49408
49160
|
|
|
49409
49161
|
// ../retina-local-fs/src/path-fence.ts
|
|
49410
49162
|
import { lstat as lstat2, readlink, realpath as realpath2 } from "node:fs/promises";
|
|
49411
|
-
import { homedir as
|
|
49163
|
+
import { homedir as homedir4 } from "node:os";
|
|
49412
49164
|
import { basename, dirname as dirname2, isAbsolute, join as join10, relative, resolve as resolve2, sep } from "node:path";
|
|
49413
49165
|
|
|
49414
49166
|
// ../retina-local-fs/src/errors.ts
|
|
@@ -49434,7 +49186,7 @@ async function resolveAndFenceProviderPath(configuredPath, options) {
|
|
|
49434
49186
|
}
|
|
49435
49187
|
var FENCED_CORTEXKIT_ROOTS = ["plexus", "claustrum", "staging", "run", "magic-context"];
|
|
49436
49188
|
async function resolveFenceRoots(options) {
|
|
49437
|
-
const configuredHomePath = resolve2(options.homeDirectory ?? process.env.HOME ??
|
|
49189
|
+
const configuredHomePath = resolve2(options.homeDirectory ?? process.env.HOME ?? homedir4());
|
|
49438
49190
|
let home;
|
|
49439
49191
|
try {
|
|
49440
49192
|
home = await realpath2(configuredHomePath);
|
|
@@ -50176,7 +49928,7 @@ function ctxReduceSelfStampMessage(tagNumber) {
|
|
|
50176
49928
|
return CTX_REDUCE_SELF_STAMP_MESSAGE_TEMPLATE.replace("§N§", `§${tagNumber}§`);
|
|
50177
49929
|
}
|
|
50178
49930
|
// src/tools/ctx-reduce/tools.ts
|
|
50179
|
-
import { createHash as
|
|
49931
|
+
import { createHash as createHash17 } from "node:crypto";
|
|
50180
49932
|
|
|
50181
49933
|
// src/features/magic-context/range-parser.ts
|
|
50182
49934
|
function parseRangeString(input) {
|
|
@@ -50245,11 +49997,11 @@ function createCtxReduceTool(deps) {
|
|
|
50245
49997
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
50246
49998
|
if (Buffer.byteLength(stableId) <= 128)
|
|
50247
49999
|
return stableId;
|
|
50248
|
-
return `oc-${
|
|
50000
|
+
return `oc-${createHash17("sha256").update(stableId).digest("hex")}`;
|
|
50249
50001
|
}
|
|
50250
50002
|
fallbackCommandSequence += 1;
|
|
50251
50003
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
50252
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
50004
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash17("sha256").update(monotonicId).digest("hex")}`;
|
|
50253
50005
|
};
|
|
50254
50006
|
return tool({
|
|
50255
50007
|
description: CTX_REDUCE_DESCRIPTION,
|
|
@@ -50332,7 +50084,7 @@ function createCtxReduceTool(deps) {
|
|
|
50332
50084
|
...protectedSet,
|
|
50333
50085
|
...protectedToolTagNumbers(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools)
|
|
50334
50086
|
]);
|
|
50335
|
-
const inertWhitespaceTagNumbers = new Set(
|
|
50087
|
+
const inertWhitespaceTagNumbers = new Set(getInertWhitespaceAssistantTagsByNumbers2(deps.db, sessionId, dropIds).map((tag) => tag.tagNumber));
|
|
50336
50088
|
const inertDropIds = [
|
|
50337
50089
|
...new Set(dropIds.filter((id) => inertWhitespaceTagNumbers.has(id)))
|
|
50338
50090
|
];
|
|
@@ -50573,6 +50325,7 @@ function createCtxSearchTool(deps) {
|
|
|
50573
50325
|
diagnostics,
|
|
50574
50326
|
gitRepositoryAvailable: typeof toolContext.directory === "string" ? directoryHasGitMetadata(toolContext.directory) : undefined,
|
|
50575
50327
|
explicitSearch: true,
|
|
50328
|
+
rerankConnectionFile: deps.rerankConnectionFile,
|
|
50576
50329
|
searchMessageHistory: (request) => searchMessageHistoryOffThread(deps.db, request),
|
|
50577
50330
|
...dateRange
|
|
50578
50331
|
});
|
|
@@ -50608,7 +50361,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
|
|
|
50608
50361
|
smartNotesEnabled: config.smart_notes.enabled,
|
|
50609
50362
|
...rustToolBackends ? { rustToolBackends } : {}
|
|
50610
50363
|
}),
|
|
50611
|
-
...createCtxSearchTools(project),
|
|
50364
|
+
...createCtxSearchTools({ ...project, rerankConnectionFile: config.subc?.connection_file }),
|
|
50612
50365
|
...config.memory.enabled ? {
|
|
50613
50366
|
...createCtxMemoryTools({
|
|
50614
50367
|
...project,
|
|
@@ -51079,6 +50832,7 @@ async function registerContext(context) {
|
|
|
51079
50832
|
keepSubagents: config.keep_subagents === true,
|
|
51080
50833
|
ensureAgent: () => hiddenAgentsReady ??= context.agent.reload(),
|
|
51081
50834
|
modelCatalog: () => Promise.resolve(context.model.list()),
|
|
50835
|
+
historianTemperature: () => config.historian?.temperature,
|
|
51082
50836
|
openReader: openStoreReader
|
|
51083
50837
|
});
|
|
51084
50838
|
};
|
|
@@ -51389,6 +51143,7 @@ async function registerContext(context) {
|
|
|
51389
51143
|
}
|
|
51390
51144
|
if (event.type === "session.deleted") {
|
|
51391
51145
|
deletedSessions.add(sessionID);
|
|
51146
|
+
transform?.clearSessionLogState(sessionID);
|
|
51392
51147
|
if (db) {
|
|
51393
51148
|
markSessionCleanupPending(db, sessionID);
|
|
51394
51149
|
clearSession(db, sessionID);
|
|
@@ -51922,10 +51677,12 @@ ${baseline}
|
|
|
51922
51677
|
}
|
|
51923
51678
|
};
|
|
51924
51679
|
await context.session.hook("context", (draft) => withSqliteTransformPass2(async () => {
|
|
51925
|
-
const anchor = draft.messages
|
|
51680
|
+
const anchor = generateReplayAnchor(draft.messages);
|
|
51926
51681
|
await runManagedContext(draft);
|
|
51927
|
-
if (!compactionOff
|
|
51682
|
+
if (!compactionOff)
|
|
51928
51683
|
generateReplay.capture(draft, anchor);
|
|
51684
|
+
else
|
|
51685
|
+
sessionLog2(draft.sessionID, "generate replay capture skipped: compaction-disabled");
|
|
51929
51686
|
}));
|
|
51930
51687
|
await context.session.hook("generate", async (draft) => {
|
|
51931
51688
|
if (!compactionOff && !deletedSessions.has(draft.sessionID))
|