pi-agy-acp 0.1.2 → 0.1.4

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,3 +1,4 @@
1
+ import { asEffort, type Effort, type QuotaDisplay } from './config.ts'
1
2
  import type {
2
3
  AccountInfo,
3
4
  QuotaSnapshot,
@@ -21,21 +22,319 @@ function formatAccount(account?: AccountInfo): string {
21
22
  return [account?.email, account?.plan].filter(Boolean).join(' · ')
22
23
  }
23
24
 
24
- /** Lowest known window for the model family; unknown groups fall back conservatively. */
25
+ /** Active model identity from Pi (`id` plus optional display `name` for `/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
+ // Effort or thinking-mode suffixes in model IDs (`-thinking`) and `/usage` labels (`(Thinking)`).
37
+ const ID_QUALIFIER_SUFFIX = /[-_](low|medium|high|thinking)$/i
38
+ const GROUP_QUALIFIER_SUFFIX =
39
+ /\s*\((low|medium|high|thinking)\)(?=\s*(?:models?|groups?)?[\s.!?)]*$)/i
40
+ const SPECIFIER = /^\d+(?:\.\d+)*b?$/
41
+ const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
42
+ const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
43
+ const GROUP_NOISE_TOKENS = new Set(['model', 'models', 'group', 'groups'])
44
+ const GENERIC_GROUP_TOKENS = new Set([
45
+ ...VENDOR_TOKENS,
46
+ ...FAMILY_TOKENS,
47
+ ...GROUP_NOISE_TOKENS,
48
+ 'all',
49
+ 'other',
50
+ 'default',
51
+ 'general',
52
+ ])
53
+
54
+ /**
55
+ * Tokenize into lowercase words, dotted versions, and `<n>b` parameter sizes.
56
+ * Hyphens between digits become dots only for 1-2 digit version segments (`5-5` -> `5.5`),
57
+ * preserving parameter sizes (`3-8b`, `120b`) and dates stripped beforehand.
58
+ */
59
+ function normalizeTokens(text: string): string[] {
60
+ return (
61
+ text
62
+ .toLowerCase()
63
+ .replace(/(?<=\d)-(?=\d{1,2}(?![a-z0-9.]))/g, '.')
64
+ .match(/[a-z0-9]+(?:\.[0-9]+)*(?:b(?![a-z0-9]))?/g) ?? []
65
+ )
66
+ }
67
+
68
+ interface ParsedPhrase {
69
+ readonly head: string | undefined
70
+ readonly words: readonly string[]
71
+ readonly specs: readonly string[]
72
+ readonly effort: Effort | undefined
73
+ readonly thinking: boolean
74
+ readonly effortConflict: boolean
75
+ readonly tokenCount: number
76
+ readonly canonical: string
77
+ }
78
+
79
+ function buildPhrase(
80
+ tokens: readonly string[],
81
+ effort?: Effort,
82
+ thinking = false,
83
+ effortConflict = false,
84
+ ): ParsedPhrase {
85
+ const words: string[] = []
86
+ const specs: string[] = []
87
+ for (const token of tokens) {
88
+ if (SPECIFIER.test(token)) specs.push(token)
89
+ else words.push(token)
90
+ }
91
+ return {
92
+ head: tokens[0],
93
+ words,
94
+ specs,
95
+ effort,
96
+ thinking,
97
+ effortConflict,
98
+ tokenCount: tokens.length,
99
+ canonical: `${words.join(' ')}|${specs.join(' ')}`,
100
+ }
101
+ }
102
+
103
+ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
104
+ let text = raw.trim().replace(/[.!?]+$/, '')
105
+ let effort: Effort | undefined
106
+ let thinking = false
107
+ let effortConflict = false
108
+ while (text.length > 0) {
109
+ const withoutDate = text.replace(ID_DATE_SUFFIX, '')
110
+ if (withoutDate !== text) {
111
+ text = withoutDate
112
+ continue
113
+ }
114
+ const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
115
+ if (groupQual) {
116
+ const nextEffort = asEffort(groupQual[1]!.toLowerCase())
117
+ if (nextEffort) {
118
+ if (effort && effort !== nextEffort) effortConflict = true
119
+ effort = nextEffort
120
+ } else {
121
+ thinking = true
122
+ }
123
+ text =
124
+ text.slice(0, groupQual.index) +
125
+ text.slice(groupQual.index + groupQual[0].length)
126
+ continue
127
+ }
128
+ const idQual = ID_QUALIFIER_SUFFIX.exec(text)
129
+ if (idQual) {
130
+ const nextEffort = asEffort(idQual[1]!.toLowerCase())
131
+ if (nextEffort) {
132
+ if (effort && effort !== nextEffort) effortConflict = true
133
+ effort = nextEffort
134
+ } else {
135
+ thinking = true
136
+ }
137
+ text = text.slice(0, idQual.index)
138
+ continue
139
+ }
140
+ break
141
+ }
142
+ const baseTokens = normalizeTokens(text)
143
+ const fallback = baseTokens.length === 0
144
+ const tokens = [...(fallback ? normalizeTokens(raw) : baseTokens)]
145
+ while (tokens.length >= 2 && VENDOR_TOKENS.has(tokens[0]!)) tokens.shift()
146
+ const cleaned = stripNoise
147
+ ? (() => {
148
+ const stripped = tokens.filter((t) => !GROUP_NOISE_TOKENS.has(t))
149
+ return stripped.length >= 2 ? stripped : tokens
150
+ })()
151
+ : tokens
152
+ return buildPhrase(
153
+ cleaned,
154
+ fallback ? undefined : effort,
155
+ fallback ? false : thinking,
156
+ !fallback && effortConflict,
157
+ )
158
+ }
159
+
160
+ function parseGroupPhrases(
161
+ text: string,
162
+ excludeGeneric: boolean,
163
+ ): ParsedPhrase[] {
164
+ const phrases: ParsedPhrase[] = []
165
+ for (const part of text.split(CLAUSE_SPLIT)) {
166
+ if (
167
+ excludeGeneric &&
168
+ normalizeTokens(part).every((token) => GENERIC_GROUP_TOKENS.has(token))
169
+ )
170
+ continue
171
+ const phrase = parseClause(part, true)
172
+ if (phrase.tokenCount > 0 && !phrase.effortConflict) phrases.push(phrase)
173
+ }
174
+ return phrases
175
+ }
176
+
177
+ function buildModelCandidates(id: string, name?: string): ParsedPhrase[] {
178
+ const idPhrase = parseClause(id)
179
+ const namePhrase = name ? parseClause(name) : undefined
180
+ if (
181
+ idPhrase.effortConflict ||
182
+ namePhrase?.effortConflict ||
183
+ (idPhrase.effort &&
184
+ namePhrase?.effort &&
185
+ idPhrase.effort !== namePhrase.effort)
186
+ )
187
+ return []
188
+ const effort = idPhrase.effort ?? namePhrase?.effort
189
+ const thinking = idPhrase.thinking || Boolean(namePhrase?.thinking)
190
+ const seen = new Set<string>()
191
+ const out: ParsedPhrase[] = []
192
+ for (const candidate of [idPhrase, namePhrase]) {
193
+ if (!candidate || candidate.tokenCount === 0) continue
194
+ const phrase = { ...candidate, effort, thinking }
195
+ const key = `${phrase.canonical}#${phrase.effort ?? ''}#${phrase.thinking ? 't' : ''}`
196
+ if (!seen.has(key)) {
197
+ seen.add(key)
198
+ out.push(phrase)
199
+ }
200
+ }
201
+ return out
202
+ }
203
+
204
+ const isExactPhrase = (groupPhrase: ParsedPhrase, modelPhrase: ParsedPhrase) =>
205
+ groupPhrase.canonical === modelPhrase.canonical
206
+
207
+ /**
208
+ * True for a subfamily without version/size (`GPT-OSS`, `Gemini Flash`) or a
209
+ * single-version generation line (`Gemini 4`, `Gemini 3.8`) matching the model.
210
+ */
211
+ function isBroaderVariant(
212
+ groupPhrase: ParsedPhrase,
213
+ modelPhrase: ParsedPhrase,
214
+ ): boolean {
215
+ if (
216
+ groupPhrase.tokenCount < 2 ||
217
+ !groupPhrase.head ||
218
+ groupPhrase.head !== modelPhrase.head
219
+ )
220
+ return false
221
+ if (groupPhrase.words.length >= 2 && groupPhrase.specs.length === 0)
222
+ return groupPhrase.words.join(' ') === modelPhrase.words.join(' ')
223
+ const modelVersions = modelPhrase.specs.filter((s) => !s.endsWith('b'))
224
+ return (
225
+ groupPhrase.words.length === 1 &&
226
+ groupPhrase.specs.length === 1 &&
227
+ !groupPhrase.specs[0]!.endsWith('b') &&
228
+ modelVersions.length === 1 &&
229
+ modelVersions[0] === groupPhrase.specs[0]
230
+ )
231
+ }
232
+
233
+ function extractFamily(text?: string): string | undefined {
234
+ const head = text
235
+ ? normalizeTokens(text).find((token) => !VENDOR_TOKENS.has(token))
236
+ : undefined
237
+ return head && FAMILY_TOKENS.has(head) ? head : undefined
238
+ }
239
+
240
+ function isGenericFamilyGroup(group: QuotaGroup, family: string): boolean {
241
+ if (EXPLICIT_MEMBERS_PREFIX.test(group.description)) return false
242
+ return group.name.split(CLAUSE_SPLIT).some((clause) => {
243
+ const tokens = normalizeTokens(clause)
244
+ return (
245
+ tokens.includes(family) &&
246
+ tokens.every((token) => GENERIC_GROUP_TOKENS.has(token))
247
+ )
248
+ })
249
+ }
250
+
251
+ const matchGroup = (
252
+ phrases: readonly ParsedPhrase[],
253
+ candidates: readonly ParsedPhrase[],
254
+ relation: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
255
+ qualOk: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
256
+ ) => phrases.some((p) => candidates.some((c) => qualOk(p, c) && relation(p, c)))
257
+
258
+ function selectQuotaGroups(
259
+ snapshot: QuotaSnapshot,
260
+ model?: QuotaModelRef,
261
+ ): QuotaGroup[] {
262
+ if (!model) return []
263
+ const candidates = buildModelCandidates(model.id, model.name)
264
+ if (candidates.length === 0) return []
265
+
266
+ const indexed = snapshot.groups.map((group) => {
267
+ const explicit = EXPLICIT_MEMBERS_PREFIX.test(group.description)
268
+ const raw = explicit
269
+ ? group.description.replace(EXPLICIT_MEMBERS_PREFIX, '')
270
+ : group.name
271
+ return { group, explicit, phrases: parseGroupPhrases(raw, !explicit) }
272
+ })
273
+
274
+ // Without an effort qualifier (`low`/`medium`/`high`) on the model reference, any matching
275
+ // effort-capped pool makes group ownership depend on unknown active effort; return unknown.
276
+ const omittedEffort = (g: ParsedPhrase, m: ParsedPhrase) =>
277
+ g.effort !== undefined && m.effort === undefined
278
+ if (
279
+ indexed.some(
280
+ (entry) =>
281
+ matchGroup(entry.phrases, candidates, isExactPhrase, omittedEffort) ||
282
+ matchGroup(entry.phrases, candidates, isBroaderVariant, omittedEffort),
283
+ )
284
+ )
285
+ return []
286
+
287
+ const compatQual = (g: ParsedPhrase, m: ParsedPhrase) =>
288
+ (g.effort === undefined || g.effort === m.effort) &&
289
+ (!g.thinking || m.thinking || m.effort !== undefined)
290
+
291
+ const authoritative: (typeof indexed)[number][] = []
292
+ const variantOnly: (typeof indexed)[number][] = []
293
+ for (const entry of indexed) {
294
+ const exact = matchGroup(entry.phrases, candidates, isExactPhrase, compatQual)
295
+ const variant = matchGroup(
296
+ entry.phrases,
297
+ candidates,
298
+ isBroaderVariant,
299
+ compatQual,
300
+ )
301
+ if (exact || (entry.explicit && variant)) authoritative.push(entry)
302
+ else if (variant) variantOnly.push(entry)
303
+ }
304
+ if (authoritative.length > 0) {
305
+ return [
306
+ ...authoritative,
307
+ ...(variantOnly.length === 1 ? variantOnly : []),
308
+ ].map((e) => e.group)
309
+ }
310
+ if (variantOnly.length === 1) return [variantOnly[0]!.group]
311
+ if (variantOnly.length > 1) return []
312
+
313
+ const thinkingQual = (g: ParsedPhrase, m: ParsedPhrase) =>
314
+ g.thinking && !m.thinking && g.effort === undefined && m.effort === undefined
315
+ const thinkingMatches = indexed.filter(
316
+ (entry) =>
317
+ matchGroup(entry.phrases, candidates, isExactPhrase, thinkingQual) ||
318
+ matchGroup(entry.phrases, candidates, isBroaderVariant, thinkingQual),
319
+ )
320
+ if (thinkingMatches.length === 1) return [thinkingMatches[0]!.group]
321
+ if (thinkingMatches.length > 1) return []
322
+
323
+ const family = extractFamily(model.id) ?? extractFamily(model.name)
324
+ if (!family) return []
325
+ const generic = indexed.filter(
326
+ (entry) => !entry.explicit && isGenericFamilyGroup(entry.group, family),
327
+ )
328
+ return generic.length === 1 ? [generic[0]!.group] : []
329
+ }
330
+
331
+ /** Lowest known window across the model's governing quota group(s); returns undefined when unknown or ambiguous. */
25
332
  export function quotaForModel(
26
333
  snapshot: QuotaSnapshot,
27
- model?: string,
334
+ model?: QuotaModelRef,
28
335
  ): { group: QuotaGroup; bucket: QuotaBucket; fraction: number } | undefined {
29
336
  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
337
+ const groups = selectQuotaGroups(snapshot, model)
39
338
  let lowest: ReturnType<typeof quotaForModel>
40
339
  for (const group of groups) {
41
340
  for (const bucket of group.buckets) {
@@ -48,12 +347,22 @@ export function quotaForModel(
48
347
  return lowest
49
348
  }
50
349
 
350
+ /** Convert a remaining fraction (`0..1`) into the fraction shown for `display`. */
351
+ export function displayFraction(
352
+ remainingFraction: number,
353
+ display: QuotaDisplay = 'used',
354
+ ): number {
355
+ return display === 'used' ? 1 - remainingFraction : remainingFraction
356
+ }
357
+
51
358
  export function formatQuotaStatus(
52
359
  snapshot: QuotaSnapshot,
53
- model?: string,
360
+ model?: QuotaModelRef,
361
+ display: QuotaDisplay = 'used',
54
362
  ): string | undefined {
55
363
  const quota = quotaForModel(snapshot, model)
56
- return quota ? `AGY ${Math.round(quota.fraction * 100)}%` : undefined
364
+ if (!quota) return undefined
365
+ return `AGY ${Math.round(displayFraction(quota.fraction, display) * 100)}%`
57
366
  }
58
367
 
59
368
  function resetCountdown(resetTime: string, now: number): string {
@@ -71,6 +380,7 @@ function resetCountdown(resetTime: string, now: number): string {
71
380
  export function formatQuota(
72
381
  snapshot: QuotaSnapshot,
73
382
  now = Date.now(),
383
+ display: QuotaDisplay = 'used',
74
384
  ): FormattedNotice {
75
385
  const stale = snapshot.status === 'error' && snapshot.groups.length > 0
76
386
  const lines = [`Antigravity Quota${stale ? ' (stale)' : ''}`]
@@ -85,19 +395,22 @@ export function formatQuota(
85
395
  }
86
396
  for (const group of snapshot.groups) {
87
397
  lines.push('', ` ${group.name || 'Unnamed model group'}`)
88
- if (group.description) {
89
- lines.push(
90
- ` ${group.description.replace(/^Models within this group:\s*/i, '')}`,
91
- )
398
+ const description = group.description
399
+ .replace(EXPLICIT_MEMBERS_PREFIX, '')
400
+ .trim()
401
+ if (description) {
402
+ lines.push(` ${description}`)
92
403
  }
93
404
  if (group.buckets.length === 0)
94
405
  lines.push(' No quota windows available.')
95
406
  for (const bucket of group.buckets) {
96
407
  const fraction = clampFraction(bucket.remainingFraction)
97
- const filled = fraction === undefined ? 0 : Math.round(fraction * 12)
408
+ const shown =
409
+ fraction === undefined ? undefined : displayFraction(fraction, display)
410
+ const filled = shown === undefined ? 0 : Math.round(shown * 12)
98
411
  const bar = '█'.repeat(filled) + '░'.repeat(12 - filled)
99
412
  const percent =
100
- fraction === undefined ? 'n/a' : `${Math.round(fraction * 100)}%`
413
+ shown === undefined ? 'n/a' : `${Math.round(shown * 100)}%`
101
414
  const label = (
102
415
  bucket.window ||
103
416
  bucket.name ||
package/src/history.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * Projection of Pi request history into Antigravity ACP prompts.
3
3
  *
4
- * ACP sessions own their history, so Pi replays its authoritative history
5
- * once when a session is (re)built and afterwards sends only new input. The
6
- * replay renders earlier turns as a delimited transcript in front of the
7
- * newest user input; tool calls keep the agent-visible `mcp_pi_` names.
4
+ * ACP sessions own their history, so `session/new` appends only the static MCP
5
+ * tool-routing preamble while `<system_instructions>`,
6
+ * `<harness_tool_instructions>`, and `<pi_history>` travel in a session's
7
+ * opening prompt; subsequent turns send only new input. The replay renders
8
+ * earlier turns as a delimited transcript in front of the newest user input;
9
+ * tool calls keep the agent-visible `mcp_pi_` names.
8
10
  * @module pi-agy-acp/history
9
11
  */
10
12
 
@@ -87,18 +89,60 @@ export function textOf(content: readonly ContentBlock[]): string {
87
89
  .join('')
88
90
  }
89
91
 
92
+ /** Compacted initial tool declaration forwarded in the session preamble. */
93
+ export interface SupplementalTool {
94
+ name: string
95
+ description: string
96
+ inputSchema: Record<string, unknown>
97
+ }
98
+
99
+ /** Options controlling session preamble rendering and replay budgeting. */
100
+ export interface ReplayPromptOptions {
101
+ system?: string
102
+ supplementalTools?: readonly SupplementalTool[]
103
+ maxHistoryBytes?: number
104
+ }
105
+
90
106
  /**
91
- * The bridge instructions appended to the agent's system prompt.
92
- * @param system - the Pi system prompt.
93
- * @returns the complete appended system text.
107
+ * Static bridge instructions appended to the agent's system prompt.
108
+ * @returns the static bridge preamble.
94
109
  */
95
- export function bridgeSystemPrompt(system: string): string {
96
- const preamble = [
110
+ export function bridgeSystemPrompt(): string {
111
+ return [
97
112
  'You are the primary model of a Pi coding agent session. The harness owns the conversation, the tools, and their permissions.',
98
- `Every harness tool is available to you under the prefix \`${AGENT_TOOL_PREFIX}\`: a tool named \`X\` in the instructions below is the tool \`${AGENT_TOOL_PREFIX}X\`. If \`${AGENT_TOOL_PREFIX}X\` is absent from your direct tool declarations, invoke it via \`${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME}\` with \`{"name":"X","arguments":{...}}\`. Use only these tools; pass arguments exactly as their schemas define.`,
99
- 'When the first user message contains a <pi_history> block, it reproduces the earlier part of this conversation; continue from the newest input after it without repeating completed actions.',
113
+ `Every harness tool is available to you under the prefix \`${AGENT_TOOL_PREFIX}\`: a tool named \`X\` in the harness instructions is the tool \`${AGENT_TOOL_PREFIX}X\`. If \`${AGENT_TOOL_PREFIX}X\` is absent from your direct tool declarations, invoke it via \`${AGENT_TOOL_PREFIX}${CALL_TOOL_NAME}\` with \`{"name":"X","arguments":{...}}\`. Use only these tools; pass arguments exactly as their schemas define.`,
114
+ 'When the first user message contains <system_instructions>, <harness_tool_instructions>, or <pi_history> blocks, treat <system_instructions> and <harness_tool_instructions> as harness instructions for the entire session and <pi_history> as the earlier part of this conversation; continue from the newest input after them without repeating completed actions.',
100
115
  ].join('\n')
101
- return system.length > 0 ? `${preamble}\n\n${system}` : preamble
116
+ }
117
+
118
+ /**
119
+ * Render the harness system prompt and compacted initial tool instructions for
120
+ * delivery at the head of a session's opening prompt.
121
+ * @param system - the Pi system prompt.
122
+ * @param supplementalTools - initially advertised tools whose MCP schemas were compacted, preserving their full instructions.
123
+ * @returns the delimited instruction preamble ending in a blank line, or empty string when absent.
124
+ */
125
+ export function renderSessionInstructions(
126
+ system: string,
127
+ supplementalTools: readonly SupplementalTool[] = [],
128
+ ): string {
129
+ const sections: string[] = []
130
+ if (system.length > 0) {
131
+ sections.push(`<system_instructions>\n${system}\n</system_instructions>`)
132
+ }
133
+ if (supplementalTools.length > 0) {
134
+ const entries = supplementalTools.map((t) =>
135
+ JSON.stringify({
136
+ name: t.name,
137
+ description: t.description,
138
+ parameters: t.inputSchema,
139
+ }),
140
+ )
141
+ sections.push(
142
+ `<harness_tool_instructions>\n${entries.join('\n')}\n</harness_tool_instructions>`,
143
+ )
144
+ }
145
+ return sections.length > 0 ? `${sections.join('\n\n')}\n\n` : ''
102
146
  }
103
147
 
104
148
  /**
@@ -186,32 +230,39 @@ export function promptBlocks(
186
230
  }
187
231
 
188
232
  /**
189
- * Build the prompt that (re)creates a session: earlier history as transcript,
190
- * then the trailing input messages as live content.
233
+ * Build the prompt that (re)creates a session: harness system/tool instructions,
234
+ * earlier history as transcript, and trailing input messages as live content.
191
235
  *
192
- * The trailing input is always complete. History renders newest-first into the
193
- * remaining byte budget, so the most recent turns survive and only the oldest
194
- * messages are omitted; an omitted prefix is announced inside the block. The
195
- * `<pi_history>` block is always closed before the live input. When the plan
196
- * leaves no trailing input (the history ends with tool results), a short
197
- * continuation instruction is appended so the prompt is never empty.
236
+ * The trailing input and session instructions are always complete. History
237
+ * renders newest-first into the remaining byte budget, so the most recent turns
238
+ * survive and only the oldest messages are omitted; an omitted prefix is
239
+ * announced inside the block. The `<pi_history>` block is always closed before
240
+ * the live input. When the plan leaves no trailing input (the history ends with
241
+ * tool results), a short continuation instruction is appended so the prompt is
242
+ * never empty.
198
243
  * @param history - messages before the trailing input.
199
244
  * @param input - trailing input messages sent as live content.
200
- * @param maxHistoryBytes - combined history and input byte ceiling; defaults to {@link REPLAY_BUDGET_BYTES}.
245
+ * @param options - session instructions and replay byte ceiling; defaults to {@link REPLAY_BUDGET_BYTES}.
201
246
  * @returns prompt blocks.
202
247
  */
203
248
  export function replayPrompt(
204
249
  history: readonly RequestMessage[],
205
250
  input: readonly RequestMessage[],
206
- maxHistoryBytes?: number,
251
+ options: ReplayPromptOptions = {},
207
252
  ): AcpPromptBlock[] {
253
+ const preamble = renderSessionInstructions(
254
+ options.system ?? '',
255
+ options.supplementalTools ?? [],
256
+ )
208
257
  const inputBlocks: AcpPromptBlock[] =
209
258
  input.length > 0
210
259
  ? inputPrompt(input)
211
260
  : [{ type: 'text', text: EMPTY_INPUT_CONTINUATION }]
212
261
  const blocks: AcpPromptBlock[] = []
262
+ if (preamble.length > 0) blocks.push({ type: 'text', text: preamble })
213
263
  if (history.length > 0) {
214
- const maxBytes = maxHistoryBytes ?? REPLAY_BUDGET_BYTES
264
+ const maxBytes = options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES
265
+ const preambleBytes = utf8Bytes(preamble)
215
266
  const inputBytes = inputBlocks.reduce(
216
267
  (total, block) =>
217
268
  total + (block.type === 'text' ? utf8Bytes(block.text) : 0),
@@ -223,7 +274,7 @@ export function replayPrompt(
223
274
  OMISSION_NOTICE_RESERVE_BYTES
224
275
  const text = historyTranscript(
225
276
  history,
226
- Math.max(0, maxBytes - inputBytes - overhead),
277
+ Math.max(0, maxBytes - preambleBytes - inputBytes - overhead),
227
278
  )
228
279
  if (text.length > 0) blocks.push({ type: 'text', text })
229
280
  }
package/src/jsonrpc.ts CHANGED
@@ -232,6 +232,22 @@ export class JsonRpcPeer {
232
232
  if (pending === undefined) return
233
233
  this.pending.delete(id)
234
234
  if (message.error !== undefined) {
235
+ if (
236
+ message.error === null ||
237
+ typeof message.error !== 'object' ||
238
+ Array.isArray(message.error)
239
+ ) {
240
+ this.handlers.onProtocolError?.(
241
+ `invalid error response for id ${id}: ${line.slice(0, 200)}`,
242
+ )
243
+ pending.reject(
244
+ new JsonRpcRemoteError(pending.method, {
245
+ code: -32603,
246
+ message: 'invalid error response',
247
+ }),
248
+ )
249
+ return
250
+ }
235
251
  const rpc = message.error as JsonRpcErrorObject
236
252
  pending.reject(
237
253
  new JsonRpcRemoteError(pending.method, {