@cortexkit/pi-magic-context 0.44.4 → 0.45.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/embedding-worker.js +47 -0
- package/dist/emscripten-module-0g8f45e6.js +602 -0
- package/dist/emscripten-module-0pekdjxz.js +1532 -0
- package/dist/emscripten-module-e67xwsp3.js +503 -0
- package/dist/emscripten-module-pj1vyb44.js +4559 -0
- package/dist/ffi-3cx1cxpk.js +78 -0
- package/dist/ffi-7bqqe4cd.js +91 -0
- package/dist/ffi-7e6gryj5.js +91 -0
- package/dist/ffi-bpvkebwr.js +78 -0
- package/dist/historian-calibration-extension.js +7 -4
- package/dist/{index-5am7amy4.js → index-2bw9k8nx.js} +7848 -23072
- package/dist/index-2pbbk3en.js +410 -0
- package/dist/index-4d3cba70.js +10 -0
- package/dist/{index-59dmj4zs.js → index-7n8gb6j3.js} +165 -3
- package/dist/{index-97e5fzy3.js → index-7s5yk3za.js} +1 -1
- package/dist/index-901ekbga.js +244 -0
- package/dist/index-e16q5sd7.js +240 -0
- package/dist/index-g0xfx1c2.js +275 -0
- package/dist/{module-asyncify-2EFITU5U-rkqjhjxd.js → index-g20jdh0p.js} +114 -105
- package/dist/index-j0mbc5vj.js +359 -0
- package/dist/index-k0yd1ph9.js +7774 -0
- package/dist/{index-5fw91enm.js → index-n3g5mwa8.js} +1 -1
- package/dist/index-q1yc6bs0.js +104 -0
- package/dist/index-ttf0cqq8.js +8938 -0
- package/dist/{index-npagr1cy.js → index-vxjgsr9m.js} +736 -904
- package/dist/{index-n8kg008j.js → index-w76x3af7.js} +28 -18
- package/dist/index.js +3983 -1670
- package/dist/{message-time-backfill-5yrp95cx.js → message-time-backfill-g83dkh8m.js} +19 -4
- package/dist/migration-worker.js +51 -0
- package/dist/module-ES6BEMUI-3cet1pyp.js +12 -0
- package/dist/module-asyncify-2EFITU5U-c2razzd9.js +6 -0
- package/dist/{read-session-chunk-w493f72c.js → read-session-chunk-kmt7a6zj.js} +32 -5
- package/dist/rpc-notifications-gm1mdpwh.js +16 -0
- package/dist/{safe-notification-target-y3hg2m7p.js → safe-notification-target-6cn3z99t.js} +2 -2
- package/dist/subagent-entry.js +15 -6
- package/package.json +4 -4
- package/dist/index-b3eqj1g6.js +0 -51
- package/dist/index-rn7gafjr.js +0 -8
- package/dist/index-v6t0tg85.js +0 -13
- package/dist/rpc-notifications-jxy30tgz.js +0 -8
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// ../plugin/src/shared/sqlite.ts
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
var reportSlowPrivilegedWrite;
|
|
4
|
+
function registerSlowWriteReporter(reporter) {
|
|
5
|
+
reportSlowPrivilegedWrite = reporter;
|
|
6
|
+
}
|
|
7
|
+
var sqliteDiagnosticSink;
|
|
8
|
+
function registerSqliteDiagnosticSink(sink) {
|
|
9
|
+
sqliteDiagnosticSink = sink;
|
|
10
|
+
}
|
|
11
|
+
function reportSqliteDiagnostic(message) {
|
|
12
|
+
try {
|
|
13
|
+
sqliteDiagnosticSink?.(`[magic-context] ${message}`);
|
|
14
|
+
} catch {}
|
|
15
|
+
}
|
|
16
|
+
function detectSqliteRuntime() {
|
|
17
|
+
const hasBunVersion = typeof process !== "undefined" && typeof process.versions?.bun === "string";
|
|
18
|
+
const hasBunGlobal = typeof globalThis !== "undefined" && typeof globalThis.Bun !== "undefined";
|
|
19
|
+
return hasBunVersion || hasBunGlobal ? "Bun" : "Node.js";
|
|
20
|
+
}
|
|
21
|
+
var bunSpec = "bun:" + "sqlite";
|
|
22
|
+
var nodeSpec = "node:" + "sqlite";
|
|
23
|
+
async function importSqliteModule(specifier) {
|
|
24
|
+
return await import(specifier);
|
|
25
|
+
}
|
|
26
|
+
function isModuleNotFoundError(error, specifier) {
|
|
27
|
+
const candidate = error;
|
|
28
|
+
const code = typeof candidate?.code === "string" ? candidate.code : "";
|
|
29
|
+
const name = typeof candidate?.name === "string" ? candidate.name : "";
|
|
30
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
31
|
+
const details = `${code} ${name} ${message}`.toLowerCase();
|
|
32
|
+
const mentionsSpecifier = details.includes(specifier.toLowerCase());
|
|
33
|
+
if (!mentionsSpecifier)
|
|
34
|
+
return false;
|
|
35
|
+
return code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND" || name === "ResolveMessage" || details.includes("module not found") || details.includes("cannot find module") || details.includes("cannot find package") || details.includes("no such built-in module");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
class SqliteRuntimeUnavailableError extends Error {
|
|
39
|
+
runtime;
|
|
40
|
+
specifier;
|
|
41
|
+
constructor(runtime, specifier, cause) {
|
|
42
|
+
const requirement = specifier === nodeSpec ? "Requires Node.js >= 24, or Bun with bun:sqlite — this Bun build lacks node:sqlite." : "Requires Bun with bun:sqlite, or Node.js >= 24 — this Bun build lacks bun:sqlite.";
|
|
43
|
+
super(`Magic Context detected ${runtime}, but could not load ${specifier}. ${requirement}`, { cause });
|
|
44
|
+
this.name = "SqliteRuntimeUnavailableError";
|
|
45
|
+
this.runtime = runtime;
|
|
46
|
+
this.specifier = specifier;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function loadSqliteModule(runtime = detectSqliteRuntime(), importer = importSqliteModule) {
|
|
50
|
+
const specifier = runtime === "Bun" ? bunSpec : nodeSpec;
|
|
51
|
+
try {
|
|
52
|
+
return await importer(specifier);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (isModuleNotFoundError(error, specifier)) {
|
|
55
|
+
throw new SqliteRuntimeUnavailableError(runtime, specifier, error);
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
var detectedRuntime = detectSqliteRuntime();
|
|
61
|
+
var isBun = detectedRuntime === "Bun";
|
|
62
|
+
var sqliteModule = await loadSqliteModule(detectedRuntime);
|
|
63
|
+
var DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
|
|
64
|
+
var trackedSqliteConnections = new Map;
|
|
65
|
+
var nextSqliteConnectionSequence = 1;
|
|
66
|
+
function installTransactionRouting(db, readonly) {
|
|
67
|
+
const nativeExec = db.exec.bind(db);
|
|
68
|
+
Object.defineProperty(db, "exec", {
|
|
69
|
+
configurable: true,
|
|
70
|
+
writable: true,
|
|
71
|
+
value: (sql) => {
|
|
72
|
+
if (/^\s*BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)(?:\s+TRANSACTION)?\s*;?\s*$/i.test(sql)) {
|
|
73
|
+
openWriterTransactions.delete(db);
|
|
74
|
+
if (transformPassScope.getStore()?.active || backgroundWriterScope.getStore())
|
|
75
|
+
acquireShort(db, () => nativeExec(sql), sql.trim());
|
|
76
|
+
else
|
|
77
|
+
nativeExec(sql);
|
|
78
|
+
return db;
|
|
79
|
+
}
|
|
80
|
+
if (WRITER_TRANSACTION_END.test(sql) && openWriterTransactions.has(db))
|
|
81
|
+
return endWriterTransaction(db, () => nativeExec(sql), sql);
|
|
82
|
+
if (!/^\s*(?:SELECT|EXPLAIN|PRAGMA|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i.test(sql))
|
|
83
|
+
return withAutocommitTimeout(db, () => nativeExec(sql));
|
|
84
|
+
return nativeExec(sql);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
const nativePrepare = db.prepare.bind(db);
|
|
88
|
+
Object.defineProperty(db, "prepare", {
|
|
89
|
+
configurable: true,
|
|
90
|
+
writable: true,
|
|
91
|
+
value: (sql) => {
|
|
92
|
+
const statement = nativePrepare(sql);
|
|
93
|
+
if (!readonly && !/^\s*(?:SELECT|EXPLAIN|PRAGMA)\b/i.test(sql)) {
|
|
94
|
+
for (const method of ["run", "get", "all"]) {
|
|
95
|
+
const execute = statement[method].bind(statement);
|
|
96
|
+
Object.defineProperty(statement, method, {
|
|
97
|
+
configurable: true,
|
|
98
|
+
value: (...args) => withAutocommitTimeout(db, () => execute(...args))
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return statement;
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
Object.defineProperty(db, "transaction", {
|
|
106
|
+
configurable: true,
|
|
107
|
+
writable: true,
|
|
108
|
+
value: (fn) => {
|
|
109
|
+
const make = (mode) => function(...args) {
|
|
110
|
+
const nested = isInTransaction(db);
|
|
111
|
+
const savepoint = "mc_tx_sp";
|
|
112
|
+
db.exec(nested ? `SAVEPOINT ${savepoint}` : `BEGIN ${mode}`);
|
|
113
|
+
try {
|
|
114
|
+
const result = fn.apply(this, args);
|
|
115
|
+
db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
|
|
116
|
+
return result;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (isInTransaction(db)) {
|
|
119
|
+
if (nested) {
|
|
120
|
+
db.exec(`ROLLBACK TO ${savepoint}`);
|
|
121
|
+
db.exec(`RELEASE ${savepoint}`);
|
|
122
|
+
} else
|
|
123
|
+
db.exec("ROLLBACK");
|
|
124
|
+
}
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
const defaultTransaction = make(readonly ? "DEFERRED" : "IMMEDIATE");
|
|
129
|
+
const variants = {
|
|
130
|
+
default: defaultTransaction,
|
|
131
|
+
deferred: make("DEFERRED"),
|
|
132
|
+
immediate: make("IMMEDIATE"),
|
|
133
|
+
exclusive: make("EXCLUSIVE"),
|
|
134
|
+
database: db
|
|
135
|
+
};
|
|
136
|
+
for (const transaction of [
|
|
137
|
+
variants.default,
|
|
138
|
+
variants.deferred,
|
|
139
|
+
variants.immediate,
|
|
140
|
+
variants.exclusive
|
|
141
|
+
]) {
|
|
142
|
+
Object.assign(transaction, variants);
|
|
143
|
+
}
|
|
144
|
+
return defaultTransaction;
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
function trackSqliteConnection(db, filename, options) {
|
|
149
|
+
const originalClose = db.close.bind(db);
|
|
150
|
+
const sequence = nextSqliteConnectionSequence++;
|
|
151
|
+
const metadata = {
|
|
152
|
+
sequence,
|
|
153
|
+
filename: typeof filename === "string" ? filename : Buffer.isBuffer(filename) ? "<buffer>" : ":memory:",
|
|
154
|
+
readonly: Boolean(options) && typeof options === "object" && (options.readonly === true || options.readOnly === true)
|
|
155
|
+
};
|
|
156
|
+
installTransactionRouting(db, metadata.readonly);
|
|
157
|
+
Object.defineProperty(db, "close", {
|
|
158
|
+
configurable: true,
|
|
159
|
+
value: (...args) => {
|
|
160
|
+
try {
|
|
161
|
+
return originalClose(...args);
|
|
162
|
+
} finally {
|
|
163
|
+
trackedSqliteConnections.delete(sequence);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
trackedSqliteConnections.set(sequence, {
|
|
168
|
+
...metadata,
|
|
169
|
+
reference: new WeakRef(db)
|
|
170
|
+
});
|
|
171
|
+
return db;
|
|
172
|
+
}
|
|
173
|
+
var TrackedDatabase = new Proxy(DatabaseImpl, {
|
|
174
|
+
construct(target, args) {
|
|
175
|
+
const db = Reflect.construct(target, args, target);
|
|
176
|
+
return trackSqliteConnection(db, args[0], args[1]);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
function buildNodeSqliteDatabaseClass(DatabaseSync) {
|
|
180
|
+
|
|
181
|
+
class NodeSqliteDatabase extends DatabaseSync {
|
|
182
|
+
constructor(filename, options) {
|
|
183
|
+
const translated = { ...options };
|
|
184
|
+
if (options && "readonly" in options) {
|
|
185
|
+
translated.readOnly = options.readonly;
|
|
186
|
+
delete translated.readonly;
|
|
187
|
+
}
|
|
188
|
+
super(typeof filename === "string" ? filename : ":memory:", translated);
|
|
189
|
+
}
|
|
190
|
+
prepare(sql) {
|
|
191
|
+
const stmt = super.prepare(sql);
|
|
192
|
+
for (const method of ["run", "get", "all"]) {
|
|
193
|
+
const original = stmt[method].bind(stmt);
|
|
194
|
+
stmt[method] = (...args) => args.length === 1 && Array.isArray(args[0]) ? original(...args[0]) : original(...args);
|
|
195
|
+
}
|
|
196
|
+
return stmt;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return NodeSqliteDatabase;
|
|
200
|
+
}
|
|
201
|
+
var Database = TrackedDatabase;
|
|
202
|
+
function pragmaValue(db, name) {
|
|
203
|
+
const row = db.prepare(`PRAGMA ${name}`).get();
|
|
204
|
+
if (!row)
|
|
205
|
+
return;
|
|
206
|
+
return row[name] ?? Object.values(row)[0];
|
|
207
|
+
}
|
|
208
|
+
function pragmaNumber(db, name) {
|
|
209
|
+
try {
|
|
210
|
+
const value = pragmaValue(db, name);
|
|
211
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
212
|
+
} catch {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
var privilegeDepth = new WeakMap;
|
|
217
|
+
var transformPassScope = new AsyncLocalStorage;
|
|
218
|
+
var admissionScope = new AsyncLocalStorage;
|
|
219
|
+
var backgroundWriterScope = new AsyncLocalStorage;
|
|
220
|
+
function withSqliteBackgroundWriter(operation) {
|
|
221
|
+
return backgroundWriterScope.run(true, operation);
|
|
222
|
+
}
|
|
223
|
+
function withSqliteTransformPass(operation) {
|
|
224
|
+
const existing = transformPassScope.getStore();
|
|
225
|
+
if (existing?.active)
|
|
226
|
+
return operation();
|
|
227
|
+
const lease = { active: true, remainingWaitMs: FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS };
|
|
228
|
+
return transformPassScope.run(lease, () => {
|
|
229
|
+
try {
|
|
230
|
+
const result = operation();
|
|
231
|
+
if (result && typeof result.then === "function") {
|
|
232
|
+
return Promise.resolve(result).finally(() => {
|
|
233
|
+
lease.active = false;
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
lease.active = false;
|
|
237
|
+
return result;
|
|
238
|
+
} catch (error) {
|
|
239
|
+
lease.active = false;
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
function withoutSqliteTransformPass(operation) {
|
|
245
|
+
return transformPassScope.run(undefined, operation);
|
|
246
|
+
}
|
|
247
|
+
function isTransientSqliteError(error) {
|
|
248
|
+
if (!error || typeof error !== "object")
|
|
249
|
+
return false;
|
|
250
|
+
const value = error;
|
|
251
|
+
return typeof value.code === "string" && /^(SQLITE_BUSY|SQLITE_LOCKED)(_|$)/.test(value.code) || typeof value.errcode === "number" && [5, 6].includes(value.errcode & 255);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
class SqliteAcquisitionBusyError extends Error {
|
|
255
|
+
code = "SQLITE_BUSY";
|
|
256
|
+
stage;
|
|
257
|
+
constructor(cause, stage = "BEGIN IMMEDIATE") {
|
|
258
|
+
super("SQLite writer acquisition remained busy", { cause });
|
|
259
|
+
this.name = "SqliteAcquisitionBusyError";
|
|
260
|
+
this.stage = stage;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
var SHORT_BUSY_TIMEOUT_MS = 25;
|
|
264
|
+
var FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS = 250;
|
|
265
|
+
var SLOW_WRITER_LOG_MS = 250;
|
|
266
|
+
var WRITER_TRANSACTION_END = /^\s*(?:COMMIT|END|ROLLBACK)(?:\s+TRANSACTION)?\s*;?\s*$/i;
|
|
267
|
+
var writerAcquisitionScope = new AsyncLocalStorage;
|
|
268
|
+
var openWriterTransactions = new WeakMap;
|
|
269
|
+
function foregroundWaitLease() {
|
|
270
|
+
const lease = transformPassScope.getStore();
|
|
271
|
+
return lease?.active && !admissionScope.getStore() && !backgroundWriterScope.getStore() ? lease : undefined;
|
|
272
|
+
}
|
|
273
|
+
function withAutocommitTimeout(db, operation) {
|
|
274
|
+
const lease = foregroundWaitLease();
|
|
275
|
+
if (isInTransaction(db) || !lease && !backgroundWriterScope.getStore())
|
|
276
|
+
return operation();
|
|
277
|
+
const previous = pragmaNumber(db, "busy_timeout");
|
|
278
|
+
db.exec(`PRAGMA busy_timeout=${lease ? Math.floor(lease.remainingWaitMs) : SHORT_BUSY_TIMEOUT_MS}`);
|
|
279
|
+
const started = performance.now();
|
|
280
|
+
try {
|
|
281
|
+
return operation();
|
|
282
|
+
} catch (error) {
|
|
283
|
+
if (lease && isTransientSqliteError(error))
|
|
284
|
+
throw new SqliteAcquisitionBusyError(error, "autocommit");
|
|
285
|
+
throw error;
|
|
286
|
+
} finally {
|
|
287
|
+
if (lease)
|
|
288
|
+
lease.remainingWaitMs = Math.max(0, lease.remainingWaitMs - (performance.now() - started));
|
|
289
|
+
if (previous !== null)
|
|
290
|
+
db.exec(`PRAGMA busy_timeout=${previous}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
function acquireShort(db, acquire, site) {
|
|
294
|
+
const started = performance.now();
|
|
295
|
+
const previous = pragmaNumber(db, "busy_timeout");
|
|
296
|
+
const outer = writerAcquisitionScope.getStore();
|
|
297
|
+
const owner = outer && !outer.claimed ? outer : undefined;
|
|
298
|
+
if (owner)
|
|
299
|
+
owner.claimed = true;
|
|
300
|
+
const writerSite = owner?.site ?? site;
|
|
301
|
+
const lane = owner?.lane ?? (transformPassScope.getStore()?.active ? "foreground" : "background");
|
|
302
|
+
let acquiredAt;
|
|
303
|
+
try {
|
|
304
|
+
const lease = foregroundWaitLease();
|
|
305
|
+
const timeout = lease ? Math.floor(lease.remainingWaitMs) : SHORT_BUSY_TIMEOUT_MS;
|
|
306
|
+
db.exec(`PRAGMA busy_timeout=${timeout}`);
|
|
307
|
+
acquire();
|
|
308
|
+
acquiredAt = performance.now();
|
|
309
|
+
} catch (error) {
|
|
310
|
+
if (transformPassScope.getStore()?.active && isTransientSqliteError(error))
|
|
311
|
+
throw new SqliteAcquisitionBusyError(error, site);
|
|
312
|
+
throw error;
|
|
313
|
+
} finally {
|
|
314
|
+
const attemptMs = (acquiredAt ?? performance.now()) - started;
|
|
315
|
+
const lease = foregroundWaitLease();
|
|
316
|
+
if (lease)
|
|
317
|
+
lease.remainingWaitMs = Math.max(0, lease.remainingWaitMs - attemptMs);
|
|
318
|
+
if (previous !== null)
|
|
319
|
+
db.exec(`PRAGMA busy_timeout=${previous}`);
|
|
320
|
+
if (acquiredAt !== undefined) {
|
|
321
|
+
openWriterTransactions.set(db, {
|
|
322
|
+
site: writerSite,
|
|
323
|
+
lane,
|
|
324
|
+
acquireMs: acquiredAt - (owner?.startedAt ?? started),
|
|
325
|
+
attempts: owner?.attempts ?? 1,
|
|
326
|
+
acquiredAt
|
|
327
|
+
});
|
|
328
|
+
} else if (attemptMs >= SLOW_WRITER_LOG_MS) {
|
|
329
|
+
reportSqliteDiagnostic(`sqlite writer site=${writerSite} lane=${lane} acquire_ms=${Math.round(attemptMs)} attempts=${owner?.attempts ?? 1} outcome=busy`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function endWriterTransaction(db, end, sql) {
|
|
334
|
+
let ended = false;
|
|
335
|
+
try {
|
|
336
|
+
const result = end();
|
|
337
|
+
ended = true;
|
|
338
|
+
return result;
|
|
339
|
+
} finally {
|
|
340
|
+
const open = openWriterTransactions.get(db);
|
|
341
|
+
if (open && !isInTransaction(db)) {
|
|
342
|
+
openWriterTransactions.delete(db);
|
|
343
|
+
const holdMs = performance.now() - open.acquiredAt;
|
|
344
|
+
if (open.acquireMs >= SLOW_WRITER_LOG_MS || holdMs >= SLOW_WRITER_LOG_MS) {
|
|
345
|
+
const outcome = /^\s*ROLLBACK/i.test(sql) ? "rolled_back" : ended ? "committed" : "failed";
|
|
346
|
+
reportSqliteDiagnostic(`sqlite writer site=${open.site} lane=${open.lane} acquire_ms=${Math.round(open.acquireMs)} hold_ms=${Math.round(holdMs)} attempts=${open.attempts} outcome=${outcome}`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function isInTransaction(db) {
|
|
352
|
+
const candidate = db;
|
|
353
|
+
return candidate.inTransaction === true || candidate.isTransaction === true;
|
|
354
|
+
}
|
|
355
|
+
function withPrivilegedWriter(db, operation) {
|
|
356
|
+
const previousDepth = privilegeDepth.get(db) ?? 0;
|
|
357
|
+
const nested = isInTransaction(db);
|
|
358
|
+
const savepoint = "mc_privilege_scope";
|
|
359
|
+
let transactionStartedAt;
|
|
360
|
+
if (nested) {
|
|
361
|
+
db.exec(`SAVEPOINT ${savepoint}`);
|
|
362
|
+
} else {
|
|
363
|
+
try {
|
|
364
|
+
db.exec("BEGIN IMMEDIATE");
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if (transformPassScope.getStore()?.active && isTransientSqliteError(error))
|
|
367
|
+
throw new SqliteAcquisitionBusyError(error);
|
|
368
|
+
throw error;
|
|
369
|
+
}
|
|
370
|
+
transactionStartedAt = performance.now();
|
|
371
|
+
}
|
|
372
|
+
privilegeDepth.set(db, previousDepth + 1);
|
|
373
|
+
try {
|
|
374
|
+
db.prepare("INSERT INTO context_privilege_state(id, enabled) VALUES (1, 1) ON CONFLICT(id) DO UPDATE SET enabled = 1").run();
|
|
375
|
+
const result = operation();
|
|
376
|
+
if (previousDepth === 0) {
|
|
377
|
+
db.prepare("UPDATE context_privilege_state SET enabled = 0 WHERE id = 1").run();
|
|
378
|
+
}
|
|
379
|
+
if (nested) {
|
|
380
|
+
db.exec(`RELEASE ${savepoint}`);
|
|
381
|
+
} else {
|
|
382
|
+
db.exec("COMMIT");
|
|
383
|
+
if (transactionStartedAt !== undefined) {
|
|
384
|
+
reportSlowPrivilegedWrite?.("privileged_writer", transactionStartedAt);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (previousDepth > 0)
|
|
388
|
+
privilegeDepth.set(db, previousDepth);
|
|
389
|
+
else
|
|
390
|
+
privilegeDepth.delete(db);
|
|
391
|
+
return result;
|
|
392
|
+
} catch (error) {
|
|
393
|
+
try {
|
|
394
|
+
if (nested) {
|
|
395
|
+
db.exec(`ROLLBACK TO ${savepoint}`);
|
|
396
|
+
db.exec(`RELEASE ${savepoint}`);
|
|
397
|
+
} else {
|
|
398
|
+
db.exec("ROLLBACK");
|
|
399
|
+
}
|
|
400
|
+
} finally {
|
|
401
|
+
if (previousDepth > 0)
|
|
402
|
+
privilegeDepth.set(db, previousDepth);
|
|
403
|
+
else
|
|
404
|
+
privilegeDepth.delete(db);
|
|
405
|
+
}
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export { registerSlowWriteReporter, registerSqliteDiagnosticSink, detectSqliteRuntime, Database, withSqliteBackgroundWriter, withSqliteTransformPass, withoutSqliteTransformPass, isTransientSqliteError, withPrivilegedWriter };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// ../plugin/src/shared/storage-permissions.ts
|
|
2
|
+
var enforcePrivateStoragePermissions = true;
|
|
3
|
+
function setStoragePrivatePermissionEnforcement(enforce) {
|
|
4
|
+
enforcePrivateStoragePermissions = enforce;
|
|
5
|
+
}
|
|
6
|
+
function shouldEnforcePrivateStoragePermissions() {
|
|
7
|
+
return enforcePrivateStoragePermissions;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export { setStoragePrivatePermissionEnforcement, shouldEnforcePrivateStoragePermissions };
|
|
@@ -163,8 +163,10 @@ var SECRET_QUALIFIERS = new Set([
|
|
|
163
163
|
"github",
|
|
164
164
|
"huggingface",
|
|
165
165
|
"aws",
|
|
166
|
-
"azure"
|
|
166
|
+
"azure",
|
|
167
|
+
"id"
|
|
167
168
|
]);
|
|
169
|
+
var UNQUALIFIED_SECRET_SEGMENT_PATTERN = /^(?:password|secret|credential|bearer|authorization)s?$/;
|
|
168
170
|
function isSecretKey(key) {
|
|
169
171
|
const segments = key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().split(/[._-]+/).filter(Boolean);
|
|
170
172
|
if (segments.length === 0)
|
|
@@ -191,6 +193,8 @@ function isSecretKey(key) {
|
|
|
191
193
|
}
|
|
192
194
|
if (!trailingOk)
|
|
193
195
|
continue;
|
|
196
|
+
if (UNQUALIFIED_SECRET_SEGMENT_PATTERN.test(seg))
|
|
197
|
+
return true;
|
|
194
198
|
for (let k = i - 1;k >= 0; k--) {
|
|
195
199
|
const lead = segments[k];
|
|
196
200
|
if (lead && SECRET_QUALIFIERS.has(lead))
|
|
@@ -251,6 +255,18 @@ var SECRET_TEXT_PATTERNS = [
|
|
|
251
255
|
pattern: /\b(Authorization\s*:\s*Bearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi,
|
|
252
256
|
replacement: (_full, prefix) => `${prefix}<REDACTED:bearer>`
|
|
253
257
|
},
|
|
258
|
+
{
|
|
259
|
+
pattern: /\b((?:Proxy-)?Authorization\s*:\s*(?:Basic|Digest|Token|Negotiate|NTLM)\s+)([A-Za-z0-9._~+/=-]{4,})/gi,
|
|
260
|
+
replacement: (_full, prefix) => `${prefix}<REDACTED:authorization>`
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
pattern: /\b((?:x-)?(?:api-?key|api-?token|auth-?token|access-?token)\s*:\s*)([^\s'"`,;<>]{6,})/gi,
|
|
264
|
+
replacement: (full, prefix, value) => isNonSecretScalarValue(value) ? full : `${prefix}<REDACTED:api_key>`
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
pattern: /\b([a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:)([^\s/@]+)(@)/gi,
|
|
268
|
+
replacement: (_full, prefix, _password, at) => `${prefix}<REDACTED:password>${at}`
|
|
269
|
+
},
|
|
254
270
|
{
|
|
255
271
|
pattern: /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
|
|
256
272
|
replacement: "<JWT_REDACTED>"
|
|
@@ -317,6 +333,122 @@ function sanitizeConfigValue(value, keyPath = []) {
|
|
|
317
333
|
return value;
|
|
318
334
|
}
|
|
319
335
|
|
|
336
|
+
// ../plugin/src/shared/stale-plugin-build.ts
|
|
337
|
+
import { posix } from "node:path";
|
|
338
|
+
import { fileURLToPath } from "node:url";
|
|
339
|
+
var STATE = Symbol.for("magic-context.stale-plugin-build");
|
|
340
|
+
function state() {
|
|
341
|
+
const globals = globalThis;
|
|
342
|
+
return globals[STATE] ??= {
|
|
343
|
+
hosts: new Map,
|
|
344
|
+
loggedChunks: new Set,
|
|
345
|
+
notified: false
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function absolutePath(value) {
|
|
349
|
+
let path = value;
|
|
350
|
+
if (path.startsWith("file:")) {
|
|
351
|
+
try {
|
|
352
|
+
path = fileURLToPath(path);
|
|
353
|
+
} catch {
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
path = path.replaceAll("\\", "/").replace(/^\/(?=[A-Za-z]:\/)/, "");
|
|
358
|
+
if (!path.startsWith("/") && !/^[A-Za-z]:\//.test(path))
|
|
359
|
+
return;
|
|
360
|
+
path = posix.normalize(path);
|
|
361
|
+
return /^[A-Za-z]:\//.test(path) ? path.toLowerCase() : path;
|
|
362
|
+
}
|
|
363
|
+
function distForModule(moduleUrl) {
|
|
364
|
+
const path = absolutePath(moduleUrl);
|
|
365
|
+
if (!path)
|
|
366
|
+
return;
|
|
367
|
+
const dist = path.lastIndexOf("/dist/");
|
|
368
|
+
return dist < 0 ? undefined : path.slice(0, dist + "/dist".length);
|
|
369
|
+
}
|
|
370
|
+
function stalePluginBuildGuidance(harness) {
|
|
371
|
+
return harness === "pi" || harness === "omp" ? "Magic Context was rebuilt while this Pi was running; type /reload to load the new build" : "Magic Context was rebuilt while this OpenCode host was running; restart the host to load the new build";
|
|
372
|
+
}
|
|
373
|
+
function deliverNotice(host) {
|
|
374
|
+
const current = state();
|
|
375
|
+
if (current.notified || !current.pendingNotice || !host.notify)
|
|
376
|
+
return;
|
|
377
|
+
current.notified = true;
|
|
378
|
+
try {
|
|
379
|
+
Promise.resolve(host.notify(current.pendingNotice)).catch(() => {});
|
|
380
|
+
} catch {}
|
|
381
|
+
}
|
|
382
|
+
function registerStalePluginBuildHost(options) {
|
|
383
|
+
const dist = distForModule(options.moduleUrl);
|
|
384
|
+
if (!dist)
|
|
385
|
+
return;
|
|
386
|
+
const host = { ...options, dist };
|
|
387
|
+
state().hosts.set(dist, host);
|
|
388
|
+
deliverNotice(host);
|
|
389
|
+
}
|
|
390
|
+
function classifyStalePluginBuild(error) {
|
|
391
|
+
if (error instanceof StalePluginBuildError)
|
|
392
|
+
return error.build;
|
|
393
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
394
|
+
const missing = message.match(/(?:Cannot find module|ENOENT reading)\s+(['"])(.*?)\1/);
|
|
395
|
+
if (!missing)
|
|
396
|
+
return null;
|
|
397
|
+
let chunk = absolutePath(missing[2]);
|
|
398
|
+
if (!chunk && /^\.\.?[/\\]/.test(missing[2])) {
|
|
399
|
+
const importer = message.slice((missing.index ?? 0) + missing[0].length).match(/(?:imported from|from)\s+(?:['"]([^'"]+)['"]|([^\n]+))/);
|
|
400
|
+
const from = importer && absolutePath((importer[1] ?? importer[2]).trim());
|
|
401
|
+
if (from)
|
|
402
|
+
chunk = absolutePath(posix.join(posix.dirname(from), missing[2].replaceAll("\\", "/")));
|
|
403
|
+
}
|
|
404
|
+
if (!chunk)
|
|
405
|
+
return null;
|
|
406
|
+
for (const host of state().hosts.values()) {
|
|
407
|
+
if (chunk.startsWith(`${host.dist}/`)) {
|
|
408
|
+
return { chunk, guidance: stalePluginBuildGuidance(host.harness) };
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const ownDist = distForModule(import.meta.url);
|
|
412
|
+
return ownDist && chunk.startsWith(`${ownDist}/`) ? { chunk, guidance: stalePluginBuildGuidance(getHarness()) } : null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
class StalePluginBuildError extends Error {
|
|
416
|
+
build;
|
|
417
|
+
constructor(build) {
|
|
418
|
+
super(build.guidance);
|
|
419
|
+
this.build = build;
|
|
420
|
+
this.name = "StalePluginBuildError";
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
function stalePluginBuildDiagnostic(error) {
|
|
424
|
+
const pending = state().pendingNotice;
|
|
425
|
+
const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
|
|
426
|
+
if (pending && message.includes(pending))
|
|
427
|
+
return null;
|
|
428
|
+
const build = classifyStalePluginBuild(error);
|
|
429
|
+
if (!build)
|
|
430
|
+
return;
|
|
431
|
+
const current = state();
|
|
432
|
+
current.pendingNotice ??= build.guidance;
|
|
433
|
+
for (const host of current.hosts.values())
|
|
434
|
+
deliverNotice(host);
|
|
435
|
+
if (current.loggedChunks.has(build.chunk))
|
|
436
|
+
return null;
|
|
437
|
+
current.loggedChunks.add(build.chunk);
|
|
438
|
+
return `[magic-context] stale plugin build: missing ${build.chunk.replace(/[\r\n]/g, " ")}; ${build.guidance}`;
|
|
439
|
+
}
|
|
440
|
+
async function importPluginModule(load) {
|
|
441
|
+
try {
|
|
442
|
+
return await load();
|
|
443
|
+
} catch (error) {
|
|
444
|
+
const build = classifyStalePluginBuild(error);
|
|
445
|
+
if (!build)
|
|
446
|
+
throw error;
|
|
447
|
+
log("[magic-context] lazy import failed", error);
|
|
448
|
+
throw new StalePluginBuildError(build);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
320
452
|
// ../plugin/src/shared/logger.ts
|
|
321
453
|
var isTestEnv = false;
|
|
322
454
|
var buffer = [];
|
|
@@ -459,15 +591,45 @@ function scheduleFlush() {
|
|
|
459
591
|
flush();
|
|
460
592
|
}, FLUSH_INTERVAL_MS);
|
|
461
593
|
}
|
|
462
|
-
|
|
594
|
+
var lineForwarder = null;
|
|
595
|
+
function setLogLineForwarder(forward) {
|
|
596
|
+
lineForwarder = forward;
|
|
597
|
+
}
|
|
598
|
+
function writeForwardedLogLine(line) {
|
|
463
599
|
if (isTestEnv)
|
|
464
600
|
return;
|
|
465
601
|
try {
|
|
602
|
+
buffer.push(line);
|
|
603
|
+
bufferedBytes += Buffer.byteLength(line);
|
|
604
|
+
boundBuffer();
|
|
605
|
+
if (buffer.length >= BUFFER_SIZE_LIMIT)
|
|
606
|
+
flush();
|
|
607
|
+
else
|
|
608
|
+
scheduleFlush();
|
|
609
|
+
} catch {}
|
|
610
|
+
}
|
|
611
|
+
function log(message, data) {
|
|
612
|
+
try {
|
|
613
|
+
let diagnostic = stalePluginBuildDiagnostic(data);
|
|
614
|
+
if (diagnostic === undefined)
|
|
615
|
+
diagnostic = stalePluginBuildDiagnostic(message);
|
|
616
|
+
if (diagnostic === null)
|
|
617
|
+
return;
|
|
618
|
+
if (diagnostic !== undefined) {
|
|
619
|
+
message = diagnostic;
|
|
620
|
+
data = undefined;
|
|
621
|
+
}
|
|
622
|
+
if (isTestEnv)
|
|
623
|
+
return;
|
|
466
624
|
const timestamp = new Date().toISOString();
|
|
467
625
|
const serialized = data === undefined ? "" : data instanceof Error ? ` ${sanitizeDiagnosticText(`${data.message}${data.stack ? `
|
|
468
626
|
${data.stack}` : ""}`)}` : ` ${JSON.stringify(sanitizeConfigValue(data))}`;
|
|
469
627
|
const line = `[${timestamp}] ${sanitizeDiagnosticText(message)}${serialized}
|
|
470
628
|
`;
|
|
629
|
+
if (lineForwarder) {
|
|
630
|
+
lineForwarder(line);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
471
633
|
buffer.push(line);
|
|
472
634
|
bufferedBytes += Buffer.byteLength(line);
|
|
473
635
|
boundBuffer();
|
|
@@ -488,4 +650,4 @@ if (!isTestEnv) {
|
|
|
488
650
|
process.on("exit", flush);
|
|
489
651
|
}
|
|
490
652
|
|
|
491
|
-
export { setHarness, getHarness, harnessOwnsOpenCodeStore, getDataDir, ensureCortexKitArtifactGitignore, getProjectMagicContextHistorianDir, getMagicContextStorageDir, getLegacyOpenCodeMagicContextStorageDir, sanitizeDiagnosticText, hasShareabilitySensitiveText, log, sessionLog, flushLogger };
|
|
653
|
+
export { setHarness, getHarness, harnessOwnsOpenCodeStore, getDataDir, ensureCortexKitArtifactGitignore, getProjectMagicContextHistorianDir, getMagicContextStorageDir, getLegacyOpenCodeMagicContextStorageDir, sanitizeDiagnosticText, hasShareabilitySensitiveText, registerStalePluginBuildHost, classifyStalePluginBuild, importPluginModule, setLogLineForwarder, writeForwardedLogLine, log, sessionLog, flushLogger };
|