@howaboua/pi-subagent-review 0.2.13 → 0.2.14

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-subagent-review",
3
- "version": "0.2.13",
3
+ "version": "0.2.14",
4
4
  "description": "Pi extension that adds /review via an isolated review subagent.",
5
5
  "type": "module",
6
6
  "main": "index.ts",
package/src/constants.ts CHANGED
@@ -7,6 +7,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
7
  export const CHILD_ENV = "PI_REVIEW_EXTENSION_CHILD";
8
8
  export const REVIEW_COMMAND = "review";
9
9
  export const REVIEW_LABEL = "Review";
10
+ export const REVIEW_PREFACE_MESSAGE_TYPE = "subagent-review-preface";
11
+ export const REVIEW_FINDINGS_MESSAGE_TYPE = "subagent-review-findings";
10
12
  const CONFIG_FILENAME = "pi-subagent-review.json";
11
13
  export const REVIEW_PROMPT_PATH = path.join(
12
14
  path.resolve(__dirname, ".."),
@@ -32,8 +34,6 @@ export const ALLOWED_THINKING = new Set([
32
34
  "xhigh",
33
35
  "max",
34
36
  ] as const);
35
- export const RPC_READY_TIMEOUT_MS = 10_000;
36
- export const RPC_RESPONSE_TIMEOUT_MS = 30_000;
37
37
 
38
38
  export function getAgentDir(): string {
39
39
  const configured = process.env["PI_CODING_AGENT_DIR"]?.trim();
package/src/messages.ts CHANGED
@@ -2,12 +2,13 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionCommandContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
- import { REVIEW_COMMAND } from "./constants.js";
5
+ import {
6
+ REVIEW_COMMAND,
7
+ REVIEW_FINDINGS_MESSAGE_TYPE,
8
+ REVIEW_PREFACE_MESSAGE_TYPE,
9
+ } from "./constants.js";
6
10
  import type { ReviewContext } from "./types.js";
7
11
 
8
- const REVIEW_LOOP_PREFACE_MESSAGE_TYPE = "subagent-review-preface";
9
- const REVIEW_FINDINGS_MESSAGE_TYPE = "subagent-review-findings";
10
-
11
12
  const REVIEW_LOOP_PREFACE_MESSAGE = [
12
13
  "A review subagent is about to inspect the repository in isolation. Its findings are advisory only and may be wrong, overbroad, or missing session context.",
13
14
  "",
@@ -33,7 +34,7 @@ function getReviewPrefaceMessageId(
33
34
  for (const entry of ctx.sessionManager.buildContextEntries()) {
34
35
  if (
35
36
  entry.type === "custom_message" &&
36
- entry.customType === REVIEW_LOOP_PREFACE_MESSAGE_TYPE
37
+ entry.customType === REVIEW_PREFACE_MESSAGE_TYPE
37
38
  ) {
38
39
  messageId = entry.id;
39
40
  }
@@ -41,30 +42,20 @@ function getReviewPrefaceMessageId(
41
42
  return messageId;
42
43
  }
43
44
 
44
- export function sendReviewPrefaceOnce(
45
+ export function sendReviewPreface(
45
46
  pi: ExtensionAPI,
46
47
  ctx: ExtensionCommandContext,
47
- details: { markerId?: string } = {},
48
- ): { inserted: boolean; entryId?: string } {
49
- const existingId = getReviewPrefaceMessageId(ctx);
50
- if (existingId) return { inserted: false, entryId: existingId };
51
-
52
- const previousLeafId = ctx.sessionManager.getLeafId();
48
+ options: { freshLoop?: boolean } = {},
49
+ ): void {
50
+ if (!options.freshLoop && getReviewPrefaceMessageId(ctx)) return;
53
51
  pi.sendMessage(
54
52
  {
55
- customType: REVIEW_LOOP_PREFACE_MESSAGE_TYPE,
53
+ customType: REVIEW_PREFACE_MESSAGE_TYPE,
56
54
  content: REVIEW_LOOP_PREFACE_MESSAGE,
57
55
  display: true,
58
- details,
59
56
  },
60
57
  { triggerTurn: false },
61
58
  );
62
-
63
- const nextLeafId = ctx.sessionManager.getLeafId();
64
- if (nextLeafId && nextLeafId !== previousLeafId) {
65
- return { inserted: true, entryId: nextLeafId };
66
- }
67
- return { inserted: true };
68
59
  }
69
60
 
70
61
  function buildReviewScopeText(review: ReviewContext): string {
@@ -2,7 +2,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { resolveReviewConfig } from "./config.js";
3
3
  import { REVIEW_COMMAND } from "./constants.js";
4
4
  import { buildReviewConversationSummary } from "./conversation-summary.js";
5
- import { sendReviewFindings, sendReviewPrefaceOnce } from "./messages.js";
5
+ import { sendReviewFindings, sendReviewPreface } from "./messages.js";
6
6
  import { detectReviewContext } from "./review-context.js";
7
7
  import {
8
8
  appendReviewLoopBoundary,
@@ -13,8 +13,11 @@ import {
13
13
  summarizeReviewLoopIncrement,
14
14
  } from "./review-loop.js";
15
15
  import { buildReviewTask } from "./review-task.js";
16
- import { getFinalOutput } from "./rpc-protocol.js";
17
- import { createChildRunDetails, isSubagentFailure } from "./run-details.js";
16
+ import {
17
+ createChildRunDetails,
18
+ getFinalOutput,
19
+ isSubagentFailure,
20
+ } from "./run-details.js";
18
21
  import { runReviewSubagent } from "./subagent.js";
19
22
  import type { NavigateWithSummaryModel } from "./tree-summary.js";
20
23
 
@@ -87,7 +90,7 @@ export function registerReviewCommand(
87
90
  return;
88
91
  }
89
92
 
90
- sendReviewPrefaceOnce(pi, ctx);
93
+ sendReviewPreface(pi, ctx, { freshLoop: parsedArgs.startLoop });
91
94
 
92
95
  if (parsedArgs.startLoop) {
93
96
  const targetId =
@@ -183,6 +186,12 @@ export function registerReviewCommand(
183
186
  const message = error instanceof Error ? error.message : String(error);
184
187
  details.exitCode = details.exitCode || 1;
185
188
  details.errorMessage = message;
189
+ pi.appendEntry("subagent-review-failure", {
190
+ version: 1,
191
+ message,
192
+ model: details.model,
193
+ cwd: details.cwd,
194
+ });
186
195
  ctx.ui.notify(`/${REVIEW_COMMAND} failed: ${message}`, "error");
187
196
  } finally {
188
197
  setReviewWidget();
@@ -1,7 +1,12 @@
1
1
  import type {
2
2
  ExtensionAPI,
3
3
  ExtensionCommandContext,
4
+ SessionEntry,
4
5
  } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ REVIEW_FINDINGS_MESSAGE_TYPE,
8
+ REVIEW_PREFACE_MESSAGE_TYPE,
9
+ } from "./constants.js";
5
10
  import type { NavigateWithSummaryModel } from "./tree-summary.js";
6
11
  import type { ResolvedSummaryConfig } from "./types.js";
7
12
 
@@ -119,6 +124,29 @@ export function appendReviewLoopBoundary(
119
124
  return nextLeafId && nextLeafId !== previousLeafId ? nextLeafId : undefined;
120
125
  }
121
126
 
127
+ function isReviewLoopIncrementEntry(entry: SessionEntry): boolean {
128
+ if (entry.type === "message") return true;
129
+ if (entry.type === "branch_summary" || entry.type === "compaction")
130
+ return true;
131
+ return (
132
+ entry.type === "custom_message" &&
133
+ entry.customType !== REVIEW_PREFACE_MESSAGE_TYPE &&
134
+ entry.customType !== REVIEW_FINDINGS_MESSAGE_TYPE
135
+ );
136
+ }
137
+
138
+ export function hasReviewLoopIncrement(
139
+ ctx: ExtensionCommandContext,
140
+ markerId: string,
141
+ ): boolean {
142
+ const branch = ctx.sessionManager.getBranch();
143
+ const markerIndex = branch.findIndex((entry) => entry.id === markerId);
144
+ return (
145
+ markerIndex >= 0 &&
146
+ branch.slice(markerIndex + 1).some(isReviewLoopIncrementEntry)
147
+ );
148
+ }
149
+
122
150
  export async function summarizeReviewLoopIncrement(
123
151
  pi: ExtensionAPI,
124
152
  ctx: ExtensionCommandContext,
@@ -127,11 +155,7 @@ export async function summarizeReviewLoopIncrement(
127
155
  navigateWithSummaryModel: NavigateWithSummaryModel,
128
156
  ): Promise<"summarized" | "skipped" | "cancelled"> {
129
157
  if (!ctx.sessionManager.getEntry(markerId)) return "skipped";
130
-
131
- const currentSemanticLeafId = getSemanticLeafId(ctx);
132
- if (!currentSemanticLeafId || currentSemanticLeafId === markerId) {
133
- return "skipped";
134
- }
158
+ if (!hasReviewLoopIncrement(ctx, markerId)) return "skipped";
135
159
 
136
160
  const clearLoopFeedback = () => {
137
161
  if (ctx.hasUI) ctx.ui.setWidget(REVIEW_LOOP_WIDGET, undefined);
@@ -45,3 +45,14 @@ export function isSubagentFailure(
45
45
  details.stopReason === "aborted"
46
46
  );
47
47
  }
48
+
49
+ export function getFinalOutput(messages: ChildRunDetails["messages"]): string {
50
+ for (let index = messages.length - 1; index >= 0; index--) {
51
+ const message = messages[index];
52
+ if (!message) continue;
53
+ for (const part of message.content) {
54
+ if (part.type === "text") return part.text;
55
+ }
56
+ }
57
+ return "";
58
+ }
package/src/subagent.ts CHANGED
@@ -1,18 +1,27 @@
1
- import { spawn } from "node:child_process";
2
- import { StringDecoder } from "node:string_decoder";
3
- import {
4
- CHILD_ENV,
5
- REVIEW_LABEL,
6
- REVIEW_PROMPT_PATH,
7
- RPC_READY_TIMEOUT_MS,
8
- RPC_RESPONSE_TIMEOUT_MS,
9
- } from "./constants.js";
10
- import { parseReviewRpcFrame, type ReviewRpcFrame } from "./rpc-protocol.js";
1
+ import { join } from "node:path";
2
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
3
+ import { getPackageDir, RpcClient } from "@earendil-works/pi-coding-agent";
4
+ import { CHILD_ENV, REVIEW_LABEL, REVIEW_PROMPT_PATH } from "./constants.js";
11
5
  import { createChildRunDetails } from "./run-details.js";
12
- import type { ResolvedReviewConfig } from "./types.js";
13
-
14
- const sleep = (ms: number) =>
15
- new Promise<void>((resolve) => setTimeout(resolve, ms));
6
+ import type { ChildRunDetails, ResolvedReviewConfig } from "./types.js";
7
+
8
+ const REVIEW_TIMEOUT_MS = 30 * 60 * 1_000;
9
+
10
+ function recordAssistantMessage(
11
+ details: ChildRunDetails,
12
+ message: AssistantMessage,
13
+ ): void {
14
+ details.messages.push(message);
15
+ details.usage.turns++;
16
+ details.usage.input += message.usage.input || 0;
17
+ details.usage.output += message.usage.output || 0;
18
+ details.usage.cacheRead += message.usage.cacheRead || 0;
19
+ details.usage.cacheWrite += message.usage.cacheWrite || 0;
20
+ details.usage.cost += message.usage.cost.total || 0;
21
+ details.usage.contextTokens = message.usage.totalTokens || 0;
22
+ details.stopReason = message.stopReason;
23
+ if (message.errorMessage) details.errorMessage = message.errorMessage;
24
+ }
16
25
 
17
26
  export async function runReviewSubagent(
18
27
  task: string,
@@ -21,225 +30,60 @@ export async function runReviewSubagent(
21
30
  signal?: AbortSignal,
22
31
  ) {
23
32
  const details = createChildRunDetails(task, cwd, config);
24
- const args = [
25
- "--mode",
26
- "rpc",
27
- "--no-session",
28
- "--no-skills",
29
- "--model",
30
- config.model,
31
- "--thinking",
32
- config.thinking,
33
- "--append-system-prompt",
34
- REVIEW_PROMPT_PATH,
35
- ];
36
- const promptText = [
33
+ const client = new RpcClient({
34
+ cliPath: join(getPackageDir(), "dist", "cli.js"),
35
+ cwd,
36
+ env: { [CHILD_ENV]: "1" },
37
+ model: config.model,
38
+ args: [
39
+ "--no-session",
40
+ "--no-skills",
41
+ "--thinking",
42
+ config.thinking,
43
+ "--append-system-prompt",
44
+ REVIEW_PROMPT_PATH,
45
+ ],
46
+ });
47
+ const prompt = [
37
48
  "Run as the Review Subagent inside an isolated no-session RPC subprocess.",
38
49
  "Stay strictly in review mode. Do not edit files or propose implementation plans beyond concise fixes.",
39
50
  "Do not stop after one or two findings; keep looking for additional credible issues, aiming for roughly 10-20 if warranted.",
40
51
  "Mode: review",
41
52
  `Task: ${task}`,
42
53
  ].join("\n\n");
43
-
44
- let processClosed = false;
45
- let processExitCode: number | undefined;
46
- let requestId = 0;
47
- let stoppedAfterCompletion = false;
48
- let stdoutBuffer = "";
49
- const stdoutDecoder = new StringDecoder("utf8");
50
- let resolveSettled!: () => void;
51
- let rejectSettled!: (error: Error) => void;
52
- const settledPromise = new Promise<void>((resolve, reject) => {
53
- resolveSettled = resolve;
54
- rejectSettled = reject;
55
- });
56
- void settledPromise.catch(() => undefined);
57
- const pendingRequests = new Map<
58
- string,
59
- {
60
- resolve: (value: unknown) => void;
61
- reject: (error: Error) => void;
62
- timeout: ReturnType<typeof setTimeout>;
63
- }
64
- >();
65
-
66
- const proc = spawn("pi", args, {
67
- cwd,
68
- shell: false,
69
- stdio: ["pipe", "pipe", "pipe"],
70
- env: { ...process.env, [CHILD_ENV]: "1" },
71
- });
72
-
73
- const rejectPendingRequests = (error: Error) => {
74
- for (const pending of pendingRequests.values()) {
75
- clearTimeout(pending.timeout);
76
- pending.reject(error);
77
- }
78
- pendingRequests.clear();
54
+ const abort = () => {
55
+ void client.abort().catch(() => undefined);
79
56
  };
80
57
 
81
- const sendCommand = <T = unknown>(
82
- command: Record<string, unknown>,
83
- timeoutMs = RPC_RESPONSE_TIMEOUT_MS,
84
- ): Promise<T> => {
85
- if (processClosed || !proc.stdin.writable) {
86
- throw new Error(
87
- `Review subagent RPC process is not available.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`,
88
- );
89
- }
90
-
91
- const id = `req_${++requestId}`;
92
- const payload = JSON.stringify({ ...command, id }) + "\n";
93
-
94
- return new Promise<T>((resolve, reject) => {
95
- const timeout = setTimeout(() => {
96
- pendingRequests.delete(id);
97
- reject(
98
- new Error(
99
- `Timed out waiting for RPC response to ${String(command["type"])}.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`,
100
- ),
101
- );
102
- }, timeoutMs);
103
-
104
- pendingRequests.set(id, {
105
- resolve: (value) => resolve(value as T),
106
- reject,
107
- timeout,
108
- });
109
- proc.stdin.write(payload, (error) => {
110
- if (!error) return;
111
- clearTimeout(timeout);
112
- pendingRequests.delete(id);
113
- reject(error instanceof Error ? error : new Error(String(error)));
114
- });
115
- });
116
- };
117
-
118
- const handleEvent = (event: ReviewRpcFrame) => {
119
- if (event.type === "message_end") {
120
- const message = event.message;
121
- details.messages.push(message);
122
- if (message.role === "assistant") {
123
- details.usage.turns++;
124
- const usage = message.usage;
125
- if (usage) {
126
- details.usage.input += usage.input || 0;
127
- details.usage.output += usage.output || 0;
128
- details.usage.cacheRead += usage.cacheRead || 0;
129
- details.usage.cacheWrite += usage.cacheWrite || 0;
130
- details.usage.cost += usage.cost?.total || 0;
131
- details.usage.contextTokens = usage.totalTokens || 0;
132
- }
133
- if (message.stopReason) details.stopReason = message.stopReason;
134
- if (message.errorMessage) details.errorMessage = message.errorMessage;
135
- }
136
- return;
137
- }
138
-
139
- if (event.type === "agent_settled") resolveSettled();
140
- };
141
-
142
- const handleLine = (line: string) => {
143
- const frame = parseReviewRpcFrame(line);
144
- if (!frame) return;
145
-
146
- if (frame.type === "response" && pendingRequests.has(frame.id)) {
147
- const pending = pendingRequests.get(frame.id);
148
- if (!pending) return;
149
- clearTimeout(pending.timeout);
150
- pendingRequests.delete(frame.id);
151
- if (!frame.success)
152
- pending.reject(
153
- new Error(
154
- frame.error ?? `RPC ${String(frame.command ?? "command")} failed`,
155
- ),
156
- );
157
- else pending.resolve(frame.data);
158
- return;
159
- }
160
-
161
- handleEvent(frame);
162
- };
163
-
164
- const stopProcess = async () => {
165
- if (processClosed) return;
166
- stoppedAfterCompletion = true;
167
- proc.kill("SIGTERM");
168
- await Promise.race([
169
- new Promise<void>((resolve) => proc.once("close", () => resolve())),
170
- sleep(1_000).then(() => {
171
- if (!processClosed) proc.kill("SIGKILL");
172
- }),
173
- ]);
174
- };
175
-
176
- const abortProcess = () => {
177
- rejectSettled(new Error(`${REVIEW_LABEL} aborted.`));
178
- void stopProcess();
179
- };
180
- signal?.addEventListener("abort", abortProcess, { once: true });
181
-
182
- proc.stdout.on("data", (chunk) => {
183
- stdoutBuffer += stdoutDecoder.write(chunk);
184
- const lines = stdoutBuffer.split("\n");
185
- stdoutBuffer = lines.pop() || "";
186
- for (const line of lines)
187
- handleLine(line.endsWith("\r") ? line.slice(0, -1) : line);
188
- });
189
- proc.stdout.on("end", () => {
190
- stdoutBuffer += stdoutDecoder.end();
191
- });
192
-
193
- proc.stderr.on("data", (chunk) => {
194
- details.stderr += chunk.toString();
195
- });
196
-
197
- proc.on("close", (code) => {
198
- processClosed = true;
199
- processExitCode = code ?? 0;
200
- if (stdoutBuffer.trim()) {
201
- handleLine(
202
- stdoutBuffer.endsWith("\r") ? stdoutBuffer.slice(0, -1) : stdoutBuffer,
203
- );
204
- stdoutBuffer = "";
205
- }
206
- rejectPendingRequests(
207
- new Error(
208
- `Review subagent RPC process exited with code ${processExitCode}.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`,
209
- ),
210
- );
211
- if (!stoppedAfterCompletion) {
212
- rejectSettled(
213
- new Error(
214
- `Review subagent exited before agent_settled.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`,
215
- ),
216
- );
217
- }
218
- });
219
-
220
- proc.on("error", (error) => {
221
- const processError =
222
- error instanceof Error ? error : new Error(String(error));
223
- rejectPendingRequests(processError);
224
- rejectSettled(processError);
225
- });
226
-
227
58
  try {
228
59
  if (signal?.aborted) throw new Error(`${REVIEW_LABEL} aborted.`);
229
- await sendCommand({ type: "get_state" }, RPC_READY_TIMEOUT_MS);
60
+ await client.start();
61
+ signal?.addEventListener("abort", abort, { once: true });
62
+ if (signal?.aborted) throw new Error(`${REVIEW_LABEL} aborted.`);
63
+ await client.setAutoCompaction(true);
64
+ await client.setAutoRetry(true);
230
65
  if (signal?.aborted) throw new Error(`${REVIEW_LABEL} aborted.`);
231
- await sendCommand({ type: "set_auto_compaction", enabled: true });
232
- await sendCommand({ type: "set_auto_retry", enabled: true });
233
- await sendCommand({ type: "prompt", message: promptText });
234
- await settledPromise;
66
+ const events = await client.promptAndWait(
67
+ prompt,
68
+ undefined,
69
+ REVIEW_TIMEOUT_MS,
70
+ );
71
+ for (const event of events) {
72
+ if (event.type === "message_end" && event.message.role === "assistant") {
73
+ recordAssistantMessage(details, event.message);
74
+ }
75
+ }
76
+ } catch (error) {
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ const stderr = client.getStderr().trim();
79
+ if (!stderr || message.includes(stderr)) throw error;
80
+ throw new Error(`${message}\nStderr: ${stderr}`, { cause: error });
235
81
  } finally {
236
- signal?.removeEventListener("abort", abortProcess);
237
- await stopProcess();
82
+ signal?.removeEventListener("abort", abort);
83
+ await client.stop();
238
84
  }
239
85
 
240
- details.exitCode = stoppedAfterCompletion ? 0 : (processExitCode ?? 0);
241
- if (details.exitCode !== 0 && !details.errorMessage) {
242
- details.errorMessage = `${REVIEW_LABEL} subagent exited with code ${details.exitCode}`;
243
- }
86
+ details.stderr = client.getStderr();
87
+ details.exitCode = 0;
244
88
  return details;
245
89
  }
package/src/types.ts CHANGED
@@ -1,4 +1,7 @@
1
- import type { Message, ModelThinkingLevel } from "@earendil-works/pi-ai";
1
+ import type {
2
+ AssistantMessage,
3
+ ModelThinkingLevel,
4
+ } from "@earendil-works/pi-ai";
2
5
 
3
6
  export type ThinkingLevel = ModelThinkingLevel;
4
7
 
@@ -51,7 +54,7 @@ export interface ChildRunDetails {
51
54
  cwd: string;
52
55
  model: string;
53
56
  thinking?: ThinkingLevel;
54
- messages: Message[];
57
+ messages: AssistantMessage[];
55
58
  stderr: string;
56
59
  exitCode: number;
57
60
  stopReason?: string;
@@ -1,79 +0,0 @@
1
- import type { AssistantMessage, Message } from "@earendil-works/pi-ai";
2
-
3
- export type ReviewRpcFrame =
4
- | {
5
- type: "response";
6
- id: string;
7
- success: boolean;
8
- data?: unknown;
9
- error?: string;
10
- command?: unknown;
11
- }
12
- | { type: "message_end"; message: Message }
13
- | { type: "agent_settled" };
14
-
15
- function isRecord(value: unknown): value is Record<string, unknown> {
16
- return typeof value === "object" && value !== null;
17
- }
18
-
19
- function isContentBlocks(value: unknown): boolean {
20
- return (
21
- Array.isArray(value) &&
22
- value.every((part) => isRecord(part) && typeof part["type"] === "string")
23
- );
24
- }
25
-
26
- function isMessage(value: unknown): value is Message {
27
- if (!isRecord(value)) return false;
28
- if (value["role"] === "user") {
29
- return (
30
- typeof value["content"] === "string" || isContentBlocks(value["content"])
31
- );
32
- }
33
- return (
34
- (value["role"] === "assistant" || value["role"] === "toolResult") &&
35
- isContentBlocks(value["content"])
36
- );
37
- }
38
-
39
- function isAssistantMessage(message: Message): message is AssistantMessage {
40
- return message.role === "assistant";
41
- }
42
-
43
- export function parseReviewRpcFrame(line: string): ReviewRpcFrame | undefined {
44
- if (!line.trim()) return undefined;
45
- let value: unknown;
46
- try {
47
- value = JSON.parse(line) as unknown;
48
- } catch {
49
- return undefined;
50
- }
51
- if (!isRecord(value)) return undefined;
52
-
53
- if (value["type"] === "response" && typeof value["id"] === "string") {
54
- return {
55
- type: "response",
56
- id: value["id"],
57
- success: value["success"] !== false,
58
- ...(value["data"] !== undefined ? { data: value["data"] } : {}),
59
- ...(typeof value["error"] === "string" ? { error: value["error"] } : {}),
60
- ...(value["command"] !== undefined ? { command: value["command"] } : {}),
61
- };
62
- }
63
- if (value["type"] === "message_end" && isMessage(value["message"])) {
64
- return { type: "message_end", message: value["message"] };
65
- }
66
- if (value["type"] === "agent_settled") return { type: "agent_settled" };
67
- return undefined;
68
- }
69
-
70
- export function getFinalOutput(messages: Message[]): string {
71
- for (let index = messages.length - 1; index >= 0; index--) {
72
- const message = messages[index];
73
- if (!message || !isAssistantMessage(message)) continue;
74
- for (const part of message.content) {
75
- if (part.type === "text") return part.text;
76
- }
77
- }
78
- return "";
79
- }