@cydm/pie 4.8.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.
Files changed (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +906 -158
  4. package/dist/builtin/extensions/im-forward/README.md +4 -2
  5. package/dist/builtin/extensions/im-forward/index.js +6822 -3951
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +282 -58
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +227 -75
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +26 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +293 -64
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
  26. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
  27. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
  28. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  29. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
  30. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  31. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
  32. package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
  33. package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
  34. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
  35. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  36. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
  37. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
  38. package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
  40. package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
  41. package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
  42. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
  43. package/dist/cli.js +1890 -1489
  44. package/models.schema.json +271 -0
  45. package/package.json +2 -2
  46. package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
  47. package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
  48. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -1,12 +1,15 @@
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-CGSFBWOM.js";
5
- import "../../../chunks/chunk-CBDQJMUI.js";
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";
@@ -16,9 +19,132 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
16
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 fs from "node:fs";
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,11 +153,11 @@ 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 path.join(os.homedir(), ".pie", "sessions");
31
- if (override.startsWith("~/")) return path.join(os.homedir(), override.slice(2));
32
- if (path.isAbsolute(override)) return override;
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 path.join(os.homedir(), ".pie", "sessions");
160
+ return path2.join(os.homedir(), ".pie", "sessions");
35
161
  }
36
162
  }
37
163
  var DEFAULT_MAX_WORKERS = 50;
@@ -41,20 +167,20 @@ var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
41
167
  var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
42
168
  function configDirRoot() {
43
169
  const env = process.env.PIE_CODING_AGENT_DIR;
44
- if (!env) return path.join(os.homedir(), ".pie");
45
- return path.resolve(expandTilde(env));
170
+ if (!env) return path2.join(os.homedir(), ".pie");
171
+ return path2.resolve(expandTilde(env));
46
172
  }
47
173
  function expandTilde(p) {
48
- return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
174
+ return p === "~" ? os.homedir() : p.startsWith("~/") ? path2.join(os.homedir(), p.slice(2)) : p;
49
175
  }
50
176
  function configCandidates() {
51
- const candidates = [path.join(configDirRoot(), "pie-proc.json")];
177
+ const candidates = [path2.join(configDirRoot(), "pie-proc.json")];
52
178
  const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
53
179
  if (pinnedRoot) {
54
- const pinDerived = path.join(path.dirname(path.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
180
+ const pinDerived = path2.join(path2.dirname(path2.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
55
181
  if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
56
- } else if (configDirRoot() !== path.join(os.homedir(), ".pie")) {
57
- candidates.push(path.join(os.homedir(), ".pie", "pie-proc.json"));
182
+ } else if (configDirRoot() !== path2.join(os.homedir(), ".pie")) {
183
+ candidates.push(path2.join(os.homedir(), ".pie", "pie-proc.json"));
58
184
  }
59
185
  return candidates;
60
186
  }
@@ -62,7 +188,7 @@ function readConfig() {
62
188
  const candidates = configCandidates();
63
189
  for (const file of candidates) {
64
190
  try {
65
- const raw = JSON.parse(fs.readFileSync(file, "utf8"));
191
+ const raw = JSON.parse(fs2.readFileSync(file, "utf8"));
66
192
  return {
67
193
  allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
68
194
  maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
@@ -70,21 +196,21 @@ function readConfig() {
70
196
  defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
71
197
  };
72
198
  } catch {
73
- if (fs.existsSync(file)) return { ...DEFAULT_CONFIG };
199
+ if (fs2.existsSync(file)) return { ...DEFAULT_CONFIG };
74
200
  }
75
201
  }
76
202
  return { ...DEFAULT_CONFIG };
77
203
  }
78
204
  function pieProcDir() {
79
205
  const pinned = process.env.PIE_PROC_REGISTRY_ROOT;
80
- if (pinned) return path.resolve(expandTilde(pinned));
81
- return path.join(configDirRoot(), "pie-proc");
206
+ if (pinned) return path2.resolve(expandTilde(pinned));
207
+ return path2.join(configDirRoot(), "pie-proc");
82
208
  }
83
209
  function registryFile() {
84
- return path.join(pieProcDir(), "workers.json");
210
+ return path2.join(pieProcDir(), "workers.json");
85
211
  }
86
212
  function revisionFile(n) {
87
- return path.join(pieProcDir(), `workers.r${n}.json`);
213
+ return path2.join(pieProcDir(), `workers.r${n}.json`);
88
214
  }
89
215
  function parseRegistry(rawText, file, revision) {
90
216
  let raw;
@@ -116,7 +242,7 @@ function parseRegistry(rawText, file, revision) {
116
242
  function latestRevisionOnDisk() {
117
243
  let max = 0;
118
244
  try {
119
- for (const entry of fs.readdirSync(pieProcDir())) {
245
+ for (const entry of fs2.readdirSync(pieProcDir())) {
120
246
  const match = /^workers\.r(\d+)\.json$/.exec(entry);
121
247
  if (match) max = Math.max(max, Number(match[1]));
122
248
  }
@@ -130,7 +256,7 @@ function readRegistryUncached() {
130
256
  if (latest > 0) {
131
257
  const file2 = revisionFile(latest);
132
258
  try {
133
- return parseRegistry(fs.readFileSync(file2, "utf8"), file2, latest);
259
+ return parseRegistry(fs2.readFileSync(file2, "utf8"), file2, latest);
134
260
  } catch (error) {
135
261
  if (error.code === "ENOENT") continue;
136
262
  throw error;
@@ -138,7 +264,7 @@ function readRegistryUncached() {
138
264
  }
139
265
  const file = registryFile();
140
266
  try {
141
- return parseRegistry(fs.readFileSync(file, "utf8"), file, 0);
267
+ return parseRegistry(fs2.readFileSync(file, "utf8"), file, 0);
142
268
  } catch (error) {
143
269
  if (error.code === "ENOENT") return { revision: 0, workers: [] };
144
270
  throw error;
@@ -149,7 +275,7 @@ function readRegistryUncached() {
149
275
  function compactRevisions(_current) {
150
276
  }
151
277
  function casRegistry(mutate) {
152
- fs.mkdirSync(pieProcDir(), { recursive: true });
278
+ fs2.mkdirSync(pieProcDir(), { recursive: true });
153
279
  for (let attempt = 0; attempt < 20; attempt += 1) {
154
280
  const snapshot = readRegistryUncached();
155
281
  const outcome = mutate(snapshot);
@@ -160,26 +286,26 @@ function casRegistry(mutate) {
160
286
  const nextRevision = snapshot.revision + 1;
161
287
  const target = revisionFile(nextRevision);
162
288
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}-${attempt}.tmp`;
163
- fs.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
289
+ fs2.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
164
290
  if (latestRevisionOnDisk() > snapshot.revision) {
165
291
  try {
166
- fs.rmSync(tmp, { force: true });
292
+ fs2.rmSync(tmp, { force: true });
167
293
  } catch {
168
294
  }
169
295
  continue;
170
296
  }
171
297
  try {
172
- fs.linkSync(tmp, target);
298
+ fs2.linkSync(tmp, target);
173
299
  } catch (error) {
174
300
  try {
175
- fs.rmSync(tmp, { force: true });
301
+ fs2.rmSync(tmp, { force: true });
176
302
  } catch {
177
303
  }
178
304
  if (error.code === "EEXIST") continue;
179
305
  throw error;
180
306
  }
181
307
  try {
182
- fs.rmSync(tmp, { force: true });
308
+ fs2.rmSync(tmp, { force: true });
183
309
  } catch {
184
310
  }
185
311
  compactRevisions(nextRevision);
@@ -273,7 +399,7 @@ function verifyProcessEnvOwnership(pid, marker, pieDir) {
273
399
  if (process.platform === "linux") {
274
400
  let raw2;
275
401
  try {
276
- raw2 = fs.readFileSync(`/proc/${pid}/environ`, "utf8");
402
+ raw2 = fs2.readFileSync(`/proc/${pid}/environ`, "utf8");
277
403
  } catch {
278
404
  return "unverified";
279
405
  }
@@ -343,9 +469,9 @@ function workerLiveness(record, opts = {}) {
343
469
  return "dead";
344
470
  }
345
471
  function canonicalDir(dir) {
346
- const resolved = path.resolve(expandTilde(dir));
347
- const real = fs.realpathSync(resolved);
348
- const stat = fs.statSync(real);
472
+ const resolved = path2.resolve(expandTilde(dir));
473
+ const real = fs2.realpathSync(resolved);
474
+ const stat = fs2.statSync(real);
349
475
  if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
350
476
  return real;
351
477
  }
@@ -354,19 +480,19 @@ function cwdAllowedOrThrow(cwd, allow) {
354
480
  for (const root of allow) {
355
481
  try {
356
482
  const canonicalRoot = canonicalDir(root);
357
- if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path.sep)) return canonical;
483
+ if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path2.sep)) return canonical;
358
484
  } catch {
359
485
  }
360
486
  }
361
487
  const file = configCandidates()[0];
362
488
  let exists = false;
363
489
  try {
364
- exists = fs.existsSync(file);
490
+ exists = fs2.existsSync(file);
365
491
  } catch {
366
492
  }
367
493
  const effective = configCandidates().find((c) => {
368
494
  try {
369
- return fs.existsSync(c);
495
+ return fs2.existsSync(c);
370
496
  } catch {
371
497
  return false;
372
498
  }
@@ -397,10 +523,10 @@ function sanitizeImForward(raw) {
397
523
  }
398
524
  function readUserImForwardIdentity() {
399
525
  try {
400
- const candidates = [path.join(configDirRoot(), "im-forward.json")];
526
+ const candidates = [path2.join(configDirRoot(), "im-forward.json")];
401
527
  for (const file of candidates) {
402
528
  try {
403
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
529
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
404
530
  const provider = typeof parsed.provider === "string" ? parsed.provider : "feishu";
405
531
  const settings = parsed.providers?.[provider];
406
532
  if (!settings) continue;
@@ -417,12 +543,12 @@ function readUserImForwardIdentity() {
417
543
  return void 0;
418
544
  }
419
545
  function cliEntry() {
420
- const moduleDir = path.dirname(fileURLToPath(import.meta.url));
546
+ const moduleDir = path2.dirname(fileURLToPath(import.meta.url));
421
547
  for (const rel of ["../../../src/cli.ts", "../../../cli.js"]) {
422
- const candidate = path.resolve(moduleDir, rel);
548
+ const candidate = path2.resolve(moduleDir, rel);
423
549
  try {
424
- const real = fs.realpathSync(candidate);
425
- if (fs.statSync(real).isFile()) return real;
550
+ const real = fs2.realpathSync(candidate);
551
+ if (fs2.statSync(real).isFile()) return real;
426
552
  } catch {
427
553
  }
428
554
  }
@@ -432,10 +558,10 @@ function loaderArgs() {
432
558
  for (let i = 0; i < process.execArgv.length - 1; i += 1) {
433
559
  if (process.execArgv[i] === "--import") {
434
560
  const target = process.execArgv[i + 1];
435
- if (target && !path.isAbsolute(target) && !target.startsWith("file:")) {
561
+ if (target && !path2.isAbsolute(target) && !target.startsWith("file:")) {
436
562
  try {
437
- const pkgRoot = path.dirname(require_.resolve(`${target}/package.json`, { paths: [path.dirname(cliEntry())] }));
438
- return ["--import", path.join(pkgRoot, "dist", "loader.mjs")];
563
+ const pkgRoot = path2.dirname(require_.resolve(`${target}/package.json`, { paths: [path2.dirname(cliEntry())] }));
564
+ return ["--import", path2.join(pkgRoot, "dist", "loader.mjs")];
439
565
  } catch {
440
566
  return [];
441
567
  }
@@ -446,7 +572,7 @@ function loaderArgs() {
446
572
  return [];
447
573
  }
448
574
  function logDir() {
449
- return path.join(pieProcDir(), "logs");
575
+ return path2.join(pieProcDir(), "logs");
450
576
  }
451
577
  var toolText = (text, isError = false) => ({ content: [{ type: "text", text }], details: {}, ...isError ? { isError: true } : {} });
452
578
  function pieProc(ctx) {
@@ -458,18 +584,18 @@ function pieProc(ctx) {
458
584
  const observeActivity = (record) => {
459
585
  const logTime = (() => {
460
586
  try {
461
- return fs.statSync(path.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
587
+ return fs2.statSync(path2.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
462
588
  } catch {
463
589
  return record.lastActiveAt;
464
590
  }
465
591
  })();
466
592
  if (record.pid === 0) return logTime;
467
- const statusRoot = path.join(path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
593
+ const statusRoot = path2.join(path2.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
468
594
  try {
469
- for (const file of fs.readdirSync(statusRoot)) {
595
+ for (const file of fs2.readdirSync(statusRoot)) {
470
596
  if (!file.endsWith(".json")) continue;
471
597
  try {
472
- const status = JSON.parse(fs.readFileSync(path.join(statusRoot, file), "utf8"));
598
+ const status = JSON.parse(fs2.readFileSync(path2.join(statusRoot, file), "utf8"));
473
599
  if (status.sessionId === record.sessionId && status.state === "working") return Date.now();
474
600
  } catch {
475
601
  }
@@ -640,11 +766,11 @@ function pieProc(ctx) {
640
766
  if (params.resumeSessionId) {
641
767
  if (!/^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(params.resumeSessionId)) throw new Error(`invalid resumeSessionId "${params.resumeSessionId}"`);
642
768
  const operatorSessionsDir = resolveOperatorSessionsDir();
643
- const workerSessionsDir = path.join(pieProcDir(), "agents", params.name, "sessions");
769
+ const workerSessionsDir = path2.join(pieProcDir(), "agents", params.name, "sessions");
644
770
  let recordedCwd;
645
771
  for (const dir of [workerSessionsDir, operatorSessionsDir]) {
646
772
  try {
647
- const head = JSON.parse(fs.readFileSync(path.join(dir, params.resumeSessionId, "head.json"), "utf8"));
773
+ const head = JSON.parse(fs2.readFileSync(path2.join(dir, params.resumeSessionId, "head.json"), "utf8"));
648
774
  recordedCwd = head.metadata?.cwd;
649
775
  resumeSessionsDir = dir;
650
776
  break;
@@ -655,7 +781,7 @@ function pieProc(ctx) {
655
781
  if (typeof recordedCwd !== "string" || !recordedCwd) throw new Error(`session "${params.resumeSessionId}" has no recorded cwd; resume requires one`);
656
782
  let canonicalRecorded = recordedCwd;
657
783
  try {
658
- canonicalRecorded = fs.realpathSync(recordedCwd);
784
+ canonicalRecorded = fs2.realpathSync(recordedCwd);
659
785
  } catch {
660
786
  }
661
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`);
@@ -732,21 +858,21 @@ function pieProc(ctx) {
732
858
  });
733
859
  let child;
734
860
  try {
735
- const pieDir = path.join(pieProcDir(), "agents", params.name);
736
- fs.mkdirSync(pieDir, { recursive: true });
861
+ const pieDir = path2.join(pieProcDir(), "agents", params.name);
862
+ fs2.mkdirSync(pieDir, { recursive: true });
737
863
  for (const file of ["models.json", "config.json", "auth.json"]) {
738
- const dst = path.join(pieDir, file);
739
- const src = path.join(configDirRoot(), file);
740
- if (!fs.existsSync(dst) && fs.existsSync(src)) {
864
+ const dst = path2.join(pieDir, file);
865
+ const src = path2.join(configDirRoot(), file);
866
+ if (!fs2.existsSync(dst) && fs2.existsSync(src)) {
741
867
  try {
742
- fs.copyFileSync(src, dst);
868
+ fs2.copyFileSync(src, dst);
743
869
  } catch {
744
870
  }
745
871
  }
746
872
  }
747
873
  if (imForward) {
748
- const imFile = path.join(pieDir, "im-forward.json");
749
- if (!fs.existsSync(imFile)) {
874
+ const imFile = path2.join(pieDir, "im-forward.json");
875
+ if (!fs2.existsSync(imFile)) {
750
876
  const provider = typeof imForward.provider === "string" && imForward.provider.trim() ? imForward.provider : "feishu";
751
877
  const providerSettings = {};
752
878
  for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
@@ -758,11 +884,11 @@ function pieProc(ctx) {
758
884
  providers: { [provider]: providerSettings }
759
885
  };
760
886
  if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
761
- fs.writeFileSync(imFile, JSON.stringify(doc, null, " "));
887
+ fs2.writeFileSync(imFile, JSON.stringify(doc, null, " "));
762
888
  }
763
889
  }
764
- fs.mkdirSync(logDir(), { recursive: true });
765
- const logFile = fs.openSync(path.join(logDir(), `${params.name}.jsonl`), "a");
890
+ fs2.mkdirSync(logDir(), { recursive: true });
891
+ const logFile = fs2.openSync(path2.join(logDir(), `${params.name}.jsonl`), "a");
766
892
  const args = params.kind === "resident" ? [
767
893
  ...loaderArgs(),
768
894
  entry,
@@ -776,8 +902,8 @@ function pieProc(ctx) {
776
902
  // --session-id carries a reusable business session id.
777
903
  ...resumeSessionId ? ["--resume-required", "--worker-token", launchToken] : []
778
904
  ] : [...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()));
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()));
781
907
  const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
782
908
  const childEnv = {
783
909
  ...inheritedEnv,
@@ -810,12 +936,12 @@ function pieProc(ctx) {
810
936
  });
811
937
  } finally {
812
938
  try {
813
- fs.closeSync(logFile);
939
+ fs2.closeSync(logFile);
814
940
  } catch {
815
941
  }
816
942
  }
817
943
  if (typeof child.pid !== "number") {
818
- throw new Error(`worker spawn failed (no pid) \u2014 see ${path.join(logDir(), `${params.name}.jsonl`)}`);
944
+ throw new Error(`worker spawn failed (no pid) \u2014 see ${path2.join(logDir(), `${params.name}.jsonl`)}`);
819
945
  }
820
946
  child.unref();
821
947
  const record = {
@@ -856,7 +982,7 @@ function pieProc(ctx) {
856
982
  throw error instanceof Error ? error : new Error(String(error));
857
983
  }
858
984
  ctx.log(`pie-proc: spawned ${params.kind} worker "${params.name}" (pid ${record.pid}, cwd ${record.cwd}, gen ${generation})`);
859
- return toolText(`Spawned ${params.kind} worker "${params.name}" (pid ${record.pid}, peer name "${params.name}", cwd ${record.cwd}${params.kind === "resident" && params.ttlMs ? `, idle TTL ${Math.round(params.ttlMs / 1e3)}s` : ""}). Resident workers accept ipc_send_notify by peer name "${params.name}"; their stdout events are at ${path.join(logDir(), `${params.name}.jsonl`)}.`);
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`)}.`);
860
986
  } catch (error) {
861
987
  releaseReservation(generation);
862
988
  throw error instanceof Error ? error : new Error(String(error));
@@ -866,6 +992,9 @@ function pieProc(ctx) {
866
992
  let target;
867
993
  target = readRegistryUncached().workers.find((w) => w.name === name);
868
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
+ }
869
998
  if (target.pid === 0) {
870
999
  return updateRegistry((snap) => {
871
1000
  const mine = snap.workers.find((w) => w.generation === target.generation);
@@ -885,9 +1014,7 @@ function pieProc(ctx) {
885
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.`);
886
1015
  }
887
1016
  const verifiedGroupOpts = { trustVerifiedGroup: true };
888
- signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", {
889
- groupOnly: liveness === "orphaned_group"
890
- });
1017
+ signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", { groupOnly: liveness === "orphaned_group" });
891
1018
  if (opts.force) {
892
1019
  const killDeadline = Date.now() + 1500;
893
1020
  while (Date.now() < killDeadline) {
@@ -902,9 +1029,7 @@ function pieProc(ctx) {
902
1029
  }
903
1030
  const afterGrace = workerLiveness(target, verifiedGroupOpts);
904
1031
  if (afterGrace === "alive" || afterGrace === "orphaned_group") {
905
- signalWorkerProcessGroup(target.pid, "SIGKILL", {
906
- groupOnly: afterGrace === "orphaned_group"
907
- });
1032
+ signalWorkerProcessGroup(target.pid, "SIGKILL", { groupOnly: afterGrace === "orphaned_group" });
908
1033
  const killDeadline = Date.now() + 1500;
909
1034
  while (Date.now() < killDeadline) {
910
1035
  await new Promise((r) => setTimeout(r, 100));
@@ -925,6 +1050,33 @@ function pieProc(ctx) {
925
1050
  ctx.log("pie-proc: tool not registered (role-pruned; manager-only)");
926
1051
  return;
927
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
+ });
928
1080
  ctx.registerTool({
929
1081
  name: "pie_proc",
930
1082
  label: "Pie worker processes",
@@ -6,10 +6,10 @@ import {
6
6
  createPlanCapability,
7
7
  markCompletedPlanSteps,
8
8
  restoreExecutionState
9
- } from "../../../chunks/chunk-BLDI2GRF.js";
10
- import "../../../chunks/chunk-Y3I2UV5Y.js";
11
- import "../../../chunks/chunk-5KI4Y4LA.js";
12
- import "../../../chunks/chunk-3W3SXVPB.js";
9
+ } from "../../../chunks/chunk-DBDU3RRN.js";
10
+ import "../../../chunks/chunk-LRHNAG4V.js";
11
+ import "../../../chunks/chunk-BA4Z27XT.js";
12
+ import "../../../chunks/chunk-4UIUMTHG.js";
13
13
  import {
14
14
  Type
15
15
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -407,7 +407,7 @@ Discuss the revision with the user (read-only; Plan mode is back on). When the u
407
407
  if (!executingPlan || state.steps.length === 0) return;
408
408
  const message = event.message;
409
409
  if (message?.role !== "assistant" || !Array.isArray(message.content)) return;
410
- const text = message.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
410
+ const text = message.content.filter((item) => typeof item === "object" && item !== null && "type" in item && item.type === "text" && "text" in item && typeof item.text === "string").map((item) => item.text).join("\n");
411
411
  const todoItems = toPlanTodoItems(state);
412
412
  if (markCompletedPlanSteps(text, todoItems) <= 0) return;
413
413
  const nextState = createExecutionStateFromPlan(todoItems);
@@ -5,19 +5,19 @@ import {
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
7
  logTransportLifecycle
8
- } from "../../../chunks/chunk-LAJXWOKS.js";
9
- import {
10
- getConfigDir
11
- } from "../../../chunks/chunk-CBDQJMUI.js";
8
+ } from "../../../chunks/chunk-EEC5PJTC.js";
12
9
  import {
13
10
  SUBAGENT_SESSION_RECORD_VERSION,
14
11
  createPolicyEnforcedTools,
15
12
  createSharedFileSystemTools,
16
13
  createSubagentCapability
17
- } from "../../../chunks/chunk-BLDI2GRF.js";
18
- import "../../../chunks/chunk-Y3I2UV5Y.js";
19
- import "../../../chunks/chunk-5KI4Y4LA.js";
20
- import "../../../chunks/chunk-3W3SXVPB.js";
14
+ } from "../../../chunks/chunk-DBDU3RRN.js";
15
+ import "../../../chunks/chunk-LRHNAG4V.js";
16
+ import "../../../chunks/chunk-BA4Z27XT.js";
17
+ import {
18
+ getConfigDir
19
+ } from "../../../chunks/chunk-CBDQJMUI.js";
20
+ import "../../../chunks/chunk-4UIUMTHG.js";
21
21
  import "../../../chunks/chunk-XXGYUYXI.js";
22
22
  import "../../../chunks/chunk-LZQXQOPJ.js";
23
23
 
@@ -8,10 +8,10 @@ import {
8
8
  executeManageTodoList,
9
9
  executionStateToTodos,
10
10
  restoreExecutionState
11
- } from "../../../chunks/chunk-BLDI2GRF.js";
12
- import "../../../chunks/chunk-Y3I2UV5Y.js";
13
- import "../../../chunks/chunk-5KI4Y4LA.js";
14
- import "../../../chunks/chunk-3W3SXVPB.js";
11
+ } from "../../../chunks/chunk-DBDU3RRN.js";
12
+ import "../../../chunks/chunk-LRHNAG4V.js";
13
+ import "../../../chunks/chunk-BA4Z27XT.js";
14
+ import "../../../chunks/chunk-4UIUMTHG.js";
15
15
  import "../../../chunks/chunk-XXGYUYXI.js";
16
16
  import "../../../chunks/chunk-LZQXQOPJ.js";
17
17