@cydm/pie 2.7.20 → 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 (40) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +4 -3
  4. package/dist/builtin/extensions/cron/index.js +299 -39
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +315 -27
  7. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  8. package/dist/builtin/extensions/memory/index.js +515 -0
  9. package/dist/builtin/extensions/memory/package.json +19 -0
  10. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  11. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  12. package/dist/builtin/extensions/plan-mode/index.js +150 -82
  13. package/dist/builtin/extensions/subagent/README.md +315 -0
  14. package/dist/builtin/extensions/subagent/index.js +8 -5
  15. package/dist/builtin/extensions/todo/index.js +4 -3
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  18. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  19. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  22. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  23. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
  24. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  25. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
  27. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
  28. package/dist/chunks/chunk-ILUHTKF3.js +149 -0
  29. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
  30. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  31. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  32. package/dist/chunks/config-74AUVDLT.js +46 -0
  33. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  34. package/dist/chunks/src-66XSMIAM.js +134 -0
  35. package/dist/chunks/src-BPSQMSSC.js +431 -0
  36. package/dist/chunks/src-OPPYTPWG.js +285 -0
  37. package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
  38. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
  39. package/dist/cli.js +986 -2292
  40. package/package.json +3 -3
@@ -0,0 +1,515 @@
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";
7
+ import {
8
+ getConfigDir,
9
+ getSettingsPath
10
+ } from "../../../chunks/chunk-ILUHTKF3.js";
11
+ import {
12
+ DEFAULT_MEMORY_INJECTION_BUDGET,
13
+ MemoryStore,
14
+ consumptionSummary,
15
+ projectKeyForDir,
16
+ recordConsumption,
17
+ recordInjection,
18
+ saveAttestedEntry,
19
+ searchMemory,
20
+ todayKey
21
+ } from "../../../chunks/chunk-PK72LVWQ.js";
22
+ import "../../../chunks/chunk-RSL7E4R7.js";
23
+ import "../../../chunks/chunk-GH4VW2OT.js";
24
+ import "../../../chunks/chunk-3BC5KGDQ.js";
25
+ import {
26
+ Type
27
+ } from "../../../chunks/chunk-XXGYUYXI.js";
28
+ import "../../../chunks/chunk-LZQXQOPJ.js";
29
+
30
+ // builtin/extensions/memory/index.ts
31
+ import * as fs from "node:fs";
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
+ }
38
+ function estimateTokens(text) {
39
+ const cjk = (text.match(/[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/g) ?? []).length;
40
+ const rest = text.length - cjk;
41
+ return Math.ceil(cjk + rest / 4);
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
+ }
104
+ function memoryExtension(ctx) {
105
+ const memoryDir = path.join(getConfigDir(), "memory");
106
+ const store = new MemoryStore(memoryDir);
107
+ const budget = DEFAULT_MEMORY_INJECTION_BUDGET;
108
+ const project = projectKeyForDir(ctx.cwd);
109
+ let activeSessionId = null;
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
+ }
117
+ activeSessionId = event.sessionId;
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
+ });
155
+ ctx.on("before_agent_start", (event) => {
156
+ try {
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;
177
+ return { systemPrompt: `${event.baseSystemPrompt}
178
+
179
+ ${injectionMemo.text}` };
180
+ } catch (error) {
181
+ ctx.log(`[memory] injection failed (skipping): ${String(error)}`);
182
+ return {};
183
+ }
184
+ });
185
+ ctx.registerTool({
186
+ name: "memory_save",
187
+ description: 'Explicitly save a durable memory. HIGHEST-PRIORITY RULE: when the user explicitly asks to remember something (e.g. "\u8BB0\u4F4F\u2026", "from now on\u2026", "always\u2026"), you MUST call this tool \u2014 never claim you will remember without a successful call. Supersedes conflicting entries of the same kind automatically. After success, confirm briefly (e.g. "\u5DF2\u8BB0\u4F4F\uFF1A\u2026"). If this tool is unavailable, say the request only holds for the current session.',
188
+ parameters: Type.Object({
189
+ kind: Type.Union([
190
+ Type.Literal("preference"),
191
+ Type.Literal("fact"),
192
+ Type.Literal("project"),
193
+ Type.Literal("thread")
194
+ ]),
195
+ text: Type.String({ description: "The durable memory, <= 240 chars single line, in the user's dominant language", maxLength: 240 }),
196
+ quote: Type.String({ description: "The user's verbatim phrasing that attests this memory, <= 240 chars", maxLength: 240, minLength: 1 })
197
+ }),
198
+ async execute(args) {
199
+ const { ops, entryId } = saveAttestedEntry(store, {
200
+ kind: args.kind,
201
+ text: args.text,
202
+ quote: args.quote,
203
+ // No fabricated provenance: without a bound session the entry
204
+ // explicitly records that its source transcript is unknown.
205
+ sessionId: activeSessionId ?? "session-unbound",
206
+ cwd: ctx.cwd
207
+ });
208
+ const retired = ops.filter((op) => op.op === "retire").length;
209
+ return {
210
+ content: [
211
+ {
212
+ type: "text",
213
+ text: `Saved memory ${entryId}${retired > 0 ? ` (superseded ${retired} old entr${retired === 1 ? "y" : "ies"})` : ""}.`
214
+ }
215
+ ]
216
+ };
217
+ }
218
+ });
219
+ ctx.registerTool({
220
+ name: "memory_search",
221
+ description: "Search long-term memory (preferences, facts, threads, journals) with a literal query. Use before assuming user preferences or re-deriving project conclusions a past session already settled.",
222
+ parameters: Type.Object({
223
+ query: Type.String({ description: "Literal text to search for" }),
224
+ kind: Type.Optional(
225
+ Type.Union([
226
+ Type.Literal("preference"),
227
+ Type.Literal("fact"),
228
+ Type.Literal("project"),
229
+ Type.Literal("thread")
230
+ ])
231
+ ),
232
+ limit: Type.Optional(Type.Number({ minimum: 1, maximum: 50 }))
233
+ }),
234
+ async execute(args) {
235
+ const result = searchMemory(store, args.query, { kind: args.kind, limit: args.limit });
236
+ if (result.hits.length === 0) {
237
+ return { content: [{ type: "text", text: "No memory hits." }] };
238
+ }
239
+ const lines = result.hits.map((hit) => `- [${hit.kind}] ${hit.text} (${hit.path})`);
240
+ return {
241
+ content: [{ type: "text", text: lines.join("\n") + (result.truncated ? "\n(truncated)" : "") }]
242
+ };
243
+ }
244
+ });
245
+ ctx.registerCommand({
246
+ path: ["tools", "memory"],
247
+ description: "Memory menu: toggle injection / journal / status",
248
+ handler: async (commandCtx, args) => handleMemoryCommand(ctx, store, args ?? "", { updateFooterTag, refreshInjection })
249
+ });
250
+ }
251
+ function buildInjectionSection(store, budget, projectKey) {
252
+ return buildInjectionSectionWithIds(store, budget, projectKey).text;
253
+ }
254
+ function buildInjectionSectionWithIds(store, budget, projectKey) {
255
+ const entries = store.loadEntries();
256
+ const take = (surface, limit, extra) => {
257
+ const pool = entries.filter((entry) => {
258
+ if (surface === "project") return entry.kind === "project" && (!extra || extra(entry));
259
+ return entry.surface === surface && (!extra || extra(entry));
260
+ }).sort((a, b) => b.usageCount - a.usageCount || b.lastAccessed - a.lastAccessed);
261
+ const kept = [];
262
+ let used = 0;
263
+ for (const entry of pool) {
264
+ const cost = estimateTokens(`- ${entry.text}`);
265
+ if (used + cost > limit) continue;
266
+ kept.push({ line: `- ${entry.text}`, id: entry.id });
267
+ used += cost;
268
+ }
269
+ return kept;
270
+ };
271
+ const user = take("user", budget.user);
272
+ const memory = take("memory", budget.memory);
273
+ const threads = take("threads", budget.threads);
274
+ const projectLines = projectKey ? take("project", budget.project, (entry) => entry.projectKey === projectKey) : [];
275
+ const recentDates = store.listJournalDates().slice(-3);
276
+ let digestUsed = 0;
277
+ const digest = [];
278
+ for (const date of recentDates.reverse()) {
279
+ const journal = store.readJournal(date);
280
+ if (!journal) continue;
281
+ const firstParagraph = journal.split(/\n\s*\n/).slice(1).find((block) => block.trim().length > 0)?.trim() ?? "";
282
+ const snippet = firstParagraph.slice(0, 400);
283
+ const cost = estimateTokens(`- ${date}: ${snippet}`);
284
+ if (digestUsed + cost > budget.recentDigest) break;
285
+ digest.push(`- ${date}: ${snippet}`);
286
+ digestUsed += cost;
287
+ }
288
+ if (user.length === 0 && memory.length === 0 && threads.length === 0 && projectLines.length === 0 && digest.length === 0) {
289
+ return { text: "", injectedIds: [] };
290
+ }
291
+ const sections = [];
292
+ if (user.length > 0) sections.push({ heading: "User (stable preferences)", items: user });
293
+ if (projectLines.length > 0) sections.push({ heading: "This project", items: projectLines });
294
+ if (memory.length > 0) sections.push({ heading: "Durable facts", items: memory });
295
+ if (threads.length > 0) sections.push({ heading: "Open threads", items: threads });
296
+ const nonEmptyDigest = digest.filter((line) => !/:\s*$/.test(line));
297
+ if (nonEmptyDigest.length > 0) sections.push({ heading: "Recent days", items: nonEmptyDigest.map((line) => ({ line })) });
298
+ const footer = "When the user explicitly asks to remember something, call memory_save. Use memory_search for anything not listed here.";
299
+ const TOTAL_CEILING = 1500;
300
+ const ceiling = Math.min(TOTAL_CEILING, budget.user + budget.memory + budget.threads + budget.project + budget.recentDigest);
301
+ const render = (list) => ["## Memory", "", ...list.flatMap((section) => [`### ${section.heading}`, ...section.items.map((item) => item.line), ""]), footer].join("\n").trim();
302
+ while (sections.length > 0) {
303
+ const rendered = render(sections);
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
+ }
308
+ const last = sections[sections.length - 1];
309
+ if (last.items.length > 0) {
310
+ last.items.pop();
311
+ if (last.items.length === 0) sections.pop();
312
+ } else {
313
+ sections.pop();
314
+ }
315
+ }
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).";
355
+ }
356
+ function renderSnapshotDiff(store, snapshotId) {
357
+ const snapshotDir = path.join(store.dir, ".snapshots", snapshotId);
358
+ const entriesPath = path.join(snapshotDir, ".entries.json");
359
+ const tombstone = path.join(snapshotDir, ".entries.json.absent");
360
+ let before = [];
361
+ if (fs.existsSync(tombstone)) {
362
+ } else {
363
+ let raw;
364
+ try {
365
+ raw = fs.readFileSync(entriesPath, "utf8");
366
+ } catch {
367
+ return `Snapshot ${JSON.stringify(snapshotId)} not found (run /tools/memory rollback without args to list snapshots).`;
368
+ }
369
+ try {
370
+ const parsed = JSON.parse(raw);
371
+ if (!parsed || !Array.isArray(parsed.entries)) {
372
+ return `Snapshot ${snapshotId} has a corrupt entries record \u2014 inspect ${entriesPath}.`;
373
+ }
374
+ before = parsed.entries.filter(
375
+ (entry) => !!entry && typeof entry === "object" && typeof entry.id === "string"
376
+ );
377
+ } catch {
378
+ return `Snapshot ${snapshotId} has a corrupt entries file (invalid JSON) \u2014 inspect ${entriesPath}.`;
379
+ }
380
+ }
381
+ const after = store.loadEntries();
382
+ const beforeMap = new Map(before.map((entry) => [entry.id, entry]));
383
+ const afterMap = new Map(after.map((entry) => [entry.id, entry]));
384
+ const lines = [`diff vs ${snapshotId}:`];
385
+ for (const entry of afterMap.values()) {
386
+ const old = beforeMap.get(entry.id);
387
+ if (!old) lines.push(`+ [${entry.kind}] ${entry.text}`);
388
+ else if (old.text !== entry.text) lines.push(`~ [${entry.kind}] ${old.text} -> ${entry.text}`);
389
+ }
390
+ for (const entry of beforeMap.values()) {
391
+ if (!afterMap.has(entry.id)) lines.push(`- [${entry.kind}] ${entry.text} (retired)`);
392
+ }
393
+ return lines.length === 1 ? `${lines[0]}
394
+ (no changes)` : lines.join("\n");
395
+ }
396
+ async function handleMemoryCommand(ctx, store, args, hooks = {}) {
397
+ const [sub, ...rest] = args.trim().split(/\s+/);
398
+ switch (sub) {
399
+ case "": {
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);
430
+ }
431
+ case "journal": {
432
+ return journalFor(store, rest[0]);
433
+ }
434
+ case "show": {
435
+ const entry = store.entryById(rest[0] ?? "");
436
+ if (!entry) return "Entry not found.";
437
+ return JSON.stringify(entry, null, 2);
438
+ }
439
+ case "rollback": {
440
+ if (!rest[0]) return `snapshots: ${store.listSnapshots().slice(0, 10).join(", ") || "(none)"}`;
441
+ store.rollback(rest[0]);
442
+ return `Rolled back to ${rest[0]}.`;
443
+ }
444
+ case "distill": {
445
+ const date = rest[0] ?? todayKey(Date.now() - 24 * 60 * 60 * 1e3);
446
+ return triggerDistillWorker(store, date);
447
+ }
448
+ case "diff": {
449
+ const snapshotId = rest[0] ?? store.listSnapshots()[0];
450
+ if (!snapshotId) return "No snapshots yet.";
451
+ return renderSnapshotDiff(store, snapshotId);
452
+ }
453
+ case "status": {
454
+ const state = store.loadState();
455
+ const days = Object.entries(state.runs).sort(([a], [b]) => a < b ? 1 : -1).slice(0, 5);
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");
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
+ }
486
+ default:
487
+ return `Unknown subcommand: ${sub}`;
488
+ }
489
+ }
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).`;
499
+ }
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}`;
508
+ });
509
+ return ["Project memory surfaces:", ...lines].join("\n");
510
+ }
511
+ export {
512
+ buildInjectionSection,
513
+ buildInjectionSectionWithIds,
514
+ memoryExtension as default
515
+ };
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@pie/extension-memory",
3
+ "version": "1.0.0",
4
+ "description": "Session-derived memory: distillation, injection, attested saves",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "pie": {
8
+ "name": "memory",
9
+ "main": "index.js",
10
+ "defaultEnablement": false
11
+ },
12
+ "keywords": [
13
+ "pie",
14
+ "extension",
15
+ "memory"
16
+ ],
17
+ "author": "Pie Team",
18
+ "license": "MIT"
19
+ }
@@ -0,0 +1,21 @@
1
+ # pie-ipc
2
+
3
+ Experimental CLI-only local peer messaging on POSIX and verified Windows private local ACL paths. Enabled by default; no broker or core edits.
4
+
5
+ No configuration is required. By default IPC trusts authenticated local clients and auto-injects their messages into interactive sessions. To opt out, create `~/.pie/ipc.json` with `{ "enabled": false }`, then restart/reload. Optional settings, shown here with a restrictive delivery policy, are:
6
+
7
+ ```json
8
+ {
9
+ "displayName": "reviewer",
10
+ "allowPeers": [],
11
+ "autoInject": false
12
+ }
13
+ ```
14
+
15
+ Absent `allowPeers` defaults to `["*"]`, trusting authenticated local clients; an explicit empty array **denies** messages and bodies. `/tools/ipc allow <instance-id>` approves one peer for this runtime. `autoInject` defaults to `true`; set it to `false` for inbox + poll delivery. Unreadable config files disable IPC rather than selecting these defaults. Same-user processes are trusted, not isolated. Auto-injection is interactive-only; headless clients can send and wait without advertising.
16
+
17
+ Use `/tools/ipc peers`, `/tools/ipc status <peer>`, `/tools/ipc send <peer> <text>`, `/tools/ipc result <peer> [requestId]`, `/tools/ipc poll`, `/tools/ipc name`, `/tools/ipc mute [off]`, and `/tools/ipc allow <id|*>`. Only explicit `/tools/ipc poll` submits command output to the model; other commands notify the user. Changes from commands are ephemeral.
18
+
19
+ Tools: `ipc_list_peers`, `ipc_status`, `ipc_send`, `ipc_result`, `ipc_poll`. Every send exposes a requestId. Non-waiting requests can be polled with `ipc_result` through accepted/running/done or failed; omitting requestId lists recent results. Reads do not consume results. Results are session-scoped, bounded, retained in memory only, and unknown after eviction/restart. A receipt is not a result: waited results use the original authenticated socket after input consumption and execution settlement. Queued/muted input never receives unrelated turn output. Delivery is bounded, best-effort, not durable; uncertain busy followups are never automatically duplicated. Restart every peer after protocol changes; there is no compatibility layer. Windows uses native HANDLE-based ACL verification and atomic protected directory and temporary-file creation. Ancestors with public add-file/write-data, write-attributes, write-EA, delete or control grants are rejected (including standard ProgramData when it has these rights). No-delete handles prevent rename/delete; ACL checks, not a reparse lock, exclude untrusted in-place mutation. Unsafe profile/TEMP/drive ancestry fails closed without repair or insecure fallback; use an explicitly provisioned safe `PIE_IPC_CONFIG_DIR` if needed. Same-user isolation and the stale-advertisement/first-send unencrypted endpoint-identity limitation remain outside this guarantee; see the release checklist below.
20
+
21
+ See [the complete contract](../../../../../docs/pie-ipc.md) for configuration, HMAC/permissions, snapshot freshness, limits, recovery limitations, and reproducible tests including a checked-in two-process factory dogfood driver.
@@ -0,0 +1,70 @@
1
+ # Plan Mode Methodology
2
+
3
+ The runtime-mode injection carries the full behavior contract in a compact
4
+ form (discussion-first grilling + the MVP-ladder emit rules). This document
5
+ is the human-readable long form of the same contract — design notes and
6
+ reasoning, not a loadable pointer. It is deliberately **not** a registered
7
+ skill (D15): Plan-mode behavior must be deterministic, not trigger-guessed,
8
+ and non-plan sessions pay nothing for it.
9
+
10
+ ## The two phases
11
+
12
+ | Phase | Default? | Exit condition |
13
+ |---|---|---|
14
+ | **Discussion (grilling)** | yes | the user explicitly asks for the plan |
15
+ | **Proposal (emit)** | never spontaneous | user says “输出计划” / “give me the plan” / `/tools/plan/submit` |
16
+
17
+ The emit trigger is intent-based, tightened: only imperative asks-for-an-
18
+ artifact count (“输出/给出/整理成计划/submit”). **When unsure, ask back** —
19
+ one clarifying question beats an unwanted plan. `/tools/plan/submit [text]`
20
+ is the explicit escape hatch; its free text is additional context for the
21
+ proposal.
22
+
23
+ ## Discussion: grilling rounds
24
+
25
+ Interview the user relentlessly until shared understanding. Model the
26
+ discussion as a **design tree**: every decision branches into the decisions
27
+ that hang off it.
28
+
29
+ - **Round**: one message asking the whole **frontier** — every question whose
30
+ prerequisites are already settled. Never ask about something that depends
31
+ on an answer you haven't heard yet; that question belongs to a later round.
32
+ - Format every question as `❓ **Qn** - **<title>**: <body>` followed by
33
+ `➡️ <recommended answer>`, worded so "yes" accepts the recommendation.
34
+ - Recompute the frontier after each round: settled decisions push it outward.
35
+ - **Facts are your job, decisions are the user's.** Never ask the user
36
+ anything a read-only tool could answer; dispatch the lookup yourself and
37
+ let only downstream questions wait for it.
38
+ - When the user's wording collides with a settled term, stop and challenge it
39
+ immediately; capture resolved vocabulary in a `plan_scratch` glossary draft.
40
+ - The discussion is done when the frontier is empty — every branch has an
41
+ owner, nothing silently assumed.
42
+
43
+ ## Proposal: the MVP ladder
44
+
45
+ When the user asks for the plan, decompose into **MVPs** — each step is a
46
+ minimal verifiable increment that stands on the previous ones:
47
+
48
+ - **Small**: one independently shippable slice, not a phase of a slice.
49
+ - **Verifiable**: every step carries a `verify` criterion — ideally one
50
+ command or test name. No criterion, no step.
51
+ - **Stable foundation (ladder invariant)**: later steps build on earlier
52
+ steps' output; the ladder never revisits what an earlier step shipped.
53
+ - **Scoped**: every step lists `files` it intends to touch (append `(new)`
54
+ for paths to be created). Scope is advisory display for the user (D10) —
55
+ it shows size and understanding, it is not a write guard.
56
+ - Ladders run in execution order: one step at a time, verify, then `[DONE:n]`.
57
+ A failed verify stops the ladder: Retry / Revise / Abort — never Skip.
58
+
59
+ ## During execution
60
+
61
+ - Approved = the whole ladder executes in order, one step at a time.
62
+ Progress markers: `[DONE:n]`, plus `[VERIFIED:n]` for every step with a
63
+ verify criterion — the pair is the model-reported evidence that the check
64
+ held; a criterion-bearing `[DONE:n]` without `[VERIFIED:n]` leaves the step
65
+ open on purpose.
66
+ - On failure (or any time the user wants a change): `/tools/plan/revise`
67
+ suspends execution, re-enters read-only Plan mode, and carries the
68
+ completed prefix into the revised ladder automatically — completed steps
69
+ are never redone or dropped. The revised plan is emitted the same way as
70
+ any other: only when the user asks.