@linxiraos/pi-agent-core 1.0.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +1263 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +137 -0
  4. package/dist/types/agent.d.ts +465 -0
  5. package/dist/types/append-only-context.d.ts +131 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +101 -0
  7. package/dist/types/compaction/compaction-v2-streaming.d.ts +85 -0
  8. package/dist/types/compaction/compaction.d.ts +307 -0
  9. package/dist/types/compaction/entries.d.ts +111 -0
  10. package/dist/types/compaction/errors.d.ts +38 -0
  11. package/dist/types/compaction/index.d.ts +13 -0
  12. package/dist/types/compaction/message-cache.d.ts +23 -0
  13. package/dist/types/compaction/messages.d.ts +79 -0
  14. package/dist/types/compaction/openai.d.ts +117 -0
  15. package/dist/types/compaction/pruning.d.ts +105 -0
  16. package/dist/types/compaction/shake.d.ts +97 -0
  17. package/dist/types/compaction/tool-protection.d.ts +19 -0
  18. package/dist/types/compaction/utils.d.ts +61 -0
  19. package/dist/types/compaction.d.ts +1 -0
  20. package/dist/types/index.d.ts +13 -0
  21. package/dist/types/pause.d.ts +46 -0
  22. package/dist/types/proxy.d.ts +91 -0
  23. package/dist/types/replay-policy.d.ts +5 -0
  24. package/dist/types/run-collector.d.ts +196 -0
  25. package/dist/types/telemetry.d.ts +608 -0
  26. package/dist/types/thinking.d.ts +18 -0
  27. package/dist/types/tokenizer.d.ts +2 -0
  28. package/dist/types/types.d.ts +781 -0
  29. package/dist/types/utils/yield.d.ts +71 -0
  30. package/package.json +79 -0
  31. package/src/agent-loop.ts +2926 -0
  32. package/src/agent.ts +1748 -0
  33. package/src/append-only-context.ts +348 -0
  34. package/src/compaction/branch-summarization.ts +369 -0
  35. package/src/compaction/compaction-v2-streaming.ts +846 -0
  36. package/src/compaction/compaction.ts +1733 -0
  37. package/src/compaction/entries.ts +141 -0
  38. package/src/compaction/errors.ts +47 -0
  39. package/src/compaction/index.ts +14 -0
  40. package/src/compaction/message-cache.ts +92 -0
  41. package/src/compaction/messages.ts +241 -0
  42. package/src/compaction/openai.ts +992 -0
  43. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  44. package/src/compaction/prompts/branch-summary-context.md +5 -0
  45. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  46. package/src/compaction/prompts/branch-summary.md +30 -0
  47. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  48. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  49. package/src/compaction/prompts/compaction-summary.md +38 -0
  50. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  51. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  52. package/src/compaction/prompts/context-window-truncated-output.md +1 -0
  53. package/src/compaction/prompts/file-operations.md +5 -0
  54. package/src/compaction/prompts/handoff-document.md +49 -0
  55. package/src/compaction/prompts/snapcompact-archive-context.md +3 -0
  56. package/src/compaction/prompts/summarization-system.md +3 -0
  57. package/src/compaction/pruning.ts +427 -0
  58. package/src/compaction/shake.ts +446 -0
  59. package/src/compaction/tool-protection.ts +65 -0
  60. package/src/compaction/utils.ts +343 -0
  61. package/src/compaction.ts +1 -0
  62. package/src/index.ts +26 -0
  63. package/src/pause.ts +107 -0
  64. package/src/proxy.ts +391 -0
  65. package/src/replay-policy.ts +13 -0
  66. package/src/run-collector.ts +631 -0
  67. package/src/telemetry.ts +2078 -0
  68. package/src/thinking.ts +20 -0
  69. package/src/tokenizer.ts +27 -0
  70. package/src/types.ts +875 -0
  71. package/src/utils/yield.ts +183 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,1263 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ### Changed
6
+
7
+ - Reset the version to 1.0.0 and republished under the `@linxiraos/*` scope, breaking from the `@oh-my-pi` version lineage.
8
+ ## [17.2.10] - 2026-08-06
9
+
10
+ ### Fixed
11
+
12
+ - Fixed an issue in remote OpenAI response compaction replay where output-only `status` fields were incorrectly sent back as input, affecting persisted native and V1/V2 replacement history.
13
+
14
+ ## [17.2.9] - 2026-08-05
15
+
16
+ ### Fixed
17
+
18
+ - Preserved queued steering and follow-up messages when a continuation is cancelled before or during pre-dequeue hooks, and propagated the caller's cancellation signal through every continuation model-call loop.
19
+
20
+ ## [17.2.6] - 2026-08-03
21
+
22
+ ### Fixed
23
+
24
+ - Fixed an issue where peer-IRC interrupts (such as subagent messages) incorrectly skipped non-interruptible tool calls queued in the same batch.
25
+ - Improved interruption messaging to clearly distinguish between parent-agent steering and system-advisory interruptions.
26
+
27
+ ## [17.2.5] - 2026-08-03
28
+
29
+ ### Breaking Changes
30
+
31
+ - Tool examples embedded in tool descriptions now always render in Python call syntax, and the `exampleDialect` option has been removed from `AppendOnlyContextManager` build options.
32
+ - Updated `normalizeTools` to accept a `NormalizeToolsOptions` configuration object (`{ injectIntent, pruneDescriptions }`) instead of positional booleans.
33
+
34
+ ### Fixed
35
+
36
+ - Fixed an issue where runs would fail with an error if an Anthropic stream was truncated after complete tool calls were streamed; the agent now recovers and executes those tool calls.
37
+ - Fixed an issue where artifact recovery reads could be incorrectly elided during compaction.
38
+
39
+ ## [17.2.4] - 2026-08-01
40
+
41
+ ### Fixed
42
+
43
+ - Fixed Codex V2 remote compaction bypassing the provider's live WebSocket transport before trying SSE ([#7198](https://github.com/can1357/oh-my-pi/issues/7198)).
44
+ - Tool calls skipped mid-batch to service queued steering/peer input now distinguish calls that never entered `tool.execute` (`SyntheticToolResultDetails`, `executed: false`) from in-flight calls that may have performed partial work (`execution: "started"`), allowing UI/telemetry consumers to render normal steering control flow without misreporting execution state ([#7199](https://github.com/can1357/oh-my-pi/issues/7199)).
45
+
46
+ ## [17.2.2] - 2026-07-31
47
+
48
+ ### Fixed
49
+
50
+ - Fixed an issue where response-only usage records were incorrectly treated as authoritative context anchors, while ensuring prompt and total-only provider telemetry remains preserved.
51
+ - Fixed context compaction summaries growing excessively with large context windows by capping the summary output budget to 16,384 tokens, ensuring conversations are properly compressed rather than duplicated.
52
+
53
+ ## [17.2.0] - 2026-07-30
54
+
55
+ ### Fixed
56
+
57
+ - Provider-native compaction failures now surface their transport error instead of silently switching to generic summarization; streaming V2 still falls back to native V1 when available.
58
+
59
+ ## [17.1.7] - 2026-07-27
60
+
61
+ ### Changed
62
+
63
+ - `beforeToolCall` now runs during arg-prep in a pre-dispatch prepare phase — on the streamed path before the assistant message's `message_start`/`message_end` are emitted, and always ahead of concurrency resolution, `tool_execution_start`, telemetry span start, and `tool.execute` — instead of inside the already-scheduled execution slot. It receives the resolved `tool` in its context and may return `args` to replace the call's arguments; a replacement is revalidated against the tool schema, written back to the assistant message's tool-call block, and re-resolves argument-dependent interruptibility, making it the single source of truth for history, persistence, provider replay, scheduling, execution events, and `tool.execute`. Argument validation moved into the same prepare phase, so functional `concurrency` resolvers now see validated (and possibly revised) arguments rather than raw pre-validation ones. The hook now receives the run's request abort signal rather than the per-tool signal.
64
+
65
+ ## [17.1.6] - 2026-07-27
66
+
67
+ ### Added
68
+
69
+ - Added a pre-model-call gate: `AgentLoopConfig.beforeModelCall` receives the finalized provider context and run abort signal, and may return `{ stop: true, reason? }` to end the run before the provider is called, so a host can refuse a request it has decided not to pay for (prompt no longer fits, budget boundary crossed, session should hand off). `Agent.setBeforeModelCall` installs the host callback; `Agent.addBeforeModelCall` registers an additional one without displacing it and returns a disposer. A gate-stopped run retains pending soft tool reminders/escalations and an unserved hard tool choice for the next admitted request; deferred choices are revalidated against active tools and cleared with queued session state ([#6543](https://github.com/can1357/oh-my-pi/pull/6543) by [@paralin](https://github.com/paralin)).
70
+
71
+ ### Changed
72
+
73
+ - Input message events (prompt, steering, soft reminders) are now emitted once provider-context preparation succeeds, so a pre-model gate can veto the request before any turn opens; gate-stopped and failed runs still commit their accepted inputs ([#6543](https://github.com/can1357/oh-my-pi/pull/6543) by [@paralin](https://github.com/paralin)).
74
+
75
+ ## [17.1.5] - 2026-07-27
76
+
77
+ ### Fixed
78
+
79
+ - Fixed proxy-stream clients dropping finalized provider-only content blocks, including Anthropic native web-search history, by allowing `done` and `error` events to carry terminal assistant content while retaining delta-reconstructed content from older proxy servers that omit it ([#6703](https://github.com/can1357/oh-my-pi/issues/6703)).
80
+
81
+ ## [17.1.4] - 2026-07-26
82
+
83
+ ### Changed
84
+
85
+ - Steering is now woken by an event instead of polled on a fixed interval while a tool batch runs. `AgentLoopConfig.waitForSteeringMessages` resolves when a steer is enqueued, so an interruption is observed as soon as it arrives rather than at the next tick, and idle batches stop burning wakeups. The interval timer remains for the IRC interrupt queue, which has no wake callback, and checks only IRC while the event watcher owns steering. Waits are raced against local abort, so a callback that does not observe its signal cannot hang batch teardown.
86
+
87
+ ### Fixed
88
+
89
+ - Fixed a Cursor tool result being lost when a custom `cursorOnToolResult` transformer was still pending as the turn closed. The provider dispatches decoded messages without awaiting them, so a `message_end` from the same chunk could drain the buffer before the transformer resolved, dropping the result and leaving its `toolCall` block to be stripped as dangling on replay. The entry is now reserved synchronously and patched in place once the transformer resolves, preserving buffer order.
90
+ - Fixed an async `cursorOnToolResult` transformer's rewrite being silently discarded when it resolved after the buffer drain. The reservation kept the call from dangling but the late patch mutated a detached entry, so the already-persisted message kept the pre-transform payload. The drain now awaits any transformer still in flight before persisting, matching the awaited exec-channel paths. A rejecting transformer is swallowed and the reserved payload stands in, so a failing hook cannot take the turn down or cost the result.
91
+ - Fixed Cursor tool results being dropped for hosts that pass neither `cursorExecHandlers` nor `cursorOnToolResult`. Both are optional, but the Cursor provider resolves native todo calls server-side and synthesizes exec blocks regardless, marking both as resolved so no placeholder result is emitted for them. The result buffer callback was only installed when one of the options was present, so a bare SDK host discarded the provider's paired result and every rebuilt transcript stripped the interaction. It is now installed unconditionally.
92
+ - Fixed an async `cursorOnToolResult` rewrite being lost when the provider errored mid-transform. The normal drain waits for a pending transformer, but the error path snapshotted the buffer without that await, so a transform still in flight patched an entry the catch path had already detached and the pre-transform payload was persisted. A provider error is exactly when a transform is most likely to be mid-flight.
93
+ - Reduced oversized OpenAI native compaction requests by replacing only trailing tool-output bodies that exceed the model context window, while preserving calls, assistant history, and reasoning.
94
+
95
+ ## [17.1.2] - 2026-07-24
96
+
97
+ ### Added
98
+
99
+ - Added `resolveFallbackTool` option to allow routing unadvertised tool calls to host-side transports (e.g., device mounts)
100
+
101
+ ## [17.1.1] - 2026-07-24
102
+
103
+ ### Added
104
+
105
+ - Added the provider-neutral native computer-call lifecycle, preserving observation outputs and input actions across pending and acknowledged tool results.
106
+
107
+ ### Changed
108
+
109
+ - Queued steering no longer hard-aborts non-interruptible tools (e.g. `bash`): it aborts interruptible waits only and raises a cooperative steering signal (`ToolCallContext.steeringSignal`) that long-running tools may observe to finish early or background themselves. The mid-batch steering/IRC watch now runs for every tool batch instead of only batches containing an interruptible tool.
110
+
111
+ ## [17.1.0] - 2026-07-24
112
+
113
+ ### Added
114
+
115
+ - Added support for tracking Cloudflare AI Gateway cache status (hit, miss, bypass, unknown) on chat spans.
116
+
117
+ ### Changed
118
+
119
+ - Improved tool execution steering behavior: queued steering now cooperatively signals long-running, non-interruptible tools (via ToolCallContext.steeringSignal) to allow graceful early termination or backgrounding, rather than hard-aborting them.
120
+
121
+ ### Fixed
122
+
123
+ - Fixed an out-of-memory (OOM) crash caused by an infinite loop when a steer or follow-up message was queued on an agent session with an empty transcript.
124
+ - Fixed an issue where switching providers or models on a session could lose compacted history; the agent now correctly falls back to a portable local summary if the new model cannot replay the prior provider's remote-compaction payload.
125
+ - Fixed a compaction failure with Anthropic models where serializing prior assistant reasoning inside <thinking> tags triggered reasoning_extraction refusals.
126
+
127
+ ## [17.0.8] - 2026-07-22
128
+
129
+ ### Fixed
130
+
131
+ - Improved resilience against transient stream JSON parse failures by recovering completed tool calls while safely preventing incomplete, unknown, refused, or sensitive calls from executing.
132
+
133
+ ## [17.0.5] - 2026-07-18
134
+
135
+ ### Added
136
+
137
+ - Added a per-message token estimation cache to optimize performance by reusing token counts for settled message history, with automatic cache invalidation on message mutation.
138
+
139
+ ### Changed
140
+
141
+ - Improved tool execution control by making tool interruptibility resolvable per call, allowing side-effecting operations to complete while passive waits can yield to queued steering.
142
+
143
+ ## [17.0.2] - 2026-07-17
144
+
145
+ ### Fixed
146
+
147
+ - Improved error visibility in interactive clients by surfacing provider stream failures through the assistant message lifecycle, preventing silent loading spinners.
148
+ - Fixed an issue where Cursor provider contexts omitted host-supplied MCP tools from main and side-channel requests.
149
+
150
+ ## [17.0.0] - 2026-07-15
151
+
152
+ ### Breaking Changes
153
+
154
+ - Replaced the irc, job, and launch tools with a unified hub tool.
155
+ - Removed the tool discovery system (including the search-tool-bm25 tool) and its associated configuration settings (tools.discoveryMode, tools.essentialOverride, mcp.discoveryMode, and mcp.discoveryDefaultServers).
156
+ - Removed the resolve tool; plan approval and preview actions now use writes to the xd://propose virtual device path.
157
+
158
+ ### Added
159
+
160
+ - Introduced the xd:// virtual device protocol for mounting tools as URLs readable/writable via read/write tools, configurable via the new tools.xdev setting (defaults to true).
161
+ - Added the hub tool, consolidating agent peer messaging, background job control, and supervised long-running processes.
162
+ - Added the edit.enforceSeenLines configuration setting (defaults to false) to optionally reject edits on lines that have not been fully displayed.
163
+ - Added the ToolLoadMode type and an optional satisfies predicate to SoftToolRequirement to support compliance checks against specific invocation shapes (such as writing to a virtual device path).
164
+
165
+ ## [16.5.2] - 2026-07-14
166
+
167
+ ### Fixed
168
+
169
+ - Improved session deadline abort signals to carry structured cancellation reasons, enabling timeout-aware tools to correctly classify deadline cancellations.
170
+ - Fixed an issue where completed tool executions were incorrectly marked as skipped (clobbering their actual results) if a user message was queued while the tool was in flight.
171
+
172
+ ## [16.5.1] - 2026-07-14
173
+
174
+ ### Fixed
175
+
176
+ - Fixed compatibility with Copilot gpt-5.6 models by correcting token escaping in compaction summaries.
177
+
178
+ ## [16.5.0] - 2026-07-13
179
+
180
+ ### Added
181
+
182
+ - Added an automated image-dropping rescue tier to compaction dead-end recovery.
183
+ - Added visual warnings and detailed recovery instructions to the session timeline when compaction fails to free sufficient space.
184
+
185
+ ## [16.4.5] - 2026-07-11
186
+
187
+ ### Added
188
+
189
+ - Added a process-global pause gate (`agentPauseGate`) to safely pause agent loops before model calls or tool executions, allowing them to be resumed later or aborted cleanly.
190
+
191
+ ## [16.4.3] - 2026-07-11
192
+
193
+ ### Fixed
194
+
195
+ - Fixed an issue where skipped sibling tool results incorrectly reported that a queued user message caused the skip.
196
+
197
+ ## [16.4.2] - 2026-07-10
198
+
199
+ ### Fixed
200
+
201
+ - Fixed serialization of BigInt tool arguments to prevent data loss during remote compaction.
202
+
203
+ ## [16.4.1] - 2026-07-10
204
+
205
+ ### Fixed
206
+
207
+ - Enabled reasoning encryption content for all Responses Lite compaction requests
208
+
209
+ ## [16.4.0] - 2026-07-10
210
+
211
+ ### Added
212
+
213
+ - Added the `ThinkingLevel.Max` ("max") configuration option, mapping to the `Effort.Max` tier for supported models.
214
+
215
+ ### Fixed
216
+
217
+ - Fixed remote compaction behavior for Codex Responses Lite (GPT-5.6 family) models across both V1 and V2 endpoints to ensure correct formatting and routing.
218
+ - Fixed an issue where aborted tool-result hooks could trigger subsequent provider calls before the abort signal fully settled.
219
+
220
+ ## [16.3.12] - 2026-07-08
221
+
222
+ ### Added
223
+
224
+ - Added per-tool abort metadata so stream-wide aborts can label matching tool-call placeholders separately from unaffected sibling calls ([#2783](https://github.com/can1357/oh-my-pi/issues/2783)).
225
+
226
+ ### Fixed
227
+
228
+ - Fixed handoff generation retrying with `toolChoice: "auto"` when custom OpenAI-compatible providers reject `toolChoice: "none"` with an auto-only 400. ([#4715](https://github.com/can1357/oh-my-pi/issues/4715))
229
+ - Fixed generic remote compaction against OpenAI-compatible `/chat/completions` endpoints (for example llama.cpp `openai-completions`) by sending chat messages instead of the custom `{ systemPrompt, prompt }` summarizer payload. ([#4630](https://github.com/can1357/oh-my-pi/issues/4630))
230
+
231
+ ## [16.3.7] - 2026-07-05
232
+
233
+ ### Fixed
234
+
235
+ - Fixed an issue where provider orchestration tokens were incorrectly included in context token calculations, which could trigger premature context auto-compaction and promotion.
236
+
237
+ ## [16.3.3] - 2026-07-02
238
+
239
+ ### Changed
240
+
241
+ - Enabled dynamic model resolution to support seamless mid-run model switching.
242
+
243
+ ### Fixed
244
+
245
+ - Fixed an issue in the Cursor agent where assistant messages containing native tool calls could duplicate text blocks on replay.
246
+ - Fixed a bug where Cursor agent exec-channel tools (such as bash, write, and delete) were executed a second time after server-side execution.
247
+ - Improved error handling for tool calls interrupted by upstream provider stream errors, distinguishing transport/provider failures from local tool execution failures in the CLI, events, and messages.
248
+
249
+ ## [16.3.0] - 2026-07-02
250
+
251
+ ### Added
252
+
253
+ - Added support for Anthropic fallback content blocks in agent-loop assistant messages, ensuring they are preserved across session persistence and event fanout.
254
+
255
+ ### Fixed
256
+
257
+ - Fixed an issue where legacy steering messages were prematurely consumed and dropped during in-flight tool execution polls.
258
+ - Fixed an issue where skipped tool results in queued messages were incorrectly treated as completed, preventing necessary retries.
259
+ - Improved branch summaries to preserve informative tool results from abandoned branches while filtering out redundant output.
260
+ - Fixed interruptible tool waits to properly abort on host-provided IRC interrupts in addition to user steering.
261
+ - Fixed schema validation errors for closed union tools by correctly injecting intent tracing into each variant.
262
+ - Fixed token compaction reserve-budget logic to honor explicit reserveTokens values equal to the built-in default, and clamped the fallback reserve to at least one token for very small context windows.
263
+
264
+ ## [16.2.4] - 2026-06-28
265
+
266
+ ### Changed
267
+
268
+ - Improved the reliability of remote compaction by introducing transient error retries, configurable timeouts, and immediate termination upon user-initiated aborts.
269
+
270
+ ### Fixed
271
+
272
+ - Fixed an issue where assistant responses and encrypted reasoning could be lost during local history trimming prior to remote compaction.
273
+ - Fixed type compatibility for hosts with title audit entries by adding support for `title_change` session metadata.
274
+ - Fixed an issue where transient stream read failures after a completed tool call were treated as terminal errors, allowing the agent to successfully execute the tool and continue the turn.
275
+
276
+ ## [16.2.3] - 2026-06-28
277
+
278
+ ### Changed
279
+
280
+ - Enabled V2 streaming remote compaction by default for compatible AI and OpenAI-compatible models, which forwards full conversation history to the provider and supports session routing, prompt caching, provider-native tool history replay, transient error retries, and configurable timeouts.
281
+
282
+ ### Fixed
283
+
284
+ - Fixed an issue where assistant responses and encrypted reasoning could be lost during local history trimming.
285
+ - Added `title_change` session metadata to the compaction entry type union to maintain type compatibility for hosts with title audit entries.
286
+
287
+ ## [16.2.2] - 2026-06-27
288
+
289
+ ### Added
290
+
291
+ - Added optional AgentTool.matcherPaths(args) and AgentTool.matcherEntries(args) hooks to allow tools to surface target file paths and isolate file evaluations for path-scoped stream matchers (e.g., when handling multi-file payloads or embedded paths in streamed arguments).
292
+
293
+ ### Removed
294
+
295
+ - Removed support for Pi dialect integration.
296
+
297
+ ## [16.2.0] - 2026-06-27
298
+
299
+ ### Added
300
+
301
+ - Added an optional `cwdResolver` to `Agent` and `getCwd` to `AgentLoopConfig` to dynamically resolve the working directory per LLM call, allowing workspace-scoped provider discovery (such as GitLab Duo Agent) to follow live directory changes without reconstructing the agent.
302
+
303
+ ### Fixed
304
+
305
+ - Fixed an issue where API-level provider refusals were replayed as assistant dialogue on subsequent requests, preventing repeated refusals after a single blocked turn.
306
+ - Fixed a bug where internal streaming state (`partialJson`) could leak onto the final `AssistantMessage` if a stream ended without a `toolcall_end` event.
307
+ - Fixed `Agent` to correctly forward the working directory (`cwd`) into provider stream options, enabling providers like GitLab Duo Agent to scope local tool execution to the workspace.
308
+ - Enabled custom OpenAI-compatible providers to use native remote compaction instead of falling back to local summarization.
309
+
310
+ ## [16.1.23] - 2026-06-26
311
+
312
+ ### Changed
313
+
314
+ - Changed `AgentLoopConfig.onTurnEnd` and `Agent.setOnTurnEnd` callbacks to receive whether the loop will continue with another provider request.
315
+
316
+ ### Fixed
317
+
318
+ - Fixed stale snapcompact archive frames leaking into context-full compaction after `compaction.strategy` was switched from `snapcompact` to `context-full`. Switching strategy left the latest compaction entry's `preserveData.snapcompact` in place, so context-full kept rebuilding context with old image frames attached — inflating context/token usage and making sessions appear to compact early (around ~60% apparent window use). The first context-full compaction after the switch now folds the prior archive's plaintext into the LLM summary input and strips `preserveData.snapcompact` from the new entry; legacy frame-only archives (no plaintext to migrate) are stripped outright. ([#3561](https://github.com/can1357/oh-my-pi/pull/3561) by [@serverinspector](https://github.com/serverinspector))
319
+
320
+ ## [16.1.18] - 2026-06-25
321
+
322
+ ### Fixed
323
+
324
+ - Fixed `AppendOnlyContextManager.syncMessages` clearing the entire log on any in-place rewrite of an already-synced message. Per-turn tool-output pruning, image stripping, or any `transformContext` re-render that touched a single message used to drop every prior turn out of the append-only log and re-send the conversation from scratch, forcing local backends (llama.cpp / Ollama / LM Studio) to re-prefill tens of thousands of tokens every few turns. `syncMessages` now finds the longest byte-stable prefix between the previously-synced messages and the new ones, truncates the log to that prefix, and only re-appends the diverged tail — so the provider's KV cache stays warm up to the divergence point. ([#3406](https://github.com/can1357/oh-my-pi/issues/3406))
325
+
326
+ ## [16.1.17] - 2026-06-24
327
+
328
+ ### Fixed
329
+
330
+ - Hardened the agent-loop cooperative yield against backward wall-clock jumps. A stale future timestamp left in the shared yield gate (NTP step, or a fake-timer test mocking `Date.now`) could make `yieldIfDue()` gate forever and stop yielding to the event loop; the gate now treats a backward clock delta as due and re-anchors. The gate is exposed as an injectable `YieldGate` (with `yieldIfDue()` retained as the shared singleton) so it can be exercised without mocking process-global timers.
331
+
332
+ ## [16.1.16] - 2026-06-23
333
+
334
+ ### Added
335
+
336
+ - Added `generateHandoffFromContext(context, model, options)` to `@oh-my-pi/pi-agent-core/compaction`: runs the handoff oneshot against a fully-built provider `Context` (system prompt, normalized tools, transformed history, trailing handoff prompt) with `streamOptions` mirroring the live turn's cache routing, so a host that owns the transform pipeline can make the handoff request share the prompt cache the main turn populated. `generateHandoff(messages, …)` is unchanged and now delegates to it.
337
+ - Added an optional `systemPrompt` argument to `Agent.buildSideRequestContext(llmMessages, systemPrompt?)`, defaulting to the live agent prompt; callers can pin a different prompt (e.g. handoff generation, which uses the base prompt rather than a per-turn `before_agent_start` hook override).
338
+
339
+ ### Changed
340
+
341
+ - Updated `buildSideRequestContext` to allow pinning custom system prompts
342
+
343
+ ## [16.1.10] - 2026-06-21
344
+
345
+ ### Fixed
346
+
347
+ - Fixed labeled user interrupts retaining incomplete streamed tool calls before `toolcall_end`, which could persist malformed tool-call IDs into replay.
348
+
349
+ ## [16.1.8] - 2026-06-20
350
+
351
+ ### Breaking Changes
352
+
353
+ - Changed `transformProviderContext` and `buildSideRequestContext` to return a Promise
354
+
355
+ ### Added
356
+
357
+ - Added `buildSideRequestContext` to the `Agent` class to build prompt-cache-friendly provider Contexts for side-channels or ephemeral requests.
358
+ - Added `compactionContextTokens(providerContextTokens, storedConversationEstimate)`: floors the provider-reported context tokens by a local estimate of the stored conversation for the compaction decision, so a `before_provider_request` payload transform (a compression extension, obfuscator, or inline snapcompact) that shrinks the request can no longer deflate provider usage below the true history size and suppress auto-compaction.
359
+
360
+ ### Changed
361
+
362
+ - Exported helper functions `normalizeMessagesForProvider` and `resolveOwnedDialectFromEnv` from `packages/agent/src/agent-loop.ts`.
363
+
364
+ ## [16.1.5] - 2026-06-19
365
+
366
+ ### Fixed
367
+
368
+ - Wire-encoded `normalizeTools` parameters unconditionally so tools whose `intent` resolves to `"omit"` (function intent or `intent: "omit"`, e.g. builtin `eval` / `resolve`) no longer leak raw arktype/zod schema objects in `parameters` ([#3074](https://github.com/can1357/oh-my-pi/issues/3074))
369
+
370
+ ## [16.1.2] - 2026-06-19
371
+
372
+ ### Fixed
373
+
374
+ - Prevented sensitive raw JSON payloads from leaking into agent events during tool validation
375
+ - Ensured tool validation errors are handled correctly for malformed JSON parse inputs
376
+ - Ensure deep-cloning of tool-call arguments respects own enumerable properties
377
+ - Prevent direct object references between agent message snapshots and streaming events
378
+
379
+ ## [16.1.0] - 2026-06-19
380
+
381
+ ### Added
382
+
383
+ - Added `SoftToolRequirement` support to `getToolChoice`: a host can require a tool by returning a soft requirement instead of a hard `ToolChoice`. The loop injects the supplied reminder once (leaving `tool_choice` on auto), and escalates to a one-turn forced choice — skipping any detour tool batch — only if the model fails to call the required tool, avoiding the provider message-cache invalidation of forcing every turn.
384
+ - Added `pruneToolDescriptions` option to reduce token usage by stripping tool descriptions from provider-bound specs
385
+
386
+ ### Fixed
387
+
388
+ - Improved token estimation accuracy for compaction summaries containing multi-block content
389
+
390
+ ## [16.0.11] - 2026-06-19
391
+
392
+ ### Changed
393
+
394
+ - Updated the display format for truncated file operation summaries
395
+
396
+ ## [16.0.8] - 2026-06-18
397
+
398
+ ### Fixed
399
+
400
+ - Stopped the compaction `<files>` summary from tracking `scheme://` URLs — internal URIs (`conflict://`, `artifact://`, `local://`, `history://`, …) and web URLs are no longer recorded as files, and legacy entries rehydrated from older compaction summaries are dropped.
401
+
402
+ ## [16.0.6] - 2026-06-18
403
+
404
+ ### Added
405
+
406
+ - Added `transformAssistantMessage` hook to `AgentOptions` and `Agent` to allow mutating the finalized assistant message before UI emission, context appending, or tool dispatch
407
+
408
+ ## [16.0.5] - 2026-06-17
409
+
410
+ ### Breaking Changes
411
+
412
+ - Changed `AgentOptions.getApiKey` and `AgentLoopConfig.getApiKey` to receive the active `Model` and return an API key or `ApiKeyResolver`, so credential routing stays model-scoped and retry context is no longer exposed through the agent-core API
413
+
414
+ ### Added
415
+
416
+ - Added agent-loop deadline support for graceful wall-clock session stops.
417
+
418
+ ### Changed
419
+
420
+ - Changed Gemini repetition-loop detection to live in the pi-ai stream layer instead of the agent loop. The agent no longer runs its own Gemini-gated verbatim repetition check (`detectRepetition`/`truncateRepetition`); loops now surface as a retryable transient stream error that the standard auto-retry path discards and re-samples, rather than a committed contentful error message.
421
+
422
+ ### Fixed
423
+
424
+ - Fixed `PI_DIALECT=minimax` being ignored by the owned tool-calling env selector. ([#2759](https://github.com/can1357/oh-my-pi/issues/2759))
425
+
426
+ ## [16.0.1] - 2026-06-15
427
+
428
+ ### Fixed
429
+
430
+ - Fixed transient provider errors after streamed tool-call arguments so incomplete tool calls are marked as interrupted output instead of eligible for automatic retry ([#2683](https://github.com/can1357/oh-my-pi/issues/2683)).
431
+ - Fixed `@oh-my-pi/pi-agent-core` telemetry content capture crashing every chat turn with `TypeError: systemPrompt.map is not a function` when `captureMessageContent` is enabled (`OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true`). `ChatRequestSnapshot.systemPrompt` now accepts `string | readonly string[]` and the telemetry serializers normalize a bare string to a single-element array — previously the full-system serializer called `.map` on a string (the `.length` guard passed, so it threw) and the request-message serializer iterated the string into one `system` message per character.
432
+
433
+ ## [16.0.0] - 2026-06-15
434
+
435
+ ### Breaking Changes
436
+
437
+ - Renamed owned tool-calling options from `toolCallSyntax`/`exampleSyntax` to `dialect`/`exampleDialect`.
438
+ - Changed compaction conversation serialization to use the target model's native dialect turn, thinking, tool-call, and tool-result envelopes when a dialect is selected.
439
+ - Renamed the owned dialect environment variable from `PI_OWNED_TOOLS` to `PI_DIALECT`.
440
+
441
+ ### Added
442
+
443
+ - Added `onTurnEnd` hook support (`setOnTurnEnd`/`onTurnEnd`) to run awaited per-turn bookkeeping with current messages before the next model request and skip callback execution for aborted or error turns
444
+
445
+ ### Changed
446
+
447
+ - Renamed `toolCallSyntax` option to `dialect` in AgentOptions and AgentLoopConfig
448
+ - Updated conversation serialization to use dialect's native transcript rendering when a dialect is selected
449
+ - Changed internal references from `ToolCallSyntax` type to `Dialect` type across agent loop and compaction modules
450
+
451
+ ## [15.13.3] - 2026-06-15
452
+
453
+ ### Added
454
+
455
+ - Added the `interruptible` tool field: when set, the agent loop may abort the tool mid-execution to deliver a queued steering message (honored only in `immediate` interrupt mode).
456
+ - Added support for `gemini` and `gemma` as valid owned tool syntax values in environment configuration
457
+
458
+ ### Fixed
459
+
460
+ - Fixed `pruneToolOutputs` blanking tiny tool results during overflow pruning: results below `50` tokens (`MIN_PRUNE_TOKENS`) are no longer replaced with the `[Output truncated - N tokens]` placeholder, which cost more tokens than the result itself and churned the prompt cache for zero savings.
461
+
462
+ ## [15.13.2] - 2026-06-15
463
+
464
+ ### Breaking Changes
465
+
466
+ - Removed `harmony-leak` exports from the `@oh-my-pi/pi-agent-core` package entrypoint
467
+ - Replaced the experimental `promptToolCalls` agent/loop option with `toolCallSyntax`, selecting an explicit in-band tool-call grammar instead of a boolean GLM-only mode.
468
+
469
+ ### Added
470
+
471
+ - Added support for selecting owned in-band tool-call syntax via `PI_OWNED_TOOLS=<syntax>` (for example `hermes` or `qwen3`) while preserving legacy `PI_OWNED_TOOLS=1/true` as GLM mode
472
+ - Added owned in-band tool calling for multiple syntaxes (`glm`, `hermes`, `kimi`, `xml`, `anthropic`, `deepseek`, `harmony`, `pi-native`, `qwen3`). Owned mode sends no native provider tools, appends a syntax-specific prompt/catalog, re-encodes prior tool calls/results as grammar-owned text, and parses streamed model output back into canonical tool calls.
473
+ - Added tool-example folding to `normalizeTools`: when given a model's affinity syntax (resolved via `preferredToolSyntax`), it renders each tool's `examples` into an `<examples>` block in that native syntax and appends it to the wire description. Wired through both context paths (fresh build and append-only `takeSnapshot`/`build` via a new `exampleSyntax` build option), with the `_i` intent-field placeholder added to examples when intent tracing injects it.
474
+ - Added the `abortOnFabricatedToolResult` option to `AgentOptions`/`AgentLoopConfig` (default `true`): when owned tool calling is active and the model fabricates a tool result mid-turn, `true` aborts the provider request immediately while `false` lets it finish and discards the fabricated continuation.
475
+
476
+ ### Changed
477
+
478
+ - Added owned in-band syntax support to `Agent` loop configuration resolution by selecting syntax from `toolCallSyntax` or `PI_OWNED_TOOLS` when present
479
+
480
+ ### Fixed
481
+
482
+ - Fixed append-only context cache fingerprinting to account for `exampleSyntax`, so switching tool-call syntax rebuilds cached prompts with the correct injected tool examples
483
+ - Fixed owned in-band tool-calling requests to omit `toolChoice` after stripping native tools, preventing invalid tool-choice requests
484
+ - Fixed owned tool calling letting the model fabricate tool results by treating grammar-owned tool-result markers in assistant text as a hard turn boundary: calls before the fabrication are kept, fabricated results and dependent calls are dropped, and the real result is fed back on the next turn.
485
+
486
+ ## [15.13.1] - 2026-06-15
487
+
488
+ ### Added
489
+
490
+ - Added repetition-loop detection to the streaming agent loop for Gemini-family providers. A runaway run of a repeated text or thinking unit is detected mid-stream from a bounded rolling tail (O(1) per delta), the provider request is aborted, the repeated tail is collapsed to a single representative copy, and the turn ends gracefully with an `error` stop reason. Legitimate all-numeric/whitespace/punctuation runs (hexdumps, zero-fills, numeric tables) are not misclassified as loops ([#2549](https://github.com/can1357/oh-my-pi/pull/2549) by [@usr-bin-roygbiv](https://github.com/usr-bin-roygbiv)).
491
+
492
+ ### Fixed
493
+
494
+ - Fixed repetition loop handling to collapse repeated `thinking` blocks to a single representative copy when a loop is detected
495
+ - Fixed repetition-loop detection to ignore repeats that contain only digits, whitespace, or punctuation so legitimate numeric outputs no longer stop with a repetition-loop error
496
+ - Fixed false-positive repetition-loop checks across `text` and `thinking` stream boundaries by tracking loop detection per block type
497
+
498
+ ## [15.12.6] - 2026-06-14
499
+
500
+ ### Fixed
501
+
502
+ - Fixed dynamic forced tool choices from queue hooks being filtered against the active per-turn tool set before provider dispatch. ([#1701](https://github.com/can1357/oh-my-pi/issues/1701))
503
+
504
+ ## [15.12.4] - 2026-06-13
505
+
506
+ ### Fixed
507
+
508
+ - Fixed remote compaction input trimming to use unlimited context when `model.contextWindow` is unset
509
+
510
+ ## [15.12.1] - 2026-06-12
511
+
512
+ ### Breaking Changes
513
+
514
+ - Changed `pruneSupersededToolResults` to allow `supersedeKey` to be omitted so useless-result pruning can run without read-style supersede grouping
515
+
516
+ ### Added
517
+
518
+ - Added `pruneUseless` controls to `PruneConfig` and `SupersedePruneConfig` so callers can toggle compaction of `toolResult` entries marked `useless`
519
+ - Added the ability to disable useless-result pruning by setting `pruneUseless` to false
520
+ - Tools can flag a result contextually useless (`AgentToolResult.useless`; overridable via `AfterToolCallResult.useless`): the agent loop copies the flag onto the persisted `ToolResultMessage` (errors always win), and compaction consumes it — the cache-aware supersede pass and the threshold prune blank flagged results to the exact `USELESS_NOTICE` placeholder (bypassing the protect window, skipping results smaller than the notice), shake collects them inside the protect-recent window, and `serializeConversation` drops the whole tool call/result pair from summarizer input
521
+
522
+ ### Changed
523
+
524
+ - Changed `pruneSupersededToolResults` to allow omitted `supersedeKey` when `pruneUseless` is enabled, so useless-result pruning can run without read-style supersede grouping
525
+
526
+ ## [15.11.4] - 2026-06-12
527
+
528
+ ### Added
529
+
530
+ - Added `hasSteeringMessages` to `AgentLoopConfig` (wired by `Agent` to its steering queue): a peek used by the immediate-interrupt poll during tool execution, so the loop can detect queued steering without dequeuing and the queue keeps owning its messages until the injection boundary
531
+ - The agent loop now re-samples after a non-terminal stop (`stopReason: "stop"` with `stopDetails: { type: "pause_turn" }`, emitted by the Codex providers for `end_turn: false` commentary-only responses): the assistant message is committed to history and the model is called again without ending the turn. Consecutive pause continuations without an intervening tool call are capped at 8 to bound a backend that never stops pausing.
532
+
533
+ ### Changed
534
+
535
+ - Changed steering handling so queued steering messages are now dequeued only at injection boundaries, with immediate mid-batch interrupt polling using `hasSteeringMessages`. Consumers constructing `AgentLoopConfig` directly with only `getSteeringMessages` no longer get mid-batch interrupts — steering degrades to boundary-only delivery until they also supply `hasSteeringMessages`
536
+ - Compaction, handoff, short-summary, and branch-summarization helpers now accept an `ApiKey` (static string or resolver) instead of a pre-resolved string, so a 401 mid-compaction force-refreshes and rotates the credential through the central auth-retry policy before any model-level fallback. The remote OpenAI compaction request is wrapped in `withAuth` and its HTTP failures now carry `.status`, so the retry classifier actually fires on remote-compaction 401s.
537
+ - `transformProviderContext` now receives the dispatch model as a second argument (`(context, model) => Context`), so per-request transforms can gate on model capabilities (vision input, provider, API family). Existing single-argument implementations keep working unchanged.
538
+ - Remote-compaction and summarization failures now throw pi-ai's typed `ProviderHttpError` instead of mutating plain `Error`s with a `.status` property; the generic `requestRemoteCompaction` error now carries `.status` (and response headers) too.
539
+
540
+ ### Fixed
541
+
542
+ - Fixed a regression where steering messages could be injected into history during an aborted in-flight tool batch, leaving them hidden from queue consumers for post-abort continue
543
+
544
+ ## [15.11.2] - 2026-06-11
545
+
546
+ ### Added
547
+
548
+ - `AgentTool.concurrency` now also accepts a per-call resolver function `(args) => "shared" | "exclusive"`, letting tools pick the scheduling mode from the call's arguments (a throwing resolver falls back to `"exclusive"`)
549
+
550
+ ### Fixed
551
+
552
+ - Fixed whitespace-only error tool results so Anthropic requests no longer 400 with `tool_result: content cannot be empty if is_error is true` and wedge the session on every subsequent turn
553
+
554
+ ## [15.11.0] - 2026-06-10
555
+
556
+ ### Breaking Changes
557
+
558
+ - Removed `compaction/index.ts` re-export of snapcompact helpers, so snapcompact utilities are no longer available from the agent compaction barrel and should be imported from `@oh-my-pi/snapcompact`
559
+ - Removed the `convertToLlm` alias export from `compaction/messages` — it duplicated `defaultConvertToLlm` under a second name. Import `defaultConvertToLlm` (array form) or the new `convertMessageToLlm` (single-message form) instead
560
+
561
+ ### Added
562
+
563
+ - Added `convertMessageToLlm()`: the single-message core transformer behind `defaultConvertToLlm()`. Embedders with app-specific message roles should handle their own roles and delegate every core role (`user`/`developer`/`assistant`/`toolResult`/`custom`/`hookMessage`/`branchSummary`/`compactionSummary`) to it instead of duplicating the conversion — a duplicated `compactionSummary` case is how snapcompact frames once silently dropped off provider requests
564
+ - Added `pruneSupersededToolResults()` and the opt-in `PruneConfig.supersedeKey` hook so harnesses can prune stale tool results superseded by a newer read of the same file; superseded results are pruned ahead of age-based victims during overflow pruning and replaced with a `[Superseded by a newer read of this file]` placeholder. Without the new config, `pruneToolOutputs()` behavior is unchanged.
565
+ - Added `readToolSupersedeKey()` implementing the read-tool path/selector grammar (selector-free reads supersede range reads of the same file; URL-scheme paths exempt). Pruning honors prompt-cache economics: per-turn prunes only fire when the post-candidate suffix is small or the cache is cold (idle gap).
566
+ - Added the `snapcompact` compaction strategy via `@oh-my-pi/snapcompact`: instead of an LLM summary, discarded history is printed onto dense bitmap frames and re-attached to the compaction summary message as image blocks. `CompactionSummaryMessage` gains an optional `images` field, `estimateTokens()` charges per attached frame, and frames persist under `preserveData.snapcompact` with an 8-frame middle-out eviction budget.
567
+ - Snapcompact frames are now rendered in a provider-aware shape (`SNAPCOMPACT_SHAPES` + `resolveSnapcompactShape(api)`), following the snapcompact 200k-token monolithic evals: Anthropic-family and unknown APIs get `8x8r-bw` (unscii-8 square cells, black ink, every line printed twice with the copy on a pale highlight band — read at F1 parity with raw text at ~2x lower cost and the most refusal-robust), Google gets `8x8r-sent` (sentence-hue ink, ~2.9x cheaper), and OpenAI gets `6x6u-sent` (unscii Lanczos-stretched to 6x6 cells — OpenAI bills a flat ~2.9k tokens per image, so frame count is the only cost lever) with `detail: "original"` on the frame images. `snapcompactCompact()` accepts `model`/`shape` options, frames persist their shape metadata, mixed-shape archives (provider switches, legacy 5x8 frames) are flagged in the reading instructions, and `snapcompactGeometry()`/`renderSnapcompactFrame()` now take a shape
568
+
569
+ ### Changed
570
+
571
+ - Compaction and branch-summary file lists are now a single `<files>` tag instead of `<read-files>`/`<modified-files>`: paths render as the grouped, prefix-folded directory tree the find/search tools emit (`# dir/` headers, bare basenames), each annotated `(Read)`, `(Write)`, or `(RW)` — modified files that were also read get `(RW)`. Legacy tags in summaries written by earlier versions are still stripped and self-heal on the next compaction
572
+
573
+ ### Fixed
574
+
575
+ - Fixed queued steering messages being drained into an externally aborted run: interrupting mid-tool execution (e.g. Enter with a pending steer) dequeued the steer into the dying run — it landed in history without a response and the post-abort resume saw an empty queue, so the agent stopped instead of continuing. Steering/follow-up/aside queue polls are now skipped once the run's abort signal fires, leaving the queue intact for `Agent.continue()`.
576
+ - Fixed `<read-files>` compaction lists recording the same file once per line-range/raw selector (`src/foo.ts:50-200`, `:raw`, `:1-50:raw`, …): read-tool selectors are now stripped before tracking, so reads dedupe to the base path and match their write/edit path when splitting read-only vs modified lists. Selector-polluted lists stored by earlier compactions self-heal on the next compaction. `readToolSupersedeKey()` now shares the same splitter (`splitReadSelector()`), gaining the `..` range alias and `L`-prefix forms it previously missed.
577
+ - Fixed `estimateTokens()` undercounting thinking-heavy assistant messages on replay: `thinkingSignature` payloads (OpenAI Responses encrypted reasoning items, Anthropic signed thinking blocks, etc.) and `redactedThinking.data` are now charged alongside the visible thinking text, so the local estimate tracks provider-reported usage instead of straddling the threshold on every turn ([#2275](https://github.com/can1357/oh-my-pi/issues/2275)).
578
+
579
+ ## [15.10.12] - 2026-06-10
580
+
581
+ ### Added
582
+
583
+ - Added `AgentLoopConfig.getDisableReasoning` so callers can override `disableReasoning` per LLM call, mirroring `getReasoning`.
584
+ - Added `transformProviderContext` to `AgentOptions`/`AgentLoopConfig`: an optional hook applied to the assembled provider context after conversion, normalization, and append-only handling, but before telemetry capture and provider send.
585
+
586
+ ### Fixed
587
+
588
+ - Fixed `Agent` runs so explicit reasoning disablement is forwarded to provider stream options and re-resolved per continuation, keeping mid-run thinking-off changes in sync with the next provider request.
589
+
590
+ ## [15.10.11] - 2026-06-10
591
+
592
+ ### Changed
593
+
594
+ - Editorial pass over the compaction prompts: fixed garbled grammar and missing articles, RFC-keyed prohibitions, deduped restated instructions; parsed markers (`<read-files>`/`<modified-files>`/`<previous-summary>`) and all output-format headings left byte-identical
595
+ - Catalog imports moved to the new `@oh-my-pi/pi-catalog` package: subpath imports (`calculateCost`, Codex wire constants) plus catalog values previously taken from the `@oh-my-pi/pi-ai` root (`getBundledModel`, `clampThinkingLevelForModel`), which pi-ai no longer re-exports; type-only `Model`/`Api`/`Effort` imports from pi-ai are unchanged
596
+
597
+ ## [15.10.8] - 2026-06-09
598
+
599
+ ### Added
600
+
601
+ - Added optional `fetch` overrides to `SummaryOptions` and `compact`/`generateSummary` so remote compaction can use custom HTTP clients
602
+ - Added optional `fetch` option to `ProxyStreamOptions` to control the HTTP request used by `streamProxy`
603
+ - Added optional `fetch` overrides to `requestOpenAiRemoteCompaction` and `requestRemoteCompaction` for injectable HTTP transport
604
+ - Added the upstream provider that served a request (`AssistantMessage.upstreamProvider`, e.g. OpenRouter's routed provider) as a `pi.gen_ai.response.upstream_provider` chat-span telemetry attribute, alongside the existing response id and time-to-first-chunk.
605
+
606
+ ## [15.10.5] - 2026-06-08
607
+
608
+ ### Removed
609
+
610
+ - Removed the `maxToolCallsPerTurn` option from `AgentOptions` and `AgentLoopConfig`, so assistant turns are no longer capped after a configured number of completed tool calls
611
+
612
+ ### Fixed
613
+
614
+ - Fixed stalled aborted assistant responses so the run now stops without waiting for provider iterator cleanup and returns the aborted message promptly
615
+ - Fixed `afterToolCall` handling so it now runs for completed tool executions even after a run is aborted so tool post-processing still applies
616
+ - Fixed `agentLoopDetailed().detailed()` so run telemetry and coverage are captured before `stream.result()` resolves.
617
+ - Fixed agent-loop stream invariants so `agentLoopContinue` no longer mutates the caller's message array, emitted assistant events snapshot mutable provider content, terminal provider events win over late abort signals, transformed tool arguments are reflected consistently in hooks/events, and successful run-end telemetry fires from the same finalization path as failures.
618
+ - Fixed tool result parsing to mark assistant tool outputs with unsupported content block shapes as errors and include a diagnostic text block
619
+ - Fixed GPT-5 Harmony leakage handling by recovering valid leaked tool calls when possible and discarding leaked partial assistant output before retrying
620
+ - Fixed tool-call cancellation handling so aborted tools are marked aborted with an explicit reason and do not report generic errors
621
+ - Fixed tool-call completion so assistant messages on abort keep only completed tool-call blocks and continue processing tool calls when a length stop still included results
622
+ - Fixed deliberate aborts (TTSR rule matches, user-interrupt labels) so a mid-stream tool-call block that never reached `toolcall_end` is retained on the aborted assistant message and paired with a placeholder result labeled by the abort reason, instead of being dropped; anonymous aborts (bare `abort()`) still drop incomplete tool calls whose partial arguments are unsafe to replay
623
+ - Fixed runs that stopped with reason `length` after returning tool results so execution continues to handle additional tool calls
624
+
625
+ ## [15.10.3] - 2026-06-08
626
+
627
+ ### Added
628
+
629
+ - Added a non-interrupting "aside" message channel to the agent loop (`AgentLoopConfig.getAsideMessages` / `Agent.setAsideMessageProvider`). Asides are drained at each step boundary (after a tool batch, before the next model call) and at the yield check, so passive notifications (e.g. background-job completions, late LSP diagnostics) reach the model *between requests* without waiting for the agent to stop and without aborting in-flight tools the way steering does.
630
+
631
+ ### Changed
632
+
633
+ - Changed core custom and hook messages to convert to `developer` messages for provider context.
634
+
635
+ ### Fixed
636
+
637
+ - Fixed the compaction spinner freezing (only repainting on a terminal resize) when compacting very large codex/OpenAI contexts. `buildOpenAiNativeHistory` re-collected the full known/custom tool-call id sets on every history-bearing message, rescanning the entire growing native history each time — O(N²) in history items — which blocked the event loop for seconds and starved the loader's animation timer and render scheduler. The sets are now maintained incrementally (linear), so building the compaction request no longer monopolizes the main thread.
638
+
639
+ ### Removed
640
+
641
+ - Removed the now-dead `<turn-aborted>` marker from the OpenAI compaction output user-message filter, since `transformMessages` no longer emits that note.
642
+ - Removed stale synthetic user-message tag filters from OpenAI remote compaction output preservation; developer messages are now dropped by role instead.
643
+ - Tool executions now receive the active turn `AbortSignal` unconditionally.
644
+
645
+ ## [15.10.2] - 2026-06-08
646
+
647
+ ### Fixed
648
+
649
+ - Fixed proxy stream silently returning a zero-token success response when the server disconnects without sending a `done` or `error` terminal SSE event. The stream now throws an error, surfacing the disconnect as an `error` event with `stopReason: "error"` and resolving `finalResultPromise`, instead of defaulting to `stopReason: "stop"` with empty content and leaving `stream.result()` callers hanging indefinitely.
650
+
651
+ ## [15.10.1] - 2026-06-07
652
+
653
+ ### Added
654
+
655
+ - Added optional `promptCacheKey` support to `AgentOptions` and `Agent` via a new `promptCacheKey` property so providers can receive a caller-provided prompt cache key
656
+ - Added optional `ApiKeyResolveContext` parameter to `getApiKey` in `AgentOptions` and `AgentLoopConfig` so key resolvers can receive retry context
657
+
658
+ ### Changed
659
+
660
+ - Enabled streaming API calls to re-resolve credentials through the `getApiKey` callback when retries occur after authentication-related errors
661
+ - `Agent.abort(reason?)` now forwards `reason` to the underlying `AbortController`, and the synthesized aborted assistant message carries that reason on `errorMessage` (string or non-`AbortError` `Error` message) instead of always defaulting to `"Request was aborted"`. Bare `abort()` is unchanged.
662
+
663
+ ### Fixed
664
+
665
+ - Fixed handling of short-lived API keys so that expired tokens are retried with a refreshed value during 401/usage-limit failures
666
+ - Ensured fallback API key resolution uses the initially configured static `apiKey` when `getApiKey` is present
667
+ - Wrapped oneshot LLM completions (`instrumentedCompleteSimple`: handoff, compaction/branch summaries) in an `EventLoopKeepalive`. These run outside the agent `#runLoop`, so without the keepalive Bun's event loop stopped servicing timers while parked on the completion promise — freezing host spinners (e.g. the `/handoff` loader) until an unrelated terminal resize poked the loop into rendering again.
668
+
669
+ ## [15.9.5] - 2026-06-05
670
+
671
+ ### Fixed
672
+
673
+ - Surfaced Anthropic stream failures whose message starts with `Output blocked by conten` as normal assistant error lifecycle events, so interactive clients render content-filter blocks instead of silently dropping the streaming bubble at `agent_end`.
674
+
675
+ ## [15.8.3] - 2026-06-03
676
+
677
+ ### Added
678
+
679
+ - Added `getReadToolPath(context)` to `@oh-my-pi/pi-agent-core/compaction/tool-protection` to extract a paired `read` tool call's `path` for embedders building read-targeted protection matchers
680
+ - Added `getReadToolPath(context)` to `@oh-my-pi/pi-agent-core/compaction/tool-protection`: the shared primitive that extracts a paired `read` tool call's `path` argument, so embedders can build their own read-targeted compaction protection matchers (e.g. plan-file reads) the same way `isSkillReadToolResult` does.
681
+
682
+ ## [15.8.2] - 2026-06-03
683
+
684
+ ### Added
685
+
686
+ - Added optional `AgentTool.matcherDigest(args)` hook: tools whose streamed arguments encode content in a wire grammar (patch formats, escaped strings) can expose the real content they introduce, so stream-content matchers (e.g. TTSR rules) run against plain source text instead of the wire format.
687
+
688
+ ### Fixed
689
+
690
+ - Fixed the agent loop wedging the model when a `write`/`edit` tool call is truncated by `stop_reason: length` (e.g. an OpenCode Zen / Claude-3.5-Haiku turn that emits >~1000 lines of code, blowing past the 8K `max_tokens` output cap). The skipped tool result now surfaces an actionable hint — naming `stop_reason: length` and telling the model to split the payload into multiple smaller calls — instead of the generic "Tool call was not executed because the assistant ended its turn" placeholder, which left the auto-continue loop re-emitting the same oversized payload until the user gave up. Tools are still NOT executed when the arguments are truncated. ([#1785](https://github.com/can1357/oh-my-pi/issues/1785))
691
+
692
+ ## [15.8.0] - 2026-06-02
693
+
694
+ ### Fixed
695
+
696
+ - Engaged GPT-5 Harmony leak detection on the committed assistant message (openai-codex only). `detectHarmonyLeakInAssistantMessage` now runs on the streamed `done`/`error` result and the trailing fallback, so a leaked final response is aborted-and-retried by the existing mitigation instead of being committed as-is. Tool-argument (`tool_arg`) scanning is gated on the trailing-garbage `T` co-signal and only fires when a caller supplies a parse boundary via `detectHarmonyLeakInAssistantMessage`'s new optional `toolArgParseEnd` resolver. The agent loop passes none — it cannot bound a streamed tool DSL — so that surface stays inert and a legitimate codex tool call whose content legitimately carries `to=functions.*` next to a channel word or non-Latin script (e.g. editing the harmony fixtures) is never hard-aborted.
697
+
698
+ ## [15.7.4] - 2026-05-31
699
+
700
+ ### Removed
701
+
702
+ - Removed the local-model `summarizeShakeRegions` compressor and related shake-summary prompt/types; shake now only provides mechanical artifact-backed elision primitives.
703
+
704
+ ## [15.7.3] - 2026-05-31
705
+
706
+ ### Added
707
+
708
+ - Added `shake` compaction primitives (`collectShakeRegions`, `applyShakeRegion`, `applyShakeRegions`, `summarizeShakeRegions`, `DEFAULT_SHAKE_CONFIG`, `AGGRESSIVE_SHAKE_CONFIG`, plus the `ShakeRegion`/`ShakeConfig`/`ShakeSummaryItem`/`ShakeSummaryComplete`/`ProtectedToolMatcher` types) under `@oh-my-pi/pi-agent-core/compaction`. These detect heavy context regions — whole tool-call results plus large fenced/XML blocks — and either elide them with placeholders or extractively compress them through an injected completion backend (no LLM summary cut-point). The compressor is provider-agnostic: callers wire it to a local on-device model. Pure detection/mutation; no I/O.
709
+
710
+ ### Fixed
711
+
712
+ - Fixed tool-output pruning and shake protection for `read`: ordinary file/URL reads are now eligible for compaction, while `read` calls whose `path` starts with `skill://` remain protected like native `skill` results.
713
+
714
+ ## [15.5.15] - 2026-05-30
715
+
716
+ ### Added
717
+
718
+ - Added `maxToolCallsPerTurn` to `AgentLoopConfig`/`AgentOptions`, allowing callers to cut a streamed assistant turn after a completed tool-call batch and execute the runnable partial turn instead of waiting for the provider to yield.
719
+
720
+ ### Fixed
721
+
722
+ - Normalized `maxToolCallsPerTurn` to accept only positive integer limits, with non-finite or non-positive values treated as disabled
723
+
724
+ ## [15.5.14] - 2026-05-29
725
+
726
+ ### Fixed
727
+
728
+ - Fixed the agent loop abandoning tool calls that Anthropic adaptive/interleaved-thinking models (e.g. Opus) emit under `stop_reason: "end_turn"`. The previous gate only ran tools when `stopReason === "toolUse"`, so an `end_turn`+tool_use turn produced "Tool call was not executed because the assistant ended its turn" placeholders, made no progress, and could trap the model in a re-emit/abandon loop. `stop_reason` is never replayed on the wire and (verified against the live Anthropic Messages API) does not gate continuation validity, so `stop`/`end_turn` turns carrying tool_use blocks are now executed and the loop continues — exactly like `toolUse`. Only `length` (max_tokens truncation) still abandons, since the trailing tool call may have incomplete arguments. The continuation stays valid because `transformMessages` strips the now-untrustworthy thinking signature and the encoder downgrades the block to text.
729
+
730
+ ## [15.5.10] - 2026-05-28
731
+
732
+ ### Fixed
733
+
734
+ - Fixed compaction summarizer throws losing the provider's HTTP status. `generateSummary`, `generateHandoff`, `generateShortSummary`, and `generateTurnPrefixSummary` now route their `stopReason === "error"` throws through a `createSummarizationError` helper that copies `AssistantMessage.errorStatus` onto the thrown `Error` as `.status`, letting downstream consumers (e.g. `AgentSession.#isCompactionAuthFailure` in `@oh-my-pi/pi-coding-agent`) branch on real provider 401/403s without regex-scraping the message body.
735
+
736
+ ## [15.5.0] - 2026-05-26
737
+
738
+ ### Added
739
+
740
+ - Added `approval` support to `AgentTool` declarations with the new `ToolTier` and `ToolApproval` APIs, allowing tools to declare capability tiers (`read`, `write`, or `exec`) and optional override/reason metadata for approval gating
741
+ - Added `formatApprovalDetails` on `AgentTool` to append custom detail text or lines to approval prompts
742
+ - Added exported `ToolTier` and `ToolApproval` type aliases for tool approval declarations
743
+
744
+ ### Fixed
745
+
746
+ - Fixed chat-request telemetry storing the raw scoped `serviceTier` value (`"openai-only"`/`"claude-only"`) in `OpenAIAttr.RequestServiceTier` instead of the resolved wire value (`"priority"`). Dashboards and alerts filtering on the concrete tier name (`service_tier == "priority"`) were broken by the scoped placeholder; `buildChatRequestAttributes` now runs the tier through `resolveServiceTier(serviceTier, provider)` before recording, keeping the `shouldSendServiceTier` gate intact so non-OpenAI providers continue to omit the attribute entirely.
747
+
748
+ ## [15.3.0] - 2026-05-25
749
+
750
+ ### Fixed
751
+
752
+ - Fixed `transformContext` receiving the loop config object as the `signal` argument instead of the actual `AbortSignal`, so hooks that check `signal.aborted` or call `signal.addEventListener` now work correctly under abort/timeout conditions
753
+ - Fixed `appendOnlyContext` not being re-evaluated after `setModel()` — the mode was decided once at session construction based on the initial model's provider, so switching from/to DeepSeek (or changing `provider.appendOnlyContext`) mid-session produced incorrect mode behavior
754
+
755
+ ## [15.2.3] - 2026-05-22
756
+
757
+ ### Added
758
+
759
+ - Added `onBeforeYield` hook support so user code can run right before the agent loop checks for follow-up messages
760
+
761
+ ## [15.1.3] - 2026-05-17
762
+
763
+ ### Added
764
+
765
+ - Added optional `telemetry` support to `generateSummary`, `generateHandoff`, `generateBranchSummary`, and `compact` options so compaction, handoff, and branch summary one-shot LLM calls can emit OpenTelemetry chat telemetry when enabled
766
+ - Added shared oneshot telemetry instrumentation for compaction, handoff, and branch summary calls, tagging spans with `pi.gen_ai.oneshot.kind` values such as `compaction_summary`, `compaction_short_summary`, `compaction_turn_prefix`, `handoff`, and `branch_summary`
767
+
768
+ ## [15.1.2] - 2026-05-15
769
+
770
+ ### Added
771
+
772
+ - Added `responseHeaders` to `ChatUsageEvent` and `ManualChatTelemetryOptions` so telemetry hooks receive captured lowercase upstream response headers for each chat span
773
+ - Added automatic gateway/proxy detection from response headers (`litellm`, `helicone`, `portkey`, `openrouter`) and stamped `pi.gen_ai.gateway.*` span attributes for detected routing metadata
774
+ - Added exported `detectGatewayFromHeaders` API for header-based gateway detection
775
+
776
+ ## [15.1.0] - 2026-05-15
777
+
778
+ ### Breaking Changes
779
+
780
+ - Removed the `@oh-my-pi/pi-agent-core/compaction/handoff` exports from the package surface, including `extractHandoffDocument`, `createHandoffContext`, and `createHandoffFileName`
781
+ - Removed legacy telemetry constants from the public enum surface (including `AGGREGATE_ATTR`, `GenAIAttr.System`, and old `gen_ai.*` extension keys such as `gen_ai.request.service_tier`/cost/tool status/handoff fields) and replaced them with `OpenAIAttr`, `PiGenAIAttr`, and `PiGenAIAggregateAttr`
782
+
783
+ ### Added
784
+
785
+ - Added `generateHandoff(messages, model, apiKey, options)` to `@oh-my-pi/pi-agent-core/compaction` to generate a handoff document by calling the model directly, using live system/tool context and optional metadata
786
+ - Added generation filtering so the returned handoff document now includes only text content blocks from the model output
787
+ - Added support for defining `AgentTool` schemas with Zod, with legacy TypeBox schemas still supported when generating tool schemas for model calls
788
+ - Added `OpenAIAttr`, `PiGenAIAttr`, and `PiGenAIAggregateAttr` exports so consumers can reference the new `openai.*` and `pi.gen_ai.*` telemetry attribute keys directly
789
+ - Added `onChatUsage` to `AgentTelemetryConfig`, an always-fired hook receiving a `ChatUsageEvent` for every chat step that produced usage. The event carries the chat `span`, `agent`, `conversationId`, `stepNumber`, `model`, `provider`, `serviceTier`, `usage`, optional `cost`, and resolved dynamic `attributes` — independent of whether a `costEstimator` is configured.
790
+ - Added `agentLoopDetailed(...)` and `agentLoopContinueDetailed(...)` helpers that return the same event stream plus a `detailed()` result with run `telemetry` and `coverage`
791
+ - Added `onRunEnd` to `AgentTelemetryConfig` to receive `AgentRunSummary` and `AgentRunCoverage` at the end of each invocation
792
+ - Added run-level telemetry and coverage types/helpers (for example `AgentRunSummary`, `AgentRunCoverage`, `aggregateAgentRunSummaries`, and `aggregateAgentRunCoverage`) to package exports
793
+ - Added generic telemetry extension hooks for dynamic span attributes, provider/agent-name normalization, per-step cost deltas, warning callbacks, bounded summary content capture, and manual chat telemetry for non-loop model calls.
794
+ - Added opt-in OpenTelemetry instrumentation on the agent loop. Pass `telemetry: {}` (or a richer `AgentTelemetryConfig`) on `AgentLoopConfig` / `AgentOptions` / `createAgentSession({ telemetry })` to emit GenAI-semantic-convention spans plus `pi.gen_ai.*` extension attributes:
795
+ - `invoke_agent {agent.name}` wraps each `agentLoop` invocation with `gen_ai.operation.name=invoke_agent`, agent identity, conversation id, and `pi.gen_ai.agent.step.count`.
796
+ - `chat {model}` per provider call, parented under `invoke_agent`, with OTEL request/response/usage attributes (`gen_ai.request.{model,stream,temperature,top_p,top_k,max_tokens,presence_penalty,stop_sequences}`, `gen_ai.response.{model,id,finish_reasons,time_to_first_chunk}`, `gen_ai.usage.{input_tokens,output_tokens,cache_read.input_tokens,cache_creation.input_tokens,reasoning.output_tokens}`) and project extensions for reasoning effort, tool choice, available tools, usage totals, and cost.
797
+ - `execute_tool {tool.name}` per tool call, parented under `invoke_agent`, with `gen_ai.tool.{name,call.id,description,type}` plus the active context so user/MCP/provider spans created inside `tool.execute()` attach as children.
798
+ - One-shot `handoff` span available via the public `recordHandoff(...)` helper for agent-to-agent transitions.
799
+ - Added `AgentTelemetryConfig` hooks (`onSpanStart`, `onSpanEnd`, `costEstimator`), `agent` identity, `attributes` envelope merged onto every span, `captureMessageContent` toggle (defaults to the `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` env var) emitting OTEL-shaped `gen_ai.input.messages` / `gen_ai.output.messages` / `gen_ai.system_instructions` / `gen_ai.tool.call.arguments` / `gen_ai.tool.call.result`, and tracer/tracerName override surfaces.
800
+ - Added `Agent#setTelemetry(config)` so consumers can swap or disable instrumentation between invocations.
801
+ - Added `@opentelemetry/api` as a runtime dependency; SDK setup (exporters, samplers, processors) remains the host's responsibility per standard OTEL conventions. When no SDK is registered, helpers fall through to no-op spans with zero overhead.
802
+ - Added compaction APIs under `@oh-my-pi/pi-agent-core/compaction`, including context compaction, branch summarization, handoff prompt/context helpers, pruning, token budgeting, prompt templates, and OpenAI `/responses/compact` helpers.
803
+
804
+ ### Changed
805
+
806
+ - Changed handoff document generation to force `toolChoice: "none"` when calling the model so tool invocation is disabled during generation
807
+ - Changed `chat` spans to emit normalized provider identifiers in `gen_ai.provider.name` via OTEL-style values (for example `google` to `gcp.gemini`) instead of the legacy `gen_ai.system` label
808
+ - Changed service-tier telemetry to emit `openai.request.service_tier`/`openai.response.service_tier` only when supported by provider via `shouldSendServiceTier`, rather than always using `gen_ai.request.service_tier`
809
+ - Changed captured message payloads so full capture now records OTEL-structured message parts with `pi.gen_ai.request.messages`, `pi.gen_ai.system_instructions`, and `gen_ai.output.messages` including assistant `finish_reason`
810
+ - Changed the `agent_end` event payload to include optional `telemetry` and `coverage` fields when telemetry is enabled, while keeping the legacy payload shape when disabled
811
+ - Changed `invoke_agent` spans to include aggregate `pi.gen_ai.agent.*` attributes for chat/tool counts, latency, usage, cost, errors, and tool coverage
812
+
813
+ ### Fixed
814
+
815
+ - Fixed intent-field injection for tool schemas defined with Zod by converting them to wire schema before mutation
816
+ - Fixed token accounting in `ChatUsageEvent` and usage summaries so `inputTokens` and `totalTokens` now include cached read/write input tokens
817
+ - Fixed `execute_tool` span attributes so `pi.gen_ai.tool.status` and `error.type` now reflect run-level tool outcomes (`ok`, `error`, `skipped`, `blocked`, `timeout`, `aborted`) instead of mapping all non-ok cases the same way
818
+ - Fixed `onRunEnd` callbacks to be safe and idempotent by invoking them once per run and swallowing thrown callback errors so they cannot fail or duplicate successful runs
819
+ - Fixed run telemetry to count interrupted, blocked, or otherwise skipped tool calls so run coverage and tool counters now include those paths
820
+ - Fixed chat failure handling so failed chat steps are still represented in run summaries when provider streaming throws before yielding an assistant message
821
+ - Fixed double-counting of interrupted tool calls in run summaries: the `runTool` early-return on a queued steering interrupt now defers to the post-batch tail sweep so each call is recorded exactly once
822
+ - Fixed `coverage.toolsInvoked` and run-summary tool counters under-reporting tool calls embedded in an aborted/errored assistant message — those calls now record a collector orphan with status `aborted` or `error`
823
+ - Fixed `AgentRunSummary.usage.inputTokens` so it now includes `cache_read` and `cache_write` input tokens, matching `ChatUsageEvent.inputTokens`
824
+ - Fixed span lifecycle hooks (`onSpanStart`, `onSpanEnd`) so a thrown user callback is caught and surfaced via `onTelemetryWarning` (`on_span_start_failed` / `on_span_end_failed`) instead of leaking and aborting the surrounding span
825
+ - Fixed unbounded recursion in summary content capture when a captured value contains a cyclic or deeply nested array — array recursion now respects the same depth cap as plain-object recursion and replaces back-references with `"[Circular]"`
826
+
827
+ ## [15.0.1] - 2026-05-14
828
+
829
+ ### Breaking Changes
830
+
831
+ - Raised the minimum required Bun version from >=1.3.7 to >=1.3.14
832
+
833
+ ## [14.9.5] - 2026-05-12
834
+
835
+ ### Added
836
+
837
+ - Added an `isError?: boolean` field on `AgentToolResult` so tools can flag a non-throwing failure (e.g. an aggregator that catches per-entry errors). `coerceToolResult` preserves the flag and the agent loop surfaces it as a tool error on the wire.
838
+
839
+ ## [14.9.3] - 2026-05-10
840
+
841
+ ### Added
842
+
843
+ - Added `onHarmonyLeak` option on `Agent`/loop config to receive GPT-5 Harmony leak audit callbacks
844
+ - Added harmony-leak detection and audit exports to the package index for programmatic leak detection and recovery hooks
845
+
846
+ ### Changed
847
+
848
+ - Changed OpenAI Codex model runs to detect GPT-5 Harmony protocol leakage during streaming and automatically retry or recover tool calls instead of sending contaminated arguments downstream
849
+
850
+ ### Security
851
+
852
+ - Hardened tool-call handling against leaked `to=functions.*` protocol tails by truncating or retrying before execution
853
+ - Hardened failure handling so repeated GPT-5 Harmony leak mitigation is retried only up to two times before escalating to an explicit error
854
+
855
+ ## [14.9.0] - 2026-05-10
856
+
857
+ ### Added
858
+
859
+ - Added `Agent#metadata` field forwarded to every API request; callers can set arbitrary provider metadata (e.g. `metadata.user_id`) once and have it applied to all subsequent stream calls without modifying per-call options
860
+ - Added `Agent#setMetadataResolver(fn)` for installing a function that resolves request metadata at call time. The `metadata` getter dispatches through the resolver on every read (including the snapshot taken per `prompt()`), so callers reflect mutable external state (e.g. live OAuth account UUID after a token refresh) without manual re-syncs. Plain `agent.metadata = …` continues to set a static value and clears any installed resolver.
861
+ - Added an `onSseEvent` agent option and loop config forwarding path for raw provider SSE diagnostics.
862
+
863
+ ## [14.7.6] - 2026-05-07
864
+
865
+ ### Added
866
+
867
+ - Added `hideThinkingSummary` option/getter/setter on `Agent` and `AgentLoopConfig`. Forwarded to the underlying stream call so providers can omit reasoning/thinking summaries on demand.
868
+
869
+ ## [14.7.2] - 2026-05-06
870
+
871
+ ### Added
872
+
873
+ - Added `loadMode` option to `AgentTool` to mark built-in tools as `essential` for initial loading or `discoverable` for search activation
874
+ - Added optional `summary` field to `AgentTool` definitions for one-line text used in tool discovery indexes
875
+
876
+ ## [14.7.0] - 2026-05-04
877
+
878
+ ### Breaking Changes
879
+
880
+ - Changed `Agent` API types so `systemPrompt` is now a list of prompt strings, requiring callers to pass and update system prompts via string arrays
881
+
882
+ ### Changed
883
+
884
+ - Removed automatic project-context injection into each model call from loop logic
885
+
886
+ ### Removed
887
+
888
+ - Removed the `projectPrompt` field from agent state/context and the `setProjectPrompt` mutator
889
+
890
+ ## [14.6.2] - 2026-05-03
891
+
892
+ ### Fixed
893
+
894
+ - Fixed unhandled promise rejection when `getApiKey` or any other async error occurs during `streamAssistantResponse`: agent loop IIFEs now catch and route errors through `EventStream.fail()`, which terminates the `for await` loop and lets `Agent#runLoop`'s catch block create a proper error assistant message instead of crashing
895
+
896
+ ## [14.6.0] - 2026-05-02
897
+
898
+ ### Fixed
899
+
900
+ - Fixed request cancellation before provider events by emitting an aborted assistant message and ending the stream with `stopReason: "aborted"`
901
+
902
+ ## [14.5.10] - 2026-04-30
903
+
904
+ ### Added
905
+
906
+ - Added an `onResponse` stream option for observing provider response metadata after response headers arrive.
907
+
908
+ ## [14.2.0] - 2026-04-23
909
+
910
+ ### Changed
911
+
912
+ - Changed tool dispatch to match model-returned tool calls by either internal tool name or custom wire name, enabling custom OpenAI tool names such as `apply_patch`.
913
+
914
+ ## [14.0.1] - 2026-04-08
915
+
916
+ ### Added
917
+
918
+ - Added `onAssistantMessageEvent` callback option to inspect assistant streaming events before they are emitted, enabling abort decisions before buffered events continue flowing
919
+ - Added `setAssistantMessageEventInterceptor()` method to dynamically set or update the assistant message event interceptor
920
+
921
+ ## [13.13.0] - 2026-03-18
922
+
923
+ ### Added
924
+
925
+ - Added `startup.checkUpdate` setting, set to `true` by default, can be disabled to skip the update check on agent initialization
926
+
927
+ ## [13.12.7] - 2026-03-16
928
+
929
+ ### Added
930
+
931
+ - Added overload for `prompt()` method accepting a string input with optional options parameter
932
+
933
+ ### Fixed
934
+
935
+ - Fixed stale forced toolChoice being passed to provider after tools are refreshed mid-turn
936
+
937
+ ## [13.9.16] - 2026-03-10
938
+
939
+ ### Added
940
+
941
+ - Added `onPayload` option to `AgentOptions` to inspect or replace provider payloads before they are sent
942
+
943
+ ## [13.9.3] - 2026-03-07
944
+
945
+ ### Added
946
+
947
+ - Exported `ThinkingLevel` selector constants and types for configuring agent reasoning behavior
948
+ - Added `inherit` thinking level option to defer reasoning configuration to higher-level selectors
949
+ - Added `serviceTier` option to configure service tier for agent requests
950
+
951
+ ### Changed
952
+
953
+ - Changed `thinkingLevel` from required string to optional `Effort` type, allowing undefined state
954
+ - Updated `setThinkingLevel()` method to accept `Effort | undefined` instead of `ThinkingLevel` string
955
+
956
+ ## [13.4.0] - 2026-03-01
957
+
958
+ ### Added
959
+
960
+ - Added `getToolChoice` option to dynamically override tool choice per LLM call
961
+
962
+ ## [13.3.8] - 2026-02-28
963
+
964
+ ### Changed
965
+
966
+ - Changed intent field name from `agent__intent` to `_i` in tool schemas
967
+
968
+ ### Fixed
969
+
970
+ - Fixed synthetic tool result text formatting so aborted/error tool results no longer emit `Tool execution was aborted.: Request was aborted` style punctuation.
971
+
972
+ ## [13.3.7] - 2026-02-27
973
+
974
+ ### Added
975
+
976
+ - Added `lenientArgValidation` option to tools to allow graceful handling of argument validation errors by passing raw arguments to execute() instead of returning an error to the LLM
977
+
978
+ ## [13.3.1] - 2026-02-26
979
+
980
+ ### Added
981
+
982
+ - Added `topP`, `topK`, `minP`, `presencePenalty`, and `repetitionPenalty` options to `AgentOptions` for fine-grained sampling control
983
+ - Added getter and setter properties for sampling parameters on the `Agent` class to allow runtime configuration
984
+
985
+ ## [13.1.0] - 2026-02-23
986
+
987
+ ### Changed
988
+
989
+ - Removed per-tool `agent__intent` field description from injected schema to reduce token usage; intent format is now documented once in the system prompt instead of repeated in every tool definition
990
+
991
+ ## [12.19.0] - 2026-02-22
992
+
993
+ ### Changed
994
+
995
+ - Updated tool result messages to include error details when tool execution fails
996
+
997
+ ## [12.14.0] - 2026-02-19
998
+
999
+ ### Added
1000
+
1001
+ - Added `intentTracing` option to enable intent goal extraction from tool calls, allowing models to specify high-level goals via a required `_intent` field that is automatically injected into tool schemas and stripped from arguments before execution
1002
+
1003
+ ## [12.11.0] - 2026-02-19
1004
+
1005
+ ### Added
1006
+
1007
+ - Exported `AgentBusyError` exception class for handling concurrent agent operations
1008
+
1009
+ ### Changed
1010
+
1011
+ - Agent now throws `AgentBusyError` instead of generic `Error` when attempting concurrent operations
1012
+
1013
+ ## [12.8.0] - 2026-02-16
1014
+
1015
+ ### Added
1016
+
1017
+ - Added `transformToolCallArguments` option to `AgentOptions` and `AgentLoopConfig` for transforming tool call arguments before execution (e.g. secret deobfuscation)
1018
+
1019
+ ## [12.2.0] - 2026-02-13
1020
+
1021
+ ### Added
1022
+
1023
+ - Added `providerSessionState` option to share provider state map for session-scoped transport and session caches
1024
+ - Added `preferWebsockets` option to hint that websocket transport should be preferred when supported by the provider implementation
1025
+
1026
+ ## [11.10.0] - 2026-02-10
1027
+
1028
+ ### Added
1029
+
1030
+ - Added `temperature` option to `AgentOptions` to control LLM sampling temperature
1031
+ - Added `temperature` getter and setter to `Agent` class for runtime configuration
1032
+
1033
+ ## [11.6.0] - 2026-02-07
1034
+
1035
+ ### Added
1036
+
1037
+ - Added `hasQueuedMessages()` method to check for pending steering/follow-up messages
1038
+ - Resume queued steering and follow-up messages from `continue()` after auto-compaction
1039
+
1040
+ ### Changed
1041
+
1042
+ - Extracted `dequeueSteeringMessages()` and `dequeueFollowUpMessages()` from inline config callbacks
1043
+ - Added `skipInitialSteeringPoll` option to `_runLoop()` for correct queue resume ordering
1044
+
1045
+ ## [11.3.0] - 2026-02-06
1046
+
1047
+ ### Added
1048
+
1049
+ - Added `maxRetryDelayMs` option to AgentOptions to cap server-requested retry delays, allowing higher-level retry logic to handle long waits with user visibility
1050
+
1051
+ ### Changed
1052
+
1053
+ - Updated ThinkingLevel documentation to include support for gpt-5.3 and gpt-5.3-codex models with 'xhigh' thinking level
1054
+
1055
+ ## [11.2.0] - 2026-02-05
1056
+
1057
+ ### Fixed
1058
+
1059
+ - Fixed handling of aborted requests to properly throw abort errors when stream terminates without a terminal event
1060
+
1061
+ ## [10.5.0] - 2026-02-04
1062
+
1063
+ ### Added
1064
+
1065
+ - Added `concurrency` option to `AgentTool` to control tool scheduling: "shared" (default, runs in parallel) or "exclusive" (runs alone)
1066
+ - Implemented parallel execution of shared tools within a single agent turn for improved performance
1067
+
1068
+ ### Changed
1069
+
1070
+ - Refactored tool execution to support concurrent scheduling with proper interrupt handling and steering message checks
1071
+
1072
+ ## [9.2.2] - 2026-01-31
1073
+
1074
+ ### Added
1075
+
1076
+ - Added toolChoice option to AgentPromptOptions for controlling tool selection
1077
+
1078
+ ## [8.2.0] - 2026-01-24
1079
+
1080
+ ### Changed
1081
+
1082
+ - Updated TypeScript configuration for better publish-time configuration handling with tsconfig.publish.json
1083
+
1084
+ ## [8.0.0] - 2026-01-23
1085
+
1086
+ ### Added
1087
+
1088
+ - Added `nonAbortable` option to tools to ignore abort signals during execution
1089
+
1090
+ ## [6.8.0] - 2026-01-20
1091
+
1092
+ ### Changed
1093
+
1094
+ - Updated proxy stream processing to use utility function for reading lines
1095
+
1096
+ ## [6.2.0] - 2026-01-19
1097
+
1098
+ ### Added
1099
+
1100
+ - Enhanced getToolContext to receive tool call batch information including batchId, index, total count, and tool call details
1101
+
1102
+ ## [5.6.7] - 2026-01-18
1103
+
1104
+ ### Fixed
1105
+
1106
+ - Added proper tool result messages for tool calls that are aborted or error out
1107
+ - Ensured tool_use/tool_result pairing is maintained when tool execution fails
1108
+
1109
+ ## [4.6.0] - 2026-01-12
1110
+
1111
+ ### Changed
1112
+
1113
+ - Modified assistant message handling to split messages around tool results for improved readability when using Cursor tools
1114
+
1115
+ ### Fixed
1116
+
1117
+ - Fixed tool result ordering in Cursor mode by buffering results and emitting them at the correct position within assistant messages
1118
+
1119
+ ## [4.3.0] - 2026-01-11
1120
+
1121
+ ### Added
1122
+
1123
+ - Added `cursorExecHandlers` and `cursorOnToolResult` options for local tool execution with cursor-based streaming
1124
+ - Added `emitExternalEvent` method to allow external event injection into the agent state
1125
+
1126
+ ## [4.0.0] - 2026-01-10
1127
+
1128
+ ### Added
1129
+
1130
+ - Added `popLastSteer()` and `popLastFollowUp()` methods to remove and return the last queued message (LIFO) for dequeue operations
1131
+ - `thinkingBudgets` option on `Agent` and `AgentOptions` to customize token budgets per thinking level
1132
+ - `sessionId` option on `Agent` to forward session identifiers to LLM providers for session-based caching
1133
+
1134
+ ### Fixed
1135
+
1136
+ - `minimal` thinking level now maps to `minimal` reasoning effort instead of being treated as `low`
1137
+
1138
+ ## [3.33.0] - 2026-01-08
1139
+
1140
+ ### Fixed
1141
+
1142
+ - Ensured aborted assistant responses always include an error message for callers.
1143
+ - Filtered thinking blocks from Cerebras request context to keep multi-turn prompts compatible.
1144
+
1145
+ ## [3.21.0] - 2026-01-06
1146
+
1147
+ ### Changed
1148
+
1149
+ - Switched from local `@oh-my-pi/pi-ai` to upstream `@mariozechner/pi-ai` package
1150
+
1151
+ ### Added
1152
+
1153
+ - Added `sessionId` option for provider caching (e.g., OpenAI Codex session-based prompt caching)
1154
+ - Added `sessionId` getter/setter on Agent class for runtime session switching
1155
+
1156
+ ## [3.20.0] - 2026-01-06
1157
+
1158
+ ### Breaking Changes
1159
+
1160
+ - Replaced `queueMessage`/`queueMode` with steering + follow-up queues: use `steer`, `setSteeringMode`, and `getSteeringMode` for mid-run interruptions, and `followUp`, `setFollowUpMode`, and `getFollowUpMode` for post-turn messages
1161
+ - Agent loop callbacks now use `getSteeringMessages` and `getFollowUpMessages` instead of `getQueuedMessages`
1162
+
1163
+ ### Added
1164
+
1165
+ - Added follow-up message queue support so new user messages can continue a run after the agent would otherwise stop
1166
+ - Added `RenderResultOptions.spinnerFrame` for animated tool-result rendering
1167
+
1168
+ ### Changed
1169
+
1170
+ - `prompt()` and `continue()` now throw when the agent is already streaming; use steering or follow-up queues instead
1171
+
1172
+ ## [3.4.1337] - 2026-01-03
1173
+
1174
+ ### Added
1175
+
1176
+ - Added `popMessage()` method to Agent class for removing and retrieving the last message
1177
+ - Added abort signal checks during response streaming for faster interruption handling
1178
+
1179
+ ### Fixed
1180
+
1181
+ - Fixed abort handling to properly return aborted message state when stream is interrupted mid-response
1182
+
1183
+ ## [1.341.0] - 2026-01-03
1184
+
1185
+ ### Added
1186
+
1187
+ - Added `interruptMode` option to control when queued messages interrupt tool execution.
1188
+ - Implemented "immediate" mode (default) to check queue after each tool and interrupt remaining tools.
1189
+ - Implemented "wait" mode to defer queue processing until the entire turn completes.
1190
+ - Added getter and setter methods for `interruptMode` on Agent class.
1191
+
1192
+ ## [1.337.1] - 2026-01-02
1193
+
1194
+ ### Changed
1195
+
1196
+ - Forked to @oh-my-pi scope with unified versioning across all packages
1197
+
1198
+ ## [1.337.0] - 2026-01-02
1199
+
1200
+ Initial release under @oh-my-pi scope. See previous releases at [badlogic/pi-mono](https://github.com/badlogic/pi-mono).
1201
+
1202
+ ## [0.38.0] - 2026-01-08
1203
+
1204
+ ### Added
1205
+
1206
+ - `thinkingBudgets` option on `Agent` and `AgentOptions` to customize token budgets per thinking level ([#529](https://github.com/badlogic/pi-mono/pull/529) by [@melihmucuk](https://github.com/melihmucuk))
1207
+
1208
+ ## [0.37.3] - 2026-01-06
1209
+
1210
+ ### Added
1211
+
1212
+ - `sessionId` option on `Agent` to forward session identifiers to LLM providers for session-based caching.
1213
+
1214
+ ## [0.37.0] - 2026-01-05
1215
+
1216
+ ### Fixed
1217
+
1218
+ - `minimal` thinking level now maps to `minimal` reasoning effort instead of being treated as `low`.
1219
+
1220
+ ## [0.32.0] - 2026-01-03
1221
+
1222
+ ### Breaking Changes
1223
+
1224
+ - **Queue API replaced with steer/followUp**: The `queueMessage()` method has been split into two methods with different delivery semantics ([#403](https://github.com/badlogic/pi-mono/issues/403)):
1225
+ - `steer(msg)`: Interrupts the agent mid-run. Delivered after current tool execution, skips remaining tools.
1226
+ - `followUp(msg)`: Waits until the agent finishes. Delivered only when there are no more tool calls or steering messages.
1227
+ - **Queue mode renamed**: `queueMode` option renamed to `steeringMode`. Added new `followUpMode` option. Both control whether messages are delivered one-at-a-time or all at once.
1228
+ - **AgentLoopConfig callbacks renamed**: `getQueuedMessages` split into `getSteeringMessages` and `getFollowUpMessages`.
1229
+ - **Agent methods renamed**:
1230
+ - `queueMessage()` → `steer()` and `followUp()`
1231
+ - `clearMessageQueue()` → `clearSteeringQueue()`, `clearFollowUpQueue()`, `clearAllQueues()`
1232
+ - `setQueueMode()`/`getQueueMode()` → `setSteeringMode()`/`getSteeringMode()` and `setFollowUpMode()`/`getFollowUpMode()`
1233
+
1234
+ ### Fixed
1235
+
1236
+ - `prompt()` and `continue()` now throw if called while the agent is already streaming, preventing race conditions and corrupted state. Use `steer()` or `followUp()` to queue messages during streaming, or `await` the previous call.
1237
+
1238
+ ## [0.31.0] - 2026-01-02
1239
+
1240
+ ### Breaking Changes
1241
+
1242
+ - **Transport abstraction removed**: `ProviderTransport`, `AppTransport`, and `AgentTransport` interface have been removed. Use the `streamFn` option directly for custom streaming implementations.
1243
+ - **Agent options renamed**:
1244
+ - `transport` → removed (use `streamFn` instead)
1245
+ - `messageTransformer` → `convertToLlm`
1246
+ - `preprocessor` → `transformContext`
1247
+ - **`AppMessage` renamed to `AgentMessage`**: All references to `AppMessage` have been renamed to `AgentMessage` for consistency.
1248
+ - **`CustomMessages` renamed to `CustomAgentMessages`**: The declaration merging interface has been renamed.
1249
+ - **`UserMessageWithAttachments` and `Attachment` types removed**: Attachment handling is now the responsibility of the `convertToLlm` function.
1250
+ - **Agent loop moved from `@oh-my-pi/pi-ai`**: The `agentLoop`, `agentLoopContinue`, and related types have moved to this package. Import from `@oh-my-pi/pi-agent` instead.
1251
+
1252
+ ### Added
1253
+
1254
+ - `streamFn` option on `Agent` for custom stream implementations. Default uses `streamSimple` from pi-ai.
1255
+ - `streamProxy()` utility function for browser apps that need to proxy LLM calls through a backend server. Replaces the removed `AppTransport`.
1256
+ - `getApiKey` option for dynamic API key resolution (useful for expiring OAuth tokens like GitHub Copilot).
1257
+ - `agentLoop()` and `agentLoopContinue()` low-level functions for running the agent loop without the `Agent` class wrapper.
1258
+ - New exported types: `AgentLoopConfig`, `AgentContext`, `AgentTool`, `AgentToolResult`, `AgentToolUpdateCallback`, `StreamFn`.
1259
+
1260
+ ### Changed
1261
+
1262
+ - `Agent` constructor now has all options optional (empty options use defaults).
1263
+ - `queueMessage()` is now synchronous (no longer returns a Promise).