@cydm/pie 2.8.1 → 4.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.
- package/dist/builtin/extensions/ask-user/index.js +8 -4
- package/dist/builtin/extensions/changelog/index.js +2 -2
- package/dist/builtin/extensions/cron/index.js +295 -33
- package/dist/builtin/extensions/document-attachments/index.js +1 -1
- package/dist/builtin/extensions/herdr-agent-state/index.js +2 -2
- package/dist/builtin/extensions/im-forward/README.md +20 -5
- package/dist/builtin/extensions/im-forward/index.js +415 -142
- package/dist/builtin/extensions/memory/index.js +83 -30
- package/dist/builtin/extensions/pie-ipc/README.md +2 -2
- package/dist/builtin/extensions/pie-ipc/index.js +269 -30
- package/dist/builtin/extensions/pie-proc/README.md +93 -0
- package/dist/builtin/extensions/pie-proc/index.js +630 -0
- package/dist/builtin/extensions/pie-proc/package.json +11 -0
- package/dist/builtin/extensions/plan-mode/index.js +4 -4
- package/dist/builtin/extensions/subagent/index.js +6 -6
- package/dist/builtin/extensions/todo/index.js +4 -4
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +106 -2
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +1 -0
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/{chunk-BNSAEVRT.js → chunk-WOGAQ4P5.js} +2 -2
- package/dist/builtin/skills/chrome-devtools-axi/{cli-AO2ZTPRM.js → cli-CHC7XYFU.js} +27 -3
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +2 -2
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-cli.js +1 -0
- package/dist/builtin/skills/computer-use-axi/scripts/setup-helper.mjs +6 -2
- package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +179 -9
- package/dist/chunks/{chunk-PK72LVWQ.js → chunk-FDLLNPIE.js} +143 -53
- package/dist/chunks/{chunk-3BC5KGDQ.js → chunk-JQRZLVPY.js} +12 -1
- package/dist/chunks/{chunk-GH4VW2OT.js → chunk-NCP264ZE.js} +8 -2
- package/dist/chunks/{chunk-YRR6C43W.js → chunk-QX6WS73C.js} +1 -1
- package/dist/chunks/{chunk-3NHP7HK5.js → chunk-TDKNKNPL.js} +6 -5
- package/dist/chunks/{chunk-GDIYSMTS.js → chunk-UOZHQ73X.js} +25 -17
- package/dist/chunks/{chunk-RSL7E4R7.js → chunk-WK4N5HT5.js} +66 -23
- package/dist/chunks/chunk-X6LBWHK3.js +37 -0
- package/dist/chunks/concierge-cli-PIOGXKDR.js +939 -0
- package/dist/chunks/{model-registry-LI5THXV4.js → model-registry-YA6U366L.js} +2 -2
- package/dist/chunks/{src-BPSQMSSC.js → src-AB7PLORG.js} +6 -4
- package/dist/chunks/{src-YG5M2H44.js → src-ODLT57PQ.js} +2 -2
- package/dist/chunks/{src-66XSMIAM.js → src-XSLD2IQ2.js} +1 -1
- package/dist/chunks/{src-OPPYTPWG.js → src-ZZZO4HSR.js} +11 -3
- package/dist/chunks/{test-stream-JBWXKOQA.js → test-stream-GIUD5JWS.js} +1 -1
- package/dist/cli.js +1433 -235
- package/package.json +105 -105
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
readProcessCommandLine
|
|
4
|
+
} from "../../../chunks/chunk-X6LBWHK3.js";
|
|
5
|
+
import {
|
|
6
|
+
Type
|
|
7
|
+
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
8
|
+
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
9
|
+
|
|
10
|
+
// builtin/extensions/pie-proc/index.ts
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import * as os from "node:os";
|
|
16
|
+
import * as path from "node:path";
|
|
17
|
+
var require_ = createRequire(import.meta.url);
|
|
18
|
+
var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: 5, killGraceMs: 15e3, defaultTtlMs: 0 };
|
|
19
|
+
var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
|
|
20
|
+
var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
|
|
21
|
+
function configDirRoot() {
|
|
22
|
+
const env = process.env.PIE_CODING_AGENT_DIR;
|
|
23
|
+
if (!env) return path.join(os.homedir(), ".pie");
|
|
24
|
+
return path.resolve(expandTilde(env));
|
|
25
|
+
}
|
|
26
|
+
function expandTilde(p) {
|
|
27
|
+
return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
|
|
28
|
+
}
|
|
29
|
+
function readConfig() {
|
|
30
|
+
const file = path.join(configDirRoot(), "pie-proc.json");
|
|
31
|
+
try {
|
|
32
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
33
|
+
return {
|
|
34
|
+
allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
|
|
35
|
+
maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
|
|
36
|
+
killGraceMs: typeof raw.killGraceMs === "number" && raw.killGraceMs >= 1e3 ? raw.killGraceMs : DEFAULT_CONFIG.killGraceMs,
|
|
37
|
+
defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? raw.defaultTtlMs : DEFAULT_CONFIG.defaultTtlMs
|
|
38
|
+
};
|
|
39
|
+
} catch {
|
|
40
|
+
return { ...DEFAULT_CONFIG };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function pieProcDir() {
|
|
44
|
+
return path.join(configDirRoot(), "pie-proc");
|
|
45
|
+
}
|
|
46
|
+
function registryFile() {
|
|
47
|
+
return path.join(pieProcDir(), "workers.json");
|
|
48
|
+
}
|
|
49
|
+
function revisionFile(n) {
|
|
50
|
+
return path.join(pieProcDir(), `workers.r${n}.json`);
|
|
51
|
+
}
|
|
52
|
+
function parseRegistry(rawText, file, revision) {
|
|
53
|
+
let raw;
|
|
54
|
+
try {
|
|
55
|
+
raw = JSON.parse(rawText);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
throw new Error(`pie-proc registry unreadable at ${file}: ${error instanceof Error ? error.message : String(error)}; repair or remove it manually`);
|
|
58
|
+
}
|
|
59
|
+
const parsed = raw;
|
|
60
|
+
const workers = parsed.workers;
|
|
61
|
+
if (!Array.isArray(workers)) throw new Error(`pie-proc registry malformed at ${file}: workers must be an array`);
|
|
62
|
+
if (typeof parsed.revision === "number" && parsed.revision !== revision) {
|
|
63
|
+
throw new Error(`pie-proc registry revision mismatch at ${file} (content ${parsed.revision}, name ${revision}); repair or remove it manually`);
|
|
64
|
+
}
|
|
65
|
+
if (parsed.version !== 2 && workers.length > 0) {
|
|
66
|
+
const hasV1 = workers.some((w) => typeof w?.generation !== "string");
|
|
67
|
+
if (hasV1) {
|
|
68
|
+
throw new Error(`pie-proc registry at ${file} contains v1 records without generation identity; refusing to operate (possible live workers). Manually verify no pie-proc workers run, then remove the file.`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
revision,
|
|
73
|
+
workers: workers.filter((w) => {
|
|
74
|
+
const r = w;
|
|
75
|
+
return typeof r?.name === "string" && typeof r?.pid === "number" && typeof r?.sessionId === "string" && typeof r?.generation === "string";
|
|
76
|
+
})
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function latestRevisionOnDisk() {
|
|
80
|
+
let max = 0;
|
|
81
|
+
try {
|
|
82
|
+
for (const entry of fs.readdirSync(pieProcDir())) {
|
|
83
|
+
const match = /^workers\.r(\d+)\.json$/.exec(entry);
|
|
84
|
+
if (match) max = Math.max(max, Number(match[1]));
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
}
|
|
88
|
+
return max;
|
|
89
|
+
}
|
|
90
|
+
function readRegistryUncached() {
|
|
91
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
92
|
+
const latest = latestRevisionOnDisk();
|
|
93
|
+
if (latest > 0) {
|
|
94
|
+
const file2 = revisionFile(latest);
|
|
95
|
+
try {
|
|
96
|
+
return parseRegistry(fs.readFileSync(file2, "utf8"), file2, latest);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error.code === "ENOENT") continue;
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const file = registryFile();
|
|
103
|
+
try {
|
|
104
|
+
return parseRegistry(fs.readFileSync(file, "utf8"), file, 0);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (error.code === "ENOENT") return { revision: 0, workers: [] };
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
throw new Error("pie-proc registry read kept racing a concurrent writer; retry the operation");
|
|
111
|
+
}
|
|
112
|
+
function compactRevisions(_current) {
|
|
113
|
+
}
|
|
114
|
+
function casRegistry(mutate) {
|
|
115
|
+
fs.mkdirSync(pieProcDir(), { recursive: true });
|
|
116
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
117
|
+
const snapshot = readRegistryUncached();
|
|
118
|
+
const outcome = mutate(snapshot);
|
|
119
|
+
if ("abort" in outcome) {
|
|
120
|
+
if ("error" in outcome.abort) throw outcome.abort.error;
|
|
121
|
+
return outcome.abort.value;
|
|
122
|
+
}
|
|
123
|
+
const nextRevision = snapshot.revision + 1;
|
|
124
|
+
const target = revisionFile(nextRevision);
|
|
125
|
+
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}-${attempt}.tmp`;
|
|
126
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
|
|
127
|
+
if (latestRevisionOnDisk() > snapshot.revision) {
|
|
128
|
+
try {
|
|
129
|
+
fs.rmSync(tmp, { force: true });
|
|
130
|
+
} catch {
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
fs.linkSync(tmp, target);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
try {
|
|
138
|
+
fs.rmSync(tmp, { force: true });
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
if (error.code === "EEXIST") continue;
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
fs.rmSync(tmp, { force: true });
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
compactRevisions(nextRevision);
|
|
149
|
+
return outcome.result;
|
|
150
|
+
}
|
|
151
|
+
throw new Error("pie-proc registry contention: CAS retries exhausted (a concurrent writer holds the registry)");
|
|
152
|
+
}
|
|
153
|
+
function updateRegistry(mutate) {
|
|
154
|
+
return casRegistry(mutate);
|
|
155
|
+
}
|
|
156
|
+
function workerLiveness(record) {
|
|
157
|
+
if (record.pid === 0) return "dead";
|
|
158
|
+
try {
|
|
159
|
+
process.kill(record.pid, 0);
|
|
160
|
+
} catch {
|
|
161
|
+
return "dead";
|
|
162
|
+
}
|
|
163
|
+
const cmd = readProcessCommandLine(record.pid);
|
|
164
|
+
if (cmd === void 0) return "unknown";
|
|
165
|
+
return cmd.includes(record.sessionId) ? "alive" : "dead";
|
|
166
|
+
}
|
|
167
|
+
function canonicalDir(dir) {
|
|
168
|
+
const resolved = path.resolve(expandTilde(dir));
|
|
169
|
+
const real = fs.realpathSync(resolved);
|
|
170
|
+
const stat = fs.statSync(real);
|
|
171
|
+
if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
|
|
172
|
+
return real;
|
|
173
|
+
}
|
|
174
|
+
function cwdAllowedOrThrow(cwd, allow) {
|
|
175
|
+
const canonical = canonicalDir(cwd);
|
|
176
|
+
for (const root of allow) {
|
|
177
|
+
try {
|
|
178
|
+
const canonicalRoot = canonicalDir(root);
|
|
179
|
+
if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path.sep)) return canonical;
|
|
180
|
+
} catch {
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
throw new Error(`cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots; edit ${path.join(configDirRoot(), "pie-proc.json")}`);
|
|
184
|
+
}
|
|
185
|
+
function safeName(name) {
|
|
186
|
+
return /^[a-z0-9][a-z0-9-_]{0,47}$/i.test(name);
|
|
187
|
+
}
|
|
188
|
+
function sanitizeImForward(raw) {
|
|
189
|
+
if (raw === void 0) return void 0;
|
|
190
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("imForward must be an object");
|
|
191
|
+
const source = raw;
|
|
192
|
+
const out = {};
|
|
193
|
+
for (const [key, value] of Object.entries(source)) {
|
|
194
|
+
if (!IM_FORWARD_ALLOWED_KEYS.has(key)) {
|
|
195
|
+
throw new Error(`imForward field "${key}" is not allowed (executable/path selection is operator-only config). Allowed: ${[...IM_FORWARD_ALLOWED_KEYS].join(", ")}`);
|
|
196
|
+
}
|
|
197
|
+
out[key] = value;
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
function cliEntry() {
|
|
202
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
203
|
+
for (const rel of ["../../../src/cli.ts", "../../../cli.js"]) {
|
|
204
|
+
const candidate = path.resolve(moduleDir, rel);
|
|
205
|
+
try {
|
|
206
|
+
const real = fs.realpathSync(candidate);
|
|
207
|
+
if (fs.statSync(real).isFile()) return real;
|
|
208
|
+
} catch {
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return "";
|
|
212
|
+
}
|
|
213
|
+
function loaderArgs() {
|
|
214
|
+
for (let i = 0; i < process.execArgv.length - 1; i += 1) {
|
|
215
|
+
if (process.execArgv[i] === "--import") {
|
|
216
|
+
const target = process.execArgv[i + 1];
|
|
217
|
+
if (target && !path.isAbsolute(target) && !target.startsWith("file:")) {
|
|
218
|
+
try {
|
|
219
|
+
const pkgRoot = path.dirname(require_.resolve(`${target}/package.json`, { paths: [path.dirname(cliEntry())] }));
|
|
220
|
+
return ["--import", path.join(pkgRoot, "dist", "loader.mjs")];
|
|
221
|
+
} catch {
|
|
222
|
+
return [];
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return ["--import", target];
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
function logDir() {
|
|
231
|
+
return path.join(pieProcDir(), "logs");
|
|
232
|
+
}
|
|
233
|
+
var toolText = (text, isError = false) => ({ content: [{ type: "text", text }], details: {}, ...isError ? { isError: true } : {} });
|
|
234
|
+
function pieProc(ctx) {
|
|
235
|
+
if (!ctx.capabilities.longLived) {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const config = readConfig();
|
|
239
|
+
const abortedGenerations = /* @__PURE__ */ new Set();
|
|
240
|
+
const observeActivity = (record) => {
|
|
241
|
+
const logTime = (() => {
|
|
242
|
+
try {
|
|
243
|
+
return fs.statSync(path.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
|
|
244
|
+
} catch {
|
|
245
|
+
return record.lastActiveAt;
|
|
246
|
+
}
|
|
247
|
+
})();
|
|
248
|
+
if (record.pid === 0) return logTime;
|
|
249
|
+
const statusRoot = path.join(path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
|
|
250
|
+
try {
|
|
251
|
+
for (const file of fs.readdirSync(statusRoot)) {
|
|
252
|
+
if (!file.endsWith(".json")) continue;
|
|
253
|
+
try {
|
|
254
|
+
const status = JSON.parse(fs.readFileSync(path.join(statusRoot, file), "utf8"));
|
|
255
|
+
if (status.sessionId === record.sessionId && status.state === "working") return Date.now();
|
|
256
|
+
} catch {
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
} catch {
|
|
260
|
+
}
|
|
261
|
+
return logTime;
|
|
262
|
+
};
|
|
263
|
+
const persistActivity = (record, at) => {
|
|
264
|
+
try {
|
|
265
|
+
updateRegistry((snap) => ({
|
|
266
|
+
next: snap.workers.map((w) => w.generation === record.generation && at > w.lastActiveAt ? { ...w, lastActiveAt: at } : w),
|
|
267
|
+
result: void 0
|
|
268
|
+
}));
|
|
269
|
+
} catch {
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const releaseReservation = (generation) => {
|
|
273
|
+
try {
|
|
274
|
+
updateRegistry((snap) => ({
|
|
275
|
+
next: snap.workers.filter((w) => !(w.pid === 0 && w.generation === generation)),
|
|
276
|
+
result: void 0
|
|
277
|
+
}));
|
|
278
|
+
} catch (error) {
|
|
279
|
+
abortedGenerations.add(generation);
|
|
280
|
+
ctx.log(`pie-proc: reservation release for gen ${generation} failed (${error instanceof Error ? error.message : String(error)}); sweep will retry`);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
const sweep = () => {
|
|
284
|
+
try {
|
|
285
|
+
if (abortedGenerations.size > 0) {
|
|
286
|
+
for (const generation of [...abortedGenerations]) {
|
|
287
|
+
try {
|
|
288
|
+
const stillPending = readRegistryUncached().workers.some((w) => w.pid === 0 && w.generation === generation);
|
|
289
|
+
if (stillPending) {
|
|
290
|
+
updateRegistry((snap) => ({
|
|
291
|
+
next: snap.workers.filter((w) => !(w.pid === 0 && w.generation === generation)),
|
|
292
|
+
result: void 0
|
|
293
|
+
}));
|
|
294
|
+
}
|
|
295
|
+
abortedGenerations.delete(generation);
|
|
296
|
+
} catch {
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
for (const w of readRegistryUncached().workers) {
|
|
301
|
+
const observed = Math.max(w.lastActiveAt, observeActivity(w));
|
|
302
|
+
if (observed > w.lastActiveAt) persistActivity(w, observed);
|
|
303
|
+
}
|
|
304
|
+
updateRegistry((snap) => {
|
|
305
|
+
const cutoff = Date.now();
|
|
306
|
+
let changed = false;
|
|
307
|
+
const keep = [];
|
|
308
|
+
for (const w of snap.workers) {
|
|
309
|
+
if (w.pid === 0 && w.reserverPid !== void 0) {
|
|
310
|
+
if (w.reserverPid === process.pid) {
|
|
311
|
+
abortedGenerations.delete(w.generation);
|
|
312
|
+
ctx.log(`pie-proc: dropped stale own reservation ${w.name} (gen ${w.generation})`);
|
|
313
|
+
changed = true;
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
let reserverAlive = true;
|
|
317
|
+
try {
|
|
318
|
+
process.kill(w.reserverPid, 0);
|
|
319
|
+
} catch {
|
|
320
|
+
reserverAlive = false;
|
|
321
|
+
}
|
|
322
|
+
if (!reserverAlive) {
|
|
323
|
+
ctx.log(`pie-proc: reaped abandoned reservation ${w.name} (reserver ${w.reserverPid} dead)`);
|
|
324
|
+
changed = true;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
keep.push(w);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
const liveness = workerLiveness(w);
|
|
331
|
+
if (liveness === "dead") {
|
|
332
|
+
ctx.log(`pie-proc: dropped dead worker ${w.name} from registry`);
|
|
333
|
+
changed = true;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const ttl = w.kind === "resident" ? w.ttlMs ?? config.defaultTtlMs : 0;
|
|
337
|
+
if (ttl > 0 && liveness === "alive" && cutoff - Math.max(w.lastActiveAt, observeActivity(w)) > ttl) {
|
|
338
|
+
try {
|
|
339
|
+
process.kill(w.pid, "SIGTERM");
|
|
340
|
+
} catch {
|
|
341
|
+
}
|
|
342
|
+
ctx.log(`pie-proc: idle TTL signaled worker ${w.name} (idle > ${Math.round(ttl / 1e3)}s, identity verified)`);
|
|
343
|
+
keep.push({ ...w, ttlMs: 0 });
|
|
344
|
+
changed = true;
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
keep.push(w);
|
|
348
|
+
}
|
|
349
|
+
if (!changed) return { abort: { value: void 0 } };
|
|
350
|
+
return { next: keep, result: void 0 };
|
|
351
|
+
});
|
|
352
|
+
} catch (error) {
|
|
353
|
+
ctx.log(`pie-proc: sweep skipped: ${error instanceof Error ? error.message : String(error)}`);
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
const sweepTimer = setInterval(sweep, 6e4);
|
|
357
|
+
sweepTimer.unref?.();
|
|
358
|
+
ctx.registerCleanup?.(() => {
|
|
359
|
+
clearInterval(sweepTimer);
|
|
360
|
+
});
|
|
361
|
+
const spawnWorker = (params) => {
|
|
362
|
+
if (!safeName(params.name)) throw new Error(`invalid worker name "${params.name}" (use [a-z0-9-_], max 48)`);
|
|
363
|
+
if (params.kind === "oneshot" && (typeof params.task !== "string" || !params.task.trim())) throw new Error("oneshot spawn requires a non-empty task");
|
|
364
|
+
if (params.kind === "oneshot" && params.task.startsWith("-")) throw new Error(`oneshot task must not start with "-" (got "${params.task.slice(0, 20)}\u2026")`);
|
|
365
|
+
if (params.kind === "oneshot" && params.imForward) throw new Error("imForward applies to resident workers only");
|
|
366
|
+
if (params.kind !== "resident" && params.ttlMs !== void 0) throw new Error("ttlMs applies to resident workers only");
|
|
367
|
+
const canonicalCwd = cwdAllowedOrThrow(params.cwd, config.allowCwd);
|
|
368
|
+
const entry = cliEntry();
|
|
369
|
+
if (!entry) throw new Error("cannot resolve a trusted pie entry point (refusing to spawn)");
|
|
370
|
+
const generation = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
371
|
+
const sessionId = `pie-proc-${params.name}-${generation}`;
|
|
372
|
+
const imForward = sanitizeImForward(params.imForward);
|
|
373
|
+
casRegistry((snap) => {
|
|
374
|
+
const current = snap.workers;
|
|
375
|
+
const sameName = current.find((w) => w.name === params.name);
|
|
376
|
+
if (sameName && sameName.pid !== 0 && workerLiveness(sameName) !== "dead") {
|
|
377
|
+
return { abort: { error: new Error(`worker "${params.name}" already exists (pid ${sameName.pid})`) } };
|
|
378
|
+
}
|
|
379
|
+
if (sameName && sameName.pid === 0) {
|
|
380
|
+
if (sameName.reserverPid !== void 0 && sameName.reserverPid !== process.pid) {
|
|
381
|
+
let reserverAlive = true;
|
|
382
|
+
try {
|
|
383
|
+
process.kill(sameName.reserverPid, 0);
|
|
384
|
+
} catch {
|
|
385
|
+
reserverAlive = false;
|
|
386
|
+
}
|
|
387
|
+
if (reserverAlive) {
|
|
388
|
+
return { abort: { error: new Error(`worker "${params.name}" has a pending spawn reservation by pid ${sameName.reserverPid}`) } };
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const live = current.filter((w) => {
|
|
393
|
+
if (sameName === w) return false;
|
|
394
|
+
return w.pid === 0 || workerLiveness(w) !== "dead";
|
|
395
|
+
});
|
|
396
|
+
if (live.length >= config.maxWorkers) {
|
|
397
|
+
return { abort: { error: new Error(`worker cap reached (${config.maxWorkers}); kill an idle worker first (pie_proc kill)`) } };
|
|
398
|
+
}
|
|
399
|
+
const others = current.filter((w) => {
|
|
400
|
+
if (sameName === w) return false;
|
|
401
|
+
if (w.pid === 0) return true;
|
|
402
|
+
return workerLiveness(w) !== "dead";
|
|
403
|
+
});
|
|
404
|
+
const reservation = {
|
|
405
|
+
name: params.name,
|
|
406
|
+
sessionId,
|
|
407
|
+
generation,
|
|
408
|
+
pid: 0,
|
|
409
|
+
cwd: "",
|
|
410
|
+
pieDir: "",
|
|
411
|
+
kind: params.kind,
|
|
412
|
+
spawnedAt: Date.now(),
|
|
413
|
+
lastActiveAt: Date.now(),
|
|
414
|
+
ttlMs: params.ttlMs,
|
|
415
|
+
imForward,
|
|
416
|
+
reserverPid: process.pid
|
|
417
|
+
};
|
|
418
|
+
return { next: [...others, reservation], result: void 0 };
|
|
419
|
+
});
|
|
420
|
+
let child;
|
|
421
|
+
try {
|
|
422
|
+
const pieDir = path.join(pieProcDir(), "agents", params.name);
|
|
423
|
+
fs.mkdirSync(pieDir, { recursive: true });
|
|
424
|
+
for (const file of ["models.json", "config.json", "auth.json"]) {
|
|
425
|
+
const dst = path.join(pieDir, file);
|
|
426
|
+
const src = path.join(configDirRoot(), file);
|
|
427
|
+
if (!fs.existsSync(dst) && fs.existsSync(src)) {
|
|
428
|
+
try {
|
|
429
|
+
fs.copyFileSync(src, dst);
|
|
430
|
+
} catch {
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (imForward) {
|
|
435
|
+
const imFile = path.join(pieDir, "im-forward.json");
|
|
436
|
+
if (!fs.existsSync(imFile)) {
|
|
437
|
+
const provider = typeof imForward.provider === "string" && imForward.provider.trim() ? imForward.provider : "feishu";
|
|
438
|
+
const providerSettings = {};
|
|
439
|
+
for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
|
|
440
|
+
if (imForward[key] !== void 0) providerSettings[key] = imForward[key];
|
|
441
|
+
}
|
|
442
|
+
const doc = {
|
|
443
|
+
enabled: imForward.enabled === true,
|
|
444
|
+
provider,
|
|
445
|
+
providers: { [provider]: providerSettings }
|
|
446
|
+
};
|
|
447
|
+
if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
|
|
448
|
+
fs.writeFileSync(imFile, JSON.stringify(doc, null, " "));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
fs.mkdirSync(logDir(), { recursive: true });
|
|
452
|
+
const logFile = fs.openSync(path.join(logDir(), `${params.name}.jsonl`), "a");
|
|
453
|
+
const args = params.kind === "resident" ? [...loaderArgs(), entry, "--json-events", "--idle", "--session-id", sessionId] : [...loaderArgs(), entry, "--session-id", sessionId];
|
|
454
|
+
const inheritedIpcRoot = path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
|
|
455
|
+
const childEnv = {
|
|
456
|
+
...process.env,
|
|
457
|
+
PIE_CODING_AGENT_DIR: pieDir,
|
|
458
|
+
PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
|
|
459
|
+
PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
|
|
460
|
+
};
|
|
461
|
+
if (params.kind === "oneshot") childEnv[ONESHOT_TASK_ENV] = params.task ?? "";
|
|
462
|
+
try {
|
|
463
|
+
child = spawn(process.execPath, args, {
|
|
464
|
+
cwd: canonicalCwd,
|
|
465
|
+
detached: true,
|
|
466
|
+
stdio: ["ignore", logFile, logFile],
|
|
467
|
+
windowsHide: true,
|
|
468
|
+
env: childEnv
|
|
469
|
+
});
|
|
470
|
+
child.on("error", (error) => {
|
|
471
|
+
ctx.log(`pie-proc: worker "${params.name}" spawn error: ${error.message}`);
|
|
472
|
+
});
|
|
473
|
+
} finally {
|
|
474
|
+
try {
|
|
475
|
+
fs.closeSync(logFile);
|
|
476
|
+
} catch {
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (typeof child.pid !== "number") {
|
|
480
|
+
throw new Error(`worker spawn failed (no pid) \u2014 see ${path.join(logDir(), `${params.name}.jsonl`)}`);
|
|
481
|
+
}
|
|
482
|
+
child.unref();
|
|
483
|
+
const record = {
|
|
484
|
+
name: params.name,
|
|
485
|
+
sessionId,
|
|
486
|
+
generation,
|
|
487
|
+
pid: child.pid,
|
|
488
|
+
cwd: canonicalCwd,
|
|
489
|
+
pieDir,
|
|
490
|
+
kind: params.kind,
|
|
491
|
+
spawnedAt: Date.now(),
|
|
492
|
+
lastActiveAt: Date.now(),
|
|
493
|
+
ttlMs: params.ttlMs,
|
|
494
|
+
imForward
|
|
495
|
+
};
|
|
496
|
+
try {
|
|
497
|
+
casRegistry((snap) => {
|
|
498
|
+
const mine = snap.workers.find((w) => w.generation === generation);
|
|
499
|
+
if (!mine || mine.pid !== 0 || mine.reserverPid !== process.pid) {
|
|
500
|
+
throw new Error(`spawn reservation for "${params.name}" was reclaimed by another process; refusing to commit`);
|
|
501
|
+
}
|
|
502
|
+
return {
|
|
503
|
+
next: [...snap.workers.filter((w) => w.generation !== generation), record],
|
|
504
|
+
result: void 0
|
|
505
|
+
};
|
|
506
|
+
});
|
|
507
|
+
} catch (error) {
|
|
508
|
+
try {
|
|
509
|
+
child.kill("SIGKILL");
|
|
510
|
+
} catch {
|
|
511
|
+
}
|
|
512
|
+
releaseReservation(generation);
|
|
513
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
514
|
+
}
|
|
515
|
+
ctx.log(`pie-proc: spawned ${params.kind} worker "${params.name}" (pid ${record.pid}, cwd ${record.cwd}, gen ${generation})`);
|
|
516
|
+
return toolText(`Spawned ${params.kind} worker "${params.name}" (pid ${record.pid}, peer name "${params.name}", cwd ${record.cwd}${params.kind === "resident" && params.ttlMs ? `, idle TTL ${Math.round(params.ttlMs / 1e3)}s` : ""}). Resident workers accept ipc_send_notify by peer name "${params.name}"; their stdout events are at ${path.join(logDir(), `${params.name}.jsonl`)}.`);
|
|
517
|
+
} catch (error) {
|
|
518
|
+
releaseReservation(generation);
|
|
519
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
const killWorker = async (name, opts = {}) => {
|
|
523
|
+
let target;
|
|
524
|
+
target = readRegistryUncached().workers.find((w) => w.name === name);
|
|
525
|
+
if (!target) throw new Error(`no worker named "${name}"`);
|
|
526
|
+
if (target.pid === 0) {
|
|
527
|
+
return updateRegistry((snap) => {
|
|
528
|
+
const mine = snap.workers.find((w) => w.generation === target.generation);
|
|
529
|
+
if (!mine || mine.pid !== 0) return { next: snap.workers, result: toolText(`Worker "${name}" is no longer pending; refresh with pie_proc list.`) };
|
|
530
|
+
if (mine.reserverPid !== void 0 && mine.reserverPid !== process.pid) {
|
|
531
|
+
return { next: snap.workers, result: toolText(`Worker "${name}" has a pending spawn reservation by pid ${mine.reserverPid}; it clears when that spawn finishes or its process dies.`, true) };
|
|
532
|
+
}
|
|
533
|
+
return { next: snap.workers.filter((w) => w !== mine), result: toolText(`Released pending reservation "${name}".`) };
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
const liveness = workerLiveness(target);
|
|
537
|
+
if (liveness === "dead") {
|
|
538
|
+
updateRegistry((snap) => ({ next: snap.workers.filter((w) => w.generation !== target.generation), result: void 0 }));
|
|
539
|
+
return toolText(`Worker "${name}" was already dead; registry cleaned.`);
|
|
540
|
+
}
|
|
541
|
+
if (liveness === "unknown") {
|
|
542
|
+
throw new Error(`worker "${name}" (pid ${target.pid}): identity could not be verified (probe failed); refusing to signal an unverified pid. Retry shortly, or inspect the process manually before removing the registry entry.`);
|
|
543
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
process.kill(target.pid, opts.force ? "SIGKILL" : "SIGTERM");
|
|
546
|
+
} catch {
|
|
547
|
+
}
|
|
548
|
+
if (!opts.force) {
|
|
549
|
+
const deadline = Date.now() + config.killGraceMs;
|
|
550
|
+
while (Date.now() < deadline) {
|
|
551
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
552
|
+
if (workerLiveness(target) === "dead") break;
|
|
553
|
+
}
|
|
554
|
+
if (workerLiveness(target) === "alive") {
|
|
555
|
+
try {
|
|
556
|
+
process.kill(target.pid, "SIGKILL");
|
|
557
|
+
} catch {
|
|
558
|
+
}
|
|
559
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
const finalState = workerLiveness(target);
|
|
563
|
+
if (finalState === "dead") {
|
|
564
|
+
updateRegistry((snap) => ({ next: snap.workers.filter((w) => w.generation !== target.generation), result: void 0 }));
|
|
565
|
+
ctx.log(`pie-proc: killed worker "${name}" (pid ${target.pid}, gen ${target.generation})`);
|
|
566
|
+
return toolText(`Worker "${name}" (pid ${target.pid}) stopped and removed from the registry.`);
|
|
567
|
+
}
|
|
568
|
+
return toolText(`Worker "${name}" (pid ${target.pid}) was signalled but is NOT confirmed dead (state: ${finalState}); its registry entry is retained. Re-run pie_proc kill after it exits, or inspect manually.`, true);
|
|
569
|
+
};
|
|
570
|
+
ctx.registerTool({
|
|
571
|
+
name: "pie_proc",
|
|
572
|
+
label: "Pie worker processes",
|
|
573
|
+
description: "Controlled lifecycle for pie worker processes (concierge plan): spawn creates a bounded-shape pie worker \u2014 either a RESIDENT host (--json-events --idle, peer-addressable by worker name via ipc_send_notify) or a ONE-SHOT run (pie -p <task>, process exit is the completion). cwd must resolve inside the allowCwd roots configured in ~/.pie/pie-proc.json (symlinks resolved). Optional idle TTL retires idle RESIDENTS automatically (identity-verified; activity-aware). imForward accepts identity fields ONLY \u2014 executable selection is operator config. kill stops a worker gracefully (SIGTERM, bounded identity-verified escalation) and removes its generation; list shows workers with pid/session/cwd/liveness/last-active. Never use raw shell to start pie processes \u2014 this tool owns the audit trail, caps, and cleanup.",
|
|
574
|
+
parameters: Type.Object({
|
|
575
|
+
action: Type.Union([Type.Literal("spawn"), Type.Literal("kill"), Type.Literal("list")], { description: "spawn | kill | list" }),
|
|
576
|
+
name: Type.Optional(Type.String({ description: "Worker name ([a-z0-9-_], unique among alive workers)" })),
|
|
577
|
+
cwd: Type.Optional(Type.String({ description: "spawn: working directory (must resolve under an allowCwd root)" })),
|
|
578
|
+
kind: Type.Optional(Type.Union([Type.Literal("resident"), Type.Literal("oneshot")], { description: "spawn: resident (default) or oneshot" })),
|
|
579
|
+
task: Type.Optional(Type.String({ description: "oneshot: the task prompt (non-empty, must not start with '-')" })),
|
|
580
|
+
ttlMs: Type.Optional(Type.Number({ description: "spawn (resident only): idle TTL in ms (0 = never reap)", minimum: 0, maximum: 864e5 })),
|
|
581
|
+
force: Type.Optional(Type.Boolean({ description: "kill: skip graceful SIGTERM" })),
|
|
582
|
+
imForward: Type.Optional(Type.Record(Type.String(), Type.Unknown()), { description: "spawn (resident only): IM identity binding \u2014 identity fields only (enabled/provider/chatId/openId/allowUsers/larkCliProfile)" })
|
|
583
|
+
}),
|
|
584
|
+
risk: { riskClass: "process_lifecycle", requiresPermission: true, externalSideEffect: true, readsNetwork: false, writesNetwork: false, concurrencySafe: false },
|
|
585
|
+
renderHint: { summary: (args) => `${String(args.action)}${args.name ? ` ${String(args.name)}` : ""}` },
|
|
586
|
+
// EXTENSION tool signature (loader contract): execute(args, toolContext)
|
|
587
|
+
// — the loader adapts it to the AgentTool (toolCallId, args) surface.
|
|
588
|
+
execute: async (args) => {
|
|
589
|
+
const action = args.action;
|
|
590
|
+
if (action === "list") {
|
|
591
|
+
const snap = readRegistryUncached();
|
|
592
|
+
const rows = snap.workers.map((w) => ({
|
|
593
|
+
name: w.name,
|
|
594
|
+
pid: w.pid,
|
|
595
|
+
session: w.sessionId,
|
|
596
|
+
cwd: w.cwd,
|
|
597
|
+
kind: w.kind,
|
|
598
|
+
status: w.pid === 0 ? `pending (reserver ${w.reserverPid ?? "?"})` : workerLiveness(w),
|
|
599
|
+
idleSeconds: Math.round((Date.now() - Math.max(w.lastActiveAt, observeActivity(w))) / 1e3),
|
|
600
|
+
ttlMs: w.kind === "resident" ? w.ttlMs ?? config.defaultTtlMs : 0,
|
|
601
|
+
im: Boolean(w.imForward)
|
|
602
|
+
}));
|
|
603
|
+
return { content: [{ type: "text", text: rows.length === 0 ? "No pie-proc workers registered." : JSON.stringify(rows, null, 2) }], details: {} };
|
|
604
|
+
}
|
|
605
|
+
if (action === "spawn") {
|
|
606
|
+
const name = args.name;
|
|
607
|
+
const cwd = args.cwd;
|
|
608
|
+
if (!name || !cwd) throw new Error("spawn requires name and cwd");
|
|
609
|
+
if (args.kind === "oneshot" && typeof args.task !== "string") throw new Error("oneshot spawn requires task");
|
|
610
|
+
return spawnWorker({
|
|
611
|
+
name,
|
|
612
|
+
cwd,
|
|
613
|
+
kind: args.kind ?? "resident",
|
|
614
|
+
ttlMs: typeof args.ttlMs === "number" ? args.ttlMs : void 0,
|
|
615
|
+
task: args.task,
|
|
616
|
+
imForward: args.imForward
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
if (action === "kill") {
|
|
620
|
+
const name = args.name;
|
|
621
|
+
if (!name) throw new Error("kill requires name");
|
|
622
|
+
return killWorker(name, { force: args.force === true });
|
|
623
|
+
}
|
|
624
|
+
throw new Error(`unknown action "${action}"`);
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
export {
|
|
629
|
+
pieProc as default
|
|
630
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pie/extension-pie-proc",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Controlled pie worker-process lifecycle (spawn/kill/list) for the concierge",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"pie": {
|
|
8
|
+
"name": "pie-proc",
|
|
9
|
+
"main": "index.js"
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -6,10 +6,10 @@ import {
|
|
|
6
6
|
createPlanCapability,
|
|
7
7
|
markCompletedPlanSteps,
|
|
8
8
|
restoreExecutionState
|
|
9
|
-
} from "../../../chunks/chunk-
|
|
10
|
-
import "../../../chunks/chunk-
|
|
11
|
-
import "../../../chunks/chunk-
|
|
12
|
-
import "../../../chunks/chunk-
|
|
9
|
+
} from "../../../chunks/chunk-FDLLNPIE.js";
|
|
10
|
+
import "../../../chunks/chunk-WK4N5HT5.js";
|
|
11
|
+
import "../../../chunks/chunk-NCP264ZE.js";
|
|
12
|
+
import "../../../chunks/chunk-JQRZLVPY.js";
|
|
13
13
|
import {
|
|
14
14
|
Type
|
|
15
15
|
} from "../../../chunks/chunk-XXGYUYXI.js";
|