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/runtime.ts CHANGED
@@ -8,7 +8,6 @@
8
8
  */
9
9
 
10
10
  import { randomBytes, timingSafeEqual } from 'node:crypto'
11
- import { existsSync } from 'node:fs'
12
11
  import { homedir } from 'node:os'
13
12
  import { join } from 'node:path'
14
13
  import { LlmError } from './protocol.ts'
@@ -17,7 +16,6 @@ import type {
17
16
  GenerateOptions,
18
17
  RequestMessage,
19
18
  StreamChunk,
20
- ToolSchema,
21
19
  } from './protocol.ts'
22
20
  import {
23
21
  AcpProcess,
@@ -25,9 +23,7 @@ import {
25
23
  type AcpPermissionOutcome,
26
24
  type AcpPermissionRequest,
27
25
  type AcpPromptResult,
28
- type AcpSessionUpdate,
29
26
  type AcpSpawner,
30
- type AcpToolCallMeta,
31
27
  } from './acp-process.ts'
32
28
  import { ModelCatalog, nearestEffort } from './catalog.ts'
33
29
  import { asEffort, type Config, type Effort } from './config.ts'
@@ -36,16 +32,19 @@ import {
36
32
  AWAIT_TOOL,
37
33
  AWAIT_TOOL_NAME,
38
34
  CALL_TOOL,
39
- CALL_TOOL_NAME,
40
35
  pumpStep,
41
36
  relayNotice,
42
37
  type ParkedCall,
38
+ type ReportedToolCall,
39
+ structuredToolMeta,
40
+ recordReportedToolCall,
41
+ isEmptyInput,
43
42
  } from './conversation.ts'
44
43
  import {
45
44
  AGENT_TOOL_PREFIX,
45
+ CALL_TOOL_NAME,
46
46
  bridgeSystemPrompt,
47
47
  inputPrompt,
48
- REPLAY_BUDGET_BYTES,
49
48
  MCP_SERVER_NAME,
50
49
  renderTranscript,
51
50
  replayPrompt,
@@ -55,6 +54,8 @@ import {
55
54
  import { JsonRpcClosedError, JsonRpcRemoteError } from './jsonrpc.ts'
56
55
  import {
57
56
  McpBridge,
57
+ consumeToolDelta,
58
+ toBridgeTools,
58
59
  type BridgeCallRequest,
59
60
  type BridgeContent,
60
61
  type BridgeTool,
@@ -80,7 +81,8 @@ import {
80
81
  type AccountInfo,
81
82
  type QuotaSnapshot,
82
83
  } from './quota.ts'
83
- import { delay, digest, KeyedMutex } from './util.ts'
84
+ import { delay, digest, KeyedMutex, abortable } from './util.ts'
85
+ import { VERSION } from './version.ts'
84
86
 
85
87
  /** Parked calls answer with a still-running notice before Gemini cache TTL expiry and agy's 180-second MCP deadline. */
86
88
  export const DEFAULT_RELAY_AFTER_MS = 85_000
@@ -109,7 +111,6 @@ export interface RuntimeStatus {
109
111
  account?: AccountInfo
110
112
  contextWindow: number
111
113
  defaultEffort: Effort
112
- longDecodeContinuations: number
113
114
  models: {
114
115
  id: string
115
116
  name: string
@@ -131,15 +132,6 @@ export interface RuntimeStatus {
131
132
  }
132
133
  }
133
134
 
134
- /** Structured MCP metadata the agent reported for one tool call. */
135
- interface ReportedToolCall {
136
- kind?: string
137
- serverName?: string
138
- toolName?: string
139
- /** Set when later updates contradicted an already established field. */
140
- conflict?: boolean
141
- }
142
-
143
135
  interface Conversation {
144
136
  readonly key: string
145
137
  tenantKey: string | undefined
@@ -239,16 +231,6 @@ export class AntigravityRuntime {
239
231
  return this.catalog.fixedEffort(model) ?? requested
240
232
  }
241
233
 
242
- /** Default effort. */
243
- defaultEffort(): Effort {
244
- return this.host.config.defaultEffort
245
- }
246
-
247
- /** Maximum automatic long-decode continuations. */
248
- longDecodeContinuations(): number {
249
- return this.host.config.longDecodeContinuations
250
- }
251
-
252
234
  /**
253
235
  * Current status for diagnostics surfaces.
254
236
  * @returns the status snapshot.
@@ -266,8 +248,7 @@ export class AntigravityRuntime {
266
248
  home: this.home,
267
249
  account: this.accountInfo(),
268
250
  contextWindow: DEFAULT_CONTEXT_WINDOW,
269
- defaultEffort: this.defaultEffort(),
270
- longDecodeContinuations: this.longDecodeContinuations(),
251
+ defaultEffort: this.host.config.defaultEffort,
271
252
  models: this.catalog.list().map((m) => ({
272
253
  ...m,
273
254
  efforts: this.catalog.effortsFor(m.id),
@@ -345,12 +326,15 @@ export class AntigravityRuntime {
345
326
  * Warm the process and refresh the catalog through a tool-less discovery session.
346
327
  * @returns resolves when discovery finished.
347
328
  */
348
- async warmup(): Promise<void> {
349
- if (this.warmupPromise !== undefined) return this.warmupPromise
350
- if (this.catalog.observed) return
329
+ async warmup(
330
+ options: { force?: boolean; signal?: AbortSignal } = {},
331
+ ): Promise<void> {
332
+ options.signal?.throwIfAborted()
333
+ if (this.warmupPromise !== undefined)
334
+ return abortable(this.warmupPromise, options.signal)
335
+ if (!options.force && this.catalog.observed) return
351
336
  this.warmupPromise = (async () => {
352
337
  const proc = await this.ensureReady()
353
- if (this.catalog.observed) return
354
338
  const result = await proc.newSession(
355
339
  {
356
340
  cwd: this.preflight?.workspace ?? this.home,
@@ -378,7 +362,26 @@ export class AntigravityRuntime {
378
362
  })().finally(() => {
379
363
  this.warmupPromise = undefined
380
364
  })
381
- return this.warmupPromise
365
+ return abortable(this.warmupPromise, options.signal)
366
+ }
367
+
368
+ /** Close conversation sessions while retaining the process and discovery/quota caches. */
369
+ async resetConversations(): Promise<void> {
370
+ const conversations = [...this.conversations.values()]
371
+ for (const conv of conversations)
372
+ this.dropTurn(conv, 'The Pi session changed.')
373
+ await Promise.all(
374
+ conversations.map(async (conv) => {
375
+ const release = await this.mutex.acquire(conv.key)
376
+ try {
377
+ if (this.conversations.get(conv.key) !== conv) return
378
+ await this.resetSession(conv)
379
+ this.conversations.delete(conv.key)
380
+ } finally {
381
+ release()
382
+ }
383
+ }),
384
+ )
382
385
  }
383
386
 
384
387
  /** Stop every session, the process, and the bridge. */
@@ -423,7 +426,7 @@ export class AntigravityRuntime {
423
426
  conv.toolNames = new Set(tools.map((t) => t.name))
424
427
  const effort = this.effectiveEffort(
425
428
  options.model,
426
- asEffort(options.reasoningEffort) ?? this.defaultEffort(),
429
+ asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort,
427
430
  )
428
431
 
429
432
  if (conv.turn !== undefined && conv.turn.pendingCalls.size > 0) {
@@ -588,7 +591,7 @@ export class AntigravityRuntime {
588
591
  cwd: preflight.workspace,
589
592
  spawn: this.host.spawnAcp,
590
593
  clientName: 'pi-agy-acp',
591
- clientVersion: '0.1.0',
594
+ clientVersion: VERSION,
592
595
  log: (message) => this.host.log.warn(message),
593
596
  })
594
597
  const started = proc
@@ -628,7 +631,6 @@ export class AntigravityRuntime {
628
631
  logFile: join(this.home, 'acp.log'),
629
632
  }
630
633
  this.preflight = result
631
- this.host.onModelsChanged()
632
634
  return result
633
635
  })().finally(() => {
634
636
  this.preflightPromise = undefined
@@ -652,16 +654,7 @@ export class AntigravityRuntime {
652
654
  'TRANSPORT',
653
655
  ),
654
656
  })
655
- this.releaseTenant(conv)
656
- conv.sessionId = undefined
657
- conv.process = undefined
658
- conv.tenantKey = undefined
659
- conv.tenantSecret = undefined
660
- conv.advertisedTools = []
661
- conv.advertisedToolNames.clear()
662
- conv.knownTools.clear()
663
- conv.reportedToolCalls.clear()
664
-
657
+ this.clearSession(conv)
665
658
  conv.dirty = true
666
659
  }
667
660
  }
@@ -739,12 +732,7 @@ export class AntigravityRuntime {
739
732
  )
740
733
  this.host.onModelsChanged()
741
734
  } catch (error) {
742
- this.releaseTenant(conv)
743
- conv.tenantKey = undefined
744
- conv.tenantSecret = undefined
745
- conv.advertisedTools = []
746
- conv.advertisedToolNames.clear()
747
- conv.knownTools.clear()
735
+ this.clearSession(conv)
748
736
  throw mapError(error)
749
737
  }
750
738
  }
@@ -985,12 +973,20 @@ export class AntigravityRuntime {
985
973
  }
986
974
 
987
975
  private async resetSession(conv: Conversation): Promise<void> {
976
+ let closing: Promise<void> | undefined
988
977
  if (conv.sessionId !== undefined && conv.process !== undefined) {
989
978
  const sessionId = conv.sessionId
990
- void conv.process
979
+ closing = conv.process
991
980
  .closeSession(sessionId)
992
981
  .finally(() => removeSessionArtifacts(this.home, sessionId))
993
982
  }
983
+ this.clearSession(conv)
984
+ conv.knownIds = undefined
985
+ conv.dirty = false
986
+ await closing
987
+ }
988
+
989
+ private clearSession(conv: Conversation): void {
994
990
  this.releaseTenant(conv)
995
991
  conv.sessionId = undefined
996
992
  conv.tenantKey = undefined
@@ -1000,9 +996,6 @@ export class AntigravityRuntime {
1000
996
  conv.advertisedToolNames.clear()
1001
997
  conv.knownTools.clear()
1002
998
  conv.reportedToolCalls.clear()
1003
-
1004
- conv.knownIds = undefined
1005
- conv.dirty = false
1006
999
  }
1007
1000
 
1008
1001
  private startPrompt(
@@ -1011,7 +1004,7 @@ export class AntigravityRuntime {
1011
1004
  blocks: AcpPromptBlock[],
1012
1005
  ): void {
1013
1006
  const turn = conv.turn as AcpTurn
1014
- proc.prompt(conv.sessionId as string, blocks).then(
1007
+ turn.promptSettled = proc.prompt(conv.sessionId as string, blocks).then(
1015
1008
  (result) => turn.events.push({ kind: 'done', result }),
1016
1009
  (error: unknown) =>
1017
1010
  turn.events.push({ kind: 'error', error: mapError(error) }),
@@ -1027,7 +1020,6 @@ export class AntigravityRuntime {
1027
1020
  const turn = conv.turn as AcpTurn
1028
1021
  const sessionId = conv.sessionId as string
1029
1022
  let finishKind: string | undefined
1030
- let usage: AcpPromptResult['usage']
1031
1023
  const recordTurn = (
1032
1024
  outcome: NonNullable<RuntimeStatus['lastTurn']>['outcome'],
1033
1025
  ) => {
@@ -1035,7 +1027,7 @@ export class AntigravityRuntime {
1035
1027
  model: options.model,
1036
1028
  effort,
1037
1029
  steps: turn.toolSteps + turn.continuations + 1,
1038
- usage,
1030
+ usage: turn.usage,
1039
1031
  outcome,
1040
1032
  durationMs: Math.max(0, performance.now() - turn.startedAt),
1041
1033
  retryNotices: turn.retryNotices,
@@ -1047,13 +1039,10 @@ export class AntigravityRuntime {
1047
1039
  turn,
1048
1040
  {
1049
1041
  parkSettleMs: this.host.config.parkSettleMs,
1050
- maxContinuations: this.longDecodeContinuations(),
1042
+ maxContinuations: this.host.config.longDecodeContinuations,
1051
1043
  continuePrompt: () =>
1052
1044
  proc.prompt(sessionId, [{ type: 'text', text: CONTINUE_PROMPT }]),
1053
1045
  cancel: () => proc.cancel(sessionId),
1054
- recordUsage: (sample) => {
1055
- usage = sample
1056
- },
1057
1046
  },
1058
1047
  options.signal,
1059
1048
  )) {
@@ -1079,7 +1068,7 @@ export class AntigravityRuntime {
1079
1068
  )
1080
1069
  if (finishKind === 'aborted') {
1081
1070
  // A cancelled turn leaves partial agent-side history; rebuild from Pi history next time.
1082
- await Promise.race([turnSettled(turn), delay(5_000)])
1071
+ await Promise.race([turn.promptSettled, delay(5_000)])
1083
1072
  conv.dirty = true
1084
1073
  }
1085
1074
  // The turn is over: clear the identities it established with it.
@@ -1225,39 +1214,17 @@ export class AntigravityRuntime {
1225
1214
  request.tenantKey !== undefined
1226
1215
  ? this.tenants.get(request.tenantKey)
1227
1216
  : undefined
1228
- if (conv === undefined) {
1229
- return {
1230
- content: [
1231
- {
1232
- type: 'text',
1233
- text: 'No harness turn is waiting for this tool call.',
1234
- },
1235
- ],
1236
- isError: true,
1237
- }
1238
- }
1217
+ if (conv === undefined)
1218
+ return toolError('No harness turn is waiting for this tool call.')
1239
1219
  if (
1240
1220
  request.conversationId !== undefined &&
1241
1221
  (conv.sessionId === undefined ||
1242
1222
  request.conversationId !== conv.sessionId)
1243
- ) {
1244
- return {
1245
- content: [{ type: 'text', text: 'Tenant session mismatch.' }],
1246
- isError: true,
1247
- }
1248
- }
1223
+ )
1224
+ return toolError('Tenant session mismatch.')
1249
1225
  const turn = conv.turn
1250
- if (turn === undefined || turn.finished) {
1251
- return {
1252
- content: [
1253
- {
1254
- type: 'text',
1255
- text: 'No harness turn is waiting for this tool call.',
1256
- },
1257
- ],
1258
- isError: true,
1259
- }
1260
- }
1226
+ if (turn === undefined || turn.finished)
1227
+ return toolError('No harness turn is waiting for this tool call.')
1261
1228
  if (request.name === AWAIT_TOOL_NAME) {
1262
1229
  const callId =
1263
1230
  typeof request.arguments.call_id === 'string'
@@ -1265,57 +1232,31 @@ export class AntigravityRuntime {
1265
1232
  : ''
1266
1233
  const call = turn.calls.get(callId)
1267
1234
  if (call === undefined)
1268
- return {
1269
- content: [
1270
- { type: 'text', text: `Unknown harness call id ${callId}.` },
1271
- ],
1272
- isError: true,
1273
- }
1235
+ return toolError(`Unknown harness call id ${callId}.`)
1274
1236
  turn.relaying = false
1275
1237
  return this.awaitCall(turn, call, request.signal)
1276
1238
  }
1277
- if (request.name === CALL_TOOL_NAME) {
1239
+ let name = request.name
1240
+ let args = request.arguments
1241
+ if (name === CALL_TOOL_NAME) {
1278
1242
  const rawTarget =
1279
1243
  typeof request.arguments.name === 'string'
1280
1244
  ? request.arguments.name.trim()
1281
1245
  : ''
1282
- const targetName = rawTarget.startsWith(AGENT_TOOL_PREFIX)
1246
+ name = rawTarget.startsWith(AGENT_TOOL_PREFIX)
1283
1247
  ? rawTarget.slice(AGENT_TOOL_PREFIX.length)
1284
1248
  : rawTarget
1285
1249
  const rawArgs = request.arguments.arguments
1286
- const targetArgs =
1250
+ args =
1287
1251
  rawArgs !== null &&
1288
1252
  typeof rawArgs === 'object' &&
1289
1253
  !Array.isArray(rawArgs)
1290
1254
  ? (rawArgs as Record<string, unknown>)
1291
1255
  : {}
1292
- if (!conv.toolNames.has(targetName)) {
1293
- return {
1294
- content: [
1295
- {
1296
- type: 'text',
1297
- text: `The harness has no tool named ${targetName}.`,
1298
- },
1299
- ],
1300
- isError: true,
1301
- }
1302
- }
1303
- const call = turn.park(targetName, targetArgs)
1304
- return this.awaitCall(turn, call, request.signal)
1305
- }
1306
- if (!conv.toolNames.has(request.name)) {
1307
- return {
1308
- content: [
1309
- {
1310
- type: 'text',
1311
- text: `The harness has no tool named ${request.name}.`,
1312
- },
1313
- ],
1314
- isError: true,
1315
- }
1316
1256
  }
1317
- const call = turn.park(request.name, request.arguments)
1318
- return this.awaitCall(turn, call, request.signal)
1257
+ if (!conv.toolNames.has(name))
1258
+ return toolError(`The harness has no tool named ${name}.`)
1259
+ return this.awaitCall(turn, turn.park(name, args), request.signal)
1319
1260
  }
1320
1261
 
1321
1262
  private async awaitCall(
@@ -1345,10 +1286,7 @@ export class AntigravityRuntime {
1345
1286
  return relayNotice(call)
1346
1287
  }
1347
1288
  if (outcome === 'aborted')
1348
- return {
1349
- content: [{ type: 'text', text: 'The tool call was cancelled.' }],
1350
- isError: true,
1351
- }
1289
+ return toolError('The tool call was cancelled.')
1352
1290
  return outcome
1353
1291
  } finally {
1354
1292
  if (timer !== undefined) clearTimeout(timer)
@@ -1371,241 +1309,8 @@ function messageIds(messages: readonly RequestMessage[]): string[] {
1371
1309
  return messages.map((m) => m.id ?? '')
1372
1310
  }
1373
1311
 
1374
- /** Read a non-empty string field. */
1375
- function nonEmpty(value: unknown): string | undefined {
1376
- return typeof value === 'string' && value.length > 0 ? value : undefined
1377
- }
1378
-
1379
- /**
1380
- * Extract the structured `(serverName, toolName)` an agent claimed in one
1381
- * permission request: top-level `mcpServerName`/`mcpToolName` or `_meta`.
1382
- * `title` and `rawInput` are deliberately not consulted.
1383
- */
1384
- function structuredToolMeta(toolCall: AcpPermissionRequest['toolCall']): {
1385
- serverName?: string
1386
- toolName?: string
1387
- } {
1388
- const meta: AcpToolCallMeta | undefined = toolCall?._meta
1389
- const serverName =
1390
- nonEmpty(toolCall?.mcpServerName) ??
1391
- nonEmpty(meta?.mcpServerName) ??
1392
- nonEmpty(meta?.serverName) ??
1393
- nonEmpty(meta?.server)
1394
- const toolName =
1395
- nonEmpty(toolCall?.mcpToolName) ??
1396
- nonEmpty(meta?.mcpToolName) ??
1397
- nonEmpty(meta?.toolName) ??
1398
- nonEmpty(meta?.tool)
1399
- return {
1400
- ...(serverName !== undefined ? { serverName } : {}),
1401
- ...(toolName !== undefined ? { toolName } : {}),
1402
- }
1403
- }
1404
-
1405
- /**
1406
- * Record the structured metadata of one agent-reported tool-call update.
1407
- * The first report establishes the identity; later updates merge only the
1408
- * fields actually present, so a status-only `tool_call_update` never wipes an
1409
- * established `server`/`tool`/`kind`. A later field that contradicts the
1410
- * established identity keeps the original value and marks the record
1411
- * anomalous — the permission gate refuses every further request for that call.
1412
- * @returns 'created' | 'merged' | 'conflict', or undefined for ignored updates.
1413
- */
1414
- function recordReportedToolCall(
1415
- conv: Conversation,
1416
- update: AcpSessionUpdate,
1417
- ): 'created' | 'merged' | 'conflict' | undefined {
1418
- if (
1419
- update.sessionUpdate !== 'tool_call' &&
1420
- update.sessionUpdate !== 'tool_call_update'
1421
- )
1422
- return
1423
- if (typeof update.toolCallId !== 'string' || update.toolCallId.length === 0)
1424
- return
1425
- const meta: AcpToolCallMeta | undefined = update._meta
1426
- const serverName =
1427
- nonEmpty(update.mcpServerName) ??
1428
- nonEmpty(meta?.mcpServerName) ??
1429
- nonEmpty(meta?.serverName) ??
1430
- nonEmpty(meta?.server)
1431
- const toolName =
1432
- nonEmpty(update.mcpToolName) ??
1433
- nonEmpty(meta?.mcpToolName) ??
1434
- nonEmpty(meta?.toolName) ??
1435
- nonEmpty(meta?.tool)
1436
- const kind = typeof update.kind === 'string' ? update.kind : undefined
1437
- const existing = conv.reportedToolCalls.get(update.toolCallId)
1438
- const merged: ReportedToolCall = existing === undefined ? {} : { ...existing }
1439
- let conflict = false
1440
- if (kind !== undefined) {
1441
- if (merged.kind !== undefined && merged.kind !== kind) conflict = true
1442
- else merged.kind = kind
1443
- }
1444
- if (serverName !== undefined) {
1445
- if (merged.serverName !== undefined && merged.serverName !== serverName)
1446
- conflict = true
1447
- else merged.serverName = serverName
1448
- }
1449
- if (toolName !== undefined) {
1450
- if (merged.toolName !== undefined && merged.toolName !== toolName)
1451
- conflict = true
1452
- else merged.toolName = toolName
1453
- }
1454
- if (conflict) merged.conflict = true
1455
- conv.reportedToolCalls.set(update.toolCallId, merged)
1456
- if (conflict) return 'conflict'
1457
- return existing === undefined ? 'created' : 'merged'
1458
- }
1459
-
1460
- /** Whether `rawInput` carries no arguments at all (MCP server loading probes). */
1461
- function isEmptyInput(rawInput: unknown): boolean {
1462
- if (rawInput === undefined || rawInput === null) return true
1463
- if (typeof rawInput === 'string') return rawInput.trim().length === 0
1464
- if (Array.isArray(rawInput)) return rawInput.length === 0
1465
- if (typeof rawInput === 'object') return Object.keys(rawInput).length === 0
1466
- return false
1467
- }
1468
-
1469
- /**
1470
- * Diff active tools against the session's known tool set and render a compact
1471
- * `<harness_tool_update>` block for newly added, modified, restored, or disabled tools.
1472
- * @param conv - conversation tool state (`advertisedToolNames` and `knownTools`).
1473
- * @param tools - active tools for the current step.
1474
- * @returns `<harness_tool_update>` text block, or `''` when unchanged.
1475
- */
1476
- export function consumeToolDelta(
1477
- conv: {
1478
- readonly advertisedToolNames: ReadonlySet<string>
1479
- readonly knownTools: Map<string, string>
1480
- },
1481
- tools: readonly BridgeTool[],
1482
- ): string {
1483
- const lines: string[] = []
1484
- const active = new Set<string>()
1485
- for (const tool of tools) {
1486
- active.add(tool.name)
1487
- const hash = digest(tool)
1488
- if (conv.knownTools.get(tool.name) === hash) continue
1489
- conv.knownTools.set(tool.name, hash)
1490
- if (conv.advertisedToolNames.has(tool.name)) {
1491
- lines.push(`[tool restored: ${AGENT_TOOL_PREFIX}${tool.name}]`)
1492
- } else {
1493
- lines.push(
1494
- `[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 })}`,
1495
- )
1496
- }
1497
- }
1498
- for (const name of [...conv.knownTools.keys()]) {
1499
- if (!active.has(name)) {
1500
- conv.knownTools.delete(name)
1501
- lines.push(`[tool disabled: ${name}]`)
1502
- }
1503
- }
1504
- return lines.length > 0
1505
- ? `<harness_tool_update>\n${lines.join('\n')}\n</harness_tool_update>`
1506
- : ''
1507
- }
1508
-
1509
- /** Byte ceiling keeping advertised MCP tool schemas below agy's ~1,500B lazy cutoff. */
1510
- export const MAX_EAGER_BRIDGE_TOOL_BYTES = 1_350
1511
-
1512
- function shortenText(text: string, maxChars: number): string {
1513
- const clean = text.replace(/\s+/gu, ' ').trim()
1514
- if (clean.length <= maxChars) return clean
1515
- const sentenceEnd = clean.indexOf('. ')
1516
- if (sentenceEnd >= 32 && sentenceEnd + 1 <= maxChars)
1517
- return clean.slice(0, sentenceEnd + 1)
1518
- return `${clean.slice(0, Math.max(1, maxChars - 1)).trimEnd()}…`
1519
- }
1520
-
1521
- function compactSchemaNode(value: unknown, maxDescChars: number): unknown {
1522
- if (Array.isArray(value))
1523
- return value.map((item) => compactSchemaNode(item, maxDescChars))
1524
- if (value === null || typeof value !== 'object') return value
1525
- const record = value as Record<string, unknown>
1526
- const out: Record<string, unknown> = {}
1527
- for (const [key, entry] of Object.entries(record)) {
1528
- if (key === 'description' && typeof entry === 'string') {
1529
- if (maxDescChars > 0) out[key] = shortenText(entry, maxDescChars)
1530
- continue
1531
- }
1532
- if (
1533
- key === 'properties' &&
1534
- entry !== null &&
1535
- typeof entry === 'object' &&
1536
- !Array.isArray(entry)
1537
- ) {
1538
- const props: Record<string, unknown> = {}
1539
- for (const [propKey, propVal] of Object.entries(
1540
- entry as Record<string, unknown>,
1541
- )) {
1542
- props[propKey] = compactSchemaNode(propVal, maxDescChars)
1543
- }
1544
- out[key] = props
1545
- continue
1546
- }
1547
- out[key] = compactSchemaNode(entry, maxDescChars)
1548
- }
1549
- return out
1550
- }
1551
-
1552
- /**
1553
- * Keep each MCP-advertised tool schema under `agy`'s eager size threshold while
1554
- * preserving every parameter name, type, required list, and enum constraint.
1555
- * Full prose instructions remain in Pi's system prompt.
1556
- * @param tool - raw bridge tool descriptor.
1557
- * @returns compacted descriptor when oversized, otherwise the original descriptor.
1558
- */
1559
- export function compactBridgeTool(tool: BridgeTool): BridgeTool {
1560
- if (
1561
- Buffer.byteLength(JSON.stringify(tool), 'utf8') <=
1562
- MAX_EAGER_BRIDGE_TOOL_BYTES
1563
- )
1564
- return tool
1565
- const pass1: BridgeTool = {
1566
- name: tool.name,
1567
- description: shortenText(tool.description, 220),
1568
- inputSchema: compactSchemaNode(tool.inputSchema, 90) as Record<
1569
- string,
1570
- unknown
1571
- >,
1572
- }
1573
- if (
1574
- Buffer.byteLength(JSON.stringify(pass1), 'utf8') <=
1575
- MAX_EAGER_BRIDGE_TOOL_BYTES
1576
- )
1577
- return pass1
1578
- return {
1579
- name: tool.name,
1580
- description: shortenText(tool.description, 140),
1581
- inputSchema: compactSchemaNode(tool.inputSchema, 0) as Record<
1582
- string,
1583
- unknown
1584
- >,
1585
- }
1586
- }
1587
-
1588
- function toBridgeTools(tools: readonly ToolSchema[] | undefined): BridgeTool[] {
1589
- return (tools ?? []).map((t) =>
1590
- compactBridgeTool({
1591
- name: t.name,
1592
- description: t.description,
1593
- inputSchema:
1594
- t.parameters.type === undefined
1595
- ? { type: 'object', ...t.parameters }
1596
- : t.parameters,
1597
- }),
1598
- )
1599
- }
1600
-
1601
- function turnSettled(turn: AcpTurn): Promise<void> {
1602
- return (async () => {
1603
- while (turn.events.size > 0 || !turn.finished) {
1604
- const head = turn.events.peek()
1605
- if (head?.kind === 'done' || head?.kind === 'error') return
1606
- await delay(100)
1607
- }
1608
- })()
1312
+ function toolError(text: string): BridgeToolResult {
1313
+ return { content: [{ type: 'text', text }], isError: true }
1609
1314
  }
1610
1315
 
1611
1316
  /**
@@ -1637,10 +1342,14 @@ export function mapError(error: unknown): Error {
1637
1342
  return new LlmError(message, 'QUOTA', { cause: error })
1638
1343
  if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
1639
1344
  return new LlmError(message, 'RATE_LIMIT', { cause: error })
1640
- if (/context|too long|token limit|maximum.*tokens/i.test(message))
1641
- return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
1642
1345
  if (/timeout|timed out|deadline/i.test(message))
1643
1346
  return new LlmError(message, 'TIMEOUT', { cause: error })
1347
+ if (
1348
+ /context.*(length|window|limit|overflow|exceeded)|too long|token limit|maximum.*tokens/i.test(
1349
+ message,
1350
+ )
1351
+ )
1352
+ return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
1644
1353
  if (error instanceof JsonRpcRemoteError)
1645
1354
  return new LlmError(`Antigravity: ${message}`, 'SERVER', { cause: error })
1646
1355
  return new LlmError(message, 'TRANSPORT', { cause: error })