@cortexkit/opencode-magic-context 0.49.16 → 0.49.18
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 +11 -11
- 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 +394 -394
- package/dist/{conflict-warning-hook-znry4j76.js → conflict-warning-hook-4pmz879v.js} +5 -5
- package/dist/{context-3znk23va.js → context-m897gfp9.js} +304 -145
- package/dist/{embedding-backfill-q4n8dend.js → embedding-backfill-fmz50tsy.js} +11 -11
- package/dist/embedding-worker-process.js +1 -1
- package/dist/embedding-worker.js +4 -4
- 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-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/search.d.ts +6 -1
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts +11 -0
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -0
- 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/cache-busting-signals.d.ts +22 -1
- package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -0
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts +4 -2
- package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/file-token-coverage.d.ts +11 -0
- package/dist/hooks/magic-context/file-token-coverage.d.ts.map +1 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +9 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/host-served-rows.d.ts +25 -0
- package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +7 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/pass-outcome.d.ts +2 -0
- package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts +2 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts +59 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -0
- 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-content-primitives.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-compartment-phase.d.ts +6 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts +19 -0
- package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +19 -0
- 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-9nkg2dzk.js → index-24fezq97.js} +3 -3
- package/dist/{index-v9asb16b.js → index-24jbw52d.js} +5 -5
- package/dist/{index-a8bvhwqs.js → index-2vxtcb95.js} +32 -3
- package/dist/{index-f71thw8j.js → index-4s3t0nd0.js} +1 -1
- package/dist/{index-6a6dq53h.js → index-6s5941tm.js} +5 -5
- package/dist/{index-fkx2qnvw.js → index-6x57ar45.js} +2 -2
- package/dist/{index-ek1yxvvz.js → index-936py2wm.js} +361 -70
- package/dist/{index-dqe8pq4x.js → index-a6mc0v4d.js} +6 -3
- package/dist/{index-hehkf6zm.js → index-b5vqckbw.js} +12 -6
- package/dist/{v2/server-wafzvyhg.js → index-beht37jy.js} +8 -0
- package/dist/{index-7b2cfmaz.js → index-bjcnntmz.js} +2 -2
- package/dist/{index-hqkczed7.js → index-c5pytzne.js} +22 -2
- package/dist/{index-nd7m2a5a.js → index-cf74k5ak.js} +27 -5
- package/dist/{index-kn4t1haw.js → index-e4xv8890.js} +531 -253
- package/dist/{index-cj9g0j7a.js → index-fgncb0ng.js} +7 -7
- package/dist/{index-5mwk1nek.js → index-jn12fvvh.js} +1 -1
- package/dist/{index-n6m03s3n.js → index-ke416mdc.js} +1 -1
- package/dist/{index-mtw9e71a.js → index-kq82mtg0.js} +2 -2
- package/dist/{index-n78avt2p.js → index-n37sebck.js} +1 -1
- package/dist/{index-wk0n1cgt.js → index-qn7xstt2.js} +2 -2
- package/dist/{index-v63beg1z.js → index-r4nkrs05.js} +3 -3
- package/dist/{index-j6zw70pf.js → index-rmwykbbb.js} +60 -21
- package/dist/{index-saews2s3.js → index-rr2bb45z.js} +1 -1
- package/dist/{index-ayym1x7f.js → index-s1ex9y6p.js} +195 -748
- package/dist/{index-7pa32z07.js → index-s734jcsr.js} +1 -1
- package/dist/{index-b17m64g9.js → index-s74zqahq.js} +1 -1
- package/dist/{index-4qfy7v57.js → index-s7j8tvhv.js} +31 -20
- package/dist/{index-wv9n2zcq.js → index-v8awdgvd.js} +4 -4
- package/dist/{index-p4vde22c.js → index-x4njr8df.js} +965 -77
- package/dist/{index-qrahzcqv.js → index-ze7mvk54.js} +10 -7
- package/dist/index.js +39 -39
- package/dist/{message-fts-rowid-map-yvx5a9jw.js → message-fts-rowid-map-17s0dfn4.js} +5 -3
- package/dist/{message-index-t4pz7akd.js → message-index-66jv6fh4.js} +13 -13
- package/dist/{message-index-bounded-6th8djy9.js → message-index-bounded-n1frdn85.js} +17 -17
- package/dist/{message-time-backfill-8egzkd3z.js → message-time-backfill-73mmm76q.js} +1 -1
- package/dist/migration-worker.js +8 -8
- 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-2dea0a77.js → project-embedding-registry-z74mhqkf.js} +10 -10
- package/dist/raw-ordinal-warmup-worker.js +10 -10
- package/dist/{read-session-chunk-4pwqxm5a.js → read-session-chunk-v06g3vka.js} +7 -7
- package/dist/{read-session-raw-5ar8se5v.js → read-session-raw-rsc8c7qy.js} +2 -2
- package/dist/{recomp-orchestrator-tjcaj5x7.js → recomp-orchestrator-ghpk2dtq.js} +24 -24
- package/dist/{search-archive-02jws7hw.js → search-archive-4d53y23e.js} +8 -8
- package/dist/{search-rb01n29x.js → search-nkf271d4.js} +20 -20
- package/dist/{send-session-notification-2x9edkrp.js → send-session-notification-6ve0e8p4.js} +4 -4
- 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 +2 -0
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- 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-4z1w27xa.js → storage-tags-r7k9tjcv.js} +8 -4
- package/dist/{transform-postprocess-phase-xaw5c3xp.js → transform-postprocess-phase-zpgav0h7.js} +24 -24
- package/dist/v2/auto-search-worker.js +76 -63
- package/dist/v2/chunk-embedding-write-worker.js +11 -11
- 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-acw1nhv8.js → context-f2xh7ba4.js} +1171 -448
- package/dist/v2/embedding-backfill-7c7yr69y.js +23 -0
- package/dist/v2/embedding-worker-process.js +1 -1
- package/dist/v2/embedding-worker.js +4 -4
- 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/payload.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-8vf0v7cr.js → message-fts-rowid-map-wfx67gfd.js} +5 -3
- package/dist/v2/{message-index-e6qzw477.js → message-index-48f7hw7a.js} +13 -13
- package/dist/v2/{message-index-bounded-dsrf49y7.js → message-index-bounded-w3hfm29z.js} +17 -17
- package/dist/v2/{message-time-backfill-q5pgxf0d.js → message-time-backfill-04t0km1z.js} +1 -1
- package/dist/v2/migration-worker.js +8 -8
- package/dist/v2/{project-embedding-registry-rek75aqw.js → project-embedding-registry-gnkj56xp.js} +10 -10
- package/dist/v2/raw-ordinal-warmup-worker.js +10 -10
- package/dist/v2/{read-session-chunk-7bpygfv2.js → read-session-chunk-zpgmxwte.js} +7 -7
- package/dist/v2/{read-session-raw-pw2n1qgc.js → read-session-raw-yaegtjzh.js} +2 -2
- package/dist/v2/{recomp-orchestrator-hzpgg06e.js → recomp-orchestrator-4vfxej9t.js} +24 -24
- package/dist/v2/{search-archive-fn4wy8sx.js → search-archive-vv48s2aa.js} +8 -8
- package/dist/v2/{search-sf2vg5pk.js → search-kza414f0.js} +20 -20
- package/dist/v2/{send-session-notification-hmr7q0nt.js → send-session-notification-3pxn658x.js} +4 -4
- package/dist/v2/{server-n5q841qn.js → server-1nyybqan.js} +31 -20
- package/dist/v2/{server-785mb90s.js → server-1wy7b9de.js} +6 -3
- package/dist/v2/{server-0mzjjw3s.js → server-27gq4mfz.js} +27 -5
- package/dist/v2/{server-g59aatsz.js → server-2ehj0bw7.js} +965 -77
- package/dist/v2/{server-kqpawe1a.js → server-46neh5fa.js} +12 -6
- package/dist/v2/{server-rrqpvwqd.js → server-6tmj0s7j.js} +2 -2
- package/dist/v2/{server-kr2kc9dz.js → server-8by8qfec.js} +10 -7
- package/dist/v2/{server-r9gjxcte.js → server-a2eqhkxr.js} +7 -7
- 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-6fyp0v67.js → server-bfpda1tb.js} +195 -749
- package/dist/v2/{server-05xjtq6c.js → server-d04vrx0j.js} +1 -1
- package/dist/v2/{server-zs8d0s3b.js → server-g3qma5c0.js} +1 -1
- package/dist/v2/{server-00hx04yn.js → server-gpvay0xz.js} +2 -2
- package/dist/v2/{server-gha9x4qq.js → server-h1v0pyxb.js} +2 -2
- package/dist/v2/{server-hgg55hde.js → server-hy3d3vsx.js} +1 -1
- package/dist/v2/{server-vgpab6rd.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-y5pznjt9.js → server-nj659894.js} +5 -5
- package/dist/v2/{server-zyw55ygv.js → server-qv7f0hhe.js} +5 -5
- package/dist/v2/{server-e3ftpk7v.js → server-rmygf5pn.js} +32 -3
- package/dist/v2/{server-0ppsweh6.js → server-tgnbmwah.js} +22 -2
- package/dist/v2/{server-1hcbw661.js → server-xhab8jx8.js} +60 -21
- package/dist/v2/{server-6714jebr.js → server-xj136kt8.js} +1 -1
- package/dist/v2/{server-aavz8pm6.js → server-zzkj2fch.js} +3 -3
- package/dist/v2/server.js +4 -4
- 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-hkwtbp3g.js → storage-tags-3wdb8zph.js} +8 -4
- package/dist/v2/store-reader.d.ts +8 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{wrapup-orchestrator-x4xj1782.js → wrapup-orchestrator-psqz7yh0.js} +24 -24
- package/dist/wrapup-orchestrator-s9zc5b00.js +48 -0
- package/package.json +1 -1
- package/src/config/latch-permanence-guard.test.ts +4 -0
- package/src/shared/historian-cache.test.ts +69 -0
- package/src/shared/historian-cache.ts +55 -0
- package/src/shared/model-suggestion-retry.ts +2 -0
- 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/v2/embedding-backfill-jyd6492b.js +0 -23
- package/dist/wrapup-orchestrator-vj2tbp22.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,
|
|
@@ -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,13 +53,13 @@ import {
|
|
|
52
53
|
withSqliteBackgroundWriter2,
|
|
53
54
|
withoutSqliteTransformPass2,
|
|
54
55
|
beginSqliteWriterAsync2
|
|
55
|
-
} from "./server-
|
|
56
|
+
} from "./server-beht37jy.js";
|
|
56
57
|
import {
|
|
57
58
|
isStrictGapHealingMessage2,
|
|
58
59
|
noteRawSessionSummaryRowWritten2,
|
|
59
60
|
RawOrdinalsNotReady2,
|
|
60
61
|
runSessionWarmupWorker
|
|
61
|
-
} from "./server-
|
|
62
|
+
} from "./server-xj136kt8.js";
|
|
62
63
|
import {
|
|
63
64
|
buildCanonicalChunkTextFromFts,
|
|
64
65
|
buildCompartmentSummaryFallbackText,
|
|
@@ -68,7 +69,7 @@ import {
|
|
|
68
69
|
replaceCompartmentChunkEmbeddings,
|
|
69
70
|
deleteChunkEmbedBackoffForSession,
|
|
70
71
|
chunkWindowSourceKey
|
|
71
|
-
} from "./server-
|
|
72
|
+
} from "./server-46neh5fa.js";
|
|
72
73
|
import {
|
|
73
74
|
isPidAlive
|
|
74
75
|
} from "./server-da07v4xp.js";
|
|
@@ -82,11 +83,13 @@ import {
|
|
|
82
83
|
ownsLkgDirtyFence,
|
|
83
84
|
commitLkgWithRecoveryFence,
|
|
84
85
|
clearLkgRecoveryFence,
|
|
86
|
+
gaDatabasePath,
|
|
87
|
+
V2StoreReader,
|
|
85
88
|
deleteSessionScopedRows,
|
|
86
89
|
toMessageIndexSource2,
|
|
87
90
|
clearIndexedMessagesInTransaction2,
|
|
88
91
|
indexSourcesAfterOrdinal2
|
|
89
|
-
} from "./server-
|
|
92
|
+
} from "./server-2ehj0bw7.js";
|
|
90
93
|
import {
|
|
91
94
|
detectOverflow,
|
|
92
95
|
SESSION_META_SELECT_COLUMNS,
|
|
@@ -102,12 +105,15 @@ import {
|
|
|
102
105
|
retreatPastHostUnservedRows,
|
|
103
106
|
snapTerminalCompartmentToServedRow,
|
|
104
107
|
isHostRenderedSystemMessage,
|
|
108
|
+
markCoveredInstructionRow,
|
|
109
|
+
isCoveredInstructionRow,
|
|
105
110
|
completedToolArcCrossesBoundary,
|
|
106
111
|
buildToolArcs,
|
|
107
112
|
fenceBoundaryForCompletedToolArcs,
|
|
108
113
|
fenceBoundaryForToolArcs,
|
|
109
114
|
buildTrueRawTokenIndex,
|
|
110
115
|
computeRawRangeFingerprint,
|
|
116
|
+
isFilePart,
|
|
111
117
|
DreamTokenBudgetExceeded,
|
|
112
118
|
TOKEN_BUDGET_FINALIZE_MESSAGE,
|
|
113
119
|
registerBudgetFinalizeChild,
|
|
@@ -179,7 +185,7 @@ import {
|
|
|
179
185
|
getRawSessionTagKeysThrough2,
|
|
180
186
|
getLegacyProtectedTailStartOrdinal2,
|
|
181
187
|
readSessionChunk2
|
|
182
|
-
} from "./server-
|
|
188
|
+
} from "./server-xhab8jx8.js";
|
|
183
189
|
import {
|
|
184
190
|
getTableColumnNames
|
|
185
191
|
} from "./server-pwv4ezb0.js";
|
|
@@ -189,7 +195,7 @@ import {
|
|
|
189
195
|
LATEST_SUPPORTED_VERSION,
|
|
190
196
|
getPersistedSchemaVersion,
|
|
191
197
|
openDatabase
|
|
192
|
-
} from "./server-
|
|
198
|
+
} from "./server-a2eqhkxr.js";
|
|
193
199
|
import {
|
|
194
200
|
providerMass,
|
|
195
201
|
calibrationForModelKey,
|
|
@@ -207,7 +213,7 @@ import {
|
|
|
207
213
|
foldShrunkPartTags2,
|
|
208
214
|
getTagNumberByMessageId2,
|
|
209
215
|
getActiveTagsBySession2
|
|
210
|
-
} from "./server-
|
|
216
|
+
} from "./server-27gq4mfz.js";
|
|
211
217
|
import {
|
|
212
218
|
resolveOpenCodeDbPath,
|
|
213
219
|
assertOpenCodeStoreGeneration,
|
|
@@ -218,10 +224,10 @@ import {
|
|
|
218
224
|
openCodeDbExists,
|
|
219
225
|
withReadOnlySessionDb,
|
|
220
226
|
getMessageTimesFromOpenCodeDb
|
|
221
|
-
} from "./server-
|
|
227
|
+
} from "./server-n1prf1g6.js";
|
|
222
228
|
import {
|
|
223
229
|
getMeasuredToolDefinitionTokens
|
|
224
|
-
} from "./server-
|
|
230
|
+
} from "./server-g3qma5c0.js";
|
|
225
231
|
import {
|
|
226
232
|
V2_MEMORY_CATEGORIES,
|
|
227
233
|
CATEGORY_PRIORITY,
|
|
@@ -237,11 +243,11 @@ import {
|
|
|
237
243
|
resolveStoredPathWorkspaceIdentity,
|
|
238
244
|
sourceNameForMemory,
|
|
239
245
|
computeWorkspaceEpochFingerprint
|
|
240
|
-
} from "./server-
|
|
246
|
+
} from "./server-gpvay0xz.js";
|
|
241
247
|
import {
|
|
242
248
|
shouldSkipHomeProjectMemory,
|
|
243
249
|
resolveProjectIdentity
|
|
244
|
-
} from "./server-
|
|
250
|
+
} from "./server-rmygf5pn.js";
|
|
245
251
|
import {
|
|
246
252
|
getSessionNotes,
|
|
247
253
|
getReadySmartNotes,
|
|
@@ -250,13 +256,13 @@ import {
|
|
|
250
256
|
userFacingFailureCode,
|
|
251
257
|
promoteSessionFactsDurable,
|
|
252
258
|
embedPromotedFacts
|
|
253
|
-
} from "./server-
|
|
259
|
+
} from "./server-my7k4eds.js";
|
|
254
260
|
import {
|
|
255
261
|
isMarkerCandidateBasisCurrent2,
|
|
256
262
|
invalidateMarkerCandidateBasis2,
|
|
257
263
|
readMarkerCandidateBasis2,
|
|
258
264
|
prepareMarkerCandidateBasis2
|
|
259
|
-
} from "./server-
|
|
265
|
+
} from "./server-d04vrx0j.js";
|
|
260
266
|
import {
|
|
261
267
|
computeCueContentHash,
|
|
262
268
|
getMuralCueState,
|
|
@@ -264,7 +270,7 @@ import {
|
|
|
264
270
|
getMemoriesByProject2,
|
|
265
271
|
getMemoriesByProjects2,
|
|
266
272
|
getMaxMemoryIdForProjects2
|
|
267
|
-
} from "./server-
|
|
273
|
+
} from "./server-n37sebck.js";
|
|
268
274
|
import {
|
|
269
275
|
pushNotification2
|
|
270
276
|
} from "./server-x8a7jmkh.js";
|
|
@@ -275,13 +281,10 @@ import {
|
|
|
275
281
|
} from "./server-34kwfsr4.js";
|
|
276
282
|
import {
|
|
277
283
|
sendStatusNotification2
|
|
278
|
-
} from "./server-
|
|
284
|
+
} from "./server-a9xqj88f.js";
|
|
279
285
|
import {
|
|
280
286
|
piModelRefToCanonical
|
|
281
287
|
} from "./server-avwt563y.js";
|
|
282
|
-
import {
|
|
283
|
-
sameProjectDirectory
|
|
284
|
-
} from "./server-knvkbfvh.js";
|
|
285
288
|
import {
|
|
286
289
|
getErrorMessage,
|
|
287
290
|
describeError
|
|
@@ -1002,10 +1005,10 @@ function readProjectDocsCanonical(projectDirectory) {
|
|
|
1002
1005
|
return { renderedBlock, canonicalHash };
|
|
1003
1006
|
}
|
|
1004
1007
|
// src/hooks/magic-context/lkg-slot.ts
|
|
1005
|
-
import { createHash as
|
|
1008
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
1006
1009
|
|
|
1007
1010
|
// src/hooks/magic-context/lkg-measured-request.ts
|
|
1008
|
-
import { createHash as
|
|
1011
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1009
1012
|
|
|
1010
1013
|
// src/shared/provider-response-completion.ts
|
|
1011
1014
|
function providerResponseFailed(input) {
|
|
@@ -1073,691 +1076,6 @@ function cancelAutoSearchWork(sessionId) {
|
|
|
1073
1076
|
}
|
|
1074
1077
|
}
|
|
1075
1078
|
|
|
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
1079
|
// src/features/magic-context/resolve-subagent-fallback.ts
|
|
1762
1080
|
function resolveIsSubagentFromOpenCodeDb(sessionId) {
|
|
1763
1081
|
try {
|
|
@@ -1834,17 +1152,48 @@ function findSessionMeta(db, sessionId) {
|
|
|
1834
1152
|
const result = db.prepare(`SELECT ${getSessionMetaSelectColumns(db)} FROM session_meta WHERE session_id = ?`).get(sessionId);
|
|
1835
1153
|
return isSessionMetaRow(result) ? toSessionMeta(result) : undefined;
|
|
1836
1154
|
}
|
|
1155
|
+
var parentReadRetries = new WeakMap;
|
|
1156
|
+
var PARENT_READ_ATTEMPTS = 5;
|
|
1157
|
+
var PARENT_READ_COOLDOWN_MS = 30000;
|
|
1837
1158
|
function getOrCreateSessionMeta(db, sessionId) {
|
|
1838
1159
|
const existing = findSessionMeta(db, sessionId);
|
|
1839
|
-
if (existing)
|
|
1840
|
-
return existing;
|
|
1841
|
-
const defaults = getDefaultSessionMeta(sessionId);
|
|
1842
1160
|
const harness = getHarness2();
|
|
1161
|
+
if (existing) {
|
|
1162
|
+
if (harness !== "opencode2")
|
|
1163
|
+
return existing;
|
|
1164
|
+
const row = db.prepare("SELECT is_subagent FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
1165
|
+
if (row.is_subagent !== null)
|
|
1166
|
+
return existing;
|
|
1167
|
+
}
|
|
1168
|
+
const defaults = existing ?? getDefaultSessionMeta(sessionId);
|
|
1169
|
+
let retries = parentReadRetries.get(db);
|
|
1170
|
+
if (harness === "opencode2") {
|
|
1171
|
+
if (!retries) {
|
|
1172
|
+
retries = new BoundedSessionMap(1000);
|
|
1173
|
+
parentReadRetries.set(db, retries);
|
|
1174
|
+
}
|
|
1175
|
+
const retry = retries.get(sessionId);
|
|
1176
|
+
if (retry && retry.attempts >= PARENT_READ_ATTEMPTS && Date.now() - retry.at < PARENT_READ_COOLDOWN_MS)
|
|
1177
|
+
return defaults;
|
|
1178
|
+
}
|
|
1843
1179
|
const fallbackSubagent = harness === "opencode" ? resolveIsSubagentFromOpenCodeDb(sessionId) : harness === "opencode2" ? resolveIsSubagentFromOpenCode2Db(sessionId) : null;
|
|
1844
1180
|
if (fallbackSubagent === true) {
|
|
1845
1181
|
defaults.isSubagent = true;
|
|
1846
1182
|
}
|
|
1847
|
-
|
|
1183
|
+
if (harness === "opencode2") {
|
|
1184
|
+
if (fallbackSubagent === null) {
|
|
1185
|
+
const previous = retries?.get(sessionId);
|
|
1186
|
+
const attempts = previous && Date.now() - previous.at < PARENT_READ_COOLDOWN_MS ? previous.attempts + 1 : 1;
|
|
1187
|
+
retries?.set(sessionId, { attempts, at: Date.now() });
|
|
1188
|
+
ensureSessionMetaRow(db, sessionId, null);
|
|
1189
|
+
return defaults;
|
|
1190
|
+
}
|
|
1191
|
+
retries?.delete(sessionId);
|
|
1192
|
+
ensureSessionMetaRow(db, sessionId, fallbackSubagent);
|
|
1193
|
+
db.prepare("UPDATE session_meta SET is_subagent = ? WHERE session_id = ? AND is_subagent IS NULL").run(fallbackSubagent ? 1 : 0, sessionId);
|
|
1194
|
+
return defaults;
|
|
1195
|
+
}
|
|
1196
|
+
ensureSessionMetaRow(db, sessionId);
|
|
1848
1197
|
if (harness === "opencode" && fallbackSubagent === true) {
|
|
1849
1198
|
db.prepare("UPDATE session_meta SET is_subagent = 1 WHERE session_id = ?").run(sessionId);
|
|
1850
1199
|
}
|
|
@@ -1953,14 +1302,18 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false, perm
|
|
|
1953
1302
|
cancelAutoSearchWork(sessionId);
|
|
1954
1303
|
let transactionStartedAt = 0;
|
|
1955
1304
|
let clearedMarker = null;
|
|
1305
|
+
let eligibleSessions = 0;
|
|
1956
1306
|
withoutSqliteTransformPass2(() => withSqliteBackgroundWriter2(() => db.transaction(() => {
|
|
1957
1307
|
transactionStartedAt = performance.now();
|
|
1958
1308
|
clearedMarker = getPendingPiCompactionMarkerState(db, sessionId);
|
|
1959
|
-
deleteSessionScopedRows(db, [sessionId], undefined, {
|
|
1309
|
+
eligibleSessions = deleteSessionScopedRows(db, [sessionId], undefined, {
|
|
1960
1310
|
rustModuleCleanupAcknowledged,
|
|
1961
|
-
preserveTagRevisionTombstones: !permanentlyDeleted
|
|
1311
|
+
preserveTagRevisionTombstones: !permanentlyDeleted,
|
|
1312
|
+
deferRecoveryFenceCleanup: true
|
|
1962
1313
|
});
|
|
1963
1314
|
}).immediate()));
|
|
1315
|
+
if (eligibleSessions > 0)
|
|
1316
|
+
clearLkgRecoveryFence(sessionId);
|
|
1964
1317
|
if (clearedMarker)
|
|
1965
1318
|
logPiCompactionMarkerClear(sessionId, clearedMarker, "session-reset");
|
|
1966
1319
|
clearUnpublishedAutoSearchNoHints(sessionId);
|
|
@@ -2123,7 +1476,7 @@ function lkgProviderInputTotal(tokens) {
|
|
|
2123
1476
|
return counts.every((count) => Number.isSafeInteger(count) && count >= 0) ? counts.reduce((sum, count) => sum + count, 0) : Number.NaN;
|
|
2124
1477
|
}
|
|
2125
1478
|
function identity(slot) {
|
|
2126
|
-
return
|
|
1479
|
+
return createHash3("sha256").update(JSON.stringify([
|
|
2127
1480
|
slot.capturedAt,
|
|
2128
1481
|
slot.captureSequence,
|
|
2129
1482
|
slot.rowVersion,
|
|
@@ -2219,7 +1572,7 @@ function clearCapturedLkgMeasurement(sessionId) {
|
|
|
2219
1572
|
}
|
|
2220
1573
|
|
|
2221
1574
|
// src/hooks/magic-context/lkg-persist.ts
|
|
2222
|
-
import { createHash as
|
|
1575
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
2223
1576
|
function parseStringArray(value) {
|
|
2224
1577
|
if (typeof value !== "string")
|
|
2225
1578
|
return null;
|
|
@@ -2333,7 +1686,7 @@ function rememberFingerprint(db, sessionId, fingerprint) {
|
|
|
2333
1686
|
saved.set(sessionId, fingerprint);
|
|
2334
1687
|
}
|
|
2335
1688
|
function slotFingerprint(slot) {
|
|
2336
|
-
return
|
|
1689
|
+
return createHash4("sha256").update(JSON.stringify([
|
|
2337
1690
|
slot.jsonPrefix,
|
|
2338
1691
|
slot.inputIdSeq,
|
|
2339
1692
|
slot.inputContentDigests,
|
|
@@ -2771,6 +2124,8 @@ function outputMessageIsPostAnchor(message, inputIndexById, anchorIndex) {
|
|
|
2771
2124
|
}
|
|
2772
2125
|
return false;
|
|
2773
2126
|
}
|
|
2127
|
+
if (isCoveredInstructionRow(message.info))
|
|
2128
|
+
return false;
|
|
2774
2129
|
if (!isSyntheticOutput(message))
|
|
2775
2130
|
return null;
|
|
2776
2131
|
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId"].map((key) => recordValue(message.info, key)).find((value) => typeof value === "string");
|
|
@@ -3436,7 +2791,7 @@ var DIGEST_CHUNK_BYTES = 64 * 1024;
|
|
|
3436
2791
|
var digestChunk;
|
|
3437
2792
|
function lkgContentDigestFromFields(fields) {
|
|
3438
2793
|
lkgDigestsComputed += 1;
|
|
3439
|
-
const hash =
|
|
2794
|
+
const hash = createHash5("sha256");
|
|
3440
2795
|
digestChunk ??= Buffer.allocUnsafe(DIGEST_CHUNK_BYTES);
|
|
3441
2796
|
const chunk = digestChunk;
|
|
3442
2797
|
let offset = 0;
|
|
@@ -3499,7 +2854,7 @@ function legacyLkgDigestFromFields(fields) {
|
|
|
3499
2854
|
const value = typeof field === "symbol" ? field.description ?? "" : String(field);
|
|
3500
2855
|
key += `${typeof field}:${value.length}:${value}\x00`;
|
|
3501
2856
|
}
|
|
3502
|
-
return
|
|
2857
|
+
return createHash5("sha256").update(key).digest("base64url");
|
|
3503
2858
|
}
|
|
3504
2859
|
function legacyLkgContentDigest(message) {
|
|
3505
2860
|
const fields = flattenContentFields(withoutEmptyUserDiffSummary(message));
|
|
@@ -3723,10 +3078,11 @@ function dropSlot(sessionId, _reason) {
|
|
|
3723
3078
|
if (pass !== undefined)
|
|
3724
3079
|
hydrationAttemptBySession.set(sessionId, pass);
|
|
3725
3080
|
}
|
|
3726
|
-
function noteEntry(sessionId,
|
|
3081
|
+
function noteEntry(sessionId, input) {
|
|
3727
3082
|
const slot = getSlot(sessionId);
|
|
3728
3083
|
if (!slot)
|
|
3729
3084
|
return null;
|
|
3085
|
+
const messages = input.some((message) => isCoveredInstructionRow(message.info)) ? input.filter((message) => !isCoveredInstructionRow(message.info)) : input;
|
|
3730
3086
|
const entryInputIds = messages.map((message) => {
|
|
3731
3087
|
const id = message.info?.id;
|
|
3732
3088
|
return typeof id === "string" ? id : "";
|
|
@@ -5591,14 +4947,14 @@ class HiddenCompletionRefusal extends Error {
|
|
|
5591
4947
|
}
|
|
5592
4948
|
|
|
5593
4949
|
// src/features/magic-context/compaction-marker.ts
|
|
5594
|
-
import { createHash as
|
|
5595
|
-
import { existsSync, statSync as
|
|
4950
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
4951
|
+
import { existsSync, statSync as statSync3 } from "node:fs";
|
|
5596
4952
|
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
5597
4953
|
var ID_PREFIX_HEX_LENGTH = 12;
|
|
5598
4954
|
var ID_SUFFIX_LENGTH = 14;
|
|
5599
4955
|
var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
|
|
5600
4956
|
function deterministicBase62(seed, length) {
|
|
5601
|
-
let value = BigInt(`0x${
|
|
4957
|
+
let value = BigInt(`0x${createHash6("sha256").update(seed).digest("hex")}`);
|
|
5602
4958
|
const chars = Array(length);
|
|
5603
4959
|
for (let index = length - 1;index >= 0; index -= 1) {
|
|
5604
4960
|
chars[index] = BASE62_CHARS[Number(value % 62n)];
|
|
@@ -5664,7 +5020,7 @@ function runMarkerWriteTransaction(db, site, operation) {
|
|
|
5664
5020
|
function markerWalPages(db) {
|
|
5665
5021
|
try {
|
|
5666
5022
|
const row = db.prepare("PRAGMA page_size").get();
|
|
5667
|
-
const bytes =
|
|
5023
|
+
const bytes = statSync3(`${getOpenCodeDbPath()}-wal`).size;
|
|
5668
5024
|
return Math.max(0, Math.floor((bytes - 32) / (row.page_size + 24)));
|
|
5669
5025
|
} catch {
|
|
5670
5026
|
return null;
|
|
@@ -6448,7 +5804,7 @@ function parseUserMemoryRow(row) {
|
|
|
6448
5804
|
}
|
|
6449
5805
|
// src/features/magic-context/dreamer/provider-output-failure.ts
|
|
6450
5806
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6451
|
-
import { createHash as
|
|
5807
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
6452
5808
|
var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
|
|
6453
5809
|
|
|
6454
5810
|
class DreamerProviderOutputFailureError extends Error {
|
|
@@ -6545,12 +5901,12 @@ function providerOutputFailureFromInvalidManifest(messages, responseText, now =
|
|
|
6545
5901
|
const resetAt = quotaResetAt(responseText, now);
|
|
6546
5902
|
if (resetAt === undefined && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
|
|
6547
5903
|
return null;
|
|
6548
|
-
const fingerprint =
|
|
5904
|
+
const fingerprint = createHash7("sha256").update(normalized).digest("hex").slice(0, 16);
|
|
6549
5905
|
return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText, resetAt);
|
|
6550
5906
|
}
|
|
6551
5907
|
|
|
6552
5908
|
// src/v2/hooks/hidden-child.ts
|
|
6553
|
-
import { createHash as
|
|
5909
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
6554
5910
|
|
|
6555
5911
|
// src/agents/dreamer.ts
|
|
6556
5912
|
var DREAMER_AGENT = "dreamer";
|
|
@@ -6580,6 +5936,37 @@ var DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS = [
|
|
|
6580
5936
|
"ctx_search"
|
|
6581
5937
|
];
|
|
6582
5938
|
|
|
5939
|
+
// src/shared/historian-cache.ts
|
|
5940
|
+
function withoutHistorianTailCache(body) {
|
|
5941
|
+
const value = JSON.parse(body);
|
|
5942
|
+
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)
|
|
5943
|
+
return body;
|
|
5944
|
+
const root = parseTree(body);
|
|
5945
|
+
const property = (node, key) => node?.children?.find((child) => child.children?.[0]?.value === key)?.children?.[1];
|
|
5946
|
+
const removals = [];
|
|
5947
|
+
for (const message of property(root, "messages")?.children ?? []) {
|
|
5948
|
+
for (const block of property(message, "content")?.children ?? []) {
|
|
5949
|
+
if (block.type !== "object")
|
|
5950
|
+
continue;
|
|
5951
|
+
const fields = block.children ?? [];
|
|
5952
|
+
fields.forEach((field, index) => {
|
|
5953
|
+
if (field.children?.[0]?.value !== "cache_control")
|
|
5954
|
+
return;
|
|
5955
|
+
const next = fields[index + 1];
|
|
5956
|
+
const previous = fields[index - 1];
|
|
5957
|
+
removals.push(next ? [field.offset, next.offset] : [
|
|
5958
|
+
previous ? previous.offset + previous.length : field.offset,
|
|
5959
|
+
field.offset + field.length
|
|
5960
|
+
]);
|
|
5961
|
+
});
|
|
5962
|
+
}
|
|
5963
|
+
}
|
|
5964
|
+
for (const [start, end] of removals.sort((a, b) => b[0] - a[0])) {
|
|
5965
|
+
body = body.slice(0, start) + body.slice(end);
|
|
5966
|
+
}
|
|
5967
|
+
return body;
|
|
5968
|
+
}
|
|
5969
|
+
|
|
6583
5970
|
// src/v2/hooks/hidden-child.ts
|
|
6584
5971
|
var HIDDEN_HISTORIAN_AGENT = "historian";
|
|
6585
5972
|
var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
|
|
@@ -6744,7 +6131,7 @@ function markerCandidates(text) {
|
|
|
6744
6131
|
function textDigest(text) {
|
|
6745
6132
|
return {
|
|
6746
6133
|
length: text.length,
|
|
6747
|
-
sha256:
|
|
6134
|
+
sha256: createHash8("sha256").update(text).digest("hex").slice(0, 16)
|
|
6748
6135
|
};
|
|
6749
6136
|
}
|
|
6750
6137
|
function firstDifference(a, b) {
|
|
@@ -6767,6 +6154,7 @@ class HiddenChildHook {
|
|
|
6767
6154
|
childIDs = new Map;
|
|
6768
6155
|
attempts = new Map;
|
|
6769
6156
|
active = new Map;
|
|
6157
|
+
cacheWarnings = new Set;
|
|
6770
6158
|
constructor(note = log2) {
|
|
6771
6159
|
this.note = note;
|
|
6772
6160
|
}
|
|
@@ -6792,6 +6180,30 @@ class HiddenChildHook {
|
|
|
6792
6180
|
owns(sessionID) {
|
|
6793
6181
|
return this.childIDs.has(sessionID);
|
|
6794
6182
|
}
|
|
6183
|
+
async cacheRequest(draft) {
|
|
6184
|
+
const attempt = this.active.get(draft.sessionID);
|
|
6185
|
+
if (!this.owns(draft.sessionID) || !attempt || attempt.identity.kind !== "historian" || draft.kind !== "primary" || attempt.request.cacheTail !== "skip")
|
|
6186
|
+
return;
|
|
6187
|
+
if ((attempt.wireRequests ?? 0) > 0)
|
|
6188
|
+
return;
|
|
6189
|
+
attempt.wireRequests = 1;
|
|
6190
|
+
try {
|
|
6191
|
+
const original = await draft.request.clone().text();
|
|
6192
|
+
const body = withoutHistorianTailCache(original);
|
|
6193
|
+
if (body === original)
|
|
6194
|
+
return;
|
|
6195
|
+
const headers = new Headers(draft.request.headers);
|
|
6196
|
+
headers.delete("content-length");
|
|
6197
|
+
draft.request = new Request(draft.request, { body, headers });
|
|
6198
|
+
} catch (error) {
|
|
6199
|
+
if (!this.cacheWarnings.has(draft.sessionID)) {
|
|
6200
|
+
this.cacheWarnings.add(draft.sessionID);
|
|
6201
|
+
try {
|
|
6202
|
+
this.note(`Historian cache optimization skipped for ${draft.sessionID}: ${String(error)}`);
|
|
6203
|
+
} catch {}
|
|
6204
|
+
}
|
|
6205
|
+
}
|
|
6206
|
+
}
|
|
6795
6207
|
compactionSummary(sessionID, agent) {
|
|
6796
6208
|
if (!this.owns(sessionID)) {
|
|
6797
6209
|
if (isChildOfDisposedInstance(sessionID)) {
|
|
@@ -8020,9 +7432,9 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
|
|
|
8020
7432
|
}
|
|
8021
7433
|
}
|
|
8022
7434
|
// 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
|
|
7435
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
7436
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3, statSync as statSync4 } from "node:fs";
|
|
7437
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
8026
7438
|
|
|
8027
7439
|
// src/tools/light-descriptions.ts
|
|
8028
7440
|
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 +7465,12 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
|
|
|
8053
7465
|
\x00magic-context-prompt-surface:${preset}`;
|
|
8054
7466
|
}
|
|
8055
7467
|
function systemPromptFingerprint(systemContent, preset = "full") {
|
|
8056
|
-
return
|
|
7468
|
+
return createHash9("md5").update(promptSurfaceHashMaterial(systemContent, preset)).digest("hex");
|
|
8057
7469
|
}
|
|
8058
7470
|
var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
|
|
8059
7471
|
function resolveUserConfigDirectory(options) {
|
|
8060
7472
|
if (options.userConfigDirectory)
|
|
8061
|
-
return
|
|
7473
|
+
return resolve(options.userConfigDirectory);
|
|
8062
7474
|
const sharedBase = cortexKitUserConfigBasePath();
|
|
8063
7475
|
const shared = detectConfigFile(sharedBase);
|
|
8064
7476
|
if (shared.format !== "none")
|
|
@@ -8085,10 +7497,10 @@ function createPromptSurfaceRuntime(options) {
|
|
|
8085
7497
|
const readGuidanceOverride = (configuredPath) => {
|
|
8086
7498
|
if (!configuredPath)
|
|
8087
7499
|
return;
|
|
8088
|
-
const path = isAbsolute(configuredPath) ? configuredPath :
|
|
7500
|
+
const path = isAbsolute(configuredPath) ? configuredPath : resolve(userConfigDirectory, configuredPath);
|
|
8089
7501
|
let content;
|
|
8090
7502
|
try {
|
|
8091
|
-
if (!
|
|
7503
|
+
if (!statSync4(path).isFile()) {
|
|
8092
7504
|
warnOnce(`guidance-not-file:${path}`, `prompt_surface.guidance_override_path (${path}) is not a file; using built-in guidance.`);
|
|
8093
7505
|
return;
|
|
8094
7506
|
}
|
|
@@ -9951,7 +9363,7 @@ function compareMemorySelectionPriority(left, right) {
|
|
|
9951
9363
|
}
|
|
9952
9364
|
|
|
9953
9365
|
// src/features/magic-context/mural/render-trigger.ts
|
|
9954
|
-
import { createHash as
|
|
9366
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
9955
9367
|
|
|
9956
9368
|
// src/features/magic-context/mural/mural-selection.ts
|
|
9957
9369
|
var DEFAULT_MURAL_MEMORY_BUDGET = 8000;
|
|
@@ -10655,7 +10067,7 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
10655
10067
|
return { ...cached.result };
|
|
10656
10068
|
}
|
|
10657
10069
|
const plan = planMuralRender(entries);
|
|
10658
|
-
const textHash =
|
|
10070
|
+
const textHash = createHash10("sha256").update(plan.layout.text).digest("hex");
|
|
10659
10071
|
if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
|
|
10660
10072
|
return rememberRender(db, projectIdentity, key, existing.image, {
|
|
10661
10073
|
hasMural: true,
|
|
@@ -11324,7 +10736,16 @@ function selectHiddenMessagesAtCompactionSeam(messagesBeforeTrim, skippedVisible
|
|
|
11324
10736
|
}
|
|
11325
10737
|
return markerBoundaryIndex < 0 ? [] : trimmed.slice(markerBoundaryIndex + 1);
|
|
11326
10738
|
}
|
|
11327
|
-
function
|
|
10739
|
+
function cutCoveredPrefix(messages, count, coveredInstructions) {
|
|
10740
|
+
const removed = messages.splice(0, count);
|
|
10741
|
+
for (const message of removed) {
|
|
10742
|
+
if (!isHostRenderedSystemMessage(message))
|
|
10743
|
+
continue;
|
|
10744
|
+
markCoveredInstructionRow(message.info);
|
|
10745
|
+
coveredInstructions.push(message);
|
|
10746
|
+
}
|
|
10747
|
+
}
|
|
10748
|
+
function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness) {
|
|
11328
10749
|
const cached = injectionCache.get(sessionId);
|
|
11329
10750
|
if (cached && cached.db !== db) {
|
|
11330
10751
|
clearInjectionCache(sessionId);
|
|
@@ -11341,8 +10762,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
11341
10762
|
if (prepared.compartmentEndMessageId.length > 0) {
|
|
11342
10763
|
const cutoffIndex = findBoundaryIndex(sessionId, messages, prepared.compartmentEndMessageId);
|
|
11343
10764
|
if (cutoffIndex >= 0) {
|
|
11344
|
-
|
|
11345
|
-
messages.splice(0, messages.length, ...remaining);
|
|
10765
|
+
cutCoveredPrefix(messages, cutoffIndex + (isPartialCompartmentEnd(db, sessionId, prepared.compartmentEndMessageId) ? 0 : 1), coveredInstructions);
|
|
11346
10766
|
} else {
|
|
11347
10767
|
sessionLog2(sessionId, `compartment injection: cached boundary ${prepared.compartmentEndMessageId} not in messages (already trimmed), reusing cache`);
|
|
11348
10768
|
}
|
|
@@ -11464,8 +10884,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
11464
10884
|
if (cutoffIndex >= 0) {
|
|
11465
10885
|
clearDegradedRebuild(sessionId);
|
|
11466
10886
|
skippedVisibleMessages = cutoffIndex + (isPartialCompartmentEnd(db, sessionId, trimEndMessageId) ? 0 : 1);
|
|
11467
|
-
|
|
11468
|
-
messages.splice(0, messages.length, ...remaining);
|
|
10887
|
+
cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
|
|
11469
10888
|
resultEndMessageId = trimEndMessageId;
|
|
11470
10889
|
} else {
|
|
11471
10890
|
const degradedCount = noteDegradedRebuild(sessionId);
|
|
@@ -11485,8 +10904,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
11485
10904
|
const reAnchorCutoff = findBoundaryIndex(sessionId, messages, reAnchorCompartment.endMessageId);
|
|
11486
10905
|
if (reAnchorCutoff >= 0) {
|
|
11487
10906
|
skippedVisibleMessages = reAnchorCutoff + (isPartialCompartmentEnd(db, sessionId, reAnchorCompartment.endMessageId) ? 0 : 1);
|
|
11488
|
-
|
|
11489
|
-
messages.splice(0, messages.length, ...remaining);
|
|
10907
|
+
cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
|
|
11490
10908
|
resultEndMessage = reAnchorCompartment.endMessage;
|
|
11491
10909
|
resultEndMessageId = reAnchorCompartment.endMessageId;
|
|
11492
10910
|
reAnchored = true;
|
|
@@ -15882,6 +15300,7 @@ async function runHistorianPrompt(args) {
|
|
|
15882
15300
|
let handle = null;
|
|
15883
15301
|
let completion;
|
|
15884
15302
|
const executor = resolveHiddenCompletionExecutor(args.hiddenCompletionExecutor, client, db, sessionDirectory, "historian");
|
|
15303
|
+
const cacheTail = args.cacheTail ?? (executor.capabilities.harness === "opencode2" ? "skip" : undefined);
|
|
15885
15304
|
let promptSettled = false;
|
|
15886
15305
|
let hadUnsettledPrompt = false;
|
|
15887
15306
|
const startedAt = Date.now();
|
|
@@ -15963,6 +15382,7 @@ async function runHistorianPrompt(args) {
|
|
|
15963
15382
|
try {
|
|
15964
15383
|
await promptSyncWithModelSuggestionRetry(client, {
|
|
15965
15384
|
path: { id: agentSessionId },
|
|
15385
|
+
...cacheTail !== undefined ? { cacheTail: retryIndex > 0 ? "write" : cacheTail } : {},
|
|
15966
15386
|
query: { directory: sessionDirectory },
|
|
15967
15387
|
body: {
|
|
15968
15388
|
agent: agentId,
|
|
@@ -16536,6 +15956,31 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
16536
15956
|
return saved;
|
|
16537
15957
|
}
|
|
16538
15958
|
|
|
15959
|
+
// src/hooks/magic-context/file-token-coverage.ts
|
|
15960
|
+
function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
|
|
15961
|
+
const filesByMessage = new Map;
|
|
15962
|
+
for (const message of messages) {
|
|
15963
|
+
const count = message.parts.filter(isFilePart).length;
|
|
15964
|
+
if (count > 0 && totals.has(message.id))
|
|
15965
|
+
filesByMessage.set(message.id, count);
|
|
15966
|
+
}
|
|
15967
|
+
if (filesByMessage.size === 0)
|
|
15968
|
+
return totals;
|
|
15969
|
+
const rows = db.prepare(`
|
|
15970
|
+
SELECT o.value AS owner, COUNT(t.id) AS count
|
|
15971
|
+
FROM json_each(?) o LEFT JOIN tags t
|
|
15972
|
+
ON t.session_id = ? AND t.type = 'file'
|
|
15973
|
+
AND t.message_id >= o.value || ':file'
|
|
15974
|
+
AND t.message_id < o.value || ':file;'
|
|
15975
|
+
GROUP BY o.value
|
|
15976
|
+
`).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
|
|
15977
|
+
for (const row of rows) {
|
|
15978
|
+
if (row.count < (filesByMessage.get(row.owner) ?? 0))
|
|
15979
|
+
totals.delete(row.owner);
|
|
15980
|
+
}
|
|
15981
|
+
return totals;
|
|
15982
|
+
}
|
|
15983
|
+
|
|
16539
15984
|
// src/hooks/magic-context/protected-tail-boundary.ts
|
|
16540
15985
|
function describeBoundaryDiagnostics(snapshot) {
|
|
16541
15986
|
return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
|
|
@@ -16761,7 +16206,7 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
16761
16206
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
16762
16207
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
16763
16208
|
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
16764
|
-
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
|
|
16209
|
+
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
|
|
16765
16210
|
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
16766
16211
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
16767
16212
|
cacheNamespace: ctx.cacheNamespace,
|
|
@@ -17004,9 +16449,10 @@ function resolveBoundaryContext(args) {
|
|
|
17004
16449
|
migrationFloorActive = seedResult.seeded;
|
|
17005
16450
|
}
|
|
17006
16451
|
const calibration = sessionDecisionCalibration(args.db, args.sessionId);
|
|
17007
|
-
const storedTokenTotalsForMessages = (messageIds) => {
|
|
16452
|
+
const storedTokenTotalsForMessages = (messageIds, messages = []) => {
|
|
17008
16453
|
try {
|
|
17009
|
-
|
|
16454
|
+
const totals = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds).totals;
|
|
16455
|
+
return omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, totals);
|
|
17010
16456
|
} catch (error) {
|
|
17011
16457
|
sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
|
|
17012
16458
|
return;
|
|
@@ -17041,7 +16487,7 @@ function resolveWrapupProtectedTailBoundary(args) {
|
|
|
17041
16487
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
17042
16488
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
17043
16489
|
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
17044
|
-
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
|
|
16490
|
+
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
|
|
17045
16491
|
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
17046
16492
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
17047
16493
|
cacheNamespace: ctx.cacheNamespace,
|
|
@@ -19212,4 +18658,4 @@ ${failure}`;
|
|
|
19212
18658
|
}
|
|
19213
18659
|
}
|
|
19214
18660
|
|
|
19215
|
-
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,
|
|
18661
|
+
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, omitIncompleteFileTokenTotals, 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 };
|