@cydm/pie 4.7.0 → 4.9.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 +51 -27
- package/dist/builtin/extensions/ask-user/index.js +4 -4
- package/dist/builtin/extensions/cron/index.js +916 -162
- package/dist/builtin/extensions/im-forward/README.md +24 -7
- package/dist/builtin/extensions/im-forward/index.js +6823 -3683
- package/dist/builtin/extensions/memory/index.js +76 -28
- package/dist/builtin/extensions/pie-ipc/README.md +2 -2
- package/dist/builtin/extensions/pie-ipc/index.js +421 -27
- package/dist/builtin/extensions/pie-proc/README.md +7 -7
- package/dist/builtin/extensions/pie-proc/index.js +453 -97
- package/dist/builtin/extensions/plan-mode/index.js +5 -5
- package/dist/builtin/extensions/subagent/index.js +8 -8
- package/dist/builtin/extensions/todo/index.js +4 -4
- package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +35 -24
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +391 -123
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
- package/dist/builtin/skills/chrome-devtools-axi/{cli-NLPMVDGG.js → cli-K7ESY3XD.js} +1437 -231
- package/dist/builtin/skills/computer-use-axi/SKILL.md +26 -8
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +465 -83
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +75 -22
- package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
- package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
- package/dist/chunks/chunk-6WKBQZWM.js +19 -0
- package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
- package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
- package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
- package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
- package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
- package/dist/chunks/chunk-OU33ROFD.js +717 -0
- package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
- package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
- package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
- package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
- package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
- package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
- package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
- package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
- package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
- package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
- package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
- package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
- package/dist/cli.js +1918 -1489
- package/models.schema.json +271 -0
- package/package.json +2 -2
- package/dist/builtin/skills/chrome-devtools-axi/chunk-WOGAQ4P5.js +0 -399
- package/dist/chunks/chunk-7UAUDXZW.js +0 -1425
- package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
- package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
|
@@ -1,24 +1,150 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
liveSessionHolder
|
|
4
|
-
} from "../../../chunks/chunk-
|
|
5
|
-
import
|
|
4
|
+
} from "../../../chunks/chunk-WBL73KRI.js";
|
|
5
|
+
import {
|
|
6
|
+
registerWorkerLifecycleBridge
|
|
7
|
+
} from "../../../chunks/chunk-6WKBQZWM.js";
|
|
6
8
|
import {
|
|
7
9
|
readProcessCommandLine
|
|
8
10
|
} from "../../../chunks/chunk-7RJXKN7N.js";
|
|
9
11
|
import "../../../chunks/chunk-ZPJ3BNQB.js";
|
|
12
|
+
import "../../../chunks/chunk-CBDQJMUI.js";
|
|
10
13
|
import {
|
|
11
14
|
Type
|
|
12
15
|
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
13
16
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
14
17
|
|
|
15
18
|
// builtin/extensions/pie-proc/index.ts
|
|
16
|
-
import { spawn } from "node:child_process";
|
|
19
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
17
20
|
import { createRequire } from "node:module";
|
|
18
21
|
import { fileURLToPath } from "node:url";
|
|
19
|
-
import * as
|
|
22
|
+
import * as fs2 from "node:fs";
|
|
20
23
|
import * as os from "node:os";
|
|
24
|
+
import * as path2 from "node:path";
|
|
25
|
+
|
|
26
|
+
// builtin/extensions/pie-proc/panel-bridge.ts
|
|
27
|
+
import * as fs from "node:fs";
|
|
21
28
|
import * as path from "node:path";
|
|
29
|
+
var VALID_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/;
|
|
30
|
+
function readSessionHeadCwd(headFile) {
|
|
31
|
+
try {
|
|
32
|
+
const head = JSON.parse(fs.readFileSync(headFile, "utf8"));
|
|
33
|
+
return typeof head.metadata?.cwd === "string" && head.metadata.cwd.trim() ? head.metadata.cwd.trim() : void 0;
|
|
34
|
+
} catch {
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function toInfo(w, deps) {
|
|
39
|
+
return {
|
|
40
|
+
name: w.name,
|
|
41
|
+
sessionId: w.sessionId,
|
|
42
|
+
generation: w.generation,
|
|
43
|
+
cwd: w.cwd,
|
|
44
|
+
kind: w.kind,
|
|
45
|
+
pid: w.pid,
|
|
46
|
+
liveness: w.pid === 0 ? "pending" : deps.workerLiveness(w)
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function deriveSafeWorkerName(sessionId, preferred, deps) {
|
|
50
|
+
if (preferred && deps.safeName(preferred)) return preferred;
|
|
51
|
+
const slug = sessionId.replace(/[^a-z0-9-_]/gi, "").toLowerCase().slice(-24) || "worker";
|
|
52
|
+
const candidate = `w-${slug}`.slice(0, 48);
|
|
53
|
+
return deps.safeName(candidate) ? candidate : "w-resumed";
|
|
54
|
+
}
|
|
55
|
+
function findSessionSource(sessionId, deps) {
|
|
56
|
+
if (!VALID_SESSION_ID.test(sessionId)) return void 0;
|
|
57
|
+
const workers = deps.readWorkers();
|
|
58
|
+
const fromRegistry = workers.find((w) => w.sessionId === sessionId);
|
|
59
|
+
if (fromRegistry) return { name: fromRegistry.name, cwd: fromRegistry.cwd };
|
|
60
|
+
const agentsDir = path.join(deps.pieProcDir(), "agents");
|
|
61
|
+
try {
|
|
62
|
+
for (const entry of fs.readdirSync(agentsDir, { withFileTypes: true })) {
|
|
63
|
+
if (!entry.isDirectory() || !deps.safeName(entry.name)) continue;
|
|
64
|
+
const cwd = readSessionHeadCwd(path.join(agentsDir, entry.name, "sessions", sessionId, "head.json"));
|
|
65
|
+
if (cwd) return { name: entry.name, cwd };
|
|
66
|
+
}
|
|
67
|
+
} catch {
|
|
68
|
+
}
|
|
69
|
+
const globalCwd = readSessionHeadCwd(path.join(deps.operatorSessionsDir(), sessionId, "head.json"));
|
|
70
|
+
if (globalCwd) return { name: deriveSafeWorkerName(sessionId, void 0, deps), cwd: globalCwd };
|
|
71
|
+
return void 0;
|
|
72
|
+
}
|
|
73
|
+
function registerPieProcPanelBridge(deps) {
|
|
74
|
+
const inspectResumable = (sessionId) => {
|
|
75
|
+
const found = findSessionSource(sessionId, deps);
|
|
76
|
+
if (!found) return void 0;
|
|
77
|
+
try {
|
|
78
|
+
const canonical = deps.cwdAllowedOrThrow(found.cwd, deps.allowCwd());
|
|
79
|
+
const holder = liveSessionHolder(sessionId);
|
|
80
|
+
if (holder) {
|
|
81
|
+
return { sessionId, name: found.name, cwd: canonical, allowed: false, reason: `session is already owned by a live host (pid ${holder.pid})` };
|
|
82
|
+
}
|
|
83
|
+
return { sessionId, name: found.name, cwd: canonical, allowed: true };
|
|
84
|
+
} catch (error) {
|
|
85
|
+
return { sessionId, name: found.name, cwd: found.cwd, allowed: false, reason: error instanceof Error ? error.message : String(error) };
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
return registerWorkerLifecycleBridge({
|
|
89
|
+
lookupBySession: (sessionId) => {
|
|
90
|
+
try {
|
|
91
|
+
const found = deps.readWorkers().find((w) => w.sessionId === sessionId);
|
|
92
|
+
return found ? toInfo(found, deps) : void 0;
|
|
93
|
+
} catch {
|
|
94
|
+
return void 0;
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
lookupByName: (name) => {
|
|
98
|
+
try {
|
|
99
|
+
const found = deps.readWorkers().find((w) => w.name === name);
|
|
100
|
+
return found ? toInfo(found, deps) : void 0;
|
|
101
|
+
} catch {
|
|
102
|
+
return void 0;
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
inspectResumable,
|
|
106
|
+
cleanupDeadWorker: (sessionIdOrName) => {
|
|
107
|
+
try {
|
|
108
|
+
const found = deps.readWorkers().find((w) => w.sessionId === sessionIdOrName || w.name === sessionIdOrName);
|
|
109
|
+
if (!found || found.pid === 0) return false;
|
|
110
|
+
return deps.removeGenerationIfDead(found);
|
|
111
|
+
} catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
killWorker: async (name, opts) => {
|
|
116
|
+
try {
|
|
117
|
+
if (opts?.expectedGeneration) {
|
|
118
|
+
const current = deps.readWorkers().find((w) => w.name === name);
|
|
119
|
+
if (!current || current.generation !== opts.expectedGeneration) {
|
|
120
|
+
return { ok: false, detail: `Worker "${name}" incarnation changed since the confirmation card was issued; refusing to signal a newer worker.` };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const res = await deps.killWorker(name, opts);
|
|
124
|
+
return { ok: res.isError !== true, detail: res.content[0]?.text ?? "done" };
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return { ok: false, detail: error instanceof Error ? error.message : String(error) };
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
resumeWorker: async (sessionId) => {
|
|
130
|
+
const info = inspectResumable(sessionId);
|
|
131
|
+
if (!info) return { ok: false, detail: `Session "${sessionId}" not found in worker or operator stores.` };
|
|
132
|
+
if (!info.allowed) return { ok: false, detail: info.reason ?? "Resume not permitted by pie-proc allowCwd policy." };
|
|
133
|
+
try {
|
|
134
|
+
const hasWorkerIm = fs.existsSync(path.join(deps.pieProcDir(), "agents", info.name, "im-forward.json"));
|
|
135
|
+
const inheritIm = !hasWorkerIm && deps.canInheritImForward();
|
|
136
|
+
const res = deps.spawnResumeWorker({ name: info.name, cwd: info.cwd, resumeSessionId: sessionId, inheritIm });
|
|
137
|
+
const detail = res.content[0]?.text ?? "spawned";
|
|
138
|
+
const pidMatch = /\bpid (\d+)\b/.exec(detail);
|
|
139
|
+
return { ok: res.isError !== true, detail, name: info.name, ...pidMatch ? { pid: Number(pidMatch[1]) } : {} };
|
|
140
|
+
} catch (error) {
|
|
141
|
+
return { ok: false, detail: error instanceof Error ? error.message : String(error) };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// builtin/extensions/pie-proc/index.ts
|
|
22
148
|
var require_ = createRequire(import.meta.url);
|
|
23
149
|
function resolveOperatorSessionsDir() {
|
|
24
150
|
try {
|
|
@@ -27,33 +153,34 @@ function resolveOperatorSessionsDir() {
|
|
|
27
153
|
} catch {
|
|
28
154
|
const override = process.env.PIE_SESSIONS_DIR;
|
|
29
155
|
if (override !== void 0 && override !== "") {
|
|
30
|
-
if (override === "~") return
|
|
31
|
-
if (override.startsWith("~/")) return
|
|
32
|
-
if (
|
|
156
|
+
if (override === "~") return path2.join(os.homedir(), ".pie", "sessions");
|
|
157
|
+
if (override.startsWith("~/")) return path2.join(os.homedir(), override.slice(2));
|
|
158
|
+
if (path2.isAbsolute(override)) return override;
|
|
33
159
|
}
|
|
34
|
-
return
|
|
160
|
+
return path2.join(os.homedir(), ".pie", "sessions");
|
|
35
161
|
}
|
|
36
162
|
}
|
|
37
163
|
var DEFAULT_MAX_WORKERS = 50;
|
|
38
164
|
var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: DEFAULT_MAX_WORKERS, killGraceMs: 15e3, defaultTtlMs: 0 };
|
|
39
165
|
var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
|
|
40
166
|
var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
|
|
167
|
+
var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
|
|
41
168
|
function configDirRoot() {
|
|
42
169
|
const env = process.env.PIE_CODING_AGENT_DIR;
|
|
43
|
-
if (!env) return
|
|
44
|
-
return
|
|
170
|
+
if (!env) return path2.join(os.homedir(), ".pie");
|
|
171
|
+
return path2.resolve(expandTilde(env));
|
|
45
172
|
}
|
|
46
173
|
function expandTilde(p) {
|
|
47
|
-
return p === "~" ? os.homedir() : p.startsWith("~/") ?
|
|
174
|
+
return p === "~" ? os.homedir() : p.startsWith("~/") ? path2.join(os.homedir(), p.slice(2)) : p;
|
|
48
175
|
}
|
|
49
176
|
function configCandidates() {
|
|
50
|
-
const candidates = [
|
|
177
|
+
const candidates = [path2.join(configDirRoot(), "pie-proc.json")];
|
|
51
178
|
const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
|
|
52
179
|
if (pinnedRoot) {
|
|
53
|
-
const pinDerived =
|
|
180
|
+
const pinDerived = path2.join(path2.dirname(path2.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
|
|
54
181
|
if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
|
|
55
|
-
} else if (configDirRoot() !==
|
|
56
|
-
candidates.push(
|
|
182
|
+
} else if (configDirRoot() !== path2.join(os.homedir(), ".pie")) {
|
|
183
|
+
candidates.push(path2.join(os.homedir(), ".pie", "pie-proc.json"));
|
|
57
184
|
}
|
|
58
185
|
return candidates;
|
|
59
186
|
}
|
|
@@ -61,7 +188,7 @@ function readConfig() {
|
|
|
61
188
|
const candidates = configCandidates();
|
|
62
189
|
for (const file of candidates) {
|
|
63
190
|
try {
|
|
64
|
-
const raw = JSON.parse(
|
|
191
|
+
const raw = JSON.parse(fs2.readFileSync(file, "utf8"));
|
|
65
192
|
return {
|
|
66
193
|
allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
|
|
67
194
|
maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
|
|
@@ -69,21 +196,21 @@ function readConfig() {
|
|
|
69
196
|
defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
|
|
70
197
|
};
|
|
71
198
|
} catch {
|
|
72
|
-
if (
|
|
199
|
+
if (fs2.existsSync(file)) return { ...DEFAULT_CONFIG };
|
|
73
200
|
}
|
|
74
201
|
}
|
|
75
202
|
return { ...DEFAULT_CONFIG };
|
|
76
203
|
}
|
|
77
204
|
function pieProcDir() {
|
|
78
205
|
const pinned = process.env.PIE_PROC_REGISTRY_ROOT;
|
|
79
|
-
if (pinned) return
|
|
80
|
-
return
|
|
206
|
+
if (pinned) return path2.resolve(expandTilde(pinned));
|
|
207
|
+
return path2.join(configDirRoot(), "pie-proc");
|
|
81
208
|
}
|
|
82
209
|
function registryFile() {
|
|
83
|
-
return
|
|
210
|
+
return path2.join(pieProcDir(), "workers.json");
|
|
84
211
|
}
|
|
85
212
|
function revisionFile(n) {
|
|
86
|
-
return
|
|
213
|
+
return path2.join(pieProcDir(), `workers.r${n}.json`);
|
|
87
214
|
}
|
|
88
215
|
function parseRegistry(rawText, file, revision) {
|
|
89
216
|
let raw;
|
|
@@ -115,7 +242,7 @@ function parseRegistry(rawText, file, revision) {
|
|
|
115
242
|
function latestRevisionOnDisk() {
|
|
116
243
|
let max = 0;
|
|
117
244
|
try {
|
|
118
|
-
for (const entry of
|
|
245
|
+
for (const entry of fs2.readdirSync(pieProcDir())) {
|
|
119
246
|
const match = /^workers\.r(\d+)\.json$/.exec(entry);
|
|
120
247
|
if (match) max = Math.max(max, Number(match[1]));
|
|
121
248
|
}
|
|
@@ -129,7 +256,7 @@ function readRegistryUncached() {
|
|
|
129
256
|
if (latest > 0) {
|
|
130
257
|
const file2 = revisionFile(latest);
|
|
131
258
|
try {
|
|
132
|
-
return parseRegistry(
|
|
259
|
+
return parseRegistry(fs2.readFileSync(file2, "utf8"), file2, latest);
|
|
133
260
|
} catch (error) {
|
|
134
261
|
if (error.code === "ENOENT") continue;
|
|
135
262
|
throw error;
|
|
@@ -137,7 +264,7 @@ function readRegistryUncached() {
|
|
|
137
264
|
}
|
|
138
265
|
const file = registryFile();
|
|
139
266
|
try {
|
|
140
|
-
return parseRegistry(
|
|
267
|
+
return parseRegistry(fs2.readFileSync(file, "utf8"), file, 0);
|
|
141
268
|
} catch (error) {
|
|
142
269
|
if (error.code === "ENOENT") return { revision: 0, workers: [] };
|
|
143
270
|
throw error;
|
|
@@ -148,7 +275,7 @@ function readRegistryUncached() {
|
|
|
148
275
|
function compactRevisions(_current) {
|
|
149
276
|
}
|
|
150
277
|
function casRegistry(mutate) {
|
|
151
|
-
|
|
278
|
+
fs2.mkdirSync(pieProcDir(), { recursive: true });
|
|
152
279
|
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
153
280
|
const snapshot = readRegistryUncached();
|
|
154
281
|
const outcome = mutate(snapshot);
|
|
@@ -159,26 +286,26 @@ function casRegistry(mutate) {
|
|
|
159
286
|
const nextRevision = snapshot.revision + 1;
|
|
160
287
|
const target = revisionFile(nextRevision);
|
|
161
288
|
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}-${attempt}.tmp`;
|
|
162
|
-
|
|
289
|
+
fs2.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
|
|
163
290
|
if (latestRevisionOnDisk() > snapshot.revision) {
|
|
164
291
|
try {
|
|
165
|
-
|
|
292
|
+
fs2.rmSync(tmp, { force: true });
|
|
166
293
|
} catch {
|
|
167
294
|
}
|
|
168
295
|
continue;
|
|
169
296
|
}
|
|
170
297
|
try {
|
|
171
|
-
|
|
298
|
+
fs2.linkSync(tmp, target);
|
|
172
299
|
} catch (error) {
|
|
173
300
|
try {
|
|
174
|
-
|
|
301
|
+
fs2.rmSync(tmp, { force: true });
|
|
175
302
|
} catch {
|
|
176
303
|
}
|
|
177
304
|
if (error.code === "EEXIST") continue;
|
|
178
305
|
throw error;
|
|
179
306
|
}
|
|
180
307
|
try {
|
|
181
|
-
|
|
308
|
+
fs2.rmSync(tmp, { force: true });
|
|
182
309
|
} catch {
|
|
183
310
|
}
|
|
184
311
|
compactRevisions(nextRevision);
|
|
@@ -189,22 +316,162 @@ function casRegistry(mutate) {
|
|
|
189
316
|
function updateRegistry(mutate) {
|
|
190
317
|
return casRegistry(mutate);
|
|
191
318
|
}
|
|
192
|
-
function
|
|
193
|
-
if (
|
|
319
|
+
function processExists(pid) {
|
|
320
|
+
if (!Number.isSafeInteger(pid) || pid <= 1) return false;
|
|
194
321
|
try {
|
|
195
|
-
process.kill(
|
|
322
|
+
process.kill(pid, 0);
|
|
323
|
+
return true;
|
|
324
|
+
} catch (error) {
|
|
325
|
+
return error.code === "EPERM";
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function probeProcessGroup(pgid) {
|
|
329
|
+
if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 1) return "dead";
|
|
330
|
+
try {
|
|
331
|
+
process.kill(-pgid, 0);
|
|
332
|
+
return "alive";
|
|
333
|
+
} catch (error) {
|
|
334
|
+
return error.code === "EPERM" ? "eperm" : "dead";
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function isZombieProcess(pid) {
|
|
338
|
+
if (process.platform === "win32") return false;
|
|
339
|
+
try {
|
|
340
|
+
const out = execFileSync("ps", ["-p", String(pid), "-o", "stat="], {
|
|
341
|
+
encoding: "utf8",
|
|
342
|
+
timeout: 3e3,
|
|
343
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
344
|
+
env: { ...process.env, LC_ALL: "C", LANG: "C" }
|
|
345
|
+
}).trim();
|
|
346
|
+
if (!out) return false;
|
|
347
|
+
return out.startsWith("Z");
|
|
348
|
+
} catch {
|
|
349
|
+
return "unknown";
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
function readProcessGroupMembers(pgid) {
|
|
353
|
+
if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 1) return [];
|
|
354
|
+
try {
|
|
355
|
+
const out = execFileSync("ps", ["-e", "-o", "pid=,pgid=,uid=,stat=,lstart="], {
|
|
356
|
+
encoding: "utf8",
|
|
357
|
+
timeout: 3e3,
|
|
358
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
359
|
+
env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC" }
|
|
360
|
+
});
|
|
361
|
+
const members = [];
|
|
362
|
+
for (const rawLine of out.split(/\r?\n/)) {
|
|
363
|
+
const line = rawLine.trim();
|
|
364
|
+
if (!line) continue;
|
|
365
|
+
const match = /^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/.exec(line);
|
|
366
|
+
if (!match) continue;
|
|
367
|
+
const pid = Number(match[1]);
|
|
368
|
+
const memberPgid = Number(match[2]);
|
|
369
|
+
const uid = Number(match[3]);
|
|
370
|
+
const stat = match[4];
|
|
371
|
+
if (memberPgid !== pgid) continue;
|
|
372
|
+
if (stat.startsWith("Z")) continue;
|
|
373
|
+
const normalized = match[5].replace(/\s+/g, " ").trim();
|
|
374
|
+
const parsedStart = Date.parse(`${normalized} UTC`);
|
|
375
|
+
members.push({
|
|
376
|
+
pid,
|
|
377
|
+
uid,
|
|
378
|
+
stat,
|
|
379
|
+
startedAtMs: Number.isFinite(parsedStart) ? parsedStart : void 0
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
return members;
|
|
196
383
|
} catch {
|
|
197
|
-
return
|
|
384
|
+
return void 0;
|
|
198
385
|
}
|
|
386
|
+
}
|
|
387
|
+
function hasBoundedToken(haystack, needle) {
|
|
388
|
+
let idx = haystack.indexOf(needle);
|
|
389
|
+
while (idx !== -1) {
|
|
390
|
+
const beforeOk = idx === 0 || /\s/.test(haystack[idx - 1]);
|
|
391
|
+
const afterIdx = idx + needle.length;
|
|
392
|
+
const afterOk = afterIdx === haystack.length || /\s/.test(haystack[afterIdx]);
|
|
393
|
+
if (beforeOk && afterOk) return true;
|
|
394
|
+
idx = haystack.indexOf(needle, idx + 1);
|
|
395
|
+
}
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
function verifyProcessEnvOwnership(pid, marker, pieDir) {
|
|
399
|
+
if (process.platform === "linux") {
|
|
400
|
+
let raw2;
|
|
401
|
+
try {
|
|
402
|
+
raw2 = fs2.readFileSync(`/proc/${pid}/environ`, "utf8");
|
|
403
|
+
} catch {
|
|
404
|
+
return "unverified";
|
|
405
|
+
}
|
|
406
|
+
let sawOtherToken = false;
|
|
407
|
+
for (const entry of raw2.split("\0")) {
|
|
408
|
+
if (entry === `${LAUNCH_TOKEN_ENV}=${marker}`) return "matched";
|
|
409
|
+
if (pieDir && entry === `PIE_CODING_AGENT_DIR=${pieDir}`) return "matched";
|
|
410
|
+
if (entry.startsWith(`${LAUNCH_TOKEN_ENV}=`)) sawOtherToken = true;
|
|
411
|
+
}
|
|
412
|
+
return sawOtherToken ? "foreign" : "unverified";
|
|
413
|
+
}
|
|
414
|
+
let raw;
|
|
415
|
+
try {
|
|
416
|
+
raw = execFileSync("ps", ["eww", "-p", String(pid), "-o", "command="], {
|
|
417
|
+
encoding: "utf8",
|
|
418
|
+
timeout: 3e3,
|
|
419
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
420
|
+
env: { ...process.env, LC_ALL: "C", LANG: "C" }
|
|
421
|
+
});
|
|
422
|
+
} catch {
|
|
423
|
+
return "unverified";
|
|
424
|
+
}
|
|
425
|
+
if (!raw) return "unverified";
|
|
426
|
+
if (hasBoundedToken(raw, `${LAUNCH_TOKEN_ENV}=${marker}`)) return "matched";
|
|
427
|
+
if (pieDir && hasBoundedToken(raw, `PIE_CODING_AGENT_DIR=${pieDir}`)) return "matched";
|
|
428
|
+
if (raw.includes(`${LAUNCH_TOKEN_ENV}=`)) return "foreign";
|
|
429
|
+
return "unverified";
|
|
430
|
+
}
|
|
431
|
+
function workerLiveness(record, opts = {}) {
|
|
432
|
+
if (record.pid === 0 || !Number.isSafeInteger(record.pid) || record.pid <= 1) return "dead";
|
|
199
433
|
const marker = record.launchToken ?? record.sessionId;
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
434
|
+
if (processExists(record.pid)) {
|
|
435
|
+
const cmd = readProcessCommandLine(record.pid);
|
|
436
|
+
if (cmd === void 0) return "unknown";
|
|
437
|
+
if (cmd.includes(marker)) return "alive";
|
|
438
|
+
const zombie = isZombieProcess(record.pid);
|
|
439
|
+
if (zombie === "unknown") return "unknown";
|
|
440
|
+
if (!zombie) return "dead";
|
|
441
|
+
}
|
|
442
|
+
if (process.platform !== "win32") {
|
|
443
|
+
const groupProbe = probeProcessGroup(record.pid);
|
|
444
|
+
if (groupProbe === "dead") return "dead";
|
|
445
|
+
if (groupProbe === "eperm") return "unknown";
|
|
446
|
+
const hasSpawnedAt = typeof record.spawnedAt === "number" && Number.isFinite(record.spawnedAt);
|
|
447
|
+
if (!hasSpawnedAt) return "unknown";
|
|
448
|
+
const bootAtMs = Date.now() - os.uptime() * 1e3;
|
|
449
|
+
if (record.spawnedAt < bootAtMs - 5e3) return "dead";
|
|
450
|
+
const members = readProcessGroupMembers(record.pid);
|
|
451
|
+
if (members === void 0) return "unknown";
|
|
452
|
+
if (members.length === 0) return "dead";
|
|
453
|
+
if (members.some((m) => m.pid === record.pid)) return "unknown";
|
|
454
|
+
const selfUid = typeof process.getuid === "function" ? process.getuid() : void 0;
|
|
455
|
+
if (selfUid !== void 0 && members.some((m) => m.uid !== selfUid)) return "unknown";
|
|
456
|
+
for (const member of members) {
|
|
457
|
+
if (member.startedAtMs === void 0) return "unknown";
|
|
458
|
+
if (member.startedAtMs < record.spawnedAt - 5e3) return "dead";
|
|
459
|
+
}
|
|
460
|
+
let envMatched = false;
|
|
461
|
+
for (const member of members) {
|
|
462
|
+
const ownership = verifyProcessEnvOwnership(member.pid, marker, record.pieDir);
|
|
463
|
+
if (ownership === "foreign") return "dead";
|
|
464
|
+
if (ownership === "matched") envMatched = true;
|
|
465
|
+
}
|
|
466
|
+
if (envMatched || opts.trustVerifiedGroup) return "orphaned_group";
|
|
467
|
+
return "unknown";
|
|
468
|
+
}
|
|
469
|
+
return "dead";
|
|
203
470
|
}
|
|
204
471
|
function canonicalDir(dir) {
|
|
205
|
-
const resolved =
|
|
206
|
-
const real =
|
|
207
|
-
const stat =
|
|
472
|
+
const resolved = path2.resolve(expandTilde(dir));
|
|
473
|
+
const real = fs2.realpathSync(resolved);
|
|
474
|
+
const stat = fs2.statSync(real);
|
|
208
475
|
if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
|
|
209
476
|
return real;
|
|
210
477
|
}
|
|
@@ -213,19 +480,19 @@ function cwdAllowedOrThrow(cwd, allow) {
|
|
|
213
480
|
for (const root of allow) {
|
|
214
481
|
try {
|
|
215
482
|
const canonicalRoot = canonicalDir(root);
|
|
216
|
-
if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot +
|
|
483
|
+
if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path2.sep)) return canonical;
|
|
217
484
|
} catch {
|
|
218
485
|
}
|
|
219
486
|
}
|
|
220
487
|
const file = configCandidates()[0];
|
|
221
488
|
let exists = false;
|
|
222
489
|
try {
|
|
223
|
-
exists =
|
|
490
|
+
exists = fs2.existsSync(file);
|
|
224
491
|
} catch {
|
|
225
492
|
}
|
|
226
493
|
const effective = configCandidates().find((c) => {
|
|
227
494
|
try {
|
|
228
|
-
return
|
|
495
|
+
return fs2.existsSync(c);
|
|
229
496
|
} catch {
|
|
230
497
|
return false;
|
|
231
498
|
}
|
|
@@ -256,10 +523,10 @@ function sanitizeImForward(raw) {
|
|
|
256
523
|
}
|
|
257
524
|
function readUserImForwardIdentity() {
|
|
258
525
|
try {
|
|
259
|
-
const candidates = [
|
|
526
|
+
const candidates = [path2.join(configDirRoot(), "im-forward.json")];
|
|
260
527
|
for (const file of candidates) {
|
|
261
528
|
try {
|
|
262
|
-
const parsed = JSON.parse(
|
|
529
|
+
const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
|
|
263
530
|
const provider = typeof parsed.provider === "string" ? parsed.provider : "feishu";
|
|
264
531
|
const settings = parsed.providers?.[provider];
|
|
265
532
|
if (!settings) continue;
|
|
@@ -276,12 +543,12 @@ function readUserImForwardIdentity() {
|
|
|
276
543
|
return void 0;
|
|
277
544
|
}
|
|
278
545
|
function cliEntry() {
|
|
279
|
-
const moduleDir =
|
|
546
|
+
const moduleDir = path2.dirname(fileURLToPath(import.meta.url));
|
|
280
547
|
for (const rel of ["../../../src/cli.ts", "../../../cli.js"]) {
|
|
281
|
-
const candidate =
|
|
548
|
+
const candidate = path2.resolve(moduleDir, rel);
|
|
282
549
|
try {
|
|
283
|
-
const real =
|
|
284
|
-
if (
|
|
550
|
+
const real = fs2.realpathSync(candidate);
|
|
551
|
+
if (fs2.statSync(real).isFile()) return real;
|
|
285
552
|
} catch {
|
|
286
553
|
}
|
|
287
554
|
}
|
|
@@ -291,10 +558,10 @@ function loaderArgs() {
|
|
|
291
558
|
for (let i = 0; i < process.execArgv.length - 1; i += 1) {
|
|
292
559
|
if (process.execArgv[i] === "--import") {
|
|
293
560
|
const target = process.execArgv[i + 1];
|
|
294
|
-
if (target && !
|
|
561
|
+
if (target && !path2.isAbsolute(target) && !target.startsWith("file:")) {
|
|
295
562
|
try {
|
|
296
|
-
const pkgRoot =
|
|
297
|
-
return ["--import",
|
|
563
|
+
const pkgRoot = path2.dirname(require_.resolve(`${target}/package.json`, { paths: [path2.dirname(cliEntry())] }));
|
|
564
|
+
return ["--import", path2.join(pkgRoot, "dist", "loader.mjs")];
|
|
298
565
|
} catch {
|
|
299
566
|
return [];
|
|
300
567
|
}
|
|
@@ -305,7 +572,7 @@ function loaderArgs() {
|
|
|
305
572
|
return [];
|
|
306
573
|
}
|
|
307
574
|
function logDir() {
|
|
308
|
-
return
|
|
575
|
+
return path2.join(pieProcDir(), "logs");
|
|
309
576
|
}
|
|
310
577
|
var toolText = (text, isError = false) => ({ content: [{ type: "text", text }], details: {}, ...isError ? { isError: true } : {} });
|
|
311
578
|
function pieProc(ctx) {
|
|
@@ -317,18 +584,18 @@ function pieProc(ctx) {
|
|
|
317
584
|
const observeActivity = (record) => {
|
|
318
585
|
const logTime = (() => {
|
|
319
586
|
try {
|
|
320
|
-
return
|
|
587
|
+
return fs2.statSync(path2.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
|
|
321
588
|
} catch {
|
|
322
589
|
return record.lastActiveAt;
|
|
323
590
|
}
|
|
324
591
|
})();
|
|
325
592
|
if (record.pid === 0) return logTime;
|
|
326
|
-
const statusRoot =
|
|
593
|
+
const statusRoot = path2.join(path2.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
|
|
327
594
|
try {
|
|
328
|
-
for (const file of
|
|
595
|
+
for (const file of fs2.readdirSync(statusRoot)) {
|
|
329
596
|
if (!file.endsWith(".json")) continue;
|
|
330
597
|
try {
|
|
331
|
-
const status = JSON.parse(
|
|
598
|
+
const status = JSON.parse(fs2.readFileSync(path2.join(statusRoot, file), "utf8"));
|
|
332
599
|
if (status.sessionId === record.sessionId && status.state === "working") return Date.now();
|
|
333
600
|
} catch {
|
|
334
601
|
}
|
|
@@ -357,6 +624,38 @@ function pieProc(ctx) {
|
|
|
357
624
|
ctx.log(`pie-proc: reservation release for gen ${generation} failed (${error instanceof Error ? error.message : String(error)}); sweep will retry`);
|
|
358
625
|
}
|
|
359
626
|
};
|
|
627
|
+
const signalWorkerProcessGroup = (pid, signal, opts = {}) => {
|
|
628
|
+
if (!Number.isSafeInteger(pid) || pid <= 1) return;
|
|
629
|
+
if (process.platform === "win32") {
|
|
630
|
+
try {
|
|
631
|
+
execFileSync("taskkill.exe", ["/F", "/T", "/PID", String(pid)], {
|
|
632
|
+
windowsHide: true,
|
|
633
|
+
stdio: "ignore",
|
|
634
|
+
timeout: 5e3
|
|
635
|
+
});
|
|
636
|
+
return;
|
|
637
|
+
} catch {
|
|
638
|
+
}
|
|
639
|
+
if (!opts.groupOnly) {
|
|
640
|
+
try {
|
|
641
|
+
process.kill(pid, signal);
|
|
642
|
+
} catch {
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
try {
|
|
648
|
+
process.kill(-pid, signal);
|
|
649
|
+
return;
|
|
650
|
+
} catch {
|
|
651
|
+
}
|
|
652
|
+
if (!opts.groupOnly) {
|
|
653
|
+
try {
|
|
654
|
+
process.kill(pid, signal);
|
|
655
|
+
} catch {
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
};
|
|
360
659
|
const sweep = () => {
|
|
361
660
|
try {
|
|
362
661
|
if (abortedGenerations.size > 0) {
|
|
@@ -410,14 +709,31 @@ function pieProc(ctx) {
|
|
|
410
709
|
changed = true;
|
|
411
710
|
continue;
|
|
412
711
|
}
|
|
712
|
+
if (liveness === "orphaned_group") {
|
|
713
|
+
if (w.orphanSignaledAt === void 0) {
|
|
714
|
+
signalWorkerProcessGroup(w.pid, "SIGTERM", { groupOnly: true });
|
|
715
|
+
ctx.log(`pie-proc: orphaned process group detected for dead worker ${w.name} (pgid ${w.pid}); sent SIGTERM`);
|
|
716
|
+
keep.push({ ...w, orphanSignaledAt: cutoff });
|
|
717
|
+
changed = true;
|
|
718
|
+
} else if (cutoff - w.orphanSignaledAt >= currentConfig().killGraceMs) {
|
|
719
|
+
signalWorkerProcessGroup(w.pid, "SIGKILL", { groupOnly: true });
|
|
720
|
+
ctx.log(`pie-proc: orphaned process group for ${w.name} (pgid ${w.pid}) survived grace window; escalated to SIGKILL`);
|
|
721
|
+
if (w.orphanEscalatedAt === void 0) {
|
|
722
|
+
keep.push({ ...w, orphanEscalatedAt: cutoff });
|
|
723
|
+
changed = true;
|
|
724
|
+
} else {
|
|
725
|
+
keep.push(w);
|
|
726
|
+
}
|
|
727
|
+
} else {
|
|
728
|
+
keep.push(w);
|
|
729
|
+
}
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
413
732
|
const ttl = w.kind === "resident" ? w.ttlMs ?? currentConfig().defaultTtlMs : 0;
|
|
414
733
|
if (ttl > 0 && liveness === "alive" && cutoff - Math.max(w.lastActiveAt, observeActivity(w)) > ttl) {
|
|
415
|
-
|
|
416
|
-
process.kill(w.pid, "SIGTERM");
|
|
417
|
-
} catch {
|
|
418
|
-
}
|
|
734
|
+
signalWorkerProcessGroup(w.pid, "SIGTERM");
|
|
419
735
|
ctx.log(`pie-proc: idle TTL signaled worker ${w.name} (idle > ${Math.round(ttl / 1e3)}s, identity verified)`);
|
|
420
|
-
keep.push({ ...w, ttlMs: 0 });
|
|
736
|
+
keep.push({ ...w, ttlMs: 0, orphanSignaledAt: cutoff });
|
|
421
737
|
changed = true;
|
|
422
738
|
continue;
|
|
423
739
|
}
|
|
@@ -450,11 +766,11 @@ function pieProc(ctx) {
|
|
|
450
766
|
if (params.resumeSessionId) {
|
|
451
767
|
if (!/^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(params.resumeSessionId)) throw new Error(`invalid resumeSessionId "${params.resumeSessionId}"`);
|
|
452
768
|
const operatorSessionsDir = resolveOperatorSessionsDir();
|
|
453
|
-
const workerSessionsDir =
|
|
769
|
+
const workerSessionsDir = path2.join(pieProcDir(), "agents", params.name, "sessions");
|
|
454
770
|
let recordedCwd;
|
|
455
771
|
for (const dir of [workerSessionsDir, operatorSessionsDir]) {
|
|
456
772
|
try {
|
|
457
|
-
const head = JSON.parse(
|
|
773
|
+
const head = JSON.parse(fs2.readFileSync(path2.join(dir, params.resumeSessionId, "head.json"), "utf8"));
|
|
458
774
|
recordedCwd = head.metadata?.cwd;
|
|
459
775
|
resumeSessionsDir = dir;
|
|
460
776
|
break;
|
|
@@ -465,7 +781,7 @@ function pieProc(ctx) {
|
|
|
465
781
|
if (typeof recordedCwd !== "string" || !recordedCwd) throw new Error(`session "${params.resumeSessionId}" has no recorded cwd; resume requires one`);
|
|
466
782
|
let canonicalRecorded = recordedCwd;
|
|
467
783
|
try {
|
|
468
|
-
canonicalRecorded =
|
|
784
|
+
canonicalRecorded = fs2.realpathSync(recordedCwd);
|
|
469
785
|
} catch {
|
|
470
786
|
}
|
|
471
787
|
if (canonicalRecorded !== canonicalCwd) throw new Error(`resume cwd mismatch: session recorded "${recordedCwd}" but spawn cwd is "${params.cwd}" \u2014 resume in the session's own directory`);
|
|
@@ -542,21 +858,21 @@ function pieProc(ctx) {
|
|
|
542
858
|
});
|
|
543
859
|
let child;
|
|
544
860
|
try {
|
|
545
|
-
const pieDir =
|
|
546
|
-
|
|
861
|
+
const pieDir = path2.join(pieProcDir(), "agents", params.name);
|
|
862
|
+
fs2.mkdirSync(pieDir, { recursive: true });
|
|
547
863
|
for (const file of ["models.json", "config.json", "auth.json"]) {
|
|
548
|
-
const dst =
|
|
549
|
-
const src =
|
|
550
|
-
if (!
|
|
864
|
+
const dst = path2.join(pieDir, file);
|
|
865
|
+
const src = path2.join(configDirRoot(), file);
|
|
866
|
+
if (!fs2.existsSync(dst) && fs2.existsSync(src)) {
|
|
551
867
|
try {
|
|
552
|
-
|
|
868
|
+
fs2.copyFileSync(src, dst);
|
|
553
869
|
} catch {
|
|
554
870
|
}
|
|
555
871
|
}
|
|
556
872
|
}
|
|
557
873
|
if (imForward) {
|
|
558
|
-
const imFile =
|
|
559
|
-
if (!
|
|
874
|
+
const imFile = path2.join(pieDir, "im-forward.json");
|
|
875
|
+
if (!fs2.existsSync(imFile)) {
|
|
560
876
|
const provider = typeof imForward.provider === "string" && imForward.provider.trim() ? imForward.provider : "feishu";
|
|
561
877
|
const providerSettings = {};
|
|
562
878
|
for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
|
|
@@ -568,11 +884,11 @@ function pieProc(ctx) {
|
|
|
568
884
|
providers: { [provider]: providerSettings }
|
|
569
885
|
};
|
|
570
886
|
if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
|
|
571
|
-
|
|
887
|
+
fs2.writeFileSync(imFile, JSON.stringify(doc, null, " "));
|
|
572
888
|
}
|
|
573
889
|
}
|
|
574
|
-
|
|
575
|
-
const logFile =
|
|
890
|
+
fs2.mkdirSync(logDir(), { recursive: true });
|
|
891
|
+
const logFile = fs2.openSync(path2.join(logDir(), `${params.name}.jsonl`), "a");
|
|
576
892
|
const args = params.kind === "resident" ? [
|
|
577
893
|
...loaderArgs(),
|
|
578
894
|
entry,
|
|
@@ -586,14 +902,15 @@ function pieProc(ctx) {
|
|
|
586
902
|
// --session-id carries a reusable business session id.
|
|
587
903
|
...resumeSessionId ? ["--resume-required", "--worker-token", launchToken] : []
|
|
588
904
|
] : [...loaderArgs(), entry, "--session-id", sessionId];
|
|
589
|
-
const inheritedIpcRoot =
|
|
590
|
-
const inheritedRegistryRoot =
|
|
905
|
+
const inheritedIpcRoot = path2.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
|
|
906
|
+
const inheritedRegistryRoot = path2.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
|
|
591
907
|
const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
|
|
592
908
|
const childEnv = {
|
|
593
909
|
...inheritedEnv,
|
|
594
910
|
PIE_CODING_AGENT_DIR: pieDir,
|
|
595
911
|
PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
|
|
596
912
|
PIE_PROC_REGISTRY_ROOT: inheritedRegistryRoot,
|
|
913
|
+
[LAUNCH_TOKEN_ENV]: launchToken,
|
|
597
914
|
PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
|
|
598
915
|
};
|
|
599
916
|
if (params.kind === "oneshot") {
|
|
@@ -619,12 +936,12 @@ function pieProc(ctx) {
|
|
|
619
936
|
});
|
|
620
937
|
} finally {
|
|
621
938
|
try {
|
|
622
|
-
|
|
939
|
+
fs2.closeSync(logFile);
|
|
623
940
|
} catch {
|
|
624
941
|
}
|
|
625
942
|
}
|
|
626
943
|
if (typeof child.pid !== "number") {
|
|
627
|
-
throw new Error(`worker spawn failed (no pid) \u2014 see ${
|
|
944
|
+
throw new Error(`worker spawn failed (no pid) \u2014 see ${path2.join(logDir(), `${params.name}.jsonl`)}`);
|
|
628
945
|
}
|
|
629
946
|
child.unref();
|
|
630
947
|
const record = {
|
|
@@ -654,15 +971,18 @@ function pieProc(ctx) {
|
|
|
654
971
|
};
|
|
655
972
|
});
|
|
656
973
|
} catch (error) {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
974
|
+
if (typeof child.pid === "number") signalWorkerProcessGroup(child.pid, "SIGKILL");
|
|
975
|
+
else {
|
|
976
|
+
try {
|
|
977
|
+
child.kill("SIGKILL");
|
|
978
|
+
} catch {
|
|
979
|
+
}
|
|
660
980
|
}
|
|
661
981
|
releaseReservation(generation);
|
|
662
982
|
throw error instanceof Error ? error : new Error(String(error));
|
|
663
983
|
}
|
|
664
984
|
ctx.log(`pie-proc: spawned ${params.kind} worker "${params.name}" (pid ${record.pid}, cwd ${record.cwd}, gen ${generation})`);
|
|
665
|
-
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 ${
|
|
985
|
+
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 ${path2.join(logDir(), `${params.name}.jsonl`)}.`);
|
|
666
986
|
} catch (error) {
|
|
667
987
|
releaseReservation(generation);
|
|
668
988
|
throw error instanceof Error ? error : new Error(String(error));
|
|
@@ -672,6 +992,9 @@ function pieProc(ctx) {
|
|
|
672
992
|
let target;
|
|
673
993
|
target = readRegistryUncached().workers.find((w) => w.name === name);
|
|
674
994
|
if (!target) throw new Error(`no worker named "${name}"`);
|
|
995
|
+
if (opts.expectedGeneration && target.generation !== opts.expectedGeneration) {
|
|
996
|
+
throw new Error(`worker "${name}" generation mismatch (expected ${opts.expectedGeneration}, live ${target.generation}); refusing to signal a newer incarnation`);
|
|
997
|
+
}
|
|
675
998
|
if (target.pid === 0) {
|
|
676
999
|
return updateRegistry((snap) => {
|
|
677
1000
|
const mine = snap.workers.find((w) => w.generation === target.generation);
|
|
@@ -690,25 +1013,31 @@ function pieProc(ctx) {
|
|
|
690
1013
|
if (liveness === "unknown") {
|
|
691
1014
|
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.`);
|
|
692
1015
|
}
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
1016
|
+
const verifiedGroupOpts = { trustVerifiedGroup: true };
|
|
1017
|
+
signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", { groupOnly: liveness === "orphaned_group" });
|
|
1018
|
+
if (opts.force) {
|
|
1019
|
+
const killDeadline = Date.now() + 1500;
|
|
1020
|
+
while (Date.now() < killDeadline) {
|
|
1021
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
1022
|
+
if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
|
|
1023
|
+
}
|
|
1024
|
+
} else {
|
|
698
1025
|
const deadline = Date.now() + currentConfig().killGraceMs;
|
|
699
1026
|
while (Date.now() < deadline) {
|
|
700
|
-
await new Promise((r) => setTimeout(r,
|
|
701
|
-
if (workerLiveness(target) === "dead") break;
|
|
1027
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
1028
|
+
if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
|
|
702
1029
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1030
|
+
const afterGrace = workerLiveness(target, verifiedGroupOpts);
|
|
1031
|
+
if (afterGrace === "alive" || afterGrace === "orphaned_group") {
|
|
1032
|
+
signalWorkerProcessGroup(target.pid, "SIGKILL", { groupOnly: afterGrace === "orphaned_group" });
|
|
1033
|
+
const killDeadline = Date.now() + 1500;
|
|
1034
|
+
while (Date.now() < killDeadline) {
|
|
1035
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
1036
|
+
if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
|
|
707
1037
|
}
|
|
708
|
-
await new Promise((r) => setTimeout(r, 500));
|
|
709
1038
|
}
|
|
710
1039
|
}
|
|
711
|
-
const finalState = workerLiveness(target);
|
|
1040
|
+
const finalState = workerLiveness(target, verifiedGroupOpts);
|
|
712
1041
|
if (finalState === "dead") {
|
|
713
1042
|
updateRegistry((snap) => ({ next: snap.workers.filter((w) => w.generation !== target.generation), result: void 0 }));
|
|
714
1043
|
ctx.log(`pie-proc: killed worker "${name}" (pid ${target.pid}, gen ${target.generation})`);
|
|
@@ -721,6 +1050,33 @@ function pieProc(ctx) {
|
|
|
721
1050
|
ctx.log("pie-proc: tool not registered (role-pruned; manager-only)");
|
|
722
1051
|
return;
|
|
723
1052
|
}
|
|
1053
|
+
const unregisterPanelBridge = registerPieProcPanelBridge({
|
|
1054
|
+
pieProcDir,
|
|
1055
|
+
operatorSessionsDir: resolveOperatorSessionsDir,
|
|
1056
|
+
allowCwd: () => currentConfig().allowCwd,
|
|
1057
|
+
cwdAllowedOrThrow,
|
|
1058
|
+
safeName,
|
|
1059
|
+
readWorkers: () => readRegistryUncached().workers,
|
|
1060
|
+
workerLiveness: (w) => workerLiveness(w),
|
|
1061
|
+
removeGenerationIfDead: (w) => {
|
|
1062
|
+
if (workerLiveness(w) !== "dead") return false;
|
|
1063
|
+
updateRegistry((snap) => ({ next: snap.workers.filter((item) => item.generation !== w.generation), result: void 0 }));
|
|
1064
|
+
return true;
|
|
1065
|
+
},
|
|
1066
|
+
killWorker,
|
|
1067
|
+
canInheritImForward: () => {
|
|
1068
|
+
try {
|
|
1069
|
+
sanitizeImForward("inherit");
|
|
1070
|
+
return true;
|
|
1071
|
+
} catch {
|
|
1072
|
+
return false;
|
|
1073
|
+
}
|
|
1074
|
+
},
|
|
1075
|
+
spawnResumeWorker: ({ name, cwd, resumeSessionId, inheritIm }) => spawnWorker({ name, cwd, kind: "resident", resumeSessionId, ...inheritIm ? { imForward: "inherit" } : {} })
|
|
1076
|
+
});
|
|
1077
|
+
ctx.registerCleanup?.(() => {
|
|
1078
|
+
unregisterPanelBridge();
|
|
1079
|
+
});
|
|
724
1080
|
ctx.registerTool({
|
|
725
1081
|
name: "pie_proc",
|
|
726
1082
|
label: "Pie worker processes",
|