pi-agy-acp 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/format.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { QuotaDisplay } from './config.ts'
1
+ import { asEffort, type Effort, type QuotaDisplay } from './config.ts'
2
2
  import type {
3
3
  AccountInfo,
4
4
  QuotaSnapshot,
@@ -22,21 +22,319 @@ function formatAccount(account?: AccountInfo): string {
22
22
  return [account?.email, account?.plan].filter(Boolean).join(' · ')
23
23
  }
24
24
 
25
- /** 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. */
26
332
  export function quotaForModel(
27
333
  snapshot: QuotaSnapshot,
28
- model?: string,
334
+ model?: QuotaModelRef,
29
335
  ): { group: QuotaGroup; bucket: QuotaBucket; fraction: number } | undefined {
30
336
  if (snapshot.status !== 'ok') return undefined
31
- const family = /^(gemini|claude|gpt)(?:-|$)/i.exec(model ?? '')?.[1]
32
- const matched = family
33
- ? snapshot.groups.filter((group) =>
34
- new RegExp(`\\b${family}\\b`, 'i').test(
35
- `${group.name} ${group.description}`,
36
- ),
37
- )
38
- : []
39
- const groups = matched.length > 0 ? matched : snapshot.groups
337
+ const groups = selectQuotaGroups(snapshot, model)
40
338
  let lowest: ReturnType<typeof quotaForModel>
41
339
  for (const group of groups) {
42
340
  for (const bucket of group.buckets) {
@@ -59,7 +357,7 @@ export function displayFraction(
59
357
 
60
358
  export function formatQuotaStatus(
61
359
  snapshot: QuotaSnapshot,
62
- model?: string,
360
+ model?: QuotaModelRef,
63
361
  display: QuotaDisplay = 'used',
64
362
  ): string | undefined {
65
363
  const quota = quotaForModel(snapshot, model)
@@ -97,10 +395,11 @@ export function formatQuota(
97
395
  }
98
396
  for (const group of snapshot.groups) {
99
397
  lines.push('', ` ${group.name || 'Unnamed model group'}`)
100
- if (group.description) {
101
- lines.push(
102
- ` ${group.description.replace(/^Models within this group:\s*/i, '')}`,
103
- )
398
+ const description = group.description
399
+ .replace(EXPLICIT_MEMBERS_PREFIX, '')
400
+ .trim()
401
+ if (description) {
402
+ lines.push(` ${description}`)
104
403
  }
105
404
  if (group.buckets.length === 0)
106
405
  lines.push(' No quota windows available.')
@@ -148,7 +447,7 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
148
447
  ` Home: ${status.home}`,
149
448
  ...(account ? [` Account: ${account}`] : []),
150
449
  ` Sessions: ${status.liveSessions} live · ${status.activeTurns} active turn(s)`,
151
- ` Context: ${Math.round(status.contextWindow / 1024)}K tokens · default effort: ${status.defaultEffort} (${status.efforts.join(', ')})`,
450
+ ` Context: ${status.contextWindow ? `${Math.round(status.contextWindow / 1024)}K tokens` : 'dynamic (unprobed)'} · default effort: ${status.defaultEffort} (${status.efforts.join(', ')})`,
152
451
  ' Models:',
153
452
  ]
154
453
  if (status.models.length === 0) lines.push(' No models available.')
@@ -159,7 +458,10 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
159
458
  : model.fixedEffort
160
459
  ? `[${model.fixedEffort}] (fixed)`
161
460
  : 'no effort selector'
162
- lines.push(` ${model.id} (${model.name}) — ${efforts}`)
461
+ const ctx = model.contextWindow
462
+ ? ` · ${Math.round(model.contextWindow / 1024)}K`
463
+ : ''
464
+ lines.push(` ${model.id} (${model.name}) — ${efforts}${ctx}`)
163
465
  }
164
466
  if (status.lastTurn) {
165
467
  const turn = status.lastTurn
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,27 +89,47 @@ 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.
107
+ * Static bridge instructions appended to the agent's system prompt.
108
+ * @returns the static bridge preamble.
109
+ */
110
+ export function bridgeSystemPrompt(): string {
111
+ return [
112
+ 'You are the primary model of a Pi coding agent session. The harness owns the conversation, the tools, and their permissions.',
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.',
115
+ ].join('\n')
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.
92
121
  * @param system - the Pi system prompt.
93
122
  * @param supplementalTools - initially advertised tools whose MCP schemas were compacted, preserving their full instructions.
94
- * @returns the complete appended system text.
123
+ * @returns the delimited instruction preamble ending in a blank line, or empty string when absent.
95
124
  */
96
- export function bridgeSystemPrompt(
125
+ export function renderSessionInstructions(
97
126
  system: string,
98
- supplementalTools: readonly {
99
- name: string
100
- description: string
101
- inputSchema: Record<string, unknown>
102
- }[] = [],
127
+ supplementalTools: readonly SupplementalTool[] = [],
103
128
  ): string {
104
- const sections = [
105
- [
106
- 'You are the primary model of a Pi coding agent session. The harness owns the conversation, the tools, and their permissions.',
107
- `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.`,
108
- '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.',
109
- ].join('\n'),
110
- ]
129
+ const sections: string[] = []
130
+ if (system.length > 0) {
131
+ sections.push(`<system_instructions>\n${system}\n</system_instructions>`)
132
+ }
111
133
  if (supplementalTools.length > 0) {
112
134
  const entries = supplementalTools.map((t) =>
113
135
  JSON.stringify({
@@ -120,8 +142,7 @@ export function bridgeSystemPrompt(
120
142
  `<harness_tool_instructions>\n${entries.join('\n')}\n</harness_tool_instructions>`,
121
143
  )
122
144
  }
123
- if (system.length > 0) sections.push(system)
124
- return sections.join('\n\n')
145
+ return sections.length > 0 ? `${sections.join('\n\n')}\n\n` : ''
125
146
  }
126
147
 
127
148
  /**
@@ -209,32 +230,39 @@ export function promptBlocks(
209
230
  }
210
231
 
211
232
  /**
212
- * Build the prompt that (re)creates a session: earlier history as transcript,
213
- * 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.
214
235
  *
215
- * The trailing input is always complete. History renders newest-first into the
216
- * remaining byte budget, so the most recent turns survive and only the oldest
217
- * messages are omitted; an omitted prefix is announced inside the block. The
218
- * `<pi_history>` block is always closed before the live input. When the plan
219
- * leaves no trailing input (the history ends with tool results), a short
220
- * 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.
221
243
  * @param history - messages before the trailing input.
222
244
  * @param input - trailing input messages sent as live content.
223
- * @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}.
224
246
  * @returns prompt blocks.
225
247
  */
226
248
  export function replayPrompt(
227
249
  history: readonly RequestMessage[],
228
250
  input: readonly RequestMessage[],
229
- maxHistoryBytes?: number,
251
+ options: ReplayPromptOptions = {},
230
252
  ): AcpPromptBlock[] {
253
+ const preamble = renderSessionInstructions(
254
+ options.system ?? '',
255
+ options.supplementalTools ?? [],
256
+ )
231
257
  const inputBlocks: AcpPromptBlock[] =
232
258
  input.length > 0
233
259
  ? inputPrompt(input)
234
260
  : [{ type: 'text', text: EMPTY_INPUT_CONTINUATION }]
235
261
  const blocks: AcpPromptBlock[] = []
262
+ if (preamble.length > 0) blocks.push({ type: 'text', text: preamble })
236
263
  if (history.length > 0) {
237
- const maxBytes = maxHistoryBytes ?? REPLAY_BUDGET_BYTES
264
+ const maxBytes = options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES
265
+ const preambleBytes = utf8Bytes(preamble)
238
266
  const inputBytes = inputBlocks.reduce(
239
267
  (total, block) =>
240
268
  total + (block.type === 'text' ? utf8Bytes(block.text) : 0),
@@ -246,7 +274,7 @@ export function replayPrompt(
246
274
  OMISSION_NOTICE_RESERVE_BYTES
247
275
  const text = historyTranscript(
248
276
  history,
249
- Math.max(0, maxBytes - inputBytes - overhead),
277
+ Math.max(0, maxBytes - preambleBytes - inputBytes - overhead),
250
278
  )
251
279
  if (text.length > 0) blocks.push({ type: 'text', text })
252
280
  }
package/src/mcp-bridge.ts CHANGED
@@ -356,6 +356,7 @@ export class McpBridge {
356
356
  this.openResponses.add(res)
357
357
  const controller = new AbortController()
358
358
  let settled = false
359
+ let keepAlive: ReturnType<typeof setInterval> | undefined
359
360
  const onClose = (): void => {
360
361
  this.openResponses.delete(res)
361
362
  clearInterval(keepAlive)
@@ -364,7 +365,7 @@ export class McpBridge {
364
365
  }
365
366
  res.on('close', onClose)
366
367
  let ticks = 0
367
- const keepAlive = setInterval(() => {
368
+ keepAlive = setInterval(() => {
368
369
  if (res.writableEnded || res.destroyed) return
369
370
  ticks++
370
371
  try {
@@ -553,7 +554,7 @@ function compactSchemaNode(value: unknown, maxDescChars: number): unknown {
553
554
  /**
554
555
  * Keep each MCP-advertised tool schema under `agy`'s eager size threshold while
555
556
  * preserving every parameter name, type, required list, and enum constraint.
556
- * Full prose instructions for compacted tools are appended to the session system prompt.
557
+ * Full prose instructions for compacted tools travel in the session's opening prompt.
557
558
  * @param tool - raw bridge tool descriptor.
558
559
  * @returns compacted descriptor when oversized, otherwise the original descriptor.
559
560
  */