pi-agy-acp 0.2.6 → 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`
@@ -30,10 +24,21 @@ export const CALL_TOOL_NAME = 'pi_call_tool'
30
24
  */
31
25
  export const REPLAY_BUDGET_BYTES = 160_000
32
26
 
27
+ /**
28
+ * Byte ceiling for one prelude prompt that carries session instructions
29
+ * ahead of the live turn, kept below `agy`'s 192,000-byte single-`USER_INPUT`
30
+ * truncation limit with room for the acknowledgement line.
31
+ */
32
+ export const PRELUDE_CHUNK_BYTES = 184_000
33
+
33
34
  const HISTORY_OPEN = '<pi_history>\n'
34
35
  const HISTORY_CLOSE = '\n</pi_history>\n\n'
35
36
  /** Upper bound of the omission notice, reserved before history is selected. */
36
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
37
42
 
38
43
  /**
39
44
  * Live input for a rebuild whose trailing messages are all tool results (for
@@ -111,7 +116,7 @@ export function bridgeSystemPrompt(): string {
111
116
  return [
112
117
  'You are the primary model of a Pi coding agent session. The harness owns the conversation, the tools, and their permissions.',
113
118
  `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.',
119
+ 'When the opening user messages contain <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. Large instructions may arrive split across several opening messages marked as harness instruction parts; answer each of those with only OK.',
115
120
  ].join('\n')
116
121
  }
117
122
 
@@ -226,6 +231,33 @@ function promptBlocks(
226
231
  return blocks
227
232
  }
228
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
+
229
261
  /**
230
262
  * Build the prompt that (re)creates a session: harness system/tool instructions,
231
263
  * earlier history as transcript, and trailing input messages as live content.
@@ -251,32 +283,109 @@ export function replayPrompt(
251
283
  options.system ?? '',
252
284
  options.supplementalTools ?? [],
253
285
  )
254
- const inputBlocks: AcpPromptBlock[] =
255
- input.length > 0
256
- ? inputPrompt(input)
257
- : [{ type: 'text', text: EMPTY_INPUT_CONTINUATION }]
258
- const blocks: AcpPromptBlock[] = []
259
- if (preamble.length > 0) blocks.push({ type: 'text', text: preamble })
260
- if (history.length > 0) {
261
- const maxBytes = options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES
262
- const preambleBytes = utf8Bytes(preamble)
263
- const inputBytes = inputBlocks.reduce(
264
- (total, block) =>
265
- total + (block.type === 'text' ? utf8Bytes(block.text) : 0),
266
- 0,
267
- )
268
- const overhead =
269
- utf8Bytes(HISTORY_OPEN) +
270
- utf8Bytes(HISTORY_CLOSE) +
271
- OMISSION_NOTICE_RESERVE_BYTES
272
- const text = historyTranscript(
273
- history,
274
- Math.max(0, maxBytes - preambleBytes - inputBytes - overhead),
275
- )
276
- if (text.length > 0) blocks.push({ type: 'text', text })
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
+ )
295
+ }
296
+
297
+ /**
298
+ * Plan the prompts that (re)create a session. While the session instructions
299
+ * and live input fit in one prompt without starving history or exceeding
300
+ * `agy`'s single-input truncation limit, this returns the single
301
+ * {@link replayPrompt}. Otherwise the instructions go first as one or more
302
+ * prelude prompts (each <= {@link PRELUDE_CHUNK_BYTES} plus a short
303
+ * acknowledgement footer) and the final prompt carries `<pi_history>` and the
304
+ * live input with the full replay budget.
305
+ * @param history - messages before the trailing input.
306
+ * @param input - trailing input messages sent as live content.
307
+ * @param options - session instructions and replay byte ceiling.
308
+ * @returns prompts in send order; only the last one is the live turn.
309
+ */
310
+ export function openingPrompts(
311
+ history: readonly RequestMessage[],
312
+ input: readonly RequestMessage[],
313
+ options: ReplayPromptOptions = {},
314
+ ): AcpPromptBlock[][] {
315
+ const preamble = renderSessionInstructions(
316
+ options.system ?? '',
317
+ options.supplementalTools ?? [],
318
+ )
319
+ const maxBytes = options.maxHistoryBytes ?? REPLAY_BUDGET_BYTES
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
324
+ // Without history, avoid an extra prelude LLM round-trip while preamble + input still fit under agy's 192 KB cap.
325
+ const singlePromptLimit =
326
+ history.length > 0 || options.maxHistoryBytes !== undefined
327
+ ? maxBytes
328
+ : Math.max(maxBytes, PRELUDE_CHUNK_BYTES)
329
+ if (
330
+ preamble.length === 0 ||
331
+ preambleBytes + inputBytes + historyOverhead <= singlePromptLimit
332
+ ) {
333
+ return [
334
+ buildReplayPrompt(
335
+ history,
336
+ preamble,
337
+ preambleBytes,
338
+ inputBlocks,
339
+ inputBytes,
340
+ maxBytes,
341
+ ),
342
+ ]
277
343
  }
278
- blocks.push(...inputBlocks)
279
- return blocks
344
+ const parts = splitWithinBytes(preamble, PRELUDE_CHUNK_BYTES)
345
+ const preludes = parts.map((text, index) => [
346
+ {
347
+ type: 'text' as const,
348
+ text: `${text}${preludeAck(index + 1, parts.length)}`,
349
+ },
350
+ ])
351
+ return [
352
+ ...preludes,
353
+ buildReplayPrompt(history, '', 0, inputBlocks, inputBytes, maxBytes),
354
+ ]
355
+ }
356
+
357
+ function preludeAck(part: number, total: number): string {
358
+ const next =
359
+ part < total
360
+ ? 'More harness instructions follow.'
361
+ : 'The conversation history and the newest input arrive in the next message.'
362
+ return `\n[Harness instructions part ${part} of ${total}. ${next} Reply with only OK and do not call any tools.]`
363
+ }
364
+
365
+ function textBytes(blocks: readonly AcpPromptBlock[]): number {
366
+ return blocks.reduce(
367
+ (total, block) =>
368
+ total + (block.type === 'text' ? utf8Bytes(block.text) : 0),
369
+ 0,
370
+ )
371
+ }
372
+
373
+ /**
374
+ * Split text into chunks of at most `maxBytes`, breaking after a newline when
375
+ * one falls in the second half of a chunk.
376
+ */
377
+ function splitWithinBytes(text: string, maxBytes: number): string[] {
378
+ const chunks: string[] = []
379
+ let rest = text
380
+ while (utf8Bytes(rest) > maxBytes) {
381
+ let head = headWithinBytes(rest, maxBytes)
382
+ const newline = head.lastIndexOf('\n')
383
+ if (newline > head.length / 2) head = head.slice(0, newline + 1)
384
+ chunks.push(head)
385
+ rest = rest.slice(head.length)
386
+ }
387
+ if (rest.length > 0) chunks.push(rest)
388
+ return chunks
280
389
  }
281
390
 
282
391
  /**
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) => {