@wengine-ai/ccr-provider-gemini-agy-acp 0.0.2 → 0.2.1

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.
@@ -0,0 +1,389 @@
1
+ /**
2
+ * Local MCP-over-HTTP bridge that advertises the caller's tools to an ACP agent.
3
+ *
4
+ * The agent calls tools/call; the bridge parks the invocation until the caller
5
+ * (e.g. Pi) executes the tool and returns its result on the next request. The
6
+ * bridge never executes a tool itself.
7
+ *
8
+ * This HTTP server is an internal backend: `session/new` advertises the stdio
9
+ * forwarder (agy-mcp-stdio-bridge.mjs), which the agent spawns and which
10
+ * relays its JSON-RPC here. The HTTP descriptor stays for internal callers.
11
+ *
12
+ * Security: listens on 127.0.0.1 only, on an ephemeral port, and requires a
13
+ * random per-bridge bearer token compared with timingSafeEqual. Request bodies
14
+ * and advertised schemas are bounded.
15
+ */
16
+ import { createServer } from 'node:http';
17
+ import { randomUUID, timingSafeEqual } from 'node:crypto';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { fitToolsToBudget } from './agy-tool-budget.mjs';
20
+
21
+ const MAX_BODY_BYTES = 1024 * 1024;
22
+ const MAX_TOOLS = 64;
23
+ // The caller-facing cap and the bridge's own cap must agree: the caller cannot
24
+ // answer a call it was never told about, so a parked call beyond the caller's
25
+ // cap would hang forever.
26
+ export const MAX_CALLS_PER_TURN = 32;
27
+ const MAX_SCHEMA_BYTES = 64 * 1024;
28
+
29
+ /**
30
+ * Project only representable constraints. A tool that cannot be represented is
31
+ * omitted whole rather than silently widened — the caller must be told.
32
+ */
33
+ function projectSchema(value, depth, budget) {
34
+ if (depth > 8) return { reason: 'too_deep' };
35
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { reason: 'not_object' };
36
+ if (budget.work <= 0) return { reason: 'too_large' };
37
+ budget.work -= 1;
38
+ const output = {};
39
+ for (const [key, candidate] of Object.entries(value)) {
40
+ // Annotations carry no constraint; dropping them cannot widen the schema.
41
+ if (['$schema', '$id', '$comment', 'title', 'description', 'examples', 'default', 'deprecated',
42
+ 'readOnly', 'writeOnly'].includes(key)) continue;
43
+ if (key === 'properties') {
44
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return { reason: 'invalid_keyword_value' };
45
+ const properties = {};
46
+ for (const [name, schema] of Object.entries(candidate)) {
47
+ if (['__proto__', 'constructor', 'prototype'].includes(name)) return { reason: 'unsafe_property_name' };
48
+ const projected = projectSchema(schema, depth + 1, budget);
49
+ if ('reason' in projected) return projected;
50
+ properties[name] = projected.schema;
51
+ }
52
+ output.properties = properties;
53
+ continue;
54
+ }
55
+ if (key === 'items' || (key === 'additionalProperties' && typeof candidate !== 'boolean')) {
56
+ const projected = projectSchema(candidate, depth + 1, budget);
57
+ if ('reason' in projected) return projected;
58
+ output[key] = projected.schema;
59
+ continue;
60
+ }
61
+ if (['anyOf', 'oneOf', 'allOf'].includes(key)) {
62
+ if (!Array.isArray(candidate) || !candidate.length) return { reason: 'invalid_keyword_value' };
63
+ const variants = [];
64
+ for (const item of candidate) {
65
+ const projected = projectSchema(item, depth + 1, budget);
66
+ if ('reason' in projected) return projected;
67
+ variants.push(projected.schema);
68
+ }
69
+ output[key] = variants;
70
+ continue;
71
+ }
72
+ if (['enum', 'required'].includes(key) || (key === 'type' && Array.isArray(candidate))) {
73
+ if (!Array.isArray(candidate) || !candidate.length) return { reason: 'invalid_keyword_value' };
74
+ if (key === 'required' && !candidate.every(item => typeof item === 'string')) return { reason: 'invalid_keyword_value' };
75
+ output[key] = candidate.slice(0, 128);
76
+ continue;
77
+ }
78
+ if (['type', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum',
79
+ 'minLength', 'maxLength', 'minItems', 'maxItems', 'minProperties', 'maxProperties',
80
+ 'const', 'multipleOf'].includes(key)) {
81
+ // `type` must name a JSON type; anything else cannot be projected and
82
+ // would silently widen the advertised schema, so the tool is omitted.
83
+ if (key === 'type' && !['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'].includes(candidate)) {
84
+ return { reason: 'unsupported_keyword' };
85
+ }
86
+ output[key] = candidate;
87
+ continue;
88
+ }
89
+ if (['uniqueItems', 'additionalProperties'].includes(key) && typeof candidate === 'boolean') {
90
+ output[key] = candidate;
91
+ continue;
92
+ }
93
+ return { reason: 'unsupported_keyword' };
94
+ }
95
+ // Never infer a type: beside const/enum/combinators that could contradict a
96
+ // valid typeless schema. An empty object schema legitimately allows anything.
97
+ if (output.type === undefined && output.properties === undefined &&
98
+ output.anyOf === undefined && output.oneOf === undefined && output.allOf === undefined) {
99
+ output.type = 'object';
100
+ }
101
+ if (Buffer.byteLength(JSON.stringify(output), 'utf8') > MAX_SCHEMA_BYTES) return { reason: 'too_large' };
102
+ return { schema: output };
103
+ }
104
+
105
+ /** One OpenAI tool → its MCP projection, or the reason it must be omitted. */
106
+ export function projectTool(tool) {
107
+ if (!tool || typeof tool !== 'object') return { reason: 'not_object' };
108
+ const fn = tool.type === 'function' ? tool.function : tool;
109
+ if (!fn || typeof fn !== 'object' || typeof fn.name !== 'string' || !fn.name.trim()) return { reason: 'missing_name' };
110
+ const name = fn.name.trim();
111
+ if (name.length > 128) return { reason: 'name_too_long' };
112
+ const mcpName = `ccr_${name}`.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
113
+ if (!mcpName) return { reason: 'invalid_name' };
114
+ const projected = projectSchema(fn.parameters ?? { type: 'object', properties: {} }, 0, { work: 5000 });
115
+ if ('reason' in projected) return { reason: projected.reason };
116
+ return {
117
+ mcpName,
118
+ callerName: name,
119
+ description: typeof fn.description === 'string' ? fn.description.slice(0, 1024) : name,
120
+ inputSchema: projected.schema,
121
+ };
122
+ }
123
+
124
+ /** Project a caller tool list; keeps order, drops duplicates and omissions. */
125
+ export function projectTools(tools) {
126
+ if (!Array.isArray(tools) || tools.length > MAX_TOOLS) {
127
+ return { tools: [], omitted: [{ name: '*', reason: 'too_many_tools' }] };
128
+ }
129
+ const projected = [];
130
+ const omitted = [];
131
+ const seen = new Set();
132
+ for (const tool of tools) {
133
+ const result = projectTool(tool);
134
+ if ('reason' in result) {
135
+ omitted.push({ name: String(tool?.function?.name ?? tool?.name ?? '?'), reason: result.reason });
136
+ continue;
137
+ }
138
+ if (seen.has(result.mcpName)) {
139
+ omitted.push({ name: result.callerName, reason: 'duplicate_name' });
140
+ continue;
141
+ }
142
+ seen.add(result.mcpName);
143
+ projected.push(result);
144
+ }
145
+ return { tools: projected, omitted };
146
+ }
147
+
148
+ function validToken(header, expected) {
149
+ const actual = Buffer.from(typeof header === 'string' ? header : '');
150
+ const wanted = Buffer.from(`Bearer ${expected}`);
151
+ return actual.byteLength === wanted.byteLength && timingSafeEqual(actual, wanted);
152
+ }
153
+
154
+ function toolError(text) {
155
+ return { content: [{ type: 'text', text }], isError: true };
156
+ }
157
+
158
+ /**
159
+ * Accept either an MCP result (`{content, isError}`) or the caller's own
160
+ * `{text, isError}` shape, and normalise to the MCP result shape.
161
+ */
162
+ function asMcpResult(value) {
163
+ if (!value || typeof value !== 'object') return toolError('Invalid tool result');
164
+ if (Array.isArray(value.content)) return value;
165
+ if (typeof value.text === 'string') {
166
+ return { content: [{ type: 'text', text: value.text }], isError: value.isError === true };
167
+ }
168
+ return toolError('Invalid tool result');
169
+ }
170
+
171
+ async function readJson(request) {
172
+ const chunks = [];
173
+ let size = 0;
174
+ for await (const chunk of request) {
175
+ size += chunk.length;
176
+ if (size > MAX_BODY_BYTES) throw new Error('body too large');
177
+ chunks.push(chunk);
178
+ }
179
+ try {
180
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
181
+ } catch {
182
+ throw new Error('invalid json');
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Bridge one caller tool set into an MCP HTTP server. `onCall` must return a
188
+ * promise that resolves with the MCP result once the caller has executed it.
189
+ */
190
+ export class AgyToolBridge {
191
+ constructor(tools, onCall) {
192
+ const { tools: projected, omitted } = projectTools(tools);
193
+ this.tools = projected;
194
+ this.omitted = omitted;
195
+ this.onCall = onCall;
196
+ this.token = randomUUID().replaceAll('-', '');
197
+ this.server = undefined;
198
+ this.url = undefined;
199
+ this.calls = 0;
200
+ this.closed = false;
201
+ // Every invocation this bridge has started, in arrival order. The agent's
202
+ // own ACP notification carries a different id, so the caller-visible id is
203
+ // taken from here instead.
204
+ this.invocations = [];
205
+ // Notified when a call is parked, with the bridge's own invocation.
206
+ this.onParked = null;
207
+ // Parked calls: id → a function that answers the waiting MCP request.
208
+ this.pending = new Map();
209
+ }
210
+
211
+ /** True when nothing can be advertised; the caller must be told, not ignored. */
212
+ get empty() {
213
+ return this.tools.length === 0;
214
+ }
215
+
216
+ /** MCP server descriptor for ACP `session/new`. Undefined when nothing to offer. */
217
+ async start() {
218
+ if (this.empty || this.closed) return undefined;
219
+ if (this.server && this.url) return this.descriptor();
220
+ this.server = createServer((request, response) => {
221
+ this.handle(request, response).catch(() => {
222
+ if (!response.headersSent) response.writeHead(500, { 'content-type': 'application/json' });
223
+ response.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'bridge error' } }));
224
+ });
225
+ });
226
+ this.server.on('error', () => { this.server = undefined; this.url = undefined; });
227
+ await new Promise((resolve, reject) => {
228
+ this.server.once('error', reject);
229
+ this.server.listen(0, '127.0.0.1', resolve);
230
+ });
231
+ const address = this.server.address();
232
+ if (!address || typeof address === 'string') throw new Error('bridge_bind_failed');
233
+ this.url = `http://127.0.0.1:${address.port}/mcp`;
234
+ return this.descriptor();
235
+ }
236
+
237
+ descriptor() {
238
+ if (!this.url) throw new Error('bridge_not_listening');
239
+ return {
240
+ type: 'http',
241
+ name: 'ccr-caller-tools',
242
+ url: this.url,
243
+ headers: [{ name: 'Authorization', value: `Bearer ${this.token}` }],
244
+ };
245
+ }
246
+
247
+ /**
248
+ * ACP stdio MCP server for `session/new`: the agent spawns the forwarder
249
+ * with the current node runtime (no shell) and reaches this bridge through
250
+ * it. The endpoint and bearer token travel in env, never on the command
251
+ * line. The forwarder file sits next to this module in src and dist alike.
252
+ */
253
+ stdioDescriptor() {
254
+ if (!this.url) throw new Error('bridge_not_listening');
255
+ return {
256
+ name: 'ccr-caller-tools',
257
+ // The desktop shell may spawn us with a verbatim \\?\ executable path;
258
+ // Go's exec.LookPath cannot resolve that form, so agy would silently
259
+ // drop the server. Hand the agent a plain Win32 path instead.
260
+ command: process.execPath.replace(/^\\\\\?\\/, ''),
261
+ args: [fileURLToPath(new URL('./agy-mcp-stdio-bridge.mjs', import.meta.url))],
262
+ env: [
263
+ { name: 'CCR_MCP_ENDPOINT', value: this.url },
264
+ { name: 'CCR_MCP_TOKEN', value: this.token },
265
+ ],
266
+ };
267
+ }
268
+
269
+ async close() {
270
+ this.closed = true;
271
+ // Settle anything still parked so a waiting MCP request cannot hang.
272
+ for (const answer of this.pending.values()) {
273
+ answer({ content: [{ type: 'text', text: 'The tool bridge closed before the caller returned this result' }], isError: true });
274
+ }
275
+ this.pending.clear();
276
+ const server = this.server;
277
+ this.server = undefined;
278
+ this.url = undefined;
279
+ if (!server) return;
280
+ await new Promise(resolve => {
281
+ server.close(() => resolve());
282
+ server.closeAllConnections?.();
283
+ });
284
+ }
285
+
286
+ async handle(request, response) {
287
+ if (this.closed) { response.writeHead(503).end(); return; }
288
+ let url;
289
+ try { url = new URL(request.url, 'http://127.0.0.1'); } catch { response.writeHead(400).end(); return; }
290
+ if (url.pathname !== '/mcp' || request.method !== 'POST') { response.writeHead(405).end(); return; }
291
+ if (!validToken(request.headers.authorization, this.token)) { response.writeHead(401).end(); return; }
292
+ let body;
293
+ try { body = await readJson(request); } catch { response.writeHead(400).end(); return; }
294
+ if (!body || typeof body !== 'object' || Array.isArray(body) || body.jsonrpc !== '2.0') {
295
+ response.writeHead(400).end();
296
+ return;
297
+ }
298
+ const { id, method, params } = body;
299
+ if (id === undefined || id === null || typeof method !== 'string') {
300
+ response.writeHead(200, { 'content-type': 'application/json' });
301
+ response.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'invalid request' } }));
302
+ return;
303
+ }
304
+ const reply = result => {
305
+ if (response.writableEnded) return;
306
+ response.writeHead(200, { 'content-type': 'application/json' });
307
+ response.end(JSON.stringify({ jsonrpc: '2.0', id, result }));
308
+ };
309
+ const fail = (code, message) => {
310
+ if (response.writableEnded) return;
311
+ response.writeHead(200, { 'content-type': 'application/json' });
312
+ response.end(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }));
313
+ };
314
+ if (method === 'server/discover') {
315
+ // MCP 2026-07-28 sessionless discovery (SEP-2575). agy probes this before
316
+ // initialize; advertise the legacy revisions we serve so it negotiates
317
+ // down to the initialize handshake instead of dropping the server.
318
+ reply({
319
+ resultType: 'complete',
320
+ supportedVersions: ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'],
321
+ capabilities: { tools: {} },
322
+ _meta: { 'io.modelcontextprotocol/serverInfo': { name: 'ccr-caller-tools', version: '1.0.0' } },
323
+ ttlMs: 0,
324
+ cacheScope: 'private',
325
+ });
326
+ return;
327
+ }
328
+ if (method === 'initialize') {
329
+ // MCP protocolVersion is a string date revision, not a number. Echo the
330
+ // client's requested revision when it is one we serve; otherwise fall
331
+ // back to the newest supported so the handshake never mismatches.
332
+ const supported = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
333
+ const requested = typeof params?.protocolVersion === 'string' ? params.protocolVersion : null;
334
+ reply({
335
+ protocolVersion: requested && supported.includes(requested) ? requested : '2025-11-25',
336
+ capabilities: { tools: {} },
337
+ serverInfo: { name: 'ccr-caller-tools', version: '1.0.0' },
338
+ });
339
+ return;
340
+ }
341
+ if (method === 'tools/list') {
342
+ // alwaysLoad keeps each entry loaded even when agy's shared
343
+ // customization budget would otherwise drop it; the fitter then trims
344
+ // only description prose so every tool stays listed, schema intact.
345
+ const listed = fitToolsToBudget(this.tools.map(tool => ({
346
+ name: tool.mcpName, description: tool.description, inputSchema: tool.inputSchema,
347
+ _meta: { ...(tool.meta || {}), 'antigravity/alwaysLoad': true },
348
+ })));
349
+ reply({ tools: listed });
350
+ return;
351
+ }
352
+ if (method === 'tools/call') {
353
+ if (this.calls >= MAX_CALLS_PER_TURN) { reply(toolError('Too many tool calls in one turn')); return; }
354
+ const tool = this.tools.find(candidate => candidate.mcpName === params?.name);
355
+ if (!tool) { reply(toolError('Unknown tool')); return; }
356
+ this.calls += 1;
357
+ // The bridge mints the caller-visible id, so the id the caller quotes
358
+ // back on its follow-up always matches a parked entry even though the
359
+ // agent reports its own ACP id separately.
360
+ const invocation = {
361
+ id: `call_${randomUUID().replaceAll('-', '').slice(0, 24)}`,
362
+ name: tool.callerName,
363
+ mcpName: tool.mcpName,
364
+ arguments: params?.arguments ?? {},
365
+ };
366
+ this.invocations.push(invocation);
367
+ // Register the parked entry BEFORE anyone is told about the call. A turn
368
+ // that saw "a call was raised" while the entry did not exist yet would
369
+ // close the bridge under a live call and leak the listening socket.
370
+ // `answer` is how the caller delivers its result; the returned promise is
371
+ // what keeps this MCP request — and the ACP turn — open until then.
372
+ let answer;
373
+ const delivered = new Promise(resolve => { answer = resolve; });
374
+ this.pending.set(invocation.id, answer);
375
+ this.onParked?.(invocation);
376
+ let result;
377
+ try {
378
+ result = await Promise.race([delivered, this.onCall(invocation)]);
379
+ } catch {
380
+ result = toolError('The tool call could not be completed');
381
+ }
382
+ this.pending.delete(invocation.id);
383
+ reply(asMcpResult(result));
384
+ return;
385
+ }
386
+ if (method.startsWith('notifications/')) { response.writeHead(202).end(); return; }
387
+ fail(-32601, 'Method not found');
388
+ }
389
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Fit a caller tool listing into agy's shared customization budget.
3
+ *
4
+ * agy loads every session MCP tool into one customization budget of roughly
5
+ * 20,000 tokens, counted as ceil(UTF-8 bytes / 3) over each serialized tool
6
+ * entry, and silently drops whole tools (largest first) past it. Fitting
7
+ * trims only description prose — binary-searching one byte cap applied to
8
+ * every description string, including nested schema descriptions — so every
9
+ * tool stays listed and no name, type, enum, required, items or schema key
10
+ * ever changes.
11
+ */
12
+ export const TOOL_TOKEN_BUDGET = 18000;
13
+
14
+ function tokensOf(tools) {
15
+ return tools.reduce((total, tool) => total + Math.ceil(Buffer.byteLength(JSON.stringify(tool), 'utf8') / 3), 0);
16
+ }
17
+
18
+ // Descriptions cut shorter than this say nothing ("The fil…") and only spend
19
+ // the budget on their key, so a cap below it drops the text entirely.
20
+ const MIN_DESCRIPTION_BYTES = 24;
21
+
22
+ // Shortens text to at most `max` UTF-8 bytes: a trailing Examples block goes
23
+ // first, then a sentence boundary near the cut, marked with "…".
24
+ function cutDescription(text, max) {
25
+ if (Buffer.byteLength(text, 'utf8') <= max) return text;
26
+ const bare = text.replace(/\s*\bExamples?:[\s\S]*$/i, '').trimEnd();
27
+ if (bare && Buffer.byteLength(bare, 'utf8') <= max) return bare;
28
+ const room = max - Buffer.byteLength('…', 'utf8');
29
+ if (room < 4) return undefined;
30
+ // Accumulate whole code points so a multi-byte character is never split.
31
+ let out = '';
32
+ let used = 0;
33
+ for (const ch of bare || text) {
34
+ const size = Buffer.byteLength(ch, 'utf8');
35
+ if (used + size > room) break;
36
+ out += ch;
37
+ used += size;
38
+ }
39
+ const stop = Math.max(...['. ', '; ', '。', ';'].map(sep => out.lastIndexOf(sep)));
40
+ if (stop > out.length / 2) out = out.slice(0, stop + 1);
41
+ return out.trimEnd() + '…';
42
+ }
43
+
44
+ function trimDescription(text, cap) {
45
+ if (Buffer.byteLength(text, 'utf8') <= cap) return text;
46
+ return cap < MIN_DESCRIPTION_BYTES ? undefined : cutDescription(text, cap);
47
+ }
48
+
49
+ // Recursively caps every `description` string; every other key and value
50
+ // passes through untouched, so no schema constraint ever moves.
51
+ function shapeDescriptions(node, cap) {
52
+ if (Array.isArray(node)) return node.map(item => shapeDescriptions(item, cap));
53
+ if (node === null || typeof node !== 'object') return node;
54
+ const out = {};
55
+ for (const [key, value] of Object.entries(node)) {
56
+ if (key === 'description' && typeof value === 'string') {
57
+ const text = trimDescription(value, cap);
58
+ if (text !== undefined) out.description = text;
59
+ continue;
60
+ }
61
+ out[key] = shapeDescriptions(value, cap);
62
+ }
63
+ return out;
64
+ }
65
+
66
+ function shapeTool(tool, cap) {
67
+ const out = { ...tool };
68
+ if (typeof tool.description === 'string') {
69
+ const text = trimDescription(tool.description, cap);
70
+ if (text === undefined) delete out.description;
71
+ else out.description = text;
72
+ }
73
+ if (tool.inputSchema !== undefined) out.inputSchema = shapeDescriptions(tool.inputSchema, cap);
74
+ return out;
75
+ }
76
+
77
+ function longestDescription(tools) {
78
+ let max = 0;
79
+ const visit = node => {
80
+ if (Array.isArray(node)) {
81
+ for (const item of node) visit(item);
82
+ return;
83
+ }
84
+ if (node === null || typeof node !== 'object') return;
85
+ for (const [key, value] of Object.entries(node)) {
86
+ if (key === 'description' && typeof value === 'string') {
87
+ max = Math.max(max, Buffer.byteLength(value, 'utf8'));
88
+ } else {
89
+ visit(value);
90
+ }
91
+ }
92
+ };
93
+ for (const tool of tools) {
94
+ if (typeof tool.description === 'string') max = Math.max(max, Buffer.byteLength(tool.description, 'utf8'));
95
+ visit(tool.inputSchema);
96
+ }
97
+ return max;
98
+ }
99
+
100
+ /** Pure: when the listed tools exceed the token budget, progressively
101
+ * shorten only description text (binary-searching one byte cap applied to
102
+ * every description) and never drop a tool. Fitting lists return unchanged. */
103
+ export function fitToolsToBudget(tools, budget = TOOL_TOKEN_BUDGET) {
104
+ if (!Array.isArray(tools) || tools.length === 0) return tools;
105
+ if (tokensOf(tools) <= budget) return tools;
106
+ const at = cap => tools.map(tool => shapeTool(tool, cap));
107
+ // Even with every description gone the list is over budget: keep every
108
+ // tool and let the agent see as much schema as fits.
109
+ if (tokensOf(at(0)) > budget) return at(0);
110
+ // Largest cap whose shape still fits. At the longest description the
111
+ // shape is the original over-budget list, so the search always narrows.
112
+ let lo = 0;
113
+ let hi = longestDescription(tools);
114
+ while (lo < hi) {
115
+ const mid = Math.ceil((lo + hi) / 2);
116
+ if (tokensOf(at(mid)) <= budget) lo = mid;
117
+ else hi = mid - 1;
118
+ }
119
+ return at(lo);
120
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Caller-side tool plumbing for the Agy ACP provider.
3
+ *
4
+ * Extracts an OpenAI-compatible tool declaration and its results from the
5
+ * caller's request body, and matches a follow-up request's tool results against
6
+ * the calls the ACP agent parked earlier.
7
+ *
8
+ * The caller executes every tool. This module only carries names, arguments
9
+ * and results across the two HTTP requests.
10
+ */
11
+
12
+ const MAX_TOOL_CALLS = 32;
13
+ const MAX_ARGUMENT_BYTES = 256 * 1024;
14
+
15
+ function textOf(content) {
16
+ if (typeof content === 'string') return content;
17
+ if (Array.isArray(content)) {
18
+ const parts = [];
19
+ for (const item of content) {
20
+ if (typeof item === 'string') parts.push(item);
21
+ else if (item && typeof item === 'object' && typeof item.text === 'string') parts.push(item.text);
22
+ }
23
+ return parts.join('\n');
24
+ }
25
+ return '';
26
+ }
27
+
28
+ /** True when the caller declared at least one usable tool. */
29
+ export function declaresTools(body) {
30
+ if (!body || typeof body !== 'object') return false;
31
+ if (Array.isArray(body.tools) && body.tools.some(tool => typeof tool?.function?.name === 'string' && tool.function.name.trim())) return true;
32
+ return Array.isArray(body.functions) && body.functions.some(fn => typeof fn?.name === 'string' && fn.name.trim());
33
+ }
34
+
35
+ /**
36
+ * True when a tool choice is one the bridge can honour. Anything else — an
37
+ * unknown string, a forced specific function, or a non-object — is rejected
38
+ * rather than silently ignored, so the caller is never told a tool was
39
+ * available when the agent would not have been steered to it.
40
+ */
41
+ export function toolChoiceShapeOk(body) {
42
+ const choice = body?.tool_choice ?? body?.function_call;
43
+ if (choice == null) return true;
44
+ if (typeof choice === 'string') return choice === 'auto' || choice === 'none';
45
+ if (typeof choice !== 'object') return false;
46
+ const fn = choice.function ?? choice;
47
+ // A named function choice has no equivalent the bridge can enforce.
48
+ return !(typeof fn?.name === 'string' && fn.name.trim());
49
+ }
50
+
51
+ /** Normalize a caller tool declaration into the OpenAI shape. */
52
+ export function declaredTools(body) {
53
+ const output = [];
54
+ const push = tool => {
55
+ if (!tool || typeof tool !== 'object') return;
56
+ const fn = tool.type === 'function' ? tool.function : tool;
57
+ if (!fn || typeof fn.name !== 'string' || !fn.name.trim()) return;
58
+ output.push({ type: 'function', function: {
59
+ name: fn.name.trim(),
60
+ ...(typeof fn.description === 'string' ? { description: fn.description } : {}),
61
+ ...(fn.parameters && typeof fn.parameters === 'object' ? { parameters: fn.parameters } : {}),
62
+ } });
63
+ };
64
+ if (Array.isArray(body?.tools)) body.tools.forEach(push);
65
+ if (Array.isArray(body?.functions)) body.functions.forEach(push);
66
+ return output.slice(0, MAX_TOOL_CALLS);
67
+ }
68
+
69
+ /** Extract tool calls the caller's assistant turn already carries. */
70
+ export function historyToolCalls(messages) {
71
+ const output = [];
72
+ if (!Array.isArray(messages)) return output;
73
+ for (const message of messages) {
74
+ if (message?.role !== 'assistant' || !Array.isArray(message.tool_calls)) continue;
75
+ for (const call of message.tool_calls) {
76
+ const fn = call?.function;
77
+ if (typeof fn?.name !== 'string' || !fn.name.trim()) continue;
78
+ let args = {};
79
+ if (typeof fn.arguments === 'string' && fn.arguments) {
80
+ try {
81
+ const parsed = JSON.parse(fn.arguments);
82
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) args = parsed;
83
+ } catch { /* keep empty */ }
84
+ }
85
+ output.push({
86
+ id: typeof call.id === 'string' && call.id ? call.id : `call_${output.length}`,
87
+ name: fn.name.trim(),
88
+ arguments: args,
89
+ });
90
+ }
91
+ }
92
+ return output.slice(0, MAX_TOOL_CALLS);
93
+ }
94
+
95
+ /** Extract tool results the caller returned, keyed by tool_call_id. */
96
+ export function toolResults(messages) {
97
+ const output = new Map();
98
+ if (!Array.isArray(messages)) return output;
99
+ for (const message of messages) {
100
+ if (message?.role !== 'tool' || typeof message.tool_call_id !== 'string' || !message.tool_call_id) continue;
101
+ output.set(message.tool_call_id, {
102
+ text: textOf(message.content).slice(0, MAX_ARGUMENT_BYTES),
103
+ isError: message.is_error === true,
104
+ });
105
+ }
106
+ return output;
107
+ }
108
+
109
+ /** True when every carried call has a matching caller result. */
110
+ export function hasCompleteResults(calls, messages) {
111
+ if (!calls.length) return false;
112
+ const results = toolResults(messages);
113
+ return calls.every(call => results.has(call.id));
114
+ }
115
+
116
+ /**
117
+ * Build the ACP prompt text for a follow-up request that carries tool results.
118
+ * The agent is told the actions completed so it does not repeat them.
119
+ *
120
+ * Any message the caller sent after the tool results — typically the user's next
121
+ * instruction — is carried too: dropping it would silently discard what the
122
+ * caller actually asked for on this turn.
123
+ */
124
+ export function toolResultPrompt(calls, messages) {
125
+ const results = toolResults(messages);
126
+ const lines = ['The following tool calls have completed. Use their results to continue; do not repeat completed actions.'];
127
+ for (const call of calls) {
128
+ const result = results.get(call.id);
129
+ if (!result) continue;
130
+ lines.push(`Tool: ${call.name}`);
131
+ lines.push(`Arguments: ${JSON.stringify(call.arguments)}`);
132
+ lines.push(`Result: ${result.isError ? '(error) ' : ''}${result.text}`);
133
+ lines.push('');
134
+ }
135
+ // Everything after the last tool result belongs to this turn. Assistant text
136
+ // is skipped: it is what the agent itself produced before parking.
137
+ const lastResult = messages.reduce((found, message, index) => message?.role === 'tool' ? index : found, -1);
138
+ if (lastResult >= 0) {
139
+ for (const message of messages.slice(lastResult + 1)) {
140
+ if (message?.role !== 'user' && message?.role !== 'system') continue;
141
+ const text = textOf(message.content);
142
+ if (text) lines.push(text);
143
+ }
144
+ }
145
+ return lines.join('\n');
146
+ }