@cydm/pie 4.3.7 → 4.3.12

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-WZLO5V2X.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);
@@ -841,6 +847,26 @@ var Runtime = class {
841
847
  this.initialized = false;
842
848
  this.timer = setInterval(() => void this.poll(), 1e3);
843
849
  this.timer.unref();
850
+ void this.ensureMemoryDistillationDefault();
851
+ }
852
+ /** Default daily distillation at 03:00 local. Idempotent: an existing
853
+ * managed job (running or not) is left untouched. */
854
+ async ensureMemoryDistillationDefault() {
855
+ try {
856
+ const existing = this.store.findProcess("memory");
857
+ if (existing) return;
858
+ if (fs3.existsSync(path3.join(this.store.dir, "memory-disabled"))) return;
859
+ const { managedMemoryCommand: managedMemoryCommand2, localTimeToCronUtc: localTimeToCronUtc2 } = await import("./index.js");
860
+ const command = managedMemoryCommand2();
861
+ const cronSpec = localTimeToCronUtc2("03:00");
862
+ if ("error" in cronSpec) throw new Error(cronSpec.error);
863
+ this.store.addProcess(command, "memory", process.cwd(), cronSpec);
864
+ this.ctx.log("cron: registered the default daily memory distillation (03:00)");
865
+ } catch (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}`);
869
+ }
844
870
  }
845
871
  markUnsafe() {
846
872
  fs3.mkdirSync(path3.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
@@ -932,8 +958,37 @@ var Runtime = class {
932
958
  }
933
959
  persistOwner(sessionId) {
934
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
+ }
935
979
  state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
936
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
+ }
937
992
  this.sessionId = sessionId;
938
993
  this.initialized = true;
939
994
  }
@@ -1241,7 +1296,9 @@ ${job.prompt}`;
1241
1296
  });
1242
1297
  }
1243
1298
  const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
1244
- 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);
1245
1302
  for (const job of state.jobs) {
1246
1303
  this.notify(job, Object.values(state.owners).filter((owner) => owner.sessionId === job.sessionId).length);
1247
1304
  }
@@ -1253,7 +1310,7 @@ ${job.prompt}`;
1253
1310
  this.pollFailureBackoffMs = Math.min((this.pollFailureBackoffMs ?? 1e3) * 2, 3e5);
1254
1311
  this.pollRetryAt = Date.now() + this.pollFailureBackoffMs;
1255
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.`);
1256
- this.ctx.ui.setStatus?.("cron", "cron: state invalid; scheduling paused (see logs)");
1313
+ this.ctx.ui.setStatus?.("cron", "[CRON!]");
1257
1314
  this.scheduleRecoveryPoll();
1258
1315
  } finally {
1259
1316
  this.polling = false;
@@ -1304,6 +1361,10 @@ ${job.prompt}`;
1304
1361
  if (job.state === "running" && job.target === this.id) complete(job, "owner closed before delivery; inspect before resuming");
1305
1362
  }
1306
1363
  });
1364
+ try {
1365
+ fs3.rmSync(path3.join(this.store.dir, "owners-liveness", `${this.id}.json`), { force: true });
1366
+ } catch {
1367
+ }
1307
1368
  this.completions.clear();
1308
1369
  break;
1309
1370
  } catch (error) {
@@ -1355,6 +1416,22 @@ function configPath() {
1355
1416
  const env = process.env.PIE_CODING_AGENT_DIR;
1356
1417
  return path4.resolve(env === "~" ? homedir() : env?.startsWith("~/") ? path4.join(homedir(), env.slice(2)) : env || path4.join(homedir(), ".pie"));
1357
1418
  }
1419
+ function localTimeToCronUtc(time) {
1420
+ const m = /^(\d{1,2}):(\d{2})$/.exec(time);
1421
+ if (!m) return { error: "time must be HH:MM" };
1422
+ const hour = Number(m[1]), minute = Number(m[2]);
1423
+ if (hour > 23 || minute > 59) return { error: "time out of range" };
1424
+ const local = /* @__PURE__ */ new Date();
1425
+ local.setHours(hour, minute, 0, 0);
1426
+ const utcHour = local.getUTCHours(), utcMinute = local.getUTCMinutes();
1427
+ return { cron: `${utcMinute} ${utcHour} * * *` };
1428
+ }
1429
+ function managedMemoryCommand() {
1430
+ const entry = process.argv[1] ? path4.resolve(process.argv[1]) : path4.join(configPath(), "..", "cli.js");
1431
+ const resolved = fs4.existsSync(entry) ? entry : path4.join(configPath(), "cli.js");
1432
+ const loaderArgs = process.execArgv.filter((a) => a.startsWith("--import") || a.startsWith("--loader"));
1433
+ return [process.execPath, ...loaderArgs, resolved, "memory", "distill", "--worker", "--auto", "--memory-root", path4.join(configPath(), "memory")];
1434
+ }
1358
1435
  function cron(ctx) {
1359
1436
  if (process.env.PIE_CRON_ROLE === "worker") return;
1360
1437
  const capabilities = ctx.capabilities;
@@ -1372,6 +1449,7 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
1372
1449
  };
1373
1450
  const store = new Store(path4.join(configPath(), "cron"));
1374
1451
  const runtime = new Runtime(ctx, store);
1452
+ ctx.log(`cron: starting (store=${path4.join(configPath(), "cron")})`);
1375
1453
  let startupError;
1376
1454
  try {
1377
1455
  runtime.start();
@@ -1393,16 +1471,20 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
1393
1471
  });
1394
1472
  ctx.on("terminal:input", (e) => {
1395
1473
  if (/^\/tools\/cron(?:\s|$)/.test(e.text)) return;
1474
+ let unsafe = false, duplicates = false, worker = false;
1396
1475
  try {
1397
1476
  const state = store.read();
1398
1477
  if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
1399
- const duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
1400
- const worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
1401
- 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;
1402
1482
  } catch {
1403
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";
1404
1486
  ctx.ui.notify("cron: session ownership is uncertain or duplicated; input blocked. Close the duplicate/worker and inspect /tools/cron.", "warning");
1405
- return { action: "reject" };
1487
+ return { action: "reject", reason: why };
1406
1488
  });
1407
1489
  ctx.on("session:before_switch", (e) => {
1408
1490
  if (!e.targetSessionId) return;
@@ -1419,7 +1501,26 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
1419
1501
  });
1420
1502
  const run = (action, id, prompt, schedule) => {
1421
1503
  if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
1422
- 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
+ }
1423
1524
  if (action === "add") {
1424
1525
  if (!runtime.ready || !runtime.sessionId) throw new Error("wait for an existing session to load and register");
1425
1526
  const authorization = authorizationNow();
@@ -1491,5 +1592,8 @@ export {
1491
1592
  Store,
1492
1593
  configPath,
1493
1594
  cron as default,
1595
+ isProcessJob,
1596
+ localTimeToCronUtc,
1597
+ managedMemoryCommand,
1494
1598
  parseProcessCommand
1495
1599
  };
@@ -69,7 +69,23 @@ 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
+ Registered panel cards can bypass metadata/claim/scope IO only AFTER all
84
+ conversation/sender policies pass. Card ownership is session-and-epoch bound;
85
+ pending send/patch completions never reassign the card after a session switch.
86
+ Provider chat-type lookup still happens before runtime admission. Runtime patch
87
+ logs report elapsed milliseconds; metadata-call avoidance alone is not proof
88
+ that every observed UI delay came from that lookup.
73
89
  Desired enabled state is independent of connection health. Other processes'
74
90
  enabled changes are re-read at the next forwarding/input gate; changed provider,
75
91
  target or settings fail closed until setup/reload rather than sending to a stale target.