@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,5 +1,6 @@
1
1
  /** User-owned model preference, never auth, approval or a reusable source-selection ID. */
2
- import { join } from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
3
4
  import { closed } from "./service/contracts/core.ts";
4
5
  import { PrivateFiles } from "./service/private-files.ts";
5
6
  import {
@@ -9,12 +10,32 @@ import {
9
10
  parseWireJson,
10
11
  } from "./service-contract.ts";
11
12
 
13
+ /** Pi follows links in its agent directory (dotfile setups link `~/.pi` or
14
+ * `~/.pi/agent`). Resolve the existing part of that directory as Pi does,
15
+ * then keep the no-follow private walk below it: a linked `cadence` directory
16
+ * or `settings.json`, another owner's directory or a hard link stay refused. */
17
+ function agentNamespace(agentDir: string): string {
18
+ let at = resolve(agentDir);
19
+ const missing: string[] = [];
20
+ for (;;) {
21
+ try {
22
+ return join(realpathSync(at), ...missing.reverse());
23
+ } catch {
24
+ const parent = dirname(at);
25
+ if (parent === at) return resolve(agentDir);
26
+ missing.push(basename(at));
27
+ at = parent;
28
+ }
29
+ }
30
+ }
31
+
12
32
  export class CadencePreferences {
13
33
  readonly path: string;
14
34
  private readonly files: PrivateFiles;
15
35
  constructor(agentDir: string) {
16
- this.path = join(agentDir, "cadence", "settings.json");
17
- this.files = new PrivateFiles(agentDir, false);
36
+ const namespace = agentNamespace(agentDir);
37
+ this.path = join(namespace, "cadence", "settings.json");
38
+ this.files = new PrivateFiles(namespace, false);
18
39
  }
19
40
  read(): ModelSelector | null {
20
41
  const saved = this.files.read(this.path);
@@ -27,16 +48,30 @@ export class CadencePreferences {
27
48
  throw new Error("Unsupported Cadence preferences");
28
49
  return decodeModelSelector(o.model);
29
50
  }
51
+ private encode(model: ModelSelector): string {
52
+ return canonicalJson({
53
+ schema: "cadence-preferences/1",
54
+ model: decodeModelSelector(model),
55
+ });
56
+ }
57
+ /** Implicit remembering: validate an existing user file, including its
58
+ * schema, before replacing it; never silently replace an unreadable one. */
30
59
  save(model: ModelSelector): void {
31
60
  const selected = decodeModelSelector(model);
32
61
  const previous = this.files.read(this.path);
33
- // Validate an existing user file, including its schema, before replacing it.
34
62
  if (previous && canonicalJson(this.read()) === canonicalJson(selected))
35
63
  return;
36
- const bytes = canonicalJson({
37
- schema: "cadence-preferences/1",
38
- model: selected,
39
- });
64
+ const bytes = this.encode(selected);
65
+ if (previous) this.files.replace(this.path, previous, bytes);
66
+ else this.files.create(this.path, bytes);
67
+ }
68
+ /** An explicit user model selection. It atomically replaces a regular file
69
+ * whose contents are corrupt or unsupported, since the user just chose the
70
+ * replacement; unsafe targets such as links are still refused. */
71
+ choose(model: ModelSelector): void {
72
+ const bytes = this.encode(model);
73
+ const previous = this.files.read(this.path);
74
+ if (previous?.bytes.toString("utf8") === bytes) return;
40
75
  if (previous) this.files.replace(this.path, previous, bytes);
41
76
  else this.files.create(this.path, bytes);
42
77
  }
@@ -0,0 +1,16 @@
1
+ /** Small shape predicates shared by filesystem records; no task model. */
2
+ export function object(value: unknown): value is Record<string, unknown> {
3
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4
+ }
5
+ export function boundedString(value: unknown, max: number): value is string {
6
+ return (
7
+ typeof value === "string" &&
8
+ Buffer.byteLength(value) <= max &&
9
+ !value.includes("\0")
10
+ );
11
+ }
12
+ export function validId(value: string): boolean {
13
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
14
+ value,
15
+ );
16
+ }
@@ -0,0 +1,370 @@
1
+ /** Readonly diagnostics. No task creation, plan approval, model choice or execution. */
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ Key,
8
+ matchesKey,
9
+ truncateToWidth,
10
+ wrapTextWithAnsi,
11
+ } from "@earendil-works/pi-tui";
12
+ import {
13
+ autostartHint,
14
+ departure,
15
+ MANAGEMENT_GUIDANCE,
16
+ NativeConnection,
17
+ } from "./native-client.ts";
18
+ import {
19
+ NativeHistory,
20
+ type NativeViews,
21
+ pretty,
22
+ value,
23
+ } from "./native-history.ts";
24
+ import { workflowDetails, workflowHistory } from "./native-workflow-history.ts";
25
+ import { ContractError } from "./service-contract.ts";
26
+ import { diagnosticText } from "./verification-diagnostics.ts";
27
+
28
+ /** One transient raw Enter occurrence, not an approval or model-callable control. */
29
+ export class TerminalEntryLatch {
30
+ constructor(private readonly command = "cadence") {}
31
+ private entry: { text: string; at: number } | undefined;
32
+ private pasting = false;
33
+ clear(): void {
34
+ this.entry = undefined;
35
+ }
36
+ input(
37
+ data: string,
38
+ editor: string,
39
+ eligible: boolean,
40
+ now = Date.now(),
41
+ ): void {
42
+ this.clear();
43
+ if (data.includes("\x1b[200~")) this.pasting = true;
44
+ if (data.includes("\x1b[201~")) {
45
+ this.pasting = false;
46
+ return;
47
+ }
48
+ if (this.pasting || !eligible || !matchesKey(data, Key.enter)) return;
49
+ if (new RegExp(`^/${this.command}(?:[ \\t]+[^\\r\\n]*)?$`).test(editor))
50
+ this.entry = { text: editor, at: now };
51
+ }
52
+ consume(args: string, now = Date.now()): boolean {
53
+ const entry = this.entry;
54
+ this.clear();
55
+ return (
56
+ !!entry &&
57
+ now - entry.at >= 0 &&
58
+ now - entry.at < 1500 &&
59
+ entry.text.replace(new RegExp(`^/${this.command}[ \\t]*`), "") === args
60
+ );
61
+ }
62
+ }
63
+ function eligible(ctx: ExtensionContext): boolean {
64
+ return (
65
+ ctx.mode === "tui" &&
66
+ ctx.hasUI &&
67
+ ctx.isIdle() &&
68
+ !ctx.hasPendingMessages() &&
69
+ ctx.isProjectTrusted()
70
+ );
71
+ }
72
+
73
+ export function registerHistoryShell(pi: ExtensionAPI): void {
74
+ const latch = new TerminalEntryLatch("cadence-history"),
75
+ connection = new NativeConnection();
76
+ let epoch = 0,
77
+ modal = false;
78
+ let unsubscribe: (() => void) | undefined, dismiss: (() => void) | undefined;
79
+ let abort = new AbortController();
80
+ const depart = () => {
81
+ epoch++;
82
+ latch.clear();
83
+ abort.abort();
84
+ dismiss?.();
85
+ // Detach original attachment, not service jobs/provider/auth. Shutdown does
86
+ // not wait for their lifetime. Retained transport blocks uncertain reuse.
87
+ return connection.detach().catch(() => {});
88
+ };
89
+ pi.on("session_start", (_event, ctx) => {
90
+ void depart();
91
+ unsubscribe?.();
92
+ unsubscribe = undefined;
93
+ if (ctx.mode === "tui")
94
+ unsubscribe = ctx.ui.onTerminalInput((data) => {
95
+ latch.input(data, ctx.ui.getEditorText(), !modal && eligible(ctx));
96
+ return undefined;
97
+ });
98
+ });
99
+ pi.on("session_shutdown", () => {
100
+ const leaving = depart();
101
+ unsubscribe?.();
102
+ unsubscribe = undefined;
103
+ return departure(leaving);
104
+ });
105
+ const leave = () => void depart();
106
+ pi.on("session_before_switch", leave);
107
+ pi.on("session_before_fork", leave);
108
+ pi.on("session_before_tree", leave);
109
+ pi.on("session_before_compact", leave);
110
+ pi.on("model_select", leave);
111
+ // Only local dialog input is owned. Detached service work never owns Pi's
112
+ // conversation/tool lifetime or silently cancels it.
113
+ pi.on("input", () => (modal ? { action: "handled" as const } : undefined));
114
+ pi.on("tool_call", () =>
115
+ modal
116
+ ? {
117
+ block: true,
118
+ reason:
119
+ "Cadence native dialog is active; Return detaches accepted work",
120
+ }
121
+ : undefined,
122
+ );
123
+ pi.on("user_bash", () =>
124
+ modal
125
+ ? {
126
+ result: {
127
+ output: "Cadence native dialog is active",
128
+ exitCode: 1,
129
+ cancelled: true,
130
+ truncated: false,
131
+ },
132
+ }
133
+ : undefined,
134
+ );
135
+
136
+ pi.registerCommand("cadence-history", {
137
+ description:
138
+ "Readonly run details and retained history/search/export; never starts a service or work",
139
+ handler: async (args, ctx) => {
140
+ if (
141
+ !latch.consume(args) ||
142
+ modal ||
143
+ !eligible(ctx) ||
144
+ process.env.CADENCE_SUBAGENT_CHILD === "1"
145
+ )
146
+ return;
147
+ modal = true;
148
+ const generation = epoch,
149
+ sessionId = ctx.sessionManager.getSessionId(),
150
+ cwd = ctx.cwd;
151
+ const hostModel = JSON.stringify(ctx.model),
152
+ thinking = ctx.thinkingLevel;
153
+ abort = new AbortController();
154
+ const signal = abort.signal;
155
+ const current = () => {
156
+ if (
157
+ epoch !== generation ||
158
+ signal.aborted ||
159
+ !eligible(ctx) ||
160
+ ctx.cwd !== cwd ||
161
+ ctx.sessionManager.getSessionId() !== sessionId ||
162
+ JSON.stringify(ctx.model) !== hostModel ||
163
+ ctx.thinkingLevel !== thinking
164
+ )
165
+ throw new ContractError("stale");
166
+ };
167
+ const show = async (text: string) => {
168
+ current();
169
+ // Server data already has bounded pages. Sanitize, but never clip a
170
+ // retained page/graph into a purported full view (old 256KiB cap removed).
171
+ const clean = diagnosticText(text, Number.MAX_SAFE_INTEGER);
172
+ await ctx.ui.custom<void>((tui, _theme, _keys, done) => {
173
+ let offset = 0,
174
+ rows: string[] = [],
175
+ wrapped: number | undefined;
176
+ const close = () => done();
177
+ dismiss = close;
178
+ return {
179
+ render(width) {
180
+ // Wrap the whole text once per width; paging only moves the window.
181
+ const columns = Math.max(1, width);
182
+ if (columns !== wrapped) {
183
+ rows = clean
184
+ .split("\n")
185
+ .flatMap((line) => wrapTextWithAnsi(line, columns));
186
+ wrapped = columns;
187
+ }
188
+ const height = Math.max(1, Math.min(24, tui.terminal.rows - 4));
189
+ offset = Math.max(
190
+ 0,
191
+ Math.min(offset, Math.max(0, rows.length - height)),
192
+ );
193
+ return [
194
+ truncateToWidth(
195
+ `Cadence history • ${offset + 1}/${rows.length} • ↑↓ PgUp/PgDn Home/End • Esc return`,
196
+ width,
197
+ ),
198
+ ...rows.slice(offset, offset + height),
199
+ ];
200
+ },
201
+ invalidate() {},
202
+ handleInput(data) {
203
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.enter))
204
+ done();
205
+ else if (matchesKey(data, Key.up)) offset--;
206
+ else if (matchesKey(data, Key.down)) offset++;
207
+ else if (matchesKey(data, Key.pageUp)) offset -= 12;
208
+ else if (matchesKey(data, Key.pageDown)) offset += 12;
209
+ else if (matchesKey(data, Key.home)) offset = 0;
210
+ else if (matchesKey(data, Key.end)) offset = rows.length;
211
+ tui.requestRender();
212
+ },
213
+ dispose() {
214
+ if (dismiss === close) dismiss = undefined;
215
+ },
216
+ };
217
+ });
218
+ current();
219
+ };
220
+ const ui: NativeViews = {
221
+ signal,
222
+ current,
223
+ show,
224
+ async select(title, choices) {
225
+ let page = 0;
226
+ for (;;) {
227
+ current();
228
+ const paged = choices.length > 16;
229
+ const available = paged
230
+ ? choices.slice(page * 10, page * 10 + 10)
231
+ : choices;
232
+ let labels = available.map((c) =>
233
+ diagnosticText(c, Number.MAX_SAFE_INTEGER),
234
+ );
235
+ // Sanitization is presentation, not identity. Distinct choices can
236
+ // redact to identical text; never select the first by accident.
237
+ if (
238
+ new Set(labels).size !== labels.length ||
239
+ labels.some((label) =>
240
+ ["Next options page", "Previous options page"].includes(label),
241
+ )
242
+ )
243
+ labels = labels.map(
244
+ (label, i) => `${page * 10 + i + 1}. ${label}`,
245
+ );
246
+ const next = paged && (page + 1) * 10 < choices.length;
247
+ const r = await ctx.ui.select(
248
+ diagnosticText(
249
+ `${title}${paged ? ` • options page ${page + 1}` : ""}`,
250
+ Number.MAX_SAFE_INTEGER,
251
+ ),
252
+ [
253
+ ...labels,
254
+ ...(next ? ["Next options page"] : []),
255
+ ...(page ? ["Previous options page"] : []),
256
+ ],
257
+ { signal },
258
+ );
259
+ current();
260
+ if (r === "Next options page") {
261
+ page++;
262
+ continue;
263
+ }
264
+ if (r === "Previous options page") {
265
+ page--;
266
+ continue;
267
+ }
268
+ return r === undefined ? undefined : available[labels.indexOf(r)];
269
+ }
270
+ },
271
+ async input(title, prefill) {
272
+ current();
273
+ const r = await ctx.ui.input(title, prefill, { signal });
274
+ current();
275
+ return r;
276
+ },
277
+ async confirm(title, text) {
278
+ current();
279
+ const r = await ctx.ui.confirm(
280
+ title,
281
+ diagnosticText(text, Number.MAX_SAFE_INTEGER),
282
+ { signal },
283
+ );
284
+ current();
285
+ return r;
286
+ },
287
+ notify(text) {
288
+ ctx.ui.notify(diagnosticText(text, Number.MAX_SAFE_INTEGER), "info");
289
+ },
290
+ };
291
+ let attached = false;
292
+ try {
293
+ const client = await connection.attach(cwd);
294
+ current();
295
+ attached = true;
296
+ const session = connection.session;
297
+ if (!session) throw new ContractError("unavailable");
298
+ if (!connection.compatible()) ui.notify(MANAGEMENT_GUIDANCE);
299
+ const workspace = value(await client.workspace(signal));
300
+ current();
301
+ if (
302
+ workspace.storeId !== session.storeId ||
303
+ workspace.epoch !== session.epoch
304
+ )
305
+ throw new ContractError("stale");
306
+ const history = new NativeHistory(client, session.storeId, ui);
307
+ if (args.trim()) await workflowDetails(client, ui, args.trim());
308
+ else
309
+ for (;;) {
310
+ const menu = await ui.select(
311
+ "Cadence history • readonly; Return detaches, never cancels",
312
+ [
313
+ "Workflow runs",
314
+ "Retained task history",
315
+ "Enter workflow ID",
316
+ "Command receipt",
317
+ "Service status / guidance",
318
+ "Return",
319
+ ],
320
+ );
321
+ if (!menu || menu === "Return") break;
322
+ if (menu === "Workflow runs") await workflowHistory(client, ui);
323
+ else if (menu === "Retained task history") {
324
+ const id = await history.pages(
325
+ "tasks",
326
+ { kind: "workspace", id: workspace.workspaceId },
327
+ null,
328
+ true,
329
+ );
330
+ if (id) await history.scope({ kind: "task", id });
331
+ } else if (menu === "Enter workflow ID") {
332
+ const id = await ui.input("Exact workflow UUID");
333
+ if (id) await workflowDetails(client, ui, id);
334
+ } else if (menu === "Command receipt") {
335
+ const id = await ui.input(
336
+ "Exact command UUID (observation only; never replay)",
337
+ );
338
+ if (id) await show(pretty(await client.receipt(id, signal)));
339
+ } else if (menu === "Service status / guidance") {
340
+ await show(
341
+ `${MANAGEMENT_GUIDANCE}\n${pretty(await connection.refresh())}\n${pretty(await client.activeRuns(signal))}\nRecovery is explicit native-local management; no locks are cleared here.`,
342
+ );
343
+ }
344
+ }
345
+ } catch (error) {
346
+ ctx.ui.notify(
347
+ `${error instanceof ContractError ? error.code : "unavailable"}: History observation unavailable. Nothing was started, retried or repaired.\n${attached ? "Reopen /cadence-history for a fresh observation. Accepted work may continue." : `${MANAGEMENT_GUIDANCE}${autostartHint()}`}`,
348
+ "error",
349
+ );
350
+ } finally {
351
+ latch.clear();
352
+ abort.abort();
353
+ dismiss?.();
354
+ try {
355
+ await connection.detach();
356
+ } catch {
357
+ ctx.ui.notify(
358
+ "Detach unconfirmed; exact attachment retained. Accepted work may continue.",
359
+ "warning",
360
+ );
361
+ }
362
+ modal = false;
363
+ ctx.ui.notify(
364
+ "History detached. Accepted work continues; no Cancel was requested.",
365
+ "info",
366
+ );
367
+ }
368
+ },
369
+ });
370
+ }
package/src/index.ts CHANGED
@@ -3,15 +3,15 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import { registerAgentPanel } from "./agent-panel.ts";
4
4
  import { registerCadenceAgentFeed } from "./agent-panel-cadence.ts";
5
5
  import { registerCadenceMode } from "./cadence-mode.ts";
6
+ import { registerHistoryShell } from "./history-shell.ts";
6
7
  import { autostartNotice } from "./native-client.ts";
7
8
  import { CONFIG_MISSING, startupCardLines } from "./startup-card.ts";
8
- import { registerTaskShell } from "./task-shell.ts";
9
9
 
10
10
  /** Sole production composition. Discovery registers inert capabilities only;
11
- * actual host binding belongs to the lightweight shell’s session_start. */
11
+ * actual host binding belongs to the readonly history shell’s session_start. */
12
12
  export default function register(pi: ExtensionAPI): void {
13
13
  if (process.env.CADENCE_SUBAGENT_CHILD === "1") return;
14
- registerTaskShell(pi);
14
+ registerHistoryShell(pi);
15
15
  registerCadenceMode(pi);
16
16
  // Observes `subagent:*` bus events only; renders nothing until one arrives.
17
17
  registerAgentPanel(pi);
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9",
5
+ "f0ff0c9d0481dab9fd21cdbc7c0d72b427bee60033a9af4c789f859c4c83fe75",
6
6
  } as const;
@@ -14,7 +14,7 @@ import {
14
14
  type SessionBootstrap,
15
15
  } from "./service-contract.ts";
16
16
  import { HttpServiceTransport } from "./service-http-client.ts";
17
- import { effectiveWorkspace } from "./task-store.ts";
17
+ import { effectiveWorkspace } from "./workspace.ts";
18
18
 
19
19
  export const MANAGEMENT_GUIDANCE =
20
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.";
@@ -57,8 +57,19 @@ const bootStart = (o: AutostartObservation) =>
57
57
  o.platform === "linux" && (o.uid === 0 || o.env.CADENCE_LINGER !== "0");
58
58
  /** Pi's managed copy puts no `cadence` bin on PATH; CADENCE_LINGER=0 keeps
59
59
  * the suggested command login-only, too. */
60
+ const cliCommand = (o: AutostartObservation) =>
61
+ piUserCopy(o)
62
+ ? `node ${JSON.stringify(join(o.root, "src", "service-cli.mjs"))}`
63
+ : "cadence";
60
64
  const installCommand = (o: AutostartObservation) =>
61
- `${piUserCopy(o) ? `node ${JSON.stringify(join(o.root, "src", "service-cli.mjs"))}` : "cadence"} server install${o.platform === "linux" && o.uid === 0 ? " --system" : o.platform === "linux" && o.env.CADENCE_LINGER === "0" ? " --no-linger" : ""}`;
65
+ `${cliCommand(o)} server install${o.platform === "linux" && o.uid === 0 ? " --system" : o.platform === "linux" && o.env.CADENCE_LINGER === "0" ? " --no-linger" : ""}`;
66
+ /** The explicit command that stops one project owner. Text only. */
67
+ export function projectStopCommand(
68
+ workspace: string,
69
+ o: AutostartObservation = hostObservation(),
70
+ ): string {
71
+ return `${cliCommand(o)} stop --workspace ${JSON.stringify(workspace)}`;
72
+ }
62
73
 
63
74
  /** Name the explicit command while no background service is registered.
64
75
  * Reads paths only. */
@@ -241,6 +252,38 @@ export class NativeConnection {
241
252
  compatible(safety = false): boolean {
242
253
  return compatibleBuild(this.session?.build, nativeBuild, safety);
243
254
  }
255
+ /** Forget an attachment only when the registry proves its owner instance is
256
+ * gone: absent, stopped, or replaced by another epoch. Its slot ended with
257
+ * that process, so no detach request is sent and a later attach may proceed.
258
+ * A live or unobservable same-epoch owner keeps the exact attachment. */
259
+ forgetSuperseded(cwd: string): boolean {
260
+ if ((!this.transport && !this.network) || this.closing || this.allocating)
261
+ return false;
262
+ let observed: { status: string; epoch?: string | null };
263
+ try {
264
+ observed = new ServiceCoordination(
265
+ effectiveWorkspace(cwd).workspace,
266
+ ).inspect();
267
+ } catch {
268
+ return false;
269
+ }
270
+ const epoch = "epoch" in observed ? observed.epoch : undefined;
271
+ const gone =
272
+ observed.status === "absent" ||
273
+ (observed.status === "stopped" &&
274
+ (epoch === null || epoch === this.epoch)) ||
275
+ (typeof epoch === "string" && epoch !== this.epoch);
276
+ if (!gone) return false;
277
+ const network = this.network;
278
+ this.network = undefined;
279
+ this.networkClose = undefined;
280
+ this.transport = undefined;
281
+ this.client = undefined;
282
+ this.session = undefined;
283
+ this.epoch = undefined;
284
+ void network?.close().catch(() => {});
285
+ return true;
286
+ }
244
287
  detach(): Promise<void> {
245
288
  if (this.closing) return this.closing;
246
289
  const transport = this.transport;
@@ -0,0 +1,132 @@
1
+ /** Deterministic workflow inspection, independent of model availability and mode. */
2
+ import { type NativeViews, pretty, value } from "./native-history.ts";
3
+ import type { WorkbenchResult } from "./service/contracts/workbench.ts";
4
+ import type { ServiceClient } from "./service-client.ts";
5
+ import { ContractError } from "./service-contract.ts";
6
+
7
+ export async function workflowDetails(
8
+ client: ServiceClient,
9
+ ui: NativeViews,
10
+ id: string,
11
+ ): Promise<void> {
12
+ for (;;) {
13
+ const view = value(
14
+ await client.workbenchRead({ kind: "workflow", id }, ui.signal),
15
+ );
16
+ ui.current();
17
+ if (
18
+ view.kind !== "workflow" ||
19
+ view.response.type !== "run" ||
20
+ view.response.run.id !== id
21
+ )
22
+ throw new ContractError("invalid");
23
+ const run = view.response.run;
24
+ await ui.show(
25
+ `${run.goal}\n${run.id} • ${run.status} / ${run.phase}\n${run.notice}\nMerged commit: ${run.mergedCommit ?? "none"}\nAutomatic Agent review is not human review. Step summaries are previews; select a step for its retained result.\n${pretty(run.steps)}`,
26
+ );
27
+ const labels = run.steps.map(
28
+ (s, i) => `${i + 1}. ${s.kind} • ${s.id} • ${s.status}`,
29
+ );
30
+ const selected = await ui.select("Workflow details • readonly", [
31
+ ...labels,
32
+ "Refresh",
33
+ "Return",
34
+ ]);
35
+ if (selected === "Refresh") continue;
36
+ if (!selected || !labels.includes(selected)) return;
37
+ const step = run.steps[labels.indexOf(selected)];
38
+ const choice = await ui.select("Retained step evidence", [
39
+ "Full result",
40
+ ...(step.childRunId ? ["Subagent transcript"] : []),
41
+ "Return",
42
+ ]);
43
+ if (choice === "Full result") {
44
+ const result = value(
45
+ await client.workbenchRead(
46
+ { kind: "workflow-detail", id, stepId: step.id },
47
+ ui.signal,
48
+ ),
49
+ );
50
+ ui.current();
51
+ if (result.kind !== "file" || result.path !== `workflow/${id}/${step.id}`)
52
+ throw new ContractError("invalid");
53
+ await ui.show(
54
+ `${result.limited ? "Limited retained result" : "Retained result"}\n${result.text}`,
55
+ );
56
+ } else if (choice === "Subagent transcript") {
57
+ const result = value(
58
+ await client.workbenchRead(
59
+ { kind: "workflow-transcript", id, stepId: step.id },
60
+ ui.signal,
61
+ ),
62
+ );
63
+ ui.current();
64
+ if (
65
+ result.kind !== "workflow-transcript" ||
66
+ result.runId !== id ||
67
+ result.stepId !== step.id
68
+ )
69
+ throw new ContractError("invalid");
70
+ const turn = result.turn;
71
+ await ui.show(
72
+ turn
73
+ ? `${turn.status}\n${turn.notice}\nOmitted content: ${pretty(turn.omitted)}\n${turn.items.map((item) => `${item.role} ${item.name}${item.error ? " (error)" : ""}\n${item.args}\n${item.text}`).join("\n\n")}`
74
+ : "Transcript unavailable; no outcome inferred.",
75
+ );
76
+ }
77
+ }
78
+ }
79
+ export async function workflowHistory(
80
+ client: ServiceClient,
81
+ ui: NativeViews,
82
+ ): Promise<void> {
83
+ let after: string | null = null;
84
+ let scan: string | undefined;
85
+ const previous: (string | null)[] = [];
86
+ for (;;) {
87
+ const page: WorkbenchResult = value(
88
+ await client.workbenchRead(
89
+ { kind: "workflow-history", after, ...(scan ? { scan } : {}) },
90
+ ui.signal,
91
+ ),
92
+ );
93
+ ui.current();
94
+ if (page.kind === "workflow-history-progress") {
95
+ if (page.after !== after) throw new ContractError("invalid");
96
+ const choice = await ui.select(
97
+ "Scanning workflow IDs • no complete page yet",
98
+ ["Continue scanning", "Return"],
99
+ );
100
+ if (choice !== "Continue scanning") return;
101
+ scan = page.scan;
102
+ continue;
103
+ }
104
+ if (page.kind !== "workflow-history") throw new ContractError("invalid");
105
+ scan = undefined;
106
+ const labels = page.entries.map(
107
+ (e, i) =>
108
+ `${i + 1}. ${e.run?.goal ?? e.id} • ${e.run?.status ?? "unavailable"}`,
109
+ );
110
+ const selected = await ui.select(
111
+ "Workflow history • ID order; listing may change, selected IDs never rebase",
112
+ [
113
+ ...labels,
114
+ ...(page.next ? ["Next page"] : []),
115
+ ...(previous.length ? ["Previous page"] : []),
116
+ "Return",
117
+ ],
118
+ );
119
+ if (selected === "Next page" && page.next) {
120
+ previous.push(after);
121
+ after = page.next;
122
+ } else if (selected === "Previous page") after = previous.pop() ?? null;
123
+ else if (selected && labels.includes(selected)) {
124
+ const entry = page.entries[labels.indexOf(selected)];
125
+ if (entry.run) await workflowDetails(client, ui, entry.id);
126
+ else
127
+ await ui.show(
128
+ `Workflow ${entry.id} is unreadable. Retained bytes are untouched; no outcome inferred.`,
129
+ );
130
+ } else return;
131
+ }
132
+ }