pi-agy-acp 0.1.2 → 0.1.4

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/mcp-bridge.ts CHANGED
@@ -88,6 +88,8 @@ export interface McpBridgeOptions {
88
88
  log?: (message: string) => void
89
89
  }
90
90
 
91
+ const MAX_BODY_BYTES = 1_048_576
92
+
91
93
  const MCP_PROTOCOL_VERSION = '2025-06-18'
92
94
  const CONVERSATION_META_KEY = 'antigravity.google/conversation_id'
93
95
 
@@ -121,12 +123,37 @@ export class McpBridge {
121
123
  /** Bind the loopback listener on an ephemeral port. */
122
124
  async start(): Promise<void> {
123
125
  if (this.server !== undefined) return
124
- const server = createServer((req, res) => {
125
- void this.handle(req, res)
126
- })
127
- server.keepAliveTimeout = 0
128
- server.requestTimeout = 0
129
- server.headersTimeout = 0
126
+ const server = createServer(
127
+ {
128
+ headersTimeout: 10_000,
129
+ requestTimeout: 30_000,
130
+ connectionsCheckingInterval: 1_000,
131
+ },
132
+ (req, res) => {
133
+ req.on('error', (error) => {
134
+ this.log(`mcp: request stream error: ${error.message}`)
135
+ res.destroy()
136
+ })
137
+ res.on('error', (error) => {
138
+ this.log(`mcp: response stream error: ${error.message}`)
139
+ res.destroy()
140
+ })
141
+ void this.handle(req, res).catch((error: unknown) => {
142
+ this.log(`mcp: request failed: ${error instanceof Error ? error.message : 'unknown error'}`)
143
+ if (res.headersSent || res.destroyed) {
144
+ res.destroy()
145
+ return
146
+ }
147
+ // Close after flushing the error, including clients still uploading a body.
148
+ res.writeHead(error instanceof HttpError ? error.status : 500, {
149
+ connection: 'close',
150
+ })
151
+ res.end(() => res.destroy())
152
+ })
153
+ },
154
+ )
155
+ // Node's _http_server.checkConnections bounds reception, not completed SSE requests.
156
+ server.on('error', (error) => this.log(`mcp: server error: ${error.message}`))
130
157
  await new Promise<void>((resolve, reject) => {
131
158
  server.once('error', reject)
132
159
  server.listen(0, '127.0.0.1', () => {
@@ -146,7 +173,11 @@ export class McpBridge {
146
173
  this.openResponses.clear()
147
174
  this.handshakes.clear()
148
175
  if (server !== undefined)
149
- await new Promise<void>((resolve) => server.close(() => resolve()))
176
+ await new Promise<void>((resolve) => {
177
+ server.close(() => resolve())
178
+ // Node's closeAllConnections includes parsers with incomplete headers/bodies.
179
+ server.closeAllConnections()
180
+ })
150
181
  }
151
182
 
152
183
  /**
@@ -163,11 +194,24 @@ export class McpBridge {
163
194
  if (tenantKey !== undefined) this.handshakes.delete(tenantKey)
164
195
  }
165
196
 
197
+ private log(message: string): void {
198
+ try {
199
+ this.options.log?.(message)
200
+ } catch {
201
+ // A diagnostic sink must not escape the HTTP error boundary.
202
+ }
203
+ }
204
+
166
205
  private async handle(
167
206
  req: IncomingMessage,
168
207
  res: ServerResponse,
169
208
  ): Promise<void> {
170
- const url = new URL(req.url ?? '/', 'http://127.0.0.1')
209
+ let url: URL
210
+ try {
211
+ url = new URL(req.url ?? '/', 'http://127.0.0.1')
212
+ } catch {
213
+ throw new HttpError(400)
214
+ }
171
215
  const segments = url.pathname.split('/').filter(Boolean)
172
216
  if (segments[0] !== 'mcp' || segments.length > 2) {
173
217
  res.writeHead(404).end()
@@ -196,9 +240,10 @@ export class McpBridge {
196
240
  res.writeHead(405, { allow: 'POST, DELETE' }).end()
197
241
  return
198
242
  }
243
+ const text = await readBody(req)
199
244
  let body: unknown
200
245
  try {
201
- body = JSON.parse(await readBody(req))
246
+ body = JSON.parse(text)
202
247
  } catch (_invalidJson) {
203
248
  // An unparsable body cannot be answered with a request id.
204
249
  writeJson(res, 400, {
@@ -301,6 +346,7 @@ export class McpBridge {
301
346
  ? (meta[CONVERSATION_META_KEY] as string)
302
347
  : undefined
303
348
 
349
+ if (res.destroyed || res.closed) return
304
350
  res.writeHead(200, {
305
351
  'content-type': 'text/event-stream',
306
352
  'cache-control': 'no-cache, no-transform',
@@ -310,30 +356,39 @@ export class McpBridge {
310
356
  this.openResponses.add(res)
311
357
  const controller = new AbortController()
312
358
  let settled = false
359
+ let keepAlive: ReturnType<typeof setInterval> | undefined
313
360
  const onClose = (): void => {
314
361
  this.openResponses.delete(res)
362
+ clearInterval(keepAlive)
315
363
  if (!settled)
316
364
  controller.abort(new Error('MCP client closed the tool call'))
317
365
  }
318
366
  res.on('close', onClose)
319
367
  let ticks = 0
320
- const keepAlive = setInterval(() => {
321
- if (res.writableEnded) return
368
+ keepAlive = setInterval(() => {
369
+ if (res.writableEnded || res.destroyed) return
322
370
  ticks++
323
- res.write(': keepalive\n\n')
324
- if (
325
- typeof progressToken === 'string' ||
326
- typeof progressToken === 'number'
327
- ) {
328
- writeEvent(res, {
329
- jsonrpc: '2.0',
330
- method: 'notifications/progress',
331
- params: {
332
- progressToken,
333
- progress: ticks,
334
- message: 'Pi is running the tool',
335
- },
336
- })
371
+ try {
372
+ res.write(': keepalive\n\n')
373
+ if (
374
+ typeof progressToken === 'string' ||
375
+ typeof progressToken === 'number'
376
+ ) {
377
+ writeEvent(res, {
378
+ jsonrpc: '2.0',
379
+ method: 'notifications/progress',
380
+ params: {
381
+ progressToken,
382
+ progress: ticks,
383
+ message: 'Pi is running the tool',
384
+ },
385
+ })
386
+ }
387
+ } catch (error) {
388
+ clearInterval(keepAlive)
389
+ this.log(
390
+ `mcp: keepalive write failed: ${error instanceof Error ? error.message : 'unknown error'}`,
391
+ )
337
392
  }
338
393
  }, this.options.keepAliveMs)
339
394
 
@@ -367,7 +422,7 @@ export class McpBridge {
367
422
  this.openResponses.delete(res)
368
423
  res.off('close', onClose)
369
424
  if (controller.signal.aborted)
370
- this.options.log?.(
425
+ this.log(
371
426
  `mcp: call ${name} finished after the agent disconnected`,
372
427
  )
373
428
  }
@@ -384,9 +439,26 @@ function isRecord(value: unknown): value is Record<string, unknown> {
384
439
  return value !== null && typeof value === 'object' && !Array.isArray(value)
385
440
  }
386
441
 
442
+ class HttpError extends Error {
443
+ readonly status: number
444
+
445
+ constructor(status: number) {
446
+ super(`HTTP ${status}`)
447
+ this.status = status
448
+ }
449
+ }
450
+
387
451
  async function readBody(req: IncomingMessage): Promise<string> {
452
+ if (Number(req.headers['content-length']) > MAX_BODY_BYTES)
453
+ throw new HttpError(413)
388
454
  const chunks: Buffer[] = []
389
- for await (const chunk of req) chunks.push(chunk as Buffer)
455
+ let bytes = 0
456
+ // Readable.iterator otherwise destroys the socket on early exit, losing the 413.
457
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
458
+ bytes += chunk.length
459
+ if (bytes > MAX_BODY_BYTES) throw new HttpError(413)
460
+ chunks.push(chunk as Buffer)
461
+ }
390
462
  return Buffer.concat(chunks).toString('utf8')
391
463
  }
392
464
 
@@ -406,13 +478,13 @@ function writeEvent(res: ServerResponse, value: unknown): void {
406
478
  /**
407
479
  * Diff active tools against the session's known tool set and render a compact
408
480
  * `<harness_tool_update>` block for newly added, modified, restored, or disabled tools.
409
- * @param conv - conversation tool state (`advertisedToolNames` and `knownTools`).
410
- * @param tools - active tools for the current step.
481
+ * @param conv - conversation tool state (`advertisedToolDigests` and `knownTools`).
482
+ * @param tools - active uncompacted tools for the current step.
411
483
  * @returns `<harness_tool_update>` text block, or `''` when unchanged.
412
484
  */
413
485
  export function consumeToolDelta(
414
486
  conv: {
415
- readonly advertisedToolNames: ReadonlySet<string>
487
+ readonly advertisedToolDigests: ReadonlyMap<string, string>
416
488
  readonly knownTools: Map<string, string>
417
489
  },
418
490
  tools: readonly BridgeTool[],
@@ -424,11 +496,19 @@ export function consumeToolDelta(
424
496
  const hash = digest(tool)
425
497
  if (conv.knownTools.get(tool.name) === hash) continue
426
498
  conv.knownTools.set(tool.name, hash)
427
- if (conv.advertisedToolNames.has(tool.name)) {
499
+ const advertisedHash = conv.advertisedToolDigests.get(tool.name)
500
+ if (advertisedHash === hash) {
428
501
  lines.push(`[tool restored: ${AGENT_TOOL_PREFIX}${tool.name}]`)
429
502
  } else {
503
+ const spec = JSON.stringify({
504
+ name: tool.name,
505
+ description: tool.description,
506
+ parameters: tool.inputSchema,
507
+ })
430
508
  lines.push(
431
- `[tool available via ${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME} with {"name":"${tool.name}","arguments":{...}}]: ${JSON.stringify({ name: tool.name, description: tool.description, parameters: tool.inputSchema })}`,
509
+ advertisedHash !== undefined
510
+ ? `[tool updated — direct ${AGENT_TOOL_PREFIX}${tool.name} is stale; invoke via ${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME} with {"name":"${tool.name}","arguments":{...}}]: ${spec}`
511
+ : `[tool available via ${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME} with {"name":"${tool.name}","arguments":{...}}]: ${spec}`,
432
512
  )
433
513
  }
434
514
  }
@@ -474,7 +554,7 @@ function compactSchemaNode(value: unknown, maxDescChars: number): unknown {
474
554
  /**
475
555
  * Keep each MCP-advertised tool schema under `agy`'s eager size threshold while
476
556
  * preserving every parameter name, type, required list, and enum constraint.
477
- * Full prose instructions remain in Pi's system prompt.
557
+ * Full prose instructions for compacted tools travel in the session's opening prompt.
478
558
  * @param tool - raw bridge tool descriptor.
479
559
  * @returns compacted descriptor when oversized, otherwise the original descriptor.
480
560
  */
@@ -510,14 +590,12 @@ export function compactBridgeTool(tool: BridgeTool): BridgeTool {
510
590
  export function toBridgeTools(
511
591
  tools: readonly ToolSchema[] | undefined,
512
592
  ): BridgeTool[] {
513
- return (tools ?? []).map((t) =>
514
- compactBridgeTool({
515
- name: t.name,
516
- description: t.description,
517
- inputSchema:
518
- t.parameters.type === undefined
519
- ? { type: 'object', ...t.parameters }
520
- : t.parameters,
521
- }),
522
- )
593
+ return (tools ?? []).map((t) => ({
594
+ name: t.name,
595
+ description: t.description,
596
+ inputSchema:
597
+ t.parameters.type === undefined
598
+ ? { type: 'object', ...t.parameters }
599
+ : t.parameters,
600
+ }))
523
601
  }
package/src/pi-stream.ts CHANGED
@@ -146,12 +146,53 @@ export function streamPi(
146
146
  max: 'high',
147
147
  }[options.reasoning ?? 'off'],
148
148
  }
149
+ // onPayload may replace request content, but harness-owned routing/cancellation
150
+ // metadata (sessionId, signal) is always preserved. Omitting `tools` inherits
151
+ // the original tools; passing `tools: []` explicitly disables them.
149
152
  const replacement = await options.onPayload?.(request, model)
150
- if (replacement !== undefined)
153
+ if (replacement !== undefined) {
154
+ if (
155
+ replacement === null ||
156
+ typeof replacement !== 'object' ||
157
+ Array.isArray(replacement)
158
+ ) {
159
+ throw new LlmError(
160
+ 'onPayload must return a payload object or undefined',
161
+ 'INVALID_PAYLOAD',
162
+ )
163
+ }
164
+ const candidate = replacement as Record<string, unknown>
165
+ if (
166
+ typeof candidate.model !== 'string' ||
167
+ candidate.model.trim().length === 0
168
+ ) {
169
+ throw new LlmError(
170
+ 'onPayload replacement must include a non-empty string model',
171
+ 'INVALID_PAYLOAD',
172
+ )
173
+ }
174
+ if (!Array.isArray(candidate.messages)) {
175
+ throw new LlmError(
176
+ 'onPayload replacement must include a messages array',
177
+ 'INVALID_PAYLOAD',
178
+ )
179
+ }
180
+ if (candidate.tools !== undefined && !Array.isArray(candidate.tools)) {
181
+ throw new LlmError(
182
+ 'onPayload replacement tools must be an array when provided',
183
+ 'INVALID_PAYLOAD',
184
+ )
185
+ }
151
186
  request = {
152
- ...(replacement as GenerateOptions),
187
+ ...(candidate as unknown as GenerateOptions),
188
+ tools:
189
+ candidate.tools === undefined
190
+ ? request.tools
191
+ : (candidate.tools as GenerateOptions['tools']),
192
+ sessionId: options.sessionId,
153
193
  signal: options.signal,
154
194
  }
195
+ }
155
196
  stream.push({ type: 'start', partial: message })
156
197
  let finish: Extract<StreamChunk, { type: 'finish' }> | undefined
157
198
  let responseReported = false
package/src/preflight.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  } from 'node:fs'
23
23
  import { homedir } from 'node:os'
24
24
  import { delimiter, isAbsolute, join } from 'node:path'
25
+ import { readJson } from './config.ts'
25
26
 
26
27
  /** Agent id installed in the isolated home. */
27
28
  export const BRIDGE_AGENT = 'pi-bridge'
@@ -339,20 +340,6 @@ function writeIfChanged(path: string, content: string): void {
339
340
  writeFileSync(path, content)
340
341
  }
341
342
 
342
- function readJson(path: string): Record<string, unknown> {
343
- try {
344
- const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
345
- return parsed !== null &&
346
- typeof parsed === 'object' &&
347
- !Array.isArray(parsed)
348
- ? (parsed as Record<string, unknown>)
349
- : {}
350
- } catch (_missingSettings) {
351
- // A missing or unreadable settings file starts empty.
352
- return {}
353
- }
354
- }
355
-
356
343
  function isFile(path: string): boolean {
357
344
  try {
358
345
  return statSync(path).isFile()