@cortexkit/opencode-magic-context 0.49.15 → 0.49.17
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 +76 -63
- package/dist/chunk-embedding-write-worker.js +12 -10
- package/dist/{compaction-marker-candidates-v5c6997n.js → compaction-marker-candidates-n4krhat4.js} +2 -2
- package/dist/compaction-marker-candidates-worker.js +2 -2
- package/dist/config/schema/magic-context.d.ts +343 -343
- package/dist/config/schema/magic-context.d.ts.map +1 -1
- package/dist/{conflict-warning-hook-mgq17yr3.js → conflict-warning-hook-4pmz879v.js} +6 -6
- package/dist/{context-0m46day0.js → context-yhetp0kn.js} +297 -141
- package/dist/embedding-backfill-fmz50tsy.js +24 -0
- package/dist/embedding-worker-process.js +1 -1
- package/dist/embedding-worker.js +5 -5
- package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -1
- package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
- package/dist/features/magic-context/git-commits/indexer.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
- package/dist/features/magic-context/memory/project-identity-cache.d.ts +2 -0
- package/dist/features/magic-context/memory/project-identity-cache.d.ts.map +1 -1
- package/dist/features/magic-context/message-fts-rowid-map.d.ts +2 -2
- package/dist/features/magic-context/message-fts-rowid-map.d.ts.map +1 -1
- package/dist/features/magic-context/message-fts-session-filter.d.ts +2 -0
- package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
- package/dist/features/magic-context/message-index-async.d.ts +1 -1
- package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
- package/dist/features/magic-context/message-index.d.ts +5 -0
- package/dist/features/magic-context/message-index.d.ts.map +1 -1
- package/dist/features/magic-context/message-time-backfill.d.ts +2 -2
- package/dist/features/magic-context/message-time-backfill.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts +6 -1
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/storage-db.d.ts +2 -1
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-shared.d.ts +2 -2
- package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
- package/dist/features/magic-context/storage-session-tables.d.ts +9 -1
- package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
- package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-deadline.d.ts +2 -1
- package/dist/hooks/magic-context/auto-search-deadline.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-hint.d.ts +3 -0
- package/dist/hooks/magic-context/auto-search-hint.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-worker-client.d.ts +10 -2
- package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts +4 -2
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
- package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-prompt-fit.d.ts +2 -1
- package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
- package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts +26 -0
- package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
- package/dist/hooks/magic-context/recomp-orchestrator.d.ts +3 -3
- package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
- package/dist/hooks/magic-context/system-prompt-diagnostics.d.ts +8 -0
- package/dist/hooks/magic-context/system-prompt-diagnostics.d.ts.map +1 -0
- package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts +6 -1
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/todo-view.d.ts +2 -2
- package/dist/hooks/magic-context/tool-drop-target.d.ts +3 -2
- package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-stage-logger.d.ts +3 -0
- package/dist/hooks/magic-context/transform-stage-logger.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +1 -0
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-3kdm78zp.js → index-24fezq97.js} +4 -4
- package/dist/{index-a8bvhwqs.js → index-2vxtcb95.js} +32 -3
- package/dist/{index-f71thw8j.js → index-4s3t0nd0.js} +1 -1
- package/dist/{index-ts1hjk1h.js → index-4yt7dtf4.js} +453 -227
- package/dist/{index-mc1cqza6.js → index-5a1ex6x8.js} +5 -5
- package/dist/{index-fkx2qnvw.js → index-6x57ar45.js} +2 -2
- package/dist/{index-dyvbsvga.js → index-a6mc0v4d.js} +25 -11
- package/dist/{index-snp5wbge.js → index-a7c4r5re.js} +160 -749
- package/dist/{index-42vcjcwe.js → index-aabzay3h.js} +180 -103
- package/dist/{index-3kx0kg0f.js → index-b5vqckbw.js} +14 -8
- package/dist/{v2/server-wafzvyhg.js → index-beht37jy.js} +8 -0
- package/dist/{index-e20m7284.js → index-bjcnntmz.js} +3 -3
- package/dist/{index-hqkczed7.js → index-c5pytzne.js} +22 -2
- package/dist/{index-thvnpfsv.js → index-cwzfcbtq.js} +967 -88
- package/dist/{index-yxycg7fs.js → index-fb2qxs2y.js} +26 -18
- package/dist/{index-mht7bq0z.js → index-hqhm3wke.js} +32 -8
- package/dist/{index-e4dsjj1p.js → index-jn12fvvh.js} +1 -1
- package/dist/index-kaqs6h31.js +58 -0
- package/dist/{index-n6m03s3n.js → index-ke416mdc.js} +1 -1
- package/dist/index-kmdj7dsq.js +96 -0
- package/dist/{index-1d289pq2.js → index-kq82mtg0.js} +2 -2
- package/dist/{index-n78avt2p.js → index-n37sebck.js} +1 -1
- package/dist/{index-1vc7jrkg.js → index-nkpmm9q8.js} +3 -3
- package/dist/{index-944w16m0.js → index-p7m7j0cp.js} +25 -17
- package/dist/{index-wk0n1cgt.js → index-qn7xstt2.js} +2 -2
- package/dist/{index-saews2s3.js → index-rr2bb45z.js} +1 -1
- package/dist/{index-mmfa86mt.js → index-s734jcsr.js} +169 -149
- package/dist/{index-dgs16axy.js → index-s74zqahq.js} +1 -1
- package/dist/{index-bxdg2nbt.js → index-v8awdgvd.js} +4 -4
- package/dist/{index-xn6q9pg6.js → index-vrzjhftj.js} +36 -76
- package/dist/{index-1sarmj9z.js → index-wgypt3cs.js} +6 -6
- package/dist/{index-y1qysm3q.js → index-ze7mvk54.js} +11 -8
- package/dist/index.js +47 -45
- package/dist/message-fts-rowid-map-17s0dfn4.js +25 -0
- package/dist/{message-index-bounded-vtgpq6b4.js → message-index-bounded-1633vc7f.js} +17 -17
- package/dist/{message-index-a6gztaqx.js → message-index-dprebmtt.js} +15 -15
- package/dist/{message-time-backfill-qjge9044.js → message-time-backfill-73mmm76q.js} +5 -5
- package/dist/migration-worker.js +9 -7
- package/dist/plugin/dream-timer.d.ts +11 -0
- package/dist/plugin/dream-timer.d.ts.map +1 -1
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/{project-embedding-registry-x45bv3qr.js → project-embedding-registry-z74mhqkf.js} +12 -10
- package/dist/raw-ordinal-warmup-worker.js +40 -10
- package/dist/{read-session-chunk-3ae3nfdn.js → read-session-chunk-4zp09ejb.js} +9 -9
- package/dist/{read-session-raw-m56hc7v2.js → read-session-raw-rsc8c7qy.js} +2 -2
- package/dist/{recomp-orchestrator-nwzcfhx4.js → recomp-orchestrator-z3ecszx6.js} +26 -26
- package/dist/{search-deajrd90.js → search-6mee3vty.js} +23 -22
- package/dist/search-archive-znyy44ve.js +25 -0
- package/dist/{send-session-notification-24r4esbh.js → send-session-notification-6ve0e8p4.js} +5 -5
- package/dist/shared/historian-cache.d.ts +8 -0
- package/dist/shared/historian-cache.d.ts.map +1 -0
- package/dist/shared/model-suggestion-retry.d.ts +4 -0
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- package/dist/shared/resolve-fallbacks.d.ts +3 -3
- package/dist/shared/rpc-discovery-cleanup.d.ts +3 -0
- package/dist/shared/rpc-discovery-cleanup.d.ts.map +1 -0
- package/dist/shared/rpc-server.d.ts +2 -0
- package/dist/shared/rpc-server.d.ts.map +1 -1
- package/dist/shared/search-text.d.ts +8 -0
- package/dist/shared/search-text.d.ts.map +1 -0
- package/dist/shared/sqlite.d.ts +4 -2
- package/dist/shared/sqlite.d.ts.map +1 -1
- package/dist/shared/storage-file-mutex.d.ts.map +1 -1
- package/dist/shared/subagent-runner.d.ts +2 -0
- package/dist/shared/subagent-runner.d.ts.map +1 -1
- package/dist/shared/system-directive.d.ts +2 -0
- package/dist/shared/system-directive.d.ts.map +1 -1
- package/dist/{sqlite-4pqyynrs.js → sqlite-zf72c52d.js} +1 -1
- package/dist/{storage-memory-j3v3hc83.js → storage-memory-y3qmy00r.js} +2 -2
- package/dist/{storage-tags-s5bg1ahx.js → storage-tags-8qns3012.js} +8 -4
- package/dist/tools/ctx-expand/search-archive.d.ts +5 -1
- package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-ne3z1zmt.js → transform-postprocess-phase-3ydzxa62.js} +26 -26
- package/dist/v2/auto-search-worker.js +76 -63
- package/dist/v2/chunk-embedding-write-worker.js +12 -10
- package/dist/v2/{compaction-marker-candidates-1vqwr3s5.js → compaction-marker-candidates-ebx3388k.js} +2 -2
- package/dist/v2/compaction-marker-candidates-worker.js +2 -2
- package/dist/v2/{context-4qczzck7.js → context-jn3zpeqh.js} +909 -454
- package/dist/v2/embedding-backfill-7c7yr69y.js +23 -0
- package/dist/v2/embedding-worker-process.js +1 -1
- package/dist/v2/embedding-worker.js +5 -5
- package/dist/v2/fold/native-replay.d.ts +11 -2
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/fold/policy.d.ts.map +1 -1
- package/dist/v2/fold/restore.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/hidden-child.d.ts +8 -0
- package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
- package/dist/v2/hooks/types.d.ts +17 -0
- package/dist/v2/hooks/types.d.ts.map +1 -1
- package/dist/v2/message-fts-rowid-map-wfx67gfd.js +24 -0
- package/dist/v2/{message-index-bounded-rxxznd34.js → message-index-bounded-hpejqyd8.js} +17 -17
- package/dist/v2/{message-index-f947qtbz.js → message-index-pxehjpzx.js} +15 -15
- package/dist/v2/{message-time-backfill-bsteyc4d.js → message-time-backfill-04t0km1z.js} +5 -5
- package/dist/v2/migration-worker.js +9 -7
- package/dist/v2/{project-embedding-registry-0msp56p8.js → project-embedding-registry-gnkj56xp.js} +12 -10
- package/dist/v2/raw-ordinal-warmup-worker.js +40 -10
- package/dist/v2/{read-session-chunk-rq9nx1nn.js → read-session-chunk-zdppn4bj.js} +9 -9
- package/dist/v2/{read-session-raw-b3tf6ra1.js → read-session-raw-yaegtjzh.js} +2 -2
- package/dist/v2/{recomp-orchestrator-5zhxtwha.js → recomp-orchestrator-cmqnfpp3.js} +26 -26
- package/dist/v2/{search-n8wqxb1j.js → search-66842dya.js} +23 -22
- package/dist/v2/search-archive-gfh11vs0.js +24 -0
- package/dist/v2/{send-session-notification-8ghn9tnv.js → send-session-notification-3pxn658x.js} +5 -5
- package/dist/v2/{server-yrvqaswb.js → server-1wy7b9de.js} +25 -11
- package/dist/v2/{server-th4y11y7.js → server-271qxsf5.js} +6 -6
- package/dist/v2/{server-e298hswg.js → server-3rhpvy84.js} +967 -88
- package/dist/v2/{server-qhfvvfxj.js → server-46neh5fa.js} +14 -8
- package/dist/v2/{server-rrqpvwqd.js → server-6tmj0s7j.js} +2 -2
- package/dist/v2/{server-hek6z3w6.js → server-8by8qfec.js} +11 -8
- package/dist/v2/{server-vbe4se57.js → server-a9xqj88f.js} +1 -1
- package/dist/{index-wafzvyhg.js → v2/server-beht37jy.js} +8 -0
- package/dist/v2/{server-05xjtq6c.js → server-d04vrx0j.js} +1 -1
- package/dist/v2/server-ec4ca92p.js +96 -0
- package/dist/v2/{server-dd0tz6cn.js → server-fw7wrk01.js} +160 -750
- package/dist/v2/{server-zs8d0s3b.js → server-g3qma5c0.js} +1 -1
- package/dist/v2/{server-k2bzedxk.js → server-gpvay0xz.js} +2 -2
- package/dist/v2/{server-kmbarfmn.js → server-gtfhttbr.js} +26 -18
- package/dist/v2/{server-g10mdym6.js → server-h1v0pyxb.js} +3 -3
- package/dist/v2/{server-4gn3z5an.js → server-hy3d3vsx.js} +1 -1
- package/dist/v2/server-kaqs6h31.js +58 -0
- package/dist/v2/{server-ehyava47.js → server-kh7dpa1a.js} +25 -17
- package/dist/v2/{server-6cdy4rc0.js → server-my7k4eds.js} +4 -4
- package/dist/v2/{server-d8tj10db.js → server-n1prf1g6.js} +1 -1
- package/dist/v2/{server-n78avt2p.js → server-n37sebck.js} +1 -1
- package/dist/v2/{server-zc3e54vy.js → server-nj659894.js} +6 -6
- package/dist/v2/{server-gvkm8xaj.js → server-rmygf5pn.js} +32 -3
- package/dist/v2/{server-0ppsweh6.js → server-tgnbmwah.js} +22 -2
- package/dist/v2/{server-cfbr1s2x.js → server-vsw8tmm6.js} +36 -76
- package/dist/v2/{server-prg55b7k.js → server-xj136kt8.js} +23 -3
- package/dist/v2/{server-atbc19ab.js → server-zyzawhdw.js} +32 -8
- package/dist/v2/{server-ef89gdsx.js → server-zzkj2fch.js} +4 -4
- package/dist/v2/server.js +5 -5
- package/dist/v2/{sqlite-4pqyynrs.js → sqlite-zf72c52d.js} +1 -1
- package/dist/v2/{storage-memory-j3v3hc83.js → storage-memory-y3qmy00r.js} +2 -2
- package/dist/v2/{storage-tags-hcc2adpf.js → storage-tags-1h8k6ra9.js} +8 -4
- package/dist/v2/store-reader.d.ts +2 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{wrapup-orchestrator-65pwye0d.js → wrapup-orchestrator-xs8redz9.js} +26 -26
- package/dist/wrapup-orchestrator-j7d7ry5b.js +48 -0
- package/package.json +1 -1
- package/src/config/latch-permanence-guard.test.ts +4 -0
- package/src/config/schema/magic-context.ts +14 -6
- package/src/shared/historian-cache.test.ts +69 -0
- package/src/shared/historian-cache.ts +55 -0
- package/src/shared/model-resolution.test.ts +22 -0
- package/src/shared/model-suggestion-retry.ts +11 -3
- package/src/shared/resolve-fallbacks.test.ts +2 -3
- package/src/shared/resolve-fallbacks.ts +3 -3
- package/src/shared/rpc-discovery-cleanup.test.ts +57 -0
- package/src/shared/rpc-discovery-cleanup.ts +57 -0
- package/src/shared/rpc-server.ts +36 -13
- package/src/shared/search-text.test.ts +47 -0
- package/src/shared/search-text.ts +63 -0
- package/src/shared/sqlite.test.ts +56 -0
- package/src/shared/sqlite.ts +51 -2
- package/src/shared/storage-file-mutex-review.test.ts +22 -2
- package/src/shared/storage-file-mutex.ts +11 -1
- package/src/shared/subagent-runner.ts +2 -0
- package/src/shared/system-directive.ts +19 -1
- package/src/shared/tag-transcript.ts +12 -4
- package/dist/embedding-backfill-5e1t5wha.js +0 -22
- package/dist/v2/embedding-backfill-jmaf8zrr.js +0 -21
- package/dist/wrapup-orchestrator-28xzsj5q.js +0 -48
|
@@ -11,13 +11,14 @@ import {
|
|
|
11
11
|
sessionLog2
|
|
12
12
|
} from "./server-f2xf5gcb.js";
|
|
13
13
|
import {
|
|
14
|
+
parseTree,
|
|
14
15
|
parseJsoncRecovering,
|
|
15
16
|
detectConfigFile,
|
|
16
17
|
cortexKitUserConfigBasePath,
|
|
17
18
|
cortexKitProjectConfigBasePath,
|
|
18
19
|
resolveLegacyConfigSourcesForHarness,
|
|
19
20
|
loadPluginConfigDetailed
|
|
20
|
-
} from "./server-
|
|
21
|
+
} from "./server-nj659894.js";
|
|
21
22
|
import {
|
|
22
23
|
catalogOutputReserve,
|
|
23
24
|
getSdkContextLimit,
|
|
@@ -30,7 +31,7 @@ import {
|
|
|
30
31
|
resolvePromptSurface,
|
|
31
32
|
DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
32
33
|
LIVE_RELOAD_CONFIG_PATHS
|
|
33
|
-
} from "./server-
|
|
34
|
+
} from "./server-271qxsf5.js";
|
|
34
35
|
import {
|
|
35
36
|
invalidateAutoEmbedSession,
|
|
36
37
|
drainBackgroundBatches,
|
|
@@ -39,12 +40,12 @@ import {
|
|
|
39
40
|
getProjectChunkEmbeddingModelId2,
|
|
40
41
|
getProjectEmbeddingMaxInputTokens2,
|
|
41
42
|
embedItemsForProject2
|
|
42
|
-
} from "./server-
|
|
43
|
+
} from "./server-8by8qfec.js";
|
|
43
44
|
import {
|
|
44
45
|
hasMeaningfulUserText2,
|
|
45
46
|
estimateTokens,
|
|
46
47
|
estimateFixedPromptTokens
|
|
47
|
-
} from "./server-
|
|
48
|
+
} from "./server-tgnbmwah.js";
|
|
48
49
|
import {
|
|
49
50
|
inRootAsyncContext2,
|
|
50
51
|
Database2,
|
|
@@ -52,7 +53,13 @@ import {
|
|
|
52
53
|
withSqliteBackgroundWriter2,
|
|
53
54
|
withoutSqliteTransformPass2,
|
|
54
55
|
beginSqliteWriterAsync2
|
|
55
|
-
} from "./server-
|
|
56
|
+
} from "./server-beht37jy.js";
|
|
57
|
+
import {
|
|
58
|
+
isStrictGapHealingMessage2,
|
|
59
|
+
noteRawSessionSummaryRowWritten2,
|
|
60
|
+
RawOrdinalsNotReady2,
|
|
61
|
+
runSessionWarmupWorker
|
|
62
|
+
} from "./server-xj136kt8.js";
|
|
56
63
|
import {
|
|
57
64
|
buildCanonicalChunkTextFromFts,
|
|
58
65
|
buildCompartmentSummaryFallbackText,
|
|
@@ -62,7 +69,7 @@ import {
|
|
|
62
69
|
replaceCompartmentChunkEmbeddings,
|
|
63
70
|
deleteChunkEmbedBackoffForSession,
|
|
64
71
|
chunkWindowSourceKey
|
|
65
|
-
} from "./server-
|
|
72
|
+
} from "./server-46neh5fa.js";
|
|
66
73
|
import {
|
|
67
74
|
isPidAlive
|
|
68
75
|
} from "./server-da07v4xp.js";
|
|
@@ -76,11 +83,13 @@ import {
|
|
|
76
83
|
ownsLkgDirtyFence,
|
|
77
84
|
commitLkgWithRecoveryFence,
|
|
78
85
|
clearLkgRecoveryFence,
|
|
86
|
+
gaDatabasePath,
|
|
87
|
+
V2StoreReader,
|
|
79
88
|
deleteSessionScopedRows,
|
|
80
89
|
toMessageIndexSource2,
|
|
81
90
|
clearIndexedMessagesInTransaction2,
|
|
82
91
|
indexSourcesAfterOrdinal2
|
|
83
|
-
} from "./server-
|
|
92
|
+
} from "./server-3rhpvy84.js";
|
|
84
93
|
import {
|
|
85
94
|
detectOverflow,
|
|
86
95
|
SESSION_META_SELECT_COLUMNS,
|
|
@@ -173,7 +182,7 @@ import {
|
|
|
173
182
|
getRawSessionTagKeysThrough2,
|
|
174
183
|
getLegacyProtectedTailStartOrdinal2,
|
|
175
184
|
readSessionChunk2
|
|
176
|
-
} from "./server-
|
|
185
|
+
} from "./server-kh7dpa1a.js";
|
|
177
186
|
import {
|
|
178
187
|
getTableColumnNames
|
|
179
188
|
} from "./server-pwv4ezb0.js";
|
|
@@ -183,7 +192,7 @@ import {
|
|
|
183
192
|
LATEST_SUPPORTED_VERSION,
|
|
184
193
|
getPersistedSchemaVersion,
|
|
185
194
|
openDatabase
|
|
186
|
-
} from "./server-
|
|
195
|
+
} from "./server-gtfhttbr.js";
|
|
187
196
|
import {
|
|
188
197
|
providerMass,
|
|
189
198
|
calibrationForModelKey,
|
|
@@ -201,13 +210,7 @@ import {
|
|
|
201
210
|
foldShrunkPartTags2,
|
|
202
211
|
getTagNumberByMessageId2,
|
|
203
212
|
getActiveTagsBySession2
|
|
204
|
-
} from "./server-
|
|
205
|
-
import {
|
|
206
|
-
isStrictGapHealingMessage2,
|
|
207
|
-
noteRawSessionSummaryRowWritten2,
|
|
208
|
-
RawOrdinalsNotReady2,
|
|
209
|
-
runSessionWarmupWorker
|
|
210
|
-
} from "./server-prg55b7k.js";
|
|
213
|
+
} from "./server-zyzawhdw.js";
|
|
211
214
|
import {
|
|
212
215
|
resolveOpenCodeDbPath,
|
|
213
216
|
assertOpenCodeStoreGeneration,
|
|
@@ -218,10 +221,10 @@ import {
|
|
|
218
221
|
openCodeDbExists,
|
|
219
222
|
withReadOnlySessionDb,
|
|
220
223
|
getMessageTimesFromOpenCodeDb
|
|
221
|
-
} from "./server-
|
|
224
|
+
} from "./server-n1prf1g6.js";
|
|
222
225
|
import {
|
|
223
226
|
getMeasuredToolDefinitionTokens
|
|
224
|
-
} from "./server-
|
|
227
|
+
} from "./server-g3qma5c0.js";
|
|
225
228
|
import {
|
|
226
229
|
V2_MEMORY_CATEGORIES,
|
|
227
230
|
CATEGORY_PRIORITY,
|
|
@@ -237,11 +240,11 @@ import {
|
|
|
237
240
|
resolveStoredPathWorkspaceIdentity,
|
|
238
241
|
sourceNameForMemory,
|
|
239
242
|
computeWorkspaceEpochFingerprint
|
|
240
|
-
} from "./server-
|
|
243
|
+
} from "./server-gpvay0xz.js";
|
|
241
244
|
import {
|
|
242
245
|
shouldSkipHomeProjectMemory,
|
|
243
246
|
resolveProjectIdentity
|
|
244
|
-
} from "./server-
|
|
247
|
+
} from "./server-rmygf5pn.js";
|
|
245
248
|
import {
|
|
246
249
|
getSessionNotes,
|
|
247
250
|
getReadySmartNotes,
|
|
@@ -250,13 +253,13 @@ import {
|
|
|
250
253
|
userFacingFailureCode,
|
|
251
254
|
promoteSessionFactsDurable,
|
|
252
255
|
embedPromotedFacts
|
|
253
|
-
} from "./server-
|
|
256
|
+
} from "./server-my7k4eds.js";
|
|
254
257
|
import {
|
|
255
258
|
isMarkerCandidateBasisCurrent2,
|
|
256
259
|
invalidateMarkerCandidateBasis2,
|
|
257
260
|
readMarkerCandidateBasis2,
|
|
258
261
|
prepareMarkerCandidateBasis2
|
|
259
|
-
} from "./server-
|
|
262
|
+
} from "./server-d04vrx0j.js";
|
|
260
263
|
import {
|
|
261
264
|
computeCueContentHash,
|
|
262
265
|
getMuralCueState,
|
|
@@ -264,7 +267,7 @@ import {
|
|
|
264
267
|
getMemoriesByProject2,
|
|
265
268
|
getMemoriesByProjects2,
|
|
266
269
|
getMaxMemoryIdForProjects2
|
|
267
|
-
} from "./server-
|
|
270
|
+
} from "./server-n37sebck.js";
|
|
268
271
|
import {
|
|
269
272
|
pushNotification2
|
|
270
273
|
} from "./server-x8a7jmkh.js";
|
|
@@ -275,13 +278,10 @@ import {
|
|
|
275
278
|
} from "./server-34kwfsr4.js";
|
|
276
279
|
import {
|
|
277
280
|
sendStatusNotification2
|
|
278
|
-
} from "./server-
|
|
281
|
+
} from "./server-a9xqj88f.js";
|
|
279
282
|
import {
|
|
280
283
|
piModelRefToCanonical
|
|
281
284
|
} from "./server-avwt563y.js";
|
|
282
|
-
import {
|
|
283
|
-
sameProjectDirectory
|
|
284
|
-
} from "./server-knvkbfvh.js";
|
|
285
285
|
import {
|
|
286
286
|
getErrorMessage,
|
|
287
287
|
describeError
|
|
@@ -1002,10 +1002,10 @@ function readProjectDocsCanonical(projectDirectory) {
|
|
|
1002
1002
|
return { renderedBlock, canonicalHash };
|
|
1003
1003
|
}
|
|
1004
1004
|
// src/hooks/magic-context/lkg-slot.ts
|
|
1005
|
-
import { createHash as
|
|
1005
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
1006
1006
|
|
|
1007
1007
|
// src/hooks/magic-context/lkg-measured-request.ts
|
|
1008
|
-
import { createHash as
|
|
1008
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1009
1009
|
|
|
1010
1010
|
// src/shared/provider-response-completion.ts
|
|
1011
1011
|
function providerResponseFailed(input) {
|
|
@@ -1073,691 +1073,6 @@ function cancelAutoSearchWork(sessionId) {
|
|
|
1073
1073
|
}
|
|
1074
1074
|
}
|
|
1075
1075
|
|
|
1076
|
-
// src/v2/store-reader.ts
|
|
1077
|
-
import { createHash as createHash3 } from "node:crypto";
|
|
1078
|
-
import { statSync as statSync3 } from "node:fs";
|
|
1079
|
-
import { hostname } from "node:os";
|
|
1080
|
-
import { resolve } from "node:path";
|
|
1081
|
-
function gaDatabasePath(dataHome, channel = "latest", env = process.env) {
|
|
1082
|
-
return resolveOpenCodeDbPath("v2", { dataHome, channel, env }).path;
|
|
1083
|
-
}
|
|
1084
|
-
var RAW_MESSAGE_TYPES = [
|
|
1085
|
-
"user",
|
|
1086
|
-
"synthetic",
|
|
1087
|
-
"assistant",
|
|
1088
|
-
"skill",
|
|
1089
|
-
"shell",
|
|
1090
|
-
"system"
|
|
1091
|
-
];
|
|
1092
|
-
var RAW_MESSAGE_TYPE_PARAMETERS = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1093
|
-
var V2_MESSAGE_PAGE_SQL = `WITH bounds AS (
|
|
1094
|
-
SELECT
|
|
1095
|
-
CASE WHEN ? = 0 THEN -1 ELSE COALESCE((
|
|
1096
|
-
SELECT seq FROM session_message
|
|
1097
|
-
WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
|
|
1098
|
-
ORDER BY seq ASC LIMIT 1 OFFSET ?
|
|
1099
|
-
), (SELECT MAX(seq) FROM session_message WHERE session_id = ?), -1) END AS after_seq,
|
|
1100
|
-
COALESCE((
|
|
1101
|
-
SELECT seq FROM session_message
|
|
1102
|
-
WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
|
|
1103
|
-
ORDER BY seq ASC LIMIT 1 OFFSET ?
|
|
1104
|
-
), ?) AS watermark_seq
|
|
1105
|
-
)
|
|
1106
|
-
SELECT id, session_id, type, seq, time_created, data FROM session_message, bounds
|
|
1107
|
-
WHERE session_id = ?
|
|
1108
|
-
AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
|
|
1109
|
-
AND seq > bounds.after_seq
|
|
1110
|
-
AND seq <= bounds.watermark_seq
|
|
1111
|
-
ORDER BY seq ASC LIMIT ?`;
|
|
1112
|
-
var V2_STORE_READER_DEBUG_COUNTER_KEY = "magic-context.v2.store-reader-debug";
|
|
1113
|
-
var debugSymbol = Symbol.for(V2_STORE_READER_DEBUG_COUNTER_KEY);
|
|
1114
|
-
var debugGlobal = globalThis;
|
|
1115
|
-
var QUERY_STATEMENTS = {
|
|
1116
|
-
messagePage: V2_MESSAGE_PAGE_SQL,
|
|
1117
|
-
messageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND type IN (?)",
|
|
1118
|
-
storedMessageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?",
|
|
1119
|
-
messageById: "SELECT id, session_id, type, seq, time_created, data FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1",
|
|
1120
|
-
messageExistsById: "SELECT 1 FROM session_message WHERE id = ? AND session_id = ? AND type IN (?) LIMIT 1",
|
|
1121
|
-
messageOrdinalById: `WITH target AS (
|
|
1122
|
-
SELECT seq FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1
|
|
1123
|
-
)
|
|
1124
|
-
SELECT (SELECT COUNT(*) FROM session_message WHERE session_id = ? AND type IN (?) AND seq <= target.seq) AS ordinal FROM target`,
|
|
1125
|
-
messageIdOrdinals: "SELECT id FROM session_message WHERE session_id = ? AND type IN (?) ORDER BY seq ASC LIMIT ? OFFSET ?",
|
|
1126
|
-
messageOrdinalPage: "SELECT id, type, seq, json_valid(data) AS valid FROM session_message WHERE session_id = ? AND seq > ? ORDER BY seq ASC, id ASC LIMIT ?",
|
|
1127
|
-
rawRowsThrough: "SELECT id, session_id, type, seq, time_created, data FROM session_message WHERE session_id = ? AND type IN (?) AND seq <= ? ORDER BY seq DESC LIMIT ?"
|
|
1128
|
-
};
|
|
1129
|
-
function debugCounters() {
|
|
1130
|
-
const counters = debugGlobal[debugSymbol] ??= {
|
|
1131
|
-
decodedRows: 0,
|
|
1132
|
-
operations: {},
|
|
1133
|
-
openReaders: 0,
|
|
1134
|
-
maxOpenReaders: 0,
|
|
1135
|
-
readersOpened: 0,
|
|
1136
|
-
readersClosed: 0
|
|
1137
|
-
};
|
|
1138
|
-
counters.openReaders ??= 0;
|
|
1139
|
-
counters.maxOpenReaders ??= 0;
|
|
1140
|
-
counters.readersOpened ??= 0;
|
|
1141
|
-
counters.readersClosed ??= 0;
|
|
1142
|
-
return counters;
|
|
1143
|
-
}
|
|
1144
|
-
function returnedRowCount(value) {
|
|
1145
|
-
if (Array.isArray(value))
|
|
1146
|
-
return value.length;
|
|
1147
|
-
if (value === null || value === undefined || value === false)
|
|
1148
|
-
return 0;
|
|
1149
|
-
return 1;
|
|
1150
|
-
}
|
|
1151
|
-
function trackDecodeOperation(name, operation) {
|
|
1152
|
-
const counters = debugCounters();
|
|
1153
|
-
const before = counters.decodedRows;
|
|
1154
|
-
const started = performance.now();
|
|
1155
|
-
let value;
|
|
1156
|
-
try {
|
|
1157
|
-
value = operation();
|
|
1158
|
-
return value;
|
|
1159
|
-
} finally {
|
|
1160
|
-
const decodedRows = counters.decodedRows - before;
|
|
1161
|
-
const current = counters.operations[name] ?? {
|
|
1162
|
-
calls: 0,
|
|
1163
|
-
decodedRows: 0,
|
|
1164
|
-
maxDecodedRows: 0
|
|
1165
|
-
};
|
|
1166
|
-
current.calls += 1;
|
|
1167
|
-
current.decodedRows += decodedRows;
|
|
1168
|
-
current.maxDecodedRows = Math.max(current.maxDecodedRows, decodedRows);
|
|
1169
|
-
counters.operations[name] = current;
|
|
1170
|
-
const statement = QUERY_STATEMENTS[name];
|
|
1171
|
-
if (counters.captureQueries && statement) {
|
|
1172
|
-
(counters.queries ??= []).push({
|
|
1173
|
-
operation: name,
|
|
1174
|
-
statement,
|
|
1175
|
-
rows: returnedRowCount(value),
|
|
1176
|
-
elapsedMs: performance.now() - started
|
|
1177
|
-
});
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
function decode(row) {
|
|
1182
|
-
debugCounters().decodedRows += 1;
|
|
1183
|
-
const data = JSON.parse(row.data);
|
|
1184
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
1185
|
-
throw new Error(`Invalid session_message data at seq ${row.seq}`);
|
|
1186
|
-
}
|
|
1187
|
-
if (row.type === "idle" && !["succeeded", "failed", "interrupted"].includes(String(data.outcome))) {
|
|
1188
|
-
throw new Error(`Invalid idle outcome at seq ${row.seq}`);
|
|
1189
|
-
}
|
|
1190
|
-
return { ...row, data };
|
|
1191
|
-
}
|
|
1192
|
-
function connect(path, identity = "") {
|
|
1193
|
-
const stat = statSync3(path);
|
|
1194
|
-
const acquiredIdentity = identity || `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
|
|
1195
|
-
const db = new Database2(path, { readonly: true, fileMustExist: true });
|
|
1196
|
-
try {
|
|
1197
|
-
assertOpenCodeStoreGeneration(db, "v2", path);
|
|
1198
|
-
} catch (error) {
|
|
1199
|
-
db.close();
|
|
1200
|
-
throw error;
|
|
1201
|
-
}
|
|
1202
|
-
const counters = debugCounters();
|
|
1203
|
-
counters.openReaders += 1;
|
|
1204
|
-
counters.readersOpened += 1;
|
|
1205
|
-
counters.maxOpenReaders = Math.max(counters.maxOpenReaders, counters.openReaders);
|
|
1206
|
-
return { db, statements: new Map, identity: acquiredIdentity, leases: 0, retired: false };
|
|
1207
|
-
}
|
|
1208
|
-
function closeConnection(connection) {
|
|
1209
|
-
connection.statements.clear();
|
|
1210
|
-
try {
|
|
1211
|
-
connection.db.close();
|
|
1212
|
-
} finally {
|
|
1213
|
-
const counters = debugCounters();
|
|
1214
|
-
counters.openReaders = Math.max(0, counters.openReaders - 1);
|
|
1215
|
-
counters.readersClosed += 1;
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
class V2StoreReaderPool {
|
|
1220
|
-
capacity;
|
|
1221
|
-
connections = new Map;
|
|
1222
|
-
closed = false;
|
|
1223
|
-
closing = false;
|
|
1224
|
-
holds = 0;
|
|
1225
|
-
idleWaiters = new Set;
|
|
1226
|
-
constructor(capacity = 4) {
|
|
1227
|
-
this.capacity = capacity;
|
|
1228
|
-
if (!Number.isSafeInteger(capacity) || capacity < 1)
|
|
1229
|
-
throw new Error("Invalid reader capacity");
|
|
1230
|
-
}
|
|
1231
|
-
open(path) {
|
|
1232
|
-
return new V2StoreReader(path, this);
|
|
1233
|
-
}
|
|
1234
|
-
acquire(path) {
|
|
1235
|
-
if (this.closed)
|
|
1236
|
-
throw new Error("Store reader pool is closed");
|
|
1237
|
-
const key = resolve(path);
|
|
1238
|
-
const stat = statSync3(key);
|
|
1239
|
-
const identity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
|
|
1240
|
-
let connection = this.connections.get(key);
|
|
1241
|
-
if (connection && connection.identity !== identity) {
|
|
1242
|
-
this.connections.delete(key);
|
|
1243
|
-
this.retire(connection);
|
|
1244
|
-
connection = undefined;
|
|
1245
|
-
}
|
|
1246
|
-
if (!connection)
|
|
1247
|
-
connection = connect(key, identity);
|
|
1248
|
-
connection.leases++;
|
|
1249
|
-
this.connections.delete(key);
|
|
1250
|
-
this.connections.set(key, connection);
|
|
1251
|
-
while (this.connections.size > this.capacity) {
|
|
1252
|
-
const oldest = this.connections.entries().next().value;
|
|
1253
|
-
if (!oldest)
|
|
1254
|
-
break;
|
|
1255
|
-
this.connections.delete(oldest[0]);
|
|
1256
|
-
this.retire(oldest[1]);
|
|
1257
|
-
}
|
|
1258
|
-
return connection;
|
|
1259
|
-
}
|
|
1260
|
-
release(connection) {
|
|
1261
|
-
connection.leases--;
|
|
1262
|
-
if (connection.retired && connection.leases === 0)
|
|
1263
|
-
closeConnection(connection);
|
|
1264
|
-
}
|
|
1265
|
-
retire(connection) {
|
|
1266
|
-
connection.retired = true;
|
|
1267
|
-
if (connection.leases === 0)
|
|
1268
|
-
closeConnection(connection);
|
|
1269
|
-
}
|
|
1270
|
-
hold() {
|
|
1271
|
-
if (this.closed || this.closing)
|
|
1272
|
-
throw new Error("Store reader pool is closed");
|
|
1273
|
-
this.holds++;
|
|
1274
|
-
let released = false;
|
|
1275
|
-
return () => {
|
|
1276
|
-
if (released)
|
|
1277
|
-
return;
|
|
1278
|
-
released = true;
|
|
1279
|
-
this.holds--;
|
|
1280
|
-
if (this.holds === 0 && this.closing)
|
|
1281
|
-
this.finishClose();
|
|
1282
|
-
};
|
|
1283
|
-
}
|
|
1284
|
-
isClosed() {
|
|
1285
|
-
return this.closed;
|
|
1286
|
-
}
|
|
1287
|
-
holdCount() {
|
|
1288
|
-
return this.holds;
|
|
1289
|
-
}
|
|
1290
|
-
close() {
|
|
1291
|
-
if (this.closed || this.closing)
|
|
1292
|
-
return;
|
|
1293
|
-
this.closing = true;
|
|
1294
|
-
if (this.holds === 0)
|
|
1295
|
-
this.finishClose();
|
|
1296
|
-
}
|
|
1297
|
-
async closeWhenIdle(timeoutMs) {
|
|
1298
|
-
this.close();
|
|
1299
|
-
if (this.closed)
|
|
1300
|
-
return true;
|
|
1301
|
-
let timer;
|
|
1302
|
-
let waiter;
|
|
1303
|
-
try {
|
|
1304
|
-
await new Promise((resolve) => {
|
|
1305
|
-
waiter = resolve;
|
|
1306
|
-
this.idleWaiters.add(resolve);
|
|
1307
|
-
timer = setTimeout(resolve, Math.max(0, timeoutMs));
|
|
1308
|
-
});
|
|
1309
|
-
} finally {
|
|
1310
|
-
if (timer)
|
|
1311
|
-
clearTimeout(timer);
|
|
1312
|
-
if (waiter)
|
|
1313
|
-
this.idleWaiters.delete(waiter);
|
|
1314
|
-
}
|
|
1315
|
-
return this.closed;
|
|
1316
|
-
}
|
|
1317
|
-
finishClose() {
|
|
1318
|
-
if (this.closed)
|
|
1319
|
-
return;
|
|
1320
|
-
this.closed = true;
|
|
1321
|
-
for (const connection of this.connections.values())
|
|
1322
|
-
this.retire(connection);
|
|
1323
|
-
this.connections.clear();
|
|
1324
|
-
for (const resolve of this.idleWaiters)
|
|
1325
|
-
resolve();
|
|
1326
|
-
this.idleWaiters.clear();
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
class V2StoreReader {
|
|
1331
|
-
path;
|
|
1332
|
-
pool;
|
|
1333
|
-
db;
|
|
1334
|
-
connection;
|
|
1335
|
-
closed = false;
|
|
1336
|
-
constructor(path, pool) {
|
|
1337
|
-
this.path = path;
|
|
1338
|
-
this.pool = pool;
|
|
1339
|
-
this.connection = pool ? pool.acquire(path) : connect(path);
|
|
1340
|
-
this.db = this.connection.db;
|
|
1341
|
-
}
|
|
1342
|
-
hostIdentity() {
|
|
1343
|
-
return createHash3("sha256").update(JSON.stringify([hostname(), resolve(this.path), this.connection.identity])).digest("hex");
|
|
1344
|
-
}
|
|
1345
|
-
prepare(sql) {
|
|
1346
|
-
if (this.closed)
|
|
1347
|
-
throw new Error("Store reader is closed");
|
|
1348
|
-
const statements = this.connection.statements;
|
|
1349
|
-
let statement = statements.get(sql);
|
|
1350
|
-
if (!statement) {
|
|
1351
|
-
statement = this.db.prepare(sql);
|
|
1352
|
-
if (statements.size >= 128)
|
|
1353
|
-
statements.clear();
|
|
1354
|
-
statements.set(sql, statement);
|
|
1355
|
-
}
|
|
1356
|
-
return statement;
|
|
1357
|
-
}
|
|
1358
|
-
close() {
|
|
1359
|
-
if (this.closed)
|
|
1360
|
-
return;
|
|
1361
|
-
this.closed = true;
|
|
1362
|
-
if (this.pool)
|
|
1363
|
-
this.pool.release(this.connection);
|
|
1364
|
-
else
|
|
1365
|
-
closeConnection(this.connection);
|
|
1366
|
-
}
|
|
1367
|
-
page(sessionID, options = {}) {
|
|
1368
|
-
return trackDecodeOperation("page", () => {
|
|
1369
|
-
const limit = options.limit ?? 100;
|
|
1370
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
1371
|
-
throw new Error("Invalid page limit");
|
|
1372
|
-
const after = options.after ?? -1;
|
|
1373
|
-
if (!Number.isSafeInteger(after))
|
|
1374
|
-
throw new Error("Invalid seq cursor");
|
|
1375
|
-
if (options.through !== undefined && !Number.isSafeInteger(options.through))
|
|
1376
|
-
throw new Error("Invalid seq upper bound");
|
|
1377
|
-
const predicates = ["session_id = ?", "seq > ?"];
|
|
1378
|
-
const parameters = [sessionID, after];
|
|
1379
|
-
if (options.through !== undefined) {
|
|
1380
|
-
predicates.push("seq <= ?");
|
|
1381
|
-
parameters.push(options.through);
|
|
1382
|
-
}
|
|
1383
|
-
if (options.type) {
|
|
1384
|
-
predicates.push("type = ?");
|
|
1385
|
-
parameters.push(options.type);
|
|
1386
|
-
}
|
|
1387
|
-
const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1388
|
-
WHERE ${predicates.join(" AND ")}
|
|
1389
|
-
ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode);
|
|
1390
|
-
return { rows, cursor: rows.at(-1)?.seq };
|
|
1391
|
-
});
|
|
1392
|
-
}
|
|
1393
|
-
messagePage(sessionID, afterOrdinal, limit, finalWatermark, after) {
|
|
1394
|
-
return trackDecodeOperation("messagePage", () => {
|
|
1395
|
-
if (!Number.isSafeInteger(afterOrdinal) || afterOrdinal < 0)
|
|
1396
|
-
throw new Error("Invalid raw-message ordinal cursor");
|
|
1397
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
1398
|
-
throw new Error("Invalid page limit");
|
|
1399
|
-
if (!Number.isSafeInteger(finalWatermark) || finalWatermark < 0)
|
|
1400
|
-
throw new Error("Invalid raw-message watermark");
|
|
1401
|
-
const pageSize = Math.min(limit, finalWatermark - afterOrdinal);
|
|
1402
|
-
if (pageSize <= 0)
|
|
1403
|
-
return [];
|
|
1404
|
-
if (after) {
|
|
1405
|
-
const anchor = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ?").get(sessionID, after.id);
|
|
1406
|
-
if (anchor) {
|
|
1407
|
-
return this.prepare(`SELECT id, session_id, type, seq, time_created, data
|
|
1408
|
-
FROM session_message WHERE session_id = ? AND seq > ?
|
|
1409
|
-
AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES, pageSize).map(decode);
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
|
-
const maximumSeq = Number.MAX_SAFE_INTEGER;
|
|
1413
|
-
const rows = this.prepare(V2_MESSAGE_PAGE_SQL).all(afterOrdinal, sessionID, ...RAW_MESSAGE_TYPES, Math.max(0, afterOrdinal - 1), sessionID, sessionID, ...RAW_MESSAGE_TYPES, finalWatermark - 1, maximumSeq, sessionID, ...RAW_MESSAGE_TYPES, pageSize);
|
|
1414
|
-
return rows.map(decode);
|
|
1415
|
-
});
|
|
1416
|
-
}
|
|
1417
|
-
messageCount(sessionID) {
|
|
1418
|
-
return trackDecodeOperation("messageCount", () => {
|
|
1419
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1420
|
-
const row = this.prepare(`SELECT COUNT(*) AS count FROM session_message
|
|
1421
|
-
WHERE session_id = ? AND type IN (${rawTypes})`).get(sessionID, ...RAW_MESSAGE_TYPES);
|
|
1422
|
-
return typeof row?.count === "number" ? row.count : 0;
|
|
1423
|
-
});
|
|
1424
|
-
}
|
|
1425
|
-
sessionDirectoryPage(afterSessionID, limit) {
|
|
1426
|
-
const rows = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
|
|
1427
|
-
WHERE id > ? ORDER BY id ASC LIMIT ?`).all(afterSessionID ?? "", limit);
|
|
1428
|
-
return rows.map((row) => ({ sessionId: row.id, directory: row.directory }));
|
|
1429
|
-
}
|
|
1430
|
-
latestMessageTime(sessionID) {
|
|
1431
|
-
const row = this.prepare("SELECT MAX(time_created) AS time FROM session_message WHERE session_id = ?").get(sessionID);
|
|
1432
|
-
return row?.time ?? undefined;
|
|
1433
|
-
}
|
|
1434
|
-
isSubagent(sessionID) {
|
|
1435
|
-
const row = this.prepare("SELECT parent_id FROM session_v2 WHERE id = ?").get(sessionID);
|
|
1436
|
-
if (!row)
|
|
1437
|
-
return null;
|
|
1438
|
-
return typeof row.parent_id === "string" && row.parent_id.length > 0;
|
|
1439
|
-
}
|
|
1440
|
-
latestRootSessionInDirectory(directory) {
|
|
1441
|
-
const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
|
|
1442
|
-
const archived = columns.has("time_archived") ? " AND time_archived IS NULL" : "";
|
|
1443
|
-
const order = columns.has("time_updated") ? "time_updated DESC, id DESC" : "id DESC";
|
|
1444
|
-
const page = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
|
|
1445
|
-
WHERE parent_id IS NULL${archived}
|
|
1446
|
-
AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
|
|
1447
|
-
ORDER BY ${order} LIMIT ? OFFSET ?`);
|
|
1448
|
-
const pageSize = 500;
|
|
1449
|
-
for (let offset = 0;; offset += pageSize) {
|
|
1450
|
-
const rows = page.all(pageSize, offset);
|
|
1451
|
-
const match = rows.find((row) => sameProjectDirectory(row.directory, directory));
|
|
1452
|
-
if (match)
|
|
1453
|
-
return match.id;
|
|
1454
|
-
if (rows.length < pageSize)
|
|
1455
|
-
return;
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1458
|
-
rootSessionActivity(sessionIDs) {
|
|
1459
|
-
const roots = new Map;
|
|
1460
|
-
for (let offset = 0;offset < sessionIDs.length; offset += 500) {
|
|
1461
|
-
const chunk = sessionIDs.slice(offset, offset + 500);
|
|
1462
|
-
const rows = this.prepare(`SELECT id, (
|
|
1463
|
-
SELECT MAX(time_created) FROM session_message
|
|
1464
|
-
WHERE session_id = session_v2.id AND type = 'user'
|
|
1465
|
-
) AS time FROM session_v2
|
|
1466
|
-
WHERE parent_id IS NULL
|
|
1467
|
-
AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
|
|
1468
|
-
AND id IN (${chunk.map(() => "?").join(",")})`).all(...chunk);
|
|
1469
|
-
for (const row of rows)
|
|
1470
|
-
if (row.time !== null)
|
|
1471
|
-
roots.set(row.id, row.time);
|
|
1472
|
-
}
|
|
1473
|
-
return roots;
|
|
1474
|
-
}
|
|
1475
|
-
oldestUserMessageTimesSince(sessionIDs, sinceMs) {
|
|
1476
|
-
const result = new Map;
|
|
1477
|
-
for (let offset = 0;offset < sessionIDs.length; offset += 500) {
|
|
1478
|
-
const chunk = sessionIDs.slice(offset, offset + 500);
|
|
1479
|
-
const rows = this.prepare(`SELECT session_id, MIN(time_created) AS time FROM session_message
|
|
1480
|
-
WHERE type = 'user' AND time_created > ? AND session_id IN (${chunk.map(() => "?").join(",")})
|
|
1481
|
-
GROUP BY session_id`).all(sinceMs, ...chunk);
|
|
1482
|
-
for (const row of rows)
|
|
1483
|
-
result.set(row.session_id, row.time);
|
|
1484
|
-
}
|
|
1485
|
-
return result;
|
|
1486
|
-
}
|
|
1487
|
-
retrospectiveUserPage(sessionID, options) {
|
|
1488
|
-
const { boundaryMs, before, limit, maxChars, truncationMarker } = options;
|
|
1489
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
1490
|
-
throw new Error("Invalid page limit");
|
|
1491
|
-
if (!Number.isSafeInteger(maxChars) || maxChars <= truncationMarker.length)
|
|
1492
|
-
throw new Error("Invalid text limit");
|
|
1493
|
-
const direction = before ? "DESC" : "ASC";
|
|
1494
|
-
const head = Math.floor((maxChars - truncationMarker.length) / 2);
|
|
1495
|
-
const tail = maxChars - truncationMarker.length - head;
|
|
1496
|
-
return this.prepare(`WITH users AS (
|
|
1497
|
-
SELECT session_id, seq, time_created, data FROM session_message
|
|
1498
|
-
WHERE session_id = ? AND type = 'user' AND time_created ${before ? "<=" : ">"}
|
|
1499
|
-
?
|
|
1500
|
-
ORDER BY time_created ${direction}, seq ${direction} LIMIT ?
|
|
1501
|
-
), texts AS (
|
|
1502
|
-
SELECT session_id, seq, time_created, CASE
|
|
1503
|
-
WHEN json_extract(data, '$.synthetic') = 1 OR json_extract(data, '$.ignored') = 1 THEN ''
|
|
1504
|
-
WHEN json_type(data, '$.text') = 'text' THEN json_extract(data, '$.text')
|
|
1505
|
-
ELSE COALESCE((SELECT group_concat(json_extract(value, '$.text'), char(10))
|
|
1506
|
-
FROM json_each(users.data, '$.content')
|
|
1507
|
-
WHERE json_extract(value, '$.type') IN ('text', 'input_text')
|
|
1508
|
-
AND COALESCE(json_extract(value, '$.synthetic'), 0) <> 1
|
|
1509
|
-
AND COALESCE(json_extract(value, '$.ignored'), 0) <> 1), '') END AS text
|
|
1510
|
-
FROM users WHERE json_valid(data)
|
|
1511
|
-
) SELECT seq, time_created, CASE WHEN length(text) > ?
|
|
1512
|
-
THEN substr(text, 1, ?) || ? || substr(text, -?) ELSE text END AS text,
|
|
1513
|
-
EXISTS (
|
|
1514
|
-
SELECT 1 FROM session_message assistant_reply
|
|
1515
|
-
WHERE assistant_reply.session_id = texts.session_id
|
|
1516
|
-
AND assistant_reply.type = 'assistant'
|
|
1517
|
-
AND assistant_reply.seq < texts.seq
|
|
1518
|
-
AND EXISTS (
|
|
1519
|
-
SELECT 1 FROM session_message prior_user
|
|
1520
|
-
WHERE prior_user.session_id = texts.session_id
|
|
1521
|
-
AND prior_user.type = 'user'
|
|
1522
|
-
AND prior_user.seq < assistant_reply.seq
|
|
1523
|
-
)
|
|
1524
|
-
) AS follows_assistant_reply
|
|
1525
|
-
FROM texts ORDER BY time_created ${direction}, seq ${direction}`).all(sessionID, boundaryMs, limit, maxChars, head, truncationMarker, tail);
|
|
1526
|
-
}
|
|
1527
|
-
storedRowsAfter(sessionID, after) {
|
|
1528
|
-
const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND seq > ?").get(sessionID, after);
|
|
1529
|
-
return row.count;
|
|
1530
|
-
}
|
|
1531
|
-
storedMessageCount(sessionID) {
|
|
1532
|
-
return trackDecodeOperation("storedMessageCount", () => {
|
|
1533
|
-
const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?").get(sessionID);
|
|
1534
|
-
return typeof row?.count === "number" ? row.count : 0;
|
|
1535
|
-
});
|
|
1536
|
-
}
|
|
1537
|
-
messageById(sessionID, id) {
|
|
1538
|
-
return trackDecodeOperation("messageById", () => {
|
|
1539
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1540
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1541
|
-
WHERE session_id = ? AND id = ? AND type IN (${rawTypes}) LIMIT 1`).get(sessionID, id, ...RAW_MESSAGE_TYPES);
|
|
1542
|
-
return row ? decode(row) : null;
|
|
1543
|
-
});
|
|
1544
|
-
}
|
|
1545
|
-
messageTimes(sessionID, ids) {
|
|
1546
|
-
const times = new Map;
|
|
1547
|
-
for (let offset = 0;offset < ids.length; offset += 500) {
|
|
1548
|
-
const batch = ids.slice(offset, offset + 500);
|
|
1549
|
-
const rows = this.prepare(`SELECT id, COALESCE(time_created, json_extract(data, '$.time.created')) AS created,
|
|
1550
|
-
json_extract(data, '$.time.completed') AS completed
|
|
1551
|
-
FROM session_message WHERE session_id = ? AND id IN (${batch.map(() => "?").join(",")})`).all(sessionID, ...batch);
|
|
1552
|
-
for (const row of rows)
|
|
1553
|
-
times.set(row.id, {
|
|
1554
|
-
created: typeof row.created === "number" ? row.created : undefined,
|
|
1555
|
-
completed: typeof row.completed === "number" ? row.completed : undefined
|
|
1556
|
-
});
|
|
1557
|
-
}
|
|
1558
|
-
return times;
|
|
1559
|
-
}
|
|
1560
|
-
messageExistsById(sessionID, id) {
|
|
1561
|
-
return trackDecodeOperation("messageExistsById", () => {
|
|
1562
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1563
|
-
const row = this.prepare(`SELECT 1 FROM session_message
|
|
1564
|
-
WHERE id = ? AND session_id = ? AND type IN (${rawTypes}) LIMIT 1`).get(id, sessionID, ...RAW_MESSAGE_TYPES);
|
|
1565
|
-
return row != null;
|
|
1566
|
-
});
|
|
1567
|
-
}
|
|
1568
|
-
messageOrdinalById(sessionID, id) {
|
|
1569
|
-
return trackDecodeOperation("messageOrdinalById", () => {
|
|
1570
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1571
|
-
const row = this.prepare(`WITH target AS (
|
|
1572
|
-
SELECT seq FROM session_message
|
|
1573
|
-
WHERE session_id = ? AND id = ? AND type IN (${rawTypes})
|
|
1574
|
-
LIMIT 1
|
|
1575
|
-
)
|
|
1576
|
-
SELECT (
|
|
1577
|
-
SELECT COUNT(*) FROM session_message
|
|
1578
|
-
WHERE session_id = ?
|
|
1579
|
-
AND type IN (${rawTypes})
|
|
1580
|
-
AND seq <= target.seq
|
|
1581
|
-
) AS ordinal
|
|
1582
|
-
FROM target`).get(sessionID, id, ...RAW_MESSAGE_TYPES, sessionID, ...RAW_MESSAGE_TYPES);
|
|
1583
|
-
return typeof row?.ordinal === "number" ? row.ordinal : null;
|
|
1584
|
-
});
|
|
1585
|
-
}
|
|
1586
|
-
messageIdOrdinals(sessionID, fromOrdinal, toOrdinal) {
|
|
1587
|
-
return trackDecodeOperation("messageIdOrdinals", () => {
|
|
1588
|
-
if (!Number.isSafeInteger(fromOrdinal) || fromOrdinal < 1)
|
|
1589
|
-
throw new Error("Invalid raw-message range start");
|
|
1590
|
-
if (!Number.isSafeInteger(toOrdinal) || toOrdinal < fromOrdinal)
|
|
1591
|
-
throw new Error("Invalid raw-message range end");
|
|
1592
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1593
|
-
const rows = this.prepare(`SELECT id FROM session_message
|
|
1594
|
-
WHERE session_id = ? AND type IN (${rawTypes})
|
|
1595
|
-
ORDER BY seq ASC LIMIT ? OFFSET ?`).all(sessionID, ...RAW_MESSAGE_TYPES, toOrdinal - fromOrdinal + 1, fromOrdinal - 1);
|
|
1596
|
-
return new Map(rows.map((row, index) => [row.id, fromOrdinal + index]));
|
|
1597
|
-
});
|
|
1598
|
-
}
|
|
1599
|
-
messageOrdinalPage(sessionID, after, limit) {
|
|
1600
|
-
return trackDecodeOperation("messageOrdinalPage", () => {
|
|
1601
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
1602
|
-
throw new Error("Invalid page limit");
|
|
1603
|
-
const rows = after ? this.prepare(`SELECT id, type, seq, json_valid(data) AS valid
|
|
1604
|
-
FROM session_message
|
|
1605
|
-
WHERE session_id = ? AND (seq > ? OR (seq = ? AND id > ?))
|
|
1606
|
-
ORDER BY seq ASC, id ASC LIMIT ?`).all(sessionID, after.timeCreated, after.timeCreated, after.id, limit) : this.prepare(`SELECT id, type, seq, json_valid(data) AS valid
|
|
1607
|
-
FROM session_message
|
|
1608
|
-
WHERE session_id = ?
|
|
1609
|
-
ORDER BY seq ASC, id ASC LIMIT ?`).all(sessionID, limit);
|
|
1610
|
-
const rawTypes = new Set(RAW_MESSAGE_TYPES);
|
|
1611
|
-
return rows.map((row) => ({
|
|
1612
|
-
id: row.id,
|
|
1613
|
-
timeCreated: row.seq,
|
|
1614
|
-
contributesOrdinal: rawTypes.has(row.type),
|
|
1615
|
-
hasValidInfo: row.valid === 1
|
|
1616
|
-
}));
|
|
1617
|
-
});
|
|
1618
|
-
}
|
|
1619
|
-
range(sessionID, after, through) {
|
|
1620
|
-
return trackDecodeOperation("range", () => through <= after ? [] : this.all(sessionID, after, undefined, through));
|
|
1621
|
-
}
|
|
1622
|
-
spanRowStamps(sessionID, after, through) {
|
|
1623
|
-
if (!Number.isSafeInteger(after) || !Number.isSafeInteger(through))
|
|
1624
|
-
throw new Error("Invalid seq span");
|
|
1625
|
-
const rows = this.prepare(`SELECT seq, id, time_updated AS updated, length(CAST(data AS BLOB)) AS bytes
|
|
1626
|
-
FROM session_message WHERE session_id = ? AND seq > ? AND seq <= ?
|
|
1627
|
-
ORDER BY seq ASC`).all(sessionID, after, through);
|
|
1628
|
-
const stamps = new Map;
|
|
1629
|
-
for (const row of rows)
|
|
1630
|
-
stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}`);
|
|
1631
|
-
return stamps;
|
|
1632
|
-
}
|
|
1633
|
-
rawRowsThrough(sessionID, throughSeq, limit) {
|
|
1634
|
-
return trackDecodeOperation("rawRowsThrough", () => {
|
|
1635
|
-
if (!Number.isSafeInteger(throughSeq))
|
|
1636
|
-
throw new Error("Invalid seq upper bound");
|
|
1637
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
1638
|
-
throw new Error("Invalid page limit");
|
|
1639
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
1640
|
-
return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1641
|
-
WHERE session_id = ? AND type IN (${rawTypes}) AND seq <= ?
|
|
1642
|
-
ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES, throughSeq, limit).map(decode);
|
|
1643
|
-
});
|
|
1644
|
-
}
|
|
1645
|
-
sequenceForId(sessionID, id) {
|
|
1646
|
-
if (!id)
|
|
1647
|
-
return;
|
|
1648
|
-
const row = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ? LIMIT 1").get(sessionID, id);
|
|
1649
|
-
return typeof row?.seq === "number" ? row.seq : undefined;
|
|
1650
|
-
}
|
|
1651
|
-
syntheticMessageIDs(sessionID) {
|
|
1652
|
-
const rows = this.prepare("SELECT id FROM session_message WHERE session_id = ? AND type = 'synthetic'").all(sessionID);
|
|
1653
|
-
return new Set(rows.map((row) => row.id));
|
|
1654
|
-
}
|
|
1655
|
-
forkOrigin(sessionID) {
|
|
1656
|
-
const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
|
|
1657
|
-
if (!columns.has("fork_session_id") || !columns.has("fork_boundary"))
|
|
1658
|
-
return null;
|
|
1659
|
-
const row = this.prepare("SELECT fork_session_id, fork_boundary FROM session_v2 WHERE id = ?").get(sessionID);
|
|
1660
|
-
if (!row?.fork_session_id || !row.fork_boundary)
|
|
1661
|
-
return null;
|
|
1662
|
-
try {
|
|
1663
|
-
const boundary = JSON.parse(row.fork_boundary);
|
|
1664
|
-
if (boundary.type !== "before" && boundary.type !== "through" || typeof boundary.messageID !== "string" || boundary.messageID.length === 0)
|
|
1665
|
-
return null;
|
|
1666
|
-
return {
|
|
1667
|
-
parentSessionID: row.fork_session_id,
|
|
1668
|
-
boundary: { type: boundary.type, messageID: boundary.messageID }
|
|
1669
|
-
};
|
|
1670
|
-
} catch {
|
|
1671
|
-
return null;
|
|
1672
|
-
}
|
|
1673
|
-
}
|
|
1674
|
-
sessionExists(sessionID) {
|
|
1675
|
-
return this.prepare("SELECT 1 FROM session_v2 WHERE id = ?").get(sessionID) != null;
|
|
1676
|
-
}
|
|
1677
|
-
rowStampsThrough(sessionID, throughSeq) {
|
|
1678
|
-
return this.prepare(`SELECT id, type, seq, time_created FROM session_message
|
|
1679
|
-
WHERE session_id = ? AND seq <= ? ORDER BY seq ASC`).all(sessionID, throughSeq);
|
|
1680
|
-
}
|
|
1681
|
-
latestSequenceForIds(sessionID, ids) {
|
|
1682
|
-
let latest = -1;
|
|
1683
|
-
for (let offset = 0;offset < ids.length; offset += 500) {
|
|
1684
|
-
const chunk = ids.slice(offset, offset + 500);
|
|
1685
|
-
const row = this.prepare(`SELECT MAX(seq) AS seq FROM session_message
|
|
1686
|
-
WHERE session_id = ? AND id IN (${chunk.map(() => "?").join(", ")})`).get(sessionID, ...chunk);
|
|
1687
|
-
if (typeof row?.seq === "number")
|
|
1688
|
-
latest = Math.max(latest, row.seq);
|
|
1689
|
-
}
|
|
1690
|
-
return latest;
|
|
1691
|
-
}
|
|
1692
|
-
compactionByStatus(sessionID, status) {
|
|
1693
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1694
|
-
WHERE session_id = ? AND type = 'compaction'
|
|
1695
|
-
AND json_extract(data, '$.status') = ?
|
|
1696
|
-
ORDER BY seq DESC LIMIT 1`).get(sessionID, status);
|
|
1697
|
-
return row ? decode(row) : undefined;
|
|
1698
|
-
}
|
|
1699
|
-
latestCompaction(sessionID) {
|
|
1700
|
-
return trackDecodeOperation("latestCompaction", () => this.compactionByStatus(sessionID, "completed"));
|
|
1701
|
-
}
|
|
1702
|
-
latestRunningCompaction(sessionID) {
|
|
1703
|
-
return trackDecodeOperation("latestRunningCompaction", () => this.compactionByStatus(sessionID, "running"));
|
|
1704
|
-
}
|
|
1705
|
-
idleRows(sessionID, after = -1) {
|
|
1706
|
-
return trackDecodeOperation("idleRows", () => this.all(sessionID, after, "idle"));
|
|
1707
|
-
}
|
|
1708
|
-
earliestSequence(sessionID) {
|
|
1709
|
-
const row = this.prepare("SELECT MIN(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
|
|
1710
|
-
return typeof row?.seq === "number" ? row.seq : undefined;
|
|
1711
|
-
}
|
|
1712
|
-
latestSequence(sessionID) {
|
|
1713
|
-
const row = this.prepare("SELECT MAX(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
|
|
1714
|
-
return typeof row?.seq === "number" ? row.seq : -1;
|
|
1715
|
-
}
|
|
1716
|
-
assistantSince(sessionID, afterSeq) {
|
|
1717
|
-
return trackDecodeOperation("assistantSince", () => {
|
|
1718
|
-
const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1719
|
-
WHERE session_id = ? AND type = 'assistant' AND seq > ?
|
|
1720
|
-
ORDER BY seq ASC`).all(sessionID, afterSeq);
|
|
1721
|
-
return rows.map((row) => decode(row));
|
|
1722
|
-
});
|
|
1723
|
-
}
|
|
1724
|
-
latestAssistant(sessionID) {
|
|
1725
|
-
return trackDecodeOperation("latestAssistant", () => {
|
|
1726
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1727
|
-
WHERE session_id = ? AND type = 'assistant'
|
|
1728
|
-
ORDER BY seq DESC LIMIT 1`).get(sessionID);
|
|
1729
|
-
return row ? decode(row) : undefined;
|
|
1730
|
-
});
|
|
1731
|
-
}
|
|
1732
|
-
latestIdle(sessionID) {
|
|
1733
|
-
return trackDecodeOperation("latestIdle", () => {
|
|
1734
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
1735
|
-
WHERE session_id = ? AND type = 'idle'
|
|
1736
|
-
ORDER BY seq DESC LIMIT 1`).get(sessionID);
|
|
1737
|
-
return row ? decode(row) : undefined;
|
|
1738
|
-
});
|
|
1739
|
-
}
|
|
1740
|
-
window(sessionID) {
|
|
1741
|
-
return trackDecodeOperation("window", () => this.db.transaction(() => {
|
|
1742
|
-
const cut = this.latestCompaction(sessionID);
|
|
1743
|
-
return this.all(sessionID, cut ? cut.seq - 1 : -1);
|
|
1744
|
-
}).deferred());
|
|
1745
|
-
}
|
|
1746
|
-
history(sessionID) {
|
|
1747
|
-
return trackDecodeOperation("history", () => this.all(sessionID, -1));
|
|
1748
|
-
}
|
|
1749
|
-
all(sessionID, after, type, through) {
|
|
1750
|
-
const rows = [];
|
|
1751
|
-
for (;; ) {
|
|
1752
|
-
const page = this.page(sessionID, { after, through, type });
|
|
1753
|
-
rows.push(...page.rows);
|
|
1754
|
-
if (page.rows.length < 100 || page.cursor === undefined)
|
|
1755
|
-
return rows;
|
|
1756
|
-
after = page.cursor;
|
|
1757
|
-
}
|
|
1758
|
-
}
|
|
1759
|
-
}
|
|
1760
|
-
|
|
1761
1076
|
// src/features/magic-context/resolve-subagent-fallback.ts
|
|
1762
1077
|
function resolveIsSubagentFromOpenCodeDb(sessionId) {
|
|
1763
1078
|
try {
|
|
@@ -1834,17 +1149,48 @@ function findSessionMeta(db, sessionId) {
|
|
|
1834
1149
|
const result = db.prepare(`SELECT ${getSessionMetaSelectColumns(db)} FROM session_meta WHERE session_id = ?`).get(sessionId);
|
|
1835
1150
|
return isSessionMetaRow(result) ? toSessionMeta(result) : undefined;
|
|
1836
1151
|
}
|
|
1152
|
+
var parentReadRetries = new WeakMap;
|
|
1153
|
+
var PARENT_READ_ATTEMPTS = 5;
|
|
1154
|
+
var PARENT_READ_COOLDOWN_MS = 30000;
|
|
1837
1155
|
function getOrCreateSessionMeta(db, sessionId) {
|
|
1838
1156
|
const existing = findSessionMeta(db, sessionId);
|
|
1839
|
-
if (existing)
|
|
1840
|
-
return existing;
|
|
1841
|
-
const defaults = getDefaultSessionMeta(sessionId);
|
|
1842
1157
|
const harness = getHarness2();
|
|
1158
|
+
if (existing) {
|
|
1159
|
+
if (harness !== "opencode2")
|
|
1160
|
+
return existing;
|
|
1161
|
+
const row = db.prepare("SELECT is_subagent FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
1162
|
+
if (row.is_subagent !== null)
|
|
1163
|
+
return existing;
|
|
1164
|
+
}
|
|
1165
|
+
const defaults = existing ?? getDefaultSessionMeta(sessionId);
|
|
1166
|
+
let retries = parentReadRetries.get(db);
|
|
1167
|
+
if (harness === "opencode2") {
|
|
1168
|
+
if (!retries) {
|
|
1169
|
+
retries = new BoundedSessionMap(1000);
|
|
1170
|
+
parentReadRetries.set(db, retries);
|
|
1171
|
+
}
|
|
1172
|
+
const retry = retries.get(sessionId);
|
|
1173
|
+
if (retry && retry.attempts >= PARENT_READ_ATTEMPTS && Date.now() - retry.at < PARENT_READ_COOLDOWN_MS)
|
|
1174
|
+
return defaults;
|
|
1175
|
+
}
|
|
1843
1176
|
const fallbackSubagent = harness === "opencode" ? resolveIsSubagentFromOpenCodeDb(sessionId) : harness === "opencode2" ? resolveIsSubagentFromOpenCode2Db(sessionId) : null;
|
|
1844
1177
|
if (fallbackSubagent === true) {
|
|
1845
1178
|
defaults.isSubagent = true;
|
|
1846
1179
|
}
|
|
1847
|
-
|
|
1180
|
+
if (harness === "opencode2") {
|
|
1181
|
+
if (fallbackSubagent === null) {
|
|
1182
|
+
const previous = retries?.get(sessionId);
|
|
1183
|
+
const attempts = previous && Date.now() - previous.at < PARENT_READ_COOLDOWN_MS ? previous.attempts + 1 : 1;
|
|
1184
|
+
retries?.set(sessionId, { attempts, at: Date.now() });
|
|
1185
|
+
ensureSessionMetaRow(db, sessionId, null);
|
|
1186
|
+
return defaults;
|
|
1187
|
+
}
|
|
1188
|
+
retries?.delete(sessionId);
|
|
1189
|
+
ensureSessionMetaRow(db, sessionId, fallbackSubagent);
|
|
1190
|
+
db.prepare("UPDATE session_meta SET is_subagent = ? WHERE session_id = ? AND is_subagent IS NULL").run(fallbackSubagent ? 1 : 0, sessionId);
|
|
1191
|
+
return defaults;
|
|
1192
|
+
}
|
|
1193
|
+
ensureSessionMetaRow(db, sessionId);
|
|
1848
1194
|
if (harness === "opencode" && fallbackSubagent === true) {
|
|
1849
1195
|
db.prepare("UPDATE session_meta SET is_subagent = 1 WHERE session_id = ?").run(sessionId);
|
|
1850
1196
|
}
|
|
@@ -1953,14 +1299,18 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false, perm
|
|
|
1953
1299
|
cancelAutoSearchWork(sessionId);
|
|
1954
1300
|
let transactionStartedAt = 0;
|
|
1955
1301
|
let clearedMarker = null;
|
|
1302
|
+
let eligibleSessions = 0;
|
|
1956
1303
|
withoutSqliteTransformPass2(() => withSqliteBackgroundWriter2(() => db.transaction(() => {
|
|
1957
1304
|
transactionStartedAt = performance.now();
|
|
1958
1305
|
clearedMarker = getPendingPiCompactionMarkerState(db, sessionId);
|
|
1959
|
-
deleteSessionScopedRows(db, [sessionId], undefined, {
|
|
1306
|
+
eligibleSessions = deleteSessionScopedRows(db, [sessionId], undefined, {
|
|
1960
1307
|
rustModuleCleanupAcknowledged,
|
|
1961
|
-
preserveTagRevisionTombstones: !permanentlyDeleted
|
|
1308
|
+
preserveTagRevisionTombstones: !permanentlyDeleted,
|
|
1309
|
+
deferRecoveryFenceCleanup: true
|
|
1962
1310
|
});
|
|
1963
1311
|
}).immediate()));
|
|
1312
|
+
if (eligibleSessions > 0)
|
|
1313
|
+
clearLkgRecoveryFence(sessionId);
|
|
1964
1314
|
if (clearedMarker)
|
|
1965
1315
|
logPiCompactionMarkerClear(sessionId, clearedMarker, "session-reset");
|
|
1966
1316
|
clearUnpublishedAutoSearchNoHints(sessionId);
|
|
@@ -2123,7 +1473,7 @@ function lkgProviderInputTotal(tokens) {
|
|
|
2123
1473
|
return counts.every((count) => Number.isSafeInteger(count) && count >= 0) ? counts.reduce((sum, count) => sum + count, 0) : Number.NaN;
|
|
2124
1474
|
}
|
|
2125
1475
|
function identity(slot) {
|
|
2126
|
-
return
|
|
1476
|
+
return createHash3("sha256").update(JSON.stringify([
|
|
2127
1477
|
slot.capturedAt,
|
|
2128
1478
|
slot.captureSequence,
|
|
2129
1479
|
slot.rowVersion,
|
|
@@ -2219,7 +1569,7 @@ function clearCapturedLkgMeasurement(sessionId) {
|
|
|
2219
1569
|
}
|
|
2220
1570
|
|
|
2221
1571
|
// src/hooks/magic-context/lkg-persist.ts
|
|
2222
|
-
import { createHash as
|
|
1572
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
2223
1573
|
function parseStringArray(value) {
|
|
2224
1574
|
if (typeof value !== "string")
|
|
2225
1575
|
return null;
|
|
@@ -2333,7 +1683,7 @@ function rememberFingerprint(db, sessionId, fingerprint) {
|
|
|
2333
1683
|
saved.set(sessionId, fingerprint);
|
|
2334
1684
|
}
|
|
2335
1685
|
function slotFingerprint(slot) {
|
|
2336
|
-
return
|
|
1686
|
+
return createHash4("sha256").update(JSON.stringify([
|
|
2337
1687
|
slot.jsonPrefix,
|
|
2338
1688
|
slot.inputIdSeq,
|
|
2339
1689
|
slot.inputContentDigests,
|
|
@@ -3436,7 +2786,7 @@ var DIGEST_CHUNK_BYTES = 64 * 1024;
|
|
|
3436
2786
|
var digestChunk;
|
|
3437
2787
|
function lkgContentDigestFromFields(fields) {
|
|
3438
2788
|
lkgDigestsComputed += 1;
|
|
3439
|
-
const hash =
|
|
2789
|
+
const hash = createHash5("sha256");
|
|
3440
2790
|
digestChunk ??= Buffer.allocUnsafe(DIGEST_CHUNK_BYTES);
|
|
3441
2791
|
const chunk = digestChunk;
|
|
3442
2792
|
let offset = 0;
|
|
@@ -3499,7 +2849,7 @@ function legacyLkgDigestFromFields(fields) {
|
|
|
3499
2849
|
const value = typeof field === "symbol" ? field.description ?? "" : String(field);
|
|
3500
2850
|
key += `${typeof field}:${value.length}:${value}\x00`;
|
|
3501
2851
|
}
|
|
3502
|
-
return
|
|
2852
|
+
return createHash5("sha256").update(key).digest("base64url");
|
|
3503
2853
|
}
|
|
3504
2854
|
function legacyLkgContentDigest(message) {
|
|
3505
2855
|
const fields = flattenContentFields(withoutEmptyUserDiffSummary(message));
|
|
@@ -5591,14 +4941,14 @@ class HiddenCompletionRefusal extends Error {
|
|
|
5591
4941
|
}
|
|
5592
4942
|
|
|
5593
4943
|
// src/features/magic-context/compaction-marker.ts
|
|
5594
|
-
import { createHash as
|
|
5595
|
-
import { existsSync, statSync as
|
|
4944
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
4945
|
+
import { existsSync, statSync as statSync3 } from "node:fs";
|
|
5596
4946
|
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
5597
4947
|
var ID_PREFIX_HEX_LENGTH = 12;
|
|
5598
4948
|
var ID_SUFFIX_LENGTH = 14;
|
|
5599
4949
|
var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
|
|
5600
4950
|
function deterministicBase62(seed, length) {
|
|
5601
|
-
let value = BigInt(`0x${
|
|
4951
|
+
let value = BigInt(`0x${createHash6("sha256").update(seed).digest("hex")}`);
|
|
5602
4952
|
const chars = Array(length);
|
|
5603
4953
|
for (let index = length - 1;index >= 0; index -= 1) {
|
|
5604
4954
|
chars[index] = BASE62_CHARS[Number(value % 62n)];
|
|
@@ -5664,7 +5014,7 @@ function runMarkerWriteTransaction(db, site, operation) {
|
|
|
5664
5014
|
function markerWalPages(db) {
|
|
5665
5015
|
try {
|
|
5666
5016
|
const row = db.prepare("PRAGMA page_size").get();
|
|
5667
|
-
const bytes =
|
|
5017
|
+
const bytes = statSync3(`${getOpenCodeDbPath()}-wal`).size;
|
|
5668
5018
|
return Math.max(0, Math.floor((bytes - 32) / (row.page_size + 24)));
|
|
5669
5019
|
} catch {
|
|
5670
5020
|
return null;
|
|
@@ -6448,7 +5798,7 @@ function parseUserMemoryRow(row) {
|
|
|
6448
5798
|
}
|
|
6449
5799
|
// src/features/magic-context/dreamer/provider-output-failure.ts
|
|
6450
5800
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6451
|
-
import { createHash as
|
|
5801
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
6452
5802
|
var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
|
|
6453
5803
|
|
|
6454
5804
|
class DreamerProviderOutputFailureError extends Error {
|
|
@@ -6545,12 +5895,12 @@ function providerOutputFailureFromInvalidManifest(messages, responseText, now =
|
|
|
6545
5895
|
const resetAt = quotaResetAt(responseText, now);
|
|
6546
5896
|
if (resetAt === undefined && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
|
|
6547
5897
|
return null;
|
|
6548
|
-
const fingerprint =
|
|
5898
|
+
const fingerprint = createHash7("sha256").update(normalized).digest("hex").slice(0, 16);
|
|
6549
5899
|
return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText, resetAt);
|
|
6550
5900
|
}
|
|
6551
5901
|
|
|
6552
5902
|
// src/v2/hooks/hidden-child.ts
|
|
6553
|
-
import { createHash as
|
|
5903
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
6554
5904
|
|
|
6555
5905
|
// src/agents/dreamer.ts
|
|
6556
5906
|
var DREAMER_AGENT = "dreamer";
|
|
@@ -6580,6 +5930,37 @@ var DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS = [
|
|
|
6580
5930
|
"ctx_search"
|
|
6581
5931
|
];
|
|
6582
5932
|
|
|
5933
|
+
// src/shared/historian-cache.ts
|
|
5934
|
+
function withoutHistorianTailCache(body) {
|
|
5935
|
+
const value = JSON.parse(body);
|
|
5936
|
+
if (!value || typeof value.model !== "string" || typeof value.max_tokens !== "number" || !Array.isArray(value.system) || value.system.length === 0 || !value.system.every((part) => part?.type === "text" && typeof part.text === "string") || !value.system.some((part) => part.cache_control) || !Array.isArray(value.messages) || value.cache_control !== undefined)
|
|
5937
|
+
return body;
|
|
5938
|
+
const root = parseTree(body);
|
|
5939
|
+
const property = (node, key) => node?.children?.find((child) => child.children?.[0]?.value === key)?.children?.[1];
|
|
5940
|
+
const removals = [];
|
|
5941
|
+
for (const message of property(root, "messages")?.children ?? []) {
|
|
5942
|
+
for (const block of property(message, "content")?.children ?? []) {
|
|
5943
|
+
if (block.type !== "object")
|
|
5944
|
+
continue;
|
|
5945
|
+
const fields = block.children ?? [];
|
|
5946
|
+
fields.forEach((field, index) => {
|
|
5947
|
+
if (field.children?.[0]?.value !== "cache_control")
|
|
5948
|
+
return;
|
|
5949
|
+
const next = fields[index + 1];
|
|
5950
|
+
const previous = fields[index - 1];
|
|
5951
|
+
removals.push(next ? [field.offset, next.offset] : [
|
|
5952
|
+
previous ? previous.offset + previous.length : field.offset,
|
|
5953
|
+
field.offset + field.length
|
|
5954
|
+
]);
|
|
5955
|
+
});
|
|
5956
|
+
}
|
|
5957
|
+
}
|
|
5958
|
+
for (const [start, end] of removals.sort((a, b) => b[0] - a[0])) {
|
|
5959
|
+
body = body.slice(0, start) + body.slice(end);
|
|
5960
|
+
}
|
|
5961
|
+
return body;
|
|
5962
|
+
}
|
|
5963
|
+
|
|
6583
5964
|
// src/v2/hooks/hidden-child.ts
|
|
6584
5965
|
var HIDDEN_HISTORIAN_AGENT = "historian";
|
|
6585
5966
|
var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
|
|
@@ -6744,7 +6125,7 @@ function markerCandidates(text) {
|
|
|
6744
6125
|
function textDigest(text) {
|
|
6745
6126
|
return {
|
|
6746
6127
|
length: text.length,
|
|
6747
|
-
sha256:
|
|
6128
|
+
sha256: createHash8("sha256").update(text).digest("hex").slice(0, 16)
|
|
6748
6129
|
};
|
|
6749
6130
|
}
|
|
6750
6131
|
function firstDifference(a, b) {
|
|
@@ -6767,6 +6148,7 @@ class HiddenChildHook {
|
|
|
6767
6148
|
childIDs = new Map;
|
|
6768
6149
|
attempts = new Map;
|
|
6769
6150
|
active = new Map;
|
|
6151
|
+
cacheWarnings = new Set;
|
|
6770
6152
|
constructor(note = log2) {
|
|
6771
6153
|
this.note = note;
|
|
6772
6154
|
}
|
|
@@ -6792,6 +6174,30 @@ class HiddenChildHook {
|
|
|
6792
6174
|
owns(sessionID) {
|
|
6793
6175
|
return this.childIDs.has(sessionID);
|
|
6794
6176
|
}
|
|
6177
|
+
async cacheRequest(draft) {
|
|
6178
|
+
const attempt = this.active.get(draft.sessionID);
|
|
6179
|
+
if (!this.owns(draft.sessionID) || !attempt || attempt.identity.kind !== "historian" || draft.kind !== "primary" || attempt.request.cacheTail !== "skip")
|
|
6180
|
+
return;
|
|
6181
|
+
if ((attempt.wireRequests ?? 0) > 0)
|
|
6182
|
+
return;
|
|
6183
|
+
attempt.wireRequests = 1;
|
|
6184
|
+
try {
|
|
6185
|
+
const original = await draft.request.clone().text();
|
|
6186
|
+
const body = withoutHistorianTailCache(original);
|
|
6187
|
+
if (body === original)
|
|
6188
|
+
return;
|
|
6189
|
+
const headers = new Headers(draft.request.headers);
|
|
6190
|
+
headers.delete("content-length");
|
|
6191
|
+
draft.request = new Request(draft.request, { body, headers });
|
|
6192
|
+
} catch (error) {
|
|
6193
|
+
if (!this.cacheWarnings.has(draft.sessionID)) {
|
|
6194
|
+
this.cacheWarnings.add(draft.sessionID);
|
|
6195
|
+
try {
|
|
6196
|
+
this.note(`Historian cache optimization skipped for ${draft.sessionID}: ${String(error)}`);
|
|
6197
|
+
} catch {}
|
|
6198
|
+
}
|
|
6199
|
+
}
|
|
6200
|
+
}
|
|
6795
6201
|
compactionSummary(sessionID, agent) {
|
|
6796
6202
|
if (!this.owns(sessionID)) {
|
|
6797
6203
|
if (isChildOfDisposedInstance(sessionID)) {
|
|
@@ -7262,14 +6668,14 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, tr
|
|
|
7262
6668
|
});
|
|
7263
6669
|
throw error;
|
|
7264
6670
|
}
|
|
7265
|
-
async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport) {
|
|
6671
|
+
async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true) {
|
|
7266
6672
|
const originalBody = { ...args.body };
|
|
7267
6673
|
const attemptArgs = copyPromptArgs(args, originalBody);
|
|
7268
6674
|
try {
|
|
7269
6675
|
await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport);
|
|
7270
6676
|
return;
|
|
7271
6677
|
} catch (error) {
|
|
7272
|
-
if (isNonRetryable(error, signal))
|
|
6678
|
+
if (isNonRetryable(error, signal) || !allowModelSuggestions)
|
|
7273
6679
|
throw error;
|
|
7274
6680
|
const suggestion = parseModelSuggestion(error);
|
|
7275
6681
|
if (!suggestion || !originalBody.model) {
|
|
@@ -7297,7 +6703,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
7297
6703
|
const explicitPrimaryLabel = baseBody.model?.providerID && baseBody.model.modelID ? `${baseBody.model.providerID}/${baseBody.model.modelID}` : "primary";
|
|
7298
6704
|
let lastError = null;
|
|
7299
6705
|
try {
|
|
7300
|
-
await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport);
|
|
6706
|
+
await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport, options.allowModelSuggestions);
|
|
7301
6707
|
return;
|
|
7302
6708
|
} catch (error) {
|
|
7303
6709
|
lastError = error;
|
|
@@ -7323,7 +6729,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
7323
6729
|
...fallback?.qualifier ? { variant: fallback.qualifier } : {}
|
|
7324
6730
|
});
|
|
7325
6731
|
try {
|
|
7326
|
-
await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport);
|
|
6732
|
+
await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport, options.allowModelSuggestions);
|
|
7327
6733
|
log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
|
|
7328
6734
|
return;
|
|
7329
6735
|
} catch (error) {
|
|
@@ -7341,7 +6747,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
7341
6747
|
}
|
|
7342
6748
|
async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options) {
|
|
7343
6749
|
try {
|
|
7344
|
-
await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport);
|
|
6750
|
+
await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions);
|
|
7345
6751
|
} catch (error) {
|
|
7346
6752
|
throw {
|
|
7347
6753
|
error,
|
|
@@ -8020,9 +7426,9 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
|
|
|
8020
7426
|
}
|
|
8021
7427
|
}
|
|
8022
7428
|
// src/shared/prompt-surface-runtime.ts
|
|
8023
|
-
import { createHash as
|
|
8024
|
-
import { existsSync as existsSync2, readFileSync as readFileSync3, statSync as
|
|
8025
|
-
import { dirname, isAbsolute, resolve
|
|
7429
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
7430
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3, statSync as statSync4 } from "node:fs";
|
|
7431
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
8026
7432
|
|
|
8027
7433
|
// src/tools/light-descriptions.ts
|
|
8028
7434
|
var CTX_REDUCE_LIGHT_DESCRIPTION = `Stamp an item as no longer needed for the work ahead. Not a delete: stamping QUEUES it, the item stays readable until Magic Context clears stamped items in one sweep, newest tags are protected, and a cleared item goes to the archive (recent: a [dropped §N§] placeholder; older: removed) recoverable via ctx_expand(tag=N). The question is "does this need to stay on my desk for what comes next?" — a file you keep editing stays, the grep that found it goes. Stamp used reads/searches/outputs, acted-on build/test output, redundant dumps, extracted pasted payloads; keep user messages, your own text, unresolved errors, raw evidence, exact wording that may matter. Look at each tag; never blanket-stamp "1-50". Grammar: "3-5", "1,2,9", "1-5,8,12-15".`;
|
|
@@ -8053,12 +7459,12 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
|
|
|
8053
7459
|
\x00magic-context-prompt-surface:${preset}`;
|
|
8054
7460
|
}
|
|
8055
7461
|
function systemPromptFingerprint(systemContent, preset = "full") {
|
|
8056
|
-
return
|
|
7462
|
+
return createHash9("md5").update(promptSurfaceHashMaterial(systemContent, preset)).digest("hex");
|
|
8057
7463
|
}
|
|
8058
7464
|
var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
|
|
8059
7465
|
function resolveUserConfigDirectory(options) {
|
|
8060
7466
|
if (options.userConfigDirectory)
|
|
8061
|
-
return
|
|
7467
|
+
return resolve(options.userConfigDirectory);
|
|
8062
7468
|
const sharedBase = cortexKitUserConfigBasePath();
|
|
8063
7469
|
const shared = detectConfigFile(sharedBase);
|
|
8064
7470
|
if (shared.format !== "none")
|
|
@@ -8085,10 +7491,10 @@ function createPromptSurfaceRuntime(options) {
|
|
|
8085
7491
|
const readGuidanceOverride = (configuredPath) => {
|
|
8086
7492
|
if (!configuredPath)
|
|
8087
7493
|
return;
|
|
8088
|
-
const path = isAbsolute(configuredPath) ? configuredPath :
|
|
7494
|
+
const path = isAbsolute(configuredPath) ? configuredPath : resolve(userConfigDirectory, configuredPath);
|
|
8089
7495
|
let content;
|
|
8090
7496
|
try {
|
|
8091
|
-
if (!
|
|
7497
|
+
if (!statSync4(path).isFile()) {
|
|
8092
7498
|
warnOnce(`guidance-not-file:${path}`, `prompt_surface.guidance_override_path (${path}) is not a file; using built-in guidance.`);
|
|
8093
7499
|
return;
|
|
8094
7500
|
}
|
|
@@ -9666,6 +9072,7 @@ function buildHistorianRepairPrompt(originalPrompt, previousOutput, validationEr
|
|
|
9666
9072
|
"Return a corrected full XML response for the same existing state and new messages.",
|
|
9667
9073
|
"Do not skip any displayed raw ordinal or displayed raw range, even if the message looks trivial.",
|
|
9668
9074
|
"Every displayed message range must belong to exactly one compartment unless it is intentionally left in one trailing suffix marked by <unprocessed_from>.",
|
|
9075
|
+
"If every message in the chunk is covered by a compartment, nothing is unprocessed: set `<unprocessed_from>` to the chunk's last message index + 1.",
|
|
9669
9076
|
"",
|
|
9670
9077
|
"Previous invalid XML:",
|
|
9671
9078
|
previousOutput
|
|
@@ -9950,7 +9357,7 @@ function compareMemorySelectionPriority(left, right) {
|
|
|
9950
9357
|
}
|
|
9951
9358
|
|
|
9952
9359
|
// src/features/magic-context/mural/render-trigger.ts
|
|
9953
|
-
import { createHash as
|
|
9360
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
9954
9361
|
|
|
9955
9362
|
// src/features/magic-context/mural/mural-selection.ts
|
|
9956
9363
|
var DEFAULT_MURAL_MEMORY_BUDGET = 8000;
|
|
@@ -10654,7 +10061,7 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
10654
10061
|
return { ...cached.result };
|
|
10655
10062
|
}
|
|
10656
10063
|
const plan = planMuralRender(entries);
|
|
10657
|
-
const textHash =
|
|
10064
|
+
const textHash = createHash10("sha256").update(plan.layout.text).digest("hex");
|
|
10658
10065
|
if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
|
|
10659
10066
|
return rememberRender(db, projectIdentity, key, existing.image, {
|
|
10660
10067
|
hasMural: true,
|
|
@@ -15881,6 +15288,7 @@ async function runHistorianPrompt(args) {
|
|
|
15881
15288
|
let handle = null;
|
|
15882
15289
|
let completion;
|
|
15883
15290
|
const executor = resolveHiddenCompletionExecutor(args.hiddenCompletionExecutor, client, db, sessionDirectory, "historian");
|
|
15291
|
+
const cacheTail = args.cacheTail ?? (executor.capabilities.harness === "opencode2" ? "skip" : undefined);
|
|
15884
15292
|
let promptSettled = false;
|
|
15885
15293
|
let hadUnsettledPrompt = false;
|
|
15886
15294
|
const startedAt = Date.now();
|
|
@@ -15962,6 +15370,7 @@ async function runHistorianPrompt(args) {
|
|
|
15962
15370
|
try {
|
|
15963
15371
|
await promptSyncWithModelSuggestionRetry(client, {
|
|
15964
15372
|
path: { id: agentSessionId },
|
|
15373
|
+
...cacheTail !== undefined ? { cacheTail: retryIndex > 0 ? "write" : cacheTail } : {},
|
|
15965
15374
|
query: { directory: sessionDirectory },
|
|
15966
15375
|
body: {
|
|
15967
15376
|
agent: agentId,
|
|
@@ -15982,6 +15391,7 @@ async function runHistorianPrompt(args) {
|
|
|
15982
15391
|
return executor.attempt(opened, request);
|
|
15983
15392
|
}, { childSessionId: opened.childSessionId }),
|
|
15984
15393
|
timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
15394
|
+
allowModelSuggestions: false,
|
|
15985
15395
|
fallbackModels: modelOverride ? undefined : fallbackModels,
|
|
15986
15396
|
callContext: agentId === HISTORIAN_EDITOR_AGENT ? "historian:editor" : "historian"
|
|
15987
15397
|
});
|
|
@@ -16066,7 +15476,7 @@ async function runFallbackHistorianPass(args) {
|
|
|
16066
15476
|
const primary = toModelEntry(args.model);
|
|
16067
15477
|
for (const candidateInput of [
|
|
16068
15478
|
...args.fallbackModels ?? [],
|
|
16069
|
-
|
|
15479
|
+
...!primary && args.fallbackModelId ? [{ model: args.fallbackModelId }] : []
|
|
16070
15480
|
]) {
|
|
16071
15481
|
const candidate = toModelEntry(candidateInput);
|
|
16072
15482
|
if (!candidate)
|
|
@@ -17648,7 +17058,7 @@ async function runCompartmentAgent(deps) {
|
|
|
17648
17058
|
const projectPath = resolveProjectIdentity(directory ?? process.cwd());
|
|
17649
17059
|
const fallbackWindows = [
|
|
17650
17060
|
...(deps.fallbackModels ?? []).map((entry) => toModelEntry(entry)?.model),
|
|
17651
|
-
deps.fallbackModelId
|
|
17061
|
+
...toModelEntry(deps.model) ? [] : [deps.fallbackModelId]
|
|
17652
17062
|
].filter((key) => typeof key === "string" && key !== producerModel).map((key) => resolveHistorianProducerWindow(key, deps.historianMaxOutputTokens));
|
|
17653
17063
|
const promptFit = fitHistorianPrompt({
|
|
17654
17064
|
window: producerWindow,
|
|
@@ -19210,4 +18620,4 @@ ${failure}`;
|
|
|
19210
18620
|
}
|
|
19211
18621
|
}
|
|
19212
18622
|
|
|
19213
|
-
export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork,
|
|
18623
|
+
export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, queueMemoryMutation, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, prepareCompactionMarkerCandidates, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, failedInvocationStatus, sumTokensFromChildMessages, recordChildInvocation, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };
|