@cydm/pie 4.3.11 → 4.4.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.
@@ -1,7 +1,7 @@
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-LLCEO7ET.js";
4
+ } from "../../../chunks/chunk-N5B5IGJ6.js";
5
5
  import "../../../chunks/chunk-XMOWWL4B.js";
6
6
  import "../../../chunks/chunk-B4N5LJMD.js";
7
7
  import "../../../chunks/chunk-6JEYRAQM.js";
@@ -392,7 +392,7 @@ var Store = class {
392
392
  * idempotent (one managed job per manager). A RUNNING job is never
393
393
  * replaced: removing its reservation would let another execution start
394
394
  * while the original worker is still alive (single-outstanding invariant). */
395
- addProcess(command, managedBy, cwd, schedule, now = Date.now()) {
395
+ addProcess(command, managedBy, cwd, schedule, now = Date.now(), opts) {
396
396
  const validated = validateSchedule(schedule), next = nextTime(validated, now);
397
397
  if (next === null) throw new Error("at must be in the future");
398
398
  const count = validated.count;
@@ -414,6 +414,12 @@ var Store = class {
414
414
  return this.transaction((s) => {
415
415
  const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
416
416
  if (existing?.state === "running") throw new Error("managed job is currently running; try again after it finishes");
417
+ if (!opts?.forceReplace) {
418
+ if (existing?.state === "blocked") throw new Error("managed job is blocked; resume or recover it explicitly instead of re-registering");
419
+ }
420
+ if (!opts?.forceReplace) {
421
+ if (existing && existing.enabled === false) throw new Error("managed job is paused; resume it explicitly instead of re-registering");
422
+ }
417
423
  s.jobs = s.jobs.filter((j) => j !== existing);
418
424
  if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
419
425
  s.jobs.push(job);
@@ -857,7 +863,9 @@ var Runtime = class {
857
863
  this.store.addProcess(command, "memory", process.cwd(), cronSpec);
858
864
  this.ctx.log("cron: registered the default daily memory distillation (03:00)");
859
865
  } catch (error) {
860
- this.ctx.log(`cron: default memory distillation registration failed: ${String(error)}`);
866
+ const message = String(error instanceof Error ? error.message : error);
867
+ if (/managed job is (blocked|paused|currently running)/.test(message)) return;
868
+ this.ctx.log(`cron: default memory distillation registration failed: ${message}`);
861
869
  }
862
870
  }
863
871
  markUnsafe() {
@@ -950,8 +958,37 @@ var Runtime = class {
950
958
  }
951
959
  persistOwner(sessionId) {
952
960
  this.store.transaction((state) => {
961
+ for (const key of Object.keys(state.owners)) {
962
+ if (key === this.id) continue;
963
+ const row = state.owners[key];
964
+ if (row.sessionId !== sessionId) continue;
965
+ const liveness = path3.join(this.store.dir, "owners-liveness", `${key}.json`);
966
+ try {
967
+ const parsed = JSON.parse(fs3.readFileSync(liveness, "utf8"));
968
+ if (typeof parsed.pid !== "number" || parsed.pid <= 0) continue;
969
+ try {
970
+ process.kill(parsed.pid, 0);
971
+ continue;
972
+ } catch (err) {
973
+ if (err.code !== "ESRCH") continue;
974
+ }
975
+ delete state.owners[key];
976
+ } catch {
977
+ }
978
+ }
953
979
  state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
954
980
  });
981
+ try {
982
+ const livenessDir = path3.join(this.store.dir, "owners-liveness");
983
+ fs3.mkdirSync(livenessDir, { recursive: true });
984
+ const liveness = path3.join(livenessDir, `${this.id}.json`);
985
+ try {
986
+ fs3.unlinkSync(liveness);
987
+ } catch {
988
+ }
989
+ fs3.writeFileSync(liveness, JSON.stringify({ pid: process.pid, at: Date.now() }), { mode: 384 });
990
+ } catch {
991
+ }
955
992
  this.sessionId = sessionId;
956
993
  this.initialized = true;
957
994
  }
@@ -1259,7 +1296,9 @@ ${job.prompt}`;
1259
1296
  });
1260
1297
  }
1261
1298
  const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
1262
- 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);
1299
+ const enabledCount = enabled.length;
1300
+ const blockedCount = enabled.filter((job) => job.state === "blocked").length;
1301
+ this.ctx.ui.setStatus?.("cron", this.leader && enabledCount > 0 && enabled.some((job) => job.sessionId === this.sessionId || isProcessJob(job)) ? blockedCount > 0 ? `[CRON.${enabledCount}.${blockedCount}]` : `[CRON.${enabledCount}]` : void 0);
1263
1302
  for (const job of state.jobs) {
1264
1303
  this.notify(job, Object.values(state.owners).filter((owner) => owner.sessionId === job.sessionId).length);
1265
1304
  }
@@ -1271,7 +1310,7 @@ ${job.prompt}`;
1271
1310
  this.pollFailureBackoffMs = Math.min((this.pollFailureBackoffMs ?? 1e3) * 2, 3e5);
1272
1311
  this.pollRetryAt = Date.now() + this.pollFailureBackoffMs;
1273
1312
  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.`);
1274
- this.ctx.ui.setStatus?.("cron", "cron: state invalid; scheduling paused (see logs)");
1313
+ this.ctx.ui.setStatus?.("cron", "[CRON!]");
1275
1314
  this.scheduleRecoveryPoll();
1276
1315
  } finally {
1277
1316
  this.polling = false;
@@ -1322,6 +1361,10 @@ ${job.prompt}`;
1322
1361
  if (job.state === "running" && job.target === this.id) complete(job, "owner closed before delivery; inspect before resuming");
1323
1362
  }
1324
1363
  });
1364
+ try {
1365
+ fs3.rmSync(path3.join(this.store.dir, "owners-liveness", `${this.id}.json`), { force: true });
1366
+ } catch {
1367
+ }
1325
1368
  this.completions.clear();
1326
1369
  break;
1327
1370
  } catch (error) {
@@ -1428,16 +1471,20 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
1428
1471
  });
1429
1472
  ctx.on("terminal:input", (e) => {
1430
1473
  if (/^\/tools\/cron(?:\s|$)/.test(e.text)) return;
1474
+ let unsafe = false, duplicates = false, worker = false;
1431
1475
  try {
1432
1476
  const state = store.read();
1433
1477
  if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
1434
- const duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
1435
- const worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
1436
- if (!startupError && runtime.ready && !duplicates && !worker && !fs4.existsSync(path4.join(store.dir, "unsafe.lock"))) return;
1478
+ duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
1479
+ worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
1480
+ unsafe = fs4.existsSync(path4.join(store.dir, "unsafe.lock"));
1481
+ if (!startupError && runtime.ready && !duplicates && !worker && !unsafe) return;
1437
1482
  } catch {
1438
1483
  }
1484
+ const safeStartupError = typeof startupError === "string" ? startupError.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 160) : void 0;
1485
+ const why = unsafe ? "cron \u72B6\u6001\u4E0D\u5B89\u5168\uFF08unsafe.lock\uFF09\u2014\u2014\u9700\u4EBA\u5DE5\u68C0\u67E5 /tools/cron \u540E\u6062\u590D" : duplicates ? "\u5B58\u5728\u540C\u4F1A\u8BDD\u7684\u91CD\u590D owner\uFF08\u7591\u4F3C\u6B8B\u7559\u8FDB\u7A0B\uFF09\u2014\u2014\u91CD\u8BD5\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 /tools/cron" : worker ? "\u672C\u4F1A\u8BDD\u6709\u6B63\u5728\u6267\u884C\u7684 cron \u4EFB\u52A1\uFF08worker \u6A21\u5F0F\uFF09\u2014\u2014\u4EFB\u52A1\u7ED3\u675F\u540E\u81EA\u52A8\u6062\u590D" : safeStartupError ? `cron \u542F\u52A8\u5F02\u5E38\uFF1A${safeStartupError}` : "cron \u4F1A\u8BDD\u6240\u6709\u6743\u672A\u5C31\u7EEA\u2014\u2014\u7A0D\u540E\u91CD\u8BD5";
1439
1486
  ctx.ui.notify("cron: session ownership is uncertain or duplicated; input blocked. Close the duplicate/worker and inspect /tools/cron.", "warning");
1440
- return { action: "reject" };
1487
+ return { action: "reject", reason: why };
1441
1488
  });
1442
1489
  ctx.on("session:before_switch", (e) => {
1443
1490
  if (!e.targetSessionId) return;
@@ -1454,7 +1501,26 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
1454
1501
  });
1455
1502
  const run = (action, id, prompt, schedule) => {
1456
1503
  if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
1457
- if (action === "list") return JSON.stringify({ ...store.read(), recoveryRequired: fs4.existsSync(path4.join(store.dir, "unsafe.lock")), coordinatorPresent: fs4.existsSync(path4.join(store.dir, "scheduler.lock")) }, null, 2);
1504
+ if (action === "list") {
1505
+ const state = store.read();
1506
+ const blocked = state.jobs.filter((j) => j.state === "blocked").map((j) => {
1507
+ const oneShotExpired = !!j.schedule?.at && j.occurrence !== void 0 && Date.now() > (j.occurrence ?? 0);
1508
+ return {
1509
+ id: j.id,
1510
+ error: j.error ?? "(no error recorded)",
1511
+ lastOccurrence: j.occurrence ? new Date(j.occurrence).toISOString() : "(none)",
1512
+ executionTrail: isProcessJob(j) ? `${store.dir}/process.log (if a run started)` : `${store.dir}/audit.log (if any audit event fired)`,
1513
+ cwd: j.cwd,
1514
+ resolution: oneShotExpired ? 'one-shot expired: cron_manage {action:"remove", id} (then optionally re-create); resume is impossible for a past `at`' : 'cron_manage {action:"resume"|"remove", id} \u2014 inspect the trail first'
1515
+ };
1516
+ });
1517
+ return JSON.stringify({
1518
+ ...state,
1519
+ recoveryRequired: fs4.existsSync(path4.join(store.dir, "unsafe.lock")),
1520
+ coordinatorPresent: fs4.existsSync(path4.join(store.dir, "scheduler.lock")),
1521
+ ...blocked.length > 0 ? { blockedReview: blocked } : {}
1522
+ }, null, 2);
1523
+ }
1458
1524
  if (action === "add") {
1459
1525
  if (!runtime.ready || !runtime.sessionId) throw new Error("wait for an existing session to load and register");
1460
1526
  const authorization = authorizationNow();
@@ -1526,6 +1592,7 @@ export {
1526
1592
  Store,
1527
1593
  configPath,
1528
1594
  cron as default,
1595
+ isProcessJob,
1529
1596
  localTimeToCronUtc,
1530
1597
  managedMemoryCommand,
1531
1598
  parseProcessCommand
@@ -69,7 +69,35 @@ are read as implicit Feishu settings. Unknown explicit providers never fall back
69
69
  Provider settings merge only within the same provider, with project precedence.
70
70
 
71
71
  The footer shows `[IM…]` while starting, `[IM]` only after the consumer's ready
72
- marker, `[IM!]` on configuration/connection failure, and nothing when off.
72
+ marker, `[IM!]` on configuration/connection failure, `[IM-DEGRADED:bus]`
73
+ when the last recognized bus SDK state is disconnected beyond a ten-minute
74
+ reconnect grace, and nothing when off. A five-minute probe reads a bounded
75
+ log tail using host-local timestamps; unknown/unavailable evidence preserves
76
+ an existing warning. Only a recognized reconnect clears it. This is passive
77
+ connection-state evidence, not an end-to-end heartbeat: a silent cloud stall
78
+ without a disconnect log remains undetectable. Pie never kills the shared
79
+ lark-cli daemon automatically; the warning gives the operator the explicit
80
+ `event stop --force` recovery command. Optional card/menu consumers respawn
81
+ on bounded backoff, reset only at their ready marker; dead children are removed.
82
+
83
+ On a machine where a resident holds the consumer slot, non-holder runtimes
84
+ operate in dispatch mode: they never spawn a consumer and receive events over
85
+ pie-ipc. For such runtimes the tag answers a delivery question, not a
86
+ lifecycle one: `[IM]` while dispatch mode is the working configuration (the
87
+ holder is alive and sorting), `[IM-DEGRADED:dispatch]` when the holder
88
+ heartbeat stays fresh yet nothing has been dispatched here past a ten-minute
89
+ grace window, and `[IM…]` only while the runtime is genuinely starting or
90
+ waiting to claim. A dispatched event restores `[IM]` immediately. Losing the
91
+ holder (restart churn) never shows degraded — no delivery evidence plus no
92
+ holder is not a failure signal. `/tools/im-forward status` prints the holder
93
+ identity and the last dispatched event time in dispatch mode.
94
+
95
+ Registered panel cards can bypass metadata/claim/scope IO only AFTER all
96
+ conversation/sender policies pass. Card ownership is session-and-epoch bound;
97
+ pending send/patch completions never reassign the card after a session switch.
98
+ Provider chat-type lookup still happens before runtime admission. Runtime patch
99
+ logs report elapsed milliseconds; metadata-call avoidance alone is not proof
100
+ that every observed UI delay came from that lookup.
73
101
  Desired enabled state is independent of connection health. Other processes'
74
102
  enabled changes are re-read at the next forwarding/input gate; changed provider,
75
103
  target or settings fail closed until setup/reload rather than sending to a stale target.