@cydm/pie 4.6.1 → 4.8.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.
@@ -84,6 +84,50 @@ function parseProcessCommand(job) {
84
84
  function isProcessJob(job) {
85
85
  return job.sessionId === PROCESS_SESSION_ID && parseProcessCommand(job) !== null;
86
86
  }
87
+ function sweepStaleOwners(state, dir, opts = {}) {
88
+ const now = opts.now ?? Date.now();
89
+ const legacyOrCrashWindowMs = 60 * 60 * 1e3;
90
+ const reaped = [];
91
+ for (const key of Object.keys(state.owners)) {
92
+ if (key === opts.keepKey) continue;
93
+ const row = state.owners[key];
94
+ if (opts.sessionId !== void 0 && row.sessionId !== opts.sessionId) continue;
95
+ const liveness = path.join(dir, "owners-liveness", `${key}.json`);
96
+ let sidecar;
97
+ try {
98
+ sidecar = fs.readFileSync(liveness, "utf8");
99
+ } catch (error) {
100
+ const code = error.code;
101
+ if (code !== "ENOENT") {
102
+ opts.warn?.(`cron: keeping owner ${key}; liveness sidecar read failed (${code ?? "unknown error"})`);
103
+ continue;
104
+ }
105
+ }
106
+ if (sidecar === void 0) {
107
+ if (row.registeredAt === void 0 || now - row.registeredAt > legacyOrCrashWindowMs) {
108
+ reaped.push({ key, sessionId: row.sessionId, reason: row.registeredAt === void 0 ? "legacy row (no sidecar, no registeredAt)" : "sidecar missing past crash window" });
109
+ delete state.owners[key];
110
+ }
111
+ continue;
112
+ }
113
+ try {
114
+ const parsed = JSON.parse(sidecar);
115
+ if (typeof parsed.pid !== "number" || parsed.pid <= 0) continue;
116
+ let dead = false;
117
+ try {
118
+ process.kill(parsed.pid, 0);
119
+ } catch (error) {
120
+ dead = error.code === "ESRCH";
121
+ }
122
+ if (dead) {
123
+ reaped.push({ key, sessionId: row.sessionId, reason: `pid ${parsed.pid} provably dead` });
124
+ delete state.owners[key];
125
+ }
126
+ } catch {
127
+ }
128
+ }
129
+ return reaped;
130
+ }
87
131
  var Store = class {
88
132
  constructor(dir) {
89
133
  this.dir = dir;
@@ -1000,25 +1044,8 @@ var Runtime = class {
1000
1044
  }
1001
1045
  persistOwner(sessionId) {
1002
1046
  this.store.transaction((state) => {
1003
- for (const key of Object.keys(state.owners)) {
1004
- if (key === this.id) continue;
1005
- const row = state.owners[key];
1006
- if (row.sessionId !== sessionId) continue;
1007
- const liveness = path3.join(this.store.dir, "owners-liveness", `${key}.json`);
1008
- try {
1009
- const parsed = JSON.parse(fs3.readFileSync(liveness, "utf8"));
1010
- if (typeof parsed.pid !== "number" || parsed.pid <= 0) continue;
1011
- try {
1012
- process.kill(parsed.pid, 0);
1013
- continue;
1014
- } catch (err) {
1015
- if (err.code !== "ESRCH") continue;
1016
- }
1017
- delete state.owners[key];
1018
- } catch {
1019
- }
1020
- }
1021
- state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
1047
+ sweepStaleOwners(state, this.store.dir, { sessionId, keepKey: this.id, warn: (message) => this.ctx.log(message) });
1048
+ state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle(), registeredAt: Date.now() };
1022
1049
  });
1023
1050
  try {
1024
1051
  const livenessDir = path3.join(this.store.dir, "owners-liveness");
@@ -1592,7 +1619,13 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
1592
1619
  const note = auditNote({ kind: action, jobId, sessionId: job?.sessionId, cwd: job?.cwd, authorization });
1593
1620
  return `${action}: ${jobId}${note}`;
1594
1621
  }
1595
- throw new Error('Usage: /tools/cron list | add {"prompt":"...","schedule":{"every":3600}} | pause|resume|remove <id>');
1622
+ if (action === "reap-owners") {
1623
+ const warnings = [];
1624
+ const reaped = store.transaction((state) => sweepStaleOwners(state, store.dir, { warn: (message) => warnings.push(message) }));
1625
+ const note = auditNote({ kind: "remove", detail: `reap-owners: ${reaped.length} owner row(s) reaped`, authorization: authorizationNow() });
1626
+ return JSON.stringify({ reaped, total: reaped.length, ...warnings.length ? { warnings } : {} }, null, 2) + note;
1627
+ }
1628
+ throw new Error('Usage: /tools/cron list | reap-owners | add {"prompt":"...","schedule":{"every":3600}} | pause|resume|remove <id>');
1596
1629
  };
1597
1630
  ctx.registerCommand({ path: ["tools", "cron"], description: "Persistent same-session schedules (UTC): list/add/pause/resume/remove", handler: async (_ctx, args) => {
1598
1631
  try {
@@ -287,6 +287,63 @@ path no longer truncates bodies.
287
287
  text reply can overtake an earlier multi-image download. Wait for acceptance
288
288
  before sending a follow-up that depends on those images.
289
289
 
290
+ Context and Compact buttons are shown only for peers advertising those controls.
291
+ A Compact receipt confirms submission, not a committed checkpoint. If the peer
292
+ sent no verifiable receipt, check Context before requesting compaction again.
293
+
294
+ ## Panel actions (script-backed custom buttons)
295
+
296
+ 11-23, user-settled design. A custom panel button is the trigger for a
297
+ PRE-WRITTEN script (capability sedimentation): the LLM participates exactly
298
+ once — when a group member asks the manager for a repeatable capability and a
299
+ worker develops + tests the script — and every later click is deterministic
300
+ execution (zero LLM, zero token spend).
301
+
302
+ - Registry: `<configRoot>/panel-actions/registry.json` (atomic tmp+rename
303
+ writes; a corrupt file surfaces as an error and is never silently wiped).
304
+ Scripts, per-run full logs and per-action execution locks live beside it
305
+ (`logs/`, `locks/`).
306
+ - Scopes: `manager` (main /panel card), `worker` (EVERY worker card — the
307
+ button payload carries the clicked worker's name+dir, so one generic
308
+ definition runs with any worker's context), `worker:<name>` (pinned).
309
+ - Script contract: interpreter by extension (.mjs/.js→node, .sh→bash,
310
+ .py→python3, otherwise shebang+exec bit); context arrives as env
311
+ (`PIE_ACTION_ID`, `PIE_ACTION_TRIGGER_NAME/OPEN_ID`, `PIE_ACTION_CHAT_ID`,
312
+ `PIE_ACTION_PAYLOAD` (JSON), `PIE_ACTION_WORKER`, `PIE_ACTION_WORKER_DIR`)
313
+ over a deliberately minimal environment (manager bootstrap/model identity
314
+ never leaks into scripts); stdout IS the result (markdown posted to IM);
315
+ exit 0 = success, non-zero = failure with the stderr tail; per-action
316
+ timeout defaults to 5 min. On POSIX the executor verifies the per-launch identity
317
+ of live members of the script's process group before TERM/KILL and waits for
318
+ that group to stop before releasing the action slot. A subprocess that starts
319
+ a separate process group is outside this guarantee. Unknown ownership is not
320
+ permission to signal. On IM configuration retirement, a script still awaiting
321
+ its initial card receipt is not started; an already running script is cancelled.
322
+ The old connection stays available for up to 7 s for terminal card updates.
323
+ A pending name lookup is cancelled so a finished script can report its actual
324
+ result using the captured identity. A receipt arriving after that window is
325
+ not replayed or patched via the new connection.
326
+ - Execution: the callback acks fast (<500ms contract), runs in the
327
+ background, then patches the SAME ack card with the result (one click, one
328
+ card). The per-action execution lock is a cross-process mkdir + link-CAS
329
+ protocol (the pie-proc registry's primitive): write-once info.json,
330
+ token-merged renew.json (deadline re-arm + childPid fencing record),
331
+ generation-checked release/rearm, and rename-aside reaping with
332
+ last-moment revalidation. The stale-lock reaper uses a separate check: an
333
+ unverifiable recorded child leaves the slot locked with a recovery note.
334
+ On POSIX that reaper checks signal delivery, not that all descendants have
335
+ exited. Ordinary script completion also does not wait for background jobs
336
+ whose pipes have closed. Scripts should join their background work. Windows
337
+ timeout cleanup is best effort; it does not verify that a whole tree exited.
338
+ - Governance is attribution, not permission (user decision): the registry
339
+ records the creator, every result card bylines the triggerer ("由 张三 触
340
+ 发"), and every run appends to `audit.jsonl`. There is deliberately NO
341
+ allowUsers gate on clicking; the hard limits are the execution lock and the
342
+ timeout (resource protection), plus honest degradation (`logDegraded`).
343
+ - The `panel_action` management tool (add/remove/list) registers on the
344
+ manager host only (`PIE_PROC_CURATED_NAME=manager`): the manager's panel
345
+ serves the registry, so only the manager may write it.
346
+
290
347
  ## Extension host API
291
348
 
292
349
  `ctx.beginUserInput(isCurrent?)` is interactive-only and unavailable until the