pi-openai-toolkit 0.15.1 → 0.16.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.
@@ -1,335 +1,325 @@
1
- import type {
2
- Api,
3
- AssistantMessage,
4
- Context,
5
- Message,
6
- Model,
7
- Tool,
8
- ToolCall,
9
- } from "@earendil-works/pi-ai";
10
- import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
11
- import { parseModelSpec } from "../runtime";
12
- import { backfillVerdictFields, buildReviewPrompt, reviewerSystemPrompt } from "./prompt";
13
- import {
14
- boundReviewText,
15
- type GuardianVerdict,
16
- MAX_REVIEW_MODEL_KEY_CHARS,
17
- type ReviewFailureCause,
18
- type ReviewOutcome,
19
- type RiskLevel,
20
- type UserAuthorization,
21
- } from "./types";
22
-
23
- /** The reviewer needs model lookup plus whatever read-only tools we choose to give it. */
24
- export type ReviewerRegistry = Pick<ModelRegistry, "find" | "complete">;
25
-
26
- /**
27
- * One read-only investigation tool the reviewer may call. `parameters` is passed to
28
- * the provider verbatim; `execute` is ours, so the reviewer can never reach a tool
29
- * that is not in this list.
30
- */
31
- export type EvidenceTool = {
32
- name: string;
33
- description: string;
34
- parameters: Tool["parameters"];
35
- execute: (
36
- args: Record<string, unknown>,
37
- signal: AbortSignal | undefined,
38
- ) => Promise<string>;
39
- };
40
-
41
- const RISK_LEVELS: readonly string[] = ["low", "medium", "high", "critical"];
42
- const AUTHORIZATIONS: readonly string[] = ["unknown", "low", "medium", "high"];
43
-
44
- /**
45
- * Parse a reviewer answer. Only the outcome is required; risk, authorization, and
46
- * rationale are back-filled. Both the Codex-style field names and our earlier
47
- * `decision`/`reason` spelling are accepted, so an older reviewer prompt cached by
48
- * a provider still yields a usable verdict.
49
- *
50
- * A verdict we cannot read is reported as a failure, never guessed into approval.
51
- */
52
- export function parseReviewVerdict(text: string): GuardianVerdict | undefined {
53
- for (const candidate of candidateJsonObjects(text)) {
54
- let parsed: unknown;
55
- try {
56
- parsed = JSON.parse(candidate);
57
- } catch {
58
- continue;
59
- }
60
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
61
- const record = parsed as Record<string, unknown>;
62
- const rawOutcome = record.outcome ?? record.decision;
63
- if (rawOutcome !== "allow" && rawOutcome !== "deny") continue;
64
- const risk = String(record.risk_level ?? record.riskLevel ?? "").toLowerCase();
65
- const authorization = String(
66
- record.user_authorization ?? record.userAuthorization ?? "",
67
- ).toLowerCase();
68
- const rationale =
69
- typeof record.rationale === "string"
70
- ? record.rationale
71
- : typeof record.reason === "string"
72
- ? record.reason
73
- : undefined;
74
- return backfillVerdictFields({
75
- outcome: rawOutcome,
76
- riskLevel: (RISK_LEVELS.includes(risk) ? risk : undefined) as RiskLevel | undefined,
77
- userAuthorization: (AUTHORIZATIONS.includes(authorization) ? authorization : undefined) as
78
- | UserAuthorization
79
- | undefined,
80
- rationale,
81
- });
82
- }
83
- return undefined;
84
- }
85
-
86
- function candidateJsonObjects(text: string): string[] {
87
- const candidates: string[] = [];
88
- const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
89
- if (fenced?.[1]) candidates.push(fenced[1].trim());
90
- candidates.push(text.trim());
91
- const brace = text.match(/\{[\s\S]*\}/);
92
- if (brace?.[0]) candidates.push(brace[0]);
93
- return candidates;
94
- }
95
-
96
- function firstTextBlock(message: AssistantMessage): string {
97
- return message.content
98
- .filter((block): block is { type: "text"; text: string } => block.type === "text")
99
- .map((block) => block.text)
100
- .join("")
101
- .trim();
102
- }
103
-
104
- /**
105
- * Pi 0.85 typed tool-call arguments as `Record<string, any>` and Pi 0.86 tightened
106
- * them to the public `JsonObject`. Narrow with Pi's exported `ToolCall` instead of a
107
- * handwritten shape so the guard tracks whichever contract the installed Pi declares.
108
- */
109
- function toolCallBlocks(message: AssistantMessage): ToolCall[] {
110
- return message.content.filter((block): block is ToolCall => block.type === "toolCall");
111
- }
112
-
113
- type CompletionAttempt = {
114
- response?: AssistantMessage;
115
- errorMessage?: string;
116
- timedOut: boolean;
117
- cancelled: boolean;
118
- };
119
-
120
- async function completeBefore(
121
- registry: ReviewerRegistry,
122
- model: Model<Api>,
123
- context: Context,
124
- deadlineAt: number,
125
- callerSignal?: AbortSignal,
126
- ): Promise<CompletionAttempt> {
127
- const remaining = deadlineAt - Date.now();
128
- if (remaining <= 0) {
129
- return { timedOut: true, cancelled: Boolean(callerSignal?.aborted) };
130
- }
131
-
132
- const controller = new AbortController();
133
- let timedOut = false;
134
- let cancelled = false;
135
- const abortFromCaller = () => {
136
- cancelled = true;
137
- controller.abort();
138
- };
139
- if (callerSignal?.aborted) {
140
- cancelled = true;
141
- controller.abort();
142
- } else {
143
- callerSignal?.addEventListener("abort", abortFromCaller);
144
- }
145
- const timer = setTimeout(() => {
146
- timedOut = true;
147
- controller.abort();
148
- }, remaining);
149
-
150
- try {
151
- const response = await registry.complete(model, context, {
152
- signal: controller.signal,
153
- cacheRetention: "none",
154
- });
155
- return { response, timedOut, cancelled };
156
- } catch (error) {
157
- const message = error instanceof Error ? error.message : String(error);
158
- return { errorMessage: message, timedOut, cancelled };
159
- } finally {
160
- clearTimeout(timer);
161
- callerSignal?.removeEventListener("abort", abortFromCaller);
162
- }
163
- }
164
-
165
- function failure(cause: ReviewFailureCause, reason: string): ReviewOutcome {
166
- return { kind: "unavailable", reason: boundReviewText(reason, 240), cause };
167
- }
168
-
169
- function outcomeFromVerdict(
170
- verdict: GuardianVerdict,
171
- reviewerModel: string,
172
- evidenceRounds: number,
173
- ): ReviewOutcome {
174
- return verdict.outcome === "allow"
175
- ? { kind: "allow", verdict, reviewerModel, evidenceRounds }
176
- : { kind: "deny", verdict, reviewerModel, evidenceRounds };
177
- }
178
-
179
- /**
180
- * Ask the reviewer model about one pending tool call.
181
- *
182
- * When `evidenceTools` are supplied the reviewer runs as a short bounded agent
183
- * loop: it may call read-only tools to establish facts, we execute those calls
184
- * ourselves, and we feed the results back. The whole exchange shares one deadline,
185
- * and the final round is forced to answer without tools, so a reviewer that keeps
186
- * investigating still terminates as a verdict or as an explicit failure.
187
- */
188
- export async function requestToolReview(params: {
189
- registry: ReviewerRegistry;
190
- reviewerModelSpec: string;
191
- toolName: string;
192
- toolInput: unknown;
193
- transcript?: string;
194
- cwd?: string;
195
- timeoutMs: number;
196
- signal?: AbortSignal;
197
- evidenceTools?: EvidenceTool[];
198
- maxEvidenceRounds?: number;
199
- }): Promise<ReviewOutcome> {
200
- const parsed = parseModelSpec(params.reviewerModelSpec);
201
- if (!parsed) {
202
- return failure(
203
- "not-configured",
204
- `autoMode.reviewerModel "${params.reviewerModelSpec}" is not provider/model-id.`,
205
- );
206
- }
207
-
208
- const model = params.registry.find(parsed.provider, parsed.modelId);
209
- if (!model) {
210
- return failure("not-configured", `Reviewer model ${params.reviewerModelSpec} is not available.`);
211
- }
212
- const reviewerModel = boundReviewText(`${model.provider}/${model.id}`, MAX_REVIEW_MODEL_KEY_CHARS);
213
-
214
- const tools = params.evidenceTools ?? [];
215
- const maxRounds = Math.max(0, params.maxEvidenceRounds ?? 0);
216
- const useTools = tools.length > 0 && maxRounds > 0;
217
- const toolByName = new Map(tools.map((tool) => [tool.name, tool]));
218
- const deadlineAt = Date.now() + params.timeoutMs;
219
- const messages: Message[] = [
220
- {
221
- role: "user",
222
- content: [
223
- {
224
- type: "text",
225
- text: buildReviewPrompt({
226
- toolName: params.toolName,
227
- toolInput: params.toolInput,
228
- transcript: params.transcript,
229
- cwd: params.cwd,
230
- }),
231
- },
232
- ],
233
- timestamp: Date.now(),
234
- },
235
- ];
236
-
237
- let evidenceRounds = 0;
238
- for (let round = 0; ; round += 1) {
239
- const forceAnswer = !useTools || round >= maxRounds;
240
- const context: Context = {
241
- systemPrompt: reviewerSystemPrompt(useTools),
242
- messages,
243
- ...(forceAnswer ? {} : { tools: tools.map(toProviderTool) }),
244
- };
245
-
246
- const attempt = await completeBefore(params.registry, model, context, deadlineAt, params.signal);
247
- if (attempt.cancelled) {
248
- return failure("cancelled", "Auto-mode review was cancelled before it finished.");
249
- }
250
- if (attempt.timedOut) {
251
- return failure("timeout", `Auto-mode review timed out after ${params.timeoutMs}ms.`);
252
- }
253
- if (attempt.errorMessage) {
254
- return failure("provider-error", attempt.errorMessage);
255
- }
256
- const response = attempt.response;
257
- if (!response) {
258
- return failure("provider-error", "Reviewer returned no message.");
259
- }
260
- if (response.stopReason === "error" || response.stopReason === "aborted") {
261
- return failure(
262
- "provider-error",
263
- response.errorMessage ?? `Reviewer stopped with "${response.stopReason}".`,
264
- );
265
- }
266
-
267
- const calls = toolCallBlocks(response);
268
- if (forceAnswer || calls.length === 0) {
269
- const verdict = parseReviewVerdict(firstTextBlock(response));
270
- if (!verdict) {
271
- return failure("invalid-output", "Reviewer did not return a readable allow/deny verdict.");
272
- }
273
- return outcomeFromVerdict(verdict, reviewerModel, evidenceRounds);
274
- }
275
-
276
- messages.push(response);
277
- evidenceRounds += 1;
278
- for (const call of calls) {
279
- const tool = toolByName.get(call.name);
280
- if (!tool) {
281
- messages.push(refusedToolResult(call, `Tool "${call.name}" is not available to the reviewer.`));
282
- continue;
283
- }
284
- if (params.signal?.aborted) {
285
- return failure("cancelled", "Auto-mode review was cancelled during investigation.");
286
- }
287
- try {
288
- const text = await tool.execute(call.arguments, params.signal);
289
- messages.push({
290
- role: "toolResult",
291
- toolCallId: call.id,
292
- toolName: call.name,
293
- content: [{ type: "text", text: boundReviewText(text, 4_000) }],
294
- isError: false,
295
- timestamp: Date.now(),
296
- });
297
- } catch (error) {
298
- messages.push({
299
- role: "toolResult",
300
- toolCallId: call.id,
301
- toolName: call.name,
302
- content: [
303
- {
304
- type: "text",
305
- text: boundReviewText(
306
- error instanceof Error ? error.message : String(error),
307
- 1_000,
308
- ),
309
- },
310
- ],
311
- isError: true,
312
- timestamp: Date.now(),
313
- });
314
- }
315
- }
316
- }
317
- }
318
-
319
- function toProviderTool(tool: EvidenceTool): Tool {
320
- return { name: tool.name, description: tool.description, parameters: tool.parameters };
321
- }
322
-
323
- function refusedToolResult(
324
- call: { id: string; name: string },
325
- text: string,
326
- ): Message {
327
- return {
328
- role: "toolResult",
329
- toolCallId: call.id,
330
- toolName: call.name,
331
- content: [{ type: "text", text }],
332
- isError: true,
333
- timestamp: Date.now(),
334
- };
335
- }
1
+ import type {
2
+ AssistantMessage,
3
+ Context,
4
+ Message,
5
+ Tool,
6
+ ToolCall,
7
+ } from "@earendil-works/pi-ai";
8
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
9
+ import { parseModelSpec } from "../runtime";
10
+ import { backfillVerdictFields, buildReviewPrompt, reviewerSystemPrompt } from "./prompt";
11
+ import {
12
+ boundReviewText,
13
+ type GuardianVerdict,
14
+ MAX_REVIEW_MODEL_KEY_CHARS,
15
+ type ReviewFailureCause,
16
+ type ReviewOutcome,
17
+ type RiskLevel,
18
+ type UserAuthorization,
19
+ } from "./types";
20
+
21
+ /** The reviewer needs model lookup plus whatever read-only tools we choose to give it. */
22
+ export type ReviewerRegistry = Pick<ModelRegistry, "find" | "complete">;
23
+
24
+ /**
25
+ * One read-only investigation tool the reviewer may call. `parameters` is passed to
26
+ * the provider verbatim; `execute` is ours, so the reviewer can never reach a tool
27
+ * that is not in this list.
28
+ */
29
+ export type EvidenceTool = {
30
+ name: string;
31
+ description: string;
32
+ parameters: Tool["parameters"];
33
+ execute: (
34
+ args: Record<string, unknown>,
35
+ signal: AbortSignal | undefined,
36
+ ) => Promise<string>;
37
+ };
38
+
39
+ const RISK_LEVELS: readonly string[] = ["low", "medium", "high", "critical"];
40
+ const AUTHORIZATIONS: readonly string[] = ["unknown", "low", "medium", "high"];
41
+
42
+ /**
43
+ * Parse a reviewer answer. Only the outcome is required; risk, authorization, and
44
+ * rationale are back-filled. Both the Codex-style field names and our earlier
45
+ * `decision`/`reason` spelling are accepted, so an older reviewer prompt cached by
46
+ * a provider still yields a usable verdict.
47
+ *
48
+ * A verdict we cannot read is reported as a failure, never guessed into approval.
49
+ */
50
+ export function parseReviewVerdict(text: string): GuardianVerdict | undefined {
51
+ for (const candidate of candidateJsonObjects(text)) {
52
+ let parsed: unknown;
53
+ try {
54
+ parsed = JSON.parse(candidate);
55
+ } catch {
56
+ continue;
57
+ }
58
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
59
+ const record = parsed as Record<string, unknown>;
60
+ const rawOutcome = record.outcome ?? record.decision;
61
+ if (rawOutcome !== "allow" && rawOutcome !== "deny") continue;
62
+ const risk = String(record.risk_level ?? record.riskLevel ?? "").toLowerCase();
63
+ const authorization = String(
64
+ record.user_authorization ?? record.userAuthorization ?? "",
65
+ ).toLowerCase();
66
+ const rationale =
67
+ typeof record.rationale === "string"
68
+ ? record.rationale
69
+ : typeof record.reason === "string"
70
+ ? record.reason
71
+ : undefined;
72
+ return backfillVerdictFields({
73
+ outcome: rawOutcome,
74
+ riskLevel: (RISK_LEVELS.includes(risk) ? risk : undefined) as RiskLevel | undefined,
75
+ userAuthorization: (AUTHORIZATIONS.includes(authorization) ? authorization : undefined) as
76
+ | UserAuthorization
77
+ | undefined,
78
+ rationale,
79
+ });
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ function candidateJsonObjects(text: string): string[] {
85
+ const candidates: string[] = [];
86
+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
87
+ if (fenced?.[1]) candidates.push(fenced[1].trim());
88
+ candidates.push(text.trim());
89
+ const brace = text.match(/\{[\s\S]*\}/);
90
+ if (brace?.[0]) candidates.push(brace[0]);
91
+ return candidates;
92
+ }
93
+
94
+ function firstTextBlock(message: AssistantMessage): string {
95
+ return message.content
96
+ .filter((block): block is { type: "text"; text: string } => block.type === "text")
97
+ .map((block) => block.text)
98
+ .join("")
99
+ .trim();
100
+ }
101
+
102
+ /**
103
+ * Pi 0.85 typed tool-call arguments as `Record<string, any>` and Pi 0.86 tightened
104
+ * them to the public `JsonObject`. Narrow with Pi's exported `ToolCall` instead of a
105
+ * handwritten shape so the guard tracks whichever contract the installed Pi declares.
106
+ */
107
+ function toolCallBlocks(message: AssistantMessage): ToolCall[] {
108
+ return message.content.filter((block): block is ToolCall => block.type === "toolCall");
109
+ }
110
+
111
+ type ReviewAttempt<T> = {
112
+ value?: T;
113
+ errorMessage?: string;
114
+ timedOut: boolean;
115
+ cancelled: boolean;
116
+ };
117
+
118
+ /** One deadline owns every model and evidence operation in this review. */
119
+ function createReviewDeadline(timeoutMs: number, callerSignal?: AbortSignal) {
120
+ const deadlineAt = Date.now() + timeoutMs;
121
+ const controller = new AbortController();
122
+ let timedOut = false;
123
+ let cancelled = false;
124
+ const abortFromCaller = () => {
125
+ if (controller.signal.aborted) return;
126
+ cancelled = true;
127
+ controller.abort();
128
+ };
129
+ const expire = () => {
130
+ if (controller.signal.aborted) return;
131
+ timedOut = true;
132
+ controller.abort();
133
+ };
134
+ if (callerSignal?.aborted) abortFromCaller();
135
+ else callerSignal?.addEventListener("abort", abortFromCaller, { once: true });
136
+ const timer = setTimeout(expire, Math.max(0, timeoutMs));
137
+
138
+ return {
139
+ async run<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<ReviewAttempt<T>> {
140
+ if (Date.now() >= deadlineAt) expire();
141
+ if (controller.signal.aborted) return { timedOut, cancelled };
142
+ let onAbort!: () => void;
143
+ const aborted = new Promise<ReviewAttempt<T>>((resolve) => {
144
+ onAbort = () => resolve({ timedOut, cancelled });
145
+ controller.signal.addEventListener("abort", onAbort, { once: true });
146
+ });
147
+ try {
148
+ // Both settlement handlers stay attached after cancellation, so an
149
+ // uncooperative dependency cannot leak an unhandled rejection.
150
+ const pending = Promise.resolve().then(() => {
151
+ controller.signal.throwIfAborted();
152
+ return operation(controller.signal);
153
+ }).then(
154
+ (value): ReviewAttempt<T> => ({ value, timedOut, cancelled }),
155
+ (error): ReviewAttempt<T> => ({ errorMessage: error instanceof Error ? error.message : String(error), timedOut, cancelled }),
156
+ );
157
+ const result = await Promise.race([pending, aborted]);
158
+ if (Date.now() >= deadlineAt) expire();
159
+ return { ...result, timedOut, cancelled };
160
+ } finally {
161
+ controller.signal.removeEventListener("abort", onAbort);
162
+ }
163
+ },
164
+ dispose() {
165
+ clearTimeout(timer);
166
+ callerSignal?.removeEventListener("abort", abortFromCaller);
167
+ },
168
+ };
169
+ }
170
+
171
+ function failure(cause: ReviewFailureCause, reason: string): ReviewOutcome {
172
+ return { kind: "unavailable", reason: boundReviewText(reason, 240), cause };
173
+ }
174
+
175
+ function outcomeFromVerdict(
176
+ verdict: GuardianVerdict,
177
+ reviewerModel: string,
178
+ evidenceRounds: number,
179
+ ): ReviewOutcome {
180
+ return verdict.outcome === "allow"
181
+ ? { kind: "allow", verdict, reviewerModel, evidenceRounds }
182
+ : { kind: "deny", verdict, reviewerModel, evidenceRounds };
183
+ }
184
+
185
+ /**
186
+ * Ask the reviewer model about one pending tool call.
187
+ *
188
+ * When `evidenceTools` are supplied the reviewer runs as a short bounded agent
189
+ * loop: it may call read-only tools to establish facts, we execute those calls
190
+ * ourselves, and we feed the results back. The whole exchange shares one deadline,
191
+ * and the final round is forced to answer without tools, so a reviewer that keeps
192
+ * investigating still terminates as a verdict or as an explicit failure.
193
+ */
194
+ export async function requestToolReview(params: {
195
+ registry: ReviewerRegistry;
196
+ reviewerModelSpec: string;
197
+ toolName: string;
198
+ toolInput: unknown;
199
+ transcript?: string;
200
+ cwd?: string;
201
+ timeoutMs: number;
202
+ signal?: AbortSignal;
203
+ evidenceTools?: EvidenceTool[];
204
+ maxEvidenceRounds?: number;
205
+ }): Promise<ReviewOutcome> {
206
+ const parsed = parseModelSpec(params.reviewerModelSpec);
207
+ if (!parsed) {
208
+ return failure(
209
+ "not-configured",
210
+ `autoMode.reviewerModel "${params.reviewerModelSpec}" is not provider/model-id.`,
211
+ );
212
+ }
213
+
214
+ const model = params.registry.find(parsed.provider, parsed.modelId);
215
+ if (!model) {
216
+ return failure("not-configured", `Reviewer model ${params.reviewerModelSpec} is not available.`);
217
+ }
218
+ const reviewerModel = boundReviewText(`${model.provider}/${model.id}`, MAX_REVIEW_MODEL_KEY_CHARS);
219
+
220
+ const tools = params.evidenceTools ?? [];
221
+ const maxRounds = Math.max(0, params.maxEvidenceRounds ?? 0);
222
+ const useTools = tools.length > 0 && maxRounds > 0;
223
+ const toolByName = new Map(tools.map((tool) => [tool.name, tool]));
224
+ const messages: Message[] = [
225
+ {
226
+ role: "user",
227
+ content: [
228
+ {
229
+ type: "text",
230
+ text: buildReviewPrompt({
231
+ toolName: params.toolName,
232
+ toolInput: params.toolInput,
233
+ transcript: params.transcript,
234
+ cwd: params.cwd,
235
+ }),
236
+ },
237
+ ],
238
+ timestamp: Date.now(),
239
+ },
240
+ ];
241
+
242
+ const deadline = createReviewDeadline(params.timeoutMs, params.signal);
243
+ try {
244
+ let evidenceRounds = 0;
245
+ for (let round = 0; ; round += 1) {
246
+ const forceAnswer = !useTools || round >= maxRounds;
247
+ const context: Context = {
248
+ systemPrompt: reviewerSystemPrompt(useTools),
249
+ messages,
250
+ ...(forceAnswer ? {} : { tools: tools.map(toProviderTool) }),
251
+ };
252
+
253
+ const attempt = await deadline.run((signal) => params.registry.complete(model, context, { signal, cacheRetention: "none" }));
254
+ if (attempt.cancelled) {
255
+ return failure("cancelled", "Auto-mode review was cancelled before it finished.");
256
+ }
257
+ if (attempt.timedOut) {
258
+ return failure("timeout", `Auto-mode review timed out after ${params.timeoutMs}ms.`);
259
+ }
260
+ if (attempt.errorMessage) {
261
+ return failure("provider-error", attempt.errorMessage);
262
+ }
263
+ const response = attempt.value;
264
+ if (!response) {
265
+ return failure("provider-error", "Reviewer returned no message.");
266
+ }
267
+ if (response.stopReason === "error" || response.stopReason === "aborted") {
268
+ return failure(
269
+ "provider-error",
270
+ response.errorMessage ?? `Reviewer stopped with "${response.stopReason}".`,
271
+ );
272
+ }
273
+
274
+ const calls = toolCallBlocks(response);
275
+ if (forceAnswer || calls.length === 0) {
276
+ const verdict = parseReviewVerdict(firstTextBlock(response));
277
+ if (!verdict) {
278
+ return failure("invalid-output", "Reviewer did not return a readable allow/deny verdict.");
279
+ }
280
+ return outcomeFromVerdict(verdict, reviewerModel, evidenceRounds);
281
+ }
282
+
283
+ messages.push(response);
284
+ evidenceRounds += 1;
285
+ for (const call of calls) {
286
+ const tool = toolByName.get(call.name);
287
+ if (!tool) {
288
+ messages.push(refusedToolResult(call, `Tool "${call.name}" is not available to the reviewer.`));
289
+ continue;
290
+ }
291
+ const evidence = await deadline.run((signal) => tool.execute(call.arguments, signal));
292
+ if (evidence.cancelled) return failure("cancelled", "Auto-mode review was cancelled during investigation.");
293
+ if (evidence.timedOut) return failure("timeout", `Auto-mode review timed out after ${params.timeoutMs}ms.`);
294
+ messages.push({
295
+ role: "toolResult",
296
+ toolCallId: call.id,
297
+ toolName: call.name,
298
+ content: [{ type: "text", text: boundReviewText(evidence.errorMessage ?? evidence.value ?? "", evidence.errorMessage ? 1_000 : 4_000) }],
299
+ isError: evidence.errorMessage !== undefined,
300
+ timestamp: Date.now(),
301
+ });
302
+ }
303
+ }
304
+ } finally {
305
+ deadline.dispose();
306
+ }
307
+ }
308
+
309
+ function toProviderTool(tool: EvidenceTool): Tool {
310
+ return { name: tool.name, description: tool.description, parameters: tool.parameters };
311
+ }
312
+
313
+ function refusedToolResult(
314
+ call: { id: string; name: string },
315
+ text: string,
316
+ ): Message {
317
+ return {
318
+ role: "toolResult",
319
+ toolCallId: call.id,
320
+ toolName: call.name,
321
+ content: [{ type: "text", text }],
322
+ isError: true,
323
+ timestamp: Date.now(),
324
+ };
325
+ }