@cydm/pie 3.0.0 → 4.0.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 (31) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +8 -4
  2. package/dist/builtin/extensions/cron/index.js +130 -21
  3. package/dist/builtin/extensions/im-forward/README.md +20 -5
  4. package/dist/builtin/extensions/im-forward/index.js +415 -142
  5. package/dist/builtin/extensions/memory/index.js +71 -20
  6. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  7. package/dist/builtin/extensions/pie-ipc/index.js +269 -30
  8. package/dist/builtin/extensions/pie-proc/README.md +93 -0
  9. package/dist/builtin/extensions/pie-proc/index.js +630 -0
  10. package/dist/builtin/extensions/pie-proc/package.json +11 -0
  11. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  12. package/dist/builtin/extensions/subagent/index.js +5 -5
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +49 -0
  15. package/dist/chunks/{chunk-7FEPQHYX.js → chunk-FDLLNPIE.js} +143 -53
  16. package/dist/chunks/{chunk-3BC5KGDQ.js → chunk-JQRZLVPY.js} +12 -1
  17. package/dist/chunks/{chunk-GH4VW2OT.js → chunk-NCP264ZE.js} +8 -2
  18. package/dist/chunks/{chunk-YRR6C43W.js → chunk-QX6WS73C.js} +1 -1
  19. package/dist/chunks/{chunk-OEQYEYB3.js → chunk-TDKNKNPL.js} +5 -5
  20. package/dist/chunks/{chunk-BUDXV3TR.js → chunk-UOZHQ73X.js} +3 -3
  21. package/dist/chunks/{chunk-3FRKOFSP.js → chunk-WK4N5HT5.js} +32 -22
  22. package/dist/chunks/chunk-X6LBWHK3.js +37 -0
  23. package/dist/chunks/concierge-cli-PIOGXKDR.js +939 -0
  24. package/dist/chunks/{model-registry-LI5THXV4.js → model-registry-YA6U366L.js} +2 -2
  25. package/dist/chunks/{src-AE3OCAE6.js → src-AB7PLORG.js} +6 -4
  26. package/dist/chunks/{src-YG5M2H44.js → src-ODLT57PQ.js} +2 -2
  27. package/dist/chunks/{src-66XSMIAM.js → src-XSLD2IQ2.js} +1 -1
  28. package/dist/chunks/{src-RVTDUSPJ.js → src-ZZZO4HSR.js} +3 -3
  29. package/dist/chunks/{test-stream-JBWXKOQA.js → test-stream-GIUD5JWS.js} +1 -1
  30. package/dist/cli.js +962 -174
  31. package/package.json +105 -105
@@ -1,16 +1,20 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  createAskUserCapability
4
- } from "../../../chunks/chunk-7FEPQHYX.js";
5
- import "../../../chunks/chunk-3FRKOFSP.js";
6
- import "../../../chunks/chunk-GH4VW2OT.js";
7
- import "../../../chunks/chunk-3BC5KGDQ.js";
4
+ } from "../../../chunks/chunk-FDLLNPIE.js";
5
+ import "../../../chunks/chunk-WK4N5HT5.js";
6
+ import "../../../chunks/chunk-NCP264ZE.js";
7
+ import "../../../chunks/chunk-JQRZLVPY.js";
8
8
  import "../../../chunks/chunk-XXGYUYXI.js";
9
9
  import "../../../chunks/chunk-LZQXQOPJ.js";
10
10
 
11
11
  // builtin/extensions/ask-user/index.ts
12
12
  function askUserExtension(ctx) {
13
13
  ctx.log("Ask user extension loaded");
14
+ if (!ctx.interactions.isAvailable()) {
15
+ ctx.log("Ask user extension dormant: host has no interactive UI");
16
+ return;
17
+ }
14
18
  const capability = createAskUserCapability();
15
19
  ctx.registerTool(capability.tools[0]);
16
20
  }
@@ -102,7 +102,7 @@ var Store = class {
102
102
  transaction(fn) {
103
103
  return this.withWriteLock(() => {
104
104
  this.calibrateCache();
105
- const state = this.read();
105
+ const state = this.readForRepair();
106
106
  const result = fn(state);
107
107
  this.save(state);
108
108
  return result;
@@ -266,11 +266,33 @@ var Store = class {
266
266
  }
267
267
  if (raw !== this.lastSavedContent) this.lastSavedContent = void 0;
268
268
  }
269
+ /** Structural-only read for use INSIDE a transaction: same JSON shape
270
+ * checks as read() minus the per-field fail-closed validation, so a
271
+ * transaction callback can repair an invalid field value (write it back
272
+ * valid) instead of dead-ending the store. save() still enforces the
273
+ * storage budgets. */
274
+ readForRepair() {
275
+ const file = path.join(this.dir, "state.json");
276
+ if (!fs.existsSync(file)) return { version: 1, jobs: [], owners: {} };
277
+ const s = JSON.parse(fs.readFileSync(file, "utf8"));
278
+ if (s.version !== 1 || !Array.isArray(s.jobs) || !s.owners || typeof s.owners !== "object" || Array.isArray(s.owners)) {
279
+ throw new Error("invalid cron state; manual recovery required");
280
+ }
281
+ return s;
282
+ }
269
283
  read() {
270
284
  const file = path.join(this.dir, "state.json");
271
285
  if (!fs.existsSync(file)) return { version: 1, jobs: [], owners: {} };
272
286
  if (fs.statSync(file).size > 4e6) throw new Error("cron state exceeds size limit");
273
287
  const s = JSON.parse(fs.readFileSync(file, "utf8"));
288
+ this.validateState(s);
289
+ return s;
290
+ }
291
+ /** Full per-field validation shared by read() and save(): the single source
292
+ * of truth for what a valid State is. save() runs it on the IN-MEMORY
293
+ * result of a transaction so an unrepaired poison can never persist;
294
+ * read() runs it on disk bytes so consumers fail closed. */
295
+ validateState(s) {
274
296
  if (s.version !== 1 || !Array.isArray(s.jobs) || !s.owners || typeof s.owners !== "object") throw new Error("invalid cron state; manual recovery required");
275
297
  if (Array.isArray(s.owners) || s.jobs.length > 100 || Object.keys(s.owners).length > 1e3) throw new Error("cron state exceeds record limit");
276
298
  const ids = /* @__PURE__ */ new Set();
@@ -285,11 +307,11 @@ var Store = class {
285
307
  for (const o of Object.values(s.owners)) {
286
308
  if (!o || o.sessionId !== null && typeof o.sessionId !== "string" || typeof o.cwd !== "string" || !path.isAbsolute(o.cwd) || typeof o.busy !== "boolean") throw new Error("invalid cron owner; manual recovery required");
287
309
  }
288
- return s;
289
310
  }
290
311
  save(state) {
291
312
  const content = JSON.stringify(state, null, 2);
292
313
  if (this.lastSavedContent === content) return;
314
+ this.validateState(state);
293
315
  const projected = {
294
316
  ...state,
295
317
  owners: Object.fromEntries(Object.entries(state.owners).map(([id, owner]) => [id, { ...owner, busy: false }])),
@@ -396,6 +418,7 @@ var Store = class {
396
418
  }
397
419
  j.enabled = action === "resume";
398
420
  if (j.enabled) {
421
+ if (j.remaining !== void 0 && j.remaining <= 0) throw new Error("job exhausted its execution count; create a new job");
399
422
  j.next = nextTime(j.schedule, Math.max(now, j.occurrence ?? now));
400
423
  if (j.next === null) throw new Error("one-shot expired; create a new job");
401
424
  j.state = "ready";
@@ -592,22 +615,46 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
592
615
  let settled = false;
593
616
  let failure;
594
617
  let hostCancelled = false;
595
- let killTimer;
618
+ let termination;
619
+ let cleanupFailure;
620
+ let leaderExited = false;
596
621
  let deadlineTimer;
597
622
  const ABORT_FAILURE = "worker interrupted; outcome uncertain";
598
- const terminate = () => {
599
- if (settled) return;
623
+ const signalGroup = (signal2) => {
624
+ if (!child?.pid) return false;
600
625
  try {
601
- child?.kill();
602
- } catch {
626
+ process.kill(-child.pid, signal2);
627
+ return true;
628
+ } catch (error) {
629
+ if (error.code === "ESRCH") return false;
630
+ throw error;
603
631
  }
604
- killTimer ??= setTimeout(() => {
605
- try {
606
- child?.kill("SIGKILL");
607
- } catch {
632
+ };
633
+ const terminate = () => {
634
+ if (settled || termination) return;
635
+ termination = (async () => {
636
+ if (!child?.pid) return;
637
+ if (process.platform === "win32") {
638
+ if (leaderExited) return;
639
+ const pid = child.pid;
640
+ await new Promise((resolve4, reject2) => {
641
+ const killer = spawn("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
642
+ killer.on("error", reject2);
643
+ killer.on("close", (code) => code === 0 ? resolve4() : reject2(new Error(`taskkill exited ${code}`)));
644
+ });
645
+ return;
608
646
  }
609
- }, 5e3);
610
- killTimer.unref();
647
+ if (!signalGroup("SIGTERM")) return;
648
+ const until = Date.now() + 5e3;
649
+ while (Date.now() < until) {
650
+ await new Promise((resolve4) => setTimeout(resolve4, 25));
651
+ if (!signalGroup(0)) return;
652
+ }
653
+ signalGroup("SIGKILL");
654
+ await new Promise((resolve4) => setTimeout(resolve4, 50));
655
+ })().catch((error) => {
656
+ cleanupFailure = error;
657
+ });
611
658
  };
612
659
  const stop = () => {
613
660
  if (settled) return;
@@ -620,6 +667,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
620
667
  cwd,
621
668
  env: processJobEnv(configDir),
622
669
  stdio: ["ignore", out ?? "ignore", out ?? "ignore"],
670
+ detached: process.platform !== "win32",
623
671
  windowsHide: true
624
672
  });
625
673
  } catch (error) {
@@ -634,7 +682,6 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
634
682
  }
635
683
  const cleanup = () => {
636
684
  if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
637
- if (killTimer !== void 0) clearTimeout(killTimer);
638
685
  signal?.removeEventListener("abort", stop);
639
686
  if (out !== void 0) {
640
687
  try {
@@ -654,16 +701,31 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
654
701
  child.on("error", (error) => {
655
702
  failure = error.message;
656
703
  });
657
- child.on("close", (code) => {
704
+ child.on("exit", () => {
705
+ leaderExited = true;
706
+ });
707
+ child.on("close", async (code) => {
658
708
  if (settled) return;
659
- settled = true;
660
709
  cleanup();
710
+ if (!termination && process.platform !== "win32") {
711
+ try {
712
+ if (signalGroup(0)) {
713
+ failure = "command left background descendants";
714
+ terminate();
715
+ }
716
+ } catch (error) {
717
+ cleanupFailure = error;
718
+ }
719
+ }
720
+ await termination;
721
+ settled = true;
722
+ if (cleanupFailure) failure = `process cleanup failed: ${String(cleanupFailure)}`;
661
723
  try {
662
724
  fs2.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
663
725
  `);
664
726
  } catch {
665
727
  }
666
- if (hostCancelled) {
728
+ if (hostCancelled && !cleanupFailure) {
667
729
  reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
668
730
  return;
669
731
  }
@@ -705,6 +767,16 @@ var Runtime = class {
705
767
  leader = false;
706
768
  recovering = false;
707
769
  stopped = false;
770
+ /** Non-contention poll-failure backoff (schema-invalid state): 1s → 5min.
771
+ * Cleared on the first successful poll after a failure. */
772
+ pollFailureBackoffMs;
773
+ /** Earliest wall-clock time a poll may run again after a non-contention
774
+ * failure. The 1s interval keeps firing but poll() gates on this;
775
+ * scheduleRecoveryPoll arms a timer AT the gate so recovery actually
776
+ * happens — round-5 finding: the backoff value was computed but never
777
+ * consumed, so a poisoned state logged once per second forever. */
778
+ pollRetryAt;
779
+ recoveryPollTimer;
708
780
  initialized = false;
709
781
  binding = 0;
710
782
  polling = false;
@@ -897,6 +969,7 @@ var Runtime = class {
897
969
  }
898
970
  async poll(now = Date.now()) {
899
971
  if (this.stopped || this.polling || !this.initialized) return;
972
+ if (this.pollRetryAt !== void 0 && Date.now() < this.pollRetryAt) return;
900
973
  if (fs3.existsSync(path3.join(this.store.dir, "unsafe.lock"))) {
901
974
  this.abort.abort();
902
975
  this.processAbort.abort();
@@ -906,6 +979,10 @@ var Runtime = class {
906
979
  this.polling = true;
907
980
  try {
908
981
  this.flushCompletions();
982
+ if (this.pollRetryAt !== void 0) {
983
+ this.pollRetryAt = void 0;
984
+ this.pollFailureBackoffMs = void 0;
985
+ }
909
986
  if (this.completions.size) return;
910
987
  if (!this.leader) this.withCoordinatorMutex(() => {
911
988
  try {
@@ -1039,20 +1116,48 @@ ${job.prompt}`;
1039
1116
  const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
1040
1117
  this.ctx.ui.setStatus?.("cron", this.leader && enabled.some((job) => job.sessionId === this.sessionId || isProcessJob(job)) ? `cron: ${enabled.length} enabled, ${enabled.filter((job) => job.state === "blocked").length} blocked` : void 0);
1041
1118
  for (const job of state.jobs) this.notify(job);
1042
- } catch {
1043
- this.ctx.ui.setStatus?.("cron", void 0);
1119
+ } catch (error) {
1120
+ if (isContention(error)) {
1121
+ this.ctx.ui.setStatus?.("cron", void 0);
1122
+ return;
1123
+ }
1124
+ this.pollFailureBackoffMs = Math.min((this.pollFailureBackoffMs ?? 1e3) * 2, 3e5);
1125
+ this.pollRetryAt = Date.now() + this.pollFailureBackoffMs;
1126
+ this.ctx.log?.(`cron: poll failed (${String(error instanceof Error ? error.message : error).slice(0, 200)}); backing off ${Math.round(this.pollFailureBackoffMs / 1e3)}s. If this persists, the state file is invalid \u2014 recover via /tools/cron or repair the file offline.`);
1127
+ this.ctx.ui.setStatus?.("cron", "cron: state invalid; scheduling paused (see logs)");
1128
+ this.scheduleRecoveryPoll();
1044
1129
  } finally {
1045
1130
  this.polling = false;
1046
1131
  }
1047
1132
  }
1133
+ /** One-shot delayed poll after a non-contention failure (schema-invalid
1134
+ * state): replaces the silent once-per-second retry loop with a backed-off
1135
+ * recovery attempt; the regular timer keeps running for healthy states. */
1136
+ scheduleRecoveryPoll() {
1137
+ if (this.stopped || this.recoveryPollTimer !== void 0) return;
1138
+ const delay2 = this.pollFailureBackoffMs ?? 1e3;
1139
+ this.recoveryPollTimer = setTimeout(() => {
1140
+ this.recoveryPollTimer = void 0;
1141
+ void this.poll().catch(() => {
1142
+ });
1143
+ }, delay2);
1144
+ this.recoveryPollTimer.unref();
1145
+ }
1048
1146
  async stop() {
1049
1147
  this.stopped = true;
1050
1148
  clearInterval(this.timer);
1149
+ if (this.recoveryPollTimer !== void 0) clearTimeout(this.recoveryPollTimer);
1051
1150
  this.abort.abort();
1052
1151
  this.processAbort.abort();
1053
1152
  await this.worker;
1054
1153
  while (this.polling) await delay(10);
1154
+ const shutdownDeadline = Date.now() + 1e4;
1155
+ const budgetLeft = () => Date.now() < shutdownDeadline;
1055
1156
  for (let attempt = 0; ; attempt++) {
1157
+ if (attempt > 0 && !budgetLeft()) {
1158
+ this.noteShutdownDegradation("cron: shutdown budget expired before the final state transaction completed; session ownership may be stale. If input stays blocked, run /tools/cron list and remove the stale owner row.");
1159
+ break;
1160
+ }
1056
1161
  try {
1057
1162
  this.store.transaction((state) => {
1058
1163
  for (const [id, entry] of this.completions) {
@@ -1073,7 +1178,7 @@ ${job.prompt}`;
1073
1178
  this.completions.clear();
1074
1179
  break;
1075
1180
  } catch (error) {
1076
- if (isContention(error) && attempt < 39) {
1181
+ if (isContention(error) && attempt < 39 && budgetLeft()) {
1077
1182
  await delay(25 + Math.floor(Math.random() * 25));
1078
1183
  continue;
1079
1184
  }
@@ -1083,11 +1188,15 @@ ${job.prompt}`;
1083
1188
  }
1084
1189
  if (this.leader) {
1085
1190
  for (let attempt = 0; ; attempt++) {
1191
+ if (!budgetLeft()) {
1192
+ this.noteShutdownDegradation("cron: shutdown budget expired before the coordinator lock was released; scheduling pauses until it is reclaimed; see docs/cron.md.");
1193
+ break;
1194
+ }
1086
1195
  try {
1087
1196
  this.withCoordinatorMutex(() => this.releaseCoordinator());
1088
1197
  break;
1089
1198
  } catch (error) {
1090
- if (isContention(error) && attempt < 39) {
1199
+ if (isContention(error) && attempt < 39 && budgetLeft()) {
1091
1200
  await delay(25 + Math.floor(Math.random() * 25));
1092
1201
  continue;
1093
1202
  }
@@ -1,4 +1,13 @@
1
- # IM forwarding (interactive CLI only)
1
+ # IM forwarding
2
+
3
+ **Host gating (S5 axis migration):** the forwarding RUNTIME activates on the
4
+ `editorInjection` capability axis — real intake exists on the interactive TUI
5
+ (injection) and on embedded json-events hosts (controller-queue intake since
6
+ S1), so a resident concierge host forwards too. The INTERACTIVE SURFACES
7
+ (shortcuts Ctrl+R / Alt+I, `/tools/im-forward*` commands, the setup wizard)
8
+ stay gated on `interactiveUI`: the wizard needs dialogs, and an unattended host
9
+ configures through the layered config files instead. One-shot print hosts
10
+ (`pie -p`) register nothing and perform no configuration or subprocess IO.
2
11
 
3
12
  Ctrl+R and `/tools/im-forward` are always available in interactive hosts; Alt+I is an
4
13
  optional alias where the terminal delivers Alt. Bare
@@ -9,9 +18,14 @@ confirmation dialog; malformed layers are never silently destroyed (repair them
9
18
  first), concurrent edits between confirmation and deletion abort the clear, and
10
19
  forwarding stops immediately afterwards. Without usable configuration/dependency,
11
20
  Ctrl+R opens **IM forwarding setup**;
12
- otherwise it toggles the desired enabled flag. Headless hosts register nothing
13
- and perform no configuration or subprocess IO. Only replies/thread posts associated
14
- with this process's forwarded messages can enter its originating live session.
21
+ otherwise it toggles the desired enabled flag. Replies/thread posts associated
22
+ with this process's forwarded messages enter their originating live session.
23
+ COLD-START exception (r17): until this runtime has EVER forwarded
24
+ (hasForwarded is a lifetime marker, not reset by route TTL expiry), the FIRST
25
+ authorized message in the configured target conversation binds to the current
26
+ session — a fresh resident host (the concierge) has an empty route table and
27
+ no stdin, so without this it could never hear its first message. A retry chain
28
+ never re-binds across a session switch (released for redelivery instead).
15
29
 
16
30
  Feishu (Lark) is the only implemented platform. The wizard always shows a generic
17
31
  platform picker with implemented platforms and Cancel, before provider setup. See [Feishu setup and transport](providers/feishu/README.md).
@@ -206,7 +220,8 @@ path no longer truncates bodies.
206
220
  cleared on any terminal outcome (acceptance,
207
221
  not-ours/invalidated rejection, exhaustion, forwarding disabled, extension
208
222
  cleanup). A reply chain that walks cleanly to its end with no matching
209
- forward is ignored, not retried. Events delivered while forwarding is
223
+ forward is ignored, not retried (unless the never-forwarded cold-start
224
+ bootstrap applies — see above). Events delivered while forwarding is
210
225
  globally disabled are dropped WITHOUT being committed to the dedup set, so a
211
226
  provider redelivery after re-enabling still processes.
212
227