@cydm/pie 2.8.0 → 2.8.1

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 (30) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/index.js +4 -3
  3. package/dist/builtin/extensions/cron/index.js +265 -31
  4. package/dist/builtin/extensions/im-forward/index.js +13 -2
  5. package/dist/builtin/extensions/memory/index.js +275 -83
  6. package/dist/builtin/extensions/memory/package.json +2 -1
  7. package/dist/builtin/extensions/plan-mode/index.js +4 -3
  8. package/dist/builtin/extensions/subagent/index.js +6 -5
  9. package/dist/builtin/extensions/todo/index.js +4 -3
  10. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  11. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  12. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  13. package/dist/chunks/{chunk-JNOFHHLZ.js → chunk-3BC5KGDQ.js} +383 -185
  14. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  15. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  16. package/dist/chunks/{chunk-NEES4EBX.js → chunk-GDIYSMTS.js} +6 -4
  17. package/dist/chunks/{chunk-HGC25NYB.js → chunk-GH4VW2OT.js} +1 -1
  18. package/dist/chunks/{chunk-5353DEEC.js → chunk-ILUHTKF3.js} +20 -1
  19. package/dist/chunks/{chunk-LJXHECZ7.js → chunk-PK72LVWQ.js} +13867 -19759
  20. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  21. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  22. package/dist/chunks/config-74AUVDLT.js +46 -0
  23. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  24. package/dist/chunks/src-66XSMIAM.js +134 -0
  25. package/dist/chunks/src-BPSQMSSC.js +431 -0
  26. package/dist/chunks/src-OPPYTPWG.js +285 -0
  27. package/dist/chunks/{src-5XOKRS6F.js → src-YG5M2H44.js} +2 -2
  28. package/dist/chunks/{test-stream-5SDHKKDB.js → test-stream-JBWXKOQA.js} +1 -1
  29. package/dist/cli.js +970 -2283
  30. package/package.json +2 -2
@@ -1,23 +1,27 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ distillWorkerLogPath,
4
+ readDistillWorkerLog,
5
+ spawnDistillWorker
6
+ } from "../../../chunks/chunk-3NHP7HK5.js";
2
7
  import {
3
8
  getConfigDir,
4
- getSessionsDir
5
- } from "../../../chunks/chunk-5353DEEC.js";
9
+ getSettingsPath
10
+ } from "../../../chunks/chunk-ILUHTKF3.js";
6
11
  import {
7
12
  DEFAULT_MEMORY_INJECTION_BUDGET,
8
- FileSessionStore,
9
13
  MemoryStore,
14
+ consumptionSummary,
10
15
  projectKeyForDir,
11
- runCatchUp,
12
- runDistillation,
16
+ recordConsumption,
17
+ recordInjection,
13
18
  saveAttestedEntry,
14
19
  searchMemory,
15
20
  todayKey
16
- } from "../../../chunks/chunk-LJXHECZ7.js";
17
- import "../../../chunks/chunk-HGC25NYB.js";
18
- import {
19
- completeSimple
20
- } from "../../../chunks/chunk-JNOFHHLZ.js";
21
+ } from "../../../chunks/chunk-PK72LVWQ.js";
22
+ import "../../../chunks/chunk-RSL7E4R7.js";
23
+ import "../../../chunks/chunk-GH4VW2OT.js";
24
+ import "../../../chunks/chunk-3BC5KGDQ.js";
21
25
  import {
22
26
  Type
23
27
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -26,11 +30,77 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
26
30
  // builtin/extensions/memory/index.ts
27
31
  import * as fs from "node:fs";
28
32
  import * as path from "node:path";
33
+ function yesterdayKey() {
34
+ const probe = /* @__PURE__ */ new Date();
35
+ probe.setDate(probe.getDate() - 1);
36
+ return todayKey(probe.getTime());
37
+ }
29
38
  function estimateTokens(text) {
30
39
  const cjk = (text.match(/[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/g) ?? []).length;
31
40
  const rest = text.length - cjk;
32
41
  return Math.ceil(cjk + rest / 4);
33
42
  }
43
+ function readInjectSetting() {
44
+ try {
45
+ const parsed = JSON.parse(fs.readFileSync(getSettingsPath(), "utf8"));
46
+ if (!parsed || typeof parsed !== "object") return true;
47
+ const extensions = parsed.extensions;
48
+ if (!extensions || typeof extensions !== "object" || Array.isArray(extensions)) return true;
49
+ if (!Object.hasOwn(extensions, "memory")) return true;
50
+ const entry = extensions.memory;
51
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return true;
52
+ if (!Object.hasOwn(entry, "inject")) return true;
53
+ const inject = entry.inject;
54
+ return typeof inject === "boolean" ? inject : true;
55
+ } catch {
56
+ return true;
57
+ }
58
+ }
59
+ function writeInjectSetting(enabled) {
60
+ const filePath = getSettingsPath();
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
64
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("corrupt settings");
65
+ } catch (error) {
66
+ if (error.code !== "ENOENT") return false;
67
+ parsed = {};
68
+ }
69
+ const extensionsRaw = parsed.extensions;
70
+ const extensions = {};
71
+ if (extensionsRaw && typeof extensionsRaw === "object" && !Array.isArray(extensionsRaw)) {
72
+ for (const key of Object.keys(extensionsRaw)) {
73
+ extensions[key] = extensionsRaw[key];
74
+ }
75
+ }
76
+ const previous = Object.hasOwn(extensions, "memory") ? extensions.memory : void 0;
77
+ const entry = previous === true || previous === false ? { enabled: previous } : previous && typeof previous === "object" && !Array.isArray(previous) ? { ...previous } : {};
78
+ entry.inject = enabled;
79
+ Object.defineProperty(extensions, "memory", { value: entry, enumerable: true, configurable: true, writable: true });
80
+ parsed.extensions = extensions;
81
+ try {
82
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
83
+ const tempPath = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
84
+ try {
85
+ const fd = fs.openSync(tempPath, "w");
86
+ try {
87
+ fs.writeFileSync(fd, JSON.stringify(parsed, null, 2) + "\n");
88
+ fs.fsyncSync(fd);
89
+ } finally {
90
+ fs.closeSync(fd);
91
+ }
92
+ fs.renameSync(tempPath, filePath);
93
+ } finally {
94
+ try {
95
+ fs.unlinkSync(tempPath);
96
+ } catch {
97
+ }
98
+ }
99
+ return true;
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
34
104
  function memoryExtension(ctx) {
35
105
  const memoryDir = path.join(getConfigDir(), "memory");
36
106
  const store = new MemoryStore(memoryDir);
@@ -38,15 +108,75 @@ function memoryExtension(ctx) {
38
108
  const project = projectKeyForDir(ctx.cwd);
39
109
  let activeSessionId = null;
40
110
  ctx.on("session:changed", (event) => {
111
+ if (activeSessionId !== null && activeSessionId !== event.sessionId) {
112
+ sessionConsumedIds = /* @__PURE__ */ new Set();
113
+ injectionMemo = null;
114
+ lastTurnAt = 0;
115
+ ctx.log(`[memory] session switch (${activeSessionId.slice(0, 8)} \u2192 ${event.sessionId.slice(0, 8)}): injection memo + consumption scope reset`);
116
+ }
41
117
  activeSessionId = event.sessionId;
42
118
  });
119
+ const INJECTION_IDLE_REFRESH_MS = 60 * 60 * 1e3;
120
+ let injectionMemo = null;
121
+ let sessionConsumedIds = /* @__PURE__ */ new Set();
122
+ let lastTurnAt = 0;
123
+ const distillWatermark = () => Math.max(0, ...Object.values(store.loadState().runs).map((run) => run.ops > 0 ? run.ranAt : 0));
124
+ const updateFooterTag = () => {
125
+ ctx.ui.setStatus?.("memory", readInjectSetting() ? "[MEM]" : void 0);
126
+ };
127
+ updateFooterTag();
128
+ const refreshInjection = (reason) => {
129
+ if (injectionMemo === null) return;
130
+ injectionMemo = null;
131
+ ctx.log(`[memory] injection memo dropped (${reason})`);
132
+ };
133
+ ctx.on("agent:end", (event) => {
134
+ if (injectionMemo === null || injectionMemo.injectedIds.length === 0) return;
135
+ try {
136
+ const textOf = (message) => {
137
+ if (typeof message.content === "string") return message.content;
138
+ if (Array.isArray(message.content)) {
139
+ return message.content.filter((block) => block && typeof block === "object" && block.type === "text").map((block) => block.text).join("\n");
140
+ }
141
+ return "";
142
+ };
143
+ const output = event.messages.filter((message) => message.role === "assistant" || message.role === "toolResult").map(textOf).join("\n");
144
+ const eligible = injectionMemo.injectedIds.filter((id) => !sessionConsumedIds.has(id));
145
+ if (eligible.length === 0) return;
146
+ const { consumed } = recordConsumption(store, eligible, output);
147
+ for (const id of consumed) sessionConsumedIds.add(id);
148
+ if (consumed.length > 0) {
149
+ ctx.log(`[memory] consumption credited: ${consumed.length} entr${consumed.length === 1 ? "y" : "ies"} this session`);
150
+ }
151
+ } catch (error) {
152
+ ctx.log(`[memory] consumption accounting failed (skipped): ${String(error)}`);
153
+ }
154
+ });
43
155
  ctx.on("before_agent_start", (event) => {
44
156
  try {
45
- const section = buildInjectionSection(store, budget, project.key);
46
- if (!section) return;
157
+ updateFooterTag();
158
+ const now = Date.now();
159
+ const idleMs = lastTurnAt > 0 ? now - lastTurnAt : Infinity;
160
+ lastTurnAt = now;
161
+ if (!readInjectSetting()) return {};
162
+ const watermark = distillWatermark();
163
+ if (injectionMemo === null || idleMs >= INJECTION_IDLE_REFRESH_MS || injectionMemo.watermark < watermark) {
164
+ const built = buildInjectionSectionWithIds(store, budget, project.key);
165
+ injectionMemo = {
166
+ text: built.text,
167
+ watermark,
168
+ injectedIds: built.injectedIds
169
+ };
170
+ try {
171
+ recordInjection(store, built.injectedIds);
172
+ } catch (error) {
173
+ ctx.log(`[memory] injection accounting failed (skipped): ${String(error)}`);
174
+ }
175
+ }
176
+ if (!injectionMemo.text) return;
47
177
  return { systemPrompt: `${event.baseSystemPrompt}
48
178
 
49
- ${section}` };
179
+ ${injectionMemo.text}` };
50
180
  } catch (error) {
51
181
  ctx.log(`[memory] injection failed (skipping): ${String(error)}`);
52
182
  return {};
@@ -114,19 +244,14 @@ ${section}` };
114
244
  });
115
245
  ctx.registerCommand({
116
246
  path: ["tools", "memory"],
117
- description: "Memory governance: journal/show/diff/rollback/distill/status",
118
- handler: async (_commandCtx, args) => handleMemoryCommand(ctx, store, args ?? "")
247
+ description: "Memory menu: toggle injection / journal / status",
248
+ handler: async (commandCtx, args) => handleMemoryCommand(ctx, store, args ?? "", { updateFooterTag, refreshInjection })
119
249
  });
120
- if (ctx.hasUI && process.env.PIE_CRON_ROLE !== "worker") {
121
- let disposed = false;
122
- ctx.registerCleanup?.(() => {
123
- disposed = true;
124
- });
125
- void startupCatchUp(ctx, store, () => disposed).catch((error) => ctx.log(`[memory] catch-up failed: ${String(error)}`));
126
- }
127
250
  }
128
251
  function buildInjectionSection(store, budget, projectKey) {
129
- const lines = [];
252
+ return buildInjectionSectionWithIds(store, budget, projectKey).text;
253
+ }
254
+ function buildInjectionSectionWithIds(store, budget, projectKey) {
130
255
  const entries = store.loadEntries();
131
256
  const take = (surface, limit, extra) => {
132
257
  const pool = entries.filter((entry) => {
@@ -138,7 +263,7 @@ function buildInjectionSection(store, budget, projectKey) {
138
263
  for (const entry of pool) {
139
264
  const cost = estimateTokens(`- ${entry.text}`);
140
265
  if (used + cost > limit) continue;
141
- kept.push(`- ${entry.text}`);
266
+ kept.push({ line: `- ${entry.text}`, id: entry.id });
142
267
  used += cost;
143
268
  }
144
269
  return kept;
@@ -161,7 +286,7 @@ function buildInjectionSection(store, budget, projectKey) {
161
286
  digestUsed += cost;
162
287
  }
163
288
  if (user.length === 0 && memory.length === 0 && threads.length === 0 && projectLines.length === 0 && digest.length === 0) {
164
- return "";
289
+ return { text: "", injectedIds: [] };
165
290
  }
166
291
  const sections = [];
167
292
  if (user.length > 0) sections.push({ heading: "User (stable preferences)", items: user });
@@ -169,14 +294,17 @@ function buildInjectionSection(store, budget, projectKey) {
169
294
  if (memory.length > 0) sections.push({ heading: "Durable facts", items: memory });
170
295
  if (threads.length > 0) sections.push({ heading: "Open threads", items: threads });
171
296
  const nonEmptyDigest = digest.filter((line) => !/:\s*$/.test(line));
172
- if (nonEmptyDigest.length > 0) sections.push({ heading: "Recent days", items: nonEmptyDigest });
297
+ if (nonEmptyDigest.length > 0) sections.push({ heading: "Recent days", items: nonEmptyDigest.map((line) => ({ line })) });
173
298
  const footer = "When the user explicitly asks to remember something, call memory_save. Use memory_search for anything not listed here.";
174
299
  const TOTAL_CEILING = 1500;
175
300
  const ceiling = Math.min(TOTAL_CEILING, budget.user + budget.memory + budget.threads + budget.project + budget.recentDigest);
176
- const render = (list) => ["## Memory", "", ...list.flatMap((section) => [`### ${section.heading}`, ...section.items, ""]), footer].join("\n").trim();
301
+ const render = (list) => ["## Memory", "", ...list.flatMap((section) => [`### ${section.heading}`, ...section.items.map((item) => item.line), ""]), footer].join("\n").trim();
177
302
  while (sections.length > 0) {
178
303
  const rendered = render(sections);
179
- if (estimateTokens(rendered) <= ceiling) return rendered;
304
+ if (estimateTokens(rendered) <= ceiling) {
305
+ const injectedIds = sections.flatMap((section) => section.items.map((item) => item.id).filter((id) => id !== void 0));
306
+ return { text: rendered, injectedIds };
307
+ }
180
308
  const last = sections[sections.length - 1];
181
309
  if (last.items.length > 0) {
182
310
  last.items.pop();
@@ -185,7 +313,45 @@ function buildInjectionSection(store, budget, projectKey) {
185
313
  sections.pop();
186
314
  }
187
315
  }
188
- return "";
316
+ return { text: "", injectedIds: [] };
317
+ }
318
+ function memoryOverview(store) {
319
+ const entries = store.loadEntries();
320
+ return [
321
+ `injection: ${readInjectSetting() ? "on" : "off"} (/tools/memory toggle)`,
322
+ `memory root: ${store.dir}`,
323
+ `entries: ${entries.length} (user ${entries.filter((e) => e.surface === "user").length}, memory ${entries.filter((e) => e.surface === "memory").length}, threads ${entries.filter((e) => e.surface === "threads").length}, project ${entries.filter((e) => e.surface === "project").length})`,
324
+ ...consumptionSummary(entries),
325
+ `journal days: ${store.listJournalDates().length}; snapshots: ${store.listSnapshots().length}`,
326
+ "subcommands: toggle | refresh | journal [date] | show <id> | diff <snapshotId> | rollback <snapshotId> | distill [date] | status"
327
+ ].join("\n");
328
+ }
329
+ function journalFor(store, date) {
330
+ const resolved = date ?? store.listJournalDates().at(-1);
331
+ if (!resolved) return "No journals yet.";
332
+ return store.readJournal(resolved) ?? `No journal for ${resolved}.`;
333
+ }
334
+ function refreshNow(ctx, hooks) {
335
+ if (!readInjectSetting()) {
336
+ return "Memory injection is off \u2014 nothing to refresh (toggle it on first).";
337
+ }
338
+ hooks.refreshInjection?.("explicit refresh");
339
+ ctx.ui.notify?.("Memory injection refreshed \u2014 the next turn rebuilds it from current memory (one cache re-write).", "info");
340
+ return "Memory injection will be rebuilt from current memory on the next turn (the prompt-prefix cache is invalidated once, by design).";
341
+ }
342
+ function toggleInjection(ctx, hooks) {
343
+ const next = !readInjectSetting();
344
+ if (!writeInjectSetting(next)) {
345
+ ctx.ui.notify?.("Memory: could not save settings.json; injection unchanged.", "error");
346
+ return "Could not save settings.json; injection unchanged.";
347
+ }
348
+ hooks.updateFooterTag?.();
349
+ hooks.refreshInjection?.("toggle");
350
+ ctx.ui.notify?.(
351
+ next ? "Memory injection on (effective next turn)" : "Memory injection off (effective next turn)",
352
+ "info"
353
+ );
354
+ return next ? "Memory injection on (effective next turn: the memory section returns to the system prompt)." : "Memory injection off (effective next turn: the system prompt no longer carries the memory section; tools and distillation keep running).";
189
355
  }
190
356
  function renderSnapshotDiff(store, snapshotId) {
191
357
  const snapshotDir = path.join(store.dir, ".snapshots", snapshotId);
@@ -227,22 +393,43 @@ function renderSnapshotDiff(store, snapshotId) {
227
393
  return lines.length === 1 ? `${lines[0]}
228
394
  (no changes)` : lines.join("\n");
229
395
  }
230
- async function handleMemoryCommand(ctx, store, args) {
396
+ async function handleMemoryCommand(ctx, store, args, hooks = {}) {
231
397
  const [sub, ...rest] = args.trim().split(/\s+/);
232
398
  switch (sub) {
233
399
  case "": {
234
- const entries = store.loadEntries();
235
- return [
236
- `memory root: ${store.dir}`,
237
- `entries: ${entries.length} (user ${entries.filter((e) => e.surface === "user").length}, memory ${entries.filter((e) => e.surface === "memory").length}, threads ${entries.filter((e) => e.surface === "threads").length}, project ${entries.filter((e) => e.surface === "project").length})`,
238
- `journal days: ${store.listJournalDates().length}; snapshots: ${store.listSnapshots().length}`,
239
- "subcommands: journal [date] | show <id> | diff <snapshotId> | rollback <snapshotId> | distill [date] | status"
240
- ].join("\n");
400
+ if (ctx.hasUI && ctx.ui?.select) {
401
+ const injecting = readInjectSetting();
402
+ const choice = await ctx.ui.select(
403
+ "Memory",
404
+ [
405
+ `Memory injection: ${injecting ? "ON" : "OFF"} \u2014 turn ${injecting ? "off" : "on"}`,
406
+ "Refresh injection now",
407
+ "Status overview",
408
+ "Latest journal",
409
+ "Distill yesterday"
410
+ ]
411
+ );
412
+ if (!choice) return "";
413
+ if (choice.startsWith("Memory injection:")) return toggleInjection(ctx, hooks);
414
+ if (choice === "Refresh injection now") return refreshNow(ctx, hooks);
415
+ if (choice === "Status overview") return memoryOverview(store);
416
+ if (choice === "Latest journal") return journalFor(store, void 0);
417
+ if (choice === "Distill yesterday") {
418
+ const date = yesterdayKey();
419
+ return triggerDistillWorker(store, date);
420
+ }
421
+ return "";
422
+ }
423
+ return memoryOverview(store);
424
+ }
425
+ case "toggle": {
426
+ return toggleInjection(ctx, hooks);
427
+ }
428
+ case "refresh": {
429
+ return refreshNow(ctx, hooks);
241
430
  }
242
431
  case "journal": {
243
- const date = rest[0] ?? store.listJournalDates().at(-1);
244
- if (!date) return "No journals yet.";
245
- return store.readJournal(date) ?? `No journal for ${date}.`;
432
+ return journalFor(store, rest[0]);
246
433
  }
247
434
  case "show": {
248
435
  const entry = store.entryById(rest[0] ?? "");
@@ -256,8 +443,7 @@ async function handleMemoryCommand(ctx, store, args) {
256
443
  }
257
444
  case "distill": {
258
445
  const date = rest[0] ?? todayKey(Date.now() - 24 * 60 * 60 * 1e3);
259
- const result = await distillWithHostModels(ctx, store, date);
260
- return `${result.status}: sessions=${result.sessions} ops=${result.patchOps} journal=${result.journalWritten}${result.error ? ` error=${result.error}` : ""}`;
446
+ return triggerDistillWorker(store, date);
261
447
  }
262
448
  case "diff": {
263
449
  const snapshotId = rest[0] ?? store.listSnapshots()[0];
@@ -269,55 +455,61 @@ async function handleMemoryCommand(ctx, store, args) {
269
455
  const days = Object.entries(state.runs).sort(([a], [b]) => a < b ? 1 : -1).slice(0, 5);
270
456
  return days.length === 0 ? "No distillation runs recorded yet." : days.map(([date, run]) => `${date}: ${run.ops} ops at ${new Date(run.ranAt).toISOString()}${run.gated ? " (gated)" : ""}`).join("\n");
271
457
  }
458
+ case "log": {
459
+ const log = readDistillWorkerLog(store.dir, 20);
460
+ return log.length === 0 ? `No worker log yet (${distillWorkerLogPath(store.dir)}).` : log.join("\n");
461
+ }
462
+ case "projects": {
463
+ return listProjectSurfaces(store, projectKeyForDir(ctx.cwd).key);
464
+ }
465
+ case "purge": {
466
+ const id = rest[0] ?? "";
467
+ const entry = store.entryById(id);
468
+ if (!entry) return "Entry not found.";
469
+ if (entry.retiredAt) return `Entry ${id} is already retired.`;
470
+ store.applyEntryPatch([{ op: "retire", id, reason: "purged via /tools/memory purge" }]);
471
+ return `Retired entry ${id} (${entry.kind}): ${entry.text.slice(0, 80)}`;
472
+ }
473
+ case "edit": {
474
+ if (!rest[0] || !rest[1]) return 'Usage: edit <id> "<new text>" (quote the text)';
475
+ const id = rest[0];
476
+ const entry = store.entryById(id);
477
+ if (!entry) return "Entry not found.";
478
+ let text = rest.slice(1).join(" ").slice(0, 240);
479
+ if (text.length >= 2 && (text.startsWith('"') && text.endsWith('"') || text.startsWith("'") && text.endsWith("'"))) {
480
+ text = text.slice(1, -1);
481
+ }
482
+ if (!text.trim()) return "New text must not be empty.";
483
+ store.applyEntryPatch([{ op: "update", id, text, evidence: entry.evidence }]);
484
+ return `Updated entry ${id}: ${text}`;
485
+ }
272
486
  default:
273
487
  return `Unknown subcommand: ${sub}`;
274
488
  }
275
489
  }
276
- function createModelCall(ctx, modelClass) {
277
- return async (prompt, options) => {
278
- const resolved = ctx.resolveModelClass?.(modelClass);
279
- const pair = resolved?.model && resolved?.apiKey ? { model: resolved.model, apiKey: resolved.apiKey } : ctx.model && ctx.apiKey ? { model: ctx.model, apiKey: ctx.apiKey } : void 0;
280
- if (!pair) {
281
- throw new Error(`no complete model/key pair for memory distillation (${modelClass}${resolved?.fallbackReason ? `: ${resolved.fallbackReason}` : ""})`);
282
- }
283
- const message = await completeSimple(pair.model, {
284
- systemPrompt: options?.system ?? "You are a precise extraction engine.",
285
- messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }]
286
- }, { apiKey: pair.apiKey, maxTokens: Math.min(pair.model.maxTokens ?? 4096, 4096) });
287
- if (message.stopReason && message.stopReason !== "stop") {
288
- throw new Error(`memory model call ended with stopReason=${message.stopReason}`);
289
- }
290
- return message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
291
- };
292
- }
293
- async function distillWithHostModels(ctx, store, date) {
294
- return runDistillation(
295
- {
296
- sessionStore: new FileSessionStore(getSessionsDir()),
297
- memoryStore: store,
298
- lightCall: createModelCall(ctx, "light"),
299
- balancedCall: createModelCall(ctx, "balanced"),
300
- log: (message) => ctx.log(message)
301
- },
302
- date
303
- );
490
+ function triggerDistillWorker(store, date) {
491
+ if (store.hasRun(date)) {
492
+ return `${date}: already distilled (checkpoint present). Use rollback first to re-run.`;
493
+ }
494
+ const spawned = spawnDistillWorker(store.dir, date);
495
+ if (!spawned) {
496
+ return `Could not spawn distillation worker (see ${distillWorkerLogPath(store.dir)}).`;
497
+ }
498
+ return `Distillation worker started for ${date} (detached; progress in ${distillWorkerLogPath(store.dir)}; /tools/memory status after it finishes).`;
304
499
  }
305
- async function startupCatchUp(ctx, store, isDisposed) {
306
- await runCatchUp({
307
- sessionStore: new FileSessionStore(getSessionsDir()),
308
- memoryStore: store,
309
- lightCall: async (prompt, options) => {
310
- if (isDisposed?.()) throw new Error("memory extension disposed");
311
- return createModelCall(ctx, "light")(prompt, options);
312
- },
313
- balancedCall: async (prompt, options) => {
314
- if (isDisposed?.()) throw new Error("memory extension disposed");
315
- return createModelCall(ctx, "balanced")(prompt, options);
316
- },
317
- log: (message) => ctx.log(message)
500
+ function listProjectSurfaces(store, currentKey) {
501
+ const keys = store.listProjectKeys();
502
+ if (keys.length === 0) return "No project memory yet (distillation records project surfaces as projects accumulate).";
503
+ const lines = keys.map((key) => {
504
+ const entries = store.loadEntries().filter((entry) => entry.projectKey === key && !entry.retiredAt);
505
+ const meta = store.readProjectMeta(key);
506
+ const current = key === currentKey ? " \u2190 current" : "";
507
+ return `- ${key}: ${entries.length} entr${entries.length === 1 ? "y" : "ies"}${meta?.gitUrl ? ` (${meta.gitUrl})` : ""}${current}`;
318
508
  });
509
+ return ["Project memory surfaces:", ...lines].join("\n");
319
510
  }
320
511
  export {
321
512
  buildInjectionSection,
513
+ buildInjectionSectionWithIds,
322
514
  memoryExtension as default
323
515
  };
@@ -6,7 +6,8 @@
6
6
  "type": "module",
7
7
  "pie": {
8
8
  "name": "memory",
9
- "main": "index.js"
9
+ "main": "index.js",
10
+ "defaultEnablement": false
10
11
  },
11
12
  "keywords": [
12
13
  "pie",
@@ -6,9 +6,10 @@ import {
6
6
  createPlanCapability,
7
7
  markCompletedPlanSteps,
8
8
  restoreExecutionState
9
- } from "../../../chunks/chunk-LJXHECZ7.js";
10
- import "../../../chunks/chunk-HGC25NYB.js";
11
- import "../../../chunks/chunk-JNOFHHLZ.js";
9
+ } from "../../../chunks/chunk-PK72LVWQ.js";
10
+ import "../../../chunks/chunk-RSL7E4R7.js";
11
+ import "../../../chunks/chunk-GH4VW2OT.js";
12
+ import "../../../chunks/chunk-3BC5KGDQ.js";
12
13
  import {
13
14
  Type
14
15
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -5,18 +5,19 @@ import {
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
7
  logTransportLifecycle
8
- } from "../../../chunks/chunk-NEES4EBX.js";
8
+ } from "../../../chunks/chunk-GDIYSMTS.js";
9
9
  import {
10
10
  getConfigDir
11
- } from "../../../chunks/chunk-5353DEEC.js";
11
+ } from "../../../chunks/chunk-ILUHTKF3.js";
12
12
  import {
13
13
  SUBAGENT_SESSION_RECORD_VERSION,
14
14
  createPolicyEnforcedTools,
15
15
  createSharedFileSystemTools,
16
16
  createSubagentCapability
17
- } from "../../../chunks/chunk-LJXHECZ7.js";
18
- import "../../../chunks/chunk-HGC25NYB.js";
19
- import "../../../chunks/chunk-JNOFHHLZ.js";
17
+ } from "../../../chunks/chunk-PK72LVWQ.js";
18
+ import "../../../chunks/chunk-RSL7E4R7.js";
19
+ import "../../../chunks/chunk-GH4VW2OT.js";
20
+ import "../../../chunks/chunk-3BC5KGDQ.js";
20
21
  import "../../../chunks/chunk-XXGYUYXI.js";
21
22
  import "../../../chunks/chunk-LZQXQOPJ.js";
22
23
 
@@ -8,9 +8,10 @@ import {
8
8
  executeManageTodoList,
9
9
  executionStateToTodos,
10
10
  restoreExecutionState
11
- } from "../../../chunks/chunk-LJXHECZ7.js";
12
- import "../../../chunks/chunk-HGC25NYB.js";
13
- import "../../../chunks/chunk-JNOFHHLZ.js";
11
+ } from "../../../chunks/chunk-PK72LVWQ.js";
12
+ import "../../../chunks/chunk-RSL7E4R7.js";
13
+ import "../../../chunks/chunk-GH4VW2OT.js";
14
+ import "../../../chunks/chunk-3BC5KGDQ.js";
14
15
  import "../../../chunks/chunk-XXGYUYXI.js";
15
16
  import "../../../chunks/chunk-LZQXQOPJ.js";
16
17
 
@@ -4396,9 +4396,14 @@ var VERSION = pkg.version;
4396
4396
  var ENV_AGENT_DIR = "PIE_CODING_AGENT_DIR";
4397
4397
  function getConfigDir() {
4398
4398
  const envDir = process.env[ENV_AGENT_DIR];
4399
- if (envDir) {
4399
+ if (envDir !== void 0 && envDir !== "") {
4400
4400
  if (envDir === "~") return homedir();
4401
4401
  if (envDir.startsWith("~/")) return homedir() + envDir.slice(1);
4402
+ if (envDir === "undefined" || envDir === "null") {
4403
+ throw new Error(
4404
+ `${ENV_AGENT_DIR} is set to the literal string "${envDir}"; unset it or point it at a real directory`
4405
+ );
4406
+ }
4402
4407
  return envDir;
4403
4408
  }
4404
4409
  return join(homedir(), CONFIG_DIR_NAME);
@@ -71,9 +71,14 @@ var VERSION = pkg.version;
71
71
  var ENV_AGENT_DIR = "PIE_CODING_AGENT_DIR";
72
72
  function getConfigDir() {
73
73
  const envDir = process.env[ENV_AGENT_DIR];
74
- if (envDir) {
74
+ if (envDir !== void 0 && envDir !== "") {
75
75
  if (envDir === "~") return homedir();
76
76
  if (envDir.startsWith("~/")) return homedir() + envDir.slice(1);
77
+ if (envDir === "undefined" || envDir === "null") {
78
+ throw new Error(
79
+ `${ENV_AGENT_DIR} is set to the literal string "${envDir}"; unset it or point it at a real directory`
80
+ );
81
+ }
77
82
  return envDir;
78
83
  }
79
84
  return join(homedir(), CONFIG_DIR_NAME);
@@ -0,0 +1,13 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ AuthStorage,
4
+ FileAuthStorageBackend,
5
+ InMemoryAuthStorageBackend
6
+ } from "./chunk-6DNYGVZP.js";
7
+ import "./chunk-ILUHTKF3.js";
8
+ import "./chunk-LZQXQOPJ.js";
9
+ export {
10
+ AuthStorage,
11
+ FileAuthStorageBackend,
12
+ InMemoryAuthStorageBackend
13
+ };