paseo-follow-up 2.3.0-beta.3 → 2.3.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.
package/index.client.tsx CHANGED
@@ -26,7 +26,8 @@ import { inboxSidebarView, sidebarViewHost } from "./client/sidebar-view";
26
26
  import { OVERSEER_KEY } from "./client/home-list";
27
27
  import { contributeBrief } from "./client/brief";
28
28
  import { clientTimeZoneRpc, setOnboardingRpc } from "./shared/contracts";
29
- import { isCategory, writeCategory } from "./shared/settings-nav";
29
+ import { createSettings } from "./client/settings-screens";
30
+ import type { SettingsCategory } from "./shared/settings-nav";
30
31
  import { openReportSheet, ReportSheetHost, setReportFallback } from "./client/report-issue";
31
32
  import { openRename, RenameHost } from "./client/rename";
32
33
  import { setReportError } from "./client/toast-store";
@@ -54,7 +55,6 @@ export default function contribute(host: PluginClientContext) {
54
55
  .catch(() => { if (attempt < 4) setTimeout(() => reportTimeZone(attempt + 1), [5_000, 30_000, 120_000, 600_000][attempt]); });
55
56
  };
56
57
  reportTimeZone();
57
- const openSettings = (category?: string) => { if (isCategory(category)) writeCategory(category); client.openSettings("projects"); };
58
58
  const openOverview = () => client.openScreen({ screenId: OVERVIEW });
59
59
  const openLog = () => client.openScreen({ screenId: OVERVIEW, params: { view: "log" } });
60
60
  const openCatchUp = () => client.openScreen({ screenId: OVERVIEW, params: { view: "catchup", at: "0", n: String(Date.now()) } });
@@ -67,7 +67,10 @@ export default function contribute(host: PluginClientContext) {
67
67
  setReportFallback(() => client.openScreen({ screenId: OVERVIEW }));
68
68
  setReportError((message, at) => openReportSheet({ kind: "bug", error: message, at }));
69
69
  const reportHost = (props: PluginSurfaceProps | PluginWorkspacePanelProps) => <><ReportSheetHost theme={props.theme} layout={props.layout} openAgent={props.navigation ? agentId => props.navigation!.openAgent({ agentId }) : undefined} /><RenameHost theme={props.theme} compact={props.layout.compact} /></>;
70
- const Settings = (props: PluginSurfaceProps) => <><FollowSettings {...props} openSetup={openSetup} openReport={() => openReportSheet()} />{reportHost(props)}</>;
70
+ const Settings = (props: PluginSurfaceProps & { category?: SettingsCategory }) => <><FollowSettings {...props} openSetup={openSetup} openReport={() => openReportSheet()} />{reportHost(props)}</>;
71
+ // Paseo 0.16: one settings screen per category (its own tabs); 0.15: one screen with Follow-up's tabs (client/settings-screens.ts).
72
+ const settings = createSettings(client, Settings);
73
+ const openSettings = settings.open;
71
74
  const store = createLiveStore(client);
72
75
  const inbox = createInboxStore(host);
73
76
  // A brief's x (client/dismiss.tsx) updates the inbox rows at once, like Sign off.
@@ -107,7 +110,7 @@ export default function contribute(host: PluginClientContext) {
107
110
  client.addScreen({ id: OVERVIEW, title: "Follow-up", Component: Overview }),
108
111
  client.addScreen({ id: LARGE_SCREEN, title: params => store.get(params.workspaceId ?? "")?.title ?? "Follow-up", Component: Large }),
109
112
  ...LEGACY_SETTINGS_SCREENS.map(id => client.addScreen({ id, title: "Follow-up settings", Component: Settings })),
110
- client.addSettingsScreen({ id: "projects", title: "Follow-up", icon: FOLLOW_UP_ICON, Component: Settings }),
113
+ settings.remove,
111
114
  client.addWorkspacePanel({ id: PANEL, title: "Follow-up", icon: FOLLOW_UP_ICON, locations: ["workspace", "explorer"], Component: Panel }),
112
115
  client.addCommandCenterItem({ id: "open-follow-up", title: "Follow-up: open for this workspace", icon: FOLLOW_UP_ICON, keywords: ["PR", "stack", "repairs", "done", "archive"], context: "workspace", onSelect({ openPanel }) { openPanel(PANEL, { location: location() }); } }),
113
116
  client.addCommandCenterItem({ id: "open-follow-up-large", title: "Follow-up: open the larger view", icon: "Maximize2", keywords: ["expand", "full screen", "maximize", "PR", "stack"], context: "workspace", onSelect({ workspace, openScreen }) { openScreen({ screenId: LARGE_SCREEN, params: { workspaceId: workspace.id } }); } }),
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "paseo-follow-up",
3
3
  "private": false,
4
- "version": "2.3.0-beta.3",
5
- "description": "A Paseo plugin that follows every workspace until the work is done: one Home for what needs you, questions you answer anywhere, and repairs that send themselves.",
4
+ "version": "2.3.0",
5
+ "description": "Follows every workspace your coding agents work in until it's done: one list of what needs you.",
6
6
  "type": "module",
7
7
  "files": [
8
8
  "paseo-plugin.json",
@@ -1,6 +1,7 @@
1
1
  import { constants } from "node:fs";
2
2
  import { open } from "node:fs/promises";
3
3
  import { isClaudeArtifact } from "../shared/spec";
4
+ import { toolResult } from "../shared/tool-result";
4
5
  import { receiptTitle, rememberTitle, shortTitle, type TitleIndex } from "../shared/local-titles";
5
6
 
6
7
  export const TITLE_READ_BYTES = 8192;
@@ -16,12 +17,8 @@ export async function readTitleHtml(path: string): Promise<string | null> {
16
17
  } finally { await file.close(); }
17
18
  } catch { return null; }
18
19
  }
19
- export function resultText(output: unknown): string {
20
- if (typeof output === "string") return output;
21
- if (Array.isArray(output)) return output.map(resultText).join("\n");
22
- if (output && typeof output === "object") return resultText((output as { text?: unknown }).text);
23
- return "";
24
- }
20
+ /** A tool result's text, in every shape Paseo sends (shared/tool-result.ts). */
21
+ export const resultText = (output: unknown): string => toolResult(output).text;
25
22
  export function artifactPublishUrl(output: unknown): string | null {
26
23
  const url = /^(?:Published \S.*? at|Created a new Artifact at) (https:\/\/claude\.ai\/(?:code\/)?artifact\/[\w-]+)(?=[\s(.,]|$)/.exec(resultText(output).trimStart())?.[1];
27
24
  return url && isClaudeArtifact(url) ? url : null;
@@ -32,8 +29,9 @@ export async function receiptTitles(entries: readonly { item: unknown }[], readH
32
29
  const titles: TitleIndex = new Map();
33
30
  for (const entry of entries) {
34
31
  const v = object(entry.item), detail = object(v.detail), input = object(detail.input);
35
- if (v.type !== "tool_call" || v.status !== "completed" || v.error || object(detail.output).isError === true) continue;
36
- const output = resultText(detail.output);
32
+ const result = toolResult(detail.output);
33
+ if (v.type !== "tool_call" || v.status !== "completed" || v.error || result.isError) continue;
34
+ const output = result.text;
37
35
  if (v.name === "Artifact") {
38
36
  const action = input.action ?? "publish";
39
37
  if (input.asset === true || !["publish", "read"].includes(String(action))) continue;
@@ -42,15 +40,14 @@ export async function receiptTitles(entries: readonly { item: unknown }[], readH
42
40
  let html: string | null = null;
43
41
  if (!shortTitle(input.title) && action === "publish" && typeof input.file_path === "string") html = await readHtml(input.file_path).catch(() => null);
44
42
  // Read returns raw HTML or a title-labelled summary; structured read.result is preserved by Paseo too.
45
- const read = object(object(detail.output).read);
43
+ const read = object(result.object?.read);
46
44
  if (action === "read") html = typeof read.result === "string" ? read.result : output;
47
- const named = action === "read" ? shortTitle(object(detail.output).title) ?? shortTitle(/^(?:Title|Artifact title):\s*(.+)$/im.exec(output)?.[1]) : null;
45
+ const named = action === "read" ? shortTitle(result.object?.title) ?? shortTitle(/^(?:Title|Artifact title):\s*(.+)$/im.exec(output)?.[1]) : null;
48
46
  rememberTitle(titles, url, receiptTitle(named ? { ...input, title: named } : input, html));
49
47
  }
50
48
  if (v.name === "mcp__claude_ai_Claude_Docs__batch") {
51
49
  // Each successful create result carries its URL; pair by operation index rather than guessing from prose.
52
- let parsed: unknown = detail.output;
53
- try { if (output) parsed = JSON.parse(output); } catch { /* structured output may already be present */ }
50
+ const parsed = result.value;
54
51
  const operations = Array.isArray(input.batch) ? input.batch : Array.isArray(input.operations) ? input.operations : [];
55
52
  const results = Array.isArray(parsed) ? parsed : object(parsed).results ?? object(parsed).batch;
56
53
  if (!Array.isArray(results)) continue;
package/shared/brief.ts CHANGED
@@ -326,10 +326,17 @@ export function pastAsk(ask: string): string {
326
326
  return t ? t.charAt(0).toUpperCase() + t.slice(1) : ask;
327
327
  }
328
328
 
329
+ /**
330
+ * A resolved card's outcome as the developer reads it. The stored word stays (a developer's Dismiss is recorded as
331
+ * "Dismissed", which agents and older records read); the screen says "Removed", the same word as the x's Remove and its
332
+ * toast (armed-dismiss-shows-remove-and-keep).
333
+ */
334
+ export const outcomeLabel = (outcome: string | null): string | null => outcome === "Dismissed" ? "Removed" : outcome;
335
+
329
336
  export function collapsedLine(b: Pick<Brief, "state" | "source" | "outcome" | "ask">): string {
330
- if (b.state === "superseded" && b.outcome && OWN_OUTCOMES.includes(b.outcome)) return b.outcome;
337
+ if (b.state === "superseded" && b.outcome && OWN_OUTCOMES.includes(b.outcome)) return outcomeLabel(b.outcome)!;
331
338
  if (b.state === "superseded") return b.source === "none" ? "No ask was stated · the agent kept going" : `Earlier ask, the agent kept going: ${pastAsk(b.ask)}`;
332
- return `${b.outcome} · ${pastAsk(b.ask)}`;
339
+ return `${outcomeLabel(b.outcome)} · ${pastAsk(b.ask)}`;
333
340
  }
334
341
 
335
342
  // ---------- PR facts (S5) ----------
@@ -238,7 +238,7 @@ export const CATCH_UP_KEYS: readonly { key: string; what: string; action: CatchU
238
238
  { key: "⌘↵", what: "Ask the agent", action: "ask", combos: ["Cmd+Enter", "Ctrl+Enter"], when: "more" },
239
239
  { key: "N", what: "Add a note", action: "note", combos: ["N"] },
240
240
  // D alone picks option D, so Dismiss takes Shift, as Skip workspace does beside J.
241
- { key: "⇧D", what: "Dismiss the question (the agent isn't messaged)", action: "dismiss", combos: ["Shift+D"] },
241
+ { key: "⇧D", what: "Remove it (the agent isn't messaged)", action: "dismiss", combos: ["Shift+D"] },
242
242
  { key: "V", what: "Dictate your answer, and stop", action: "dictate", combos: ["V"], needs: "dictation" },
243
243
  { key: "L", what: "Later", action: "later", combos: ["L"] },
244
244
  { key: "O", what: "Open chat", action: "chat", combos: ["O"] },
package/shared/chat.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { onBehalfOf } from "./actor";
2
2
  import { BRIDGE_TOOL, BRIDGE_SHELL_CALL, splitBatchText, isRecoveryText } from "./legacy";
3
3
  import { z } from "zod";
4
+ import { toolResult } from "./tool-result";
4
5
 
5
6
  /** Follow-up's own messages and tool calls, recognised in agent chats so they render as compact rows. */
6
7
  export const FOLLOW_TOOLS = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "declare_done", "ask_question", "record_answer", "withdraw_question", "set_spec"] as const;
@@ -51,18 +52,7 @@ export type ToolRow = z.infer<typeof toolRowSchema>;
51
52
  function record(value: unknown): value is Record<string, unknown> {
52
53
  return typeof value === "object" && value !== null && !Array.isArray(value);
53
54
  }
54
- /** Text from Claude's { output } / { content: [{ text }] } shapes or Codex's MCP result. */
55
- export function readText(value: unknown): string | undefined {
56
- if (value === null || value === undefined) return "";
57
- if (typeof value === "string") return value;
58
- if (Array.isArray(value)) {
59
- const parts = value.map(part => typeof part === "string" ? part : record(part) && typeof part.text === "string" ? part.text : undefined);
60
- return parts.every(p => p !== undefined) ? parts.join("\n") : undefined;
61
- }
62
- if (!record(value)) return undefined;
63
- const key = ["output", "content", "text", "message", "result"].find(name => name in value);
64
- return key ? readText(value[key]) : undefined;
65
- }
55
+ /** The JSON object in a result's text (toolResult's text: Claude's { output }, MCP content, or a plain string). */
66
56
  function json(text: string | undefined): Record<string, unknown> | null {
67
57
  if (!text) return null;
68
58
  const parse = (body: string) => { try { const value = JSON.parse(body); return record(value) ? value : null; } catch { return null; } };
@@ -184,14 +174,14 @@ export function followTimelineItem(item: TimelineToolCall, ledger: MomentLedger)
184
174
  let output: string | undefined;
185
175
  if (tool) {
186
176
  if (record(detail) && record(detail.input)) input = detail.input;
187
- output = record(detail) && "output" in detail ? readText(detail.output) : undefined;
177
+ output = record(detail) && "output" in detail ? toolResult(detail.output).text : undefined;
188
178
  } else if (record(detail) && detail.type === "shell" && typeof detail.command === "string") {
189
179
  const call = followShellCall(detail.command);
190
180
  if (!call) return undefined;
191
- tool = call.tool; input = call.input; output = typeof detail.output === "string" ? detail.output : undefined;
181
+ tool = call.tool; input = call.input; output = toolResult(detail.output).text || undefined;
192
182
  } else return undefined;
193
183
  if (TOOL_PRESENTATION[tool] !== "moment" || item.status !== "completed") return undefined;
194
- if (record(detail) && record(detail.output) && detail.output.isError === true) return undefined;
184
+ if (record(detail) && toolResult(detail.output).isError) return undefined;
195
185
  const row = toolRow(tool, "completed", input, output);
196
186
  if (tool !== "declare_done") return row;
197
187
  if (!row.done) return undefined;
package/shared/created.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { modelName } from "./agent-settings";
3
3
  import { PRESENCE, type TaskAgentState } from "./task-status";
4
+ import { toolResult } from "./tool-result";
4
5
 
5
6
  /**
6
7
  * The chat card for an agent or workspace another agent creates (Paseo's create_agent / create_workspace tool calls).
@@ -42,21 +43,10 @@ export function createdKind(name: string): "agent" | "workspace" | null {
42
43
  return m ? m[1] as "agent" | "workspace" : null;
43
44
  }
44
45
 
45
- /** An MCP result: a JSON string, `{ content: [{ type: "text", text }] }`, or the object itself. */
46
- function resultObject(output: unknown): Record<string, unknown> | null {
47
- if (record(output) && Array.isArray(output.content)) {
48
- const text = output.content.map(c => record(c) && typeof c.text === "string" ? c.text : "").join("");
49
- return resultObject(text);
50
- }
51
- if (typeof output === "string") { try { const v: unknown = JSON.parse(output); return record(v) ? v : null; } catch { return null; } }
52
- return record(output) ? output : null;
53
- }
54
-
46
+ /** An error's words: Paseo's tool_result error ({ content }), { message }, or an MCP error result's text. */
55
47
  const errorText = (v: unknown): string | null => {
56
- if (typeof v === "string") return str(v);
57
- if (record(v)) return str(v.message) ?? str(v.error) ?? errorText(v.content);
58
- if (Array.isArray(v)) return str(v.map(c => record(c) && typeof c.text === "string" ? c.text : "").join(" "));
59
- return null;
48
+ if (record(v) && !Array.isArray(v.content) && !("output" in v)) return str(v.message) ?? str(v.error) ?? (v.content !== undefined ? errorText(v.content) : null);
49
+ return str(toolResult(v).text);
60
50
  };
61
51
 
62
52
  /** "claude/claude-opus-5-5" → { provider: "claude", model: "Opus 5.5" }; a bare provider has no model. */
@@ -75,7 +65,8 @@ export function createdCard(item: ToolCallLike): CreatedCard | null {
75
65
  const detail = record(item.detail) ? item.detail : {};
76
66
  const input = record(detail.input) ? detail.input : {};
77
67
  const output = "output" in detail ? detail.output : undefined;
78
- const failed = item.status === "failed" || (record(output) && output.isError === true);
68
+ const result = toolResult(output);
69
+ const failed = item.status === "failed" || result.isError;
79
70
  const { provider, model } = kind === "agent" ? providerModel(input.provider, input.model) : { provider: null, model: null };
80
71
  const base = {
81
72
  kind, title: str(input.title) ?? (kind === "workspace" ? str(input.branchName) ?? str(input.worktreeSlug) : null), model, provider,
@@ -84,13 +75,14 @@ export function createdCard(item: ToolCallLike): CreatedCard | null {
84
75
  };
85
76
  if (failed) return { ...base, phase: "failed", id: null, workspaceId: null, error: errorText(item.error) ?? errorText(output) ?? "The call failed" };
86
77
  if (item.status === "running") return { ...base, phase: "starting", id: null, workspaceId: null, error: null };
87
- const result = resultObject(output);
88
- if (!result) return null;
89
- const nested = record(result.workspace) ? result.workspace : null;
90
- const id = kind === "agent" ? str(result.agentId) ?? str(result.id) : str(result.workspaceId) ?? str(nested?.id) ?? str(result.id);
78
+ // Every shape Paseo sends (shared/tool-result.ts): Claude's { output }, Codex's MCP envelope, a JSON string.
79
+ const data = result.object;
80
+ if (!data) return null;
81
+ const nested = record(data.workspace) ? data.workspace : null;
82
+ const id = kind === "agent" ? str(data.agentId) ?? str(data.id) : str(data.workspaceId) ?? str(nested?.id) ?? str(data.id);
91
83
  if (!id) return null;
92
- return { ...base, phase: "created", id, title: base.title ?? (kind === "workspace" ? str(nested?.name) ?? str(result.name) : null),
93
- workspaceId: kind === "agent" ? str(result.workspaceId) : id, error: null };
84
+ return { ...base, phase: "created", id, title: base.title ?? (kind === "workspace" ? str(nested?.name) ?? str(data.title) ?? str(data.name) : null),
85
+ workspaceId: kind === "agent" ? str(data.workspaceId) : id, error: null };
94
86
  }
95
87
 
96
88
  /** Live facts the card reads (follow.created-items), from the engine's directory snapshot. Missing: not known yet. */
package/shared/errors.ts CHANGED
@@ -43,7 +43,7 @@ export function mootNote(error: unknown, typed = false): string {
43
43
  const kept = typed ? "Your answer wasn't sent." : "Your pick wasn't sent.";
44
44
  switch (mootKind(error)) {
45
45
  case "withdrawn": return `The agent withdrew this question. ${kept}`;
46
- case "dismissed": return `This question was dismissed. ${kept}`;
46
+ case "dismissed": return `This question was removed. ${kept}`;
47
47
  case "replaced": return `A newer card replaced this one. ${kept}`;
48
48
  default: return `Already answered elsewhere. ${kept}`;
49
49
  }
@@ -107,10 +107,13 @@ export const isOpen = (q: Pick<Question, "answer" | "closed">) => !q.answer && !
107
107
  /** The developer dismissed it (dismissing-a-question-sends-the-agent-nothing): closed, no answer, nothing sent. */
108
108
  export const isDismissed = (q: Pick<Question, "answer" | "closed">) => !q.answer && !!q.closed?.dismissed;
109
109
  export const DISMISS_REASON = "Dismissed by the developer: it no longer matters.";
110
- /** A closed question's line on every surface: "Dismissed by you" (or "for you by an agent"), else why it was withdrawn. */
110
+ /**
111
+ * A closed question's line on every surface: "Removed by you" (or "for you by an agent"), else why it was withdrawn.
112
+ * Display only: the record stays `closed.dismissed`, and agents still read it as dismissed.
113
+ */
111
114
  export function closedLine(q: Pick<Question, "answer" | "closed">): string {
112
115
  if (!q.closed) return "";
113
- if (isDismissed(q)) return q.closed.by?.startsWith("agent:") ? "Dismissed for you by an agent" : "Dismissed by you";
116
+ if (isDismissed(q)) return q.closed.by?.startsWith("agent:") ? "Removed for you by an agent" : "Removed by you";
114
117
  return `Withdrawn: ${q.closed.reason}`;
115
118
  }
116
119
 
@@ -32,8 +32,20 @@ const memory = new Map<string, string>();
32
32
  let backend: KeyValue | null = null;
33
33
  const viewListeners = new Set<() => void>();
34
34
  let viewVersion = 0;
35
+ /**
36
+ * Writes made while the document is still loading (`writes-while-loading-reach-the-document`): a surface opened at
37
+ * start-up (a settings tab straight from a link, a fold) writes before the document arrives, and the document's older
38
+ * value must not win over it. They are replayed into the document when it arrives. A value merely cached from an
39
+ * earlier session is not one of them, so the document still wins over that.
40
+ */
41
+ const pending = new Map<string, string>();
35
42
  /** Swap in (or out, with null) the device document behind deviceStorage; re-renders whatever reads view state. */
36
- export function setDeviceBackend(next: KeyValue | null) { backend = next; if (next) status = "ready"; viewChanged(); }
43
+ export function setDeviceBackend(next: KeyValue | null) {
44
+ backend = next;
45
+ if (next) { status = "ready"; for (const [key, value] of pending) next.set(key, value); }
46
+ pending.clear();
47
+ viewChanged();
48
+ }
37
49
  /** none: this host keeps no device document (0.15). loading: expected, not loaded yet. ready / failed. */
38
50
  export type ViewStatus = "none" | "loading" | "ready" | "failed";
39
51
  let status: ViewStatus = "none";
@@ -48,7 +60,7 @@ const local = {
48
60
  };
49
61
  export const deviceStorage: KeyValue = {
50
62
  get(key) { return backend?.get(key) ?? local.get(key); },
51
- set(key, value) { local.set(key, value); backend?.set(key, value); viewChanged(); },
63
+ set(key, value) { local.set(key, value); if (backend) backend.set(key, value); else if (status === "loading") pending.set(key, value); viewChanged(); },
52
64
  };
53
65
  /** The localStorage cache alone: what a device migrates into its document once. */
54
66
  export const localViewStorage: KeyValue = local;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The one reader of a tool call's result as Paseo hands it to plugins (`tool_call` item `detail.output`). Every
3
+ * Follow-up reader of a tool result goes through `toolResult`, never `detail.output` directly
4
+ * (`every-tool-result-reads-through-one-normalizer`, tests/tool-result.test.ts). Paseo sends one of:
5
+ *
6
+ * - Claude: `{ output: X, files? }` (Paseo's Claude provider, `buildToolOutput`): X is the parsed JSON of the result's
7
+ * text when it parses, else the text itself.
8
+ * - Codex: the raw MCP result `{ content: [{ type: "text", text }], structuredContent?, isError?, _meta? }`. Paseo's own
9
+ * tools put a summary in front of the JSON in that text ("availableModes_count=3\n…\n\n{…}"); structuredContent
10
+ * holds the object.
11
+ * - A plain string (other providers, shell output, transcripts) or the object itself.
12
+ */
13
+ export type ToolResult = {
14
+ /** The result as text: the string itself, the MCP text blocks joined, or the object as JSON. "" when there's none. */
15
+ text: string;
16
+ /** The result as data: structuredContent, else the parsed JSON (whole text, else its trailing JSON object), else the object itself. */
17
+ value: unknown;
18
+ /** `value` when it's a plain object. */
19
+ object: Record<string, unknown> | null;
20
+ /** An MCP error result (`isError: true`), at any wrapper depth. */
21
+ isError: boolean;
22
+ };
23
+
24
+ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
25
+ const CLAUDE_WRAPPER_KEYS = new Set(["output", "files"]);
26
+ const MAX_DEPTH = 8;
27
+
28
+ /** JSON text, or text whose JSON value starts on its own line after a preamble ("key=value" lines, a sentence). */
29
+ function parseJson(text: string): unknown {
30
+ const body = text.trim();
31
+ if (!body) return undefined;
32
+ try { return JSON.parse(body); } catch { /* not whole JSON */ }
33
+ const at = body.search(/(?:^|\n)\s*[[{]/);
34
+ if (at < 0) return undefined;
35
+ const tail = body.slice(at).trim();
36
+ try { return JSON.parse(tail); } catch { return undefined; }
37
+ }
38
+
39
+ const blockText = (blocks: unknown[]): string =>
40
+ blocks.map(b => typeof b === "string" ? b : record(b) && typeof b.text === "string" ? b.text : "").filter(Boolean).join("\n");
41
+
42
+ function read(output: unknown, depth: number): ToolResult {
43
+ if (output === null || output === undefined) return { text: "", value: undefined, object: null, isError: false };
44
+ if (typeof output === "string") {
45
+ const value = parseJson(output);
46
+ return { text: output, value, object: record(value) ? value : null, isError: false };
47
+ }
48
+ if (Array.isArray(output)) {
49
+ // Bare content blocks.
50
+ const text = blockText(output);
51
+ const value = parseJson(text);
52
+ return { text, value, object: record(value) ? value : null, isError: false };
53
+ }
54
+ if (!record(output)) return { text: String(output), value: output, object: null, isError: false };
55
+ if (depth < MAX_DEPTH && "output" in output && Object.keys(output).every(k => CLAUDE_WRAPPER_KEYS.has(k))) return read(output.output, depth + 1);
56
+ if (Array.isArray(output.content)) {
57
+ const text = blockText(output.content);
58
+ const isError = output.isError === true || output.is_error === true;
59
+ const structured = record(output.structuredContent) ? output.structuredContent : undefined;
60
+ const value = structured ?? parseJson(text);
61
+ return { text, value, object: record(value) ? value : null, isError };
62
+ }
63
+ // The object itself (Claude's wrapper already peeled, or a provider that hands the result as data).
64
+ const text = typeof output.text === "string" ? output.text : JSON.stringify(output, null, 2);
65
+ return { text, value: output, object: output, isError: output.isError === true || output.is_error === true };
66
+ }
67
+
68
+ export function toolResult(output: unknown): ToolResult {
69
+ return read(output, 0);
70
+ }