@abelxiaoxing/cadence 2.0.24 → 2.0.26

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,6 +1,11 @@
1
1
  /** Background-agent panel for Pi's TUI. Observation only: it subscribes to
2
2
  * the `subagent:*` events on Pi's shared extension bus and renders them; it
3
- * never starts, cancels or keeps an agent or the Pi process alive. */
3
+ * never starts, cancels or keeps an agent or the Pi process alive.
4
+ *
5
+ * Nothing shows while no agent runs. A batch of agents is live above the
6
+ * input; once all of them ended it collapses into a card in the transcript
7
+ * (a display-only session entry) and the live view goes away. The list below
8
+ * the input appears only while it is being used. */
4
9
  import {
5
10
  AssistantMessageComponent,
6
11
  type ExtensionAPI,
@@ -24,7 +29,14 @@ import {
24
29
  truncateToWidth,
25
30
  } from "@earendil-works/pi-tui";
26
31
  import {
32
+ type AgentCard,
33
+ CARD_ENTRY,
34
+ cardLines,
35
+ cardOf,
36
+ decodeCard,
27
37
  factsText,
38
+ liveLines,
39
+ MAX_ENDED,
28
40
  type Paint,
29
41
  type PanelAction,
30
42
  PanelFocus,
@@ -35,19 +47,23 @@ import {
35
47
  type SubagentState,
36
48
  SubagentStore,
37
49
  statusSymbol,
38
- summaryLines,
39
50
  } from "./agent-panel-model.ts";
40
51
 
41
52
  export interface AgentPanelOptions {
42
53
  /** Agent rows shown at once; more collapse into `+K more`. */
43
54
  maxRows?: number;
44
- /** Keep `● main` visible with no agents (CADENCE_AGENT_PANEL=always). */
45
- showEmpty?: boolean;
55
+ /** Keep a finished batch live instead of collapsing it into a card
56
+ * (CADENCE_AGENT_PANEL=always). */
57
+ keep?: boolean;
46
58
  now?: () => number;
47
59
  }
48
- const PANEL = "cadence-agents",
49
- SUMMARY = "cadence-agents-summary",
60
+ const LIVE = "cadence-agents",
61
+ LIST = "cadence-agents-list",
50
62
  SPIN_MS = 100;
63
+ /** A batch whose agents all ended stays live this long before it collapses
64
+ * into its card, so the outcome is seen and a start that follows at once
65
+ * (the next workflow step) joins the same batch. */
66
+ export const SETTLE_MS = 1500;
51
67
 
52
68
  /** Rows kept for Pi's footer/status lines while an agent view is shown. */
53
69
  const RESERVED = 5;
@@ -86,13 +102,31 @@ export function registerAgentPanel(
86
102
  pi.events.on(channel, (data) => {
87
103
  store.apply(channel, data);
88
104
  });
105
+ // Pi renders the card where it was appended and again on resume; Ctrl+O
106
+ // (Pi's tool-output expansion) lists every member.
107
+ pi.registerEntryRenderer(CARD_ENTRY, (entry, { expanded }, theme) => {
108
+ const card = decodeCard(entry.data);
109
+ if (!card) return undefined;
110
+ const paint = themePaint(theme);
111
+ return {
112
+ render: (width) =>
113
+ cardLines(card, expanded, Math.max(1, width - 1), paint).map(
114
+ (line) => ` ${line}`,
115
+ ),
116
+ invalidate() {},
117
+ };
118
+ });
89
119
  let detach: (() => void) | undefined;
90
120
  pi.on("session_start", (_event, ctx) => {
91
121
  detach?.();
92
122
  detach =
93
123
  ctx.mode === "tui" && ctx.hasUI
94
- ? attachPanel(ctx, store, options, (id) =>
95
- pi.events.emit(SUBAGENT_VIEW, { id }),
124
+ ? attachPanel(
125
+ ctx,
126
+ store,
127
+ options,
128
+ (id) => pi.events.emit(SUBAGENT_VIEW, { id }),
129
+ (card) => pi.appendEntry(CARD_ENTRY, card),
96
130
  )
97
131
  : undefined;
98
132
  });
@@ -107,19 +141,28 @@ function attachPanel(
107
141
  store: SubagentStore,
108
142
  options: AgentPanelOptions,
109
143
  announce: (id: string | null) => void,
144
+ commit: (card: AgentCard) => void,
110
145
  ): () => void {
111
146
  const now = options.now ?? Date.now;
112
147
  const maxRows = Math.max(1, options.maxRows ?? 6);
113
- const showEmpty =
114
- options.showEmpty ?? process.env.CADENCE_AGENT_PANEL === "always";
115
- const focus = new PanelFocus(store);
148
+ const keep = options.keep ?? process.env.CADENCE_AGENT_PANEL === "always";
149
+ const focus = new PanelFocus(store, maxRows);
150
+ // A batch that ended while no session showed it has no card to give, and a
151
+ // new session lists only its own agents; ones still running carry over.
152
+ if (store.settled()) store.closeBatch();
153
+ store.prune(0);
116
154
  let tui: TUI | undefined,
117
155
  paint: Paint = (_role, text) => text,
118
156
  frame = 0,
119
157
  spinner: ReturnType<typeof setInterval> | undefined,
158
+ settling: ReturnType<typeof setTimeout> | undefined,
120
159
  view: { component: Component; done: () => void } | undefined,
121
- // Widgets mount with the first agent, so ordinary sessions show nothing.
122
- mounted = false,
160
+ // Mounted widgets: the batch above the input while one is live, and the
161
+ // list's slot below it while any agent is kept for review.
162
+ live = false,
163
+ list = false,
164
+ // The last batch, kept live after it ended (CADENCE_AGENT_PANEL=always).
165
+ kept: SubagentState[] = [],
123
166
  // The agent last announced on `subagent:view`, so producers load only it.
124
167
  announced: string | undefined;
125
168
  const announceView = () => {
@@ -132,10 +175,84 @@ function attachPanel(
132
175
  clearInterval(spinner);
133
176
  spinner = undefined;
134
177
  };
178
+ const liveAgents = () => {
179
+ const open = store.batch();
180
+ return open.length ? open : kept;
181
+ };
182
+ const widget =
183
+ (lines: (width: number) => string[]) => (t: TUI, theme: Theme) => {
184
+ tui = t;
185
+ paint = themePaint(theme);
186
+ return { render: lines, invalidate() {} };
187
+ };
188
+ const liveWidget = widget((width) =>
189
+ // The agent view takes this place; a summary above it would be noise.
190
+ view
191
+ ? []
192
+ : liveLines(
193
+ {
194
+ agents: liveAgents(),
195
+ now: now(),
196
+ frame,
197
+ maxRows,
198
+ hint: focus.focus === "input",
199
+ },
200
+ width,
201
+ paint,
202
+ ),
203
+ );
204
+ const listWidget = widget((width) => panelLines(panelFrame(), width, paint));
205
+ const mount = () => {
206
+ const showLive = liveAgents().length > 0;
207
+ // The list renders nothing until used, and Pi gives the slot below the
208
+ // input no spacing, so it costs no row; mounting it while agents exist
209
+ // is what lets ↓ see whether Pi's input box has focus.
210
+ const showList = store.size > 0 || focus.view !== undefined;
211
+ if (showLive !== live) {
212
+ live = showLive;
213
+ ctx.ui.setWidget(LIVE, showLive ? liveWidget : undefined, {
214
+ placement: "aboveEditor",
215
+ });
216
+ }
217
+ if (showList !== list) {
218
+ list = showList;
219
+ ctx.ui.setWidget(LIST, showList ? listWidget : undefined, {
220
+ placement: "belowEditor",
221
+ });
222
+ }
223
+ };
224
+ /** Close the settled batch: its card goes into the session, the live view
225
+ * goes away and older ended agents beyond the review bound are dropped. */
226
+ const close = () => {
227
+ clearTimeout(settling);
228
+ settling = undefined;
229
+ if (!store.settled()) return;
230
+ const agents = store.closeBatch();
231
+ if (keep) kept = agents;
232
+ else
233
+ try {
234
+ commit(cardOf(agents));
235
+ } catch {
236
+ // A replaced runtime cannot append; the agents stay reviewable.
237
+ }
238
+ const dropped = store.prune(MAX_ENDED, [focus.selected, focus.view]);
239
+ for (const id of dropped) transcripts.delete(id);
240
+ focus.forget(dropped);
241
+ };
135
242
  // One redraw per spinner frame while anything runs; Pi's differential
136
243
  // renderer rewrites only the changed rows.
137
244
  const changed = () => {
138
- if (!mounted && (store.size > 0 || showEmpty)) mount();
245
+ if (kept.length && store.batch().length) kept = [];
246
+ if (!store.settled()) {
247
+ clearTimeout(settling);
248
+ settling = undefined;
249
+ } else if (!settling) {
250
+ settling = setTimeout(() => {
251
+ close();
252
+ changed();
253
+ }, SETTLE_MS);
254
+ settling.unref?.();
255
+ }
139
256
  if (store.running() === 0) stopSpinner();
140
257
  else if (!spinner) {
141
258
  spinner = setInterval(() => {
@@ -144,6 +261,7 @@ function attachPanel(
144
261
  }, SPIN_MS);
145
262
  spinner.unref?.();
146
263
  }
264
+ mount();
147
265
  tui?.requestRender();
148
266
  };
149
267
  const unsubscribe = store.subscribe(changed);
@@ -157,6 +275,7 @@ function attachPanel(
157
275
  if (action === "open") openView();
158
276
  else if (action === "close") view?.done();
159
277
  announceView();
278
+ mount();
160
279
  tui?.requestRender();
161
280
  return action === "pass" ? undefined : { consume: true };
162
281
  };
@@ -168,10 +287,12 @@ function attachPanel(
168
287
  focus.abandon();
169
288
  view = undefined;
170
289
  announceView();
290
+ mount();
171
291
  }
172
292
  if (focus.focus === "panel" && !editorFocused()) {
173
293
  // A dialog took focus: its keys are not the panel's.
174
- focus.focus = "input";
294
+ focus.abandon();
295
+ mount();
175
296
  tui?.requestRender();
176
297
  return undefined;
177
298
  }
@@ -208,7 +329,6 @@ function attachPanel(
208
329
  now: now(),
209
330
  frame,
210
331
  maxRows,
211
- showEmpty,
212
332
  });
213
333
  const viewLines = (width: number): string[] => {
214
334
  const agent = focus.view === undefined ? undefined : store.get(focus.view);
@@ -257,47 +377,20 @@ function attachPanel(
257
377
  )}`;
258
378
  };
259
379
 
260
- const mount = () => {
261
- mounted = true;
262
- ctx.ui.setWidget(
263
- SUMMARY,
264
- (t, theme) => {
265
- tui = t;
266
- paint = themePaint(theme);
267
- return {
268
- // The agent view takes Z1's place; its summary would sit above it.
269
- render: (width) =>
270
- view ? [] : summaryLines(store.ordered(), width, paint, maxRows),
271
- invalidate() {},
272
- };
273
- },
274
- { placement: "aboveEditor" },
275
- );
276
- ctx.ui.setWidget(
277
- PANEL,
278
- (t, theme) => {
279
- tui = t;
280
- paint = themePaint(theme);
281
- return {
282
- render: (width) => panelLines(panelFrame(), width, paint),
283
- invalidate() {},
284
- };
285
- },
286
- { placement: "belowEditor" },
287
- );
288
- };
289
380
  changed();
290
381
  return () => {
291
382
  unsubscribe();
292
383
  unlisten();
293
384
  stopSpinner();
385
+ // A batch that already ended still gets its card in the session it ran
386
+ // in; one still running carries over to the next session.
387
+ if (settling) close();
388
+ clearTimeout(settling);
294
389
  if (announced !== undefined) announce(null);
295
390
  try {
296
391
  view?.done();
297
- if (mounted) {
298
- ctx.ui.setWidget(SUMMARY, undefined);
299
- ctx.ui.setWidget(PANEL, undefined);
300
- }
392
+ if (live) ctx.ui.setWidget(LIVE, undefined);
393
+ if (list) ctx.ui.setWidget(LIST, undefined);
301
394
  } catch {
302
395
  // A replaced runtime already cleared its UI.
303
396
  }
@@ -408,7 +408,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
408
408
  // A signal (including the timeout) reports code 0 from Pi's exec.
409
409
  if (launched.killed || launched.code !== 0)
410
410
  throw new Error(
411
- `Cadence project owner could not start${launched.killed ? " before its startup deadline" : ""}.${bun ? " Pi runs on Bun here; on-demand startup needs Node.js 22.19+ on PATH." : ""} No install, fallback or uncertain-lock cleanup was attempted. Use cadence-service diagnose --workspace <path> for details.`,
411
+ `Cadence project owner could not start${launched.killed ? " before its startup deadline" : ""}.${bun ? " Pi runs on Bun here; on-demand startup needs Node.js 22.19+ on PATH." : ""}${launched.stderr.trim() ? `\n${launched.stderr.trim().split("\n").slice(-3).join("\n")}` : ""}\nDetails: cadence doctor --workspace ${JSON.stringify(ctx.cwd)}`,
412
412
  );
413
413
  let workspace = effectiveWorkspace(ctx.cwd).workspace;
414
414
  try {
@@ -446,18 +446,29 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
446
446
  const observed = new ServiceCoordination(
447
447
  effectiveWorkspace(ctx.cwd).workspace,
448
448
  ).inspect();
449
- if (
450
- (observed.status === "absent" || observed.status === "stopped") &&
451
- allowStart
452
- ) {
449
+ const notRunning =
450
+ observed.status === "absent" || observed.status === "stopped";
451
+ if (notRunning && allowStart) {
453
452
  await launchOwner(ctx);
454
453
  check();
455
454
  }
456
455
  try {
457
456
  await connection.attach(ctx.cwd);
458
457
  } catch (error) {
459
- reattach = true;
460
- throw error;
458
+ if (notRunning || !allowStart) {
459
+ reattach = true;
460
+ throw error;
461
+ }
462
+ // A registration left by an owner that died (machine restart, crash)
463
+ // does not answer; opening the project recovers it automatically.
464
+ await launchOwner(ctx);
465
+ check();
466
+ try {
467
+ await connection.attach(ctx.cwd);
468
+ } catch (again) {
469
+ reattach = true;
470
+ throw again;
471
+ }
461
472
  }
462
473
  check();
463
474
  })();
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "b855efce6a9694452dd77fcdad0b5dbecce617643cc81ac7c55dafb0f2ca7848",
5
+ "663f71a44cd33f95377644cfc10c2cb657298f191b36d6ca05b810e849c54e68",
6
6
  } as const;
@@ -17,7 +17,7 @@ import { HttpServiceTransport } from "./service-http-client.ts";
17
17
  import { effectiveWorkspace } from "./workspace.ts";
18
18
 
19
19
  export const MANAGEMENT_GUIDANCE =
20
- "Cadence owner absent, unavailable or incompatible. Explicitly run cadence-service status --workspace <path>, cadence-service diagnose --workspace <path>, or cadence-service start --workspace <path>. Stop older Cadence sessions first. For retained fences use cadence-service recover inspect; resolve requires a local terminal and separate process, credential and storage acknowledgments. Never treat unavailable/quarantined as stopped. No service was started and no embedded executor is available.";
20
+ "Cadence owner absent, unavailable or incompatible. Start it with cadence start --workspace <path> (it recovers automatically from an unclean shutdown), or see what is wrong with cadence doctor --workspace <path>. Stop older Cadence sessions first. No service was started and no embedded executor is available.";
21
21
 
22
22
  const UNIT = "cadence.service";
23
23
  const LABEL = "com.abelxiaoxing.cadence";
@@ -13,7 +13,7 @@ import {
13
13
  unlinkSync as unlinkSync2,
14
14
  writeFileSync as writeFileSync2
15
15
  } from "node:fs";
16
- import { hostname as hostname2 } from "node:os";
16
+ import { hostname as hostname3 } from "node:os";
17
17
  import { join as join3 } from "node:path";
18
18
 
19
19
  // src/data-shapes.ts
@@ -305,8 +305,77 @@ import {
305
305
  unlinkSync,
306
306
  writeFileSync
307
307
  } from "node:fs";
308
- import { hostname } from "node:os";
308
+ import { hostname as hostname2 } from "node:os";
309
309
  import { dirname as dirname2, join as join2 } from "node:path";
310
+
311
+ // src/service/liveness.ts
312
+ import { spawnSync as spawnSync2 } from "node:child_process";
313
+ import { readFileSync } from "node:fs";
314
+ import { hostname, uptime } from "node:os";
315
+ var LEGACY_BOOT_MARGIN_MS = 10 * 60 * 1000;
316
+ var cachedBoot;
317
+ function bootId() {
318
+ if (cachedBoot !== undefined)
319
+ return cachedBoot;
320
+ cachedBoot = null;
321
+ try {
322
+ if (process.platform === "linux") {
323
+ const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
324
+ if (/^[0-9a-f-]{36}$/.test(id))
325
+ cachedBoot = id;
326
+ } else if (process.platform === "darwin") {
327
+ const r = spawnSync2("sysctl", ["-n", "kern.bootsessionuuid"], {
328
+ encoding: "utf8",
329
+ timeout: 2000
330
+ });
331
+ const id = r.status === 0 ? r.stdout.trim() : "";
332
+ if (/^[0-9A-Fa-f-]{36}$/.test(id))
333
+ cachedBoot = id;
334
+ }
335
+ } catch {
336
+ cachedBoot = null;
337
+ }
338
+ return cachedBoot;
339
+ }
340
+ function linuxStat(pid) {
341
+ try {
342
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
343
+ return stat.slice(stat.lastIndexOf(")") + 2).trim().split(" ");
344
+ } catch {
345
+ return null;
346
+ }
347
+ }
348
+ function processStart(pid) {
349
+ if (!Number.isSafeInteger(pid) || pid < 1)
350
+ return null;
351
+ if (process.platform === "linux") {
352
+ const fields = linuxStat(pid);
353
+ const ticks = fields?.[19];
354
+ return ticks && /^\d+$/.test(ticks) ? `ticks:${ticks}` : null;
355
+ }
356
+ if (process.platform === "darwin") {
357
+ const r = spawnSync2("ps", ["-o", "lstart=", "-p", String(pid)], {
358
+ encoding: "utf8",
359
+ timeout: 2000,
360
+ env: { ...process.env, LC_ALL: "C" }
361
+ });
362
+ const value = r.status === 0 ? r.stdout.trim() : "";
363
+ return value ? `lstart:${value}` : null;
364
+ }
365
+ return null;
366
+ }
367
+ var cachedSelf;
368
+ function selfMark() {
369
+ cachedSelf ??= processStart(process.pid);
370
+ return {
371
+ pid: process.pid,
372
+ host: hostname(),
373
+ boot: bootId(),
374
+ started: cachedSelf
375
+ };
376
+ }
377
+
378
+ // src/service/checkout-lock.ts
310
379
  class CheckoutStore {
311
380
  root;
312
381
  privateRoot;
@@ -357,13 +426,16 @@ class CheckoutStore {
357
426
  acquire() {
358
427
  this.inspectPrivate();
359
428
  safeDirectory(this.privateRoot, true);
429
+ const mark = selfMark();
360
430
  const lock = {
361
431
  schema: "cadence-assistant-lock/1",
362
432
  token: randomUUID(),
363
433
  runId: randomUUID(),
364
434
  pid: process.pid,
365
- host: hostname(),
366
- root: this.root
435
+ host: hostname2(),
436
+ root: this.root,
437
+ boot: mark.boot,
438
+ started: mark.started
367
439
  };
368
440
  let fd;
369
441
  try {
@@ -384,7 +456,7 @@ class CheckoutStore {
384
456
  throw new Error("Coordination lock changed");
385
457
  }
386
458
  release(lock) {
387
- if (lock.pid !== process.pid || lock.host !== hostname())
459
+ if (lock.pid !== process.pid || lock.host !== hostname2())
388
460
  throw new Error("Only the owning process may release a lock");
389
461
  this.assertOwner(lock);
390
462
  retryWindowsFileOperation(() => unlinkSync(this.lockPath), () => this.assertOwner(lock));
@@ -406,7 +478,7 @@ class TaskStore extends CheckoutStore {
406
478
  this.tasks = join3(this.root, ".cadence", "assistant", "tasks");
407
479
  }
408
480
  recover(expected, acknowledgeEscapedProcesses) {
409
- if (!acknowledgeEscapedProcesses || expected.host !== hostname2())
481
+ if (!acknowledgeEscapedProcesses || expected.host !== hostname3())
410
482
  throw new Error("Recovery requires informed local-owner confirmation");
411
483
  this.assertOwner(expected);
412
484
  try {
@@ -458,7 +530,7 @@ class TaskStore extends CheckoutStore {
458
530
  if (Buffer.byteLength(text) > MAX_RECORD_BYTES)
459
531
  throw new Error("Task record limit");
460
532
  const lock = held ?? this.acquire();
461
- if (lock.pid !== process.pid || lock.host !== hostname2())
533
+ if (lock.pid !== process.pid || lock.host !== hostname3())
462
534
  throw new Error("Not the lock owner");
463
535
  try {
464
536
  this.assertOwner(lock);
@@ -515,7 +587,7 @@ class TaskStore extends CheckoutStore {
515
587
  return data ? diagnosticText(data.toString("utf8"), 65536) : "Private diagnostic unavailable";
516
588
  }
517
589
  writeLog(lock, output) {
518
- if (lock.pid !== process.pid || lock.host !== hostname2())
590
+ if (lock.pid !== process.pid || lock.host !== hostname3())
519
591
  throw new Error("Not the lock owner");
520
592
  this.assertOwner(lock);
521
593
  const name = `${randomUUID2()}.log`;
@@ -23,6 +23,7 @@ import {
23
23
  retryWindowsFileOperation,
24
24
  safeDirectory,
25
25
  } from "../workspace.ts";
26
+ import { selfMark } from "./liveness.ts";
26
27
  export interface CheckoutLock {
27
28
  schema: "cadence-assistant-lock/1";
28
29
  token: string;
@@ -30,6 +31,9 @@ export interface CheckoutLock {
30
31
  host: string;
31
32
  runId: string;
32
33
  root: string;
34
+ /** Liveness marks (absent in locks written by older releases). */
35
+ boot?: string | null;
36
+ started?: string | null;
33
37
  }
34
38
  export class CheckoutStore {
35
39
  readonly root: string;
@@ -100,6 +104,7 @@ export class CheckoutStore {
100
104
  acquire(): CheckoutLock {
101
105
  this.inspectPrivate();
102
106
  safeDirectory(this.privateRoot, true);
107
+ const mark = selfMark();
103
108
  const lock: CheckoutLock = {
104
109
  schema: "cadence-assistant-lock/1",
105
110
  token: randomUUID(),
@@ -107,6 +112,8 @@ export class CheckoutStore {
107
112
  pid: process.pid,
108
113
  host: hostname(),
109
114
  root: this.root,
115
+ boot: mark.boot,
116
+ started: mark.started,
110
117
  };
111
118
  let fd: number;
112
119
  try {