@cydm/pie 4.13.1 → 4.14.1

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 (34) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +4 -4
  2. package/dist/builtin/extensions/cron/index.js +70 -17
  3. package/dist/builtin/extensions/im-forward/index.js +8094 -8100
  4. package/dist/builtin/extensions/mcp-adapter/index.js +86 -81
  5. package/dist/builtin/extensions/memory/index.js +30 -7
  6. package/dist/builtin/extensions/pie-ipc/index.js +13 -18
  7. package/dist/builtin/extensions/pie-proc/README.md +12 -3
  8. package/dist/builtin/extensions/pie-proc/index.js +145 -96
  9. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  10. package/dist/builtin/extensions/subagent/index.js +5 -5
  11. package/dist/builtin/extensions/todo/index.js +4 -4
  12. package/dist/chunks/{chunk-6Z54UHXM.js → chunk-2WLKAMOH.js} +21 -16
  13. package/dist/chunks/{chunk-3F2CSVNH.js → chunk-DJ4LO7PQ.js} +2 -1
  14. package/dist/chunks/{chunk-MCR4JYI6.js → chunk-IM7DLPPY.js} +74 -8
  15. package/dist/chunks/{chunk-HSMO2BEA.js → chunk-IQDVL34H.js} +24 -19
  16. package/dist/chunks/{chunk-DT22BBZL.js → chunk-OQCKDEEE.js} +1 -1
  17. package/dist/chunks/{chunk-26KRUYZH.js → chunk-SAXKBFX3.js} +1 -1
  18. package/dist/chunks/{chunk-CCPNHS6B.js → chunk-SYZR74QO.js} +1582 -1570
  19. package/dist/chunks/{chunk-UCVPNLCO.js → chunk-TNRZEQD5.js} +2 -2
  20. package/dist/chunks/{chunk-NHWWRE3T.js → chunk-TTSQWGAT.js} +727 -719
  21. package/dist/chunks/{chunk-XPJHZRTN.js → chunk-X3ZVZB2R.js} +1133 -381
  22. package/dist/chunks/{host-image-fallback-LGWYQMLA.js → host-image-fallback-AEKY2LSZ.js} +1 -1
  23. package/dist/chunks/{manager-cli-OTIMAWO6.js → manager-cli-ZV36YNPJ.js} +187 -173
  24. package/dist/chunks/{memory-git-7SRO5KLB.js → memory-git-G56IXFWU.js} +5 -5
  25. package/dist/chunks/{model-registry-IWOOAMLZ.js → model-registry-4LM2I6FR.js} +2 -2
  26. package/dist/chunks/{read-file-understanding-3TYWVOLX.js → read-file-understanding-GTNZHAK5.js} +5 -5
  27. package/dist/chunks/{src-WA2O2O2V.js → src-3YJ4UVEC.js} +3 -3
  28. package/dist/chunks/{src-ALHMJZ5R.js → src-APNP4M4N.js} +2 -2
  29. package/dist/chunks/{src-D2ICRXWW.js → src-T6AUO53N.js} +24 -6
  30. package/dist/chunks/{src-76Q33OY5.js → src-TNUD7EDH.js} +1 -1
  31. package/dist/chunks/{test-stream-OVGDTXOY.js → test-stream-EF2DHEHV.js} +1 -1
  32. package/dist/cli.js +3131 -3013
  33. package/package.json +1 -1
  34. package/dist/chunks/{chunk-3GG342QY.js → chunk-TYCKSYUF.js} +19 -19
@@ -25,7 +25,7 @@ import {
25
25
  takeDispatchFrame,
26
26
  wrapInboundText,
27
27
  wrappedMessageMarker
28
- } from "../../../chunks/chunk-3GG342QY.js";
28
+ } from "../../../chunks/chunk-TYCKSYUF.js";
29
29
  import {
30
30
  Type
31
31
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -35,7 +35,6 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
35
35
  import * as fs3 from "node:fs";
36
36
  import * as os from "node:os";
37
37
  import * as path4 from "node:path";
38
- import { randomUUID } from "node:crypto";
39
38
 
40
39
  // builtin/extensions/pie-ipc/discovery.ts
41
40
  import * as fs2 from "node:fs";
@@ -1081,11 +1080,11 @@ function fitPeekSnapshotToFrame(snapshot, frameBytes, maxBytes = 8e3) {
1081
1080
  return text;
1082
1081
  }
1083
1082
 
1084
- // builtin/extensions/pie-ipc/index.ts
1083
+ // builtin/extensions/pie-ipc/runtime-base.ts
1085
1084
  var DEFAULT_NOTIFY_FALLBACK_MS = 6e5;
1086
1085
  var FALLBACK_RENEWAL_CAP = 4;
1087
1086
  var PROBE_CACHE_MS = 2e3;
1088
- var Runtime = class {
1087
+ var RuntimeBase = class {
1089
1088
  constructor(ctx, config, discoveryDir) {
1090
1089
  this.ctx = ctx;
1091
1090
  this.config = config;
@@ -1289,7 +1288,8 @@ var Runtime = class {
1289
1288
  const status = this.currentStatus();
1290
1289
  let queueGate;
1291
1290
  try {
1292
- queueGate = this.ctx.getQueueGateDiagnostics?.();
1291
+ const diagnosticContext = this.ctx;
1292
+ queueGate = diagnosticContext.getQueueGateDiagnostics?.();
1293
1293
  } catch {
1294
1294
  }
1295
1295
  reply("state", JSON.stringify({
@@ -1772,13 +1772,12 @@ ${outcome.text}`
1772
1772
  } catch {
1773
1773
  }
1774
1774
  }
1775
- /** A completion notification (or its inbox delivery) landed for our send.
1776
- * Observability-aware (final audit): an INJECTING host shows the message
1777
- * to the model the moment it lands — the fallback timer dies (single
1778
- * wake). An INBOX-ONLY host (embedded) has no scheduler: inbox landing is
1779
- * not observation, so instead of silently cancelling the only wake, the
1780
- * fallback fires IMMEDIATELY as a [ipc-done-check] hint carrying the
1781
- * outcome — every host kind surfaces the completion exactly once. */
1775
+ };
1776
+
1777
+ // builtin/extensions/pie-ipc/runtime.ts
1778
+ import { randomUUID } from "node:crypto";
1779
+ var Runtime = class extends RuntimeBase {
1780
+ /** Surface an inbox-only completion exactly once instead of silently cancelling its fallback. */
1782
1781
  completeNotify(requestId, userAssigned = false) {
1783
1782
  const willInject = this.delivery?.willInjectNow() ?? this.ctx.capabilities.editorInjection;
1784
1783
  if (willInject) {
@@ -1796,12 +1795,6 @@ ${outcome.text}`
1796
1795
  } catch {
1797
1796
  }
1798
1797
  }
1799
- /** A completion notification (or its inbox delivery) landed for our send:
1800
- * destroy the fallback OPERATION so the model is woken exactly once —
1801
- * including a query-in-flight fallback (review r4-P1): finishOp cancels
1802
- * the in-flight continuation, which then exits without renewing or
1803
- * waking. Also records completion for sends whose push arrived BEFORE
1804
- * the ack did — armNotifyFallback then arms nothing. */
1805
1798
  clearNotifyFallback(requestId) {
1806
1799
  if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1807
1800
  this.completedNotifies.add(requestId);
@@ -2154,6 +2147,8 @@ ${message.text}`).join("\n---\n");
2154
2147
  await this.transport?.closeAndFlush();
2155
2148
  }
2156
2149
  };
2150
+
2151
+ // builtin/extensions/pie-ipc/index.ts
2157
2152
  function loadConfig(ctx, configDir) {
2158
2153
  try {
2159
2154
  const layers = [
@@ -6,8 +6,11 @@ directories, isolated agent dirs, caps, TTL sweeping, and an audit ledger.
6
6
 
7
7
  ## Host gating
8
8
 
9
- Activates on `longLived` (interactive TUI and resident json-events hosts —
10
- the manager). One-shot print hosts never own workers.
9
+ Role-pruned to the resident manager (`capabilities.unattended === true` and
10
+ `PIE_PROC_CURATED_NAME === "manager"`): both the `pie_proc` tool and the 60s
11
+ background `sweepTimer` activate only on the manager. Interactive TUI hosts,
12
+ worker processes, and one-shot print hosts never register the tool or run
13
+ background registry sweeps.
11
14
 
12
15
  ## Tool: `pie_proc`
13
16
 
@@ -85,7 +88,13 @@ fallback on Windows 11+); a probe failure is `unknown`, and unknown is
85
88
  never signalled. A v1 registry (records without generation) fails CLOSED
86
89
  with a migration error. Abandoned pending reservations are reaped only
87
90
  when their reserver process is confirmed dead (same-process aborted spawns
88
- are retried by the sweep). Every spawn/kill/TTL reap goes to the extension
91
+ are retried by the sweep). Idle-activity persistence is bounded to avoid
92
+ unbounded revision churn: `ttl === 0` resident workers never write
93
+ `lastActiveAt` bumps on log mtime changes (`pie_proc list` reads live
94
+ activity on demand), while `ttl > 0` workers throttle `lastActiveAt`
95
+ persists, maintain an in-memory high-water mark per generation, and
96
+ re-verify live activity immediately before authorizing any idle-TTL
97
+ `SIGTERM`. Every spawn/kill/TTL reap goes to the extension
89
98
  log (verbose mode / host transcript).
90
99
 
91
100
  ## Design notes
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "node:module"; const require =
2
2
  import {
3
3
  registerWorkerLifecycleBridge,
4
4
  syncInheritedWorkerModels
5
- } from "../../../chunks/chunk-DT22BBZL.js";
5
+ } from "../../../chunks/chunk-OQCKDEEE.js";
6
6
  import {
7
7
  readProcessCommandLine
8
8
  } from "../../../chunks/chunk-7RJXKN7N.js";
@@ -11,29 +11,30 @@ import {
11
11
  } from "../../../chunks/chunk-Q5PSWX3B.js";
12
12
  import "../../../chunks/chunk-Q4NJEPIZ.js";
13
13
  import {
14
- loadResolvedModelsConfig
15
- } from "../../../chunks/chunk-NHWWRE3T.js";
14
+ loadResolvedModelsConfig,
15
+ normalizeModelClassRoutes
16
+ } from "../../../chunks/chunk-TTSQWGAT.js";
16
17
  import "../../../chunks/chunk-CBDQJMUI.js";
17
18
  import {
18
19
  redactText
19
- } from "../../../chunks/chunk-XPJHZRTN.js";
20
+ } from "../../../chunks/chunk-X3ZVZB2R.js";
20
21
  import {
21
22
  isCompactSummaryMessage
22
- } from "../../../chunks/chunk-CCPNHS6B.js";
23
- import "../../../chunks/chunk-26KRUYZH.js";
24
- import "../../../chunks/chunk-MCR4JYI6.js";
23
+ } from "../../../chunks/chunk-SYZR74QO.js";
24
+ import "../../../chunks/chunk-SAXKBFX3.js";
25
+ import "../../../chunks/chunk-IM7DLPPY.js";
25
26
  import {
26
27
  Type
27
28
  } from "../../../chunks/chunk-XXGYUYXI.js";
28
29
  import "../../../chunks/chunk-LZQXQOPJ.js";
29
30
 
30
31
  // builtin/extensions/pie-proc/index.ts
31
- import { execFileSync, spawn } from "node:child_process";
32
+ import { execFileSync as execFileSync2, spawn } from "node:child_process";
32
33
  import { createRequire } from "node:module";
33
34
  import { fileURLToPath } from "node:url";
34
- import * as fs4 from "node:fs";
35
- import * as os3 from "node:os";
36
- import * as path4 from "node:path";
35
+ import * as fs5 from "node:fs";
36
+ import * as os4 from "node:os";
37
+ import * as path5 from "node:path";
37
38
 
38
39
  // builtin/extensions/pie-proc/panel-bridge.ts
39
40
  import * as fs from "node:fs";
@@ -674,12 +675,10 @@ import * as fs3 from "node:fs";
674
675
  import * as path3 from "node:path";
675
676
  var SPAWN_THINKING_LEVELS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
676
677
  var MODEL_REF_RE = /^[^/\s]+\/\S+$/;
677
- function collectModelRefsFromRaw(raw) {
678
+ function collectModelRefsFromConfig(config) {
678
679
  const refs = /* @__PURE__ */ new Set();
679
- if (!raw || typeof raw !== "object") return refs;
680
- const doc = raw;
681
- if (doc.providers && typeof doc.providers === "object") {
682
- for (const [provider, cfg] of Object.entries(doc.providers)) {
680
+ if (config.profiles) {
681
+ for (const [provider, cfg] of Object.entries(config.profiles)) {
683
682
  if (!Array.isArray(cfg?.models)) continue;
684
683
  for (const m of cfg.models) {
685
684
  if (typeof m?.id === "string" && m.id.trim()) {
@@ -688,15 +687,15 @@ function collectModelRefsFromRaw(raw) {
688
687
  }
689
688
  }
690
689
  }
691
- if (doc.defaults && typeof doc.defaults === "object") {
692
- if (typeof doc.defaults.provider === "string" && typeof doc.defaults.modelId === "string") {
693
- refs.add(`${doc.defaults.provider.trim()}/${doc.defaults.modelId.trim()}`);
694
- }
695
- if (doc.defaults.modelClasses && typeof doc.defaults.modelClasses === "object") {
696
- for (const entry of Object.values(doc.defaults.modelClasses)) {
697
- const list = Array.isArray(entry) ? entry : [entry];
698
- for (const cls of list) {
699
- if (typeof cls?.provider === "string" && typeof cls?.modelId === "string") {
690
+ if (config.defaults) {
691
+ if (typeof config.defaults.provider === "string" && typeof config.defaults.modelId === "string") {
692
+ refs.add(`${config.defaults.provider.trim()}/${config.defaults.modelId.trim()}`);
693
+ }
694
+ if (config.defaults.modelClasses) {
695
+ for (const entry of Object.values(config.defaults.modelClasses)) {
696
+ for (const cls of normalizeModelClassRoutes(entry)) {
697
+ if (!cls || typeof cls !== "object") continue;
698
+ if (typeof cls.provider === "string" && typeof cls.modelId === "string") {
700
699
  refs.add(`${cls.provider.trim()}/${cls.modelId.trim()}`);
701
700
  }
702
701
  }
@@ -705,17 +704,39 @@ function collectModelRefsFromRaw(raw) {
705
704
  }
706
705
  return refs;
707
706
  }
707
+ function collectModelRefsFromMinimalFixture(raw) {
708
+ const refs = /* @__PURE__ */ new Set();
709
+ if (!raw || typeof raw !== "object") return refs;
710
+ const doc = raw;
711
+ for (const group of [doc.profiles, doc.providers]) {
712
+ if (!group || typeof group !== "object") continue;
713
+ for (const [provider, cfg] of Object.entries(group)) {
714
+ if (!Array.isArray(cfg?.models)) continue;
715
+ for (const m of cfg.models) {
716
+ if (typeof m?.id === "string" && m.id.trim()) {
717
+ refs.add(`${provider.trim()}/${m.id.trim()}`);
718
+ }
719
+ }
720
+ }
721
+ }
722
+ if (doc.defaults && typeof doc.defaults === "object") {
723
+ for (const ref of collectModelRefsFromConfig({ defaults: doc.defaults })) {
724
+ refs.add(ref);
725
+ }
726
+ }
727
+ return refs;
728
+ }
708
729
  function readKnownModelRefs(modelsPath) {
709
730
  if (!fs3.existsSync(modelsPath)) return void 0;
710
731
  try {
711
732
  const resolved = loadResolvedModelsConfig(modelsPath);
712
- const refs = collectModelRefsFromRaw(resolved.config);
733
+ const refs = collectModelRefsFromConfig(resolved.config);
713
734
  if (refs.size > 0) return refs;
714
735
  } catch {
715
736
  }
716
737
  try {
717
738
  const raw = JSON.parse(fs3.readFileSync(modelsPath, "utf8"));
718
- const refs = collectModelRefsFromRaw(raw);
739
+ const refs = collectModelRefsFromMinimalFixture(raw);
719
740
  return refs.size > 0 ? refs : void 0;
720
741
  } catch {
721
742
  return void 0;
@@ -779,12 +800,21 @@ function readModelsJsonDefault(modelsPath) {
779
800
  const known = readKnownModelRefs(modelsPath);
780
801
  if (!known || known.size === 0) return void 0;
781
802
  try {
782
- const raw = JSON.parse(fs3.readFileSync(modelsPath, "utf8"));
783
- if (typeof raw.defaults?.provider === "string" && typeof raw.defaults?.modelId === "string") {
784
- const ref = `${raw.defaults.provider.trim()}/${raw.defaults.modelId.trim()}`;
803
+ const resolved = loadResolvedModelsConfig(modelsPath);
804
+ const { provider, modelId } = resolved.config.defaults ?? {};
805
+ if (typeof provider === "string" && typeof modelId === "string") {
806
+ const ref = `${provider.trim()}/${modelId.trim()}`;
785
807
  if (MODEL_REF_RE.test(ref)) return ref;
786
808
  }
787
809
  } catch {
810
+ try {
811
+ const raw = JSON.parse(fs3.readFileSync(modelsPath, "utf8"));
812
+ if (typeof raw.defaults?.provider === "string" && typeof raw.defaults?.modelId === "string") {
813
+ const ref = `${raw.defaults.provider.trim()}/${raw.defaults.modelId.trim()}`;
814
+ if (MODEL_REF_RE.test(ref)) return ref;
815
+ }
816
+ } catch {
817
+ }
788
818
  }
789
819
  return [...known][0];
790
820
  }
@@ -860,7 +890,7 @@ async function waitForWorkerIpcReady(opts) {
860
890
  if (!isPidAlive(opts.pid)) return { exitedEarly: true };
861
891
  const remaining = deadline - Date.now();
862
892
  if (remaining <= 0) break;
863
- await new Promise((resolve5) => setTimeout(resolve5, Math.min(pollMs, remaining)));
893
+ await new Promise((resolve6) => setTimeout(resolve6, Math.min(pollMs, remaining)));
864
894
  }
865
895
  return { peer: readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid), exitedEarly: !isPidAlive(opts.pid) };
866
896
  }
@@ -913,22 +943,11 @@ function liveWorkerModelLabel(ipcRoot, sessionId, pid) {
913
943
  return lvl ? `${peer.model} (${lvl})` : peer.model;
914
944
  }
915
945
 
916
- // builtin/extensions/pie-proc/index.ts
917
- var require_ = createRequire(import.meta.url);
918
- function resolveOperatorSessionsDir() {
919
- try {
920
- const { getSessionsDir } = require_("../../../src/config.js");
921
- return getSessionsDir();
922
- } catch {
923
- const override = process.env.PIE_SESSIONS_DIR;
924
- if (override !== void 0 && override !== "") {
925
- if (override === "~") return path4.join(os3.homedir(), ".pie", "sessions");
926
- if (override.startsWith("~/")) return path4.join(os3.homedir(), override.slice(2));
927
- if (path4.isAbsolute(override)) return override;
928
- }
929
- return path4.join(os3.homedir(), ".pie", "sessions");
930
- }
931
- }
946
+ // builtin/extensions/pie-proc/proc-runtime.ts
947
+ import { execFileSync } from "node:child_process";
948
+ import * as fs4 from "node:fs";
949
+ import * as os3 from "node:os";
950
+ import * as path4 from "node:path";
932
951
  var IM_FORWARD_CONTROL_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "retryBackoffMs"]);
933
952
  var IM_FORWARD_FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["providers", "__proto__", "constructor", "prototype", "toString", "valueOf"]);
934
953
  var SAFE_PROVIDER_ID = /^[a-z][a-z0-9_-]{0,31}$/i;
@@ -1297,13 +1316,30 @@ function readUserImForwardIdentity() {
1297
1316
  }
1298
1317
  return void 0;
1299
1318
  }
1319
+
1320
+ // builtin/extensions/pie-proc/index.ts
1321
+ var require_ = createRequire(import.meta.url);
1322
+ function resolveOperatorSessionsDir() {
1323
+ try {
1324
+ const { getSessionsDir } = require_("../../../src/config.js");
1325
+ return getSessionsDir();
1326
+ } catch {
1327
+ const override = process.env.PIE_SESSIONS_DIR;
1328
+ if (override !== void 0 && override !== "") {
1329
+ if (override === "~") return path5.join(os4.homedir(), ".pie", "sessions");
1330
+ if (override.startsWith("~/")) return path5.join(os4.homedir(), override.slice(2));
1331
+ if (path5.isAbsolute(override)) return override;
1332
+ }
1333
+ return path5.join(os4.homedir(), ".pie", "sessions");
1334
+ }
1335
+ }
1300
1336
  function cliEntry() {
1301
- const moduleDir = path4.dirname(fileURLToPath(import.meta.url));
1337
+ const moduleDir = path5.dirname(fileURLToPath(import.meta.url));
1302
1338
  for (const rel of ["../../../src/cli.ts", "../../../cli.js"]) {
1303
- const candidate = path4.resolve(moduleDir, rel);
1339
+ const candidate = path5.resolve(moduleDir, rel);
1304
1340
  try {
1305
- const real = fs4.realpathSync(candidate);
1306
- if (fs4.statSync(real).isFile()) return real;
1341
+ const real = fs5.realpathSync(candidate);
1342
+ if (fs5.statSync(real).isFile()) return real;
1307
1343
  } catch {
1308
1344
  }
1309
1345
  }
@@ -1313,10 +1349,10 @@ function loaderArgs() {
1313
1349
  for (let i = 0; i < process.execArgv.length - 1; i += 1) {
1314
1350
  if (process.execArgv[i] === "--import") {
1315
1351
  const target = process.execArgv[i + 1];
1316
- if (target && !path4.isAbsolute(target) && !target.startsWith("file:")) {
1352
+ if (target && !path5.isAbsolute(target) && !target.startsWith("file:")) {
1317
1353
  try {
1318
- const pkgRoot = path4.dirname(require_.resolve(`${target}/package.json`, { paths: [path4.dirname(cliEntry())] }));
1319
- return ["--import", path4.join(pkgRoot, "dist", "loader.mjs")];
1354
+ const pkgRoot = path5.dirname(require_.resolve(`${target}/package.json`, { paths: [path5.dirname(cliEntry())] }));
1355
+ return ["--import", path5.join(pkgRoot, "dist", "loader.mjs")];
1320
1356
  } catch {
1321
1357
  return [];
1322
1358
  }
@@ -1327,7 +1363,7 @@ function loaderArgs() {
1327
1363
  return [];
1328
1364
  }
1329
1365
  function logDir() {
1330
- return path4.join(pieProcDir(), "logs");
1366
+ return path5.join(pieProcDir(), "logs");
1331
1367
  }
1332
1368
  var toolText = (text, isError = false) => ({ content: [{ type: "text", text }], details: {}, ...isError ? { isError: true } : {} });
1333
1369
  function pieProc(ctx) {
@@ -1339,18 +1375,18 @@ function pieProc(ctx) {
1339
1375
  const observeActivity = (record) => {
1340
1376
  const logTime = (() => {
1341
1377
  try {
1342
- return fs4.statSync(path4.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
1378
+ return fs5.statSync(path5.join(logDir(), `${record.name}.jsonl`)).mtimeMs;
1343
1379
  } catch {
1344
1380
  return record.lastActiveAt;
1345
1381
  }
1346
1382
  })();
1347
1383
  if (record.pid === 0) return logTime;
1348
- const statusRoot = path4.join(path4.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
1384
+ const statusRoot = path5.join(path5.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot())), "run", "ipc");
1349
1385
  try {
1350
- for (const file of fs4.readdirSync(statusRoot)) {
1386
+ for (const file of fs5.readdirSync(statusRoot)) {
1351
1387
  if (!file.endsWith(".json")) continue;
1352
1388
  try {
1353
- const status = JSON.parse(fs4.readFileSync(path4.join(statusRoot, file), "utf8"));
1389
+ const status = JSON.parse(fs5.readFileSync(path5.join(statusRoot, file), "utf8"));
1354
1390
  if (status.sessionId === record.sessionId && status.state === "working") return Date.now();
1355
1391
  } catch {
1356
1392
  }
@@ -1359,15 +1395,13 @@ function pieProc(ctx) {
1359
1395
  }
1360
1396
  return logTime;
1361
1397
  };
1362
- const persistActivity = (record, at) => {
1363
- try {
1364
- updateRegistry((snap) => ({
1365
- next: snap.workers.map((w) => w.generation === record.generation && at > w.lastActiveAt ? { ...w, lastActiveAt: at } : w),
1366
- result: void 0
1367
- }));
1368
- } catch {
1369
- }
1398
+ const inMemoryActivity = /* @__PURE__ */ new Map();
1399
+ const recordObservedActivity = (record) => {
1400
+ const fresh = Math.max(record.lastActiveAt, inMemoryActivity.get(record.generation) ?? 0, observeActivity(record));
1401
+ inMemoryActivity.set(record.generation, fresh);
1402
+ return fresh;
1370
1403
  };
1404
+ const activityPersistThresholdMs = (ttlMs) => Math.min(6e4, Math.floor(ttlMs / 4));
1371
1405
  const releaseReservation = (generation) => {
1372
1406
  try {
1373
1407
  updateRegistry((snap) => ({
@@ -1383,7 +1417,7 @@ function pieProc(ctx) {
1383
1417
  if (!Number.isSafeInteger(pid) || pid <= 1) return;
1384
1418
  if (process.platform === "win32") {
1385
1419
  try {
1386
- execFileSync("taskkill.exe", ["/F", "/T", "/PID", String(pid)], {
1420
+ execFileSync2("taskkill.exe", ["/F", "/T", "/PID", String(pid)], {
1387
1421
  windowsHide: true,
1388
1422
  stdio: "ignore",
1389
1423
  timeout: 5e3
@@ -1429,10 +1463,11 @@ function pieProc(ctx) {
1429
1463
  }
1430
1464
  }
1431
1465
  for (const w of readRegistryUncached().workers) {
1432
- const observed = Math.max(w.lastActiveAt, observeActivity(w));
1433
- if (observed > w.lastActiveAt) persistActivity(w, observed);
1466
+ recordObservedActivity(w);
1434
1467
  }
1468
+ const liveGenerations = /* @__PURE__ */ new Set();
1435
1469
  casRegistry((snap) => {
1470
+ liveGenerations.clear();
1436
1471
  const cutoff = Date.now();
1437
1472
  let changed = false;
1438
1473
  const keep = [];
@@ -1485,10 +1520,21 @@ function pieProc(ctx) {
1485
1520
  continue;
1486
1521
  }
1487
1522
  const ttl = w.kind === "resident" ? w.ttlMs ?? currentConfig().defaultTtlMs : 0;
1488
- if (ttl > 0 && liveness === "alive" && cutoff - Math.max(w.lastActiveAt, observeActivity(w)) > ttl) {
1489
- signalWorkerProcessGroup(w.pid, "SIGTERM");
1490
- ctx.log(`pie-proc: idle TTL signaled worker ${w.name} (idle > ${Math.round(ttl / 1e3)}s, identity verified)`);
1491
- keep.push({ ...w, ttlMs: 0, orphanSignaledAt: cutoff });
1523
+ let observed = Math.max(w.lastActiveAt, inMemoryActivity.get(w.generation) ?? 0);
1524
+ if (ttl > 0 && liveness === "alive" && cutoff - observed > ttl) {
1525
+ observed = recordObservedActivity(w);
1526
+ if (Date.now() - observed > ttl) {
1527
+ signalWorkerProcessGroup(w.pid, "SIGTERM");
1528
+ ctx.log(`pie-proc: idle TTL signaled worker ${w.name} (idle > ${Math.round(ttl / 1e3)}s, identity verified)`);
1529
+ keep.push({ ...w, lastActiveAt: observed, ttlMs: 0, orphanSignaledAt: cutoff });
1530
+ liveGenerations.add(w.generation);
1531
+ changed = true;
1532
+ continue;
1533
+ }
1534
+ }
1535
+ liveGenerations.add(w.generation);
1536
+ if (ttl > 0 && liveness === "alive" && observed > w.lastActiveAt && observed - w.lastActiveAt >= activityPersistThresholdMs(ttl)) {
1537
+ keep.push({ ...w, lastActiveAt: observed });
1492
1538
  changed = true;
1493
1539
  continue;
1494
1540
  }
@@ -1497,15 +1543,13 @@ function pieProc(ctx) {
1497
1543
  if (!changed) return { abort: { value: void 0 } };
1498
1544
  return { next: keep, result: void 0 };
1499
1545
  });
1546
+ for (const gen of [...inMemoryActivity.keys()]) {
1547
+ if (!liveGenerations.has(gen)) inMemoryActivity.delete(gen);
1548
+ }
1500
1549
  } catch (error) {
1501
1550
  ctx.log(`pie-proc: sweep skipped: ${error instanceof Error ? error.message : String(error)}`);
1502
1551
  }
1503
1552
  };
1504
- const sweepTimer = setInterval(sweep, 6e4);
1505
- sweepTimer.unref?.();
1506
- ctx.registerCleanup?.(() => {
1507
- clearInterval(sweepTimer);
1508
- });
1509
1553
  const spawnWorker = async (params) => {
1510
1554
  if (!safeName(params.name)) throw new Error(`invalid worker name "${params.name}" (use [a-z0-9-_], max 48)`);
1511
1555
  if (params.kind === "oneshot" && (typeof params.task !== "string" || !params.task.trim())) throw new Error("oneshot spawn requires a non-empty task");
@@ -1516,17 +1560,17 @@ function pieProc(ctx) {
1516
1560
  const canonicalCwd = cwdAllowedOrThrow(params.cwd, readConfigDetailed());
1517
1561
  const entry = cliEntry();
1518
1562
  if (!entry) throw new Error("cannot resolve a trusted pie entry point (refusing to spawn)");
1519
- const validatedModel = validateSpawnModelParams({ model: params.model, thinkingLevel: params.thinkingLevel, pieDir: path4.join(pieProcDir(), "agents", params.name), parentConfigDir: configDirRoot() });
1563
+ const validatedModel = validateSpawnModelParams({ model: params.model, thinkingLevel: params.thinkingLevel, pieDir: path5.join(pieProcDir(), "agents", params.name), parentConfigDir: configDirRoot() });
1520
1564
  let resumeSessionId;
1521
1565
  let resumeSessionsDir;
1522
1566
  if (params.resumeSessionId) {
1523
1567
  if (!/^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(params.resumeSessionId)) throw new Error(`invalid resumeSessionId "${params.resumeSessionId}"`);
1524
1568
  const operatorSessionsDir = resolveOperatorSessionsDir();
1525
- const workerSessionsDir = path4.join(pieProcDir(), "agents", params.name, "sessions");
1569
+ const workerSessionsDir = path5.join(pieProcDir(), "agents", params.name, "sessions");
1526
1570
  let recordedCwd;
1527
1571
  for (const dir of [workerSessionsDir, operatorSessionsDir]) {
1528
1572
  try {
1529
- const head = JSON.parse(fs4.readFileSync(path4.join(dir, params.resumeSessionId, "head.json"), "utf8"));
1573
+ const head = JSON.parse(fs5.readFileSync(path5.join(dir, params.resumeSessionId, "head.json"), "utf8"));
1530
1574
  recordedCwd = head.metadata?.cwd;
1531
1575
  resumeSessionsDir = dir;
1532
1576
  break;
@@ -1537,7 +1581,7 @@ function pieProc(ctx) {
1537
1581
  if (typeof recordedCwd !== "string" || !recordedCwd) throw new Error(`session "${params.resumeSessionId}" has no recorded cwd; resume requires one`);
1538
1582
  let canonicalRecorded = recordedCwd;
1539
1583
  try {
1540
- canonicalRecorded = fs4.realpathSync(recordedCwd);
1584
+ canonicalRecorded = fs5.realpathSync(recordedCwd);
1541
1585
  } catch {
1542
1586
  }
1543
1587
  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`);
@@ -1614,12 +1658,12 @@ function pieProc(ctx) {
1614
1658
  });
1615
1659
  let child;
1616
1660
  try {
1617
- const pieDir = path4.join(pieProcDir(), "agents", params.name);
1618
- fs4.mkdirSync(pieDir, { recursive: true });
1661
+ const pieDir = path5.join(pieProcDir(), "agents", params.name);
1662
+ fs5.mkdirSync(pieDir, { recursive: true });
1619
1663
  inheritWorkerConfigFiles(pieDir, configDirRoot());
1620
1664
  if (imForward) {
1621
- const imFile = path4.join(pieDir, "im-forward.json");
1622
- if (!fs4.existsSync(imFile)) {
1665
+ const imFile = path5.join(pieDir, "im-forward.json");
1666
+ if (!fs5.existsSync(imFile)) {
1623
1667
  const provider = typeof imForward.provider === "string" ? imForward.provider.trim() : "";
1624
1668
  if (provider && SAFE_PROVIDER_ID.test(provider)) {
1625
1669
  const providerSettings = {};
@@ -1637,16 +1681,16 @@ function pieProc(ctx) {
1637
1681
  if (typeof imForward.retryBackoffMs === "number" && Number.isFinite(imForward.retryBackoffMs)) {
1638
1682
  doc.retryBackoffMs = imForward.retryBackoffMs;
1639
1683
  }
1640
- fs4.writeFileSync(imFile, JSON.stringify(doc, null, " "));
1684
+ fs5.writeFileSync(imFile, JSON.stringify(doc, null, " "));
1641
1685
  }
1642
1686
  }
1643
1687
  }
1644
- fs4.mkdirSync(logDir(), { recursive: true });
1645
- const logFile = fs4.openSync(path4.join(logDir(), `${params.name}.jsonl`), "a");
1688
+ fs5.mkdirSync(logDir(), { recursive: true });
1689
+ const logFile = fs5.openSync(path5.join(logDir(), `${params.name}.jsonl`), "a");
1646
1690
  const modelArgs = [...validatedModel.model ? ["--model", validatedModel.model] : [], ...validatedModel.thinkingLevel ? ["--thinking", validatedModel.thinkingLevel] : []];
1647
1691
  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];
1648
- const inheritedIpcRoot = path4.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1649
- const inheritedRegistryRoot = path4.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
1692
+ const inheritedIpcRoot = path5.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1693
+ const inheritedRegistryRoot = path5.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
1650
1694
  const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
1651
1695
  const childEnv = {
1652
1696
  ...inheritedEnv,
@@ -1680,12 +1724,12 @@ function pieProc(ctx) {
1680
1724
  });
1681
1725
  } finally {
1682
1726
  try {
1683
- fs4.closeSync(logFile);
1727
+ fs5.closeSync(logFile);
1684
1728
  } catch {
1685
1729
  }
1686
1730
  }
1687
1731
  if (typeof child.pid !== "number") {
1688
- throw new Error(`worker spawn failed (no pid) \u2014 see ${path4.join(logDir(), `${params.name}.jsonl`)}`);
1732
+ throw new Error(`worker spawn failed (no pid) \u2014 see ${path5.join(logDir(), `${params.name}.jsonl`)}`);
1689
1733
  }
1690
1734
  child.unref();
1691
1735
  const record = {
@@ -1733,7 +1777,7 @@ function pieProc(ctx) {
1733
1777
  cwd: record.cwd,
1734
1778
  pieDir,
1735
1779
  ipcRoot: inheritedIpcRoot,
1736
- logPath: path4.join(logDir(), `${params.name}.jsonl`),
1780
+ logPath: path5.join(logDir(), `${params.name}.jsonl`),
1737
1781
  ttlMs: params.ttlMs,
1738
1782
  explicitModel: validatedModel.model,
1739
1783
  explicitThinking: validatedModel.thinkingLevel,
@@ -1809,6 +1853,11 @@ function pieProc(ctx) {
1809
1853
  ctx.log("pie-proc: tool not registered (role-pruned; manager-only)");
1810
1854
  return;
1811
1855
  }
1856
+ const sweepTimer = setInterval(sweep, 6e4);
1857
+ sweepTimer.unref?.();
1858
+ ctx.registerCleanup?.(() => {
1859
+ clearInterval(sweepTimer);
1860
+ });
1812
1861
  const unregisterPanelBridge = registerPieProcPanelBridge({
1813
1862
  pieProcDir,
1814
1863
  operatorSessionsDir: resolveOperatorSessionsDir,
@@ -1861,7 +1910,7 @@ function pieProc(ctx) {
1861
1910
  const action = args.action;
1862
1911
  if (action === "list") {
1863
1912
  const snap = readRegistryUncached();
1864
- const ipcRoot = path4.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1913
+ const ipcRoot = path5.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
1865
1914
  const rows = snap.workers.map((w) => {
1866
1915
  const model = liveWorkerModelLabel(ipcRoot, w.sessionId, w.pid);
1867
1916
  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) };
@@ -6,10 +6,10 @@ import {
6
6
  createPlanCapability,
7
7
  markCompletedPlanSteps,
8
8
  restoreExecutionState
9
- } from "../../../chunks/chunk-XPJHZRTN.js";
10
- import "../../../chunks/chunk-CCPNHS6B.js";
11
- import "../../../chunks/chunk-26KRUYZH.js";
12
- import "../../../chunks/chunk-MCR4JYI6.js";
9
+ } from "../../../chunks/chunk-X3ZVZB2R.js";
10
+ import "../../../chunks/chunk-SYZR74QO.js";
11
+ import "../../../chunks/chunk-SAXKBFX3.js";
12
+ import "../../../chunks/chunk-IM7DLPPY.js";
13
13
  import {
14
14
  Type
15
15
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -5,7 +5,7 @@ import {
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
7
  logTransportLifecycle
8
- } from "../../../chunks/chunk-6Z54UHXM.js";
8
+ } from "../../../chunks/chunk-2WLKAMOH.js";
9
9
  import {
10
10
  getConfigDir
11
11
  } from "../../../chunks/chunk-CBDQJMUI.js";
@@ -14,10 +14,10 @@ import {
14
14
  createPolicyEnforcedTools,
15
15
  createSharedFileSystemTools,
16
16
  createSubagentCapability
17
- } from "../../../chunks/chunk-XPJHZRTN.js";
18
- import "../../../chunks/chunk-CCPNHS6B.js";
19
- import "../../../chunks/chunk-26KRUYZH.js";
20
- import "../../../chunks/chunk-MCR4JYI6.js";
17
+ } from "../../../chunks/chunk-X3ZVZB2R.js";
18
+ import "../../../chunks/chunk-SYZR74QO.js";
19
+ import "../../../chunks/chunk-SAXKBFX3.js";
20
+ import "../../../chunks/chunk-IM7DLPPY.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-XPJHZRTN.js";
12
- import "../../../chunks/chunk-CCPNHS6B.js";
13
- import "../../../chunks/chunk-26KRUYZH.js";
14
- import "../../../chunks/chunk-MCR4JYI6.js";
11
+ } from "../../../chunks/chunk-X3ZVZB2R.js";
12
+ import "../../../chunks/chunk-SYZR74QO.js";
13
+ import "../../../chunks/chunk-SAXKBFX3.js";
14
+ import "../../../chunks/chunk-IM7DLPPY.js";
15
15
  import "../../../chunks/chunk-XXGYUYXI.js";
16
16
  import "../../../chunks/chunk-LZQXQOPJ.js";
17
17