pi-agy-acp 0.1.2 → 0.1.3
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/CHANGELOG.md +7 -0
- package/README.md +9 -4
- package/docs/development.md +34 -10
- package/docs/reference.md +31 -27
- package/index.ts +57 -10
- package/package.json +6 -3
- package/src/acp-process.ts +6 -2
- package/src/config.ts +75 -0
- package/src/conversation.ts +154 -30
- package/src/format.ts +17 -3
- package/src/history.ts +30 -7
- package/src/jsonrpc.ts +16 -0
- package/src/mcp-bridge.ts +119 -42
- package/src/pi-stream.ts +43 -2
- package/src/preflight.ts +1 -14
- package/src/runtime.ts +318 -133
- package/src/util.ts +12 -5
package/src/conversation.ts
CHANGED
|
@@ -133,8 +133,15 @@ export type TurnEvent =
|
|
|
133
133
|
| { kind: 'done'; result: AcpPromptResult }
|
|
134
134
|
| { kind: 'error'; error: Error }
|
|
135
135
|
|
|
136
|
+
/** Bound on buffered text/thought chars accumulated while a tool call is relayed. */
|
|
137
|
+
const MAX_RELAY_BUFFER_CHARS = 65_536
|
|
138
|
+
|
|
136
139
|
/** One running ACP prompt turn. */
|
|
137
140
|
export class AcpTurn {
|
|
141
|
+
readonly cancellation = new AbortController()
|
|
142
|
+
/** First interruption wins; prompt completion is committed only after the step drains. */
|
|
143
|
+
private terminal: { kind: 'cancelled' } | { kind: 'failed'; error: Error } | undefined
|
|
144
|
+
releaseSignal: (() => void) | undefined
|
|
138
145
|
readonly startedAt = performance.now()
|
|
139
146
|
readonly events = new AsyncQueue<TurnEvent>()
|
|
140
147
|
/** Calls handed to Pi whose results have not arrived yet. */
|
|
@@ -150,8 +157,11 @@ export class AcpTurn {
|
|
|
150
157
|
/** Settles after the current prompt's result or error has been queued. */
|
|
151
158
|
promptSettled: Promise<void> = Promise.resolve()
|
|
152
159
|
usage?: AcpPromptResult['usage']
|
|
153
|
-
/**
|
|
154
|
-
|
|
160
|
+
/** Relayed call ids whose results the agent has not yet re-awaited via `pi_await_result`. */
|
|
161
|
+
readonly relayedCalls = new Set<string>()
|
|
162
|
+
/** Bounded output buffered while one or more calls are relayed. */
|
|
163
|
+
private relayBuffer: Array<Extract<TurnEvent, { kind: 'text' | 'thought' }>> = []
|
|
164
|
+
private relayBufferChars = 0
|
|
155
165
|
/** The turn produced visible text or a tool call. */
|
|
156
166
|
produced = false
|
|
157
167
|
/** Agent-side transport retry notices dropped from the output. */
|
|
@@ -184,6 +194,56 @@ export class AcpTurn {
|
|
|
184
194
|
return call
|
|
185
195
|
}
|
|
186
196
|
|
|
197
|
+
get isRelaying(): boolean {
|
|
198
|
+
return this.relayedCalls.size > 0
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Record that `callId` timed out into a relay notice and awaits `pi_await_result`. */
|
|
202
|
+
markRelayed(callId: string): void {
|
|
203
|
+
this.relayedCalls.add(callId)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all relays clear. */
|
|
207
|
+
resumeRelay(callId: string): void {
|
|
208
|
+
if (this.relayedCalls.delete(callId) && this.relayedCalls.size === 0) {
|
|
209
|
+
for (const event of this.relayBuffer) this.events.push(event)
|
|
210
|
+
this.clearRelayBuffer()
|
|
211
|
+
const held = this.recoverNoticeHold()
|
|
212
|
+
if (held.length > 0) this.events.push({ kind: 'text', text: held })
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Release all relay tracking and buffered output. */
|
|
217
|
+
clearRelay(): void {
|
|
218
|
+
this.relayedCalls.clear()
|
|
219
|
+
this.clearRelayBuffer()
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private clearRelayBuffer(): void {
|
|
223
|
+
this.relayBuffer.length = 0
|
|
224
|
+
this.relayBufferChars = 0
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private emitOrBuffer(
|
|
228
|
+
event: Extract<TurnEvent, { kind: 'text' | 'thought' }>,
|
|
229
|
+
): void {
|
|
230
|
+
if (!this.isRelaying) {
|
|
231
|
+
this.events.push(event)
|
|
232
|
+
return
|
|
233
|
+
}
|
|
234
|
+
const remaining = MAX_RELAY_BUFFER_CHARS - this.relayBufferChars
|
|
235
|
+
if (remaining <= 0) return
|
|
236
|
+
const text =
|
|
237
|
+
event.text.length <= remaining ? event.text : event.text.slice(0, remaining)
|
|
238
|
+
this.relayBufferChars += text.length
|
|
239
|
+
const tail = this.relayBuffer[this.relayBuffer.length - 1]
|
|
240
|
+
if (tail !== undefined && tail.kind === event.kind) {
|
|
241
|
+
tail.text += text
|
|
242
|
+
} else {
|
|
243
|
+
this.relayBuffer.push({ kind: event.kind, text })
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
187
247
|
/**
|
|
188
248
|
* Route one ACP session update into the event queue.
|
|
189
249
|
* @param update - the agent notification.
|
|
@@ -197,10 +257,8 @@ export class AcpTurn {
|
|
|
197
257
|
}
|
|
198
258
|
if (update.sessionUpdate === 'agent_thought_chunk') {
|
|
199
259
|
const held = this.recoverNoticeHold()
|
|
200
|
-
if (held.length > 0
|
|
201
|
-
|
|
202
|
-
if (text.length > 0 && !this.relaying)
|
|
203
|
-
this.events.push({ kind: 'thought', text })
|
|
260
|
+
if (held.length > 0) this.emitOrBuffer({ kind: 'text', text: held })
|
|
261
|
+
if (text.length > 0) this.emitOrBuffer({ kind: 'thought', text })
|
|
204
262
|
}
|
|
205
263
|
}
|
|
206
264
|
|
|
@@ -220,7 +278,7 @@ export class AcpTurn {
|
|
|
220
278
|
this.retryNotices++
|
|
221
279
|
return
|
|
222
280
|
}
|
|
223
|
-
|
|
281
|
+
this.emitOrBuffer({ kind: 'text', text: combined })
|
|
224
282
|
}
|
|
225
283
|
|
|
226
284
|
/**
|
|
@@ -236,7 +294,7 @@ export class AcpTurn {
|
|
|
236
294
|
this.retryNotices++
|
|
237
295
|
return ''
|
|
238
296
|
}
|
|
239
|
-
return
|
|
297
|
+
return held
|
|
240
298
|
}
|
|
241
299
|
|
|
242
300
|
/**
|
|
@@ -244,6 +302,37 @@ export class AcpTurn {
|
|
|
244
302
|
* @param reason - message delivered to the agent.
|
|
245
303
|
*/
|
|
246
304
|
abandon(reason: string): void {
|
|
305
|
+
this.terminal ??= { kind: 'cancelled' }
|
|
306
|
+
if (this.terminal.kind === 'cancelled') this.cancellation.abort()
|
|
307
|
+
this.clearRelay()
|
|
308
|
+
this.settleCalls(reason)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** End transport ownership without misreporting a process failure as cancellation. */
|
|
312
|
+
fail(error: Error): void {
|
|
313
|
+
this.terminal ??= { kind: 'failed', error }
|
|
314
|
+
this.clearRelay()
|
|
315
|
+
this.events.push({ kind: 'error', error })
|
|
316
|
+
this.settleCalls(error.message)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Guard both async-generator boundaries before emission, accounting, or drain. */
|
|
320
|
+
guard(chunk: StreamChunk | undefined, signal?: AbortSignal): StreamChunk | undefined {
|
|
321
|
+
if (signal?.aborted) this.abandon('The harness cancelled this request.')
|
|
322
|
+
if (this.terminal?.kind === 'failed') throw this.terminal.error
|
|
323
|
+
if (this.terminal?.kind === 'cancelled') return {
|
|
324
|
+
type: 'finish',
|
|
325
|
+
reason: {
|
|
326
|
+
kind: 'aborted',
|
|
327
|
+
failure: { message: 'Request aborted', code: 'ABORTED' },
|
|
328
|
+
},
|
|
329
|
+
}
|
|
330
|
+
return chunk
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private settleCalls(reason: string): void {
|
|
334
|
+
this.releaseSignal?.()
|
|
335
|
+
this.releaseSignal = undefined
|
|
247
336
|
for (const call of this.calls.values()) {
|
|
248
337
|
call.result.resolve({
|
|
249
338
|
content: [{ type: 'text', text: reason }],
|
|
@@ -324,6 +413,45 @@ export async function* pumpStep(
|
|
|
324
413
|
turn: AcpTurn,
|
|
325
414
|
host: PumpHost,
|
|
326
415
|
signal: AbortSignal | undefined,
|
|
416
|
+
): AsyncGenerator<StreamChunk> {
|
|
417
|
+
const cancel = () => turn.abandon('The harness cancelled this request.')
|
|
418
|
+
signal?.addEventListener('abort', cancel, { once: true })
|
|
419
|
+
if (signal?.aborted) cancel()
|
|
420
|
+
const chunks = stepChunks(turn, host, signal)
|
|
421
|
+
try {
|
|
422
|
+
// Real ACP exit can land behind a queued park, or while a consumer holds block-start.
|
|
423
|
+
for (;;) {
|
|
424
|
+
const interrupted = turn.guard(undefined, signal)
|
|
425
|
+
if (interrupted !== undefined) {
|
|
426
|
+
host.cancel()
|
|
427
|
+
yield interrupted
|
|
428
|
+
return
|
|
429
|
+
}
|
|
430
|
+
const next = await chunks.next()
|
|
431
|
+
const chunk = turn.guard(next.value, signal)
|
|
432
|
+
const aborted = chunk?.type === 'finish' && chunk.reason.kind === 'aborted'
|
|
433
|
+
if (aborted) host.cancel()
|
|
434
|
+
if (chunk !== undefined) yield chunk
|
|
435
|
+
if (aborted) return
|
|
436
|
+
if (next.done) return
|
|
437
|
+
}
|
|
438
|
+
} catch (error) {
|
|
439
|
+
turn.fail(error instanceof Error ? error : new Error(String(error)))
|
|
440
|
+
const interrupted = turn.guard(undefined, signal)
|
|
441
|
+
if (interrupted !== undefined) {
|
|
442
|
+
host.cancel()
|
|
443
|
+
yield interrupted
|
|
444
|
+
}
|
|
445
|
+
} finally {
|
|
446
|
+
signal?.removeEventListener('abort', cancel)
|
|
447
|
+
await chunks.return(undefined)
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function* stepChunks(
|
|
452
|
+
turn: AcpTurn,
|
|
453
|
+
host: PumpHost,
|
|
454
|
+
signal: AbortSignal | undefined,
|
|
327
455
|
): AsyncGenerator<StreamChunk> {
|
|
328
456
|
let index = 0
|
|
329
457
|
let open:
|
|
@@ -353,21 +481,9 @@ export async function* pumpStep(
|
|
|
353
481
|
}
|
|
354
482
|
|
|
355
483
|
for (;;) {
|
|
356
|
-
|
|
357
|
-
if (
|
|
358
|
-
|
|
359
|
-
turn.abandon('The harness cancelled this request.')
|
|
360
|
-
yield* close()
|
|
361
|
-
yield {
|
|
362
|
-
type: 'finish',
|
|
363
|
-
reason: {
|
|
364
|
-
kind: 'aborted',
|
|
365
|
-
failure: { message: 'Request aborted', code: 'ABORTED' },
|
|
366
|
-
},
|
|
367
|
-
}
|
|
368
|
-
return
|
|
369
|
-
}
|
|
370
|
-
if (turn.events.peek()?.kind !== 'text') {
|
|
484
|
+
await turn.events.wait(signal)
|
|
485
|
+
if (turn.guard(undefined, signal) !== undefined) return
|
|
486
|
+
if (!turn.isRelaying && turn.events.peek()?.kind !== 'text') {
|
|
371
487
|
const held = turn.recoverNoticeHold()
|
|
372
488
|
if (held.length > 0) {
|
|
373
489
|
turn.produced = true
|
|
@@ -394,6 +510,7 @@ export async function* pumpStep(
|
|
|
394
510
|
turn.events.shift()
|
|
395
511
|
batch.push(next.call)
|
|
396
512
|
}
|
|
513
|
+
if (turn.guard(undefined, signal) !== undefined) return
|
|
397
514
|
for (const call of batch) {
|
|
398
515
|
const blockIndex = index++
|
|
399
516
|
turn.pendingCalls.set(call.id, call)
|
|
@@ -434,11 +551,7 @@ export async function* pumpStep(
|
|
|
434
551
|
turn.promptSettled = host.continuePrompt().then(
|
|
435
552
|
(result) => turn.events.push({ kind: 'done', result }),
|
|
436
553
|
(error: unknown) =>
|
|
437
|
-
turn.
|
|
438
|
-
kind: 'error',
|
|
439
|
-
error:
|
|
440
|
-
error instanceof Error ? error : new Error(String(error)),
|
|
441
|
-
}),
|
|
554
|
+
turn.fail(error instanceof Error ? error : new Error(String(error))),
|
|
442
555
|
)
|
|
443
556
|
break
|
|
444
557
|
}
|
|
@@ -448,6 +561,16 @@ export async function* pumpStep(
|
|
|
448
561
|
turn.usage = event.result.usage
|
|
449
562
|
const usage = toTokenUsage(event.result.usage, calls)
|
|
450
563
|
if (usage !== undefined) yield { type: 'usage', usage }
|
|
564
|
+
if (
|
|
565
|
+
turn.isRelaying &&
|
|
566
|
+
(stop === 'end_turn' || stop === 'max_tokens')
|
|
567
|
+
) {
|
|
568
|
+
turn.clearRelay()
|
|
569
|
+
throw new LlmError(
|
|
570
|
+
'Antigravity ended the turn before retrieving relayed tool result(s)',
|
|
571
|
+
'PROVIDER_ERROR',
|
|
572
|
+
)
|
|
573
|
+
}
|
|
451
574
|
if (stop === 'end_turn' && !turn.produced) {
|
|
452
575
|
throw new LlmError(
|
|
453
576
|
'Antigravity ended the turn without visible output',
|
|
@@ -501,8 +624,9 @@ export async function* pumpStep(
|
|
|
501
624
|
}
|
|
502
625
|
case 'error':
|
|
503
626
|
turn.finished = true
|
|
504
|
-
|
|
505
|
-
|
|
627
|
+
turn.fail(event.error)
|
|
628
|
+
turn.guard(undefined, signal)
|
|
629
|
+
return
|
|
506
630
|
}
|
|
507
631
|
}
|
|
508
632
|
}
|
package/src/format.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { QuotaDisplay } from './config.ts'
|
|
1
2
|
import type {
|
|
2
3
|
AccountInfo,
|
|
3
4
|
QuotaSnapshot,
|
|
@@ -48,12 +49,22 @@ export function quotaForModel(
|
|
|
48
49
|
return lowest
|
|
49
50
|
}
|
|
50
51
|
|
|
52
|
+
/** Convert a remaining fraction (`0..1`) into the fraction shown for `display`. */
|
|
53
|
+
export function displayFraction(
|
|
54
|
+
remainingFraction: number,
|
|
55
|
+
display: QuotaDisplay = 'used',
|
|
56
|
+
): number {
|
|
57
|
+
return display === 'used' ? 1 - remainingFraction : remainingFraction
|
|
58
|
+
}
|
|
59
|
+
|
|
51
60
|
export function formatQuotaStatus(
|
|
52
61
|
snapshot: QuotaSnapshot,
|
|
53
62
|
model?: string,
|
|
63
|
+
display: QuotaDisplay = 'used',
|
|
54
64
|
): string | undefined {
|
|
55
65
|
const quota = quotaForModel(snapshot, model)
|
|
56
|
-
|
|
66
|
+
if (!quota) return undefined
|
|
67
|
+
return `AGY ${Math.round(displayFraction(quota.fraction, display) * 100)}%`
|
|
57
68
|
}
|
|
58
69
|
|
|
59
70
|
function resetCountdown(resetTime: string, now: number): string {
|
|
@@ -71,6 +82,7 @@ function resetCountdown(resetTime: string, now: number): string {
|
|
|
71
82
|
export function formatQuota(
|
|
72
83
|
snapshot: QuotaSnapshot,
|
|
73
84
|
now = Date.now(),
|
|
85
|
+
display: QuotaDisplay = 'used',
|
|
74
86
|
): FormattedNotice {
|
|
75
87
|
const stale = snapshot.status === 'error' && snapshot.groups.length > 0
|
|
76
88
|
const lines = [`Antigravity Quota${stale ? ' (stale)' : ''}`]
|
|
@@ -94,10 +106,12 @@ export function formatQuota(
|
|
|
94
106
|
lines.push(' No quota windows available.')
|
|
95
107
|
for (const bucket of group.buckets) {
|
|
96
108
|
const fraction = clampFraction(bucket.remainingFraction)
|
|
97
|
-
const
|
|
109
|
+
const shown =
|
|
110
|
+
fraction === undefined ? undefined : displayFraction(fraction, display)
|
|
111
|
+
const filled = shown === undefined ? 0 : Math.round(shown * 12)
|
|
98
112
|
const bar = '█'.repeat(filled) + '░'.repeat(12 - filled)
|
|
99
113
|
const percent =
|
|
100
|
-
|
|
114
|
+
shown === undefined ? 'n/a' : `${Math.round(shown * 100)}%`
|
|
101
115
|
const label = (
|
|
102
116
|
bucket.window ||
|
|
103
117
|
bucket.name ||
|
package/src/history.ts
CHANGED
|
@@ -90,15 +90,38 @@ export function textOf(content: readonly ContentBlock[]): string {
|
|
|
90
90
|
/**
|
|
91
91
|
* The bridge instructions appended to the agent's system prompt.
|
|
92
92
|
* @param system - the Pi system prompt.
|
|
93
|
+
* @param supplementalTools - initially advertised tools whose MCP schemas were compacted, preserving their full instructions.
|
|
93
94
|
* @returns the complete appended system text.
|
|
94
95
|
*/
|
|
95
|
-
export function bridgeSystemPrompt(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
96
|
+
export function bridgeSystemPrompt(
|
|
97
|
+
system: string,
|
|
98
|
+
supplementalTools: readonly {
|
|
99
|
+
name: string
|
|
100
|
+
description: string
|
|
101
|
+
inputSchema: Record<string, unknown>
|
|
102
|
+
}[] = [],
|
|
103
|
+
): string {
|
|
104
|
+
const sections = [
|
|
105
|
+
[
|
|
106
|
+
'You are the primary model of a Pi coding agent session. The harness owns the conversation, the tools, and their permissions.',
|
|
107
|
+
`Every harness tool is available to you under the prefix \`${AGENT_TOOL_PREFIX}\`: a tool named \`X\` in the instructions below is the tool \`${AGENT_TOOL_PREFIX}X\`. If \`${AGENT_TOOL_PREFIX}X\` is absent from your direct tool declarations, invoke it via \`${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME}\` with \`{"name":"X","arguments":{...}}\`. Use only these tools; pass arguments exactly as their schemas define.`,
|
|
108
|
+
'When the first user message contains a <pi_history> block, it reproduces the earlier part of this conversation; continue from the newest input after it without repeating completed actions.',
|
|
109
|
+
].join('\n'),
|
|
110
|
+
]
|
|
111
|
+
if (supplementalTools.length > 0) {
|
|
112
|
+
const entries = supplementalTools.map((t) =>
|
|
113
|
+
JSON.stringify({
|
|
114
|
+
name: t.name,
|
|
115
|
+
description: t.description,
|
|
116
|
+
parameters: t.inputSchema,
|
|
117
|
+
}),
|
|
118
|
+
)
|
|
119
|
+
sections.push(
|
|
120
|
+
`<harness_tool_instructions>\n${entries.join('\n')}\n</harness_tool_instructions>`,
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
if (system.length > 0) sections.push(system)
|
|
124
|
+
return sections.join('\n\n')
|
|
102
125
|
}
|
|
103
126
|
|
|
104
127
|
/**
|
package/src/jsonrpc.ts
CHANGED
|
@@ -232,6 +232,22 @@ export class JsonRpcPeer {
|
|
|
232
232
|
if (pending === undefined) return
|
|
233
233
|
this.pending.delete(id)
|
|
234
234
|
if (message.error !== undefined) {
|
|
235
|
+
if (
|
|
236
|
+
message.error === null ||
|
|
237
|
+
typeof message.error !== 'object' ||
|
|
238
|
+
Array.isArray(message.error)
|
|
239
|
+
) {
|
|
240
|
+
this.handlers.onProtocolError?.(
|
|
241
|
+
`invalid error response for id ${id}: ${line.slice(0, 200)}`,
|
|
242
|
+
)
|
|
243
|
+
pending.reject(
|
|
244
|
+
new JsonRpcRemoteError(pending.method, {
|
|
245
|
+
code: -32603,
|
|
246
|
+
message: 'invalid error response',
|
|
247
|
+
}),
|
|
248
|
+
)
|
|
249
|
+
return
|
|
250
|
+
}
|
|
235
251
|
const rpc = message.error as JsonRpcErrorObject
|
|
236
252
|
pending.reject(
|
|
237
253
|
new JsonRpcRemoteError(pending.method, {
|
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(
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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) =>
|
|
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
|
-
|
|
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(
|
|
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',
|
|
@@ -312,28 +358,36 @@ export class McpBridge {
|
|
|
312
358
|
let settled = false
|
|
313
359
|
const onClose = (): void => {
|
|
314
360
|
this.openResponses.delete(res)
|
|
361
|
+
clearInterval(keepAlive)
|
|
315
362
|
if (!settled)
|
|
316
363
|
controller.abort(new Error('MCP client closed the tool call'))
|
|
317
364
|
}
|
|
318
365
|
res.on('close', onClose)
|
|
319
366
|
let ticks = 0
|
|
320
367
|
const keepAlive = setInterval(() => {
|
|
321
|
-
if (res.writableEnded) return
|
|
368
|
+
if (res.writableEnded || res.destroyed) return
|
|
322
369
|
ticks++
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
370
|
+
try {
|
|
371
|
+
res.write(': keepalive\n\n')
|
|
372
|
+
if (
|
|
373
|
+
typeof progressToken === 'string' ||
|
|
374
|
+
typeof progressToken === 'number'
|
|
375
|
+
) {
|
|
376
|
+
writeEvent(res, {
|
|
377
|
+
jsonrpc: '2.0',
|
|
378
|
+
method: 'notifications/progress',
|
|
379
|
+
params: {
|
|
380
|
+
progressToken,
|
|
381
|
+
progress: ticks,
|
|
382
|
+
message: 'Pi is running the tool',
|
|
383
|
+
},
|
|
384
|
+
})
|
|
385
|
+
}
|
|
386
|
+
} catch (error) {
|
|
387
|
+
clearInterval(keepAlive)
|
|
388
|
+
this.log(
|
|
389
|
+
`mcp: keepalive write failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
|
390
|
+
)
|
|
337
391
|
}
|
|
338
392
|
}, this.options.keepAliveMs)
|
|
339
393
|
|
|
@@ -367,7 +421,7 @@ export class McpBridge {
|
|
|
367
421
|
this.openResponses.delete(res)
|
|
368
422
|
res.off('close', onClose)
|
|
369
423
|
if (controller.signal.aborted)
|
|
370
|
-
this.
|
|
424
|
+
this.log(
|
|
371
425
|
`mcp: call ${name} finished after the agent disconnected`,
|
|
372
426
|
)
|
|
373
427
|
}
|
|
@@ -384,9 +438,26 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
384
438
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
385
439
|
}
|
|
386
440
|
|
|
441
|
+
class HttpError extends Error {
|
|
442
|
+
readonly status: number
|
|
443
|
+
|
|
444
|
+
constructor(status: number) {
|
|
445
|
+
super(`HTTP ${status}`)
|
|
446
|
+
this.status = status
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
387
450
|
async function readBody(req: IncomingMessage): Promise<string> {
|
|
451
|
+
if (Number(req.headers['content-length']) > MAX_BODY_BYTES)
|
|
452
|
+
throw new HttpError(413)
|
|
388
453
|
const chunks: Buffer[] = []
|
|
389
|
-
|
|
454
|
+
let bytes = 0
|
|
455
|
+
// Readable.iterator otherwise destroys the socket on early exit, losing the 413.
|
|
456
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
457
|
+
bytes += chunk.length
|
|
458
|
+
if (bytes > MAX_BODY_BYTES) throw new HttpError(413)
|
|
459
|
+
chunks.push(chunk as Buffer)
|
|
460
|
+
}
|
|
390
461
|
return Buffer.concat(chunks).toString('utf8')
|
|
391
462
|
}
|
|
392
463
|
|
|
@@ -406,13 +477,13 @@ function writeEvent(res: ServerResponse, value: unknown): void {
|
|
|
406
477
|
/**
|
|
407
478
|
* Diff active tools against the session's known tool set and render a compact
|
|
408
479
|
* `<harness_tool_update>` block for newly added, modified, restored, or disabled tools.
|
|
409
|
-
* @param conv - conversation tool state (`
|
|
410
|
-
* @param tools - active tools for the current step.
|
|
480
|
+
* @param conv - conversation tool state (`advertisedToolDigests` and `knownTools`).
|
|
481
|
+
* @param tools - active uncompacted tools for the current step.
|
|
411
482
|
* @returns `<harness_tool_update>` text block, or `''` when unchanged.
|
|
412
483
|
*/
|
|
413
484
|
export function consumeToolDelta(
|
|
414
485
|
conv: {
|
|
415
|
-
readonly
|
|
486
|
+
readonly advertisedToolDigests: ReadonlyMap<string, string>
|
|
416
487
|
readonly knownTools: Map<string, string>
|
|
417
488
|
},
|
|
418
489
|
tools: readonly BridgeTool[],
|
|
@@ -424,11 +495,19 @@ export function consumeToolDelta(
|
|
|
424
495
|
const hash = digest(tool)
|
|
425
496
|
if (conv.knownTools.get(tool.name) === hash) continue
|
|
426
497
|
conv.knownTools.set(tool.name, hash)
|
|
427
|
-
|
|
498
|
+
const advertisedHash = conv.advertisedToolDigests.get(tool.name)
|
|
499
|
+
if (advertisedHash === hash) {
|
|
428
500
|
lines.push(`[tool restored: ${AGENT_TOOL_PREFIX}${tool.name}]`)
|
|
429
501
|
} else {
|
|
502
|
+
const spec = JSON.stringify({
|
|
503
|
+
name: tool.name,
|
|
504
|
+
description: tool.description,
|
|
505
|
+
parameters: tool.inputSchema,
|
|
506
|
+
})
|
|
430
507
|
lines.push(
|
|
431
|
-
|
|
508
|
+
advertisedHash !== undefined
|
|
509
|
+
? `[tool updated — direct ${AGENT_TOOL_PREFIX}${tool.name} is stale; invoke via ${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME} with {"name":"${tool.name}","arguments":{...}}]: ${spec}`
|
|
510
|
+
: `[tool available via ${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME} with {"name":"${tool.name}","arguments":{...}}]: ${spec}`,
|
|
432
511
|
)
|
|
433
512
|
}
|
|
434
513
|
}
|
|
@@ -474,7 +553,7 @@ function compactSchemaNode(value: unknown, maxDescChars: number): unknown {
|
|
|
474
553
|
/**
|
|
475
554
|
* Keep each MCP-advertised tool schema under `agy`'s eager size threshold while
|
|
476
555
|
* preserving every parameter name, type, required list, and enum constraint.
|
|
477
|
-
* Full prose instructions
|
|
556
|
+
* Full prose instructions for compacted tools are appended to the session system prompt.
|
|
478
557
|
* @param tool - raw bridge tool descriptor.
|
|
479
558
|
* @returns compacted descriptor when oversized, otherwise the original descriptor.
|
|
480
559
|
*/
|
|
@@ -510,14 +589,12 @@ export function compactBridgeTool(tool: BridgeTool): BridgeTool {
|
|
|
510
589
|
export function toBridgeTools(
|
|
511
590
|
tools: readonly ToolSchema[] | undefined,
|
|
512
591
|
): BridgeTool[] {
|
|
513
|
-
return (tools ?? []).map((t) =>
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
t.parameters
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
}),
|
|
522
|
-
)
|
|
592
|
+
return (tools ?? []).map((t) => ({
|
|
593
|
+
name: t.name,
|
|
594
|
+
description: t.description,
|
|
595
|
+
inputSchema:
|
|
596
|
+
t.parameters.type === undefined
|
|
597
|
+
? { type: 'object', ...t.parameters }
|
|
598
|
+
: t.parameters,
|
|
599
|
+
}))
|
|
523
600
|
}
|