@abelxiaoxing/cadence 2.0.21 → 2.0.23

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,12 +1,19 @@
1
1
  /** Cadence service children on the background-agent panel. Observation only:
2
2
  * a Pi TUI session attaches to the owner already running for its workspace
3
- * (never starting one), polls the active roster and task snapshots, and
4
- * announces each child run on Pi's `subagent:*` bus. Reads go through the
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
5
7
  * typed ServiceClient; nothing here starts, cancels, retries or keeps work
6
8
  * alive, and leaving the session only detaches. */
7
9
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
10
  import { SUBAGENT_EVENTS, SUBAGENT_VIEW } from "./agent-panel-model.ts";
9
11
  import { departure, NativeConnection } from "./native-client.ts";
12
+ import type { ChatTurn } from "./service/contracts/workbench.ts";
13
+ import type {
14
+ WorkflowRun,
15
+ WorkflowStep,
16
+ } from "./service/contracts/workflow.ts";
10
17
  import type { ServiceClient } from "./service-client.ts";
11
18
  import {
12
19
  type ContentRef,
@@ -25,6 +32,8 @@ export interface FeedConnection {
25
32
  refresh(): Promise<unknown>;
26
33
  compatible(): boolean;
27
34
  detach(): Promise<void>;
35
+ /** Drop an attachment whose owner the registry proves gone or replaced. */
36
+ forgetSuperseded?(cwd: string): boolean;
28
37
  }
29
38
  /** Readonly ServiceClient reads only: no command, preflight or Cancel. */
30
39
  export type FeedClient = Pick<
@@ -36,6 +45,7 @@ export type FeedClient = Pick<
36
45
  | "tools"
37
46
  | "contents"
38
47
  | "detail"
48
+ | "workbenchRead"
39
49
  >;
40
50
  export interface CadenceFeedOptions {
41
51
  connection?: () => FeedConnection;
@@ -56,7 +66,7 @@ export const FEED_TIMING: FeedTiming = {
56
66
  idleMs: LIMITS.heartbeatMs,
57
67
  retryMs: 15_000,
58
68
  };
59
- /** Retained reads are paged; a child larger than this stays in /cadence History. */
69
+ /** Retained reads are paged; a child larger than this stays in /cadence-history. */
60
70
  const MAX_PAGES = 50;
61
71
  const MAX_DETAIL_STEPS = 8;
62
72
  /** Characters of one field shown in the panel; the rest stays retained. */
@@ -64,6 +74,14 @@ const TEXT_CAP = 64 * 1024;
64
74
  const CACHE_CHARS = 16 * 1024 * 1024;
65
75
  /** Snapshots after an episode drained, while its children still look unsettled. */
66
76
  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. */
79
+ const WORKFLOW_ACTIVITY_MS = 10_000;
80
+ const WORKFLOW_KINDS: Partial<Record<WorkflowStep["kind"], string>> = {
81
+ research: "Research",
82
+ implementation: "Implementation",
83
+ review: "Review",
84
+ };
67
85
 
68
86
  type Child = {
69
87
  id: string;
@@ -84,6 +102,14 @@ type Child = {
84
102
  failedSeq?: string;
85
103
  /** Final transcript messages already announced. */
86
104
  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
+ };
87
113
  };
88
114
  type Tool = Extract<HistoryRecord, { kind: "tool" }>;
89
115
  type Block = { index: number; ref: ContentRef };
@@ -176,6 +202,74 @@ function parseArgs(text: string | undefined): object {
176
202
  return {};
177
203
  }
178
204
  }
205
+ const capped = (text: string) =>
206
+ text.length > TEXT_CAP
207
+ ? `${text.slice(0, TEXT_CAP)}\n… (truncated; the project owner retains the full text)`
208
+ : text;
209
+ /** A workflow step transcript in Pi's message shapes. Each assistant message
210
+ * carries its tool calls, followed by their results; while the turn runs, its
211
+ * last group may still grow and is a streaming snapshot. */
212
+ export function turnMessages(
213
+ turn: ChatTurn,
214
+ finished: boolean,
215
+ ): { messages: object[]; partial?: object } {
216
+ const messages: object[] = [];
217
+ let group:
218
+ | { assistant: { role: string; content: object[] }; results: object[] }
219
+ | undefined;
220
+ const close = () => {
221
+ if (group) messages.push(group.assistant, ...group.results);
222
+ group = undefined;
223
+ };
224
+ for (const item of turn.items) {
225
+ if (item.role === "user") {
226
+ close();
227
+ messages.push({
228
+ role: "user",
229
+ content: [{ type: "text", text: capped(item.text) }],
230
+ });
231
+ } else if (item.role === "assistant") {
232
+ close();
233
+ group = {
234
+ assistant: {
235
+ role: "assistant",
236
+ content: item.text ? [{ type: "text", text: capped(item.text) }] : [],
237
+ },
238
+ results: [],
239
+ };
240
+ } else {
241
+ group ??= { assistant: { role: "assistant", content: [] }, results: [] };
242
+ const name = item.name || "tool";
243
+ group.assistant.content.push({
244
+ type: "toolCall",
245
+ id: item.id,
246
+ name,
247
+ arguments: parseArgs(item.args),
248
+ });
249
+ group.results.push({
250
+ role: "toolResult",
251
+ toolCallId: item.id,
252
+ toolName: name,
253
+ content: [{ type: "text", text: capped(item.text) }],
254
+ isError: item.error,
255
+ });
256
+ }
257
+ }
258
+ if (finished || !group) {
259
+ close();
260
+ return { messages };
261
+ }
262
+ return { messages, partial: group.assistant };
263
+ }
264
+ function turnWorking(turn: ChatTurn, finished: boolean): string {
265
+ const tools = turn.items.filter((i) => i.role === "tool");
266
+ const last = tools.at(-1);
267
+ if (!last) return "Working";
268
+ if (!finished && turn.items.at(-1) === last && !last.text && !last.error)
269
+ return `Running ${last.name || "tool"}`;
270
+ const n = tools.length;
271
+ return `Working · ${n} tool call${n === 1 ? "" : "s"} (last: ${last.name || "tool"})`;
272
+ }
179
273
 
180
274
  class Feed {
181
275
  private client: FeedClient | undefined;
@@ -192,6 +286,9 @@ class Feed {
192
286
  string,
193
287
  { taskId: string; drained: number }
194
288
  >();
289
+ /** Conversation workflow → consecutive unreadable looks, followed until
290
+ * its run is observed finished. */
291
+ private readonly workflows = new Map<string, number>();
195
292
  constructor(
196
293
  private readonly pi: ExtensionAPI,
197
294
  private readonly cwd: string,
@@ -245,13 +342,19 @@ class Feed {
245
342
  next = await this.observe(this.client);
246
343
  } catch {
247
344
  // Absent, stopped, restarted or incompatible owner: detach and look
248
- // again later. Observation never starts one.
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.
249
348
  this.client = undefined;
250
- await this.connection.detach().catch(() => {});
349
+ if (!this.connection.forgetSuperseded?.(this.cwd))
350
+ await this.connection.detach().catch(() => {});
251
351
  // Still no compatible owner a whole retry after losing it: the children
252
352
  // followed so far can no longer be observed from this session.
253
- if (attaching)
353
+ if (attaching) {
254
354
  this.abandon([...this.episodes.keys()], "owner unavailable");
355
+ for (const runId of [...this.workflows.keys()])
356
+ this.abandonWorkflow(runId, "owner unavailable");
357
+ }
255
358
  } finally {
256
359
  this.busy = false;
257
360
  }
@@ -291,12 +394,183 @@ class Feed {
291
394
  this.abandon([runId], "no settled row after the run ended");
292
395
  }
293
396
  }
397
+ await this.observeWorkflows(client, ends);
398
+ if (this.stopped) return this.timing.activeMs;
294
399
  await this.refreshActivity(client);
295
400
  await this.refreshTranscript(client);
296
401
  // Ends follow the transcript so its last streaming snapshot is replaced
297
402
  // by the final message rather than kept beside it.
298
403
  for (const end of ends) this.emit("end", end);
299
- return this.episodes.size ? this.timing.activeMs : this.timing.idleMs;
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;
417
+ const signal = this.abort.signal;
418
+ const roster = await client.workbenchRead(
419
+ { kind: "workflow-active" },
420
+ signal,
421
+ );
422
+ 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
+ );
434
+ 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;
445
+ }
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);
452
+ }
453
+ }
454
+ private followStep(
455
+ run: WorkflowRun,
456
+ step: WorkflowStep,
457
+ open: boolean,
458
+ ends: object[],
459
+ ): void {
460
+ const kind = WORKFLOW_KINDS[step.kind];
461
+ if (!step.childRunId || !kind) return;
462
+ const id = step.childRunId;
463
+ // A step still marked running in a finished run did not report its end.
464
+ const outcome =
465
+ step.status === "running" ? (open ? null : "unknown") : step.status;
466
+ let child = this.state.children.get(id);
467
+ if (!child) {
468
+ child = {
469
+ id,
470
+ label: step.id,
471
+ runId: `workflow:${run.id}`,
472
+ storeId: "",
473
+ seq: "",
474
+ lifecycle: outcome ? "settled" : "running",
475
+ ended: false,
476
+ activity: "",
477
+ sent: 0,
478
+ workflow: { runId: run.id, stepId: step.id },
479
+ };
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
+ });
488
+ }
489
+ if (child.ended) return;
490
+ if (!outcome) {
491
+ this.activity(child, child.working ?? `Working · ${run.phase}`);
492
+ return;
493
+ }
494
+ child.lifecycle = "settled";
495
+ this.activity(child, outcome);
496
+ child.ended = true;
497
+ ends.push({
498
+ id,
499
+ status:
500
+ outcome === "completed"
501
+ ? "done"
502
+ : outcome === "canceled"
503
+ ? "cancelled"
504
+ : "error",
505
+ endedAt: this.now(),
506
+ ...(outcome === "completed" || outcome === "canceled"
507
+ ? {}
508
+ : { error: `${child.label} · ${outcome}` }),
509
+ });
510
+ }
511
+ private abandonWorkflow(runId: string, why: string): void {
512
+ this.workflows.delete(runId);
513
+ for (const child of this.state.children.values()) {
514
+ if (child.workflow?.runId !== runId || child.ended) continue;
515
+ this.activity(child, "outcome not observed");
516
+ child.ended = true;
517
+ this.emit("end", {
518
+ id: child.id,
519
+ status: "error",
520
+ endedAt: this.now(),
521
+ error: `${child.label} · outcome not observed here (${why}); ask cadence_status or open the WebUI`,
522
+ });
523
+ }
524
+ }
525
+ /** Reads one workflow step transcript; undefined when it is unreadable. */
526
+ private async workflowTurn(
527
+ client: FeedClient,
528
+ child: Child,
529
+ ): Promise<ChatTurn | null | undefined> {
530
+ const w = child.workflow;
531
+ if (!w || typeof client.workbenchRead !== "function") return undefined;
532
+ w.readAt = this.now();
533
+ const reply = await client.workbenchRead(
534
+ { kind: "workflow-transcript", id: w.runId, stepId: w.stepId },
535
+ this.abort.signal,
536
+ );
537
+ if (
538
+ reply.kind === "error" ||
539
+ reply.value.kind !== "workflow-transcript" ||
540
+ reply.value.runId !== w.runId ||
541
+ reply.value.stepId !== w.stepId
542
+ )
543
+ return undefined;
544
+ return reply.value.turn;
545
+ }
546
+ private async refreshWorkflowTranscript(
547
+ client: FeedClient,
548
+ child: Child,
549
+ ): 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;
554
+ if (turn === undefined) {
555
+ // Reopening the view retries, like a failed task transcript read.
556
+ child.failedSeq = "workflow";
557
+ return;
558
+ }
559
+ if (!turn) return;
560
+ const finished = !["queued", "running"].includes(turn.status);
561
+ const built = turnMessages(turn, finished);
562
+ 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;
300
574
  }
301
575
 
302
576
  /** Announce this episode's children; true while any still looks unsettled. */
@@ -381,7 +655,7 @@ class Feed {
381
655
  }
382
656
  /** Stop following these episodes. Their unsettled children end as errors
383
657
  * that say the outcome was not observed, instead of spinning as running for
384
- * the rest of the session; /cadence History keeps the actual outcome. */
658
+ * the rest of the session; /cadence-history keeps the actual outcome. */
385
659
  private abandon(runIds: string[], why: string): void {
386
660
  for (const runId of runIds) {
387
661
  this.episodes.delete(runId);
@@ -393,7 +667,7 @@ class Feed {
393
667
  id: child.id,
394
668
  status: "error",
395
669
  endedAt: this.now(),
396
- error: `${child.label} · outcome not observed here (${why}); see /cadence History`,
670
+ error: `${child.label} · outcome not observed here (${why}); see /cadence-history`,
397
671
  });
398
672
  }
399
673
  }
@@ -440,6 +714,23 @@ class Feed {
440
714
  /** Latest tool for running children not shown in a view (that read covers it). */
441
715
  private async refreshActivity(client: FeedClient): Promise<void> {
442
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
+ }
443
734
  if (
444
735
  child.ended ||
445
736
  child.lifecycle !== "running" ||
@@ -459,6 +750,7 @@ class Feed {
459
750
  private async refreshTranscript(client: FeedClient): Promise<void> {
460
751
  const id = this.state.viewing;
461
752
  const child = id === undefined ? undefined : this.state.children.get(id);
753
+ if (child?.workflow) return this.refreshWorkflowTranscript(client, child);
462
754
  if (
463
755
  !child ||
464
756
  child.transcriptSeq === child.seq ||
@@ -539,7 +831,7 @@ class Feed {
539
831
  }
540
832
  // One detail page can exceed the cap on its own, with no cursor left.
541
833
  if (cursor || text.length > TEXT_CAP)
542
- text = `${text.slice(0, TEXT_CAP)}\n… (truncated; the full text is in /cadence History)`;
834
+ text = `${text.slice(0, TEXT_CAP)}\n… (truncated; the full text is in /cadence-history)`;
543
835
  this.state.remember(key, text);
544
836
  return text;
545
837
  }
@@ -1,5 +1,5 @@
1
1
  /** Shared conversation policy; clients supply distinct human-consent adapters. */
2
- export const CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits.
2
+ export const CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
3
3
  You are the sole user-facing coordinator. Continue normal conversation, not a task-manager UI. Do not ask the user to manage tasks, IDs, JSON, service ports, Save/Start/check menus or agent assignments.
4
4
  For each new goal: inspect relevant project evidence through cadence_research (up to two independent readonly subagents); read existing AGENTS/docs/.cadence/project.md before proposing conventions. Reuse still-current findings; do not rescan the entire repository or spawn agents merely to fill slots. Aggregate questions yourself. Investigate discoverable facts and ask focused, frequent questions only for unresolved product/technical decisions. Preserve confirmed decisions across turns. Diagnosis/research alone never imply implementation.
5
5
  Once material decisions and acceptance criteria are aligned, use cadence_plan with a readable design, explicit non-goals/decisions, exact file scopes, a finite dependency DAG, real verification commands, worktree prerequisites and a bounded repair budget. Independent writes may run concurrently; shared files need a single owner or dependency. Investigate local tool/dependency prerequisites BEFORE finalizing: isolated worktrees do not inherit ignored node_modules. Setup commands require inclusion in the final approval; never silently install/download/copy dependencies or credentials. local-merge needs an existing Git branch and commit identity; working-copy is explicit direct editing without Git mutation and is serialized.