@cydm/pie 2.7.19 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/builtin/extensions/ask-user/README.md +117 -0
- package/dist/builtin/extensions/ask-user/index.js +3 -3
- package/dist/builtin/extensions/cron/index.js +166 -23
- package/dist/builtin/extensions/im-forward/README.md +297 -0
- package/dist/builtin/extensions/im-forward/index.js +319 -42
- package/dist/builtin/extensions/init/index.js +0 -6
- package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
- package/dist/builtin/extensions/memory/index.js +323 -0
- package/dist/builtin/extensions/memory/package.json +18 -0
- package/dist/builtin/extensions/pie-ipc/README.md +21 -0
- package/dist/builtin/extensions/pie-ipc/index.js +16 -16
- package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
- package/dist/builtin/extensions/plan-mode/index.js +149 -82
- package/dist/builtin/extensions/subagent/README.md +315 -0
- package/dist/builtin/extensions/subagent/index.js +7 -5
- package/dist/builtin/extensions/todo/index.js +3 -3
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
- package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
- package/dist/chunks/chunk-5353DEEC.js +130 -0
- package/dist/chunks/{chunk-2H2DD22Z.js → chunk-HGC25NYB.js} +1 -1
- package/dist/chunks/{chunk-X7UO6BA6.js → chunk-JNOFHHLZ.js} +156 -65
- package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-LJXHECZ7.js} +12183 -10951
- package/dist/chunks/{chunk-TGCI5M6R.js → chunk-NEES4EBX.js} +19 -141
- package/dist/chunks/{src-GX4UBAYF.js → src-5XOKRS6F.js} +2 -2
- package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-5SDHKKDB.js} +1 -1
- package/dist/cli.js +127 -96
- package/package.json +2 -2
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
getConfigDir,
|
|
4
|
+
getSessionsDir
|
|
5
|
+
} from "../../../chunks/chunk-5353DEEC.js";
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_MEMORY_INJECTION_BUDGET,
|
|
8
|
+
FileSessionStore,
|
|
9
|
+
MemoryStore,
|
|
10
|
+
projectKeyForDir,
|
|
11
|
+
runCatchUp,
|
|
12
|
+
runDistillation,
|
|
13
|
+
saveAttestedEntry,
|
|
14
|
+
searchMemory,
|
|
15
|
+
todayKey
|
|
16
|
+
} from "../../../chunks/chunk-LJXHECZ7.js";
|
|
17
|
+
import "../../../chunks/chunk-HGC25NYB.js";
|
|
18
|
+
import {
|
|
19
|
+
completeSimple
|
|
20
|
+
} from "../../../chunks/chunk-JNOFHHLZ.js";
|
|
21
|
+
import {
|
|
22
|
+
Type
|
|
23
|
+
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
24
|
+
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
25
|
+
|
|
26
|
+
// builtin/extensions/memory/index.ts
|
|
27
|
+
import * as fs from "node:fs";
|
|
28
|
+
import * as path from "node:path";
|
|
29
|
+
function estimateTokens(text) {
|
|
30
|
+
const cjk = (text.match(/[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/g) ?? []).length;
|
|
31
|
+
const rest = text.length - cjk;
|
|
32
|
+
return Math.ceil(cjk + rest / 4);
|
|
33
|
+
}
|
|
34
|
+
function memoryExtension(ctx) {
|
|
35
|
+
const memoryDir = path.join(getConfigDir(), "memory");
|
|
36
|
+
const store = new MemoryStore(memoryDir);
|
|
37
|
+
const budget = DEFAULT_MEMORY_INJECTION_BUDGET;
|
|
38
|
+
const project = projectKeyForDir(ctx.cwd);
|
|
39
|
+
let activeSessionId = null;
|
|
40
|
+
ctx.on("session:changed", (event) => {
|
|
41
|
+
activeSessionId = event.sessionId;
|
|
42
|
+
});
|
|
43
|
+
ctx.on("before_agent_start", (event) => {
|
|
44
|
+
try {
|
|
45
|
+
const section = buildInjectionSection(store, budget, project.key);
|
|
46
|
+
if (!section) return;
|
|
47
|
+
return { systemPrompt: `${event.baseSystemPrompt}
|
|
48
|
+
|
|
49
|
+
${section}` };
|
|
50
|
+
} catch (error) {
|
|
51
|
+
ctx.log(`[memory] injection failed (skipping): ${String(error)}`);
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
ctx.registerTool({
|
|
56
|
+
name: "memory_save",
|
|
57
|
+
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.',
|
|
58
|
+
parameters: Type.Object({
|
|
59
|
+
kind: Type.Union([
|
|
60
|
+
Type.Literal("preference"),
|
|
61
|
+
Type.Literal("fact"),
|
|
62
|
+
Type.Literal("project"),
|
|
63
|
+
Type.Literal("thread")
|
|
64
|
+
]),
|
|
65
|
+
text: Type.String({ description: "The durable memory, <= 240 chars single line, in the user's dominant language", maxLength: 240 }),
|
|
66
|
+
quote: Type.String({ description: "The user's verbatim phrasing that attests this memory, <= 240 chars", maxLength: 240, minLength: 1 })
|
|
67
|
+
}),
|
|
68
|
+
async execute(args) {
|
|
69
|
+
const { ops, entryId } = saveAttestedEntry(store, {
|
|
70
|
+
kind: args.kind,
|
|
71
|
+
text: args.text,
|
|
72
|
+
quote: args.quote,
|
|
73
|
+
// No fabricated provenance: without a bound session the entry
|
|
74
|
+
// explicitly records that its source transcript is unknown.
|
|
75
|
+
sessionId: activeSessionId ?? "session-unbound",
|
|
76
|
+
cwd: ctx.cwd
|
|
77
|
+
});
|
|
78
|
+
const retired = ops.filter((op) => op.op === "retire").length;
|
|
79
|
+
return {
|
|
80
|
+
content: [
|
|
81
|
+
{
|
|
82
|
+
type: "text",
|
|
83
|
+
text: `Saved memory ${entryId}${retired > 0 ? ` (superseded ${retired} old entr${retired === 1 ? "y" : "ies"})` : ""}.`
|
|
84
|
+
}
|
|
85
|
+
]
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
ctx.registerTool({
|
|
90
|
+
name: "memory_search",
|
|
91
|
+
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.",
|
|
92
|
+
parameters: Type.Object({
|
|
93
|
+
query: Type.String({ description: "Literal text to search for" }),
|
|
94
|
+
kind: Type.Optional(
|
|
95
|
+
Type.Union([
|
|
96
|
+
Type.Literal("preference"),
|
|
97
|
+
Type.Literal("fact"),
|
|
98
|
+
Type.Literal("project"),
|
|
99
|
+
Type.Literal("thread")
|
|
100
|
+
])
|
|
101
|
+
),
|
|
102
|
+
limit: Type.Optional(Type.Number({ minimum: 1, maximum: 50 }))
|
|
103
|
+
}),
|
|
104
|
+
async execute(args) {
|
|
105
|
+
const result = searchMemory(store, args.query, { kind: args.kind, limit: args.limit });
|
|
106
|
+
if (result.hits.length === 0) {
|
|
107
|
+
return { content: [{ type: "text", text: "No memory hits." }] };
|
|
108
|
+
}
|
|
109
|
+
const lines = result.hits.map((hit) => `- [${hit.kind}] ${hit.text} (${hit.path})`);
|
|
110
|
+
return {
|
|
111
|
+
content: [{ type: "text", text: lines.join("\n") + (result.truncated ? "\n(truncated)" : "") }]
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
ctx.registerCommand({
|
|
116
|
+
path: ["tools", "memory"],
|
|
117
|
+
description: "Memory governance: journal/show/diff/rollback/distill/status",
|
|
118
|
+
handler: async (_commandCtx, args) => handleMemoryCommand(ctx, store, args ?? "")
|
|
119
|
+
});
|
|
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
|
+
}
|
|
128
|
+
function buildInjectionSection(store, budget, projectKey) {
|
|
129
|
+
const lines = [];
|
|
130
|
+
const entries = store.loadEntries();
|
|
131
|
+
const take = (surface, limit, extra) => {
|
|
132
|
+
const pool = entries.filter((entry) => {
|
|
133
|
+
if (surface === "project") return entry.kind === "project" && (!extra || extra(entry));
|
|
134
|
+
return entry.surface === surface && (!extra || extra(entry));
|
|
135
|
+
}).sort((a, b) => b.usageCount - a.usageCount || b.lastAccessed - a.lastAccessed);
|
|
136
|
+
const kept = [];
|
|
137
|
+
let used = 0;
|
|
138
|
+
for (const entry of pool) {
|
|
139
|
+
const cost = estimateTokens(`- ${entry.text}`);
|
|
140
|
+
if (used + cost > limit) continue;
|
|
141
|
+
kept.push(`- ${entry.text}`);
|
|
142
|
+
used += cost;
|
|
143
|
+
}
|
|
144
|
+
return kept;
|
|
145
|
+
};
|
|
146
|
+
const user = take("user", budget.user);
|
|
147
|
+
const memory = take("memory", budget.memory);
|
|
148
|
+
const threads = take("threads", budget.threads);
|
|
149
|
+
const projectLines = projectKey ? take("project", budget.project, (entry) => entry.projectKey === projectKey) : [];
|
|
150
|
+
const recentDates = store.listJournalDates().slice(-3);
|
|
151
|
+
let digestUsed = 0;
|
|
152
|
+
const digest = [];
|
|
153
|
+
for (const date of recentDates.reverse()) {
|
|
154
|
+
const journal = store.readJournal(date);
|
|
155
|
+
if (!journal) continue;
|
|
156
|
+
const firstParagraph = journal.split(/\n\s*\n/).slice(1).find((block) => block.trim().length > 0)?.trim() ?? "";
|
|
157
|
+
const snippet = firstParagraph.slice(0, 400);
|
|
158
|
+
const cost = estimateTokens(`- ${date}: ${snippet}`);
|
|
159
|
+
if (digestUsed + cost > budget.recentDigest) break;
|
|
160
|
+
digest.push(`- ${date}: ${snippet}`);
|
|
161
|
+
digestUsed += cost;
|
|
162
|
+
}
|
|
163
|
+
if (user.length === 0 && memory.length === 0 && threads.length === 0 && projectLines.length === 0 && digest.length === 0) {
|
|
164
|
+
return "";
|
|
165
|
+
}
|
|
166
|
+
const sections = [];
|
|
167
|
+
if (user.length > 0) sections.push({ heading: "User (stable preferences)", items: user });
|
|
168
|
+
if (projectLines.length > 0) sections.push({ heading: "This project", items: projectLines });
|
|
169
|
+
if (memory.length > 0) sections.push({ heading: "Durable facts", items: memory });
|
|
170
|
+
if (threads.length > 0) sections.push({ heading: "Open threads", items: threads });
|
|
171
|
+
const nonEmptyDigest = digest.filter((line) => !/:\s*$/.test(line));
|
|
172
|
+
if (nonEmptyDigest.length > 0) sections.push({ heading: "Recent days", items: nonEmptyDigest });
|
|
173
|
+
const footer = "When the user explicitly asks to remember something, call memory_save. Use memory_search for anything not listed here.";
|
|
174
|
+
const TOTAL_CEILING = 1500;
|
|
175
|
+
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();
|
|
177
|
+
while (sections.length > 0) {
|
|
178
|
+
const rendered = render(sections);
|
|
179
|
+
if (estimateTokens(rendered) <= ceiling) return rendered;
|
|
180
|
+
const last = sections[sections.length - 1];
|
|
181
|
+
if (last.items.length > 0) {
|
|
182
|
+
last.items.pop();
|
|
183
|
+
if (last.items.length === 0) sections.pop();
|
|
184
|
+
} else {
|
|
185
|
+
sections.pop();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return "";
|
|
189
|
+
}
|
|
190
|
+
function renderSnapshotDiff(store, snapshotId) {
|
|
191
|
+
const snapshotDir = path.join(store.dir, ".snapshots", snapshotId);
|
|
192
|
+
const entriesPath = path.join(snapshotDir, ".entries.json");
|
|
193
|
+
const tombstone = path.join(snapshotDir, ".entries.json.absent");
|
|
194
|
+
let before = [];
|
|
195
|
+
if (fs.existsSync(tombstone)) {
|
|
196
|
+
} else {
|
|
197
|
+
let raw;
|
|
198
|
+
try {
|
|
199
|
+
raw = fs.readFileSync(entriesPath, "utf8");
|
|
200
|
+
} catch {
|
|
201
|
+
return `Snapshot ${JSON.stringify(snapshotId)} not found (run /tools/memory rollback without args to list snapshots).`;
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
const parsed = JSON.parse(raw);
|
|
205
|
+
if (!parsed || !Array.isArray(parsed.entries)) {
|
|
206
|
+
return `Snapshot ${snapshotId} has a corrupt entries record \u2014 inspect ${entriesPath}.`;
|
|
207
|
+
}
|
|
208
|
+
before = parsed.entries.filter(
|
|
209
|
+
(entry) => !!entry && typeof entry === "object" && typeof entry.id === "string"
|
|
210
|
+
);
|
|
211
|
+
} catch {
|
|
212
|
+
return `Snapshot ${snapshotId} has a corrupt entries file (invalid JSON) \u2014 inspect ${entriesPath}.`;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const after = store.loadEntries();
|
|
216
|
+
const beforeMap = new Map(before.map((entry) => [entry.id, entry]));
|
|
217
|
+
const afterMap = new Map(after.map((entry) => [entry.id, entry]));
|
|
218
|
+
const lines = [`diff vs ${snapshotId}:`];
|
|
219
|
+
for (const entry of afterMap.values()) {
|
|
220
|
+
const old = beforeMap.get(entry.id);
|
|
221
|
+
if (!old) lines.push(`+ [${entry.kind}] ${entry.text}`);
|
|
222
|
+
else if (old.text !== entry.text) lines.push(`~ [${entry.kind}] ${old.text} -> ${entry.text}`);
|
|
223
|
+
}
|
|
224
|
+
for (const entry of beforeMap.values()) {
|
|
225
|
+
if (!afterMap.has(entry.id)) lines.push(`- [${entry.kind}] ${entry.text} (retired)`);
|
|
226
|
+
}
|
|
227
|
+
return lines.length === 1 ? `${lines[0]}
|
|
228
|
+
(no changes)` : lines.join("\n");
|
|
229
|
+
}
|
|
230
|
+
async function handleMemoryCommand(ctx, store, args) {
|
|
231
|
+
const [sub, ...rest] = args.trim().split(/\s+/);
|
|
232
|
+
switch (sub) {
|
|
233
|
+
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");
|
|
241
|
+
}
|
|
242
|
+
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}.`;
|
|
246
|
+
}
|
|
247
|
+
case "show": {
|
|
248
|
+
const entry = store.entryById(rest[0] ?? "");
|
|
249
|
+
if (!entry) return "Entry not found.";
|
|
250
|
+
return JSON.stringify(entry, null, 2);
|
|
251
|
+
}
|
|
252
|
+
case "rollback": {
|
|
253
|
+
if (!rest[0]) return `snapshots: ${store.listSnapshots().slice(0, 10).join(", ") || "(none)"}`;
|
|
254
|
+
store.rollback(rest[0]);
|
|
255
|
+
return `Rolled back to ${rest[0]}.`;
|
|
256
|
+
}
|
|
257
|
+
case "distill": {
|
|
258
|
+
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}` : ""}`;
|
|
261
|
+
}
|
|
262
|
+
case "diff": {
|
|
263
|
+
const snapshotId = rest[0] ?? store.listSnapshots()[0];
|
|
264
|
+
if (!snapshotId) return "No snapshots yet.";
|
|
265
|
+
return renderSnapshotDiff(store, snapshotId);
|
|
266
|
+
}
|
|
267
|
+
case "status": {
|
|
268
|
+
const state = store.loadState();
|
|
269
|
+
const days = Object.entries(state.runs).sort(([a], [b]) => a < b ? 1 : -1).slice(0, 5);
|
|
270
|
+
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
|
+
}
|
|
272
|
+
default:
|
|
273
|
+
return `Unknown subcommand: ${sub}`;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
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
|
+
);
|
|
304
|
+
}
|
|
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)
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
export {
|
|
321
|
+
buildInjectionSection,
|
|
322
|
+
memoryExtension as default
|
|
323
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
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
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"pie",
|
|
13
|
+
"extension",
|
|
14
|
+
"memory"
|
|
15
|
+
],
|
|
16
|
+
"author": "Pie Team",
|
|
17
|
+
"license": "MIT"
|
|
18
|
+
}
|
|
@@ -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.
|
|
@@ -1116,7 +1116,7 @@ var InboundDelivery = class {
|
|
|
1116
1116
|
verifyDeadlineMs;
|
|
1117
1117
|
/** Degraded = autoInject force-disabled after repeated delivery misses. */
|
|
1118
1118
|
degraded = false;
|
|
1119
|
-
/** Counters surfaced by /ipc status. */
|
|
1119
|
+
/** Counters surfaced by /tools/ipc status. */
|
|
1120
1120
|
counters = { injected: 0, queued: 0, dropped: 0, denied: 0, degradedAt: 0, recovered: 0 };
|
|
1121
1121
|
get effectiveAutoInject() {
|
|
1122
1122
|
return this.autoInject && !this.degraded;
|
|
@@ -1143,7 +1143,7 @@ var InboundDelivery = class {
|
|
|
1143
1143
|
}
|
|
1144
1144
|
if (!this.options.allowPolicy.allows(envelope.from)) {
|
|
1145
1145
|
this.counters.denied += 1;
|
|
1146
|
-
this.host.notify?.(`pie-ipc: message from unapproved peer ${peerLabel(envelope.from, displayName)} \u2014 run /ipc allow`, "warning");
|
|
1146
|
+
this.host.notify?.(`pie-ipc: message from unapproved peer ${peerLabel(envelope.from, displayName)} \u2014 run /tools/ipc allow`, "warning");
|
|
1147
1147
|
return "denied";
|
|
1148
1148
|
}
|
|
1149
1149
|
const label = peerLabel(envelope.from, displayName);
|
|
@@ -1235,7 +1235,7 @@ var InboundDelivery = class {
|
|
|
1235
1235
|
this.degraded = true;
|
|
1236
1236
|
this.counters.degradedAt = Date.now();
|
|
1237
1237
|
this.host.notify?.(
|
|
1238
|
-
`pie-ipc: injected messages stopped landing ${this.consecutiveMisses}x \u2014 auto-inject disabled, messages now wait in the inbox (/ipc poll)`,
|
|
1238
|
+
`pie-ipc: injected messages stopped landing ${this.consecutiveMisses}x \u2014 auto-inject disabled, messages now wait in the inbox (/tools/ipc poll)`,
|
|
1239
1239
|
"warning"
|
|
1240
1240
|
);
|
|
1241
1241
|
}
|
|
@@ -1279,7 +1279,7 @@ var InboundDelivery = class {
|
|
|
1279
1279
|
const suffix = this.degraded ? " (degraded)" : "";
|
|
1280
1280
|
this.host.setStatus("pie-ipc", `ipc inbox ${this.inbox.length}${suffix}`);
|
|
1281
1281
|
} else if (this.degraded) {
|
|
1282
|
-
this.host.setStatus("pie-ipc", "ipc auto-inject degraded; /ipc poll");
|
|
1282
|
+
this.host.setStatus("pie-ipc", "ipc auto-inject degraded; /tools/ipc poll");
|
|
1283
1283
|
} else {
|
|
1284
1284
|
this.host.setStatus("pie-ipc", void 0);
|
|
1285
1285
|
}
|
|
@@ -1540,7 +1540,7 @@ var Runtime = class {
|
|
|
1540
1540
|
transport = null;
|
|
1541
1541
|
delivery = null;
|
|
1542
1542
|
projection;
|
|
1543
|
-
/** Shared allow policy: /ipc allow affects delivery AND state.get gates. */
|
|
1543
|
+
/** Shared allow policy: /tools/ipc allow affects delivery AND state.get gates. */
|
|
1544
1544
|
allowPolicy;
|
|
1545
1545
|
/** Inbound messages we accepted for a turn; answered on turn settle. */
|
|
1546
1546
|
awaitingReply = /* @__PURE__ */ new Map();
|
|
@@ -1691,7 +1691,7 @@ var Runtime = class {
|
|
|
1691
1691
|
}
|
|
1692
1692
|
if (!this.allowPolicy.allows(envelope.from)) {
|
|
1693
1693
|
this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
|
|
1694
|
-
this.finishReply(deliveryId, "denied: not on this peer's allow list (/ipc allow)");
|
|
1694
|
+
this.finishReply(deliveryId, "denied: not on this peer's allow list (/tools/ipc allow)");
|
|
1695
1695
|
if (!envelope.waitMs) reply("result", "denied: not allowed");
|
|
1696
1696
|
return;
|
|
1697
1697
|
}
|
|
@@ -1699,7 +1699,7 @@ var Runtime = class {
|
|
|
1699
1699
|
const decision = this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
|
|
1700
1700
|
if (decision === "denied") {
|
|
1701
1701
|
this.results.remove(deliveryId);
|
|
1702
|
-
this.finishReply(deliveryId, "denied: not on this peer's allow list (/ipc allow)");
|
|
1702
|
+
this.finishReply(deliveryId, "denied: not on this peer's allow list (/tools/ipc allow)");
|
|
1703
1703
|
if (!envelope.waitMs) reply("result", "denied: not allowed");
|
|
1704
1704
|
return;
|
|
1705
1705
|
}
|
|
@@ -1953,7 +1953,7 @@ ${message.text}`).join("\n---\n");
|
|
|
1953
1953
|
}
|
|
1954
1954
|
return text;
|
|
1955
1955
|
}
|
|
1956
|
-
/** /ipc send: deliver text, then surface the result without waiting. */
|
|
1956
|
+
/** /tools/ipc send: deliver text, then surface the result without waiting. */
|
|
1957
1957
|
async drainReplyAfterSend(peerRef, text) {
|
|
1958
1958
|
const result = await this.sendToPeer(peerRef, text, false, 0, { toolCallId: "ipc-command", cwd: this.ctx.cwd, log: () => {
|
|
1959
1959
|
}, reportProgress: () => {
|
|
@@ -2157,8 +2157,8 @@ function pieIpcExtension(ctx) {
|
|
|
2157
2157
|
execute: async (args) => ({ content: [{ type: "text", text: runtime.drainInbox(args.limit ?? 20) }] })
|
|
2158
2158
|
});
|
|
2159
2159
|
ctx.registerCommand({
|
|
2160
|
-
path: ["ipc"],
|
|
2161
|
-
description: "Pie IPC peers: /ipc peers|send|result|poll|status|name|mute|allow",
|
|
2160
|
+
path: ["tools", "ipc"],
|
|
2161
|
+
description: "Pie IPC peers: /tools/ipc peers|send|result|poll|status|name|mute|allow",
|
|
2162
2162
|
handler: async (_extensionCtx, args) => {
|
|
2163
2163
|
const [sub, ...rest] = (args ?? "").trim().split(/\s+/);
|
|
2164
2164
|
const mutations = runtime.mutations();
|
|
@@ -2170,12 +2170,12 @@ function pieIpcExtension(ctx) {
|
|
|
2170
2170
|
return await runtime.listPeers();
|
|
2171
2171
|
case "send": {
|
|
2172
2172
|
const [peerRef, ...words] = rest;
|
|
2173
|
-
if (!peerRef || words.length === 0) return "Usage: /ipc send <peer> <text>";
|
|
2173
|
+
if (!peerRef || words.length === 0) return "Usage: /tools/ipc send <peer> <text>";
|
|
2174
2174
|
return runtime.drainReplyAfterSend(peerRef, words.join(" "));
|
|
2175
2175
|
}
|
|
2176
2176
|
case "result": {
|
|
2177
2177
|
const [peerRef, requestId] = rest;
|
|
2178
|
-
if (!peerRef) return "Usage: /ipc result <peer> [requestId]";
|
|
2178
|
+
if (!peerRef) return "Usage: /tools/ipc result <peer> [requestId]";
|
|
2179
2179
|
const result = await runtime.resultOf(peerRef, requestId, 5, { toolCallId: "ipc-command", cwd: _extensionCtx.cwd, log: () => {
|
|
2180
2180
|
}, reportProgress: () => {
|
|
2181
2181
|
} });
|
|
@@ -2185,19 +2185,19 @@ function pieIpcExtension(ctx) {
|
|
|
2185
2185
|
return runtime.drainInbox(20, false);
|
|
2186
2186
|
case "status": {
|
|
2187
2187
|
const peerRef = rest[0];
|
|
2188
|
-
if (!peerRef) return "Usage: /ipc status <peer>";
|
|
2188
|
+
if (!peerRef) return "Usage: /tools/ipc status <peer>";
|
|
2189
2189
|
return await runtime.statusOf(peerRef);
|
|
2190
2190
|
}
|
|
2191
2191
|
case "name":
|
|
2192
2192
|
if (!rest[0]) return `Current name: ${runtime.displayName}
|
|
2193
|
-
Usage: /ipc name <new-name>`;
|
|
2193
|
+
Usage: /tools/ipc name <new-name>`;
|
|
2194
2194
|
mutations.setDisplayName(rest[0]);
|
|
2195
2195
|
return `Display name set to: ${rest[0]}`;
|
|
2196
2196
|
case "mute":
|
|
2197
2197
|
mutations.mute(rest[0] !== "off");
|
|
2198
2198
|
return rest[0] === "off" ? "Auto-inject re-enabled (inbox still available via ipc_poll)." : "Muted: inbound messages wait in the inbox (ipc_poll).";
|
|
2199
2199
|
case "allow": {
|
|
2200
|
-
if (!rest[0]) return "Usage: /ipc allow <instance-id>";
|
|
2200
|
+
if (!rest[0]) return "Usage: /tools/ipc allow <instance-id>";
|
|
2201
2201
|
const target = runtime.resolvePeer(rest[0]);
|
|
2202
2202
|
const id = target?.instanceId ?? rest[0];
|
|
2203
2203
|
if (id !== "*" && !/^pie-[a-z0-9]{12}$/.test(id)) return "Invalid instance id.";
|
|
@@ -2205,7 +2205,7 @@ Usage: /ipc name <new-name>`;
|
|
|
2205
2205
|
return `Allowed peer: ${id}`;
|
|
2206
2206
|
}
|
|
2207
2207
|
default:
|
|
2208
|
-
return "Usage: /ipc peers|send <peer> <text>|result <peer> [requestId]|poll|status <peer>|name <name>|mute [off]|allow <id>";
|
|
2208
|
+
return "Usage: /tools/ipc peers|send <peer> <text>|result <peer> [requestId]|poll|status <peer>|name <name>|mute [off]|allow <id>";
|
|
2209
2209
|
}
|
|
2210
2210
|
};
|
|
2211
2211
|
const output = await run();
|
|
@@ -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.
|