agy-delegate-mcp 0.0.0 → 1.0.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/src/doctor.js ADDED
@@ -0,0 +1,202 @@
1
+ import process from "node:process";
2
+ import { spawn } from "node:child_process";
3
+ import { AcpClient } from "./acp-client.js";
4
+ import { resolveAcpSpawn } from "./spawn.js";
5
+ import { DETACHED, treeKill } from "./proc.js";
6
+ import { readPackageVersion } from "./version.js";
7
+ import { allowedValues, describeOptions } from "./model-options.js";
8
+
9
+ const HANDSHAKE_TIMEOUT_MS = 15_000;
10
+ const VERSION_PROBE_TIMEOUT_MS = 10_000;
11
+ const PROBE_STDOUT_CAP = 64 * 1024;
12
+ const DEFAULT_LOG_SIZE = "2000";
13
+
14
+ function formatArg(value) {
15
+ const s = String(value);
16
+ if (!/[\s"]/.test(s)) return s;
17
+ return `"${s.replace(/"/g, '\\"')}"`;
18
+ }
19
+
20
+ function formatCommand({ command, args }) {
21
+ const bits = [formatArg(command), ...(args || []).map(formatArg)];
22
+ return args?.length ? bits.join(" ") : formatArg(command);
23
+ }
24
+
25
+ function isJsLauncher(command) {
26
+ const trimmed = String(command || "").replace(/^["']|["']$/g, "");
27
+ return /\.(?:cjs|mjs|js)$/i.test(trimmed);
28
+ }
29
+
30
+ function envReport(name, fallback = null) {
31
+ return process.env[name] !== undefined ? process.env[name] : fallback;
32
+ }
33
+
34
+ // Time-boxed because a launcher that accepts --version and then never answers would hang doctor
35
+ // forever — and doctor is what you run when delegation is already broken, so a wedged agent is
36
+ // exactly the case it must survive. Same guard the deep handshake has.
37
+ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS) {
38
+ const { command, options } = spawnSpec;
39
+ const launcher = String(command || "").replace(/^["']|["']$/g, "");
40
+ const isJsScript = isJsLauncher(launcher);
41
+ const execCommand = isJsScript ? process.execPath : command;
42
+ const execArgs = isJsScript ? [launcher, "--version"] : ["--version"];
43
+ return new Promise((resolve) => {
44
+ let settled = false;
45
+ let stdout = "";
46
+ let timer;
47
+ const finish = (result) => {
48
+ if (settled) return;
49
+ settled = true;
50
+ clearTimeout(timer);
51
+ resolve(result);
52
+ };
53
+ const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
54
+ // Capped: a version string is a line, and a launcher that streams instead should not be
55
+ // accumulated whole while the probe waits out its timeout.
56
+ child.stdout?.on("data", (chunk) => {
57
+ if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
58
+ });
59
+ // Drained, not merely piped. An unread pipe fills, the launcher blocks writing to it and so
60
+ // never exits, and the probe can only report that as a timeout — a healthy but noisy
61
+ // launcher reads out identically to a wedged one. Nothing consumes the bytes.
62
+ child.stderr?.on("data", () => {});
63
+ child.stderr?.on("error", () => {});
64
+ child.on("error", () => finish({ found: false, version: null }));
65
+ child.on("close", (code) => {
66
+ const version = code === 0 ? stdout.trim() || null : null;
67
+ finish({
68
+ found: true,
69
+ version,
70
+ ...(code !== 0 ? { error: `version probe exited ${code}` } : {}),
71
+ });
72
+ });
73
+ timer = setTimeout(() => {
74
+ // treeKill, not child.kill: the spawn spec carries shell:true on win32, where a plain
75
+ // kill only reaches the wrapper and leaves the launcher running.
76
+ if (child.pid) treeKill(child.pid).catch(() => {});
77
+ // The launcher exists — it spawned — it just never answered, which is a different
78
+ // diagnosis from "not installed" and has to read that way.
79
+ finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
80
+ }, timeoutMs);
81
+ timer.unref?.();
82
+ });
83
+ }
84
+
85
+ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs }) {
86
+ const client = clientFactory({ spawnSpec });
87
+ const workspaceDir = workspace || process.cwd();
88
+ let timer;
89
+ try {
90
+ const details = {};
91
+ const work = (async () => {
92
+ await client.start();
93
+ await client.initialize();
94
+ await client.newSession(workspaceDir);
95
+ details.protocolVersion = client.protocolVersion ?? null;
96
+ details.agentCapabilities = client.agentCapabilities ?? {};
97
+ // The ids delegate's model accepts: the model config option's values, base ids such as
98
+ // gemini-4-neon. availableModels repeats each with a level suffix, which delegate does not
99
+ // take, so it is the fallback only for an agent that reports no model option.
100
+ const modelOption = (client.configOptions ?? []).find((o) => o?.id === "model");
101
+ const baseIds = allowedValues(modelOption);
102
+ details.models = baseIds.length
103
+ ? baseIds
104
+ : (client.sessionModels?.availableModels ?? []).map((m) => m?.modelId).filter(Boolean);
105
+ details.currentModel = (typeof modelOption?.currentValue === "string" ? modelOption.currentValue : null)
106
+ ?? client.sessionModels?.currentModelId ?? null;
107
+ details.modes = (client.sessionModes?.availableModes ?? []).map((m) => m?.id).filter(Boolean);
108
+ // session/new already returned these. currentModel only — any other model needs a model
109
+ // switch first, which this handshake does not send. name and category are what tell an
110
+ // effort option apart when its id is unfamiliar; currentValue is the level in force.
111
+ details.currentModelOptions = describeOptions(client.configOptions);
112
+ // The plan the signed-in account is on, as agy reports it.
113
+ details.tier = client.sessionMeta?.antigravity?.tier ?? null;
114
+ })();
115
+ const timeout = new Promise((_, reject) => {
116
+ timer = setTimeout(() => {
117
+ // Not awaited, so the timeout still rejects at its stated deadline rather than at the
118
+ // deadline plus teardown. The finally below awaits the same idempotent promise.
119
+ try { Promise.resolve(client.stop()).catch(() => {}); } catch {}
120
+ reject(new Error(`Handshake timed out after ${timeoutMs}ms`));
121
+ }, timeoutMs);
122
+ });
123
+ await Promise.race([work, timeout]);
124
+ return { ok: true, ...details };
125
+ } catch (err) {
126
+ return { ok: false, error: err?.message || String(err) };
127
+ } finally {
128
+ clearTimeout(timer);
129
+ // Awaited so doctor does not return while the agent it spawned is still being torn down.
130
+ // A killed child exits in milliseconds; only one that ignores the kill costs the full bound.
131
+ try { await Promise.resolve(client.stop()); } catch {}
132
+ }
133
+ }
134
+
135
+ /**
136
+ * @param {{
137
+ * getClientInfo?: () => { capabilities?: any, version?: any },
138
+ * deep?: boolean,
139
+ * spawnSpec?: { command: string, args: string[], options?: object },
140
+ * clientFactory?: (opts: any) => any,
141
+ * workspace?: string,
142
+ * handshakeTimeoutMs?: number,
143
+ * versionTimeoutMs?: number,
144
+ * readVersion?: () => string,
145
+ * }} [opts]
146
+ */
147
+ export async function runDoctor({
148
+ getClientInfo = () => ({ capabilities: {}, version: {} }),
149
+ deep = false,
150
+ spawnSpec = resolveAcpSpawn(),
151
+ clientFactory = (opts) => new AcpClient(opts),
152
+ workspace,
153
+ handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
154
+ versionTimeoutMs = VERSION_PROBE_TIMEOUT_MS,
155
+ readVersion = readPackageVersion,
156
+ } = {}) {
157
+ const { capabilities, version } = getClientInfo();
158
+ const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs);
159
+
160
+ /** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
161
+ const out = {
162
+ plugin: { version: readVersion() },
163
+ client: {
164
+ name: version?.name ?? null,
165
+ version: version?.version ?? null,
166
+ capabilities: capabilities ?? {},
167
+ },
168
+ agent: {
169
+ found: agentProbe.found,
170
+ command: formatCommand(spawnSpec),
171
+ version: agentProbe.version,
172
+ ...(agentProbe.error ? { error: agentProbe.error } : {}),
173
+ },
174
+ runtime: {
175
+ node: process.versions.node,
176
+ platform: process.platform,
177
+ arch: process.arch,
178
+ cwd: process.cwd(),
179
+ transport: "stdio",
180
+ },
181
+ env: {
182
+ ACP_LOG_SIZE: envReport("ACP_LOG_SIZE", DEFAULT_LOG_SIZE),
183
+ ACP_AGENT_COMMAND: envReport("ACP_AGENT_COMMAND"),
184
+ ACP_AGENT_ARGS: envReport("ACP_AGENT_ARGS"),
185
+ AGY_DELEGATE_TRANSCRIPT: envReport("AGY_DELEGATE_TRANSCRIPT"),
186
+ AGY_DELEGATE_HANDSHAKE_MS: envReport("AGY_DELEGATE_HANDSHAKE_MS"),
187
+ AGY_DELEGATE_HARD_CAP_MS: envReport("AGY_DELEGATE_HARD_CAP_MS"),
188
+ AGY_DELEGATE_IDLE_MS: envReport("AGY_DELEGATE_IDLE_MS"),
189
+ },
190
+ };
191
+
192
+ if (deep) {
193
+ out.agent.handshake = await runDeepHandshake({
194
+ spawnSpec,
195
+ clientFactory,
196
+ workspace,
197
+ timeoutMs: handshakeTimeoutMs,
198
+ });
199
+ }
200
+
201
+ return out;
202
+ }
package/src/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Every failure this bridge raises carries a `reason`, which is what lets a caller tell
3
+ * "fix your arguments" from "retry" without parsing prose. Errors that came off the wire also
4
+ * carry the agent's JSON-RPC `code`. One shape, one constructor, so the tag is never forgotten
5
+ * and the type checker has something to check against.
6
+ *
7
+ * @typedef {Error & { reason?: string, code?: number }} DelegateError
8
+ */
9
+
10
+ /**
11
+ * @param {string} reason
12
+ * @param {string} message
13
+ * @returns {DelegateError}
14
+ */
15
+ export function makeError(reason, message) {
16
+ /** @type {DelegateError} */
17
+ const err = new Error(message);
18
+ err.reason = reason;
19
+ return err;
20
+ }
package/src/jsonrpc.js ADDED
@@ -0,0 +1,145 @@
1
+ import readline from "node:readline";
2
+
3
+ const FRAME_CAP = 2048;
4
+ const DEFAULT_LOG_SIZE = 2000;
5
+
6
+ function readLogSize(raw) {
7
+ if (raw === undefined) return DEFAULT_LOG_SIZE;
8
+ const n = Number(raw);
9
+ if (!Number.isFinite(n) || n < 0) return DEFAULT_LOG_SIZE;
10
+ return Math.floor(n);
11
+ }
12
+
13
+ // Depth an unparseable AGY_DELEGATE_TRANSCRIPT reads as. Deliberately not DEFAULT_LOG_SIZE:
14
+ // that one bounds what the log retains in memory, this one is how much lands in the caller's
15
+ // context. 1.10.0 removed a 40-frame always-on dump from failure text; opt-in is what buys this
16
+ // budget, so keep it in that neighbourhood.
17
+ const TRANSCRIPT_DEFAULT_FRAMES = 50;
18
+
19
+ // Frames of transcript AGY_DELEGATE_TRANSCRIPT asks for. Unset or blank means none and a
20
+ // number is the count (0 = none); anything unparseable reads as on at the default depth —
21
+ // "true" and "yes" are natural things to set, and silently disabling the transcript on them is
22
+ // the opposite of what the setter wanted.
23
+ export function transcriptFrames(raw = process.env.AGY_DELEGATE_TRANSCRIPT) {
24
+ if (raw === undefined || raw.trim() === "") return 0;
25
+ const n = Number(raw);
26
+ if (!Number.isFinite(n)) return TRANSCRIPT_DEFAULT_FRAMES;
27
+ return Math.max(0, Math.floor(n));
28
+ }
29
+
30
+ export class JsonRpcPeer {
31
+ /**
32
+ * @param {import("node:stream").Readable} input
33
+ * @param {import("node:stream").Writable} output
34
+ * @param {{
35
+ * onNotification?: (method: string, params: any) => void,
36
+ * onRequest?: (id: any, method: string, params: any) => void,
37
+ * onActivity?: () => void,
38
+ * }} handlers
39
+ */
40
+ constructor(input, output, { onNotification, onRequest, onActivity } = {}) {
41
+ this.output = output;
42
+ this.onNotification = onNotification || (() => {});
43
+ this.onRequest = onRequest || (() => {});
44
+ this.onActivity = onActivity || (() => {});
45
+ this.nextId = 1;
46
+ this.pending = new Map();
47
+ // 0 disables recording and is documented; anything unparseable is a typo, and silently
48
+ // disabling the transcript on a typo is the opposite of what the setter wanted.
49
+ this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
50
+ // The failure transcript is the only thing that reads these frames, and it is opt-in, so
51
+ // recording by default retained up to _logSize × FRAME_CAP bytes per delegation that nothing
52
+ // would ever ask for. ACP_LOG_SIZE still bounds retention and still disables at 0.
53
+ this._recording = this._logSize > 0 && transcriptFrames() > 0;
54
+ this._log = [];
55
+ this.rl = readline.createInterface({ input });
56
+ // The interface re-emits the input stream's error as its own, so the handler acp-client.js
57
+ // puts on the child's stdout does not cover this one: an unhandled 'error' here is an
58
+ // uncaught exception, which takes down the server and every concurrent delegation with it.
59
+ this.rl.on("error", () => {});
60
+ this.rl.on("line", (line) => this._onLine(line));
61
+ }
62
+
63
+ // Trimming to the cap on every frame meant shifting a 2000-entry array per frame, which on a
64
+ // chatty turn cost more than parsing the frames. Let the array overshoot by a quarter and trim
65
+ // in one batch; readers below take the last _logSize, so what the log reports is unchanged.
66
+ _record(dir, line) {
67
+ if (!this._recording) return;
68
+ const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
69
+ this._log.push({ t: Date.now(), dir, line: truncated });
70
+ if (this._log.length > this._logSize + (this._logSize >> 2)) {
71
+ this._log = this._log.slice(-this._logSize);
72
+ }
73
+ }
74
+
75
+ _entries() {
76
+ return this._log.length > this._logSize ? this._log.slice(-this._logSize) : this._log;
77
+ }
78
+
79
+ getLog() { return [...this._entries()]; }
80
+
81
+ formatLog(n) {
82
+ const entries = n !== undefined ? this._entries().slice(-n) : this._entries();
83
+ return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
84
+ }
85
+
86
+ _onLine(line) {
87
+ this._record("in", line);
88
+ if (!line.trim()) return;
89
+ let msg;
90
+ try { msg = JSON.parse(line); } catch { return; }
91
+ if (msg === null || typeof msg !== "object" || Array.isArray(msg)) return;
92
+ // Only a parsed frame counts. A blank line, a launcher banner or anything else the agent
93
+ // prints is not the protocol advancing, and treating it as such is what let a chatty
94
+ // launcher hold the idle guard open and made "Last ACP frame Ns ago" report a stderr byte.
95
+ this.onActivity();
96
+ const hasId = msg.id !== undefined && msg.id !== null;
97
+ if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
98
+ // Keyed by string: a peer that echoes "1" for the id 1 is still answering that request,
99
+ // and matching by identity left it pending until a timeout fired an hour later.
100
+ const key = String(msg.id);
101
+ const p = this.pending.get(key);
102
+ if (p) {
103
+ this.pending.delete(key);
104
+ // An agent can put the actual reason in error.data.message; error.message alone
105
+ // is a bare "Invalid params".
106
+ if (msg.error) {
107
+ /** @type {import("./errors.js").DelegateError} */
108
+ const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
109
+ err.code = msg.error.code;
110
+ p.reject(err);
111
+ }
112
+ else p.resolve(msg.result);
113
+ }
114
+ } else if (msg.method && hasId) {
115
+ this.onRequest(msg.id, msg.method, msg.params);
116
+ } else if (msg.method) {
117
+ this.onNotification(msg.method, msg.params);
118
+ }
119
+ }
120
+
121
+ _write(obj) {
122
+ const serialized = JSON.stringify(obj) + "\n";
123
+ this._record("out", serialized);
124
+ this.output.write(serialized);
125
+ }
126
+
127
+ request(method, params) {
128
+ const id = this.nextId++;
129
+ return new Promise((resolve, reject) => {
130
+ this.pending.set(String(id), { resolve, reject });
131
+ this._write({ jsonrpc: "2.0", id, method, params });
132
+ });
133
+ }
134
+
135
+ notify(method, params) { this._write({ jsonrpc: "2.0", method, params }); }
136
+ respond(id, result) { this._write({ jsonrpc: "2.0", id, result }); }
137
+ respondError(id, code, message) { this._write({ jsonrpc: "2.0", id, error: { code, message } }); }
138
+
139
+ rejectAllPending(err) {
140
+ for (const p of this.pending.values()) p.reject(err);
141
+ this.pending.clear();
142
+ }
143
+
144
+ close() { this.rl.close(); }
145
+ }
@@ -0,0 +1,76 @@
1
+ // Config option ids differ per model, and a model rejects any id it does not declare. The set is
2
+ // knowable only once a model is selected, from the configOptions the agent echoes back.
3
+
4
+ // ACP marks a thought/reasoning level selector with category "thought_level" — agy declares
5
+ // thought_level ("Thinking Level") that way. Categories are optional in ACP, so the ids and names
6
+ // below still classify options from an agent that sends none. A match only nominates an option:
7
+ // the requested value must still appear exactly among the values it advertises.
8
+ const THOUGHT_LEVEL_IDS = new Set(["thinking", "reasoning", "effort", "reasoning_effort", "thought_level"]);
9
+ // Never an effort setting, and doctor reports them as currentModel and modes, so a list of what a
10
+ // model offers leaves them out.
11
+ const SELECTOR_IDS = new Set(["model", "mode"]);
12
+
13
+ export function isThoughtLevel(opt) {
14
+ if (opt?.category === "thought_level") return true;
15
+ const id = typeof opt?.id === "string" ? opt.id.toLowerCase() : "";
16
+ if (THOUGHT_LEVEL_IDS.has(id)) return true;
17
+ const name = typeof opt?.name === "string" ? opt.name.toLowerCase() : "";
18
+ return /thinking|reasoning|thought|effort/.test(name);
19
+ }
20
+
21
+ export function optionsFrom(res) {
22
+ return Array.isArray(res?.configOptions) ? res.configOptions : undefined;
23
+ }
24
+
25
+ export function allowedValues(opt) {
26
+ return (Array.isArray(opt?.options) ? opt.options : [])
27
+ .map((o) => o?.value)
28
+ .filter((v) => typeof v === "string");
29
+ }
30
+
31
+ // What a model offers besides the model and mode selectors, as doctor reports it and as an
32
+ // unrecognized effort names it. Optional metadata appears only when the agent sent a string.
33
+ export function describeOptions(options) {
34
+ return (Array.isArray(options) ? options : [])
35
+ .filter((o) => typeof o?.id === "string" && !SELECTOR_IDS.has(o.id))
36
+ .map((o) => ({
37
+ id: o.id,
38
+ ...(typeof o.name === "string" ? { name: o.name } : {}),
39
+ ...(typeof o.category === "string" ? { category: o.category } : {}),
40
+ values: allowedValues(o),
41
+ ...(typeof o.currentValue === "string" ? { currentValue: o.currentValue } : {}),
42
+ }));
43
+ }
44
+
45
+ // The current value of every recognized effort option, keyed by id. All of them rather than one
46
+ // picked: a model can declare a thinking toggle beside a level, and either alone can mislead.
47
+ // Undefined when no recognized option reports a string value.
48
+ export function effortSettings(options) {
49
+ const settings = {};
50
+ for (const o of Array.isArray(options) ? options : []) {
51
+ if (isThoughtLevel(o) && typeof o?.id === "string" && typeof o.currentValue === "string") {
52
+ settings[o.id] = o.currentValue;
53
+ }
54
+ }
55
+ return Object.keys(settings).length > 0 ? settings : undefined;
56
+ }
57
+
58
+ // Resolve only values the selected model advertised. This keeps future vocabularies working
59
+ // without aliases or a ranking table: xhigh, extra-high, max and ultra are just exact tokens.
60
+ // No list, an empty list, or a thought-level option with no usable id/values is unavailable. A
61
+ // list with nothing classified as thought-level is unrecognized — not proof the model has no
62
+ // effort setting: categories are optional and ids get renamed, so the caller is shown the list.
63
+ export function resolveEffort(options, value) {
64
+ if (!Array.isArray(options) || options.length === 0) return { status: "unavailable" };
65
+
66
+ const candidates = options.filter(isThoughtLevel);
67
+ if (candidates.length === 0) return { status: "unrecognized", advertised: describeOptions(options) };
68
+
69
+ const usable = candidates.filter((o) => typeof o?.id === "string");
70
+ const accepted = [...new Set(usable.flatMap(allowedValues))];
71
+ if (usable.length === 0 || accepted.length === 0) return { status: "unavailable" };
72
+
73
+ const pick = usable.find((o) => allowedValues(o).includes(value));
74
+ if (pick === undefined) return { status: "invalid", accepted };
75
+ return { status: "matched", id: pick.id, value };
76
+ }
package/src/proc.js ADDED
@@ -0,0 +1,36 @@
1
+ import process from "node:process";
2
+ import { execFile } from "node:child_process";
3
+
4
+ export function isChildAlive(child) {
5
+ return child && child.exitCode === null && child.signalCode === null;
6
+ }
7
+
8
+ // POSIX only: detached makes the child a process group leader (setsid), which is what lets
9
+ // treeKill reach the agent's own children. On win32 it would mean a separate console instead,
10
+ // and taskkill /T already walks the tree. Every spawn site applies it, not resolveAcpSpawn —
11
+ // an injected spawnSpec has to become a group leader too or the group kill finds nothing.
12
+ export const DETACHED = process.platform !== "win32";
13
+
14
+ // On win32 a plain child.kill() only reaches the shell wrapper (spawn uses shell: true);
15
+ // taskkill /T takes the whole tree so the agent itself dies too.
16
+ export async function treeKill(pid, { childAlive = true } = {}) {
17
+ if (!pid) return;
18
+ if (process.platform === "win32") {
19
+ // taskkill /T walks parent links, which an exited leader no longer has: what it started is
20
+ // either gone with it or detached and out of reach. So a post-exit kill has nothing left to
21
+ // reach, and a reaped pid can already belong to somebody else — which makes the gate the
22
+ // whole of it here, where POSIX still has the group to aim at.
23
+ if (!childAlive) return;
24
+ await /** @type {Promise<void>} */ (new Promise((resolve) => {
25
+ execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve());
26
+ }));
27
+ return;
28
+ }
29
+ // Negative pid signals the whole group, so the agent's descendants go with it. A group outlives
30
+ // its leader while any member is left, which is why this runs even for an exited child: that is
31
+ // the case where descendants are the only thing still running.
32
+ try { process.kill(-pid, "SIGKILL"); } catch {}
33
+ // Reaches a child that is not a group leader, where the group kill raised ESRCH. Skipped once
34
+ // the child is gone, since a reaped pid can already belong to something else.
35
+ if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
36
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @param {{
3
+ * respond: (id: any, result: any) => void,
4
+ * respondError: (id: any, code: number, message: string) => void,
5
+ * }} deps
6
+ */
7
+ export function createRequestRouter({ respond, respondError }) {
8
+ return async function handle(id, method, params) {
9
+ try {
10
+ if (method === "session/request_permission") {
11
+ const opts = params?.options || [];
12
+ // The two allow kinds only. Taking opts[0] when neither is offered returned a reject
13
+ // id under a `selected` outcome, which the agent reads as an approval of the denial —
14
+ // a silent skip from a bridge that advertises auto-approval. agy offers allow_once
15
+ // ("allow") and reject_once ("deny").
16
+ const pick =
17
+ opts.find((o) => o.kind === "allow_always") ||
18
+ opts.find((o) => o.kind === "allow_once");
19
+ // Selecting nothing is not a selection: an options-less request answered with
20
+ // optionId undefined is a malformed ACP response, and a request offering no allow
21
+ // option is one this bridge can approve nothing in. Say cancelled to both and let the
22
+ // agent decide what to do about it.
23
+ if (!pick?.optionId) return respond(id, { outcome: { outcome: "cancelled" } });
24
+ return respond(id, { outcome: { outcome: "selected", optionId: pick.optionId } });
25
+ }
26
+ return respondError(id, -32601, `Unhandled method: ${method}`);
27
+ } catch (err) {
28
+ // -32603, not -32000: ACP assigns -32000 to auth_required, and a bug on this side
29
+ // reported as "authenticate" sends the agent down a recovery path that cannot work.
30
+ if (id != null) return respondError(id, -32603, `Router error: ${err?.message || err}`);
31
+ }
32
+ };
33
+ }