@cortexkit/pi-magic-context 0.36.1 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-npnqc564.js → index-hk6sj7dn.js} +13 -8
- package/dist/{index-zxgbtsnj.js → index-kvttksef.js} +1020 -192
- package/dist/index.js +159 -63
- package/dist/{safe-notification-target-0s6j4m9f.js → safe-notification-target-7n7s6xv7.js} +1 -1
- package/dist/subagent-entry.js +2 -2
- package/package.json +2 -1
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
getMagicContextStorageDir,
|
|
6
6
|
log,
|
|
7
7
|
sessionLog
|
|
8
|
-
} from "./index-
|
|
8
|
+
} from "./index-hk6sj7dn.js";
|
|
9
9
|
import {
|
|
10
10
|
__commonJS,
|
|
11
11
|
__export,
|
|
@@ -7696,10 +7696,10 @@ var require_stringify = __commonJS((exports, module) => {
|
|
|
7696
7696
|
replacer = null;
|
|
7697
7697
|
indent = EMPTY;
|
|
7698
7698
|
};
|
|
7699
|
-
var
|
|
7699
|
+
var join8 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two)), gap) : EMPTY;
|
|
7700
7700
|
var join_content = (inside, value, gap) => {
|
|
7701
7701
|
const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
|
|
7702
|
-
return
|
|
7702
|
+
return join8(comment, inside, gap);
|
|
7703
7703
|
};
|
|
7704
7704
|
var stringify_string = (holder, key, value) => {
|
|
7705
7705
|
const raw = get_raw_string_literal(holder, key);
|
|
@@ -7721,13 +7721,13 @@ var require_stringify = __commonJS((exports, module) => {
|
|
|
7721
7721
|
if (i !== 0) {
|
|
7722
7722
|
inside += COMMA;
|
|
7723
7723
|
}
|
|
7724
|
-
const before =
|
|
7724
|
+
const before = join8(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
|
|
7725
7725
|
inside += before || LF + deeper_gap;
|
|
7726
7726
|
inside += stringify(i, value, deeper_gap) || STR_NULL;
|
|
7727
7727
|
inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
|
|
7728
7728
|
after_comma = process_comments(value, AFTER(i), deeper_gap);
|
|
7729
7729
|
}
|
|
7730
|
-
inside +=
|
|
7730
|
+
inside += join8(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
|
|
7731
7731
|
return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
|
|
7732
7732
|
};
|
|
7733
7733
|
var object_stringify = (value, gap) => {
|
|
@@ -7748,13 +7748,13 @@ var require_stringify = __commonJS((exports, module) => {
|
|
|
7748
7748
|
inside += COMMA;
|
|
7749
7749
|
}
|
|
7750
7750
|
first = false;
|
|
7751
|
-
const before =
|
|
7751
|
+
const before = join8(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
|
|
7752
7752
|
inside += before || LF + deeper_gap;
|
|
7753
7753
|
inside += quote(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
|
|
7754
7754
|
after_comma = process_comments(value, AFTER(key), deeper_gap);
|
|
7755
7755
|
};
|
|
7756
7756
|
keys.forEach(iteratee);
|
|
7757
|
-
inside +=
|
|
7757
|
+
inside += join8(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
|
|
7758
7758
|
return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
|
|
7759
7759
|
};
|
|
7760
7760
|
function stringify(key, holder, gap) {
|
|
@@ -8292,6 +8292,7 @@ import path from "node:path";
|
|
|
8292
8292
|
var GIT_TIMEOUT_MS = 5000;
|
|
8293
8293
|
var TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
|
|
8294
8294
|
var identityCache = new Map;
|
|
8295
|
+
var linkedGitWorktreeCache = new Map;
|
|
8295
8296
|
var lastKnownGitIdentityCache = new Map;
|
|
8296
8297
|
var directoryFallbackCache = new Map;
|
|
8297
8298
|
var transientFailureCooldown = new Map;
|
|
@@ -8497,7 +8498,12 @@ function recordDubiousOwnershipFallback(canonical) {
|
|
|
8497
8498
|
log(`[magic-context] ${formatDubiousOwnershipWarning(canonical)}`);
|
|
8498
8499
|
}
|
|
8499
8500
|
function canonicalUserHomeDirectory() {
|
|
8500
|
-
|
|
8501
|
+
const homeDirectory = userHomeDirectoryForIdentity();
|
|
8502
|
+
try {
|
|
8503
|
+
return realpathSync.native(homeDirectory);
|
|
8504
|
+
} catch {
|
|
8505
|
+
return homeDirectory;
|
|
8506
|
+
}
|
|
8501
8507
|
}
|
|
8502
8508
|
function isUserHomeDirectory(directory) {
|
|
8503
8509
|
try {
|
|
@@ -8953,6 +8959,58 @@ function mergeCommitHashes(existing, next) {
|
|
|
8953
8959
|
return merged;
|
|
8954
8960
|
}
|
|
8955
8961
|
|
|
8962
|
+
// ../plugin/src/shared/harness-provider-map.ts
|
|
8963
|
+
var CANONICAL_TO_PI_PROVIDER = {
|
|
8964
|
+
openai: "openai-codex",
|
|
8965
|
+
google: "google-antigravity"
|
|
8966
|
+
};
|
|
8967
|
+
var PI_TO_CANONICAL_PROVIDER = {
|
|
8968
|
+
"openai-codex": "openai",
|
|
8969
|
+
"google-antigravity": "google"
|
|
8970
|
+
};
|
|
8971
|
+
var CANONICAL_TO_OMP_PROVIDER = {
|
|
8972
|
+
openai: "openai-codex",
|
|
8973
|
+
google: "google-antigravity"
|
|
8974
|
+
};
|
|
8975
|
+
var OMP_TO_CANONICAL_PROVIDER = {
|
|
8976
|
+
"openai-codex": "openai",
|
|
8977
|
+
"google-antigravity": "google"
|
|
8978
|
+
};
|
|
8979
|
+
function remapProviderPrefix(ref, map) {
|
|
8980
|
+
if (typeof ref !== "string")
|
|
8981
|
+
return ref;
|
|
8982
|
+
const slash = ref.indexOf("/");
|
|
8983
|
+
if (slash <= 0)
|
|
8984
|
+
return ref;
|
|
8985
|
+
const provider = ref.slice(0, slash);
|
|
8986
|
+
if (!Object.hasOwn(map, provider))
|
|
8987
|
+
return ref;
|
|
8988
|
+
return `${map[provider]}${ref.slice(slash)}`;
|
|
8989
|
+
}
|
|
8990
|
+
function piModelRefToCanonical(ref) {
|
|
8991
|
+
return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
|
|
8992
|
+
}
|
|
8993
|
+
function resolveModelRefForPi(ref) {
|
|
8994
|
+
return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
|
|
8995
|
+
}
|
|
8996
|
+
function modelRefLookupOrder(ref) {
|
|
8997
|
+
const canonical = piModelRefToCanonical(ompModelRefToCanonical(ref));
|
|
8998
|
+
return [
|
|
8999
|
+
...new Set([
|
|
9000
|
+
canonical,
|
|
9001
|
+
ref,
|
|
9002
|
+
resolveModelRefForPi(canonical),
|
|
9003
|
+
resolveModelRefForOmp(canonical)
|
|
9004
|
+
])
|
|
9005
|
+
];
|
|
9006
|
+
}
|
|
9007
|
+
function ompModelRefToCanonical(ref) {
|
|
9008
|
+
return remapProviderPrefix(ref, OMP_TO_CANONICAL_PROVIDER);
|
|
9009
|
+
}
|
|
9010
|
+
function resolveModelRefForOmp(ref) {
|
|
9011
|
+
return remapProviderPrefix(ompModelRefToCanonical(ref), CANONICAL_TO_OMP_PROVIDER);
|
|
9012
|
+
}
|
|
9013
|
+
|
|
8956
9014
|
// ../plugin/src/shared/storage-permissions.ts
|
|
8957
9015
|
var enforcePrivateStoragePermissions = true;
|
|
8958
9016
|
function setStoragePrivatePermissionEnforcement(enforce) {
|
|
@@ -9057,20 +9115,24 @@ import { execFileSync as execFileSync2 } from "node:child_process";
|
|
|
9057
9115
|
import { readFileSync as readFileSync3 } from "node:fs";
|
|
9058
9116
|
function isPidAlive(pid) {
|
|
9059
9117
|
if (!Number.isInteger(pid) || pid <= 0)
|
|
9060
|
-
return
|
|
9118
|
+
return "dead";
|
|
9119
|
+
if (rpcIdentityPlatform === "win32")
|
|
9120
|
+
return readWindowsProcess(pid).state;
|
|
9061
9121
|
try {
|
|
9062
|
-
|
|
9063
|
-
return
|
|
9064
|
-
} catch (
|
|
9065
|
-
return
|
|
9122
|
+
rpcIdentityProcessKill(pid, 0);
|
|
9123
|
+
return "alive";
|
|
9124
|
+
} catch (error) {
|
|
9125
|
+
return error.code === "ESRCH" ? "dead" : "inconclusive";
|
|
9066
9126
|
}
|
|
9067
9127
|
}
|
|
9068
9128
|
var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
|
|
9069
9129
|
var LINUX_CLOCK_TICKS_PER_SECOND = 100;
|
|
9070
9130
|
var PS_PROBE_TIMEOUT_MS = 1000;
|
|
9071
9131
|
var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
|
|
9132
|
+
var TASKLIST_NO_TASKS_PATTERN = /^INFO:\s+No tasks are running which match the specified criteria\.?$/im;
|
|
9072
9133
|
var rpcIdentityReadFileSync = readFileSync3;
|
|
9073
9134
|
var rpcIdentityExecFileSync = execFileSync2;
|
|
9135
|
+
var rpcIdentityProcessKill = process.kill;
|
|
9074
9136
|
var rpcProcessListExecFileSync = execFileSync2;
|
|
9075
9137
|
var rpcIdentityPlatform = process.platform;
|
|
9076
9138
|
var rpcIdentityNowMs = () => Date.now();
|
|
@@ -9100,7 +9162,8 @@ function readPsProcessStartTime(pid) {
|
|
|
9100
9162
|
try {
|
|
9101
9163
|
const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
|
|
9102
9164
|
encoding: "utf8",
|
|
9103
|
-
timeout: PS_PROBE_TIMEOUT_MS
|
|
9165
|
+
timeout: PS_PROBE_TIMEOUT_MS,
|
|
9166
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
9104
9167
|
});
|
|
9105
9168
|
const processStartTime = Date.parse(String(output).trim());
|
|
9106
9169
|
return Number.isFinite(processStartTime) ? processStartTime : null;
|
|
@@ -9108,6 +9171,70 @@ function readPsProcessStartTime(pid) {
|
|
|
9108
9171
|
return null;
|
|
9109
9172
|
}
|
|
9110
9173
|
}
|
|
9174
|
+
function parseCsvLine(line) {
|
|
9175
|
+
const fields = [];
|
|
9176
|
+
let field = "";
|
|
9177
|
+
let quoted = false;
|
|
9178
|
+
for (let index = 0;index < line.length; index += 1) {
|
|
9179
|
+
const character = line[index];
|
|
9180
|
+
if (character === '"') {
|
|
9181
|
+
if (quoted && line[index + 1] === '"') {
|
|
9182
|
+
field += '"';
|
|
9183
|
+
index += 1;
|
|
9184
|
+
} else {
|
|
9185
|
+
quoted = !quoted;
|
|
9186
|
+
}
|
|
9187
|
+
} else if (character === "," && !quoted) {
|
|
9188
|
+
fields.push(field);
|
|
9189
|
+
field = "";
|
|
9190
|
+
} else {
|
|
9191
|
+
field += character;
|
|
9192
|
+
}
|
|
9193
|
+
}
|
|
9194
|
+
if (quoted)
|
|
9195
|
+
return null;
|
|
9196
|
+
fields.push(field);
|
|
9197
|
+
return fields;
|
|
9198
|
+
}
|
|
9199
|
+
function parseTasklistOutput(output) {
|
|
9200
|
+
const entries = [];
|
|
9201
|
+
let sawHeader = false;
|
|
9202
|
+
for (const rawLine of output.split(/\r?\n/)) {
|
|
9203
|
+
const line = rawLine.trim();
|
|
9204
|
+
if (!line)
|
|
9205
|
+
continue;
|
|
9206
|
+
if (TASKLIST_NO_TASKS_PATTERN.test(line))
|
|
9207
|
+
return [];
|
|
9208
|
+
const fields = parseCsvLine(line);
|
|
9209
|
+
if (!fields)
|
|
9210
|
+
continue;
|
|
9211
|
+
if (fields[1]?.trim().toLowerCase() === "pid") {
|
|
9212
|
+
sawHeader = true;
|
|
9213
|
+
continue;
|
|
9214
|
+
}
|
|
9215
|
+
const pid = Number(fields[1]);
|
|
9216
|
+
if (!Number.isInteger(pid) || pid <= 0 || !fields[0])
|
|
9217
|
+
continue;
|
|
9218
|
+
entries.push({ pid, command: fields[0] });
|
|
9219
|
+
}
|
|
9220
|
+
return entries.length > 0 || sawHeader ? entries : null;
|
|
9221
|
+
}
|
|
9222
|
+
function readWindowsProcess(pid) {
|
|
9223
|
+
try {
|
|
9224
|
+
const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/FI", `PID eq ${pid}`], {
|
|
9225
|
+
encoding: "utf8",
|
|
9226
|
+
timeout: PS_PROBE_TIMEOUT_MS,
|
|
9227
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
9228
|
+
});
|
|
9229
|
+
const entries = parseTasklistOutput(String(output));
|
|
9230
|
+
if (entries === null)
|
|
9231
|
+
return { state: "inconclusive" };
|
|
9232
|
+
const process2 = entries.find((entry) => entry.pid === pid);
|
|
9233
|
+
return process2 ? { state: "alive", command: process2.command } : { state: "dead" };
|
|
9234
|
+
} catch {
|
|
9235
|
+
return { state: "inconclusive" };
|
|
9236
|
+
}
|
|
9237
|
+
}
|
|
9111
9238
|
function readLinuxProcessCommand(pid) {
|
|
9112
9239
|
try {
|
|
9113
9240
|
return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
|
|
@@ -9119,7 +9246,8 @@ function readPsProcessCommand(pid) {
|
|
|
9119
9246
|
try {
|
|
9120
9247
|
const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "command="], {
|
|
9121
9248
|
encoding: "utf8",
|
|
9122
|
-
timeout: PS_PROBE_TIMEOUT_MS
|
|
9249
|
+
timeout: PS_PROBE_TIMEOUT_MS,
|
|
9250
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
9123
9251
|
});
|
|
9124
9252
|
return String(output);
|
|
9125
9253
|
} catch {
|
|
@@ -9132,17 +9260,17 @@ function commandLooksLikeOpenCode(command) {
|
|
|
9132
9260
|
}
|
|
9133
9261
|
function isPidIdentityPlausible(record) {
|
|
9134
9262
|
if (!Number.isInteger(record.pid) || record.pid <= 0)
|
|
9135
|
-
return
|
|
9263
|
+
return "implausible";
|
|
9136
9264
|
if (Number.isFinite(record.started_at) && record.started_at > 0) {
|
|
9137
|
-
const processStartTime = rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(record.pid) : readPsProcessStartTime(record.pid);
|
|
9265
|
+
const processStartTime = rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(record.pid) : rpcIdentityPlatform === "win32" ? null : readPsProcessStartTime(record.pid);
|
|
9138
9266
|
if (processStartTime === null)
|
|
9139
|
-
return
|
|
9140
|
-
return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS;
|
|
9267
|
+
return "inconclusive";
|
|
9268
|
+
return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS ? "plausible" : "implausible";
|
|
9141
9269
|
}
|
|
9142
|
-
const command = rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : readPsProcessCommand(record.pid);
|
|
9270
|
+
const command = rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(record.pid).command ?? null : readPsProcessCommand(record.pid);
|
|
9143
9271
|
if (command === null)
|
|
9144
|
-
return
|
|
9145
|
-
return commandLooksLikeOpenCode(command);
|
|
9272
|
+
return "inconclusive";
|
|
9273
|
+
return commandLooksLikeOpenCode(command) ? "plausible" : "implausible";
|
|
9146
9274
|
}
|
|
9147
9275
|
function commandLooksLikePi(command) {
|
|
9148
9276
|
const normalized = command.trim().toLowerCase().replaceAll("\\", "/");
|
|
@@ -9160,20 +9288,39 @@ function commandLooksLikePi(command) {
|
|
|
9160
9288
|
function inspectLivePiProcesses() {
|
|
9161
9289
|
if (false) {}
|
|
9162
9290
|
try {
|
|
9163
|
-
const
|
|
9291
|
+
const isWindows = rpcIdentityPlatform === "win32";
|
|
9292
|
+
const output = String(rpcProcessListExecFileSync(isWindows ? "tasklist" : "ps", isWindows ? ["/FO", "CSV"] : ["-axo", "pid=,command="], {
|
|
9164
9293
|
encoding: "utf8",
|
|
9165
|
-
timeout: PS_PROBE_TIMEOUT_MS
|
|
9294
|
+
timeout: PS_PROBE_TIMEOUT_MS,
|
|
9295
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
9166
9296
|
}));
|
|
9167
9297
|
const pids = new Set;
|
|
9168
|
-
|
|
9169
|
-
const
|
|
9170
|
-
if (
|
|
9171
|
-
|
|
9172
|
-
|
|
9173
|
-
|
|
9174
|
-
|
|
9175
|
-
|
|
9176
|
-
|
|
9298
|
+
if (isWindows) {
|
|
9299
|
+
const entries = parseTasklistOutput(output);
|
|
9300
|
+
if (entries === null) {
|
|
9301
|
+
return {
|
|
9302
|
+
state: "unreadable",
|
|
9303
|
+
processIds: [],
|
|
9304
|
+
error: "tasklist output unavailable"
|
|
9305
|
+
};
|
|
9306
|
+
}
|
|
9307
|
+
for (const entry of entries) {
|
|
9308
|
+
if (entry.pid === process.pid)
|
|
9309
|
+
continue;
|
|
9310
|
+
if (commandLooksLikePi(entry.command))
|
|
9311
|
+
pids.add(entry.pid);
|
|
9312
|
+
}
|
|
9313
|
+
} else {
|
|
9314
|
+
for (const line of output.split(/\r?\n/)) {
|
|
9315
|
+
const match = /^\s*(\d+)\s+(.+)$/.exec(line);
|
|
9316
|
+
if (!match)
|
|
9317
|
+
continue;
|
|
9318
|
+
const pid = Number(match[1]);
|
|
9319
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
|
|
9320
|
+
continue;
|
|
9321
|
+
if (commandLooksLikePi(match[2]))
|
|
9322
|
+
pids.add(pid);
|
|
9323
|
+
}
|
|
9177
9324
|
}
|
|
9178
9325
|
return { state: "known", processIds: [...pids].sort((left, right) => left - right) };
|
|
9179
9326
|
} catch (error) {
|
|
@@ -9184,9 +9331,6 @@ function inspectLivePiProcesses() {
|
|
|
9184
9331
|
};
|
|
9185
9332
|
}
|
|
9186
9333
|
}
|
|
9187
|
-
function discoverLivePiProcessIds() {
|
|
9188
|
-
return inspectLivePiProcesses().processIds;
|
|
9189
|
-
}
|
|
9190
9334
|
function parseRpcPortFile(content, fallbackPid = 0) {
|
|
9191
9335
|
const trimmed = content.trim();
|
|
9192
9336
|
if (!trimmed)
|
|
@@ -9631,6 +9775,8 @@ function healAllNullColumns(db) {
|
|
|
9631
9775
|
["stripped_placeholder_ids", ""],
|
|
9632
9776
|
["stale_reduce_stripped_ids", ""],
|
|
9633
9777
|
["processed_image_stripped_ids", ""],
|
|
9778
|
+
["merged_reasoning_stripped_ids", ""],
|
|
9779
|
+
["trailing_blank_decisions", ""],
|
|
9634
9780
|
["memory_block_cache", ""],
|
|
9635
9781
|
["memory_block_ids", ""],
|
|
9636
9782
|
["compaction_marker_state", ""],
|
|
@@ -10223,6 +10369,7 @@ var MIGRATIONS = [
|
|
|
10223
10369
|
status TEXT NOT NULL DEFAULT 'active',
|
|
10224
10370
|
promoted_at INTEGER NOT NULL,
|
|
10225
10371
|
source_candidate_ids TEXT DEFAULT '[]',
|
|
10372
|
+
source_candidate_provenance TEXT,
|
|
10226
10373
|
created_at INTEGER NOT NULL,
|
|
10227
10374
|
updated_at INTEGER NOT NULL
|
|
10228
10375
|
);
|
|
@@ -11249,6 +11396,7 @@ var MIGRATIONS = [
|
|
|
11249
11396
|
last_observed_at INTEGER,
|
|
11250
11397
|
answer_refreshed_at INTEGER,
|
|
11251
11398
|
source_candidate_ids TEXT NOT NULL DEFAULT '[]',
|
|
11399
|
+
source_candidate_provenance TEXT,
|
|
11252
11400
|
created_at INTEGER NOT NULL,
|
|
11253
11401
|
updated_at INTEGER NOT NULL
|
|
11254
11402
|
);
|
|
@@ -12058,6 +12206,37 @@ var MIGRATIONS = [
|
|
|
12058
12206
|
ensureColumn(db, "notes", "compiled_at", "INTEGER");
|
|
12059
12207
|
ensureColumn(db, "notes", "compile_status", "TEXT CHECK(compile_status IN ('compiled', 'plain', 'refused'))");
|
|
12060
12208
|
}
|
|
12209
|
+
},
|
|
12210
|
+
{
|
|
12211
|
+
version: 77,
|
|
12212
|
+
description: "persist scoped provenance for promoted user memories and primers",
|
|
12213
|
+
up(db) {
|
|
12214
|
+
if (tableExists2(db, "user_memories")) {
|
|
12215
|
+
ensureColumn(db, "user_memories", "source_candidate_provenance", "TEXT");
|
|
12216
|
+
}
|
|
12217
|
+
if (tableExists2(db, "primers")) {
|
|
12218
|
+
ensureColumn(db, "primers", "source_candidate_provenance", "TEXT");
|
|
12219
|
+
}
|
|
12220
|
+
}
|
|
12221
|
+
},
|
|
12222
|
+
{
|
|
12223
|
+
version: 78,
|
|
12224
|
+
description: "add migration_pending journal for crash-safe cross-harness session migration",
|
|
12225
|
+
up(db) {
|
|
12226
|
+
db.exec(`
|
|
12227
|
+
CREATE TABLE IF NOT EXISTS migration_pending (
|
|
12228
|
+
migration_key TEXT PRIMARY KEY,
|
|
12229
|
+
source_session_id TEXT NOT NULL,
|
|
12230
|
+
target_harness TEXT NOT NULL,
|
|
12231
|
+
pi_session_id TEXT NOT NULL,
|
|
12232
|
+
final_path TEXT NOT NULL,
|
|
12233
|
+
stage_path TEXT NOT NULL,
|
|
12234
|
+
content_sha256 TEXT NOT NULL,
|
|
12235
|
+
phase TEXT NOT NULL CHECK (phase IN ('staged', 'db_committed')),
|
|
12236
|
+
created_at INTEGER NOT NULL
|
|
12237
|
+
);
|
|
12238
|
+
`);
|
|
12239
|
+
}
|
|
12061
12240
|
}
|
|
12062
12241
|
];
|
|
12063
12242
|
var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
|
|
@@ -12492,7 +12671,7 @@ function getSchemaFenceRejection() {
|
|
|
12492
12671
|
function getMigrationOnOpenRefusal() {
|
|
12493
12672
|
return lastMigrationOnOpenRefusal;
|
|
12494
12673
|
}
|
|
12495
|
-
var LATEST_SUPPORTED_VERSION =
|
|
12674
|
+
var LATEST_SUPPORTED_VERSION = 78;
|
|
12496
12675
|
var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
|
|
12497
12676
|
var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
|
|
12498
12677
|
var storagePermissionFs = defaultStoragePermissionFs;
|
|
@@ -12692,6 +12871,7 @@ function inspectRpcServerDiscovery(storageDir) {
|
|
|
12692
12871
|
}
|
|
12693
12872
|
const pids = new Set;
|
|
12694
12873
|
const staleFiles = [];
|
|
12874
|
+
const inconclusivePids = new Set;
|
|
12695
12875
|
for (const portFile of portFiles) {
|
|
12696
12876
|
let raw;
|
|
12697
12877
|
try {
|
|
@@ -12711,10 +12891,15 @@ function inspectRpcServerDiscovery(storageDir) {
|
|
|
12711
12891
|
return junk;
|
|
12712
12892
|
continue;
|
|
12713
12893
|
}
|
|
12714
|
-
|
|
12894
|
+
const liveness = isPidAlive(record.pid);
|
|
12895
|
+
const identity = liveness === "dead" ? "implausible" : isPidIdentityPlausible(record);
|
|
12896
|
+
if (liveness === "alive" && identity === "plausible") {
|
|
12715
12897
|
pids.add(record.pid);
|
|
12716
|
-
else
|
|
12898
|
+
} else if (liveness === "dead" || identity === "implausible") {
|
|
12717
12899
|
staleFiles.push(portFile);
|
|
12900
|
+
} else {
|
|
12901
|
+
inconclusivePids.add(record.pid);
|
|
12902
|
+
}
|
|
12718
12903
|
}
|
|
12719
12904
|
for (const staleFile of staleFiles) {
|
|
12720
12905
|
try {
|
|
@@ -12727,8 +12912,29 @@ function inspectRpcServerDiscovery(storageDir) {
|
|
|
12727
12912
|
if (serverPids.length > 0) {
|
|
12728
12913
|
return { state: "live", serverPids, staleFiles };
|
|
12729
12914
|
}
|
|
12915
|
+
const uncertainPids = [...inconclusivePids].sort((a, b) => a - b);
|
|
12916
|
+
if (uncertainPids.length > 0) {
|
|
12917
|
+
return {
|
|
12918
|
+
state: "inconclusive",
|
|
12919
|
+
serverPids: [],
|
|
12920
|
+
staleFiles,
|
|
12921
|
+
inconclusivePids: uncertainPids
|
|
12922
|
+
};
|
|
12923
|
+
}
|
|
12730
12924
|
return { state: "stale", serverPids: [], staleFiles };
|
|
12731
12925
|
}
|
|
12926
|
+
function formatInconclusiveOpenCodeMigrationWarning(dbPath, pids) {
|
|
12927
|
+
return `[magic-context] storage warning: continuing migration for ${dbPath}; OpenCode server PID ${pids.join(", ")} was not confirmed because its liveness or identity check could not run. This commonly means an OS sandbox denied kill(0) or ps. No live OpenCode server was confirmed.`;
|
|
12928
|
+
}
|
|
12929
|
+
function logInconclusiveMigrationProbes(dbPath, discovery, piProbeState) {
|
|
12930
|
+
const uncertainPids = discovery.inconclusivePids ?? [];
|
|
12931
|
+
if (uncertainPids.length > 0) {
|
|
12932
|
+
log(formatInconclusiveOpenCodeMigrationWarning(dbPath, uncertainPids));
|
|
12933
|
+
}
|
|
12934
|
+
if (piProbeState === "unreadable") {
|
|
12935
|
+
log(`[magic-context] storage warning: continuing migration for ${dbPath}; the Pi/OMP process-list probe could not run, which commonly means an OS sandbox denied ps. No live Pi harness was confirmed.`);
|
|
12936
|
+
}
|
|
12937
|
+
}
|
|
12732
12938
|
function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion) {
|
|
12733
12939
|
const persistedVersion = getPersistedSchemaVersion(db);
|
|
12734
12940
|
if (persistedVersion >= latestSupportedVersion) {
|
|
@@ -12736,9 +12942,11 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
|
|
|
12736
12942
|
return true;
|
|
12737
12943
|
}
|
|
12738
12944
|
const discovery = inspectRpcServerDiscovery(dbDir);
|
|
12739
|
-
const
|
|
12740
|
-
|
|
12945
|
+
const piDiscovery = inspectLivePiProcesses();
|
|
12946
|
+
const piPids = piDiscovery.processIds;
|
|
12947
|
+
if ((discovery.state === "absent" || discovery.state === "stale" || discovery.state === "inconclusive") && piPids.length === 0) {
|
|
12741
12948
|
lastMigrationOnOpenRefusal = null;
|
|
12949
|
+
logInconclusiveMigrationProbes(dbPath, discovery, piDiscovery.state);
|
|
12742
12950
|
return true;
|
|
12743
12951
|
}
|
|
12744
12952
|
const blockingPids = [...new Set([...discovery.serverPids, ...piPids])].sort((left, right) => left - right);
|
|
@@ -12756,10 +12964,10 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
|
|
|
12756
12964
|
log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} because RPC discovery file ${unreadableFile} is uncertain (${arm} arm), so the absence of a live OpenCode server cannot be proven. ${recovery}`);
|
|
12757
12965
|
} else {
|
|
12758
12966
|
const blockers = [
|
|
12759
|
-
...discovery.serverPids.map((pid) => `OpenCode server PID ${pid}`),
|
|
12760
|
-
...piPids.map((pid) => `Pi harness PID ${pid}`)
|
|
12967
|
+
...discovery.serverPids.map((pid) => `confirmed OpenCode server PID ${pid}`),
|
|
12968
|
+
...piPids.map((pid) => `confirmed Pi harness PID ${pid}`)
|
|
12761
12969
|
];
|
|
12762
|
-
log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while ${blockers.join(", ")}
|
|
12970
|
+
log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while ${blockers.join(", ")} still use the old plugin build. Restart the blocking harness, then retry this process.`);
|
|
12763
12971
|
}
|
|
12764
12972
|
return false;
|
|
12765
12973
|
}
|
|
@@ -12983,6 +13191,7 @@ function initializeDatabase(db) {
|
|
|
12983
13191
|
last_observed_at INTEGER,
|
|
12984
13192
|
answer_refreshed_at INTEGER,
|
|
12985
13193
|
source_candidate_ids TEXT NOT NULL DEFAULT '[]',
|
|
13194
|
+
source_candidate_provenance TEXT,
|
|
12986
13195
|
created_at INTEGER NOT NULL,
|
|
12987
13196
|
updated_at INTEGER NOT NULL
|
|
12988
13197
|
);
|
|
@@ -13618,6 +13827,11 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
13618
13827
|
ensureColumn(db, "primer_candidates", "question_embedding", "BLOB");
|
|
13619
13828
|
ensureColumn(db, "primer_candidates", "question_embedding_model_id", "TEXT");
|
|
13620
13829
|
ensureColumn(db, "primers", "question_embedding_model_id", "TEXT");
|
|
13830
|
+
ensureColumn(db, "primers", "source_candidate_provenance", "TEXT");
|
|
13831
|
+
const hasUserMemoriesTable = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'user_memories'").get();
|
|
13832
|
+
if (hasUserMemoriesTable) {
|
|
13833
|
+
ensureColumn(db, "user_memories", "source_candidate_provenance", "TEXT");
|
|
13834
|
+
}
|
|
13621
13835
|
db.exec(`
|
|
13622
13836
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_primer_candidates_occurrence
|
|
13623
13837
|
ON primer_candidates(project_path, harness, session_id, source_start_message_id, source_end_message_id);
|
|
@@ -13691,6 +13905,8 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
13691
13905
|
ensureColumn(db, "session_meta", "stripped_placeholder_ids", "TEXT DEFAULT ''");
|
|
13692
13906
|
ensureColumn(db, "session_meta", "stale_reduce_stripped_ids", "TEXT DEFAULT ''");
|
|
13693
13907
|
ensureColumn(db, "session_meta", "processed_image_stripped_ids", "TEXT DEFAULT ''");
|
|
13908
|
+
ensureColumn(db, "session_meta", "merged_reasoning_stripped_ids", "TEXT DEFAULT ''");
|
|
13909
|
+
ensureColumn(db, "session_meta", "trailing_blank_decisions", "TEXT DEFAULT ''");
|
|
13694
13910
|
ensureColumn(db, "compartments", "start_message_id", "TEXT DEFAULT ''");
|
|
13695
13911
|
ensureColumn(db, "compartments", "end_message_id", "TEXT DEFAULT ''");
|
|
13696
13912
|
ensureColumn(db, "memory_embeddings", "model_id", "TEXT");
|
|
@@ -14338,7 +14554,7 @@ function persistCachedM0(db, sessionId, payload) {
|
|
|
14338
14554
|
cached_m0_system_hash = ?,
|
|
14339
14555
|
cached_m0_model_key = ?,
|
|
14340
14556
|
cached_m0_project_identity = ?
|
|
14341
|
-
WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.modelKey
|
|
14557
|
+
WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.modelKey ? piModelRefToCanonical(payload.modelKey) : "", payload.projectIdentity ?? null, sessionId);
|
|
14342
14558
|
}
|
|
14343
14559
|
function clearCachedM0M1(db, sessionId) {
|
|
14344
14560
|
ensureSessionMetaRow(db, sessionId);
|
|
@@ -15115,7 +15331,7 @@ function clearHistorianFailureState(db, sessionId) {
|
|
|
15115
15331
|
})();
|
|
15116
15332
|
}
|
|
15117
15333
|
function normalizeDetectedLimitModelKey(modelKey) {
|
|
15118
|
-
return typeof modelKey === "string" && modelKey.length > 0 ? modelKey : null;
|
|
15334
|
+
return typeof modelKey === "string" && modelKey.length > 0 ? piModelRefToCanonical(modelKey) : null;
|
|
15119
15335
|
}
|
|
15120
15336
|
function normalizeEmergencyRecoveryOrigin(value) {
|
|
15121
15337
|
return value === "provider_overflow" || value === "proactive_model_shrink" ? value : null;
|
|
@@ -17225,7 +17441,7 @@ function updateSessionMeta(db, sessionId, updates) {
|
|
|
17225
17441
|
values.push(value ? 1 : 0);
|
|
17226
17442
|
} else if (typeof value === "string" || typeof value === "number") {
|
|
17227
17443
|
setClauses.push(`${column} = ?`);
|
|
17228
|
-
values.push(value);
|
|
17444
|
+
values.push(key === "lastObservedModelKey" && typeof value === "string" ? piModelRefToCanonical(value) : value);
|
|
17229
17445
|
}
|
|
17230
17446
|
}
|
|
17231
17447
|
if (setClauses.length === 0) {
|
|
@@ -18435,6 +18651,76 @@ function parseCandidateIds(raw) {
|
|
|
18435
18651
|
return [];
|
|
18436
18652
|
}
|
|
18437
18653
|
}
|
|
18654
|
+
function parsePrimerSourceProvenance(raw) {
|
|
18655
|
+
if (raw === null)
|
|
18656
|
+
return null;
|
|
18657
|
+
try {
|
|
18658
|
+
const parsed = JSON.parse(raw);
|
|
18659
|
+
if (!Array.isArray(parsed))
|
|
18660
|
+
return null;
|
|
18661
|
+
const provenance = [];
|
|
18662
|
+
for (const value of parsed) {
|
|
18663
|
+
if (!value || typeof value !== "object")
|
|
18664
|
+
return null;
|
|
18665
|
+
const source = value;
|
|
18666
|
+
if (typeof source.candidate_id !== "number" || !Number.isFinite(source.candidate_id) || typeof source.project_path !== "string" || typeof source.harness !== "string" || typeof source.session_id !== "string" || source.source_compartment_start !== null && typeof source.source_compartment_start !== "number" || source.source_compartment_end !== null && typeof source.source_compartment_end !== "number" || typeof source.source_start_message_id !== "string" || typeof source.source_end_message_id !== "string") {
|
|
18667
|
+
return null;
|
|
18668
|
+
}
|
|
18669
|
+
provenance.push({
|
|
18670
|
+
candidateId: source.candidate_id,
|
|
18671
|
+
projectPath: source.project_path,
|
|
18672
|
+
harness: source.harness,
|
|
18673
|
+
sessionId: source.session_id,
|
|
18674
|
+
sourceCompartmentStart: source.source_compartment_start,
|
|
18675
|
+
sourceCompartmentEnd: source.source_compartment_end,
|
|
18676
|
+
sourceStartMessageId: source.source_start_message_id,
|
|
18677
|
+
sourceEndMessageId: source.source_end_message_id
|
|
18678
|
+
});
|
|
18679
|
+
}
|
|
18680
|
+
return provenance;
|
|
18681
|
+
} catch {
|
|
18682
|
+
return null;
|
|
18683
|
+
}
|
|
18684
|
+
}
|
|
18685
|
+
function loadPrimerSourceProvenance(db, candidateIds) {
|
|
18686
|
+
const ids = [...new Set(candidateIds)].sort((a, b) => a - b);
|
|
18687
|
+
if (ids.length === 0)
|
|
18688
|
+
return [];
|
|
18689
|
+
const placeholders3 = ids.map(() => "?").join(",");
|
|
18690
|
+
const rows = db.prepare(`SELECT id, project_path, harness, session_id,
|
|
18691
|
+
source_compartment_start, source_compartment_end,
|
|
18692
|
+
source_start_message_id, source_end_message_id
|
|
18693
|
+
FROM primer_candidates
|
|
18694
|
+
WHERE id IN (${placeholders3})
|
|
18695
|
+
ORDER BY id ASC`).all(...ids);
|
|
18696
|
+
return rows.map((row) => ({
|
|
18697
|
+
candidateId: row.id,
|
|
18698
|
+
projectPath: row.project_path,
|
|
18699
|
+
harness: row.harness,
|
|
18700
|
+
sessionId: row.session_id,
|
|
18701
|
+
sourceCompartmentStart: row.source_compartment_start,
|
|
18702
|
+
sourceCompartmentEnd: row.source_compartment_end,
|
|
18703
|
+
sourceStartMessageId: row.source_start_message_id,
|
|
18704
|
+
sourceEndMessageId: row.source_end_message_id
|
|
18705
|
+
}));
|
|
18706
|
+
}
|
|
18707
|
+
function serializePrimerSourceProvenance(provenance, sourceCandidateIds) {
|
|
18708
|
+
if (provenance.length === 0 && sourceCandidateIds.length > 0)
|
|
18709
|
+
return null;
|
|
18710
|
+
return JSON.stringify(provenance.map((source) => ({
|
|
18711
|
+
candidate_id: source.candidateId,
|
|
18712
|
+
project_path: source.projectPath,
|
|
18713
|
+
harness: source.harness,
|
|
18714
|
+
session_id: source.sessionId,
|
|
18715
|
+
source_compartment_start: source.sourceCompartmentStart,
|
|
18716
|
+
source_compartment_end: source.sourceCompartmentEnd,
|
|
18717
|
+
source_start_message_id: source.sourceStartMessageId,
|
|
18718
|
+
source_end_message_id: source.sourceEndMessageId
|
|
18719
|
+
})));
|
|
18720
|
+
}
|
|
18721
|
+
function normalizedCandidateIds(candidateIds) {
|
|
18722
|
+
return [...new Set(candidateIds)].sort((a, b) => a - b);
|
|
18723
|
+
}
|
|
18438
18724
|
function toCandidate(row) {
|
|
18439
18725
|
return {
|
|
18440
18726
|
id: row.id,
|
|
@@ -18467,6 +18753,7 @@ function toPrimer(row) {
|
|
|
18467
18753
|
lastObservedAt: row.last_observed_at,
|
|
18468
18754
|
answerRefreshedAt: row.answer_refreshed_at,
|
|
18469
18755
|
sourceCandidateIds: parseCandidateIds(row.source_candidate_ids),
|
|
18756
|
+
sourceProvenance: parsePrimerSourceProvenance(row.source_candidate_provenance),
|
|
18470
18757
|
createdAt: row.created_at,
|
|
18471
18758
|
updatedAt: row.updated_at
|
|
18472
18759
|
};
|
|
@@ -18538,23 +18825,43 @@ function getActivePrimers(db, projectPath) {
|
|
|
18538
18825
|
return rows.map(toPrimer);
|
|
18539
18826
|
}
|
|
18540
18827
|
function createPrimer(db, input) {
|
|
18541
|
-
|
|
18542
|
-
|
|
18543
|
-
|
|
18544
|
-
|
|
18545
|
-
|
|
18546
|
-
|
|
18547
|
-
|
|
18828
|
+
return db.transaction(() => {
|
|
18829
|
+
const now = input.now ?? Date.now();
|
|
18830
|
+
const sourceCandidateIds = normalizedCandidateIds(input.sourceCandidateIds);
|
|
18831
|
+
const sourceProvenance = loadPrimerSourceProvenance(db, sourceCandidateIds);
|
|
18832
|
+
const info = db.prepare(`INSERT INTO primers (
|
|
18833
|
+
project_path, question, question_embedding, question_embedding_model_id, answer,
|
|
18834
|
+
status, total_support, last_observed_at, answer_refreshed_at,
|
|
18835
|
+
source_candidate_ids, source_candidate_provenance, created_at, updated_at
|
|
18836
|
+
) VALUES (?, ?, ?, ?, ?, 'active', ?, ?, NULL, ?, ?, ?, ?)`).run(input.projectPath, input.question, vectorBlob(input.questionEmbedding), input.questionEmbeddingModelId ?? null, input.answer ?? "", input.totalSupport, input.lastObservedAt, JSON.stringify(sourceCandidateIds), serializePrimerSourceProvenance(sourceProvenance, sourceCandidateIds), now, now);
|
|
18837
|
+
return Number(info.lastInsertRowid);
|
|
18838
|
+
})();
|
|
18548
18839
|
}
|
|
18549
18840
|
function updatePrimerSupport(db, input) {
|
|
18550
|
-
db.
|
|
18551
|
-
|
|
18552
|
-
|
|
18553
|
-
|
|
18554
|
-
|
|
18555
|
-
|
|
18556
|
-
|
|
18557
|
-
|
|
18841
|
+
db.transaction(() => {
|
|
18842
|
+
const sourceCandidateIds = normalizedCandidateIds(input.sourceCandidateIds);
|
|
18843
|
+
const allowedIds = new Set(sourceCandidateIds);
|
|
18844
|
+
const existingRow = db.prepare("SELECT source_candidate_provenance FROM primers WHERE id = ?").get(input.primerId);
|
|
18845
|
+
const provenanceByCandidateId = new Map;
|
|
18846
|
+
for (const source of parsePrimerSourceProvenance(existingRow?.source_candidate_provenance ?? null) ?? []) {
|
|
18847
|
+
if (allowedIds.has(source.candidateId)) {
|
|
18848
|
+
provenanceByCandidateId.set(source.candidateId, source);
|
|
18849
|
+
}
|
|
18850
|
+
}
|
|
18851
|
+
for (const source of loadPrimerSourceProvenance(db, sourceCandidateIds)) {
|
|
18852
|
+
provenanceByCandidateId.set(source.candidateId, source);
|
|
18853
|
+
}
|
|
18854
|
+
const sourceProvenance = [...provenanceByCandidateId.values()].sort((a, b) => a.candidateId - b.candidateId);
|
|
18855
|
+
db.prepare(`UPDATE primers
|
|
18856
|
+
SET question_embedding = COALESCE(?, question_embedding),
|
|
18857
|
+
question_embedding_model_id = COALESCE(?, question_embedding_model_id),
|
|
18858
|
+
total_support = ?,
|
|
18859
|
+
last_observed_at = ?,
|
|
18860
|
+
source_candidate_ids = ?,
|
|
18861
|
+
source_candidate_provenance = ?,
|
|
18862
|
+
updated_at = ?
|
|
18863
|
+
WHERE id = ?`).run(vectorBlob(input.questionEmbedding), input.questionEmbeddingModelId ?? null, input.totalSupport, input.lastObservedAt, JSON.stringify(sourceCandidateIds), serializePrimerSourceProvenance(sourceProvenance, sourceCandidateIds), input.now ?? Date.now(), input.primerId);
|
|
18864
|
+
})();
|
|
18558
18865
|
}
|
|
18559
18866
|
function updatePrimerAnswer(db, primerId, answer, refreshedAt = Date.now()) {
|
|
18560
18867
|
db.prepare("UPDATE primers SET answer = ?, answer_refreshed_at = ?, updated_at = ? WHERE id = ?").run(answer, refreshedAt, refreshedAt, primerId);
|
|
@@ -19366,47 +19673,6 @@ var ERROR_CLASSES = new Set([
|
|
|
19366
19673
|
"permission_denied",
|
|
19367
19674
|
"unknown"
|
|
19368
19675
|
]);
|
|
19369
|
-
// ../plugin/src/shared/harness-provider-map.ts
|
|
19370
|
-
var CANONICAL_TO_PI_PROVIDER = {
|
|
19371
|
-
openai: "openai-codex",
|
|
19372
|
-
google: "google-antigravity"
|
|
19373
|
-
};
|
|
19374
|
-
var PI_TO_CANONICAL_PROVIDER = {
|
|
19375
|
-
"openai-codex": "openai",
|
|
19376
|
-
"google-antigravity": "google"
|
|
19377
|
-
};
|
|
19378
|
-
var CANONICAL_TO_OMP_PROVIDER = {
|
|
19379
|
-
openai: "openai-codex",
|
|
19380
|
-
google: "google-antigravity"
|
|
19381
|
-
};
|
|
19382
|
-
var OMP_TO_CANONICAL_PROVIDER = {
|
|
19383
|
-
"openai-codex": "openai",
|
|
19384
|
-
"google-antigravity": "google"
|
|
19385
|
-
};
|
|
19386
|
-
function remapProviderPrefix(ref, map) {
|
|
19387
|
-
if (typeof ref !== "string")
|
|
19388
|
-
return ref;
|
|
19389
|
-
const slash = ref.indexOf("/");
|
|
19390
|
-
if (slash <= 0)
|
|
19391
|
-
return ref;
|
|
19392
|
-
const provider = ref.slice(0, slash);
|
|
19393
|
-
if (!Object.hasOwn(map, provider))
|
|
19394
|
-
return ref;
|
|
19395
|
-
return `${map[provider]}${ref.slice(slash)}`;
|
|
19396
|
-
}
|
|
19397
|
-
function piModelRefToCanonical(ref) {
|
|
19398
|
-
return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
|
|
19399
|
-
}
|
|
19400
|
-
function resolveModelRefForPi(ref) {
|
|
19401
|
-
return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
|
|
19402
|
-
}
|
|
19403
|
-
function ompModelRefToCanonical(ref) {
|
|
19404
|
-
return remapProviderPrefix(ref, OMP_TO_CANONICAL_PROVIDER);
|
|
19405
|
-
}
|
|
19406
|
-
function resolveModelRefForOmp(ref) {
|
|
19407
|
-
return remapProviderPrefix(ompModelRefToCanonical(ref), CANONICAL_TO_OMP_PROVIDER);
|
|
19408
|
-
}
|
|
19409
|
-
|
|
19410
19676
|
// ../plugin/src/hooks/magic-context/todo-view.ts
|
|
19411
19677
|
import { createHash as createHash7 } from "node:crypto";
|
|
19412
19678
|
var TODO_STATUS_PENDING = "pending";
|
|
@@ -19649,16 +19915,25 @@ function modelKeyLookupOrder(modelKey) {
|
|
|
19649
19915
|
return [];
|
|
19650
19916
|
const provider = modelKey.slice(0, slash);
|
|
19651
19917
|
let modelID = modelKey.slice(slash + 1);
|
|
19918
|
+
const providerRefs = modelRefLookupOrder(`${provider}/${modelID}`);
|
|
19652
19919
|
const candidates = [];
|
|
19653
19920
|
while (modelID.length > 0) {
|
|
19654
|
-
|
|
19921
|
+
for (const providerRef of providerRefs) {
|
|
19922
|
+
const providerSlash = providerRef.indexOf("/");
|
|
19923
|
+
const providerPrefix = providerRef.slice(0, providerSlash);
|
|
19924
|
+
candidates.push({ key: `${providerPrefix}/${modelID}`, source: "exact" });
|
|
19925
|
+
}
|
|
19655
19926
|
candidates.push({ key: modelID, source: "bare" });
|
|
19656
19927
|
const lastDash = modelID.lastIndexOf("-");
|
|
19657
19928
|
if (lastDash <= 0)
|
|
19658
19929
|
break;
|
|
19659
19930
|
modelID = modelID.slice(0, lastDash);
|
|
19660
19931
|
}
|
|
19661
|
-
|
|
19932
|
+
for (const providerRef of providerRefs) {
|
|
19933
|
+
const providerSlash = providerRef.indexOf("/");
|
|
19934
|
+
const providerPrefix = providerRef.slice(0, providerSlash);
|
|
19935
|
+
candidates.push({ key: `${providerPrefix}/*`, source: "wildcard" });
|
|
19936
|
+
}
|
|
19662
19937
|
const seen = new Set;
|
|
19663
19938
|
return candidates.filter((candidate) => {
|
|
19664
19939
|
if (seen.has(candidate.key))
|
|
@@ -19801,12 +20076,13 @@ function createPromptSurfaceGuidanceEpochCache(runtime) {
|
|
|
19801
20076
|
const epochs = new Map;
|
|
19802
20077
|
return {
|
|
19803
20078
|
resolve(sessionId, config, modelKey) {
|
|
20079
|
+
const canonicalModelKey = modelKey ? piModelRefToCanonical(modelKey) : undefined;
|
|
19804
20080
|
const cached = epochs.get(sessionId);
|
|
19805
|
-
if (cached && cached.config === config && cached.modelKey ===
|
|
20081
|
+
if (cached && cached.config === config && cached.modelKey === canonicalModelKey) {
|
|
19806
20082
|
return cached.selection;
|
|
19807
20083
|
}
|
|
19808
|
-
const selection = runtime.resolveGuidance(config,
|
|
19809
|
-
epochs.set(sessionId, { config, modelKey, selection });
|
|
20084
|
+
const selection = runtime.resolveGuidance(config, canonicalModelKey);
|
|
20085
|
+
epochs.set(sessionId, { config, modelKey: canonicalModelKey, selection });
|
|
19810
20086
|
return selection;
|
|
19811
20087
|
},
|
|
19812
20088
|
clear(sessionId) {
|
|
@@ -20165,7 +20441,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
|
|
|
20165
20441
|
}
|
|
20166
20442
|
|
|
20167
20443
|
// src/config/index.ts
|
|
20168
|
-
import { existsSync as existsSync10, readFileSync as
|
|
20444
|
+
import { existsSync as existsSync10, readFileSync as readFileSync11 } from "node:fs";
|
|
20169
20445
|
|
|
20170
20446
|
// ../plugin/src/config/migrate-dreamer-v2.ts
|
|
20171
20447
|
var OLD_VERIFY_TASK = "verify";
|
|
@@ -35229,6 +35505,9 @@ var MagicContextConfigSchema = exports_external.object({
|
|
|
35229
35505
|
exports_external.number().min(0),
|
|
35230
35506
|
exports_external.object({ default: exports_external.number().min(0) }).catchall(exports_external.number().min(0))
|
|
35231
35507
|
]).optional().describe('User-only output-token reservation override. Number or per-model object ({ default: 16384, "provider/model": 8192 }); 0 disables reservation. When unset, Magic Context reserves the catalog output limit (capped at 25% of context) for shared-window providers and keeps proven separate-quota Google/Gemini windows unchanged.'),
|
|
35508
|
+
models: exports_external.object({
|
|
35509
|
+
window_overlay_path: exports_external.string().trim().min(1).optional()
|
|
35510
|
+
}).optional().describe("User-only Fusiform window-overlay settings. The path defaults to <dataDir>/fusiform/window-overlay.json."),
|
|
35232
35511
|
toast_duration_ms: exports_external.number().min(0).max(60000).default(5000).describe("TUI toast lifetime in milliseconds for Magic Context notifications. Set to 0 to disable Magic Context toasts entirely (min: 0, max: 60000, default: 5000)"),
|
|
35233
35512
|
execute_threshold_percentage: exports_external.union([
|
|
35234
35513
|
exports_external.number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE),
|
|
@@ -35442,6 +35721,11 @@ function stripUnsafeProjectConfigFields(projectRaw) {
|
|
|
35442
35721
|
delete projectRaw.output_reserve;
|
|
35443
35722
|
warnings.push("Ignoring output_reserve from project config (security: output-token reservation only honors user-level config).");
|
|
35444
35723
|
}
|
|
35724
|
+
const models = projectRaw.models;
|
|
35725
|
+
if (isPlainObject3(models) && "window_overlay_path" in models) {
|
|
35726
|
+
delete models.window_overlay_path;
|
|
35727
|
+
warnings.push("Ignoring models.window_overlay_path from project config (security: only user-level config may select model geometry metadata).");
|
|
35728
|
+
}
|
|
35445
35729
|
if ("language" in projectRaw) {
|
|
35446
35730
|
delete projectRaw.language;
|
|
35447
35731
|
warnings.push("Ignoring language from project config (security: output language is a user-level setting).");
|
|
@@ -35760,29 +36044,418 @@ function substituteConfigVariables(input) {
|
|
|
35760
36044
|
}
|
|
35761
36045
|
|
|
35762
36046
|
// ../plugin/src/shared/models-dev-cache.ts
|
|
35763
|
-
import { mkdirSync as mkdirSync3, readFileSync as
|
|
36047
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync10, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
36048
|
+
import { join as join7 } from "node:path";
|
|
36049
|
+
|
|
36050
|
+
// ../plugin/src/shared/window-geometry.ts
|
|
36051
|
+
import { readFileSync as readFileSync9 } from "node:fs";
|
|
35764
36052
|
import { join as join6 } from "node:path";
|
|
36053
|
+
var WINDOW_OVERLAY_SCHEMA = "fusiform-window-overlay/v1";
|
|
36054
|
+
var PROMPT_WALL_MARGIN = 4096;
|
|
36055
|
+
var PI_OUTPUT_FLOOR = 4096;
|
|
36056
|
+
var OPENCODE_OUTPUT_CAP = 32000;
|
|
36057
|
+
var MIN_PLAUSIBLE_CONTEXT_LIMIT = 1024;
|
|
36058
|
+
var OUTPUT_RESERVE_CAP_RATIO = 0.25;
|
|
36059
|
+
var PROVIDER_GEOMETRY = {
|
|
36060
|
+
anthropic: "shared_truncating",
|
|
36061
|
+
xai: "shared_truncating",
|
|
36062
|
+
google: "separate",
|
|
36063
|
+
"google-antigravity": "separate"
|
|
36064
|
+
};
|
|
36065
|
+
var GRADES = new Set([
|
|
36066
|
+
"provider_asserted_runtime",
|
|
36067
|
+
"measured",
|
|
36068
|
+
"provider_asserted_doc",
|
|
36069
|
+
"catalog",
|
|
36070
|
+
"unknown"
|
|
36071
|
+
]);
|
|
36072
|
+
var UNITS = new Set(["provider", "estimate"]);
|
|
36073
|
+
var BOUNDARIES = new Set(["Observed", "Asserted", "Corrected"]);
|
|
36074
|
+
var UNKNOWN_REASONS = new Set([
|
|
36075
|
+
"placeholder_output_equals_context",
|
|
36076
|
+
"placeholder_zero",
|
|
36077
|
+
"never_measured",
|
|
36078
|
+
"not_single_valued_at_key",
|
|
36079
|
+
"retracted"
|
|
36080
|
+
]);
|
|
36081
|
+
var NUMERIC_FACT_KEYS = new Set([
|
|
36082
|
+
"window.advertised",
|
|
36083
|
+
"window.enforced",
|
|
36084
|
+
"output.advertised",
|
|
36085
|
+
"output.enforced",
|
|
36086
|
+
"output.default"
|
|
36087
|
+
]);
|
|
36088
|
+
var configuredOverlayPath;
|
|
36089
|
+
var loadedOverlayPath;
|
|
36090
|
+
var loadedOverlay;
|
|
36091
|
+
var geometryClampLogSeen = new Set;
|
|
36092
|
+
function isRecord2(value) {
|
|
36093
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
36094
|
+
}
|
|
36095
|
+
function isFinitePositive(value) {
|
|
36096
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
36097
|
+
}
|
|
36098
|
+
function modelKeyLookupOrder2(providerID, modelID) {
|
|
36099
|
+
const candidates = [...modelRefLookupOrder(`${providerID}/${modelID}`), modelID];
|
|
36100
|
+
const colon = modelID.lastIndexOf(":");
|
|
36101
|
+
if (colon > 0) {
|
|
36102
|
+
const bareModel = modelID.slice(0, colon);
|
|
36103
|
+
candidates.push(...modelRefLookupOrder(`${providerID}/${bareModel}`), bareModel);
|
|
36104
|
+
}
|
|
36105
|
+
return [...new Set(candidates)];
|
|
36106
|
+
}
|
|
36107
|
+
function configuredOutputReserve(config2, providerID, modelID) {
|
|
36108
|
+
if (typeof config2 === "number") {
|
|
36109
|
+
return Number.isFinite(config2) && config2 >= 0 ? config2 : undefined;
|
|
36110
|
+
}
|
|
36111
|
+
if (!config2)
|
|
36112
|
+
return;
|
|
36113
|
+
for (const candidate of modelKeyLookupOrder2(providerID, modelID)) {
|
|
36114
|
+
const value = config2[candidate];
|
|
36115
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
|
|
36116
|
+
return value;
|
|
36117
|
+
}
|
|
36118
|
+
return Number.isFinite(config2.default) && config2.default >= 0 ? config2.default : undefined;
|
|
36119
|
+
}
|
|
36120
|
+
function scalarizeFact(value) {
|
|
36121
|
+
if (value.kind === "stated")
|
|
36122
|
+
return isFinitePositive(value.value) ? value.value : undefined;
|
|
36123
|
+
if (value.kind === "bracket") {
|
|
36124
|
+
return isFinitePositive(value.at_least) ? value.at_least : undefined;
|
|
36125
|
+
}
|
|
36126
|
+
return;
|
|
36127
|
+
}
|
|
36128
|
+
function parseFactValue(value) {
|
|
36129
|
+
if (!isRecord2(value) || typeof value.kind !== "string")
|
|
36130
|
+
return;
|
|
36131
|
+
if (value.kind === "stated") {
|
|
36132
|
+
if ((typeof value.value !== "number" || !Number.isFinite(value.value)) && typeof value.value !== "string") {
|
|
36133
|
+
return;
|
|
36134
|
+
}
|
|
36135
|
+
return { kind: "stated", value: value.value };
|
|
36136
|
+
}
|
|
36137
|
+
if (value.kind === "bracket") {
|
|
36138
|
+
const atLeast = value.at_least;
|
|
36139
|
+
const below = value.below;
|
|
36140
|
+
if (atLeast === undefined && below === undefined)
|
|
36141
|
+
return { kind: "bracket" };
|
|
36142
|
+
if (atLeast !== undefined && !isFinitePositive(atLeast))
|
|
36143
|
+
return;
|
|
36144
|
+
if (below !== undefined && !isFinitePositive(below))
|
|
36145
|
+
return;
|
|
36146
|
+
if (isFinitePositive(atLeast) && isFinitePositive(below) && below <= atLeast) {
|
|
36147
|
+
return;
|
|
36148
|
+
}
|
|
36149
|
+
return {
|
|
36150
|
+
kind: "bracket",
|
|
36151
|
+
...isFinitePositive(atLeast) ? { at_least: atLeast } : {},
|
|
36152
|
+
...isFinitePositive(below) ? { below } : {}
|
|
36153
|
+
};
|
|
36154
|
+
}
|
|
36155
|
+
if (value.kind === "unknown" && UNKNOWN_REASONS.has(value.why)) {
|
|
36156
|
+
return { kind: "unknown", why: value.why };
|
|
36157
|
+
}
|
|
36158
|
+
return;
|
|
36159
|
+
}
|
|
36160
|
+
function parseFact(key, value) {
|
|
36161
|
+
if (!isRecord2(value))
|
|
36162
|
+
return;
|
|
36163
|
+
const parsedValue = parseFactValue(value.value);
|
|
36164
|
+
if (!parsedValue || !GRADES.has(value.grade) || !UNITS.has(value.units) || !BOUNDARIES.has(value.boundary) || typeof value.source_ref !== "string" || value.source_ref.length === 0 || typeof value.observed_at !== "string" || value.observed_at.length === 0) {
|
|
36165
|
+
return;
|
|
36166
|
+
}
|
|
36167
|
+
if (NUMERIC_FACT_KEYS.has(key) && parsedValue.kind === "stated" && !isFinitePositive(parsedValue.value)) {
|
|
36168
|
+
return;
|
|
36169
|
+
}
|
|
36170
|
+
if (key === "geometry" && parsedValue.kind === "stated" && !["shared_upfront", "shared_truncating", "separate"].includes(String(parsedValue.value))) {
|
|
36171
|
+
return;
|
|
36172
|
+
}
|
|
36173
|
+
return {
|
|
36174
|
+
...value,
|
|
36175
|
+
value: parsedValue,
|
|
36176
|
+
grade: value.grade,
|
|
36177
|
+
units: value.units,
|
|
36178
|
+
boundary: value.boundary,
|
|
36179
|
+
source_ref: value.source_ref,
|
|
36180
|
+
observed_at: value.observed_at
|
|
36181
|
+
};
|
|
36182
|
+
}
|
|
36183
|
+
function parseWindowOverlay(value) {
|
|
36184
|
+
if (!isRecord2(value)) {
|
|
36185
|
+
return { badCells: 0, refusal: "overlay root is not an object" };
|
|
36186
|
+
}
|
|
36187
|
+
if (value.schema !== WINDOW_OVERLAY_SCHEMA) {
|
|
36188
|
+
return {
|
|
36189
|
+
badCells: 0,
|
|
36190
|
+
refusal: `unrecognized schema ${JSON.stringify(value.schema)}`
|
|
36191
|
+
};
|
|
36192
|
+
}
|
|
36193
|
+
if (typeof value.generated_at !== "string" || !Array.isArray(value.minted_provider_ids) || !value.minted_provider_ids.every((id) => typeof id === "string" && id.length > 0) || !Array.isArray(value.cells)) {
|
|
36194
|
+
return { badCells: 0, refusal: "invalid v1 envelope" };
|
|
36195
|
+
}
|
|
36196
|
+
const cells = [];
|
|
36197
|
+
let badCells = 0;
|
|
36198
|
+
for (const rawCell of value.cells) {
|
|
36199
|
+
if (!isRecord2(rawCell) || typeof rawCell.provider_id !== "string" || rawCell.provider_id.length === 0 || typeof rawCell.model_id !== "string" || rawCell.model_id.length === 0 || !isRecord2(rawCell.facts)) {
|
|
36200
|
+
badCells++;
|
|
36201
|
+
continue;
|
|
36202
|
+
}
|
|
36203
|
+
const facts = {};
|
|
36204
|
+
let valid = true;
|
|
36205
|
+
for (const [key, rawFact] of Object.entries(rawCell.facts)) {
|
|
36206
|
+
const fact = parseFact(key, rawFact);
|
|
36207
|
+
if (!fact) {
|
|
36208
|
+
valid = false;
|
|
36209
|
+
break;
|
|
36210
|
+
}
|
|
36211
|
+
facts[key] = fact;
|
|
36212
|
+
}
|
|
36213
|
+
if (!valid) {
|
|
36214
|
+
badCells++;
|
|
36215
|
+
continue;
|
|
36216
|
+
}
|
|
36217
|
+
cells.push({
|
|
36218
|
+
provider_id: rawCell.provider_id,
|
|
36219
|
+
model_id: rawCell.model_id,
|
|
36220
|
+
facts
|
|
36221
|
+
});
|
|
36222
|
+
}
|
|
36223
|
+
return {
|
|
36224
|
+
overlay: {
|
|
36225
|
+
schema: WINDOW_OVERLAY_SCHEMA,
|
|
36226
|
+
generated_at: value.generated_at,
|
|
36227
|
+
minted_provider_ids: [...value.minted_provider_ids],
|
|
36228
|
+
cells
|
|
36229
|
+
},
|
|
36230
|
+
badCells
|
|
36231
|
+
};
|
|
36232
|
+
}
|
|
36233
|
+
function defaultWindowOverlayPath() {
|
|
36234
|
+
return join6(getDataDir(), "fusiform", "window-overlay.json");
|
|
36235
|
+
}
|
|
36236
|
+
function readWindowOverlayFile(path3, log2 = (message) => sessionLog("global", message)) {
|
|
36237
|
+
let raw;
|
|
36238
|
+
try {
|
|
36239
|
+
raw = readFileSync9(path3, "utf8");
|
|
36240
|
+
} catch (error51) {
|
|
36241
|
+
if (error51.code === "ENOENT")
|
|
36242
|
+
return;
|
|
36243
|
+
log2(`window-overlay: unable to read ${path3}; overlay ignored`);
|
|
36244
|
+
return;
|
|
36245
|
+
}
|
|
36246
|
+
let decoded;
|
|
36247
|
+
try {
|
|
36248
|
+
decoded = JSON.parse(raw);
|
|
36249
|
+
} catch {
|
|
36250
|
+
log2(`window-overlay: invalid JSON in ${path3}; overlay ignored`);
|
|
36251
|
+
return;
|
|
36252
|
+
}
|
|
36253
|
+
const parsed = parseWindowOverlay(decoded);
|
|
36254
|
+
if (parsed.refusal) {
|
|
36255
|
+
log2(`window-overlay: ${parsed.refusal} in ${path3}; entire overlay ignored`);
|
|
36256
|
+
return;
|
|
36257
|
+
}
|
|
36258
|
+
if (parsed.badCells > 0) {
|
|
36259
|
+
log2(`window-overlay: skipped ${parsed.badCells} invalid cell(s) from ${path3}`);
|
|
36260
|
+
}
|
|
36261
|
+
return parsed.overlay;
|
|
36262
|
+
}
|
|
36263
|
+
function setWindowOverlayPath(path3) {
|
|
36264
|
+
configuredOverlayPath = path3;
|
|
36265
|
+
loadedOverlayPath = undefined;
|
|
36266
|
+
loadedOverlay = undefined;
|
|
36267
|
+
}
|
|
36268
|
+
function getWindowOverlay() {
|
|
36269
|
+
const path3 = configuredOverlayPath ?? defaultWindowOverlayPath();
|
|
36270
|
+
if (loadedOverlayPath === path3 && loadedOverlay !== undefined) {
|
|
36271
|
+
return loadedOverlay ?? undefined;
|
|
36272
|
+
}
|
|
36273
|
+
loadedOverlayPath = path3;
|
|
36274
|
+
loadedOverlay = readWindowOverlayFile(path3) ?? null;
|
|
36275
|
+
return loadedOverlay ?? undefined;
|
|
36276
|
+
}
|
|
36277
|
+
function resolveWindowOverlayFacts(providerID, modelID, overlay = getWindowOverlay()) {
|
|
36278
|
+
if (!overlay)
|
|
36279
|
+
return;
|
|
36280
|
+
const modelRefs = modelRefLookupOrder(`${providerID}/${modelID}`);
|
|
36281
|
+
const providerCandidates = new Set(modelRefs.map((ref) => ref.slice(0, ref.indexOf("/"))));
|
|
36282
|
+
const modelCandidates = new Set([
|
|
36283
|
+
modelID,
|
|
36284
|
+
...modelRefs.map((ref) => ref.slice(ref.indexOf("/") + 1))
|
|
36285
|
+
]);
|
|
36286
|
+
const colon = modelID.lastIndexOf(":");
|
|
36287
|
+
if (colon > 0)
|
|
36288
|
+
modelCandidates.add(modelID.slice(0, colon));
|
|
36289
|
+
const wildcardFacts = {};
|
|
36290
|
+
const specificFacts = {};
|
|
36291
|
+
for (const cell of overlay.cells) {
|
|
36292
|
+
if (!providerCandidates.has(cell.provider_id))
|
|
36293
|
+
continue;
|
|
36294
|
+
if (cell.model_id === "*")
|
|
36295
|
+
Object.assign(wildcardFacts, cell.facts);
|
|
36296
|
+
else if (modelCandidates.has(cell.model_id))
|
|
36297
|
+
Object.assign(specificFacts, cell.facts);
|
|
36298
|
+
}
|
|
36299
|
+
const facts = { ...wildcardFacts, ...specificFacts };
|
|
36300
|
+
return Object.keys(facts).length > 0 ? { facts } : undefined;
|
|
36301
|
+
}
|
|
36302
|
+
function numericOverlayFact(overlay, key) {
|
|
36303
|
+
const fact = overlay?.facts[key];
|
|
36304
|
+
return fact ? scalarizeFact(fact.value) : undefined;
|
|
36305
|
+
}
|
|
36306
|
+
function overlayGeometry(overlay) {
|
|
36307
|
+
const fact = overlay?.facts.geometry;
|
|
36308
|
+
if (fact === undefined)
|
|
36309
|
+
return;
|
|
36310
|
+
if (fact.value.kind === "unknown")
|
|
36311
|
+
return { kind: "unknown" };
|
|
36312
|
+
if (fact.value.kind !== "stated")
|
|
36313
|
+
return;
|
|
36314
|
+
const value = fact.value.value;
|
|
36315
|
+
return value === "shared_upfront" || value === "shared_truncating" || value === "separate" ? { kind: "stated", value } : undefined;
|
|
36316
|
+
}
|
|
36317
|
+
function placeholderFilteredOutput(output, context) {
|
|
36318
|
+
if (!isFinitePositive(output))
|
|
36319
|
+
return;
|
|
36320
|
+
if (isFinitePositive(context) && output >= context)
|
|
36321
|
+
return;
|
|
36322
|
+
return output;
|
|
36323
|
+
}
|
|
36324
|
+
function mergePositive(overlayValue, providerValue) {
|
|
36325
|
+
return isFinitePositive(providerValue) ? providerValue : overlayValue;
|
|
36326
|
+
}
|
|
36327
|
+
function logGeometryClampOnce(key, message, log2) {
|
|
36328
|
+
if (geometryClampLogSeen.has(key))
|
|
36329
|
+
return;
|
|
36330
|
+
geometryClampLogSeen.add(key);
|
|
36331
|
+
(log2 ?? ((entry) => sessionLog("global", `window-geometry: ${entry}`)))(message);
|
|
36332
|
+
}
|
|
36333
|
+
function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
|
|
36334
|
+
if (!catalogLimit && !options.providerLimit)
|
|
36335
|
+
return;
|
|
36336
|
+
const providerLimit = options.providerLimit;
|
|
36337
|
+
const catalogContext = isFinitePositive(catalogLimit?.context) ? catalogLimit.context : undefined;
|
|
36338
|
+
const advertised = numericOverlayFact(options.overlay, "window.advertised");
|
|
36339
|
+
const enforced = numericOverlayFact(options.overlay, "window.enforced");
|
|
36340
|
+
let softContext = mergePositive(enforced ?? advertised ?? catalogContext, providerLimit?.context);
|
|
36341
|
+
let hardContext = mergePositive(enforced ?? softContext, providerLimit?.context);
|
|
36342
|
+
if (isFinitePositive(options.contextCap)) {
|
|
36343
|
+
softContext = isFinitePositive(softContext) ? Math.min(softContext, options.contextCap) : options.contextCap;
|
|
36344
|
+
hardContext = isFinitePositive(hardContext) ? Math.min(hardContext, options.contextCap) : options.contextCap;
|
|
36345
|
+
}
|
|
36346
|
+
const input = mergePositive(isFinitePositive(catalogLimit?.input) ? catalogLimit.input : undefined, providerLimit?.input);
|
|
36347
|
+
if (!isFinitePositive(softContext) && !isFinitePositive(input))
|
|
36348
|
+
return;
|
|
36349
|
+
const catalogOutput = options.overlay === undefined && options.providerLimit === undefined ? isFinitePositive(catalogLimit?.output) ? catalogLimit.output : undefined : placeholderFilteredOutput(catalogLimit?.output, softContext);
|
|
36350
|
+
const overlayOutput = placeholderFilteredOutput(numericOverlayFact(options.overlay, "output.enforced") ?? numericOverlayFact(options.overlay, "output.default") ?? numericOverlayFact(options.overlay, "output.advertised"), softContext);
|
|
36351
|
+
const providerOutput = placeholderFilteredOutput(providerLimit?.output, softContext);
|
|
36352
|
+
const output = providerOutput ?? overlayOutput ?? catalogOutput;
|
|
36353
|
+
const geometryFact = overlayGeometry(options.overlay);
|
|
36354
|
+
const geometry = geometryFact?.kind === "stated" ? geometryFact.value : geometryFact?.kind === "unknown" ? "shared_upfront" : PROVIDER_GEOMETRY[providerID] ?? "shared_upfront";
|
|
36355
|
+
const geometryOverride = geometryFact?.kind === "stated" ? geometryFact.value : undefined;
|
|
36356
|
+
let usableSoft;
|
|
36357
|
+
let softReserve = 0;
|
|
36358
|
+
let reserveSource = "none";
|
|
36359
|
+
if (isFinitePositive(input) && (!isFinitePositive(softContext) || input < softContext)) {
|
|
36360
|
+
usableSoft = input;
|
|
36361
|
+
if (isFinitePositive(softContext)) {
|
|
36362
|
+
softReserve = Math.max(0, softContext - input);
|
|
36363
|
+
reserveSource = "output_catalog";
|
|
36364
|
+
}
|
|
36365
|
+
} else if (isFinitePositive(softContext)) {
|
|
36366
|
+
const configuredReserve = configuredOutputReserve(options.reserveConfig, providerID, modelID);
|
|
36367
|
+
if (configuredReserve !== undefined) {
|
|
36368
|
+
softReserve = configuredReserve;
|
|
36369
|
+
reserveSource = "output_config";
|
|
36370
|
+
} else if (geometry === "separate" && (options.overlay === undefined || options.harness === "pi" || geometryOverride !== undefined)) {
|
|
36371
|
+
softReserve = 0;
|
|
36372
|
+
reserveSource = "none";
|
|
36373
|
+
} else {
|
|
36374
|
+
softReserve = output ?? 0;
|
|
36375
|
+
reserveSource = output === undefined ? "none" : "output_catalog";
|
|
36376
|
+
const cap = softContext * OUTPUT_RESERVE_CAP_RATIO;
|
|
36377
|
+
softReserve = Math.min(softReserve, options.harness === "pi" || options.overlay === undefined ? cap : Math.min(cap, OPENCODE_OUTPUT_CAP));
|
|
36378
|
+
}
|
|
36379
|
+
const floor = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, softContext * 0.5);
|
|
36380
|
+
const flooredReserve = Math.min(softReserve, Math.max(0, softContext - floor));
|
|
36381
|
+
if (flooredReserve < softReserve) {
|
|
36382
|
+
logGeometryClampOnce(`soft-floor|${providerID}/${modelID}|${softReserve}|${flooredReserve}`, `output reserve clamped by the half-window floor for ${providerID}/${modelID}: reserve ${softReserve} → ${flooredReserve} (catalog context/output pair is contradictory)`, options.log);
|
|
36383
|
+
}
|
|
36384
|
+
softReserve = flooredReserve;
|
|
36385
|
+
usableSoft = Math.floor(softContext - softReserve);
|
|
36386
|
+
} else {
|
|
36387
|
+
usableSoft = input;
|
|
36388
|
+
}
|
|
36389
|
+
const hardWindow = hardContext ?? softContext ?? input;
|
|
36390
|
+
if (!isFinitePositive(hardWindow))
|
|
36391
|
+
return;
|
|
36392
|
+
let usableHard;
|
|
36393
|
+
if (geometry === "separate") {
|
|
36394
|
+
usableHard = hardWindow;
|
|
36395
|
+
} else if (geometry === "shared_truncating") {
|
|
36396
|
+
usableHard = hardWindow - PROMPT_WALL_MARGIN;
|
|
36397
|
+
} else if (options.harness === "pi" && providerID !== "openai-codex") {
|
|
36398
|
+
usableHard = hardWindow - PI_OUTPUT_FLOOR;
|
|
36399
|
+
} else if (options.harness === "pi") {
|
|
36400
|
+
usableHard = hardWindow - (output ?? OPENCODE_OUTPUT_CAP);
|
|
36401
|
+
} else {
|
|
36402
|
+
const requestedOutput = Math.min(output ?? OPENCODE_OUTPUT_CAP, OPENCODE_OUTPUT_CAP);
|
|
36403
|
+
usableHard = hardWindow - requestedOutput;
|
|
36404
|
+
}
|
|
36405
|
+
usableHard = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, Math.floor(usableHard));
|
|
36406
|
+
if (usableHard < usableSoft) {
|
|
36407
|
+
logGeometryClampOnce(`${providerID}/${modelID}|${usableSoft}|${usableHard}`, `usable hard limit clamped for ${providerID}/${modelID}: ${usableHard} → ${usableSoft} (overlay/provider inversion)`, options.log);
|
|
36408
|
+
usableHard = usableSoft;
|
|
36409
|
+
}
|
|
36410
|
+
return {
|
|
36411
|
+
usableSoft,
|
|
36412
|
+
usableHard,
|
|
36413
|
+
geometry,
|
|
36414
|
+
derivation: {
|
|
36415
|
+
window: Math.floor(softContext ?? usableSoft),
|
|
36416
|
+
reserve: Math.floor(Math.max(0, (softContext ?? usableSoft) - usableSoft)),
|
|
36417
|
+
reserveSource,
|
|
36418
|
+
geometry
|
|
36419
|
+
}
|
|
36420
|
+
};
|
|
36421
|
+
}
|
|
36422
|
+
function formatWindowDerivationLine(inputTokens, result) {
|
|
36423
|
+
const percentage = result.usableSoft > 0 ? inputTokens / result.usableSoft * 100 : 0;
|
|
36424
|
+
const reserveLabel = result.derivation.reserveSource === "wall_margin" ? "wall margin" : result.derivation.reserveSource === "none" ? "reserve" : "output reserve";
|
|
36425
|
+
return `Context: ${formatCompactTokens(inputTokens)} / ${formatCompactTokens(result.usableSoft)} usable (${percentage.toFixed(1)}%) — window ${formatCompactTokens(result.derivation.window)} − ${formatCompactTokens(result.derivation.reserve)} ${reserveLabel} [${result.geometry}]`;
|
|
36426
|
+
}
|
|
36427
|
+
function formatCompactTokens(value) {
|
|
36428
|
+
if (Math.abs(value) >= 1e6) {
|
|
36429
|
+
return `${(value / 1e6).toFixed(1).replace(/\.0$/, "")}m`;
|
|
36430
|
+
}
|
|
36431
|
+
if (Math.abs(value) >= 1000) {
|
|
36432
|
+
return `${(value / 1000).toFixed(1).replace(/\.0$/, "")}k`;
|
|
36433
|
+
}
|
|
36434
|
+
return Math.round(value).toLocaleString();
|
|
36435
|
+
}
|
|
36436
|
+
|
|
36437
|
+
// ../plugin/src/shared/models-dev-cache.ts
|
|
35765
36438
|
var MIN_SANE_LIMIT = 20000;
|
|
35766
36439
|
var MAX_SANE_LIMIT = 3000000;
|
|
35767
36440
|
function isSaneLimit(limit) {
|
|
35768
36441
|
return typeof limit === "number" && limit >= MIN_SANE_LIMIT && limit <= MAX_SANE_LIMIT;
|
|
35769
36442
|
}
|
|
35770
36443
|
var SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set(["google", "google-antigravity"]);
|
|
35771
|
-
var
|
|
35772
|
-
var
|
|
36444
|
+
var MIN_PLAUSIBLE_CONTEXT_LIMIT2 = 1024;
|
|
36445
|
+
var OUTPUT_RESERVE_CAP_RATIO2 = 0.25;
|
|
35773
36446
|
var outputReserveConfig;
|
|
35774
36447
|
var reserveClampLogSeen = new Set;
|
|
35775
36448
|
var apiCache = null;
|
|
35776
36449
|
var persistSeedLoaded = false;
|
|
35777
36450
|
function persistFilePath() {
|
|
35778
|
-
return
|
|
36451
|
+
return join7(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
|
|
35779
36452
|
}
|
|
35780
36453
|
function loadPersistedApiCacheOnce() {
|
|
35781
36454
|
if (persistSeedLoaded || apiCache !== null)
|
|
35782
36455
|
return;
|
|
35783
36456
|
persistSeedLoaded = true;
|
|
35784
36457
|
try {
|
|
35785
|
-
const raw =
|
|
36458
|
+
const raw = readFileSync10(persistFilePath(), "utf-8");
|
|
35786
36459
|
const obj = JSON.parse(raw);
|
|
35787
36460
|
const map2 = new Map;
|
|
35788
36461
|
for (const [key, persisted] of Object.entries(obj)) {
|
|
@@ -35796,7 +36469,7 @@ function loadPersistedApiCacheOnce() {
|
|
|
35796
36469
|
limit: isSaneLimit(limit) ? limit : undefined,
|
|
35797
36470
|
contextLimit: isSaneLimit(contextLimit) ? contextLimit : undefined,
|
|
35798
36471
|
inputLimit: isSaneLimit(inputLimit) ? inputLimit : undefined,
|
|
35799
|
-
outputLimit:
|
|
36472
|
+
outputLimit: isFinitePositive2(outputLimit) ? outputLimit : undefined,
|
|
35800
36473
|
vision
|
|
35801
36474
|
});
|
|
35802
36475
|
}
|
|
@@ -35807,27 +36480,24 @@ function loadPersistedApiCacheOnce() {
|
|
|
35807
36480
|
}
|
|
35808
36481
|
} catch {}
|
|
35809
36482
|
}
|
|
35810
|
-
function
|
|
36483
|
+
function isFinitePositive2(value) {
|
|
35811
36484
|
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
35812
36485
|
}
|
|
35813
|
-
function
|
|
35814
|
-
const
|
|
35815
|
-
const canonicalFull = piModelRefToCanonical(full);
|
|
35816
|
-
const candidates = [full, canonicalFull, modelID];
|
|
36486
|
+
function modelKeyLookupOrder3(providerID, modelID) {
|
|
36487
|
+
const candidates = [...modelRefLookupOrder(`${providerID}/${modelID}`), modelID];
|
|
35817
36488
|
const colon = modelID.lastIndexOf(":");
|
|
35818
36489
|
if (colon > 0) {
|
|
35819
36490
|
const bareModel = modelID.slice(0, colon);
|
|
35820
|
-
|
|
35821
|
-
candidates.push(providerBare, piModelRefToCanonical(providerBare), bareModel);
|
|
36491
|
+
candidates.push(...modelRefLookupOrder(`${providerID}/${bareModel}`), bareModel);
|
|
35822
36492
|
}
|
|
35823
36493
|
return [...new Set(candidates)];
|
|
35824
36494
|
}
|
|
35825
|
-
function
|
|
36495
|
+
function configuredOutputReserve2(config2, providerID, modelID) {
|
|
35826
36496
|
if (typeof config2 === "number")
|
|
35827
36497
|
return Number.isFinite(config2) && config2 >= 0 ? config2 : undefined;
|
|
35828
36498
|
if (!config2)
|
|
35829
36499
|
return;
|
|
35830
|
-
for (const candidate of
|
|
36500
|
+
for (const candidate of modelKeyLookupOrder3(providerID, modelID)) {
|
|
35831
36501
|
const value = config2[candidate];
|
|
35832
36502
|
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
|
|
35833
36503
|
return value;
|
|
@@ -35846,27 +36516,27 @@ function setOutputReserveConfig(config2) {
|
|
|
35846
36516
|
function resolveLimit(limit, providerID, modelID, reserveConfig = outputReserveConfig) {
|
|
35847
36517
|
if (!limit)
|
|
35848
36518
|
return;
|
|
35849
|
-
const context =
|
|
35850
|
-
const input =
|
|
36519
|
+
const context = isFinitePositive2(limit.context) ? limit.context : undefined;
|
|
36520
|
+
const input = isFinitePositive2(limit.input) ? limit.input : undefined;
|
|
35851
36521
|
if (input !== undefined && (context === undefined || input < context))
|
|
35852
36522
|
return input;
|
|
35853
36523
|
if (context === undefined)
|
|
35854
36524
|
return;
|
|
35855
|
-
const configuredReserve =
|
|
36525
|
+
const configuredReserve = configuredOutputReserve2(reserveConfig, providerID, modelID);
|
|
35856
36526
|
let reserve;
|
|
35857
36527
|
if (configuredReserve !== undefined) {
|
|
35858
36528
|
reserve = configuredReserve;
|
|
35859
36529
|
} else if (SEPARATE_OUTPUT_QUOTA_PROVIDERS.has(providerID)) {
|
|
35860
36530
|
reserve = 0;
|
|
35861
36531
|
} else {
|
|
35862
|
-
const output =
|
|
35863
|
-
const cap = context *
|
|
36532
|
+
const output = isFinitePositive2(limit.output) ? limit.output : 0;
|
|
36533
|
+
const cap = context * OUTPUT_RESERVE_CAP_RATIO2;
|
|
35864
36534
|
reserve = Math.min(output, cap);
|
|
35865
36535
|
if (output > cap) {
|
|
35866
36536
|
logReserveClampOnce(`cap|${providerID}/${modelID}|${context}|${output}`, `output reserve capped at 25% for ${providerID}/${modelID}: ${output} → ${cap}`);
|
|
35867
36537
|
}
|
|
35868
36538
|
}
|
|
35869
|
-
const floor = Math.max(
|
|
36539
|
+
const floor = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT2, context * 0.5);
|
|
35870
36540
|
const maxReserve = Math.max(0, context - floor);
|
|
35871
36541
|
if (reserve > maxReserve) {
|
|
35872
36542
|
logReserveClampOnce(`floor|${providerID}/${modelID}|${context}|${reserve}`, `output reserve clamped for ${providerID}/${modelID}: ${reserve} → ${maxReserve} (usable floor ${floor})`);
|
|
@@ -35874,15 +36544,46 @@ function resolveLimit(limit, providerID, modelID, reserveConfig = outputReserveC
|
|
|
35874
36544
|
}
|
|
35875
36545
|
return Math.floor(context - reserve);
|
|
35876
36546
|
}
|
|
36547
|
+
function getSdkWindowGeometry(providerID, modelID, detectedContextLimit, options) {
|
|
36548
|
+
loadPersistedApiCacheOnce();
|
|
36549
|
+
const metadata = lookupMetadataWithTagFallback(apiCache, providerID, modelID);
|
|
36550
|
+
if (!metadata)
|
|
36551
|
+
return;
|
|
36552
|
+
const rawContext = metadata.contextLimit ?? metadata.limit;
|
|
36553
|
+
const promptOnlyDetected = options?.detectedLimitProvenance === "prompt_only" && isFinitePositive2(detectedContextLimit) ? detectedContextLimit : undefined;
|
|
36554
|
+
const result = deriveWindowGeometry(providerID, modelID, {
|
|
36555
|
+
context: rawContext,
|
|
36556
|
+
input: metadata.inputLimit,
|
|
36557
|
+
output: metadata.outputLimit
|
|
36558
|
+
}, {
|
|
36559
|
+
overlay: resolveWindowOverlayFacts(providerID, modelID, getWindowOverlay()),
|
|
36560
|
+
reserveConfig: outputReserveConfig,
|
|
36561
|
+
harness: options?.harness ?? "opencode",
|
|
36562
|
+
contextCap: promptOnlyDetected === undefined && isFinitePositive2(detectedContextLimit) ? detectedContextLimit : undefined
|
|
36563
|
+
});
|
|
36564
|
+
if (!result || promptOnlyDetected === undefined)
|
|
36565
|
+
return result;
|
|
36566
|
+
const usableSoft = promptOnlyDetected;
|
|
36567
|
+
return {
|
|
36568
|
+
...result,
|
|
36569
|
+
usableSoft,
|
|
36570
|
+
usableHard: Math.max(usableSoft, Math.min(result.usableHard, promptOnlyDetected))
|
|
36571
|
+
};
|
|
36572
|
+
}
|
|
35877
36573
|
function getSdkContextLimit(providerID, modelID, detectedContextLimit, options) {
|
|
36574
|
+
if (options?.reservation !== "none") {
|
|
36575
|
+
return getSdkWindowGeometry(providerID, modelID, detectedContextLimit, {
|
|
36576
|
+
detectedLimitProvenance: options?.detectedLimitProvenance
|
|
36577
|
+
})?.usableSoft;
|
|
36578
|
+
}
|
|
35878
36579
|
loadPersistedApiCacheOnce();
|
|
35879
36580
|
const metadata = lookupMetadataWithTagFallback(apiCache, providerID, modelID);
|
|
35880
36581
|
if (!metadata)
|
|
35881
36582
|
return;
|
|
35882
36583
|
const rawContext = metadata.contextLimit ?? metadata.limit;
|
|
35883
|
-
const promptOnlyDetected = options?.detectedLimitProvenance === "prompt_only" &&
|
|
35884
|
-
const context = promptOnlyDetected === undefined &&
|
|
35885
|
-
const inputCandidates = [metadata.inputLimit, promptOnlyDetected].filter(
|
|
36584
|
+
const promptOnlyDetected = options?.detectedLimitProvenance === "prompt_only" && isFinitePositive2(detectedContextLimit) ? detectedContextLimit : undefined;
|
|
36585
|
+
const context = promptOnlyDetected === undefined && isFinitePositive2(detectedContextLimit) && isFinitePositive2(rawContext) ? Math.min(rawContext, detectedContextLimit) : promptOnlyDetected === undefined && isFinitePositive2(detectedContextLimit) ? detectedContextLimit : rawContext;
|
|
36586
|
+
const inputCandidates = [metadata.inputLimit, promptOnlyDetected].filter(isFinitePositive2);
|
|
35886
36587
|
const input = inputCandidates.length > 0 ? Math.min(...inputCandidates) : undefined;
|
|
35887
36588
|
return resolveLimit({
|
|
35888
36589
|
context,
|
|
@@ -35931,7 +36632,7 @@ function resolvePiLegacyFallback(sources) {
|
|
|
35931
36632
|
}
|
|
35932
36633
|
function loadConfigFile(path3, scope) {
|
|
35933
36634
|
try {
|
|
35934
|
-
const rawText =
|
|
36635
|
+
const rawText = readFileSync11(path3, "utf-8");
|
|
35935
36636
|
const substituted = substituteConfigVariables({
|
|
35936
36637
|
text: rawText,
|
|
35937
36638
|
configPath: path3,
|
|
@@ -36137,6 +36838,7 @@ function loadPiConfig(opts = {}) {
|
|
|
36137
36838
|
}
|
|
36138
36839
|
const parsed = parsePiConfig(rawConfig);
|
|
36139
36840
|
setOutputReserveConfig(parsed.config.output_reserve);
|
|
36841
|
+
setWindowOverlayPath(parsed.config.models?.window_overlay_path);
|
|
36140
36842
|
warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
|
|
36141
36843
|
return {
|
|
36142
36844
|
config: parsed.config,
|
|
@@ -36258,6 +36960,7 @@ function loadPiConfigDetailed(opts = {}) {
|
|
|
36258
36960
|
const recoveredTopLevelKeys = [];
|
|
36259
36961
|
const parsed = parsePiConfig(rawConfig, recoveredTopLevelKeys);
|
|
36260
36962
|
setOutputReserveConfig(parsed.config.output_reserve);
|
|
36963
|
+
setWindowOverlayPath(parsed.config.models?.window_overlay_path);
|
|
36261
36964
|
warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
|
|
36262
36965
|
const substitutionFailures = loadedFiles.flatMap(bindSubstitutionFailures);
|
|
36263
36966
|
const userLoaded = loadedFiles.find((loaded) => loaded.scope === "user");
|
|
@@ -39668,7 +40371,7 @@ function getEmbeddingProviderIdentity(config2) {
|
|
|
39668
40371
|
// ../plugin/src/features/magic-context/memory/embedding-local.ts
|
|
39669
40372
|
import { chmodSync as chmodSync2, mkdirSync as mkdirSync4 } from "node:fs";
|
|
39670
40373
|
import { open, stat, unlink, writeFile } from "node:fs/promises";
|
|
39671
|
-
import { dirname as dirname6, join as
|
|
40374
|
+
import { dirname as dirname6, join as join8 } from "node:path";
|
|
39672
40375
|
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
39673
40376
|
var LOCK_POLL_MS = 150;
|
|
39674
40377
|
var STALE_LOCK_MS = 3 * 60000;
|
|
@@ -39869,7 +40572,7 @@ class LocalEmbeddingProvider {
|
|
|
39869
40572
|
if (LogLevel && "ERROR" in LogLevel) {
|
|
39870
40573
|
env.logLevel = LogLevel.ERROR;
|
|
39871
40574
|
}
|
|
39872
|
-
const modelCacheDir =
|
|
40575
|
+
const modelCacheDir = join8(getMagicContextStorageDir(), "models");
|
|
39873
40576
|
try {
|
|
39874
40577
|
if (shouldEnforcePrivateStoragePermissions()) {
|
|
39875
40578
|
mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
|
|
@@ -39886,7 +40589,7 @@ class LocalEmbeddingProvider {
|
|
|
39886
40589
|
log("[magic-context] could not create model cache dir, using library default");
|
|
39887
40590
|
}
|
|
39888
40591
|
const createPipeline = transformersModule.pipeline;
|
|
39889
|
-
const lockPath =
|
|
40592
|
+
const lockPath = join8(modelCacheDir, ".load.lock");
|
|
39890
40593
|
const releaseLock = await acquireModelLoadLock(lockPath);
|
|
39891
40594
|
const stopHeartbeat = startLockHeartbeat(lockPath);
|
|
39892
40595
|
try {
|
|
@@ -40102,9 +40805,14 @@ function blockedEmbeddingEndpointReason(endpoint) {
|
|
|
40102
40805
|
function normalizeEndpoint3(endpoint) {
|
|
40103
40806
|
return endpoint?.trim().replace(/\/+$/, "") ?? "";
|
|
40104
40807
|
}
|
|
40105
|
-
function
|
|
40106
|
-
const
|
|
40107
|
-
|
|
40808
|
+
function parseEmbeddingModel(model) {
|
|
40809
|
+
const lastColon = model.lastIndexOf(":");
|
|
40810
|
+
if (lastColon > model.lastIndexOf("/")) {
|
|
40811
|
+
return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
|
|
40812
|
+
}
|
|
40813
|
+
return { base: model };
|
|
40814
|
+
}
|
|
40815
|
+
function matchNormalizedEmbeddingModels(a, b) {
|
|
40108
40816
|
if (a.length === 0 || b.length === 0)
|
|
40109
40817
|
return true;
|
|
40110
40818
|
if (a === b)
|
|
@@ -40118,6 +40826,16 @@ function embeddingModelsMatch(served, requested) {
|
|
|
40118
40826
|
return true;
|
|
40119
40827
|
return false;
|
|
40120
40828
|
}
|
|
40829
|
+
function embeddingModelsMatch(served, requested) {
|
|
40830
|
+
const a = served.trim().toLowerCase();
|
|
40831
|
+
const b = requested.trim().toLowerCase();
|
|
40832
|
+
const servedModel = parseEmbeddingModel(a);
|
|
40833
|
+
const requestedModel = parseEmbeddingModel(b);
|
|
40834
|
+
if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
|
|
40835
|
+
return false;
|
|
40836
|
+
}
|
|
40837
|
+
return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
|
|
40838
|
+
}
|
|
40121
40839
|
var FAILURE_THRESHOLD = 3;
|
|
40122
40840
|
var FAILURE_WINDOW_MS = 60000;
|
|
40123
40841
|
var OPEN_DURATION_MS = 5 * 60000;
|
|
@@ -40248,7 +40966,7 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
40248
40966
|
const servedModel = typeof body.model === "string" ? body.model : "";
|
|
40249
40967
|
if (this.model && servedModel && !embeddingModelsMatch(servedModel, this.model)) {
|
|
40250
40968
|
if (!this.modelMismatchLogged) {
|
|
40251
|
-
log(`[magic-context] embedding endpoint served a DIFFERENT model than requested — refusing the substituted vectors (they have the wrong dimensions/space). requested="${this.model}" served="${servedModel}".
|
|
40969
|
+
log(`[magic-context] embedding endpoint served a DIFFERENT model than requested — refusing the substituted vectors (they have the wrong dimensions/space). requested="${this.model}" served="${servedModel}". Check that the endpoint serves the requested model; variant suffixes and vendor prefixes are matched automatically.`);
|
|
40252
40970
|
this.modelMismatchLogged = true;
|
|
40253
40971
|
}
|
|
40254
40972
|
this.recordFailure(isProbe);
|
|
@@ -42833,7 +43551,7 @@ Two recovery modes for finer detail:
|
|
|
42833
43551
|
var CTX_EXPAND_TOKEN_BUDGET = 15000;
|
|
42834
43552
|
|
|
42835
43553
|
// ../plugin/src/tools/ctx-expand/render.ts
|
|
42836
|
-
function
|
|
43554
|
+
function isRecord3(value) {
|
|
42837
43555
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
42838
43556
|
}
|
|
42839
43557
|
function roleLabel(role) {
|
|
@@ -42862,15 +43580,15 @@ function keyArg(input) {
|
|
|
42862
43580
|
function asToolPart(part) {
|
|
42863
43581
|
const type = typeof part.type === "string" ? part.type : "";
|
|
42864
43582
|
if (type === "tool") {
|
|
42865
|
-
const state =
|
|
43583
|
+
const state = isRecord3(part.state) ? part.state : null;
|
|
42866
43584
|
const output = state && typeof state.output === "string" ? state.output : state && state.output != null ? JSON.stringify(state.output) : null;
|
|
42867
|
-
const metadata = state &&
|
|
43585
|
+
const metadata = state && isRecord3(state.metadata) ? state.metadata : null;
|
|
42868
43586
|
const title = state && typeof state.title === "string" && state.title || metadata && typeof metadata.title === "string" && metadata.title || null;
|
|
42869
43587
|
return {
|
|
42870
43588
|
name: typeof part.tool === "string" ? part.tool : "tool",
|
|
42871
43589
|
callId: typeof part.callID === "string" ? part.callID : "",
|
|
42872
43590
|
title,
|
|
42873
|
-
input: state &&
|
|
43591
|
+
input: state && isRecord3(state.input) ? state.input : null,
|
|
42874
43592
|
output
|
|
42875
43593
|
};
|
|
42876
43594
|
}
|
|
@@ -42879,7 +43597,7 @@ function asToolPart(part) {
|
|
|
42879
43597
|
name: typeof part.name === "string" ? part.name : "tool",
|
|
42880
43598
|
callId: typeof part.id === "string" ? part.id : "",
|
|
42881
43599
|
title: null,
|
|
42882
|
-
input:
|
|
43600
|
+
input: isRecord3(part.input) ? part.input : null,
|
|
42883
43601
|
output: null
|
|
42884
43602
|
};
|
|
42885
43603
|
}
|
|
@@ -42908,7 +43626,7 @@ function reasoningOf(part) {
|
|
|
42908
43626
|
return null;
|
|
42909
43627
|
}
|
|
42910
43628
|
function renderPartPreview(part) {
|
|
42911
|
-
if (!
|
|
43629
|
+
if (!isRecord3(part))
|
|
42912
43630
|
return null;
|
|
42913
43631
|
const text = textOf(part);
|
|
42914
43632
|
if (text !== null) {
|
|
@@ -42932,7 +43650,7 @@ function renderPartPreview(part) {
|
|
|
42932
43650
|
return ` • [${type}]`;
|
|
42933
43651
|
}
|
|
42934
43652
|
function renderPartFull(part) {
|
|
42935
|
-
if (!
|
|
43653
|
+
if (!isRecord3(part))
|
|
42936
43654
|
return null;
|
|
42937
43655
|
const text = textOf(part);
|
|
42938
43656
|
if (text !== null) {
|
|
@@ -48039,25 +48757,6 @@ function getMaxMemoryIdForProjects(db, projectPaths, ownIdentities, shareCategor
|
|
|
48039
48757
|
AND (expires_at IS NULL OR expires_at > ?)${sharingFilter.clause}`).get(...identities, expiryCutoff, ...sharingFilter.params);
|
|
48040
48758
|
return typeof row?.max_id === "number" ? row.max_id : 0;
|
|
48041
48759
|
}
|
|
48042
|
-
function readNewMemoriesForM1Union(db, projectPaths, afterId, expiryCutoff, ownIdentities, shareCategories) {
|
|
48043
|
-
const identities = uniqueValues(projectPaths);
|
|
48044
|
-
if (identities.length === 0)
|
|
48045
|
-
return [];
|
|
48046
|
-
const sharingFilter = buildWorkspaceMemorySqlFilter({
|
|
48047
|
-
identities,
|
|
48048
|
-
ownIdentities,
|
|
48049
|
-
shareCategories,
|
|
48050
|
-
includeClassificationFields: hasMemoryShareableColumn(db) && hasMemoryScopeColumn(db)
|
|
48051
|
-
});
|
|
48052
|
-
const rows = db.prepare(`SELECT ${getMemorySelectColumns(db)}
|
|
48053
|
-
FROM memories
|
|
48054
|
-
WHERE project_path IN (${sqlPlaceholders(identities)})
|
|
48055
|
-
AND id > ?
|
|
48056
|
-
AND status IN ('active', 'permanent')
|
|
48057
|
-
AND (expires_at IS NULL OR expires_at > ?)${sharingFilter.clause}
|
|
48058
|
-
ORDER BY ${MEMORY_CATEGORY_ORDER_SQL}, id ASC`).all(...identities, afterId, expiryCutoff, ...sharingFilter.params).filter(isMemoryRow);
|
|
48059
|
-
return rows.map(toMemory);
|
|
48060
|
-
}
|
|
48061
48760
|
function getAllActiveMemoriesForMigration(db, projectPath) {
|
|
48062
48761
|
const rows = getActiveMemoriesNoExpiryStatement(db).all(projectPath).filter(isMemoryRow);
|
|
48063
48762
|
return rows.map(toMemory);
|
|
@@ -49119,7 +49818,7 @@ import { isAbsolute as isAbsolute5 } from "node:path";
|
|
|
49119
49818
|
// ../retina-local-fs/src/path-fence.ts
|
|
49120
49819
|
import { lstat, readlink, realpath } from "node:fs/promises";
|
|
49121
49820
|
import { homedir as homedir6 } from "node:os";
|
|
49122
|
-
import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute4, join as
|
|
49821
|
+
import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute4, join as join9, relative, resolve as resolve4, sep } from "node:path";
|
|
49123
49822
|
|
|
49124
49823
|
// ../retina-local-fs/src/errors.ts
|
|
49125
49824
|
class ProviderError extends Error {
|
|
@@ -49134,7 +49833,7 @@ class ProviderError extends Error {
|
|
|
49134
49833
|
// ../retina-local-fs/src/path-fence.ts
|
|
49135
49834
|
async function resolveAndFenceProviderPath(configuredPath, options) {
|
|
49136
49835
|
const { home, dataDirectory } = await resolveFenceRoots(options);
|
|
49137
|
-
const expanded = configuredPath.startsWith("~/") ?
|
|
49836
|
+
const expanded = configuredPath.startsWith("~/") ? join9(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
|
|
49138
49837
|
const absolute = isAbsolute4(expanded) ? resolve4(expanded) : resolve4(options.cwd ?? process.cwd(), expanded);
|
|
49139
49838
|
const canonical = await canonicalPath(absolute, options.allowMissing);
|
|
49140
49839
|
if (isFencedPath(canonical, home, dataDirectory)) {
|
|
@@ -49150,7 +49849,7 @@ async function resolveFenceRoots(options) {
|
|
|
49150
49849
|
} catch (error51) {
|
|
49151
49850
|
throw fsError(configuredHomePath, error51);
|
|
49152
49851
|
}
|
|
49153
|
-
const configuredDataDirectory = resolve4(options.dataDirectory ?? process.env.XDG_DATA_HOME ??
|
|
49852
|
+
const configuredDataDirectory = resolve4(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join9(home, ".local", "share"));
|
|
49154
49853
|
const dataDirectory = await canonicalPath(configuredDataDirectory, true);
|
|
49155
49854
|
return { home, dataDirectory };
|
|
49156
49855
|
}
|
|
@@ -49169,7 +49868,7 @@ async function canonicalPath(path4, allowMissing) {
|
|
|
49169
49868
|
if (metadata.isSymbolicLink()) {
|
|
49170
49869
|
const target2 = await readlink(candidate);
|
|
49171
49870
|
const resolvedTarget = resolve4(dirname7(candidate), target2);
|
|
49172
|
-
return canonicalPath(
|
|
49871
|
+
return canonicalPath(join9(resolvedTarget, ...suffix), true);
|
|
49173
49872
|
}
|
|
49174
49873
|
} catch (candidateError) {
|
|
49175
49874
|
if (!isMissingError(candidateError)) {
|
|
@@ -49183,7 +49882,7 @@ async function canonicalPath(path4, allowMissing) {
|
|
|
49183
49882
|
suffix.unshift(basename3(candidate));
|
|
49184
49883
|
candidate = parent;
|
|
49185
49884
|
try {
|
|
49186
|
-
return
|
|
49885
|
+
return join9(await realpath(candidate), ...suffix);
|
|
49187
49886
|
} catch (parentError) {
|
|
49188
49887
|
if (!isMissingError(parentError)) {
|
|
49189
49888
|
throw fsError(path4, parentError);
|
|
@@ -49192,8 +49891,8 @@ async function canonicalPath(path4, allowMissing) {
|
|
|
49192
49891
|
}
|
|
49193
49892
|
}
|
|
49194
49893
|
}
|
|
49195
|
-
function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ??
|
|
49196
|
-
const cortexkitRoot =
|
|
49894
|
+
function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join9(resolve4(homeDirectory), ".local", "share")) {
|
|
49895
|
+
const cortexkitRoot = join9(resolve4(dataDirectory), "cortexkit");
|
|
49197
49896
|
const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
|
|
49198
49897
|
const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
|
|
49199
49898
|
const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
|
|
@@ -49600,6 +50299,63 @@ function singleLine(value) {
|
|
|
49600
50299
|
return value.replace(/\s+/g, " ").trim();
|
|
49601
50300
|
}
|
|
49602
50301
|
|
|
50302
|
+
// ../plugin/src/features/magic-context/smart-notes/wake-plane.ts
|
|
50303
|
+
import { join as join10 } from "node:path";
|
|
50304
|
+
var WAKE_PLANE_CAPABILITY = "wake.create";
|
|
50305
|
+
var WAKE_PLANE_STATUS_TTL_MS = 5 * 60 * 1000;
|
|
50306
|
+
var WAKE_PLANE_HANDSHAKE_TIMEOUT_MS = 2000;
|
|
50307
|
+
var cachedStatus = null;
|
|
50308
|
+
var inFlightProbe = null;
|
|
50309
|
+
var catalogProbe = probeWakePlaneCatalog;
|
|
50310
|
+
var now = () => Date.now();
|
|
50311
|
+
function connectionFile() {
|
|
50312
|
+
return join10(getDataDir(), "cortexkit", "run", "subc-connection.json");
|
|
50313
|
+
}
|
|
50314
|
+
async function probeWakePlaneCatalog() {
|
|
50315
|
+
const file2 = connectionFile();
|
|
50316
|
+
if (!await connectionFileExists(file2)) {
|
|
50317
|
+
throw new Error("subc connection is not configured");
|
|
50318
|
+
}
|
|
50319
|
+
const client = await SubcClient.connect({
|
|
50320
|
+
connectionFile: file2,
|
|
50321
|
+
handshakeTimeoutMs: WAKE_PLANE_HANDSHAKE_TIMEOUT_MS
|
|
50322
|
+
});
|
|
50323
|
+
try {
|
|
50324
|
+
return await client.catalogList();
|
|
50325
|
+
} finally {
|
|
50326
|
+
client.close();
|
|
50327
|
+
}
|
|
50328
|
+
}
|
|
50329
|
+
function catalogHasWakePlane(entries) {
|
|
50330
|
+
return entries.some((entry) => Array.isArray(entry.control_ops) && entry.control_ops.includes(WAKE_PLANE_CAPABILITY));
|
|
50331
|
+
}
|
|
50332
|
+
async function probeStatus() {
|
|
50333
|
+
try {
|
|
50334
|
+
return catalogHasWakePlane(await catalogProbe()) ? "present" : "absent";
|
|
50335
|
+
} catch {
|
|
50336
|
+
return "unknown";
|
|
50337
|
+
}
|
|
50338
|
+
}
|
|
50339
|
+
async function wakePlaneStatus() {
|
|
50340
|
+
const cached2 = cachedStatus;
|
|
50341
|
+
if (cached2 && now() < cached2.expiresAt)
|
|
50342
|
+
return cached2.status;
|
|
50343
|
+
if (inFlightProbe)
|
|
50344
|
+
return await inFlightProbe;
|
|
50345
|
+
const startedAt = now();
|
|
50346
|
+
const probe = probeStatus().then((status) => {
|
|
50347
|
+
cachedStatus = { status, expiresAt: startedAt + WAKE_PLANE_STATUS_TTL_MS };
|
|
50348
|
+
return status;
|
|
50349
|
+
});
|
|
50350
|
+
inFlightProbe = probe;
|
|
50351
|
+
try {
|
|
50352
|
+
return await probe;
|
|
50353
|
+
} finally {
|
|
50354
|
+
if (inFlightProbe === probe)
|
|
50355
|
+
inFlightProbe = null;
|
|
50356
|
+
}
|
|
50357
|
+
}
|
|
50358
|
+
|
|
49603
50359
|
// ../plugin/src/tools/ctx-note/constants.ts
|
|
49604
50360
|
var CTX_NOTE_DESCRIPTION = `Working notes for this session's future — reminders, follow-ups, and things to revisit later.
|
|
49605
50361
|
|
|
@@ -49727,6 +50483,15 @@ function createCtxNoteTool(deps) {
|
|
|
49727
50483
|
const anchorOrdinal = captureAnchorOrdinal(deps.db, sessionId);
|
|
49728
50484
|
const surfaceCondition = params.surface_condition?.trim();
|
|
49729
50485
|
if (surfaceCondition) {
|
|
50486
|
+
if (await wakePlaneStatus() === "present") {
|
|
50487
|
+
const note3 = addNote(deps.db, "session", {
|
|
50488
|
+
sessionId,
|
|
50489
|
+
content,
|
|
50490
|
+
anchorOrdinal
|
|
50491
|
+
});
|
|
50492
|
+
return ok3(`Saved session note #${note3.id}.
|
|
50493
|
+
wake plane active — create a scheduled wake instead; stored as a plain note.`);
|
|
50494
|
+
}
|
|
49730
50495
|
if (dreamerEnabled !== true) {
|
|
49731
50496
|
return err3("Error: Smart notes require dreamer to be enabled. Enable dreamer in magic-context.jsonc to use surface_condition.");
|
|
49732
50497
|
}
|
|
@@ -50041,9 +50806,9 @@ function createCtxReduceTool(deps) {
|
|
|
50041
50806
|
}
|
|
50042
50807
|
try {
|
|
50043
50808
|
deps.db.transaction(() => {
|
|
50044
|
-
const
|
|
50809
|
+
const now2 = Date.now();
|
|
50045
50810
|
for (const id of dropIds) {
|
|
50046
|
-
queuePendingOp(deps.db, sessionId, id, "drop",
|
|
50811
|
+
queuePendingOp(deps.db, sessionId, id, "drop", now2);
|
|
50047
50812
|
}
|
|
50048
50813
|
})();
|
|
50049
50814
|
} catch (error51) {
|
|
@@ -52256,11 +53021,11 @@ var USER_MEMORY_CANDIDATE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
|
52256
53021
|
function insertUserMemoryCandidates(db, candidates2) {
|
|
52257
53022
|
if (candidates2.length === 0)
|
|
52258
53023
|
return;
|
|
52259
|
-
const
|
|
53024
|
+
const now2 = Date.now();
|
|
52260
53025
|
const stmt = db.prepare("INSERT INTO user_memory_candidates (content, session_id, source_compartment_start, source_compartment_end, created_at) VALUES (?, ?, ?, ?, ?)");
|
|
52261
53026
|
db.transaction(() => {
|
|
52262
53027
|
for (const c of candidates2) {
|
|
52263
|
-
stmt.run(c.content, c.sessionId, c.sourceCompartmentStart ?? null, c.sourceCompartmentEnd ?? null,
|
|
53028
|
+
stmt.run(c.content, c.sessionId, c.sourceCompartmentStart ?? null, c.sourceCompartmentEnd ?? null, now2);
|
|
52264
53029
|
}
|
|
52265
53030
|
})();
|
|
52266
53031
|
}
|
|
@@ -52281,18 +53046,49 @@ function deleteUserMemoryCandidates(db, ids) {
|
|
|
52281
53046
|
const placeholders4 = ids.map(() => "?").join(",");
|
|
52282
53047
|
db.prepare(`DELETE FROM user_memory_candidates WHERE id IN (${placeholders4})`).run(...ids);
|
|
52283
53048
|
}
|
|
52284
|
-
function pruneExpiredUserMemoryCandidates(db, ttlMs,
|
|
52285
|
-
const cutoff =
|
|
53049
|
+
function pruneExpiredUserMemoryCandidates(db, ttlMs, now2 = Date.now()) {
|
|
53050
|
+
const cutoff = now2 - ttlMs;
|
|
52286
53051
|
const result = db.prepare("DELETE FROM user_memory_candidates WHERE created_at < ?").run(cutoff);
|
|
52287
53052
|
return Number(result.changes ?? 0);
|
|
52288
53053
|
}
|
|
53054
|
+
function loadUserMemorySourceProvenance(db, candidateIds) {
|
|
53055
|
+
const ids = [...new Set(candidateIds)].sort((a, b) => a - b);
|
|
53056
|
+
if (ids.length === 0)
|
|
53057
|
+
return [];
|
|
53058
|
+
const placeholders4 = ids.map(() => "?").join(",");
|
|
53059
|
+
const rows = db.prepare(`SELECT id, session_id, source_compartment_start, source_compartment_end
|
|
53060
|
+
FROM user_memory_candidates
|
|
53061
|
+
WHERE id IN (${placeholders4})
|
|
53062
|
+
ORDER BY id ASC`).all(...ids);
|
|
53063
|
+
return rows.map((row) => ({
|
|
53064
|
+
candidateId: row.id,
|
|
53065
|
+
sessionId: row.session_id,
|
|
53066
|
+
sourceCompartmentStart: row.source_compartment_start,
|
|
53067
|
+
sourceCompartmentEnd: row.source_compartment_end
|
|
53068
|
+
}));
|
|
53069
|
+
}
|
|
53070
|
+
function serializeUserMemorySourceProvenance(provenance, sourceCandidateIds) {
|
|
53071
|
+
if (provenance.length === 0 && sourceCandidateIds.length > 0)
|
|
53072
|
+
return null;
|
|
53073
|
+
return JSON.stringify(provenance.map((source) => ({
|
|
53074
|
+
candidate_id: source.candidateId,
|
|
53075
|
+
session_id: source.sessionId,
|
|
53076
|
+
source_compartment_start: source.sourceCompartmentStart,
|
|
53077
|
+
source_compartment_end: source.sourceCompartmentEnd
|
|
53078
|
+
})));
|
|
53079
|
+
}
|
|
52289
53080
|
function insertUserMemory(db, content, sourceCandidateIds) {
|
|
52290
|
-
|
|
52291
|
-
|
|
52292
|
-
|
|
53081
|
+
return db.transaction(() => {
|
|
53082
|
+
const now2 = Date.now();
|
|
53083
|
+
const sourceProvenance = loadUserMemorySourceProvenance(db, sourceCandidateIds);
|
|
53084
|
+
const result = db.prepare(`INSERT INTO user_memories
|
|
53085
|
+
(content, status, promoted_at, source_candidate_ids, source_candidate_provenance, created_at, updated_at)
|
|
53086
|
+
VALUES (?, 'active', ?, ?, ?, ?, ?)`).run(content, now2, JSON.stringify(sourceCandidateIds), serializeUserMemorySourceProvenance(sourceProvenance, sourceCandidateIds), now2, now2);
|
|
53087
|
+
return Number(result.lastInsertRowid);
|
|
53088
|
+
})();
|
|
52293
53089
|
}
|
|
52294
53090
|
function getActiveUserMemories(db) {
|
|
52295
|
-
const rows = db.prepare("SELECT id, content, status, promoted_at, source_candidate_ids, created_at, updated_at FROM user_memories WHERE status = 'active' ORDER BY promoted_at ASC, id ASC").all();
|
|
53091
|
+
const rows = db.prepare("SELECT id, content, status, promoted_at, source_candidate_ids, source_candidate_provenance, created_at, updated_at FROM user_memories WHERE status = 'active' ORDER BY promoted_at ASC, id ASC").all();
|
|
52296
53092
|
return rows.map(parseUserMemoryRow);
|
|
52297
53093
|
}
|
|
52298
53094
|
function updateUserMemoryContent(db, id, content) {
|
|
@@ -52301,17 +53097,49 @@ function updateUserMemoryContent(db, id, content) {
|
|
|
52301
53097
|
function dismissUserMemory(db, id) {
|
|
52302
53098
|
db.prepare("UPDATE user_memories SET status = 'dismissed', updated_at = ? WHERE id = ?").run(Date.now(), id);
|
|
52303
53099
|
}
|
|
52304
|
-
function
|
|
52305
|
-
let candidateIds = [];
|
|
53100
|
+
function parseCandidateIds2(raw) {
|
|
52306
53101
|
try {
|
|
52307
|
-
|
|
52308
|
-
|
|
53102
|
+
const parsed = JSON.parse(raw);
|
|
53103
|
+
return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "number" && Number.isFinite(id)) : [];
|
|
53104
|
+
} catch {
|
|
53105
|
+
return [];
|
|
53106
|
+
}
|
|
53107
|
+
}
|
|
53108
|
+
function parseUserMemorySourceProvenance(raw) {
|
|
53109
|
+
if (raw === null)
|
|
53110
|
+
return null;
|
|
53111
|
+
try {
|
|
53112
|
+
const parsed = JSON.parse(raw);
|
|
53113
|
+
if (!Array.isArray(parsed))
|
|
53114
|
+
return null;
|
|
53115
|
+
const provenance = [];
|
|
53116
|
+
for (const value of parsed) {
|
|
53117
|
+
if (!value || typeof value !== "object")
|
|
53118
|
+
return null;
|
|
53119
|
+
const source = value;
|
|
53120
|
+
if (typeof source.candidate_id !== "number" || !Number.isFinite(source.candidate_id) || typeof source.session_id !== "string" || source.source_compartment_start !== null && typeof source.source_compartment_start !== "number" || source.source_compartment_end !== null && typeof source.source_compartment_end !== "number") {
|
|
53121
|
+
return null;
|
|
53122
|
+
}
|
|
53123
|
+
provenance.push({
|
|
53124
|
+
candidateId: source.candidate_id,
|
|
53125
|
+
sessionId: source.session_id,
|
|
53126
|
+
sourceCompartmentStart: source.source_compartment_start,
|
|
53127
|
+
sourceCompartmentEnd: source.source_compartment_end
|
|
53128
|
+
});
|
|
53129
|
+
}
|
|
53130
|
+
return provenance;
|
|
53131
|
+
} catch {
|
|
53132
|
+
return null;
|
|
53133
|
+
}
|
|
53134
|
+
}
|
|
53135
|
+
function parseUserMemoryRow(row) {
|
|
52309
53136
|
return {
|
|
52310
53137
|
id: row.id,
|
|
52311
53138
|
content: row.content,
|
|
52312
53139
|
status: row.status === "dismissed" ? "dismissed" : "active",
|
|
52313
53140
|
promotedAt: row.promoted_at,
|
|
52314
|
-
sourceCandidateIds:
|
|
53141
|
+
sourceCandidateIds: parseCandidateIds2(row.source_candidate_ids),
|
|
53142
|
+
sourceProvenance: parseUserMemorySourceProvenance(row.source_candidate_provenance),
|
|
52315
53143
|
createdAt: row.created_at,
|
|
52316
53144
|
updatedAt: row.updated_at
|
|
52317
53145
|
};
|
|
@@ -52365,7 +53193,7 @@ class BoundedSessionMap {
|
|
|
52365
53193
|
// ../plugin/src/features/magic-context/compaction-marker.ts
|
|
52366
53194
|
import { createHash as createHash16 } from "node:crypto";
|
|
52367
53195
|
import { existsSync as existsSync13 } from "node:fs";
|
|
52368
|
-
import { join as
|
|
53196
|
+
import { join as join11 } from "node:path";
|
|
52369
53197
|
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
52370
53198
|
var ID_PREFIX_HEX_LENGTH = 12;
|
|
52371
53199
|
var ID_SUFFIX_LENGTH = 14;
|
|
@@ -52391,7 +53219,7 @@ function generatePartId(timestampMs, counter = 0n, identity = "") {
|
|
|
52391
53219
|
return generateId("prt", timestampMs, counter, identity);
|
|
52392
53220
|
}
|
|
52393
53221
|
function getOpenCodeDbPath2() {
|
|
52394
|
-
return
|
|
53222
|
+
return join11(getDataDir(), "opencode", "opencode.db");
|
|
52395
53223
|
}
|
|
52396
53224
|
var cachedWriteDb = null;
|
|
52397
53225
|
var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
|
|
@@ -53577,4 +54405,4 @@ function registerMagicContextTools(pi, opts) {
|
|
|
53577
54405
|
}
|
|
53578
54406
|
}
|
|
53579
54407
|
|
|
53580
|
-
export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap,
|
|
54408
|
+
export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, getSdkContextLimit, resolveModelConfigOrDefault, normalizeTodoStateJson, buildSyntheticTodoPart, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };
|