@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
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
log2,
|
|
16
16
|
sessionLog2,
|
|
17
17
|
getLoggerDiagnostics2
|
|
18
|
-
} from "./index-
|
|
18
|
+
} from "./index-nsjyysj0.js";
|
|
19
19
|
import {
|
|
20
20
|
resolveOpenCodeDbPath,
|
|
21
21
|
assertOpenCodeStoreGeneration,
|
|
@@ -54,7 +54,7 @@ import {
|
|
|
54
54
|
storedPathBelongsToIdentity,
|
|
55
55
|
beginBootQuietPeriod,
|
|
56
56
|
scheduleAfterBootQuiet
|
|
57
|
-
} from "./index-
|
|
57
|
+
} from "./index-pxwp2hjk.js";
|
|
58
58
|
import {
|
|
59
59
|
recordSessionProjectIdentity,
|
|
60
60
|
hasRecordedSessionProjectIdentity,
|
|
@@ -82,21 +82,7 @@ import {
|
|
|
82
82
|
drainCommitBacklogForProject2,
|
|
83
83
|
embedSessionCompartmentChunks2,
|
|
84
84
|
getEmbeddingCoverageStatus2
|
|
85
|
-
} from "./index-
|
|
86
|
-
import {
|
|
87
|
-
Priority,
|
|
88
|
-
AdmissionClass,
|
|
89
|
-
SocketClosedError,
|
|
90
|
-
SocketTimeoutError,
|
|
91
|
-
StaleRouteHandleError,
|
|
92
|
-
SubcClient,
|
|
93
|
-
isConsumerReconnectTransient,
|
|
94
|
-
connectionFileExists,
|
|
95
|
-
SYNAPSE_DEFAULT_MODEL,
|
|
96
|
-
toSynapseLaneDescriptor,
|
|
97
|
-
formatSynapseLaneDescriptor,
|
|
98
|
-
SynapseEmbeddingProvider
|
|
99
|
-
} from "./index-72nhv486.js";
|
|
85
|
+
} from "./index-kp5qe690.js";
|
|
100
86
|
import {
|
|
101
87
|
hasTrustedAbsoluteWall,
|
|
102
88
|
applyProvenInputFloor,
|
|
@@ -108,7 +94,7 @@ import {
|
|
|
108
94
|
deriveTriggerBudget2,
|
|
109
95
|
resolveKnownHistorianContextLimit2,
|
|
110
96
|
resolveHistorianProducerLimits2
|
|
111
|
-
} from "./index-
|
|
97
|
+
} from "./index-57mrqed8.js";
|
|
112
98
|
import {
|
|
113
99
|
resolveModelCalibration,
|
|
114
100
|
calibrateBuckets,
|
|
@@ -122,7 +108,7 @@ import {
|
|
|
122
108
|
estimateTokens,
|
|
123
109
|
estimateFixedPromptTokens,
|
|
124
110
|
normalizeText
|
|
125
|
-
} from "./index-
|
|
111
|
+
} from "./index-qx53vezw.js";
|
|
126
112
|
import {
|
|
127
113
|
protectedToolTagNumbers,
|
|
128
114
|
protectedToolTokenCount,
|
|
@@ -151,7 +137,7 @@ import {
|
|
|
151
137
|
tryGetReasoningTokenEstimatesByMessage2,
|
|
152
138
|
isTagOwnerSummaryReady2,
|
|
153
139
|
updateTagStatus2,
|
|
154
|
-
|
|
140
|
+
getInertWhitespaceAssistantTagsByNumbers2,
|
|
155
141
|
deriveTagLoadFloor2,
|
|
156
142
|
getTagsBySession2,
|
|
157
143
|
getActiveTagsBySession2,
|
|
@@ -160,23 +146,23 @@ import {
|
|
|
160
146
|
getDroppedTagsByNumbers2,
|
|
161
147
|
getMaxDroppedTagNumber2,
|
|
162
148
|
getTagById2
|
|
163
|
-
} from "./index-
|
|
149
|
+
} from "./index-nydv6g8r.js";
|
|
164
150
|
import {
|
|
165
151
|
observeTemporalDecisions
|
|
166
|
-
} from "./index-
|
|
152
|
+
} from "./index-1bt88epp.js";
|
|
167
153
|
import {
|
|
168
154
|
isRawCompactionSummaryInfo2,
|
|
169
155
|
extractInMemoryMessageViews2,
|
|
170
156
|
buildInMemoryTailRawMessages2,
|
|
171
157
|
runSessionWarmupWorker
|
|
172
|
-
} from "./index-
|
|
158
|
+
} from "./index-h5zfkjyk.js";
|
|
173
159
|
import {
|
|
174
160
|
openCodeDbExists,
|
|
175
161
|
withReadOnlySessionDb,
|
|
176
162
|
assistantAwaitingTools,
|
|
177
163
|
latestPersistedMessageForRecovery,
|
|
178
164
|
findLastAssistantModelFromOpenCodeDb
|
|
179
|
-
} from "./index-
|
|
165
|
+
} from "./index-9qjqq45k.js";
|
|
180
166
|
import {
|
|
181
167
|
expandToolPart,
|
|
182
168
|
estimateTrueRawMessageTokens,
|
|
@@ -207,13 +193,14 @@ import {
|
|
|
207
193
|
getRawSessionStoredMessageCount2,
|
|
208
194
|
readRawSessionMessageIdOrdinalsForRange2,
|
|
209
195
|
readRawSessionMessagePartsById2,
|
|
196
|
+
readRawSessionBoundaryEndpoints2,
|
|
210
197
|
readRawSessionMessageById2,
|
|
211
198
|
readSessionChunk2,
|
|
212
199
|
readRawSessionSeedTail2
|
|
213
|
-
} from "./index-
|
|
200
|
+
} from "./index-2jgwttpt.js";
|
|
214
201
|
import {
|
|
215
202
|
getMeasuredToolDefinitionTokens
|
|
216
|
-
} from "./index-
|
|
203
|
+
} from "./index-h2wc01qk.js";
|
|
217
204
|
import {
|
|
218
205
|
CANONICAL_DREAM_TASKS,
|
|
219
206
|
DREAM_TASK_CAPABILITIES,
|
|
@@ -241,7 +228,7 @@ import {
|
|
|
241
228
|
DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
242
229
|
DREAM_TASK_PROMOTION_DEFAULTS,
|
|
243
230
|
getLocalEmbeddingNativeMemoryStats
|
|
244
|
-
} from "./index-
|
|
231
|
+
} from "./index-kq57tdf0.js";
|
|
245
232
|
import {
|
|
246
233
|
isFailClosedBlockingError,
|
|
247
234
|
shouldBypassFailClosedBlock,
|
|
@@ -260,7 +247,7 @@ import {
|
|
|
260
247
|
runSqliteOptimize,
|
|
261
248
|
openDatabase,
|
|
262
249
|
openCurrentDatabase
|
|
263
|
-
} from "./index-
|
|
250
|
+
} from "./index-s4j7t92z.js";
|
|
264
251
|
import {
|
|
265
252
|
configureContextDatabasePragmas2
|
|
266
253
|
} from "./index-fb3zxn06.js";
|
|
@@ -274,7 +261,7 @@ import {
|
|
|
274
261
|
resolveStoredPathWorkspaceIdentity,
|
|
275
262
|
storedPathBelongsToWorkspace,
|
|
276
263
|
computeWorkspaceEpochFingerprint
|
|
277
|
-
} from "./index-
|
|
264
|
+
} from "./index-nm6a8xpd.js";
|
|
278
265
|
import {
|
|
279
266
|
V2_MEMORY_CATEGORIES,
|
|
280
267
|
CATEGORY_PRIORITY
|
|
@@ -291,14 +278,6 @@ import {
|
|
|
291
278
|
BoundedSessionMap,
|
|
292
279
|
historianRunConfig,
|
|
293
280
|
currentPluginConfigReader,
|
|
294
|
-
USER_FACING_FAILURES,
|
|
295
|
-
renderUserFacingFailure,
|
|
296
|
-
userFacingFailureCode,
|
|
297
|
-
renderCapabilityRefusal,
|
|
298
|
-
capabilityRefusalCode,
|
|
299
|
-
renderDreamFailure,
|
|
300
|
-
dreamFailureCode,
|
|
301
|
-
renderEmbeddingFailure,
|
|
302
281
|
clampProducerAtomChars,
|
|
303
282
|
producerInputTokenLimit,
|
|
304
283
|
historianProducerReserve,
|
|
@@ -371,10 +350,12 @@ import {
|
|
|
371
350
|
getPersistedCompactionMarkerState,
|
|
372
351
|
setPersistedCompactionMarkerState,
|
|
373
352
|
getStrippedPlaceholderIds,
|
|
353
|
+
thinkingBindingRecoveryFrozenId,
|
|
374
354
|
getThinkingBindingRecoveryTarget,
|
|
375
355
|
armThinkingBindingRecovery,
|
|
376
356
|
clearThinkingBindingRecoveryIf,
|
|
377
357
|
getMergedReasoningStrippedIds,
|
|
358
|
+
addMergedReasoningStrippedIds,
|
|
378
359
|
getStaleReduceStrippedIds,
|
|
379
360
|
getProcessedImageStrippedIds,
|
|
380
361
|
getPendingCompactionMarkerState,
|
|
@@ -497,7 +478,15 @@ import {
|
|
|
497
478
|
snapRangeToCompartments,
|
|
498
479
|
getActiveCompartmentRun,
|
|
499
480
|
startCompartmentAgent
|
|
500
|
-
} from "./index-
|
|
481
|
+
} from "./index-2jcbj7r1.js";
|
|
482
|
+
import {
|
|
483
|
+
SubcClient,
|
|
484
|
+
connectionFileExists,
|
|
485
|
+
SYNAPSE_DEFAULT_MODEL,
|
|
486
|
+
toSynapseLaneDescriptor,
|
|
487
|
+
formatSynapseLaneDescriptor,
|
|
488
|
+
SynapseEmbeddingProvider
|
|
489
|
+
} from "./index-vkbqdnkj.js";
|
|
501
490
|
import {
|
|
502
491
|
getMessageIndexSourceIdentity,
|
|
503
492
|
isMessageIndexSourceCurrent,
|
|
@@ -508,8 +497,15 @@ import {
|
|
|
508
497
|
indexSingleMessage,
|
|
509
498
|
indexMessagesAfterOrdinal,
|
|
510
499
|
sweepOrphanedOpenCodeMessageIndexes
|
|
511
|
-
} from "./index-
|
|
500
|
+
} from "./index-hj2q50k0.js";
|
|
512
501
|
import {
|
|
502
|
+
renderUserFacingFailure,
|
|
503
|
+
userFacingFailureCode,
|
|
504
|
+
renderCapabilityRefusal,
|
|
505
|
+
capabilityRefusalCode,
|
|
506
|
+
renderDreamFailure,
|
|
507
|
+
dreamFailureCode,
|
|
508
|
+
renderEmbeddingFailure,
|
|
513
509
|
SESSION_NOTE_CONDITION_ERROR,
|
|
514
510
|
getNoteByIdInScope,
|
|
515
511
|
getNotes,
|
|
@@ -545,7 +541,7 @@ import {
|
|
|
545
541
|
readGitFileChangeTimesSince,
|
|
546
542
|
verificationFileExists,
|
|
547
543
|
normalizeVerificationFiles
|
|
548
|
-
} from "./index-
|
|
544
|
+
} from "./index-kmpvemph.js";
|
|
549
545
|
import {
|
|
550
546
|
registerNotificationSink2,
|
|
551
547
|
pushNotification2,
|
|
@@ -560,7 +556,7 @@ import {
|
|
|
560
556
|
} from "./index-4dhv7mqz.js";
|
|
561
557
|
import {
|
|
562
558
|
cosineSimilarity
|
|
563
|
-
} from "./index-
|
|
559
|
+
} from "./index-peshmj6h.js";
|
|
564
560
|
import {
|
|
565
561
|
computeCueContentHash,
|
|
566
562
|
hasMuralCueColumns,
|
|
@@ -587,6 +583,18 @@ import {
|
|
|
587
583
|
getMemoryCountsByStatus2
|
|
588
584
|
} from "./index-7jzrrxap.js";
|
|
589
585
|
import {
|
|
586
|
+
renderSingleStoreMigrationRequiredRefusal,
|
|
587
|
+
SingleStoreMigrationRequiredError,
|
|
588
|
+
singleStoreMigrationRequiredFailure,
|
|
589
|
+
projectNeedsSingleStoreMigration,
|
|
590
|
+
STORE_AHEAD_OF_BINARY_CODE,
|
|
591
|
+
storeAheadOfBinaryFailure,
|
|
592
|
+
TRANSFORM_PAGE_UPLOAD_TIMEOUT_MS,
|
|
593
|
+
transformColdStartExecuteTimeoutMs,
|
|
594
|
+
MAX_WRAPUP_REQUEST_BUDGET_MS,
|
|
595
|
+
getDefaultSubcConnectionFile,
|
|
596
|
+
isModuleTransportGenerationChangedResult,
|
|
597
|
+
SubcModuleTransport,
|
|
590
598
|
indexCommitsForProject,
|
|
591
599
|
embedUnembeddedCommits,
|
|
592
600
|
createUnifiedSearchDiagnostics2,
|
|
@@ -594,17 +602,17 @@ import {
|
|
|
594
602
|
resolveMemoriesByIdsForSearch2,
|
|
595
603
|
unifiedSearch2,
|
|
596
604
|
formatSearchResults2
|
|
597
|
-
} from "./index-
|
|
605
|
+
} from "./index-ha87j7a8.js";
|
|
598
606
|
import {
|
|
599
607
|
flushIgnoredMessages2,
|
|
600
608
|
clearIgnoredMessages2,
|
|
601
609
|
observeIgnoredNotificationEvent2,
|
|
602
610
|
sendStatusNotification2
|
|
603
|
-
} from "./index-
|
|
611
|
+
} from "./index-9rt53q79.js";
|
|
604
612
|
import {
|
|
605
613
|
setRecompStarting2,
|
|
606
614
|
setRecompTerminal2
|
|
607
|
-
} from "./index-
|
|
615
|
+
} from "./index-ezmszwbd.js";
|
|
608
616
|
import {
|
|
609
617
|
searchMessageHistoryOffThread,
|
|
610
618
|
findSessionId,
|
|
@@ -626,6 +634,7 @@ import {
|
|
|
626
634
|
replayClearedReasoning,
|
|
627
635
|
replayStrippedInlineThinking,
|
|
628
636
|
stripClearedReasoning,
|
|
637
|
+
findReasoningBearingAssistantIds,
|
|
629
638
|
snapshotTrailingBlankSourceDecisions,
|
|
630
639
|
projectOpencodeReasoningBudgetCutoff,
|
|
631
640
|
resolveKeepReasoningTokens,
|
|
@@ -633,9 +642,12 @@ import {
|
|
|
633
642
|
captureOpencodeReasoningBudgetStatus,
|
|
634
643
|
reasoningBudgetStatusLine,
|
|
635
644
|
ENGINE_RECONNECTING_USER_MESSAGE,
|
|
645
|
+
ENGINE_BUSY_USER_MESSAGE,
|
|
646
|
+
SIGNED_THINKING_RESET_FENCE_FAILED,
|
|
636
647
|
contextRefusalError,
|
|
637
648
|
protectedToolRefusal,
|
|
638
649
|
outgoingContextRefusal,
|
|
650
|
+
signedTurnContextRefusal,
|
|
639
651
|
EmergencyFailClosedError,
|
|
640
652
|
latestAssistantTurnStart,
|
|
641
653
|
latestAssistantTurnMessages,
|
|
@@ -658,7 +670,7 @@ import {
|
|
|
658
670
|
abortSessionFailClosed2,
|
|
659
671
|
evaluateEmergencyFailClosed2,
|
|
660
672
|
runPostTransformPhase2
|
|
661
|
-
} from "./index-
|
|
673
|
+
} from "./index-1g30axtz.js";
|
|
662
674
|
import {
|
|
663
675
|
ANNOUNCEMENT_VERSION2,
|
|
664
676
|
ANNOUNCEMENT_FEATURES2,
|
|
@@ -697,7 +709,7 @@ import {
|
|
|
697
709
|
} from "./index-8ajstryz.js";
|
|
698
710
|
import {
|
|
699
711
|
logSlowWriteTransaction
|
|
700
|
-
} from "./index-
|
|
712
|
+
} from "./index-4mjhqadz.js";
|
|
701
713
|
|
|
702
714
|
// src/features/magic-context/dreamer/open-opencode-db.ts
|
|
703
715
|
function openOpenCodeDb() {
|
|
@@ -1258,765 +1270,6 @@ function createLiveSessionState() {
|
|
|
1258
1270
|
};
|
|
1259
1271
|
}
|
|
1260
1272
|
|
|
1261
|
-
// src/hooks/magic-context/module-transport.ts
|
|
1262
|
-
import { realpathSync } from "node:fs";
|
|
1263
|
-
import { join } from "node:path";
|
|
1264
|
-
|
|
1265
|
-
// src/hooks/magic-context/reply-pages.ts
|
|
1266
|
-
import { createHash } from "node:crypto";
|
|
1267
|
-
var MAX_REPLY_BYTES = 128 * 1024 * 1024;
|
|
1268
|
-
var MAX_PAGE_BYTES = 512 * 1024;
|
|
1269
|
-
function fail() {
|
|
1270
|
-
throw Object.assign(new Error("Incomplete or invalid module reply; abandon this pass"), {
|
|
1271
|
-
code: "reply_page_invalid"
|
|
1272
|
-
});
|
|
1273
|
-
}
|
|
1274
|
-
async function assembleReplyPages(response, fetchPage) {
|
|
1275
|
-
if (!isRecord(response) || !("reply_page" in response))
|
|
1276
|
-
return response;
|
|
1277
|
-
const first = response.reply_page;
|
|
1278
|
-
if (!isRecord(first))
|
|
1279
|
-
fail();
|
|
1280
|
-
const { id, total, bytes } = first;
|
|
1281
|
-
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)
|
|
1282
|
-
fail();
|
|
1283
|
-
const chunks = [];
|
|
1284
|
-
let received = 0;
|
|
1285
|
-
for (let index = 0;index < total; index += 1) {
|
|
1286
|
-
const envelope = index === 0 ? response : await fetchPage(id, index);
|
|
1287
|
-
if (!isRecord(envelope) || !isRecord(envelope.reply_page))
|
|
1288
|
-
fail();
|
|
1289
|
-
const page = envelope.reply_page;
|
|
1290
|
-
if (page.id !== id || page.index !== index || page.total !== total || page.bytes !== bytes || typeof page.data !== "string")
|
|
1291
|
-
fail();
|
|
1292
|
-
if (Buffer.byteLength(JSON.stringify(envelope)) > MAX_PAGE_BYTES)
|
|
1293
|
-
fail();
|
|
1294
|
-
const chunk = Buffer.from(page.data, "utf8");
|
|
1295
|
-
received += chunk.length;
|
|
1296
|
-
if (received > bytes)
|
|
1297
|
-
fail();
|
|
1298
|
-
chunks.push(chunk);
|
|
1299
|
-
}
|
|
1300
|
-
if (received !== bytes)
|
|
1301
|
-
fail();
|
|
1302
|
-
const rebuilt = Buffer.concat(chunks, received);
|
|
1303
|
-
if (createHash("sha256").update(rebuilt).digest("hex") !== id)
|
|
1304
|
-
fail();
|
|
1305
|
-
return JSON.parse(rebuilt.toString("utf8"));
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
// src/hooks/magic-context/single-store-refusal.ts
|
|
1309
|
-
var SINGLE_STORE_MIGRATION_REQUIRED_CODE = "single_store_migration_required";
|
|
1310
|
-
function renderSingleStoreMigrationRequiredRefusal() {
|
|
1311
|
-
const failure = USER_FACING_FAILURES.single_store_migration_required;
|
|
1312
|
-
return `${failure.sentence} ${failure.action} (${failure.code})`;
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
class SingleStoreMigrationRequiredError extends Error {
|
|
1316
|
-
code = SINGLE_STORE_MIGRATION_REQUIRED_CODE;
|
|
1317
|
-
constructor(options) {
|
|
1318
|
-
super(renderSingleStoreMigrationRequiredRefusal(), options);
|
|
1319
|
-
this.name = "SingleStoreMigrationRequiredError";
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
function singleStoreMigrationRequiredFailure(error) {
|
|
1323
|
-
let current = error;
|
|
1324
|
-
const seen = new Set;
|
|
1325
|
-
while (current !== null && typeof current === "object" && !seen.has(current)) {
|
|
1326
|
-
seen.add(current);
|
|
1327
|
-
if (current instanceof SingleStoreMigrationRequiredError)
|
|
1328
|
-
return current;
|
|
1329
|
-
const frame = current;
|
|
1330
|
-
if (frame.code === SINGLE_STORE_MIGRATION_REQUIRED_CODE || frame.code === "single_store_state_split") {
|
|
1331
|
-
return new SingleStoreMigrationRequiredError({ cause: error });
|
|
1332
|
-
}
|
|
1333
|
-
current = frame.cause;
|
|
1334
|
-
}
|
|
1335
|
-
return null;
|
|
1336
|
-
}
|
|
1337
|
-
function projectNeedsSingleStoreMigration(db, projectPath) {
|
|
1338
|
-
const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'authority_managed'").get();
|
|
1339
|
-
return Boolean(table && db.prepare("SELECT 1 FROM authority_managed WHERE project_path = ?").get(projectPath));
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
// src/hooks/magic-context/store-ahead-refusal.ts
|
|
1343
|
-
var STORE_AHEAD_OF_BINARY_CODE = "store_ahead_of_binary";
|
|
1344
|
-
function renderStoreAheadOfBinaryRefusal(versions) {
|
|
1345
|
-
const failure = USER_FACING_FAILURES.store_ahead_of_binary;
|
|
1346
|
-
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;
|
|
1347
|
-
return `${sentence} ${failure.action} (${failure.code})`;
|
|
1348
|
-
}
|
|
1349
|
-
|
|
1350
|
-
class StoreAheadOfBinaryError extends Error {
|
|
1351
|
-
code = STORE_AHEAD_OF_BINARY_CODE;
|
|
1352
|
-
versions;
|
|
1353
|
-
constructor(versions, options) {
|
|
1354
|
-
super(renderStoreAheadOfBinaryRefusal(versions), options);
|
|
1355
|
-
this.name = "StoreAheadOfBinaryError";
|
|
1356
|
-
this.versions = versions;
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
1359
|
-
function isRecord2(value) {
|
|
1360
|
-
return value !== null && typeof value === "object";
|
|
1361
|
-
}
|
|
1362
|
-
function nonNegativeInteger(value) {
|
|
1363
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
1364
|
-
}
|
|
1365
|
-
function versionsFromDetail(detail) {
|
|
1366
|
-
if (!isRecord2(detail))
|
|
1367
|
-
return null;
|
|
1368
|
-
const dbVersion = nonNegativeInteger(detail.db_version);
|
|
1369
|
-
const binaryMax = nonNegativeInteger(detail.binary_max);
|
|
1370
|
-
return dbVersion !== null && binaryMax !== null ? { dbVersion, binaryMax } : null;
|
|
1371
|
-
}
|
|
1372
|
-
function versionsFromMessage(message) {
|
|
1373
|
-
if (typeof message !== "string")
|
|
1374
|
-
return null;
|
|
1375
|
-
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);
|
|
1376
|
-
if (!match)
|
|
1377
|
-
return null;
|
|
1378
|
-
return { dbVersion: Number(match[1]), binaryMax: Number(match[2]) };
|
|
1379
|
-
}
|
|
1380
|
-
function storeAheadOfBinaryFailure(error) {
|
|
1381
|
-
let current = error;
|
|
1382
|
-
const seen = new Set;
|
|
1383
|
-
while (isRecord2(current) && !seen.has(current)) {
|
|
1384
|
-
seen.add(current);
|
|
1385
|
-
if (current instanceof StoreAheadOfBinaryError)
|
|
1386
|
-
return current;
|
|
1387
|
-
if (current.code === STORE_AHEAD_OF_BINARY_CODE) {
|
|
1388
|
-
const versions = versionsFromDetail(current.detail) ?? versionsFromMessage(current.message);
|
|
1389
|
-
return new StoreAheadOfBinaryError(versions, { cause: error });
|
|
1390
|
-
}
|
|
1391
|
-
current = current.cause;
|
|
1392
|
-
}
|
|
1393
|
-
return null;
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
// src/hooks/magic-context/module-transport.ts
|
|
1397
|
-
var DEFAULT_MODULE_ID = "magic-context";
|
|
1398
|
-
var CONNECT_BACKOFF_INITIAL_MS = 1000;
|
|
1399
|
-
var CONNECT_BACKOFF_MAX_MS = 30000;
|
|
1400
|
-
var CONNECT_BACKOFF_WAIT_BUDGET_MS = 12000;
|
|
1401
|
-
var CONNECT_BACKOFF_WAIT_JITTER_MS = 100;
|
|
1402
|
-
var HANDSHAKE_TIMEOUT_MS = 2000;
|
|
1403
|
-
var MODULE_SEND_TIMEOUT_MS = 15000;
|
|
1404
|
-
var TRANSFORM_PAGE_UPLOAD_TIMEOUT_MS = 5000;
|
|
1405
|
-
var TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MS = 15000;
|
|
1406
|
-
var TRANSFORM_COLD_START_EXECUTE_TIMEOUT_PER_MESSAGE_MS = 2;
|
|
1407
|
-
var TRANSFORM_COLD_START_EXECUTE_TIMEOUT_MAX_MS = 90000;
|
|
1408
|
-
function transformColdStartExecuteTimeoutMs(seedMessageCount) {
|
|
1409
|
-
const messages = Number.isSafeInteger(seedMessageCount) ? Math.max(0, seedMessageCount) : 0;
|
|
1410
|
-
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);
|
|
1411
|
-
}
|
|
1412
|
-
var MAX_WRAPUP_REQUEST_BUDGET_MS = 3800000;
|
|
1413
|
-
var SERIAL_LANE_MAX_WAITERS = 16;
|
|
1414
|
-
var SERIAL_LANE_MAX_WAITERS_PER_SESSION = 8;
|
|
1415
|
-
var SERIAL_LANE_MIN_REMAINING_MS = 25;
|
|
1416
|
-
var CANONICAL_ROOT_CACHE_MAX_ENTRIES = 256;
|
|
1417
|
-
function getDefaultSubcConnectionFile() {
|
|
1418
|
-
return join(getDataDir(), "cortexkit", "run", "subc-connection.json");
|
|
1419
|
-
}
|
|
1420
|
-
function errorChainSome(error, predicate) {
|
|
1421
|
-
let current = error;
|
|
1422
|
-
const seen = new Set;
|
|
1423
|
-
while (isRecord(current) && !seen.has(current)) {
|
|
1424
|
-
seen.add(current);
|
|
1425
|
-
if (predicate(current))
|
|
1426
|
-
return true;
|
|
1427
|
-
current = current.cause;
|
|
1428
|
-
}
|
|
1429
|
-
return false;
|
|
1430
|
-
}
|
|
1431
|
-
function isStaleOrDeadRouteFailure(error) {
|
|
1432
|
-
return errorChainSome(error, (current) => {
|
|
1433
|
-
const code = typeof current.code === "string" ? current.code : "";
|
|
1434
|
-
const name = typeof current.name === "string" ? current.name : "";
|
|
1435
|
-
const message = typeof current.message === "string" ? current.message : "";
|
|
1436
|
-
return [
|
|
1437
|
-
"stale_route_handle",
|
|
1438
|
-
"route_closed",
|
|
1439
|
-
"unknown_channel",
|
|
1440
|
-
"unrecognized_channel",
|
|
1441
|
-
"route_gone"
|
|
1442
|
-
].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);
|
|
1443
|
-
});
|
|
1444
|
-
}
|
|
1445
|
-
function isDeadlineFailure(error) {
|
|
1446
|
-
if (error instanceof SocketTimeoutError)
|
|
1447
|
-
return true;
|
|
1448
|
-
return errorChainSome(error, (current) => {
|
|
1449
|
-
const code = typeof current.code === "string" ? current.code : "";
|
|
1450
|
-
return ["ETIMEDOUT", "request_deadline", "deadline_exceeded_no_drop_observed"].includes(code);
|
|
1451
|
-
});
|
|
1452
|
-
}
|
|
1453
|
-
function isConnectionFailure(error) {
|
|
1454
|
-
if (error instanceof SocketClosedError || error instanceof SocketTimeoutError || error instanceof StaleRouteHandleError || isConsumerReconnectTransient(error) || isStaleOrDeadRouteFailure(error)) {
|
|
1455
|
-
return true;
|
|
1456
|
-
}
|
|
1457
|
-
return errorChainSome(error, (current) => {
|
|
1458
|
-
const code = typeof current.code === "string" ? current.code : "";
|
|
1459
|
-
const message = typeof current.message === "string" ? current.message : "";
|
|
1460
|
-
return [
|
|
1461
|
-
"ENOENT",
|
|
1462
|
-
"ECONNREFUSED",
|
|
1463
|
-
"ECONNRESET",
|
|
1464
|
-
"EPIPE",
|
|
1465
|
-
"ETIMEDOUT",
|
|
1466
|
-
"request_deadline",
|
|
1467
|
-
"deadline_exceeded_no_drop_observed",
|
|
1468
|
-
"connection_dropped",
|
|
1469
|
-
"SUBC_CONNECTION_BACKOFF"
|
|
1470
|
-
].includes(code) || /\bclient closed\b|\bconnection closed\b|\bclosed the connection\b/i.test(message);
|
|
1471
|
-
});
|
|
1472
|
-
}
|
|
1473
|
-
function routeOpenWithoutAmbientConsumerIdentity(client, target, identity, options = {}) {
|
|
1474
|
-
return client.routeOpen(target, identity, {
|
|
1475
|
-
...options,
|
|
1476
|
-
consumerIdentity: null
|
|
1477
|
-
});
|
|
1478
|
-
}
|
|
1479
|
-
function isModuleTransportGenerationChangedResult(value) {
|
|
1480
|
-
return isRecord(value) && value.transport_status === "connection_generation_changed" && typeof value.previous_generation === "number" && typeof value.current_generation === "number";
|
|
1481
|
-
}
|
|
1482
|
-
function moduleRequestBody(body, method) {
|
|
1483
|
-
if (!isRecord(body))
|
|
1484
|
-
return body;
|
|
1485
|
-
const facade = typeof body.name === "string" && isRecord(body.arguments);
|
|
1486
|
-
return { ...body, ...facade ? {} : { method }, accept_reply_pages: true };
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
class SubcModuleTransport {
|
|
1490
|
-
connectionFile;
|
|
1491
|
-
moduleId;
|
|
1492
|
-
requestTimeoutMs;
|
|
1493
|
-
routeSessionPrefix;
|
|
1494
|
-
client = null;
|
|
1495
|
-
routes = new Map;
|
|
1496
|
-
routeOpenings = new Map;
|
|
1497
|
-
canonicalRootCache = new Map;
|
|
1498
|
-
sessionLanes = new Map;
|
|
1499
|
-
queuedLaneWaiters = 0;
|
|
1500
|
-
wrapupSessions = new Map;
|
|
1501
|
-
nextProbeMs = 0;
|
|
1502
|
-
connectionPromise = null;
|
|
1503
|
-
backoffMs = CONNECT_BACKOFF_INITIAL_MS;
|
|
1504
|
-
connectionGeneration = 0;
|
|
1505
|
-
stateSyncCapabilityCache = null;
|
|
1506
|
-
getCachedStateSyncCapabilities() {
|
|
1507
|
-
const cached = this.stateSyncCapabilityCache;
|
|
1508
|
-
if (!cached || cached.generation !== this.connectionGeneration)
|
|
1509
|
-
return;
|
|
1510
|
-
return cached.capabilities;
|
|
1511
|
-
}
|
|
1512
|
-
invalidateStateSyncCapabilities() {
|
|
1513
|
-
this.stateSyncCapabilityCache = null;
|
|
1514
|
-
}
|
|
1515
|
-
async stateSyncCapabilities(args) {
|
|
1516
|
-
const cached = this.getCachedStateSyncCapabilities();
|
|
1517
|
-
if (cached)
|
|
1518
|
-
return cached;
|
|
1519
|
-
const response = await this.call({
|
|
1520
|
-
sessionId: args.sessionId,
|
|
1521
|
-
projectRoot: args.projectRoot,
|
|
1522
|
-
method: "session.status",
|
|
1523
|
-
body: { method: "session.status", v: 1, session_id: args.sessionId }
|
|
1524
|
-
});
|
|
1525
|
-
const raw = isRecord(response) ? response : {};
|
|
1526
|
-
const value = isRecord(raw.result) ? raw.result : raw;
|
|
1527
|
-
const epochs = isRecord(value.epochs) ? value.epochs : {};
|
|
1528
|
-
const capabilities = {
|
|
1529
|
-
state_sync_deltas: epochs.state_sync_deltas === true,
|
|
1530
|
-
...epochs.state_sync_resume === true ? { state_sync_resume: true } : {}
|
|
1531
|
-
};
|
|
1532
|
-
this.stateSyncCapabilityCache = { generation: this.connectionGeneration, capabilities };
|
|
1533
|
-
return capabilities;
|
|
1534
|
-
}
|
|
1535
|
-
constructor(connectionFile, moduleId = DEFAULT_MODULE_ID, requestTimeoutMs = MODULE_SEND_TIMEOUT_MS, routeSessionPrefix = "") {
|
|
1536
|
-
this.connectionFile = connectionFile;
|
|
1537
|
-
this.moduleId = moduleId;
|
|
1538
|
-
this.requestTimeoutMs = requestTimeoutMs;
|
|
1539
|
-
this.routeSessionPrefix = routeSessionPrefix;
|
|
1540
|
-
}
|
|
1541
|
-
deadlineError(detail) {
|
|
1542
|
-
const error = new Error(`module transport deadline expired ${detail}`);
|
|
1543
|
-
error.code = "ETIMEDOUT";
|
|
1544
|
-
return error;
|
|
1545
|
-
}
|
|
1546
|
-
laneTimeoutError() {
|
|
1547
|
-
return this.deadlineError("while queued");
|
|
1548
|
-
}
|
|
1549
|
-
connectionChangedError(detail) {
|
|
1550
|
-
const error = new Error(detail);
|
|
1551
|
-
error.code = "ECONNRESET";
|
|
1552
|
-
return error;
|
|
1553
|
-
}
|
|
1554
|
-
async beforeDeadline(operation, deadlineMs, detail) {
|
|
1555
|
-
operation.catch(() => {});
|
|
1556
|
-
const remainingMs = deadlineMs - Date.now();
|
|
1557
|
-
if (remainingMs <= 0)
|
|
1558
|
-
throw this.deadlineError(detail);
|
|
1559
|
-
let timer;
|
|
1560
|
-
try {
|
|
1561
|
-
return await Promise.race([
|
|
1562
|
-
operation,
|
|
1563
|
-
new Promise((_resolve, reject) => {
|
|
1564
|
-
timer = setTimeout(() => reject(this.deadlineError(detail)), remainingMs);
|
|
1565
|
-
})
|
|
1566
|
-
]);
|
|
1567
|
-
} finally {
|
|
1568
|
-
if (timer)
|
|
1569
|
-
clearTimeout(timer);
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
cleanupLane(sessionId, lane) {
|
|
1573
|
-
if (!lane.active && lane.waiters.length === 0 && this.sessionLanes.get(sessionId) === lane) {
|
|
1574
|
-
this.sessionLanes.delete(sessionId);
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
laneRelease(sessionId, lane) {
|
|
1578
|
-
let released = false;
|
|
1579
|
-
return () => {
|
|
1580
|
-
if (released)
|
|
1581
|
-
return;
|
|
1582
|
-
released = true;
|
|
1583
|
-
lane.active = false;
|
|
1584
|
-
this.dispatchNextLaneWaiter(sessionId, lane);
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
dispatchNextLaneWaiter(sessionId, lane) {
|
|
1588
|
-
if (lane.active)
|
|
1589
|
-
return;
|
|
1590
|
-
while (lane.waiters.length > 0) {
|
|
1591
|
-
const waiter = lane.waiters.shift();
|
|
1592
|
-
if (!waiter)
|
|
1593
|
-
continue;
|
|
1594
|
-
this.queuedLaneWaiters = Math.max(0, this.queuedLaneWaiters - 1);
|
|
1595
|
-
if (waiter.settled)
|
|
1596
|
-
continue;
|
|
1597
|
-
waiter.settled = true;
|
|
1598
|
-
clearTimeout(waiter.timer);
|
|
1599
|
-
waiter.signal?.removeEventListener("abort", waiter.onAbort);
|
|
1600
|
-
if (waiter.signal?.aborted) {
|
|
1601
|
-
waiter.reject(waiter.signal.reason ?? new Error("module transport call aborted"));
|
|
1602
|
-
continue;
|
|
1603
|
-
}
|
|
1604
|
-
if (waiter.deadlineMs - Date.now() < SERIAL_LANE_MIN_REMAINING_MS) {
|
|
1605
|
-
waiter.reject(this.laneTimeoutError());
|
|
1606
|
-
continue;
|
|
1607
|
-
}
|
|
1608
|
-
lane.active = true;
|
|
1609
|
-
waiter.resolve(this.laneRelease(sessionId, lane));
|
|
1610
|
-
return;
|
|
1611
|
-
}
|
|
1612
|
-
this.cleanupLane(sessionId, lane);
|
|
1613
|
-
}
|
|
1614
|
-
queueFullError() {
|
|
1615
|
-
const error = new Error("module transport queue is full");
|
|
1616
|
-
error.code = "EBUSY";
|
|
1617
|
-
return error;
|
|
1618
|
-
}
|
|
1619
|
-
acquireCorrectnessLane(sessionId, signal, deadlineMs) {
|
|
1620
|
-
if (signal?.aborted) {
|
|
1621
|
-
return Promise.reject(signal.reason ?? new Error("module transport call aborted"));
|
|
1622
|
-
}
|
|
1623
|
-
if (deadlineMs - Date.now() < SERIAL_LANE_MIN_REMAINING_MS) {
|
|
1624
|
-
return Promise.reject(this.laneTimeoutError());
|
|
1625
|
-
}
|
|
1626
|
-
const lane = this.sessionLanes.get(sessionId) ?? { active: false, waiters: [] };
|
|
1627
|
-
this.sessionLanes.set(sessionId, lane);
|
|
1628
|
-
if (!lane.active && lane.waiters.length === 0) {
|
|
1629
|
-
lane.active = true;
|
|
1630
|
-
return Promise.resolve(this.laneRelease(sessionId, lane));
|
|
1631
|
-
}
|
|
1632
|
-
if (this.queuedLaneWaiters >= SERIAL_LANE_MAX_WAITERS || lane.waiters.length >= SERIAL_LANE_MAX_WAITERS_PER_SESSION) {
|
|
1633
|
-
return Promise.reject(this.queueFullError());
|
|
1634
|
-
}
|
|
1635
|
-
return new Promise((resolve, reject) => {
|
|
1636
|
-
const waiter = {};
|
|
1637
|
-
const removeAndReject = (error) => {
|
|
1638
|
-
if (waiter.settled)
|
|
1639
|
-
return;
|
|
1640
|
-
waiter.settled = true;
|
|
1641
|
-
clearTimeout(waiter.timer);
|
|
1642
|
-
signal?.removeEventListener("abort", waiter.onAbort);
|
|
1643
|
-
const index = lane.waiters.indexOf(waiter);
|
|
1644
|
-
if (index >= 0) {
|
|
1645
|
-
lane.waiters.splice(index, 1);
|
|
1646
|
-
this.queuedLaneWaiters = Math.max(0, this.queuedLaneWaiters - 1);
|
|
1647
|
-
}
|
|
1648
|
-
reject(error);
|
|
1649
|
-
this.cleanupLane(sessionId, lane);
|
|
1650
|
-
};
|
|
1651
|
-
waiter.signal = signal;
|
|
1652
|
-
waiter.deadlineMs = deadlineMs;
|
|
1653
|
-
waiter.resolve = resolve;
|
|
1654
|
-
waiter.reject = reject;
|
|
1655
|
-
waiter.settled = false;
|
|
1656
|
-
waiter.onAbort = () => removeAndReject(signal?.reason ?? new Error("module transport call aborted"));
|
|
1657
|
-
waiter.timer = setTimeout(() => removeAndReject(this.laneTimeoutError()), Math.max(0, deadlineMs - Date.now()));
|
|
1658
|
-
signal?.addEventListener("abort", waiter.onAbort, { once: true });
|
|
1659
|
-
lane.waiters.push(waiter);
|
|
1660
|
-
this.queuedLaneWaiters += 1;
|
|
1661
|
-
});
|
|
1662
|
-
}
|
|
1663
|
-
async call(args) {
|
|
1664
|
-
const callStartedAt = performance.now();
|
|
1665
|
-
const timings = {
|
|
1666
|
-
lane: 0,
|
|
1667
|
-
route: 0,
|
|
1668
|
-
encode: 0,
|
|
1669
|
-
issue: 0,
|
|
1670
|
-
responseWait: 0,
|
|
1671
|
-
settle: 0
|
|
1672
|
-
};
|
|
1673
|
-
const wrapupInFlight = (this.wrapupSessions.get(args.sessionId) ?? 0) > 0;
|
|
1674
|
-
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);
|
|
1675
|
-
const tracksWrapup = args.method === "session.wrapup";
|
|
1676
|
-
if (tracksWrapup) {
|
|
1677
|
-
this.wrapupSessions.set(args.sessionId, (this.wrapupSessions.get(args.sessionId) ?? 0) + 1);
|
|
1678
|
-
}
|
|
1679
|
-
const finishWrapupTracking = () => {
|
|
1680
|
-
if (!tracksWrapup)
|
|
1681
|
-
return;
|
|
1682
|
-
const remaining = (this.wrapupSessions.get(args.sessionId) ?? 1) - 1;
|
|
1683
|
-
if (remaining > 0)
|
|
1684
|
-
this.wrapupSessions.set(args.sessionId, remaining);
|
|
1685
|
-
else
|
|
1686
|
-
this.wrapupSessions.delete(args.sessionId);
|
|
1687
|
-
};
|
|
1688
|
-
const laneDeadlineMs = Date.now() + attemptTimeoutMs;
|
|
1689
|
-
let releaseLane = () => {};
|
|
1690
|
-
try {
|
|
1691
|
-
const outsideSessionOrder = args.method.startsWith("historian.");
|
|
1692
|
-
if (!args.bypassSessionLane && !outsideSessionOrder) {
|
|
1693
|
-
releaseLane = await this.acquireCorrectnessLane(args.sessionId, args.signal, laneDeadlineMs);
|
|
1694
|
-
}
|
|
1695
|
-
} catch (error) {
|
|
1696
|
-
finishWrapupTracking();
|
|
1697
|
-
if (args.method === "state_sync" && isDeadlineFailure(error)) {
|
|
1698
|
-
const body = isRecord(args.body) ? args.body : {};
|
|
1699
|
-
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}`), {
|
|
1700
|
-
code: "state_sync_timeout",
|
|
1701
|
-
stage: "correctness_lane",
|
|
1702
|
-
page: body.seed_batch_index ?? 0,
|
|
1703
|
-
pages: body.seed_batch_total ?? 1,
|
|
1704
|
-
series: body.seed_id ?? null,
|
|
1705
|
-
cause: error
|
|
1706
|
-
});
|
|
1707
|
-
}
|
|
1708
|
-
throw error;
|
|
1709
|
-
}
|
|
1710
|
-
timings.lane = performance.now() - callStartedAt;
|
|
1711
|
-
let rejectAbort;
|
|
1712
|
-
const aborted = new Promise((_resolve, reject) => {
|
|
1713
|
-
rejectAbort = reject;
|
|
1714
|
-
});
|
|
1715
|
-
aborted.catch(() => {});
|
|
1716
|
-
const onAbort = () => rejectAbort(args.signal?.reason ?? new Error("module transport call aborted"));
|
|
1717
|
-
args.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1718
|
-
try {
|
|
1719
|
-
for (let attempt = 0;attempt < 2; attempt += 1) {
|
|
1720
|
-
let ensuredRoute = null;
|
|
1721
|
-
let initialResponseReceived = false;
|
|
1722
|
-
try {
|
|
1723
|
-
if (args.signal?.aborted) {
|
|
1724
|
-
throw args.signal.reason ?? new Error("module transport call aborted");
|
|
1725
|
-
}
|
|
1726
|
-
const attemptDeadlineMs = Date.now() + attemptTimeoutMs;
|
|
1727
|
-
const routeStartedAt = performance.now();
|
|
1728
|
-
ensuredRoute = await this.ensureRoute(args.sessionId, args.projectRoot, attemptDeadlineMs, args.signal);
|
|
1729
|
-
if (args.signal?.aborted) {
|
|
1730
|
-
throw args.signal.reason ?? new Error("module transport call aborted");
|
|
1731
|
-
}
|
|
1732
|
-
timings.route += performance.now() - routeStartedAt;
|
|
1733
|
-
const encodeStartedAt = performance.now();
|
|
1734
|
-
const body = args.body instanceof Uint8Array ? args.body : Buffer.from(JSON.stringify(moduleRequestBody(args.body, args.method)));
|
|
1735
|
-
timings.encode += performance.now() - encodeStartedAt;
|
|
1736
|
-
const issueStartedAt = performance.now();
|
|
1737
|
-
const request = ensuredRoute.client.request(ensuredRoute.route, body, {
|
|
1738
|
-
priority: Priority.Background,
|
|
1739
|
-
admissionClass: AdmissionClass.Normal,
|
|
1740
|
-
timeoutMs: Math.max(1, attemptDeadlineMs - Date.now())
|
|
1741
|
-
});
|
|
1742
|
-
timings.issue += performance.now() - issueStartedAt;
|
|
1743
|
-
const waitStartedAt = performance.now();
|
|
1744
|
-
const response = await this.beforeDeadline(Promise.race([request, aborted]), attemptDeadlineMs, "waiting for the module response");
|
|
1745
|
-
timings.responseWait += performance.now() - waitStartedAt;
|
|
1746
|
-
initialResponseReceived = true;
|
|
1747
|
-
if (this.client !== ensuredRoute.client || this.connectionGeneration !== ensuredRoute.generation) {
|
|
1748
|
-
throw this.connectionChangedError("subc connection changed while awaiting the module response");
|
|
1749
|
-
}
|
|
1750
|
-
const pageRoute = ensuredRoute;
|
|
1751
|
-
const assembled = await assembleReplyPages(response, async (id, index) => {
|
|
1752
|
-
if (args.signal?.aborted)
|
|
1753
|
-
throw args.signal.reason;
|
|
1754
|
-
const page = await this.beforeDeadline(Promise.race([
|
|
1755
|
-
pageRoute.client.request(pageRoute.route, Buffer.from(JSON.stringify({
|
|
1756
|
-
method: "reply.page",
|
|
1757
|
-
reply_page_id: id,
|
|
1758
|
-
reply_page_index: index
|
|
1759
|
-
})), {
|
|
1760
|
-
priority: Priority.Background,
|
|
1761
|
-
admissionClass: AdmissionClass.Normal,
|
|
1762
|
-
timeoutMs: Math.max(1, attemptDeadlineMs - Date.now())
|
|
1763
|
-
}),
|
|
1764
|
-
aborted
|
|
1765
|
-
]), attemptDeadlineMs, "waiting for a module reply page");
|
|
1766
|
-
if (this.client !== pageRoute.client || this.connectionGeneration !== pageRoute.generation) {
|
|
1767
|
-
throw this.connectionChangedError("subc connection changed during reply paging");
|
|
1768
|
-
}
|
|
1769
|
-
return page;
|
|
1770
|
-
});
|
|
1771
|
-
return assembled;
|
|
1772
|
-
} catch (error) {
|
|
1773
|
-
if (args.signal?.aborted)
|
|
1774
|
-
throw args.signal.reason ?? error;
|
|
1775
|
-
const migration = singleStoreMigrationRequiredFailure(error);
|
|
1776
|
-
if (migration)
|
|
1777
|
-
throw migration;
|
|
1778
|
-
const storeAhead = storeAheadOfBinaryFailure(error);
|
|
1779
|
-
if (storeAhead)
|
|
1780
|
-
throw storeAhead;
|
|
1781
|
-
if (args.method === "state_sync" && isDeadlineFailure(error)) {
|
|
1782
|
-
const body = isRecord(args.body) ? args.body : {};
|
|
1783
|
-
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}`), {
|
|
1784
|
-
code: "state_sync_timeout",
|
|
1785
|
-
stage: "module_ack",
|
|
1786
|
-
page: body.seed_batch_index ?? 0,
|
|
1787
|
-
pages: body.seed_batch_total ?? 1,
|
|
1788
|
-
series: body.seed_id ?? null,
|
|
1789
|
-
cause: error
|
|
1790
|
-
});
|
|
1791
|
-
}
|
|
1792
|
-
if (args.attemptClass === "transform_series_execute" && isDeadlineFailure(error)) {
|
|
1793
|
-
throw error;
|
|
1794
|
-
}
|
|
1795
|
-
if (isConnectionFailure(error)) {
|
|
1796
|
-
const previousGeneration = ensuredRoute?.generation ?? this.connectionGeneration;
|
|
1797
|
-
if (ensuredRoute) {
|
|
1798
|
-
this.dropRoute(ensuredRoute.routeKey, ensuredRoute.route);
|
|
1799
|
-
this.invalidateConnection(ensuredRoute.client);
|
|
1800
|
-
} else {
|
|
1801
|
-
this.invalidateConnection();
|
|
1802
|
-
}
|
|
1803
|
-
const locallyUnsent = isRecord(error) && error.name === "StaleRouteHandleError" && error.code === "stale_route_handle";
|
|
1804
|
-
if (attempt === 0 && ensuredRoute && !initialResponseReceived && locallyUnsent && !args.generationSensitive) {
|
|
1805
|
-
continue;
|
|
1806
|
-
}
|
|
1807
|
-
if (args.method === "transform") {
|
|
1808
|
-
if (!ensuredRoute)
|
|
1809
|
-
throw error;
|
|
1810
|
-
throw Object.assign(new Error("Transform transport interrupted; abandon this pass"), { code: "transform_transport_interrupted", cause: error });
|
|
1811
|
-
}
|
|
1812
|
-
if (args.generationSensitive && !args.signal?.aborted) {
|
|
1813
|
-
return {
|
|
1814
|
-
transport_status: "connection_generation_changed",
|
|
1815
|
-
previous_generation: previousGeneration,
|
|
1816
|
-
current_generation: this.connectionGeneration
|
|
1817
|
-
};
|
|
1818
|
-
}
|
|
1819
|
-
if (attempt === 0 && !args.signal?.aborted)
|
|
1820
|
-
continue;
|
|
1821
|
-
}
|
|
1822
|
-
throw error;
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
throw new Error("module transport route retry exhausted");
|
|
1826
|
-
} finally {
|
|
1827
|
-
args.signal?.removeEventListener("abort", onAbort);
|
|
1828
|
-
finishWrapupTracking();
|
|
1829
|
-
releaseLane();
|
|
1830
|
-
timings.settle = Math.max(0, performance.now() - callStartedAt - timings.lane - timings.route - timings.encode - timings.issue - timings.responseWait);
|
|
1831
|
-
args.onTimings?.(timings);
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
async deleteSession(sessionId, projectRoot) {
|
|
1835
|
-
await this.call({
|
|
1836
|
-
sessionId,
|
|
1837
|
-
projectRoot,
|
|
1838
|
-
method: "session.delete",
|
|
1839
|
-
body: { method: "session.delete", v: 1, session_id: sessionId }
|
|
1840
|
-
});
|
|
1841
|
-
}
|
|
1842
|
-
closeSession(sessionId) {
|
|
1843
|
-
const client = this.client;
|
|
1844
|
-
const prefix = `${sessionId}\x00`;
|
|
1845
|
-
const routes = [...this.routes.entries()].filter(([key]) => key.startsWith(prefix));
|
|
1846
|
-
for (const [key, cachedRoute] of routes) {
|
|
1847
|
-
this.routes.delete(key);
|
|
1848
|
-
if (client) {
|
|
1849
|
-
client.closeRoute(cachedRoute.route).catch((error) => {
|
|
1850
|
-
if (this.client === client && isConnectionFailure(error)) {
|
|
1851
|
-
this.invalidateConnection(client);
|
|
1852
|
-
}
|
|
1853
|
-
});
|
|
1854
|
-
}
|
|
1855
|
-
}
|
|
1856
|
-
if (routes.length === 0 && this.sessionLanes.get(sessionId)?.active) {
|
|
1857
|
-
this.invalidateConnection(client);
|
|
1858
|
-
}
|
|
1859
|
-
}
|
|
1860
|
-
async ensureRoute(sessionId, rawProjectRoot, deadlineMs = Date.now() + this.requestTimeoutMs, signal) {
|
|
1861
|
-
const projectRoot = this.canonicalRoot(rawProjectRoot);
|
|
1862
|
-
const routeKey = `${sessionId}\x00${projectRoot}`;
|
|
1863
|
-
const client = await this.ensureConnected(signal);
|
|
1864
|
-
const generation = this.connectionGeneration;
|
|
1865
|
-
const existing = this.routes.get(routeKey);
|
|
1866
|
-
if (existing?.generation === generation) {
|
|
1867
|
-
return { client, route: existing.route, routeKey, generation };
|
|
1868
|
-
}
|
|
1869
|
-
if (existing)
|
|
1870
|
-
this.routes.delete(routeKey);
|
|
1871
|
-
const opening = this.routeOpenings.get(routeKey);
|
|
1872
|
-
if (opening?.client === client && opening.generation === generation) {
|
|
1873
|
-
return await opening.promise;
|
|
1874
|
-
}
|
|
1875
|
-
const promise = (async () => {
|
|
1876
|
-
const target = { kind: "tool_provider", module_id: this.moduleId };
|
|
1877
|
-
const identity = {
|
|
1878
|
-
project_root: projectRoot,
|
|
1879
|
-
harness: getHarness2(),
|
|
1880
|
-
session: `${this.routeSessionPrefix}${sessionId}`
|
|
1881
|
-
};
|
|
1882
|
-
const route = await this.beforeDeadline(routeOpenWithoutAmbientConsumerIdentity(client, target, identity), deadlineMs, "opening the module route");
|
|
1883
|
-
if (this.client !== client || generation !== this.connectionGeneration) {
|
|
1884
|
-
await client.closeRoute(route).catch(() => {
|
|
1885
|
-
return;
|
|
1886
|
-
});
|
|
1887
|
-
throw this.connectionChangedError("subc connection changed while opening module route");
|
|
1888
|
-
}
|
|
1889
|
-
this.routes.set(routeKey, { route, generation });
|
|
1890
|
-
return { client, route, routeKey, generation };
|
|
1891
|
-
})();
|
|
1892
|
-
const routeOpening = { client, generation, promise };
|
|
1893
|
-
this.routeOpenings.set(routeKey, routeOpening);
|
|
1894
|
-
try {
|
|
1895
|
-
return await promise;
|
|
1896
|
-
} finally {
|
|
1897
|
-
if (this.routeOpenings.get(routeKey) === routeOpening) {
|
|
1898
|
-
this.routeOpenings.delete(routeKey);
|
|
1899
|
-
}
|
|
1900
|
-
}
|
|
1901
|
-
}
|
|
1902
|
-
dropRoute(routeKey, route) {
|
|
1903
|
-
const existing = this.routes.get(routeKey);
|
|
1904
|
-
if (!existing || route && existing.route !== route)
|
|
1905
|
-
return;
|
|
1906
|
-
this.routes.delete(routeKey);
|
|
1907
|
-
}
|
|
1908
|
-
canonicalRoot(root) {
|
|
1909
|
-
const cached = this.canonicalRootCache.get(root);
|
|
1910
|
-
if (cached !== undefined) {
|
|
1911
|
-
this.canonicalRootCache.delete(root);
|
|
1912
|
-
this.canonicalRootCache.set(root, cached);
|
|
1913
|
-
return cached;
|
|
1914
|
-
}
|
|
1915
|
-
let resolved = root;
|
|
1916
|
-
try {
|
|
1917
|
-
resolved = realpathSync.native(root);
|
|
1918
|
-
} catch {}
|
|
1919
|
-
this.canonicalRootCache.set(root, resolved);
|
|
1920
|
-
while (this.canonicalRootCache.size > CANONICAL_ROOT_CACHE_MAX_ENTRIES) {
|
|
1921
|
-
const oldestRoot = this.canonicalRootCache.keys().next().value;
|
|
1922
|
-
if (oldestRoot === undefined)
|
|
1923
|
-
break;
|
|
1924
|
-
this.canonicalRootCache.delete(oldestRoot);
|
|
1925
|
-
}
|
|
1926
|
-
return resolved;
|
|
1927
|
-
}
|
|
1928
|
-
connectClient() {
|
|
1929
|
-
return SubcClient.connect({
|
|
1930
|
-
connectionFile: this.connectionFile,
|
|
1931
|
-
handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS
|
|
1932
|
-
});
|
|
1933
|
-
}
|
|
1934
|
-
backoffActiveError() {
|
|
1935
|
-
const error = new Error(`subc connection backoff active until ${this.nextProbeMs}`);
|
|
1936
|
-
error.code = "SUBC_CONNECTION_BACKOFF";
|
|
1937
|
-
return error;
|
|
1938
|
-
}
|
|
1939
|
-
sleepAbortable(durationMs, signal) {
|
|
1940
|
-
return new Promise((resolve, reject) => {
|
|
1941
|
-
if (signal?.aborted) {
|
|
1942
|
-
reject(signal.reason ?? new Error("module transport call aborted"));
|
|
1943
|
-
return;
|
|
1944
|
-
}
|
|
1945
|
-
const onAbort = () => {
|
|
1946
|
-
clearTimeout(timer);
|
|
1947
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1948
|
-
reject(signal?.reason ?? new Error("module transport call aborted"));
|
|
1949
|
-
};
|
|
1950
|
-
const timer = setTimeout(() => {
|
|
1951
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1952
|
-
resolve();
|
|
1953
|
-
}, Math.max(0, durationMs));
|
|
1954
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1955
|
-
});
|
|
1956
|
-
}
|
|
1957
|
-
async ensureConnected(signal) {
|
|
1958
|
-
if (this.client)
|
|
1959
|
-
return this.client;
|
|
1960
|
-
if (this.connectionPromise)
|
|
1961
|
-
return await this.connectionPromise;
|
|
1962
|
-
let now = Date.now();
|
|
1963
|
-
if (now < this.nextProbeMs) {
|
|
1964
|
-
const remainingMs = this.nextProbeMs - now;
|
|
1965
|
-
if (remainingMs > CONNECT_BACKOFF_WAIT_BUDGET_MS)
|
|
1966
|
-
throw this.backoffActiveError();
|
|
1967
|
-
const jitterMs = Math.floor(Math.random() * CONNECT_BACKOFF_WAIT_JITTER_MS);
|
|
1968
|
-
await this.sleepAbortable(remainingMs + jitterMs, signal);
|
|
1969
|
-
if (this.client)
|
|
1970
|
-
return this.client;
|
|
1971
|
-
if (this.connectionPromise)
|
|
1972
|
-
return await this.connectionPromise;
|
|
1973
|
-
now = Date.now();
|
|
1974
|
-
if (now < this.nextProbeMs)
|
|
1975
|
-
throw this.backoffActiveError();
|
|
1976
|
-
}
|
|
1977
|
-
const generation = this.connectionGeneration;
|
|
1978
|
-
const connecting = (async () => {
|
|
1979
|
-
let candidate = null;
|
|
1980
|
-
try {
|
|
1981
|
-
candidate = await this.connectClient();
|
|
1982
|
-
if (generation !== this.connectionGeneration) {
|
|
1983
|
-
candidate.close();
|
|
1984
|
-
throw this.connectionChangedError("subc connection attempt was superseded");
|
|
1985
|
-
}
|
|
1986
|
-
this.client = candidate;
|
|
1987
|
-
this.routes.clear();
|
|
1988
|
-
this.backoffMs = CONNECT_BACKOFF_INITIAL_MS;
|
|
1989
|
-
this.nextProbeMs = 0;
|
|
1990
|
-
return candidate;
|
|
1991
|
-
} catch (error) {
|
|
1992
|
-
candidate?.close();
|
|
1993
|
-
if (generation === this.connectionGeneration)
|
|
1994
|
-
this.invalidateConnection();
|
|
1995
|
-
this.nextProbeMs = Date.now() + this.backoffMs;
|
|
1996
|
-
this.backoffMs = Math.min(this.backoffMs * 2, CONNECT_BACKOFF_MAX_MS);
|
|
1997
|
-
throw error;
|
|
1998
|
-
}
|
|
1999
|
-
})();
|
|
2000
|
-
this.connectionPromise = connecting;
|
|
2001
|
-
try {
|
|
2002
|
-
return await connecting;
|
|
2003
|
-
} finally {
|
|
2004
|
-
if (this.connectionPromise === connecting)
|
|
2005
|
-
this.connectionPromise = null;
|
|
2006
|
-
}
|
|
2007
|
-
}
|
|
2008
|
-
invalidateConnection(client = this.client) {
|
|
2009
|
-
if (client && this.client !== client)
|
|
2010
|
-
return;
|
|
2011
|
-
this.connectionGeneration += 1;
|
|
2012
|
-
this.invalidateStateSyncCapabilities();
|
|
2013
|
-
this.client = null;
|
|
2014
|
-
this.routes.clear();
|
|
2015
|
-
this.routeOpenings.clear();
|
|
2016
|
-
client?.close();
|
|
2017
|
-
}
|
|
2018
|
-
}
|
|
2019
|
-
|
|
2020
1273
|
// src/plugin/dream-timer.ts
|
|
2021
1274
|
import { statSync as statSync2 } from "node:fs";
|
|
2022
1275
|
|
|
@@ -2939,11 +2192,11 @@ function recordRetrospectiveWindowProcessed(db, projectPath, windowKey) {
|
|
|
2939
2192
|
}
|
|
2940
2193
|
|
|
2941
2194
|
// src/features/magic-context/dreamer/task-executor.ts
|
|
2942
|
-
import { createHash as
|
|
2195
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
2943
2196
|
import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
|
|
2944
2197
|
|
|
2945
2198
|
// src/features/magic-context/mural/compress-cues.ts
|
|
2946
|
-
import { createHash
|
|
2199
|
+
import { createHash } from "node:crypto";
|
|
2947
2200
|
|
|
2948
2201
|
// src/features/magic-context/dreamer/manifest-parser.ts
|
|
2949
2202
|
function extractCompleteManifestBody(text, rootName) {
|
|
@@ -3409,7 +2662,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
|
|
|
3409
2662
|
log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
|
|
3410
2663
|
}
|
|
3411
2664
|
}
|
|
3412
|
-
const commandId = `mural-cues:${route.moduleCommandId}:${
|
|
2665
|
+
const commandId = `mural-cues:${route.moduleCommandId}:${createHash("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
3413
2666
|
let response;
|
|
3414
2667
|
try {
|
|
3415
2668
|
response = await route.moduleClient.call({
|
|
@@ -3779,7 +3032,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
|
|
|
3779
3032
|
}
|
|
3780
3033
|
|
|
3781
3034
|
// src/features/magic-context/dreamer/classify.ts
|
|
3782
|
-
import { createHash as
|
|
3035
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
3783
3036
|
|
|
3784
3037
|
// src/plugin/rust-tool-backends.ts
|
|
3785
3038
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -4216,7 +3469,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
|
|
|
4216
3469
|
if (entry.qualifier)
|
|
4217
3470
|
modelVariants[entry.model] = entry.qualifier;
|
|
4218
3471
|
}
|
|
4219
|
-
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
3472
|
+
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash2("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
4220
3473
|
const runTask = (hostCompletion) => args.moduleClient?.call({
|
|
4221
3474
|
sessionId: args.moduleSessionId,
|
|
4222
3475
|
projectRoot: args.moduleProjectRoot,
|
|
@@ -4583,32 +3836,32 @@ function takeCurateSafetyRefusalCount(sessionId) {
|
|
|
4583
3836
|
|
|
4584
3837
|
// src/features/magic-context/dreamer/docs-proposals.ts
|
|
4585
3838
|
import { execFileSync } from "node:child_process";
|
|
4586
|
-
import { createHash as
|
|
3839
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4587
3840
|
import {
|
|
4588
3841
|
existsSync as existsSync2,
|
|
4589
3842
|
mkdirSync,
|
|
4590
3843
|
mkdtempSync,
|
|
4591
3844
|
readdirSync,
|
|
4592
3845
|
readFileSync,
|
|
4593
|
-
realpathSync
|
|
3846
|
+
realpathSync,
|
|
4594
3847
|
renameSync,
|
|
4595
3848
|
rmSync,
|
|
4596
3849
|
writeFileSync
|
|
4597
3850
|
} from "node:fs";
|
|
4598
3851
|
import { tmpdir } from "node:os";
|
|
4599
|
-
import { join
|
|
3852
|
+
import { join } from "node:path";
|
|
4600
3853
|
var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
4601
|
-
var hash = (text) =>
|
|
4602
|
-
var proposalDir = (projectDir) =>
|
|
3854
|
+
var hash = (text) => createHash3("sha256").update(text).digest("hex");
|
|
3855
|
+
var proposalDir = (projectDir) => join(projectDir, ".cortexkit/magic-context/docs-update-proposals");
|
|
4603
3856
|
function docsBaseHashes(projectDir) {
|
|
4604
3857
|
return Object.fromEntries(FILES.map((name) => [
|
|
4605
3858
|
name,
|
|
4606
|
-
hash(existsSync2(
|
|
3859
|
+
hash(existsSync2(join(projectDir, name)) ? readFileSync(join(projectDir, name), "utf8") : "")
|
|
4607
3860
|
]));
|
|
4608
3861
|
}
|
|
4609
3862
|
function listPendingDocsProposals(projectDir) {
|
|
4610
3863
|
const dir = proposalDir(projectDir);
|
|
4611
|
-
return existsSync2(dir) ? readdirSync(dir).filter((name) => name.endsWith(".md")).sort().map((name) =>
|
|
3864
|
+
return existsSync2(dir) ? readdirSync(dir).filter((name) => name.endsWith(".md")).sort().map((name) => join(dir, name)) : [];
|
|
4612
3865
|
}
|
|
4613
3866
|
function hasCurrentDocsProposal(projectDir) {
|
|
4614
3867
|
const hashes = docsBaseHashes(projectDir);
|
|
@@ -4640,7 +3893,7 @@ function gitOutputPrefix(projectDir, args) {
|
|
|
4640
3893
|
var MAX_PATHSPEC_BYTES = 256000;
|
|
4641
3894
|
function docsChangeSet(projectDir, storedAnchor) {
|
|
4642
3895
|
try {
|
|
4643
|
-
if (
|
|
3896
|
+
if (realpathSync(git(projectDir, ["rev-parse", "--show-toplevel"])) !== realpathSync(projectDir))
|
|
4644
3897
|
return null;
|
|
4645
3898
|
const head = git(projectDir, ["rev-parse", "HEAD"]);
|
|
4646
3899
|
const recorded = Boolean(storedAnchor);
|
|
@@ -4666,7 +3919,7 @@ function docsChangeSet(projectDir, storedAnchor) {
|
|
|
4666
3919
|
const files = [
|
|
4667
3920
|
...new Set(changed.flat().filter((file) => file !== "ARCHITECTURE.md" && file !== "STRUCTURE.md" && !/(?:^|[./-])(test|spec)(?:[./-]|$)/.test(file) && !file.endsWith(".lock")))
|
|
4668
3921
|
];
|
|
4669
|
-
const docs = FILES.map((file) => existsSync2(
|
|
3922
|
+
const docs = FILES.map((file) => existsSync2(join(projectDir, file)) ? readFileSync(join(projectDir, file), "utf8") : "").join(`
|
|
4670
3923
|
`);
|
|
4671
3924
|
const relevant = files.some((file) => {
|
|
4672
3925
|
const directory = file.split("/").slice(0, -1).join("/");
|
|
@@ -4794,14 +4047,14 @@ function protectedBytes(text) {
|
|
|
4794
4047
|
].map((match) => match[0]);
|
|
4795
4048
|
}
|
|
4796
4049
|
function diff(name, before, after) {
|
|
4797
|
-
const dir = mkdtempSync(
|
|
4050
|
+
const dir = mkdtempSync(join(tmpdir(), "mc-doc-diff-"));
|
|
4798
4051
|
try {
|
|
4799
|
-
writeFileSync(
|
|
4800
|
-
writeFileSync(
|
|
4052
|
+
writeFileSync(join(dir, "before"), before);
|
|
4053
|
+
writeFileSync(join(dir, "after"), after);
|
|
4801
4054
|
try {
|
|
4802
|
-
return execFileSync("git", ["diff", "--no-index", "--",
|
|
4055
|
+
return execFileSync("git", ["diff", "--no-index", "--", join(dir, "before"), join(dir, "after")], { windowsHide: true, encoding: "utf8" });
|
|
4803
4056
|
} catch (error) {
|
|
4804
|
-
return error.stdout?.replaceAll(
|
|
4057
|
+
return error.stdout?.replaceAll(join(dir, "before"), `a/${name}`).replaceAll(join(dir, "after"), `b/${name}`) ?? "";
|
|
4805
4058
|
}
|
|
4806
4059
|
} finally {
|
|
4807
4060
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -4822,7 +4075,7 @@ function validateDocsProposal(projectDir, output, budget, expected) {
|
|
|
4822
4075
|
let tokens = 0;
|
|
4823
4076
|
let diffs = "";
|
|
4824
4077
|
for (const file of FILES) {
|
|
4825
|
-
const before = existsSync2(
|
|
4078
|
+
const before = existsSync2(join(projectDir, file)) ? readFileSync(join(projectDir, file), "utf8") : "";
|
|
4826
4079
|
let after = before;
|
|
4827
4080
|
const seen = new Set;
|
|
4828
4081
|
for (const change of changes.filter((item) => item.file === file)) {
|
|
@@ -4872,9 +4125,9 @@ ${change.text.trimEnd()}
|
|
|
4872
4125
|
function writeDocsProposal(projectDir, output, budget, expected, head) {
|
|
4873
4126
|
const result = validateDocsProposal(projectDir, output, budget, expected);
|
|
4874
4127
|
const dir = proposalDir(projectDir);
|
|
4875
|
-
mkdirSync(
|
|
4128
|
+
mkdirSync(join(dir, "superseded"), { recursive: true });
|
|
4876
4129
|
const stamp = `${new Date().toISOString().replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2, 8)}`;
|
|
4877
|
-
const path =
|
|
4130
|
+
const path = join(dir, `${stamp}.md`);
|
|
4878
4131
|
const body = `# Docs update proposal
|
|
4879
4132
|
|
|
4880
4133
|
Base commit: ${head}
|
|
@@ -4902,7 +4155,7 @@ ${result.diffs}
|
|
|
4902
4155
|
writeFileSync(path, body, { flag: "wx" });
|
|
4903
4156
|
for (const old of listPendingDocsProposals(projectDir))
|
|
4904
4157
|
if (old !== path)
|
|
4905
|
-
renameSync(old,
|
|
4158
|
+
renameSync(old, join(dir, "superseded", old.split("/").at(-1) ?? "proposal.md"));
|
|
4906
4159
|
return path;
|
|
4907
4160
|
}
|
|
4908
4161
|
|
|
@@ -5655,7 +4908,7 @@ function throwIfAborted2(signal) {
|
|
|
5655
4908
|
}
|
|
5656
4909
|
|
|
5657
4910
|
// src/features/magic-context/smart-notes/compiler.ts
|
|
5658
|
-
import { createHash as
|
|
4911
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
5659
4912
|
|
|
5660
4913
|
// src/features/magic-context/smart-notes/sandbox-runner.ts
|
|
5661
4914
|
var asyncModulePromise = null;
|
|
@@ -6386,7 +5639,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
6386
5639
|
return warnings;
|
|
6387
5640
|
}
|
|
6388
5641
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
6389
|
-
return
|
|
5642
|
+
return createHash4("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
6390
5643
|
}
|
|
6391
5644
|
function extractJsonObject(output) {
|
|
6392
5645
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -6646,7 +5899,7 @@ function backoffMs(failureCount) {
|
|
|
6646
5899
|
}
|
|
6647
5900
|
|
|
6648
5901
|
// src/features/magic-context/smart-notes/wake-plane.ts
|
|
6649
|
-
import { join as
|
|
5902
|
+
import { join as join2 } from "node:path";
|
|
6650
5903
|
var WAKE_PLANE_CAPABILITY = "wake.create";
|
|
6651
5904
|
var WAKE_PLANE_STATUS_TTL_MS = 5 * 60 * 1000;
|
|
6652
5905
|
var WAKE_PLANE_HANDSHAKE_TIMEOUT_MS = 2000;
|
|
@@ -6655,7 +5908,7 @@ var inFlightProbe = null;
|
|
|
6655
5908
|
var catalogProbe = probeWakePlaneCatalog;
|
|
6656
5909
|
var now = () => Date.now();
|
|
6657
5910
|
function connectionFile() {
|
|
6658
|
-
return
|
|
5911
|
+
return join2(getDataDir(), "cortexkit", "run", "subc-connection.json");
|
|
6659
5912
|
}
|
|
6660
5913
|
async function probeWakePlaneCatalog() {
|
|
6661
5914
|
const file = connectionFile();
|
|
@@ -7318,12 +6571,12 @@ async function archiveExpiredMemories(args) {
|
|
|
7318
6571
|
|
|
7319
6572
|
// src/features/magic-context/dreamer/maintain-docs-protected-enforcement.ts
|
|
7320
6573
|
import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
7321
|
-
import { join as
|
|
6574
|
+
import { join as join3 } from "node:path";
|
|
7322
6575
|
var MAINTAIN_DOCS_SNAPSHOT_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
7323
6576
|
function snapshotMaintainDocsFiles(docsDir) {
|
|
7324
6577
|
const snapshot = new Map;
|
|
7325
6578
|
for (const name of MAINTAIN_DOCS_SNAPSHOT_FILES) {
|
|
7326
|
-
const path =
|
|
6579
|
+
const path = join3(docsDir, name);
|
|
7327
6580
|
try {
|
|
7328
6581
|
if (existsSync3(path)) {
|
|
7329
6582
|
snapshot.set(name, readFileSync2(path, "utf8"));
|
|
@@ -7334,7 +6587,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
7334
6587
|
}
|
|
7335
6588
|
|
|
7336
6589
|
// src/features/magic-context/dreamer/map-memories.ts
|
|
7337
|
-
import { createHash as
|
|
6590
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
7338
6591
|
|
|
7339
6592
|
// src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
7340
6593
|
import { existsSync as existsSync4, statSync } from "node:fs";
|
|
@@ -7807,7 +7060,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
|
|
|
7807
7060
|
name: "memory.set_mapping",
|
|
7808
7061
|
arguments: {
|
|
7809
7062
|
memory_project: args.projectIdentity,
|
|
7810
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
7063
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash5("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
7811
7064
|
rows
|
|
7812
7065
|
}
|
|
7813
7066
|
}
|
|
@@ -8918,7 +8171,7 @@ function evaluateTaskGate(task, ctx) {
|
|
|
8918
8171
|
}
|
|
8919
8172
|
|
|
8920
8173
|
// src/features/magic-context/dreamer/verify.ts
|
|
8921
|
-
import { createHash as
|
|
8174
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
8922
8175
|
|
|
8923
8176
|
// src/features/magic-context/dreamer/verify-diff.ts
|
|
8924
8177
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -9662,7 +8915,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
|
|
|
9662
8915
|
name: "memory.set_verification",
|
|
9663
8916
|
arguments: {
|
|
9664
8917
|
memory_project: args.projectIdentity,
|
|
9665
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
8918
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash6("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
9666
8919
|
rows
|
|
9667
8920
|
}
|
|
9668
8921
|
}
|
|
@@ -10468,7 +9721,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
10468
9721
|
}
|
|
10469
9722
|
function computeRetrospectiveWindowKey(flagged) {
|
|
10470
9723
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
10471
|
-
return
|
|
9724
|
+
return createHash7("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
10472
9725
|
}
|
|
10473
9726
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
10474
9727
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -11547,7 +10800,7 @@ function clearDreamerTickFailure(db) {
|
|
|
11547
10800
|
}
|
|
11548
10801
|
|
|
11549
10802
|
// src/hooks/magic-context/lkg-persist.ts
|
|
11550
|
-
import { createHash as
|
|
10803
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
11551
10804
|
function parseStringArray(value) {
|
|
11552
10805
|
if (typeof value !== "string")
|
|
11553
10806
|
return null;
|
|
@@ -11661,7 +10914,7 @@ function rememberFingerprint(db, sessionId, fingerprint) {
|
|
|
11661
10914
|
saved.set(sessionId, fingerprint);
|
|
11662
10915
|
}
|
|
11663
10916
|
function slotFingerprint(slot) {
|
|
11664
|
-
return
|
|
10917
|
+
return createHash8("sha256").update(JSON.stringify([
|
|
11665
10918
|
slot.jsonPrefix,
|
|
11666
10919
|
slot.inputIdSeq,
|
|
11667
10920
|
slot.inputContentDigests,
|
|
@@ -12275,7 +11528,7 @@ async function sweepGitCommits(args) {
|
|
|
12275
11528
|
import { readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
|
|
12276
11529
|
|
|
12277
11530
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
12278
|
-
import { createHash as
|
|
11531
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
12279
11532
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
12280
11533
|
"embedding.api_key",
|
|
12281
11534
|
"embedding.endpoint",
|
|
@@ -12323,7 +11576,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
12323
11576
|
];
|
|
12324
11577
|
var loggedFailureSignatures = new Map;
|
|
12325
11578
|
function sha256Prefix(value, length = 16) {
|
|
12326
|
-
return
|
|
11579
|
+
return createHash9("sha256").update(value).digest("hex").slice(0, length);
|
|
12327
11580
|
}
|
|
12328
11581
|
function warningLooksEmbeddingRelated(message) {
|
|
12329
11582
|
const lower = message.toLowerCase();
|
|
@@ -13040,7 +12293,7 @@ function describeStorageUnavailability(fallbackCause) {
|
|
|
13040
12293
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
13041
12294
|
import { once } from "node:events";
|
|
13042
12295
|
import { rmSync as rmSync2 } from "node:fs";
|
|
13043
|
-
import { join as
|
|
12296
|
+
import { join as join5 } from "node:path";
|
|
13044
12297
|
|
|
13045
12298
|
// src/features/magic-context/memory/memory-diagnostics.ts
|
|
13046
12299
|
function emptyMemoryImportanceHistogram() {
|
|
@@ -15184,8 +14437,12 @@ Starting wrapup…`, {});
|
|
|
15184
14437
|
v: 1,
|
|
15185
14438
|
session_id: sessionId,
|
|
15186
14439
|
keep,
|
|
15187
|
-
command_id: rustCommandId("wrapup")
|
|
14440
|
+
command_id: rustCommandId("wrapup"),
|
|
14441
|
+
...deps.resolveRustWrapupHistorianFields?.()
|
|
15188
14442
|
}, MAX_WRAPUP_REQUEST_BUDGET_MS);
|
|
14443
|
+
if (value.disposition !== "completed" && value.disposition !== "nothing_to_compact") {
|
|
14444
|
+
sessionLog2(sessionId, `ctx-wrapup not completed disposition=${String(value.disposition)} reason=${String(value.reason ?? "none")} summary=${JSON.stringify(value.summary ?? "")}`);
|
|
14445
|
+
}
|
|
15189
14446
|
result = formatRustOperationMessage("wrapup", value);
|
|
15190
14447
|
} catch (error) {
|
|
15191
14448
|
sessionLog2(sessionId, `ctx-wrapup failed code=${capabilityRefusalCode("history_compression")}`, error);
|
|
@@ -15716,7 +14973,7 @@ function activeHostLimitations() {
|
|
|
15716
14973
|
|
|
15717
14974
|
// src/shared/plugin-package-version.ts
|
|
15718
14975
|
import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
|
|
15719
|
-
import { dirname, join as
|
|
14976
|
+
import { dirname, join as join4 } from "node:path";
|
|
15720
14977
|
import { fileURLToPath } from "node:url";
|
|
15721
14978
|
var PACKAGE_NAME = "@cortexkit/opencode-magic-context";
|
|
15722
14979
|
var cachedVersion;
|
|
@@ -15728,7 +14985,7 @@ function pluginPackageVersion(moduleUrl = import.meta.url) {
|
|
|
15728
14985
|
try {
|
|
15729
14986
|
let directory = dirname(fileURLToPath(moduleUrl));
|
|
15730
14987
|
for (let depth = 0;depth < 10; depth++) {
|
|
15731
|
-
const candidate =
|
|
14988
|
+
const candidate = join4(directory, "package.json");
|
|
15732
14989
|
if (existsSync6(candidate)) {
|
|
15733
14990
|
const parsed = JSON.parse(readFileSync5(candidate, "utf8"));
|
|
15734
14991
|
if (typeof parsed === "object" && parsed !== null && "name" in parsed && parsed.name === PACKAGE_NAME && "version" in parsed && typeof parsed.version === "string") {
|
|
@@ -16475,11 +15732,11 @@ async function generateDebugHeapSnapshot(storageDir, memory) {
|
|
|
16475
15732
|
if (rssBytes > maxRssBytes) {
|
|
16476
15733
|
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`);
|
|
16477
15734
|
}
|
|
16478
|
-
const directory =
|
|
15735
|
+
const directory = join5(storageDir, "heap-snapshots");
|
|
16479
15736
|
const enforcePrivatePermissions = shouldEnforcePrivateStoragePermissions();
|
|
16480
15737
|
ensureStorageDirectorySync(directory);
|
|
16481
15738
|
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
16482
|
-
const path =
|
|
15739
|
+
const path = join5(directory, `${timestamp}-${process.pid}.heapsnapshot`);
|
|
16483
15740
|
let format = "jsc";
|
|
16484
15741
|
let snapshotVersion;
|
|
16485
15742
|
let snapshot;
|
|
@@ -16629,7 +15886,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16629
15886
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
16630
15887
|
});
|
|
16631
15888
|
const buildManagedCtx = async (db) => {
|
|
16632
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
15889
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-qz5rrr08.js"));
|
|
16633
15890
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-nx97z3x7.js"));
|
|
16634
15891
|
const { userMemoryCollectionEnabled } = await importPluginModule(() => import("./task-config-cgpg0nvh.js"));
|
|
16635
15892
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -16665,8 +15922,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16665
15922
|
const db = readDatabase();
|
|
16666
15923
|
if (!db)
|
|
16667
15924
|
return { ok: false, error: "db unavailable" };
|
|
16668
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
16669
|
-
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-
|
|
15925
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-4f1yyd1q.js"));
|
|
15926
|
+
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-38cd5dqt.js"));
|
|
16670
15927
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
16671
15928
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
16672
15929
|
return {
|
|
@@ -16735,7 +15992,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16735
15992
|
const db = readDatabase();
|
|
16736
15993
|
if (!db)
|
|
16737
15994
|
return { ok: false, error: "db unavailable" };
|
|
16738
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
15995
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-barbc6h9.js"));
|
|
16739
15996
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
16740
15997
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
16741
15998
|
const ctx = {
|
|
@@ -16884,7 +16141,8 @@ function writeRustTransformDecision(args) {
|
|
|
16884
16141
|
droppedTokens: 0,
|
|
16885
16142
|
droppedCount: 0,
|
|
16886
16143
|
inputTokens: args.inputTokens,
|
|
16887
|
-
bustedThisPass: mapped.bustedThisPass
|
|
16144
|
+
bustedThisPass: mapped.bustedThisPass,
|
|
16145
|
+
lkgFrozenReleaseReason: args.lkgFrozenReleaseReason
|
|
16888
16146
|
});
|
|
16889
16147
|
}
|
|
16890
16148
|
function clearOpenCodePendingTransformDecision(sessionId) {
|
|
@@ -16979,13 +16237,14 @@ function writeTransformDecisionRowOnDatabase(db, row, configureBusyTimeout) {
|
|
|
16979
16237
|
const m0ModelKeyNew = row.materialized ? row.m0ModelKeyNew : null;
|
|
16980
16238
|
const m0ToolSetHashPrev = row.m0ToolSetHashPrev ?? null;
|
|
16981
16239
|
const m0ToolSetHashNew = row.m0ToolSetHashNew ?? null;
|
|
16240
|
+
const persistedMaterializeReason = row.lkgFrozenReleaseReason ? `lkg_frozen_release:${row.lkgFrozenReleaseReason}` + (row.materializeReason ? `;materialize_reason=${row.materializeReason}` : "") : row.materializeReason;
|
|
16982
16241
|
db.prepare(`INSERT OR REPLACE INTO transform_decisions (
|
|
16983
16242
|
session_id, harness, message_id, ts_ms, decision, materialized,
|
|
16984
16243
|
materialize_reason, system_hash_prev, system_hash_new,
|
|
16985
16244
|
m0_tool_set_hash_prev, m0_tool_set_hash_new,
|
|
16986
16245
|
m0_model_key_prev, m0_model_key_new, emergency, dropped_tokens,
|
|
16987
16246
|
dropped_count, input_tokens
|
|
16988
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.sessionId, row.harness, row.messageId, row.tsMs, row.decision, row.materialized ? 1 : 0,
|
|
16247
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.sessionId, row.harness, row.messageId, row.tsMs, row.decision, row.materialized ? 1 : 0, persistedMaterializeReason, systemHashPrev, systemHashNew, m0ToolSetHashPrev, m0ToolSetHashNew, m0ModelKeyPrev, m0ModelKeyNew, row.emergency ? 1 : 0, Math.max(0, Math.floor(row.droppedTokens)), Math.max(0, Math.floor(row.droppedCount)), Math.max(0, Math.floor(row.inputTokens)));
|
|
16989
16248
|
db.prepare(`DELETE FROM transform_decisions
|
|
16990
16249
|
WHERE session_id = ? AND harness = ?
|
|
16991
16250
|
AND rowid NOT IN (
|
|
@@ -17224,6 +16483,13 @@ function prepareLatestThinkingRecovery(args) {
|
|
|
17224
16483
|
}
|
|
17225
16484
|
return { restore: true, ended: false };
|
|
17226
16485
|
}
|
|
16486
|
+
function endLatestThinkingRecoveryAfterReset(db, sessionId) {
|
|
16487
|
+
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
16488
|
+
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
16489
|
+
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, target);
|
|
16490
|
+
}
|
|
16491
|
+
knownRejectedSessions.delete(sessionId);
|
|
16492
|
+
}
|
|
17227
16493
|
function captureOriginalTurn(messages, parts, setParts) {
|
|
17228
16494
|
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
17229
16495
|
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
@@ -18061,6 +17327,7 @@ var PASS_DEGRADATION_EFFECTS = {
|
|
|
18061
17327
|
"auto-search-timeout": "served",
|
|
18062
17328
|
"auto-search-search-failure": "served",
|
|
18063
17329
|
"auto-search-cas-exhaustion": "served",
|
|
17330
|
+
"auto-search-storage-busy": "served",
|
|
18064
17331
|
"auto-search-internal-failure": "served",
|
|
18065
17332
|
"thinking-binding-recovery-persistence-failure": "changes-request",
|
|
18066
17333
|
"merged-reasoning-strip-persistence-failure": "changes-request",
|
|
@@ -18100,7 +17367,7 @@ function createPassOutcome() {
|
|
|
18100
17367
|
}
|
|
18101
17368
|
|
|
18102
17369
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
18103
|
-
import { createHash as
|
|
17370
|
+
import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
|
|
18104
17371
|
|
|
18105
17372
|
// src/features/magic-context/memory/single-store-embedding-drain.ts
|
|
18106
17373
|
function isWatermarkRow(row) {
|
|
@@ -18164,7 +17431,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
|
18164
17431
|
}
|
|
18165
17432
|
|
|
18166
17433
|
// src/features/magic-context/mural/source-revision.ts
|
|
18167
|
-
import { createHash as
|
|
17434
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
18168
17435
|
var statements = new WeakMap;
|
|
18169
17436
|
function muralSourceRevision(db, projectPath) {
|
|
18170
17437
|
let statement = statements.get(db);
|
|
@@ -18181,7 +17448,7 @@ function muralSourceRevision(db, projectPath) {
|
|
|
18181
17448
|
statements.set(db, statement);
|
|
18182
17449
|
}
|
|
18183
17450
|
const row = statement.get(projectPath, Date.now());
|
|
18184
|
-
return
|
|
17451
|
+
return createHash10("sha256").update(row.revision).digest("hex");
|
|
18185
17452
|
}
|
|
18186
17453
|
|
|
18187
17454
|
// src/features/magic-context/install-instance-id.ts
|
|
@@ -18204,11 +17471,11 @@ function ensureInstallInstanceId(db) {
|
|
|
18204
17471
|
var CLAIM_START_MARGIN_MS = 5000;
|
|
18205
17472
|
var IDLE_INTERVAL_MS = 30000;
|
|
18206
17473
|
var IDLE_POLLS_AFTER_PASS = 3;
|
|
18207
|
-
function
|
|
17474
|
+
function isRecord2(value) {
|
|
18208
17475
|
return typeof value === "object" && value !== null;
|
|
18209
17476
|
}
|
|
18210
17477
|
function refusalOf(response) {
|
|
18211
|
-
if (!
|
|
17478
|
+
if (!isRecord2(response))
|
|
18212
17479
|
return "malformed_response";
|
|
18213
17480
|
if (response.ok === true)
|
|
18214
17481
|
return null;
|
|
@@ -18216,11 +17483,11 @@ function refusalOf(response) {
|
|
|
18216
17483
|
return typeof refusal === "string" && refusal.length > 0 ? refusal : "malformed_response";
|
|
18217
17484
|
}
|
|
18218
17485
|
function readPendingRuns(response) {
|
|
18219
|
-
if (!
|
|
17486
|
+
if (!isRecord2(response) || !Array.isArray(response.runs))
|
|
18220
17487
|
return [];
|
|
18221
17488
|
const runs = [];
|
|
18222
17489
|
for (const entry of response.runs) {
|
|
18223
|
-
if (!
|
|
17490
|
+
if (!isRecord2(entry))
|
|
18224
17491
|
continue;
|
|
18225
17492
|
const runId = entry.run_id;
|
|
18226
17493
|
const sessionId = entry.session_id;
|
|
@@ -18237,9 +17504,9 @@ function readPendingRuns(response) {
|
|
|
18237
17504
|
return runs;
|
|
18238
17505
|
}
|
|
18239
17506
|
function readClaim(response) {
|
|
18240
|
-
if (!
|
|
17507
|
+
if (!isRecord2(response) || response.ok !== true)
|
|
18241
17508
|
return null;
|
|
18242
|
-
const prompt =
|
|
17509
|
+
const prompt = isRecord2(response.prompt) ? response.prompt : {};
|
|
18243
17510
|
const runId = response.run_id;
|
|
18244
17511
|
const sessionId = response.session_id;
|
|
18245
17512
|
const token = response.token;
|
|
@@ -18447,17 +17714,19 @@ class HistorianHostRunner {
|
|
|
18447
17714
|
});
|
|
18448
17715
|
}
|
|
18449
17716
|
async execute(claim, abort) {
|
|
17717
|
+
const invocations = [];
|
|
18450
17718
|
const budgetMs = Math.max(1, claim.awaitBudgetMs);
|
|
18451
17719
|
const heartbeat = this.startHeartbeat(claim, abort);
|
|
18452
17720
|
const cancelDeadline = this.schedule(() => {
|
|
18453
17721
|
abort.abort(new Error(`historian host run ${claim.runId} exceeded its await budget`));
|
|
18454
17722
|
}, budgetMs);
|
|
18455
17723
|
try {
|
|
18456
|
-
const completion = await this.runCompletion(claim, budgetMs, abort.signal);
|
|
17724
|
+
const completion = await this.runCompletion(claim, budgetMs, abort.signal, invocations);
|
|
18457
17725
|
if (heartbeat.claimOver)
|
|
18458
17726
|
return;
|
|
18459
17727
|
await this.report(claim, {
|
|
18460
|
-
output: { text: completion.text, length_capped: completion.lengthCapped }
|
|
17728
|
+
output: { text: completion.text, length_capped: completion.lengthCapped },
|
|
17729
|
+
invocations
|
|
18461
17730
|
});
|
|
18462
17731
|
} catch (error) {
|
|
18463
17732
|
if (heartbeat.claimOver) {
|
|
@@ -18472,7 +17741,8 @@ class HistorianHostRunner {
|
|
|
18472
17741
|
error: {
|
|
18473
17742
|
code: failureCode(error, abort.signal.aborted),
|
|
18474
17743
|
message: describeError2(error)
|
|
18475
|
-
}
|
|
17744
|
+
},
|
|
17745
|
+
invocations
|
|
18476
17746
|
});
|
|
18477
17747
|
} finally {
|
|
18478
17748
|
cancelDeadline();
|
|
@@ -18548,7 +17818,7 @@ class HistorianHostRunner {
|
|
|
18548
17818
|
});
|
|
18549
17819
|
return failure ? `${key}: ${failure}` : null;
|
|
18550
17820
|
}
|
|
18551
|
-
async runCompletion(claim, budgetMs, signal) {
|
|
17821
|
+
async runCompletion(claim, budgetMs, signal, invocations) {
|
|
18552
17822
|
const binding = this.deps.openExecutor(claim.sessionId);
|
|
18553
17823
|
if (!binding) {
|
|
18554
17824
|
throw new Error(`no hidden completion carrier for session ${claim.sessionId}`);
|
|
@@ -18575,6 +17845,31 @@ class HistorianHostRunner {
|
|
|
18575
17845
|
});
|
|
18576
17846
|
let promptSettled = false;
|
|
18577
17847
|
let attemptStartedAt = Date.now();
|
|
17848
|
+
const withVariant = (model) => {
|
|
17849
|
+
const qualifier = this.deps.resolveVariant?.(model);
|
|
17850
|
+
return qualifier ? { model, qualifier } : model;
|
|
17851
|
+
};
|
|
17852
|
+
let attemptModel = head;
|
|
17853
|
+
let attemptRecorded = false;
|
|
17854
|
+
const recordAttempt = (completion, error) => {
|
|
17855
|
+
if (attemptRecorded)
|
|
17856
|
+
return;
|
|
17857
|
+
attemptRecorded = true;
|
|
17858
|
+
const split = attemptModel.indexOf("/");
|
|
17859
|
+
const token = (value) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
17860
|
+
invocations.push({
|
|
17861
|
+
provider_id: completion?.providerId ?? (split >= 0 ? attemptModel.slice(0, split) : null),
|
|
17862
|
+
model_id: completion?.modelId ?? (split >= 0 ? attemptModel.slice(split + 1) : attemptModel),
|
|
17863
|
+
started_at: attemptStartedAt,
|
|
17864
|
+
ended_at: Date.now(),
|
|
17865
|
+
status: error ? signal.aborted ? "aborted" : failedInvocationStatus(error) : completion?.text?.trim() ? "completed" : "empty",
|
|
17866
|
+
input_tokens: token(completion?.usage.input),
|
|
17867
|
+
output_tokens: token(completion?.usage.output),
|
|
17868
|
+
cache_read_tokens: token(completion?.usage.cacheRead),
|
|
17869
|
+
cache_write_tokens: token(completion?.usage.cacheWrite),
|
|
17870
|
+
error: error ? describeError2(error) : null
|
|
17871
|
+
});
|
|
17872
|
+
};
|
|
18578
17873
|
try {
|
|
18579
17874
|
if (!handle.id)
|
|
18580
17875
|
throw new Error("hidden completion carrier returned no session id");
|
|
@@ -18584,33 +17879,53 @@ class HistorianHostRunner {
|
|
|
18584
17879
|
body: {
|
|
18585
17880
|
agent: "historian",
|
|
18586
17881
|
system: claim.system,
|
|
18587
|
-
...modelBodyField(head),
|
|
17882
|
+
...modelBodyField(withVariant(head)),
|
|
18588
17883
|
parts: [{ type: "text", text: claim.user, synthetic: true }]
|
|
18589
17884
|
}
|
|
18590
17885
|
}, {
|
|
18591
17886
|
transport: Object.assign((request) => {
|
|
18592
17887
|
const model = request.body?.model;
|
|
18593
17888
|
const key = model?.providerID && model?.modelID ? `${model.providerID}/${model.modelID}` : head;
|
|
18594
|
-
const failure = this.admissionFailure(claim, key);
|
|
18595
|
-
if (failure)
|
|
18596
|
-
throw new Error(failure);
|
|
18597
17889
|
attemptStartedAt = Date.now();
|
|
18598
|
-
|
|
17890
|
+
attemptModel = key;
|
|
17891
|
+
attemptRecorded = false;
|
|
17892
|
+
try {
|
|
17893
|
+
const failure = this.admissionFailure(claim, key);
|
|
17894
|
+
if (failure)
|
|
17895
|
+
throw new Error(failure);
|
|
17896
|
+
return executor.attempt(handle, request).catch((error) => {
|
|
17897
|
+
recordAttempt(undefined, error);
|
|
17898
|
+
throw error;
|
|
17899
|
+
});
|
|
17900
|
+
} catch (error) {
|
|
17901
|
+
recordAttempt(undefined, error);
|
|
17902
|
+
throw error;
|
|
17903
|
+
}
|
|
18599
17904
|
}, { childSessionId: handle.childSessionId }),
|
|
18600
17905
|
timeoutMs: attemptMs,
|
|
18601
17906
|
signal,
|
|
18602
|
-
fallbackModels: rest,
|
|
17907
|
+
fallbackModels: rest.map(withVariant),
|
|
18603
17908
|
callContext: `historian-host:${claim.runId}`,
|
|
18604
|
-
fetchOutput: () => withinAttempt(executor.collect(handle, 50), attemptStartedAt + attemptMs - Date.now(), attemptMs, signal)
|
|
17909
|
+
fetchOutput: () => withinAttempt(executor.collect(handle, 50), attemptStartedAt + attemptMs - Date.now(), attemptMs, signal).catch((error) => {
|
|
17910
|
+
recordAttempt(undefined, error);
|
|
17911
|
+
throw error;
|
|
17912
|
+
}),
|
|
18605
17913
|
validateOutput: (completion) => {
|
|
18606
17914
|
const text = completion.text;
|
|
18607
|
-
if (!text)
|
|
18608
|
-
|
|
17915
|
+
if (!text?.trim()) {
|
|
17916
|
+
const error = new Error("historian host completion returned no output");
|
|
17917
|
+
recordAttempt(completion, error);
|
|
17918
|
+
throw error;
|
|
17919
|
+
}
|
|
17920
|
+
recordAttempt(completion);
|
|
18609
17921
|
return { text, lengthCapped: completion.lengthCapped === true };
|
|
18610
17922
|
}
|
|
18611
17923
|
});
|
|
18612
17924
|
promptSettled = true;
|
|
18613
17925
|
return run.validated;
|
|
17926
|
+
} catch (error) {
|
|
17927
|
+
recordAttempt(undefined, error);
|
|
17928
|
+
throw error;
|
|
18614
17929
|
} finally {
|
|
18615
17930
|
await executor.close(handle, {
|
|
18616
17931
|
promptSettled,
|
|
@@ -18637,7 +17952,7 @@ class HistorianHostRunner {
|
|
|
18637
17952
|
this.log(`report for ${claim.runId} refused: ${refusal}`);
|
|
18638
17953
|
return;
|
|
18639
17954
|
}
|
|
18640
|
-
const publish =
|
|
17955
|
+
const publish = isRecord2(response) && typeof response.publish === "string" ? response.publish : "immediate";
|
|
18641
17956
|
this.log(`report for ${claim.runId} accepted (publish=${publish})`);
|
|
18642
17957
|
}
|
|
18643
17958
|
schedule(callback, delayMs) {
|
|
@@ -18676,6 +17991,7 @@ function createHistorianHostRunner(args) {
|
|
|
18676
17991
|
enabled: args.enabled,
|
|
18677
17992
|
...args.maxOutputTokens !== undefined ? { maxOutputTokens: args.maxOutputTokens } : {},
|
|
18678
17993
|
...args.attemptTimeoutMs ? { attemptTimeoutMs: args.attemptTimeoutMs } : {},
|
|
17994
|
+
...args.resolveVariant ? { resolveVariant: args.resolveVariant } : {},
|
|
18679
17995
|
...args.now ? { now: args.now } : {},
|
|
18680
17996
|
...args.log ? { log: args.log } : {},
|
|
18681
17997
|
...args.idleIntervalMs !== undefined ? { idleIntervalMs: args.idleIntervalMs } : {},
|
|
@@ -19629,17 +18945,41 @@ function resolveSharedCompartmentBoundaries(db, sessionId) {
|
|
|
19629
18945
|
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);
|
|
19630
18946
|
if (rows.every((row) => row.start_block_index !== null && row.end_block_index !== null))
|
|
19631
18947
|
return [];
|
|
19632
|
-
|
|
19633
|
-
const
|
|
18948
|
+
let ordinalBasis;
|
|
18949
|
+
const ordinals = () => {
|
|
18950
|
+
ordinalBasis ??= readRawSessionMessageIdOrdinalsForRange2(sessionId, 1, Number.MAX_SAFE_INTEGER);
|
|
18951
|
+
return ordinalBasis;
|
|
18952
|
+
};
|
|
18953
|
+
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] : []));
|
|
18954
|
+
const providerRaw = new Map;
|
|
19634
18955
|
const endpoint = (rawId, blockIndex, edge) => {
|
|
19635
|
-
|
|
19636
|
-
|
|
19637
|
-
|
|
19638
|
-
|
|
19639
|
-
|
|
19640
|
-
|
|
18956
|
+
const needsLastBlock = blockIndex === null && edge === "end";
|
|
18957
|
+
let ordinal;
|
|
18958
|
+
let createdAt;
|
|
18959
|
+
let lastBlockIndex = 0;
|
|
18960
|
+
if (stored === null) {
|
|
18961
|
+
if (!providerRaw.has(rawId))
|
|
18962
|
+
providerRaw.set(rawId, readRawSessionMessagePartsById2(sessionId, rawId));
|
|
18963
|
+
const raw = providerRaw.get(rawId) ?? null;
|
|
18964
|
+
ordinal = raw?.id === rawId ? ordinals().get(rawId) ?? null : null;
|
|
18965
|
+
createdAt = raw?.createdAt;
|
|
18966
|
+
if (needsLastBlock)
|
|
18967
|
+
lastBlockIndex = moduleRawBlockMappings(raw).at(-1)?.blockIndex ?? 0;
|
|
18968
|
+
} else {
|
|
18969
|
+
let read = stored.get(rawId);
|
|
18970
|
+
if (read === undefined || needsLastBlock && read && read.lastBlockIndex === undefined) {
|
|
18971
|
+
read = readRawSessionBoundaryEndpoints2(sessionId, [rawId], needsLastBlock ? [rawId] : [])?.get(rawId) ?? null;
|
|
18972
|
+
stored.set(rawId, read);
|
|
18973
|
+
}
|
|
18974
|
+
ordinal = read?.ordinal ?? null;
|
|
18975
|
+
createdAt = read?.createdAt;
|
|
18976
|
+
if (needsLastBlock)
|
|
18977
|
+
lastBlockIndex = read?.lastBlockIndex ?? 0;
|
|
18978
|
+
}
|
|
18979
|
+
const block = blockIndex !== null ? blockIndex : edge === "start" ? 0 : lastBlockIndex;
|
|
18980
|
+
return { ordinal, id: `${rawId}#${block}`, createdAt };
|
|
19641
18981
|
};
|
|
19642
|
-
const idsByOrdinal = rows.some((row) => !row.start_message_id || !row.end_message_id) ? new Map([...ordinals].map(([id, ordinal]) => [ordinal, id])) : null;
|
|
18982
|
+
const idsByOrdinal = rows.some((row) => !row.start_message_id || !row.end_message_id) ? new Map([...ordinals()].map(([id, ordinal]) => [ordinal, id])) : null;
|
|
19643
18983
|
const endpoints = rows.map((row) => ({
|
|
19644
18984
|
start: endpoint(row.start_message_id, row.start_block_index, "start"),
|
|
19645
18985
|
end: endpoint(row.end_message_id, row.end_block_index, "end")
|
|
@@ -19671,9 +19011,9 @@ function resolveSharedCompartmentBoundaries(db, sessionId) {
|
|
|
19671
19011
|
start = resolveMissingId(row.start_message_id, row.start_block_index, startOrdinal, "start");
|
|
19672
19012
|
if (!row.end_message_id)
|
|
19673
19013
|
end = resolveMissingId(row.end_message_id, row.end_block_index, endOrdinal, "end");
|
|
19674
|
-
const dates = typeof start.
|
|
19675
|
-
start_date: formatDate(start.
|
|
19676
|
-
end_date: formatDate(end.
|
|
19014
|
+
const dates = typeof start.createdAt === "number" && typeof end.createdAt === "number" ? {
|
|
19015
|
+
start_date: formatDate(start.createdAt),
|
|
19016
|
+
end_date: formatDate(end.createdAt)
|
|
19677
19017
|
} : { start_date: null, end_date: null };
|
|
19678
19018
|
return {
|
|
19679
19019
|
sequence: row.sequence,
|
|
@@ -20693,6 +20033,9 @@ class FrozenReplayOverProvenLimitRefusal extends Error {
|
|
|
20693
20033
|
}
|
|
20694
20034
|
}
|
|
20695
20035
|
var RUST_FAILURE_PARK_THRESHOLD = 3;
|
|
20036
|
+
var TRANSFORM_FINAL_PAGE_ABANDONED_CODE = "transform_final_page_abandoned";
|
|
20037
|
+
var TRANSFORM_PAGE_IN_PROGRESS_CODE = "authority_transform_page_in_progress";
|
|
20038
|
+
var RUST_IN_PROGRESS_PARK_EXEMPTION_MS = 5 * 60000;
|
|
20696
20039
|
var RUST_PARK_RETRY_INTERVAL = 5;
|
|
20697
20040
|
var RUST_EMERGENCY_WALL_PCT = 95;
|
|
20698
20041
|
var RUST_PARK_PROBE_PRESSURE_BYPASS_PCT = 90;
|
|
@@ -20769,20 +20112,20 @@ function rustWireCacheEstimatedBytes(cache) {
|
|
|
20769
20112
|
}
|
|
20770
20113
|
return bytes;
|
|
20771
20114
|
}
|
|
20772
|
-
function
|
|
20115
|
+
function isRecord3(value) {
|
|
20773
20116
|
return value !== null && typeof value === "object";
|
|
20774
20117
|
}
|
|
20775
20118
|
function moduleFailureCode(error) {
|
|
20776
20119
|
let current = error;
|
|
20777
20120
|
const seen = new Set;
|
|
20778
|
-
while (
|
|
20121
|
+
while (isRecord3(current) && !seen.has(current)) {
|
|
20779
20122
|
seen.add(current);
|
|
20780
20123
|
if (typeof current.code === "string" && current.code.length > 0)
|
|
20781
20124
|
return current.code;
|
|
20782
20125
|
if (typeof current.message === "string") {
|
|
20783
20126
|
try {
|
|
20784
20127
|
const detail = JSON.parse(current.message);
|
|
20785
|
-
if (
|
|
20128
|
+
if (isRecord3(detail) && typeof detail.code === "string")
|
|
20786
20129
|
return detail.code;
|
|
20787
20130
|
} catch {}
|
|
20788
20131
|
}
|
|
@@ -20793,6 +20136,10 @@ function moduleFailureCode(error) {
|
|
|
20793
20136
|
function isNonRetryableStateSyncFailure(error) {
|
|
20794
20137
|
return moduleFailureCode(error) === "state_sync_non_retryable";
|
|
20795
20138
|
}
|
|
20139
|
+
function isModuleBusyWithAbandonedTransform(error) {
|
|
20140
|
+
const code = moduleFailureCode(error);
|
|
20141
|
+
return code === TRANSFORM_FINAL_PAGE_ABANDONED_CODE || code === TRANSFORM_PAGE_IN_PROGRESS_CODE;
|
|
20142
|
+
}
|
|
20796
20143
|
function replaceMessagesInPlace(output, next) {
|
|
20797
20144
|
const target = output.messages;
|
|
20798
20145
|
if (target !== next)
|
|
@@ -20800,9 +20147,9 @@ function replaceMessagesInPlace(output, next) {
|
|
|
20800
20147
|
return target;
|
|
20801
20148
|
}
|
|
20802
20149
|
function messageInfo2(value) {
|
|
20803
|
-
if (!
|
|
20150
|
+
if (!isRecord3(value))
|
|
20804
20151
|
return {};
|
|
20805
|
-
return
|
|
20152
|
+
return isRecord3(value.info) ? value.info : value;
|
|
20806
20153
|
}
|
|
20807
20154
|
function messageIdOf2(message) {
|
|
20808
20155
|
const id = messageInfo2(message).id;
|
|
@@ -20863,10 +20210,10 @@ function messageCacheSignature(message) {
|
|
|
20863
20210
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
20864
20211
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
20865
20212
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
20866
|
-
return `${messageIdOf2(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${
|
|
20213
|
+
return `${messageIdOf2(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash12("sha256").update(serializedMessage).digest("hex")}`;
|
|
20867
20214
|
}
|
|
20868
20215
|
function advanceWireFingerprint(previous, encoded) {
|
|
20869
|
-
return
|
|
20216
|
+
return createHash12("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
20870
20217
|
}
|
|
20871
20218
|
function buildWireFingerprint(encoded) {
|
|
20872
20219
|
let fingerprint = "rust-wire-v1";
|
|
@@ -20972,7 +20319,7 @@ function isSyntheticUserMessage(message) {
|
|
|
20972
20319
|
if (!message || messageInfo2(message).role !== "user" || !Array.isArray(message.parts)) {
|
|
20973
20320
|
return false;
|
|
20974
20321
|
}
|
|
20975
|
-
return message.parts.length > 0 && message.parts.every((part) =>
|
|
20322
|
+
return message.parts.length > 0 && message.parts.every((part) => isRecord3(part) && (part.synthetic === true || part.ignored === true));
|
|
20976
20323
|
}
|
|
20977
20324
|
function observeSyntheticTurn(state, messages) {
|
|
20978
20325
|
const newest = newestUserMessage(messages);
|
|
@@ -20992,25 +20339,25 @@ function observeSyntheticTurn(state, messages) {
|
|
|
20992
20339
|
function assertNativeBoundary(output, sessionId, boundaryId) {
|
|
20993
20340
|
const first = output.find((message) => messageInfo2(message).role !== "system");
|
|
20994
20341
|
const info = messageInfo2(first);
|
|
20995
|
-
const parts =
|
|
20996
|
-
const synthetic = parts.length > 0 && parts.every((part) =>
|
|
20342
|
+
const parts = isRecord3(first) && Array.isArray(first.parts) ? first.parts : [];
|
|
20343
|
+
const synthetic = parts.length > 0 && parts.every((part) => isRecord3(part) && part.synthetic === true);
|
|
20997
20344
|
if (info.role === "user" && info.sessionID === sessionId && synthetic)
|
|
20998
20345
|
return;
|
|
20999
20346
|
const headSummary = output.slice(0, 3).map((message) => {
|
|
21000
20347
|
const mi = messageInfo2(message);
|
|
21001
|
-
const mParts =
|
|
21002
|
-
const partDesc = mParts.slice(0, 5).map((part) =>
|
|
20348
|
+
const mParts = isRecord3(message) && Array.isArray(message.parts) ? message.parts : [];
|
|
20349
|
+
const partDesc = mParts.slice(0, 5).map((part) => isRecord3(part) ? `${String(part.type)}${part.synthetic === true ? "" : "!"}` : "?").join(",");
|
|
21003
20350
|
return `role=${String(mi.role)} sid=${mi.sessionID === sessionId ? "ok" : String(mi.sessionID ?? "absent")} id=${String(mi.id ?? "-").slice(0, 24)} parts=[${partDesc}]`;
|
|
21004
20351
|
});
|
|
21005
20352
|
throw new Error(`rust transform wire invariant failed: boundary=${boundaryId} expected a synthetic m0 user message scoped to session ${sessionId}; head: ${headSummary.join(" | ")}`);
|
|
21006
20353
|
}
|
|
21007
20354
|
function responseValue(response) {
|
|
21008
|
-
if (
|
|
20355
|
+
if (isRecord3(response) && (response.ok === false || response.isError === true || response.error != null)) {
|
|
21009
20356
|
throw new RustTransformProtocolError("rust transform wire invariant failed: error envelope cannot permit host mutations");
|
|
21010
20357
|
}
|
|
21011
|
-
if (
|
|
20358
|
+
if (isRecord3(response) && isRecord3(response.result))
|
|
21012
20359
|
return response.result;
|
|
21013
|
-
if (
|
|
20360
|
+
if (isRecord3(response))
|
|
21014
20361
|
return response;
|
|
21015
20362
|
throw new Error("module transform returned a non-object response");
|
|
21016
20363
|
}
|
|
@@ -21042,7 +20389,7 @@ function stateSyncInputSignature(args) {
|
|
|
21042
20389
|
function isTransformPageAttemptMismatch(error) {
|
|
21043
20390
|
let current = error;
|
|
21044
20391
|
const seen = new Set;
|
|
21045
|
-
while (
|
|
20392
|
+
while (isRecord3(current) && !seen.has(current)) {
|
|
21046
20393
|
seen.add(current);
|
|
21047
20394
|
const code = typeof current.code === "string" ? current.code : "";
|
|
21048
20395
|
const message = typeof current.message === "string" ? current.message : "";
|
|
@@ -21069,7 +20416,7 @@ function mirrorRustRenderedMemoryIds(args) {
|
|
|
21069
20416
|
function modelFromMessages(messages) {
|
|
21070
20417
|
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
21071
20418
|
const info = messages[index]?.info;
|
|
21072
|
-
const model =
|
|
20419
|
+
const model = isRecord3(info?.model) ? info.model : undefined;
|
|
21073
20420
|
if (typeof model?.providerID === "string" && typeof model.modelID === "string") {
|
|
21074
20421
|
return { providerID: model.providerID, modelID: model.modelID };
|
|
21075
20422
|
}
|
|
@@ -21090,6 +20437,7 @@ function ensureState(states, sessionId) {
|
|
|
21090
20437
|
passesSincePark: 0,
|
|
21091
20438
|
warningSent: false,
|
|
21092
20439
|
forceFullWire: false,
|
|
20440
|
+
transformInProgressSinceMs: null,
|
|
21093
20441
|
ordinalMemoAnchor: null,
|
|
21094
20442
|
ordinalMemoStoredCount: null,
|
|
21095
20443
|
ordinalMemoCanonicalCount: 0,
|
|
@@ -21223,8 +20571,8 @@ function shouldDisarmRustEmergencyRecovery(input) {
|
|
|
21223
20571
|
return null;
|
|
21224
20572
|
}
|
|
21225
20573
|
function directiveTextOf(response) {
|
|
21226
|
-
const directives =
|
|
21227
|
-
const channel2 =
|
|
20574
|
+
const directives = isRecord3(response.host_directives) ? response.host_directives : undefined;
|
|
20575
|
+
const channel2 = isRecord3(directives?.channel2_nudge) ? directives.channel2_nudge : undefined;
|
|
21228
20576
|
return typeof channel2?.text === "string" && channel2.text.length > 0 ? channel2.text : undefined;
|
|
21229
20577
|
}
|
|
21230
20578
|
function isNeedFullSync(response) {
|
|
@@ -21234,18 +20582,18 @@ var TODO_HEAD_ANCHOR_ID = "__magic_context_todo_head__";
|
|
|
21234
20582
|
function syntheticTodoAnchorFromNative(messages) {
|
|
21235
20583
|
for (let index = 0;index < messages.length; index += 1) {
|
|
21236
20584
|
const message = messages[index];
|
|
21237
|
-
if (!
|
|
20585
|
+
if (!isRecord3(message) || !Array.isArray(message.parts))
|
|
21238
20586
|
continue;
|
|
21239
|
-
const part = message.parts.find((candidate) =>
|
|
21240
|
-
if (!
|
|
20587
|
+
const part = message.parts.find((candidate) => isRecord3(candidate) && candidate.syntheticTodoMarker === true);
|
|
20588
|
+
if (!isRecord3(part) || typeof part.callID !== "string")
|
|
21241
20589
|
continue;
|
|
21242
|
-
const state =
|
|
21243
|
-
const input = state &&
|
|
20590
|
+
const state = isRecord3(part.state) ? part.state : undefined;
|
|
20591
|
+
const input = state && isRecord3(state.input) ? state.input : undefined;
|
|
21244
20592
|
const stateJson = normalizeTodoStateJson(input?.todos);
|
|
21245
20593
|
if (stateJson === null || computeSyntheticCallId(stateJson) !== part.callID)
|
|
21246
20594
|
continue;
|
|
21247
20595
|
const previous = messages[index - 1];
|
|
21248
|
-
const previousInfo =
|
|
20596
|
+
const previousInfo = isRecord3(previous) && isRecord3(previous.info) ? previous.info : undefined;
|
|
21249
20597
|
const messageId = previousInfo && typeof previousInfo.id === "string" && previousInfo.id.length > 0 ? previousInfo.id : TODO_HEAD_ANCHOR_ID;
|
|
21250
20598
|
return { callId: part.callID, messageId, stateJson };
|
|
21251
20599
|
}
|
|
@@ -21274,7 +20622,7 @@ function hasNativeResponseContent(response) {
|
|
|
21274
20622
|
return true;
|
|
21275
20623
|
}
|
|
21276
20624
|
const delta = response.native_messages_delta;
|
|
21277
|
-
return
|
|
20625
|
+
return isRecord3(delta) && Array.isArray(delta.messages);
|
|
21278
20626
|
}
|
|
21279
20627
|
function applyNativeMessagesVerbatim(output, response, previous) {
|
|
21280
20628
|
const nativeMessages = response.native_messages;
|
|
@@ -21288,7 +20636,7 @@ function applyNativeMessagesVerbatim(output, response, previous) {
|
|
|
21288
20636
|
return replaceMessagesInPlace(output, nativeMessages);
|
|
21289
20637
|
}
|
|
21290
20638
|
const delta = response.native_messages_delta;
|
|
21291
|
-
if (!
|
|
20639
|
+
if (!isRecord3(delta) || !Array.isArray(delta.messages)) {
|
|
21292
20640
|
throw new Error("rust transform response omitted native_messages");
|
|
21293
20641
|
}
|
|
21294
20642
|
const replaceFrom = delta.replace_from;
|
|
@@ -21300,6 +20648,16 @@ function applyNativeMessagesVerbatim(output, response, previous) {
|
|
|
21300
20648
|
...delta.messages
|
|
21301
20649
|
]);
|
|
21302
20650
|
}
|
|
20651
|
+
function rustWrapupHistorianFields(historian) {
|
|
20652
|
+
const chain = resolvedHistorianModelChain(historian);
|
|
20653
|
+
return {
|
|
20654
|
+
historian_model_chain: chain,
|
|
20655
|
+
historian_model_limits: resolvedHistorianModelLimits(chain),
|
|
20656
|
+
historian_model_variants: resolvedHistorianModelVariants(historian),
|
|
20657
|
+
historian_timeout_ms: historian.timeoutMs,
|
|
20658
|
+
...historian.maxOutputTokens !== undefined ? { historian_max_output_tokens: historian.maxOutputTokens } : {}
|
|
20659
|
+
};
|
|
20660
|
+
}
|
|
21303
20661
|
function resolvedHistorianModelChain(deps) {
|
|
21304
20662
|
const models = [deps.historianModel, ...deps.fallbackModels ?? []].map((entry) => typeof entry === "string" ? entry : entry?.model).filter((model) => typeof model === "string" && model.length > 0);
|
|
21305
20663
|
return [...new Set(models)];
|
|
@@ -21489,7 +20847,14 @@ function createRustModeTransform(deps, options) {
|
|
|
21489
20847
|
sessionDirectory: (sessionId) => deps.sessionDirectoryBySession?.get(sessionId) ?? deps.directory ?? process.cwd(),
|
|
21490
20848
|
enabled: () => deps.historianHostRunnerEnabled !== false,
|
|
21491
20849
|
...deps.historianMaxOutputTokens !== undefined ? { maxOutputTokens: deps.historianMaxOutputTokens } : {},
|
|
21492
|
-
attemptTimeoutMs: () => deps.resolveHistorianRun?.().timeoutMs ?? deps.historianTimeoutMs
|
|
20850
|
+
attemptTimeoutMs: () => deps.resolveHistorianRun?.().timeoutMs ?? deps.historianTimeoutMs,
|
|
20851
|
+
resolveVariant: (model) => {
|
|
20852
|
+
const run = deps.resolveHistorianRun?.();
|
|
20853
|
+
return resolvedHistorianModelVariants({
|
|
20854
|
+
historianModel: run?.model ?? deps.historianModel,
|
|
20855
|
+
fallbackModels: run?.fallbackModels ?? deps.fallbackModels
|
|
20856
|
+
})[model];
|
|
20857
|
+
}
|
|
21493
20858
|
});
|
|
21494
20859
|
} catch (error) {
|
|
21495
20860
|
hostRunner = undefined;
|
|
@@ -21528,7 +20893,7 @@ function createRustModeTransform(deps, options) {
|
|
|
21528
20893
|
};
|
|
21529
20894
|
const callModule = async (args, attemptTimeoutMs = args.timeoutMs ?? timeoutMs, allowTimeoutRetry = true) => {
|
|
21530
20895
|
const controller = new AbortController;
|
|
21531
|
-
const body =
|
|
20896
|
+
const body = isRecord3(args.body) ? args.body : {};
|
|
21532
20897
|
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}`), {
|
|
21533
20898
|
code: "state_sync_timeout",
|
|
21534
20899
|
stage: "module_ack",
|
|
@@ -21559,18 +20924,24 @@ function createRustModeTransform(deps, options) {
|
|
|
21559
20924
|
clock.clearTimeout(timer);
|
|
21560
20925
|
sessionLog2(args.sessionId, "rust transform deadline: waiting up to 45000ms for identical final-page completion");
|
|
21561
20926
|
const completionDeadline = clock.now() + 45000;
|
|
20927
|
+
const abandoned = (cause) => Object.assign(new Error(timeoutError.message, { cause }), {
|
|
20928
|
+
code: TRANSFORM_FINAL_PAGE_ABANDONED_CODE
|
|
20929
|
+
});
|
|
21562
20930
|
for (;; ) {
|
|
21563
20931
|
const remaining = completionDeadline - clock.now();
|
|
21564
20932
|
if (remaining <= 0)
|
|
21565
|
-
throw timeoutError;
|
|
20933
|
+
throw abandoned(timeoutError);
|
|
21566
20934
|
try {
|
|
21567
20935
|
return await callModule(args, remaining, false);
|
|
21568
20936
|
} catch (retryError) {
|
|
21569
|
-
if (moduleFailureCode(retryError) !==
|
|
20937
|
+
if (moduleFailureCode(retryError) !== TRANSFORM_PAGE_IN_PROGRESS_CODE) {
|
|
20938
|
+
if (retryError instanceof Error && /timed out|deadline/i.test(retryError.message))
|
|
20939
|
+
throw abandoned(retryError);
|
|
21570
20940
|
throw retryError;
|
|
20941
|
+
}
|
|
21571
20942
|
const wait = Math.min(250, completionDeadline - clock.now());
|
|
21572
20943
|
if (wait <= 0)
|
|
21573
|
-
throw
|
|
20944
|
+
throw abandoned(retryError);
|
|
21574
20945
|
await new Promise((resolve) => clock.setTimeout(resolve, wait));
|
|
21575
20946
|
}
|
|
21576
20947
|
}
|
|
@@ -21588,7 +20959,7 @@ function createRustModeTransform(deps, options) {
|
|
|
21588
20959
|
const probeAfterMs = options.stallProbeAfterMsForTests ?? RUST_STALL_PROBE_AFTER_MS;
|
|
21589
20960
|
const probeTimeoutMs = options.healthProbeTimeoutMsForTests ?? RUST_HEALTH_PROBE_TIMEOUT_MS;
|
|
21590
20961
|
const originalAttemptId = randomUUID6();
|
|
21591
|
-
const originalBody =
|
|
20962
|
+
const originalBody = isRecord3(args.body) ? { ...args.body, attempt_id: originalAttemptId } : args.body;
|
|
21592
20963
|
const original = callModule({ ...args, body: originalBody }, attemptTimeoutMs);
|
|
21593
20964
|
if (attemptTimeoutMs <= probeAfterMs)
|
|
21594
20965
|
return original;
|
|
@@ -21626,7 +20997,24 @@ function createRustModeTransform(deps, options) {
|
|
|
21626
20997
|
sessionLog2(args.sessionId, `rust transform still pending after healthy probe original_attempt=${originalAttemptId} stall_ms=${clock.now() - startedAtMs}; duplicate resend suppressed`);
|
|
21627
20998
|
return original;
|
|
21628
20999
|
};
|
|
21000
|
+
const inProgressRunWithinBound = (state) => state.transformInProgressSinceMs !== null && clock.now() - state.transformInProgressSinceMs <= RUST_IN_PROGRESS_PARK_EXEMPTION_MS;
|
|
21001
|
+
const exemptInProgressRefusal = (state, error) => {
|
|
21002
|
+
if (moduleFailureCode(error) !== TRANSFORM_PAGE_IN_PROGRESS_CODE) {
|
|
21003
|
+
state.transformInProgressSinceMs = null;
|
|
21004
|
+
return false;
|
|
21005
|
+
}
|
|
21006
|
+
state.transformInProgressSinceMs ??= clock.now();
|
|
21007
|
+
return inProgressRunWithinBound(state);
|
|
21008
|
+
};
|
|
21629
21009
|
const markFailure = (sessionId, state, error) => {
|
|
21010
|
+
if (isModuleBusyWithAbandonedTransform(error)) {
|
|
21011
|
+
state.forceFullWire = true;
|
|
21012
|
+
}
|
|
21013
|
+
if (exemptInProgressRefusal(state, error)) {
|
|
21014
|
+
state.failureCount += 1;
|
|
21015
|
+
sessionLog2(sessionId, "rust transform deferred; the module is still applying an earlier transform of this session; attempting LKG replay:", error);
|
|
21016
|
+
return;
|
|
21017
|
+
}
|
|
21630
21018
|
state.consecutiveFailures = isNonRetryableStateSyncFailure(error) ? Math.max(RUST_FAILURE_PARK_THRESHOLD, state.consecutiveFailures + 1) : state.consecutiveFailures + 1;
|
|
21631
21019
|
state.failureCount += 1;
|
|
21632
21020
|
sessionLog2(sessionId, "rust transform failed; attempting LKG replay:", error);
|
|
@@ -21975,6 +21363,7 @@ function createRustModeTransform(deps, options) {
|
|
|
21975
21363
|
let requestInputTokens = 0;
|
|
21976
21364
|
let decision = "error";
|
|
21977
21365
|
let materializeReason = "none";
|
|
21366
|
+
let frozenReleaseReason = null;
|
|
21978
21367
|
let schedulerDecision;
|
|
21979
21368
|
let responseCommitted;
|
|
21980
21369
|
let responsePrefixBustPermitted;
|
|
@@ -22074,6 +21463,9 @@ function createRustModeTransform(deps, options) {
|
|
|
22074
21463
|
if (moduleFailureCode(cause) === "transform_transport_interrupted") {
|
|
22075
21464
|
throw new EmergencyFailClosedError(ENGINE_RECONNECTING_USER_MESSAGE, { cause });
|
|
22076
21465
|
}
|
|
21466
|
+
if (isModuleBusyWithAbandonedTransform(cause)) {
|
|
21467
|
+
throw new EmergencyFailClosedError(moduleFailureCode(cause) === TRANSFORM_PAGE_IN_PROGRESS_CODE ? ENGINE_BUSY_USER_MESSAGE : ENGINE_RECONNECTING_USER_MESSAGE, { cause });
|
|
21468
|
+
}
|
|
22077
21469
|
if (!deps.compactionOff && isTransientSqliteError2(cause)) {
|
|
22078
21470
|
throw new StorageBusyRefusalError(cause, "rust-mode-transform");
|
|
22079
21471
|
}
|
|
@@ -22212,7 +21604,8 @@ function createRustModeTransform(deps, options) {
|
|
|
22212
21604
|
decision,
|
|
22213
21605
|
materializeReason: materializeReason === "none" ? null : materializeReason,
|
|
22214
21606
|
inputTokens: requestInputTokens,
|
|
22215
|
-
tsMs: passObservedAtMs
|
|
21607
|
+
tsMs: passObservedAtMs,
|
|
21608
|
+
lkgFrozenReleaseReason: applied && served ? frozenReleaseReason ?? undefined : undefined
|
|
22216
21609
|
});
|
|
22217
21610
|
}
|
|
22218
21611
|
};
|
|
@@ -22223,12 +21616,12 @@ function createRustModeTransform(deps, options) {
|
|
|
22223
21616
|
servedFrom = typeof response.served_from === "string" ? response.served_from : "unknown";
|
|
22224
21617
|
schedulerDecision = typeof response.scheduler_decision === "string" ? response.scheduler_decision : undefined;
|
|
22225
21618
|
schedulerDeferReason = typeof response.scheduler_defer_reason === "string" ? response.scheduler_defer_reason : undefined;
|
|
22226
|
-
const historian =
|
|
21619
|
+
const historian = isRecord3(response.historian) ? response.historian : undefined;
|
|
22227
21620
|
historianNoFire = typeof historian?.no_fire === "string" ? historian.no_fire : undefined;
|
|
22228
21621
|
historianCanonicalCause = typeof historian?.canonical_cause === "string" ? historian.canonical_cause : undefined;
|
|
22229
21622
|
materializeReason = typeof response.materialize_reason === "string" && response.materialize_reason.length > 0 ? response.materialize_reason : "none";
|
|
22230
21623
|
identityDelta = Array.isArray(response.identity_delta) ? response.identity_delta.filter((component) => typeof component === "string" && component.length > 0) : [];
|
|
22231
|
-
const timings =
|
|
21624
|
+
const timings = isRecord3(response.timings) ? response.timings : undefined;
|
|
22232
21625
|
const applyOnceTotal = timings?.total;
|
|
22233
21626
|
const handlerTotal = timings?.handler_total;
|
|
22234
21627
|
moduleElapsedMs = typeof handlerTotal === "number" && Number.isFinite(handlerTotal) ? handlerTotal : typeof applyOnceTotal === "number" && Number.isFinite(applyOnceTotal) ? applyOnceTotal : 0;
|
|
@@ -22530,9 +21923,9 @@ function createRustModeTransform(deps, options) {
|
|
|
22530
21923
|
const todoCalls = wireDelta ? new Map(state.todoCallSignatures) : new Map;
|
|
22531
21924
|
for (const [offset, message] of todoCandidates.entries()) {
|
|
22532
21925
|
const id = messageIdOf2(message) ?? `index:${todoStart + offset}`;
|
|
22533
|
-
const parts = message.parts?.filter((part) =>
|
|
21926
|
+
const parts = message.parts?.filter((part) => isRecord3(part) && part.type === "tool" && part.tool === "todowrite");
|
|
22534
21927
|
if (parts?.length) {
|
|
22535
|
-
todoCalls.set(id,
|
|
21928
|
+
todoCalls.set(id, createHash12("sha256").update(JSON.stringify(parts)).digest("hex"));
|
|
22536
21929
|
} else {
|
|
22537
21930
|
todoCalls.delete(id);
|
|
22538
21931
|
}
|
|
@@ -22703,7 +22096,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22703
22096
|
logStage(sessionId, "wireBuild", wireBuildStartedAt, timings, wireDelta ? `mode=tail_delta input=${encodedInput.length}` : "mode=full");
|
|
22704
22097
|
const sendTransformSeries = async (payload, detail = "") => {
|
|
22705
22098
|
const pagingStartedAt = performance.now();
|
|
22706
|
-
const fullWire = !
|
|
22099
|
+
const fullWire = !isRecord3(payload.tail_delta);
|
|
22707
22100
|
const pages = buildPagedModuleTransformPayloads(payload, options.modulePageMaxBytes, true);
|
|
22708
22101
|
timings.paging += performance.now() - pagingStartedAt;
|
|
22709
22102
|
const seedMessageCount = Array.isArray(payload.input) ? payload.input.length : Array.isArray(payload.messages) ? payload.messages.length : 0;
|
|
@@ -22761,6 +22154,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22761
22154
|
}
|
|
22762
22155
|
if (!response)
|
|
22763
22156
|
throw new Error("rust module returned no transform response");
|
|
22157
|
+
state.transformInProgressSinceMs = null;
|
|
22764
22158
|
return { response };
|
|
22765
22159
|
};
|
|
22766
22160
|
let transformSeriesRestarted = false;
|
|
@@ -22787,7 +22181,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22787
22181
|
body: { method: "session.flush", v: 1, session_id: sessionId },
|
|
22788
22182
|
timeoutMs: options.moduleTimeoutMs
|
|
22789
22183
|
});
|
|
22790
|
-
if (!
|
|
22184
|
+
if (!isRecord3(flushed) || flushed.ok !== true)
|
|
22791
22185
|
throw new RustTransformProtocolError("rust marker admission recovery: module did not acknowledge rebuilding the new cut");
|
|
22792
22186
|
}
|
|
22793
22187
|
let response = await sendTransformSeriesWithSingleRestart(body);
|
|
@@ -22920,6 +22314,20 @@ function createRustModeTransform(deps, options) {
|
|
|
22920
22314
|
if (moduleDecisionBusts && decisionUpper === "SOFT+") {
|
|
22921
22315
|
throw new RustTransformProtocolError("rust transform wire invariant failed: SOFT+ cannot permit a prefix bust");
|
|
22922
22316
|
}
|
|
22317
|
+
const signedThinkingReset = moduleDecisionBusts && response.signed_thinking_reset === true;
|
|
22318
|
+
if (signedThinkingReset) {
|
|
22319
|
+
const fenced = findReasoningBearingAssistantIds(messages);
|
|
22320
|
+
let recorded = false;
|
|
22321
|
+
try {
|
|
22322
|
+
recorded = addMergedReasoningStrippedIds(deps.db, sessionId, fenced.map(thinkingBindingRecoveryFrozenId));
|
|
22323
|
+
} catch (error) {
|
|
22324
|
+
sessionLog2(sessionId, "signed thinking reset fence: persistence threw:", error);
|
|
22325
|
+
}
|
|
22326
|
+
if (!recorded) {
|
|
22327
|
+
throw new EmergencyFailClosedError(SIGNED_THINKING_RESET_FENCE_FAILED);
|
|
22328
|
+
}
|
|
22329
|
+
sessionLog2(sessionId, `signed thinking reset fence: ${fenced.length} assistant(s) [${fenced.join(",")}]`);
|
|
22330
|
+
}
|
|
22923
22331
|
const cacheBustingPass = moduleDecisionBusts;
|
|
22924
22332
|
let frozenReplayReleased = false;
|
|
22925
22333
|
if (markerAdmissionRecovery && !moduleDecisionBusts)
|
|
@@ -22933,7 +22341,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22933
22341
|
timings.todoUnprobedBust += 1;
|
|
22934
22342
|
sessionLog2(sessionId, `todo_permission_probe_miss decision=${decisionUpper} reason=${response.materialize_reason ?? "unknown"} verdict_stale_ok=false`);
|
|
22935
22343
|
}
|
|
22936
|
-
const deferredFirstDivergence =
|
|
22344
|
+
const deferredFirstDivergence = isRecord3(response.first_divergence) ? response.first_divergence : undefined;
|
|
22937
22345
|
const deferredFrozenPrefixDivergence = !cacheBustingPass && [deferredFirstDivergence?.block_id_old, deferredFirstDivergence?.block_id_new].some((blockId) => blockId === "mc_m0#0" || blockId === "mc_m1#0");
|
|
22938
22346
|
if (deferredFrozenPrefixDivergence) {
|
|
22939
22347
|
state.lkgRepresentationFrozen = true;
|
|
@@ -22943,7 +22351,6 @@ function createRustModeTransform(deps, options) {
|
|
|
22943
22351
|
const materializedBoundary = materializedCompactionBoundary(response, moduleDecisionBusts);
|
|
22944
22352
|
let thinkingBindingRecovery = null;
|
|
22945
22353
|
let frozenHealthyPassesAfterApply = null;
|
|
22946
|
-
let frozenReleaseReason = null;
|
|
22947
22354
|
const applyStartedAt = performance.now();
|
|
22948
22355
|
try {
|
|
22949
22356
|
const moduleMessages = applyNativeMessagesVerbatim({ messages: [] }, response, previousWireCache?.nativeOutput ? {
|
|
@@ -23092,6 +22499,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23092
22499
|
cacheBustingPass: moduleDecisionBusts,
|
|
23093
22500
|
prefixPermissionSupported: permissionSupported,
|
|
23094
22501
|
moduleReasoningTrimOnly: response.reasoning_trim_only === true,
|
|
22502
|
+
moduleSignedThinkingReset: response.signed_thinking_reset === true,
|
|
23095
22503
|
...permissionSupported && (passStartedFrozen || frozenReleaseReason || coldStartLastServed) ? { frozenReleaseLastServed } : {},
|
|
23096
22504
|
trailingBlankSourceDecisions,
|
|
23097
22505
|
trailingBlankNewestAssistantId: typeof trailingBlankNewestAssistantId === "string" ? trailingBlankNewestAssistantId : undefined,
|
|
@@ -23126,7 +22534,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23126
22534
|
agentName: deps.getNotificationParams?.(sessionId)?.agent,
|
|
23127
22535
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
23128
22536
|
}, resolvedWindowGeometry?.usableHard ?? resolvedContextLimit);
|
|
23129
|
-
const refusal = outgoingContextRefusal(servedFinalWireEstimate, resolvedWindowGeometry?.usableHard ?? resolvedContextLimit, protectedToolTokenCount(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools, resolveDecisionCalibration(model?.providerID, model?.modelID)));
|
|
22537
|
+
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);
|
|
23130
22538
|
if (refusal) {
|
|
23131
22539
|
if (cacheBustingPass) {
|
|
23132
22540
|
dropSlot(sessionId, "lkg_over_limit_replacement");
|
|
@@ -23149,6 +22557,8 @@ function createRustModeTransform(deps, options) {
|
|
|
23149
22557
|
}
|
|
23150
22558
|
const lkgSnapshotStartedAt = performance.now();
|
|
23151
22559
|
const synchronousReplacement = shouldAdoptModuleAfterFreeze(moduleDecisionBusts, frozenReplayReleased) || !permissionSupported;
|
|
22560
|
+
if (signedThinkingReset)
|
|
22561
|
+
options.afterSignedThinkingResetFenceForTests?.(sessionId);
|
|
23152
22562
|
if (synchronousReplacement && !markerDefinitelyNoCut) {
|
|
23153
22563
|
dropSlot(sessionId, "lkg_cache_bust_pending_capture");
|
|
23154
22564
|
state.lkgAcceptedCapture = undefined;
|
|
@@ -23157,6 +22567,11 @@ function createRustModeTransform(deps, options) {
|
|
|
23157
22567
|
let captureMode = "async";
|
|
23158
22568
|
if (capturePlan)
|
|
23159
22569
|
state.lkgLastServedCaptureSequence = capturePlan.captureSequence;
|
|
22570
|
+
const endRecoveryAfterResetCapture = () => {
|
|
22571
|
+
if (signedThinkingReset && thinkingRecovery.restore) {
|
|
22572
|
+
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
22573
|
+
}
|
|
22574
|
+
};
|
|
23160
22575
|
const captureFailed = (mode, error) => {
|
|
23161
22576
|
if (states.get(sessionId) !== state || capturePlan && capturePlan.captureSequence !== state.lkgCaptureSequence) {
|
|
23162
22577
|
return;
|
|
@@ -23177,6 +22592,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23177
22592
|
captureMode = synchronousReplacement ? "sync_priced" : "sync_recovery";
|
|
23178
22593
|
try {
|
|
23179
22594
|
commitRustCapture(state, capturePlan, synchronousReplacement);
|
|
22595
|
+
endRecoveryAfterResetCapture();
|
|
23180
22596
|
} catch (error) {
|
|
23181
22597
|
captureFailed("sync", error);
|
|
23182
22598
|
if (synchronousReplacement)
|
|
@@ -23188,6 +22604,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23188
22604
|
const asyncStartedAt = performance.now();
|
|
23189
22605
|
try {
|
|
23190
22606
|
const result = commitRustCapture(state, capturePlan);
|
|
22607
|
+
endRecoveryAfterResetCapture();
|
|
23191
22608
|
logTransformTiming(sessionId, "rust.lkg_snapshot_async", asyncStartedAt, `result=${result} row_version=${capturePlan.rowVersion}`);
|
|
23192
22609
|
} catch (error) {
|
|
23193
22610
|
captureFailed("async", error);
|
|
@@ -23286,7 +22703,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23286
22703
|
state.todoProbeIdentity = todoProbeIdentity;
|
|
23287
22704
|
state.todoBustIdentity = todoBustIdentity;
|
|
23288
22705
|
}
|
|
23289
|
-
state.todoProbeNextPass = response.reconcile_pending === true ||
|
|
22706
|
+
state.todoProbeNextPass = response.reconcile_pending === true || isRecord3(response.historian) && response.historian.fired === true;
|
|
23290
22707
|
state.lastAppliedAtMs = requestObservedAtMs;
|
|
23291
22708
|
heapHolder.wireCaches.set(sessionId, pendingWireCache);
|
|
23292
22709
|
timings.bookkeeping += performance.now() - bookkeepingStartedAt - timings.delivery;
|
|
@@ -23410,6 +22827,11 @@ function createRustModeTransform(deps, options) {
|
|
|
23410
22827
|
sessionLog2(sessionId, "mc_rust_emergency_refusal before_lkg");
|
|
23411
22828
|
markFailure(sessionId, state, error);
|
|
23412
22829
|
finishPass(false, false);
|
|
22830
|
+
if (moduleFailureCode(error) === TRANSFORM_PAGE_IN_PROGRESS_CODE && inProgressRunWithinBound(state)) {
|
|
22831
|
+
throw new EmergencyFailClosedError(ENGINE_BUSY_USER_MESSAGE, {
|
|
22832
|
+
cause: error
|
|
22833
|
+
});
|
|
22834
|
+
}
|
|
23413
22835
|
const refusedUser = newestUserMessage(messages);
|
|
23414
22836
|
const refusedUserMessageId = refusedUser ? messageIdOf2(refusedUser) : null;
|
|
23415
22837
|
if (refusedUserMessageId) {
|
|
@@ -23978,6 +23400,11 @@ function createTransform(deps) {
|
|
|
23978
23400
|
const finalWireUsage = createFinalWireUsageTracker();
|
|
23979
23401
|
const host = resolveTransformHostSeams(deps);
|
|
23980
23402
|
const loadedSessions = new Set;
|
|
23403
|
+
const prefixHoldLogTurnIds = new Map;
|
|
23404
|
+
const thinkingFitRetries = new Set;
|
|
23405
|
+
const clearSessionLogState = (sessionId) => {
|
|
23406
|
+
prefixHoldLogTurnIds.delete(sessionId);
|
|
23407
|
+
};
|
|
23981
23408
|
const unmanagedOverWindowSessions = new Set;
|
|
23982
23409
|
const rustModeTransform = deps.transformMode === "rust" && deps.rustModeModuleClient ? createRustModeTransform(deps, {
|
|
23983
23410
|
moduleClient: deps.rustModeModuleClient,
|
|
@@ -24007,6 +23434,7 @@ function createTransform(deps) {
|
|
|
24007
23434
|
const startTime = performance.now();
|
|
24008
23435
|
const historianRun = deps.resolveHistorianRun?.();
|
|
24009
23436
|
const messages = output.messages;
|
|
23437
|
+
const originalForThinkingFit = messages.some((message) => message.parts.some((part) => isRecord(part) && ["reasoning", "thinking", "redacted_thinking"].includes(String(part.type)))) ? structuredClone(messages) : null;
|
|
24010
23438
|
const passOutcome = createPassOutcome();
|
|
24011
23439
|
const tSessionId = performance.now();
|
|
24012
23440
|
const sessionId = findSessionId(messages);
|
|
@@ -24194,16 +23622,15 @@ function createTransform(deps) {
|
|
|
24194
23622
|
deps.pendingMaterializationSessions?.add(sessionId);
|
|
24195
23623
|
let restoreLatestTurnOriginals;
|
|
24196
23624
|
let activeThinkingTurn = hasActiveAnthropicThinkingTurn(messages, activeThinkingModel?.providerID, activeThinkingModel?.modelID);
|
|
24197
|
-
|
|
23625
|
+
const unresolvedDirectoryHold = sessionDirectoryFellBack && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null && (() => {
|
|
24198
23626
|
try {
|
|
24199
23627
|
return hasRecordedSessionProjectIdentity(db, sessionId);
|
|
24200
23628
|
} catch {
|
|
24201
23629
|
return true;
|
|
24202
23630
|
}
|
|
24203
23631
|
})();
|
|
24204
|
-
|
|
24205
|
-
|
|
24206
|
-
}
|
|
23632
|
+
let activeThinkingPrefixHold = activeThinkingTurn && isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID);
|
|
23633
|
+
let freezeM0M1 = unresolvedDirectoryHold || activeThinkingPrefixHold;
|
|
24207
23634
|
const compartmentDirectory = sessionDirectory;
|
|
24208
23635
|
const historianRunnable = deps.historianRunnable !== false;
|
|
24209
23636
|
const canRunCompartments = fullFeatureMode && !compactionOff && historianRunnable && (deps.client !== undefined || deps.hiddenCompletionExecutor !== undefined) && compartmentDirectory.length > 0;
|
|
@@ -24331,7 +23758,13 @@ function createTransform(deps) {
|
|
|
24331
23758
|
}
|
|
24332
23759
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
24333
23760
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
24334
|
-
|
|
23761
|
+
activeThinkingPrefixHold ||= activeThinkingTurn && isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID);
|
|
23762
|
+
freezeM0M1 ||= activeThinkingPrefixHold;
|
|
23763
|
+
if (freezeM0M1 && prefixHoldLogTurnIds.get(sessionId) !== currentTurnId) {
|
|
23764
|
+
prefixHoldLogTurnIds.set(sessionId, currentTurnId);
|
|
23765
|
+
const reason = activeThinkingPrefixHold ? "active thinking turn (prefix-bound model)" : "session directory unresolved";
|
|
23766
|
+
sessionLog2(sessionId, `m[0]/m[1] frozen: ${reason}; replaying the frozen prefix and deferring any rebuild`);
|
|
23767
|
+
}
|
|
24335
23768
|
const canUseEmptySentinels = modelAcceptsEmptyContent(resolvedProviderID);
|
|
24336
23769
|
const protectedThinkingMessages = activeThinkingTurn || isAnthropicFamilyRoute(resolvedProviderID, modelForBudget?.modelID) ? latestAssistantTurnMessages(messages) : new Set;
|
|
24337
23770
|
const resolvedContextLimit = modelForBudget ? resolveTrustedContextLimit(modelForBudget.providerID, modelForBudget.modelID, {
|
|
@@ -24862,7 +24295,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24862
24295
|
client: deps.client,
|
|
24863
24296
|
activeAgent,
|
|
24864
24297
|
batch,
|
|
24865
|
-
contextUsage,
|
|
24298
|
+
contextUsage: thinkingFitRetries.has(sessionId) ? { ...contextUsage, percentage: Math.max(95, contextUsage.percentage) } : contextUsage,
|
|
24866
24299
|
usableWindow: resolvedContextLimit ?? 0,
|
|
24867
24300
|
schedulerDecision,
|
|
24868
24301
|
schedulerDeferReason,
|
|
@@ -24877,6 +24310,17 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24877
24310
|
compartmentInProgress,
|
|
24878
24311
|
historyRefreshExplicitBeforePrepare,
|
|
24879
24312
|
freezeM0M1,
|
|
24313
|
+
activeThinkingPrefixHold,
|
|
24314
|
+
directoryPrefixHold: unresolvedDirectoryHold,
|
|
24315
|
+
forceSignedRebuildForFit: thinkingFitRetries.has(sessionId),
|
|
24316
|
+
readLastServedMessages: () => {
|
|
24317
|
+
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
24318
|
+
try {
|
|
24319
|
+
return slot ? JSON.parse(slot.jsonPrefix) : null;
|
|
24320
|
+
} catch {
|
|
24321
|
+
return null;
|
|
24322
|
+
}
|
|
24323
|
+
},
|
|
24880
24324
|
deferredHistoryWasPendingAtPassStart,
|
|
24881
24325
|
compartmentInjectionRebuiltFromDb: pendingCompartmentInjection?.rebuiltFromDb === true,
|
|
24882
24326
|
rebuiltHistoryFromInitialPrepare,
|
|
@@ -24961,6 +24405,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24961
24405
|
if (finalWireEstimate) {
|
|
24962
24406
|
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}`);
|
|
24963
24407
|
}
|
|
24408
|
+
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
24409
|
+
if (!thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && originalForThinkingFit && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID)) {
|
|
24410
|
+
thinkingFitRetries.add(sessionId);
|
|
24411
|
+
deps.pendingMaterializationSessions.add(sessionId);
|
|
24412
|
+
messages.splice(0, messages.length, ...originalForThinkingFit);
|
|
24413
|
+
try {
|
|
24414
|
+
await transform({}, output);
|
|
24415
|
+
} finally {
|
|
24416
|
+
thinkingFitRetries.delete(sessionId);
|
|
24417
|
+
}
|
|
24418
|
+
return;
|
|
24419
|
+
}
|
|
24420
|
+
if (thinkingFitRetries.has(sessionId) || postTransformResult.thinkingReleasedForFit)
|
|
24421
|
+
throw contextRefusalError("The request remains over the model window after stripping signed thinking and reclaiming context");
|
|
24422
|
+
}
|
|
24964
24423
|
if (postTransformResult.prefixTrimStatus === "refused") {
|
|
24965
24424
|
const untrimmed = finalWireEstimate ?? estimateFinalWireInputTokens({
|
|
24966
24425
|
messages,
|
|
@@ -25224,10 +24683,12 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25224
24683
|
});
|
|
25225
24684
|
};
|
|
25226
24685
|
return Object.assign(transform, {
|
|
24686
|
+
clearSessionLogState,
|
|
25227
24687
|
invalidateRustWireState(sessionId) {
|
|
25228
24688
|
rustModeTransform?.invalidateWireState(sessionId);
|
|
25229
24689
|
},
|
|
25230
24690
|
async clearRustSession(sessionId) {
|
|
24691
|
+
clearSessionLogState(sessionId);
|
|
25231
24692
|
await rustModeTransform?.clearSession(sessionId);
|
|
25232
24693
|
},
|
|
25233
24694
|
disposeRust() {
|
|
@@ -25445,7 +24906,7 @@ function createRustRefusalRecovery(options) {
|
|
|
25445
24906
|
}
|
|
25446
24907
|
|
|
25447
24908
|
// src/hooks/magic-context/system-prompt-hash.ts
|
|
25448
|
-
import { createHash as
|
|
24909
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
25449
24910
|
var MAGIC_CONTEXT_MARKER = "## Magic Context";
|
|
25450
24911
|
var SYSTEM_PROMPT_GUIDANCE_SEPARATOR = `
|
|
25451
24912
|
|
|
@@ -25545,7 +25006,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
25545
25006
|
}
|
|
25546
25007
|
const stickyDate = stickyDateBySession.get(sessionId);
|
|
25547
25008
|
const stableCandidate = currentDate && stickyDate && currentDate !== stickyDate ? liveSystemContent.replace(DATE_PATTERN_ALL, stickyDate) : liveSystemContent;
|
|
25548
|
-
const stableCandidateHash =
|
|
25009
|
+
const stableCandidateHash = createHash13("md5").update(promptSurfaceHashMaterial(stableCandidate, promptSurface.preset)).digest("hex");
|
|
25549
25010
|
const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
|
|
25550
25011
|
const dateMayAdvance = isCacheBusting || idleCacheExpired || contentOrPresetChanged;
|
|
25551
25012
|
if (currentDate && !stickyDate) {
|
|
@@ -25565,7 +25026,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
25565
25026
|
`);
|
|
25566
25027
|
if (!availability.frozen || !modelKey)
|
|
25567
25028
|
return;
|
|
25568
|
-
const currentHash =
|
|
25029
|
+
const currentHash = createHash13("md5").update(promptSurfaceHashMaterial(systemContent, promptSurface.preset)).digest("hex");
|
|
25569
25030
|
if (!sessionMetaEarly) {
|
|
25570
25031
|
return;
|
|
25571
25032
|
}
|
|
@@ -26197,8 +25658,8 @@ function resolveCtxExpandMode(args, domain) {
|
|
|
26197
25658
|
}
|
|
26198
25659
|
|
|
26199
25660
|
// src/tools/ctx-expand/render.ts
|
|
26200
|
-
import { createHash as
|
|
26201
|
-
function
|
|
25661
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
25662
|
+
function isRecord4(value) {
|
|
26202
25663
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
26203
25664
|
}
|
|
26204
25665
|
function roleLabel(role) {
|
|
@@ -26210,7 +25671,7 @@ function roleLabel(role) {
|
|
|
26210
25671
|
}
|
|
26211
25672
|
function verboseRoleLabel(msg) {
|
|
26212
25673
|
if (msg.role === "user" && msg.parts.length > 0 && msg.parts.every((part) => {
|
|
26213
|
-
if (!
|
|
25674
|
+
if (!isRecord4(part))
|
|
26214
25675
|
return false;
|
|
26215
25676
|
if (part.type === "tool_result")
|
|
26216
25677
|
return true;
|
|
@@ -26238,15 +25699,15 @@ function keyArg(input) {
|
|
|
26238
25699
|
function asToolPart(part) {
|
|
26239
25700
|
const type = typeof part.type === "string" ? part.type : "";
|
|
26240
25701
|
if (type === "tool") {
|
|
26241
|
-
const state =
|
|
25702
|
+
const state = isRecord4(part.state) ? part.state : null;
|
|
26242
25703
|
const output = state && typeof state.output === "string" ? state.output : state && state.output != null ? JSON.stringify(state.output) : null;
|
|
26243
|
-
const metadata = state &&
|
|
25704
|
+
const metadata = state && isRecord4(state.metadata) ? state.metadata : null;
|
|
26244
25705
|
const title = state && typeof state.title === "string" && state.title || metadata && typeof metadata.title === "string" && metadata.title || null;
|
|
26245
25706
|
return {
|
|
26246
25707
|
name: typeof part.tool === "string" ? part.tool : "tool",
|
|
26247
25708
|
callId: typeof part.callID === "string" ? part.callID : "",
|
|
26248
25709
|
title,
|
|
26249
|
-
input: state &&
|
|
25710
|
+
input: state && isRecord4(state.input) ? state.input : null,
|
|
26250
25711
|
output
|
|
26251
25712
|
};
|
|
26252
25713
|
}
|
|
@@ -26255,7 +25716,7 @@ function asToolPart(part) {
|
|
|
26255
25716
|
name: typeof part.name === "string" ? part.name : "tool",
|
|
26256
25717
|
callId: typeof part.id === "string" ? part.id : "",
|
|
26257
25718
|
title: null,
|
|
26258
|
-
input:
|
|
25719
|
+
input: isRecord4(part.input) ? part.input : null,
|
|
26259
25720
|
output: null
|
|
26260
25721
|
};
|
|
26261
25722
|
}
|
|
@@ -26284,7 +25745,7 @@ function reasoningOf(part) {
|
|
|
26284
25745
|
return null;
|
|
26285
25746
|
}
|
|
26286
25747
|
function renderPartPreview(part, expandTools) {
|
|
26287
|
-
if (!
|
|
25748
|
+
if (!isRecord4(part))
|
|
26288
25749
|
return null;
|
|
26289
25750
|
const expansion = expandToolPart(part, expandTools, true);
|
|
26290
25751
|
if (expansion !== null)
|
|
@@ -26311,7 +25772,7 @@ function renderPartPreview(part, expandTools) {
|
|
|
26311
25772
|
return ` • [${type}]`;
|
|
26312
25773
|
}
|
|
26313
25774
|
function renderPartFull(part) {
|
|
26314
|
-
if (!
|
|
25775
|
+
if (!isRecord4(part))
|
|
26315
25776
|
return null;
|
|
26316
25777
|
const text = textOf(part);
|
|
26317
25778
|
if (text !== null) {
|
|
@@ -26398,11 +25859,11 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
26398
25859
|
const message = readRawSessionMessageById2(sessionId, owner);
|
|
26399
25860
|
if (!message)
|
|
26400
25861
|
return `Tag ${number}'s original tool owner is no longer in stored history.`;
|
|
26401
|
-
const parts = message?.parts.filter((part) =>
|
|
26402
|
-
if (!parts.some((part) =>
|
|
25862
|
+
const parts = message?.parts.filter((part) => isRecord4(part) && asToolPart(part)?.callId === tag.messageId) ?? [];
|
|
25863
|
+
if (!parts.some((part) => isRecord4(part) && asToolPart(part)?.output !== null)) {
|
|
26403
25864
|
visitRawSessionMessages2(sessionId, message.ordinal + 1, Number.MAX_SAFE_INTEGER, (candidate) => {
|
|
26404
|
-
const matching = candidate.parts.filter((part) =>
|
|
26405
|
-
if (matching.some((part) =>
|
|
25865
|
+
const matching = candidate.parts.filter((part) => isRecord4(part) && asToolPart(part)?.callId === tag.messageId);
|
|
25866
|
+
if (matching.some((part) => isRecord4(part) && part.type === "tool_use"))
|
|
26406
25867
|
return false;
|
|
26407
25868
|
parts.push(...matching);
|
|
26408
25869
|
return matching.length === 0;
|
|
@@ -26419,9 +25880,9 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
26419
25880
|
if (!message)
|
|
26420
25881
|
return `Tag ${number}'s original text is no longer in stored history.`;
|
|
26421
25882
|
const index = scoped ? Number(scoped[2]) : 0;
|
|
26422
|
-
const piText = message.parts.filter((part) =>
|
|
25883
|
+
const piText = message.parts.filter((part) => isRecord4(part) && part.type === "text");
|
|
26423
25884
|
const part = message.parts[index];
|
|
26424
|
-
const matching = derived ? piText.filter((part) =>
|
|
25885
|
+
const matching = derived ? piText.filter((part) => isRecord4(part) && typeof part.text === "string" && createHash14("sha256").update(part.text).digest("hex") === derived[3]) : [];
|
|
26425
25886
|
const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" ? piText[index] : part;
|
|
26426
25887
|
return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
|
|
26427
25888
|
}
|
|
@@ -27202,7 +26663,7 @@ import { isAbsolute as isAbsolute2 } from "node:path";
|
|
|
27202
26663
|
// ../retina-local-fs/src/path-fence.ts
|
|
27203
26664
|
import { lstat as lstat2, readlink, realpath as realpath2 } from "node:fs/promises";
|
|
27204
26665
|
import { homedir } from "node:os";
|
|
27205
|
-
import { basename, dirname as dirname2, isAbsolute, join as
|
|
26666
|
+
import { basename, dirname as dirname2, isAbsolute, join as join6, relative, resolve, sep } from "node:path";
|
|
27206
26667
|
|
|
27207
26668
|
// ../retina-local-fs/src/errors.ts
|
|
27208
26669
|
class ProviderError extends Error {
|
|
@@ -27217,7 +26678,7 @@ class ProviderError extends Error {
|
|
|
27217
26678
|
// ../retina-local-fs/src/path-fence.ts
|
|
27218
26679
|
async function resolveAndFenceProviderPath(configuredPath, options) {
|
|
27219
26680
|
const { home, dataDirectory, aliases } = await resolveFenceRoots(options);
|
|
27220
|
-
const expanded = configuredPath.startsWith("~/") ?
|
|
26681
|
+
const expanded = configuredPath.startsWith("~/") ? join6(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
|
|
27221
26682
|
const absolute = isAbsolute(expanded) ? resolve(expanded) : resolve(options.cwd ?? process.cwd(), expanded);
|
|
27222
26683
|
const canonical = await canonicalPath(absolute, options.allowMissing);
|
|
27223
26684
|
if (fenceCandidates(canonical, aliases).some((candidate) => isFencedPath(candidate, home, dataDirectory))) {
|
|
@@ -27234,13 +26695,13 @@ async function resolveFenceRoots(options) {
|
|
|
27234
26695
|
} catch (error) {
|
|
27235
26696
|
throw fsError(configuredHomePath, error);
|
|
27236
26697
|
}
|
|
27237
|
-
const configuredDataDirectory = resolve(options.dataDirectory ?? process.env.XDG_DATA_HOME ??
|
|
26698
|
+
const configuredDataDirectory = resolve(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join6(home, ".local", "share"));
|
|
27238
26699
|
const dataDirectory = await canonicalPath(configuredDataDirectory, true);
|
|
27239
26700
|
const aliases = [];
|
|
27240
|
-
const logicalCortexkit =
|
|
26701
|
+
const logicalCortexkit = join6(dataDirectory, "cortexkit");
|
|
27241
26702
|
for (const logical of [
|
|
27242
26703
|
logicalCortexkit,
|
|
27243
|
-
...FENCED_CORTEXKIT_ROOTS.map((root) =>
|
|
26704
|
+
...FENCED_CORTEXKIT_ROOTS.map((root) => join6(logicalCortexkit, root))
|
|
27244
26705
|
]) {
|
|
27245
26706
|
const canonical = await canonicalPath(logical, true);
|
|
27246
26707
|
if (canonical !== logical)
|
|
@@ -27254,7 +26715,7 @@ function fenceCandidates(canonical, aliases) {
|
|
|
27254
26715
|
const relativeToAlias = relative(alias.canonical, canonical);
|
|
27255
26716
|
const inside = relativeToAlias === "" || relativeToAlias !== ".." && !relativeToAlias.startsWith(`..${sep}`) && !isAbsolute(relativeToAlias);
|
|
27256
26717
|
if (inside)
|
|
27257
|
-
candidates.push(
|
|
26718
|
+
candidates.push(join6(alias.logical, relativeToAlias));
|
|
27258
26719
|
}
|
|
27259
26720
|
return candidates;
|
|
27260
26721
|
}
|
|
@@ -27273,7 +26734,7 @@ async function canonicalPath(path, allowMissing) {
|
|
|
27273
26734
|
if (metadata.isSymbolicLink()) {
|
|
27274
26735
|
const target = await readlink(candidate);
|
|
27275
26736
|
const resolvedTarget = resolve(dirname2(candidate), target);
|
|
27276
|
-
return canonicalPath(
|
|
26737
|
+
return canonicalPath(join6(resolvedTarget, ...suffix), true);
|
|
27277
26738
|
}
|
|
27278
26739
|
} catch (candidateError) {
|
|
27279
26740
|
if (!isMissingError(candidateError)) {
|
|
@@ -27287,7 +26748,7 @@ async function canonicalPath(path, allowMissing) {
|
|
|
27287
26748
|
suffix.unshift(basename(candidate));
|
|
27288
26749
|
candidate = parent;
|
|
27289
26750
|
try {
|
|
27290
|
-
return
|
|
26751
|
+
return join6(await realpath2(candidate), ...suffix);
|
|
27291
26752
|
} catch (parentError) {
|
|
27292
26753
|
if (!isMissingError(parentError)) {
|
|
27293
26754
|
throw fsError(path, parentError);
|
|
@@ -27296,8 +26757,8 @@ async function canonicalPath(path, allowMissing) {
|
|
|
27296
26757
|
}
|
|
27297
26758
|
}
|
|
27298
26759
|
}
|
|
27299
|
-
function isFencedPath(canonicalPath, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ??
|
|
27300
|
-
const cortexkitRoot =
|
|
26760
|
+
function isFencedPath(canonicalPath, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join6(resolve(homeDirectory), ".local", "share")) {
|
|
26761
|
+
const cortexkitRoot = join6(resolve(dataDirectory), "cortexkit");
|
|
27301
26762
|
const relativeToCortexkit = relative(cortexkitRoot, canonicalPath);
|
|
27302
26763
|
const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute(relativeToCortexkit);
|
|
27303
26764
|
const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
|
|
@@ -27969,7 +27430,7 @@ function ctxReduceSelfStampMessage(tagNumber) {
|
|
|
27969
27430
|
return CTX_REDUCE_SELF_STAMP_MESSAGE_TEMPLATE.replace("§N§", `§${tagNumber}§`);
|
|
27970
27431
|
}
|
|
27971
27432
|
// src/tools/ctx-reduce/tools.ts
|
|
27972
|
-
import { createHash as
|
|
27433
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
27973
27434
|
import { tool as tool4 } from "@opencode-ai/plugin";
|
|
27974
27435
|
|
|
27975
27436
|
// src/features/magic-context/range-parser.ts
|
|
@@ -28039,11 +27500,11 @@ function createCtxReduceTool(deps) {
|
|
|
28039
27500
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
28040
27501
|
if (Buffer.byteLength(stableId) <= 128)
|
|
28041
27502
|
return stableId;
|
|
28042
|
-
return `oc-${
|
|
27503
|
+
return `oc-${createHash15("sha256").update(stableId).digest("hex")}`;
|
|
28043
27504
|
}
|
|
28044
27505
|
fallbackCommandSequence += 1;
|
|
28045
27506
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
28046
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
27507
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash15("sha256").update(monotonicId).digest("hex")}`;
|
|
28047
27508
|
};
|
|
28048
27509
|
return tool4({
|
|
28049
27510
|
description: CTX_REDUCE_DESCRIPTION,
|
|
@@ -28126,7 +27587,7 @@ function createCtxReduceTool(deps) {
|
|
|
28126
27587
|
...protectedSet,
|
|
28127
27588
|
...protectedToolTagNumbers(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools)
|
|
28128
27589
|
]);
|
|
28129
|
-
const inertWhitespaceTagNumbers = new Set(
|
|
27590
|
+
const inertWhitespaceTagNumbers = new Set(getInertWhitespaceAssistantTagsByNumbers2(deps.db, sessionId, dropIds).map((tag) => tag.tagNumber));
|
|
28130
27591
|
const inertDropIds = [
|
|
28131
27592
|
...new Set(dropIds.filter((id) => inertWhitespaceTagNumbers.has(id)))
|
|
28132
27593
|
];
|
|
@@ -28370,6 +27831,7 @@ function createCtxSearchTool(deps) {
|
|
|
28370
27831
|
diagnostics,
|
|
28371
27832
|
gitRepositoryAvailable: typeof toolContext.directory === "string" ? directoryHasGitMetadata(toolContext.directory) : undefined,
|
|
28372
27833
|
explicitSearch: true,
|
|
27834
|
+
rerankConnectionFile: deps.rerankConnectionFile,
|
|
28373
27835
|
searchMessageHistory: (request) => searchMessageHistoryOffThread(deps.db, request),
|
|
28374
27836
|
...dateRange
|
|
28375
27837
|
});
|
|
@@ -28736,4 +28198,118 @@ function json(body, status = 200) {
|
|
|
28736
28198
|
});
|
|
28737
28199
|
}
|
|
28738
28200
|
|
|
28739
|
-
|
|
28201
|
+
// src/shared/models-dev-temperature.ts
|
|
28202
|
+
import { readFileSync as readFileSync7, statSync as statSync4 } from "node:fs";
|
|
28203
|
+
import { homedir as homedir2 } from "node:os";
|
|
28204
|
+
import { join as join7 } from "node:path";
|
|
28205
|
+
var CATALOG_PROVIDER_ALIASES = {
|
|
28206
|
+
"google-antigravity": "google",
|
|
28207
|
+
"opencode-zen": "opencode"
|
|
28208
|
+
};
|
|
28209
|
+
var ANTIGRAVITY_MODEL_PREFIX = "antigravity-";
|
|
28210
|
+
var cached;
|
|
28211
|
+
function modelsDevCatalogPath(env = process.env) {
|
|
28212
|
+
if (env.OPENCODE_MODELS_PATH)
|
|
28213
|
+
return env.OPENCODE_MODELS_PATH;
|
|
28214
|
+
return join7(env.XDG_CACHE_HOME || join7(homedir2(), ".cache"), "opencode", "models.json");
|
|
28215
|
+
}
|
|
28216
|
+
function buildIndex(raw) {
|
|
28217
|
+
const index = new Map;
|
|
28218
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
28219
|
+
return index;
|
|
28220
|
+
for (const [providerID, provider] of Object.entries(raw)) {
|
|
28221
|
+
const models = provider?.models;
|
|
28222
|
+
if (!models || typeof models !== "object")
|
|
28223
|
+
continue;
|
|
28224
|
+
for (const [modelID, model] of Object.entries(models)) {
|
|
28225
|
+
const temperature = model?.temperature;
|
|
28226
|
+
if (typeof temperature === "boolean")
|
|
28227
|
+
index.set(`${providerID}/${modelID}`, temperature);
|
|
28228
|
+
}
|
|
28229
|
+
}
|
|
28230
|
+
return index;
|
|
28231
|
+
}
|
|
28232
|
+
function loadIndex() {
|
|
28233
|
+
const path = modelsDevCatalogPath();
|
|
28234
|
+
try {
|
|
28235
|
+
const stat = statSync4(path);
|
|
28236
|
+
if (cached?.path === path && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
|
|
28237
|
+
return cached.index;
|
|
28238
|
+
const index = buildIndex(JSON.parse(readFileSync7(path, "utf8")));
|
|
28239
|
+
cached = { path, mtimeMs: stat.mtimeMs, size: stat.size, index };
|
|
28240
|
+
return index;
|
|
28241
|
+
} catch {
|
|
28242
|
+
return;
|
|
28243
|
+
}
|
|
28244
|
+
}
|
|
28245
|
+
function catalogCandidates(providerID, modelID) {
|
|
28246
|
+
const provider = Object.hasOwn(CATALOG_PROVIDER_ALIASES, providerID) ? CATALOG_PROVIDER_ALIASES[providerID] : providerID;
|
|
28247
|
+
const candidates = [`${provider}/${modelID}`];
|
|
28248
|
+
if (provider === "google" && modelID.startsWith(ANTIGRAVITY_MODEL_PREFIX))
|
|
28249
|
+
candidates.push(`google/${modelID.slice(ANTIGRAVITY_MODEL_PREFIX.length)}`);
|
|
28250
|
+
return candidates;
|
|
28251
|
+
}
|
|
28252
|
+
function catalogTemperature(model) {
|
|
28253
|
+
const slash = model.indexOf("/");
|
|
28254
|
+
if (slash <= 0 || slash === model.length - 1)
|
|
28255
|
+
return;
|
|
28256
|
+
const index = loadIndex();
|
|
28257
|
+
if (!index)
|
|
28258
|
+
return;
|
|
28259
|
+
for (const entry of catalogCandidates(model.slice(0, slash), model.slice(slash + 1))) {
|
|
28260
|
+
const temperature = index.get(entry);
|
|
28261
|
+
if (temperature !== undefined)
|
|
28262
|
+
return { temperature, entry };
|
|
28263
|
+
}
|
|
28264
|
+
return;
|
|
28265
|
+
}
|
|
28266
|
+
|
|
28267
|
+
// src/shared/subagent-temperature.ts
|
|
28268
|
+
var loggedDecisions = new Set;
|
|
28269
|
+
function temperatureCapability(metadata) {
|
|
28270
|
+
if (!metadata || typeof metadata !== "object")
|
|
28271
|
+
return;
|
|
28272
|
+
const model = metadata;
|
|
28273
|
+
const supported = model.capabilities?.temperature ?? model.temperature ?? model.compat?.supportsTemperature ?? model.compat?.supportsSamplingParams;
|
|
28274
|
+
return typeof supported === "boolean" ? supported : undefined;
|
|
28275
|
+
}
|
|
28276
|
+
function resolveTemperatureCapability(model, metadata) {
|
|
28277
|
+
const host = temperatureCapability(metadata);
|
|
28278
|
+
if (host !== undefined)
|
|
28279
|
+
return { supported: host, source: "host" };
|
|
28280
|
+
const catalog = catalogTemperature(model);
|
|
28281
|
+
if (catalog)
|
|
28282
|
+
return { supported: catalog.temperature, source: "catalog", entry: catalog.entry };
|
|
28283
|
+
return { supported: undefined, source: "none" };
|
|
28284
|
+
}
|
|
28285
|
+
function describeTemperatureDecision(model, decision) {
|
|
28286
|
+
const verdict = decision.supported === true ? "sent" : "omitted";
|
|
28287
|
+
const answer = decision.supported === true ? "yes" : "no";
|
|
28288
|
+
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";
|
|
28289
|
+
return `Subagent temperature ${verdict} for ${model}: ${reason}`;
|
|
28290
|
+
}
|
|
28291
|
+
function logTemperatureDecision(model, decision, log) {
|
|
28292
|
+
const key = `${model}\x00${decision.source}\x00${decision.supported}\x00${decision.entry ?? ""}`;
|
|
28293
|
+
if (loggedDecisions.has(key))
|
|
28294
|
+
return;
|
|
28295
|
+
loggedDecisions.add(key);
|
|
28296
|
+
log(describeTemperatureDecision(model, decision), decision);
|
|
28297
|
+
}
|
|
28298
|
+
function subagentTemperature(model, metadata, temperature, log) {
|
|
28299
|
+
if (temperature === undefined)
|
|
28300
|
+
return;
|
|
28301
|
+
const decision = resolveTemperatureCapability(model, metadata);
|
|
28302
|
+
logTemperatureDecision(model, decision, log);
|
|
28303
|
+
return decision.supported === true ? temperature : undefined;
|
|
28304
|
+
}
|
|
28305
|
+
function applyHiddenSubagentTemperature(input, output, log) {
|
|
28306
|
+
if (!/^(?:historian(?:-|$)|dreamer(?:-|$)|smart-note-compiler$)/.test(input.agent))
|
|
28307
|
+
return;
|
|
28308
|
+
const temperature = subagentTemperature(`${input.model?.providerID ?? "unknown"}/${input.model?.id ?? "unknown"}`, input.model, output.temperature, (message) => log(message));
|
|
28309
|
+
if (temperature === undefined)
|
|
28310
|
+
delete output.temperature;
|
|
28311
|
+
else
|
|
28312
|
+
output.temperature = temperature;
|
|
28313
|
+
}
|
|
28314
|
+
|
|
28315
|
+
export { openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, createDbLkgPersistence, startDreamScheduleTimer, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, createScheduler, describeStorageUnavailability, scheduleClearAndReindex, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, maybeDeliverChannel2, armLatestThinkingRecovery, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };
|