pi-agy-acp 0.1.0 → 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/CHANGELOG.md +22 -0
- package/README.md +12 -36
- package/docs/development.md +60 -13
- package/docs/reference.md +39 -28
- package/index.ts +100 -9
- package/package.json +4 -2
- package/src/acp-process.ts +1 -3
- package/src/conversation.ts +107 -7
- package/src/format.ts +54 -12
- package/src/mcp-bridge.ts +124 -6
- package/src/pi-stream.ts +77 -44
- package/src/preflight.ts +61 -0
- package/src/quota.ts +15 -0
- package/src/runtime.ts +114 -382
- package/src/util.ts +23 -0
- package/src/version.ts +5 -0
package/src/conversation.ts
CHANGED
|
@@ -13,13 +13,16 @@
|
|
|
13
13
|
|
|
14
14
|
import { LlmError } from './protocol.ts'
|
|
15
15
|
import type { ContentBlock, StreamChunk, TokenUsage } from './protocol.ts'
|
|
16
|
-
import type {
|
|
16
|
+
import type {
|
|
17
|
+
AcpPromptResult,
|
|
18
|
+
AcpSessionUpdate,
|
|
19
|
+
AcpPermissionRequest,
|
|
20
|
+
AcpToolCallMeta,
|
|
21
|
+
} from './acp-process.ts'
|
|
17
22
|
import type { BridgeTool, BridgeToolResult } from './mcp-bridge.ts'
|
|
18
23
|
import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
|
|
19
24
|
import { AsyncQueue, deferred, type Deferred } from './util.ts'
|
|
20
25
|
|
|
21
|
-
export { CALL_TOOL_NAME }
|
|
22
|
-
|
|
23
26
|
/** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
|
|
24
27
|
const AGENT_RETRY_NOTICE = /^\s*⚠\s*API error \(attempt \d+\)/
|
|
25
28
|
/** First sentence of the notice agy inserts when one generation hits its own output cap. */
|
|
@@ -144,6 +147,9 @@ export class AcpTurn {
|
|
|
144
147
|
continuations = 0
|
|
145
148
|
/** The agent ended the prompt. */
|
|
146
149
|
finished = false
|
|
150
|
+
/** Settles after the current prompt's result or error has been queued. */
|
|
151
|
+
promptSettled: Promise<void> = Promise.resolve()
|
|
152
|
+
usage?: AcpPromptResult['usage']
|
|
147
153
|
/** A parked call was answered with a still-running notice and the agent has not resumed waiting yet. */
|
|
148
154
|
relaying = false
|
|
149
155
|
/** The turn produced visible text or a tool call. */
|
|
@@ -258,8 +264,6 @@ export interface PumpHost {
|
|
|
258
264
|
continuePrompt(): Promise<AcpPromptResult>
|
|
259
265
|
/** Request cancellation of the running turn. */
|
|
260
266
|
cancel(): void
|
|
261
|
-
/** Observe the final usage of a prompt turn. */
|
|
262
|
-
recordUsage(usage: AcpPromptResult['usage'], steps: number): void
|
|
263
267
|
}
|
|
264
268
|
|
|
265
269
|
/**
|
|
@@ -427,7 +431,7 @@ export async function* pumpStep(
|
|
|
427
431
|
turn.continuations < host.maxContinuations
|
|
428
432
|
) {
|
|
429
433
|
turn.continuations++
|
|
430
|
-
|
|
434
|
+
turn.promptSettled = host.continuePrompt().then(
|
|
431
435
|
(result) => turn.events.push({ kind: 'done', result }),
|
|
432
436
|
(error: unknown) =>
|
|
433
437
|
turn.events.push({
|
|
@@ -441,7 +445,7 @@ export async function* pumpStep(
|
|
|
441
445
|
turn.finished = true
|
|
442
446
|
yield* close()
|
|
443
447
|
const calls = turn.toolSteps + turn.continuations + 1
|
|
444
|
-
|
|
448
|
+
turn.usage = event.result.usage
|
|
445
449
|
const usage = toTokenUsage(event.result.usage, calls)
|
|
446
450
|
if (usage !== undefined) yield { type: 'usage', usage }
|
|
447
451
|
if (stop === 'end_turn' && !turn.produced) {
|
|
@@ -518,3 +522,99 @@ export function relayNotice(call: ParkedCall): BridgeToolResult {
|
|
|
518
522
|
],
|
|
519
523
|
}
|
|
520
524
|
}
|
|
525
|
+
|
|
526
|
+
/** Structured MCP metadata the agent reported for one tool call. */
|
|
527
|
+
export interface ReportedToolCall {
|
|
528
|
+
kind?: string
|
|
529
|
+
serverName?: string
|
|
530
|
+
toolName?: string
|
|
531
|
+
/** Set when later updates contradicted an already established field. */
|
|
532
|
+
conflict?: boolean
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Read a non-empty string field. */
|
|
536
|
+
function nonEmpty(value: unknown): string | undefined {
|
|
537
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Extract the structured `(serverName, toolName)` an agent claimed in one
|
|
542
|
+
* permission request: top-level `mcpServerName`/`mcpToolName` or `_meta`.
|
|
543
|
+
* `title` and `rawInput` are deliberately not consulted.
|
|
544
|
+
*/
|
|
545
|
+
export function structuredToolMeta(
|
|
546
|
+
toolCall: AcpPermissionRequest['toolCall'],
|
|
547
|
+
): {
|
|
548
|
+
serverName?: string
|
|
549
|
+
toolName?: string
|
|
550
|
+
} {
|
|
551
|
+
const meta: AcpToolCallMeta | undefined = toolCall?._meta
|
|
552
|
+
const serverName =
|
|
553
|
+
nonEmpty(toolCall?.mcpServerName) ??
|
|
554
|
+
nonEmpty(meta?.mcpServerName) ??
|
|
555
|
+
nonEmpty(meta?.serverName) ??
|
|
556
|
+
nonEmpty(meta?.server)
|
|
557
|
+
const toolName =
|
|
558
|
+
nonEmpty(toolCall?.mcpToolName) ??
|
|
559
|
+
nonEmpty(meta?.mcpToolName) ??
|
|
560
|
+
nonEmpty(meta?.toolName) ??
|
|
561
|
+
nonEmpty(meta?.tool)
|
|
562
|
+
return {
|
|
563
|
+
...(serverName !== undefined ? { serverName } : {}),
|
|
564
|
+
...(toolName !== undefined ? { toolName } : {}),
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Record the structured metadata of one agent-reported tool-call update.
|
|
570
|
+
* The first report establishes the identity; later updates merge only the
|
|
571
|
+
* fields actually present, so a status-only `tool_call_update` never wipes an
|
|
572
|
+
* established `server`/`tool`/`kind`. A later field that contradicts the
|
|
573
|
+
* established identity keeps the original value and marks the record
|
|
574
|
+
* anomalous — the permission gate refuses every further request for that call.
|
|
575
|
+
* @returns 'created' | 'merged' | 'conflict', or undefined for ignored updates.
|
|
576
|
+
*/
|
|
577
|
+
export function recordReportedToolCall(
|
|
578
|
+
conv: { reportedToolCalls: Map<string, ReportedToolCall> },
|
|
579
|
+
update: AcpSessionUpdate,
|
|
580
|
+
): 'created' | 'merged' | 'conflict' | undefined {
|
|
581
|
+
if (
|
|
582
|
+
update.sessionUpdate !== 'tool_call' &&
|
|
583
|
+
update.sessionUpdate !== 'tool_call_update'
|
|
584
|
+
)
|
|
585
|
+
return
|
|
586
|
+
if (typeof update.toolCallId !== 'string' || update.toolCallId.length === 0)
|
|
587
|
+
return
|
|
588
|
+
const { serverName, toolName } = structuredToolMeta(update)
|
|
589
|
+
const kind = typeof update.kind === 'string' ? update.kind : undefined
|
|
590
|
+
const existing = conv.reportedToolCalls.get(update.toolCallId)
|
|
591
|
+
const merged: ReportedToolCall = existing === undefined ? {} : { ...existing }
|
|
592
|
+
let conflict = false
|
|
593
|
+
if (kind !== undefined) {
|
|
594
|
+
if (merged.kind !== undefined && merged.kind !== kind) conflict = true
|
|
595
|
+
else merged.kind = kind
|
|
596
|
+
}
|
|
597
|
+
if (serverName !== undefined) {
|
|
598
|
+
if (merged.serverName !== undefined && merged.serverName !== serverName)
|
|
599
|
+
conflict = true
|
|
600
|
+
else merged.serverName = serverName
|
|
601
|
+
}
|
|
602
|
+
if (toolName !== undefined) {
|
|
603
|
+
if (merged.toolName !== undefined && merged.toolName !== toolName)
|
|
604
|
+
conflict = true
|
|
605
|
+
else merged.toolName = toolName
|
|
606
|
+
}
|
|
607
|
+
if (conflict) merged.conflict = true
|
|
608
|
+
conv.reportedToolCalls.set(update.toolCallId, merged)
|
|
609
|
+
if (conflict) return 'conflict'
|
|
610
|
+
return existing === undefined ? 'created' : 'merged'
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Whether `rawInput` carries no arguments at all (MCP server loading probes). */
|
|
614
|
+
export function isEmptyInput(rawInput: unknown): boolean {
|
|
615
|
+
if (rawInput === undefined || rawInput === null) return true
|
|
616
|
+
if (typeof rawInput === 'string') return rawInput.trim().length === 0
|
|
617
|
+
if (Array.isArray(rawInput)) return rawInput.length === 0
|
|
618
|
+
if (typeof rawInput === 'object') return Object.keys(rawInput).length === 0
|
|
619
|
+
return false
|
|
620
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import type {
|
|
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 =
|
|
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 =
|
|
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:
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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 (
|
|
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
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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 =
|
|
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()
|