@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
|
@@ -8,12 +8,15 @@ import {
|
|
|
8
8
|
retreatPastHostUnservedRows,
|
|
9
9
|
snapTerminalCompartmentToServedRow,
|
|
10
10
|
isHostRenderedSystemMessage,
|
|
11
|
+
markCoveredInstructionRow,
|
|
12
|
+
isCoveredInstructionRow,
|
|
11
13
|
completedToolArcCrossesBoundary,
|
|
12
14
|
buildToolArcs,
|
|
13
15
|
fenceBoundaryForCompletedToolArcs,
|
|
14
16
|
fenceBoundaryForToolArcs,
|
|
15
17
|
buildTrueRawTokenIndex,
|
|
16
18
|
computeRawRangeFingerprint,
|
|
19
|
+
isFilePart,
|
|
17
20
|
DreamTokenBudgetExceeded,
|
|
18
21
|
TOKEN_BUDGET_FINALIZE_MESSAGE,
|
|
19
22
|
registerBudgetFinalizeChild,
|
|
@@ -92,7 +95,7 @@ import {
|
|
|
92
95
|
getRawSessionTagKeysThrough2,
|
|
93
96
|
getLegacyProtectedTailStartOrdinal2,
|
|
94
97
|
readSessionChunk2
|
|
95
|
-
} from "./index-
|
|
98
|
+
} from "./index-rmwykbbb.js";
|
|
96
99
|
import {
|
|
97
100
|
getHarness2,
|
|
98
101
|
harnessOwnsOpenCodeStore2
|
|
@@ -152,14 +155,14 @@ import {
|
|
|
152
155
|
hasMeaningfulUserText2,
|
|
153
156
|
estimateTokens,
|
|
154
157
|
estimateFixedPromptTokens
|
|
155
|
-
} from "./index-
|
|
158
|
+
} from "./index-c5pytzne.js";
|
|
156
159
|
import {
|
|
157
160
|
FAIL_CLOSED_DOCTOR_COMMAND,
|
|
158
161
|
getSchemaFenceRejection,
|
|
159
162
|
LATEST_SUPPORTED_VERSION,
|
|
160
163
|
getPersistedSchemaVersion,
|
|
161
164
|
openDatabase
|
|
162
|
-
} from "./index-
|
|
165
|
+
} from "./index-fgncb0ng.js";
|
|
163
166
|
import {
|
|
164
167
|
inRootAsyncContext2,
|
|
165
168
|
Database2,
|
|
@@ -167,11 +170,11 @@ import {
|
|
|
167
170
|
withSqliteBackgroundWriter2,
|
|
168
171
|
withoutSqliteTransformPass2,
|
|
169
172
|
beginSqliteWriterAsync2
|
|
170
|
-
} from "./index-
|
|
173
|
+
} from "./index-beht37jy.js";
|
|
171
174
|
import {
|
|
172
175
|
shouldSkipHomeProjectMemory,
|
|
173
176
|
resolveProjectIdentity
|
|
174
|
-
} from "./index-
|
|
177
|
+
} from "./index-2vxtcb95.js";
|
|
175
178
|
import {
|
|
176
179
|
isPidAlive
|
|
177
180
|
} from "./index-nj7yykkx.js";
|
|
@@ -180,7 +183,7 @@ import {
|
|
|
180
183
|
noteRawSessionSummaryRowWritten2,
|
|
181
184
|
RawOrdinalsNotReady2,
|
|
182
185
|
runSessionWarmupWorker
|
|
183
|
-
} from "./index-
|
|
186
|
+
} from "./index-s734jcsr.js";
|
|
184
187
|
import {
|
|
185
188
|
layoutLkgPrefix,
|
|
186
189
|
assembleLkgPrefix,
|
|
@@ -191,7 +194,7 @@ import {
|
|
|
191
194
|
resolveStoredPathWorkspaceIdentity,
|
|
192
195
|
sourceNameForMemory,
|
|
193
196
|
computeWorkspaceEpochFingerprint
|
|
194
|
-
} from "./index-
|
|
197
|
+
} from "./index-qn7xstt2.js";
|
|
195
198
|
import {
|
|
196
199
|
getTableColumnNames
|
|
197
200
|
} from "./index-bp5083x2.js";
|
|
@@ -208,7 +211,7 @@ import {
|
|
|
208
211
|
} from "./index-58e3y90n.js";
|
|
209
212
|
import {
|
|
210
213
|
getMeasuredToolDefinitionTokens
|
|
211
|
-
} from "./index-
|
|
214
|
+
} from "./index-ke416mdc.js";
|
|
212
215
|
import {
|
|
213
216
|
invalidateAutoEmbedSession,
|
|
214
217
|
drainBackgroundBatches,
|
|
@@ -217,7 +220,7 @@ import {
|
|
|
217
220
|
getProjectChunkEmbeddingModelId2,
|
|
218
221
|
getProjectEmbeddingMaxInputTokens2,
|
|
219
222
|
embedItemsForProject2
|
|
220
|
-
} from "./index-
|
|
223
|
+
} from "./index-ze7mvk54.js";
|
|
221
224
|
import {
|
|
222
225
|
buildCanonicalChunkTextFromFts,
|
|
223
226
|
buildCompartmentSummaryFallbackText,
|
|
@@ -227,7 +230,7 @@ import {
|
|
|
227
230
|
replaceCompartmentChunkEmbeddings,
|
|
228
231
|
deleteChunkEmbedBackoffForSession,
|
|
229
232
|
chunkWindowSourceKey
|
|
230
|
-
} from "./index-
|
|
233
|
+
} from "./index-b5vqckbw.js";
|
|
231
234
|
import {
|
|
232
235
|
BoundedSessionMap,
|
|
233
236
|
clearCompressionDepth,
|
|
@@ -238,11 +241,13 @@ import {
|
|
|
238
241
|
ownsLkgDirtyFence,
|
|
239
242
|
commitLkgWithRecoveryFence,
|
|
240
243
|
clearLkgRecoveryFence,
|
|
244
|
+
gaDatabasePath,
|
|
245
|
+
V2StoreReader,
|
|
241
246
|
deleteSessionScopedRows,
|
|
242
247
|
toMessageIndexSource2,
|
|
243
248
|
clearIndexedMessagesInTransaction2,
|
|
244
249
|
indexSourcesAfterOrdinal2
|
|
245
|
-
} from "./index-
|
|
250
|
+
} from "./index-x4njr8df.js";
|
|
246
251
|
import {
|
|
247
252
|
stripWellFormedLeadingTagPrefix,
|
|
248
253
|
stripTagPrefix,
|
|
@@ -255,12 +260,12 @@ import {
|
|
|
255
260
|
foldShrunkPartTags2,
|
|
256
261
|
getTagNumberByMessageId2,
|
|
257
262
|
getActiveTagsBySession2
|
|
258
|
-
} from "./index-
|
|
263
|
+
} from "./index-cf74k5ak.js";
|
|
259
264
|
import {
|
|
260
265
|
openCodeDbExists,
|
|
261
266
|
withReadOnlySessionDb,
|
|
262
267
|
getMessageTimesFromOpenCodeDb
|
|
263
|
-
} from "./index-
|
|
268
|
+
} from "./index-kq82mtg0.js";
|
|
264
269
|
import {
|
|
265
270
|
renderUserFacingFailure,
|
|
266
271
|
userFacingFailureCode,
|
|
@@ -269,7 +274,7 @@ import {
|
|
|
269
274
|
insertPrimerCandidates,
|
|
270
275
|
promoteSessionFactsDurable,
|
|
271
276
|
embedPromotedFacts
|
|
272
|
-
} from "./index-
|
|
277
|
+
} from "./index-v8awdgvd.js";
|
|
273
278
|
import {
|
|
274
279
|
pushNotification2
|
|
275
280
|
} from "./index-x8a7jmkh.js";
|
|
@@ -280,16 +285,16 @@ import {
|
|
|
280
285
|
getMemoriesByProject2,
|
|
281
286
|
getMemoriesByProjects2,
|
|
282
287
|
getMaxMemoryIdForProjects2
|
|
283
|
-
} from "./index-
|
|
288
|
+
} from "./index-n37sebck.js";
|
|
284
289
|
import {
|
|
285
290
|
isMarkerCandidateBasisCurrent2,
|
|
286
291
|
invalidateMarkerCandidateBasis2,
|
|
287
292
|
readMarkerCandidateBasis2,
|
|
288
293
|
prepareMarkerCandidateBasis2
|
|
289
|
-
} from "./index-
|
|
294
|
+
} from "./index-4s3t0nd0.js";
|
|
290
295
|
import {
|
|
291
296
|
sendStatusNotification2
|
|
292
|
-
} from "./index-
|
|
297
|
+
} from "./index-s74zqahq.js";
|
|
293
298
|
import {
|
|
294
299
|
isCompactionEnabled,
|
|
295
300
|
migrateLegacyAgentEnabledInMemory
|
|
@@ -297,9 +302,6 @@ import {
|
|
|
297
302
|
import {
|
|
298
303
|
piModelRefToCanonical
|
|
299
304
|
} from "./index-avwt563y.js";
|
|
300
|
-
import {
|
|
301
|
-
sameProjectDirectory
|
|
302
|
-
} from "./index-knvkbfvh.js";
|
|
303
305
|
import {
|
|
304
306
|
getErrorMessage,
|
|
305
307
|
describeError
|
|
@@ -4912,10 +4914,10 @@ function readProjectDocsCanonical(projectDirectory) {
|
|
|
4912
4914
|
return { renderedBlock, canonicalHash };
|
|
4913
4915
|
}
|
|
4914
4916
|
// src/hooks/magic-context/lkg-slot.ts
|
|
4915
|
-
import { createHash as
|
|
4917
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
4916
4918
|
|
|
4917
4919
|
// src/hooks/magic-context/lkg-measured-request.ts
|
|
4918
|
-
import { createHash as
|
|
4920
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4919
4921
|
|
|
4920
4922
|
// src/shared/provider-response-completion.ts
|
|
4921
4923
|
function providerResponseFailed(input) {
|
|
@@ -4983,691 +4985,6 @@ function cancelAutoSearchWork(sessionId) {
|
|
|
4983
4985
|
}
|
|
4984
4986
|
}
|
|
4985
4987
|
|
|
4986
|
-
// src/v2/store-reader.ts
|
|
4987
|
-
import { createHash as createHash3 } from "node:crypto";
|
|
4988
|
-
import { statSync as statSync5 } from "node:fs";
|
|
4989
|
-
import { hostname } from "node:os";
|
|
4990
|
-
import { resolve as resolve2 } from "node:path";
|
|
4991
|
-
function gaDatabasePath(dataHome, channel = "latest", env = process.env) {
|
|
4992
|
-
return resolveOpenCodeDbPath("v2", { dataHome, channel, env }).path;
|
|
4993
|
-
}
|
|
4994
|
-
var RAW_MESSAGE_TYPES = [
|
|
4995
|
-
"user",
|
|
4996
|
-
"synthetic",
|
|
4997
|
-
"assistant",
|
|
4998
|
-
"skill",
|
|
4999
|
-
"shell",
|
|
5000
|
-
"system"
|
|
5001
|
-
];
|
|
5002
|
-
var RAW_MESSAGE_TYPE_PARAMETERS = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5003
|
-
var V2_MESSAGE_PAGE_SQL = `WITH bounds AS (
|
|
5004
|
-
SELECT
|
|
5005
|
-
CASE WHEN ? = 0 THEN -1 ELSE COALESCE((
|
|
5006
|
-
SELECT seq FROM session_message
|
|
5007
|
-
WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
|
|
5008
|
-
ORDER BY seq ASC LIMIT 1 OFFSET ?
|
|
5009
|
-
), (SELECT MAX(seq) FROM session_message WHERE session_id = ?), -1) END AS after_seq,
|
|
5010
|
-
COALESCE((
|
|
5011
|
-
SELECT seq FROM session_message
|
|
5012
|
-
WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
|
|
5013
|
-
ORDER BY seq ASC LIMIT 1 OFFSET ?
|
|
5014
|
-
), ?) AS watermark_seq
|
|
5015
|
-
)
|
|
5016
|
-
SELECT id, session_id, type, seq, time_created, data FROM session_message, bounds
|
|
5017
|
-
WHERE session_id = ?
|
|
5018
|
-
AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
|
|
5019
|
-
AND seq > bounds.after_seq
|
|
5020
|
-
AND seq <= bounds.watermark_seq
|
|
5021
|
-
ORDER BY seq ASC LIMIT ?`;
|
|
5022
|
-
var V2_STORE_READER_DEBUG_COUNTER_KEY = "magic-context.v2.store-reader-debug";
|
|
5023
|
-
var debugSymbol = Symbol.for(V2_STORE_READER_DEBUG_COUNTER_KEY);
|
|
5024
|
-
var debugGlobal = globalThis;
|
|
5025
|
-
var QUERY_STATEMENTS = {
|
|
5026
|
-
messagePage: V2_MESSAGE_PAGE_SQL,
|
|
5027
|
-
messageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND type IN (?)",
|
|
5028
|
-
storedMessageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?",
|
|
5029
|
-
messageById: "SELECT id, session_id, type, seq, time_created, data FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1",
|
|
5030
|
-
messageExistsById: "SELECT 1 FROM session_message WHERE id = ? AND session_id = ? AND type IN (?) LIMIT 1",
|
|
5031
|
-
messageOrdinalById: `WITH target AS (
|
|
5032
|
-
SELECT seq FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1
|
|
5033
|
-
)
|
|
5034
|
-
SELECT (SELECT COUNT(*) FROM session_message WHERE session_id = ? AND type IN (?) AND seq <= target.seq) AS ordinal FROM target`,
|
|
5035
|
-
messageIdOrdinals: "SELECT id FROM session_message WHERE session_id = ? AND type IN (?) ORDER BY seq ASC LIMIT ? OFFSET ?",
|
|
5036
|
-
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 ?",
|
|
5037
|
-
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 ?"
|
|
5038
|
-
};
|
|
5039
|
-
function debugCounters() {
|
|
5040
|
-
const counters = debugGlobal[debugSymbol] ??= {
|
|
5041
|
-
decodedRows: 0,
|
|
5042
|
-
operations: {},
|
|
5043
|
-
openReaders: 0,
|
|
5044
|
-
maxOpenReaders: 0,
|
|
5045
|
-
readersOpened: 0,
|
|
5046
|
-
readersClosed: 0
|
|
5047
|
-
};
|
|
5048
|
-
counters.openReaders ??= 0;
|
|
5049
|
-
counters.maxOpenReaders ??= 0;
|
|
5050
|
-
counters.readersOpened ??= 0;
|
|
5051
|
-
counters.readersClosed ??= 0;
|
|
5052
|
-
return counters;
|
|
5053
|
-
}
|
|
5054
|
-
function returnedRowCount(value) {
|
|
5055
|
-
if (Array.isArray(value))
|
|
5056
|
-
return value.length;
|
|
5057
|
-
if (value === null || value === undefined || value === false)
|
|
5058
|
-
return 0;
|
|
5059
|
-
return 1;
|
|
5060
|
-
}
|
|
5061
|
-
function trackDecodeOperation(name, operation) {
|
|
5062
|
-
const counters = debugCounters();
|
|
5063
|
-
const before = counters.decodedRows;
|
|
5064
|
-
const started = performance.now();
|
|
5065
|
-
let value;
|
|
5066
|
-
try {
|
|
5067
|
-
value = operation();
|
|
5068
|
-
return value;
|
|
5069
|
-
} finally {
|
|
5070
|
-
const decodedRows = counters.decodedRows - before;
|
|
5071
|
-
const current = counters.operations[name] ?? {
|
|
5072
|
-
calls: 0,
|
|
5073
|
-
decodedRows: 0,
|
|
5074
|
-
maxDecodedRows: 0
|
|
5075
|
-
};
|
|
5076
|
-
current.calls += 1;
|
|
5077
|
-
current.decodedRows += decodedRows;
|
|
5078
|
-
current.maxDecodedRows = Math.max(current.maxDecodedRows, decodedRows);
|
|
5079
|
-
counters.operations[name] = current;
|
|
5080
|
-
const statement = QUERY_STATEMENTS[name];
|
|
5081
|
-
if (counters.captureQueries && statement) {
|
|
5082
|
-
(counters.queries ??= []).push({
|
|
5083
|
-
operation: name,
|
|
5084
|
-
statement,
|
|
5085
|
-
rows: returnedRowCount(value),
|
|
5086
|
-
elapsedMs: performance.now() - started
|
|
5087
|
-
});
|
|
5088
|
-
}
|
|
5089
|
-
}
|
|
5090
|
-
}
|
|
5091
|
-
function decode(row) {
|
|
5092
|
-
debugCounters().decodedRows += 1;
|
|
5093
|
-
const data = JSON.parse(row.data);
|
|
5094
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
5095
|
-
throw new Error(`Invalid session_message data at seq ${row.seq}`);
|
|
5096
|
-
}
|
|
5097
|
-
if (row.type === "idle" && !["succeeded", "failed", "interrupted"].includes(String(data.outcome))) {
|
|
5098
|
-
throw new Error(`Invalid idle outcome at seq ${row.seq}`);
|
|
5099
|
-
}
|
|
5100
|
-
return { ...row, data };
|
|
5101
|
-
}
|
|
5102
|
-
function connect(path, identity = "") {
|
|
5103
|
-
const stat = statSync5(path);
|
|
5104
|
-
const acquiredIdentity = identity || `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
|
|
5105
|
-
const db = new Database2(path, { readonly: true, fileMustExist: true });
|
|
5106
|
-
try {
|
|
5107
|
-
assertOpenCodeStoreGeneration(db, "v2", path);
|
|
5108
|
-
} catch (error) {
|
|
5109
|
-
db.close();
|
|
5110
|
-
throw error;
|
|
5111
|
-
}
|
|
5112
|
-
const counters = debugCounters();
|
|
5113
|
-
counters.openReaders += 1;
|
|
5114
|
-
counters.readersOpened += 1;
|
|
5115
|
-
counters.maxOpenReaders = Math.max(counters.maxOpenReaders, counters.openReaders);
|
|
5116
|
-
return { db, statements: new Map, identity: acquiredIdentity, leases: 0, retired: false };
|
|
5117
|
-
}
|
|
5118
|
-
function closeConnection(connection) {
|
|
5119
|
-
connection.statements.clear();
|
|
5120
|
-
try {
|
|
5121
|
-
connection.db.close();
|
|
5122
|
-
} finally {
|
|
5123
|
-
const counters = debugCounters();
|
|
5124
|
-
counters.openReaders = Math.max(0, counters.openReaders - 1);
|
|
5125
|
-
counters.readersClosed += 1;
|
|
5126
|
-
}
|
|
5127
|
-
}
|
|
5128
|
-
|
|
5129
|
-
class V2StoreReaderPool {
|
|
5130
|
-
capacity;
|
|
5131
|
-
connections = new Map;
|
|
5132
|
-
closed = false;
|
|
5133
|
-
closing = false;
|
|
5134
|
-
holds = 0;
|
|
5135
|
-
idleWaiters = new Set;
|
|
5136
|
-
constructor(capacity = 4) {
|
|
5137
|
-
this.capacity = capacity;
|
|
5138
|
-
if (!Number.isSafeInteger(capacity) || capacity < 1)
|
|
5139
|
-
throw new Error("Invalid reader capacity");
|
|
5140
|
-
}
|
|
5141
|
-
open(path) {
|
|
5142
|
-
return new V2StoreReader(path, this);
|
|
5143
|
-
}
|
|
5144
|
-
acquire(path) {
|
|
5145
|
-
if (this.closed)
|
|
5146
|
-
throw new Error("Store reader pool is closed");
|
|
5147
|
-
const key = resolve2(path);
|
|
5148
|
-
const stat = statSync5(key);
|
|
5149
|
-
const identity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
|
|
5150
|
-
let connection = this.connections.get(key);
|
|
5151
|
-
if (connection && connection.identity !== identity) {
|
|
5152
|
-
this.connections.delete(key);
|
|
5153
|
-
this.retire(connection);
|
|
5154
|
-
connection = undefined;
|
|
5155
|
-
}
|
|
5156
|
-
if (!connection)
|
|
5157
|
-
connection = connect(key, identity);
|
|
5158
|
-
connection.leases++;
|
|
5159
|
-
this.connections.delete(key);
|
|
5160
|
-
this.connections.set(key, connection);
|
|
5161
|
-
while (this.connections.size > this.capacity) {
|
|
5162
|
-
const oldest = this.connections.entries().next().value;
|
|
5163
|
-
if (!oldest)
|
|
5164
|
-
break;
|
|
5165
|
-
this.connections.delete(oldest[0]);
|
|
5166
|
-
this.retire(oldest[1]);
|
|
5167
|
-
}
|
|
5168
|
-
return connection;
|
|
5169
|
-
}
|
|
5170
|
-
release(connection) {
|
|
5171
|
-
connection.leases--;
|
|
5172
|
-
if (connection.retired && connection.leases === 0)
|
|
5173
|
-
closeConnection(connection);
|
|
5174
|
-
}
|
|
5175
|
-
retire(connection) {
|
|
5176
|
-
connection.retired = true;
|
|
5177
|
-
if (connection.leases === 0)
|
|
5178
|
-
closeConnection(connection);
|
|
5179
|
-
}
|
|
5180
|
-
hold() {
|
|
5181
|
-
if (this.closed || this.closing)
|
|
5182
|
-
throw new Error("Store reader pool is closed");
|
|
5183
|
-
this.holds++;
|
|
5184
|
-
let released = false;
|
|
5185
|
-
return () => {
|
|
5186
|
-
if (released)
|
|
5187
|
-
return;
|
|
5188
|
-
released = true;
|
|
5189
|
-
this.holds--;
|
|
5190
|
-
if (this.holds === 0 && this.closing)
|
|
5191
|
-
this.finishClose();
|
|
5192
|
-
};
|
|
5193
|
-
}
|
|
5194
|
-
isClosed() {
|
|
5195
|
-
return this.closed;
|
|
5196
|
-
}
|
|
5197
|
-
holdCount() {
|
|
5198
|
-
return this.holds;
|
|
5199
|
-
}
|
|
5200
|
-
close() {
|
|
5201
|
-
if (this.closed || this.closing)
|
|
5202
|
-
return;
|
|
5203
|
-
this.closing = true;
|
|
5204
|
-
if (this.holds === 0)
|
|
5205
|
-
this.finishClose();
|
|
5206
|
-
}
|
|
5207
|
-
async closeWhenIdle(timeoutMs) {
|
|
5208
|
-
this.close();
|
|
5209
|
-
if (this.closed)
|
|
5210
|
-
return true;
|
|
5211
|
-
let timer;
|
|
5212
|
-
let waiter;
|
|
5213
|
-
try {
|
|
5214
|
-
await new Promise((resolve) => {
|
|
5215
|
-
waiter = resolve;
|
|
5216
|
-
this.idleWaiters.add(resolve);
|
|
5217
|
-
timer = setTimeout(resolve, Math.max(0, timeoutMs));
|
|
5218
|
-
});
|
|
5219
|
-
} finally {
|
|
5220
|
-
if (timer)
|
|
5221
|
-
clearTimeout(timer);
|
|
5222
|
-
if (waiter)
|
|
5223
|
-
this.idleWaiters.delete(waiter);
|
|
5224
|
-
}
|
|
5225
|
-
return this.closed;
|
|
5226
|
-
}
|
|
5227
|
-
finishClose() {
|
|
5228
|
-
if (this.closed)
|
|
5229
|
-
return;
|
|
5230
|
-
this.closed = true;
|
|
5231
|
-
for (const connection of this.connections.values())
|
|
5232
|
-
this.retire(connection);
|
|
5233
|
-
this.connections.clear();
|
|
5234
|
-
for (const resolve of this.idleWaiters)
|
|
5235
|
-
resolve();
|
|
5236
|
-
this.idleWaiters.clear();
|
|
5237
|
-
}
|
|
5238
|
-
}
|
|
5239
|
-
|
|
5240
|
-
class V2StoreReader {
|
|
5241
|
-
path;
|
|
5242
|
-
pool;
|
|
5243
|
-
db;
|
|
5244
|
-
connection;
|
|
5245
|
-
closed = false;
|
|
5246
|
-
constructor(path, pool) {
|
|
5247
|
-
this.path = path;
|
|
5248
|
-
this.pool = pool;
|
|
5249
|
-
this.connection = pool ? pool.acquire(path) : connect(path);
|
|
5250
|
-
this.db = this.connection.db;
|
|
5251
|
-
}
|
|
5252
|
-
hostIdentity() {
|
|
5253
|
-
return createHash3("sha256").update(JSON.stringify([hostname(), resolve2(this.path), this.connection.identity])).digest("hex");
|
|
5254
|
-
}
|
|
5255
|
-
prepare(sql) {
|
|
5256
|
-
if (this.closed)
|
|
5257
|
-
throw new Error("Store reader is closed");
|
|
5258
|
-
const statements = this.connection.statements;
|
|
5259
|
-
let statement = statements.get(sql);
|
|
5260
|
-
if (!statement) {
|
|
5261
|
-
statement = this.db.prepare(sql);
|
|
5262
|
-
if (statements.size >= 128)
|
|
5263
|
-
statements.clear();
|
|
5264
|
-
statements.set(sql, statement);
|
|
5265
|
-
}
|
|
5266
|
-
return statement;
|
|
5267
|
-
}
|
|
5268
|
-
close() {
|
|
5269
|
-
if (this.closed)
|
|
5270
|
-
return;
|
|
5271
|
-
this.closed = true;
|
|
5272
|
-
if (this.pool)
|
|
5273
|
-
this.pool.release(this.connection);
|
|
5274
|
-
else
|
|
5275
|
-
closeConnection(this.connection);
|
|
5276
|
-
}
|
|
5277
|
-
page(sessionID, options = {}) {
|
|
5278
|
-
return trackDecodeOperation("page", () => {
|
|
5279
|
-
const limit = options.limit ?? 100;
|
|
5280
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
5281
|
-
throw new Error("Invalid page limit");
|
|
5282
|
-
const after = options.after ?? -1;
|
|
5283
|
-
if (!Number.isSafeInteger(after))
|
|
5284
|
-
throw new Error("Invalid seq cursor");
|
|
5285
|
-
if (options.through !== undefined && !Number.isSafeInteger(options.through))
|
|
5286
|
-
throw new Error("Invalid seq upper bound");
|
|
5287
|
-
const predicates = ["session_id = ?", "seq > ?"];
|
|
5288
|
-
const parameters = [sessionID, after];
|
|
5289
|
-
if (options.through !== undefined) {
|
|
5290
|
-
predicates.push("seq <= ?");
|
|
5291
|
-
parameters.push(options.through);
|
|
5292
|
-
}
|
|
5293
|
-
if (options.type) {
|
|
5294
|
-
predicates.push("type = ?");
|
|
5295
|
-
parameters.push(options.type);
|
|
5296
|
-
}
|
|
5297
|
-
const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5298
|
-
WHERE ${predicates.join(" AND ")}
|
|
5299
|
-
ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode);
|
|
5300
|
-
return { rows, cursor: rows.at(-1)?.seq };
|
|
5301
|
-
});
|
|
5302
|
-
}
|
|
5303
|
-
messagePage(sessionID, afterOrdinal, limit, finalWatermark, after) {
|
|
5304
|
-
return trackDecodeOperation("messagePage", () => {
|
|
5305
|
-
if (!Number.isSafeInteger(afterOrdinal) || afterOrdinal < 0)
|
|
5306
|
-
throw new Error("Invalid raw-message ordinal cursor");
|
|
5307
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
5308
|
-
throw new Error("Invalid page limit");
|
|
5309
|
-
if (!Number.isSafeInteger(finalWatermark) || finalWatermark < 0)
|
|
5310
|
-
throw new Error("Invalid raw-message watermark");
|
|
5311
|
-
const pageSize = Math.min(limit, finalWatermark - afterOrdinal);
|
|
5312
|
-
if (pageSize <= 0)
|
|
5313
|
-
return [];
|
|
5314
|
-
if (after) {
|
|
5315
|
-
const anchor = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ?").get(sessionID, after.id);
|
|
5316
|
-
if (anchor) {
|
|
5317
|
-
return this.prepare(`SELECT id, session_id, type, seq, time_created, data
|
|
5318
|
-
FROM session_message WHERE session_id = ? AND seq > ?
|
|
5319
|
-
AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES, pageSize).map(decode);
|
|
5320
|
-
}
|
|
5321
|
-
}
|
|
5322
|
-
const maximumSeq = Number.MAX_SAFE_INTEGER;
|
|
5323
|
-
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);
|
|
5324
|
-
return rows.map(decode);
|
|
5325
|
-
});
|
|
5326
|
-
}
|
|
5327
|
-
messageCount(sessionID) {
|
|
5328
|
-
return trackDecodeOperation("messageCount", () => {
|
|
5329
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5330
|
-
const row = this.prepare(`SELECT COUNT(*) AS count FROM session_message
|
|
5331
|
-
WHERE session_id = ? AND type IN (${rawTypes})`).get(sessionID, ...RAW_MESSAGE_TYPES);
|
|
5332
|
-
return typeof row?.count === "number" ? row.count : 0;
|
|
5333
|
-
});
|
|
5334
|
-
}
|
|
5335
|
-
sessionDirectoryPage(afterSessionID, limit) {
|
|
5336
|
-
const rows = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
|
|
5337
|
-
WHERE id > ? ORDER BY id ASC LIMIT ?`).all(afterSessionID ?? "", limit);
|
|
5338
|
-
return rows.map((row) => ({ sessionId: row.id, directory: row.directory }));
|
|
5339
|
-
}
|
|
5340
|
-
latestMessageTime(sessionID) {
|
|
5341
|
-
const row = this.prepare("SELECT MAX(time_created) AS time FROM session_message WHERE session_id = ?").get(sessionID);
|
|
5342
|
-
return row?.time ?? undefined;
|
|
5343
|
-
}
|
|
5344
|
-
isSubagent(sessionID) {
|
|
5345
|
-
const row = this.prepare("SELECT parent_id FROM session_v2 WHERE id = ?").get(sessionID);
|
|
5346
|
-
if (!row)
|
|
5347
|
-
return null;
|
|
5348
|
-
return typeof row.parent_id === "string" && row.parent_id.length > 0;
|
|
5349
|
-
}
|
|
5350
|
-
latestRootSessionInDirectory(directory) {
|
|
5351
|
-
const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
|
|
5352
|
-
const archived = columns.has("time_archived") ? " AND time_archived IS NULL" : "";
|
|
5353
|
-
const order = columns.has("time_updated") ? "time_updated DESC, id DESC" : "id DESC";
|
|
5354
|
-
const page = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
|
|
5355
|
-
WHERE parent_id IS NULL${archived}
|
|
5356
|
-
AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
|
|
5357
|
-
ORDER BY ${order} LIMIT ? OFFSET ?`);
|
|
5358
|
-
const pageSize = 500;
|
|
5359
|
-
for (let offset = 0;; offset += pageSize) {
|
|
5360
|
-
const rows = page.all(pageSize, offset);
|
|
5361
|
-
const match = rows.find((row) => sameProjectDirectory(row.directory, directory));
|
|
5362
|
-
if (match)
|
|
5363
|
-
return match.id;
|
|
5364
|
-
if (rows.length < pageSize)
|
|
5365
|
-
return;
|
|
5366
|
-
}
|
|
5367
|
-
}
|
|
5368
|
-
rootSessionActivity(sessionIDs) {
|
|
5369
|
-
const roots = new Map;
|
|
5370
|
-
for (let offset = 0;offset < sessionIDs.length; offset += 500) {
|
|
5371
|
-
const chunk = sessionIDs.slice(offset, offset + 500);
|
|
5372
|
-
const rows = this.prepare(`SELECT id, (
|
|
5373
|
-
SELECT MAX(time_created) FROM session_message
|
|
5374
|
-
WHERE session_id = session_v2.id AND type = 'user'
|
|
5375
|
-
) AS time FROM session_v2
|
|
5376
|
-
WHERE parent_id IS NULL
|
|
5377
|
-
AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
|
|
5378
|
-
AND id IN (${chunk.map(() => "?").join(",")})`).all(...chunk);
|
|
5379
|
-
for (const row of rows)
|
|
5380
|
-
if (row.time !== null)
|
|
5381
|
-
roots.set(row.id, row.time);
|
|
5382
|
-
}
|
|
5383
|
-
return roots;
|
|
5384
|
-
}
|
|
5385
|
-
oldestUserMessageTimesSince(sessionIDs, sinceMs) {
|
|
5386
|
-
const result = new Map;
|
|
5387
|
-
for (let offset = 0;offset < sessionIDs.length; offset += 500) {
|
|
5388
|
-
const chunk = sessionIDs.slice(offset, offset + 500);
|
|
5389
|
-
const rows = this.prepare(`SELECT session_id, MIN(time_created) AS time FROM session_message
|
|
5390
|
-
WHERE type = 'user' AND time_created > ? AND session_id IN (${chunk.map(() => "?").join(",")})
|
|
5391
|
-
GROUP BY session_id`).all(sinceMs, ...chunk);
|
|
5392
|
-
for (const row of rows)
|
|
5393
|
-
result.set(row.session_id, row.time);
|
|
5394
|
-
}
|
|
5395
|
-
return result;
|
|
5396
|
-
}
|
|
5397
|
-
retrospectiveUserPage(sessionID, options) {
|
|
5398
|
-
const { boundaryMs, before, limit, maxChars, truncationMarker } = options;
|
|
5399
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
5400
|
-
throw new Error("Invalid page limit");
|
|
5401
|
-
if (!Number.isSafeInteger(maxChars) || maxChars <= truncationMarker.length)
|
|
5402
|
-
throw new Error("Invalid text limit");
|
|
5403
|
-
const direction = before ? "DESC" : "ASC";
|
|
5404
|
-
const head = Math.floor((maxChars - truncationMarker.length) / 2);
|
|
5405
|
-
const tail = maxChars - truncationMarker.length - head;
|
|
5406
|
-
return this.prepare(`WITH users AS (
|
|
5407
|
-
SELECT session_id, seq, time_created, data FROM session_message
|
|
5408
|
-
WHERE session_id = ? AND type = 'user' AND time_created ${before ? "<=" : ">"}
|
|
5409
|
-
?
|
|
5410
|
-
ORDER BY time_created ${direction}, seq ${direction} LIMIT ?
|
|
5411
|
-
), texts AS (
|
|
5412
|
-
SELECT session_id, seq, time_created, CASE
|
|
5413
|
-
WHEN json_extract(data, '$.synthetic') = 1 OR json_extract(data, '$.ignored') = 1 THEN ''
|
|
5414
|
-
WHEN json_type(data, '$.text') = 'text' THEN json_extract(data, '$.text')
|
|
5415
|
-
ELSE COALESCE((SELECT group_concat(json_extract(value, '$.text'), char(10))
|
|
5416
|
-
FROM json_each(users.data, '$.content')
|
|
5417
|
-
WHERE json_extract(value, '$.type') IN ('text', 'input_text')
|
|
5418
|
-
AND COALESCE(json_extract(value, '$.synthetic'), 0) <> 1
|
|
5419
|
-
AND COALESCE(json_extract(value, '$.ignored'), 0) <> 1), '') END AS text
|
|
5420
|
-
FROM users WHERE json_valid(data)
|
|
5421
|
-
) SELECT seq, time_created, CASE WHEN length(text) > ?
|
|
5422
|
-
THEN substr(text, 1, ?) || ? || substr(text, -?) ELSE text END AS text,
|
|
5423
|
-
EXISTS (
|
|
5424
|
-
SELECT 1 FROM session_message assistant_reply
|
|
5425
|
-
WHERE assistant_reply.session_id = texts.session_id
|
|
5426
|
-
AND assistant_reply.type = 'assistant'
|
|
5427
|
-
AND assistant_reply.seq < texts.seq
|
|
5428
|
-
AND EXISTS (
|
|
5429
|
-
SELECT 1 FROM session_message prior_user
|
|
5430
|
-
WHERE prior_user.session_id = texts.session_id
|
|
5431
|
-
AND prior_user.type = 'user'
|
|
5432
|
-
AND prior_user.seq < assistant_reply.seq
|
|
5433
|
-
)
|
|
5434
|
-
) AS follows_assistant_reply
|
|
5435
|
-
FROM texts ORDER BY time_created ${direction}, seq ${direction}`).all(sessionID, boundaryMs, limit, maxChars, head, truncationMarker, tail);
|
|
5436
|
-
}
|
|
5437
|
-
storedRowsAfter(sessionID, after) {
|
|
5438
|
-
const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND seq > ?").get(sessionID, after);
|
|
5439
|
-
return row.count;
|
|
5440
|
-
}
|
|
5441
|
-
storedMessageCount(sessionID) {
|
|
5442
|
-
return trackDecodeOperation("storedMessageCount", () => {
|
|
5443
|
-
const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?").get(sessionID);
|
|
5444
|
-
return typeof row?.count === "number" ? row.count : 0;
|
|
5445
|
-
});
|
|
5446
|
-
}
|
|
5447
|
-
messageById(sessionID, id) {
|
|
5448
|
-
return trackDecodeOperation("messageById", () => {
|
|
5449
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5450
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5451
|
-
WHERE session_id = ? AND id = ? AND type IN (${rawTypes}) LIMIT 1`).get(sessionID, id, ...RAW_MESSAGE_TYPES);
|
|
5452
|
-
return row ? decode(row) : null;
|
|
5453
|
-
});
|
|
5454
|
-
}
|
|
5455
|
-
messageTimes(sessionID, ids) {
|
|
5456
|
-
const times = new Map;
|
|
5457
|
-
for (let offset = 0;offset < ids.length; offset += 500) {
|
|
5458
|
-
const batch = ids.slice(offset, offset + 500);
|
|
5459
|
-
const rows = this.prepare(`SELECT id, COALESCE(time_created, json_extract(data, '$.time.created')) AS created,
|
|
5460
|
-
json_extract(data, '$.time.completed') AS completed
|
|
5461
|
-
FROM session_message WHERE session_id = ? AND id IN (${batch.map(() => "?").join(",")})`).all(sessionID, ...batch);
|
|
5462
|
-
for (const row of rows)
|
|
5463
|
-
times.set(row.id, {
|
|
5464
|
-
created: typeof row.created === "number" ? row.created : undefined,
|
|
5465
|
-
completed: typeof row.completed === "number" ? row.completed : undefined
|
|
5466
|
-
});
|
|
5467
|
-
}
|
|
5468
|
-
return times;
|
|
5469
|
-
}
|
|
5470
|
-
messageExistsById(sessionID, id) {
|
|
5471
|
-
return trackDecodeOperation("messageExistsById", () => {
|
|
5472
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5473
|
-
const row = this.prepare(`SELECT 1 FROM session_message
|
|
5474
|
-
WHERE id = ? AND session_id = ? AND type IN (${rawTypes}) LIMIT 1`).get(id, sessionID, ...RAW_MESSAGE_TYPES);
|
|
5475
|
-
return row != null;
|
|
5476
|
-
});
|
|
5477
|
-
}
|
|
5478
|
-
messageOrdinalById(sessionID, id) {
|
|
5479
|
-
return trackDecodeOperation("messageOrdinalById", () => {
|
|
5480
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5481
|
-
const row = this.prepare(`WITH target AS (
|
|
5482
|
-
SELECT seq FROM session_message
|
|
5483
|
-
WHERE session_id = ? AND id = ? AND type IN (${rawTypes})
|
|
5484
|
-
LIMIT 1
|
|
5485
|
-
)
|
|
5486
|
-
SELECT (
|
|
5487
|
-
SELECT COUNT(*) FROM session_message
|
|
5488
|
-
WHERE session_id = ?
|
|
5489
|
-
AND type IN (${rawTypes})
|
|
5490
|
-
AND seq <= target.seq
|
|
5491
|
-
) AS ordinal
|
|
5492
|
-
FROM target`).get(sessionID, id, ...RAW_MESSAGE_TYPES, sessionID, ...RAW_MESSAGE_TYPES);
|
|
5493
|
-
return typeof row?.ordinal === "number" ? row.ordinal : null;
|
|
5494
|
-
});
|
|
5495
|
-
}
|
|
5496
|
-
messageIdOrdinals(sessionID, fromOrdinal, toOrdinal) {
|
|
5497
|
-
return trackDecodeOperation("messageIdOrdinals", () => {
|
|
5498
|
-
if (!Number.isSafeInteger(fromOrdinal) || fromOrdinal < 1)
|
|
5499
|
-
throw new Error("Invalid raw-message range start");
|
|
5500
|
-
if (!Number.isSafeInteger(toOrdinal) || toOrdinal < fromOrdinal)
|
|
5501
|
-
throw new Error("Invalid raw-message range end");
|
|
5502
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5503
|
-
const rows = this.prepare(`SELECT id FROM session_message
|
|
5504
|
-
WHERE session_id = ? AND type IN (${rawTypes})
|
|
5505
|
-
ORDER BY seq ASC LIMIT ? OFFSET ?`).all(sessionID, ...RAW_MESSAGE_TYPES, toOrdinal - fromOrdinal + 1, fromOrdinal - 1);
|
|
5506
|
-
return new Map(rows.map((row, index) => [row.id, fromOrdinal + index]));
|
|
5507
|
-
});
|
|
5508
|
-
}
|
|
5509
|
-
messageOrdinalPage(sessionID, after, limit) {
|
|
5510
|
-
return trackDecodeOperation("messageOrdinalPage", () => {
|
|
5511
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
5512
|
-
throw new Error("Invalid page limit");
|
|
5513
|
-
const rows = after ? this.prepare(`SELECT id, type, seq, json_valid(data) AS valid
|
|
5514
|
-
FROM session_message
|
|
5515
|
-
WHERE session_id = ? AND (seq > ? OR (seq = ? AND id > ?))
|
|
5516
|
-
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
|
|
5517
|
-
FROM session_message
|
|
5518
|
-
WHERE session_id = ?
|
|
5519
|
-
ORDER BY seq ASC, id ASC LIMIT ?`).all(sessionID, limit);
|
|
5520
|
-
const rawTypes = new Set(RAW_MESSAGE_TYPES);
|
|
5521
|
-
return rows.map((row) => ({
|
|
5522
|
-
id: row.id,
|
|
5523
|
-
timeCreated: row.seq,
|
|
5524
|
-
contributesOrdinal: rawTypes.has(row.type),
|
|
5525
|
-
hasValidInfo: row.valid === 1
|
|
5526
|
-
}));
|
|
5527
|
-
});
|
|
5528
|
-
}
|
|
5529
|
-
range(sessionID, after, through) {
|
|
5530
|
-
return trackDecodeOperation("range", () => through <= after ? [] : this.all(sessionID, after, undefined, through));
|
|
5531
|
-
}
|
|
5532
|
-
spanRowStamps(sessionID, after, through) {
|
|
5533
|
-
if (!Number.isSafeInteger(after) || !Number.isSafeInteger(through))
|
|
5534
|
-
throw new Error("Invalid seq span");
|
|
5535
|
-
const rows = this.prepare(`SELECT seq, id, time_updated AS updated, length(CAST(data AS BLOB)) AS bytes
|
|
5536
|
-
FROM session_message WHERE session_id = ? AND seq > ? AND seq <= ?
|
|
5537
|
-
ORDER BY seq ASC`).all(sessionID, after, through);
|
|
5538
|
-
const stamps = new Map;
|
|
5539
|
-
for (const row of rows)
|
|
5540
|
-
stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}`);
|
|
5541
|
-
return stamps;
|
|
5542
|
-
}
|
|
5543
|
-
rawRowsThrough(sessionID, throughSeq, limit) {
|
|
5544
|
-
return trackDecodeOperation("rawRowsThrough", () => {
|
|
5545
|
-
if (!Number.isSafeInteger(throughSeq))
|
|
5546
|
-
throw new Error("Invalid seq upper bound");
|
|
5547
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
|
|
5548
|
-
throw new Error("Invalid page limit");
|
|
5549
|
-
const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
|
|
5550
|
-
return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5551
|
-
WHERE session_id = ? AND type IN (${rawTypes}) AND seq <= ?
|
|
5552
|
-
ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES, throughSeq, limit).map(decode);
|
|
5553
|
-
});
|
|
5554
|
-
}
|
|
5555
|
-
sequenceForId(sessionID, id) {
|
|
5556
|
-
if (!id)
|
|
5557
|
-
return;
|
|
5558
|
-
const row = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ? LIMIT 1").get(sessionID, id);
|
|
5559
|
-
return typeof row?.seq === "number" ? row.seq : undefined;
|
|
5560
|
-
}
|
|
5561
|
-
syntheticMessageIDs(sessionID) {
|
|
5562
|
-
const rows = this.prepare("SELECT id FROM session_message WHERE session_id = ? AND type = 'synthetic'").all(sessionID);
|
|
5563
|
-
return new Set(rows.map((row) => row.id));
|
|
5564
|
-
}
|
|
5565
|
-
forkOrigin(sessionID) {
|
|
5566
|
-
const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
|
|
5567
|
-
if (!columns.has("fork_session_id") || !columns.has("fork_boundary"))
|
|
5568
|
-
return null;
|
|
5569
|
-
const row = this.prepare("SELECT fork_session_id, fork_boundary FROM session_v2 WHERE id = ?").get(sessionID);
|
|
5570
|
-
if (!row?.fork_session_id || !row.fork_boundary)
|
|
5571
|
-
return null;
|
|
5572
|
-
try {
|
|
5573
|
-
const boundary = JSON.parse(row.fork_boundary);
|
|
5574
|
-
if (boundary.type !== "before" && boundary.type !== "through" || typeof boundary.messageID !== "string" || boundary.messageID.length === 0)
|
|
5575
|
-
return null;
|
|
5576
|
-
return {
|
|
5577
|
-
parentSessionID: row.fork_session_id,
|
|
5578
|
-
boundary: { type: boundary.type, messageID: boundary.messageID }
|
|
5579
|
-
};
|
|
5580
|
-
} catch {
|
|
5581
|
-
return null;
|
|
5582
|
-
}
|
|
5583
|
-
}
|
|
5584
|
-
sessionExists(sessionID) {
|
|
5585
|
-
return this.prepare("SELECT 1 FROM session_v2 WHERE id = ?").get(sessionID) != null;
|
|
5586
|
-
}
|
|
5587
|
-
rowStampsThrough(sessionID, throughSeq) {
|
|
5588
|
-
return this.prepare(`SELECT id, type, seq, time_created FROM session_message
|
|
5589
|
-
WHERE session_id = ? AND seq <= ? ORDER BY seq ASC`).all(sessionID, throughSeq);
|
|
5590
|
-
}
|
|
5591
|
-
latestSequenceForIds(sessionID, ids) {
|
|
5592
|
-
let latest = -1;
|
|
5593
|
-
for (let offset = 0;offset < ids.length; offset += 500) {
|
|
5594
|
-
const chunk = ids.slice(offset, offset + 500);
|
|
5595
|
-
const row = this.prepare(`SELECT MAX(seq) AS seq FROM session_message
|
|
5596
|
-
WHERE session_id = ? AND id IN (${chunk.map(() => "?").join(", ")})`).get(sessionID, ...chunk);
|
|
5597
|
-
if (typeof row?.seq === "number")
|
|
5598
|
-
latest = Math.max(latest, row.seq);
|
|
5599
|
-
}
|
|
5600
|
-
return latest;
|
|
5601
|
-
}
|
|
5602
|
-
compactionByStatus(sessionID, status) {
|
|
5603
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5604
|
-
WHERE session_id = ? AND type = 'compaction'
|
|
5605
|
-
AND json_extract(data, '$.status') = ?
|
|
5606
|
-
ORDER BY seq DESC LIMIT 1`).get(sessionID, status);
|
|
5607
|
-
return row ? decode(row) : undefined;
|
|
5608
|
-
}
|
|
5609
|
-
latestCompaction(sessionID) {
|
|
5610
|
-
return trackDecodeOperation("latestCompaction", () => this.compactionByStatus(sessionID, "completed"));
|
|
5611
|
-
}
|
|
5612
|
-
latestRunningCompaction(sessionID) {
|
|
5613
|
-
return trackDecodeOperation("latestRunningCompaction", () => this.compactionByStatus(sessionID, "running"));
|
|
5614
|
-
}
|
|
5615
|
-
idleRows(sessionID, after = -1) {
|
|
5616
|
-
return trackDecodeOperation("idleRows", () => this.all(sessionID, after, "idle"));
|
|
5617
|
-
}
|
|
5618
|
-
earliestSequence(sessionID) {
|
|
5619
|
-
const row = this.prepare("SELECT MIN(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
|
|
5620
|
-
return typeof row?.seq === "number" ? row.seq : undefined;
|
|
5621
|
-
}
|
|
5622
|
-
latestSequence(sessionID) {
|
|
5623
|
-
const row = this.prepare("SELECT MAX(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
|
|
5624
|
-
return typeof row?.seq === "number" ? row.seq : -1;
|
|
5625
|
-
}
|
|
5626
|
-
assistantSince(sessionID, afterSeq) {
|
|
5627
|
-
return trackDecodeOperation("assistantSince", () => {
|
|
5628
|
-
const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5629
|
-
WHERE session_id = ? AND type = 'assistant' AND seq > ?
|
|
5630
|
-
ORDER BY seq ASC`).all(sessionID, afterSeq);
|
|
5631
|
-
return rows.map((row) => decode(row));
|
|
5632
|
-
});
|
|
5633
|
-
}
|
|
5634
|
-
latestAssistant(sessionID) {
|
|
5635
|
-
return trackDecodeOperation("latestAssistant", () => {
|
|
5636
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5637
|
-
WHERE session_id = ? AND type = 'assistant'
|
|
5638
|
-
ORDER BY seq DESC LIMIT 1`).get(sessionID);
|
|
5639
|
-
return row ? decode(row) : undefined;
|
|
5640
|
-
});
|
|
5641
|
-
}
|
|
5642
|
-
latestIdle(sessionID) {
|
|
5643
|
-
return trackDecodeOperation("latestIdle", () => {
|
|
5644
|
-
const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
|
|
5645
|
-
WHERE session_id = ? AND type = 'idle'
|
|
5646
|
-
ORDER BY seq DESC LIMIT 1`).get(sessionID);
|
|
5647
|
-
return row ? decode(row) : undefined;
|
|
5648
|
-
});
|
|
5649
|
-
}
|
|
5650
|
-
window(sessionID) {
|
|
5651
|
-
return trackDecodeOperation("window", () => this.db.transaction(() => {
|
|
5652
|
-
const cut = this.latestCompaction(sessionID);
|
|
5653
|
-
return this.all(sessionID, cut ? cut.seq - 1 : -1);
|
|
5654
|
-
}).deferred());
|
|
5655
|
-
}
|
|
5656
|
-
history(sessionID) {
|
|
5657
|
-
return trackDecodeOperation("history", () => this.all(sessionID, -1));
|
|
5658
|
-
}
|
|
5659
|
-
all(sessionID, after, type, through) {
|
|
5660
|
-
const rows = [];
|
|
5661
|
-
for (;; ) {
|
|
5662
|
-
const page = this.page(sessionID, { after, through, type });
|
|
5663
|
-
rows.push(...page.rows);
|
|
5664
|
-
if (page.rows.length < 100 || page.cursor === undefined)
|
|
5665
|
-
return rows;
|
|
5666
|
-
after = page.cursor;
|
|
5667
|
-
}
|
|
5668
|
-
}
|
|
5669
|
-
}
|
|
5670
|
-
|
|
5671
4988
|
// src/features/magic-context/resolve-subagent-fallback.ts
|
|
5672
4989
|
function resolveIsSubagentFromOpenCodeDb(sessionId) {
|
|
5673
4990
|
try {
|
|
@@ -5744,17 +5061,48 @@ function findSessionMeta(db, sessionId) {
|
|
|
5744
5061
|
const result = db.prepare(`SELECT ${getSessionMetaSelectColumns(db)} FROM session_meta WHERE session_id = ?`).get(sessionId);
|
|
5745
5062
|
return isSessionMetaRow(result) ? toSessionMeta(result) : undefined;
|
|
5746
5063
|
}
|
|
5064
|
+
var parentReadRetries = new WeakMap;
|
|
5065
|
+
var PARENT_READ_ATTEMPTS = 5;
|
|
5066
|
+
var PARENT_READ_COOLDOWN_MS = 30000;
|
|
5747
5067
|
function getOrCreateSessionMeta(db, sessionId) {
|
|
5748
5068
|
const existing = findSessionMeta(db, sessionId);
|
|
5749
|
-
if (existing)
|
|
5750
|
-
return existing;
|
|
5751
|
-
const defaults = getDefaultSessionMeta(sessionId);
|
|
5752
5069
|
const harness = getHarness2();
|
|
5070
|
+
if (existing) {
|
|
5071
|
+
if (harness !== "opencode2")
|
|
5072
|
+
return existing;
|
|
5073
|
+
const row = db.prepare("SELECT is_subagent FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5074
|
+
if (row.is_subagent !== null)
|
|
5075
|
+
return existing;
|
|
5076
|
+
}
|
|
5077
|
+
const defaults = existing ?? getDefaultSessionMeta(sessionId);
|
|
5078
|
+
let retries = parentReadRetries.get(db);
|
|
5079
|
+
if (harness === "opencode2") {
|
|
5080
|
+
if (!retries) {
|
|
5081
|
+
retries = new BoundedSessionMap(1000);
|
|
5082
|
+
parentReadRetries.set(db, retries);
|
|
5083
|
+
}
|
|
5084
|
+
const retry = retries.get(sessionId);
|
|
5085
|
+
if (retry && retry.attempts >= PARENT_READ_ATTEMPTS && Date.now() - retry.at < PARENT_READ_COOLDOWN_MS)
|
|
5086
|
+
return defaults;
|
|
5087
|
+
}
|
|
5753
5088
|
const fallbackSubagent = harness === "opencode" ? resolveIsSubagentFromOpenCodeDb(sessionId) : harness === "opencode2" ? resolveIsSubagentFromOpenCode2Db(sessionId) : null;
|
|
5754
5089
|
if (fallbackSubagent === true) {
|
|
5755
5090
|
defaults.isSubagent = true;
|
|
5756
5091
|
}
|
|
5757
|
-
|
|
5092
|
+
if (harness === "opencode2") {
|
|
5093
|
+
if (fallbackSubagent === null) {
|
|
5094
|
+
const previous = retries?.get(sessionId);
|
|
5095
|
+
const attempts = previous && Date.now() - previous.at < PARENT_READ_COOLDOWN_MS ? previous.attempts + 1 : 1;
|
|
5096
|
+
retries?.set(sessionId, { attempts, at: Date.now() });
|
|
5097
|
+
ensureSessionMetaRow(db, sessionId, null);
|
|
5098
|
+
return defaults;
|
|
5099
|
+
}
|
|
5100
|
+
retries?.delete(sessionId);
|
|
5101
|
+
ensureSessionMetaRow(db, sessionId, fallbackSubagent);
|
|
5102
|
+
db.prepare("UPDATE session_meta SET is_subagent = ? WHERE session_id = ? AND is_subagent IS NULL").run(fallbackSubagent ? 1 : 0, sessionId);
|
|
5103
|
+
return defaults;
|
|
5104
|
+
}
|
|
5105
|
+
ensureSessionMetaRow(db, sessionId);
|
|
5758
5106
|
if (harness === "opencode" && fallbackSubagent === true) {
|
|
5759
5107
|
db.prepare("UPDATE session_meta SET is_subagent = 1 WHERE session_id = ?").run(sessionId);
|
|
5760
5108
|
}
|
|
@@ -5863,14 +5211,18 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false, perm
|
|
|
5863
5211
|
cancelAutoSearchWork(sessionId);
|
|
5864
5212
|
let transactionStartedAt = 0;
|
|
5865
5213
|
let clearedMarker = null;
|
|
5214
|
+
let eligibleSessions = 0;
|
|
5866
5215
|
withoutSqliteTransformPass2(() => withSqliteBackgroundWriter2(() => db.transaction(() => {
|
|
5867
5216
|
transactionStartedAt = performance.now();
|
|
5868
5217
|
clearedMarker = getPendingPiCompactionMarkerState(db, sessionId);
|
|
5869
|
-
deleteSessionScopedRows(db, [sessionId], undefined, {
|
|
5218
|
+
eligibleSessions = deleteSessionScopedRows(db, [sessionId], undefined, {
|
|
5870
5219
|
rustModuleCleanupAcknowledged,
|
|
5871
|
-
preserveTagRevisionTombstones: !permanentlyDeleted
|
|
5220
|
+
preserveTagRevisionTombstones: !permanentlyDeleted,
|
|
5221
|
+
deferRecoveryFenceCleanup: true
|
|
5872
5222
|
});
|
|
5873
5223
|
}).immediate()));
|
|
5224
|
+
if (eligibleSessions > 0)
|
|
5225
|
+
clearLkgRecoveryFence(sessionId);
|
|
5874
5226
|
if (clearedMarker)
|
|
5875
5227
|
logPiCompactionMarkerClear(sessionId, clearedMarker, "session-reset");
|
|
5876
5228
|
clearUnpublishedAutoSearchNoHints(sessionId);
|
|
@@ -6033,7 +5385,7 @@ function lkgProviderInputTotal(tokens) {
|
|
|
6033
5385
|
return counts.every((count) => Number.isSafeInteger(count) && count >= 0) ? counts.reduce((sum, count) => sum + count, 0) : Number.NaN;
|
|
6034
5386
|
}
|
|
6035
5387
|
function identity(slot) {
|
|
6036
|
-
return
|
|
5388
|
+
return createHash3("sha256").update(JSON.stringify([
|
|
6037
5389
|
slot.capturedAt,
|
|
6038
5390
|
slot.captureSequence,
|
|
6039
5391
|
slot.rowVersion,
|
|
@@ -6129,7 +5481,7 @@ function clearCapturedLkgMeasurement(sessionId) {
|
|
|
6129
5481
|
}
|
|
6130
5482
|
|
|
6131
5483
|
// src/hooks/magic-context/lkg-persist.ts
|
|
6132
|
-
import { createHash as
|
|
5484
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
6133
5485
|
function parseStringArray(value) {
|
|
6134
5486
|
if (typeof value !== "string")
|
|
6135
5487
|
return null;
|
|
@@ -6243,7 +5595,7 @@ function rememberFingerprint(db, sessionId, fingerprint) {
|
|
|
6243
5595
|
saved.set(sessionId, fingerprint);
|
|
6244
5596
|
}
|
|
6245
5597
|
function slotFingerprint(slot) {
|
|
6246
|
-
return
|
|
5598
|
+
return createHash4("sha256").update(JSON.stringify([
|
|
6247
5599
|
slot.jsonPrefix,
|
|
6248
5600
|
slot.inputIdSeq,
|
|
6249
5601
|
slot.inputContentDigests,
|
|
@@ -6687,6 +6039,8 @@ function outputMessageIsPostAnchor(message, inputIndexById, anchorIndex) {
|
|
|
6687
6039
|
}
|
|
6688
6040
|
return false;
|
|
6689
6041
|
}
|
|
6042
|
+
if (isCoveredInstructionRow(message.info))
|
|
6043
|
+
return false;
|
|
6690
6044
|
if (!isSyntheticOutput(message))
|
|
6691
6045
|
return null;
|
|
6692
6046
|
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId"].map((key) => recordValue(message.info, key)).find((value) => typeof value === "string");
|
|
@@ -7357,7 +6711,7 @@ var DIGEST_CHUNK_BYTES = 64 * 1024;
|
|
|
7357
6711
|
var digestChunk;
|
|
7358
6712
|
function lkgContentDigestFromFields(fields) {
|
|
7359
6713
|
lkgDigestsComputed += 1;
|
|
7360
|
-
const hash =
|
|
6714
|
+
const hash = createHash5("sha256");
|
|
7361
6715
|
digestChunk ??= Buffer.allocUnsafe(DIGEST_CHUNK_BYTES);
|
|
7362
6716
|
const chunk = digestChunk;
|
|
7363
6717
|
let offset = 0;
|
|
@@ -7420,7 +6774,7 @@ function legacyLkgDigestFromFields(fields) {
|
|
|
7420
6774
|
const value = typeof field === "symbol" ? field.description ?? "" : String(field);
|
|
7421
6775
|
key += `${typeof field}:${value.length}:${value}\x00`;
|
|
7422
6776
|
}
|
|
7423
|
-
return
|
|
6777
|
+
return createHash5("sha256").update(key).digest("base64url");
|
|
7424
6778
|
}
|
|
7425
6779
|
function legacyLkgContentDigest(message) {
|
|
7426
6780
|
const fields = flattenContentFields(withoutEmptyUserDiffSummary(message));
|
|
@@ -7644,10 +6998,11 @@ function dropSlot(sessionId, _reason) {
|
|
|
7644
6998
|
if (pass !== undefined)
|
|
7645
6999
|
hydrationAttemptBySession.set(sessionId, pass);
|
|
7646
7000
|
}
|
|
7647
|
-
function noteEntry(sessionId,
|
|
7001
|
+
function noteEntry(sessionId, input) {
|
|
7648
7002
|
const slot = getSlot(sessionId);
|
|
7649
7003
|
if (!slot)
|
|
7650
7004
|
return null;
|
|
7005
|
+
const messages = input.some((message) => isCoveredInstructionRow(message.info)) ? input.filter((message) => !isCoveredInstructionRow(message.info)) : input;
|
|
7651
7006
|
const entryInputIds = messages.map((message) => {
|
|
7652
7007
|
const id = message.info?.id;
|
|
7653
7008
|
return typeof id === "string" ? id : "";
|
|
@@ -8888,7 +8243,7 @@ class HiddenCompletionRefusal extends Error {
|
|
|
8888
8243
|
}
|
|
8889
8244
|
// src/features/magic-context/dreamer/provider-output-failure.ts
|
|
8890
8245
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8891
|
-
import { createHash as
|
|
8246
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
8892
8247
|
var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
|
|
8893
8248
|
|
|
8894
8249
|
class DreamerProviderOutputFailureError extends Error {
|
|
@@ -8985,12 +8340,45 @@ function providerOutputFailureFromInvalidManifest(messages, responseText, now =
|
|
|
8985
8340
|
const resetAt = quotaResetAt(responseText, now);
|
|
8986
8341
|
if (resetAt === undefined && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
|
|
8987
8342
|
return null;
|
|
8988
|
-
const fingerprint =
|
|
8343
|
+
const fingerprint = createHash6("sha256").update(normalized).digest("hex").slice(0, 16);
|
|
8989
8344
|
return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText, resetAt);
|
|
8990
8345
|
}
|
|
8991
8346
|
|
|
8992
8347
|
// src/v2/hooks/hidden-child.ts
|
|
8993
|
-
import { createHash as
|
|
8348
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
8349
|
+
|
|
8350
|
+
// src/shared/historian-cache.ts
|
|
8351
|
+
function withoutHistorianTailCache(body) {
|
|
8352
|
+
const value = JSON.parse(body);
|
|
8353
|
+
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)
|
|
8354
|
+
return body;
|
|
8355
|
+
const root = parseTree(body);
|
|
8356
|
+
const property = (node, key) => node?.children?.find((child) => child.children?.[0]?.value === key)?.children?.[1];
|
|
8357
|
+
const removals = [];
|
|
8358
|
+
for (const message of property(root, "messages")?.children ?? []) {
|
|
8359
|
+
for (const block of property(message, "content")?.children ?? []) {
|
|
8360
|
+
if (block.type !== "object")
|
|
8361
|
+
continue;
|
|
8362
|
+
const fields = block.children ?? [];
|
|
8363
|
+
fields.forEach((field, index) => {
|
|
8364
|
+
if (field.children?.[0]?.value !== "cache_control")
|
|
8365
|
+
return;
|
|
8366
|
+
const next = fields[index + 1];
|
|
8367
|
+
const previous = fields[index - 1];
|
|
8368
|
+
removals.push(next ? [field.offset, next.offset] : [
|
|
8369
|
+
previous ? previous.offset + previous.length : field.offset,
|
|
8370
|
+
field.offset + field.length
|
|
8371
|
+
]);
|
|
8372
|
+
});
|
|
8373
|
+
}
|
|
8374
|
+
}
|
|
8375
|
+
for (const [start, end] of removals.sort((a, b) => b[0] - a[0])) {
|
|
8376
|
+
body = body.slice(0, start) + body.slice(end);
|
|
8377
|
+
}
|
|
8378
|
+
return body;
|
|
8379
|
+
}
|
|
8380
|
+
|
|
8381
|
+
// src/v2/hooks/hidden-child.ts
|
|
8994
8382
|
var HIDDEN_HISTORIAN_AGENT = "historian";
|
|
8995
8383
|
var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
|
|
8996
8384
|
var HIDDEN_CURATE_AGENT = DREAMER_AGENT;
|
|
@@ -9154,7 +8542,7 @@ function markerCandidates(text) {
|
|
|
9154
8542
|
function textDigest(text) {
|
|
9155
8543
|
return {
|
|
9156
8544
|
length: text.length,
|
|
9157
|
-
sha256:
|
|
8545
|
+
sha256: createHash7("sha256").update(text).digest("hex").slice(0, 16)
|
|
9158
8546
|
};
|
|
9159
8547
|
}
|
|
9160
8548
|
function firstDifference(a, b) {
|
|
@@ -9177,6 +8565,7 @@ class HiddenChildHook {
|
|
|
9177
8565
|
childIDs = new Map;
|
|
9178
8566
|
attempts = new Map;
|
|
9179
8567
|
active = new Map;
|
|
8568
|
+
cacheWarnings = new Set;
|
|
9180
8569
|
constructor(note = log2) {
|
|
9181
8570
|
this.note = note;
|
|
9182
8571
|
}
|
|
@@ -9202,6 +8591,30 @@ class HiddenChildHook {
|
|
|
9202
8591
|
owns(sessionID) {
|
|
9203
8592
|
return this.childIDs.has(sessionID);
|
|
9204
8593
|
}
|
|
8594
|
+
async cacheRequest(draft) {
|
|
8595
|
+
const attempt = this.active.get(draft.sessionID);
|
|
8596
|
+
if (!this.owns(draft.sessionID) || !attempt || attempt.identity.kind !== "historian" || draft.kind !== "primary" || attempt.request.cacheTail !== "skip")
|
|
8597
|
+
return;
|
|
8598
|
+
if ((attempt.wireRequests ?? 0) > 0)
|
|
8599
|
+
return;
|
|
8600
|
+
attempt.wireRequests = 1;
|
|
8601
|
+
try {
|
|
8602
|
+
const original = await draft.request.clone().text();
|
|
8603
|
+
const body = withoutHistorianTailCache(original);
|
|
8604
|
+
if (body === original)
|
|
8605
|
+
return;
|
|
8606
|
+
const headers = new Headers(draft.request.headers);
|
|
8607
|
+
headers.delete("content-length");
|
|
8608
|
+
draft.request = new Request(draft.request, { body, headers });
|
|
8609
|
+
} catch (error) {
|
|
8610
|
+
if (!this.cacheWarnings.has(draft.sessionID)) {
|
|
8611
|
+
this.cacheWarnings.add(draft.sessionID);
|
|
8612
|
+
try {
|
|
8613
|
+
this.note(`Historian cache optimization skipped for ${draft.sessionID}: ${String(error)}`);
|
|
8614
|
+
} catch {}
|
|
8615
|
+
}
|
|
8616
|
+
}
|
|
8617
|
+
}
|
|
9205
8618
|
compactionSummary(sessionID, agent) {
|
|
9206
8619
|
if (!this.owns(sessionID)) {
|
|
9207
8620
|
if (isChildOfDisposedInstance(sessionID)) {
|
|
@@ -10300,9 +9713,9 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
|
|
|
10300
9713
|
}
|
|
10301
9714
|
}
|
|
10302
9715
|
// src/shared/prompt-surface-runtime.ts
|
|
10303
|
-
import { createHash as
|
|
10304
|
-
import { existsSync as existsSync5, readFileSync as readFileSync6, statSync as
|
|
10305
|
-
import { dirname as dirname4, isAbsolute as isAbsolute3, resolve as
|
|
9716
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
9717
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
|
|
9718
|
+
import { dirname as dirname4, isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
|
|
10306
9719
|
|
|
10307
9720
|
// src/tools/light-descriptions.ts
|
|
10308
9721
|
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".`;
|
|
@@ -10333,12 +9746,12 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
|
|
|
10333
9746
|
\x00magic-context-prompt-surface:${preset}`;
|
|
10334
9747
|
}
|
|
10335
9748
|
function systemPromptFingerprint(systemContent, preset = "full") {
|
|
10336
|
-
return
|
|
9749
|
+
return createHash8("md5").update(promptSurfaceHashMaterial(systemContent, preset)).digest("hex");
|
|
10337
9750
|
}
|
|
10338
9751
|
var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
|
|
10339
9752
|
function resolveUserConfigDirectory(options) {
|
|
10340
9753
|
if (options.userConfigDirectory)
|
|
10341
|
-
return
|
|
9754
|
+
return resolve2(options.userConfigDirectory);
|
|
10342
9755
|
const sharedBase = cortexKitUserConfigBasePath();
|
|
10343
9756
|
const shared = detectConfigFile(sharedBase);
|
|
10344
9757
|
if (shared.format !== "none")
|
|
@@ -10365,10 +9778,10 @@ function createPromptSurfaceRuntime(options) {
|
|
|
10365
9778
|
const readGuidanceOverride = (configuredPath) => {
|
|
10366
9779
|
if (!configuredPath)
|
|
10367
9780
|
return;
|
|
10368
|
-
const path = isAbsolute3(configuredPath) ? configuredPath :
|
|
9781
|
+
const path = isAbsolute3(configuredPath) ? configuredPath : resolve2(userConfigDirectory, configuredPath);
|
|
10369
9782
|
let content;
|
|
10370
9783
|
try {
|
|
10371
|
-
if (!
|
|
9784
|
+
if (!statSync5(path).isFile()) {
|
|
10372
9785
|
warnOnce(`guidance-not-file:${path}`, `prompt_surface.guidance_override_path (${path}) is not a file; using built-in guidance.`);
|
|
10373
9786
|
return;
|
|
10374
9787
|
}
|
|
@@ -11019,7 +10432,7 @@ function compareMemorySelectionPriority(left, right) {
|
|
|
11019
10432
|
}
|
|
11020
10433
|
|
|
11021
10434
|
// src/features/magic-context/mural/render-trigger.ts
|
|
11022
|
-
import { createHash as
|
|
10435
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
11023
10436
|
|
|
11024
10437
|
// src/features/magic-context/mural/mural-selection.ts
|
|
11025
10438
|
var DEFAULT_MURAL_MEMORY_BUDGET = 8000;
|
|
@@ -11723,7 +11136,7 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
11723
11136
|
return { ...cached.result };
|
|
11724
11137
|
}
|
|
11725
11138
|
const plan = planMuralRender(entries);
|
|
11726
|
-
const textHash =
|
|
11139
|
+
const textHash = createHash9("sha256").update(plan.layout.text).digest("hex");
|
|
11727
11140
|
if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
|
|
11728
11141
|
return rememberRender(db, projectIdentity, key, existing.image, {
|
|
11729
11142
|
hasMural: true,
|
|
@@ -11912,14 +11325,14 @@ function parseUserMemoryRow(row) {
|
|
|
11912
11325
|
}
|
|
11913
11326
|
|
|
11914
11327
|
// src/features/magic-context/compaction-marker.ts
|
|
11915
|
-
import { createHash as
|
|
11916
|
-
import { existsSync as existsSync6, statSync as
|
|
11328
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
11329
|
+
import { existsSync as existsSync6, statSync as statSync6 } from "node:fs";
|
|
11917
11330
|
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
11918
11331
|
var ID_PREFIX_HEX_LENGTH = 12;
|
|
11919
11332
|
var ID_SUFFIX_LENGTH = 14;
|
|
11920
11333
|
var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
|
|
11921
11334
|
function deterministicBase62(seed, length) {
|
|
11922
|
-
let value = BigInt(`0x${
|
|
11335
|
+
let value = BigInt(`0x${createHash10("sha256").update(seed).digest("hex")}`);
|
|
11923
11336
|
const chars = Array(length);
|
|
11924
11337
|
for (let index = length - 1;index >= 0; index -= 1) {
|
|
11925
11338
|
chars[index] = BASE62_CHARS[Number(value % 62n)];
|
|
@@ -11985,7 +11398,7 @@ function runMarkerWriteTransaction(db, site, operation) {
|
|
|
11985
11398
|
function markerWalPages(db) {
|
|
11986
11399
|
try {
|
|
11987
11400
|
const row = db.prepare("PRAGMA page_size").get();
|
|
11988
|
-
const bytes =
|
|
11401
|
+
const bytes = statSync6(`${getOpenCodeDbPath()}-wal`).size;
|
|
11989
11402
|
return Math.max(0, Math.floor((bytes - 32) / (row.page_size + 24)));
|
|
11990
11403
|
} catch {
|
|
11991
11404
|
return null;
|
|
@@ -13467,7 +12880,16 @@ function selectHiddenMessagesAtCompactionSeam(messagesBeforeTrim, skippedVisible
|
|
|
13467
12880
|
}
|
|
13468
12881
|
return markerBoundaryIndex < 0 ? [] : trimmed.slice(markerBoundaryIndex + 1);
|
|
13469
12882
|
}
|
|
13470
|
-
function
|
|
12883
|
+
function cutCoveredPrefix(messages, count, coveredInstructions) {
|
|
12884
|
+
const removed = messages.splice(0, count);
|
|
12885
|
+
for (const message of removed) {
|
|
12886
|
+
if (!isHostRenderedSystemMessage(message))
|
|
12887
|
+
continue;
|
|
12888
|
+
markCoveredInstructionRow(message.info);
|
|
12889
|
+
coveredInstructions.push(message);
|
|
12890
|
+
}
|
|
12891
|
+
}
|
|
12892
|
+
function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness) {
|
|
13471
12893
|
const cached = injectionCache.get(sessionId);
|
|
13472
12894
|
if (cached && cached.db !== db) {
|
|
13473
12895
|
clearInjectionCache(sessionId);
|
|
@@ -13484,8 +12906,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
13484
12906
|
if (prepared.compartmentEndMessageId.length > 0) {
|
|
13485
12907
|
const cutoffIndex = findBoundaryIndex(sessionId, messages, prepared.compartmentEndMessageId);
|
|
13486
12908
|
if (cutoffIndex >= 0) {
|
|
13487
|
-
|
|
13488
|
-
messages.splice(0, messages.length, ...remaining);
|
|
12909
|
+
cutCoveredPrefix(messages, cutoffIndex + (isPartialCompartmentEnd(db, sessionId, prepared.compartmentEndMessageId) ? 0 : 1), coveredInstructions);
|
|
13489
12910
|
} else {
|
|
13490
12911
|
sessionLog2(sessionId, `compartment injection: cached boundary ${prepared.compartmentEndMessageId} not in messages (already trimmed), reusing cache`);
|
|
13491
12912
|
}
|
|
@@ -13607,8 +13028,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
13607
13028
|
if (cutoffIndex >= 0) {
|
|
13608
13029
|
clearDegradedRebuild(sessionId);
|
|
13609
13030
|
skippedVisibleMessages = cutoffIndex + (isPartialCompartmentEnd(db, sessionId, trimEndMessageId) ? 0 : 1);
|
|
13610
|
-
|
|
13611
|
-
messages.splice(0, messages.length, ...remaining);
|
|
13031
|
+
cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
|
|
13612
13032
|
resultEndMessageId = trimEndMessageId;
|
|
13613
13033
|
} else {
|
|
13614
13034
|
const degradedCount = noteDegradedRebuild(sessionId);
|
|
@@ -13628,8 +13048,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, pr
|
|
|
13628
13048
|
const reAnchorCutoff = findBoundaryIndex(sessionId, messages, reAnchorCompartment.endMessageId);
|
|
13629
13049
|
if (reAnchorCutoff >= 0) {
|
|
13630
13050
|
skippedVisibleMessages = reAnchorCutoff + (isPartialCompartmentEnd(db, sessionId, reAnchorCompartment.endMessageId) ? 0 : 1);
|
|
13631
|
-
|
|
13632
|
-
messages.splice(0, messages.length, ...remaining);
|
|
13051
|
+
cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
|
|
13633
13052
|
resultEndMessage = reAnchorCompartment.endMessage;
|
|
13634
13053
|
resultEndMessageId = reAnchorCompartment.endMessageId;
|
|
13635
13054
|
reAnchored = true;
|
|
@@ -17932,6 +17351,7 @@ async function runHistorianPrompt(args) {
|
|
|
17932
17351
|
let handle = null;
|
|
17933
17352
|
let completion;
|
|
17934
17353
|
const executor = resolveHiddenCompletionExecutor(args.hiddenCompletionExecutor, client, db, sessionDirectory, "historian");
|
|
17354
|
+
const cacheTail = args.cacheTail ?? (executor.capabilities.harness === "opencode2" ? "skip" : undefined);
|
|
17935
17355
|
let promptSettled = false;
|
|
17936
17356
|
let hadUnsettledPrompt = false;
|
|
17937
17357
|
const startedAt = Date.now();
|
|
@@ -18013,6 +17433,7 @@ async function runHistorianPrompt(args) {
|
|
|
18013
17433
|
try {
|
|
18014
17434
|
await promptSyncWithModelSuggestionRetry(client, {
|
|
18015
17435
|
path: { id: agentSessionId },
|
|
17436
|
+
...cacheTail !== undefined ? { cacheTail: retryIndex > 0 ? "write" : cacheTail } : {},
|
|
18016
17437
|
query: { directory: sessionDirectory },
|
|
18017
17438
|
body: {
|
|
18018
17439
|
agent: agentId,
|
|
@@ -19380,6 +18801,31 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
19380
18801
|
return saved;
|
|
19381
18802
|
}
|
|
19382
18803
|
|
|
18804
|
+
// src/hooks/magic-context/file-token-coverage.ts
|
|
18805
|
+
function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
|
|
18806
|
+
const filesByMessage = new Map;
|
|
18807
|
+
for (const message of messages) {
|
|
18808
|
+
const count = message.parts.filter(isFilePart).length;
|
|
18809
|
+
if (count > 0 && totals.has(message.id))
|
|
18810
|
+
filesByMessage.set(message.id, count);
|
|
18811
|
+
}
|
|
18812
|
+
if (filesByMessage.size === 0)
|
|
18813
|
+
return totals;
|
|
18814
|
+
const rows = db.prepare(`
|
|
18815
|
+
SELECT o.value AS owner, COUNT(t.id) AS count
|
|
18816
|
+
FROM json_each(?) o LEFT JOIN tags t
|
|
18817
|
+
ON t.session_id = ? AND t.type = 'file'
|
|
18818
|
+
AND t.message_id >= o.value || ':file'
|
|
18819
|
+
AND t.message_id < o.value || ':file;'
|
|
18820
|
+
GROUP BY o.value
|
|
18821
|
+
`).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
|
|
18822
|
+
for (const row of rows) {
|
|
18823
|
+
if (row.count < (filesByMessage.get(row.owner) ?? 0))
|
|
18824
|
+
totals.delete(row.owner);
|
|
18825
|
+
}
|
|
18826
|
+
return totals;
|
|
18827
|
+
}
|
|
18828
|
+
|
|
19383
18829
|
// src/hooks/magic-context/protected-tail-boundary.ts
|
|
19384
18830
|
function describeBoundaryDiagnostics(snapshot) {
|
|
19385
18831
|
return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
|
|
@@ -19605,7 +19051,7 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
19605
19051
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
19606
19052
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
19607
19053
|
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
19608
|
-
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
|
|
19054
|
+
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
|
|
19609
19055
|
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
19610
19056
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
19611
19057
|
cacheNamespace: ctx.cacheNamespace,
|
|
@@ -19848,9 +19294,10 @@ function resolveBoundaryContext(args) {
|
|
|
19848
19294
|
migrationFloorActive = seedResult.seeded;
|
|
19849
19295
|
}
|
|
19850
19296
|
const calibration = sessionDecisionCalibration(args.db, args.sessionId);
|
|
19851
|
-
const storedTokenTotalsForMessages = (messageIds) => {
|
|
19297
|
+
const storedTokenTotalsForMessages = (messageIds, messages = []) => {
|
|
19852
19298
|
try {
|
|
19853
|
-
|
|
19299
|
+
const totals = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds).totals;
|
|
19300
|
+
return omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, totals);
|
|
19854
19301
|
} catch (error) {
|
|
19855
19302
|
sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
|
|
19856
19303
|
return;
|
|
@@ -19885,7 +19332,7 @@ function resolveWrapupProtectedTailBoundary(args) {
|
|
|
19885
19332
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
19886
19333
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
19887
19334
|
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
19888
|
-
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
|
|
19335
|
+
const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
|
|
19889
19336
|
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
19890
19337
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
19891
19338
|
cacheNamespace: ctx.cacheNamespace,
|
|
@@ -21931,4 +21378,4 @@ async function executeContextRecomp(deps, options = {}) {
|
|
|
21931
21378
|
return (await executeContextRecompWithResult(deps, options)).message;
|
|
21932
21379
|
}
|
|
21933
21380
|
|
|
21934
|
-
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork,
|
|
21381
|
+
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, 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, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, registerLkgPersistence, 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, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, 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, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, prepareCompactionMarkerCandidates, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, 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, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|