@cortexkit/pi-magic-context 0.49.34 → 0.49.36

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.
Files changed (73) hide show
  1. package/dist/auto-search-worker.js +163 -155
  2. package/dist/chunk-embedding-write-worker.js +71 -66
  3. package/dist/{compaction-marker-candidates-p1kqkqhq.js → compaction-marker-candidates-9fzqg6y0.js} +6 -3
  4. package/dist/compaction-marker-candidates-worker.js +24 -23
  5. package/dist/{compartment-chunk-embedding-8c85ebce.js → compartment-chunk-embedding-jpcme6tz.js} +11 -9
  6. package/dist/embedding-backfill-002vyexq.js +27 -0
  7. package/dist/embedding-worker-process.js +2 -1
  8. package/dist/embedding-worker.js +5 -4
  9. package/dist/expand-attachments-8sxeyj26.js +21 -0
  10. package/dist/historian-calibration-extension.js +2 -1
  11. package/dist/{index-hqw0rt9k.js → index-0wtm7g7f.js} +1 -1
  12. package/dist/{index-wqpjhx1p.js → index-2qqsnh1b.js} +2 -2
  13. package/dist/index-3bb24eb6.js +229 -0
  14. package/dist/{index-48twbev2.js → index-6pk49fc3.js} +37 -51
  15. package/dist/{index-399p688g.js → index-8sqebjzk.js} +4 -1
  16. package/dist/{index-np9ryr8y.js → index-a7sj2bam.js} +24 -241
  17. package/dist/index-by1bzjcd.js +24 -0
  18. package/dist/{index-6981g1xv.js → index-c1dqxr10.js} +35 -5
  19. package/dist/index-c6wbq66z.js +168 -0
  20. package/dist/{index-bvpar0bg.js → index-ck8wj35v.js} +2 -2
  21. package/dist/{index-jn44h81p.js → index-cq71g4dk.js} +1 -1
  22. package/dist/{index-pb3ea2tq.js → index-d107f484.js} +5 -5
  23. package/dist/{index-f4fz95fy.js → index-dgqjq8sg.js} +398 -4996
  24. package/dist/index-dnp1jjar.js +222 -0
  25. package/dist/index-ea37qn4x.js +777 -0
  26. package/dist/{index-g2tfayfc.js → index-f6y7mdq9.js} +98 -552
  27. package/dist/{index-0gymvr5j.js → index-f9qet7y8.js} +19 -8
  28. package/dist/index-gxqmh9hq.js +194 -0
  29. package/dist/{index-fgs78jyd.js → index-gymgz20n.js} +5 -222
  30. package/dist/index-hgd00nas.js +113 -0
  31. package/dist/{index-9xd7qveg.js → index-jbkwszd5.js} +4 -4
  32. package/dist/{index-e61zxfts.js → index-kj49vs41.js} +4 -4
  33. package/dist/{index-4zemngt7.js → index-mp0gh04g.js} +2 -2
  34. package/dist/{index-eenxm3t3.js → index-mx757f3g.js} +51 -32
  35. package/dist/{index-23t8ryqw.js → index-n0zjvs3h.js} +1 -168
  36. package/dist/index-nypgv96r.js +58 -0
  37. package/dist/index-p9jfa33t.js +4171 -0
  38. package/dist/{index-eqw9t2ty.js → index-pwp6zyx3.js} +15 -4
  39. package/dist/{index-cj3bkd16.js → index-ry84c8dr.js} +2 -2
  40. package/dist/{index-gwxaz0z5.js → index-rzfr7wdv.js} +2 -2
  41. package/dist/index-w26zvs1q.js +528 -0
  42. package/dist/index-wfqysrwq.js +204 -0
  43. package/dist/index-wrr9rp9a.js +16 -0
  44. package/dist/{index-my0dn413.js → index-wt7vmyj4.js} +1 -1
  45. package/dist/{index-0mc0vv97.js → index-wwsfevck.js} +8 -5
  46. package/dist/{index-54wmg4rj.js → index-x2n261wp.js} +16 -14
  47. package/dist/{index-6wdwv3a6.js → index-y90fxz4t.js} +10 -4
  48. package/dist/{index-c474g0gj.js → index-yacs388s.js} +1 -1
  49. package/dist/{index-xn5yh0pn.js → index-z7dktknj.js} +34 -131
  50. package/dist/index.js +1316 -488
  51. package/dist/{logger-shetp43v.js → logger-2j70hhz4.js} +2 -1
  52. package/dist/{message-fts-rowid-map-3mbvdgn9.js → message-fts-rowid-map-hmgyfxxa.js} +8 -6
  53. package/dist/{message-index-bounded-a6na71rg.js → message-index-bounded-82sergz7.js} +15 -12
  54. package/dist/{message-time-backfill-e3r8ddh1.js → message-time-backfill-x45573rs.js} +3 -2
  55. package/dist/migration-worker.js +56 -48
  56. package/dist/{project-embedding-registry-acqb6be4.js → project-embedding-registry-16pj4vyf.js} +16 -13
  57. package/dist/raw-ordinal-warmup-worker.js +114 -113
  58. package/dist/{read-session-chunk-2xcp6f40.js → read-session-chunk-jxq427v6.js} +17 -10
  59. package/dist/{read-session-raw-g9b1zdn5.js → read-session-raw-a9ntjqap.js} +6 -4
  60. package/dist/render-2wan3bfh.js +42 -0
  61. package/dist/{safe-notification-target-zcpchea6.js → safe-notification-target-jk69jxwp.js} +3 -2
  62. package/dist/search-3p18trsb.js +50 -0
  63. package/dist/search-archive-pgrv04gv.js +25 -0
  64. package/dist/{storage-tags-6409qq18.js → storage-tags-p9y3bnw7.js} +5 -4
  65. package/dist/store-reader-2m80zs5z.js +14 -0
  66. package/dist/store-v60q7dje.js +452 -0
  67. package/dist/subagent-entry.js +34 -25
  68. package/dist/tag-snapshot-worker-pi.js +218 -209
  69. package/dist/v2-archive-reader-5zpj8hrg.js +11 -0
  70. package/package.json +1 -1
  71. package/dist/embedding-backfill-rwfmyvze.js +0 -24
  72. package/dist/search-archive-jate39w5.js +0 -21
  73. package/dist/search-b6hp64hc.js +0 -45
@@ -1,15 +1,14 @@
1
+ import {
2
+ getHarness2,
3
+ harnessOwnsOpenCodeStore2
4
+ } from "./index-0h2mkab2.js";
1
5
  import {
2
6
  getMagicContextStorageDir,
3
7
  getLegacyOpenCodeMagicContextStorageDir,
4
- sanitizeDiagnosticText,
5
8
  importPluginModule,
6
9
  writeForwardedLogLine2,
7
10
  log2
8
- } from "./index-fgs78jyd.js";
9
- import {
10
- getHarness2,
11
- harnessOwnsOpenCodeStore2
12
- } from "./index-0h2mkab2.js";
11
+ } from "./index-gymgz20n.js";
13
12
  import {
14
13
  inRootAsyncContext2,
15
14
  registerSlowWriteReporter2,
@@ -25,13 +24,19 @@ import {
25
24
  } from "./index-2qtx0q6h.js";
26
25
  import {
27
26
  scheduleAfterBootQuiet
28
- } from "./index-48twbev2.js";
27
+ } from "./index-6pk49fc3.js";
29
28
  import {
30
29
  configureContextDatabasePragmas2
31
30
  } from "./index-fapenpch.js";
31
+ import {
32
+ attachFailClosedBlockingProcessEvidence
33
+ } from "./index-3bb24eb6.js";
34
+ import {
35
+ reuseWorker
36
+ } from "./index-wfqysrwq.js";
32
37
  import {
33
38
  startMessageFtsRowidMapBackfill2
34
- } from "./index-bvpar0bg.js";
39
+ } from "./index-ck8wj35v.js";
35
40
  import {
36
41
  LKG_SLOT_CHUNKS_DDL,
37
42
  SESSION_REPLAY_DECISIONS_DDL,
@@ -41,24 +46,26 @@ import {
41
46
  hasPendingMigrations,
42
47
  getMainThreadMigrationBodyCount,
43
48
  runMigrations
44
- } from "./index-pb3ea2tq.js";
49
+ } from "./index-d107f484.js";
45
50
  import {
46
51
  ensureColumn,
47
52
  installV95PerfSchema,
48
53
  installTagIdentityRevisionTrigger
49
- } from "./index-c474g0gj.js";
54
+ } from "./index-yacs388s.js";
50
55
  import {
51
56
  resolveOpenCodeDbPath,
52
- hasV1MessageTables,
57
+ hasV1MessageTables
58
+ } from "./index-n0zjvs3h.js";
59
+ import {
53
60
  setDatabase,
54
61
  loadToolDefinitionMeasurements
55
- } from "./index-23t8ryqw.js";
62
+ } from "./index-c6wbq66z.js";
56
63
  import {
57
64
  closeQuietly
58
65
  } from "./index-nrzkqte4.js";
59
66
  import {
60
67
  logSlowWriteTransaction
61
- } from "./index-hqw0rt9k.js";
68
+ } from "./index-0wtm7g7f.js";
62
69
  import {
63
70
  shouldEnforcePrivateStoragePermissions,
64
71
  ensureStorageDirectorySync,
@@ -68,230 +75,6 @@ import {
68
75
  tightenStorageTreeSync
69
76
  } from "./index-81nthk8j.js";
70
77
 
71
- // ../plugin/src/features/magic-context/fail-closed-block.ts
72
- var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
73
- var FAIL_CLOSED_REPROBE_EVERY_N = 5;
74
- function attachFailClosedBlockingProcessEvidence(process2, evidence) {
75
- Object.defineProperties(process2, {
76
- startTime: { configurable: true, value: evidence.startTime },
77
- commandLine: { configurable: true, value: evidence.commandLine }
78
- });
79
- return process2;
80
- }
81
-
82
- class FailClosedBlockingError extends Error {
83
- code = "FAIL_CLOSED_BLOCKING";
84
- reason;
85
- constructor(message, reason, options) {
86
- super(message, options);
87
- this.name = "FailClosedBlockingError";
88
- this.reason = reason;
89
- }
90
- }
91
- var OPENCODE_INTERNAL_AGENT_NAMES = new Set(["title", "summary", "compaction"]);
92
- function isMagicContextHiddenAgentName(agent) {
93
- if (agent === "smart-note-compiler" || agent.startsWith("smart-note-")) {
94
- return true;
95
- }
96
- if (agent === "historian" || agent.startsWith("historian-"))
97
- return true;
98
- if (agent === "dreamer" || agent.startsWith("dreamer-"))
99
- return true;
100
- return false;
101
- }
102
- var MAX_FORMATTED_BLOCKING_PROCESSES = 8;
103
- var MAX_FORMATTED_COMMAND_LINE_LENGTH = 80;
104
- function normalizeFailClosedProcessKind(process2) {
105
- switch (process2.kind) {
106
- case "OpenCode server":
107
- case "OpenCode instance (TUI/CLI)":
108
- case "Pi":
109
- case "process":
110
- return process2.kind;
111
- }
112
- switch (process2.harness?.trim().toLowerCase()) {
113
- case "opencode server":
114
- return "OpenCode server";
115
- case "opencode instance (tui/cli)":
116
- case "opencode instance":
117
- return "OpenCode instance (TUI/CLI)";
118
- case "pi":
119
- case "pi harness":
120
- case "omp":
121
- return "Pi";
122
- default:
123
- return "process";
124
- }
125
- }
126
- function formatFailClosedProcessStartTime(startTime) {
127
- if (!Number.isFinite(startTime) || startTime <= 0)
128
- return "unverified";
129
- try {
130
- const parts = new Intl.DateTimeFormat("en-US", {
131
- day: "numeric",
132
- hour: "2-digit",
133
- minute: "2-digit",
134
- month: "short",
135
- hour12: false
136
- }).formatToParts(new Date(startTime));
137
- const values = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
138
- if (!values.month || !values.day || !values.hour || !values.minute)
139
- return "unverified";
140
- return `${values.month} ${values.day} ${values.hour}:${values.minute}`;
141
- } catch {
142
- return "unverified";
143
- }
144
- }
145
- function formatFailClosedCommandLine(commandLine) {
146
- if (typeof commandLine !== "string" || commandLine.trim().length === 0)
147
- return "unverified";
148
- try {
149
- const normalized = commandLine.replaceAll("\x00", " ").replace(/\s+/g, " ").trim();
150
- if (normalized.length === 0)
151
- return "unverified";
152
- const sanitized = sanitizeDiagnosticText(normalized).trim();
153
- if (sanitized.length === 0)
154
- return "unverified";
155
- return sanitized.length > MAX_FORMATTED_COMMAND_LINE_LENGTH ? `${sanitized.slice(0, MAX_FORMATTED_COMMAND_LINE_LENGTH - 3)}...` : sanitized;
156
- } catch {
157
- return "unverified";
158
- }
159
- }
160
- function formatFailClosedBlockingProcesses(processes) {
161
- const uniqueProcesses = new Map;
162
- for (const process2 of processes) {
163
- if (!Number.isInteger(process2.pid) || process2.pid <= 0)
164
- continue;
165
- const candidate = {
166
- kind: normalizeFailClosedProcessKind(process2),
167
- pid: process2.pid,
168
- startTime: process2.startTime,
169
- commandLine: process2.commandLine
170
- };
171
- const previous = uniqueProcesses.get(process2.pid);
172
- if (!previous || previous.kind === "process" && candidate.kind !== "process") {
173
- uniqueProcesses.set(process2.pid, candidate);
174
- } else {
175
- uniqueProcesses.set(process2.pid, {
176
- ...previous,
177
- startTime: previous.startTime ?? candidate.startTime,
178
- commandLine: previous.commandLine ?? candidate.commandLine
179
- });
180
- }
181
- }
182
- const entries = [...uniqueProcesses.values()];
183
- const visible = entries.slice(0, MAX_FORMATTED_BLOCKING_PROCESSES);
184
- const rendered = visible.map(({ kind, pid }) => `${kind} (PID ${pid})`);
185
- const omitted = entries.length - visible.length;
186
- if (omitted > 0)
187
- rendered.push(`${omitted} more blocking process(es)`);
188
- if (rendered.length === 0)
189
- return "a live process";
190
- const summary = rendered.length === 1 ? rendered[0] : `${rendered.slice(0, -1).join(", ")}, and ${rendered.at(-1)}`;
191
- const evidence = entries.map(({ kind, pid, startTime, commandLine }) => `- PID ${pid}: ${kind}, started ${formatFailClosedProcessStartTime(startTime)}, cmd: ${formatFailClosedCommandLine(commandLine)}`).join(`
192
- `);
193
- return `${summary}
194
- Blocking process evidence:
195
- ${evidence}`;
196
- }
197
- function formatFailClosedBlockingMessage(reason) {
198
- if (reason.kind === "migration_guard") {
199
- if (reason.unreadableFile) {
200
- const arm = reason.unreadableArm ?? "io";
201
- const recovery = arm === "io" ? `If none of these processes are running, it is safe to delete ${reason.unreadableFile} and retry.` : `The file may be a recent incomplete write; retry after the file is older than the ten-minute grace window, or stop the relevant process before deleting it.`;
202
- return [
203
- `Magic Context cannot migrate the shared database because RPC discovery file ${reason.unreadableFile} is uncertain (${arm} arm), so the absence of a live process cannot be proven.`,
204
- recovery,
205
- `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
206
- ].join(" ");
207
- }
208
- return [
209
- `Magic Context cannot migrate the shared database (one database serves every project on this machine) because ${formatFailClosedBlockingProcesses(reason.blockingProcesses)} may be running an older Magic Context build that would fail against the migrated database.`,
210
- `The database is at upstream migration v${reason.persistedVersion}; this build needs v${reason.supportedVersion}.`,
211
- "Restart the blocking process — even one from a different project — and it will pick up the new build and migrate on start; or shut it down and retry.",
212
- "If that host loads a pinned or cached older Magic Context build, a restart alone is not enough: stop it or update its Magic Context build, then start this host once so it migrates the database with nothing older attached.",
213
- `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
214
- ].join(" ");
215
- }
216
- if (reason.kind === "schema_fence") {
217
- return [
218
- `Magic Context cannot operate: this Magic Context build is older than the database; upgrade/restart this harness (upstream migration lane v${reason.persistedVersion}, build supports through v${reason.supportedVersion}).`,
219
- `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
220
- ].join(" ");
221
- }
222
- const cause = reason.cause.trim().length > 0 ? reason.cause.trim() : "unknown storage error";
223
- return [
224
- `Magic Context cannot operate: persistent storage failed (${cause}).`,
225
- "The plugin will not silently degrade to native compaction while enabled.",
226
- `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
227
- ].join(" ");
228
- }
229
- function createFailClosedBlockingError(reason, options) {
230
- return new FailClosedBlockingError(formatFailClosedBlockingMessage(reason), reason, options);
231
- }
232
- function isFailClosedBlockingError(error) {
233
- return error instanceof FailClosedBlockingError || typeof error === "object" && error !== null && error.name === "FailClosedBlockingError" && error.code === "FAIL_CLOSED_BLOCKING";
234
- }
235
- function shouldBypassFailClosedBlock(input) {
236
- if (input.isPiSubagentEnv === true)
237
- return true;
238
- if (input.isInternalChildSession === true)
239
- return true;
240
- const agent = typeof input.agent === "string" ? input.agent.trim() : "";
241
- if (agent.length === 0)
242
- return false;
243
- if (OPENCODE_INTERNAL_AGENT_NAMES.has(agent))
244
- return true;
245
- if (isMagicContextHiddenAgentName(agent))
246
- return true;
247
- return false;
248
- }
249
- function createFailClosedController(options) {
250
- const reprobeEveryN = Math.max(1, options?.reprobeEveryN ?? FAIL_CLOSED_REPROBE_EVERY_N);
251
- let reason = null;
252
- let blockedPassCount = 0;
253
- return {
254
- arm(next) {
255
- reason = next;
256
- blockedPassCount = 0;
257
- },
258
- clear() {
259
- reason = null;
260
- blockedPassCount = 0;
261
- },
262
- isArmed() {
263
- return reason !== null;
264
- },
265
- getReason() {
266
- return reason;
267
- },
268
- async enforce(input) {
269
- if (!reason)
270
- return;
271
- if (!input.blockingEnabled)
272
- return;
273
- if (input.exempt)
274
- return;
275
- blockedPassCount += 1;
276
- const shouldReprobe = typeof input.tryReopen === "function" && (blockedPassCount === 1 || blockedPassCount % reprobeEveryN === 0);
277
- if (shouldReprobe) {
278
- try {
279
- const healed = await input.tryReopen?.();
280
- if (healed) {
281
- reason = null;
282
- blockedPassCount = 0;
283
- return;
284
- }
285
- } catch {}
286
- }
287
- const blockedReason = reason;
288
- if (!blockedReason)
289
- return;
290
- throw createFailClosedBlockingError(blockedReason);
291
- }
292
- };
293
- }
294
-
295
78
  // ../plugin/src/shared/rpc-utils.ts
296
79
  import { execFile, execFileSync } from "node:child_process";
297
80
  import { readFileSync } from "node:fs";
@@ -1211,7 +994,7 @@ function runMigrationsOffThread(data) {
1211
994
  return new Promise((resolve, reject) => {
1212
995
  let worker;
1213
996
  try {
1214
- worker = inRootAsyncContext2(() => new Worker(workerEntryOverride ?? defaultWorkerEntry(), { workerData: data }));
997
+ worker = inRootAsyncContext2(() => workerEntryOverride ? new Worker(workerEntryOverride, { workerData: data }) : reuseWorker(defaultWorkerEntry(), { workerData: data }));
1215
998
  } catch (error) {
1216
999
  reject(workerStartError(error instanceof Error ? error.message : String(error)));
1217
1000
  return;
@@ -2005,8 +1788,8 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
2005
1788
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
2006
1789
  if (signal.aborted || !readsOpenCodeStore)
2007
1790
  return;
2008
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-2xcp6f40.js"));
2009
- const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-e3r8ddh1.js"));
1791
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-jxq427v6.js"));
1792
+ const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-x45573rs.js"));
2010
1793
  if (signal.aborted)
2011
1794
  return;
2012
1795
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
@@ -3525,4 +3308,4 @@ function closeDatabase() {
3525
3308
  return Promise.all(pendingDatabaseCloses).then(() => {});
3526
3309
  }
3527
3310
 
3528
- export { FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, piHarnessKindFromExecutable, isPidAlive, readProcessStartTime, getErrorMessage, describeError, startBootDeadline, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, enforceSchemaFence, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, closeDatabase };
3311
+ export { piHarnessKindFromExecutable, isPidAlive, readProcessStartTime, getErrorMessage, describeError, startBootDeadline, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, enforceSchemaFence, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, closeDatabase };
@@ -0,0 +1,24 @@
1
+ // ../plugin/src/hooks/magic-context/host-served-rows.ts
2
+ var HOST_UNSERVED_ROW = "hostUnservedRow";
3
+ function markHostUnservedRow(target) {
4
+ Object.defineProperty(target, HOST_UNSERVED_ROW, {
5
+ value: true,
6
+ enumerable: false,
7
+ configurable: true
8
+ });
9
+ return target;
10
+ }
11
+ function isHostUnservedRow(value) {
12
+ return typeof value === "object" && value !== null && value[HOST_UNSERVED_ROW] === true;
13
+ }
14
+ function retreatPastHostUnservedRows(messages, exclusiveEnd, floor) {
15
+ if (!messages.some(isHostUnservedRow))
16
+ return exclusiveEnd;
17
+ const byOrdinal = new Map(messages.map((message) => [message.ordinal, message]));
18
+ let end = exclusiveEnd;
19
+ while (end - 1 >= floor && isHostUnservedRow(byOrdinal.get(end - 1)))
20
+ end -= 1;
21
+ return end;
22
+ }
23
+
24
+ export { markHostUnservedRow, isHostUnservedRow, retreatPastHostUnservedRows };
@@ -5,13 +5,16 @@ import {
5
5
  } from "./index-2qtx0q6h.js";
6
6
  import {
7
7
  registerExitAbort
8
- } from "./index-399p688g.js";
8
+ } from "./index-8sqebjzk.js";
9
9
  import {
10
10
  log2
11
- } from "./index-fgs78jyd.js";
11
+ } from "./index-gymgz20n.js";
12
+ import {
13
+ reuseWorker
14
+ } from "./index-wfqysrwq.js";
12
15
  import {
13
16
  createWorkerShutdown
14
- } from "./index-54wmg4rj.js";
17
+ } from "./index-x2n261wp.js";
15
18
 
16
19
  // ../plugin/src/hooks/magic-context/read-session-raw.ts
17
20
  import { isMainThread } from "node:worker_threads";
@@ -60,6 +63,7 @@ function runSessionWarmupWorker(input, options) {
60
63
  clearTimeout(deadline);
61
64
  options.signal?.removeEventListener("abort", abort);
62
65
  if (worker) {
66
+ worker.off("online", startDeadline);
63
67
  activeWorkers.delete(worker);
64
68
  const stopped = shutdown?.close() ?? worker.terminate();
65
69
  worker.unref();
@@ -77,6 +81,10 @@ function runSessionWarmupWorker(input, options) {
77
81
  deadline = setTimeout(() => finish({ failure, detail: `no reply within ${ms} ms` }), ms);
78
82
  deadline.unref?.();
79
83
  };
84
+ const startDeadline = () => {
85
+ if (!settled)
86
+ arm("not-accepted", options.acceptMs ?? ACCEPT_TIMEOUT_MS);
87
+ };
80
88
  const abort = () => finish({ failure: "stopped", detail: "stopped" });
81
89
  if (options.signal?.aborted) {
82
90
  abort();
@@ -84,8 +92,14 @@ function runSessionWarmupWorker(input, options) {
84
92
  }
85
93
  options.signal?.addEventListener("abort", abort, { once: true });
86
94
  try {
87
- worker = inRootAsyncContext2(() => new Worker(options.entry ?? defaultEntry(), {
95
+ worker = inRootAsyncContext2(() => options.entry ? new Worker(options.entry, {
88
96
  workerData: { ...input, openCancellation: openCancellation.buffer }
97
+ }) : reuseWorker(defaultEntry(), {
98
+ workerData: {
99
+ ...input,
100
+ job: rawWorkerJobKind(input),
101
+ openCancellation: openCancellation.buffer
102
+ }
89
103
  }));
90
104
  shutdown = createWorkerShutdown(worker, "raw-ordinal-warmup", WARMUP_CLOSE_DEADLINE_MS);
91
105
  } catch (error) {
@@ -94,7 +108,10 @@ function runSessionWarmupWorker(input, options) {
94
108
  }
95
109
  worker.unref();
96
110
  activeWorkers.set(worker, (failure) => finish({ failure, detail: "stopped" }));
97
- arm("not-accepted", options.acceptMs ?? ACCEPT_TIMEOUT_MS);
111
+ if (options.entry)
112
+ startDeadline();
113
+ else
114
+ worker.once("online", startDeadline);
98
115
  worker.on("message", (reply) => {
99
116
  if (reply.kind === "accepted")
100
117
  arm("no-result", options.resultMs ?? RESULT_TIMEOUT_MS);
@@ -124,6 +141,19 @@ function runSessionWarmupWorker(input, options) {
124
141
  worker.on("exit", (code) => finish({ failure: "exited", detail: `exit code ${code}` }));
125
142
  });
126
143
  }
144
+ function rawWorkerJobKind(input) {
145
+ if (input.indexMessage)
146
+ return "index-message";
147
+ if (input.ftsRowidBackfill)
148
+ return "fts-rowid-backfill";
149
+ if (input.searchArchive)
150
+ return "search-archive";
151
+ if (input.exactOrdinalIds)
152
+ return "exact-ordinal-ids";
153
+ if (input.tagRatio !== undefined)
154
+ return input.tagState ? "tag-delta" : "tag-summary";
155
+ return "ordinal-scan";
156
+ }
127
157
  function prewarmRawSessionOrdinalsForDb(db, sessionId, options = {}) {
128
158
  if (isRawSessionSummaryWarm2(db, sessionId))
129
159
  return Promise.resolve("warm");
@@ -0,0 +1,168 @@
1
+ // ../plugin/src/shared/bounded-session-map.ts
2
+ class BoundedSessionMap {
3
+ maxEntries;
4
+ store = new Map;
5
+ constructor(maxEntries) {
6
+ if (!Number.isFinite(maxEntries) || maxEntries < 1) {
7
+ throw new Error(`BoundedSessionMap: maxEntries must be >= 1, got ${maxEntries}`);
8
+ }
9
+ this.maxEntries = maxEntries;
10
+ }
11
+ get(sessionId) {
12
+ const value = this.store.get(sessionId);
13
+ if (value === undefined)
14
+ return;
15
+ this.store.delete(sessionId);
16
+ this.store.set(sessionId, value);
17
+ return value;
18
+ }
19
+ peek(sessionId) {
20
+ return this.store.get(sessionId);
21
+ }
22
+ has(sessionId) {
23
+ return this.store.has(sessionId);
24
+ }
25
+ set(sessionId, value) {
26
+ if (this.store.has(sessionId)) {
27
+ this.store.delete(sessionId);
28
+ } else if (this.store.size >= this.maxEntries) {
29
+ const oldest = this.store.keys().next().value;
30
+ if (oldest !== undefined)
31
+ this.store.delete(oldest);
32
+ }
33
+ this.store.set(sessionId, value);
34
+ }
35
+ delete(sessionId) {
36
+ return this.store.delete(sessionId);
37
+ }
38
+ clear() {
39
+ this.store.clear();
40
+ }
41
+ get size() {
42
+ return this.store.size;
43
+ }
44
+ }
45
+
46
+ // ../plugin/src/features/magic-context/tool-definition-tokens.ts
47
+ var ACTIVITY_WINDOW_MS = 10 * 60000;
48
+ var MAX_ACTIVITY_GAP_MS = 60000;
49
+ var WINDOWED_SINCE_KEY = "tool_definition_measurements:windowed_since";
50
+ var routes = new Map;
51
+ var sessionFlights = new BoundedSessionMap(1000);
52
+ var persistenceDb = null;
53
+ var windowedSince;
54
+ var boundAt = 0;
55
+ var cachedInsertStmt = null;
56
+ var cachedDeleteStmt = null;
57
+ function agentKey(agentName) {
58
+ return agentName && agentName.length > 0 ? agentName : "default";
59
+ }
60
+ function keyFor(providerID, modelID, agentName) {
61
+ return `${providerID}/${modelID}/${agentKey(agentName)}`;
62
+ }
63
+ function routeFor(providerID, modelID, agentName) {
64
+ const key = keyFor(providerID, modelID, agentName);
65
+ let route = routes.get(key);
66
+ if (!route) {
67
+ route = {
68
+ providerID,
69
+ modelID,
70
+ agentName: agentKey(agentName),
71
+ tools: new Map,
72
+ live: false,
73
+ clock: 0,
74
+ lastWallAt: Date.now(),
75
+ oldestFireAt: Number.POSITIVE_INFINITY,
76
+ retired: new Map,
77
+ legacyRows: new Set
78
+ };
79
+ routes.set(key, route);
80
+ }
81
+ return { key, route };
82
+ }
83
+ function advanceClock(route) {
84
+ const now = Date.now();
85
+ const gap = Math.min(Math.max(now - route.lastWallAt, 0), MAX_ACTIVITY_GAP_MS);
86
+ route.clock += gap;
87
+ route.lastWallAt = Math.max(route.lastWallAt, now);
88
+ return route.clock;
89
+ }
90
+ function readWindowedSince(db) {
91
+ try {
92
+ const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(WINDOWED_SINCE_KEY);
93
+ if (!row)
94
+ return;
95
+ const value = Number(row.value);
96
+ return Number.isFinite(value) ? value : undefined;
97
+ } catch {
98
+ return;
99
+ }
100
+ }
101
+ function markWindowed() {
102
+ if (windowedSince !== undefined || !persistenceDb)
103
+ return;
104
+ try {
105
+ persistenceDb.prepare("INSERT OR IGNORE INTO schema_migrations_meta (key, value) VALUES (?, ?)").run(WINDOWED_SINCE_KEY, String(boundAt));
106
+ windowedSince = readWindowedSince(persistenceDb);
107
+ } catch {}
108
+ }
109
+ function setDatabase(db) {
110
+ const rebound = persistenceDb !== null && persistenceDb !== db;
111
+ persistenceDb = db;
112
+ boundAt = Date.now();
113
+ cachedInsertStmt = null;
114
+ cachedDeleteStmt = null;
115
+ if (rebound) {
116
+ for (const route of routes.values()) {
117
+ for (const slot of route.tools.values()) {
118
+ slot.persisted = false;
119
+ slot.writeFailedAt = undefined;
120
+ }
121
+ for (const retired of route.retired.values())
122
+ retired.rowKept = false;
123
+ route.legacyRows.clear();
124
+ }
125
+ }
126
+ windowedSince = readWindowedSince(db);
127
+ if (windowedSince !== undefined)
128
+ return;
129
+ try {
130
+ if (!db.prepare("SELECT 1 FROM tool_definition_measurements LIMIT 1").get())
131
+ markWindowed();
132
+ } catch {}
133
+ }
134
+ function loadToolDefinitionMeasurements(db) {
135
+ let rows = [];
136
+ try {
137
+ rows = db.prepare("SELECT provider_id, model_id, agent_name, tool_id, token_count, recorded_at FROM tool_definition_measurements").all();
138
+ } catch {
139
+ return;
140
+ }
141
+ const since = readWindowedSince(db);
142
+ const loadedAt = new Map;
143
+ for (const row of rows) {
144
+ const { route } = routeFor(row.provider_id, row.model_id, row.agent_name);
145
+ if (route.live)
146
+ continue;
147
+ let now = loadedAt.get(route);
148
+ if (now === undefined) {
149
+ now = advanceClock(route);
150
+ loadedAt.set(route, now);
151
+ }
152
+ const legacy = since === undefined || !(Number(row.recorded_at) >= since);
153
+ route.tools.set(row.tool_id, {
154
+ tokens: row.token_count,
155
+ fingerprint: undefined,
156
+ lastFireAt: now,
157
+ legacy,
158
+ persisted: !legacy
159
+ });
160
+ route.oldestFireAt = Math.min(route.oldestFireAt, now);
161
+ if (legacy)
162
+ route.legacyRows.add(row.tool_id);
163
+ else
164
+ route.legacyRows.delete(row.tool_id);
165
+ }
166
+ }
167
+
168
+ export { BoundedSessionMap, setDatabase, loadToolDefinitionMeasurements };
@@ -5,10 +5,10 @@ import {
5
5
  } from "./index-2qtx0q6h.js";
6
6
  import {
7
7
  runSessionWarmupWorker
8
- } from "./index-6981g1xv.js";
8
+ } from "./index-c1dqxr10.js";
9
9
  import {
10
10
  logSlowWriteTransaction
11
- } from "./index-hqw0rt9k.js";
11
+ } from "./index-0wtm7g7f.js";
12
12
 
13
13
  // ../plugin/src/features/magic-context/message-fts-rowid-map.ts
14
14
  import { createHash } from "node:crypto";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  log2
3
- } from "./index-fgs78jyd.js";
3
+ } from "./index-gymgz20n.js";
4
4
 
5
5
  // ../plugin/src/shared/safe-notification-target.ts
6
6
  var DEFAULT_TITLE_RE = /^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
@@ -3,27 +3,27 @@ import {
3
3
  } from "./index-135e8hvg.js";
4
4
  import {
5
5
  log2
6
- } from "./index-fgs78jyd.js";
6
+ } from "./index-gymgz20n.js";
7
7
  import {
8
8
  ensureColumn,
9
9
  healAllNullColumns,
10
10
  installV95PerfSchema
11
- } from "./index-c474g0gj.js";
11
+ } from "./index-yacs388s.js";
12
12
  import {
13
13
  resolveOpenCodeDbPath,
14
14
  openCodeDbPathExists,
15
15
  getOpenCodeDbProbeDescriptions
16
- } from "./index-23t8ryqw.js";
16
+ } from "./index-n0zjvs3h.js";
17
17
  import {
18
18
  Database2
19
19
  } from "./index-2qtx0q6h.js";
20
20
  import {
21
21
  normalizeStoredProjectPath,
22
22
  storedPathBelongsToIdentity
23
- } from "./index-48twbev2.js";
23
+ } from "./index-6pk49fc3.js";
24
24
  import {
25
25
  logSlowWriteTransaction
26
- } from "./index-hqw0rt9k.js";
26
+ } from "./index-0wtm7g7f.js";
27
27
 
28
28
  // ../plugin/src/features/magic-context/migrations.ts
29
29
  import { isMainThread } from "node:worker_threads";