@cydm/pie 4.10.1 → 4.11.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.
@@ -3,15 +3,16 @@ import {
3
3
  liveSessionHolder
4
4
  } from "../../../chunks/chunk-KWK7KTSZ.js";
5
5
  import {
6
- registerWorkerLifecycleBridge
7
- } from "../../../chunks/chunk-6WKBQZWM.js";
6
+ registerWorkerLifecycleBridge,
7
+ syncInheritedWorkerModels
8
+ } from "../../../chunks/chunk-EWPPGYBU.js";
8
9
  import {
9
10
  readProcessCommandLine
10
11
  } from "../../../chunks/chunk-7RJXKN7N.js";
11
12
  import "../../../chunks/chunk-ZPJ3BNQB.js";
12
13
  import {
13
14
  loadResolvedModelsConfig
14
- } from "../../../chunks/chunk-FC5AN5QP.js";
15
+ } from "../../../chunks/chunk-B5GKDXVG.js";
15
16
  import "../../../chunks/chunk-CBDQJMUI.js";
16
17
  import "../../../chunks/chunk-G2K4GY6N.js";
17
18
  import {
@@ -23,9 +24,9 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
23
24
  import { execFileSync, spawn } from "node:child_process";
24
25
  import { createRequire } from "node:module";
25
26
  import { fileURLToPath } from "node:url";
26
- import * as fs3 from "node:fs";
27
- import * as os from "node:os";
28
- import * as path3 from "node:path";
27
+ import * as fs4 from "node:fs";
28
+ import * as os2 from "node:os";
29
+ import * as path4 from "node:path";
29
30
 
30
31
  // builtin/extensions/pie-proc/panel-bridge.ts
31
32
  import * as fs from "node:fs";
@@ -148,9 +149,108 @@ function registerPieProcPanelBridge(deps) {
148
149
  });
149
150
  }
150
151
 
151
- // builtin/extensions/pie-proc/spawn-model.ts
152
+ // builtin/extensions/pie-proc/proc-config.ts
152
153
  import * as fs2 from "node:fs";
154
+ import * as os from "node:os";
153
155
  import * as path2 from "node:path";
156
+ var DEFAULT_MAX_WORKERS = 50;
157
+ var DEFAULT_CONFIG = {
158
+ allowCwd: [],
159
+ maxWorkers: DEFAULT_MAX_WORKERS,
160
+ killGraceMs: 15e3,
161
+ defaultTtlMs: 0
162
+ };
163
+ function expandTilde(p) {
164
+ return p === "~" ? os.homedir() : p.startsWith("~/") ? path2.join(os.homedir(), p.slice(2)) : p;
165
+ }
166
+ function configDirRoot() {
167
+ const env = process.env.PIE_CODING_AGENT_DIR;
168
+ if (!env) return path2.join(os.homedir(), ".pie");
169
+ return path2.resolve(expandTilde(env));
170
+ }
171
+ function configCandidates() {
172
+ const candidates = [path2.join(configDirRoot(), "pie-proc.json")];
173
+ const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
174
+ if (pinnedRoot) {
175
+ const pinDerived = path2.join(path2.dirname(path2.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
176
+ if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
177
+ } else if (configDirRoot() !== path2.join(os.homedir(), ".pie")) {
178
+ candidates.push(path2.join(os.homedir(), ".pie", "pie-proc.json"));
179
+ }
180
+ return candidates;
181
+ }
182
+ function readConfigDetailed() {
183
+ const candidates = configCandidates();
184
+ for (const file of candidates) {
185
+ try {
186
+ const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
187
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
188
+ throw new Error("top-level JSON value must be an object");
189
+ }
190
+ const raw = parsed;
191
+ return {
192
+ config: {
193
+ allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
194
+ maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
195
+ killGraceMs: typeof raw.killGraceMs === "number" && raw.killGraceMs >= 1e3 ? Math.floor(raw.killGraceMs) : DEFAULT_CONFIG.killGraceMs,
196
+ defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
197
+ }
198
+ };
199
+ } catch (error) {
200
+ if (fs2.existsSync(file)) {
201
+ return {
202
+ config: { ...DEFAULT_CONFIG },
203
+ loadError: { file, detail: error instanceof Error ? error.message : String(error) }
204
+ };
205
+ }
206
+ }
207
+ }
208
+ return { config: { ...DEFAULT_CONFIG } };
209
+ }
210
+ function readConfig() {
211
+ return readConfigDetailed().config;
212
+ }
213
+ function canonicalDir(dir) {
214
+ const resolved = path2.resolve(expandTilde(dir));
215
+ const real = fs2.realpathSync(resolved);
216
+ const stat = fs2.statSync(real);
217
+ if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
218
+ return real;
219
+ }
220
+ function cwdAllowedOrThrow(cwd, allowOrRead) {
221
+ const read = Array.isArray(allowOrRead) ? { config: { ...DEFAULT_CONFIG, allowCwd: allowOrRead } } : allowOrRead;
222
+ if (read.loadError) {
223
+ throw new Error(
224
+ `pie-proc policy at ${read.loadError.file} could not be loaded (${read.loadError.detail}); refusing to spawn. Run \`pie manager allow "${cwd}" --backup-corrupt\` to back up the broken file and authorize this root, or fix the JSON.`
225
+ );
226
+ }
227
+ const canonical = canonicalDir(cwd);
228
+ for (const root of read.config.allowCwd) {
229
+ try {
230
+ const canonicalRoot = canonicalDir(root);
231
+ if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path2.sep)) return canonical;
232
+ } catch {
233
+ }
234
+ }
235
+ const file = configCandidates()[0];
236
+ let exists = false;
237
+ try {
238
+ exists = fs2.existsSync(file);
239
+ } catch {
240
+ }
241
+ const effective = configCandidates().find((c) => {
242
+ try {
243
+ return fs2.existsSync(c);
244
+ } catch {
245
+ return false;
246
+ }
247
+ }) ?? file;
248
+ throw new Error(exists || effective !== file ? `cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots in ${effective}. Run \`pie manager allow "${cwd}"\` (or edit that file) \u2014 it is re-read on every spawn, so no host restart is needed` : `cwd "${cwd}" is outside the pie-proc allowCwd roots: there is no config yet at ${effective}. Run \`pie manager allow "${cwd}"\` (or create ${effective} with {"allowCwd": ["${cwd}"]}) \u2014 it is read on every spawn, so no host restart is needed`);
249
+ }
250
+
251
+ // builtin/extensions/pie-proc/spawn-model.ts
252
+ import * as fs3 from "node:fs";
253
+ import * as path3 from "node:path";
154
254
  var SPAWN_THINKING_LEVELS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
155
255
  var MODEL_REF_RE = /^[^/\s]+\/\S+$/;
156
256
  function collectModelRefsFromRaw(raw) {
@@ -182,7 +282,7 @@ function collectModelRefsFromRaw(raw) {
182
282
  return refs;
183
283
  }
184
284
  function readKnownModelRefs(modelsPath) {
185
- if (!fs2.existsSync(modelsPath)) return void 0;
285
+ if (!fs3.existsSync(modelsPath)) return void 0;
186
286
  try {
187
287
  const resolved = loadResolvedModelsConfig(modelsPath);
188
288
  const refs = collectModelRefsFromRaw(resolved.config);
@@ -190,7 +290,7 @@ function readKnownModelRefs(modelsPath) {
190
290
  } catch {
191
291
  }
192
292
  try {
193
- const raw = JSON.parse(fs2.readFileSync(modelsPath, "utf8"));
293
+ const raw = JSON.parse(fs3.readFileSync(modelsPath, "utf8"));
194
294
  const refs = collectModelRefsFromRaw(raw);
195
295
  return refs.size > 0 ? refs : void 0;
196
296
  } catch {
@@ -212,8 +312,8 @@ function validateSpawnModelParams(opts) {
212
312
  if (!MODEL_REF_RE.test(normalized)) {
213
313
  throw new Error(`invalid model "${opts.model}" (expected "provider/modelId")`);
214
314
  }
215
- const workerModels = path2.join(opts.pieDir, "models.json");
216
- const parentModels = path2.join(opts.parentConfigDir, "models.json");
315
+ const workerModels = path3.join(opts.pieDir, "models.json");
316
+ const parentModels = path3.join(opts.parentConfigDir, "models.json");
217
317
  const known = readKnownModelRefs(workerModels) ?? readKnownModelRefs(parentModels);
218
318
  if (known && known.size > 0) {
219
319
  if (known.has(normalized)) {
@@ -238,8 +338,8 @@ function validateSpawnModelParams(opts) {
238
338
  }
239
339
  function readSettingsDefaults(settingsPath) {
240
340
  try {
241
- if (!fs2.existsSync(settingsPath)) return {};
242
- const raw = JSON.parse(fs2.readFileSync(settingsPath, "utf8"));
341
+ if (!fs3.existsSync(settingsPath)) return {};
342
+ const raw = JSON.parse(fs3.readFileSync(settingsPath, "utf8"));
243
343
  const provider = typeof raw.defaultProvider === "string" ? raw.defaultProvider.trim() : "";
244
344
  const modelId = typeof raw.defaultModel === "string" ? raw.defaultModel.trim() : "";
245
345
  const thinking = typeof raw.defaultThinkingLevel === "string" && SPAWN_THINKING_LEVELS.has(raw.defaultThinkingLevel.trim()) ? raw.defaultThinkingLevel.trim() : void 0;
@@ -255,7 +355,7 @@ function readModelsJsonDefault(modelsPath) {
255
355
  const known = readKnownModelRefs(modelsPath);
256
356
  if (!known || known.size === 0) return void 0;
257
357
  try {
258
- const raw = JSON.parse(fs2.readFileSync(modelsPath, "utf8"));
358
+ const raw = JSON.parse(fs3.readFileSync(modelsPath, "utf8"));
259
359
  if (typeof raw.defaults?.provider === "string" && typeof raw.defaults?.modelId === "string") {
260
360
  const ref = `${raw.defaults.provider.trim()}/${raw.defaults.modelId.trim()}`;
261
361
  if (MODEL_REF_RE.test(ref)) return ref;
@@ -266,9 +366,9 @@ function readModelsJsonDefault(modelsPath) {
266
366
  }
267
367
  function readSessionHeadModel(sessionsDir, sessionId) {
268
368
  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"));
369
+ const headPath = path3.join(sessionsDir, sessionId, "head.json");
370
+ if (!fs3.existsSync(headPath)) return {};
371
+ const parsed = JSON.parse(fs3.readFileSync(headPath, "utf8"));
272
372
  const meta = parsed.metadata;
273
373
  const provider = typeof meta?.provider === "string" ? meta.provider.trim() : "";
274
374
  const modelId = typeof meta?.modelId === "string" ? meta.modelId.trim() : "";
@@ -282,9 +382,9 @@ function readSessionHeadModel(sessionsDir, sessionId) {
282
382
  }
283
383
  }
284
384
  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"));
385
+ const projectDefaults = readSettingsDefaults(path3.join(opts.cwd, ".pie", "settings.json"));
386
+ const workerDefaults = readSettingsDefaults(path3.join(opts.pieDir, "settings.json"));
387
+ const fallbackModel = readModelsJsonDefault(path3.join(opts.pieDir, "models.json"));
288
388
  const model = opts.explicitModel ?? opts.resumed?.model ?? projectDefaults.model ?? workerDefaults.model ?? fallbackModel;
289
389
  const thinkingLevel = opts.explicitThinking ?? opts.resumed?.thinkingLevel ?? projectDefaults.thinkingLevel ?? workerDefaults.thinkingLevel;
290
390
  return { model, thinkingLevel };
@@ -300,12 +400,12 @@ function isPidAlive(pid) {
300
400
  }
301
401
  function readLiveWorkerPeer(ipcRoot, sessionId, pid) {
302
402
  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)) {
403
+ const dir = path3.join(ipcRoot, "run", "ipc");
404
+ if (!fs3.existsSync(dir)) return void 0;
405
+ for (const file of fs3.readdirSync(dir)) {
306
406
  if (!file.endsWith(".json")) continue;
307
407
  try {
308
- const parsed = JSON.parse(fs2.readFileSync(path2.join(dir, file), "utf8"));
408
+ const parsed = JSON.parse(fs3.readFileSync(path3.join(dir, file), "utf8"));
309
409
  if (parsed.pid !== pid || parsed.sessionId !== sessionId) continue;
310
410
  if (!isPidAlive(pid)) return void 0;
311
411
  return {
@@ -336,7 +436,7 @@ async function waitForWorkerIpcReady(opts) {
336
436
  if (!isPidAlive(opts.pid)) return { exitedEarly: true };
337
437
  const remaining = deadline - Date.now();
338
438
  if (remaining <= 0) break;
339
- await new Promise((resolve2) => setTimeout(resolve2, Math.min(pollMs, remaining)));
439
+ await new Promise((resolve4) => setTimeout(resolve4, Math.min(pollMs, remaining)));
340
440
  }
341
441
  return { peer: readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid), exitedEarly: !isPidAlive(opts.pid) };
342
442
  }
@@ -364,12 +464,18 @@ async function buildSpawnReceipt(opts) {
364
464
  return { modelLabel, text };
365
465
  }
366
466
  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)) {
467
+ const relToParent = path3.relative(path3.resolve(parentConfigDir), path3.resolve(pieDir));
468
+ const allowedDestRoot = relToParent && !relToParent.startsWith("..") && !path3.isAbsolute(relToParent) ? parentConfigDir : path3.dirname(pieDir);
469
+ syncInheritedWorkerModels(path3.join(pieDir, "models.json"), path3.join(parentConfigDir, "models.json"), {
470
+ allowedDestRoot,
471
+ allowedSrcRoot: parentConfigDir
472
+ });
473
+ for (const file of ["config.json", "auth.json", "settings.json"]) {
474
+ const dst = path3.join(pieDir, file);
475
+ const src = path3.join(parentConfigDir, file);
476
+ if (!fs3.existsSync(dst) && fs3.existsSync(src)) {
371
477
  try {
372
- fs2.copyFileSync(src, dst);
478
+ fs3.copyFileSync(src, dst);
373
479
  } catch {
374
480
  }
375
481
  }
@@ -392,64 +498,26 @@ function resolveOperatorSessionsDir() {
392
498
  } catch {
393
499
  const override = process.env.PIE_SESSIONS_DIR;
394
500
  if (override !== void 0 && override !== "") {
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;
501
+ if (override === "~") return path4.join(os2.homedir(), ".pie", "sessions");
502
+ if (override.startsWith("~/")) return path4.join(os2.homedir(), override.slice(2));
503
+ if (path4.isAbsolute(override)) return override;
398
504
  }
399
- return path3.join(os.homedir(), ".pie", "sessions");
505
+ return path4.join(os2.homedir(), ".pie", "sessions");
400
506
  }
401
507
  }
402
- var DEFAULT_MAX_WORKERS = 50;
403
- var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: DEFAULT_MAX_WORKERS, killGraceMs: 15e3, defaultTtlMs: 0 };
404
508
  var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
405
509
  var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
406
510
  var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
407
- function configDirRoot() {
408
- const env = process.env.PIE_CODING_AGENT_DIR;
409
- if (!env) return path3.join(os.homedir(), ".pie");
410
- return path3.resolve(expandTilde(env));
411
- }
412
- function expandTilde(p) {
413
- return p === "~" ? os.homedir() : p.startsWith("~/") ? path3.join(os.homedir(), p.slice(2)) : p;
414
- }
415
- function configCandidates() {
416
- const candidates = [path3.join(configDirRoot(), "pie-proc.json")];
417
- const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
418
- if (pinnedRoot) {
419
- const pinDerived = path3.join(path3.dirname(path3.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
420
- if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
421
- } else if (configDirRoot() !== path3.join(os.homedir(), ".pie")) {
422
- candidates.push(path3.join(os.homedir(), ".pie", "pie-proc.json"));
423
- }
424
- return candidates;
425
- }
426
- function readConfig() {
427
- const candidates = configCandidates();
428
- for (const file of candidates) {
429
- try {
430
- const raw = JSON.parse(fs3.readFileSync(file, "utf8"));
431
- return {
432
- allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
433
- maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
434
- killGraceMs: typeof raw.killGraceMs === "number" && raw.killGraceMs >= 1e3 ? Math.floor(raw.killGraceMs) : DEFAULT_CONFIG.killGraceMs,
435
- defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
436
- };
437
- } catch {
438
- if (fs3.existsSync(file)) return { ...DEFAULT_CONFIG };
439
- }
440
- }
441
- return { ...DEFAULT_CONFIG };
442
- }
443
511
  function pieProcDir() {
444
512
  const pinned = process.env.PIE_PROC_REGISTRY_ROOT;
445
- if (pinned) return path3.resolve(expandTilde(pinned));
446
- return path3.join(configDirRoot(), "pie-proc");
513
+ if (pinned) return path4.resolve(expandTilde(pinned));
514
+ return path4.join(configDirRoot(), "pie-proc");
447
515
  }
448
516
  function registryFile() {
449
- return path3.join(pieProcDir(), "workers.json");
517
+ return path4.join(pieProcDir(), "workers.json");
450
518
  }
451
519
  function revisionFile(n) {
452
- return path3.join(pieProcDir(), `workers.r${n}.json`);
520
+ return path4.join(pieProcDir(), `workers.r${n}.json`);
453
521
  }
454
522
  function parseRegistry(rawText, file, revision) {
455
523
  let raw;
@@ -481,7 +549,7 @@ function parseRegistry(rawText, file, revision) {
481
549
  function latestRevisionOnDisk() {
482
550
  let max = 0;
483
551
  try {
484
- for (const entry of fs3.readdirSync(pieProcDir())) {
552
+ for (const entry of fs4.readdirSync(pieProcDir())) {
485
553
  const match = /^workers\.r(\d+)\.json$/.exec(entry);
486
554
  if (match) max = Math.max(max, Number(match[1]));
487
555
  }
@@ -495,7 +563,7 @@ function readRegistryUncached() {
495
563
  if (latest > 0) {
496
564
  const file2 = revisionFile(latest);
497
565
  try {
498
- return parseRegistry(fs3.readFileSync(file2, "utf8"), file2, latest);
566
+ return parseRegistry(fs4.readFileSync(file2, "utf8"), file2, latest);
499
567
  } catch (error) {
500
568
  if (error.code === "ENOENT") continue;
501
569
  throw error;
@@ -503,7 +571,7 @@ function readRegistryUncached() {
503
571
  }
504
572
  const file = registryFile();
505
573
  try {
506
- return parseRegistry(fs3.readFileSync(file, "utf8"), file, 0);
574
+ return parseRegistry(fs4.readFileSync(file, "utf8"), file, 0);
507
575
  } catch (error) {
508
576
  if (error.code === "ENOENT") return { revision: 0, workers: [] };
509
577
  throw error;
@@ -514,7 +582,7 @@ function readRegistryUncached() {
514
582
  function compactRevisions(_current) {
515
583
  }
516
584
  function casRegistry(mutate) {
517
- fs3.mkdirSync(pieProcDir(), { recursive: true });
585
+ fs4.mkdirSync(pieProcDir(), { recursive: true });
518
586
  for (let attempt = 0; attempt < 20; attempt += 1) {
519
587
  const snapshot = readRegistryUncached();
520
588
  const outcome = mutate(snapshot);
@@ -525,26 +593,26 @@ function casRegistry(mutate) {
525
593
  const nextRevision = snapshot.revision + 1;
526
594
  const target = revisionFile(nextRevision);
527
595
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}-${attempt}.tmp`;
528
- fs3.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
596
+ fs4.writeFileSync(tmp, JSON.stringify({ version: 2, revision: nextRevision, workers: outcome.next }, null, " "));
529
597
  if (latestRevisionOnDisk() > snapshot.revision) {
530
598
  try {
531
- fs3.rmSync(tmp, { force: true });
599
+ fs4.rmSync(tmp, { force: true });
532
600
  } catch {
533
601
  }
534
602
  continue;
535
603
  }
536
604
  try {
537
- fs3.linkSync(tmp, target);
605
+ fs4.linkSync(tmp, target);
538
606
  } catch (error) {
539
607
  try {
540
- fs3.rmSync(tmp, { force: true });
608
+ fs4.rmSync(tmp, { force: true });
541
609
  } catch {
542
610
  }
543
611
  if (error.code === "EEXIST") continue;
544
612
  throw error;
545
613
  }
546
614
  try {
547
- fs3.rmSync(tmp, { force: true });
615
+ fs4.rmSync(tmp, { force: true });
548
616
  } catch {
549
617
  }
550
618
  compactRevisions(nextRevision);
@@ -638,7 +706,7 @@ function verifyProcessEnvOwnership(pid, marker, pieDir) {
638
706
  if (process.platform === "linux") {
639
707
  let raw2;
640
708
  try {
641
- raw2 = fs3.readFileSync(`/proc/${pid}/environ`, "utf8");
709
+ raw2 = fs4.readFileSync(`/proc/${pid}/environ`, "utf8");
642
710
  } catch {
643
711
  return "unverified";
644
712
  }
@@ -684,7 +752,7 @@ function workerLiveness(record, opts = {}) {
684
752
  if (groupProbe === "eperm") return "unknown";
685
753
  const hasSpawnedAt = typeof record.spawnedAt === "number" && Number.isFinite(record.spawnedAt);
686
754
  if (!hasSpawnedAt) return "unknown";
687
- const bootAtMs = Date.now() - os.uptime() * 1e3;
755
+ const bootAtMs = Date.now() - os2.uptime() * 1e3;
688
756
  if (record.spawnedAt < bootAtMs - 5e3) return "dead";
689
757
  const members = readProcessGroupMembers(record.pid);
690
758
  if (members === void 0) return "unknown";
@@ -707,37 +775,6 @@ function workerLiveness(record, opts = {}) {
707
775
  }
708
776
  return "dead";
709
777
  }
710
- function canonicalDir(dir) {
711
- const resolved = path3.resolve(expandTilde(dir));
712
- const real = fs3.realpathSync(resolved);
713
- const stat = fs3.statSync(real);
714
- if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
715
- return real;
716
- }
717
- function cwdAllowedOrThrow(cwd, allow) {
718
- const canonical = canonicalDir(cwd);
719
- for (const root of allow) {
720
- try {
721
- const canonicalRoot = canonicalDir(root);
722
- if (canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path3.sep)) return canonical;
723
- } catch {
724
- }
725
- }
726
- const file = configCandidates()[0];
727
- let exists = false;
728
- try {
729
- exists = fs3.existsSync(file);
730
- } catch {
731
- }
732
- const effective = configCandidates().find((c) => {
733
- try {
734
- return fs3.existsSync(c);
735
- } catch {
736
- return false;
737
- }
738
- }) ?? file;
739
- throw new Error(exists || effective !== file ? `cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots in ${effective}; edit that file \u2014 it is re-read on every spawn, so no host restart is needed` : `cwd "${cwd}" is outside the pie-proc allowCwd roots: there is no config yet at ${effective}. Create it with {"allowCwd": ["${cwd}"]} \u2014 it is read on every spawn, so no host restart is needed`);
740
- }
741
778
  function safeName(name) {
742
779
  return /^[a-z0-9][a-z0-9-_]{0,47}$/i.test(name);
743
780
  }
@@ -762,10 +799,10 @@ function sanitizeImForward(raw) {
762
799
  }
763
800
  function readUserImForwardIdentity() {
764
801
  try {
765
- const candidates = [path3.join(configDirRoot(), "im-forward.json")];
802
+ const candidates = [path4.join(configDirRoot(), "im-forward.json")];
766
803
  for (const file of candidates) {
767
804
  try {
768
- const parsed = JSON.parse(fs3.readFileSync(file, "utf8"));
805
+ const parsed = JSON.parse(fs4.readFileSync(file, "utf8"));
769
806
  const provider = typeof parsed.provider === "string" ? parsed.provider : "feishu";
770
807
  const settings = parsed.providers?.[provider];
771
808
  if (!settings) continue;
@@ -782,12 +819,12 @@ function readUserImForwardIdentity() {
782
819
  return void 0;
783
820
  }
784
821
  function cliEntry() {
785
- const moduleDir = path3.dirname(fileURLToPath(import.meta.url));
822
+ const moduleDir = path4.dirname(fileURLToPath(import.meta.url));
786
823
  for (const rel of ["../../../src/cli.ts", "../../../cli.js"]) {
787
- const candidate = path3.resolve(moduleDir, rel);
824
+ const candidate = path4.resolve(moduleDir, rel);
788
825
  try {
789
- const real = fs3.realpathSync(candidate);
790
- if (fs3.statSync(real).isFile()) return real;
826
+ const real = fs4.realpathSync(candidate);
827
+ if (fs4.statSync(real).isFile()) return real;
791
828
  } catch {
792
829
  }
793
830
  }
@@ -797,10 +834,10 @@ function loaderArgs() {
797
834
  for (let i = 0; i < process.execArgv.length - 1; i += 1) {
798
835
  if (process.execArgv[i] === "--import") {
799
836
  const target = process.execArgv[i + 1];
800
- if (target && !path3.isAbsolute(target) && !target.startsWith("file:")) {
837
+ if (target && !path4.isAbsolute(target) && !target.startsWith("file:")) {
801
838
  try {
802
- const pkgRoot = path3.dirname(require_.resolve(`${target}/package.json`, { paths: [path3.dirname(cliEntry())] }));
803
- return ["--import", path3.join(pkgRoot, "dist", "loader.mjs")];
839
+ const pkgRoot = path4.dirname(require_.resolve(`${target}/package.json`, { paths: [path4.dirname(cliEntry())] }));
840
+ return ["--import", path4.join(pkgRoot, "dist", "loader.mjs")];
804
841
  } catch {
805
842
  return [];
806
843
  }
@@ -811,7 +848,7 @@ function loaderArgs() {
811
848
  return [];
812
849
  }
813
850
  function logDir() {
814
- return path3.join(pieProcDir(), "logs");
851
+ return path4.join(pieProcDir(), "logs");
815
852
  }
816
853
  var toolText = (text, isError = false) => ({ content: [{ type: "text", text }], details: {}, ...isError ? { isError: true } : {} });
817
854
  function pieProc(ctx) {
@@ -823,18 +860,18 @@ function pieProc(ctx) {
823
860
  const observeActivity = (record) => {
824
861
  const logTime = (() => {
825
862
  try {
826
- return fs3.statSync(path3.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
863
+ return fs4.statSync(path4.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
827
864
  } catch {
828
865
  return record.lastActiveAt;
829
866
  }
830
867
  })();
831
868
  if (record.pid === 0) return logTime;
832
- const statusRoot = path3.join(path3.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
869
+ const statusRoot = path4.join(path4.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
833
870
  try {
834
- for (const file of fs3.readdirSync(statusRoot)) {
871
+ for (const file of fs4.readdirSync(statusRoot)) {
835
872
  if (!file.endsWith(".json")) continue;
836
873
  try {
837
- const status = JSON.parse(fs3.readFileSync(path3.join(statusRoot, file), "utf8"));
874
+ const status = JSON.parse(fs4.readFileSync(path4.join(statusRoot, file), "utf8"));
838
875
  if (status.sessionId === record.sessionId && status.state === "working") return Date.now();
839
876
  } catch {
840
877
  }
@@ -997,20 +1034,20 @@ function pieProc(ctx) {
997
1034
  if (params.kind === "oneshot" && params.imForward) throw new Error("imForward applies to resident workers only");
998
1035
  if (params.kind !== "resident" && params.ttlMs !== void 0) throw new Error("ttlMs applies to resident workers only");
999
1036
  if (params.kind !== "resident" && params.resumeSessionId) throw new Error("resumeSessionId applies to resident workers only");
1000
- const canonicalCwd = cwdAllowedOrThrow(params.cwd, currentConfig().allowCwd);
1037
+ const canonicalCwd = cwdAllowedOrThrow(params.cwd, readConfigDetailed());
1001
1038
  const entry = cliEntry();
1002
1039
  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() });
1040
+ const validatedModel = validateSpawnModelParams({ model: params.model, thinkingLevel: params.thinkingLevel, pieDir: path4.join(pieProcDir(), "agents", params.name), parentConfigDir: configDirRoot() });
1004
1041
  let resumeSessionId;
1005
1042
  let resumeSessionsDir;
1006
1043
  if (params.resumeSessionId) {
1007
1044
  if (!/^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(params.resumeSessionId)) throw new Error(`invalid resumeSessionId "${params.resumeSessionId}"`);
1008
1045
  const operatorSessionsDir = resolveOperatorSessionsDir();
1009
- const workerSessionsDir = path3.join(pieProcDir(), "agents", params.name, "sessions");
1046
+ const workerSessionsDir = path4.join(pieProcDir(), "agents", params.name, "sessions");
1010
1047
  let recordedCwd;
1011
1048
  for (const dir of [workerSessionsDir, operatorSessionsDir]) {
1012
1049
  try {
1013
- const head = JSON.parse(fs3.readFileSync(path3.join(dir, params.resumeSessionId, "head.json"), "utf8"));
1050
+ const head = JSON.parse(fs4.readFileSync(path4.join(dir, params.resumeSessionId, "head.json"), "utf8"));
1014
1051
  recordedCwd = head.metadata?.cwd;
1015
1052
  resumeSessionsDir = dir;
1016
1053
  break;
@@ -1021,7 +1058,7 @@ function pieProc(ctx) {
1021
1058
  if (typeof recordedCwd !== "string" || !recordedCwd) throw new Error(`session "${params.resumeSessionId}" has no recorded cwd; resume requires one`);
1022
1059
  let canonicalRecorded = recordedCwd;
1023
1060
  try {
1024
- canonicalRecorded = fs3.realpathSync(recordedCwd);
1061
+ canonicalRecorded = fs4.realpathSync(recordedCwd);
1025
1062
  } catch {
1026
1063
  }
1027
1064
  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`);
@@ -1098,12 +1135,12 @@ function pieProc(ctx) {
1098
1135
  });
1099
1136
  let child;
1100
1137
  try {
1101
- const pieDir = path3.join(pieProcDir(), "agents", params.name);
1102
- fs3.mkdirSync(pieDir, { recursive: true });
1138
+ const pieDir = path4.join(pieProcDir(), "agents", params.name);
1139
+ fs4.mkdirSync(pieDir, { recursive: true });
1103
1140
  inheritWorkerConfigFiles(pieDir, configDirRoot());
1104
1141
  if (imForward) {
1105
- const imFile = path3.join(pieDir, "im-forward.json");
1106
- if (!fs3.existsSync(imFile)) {
1142
+ const imFile = path4.join(pieDir, "im-forward.json");
1143
+ if (!fs4.existsSync(imFile)) {
1107
1144
  const provider = typeof imForward.provider === "string" && imForward.provider.trim() ? imForward.provider : "feishu";
1108
1145
  const providerSettings = {};
1109
1146
  for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
@@ -1115,15 +1152,15 @@ function pieProc(ctx) {
1115
1152
  providers: { [provider]: providerSettings }
1116
1153
  };
1117
1154
  if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
1118
- fs3.writeFileSync(imFile, JSON.stringify(doc, null, " "));
1155
+ fs4.writeFileSync(imFile, JSON.stringify(doc, null, " "));
1119
1156
  }
1120
1157
  }
1121
- fs3.mkdirSync(logDir(), { recursive: true });
1122
- const logFile = fs3.openSync(path3.join(logDir(), `${params.name}.jsonl`), "a");
1158
+ fs4.mkdirSync(logDir(), { recursive: true });
1159
+ const logFile = fs4.openSync(path4.join(logDir(), `${params.name}.jsonl`), "a");
1123
1160
  const modelArgs = [...validatedModel.model ? ["--model", validatedModel.model] : [], ...validatedModel.thinkingLevel ? ["--thinking", validatedModel.thinkingLevel] : []];
1124
1161
  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()));
1162
+ const inheritedIpcRoot = path4.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1163
+ const inheritedRegistryRoot = path4.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
1127
1164
  const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
1128
1165
  const childEnv = {
1129
1166
  ...inheritedEnv,
@@ -1157,12 +1194,12 @@ function pieProc(ctx) {
1157
1194
  });
1158
1195
  } finally {
1159
1196
  try {
1160
- fs3.closeSync(logFile);
1197
+ fs4.closeSync(logFile);
1161
1198
  } catch {
1162
1199
  }
1163
1200
  }
1164
1201
  if (typeof child.pid !== "number") {
1165
- throw new Error(`worker spawn failed (no pid) \u2014 see ${path3.join(logDir(), `${params.name}.jsonl`)}`);
1202
+ throw new Error(`worker spawn failed (no pid) \u2014 see ${path4.join(logDir(), `${params.name}.jsonl`)}`);
1166
1203
  }
1167
1204
  child.unref();
1168
1205
  const record = {
@@ -1210,7 +1247,7 @@ function pieProc(ctx) {
1210
1247
  cwd: record.cwd,
1211
1248
  pieDir,
1212
1249
  ipcRoot: inheritedIpcRoot,
1213
- logPath: path3.join(logDir(), `${params.name}.jsonl`),
1250
+ logPath: path4.join(logDir(), `${params.name}.jsonl`),
1214
1251
  ttlMs: params.ttlMs,
1215
1252
  explicitModel: validatedModel.model,
1216
1253
  explicitThinking: validatedModel.thinkingLevel,
@@ -1338,7 +1375,7 @@ function pieProc(ctx) {
1338
1375
  const action = args.action;
1339
1376
  if (action === "list") {
1340
1377
  const snap = readRegistryUncached();
1341
- const ipcRoot = path3.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1378
+ const ipcRoot = path4.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1342
1379
  const rows = snap.workers.map((w) => {
1343
1380
  const model = liveWorkerModelLabel(ipcRoot, w.sessionId, w.pid);
1344
1381
  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) };