@loka1/pi-orchestra 0.0.0-stage → 0.6.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.
@@ -0,0 +1,226 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <style>
6
+ :root {
7
+ --bg: #0b0e14;
8
+ --panel: #11151d;
9
+ --text: #cdd6e4;
10
+ --dim: #6b7688;
11
+ --accent: #63c9ff;
12
+ --green: #7ee787;
13
+ --yellow: #e3b341;
14
+ --red: #ff7b72;
15
+ --border: #1f2632;
16
+ }
17
+ * { box-sizing: border-box; }
18
+ body {
19
+ margin: 0;
20
+ background: #05070a;
21
+ font-family: "JetBrains Mono", "Fira Code", "DejaVu Sans Mono", monospace;
22
+ font-size: 14.5px;
23
+ line-height: 1.45;
24
+ color: var(--text);
25
+ display: flex;
26
+ justify-content: center;
27
+ padding: 28px;
28
+ }
29
+ .term {
30
+ width: 1120px;
31
+ background: var(--bg);
32
+ border: 1px solid var(--border);
33
+ border-radius: 10px;
34
+ overflow: hidden;
35
+ box-shadow: 0 24px 80px rgba(0,0,0,.6);
36
+ }
37
+ .bar {
38
+ display: flex;
39
+ gap: 8px;
40
+ align-items: center;
41
+ padding: 9px 14px;
42
+ background: var(--panel);
43
+ border-bottom: 1px solid var(--border);
44
+ color: var(--dim);
45
+ font-size: 12px;
46
+ }
47
+ .dot { width: 10px; height: 10px; border-radius: 50%; }
48
+ .dot.r { background: #ff5f57; } .dot.y { background: #febc2e; } .dot.g { background: #28c840; }
49
+ .title { margin-left: 10px; }
50
+ .body { padding: 16px 20px 6px; }
51
+ .row { display: flex; gap: 10px; }
52
+ .gutter { color: var(--dim); width: 16px; text-align: right; user-select: none; }
53
+ .line { white-space: pre-wrap; }
54
+ .user { color: #e6edf3; }
55
+ .u-mark { color: var(--accent); font-weight: 700; }
56
+ .tool { color: var(--dim); }
57
+ .tool .name { color: var(--accent); }
58
+ .ok { color: var(--green); }
59
+ .dim { color: var(--dim); }
60
+ .yellow { color: var(--yellow); }
61
+ .warn { color: var(--yellow); }
62
+ .red { color: var(--red); }
63
+ .accent { color: var(--accent); }
64
+ .bold { font-weight: 700; }
65
+ .box { border-left: 2px solid #2b3648; padding-left: 12px; margin: 6px 0; }
66
+ .widget {
67
+ margin: 14px 20px 0;
68
+ border: 1px solid var(--border);
69
+ background: var(--panel);
70
+ border-radius: 8px;
71
+ padding: 10px 14px;
72
+ font-size: 13px;
73
+ }
74
+ .widget .head { color: var(--dim); font-size: 11.5px; text-transform: uppercase; letter-spacing: .08em; margin-bottom: 6px; }
75
+ .editor {
76
+ margin: 12px 20px 0;
77
+ border-top: 1px solid var(--border);
78
+ border-bottom: 1px solid var(--border);
79
+ padding: 10px 4px;
80
+ color: var(--dim);
81
+ }
82
+ .footer {
83
+ display: flex;
84
+ gap: 18px;
85
+ padding: 8px 20px 10px;
86
+ color: var(--dim);
87
+ font-size: 12.5px;
88
+ align-items: center;
89
+ }
90
+ .status { color: var(--accent); }
91
+ .badge { color: var(--green); }
92
+ .sep { color: #2b3648; }
93
+ .stack { display: flex; flex-direction: column; gap: 26px; }
94
+ .browse { padding: 14px 20px 16px; font-size: 13.5px; }
95
+ .browse .crumb { display: flex; justify-content: space-between; color: var(--dim); margin-bottom: 8px; }
96
+ .browse .crumb b { color: var(--text); }
97
+ .browse .row { padding: 1px 0; }
98
+ .browse .sel { background: #18202c; border-radius: 4px; }
99
+ .browse .prefix { width: 16px; color: var(--dim); }
100
+ .browse .state { width: 104px; }
101
+ .browse .keys { margin-top: 10px; color: var(--dim); border-top: 1px solid var(--border); padding-top: 8px; }
102
+ .join { padding: 14px 20px 16px; font-size: 13.5px; }
103
+ .join .head { color: var(--text); font-weight: 700; }
104
+ .join .sub { color: var(--dim); }
105
+ .join .bar2 { color: var(--dim); border-bottom: 1px solid var(--border); padding: 6px 0 8px; margin-bottom: 8px; }
106
+ .join .who { color: var(--accent); font-weight: 700; margin-top: 6px; }
107
+ .join .who.worker { color: var(--green); }
108
+ .join .said { padding-left: 14px; }
109
+ .join .tool2 { padding-left: 14px; color: var(--dim); }
110
+ .join .out { padding-left: 26px; color: var(--dim); }
111
+ .join .composer { margin-top: 10px; border-top: 1px solid var(--border); padding-top: 8px; color: var(--dim); }
112
+ .join .keys { margin-top: 6px; color: var(--dim); }
113
+ </style>
114
+ </head>
115
+ <body>
116
+ <div class="stack">
117
+ <div class="term">
118
+ <div class="bar">
119
+ <div class="dot r"></div><div class="dot y"></div><div class="dot g"></div>
120
+ <div class="title">pi — session-store-refactor — ~/work/session-store</div>
121
+ </div>
122
+
123
+ <div class="body">
124
+ <div class="row"><div class="gutter">›</div><div class="line user"><span class="u-mark">❯</span> Split the session-store refactor across three workers and report back.</div></div>
125
+
126
+ <div class="row"><div class="gutter"></div><div class="line accent bold">● assistant</div></div>
127
+
128
+ <div class="box">
129
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra</span> action=run_create name="session-store" goal="split the storage layer"</div></div>
130
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra</span> action=task_create title="Extract storage interface"</div></div>
131
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra</span> action=task_create title="Port the JSONL backend" deps=[task_7f21c0aa91]</div></div>
132
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra</span> action=task_create title="Add migration tests" deps=[task_2bd90e14c3]</div></div>
133
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra</span> action=worker_start taskId=task_7f21c0aa91</div></div>
134
+ <div class="row"><div class="gutter"></div><div class="line ok">◌ Started worker dispatch_ab12cd34ef (pid 42117) model=claude-sonnet-4-5</div></div>
135
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra</span> action=worker_start taskId=task_2bd90e14c3</div></div>
136
+ <div class="row"><div class="gutter"></div><div class="line ok">◌ Started worker dispatch_9c4e7a10bd (pid 42118) model=claude-sonnet-4-5</div></div>
137
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra_wait</span> timeoutMs=600000</div></div>
138
+ </div>
139
+
140
+ <div class="row"><div class="gutter"></div><div class="line yellow">? Worker dispatch_9c4e7a10bd is blocked on a question</div></div>
141
+ <div class="row"><div class="gutter"></div><div class="line dim"> Should the JSONL backend keep the legacy header byte?</div></div>
142
+ <div class="row"><div class="gutter"></div><div class="line dim"> Answer: orchestra_answer questionId=q_4f8ab21c answer="…"</div></div>
143
+
144
+ <div class="row"><div class="gutter"></div><div class="line tool"><span class="name">orchestra_answer</span> questionId=q_4f8ab21c answer="No — version the header, migrate on read."</div></div>
145
+
146
+ <div class="row"><div class="gutter"></div><div class="line">✓ Worker dispatch_ab12cd34ef (worker) settled — Extract storage interface</div></div>
147
+ <div class="row"><div class="gutter"></div><div class="line dim"> Usage: 11 turns · 24 tools · ↑182k ↓9.4k · $0.42</div></div>
148
+ <div class="row"><div class="gutter"></div><div class="line"> Extracted SessionStore/JsonlStore, all 214 tests pass. `npm test` → 214 passing.</div></div>
149
+ </div>
150
+
151
+ <div class="widget">
152
+ <div class="line dim">session-store (run_5e0c11ab77) tasks 6 · workers 5</div>
153
+ <div class="line"><span class="yellow">?</span> <span class="yellow">question 12s</span> Ask whether the legacy header byte is versioned</div>
154
+ <div class="line"><span class="accent">●</span> <span class="accent">running 3m </span> Port the JSONL backend</div>
155
+ <div class="line"><span class="red">⏱</span> <span class="red">timeout 15m</span> Extract storage interface</div>
156
+ <div class="line"><span class="red">✗</span> <span class="red">failed </span> Add migration tests</div>
157
+ <div class="line"><span class="dim">◌</span> <span class="dim">ready </span> Compare page</div>
158
+ <div class="line dim">… +2 more · ✓ 3 settled · ⏱ 1 timed out · ⚠ 1 stalled — /orchestra browse</div>
159
+ <div class="line dim">18 turns · 39 tools · ↑312k ↓17.8k · $0.71</div>
160
+ </div>
161
+
162
+ <div class="editor">❯ send the reviewer after the migration tests land<span class="dim">█</span></div>
163
+
164
+ <div class="footer">
165
+ <span class="status">orchestra: 1 running · 1 settled</span>
166
+ <span class="sep">│</span>
167
+ <span>claude-sonnet-4-5</span>
168
+ <span class="sep">│</span>
169
+ <span class="badge">~/work/session-store</span>
170
+ <span class="sep">│</span>
171
+ <span>42% ctx</span>
172
+ </div>
173
+ </div>
174
+
175
+ <div class="term">
176
+ <div class="bar">
177
+ <div class="dot r"></div><div class="dot y"></div><div class="dot g"></div>
178
+ <div class="title">pi — /orchestra browse — ~/work/session-store</div>
179
+ </div>
180
+ <div class="browse">
181
+ <div class="row"><div class="line bold">orchestra — session-store (run_5e0c11ab77)</div></div>
182
+ <div class="crumb"><div><b>tasks</b> · workers · runs</div><div>/ search</div></div>
183
+ <div class="row"><div class="prefix"> </div><div class="state yellow">? question 12s</div><div class="line">Ask whether the legacy header byte is versioned</div></div>
184
+ <div class="row sel"><div class="prefix">→</div><div class="state accent">● running 3m</div><div class="line">Port the JSONL backend <span class="dim">· 9c4e7a10bd · worker · 4 turns · $0.07</span></div></div>
185
+ <div class="row"><div class="prefix">▣</div><div class="state warn">⚠ stalled 12m</div><div class="line">Compare page <span class="dim">· 7fa10c22de · worker · waiting on npm test</span></div></div>
186
+ <div class="row"><div class="prefix"> </div><div class="state red">⏱ timeout 15m</div><div class="line">Extract storage interface <span class="dim">· ab12cd34ef · worker · 11 turns</span></div></div>
187
+ <div class="row"><div class="prefix"> </div><div class="state red">✗ failed</div><div class="line">Add migration tests <span class="dim">· 2bd90e14c3 · worker · 3 turns</span></div></div>
188
+ <div class="row"><div class="prefix"> </div><div class="state dim">◌ ready</div><div class="line">Budget the review pass</div></div>
189
+ <div class="row"><div class="prefix"> </div><div class="state dim">· pending</div><div class="line">Ship the changelog <span class="dim">· after 2bd90e14c3</span></div></div>
190
+ <div class="row"><div class="prefix"> </div><div class="state ok">✓ done</div><div class="line">Docs for the storage interface</div></div>
191
+ <div class="keys">↑↓ · ⏎ · j join · d log · D diff · space mark(1) · x stop · r retry · c copy · s/t · tab · q</div>
192
+ </div>
193
+ </div>
194
+
195
+ <div class="term">
196
+ <div class="bar">
197
+ <div class="dot r"></div><div class="dot y"></div><div class="dot g"></div>
198
+ <div class="title">pi — /orchestra join 9c4e7a10bd — ~/work/session-store</div>
199
+ </div>
200
+ <div class="join">
201
+ <div class="row"><div class="line head">⤷ joined 9c4e7a10bd · worker · running</div></div>
202
+ <div class="row"><div class="line sub"><span class="accent">● running 3m</span> · Port the JSONL backend</div></div>
203
+ <div class="row"><div class="line sub">claude-sonnet-4-5 · 4 turns · 12 tools · $0.07 of $2.00</div></div>
204
+ <div class="bar2">12-31/52 · live</div>
205
+
206
+ <div class="tool2"><span class="dim">— worker started —</span></div>
207
+ <div class="who">▶ you</div>
208
+ <div class="said">Port the JSONL backend to the new SessionStore. Keep the on-disk header format, add migration tests, run the suite.</div>
209
+
210
+ <div class="who worker">◆ worker</div>
211
+ <div class="said">Reading the store and the header codec before touching anything.</div>
212
+ <div class="tool2">→ <b>read</b> src/store.ts</div>
213
+ <div class="out">export interface Store { read(key: string): Promise&lt;Row | null&gt; }</div>
214
+ <div class="tool2">→ <b>bash</b> npm test -- jsonl</div>
215
+ <div class="out">42 passing · 0 failing</div>
216
+
217
+ <div class="who worker">◆ worker</div>
218
+ <div class="said">The header byte is legacy and unversioned. I'll add a version byte and migrate on read — that keeps old files loadable. Proceeding.</div>
219
+
220
+ <div class="composer">❯ keep the legacy reader behind a flag so we can roll back<span class="dim">█</span></div>
221
+ <div class="keys">enter send · ctrl+e editor · ctrl+t think · ctrl+o tools · ctrl+g main · esc orchestra</div>
222
+ </div>
223
+ </div>
224
+ </div>
225
+ </body>
226
+ </html>
Binary file
@@ -0,0 +1,35 @@
1
+ {
2
+ "maxConcurrency": 4,
3
+ "defaultAgent": "worker",
4
+ "inheritModel": true,
5
+ "timeoutMs": 900000,
6
+ "timeoutMode": "total",
7
+ "keepOpen": true,
8
+ "notifyOnSettle": true,
9
+ "widgetMaxLines": 8,
10
+ "widgetShowSettled": false,
11
+ "widget": "auto",
12
+ "staleRunHours": 12,
13
+ "providerExtensions": [],
14
+ "sessionMode": "session",
15
+ "budgetUsdPerWorker": 2,
16
+ "budgetUsdPerRun": 10,
17
+ "budgetMsPerWorker": 1200000,
18
+ "budgetGraceMs": 60000,
19
+ "stallMs": 600000,
20
+ "stallAction": "notify",
21
+ "budgetAction": "ask",
22
+ "retries": 2,
23
+ "retryBackoffMs": 5000,
24
+ "agents": {
25
+ "reviewer": {
26
+ "model": "claude-sonnet-4-5",
27
+ "thinking": "high",
28
+ "tools": ["read", "grep", "find", "ls", "bash"]
29
+ },
30
+ "scout": {
31
+ "model": "claude-haiku-4-5",
32
+ "tools": ["read", "grep", "find", "ls"]
33
+ }
34
+ }
35
+ }
@@ -0,0 +1,11 @@
1
+ # Review squad
2
+ goal: Land a change, then have an independent reviewer check it before it is called done.
3
+
4
+ ## Implement the change
5
+ agent: worker
6
+ spec: Read the task in the prompt, implement it on the current branch, and run the project's checks. Report the files you touched, the commands you ran and their output, and anything you could not finish.
7
+
8
+ ## Review the change
9
+ agent: reviewer
10
+ deps: Implement the change
11
+ spec: Review the working tree as an independent reviewer. Read the diff, look for correctness, regressions and missing tests, and order your findings by severity. End with a verdict: SHIP, SHIP WITH NITS or BLOCK. Do not edit files.
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Agent discovery.
3
+ *
4
+ * Same convention as pi's built-in `subagent` example: markdown files with YAML
5
+ * frontmatter under `~/.pi/agent/agents/` and (trusted) `.pi/agents/`.
6
+ *
7
+ * ---
8
+ * name: worker
9
+ * description: General purpose implementation agent
10
+ * tools: read, grep, find, ls, bash, edit, write
11
+ * model: claude-sonnet-4-5
12
+ * provider: anthropic
13
+ * thinking: medium
14
+ * ---
15
+ * System prompt...
16
+ */
17
+
18
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
19
+ import { homedir } from "node:os";
20
+ import { join, resolve } from "node:path";
21
+
22
+ export type AgentScope = "user" | "project" | "both";
23
+
24
+ export interface AgentConfig {
25
+ name: string;
26
+ description: string;
27
+ systemPrompt: string;
28
+ tools?: string[];
29
+ model?: string;
30
+ provider?: string;
31
+ thinking?: string;
32
+ path: string;
33
+ source: "user" | "project";
34
+ }
35
+
36
+ function parseFrontmatter(raw: string): { frontmatter: Record<string, string>; body: string } {
37
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
38
+ if (!match) return { frontmatter: {}, body: raw };
39
+ const frontmatter: Record<string, string> = {};
40
+ for (const line of (match[1] ?? "").split(/\r?\n/)) {
41
+ const idx = line.indexOf(":");
42
+ if (idx === -1) continue;
43
+ const key = line.slice(0, idx).trim();
44
+ let value = line.slice(idx + 1).trim();
45
+ if (
46
+ (value.startsWith('"') && value.endsWith('"')) ||
47
+ (value.startsWith("'") && value.endsWith("'"))
48
+ ) {
49
+ value = value.slice(1, -1);
50
+ }
51
+ if (key) frontmatter[key] = value;
52
+ }
53
+ return { frontmatter, body: match[2] ?? "" };
54
+ }
55
+
56
+ function readAgentsIn(dir: string, source: "user" | "project"): AgentConfig[] {
57
+ if (!existsSync(dir)) return [];
58
+ const agents: AgentConfig[] = [];
59
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
60
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
61
+ const filePath = join(dir, entry.name);
62
+ let raw: string;
63
+ try {
64
+ raw = readFileSync(filePath, "utf8");
65
+ } catch {
66
+ continue;
67
+ }
68
+ const { frontmatter, body } = parseFrontmatter(raw);
69
+ const name = (frontmatter.name || entry.name.replace(/\.md$/, "")).trim();
70
+ if (!name) continue;
71
+ const tools = (frontmatter.tools ?? "")
72
+ .split(",")
73
+ .map((tool) => tool.trim())
74
+ .filter(Boolean);
75
+ agents.push({
76
+ name,
77
+ description: (frontmatter.description ?? "").trim(),
78
+ systemPrompt: body.trim(),
79
+ tools: tools.length > 0 ? tools : undefined,
80
+ model: frontmatter.model?.trim() || undefined,
81
+ provider: frontmatter.provider?.trim() || undefined,
82
+ thinking: frontmatter.thinking?.trim() || undefined,
83
+ path: filePath,
84
+ source,
85
+ });
86
+ }
87
+ return agents;
88
+ }
89
+
90
+ /** User agents win over project agents only when scopes do not overlap; project overrides by name. */
91
+ export function discoverAgents(cwd: string, scope: AgentScope = "both"): AgentConfig[] {
92
+ const byName = new Map<string, AgentConfig>();
93
+
94
+ if (scope === "user" || scope === "both") {
95
+ for (const agent of readAgentsIn(join(homedir(), ".pi", "agent", "agents"), "user")) {
96
+ byName.set(agent.name, agent);
97
+ }
98
+ }
99
+ if (scope === "project" || scope === "both") {
100
+ for (const agent of readAgentsIn(join(resolve(cwd), ".pi", "agents"), "project")) {
101
+ byName.set(agent.name, agent);
102
+ }
103
+ }
104
+
105
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
106
+ }
107
+
108
+ export function findAgent(cwd: string, name: string, scope: AgentScope = "both"): AgentConfig | undefined {
109
+ return discoverAgents(cwd, scope).find((agent) => agent.name === name);
110
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Worker conversation blocks.
3
+ *
4
+ * The JSONL event stream is fine for a transcript, but joining a worker means
5
+ * reading a conversation: who said what, which tool ran, what came back. This
6
+ * module turns raw events into those blocks once, so the joined view, the log
7
+ * pager and the text output all render the same thing.
8
+ */
9
+
10
+ import { toolArgsSummary } from "./log.ts";
11
+
12
+ export type ChatBlockKind = "user" | "assistant" | "thinking" | "tool" | "result" | "error" | "start" | "settle" | "note";
13
+
14
+ export interface ChatBlock {
15
+ kind: ChatBlockKind;
16
+ text: string;
17
+ /** Tool name, for `kind: "tool"`. */
18
+ name?: string;
19
+ /** Tool result that failed. */
20
+ isError?: boolean;
21
+ }
22
+
23
+ function blockText(content: unknown): string {
24
+ if (typeof content === "string") return content;
25
+ if (!Array.isArray(content)) return "";
26
+ const parts: string[] = [];
27
+ for (const block of content) {
28
+ if (!block || typeof block !== "object") continue;
29
+ const typed = block as { type?: string; text?: string };
30
+ if (typed.type === "text" && typeof typed.text === "string") parts.push(typed.text);
31
+ }
32
+ return parts.join("\n").trim();
33
+ }
34
+
35
+ /**
36
+ * The dispatch preamble is long boilerplate; in a joined chat only its brief
37
+ * matters, so keep the task/continuation section and drop the rules.
38
+ */
39
+ function condensePreamble(text: string): string {
40
+ if (!text.includes("You are worker ")) return text;
41
+ for (const heading of ["## Task", "## Continue with"]) {
42
+ const start = text.indexOf(heading);
43
+ if (start === -1) continue;
44
+ const body = text.slice(start + heading.length);
45
+ const end = body.indexOf("\n## ");
46
+ const section = (end === -1 ? body : body.slice(0, end)).trim();
47
+ if (section) return section;
48
+ }
49
+ return text;
50
+ }
51
+
52
+ /** Text blocks and thinking blocks of one assistant message, in order. */
53
+ function assistantBlocks(content: unknown): ChatBlock[] {
54
+ if (!Array.isArray(content)) {
55
+ const text = blockText(content);
56
+ return text ? [{ kind: "assistant", text }] : [];
57
+ }
58
+ const blocks: ChatBlock[] = [];
59
+ for (const block of content) {
60
+ if (!block || typeof block !== "object") continue;
61
+ const typed = block as { type?: string; text?: string; thinking?: string };
62
+ if (typed.type === "thinking" && typeof typed.thinking === "string" && typed.thinking.trim()) {
63
+ blocks.push({ kind: "thinking", text: typed.thinking.trim() });
64
+ } else if (typed.type === "text" && typeof typed.text === "string" && typed.text.trim()) {
65
+ blocks.push({ kind: "assistant", text: typed.text.trim() });
66
+ }
67
+ }
68
+ return blocks;
69
+ }
70
+
71
+ /** Map one RPC event to zero or more conversation blocks. */
72
+ export function chatBlockFromEvent(record: Record<string, unknown>): ChatBlock[] {
73
+ switch (record.type) {
74
+ case "agent_start":
75
+ return [{ kind: "start", text: "worker started" }];
76
+ case "agent_settled":
77
+ return [{ kind: "settle", text: record.aborted === true ? "settled (aborted)" : "worker settled" }];
78
+ case "tool_execution_start": {
79
+ const args = record.args as Record<string, unknown> | undefined;
80
+ return [
81
+ {
82
+ kind: "tool",
83
+ name: String(record.toolName ?? "tool"),
84
+ text: toolArgsSummary(args).trim(),
85
+ },
86
+ ];
87
+ }
88
+ case "tool_execution_end": {
89
+ const text = blockText((record.result as { content?: unknown } | undefined)?.content);
90
+ return [
91
+ {
92
+ kind: "result",
93
+ text: text || (record.isError === true ? "(tool failed)" : "(no output)"),
94
+ isError: record.isError === true,
95
+ },
96
+ ];
97
+ }
98
+ case "message_end": {
99
+ const message = record.message as { role?: string; content?: unknown } | undefined;
100
+ if (!message) return [];
101
+ if (message.role === "assistant") return assistantBlocks(message.content);
102
+ if (message.role === "user") {
103
+ const text = blockText(message.content);
104
+ return text ? [{ kind: "user", text: condensePreamble(text) }] : [];
105
+ }
106
+ // Tool results are already covered by tool_execution_end.
107
+ return [];
108
+ }
109
+ case "error":
110
+ case "agent_error": {
111
+ const text = String(record.message ?? record.error ?? "worker error");
112
+ return [{ kind: "error", text }];
113
+ }
114
+ default:
115
+ return [];
116
+ }
117
+ }
118
+
119
+ /** Conversation for a whole event stream, dropping the empty noise. */
120
+ export function chatBlocks(events: Array<Record<string, unknown>>): ChatBlock[] {
121
+ const blocks: ChatBlock[] = [];
122
+ for (const event of events) {
123
+ for (const block of chatBlockFromEvent(event)) {
124
+ const previous = blocks[blocks.length - 1];
125
+ // Consecutive assistant paragraphs from the same message read as one block.
126
+ if (block.kind === "assistant" && previous?.kind === "assistant") {
127
+ previous.text = `${previous.text}\n\n${block.text}`;
128
+ continue;
129
+ }
130
+ blocks.push(block);
131
+ }
132
+ }
133
+ return blocks;
134
+ }
135
+
136
+ /** Plain-text form, used by `action=chat`, tests and non-TUI modes. */
137
+ export function chatText(blocks: ChatBlock[], options: { thinking?: boolean; tools?: boolean } = {}): string {
138
+ const lines: string[] = [];
139
+ const showThinking = options.thinking ?? false;
140
+ const showTools = options.tools ?? true;
141
+ for (const block of blocks) {
142
+ switch (block.kind) {
143
+ case "user":
144
+ lines.push(`▶ you: ${block.text}`, "");
145
+ break;
146
+ case "assistant":
147
+ lines.push(`◆ worker: ${block.text}`, "");
148
+ break;
149
+ case "thinking":
150
+ if (showThinking) lines.push(` (thinking) ${block.text}`, "");
151
+ break;
152
+ case "tool":
153
+ if (showTools) lines.push(` → ${block.name ?? "tool"} ${block.text}`.trimEnd());
154
+ break;
155
+ case "result":
156
+ if (showTools) lines.push(` ${block.isError ? "✗ " : ""}${block.text.split("\n")[0]}`, "");
157
+ break;
158
+ case "error":
159
+ lines.push(`✗ ${block.text}`, "");
160
+ break;
161
+ case "start":
162
+ case "settle":
163
+ lines.push(`— ${block.text} —`, "");
164
+ break;
165
+ case "note":
166
+ lines.push(`· ${block.text}`, "");
167
+ break;
168
+ }
169
+ }
170
+ return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim();
171
+ }