@cortexkit/opencode-magic-context 0.42.2 → 0.42.4
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 +3 -1
- package/dist/{announcement-3c1vertn.js → announcement-8mgn61fw.js} +1 -1
- package/dist/{conflict-warning-hook-6p3xqeac.js → conflict-warning-hook-jyj54gbe.js} +4 -4
- package/dist/{derive-budgets-s2pgnnm4.js → derive-budgets-v1fkhjjr.js} +2 -2
- package/dist/features/magic-context/compaction-marker.d.ts +4 -10
- package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
- package/dist/features/magic-context/context-authority.d.ts +13 -0
- package/dist/features/magic-context/context-authority.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/classify.d.ts +3 -1
- package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-executor.d.ts +6 -2
- package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-registry.d.ts +3 -0
- package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
- package/dist/features/magic-context/mural/compress-cues.d.ts +3 -1
- package/dist/features/magic-context/mural/compress-cues.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts +4 -0
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/hooks/magic-context/apply-operations.d.ts +4 -1
- package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
- package/dist/hooks/magic-context/caveman-cleanup.d.ts +4 -0
- package/dist/hooks/magic-context/caveman-cleanup.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts +5 -2
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts +2 -2
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-types.d.ts +61 -2
- package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner.d.ts +2 -2
- package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/dropped-token-estimate.d.ts +20 -0
- package/dist/hooks/magic-context/dropped-token-estimate.d.ts.map +1 -0
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts +2 -0
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts +2 -2
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-transport.d.ts +4 -1
- package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-raw.d.ts +4 -4
- package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +2 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +3 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +8 -0
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +21 -0
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-jmtjh2d3.js → index-1ar7b3e9.js} +3 -3
- package/dist/{index-3fe78beq.js → index-4ftb5hcq.js} +9 -1
- package/dist/{index-may8skc8.js → index-bkg2fdj1.js} +15 -1
- package/dist/{index-36wd1d6k.js → index-d8mgqezq.js} +2 -2
- package/dist/{index-xdtge3y2.js → index-f9gem5cr.js} +2 -2
- package/dist/{index-953x7a79.js → index-faay035c.js} +248 -88
- package/dist/{index-1974jvn3.js → index-jkrqhc7y.js} +2 -2
- package/dist/{index-3wzdwt6p.js → index-ntbmt6rq.js} +1 -1
- package/dist/{index-nqgjwfzn.js → index-p474rw9p.js} +3 -3
- package/dist/{index-dkv2dn46.js → index-qp20p2py.js} +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1442 -127
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts +18 -0
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/plugin/rust-tool-backends.d.ts +3 -1
- package/dist/plugin/rust-tool-backends.d.ts.map +1 -1
- package/dist/{recomp-orchestrator-5g8f5rhy.js → recomp-orchestrator-c4sa354a.js} +6 -6
- package/dist/{safe-notification-target-q9z81zt3.js → safe-notification-target-fepvcbsj.js} +1 -1
- package/dist/{send-session-notification-1qeqkswb.js → send-session-notification-xnypkxpx.js} +3 -3
- package/dist/shared/harness.d.ts +2 -1
- package/dist/shared/harness.d.ts.map +1 -1
- package/dist/shared/model-suggestion-retry.d.ts +5 -1
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- package/dist/shared/prompt-surface-runtime.d.ts.map +1 -1
- package/dist/shared/rpc-types.d.ts +13 -0
- package/dist/shared/rpc-types.d.ts.map +1 -1
- package/dist/shared/status-detail-text.d.ts.map +1 -1
- package/dist/shared/status-summary.d.ts.map +1 -1
- package/dist/shared/user-facing-codes.d.ts +10 -0
- package/dist/shared/user-facing-codes.d.ts.map +1 -1
- package/dist/{storage-meta-session-e6g0mmec.js → storage-meta-session-x3j0q9qy.js} +3 -3
- package/dist/{task-config-hnv93r7p.js → task-config-ys0arma5.js} +1 -1
- package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
- package/dist/tools/ctx-note/tools.d.ts.map +1 -1
- package/dist/v2/fold/markers.d.ts +7 -0
- package/dist/v2/fold/markers.d.ts.map +1 -0
- package/dist/v2/fold/owner.d.ts +40 -0
- package/dist/v2/fold/owner.d.ts.map +1 -0
- package/dist/v2/fold/restore.d.ts +11 -0
- package/dist/v2/fold/restore.d.ts.map +1 -0
- package/dist/v2/hidden-completion.d.ts +20 -0
- package/dist/v2/hidden-completion.d.ts.map +1 -0
- package/dist/v2/hooks/channel2.d.ts +8 -0
- package/dist/v2/hooks/channel2.d.ts.map +1 -0
- package/dist/v2/hooks/context.d.ts +7 -0
- package/dist/v2/hooks/context.d.ts.map +1 -0
- package/dist/v2/hooks/dream-trigger.d.ts +19 -0
- package/dist/v2/hooks/dream-trigger.d.ts.map +1 -0
- package/dist/v2/hooks/payload.d.ts +12 -0
- package/dist/v2/hooks/payload.d.ts.map +1 -0
- package/dist/v2/hooks/refusal.d.ts +7 -0
- package/dist/v2/hooks/refusal.d.ts.map +1 -0
- package/dist/v2/hooks/store.d.ts +6 -0
- package/dist/v2/hooks/store.d.ts.map +1 -0
- package/dist/v2/hooks/types.d.ts +90 -0
- package/dist/v2/hooks/types.d.ts.map +1 -0
- package/dist/v2/hooks/update-check.d.ts +10 -0
- package/dist/v2/hooks/update-check.d.ts.map +1 -0
- package/dist/v2/server.d.ts +8 -0
- package/dist/v2/server.d.ts.map +1 -0
- package/dist/v2/server.js +118588 -0
- package/dist/v2/store-reader.d.ts +65 -0
- package/dist/v2/store-reader.d.ts.map +1 -0
- package/index.js +1 -0
- package/package.json +10 -4
- package/src/features/magic-context/dreamer/task-registry.ts +19 -0
- package/src/shared/harness.ts +2 -1
- package/src/shared/model-suggestion-retry.ts +66 -14
- package/src/shared/prompt-surface-runtime.ts +5 -1
- package/src/shared/rpc-types.ts +13 -0
- package/src/shared/status-detail-text.test.ts +26 -0
- package/src/shared/status-detail-text.ts +11 -0
- package/src/shared/status-summary.ts +2 -0
- package/src/shared/user-facing-codes.test.ts +1 -1
- package/src/shared/user-facing-codes.ts +10 -0
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
sanitizeDiagnosticText,
|
|
3
3
|
log,
|
|
4
4
|
sessionLog
|
|
5
|
-
} from "./index-
|
|
5
|
+
} from "./index-qp20p2py.js";
|
|
6
6
|
import {
|
|
7
7
|
logSlowWriteTransaction,
|
|
8
8
|
ensureSessionMetaRow,
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
SESSION_SCOPED_TABLES,
|
|
12
12
|
deleteSessionScopedRows,
|
|
13
13
|
updateSessionMeta2
|
|
14
|
-
} from "./index-
|
|
14
|
+
} from "./index-1ar7b3e9.js";
|
|
15
15
|
import {
|
|
16
16
|
resolveOpenCodeDbPath,
|
|
17
17
|
openCodeDbPathExists,
|
|
@@ -25,7 +25,7 @@ import {
|
|
|
25
25
|
withReadOnlySessionDb,
|
|
26
26
|
getRawSessionMessageCountFromDb,
|
|
27
27
|
getMessageTimesFromOpenCodeDb
|
|
28
|
-
} from "./index-
|
|
28
|
+
} from "./index-jkrqhc7y.js";
|
|
29
29
|
import {
|
|
30
30
|
pushNotification2
|
|
31
31
|
} from "./index-jdxxq8cz.js";
|
|
@@ -42,12 +42,12 @@ import {
|
|
|
42
42
|
shouldEnforcePrivateStoragePermissions,
|
|
43
43
|
modelSupportsVision,
|
|
44
44
|
deriveTriggerBudget2
|
|
45
|
-
} from "./index-
|
|
45
|
+
} from "./index-f9gem5cr.js";
|
|
46
46
|
import {
|
|
47
47
|
getErrorMessage,
|
|
48
48
|
describeError,
|
|
49
49
|
sendStatusNotification2
|
|
50
|
-
} from "./index-
|
|
50
|
+
} from "./index-p474rw9p.js";
|
|
51
51
|
import {
|
|
52
52
|
piModelRefToCanonical,
|
|
53
53
|
modelRefLookupOrder
|
|
@@ -58,7 +58,7 @@ import {
|
|
|
58
58
|
getProjectMagicContextHistorianDir,
|
|
59
59
|
getMagicContextStorageDir,
|
|
60
60
|
getLegacyOpenCodeMagicContextStorageDir
|
|
61
|
-
} from "./index-
|
|
61
|
+
} from "./index-4ftb5hcq.js";
|
|
62
62
|
|
|
63
63
|
// src/features/magic-context/compartment-lease.ts
|
|
64
64
|
var COMPARTMENT_LEASE_TTL_MS = 5 * 60 * 1000;
|
|
@@ -1737,6 +1737,11 @@ async function drainAuthority(args) {
|
|
|
1737
1737
|
if (finished.state !== "TS") {
|
|
1738
1738
|
throw new Error("memory authority drain did not reactivate TypeScript ownership");
|
|
1739
1739
|
}
|
|
1740
|
+
if (args.domain === "memories") {
|
|
1741
|
+
withPrivilegedWriter(args.db, () => {
|
|
1742
|
+
args.db.prepare("DELETE FROM mirror_live_memory_rows WHERE module_project = ?").run(args.projectPath);
|
|
1743
|
+
});
|
|
1744
|
+
}
|
|
1740
1745
|
const remaining = await Promise.all(AUTHORITY_DOMAINS.map((domain) => args.module.authorityStatus({
|
|
1741
1746
|
context_store_uuid: contextStoreUuid,
|
|
1742
1747
|
project: args.projectPath,
|
|
@@ -1779,6 +1784,28 @@ function chunkRowsForFrame(rows) {
|
|
|
1779
1784
|
chunks.push(current);
|
|
1780
1785
|
return chunks;
|
|
1781
1786
|
}
|
|
1787
|
+
var MEMORY_MIRROR_STALL_THRESHOLD_MS = 40000;
|
|
1788
|
+
function getMemoryMirrorStatus(db, feedHead, nowMs = Date.now()) {
|
|
1789
|
+
const cursorRow = db.prepare("SELECT cursor, updated_at FROM mirror_cursors WHERE domain = 'memories'").get();
|
|
1790
|
+
const liveRow = db.prepare("SELECT COUNT(*) AS count FROM mirror_live_memory_rows").get();
|
|
1791
|
+
const cursor = typeof cursorRow?.cursor === "number" ? cursorRow.cursor : 0;
|
|
1792
|
+
const cursorUpdatedAt = typeof cursorRow?.updated_at === "number" && cursorRow.updated_at > 0 ? cursorRow.updated_at : null;
|
|
1793
|
+
const cursorAgeMs = cursorUpdatedAt === null ? null : Math.max(0, Math.floor(nowMs - cursorUpdatedAt));
|
|
1794
|
+
const liveRows = typeof liveRow?.count === "number" ? liveRow.count : 0;
|
|
1795
|
+
const resolvedFeedHead = typeof feedHead === "number" && Number.isSafeInteger(feedHead) && feedHead >= 0 ? feedHead : null;
|
|
1796
|
+
const pendingRows = resolvedFeedHead === null ? null : Math.max(0, resolvedFeedHead - cursor);
|
|
1797
|
+
const stalled = liveRows > 0 && pendingRows !== null && pendingRows > 0 && cursorAgeMs !== null && cursorAgeMs >= MEMORY_MIRROR_STALL_THRESHOLD_MS;
|
|
1798
|
+
return {
|
|
1799
|
+
cursor,
|
|
1800
|
+
cursorUpdatedAt,
|
|
1801
|
+
cursorAgeMs,
|
|
1802
|
+
liveRows,
|
|
1803
|
+
feedHead: resolvedFeedHead,
|
|
1804
|
+
pendingRows,
|
|
1805
|
+
stalled,
|
|
1806
|
+
code: stalled ? "MC-M01" : null
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1782
1809
|
function getMirrorCursor(db, domain) {
|
|
1783
1810
|
const row = db.prepare("SELECT cursor FROM mirror_cursors WHERE domain = ?").get(domain);
|
|
1784
1811
|
return typeof row?.cursor === "number" ? row.cursor : 0;
|
|
@@ -2587,7 +2614,7 @@ function pullMemoryMirrorOnce(args) {
|
|
|
2587
2614
|
db: args.db,
|
|
2588
2615
|
module: args.module,
|
|
2589
2616
|
domain: "memories",
|
|
2590
|
-
limit: args.limit,
|
|
2617
|
+
limit: args.limit ?? 1000,
|
|
2591
2618
|
pageBudget: args.pageBudget ?? TRANSFORM_MEMORY_MIRROR_PAGE_BUDGET
|
|
2592
2619
|
}).then((result) => ({ ...result, cuePoolVersion: result.cursor })).finally(() => mirrorFlights.delete(args.module));
|
|
2593
2620
|
mirrorFlights.set(args.module, flight);
|
|
@@ -10606,7 +10633,7 @@ function deleteToolTagsByOwner(db, sessionId, ownerMsgId) {
|
|
|
10606
10633
|
}
|
|
10607
10634
|
|
|
10608
10635
|
// src/hooks/magic-context/read-session-raw.ts
|
|
10609
|
-
var RAW_MESSAGE_PARTS_BY_ID_SQL = "SELECT message_id, data, time_updated FROM part WHERE session_id = ? AND likelihood(message_id = ?, 0.000001) ORDER BY time_created ASC, id ASC";
|
|
10636
|
+
var RAW_MESSAGE_PARTS_BY_ID_SQL = "SELECT message_id, data, time_updated FROM part WHERE +session_id = ? AND likelihood(message_id = ?, 0.000001) ORDER BY time_created ASC, id ASC";
|
|
10610
10637
|
function isRawMessageRow(row) {
|
|
10611
10638
|
if (row === null || typeof row !== "object")
|
|
10612
10639
|
return false;
|
|
@@ -10668,7 +10695,7 @@ function readRawSessionMessagesFromDb(db, sessionId) {
|
|
|
10668
10695
|
const placeholders = messageIds.map(() => "?").join(", ");
|
|
10669
10696
|
const partRows = db.prepare(`SELECT message_id, data, time_updated
|
|
10670
10697
|
FROM part
|
|
10671
|
-
WHERE session_id = ?
|
|
10698
|
+
WHERE +session_id = ?
|
|
10672
10699
|
AND likelihood(message_id IN (${placeholders}), 0.000001)
|
|
10673
10700
|
ORDER BY message_id ASC, time_created ASC, id ASC`).all(sessionId, ...messageIds).filter(isRawPartRow);
|
|
10674
10701
|
for (const part of partRows) {
|
|
@@ -10719,7 +10746,7 @@ function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, fin
|
|
|
10719
10746
|
const placeholders = messageRows.map(() => "?").join(", ");
|
|
10720
10747
|
const partRows = db.prepare(`SELECT message_id, data, time_updated
|
|
10721
10748
|
FROM part
|
|
10722
|
-
WHERE session_id = ?
|
|
10749
|
+
WHERE +session_id = ?
|
|
10723
10750
|
AND likelihood(message_id IN (${placeholders}), 0.000001)
|
|
10724
10751
|
ORDER BY message_id ASC, time_created ASC, id ASC`).all(sessionId, ...messageRows.map((row) => row.id)).filter(isRawPartRow);
|
|
10725
10752
|
const partsByMessageId = new Map;
|
|
@@ -10807,7 +10834,7 @@ function readRawSessionTailFromDb(db, sessionId, baseOrdinal, anchorMessageId) {
|
|
|
10807
10834
|
for (let i = 0;i < ids.length; i += CHUNK) {
|
|
10808
10835
|
const slice = ids.slice(i, i + CHUNK);
|
|
10809
10836
|
const placeholders = slice.map(() => "?").join(",");
|
|
10810
|
-
const partRows = db.prepare(`SELECT message_id, data, time_updated FROM part WHERE session_id = ? AND likelihood(message_id IN (${placeholders}), 0.000001) ORDER BY time_created ASC, id ASC`).all(sessionId, ...slice).filter(isRawPartRow);
|
|
10837
|
+
const partRows = db.prepare(`SELECT message_id, data, time_updated FROM part WHERE +session_id = ? AND likelihood(message_id IN (${placeholders}), 0.000001) ORDER BY time_created ASC, id ASC`).all(sessionId, ...slice).filter(isRawPartRow);
|
|
10811
10838
|
for (const part of partRows) {
|
|
10812
10839
|
const list = partsByMessageId.get(part.message_id) ?? [];
|
|
10813
10840
|
list.push(attachRawPartVersion(parseJsonUnknown(part.data), part.time_updated));
|
|
@@ -10973,7 +11000,7 @@ function readRawSeedTailFromDb(db, sessionId, boundaryId) {
|
|
|
10973
11000
|
SELECT c.id, m.data, c.time_created, m.time_updated, c.ordinal,
|
|
10974
11001
|
p.data AS part_data, p.time_updated AS part_updated
|
|
10975
11002
|
FROM canonical c JOIN message m ON m.id = c.id
|
|
10976
|
-
LEFT JOIN part p ON p.session_id = ? AND likelihood(p.message_id = c.id, 0.000001)
|
|
11003
|
+
LEFT JOIN part p ON +p.session_id = ? AND likelihood(p.message_id = c.id, 0.000001)
|
|
10977
11004
|
WHERE ? IS NULL OR c.ordinal >= (SELECT ordinal FROM canonical WHERE id = ?)
|
|
10978
11005
|
ORDER BY c.ordinal, p.time_created, p.id
|
|
10979
11006
|
`).all(sessionId, sessionId, boundaryId, boundaryId);
|
|
@@ -21652,7 +21679,7 @@ function parseModelSuggestion(error) {
|
|
|
21652
21679
|
suggestion: suggestionMatch[1].trim()
|
|
21653
21680
|
};
|
|
21654
21681
|
}
|
|
21655
|
-
async function promptWithTimeout(client, args, timeoutMs, signal) {
|
|
21682
|
+
async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
|
|
21656
21683
|
if (signal?.aborted) {
|
|
21657
21684
|
throw new Error("prompt aborted by external signal");
|
|
21658
21685
|
}
|
|
@@ -21661,17 +21688,25 @@ async function promptWithTimeout(client, args, timeoutMs, signal) {
|
|
|
21661
21688
|
const onExternalAbort = () => controller.abort();
|
|
21662
21689
|
signal?.addEventListener("abort", onExternalAbort);
|
|
21663
21690
|
try {
|
|
21664
|
-
|
|
21665
|
-
|
|
21666
|
-
|
|
21667
|
-
|
|
21691
|
+
const request = { ...args, signal: controller.signal };
|
|
21692
|
+
if (transport)
|
|
21693
|
+
await transport(request);
|
|
21694
|
+
else {
|
|
21695
|
+
if (!client)
|
|
21696
|
+
throw new Error("Hidden completion transport is unavailable");
|
|
21697
|
+
await client.session.prompt(request);
|
|
21698
|
+
}
|
|
21668
21699
|
} catch (error) {
|
|
21669
21700
|
if (signal?.aborted) {
|
|
21670
|
-
|
|
21701
|
+
if (!transport || transport.childSessionId) {
|
|
21702
|
+
await abortChildRun(client, transport?.childSessionId ?? args.path.id);
|
|
21703
|
+
}
|
|
21671
21704
|
throw new Error("prompt aborted by external signal");
|
|
21672
21705
|
}
|
|
21673
21706
|
if (controller.signal.aborted) {
|
|
21674
|
-
|
|
21707
|
+
if (!transport || transport.childSessionId) {
|
|
21708
|
+
await abortChildRun(client, transport?.childSessionId ?? args.path.id);
|
|
21709
|
+
}
|
|
21675
21710
|
throw new Error(`prompt timed out after ${timeoutMs}ms`);
|
|
21676
21711
|
}
|
|
21677
21712
|
throw error;
|
|
@@ -21681,6 +21716,8 @@ async function promptWithTimeout(client, args, timeoutMs, signal) {
|
|
|
21681
21716
|
}
|
|
21682
21717
|
}
|
|
21683
21718
|
async function abortChildRun(client, sessionId) {
|
|
21719
|
+
if (!client)
|
|
21720
|
+
return;
|
|
21684
21721
|
try {
|
|
21685
21722
|
await Promise.race([
|
|
21686
21723
|
client.session.abort({ path: { id: sessionId } }),
|
|
@@ -21729,7 +21766,7 @@ function classifyPromptFailure(error, phase, externalSignal) {
|
|
|
21729
21766
|
}
|
|
21730
21767
|
return phase === "prompt" || phase === "output" ? "provider_error" : "unknown";
|
|
21731
21768
|
}
|
|
21732
|
-
function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs) {
|
|
21769
|
+
function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, transport) {
|
|
21733
21770
|
const error = legacyError instanceof Error ? legacyError : new Error(extractMessage(legacyError));
|
|
21734
21771
|
const last = failedAttempts.at(-1);
|
|
21735
21772
|
const failureClass = last?.failureClass ?? "unknown";
|
|
@@ -21740,15 +21777,15 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs) {
|
|
|
21740
21777
|
modelsTried: failedAttempts.map((failure) => failure.attempt.label),
|
|
21741
21778
|
providerError,
|
|
21742
21779
|
timeoutMs: failureClass === "provider_timeout" ? timeoutMs : null,
|
|
21743
|
-
childSessionId: args.path.id || null
|
|
21780
|
+
childSessionId: transport ? transport.childSessionId ?? null : args.path.id || null
|
|
21744
21781
|
});
|
|
21745
21782
|
throw error;
|
|
21746
21783
|
}
|
|
21747
|
-
async function attemptOnce(client, args, timeoutMs, signal, callContext, label) {
|
|
21784
|
+
async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport) {
|
|
21748
21785
|
const originalBody = { ...args.body };
|
|
21749
21786
|
const attemptArgs = copyPromptArgs(args, originalBody);
|
|
21750
21787
|
try {
|
|
21751
|
-
await promptWithTimeout(client, attemptArgs, timeoutMs, signal);
|
|
21788
|
+
await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport);
|
|
21752
21789
|
return;
|
|
21753
21790
|
} catch (error) {
|
|
21754
21791
|
if (isNonRetryable(error, signal))
|
|
@@ -21767,7 +21804,7 @@ async function attemptOnce(client, args, timeoutMs, signal, callContext, label)
|
|
|
21767
21804
|
providerID: suggestion.providerID,
|
|
21768
21805
|
modelID: suggestion.suggestion
|
|
21769
21806
|
}
|
|
21770
|
-
}), timeoutMs, signal);
|
|
21807
|
+
}), timeoutMs, signal, transport);
|
|
21771
21808
|
}
|
|
21772
21809
|
}
|
|
21773
21810
|
async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
@@ -21779,7 +21816,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
21779
21816
|
const explicitPrimaryLabel = baseBody.model?.providerID && baseBody.model.modelID ? `${baseBody.model.providerID}/${baseBody.model.modelID}` : "primary";
|
|
21780
21817
|
let lastError = null;
|
|
21781
21818
|
try {
|
|
21782
|
-
await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel);
|
|
21819
|
+
await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport);
|
|
21783
21820
|
return;
|
|
21784
21821
|
} catch (error) {
|
|
21785
21822
|
lastError = error;
|
|
@@ -21805,7 +21842,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
21805
21842
|
...fallback?.qualifier ? { variant: fallback.qualifier } : {}
|
|
21806
21843
|
});
|
|
21807
21844
|
try {
|
|
21808
|
-
await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label);
|
|
21845
|
+
await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport);
|
|
21809
21846
|
log(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
|
|
21810
21847
|
return;
|
|
21811
21848
|
} catch (error) {
|
|
@@ -21823,7 +21860,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
|
21823
21860
|
}
|
|
21824
21861
|
async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options) {
|
|
21825
21862
|
try {
|
|
21826
|
-
await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label);
|
|
21863
|
+
await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport);
|
|
21827
21864
|
} catch (error) {
|
|
21828
21865
|
throw {
|
|
21829
21866
|
error,
|
|
@@ -21877,10 +21914,10 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
21877
21914
|
firstError = failure.error;
|
|
21878
21915
|
lastError = failure.error;
|
|
21879
21916
|
if (isNonRetryable(failure.error, options.signal)) {
|
|
21880
|
-
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs);
|
|
21917
|
+
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
|
|
21881
21918
|
}
|
|
21882
21919
|
if (fallbacks.length === 0) {
|
|
21883
|
-
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs);
|
|
21920
|
+
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
|
|
21884
21921
|
}
|
|
21885
21922
|
log(`[${callContext}] primary (${explicitPrimaryLabel}) failed validation/prompt: ${shortErr(failure.error)}; trying ${fallbacks.length} fallback(s)`);
|
|
21886
21923
|
}
|
|
@@ -21914,7 +21951,7 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
21914
21951
|
failedAttempts.push(failure);
|
|
21915
21952
|
lastError = failure.error;
|
|
21916
21953
|
if (isNonRetryable(failure.error, options.signal)) {
|
|
21917
|
-
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs);
|
|
21954
|
+
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
|
|
21918
21955
|
}
|
|
21919
21956
|
const remaining = fallbacks.length - i - 1;
|
|
21920
21957
|
if (remaining > 0) {
|
|
@@ -21923,7 +21960,7 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
21923
21960
|
}
|
|
21924
21961
|
}
|
|
21925
21962
|
log(`[${callContext}] all models exhausted; tried: ${failedAttempts.map((failure) => failure.attempt.label).join(", ")}; original error: ${shortErr(firstError)}; last error: ${shortErr(lastError)}`);
|
|
21926
|
-
throwWithPromptFailure(firstError ?? lastError ?? new Error("All fallback models failed validation"), failedAttempts, args, timeoutMs);
|
|
21963
|
+
throwWithPromptFailure(firstError ?? lastError ?? new Error("All fallback models failed validation"), failedAttempts, args, timeoutMs, options.transport);
|
|
21927
21964
|
}
|
|
21928
21965
|
// src/shared/normalize-sdk-response.ts
|
|
21929
21966
|
function normalizeSDKResponse(response, fallback, options) {
|
|
@@ -22449,7 +22486,7 @@ function resolveUserConfigDirectory(options) {
|
|
|
22449
22486
|
if (shared.format !== "none")
|
|
22450
22487
|
return dirname4(shared.path);
|
|
22451
22488
|
if (options.harness) {
|
|
22452
|
-
const legacy = resolveLegacyConfigSourcesForHarness(options.directory ?? process.cwd(), options.harness === "omp" ? "pi" : options.harness).user.find((source) => existsSync6(source.path));
|
|
22489
|
+
const legacy = resolveLegacyConfigSourcesForHarness(options.directory ?? process.cwd(), options.harness === "omp" ? "pi" : options.harness === "opencode2" ? "opencode" : options.harness).user.find((source) => existsSync6(source.path));
|
|
22453
22490
|
if (legacy)
|
|
22454
22491
|
return dirname4(legacy.path);
|
|
22455
22492
|
}
|
|
@@ -24127,6 +24164,16 @@ var USER_FACING_FAILURES = {
|
|
|
24127
24164
|
code: "MC-C10",
|
|
24128
24165
|
sentence: "Magic Context is temporarily unavailable.",
|
|
24129
24166
|
action: "Retry in a moment."
|
|
24167
|
+
},
|
|
24168
|
+
memory_mirror_stalled: {
|
|
24169
|
+
code: "MC-M01",
|
|
24170
|
+
sentence: "Memory synchronization stopped before the host mirror caught up.",
|
|
24171
|
+
action: "Send another message to resume it, or run `ck doctor drain-authority`."
|
|
24172
|
+
},
|
|
24173
|
+
memory_authority_mismatch: {
|
|
24174
|
+
code: "MC-M02",
|
|
24175
|
+
sentence: "Memory authority is inconsistent between the host and module.",
|
|
24176
|
+
action: "Run `ck doctor drain-authority` before changing Rust mode."
|
|
24130
24177
|
}
|
|
24131
24178
|
};
|
|
24132
24179
|
function renderUserFacingFailure(key, style = "markdown") {
|
|
@@ -31373,7 +31420,7 @@ function removeLegacyMarkerLineageRows(db, args) {
|
|
|
31373
31420
|
AND EXISTS (
|
|
31374
31421
|
SELECT 1
|
|
31375
31422
|
FROM part p
|
|
31376
|
-
WHERE p.session_id = m.session_id
|
|
31423
|
+
WHERE +p.session_id = m.session_id
|
|
31377
31424
|
AND p.message_id = m.id
|
|
31378
31425
|
AND COALESCE(json_extract(p.data, '$.type'), '') = 'text'
|
|
31379
31426
|
AND COALESCE(json_extract(p.data, '$.text'), '') = ?
|
|
@@ -31381,14 +31428,14 @@ function removeLegacyMarkerLineageRows(db, args) {
|
|
|
31381
31428
|
const legacySummaryIds = legacySummaries.flatMap((row) => typeof row.id === "string" ? [row.id] : []);
|
|
31382
31429
|
if (legacySummaryIds.length === 0)
|
|
31383
31430
|
return;
|
|
31384
|
-
const deleteSummaryParts = db.prepare("DELETE FROM part WHERE session_id = ? AND message_id = ?");
|
|
31431
|
+
const deleteSummaryParts = db.prepare("DELETE FROM part WHERE +session_id = ? AND message_id = ?");
|
|
31385
31432
|
const deleteSummary = db.prepare("DELETE FROM message WHERE session_id = ? AND id = ?");
|
|
31386
31433
|
for (const summaryMessageId of legacySummaryIds) {
|
|
31387
31434
|
deleteSummaryParts.run(args.sessionId, summaryMessageId);
|
|
31388
31435
|
deleteSummary.run(args.sessionId, summaryMessageId);
|
|
31389
31436
|
}
|
|
31390
31437
|
db.prepare(`DELETE FROM part
|
|
31391
|
-
WHERE session_id = ?
|
|
31438
|
+
WHERE +session_id = ?
|
|
31392
31439
|
AND message_id = ?
|
|
31393
31440
|
AND id <> ?
|
|
31394
31441
|
AND COALESCE(json_extract(data, '$.type'), '') = 'compaction'
|
|
@@ -31470,36 +31517,56 @@ function injectCompactionMarker(args) {
|
|
|
31470
31517
|
}
|
|
31471
31518
|
function listSessionCompactionMarkers(sessionId) {
|
|
31472
31519
|
const db = getWritableOpenCodeDb();
|
|
31473
|
-
const
|
|
31474
|
-
FROM
|
|
31520
|
+
const summaryRows = db.prepare(`SELECT id, json_extract(data, '$.parentID') AS boundary_message_id
|
|
31521
|
+
FROM message
|
|
31475
31522
|
WHERE session_id = ?
|
|
31476
|
-
AND COALESCE(json_extract(data, '$.
|
|
31477
|
-
|
|
31478
|
-
|
|
31479
|
-
|
|
31480
|
-
|
|
31481
|
-
|
|
31482
|
-
|
|
31483
|
-
AND COALESCE(json_extract(data, '$.finish'), '') = 'stop'
|
|
31484
|
-
AND COALESCE(json_extract(data, '$.providerID'), '') = 'magic-context'`);
|
|
31485
|
-
for (const row of partRows) {
|
|
31486
|
-
if (typeof row.id !== "string" || typeof row.message_id !== "string")
|
|
31523
|
+
AND COALESCE(json_extract(data, '$.summary'), 0) = 1
|
|
31524
|
+
AND COALESCE(json_extract(data, '$.finish'), '') = 'stop'
|
|
31525
|
+
AND COALESCE(json_extract(data, '$.providerID'), '') = 'magic-context'
|
|
31526
|
+
ORDER BY time_created ASC, id ASC`).all(sessionId);
|
|
31527
|
+
const summaryIdsByBoundary = new Map;
|
|
31528
|
+
for (const row of summaryRows) {
|
|
31529
|
+
if (typeof row.id !== "string" || typeof row.boundary_message_id !== "string")
|
|
31487
31530
|
continue;
|
|
31488
|
-
const
|
|
31489
|
-
|
|
31490
|
-
|
|
31491
|
-
|
|
31492
|
-
|
|
31493
|
-
|
|
31494
|
-
|
|
31531
|
+
const summaryIds = summaryIdsByBoundary.get(row.boundary_message_id) ?? [];
|
|
31532
|
+
summaryIds.push(row.id);
|
|
31533
|
+
summaryIdsByBoundary.set(row.boundary_message_id, summaryIds);
|
|
31534
|
+
}
|
|
31535
|
+
const boundaryIds = [...summaryIdsByBoundary.keys()];
|
|
31536
|
+
const markers = [];
|
|
31537
|
+
const chunkSize = 800;
|
|
31538
|
+
for (let offset = 0;offset < boundaryIds.length; offset += chunkSize) {
|
|
31539
|
+
const boundaryChunk = boundaryIds.slice(offset, offset + chunkSize);
|
|
31540
|
+
const placeholders = boundaryChunk.map(() => "?").join(", ");
|
|
31541
|
+
const partRows = db.prepare(`SELECT id, message_id, time_created
|
|
31542
|
+
FROM part
|
|
31543
|
+
WHERE +session_id = ?
|
|
31544
|
+
AND likelihood(message_id IN (${placeholders}), 0.000001)
|
|
31545
|
+
AND COALESCE(json_extract(data, '$.type'), '') = 'compaction'
|
|
31546
|
+
ORDER BY time_created ASC, id ASC`).all(sessionId, ...boundaryChunk);
|
|
31547
|
+
for (const row of partRows) {
|
|
31548
|
+
if (typeof row.id !== "string" || typeof row.message_id !== "string" || typeof row.time_created !== "number") {
|
|
31549
|
+
continue;
|
|
31550
|
+
}
|
|
31551
|
+
const summaryMessageIds = summaryIdsByBoundary.get(row.message_id);
|
|
31552
|
+
if (!summaryMessageIds)
|
|
31553
|
+
continue;
|
|
31554
|
+
markers.push({
|
|
31555
|
+
compactionPartId: row.id,
|
|
31556
|
+
boundaryMessageId: row.message_id,
|
|
31557
|
+
summaryMessageIds: [...summaryMessageIds],
|
|
31558
|
+
timeCreated: row.time_created
|
|
31559
|
+
});
|
|
31560
|
+
}
|
|
31495
31561
|
}
|
|
31496
|
-
|
|
31562
|
+
markers.sort((left, right) => left.timeCreated - right.timeCreated || left.compactionPartId.localeCompare(right.compactionPartId));
|
|
31563
|
+
return markers.map(({ timeCreated: _, ...marker }) => marker);
|
|
31497
31564
|
}
|
|
31498
31565
|
function removeForeignCompactionMarker(sessionId, marker, protectedSummaryMessageId) {
|
|
31499
31566
|
try {
|
|
31500
31567
|
const db = getWritableOpenCodeDb();
|
|
31501
31568
|
db.transaction(() => {
|
|
31502
|
-
const deletePartsOfMessage = db.prepare("DELETE FROM part WHERE session_id = ? AND message_id = ?");
|
|
31569
|
+
const deletePartsOfMessage = db.prepare("DELETE FROM part WHERE +session_id = ? AND message_id = ?");
|
|
31503
31570
|
const deleteMessage = db.prepare("DELETE FROM message WHERE session_id = ? AND id = ?");
|
|
31504
31571
|
for (const summaryMessageId of marker.summaryMessageIds) {
|
|
31505
31572
|
if (summaryMessageId === protectedSummaryMessageId)
|
|
@@ -31562,7 +31629,7 @@ function removeMcOwnedCompactionMarkers(sessionId, summaryText) {
|
|
|
31562
31629
|
AND EXISTS (
|
|
31563
31630
|
SELECT 1
|
|
31564
31631
|
FROM part p
|
|
31565
|
-
WHERE p.session_id = m.session_id
|
|
31632
|
+
WHERE +p.session_id = m.session_id
|
|
31566
31633
|
AND p.message_id = m.id
|
|
31567
31634
|
AND COALESCE(json_extract(p.data, '$.type'), '') = 'text'
|
|
31568
31635
|
AND COALESCE(json_extract(p.data, '$.text'), '') = ?
|
|
@@ -31622,7 +31689,7 @@ function removeMcOwnedCompactionMarkers(sessionId, summaryText) {
|
|
|
31622
31689
|
let removedLineages = 0;
|
|
31623
31690
|
let removedRows = 0;
|
|
31624
31691
|
let retainedLineages = 0;
|
|
31625
|
-
const deletePartsOfMessage = db.prepare("DELETE FROM part WHERE session_id = ? AND message_id = ?");
|
|
31692
|
+
const deletePartsOfMessage = db.prepare("DELETE FROM part WHERE +session_id = ? AND message_id = ?");
|
|
31626
31693
|
const deleteMessage = db.prepare("DELETE FROM message WHERE session_id = ? AND id = ?");
|
|
31627
31694
|
const deletePart = db.prepare("DELETE FROM part WHERE session_id = ? AND id = ?");
|
|
31628
31695
|
const deleteSummaries = (summaryIds) => {
|
|
@@ -33004,6 +33071,18 @@ function recordChildInvocation(input) {
|
|
|
33004
33071
|
}
|
|
33005
33072
|
}
|
|
33006
33073
|
|
|
33074
|
+
// src/hooks/magic-context/compartment-runner-types.ts
|
|
33075
|
+
class HiddenCompletionRefusal extends Error {
|
|
33076
|
+
code;
|
|
33077
|
+
terminal;
|
|
33078
|
+
constructor(code, message, terminal = false) {
|
|
33079
|
+
super(`${code}: ${message}`);
|
|
33080
|
+
this.code = code;
|
|
33081
|
+
this.terminal = terminal;
|
|
33082
|
+
this.name = "HiddenCompletionRefusal";
|
|
33083
|
+
}
|
|
33084
|
+
}
|
|
33085
|
+
|
|
33007
33086
|
// src/hooks/magic-context/compartment-runner-mapping.ts
|
|
33008
33087
|
function tierFieldsOf(c) {
|
|
33009
33088
|
return {
|
|
@@ -33250,6 +33329,61 @@ function historianMessageCreatedAt(message) {
|
|
|
33250
33329
|
return 0;
|
|
33251
33330
|
return typeof message.info.time.created === "number" ? message.info.time.created : 0;
|
|
33252
33331
|
}
|
|
33332
|
+
function createV1HiddenCompletionExecutor(client, db, directory) {
|
|
33333
|
+
return {
|
|
33334
|
+
capabilities: { tools: true, harness: "opencode" },
|
|
33335
|
+
async open(run) {
|
|
33336
|
+
if (!client)
|
|
33337
|
+
throw new Error("Hidden completion client is unavailable");
|
|
33338
|
+
const response = await createChildSessionWithFence({
|
|
33339
|
+
client,
|
|
33340
|
+
db,
|
|
33341
|
+
parentSessionId: run.parentSessionId,
|
|
33342
|
+
title: run.title,
|
|
33343
|
+
directory: run.directory
|
|
33344
|
+
});
|
|
33345
|
+
const created = normalizeSDKResponse(response, null, {
|
|
33346
|
+
preferResponseOnMissingData: true
|
|
33347
|
+
});
|
|
33348
|
+
const id = typeof created?.id === "string" ? created.id : "";
|
|
33349
|
+
return { id, childSessionId: id || undefined };
|
|
33350
|
+
},
|
|
33351
|
+
async attempt(_handle, request) {
|
|
33352
|
+
if (!client)
|
|
33353
|
+
throw new Error("Hidden completion client is unavailable");
|
|
33354
|
+
await client.session.prompt(request);
|
|
33355
|
+
},
|
|
33356
|
+
async collect(handle, limit) {
|
|
33357
|
+
if (!client)
|
|
33358
|
+
throw new Error("Hidden completion client is unavailable");
|
|
33359
|
+
const response = await client.session.messages({
|
|
33360
|
+
path: { id: handle.id },
|
|
33361
|
+
query: { directory, limit }
|
|
33362
|
+
});
|
|
33363
|
+
const messages = normalizeSDKResponse(response, [], {
|
|
33364
|
+
preferResponseOnMissingData: true
|
|
33365
|
+
});
|
|
33366
|
+
const text = extractLatestAssistantText(messages);
|
|
33367
|
+
return {
|
|
33368
|
+
messages,
|
|
33369
|
+
text,
|
|
33370
|
+
reasoning: text ? null : extractLatestHistorianReasoning(messages),
|
|
33371
|
+
lengthCapped: hasLengthCappedOutput(messages),
|
|
33372
|
+
usage: sumTokensFromChildMessages(messages)
|
|
33373
|
+
};
|
|
33374
|
+
},
|
|
33375
|
+
async close(handle, settlement) {
|
|
33376
|
+
if (!client)
|
|
33377
|
+
return;
|
|
33378
|
+
await teardownChildSession({
|
|
33379
|
+
client,
|
|
33380
|
+
sessionId: handle?.id || null,
|
|
33381
|
+
sessionDirectory: directory,
|
|
33382
|
+
...settlement
|
|
33383
|
+
});
|
|
33384
|
+
}
|
|
33385
|
+
};
|
|
33386
|
+
}
|
|
33253
33387
|
async function runValidatedHistorianPass(args) {
|
|
33254
33388
|
const firstRun = await runHistorianPrompt({
|
|
33255
33389
|
...args,
|
|
@@ -33258,6 +33392,8 @@ async function runValidatedHistorianPass(args) {
|
|
|
33258
33392
|
agentId: args.agentId
|
|
33259
33393
|
});
|
|
33260
33394
|
if (!firstRun.ok || !firstRun.result) {
|
|
33395
|
+
if (firstRun.refusal?.terminal)
|
|
33396
|
+
return { ok: false, error: firstRun.error ?? firstRun.refusal.message };
|
|
33261
33397
|
return runFallbackHistorianPass({
|
|
33262
33398
|
...args,
|
|
33263
33399
|
prompt: args.prompt,
|
|
@@ -33287,6 +33423,8 @@ async function runValidatedHistorianPass(args) {
|
|
|
33287
33423
|
agentId: args.agentId
|
|
33288
33424
|
});
|
|
33289
33425
|
if (!repairRun.ok || !repairRun.result) {
|
|
33426
|
+
if (repairRun.refusal?.terminal)
|
|
33427
|
+
return { ok: false, error: repairRun.error ?? repairRun.refusal.message };
|
|
33290
33428
|
return runFallbackHistorianPass({
|
|
33291
33429
|
...args,
|
|
33292
33430
|
prompt: repairPrompt,
|
|
@@ -33317,11 +33455,14 @@ async function runEditorPassOrFallback(args) {
|
|
|
33317
33455
|
sessionLog(args.parentSessionId, "historian two-pass: running editor on draft");
|
|
33318
33456
|
const editorRun = await runHistorianPrompt({
|
|
33319
33457
|
client: args.client,
|
|
33458
|
+
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
33320
33459
|
db: args.db,
|
|
33321
33460
|
parentSessionId: args.parentSessionId,
|
|
33322
33461
|
sessionDirectory: args.sessionDirectory,
|
|
33323
33462
|
prompt: buildHistorianEditorPrompt(args.draftXml),
|
|
33324
33463
|
timeoutMs: args.timeoutMs,
|
|
33464
|
+
maxOutputTokens: args.maxOutputTokens,
|
|
33465
|
+
language: args.language,
|
|
33325
33466
|
dumpLabel: `${args.dumpLabelBase}-editor`,
|
|
33326
33467
|
agentId: HISTORIAN_EDITOR_AGENT,
|
|
33327
33468
|
parentInvocationId: args.draftInvocationId ?? null,
|
|
@@ -33358,6 +33499,9 @@ async function runHistorianPrompt(args) {
|
|
|
33358
33499
|
parentInvocationId
|
|
33359
33500
|
} = args;
|
|
33360
33501
|
let agentSessionId = null;
|
|
33502
|
+
let handle = null;
|
|
33503
|
+
let completion;
|
|
33504
|
+
const executor = args.hiddenCompletionExecutor ?? createV1HiddenCompletionExecutor(client, db, sessionDirectory);
|
|
33361
33505
|
let promptSettled = false;
|
|
33362
33506
|
let hadUnsettledPrompt = false;
|
|
33363
33507
|
const startedAt = Date.now();
|
|
@@ -33369,26 +33513,41 @@ async function runHistorianPrompt(args) {
|
|
|
33369
33513
|
return recordChildInvocation({
|
|
33370
33514
|
db: openDatabase(),
|
|
33371
33515
|
parentSessionId,
|
|
33372
|
-
harness:
|
|
33516
|
+
harness: executor.capabilities.harness,
|
|
33373
33517
|
subagent: agentId === HISTORIAN_EDITOR_AGENT ? "historian_editor" : subagentKind ?? "historian",
|
|
33374
33518
|
startedAt,
|
|
33375
33519
|
status: params.status,
|
|
33376
33520
|
messages: params.messages,
|
|
33521
|
+
...completion && !completion.messages ? {
|
|
33522
|
+
tokens: completion.usage,
|
|
33523
|
+
providerId: completion.providerId,
|
|
33524
|
+
modelId: completion.modelId
|
|
33525
|
+
} : {},
|
|
33377
33526
|
error: params.error,
|
|
33378
33527
|
parentInvocationId: agentId === HISTORIAN_EDITOR_AGENT ? parentInvocationId ?? null : null
|
|
33379
33528
|
});
|
|
33380
33529
|
};
|
|
33381
33530
|
try {
|
|
33382
33531
|
sessionLog(parentSessionId, `historian: creating child session (agent=${toModelEntry(modelOverride)?.model ?? `agent:${agentId}`})`);
|
|
33383
|
-
|
|
33384
|
-
client,
|
|
33385
|
-
db,
|
|
33532
|
+
handle = await executor.open({
|
|
33386
33533
|
parentSessionId,
|
|
33534
|
+
parentInvocationId,
|
|
33535
|
+
agent: agentId,
|
|
33536
|
+
kind: agentId === HISTORIAN_EDITOR_AGENT ? "historian-editor" : "historian",
|
|
33537
|
+
system: withContentLanguageDirective(agentId === HISTORIAN_EDITOR_AGENT ? HISTORIAN_EDITOR_SYSTEM_PROMPT : COMPARTMENT_AGENT_SYSTEM_PROMPT, args.language),
|
|
33538
|
+
maxOutputTokens: args.maxOutputTokens,
|
|
33539
|
+
model: modelOverride,
|
|
33540
|
+
configuredModels: [
|
|
33541
|
+
...modelOverride ? [modelOverride] : [],
|
|
33542
|
+
...fallbackModels ?? []
|
|
33543
|
+
],
|
|
33544
|
+
timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
33387
33545
|
title: "magic-context-compartment",
|
|
33388
|
-
directory: sessionDirectory
|
|
33546
|
+
directory: sessionDirectory,
|
|
33547
|
+
metadata: { dumpLabel, subagentKind }
|
|
33389
33548
|
});
|
|
33390
|
-
|
|
33391
|
-
|
|
33549
|
+
agentSessionId = handle.id || null;
|
|
33550
|
+
const opened = handle;
|
|
33392
33551
|
if (!agentSessionId) {
|
|
33393
33552
|
recordInvocation({
|
|
33394
33553
|
status: "failed",
|
|
@@ -33407,6 +33566,7 @@ async function runHistorianPrompt(args) {
|
|
|
33407
33566
|
parts: [{ type: "text", text: prompt, synthetic: true }]
|
|
33408
33567
|
}
|
|
33409
33568
|
}, {
|
|
33569
|
+
transport: Object.assign((request) => executor.attempt(opened, request), { childSessionId: opened.childSessionId }),
|
|
33410
33570
|
timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
33411
33571
|
fallbackModels: modelOverride ? undefined : fallbackModels,
|
|
33412
33572
|
callContext: agentId === HISTORIAN_EDITOR_AGENT ? "historian:editor" : "historian"
|
|
@@ -33428,19 +33588,16 @@ async function runHistorianPrompt(args) {
|
|
|
33428
33588
|
await sleep(backoffMs);
|
|
33429
33589
|
}
|
|
33430
33590
|
}
|
|
33431
|
-
|
|
33432
|
-
|
|
33433
|
-
|
|
33434
|
-
|
|
33435
|
-
const messages = normalizeSDKResponse(messagesResponse, [], {
|
|
33436
|
-
preferResponseOnMissingData: true
|
|
33591
|
+
completion = await executor.collect(handle, 50);
|
|
33592
|
+
const invocationId = recordInvocation({
|
|
33593
|
+
status: "completed",
|
|
33594
|
+
messages: completion.messages
|
|
33437
33595
|
});
|
|
33438
|
-
const
|
|
33439
|
-
const
|
|
33440
|
-
const
|
|
33441
|
-
const reasoningResult = textResult ? null : extractLatestHistorianReasoning(messages);
|
|
33596
|
+
const lengthCapped = completion.lengthCapped;
|
|
33597
|
+
const textResult = completion.text;
|
|
33598
|
+
const reasoningResult = textResult ? null : completion.reasoning;
|
|
33442
33599
|
if (!textResult && reasoningResult && lengthCapped) {
|
|
33443
|
-
const outputTokens =
|
|
33600
|
+
const outputTokens = completion.usage.output;
|
|
33444
33601
|
return {
|
|
33445
33602
|
ok: false,
|
|
33446
33603
|
error: `historian output length-capped at ${outputTokens} tokens (all reasoning, no text) — set historian.maxTokens or route historian.model to a low-reasoning lane/variant`,
|
|
@@ -33463,13 +33620,11 @@ async function runHistorianPrompt(args) {
|
|
|
33463
33620
|
recordInvocation({ status: "failed", error: modelError });
|
|
33464
33621
|
return {
|
|
33465
33622
|
ok: false,
|
|
33466
|
-
error: `Historian failed while processing this session: ${desc.brief}
|
|
33623
|
+
error: `Historian failed while processing this session: ${desc.brief}`,
|
|
33624
|
+
...modelError instanceof HiddenCompletionRefusal ? { refusal: modelError } : {}
|
|
33467
33625
|
};
|
|
33468
33626
|
} finally {
|
|
33469
|
-
await
|
|
33470
|
-
client,
|
|
33471
|
-
sessionId: agentSessionId,
|
|
33472
|
-
sessionDirectory,
|
|
33627
|
+
await executor.close(handle, {
|
|
33473
33628
|
promptSettled,
|
|
33474
33629
|
privacySensitive: false,
|
|
33475
33630
|
context: "historian",
|
|
@@ -33511,11 +33666,14 @@ async function runFallbackHistorianPass(args) {
|
|
|
33511
33666
|
args.callbacks?.onModelFallback?.(modelId, i + 1, chain.length);
|
|
33512
33667
|
const fallbackRun = await runHistorianPrompt({
|
|
33513
33668
|
client: args.client,
|
|
33669
|
+
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
33514
33670
|
db: args.db,
|
|
33515
33671
|
parentSessionId: args.parentSessionId,
|
|
33516
33672
|
sessionDirectory: args.sessionDirectory,
|
|
33517
33673
|
prompt: args.prompt,
|
|
33518
33674
|
timeoutMs: args.timeoutMs,
|
|
33675
|
+
maxOutputTokens: args.maxOutputTokens,
|
|
33676
|
+
language: args.language,
|
|
33519
33677
|
dumpLabel: `${args.dumpLabelBase}-fallback-${i + 1}`,
|
|
33520
33678
|
modelOverride,
|
|
33521
33679
|
agentId: args.agentId
|
|
@@ -39342,7 +39500,7 @@ async function runCompartmentAgent(deps) {
|
|
|
39342
39500
|
const invocationId = latest != null && (invocationBaseline == null || latest > invocationBaseline) ? latest : null;
|
|
39343
39501
|
recordHistorianRun(db, {
|
|
39344
39502
|
sessionId,
|
|
39345
|
-
harness: "opencode",
|
|
39503
|
+
harness: deps.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
|
|
39346
39504
|
subagentInvocationId: invocationId,
|
|
39347
39505
|
runKind: telemetry.runKind ?? "incremental",
|
|
39348
39506
|
status: telemetry.status ?? "failed",
|
|
@@ -39566,7 +39724,7 @@ async function runCompartmentAgent(deps) {
|
|
|
39566
39724
|
${chunkText}`,
|
|
39567
39725
|
memoryEnabled: deps.memoryEnabled !== false
|
|
39568
39726
|
});
|
|
39569
|
-
const parentSessionResponse = await client
|
|
39727
|
+
const parentSessionResponse = await client?.session.get({ path: { id: sessionId } }).catch(() => null);
|
|
39570
39728
|
const parentSession = normalizeSDKResponse(parentSessionResponse, null, { preferResponseOnMissingData: true });
|
|
39571
39729
|
const sessionDirectory = parentSession?.directory ?? directory;
|
|
39572
39730
|
const maxExistingSequence = priorCompartments.reduce((max, c) => c.sequence > max ? c.sequence : max, -1);
|
|
@@ -39574,6 +39732,7 @@ ${chunkText}`,
|
|
|
39574
39732
|
retainDrainReservationForRetryThrottle = true;
|
|
39575
39733
|
const validatedPass = await runValidatedHistorianPass({
|
|
39576
39734
|
client,
|
|
39735
|
+
hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
|
|
39577
39736
|
db,
|
|
39578
39737
|
parentSessionId: sessionId,
|
|
39579
39738
|
sessionDirectory,
|
|
@@ -39583,6 +39742,7 @@ ${chunkText}`,
|
|
|
39583
39742
|
sequenceOffset,
|
|
39584
39743
|
dumpLabelBase: `incremental-${sessionId}-${chunk.startIndex}-${chunk.endIndex}`,
|
|
39585
39744
|
timeoutMs: historianTimeoutMs,
|
|
39745
|
+
maxOutputTokens: deps.historianMaxOutputTokens,
|
|
39586
39746
|
model: deps.model,
|
|
39587
39747
|
fallbackModelId: deps.fallbackModelId,
|
|
39588
39748
|
fallbackModels: deps.fallbackModels,
|
|
@@ -39696,7 +39856,7 @@ ${chunkText}`,
|
|
|
39696
39856
|
clearEmergencyRecovery(db, sessionId);
|
|
39697
39857
|
drainReservation = null;
|
|
39698
39858
|
if (deferMarkerApplication && lastNewEndMessageId) {
|
|
39699
|
-
setPendingCompactionMarkerState(db, sessionId, {
|
|
39859
|
+
(deps.compactionMarkerStrategy?.setPending ?? setPendingCompactionMarkerState)(db, sessionId, {
|
|
39700
39860
|
ordinal: lastCompartmentEnd,
|
|
39701
39861
|
endMessageId: lastNewEndMessageId,
|
|
39702
39862
|
publishedAt: Date.now()
|
|
@@ -39719,7 +39879,7 @@ ${chunkText}`,
|
|
|
39719
39879
|
if (deferMarkerApplication) {
|
|
39720
39880
|
deps.onDeferredMarkerPending?.(sessionId);
|
|
39721
39881
|
} else {
|
|
39722
|
-
updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEnd, sessionDirectory);
|
|
39882
|
+
(deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId, lastCompartmentEnd, sessionDirectory);
|
|
39723
39883
|
}
|
|
39724
39884
|
updateSessionMeta2(db, sessionId, { compartmentInProgress: false });
|
|
39725
39885
|
completedSuccessfully = true;
|
|
@@ -39798,7 +39958,7 @@ ${chunkText}`,
|
|
|
39798
39958
|
const stored = insertPrimerCandidates(db, [
|
|
39799
39959
|
{
|
|
39800
39960
|
projectPath: promotionProjectIdentity,
|
|
39801
|
-
harness: "opencode",
|
|
39961
|
+
harness: deps.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
|
|
39802
39962
|
sessionId,
|
|
39803
39963
|
question: candidate.question,
|
|
39804
39964
|
sourceCompartmentStart: startC?.startMessage,
|
|
@@ -41355,4 +41515,4 @@ async function runUpgradeMemoryMigration(ctx, sessionId, migrationDirectory) {
|
|
|
41355
41515
|
}
|
|
41356
41516
|
}
|
|
41357
41517
|
|
|
41358
|
-
export { withContentLanguageDirective, buildPrimaryLanguageDirective, setJsoncValue, removeJsoncValue, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, MagicContextConfigSchema, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, directoryHasGitMetadata, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, applyMirroredNoteCompileFields, drainMirrorPages, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, isRecord, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, updateTagMessageId, markTagsCompactedByMessageIds, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, createDroppedInputToolExecuteBeforeHook, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, readRawSessionSeedTail, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, readFrozenMergedReasoningParts, getProtectionWindowForSession, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getSessionsWithPendingMarker, setSessionWorkMetrics, getObservedEpochFloor, resolveEpochFloorForPass, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNotes, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, detectThinkingBindingMismatch, isFable51ThinkingBindingModel, detectOverflow, modelBodyField, toModelEntry, getPromptFailureDetail, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, teardownChildSession, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, capabilityRefusalCode, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, getCompartmentEvents, SYNAPSE_DEFAULT_MODEL, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, SynapseEmbeddingProvider, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, computeNormalizedHash, getLocalEmbeddingNativeMemoryStats, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, describeShadowBackfillWriteRefusal, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, recordChildInvocation, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, beginLkgPass, visitMessageContentFields, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getInMemorySlot, getSlot, dropSlot, noteEntry, getLkgSlotHeapStats, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, setRecompStarting2, setRecompTerminal2, runManagedRecomp2, runManagedUpgrade2 };
|
|
41518
|
+
export { withContentLanguageDirective, buildPrimaryLanguageDirective, setJsoncValue, removeJsoncValue, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, MagicContextConfigSchema, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, directoryHasGitMetadata, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMemoryMirrorStatus, applyMirroredNoteCompileFields, drainMirrorPages, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, isRecord, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, updateTagMessageId, markTagsCompactedByMessageIds, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, assertExecutableToolInput, createDroppedInputToolExecuteBeforeHook, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, readRawSessionSeedTail, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, readFrozenMergedReasoningParts, getProtectionWindowForSession, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getSessionsWithPendingMarker, setSessionWorkMetrics, getObservedEpochFloor, resolveEpochFloorForPass, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNotes, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, detectThinkingBindingMismatch, isFable51ThinkingBindingModel, detectOverflow, modelBodyField, toModelEntry, getPromptFailureDetail, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, teardownChildSession, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, capabilityRefusalCode, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, getCompartmentEvents, SYNAPSE_DEFAULT_MODEL, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, SynapseEmbeddingProvider, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, computeNormalizedHash, getLocalEmbeddingNativeMemoryStats, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, describeShadowBackfillWriteRefusal, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, recordChildInvocation, createV1HiddenCompletionExecutor, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, beginLkgPass, visitMessageContentFields, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getInMemorySlot, getSlot, dropSlot, noteEntry, getLkgSlotHeapStats, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, setRecompStarting2, setRecompTerminal2, runManagedRecomp2, runManagedUpgrade2 };
|