1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
|
import type { TSchema, Static } from "typebox";
import type {
AgentToolResult,
AgentToolUpdateCallback,
ExtensionAPI,
ExtensionContext,
Theme,
ToolDefinition,
ToolRenderResultOptions,
} from "@mariozechner/pi-coding-agent";
import type { Component } from "@mariozechner/pi-tui";
import type { BrowserClient } from "../client";
import type { Result } from "./result";
export type ToolOk = {
readonly text: string;
readonly details?: Readonly<Record<string, unknown>>;
};
export type ToolErrKind =
| "not_connected"
| "cdp_error"
| "timeout"
| "invalid_state"
| "io_error"
| "internal";
export type ToolErr = {
readonly kind: ToolErrKind;
readonly message: string;
readonly details?: Readonly<Record<string, unknown>>;
};
export type HandlerContext = {
readonly client: BrowserClient;
readonly signal: AbortSignal | undefined;
readonly onUpdate: (update: ToolOk) => void;
readonly extensionCtx: ExtensionContext;
};
export type ToolHandler<S extends TSchema> = (
args: Static<S>,
ctx: HandlerContext,
) => Promise<Result<ToolOk, ToolErr>>;
export type BrowserToolDefinition<S extends TSchema> = {
readonly name: string;
readonly label: string;
readonly description: string;
readonly promptSnippet: string;
readonly promptGuidelines: ReadonlyArray<string>;
readonly parameters: S;
readonly handler: ToolHandler<S>;
readonly renderCall?: (args: Static<S>, theme: Theme) => Component;
readonly renderResult?: (result: AgentToolResult<unknown>, expanded: boolean, theme: Theme) => Component;
/** If true, the tool acquires the client's mutation mutex before executing.
* This ensures that two serialized tools never run concurrently,
* preventing race conditions on shared CDP session/page state. */
readonly serialized?: boolean;
readonly ensureAlive?: boolean;
};
// Type-erased entry for the registry's heterogeneous TOOLS array.
// renderCall accepts `never` so any concrete args type satisfies it via
// function-parameter contravariance (a handler that takes SpecificT is
// assignable to one that takes never, because never is a subtype of everything).
export type AnyBrowserToolDefinition = Omit<BrowserToolDefinition<TSchema>, "renderCall" | "renderResult"> & {
readonly renderCall?: (args: never, theme: Theme) => Component;
readonly renderResult?: (result: AgentToolResult<unknown>, expanded: boolean, theme: Theme) => Component;
};
export const defineBrowserTool = <S extends TSchema>(
def: BrowserToolDefinition<S>,
): BrowserToolDefinition<S> => def;
type OkDetails = { readonly ok: true } & Readonly<Record<string, unknown>>;
type ErrDetails = { readonly ok: false; readonly kind: ToolErrKind; readonly message: string } & Readonly<Record<string, unknown>>;
const toToolResult = (
r: Result<ToolOk, ToolErr>,
toolName: string,
): AgentToolResult<OkDetails | ErrDetails> => {
if (r.success) {
const details: OkDetails = { ok: true, ...(r.data.details ?? {}) };
return {
content: [{ type: "text", text: r.data.text }],
details,
};
}
const details: ErrDetails = {
ok: false,
kind: r.error.kind,
message: r.error.message,
...(r.error.details ?? {}),
};
return {
// isError is an extension the pi-coding-agent runtime picks up from the result object;
// AgentToolResult<T> itself doesn't declare it but the runtime reads it via duck-typing.
// We cast through unknown to avoid widening the return type.
...(({ isError: true }) as unknown as object),
content: [{ type: "text", text: `${toolName} failed (${r.error.kind}): ${r.error.message}` }],
details,
};
};
export const registerBrowserTool = (
pi: ExtensionAPI,
client: BrowserClient,
def: AnyBrowserToolDefinition,
): void => {
// AnyBrowserToolDefinition is type-erased; we recover the schema-typed surface
// by casting def to the generic form. The cast is safe because defineBrowserTool
// ensures the handler, parameters, and renderCall were all created with the same S.
type S = TSchema;
const td: ToolDefinition<S> = {
name: def.name,
label: def.label,
description: def.description,
promptSnippet: def.promptSnippet,
promptGuidelines: [...def.promptGuidelines],
parameters: def.parameters,
...(def.renderCall
? {
renderCall: (args: Static<S>, theme: Theme, _ctx: Parameters<NonNullable<ToolDefinition<S>["renderCall"]>>[2]) =>
// Non-null assertion safe: this branch only runs when renderCall was provided.
// Cast from never->Component to unknown->Component: safe because at runtime
// args is always the concrete Static<S> value the tool was defined with.
(def.renderCall as (args: unknown, theme: Theme) => Component)(args, theme),
}
: {}),
...(def.renderResult
? {
renderResult: (
result: AgentToolResult<unknown>,
options: ToolRenderResultOptions,
theme: Theme,
_ctx: Parameters<NonNullable<ToolDefinition<S>["renderResult"]>>[3],
) =>
// Non-null assertion safe: this branch only runs when renderResult was provided.
def.renderResult!(result, options.expanded ?? false, theme),
}
: {}),
async execute(_toolCallId, args, signal, onUpdate, extensionCtx) {
if (def.ensureAlive !== false) {
const alive = await client.ensureAlive();
if (!alive.success) {
return toToolResult(
{ success: false, error: { kind: "not_connected", message: alive.error.message } },
def.name,
);
}
}
// Serialized tools acquire the client's mutation mutex so that only one
// mutation tool runs at a time. Observation tools skip this and run freely
// in parallel. AbortSignal is checked after acquiring the lock so that a
// cancelled task doesn't hold the mutex forever.
let release: (() => void) | undefined;
if (def.serialized) {
const acquire = await client.mutationMutex().acquire();
release = acquire;
if (signal?.aborted) {
release();
return toToolResult(
{ success: false, error: { kind: "invalid_state", message: "Tool execution aborted before entering serialized lane" } },
def.name,
);
}
}
try {
const result = await def.handler(args, {
client,
signal,
onUpdate: (u) => {
if (onUpdate) {
// AgentToolUpdateCallback expects AgentToolResult<TDetails>; we use unknown for TDetails.
const update: AgentToolResult<OkDetails> = {
content: [{ type: "text", text: u.text }],
details: { ok: true, ...(u.details ?? {}) },
};
// Cast needed: onUpdate is AgentToolUpdateCallback<unknown> (generic TDetails).
(onUpdate as AgentToolUpdateCallback<OkDetails>)(update);
}
},
extensionCtx,
});
return toToolResult(result, def.name);
} finally {
release?.();
}
},
};
pi.registerTool(td);
};
|