@cydm/pie 2.8.0 → 3.0.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.
Files changed (41) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/index.js +4 -3
  3. package/dist/builtin/extensions/changelog/index.js +2 -2
  4. package/dist/builtin/extensions/cron/index.js +430 -43
  5. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  6. package/dist/builtin/extensions/herdr-agent-state/index.js +2 -2
  7. package/dist/builtin/extensions/im-forward/index.js +13 -2
  8. package/dist/builtin/extensions/memory/index.js +277 -83
  9. package/dist/builtin/extensions/memory/package.json +2 -1
  10. package/dist/builtin/extensions/plan-mode/index.js +4 -3
  11. package/dist/builtin/extensions/subagent/index.js +7 -6
  12. package/dist/builtin/extensions/todo/index.js +4 -3
  13. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +106 -2
  14. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +1 -0
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  16. package/dist/builtin/skills/chrome-devtools-axi/{chunk-BNSAEVRT.js → chunk-WOGAQ4P5.js} +2 -2
  17. package/dist/builtin/skills/chrome-devtools-axi/{cli-AO2ZTPRM.js → cli-CHC7XYFU.js} +27 -3
  18. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +8 -3
  19. package/dist/builtin/skills/computer-use-axi/computer-use-axi-cli.js +1 -0
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/scripts/setup-helper.mjs +6 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +130 -9
  23. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  24. package/dist/chunks/{chunk-JNOFHHLZ.js → chunk-3BC5KGDQ.js} +383 -185
  25. package/dist/chunks/chunk-3FRKOFSP.js +9667 -0
  26. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  27. package/dist/chunks/{chunk-LJXHECZ7.js → chunk-7FEPQHYX.js} +13867 -19759
  28. package/dist/chunks/{chunk-NEES4EBX.js → chunk-BUDXV3TR.js} +28 -18
  29. package/dist/chunks/{chunk-HGC25NYB.js → chunk-GH4VW2OT.js} +1 -1
  30. package/dist/chunks/{chunk-5353DEEC.js → chunk-ILUHTKF3.js} +20 -1
  31. package/dist/chunks/chunk-OEQYEYB3.js +299 -0
  32. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  33. package/dist/chunks/config-74AUVDLT.js +46 -0
  34. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  35. package/dist/chunks/src-66XSMIAM.js +134 -0
  36. package/dist/chunks/src-AE3OCAE6.js +431 -0
  37. package/dist/chunks/src-RVTDUSPJ.js +293 -0
  38. package/dist/chunks/{src-5XOKRS6F.js → src-YG5M2H44.js} +2 -2
  39. package/dist/chunks/{test-stream-5SDHKKDB.js → test-stream-JBWXKOQA.js} +1 -1
  40. package/dist/cli.js +1455 -2358
  41. package/package.json +4 -4
@@ -43,7 +43,7 @@ function truncateText(text) {
43
43
  function runPythonScript(script, fallbackMessage) {
44
44
  const failures = [];
45
45
  for (const pythonBin of PYTHON_CANDIDATES) {
46
- const result = spawnSync(pythonBin, ["-c", script], { encoding: "utf8" });
46
+ const result = spawnSync(pythonBin, ["-c", script], { encoding: "utf8", windowsHide: true });
47
47
  if (result.status === 0) {
48
48
  return result.stdout;
49
49
  }
@@ -110,7 +110,7 @@ function buildReleaseReportArgs(params) {
110
110
  }
111
111
  function spawnHerdrReport(binPath, args, timeoutMs = REPORT_TIMEOUT_MS) {
112
112
  try {
113
- const child = spawn(binPath, args, { detached: true, stdio: "ignore" });
113
+ const child = spawn(binPath, args, { detached: true, stdio: "ignore", windowsHide: true });
114
114
  let killTimer;
115
115
  const clearTimers = () => {
116
116
  clearTimeout(timer);
@@ -140,7 +140,7 @@ var KILL_GRACE_MS = 1e3;
140
140
  async function runHerdrReportBounded(binPath, args, timeoutMs = REPORT_TIMEOUT_MS) {
141
141
  let child;
142
142
  try {
143
- child = spawn(binPath, args, { detached: true, stdio: "ignore" });
143
+ child = spawn(binPath, args, { detached: true, stdio: "ignore", windowsHide: true });
144
144
  } catch {
145
145
  return { outcome: "spawn-error", exitCode: null };
146
146
  }
@@ -848,6 +848,16 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
848
848
  terminalCleanup();
849
849
  }
850
850
  }
851
+ function escapeRegExp(text) {
852
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
853
+ }
854
+ function parseSessionAddress(text) {
855
+ const name = ctx.getSessionName?.()?.trim();
856
+ if (!name) return { kind: "absent" };
857
+ const own = new RegExp(`^${escapeRegExp(name)}:[ \\t]+(.+)$`, "s").exec(text.trim());
858
+ if (own) return { kind: "addressed", body: own[1] };
859
+ return { kind: "absent" };
860
+ }
851
861
  async function handleInboundEventInner(event, retry) {
852
862
  const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId;
853
863
  if (!matchesTarget) return;
@@ -875,7 +885,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
875
885
  releaseInvalidatedEvent();
876
886
  return;
877
887
  }
878
- const resolution = await resolveRouteForInbound(messageId, meta);
888
+ const address = parseSessionAddress(event.text);
889
+ const resolution = address.kind === "addressed" ? { found: { messageId: "", threadId: meta.threadId ?? null, sessionId, sentAt: Date.now() } } : await resolveRouteForInbound(messageId, meta);
879
890
  if (!("found" in resolution)) {
880
891
  if (isTransient(resolution)) retry();
881
892
  else ctx.log(`im-forward: no route for ${messageId}; ignoring`);
@@ -887,7 +898,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
887
898
  return;
888
899
  }
889
900
  const imageKeys = event.images;
890
- const caption = event.text;
901
+ const caption = address.kind === "addressed" ? address.body : event.text;
891
902
  if (!caption && !imageKeys.length) return;
892
903
  const submitText = `${IM_INPUT_PREFIX}
893
904
  ${caption || IM_INPUT_FALLBACK_CAPTION}`;
@@ -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-OEQYEYB3.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-7FEPQHYX.js";
22
+ import "../../../chunks/chunk-3FRKOFSP.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,77 @@ 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
+ pendingDistillHint = false;
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
+ let injectionMemo = null;
120
+ let sessionConsumedIds = /* @__PURE__ */ new Set();
121
+ let pendingDistillHint = false;
122
+ const distillWatermark = () => Math.max(0, ...Object.values(store.loadState().runs).map((run) => run.ops > 0 ? run.ranAt : 0));
123
+ const updateFooterTag = () => {
124
+ ctx.ui.setStatus?.("memory", readInjectSetting() ? pendingDistillHint && injectionMemo !== null ? "[MEM*]" : "[MEM]" : void 0);
125
+ };
126
+ updateFooterTag();
127
+ const refreshInjection = (reason) => {
128
+ pendingDistillHint = false;
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
+ const injectOn = readInjectSetting();
158
+ ctx.ui.setStatus?.("memory", injectOn ? pendingDistillHint && injectionMemo !== null ? "[MEM*]" : "[MEM]" : void 0);
159
+ if (!injectOn) return {};
160
+ const watermark = distillWatermark();
161
+ if (injectionMemo === null) {
162
+ const built = buildInjectionSectionWithIds(store, budget, project.key);
163
+ injectionMemo = {
164
+ text: built.text,
165
+ watermark,
166
+ injectedIds: built.injectedIds
167
+ };
168
+ pendingDistillHint = false;
169
+ try {
170
+ recordInjection(store, built.injectedIds);
171
+ } catch (error) {
172
+ ctx.log(`[memory] injection accounting failed (skipped): ${String(error)}`);
173
+ }
174
+ } else if (watermark > injectionMemo.watermark) {
175
+ pendingDistillHint = true;
176
+ ctx.ui.setStatus?.("memory", "[MEM*]");
177
+ }
178
+ if (!injectionMemo.text) return;
47
179
  return { systemPrompt: `${event.baseSystemPrompt}
48
180
 
49
- ${section}` };
181
+ ${injectionMemo.text}` };
50
182
  } catch (error) {
51
183
  ctx.log(`[memory] injection failed (skipping): ${String(error)}`);
52
184
  return {};
@@ -114,19 +246,14 @@ ${section}` };
114
246
  });
115
247
  ctx.registerCommand({
116
248
  path: ["tools", "memory"],
117
- description: "Memory governance: journal/show/diff/rollback/distill/status",
118
- handler: async (_commandCtx, args) => handleMemoryCommand(ctx, store, args ?? "")
249
+ description: "Memory menu: toggle injection / journal / status",
250
+ handler: async (commandCtx, args) => handleMemoryCommand(ctx, store, args ?? "", { updateFooterTag, refreshInjection })
119
251
  });
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
252
  }
128
253
  function buildInjectionSection(store, budget, projectKey) {
129
- const lines = [];
254
+ return buildInjectionSectionWithIds(store, budget, projectKey).text;
255
+ }
256
+ function buildInjectionSectionWithIds(store, budget, projectKey) {
130
257
  const entries = store.loadEntries();
131
258
  const take = (surface, limit, extra) => {
132
259
  const pool = entries.filter((entry) => {
@@ -138,7 +265,7 @@ function buildInjectionSection(store, budget, projectKey) {
138
265
  for (const entry of pool) {
139
266
  const cost = estimateTokens(`- ${entry.text}`);
140
267
  if (used + cost > limit) continue;
141
- kept.push(`- ${entry.text}`);
268
+ kept.push({ line: `- ${entry.text}`, id: entry.id });
142
269
  used += cost;
143
270
  }
144
271
  return kept;
@@ -161,7 +288,7 @@ function buildInjectionSection(store, budget, projectKey) {
161
288
  digestUsed += cost;
162
289
  }
163
290
  if (user.length === 0 && memory.length === 0 && threads.length === 0 && projectLines.length === 0 && digest.length === 0) {
164
- return "";
291
+ return { text: "", injectedIds: [] };
165
292
  }
166
293
  const sections = [];
167
294
  if (user.length > 0) sections.push({ heading: "User (stable preferences)", items: user });
@@ -169,14 +296,17 @@ function buildInjectionSection(store, budget, projectKey) {
169
296
  if (memory.length > 0) sections.push({ heading: "Durable facts", items: memory });
170
297
  if (threads.length > 0) sections.push({ heading: "Open threads", items: threads });
171
298
  const nonEmptyDigest = digest.filter((line) => !/:\s*$/.test(line));
172
- if (nonEmptyDigest.length > 0) sections.push({ heading: "Recent days", items: nonEmptyDigest });
299
+ if (nonEmptyDigest.length > 0) sections.push({ heading: "Recent days", items: nonEmptyDigest.map((line) => ({ line })) });
173
300
  const footer = "When the user explicitly asks to remember something, call memory_save. Use memory_search for anything not listed here.";
174
301
  const TOTAL_CEILING = 1500;
175
302
  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();
303
+ const render = (list) => ["## Memory", "", ...list.flatMap((section) => [`### ${section.heading}`, ...section.items.map((item) => item.line), ""]), footer].join("\n").trim();
177
304
  while (sections.length > 0) {
178
305
  const rendered = render(sections);
179
- if (estimateTokens(rendered) <= ceiling) return rendered;
306
+ if (estimateTokens(rendered) <= ceiling) {
307
+ const injectedIds = sections.flatMap((section) => section.items.map((item) => item.id).filter((id) => id !== void 0));
308
+ return { text: rendered, injectedIds };
309
+ }
180
310
  const last = sections[sections.length - 1];
181
311
  if (last.items.length > 0) {
182
312
  last.items.pop();
@@ -185,7 +315,45 @@ function buildInjectionSection(store, budget, projectKey) {
185
315
  sections.pop();
186
316
  }
187
317
  }
188
- return "";
318
+ return { text: "", injectedIds: [] };
319
+ }
320
+ function memoryOverview(store) {
321
+ const entries = store.loadEntries();
322
+ return [
323
+ `injection: ${readInjectSetting() ? "on" : "off"} (/tools/memory toggle)`,
324
+ `memory root: ${store.dir}`,
325
+ `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})`,
326
+ ...consumptionSummary(entries),
327
+ `journal days: ${store.listJournalDates().length}; snapshots: ${store.listSnapshots().length}`,
328
+ "subcommands: toggle | refresh | journal [date] | show <id> | diff <snapshotId> | rollback <snapshotId> | distill [date] | status"
329
+ ].join("\n");
330
+ }
331
+ function journalFor(store, date) {
332
+ const resolved = date ?? store.listJournalDates().at(-1);
333
+ if (!resolved) return "No journals yet.";
334
+ return store.readJournal(resolved) ?? `No journal for ${resolved}.`;
335
+ }
336
+ function refreshNow(ctx, hooks) {
337
+ if (!readInjectSetting()) {
338
+ return "Memory injection is off \u2014 nothing to refresh (toggle it on first).";
339
+ }
340
+ hooks.refreshInjection?.("explicit refresh");
341
+ ctx.ui.notify?.("Memory injection refreshed \u2014 the next turn rebuilds it from current memory (one cache re-write).", "info");
342
+ return "Memory injection will be rebuilt from current memory on the next turn (the prompt-prefix cache is invalidated once, by design).";
343
+ }
344
+ function toggleInjection(ctx, hooks) {
345
+ const next = !readInjectSetting();
346
+ if (!writeInjectSetting(next)) {
347
+ ctx.ui.notify?.("Memory: could not save settings.json; injection unchanged.", "error");
348
+ return "Could not save settings.json; injection unchanged.";
349
+ }
350
+ hooks.updateFooterTag?.();
351
+ hooks.refreshInjection?.("toggle");
352
+ ctx.ui.notify?.(
353
+ next ? "Memory injection on (effective next turn)" : "Memory injection off (effective next turn)",
354
+ "info"
355
+ );
356
+ 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
357
  }
190
358
  function renderSnapshotDiff(store, snapshotId) {
191
359
  const snapshotDir = path.join(store.dir, ".snapshots", snapshotId);
@@ -227,22 +395,43 @@ function renderSnapshotDiff(store, snapshotId) {
227
395
  return lines.length === 1 ? `${lines[0]}
228
396
  (no changes)` : lines.join("\n");
229
397
  }
230
- async function handleMemoryCommand(ctx, store, args) {
398
+ async function handleMemoryCommand(ctx, store, args, hooks = {}) {
231
399
  const [sub, ...rest] = args.trim().split(/\s+/);
232
400
  switch (sub) {
233
401
  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");
402
+ if (ctx.hasUI && ctx.ui?.select) {
403
+ const injecting = readInjectSetting();
404
+ const choice = await ctx.ui.select(
405
+ "Memory",
406
+ [
407
+ `Memory injection: ${injecting ? "ON" : "OFF"} \u2014 turn ${injecting ? "off" : "on"}`,
408
+ "Refresh injection now",
409
+ "Status overview",
410
+ "Latest journal",
411
+ "Distill yesterday"
412
+ ]
413
+ );
414
+ if (!choice) return "";
415
+ if (choice.startsWith("Memory injection:")) return toggleInjection(ctx, hooks);
416
+ if (choice === "Refresh injection now") return refreshNow(ctx, hooks);
417
+ if (choice === "Status overview") return memoryOverview(store);
418
+ if (choice === "Latest journal") return journalFor(store, void 0);
419
+ if (choice === "Distill yesterday") {
420
+ const date = yesterdayKey();
421
+ return triggerDistillWorker(store, date);
422
+ }
423
+ return "";
424
+ }
425
+ return memoryOverview(store);
426
+ }
427
+ case "toggle": {
428
+ return toggleInjection(ctx, hooks);
429
+ }
430
+ case "refresh": {
431
+ return refreshNow(ctx, hooks);
241
432
  }
242
433
  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}.`;
434
+ return journalFor(store, rest[0]);
246
435
  }
247
436
  case "show": {
248
437
  const entry = store.entryById(rest[0] ?? "");
@@ -256,8 +445,7 @@ async function handleMemoryCommand(ctx, store, args) {
256
445
  }
257
446
  case "distill": {
258
447
  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}` : ""}`;
448
+ return triggerDistillWorker(store, date);
261
449
  }
262
450
  case "diff": {
263
451
  const snapshotId = rest[0] ?? store.listSnapshots()[0];
@@ -269,55 +457,61 @@ async function handleMemoryCommand(ctx, store, args) {
269
457
  const days = Object.entries(state.runs).sort(([a], [b]) => a < b ? 1 : -1).slice(0, 5);
270
458
  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
459
  }
460
+ case "log": {
461
+ const log = readDistillWorkerLog(store.dir, 20);
462
+ return log.length === 0 ? `No worker log yet (${distillWorkerLogPath(store.dir)}).` : log.join("\n");
463
+ }
464
+ case "projects": {
465
+ return listProjectSurfaces(store, projectKeyForDir(ctx.cwd).key);
466
+ }
467
+ case "purge": {
468
+ const id = rest[0] ?? "";
469
+ const entry = store.entryById(id);
470
+ if (!entry) return "Entry not found.";
471
+ if (entry.retiredAt) return `Entry ${id} is already retired.`;
472
+ store.applyEntryPatch([{ op: "retire", id, reason: "purged via /tools/memory purge" }]);
473
+ return `Retired entry ${id} (${entry.kind}): ${entry.text.slice(0, 80)}`;
474
+ }
475
+ case "edit": {
476
+ if (!rest[0] || !rest[1]) return 'Usage: edit <id> "<new text>" (quote the text)';
477
+ const id = rest[0];
478
+ const entry = store.entryById(id);
479
+ if (!entry) return "Entry not found.";
480
+ let text = rest.slice(1).join(" ").slice(0, 240);
481
+ if (text.length >= 2 && (text.startsWith('"') && text.endsWith('"') || text.startsWith("'") && text.endsWith("'"))) {
482
+ text = text.slice(1, -1);
483
+ }
484
+ if (!text.trim()) return "New text must not be empty.";
485
+ store.applyEntryPatch([{ op: "update", id, text, evidence: entry.evidence }]);
486
+ return `Updated entry ${id}: ${text}`;
487
+ }
272
488
  default:
273
489
  return `Unknown subcommand: ${sub}`;
274
490
  }
275
491
  }
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
- );
492
+ function triggerDistillWorker(store, date) {
493
+ if (store.hasRun(date)) {
494
+ return `${date}: already distilled (checkpoint present). Use rollback first to re-run.`;
495
+ }
496
+ const spawned = spawnDistillWorker(store.dir, date);
497
+ if (!spawned) {
498
+ return `Could not spawn distillation worker (see ${distillWorkerLogPath(store.dir)}).`;
499
+ }
500
+ return `Distillation worker started for ${date} (detached; progress in ${distillWorkerLogPath(store.dir)}; /tools/memory status after it finishes).`;
304
501
  }
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)
502
+ function listProjectSurfaces(store, currentKey) {
503
+ const keys = store.listProjectKeys();
504
+ if (keys.length === 0) return "No project memory yet (distillation records project surfaces as projects accumulate).";
505
+ const lines = keys.map((key) => {
506
+ const entries = store.loadEntries().filter((entry) => entry.projectKey === key && !entry.retiredAt);
507
+ const meta = store.readProjectMeta(key);
508
+ const current = key === currentKey ? " \u2190 current" : "";
509
+ return `- ${key}: ${entries.length} entr${entries.length === 1 ? "y" : "ies"}${meta?.gitUrl ? ` (${meta.gitUrl})` : ""}${current}`;
318
510
  });
511
+ return ["Project memory surfaces:", ...lines].join("\n");
319
512
  }
320
513
  export {
321
514
  buildInjectionSection,
515
+ buildInjectionSectionWithIds,
322
516
  memoryExtension as default
323
517
  };
@@ -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-7FEPQHYX.js";
10
+ import "../../../chunks/chunk-3FRKOFSP.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-BUDXV3TR.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-7FEPQHYX.js";
18
+ import "../../../chunks/chunk-3FRKOFSP.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
 
@@ -42,7 +43,7 @@ function defaultReadProcessStartTime(pid) {
42
43
  "-Command",
43
44
  `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; if ($p) { $p.CreationDate.ToString('o') }`
44
45
  ],
45
- { encoding: "utf-8", timeout: 4e3 }
46
+ { encoding: "utf-8", timeout: 4e3, windowsHide: true }
46
47
  );
47
48
  const line = output.split(/\r?\n/).find((entry) => entry.trim().length > 0);
48
49
  return line?.trim();
@@ -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-7FEPQHYX.js";
12
+ import "../../../chunks/chunk-3FRKOFSP.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