@gaiventures/pilotfish 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +182 -2
- package/dist/client.d.ts +272 -0
- package/dist/client.js +385 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.js +89 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/local.d.ts +161 -0
- package/dist/local.js +274 -0
- package/dist/types.d.ts +334 -0
- package/dist/types.js +2 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/webhooks.d.ts +23 -0
- package/dist/webhooks.js +44 -0
- package/package.json +52 -4
package/dist/local.d.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { PilotfishError } from "./errors.js";
|
|
2
|
+
/** A tool's answer: its text (the page, what changed, what needs a person), pictures, and structured value. */
|
|
3
|
+
export interface ToolResult {
|
|
4
|
+
text: string;
|
|
5
|
+
images: Array<{
|
|
6
|
+
data: Uint8Array;
|
|
7
|
+
mimeType: string;
|
|
8
|
+
}>;
|
|
9
|
+
/** `browser_query` with a schema: `{value}`. */
|
|
10
|
+
structured?: Record<string, unknown>;
|
|
11
|
+
isError: boolean;
|
|
12
|
+
}
|
|
13
|
+
/** A tool answered with an error (a refused click, a stale ref, a bad expression). `result` has its whole text. */
|
|
14
|
+
export declare class LocalToolError extends PilotfishError {
|
|
15
|
+
readonly tool: string;
|
|
16
|
+
readonly result: ToolResult;
|
|
17
|
+
constructor(tool: string, result: ToolResult);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Something the MCP asks the person: `confirm` before a step that looks irreversible (pay, send, delete: answer true to
|
|
21
|
+
* allow), or `handoff` when the page needs a person (a sign-in, a code, a CAPTCHA: answer true once it is done in the
|
|
22
|
+
* browser window). Null or false declines.
|
|
23
|
+
*/
|
|
24
|
+
export interface LocalQuestion {
|
|
25
|
+
kind: "confirm" | "handoff";
|
|
26
|
+
message: string;
|
|
27
|
+
}
|
|
28
|
+
export interface LocalOptions {
|
|
29
|
+
/** Hide the browser window. Default: a window where one can open. A hidden one cannot be signed in to by hand. */
|
|
30
|
+
headless?: boolean;
|
|
31
|
+
/** Hostnames the browser may visit, `*` wildcards allowed. Default: any public site. */
|
|
32
|
+
allowedHosts?: string[];
|
|
33
|
+
/** Allow localhost and private networks (testing your own app). */
|
|
34
|
+
allowPrivate?: boolean;
|
|
35
|
+
/** Secrets typed as `{{name}}`: `{"name": "value"}` or `{"name": {value?, totp?, allowedHosts?}}`. Never in any result. */
|
|
36
|
+
secrets?: Record<string, string | {
|
|
37
|
+
value?: string;
|
|
38
|
+
totp?: string;
|
|
39
|
+
allowedHosts?: string[];
|
|
40
|
+
}>;
|
|
41
|
+
/** The browser executable. Default: found automatically. */
|
|
42
|
+
chrome?: string;
|
|
43
|
+
/** Further environment variables for the MCP (its settings: https://pilotfish.gai.ventures/docs/open-settings). */
|
|
44
|
+
env?: Record<string, string>;
|
|
45
|
+
/** How to start the MCP: the command and its arguments. Default: the installed package, else npx. */
|
|
46
|
+
command?: string[];
|
|
47
|
+
/** Answers the MCP's questions to the person. Without it, irreversible steps are refused and a page that needs a person says so in the result. */
|
|
48
|
+
onQuestion?: (q: LocalQuestion) => Promise<boolean | string | null> | boolean | string | null;
|
|
49
|
+
/** Throw LocalToolError when a tool answers with an error (default true); false returns the result. */
|
|
50
|
+
throwOnError?: boolean;
|
|
51
|
+
/** Per-call timeout, ms. Default 5 min (browser_resume waits for a person). */
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
}
|
|
54
|
+
type Expect = {
|
|
55
|
+
text?: string;
|
|
56
|
+
gone?: string;
|
|
57
|
+
url?: string;
|
|
58
|
+
in?: string;
|
|
59
|
+
within?: number;
|
|
60
|
+
};
|
|
61
|
+
type ActOpts = {
|
|
62
|
+
snapshot?: boolean;
|
|
63
|
+
expect?: Expect;
|
|
64
|
+
escalate?: boolean;
|
|
65
|
+
};
|
|
66
|
+
/** One step of `actions`: `{action: "click", ref}`, `{action: "type", ref, text, submit?}`, `{action: "select", ref, values}`, `{action: "press", key}`, `{action: "scroll", direction}`, `{action: "wait", seconds, until?, gone?}`. */
|
|
67
|
+
export type Step = {
|
|
68
|
+
action: "click" | "type" | "select" | "press" | "scroll" | "wait";
|
|
69
|
+
[key: string]: unknown;
|
|
70
|
+
};
|
|
71
|
+
export declare class LocalBrowser {
|
|
72
|
+
private readonly proc;
|
|
73
|
+
private readonly o;
|
|
74
|
+
private nextId;
|
|
75
|
+
private readonly pending;
|
|
76
|
+
private buf;
|
|
77
|
+
private closed;
|
|
78
|
+
private exited;
|
|
79
|
+
/** Why the MCP stopped, kept for every later call. */
|
|
80
|
+
private stopped;
|
|
81
|
+
private stderrTail;
|
|
82
|
+
/** The MCP's own name and version (initialize). */
|
|
83
|
+
serverInfo: {
|
|
84
|
+
name: string;
|
|
85
|
+
version: string;
|
|
86
|
+
} | null;
|
|
87
|
+
private constructor();
|
|
88
|
+
/** Start the open MCP and connect to it. The browser itself opens on the first call that needs it. */
|
|
89
|
+
static start(o?: LocalOptions): Promise<LocalBrowser>;
|
|
90
|
+
/** Open an http(s) URL; returns what happened and the visible screen (`snapshot: false` leaves the screen out). */
|
|
91
|
+
navigate(url: string, o?: ActOpts): Promise<ToolResult>;
|
|
92
|
+
/** The page as a compact outline with refs (`[e12]<button>Search`); `wholePage` for all of it. */
|
|
93
|
+
snapshot(o?: {
|
|
94
|
+
wholePage?: boolean;
|
|
95
|
+
}): Promise<ToolResult>;
|
|
96
|
+
click(ref: string, o?: ActOpts): Promise<ToolResult>;
|
|
97
|
+
/** Replace a field's text (`{{name}}` types a secret); `submit` presses Enter after. */
|
|
98
|
+
type(ref: string, text: string, o?: ActOpts & {
|
|
99
|
+
submit?: boolean;
|
|
100
|
+
}): Promise<ToolResult>;
|
|
101
|
+
select(ref: string, values: string[], o?: ActOpts): Promise<ToolResult>;
|
|
102
|
+
/** A key or shortcut: `Enter`, `Escape`, `Control+a`. */
|
|
103
|
+
press(key: string, o?: ActOpts): Promise<ToolResult>;
|
|
104
|
+
scroll(direction: "up" | "down" | "left" | "right", o?: {
|
|
105
|
+
snapshot?: boolean;
|
|
106
|
+
}): Promise<ToolResult>;
|
|
107
|
+
/** Up to 10 steps in one call (a form's fields and its submit). */
|
|
108
|
+
actions(steps: Step[], o?: {
|
|
109
|
+
snapshot?: boolean;
|
|
110
|
+
}): Promise<ToolResult>;
|
|
111
|
+
/** Read values with a JavaScript expression that returns JSON: `value` is the parsed result. It cannot change the page. */
|
|
112
|
+
query<T = unknown>(expression: string, o?: {
|
|
113
|
+
schema?: Record<string, unknown>;
|
|
114
|
+
}): Promise<ToolResult & {
|
|
115
|
+
value: T;
|
|
116
|
+
}>;
|
|
117
|
+
/** Elements anywhere on the page by their words, best match first (comma-separate several targets). */
|
|
118
|
+
find(query: string): Promise<ToolResult>;
|
|
119
|
+
/** The page's readable text (PDFs too), or one element's (`selector`). */
|
|
120
|
+
getText(o?: {
|
|
121
|
+
maxChars?: number;
|
|
122
|
+
selector?: string;
|
|
123
|
+
}): Promise<ToolResult>;
|
|
124
|
+
/** A JPEG of the viewport. */
|
|
125
|
+
screenshot(): Promise<Uint8Array>;
|
|
126
|
+
/** Wait up to `seconds` (0.5-10), or until `until` appears or `gone` goes. */
|
|
127
|
+
wait(seconds: number, o?: {
|
|
128
|
+
until?: string;
|
|
129
|
+
gone?: string;
|
|
130
|
+
in?: string;
|
|
131
|
+
snapshot?: boolean;
|
|
132
|
+
}): Promise<ToolResult>;
|
|
133
|
+
/** After a result said NEEDS A PERSON: wait (default 300 s) until the person has dealt with the page. */
|
|
134
|
+
resume(o?: {
|
|
135
|
+
timeoutS?: number;
|
|
136
|
+
}): Promise<ToolResult>;
|
|
137
|
+
/** Open tabs, or switch to one (`"t2"`). */
|
|
138
|
+
tabs(o?: {
|
|
139
|
+
switchTo?: string;
|
|
140
|
+
}): Promise<ToolResult>;
|
|
141
|
+
/** A tool the page itself offers (WebMCP), as its snapshot's PAGE TOOLS line lists it. */
|
|
142
|
+
pageTool(tool: string, args?: Record<string, unknown>): Promise<ToolResult>;
|
|
143
|
+
/** The tools the MCP offers now. */
|
|
144
|
+
tools(): Promise<Array<{
|
|
145
|
+
name: string;
|
|
146
|
+
description?: string;
|
|
147
|
+
inputSchema?: unknown;
|
|
148
|
+
}>>;
|
|
149
|
+
/** Any tool by name, with its arguments as the MCP takes them. */
|
|
150
|
+
call(name: string, args?: Record<string, unknown>): Promise<ToolResult>;
|
|
151
|
+
/** Close the browser and stop the MCP. */
|
|
152
|
+
close(): Promise<void>;
|
|
153
|
+
private send;
|
|
154
|
+
private notify;
|
|
155
|
+
private rpc;
|
|
156
|
+
private onData;
|
|
157
|
+
/** The MCP's requests to us: ping, and questions for the person (elicitation). */
|
|
158
|
+
private onRequest;
|
|
159
|
+
private fail;
|
|
160
|
+
}
|
|
161
|
+
export {};
|
package/dist/local.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// The local client: Chrome on your own machine and IP, driven from code through the open MCP's browser tools
|
|
2
|
+
// (@gaiventures/pilotfish-mcp, MIT). No account, no API key, no model calls: your code is the one deciding each step.
|
|
3
|
+
//
|
|
4
|
+
// It starts the open MCP as a child process and speaks MCP to it over stdio (newline-delimited JSON-RPC). The MCP is the
|
|
5
|
+
// installed `@gaiventures/pilotfish-mcp` when there is one, else `npx -y @gaiventures/pilotfish-mcp`.
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import { PilotfishError } from "./errors.js";
|
|
9
|
+
import { VERSION } from "./version.js";
|
|
10
|
+
const PROTOCOL = "2025-06-18";
|
|
11
|
+
const MCP_PACKAGE = "@gaiventures/pilotfish-mcp";
|
|
12
|
+
/** A tool answered with an error (a refused click, a stale ref, a bad expression). `result` has its whole text. */
|
|
13
|
+
export class LocalToolError extends PilotfishError {
|
|
14
|
+
tool;
|
|
15
|
+
result;
|
|
16
|
+
constructor(tool, result) {
|
|
17
|
+
super(0, { error: result.text || `${tool} failed`, code: "tool_error" });
|
|
18
|
+
this.tool = tool;
|
|
19
|
+
this.result = result;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** The command that starts the open MCP: the installed package's cli.js, else npx. */
|
|
23
|
+
function defaultCommand() {
|
|
24
|
+
if (process.env["PILOTFISH_MCP_CLI"])
|
|
25
|
+
return [process.execPath, process.env["PILOTFISH_MCP_CLI"]];
|
|
26
|
+
try {
|
|
27
|
+
const cli = createRequire(import.meta.url).resolve(`${MCP_PACKAGE}/cli.js`);
|
|
28
|
+
return [process.execPath, cli];
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return [process.platform === "win32" ? "npx.cmd" : "npx", "-y", MCP_PACKAGE];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const settingsEnv = (o) => ({
|
|
35
|
+
...(o.headless !== undefined ? { PILOTFISH_HEADLESS: o.headless ? "1" : "0" } : {}),
|
|
36
|
+
...(o.allowedHosts ? { PILOTFISH_ALLOWED_HOSTS: o.allowedHosts.join(",") } : {}),
|
|
37
|
+
...(o.allowPrivate ? { PILOTFISH_ALLOW_PRIVATE: "1" } : {}),
|
|
38
|
+
...(o.secrets ? { PILOTFISH_SECRETS: JSON.stringify(o.secrets) } : {}),
|
|
39
|
+
...(o.chrome ? { PILOTFISH_CHROME: o.chrome } : {}),
|
|
40
|
+
...(o.env ?? {}),
|
|
41
|
+
});
|
|
42
|
+
export class LocalBrowser {
|
|
43
|
+
proc;
|
|
44
|
+
o;
|
|
45
|
+
nextId = 1;
|
|
46
|
+
pending = new Map();
|
|
47
|
+
buf = "";
|
|
48
|
+
closed = false;
|
|
49
|
+
exited = false;
|
|
50
|
+
/** Why the MCP stopped, kept for every later call. */
|
|
51
|
+
stopped = null;
|
|
52
|
+
stderrTail = "";
|
|
53
|
+
/** The MCP's own name and version (initialize). */
|
|
54
|
+
serverInfo = null;
|
|
55
|
+
constructor(proc, o) {
|
|
56
|
+
this.proc = proc;
|
|
57
|
+
this.o = o;
|
|
58
|
+
proc.stdout.setEncoding("utf8");
|
|
59
|
+
proc.stdout.on("data", (chunk) => this.onData(chunk));
|
|
60
|
+
proc.stderr.setEncoding("utf8");
|
|
61
|
+
proc.stderr.on("data", (chunk) => void (this.stderrTail = (this.stderrTail + chunk).slice(-4_000)));
|
|
62
|
+
proc.on("exit", (code) => (this.exited = true, this.fail(new PilotfishError(0, { error: `The pilotfish MCP stopped (exit ${code}).${this.stderrTail ? ` ${this.stderrTail.trim().split("\n").slice(-3).join(" ")}` : ""}`, code: "mcp_exited" }))));
|
|
63
|
+
proc.on("error", (e) => this.fail(new PilotfishError(0, { error: `Could not start the pilotfish MCP: ${e.message}`, code: "mcp_start_failed" })));
|
|
64
|
+
}
|
|
65
|
+
/** Start the open MCP and connect to it. The browser itself opens on the first call that needs it. */
|
|
66
|
+
static async start(o = {}) {
|
|
67
|
+
const [cmd, ...args] = o.command ?? defaultCommand();
|
|
68
|
+
const proc = spawn(cmd, args, { env: { ...process.env, ...settingsEnv(o) }, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32" && /\.cmd$/i.test(cmd) });
|
|
69
|
+
const b = new LocalBrowser(proc, o);
|
|
70
|
+
const init = (await b.rpc("initialize", {
|
|
71
|
+
protocolVersion: PROTOCOL,
|
|
72
|
+
capabilities: o.onQuestion ? { elicitation: { form: {} } } : {},
|
|
73
|
+
clientInfo: { name: "pilotfish-sdk-ts", version: VERSION },
|
|
74
|
+
}));
|
|
75
|
+
b.serverInfo = init.serverInfo ?? null;
|
|
76
|
+
b.notify("notifications/initialized", {});
|
|
77
|
+
return b;
|
|
78
|
+
}
|
|
79
|
+
// ----------------------------------------------------------------------------------------- the tools
|
|
80
|
+
/** Open an http(s) URL; returns what happened and the visible screen (`snapshot: false` leaves the screen out). */
|
|
81
|
+
navigate(url, o = {}) {
|
|
82
|
+
return this.call("browser_navigate", { url, ...o });
|
|
83
|
+
}
|
|
84
|
+
/** The page as a compact outline with refs (`[e12]<button>Search`); `wholePage` for all of it. */
|
|
85
|
+
snapshot(o = {}) {
|
|
86
|
+
return this.call("browser_snapshot", o.wholePage ? { whole_page: true } : {});
|
|
87
|
+
}
|
|
88
|
+
click(ref, o = {}) {
|
|
89
|
+
return this.call("browser_click", { ref, ...o });
|
|
90
|
+
}
|
|
91
|
+
/** Replace a field's text (`{{name}}` types a secret); `submit` presses Enter after. */
|
|
92
|
+
type(ref, text, o = {}) {
|
|
93
|
+
return this.call("browser_type", { ref, text, ...o });
|
|
94
|
+
}
|
|
95
|
+
select(ref, values, o = {}) {
|
|
96
|
+
return this.call("browser_select", { ref, values, ...o });
|
|
97
|
+
}
|
|
98
|
+
/** A key or shortcut: `Enter`, `Escape`, `Control+a`. */
|
|
99
|
+
press(key, o = {}) {
|
|
100
|
+
return this.call("browser_press", { key, ...o });
|
|
101
|
+
}
|
|
102
|
+
scroll(direction, o = {}) {
|
|
103
|
+
return this.call("browser_scroll", { direction, ...o });
|
|
104
|
+
}
|
|
105
|
+
/** Up to 10 steps in one call (a form's fields and its submit). */
|
|
106
|
+
actions(steps, o = {}) {
|
|
107
|
+
return this.call("browser_actions", { actions: steps, ...o });
|
|
108
|
+
}
|
|
109
|
+
/** Read values with a JavaScript expression that returns JSON: `value` is the parsed result. It cannot change the page. */
|
|
110
|
+
async query(expression, o = {}) {
|
|
111
|
+
const r = await this.call("browser_query", { expression, ...o });
|
|
112
|
+
let value = r.structured?.["value"];
|
|
113
|
+
if (value === undefined) {
|
|
114
|
+
try {
|
|
115
|
+
value = JSON.parse(r.text);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
value = r.text;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { ...r, value: value };
|
|
122
|
+
}
|
|
123
|
+
/** Elements anywhere on the page by their words, best match first (comma-separate several targets). */
|
|
124
|
+
find(query) {
|
|
125
|
+
return this.call("browser_find", { query });
|
|
126
|
+
}
|
|
127
|
+
/** The page's readable text (PDFs too), or one element's (`selector`). */
|
|
128
|
+
getText(o = {}) {
|
|
129
|
+
return this.call("browser_get_text", { ...(o.maxChars !== undefined ? { max_chars: o.maxChars } : {}), ...(o.selector !== undefined ? { selector: o.selector } : {}) });
|
|
130
|
+
}
|
|
131
|
+
/** A JPEG of the viewport. */
|
|
132
|
+
async screenshot() {
|
|
133
|
+
const r = await this.call("browser_screenshot", {});
|
|
134
|
+
const img = r.images[0];
|
|
135
|
+
if (!img)
|
|
136
|
+
throw new LocalToolError("browser_screenshot", { ...r, isError: true });
|
|
137
|
+
return img.data;
|
|
138
|
+
}
|
|
139
|
+
/** Wait up to `seconds` (0.5-10), or until `until` appears or `gone` goes. */
|
|
140
|
+
wait(seconds, o = {}) {
|
|
141
|
+
return this.call("browser_wait", { seconds, ...o });
|
|
142
|
+
}
|
|
143
|
+
/** After a result said NEEDS A PERSON: wait (default 300 s) until the person has dealt with the page. */
|
|
144
|
+
resume(o = {}) {
|
|
145
|
+
return this.call("browser_resume", o.timeoutS !== undefined ? { timeout_s: o.timeoutS } : {});
|
|
146
|
+
}
|
|
147
|
+
/** Open tabs, or switch to one (`"t2"`). */
|
|
148
|
+
tabs(o = {}) {
|
|
149
|
+
return this.call("browser_tabs", o.switchTo !== undefined ? { switch_to: o.switchTo } : {});
|
|
150
|
+
}
|
|
151
|
+
/** A tool the page itself offers (WebMCP), as its snapshot's PAGE TOOLS line lists it. */
|
|
152
|
+
pageTool(tool, args = {}) {
|
|
153
|
+
return this.call("browser_page_tool", { tool, arguments: args });
|
|
154
|
+
}
|
|
155
|
+
/** The tools the MCP offers now. */
|
|
156
|
+
async tools() {
|
|
157
|
+
return (await this.rpc("tools/list", {})).tools;
|
|
158
|
+
}
|
|
159
|
+
/** Any tool by name, with its arguments as the MCP takes them. */
|
|
160
|
+
async call(name, args = {}) {
|
|
161
|
+
const raw = (await this.rpc("tools/call", { name, arguments: args }));
|
|
162
|
+
const content = raw.content ?? [];
|
|
163
|
+
const r = {
|
|
164
|
+
text: content
|
|
165
|
+
.filter((c) => c.type === "text")
|
|
166
|
+
.map((c) => c.text ?? "")
|
|
167
|
+
.join("\n"),
|
|
168
|
+
images: content.filter((c) => c.type === "image" && c.data).map((c) => ({ data: Uint8Array.from(Buffer.from(c.data, "base64")), mimeType: c.mimeType ?? "image/jpeg" })),
|
|
169
|
+
...(raw.structuredContent ? { structured: raw.structuredContent } : {}),
|
|
170
|
+
isError: raw.isError === true,
|
|
171
|
+
};
|
|
172
|
+
if (r.isError && this.o.throwOnError !== false)
|
|
173
|
+
throw new LocalToolError(name, r);
|
|
174
|
+
return r;
|
|
175
|
+
}
|
|
176
|
+
/** Close the browser and stop the MCP. */
|
|
177
|
+
async close() {
|
|
178
|
+
if (this.closed && this.exited)
|
|
179
|
+
return;
|
|
180
|
+
if (!this.closed)
|
|
181
|
+
await this.call("browser_close", {}).catch(() => undefined);
|
|
182
|
+
this.closed = true;
|
|
183
|
+
if (this.exited)
|
|
184
|
+
return;
|
|
185
|
+
this.proc.stdin.end();
|
|
186
|
+
const exited = new Promise((r) => (this.exited ? r() : this.proc.once("exit", () => r())));
|
|
187
|
+
const t = setTimeout(() => this.proc.kill(), 5_000);
|
|
188
|
+
await exited;
|
|
189
|
+
clearTimeout(t);
|
|
190
|
+
}
|
|
191
|
+
// ----------------------------------------------------------------------------------------- JSON-RPC over stdio
|
|
192
|
+
send(msg) {
|
|
193
|
+
if (this.closed || this.proc.stdin.destroyed)
|
|
194
|
+
return;
|
|
195
|
+
this.proc.stdin.write(`${JSON.stringify(msg)}\n`);
|
|
196
|
+
}
|
|
197
|
+
notify(method, params) {
|
|
198
|
+
this.send({ jsonrpc: "2.0", method, params });
|
|
199
|
+
}
|
|
200
|
+
rpc(method, params) {
|
|
201
|
+
if (this.closed)
|
|
202
|
+
return Promise.reject(this.stopped ?? new PilotfishError(0, { error: "This browser is closed.", code: "closed" }));
|
|
203
|
+
const id = this.nextId++;
|
|
204
|
+
return new Promise((resolve, reject) => {
|
|
205
|
+
const timer = setTimeout(() => {
|
|
206
|
+
this.pending.delete(id);
|
|
207
|
+
this.notify("notifications/cancelled", { requestId: id, reason: "timeout" });
|
|
208
|
+
reject(new PilotfishError(0, { error: `${method} took longer than ${Math.round((this.o.timeoutMs ?? 300_000) / 1000)} s`, code: "timeout" }));
|
|
209
|
+
}, this.o.timeoutMs ?? 300_000);
|
|
210
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
211
|
+
this.send({ jsonrpc: "2.0", id, method, params });
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
onData(chunk) {
|
|
215
|
+
this.buf += chunk;
|
|
216
|
+
let nl;
|
|
217
|
+
while ((nl = this.buf.indexOf("\n")) >= 0) {
|
|
218
|
+
const line = this.buf.slice(0, nl).trim();
|
|
219
|
+
this.buf = this.buf.slice(nl + 1);
|
|
220
|
+
if (!line)
|
|
221
|
+
continue;
|
|
222
|
+
let msg;
|
|
223
|
+
try {
|
|
224
|
+
msg = JSON.parse(line);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (msg.method && msg.id !== undefined)
|
|
230
|
+
void this.onRequest(msg.id, msg.method, msg.params ?? {});
|
|
231
|
+
else if (msg.id !== undefined) {
|
|
232
|
+
const p = this.pending.get(Number(msg.id));
|
|
233
|
+
if (!p)
|
|
234
|
+
continue;
|
|
235
|
+
this.pending.delete(Number(msg.id));
|
|
236
|
+
clearTimeout(p.timer);
|
|
237
|
+
if (msg.error)
|
|
238
|
+
p.reject(new PilotfishError(0, { error: msg.error.message ?? "MCP error", code: `mcp_${msg.error.code ?? "error"}` }));
|
|
239
|
+
else
|
|
240
|
+
p.resolve(msg.result);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** The MCP's requests to us: ping, and questions for the person (elicitation). */
|
|
245
|
+
async onRequest(id, method, params) {
|
|
246
|
+
if (method === "ping")
|
|
247
|
+
return this.send({ jsonrpc: "2.0", id, result: {} });
|
|
248
|
+
if (method === "elicitation/create" && this.o.onQuestion) {
|
|
249
|
+
const props = (params["requestedSchema"]?.properties ?? {});
|
|
250
|
+
const kind = "done" in props ? "handoff" : "confirm";
|
|
251
|
+
let answer = null;
|
|
252
|
+
try {
|
|
253
|
+
answer = await this.o.onQuestion({ kind, message: String(params["message"] ?? "") });
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
answer = null;
|
|
257
|
+
}
|
|
258
|
+
if (answer === null || answer === false)
|
|
259
|
+
return this.send({ jsonrpc: "2.0", id, result: { action: "decline" } });
|
|
260
|
+
const content = kind === "handoff" ? { done: true } : { answer: answer === true ? "yes" : String(answer) };
|
|
261
|
+
return this.send({ jsonrpc: "2.0", id, result: { action: "accept", content } });
|
|
262
|
+
}
|
|
263
|
+
this.send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });
|
|
264
|
+
}
|
|
265
|
+
fail(e) {
|
|
266
|
+
this.closed = true;
|
|
267
|
+
this.stopped ??= e;
|
|
268
|
+
for (const [id, p] of this.pending) {
|
|
269
|
+
clearTimeout(p.timer);
|
|
270
|
+
p.reject(e);
|
|
271
|
+
this.pending.delete(id);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|