pi-agy-acp 0.1.1 → 0.1.2

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/format.ts CHANGED
@@ -1,4 +1,9 @@
1
- import type { QuotaSnapshot } from './quota.ts'
1
+ import type {
2
+ AccountInfo,
3
+ QuotaSnapshot,
4
+ QuotaGroup,
5
+ QuotaBucket,
6
+ } from './quota.ts'
2
7
  import type { RuntimeStatus } from './runtime.ts'
3
8
 
4
9
  export interface FormattedNotice {
@@ -6,6 +11,51 @@ export interface FormattedNotice {
6
11
  level: 'info' | 'warning' | 'error'
7
12
  }
8
13
 
14
+ function clampFraction(value: number | undefined): number | undefined {
15
+ return typeof value === 'number' && Number.isFinite(value)
16
+ ? Math.max(0, Math.min(1, value))
17
+ : undefined
18
+ }
19
+
20
+ function formatAccount(account?: AccountInfo): string {
21
+ return [account?.email, account?.plan].filter(Boolean).join(' · ')
22
+ }
23
+
24
+ /** Lowest known window for the model family; unknown groups fall back conservatively. */
25
+ export function quotaForModel(
26
+ snapshot: QuotaSnapshot,
27
+ model?: string,
28
+ ): { group: QuotaGroup; bucket: QuotaBucket; fraction: number } | undefined {
29
+ if (snapshot.status !== 'ok') return undefined
30
+ const family = /^(gemini|claude|gpt)(?:-|$)/i.exec(model ?? '')?.[1]
31
+ const matched = family
32
+ ? snapshot.groups.filter((group) =>
33
+ new RegExp(`\\b${family}\\b`, 'i').test(
34
+ `${group.name} ${group.description}`,
35
+ ),
36
+ )
37
+ : []
38
+ const groups = matched.length > 0 ? matched : snapshot.groups
39
+ let lowest: ReturnType<typeof quotaForModel>
40
+ for (const group of groups) {
41
+ for (const bucket of group.buckets) {
42
+ const fraction = clampFraction(bucket.remainingFraction)
43
+ if (fraction === undefined) continue
44
+ if (!lowest || fraction < lowest.fraction)
45
+ lowest = { group, bucket, fraction }
46
+ }
47
+ }
48
+ return lowest
49
+ }
50
+
51
+ export function formatQuotaStatus(
52
+ snapshot: QuotaSnapshot,
53
+ model?: string,
54
+ ): string | undefined {
55
+ const quota = quotaForModel(snapshot, model)
56
+ return quota ? `AGY ${Math.round(quota.fraction * 100)}%` : undefined
57
+ }
58
+
9
59
  function resetCountdown(resetTime: string, now: number): string {
10
60
  const reset = Date.parse(resetTime)
11
61
  if (!Number.isFinite(reset)) return 'reset time unavailable'
@@ -24,9 +74,7 @@ export function formatQuota(
24
74
  ): FormattedNotice {
25
75
  const stale = snapshot.status === 'error' && snapshot.groups.length > 0
26
76
  const lines = [`Antigravity Quota${stale ? ' (stale)' : ''}`]
27
- const account = [snapshot.account?.email, snapshot.account?.plan]
28
- .filter(Boolean)
29
- .join(' · ')
77
+ const account = formatAccount(snapshot.account)
30
78
  if (account) lines.push(` Account: ${account}`)
31
79
  let level: FormattedNotice['level'] =
32
80
  snapshot.status === 'error' ? 'error' : 'info'
@@ -45,11 +93,7 @@ export function formatQuota(
45
93
  if (group.buckets.length === 0)
46
94
  lines.push(' No quota windows available.')
47
95
  for (const bucket of group.buckets) {
48
- const fraction =
49
- typeof bucket.remainingFraction === 'number' &&
50
- Number.isFinite(bucket.remainingFraction)
51
- ? Math.max(0, Math.min(1, bucket.remainingFraction))
52
- : undefined
96
+ const fraction = clampFraction(bucket.remainingFraction)
53
97
  const filled = fraction === undefined ? 0 : Math.round(fraction * 12)
54
98
  const bar = '█'.repeat(filled) + '░'.repeat(12 - filled)
55
99
  const percent =
@@ -83,9 +127,7 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
83
127
  const binary = status.binary
84
128
  ? `${status.version || 'unknown version'} (${status.binary})`
85
129
  : 'not probed yet (lazy init on first turn)'
86
- const account = [status.account?.email, status.account?.plan]
87
- .filter(Boolean)
88
- .join(' · ')
130
+ const account = formatAccount(status.account)
89
131
  const lines = [
90
132
  `Antigravity ACP · ${badges[status.state]}`,
91
133
  ` Binary: ${binary}`,
package/src/mcp-bridge.ts CHANGED
@@ -17,6 +17,10 @@ import {
17
17
  type ServerResponse,
18
18
  } from 'node:http'
19
19
  import type { AddressInfo } from 'node:net'
20
+ import type { ToolSchema } from './protocol.ts'
21
+ import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
22
+ import { digest } from './util.ts'
23
+ import { VERSION } from './version.ts'
20
24
 
21
25
  /** One tool schema advertised over MCP. */
22
26
  export interface BridgeTool {
@@ -106,11 +110,6 @@ export class McpBridge {
106
110
  this.options = options
107
111
  }
108
112
 
109
- /** Whether the HTTP listener is bound. */
110
- get listening(): boolean {
111
- return this.server !== undefined
112
- }
113
-
114
113
  /**
115
114
  * Base URL of the endpoint; append `/<tenant>` for a tenant-scoped endpoint.
116
115
  * @returns the loopback MCP URL.
@@ -254,7 +253,7 @@ export class McpBridge {
254
253
  return reply({
255
254
  protocolVersion: version,
256
255
  capabilities: { tools: { listChanged: false } },
257
- serverInfo: { name: 'pi', version: '0.1.0' },
256
+ serverInfo: { name: 'pi', version: VERSION },
258
257
  instructions:
259
258
  'Tools of the Pi session. Every call is executed by the harness under its own permission policy.',
260
259
  })
@@ -403,3 +402,122 @@ function writeJson(res: ServerResponse, status: number, value: unknown): void {
403
402
  function writeEvent(res: ServerResponse, value: unknown): void {
404
403
  res.write(`event: message\ndata: ${JSON.stringify(value)}\n\n`)
405
404
  }
405
+
406
+ /**
407
+ * Diff active tools against the session's known tool set and render a compact
408
+ * `<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.
411
+ * @returns `<harness_tool_update>` text block, or `''` when unchanged.
412
+ */
413
+ export function consumeToolDelta(
414
+ conv: {
415
+ readonly advertisedToolNames: ReadonlySet<string>
416
+ readonly knownTools: Map<string, string>
417
+ },
418
+ tools: readonly BridgeTool[],
419
+ ): string {
420
+ const lines: string[] = []
421
+ const active = new Set<string>()
422
+ for (const tool of tools) {
423
+ active.add(tool.name)
424
+ const hash = digest(tool)
425
+ if (conv.knownTools.get(tool.name) === hash) continue
426
+ conv.knownTools.set(tool.name, hash)
427
+ if (conv.advertisedToolNames.has(tool.name)) {
428
+ lines.push(`[tool restored: ${AGENT_TOOL_PREFIX}${tool.name}]`)
429
+ } else {
430
+ 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 })}`,
432
+ )
433
+ }
434
+ }
435
+ for (const name of [...conv.knownTools.keys()]) {
436
+ if (!active.has(name)) {
437
+ conv.knownTools.delete(name)
438
+ lines.push(`[tool disabled: ${name}]`)
439
+ }
440
+ }
441
+ return lines.length > 0
442
+ ? `<harness_tool_update>\n${lines.join('\n')}\n</harness_tool_update>`
443
+ : ''
444
+ }
445
+
446
+ /** Byte ceiling keeping advertised MCP tool schemas below agy's ~1,500B lazy cutoff. */
447
+ export const MAX_EAGER_BRIDGE_TOOL_BYTES = 1_350
448
+
449
+ function shortenText(text: string, maxChars: number): string {
450
+ const clean = text.replace(/\s+/gu, ' ').trim()
451
+ if (clean.length <= maxChars) return clean
452
+ const sentenceEnd = clean.indexOf('. ')
453
+ if (sentenceEnd >= 32 && sentenceEnd + 1 <= maxChars)
454
+ return clean.slice(0, sentenceEnd + 1)
455
+ return `${clean.slice(0, Math.max(1, maxChars - 1)).trimEnd()}…`
456
+ }
457
+
458
+ function compactSchemaNode(value: unknown, maxDescChars: number): unknown {
459
+ if (Array.isArray(value))
460
+ return value.map((item) => compactSchemaNode(item, maxDescChars))
461
+ if (value === null || typeof value !== 'object') return value
462
+ const record = value as Record<string, unknown>
463
+ const out: Record<string, unknown> = {}
464
+ for (const [key, entry] of Object.entries(record)) {
465
+ if (key === 'description' && typeof entry === 'string') {
466
+ if (maxDescChars > 0) out[key] = shortenText(entry, maxDescChars)
467
+ continue
468
+ }
469
+ out[key] = compactSchemaNode(entry, maxDescChars)
470
+ }
471
+ return out
472
+ }
473
+
474
+ /**
475
+ * Keep each MCP-advertised tool schema under `agy`'s eager size threshold while
476
+ * preserving every parameter name, type, required list, and enum constraint.
477
+ * Full prose instructions remain in Pi's system prompt.
478
+ * @param tool - raw bridge tool descriptor.
479
+ * @returns compacted descriptor when oversized, otherwise the original descriptor.
480
+ */
481
+ export function compactBridgeTool(tool: BridgeTool): BridgeTool {
482
+ if (
483
+ Buffer.byteLength(JSON.stringify(tool), 'utf8') <=
484
+ MAX_EAGER_BRIDGE_TOOL_BYTES
485
+ )
486
+ return tool
487
+ const pass1: BridgeTool = {
488
+ name: tool.name,
489
+ description: shortenText(tool.description, 220),
490
+ inputSchema: compactSchemaNode(tool.inputSchema, 90) as Record<
491
+ string,
492
+ unknown
493
+ >,
494
+ }
495
+ if (
496
+ Buffer.byteLength(JSON.stringify(pass1), 'utf8') <=
497
+ MAX_EAGER_BRIDGE_TOOL_BYTES
498
+ )
499
+ return pass1
500
+ return {
501
+ name: tool.name,
502
+ description: shortenText(tool.description, 140),
503
+ inputSchema: compactSchemaNode(tool.inputSchema, 0) as Record<
504
+ string,
505
+ unknown
506
+ >,
507
+ }
508
+ }
509
+
510
+ export function toBridgeTools(
511
+ tools: readonly ToolSchema[] | undefined,
512
+ ): 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
+ )
523
+ }
package/src/pi-stream.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { createHash } from 'node:crypto'
2
1
  import {
3
2
  createAssistantMessageEventStream,
4
3
  calculateCost,
5
4
  getCurrentTools,
6
5
  getSystemMessageText,
7
6
  renderSystemMessageUpdate,
7
+ ToolCallArgumentsStream,
8
8
  } from '@earendil-works/pi-ai'
9
9
  import type {
10
10
  AssistantMessage,
@@ -20,26 +20,30 @@ import type {
20
20
  RequestMessage,
21
21
  StreamChunk,
22
22
  } from './protocol.ts'
23
+ import { LlmError } from './protocol.ts'
24
+ import { digest } from './util.ts'
23
25
 
24
26
  export function requestMessages(messages: Message[]): RequestMessage[] {
25
- return messages.map((message, index) => {
26
- const id = createHash('sha256')
27
- .update(JSON.stringify(message))
28
- .digest('hex')
29
- if (message.role === 'system')
27
+ let leadingSystem = true
28
+ return messages.flatMap<RequestMessage>((message) => {
29
+ const id = digest(message)
30
+ if (message.role === 'system') {
31
+ const text = leadingSystem
32
+ ? getSystemMessageText(message)
33
+ : renderSystemMessageUpdate(message)
34
+ if (!leadingSystem && text.trim().length === 0) return []
30
35
  return {
31
36
  id,
32
37
  role: 'system',
33
38
  content: [
34
39
  {
35
40
  type: 'text',
36
- text:
37
- index === 0
38
- ? getSystemMessageText(message)
39
- : renderSystemMessageUpdate(message),
41
+ text,
40
42
  },
41
43
  ],
42
44
  }
45
+ }
46
+ leadingSystem = false
43
47
  const content: ContentBlock[] =
44
48
  typeof message.content === 'string'
45
49
  ? [{ type: 'text', text: message.content }]
@@ -54,8 +58,6 @@ export function requestMessages(messages: Message[]): RequestMessage[] {
54
58
  name: block.name,
55
59
  arguments: JSON.stringify(block.arguments),
56
60
  }
57
- case 'image':
58
- return block
59
61
  default:
60
62
  return block
61
63
  }
@@ -78,6 +80,23 @@ export function requestMessages(messages: Message[]): RequestMessage[] {
78
80
  return { id, role: 'user', content }
79
81
  })
80
82
  }
83
+
84
+ function errorMessage(
85
+ message: string | undefined,
86
+ code?: string,
87
+ ): string | undefined {
88
+ if (
89
+ code === 'CONTEXT_WINDOW_EXCEEDED' &&
90
+ !/context_length_exceeded/i.test(message ?? '')
91
+ )
92
+ return `context_length_exceeded: ${message ?? ''}`
93
+ if (
94
+ code === 'QUOTA' &&
95
+ !/quota exceeded|insufficient_quota/i.test(message ?? '')
96
+ )
97
+ return `quota exceeded: ${message ?? ''}`
98
+ return message
99
+ }
81
100
  export interface StreamRuntime {
82
101
  stream(options: GenerateOptions): AsyncIterable<StreamChunk>
83
102
  }
@@ -117,16 +136,15 @@ export function streamPi(
117
136
  })),
118
137
  sessionId: options.sessionId,
119
138
  signal: options.signal,
120
- reasoningEffort:
121
- options.reasoning === 'minimal'
122
- ? 'low'
123
- : options.reasoning === 'xhigh' || options.reasoning === 'max'
124
- ? 'high'
125
- : options.reasoning === 'low' ||
126
- options.reasoning === 'medium' ||
127
- options.reasoning === 'high'
128
- ? options.reasoning
129
- : undefined,
139
+ reasoningEffort: {
140
+ off: undefined,
141
+ minimal: 'low',
142
+ low: 'low',
143
+ medium: 'medium',
144
+ high: 'high',
145
+ xhigh: 'high',
146
+ max: 'high',
147
+ }[options.reasoning ?? 'off'],
130
148
  }
131
149
  const replacement = await options.onPayload?.(request, model)
132
150
  if (replacement !== undefined)
@@ -137,8 +155,12 @@ export function streamPi(
137
155
  stream.push({ type: 'start', partial: message })
138
156
  let finish: Extract<StreamChunk, { type: 'finish' }> | undefined
139
157
  let responseReported = false
158
+ const toolArguments = new Map<number, ToolCallArgumentsStream>()
140
159
  for await (const chunk of runtime.stream(request)) {
141
- if (!responseReported) {
160
+ if (
161
+ !responseReported &&
162
+ !(chunk.type === 'finish' && chunk.reason.kind === 'aborted')
163
+ ) {
142
164
  // ACP has no HTTP headers; report a synthetic response before its first event.
143
165
  await options.onResponse?.({ status: 200, headers: {} }, model)
144
166
  responseReported = true
@@ -181,23 +203,25 @@ export function streamPi(
181
203
  partial: message,
182
204
  })
183
205
  } else if (chunk.type === 'tool-call-delta') {
184
- message.content[chunk.index] = {
185
- type: 'toolCall',
186
- id: chunk.id,
187
- name: chunk.name,
188
- arguments: {},
189
- }
190
- stream.push({
191
- type: 'toolcall_start',
192
- contentIndex: chunk.index,
193
- partial: message,
194
- })
195
- message.content[chunk.index] = {
196
- type: 'toolCall',
197
- id: chunk.id,
198
- name: chunk.name,
199
- arguments: JSON.parse(chunk.argumentsDelta),
206
+ let args = toolArguments.get(chunk.index)
207
+ if (!args) {
208
+ args = new ToolCallArgumentsStream()
209
+ toolArguments.set(chunk.index, args)
210
+ message.content[chunk.index] = {
211
+ type: 'toolCall',
212
+ id: chunk.id,
213
+ name: chunk.name,
214
+ arguments: {},
215
+ }
216
+ stream.push({
217
+ type: 'toolcall_start',
218
+ contentIndex: chunk.index,
219
+ partial: message,
220
+ })
200
221
  }
222
+ const block = message.content[chunk.index]!
223
+ if (block.type === 'toolCall')
224
+ block.arguments = args.append(chunk.argumentsDelta)
201
225
  stream.push({
202
226
  type: 'toolcall_delta',
203
227
  contentIndex: chunk.index,
@@ -206,14 +230,18 @@ export function streamPi(
206
230
  })
207
231
  } else if (chunk.type === 'block-end') {
208
232
  const block = message.content[chunk.index]!
209
- if (block.type === 'toolCall')
233
+ if (block.type === 'toolCall') {
234
+ const args = toolArguments.get(chunk.index)!
235
+ if (chunk.block.type === 'tool-call')
236
+ args.replace(chunk.block.arguments)
237
+ Object.assign(block, args.finish())
210
238
  stream.push({
211
239
  type: 'toolcall_end',
212
240
  contentIndex: chunk.index,
213
241
  toolCall: block,
214
242
  partial: message,
215
243
  })
216
- else
244
+ } else
217
245
  stream.push({
218
246
  type: block.type === 'thinking' ? 'thinking_end' : 'text_end',
219
247
  contentIndex: chunk.index,
@@ -229,7 +257,10 @@ export function streamPi(
229
257
  const reason = finish.reason.kind
230
258
  if (reason === 'aborted' || reason === 'error') {
231
259
  message.stopReason = reason
232
- message.errorMessage = finish.reason.failure?.message
260
+ message.errorMessage = errorMessage(
261
+ finish.reason.failure?.message,
262
+ finish.reason.failure?.code,
263
+ )
233
264
  stream.push({ type: 'error', reason, error: message })
234
265
  } else {
235
266
  message.stopReason =
@@ -245,8 +276,10 @@ export function streamPi(
245
276
  throw new Error('ACP stream ended without a finish event')
246
277
  } catch (error) {
247
278
  message.stopReason = options.signal?.aborted ? 'aborted' : 'error'
248
- message.errorMessage =
249
- error instanceof Error ? error.message : String(error)
279
+ message.errorMessage = errorMessage(
280
+ error instanceof Error ? error.message : String(error),
281
+ error instanceof LlmError ? error.code : undefined,
282
+ )
250
283
  stream.push({ type: 'error', reason: message.stopReason, error: message })
251
284
  } finally {
252
285
  stream.end()
package/src/quota.ts CHANGED
@@ -123,6 +123,18 @@ export class QuotaReader {
123
123
  this.ttlMs = ttlMs
124
124
  }
125
125
 
126
+ /** Fresh successful data only; never starts a command. */
127
+ peek(): QuotaSnapshot | undefined {
128
+ return this.cached?.status === 'ok' &&
129
+ Date.now() - this.cachedAt < this.ttlMs
130
+ ? this.cached
131
+ : undefined
132
+ }
133
+
134
+ get pending(): boolean {
135
+ return this.inflight !== undefined
136
+ }
137
+
126
138
  /**
127
139
  * Read the quota snapshot.
128
140
  * @param force - bypass the cache.
@@ -167,6 +179,9 @@ export class QuotaReader {
167
179
  groups: this.cached?.groups ?? [],
168
180
  error: error instanceof Error ? error.message : String(error),
169
181
  }
182
+ // Apply the same TTL to failures so settled events cannot hammer an unavailable CLI.
183
+ this.cached = snapshot
184
+ this.cachedAt = Date.now()
170
185
  return snapshot
171
186
  }
172
187
  }