@cortexkit/opencode-magic-context 0.49.89 → 0.49.91
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 +4 -4
- package/dist/chunk-embedding-write-worker.js +6 -6
- package/dist/{compartment-chunk-embedding-fey2bsyf.js → compartment-chunk-embedding-rp4asvk0.js} +3 -3
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/migrate-dreamer-v2.d.ts +1 -0
- package/dist/config/migrate-dreamer-v2.d.ts.map +1 -1
- package/dist/{context-grdg1k2k.js → context-6qq5e1ry.js} +716 -216
- package/dist/{embedding-backfill-qjkaee9s.js → embedding-backfill-w0yq71q2.js} +6 -6
- package/dist/embedding-worker.js +3 -3
- package/dist/features/magic-context/dreamer/refresh-primers.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts +2 -2
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
- package/dist/features/magic-context/memory/single-store-embedding-drain.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts +2 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-types.d.ts +2 -2
- package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-host-runner.d.ts +1 -1
- package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/history-boundary-repair.d.ts +2 -0
- package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-formatting.d.ts +2 -0
- package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
- package/dist/{index-3pdknr07.js → index-0twg41mh.js} +2 -2
- package/dist/{index-2pdgy88n.js → index-3n376ann.js} +19 -7
- package/dist/{index-wmb2mcdw.js → index-3yw525kb.js} +5 -5
- package/dist/{index-mrjat4eq.js → index-5wgdbj2h.js} +3 -3
- package/dist/{index-pxnzyvjc.js → index-6r99v53h.js} +1 -1
- package/dist/{index-9d3qgwq0.js → index-6t7jvp76.js} +3 -3
- package/dist/{index-jzfsnbmm.js → index-7rgnh11t.js} +5 -5
- package/dist/{index-chpzb6xy.js → index-capcna4r.js} +2 -2
- package/dist/{index-1y4y98r1.js → index-czz0w2c4.js} +14 -2
- package/dist/{index-zxhev8ze.js → index-dva352qe.js} +1 -1
- package/dist/{index-dk3hy2a2.js → index-e8my7q6m.js} +10 -10
- package/dist/{index-w51n3576.js → index-f25ha337.js} +1 -1
- package/dist/{index-q7msfgwz.js → index-febyth5n.js} +94 -27
- package/dist/{index-kknjvmpx.js → index-fqth7850.js} +51 -60
- package/dist/{index-60wnwcwz.js → index-gqhebzxx.js} +2 -2
- package/dist/{index-n1ty0vd3.js → index-m6vhxsce.js} +58 -56
- package/dist/{index-m6dnydf8.js → index-mg9s2rc3.js} +1 -1
- package/dist/{index-2qsca7h7.js → index-mq97qmb8.js} +3 -3
- package/dist/{index-78t37mcq.js → index-nmkv8yvs.js} +3 -3
- package/dist/{index-tt0vs4x5.js → index-qna2ra0s.js} +1 -1
- package/dist/{index-qfcjrnpe.js → index-r6r2eh90.js} +4 -4
- package/dist/{index-g0mb2kb4.js → index-ran2b3fn.js} +10 -10
- package/dist/{index-5vsk2cpp.js → index-s7460efs.js} +12 -1
- package/dist/{index-08jfpny9.js → index-sr8dmp7p.js} +1 -1
- package/dist/{index-h9hybzr5.js → index-wfahebsc.js} +5 -5
- package/dist/index-x3rdza40.js +63 -0
- package/dist/{index-60x5d68t.js → index-xn9efn18.js} +1 -1
- package/dist/{index-39rzef89.js → index-ydhymf0b.js} +3 -3
- package/dist/{index-61knrt52.js → index-ywgv1xcb.js} +1 -1
- package/dist/index.js +40 -40
- package/dist/{message-index-bounded-r1qys471.js → message-index-bounded-wvnp6fcp.js} +5 -5
- package/dist/migration-worker.js +4 -4
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/{project-embedding-registry-m3fp1pa4.js → project-embedding-registry-8je0xg18.js} +7 -5
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-xv9f0wgb.js → read-session-chunk-j4hjc1pk.js} +4 -4
- package/dist/{recomp-orchestrator-dgyb394j.js → recomp-orchestrator-ps1c8c5h.js} +19 -18
- package/dist/{render-d014e603.js → render-nfj7280n.js} +13 -13
- package/dist/{search-9gceftb9.js → search-3r8b0jfa.js} +15 -15
- package/dist/{search-archive-gybn6q7s.js → search-archive-1etwnve4.js} +6 -6
- package/dist/shared/model-suggestion-retry.d.ts +18 -0
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- package/dist/{storage-tags-f1ftvjpw.js → storage-tags-nh2ftqhx.js} +3 -3
- package/dist/{store-n4yz3n66.js → store-019k3ek7.js} +2 -2
- package/dist/{store-reader-nf8z86n9.js → store-reader-a2v34xnh.js} +1 -1
- package/dist/{task-config-qt6n4bxm.js → task-config-vrebjxyy.js} +2 -1
- package/dist/{transform-postprocess-phase-34k1zwsy.js → transform-postprocess-phase-tqp968w4.js} +20 -19
- package/dist/v2/auto-search-worker.js +4 -4
- package/dist/v2/chunk-embedding-write-worker.js +6 -6
- package/dist/v2/{compartment-chunk-embedding-knt2468v.js → compartment-chunk-embedding-w7ht0t9v.js} +3 -3
- package/dist/v2/{context-8bzydxfy.js → context-d57v8c10.js} +753 -253
- package/dist/v2/{embedding-backfill-0ar1bm97.js → embedding-backfill-95m72gxa.js} +6 -6
- package/dist/v2/embedding-worker.js +3 -3
- package/dist/v2/fold/native-replay-v3.d.ts.map +1 -1
- package/dist/v2/fold/native-replay.d.ts +11 -2
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/hidden-child-native.d.ts +1 -1
- package/dist/v2/hidden-child-native.d.ts.map +1 -1
- package/dist/v2/hidden-child-record.d.ts +11 -2
- package/dist/v2/hidden-child-record.d.ts.map +1 -1
- package/dist/v2/hidden-child-sweep.d.ts +3 -0
- package/dist/v2/hidden-child-sweep.d.ts.map +1 -1
- package/dist/v2/hidden-completion.d.ts +4 -0
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/hidden-run-holder.d.ts +2 -2
- package/dist/v2/hidden-run-holder.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts +2 -2
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/hidden-child.d.ts +2 -0
- package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
- package/dist/v2/hooks/revert-message-state.d.ts +19 -1
- package/dist/v2/hooks/revert-message-state.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-b07r9cjv.js → message-index-bounded-2nhbwry6.js} +5 -5
- package/dist/v2/migration-worker.js +4 -4
- package/dist/v2/{project-embedding-registry-gx2waee8.js → project-embedding-registry-fcxf4qht.js} +7 -5
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-38wdy8nd.js → read-session-chunk-jrrhwxgx.js} +4 -4
- package/dist/v2/{recomp-orchestrator-wq7gbkqa.js → recomp-orchestrator-n79hdd7n.js} +19 -18
- package/dist/v2/{render-2dan17xc.js → render-7emcjdt1.js} +13 -13
- package/dist/v2/{search-archive-89hdy0a2.js → search-archive-fpjbmxcx.js} +6 -6
- package/dist/v2/{search-nyqykx7q.js → search-vz2cpgr0.js} +14 -14
- package/dist/v2/{server-ytqps2xa.js → server-0h875f56.js} +1 -1
- package/dist/v2/server-3gz9k20t.js +63 -0
- package/dist/v2/{server-ta4h0fch.js → server-3z8rhacq.js} +9 -9
- package/dist/v2/{server-dtcwkdqj.js → server-4axv6kq6.js} +63 -23
- package/dist/v2/{server-c7awk5s2.js → server-4bfk1sky.js} +3 -3
- package/dist/v2/{server-dgjqvpgd.js → server-72k2r3kt.js} +19 -7
- package/dist/v2/{server-pjk9spbf.js → server-7e89a2kf.js} +1 -1
- package/dist/v2/{server-add0j5n3.js → server-8ps3717t.js} +3 -3
- package/dist/v2/{server-a85j3kam.js → server-8r32etq0.js} +1 -1
- package/dist/v2/{server-f7tzvmzs.js → server-b4efn08m.js} +1 -1
- package/dist/v2/{server-y17r5ryz.js → server-barj0mjz.js} +2 -2
- package/dist/v2/{server-yx0nyj1q.js → server-hgfd6c3e.js} +3 -3
- package/dist/v2/{server-qyazxy92.js → server-j9cm1czj.js} +14 -2
- package/dist/v2/{server-9n2qgk29.js → server-kwsqytwj.js} +2 -2
- package/dist/v2/{server-fb5hvvfc.js → server-n431vzn5.js} +3 -3
- package/dist/v2/{server-2kswss3d.js → server-n5wn7d9b.js} +48 -60
- package/dist/v2/{server-x6fn9x8q.js → server-ps6zrzwj.js} +1 -1
- package/dist/v2/{server-pmws7we9.js → server-q104czn6.js} +2 -2
- package/dist/v2/{server-vy0beygw.js → server-q2ap5cty.js} +3 -3
- package/dist/v2/{server-y8xjr8rx.js → server-qb3s0mnc.js} +12 -1
- package/dist/v2/{server-stjy5dxv.js → server-qntmqaca.js} +1 -1
- package/dist/v2/{server-09h2vyvs.js → server-r4816kwv.js} +5 -5
- package/dist/v2/{server-b0a9h3ds.js → server-vfa7byfa.js} +5 -5
- package/dist/v2/{server-tj65pgvg.js → server-vsqmkvxc.js} +32 -5
- package/dist/v2/{server-fn4ky6mn.js → server-xmgvy3cq.js} +1 -1
- package/dist/v2/server.js +4 -3
- package/dist/v2/{storage-tags-pmw33chf.js → storage-tags-t0f9njdp.js} +3 -3
- package/dist/v2/{store-y56y034s.js → store-q3ef5rvz.js} +2 -2
- package/dist/v2/{store-reader-2vhx33n6.js → store-reader-wc01y2rc.js} +1 -1
- package/dist/v2/store-reader.d.ts +2 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{task-config-ex2vajr2.js → task-config-4nqq2s0w.js} +2 -1
- package/dist/v2/{v2-archive-reader-gh1jghf7.js → v2-archive-reader-9p84yzk5.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-2h7ayss9.js → wrapup-orchestrator-acebazx8.js} +19 -18
- package/dist/{v2-archive-reader-8158kyfd.js → v2-archive-reader-w1bbaqe8.js} +1 -1
- package/dist/{wrapup-orchestrator-ct59br0c.js → wrapup-orchestrator-fwbe0mvm.js} +20 -19
- package/package.json +1 -1
- package/src/config/index.test.ts +58 -0
- package/src/config/index.ts +4 -1
- package/src/config/migrate-dreamer-v2.ts +42 -0
- package/src/shared/model-suggestion-retry.test.ts +37 -0
- package/src/shared/model-suggestion-retry.ts +38 -4
- package/src/shared/startup-maintenance-policy.test.ts +11 -6
- package/dist/index-ksdyrrav.js +0 -52
- package/dist/v2/server-0s95v3en.js +0 -49
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveLegacyConfigSources,
|
|
8
8
|
getProtectedTokensTierOverrides,
|
|
9
9
|
loadPluginConfigDetailed
|
|
10
|
-
} from "./server-
|
|
10
|
+
} from "./server-vsqmkvxc.js";
|
|
11
11
|
import {
|
|
12
12
|
getHarness2,
|
|
13
13
|
harnessOwnsOpenCodeStore2
|
|
@@ -53,6 +53,25 @@ import {
|
|
|
53
53
|
getSdkOutputLimit,
|
|
54
54
|
getModelsDevCacheState
|
|
55
55
|
} from "./server-96nm9vk4.js";
|
|
56
|
+
import {
|
|
57
|
+
COMPACTION_ENABLED_PATH,
|
|
58
|
+
isDreamerRunnable,
|
|
59
|
+
isSmartNoteSurfaceAvailable,
|
|
60
|
+
isCompactionEnabled,
|
|
61
|
+
CANONICAL_DREAM_TASKS,
|
|
62
|
+
MIN_POOL_TO_CLASSIFY,
|
|
63
|
+
DREAM_TASK_CAPABILITIES,
|
|
64
|
+
toolLoopDreamTasks,
|
|
65
|
+
formatUnsupportedDreamTasks,
|
|
66
|
+
formatDreamTaskBacklogs,
|
|
67
|
+
processedDreamTaskItems,
|
|
68
|
+
PROJECT_MEMORY_DREAM_TASKS,
|
|
69
|
+
dreamTaskAllowedBySettings,
|
|
70
|
+
leaseKindFor,
|
|
71
|
+
leaseKeyFor,
|
|
72
|
+
isCanonicalDreamTask,
|
|
73
|
+
compareTaskOrder
|
|
74
|
+
} from "./server-n5wn7d9b.js";
|
|
56
75
|
import {
|
|
57
76
|
string,
|
|
58
77
|
number,
|
|
@@ -75,25 +94,6 @@ import {
|
|
|
75
94
|
DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
76
95
|
DREAM_TASK_PROMOTION_DEFAULTS
|
|
77
96
|
} from "./server-rz6g5xne.js";
|
|
78
|
-
import {
|
|
79
|
-
CANONICAL_DREAM_TASKS,
|
|
80
|
-
MIN_POOL_TO_CLASSIFY,
|
|
81
|
-
DREAM_TASK_CAPABILITIES,
|
|
82
|
-
toolLoopDreamTasks,
|
|
83
|
-
formatUnsupportedDreamTasks,
|
|
84
|
-
formatDreamTaskBacklogs,
|
|
85
|
-
processedDreamTaskItems,
|
|
86
|
-
PROJECT_MEMORY_DREAM_TASKS,
|
|
87
|
-
dreamTaskAllowedBySettings,
|
|
88
|
-
leaseKindFor,
|
|
89
|
-
leaseKeyFor,
|
|
90
|
-
isCanonicalDreamTask,
|
|
91
|
-
compareTaskOrder,
|
|
92
|
-
buildDreamTaskRuntimeConfigs2,
|
|
93
|
-
userMemoryCollectionEnabled2,
|
|
94
|
-
userObservationCollectionEnabled2,
|
|
95
|
-
userObservationsRequested2
|
|
96
|
-
} from "./server-2kswss3d.js";
|
|
97
97
|
import {
|
|
98
98
|
historianRunConfig,
|
|
99
99
|
dreamerRunConfig,
|
|
@@ -139,6 +139,7 @@ import {
|
|
|
139
139
|
hiddenToolLoop,
|
|
140
140
|
HIDDEN_RUN_DISPOSED_REASON,
|
|
141
141
|
noteChildOfDisposedInstance,
|
|
142
|
+
noteTimedOutHiddenChild,
|
|
142
143
|
hiddenChildPermissions,
|
|
143
144
|
registerHiddenChildAgents,
|
|
144
145
|
hiddenToolCallRefusal,
|
|
@@ -152,6 +153,8 @@ import {
|
|
|
152
153
|
toModelEntry,
|
|
153
154
|
hiddenModelCooldowns,
|
|
154
155
|
ModelProducedNoOutputError,
|
|
156
|
+
promptTransportBudget,
|
|
157
|
+
notePromptSetupTimeout,
|
|
155
158
|
noteModelActivityMonitored,
|
|
156
159
|
noteModelOutputReceived,
|
|
157
160
|
isPromptTimeoutError,
|
|
@@ -243,7 +246,7 @@ import {
|
|
|
243
246
|
startCompartmentAgent,
|
|
244
247
|
setRecompStarting2,
|
|
245
248
|
setRecompTerminal2
|
|
246
|
-
} from "./server-
|
|
249
|
+
} from "./server-4axv6kq6.js";
|
|
247
250
|
import {
|
|
248
251
|
embedPauseBySession,
|
|
249
252
|
embedRunStateBySession,
|
|
@@ -259,13 +262,14 @@ import {
|
|
|
259
262
|
textMentionsRecentCommit,
|
|
260
263
|
hasMeaningfulUserText2,
|
|
261
264
|
extractTexts2,
|
|
265
|
+
hasCompletedToolCall,
|
|
262
266
|
extractToolCallSummaries,
|
|
263
267
|
getTokenizerNativeMemoryStats,
|
|
264
268
|
preloadTokenizer,
|
|
265
269
|
estimateTokens,
|
|
266
270
|
estimateFixedPromptTokens,
|
|
267
271
|
normalizeText
|
|
268
|
-
} from "./server-
|
|
272
|
+
} from "./server-qb3s0mnc.js";
|
|
269
273
|
import {
|
|
270
274
|
SubcClient,
|
|
271
275
|
connectionFileExists,
|
|
@@ -273,7 +277,7 @@ import {
|
|
|
273
277
|
toSynapseLaneDescriptor,
|
|
274
278
|
formatSynapseLaneDescriptor,
|
|
275
279
|
SynapseEmbeddingProvider
|
|
276
|
-
} from "./server-
|
|
280
|
+
} from "./server-ps6zrzwj.js";
|
|
277
281
|
import {
|
|
278
282
|
inRootAsyncContext2,
|
|
279
283
|
getTagIdentityWriteGeneration2,
|
|
@@ -306,7 +310,7 @@ import {
|
|
|
306
310
|
import"./server-ds8vpfkr.js";
|
|
307
311
|
import {
|
|
308
312
|
deleteChunkEmbedBackoffForSession2
|
|
309
|
-
} from "./server-
|
|
313
|
+
} from "./server-barj0mjz.js";
|
|
310
314
|
import {
|
|
311
315
|
acquireCompartmentLease,
|
|
312
316
|
releaseCompartmentLeaseBestEffort,
|
|
@@ -426,12 +430,12 @@ import {
|
|
|
426
430
|
saveSourceContent,
|
|
427
431
|
replaceSourceContent,
|
|
428
432
|
getSourceContents
|
|
429
|
-
} from "./server-
|
|
433
|
+
} from "./server-r4816kwv.js";
|
|
430
434
|
import {
|
|
431
435
|
cleanSearchText,
|
|
432
436
|
matchedSearchSnippet,
|
|
433
437
|
getLastIndexedOrdinal
|
|
434
|
-
} from "./server-
|
|
438
|
+
} from "./server-kwsqytwj.js";
|
|
435
439
|
import {
|
|
436
440
|
ensureSessionMetaRow,
|
|
437
441
|
clearCachedM0M1,
|
|
@@ -687,7 +691,7 @@ import {
|
|
|
687
691
|
adoptNullOwnerToolTag2,
|
|
688
692
|
getCandidateToolOwners2,
|
|
689
693
|
pickNearestPriorOwner2
|
|
690
|
-
} from "./server-
|
|
694
|
+
} from "./server-q104czn6.js";
|
|
691
695
|
import {
|
|
692
696
|
BoundedSessionMap,
|
|
693
697
|
getTableColumnNames,
|
|
@@ -701,10 +705,16 @@ import {
|
|
|
701
705
|
freezeTemporalDecisions,
|
|
702
706
|
tagRevisionKey,
|
|
703
707
|
tagIdentityRevisionKey
|
|
704
|
-
} from "./server-
|
|
708
|
+
} from "./server-qntmqaca.js";
|
|
705
709
|
import {
|
|
706
710
|
resolveHistorianModel2
|
|
707
711
|
} from "./server-5kym00ag.js";
|
|
712
|
+
import {
|
|
713
|
+
buildDreamTaskRuntimeConfigs2,
|
|
714
|
+
userMemoryCollectionEnabled2,
|
|
715
|
+
userObservationCollectionEnabled2,
|
|
716
|
+
userObservationsRequested2
|
|
717
|
+
} from "./server-3gz9k20t.js";
|
|
708
718
|
import {
|
|
709
719
|
formatFailClosedBlockingMessage,
|
|
710
720
|
formatFailClosedBlockingSummary,
|
|
@@ -794,7 +804,7 @@ import {
|
|
|
794
804
|
readRawSessionMessageOrdinalById2,
|
|
795
805
|
readSessionChunk2,
|
|
796
806
|
readRawSessionSeedTail2
|
|
797
|
-
} from "./server-
|
|
807
|
+
} from "./server-4bfk1sky.js";
|
|
798
808
|
import {
|
|
799
809
|
getMessageIndexEpoch,
|
|
800
810
|
isMessageIndexSearchable,
|
|
@@ -820,7 +830,7 @@ import {
|
|
|
820
830
|
resolveMemoriesByIdsForSearch2,
|
|
821
831
|
unifiedSearch2,
|
|
822
832
|
formatSearchResults2
|
|
823
|
-
} from "./server-
|
|
833
|
+
} from "./server-3z8rhacq.js";
|
|
824
834
|
import {
|
|
825
835
|
startBootDeadline,
|
|
826
836
|
getUnconfirmedMigrationHolders,
|
|
@@ -836,7 +846,7 @@ import {
|
|
|
836
846
|
openDatabaseAsync,
|
|
837
847
|
isDatabasePersisted,
|
|
838
848
|
getDatabasePersistenceError
|
|
839
|
-
} from "./server-
|
|
849
|
+
} from "./server-n431vzn5.js";
|
|
840
850
|
import {
|
|
841
851
|
V2_MEMORY_CATEGORIES,
|
|
842
852
|
CATEGORY_PRIORITY
|
|
@@ -849,13 +859,13 @@ import {
|
|
|
849
859
|
resolveStoredPathWorkspaceIdentity,
|
|
850
860
|
storedPathBelongsToWorkspace,
|
|
851
861
|
computeWorkspaceEpochFingerprint
|
|
852
|
-
} from "./server-
|
|
862
|
+
} from "./server-8r32etq0.js";
|
|
853
863
|
import {
|
|
854
864
|
gaDatabasePath2,
|
|
855
865
|
RAW_MESSAGE_TYPES2,
|
|
856
866
|
V2StoreReaderPool2,
|
|
857
867
|
V2StoreReader2
|
|
858
|
-
} from "./server-
|
|
868
|
+
} from "./server-j9cm1czj.js";
|
|
859
869
|
import {
|
|
860
870
|
configureContextDatabasePragmas2
|
|
861
871
|
} from "./server-fb3zxn06.js";
|
|
@@ -884,7 +894,7 @@ import {
|
|
|
884
894
|
createPrimer,
|
|
885
895
|
updatePrimerSupport,
|
|
886
896
|
updatePrimerAnswer
|
|
887
|
-
} from "./server-
|
|
897
|
+
} from "./server-xmgvy3cq.js";
|
|
888
898
|
import {
|
|
889
899
|
deriveTriggerBudget2,
|
|
890
900
|
deriveHistorianChunkTokens2,
|
|
@@ -911,13 +921,14 @@ import {
|
|
|
911
921
|
getProjectEmbeddingSnapshot2,
|
|
912
922
|
embedTextForProject2,
|
|
913
923
|
embedBatchForProject2,
|
|
924
|
+
countUnembeddedMemoriesForProject2,
|
|
914
925
|
embedUnembeddedMemoriesForProject2,
|
|
915
926
|
embedUnembeddedMemoriesForProjectOutcome2,
|
|
916
927
|
drainCommitBacklogForProject2,
|
|
917
928
|
embedSessionCompartmentChunks2,
|
|
918
929
|
getEmbeddingCoverageStatus2,
|
|
919
930
|
getAutoEmbeddingSessionCoverage2
|
|
920
|
-
} from "./server-
|
|
931
|
+
} from "./server-72k2r3kt.js";
|
|
921
932
|
import {
|
|
922
933
|
GIT_SWEEP_LEASE_RENEWAL_MS,
|
|
923
934
|
acquireGitSweepLease,
|
|
@@ -937,7 +948,7 @@ import {
|
|
|
937
948
|
getCachedLocalEmbeddingPooling,
|
|
938
949
|
preflightLocalEmbeddingPooling,
|
|
939
950
|
getLocalEmbeddingNativeMemoryStats
|
|
940
|
-
} from "./server-
|
|
951
|
+
} from "./server-7e89a2kf.js";
|
|
941
952
|
import {
|
|
942
953
|
renderUserFacingFailure,
|
|
943
954
|
userFacingFailureCode,
|
|
@@ -957,8 +968,8 @@ import {
|
|
|
957
968
|
readGitFileChangeTimesSince,
|
|
958
969
|
verificationFileExists,
|
|
959
970
|
normalizeVerificationFiles
|
|
960
|
-
} from "./server-
|
|
961
|
-
import"./server-
|
|
971
|
+
} from "./server-8ps3717t.js";
|
|
972
|
+
import"./server-b4efn08m.js";
|
|
962
973
|
import {
|
|
963
974
|
computeCueContentHash,
|
|
964
975
|
hasMuralCueColumns,
|
|
@@ -1024,7 +1035,7 @@ import {
|
|
|
1024
1035
|
readV2RawMessagePagesForConversion2,
|
|
1025
1036
|
createV2RawMessageReader2,
|
|
1026
1037
|
createV2RawMessageProvider2
|
|
1027
|
-
} from "./server-
|
|
1038
|
+
} from "./server-0h875f56.js";
|
|
1028
1039
|
import {
|
|
1029
1040
|
resolvePromptContext2
|
|
1030
1041
|
} from "./server-fmsr7v69.js";
|
|
@@ -1032,14 +1043,14 @@ import {
|
|
|
1032
1043
|
renderMessageByOrdinal2,
|
|
1033
1044
|
renderVerboseRangeForTool2,
|
|
1034
1045
|
renderItemByTag2
|
|
1035
|
-
} from "./server-
|
|
1046
|
+
} from "./server-hgfd6c3e.js";
|
|
1036
1047
|
import"./server-52x68mj4.js";
|
|
1037
1048
|
import {
|
|
1038
1049
|
readV2ArchiveOffThread2
|
|
1039
|
-
} from "./server-
|
|
1050
|
+
} from "./server-vfa7byfa.js";
|
|
1040
1051
|
import {
|
|
1041
1052
|
renderSearchArchiveOffThread2
|
|
1042
|
-
} from "./server-
|
|
1053
|
+
} from "./server-q2ap5cty.js";
|
|
1043
1054
|
import {
|
|
1044
1055
|
markHostInstructionRow,
|
|
1045
1056
|
hostInstructionRow,
|
|
@@ -1053,12 +1064,6 @@ import {
|
|
|
1053
1064
|
import {
|
|
1054
1065
|
compareSemverCore
|
|
1055
1066
|
} from "./server-84w6rvvf.js";
|
|
1056
|
-
import {
|
|
1057
|
-
COMPACTION_ENABLED_PATH,
|
|
1058
|
-
isDreamerRunnable,
|
|
1059
|
-
isSmartNoteSurfaceAvailable,
|
|
1060
|
-
isCompactionEnabled
|
|
1061
|
-
} from "./server-0s95v3en.js";
|
|
1062
1067
|
import {
|
|
1063
1068
|
__toESM,
|
|
1064
1069
|
__export
|
|
@@ -3384,6 +3389,49 @@ function dropCompartmentsAfter(db, sessionId, anchor, holderId, activeBranch = f
|
|
|
3384
3389
|
}
|
|
3385
3390
|
function repairMissingHistoryBoundary(args) {
|
|
3386
3391
|
const { db, sessionId, isInHostStore, scope = "store" } = args;
|
|
3392
|
+
const removed = args.removedByCommittedRevert;
|
|
3393
|
+
if (removed) {
|
|
3394
|
+
const firstRemoved = removed.values().next().value;
|
|
3395
|
+
if (firstRemoved === undefined)
|
|
3396
|
+
return { kind: "intact" };
|
|
3397
|
+
const busy = {
|
|
3398
|
+
kind: "unresolved",
|
|
3399
|
+
reason: "busy",
|
|
3400
|
+
missingEndMessageId: firstRemoved
|
|
3401
|
+
};
|
|
3402
|
+
const holderId = crypto.randomUUID();
|
|
3403
|
+
if (getActiveCompartmentRun(sessionId) || !acquireCompartmentLease(db, sessionId, holderId))
|
|
3404
|
+
return busy;
|
|
3405
|
+
try {
|
|
3406
|
+
const boundaries = readStoreBoundaries(db, sessionId);
|
|
3407
|
+
const first = boundaries.findIndex(({ endMessageId }) => removed.has(endMessageId));
|
|
3408
|
+
const affected = boundaries[first];
|
|
3409
|
+
if (!affected)
|
|
3410
|
+
return { kind: "intact" };
|
|
3411
|
+
const previous = boundaries[first - 1];
|
|
3412
|
+
let anchor = null;
|
|
3413
|
+
if (previous) {
|
|
3414
|
+
const row = db.prepare("SELECT end_message AS endMessage FROM compartments WHERE session_id = ? AND sequence = ?").get(sessionId, previous.sequence);
|
|
3415
|
+
if (!row)
|
|
3416
|
+
return busy;
|
|
3417
|
+
anchor = { ...previous, endMessage: row.endMessage };
|
|
3418
|
+
}
|
|
3419
|
+
const dropped = dropCompartmentsAfter(db, sessionId, anchor, holderId, false, () => args.onRetire?.(boundaries.slice(first), anchor));
|
|
3420
|
+
if (dropped === null)
|
|
3421
|
+
return busy;
|
|
3422
|
+
invalidateAutoEmbedSession(sessionId);
|
|
3423
|
+
forgetCachedPrefix(sessionId);
|
|
3424
|
+
sessionLog2(sessionId, `committed revert history repair: removed compartments ${dropped.join(",")} and cleared the cached history; removed boundary ${affected.endMessageId}`);
|
|
3425
|
+
return {
|
|
3426
|
+
kind: "repaired",
|
|
3427
|
+
missingEndMessageId: affected.endMessageId,
|
|
3428
|
+
anchorEndMessageId: anchor?.endMessageId ?? "",
|
|
3429
|
+
droppedSequences: dropped
|
|
3430
|
+
};
|
|
3431
|
+
} finally {
|
|
3432
|
+
releaseCompartmentLeaseBestEffort(db, sessionId, holderId);
|
|
3433
|
+
}
|
|
3434
|
+
}
|
|
3387
3435
|
const compartments = scope === "active-branch" ? db.prepare("SELECT sequence, COALESCE(end_message_id, '') AS endMessageId FROM compartments WHERE session_id = ? ORDER BY sequence").all(sessionId) : readStoreBoundaries(db, sessionId);
|
|
3388
3436
|
let latestIndex = compartments.length - 1;
|
|
3389
3437
|
while (latestIndex >= 0 && !compartments[latestIndex]?.endMessageId)
|
|
@@ -14449,7 +14497,7 @@ async function drainSingleStoreEmbeddingWatermarks(db) {
|
|
|
14449
14497
|
let outcome = await embedUnembeddedMemoriesForProjectOutcome2(db, watermark.project_path);
|
|
14450
14498
|
if (outcome.kind === "embedded") {
|
|
14451
14499
|
embedded += outcome.count;
|
|
14452
|
-
if (
|
|
14500
|
+
if (countUnembeddedMemoriesForProject2(db, watermark.project_path) === 0) {
|
|
14453
14501
|
outcome = await embedUnembeddedMemoriesForProjectOutcome2(db, watermark.project_path);
|
|
14454
14502
|
if (outcome.kind === "embedded")
|
|
14455
14503
|
embedded += outcome.count;
|
|
@@ -14467,13 +14515,6 @@ async function drainSingleStoreEmbeddingWatermarks(db) {
|
|
|
14467
14515
|
}
|
|
14468
14516
|
return embedded;
|
|
14469
14517
|
}
|
|
14470
|
-
function countUnembeddedBelow(db, projectPath) {
|
|
14471
|
-
const row = db.prepare(`SELECT COUNT(*) AS count FROM memories
|
|
14472
|
-
WHERE project_path = ?
|
|
14473
|
-
AND status IN ('active', 'permanent')
|
|
14474
|
-
AND NOT EXISTS (SELECT 1 FROM memory_embeddings WHERE memory_id = memories.id)`).get(projectPath);
|
|
14475
|
-
return typeof row?.count === "number" ? row.count : 0;
|
|
14476
|
-
}
|
|
14477
14518
|
function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
14478
14519
|
db.prepare(`UPDATE memory_embedding_watermarks
|
|
14479
14520
|
SET embedded_memory_id = MAX(embedded_memory_id, ?),
|
|
@@ -14614,6 +14655,8 @@ function describeError2(error) {
|
|
|
14614
14655
|
function failureCode(error, aborted) {
|
|
14615
14656
|
if (aborted)
|
|
14616
14657
|
return "aborted";
|
|
14658
|
+
if (error instanceof HiddenCompletionRefusal)
|
|
14659
|
+
return "local_refusal";
|
|
14617
14660
|
const text = describeError2(error).toLowerCase();
|
|
14618
14661
|
if (text.includes("all models exhausted") || text.includes("all fallback models failed")) {
|
|
14619
14662
|
return "chain_exhausted";
|
|
@@ -26437,7 +26480,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26437
26480
|
const buildManagedCtx = async (db) => {
|
|
26438
26481
|
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-hr4qqrnv.js"));
|
|
26439
26482
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
|
|
26440
|
-
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-
|
|
26483
|
+
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-4nqq2s0w.js"));
|
|
26441
26484
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
26442
26485
|
const runConfig = historianRunConfig(config, currentPluginConfigReader(directory)?.poll().effective ?? config);
|
|
26443
26486
|
const historianModel = resolveHistorianModel(runConfig, "opencode");
|
|
@@ -26487,7 +26530,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26487
26530
|
const db = readDatabase();
|
|
26488
26531
|
if (!db)
|
|
26489
26532
|
return { ok: false, error: "db unavailable" };
|
|
26490
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
26533
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-n79hdd7n.js"));
|
|
26491
26534
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-zazaxxpf.js"));
|
|
26492
26535
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
26493
26536
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -26572,7 +26615,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26572
26615
|
const db = readDatabase();
|
|
26573
26616
|
if (!db)
|
|
26574
26617
|
return { ok: false, error: "db unavailable" };
|
|
26575
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
26618
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-acebazx8.js"));
|
|
26576
26619
|
const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
|
|
26577
26620
|
const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
|
|
26578
26621
|
if (!window)
|
|
@@ -28916,7 +28959,13 @@ function importedFloor(reader, sessionID, through = reader.latestSequence(sessio
|
|
|
28916
28959
|
let after = -1;
|
|
28917
28960
|
let found;
|
|
28918
28961
|
while (true) {
|
|
28919
|
-
const page = reader.page(sessionID, {
|
|
28962
|
+
const page = reader.page(sessionID, {
|
|
28963
|
+
after,
|
|
28964
|
+
through,
|
|
28965
|
+
type: "compaction",
|
|
28966
|
+
limit: 1000,
|
|
28967
|
+
preferTypeIndex: true
|
|
28968
|
+
});
|
|
28920
28969
|
if (!page.rows.length)
|
|
28921
28970
|
break;
|
|
28922
28971
|
for (const row of page.rows) {
|
|
@@ -29202,15 +29251,33 @@ class NativeFoldReplay {
|
|
|
29202
29251
|
this.options.log?.(sessionID, `v3 host fold: ${reason}`);
|
|
29203
29252
|
} catch {}
|
|
29204
29253
|
}
|
|
29254
|
+
historyCoverage(sessionID, reader) {
|
|
29255
|
+
if (!this.options.rendersHistory?.(sessionID))
|
|
29256
|
+
return;
|
|
29257
|
+
const db = this.storage.db;
|
|
29258
|
+
const cached = db.prepare("SELECT cached_m0_last_baseline_end_message_id AS id, cached_m0_bytes IS NOT NULL AS hasBytes FROM session_meta WHERE session_id=?").get(sessionID);
|
|
29259
|
+
const id = cached?.hasBytes ? cached.id : getLastCompartmentEndMessageId(db, sessionID);
|
|
29260
|
+
const after = id ? reader.sequenceForId(sessionID, id) : (reader.earliestSequence(sessionID) ?? 0) - 1;
|
|
29261
|
+
return after === undefined ? undefined : { id, after };
|
|
29262
|
+
}
|
|
29263
|
+
floorCovered(sessionID, floor, coverage, record) {
|
|
29264
|
+
if (!coverage || floor.kind === "start" || floor.kind === "host-checkpoint" && !record?.withoutRecentContext && this.options.servesHostCheckpoint?.(sessionID, floor.id) || floor.after <= coverage.after)
|
|
29265
|
+
return true;
|
|
29266
|
+
this.options.onUncoveredFloor?.(sessionID, floor, coverage);
|
|
29267
|
+
return false;
|
|
29268
|
+
}
|
|
29205
29269
|
async floorState(sessionID, reader, boundary, served, preferCapture = false) {
|
|
29270
|
+
const coverage = this.historyCoverage(sessionID, reader);
|
|
29206
29271
|
const retained = this.tail(sessionID)?.replay;
|
|
29207
29272
|
const controlsKnown = (replay) => replay.controls.every((control) => !control.after || reader.sequenceForId(sessionID, control.after) !== undefined);
|
|
29208
|
-
const memory = retained && validReplayState(retained) && controlsKnown(retained) && validFloor(reader, sessionID, retained.floor) ? retained : undefined;
|
|
29273
|
+
const memory = retained && validReplayState(retained) && controlsKnown(retained) && validFloor(reader, sessionID, retained.floor) && this.floorCovered(sessionID, retained.floor, coverage, retained) ? retained : undefined;
|
|
29209
29274
|
const cut = reader.latestCompaction(sessionID);
|
|
29210
29275
|
const saved = await this.readV3(sessionID);
|
|
29211
|
-
const durable = saved && saved.proof.sourceDigest === foldDigest(reader.hostIdentity()) && (!cut || saved.proof.admissionID === cut.id) && controlsKnown(saved.replay) && validFloor(reader, sessionID, saved.replay.floor) ? saved.replay : undefined;
|
|
29212
|
-
const
|
|
29213
|
-
const
|
|
29276
|
+
const durable = saved && saved.proof.sourceDigest === foldDigest(reader.hostIdentity()) && (!cut || saved.proof.admissionID === cut.id) && controlsKnown(saved.replay) && validFloor(reader, sessionID, saved.replay.floor) && this.floorCovered(sessionID, saved.replay.floor, coverage, saved.replay) ? saved.replay : undefined;
|
|
29277
|
+
const marker = importedFloor(reader, sessionID, cut?.seq);
|
|
29278
|
+
const imported = marker && this.floorCovered(sessionID, marker, coverage) ? marker : undefined;
|
|
29279
|
+
const capturedRecord = await this.readCapturedReplay(sessionID, reader);
|
|
29280
|
+
const captured = capturedRecord && this.floorCovered(sessionID, capturedRecord.floor, coverage, capturedRecord) ? capturedRecord : undefined;
|
|
29214
29281
|
const existing = preferCapture ? captured ?? memory ?? durable : memory ?? durable ?? captured;
|
|
29215
29282
|
if (preferCapture && !existing && !served)
|
|
29216
29283
|
return;
|
|
@@ -29517,6 +29584,8 @@ ${cached}
|
|
|
29517
29584
|
await this.retainReplay(sessionID, replay, this.tail(sessionID)?.model ?? "", cut.seq - 1);
|
|
29518
29585
|
return false;
|
|
29519
29586
|
}
|
|
29587
|
+
if (!this.floorCovered(sessionID, replay.floor, this.historyCoverage(sessionID, reader), replay))
|
|
29588
|
+
return false;
|
|
29520
29589
|
await this.retainReplay(sessionID, saved.replay, this.tail(sessionID)?.model ?? "", cut.seq - 1);
|
|
29521
29590
|
if (proof.historyDigest !== historyDigest(reader, sessionID, cut.seq - 1, saved.replay.floor.after)) {
|
|
29522
29591
|
this.staleHeads.add(sessionID);
|
|
@@ -29611,7 +29680,7 @@ ${cached}
|
|
|
29611
29680
|
return "legacy";
|
|
29612
29681
|
if (saved.proof.admissionID !== cut.id)
|
|
29613
29682
|
return "legacy";
|
|
29614
|
-
return saved.proof.sourceDigest === foldDigest(reader.hostIdentity()) && saved.proof.summaryDigest === foldDigest(cut.data.summary ?? "") && validFloor(reader, sessionID, saved.replay.floor) && saved.proof.historyDigest === historyDigest(reader, sessionID, cut.seq - 1, saved.replay.floor.after) ? "native" : undefined;
|
|
29683
|
+
return saved.proof.sourceDigest === foldDigest(reader.hostIdentity()) && saved.proof.summaryDigest === foldDigest(cut.data.summary ?? "") && validFloor(reader, sessionID, saved.replay.floor) && this.floorCovered(sessionID, saved.replay.floor, this.historyCoverage(sessionID, reader), saved.replay) && saved.proof.historyDigest === historyDigest(reader, sessionID, cut.seq - 1, saved.replay.floor.after) ? "native" : undefined;
|
|
29615
29684
|
}
|
|
29616
29685
|
if (!isLocalCheckpoint(cut) || cut.session_id !== sessionID)
|
|
29617
29686
|
return;
|
|
@@ -29778,7 +29847,7 @@ ${cached}
|
|
|
29778
29847
|
}
|
|
29779
29848
|
return [...grouped].map(([row, messages]) => this.record(row, messages));
|
|
29780
29849
|
}
|
|
29781
|
-
async capture(draft, native, boundary) {
|
|
29850
|
+
async capture(draft, native, boundary, restoredFirstRow) {
|
|
29782
29851
|
const release = this.storage.hold(draft.sessionID);
|
|
29783
29852
|
let replay;
|
|
29784
29853
|
let sourceSeq = -1;
|
|
@@ -29788,6 +29857,11 @@ ${cached}
|
|
|
29788
29857
|
try {
|
|
29789
29858
|
if (this.options.protocol === 3) {
|
|
29790
29859
|
replay = await this.floorState(draft.sessionID, reader, boundary, draft);
|
|
29860
|
+
if (!replay && restoredFirstRow) {
|
|
29861
|
+
const first = reader.page(draft.sessionID, { limit: 1 }).rows[0];
|
|
29862
|
+
if (first?.id === restoredFirstRow)
|
|
29863
|
+
replay = { floor: floorFor(first, "start"), controls: [] };
|
|
29864
|
+
}
|
|
29791
29865
|
if (!replay)
|
|
29792
29866
|
throw new NativeReplayUnavailable("No usable host replay boundary");
|
|
29793
29867
|
replay = { ...replay, blocked: false };
|
|
@@ -29855,7 +29929,7 @@ ${cached}
|
|
|
29855
29929
|
await this.saveCapturedReplay(draft.sessionID, replay, reader);
|
|
29856
29930
|
const saved = await this.readV3(draft.sessionID);
|
|
29857
29931
|
const cut = reader.latestCompaction(draft.sessionID);
|
|
29858
|
-
if (saved && !this.editedAdmissions.has(draft.sessionID) && cut?.id === saved.proof.admissionID && replay.floor.after > saved.replay.floor.after && boundary && this.servedBaseline(draft) === boundary.summary) {
|
|
29932
|
+
if (saved && !this.editedAdmissions.has(draft.sessionID) && cut?.id === saved.proof.admissionID && (replay.floor.after > saved.replay.floor.after || !this.floorCovered(draft.sessionID, saved.replay.floor, this.historyCoverage(draft.sessionID, reader), saved.replay)) && (boundary && this.servedBaseline(draft) === boundary.summary || replay.floor.kind === "start" && restoredFirstRow === replay.floor.id)) {
|
|
29859
29933
|
const value = {
|
|
29860
29934
|
...saved,
|
|
29861
29935
|
replay: {
|
|
@@ -30106,11 +30180,12 @@ ${cached}
|
|
|
30106
30180
|
}
|
|
30107
30181
|
const through = cut.seq - 1;
|
|
30108
30182
|
let metadata = this.metadata.get(sessionID);
|
|
30109
|
-
if (!metadata || (this.metadataThrough.get(sessionID) ?? -1) < through) {
|
|
30183
|
+
if (!metadata || (this.metadataThrough.get(sessionID) ?? -1) < through || this.options.protocol === 3 && this.options.rendersHistory?.(sessionID) && (this.metadataAfter.get(sessionID) ?? -1) > after) {
|
|
30110
30184
|
reader ??= this.openReader(sessionID);
|
|
30111
30185
|
metadata = reader.rowStampsThrough(sessionID, through, this.options.protocol === 3 ? after : undefined).filter(conversational);
|
|
30112
30186
|
this.metadata.set(sessionID, metadata);
|
|
30113
30187
|
this.metadataThrough.set(sessionID, through);
|
|
30188
|
+
this.metadataAfter.set(sessionID, this.options.protocol === 3 ? after : undefined);
|
|
30114
30189
|
}
|
|
30115
30190
|
const required = metadata.filter((row) => row.seq > after && row.seq <= through);
|
|
30116
30191
|
if (this.dirty.has(sessionID) || !tail || (this.loaded.get(sessionID) ?? -1) < through && !this.storage.admission(sessionID, cut.id) || !this.storage.containsRows(sessionID, required.map((row) => row.id))) {
|
|
@@ -30612,6 +30687,10 @@ var SWEEP_BUDGET_MS = 30000;
|
|
|
30612
30687
|
function recordHiddenChild(db, child) {
|
|
30613
30688
|
db.prepare("INSERT INTO schema_migrations_meta (key, value) VALUES (?, ?)").run(`${PREFIX}${child.id}`, JSON.stringify(child));
|
|
30614
30689
|
}
|
|
30690
|
+
function recordRetiringHiddenChild(db, child) {
|
|
30691
|
+
db.prepare(`INSERT INTO schema_migrations_meta (key, value) VALUES (?, ?)
|
|
30692
|
+
ON CONFLICT(key) DO UPDATE SET value = json_set(value, '$.retiring', json('true'))`).run(`${PREFIX}${child.id}`, JSON.stringify({ ...child, retiring: true }));
|
|
30693
|
+
}
|
|
30615
30694
|
function forgetHiddenChild(db, id) {
|
|
30616
30695
|
db.prepare("DELETE FROM schema_migrations_meta WHERE key = ?").run(`${PREFIX}${id}`);
|
|
30617
30696
|
}
|
|
@@ -30718,6 +30797,20 @@ function isSessionNotFound(error) {
|
|
|
30718
30797
|
function createNativeHiddenChildren(host, removeSession, options) {
|
|
30719
30798
|
const quiet = supportsQuietHiddenChildren(options.hostVersion);
|
|
30720
30799
|
const removing = new Map;
|
|
30800
|
+
const removeBounded = async (id, timeoutMs = options.removalTimeoutMs ?? 5000) => {
|
|
30801
|
+
let timer;
|
|
30802
|
+
try {
|
|
30803
|
+
await Promise.race([
|
|
30804
|
+
removeSession({ sessionID: id }),
|
|
30805
|
+
new Promise((_, reject) => {
|
|
30806
|
+
timer = setTimeout(() => reject(new Error("session.remove timed out")), timeoutMs);
|
|
30807
|
+
})
|
|
30808
|
+
]);
|
|
30809
|
+
} finally {
|
|
30810
|
+
if (timer)
|
|
30811
|
+
clearTimeout(timer);
|
|
30812
|
+
}
|
|
30813
|
+
};
|
|
30721
30814
|
const remove = (child) => {
|
|
30722
30815
|
const inFlight = removing.get(child.id);
|
|
30723
30816
|
if (inFlight)
|
|
@@ -30725,18 +30818,7 @@ function createNativeHiddenChildren(host, removeSession, options) {
|
|
|
30725
30818
|
options.log(`[magic-context] hidden child ${child.id} removing`);
|
|
30726
30819
|
const done = (async () => {
|
|
30727
30820
|
try {
|
|
30728
|
-
|
|
30729
|
-
try {
|
|
30730
|
-
await Promise.race([
|
|
30731
|
-
removeSession({ sessionID: child.id }),
|
|
30732
|
-
new Promise((_, reject) => {
|
|
30733
|
-
timer = setTimeout(() => reject(new Error("session.remove timed out")), options.removalTimeoutMs ?? 5000);
|
|
30734
|
-
})
|
|
30735
|
-
]);
|
|
30736
|
-
} finally {
|
|
30737
|
-
if (timer)
|
|
30738
|
-
clearTimeout(timer);
|
|
30739
|
-
}
|
|
30821
|
+
await removeBounded(child.id);
|
|
30740
30822
|
forgetHiddenChild(options.db, child.id);
|
|
30741
30823
|
options.log(`[magic-context] hidden child ${child.id} removed`);
|
|
30742
30824
|
} catch (error) {
|
|
@@ -30757,18 +30839,52 @@ function createNativeHiddenChildren(host, removeSession, options) {
|
|
|
30757
30839
|
removing.set(child.id, done);
|
|
30758
30840
|
return done;
|
|
30759
30841
|
};
|
|
30760
|
-
const
|
|
30842
|
+
const retireLate = async (id, directory, createdAt, cleanupMs) => {
|
|
30843
|
+
noteTimedOutHiddenChild(id);
|
|
30844
|
+
liveChildren.delete(id);
|
|
30845
|
+
try {
|
|
30846
|
+
recordRetiringHiddenChild(options.db, { id, directory, created_at: createdAt });
|
|
30847
|
+
} catch (error) {
|
|
30848
|
+
const kind = error instanceof Error ? error.constructor.name : typeof error;
|
|
30849
|
+
options.log(`[magic-context] late hidden child ${id} record failed (${kind})`);
|
|
30850
|
+
}
|
|
30851
|
+
try {
|
|
30852
|
+
await removeBounded(id, cleanupMs);
|
|
30853
|
+
} catch (error) {
|
|
30854
|
+
if (!isSessionNotFound(error)) {
|
|
30855
|
+
options.log(`[magic-context] late hidden child ${id} could not be removed`);
|
|
30856
|
+
return;
|
|
30857
|
+
}
|
|
30858
|
+
}
|
|
30859
|
+
try {
|
|
30860
|
+
forgetHiddenChild(options.db, id);
|
|
30861
|
+
} catch {}
|
|
30862
|
+
};
|
|
30863
|
+
const create = async (identity, role, model, budget) => {
|
|
30761
30864
|
const input = childCreateInput(identity, role, model);
|
|
30762
30865
|
const directory = identity.directory;
|
|
30763
30866
|
if (quiet) {
|
|
30764
30867
|
if (!host.createHolder)
|
|
30765
30868
|
throw new Error("OpenCode 2 background holder API is not wired");
|
|
30766
|
-
const placement = await hiddenRunPlacement(host.createHolder, directory);
|
|
30869
|
+
const placement = await hiddenRunPlacement(host.createHolder, directory, budget);
|
|
30767
30870
|
input.id = placement.id;
|
|
30768
30871
|
input.parentID = placement.parentID;
|
|
30769
30872
|
delete input.location;
|
|
30770
30873
|
}
|
|
30771
|
-
|
|
30874
|
+
budget?.setStage("creating the child session");
|
|
30875
|
+
const start = () => host.create(input);
|
|
30876
|
+
const removeLate = ({ id }) => {
|
|
30877
|
+
if (!id || !budget)
|
|
30878
|
+
return;
|
|
30879
|
+
retireLate(id, directory, Date.now(), budget.cleanupMs);
|
|
30880
|
+
};
|
|
30881
|
+
const created = await (budget?.work(start, removeLate) ?? start());
|
|
30882
|
+
try {
|
|
30883
|
+
budget?.check();
|
|
30884
|
+
} catch (error) {
|
|
30885
|
+
removeLate(created);
|
|
30886
|
+
throw error;
|
|
30887
|
+
}
|
|
30772
30888
|
if (!created.id)
|
|
30773
30889
|
throw new Error("OpenCode 2 did not return a child session id");
|
|
30774
30890
|
const createdAt = Date.now();
|
|
@@ -30783,20 +30899,12 @@ function createNativeHiddenChildren(host, removeSession, options) {
|
|
|
30783
30899
|
});
|
|
30784
30900
|
} catch (storeError) {
|
|
30785
30901
|
let removed = false;
|
|
30786
|
-
let timer;
|
|
30787
30902
|
try {
|
|
30788
|
-
await
|
|
30789
|
-
removeSession({ sessionID: created.id }),
|
|
30790
|
-
new Promise((_, reject) => {
|
|
30791
|
-
timer = setTimeout(() => reject(new Error("session.remove timed out")), options.removalTimeoutMs ?? 5000);
|
|
30792
|
-
})
|
|
30793
|
-
]);
|
|
30903
|
+
await removeBounded(created.id);
|
|
30794
30904
|
removed = true;
|
|
30795
30905
|
} catch (error) {
|
|
30796
30906
|
removed = isSessionNotFound(error);
|
|
30797
30907
|
} finally {
|
|
30798
|
-
if (timer)
|
|
30799
|
-
clearTimeout(timer);
|
|
30800
30908
|
liveChildren.delete(created.id);
|
|
30801
30909
|
}
|
|
30802
30910
|
options.log(`[magic-context] hidden child ${created.id} record failed; removed=${removed}: ${errorText(storeError)}`);
|
|
@@ -30824,6 +30932,9 @@ function createNativeHiddenChildren(host, removeSession, options) {
|
|
|
30824
30932
|
return {
|
|
30825
30933
|
open: create,
|
|
30826
30934
|
create,
|
|
30935
|
+
retireLate(child, cleanupMs) {
|
|
30936
|
+
retireLate(child.id, child.directory ?? "", child.created_at, cleanupMs);
|
|
30937
|
+
},
|
|
30827
30938
|
retire(child) {
|
|
30828
30939
|
if (kept(child)) {
|
|
30829
30940
|
liveChildren.delete(child.id);
|
|
@@ -31027,17 +31138,83 @@ function subagentTemperature(model, metadata, temperature, log) {
|
|
|
31027
31138
|
|
|
31028
31139
|
// src/v2/hidden-completion.ts
|
|
31029
31140
|
var DEFAULT_DISPOSE_DRAIN_MS = 2000;
|
|
31141
|
+
|
|
31142
|
+
class HiddenWorkTimeout extends Error {
|
|
31143
|
+
constructor(timeoutMs) {
|
|
31144
|
+
super(`prompt timed out after ${timeoutMs}ms`);
|
|
31145
|
+
}
|
|
31146
|
+
}
|
|
31147
|
+
|
|
31148
|
+
class HiddenSetupTimeout extends HiddenCompletionRefusal {
|
|
31149
|
+
constructor(stage) {
|
|
31150
|
+
super("hidden_setup_timeout", `Hidden completion setup timed out while ${stage}`, true);
|
|
31151
|
+
}
|
|
31152
|
+
}
|
|
31153
|
+
|
|
31154
|
+
class HiddenWorkAborted extends Error {
|
|
31155
|
+
constructor() {
|
|
31156
|
+
super("Hidden completion prompt aborted");
|
|
31157
|
+
}
|
|
31158
|
+
}
|
|
31159
|
+
function setupBudget(deadline, timeout, signal) {
|
|
31160
|
+
let stage = "preparing the attempt";
|
|
31161
|
+
let lost;
|
|
31162
|
+
const check = () => {
|
|
31163
|
+
if (lost)
|
|
31164
|
+
throw lost;
|
|
31165
|
+
if (Date.now() >= deadline)
|
|
31166
|
+
throw lost = timeout(stage);
|
|
31167
|
+
if (signal?.aborted)
|
|
31168
|
+
throw lost = new HiddenWorkAborted;
|
|
31169
|
+
};
|
|
31170
|
+
return {
|
|
31171
|
+
check,
|
|
31172
|
+
setStage: (value) => {
|
|
31173
|
+
stage = value;
|
|
31174
|
+
},
|
|
31175
|
+
get stage() {
|
|
31176
|
+
return stage;
|
|
31177
|
+
},
|
|
31178
|
+
cleanupMs: DEFAULT_DISPOSE_DRAIN_MS,
|
|
31179
|
+
async work(start, onLate) {
|
|
31180
|
+
check();
|
|
31181
|
+
let timer;
|
|
31182
|
+
let abort;
|
|
31183
|
+
try {
|
|
31184
|
+
return await Promise.race([
|
|
31185
|
+
start().then((result) => {
|
|
31186
|
+
try {
|
|
31187
|
+
check();
|
|
31188
|
+
} catch (error) {
|
|
31189
|
+
onLate?.(result);
|
|
31190
|
+
throw error;
|
|
31191
|
+
}
|
|
31192
|
+
return result;
|
|
31193
|
+
}),
|
|
31194
|
+
new Promise((_, reject) => {
|
|
31195
|
+
timer = setTimeout(() => reject(lost ??= timeout(stage)), Math.max(0, deadline - Date.now()));
|
|
31196
|
+
abort = () => reject(lost ??= new HiddenWorkAborted);
|
|
31197
|
+
if (signal?.aborted)
|
|
31198
|
+
abort();
|
|
31199
|
+
else
|
|
31200
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
31201
|
+
})
|
|
31202
|
+
]);
|
|
31203
|
+
} finally {
|
|
31204
|
+
clearTimeout(timer);
|
|
31205
|
+
if (abort)
|
|
31206
|
+
signal?.removeEventListener("abort", abort);
|
|
31207
|
+
}
|
|
31208
|
+
}
|
|
31209
|
+
};
|
|
31210
|
+
}
|
|
31030
31211
|
async function settleWithin(work, ms) {
|
|
31031
31212
|
let timer;
|
|
31032
31213
|
try {
|
|
31033
|
-
await Promise.race([
|
|
31034
|
-
work.then(() =>
|
|
31035
|
-
return;
|
|
31036
|
-
}, () => {
|
|
31037
|
-
return;
|
|
31038
|
-
}),
|
|
31214
|
+
return await Promise.race([
|
|
31215
|
+
work.then(() => true, () => true),
|
|
31039
31216
|
new Promise((resolve) => {
|
|
31040
|
-
timer = setTimeout(resolve, Math.max(0, ms));
|
|
31217
|
+
timer = setTimeout(() => resolve(false), Math.max(0, ms));
|
|
31041
31218
|
})
|
|
31042
31219
|
]);
|
|
31043
31220
|
} finally {
|
|
@@ -31234,8 +31411,9 @@ function isProviderFailure(error) {
|
|
|
31234
31411
|
const type = error.type;
|
|
31235
31412
|
return typeof type === "string" && (type.startsWith("provider.") || type.toLowerCase().includes("provider"));
|
|
31236
31413
|
}
|
|
31237
|
-
async function awaitAssistantRow(openReader, readSessionError, localFailure, childID, afterSeq, deadline, signal) {
|
|
31414
|
+
async function awaitAssistantRow(openReader, readSessionError, localFailure, childID, afterSeq, deadline, signal, checkDeadline) {
|
|
31238
31415
|
for (;; ) {
|
|
31416
|
+
checkDeadline?.();
|
|
31239
31417
|
const refusedBefore = localFailure();
|
|
31240
31418
|
if (refusedBefore)
|
|
31241
31419
|
throw refusedBefore;
|
|
@@ -31291,9 +31469,6 @@ async function awaitAssistantRow(openReader, readSessionError, localFailure, chi
|
|
|
31291
31469
|
return { row: newAssistant };
|
|
31292
31470
|
}
|
|
31293
31471
|
}
|
|
31294
|
-
if (Date.now() >= deadline) {
|
|
31295
|
-
throw new Error("Hidden completion timed out waiting for a persisted assistant row");
|
|
31296
|
-
}
|
|
31297
31472
|
await sleepUntilPoll(signal, deadline);
|
|
31298
31473
|
}
|
|
31299
31474
|
}
|
|
@@ -31358,11 +31533,11 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31358
31533
|
};
|
|
31359
31534
|
};
|
|
31360
31535
|
const warnedVariants = new Set;
|
|
31361
|
-
const validateVariant = async (model) => {
|
|
31536
|
+
const validateVariant = async (model, work) => {
|
|
31362
31537
|
if (!model.variant || !options.modelCatalog)
|
|
31363
31538
|
return model;
|
|
31364
31539
|
try {
|
|
31365
|
-
const listed = await options.modelCatalog
|
|
31540
|
+
const listed = await work(options.modelCatalog);
|
|
31366
31541
|
const rows = Array.isArray(listed) ? listed : listed && typeof listed === "object" && Array.isArray(listed.data) ? listed.data : [];
|
|
31367
31542
|
const entry = rows.find((row) => row && typeof row === "object" && row.providerID === model.providerID && row.id === model.modelID);
|
|
31368
31543
|
if (!entry)
|
|
@@ -31375,18 +31550,21 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31375
31550
|
note(`[magic-context] ${recordHiddenVariantWarning(model.providerID, model.modelID, model.variant)}`);
|
|
31376
31551
|
}
|
|
31377
31552
|
return { providerID: model.providerID, modelID: model.modelID };
|
|
31378
|
-
} catch {
|
|
31553
|
+
} catch (error) {
|
|
31554
|
+
if (error instanceof HiddenSetupTimeout || error instanceof HiddenWorkAborted)
|
|
31555
|
+
throw error;
|
|
31379
31556
|
return model;
|
|
31380
31557
|
}
|
|
31381
31558
|
};
|
|
31382
|
-
const resolveHead = async (identity) => {
|
|
31559
|
+
const resolveHead = async (identity, work) => {
|
|
31383
31560
|
const configured = configuredHead(identity);
|
|
31384
31561
|
if (configured)
|
|
31385
|
-
return validateVariant(configured);
|
|
31386
|
-
|
|
31562
|
+
return validateVariant(configured, work);
|
|
31563
|
+
const parentSessionId = identity.parentSessionId;
|
|
31564
|
+
if (!parentSessionId) {
|
|
31387
31565
|
throw new HiddenCompletionRefusal("hidden_model_unsupported", "Hidden completion requires a configured model or an existing parent session model", true);
|
|
31388
31566
|
}
|
|
31389
|
-
const parent = await host.get({ sessionID:
|
|
31567
|
+
const parent = await work(() => host.get({ sessionID: parentSessionId }));
|
|
31390
31568
|
if (!parent.model) {
|
|
31391
31569
|
throw new HiddenCompletionRefusal("hidden_model_unsupported", "Hidden completion could not resolve the parent session model", true);
|
|
31392
31570
|
}
|
|
@@ -31396,17 +31574,18 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31396
31574
|
...parent.model.variant ? { variant: parent.model.variant } : {}
|
|
31397
31575
|
};
|
|
31398
31576
|
};
|
|
31399
|
-
const switchChildModel = async (run, requested) => {
|
|
31577
|
+
const switchChildModel = async (run, requested, setup) => {
|
|
31400
31578
|
if (sameModel(run.child.model, requested))
|
|
31401
31579
|
return;
|
|
31402
|
-
await host.switchModel({
|
|
31580
|
+
await setup.work(() => host.switchModel({
|
|
31403
31581
|
sessionID: run.child.id,
|
|
31404
31582
|
model: {
|
|
31405
31583
|
providerID: requested.providerID,
|
|
31406
31584
|
id: requested.modelID,
|
|
31407
31585
|
...requested.variant ? { variant: requested.variant } : {}
|
|
31408
31586
|
}
|
|
31409
|
-
});
|
|
31587
|
+
}));
|
|
31588
|
+
setup.check();
|
|
31410
31589
|
run.child = lifecycle.updateModel(run.child, requested);
|
|
31411
31590
|
};
|
|
31412
31591
|
const partialCompletion = (run) => {
|
|
@@ -31438,30 +31617,63 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31438
31617
|
lifecycle.retire(run.child, reason);
|
|
31439
31618
|
run.retired = true;
|
|
31440
31619
|
};
|
|
31441
|
-
const interruptAndRetire =
|
|
31442
|
-
|
|
31443
|
-
|
|
31444
|
-
|
|
31445
|
-
|
|
31446
|
-
|
|
31620
|
+
const interruptAndRetire = (run, reason) => {
|
|
31621
|
+
if (run.retired)
|
|
31622
|
+
return run.retirement ?? Promise.resolve();
|
|
31623
|
+
return run.retirement ??= (async () => {
|
|
31624
|
+
const id = run.child.id;
|
|
31625
|
+
const warn = (error) => {
|
|
31626
|
+
const kind = error instanceof Error ? error.constructor.name : typeof error;
|
|
31627
|
+
const message = `[magic-context] hidden child ${id} could not be interrupted (${kind})`;
|
|
31628
|
+
if (options.log)
|
|
31629
|
+
options.log(message);
|
|
31630
|
+
else
|
|
31631
|
+
log2(message);
|
|
31632
|
+
};
|
|
31633
|
+
try {
|
|
31634
|
+
await settleWithin(host.interrupt({ sessionID: id }).catch(warn), DEFAULT_DISPOSE_DRAIN_MS);
|
|
31635
|
+
} catch (error) {
|
|
31636
|
+
warn(error);
|
|
31637
|
+
} finally {
|
|
31638
|
+
retire(run, reason);
|
|
31639
|
+
}
|
|
31640
|
+
})();
|
|
31447
31641
|
};
|
|
31448
31642
|
return {
|
|
31449
31643
|
capabilities: V2_HIDDEN_EXECUTOR_CAPABILITIES,
|
|
31450
31644
|
async open(identity) {
|
|
31451
31645
|
if (disposed)
|
|
31452
31646
|
throw disposed;
|
|
31647
|
+
const roleWait = setupBudget(Date.now() + identity.timeoutMs, (stage) => new HiddenSetupTimeout(stage));
|
|
31648
|
+
roleWait.setStage("waiting for its role");
|
|
31453
31649
|
const role = roleFor(identity);
|
|
31454
31650
|
const releaseStore = options.holdStore?.() ?? (() => {});
|
|
31455
31651
|
let releaseRole;
|
|
31456
31652
|
let openedChild;
|
|
31457
31653
|
let opened;
|
|
31458
31654
|
try {
|
|
31459
|
-
releaseRole = await acquireRole(role);
|
|
31655
|
+
releaseRole = await roleWait.work(() => acquireRole(role), (release) => release());
|
|
31460
31656
|
if (disposed)
|
|
31461
31657
|
throw disposed;
|
|
31462
|
-
|
|
31463
|
-
const
|
|
31464
|
-
const
|
|
31658
|
+
const deadline = Date.now() + identity.timeoutMs;
|
|
31659
|
+
const setup = setupBudget(deadline, (stage) => new HiddenSetupTimeout(stage));
|
|
31660
|
+
const work = setup.work;
|
|
31661
|
+
const ensureAgent = options.ensureAgent;
|
|
31662
|
+
if (ensureAgent) {
|
|
31663
|
+
setup.setStage("reloading the hidden agent");
|
|
31664
|
+
let pending;
|
|
31665
|
+
try {
|
|
31666
|
+
await work(() => pending = ensureAgent.call(options));
|
|
31667
|
+
} catch (error) {
|
|
31668
|
+
if (pending)
|
|
31669
|
+
options.forgetAgent?.(pending);
|
|
31670
|
+
throw error;
|
|
31671
|
+
}
|
|
31672
|
+
}
|
|
31673
|
+
setup.setStage("resolving the hidden model");
|
|
31674
|
+
const head = await resolveHead(identity, work);
|
|
31675
|
+
setup.setStage("creating the child session");
|
|
31676
|
+
const active = await work(() => lifecycle.open(identity, role, head, setup), (child) => lifecycle.retireLate(child, setup.cleanupMs));
|
|
31465
31677
|
openedChild = active;
|
|
31466
31678
|
const configuredModel = toModelEntry(identity.model);
|
|
31467
31679
|
const handle = {
|
|
@@ -31478,6 +31690,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31478
31690
|
child: active,
|
|
31479
31691
|
releaseRole,
|
|
31480
31692
|
releaseStore,
|
|
31693
|
+
firstDeadline: deadline,
|
|
31481
31694
|
failed: false,
|
|
31482
31695
|
unsettledFailure: false,
|
|
31483
31696
|
retired: false
|
|
@@ -31487,15 +31700,23 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31487
31700
|
openRuns.add(run);
|
|
31488
31701
|
if (disposed)
|
|
31489
31702
|
noteChildOfDisposedInstance(active.id);
|
|
31490
|
-
|
|
31703
|
+
setup.setStage("switching the child model");
|
|
31704
|
+
await switchChildModel(run, head, setup);
|
|
31705
|
+
setup.check();
|
|
31491
31706
|
return handle;
|
|
31492
31707
|
} catch (error) {
|
|
31493
|
-
|
|
31494
|
-
|
|
31495
|
-
|
|
31496
|
-
|
|
31497
|
-
|
|
31498
|
-
|
|
31708
|
+
try {
|
|
31709
|
+
if (openedChild) {
|
|
31710
|
+
if (error instanceof HiddenSetupTimeout)
|
|
31711
|
+
noteTimedOutHiddenChild(openedChild.id);
|
|
31712
|
+
lifecycle.retire(openedChild, "hidden-run-open-failed");
|
|
31713
|
+
}
|
|
31714
|
+
} finally {
|
|
31715
|
+
if (opened)
|
|
31716
|
+
openRuns.delete(opened);
|
|
31717
|
+
releaseRole?.();
|
|
31718
|
+
releaseStore();
|
|
31719
|
+
}
|
|
31499
31720
|
throw error;
|
|
31500
31721
|
}
|
|
31501
31722
|
},
|
|
@@ -31504,6 +31725,35 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31504
31725
|
const run = runs.get(handle);
|
|
31505
31726
|
if (!run)
|
|
31506
31727
|
throw new Error("Unknown hidden completion run");
|
|
31728
|
+
const timeoutMs = run.identity.timeoutMs;
|
|
31729
|
+
const deadline = run.firstDeadline ?? startedAt + timeoutMs;
|
|
31730
|
+
run.firstDeadline = undefined;
|
|
31731
|
+
let dispatched = false;
|
|
31732
|
+
const setup = setupBudget(deadline, (stage) => dispatched ? new HiddenWorkTimeout(timeoutMs) : new HiddenSetupTimeout(stage), request.signal);
|
|
31733
|
+
const work = setup.work;
|
|
31734
|
+
const sharedBudget = promptTransportBudget(request.signal);
|
|
31735
|
+
const refuseSliver = () => {
|
|
31736
|
+
const now = Date.now();
|
|
31737
|
+
if (deadline - now < timeoutMs * 0.05 || sharedBudget && sharedBudget.deadline - now < sharedBudget.timeoutMs * 0.05)
|
|
31738
|
+
throw new HiddenSetupTimeout("preparing to send the prompt");
|
|
31739
|
+
};
|
|
31740
|
+
const retireFailedSetup = (error) => {
|
|
31741
|
+
if (error instanceof HiddenSetupTimeout) {
|
|
31742
|
+
run.deadlineExpired = true;
|
|
31743
|
+
noteTimedOutHiddenChild(run.child.id);
|
|
31744
|
+
}
|
|
31745
|
+
run.failed = true;
|
|
31746
|
+
run.unsettledFailure = true;
|
|
31747
|
+
if (!run.retirement)
|
|
31748
|
+
retire(run, "hidden-attempt-setup-cancelled");
|
|
31749
|
+
};
|
|
31750
|
+
const stopWithinWork = async (reason) => {
|
|
31751
|
+
const retirement = interruptAndRetire(run, reason);
|
|
31752
|
+
if (Date.now() < deadline)
|
|
31753
|
+
await settleWithin(retirement, deadline - Date.now());
|
|
31754
|
+
if (Date.now() >= deadline)
|
|
31755
|
+
run.deadlineExpired = true;
|
|
31756
|
+
};
|
|
31507
31757
|
const refuseDisposed = () => {
|
|
31508
31758
|
if (!disposed)
|
|
31509
31759
|
return;
|
|
@@ -31514,46 +31764,78 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31514
31764
|
};
|
|
31515
31765
|
refuseDisposed();
|
|
31516
31766
|
if (request.signal?.aborted) {
|
|
31517
|
-
await
|
|
31767
|
+
await stopWithinWork("aborted-before-prompt");
|
|
31518
31768
|
throw new Error("Hidden completion prompt aborted");
|
|
31519
31769
|
}
|
|
31520
|
-
|
|
31521
|
-
|
|
31522
|
-
|
|
31523
|
-
|
|
31524
|
-
|
|
31525
|
-
|
|
31526
|
-
|
|
31527
|
-
|
|
31528
|
-
|
|
31529
|
-
|
|
31530
|
-
|
|
31531
|
-
|
|
31532
|
-
|
|
31533
|
-
|
|
31534
|
-
|
|
31535
|
-
|
|
31536
|
-
|
|
31537
|
-
|
|
31538
|
-
|
|
31539
|
-
|
|
31540
|
-
|
|
31541
|
-
|
|
31542
|
-
|
|
31543
|
-
|
|
31544
|
-
|
|
31545
|
-
|
|
31546
|
-
|
|
31547
|
-
|
|
31548
|
-
|
|
31549
|
-
|
|
31550
|
-
|
|
31551
|
-
|
|
31552
|
-
|
|
31553
|
-
|
|
31554
|
-
|
|
31770
|
+
let requested;
|
|
31771
|
+
let requestedRef;
|
|
31772
|
+
notePromptSetupTimeout(request.signal, () => new HiddenSetupTimeout(setup.stage));
|
|
31773
|
+
try {
|
|
31774
|
+
const previousRetirement = run.retirement;
|
|
31775
|
+
setup.setStage("waiting for the previous child to retire");
|
|
31776
|
+
if (previousRetirement)
|
|
31777
|
+
await work(() => previousRetirement);
|
|
31778
|
+
setup.setStage("resolving the hidden model");
|
|
31779
|
+
requested = await validateVariant(requestModel(request, run.child.model), work);
|
|
31780
|
+
requestedRef = modelKey(requested);
|
|
31781
|
+
const configuredModel = [
|
|
31782
|
+
run.identity.model,
|
|
31783
|
+
...run.identity.configuredModels ?? []
|
|
31784
|
+
].map(toModelEntry).find((entry) => entry?.model === requestedRef);
|
|
31785
|
+
handle.attemptedModel = requestedRef;
|
|
31786
|
+
handle.modelConfigKey = configuredModel?.sourceConfigKey ?? handle.modelConfigKey;
|
|
31787
|
+
if (run.identity.kind !== "dreamer-task" && request.body.temperature === undefined) {
|
|
31788
|
+
const configured = options.historianTemperature?.();
|
|
31789
|
+
if (typeof configured === "number" && Number.isFinite(configured))
|
|
31790
|
+
request = {
|
|
31791
|
+
...request,
|
|
31792
|
+
body: { ...request.body, temperature: configured }
|
|
31793
|
+
};
|
|
31794
|
+
}
|
|
31795
|
+
if (typeof request.body.temperature === "number") {
|
|
31796
|
+
let metadata;
|
|
31797
|
+
try {
|
|
31798
|
+
const listed = options.modelCatalog ? await work(options.modelCatalog) : undefined;
|
|
31799
|
+
const rows = Array.isArray(listed) ? listed : listed?.data;
|
|
31800
|
+
metadata = rows?.find((row) => row?.providerID === requested.providerID && (row?.id === requested.modelID || row?.modelID === requested.modelID));
|
|
31801
|
+
} catch (error) {
|
|
31802
|
+
if (error instanceof HiddenSetupTimeout || error instanceof HiddenWorkAborted)
|
|
31803
|
+
throw error;
|
|
31804
|
+
}
|
|
31805
|
+
const temperature = subagentTemperature(modelKey(requested), metadata, request.body.temperature, (message) => note(message));
|
|
31806
|
+
const body = { ...request.body };
|
|
31807
|
+
if (temperature === undefined)
|
|
31808
|
+
delete body.temperature;
|
|
31809
|
+
else
|
|
31810
|
+
body.temperature = temperature;
|
|
31811
|
+
request = { ...request, body };
|
|
31812
|
+
}
|
|
31813
|
+
if (needsBlockedRead(run.identity.agent, run.child.model.providerID) !== needsBlockedRead(run.identity.agent, requested.providerID)) {
|
|
31814
|
+
retire(run, "hidden-run-tool-surface-changed");
|
|
31815
|
+
}
|
|
31816
|
+
if (run.retired) {
|
|
31817
|
+
setup.setStage("creating the replacement child session");
|
|
31818
|
+
run.child = await work(() => lifecycle.create(run.identity, run.role, requested, setup), (child) => lifecycle.retireLate(child, setup.cleanupMs));
|
|
31819
|
+
run.retirement = undefined;
|
|
31820
|
+
run.deadlineExpired = false;
|
|
31821
|
+
run.failed = false;
|
|
31822
|
+
run.unsettledFailure = false;
|
|
31823
|
+
run.retired = false;
|
|
31824
|
+
handle.id = run.child.id;
|
|
31825
|
+
handle.childSessionId = run.child.id;
|
|
31826
|
+
}
|
|
31827
|
+
setup.setStage("switching the child model");
|
|
31828
|
+
await switchChildModel(run, requested, setup);
|
|
31829
|
+
setup.check();
|
|
31830
|
+
setup.setStage("preparing to send the prompt");
|
|
31831
|
+
refuseSliver();
|
|
31832
|
+
} catch (error) {
|
|
31833
|
+
if (error instanceof HiddenSetupTimeout || error instanceof HiddenWorkAborted)
|
|
31834
|
+
retireFailedSetup(error);
|
|
31835
|
+
throw error;
|
|
31836
|
+
} finally {
|
|
31837
|
+
notePromptSetupTimeout(request.signal);
|
|
31555
31838
|
}
|
|
31556
|
-
await switchChildModel(run, requested);
|
|
31557
31839
|
refuseDisposed();
|
|
31558
31840
|
const baseline = withReader(options.openReader, (reader) => reader.latestSequence(run.child.id));
|
|
31559
31841
|
const marker = `mc:hidden:${crypto.randomUUID()}:${crypto.randomUUID()}`;
|
|
@@ -31568,7 +31850,6 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31568
31850
|
run.partialCompletion = undefined;
|
|
31569
31851
|
run.attempt = { child: attempt, baseline };
|
|
31570
31852
|
options.hook.registerAttempt(marker, attempt);
|
|
31571
|
-
const deadline = Date.now() + run.identity.timeoutMs;
|
|
31572
31853
|
lifecycle.extendDeadline(run.child, deadline);
|
|
31573
31854
|
const budget = run.budget;
|
|
31574
31855
|
if (budget?.snapshot().finalizeFired) {
|
|
@@ -31627,6 +31908,8 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31627
31908
|
});
|
|
31628
31909
|
const onAbort = () => {
|
|
31629
31910
|
const reason = request.signal?.reason;
|
|
31911
|
+
if (dispatched)
|
|
31912
|
+
noteTimedOutHiddenChild(run.child.id);
|
|
31630
31913
|
if (reason instanceof ModelProducedNoOutputError && run.identity.kind === "dreamer-task") {
|
|
31631
31914
|
recordChildInvocation({
|
|
31632
31915
|
db: options.db,
|
|
@@ -31644,9 +31927,6 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31644
31927
|
}
|
|
31645
31928
|
interruptAndRetire(run, "prompt-aborted").finally(() => abortReject(new Error("Hidden completion prompt aborted")));
|
|
31646
31929
|
};
|
|
31647
|
-
const deadlineTimer = setTimeout(() => {
|
|
31648
|
-
interruptAndRetire(run, "prompt-timeout").finally(() => abortReject(new Error("Hidden completion prompt timed out")));
|
|
31649
|
-
}, Math.max(0, deadline - Date.now()));
|
|
31650
31930
|
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
31651
31931
|
let settle;
|
|
31652
31932
|
const entry = {
|
|
@@ -31655,8 +31935,6 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31655
31935
|
noteChildOfDisposedInstance(run.child.id);
|
|
31656
31936
|
try {
|
|
31657
31937
|
await interruptAndRetire(run, "plugin-instance-disposed");
|
|
31658
|
-
} catch (error) {
|
|
31659
|
-
note(`[magic-context] hidden child ${run.child.id} could not be interrupted on dispose: ${errorText(error)}`);
|
|
31660
31938
|
} finally {
|
|
31661
31939
|
abortReject(refusal);
|
|
31662
31940
|
}
|
|
@@ -31675,28 +31953,32 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31675
31953
|
noteModelActivityMonitored(request.signal);
|
|
31676
31954
|
try {
|
|
31677
31955
|
await Promise.race([
|
|
31678
|
-
|
|
31956
|
+
work(() => {
|
|
31957
|
+
refuseSliver();
|
|
31958
|
+
dispatched = true;
|
|
31959
|
+
return host.prompt({ sessionID: run.child.id, text: marker });
|
|
31960
|
+
}),
|
|
31679
31961
|
aborted,
|
|
31680
31962
|
...budget ? [budgetStopped] : []
|
|
31681
31963
|
]);
|
|
31682
31964
|
await Promise.race([
|
|
31683
|
-
host.wait({ sessionID: run.child.id }),
|
|
31965
|
+
work(() => host.wait({ sessionID: run.child.id })),
|
|
31684
31966
|
aborted,
|
|
31685
31967
|
...budget ? [budgetStopped] : []
|
|
31686
31968
|
]);
|
|
31687
31969
|
const { row, outputLimit } = await Promise.race([
|
|
31688
|
-
awaitAssistantRow(options.openReader, async () => {
|
|
31970
|
+
work(() => awaitAssistantRow(options.openReader, async () => {
|
|
31689
31971
|
try {
|
|
31690
|
-
const
|
|
31691
|
-
|
|
31692
|
-
});
|
|
31972
|
+
const id = run.child.id;
|
|
31973
|
+
const terminalError = host.terminalError;
|
|
31974
|
+
const eventError = terminalError ? await work(() => terminalError.call(host, { sessionID: id })) : undefined;
|
|
31693
31975
|
if (eventError !== undefined)
|
|
31694
31976
|
return eventError;
|
|
31695
|
-
return (await host.get({ sessionID:
|
|
31977
|
+
return (await work(() => host.get({ sessionID: id }))).error;
|
|
31696
31978
|
} catch {
|
|
31697
31979
|
return;
|
|
31698
31980
|
}
|
|
31699
|
-
}, () => attempt.refusal ?? attempt.stepLimit, run.child.id, baseline, deadline, request.signal),
|
|
31981
|
+
}, () => attempt.refusal ?? attempt.stepLimit, run.child.id, baseline, deadline, request.signal, setup.check)),
|
|
31700
31982
|
aborted,
|
|
31701
31983
|
...budget ? [budgetStopped] : []
|
|
31702
31984
|
]);
|
|
@@ -31712,15 +31994,17 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31712
31994
|
const steps = attemptRows.filter((step) => step.type === "assistant" && step.seq > baseline && step.seq <= row.seq);
|
|
31713
31995
|
const exceeded = chargeBudgetRows(steps);
|
|
31714
31996
|
if (exceeded) {
|
|
31715
|
-
await
|
|
31997
|
+
await stopWithinWork("token-budget");
|
|
31716
31998
|
throw exceeded;
|
|
31717
31999
|
}
|
|
31718
32000
|
const cappedChainStart = outputLimit ? outputLimitChainStart(attemptRows, row.seq) : row.seq;
|
|
31719
32001
|
const usageRows = cappedChainStart < row.seq ? steps.filter((step) => step.seq < cappedChainStart || step.seq === row.seq) : steps;
|
|
31720
32002
|
const reportedUsage = usageRows.some((step) => tokenNumber(step.data.tokens?.input) !== undefined || tokenNumber(step.data.tokens?.output) !== undefined);
|
|
31721
32003
|
const usage = sumRowUsage(usageRows);
|
|
31722
|
-
if (
|
|
31723
|
-
|
|
32004
|
+
if (Date.now() >= deadline)
|
|
32005
|
+
throw new HiddenWorkTimeout(timeoutMs);
|
|
32006
|
+
if (request.signal?.aborted || run.retired) {
|
|
32007
|
+
await stopWithinWork("prompt-aborted-or-timeout");
|
|
31724
32008
|
throw new Error(request.signal?.aborted ? "Hidden completion prompt aborted" : "Hidden completion prompt timed out");
|
|
31725
32009
|
}
|
|
31726
32010
|
run.completion = {
|
|
@@ -31749,17 +32033,25 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31749
32033
|
if (!(error instanceof HiddenProviderError)) {
|
|
31750
32034
|
run.unsettledFailure = true;
|
|
31751
32035
|
}
|
|
31752
|
-
|
|
31753
|
-
|
|
31754
|
-
|
|
31755
|
-
|
|
32036
|
+
const dispatchedTimeout = dispatched && isPromptTimeoutError(error);
|
|
32037
|
+
if (error instanceof HiddenSetupTimeout) {
|
|
32038
|
+
retireFailedSetup(error);
|
|
32039
|
+
} else if (dispatched && (caught instanceof HiddenWorkTimeout || Date.now() >= deadline)) {
|
|
32040
|
+
run.deadlineExpired = true;
|
|
32041
|
+
noteTimedOutHiddenChild(run.child.id);
|
|
32042
|
+
interruptAndRetire(run, "prompt-timeout");
|
|
32043
|
+
} else if (request.signal?.aborted && !run.retired) {
|
|
32044
|
+
await stopWithinWork("prompt-aborted");
|
|
32045
|
+
} else if (!run.retired && (dispatchedTimeout || error instanceof Error && error.message.includes("timed out"))) {
|
|
32046
|
+
if (dispatchedTimeout)
|
|
32047
|
+
noteTimedOutHiddenChild(run.child.id);
|
|
32048
|
+
await stopWithinWork("prompt-timeout");
|
|
31756
32049
|
} else if ((error instanceof HiddenAgentStepLimit || error instanceof HiddenProviderError && error.settled) && !run.retired) {
|
|
31757
|
-
await
|
|
32050
|
+
await stopWithinWork(error instanceof HiddenAgentStepLimit ? "hidden-run-step-limit" : "hidden-run-provider-error");
|
|
31758
32051
|
}
|
|
31759
32052
|
throw error;
|
|
31760
32053
|
} finally {
|
|
31761
32054
|
stopWatching?.();
|
|
31762
|
-
clearTimeout(deadlineTimer);
|
|
31763
32055
|
if (budgetPoll)
|
|
31764
32056
|
clearInterval(budgetPoll);
|
|
31765
32057
|
request.signal?.removeEventListener("abort", onAbort);
|
|
@@ -31786,7 +32078,18 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31786
32078
|
const run = runs.get(handle);
|
|
31787
32079
|
if (!run)
|
|
31788
32080
|
return;
|
|
32081
|
+
if (run.retirement && (!run.retired || run.deadlineExpired)) {
|
|
32082
|
+
runs.delete(handle);
|
|
32083
|
+
run.retirement.finally(() => {
|
|
32084
|
+
openRuns.delete(run);
|
|
32085
|
+
run.releaseRole();
|
|
32086
|
+
run.releaseStore();
|
|
32087
|
+
});
|
|
32088
|
+
return;
|
|
32089
|
+
}
|
|
31789
32090
|
try {
|
|
32091
|
+
if (run.retirement)
|
|
32092
|
+
await run.retirement;
|
|
31790
32093
|
const reusable = !run.retired && run.failed && !run.unsettledFailure;
|
|
31791
32094
|
if (hiddenToolLoop(run.identity)) {
|
|
31792
32095
|
retire(run, settlement.promptSettled ? "tool-loop-settled" : "tool-loop-failed");
|
|
@@ -31799,7 +32102,9 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
31799
32102
|
run.releaseRole();
|
|
31800
32103
|
run.releaseStore();
|
|
31801
32104
|
}
|
|
31802
|
-
|
|
32105
|
+
const finished = lifecycle.finish(run.child, run.retired);
|
|
32106
|
+
if (!run.deadlineExpired)
|
|
32107
|
+
await finished;
|
|
31803
32108
|
},
|
|
31804
32109
|
async dispose() {
|
|
31805
32110
|
disposed ??= new HiddenCompletionRefusal("hidden_instance_disposed", HIDDEN_RUN_DISPOSED_REASON, true);
|
|
@@ -37196,18 +37501,15 @@ ${prePost || "(none)"}
|
|
|
37196
37501
|
Return valid JSON only, no markdown fencing:
|
|
37197
37502
|
{ "answer": "..." }`;
|
|
37198
37503
|
}
|
|
37199
|
-
function
|
|
37504
|
+
function hasInvestigationEvidence(messages) {
|
|
37200
37505
|
if (!Array.isArray(messages))
|
|
37201
|
-
return
|
|
37202
|
-
|
|
37203
|
-
for (const message of messages) {
|
|
37506
|
+
return false;
|
|
37507
|
+
return messages.some((message) => {
|
|
37204
37508
|
if (message === null || typeof message !== "object")
|
|
37205
|
-
|
|
37509
|
+
return false;
|
|
37206
37510
|
const parts = message.parts;
|
|
37207
|
-
|
|
37208
|
-
|
|
37209
|
-
}
|
|
37210
|
-
return count;
|
|
37511
|
+
return Array.isArray(parts) && hasCompletedToolCall(parts);
|
|
37512
|
+
});
|
|
37211
37513
|
}
|
|
37212
37514
|
function parseAnswer(messages, fallback) {
|
|
37213
37515
|
const text = extractLatestAssistantText(messages);
|
|
@@ -37301,7 +37603,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
|
|
|
37301
37603
|
messages: run.completion.messages ?? []
|
|
37302
37604
|
});
|
|
37303
37605
|
const answer = run.validated.trim();
|
|
37304
|
-
if (!answer ||
|
|
37606
|
+
if (!answer || !hasInvestigationEvidence(run.completion.messages ?? []))
|
|
37305
37607
|
return false;
|
|
37306
37608
|
runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
|
|
37307
37609
|
updatePrimerAnswer(args.db, primer.id, answer);
|
|
@@ -37361,8 +37663,8 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
|
|
|
37361
37663
|
const answer = run.validated.trim();
|
|
37362
37664
|
if (!answer)
|
|
37363
37665
|
return false;
|
|
37364
|
-
if (
|
|
37365
|
-
log2(`[dreamer] refresh-primers: primer #${primer.id} answer not committed (no investigation tool
|
|
37666
|
+
if (!hasInvestigationEvidence(run.output)) {
|
|
37667
|
+
log2(`[dreamer] refresh-primers: primer #${primer.id} answer not committed (no successful investigation tool results)`);
|
|
37366
37668
|
return false;
|
|
37367
37669
|
}
|
|
37368
37670
|
runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
|
|
@@ -40826,8 +41128,9 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
40826
41128
|
log2(`[dreamer] domain lease busy (${leaseKey}) — deferring ${group.length} task(s)`);
|
|
40827
41129
|
for (const due of group)
|
|
40828
41130
|
cb?.onBusy?.(due.config.task);
|
|
40829
|
-
return;
|
|
41131
|
+
return 0;
|
|
40830
41132
|
}
|
|
41133
|
+
let staleSlots = 0;
|
|
40831
41134
|
try {
|
|
40832
41135
|
for (const due of [...group].sort((a, b) => compareTaskOrder(a.config.task, b.config.task))) {
|
|
40833
41136
|
if (!reacquireOwnedLease(db, holderId, leaseKey, acquisition.generation)) {
|
|
@@ -40835,6 +41138,11 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
40835
41138
|
break;
|
|
40836
41139
|
}
|
|
40837
41140
|
acquisition = { acquiredAt: Date.now(), generation: acquisition.generation };
|
|
41141
|
+
if (!cb?.ignoreSchedule && getTaskScheduleState(db, projectIdentity, due.config.task)?.nextDueAt !== due.scheduledAt) {
|
|
41142
|
+
log2(`[dreamer] ${due.config.task} slot changed (${leaseKey}) — not running`);
|
|
41143
|
+
staleSlots += 1;
|
|
41144
|
+
continue;
|
|
41145
|
+
}
|
|
40838
41146
|
if (!cb?.forceGate) {
|
|
40839
41147
|
const gatePass = evaluateTaskGate(due.config.task, {
|
|
40840
41148
|
db,
|
|
@@ -40890,6 +41198,7 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
40890
41198
|
} finally {
|
|
40891
41199
|
releaseLease(db, holderId, leaseKey);
|
|
40892
41200
|
}
|
|
41201
|
+
return staleSlots;
|
|
40893
41202
|
}
|
|
40894
41203
|
async function runManualDream(deps) {
|
|
40895
41204
|
const now = Date.now();
|
|
@@ -40956,6 +41265,7 @@ async function runManualDream(deps) {
|
|
|
40956
41265
|
groups.set(kind, arr);
|
|
40957
41266
|
}
|
|
40958
41267
|
await Promise.all([...groups.values()].map((group) => runDomainGroup({ ...deps, executor: deps.executor }, group, {
|
|
41268
|
+
ignoreSchedule: true,
|
|
40959
41269
|
forceGate,
|
|
40960
41270
|
leaseWaitMs: MANUAL_RUN_LEASE_WAIT_MS,
|
|
40961
41271
|
onRan: (t, detail, backlog) => {
|
|
@@ -41013,8 +41323,8 @@ async function runDueTasksForProject(deps) {
|
|
|
41013
41323
|
arr.push(d);
|
|
41014
41324
|
groups.set(kind, arr);
|
|
41015
41325
|
}
|
|
41016
|
-
await Promise.all([...groups.values()].map((group) => runDomainGroup(deps, group)));
|
|
41017
|
-
return gated.length;
|
|
41326
|
+
const staleSlots = await Promise.all([...groups.values()].map((group) => runDomainGroup(deps, group)));
|
|
41327
|
+
return gated.length - staleSlots.reduce((total, count) => total + count, 0);
|
|
41018
41328
|
}
|
|
41019
41329
|
|
|
41020
41330
|
// src/v2/retrospective-raw-provider.ts
|
|
@@ -42496,6 +42806,7 @@ var MAX_STAGED_SUFFIX_ROWS = 1e4;
|
|
|
42496
42806
|
class V2RevertMessageCleanup {
|
|
42497
42807
|
openStoreReader;
|
|
42498
42808
|
staged = new BoundedSessionMap(MAX_STAGED_REVERTS);
|
|
42809
|
+
pendingHistory = [];
|
|
42499
42810
|
constructor(openStoreReader) {
|
|
42500
42811
|
this.openStoreReader = openStoreReader;
|
|
42501
42812
|
}
|
|
@@ -42524,7 +42835,11 @@ class V2RevertMessageCleanup {
|
|
|
42524
42835
|
discardAllStageProofs() {
|
|
42525
42836
|
this.staged.clear();
|
|
42526
42837
|
}
|
|
42527
|
-
|
|
42838
|
+
forgetSession(sessionID) {
|
|
42839
|
+
this.discardStageProof(sessionID);
|
|
42840
|
+
this.pendingHistory = this.pendingHistory.filter((proof) => proof.sessionID !== sessionID);
|
|
42841
|
+
}
|
|
42842
|
+
pruneOnCommit(db, sessionID, to, retireHistory) {
|
|
42528
42843
|
const staged = this.staged.peek(sessionID);
|
|
42529
42844
|
this.discardStageProof(sessionID);
|
|
42530
42845
|
const noteSkippedCleanup = (reason) => {
|
|
@@ -42554,9 +42869,45 @@ class V2RevertMessageCleanup {
|
|
|
42554
42869
|
return noteSkippedCleanup("retained predecessor is not visible at commit");
|
|
42555
42870
|
if (!removed.size)
|
|
42556
42871
|
return noteSkippedCleanup("all staged rows still exist");
|
|
42872
|
+
if (retireHistory) {
|
|
42873
|
+
if (this.pendingHistory.length === MAX_STAGED_REVERTS)
|
|
42874
|
+
this.pendingHistory.shift();
|
|
42875
|
+
this.pendingHistory.push({ sessionID, host: staged.host, removed });
|
|
42876
|
+
}
|
|
42557
42877
|
pruneMessages(db, sessionID, removed);
|
|
42558
42878
|
return true;
|
|
42559
42879
|
}
|
|
42880
|
+
retireProvenHistory(db, sessionID, reader) {
|
|
42881
|
+
const ownProofs = this.pendingHistory.filter((proof) => proof.sessionID === sessionID);
|
|
42882
|
+
if (ownProofs.length === 0)
|
|
42883
|
+
return;
|
|
42884
|
+
const source = reader ?? this.openStoreReader();
|
|
42885
|
+
try {
|
|
42886
|
+
const host = source.hostIdentity();
|
|
42887
|
+
const current = ownProofs.filter((proof) => proof.host === host);
|
|
42888
|
+
this.pendingHistory = this.pendingHistory.filter((proof) => proof.sessionID !== sessionID || proof.host === host);
|
|
42889
|
+
if (current.length === 0)
|
|
42890
|
+
return;
|
|
42891
|
+
const removed = new Set;
|
|
42892
|
+
for (const proof of current)
|
|
42893
|
+
for (const id of proof.removed)
|
|
42894
|
+
removed.add(id);
|
|
42895
|
+
const result = repairMissingHistoryBoundary({
|
|
42896
|
+
db,
|
|
42897
|
+
sessionId: sessionID,
|
|
42898
|
+
isInHostStore: (id) => source.sequenceForId(sessionID, id) !== undefined,
|
|
42899
|
+
removedByCommittedRevert: removed,
|
|
42900
|
+
onRetire: () => clearRecompStaging(db, sessionID)
|
|
42901
|
+
});
|
|
42902
|
+
if (result.kind !== "unresolved") {
|
|
42903
|
+
this.pendingHistory = this.pendingHistory.filter((proof) => proof.sessionID !== sessionID);
|
|
42904
|
+
}
|
|
42905
|
+
return result.kind === "intact" ? undefined : result;
|
|
42906
|
+
} finally {
|
|
42907
|
+
if (!reader)
|
|
42908
|
+
source.close();
|
|
42909
|
+
}
|
|
42910
|
+
}
|
|
42560
42911
|
}
|
|
42561
42912
|
function pruneMessages(db, sessionID, removed) {
|
|
42562
42913
|
db.transaction(() => {
|
|
@@ -57334,9 +57685,23 @@ function servableCarrier(stored, head) {
|
|
|
57334
57685
|
}
|
|
57335
57686
|
function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
|
|
57336
57687
|
const rows = reader.instructionRowsThrough(sessionID, reader.latestSequence(sessionID));
|
|
57688
|
+
const visible = (message) => message !== incoming && !effortPart(message);
|
|
57689
|
+
const ids = new Set;
|
|
57690
|
+
for (const message of messages) {
|
|
57691
|
+
if (!visible(message))
|
|
57692
|
+
continue;
|
|
57693
|
+
const id = nativeRowID(message);
|
|
57694
|
+
if (id)
|
|
57695
|
+
ids.add(id);
|
|
57696
|
+
}
|
|
57697
|
+
const sequences = reader.sequencesForIds(sessionID, [...ids]);
|
|
57337
57698
|
let previous;
|
|
57338
57699
|
let pending = [];
|
|
57339
57700
|
const matches = (message, row) => message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row?.data.text;
|
|
57701
|
+
const bindRow = (message, row) => {
|
|
57702
|
+
bindNativeRowID(message, row.id, row.seq);
|
|
57703
|
+
sequences.set(row.id, row.seq);
|
|
57704
|
+
};
|
|
57340
57705
|
const bind = (next) => {
|
|
57341
57706
|
if (!pending.length)
|
|
57342
57707
|
return;
|
|
@@ -57346,7 +57711,7 @@ function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
|
|
|
57346
57711
|
selected.forEach((row, index) => {
|
|
57347
57712
|
const message = pending[index];
|
|
57348
57713
|
if (message)
|
|
57349
|
-
|
|
57714
|
+
bindRow(message, row);
|
|
57350
57715
|
});
|
|
57351
57716
|
} else {
|
|
57352
57717
|
const earliest = [];
|
|
@@ -57367,16 +57732,16 @@ function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
|
|
|
57367
57732
|
pending.forEach((message, index) => {
|
|
57368
57733
|
const row = candidates[earliest[index]];
|
|
57369
57734
|
if (row && earliest[index] === latest[index])
|
|
57370
|
-
|
|
57735
|
+
bindRow(message, row);
|
|
57371
57736
|
});
|
|
57372
57737
|
}
|
|
57373
57738
|
pending = [];
|
|
57374
57739
|
};
|
|
57375
57740
|
for (const message of messages) {
|
|
57376
|
-
if (
|
|
57741
|
+
if (!visible(message))
|
|
57377
57742
|
continue;
|
|
57378
57743
|
const id = nativeRowID(message);
|
|
57379
|
-
const seq = id ?
|
|
57744
|
+
const seq = id ? sequences.get(id) : undefined;
|
|
57380
57745
|
if (seq !== undefined) {
|
|
57381
57746
|
bind(seq);
|
|
57382
57747
|
previous = seq;
|
|
@@ -57517,12 +57882,16 @@ function checkHistoryBoundary(db, reader, sessionID) {
|
|
|
57517
57882
|
}
|
|
57518
57883
|
}
|
|
57519
57884
|
function newBaselineStartAfter(db, reader, sessionID, cached, compactionOff) {
|
|
57520
|
-
if (cached?.id != null
|
|
57885
|
+
if (cached?.id != null)
|
|
57521
57886
|
return;
|
|
57522
57887
|
const isSubagent = storedSubagentMode(db, sessionID);
|
|
57523
57888
|
if (isSubagent === undefined || !rendersCompartmentHistory(isSubagent, compactionOff))
|
|
57524
57889
|
return;
|
|
57890
|
+
if (cached?.hasBytes)
|
|
57891
|
+
return reader.earliestSequence(sessionID) === undefined ? undefined : null;
|
|
57525
57892
|
const newest = db.prepare("SELECT end_message_id AS id, rebase_status AS status FROM compartments WHERE session_id = ? ORDER BY sequence DESC LIMIT 1").get(sessionID);
|
|
57893
|
+
if (!newest && reader.earliestSequence(sessionID) !== undefined)
|
|
57894
|
+
return null;
|
|
57526
57895
|
if (newest?.id && newest.status !== "unresolved" && reader.sequenceForId(sessionID, newest.id) !== undefined)
|
|
57527
57896
|
return newest.id;
|
|
57528
57897
|
return;
|
|
@@ -57540,6 +57909,12 @@ async function cacheV2SessionDirectory(session, sessionID, directories) {
|
|
|
57540
57909
|
}
|
|
57541
57910
|
}
|
|
57542
57911
|
var contextPass = new AsyncLocalStorage2;
|
|
57912
|
+
function noteCheckpointWithoutTail(sessionID, cut, incoming, messageCount) {
|
|
57913
|
+
const pass = contextPass.getStore();
|
|
57914
|
+
if (pass?.sessionID !== sessionID)
|
|
57915
|
+
return;
|
|
57916
|
+
pass.checkpointWithoutTail = cut && incoming && messageCount === 1 && !isCheckpointNote(cut.data.summary) ? cut.id : undefined;
|
|
57917
|
+
}
|
|
57543
57918
|
function withV2ContextPass(sessionID, run) {
|
|
57544
57919
|
const pass = { sessionID, refused: false };
|
|
57545
57920
|
return withSqliteTransformPass2(() => contextPass.run(pass, () => run(pass)));
|
|
@@ -57715,9 +58090,31 @@ function coveredInstructionRows(reader, sessionID, throughSeq, model, retired =
|
|
|
57715
58090
|
return [];
|
|
57716
58091
|
return reader.instructionRowsThrough(sessionID, throughSeq).filter((row) => !retired(row)).flatMap((row) => restoreRow(row, model)).map((message) => markCoveredInstructionRow(message));
|
|
57717
58092
|
}
|
|
58093
|
+
var contextDisposalOrder = [
|
|
58094
|
+
"sweep",
|
|
58095
|
+
"backfill",
|
|
58096
|
+
"idle",
|
|
58097
|
+
"abortUsage",
|
|
58098
|
+
"hidden",
|
|
58099
|
+
"joinUsage",
|
|
58100
|
+
"rpc",
|
|
58101
|
+
"transform",
|
|
58102
|
+
"tools",
|
|
58103
|
+
"deletedSessions",
|
|
58104
|
+
"dream",
|
|
58105
|
+
"maintenance",
|
|
58106
|
+
"embeddings",
|
|
58107
|
+
"rawProviders",
|
|
58108
|
+
"restoredRows",
|
|
58109
|
+
"readerPool",
|
|
58110
|
+
"synthetic"
|
|
58111
|
+
];
|
|
57718
58112
|
async function registerContext(context) {
|
|
57719
58113
|
const directory = context.location.directory;
|
|
57720
58114
|
const config = loadPluginConfigDetailed(directory).config;
|
|
58115
|
+
for (const warning of new Set(config.configWarnings)) {
|
|
58116
|
+
log2(`[magic-context] config warning: ${warning}`);
|
|
58117
|
+
}
|
|
57721
58118
|
log2(`[magic-context] OpenCode 2 keep_subagents=${config.keep_subagents === true}`);
|
|
57722
58119
|
setHomeProjectPermission(config.allow_home_project);
|
|
57723
58120
|
if (!config.enabled)
|
|
@@ -57743,7 +58140,6 @@ async function registerContext(context) {
|
|
|
57743
58140
|
});
|
|
57744
58141
|
return;
|
|
57745
58142
|
}
|
|
57746
|
-
const liveConfigReader = pluginConfigReader(directory, config);
|
|
57747
58143
|
const compactionOff = !isCompactionEnabled(config);
|
|
57748
58144
|
const conflicts = detectConflicts(directory, {
|
|
57749
58145
|
compactionEnabled: !compactionOff,
|
|
@@ -57753,12 +58149,62 @@ async function registerContext(context) {
|
|
|
57753
58149
|
console.warn(`[magic-context] v2 setup disabled by conflicting context hooks: ${conflicts.reasons.join("; ")}`);
|
|
57754
58150
|
return;
|
|
57755
58151
|
}
|
|
58152
|
+
const cleanup = {};
|
|
58153
|
+
const dispose = async (failedSetup = false) => {
|
|
58154
|
+
for (const resource of contextDisposalOrder) {
|
|
58155
|
+
try {
|
|
58156
|
+
const drain = cleanup[resource]?.(failedSetup);
|
|
58157
|
+
if (drain)
|
|
58158
|
+
await drain;
|
|
58159
|
+
} catch (error) {
|
|
58160
|
+
const kind = error instanceof Error ? error.constructor.name : typeof error;
|
|
58161
|
+
log2(`[magic-context] v2 ${resource} cleanup failed (${kind})`);
|
|
58162
|
+
}
|
|
58163
|
+
}
|
|
58164
|
+
};
|
|
58165
|
+
try {
|
|
58166
|
+
await setupContext(context, config, nativeRemove, compactionOff, cleanup);
|
|
58167
|
+
} catch (error) {
|
|
58168
|
+
await dispose(true);
|
|
58169
|
+
throw error;
|
|
58170
|
+
}
|
|
58171
|
+
return { dispose: () => dispose() };
|
|
58172
|
+
}
|
|
58173
|
+
async function setupContext(context, config, nativeRemove, compactionOff, cleanup) {
|
|
58174
|
+
const directory = context.location.directory;
|
|
58175
|
+
const liveConfigReader = pluginConfigReader(directory, config);
|
|
57756
58176
|
const embeddings = createV2EmbeddingScope(resolveProjectIdentityForSession(directory, config.allow_home_project));
|
|
58177
|
+
cleanup.embeddings = () => embeddings.dispose();
|
|
57757
58178
|
const folds = new FoldOwner(context.storage);
|
|
57758
58179
|
const nativeFoldMemory = compactionOff ? undefined : nativeFoldCache(() => storage.require());
|
|
58180
|
+
const loggedUncoveredCheckpoints = new BoundedSessionMap(1000);
|
|
57759
58181
|
const nativeFoldReplay = nativeFoldMemory ? new NativeFoldReplay(nativeFoldMemory, () => openStoreReader(), context.storage, {
|
|
57760
58182
|
protocol: 3,
|
|
57761
|
-
log: sessionLog2
|
|
58183
|
+
log: sessionLog2,
|
|
58184
|
+
rendersHistory: (sessionID) => {
|
|
58185
|
+
if (rustModeModuleClient)
|
|
58186
|
+
return false;
|
|
58187
|
+
const mode = storedSubagentMode(storage.require(), sessionID);
|
|
58188
|
+
return mode !== undefined && rendersCompartmentHistory(mode, compactionOff);
|
|
58189
|
+
},
|
|
58190
|
+
servesHostCheckpoint: (sessionID, checkpointID) => {
|
|
58191
|
+
const pass = contextPass.getStore();
|
|
58192
|
+
return pass?.sessionID === sessionID && pass.checkpointWithoutTail === checkpointID;
|
|
58193
|
+
},
|
|
58194
|
+
onUncoveredFloor: (sessionID, floor, coverage) => {
|
|
58195
|
+
const pass = contextPass.getStore();
|
|
58196
|
+
if (pass?.sessionID === sessionID && pass.loggedUncoveredFloor)
|
|
58197
|
+
return;
|
|
58198
|
+
if (floor.kind === "checkpoint") {
|
|
58199
|
+
const key = JSON.stringify([sessionID, floor.id]);
|
|
58200
|
+
if (loggedUncoveredCheckpoints.get(key))
|
|
58201
|
+
return;
|
|
58202
|
+
loggedUncoveredCheckpoints.set(key, true);
|
|
58203
|
+
}
|
|
58204
|
+
if (pass?.sessionID === sessionID)
|
|
58205
|
+
pass.loggedUncoveredFloor = true;
|
|
58206
|
+
sessionLog2(sessionID, `v2 restore: ignored ${floor.kind} floor ${floor.id} at seq=${floor.after}; rendered coverage ${coverage.id ?? "none"} ends at seq=${coverage.after}`);
|
|
58207
|
+
}
|
|
57762
58208
|
}) : undefined;
|
|
57763
58209
|
setOutputReserveConfig(config.output_reserve);
|
|
57764
58210
|
const queriedModels = new Set;
|
|
@@ -57796,6 +58242,11 @@ async function registerContext(context) {
|
|
|
57796
58242
|
isLive: isLiveHiddenChild
|
|
57797
58243
|
});
|
|
57798
58244
|
let hiddenChildSweepTimer;
|
|
58245
|
+
cleanup.sweep = () => {
|
|
58246
|
+
if (hiddenChildSweepTimer)
|
|
58247
|
+
clearInterval(hiddenChildSweepTimer);
|
|
58248
|
+
return hiddenChildSweep.dispose();
|
|
58249
|
+
};
|
|
57799
58250
|
const sweepChildren = (database) => {
|
|
57800
58251
|
hiddenChildSweep.start(database);
|
|
57801
58252
|
};
|
|
@@ -57861,6 +58312,8 @@ async function registerContext(context) {
|
|
|
57861
58312
|
});
|
|
57862
58313
|
});
|
|
57863
58314
|
const tools = db && isDatabasePersisted(db) ? await registerTools(context, db, config, moduleToolBackends?.backends, (id) => hiddenChildHook.owns(id), embeddings.ensureRegistered) : undefined;
|
|
58315
|
+
if (tools)
|
|
58316
|
+
cleanup.tools = () => tools.dispose();
|
|
57864
58317
|
const generateReplay = new V2GenerateReplay;
|
|
57865
58318
|
await context.session.hook("http.response", async (draft) => {
|
|
57866
58319
|
if (!db || draft.kind !== "primary" || draft.response.ok)
|
|
@@ -57884,6 +58337,11 @@ async function registerContext(context) {
|
|
|
57884
58337
|
});
|
|
57885
58338
|
let hiddenAgentsReady;
|
|
57886
58339
|
const readerPool = new V2StoreReaderPool2;
|
|
58340
|
+
cleanup.readerPool = async () => {
|
|
58341
|
+
if (!await readerPool.closeWhenIdle(STORE_POOL_DISPOSE_WAIT_MS))
|
|
58342
|
+
log2(`[magic-context] v2 store reader pool still held by ${readerPool.holdCount()} hidden run(s) at dispose; it closes when they finish`);
|
|
58343
|
+
};
|
|
58344
|
+
cleanup.synthetic = () => clearSyntheticCandidates(context);
|
|
57887
58345
|
const messageTimesCache = new V2MessageTimesCache;
|
|
57888
58346
|
const openStoreReader = () => readerPool.open(gaDatabasePath2(getDataDir(), process.env.OPENCODE_CHANNEL ?? "latest"));
|
|
57889
58347
|
const revertMessageCleanup = new V2RevertMessageCleanup(openStoreReader);
|
|
@@ -57954,6 +58412,10 @@ async function registerContext(context) {
|
|
|
57954
58412
|
hostVersion: context.app?.version,
|
|
57955
58413
|
keepSubagents: config.keep_subagents === true,
|
|
57956
58414
|
ensureAgent: () => hiddenAgentsReady ??= context.agent.reload(),
|
|
58415
|
+
forgetAgent: (pending) => {
|
|
58416
|
+
if (hiddenAgentsReady === pending)
|
|
58417
|
+
hiddenAgentsReady = undefined;
|
|
58418
|
+
},
|
|
57957
58419
|
modelCatalog: () => Promise.resolve(context.model.list()),
|
|
57958
58420
|
historianTemperature: () => config.historian?.temperature,
|
|
57959
58421
|
openReader: openStoreReader,
|
|
@@ -57987,9 +58449,12 @@ async function registerContext(context) {
|
|
|
57987
58449
|
return trigger;
|
|
57988
58450
|
};
|
|
57989
58451
|
let hiddenCompletionExecutor = db && isDatabasePersisted(db) && resolveProjectIdentityForSession(directory, config.allow_home_project) ? await createHiddenExecutor(db) : undefined;
|
|
58452
|
+
cleanup.hidden = () => hiddenCompletionExecutor?.dispose();
|
|
57990
58453
|
let dreamTrigger = hiddenCompletionExecutor ? startDreamer(hiddenCompletionExecutor) : undefined;
|
|
58454
|
+
cleanup.dream = () => dreamTrigger?.dispose();
|
|
57991
58455
|
const lateHiddenExecutor = createLateHiddenExecutor(() => hiddenCompletionExecutor);
|
|
57992
58456
|
let maintenanceTimer;
|
|
58457
|
+
cleanup.maintenance = () => maintenanceTimer?.dispose();
|
|
57993
58458
|
const startMaintenance = () => {
|
|
57994
58459
|
const timerProjectIdentity = resolveProjectIdentityForSession(directory, config.allow_home_project);
|
|
57995
58460
|
if (!timerProjectIdentity || maintenanceTimer)
|
|
@@ -58050,6 +58515,12 @@ async function registerContext(context) {
|
|
|
58050
58515
|
const commitSeenLastPass = new Map;
|
|
58051
58516
|
const restoredRows = new RestoredRowCache;
|
|
58052
58517
|
const rawProviders = new Map;
|
|
58518
|
+
cleanup.restoredRows = () => restoredRows.clear();
|
|
58519
|
+
cleanup.rawProviders = () => {
|
|
58520
|
+
for (const release of rawProviders.values())
|
|
58521
|
+
release();
|
|
58522
|
+
rawProviders.clear();
|
|
58523
|
+
};
|
|
58053
58524
|
let passDuties;
|
|
58054
58525
|
let toolDuties;
|
|
58055
58526
|
const droppedInputGuard = createDroppedInputGuard();
|
|
@@ -58088,8 +58559,9 @@ async function registerContext(context) {
|
|
|
58088
58559
|
};
|
|
58089
58560
|
if (db && isDatabasePersisted(db)) {
|
|
58090
58561
|
const backfillDb = db;
|
|
58091
|
-
|
|
58092
|
-
|
|
58562
|
+
let running;
|
|
58563
|
+
const timer = scheduleAfterBootQuiet(() => {
|
|
58564
|
+
running = runV2SessionProjectBackfill(backfillDb, openStoreReader, config.allow_home_project).then(() => backfillSessionActivity(backfillDb, "opencode", (sessionId) => {
|
|
58093
58565
|
const reader = openStoreReader();
|
|
58094
58566
|
try {
|
|
58095
58567
|
return reader.latestMessageTime(sessionId);
|
|
@@ -58098,6 +58570,17 @@ async function registerContext(context) {
|
|
|
58098
58570
|
}
|
|
58099
58571
|
})).catch((error) => log2("[session-project-backfill] OpenCode 2 backfill failed:", error));
|
|
58100
58572
|
});
|
|
58573
|
+
cleanup.backfill = (failedSetup) => {
|
|
58574
|
+
if (!failedSetup)
|
|
58575
|
+
return;
|
|
58576
|
+
clearTimeout(timer);
|
|
58577
|
+
if (!running)
|
|
58578
|
+
return;
|
|
58579
|
+
return settleWithin(running, DEFAULT_DISPOSE_DRAIN_MS).then((joined) => {
|
|
58580
|
+
if (!joined)
|
|
58581
|
+
log2("[magic-context] v2 backfill still running after setup cleanup");
|
|
58582
|
+
});
|
|
58583
|
+
};
|
|
58101
58584
|
}
|
|
58102
58585
|
const readAllForConversion = (sessionID) => readAllV2RawMessagesForConversion2(openStoreReader, sessionID);
|
|
58103
58586
|
const readRowsFrom = (sessionID, messageID) => {
|
|
@@ -58118,10 +58601,12 @@ async function registerContext(context) {
|
|
|
58118
58601
|
}) : undefined;
|
|
58119
58602
|
const lkgSystems = new V2LkgSystemReplay;
|
|
58120
58603
|
let transform;
|
|
58604
|
+
cleanup.transform = () => transform?.disposeRust();
|
|
58121
58605
|
let systemPrompt;
|
|
58122
58606
|
const systemPromptRefreshSessions = new Set;
|
|
58123
58607
|
const tagger = createTagger();
|
|
58124
58608
|
const deletedSessions = new DeletedSessionTombstones;
|
|
58609
|
+
cleanup.deletedSessions = () => deletedSessions.clear();
|
|
58125
58610
|
const forkSeedSettled = new Set;
|
|
58126
58611
|
const inheritForkState = (database, sessionID) => {
|
|
58127
58612
|
if (forkSeedSettled.has(sessionID))
|
|
@@ -58292,6 +58777,12 @@ async function registerContext(context) {
|
|
|
58292
58777
|
log: sessionLog2
|
|
58293
58778
|
}) : undefined;
|
|
58294
58779
|
const hostFoldIdle = hostFolds ? new HostFoldIdle((sessionID, eligible) => hostFolds.idle(sessionID, eligible)) : undefined;
|
|
58780
|
+
cleanup.idle = () => {
|
|
58781
|
+
messageTimesCache.clear();
|
|
58782
|
+
recoveredInstructions.clear();
|
|
58783
|
+
loggedUncoveredCheckpoints.clear();
|
|
58784
|
+
hostFoldIdle?.dispose();
|
|
58785
|
+
};
|
|
58295
58786
|
const armBindingRecoveryFromEvent = (sessionID, error, source) => {
|
|
58296
58787
|
if (error === undefined || !db || compactionOff)
|
|
58297
58788
|
return;
|
|
@@ -58327,6 +58818,7 @@ async function registerContext(context) {
|
|
|
58327
58818
|
}
|
|
58328
58819
|
};
|
|
58329
58820
|
const usageController = new AbortController;
|
|
58821
|
+
cleanup.abortUsage = () => usageController.abort();
|
|
58330
58822
|
const usageDone = (async () => {
|
|
58331
58823
|
let retry = 0;
|
|
58332
58824
|
while (!usageController.signal.aborted) {
|
|
@@ -58363,9 +58855,11 @@ async function registerContext(context) {
|
|
|
58363
58855
|
if (event.type === "session.revert.staged" && db) {
|
|
58364
58856
|
revertMessageCleanup.captureStageProof(sessionID, event.data.revert?.messageID);
|
|
58365
58857
|
}
|
|
58366
|
-
if (event.type === "session.revert.cleared"
|
|
58858
|
+
if (event.type === "session.revert.cleared") {
|
|
58367
58859
|
revertMessageCleanup.discardStageProof(sessionID);
|
|
58368
58860
|
}
|
|
58861
|
+
if (event.type === "session.deleted")
|
|
58862
|
+
revertMessageCleanup.forgetSession(sessionID);
|
|
58369
58863
|
if (event.type === "session.revert.committed") {
|
|
58370
58864
|
dropServedRecord(sessionID, "host_edit");
|
|
58371
58865
|
if (db) {
|
|
@@ -58373,9 +58867,10 @@ async function registerContext(context) {
|
|
|
58373
58867
|
withoutSqliteTransformPass2(() => {
|
|
58374
58868
|
scheduleClearAndReindex(indexDb, sessionID, pagedRead);
|
|
58375
58869
|
try {
|
|
58376
|
-
if (revertMessageCleanup.pruneOnCommit(indexDb, sessionID, event.data?.to)) {
|
|
58870
|
+
if (revertMessageCleanup.pruneOnCommit(indexDb, sessionID, event.data?.to, !compactionOff && !rustModeModuleClient)) {
|
|
58377
58871
|
tagger.cleanup(sessionID);
|
|
58378
58872
|
transform?.invalidateRustWireState(sessionID);
|
|
58873
|
+
revertMessageCleanup.retireProvenHistory(indexDb, sessionID);
|
|
58379
58874
|
}
|
|
58380
58875
|
} catch (error) {
|
|
58381
58876
|
sessionLog2(sessionID, "committed revert message cleanup failed:", error);
|
|
@@ -58503,6 +58998,7 @@ async function registerContext(context) {
|
|
|
58503
58998
|
}
|
|
58504
58999
|
}
|
|
58505
59000
|
})();
|
|
59001
|
+
cleanup.joinUsage = () => usageDone;
|
|
58506
59002
|
const m0RenderOptions = (draft, store, state) => {
|
|
58507
59003
|
const modelKey = `${draft.model.providerID}/${draft.model.id}`;
|
|
58508
59004
|
const contextLimit = resolveContextLimit(draft.model.providerID, draft.model.id, {
|
|
@@ -58673,7 +59169,7 @@ async function registerContext(context) {
|
|
|
58673
59169
|
const nativeFloor = await nativeFoldReplay?.restorationFloor(draft.sessionID, cut, reader, {
|
|
58674
59170
|
allowMissingFloor: newStart !== undefined
|
|
58675
59171
|
});
|
|
58676
|
-
if (newStart && nativeFloor === undefined) {
|
|
59172
|
+
if (newStart !== undefined && nativeFloor === undefined) {
|
|
58677
59173
|
const pass = contextPass.getStore();
|
|
58678
59174
|
if (pass)
|
|
58679
59175
|
pass.recoveredCheckpointID = cut.id;
|
|
@@ -58682,6 +59178,12 @@ async function registerContext(context) {
|
|
|
58682
59178
|
const servedBoundary = boundaryID ? servedBoundaryRow2(reader, draft.sessionID, boundaryID) : null;
|
|
58683
59179
|
const retiredInstructions = await nativeFoldReplay?.instructionRetirement(draft.sessionID, reader) ?? (() => false);
|
|
58684
59180
|
const floor = Math.max(nativeFloor ?? -Infinity, (nativeFoldReplay?.sourceChanged(draft.sessionID) && !rustModeModuleClient ? (reader.earliestSequence(draft.sessionID) ?? 0) - 1 : undefined) ?? (moduleBoundarySeq !== undefined ? moduleBoundarySeq - 1 : undefined) ?? servedBoundary?.seq ?? reader.sequenceForId(draft.sessionID, boundaryID) ?? (reader.earliestSequence(draft.sessionID) ?? 0) - 1);
|
|
59181
|
+
if (nativeFloor === undefined && newStart === null) {
|
|
59182
|
+
const first = reader.page(draft.sessionID, { limit: 1 }).rows[0];
|
|
59183
|
+
if (first?.seq === floor + 1)
|
|
59184
|
+
args.onStartAtFirstRow?.(first.id);
|
|
59185
|
+
sessionLog2(draft.sessionID, `v2 restore: no rendered history boundary; starting at stored row seq=${floor + 1}`);
|
|
59186
|
+
}
|
|
58685
59187
|
const floorRow = !rustModeModuleClient && Number.isFinite(floor) ? reader.range(draft.sessionID, floor - 1, floor).find((row) => row.seq === floor) : undefined;
|
|
58686
59188
|
const boundary = floorRow && hasUnsummarizedBlocks(db, reader, draft.sessionID, floorRow.id) ? floor - 1 : floor;
|
|
58687
59189
|
if (moduleBoundarySeq !== undefined)
|
|
@@ -58910,6 +59412,7 @@ async function registerContext(context) {
|
|
|
58910
59412
|
const incoming = localCut && messages.find((message) => message.id === localCut.id);
|
|
58911
59413
|
if (localCut && !incoming)
|
|
58912
59414
|
return;
|
|
59415
|
+
noteCheckpointWithoutTail(draft.sessionID, localCut, incoming, messages.length);
|
|
58913
59416
|
checkpointAtEntry = incoming || null;
|
|
58914
59417
|
const modeDb = db ?? storage.current();
|
|
58915
59418
|
const subagent = modeDb ? storedSubagentMode(modeDb, draft.sessionID) : undefined;
|
|
@@ -59106,18 +59609,20 @@ async function registerContext(context) {
|
|
|
59106
59609
|
let submitted;
|
|
59107
59610
|
let recordedHead;
|
|
59108
59611
|
let upgradeCheckpointSequence;
|
|
59612
|
+
let restoredFirstRow;
|
|
59109
59613
|
try {
|
|
59110
59614
|
syntheticIDs = await readSyntheticProvenance(reader, draft.messages);
|
|
59111
59615
|
const cut = reader.latestCompaction(draft.sessionID);
|
|
59112
59616
|
if (nativeFoldReplay)
|
|
59113
59617
|
await nativeFoldReplay.observeSource(draft.sessionID, reader);
|
|
59114
|
-
const boundaryRepair = !rustModeModuleClient && db && !compactionOff ? checkHistoryBoundary(db, reader, draft.sessionID) : undefined;
|
|
59618
|
+
const boundaryRepair = !rustModeModuleClient && db && !compactionOff ? revertMessageCleanup.retireProvenHistory(db, draft.sessionID, reader) ?? checkHistoryBoundary(db, reader, draft.sessionID) : undefined;
|
|
59115
59619
|
if (boundaryRepair?.kind === "repaired" || boundaryRepair?.kind === "baseline-reset") {
|
|
59116
59620
|
historyRefreshSessions.add(draft.sessionID);
|
|
59117
59621
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "boundary_repair");
|
|
59118
59622
|
}
|
|
59119
59623
|
const localCut = cut && isLocalCheckpoint(cut) ? cut : undefined;
|
|
59120
59624
|
const incoming = localCut && draft.messages.find((message) => message.id === localCut.id);
|
|
59625
|
+
noteCheckpointWithoutTail(draft.sessionID, localCut, incoming, draft.messages.length);
|
|
59121
59626
|
if (!compactionOff && localCut && !incoming)
|
|
59122
59627
|
throw new Error("The host checkpoint disappeared from the context draft");
|
|
59123
59628
|
checkpointAtEntry = incoming || null;
|
|
@@ -59199,7 +59704,10 @@ async function registerContext(context) {
|
|
|
59199
59704
|
messages: draft.messages,
|
|
59200
59705
|
cut: localCut,
|
|
59201
59706
|
incoming,
|
|
59202
|
-
canRebuild: true
|
|
59707
|
+
canRebuild: true,
|
|
59708
|
+
onStartAtFirstRow: (id) => {
|
|
59709
|
+
restoredFirstRow = id;
|
|
59710
|
+
}
|
|
59203
59711
|
}));
|
|
59204
59712
|
}
|
|
59205
59713
|
instructionRows = new Map(bindKeptInstructionCoordinates(draft.messages, incoming || undefined, reader, draft.sessionID).map((row) => [row.id, row]));
|
|
@@ -59253,14 +59761,30 @@ async function registerContext(context) {
|
|
|
59253
59761
|
})({}, mapped);
|
|
59254
59762
|
mapped.commit();
|
|
59255
59763
|
if (replayHead === undefined && (pass.recoveredCheckpointID || previousRecovery && pass.nativeReplayCheckpointID === previousRecovery.checkpointID)) {
|
|
59764
|
+
let coveredAfterRestore;
|
|
59765
|
+
if (pass.recoveredCheckpointID && restoredFirstRow) {
|
|
59766
|
+
try {
|
|
59767
|
+
const end = db.prepare("SELECT cached_m0_last_baseline_end_message_id AS id FROM session_meta WHERE session_id=?").get(draft.sessionID);
|
|
59768
|
+
if (end?.id) {
|
|
59769
|
+
const source = openStoreReader();
|
|
59770
|
+
try {
|
|
59771
|
+
const seq = source.sequenceForId(draft.sessionID, end.id);
|
|
59772
|
+
if (seq !== undefined)
|
|
59773
|
+
coveredAfterRestore = new Set(source.instructionRowsThrough(draft.sessionID, seq).map(({ id }) => id));
|
|
59774
|
+
} finally {
|
|
59775
|
+
source.close();
|
|
59776
|
+
}
|
|
59777
|
+
}
|
|
59778
|
+
} catch {}
|
|
59779
|
+
}
|
|
59256
59780
|
pass.servedInstructionIDs = new Set(mapped.messages.flatMap(({ info, parts }) => {
|
|
59257
|
-
|
|
59781
|
+
const id = hostInstructionRowID(info);
|
|
59782
|
+
if (!id || info.role !== "system" || pass.recoveredCheckpointID && !isCoveredInstructionRow(info) && !coveredAfterRestore?.has(id) || !parts.some((value) => {
|
|
59258
59783
|
const part = value;
|
|
59259
59784
|
return part?.type === "text" && typeof part.text === "string" && part.text.length > 0;
|
|
59260
59785
|
}))
|
|
59261
59786
|
return [];
|
|
59262
|
-
|
|
59263
|
-
return id ? [id] : [];
|
|
59787
|
+
return [id];
|
|
59264
59788
|
}));
|
|
59265
59789
|
}
|
|
59266
59790
|
const checkpointPermission = checkpointPassPermissions.get(draft.sessionID);
|
|
@@ -59308,7 +59832,7 @@ async function registerContext(context) {
|
|
|
59308
59832
|
try {
|
|
59309
59833
|
const state = db && getOrCreateSessionMeta(db, draft.sessionID);
|
|
59310
59834
|
const boundary = db?.prepare("SELECT cached_m0_last_baseline_end_message_id AS id FROM session_meta WHERE session_id=?").get(draft.sessionID);
|
|
59311
|
-
await nativeFoldReplay?.capture(draft, nativeMessages, boundary?.id && state?.cachedM0Bytes ? { id: boundary.id, summary: state.cachedM0Bytes.toString("utf8") } : undefined);
|
|
59835
|
+
await nativeFoldReplay?.capture(draft, nativeMessages, boundary?.id && state?.cachedM0Bytes ? { id: boundary.id, summary: state.cachedM0Bytes.toString("utf8") } : undefined, restoredFirstRow);
|
|
59312
59836
|
} catch (error) {
|
|
59313
59837
|
nativeFoldReplay?.invalidate(draft.sessionID, true);
|
|
59314
59838
|
sessionLog2(draft.sessionID, "v2 host fold: optional capture unavailable", error);
|
|
@@ -59512,6 +60036,10 @@ async function registerContext(context) {
|
|
|
59512
60036
|
const storageDir = getMagicContextStorageDir();
|
|
59513
60037
|
const rpcServer = new MagicContextRpcServer(storageDir, directory);
|
|
59514
60038
|
let rpcStopped = false;
|
|
60039
|
+
cleanup.rpc = () => {
|
|
60040
|
+
rpcStopped = true;
|
|
60041
|
+
rpcServer.stop();
|
|
60042
|
+
};
|
|
59515
60043
|
registerRpcHandlers(rpcServer, {
|
|
59516
60044
|
directory,
|
|
59517
60045
|
config,
|
|
@@ -59618,34 +60146,6 @@ async function registerContext(context) {
|
|
|
59618
60146
|
return;
|
|
59619
60147
|
rpcServer.start().catch((error) => log2("[magic-context] v2 RPC server failed to start", error));
|
|
59620
60148
|
}, 0));
|
|
59621
|
-
return {
|
|
59622
|
-
async dispose() {
|
|
59623
|
-
if (hiddenChildSweepTimer)
|
|
59624
|
-
clearInterval(hiddenChildSweepTimer);
|
|
59625
|
-
await hiddenChildSweep.dispose();
|
|
59626
|
-
messageTimesCache.clear();
|
|
59627
|
-
recoveredInstructions.clear();
|
|
59628
|
-
hostFoldIdle?.dispose();
|
|
59629
|
-
usageController.abort();
|
|
59630
|
-
await hiddenCompletionExecutor?.dispose();
|
|
59631
|
-
await usageDone;
|
|
59632
|
-
rpcStopped = true;
|
|
59633
|
-
rpcServer.stop();
|
|
59634
|
-
transform?.disposeRust();
|
|
59635
|
-
tools?.dispose();
|
|
59636
|
-
deletedSessions.clear();
|
|
59637
|
-
await dreamTrigger?.dispose();
|
|
59638
|
-
await maintenanceTimer?.dispose();
|
|
59639
|
-
await embeddings.dispose();
|
|
59640
|
-
for (const release of rawProviders.values())
|
|
59641
|
-
release();
|
|
59642
|
-
rawProviders.clear();
|
|
59643
|
-
restoredRows.clear();
|
|
59644
|
-
if (!await readerPool.closeWhenIdle(STORE_POOL_DISPOSE_WAIT_MS))
|
|
59645
|
-
log2(`[magic-context] v2 store reader pool still held by ${readerPool.holdCount()} hidden run(s) at dispose; it closes when they finish`);
|
|
59646
|
-
clearSyntheticCandidates(context);
|
|
59647
|
-
}
|
|
59648
|
-
};
|
|
59649
60149
|
}
|
|
59650
60150
|
export {
|
|
59651
60151
|
registerContext
|