pi-agy-acp 0.2.7 → 0.2.8

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,9 +1,12 @@
1
- import { asEffort, EFFORTS, type Effort, type QuotaDisplay } from './config.ts'
2
- import type {
3
- AccountInfo,
4
- QuotaSnapshot,
5
- QuotaGroup,
6
- QuotaBucket,
1
+ import type { QuotaDisplay } from './config.ts'
2
+ import {
3
+ clampFraction,
4
+ EXPLICIT_MEMBERS_PREFIX,
5
+ quotaForModel,
6
+ type AccountInfo,
7
+ type QuotaBucket,
8
+ type QuotaModelRef,
9
+ type QuotaSnapshot,
7
10
  } from './quota.ts'
8
11
  import type { RuntimeStatus } from './runtime.ts'
9
12
 
@@ -12,359 +15,10 @@ export interface FormattedNotice {
12
15
  level: 'info' | 'warning' | 'error'
13
16
  }
14
17
 
15
- function clampFraction(value: number | undefined): number | undefined {
16
- return typeof value === 'number' && Number.isFinite(value)
17
- ? Math.max(0, Math.min(1, value))
18
- : undefined
19
- }
20
-
21
18
  function formatAccount(account?: AccountInfo): string {
22
19
  return [account?.email, account?.plan].filter(Boolean).join(' · ')
23
20
  }
24
21
 
25
- /** Active model identity from Pi (`id` plus optional display `name` for `agy usage` labels such as `Orchestrator (Carbon)`). */
26
- export interface QuotaModelRef {
27
- readonly id: string
28
- readonly name?: string
29
- }
30
-
31
- // `agy usage` prefixes closed, exhaustive member lists with "Models within this group:";
32
- // unprefixed descriptions are free-form prose notes.
33
- const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
34
- const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
35
- const ID_DATE_SUFFIX = /[-_](?:20\d{2}[-_]\d{2}[-_]\d{2}|20\d{6})$/i
36
- type EffortQualifier = Effort | 'extra-low'
37
-
38
- // Keep longest qualifiers first (`extra[-_]low` before `low`) so compound suffixes match whole.
39
- const EFFORT_QUALIFIER_PATTERN = [
40
- 'extra[-_]low',
41
- ...[...EFFORTS].sort((a, b) => b.length - a.length),
42
- ].join('|')
43
- // Effort or thinking-mode suffixes in model IDs (`-thinking`) and `agy usage` labels (`(Thinking)`).
44
- const ID_QUALIFIER_SUFFIX = new RegExp(
45
- `[-_](?:(${EFFORT_QUALIFIER_PATTERN})(?:[-_]effort)?|(thinking))$`,
46
- 'i',
47
- )
48
- const GROUP_QUALIFIER_SUFFIX = new RegExp(
49
- `\\s*\\((${EFFORT_QUALIFIER_PATTERN}|thinking)\\)(?=\\s*(?:models?|groups?)?[\\s.!?)]*$)`,
50
- 'i',
51
- )
52
-
53
- function parseEffortQualifier(raw: string): EffortQualifier | undefined {
54
- const normalized = raw.toLowerCase().replace(/_/g, '-')
55
- if (normalized === 'extra-low') return 'extra-low'
56
- return asEffort(normalized)
57
- }
58
- const SPECIFIER = /^\d+(?:\.\d+)*b?$/
59
- const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
60
- const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
61
- const GROUP_NOISE_TOKENS = new Set(['model', 'models', 'group', 'groups'])
62
- const GENERIC_GROUP_TOKENS = new Set([
63
- ...VENDOR_TOKENS,
64
- ...FAMILY_TOKENS,
65
- ...GROUP_NOISE_TOKENS,
66
- 'all',
67
- 'other',
68
- 'default',
69
- 'general',
70
- ])
71
-
72
- /**
73
- * Tokenize into lowercase words, dotted versions, and `<n>b` parameter sizes.
74
- * Hyphens between digits become dots only for 1-2 digit version segments (`5-5` -> `5.5`),
75
- * preserving parameter sizes (`3-8b`, `120b`) and dates stripped beforehand.
76
- */
77
- function normalizeTokens(text: string): string[] {
78
- return (
79
- text
80
- .toLowerCase()
81
- .replace(/(?<=\d)-(?=\d{1,2}(?![a-z0-9.]))/g, '.')
82
- .match(/[a-z0-9]+(?:\.[0-9]+)*(?:b(?![a-z0-9]))?/g) ?? []
83
- )
84
- }
85
-
86
- interface ParsedPhrase {
87
- readonly head: string | undefined
88
- readonly words: readonly string[]
89
- readonly specs: readonly string[]
90
- readonly effort: EffortQualifier | undefined
91
- readonly thinking: boolean
92
- readonly effortConflict: boolean
93
- readonly tokenCount: number
94
- readonly canonical: string
95
- }
96
-
97
- function buildPhrase(
98
- tokens: readonly string[],
99
- effort?: EffortQualifier,
100
- thinking = false,
101
- effortConflict = false,
102
- ): ParsedPhrase {
103
- const words: string[] = []
104
- const specs: string[] = []
105
- for (const token of tokens) {
106
- if (SPECIFIER.test(token)) specs.push(token)
107
- else words.push(token)
108
- }
109
- return {
110
- head: tokens[0],
111
- words,
112
- specs,
113
- effort,
114
- thinking,
115
- effortConflict,
116
- tokenCount: tokens.length,
117
- canonical: `${words.join(' ')}|${specs.join(' ')}`,
118
- }
119
- }
120
-
121
- function parseClause(raw: string, stripNoise = false): ParsedPhrase {
122
- let text = raw.trim().replace(/[.!?]+$/, '')
123
- let effort: EffortQualifier | undefined
124
- let thinking = false
125
- let effortConflict = false
126
- const applyQualifier = (rawQualifier: string) => {
127
- const token = rawQualifier.toLowerCase()
128
- if (token === 'thinking') {
129
- thinking = true
130
- return
131
- }
132
- const nextEffort = parseEffortQualifier(token)
133
- if (nextEffort) {
134
- if (effort && effort !== nextEffort) effortConflict = true
135
- effort = nextEffort
136
- }
137
- }
138
- while (text.length > 0) {
139
- const withoutDate = text.replace(ID_DATE_SUFFIX, '')
140
- if (withoutDate !== text) {
141
- text = withoutDate
142
- continue
143
- }
144
- const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
145
- if (groupQual) {
146
- applyQualifier(groupQual[1]!)
147
- text =
148
- text.slice(0, groupQual.index) +
149
- text.slice(groupQual.index + groupQual[0].length)
150
- continue
151
- }
152
- const idQual = ID_QUALIFIER_SUFFIX.exec(text)
153
- if (idQual) {
154
- applyQualifier((idQual[1] ?? idQual[2])!)
155
- text = text.slice(0, idQual.index)
156
- continue
157
- }
158
- break
159
- }
160
- const baseTokens = normalizeTokens(text)
161
- const fallback = baseTokens.length === 0
162
- const tokens = [...(fallback ? normalizeTokens(raw) : baseTokens)]
163
- while (tokens.length >= 2 && VENDOR_TOKENS.has(tokens[0]!)) tokens.shift()
164
- const cleaned = stripNoise
165
- ? (() => {
166
- const stripped = tokens.filter((t) => !GROUP_NOISE_TOKENS.has(t))
167
- return stripped.length >= 2 ? stripped : tokens
168
- })()
169
- : tokens
170
- return buildPhrase(
171
- cleaned,
172
- fallback ? undefined : effort,
173
- fallback ? false : thinking,
174
- !fallback && effortConflict,
175
- )
176
- }
177
-
178
- function parseGroupPhrases(
179
- text: string,
180
- excludeGeneric: boolean,
181
- ): ParsedPhrase[] {
182
- const phrases: ParsedPhrase[] = []
183
- for (const part of text.split(CLAUSE_SPLIT)) {
184
- if (
185
- excludeGeneric &&
186
- normalizeTokens(part).every((token) => GENERIC_GROUP_TOKENS.has(token))
187
- )
188
- continue
189
- const phrase = parseClause(part, true)
190
- if (phrase.tokenCount > 0 && !phrase.effortConflict) phrases.push(phrase)
191
- }
192
- return phrases
193
- }
194
-
195
- function buildModelCandidates(id: string, name?: string): ParsedPhrase[] {
196
- const idPhrase = parseClause(id)
197
- const namePhrase = name ? parseClause(name) : undefined
198
- if (
199
- idPhrase.effortConflict ||
200
- namePhrase?.effortConflict ||
201
- (idPhrase.effort &&
202
- namePhrase?.effort &&
203
- idPhrase.effort !== namePhrase.effort)
204
- )
205
- return []
206
- const effort = idPhrase.effort ?? namePhrase?.effort
207
- const thinking = idPhrase.thinking || Boolean(namePhrase?.thinking)
208
- const seen = new Set<string>()
209
- const out: ParsedPhrase[] = []
210
- for (const candidate of [idPhrase, namePhrase]) {
211
- if (!candidate || candidate.tokenCount === 0) continue
212
- const phrase = { ...candidate, effort, thinking }
213
- const key = `${phrase.canonical}#${phrase.effort ?? ''}#${phrase.thinking ? 't' : ''}`
214
- if (!seen.has(key)) {
215
- seen.add(key)
216
- out.push(phrase)
217
- }
218
- }
219
- return out
220
- }
221
-
222
- const isExactPhrase = (groupPhrase: ParsedPhrase, modelPhrase: ParsedPhrase) =>
223
- groupPhrase.canonical === modelPhrase.canonical
224
-
225
- /**
226
- * True for a subfamily without version/size (`GPT-OSS`, `Gemini Flash`) or a
227
- * single-version generation line (`Gemini 4`, `Gemini 3.8`) matching the model.
228
- */
229
- function isBroaderVariant(
230
- groupPhrase: ParsedPhrase,
231
- modelPhrase: ParsedPhrase,
232
- ): boolean {
233
- if (
234
- groupPhrase.tokenCount < 2 ||
235
- !groupPhrase.head ||
236
- groupPhrase.head !== modelPhrase.head
237
- )
238
- return false
239
- if (groupPhrase.words.length >= 2 && groupPhrase.specs.length === 0)
240
- return groupPhrase.words.join(' ') === modelPhrase.words.join(' ')
241
- const modelVersions = modelPhrase.specs.filter((s) => !s.endsWith('b'))
242
- return (
243
- groupPhrase.words.length === 1 &&
244
- groupPhrase.specs.length === 1 &&
245
- !groupPhrase.specs[0]!.endsWith('b') &&
246
- modelVersions.length === 1 &&
247
- modelVersions[0] === groupPhrase.specs[0]
248
- )
249
- }
250
-
251
- function extractFamily(text?: string): string | undefined {
252
- const head = text
253
- ? normalizeTokens(text).find((token) => !VENDOR_TOKENS.has(token))
254
- : undefined
255
- return head && FAMILY_TOKENS.has(head) ? head : undefined
256
- }
257
-
258
- function isGenericFamilyGroup(group: QuotaGroup, family: string): boolean {
259
- if (EXPLICIT_MEMBERS_PREFIX.test(group.description)) return false
260
- return group.name.split(CLAUSE_SPLIT).some((clause) => {
261
- const tokens = normalizeTokens(clause)
262
- return (
263
- tokens.includes(family) &&
264
- tokens.every((token) => GENERIC_GROUP_TOKENS.has(token))
265
- )
266
- })
267
- }
268
-
269
- const matchGroup = (
270
- phrases: readonly ParsedPhrase[],
271
- candidates: readonly ParsedPhrase[],
272
- relation: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
273
- qualOk: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
274
- ) => phrases.some((p) => candidates.some((c) => qualOk(p, c) && relation(p, c)))
275
-
276
- function selectQuotaGroups(
277
- snapshot: QuotaSnapshot,
278
- model?: QuotaModelRef,
279
- ): QuotaGroup[] {
280
- if (!model) return []
281
- const candidates = buildModelCandidates(model.id, model.name)
282
- if (candidates.length === 0) return []
283
-
284
- const indexed = snapshot.groups.map((group) => {
285
- const explicit = EXPLICIT_MEMBERS_PREFIX.test(group.description)
286
- const raw = explicit
287
- ? group.description.replace(EXPLICIT_MEMBERS_PREFIX, '')
288
- : group.name
289
- return { group, explicit, phrases: parseGroupPhrases(raw, !explicit) }
290
- })
291
-
292
- // Without an effort qualifier (`low`/`medium`/`high`) on the model reference, any matching
293
- // effort-capped pool makes group ownership depend on unknown active effort; return unknown.
294
- const omittedEffort = (g: ParsedPhrase, m: ParsedPhrase) =>
295
- g.effort !== undefined && m.effort === undefined
296
- if (
297
- indexed.some(
298
- (entry) =>
299
- matchGroup(entry.phrases, candidates, isExactPhrase, omittedEffort) ||
300
- matchGroup(entry.phrases, candidates, isBroaderVariant, omittedEffort),
301
- )
302
- )
303
- return []
304
-
305
- const compatQual = (g: ParsedPhrase, m: ParsedPhrase) =>
306
- (g.effort === undefined || g.effort === m.effort) &&
307
- (!g.thinking || m.thinking || m.effort !== undefined)
308
-
309
- const authoritative: (typeof indexed)[number][] = []
310
- const variantOnly: (typeof indexed)[number][] = []
311
- for (const entry of indexed) {
312
- const exact = matchGroup(entry.phrases, candidates, isExactPhrase, compatQual)
313
- const variant = matchGroup(
314
- entry.phrases,
315
- candidates,
316
- isBroaderVariant,
317
- compatQual,
318
- )
319
- if (exact || (entry.explicit && variant)) authoritative.push(entry)
320
- else if (variant) variantOnly.push(entry)
321
- }
322
- if (authoritative.length > 0) {
323
- return [
324
- ...authoritative,
325
- ...(variantOnly.length === 1 ? variantOnly : []),
326
- ].map((e) => e.group)
327
- }
328
- if (variantOnly.length === 1) return [variantOnly[0]!.group]
329
- if (variantOnly.length > 1) return []
330
-
331
- const thinkingQual = (g: ParsedPhrase, m: ParsedPhrase) =>
332
- g.thinking && !m.thinking && g.effort === undefined && m.effort === undefined
333
- const thinkingMatches = indexed.filter(
334
- (entry) =>
335
- matchGroup(entry.phrases, candidates, isExactPhrase, thinkingQual) ||
336
- matchGroup(entry.phrases, candidates, isBroaderVariant, thinkingQual),
337
- )
338
- if (thinkingMatches.length === 1) return [thinkingMatches[0]!.group]
339
- if (thinkingMatches.length > 1) return []
340
-
341
- const family = extractFamily(model.id) ?? extractFamily(model.name)
342
- if (!family) return []
343
- const generic = indexed.filter(
344
- (entry) => !entry.explicit && isGenericFamilyGroup(entry.group, family),
345
- )
346
- return generic.length === 1 ? [generic[0]!.group] : []
347
- }
348
-
349
- /** Lowest known window across the model's governing quota group(s); returns undefined when unknown or ambiguous. */
350
- export function quotaForModel(
351
- snapshot: QuotaSnapshot,
352
- model?: QuotaModelRef,
353
- ): { group: QuotaGroup; bucket: QuotaBucket; fraction: number } | undefined {
354
- if (snapshot.status !== 'ok') return undefined
355
- const groups = selectQuotaGroups(snapshot, model)
356
- let lowest: ReturnType<typeof quotaForModel>
357
- for (const group of groups) {
358
- for (const bucket of group.buckets) {
359
- const fraction = clampFraction(bucket.remainingFraction)
360
- if (fraction === undefined) continue
361
- if (!lowest || fraction < lowest.fraction)
362
- lowest = { group, bucket, fraction }
363
- }
364
- }
365
- return lowest
366
- }
367
-
368
22
  /** Convert a remaining fraction (`0..1`) into the fraction shown for `display`. */
369
23
  export function displayFraction(
370
24
  remainingFraction: number,
package/src/history.ts CHANGED
@@ -15,13 +15,7 @@ import type {
15
15
  GenerateOptions,
16
16
  RequestMessage,
17
17
  } from './protocol.ts'
18
-
19
- /** Server name under which Pi tools reach the agent; the agent prefixes tool names with `mcp_<server>_`. */
20
- export const MCP_SERVER_NAME = 'pi'
21
- /** Agent-visible prefix of every Pi tool. */
22
- export const AGENT_TOOL_PREFIX = `mcp_${MCP_SERVER_NAME}_`
23
- /** Fallback MCP tool name for invoking any Pi tool omitted from direct declarations. */
24
- export const CALL_TOOL_NAME = 'pi_call_tool'
18
+ import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './mcp-bridge.ts'
25
19
 
26
20
  /**
27
21
  * Replay budget for `agy`, kept below its `64,000 * 3 = 192,000`
@@ -41,6 +35,10 @@ const HISTORY_OPEN = '<pi_history>\n'
41
35
  const HISTORY_CLOSE = '\n</pi_history>\n\n'
42
36
  /** Upper bound of the omission notice, reserved before history is selected. */
43
37
  const OMISSION_NOTICE_RESERVE_BYTES = 128
38
+ const HISTORY_OVERHEAD_BYTES =
39
+ utf8Bytes(HISTORY_OPEN) +
40
+ utf8Bytes(HISTORY_CLOSE) +
41
+ OMISSION_NOTICE_RESERVE_BYTES
44
42
 
45
43
  /**
46
44
  * Live input for a rebuild whose trailing messages are all tool results (for
@@ -233,6 +231,33 @@ function promptBlocks(
233
231
  return blocks
234
232
  }
235
233
 
234
+ function liveInputBlocks(input: readonly RequestMessage[]): AcpPromptBlock[] {
235
+ return input.length > 0
236
+ ? inputPrompt(input)
237
+ : [{ type: 'text', text: EMPTY_INPUT_CONTINUATION }]
238
+ }
239
+
240
+ function buildReplayPrompt(
241
+ history: readonly RequestMessage[],
242
+ preamble: string,
243
+ preambleBytes: number,
244
+ inputBlocks: readonly AcpPromptBlock[],
245
+ inputBytes: number,
246
+ maxBytes: number,
247
+ ): AcpPromptBlock[] {
248
+ const blocks: AcpPromptBlock[] = []
249
+ if (preamble.length > 0) blocks.push({ type: 'text', text: preamble })
250
+ if (history.length > 0) {
251
+ const text = historyTranscript(
252
+ history,
253
+ Math.max(0, maxBytes - preambleBytes - inputBytes - HISTORY_OVERHEAD_BYTES),
254
+ )
255
+ if (text.length > 0) blocks.push({ type: 'text', text })
256
+ }
257
+ blocks.push(...inputBlocks)
258
+ return blocks
259
+ }
260
+
236
261
  /**
237
262
  * Build the prompt that (re)creates a session: harness system/tool instructions,
238
263
  * earlier history as transcript, and trailing input messages as live content.
@@ -258,32 +283,15 @@ export function replayPrompt(
258
283
  options.system ?? '',
259
284
  options.supplementalTools ?? [],
260
285
  )
261
- const inputBlocks: AcpPromptBlock[] =
262
- input.length > 0
263
- ? inputPrompt(input)
264
- : [{ type: 'text', text: EMPTY_INPUT_CONTINUATION }]
265
- const blocks: AcpPromptBlock[] = []
266
- if (preamble.length > 0) blocks.push({ type: 'text', text: preamble })
267
- if (history.length > 0) {
268
- const maxBytes = options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES
269
- const preambleBytes = utf8Bytes(preamble)
270
- const inputBytes = inputBlocks.reduce(
271
- (total, block) =>
272
- total + (block.type === 'text' ? utf8Bytes(block.text) : 0),
273
- 0,
274
- )
275
- const overhead =
276
- utf8Bytes(HISTORY_OPEN) +
277
- utf8Bytes(HISTORY_CLOSE) +
278
- OMISSION_NOTICE_RESERVE_BYTES
279
- const text = historyTranscript(
280
- history,
281
- Math.max(0, maxBytes - preambleBytes - inputBytes - overhead),
282
- )
283
- if (text.length > 0) blocks.push({ type: 'text', text })
284
- }
285
- blocks.push(...inputBlocks)
286
- return blocks
286
+ const inputBlocks = liveInputBlocks(input)
287
+ return buildReplayPrompt(
288
+ history,
289
+ preamble,
290
+ utf8Bytes(preamble),
291
+ inputBlocks,
292
+ textBytes(inputBlocks),
293
+ options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES,
294
+ )
287
295
  }
288
296
 
289
297
  /**
@@ -309,16 +317,10 @@ export function openingPrompts(
309
317
  options.supplementalTools ?? [],
310
318
  )
311
319
  const maxBytes = options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES
312
- const inputBlocks =
313
- input.length > 0
314
- ? inputPrompt(input)
315
- : [{ type: 'text' as const, text: EMPTY_INPUT_CONTINUATION }]
316
- const historyOverhead =
317
- history.length > 0
318
- ? utf8Bytes(HISTORY_OPEN) +
319
- utf8Bytes(HISTORY_CLOSE) +
320
- OMISSION_NOTICE_RESERVE_BYTES
321
- : 0
320
+ const inputBlocks = liveInputBlocks(input)
321
+ const preambleBytes = utf8Bytes(preamble)
322
+ const inputBytes = textBytes(inputBlocks)
323
+ const historyOverhead = history.length > 0 ? HISTORY_OVERHEAD_BYTES : 0
322
324
  // Without history, avoid an extra prelude LLM round-trip while preamble + input still fit under agy's 192 KB cap.
323
325
  const singlePromptLimit =
324
326
  history.length > 0 || options.maxHistoryBytes !== undefined
@@ -326,10 +328,19 @@ export function openingPrompts(
326
328
  : Math.max(maxBytes, PRELUDE_CHUNK_BYTES)
327
329
  if (
328
330
  preamble.length === 0 ||
329
- utf8Bytes(preamble) + textBytes(inputBlocks) + historyOverhead <=
330
- singlePromptLimit
331
- )
332
- return [replayPrompt(history, input, options)]
331
+ preambleBytes + inputBytes + historyOverhead <= singlePromptLimit
332
+ ) {
333
+ return [
334
+ buildReplayPrompt(
335
+ history,
336
+ preamble,
337
+ preambleBytes,
338
+ inputBlocks,
339
+ inputBytes,
340
+ maxBytes,
341
+ ),
342
+ ]
343
+ }
333
344
  const parts = splitWithinBytes(preamble, PRELUDE_CHUNK_BYTES)
334
345
  const preludes = parts.map((text, index) => [
335
346
  {
@@ -339,7 +350,7 @@ export function openingPrompts(
339
350
  ])
340
351
  return [
341
352
  ...preludes,
342
- replayPrompt(history, input, { maxHistoryBytes: maxBytes }),
353
+ buildReplayPrompt(history, '', 0, inputBlocks, inputBytes, maxBytes),
343
354
  ]
344
355
  }
345
356
 
package/src/host.ts CHANGED
@@ -183,7 +183,7 @@ export const spawnAcp: AcpSpawner = (argv, cwd) => {
183
183
 
184
184
  export const runCommand: CommandRunner = (
185
185
  argv: readonly string[],
186
- timeout: number,
186
+ timeoutMs: number,
187
187
  options?: CommandOptions,
188
188
  ): Promise<CommandOutput> =>
189
189
  new Promise((resolve) => {
@@ -261,7 +261,7 @@ export const runCommand: CommandRunner = (
261
261
  const onSignalAbort = (): void => abort('signal')
262
262
  options?.signal?.addEventListener('abort', onSignalAbort, { once: true })
263
263
 
264
- const timeoutTimer = setTimeout(() => abort('timeout'), timeout)
264
+ const timeoutTimer = setTimeout(() => abort('timeout'), timeoutMs)
265
265
  timeoutTimer.unref()
266
266
 
267
267
  child.stdout.on('data', (chunk: Buffer) => {
package/src/mcp-bridge.ts CHANGED
@@ -18,10 +18,18 @@ import {
18
18
  } from 'node:http'
19
19
  import type { AddressInfo } from 'node:net'
20
20
  import type { ToolSchema } from './protocol.ts'
21
- import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
22
- import { digest } from './util.ts'
21
+ import { digest, isRecord } from './util.ts'
23
22
  import { VERSION } from './version.ts'
24
23
 
24
+ /** Server name under which Pi tools reach the agent; the agent prefixes tool names with `mcp_<server>_`. */
25
+ export const MCP_SERVER_NAME = 'pi'
26
+ /** Agent-visible prefix of every Pi tool. */
27
+ export const AGENT_TOOL_PREFIX = `mcp_${MCP_SERVER_NAME}_`
28
+ /** Fallback MCP tool name for invoking any Pi tool omitted from direct declarations. */
29
+ export const CALL_TOOL_NAME = 'pi_call_tool'
30
+ /** Tool the agent calls to keep waiting on a relayed Pi tool result. */
31
+ export const AWAIT_TOOL_NAME = 'pi_await_result'
32
+
25
33
  /** One tool schema advertised over MCP. */
26
34
  export interface BridgeTool {
27
35
  name: string
@@ -29,6 +37,44 @@ export interface BridgeTool {
29
37
  inputSchema: Record<string, unknown>
30
38
  }
31
39
 
40
+ /** MCP descriptor of {@link AWAIT_TOOL_NAME}. */
41
+ export const AWAIT_TOOL: BridgeTool = {
42
+ name: AWAIT_TOOL_NAME,
43
+ description:
44
+ 'Wait for the result of a harness tool call that reported it is still running. Call this only when a tool result tells you to, passing the call_id it gave.',
45
+ inputSchema: {
46
+ type: 'object',
47
+ properties: {
48
+ call_id: {
49
+ type: 'string',
50
+ description: 'The call id from the still-running notice.',
51
+ },
52
+ },
53
+ required: ['call_id'],
54
+ },
55
+ }
56
+
57
+ /** MCP descriptor of {@link CALL_TOOL_NAME} (~340B, stays below agy's lazy cutoff). */
58
+ export const CALL_TOOL: BridgeTool = {
59
+ name: CALL_TOOL_NAME,
60
+ description:
61
+ 'Invoke any harness tool by exact name when mcp_pi_<name> is absent from your direct tool declarations.',
62
+ inputSchema: {
63
+ type: 'object',
64
+ properties: {
65
+ name: {
66
+ type: 'string',
67
+ description: 'Exact Pi tool name without mcp_pi_ prefix.',
68
+ },
69
+ arguments: {
70
+ type: 'object',
71
+ description: 'Arguments object matching that tool schema.',
72
+ },
73
+ },
74
+ required: ['name'],
75
+ },
76
+ }
77
+
32
78
  /** One MCP content item returned to the agent. */
33
79
  export type BridgeContent =
34
80
  | { type: 'text'; text: string }
@@ -45,7 +91,7 @@ export interface BridgeCallRequest {
45
91
  /** Tenant key taken from the request path, when the session registered one. */
46
92
  tenantKey: string | undefined
47
93
  /** ACP session id the agent reported in `_meta`, when present. */
48
- conversationId: string | undefined
94
+ acpSessionId: string | undefined
49
95
  /** MCP tool name without any agent-side prefix. */
50
96
  name: string
51
97
  /** Parsed tool arguments. */
@@ -355,7 +401,7 @@ export class McpBridge {
355
401
  const name = typeof params.name === 'string' ? params.name : ''
356
402
  const args = isRecord(params.arguments) ? params.arguments : {}
357
403
  const progressToken = meta.progressToken
358
- const conversationId =
404
+ const acpSessionId =
359
405
  typeof meta[CONVERSATION_META_KEY] === 'string'
360
406
  ? (meta[CONVERSATION_META_KEY] as string)
361
407
  : undefined
@@ -428,7 +474,7 @@ export class McpBridge {
428
474
  try {
429
475
  result = await this.router.callTool({
430
476
  tenantKey,
431
- conversationId,
477
+ acpSessionId,
432
478
  name,
433
479
  arguments: args,
434
480
  signal: controller.signal,
@@ -470,10 +516,6 @@ interface RpcRequest {
470
516
  params?: unknown
471
517
  }
472
518
 
473
- function isRecord(value: unknown): value is Record<string, unknown> {
474
- return value !== null && typeof value === 'object' && !Array.isArray(value)
475
- }
476
-
477
519
  class HttpError extends Error {
478
520
  readonly status: number
479
521
 
@@ -573,10 +615,9 @@ function shortenText(text: string, maxChars: number): string {
573
615
  function compactSchemaNode(value: unknown, maxDescChars: number): unknown {
574
616
  if (Array.isArray(value))
575
617
  return value.map((item) => compactSchemaNode(item, maxDescChars))
576
- if (value === null || typeof value !== 'object') return value
577
- const record = value as Record<string, unknown>
618
+ if (!isRecord(value)) return value
578
619
  const out: Record<string, unknown> = {}
579
- for (const [key, entry] of Object.entries(record)) {
620
+ for (const [key, entry] of Object.entries(value)) {
580
621
  if (key === 'description' && typeof entry === 'string') {
581
622
  if (maxDescChars > 0) out[key] = shortenText(entry, maxDescChars)
582
623
  continue