@cortexkit/opencode-magic-context 0.49.86 → 0.49.87
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 +13 -7
- package/dist/chunk-embedding-write-worker.js +4 -4
- package/dist/{compartment-chunk-embedding-ymc9mtwv.js → compartment-chunk-embedding-fey2bsyf.js} +3 -1
- package/dist/{conflict-warning-hook-a0wrnzch.js → conflict-warning-hook-kbq6ppjf.js} +2 -2
- package/dist/{context-xesm7rj3.js → context-gnk68pyy.js} +126 -46
- package/dist/{embedding-backfill-v6sw58m8.js → embedding-backfill-9khxv6a9.js} +4 -4
- package/dist/{embedding-cache-mgyr73ef.js → embedding-cache-zn4r1c31.js} +5 -1
- package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -0
- package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/token-budget.d.ts +8 -3
- package/dist/features/magic-context/dreamer/token-budget.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-cache.d.ts +7 -0
- package/dist/features/magic-context/memory/embedding-cache.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts +6 -0
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/tool-definition-tokens.d.ts +2 -0
- package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-worker-probe.fixture.d.ts +2 -0
- package/dist/hooks/magic-context/auto-search-worker-probe.fixture.d.ts.map +1 -0
- package/dist/hooks/magic-context/dropped-input-guard.d.ts.map +1 -1
- package/dist/hooks/magic-context/emergency-fail-closed.d.ts +2 -0
- package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
- package/dist/hooks/magic-context/send-session-notification.d.ts +11 -1
- package/dist/hooks/magic-context/send-session-notification.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-7j2zv9nm.js → index-2qsca7h7.js} +47 -11
- package/dist/{index-25nktq8n.js → index-3jgzd7nz.js} +7 -7
- package/dist/{index-snbpdpa3.js → index-3pdknr07.js} +4 -4
- package/dist/{index-k0tb2z28.js → index-3x4qvp29.js} +2 -2
- package/dist/{index-d0rtbv0f.js → index-5nmqgvz2.js} +21 -14
- package/dist/{index-xrnhxkz7.js → index-60wnwcwz.js} +1 -1
- package/dist/{index-g6hfh4h4.js → index-6zewd2n5.js} +14 -8
- package/dist/{index-nny4gm06.js → index-74sh122g.js} +2 -2
- package/dist/{index-70cv85b0.js → index-78t37mcq.js} +2 -2
- package/dist/{index-stx8zd81.js → index-83qd3n7s.js} +2 -2
- package/dist/{index-jjvbk92s.js → index-9emdjcb5.js} +1 -1
- package/dist/{index-gxdc95cp.js → index-awyqqnd8.js} +585 -82
- package/dist/{index-022w6314.js → index-b364vr04.js} +109 -505
- package/dist/{index-4w5rx7de.js → index-bxrfq3mv.js} +1 -1
- package/dist/{index-1bqkqde0.js → index-c1s40xmj.js} +3 -3
- package/dist/{index-05bm2ndp.js → index-chpzb6xy.js} +1 -1
- package/dist/{index-ttk3trse.js → index-csztadkj.js} +46 -17
- package/dist/{index-798s7c8s.js → index-hdyfvdag.js} +1 -1
- package/dist/{index-4ntnt8ee.js → index-jka4y6mv.js} +1 -1
- package/dist/{index-w6v4dw5f.js → index-kmrv1fw3.js} +4 -4
- package/dist/{index-jrj95cce.js → index-m6dnydf8.js} +9 -2
- package/dist/{index-e32b3x4n.js → index-pmcvg3k1.js} +4 -4
- package/dist/{index-4dhv7mqz.js → index-qjwpqvnf.js} +48 -1
- package/dist/{index-xccywqdj.js → index-rvf1726x.js} +3 -3
- package/dist/{index-1pf5qrx4.js → index-vyfrgwhk.js} +3 -3
- package/dist/{index-s8ks5nz4.js → index-watde7a1.js} +2 -2
- package/dist/{v2/server-fzgyvsb1.js → index-y14pawe1.js} +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +61 -52
- package/dist/{message-index-bounded-6fr624zf.js → message-index-bounded-r1qys471.js} +4 -4
- package/dist/migration-worker.js +3 -3
- package/dist/plugin/messages-transform.d.ts +3 -4
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/plugin/refusal-notice.d.ts +3 -0
- package/dist/plugin/refusal-notice.d.ts.map +1 -0
- package/dist/{project-embedding-registry-q80scexh.js → project-embedding-registry-8t0gwf59.js} +3 -3
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-6wedfths.js → read-session-chunk-xv9f0wgb.js} +3 -3
- package/dist/{recomp-orchestrator-7ecg8ryx.js → recomp-orchestrator-2ztmtxt2.js} +18 -18
- package/dist/{render-yqp7q79f.js → render-d6q6h9hy.js} +10 -10
- package/dist/{rpc-notifications-t9q0ynq7.js → rpc-notifications-ta2zsxpq.js} +1 -1
- package/dist/{search-archive-r4h96j2z.js → search-archive-g96jn6p0.js} +5 -5
- package/dist/{search-bw22d7zc.js → search-d5aajhs3.js} +14 -14
- package/dist/{send-session-notification-7x518gew.js → send-session-notification-gzxz88vq.js} +1 -1
- package/dist/shared/assistant-message-extractor.d.ts +2 -0
- package/dist/shared/assistant-message-extractor.d.ts.map +1 -1
- package/dist/shared/prompt-async-transport.d.ts.map +1 -1
- package/dist/shared/rpc-notifications.d.ts +1 -1
- package/dist/shared/rpc-notifications.d.ts.map +1 -1
- package/dist/{storage-memory-e6a7mb0k.js → storage-memory-hhrvfw0x.js} +2 -2
- package/dist/{storage-tags-y2mrb8e6.js → storage-tags-f1ftvjpw.js} +2 -2
- package/dist/{transform-postprocess-phase-t99yj9vt.js → transform-postprocess-phase-b2yjw8by.js} +19 -19
- package/dist/v2/auto-search-worker.js +13 -7
- package/dist/v2/chunk-embedding-write-worker.js +4 -4
- package/dist/v2/{compartment-chunk-embedding-x6qw6mjk.js → compartment-chunk-embedding-knt2468v.js} +3 -1
- package/dist/v2/{context-k8sx1nyy.js → context-s86114yy.js} +219 -62
- package/dist/v2/{embedding-backfill-k8kqnwfq.js → embedding-backfill-tazkbpyg.js} +4 -4
- package/dist/v2/{embedding-cache-mgyr73ef.js → embedding-cache-zn4r1c31.js} +5 -1
- package/dist/v2/fold/native-replay.d.ts +3 -1
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/hidden-child-record.d.ts +1 -0
- package/dist/v2/hidden-child-record.d.ts.map +1 -1
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-jqy7283g.js → message-index-bounded-b07r9cjv.js} +4 -4
- package/dist/v2/migration-worker.js +3 -3
- package/dist/v2/{project-embedding-registry-2jp1antr.js → project-embedding-registry-ah3gsg48.js} +3 -3
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-n3nhfvd7.js → read-session-chunk-38wdy8nd.js} +3 -3
- package/dist/v2/{recomp-orchestrator-ssde9ft1.js → recomp-orchestrator-kc62xgb9.js} +17 -17
- package/dist/v2/{render-fezgh7pa.js → render-j05per51.js} +10 -10
- package/dist/v2/{rpc-notifications-t9q0ynq7.js → rpc-notifications-ta2zsxpq.js} +1 -1
- package/dist/v2/{search-archive-zz1kza50.js → search-archive-b4ptw02k.js} +5 -5
- package/dist/v2/{search-m251amra.js → search-kg31ad2s.js} +13 -13
- package/dist/v2/{send-session-notification-p52rhjzy.js → send-session-notification-zazaxxpf.js} +1 -1
- package/dist/v2/{server-ps6rz88g.js → server-2p0qayr1.js} +1 -1
- package/dist/v2/{server-fsw8kbng.js → server-2r9btf0g.js} +46 -17
- package/dist/v2/{server-wdq85mxj.js → server-6250cxzs.js} +14 -8
- package/dist/v2/{server-brgandk4.js → server-6vnbz81n.js} +2 -2
- package/dist/v2/{server-jjvbk92s.js → server-9emdjcb5.js} +1 -1
- package/dist/v2/{server-ap81bk3c.js → server-9n2qgk29.js} +1 -1
- package/dist/v2/{server-mbkwcwgw.js → server-axdmkvd5.js} +2 -2
- package/dist/v2/{server-2k8tkbhz.js → server-c7awk5s2.js} +10 -4
- package/dist/v2/{server-4wwwm2ya.js → server-ct0gs8fc.js} +4 -4
- package/dist/v2/{server-97w51d8n.js → server-ff5wcfy4.js} +3 -3
- package/dist/v2/{server-ssg29wjg.js → server-gqrw0br5.js} +20 -13
- package/dist/v2/{server-y31y6gws.js → server-gwhj0362.js} +3 -3
- package/dist/v2/{server-w7mpvkpj.js → server-pbp58w5x.js} +1 -1
- package/dist/v2/{server-s15knz0w.js → server-pmws7we9.js} +1 -1
- package/dist/v2/{server-4dhv7mqz.js → server-qjwpqvnf.js} +48 -1
- package/dist/v2/{server-a2f1bhyj.js → server-stjy5dxv.js} +9 -2
- package/dist/v2/{server-hn8b7sfe.js → server-xn7zqs4j.js} +2 -2
- package/dist/{index-fzgyvsb1.js → v2/server-y14pawe1.js} +3 -0
- package/dist/v2/{server-8pdfmc27.js → server-y17r5ryz.js} +4 -4
- package/dist/v2/{server-n5zr7190.js → server-yh2z4gg2.js} +3 -3
- package/dist/v2/{server-sxfbjdye.js → server-yx0nyj1q.js} +2 -2
- package/dist/v2/server.js +3 -3
- package/dist/v2/{storage-memory-e6a7mb0k.js → storage-memory-hhrvfw0x.js} +2 -2
- package/dist/v2/{storage-tags-xq81zgt2.js → storage-tags-pmw33chf.js} +2 -2
- package/dist/v2/{v2-archive-reader-e2w39c3p.js → v2-archive-reader-2ayz16s4.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-eg5b1p89.js → wrapup-orchestrator-e20sjbdz.js} +17 -17
- package/dist/{v2-archive-reader-8dsngf2j.js → v2-archive-reader-x39mzvwn.js} +1 -1
- package/dist/{wrapup-orchestrator-nmk6yf7f.js → wrapup-orchestrator-h3s905vs.js} +19 -19
- package/package.json +1 -1
- package/src/shared/assistant-message-extractor.test.ts +22 -0
- package/src/shared/assistant-message-extractor.ts +13 -0
- package/src/shared/model-suggestion-retry.test.ts +43 -12
- package/src/shared/prompt-async-transport.test.ts +275 -8
- package/src/shared/prompt-async-transport.ts +41 -2
- package/src/shared/reusable-worker.fixture.ts +15 -3
- package/src/shared/reusable-worker.test.ts +20 -10
- package/src/shared/rpc-notifications.ts +4 -1
- package/src/shared/sqlite-foreground-wait.test.ts +2 -2
- package/src/shared/startup-maintenance-policy.test.ts +4 -2
|
@@ -2,13 +2,60 @@ import {
|
|
|
2
2
|
getHarness2
|
|
3
3
|
} from "./index-pavzsdc6.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
getMagicContextStorageDir,
|
|
6
|
+
log2,
|
|
7
|
+
sessionLog2
|
|
8
|
+
} from "./index-ywrz4wy2.js";
|
|
9
|
+
import {
|
|
10
|
+
textMentionsRecentCommit,
|
|
11
|
+
hasMeaningfulUserText2,
|
|
12
|
+
estimateTokens
|
|
13
|
+
} from "./index-5vsk2cpp.js";
|
|
14
|
+
import {
|
|
15
|
+
inRootAsyncContext2,
|
|
16
|
+
getTagIdentityWriteGeneration2,
|
|
17
|
+
getSqliteDatabasePath2,
|
|
18
|
+
assertTransformWrite2,
|
|
19
|
+
isTransientSqliteError2
|
|
20
|
+
} from "./index-gzy5w8ya.js";
|
|
21
|
+
import {
|
|
22
|
+
reuseWorker
|
|
23
|
+
} from "./index-96ztjvkn.js";
|
|
24
|
+
import {
|
|
25
|
+
createWorkerShutdown
|
|
26
|
+
} from "./index-1d042x6w.js";
|
|
27
|
+
import {
|
|
28
|
+
runSessionWarmupWorker
|
|
29
|
+
} from "./index-q7q6qp1f.js";
|
|
30
|
+
import {
|
|
31
|
+
getMaxM0MutationId,
|
|
32
|
+
getLastCompartmentEndMessage,
|
|
33
|
+
providerResponseFailed,
|
|
34
|
+
rememberUnpublishedAutoSearchNoHint,
|
|
35
|
+
getUnpublishedAutoSearchNoHint,
|
|
36
|
+
forgetUnpublishedAutoSearchNoHint,
|
|
37
|
+
registerAutoSearchWork,
|
|
38
|
+
cancelAutoSearchWork,
|
|
39
|
+
getOrCreateSessionMeta,
|
|
40
|
+
updateSessionMeta,
|
|
41
|
+
advanceToolReclaimWatermark,
|
|
42
|
+
requestPendingMaterialization,
|
|
43
|
+
pendingMaterializationOrigin,
|
|
44
|
+
hasPendingMaterializationOrigin,
|
|
45
|
+
hasExplicitRefreshRequest,
|
|
46
|
+
clearReclaimedMaterialization,
|
|
47
|
+
clearPendingMaterializationOrigin,
|
|
48
|
+
noteServedPassPermission,
|
|
49
|
+
dropSlot,
|
|
50
|
+
TOOL_SWEEP_SCOPED_MARKER,
|
|
51
|
+
saveSourceContent,
|
|
52
|
+
replaceSourceContent,
|
|
53
|
+
getSourceContents
|
|
54
|
+
} from "./index-kmrv1fw3.js";
|
|
55
|
+
import {
|
|
56
|
+
cleanSearchText,
|
|
57
|
+
matchedSearchSnippet
|
|
58
|
+
} from "./index-chpzb6xy.js";
|
|
12
59
|
import {
|
|
13
60
|
protectedToolTagNumbers,
|
|
14
61
|
stripPersistedAssistantText,
|
|
@@ -32,6 +79,7 @@ import {
|
|
|
32
79
|
CHANNEL1_FLOOR_TOKENS,
|
|
33
80
|
decodeMergedReasoningParts,
|
|
34
81
|
readFrozenMergedReasoningParts,
|
|
82
|
+
MAX_EXECUTE_THRESHOLD,
|
|
35
83
|
escalationBands,
|
|
36
84
|
HYGIENE_PROVIDER_UNITS_VERSION,
|
|
37
85
|
sessionDecisionCalibration,
|
|
@@ -41,6 +89,7 @@ import {
|
|
|
41
89
|
ReplayDocumentError,
|
|
42
90
|
readReplayEnvelope,
|
|
43
91
|
updateReplayDocument,
|
|
92
|
+
loadPersistedUsage,
|
|
44
93
|
loadProtectedTailMeta,
|
|
45
94
|
getEmergencyInputSample,
|
|
46
95
|
setEmergencyDropSample,
|
|
@@ -58,6 +107,7 @@ import {
|
|
|
58
107
|
getPersistedTodoSyntheticAnchor,
|
|
59
108
|
setPersistedTodoSyntheticAnchor,
|
|
60
109
|
clearPersistedTodoSyntheticAnchor,
|
|
110
|
+
getOverflowState,
|
|
61
111
|
getPersistedCompactionMarkerState,
|
|
62
112
|
setPersistedCompactionMarkerState,
|
|
63
113
|
getDeferredClearedCompactionMarkerState,
|
|
@@ -171,85 +221,26 @@ import {
|
|
|
171
221
|
adoptNullOwnerToolTag2,
|
|
172
222
|
getCandidateToolOwners2,
|
|
173
223
|
pickNearestPriorOwner2
|
|
174
|
-
} from "./index-
|
|
224
|
+
} from "./index-60wnwcwz.js";
|
|
175
225
|
import {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
sessionLog2
|
|
184
|
-
} from "./index-ywrz4wy2.js";
|
|
226
|
+
BoundedSessionMap,
|
|
227
|
+
tagRevisionKey,
|
|
228
|
+
tagIdentityRevisionKey,
|
|
229
|
+
getTemporalDecisions,
|
|
230
|
+
freezeTemporalDecisions,
|
|
231
|
+
stableStringify
|
|
232
|
+
} from "./index-m6dnydf8.js";
|
|
185
233
|
import {
|
|
186
234
|
isValidLanguageCode,
|
|
235
|
+
resolveModelConfigValue,
|
|
187
236
|
normalizeProtectedToolName,
|
|
188
237
|
mergeProtectedTools
|
|
189
238
|
} from "./index-6nqz8hsz.js";
|
|
190
|
-
import {
|
|
191
|
-
inRootAsyncContext2,
|
|
192
|
-
getTagIdentityWriteGeneration2,
|
|
193
|
-
getSqliteDatabasePath2,
|
|
194
|
-
assertTransformWrite2,
|
|
195
|
-
isTransientSqliteError2
|
|
196
|
-
} from "./index-gzy5w8ya.js";
|
|
197
|
-
import {
|
|
198
|
-
reuseWorker
|
|
199
|
-
} from "./index-96ztjvkn.js";
|
|
200
|
-
import {
|
|
201
|
-
createWorkerShutdown
|
|
202
|
-
} from "./index-1d042x6w.js";
|
|
203
|
-
import {
|
|
204
|
-
runSessionWarmupWorker
|
|
205
|
-
} from "./index-q7q6qp1f.js";
|
|
206
|
-
import {
|
|
207
|
-
getMaxM0MutationId,
|
|
208
|
-
getLastCompartmentEndMessage,
|
|
209
|
-
rememberUnpublishedAutoSearchNoHint,
|
|
210
|
-
getUnpublishedAutoSearchNoHint,
|
|
211
|
-
forgetUnpublishedAutoSearchNoHint,
|
|
212
|
-
registerAutoSearchWork,
|
|
213
|
-
cancelAutoSearchWork,
|
|
214
|
-
updateSessionMeta,
|
|
215
|
-
advanceToolReclaimWatermark,
|
|
216
|
-
requestPendingMaterialization,
|
|
217
|
-
pendingMaterializationOrigin,
|
|
218
|
-
hasPendingMaterializationOrigin,
|
|
219
|
-
hasExplicitRefreshRequest,
|
|
220
|
-
clearReclaimedMaterialization,
|
|
221
|
-
clearPendingMaterializationOrigin,
|
|
222
|
-
noteServedPassPermission,
|
|
223
|
-
dropSlot,
|
|
224
|
-
TOOL_SWEEP_SCOPED_MARKER,
|
|
225
|
-
saveSourceContent,
|
|
226
|
-
replaceSourceContent,
|
|
227
|
-
getSourceContents
|
|
228
|
-
} from "./index-w6v4dw5f.js";
|
|
229
|
-
import {
|
|
230
|
-
cleanSearchText,
|
|
231
|
-
matchedSearchSnippet
|
|
232
|
-
} from "./index-05bm2ndp.js";
|
|
233
|
-
import {
|
|
234
|
-
getProjectEmbeddingSnapshot2,
|
|
235
|
-
embedTextForProject2,
|
|
236
|
-
embedBatchForProject2
|
|
237
|
-
} from "./index-s8ks5nz4.js";
|
|
238
|
-
import {
|
|
239
|
-
isEmbeddingHostBusy2
|
|
240
|
-
} from "./index-qt1qqasc.js";
|
|
241
|
-
import {
|
|
242
|
-
userFacingFailureCode
|
|
243
|
-
} from "./index-1bqkqde0.js";
|
|
244
|
-
import {
|
|
245
|
-
getMessageIndexEpoch,
|
|
246
|
-
isMessageIndexSearchable,
|
|
247
|
-
createAutoSearchDiagnostics
|
|
248
|
-
} from "./index-798s7c8s.js";
|
|
249
239
|
import {
|
|
250
240
|
openCodeDbExists,
|
|
251
241
|
withReadOnlySessionDb,
|
|
252
|
-
getMessageTimesFromOpenCodeDb
|
|
242
|
+
getMessageTimesFromOpenCodeDb,
|
|
243
|
+
findLastAssistantModelFromOpenCodeDb
|
|
253
244
|
} from "./index-x40zr813.js";
|
|
254
245
|
import {
|
|
255
246
|
stripSystemInjection,
|
|
@@ -263,7 +254,30 @@ import {
|
|
|
263
254
|
extractToolCallObservation,
|
|
264
255
|
ToolMutationBatch,
|
|
265
256
|
createToolDropTarget
|
|
266
|
-
} from "./index-
|
|
257
|
+
} from "./index-2qsca7h7.js";
|
|
258
|
+
import {
|
|
259
|
+
hasTrustedAbsoluteWall,
|
|
260
|
+
applyProvenInputFloor,
|
|
261
|
+
isSaneLimit,
|
|
262
|
+
getSdkWindowGeometry,
|
|
263
|
+
getSdkContextLimit
|
|
264
|
+
} from "./index-zmqx48vt.js";
|
|
265
|
+
import {
|
|
266
|
+
getProjectEmbeddingSnapshot2,
|
|
267
|
+
embedTextForProject2,
|
|
268
|
+
embedBatchForProject2
|
|
269
|
+
} from "./index-watde7a1.js";
|
|
270
|
+
import {
|
|
271
|
+
isEmbeddingHostBusy2
|
|
272
|
+
} from "./index-qt1qqasc.js";
|
|
273
|
+
import {
|
|
274
|
+
userFacingFailureCode
|
|
275
|
+
} from "./index-c1s40xmj.js";
|
|
276
|
+
import {
|
|
277
|
+
getMessageIndexEpoch,
|
|
278
|
+
isMessageIndexSearchable,
|
|
279
|
+
createAutoSearchDiagnostics
|
|
280
|
+
} from "./index-hdyfvdag.js";
|
|
267
281
|
import {
|
|
268
282
|
compareOpenCodeMessagesByCanonicalOrder,
|
|
269
283
|
startCompactionMarkerCandidatePreparation,
|
|
@@ -285,7 +299,12 @@ import {
|
|
|
285
299
|
peekNoteNudgeText,
|
|
286
300
|
markNoteNudgeDelivered,
|
|
287
301
|
getActiveCompartmentRun
|
|
288
|
-
} from "./index-
|
|
302
|
+
} from "./index-csztadkj.js";
|
|
303
|
+
import {
|
|
304
|
+
canonicalModelIdentity,
|
|
305
|
+
piModelRefToCanonical,
|
|
306
|
+
modelRefLookupOrder
|
|
307
|
+
} from "./index-avwt563y.js";
|
|
289
308
|
import {
|
|
290
309
|
getErrorMessage
|
|
291
310
|
} from "./index-y8v6yerm.js";
|
|
@@ -293,6 +312,450 @@ import {
|
|
|
293
312
|
logSlowWriteTransaction
|
|
294
313
|
} from "./index-m0pwswv9.js";
|
|
295
314
|
|
|
315
|
+
// src/shared/model-cache-ttl.ts
|
|
316
|
+
var MODEL_CACHE_LIFETIMES = [
|
|
317
|
+
{
|
|
318
|
+
source: "OpenAI GPT-5.6+ default",
|
|
319
|
+
value: "30m",
|
|
320
|
+
matches(model) {
|
|
321
|
+
const version = /^gpt-(\d+)(?:\.(\d+))?(?:$|[^\d.])/.exec(model);
|
|
322
|
+
if (!version)
|
|
323
|
+
return false;
|
|
324
|
+
const major = Number(version[1]);
|
|
325
|
+
const minor = Number(version[2] ?? 0);
|
|
326
|
+
return major > 5 || major === 5 && minor >= 6;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
];
|
|
330
|
+
function resolveModelCacheTtl(config, modelKey, configuredExplicitly = typeof config === "object" || typeof config === "string" && config !== "5m") {
|
|
331
|
+
if (config && typeof config !== "string") {
|
|
332
|
+
const match = modelKey && !modelKey.includes("/") && Object.hasOwn(config, modelKey) && modelKey !== "default" ? config[modelKey] : resolveModelConfigValue(config, modelKey)?.value;
|
|
333
|
+
const value = match ?? config.default;
|
|
334
|
+
if (value !== undefined && configuredExplicitly)
|
|
335
|
+
return { value, source: "config", modelKey };
|
|
336
|
+
}
|
|
337
|
+
if (typeof config === "string" && configuredExplicitly)
|
|
338
|
+
return { value: config, source: "config", modelKey };
|
|
339
|
+
const model = canonicalModelIdentity(modelKey ?? "").toLowerCase().split("/").at(-1) ?? "";
|
|
340
|
+
const known = MODEL_CACHE_LIFETIMES.find((entry) => entry.matches(model));
|
|
341
|
+
if (known)
|
|
342
|
+
return { value: known.value, source: known.source, modelKey };
|
|
343
|
+
return {
|
|
344
|
+
value: (typeof config === "object" ? config.default : config) ?? "5m",
|
|
345
|
+
source: "default",
|
|
346
|
+
modelKey
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/hooks/magic-context/opencode-proven-floor.ts
|
|
351
|
+
var KEY = "opencodeProvenInputFloor";
|
|
352
|
+
function recordOpenCodeProvenInputFloor(db, sessionId, modelKey, tokens) {
|
|
353
|
+
db.prepare(`UPDATE session_meta SET deferred_execute_state = json_set(
|
|
354
|
+
CASE WHEN json_valid(deferred_execute_state) AND json_type(deferred_execute_state) = 'object'
|
|
355
|
+
THEN deferred_execute_state ELSE '{}' END, '$.${KEY}', json(?)) WHERE session_id = ?`).run(JSON.stringify({ modelKey, tokens, basis: "provider_usage_v1" }), sessionId);
|
|
356
|
+
}
|
|
357
|
+
function largestAcceptedInput(sessionId, modelKey) {
|
|
358
|
+
return withReadOnlySessionDb((db) => {
|
|
359
|
+
const rows = db.prepare(`SELECT
|
|
360
|
+
COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID')) AS provider,
|
|
361
|
+
COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.id')) AS model,
|
|
362
|
+
json_extract(data, '$.finish') AS finish, json_extract(data, '$.error') AS error,
|
|
363
|
+
json_extract(data, '$.tokens.input') AS input,
|
|
364
|
+
json_extract(data, '$.tokens.cache.read') AS cacheRead,
|
|
365
|
+
json_extract(data, '$.tokens.cache.write') AS cacheWrite
|
|
366
|
+
FROM message WHERE session_id = ? AND json_valid(data)
|
|
367
|
+
AND json_extract(data, '$.role') = 'assistant'`).all(sessionId);
|
|
368
|
+
let largest = 0;
|
|
369
|
+
for (const row of rows) {
|
|
370
|
+
if (!row.provider || !row.model || piModelRefToCanonical(`${row.provider}/${row.model}`) !== piModelRefToCanonical(modelKey) || providerResponseFailed(row))
|
|
371
|
+
continue;
|
|
372
|
+
const components = [row.input ?? 0, row.cacheRead ?? 0, row.cacheWrite ?? 0];
|
|
373
|
+
if (components.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0)) {
|
|
374
|
+
largest = Math.max(largest, components.reduce((sum, n) => sum + n, 0));
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return largest;
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
function resolveOpenCodeProvenInputFloor(db, sessionId, modelKey) {
|
|
381
|
+
const row = db.prepare("SELECT observed_safe_input_tokens, last_observed_model_key, deferred_execute_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
382
|
+
const stored = row?.observed_safe_input_tokens ?? 0;
|
|
383
|
+
if (!modelKey || piModelRefToCanonical(row?.last_observed_model_key ?? "") !== piModelRefToCanonical(modelKey) || !Number.isFinite(stored) || stored <= 0)
|
|
384
|
+
return 0;
|
|
385
|
+
try {
|
|
386
|
+
const record = JSON.parse(row?.deferred_execute_state ?? "{}")[KEY];
|
|
387
|
+
if (record?.basis === "provider_usage_v1" && record.modelKey === modelKey && record.tokens === stored)
|
|
388
|
+
return stored;
|
|
389
|
+
} catch {}
|
|
390
|
+
let measured = 0;
|
|
391
|
+
try {
|
|
392
|
+
measured = largestAcceptedInput(sessionId, modelKey);
|
|
393
|
+
} catch {}
|
|
394
|
+
const repaired = Math.min(stored, measured);
|
|
395
|
+
updateSessionMeta(db, sessionId, {
|
|
396
|
+
observedSafeInputTokens: repaired,
|
|
397
|
+
cacheAlertSent: false,
|
|
398
|
+
lastUsageContextLimit: 0
|
|
399
|
+
});
|
|
400
|
+
recordOpenCodeProvenInputFloor(db, sessionId, modelKey, repaired);
|
|
401
|
+
sessionLog2(sessionId, `legacy proven input floor ${stored} clamped to accepted provider usage: ${repaired}`);
|
|
402
|
+
return repaired;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/hooks/magic-context/event-resolvers.ts
|
|
406
|
+
var DEFAULT_CONTEXT_LIMIT = 200000;
|
|
407
|
+
function modelMatchedPersistedUsage(db, sessionID, modelKey) {
|
|
408
|
+
if (!db || !sessionID || !modelKey)
|
|
409
|
+
return;
|
|
410
|
+
try {
|
|
411
|
+
resolveOpenCodeProvenInputFloor(db, sessionID, modelKey);
|
|
412
|
+
const persisted = loadPersistedUsage(db, sessionID);
|
|
413
|
+
if (persisted !== null && piModelRefToCanonical(persisted.lastObservedModelKey ?? "") === piModelRefToCanonical(modelKey)) {
|
|
414
|
+
return persisted;
|
|
415
|
+
}
|
|
416
|
+
} catch {}
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
function modelMatchedProvenContextLimit(db, sessionID, modelKey) {
|
|
420
|
+
if (!db || !sessionID || !modelKey)
|
|
421
|
+
return;
|
|
422
|
+
try {
|
|
423
|
+
const provenLimit = resolveOpenCodeProvenInputFloor(db, sessionID, modelKey);
|
|
424
|
+
return isSaneLimit(provenLimit) ? provenLimit : undefined;
|
|
425
|
+
} catch {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
function applySessionProvenFloor(geometry, provenLimit, ctx) {
|
|
430
|
+
const result = applyProvenInputFloor(geometry, provenLimit);
|
|
431
|
+
if (result.refused && ctx?.db && ctx.sessionID) {
|
|
432
|
+
const persisted = loadPersistedUsage(ctx.db, ctx.sessionID);
|
|
433
|
+
const impossiblePressure = persisted?.usage.inputTokens ? persisted.usage.inputTokens > result.refused.absoluteWall : false;
|
|
434
|
+
updateSessionMeta(ctx.db, ctx.sessionID, {
|
|
435
|
+
observedSafeInputTokens: 0,
|
|
436
|
+
cacheAlertSent: false,
|
|
437
|
+
lastUsageContextLimit: geometry.usableSoft,
|
|
438
|
+
lastInputTokens: impossiblePressure ? 0 : persisted?.usage.inputTokens,
|
|
439
|
+
lastContextPercentage: impossiblePressure ? 0 : persisted?.usage.percentage
|
|
440
|
+
});
|
|
441
|
+
sessionLog2(ctx.sessionID, `persisted proven floor ${result.refused.reading} exceeds trusted absolute wall ${result.refused.absoluteWall}; cleared and re-resolved to ${geometry.usableSoft}`);
|
|
442
|
+
}
|
|
443
|
+
return result.geometry;
|
|
444
|
+
}
|
|
445
|
+
function resolveContextWindowGeometry(providerID, modelID, ctx) {
|
|
446
|
+
if (!providerID || !modelID)
|
|
447
|
+
return;
|
|
448
|
+
const modelKey = resolveModelKey(providerID, modelID);
|
|
449
|
+
let detected;
|
|
450
|
+
let detectedLimitProvenance = "unknown";
|
|
451
|
+
if (ctx?.db && ctx.sessionID) {
|
|
452
|
+
try {
|
|
453
|
+
const overflow = getOverflowState(ctx.db, ctx.sessionID, modelKey);
|
|
454
|
+
if (overflow.detectedContextLimit > 0) {
|
|
455
|
+
detected = overflow.detectedContextLimit;
|
|
456
|
+
detectedLimitProvenance = overflow.detectedContextLimitProvenance;
|
|
457
|
+
}
|
|
458
|
+
} catch {}
|
|
459
|
+
}
|
|
460
|
+
const geometry = getSdkWindowGeometry(providerID, modelID, detected, {
|
|
461
|
+
detectedLimitProvenance,
|
|
462
|
+
harness: "opencode"
|
|
463
|
+
});
|
|
464
|
+
if (!geometry || detected !== undefined)
|
|
465
|
+
return geometry;
|
|
466
|
+
return applySessionProvenFloor(geometry, modelMatchedProvenContextLimit(ctx?.db, ctx?.sessionID, modelKey), ctx);
|
|
467
|
+
}
|
|
468
|
+
function resolveContextLimit(providerID, modelID, ctx) {
|
|
469
|
+
const modelKey = resolveModelKey(providerID, modelID);
|
|
470
|
+
let detected;
|
|
471
|
+
let detectedLimitProvenance = "unknown";
|
|
472
|
+
if (ctx?.db && ctx.sessionID) {
|
|
473
|
+
try {
|
|
474
|
+
const overflow = getOverflowState(ctx.db, ctx.sessionID, modelKey);
|
|
475
|
+
if (overflow.detectedContextLimit > 0) {
|
|
476
|
+
detected = overflow.detectedContextLimit;
|
|
477
|
+
detectedLimitProvenance = overflow.detectedContextLimitProvenance;
|
|
478
|
+
}
|
|
479
|
+
} catch {}
|
|
480
|
+
}
|
|
481
|
+
const fromModelsDev = providerID && modelID ? getSdkContextLimit(providerID, modelID, detected, {
|
|
482
|
+
reservation: ctx?.reservation,
|
|
483
|
+
detectedLimitProvenance
|
|
484
|
+
}) : undefined;
|
|
485
|
+
const resolved = fromModelsDev ?? detected ?? DEFAULT_CONTEXT_LIMIT;
|
|
486
|
+
if (detected !== undefined)
|
|
487
|
+
return resolved;
|
|
488
|
+
const provenLimit = modelMatchedProvenContextLimit(ctx?.db, ctx?.sessionID, modelKey);
|
|
489
|
+
if (!isSaneLimit(provenLimit))
|
|
490
|
+
return resolved;
|
|
491
|
+
const geometry = resolveContextWindowGeometry(providerID, modelID, ctx);
|
|
492
|
+
if (ctx?.reservation !== "none" && geometry)
|
|
493
|
+
return geometry.usableSoft;
|
|
494
|
+
if (geometry && hasTrustedAbsoluteWall(geometry) && provenLimit > geometry.derivation.absoluteWall) {
|
|
495
|
+
return resolved;
|
|
496
|
+
}
|
|
497
|
+
return Math.max(resolved, provenLimit);
|
|
498
|
+
}
|
|
499
|
+
function resolveTrustedContextLimit(providerID, modelID, ctx) {
|
|
500
|
+
const modelKey = resolveModelKey(providerID, modelID);
|
|
501
|
+
let detected;
|
|
502
|
+
let detectedLimitProvenance = "unknown";
|
|
503
|
+
if (ctx?.db && ctx.sessionID) {
|
|
504
|
+
try {
|
|
505
|
+
const overflow = getOverflowState(ctx.db, ctx.sessionID, modelKey);
|
|
506
|
+
if (overflow.detectedContextLimit > 0) {
|
|
507
|
+
detected = overflow.detectedContextLimit;
|
|
508
|
+
detectedLimitProvenance = overflow.detectedContextLimitProvenance;
|
|
509
|
+
}
|
|
510
|
+
} catch {}
|
|
511
|
+
}
|
|
512
|
+
const fromModelsDev = providerID && modelID ? getSdkContextLimit(providerID, modelID, detected, {
|
|
513
|
+
detectedLimitProvenance
|
|
514
|
+
}) : undefined;
|
|
515
|
+
if (detected !== undefined) {
|
|
516
|
+
return typeof fromModelsDev === "number" && fromModelsDev > 0 ? fromModelsDev : detected;
|
|
517
|
+
}
|
|
518
|
+
const provenLimit = modelMatchedProvenContextLimit(ctx?.db, ctx?.sessionID, modelKey);
|
|
519
|
+
if (typeof fromModelsDev === "number" && fromModelsDev > 0) {
|
|
520
|
+
return isSaneLimit(provenLimit) ? Math.max(fromModelsDev, provenLimit) : fromModelsDev;
|
|
521
|
+
}
|
|
522
|
+
if (isSaneLimit(provenLimit))
|
|
523
|
+
return provenLimit;
|
|
524
|
+
const persisted = modelMatchedPersistedUsage(ctx?.db, ctx?.sessionID, modelKey);
|
|
525
|
+
return isSaneLimit(persisted?.lastUsageContextLimit) ? persisted.lastUsageContextLimit : undefined;
|
|
526
|
+
}
|
|
527
|
+
var WRAPUP_WINDOW_UNAVAILABLE = "Cannot run /ctx-wrapup: the model's context window is unknown. Select a model with a configured context window or send a message with that model, then retry.";
|
|
528
|
+
function readPersistedWrapupWindow(db, sessionId, modelKey) {
|
|
529
|
+
const { lastUsageContextLimit, lastObservedModelKey } = getOrCreateSessionMeta(db, sessionId);
|
|
530
|
+
if (!isSaneLimit(lastUsageContextLimit) || !lastObservedModelKey)
|
|
531
|
+
return;
|
|
532
|
+
if (modelKey && piModelRefToCanonical(modelKey) !== piModelRefToCanonical(lastObservedModelKey))
|
|
533
|
+
return;
|
|
534
|
+
return { contextLimit: lastUsageContextLimit, modelKey: lastObservedModelKey };
|
|
535
|
+
}
|
|
536
|
+
function resolveOpenCodeWrapupWindow(db, sessionId, model) {
|
|
537
|
+
const route = model ?? findLastAssistantModelFromOpenCodeDb(sessionId);
|
|
538
|
+
const modelKey = resolveModelKey(route?.providerID, route?.modelID);
|
|
539
|
+
if (modelKey) {
|
|
540
|
+
const contextLimit = resolveTrustedContextLimit(route?.providerID, route?.modelID, {
|
|
541
|
+
db,
|
|
542
|
+
sessionID: sessionId
|
|
543
|
+
});
|
|
544
|
+
if (contextLimit !== undefined)
|
|
545
|
+
return { contextLimit, modelKey };
|
|
546
|
+
}
|
|
547
|
+
return readPersistedWrapupWindow(db, sessionId, modelKey);
|
|
548
|
+
}
|
|
549
|
+
var clampWarnSeen = new Set;
|
|
550
|
+
function isFinitePositive(v) {
|
|
551
|
+
return typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
552
|
+
}
|
|
553
|
+
function* modelKeyLookupOrder(modelKey) {
|
|
554
|
+
const slash = modelKey.indexOf("/");
|
|
555
|
+
const providerRefs = slash >= 0 ? modelRefLookupOrder(modelKey) : [];
|
|
556
|
+
let modelId = slash >= 0 ? modelKey.slice(slash + 1) : modelKey;
|
|
557
|
+
while (modelId.length > 0) {
|
|
558
|
+
for (const providerRef of providerRefs) {
|
|
559
|
+
const providerSlash = providerRef.indexOf("/");
|
|
560
|
+
yield `${providerRef.slice(0, providerSlash)}/${modelId}`;
|
|
561
|
+
}
|
|
562
|
+
yield modelId;
|
|
563
|
+
const lastDash = modelId.lastIndexOf("-");
|
|
564
|
+
if (lastDash <= 0)
|
|
565
|
+
break;
|
|
566
|
+
modelId = modelId.slice(0, lastDash);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
function resolveExecuteThresholdDetail(config, modelKey, fallback, options) {
|
|
570
|
+
if (options?.tokensConfig && isFinitePositive(options.contextLimit)) {
|
|
571
|
+
const contextLimit = options.contextLimit;
|
|
572
|
+
const tokenMatch = resolveTokensMatchWithKey(options.tokensConfig, modelKey);
|
|
573
|
+
if (tokenMatch && isFinitePositive(tokenMatch.value)) {
|
|
574
|
+
const cap = contextLimit * (MAX_EXECUTE_THRESHOLD / 100);
|
|
575
|
+
const effectiveTokens = Math.min(tokenMatch.value, cap);
|
|
576
|
+
if (effectiveTokens < tokenMatch.value) {
|
|
577
|
+
const dedupeKey = `${options.sessionId ?? "__global__"}|${modelKey ?? "__default__"}|${tokenMatch.value}|${cap}`;
|
|
578
|
+
if (!clampWarnSeen.has(dedupeKey)) {
|
|
579
|
+
clampWarnSeen.add(dedupeKey);
|
|
580
|
+
const msg = `execute_threshold_tokens clamped: ${tokenMatch.value} → ${effectiveTokens} (${MAX_EXECUTE_THRESHOLD}% of ${contextLimit}) for ${modelKey ?? "default"}`;
|
|
581
|
+
if (options.sessionId) {
|
|
582
|
+
sessionLog2(options.sessionId, `WARN: ${msg}`);
|
|
583
|
+
} else {
|
|
584
|
+
log2(`[magic-context] WARN: ${msg}`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const percentage = effectiveTokens / contextLimit * 100;
|
|
589
|
+
const detail = {
|
|
590
|
+
percentage: Math.min(percentage, MAX_EXECUTE_THRESHOLD),
|
|
591
|
+
mode: "tokens",
|
|
592
|
+
absoluteTokens: Math.floor(effectiveTokens),
|
|
593
|
+
matchedKey: tokenMatch.matchedKey
|
|
594
|
+
};
|
|
595
|
+
if (effectiveTokens < tokenMatch.value) {
|
|
596
|
+
detail.clamped = true;
|
|
597
|
+
detail.configuredValue = tokenMatch.value;
|
|
598
|
+
}
|
|
599
|
+
return detail;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
let resolved;
|
|
603
|
+
let matchedKey;
|
|
604
|
+
if (typeof config === "number") {
|
|
605
|
+
resolved = config;
|
|
606
|
+
} else if (modelKey) {
|
|
607
|
+
let matched;
|
|
608
|
+
for (const candidate of modelKeyLookupOrder(modelKey)) {
|
|
609
|
+
if (typeof config[candidate] === "number") {
|
|
610
|
+
matched = config[candidate];
|
|
611
|
+
matchedKey = candidate;
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (matched === undefined && typeof config.default === "number") {
|
|
616
|
+
resolved = config.default;
|
|
617
|
+
matchedKey = "default";
|
|
618
|
+
} else {
|
|
619
|
+
resolved = matched ?? fallback;
|
|
620
|
+
}
|
|
621
|
+
} else if (typeof config.default === "number") {
|
|
622
|
+
resolved = config.default;
|
|
623
|
+
matchedKey = "default";
|
|
624
|
+
} else {
|
|
625
|
+
resolved = fallback;
|
|
626
|
+
}
|
|
627
|
+
if (!Number.isFinite(resolved) || resolved < 0) {
|
|
628
|
+
resolved = fallback;
|
|
629
|
+
}
|
|
630
|
+
const cappedPercentage = Math.min(resolved, MAX_EXECUTE_THRESHOLD);
|
|
631
|
+
const percentageClamped = cappedPercentage < resolved;
|
|
632
|
+
if (percentageClamped) {
|
|
633
|
+
const dedupeKey = `pct|${options?.sessionId ?? "__global__"}|${modelKey ?? "__default__"}|${resolved}`;
|
|
634
|
+
if (!clampWarnSeen.has(dedupeKey)) {
|
|
635
|
+
clampWarnSeen.add(dedupeKey);
|
|
636
|
+
const msg = `execute_threshold clamped ${resolved}% → ${MAX_EXECUTE_THRESHOLD}% for ${modelKey ?? "default"} (capped against the output-reserved safe window; 10% remains for mid-turn growth before the absolute 95% wall)`;
|
|
637
|
+
if (options?.sessionId) {
|
|
638
|
+
sessionLog2(options.sessionId, `WARN: ${msg}`);
|
|
639
|
+
} else {
|
|
640
|
+
log2(`[magic-context] WARN: ${msg}`);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const detail = {
|
|
645
|
+
percentage: cappedPercentage,
|
|
646
|
+
mode: "percentage",
|
|
647
|
+
matchedKey
|
|
648
|
+
};
|
|
649
|
+
if (percentageClamped) {
|
|
650
|
+
detail.clamped = true;
|
|
651
|
+
detail.configuredValue = resolved;
|
|
652
|
+
}
|
|
653
|
+
return detail;
|
|
654
|
+
}
|
|
655
|
+
function resolveExecuteThreshold(config, modelKey, fallback, options) {
|
|
656
|
+
return resolveExecuteThresholdDetail(config, modelKey, fallback, options).percentage;
|
|
657
|
+
}
|
|
658
|
+
function resolveTokensMatchWithKey(tokensConfig, modelKey) {
|
|
659
|
+
if (!tokensConfig) {
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (modelKey) {
|
|
663
|
+
for (const candidate of modelKeyLookupOrder(modelKey)) {
|
|
664
|
+
const value = tokensConfig[candidate];
|
|
665
|
+
if (typeof value === "number") {
|
|
666
|
+
return { value, matchedKey: candidate };
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
if (typeof tokensConfig.default === "number") {
|
|
671
|
+
return { value: tokensConfig.default, matchedKey: "default" };
|
|
672
|
+
}
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
function resolveModelKey(providerID, modelID) {
|
|
676
|
+
if (!providerID || !modelID) {
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
return piModelRefToCanonical(`${providerID}/${modelID}`);
|
|
680
|
+
}
|
|
681
|
+
function resolveSessionId(properties) {
|
|
682
|
+
if (typeof properties?.sessionID === "string") {
|
|
683
|
+
return properties.sessionID;
|
|
684
|
+
}
|
|
685
|
+
const info = properties?.info;
|
|
686
|
+
if (info === null || typeof info !== "object") {
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
const record = info;
|
|
690
|
+
if (typeof record.sessionID === "string") {
|
|
691
|
+
return record.sessionID;
|
|
692
|
+
}
|
|
693
|
+
if (typeof record.id === "string") {
|
|
694
|
+
return record.id;
|
|
695
|
+
}
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
function historyBudgetPolicyIdentity(historyBudgetPercentage, executeThresholdPercentage, modelKey, executeThresholdTokens) {
|
|
699
|
+
if (!historyBudgetPercentage)
|
|
700
|
+
return "pdefault";
|
|
701
|
+
const threshold = resolveExecuteThresholdDetail(executeThresholdPercentage ?? 65, modelKey, 65, { tokensConfig: executeThresholdTokens, contextLimit: Number.MAX_SAFE_INTEGER });
|
|
702
|
+
return `p${historyBudgetPercentage}:${threshold.mode}:${threshold.absoluteTokens ?? threshold.percentage}`;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// src/features/magic-context/scheduler.ts
|
|
706
|
+
var TTL_PATTERN = /^(\d+)([smh])$/;
|
|
707
|
+
var NUMERIC_PATTERN = /^\d+$/;
|
|
708
|
+
var UNIT_TO_MS = {
|
|
709
|
+
s: 1000,
|
|
710
|
+
m: 60 * 1000,
|
|
711
|
+
h: 60 * 60 * 1000
|
|
712
|
+
};
|
|
713
|
+
function parseCacheTtl(ttl) {
|
|
714
|
+
const normalizedTtl = ttl.trim();
|
|
715
|
+
if (normalizedTtl.toLowerCase() === "never") {
|
|
716
|
+
return Number.POSITIVE_INFINITY;
|
|
717
|
+
}
|
|
718
|
+
if (NUMERIC_PATTERN.test(normalizedTtl)) {
|
|
719
|
+
return Number(normalizedTtl);
|
|
720
|
+
}
|
|
721
|
+
const match = normalizedTtl.match(TTL_PATTERN);
|
|
722
|
+
if (!match) {
|
|
723
|
+
throw new Error(`Invalid cache TTL format: ${ttl}`);
|
|
724
|
+
}
|
|
725
|
+
const value = Number(match[1]);
|
|
726
|
+
const unit = match[2];
|
|
727
|
+
return value * UNIT_TO_MS[unit];
|
|
728
|
+
}
|
|
729
|
+
function createScheduler(config) {
|
|
730
|
+
return {
|
|
731
|
+
shouldExecute(sessionMeta, contextUsage, _currentTime, sessionId, modelKey, contextLimit) {
|
|
732
|
+
if (contextUsage.percentage === 0 && sessionMeta.lastResponseTime === 0) {
|
|
733
|
+
return "defer";
|
|
734
|
+
}
|
|
735
|
+
const effectiveContextLimit = contextLimit ?? (contextUsage.percentage > 0 && contextUsage.inputTokens > 0 ? contextUsage.inputTokens / (contextUsage.percentage / 100) : undefined);
|
|
736
|
+
const threshold = resolveExecuteThreshold(config.executeThresholdPercentage, modelKey, 65, {
|
|
737
|
+
tokensConfig: config.executeThresholdTokens,
|
|
738
|
+
contextLimit: effectiveContextLimit,
|
|
739
|
+
sessionId
|
|
740
|
+
});
|
|
741
|
+
if (contextUsage.percentage >= threshold) {
|
|
742
|
+
return "execute";
|
|
743
|
+
}
|
|
744
|
+
return "defer";
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
function computeHardCacheExpired(cacheTtl, lastResponseTime, now, onInvalid) {
|
|
749
|
+
let ttlMs;
|
|
750
|
+
try {
|
|
751
|
+
ttlMs = parseCacheTtl(cacheTtl);
|
|
752
|
+
} catch (error) {
|
|
753
|
+
onInvalid?.(error);
|
|
754
|
+
ttlMs = 5 * 60 * 1000;
|
|
755
|
+
}
|
|
756
|
+
return lastResponseTime > 0 && now - lastResponseTime > ttlMs;
|
|
757
|
+
}
|
|
758
|
+
|
|
296
759
|
// src/features/magic-context/tagger.ts
|
|
297
760
|
var TOOL_COMPOSITE_KEY_SEP = "\x00";
|
|
298
761
|
function makeToolCompositeKey(ownerMsgId, callId) {
|
|
@@ -1422,6 +1885,43 @@ var searchWorkers = new WeakMap;
|
|
|
1422
1885
|
var liveSearchWorkers = new Set;
|
|
1423
1886
|
var MAX_IDLE_SEARCH_WORKERS = 4;
|
|
1424
1887
|
var SEARCH_WORKER_IDLE_MS = 5 * 60000;
|
|
1888
|
+
var MAX_SEARCH_WORKER_CACHE_TTL_MS = 60 * 60000;
|
|
1889
|
+
function scheduleSearchWorkerExpiry(db, slot) {
|
|
1890
|
+
const arm = (delay) => {
|
|
1891
|
+
slot.idleTimer = setTimeout(check, delay);
|
|
1892
|
+
slot.idleTimer.unref?.();
|
|
1893
|
+
};
|
|
1894
|
+
const check = () => {
|
|
1895
|
+
const now = Date.now();
|
|
1896
|
+
let expires = now;
|
|
1897
|
+
try {
|
|
1898
|
+
const read = db.prepare("SELECT cache_ttl, last_response_time FROM session_meta WHERE session_id = ?");
|
|
1899
|
+
for (const session of slot.searchedSessions) {
|
|
1900
|
+
const row = read.get(session);
|
|
1901
|
+
if (!row) {
|
|
1902
|
+
slot.searchedSessions.delete(session);
|
|
1903
|
+
continue;
|
|
1904
|
+
}
|
|
1905
|
+
if (!row.cache_ttl || !row.last_response_time || row.last_response_time > now)
|
|
1906
|
+
continue;
|
|
1907
|
+
let ttl;
|
|
1908
|
+
try {
|
|
1909
|
+
ttl = Math.min(parseCacheTtl(row.cache_ttl), MAX_SEARCH_WORKER_CACHE_TTL_MS);
|
|
1910
|
+
} catch {
|
|
1911
|
+
continue;
|
|
1912
|
+
}
|
|
1913
|
+
if (ttl <= SEARCH_WORKER_IDLE_MS)
|
|
1914
|
+
continue;
|
|
1915
|
+
expires = Math.max(expires, row.last_response_time + ttl);
|
|
1916
|
+
}
|
|
1917
|
+
} catch {}
|
|
1918
|
+
if (expires > now)
|
|
1919
|
+
arm(expires - now);
|
|
1920
|
+
else
|
|
1921
|
+
slot.dispose();
|
|
1922
|
+
};
|
|
1923
|
+
arm(SEARCH_WORKER_IDLE_MS);
|
|
1924
|
+
}
|
|
1425
1925
|
var DETACHED_SEARCH_LIMIT_MS = 30000;
|
|
1426
1926
|
var AUTO_SEARCH_WORKER_CLOSE_DEADLINE_MS = 2000;
|
|
1427
1927
|
var workersCreated = 0;
|
|
@@ -1456,6 +1956,7 @@ async function acquireSearchWorker(db, key, entry, input, signal) {
|
|
|
1456
1956
|
const shutdown = createWorkerShutdown(worker, "auto-search", AUTO_SEARCH_WORKER_CLOSE_DEADLINE_MS);
|
|
1457
1957
|
slot = {
|
|
1458
1958
|
worker,
|
|
1959
|
+
searchedSessions: new Set,
|
|
1459
1960
|
dispose() {
|
|
1460
1961
|
this.disposed = true;
|
|
1461
1962
|
clearTimeout(this.idleTimer);
|
|
@@ -1624,8 +2125,8 @@ async function executeAutoSearchWorker(db, sessionId, projectPath, query, option
|
|
|
1624
2125
|
if (dispose || !detachable)
|
|
1625
2126
|
slot.dispose();
|
|
1626
2127
|
else if (!slot.disposed) {
|
|
1627
|
-
slot.
|
|
1628
|
-
slot
|
|
2128
|
+
slot.searchedSessions.add(sessionId);
|
|
2129
|
+
scheduleSearchWorkerExpiry(db, slot);
|
|
1629
2130
|
}
|
|
1630
2131
|
const free = slot.release;
|
|
1631
2132
|
slot.busy = undefined;
|
|
@@ -2870,9 +3371,11 @@ function signedTurnContextRefusal(estimate, limit) {
|
|
|
2870
3371
|
|
|
2871
3372
|
class EmergencyFailClosedError extends Error {
|
|
2872
3373
|
code;
|
|
3374
|
+
noticeHandled;
|
|
2873
3375
|
constructor(message, options) {
|
|
2874
3376
|
super(message, options);
|
|
2875
3377
|
this.code = options?.code ?? "EMERGENCY_FAIL_CLOSED";
|
|
3378
|
+
this.noticeHandled = options?.noticeHandled;
|
|
2876
3379
|
this.name = "EmergencyFailClosedError";
|
|
2877
3380
|
}
|
|
2878
3381
|
}
|
|
@@ -8729,4 +9232,4 @@ function checkM0MutationDriftAndSignal2(args) {
|
|
|
8729
9232
|
return false;
|
|
8730
9233
|
}
|
|
8731
9234
|
|
|
8732
|
-
export { makeToolCompositeKey, createTagger, cavemanWordRulesForLanguage, searchMessageHistoryOffThread, findSessionId, findLastUserMessageId, clearAutoSearchForSession, setCtxReduceRegisteredGlobally, resolveCtxReduceAvailabilityFromMessages, resolveCtxReduceAvailability, primeCtxReduceSpawnPermission, ctxReduceSpawnPermissionReadNeeded, spawnAgentFromMessages, spawnAgentFromOpenCodeDb, todowritePermissionDenied, cachedToolPermissionDenied, clearToolPermissionDenied, resolveTodowriteAvailabilityFromMessages, resolveTodowriteAvailability, diagnosticStateChanged, clearDiagnosticLogState, canConsumeDeferredOnThisPass, hasReclaimRide, reclaimRidePermitted, reclaimRideLabel, pendingDropEligibilityKey, createPendingDropEligibilityCache, readExecuteReclaimState, writeExecuteReclaimState, maintainExecuteFloorMark, captureOpencodeReasoningBudgetStatus, reasoningBudgetStatusLine, ENGINE_RECONNECTING_USER_MESSAGE, ENGINE_BUSY_USER_MESSAGE, SIGNED_THINKING_RESET_FENCE_FAILED, contextRefusalError, protectedToolRefusal, outgoingContextRefusal, signedTurnContextRefusal, EmergencyFailClosedError, removeReasoningParts, latestAssistantTurnStart, latestAssistantTurnMessages, hasActiveAnthropicThinkingTurn, retainedActiveThinkingParts, armLatestThinkingRecovery, LATEST_TURN_THINKING_REMOVED_REASON, prepareLatestThinkingRecovery, endLatestThinkingRecoveryAfterReset, restoredTurnMessages, captureLatestTurnOriginals, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, armThinkingBindingRecoveryFromError, hostInstructionRetentionEnabled, isHostInstructionRetentionOn, recordHostInstructionDecisions, replayCavemanCompression, DegradedPassRefusalError, degradedPassError, servedHeadChanged, noteHostCheckpointCommit, revertHostCheckpointPass, forgetHostCheckpointPass, forceBandConfirmed, pressureBands, forceRide, heuristicsRunOnPass, routineCleanupRunsOnPass, heuristicsAlreadyRanThisTurn, routinePressureAlreadyApplied, safeReasoningCutoff, isStructuralNoiseSentinel, stripStructuralNoise, prepareStructuralSentinelChoices, renderDroppedText, applyFlushedStatuses, prewarmTagOwners, waitForTagOwners, collectForeignTextParts, isLegacyForeignTextTag, withTransformTimingSummary, logTransformTiming, hasRecentAssistantCommit, tagMessages, resetDegradedCacheCount2, isSyntheticHeadMessage2, applyTodoSynthesis2, freezeReasoningOnBustingPass2, servesThinkingBlock2, firstServedDivergenceIndex2, rustModeServedKeyAfterPersistedStrips2, replayRustModeBindingMismatchStrips2, RUST_MARKER_LOCK_SKIP_LOG2, applyRustModeDeferredCompactionMarker2, clearRustModeBoundaryRecord2, runRustModePostprocess2, reconcileMarkerRepresentation2, clearPendingCompactionMarkerAfterSuccessfulDrain2, defaultCompactionMarkerStrategy2, abortSessionFailClosed2, evaluateEmergencyFailClosed2, finalizeMessageRepresentation2, runPostTransformPhase2, checkM0MutationDriftAndSignal2 };
|
|
9235
|
+
export { resolveModelCacheTtl, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveTrustedContextLimit, WRAPUP_WINDOW_UNAVAILABLE, resolveOpenCodeWrapupWindow, resolveExecuteThresholdDetail, resolveExecuteThreshold, resolveModelKey, resolveSessionId, historyBudgetPolicyIdentity, parseCacheTtl, createScheduler, computeHardCacheExpired, makeToolCompositeKey, createTagger, cavemanWordRulesForLanguage, searchMessageHistoryOffThread, findSessionId, findLastUserMessageId, clearAutoSearchForSession, setCtxReduceRegisteredGlobally, resolveCtxReduceAvailabilityFromMessages, resolveCtxReduceAvailability, primeCtxReduceSpawnPermission, ctxReduceSpawnPermissionReadNeeded, spawnAgentFromMessages, spawnAgentFromOpenCodeDb, todowritePermissionDenied, cachedToolPermissionDenied, clearToolPermissionDenied, resolveTodowriteAvailabilityFromMessages, resolveTodowriteAvailability, diagnosticStateChanged, clearDiagnosticLogState, canConsumeDeferredOnThisPass, hasReclaimRide, reclaimRidePermitted, reclaimRideLabel, pendingDropEligibilityKey, createPendingDropEligibilityCache, readExecuteReclaimState, writeExecuteReclaimState, maintainExecuteFloorMark, captureOpencodeReasoningBudgetStatus, reasoningBudgetStatusLine, ENGINE_RECONNECTING_USER_MESSAGE, ENGINE_BUSY_USER_MESSAGE, SIGNED_THINKING_RESET_FENCE_FAILED, contextRefusalError, protectedToolRefusal, outgoingContextRefusal, signedTurnContextRefusal, EmergencyFailClosedError, removeReasoningParts, latestAssistantTurnStart, latestAssistantTurnMessages, hasActiveAnthropicThinkingTurn, retainedActiveThinkingParts, armLatestThinkingRecovery, LATEST_TURN_THINKING_REMOVED_REASON, prepareLatestThinkingRecovery, endLatestThinkingRecoveryAfterReset, restoredTurnMessages, captureLatestTurnOriginals, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, armThinkingBindingRecoveryFromError, hostInstructionRetentionEnabled, isHostInstructionRetentionOn, recordHostInstructionDecisions, replayCavemanCompression, describeDegradedPassFailure, DegradedPassRefusalError, degradedPassError, servedHeadChanged, noteHostCheckpointCommit, revertHostCheckpointPass, forgetHostCheckpointPass, forceBandConfirmed, pressureBands, forceRide, heuristicsRunOnPass, routineCleanupRunsOnPass, heuristicsAlreadyRanThisTurn, routinePressureAlreadyApplied, safeReasoningCutoff, isStructuralNoiseSentinel, stripStructuralNoise, prepareStructuralSentinelChoices, renderDroppedText, applyFlushedStatuses, prewarmTagOwners, waitForTagOwners, collectForeignTextParts, isLegacyForeignTextTag, withTransformTimingSummary, logTransformTiming, hasRecentAssistantCommit, tagMessages, resetDegradedCacheCount2, isSyntheticHeadMessage2, applyTodoSynthesis2, freezeReasoningOnBustingPass2, servesThinkingBlock2, firstServedDivergenceIndex2, rustModeServedKeyAfterPersistedStrips2, replayRustModeBindingMismatchStrips2, RUST_MARKER_LOCK_SKIP_LOG2, applyRustModeDeferredCompactionMarker2, clearRustModeBoundaryRecord2, runRustModePostprocess2, reconcileMarkerRepresentation2, clearPendingCompactionMarkerAfterSuccessfulDrain2, defaultCompactionMarkerStrategy2, abortSessionFailClosed2, evaluateEmergencyFailClosed2, finalizeMessageRepresentation2, runPostTransformPhase2, checkM0MutationDriftAndSignal2 };
|