@abelxiaoxing/cadence 2.0.37 → 2.0.38

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 (43) hide show
  1. package/README.de.md +2 -2
  2. package/README.es.md +2 -2
  3. package/README.fr.md +2 -2
  4. package/README.ja.md +2 -2
  5. package/README.ko.md +2 -2
  6. package/README.md +9 -7
  7. package/README.pt-BR.md +2 -2
  8. package/README.ru.md +2 -2
  9. package/README.zh-CN.md +10 -8
  10. package/agents/design-explorer.md +4 -2
  11. package/agents/diagnosis-worker.md +5 -2
  12. package/agents/implementation-worker.md +19 -12
  13. package/docs/conversation-mode.md +43 -16
  14. package/package.json +4 -1
  15. package/src/agent-browser/session-navigator.ts +33 -6
  16. package/src/agent-browser/source.ts +23 -19
  17. package/src/agent-panel-cadence.ts +147 -628
  18. package/src/agent-panel-model.ts +30 -19
  19. package/src/agent-panel.ts +12 -16
  20. package/src/cadence-instructions.ts +8 -7
  21. package/src/cadence-mode.ts +30 -9
  22. package/src/change-tools.mjs +268 -0
  23. package/src/coordinator-tools.mjs +2 -2
  24. package/src/git-environment.d.mts +2 -0
  25. package/src/git-environment.mjs +24 -0
  26. package/src/index.ts +1 -1
  27. package/src/native-build.ts +1 -1
  28. package/src/native-workflow-history.ts +20 -3
  29. package/src/operator-cli.mjs +18 -11
  30. package/src/sdk-worker.mjs +2 -0
  31. package/src/service/contracts/workbench.ts +11 -3
  32. package/src/service/contracts/workflow.ts +283 -16
  33. package/src/service/coordination.ts +7 -0
  34. package/src/service-cli.mjs +366 -85
  35. package/src/service-host.mjs +2450 -983
  36. package/src/worker-capture.mjs +24 -1
  37. package/src/worker-public.mjs +18 -0
  38. package/src/worker-redaction.mjs +11 -0
  39. package/src/worker-toolkit.mjs +48 -1
  40. package/src/workspace.ts +4 -24
  41. package/web/dist/assets/cadence.css +1 -1
  42. package/web/dist/assets/cadence.js +18 -17
  43. package/web/dist/manifest.json +7 -7
@@ -1,11 +1,6 @@
1
- /** Cadence service children on the background-agent panel. Observation only:
2
- * a Pi TUI session attaches to the owner already running for its workspace
3
- * (never starting one), polls the active task roster and task snapshots plus
4
- * the conversation-workflow roster and runs, and announces each child run
5
- * (task children and workflow research/implementation/review subagents) on
6
- * Pi's `subagent:*` bus. Reads go through the
7
- * typed ServiceClient; nothing here starts, cancels, retries or keeps work
8
- * alive, and leaving the session only detaches. */
1
+ /** Readonly workflow observation for this Pi conversation, never the whole
2
+ * checkout. Attribution uses the run's immutable admission context, not copied
3
+ * session history. Missing attribution never broadcasts. Departure detaches. */
9
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
5
  import { SUBAGENT_EVENTS, SUBAGENT_VIEW } from "./agent-panel-model.ts";
11
6
  import { departure, NativeConnection } from "./native-client.ts";
@@ -15,16 +10,7 @@ import type {
15
10
  WorkflowStep,
16
11
  } from "./service/contracts/workflow.ts";
17
12
  import type { ServiceClient } from "./service-client.ts";
18
- import {
19
- type ContentRef,
20
- type GraphReadRequest,
21
- type HistoryRecord,
22
- LIMITS,
23
- type ListRequest,
24
- type ReadCursor,
25
- type RunProjection,
26
- type Snapshot,
27
- } from "./service-contract.ts";
13
+ import { LIMITS } from "./service-contract.ts";
28
14
 
29
15
  /** The NativeConnection surface the feed uses; tests substitute it. */
30
16
  export interface FeedConnection {
@@ -32,21 +18,10 @@ export interface FeedConnection {
32
18
  refresh(): Promise<unknown>;
33
19
  compatible(): boolean;
34
20
  detach(): Promise<void>;
35
- /** Drop an attachment whose owner the registry proves gone or replaced. */
36
21
  forgetSuperseded?(cwd: string): boolean;
37
22
  }
38
- /** Readonly ServiceClient reads only: no command, preflight or Cancel. */
39
- export type FeedClient = Pick<
40
- ServiceClient,
41
- | "activeRuns"
42
- | "snapshot"
43
- | "graph"
44
- | "messages"
45
- | "tools"
46
- | "contents"
47
- | "detail"
48
- | "workbenchRead"
49
- >;
23
+ /** No command, preflight, Cancel or project-wide legacy task reads. */
24
+ export type FeedClient = Pick<ServiceClient, "workbenchRead">;
50
25
  export interface CadenceFeedOptions {
51
26
  connection?: () => FeedConnection;
52
27
  now?: () => number;
@@ -58,7 +33,6 @@ export interface FeedTiming {
58
33
  idleMs: number;
59
34
  retryMs: number;
60
35
  }
61
-
62
36
  /** First look waits for Pi's startup render; workspace resolution runs Git. */
63
37
  export const FEED_TIMING: FeedTiming = {
64
38
  firstMs: 500,
@@ -66,85 +40,40 @@ export const FEED_TIMING: FeedTiming = {
66
40
  idleMs: LIMITS.heartbeatMs,
67
41
  retryMs: 15_000,
68
42
  };
69
- /** Retained reads are paged; a child larger than this stays in /cadence-history. */
70
- const MAX_PAGES = 50;
71
- const MAX_DETAIL_STEPS = 8;
72
43
  /** Characters of one field shown in the panel; the rest stays retained. */
73
44
  const TEXT_CAP = 64 * 1024;
74
- const CACHE_CHARS = 16 * 1024 * 1024;
75
- /** Snapshots after an episode drained, while its children still look unsettled. */
45
+ /** Consecutive unreadable looks before ending an observation as unknown. */
76
46
  const DRAIN_LOOKS = 5;
77
- /** A running workflow subagent not shown in a view refreshes its activity at
78
- * most this often; its retained transcript is one bounded owner file. */
47
+ /** Unviewed running children refresh their activity at most this often. */
79
48
  const WORKFLOW_ACTIVITY_MS = 10_000;
80
49
  const WORKFLOW_KINDS: Partial<Record<WorkflowStep["kind"], string>> = {
81
50
  research: "Research",
82
51
  implementation: "Implementation",
52
+ diagnosis: "Diagnosis",
53
+ knowledge: "Knowledge",
83
54
  review: "Review",
84
55
  };
85
-
86
56
  type Child = {
87
57
  id: string;
88
- /** Assignment ID: rows lead with it, since kinds repeat. */
89
58
  label: string;
90
59
  runId: string;
91
- storeId: string;
92
- /** Committed watermark of the latest snapshot that showed this child. */
93
- seq: string;
94
- lifecycle: RunProjection["lifecycle"];
60
+ stepId: string;
95
61
  ended: boolean;
96
62
  activity: string;
97
- /** Activity from the latest tools read, shown while the child is running. */
98
63
  working?: string;
99
- toolsSeq?: string;
100
- transcriptSeq?: string;
101
- /** A transcript read failed at this watermark; reopening the view retries. */
102
- failedSeq?: string;
103
- /** Final transcript messages already announced. */
64
+ readAt?: number;
65
+ failed?: boolean;
104
66
  sent: number;
105
- /** A conversation-workflow subagent, read through workflow transcripts. */
106
- workflow?: {
107
- runId: string;
108
- stepId: string;
109
- /** The final transcript was announced after the step ended. */
110
- done?: boolean;
111
- readAt?: number;
112
- };
113
67
  };
114
- type Tool = Extract<HistoryRecord, { kind: "tool" }>;
115
- type Block = { index: number; ref: ContentRef };
116
- type Built = { messages: object[]; partial?: object; tools: Tool[] };
117
-
118
- /** Process-wide: children keep their announced state across sessions, like the
119
- * panel's store, so a later session never announces one twice. */
120
- class FeedState {
121
- readonly children = new Map<string, Child>();
122
- readonly purposes = new Map<string, Map<string, string>>();
123
- readonly texts = new Map<string, string>();
124
- cached = 0;
125
- viewing: string | undefined;
126
- remember(key: string, text: string): void {
127
- if (this.cached + text.length > CACHE_CHARS) {
128
- this.texts.clear();
129
- this.cached = 0;
130
- }
131
- this.texts.set(key, text);
132
- this.cached += text.length;
133
- }
134
- }
135
68
 
136
69
  export function registerCadenceAgentFeed(
137
70
  pi: ExtensionAPI,
138
71
  options: CadenceFeedOptions = {},
139
72
  ): void {
140
- const state = new FeedState();
141
73
  let feed: Feed | undefined;
142
74
  pi.events.on(SUBAGENT_VIEW, (data) => {
143
75
  const id = (data as { id?: unknown } | undefined)?.id;
144
- state.viewing = typeof id === "string" ? id : undefined;
145
- const child = state.viewing && state.children.get(state.viewing);
146
- if (child) child.failedSeq = undefined;
147
- feed?.wake();
76
+ feed?.view(typeof id === "string" ? id : undefined);
148
77
  });
149
78
  const stop = () => {
150
79
  const leaving = feed?.stop();
@@ -159,38 +88,13 @@ export function registerCadenceAgentFeed(
159
88
  process.env.CADENCE_AGENT_PANEL === "off"
160
89
  )
161
90
  return;
162
- feed = new Feed(pi, ctx.cwd, state, options);
91
+ const conversationId = ctx.sessionManager.getSessionId();
92
+ if (!conversationId) return;
93
+ feed = new Feed(pi, ctx.cwd, conversationId, options);
163
94
  });
164
95
  pi.on("session_shutdown", () => departure(stop()));
165
96
  }
166
97
 
167
- const label = (purpose: string | undefined, kind: string) =>
168
- purpose
169
- ? purpose[0].toUpperCase() + purpose.slice(1)
170
- : kind === "generate-plan"
171
- ? "Planner"
172
- : "Child";
173
- function lifecycleText(row: RunProjection): string {
174
- switch (row.lifecycle) {
175
- case "queued":
176
- return row.reason
177
- ? `Queued · ${row.reason.replaceAll("-", " ")}`
178
- : "Queued";
179
- case "preparing":
180
- return "Preparing";
181
- case "closing":
182
- return "Finishing";
183
- default:
184
- return "Working";
185
- }
186
- }
187
- function workingText(tools: Tool[]): string {
188
- const last = tools.at(-1);
189
- if (!last) return "Working";
190
- if (last.result === null) return `Running ${last.name}`;
191
- const n = tools.length;
192
- return `Working · ${n} tool call${n === 1 ? "" : "s"} (last: ${last.name})`;
193
- }
194
98
  /** Final or execution arguments are canonical JSON; anything else shows none. */
195
99
  function parseArgs(text: string | undefined): object {
196
100
  try {
@@ -281,18 +185,20 @@ class Feed {
281
185
  private readonly connection: FeedConnection;
282
186
  private readonly now: () => number;
283
187
  private readonly timing: FeedTiming;
284
- /** Parent run → task, followed until a snapshot after it left the roster. */
285
- private readonly episodes = new Map<
286
- string,
287
- { taskId: string; drained: number }
288
- >();
289
- /** Conversation workflow → consecutive unreadable looks, followed until
290
- * its run is observed finished. */
188
+ /** Only running children; settled ones live in the panel's display snapshot. */
189
+ private readonly children = new Map<string, Child>();
190
+ private viewing: string | undefined;
191
+ /** Attributed workflow → consecutive unreadable looks. A run leaving the
192
+ * roster remains ours until its final observation; attribution is not lost
193
+ * just because the roster no longer includes the finished run. */
291
194
  private readonly workflows = new Map<string, number>();
195
+ /** Failed observation is terminal for this observer, not a retry loop.
196
+ * Only ids remain, and only while the roster still lists those runs. */
197
+ private readonly abandoned = new Set<string>();
292
198
  constructor(
293
199
  private readonly pi: ExtensionAPI,
294
200
  private readonly cwd: string,
295
- private readonly state: FeedState,
201
+ private readonly conversationId: string,
296
202
  options: CadenceFeedOptions,
297
203
  ) {
298
204
  this.connection = options.connection?.() ?? new NativeConnection();
@@ -304,11 +210,13 @@ class Feed {
304
210
  this.stopped = true;
305
211
  clearTimeout(this.timer);
306
212
  this.abort.abort();
307
- // Detach this observer only; accepted work continues in the service.
308
213
  return this.connection.detach().catch(() => {});
309
214
  }
310
- /** The viewed agent changed: load its transcript now if attached. */
311
- wake(): void {
215
+ view(id: string | undefined): void {
216
+ this.viewing = id;
217
+ const child = id === undefined ? undefined : this.children.get(id);
218
+ if (!child || child.ended) return;
219
+ child.failed = false;
312
220
  if (this.busy) this.woken = true;
313
221
  else if (this.client) this.schedule(0);
314
222
  }
@@ -316,7 +224,6 @@ class Feed {
316
224
  clearTimeout(this.timer);
317
225
  if (this.stopped) return;
318
226
  this.timer = setTimeout(() => void this.tick(), ms);
319
- // Observation never keeps Pi alive.
320
227
  this.timer.unref?.();
321
228
  }
322
229
  private emit(event: keyof typeof SUBAGENT_EVENTS, data: object): void {
@@ -339,118 +246,103 @@ class Feed {
339
246
  if (!this.connection.compatible()) throw new Error("incompatible");
340
247
  this.client = client;
341
248
  }
342
- next = await this.observe(this.client);
249
+ await this.observe(this.client);
250
+ next = this.workflows.size ? this.timing.activeMs : this.timing.idleMs;
343
251
  } catch {
344
- // Absent, stopped, restarted or incompatible owner: detach and look
345
- // again later. Observation never starts one. An owner the registry
346
- // proves gone or replaced cannot accept a detach (a restarted one on the
347
- // same port refuses the old capability), so its attachment is dropped.
348
252
  this.client = undefined;
349
253
  if (!this.connection.forgetSuperseded?.(this.cwd))
350
254
  await this.connection.detach().catch(() => {});
351
- // Still no compatible owner a whole retry after losing it: the children
352
- // followed so far can no longer be observed from this session.
353
- if (attaching) {
354
- this.abandon([...this.episodes.keys()], "owner unavailable");
255
+ // One lost look is not an outcome. After a whole failed retry we can
256
+ // no longer observe the work, without claiming it actually failed.
257
+ if (attaching)
355
258
  for (const runId of [...this.workflows.keys()])
356
- this.abandonWorkflow(runId, "owner unavailable");
357
- }
259
+ this.abandon(runId, "owner unavailable");
358
260
  } finally {
359
261
  this.busy = false;
360
262
  }
361
263
  this.schedule(this.woken ? 0 : next);
362
264
  }
363
-
364
- private async observe(client: FeedClient): Promise<number> {
365
- const signal = this.abort.signal;
366
- const roster = await client.activeRuns(signal);
367
- if (roster.kind === "error" || roster.value.status !== "complete") {
368
- // stop() aborted this read; a session request now would race its detach.
369
- if (this.stopped) return this.timing.activeMs;
370
- // Throws when the owner is gone or restarted; otherwise look again soon.
371
- await this.connection.refresh();
372
- return this.timing.activeMs;
373
- }
374
- const active = new Set<string>();
375
- for (const run of roster.value.runs) {
376
- active.add(run.runId);
377
- this.episodes.set(run.runId, { taskId: run.taskId, drained: 0 });
378
- }
379
- const ends: object[] = [];
380
- for (const taskId of new Set(
381
- [...this.episodes.values()].map((e) => e.taskId),
382
- )) {
383
- const reply = await client.snapshot({ kind: "task", id: taskId }, signal);
384
- if (this.stopped) return this.timing.activeMs;
385
- for (const [runId, episode] of this.episodes) {
386
- if (episode.taskId !== taskId) continue;
387
- // A refused snapshot drains a finished episode like an unsettled one.
388
- const open =
389
- reply.kind === "error" ||
390
- (await this.follow(client, reply.value, runId, ends));
391
- if (active.has(runId)) continue;
392
- if (!open) this.episodes.delete(runId);
393
- else if (++episode.drained >= DRAIN_LOOKS)
394
- this.abandon([runId], "no settled row after the run ended");
395
- }
396
- }
397
- await this.observeWorkflows(client, ends);
398
- if (this.stopped) return this.timing.activeMs;
399
- await this.refreshActivity(client);
400
- await this.refreshTranscript(client);
401
- // Ends follow the transcript so its last streaming snapshot is replaced
402
- // by the final message rather than kept beside it.
403
- for (const end of ends) this.emit("end", end);
404
- return this.episodes.size || this.workflows.size
405
- ? this.timing.activeMs
406
- : this.timing.idleMs;
407
- }
408
-
409
- /** Conversation-workflow subagents: the live roster names runs, each run
410
- * read names its steps' child IDs. Readonly; an older owner without these
411
- * reads leaves only task children. */
412
- private async observeWorkflows(
413
- client: FeedClient,
414
- ends: object[],
415
- ): Promise<void> {
416
- if (typeof client.workbenchRead !== "function") return;
265
+ private async observe(client: FeedClient): Promise<void> {
417
266
  const signal = this.abort.signal;
418
267
  const roster = await client.workbenchRead(
419
268
  { kind: "workflow-active" },
420
269
  signal,
421
270
  );
422
271
  if (this.stopped) return;
423
- const live = new Set<string>();
424
- if (roster.kind === "ok" && roster.value.kind === "workflow-active")
425
- for (const run of roster.value.runs) {
426
- live.add(run.id);
427
- if (!this.workflows.has(run.id)) this.workflows.set(run.id, 0);
428
- }
429
- for (const [runId, misses] of [...this.workflows]) {
430
- const reply = await client.workbenchRead(
431
- { kind: "workflow", id: runId },
432
- signal,
433
- );
272
+ if (roster.kind === "ok" && roster.value.kind === "workflow-active") {
273
+ const listed = new Set(roster.value.runs.map((run) => run.id));
274
+ for (const id of this.abandoned)
275
+ if (!listed.has(id)) this.abandoned.delete(id);
276
+ for (const run of roster.value.runs)
277
+ if (
278
+ run.execution?.version.conversation?.id === this.conversationId &&
279
+ !this.abandoned.has(run.id) &&
280
+ !this.workflows.has(run.id)
281
+ )
282
+ this.workflows.set(run.id, 0);
283
+ } else {
284
+ // Detect a restarted owner, but do not turn an unreadable roster into
285
+ // evidence that already-attributed work finished.
286
+ await this.connection.refresh();
434
287
  if (this.stopped) return;
435
- if (
436
- reply.kind === "error" ||
437
- reply.value.kind !== "workflow" ||
438
- reply.value.response.type !== "run" ||
439
- reply.value.response.run.id !== runId
440
- ) {
441
- if (misses + 1 >= DRAIN_LOOKS)
442
- this.abandonWorkflow(runId, "workflow not readable");
443
- else this.workflows.set(runId, misses + 1);
444
- continue;
288
+ }
289
+ const ends: object[] = [];
290
+ try {
291
+ for (const [runId, misses] of [...this.workflows]) {
292
+ const reply = await client.workbenchRead(
293
+ { kind: "workflow", id: runId },
294
+ signal,
295
+ );
296
+ if (this.stopped) return;
297
+ if (
298
+ reply.kind === "error" ||
299
+ reply.value.kind !== "workflow" ||
300
+ reply.value.response.type !== "run" ||
301
+ reply.value.response.run.id !== runId
302
+ ) {
303
+ if (misses + 1 >= DRAIN_LOOKS)
304
+ this.abandon(runId, "workflow not readable");
305
+ else this.workflows.set(runId, misses + 1);
306
+ continue;
307
+ }
308
+ this.workflows.set(runId, 0);
309
+ const run = reply.value.response.run;
310
+ const open = ["queued", "running"].includes(run.status);
311
+ for (const step of run.steps) this.followStep(run, step, open, ends);
312
+ if (!open) this.workflows.delete(runId);
313
+ }
314
+ for (const child of this.children.values()) {
315
+ if (this.stopped) return;
316
+ const viewed = child.id === this.viewing;
317
+ // One final read for a transcript already open when its end arrived.
318
+ // Never load/retry an ended child's history after this observation.
319
+ if (viewed) {
320
+ if (child.ended || !child.failed)
321
+ await this.refreshTranscript(client, child);
322
+ } else if (
323
+ !child.ended &&
324
+ this.now() - (child.readAt ?? 0) >= WORKFLOW_ACTIVITY_MS
325
+ ) {
326
+ const turn = await this.turn(client, child);
327
+ if (this.stopped) return;
328
+ if (turn) {
329
+ child.working = turnWorking(
330
+ turn,
331
+ !["queued", "running"].includes(turn.status),
332
+ );
333
+ this.activity(child, child.working);
334
+ }
335
+ }
445
336
  }
446
- this.workflows.set(runId, 0);
447
- const run = reply.value.response.run;
448
- const open =
449
- live.has(runId) || ["queued", "running"].includes(run.status);
450
- for (const step of run.steps) this.followStep(run, step, open, ends);
451
- if (!open) this.workflows.delete(runId);
337
+ } finally {
338
+ // A later read failing cannot discard a previously observed outcome.
339
+ // Final streaming snapshots, when available, still precede their end.
340
+ for (const end of ends) this.emit("end", end);
341
+ for (const [id, child] of this.children)
342
+ if (child.ended) this.children.delete(id);
452
343
  }
453
344
  }
345
+
454
346
  private followStep(
455
347
  run: WorkflowRun,
456
348
  step: WorkflowStep,
@@ -460,38 +352,29 @@ class Feed {
460
352
  const kind = WORKFLOW_KINDS[step.kind];
461
353
  if (!step.childRunId || !kind) return;
462
354
  const id = step.childRunId;
463
- // A step still marked running in a finished run did not report its end.
464
355
  const outcome =
465
356
  step.status === "running" ? (open ? null : "unknown") : step.status;
466
- let child = this.state.children.get(id);
357
+ let child = this.children.get(id);
467
358
  if (!child) {
359
+ // Historical steps are not live agents, even inside an active run.
360
+ if (outcome) return;
468
361
  child = {
469
362
  id,
470
363
  label: step.id,
471
- runId: `workflow:${run.id}`,
472
- storeId: "",
473
- seq: "",
474
- lifecycle: outcome ? "settled" : "running",
364
+ runId: run.id,
365
+ stepId: step.id,
475
366
  ended: false,
476
367
  activity: "",
477
368
  sent: 0,
478
- workflow: { runId: run.id, stepId: step.id },
479
369
  };
480
- this.state.children.set(id, child);
481
- this.emit("start", {
482
- id,
483
- label: step.id,
484
- kind,
485
- // A subagent first seen settled ran before this session looked.
486
- startedAt: outcome ? null : this.now(),
487
- });
370
+ this.children.set(id, child);
371
+ this.emit("start", { id, label: step.id, kind, startedAt: this.now() });
488
372
  }
489
373
  if (child.ended) return;
490
374
  if (!outcome) {
491
375
  this.activity(child, child.working ?? `Working · ${run.phase}`);
492
376
  return;
493
377
  }
494
- child.lifecycle = "settled";
495
378
  this.activity(child, outcome);
496
379
  child.ended = true;
497
380
  ends.push({
@@ -499,275 +382,73 @@ class Feed {
499
382
  status:
500
383
  outcome === "completed"
501
384
  ? "done"
502
- : outcome === "canceled"
503
- ? "cancelled"
504
- : "error",
385
+ : outcome === "rejected"
386
+ ? "rejected"
387
+ : outcome === "canceled"
388
+ ? "cancelled"
389
+ : "error",
505
390
  endedAt: this.now(),
506
- ...(outcome === "completed" || outcome === "canceled"
391
+ ...(outcome === "completed" ||
392
+ outcome === "canceled" ||
393
+ outcome === "rejected"
507
394
  ? {}
508
395
  : { error: `${child.label} · ${outcome}` }),
509
396
  });
510
397
  }
511
- private abandonWorkflow(runId: string, why: string): void {
398
+ private abandon(runId: string, why: string): void {
512
399
  this.workflows.delete(runId);
513
- for (const child of this.state.children.values()) {
514
- if (child.workflow?.runId !== runId || child.ended) continue;
400
+ this.abandoned.add(runId);
401
+ for (const [id, child] of this.children) {
402
+ if (child.runId !== runId) continue;
515
403
  this.activity(child, "outcome not observed");
516
- child.ended = true;
517
404
  this.emit("end", {
518
- id: child.id,
405
+ id,
519
406
  status: "error",
520
407
  endedAt: this.now(),
521
- error: `${child.label} · outcome not observed here (${why}); ask cadence_status or open the WebUI`,
408
+ error: `${child.label} · outcome not observed here (${why}); see /cadence-history`,
522
409
  });
410
+ this.children.delete(id);
523
411
  }
524
412
  }
525
- /** Reads one workflow step transcript; undefined when it is unreadable. */
526
- private async workflowTurn(
413
+ private activity(child: Child, text: string): void {
414
+ const activity = `${child.label} · ${text}`;
415
+ if (child.ended || activity === child.activity) return;
416
+ child.activity = activity;
417
+ this.emit("activity", { id: child.id, activity });
418
+ }
419
+ private async turn(
527
420
  client: FeedClient,
528
421
  child: Child,
529
422
  ): Promise<ChatTurn | null | undefined> {
530
- const w = child.workflow;
531
- if (!w || typeof client.workbenchRead !== "function") return undefined;
532
- w.readAt = this.now();
423
+ child.readAt = this.now();
533
424
  const reply = await client.workbenchRead(
534
- { kind: "workflow-transcript", id: w.runId, stepId: w.stepId },
425
+ { kind: "workflow-transcript", id: child.runId, stepId: child.stepId },
535
426
  this.abort.signal,
536
427
  );
537
428
  if (
538
429
  reply.kind === "error" ||
539
430
  reply.value.kind !== "workflow-transcript" ||
540
- reply.value.runId !== w.runId ||
541
- reply.value.stepId !== w.stepId
431
+ reply.value.runId !== child.runId ||
432
+ reply.value.stepId !== child.stepId
542
433
  )
543
434
  return undefined;
544
435
  return reply.value.turn;
545
436
  }
546
- private async refreshWorkflowTranscript(
437
+ private async refreshTranscript(
547
438
  client: FeedClient,
548
439
  child: Child,
549
440
  ): Promise<void> {
550
- const w = child.workflow;
551
- if (!w || w.done || child.failedSeq !== undefined) return;
552
- const turn = await this.workflowTurn(client, child);
553
- if (this.stopped) return;
441
+ const turn = await this.turn(client, child);
442
+ if (this.stopped || this.viewing !== child.id) return;
554
443
  if (turn === undefined) {
555
- // Reopening the view retries, like a failed task transcript read.
556
- child.failedSeq = "workflow";
444
+ child.failed = true;
557
445
  return;
558
446
  }
559
447
  if (!turn) return;
560
448
  const finished = !["queued", "running"].includes(turn.status);
561
449
  const built = turnMessages(turn, finished);
562
450
  child.working = turnWorking(turn, finished);
563
- if (!child.ended) this.activity(child, child.working);
564
- for (let i = child.sent; i < built.messages.length; i++)
565
- this.emit("message", { id: child.id, message: built.messages[i] });
566
- child.sent = Math.max(child.sent, built.messages.length);
567
- if (built.partial)
568
- this.emit("message", {
569
- id: child.id,
570
- message: built.partial,
571
- streaming: true,
572
- });
573
- if (finished && child.ended) w.done = true;
574
- }
575
-
576
- /** Announce this episode's children; true while any still looks unsettled. */
577
- private async follow(
578
- client: FeedClient,
579
- snapshot: Snapshot,
580
- runId: string,
581
- ends: object[],
582
- ): Promise<boolean> {
583
- const rows = snapshot.runs.filter(
584
- (r) => r.runId === runId && r.childRunId !== null,
585
- );
586
- // A check has no children: follow it only until its own row settles.
587
- if (!rows.length)
588
- return !snapshot.runs.some(
589
- (r) => r.runId === runId && !r.childRunId && r.lifecycle === "settled",
590
- );
591
- const purposes = await this.purposes(client, snapshot, rows[0]);
592
- let open = false;
593
- for (const row of rows) {
594
- const id = row.childRunId as string;
595
- const settled = row.lifecycle === "settled";
596
- open ||= !settled;
597
- let child = this.state.children.get(id);
598
- if (!child) {
599
- child = {
600
- id,
601
- label: row.assignmentId ?? id,
602
- runId,
603
- storeId: snapshot.storeId,
604
- seq: snapshot.committedSeq,
605
- lifecycle: row.lifecycle,
606
- ended: false,
607
- activity: "",
608
- sent: 0,
609
- };
610
- this.state.children.set(id, child);
611
- this.emit("start", {
612
- id,
613
- label: child.label,
614
- kind: label(purposes.get(row.assignmentId ?? ""), row.admission.kind),
615
- // A child first seen settled ran before this session looked.
616
- startedAt: settled ? null : this.now(),
617
- });
618
- }
619
- child.storeId = snapshot.storeId;
620
- child.seq = snapshot.committedSeq;
621
- child.lifecycle = row.lifecycle;
622
- if (child.ended) continue;
623
- if (settled) {
624
- const outcome = row.outcome ?? "unknown";
625
- // The row keeps its last activity after the end; make it the outcome.
626
- this.activity(child, outcome);
627
- child.ended = true;
628
- ends.push({
629
- id,
630
- status:
631
- outcome === "completed"
632
- ? "done"
633
- : outcome === "canceled"
634
- ? "cancelled"
635
- : "error",
636
- endedAt: this.now(),
637
- ...(outcome === "completed" || outcome === "canceled"
638
- ? {}
639
- : {
640
- error: `${child.label} · ${outcome}${
641
- row.reason ? ` (${row.reason.replaceAll("-", " ")})` : ""
642
- }`,
643
- }),
644
- });
645
- continue;
646
- }
647
- this.activity(
648
- child,
649
- row.lifecycle === "running"
650
- ? (child.working ?? "Working")
651
- : lifecycleText(row),
652
- );
653
- }
654
- return open;
655
- }
656
- /** Stop following these episodes. Their unsettled children end as errors
657
- * that say the outcome was not observed, instead of spinning as running for
658
- * the rest of the session; /cadence-history keeps the actual outcome. */
659
- private abandon(runIds: string[], why: string): void {
660
- for (const runId of runIds) {
661
- this.episodes.delete(runId);
662
- for (const child of this.state.children.values()) {
663
- if (child.runId !== runId || child.ended) continue;
664
- this.activity(child, "outcome not observed");
665
- child.ended = true;
666
- this.emit("end", {
667
- id: child.id,
668
- status: "error",
669
- endedAt: this.now(),
670
- error: `${child.label} · outcome not observed here (${why}); see /cadence-history`,
671
- });
672
- }
673
- }
674
- }
675
- private activity(child: Child, text: string): void {
676
- const activity = `${child.label} · ${text}`;
677
- if (child.ended || activity === child.activity) return;
678
- child.activity = activity;
679
- this.emit("activity", { id: child.id, activity });
680
- }
681
- /** Assignment purposes from the admitted graph, read once per episode. */
682
- private async purposes(
683
- client: FeedClient,
684
- snapshot: Snapshot,
685
- row: RunProjection,
686
- ): Promise<Map<string, string>> {
687
- const cached = this.state.purposes.get(row.runId);
688
- if (cached) return cached;
689
- const purposes = new Map<string, string>();
690
- const graph = row.admission.graph;
691
- if (graph) {
692
- let request: GraphReadRequest = {
693
- storeId: snapshot.storeId,
694
- scope: { kind: "run", id: row.runId },
695
- snapshotSeq: snapshot.committedSeq,
696
- graph,
697
- };
698
- for (let step = 0; step < MAX_DETAIL_STEPS; step++) {
699
- const reply = await client.graph(request, this.abort.signal);
700
- if (reply.kind === "error") break;
701
- if (!("kind" in reply.value)) {
702
- for (const a of reply.value.graph.assignments)
703
- purposes.set(a.id, a.purpose);
704
- break;
705
- }
706
- request = reply.value.next;
707
- }
708
- }
709
- // A failed read falls back to a generic kind rather than rereading.
710
- this.state.purposes.set(row.runId, purposes);
711
- return purposes;
712
- }
713
-
714
- /** Latest tool for running children not shown in a view (that read covers it). */
715
- private async refreshActivity(client: FeedClient): Promise<void> {
716
- for (const child of this.state.children.values()) {
717
- if (child.workflow) {
718
- if (
719
- child.ended ||
720
- child.id === this.state.viewing ||
721
- !this.workflows.has(child.workflow.runId) ||
722
- this.now() - (child.workflow.readAt ?? 0) < WORKFLOW_ACTIVITY_MS
723
- )
724
- continue;
725
- const turn = await this.workflowTurn(client, child);
726
- if (this.stopped || !turn) continue;
727
- child.working = turnWorking(
728
- turn,
729
- !["queued", "running"].includes(turn.status),
730
- );
731
- this.activity(child, child.working);
732
- continue;
733
- }
734
- if (
735
- child.ended ||
736
- child.lifecycle !== "running" ||
737
- child.id === this.state.viewing ||
738
- child.toolsSeq === child.seq ||
739
- // Another session's workspace: not this owner's to read.
740
- !this.episodes.has(child.runId)
741
- )
742
- continue;
743
- const tools = await this.records(client, "tools", child);
744
- if (!tools) continue;
745
- child.toolsSeq = child.seq;
746
- child.working = workingText(tools as Tool[]);
747
- this.activity(child, child.working);
748
- }
749
- }
750
- private async refreshTranscript(client: FeedClient): Promise<void> {
751
- const id = this.state.viewing;
752
- const child = id === undefined ? undefined : this.state.children.get(id);
753
- if (child?.workflow) return this.refreshWorkflowTranscript(client, child);
754
- if (
755
- !child ||
756
- child.transcriptSeq === child.seq ||
757
- child.failedSeq === child.seq
758
- )
759
- return;
760
- const seq = child.seq;
761
- const built = await this.transcript(client, child);
762
- if (this.stopped) return;
763
- if (!built) {
764
- child.failedSeq = seq;
765
- return;
766
- }
767
- child.transcriptSeq = seq;
768
- child.toolsSeq = seq;
769
- child.working = workingText(built.tools);
770
- if (child.lifecycle === "running") this.activity(child, child.working);
451
+ this.activity(child, child.working);
771
452
  for (let i = child.sent; i < built.messages.length; i++)
772
453
  this.emit("message", { id: child.id, message: built.messages[i] });
773
454
  child.sent = Math.max(child.sent, built.messages.length);
@@ -778,166 +459,4 @@ class Feed {
778
459
  streaming: true,
779
460
  });
780
461
  }
781
-
782
- private async records(
783
- client: FeedClient,
784
- reader: "messages" | "tools" | "contents",
785
- child: Child,
786
- ): Promise<HistoryRecord[] | undefined> {
787
- let request: ListRequest = {
788
- reader,
789
- storeId: child.storeId,
790
- scope: { kind: "child", id: child.id },
791
- snapshotSeq: child.seq,
792
- after: null,
793
- limit: LIMITS.maxPageEntries,
794
- };
795
- const records: HistoryRecord[] = [];
796
- for (let page = 0; page < MAX_PAGES; page++) {
797
- const reply = await client[reader](request, this.abort.signal);
798
- if (reply.kind === "error") return undefined;
799
- if (!("kind" in reply.value)) records.push(...reply.value.records);
800
- if (!reply.value.next) return records;
801
- request = reply.value.next;
802
- }
803
- return undefined;
804
- }
805
- /** One retained field's leading text, cached by its immutable reference. */
806
- private async text(
807
- client: FeedClient,
808
- child: Child,
809
- ref: ContentRef,
810
- ): Promise<string | undefined> {
811
- const key = `${ref.recordId}:${ref.version}:${ref.field}:${ref.sha256}`;
812
- const hit = this.state.texts.get(key);
813
- if (hit !== undefined) return hit;
814
- let cursor: ReadCursor | null = {
815
- storeId: child.storeId,
816
- scope: { kind: "child", id: child.id },
817
- snapshotSeq: child.seq,
818
- query: null,
819
- recordId: ref.recordId,
820
- recordVersion: ref.version,
821
- field: ref.field,
822
- offset: 0,
823
- };
824
- let text = "";
825
- for (let step = 0; cursor && step < MAX_DETAIL_STEPS; step++) {
826
- const reply = await client.detail(cursor, this.abort.signal);
827
- if (reply.kind === "error") return undefined;
828
- if (!("kind" in reply.value)) text += reply.value.text;
829
- cursor = reply.value.next;
830
- if (text.length >= TEXT_CAP) break;
831
- }
832
- // One detail page can exceed the cap on its own, with no cursor left.
833
- if (cursor || text.length > TEXT_CAP)
834
- text = `${text.slice(0, TEXT_CAP)}\n… (truncated; the full text is in /cadence-history)`;
835
- this.state.remember(key, text);
836
- return text;
837
- }
838
- private async joined(
839
- client: FeedClient,
840
- child: Child,
841
- blocks: Block[] | undefined,
842
- ): Promise<string | undefined> {
843
- const parts: string[] = [];
844
- for (const block of [...(blocks ?? [])].sort((a, b) => a.index - b.index)) {
845
- const text = await this.text(client, child, block.ref);
846
- if (text === undefined) return undefined;
847
- parts.push(text);
848
- }
849
- return parts.join("\n");
850
- }
851
- /** The child's retained messages in Pi's message shapes: user prompt,
852
- * assistant text with its tool calls, and tool results. A partial message
853
- * ends the list as a streaming snapshot. */
854
- private async transcript(
855
- client: FeedClient,
856
- child: Child,
857
- ): Promise<Built | undefined> {
858
- const messages = await this.records(client, "messages", child);
859
- const tools = (await this.records(client, "tools", child)) as
860
- | Tool[]
861
- | undefined;
862
- const contents = await this.records(client, "contents", child);
863
- if (!messages || !tools || !contents) return undefined;
864
- const args = new Map<string, ContentRef>(),
865
- results = new Map<string, Block[]>(),
866
- finals = new Map<string, Block[]>(),
867
- streams = new Map<string, Block[]>();
868
- const push = (map: Map<string, Block[]>, key: string, block: Block) =>
869
- map.set(key, [...(map.get(key) ?? []), block]);
870
- for (const r of contents) {
871
- if (r.kind !== "content") continue;
872
- const owner = r.descriptor.owner;
873
- if (owner.kind === "tool") {
874
- if (
875
- owner.stage === "execution-arguments" ||
876
- (owner.stage === "arguments-final" && !args.has(owner.callId))
877
- )
878
- args.set(owner.callId, r.content);
879
- else if (owner.stage === "result")
880
- push(results, owner.callId, { index: owner.index, ref: r.content });
881
- } else if (owner.kind === "message")
882
- push(owner.stage === "final" ? finals : streams, owner.messageId, {
883
- index: owner.index,
884
- ref: r.content,
885
- });
886
- }
887
- const calls = new Map<string, Tool[]>(),
888
- byId = new Map<string, Tool>();
889
- for (const tool of tools) {
890
- byId.set(tool.owner.entity.id, tool);
891
- const message = tool.declaration?.messageId;
892
- if (message) calls.set(message, [...(calls.get(message) ?? []), tool]);
893
- }
894
- const built: Built = { messages: [], tools };
895
- for (const m of messages) {
896
- if (m.kind !== "message") continue;
897
- const id = m.owner.entity.id;
898
- // Only assistant messages carry a derived final text; a user prompt
899
- // keeps its final blocks, a partial message its stream blocks.
900
- const blocks =
901
- m.role === "tool-result" && m.resultCallId
902
- ? results.get(m.resultCallId)
903
- : (finals.get(id) ?? streams.get(id));
904
- const text = m.finalText
905
- ? await this.text(client, child, m.finalText)
906
- : await this.joined(client, child, blocks);
907
- if (text === undefined) return undefined;
908
- let message: object;
909
- if (m.role === "user")
910
- message = { role: "user", content: [{ type: "text", text }] };
911
- else if (m.role === "assistant") {
912
- const content: object[] = text ? [{ type: "text", text }] : [];
913
- for (const tool of calls.get(id) ?? []) {
914
- const ref = args.get(tool.owner.entity.id);
915
- const raw = ref ? await this.text(client, child, ref) : undefined;
916
- if (ref && raw === undefined) return undefined;
917
- content.push({
918
- type: "toolCall",
919
- id: tool.owner.entity.id,
920
- name: tool.name,
921
- arguments: parseArgs(raw),
922
- });
923
- }
924
- message = { role: "assistant", content };
925
- } else {
926
- const tool = m.resultCallId ? byId.get(m.resultCallId) : undefined;
927
- message = {
928
- role: "toolResult",
929
- toolCallId: m.resultCallId ?? "",
930
- toolName: tool?.name ?? "tool",
931
- content: [{ type: "text", text }],
932
- isError: tool?.result?.isError === true,
933
- };
934
- }
935
- if (m.state !== "final") {
936
- built.partial = message;
937
- break;
938
- }
939
- built.messages.push(message);
940
- }
941
- return built;
942
- }
943
462
  }