@cortexkit/opencode-magic-context 0.44.0 → 0.44.2
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/README.md +6 -0
- package/dist/agents/dreamer.d.ts +4 -6
- package/dist/agents/dreamer.d.ts.map +1 -1
- package/dist/agents/magic-context-prompt.d.ts +2 -0
- package/dist/agents/magic-context-prompt.d.ts.map +1 -1
- package/dist/{announcement-1a8bvswd.js → announcement-n8hs7kjw.js} +2 -2
- package/dist/config/live-child-output-cap.d.ts +18 -0
- package/dist/config/live-child-output-cap.d.ts.map +1 -0
- package/dist/config/schema/magic-context.d.ts +64 -11
- package/dist/config/schema/magic-context.d.ts.map +1 -1
- package/dist/{conflict-warning-hook-48f7np9d.js → conflict-warning-hook-1msyvb51.js} +6 -6
- package/dist/{derive-budgets-8kgevxmx.js → derive-budgets-gd2270s0.js} +3 -3
- package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
- package/dist/features/magic-context/compartment-chunk-embedding.d.ts +11 -0
- package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
- package/dist/features/magic-context/compartment-storage.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/docs-proposals.d.ts +2 -0
- package/dist/features/magic-context/dreamer/docs-proposals.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/manual-summary.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts +1 -1
- package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/map-memories.d.ts +5 -0
- package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/open-opencode-db.d.ts +2 -0
- package/dist/features/magic-context/dreamer/open-opencode-db.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/primer-seed.d.ts +11 -5
- package/dist/features/magic-context/dreamer/primer-seed.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/refresh-primers.d.ts +7 -2
- package/dist/features/magic-context/dreamer/refresh-primers.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts +2 -2
- package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts +8 -1
- package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-config.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-executor.d.ts +5 -0
- package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-prompts.d.ts +18 -2
- package/dist/features/magic-context/dreamer/task-prompts.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-registry.d.ts +12 -0
- package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts +3 -1
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/token-budget.d.ts +33 -0
- package/dist/features/magic-context/dreamer/token-budget.d.ts.map +1 -0
- package/dist/features/magic-context/dreamer/verify-diff.d.ts +15 -0
- package/dist/features/magic-context/dreamer/verify-diff.d.ts.map +1 -0
- package/dist/features/magic-context/dreamer/verify-gate.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/verify-prompt.d.ts +5 -2
- package/dist/features/magic-context/dreamer/verify-prompt.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/verify-read-cap.d.ts +4 -0
- package/dist/features/magic-context/dreamer/verify-read-cap.d.ts.map +1 -0
- package/dist/features/magic-context/dreamer/verify.d.ts +5 -0
- package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
- package/dist/features/magic-context/git-commits/git-log-reader.d.ts.map +1 -1
- package/dist/features/magic-context/memory/project-identity-cache.d.ts +6 -0
- package/dist/features/magic-context/memory/project-identity-cache.d.ts.map +1 -0
- package/dist/features/magic-context/memory/project-identity.d.ts +15 -22
- package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
- package/dist/features/magic-context/memory/storage-memory-fts.d.ts +1 -0
- package/dist/features/magic-context/memory/storage-memory-fts.d.ts.map +1 -1
- package/dist/features/magic-context/memory/verification-paths.d.ts +1 -0
- package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
- package/dist/features/magic-context/mural/mural-font.generated.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts +5 -0
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/session-activity.d.ts +10 -0
- package/dist/features/magic-context/session-activity.d.ts.map +1 -0
- package/dist/features/magic-context/session-cache-ttl.d.ts +10 -0
- package/dist/features/magic-context/session-cache-ttl.d.ts.map +1 -0
- package/dist/features/magic-context/session-project-backfill.d.ts +4 -1
- package/dist/features/magic-context/session-project-backfill.d.ts.map +1 -1
- package/dist/features/magic-context/smart-notes/compiler.d.ts +5 -0
- package/dist/features/magic-context/smart-notes/compiler.d.ts.map +1 -1
- package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts +1 -0
- package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts.map +1 -1
- package/dist/features/magic-context/smart-notes/storage.d.ts +1 -1
- package/dist/features/magic-context/smart-notes/storage.d.ts.map +1 -1
- package/dist/features/magic-context/smart-notes/types.d.ts +2 -0
- package/dist/features/magic-context/smart-notes/types.d.ts.map +1 -1
- package/dist/features/magic-context/storage-db.d.ts +2 -1
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/storage-identity-merge.d.ts +4 -1
- package/dist/features/magic-context/storage-identity-merge.d.ts.map +1 -1
- package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
- package/dist/features/magic-context/v22-deferred-backfill.d.ts.map +1 -1
- package/dist/hooks/auto-update-checker/checker.d.ts.map +1 -1
- package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner.d.ts +1 -0
- package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/dropped-input-guard.d.ts.map +1 -1
- package/dist/hooks/magic-context/embed-session-state.d.ts +3 -0
- package/dist/hooks/magic-context/embed-session-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts +1 -0
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-payloads.d.ts +1 -0
- package/dist/hooks/magic-context/event-payloads.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
- package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts +6 -4
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
- package/dist/hooks/magic-context/opencode-v1-store-fixture.d.ts +12 -0
- package/dist/hooks/magic-context/opencode-v1-store-fixture.d.ts.map +1 -0
- package/dist/hooks/magic-context/read-session-chunk.d.ts +16 -0
- package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-db.d.ts +5 -1
- package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-raw.d.ts +10 -0
- package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/storage-busy-refusal.d.ts +7 -0
- package/dist/hooks/magic-context/storage-busy-refusal.d.ts.map +1 -0
- package/dist/hooks/magic-context/strip-content.d.ts +1 -0
- package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.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-5f4qsnaq.js → index-18tjha8g.js} +2 -2
- package/dist/{index-4b30nf6z.js → index-32b096cc.js} +1 -1
- package/dist/{index-tjq5jztd.js → index-3bygzk2d.js} +1 -1
- package/dist/{index-cj5qe2nw.js → index-3x9caerx.js} +8 -6
- package/dist/index-40s1xz22.js +125 -0
- package/dist/{index-pye48m79.js → index-egkfvhms.js} +130 -42
- package/dist/{index-2zf5fv89.js → index-esxfcz5z.js} +171 -12
- package/dist/index-gtzcmv90.js +7260 -0
- package/dist/{index-6w9p73jz.js → index-jqcbs2k1.js} +10 -0
- package/dist/{index-v6wsttqt.js → index-kr5qehbd.js} +1 -1
- package/dist/{index-dx0xnd4q.js → index-kwe03yde.js} +1 -1
- package/dist/{index-c906f3ff.js → index-r9vkp4n9.js} +4 -4
- package/dist/{index-6z9g64js.js → index-s70wtd8k.js} +4 -1
- package/dist/{index-01ft0h3p.js → index-stb5fg12.js} +2 -2
- package/dist/{index-rdey8znw.js → index-ttdn47aq.js} +35260 -32540
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15123 -23504
- package/dist/{message-time-backfill-rm9wmcem.js → message-time-backfill-q374fxc5.js} +3 -3
- package/dist/plugin/dream-timer.d.ts.map +1 -1
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/messages-transform.d.ts +10 -9
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts +1 -0
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/{read-session-chunk-ktz5zt70.js → read-session-chunk-wmvgnd24.js} +6 -4
- package/dist/{recomp-orchestrator-ahekzt0s.js → recomp-orchestrator-rk40ff15.js} +10 -9
- package/dist/{safe-notification-target-6w0esgd6.js → safe-notification-target-50gm9c58.js} +3 -3
- package/dist/{send-session-notification-w7xbnrsm.js → send-session-notification-6xsrcxnp.js} +5 -5
- package/dist/shared/cache-ttl-display.d.ts +3 -1
- package/dist/shared/cache-ttl-display.d.ts.map +1 -1
- package/dist/shared/harness.d.ts +11 -0
- package/dist/shared/harness.d.ts.map +1 -1
- package/dist/shared/model-cache-ttl.d.ts +9 -0
- package/dist/shared/model-cache-ttl.d.ts.map +1 -0
- package/dist/shared/model-suggestion-retry.d.ts +1 -1
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- package/dist/shared/prompt-async-transport.d.ts +7 -7
- package/dist/shared/prompt-async-transport.d.ts.map +1 -1
- package/dist/shared/rpc-server.d.ts.map +1 -1
- package/dist/shared/rpc-types.d.ts +1 -1
- package/dist/shared/rpc-types.d.ts.map +1 -1
- package/dist/shared/rpc-utils.d.ts +21 -0
- package/dist/shared/rpc-utils.d.ts.map +1 -1
- package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -1
- package/dist/shared/sqlite.d.ts +12 -0
- package/dist/shared/sqlite.d.ts.map +1 -1
- package/dist/shared/status-view.d.ts +1 -1
- package/dist/shared/status-view.d.ts.map +1 -1
- package/dist/shared/subagent-runner.d.ts +3 -1
- package/dist/shared/subagent-runner.d.ts.map +1 -1
- package/dist/shared/user-facing-codes.d.ts +5 -0
- package/dist/shared/user-facing-codes.d.ts.map +1 -1
- package/dist/{task-config-mgf5nsh3.js → task-config-2bm68628.js} +1 -1
- package/dist/tools/ctx-expand/render.d.ts.map +1 -1
- package/dist/transform-postprocess-phase-t7xgdhdf.js +36 -0
- package/dist/v2/hidden-completion.d.ts +2 -0
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/hidden-child.d.ts +1 -0
- package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
- package/dist/v2/hooks/lkg-system.d.ts +11 -0
- package/dist/v2/hooks/lkg-system.d.ts.map +1 -0
- package/dist/v2/hooks/session-project-backfill.d.ts +1 -1
- package/dist/v2/hooks/session-project-backfill.d.ts.map +1 -1
- package/dist/v2/hooks/storage-gate.d.ts +11 -5
- package/dist/v2/hooks/storage-gate.d.ts.map +1 -1
- package/dist/v2/host-service.d.ts +2 -1
- package/dist/v2/host-service.d.ts.map +1 -1
- package/dist/v2/server.js +95347 -93236
- package/dist/v2/store-reader.d.ts +2 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/wrapup-orchestrator-h8tr10c6.js +19 -0
- package/package.json +1 -1
- package/src/agents/dreamer.ts +4 -6
- package/src/agents/hidden-agent-registrations.ts +3 -3
- package/src/agents/magic-context-prompt.test.ts +125 -0
- package/src/agents/magic-context-prompt.ts +12 -7
- package/src/agents/permissions.test.ts +3 -4
- package/src/config/latch-permanence-guard.test.ts +9 -0
- package/src/config/live-child-output-cap.test.ts +101 -0
- package/src/config/live-child-output-cap.ts +74 -0
- package/src/config/live-run-config.test.ts +24 -11
- package/src/config/schema/magic-context.test.ts +16 -1
- package/src/config/schema/magic-context.ts +27 -10
- package/src/features/magic-context/dreamer/task-registry.ts +13 -0
- package/src/shared/cache-ttl-display.ts +14 -20
- package/src/shared/harness.ts +14 -0
- package/src/shared/logger.test.ts +1 -0
- package/src/shared/model-cache-ttl.test.ts +40 -0
- package/src/shared/model-cache-ttl.ts +58 -0
- package/src/shared/model-suggestion-retry.ts +9 -2
- package/src/shared/prompt-async-transport.test.ts +254 -1
- package/src/shared/prompt-async-transport.ts +153 -44
- package/src/shared/prompt-surface-a1-golden.md +13 -13
- package/src/shared/rpc-async-probes.test.ts +230 -0
- package/src/shared/rpc-server.ts +6 -4
- package/src/shared/rpc-types.ts +1 -1
- package/src/shared/rpc-utils.test.ts +27 -1
- package/src/shared/rpc-utils.ts +161 -9
- package/src/shared/sqlite-acquisition-fence.test.ts +132 -0
- package/src/shared/sqlite-acquisition-routing.test.ts +94 -0
- package/src/shared/sqlite-pass-scope.test.ts +182 -0
- package/src/shared/sqlite-transaction-mode-guard.test.ts +42 -10
- package/src/shared/sqlite-write-locker-test-support.ts +1 -0
- package/src/shared/sqlite.ts +142 -56
- package/src/shared/status-view.ts +1 -1
- package/src/shared/storage-busy.test.ts +95 -0
- package/src/shared/subagent-runner.ts +4 -0
- package/src/shared/user-facing-codes.ts +6 -0
- package/src/shared/windows-hidden-spawns.test.ts +132 -0
- package/src/shared/write-transaction-attribution.test.ts +1 -0
- package/dist/wrapup-orchestrator-9srk0kjf.js +0 -18
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
sessionLog
|
|
3
|
-
} from "./index-
|
|
3
|
+
} from "./index-3bygzk2d.js";
|
|
4
4
|
import {
|
|
5
5
|
COMPARTMENT_LEASE_RENEWAL_MS,
|
|
6
6
|
acquireCompartmentLease,
|
|
@@ -20,16 +20,18 @@ import {
|
|
|
20
20
|
runCompartmentAgent,
|
|
21
21
|
getActiveCompartmentRun,
|
|
22
22
|
markActiveCompartmentRunPublished,
|
|
23
|
-
registerActiveCompartmentRun
|
|
24
|
-
|
|
25
|
-
setRecompTerminal2
|
|
26
|
-
} from "./index-rdey8znw.js";
|
|
23
|
+
registerActiveCompartmentRun
|
|
24
|
+
} from "./index-ttdn47aq.js";
|
|
27
25
|
import {
|
|
28
26
|
pushNotification2
|
|
29
27
|
} from "./index-jdxxq8cz.js";
|
|
30
28
|
import {
|
|
31
29
|
sendStatusNotification2
|
|
32
|
-
} from "./index-
|
|
30
|
+
} from "./index-r9vkp4n9.js";
|
|
31
|
+
import {
|
|
32
|
+
setRecompStarting2,
|
|
33
|
+
setRecompTerminal2
|
|
34
|
+
} from "./index-40s1xz22.js";
|
|
33
35
|
|
|
34
36
|
// src/hooks/magic-context/wrapup-orchestrator.ts
|
|
35
37
|
import * as crypto from "node:crypto";
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import {
|
|
2
|
+
renderUserFacingFailure,
|
|
3
|
+
userFacingFailureCode,
|
|
4
|
+
clearEmergencyRecovery,
|
|
5
|
+
dropSlot,
|
|
6
|
+
executeContextRecomp
|
|
7
|
+
} from "./index-ttdn47aq.js";
|
|
8
|
+
import {
|
|
9
|
+
sessionLog
|
|
10
|
+
} from "./index-3bygzk2d.js";
|
|
11
|
+
|
|
12
|
+
// src/hooks/magic-context/recomp-orchestrator.ts
|
|
13
|
+
function resolveLiveModelKey(liveSessionState, sessionId) {
|
|
14
|
+
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
15
|
+
return model ? `${model.providerID}/${model.modelID}` : undefined;
|
|
16
|
+
}
|
|
17
|
+
function isRecompFailure(message) {
|
|
18
|
+
return /—\s*(Failed|Skipped)/.test(message);
|
|
19
|
+
}
|
|
20
|
+
function isRecompSkip(message) {
|
|
21
|
+
return /—\s*Skipped|already mutating compartment state|already running/i.test(message);
|
|
22
|
+
}
|
|
23
|
+
function extractRecompReason(raw) {
|
|
24
|
+
const meaningful = raw.split(`
|
|
25
|
+
`).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
|
|
26
|
+
return meaningful.join(" ").trim() || "Recomp finished";
|
|
27
|
+
}
|
|
28
|
+
var RECOMP_DONE_GRACE_MS = 30000;
|
|
29
|
+
function setRecompStarting2(liveSessionState, sessionId, note, kind = "recomp") {
|
|
30
|
+
dropSlot(sessionId, "recomp-start");
|
|
31
|
+
liveSessionState.recompProgressBySession.set(sessionId, {
|
|
32
|
+
sessionId,
|
|
33
|
+
kind,
|
|
34
|
+
phase: "recomp",
|
|
35
|
+
processedMessages: 0,
|
|
36
|
+
totalMessages: 0,
|
|
37
|
+
passCount: 0,
|
|
38
|
+
compartmentsCreated: 0,
|
|
39
|
+
startedAt: Date.now(),
|
|
40
|
+
updatedAt: Date.now(),
|
|
41
|
+
note
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function setRecompTerminal2(liveSessionState, sessionId, phase, message) {
|
|
45
|
+
const existing = liveSessionState.recompProgressBySession.get(sessionId);
|
|
46
|
+
liveSessionState.recompProgressBySession.set(sessionId, {
|
|
47
|
+
sessionId,
|
|
48
|
+
kind: existing?.kind ?? "recomp",
|
|
49
|
+
phase,
|
|
50
|
+
processedMessages: existing?.processedMessages ?? 0,
|
|
51
|
+
totalMessages: existing?.totalMessages ?? 0,
|
|
52
|
+
passCount: existing?.passCount ?? 0,
|
|
53
|
+
compartmentsCreated: existing?.compartmentsCreated ?? 0,
|
|
54
|
+
startedAt: existing?.startedAt ?? Date.now(),
|
|
55
|
+
updatedAt: Date.now(),
|
|
56
|
+
message
|
|
57
|
+
});
|
|
58
|
+
if (phase === "done" || phase === "skipped") {
|
|
59
|
+
const t = setTimeout(() => {
|
|
60
|
+
const cur = liveSessionState.recompProgressBySession.get(sessionId);
|
|
61
|
+
if (cur?.phase === phase)
|
|
62
|
+
liveSessionState.recompProgressBySession.delete(sessionId);
|
|
63
|
+
}, RECOMP_DONE_GRACE_MS);
|
|
64
|
+
t.unref?.();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function buildRecompDeps(ctx, sessionId) {
|
|
68
|
+
return {
|
|
69
|
+
client: ctx.client,
|
|
70
|
+
hiddenCompletionExecutor: ctx.hiddenCompletionExecutor,
|
|
71
|
+
db: ctx.db,
|
|
72
|
+
sessionId,
|
|
73
|
+
historianChunkTokens: ctx.historianChunkTokens,
|
|
74
|
+
historianTimeoutMs: ctx.historianTimeoutMs,
|
|
75
|
+
directory: ctx.directory,
|
|
76
|
+
memoryEnabled: ctx.memoryEnabled,
|
|
77
|
+
autoPromote: ctx.autoPromote,
|
|
78
|
+
model: ctx.historianModel,
|
|
79
|
+
historianContextLimit: ctx.historianContextLimit,
|
|
80
|
+
historianMaxOutputTokens: ctx.historianMaxOutputTokens,
|
|
81
|
+
fallbackModels: ctx.fallbackModels,
|
|
82
|
+
language: ctx.language,
|
|
83
|
+
fallbackModelId: ctx.fallbackModelId ?? resolveLiveModelKey(ctx.liveSessionState, sessionId),
|
|
84
|
+
historianTwoPass: ctx.historianTwoPass,
|
|
85
|
+
ensureProjectRegistered: ctx.ensureProjectRegistered,
|
|
86
|
+
getNotificationParams: () => ctx.getNotificationParams(sessionId),
|
|
87
|
+
onCompartmentStatePublished: (sid) => {
|
|
88
|
+
ctx.liveSessionState.historyRefreshSessions.add(sid);
|
|
89
|
+
ctx.liveSessionState.pendingMaterializationSessions.add(sid);
|
|
90
|
+
},
|
|
91
|
+
onDeferredMarkerPending: (sid) => {
|
|
92
|
+
ctx.liveSessionState.deferredHistoryRefreshSessions.add(sid);
|
|
93
|
+
},
|
|
94
|
+
onRecompProgress: (p) => {
|
|
95
|
+
const prevKind = ctx.liveSessionState.recompProgressBySession.get(sessionId)?.kind ?? "recomp";
|
|
96
|
+
ctx.liveSessionState.recompProgressBySession.set(sessionId, {
|
|
97
|
+
...p,
|
|
98
|
+
kind: p.kind ?? prevKind
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
async function runManagedRecomp2(ctx, sessionId, options) {
|
|
104
|
+
setRecompStarting2(ctx.liveSessionState, sessionId, "Starting recomp…", "recomp");
|
|
105
|
+
try {
|
|
106
|
+
const message = await executeContextRecomp(buildRecompDeps(ctx, sessionId), options);
|
|
107
|
+
const terminalPhase = isRecompSkip(message) ? "skipped" : isRecompFailure(message) ? "failed" : "done";
|
|
108
|
+
if (terminalPhase === "done") {
|
|
109
|
+
try {
|
|
110
|
+
clearEmergencyRecovery(ctx.db, sessionId);
|
|
111
|
+
} catch {}
|
|
112
|
+
}
|
|
113
|
+
setRecompTerminal2(ctx.liveSessionState, sessionId, terminalPhase, extractRecompReason(message));
|
|
114
|
+
return message;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const failure = renderUserFacingFailure("recomp_unavailable");
|
|
117
|
+
sessionLog(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")}`, error);
|
|
118
|
+
setRecompTerminal2(ctx.liveSessionState, sessionId, "failed", failure);
|
|
119
|
+
return `## Magic Recomp — Failed
|
|
120
|
+
|
|
121
|
+
${failure}`;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export { setRecompStarting2, setRecompTerminal2, runManagedRecomp2 };
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
harnessOwnsOpenCodeStore
|
|
3
|
+
} from "./index-s70wtd8k.js";
|
|
1
4
|
import {
|
|
2
5
|
log
|
|
3
|
-
} from "./index-
|
|
6
|
+
} from "./index-3bygzk2d.js";
|
|
4
7
|
|
|
5
8
|
// src/shared/opencode-db-path.ts
|
|
6
9
|
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
@@ -204,6 +207,7 @@ function closeQuietly(db) {
|
|
|
204
207
|
}
|
|
205
208
|
|
|
206
209
|
// src/shared/sqlite.ts
|
|
210
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
207
211
|
import { statSync as statSync2 } from "node:fs";
|
|
208
212
|
var reportSlowPrivilegedWrite;
|
|
209
213
|
function registerSlowWriteReporter(reporter) {
|
|
@@ -259,6 +263,62 @@ var sqliteModule = await loadSqliteModule(detectedRuntime);
|
|
|
259
263
|
var DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
|
|
260
264
|
var trackedSqliteConnections = new Map;
|
|
261
265
|
var nextSqliteConnectionSequence = 1;
|
|
266
|
+
function installTransactionRouting(db, readonly) {
|
|
267
|
+
const nativeExec = db.exec.bind(db);
|
|
268
|
+
Object.defineProperty(db, "exec", {
|
|
269
|
+
configurable: true,
|
|
270
|
+
writable: true,
|
|
271
|
+
value: (sql) => {
|
|
272
|
+
if (/^\s*BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)(?:\s+TRANSACTION)?\s*;?\s*$/i.test(sql)) {
|
|
273
|
+
retryAcquisition(() => nativeExec(sql), sql.trim());
|
|
274
|
+
return db;
|
|
275
|
+
}
|
|
276
|
+
return nativeExec(sql);
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
Object.defineProperty(db, "transaction", {
|
|
280
|
+
configurable: true,
|
|
281
|
+
writable: true,
|
|
282
|
+
value: (fn) => {
|
|
283
|
+
const make = (mode) => function(...args) {
|
|
284
|
+
const nested = isInTransaction(db);
|
|
285
|
+
const savepoint = "mc_tx_sp";
|
|
286
|
+
db.exec(nested ? `SAVEPOINT ${savepoint}` : `BEGIN ${mode}`);
|
|
287
|
+
try {
|
|
288
|
+
const result = fn.apply(this, args);
|
|
289
|
+
db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
|
|
290
|
+
return result;
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (isInTransaction(db)) {
|
|
293
|
+
if (nested) {
|
|
294
|
+
db.exec(`ROLLBACK TO ${savepoint}`);
|
|
295
|
+
db.exec(`RELEASE ${savepoint}`);
|
|
296
|
+
} else
|
|
297
|
+
db.exec("ROLLBACK");
|
|
298
|
+
}
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const defaultTransaction = make(readonly ? "DEFERRED" : "IMMEDIATE");
|
|
303
|
+
const variants = {
|
|
304
|
+
default: defaultTransaction,
|
|
305
|
+
deferred: make("DEFERRED"),
|
|
306
|
+
immediate: make("IMMEDIATE"),
|
|
307
|
+
exclusive: make("EXCLUSIVE"),
|
|
308
|
+
database: db
|
|
309
|
+
};
|
|
310
|
+
for (const transaction of [
|
|
311
|
+
variants.default,
|
|
312
|
+
variants.deferred,
|
|
313
|
+
variants.immediate,
|
|
314
|
+
variants.exclusive
|
|
315
|
+
]) {
|
|
316
|
+
Object.assign(transaction, variants);
|
|
317
|
+
}
|
|
318
|
+
return defaultTransaction;
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
}
|
|
262
322
|
function trackSqliteConnection(db, filename, options) {
|
|
263
323
|
const originalClose = db.close.bind(db);
|
|
264
324
|
const sequence = nextSqliteConnectionSequence++;
|
|
@@ -267,6 +327,7 @@ function trackSqliteConnection(db, filename, options) {
|
|
|
267
327
|
filename: typeof filename === "string" ? filename : Buffer.isBuffer(filename) ? "<buffer>" : ":memory:",
|
|
268
328
|
readonly: Boolean(options) && typeof options === "object" && (options.readonly === true || options.readOnly === true)
|
|
269
329
|
};
|
|
330
|
+
installTransactionRouting(db, metadata.readonly);
|
|
270
331
|
Object.defineProperty(db, "close", {
|
|
271
332
|
configurable: true,
|
|
272
333
|
value: (...args) => {
|
|
@@ -290,7 +351,6 @@ var TrackedDatabase = new Proxy(DatabaseImpl, {
|
|
|
290
351
|
}
|
|
291
352
|
});
|
|
292
353
|
function buildNodeSqliteDatabaseClass(DatabaseSync) {
|
|
293
|
-
const SAVEPOINT = "mc_tx_sp";
|
|
294
354
|
|
|
295
355
|
class NodeSqliteDatabase extends DatabaseSync {
|
|
296
356
|
constructor(filename, options) {
|
|
@@ -309,42 +369,6 @@ function buildNodeSqliteDatabaseClass(DatabaseSync) {
|
|
|
309
369
|
}
|
|
310
370
|
return stmt;
|
|
311
371
|
}
|
|
312
|
-
transaction(fn) {
|
|
313
|
-
const self = this;
|
|
314
|
-
const execute = (mode, receiver, args) => {
|
|
315
|
-
const nested = self.isTransaction === true;
|
|
316
|
-
self.exec(nested ? `SAVEPOINT ${SAVEPOINT}` : `BEGIN${mode ? ` ${mode}` : ""}`);
|
|
317
|
-
try {
|
|
318
|
-
const result = fn.apply(receiver, args);
|
|
319
|
-
self.exec(nested ? `RELEASE ${SAVEPOINT}` : "COMMIT");
|
|
320
|
-
return result;
|
|
321
|
-
} catch (error) {
|
|
322
|
-
if (nested) {
|
|
323
|
-
self.exec(`ROLLBACK TO ${SAVEPOINT}`);
|
|
324
|
-
self.exec(`RELEASE ${SAVEPOINT}`);
|
|
325
|
-
} else {
|
|
326
|
-
self.exec("ROLLBACK");
|
|
327
|
-
}
|
|
328
|
-
throw error;
|
|
329
|
-
}
|
|
330
|
-
};
|
|
331
|
-
const wrapped = function(...args) {
|
|
332
|
-
return execute("", this, args);
|
|
333
|
-
};
|
|
334
|
-
wrapped.default = function(...args) {
|
|
335
|
-
return execute("", this, args);
|
|
336
|
-
};
|
|
337
|
-
wrapped.deferred = function(...args) {
|
|
338
|
-
return execute("DEFERRED", this, args);
|
|
339
|
-
};
|
|
340
|
-
wrapped.immediate = function(...args) {
|
|
341
|
-
return execute("IMMEDIATE", this, args);
|
|
342
|
-
};
|
|
343
|
-
wrapped.exclusive = function(...args) {
|
|
344
|
-
return execute("EXCLUSIVE", this, args);
|
|
345
|
-
};
|
|
346
|
-
return wrapped;
|
|
347
|
-
}
|
|
348
372
|
}
|
|
349
373
|
return NodeSqliteDatabase;
|
|
350
374
|
}
|
|
@@ -429,6 +453,63 @@ function getSqliteMemoryStats() {
|
|
|
429
453
|
};
|
|
430
454
|
}
|
|
431
455
|
var privilegeDepth = new WeakMap;
|
|
456
|
+
var transformPassScope = new AsyncLocalStorage;
|
|
457
|
+
function withSqliteTransformPass(operation) {
|
|
458
|
+
const lease = { active: true };
|
|
459
|
+
return transformPassScope.run(lease, () => {
|
|
460
|
+
try {
|
|
461
|
+
const result = operation();
|
|
462
|
+
if (result && typeof result.then === "function") {
|
|
463
|
+
return Promise.resolve(result).finally(() => {
|
|
464
|
+
lease.active = false;
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
lease.active = false;
|
|
468
|
+
return result;
|
|
469
|
+
} catch (error) {
|
|
470
|
+
lease.active = false;
|
|
471
|
+
throw error;
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
function withoutSqliteTransformPass(operation) {
|
|
476
|
+
return transformPassScope.run(undefined, operation);
|
|
477
|
+
}
|
|
478
|
+
function isTransientSqliteError(error) {
|
|
479
|
+
if (!error || typeof error !== "object")
|
|
480
|
+
return false;
|
|
481
|
+
const value = error;
|
|
482
|
+
return typeof value.code === "string" && /^(SQLITE_BUSY|SQLITE_LOCKED)(_|$)/.test(value.code) || typeof value.errcode === "number" && [5, 6].includes(value.errcode & 255);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
class SqliteAcquisitionBusyError extends Error {
|
|
486
|
+
code = "SQLITE_BUSY";
|
|
487
|
+
stage;
|
|
488
|
+
constructor(cause, stage = "BEGIN IMMEDIATE") {
|
|
489
|
+
super("SQLite writer acquisition remained busy after 3 attempts", { cause });
|
|
490
|
+
this.name = "SqliteAcquisitionBusyError";
|
|
491
|
+
this.stage = stage;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function retryAcquisition(acquire, stage) {
|
|
495
|
+
if (!transformPassScope.getStore()?.active) {
|
|
496
|
+
acquire();
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const delays = [500, 1000];
|
|
500
|
+
for (let attempt = 0;; attempt++) {
|
|
501
|
+
try {
|
|
502
|
+
acquire();
|
|
503
|
+
return;
|
|
504
|
+
} catch (error) {
|
|
505
|
+
if (error instanceof SqliteAcquisitionBusyError || !isTransientSqliteError(error))
|
|
506
|
+
throw error;
|
|
507
|
+
if (attempt === delays.length)
|
|
508
|
+
throw new SqliteAcquisitionBusyError(error, stage);
|
|
509
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delays[attempt]);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
432
513
|
function isInTransaction(db) {
|
|
433
514
|
const candidate = db;
|
|
434
515
|
return candidate.inTransaction === true || candidate.isTransaction === true;
|
|
@@ -441,7 +522,7 @@ function withPrivilegedWriter(db, operation) {
|
|
|
441
522
|
if (nested) {
|
|
442
523
|
db.exec(`SAVEPOINT ${savepoint}`);
|
|
443
524
|
} else {
|
|
444
|
-
db.exec("BEGIN IMMEDIATE");
|
|
525
|
+
retryAcquisition(() => db.exec("BEGIN IMMEDIATE"), "BEGIN IMMEDIATE");
|
|
445
526
|
}
|
|
446
527
|
privilegeDepth.set(db, previousDepth + 1);
|
|
447
528
|
try {
|
|
@@ -483,7 +564,7 @@ function withPrivilegedWriter(db, operation) {
|
|
|
483
564
|
|
|
484
565
|
// src/hooks/magic-context/read-session-db.ts
|
|
485
566
|
function openCodeDbExists() {
|
|
486
|
-
return openCodeDbPathExists(resolveOpenCodeDbPath());
|
|
567
|
+
return harnessOwnsOpenCodeStore() && openCodeDbPathExists(resolveOpenCodeDbPath());
|
|
487
568
|
}
|
|
488
569
|
var cachedReadOnlyDb = null;
|
|
489
570
|
function closeCachedReadOnlyDb() {
|
|
@@ -499,6 +580,9 @@ function closeCachedReadOnlyDb() {
|
|
|
499
580
|
}
|
|
500
581
|
}
|
|
501
582
|
function getReadOnlySessionDb() {
|
|
583
|
+
if (!harnessOwnsOpenCodeStore()) {
|
|
584
|
+
throw new Error("OpenCode session database is not readable from a Pi-compatible process; its history lives in Pi sessions");
|
|
585
|
+
}
|
|
502
586
|
const resolution = resolveOpenCodeDbPath();
|
|
503
587
|
const dbPath = resolution.path;
|
|
504
588
|
if (!openCodeDbPathExists(resolution)) {
|
|
@@ -684,6 +768,8 @@ function logProbeFailureOnce(resolution, error) {
|
|
|
684
768
|
}
|
|
685
769
|
function resolvedDbIsAvailable() {
|
|
686
770
|
const resolution = resolveOpenCodeDbPath();
|
|
771
|
+
if (!harnessOwnsOpenCodeStore())
|
|
772
|
+
return { resolution, available: false };
|
|
687
773
|
const available = openCodeDbPathExists(resolution);
|
|
688
774
|
if (available)
|
|
689
775
|
clearOpenCodeDbReadFailure(resolution.path);
|
|
@@ -825,7 +911,7 @@ function hasUnansweredRealUser(db, sessionId) {
|
|
|
825
911
|
}
|
|
826
912
|
function getMessageTimesFromOpenCodeDb(sessionId, messageIds) {
|
|
827
913
|
const result = new Map;
|
|
828
|
-
if (messageIds.length === 0)
|
|
914
|
+
if (messageIds.length === 0 || !harnessOwnsOpenCodeStore())
|
|
829
915
|
return result;
|
|
830
916
|
try {
|
|
831
917
|
withReadOnlySessionDb((db) => {
|
|
@@ -843,6 +929,8 @@ function getMessageTimesFromOpenCodeDb(sessionId, messageIds) {
|
|
|
843
929
|
return result;
|
|
844
930
|
}
|
|
845
931
|
function findLastAssistantModelFromOpenCodeDb(sessionId) {
|
|
932
|
+
if (!harnessOwnsOpenCodeStore())
|
|
933
|
+
return null;
|
|
846
934
|
const resolution = resolveOpenCodeDbPath();
|
|
847
935
|
try {
|
|
848
936
|
if (!openCodeDbPathExists(resolution)) {
|
|
@@ -899,4 +987,4 @@ function findLastAssistantModelFromOpenCodeDb(sessionId) {
|
|
|
899
987
|
}
|
|
900
988
|
}
|
|
901
989
|
|
|
902
|
-
export { resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, openCodeDbPathExists, getOpenCodeDbProbeDescriptions, formatOpenCodeDbMissingBanner, formatOpenCodeDbMissingStatusLine, formatOpenCodeDbReadFailureStatusLine, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, getOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, registerSlowWriteReporter, detectSqliteRuntime, Database, getSqliteMemoryStats, withPrivilegedWriter, closeQuietly, openCodeDbExists, withReadOnlySessionDb, getRawSessionMessageCountFromDb, observeOpenCodeTurnEvent, clearTrackedOpenCodeSession, assistantAwaitingTools, shouldHoldIgnoredNotification, latestPersistedMessageForRecovery, getMessageTimesFromOpenCodeDb, findLastAssistantModelFromOpenCodeDb };
|
|
990
|
+
export { resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, openCodeDbPathExists, getOpenCodeDbProbeDescriptions, formatOpenCodeDbMissingBanner, formatOpenCodeDbMissingStatusLine, formatOpenCodeDbReadFailureStatusLine, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, getOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, registerSlowWriteReporter, detectSqliteRuntime, Database, getSqliteMemoryStats, withSqliteTransformPass, withoutSqliteTransformPass, isTransientSqliteError, SqliteAcquisitionBusyError, withPrivilegedWriter, closeQuietly, openCodeDbExists, withReadOnlySessionDb, getRawSessionMessageCountFromDb, observeOpenCodeTurnEvent, clearTrackedOpenCodeSession, assistantAwaitingTools, shouldHoldIgnoredNotification, latestPersistedMessageForRecovery, getMessageTimesFromOpenCodeDb, findLastAssistantModelFromOpenCodeDb };
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getHarness
|
|
3
|
-
} from "./index-
|
|
3
|
+
} from "./index-s70wtd8k.js";
|
|
4
4
|
import {
|
|
5
5
|
openCodeDbExists,
|
|
6
6
|
withReadOnlySessionDb,
|
|
7
7
|
getRawSessionMessageCountFromDb,
|
|
8
8
|
getMessageTimesFromOpenCodeDb
|
|
9
|
-
} from "./index-
|
|
9
|
+
} from "./index-egkfvhms.js";
|
|
10
10
|
import {
|
|
11
11
|
UNKNOWN_FIT_RATIO,
|
|
12
12
|
resolveDecisionCalibration,
|
|
@@ -3051,11 +3051,23 @@ function readRawSessionMessagesFromDb(db, sessionId) {
|
|
|
3051
3051
|
});
|
|
3052
3052
|
}
|
|
3053
3053
|
function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark = Number.MAX_SAFE_INTEGER) {
|
|
3054
|
+
const messageRows = readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark);
|
|
3055
|
+
if (messageRows.length === 0)
|
|
3056
|
+
return [];
|
|
3057
|
+
const placeholders = messageRows.map(() => "?").join(", ");
|
|
3058
|
+
const partRows = db.prepare(`SELECT message_id, data, time_updated
|
|
3059
|
+
FROM part
|
|
3060
|
+
WHERE +session_id = ?
|
|
3061
|
+
AND likelihood(message_id IN (${placeholders}), 0.000001)
|
|
3062
|
+
ORDER BY message_id ASC, time_created ASC, id ASC`).all(sessionId, ...messageRows.map((row) => row.id)).filter(isRawPartRow);
|
|
3063
|
+
return assembleRawMessagePage(messageRows, partRows);
|
|
3064
|
+
}
|
|
3065
|
+
function readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark) {
|
|
3054
3066
|
const remaining = Math.max(0, Math.floor(finalWatermark) - Math.floor(afterOrdinal));
|
|
3055
3067
|
const pageSize = Math.min(Math.max(1, Math.floor(limit)), remaining);
|
|
3056
3068
|
if (pageSize === 0)
|
|
3057
3069
|
return [];
|
|
3058
|
-
|
|
3070
|
+
return db.prepare(`SELECT id, data, time_created, time_updated
|
|
3059
3071
|
FROM message
|
|
3060
3072
|
WHERE session_id = ?
|
|
3061
3073
|
AND NOT (
|
|
@@ -3071,14 +3083,8 @@ function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, fin
|
|
|
3071
3083
|
...row,
|
|
3072
3084
|
ordinal: Math.floor(afterOrdinal) + index + 1
|
|
3073
3085
|
}));
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
const placeholders = messageRows.map(() => "?").join(", ");
|
|
3077
|
-
const partRows = db.prepare(`SELECT message_id, data, time_updated
|
|
3078
|
-
FROM part
|
|
3079
|
-
WHERE +session_id = ?
|
|
3080
|
-
AND likelihood(message_id IN (${placeholders}), 0.000001)
|
|
3081
|
-
ORDER BY message_id ASC, time_created ASC, id ASC`).all(sessionId, ...messageRows.map((row) => row.id)).filter(isRawPartRow);
|
|
3086
|
+
}
|
|
3087
|
+
function assembleRawMessagePage(messageRows, partRows) {
|
|
3082
3088
|
const partsByMessageId = new Map;
|
|
3083
3089
|
for (const part of partRows) {
|
|
3084
3090
|
const list = partsByMessageId.get(part.message_id) ?? [];
|
|
@@ -3097,6 +3103,49 @@ function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, fin
|
|
|
3097
3103
|
};
|
|
3098
3104
|
});
|
|
3099
3105
|
}
|
|
3106
|
+
var RAW_SUMMARY_TEXT_MAX_CHARS = 8192;
|
|
3107
|
+
var RAW_SUMMARY_ARG_MAX_CHARS = 512;
|
|
3108
|
+
var RAW_SUMMARY_TOOL_INPUT_KEYS = [
|
|
3109
|
+
"description",
|
|
3110
|
+
"filePath",
|
|
3111
|
+
"path",
|
|
3112
|
+
"pattern",
|
|
3113
|
+
"query",
|
|
3114
|
+
"symbol",
|
|
3115
|
+
"module",
|
|
3116
|
+
"action"
|
|
3117
|
+
];
|
|
3118
|
+
function summaryStringField(jsonPath) {
|
|
3119
|
+
return `CASE WHEN json_type(data, '${jsonPath}') = 'text' THEN substr(json_extract(data, '${jsonPath}'), 1, ${RAW_SUMMARY_ARG_MAX_CHARS}) END`;
|
|
3120
|
+
}
|
|
3121
|
+
var RAW_SUMMARY_PART_DATA_SQL = `CASE
|
|
3122
|
+
WHEN json_extract(data, '$.type') = 'text'
|
|
3123
|
+
THEN json_set(data, '$.text', substr(json_extract(data, '$.text'), 1, ${RAW_SUMMARY_TEXT_MAX_CHARS}))
|
|
3124
|
+
ELSE json_object(
|
|
3125
|
+
'type', 'tool',
|
|
3126
|
+
'tool', ${summaryStringField("$.tool")},
|
|
3127
|
+
'callID', ${summaryStringField("$.callID")},
|
|
3128
|
+
'state', json_object(
|
|
3129
|
+
'status', ${summaryStringField("$.state.status")},
|
|
3130
|
+
'input', json_object(${RAW_SUMMARY_TOOL_INPUT_KEYS.map((key) => `'${key}', ${summaryStringField(`$.state.input.${key}`)}`).join(", ")}),
|
|
3131
|
+
'metadata', json_object('description', ${summaryStringField("$.state.metadata.description")})
|
|
3132
|
+
)
|
|
3133
|
+
)
|
|
3134
|
+
END`;
|
|
3135
|
+
function readRawSessionMessageSummaryPageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark = Number.MAX_SAFE_INTEGER) {
|
|
3136
|
+
const messageRows = readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark);
|
|
3137
|
+
if (messageRows.length === 0)
|
|
3138
|
+
return [];
|
|
3139
|
+
const placeholders = messageRows.map(() => "?").join(", ");
|
|
3140
|
+
const partRows = db.prepare(`SELECT message_id, ${RAW_SUMMARY_PART_DATA_SQL} AS data, time_updated
|
|
3141
|
+
FROM part
|
|
3142
|
+
WHERE +session_id = ?
|
|
3143
|
+
AND likelihood(message_id IN (${placeholders}), 0.000001)
|
|
3144
|
+
AND json_valid(data) = 1
|
|
3145
|
+
AND json_extract(data, '$.type') IN ('text', 'tool')
|
|
3146
|
+
ORDER BY message_id ASC, time_created ASC, id ASC`).all(sessionId, ...messageRows.map((row) => row.id)).filter(isRawPartRow);
|
|
3147
|
+
return assembleRawMessagePage(messageRows, partRows);
|
|
3148
|
+
}
|
|
3100
3149
|
function countRawSessionMessageOrdinalsFromDb(db, sessionId) {
|
|
3101
3150
|
const row = db.prepare(`SELECT COUNT(*) AS count
|
|
3102
3151
|
FROM message
|
|
@@ -3935,6 +3984,72 @@ function buildFileSourceContent(parts) {
|
|
|
3935
3984
|
return content.length > 0 ? content : null;
|
|
3936
3985
|
}
|
|
3937
3986
|
|
|
3987
|
+
// src/features/magic-context/dreamer/token-budget.ts
|
|
3988
|
+
class DreamTokenBudgetExceeded extends Error {
|
|
3989
|
+
sessionId;
|
|
3990
|
+
spent;
|
|
3991
|
+
constructor(sessionId, spent) {
|
|
3992
|
+
super(`Dreamer child ${sessionId} spent ${spent} prompt tokens (token_budget)`);
|
|
3993
|
+
this.sessionId = sessionId;
|
|
3994
|
+
this.spent = spent;
|
|
3995
|
+
this.name = "DreamTokenBudgetExceeded";
|
|
3996
|
+
}
|
|
3997
|
+
}
|
|
3998
|
+
var TOKEN_BUDGET_FINALIZE_MESSAGE = "You're out of token budget. Stop investigating: make no more tool calls and output your result now, covering only what you've already checked; leave the rest out.";
|
|
3999
|
+
var TOKEN_BUDGET_TOOL_REFUSAL = "Out of token budget: no more tool calls. Output your result now.";
|
|
4000
|
+
var finalizingChildren = new Map;
|
|
4001
|
+
function registerBudgetFinalizeChild(sessionId, guard) {
|
|
4002
|
+
finalizingChildren.set(sessionId, guard);
|
|
4003
|
+
}
|
|
4004
|
+
function releaseBudgetFinalizeChild(sessionId) {
|
|
4005
|
+
finalizingChildren.delete(sessionId);
|
|
4006
|
+
}
|
|
4007
|
+
function refuseBudgetedToolCall(sessionId) {
|
|
4008
|
+
return finalizingChildren.get(sessionId)?.refuseTool() ?? null;
|
|
4009
|
+
}
|
|
4010
|
+
function createDreamTokenBudget(budget) {
|
|
4011
|
+
if (!Number.isSafeInteger(budget) || budget <= 0)
|
|
4012
|
+
throw new Error("Invalid token budget");
|
|
4013
|
+
let spent = 0;
|
|
4014
|
+
let finalizeFired = false;
|
|
4015
|
+
let refusedCalls = 0;
|
|
4016
|
+
let forcedStop = false;
|
|
4017
|
+
const snapshot = () => ({
|
|
4018
|
+
budget,
|
|
4019
|
+
spent,
|
|
4020
|
+
finalizeFired,
|
|
4021
|
+
refusedCalls,
|
|
4022
|
+
hardStopped: forcedStop || spent >= budget || refusedCalls >= 2
|
|
4023
|
+
});
|
|
4024
|
+
return {
|
|
4025
|
+
snapshot,
|
|
4026
|
+
charge(input, cacheRead, cacheWrite, completed = false, canFinalize = true) {
|
|
4027
|
+
for (const value of [input, cacheRead, cacheWrite]) {
|
|
4028
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
4029
|
+
throw new Error("Invalid prompt usage");
|
|
4030
|
+
}
|
|
4031
|
+
spent += input + cacheRead + cacheWrite;
|
|
4032
|
+
if (spent >= budget)
|
|
4033
|
+
return "stop";
|
|
4034
|
+
if (!completed && !finalizeFired && spent >= budget * 0.8) {
|
|
4035
|
+
if (!canFinalize) {
|
|
4036
|
+
forcedStop = true;
|
|
4037
|
+
return "stop";
|
|
4038
|
+
}
|
|
4039
|
+
finalizeFired = true;
|
|
4040
|
+
return "finalize";
|
|
4041
|
+
}
|
|
4042
|
+
return "continue";
|
|
4043
|
+
},
|
|
4044
|
+
refuseTool() {
|
|
4045
|
+
if (!finalizeFired)
|
|
4046
|
+
return null;
|
|
4047
|
+
refusedCalls += 1;
|
|
4048
|
+
return { message: TOKEN_BUDGET_TOOL_REFUSAL, hardStopped: snapshot().hardStopped };
|
|
4049
|
+
}
|
|
4050
|
+
};
|
|
4051
|
+
}
|
|
4052
|
+
|
|
3938
4053
|
// src/hooks/magic-context/dropped-input-guard.ts
|
|
3939
4054
|
var LEGACY_TRUNCATED_VALUE = /^[\s\S]{0,5}\.\.\.\[truncated\]$/;
|
|
3940
4055
|
var MAX_QUOTED_ARGUMENTS = 160;
|
|
@@ -4101,6 +4216,11 @@ function createDroppedInputToolExecuteBeforeHook() {
|
|
|
4101
4216
|
return async (input, output) => {
|
|
4102
4217
|
const call = isRecord2(input) ? input : {};
|
|
4103
4218
|
const args = isRecord2(output) ? output.args : undefined;
|
|
4219
|
+
if (typeof call.sessionID === "string") {
|
|
4220
|
+
const refusal = refuseBudgetedToolCall(call.sessionID);
|
|
4221
|
+
if (refusal)
|
|
4222
|
+
throw new Error(refusal.message);
|
|
4223
|
+
}
|
|
4104
4224
|
assertExecutableToolInput(guard, {
|
|
4105
4225
|
sessionID: typeof call.sessionID === "string" ? call.sessionID : undefined,
|
|
4106
4226
|
toolName: typeof call.tool === "string" ? call.tool : undefined,
|
|
@@ -5001,6 +5121,45 @@ function readRawSessionMessageRangeFromSource(sessionId, fromOrdinal, toOrdinal)
|
|
|
5001
5121
|
}
|
|
5002
5122
|
return messages;
|
|
5003
5123
|
}
|
|
5124
|
+
var RAW_MESSAGE_VISIT_PAGE_SIZE = 50;
|
|
5125
|
+
function visitRawSessionMessages2(sessionId, fromOrdinal, toOrdinal, visit, options = {}) {
|
|
5126
|
+
const from = Math.max(1, Math.floor(fromOrdinal));
|
|
5127
|
+
const to = Math.floor(toOrdinal);
|
|
5128
|
+
if (to < from)
|
|
5129
|
+
return;
|
|
5130
|
+
const provider = sessionProviders.get(sessionId);
|
|
5131
|
+
if (provider && !provider.readMessagePage) {
|
|
5132
|
+
for (const message of provider.readMessages()) {
|
|
5133
|
+
if (message.ordinal < from || message.ordinal > to)
|
|
5134
|
+
continue;
|
|
5135
|
+
if (!visit(message))
|
|
5136
|
+
return;
|
|
5137
|
+
}
|
|
5138
|
+
return;
|
|
5139
|
+
}
|
|
5140
|
+
if (!provider && !openCodeDbExists())
|
|
5141
|
+
return;
|
|
5142
|
+
const pageSize = Math.max(1, Math.floor(options.pageSize ?? RAW_MESSAGE_VISIT_PAGE_SIZE));
|
|
5143
|
+
let afterOrdinal = from - 1;
|
|
5144
|
+
while (afterOrdinal < to) {
|
|
5145
|
+
const limit = Math.min(pageSize, to - afterOrdinal);
|
|
5146
|
+
const cursor = afterOrdinal;
|
|
5147
|
+
const page = provider?.readMessagePage ? provider.readMessagePage(cursor, limit, to) : withReadOnlySessionDb((db) => options.summary ? readRawSessionMessageSummaryPageFromDb(db, sessionId, cursor, limit, to) : readRawSessionMessagePageFromDb(db, sessionId, cursor, limit, to));
|
|
5148
|
+
if (page.length === 0)
|
|
5149
|
+
return;
|
|
5150
|
+
let nextOrdinal = afterOrdinal;
|
|
5151
|
+
for (const message of page) {
|
|
5152
|
+
if (message.ordinal < from || message.ordinal > to)
|
|
5153
|
+
continue;
|
|
5154
|
+
if (!visit(message))
|
|
5155
|
+
return;
|
|
5156
|
+
nextOrdinal = Math.max(nextOrdinal, message.ordinal);
|
|
5157
|
+
}
|
|
5158
|
+
if (nextOrdinal <= afterOrdinal)
|
|
5159
|
+
return;
|
|
5160
|
+
afterOrdinal = nextOrdinal;
|
|
5161
|
+
}
|
|
5162
|
+
}
|
|
5004
5163
|
function readRawSessionMessageRange2(sessionId, fromOrdinal, toOrdinal) {
|
|
5005
5164
|
const from = Math.max(1, Math.floor(fromOrdinal));
|
|
5006
5165
|
const to = Math.floor(toOrdinal);
|
|
@@ -5599,4 +5758,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
|
|
|
5599
5758
|
});
|
|
5600
5759
|
}
|
|
5601
5760
|
|
|
5602
|
-
export { textMentionsRecentCommit, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, extractToolCallSummaries, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, normalizeText, stableStringify, getCurrentToolSetHash, setDatabase, loadToolDefinitionMeasurements, recordToolDefinition, getMeasuredToolDefinitionTokens, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, isRecord, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, getAllStatusTagTokenTotalsFlat, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, updateTagMessageId, foldShrunkPartTags, markTagsCompactedByMessageIds, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, markHostUnservedRow, retreatPastHostUnservedRows, snapTerminalCompartmentToServedRow, isHostRenderedSystemMessage, isStrictGapHealingMessage, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, recordToolParameters, createDroppedInputGuard, assertExecutableToolInput, createDroppedInputToolExecuteBeforeHook, isEditTool, describeFinalWireTail, estimateMessageTokens, estimateFinalWireInputTokens, SKELETON_REAL_INPUT_MAX_BYTES, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessagePartsById2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2, readRawSessionSeedTail2 };
|
|
5761
|
+
export { textMentionsRecentCommit, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, extractToolCallSummaries, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, normalizeText, stableStringify, getCurrentToolSetHash, setDatabase, loadToolDefinitionMeasurements, recordToolDefinition, getMeasuredToolDefinitionTokens, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, isRecord, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, getAllStatusTagTokenTotalsFlat, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, updateTagMessageId, foldShrunkPartTags, markTagsCompactedByMessageIds, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, markHostUnservedRow, retreatPastHostUnservedRows, snapTerminalCompartmentToServedRow, isHostRenderedSystemMessage, isStrictGapHealingMessage, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, recordToolParameters, createDroppedInputGuard, assertExecutableToolInput, createDroppedInputToolExecuteBeforeHook, isEditTool, describeFinalWireTail, estimateMessageTokens, estimateFinalWireInputTokens, SKELETON_REAL_INPUT_MAX_BYTES, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessagePartsById2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2, readRawSessionSeedTail2 };
|