@cydm/pie 4.8.0 → 4.10.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 +906 -158
- package/dist/builtin/extensions/im-forward/README.md +4 -2
- package/dist/builtin/extensions/im-forward/index.js +6875 -3972
- 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 +285 -61
- package/dist/builtin/extensions/pie-proc/README.md +7 -7
- package/dist/builtin/extensions/pie-proc/index.js +493 -107
- 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 +26 -24
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
- 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-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
- package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +367 -65
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
- package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
- package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-5QMS6RQC.js} +353 -287
- package/dist/chunks/chunk-6WKBQZWM.js +19 -0
- package/dist/chunks/{chunk-LAJXWOKS.js → chunk-7LICWWUE.js} +11 -9
- package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BQWHLYYZ.js} +4 -3
- package/dist/chunks/{chunk-4PR34UZF.js → chunk-BTUMBUDU.js} +159 -145
- package/dist/chunks/{chunk-NHV2CALB.js → chunk-FC5AN5QP.js} +409 -32
- package/dist/chunks/{chunk-3W3SXVPB.js → chunk-G2K4GY6N.js} +993 -371
- package/dist/chunks/{chunk-BLDI2GRF.js → chunk-HK3FHIAH.js} +1364 -446
- package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
- package/dist/chunks/{chunk-CGSFBWOM.js → chunk-KWK7KTSZ.js} +4 -3
- package/dist/chunks/chunk-OU33ROFD.js +717 -0
- package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-XMTRKMBG.js} +104 -22
- package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-3TEMOQM5.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-QKJ3YVDS.js} +2 -2
- package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-N2ZZQLTZ.js} +5 -5
- package/dist/chunks/{src-EGXFJ3WA.js → src-3PSR2AAX.js} +3 -3
- package/dist/chunks/{src-B44QWSGM.js → src-D5GN4Q5O.js} +2 -2
- package/dist/chunks/{src-CLE5ILN4.js → src-F5N6O2HR.js} +20 -4
- package/dist/chunks/{src-Q7LU27C2.js → src-TIDKYA5F.js} +31 -1
- package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-JAJHK44G.js} +2 -2
- package/dist/cli.js +4123 -2389
- package/models.schema.json +271 -0
- package/package.json +2 -2
- package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
- package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
- package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
|
@@ -1,12 +1,19 @@
|
|
|
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-KWK7KTSZ.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 {
|
|
13
|
+
loadResolvedModelsConfig
|
|
14
|
+
} from "../../../chunks/chunk-FC5AN5QP.js";
|
|
15
|
+
import "../../../chunks/chunk-CBDQJMUI.js";
|
|
16
|
+
import "../../../chunks/chunk-G2K4GY6N.js";
|
|
10
17
|
import {
|
|
11
18
|
Type
|
|
12
19
|
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
@@ -16,9 +23,367 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
|
16
23
|
import { execFileSync, spawn } from "node:child_process";
|
|
17
24
|
import { createRequire } from "node:module";
|
|
18
25
|
import { fileURLToPath } from "node:url";
|
|
19
|
-
import * as
|
|
26
|
+
import * as fs3 from "node:fs";
|
|
20
27
|
import * as os from "node:os";
|
|
28
|
+
import * as path3 from "node:path";
|
|
29
|
+
|
|
30
|
+
// builtin/extensions/pie-proc/panel-bridge.ts
|
|
31
|
+
import * as fs from "node:fs";
|
|
21
32
|
import * as path from "node:path";
|
|
33
|
+
var VALID_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/;
|
|
34
|
+
function readSessionHeadCwd(headFile) {
|
|
35
|
+
try {
|
|
36
|
+
const head = JSON.parse(fs.readFileSync(headFile, "utf8"));
|
|
37
|
+
return typeof head.metadata?.cwd === "string" && head.metadata.cwd.trim() ? head.metadata.cwd.trim() : void 0;
|
|
38
|
+
} catch {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function toInfo(w, deps) {
|
|
43
|
+
return {
|
|
44
|
+
name: w.name,
|
|
45
|
+
sessionId: w.sessionId,
|
|
46
|
+
generation: w.generation,
|
|
47
|
+
cwd: w.cwd,
|
|
48
|
+
kind: w.kind,
|
|
49
|
+
pid: w.pid,
|
|
50
|
+
liveness: w.pid === 0 ? "pending" : deps.workerLiveness(w)
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function deriveSafeWorkerName(sessionId, preferred, deps) {
|
|
54
|
+
if (preferred && deps.safeName(preferred)) return preferred;
|
|
55
|
+
const slug = sessionId.replace(/[^a-z0-9-_]/gi, "").toLowerCase().slice(-24) || "worker";
|
|
56
|
+
const candidate = `w-${slug}`.slice(0, 48);
|
|
57
|
+
return deps.safeName(candidate) ? candidate : "w-resumed";
|
|
58
|
+
}
|
|
59
|
+
function findSessionSource(sessionId, deps) {
|
|
60
|
+
if (!VALID_SESSION_ID.test(sessionId)) return void 0;
|
|
61
|
+
const workers = deps.readWorkers();
|
|
62
|
+
const fromRegistry = workers.find((w) => w.sessionId === sessionId);
|
|
63
|
+
if (fromRegistry) return { name: fromRegistry.name, cwd: fromRegistry.cwd };
|
|
64
|
+
const agentsDir = path.join(deps.pieProcDir(), "agents");
|
|
65
|
+
try {
|
|
66
|
+
for (const entry of fs.readdirSync(agentsDir, { withFileTypes: true })) {
|
|
67
|
+
if (!entry.isDirectory() || !deps.safeName(entry.name)) continue;
|
|
68
|
+
const cwd = readSessionHeadCwd(path.join(agentsDir, entry.name, "sessions", sessionId, "head.json"));
|
|
69
|
+
if (cwd) return { name: entry.name, cwd };
|
|
70
|
+
}
|
|
71
|
+
} catch {
|
|
72
|
+
}
|
|
73
|
+
const globalCwd = readSessionHeadCwd(path.join(deps.operatorSessionsDir(), sessionId, "head.json"));
|
|
74
|
+
if (globalCwd) return { name: deriveSafeWorkerName(sessionId, void 0, deps), cwd: globalCwd };
|
|
75
|
+
return void 0;
|
|
76
|
+
}
|
|
77
|
+
function registerPieProcPanelBridge(deps) {
|
|
78
|
+
const inspectResumable = (sessionId) => {
|
|
79
|
+
const found = findSessionSource(sessionId, deps);
|
|
80
|
+
if (!found) return void 0;
|
|
81
|
+
try {
|
|
82
|
+
const canonical = deps.cwdAllowedOrThrow(found.cwd, deps.allowCwd());
|
|
83
|
+
const holder = liveSessionHolder(sessionId);
|
|
84
|
+
if (holder) {
|
|
85
|
+
return { sessionId, name: found.name, cwd: canonical, allowed: false, reason: `session is already owned by a live host (pid ${holder.pid})` };
|
|
86
|
+
}
|
|
87
|
+
return { sessionId, name: found.name, cwd: canonical, allowed: true };
|
|
88
|
+
} catch (error) {
|
|
89
|
+
return { sessionId, name: found.name, cwd: found.cwd, allowed: false, reason: error instanceof Error ? error.message : String(error) };
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
return registerWorkerLifecycleBridge({
|
|
93
|
+
lookupBySession: (sessionId) => {
|
|
94
|
+
try {
|
|
95
|
+
const found = deps.readWorkers().find((w) => w.sessionId === sessionId);
|
|
96
|
+
return found ? toInfo(found, deps) : void 0;
|
|
97
|
+
} catch {
|
|
98
|
+
return void 0;
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
lookupByName: (name) => {
|
|
102
|
+
try {
|
|
103
|
+
const found = deps.readWorkers().find((w) => w.name === name);
|
|
104
|
+
return found ? toInfo(found, deps) : void 0;
|
|
105
|
+
} catch {
|
|
106
|
+
return void 0;
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
inspectResumable,
|
|
110
|
+
cleanupDeadWorker: (sessionIdOrName) => {
|
|
111
|
+
try {
|
|
112
|
+
const found = deps.readWorkers().find((w) => w.sessionId === sessionIdOrName || w.name === sessionIdOrName);
|
|
113
|
+
if (!found || found.pid === 0) return false;
|
|
114
|
+
return deps.removeGenerationIfDead(found);
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
killWorker: async (name, opts) => {
|
|
120
|
+
try {
|
|
121
|
+
if (opts?.expectedGeneration) {
|
|
122
|
+
const current = deps.readWorkers().find((w) => w.name === name);
|
|
123
|
+
if (!current || current.generation !== opts.expectedGeneration) {
|
|
124
|
+
return { ok: false, detail: `Worker "${name}" incarnation changed since the confirmation card was issued; refusing to signal a newer worker.` };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const res = await deps.killWorker(name, opts);
|
|
128
|
+
return { ok: res.isError !== true, detail: res.content[0]?.text ?? "done" };
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return { ok: false, detail: error instanceof Error ? error.message : String(error) };
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
resumeWorker: async (sessionId) => {
|
|
134
|
+
const info = inspectResumable(sessionId);
|
|
135
|
+
if (!info) return { ok: false, detail: `Session "${sessionId}" not found in worker or operator stores.` };
|
|
136
|
+
if (!info.allowed) return { ok: false, detail: info.reason ?? "Resume not permitted by pie-proc allowCwd policy." };
|
|
137
|
+
try {
|
|
138
|
+
const hasWorkerIm = fs.existsSync(path.join(deps.pieProcDir(), "agents", info.name, "im-forward.json"));
|
|
139
|
+
const inheritIm = !hasWorkerIm && deps.canInheritImForward();
|
|
140
|
+
const res = await deps.spawnResumeWorker({ name: info.name, cwd: info.cwd, resumeSessionId: sessionId, inheritIm });
|
|
141
|
+
const detail = res.content[0]?.text ?? "spawned";
|
|
142
|
+
const pidMatch = /\bpid (\d+)\b/.exec(detail);
|
|
143
|
+
return { ok: res.isError !== true, detail, name: info.name, ...pidMatch ? { pid: Number(pidMatch[1]) } : {} };
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return { ok: false, detail: error instanceof Error ? error.message : String(error) };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// builtin/extensions/pie-proc/spawn-model.ts
|
|
152
|
+
import * as fs2 from "node:fs";
|
|
153
|
+
import * as path2 from "node:path";
|
|
154
|
+
var SPAWN_THINKING_LEVELS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
155
|
+
var MODEL_REF_RE = /^[^/\s]+\/\S+$/;
|
|
156
|
+
function collectModelRefsFromRaw(raw) {
|
|
157
|
+
const refs = /* @__PURE__ */ new Set();
|
|
158
|
+
if (!raw || typeof raw !== "object") return refs;
|
|
159
|
+
const doc = raw;
|
|
160
|
+
if (doc.providers && typeof doc.providers === "object") {
|
|
161
|
+
for (const [provider, cfg] of Object.entries(doc.providers)) {
|
|
162
|
+
if (!Array.isArray(cfg?.models)) continue;
|
|
163
|
+
for (const m of cfg.models) {
|
|
164
|
+
if (typeof m?.id === "string" && m.id.trim()) {
|
|
165
|
+
refs.add(`${provider.trim()}/${m.id.trim()}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (doc.defaults && typeof doc.defaults === "object") {
|
|
171
|
+
if (typeof doc.defaults.provider === "string" && typeof doc.defaults.modelId === "string") {
|
|
172
|
+
refs.add(`${doc.defaults.provider.trim()}/${doc.defaults.modelId.trim()}`);
|
|
173
|
+
}
|
|
174
|
+
if (doc.defaults.modelClasses && typeof doc.defaults.modelClasses === "object") {
|
|
175
|
+
for (const cls of Object.values(doc.defaults.modelClasses)) {
|
|
176
|
+
if (typeof cls?.provider === "string" && typeof cls?.modelId === "string") {
|
|
177
|
+
refs.add(`${cls.provider.trim()}/${cls.modelId.trim()}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return refs;
|
|
183
|
+
}
|
|
184
|
+
function readKnownModelRefs(modelsPath) {
|
|
185
|
+
if (!fs2.existsSync(modelsPath)) return void 0;
|
|
186
|
+
try {
|
|
187
|
+
const resolved = loadResolvedModelsConfig(modelsPath);
|
|
188
|
+
const refs = collectModelRefsFromRaw(resolved.config);
|
|
189
|
+
if (refs.size > 0) return refs;
|
|
190
|
+
} catch {
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
const raw = JSON.parse(fs2.readFileSync(modelsPath, "utf8"));
|
|
194
|
+
const refs = collectModelRefsFromRaw(raw);
|
|
195
|
+
return refs.size > 0 ? refs : void 0;
|
|
196
|
+
} catch {
|
|
197
|
+
return void 0;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function validateSpawnModelParams(opts) {
|
|
201
|
+
let model;
|
|
202
|
+
let thinkingLevel;
|
|
203
|
+
if (opts.thinkingLevel !== void 0) {
|
|
204
|
+
const normalized = opts.thinkingLevel.trim();
|
|
205
|
+
if (!SPAWN_THINKING_LEVELS.has(normalized)) {
|
|
206
|
+
throw new Error(`invalid thinkingLevel "${opts.thinkingLevel}" (expected one of: ${[...SPAWN_THINKING_LEVELS].join(", ")})`);
|
|
207
|
+
}
|
|
208
|
+
thinkingLevel = normalized;
|
|
209
|
+
}
|
|
210
|
+
if (opts.model !== void 0) {
|
|
211
|
+
const normalized = opts.model.trim();
|
|
212
|
+
if (!MODEL_REF_RE.test(normalized)) {
|
|
213
|
+
throw new Error(`invalid model "${opts.model}" (expected "provider/modelId")`);
|
|
214
|
+
}
|
|
215
|
+
const workerModels = path2.join(opts.pieDir, "models.json");
|
|
216
|
+
const parentModels = path2.join(opts.parentConfigDir, "models.json");
|
|
217
|
+
const known = readKnownModelRefs(workerModels) ?? readKnownModelRefs(parentModels);
|
|
218
|
+
if (known && known.size > 0) {
|
|
219
|
+
if (known.has(normalized)) {
|
|
220
|
+
model = normalized;
|
|
221
|
+
} else {
|
|
222
|
+
const lowerTarget = normalized.toLowerCase();
|
|
223
|
+
const ciMatches = [...known].filter((ref) => ref.toLowerCase() === lowerTarget);
|
|
224
|
+
if (ciMatches.length === 1) {
|
|
225
|
+
model = ciMatches[0];
|
|
226
|
+
} else if (ciMatches.length > 1) {
|
|
227
|
+
throw new Error(`model "${normalized}" is ambiguous (matches: ${ciMatches.join(", ")}); use exact casing`);
|
|
228
|
+
} else {
|
|
229
|
+
const sample = [...known].slice(0, 8).join(", ");
|
|
230
|
+
throw new Error(`model "${normalized}" not found in models.json (available examples: ${sample})`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
} else {
|
|
234
|
+
model = normalized;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return { model, thinkingLevel };
|
|
238
|
+
}
|
|
239
|
+
function readSettingsDefaults(settingsPath) {
|
|
240
|
+
try {
|
|
241
|
+
if (!fs2.existsSync(settingsPath)) return {};
|
|
242
|
+
const raw = JSON.parse(fs2.readFileSync(settingsPath, "utf8"));
|
|
243
|
+
const provider = typeof raw.defaultProvider === "string" ? raw.defaultProvider.trim() : "";
|
|
244
|
+
const modelId = typeof raw.defaultModel === "string" ? raw.defaultModel.trim() : "";
|
|
245
|
+
const thinking = typeof raw.defaultThinkingLevel === "string" && SPAWN_THINKING_LEVELS.has(raw.defaultThinkingLevel.trim()) ? raw.defaultThinkingLevel.trim() : void 0;
|
|
246
|
+
return {
|
|
247
|
+
...provider && modelId ? { model: `${provider}/${modelId}` } : {},
|
|
248
|
+
...thinking ? { thinkingLevel: thinking } : {}
|
|
249
|
+
};
|
|
250
|
+
} catch {
|
|
251
|
+
return {};
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function readModelsJsonDefault(modelsPath) {
|
|
255
|
+
const known = readKnownModelRefs(modelsPath);
|
|
256
|
+
if (!known || known.size === 0) return void 0;
|
|
257
|
+
try {
|
|
258
|
+
const raw = JSON.parse(fs2.readFileSync(modelsPath, "utf8"));
|
|
259
|
+
if (typeof raw.defaults?.provider === "string" && typeof raw.defaults?.modelId === "string") {
|
|
260
|
+
const ref = `${raw.defaults.provider.trim()}/${raw.defaults.modelId.trim()}`;
|
|
261
|
+
if (MODEL_REF_RE.test(ref)) return ref;
|
|
262
|
+
}
|
|
263
|
+
} catch {
|
|
264
|
+
}
|
|
265
|
+
return [...known][0];
|
|
266
|
+
}
|
|
267
|
+
function readSessionHeadModel(sessionsDir, sessionId) {
|
|
268
|
+
try {
|
|
269
|
+
const headPath = path2.join(sessionsDir, sessionId, "head.json");
|
|
270
|
+
if (!fs2.existsSync(headPath)) return {};
|
|
271
|
+
const parsed = JSON.parse(fs2.readFileSync(headPath, "utf8"));
|
|
272
|
+
const meta = parsed.metadata;
|
|
273
|
+
const provider = typeof meta?.provider === "string" ? meta.provider.trim() : "";
|
|
274
|
+
const modelId = typeof meta?.modelId === "string" ? meta.modelId.trim() : "";
|
|
275
|
+
const thinking = typeof meta?.thinkingLevel === "string" && SPAWN_THINKING_LEVELS.has(meta.thinkingLevel.trim()) ? meta.thinkingLevel.trim() : void 0;
|
|
276
|
+
return {
|
|
277
|
+
...provider && modelId ? { model: `${provider}/${modelId}` } : {},
|
|
278
|
+
...thinking ? { thinkingLevel: thinking } : {}
|
|
279
|
+
};
|
|
280
|
+
} catch {
|
|
281
|
+
return {};
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function predictWorkerModel(opts) {
|
|
285
|
+
const projectDefaults = readSettingsDefaults(path2.join(opts.cwd, ".pie", "settings.json"));
|
|
286
|
+
const workerDefaults = readSettingsDefaults(path2.join(opts.pieDir, "settings.json"));
|
|
287
|
+
const fallbackModel = readModelsJsonDefault(path2.join(opts.pieDir, "models.json"));
|
|
288
|
+
const model = opts.explicitModel ?? opts.resumed?.model ?? projectDefaults.model ?? workerDefaults.model ?? fallbackModel;
|
|
289
|
+
const thinkingLevel = opts.explicitThinking ?? opts.resumed?.thinkingLevel ?? projectDefaults.thinkingLevel ?? workerDefaults.thinkingLevel;
|
|
290
|
+
return { model, thinkingLevel };
|
|
291
|
+
}
|
|
292
|
+
function isPidAlive(pid) {
|
|
293
|
+
if (!Number.isSafeInteger(pid) || pid <= 1) return false;
|
|
294
|
+
try {
|
|
295
|
+
process.kill(pid, 0);
|
|
296
|
+
return true;
|
|
297
|
+
} catch (error) {
|
|
298
|
+
return error.code === "EPERM";
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function readLiveWorkerPeer(ipcRoot, sessionId, pid) {
|
|
302
|
+
try {
|
|
303
|
+
const dir = path2.join(ipcRoot, "run", "ipc");
|
|
304
|
+
if (!fs2.existsSync(dir)) return void 0;
|
|
305
|
+
for (const file of fs2.readdirSync(dir)) {
|
|
306
|
+
if (!file.endsWith(".json")) continue;
|
|
307
|
+
try {
|
|
308
|
+
const parsed = JSON.parse(fs2.readFileSync(path2.join(dir, file), "utf8"));
|
|
309
|
+
if (parsed.pid !== pid || parsed.sessionId !== sessionId) continue;
|
|
310
|
+
if (!isPidAlive(pid)) return void 0;
|
|
311
|
+
return {
|
|
312
|
+
model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0,
|
|
313
|
+
thinkingLevel: typeof parsed.thinkingLevel === "string" && parsed.thinkingLevel ? parsed.thinkingLevel : void 0,
|
|
314
|
+
effectiveThinkingLevel: typeof parsed.effectiveThinkingLevel === "string" && parsed.effectiveThinkingLevel ? parsed.effectiveThinkingLevel : void 0,
|
|
315
|
+
state: typeof parsed.state === "string" && parsed.state ? parsed.state : void 0
|
|
316
|
+
};
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
} catch {
|
|
321
|
+
}
|
|
322
|
+
return void 0;
|
|
323
|
+
}
|
|
324
|
+
async function waitForWorkerIpcReady(opts) {
|
|
325
|
+
const rawEnv = process.env.PIE_PROC_SPAWN_READY_WAIT_MS;
|
|
326
|
+
const envWait = rawEnv !== void 0 ? Number(rawEnv) : Number.NaN;
|
|
327
|
+
const timeoutMs = Number.isFinite(envWait) && envWait >= 0 ? envWait : opts.timeoutMs ?? 3e3;
|
|
328
|
+
const pollMs = opts.pollIntervalMs ?? 100;
|
|
329
|
+
if (timeoutMs <= 0) {
|
|
330
|
+
return { peer: readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid), exitedEarly: !isPidAlive(opts.pid) };
|
|
331
|
+
}
|
|
332
|
+
const deadline = Date.now() + timeoutMs;
|
|
333
|
+
while (Date.now() <= deadline) {
|
|
334
|
+
const peer = readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid);
|
|
335
|
+
if (peer) return { peer, exitedEarly: false };
|
|
336
|
+
if (!isPidAlive(opts.pid)) return { exitedEarly: true };
|
|
337
|
+
const remaining = deadline - Date.now();
|
|
338
|
+
if (remaining <= 0) break;
|
|
339
|
+
await new Promise((resolve2) => setTimeout(resolve2, Math.min(pollMs, remaining)));
|
|
340
|
+
}
|
|
341
|
+
return { peer: readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid), exitedEarly: !isPidAlive(opts.pid) };
|
|
342
|
+
}
|
|
343
|
+
function formatSpawnModelSummary(opts) {
|
|
344
|
+
const model = opts.livePeer?.model ?? opts.predicted.model ?? "unconfigured";
|
|
345
|
+
const thinking = opts.livePeer?.effectiveThinkingLevel ?? opts.livePeer?.thinkingLevel ?? opts.predicted.thinkingLevel;
|
|
346
|
+
const base = thinking ? `${model} (${thinking})` : model;
|
|
347
|
+
if (opts.kind === "resident" && !opts.livePeer) return `${base} [starting]`;
|
|
348
|
+
return base;
|
|
349
|
+
}
|
|
350
|
+
async function buildSpawnReceipt(opts) {
|
|
351
|
+
const resumed = opts.resumeSessionId && opts.resumeSessionsDir ? readSessionHeadModel(opts.resumeSessionsDir, opts.resumeSessionId) : void 0;
|
|
352
|
+
const predicted = predictWorkerModel({
|
|
353
|
+
pieDir: opts.pieDir,
|
|
354
|
+
cwd: opts.cwd,
|
|
355
|
+
explicitModel: opts.explicitModel,
|
|
356
|
+
explicitThinking: opts.explicitThinking,
|
|
357
|
+
resumed
|
|
358
|
+
});
|
|
359
|
+
const ready = opts.kind === "resident" ? await waitForWorkerIpcReady({ ipcRoot: opts.ipcRoot, sessionId: opts.sessionId, pid: opts.pid }) : { peer: void 0, exitedEarly: false };
|
|
360
|
+
const modelLabel = formatSpawnModelSummary({ livePeer: ready.peer, predicted, kind: opts.kind });
|
|
361
|
+
const bootNote = ready.exitedEarly ? " WARNING: worker process exited during startup \u2014 inspect log." : "";
|
|
362
|
+
const ttlPart = opts.kind === "resident" && opts.ttlMs ? `, idle TTL ${Math.round(opts.ttlMs / 1e3)}s` : "";
|
|
363
|
+
const text = `Spawned ${opts.kind} worker "${opts.name}" (pid ${opts.pid}, peer name "${opts.name}", session ${opts.sessionId}, model: ${modelLabel}, cwd ${opts.cwd}${ttlPart}).${bootNote} Resident workers accept ipc_send_notify by peer name "${opts.name}"; their stdout events are at ${opts.logPath}.`;
|
|
364
|
+
return { modelLabel, text };
|
|
365
|
+
}
|
|
366
|
+
function inheritWorkerConfigFiles(pieDir, parentConfigDir) {
|
|
367
|
+
for (const file of ["models.json", "config.json", "auth.json", "settings.json"]) {
|
|
368
|
+
const dst = path2.join(pieDir, file);
|
|
369
|
+
const src = path2.join(parentConfigDir, file);
|
|
370
|
+
if (!fs2.existsSync(dst) && fs2.existsSync(src)) {
|
|
371
|
+
try {
|
|
372
|
+
fs2.copyFileSync(src, dst);
|
|
373
|
+
} catch {
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
function liveWorkerModelLabel(ipcRoot, sessionId, pid) {
|
|
379
|
+
if (pid <= 0) return void 0;
|
|
380
|
+
const peer = readLiveWorkerPeer(ipcRoot, sessionId, pid);
|
|
381
|
+
if (!peer?.model) return void 0;
|
|
382
|
+
const lvl = peer.effectiveThinkingLevel ?? peer.thinkingLevel;
|
|
383
|
+
return lvl ? `${peer.model} (${lvl})` : peer.model;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// builtin/extensions/pie-proc/index.ts
|
|
22
387
|
var require_ = createRequire(import.meta.url);
|
|
23
388
|
function resolveOperatorSessionsDir() {
|
|
24
389
|
try {
|
|
@@ -27,11 +392,11 @@ function resolveOperatorSessionsDir() {
|
|
|
27
392
|
} catch {
|
|
28
393
|
const override = process.env.PIE_SESSIONS_DIR;
|
|
29
394
|
if (override !== void 0 && override !== "") {
|
|
30
|
-
if (override === "~") return
|
|
31
|
-
if (override.startsWith("~/")) return
|
|
32
|
-
if (
|
|
395
|
+
if (override === "~") return path3.join(os.homedir(), ".pie", "sessions");
|
|
396
|
+
if (override.startsWith("~/")) return path3.join(os.homedir(), override.slice(2));
|
|
397
|
+
if (path3.isAbsolute(override)) return override;
|
|
33
398
|
}
|
|
34
|
-
return
|
|
399
|
+
return path3.join(os.homedir(), ".pie", "sessions");
|
|
35
400
|
}
|
|
36
401
|
}
|
|
37
402
|
var DEFAULT_MAX_WORKERS = 50;
|
|
@@ -41,20 +406,20 @@ var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
|
|
|
41
406
|
var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
|
|
42
407
|
function configDirRoot() {
|
|
43
408
|
const env = process.env.PIE_CODING_AGENT_DIR;
|
|
44
|
-
if (!env) return
|
|
45
|
-
return
|
|
409
|
+
if (!env) return path3.join(os.homedir(), ".pie");
|
|
410
|
+
return path3.resolve(expandTilde(env));
|
|
46
411
|
}
|
|
47
412
|
function expandTilde(p) {
|
|
48
|
-
return p === "~" ? os.homedir() : p.startsWith("~/") ?
|
|
413
|
+
return p === "~" ? os.homedir() : p.startsWith("~/") ? path3.join(os.homedir(), p.slice(2)) : p;
|
|
49
414
|
}
|
|
50
415
|
function configCandidates() {
|
|
51
|
-
const candidates = [
|
|
416
|
+
const candidates = [path3.join(configDirRoot(), "pie-proc.json")];
|
|
52
417
|
const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
|
|
53
418
|
if (pinnedRoot) {
|
|
54
|
-
const pinDerived =
|
|
419
|
+
const pinDerived = path3.join(path3.dirname(path3.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
|
|
55
420
|
if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
|
|
56
|
-
} else if (configDirRoot() !==
|
|
57
|
-
candidates.push(
|
|
421
|
+
} else if (configDirRoot() !== path3.join(os.homedir(), ".pie")) {
|
|
422
|
+
candidates.push(path3.join(os.homedir(), ".pie", "pie-proc.json"));
|
|
58
423
|
}
|
|
59
424
|
return candidates;
|
|
60
425
|
}
|
|
@@ -62,7 +427,7 @@ function readConfig() {
|
|
|
62
427
|
const candidates = configCandidates();
|
|
63
428
|
for (const file of candidates) {
|
|
64
429
|
try {
|
|
65
|
-
const raw = JSON.parse(
|
|
430
|
+
const raw = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
66
431
|
return {
|
|
67
432
|
allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
|
|
68
433
|
maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
|
|
@@ -70,21 +435,21 @@ function readConfig() {
|
|
|
70
435
|
defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
|
|
71
436
|
};
|
|
72
437
|
} catch {
|
|
73
|
-
if (
|
|
438
|
+
if (fs3.existsSync(file)) return { ...DEFAULT_CONFIG };
|
|
74
439
|
}
|
|
75
440
|
}
|
|
76
441
|
return { ...DEFAULT_CONFIG };
|
|
77
442
|
}
|
|
78
443
|
function pieProcDir() {
|
|
79
444
|
const pinned = process.env.PIE_PROC_REGISTRY_ROOT;
|
|
80
|
-
if (pinned) return
|
|
81
|
-
return
|
|
445
|
+
if (pinned) return path3.resolve(expandTilde(pinned));
|
|
446
|
+
return path3.join(configDirRoot(), "pie-proc");
|
|
82
447
|
}
|
|
83
448
|
function registryFile() {
|
|
84
|
-
return
|
|
449
|
+
return path3.join(pieProcDir(), "workers.json");
|
|
85
450
|
}
|
|
86
451
|
function revisionFile(n) {
|
|
87
|
-
return
|
|
452
|
+
return path3.join(pieProcDir(), `workers.r${n}.json`);
|
|
88
453
|
}
|
|
89
454
|
function parseRegistry(rawText, file, revision) {
|
|
90
455
|
let raw;
|
|
@@ -116,7 +481,7 @@ function parseRegistry(rawText, file, revision) {
|
|
|
116
481
|
function latestRevisionOnDisk() {
|
|
117
482
|
let max = 0;
|
|
118
483
|
try {
|
|
119
|
-
for (const entry of
|
|
484
|
+
for (const entry of fs3.readdirSync(pieProcDir())) {
|
|
120
485
|
const match = /^workers\.r(\d+)\.json$/.exec(entry);
|
|
121
486
|
if (match) max = Math.max(max, Number(match[1]));
|
|
122
487
|
}
|
|
@@ -130,7 +495,7 @@ function readRegistryUncached() {
|
|
|
130
495
|
if (latest > 0) {
|
|
131
496
|
const file2 = revisionFile(latest);
|
|
132
497
|
try {
|
|
133
|
-
return parseRegistry(
|
|
498
|
+
return parseRegistry(fs3.readFileSync(file2, "utf8"), file2, latest);
|
|
134
499
|
} catch (error) {
|
|
135
500
|
if (error.code === "ENOENT") continue;
|
|
136
501
|
throw error;
|
|
@@ -138,7 +503,7 @@ function readRegistryUncached() {
|
|
|
138
503
|
}
|
|
139
504
|
const file = registryFile();
|
|
140
505
|
try {
|
|
141
|
-
return parseRegistry(
|
|
506
|
+
return parseRegistry(fs3.readFileSync(file, "utf8"), file, 0);
|
|
142
507
|
} catch (error) {
|
|
143
508
|
if (error.code === "ENOENT") return { revision: 0, workers: [] };
|
|
144
509
|
throw error;
|
|
@@ -149,7 +514,7 @@ function readRegistryUncached() {
|
|
|
149
514
|
function compactRevisions(_current) {
|
|
150
515
|
}
|
|
151
516
|
function casRegistry(mutate) {
|
|
152
|
-
|
|
517
|
+
fs3.mkdirSync(pieProcDir(), { recursive: true });
|
|
153
518
|
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
154
519
|
const snapshot = readRegistryUncached();
|
|
155
520
|
const outcome = mutate(snapshot);
|
|
@@ -160,26 +525,26 @@ function casRegistry(mutate) {
|
|
|
160
525
|
const nextRevision = snapshot.revision + 1;
|
|
161
526
|
const target = revisionFile(nextRevision);
|
|
162
527
|
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}-${attempt}.tmp`;
|
|
163
|
-
|
|
528
|
+
fs3.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
|
|
164
529
|
if (latestRevisionOnDisk() > snapshot.revision) {
|
|
165
530
|
try {
|
|
166
|
-
|
|
531
|
+
fs3.rmSync(tmp, { force: true });
|
|
167
532
|
} catch {
|
|
168
533
|
}
|
|
169
534
|
continue;
|
|
170
535
|
}
|
|
171
536
|
try {
|
|
172
|
-
|
|
537
|
+
fs3.linkSync(tmp, target);
|
|
173
538
|
} catch (error) {
|
|
174
539
|
try {
|
|
175
|
-
|
|
540
|
+
fs3.rmSync(tmp, { force: true });
|
|
176
541
|
} catch {
|
|
177
542
|
}
|
|
178
543
|
if (error.code === "EEXIST") continue;
|
|
179
544
|
throw error;
|
|
180
545
|
}
|
|
181
546
|
try {
|
|
182
|
-
|
|
547
|
+
fs3.rmSync(tmp, { force: true });
|
|
183
548
|
} catch {
|
|
184
549
|
}
|
|
185
550
|
compactRevisions(nextRevision);
|
|
@@ -273,7 +638,7 @@ function verifyProcessEnvOwnership(pid, marker, pieDir) {
|
|
|
273
638
|
if (process.platform === "linux") {
|
|
274
639
|
let raw2;
|
|
275
640
|
try {
|
|
276
|
-
raw2 =
|
|
641
|
+
raw2 = fs3.readFileSync(`/proc/${pid}/environ`, "utf8");
|
|
277
642
|
} catch {
|
|
278
643
|
return "unverified";
|
|
279
644
|
}
|
|
@@ -343,9 +708,9 @@ function workerLiveness(record, opts = {}) {
|
|
|
343
708
|
return "dead";
|
|
344
709
|
}
|
|
345
710
|
function canonicalDir(dir) {
|
|
346
|
-
const resolved =
|
|
347
|
-
const real =
|
|
348
|
-
const stat =
|
|
711
|
+
const resolved = path3.resolve(expandTilde(dir));
|
|
712
|
+
const real = fs3.realpathSync(resolved);
|
|
713
|
+
const stat = fs3.statSync(real);
|
|
349
714
|
if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
|
|
350
715
|
return real;
|
|
351
716
|
}
|
|
@@ -354,19 +719,19 @@ function cwdAllowedOrThrow(cwd, allow) {
|
|
|
354
719
|
for (const root of allow) {
|
|
355
720
|
try {
|
|
356
721
|
const canonicalRoot = canonicalDir(root);
|
|
357
|
-
if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot +
|
|
722
|
+
if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path3.sep)) return canonical;
|
|
358
723
|
} catch {
|
|
359
724
|
}
|
|
360
725
|
}
|
|
361
726
|
const file = configCandidates()[0];
|
|
362
727
|
let exists = false;
|
|
363
728
|
try {
|
|
364
|
-
exists =
|
|
729
|
+
exists = fs3.existsSync(file);
|
|
365
730
|
} catch {
|
|
366
731
|
}
|
|
367
732
|
const effective = configCandidates().find((c) => {
|
|
368
733
|
try {
|
|
369
|
-
return
|
|
734
|
+
return fs3.existsSync(c);
|
|
370
735
|
} catch {
|
|
371
736
|
return false;
|
|
372
737
|
}
|
|
@@ -397,10 +762,10 @@ function sanitizeImForward(raw) {
|
|
|
397
762
|
}
|
|
398
763
|
function readUserImForwardIdentity() {
|
|
399
764
|
try {
|
|
400
|
-
const candidates = [
|
|
765
|
+
const candidates = [path3.join(configDirRoot(), "im-forward.json")];
|
|
401
766
|
for (const file of candidates) {
|
|
402
767
|
try {
|
|
403
|
-
const parsed = JSON.parse(
|
|
768
|
+
const parsed = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
404
769
|
const provider = typeof parsed.provider === "string" ? parsed.provider : "feishu";
|
|
405
770
|
const settings = parsed.providers?.[provider];
|
|
406
771
|
if (!settings) continue;
|
|
@@ -417,12 +782,12 @@ function readUserImForwardIdentity() {
|
|
|
417
782
|
return void 0;
|
|
418
783
|
}
|
|
419
784
|
function cliEntry() {
|
|
420
|
-
const moduleDir =
|
|
785
|
+
const moduleDir = path3.dirname(fileURLToPath(import.meta.url));
|
|
421
786
|
for (const rel of ["../../../src/cli.ts", "../../../cli.js"]) {
|
|
422
|
-
const candidate =
|
|
787
|
+
const candidate = path3.resolve(moduleDir, rel);
|
|
423
788
|
try {
|
|
424
|
-
const real =
|
|
425
|
-
if (
|
|
789
|
+
const real = fs3.realpathSync(candidate);
|
|
790
|
+
if (fs3.statSync(real).isFile()) return real;
|
|
426
791
|
} catch {
|
|
427
792
|
}
|
|
428
793
|
}
|
|
@@ -432,10 +797,10 @@ function loaderArgs() {
|
|
|
432
797
|
for (let i = 0; i < process.execArgv.length - 1; i += 1) {
|
|
433
798
|
if (process.execArgv[i] === "--import") {
|
|
434
799
|
const target = process.execArgv[i + 1];
|
|
435
|
-
if (target && !
|
|
800
|
+
if (target && !path3.isAbsolute(target) && !target.startsWith("file:")) {
|
|
436
801
|
try {
|
|
437
|
-
const pkgRoot =
|
|
438
|
-
return ["--import",
|
|
802
|
+
const pkgRoot = path3.dirname(require_.resolve(`${target}/package.json`, { paths: [path3.dirname(cliEntry())] }));
|
|
803
|
+
return ["--import", path3.join(pkgRoot, "dist", "loader.mjs")];
|
|
439
804
|
} catch {
|
|
440
805
|
return [];
|
|
441
806
|
}
|
|
@@ -446,7 +811,7 @@ function loaderArgs() {
|
|
|
446
811
|
return [];
|
|
447
812
|
}
|
|
448
813
|
function logDir() {
|
|
449
|
-
return
|
|
814
|
+
return path3.join(pieProcDir(), "logs");
|
|
450
815
|
}
|
|
451
816
|
var toolText = (text, isError = false) => ({ content: [{ type: "text", text }], details: {}, ...isError ? { isError: true } : {} });
|
|
452
817
|
function pieProc(ctx) {
|
|
@@ -458,18 +823,18 @@ function pieProc(ctx) {
|
|
|
458
823
|
const observeActivity = (record) => {
|
|
459
824
|
const logTime = (() => {
|
|
460
825
|
try {
|
|
461
|
-
return
|
|
826
|
+
return fs3.statSync(path3.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
|
|
462
827
|
} catch {
|
|
463
828
|
return record.lastActiveAt;
|
|
464
829
|
}
|
|
465
830
|
})();
|
|
466
831
|
if (record.pid === 0) return logTime;
|
|
467
|
-
const statusRoot =
|
|
832
|
+
const statusRoot = path3.join(path3.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
|
|
468
833
|
try {
|
|
469
|
-
for (const file of
|
|
834
|
+
for (const file of fs3.readdirSync(statusRoot)) {
|
|
470
835
|
if (!file.endsWith(".json")) continue;
|
|
471
836
|
try {
|
|
472
|
-
const status = JSON.parse(
|
|
837
|
+
const status = JSON.parse(fs3.readFileSync(path3.join(statusRoot, file), "utf8"));
|
|
473
838
|
if (status.sessionId === record.sessionId && status.state === "working") return Date.now();
|
|
474
839
|
} catch {
|
|
475
840
|
}
|
|
@@ -625,7 +990,7 @@ function pieProc(ctx) {
|
|
|
625
990
|
ctx.registerCleanup?.(() => {
|
|
626
991
|
clearInterval(sweepTimer);
|
|
627
992
|
});
|
|
628
|
-
const spawnWorker = (params) => {
|
|
993
|
+
const spawnWorker = async (params) => {
|
|
629
994
|
if (!safeName(params.name)) throw new Error(`invalid worker name "${params.name}" (use [a-z0-9-_], max 48)`);
|
|
630
995
|
if (params.kind === "oneshot" && (typeof params.task !== "string" || !params.task.trim())) throw new Error("oneshot spawn requires a non-empty task");
|
|
631
996
|
if (params.kind === "oneshot" && params.task.startsWith("-")) throw new Error(`oneshot task must not start with "-" (got "${params.task.slice(0, 20)}\u2026")`);
|
|
@@ -635,16 +1000,17 @@ function pieProc(ctx) {
|
|
|
635
1000
|
const canonicalCwd = cwdAllowedOrThrow(params.cwd, currentConfig().allowCwd);
|
|
636
1001
|
const entry = cliEntry();
|
|
637
1002
|
if (!entry) throw new Error("cannot resolve a trusted pie entry point (refusing to spawn)");
|
|
1003
|
+
const validatedModel = validateSpawnModelParams({ model: params.model, thinkingLevel: params.thinkingLevel, pieDir: path3.join(pieProcDir(), "agents", params.name), parentConfigDir: configDirRoot() });
|
|
638
1004
|
let resumeSessionId;
|
|
639
1005
|
let resumeSessionsDir;
|
|
640
1006
|
if (params.resumeSessionId) {
|
|
641
1007
|
if (!/^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(params.resumeSessionId)) throw new Error(`invalid resumeSessionId "${params.resumeSessionId}"`);
|
|
642
1008
|
const operatorSessionsDir = resolveOperatorSessionsDir();
|
|
643
|
-
const workerSessionsDir =
|
|
1009
|
+
const workerSessionsDir = path3.join(pieProcDir(), "agents", params.name, "sessions");
|
|
644
1010
|
let recordedCwd;
|
|
645
1011
|
for (const dir of [workerSessionsDir, operatorSessionsDir]) {
|
|
646
1012
|
try {
|
|
647
|
-
const head = JSON.parse(
|
|
1013
|
+
const head = JSON.parse(fs3.readFileSync(path3.join(dir, params.resumeSessionId, "head.json"), "utf8"));
|
|
648
1014
|
recordedCwd = head.metadata?.cwd;
|
|
649
1015
|
resumeSessionsDir = dir;
|
|
650
1016
|
break;
|
|
@@ -655,7 +1021,7 @@ function pieProc(ctx) {
|
|
|
655
1021
|
if (typeof recordedCwd !== "string" || !recordedCwd) throw new Error(`session "${params.resumeSessionId}" has no recorded cwd; resume requires one`);
|
|
656
1022
|
let canonicalRecorded = recordedCwd;
|
|
657
1023
|
try {
|
|
658
|
-
canonicalRecorded =
|
|
1024
|
+
canonicalRecorded = fs3.realpathSync(recordedCwd);
|
|
659
1025
|
} catch {
|
|
660
1026
|
}
|
|
661
1027
|
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`);
|
|
@@ -732,21 +1098,12 @@ function pieProc(ctx) {
|
|
|
732
1098
|
});
|
|
733
1099
|
let child;
|
|
734
1100
|
try {
|
|
735
|
-
const pieDir =
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
const dst = path.join(pieDir, file);
|
|
739
|
-
const src = path.join(configDirRoot(), file);
|
|
740
|
-
if (!fs.existsSync(dst) && fs.existsSync(src)) {
|
|
741
|
-
try {
|
|
742
|
-
fs.copyFileSync(src, dst);
|
|
743
|
-
} catch {
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
}
|
|
1101
|
+
const pieDir = path3.join(pieProcDir(), "agents", params.name);
|
|
1102
|
+
fs3.mkdirSync(pieDir, { recursive: true });
|
|
1103
|
+
inheritWorkerConfigFiles(pieDir, configDirRoot());
|
|
747
1104
|
if (imForward) {
|
|
748
|
-
const imFile =
|
|
749
|
-
if (!
|
|
1105
|
+
const imFile = path3.join(pieDir, "im-forward.json");
|
|
1106
|
+
if (!fs3.existsSync(imFile)) {
|
|
750
1107
|
const provider = typeof imForward.provider === "string" && imForward.provider.trim() ? imForward.provider : "feishu";
|
|
751
1108
|
const providerSettings = {};
|
|
752
1109
|
for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
|
|
@@ -758,26 +1115,15 @@ function pieProc(ctx) {
|
|
|
758
1115
|
providers: { [provider]: providerSettings }
|
|
759
1116
|
};
|
|
760
1117
|
if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
|
|
761
|
-
|
|
1118
|
+
fs3.writeFileSync(imFile, JSON.stringify(doc, null, " "));
|
|
762
1119
|
}
|
|
763
1120
|
}
|
|
764
|
-
|
|
765
|
-
const logFile =
|
|
766
|
-
const
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
"--idle",
|
|
771
|
-
"--session-id",
|
|
772
|
-
sessionId,
|
|
773
|
-
// 4.4.1 resume: --resume-required makes a failed load a HARD exit
|
|
774
|
-
// (never silently mint a same-id empty session); --worker-token
|
|
775
|
-
// keeps argv liveness matching on the per-launch token even when
|
|
776
|
-
// --session-id carries a reusable business session id.
|
|
777
|
-
...resumeSessionId ? ["--resume-required", "--worker-token", launchToken] : []
|
|
778
|
-
] : [...loaderArgs(), entry, "--session-id", sessionId];
|
|
779
|
-
const inheritedIpcRoot = path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
|
|
780
|
-
const inheritedRegistryRoot = path.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
|
|
1121
|
+
fs3.mkdirSync(logDir(), { recursive: true });
|
|
1122
|
+
const logFile = fs3.openSync(path3.join(logDir(), `${params.name}.jsonl`), "a");
|
|
1123
|
+
const modelArgs = [...validatedModel.model ? ["--model", validatedModel.model] : [], ...validatedModel.thinkingLevel ? ["--thinking", validatedModel.thinkingLevel] : []];
|
|
1124
|
+
const args = params.kind === "resident" ? [...loaderArgs(), entry, "--json-events", "--idle", "--session-id", sessionId, ...resumeSessionId ? ["--resume-required", "--worker-token", launchToken] : [], ...modelArgs] : [...loaderArgs(), entry, "--session-id", sessionId, ...modelArgs];
|
|
1125
|
+
const inheritedIpcRoot = path3.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
|
|
1126
|
+
const inheritedRegistryRoot = path3.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
|
|
781
1127
|
const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
|
|
782
1128
|
const childEnv = {
|
|
783
1129
|
...inheritedEnv,
|
|
@@ -797,6 +1143,7 @@ function pieProc(ctx) {
|
|
|
797
1143
|
}
|
|
798
1144
|
}
|
|
799
1145
|
if (resumeSessionId && resumeSessionsDir !== void 0) childEnv.PIE_SESSIONS_DIR = resumeSessionsDir;
|
|
1146
|
+
else if (params.kind === "resident") childEnv.PIE_SESSIONS_DIR = resolveOperatorSessionsDir();
|
|
800
1147
|
try {
|
|
801
1148
|
child = spawn(process.execPath, args, {
|
|
802
1149
|
cwd: canonicalCwd,
|
|
@@ -810,12 +1157,12 @@ function pieProc(ctx) {
|
|
|
810
1157
|
});
|
|
811
1158
|
} finally {
|
|
812
1159
|
try {
|
|
813
|
-
|
|
1160
|
+
fs3.closeSync(logFile);
|
|
814
1161
|
} catch {
|
|
815
1162
|
}
|
|
816
1163
|
}
|
|
817
1164
|
if (typeof child.pid !== "number") {
|
|
818
|
-
throw new Error(`worker spawn failed (no pid) \u2014 see ${
|
|
1165
|
+
throw new Error(`worker spawn failed (no pid) \u2014 see ${path3.join(logDir(), `${params.name}.jsonl`)}`);
|
|
819
1166
|
}
|
|
820
1167
|
child.unref();
|
|
821
1168
|
const record = {
|
|
@@ -855,8 +1202,23 @@ function pieProc(ctx) {
|
|
|
855
1202
|
releaseReservation(generation);
|
|
856
1203
|
throw error instanceof Error ? error : new Error(String(error));
|
|
857
1204
|
}
|
|
858
|
-
|
|
859
|
-
|
|
1205
|
+
const receipt = await buildSpawnReceipt({
|
|
1206
|
+
name: params.name,
|
|
1207
|
+
kind: params.kind,
|
|
1208
|
+
pid: record.pid,
|
|
1209
|
+
sessionId,
|
|
1210
|
+
cwd: record.cwd,
|
|
1211
|
+
pieDir,
|
|
1212
|
+
ipcRoot: inheritedIpcRoot,
|
|
1213
|
+
logPath: path3.join(logDir(), `${params.name}.jsonl`),
|
|
1214
|
+
ttlMs: params.ttlMs,
|
|
1215
|
+
explicitModel: validatedModel.model,
|
|
1216
|
+
explicitThinking: validatedModel.thinkingLevel,
|
|
1217
|
+
resumeSessionId,
|
|
1218
|
+
resumeSessionsDir
|
|
1219
|
+
});
|
|
1220
|
+
ctx.log(`pie-proc: spawned ${params.kind} worker "${params.name}" (pid ${record.pid}, model ${receipt.modelLabel}, cwd ${record.cwd}, gen ${generation})`);
|
|
1221
|
+
return toolText(receipt.text);
|
|
860
1222
|
} catch (error) {
|
|
861
1223
|
releaseReservation(generation);
|
|
862
1224
|
throw error instanceof Error ? error : new Error(String(error));
|
|
@@ -866,6 +1228,9 @@ function pieProc(ctx) {
|
|
|
866
1228
|
let target;
|
|
867
1229
|
target = readRegistryUncached().workers.find((w) => w.name === name);
|
|
868
1230
|
if (!target) throw new Error(`no worker named "${name}"`);
|
|
1231
|
+
if (opts.expectedGeneration && target.generation !== opts.expectedGeneration) {
|
|
1232
|
+
throw new Error(`worker "${name}" generation mismatch (expected ${opts.expectedGeneration}, live ${target.generation}); refusing to signal a newer incarnation`);
|
|
1233
|
+
}
|
|
869
1234
|
if (target.pid === 0) {
|
|
870
1235
|
return updateRegistry((snap) => {
|
|
871
1236
|
const mine = snap.workers.find((w) => w.generation === target.generation);
|
|
@@ -885,9 +1250,7 @@ function pieProc(ctx) {
|
|
|
885
1250
|
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.`);
|
|
886
1251
|
}
|
|
887
1252
|
const verifiedGroupOpts = { trustVerifiedGroup: true };
|
|
888
|
-
signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", {
|
|
889
|
-
groupOnly: liveness === "orphaned_group"
|
|
890
|
-
});
|
|
1253
|
+
signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", { groupOnly: liveness === "orphaned_group" });
|
|
891
1254
|
if (opts.force) {
|
|
892
1255
|
const killDeadline = Date.now() + 1500;
|
|
893
1256
|
while (Date.now() < killDeadline) {
|
|
@@ -902,9 +1265,7 @@ function pieProc(ctx) {
|
|
|
902
1265
|
}
|
|
903
1266
|
const afterGrace = workerLiveness(target, verifiedGroupOpts);
|
|
904
1267
|
if (afterGrace === "alive" || afterGrace === "orphaned_group") {
|
|
905
|
-
signalWorkerProcessGroup(target.pid, "SIGKILL", {
|
|
906
|
-
groupOnly: afterGrace === "orphaned_group"
|
|
907
|
-
});
|
|
1268
|
+
signalWorkerProcessGroup(target.pid, "SIGKILL", { groupOnly: afterGrace === "orphaned_group" });
|
|
908
1269
|
const killDeadline = Date.now() + 1500;
|
|
909
1270
|
while (Date.now() < killDeadline) {
|
|
910
1271
|
await new Promise((r) => setTimeout(r, 100));
|
|
@@ -925,6 +1286,33 @@ function pieProc(ctx) {
|
|
|
925
1286
|
ctx.log("pie-proc: tool not registered (role-pruned; manager-only)");
|
|
926
1287
|
return;
|
|
927
1288
|
}
|
|
1289
|
+
const unregisterPanelBridge = registerPieProcPanelBridge({
|
|
1290
|
+
pieProcDir,
|
|
1291
|
+
operatorSessionsDir: resolveOperatorSessionsDir,
|
|
1292
|
+
allowCwd: () => currentConfig().allowCwd,
|
|
1293
|
+
cwdAllowedOrThrow,
|
|
1294
|
+
safeName,
|
|
1295
|
+
readWorkers: () => readRegistryUncached().workers,
|
|
1296
|
+
workerLiveness: (w) => workerLiveness(w),
|
|
1297
|
+
removeGenerationIfDead: (w) => {
|
|
1298
|
+
if (workerLiveness(w) !== "dead") return false;
|
|
1299
|
+
updateRegistry((snap) => ({ next: snap.workers.filter((item) => item.generation !== w.generation), result: void 0 }));
|
|
1300
|
+
return true;
|
|
1301
|
+
},
|
|
1302
|
+
killWorker,
|
|
1303
|
+
canInheritImForward: () => {
|
|
1304
|
+
try {
|
|
1305
|
+
sanitizeImForward("inherit");
|
|
1306
|
+
return true;
|
|
1307
|
+
} catch {
|
|
1308
|
+
return false;
|
|
1309
|
+
}
|
|
1310
|
+
},
|
|
1311
|
+
spawnResumeWorker: ({ name, cwd, resumeSessionId, inheritIm }) => spawnWorker({ name, cwd, kind: "resident", resumeSessionId, ...inheritIm ? { imForward: "inherit" } : {} })
|
|
1312
|
+
});
|
|
1313
|
+
ctx.registerCleanup?.(() => {
|
|
1314
|
+
unregisterPanelBridge();
|
|
1315
|
+
});
|
|
928
1316
|
ctx.registerTool({
|
|
929
1317
|
name: "pie_proc",
|
|
930
1318
|
label: "Pie worker processes",
|
|
@@ -935,6 +1323,8 @@ function pieProc(ctx) {
|
|
|
935
1323
|
cwd: Type.Optional(Type.String({ description: "spawn: working directory (must resolve under an allowCwd root)" })),
|
|
936
1324
|
kind: Type.Optional(Type.Union([Type.Literal("resident"), Type.Literal("oneshot")], { description: "spawn: resident (default) or oneshot" })),
|
|
937
1325
|
task: Type.Optional(Type.String({ description: "oneshot: the task prompt (non-empty, must not start with '-')" })),
|
|
1326
|
+
model: Type.Optional(Type.String({ description: "spawn: optional per-worker model override as 'provider/modelId' (validated against models.json; overrides default/resumed model when set)" })),
|
|
1327
|
+
thinkingLevel: Type.Optional(Type.String({ description: "spawn: optional thinking level override (off|minimal|low|medium|high|xhigh|max)" })),
|
|
938
1328
|
ttlMs: Type.Optional(Type.Number({ description: "spawn (resident only): idle TTL in ms (0 = never reap)", minimum: 0, maximum: 864e5 })),
|
|
939
1329
|
force: Type.Optional(Type.Boolean({ description: "kill: skip graceful SIGTERM" })),
|
|
940
1330
|
imForward: Type.Optional(Type.Union([Type.Literal("inherit"), Type.Record(Type.String(), Type.Unknown())], { description: "spawn (resident only): IM identity binding \u2014 'inherit' copies the operator's user-layer IM identity verbatim (recommended: open_ids are per-app, hand copies break silently), or an object of identity fields only (enabled/provider/chatId/openId/allowUsers/larkCliProfile/inherit)" })),
|
|
@@ -948,17 +1338,11 @@ function pieProc(ctx) {
|
|
|
948
1338
|
const action = args.action;
|
|
949
1339
|
if (action === "list") {
|
|
950
1340
|
const snap = readRegistryUncached();
|
|
951
|
-
const
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
session: w.sessionId,
|
|
955
|
-
|
|
956
|
-
kind: w.kind,
|
|
957
|
-
status: w.pid === 0 ? `pending (reserver ${w.reserverPid ?? "?"})` : workerLiveness(w),
|
|
958
|
-
idleSeconds: Math.round((Date.now() - Math.max(w.lastActiveAt, observeActivity(w))) / 1e3),
|
|
959
|
-
ttlMs: w.kind === "resident" ? w.ttlMs ?? currentConfig().defaultTtlMs : 0,
|
|
960
|
-
im: Boolean(w.imForward)
|
|
961
|
-
}));
|
|
1341
|
+
const ipcRoot = path3.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
|
|
1342
|
+
const rows = snap.workers.map((w) => {
|
|
1343
|
+
const model = liveWorkerModelLabel(ipcRoot, w.sessionId, w.pid);
|
|
1344
|
+
return { name: w.name, pid: w.pid, session: w.sessionId, cwd: w.cwd, kind: w.kind, ...model ? { model } : {}, status: w.pid === 0 ? `pending (reserver ${w.reserverPid ?? "?"})` : workerLiveness(w), idleSeconds: Math.round((Date.now() - Math.max(w.lastActiveAt, observeActivity(w))) / 1e3), ttlMs: w.kind === "resident" ? w.ttlMs ?? currentConfig().defaultTtlMs : 0, im: Boolean(w.imForward) };
|
|
1345
|
+
});
|
|
962
1346
|
return { content: [{ type: "text", text: rows.length === 0 ? "No pie-proc workers registered." : JSON.stringify(rows, null, 2) }], details: {} };
|
|
963
1347
|
}
|
|
964
1348
|
if (action === "spawn") {
|
|
@@ -972,6 +1356,8 @@ function pieProc(ctx) {
|
|
|
972
1356
|
kind: args.kind ?? "resident",
|
|
973
1357
|
ttlMs: typeof args.ttlMs === "number" ? args.ttlMs : void 0,
|
|
974
1358
|
task: args.task,
|
|
1359
|
+
model: typeof args.model === "string" ? args.model : void 0,
|
|
1360
|
+
thinkingLevel: typeof args.thinkingLevel === "string" ? args.thinkingLevel : void 0,
|
|
975
1361
|
imForward: args.imForward,
|
|
976
1362
|
resumeSessionId: args.resumeSessionId
|
|
977
1363
|
});
|