@oh-my-pi/pi-coding-agent 15.11.4 → 15.11.7

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 (98) hide show
  1. package/CHANGELOG.md +82 -1
  2. package/dist/cli.js +520 -451
  3. package/dist/types/cli/bench-cli.d.ts +78 -0
  4. package/dist/types/cli/usage-cli.d.ts +10 -1
  5. package/dist/types/commands/bench.d.ts +29 -0
  6. package/dist/types/commands/usage.d.ts +9 -0
  7. package/dist/types/config/model-resolver.d.ts +3 -2
  8. package/dist/types/config/settings-schema.d.ts +125 -3
  9. package/dist/types/edit/renderer.d.ts +1 -0
  10. package/dist/types/modes/components/oauth-selector.d.ts +10 -1
  11. package/dist/types/modes/components/reset-usage-selector.d.ts +12 -0
  12. package/dist/types/modes/components/session-selector.d.ts +1 -1
  13. package/dist/types/modes/components/settings-selector.d.ts +8 -1
  14. package/dist/types/modes/components/snapcompact-shape-preview.d.ts +31 -0
  15. package/dist/types/modes/components/tool-execution.d.ts +18 -0
  16. package/dist/types/modes/controllers/selector-controller.d.ts +1 -0
  17. package/dist/types/modes/interactive-mode.d.ts +10 -0
  18. package/dist/types/modes/session-observer-registry.d.ts +2 -0
  19. package/dist/types/modes/setup-wizard/scenes/sign-in.d.ts +3 -0
  20. package/dist/types/modes/setup-wizard/scenes/types.d.ts +10 -1
  21. package/dist/types/modes/setup-wizard/scenes/web-search.d.ts +3 -0
  22. package/dist/types/modes/types.d.ts +2 -0
  23. package/dist/types/modes/utils/context-usage.d.ts +6 -1
  24. package/dist/types/session/agent-session.d.ts +14 -1
  25. package/dist/types/session/auth-storage.d.ts +1 -1
  26. package/dist/types/session/codex-auto-reset.d.ts +107 -0
  27. package/dist/types/session/snapcompact-inline.d.ts +107 -4
  28. package/dist/types/slash-commands/helpers/reset-usage.d.ts +27 -0
  29. package/dist/types/task/render.d.ts +1 -0
  30. package/dist/types/tools/bash.d.ts +2 -0
  31. package/dist/types/tools/eval-render.d.ts +1 -0
  32. package/dist/types/tools/renderers.d.ts +13 -0
  33. package/dist/types/tools/ssh.d.ts +1 -0
  34. package/dist/types/tools/todo.d.ts +0 -11
  35. package/package.json +11 -11
  36. package/src/cli/bench-cli.ts +437 -0
  37. package/src/cli/usage-cli.ts +187 -16
  38. package/src/cli-commands.ts +1 -0
  39. package/src/commands/bench.ts +42 -0
  40. package/src/commands/usage.ts +8 -0
  41. package/src/config/model-registry.ts +52 -5
  42. package/src/config/model-resolver.ts +36 -5
  43. package/src/config/settings-schema.ts +148 -3
  44. package/src/config/settings.ts +9 -0
  45. package/src/edit/renderer.ts +5 -0
  46. package/src/hindsight/client.ts +26 -1
  47. package/src/hindsight/state.ts +6 -2
  48. package/src/internal-urls/docs-index.generated.ts +2 -2
  49. package/src/mcp/transports/stdio.ts +81 -7
  50. package/src/modes/components/oauth-selector.ts +67 -7
  51. package/src/modes/components/reset-usage-selector.ts +161 -0
  52. package/src/modes/components/session-selector.ts +8 -2
  53. package/src/modes/components/settings-selector.ts +89 -47
  54. package/src/modes/components/snapcompact-shape-preview-doc.md +11 -0
  55. package/src/modes/components/snapcompact-shape-preview.ts +192 -0
  56. package/src/modes/components/tool-execution.ts +26 -0
  57. package/src/modes/components/transcript-container.ts +23 -1
  58. package/src/modes/controllers/command-controller.ts +24 -1
  59. package/src/modes/controllers/input-controller.ts +8 -6
  60. package/src/modes/controllers/selector-controller.ts +72 -2
  61. package/src/modes/interactive-mode.ts +83 -0
  62. package/src/modes/session-observer-registry.ts +61 -3
  63. package/src/modes/setup-wizard/index.ts +1 -0
  64. package/src/modes/setup-wizard/scenes/glyph.ts +24 -6
  65. package/src/modes/setup-wizard/scenes/providers.ts +36 -2
  66. package/src/modes/setup-wizard/scenes/sign-in.ts +10 -1
  67. package/src/modes/setup-wizard/scenes/theme.ts +28 -1
  68. package/src/modes/setup-wizard/scenes/types.ts +10 -1
  69. package/src/modes/setup-wizard/scenes/web-search.ts +22 -6
  70. package/src/modes/setup-wizard/wizard-overlay.ts +38 -1
  71. package/src/modes/theme/theme.ts +2 -2
  72. package/src/modes/types.ts +2 -0
  73. package/src/modes/utils/context-usage.ts +75 -1
  74. package/src/prompts/bench.md +7 -0
  75. package/src/prompts/system/snapcompact-context-frames-note.md +1 -0
  76. package/src/prompts/system/snapcompact-context-stub.md +1 -0
  77. package/src/prompts/system/snapcompact-toolresult-note.md +1 -1
  78. package/src/prompts/tools/browser.md +33 -43
  79. package/src/prompts/tools/eval.md +27 -50
  80. package/src/prompts/tools/irc.md +29 -31
  81. package/src/prompts/tools/read.md +31 -37
  82. package/src/prompts/tools/todo.md +1 -2
  83. package/src/sdk.ts +4 -2
  84. package/src/session/agent-session.ts +136 -6
  85. package/src/session/auth-storage.ts +3 -0
  86. package/src/session/codex-auto-reset.ts +190 -0
  87. package/src/session/snapcompact-inline.ts +404 -75
  88. package/src/slash-commands/builtin-registry.ts +145 -8
  89. package/src/slash-commands/helpers/context-report.ts +28 -1
  90. package/src/slash-commands/helpers/reset-usage.ts +66 -0
  91. package/src/slash-commands/helpers/usage-report.ts +12 -0
  92. package/src/task/index.ts +30 -7
  93. package/src/task/render.ts +34 -19
  94. package/src/tools/bash.ts +3 -0
  95. package/src/tools/eval-render.ts +4 -0
  96. package/src/tools/renderers.ts +13 -0
  97. package/src/tools/ssh.ts +3 -0
  98. package/src/tools/todo.ts +8 -128
@@ -1,41 +1,42 @@
1
1
  /**
2
2
  * Snapcompact inline imaging: per-request transform that swaps the system
3
- * prompt and/or large historical tool results for dense PNG frames on
4
- * vision-capable models.
5
- *
3
+ * prompt, loaded context-file instructions, and/or large historical tool
4
+ * results for dense PNG frames on vision-capable models.
6
5
  * Runs inside the agent loop's `transformProviderContext` hook — after the
7
6
  * persisted history is converted to the outgoing `Context`, before the
8
7
  * provider stream call. It only ever builds NEW message objects/arrays; the
9
8
  * input context shares `content` array references with the persisted
10
9
  * `SessionMessageEntry` messages, so mutation would leak rendered images
11
10
  * into session.jsonl.
11
+ *
12
+ * The swap policy (budget, savings gate, skip rules) lives in
13
+ * `planInlineSwaps`, shared by the transform and the `/context` savings
14
+ * estimate (`estimateInlineSavings`) so the two can never disagree.
12
15
  */
16
+
13
17
  import type { Context, ImageContent, Model, TextContent, ToolResultMessage, UserMessage } from "@oh-my-pi/pi-ai";
14
18
  import { countTokens } from "@oh-my-pi/pi-natives";
15
19
  import * as snapcompact from "@oh-my-pi/snapcompact";
20
+ import contextFramesNote from "../prompts/system/snapcompact-context-frames-note.md" with { type: "text" };
21
+ import contextStub from "../prompts/system/snapcompact-context-stub.md" with { type: "text" };
16
22
  import systemFramesNote from "../prompts/system/snapcompact-system-frames-note.md" with { type: "text" };
17
23
  import systemStub from "../prompts/system/snapcompact-system-stub.md" with { type: "text" };
18
24
  import toolResultNote from "../prompts/system/snapcompact-toolresult-note.md" with { type: "text" };
19
25
 
26
+ export type SnapcompactSystemPromptMode = "none" | "agents-md" | "all";
27
+
20
28
  export interface SnapcompactInlineOptions {
21
- renderSystemPrompt: boolean;
29
+ renderSystemPrompt: SnapcompactSystemPromptMode;
22
30
  renderToolResults: boolean;
31
+ /** Frame variant override; `"auto"`/omitted picks the provider's eval winner. */
32
+ shape?: snapcompact.ShapeVariantName | "auto";
23
33
  }
24
34
 
25
- /**
26
- * Image-count budget per provider. Snapcompact frames are 1568px (<2000px) so
27
- * dimension/size limits never bind; only COUNT does. Strictest mainstream is
28
- * Groq (~5), so unknown providers get the safe floor.
29
- */
30
- const INLINE_IMAGE_BUDGET_BY_PROVIDER: Record<string, number> = {
31
- anthropic: 90,
32
- "amazon-bedrock": 90,
33
- openai: 200,
34
- google: 200,
35
- "google-vertex": 200,
36
- "google-gemini-cli": 200,
37
- };
38
- const DEFAULT_INLINE_IMAGE_BUDGET = 5;
35
+ // Per-provider image-count budgets live in @oh-my-pi/snapcompact
36
+ // (`providerImageBudget`): snapcompact frames are 1568px (<2000px) so
37
+ // dimension/size limits never bind; only COUNT does. Once the budget is
38
+ // spent (e.g. OpenRouter's hard 8-image cap, already consumed by archive
39
+ // frames), tool results ship verbatim as text.
39
40
  const MAX_SYSTEM_PROMPT_FRAMES = 6;
40
41
  /** Tool results under this many tokens are never rasterized — the swap can't
41
42
  * save enough to justify trading crisp text for an image. */
@@ -65,6 +66,318 @@ function passesSavingsGate(frames: number, shape: snapcompact.Shape, textTokens:
65
66
  return frames * shape.frameTokenEstimate <= textTokens * SAVINGS_MARGIN;
66
67
  }
67
68
 
69
+ interface SystemPromptImageTarget {
70
+ scope: Exclude<SnapcompactSystemPromptMode, "none">;
71
+ text: string;
72
+ replacement: string[];
73
+ userNote: string;
74
+ }
75
+
76
+ const CONTEXT_SECTION_PATTERNS = [
77
+ /<context>\n[\s\S]*?\n<\/context>/g,
78
+ /## Context\n<instructions>\n[\s\S]*?\n<\/instructions>/g,
79
+ ] as const;
80
+
81
+ function replaceContextSections(block: string, extracted: string[]): string {
82
+ let replaced = block;
83
+ for (const pattern of CONTEXT_SECTION_PATTERNS) {
84
+ replaced = replaced.replace(pattern, match => {
85
+ extracted.push(match.trim());
86
+ return contextStub.trim();
87
+ });
88
+ }
89
+ return replaced;
90
+ }
91
+
92
+ function selectSystemPromptImageTarget(
93
+ systemPrompt: readonly string[] | undefined,
94
+ mode: SnapcompactSystemPromptMode,
95
+ ): SystemPromptImageTarget | undefined {
96
+ if (!systemPrompt?.length || mode === "none") return undefined;
97
+ if (mode === "all") {
98
+ const text = systemPrompt.join("\n\n");
99
+ if (!text) return undefined;
100
+ return {
101
+ scope: "all",
102
+ text,
103
+ replacement: [systemStub],
104
+ userNote: systemFramesNote,
105
+ };
106
+ }
107
+
108
+ const extracted: string[] = [];
109
+ const replacement = systemPrompt.map(block => replaceContextSections(block, extracted));
110
+ const text = extracted.join("\n\n");
111
+ if (!text) return undefined;
112
+ return {
113
+ scope: "agents-md",
114
+ text,
115
+ replacement,
116
+ userNote: contextFramesNote,
117
+ };
118
+ }
119
+
120
+ // ============================================================================
121
+ // Swap planning (shared by the live transform and /context estimation)
122
+ // ============================================================================
123
+
124
+ /** Tool-result swap candidate, in context order. */
125
+ export interface InlineToolResultCandidate {
126
+ /** toolCallId — stable identity for render caching and application. */
127
+ id: string;
128
+ /** Token count of the joined text blocks (0 when empty or image-carrying). */
129
+ textTokens: number;
130
+ /** Frames needed to render the text (0 = empty or below the token floor). */
131
+ frames: number;
132
+ /** Already carries an image (screenshot etc.) — never re-imaged. */
133
+ hasImage: boolean;
134
+ }
135
+
136
+ export interface InlineSystemPromptCandidate {
137
+ textTokens: number;
138
+ frames: number;
139
+ }
140
+
141
+ export interface InlinePlanInput {
142
+ options: SnapcompactInlineOptions;
143
+ shape: snapcompact.Shape;
144
+ /** Provider image-count budget minus images already present in the context. */
145
+ budget: number;
146
+ /** All tool results in context order, INCLUDING the most recent one. */
147
+ toolResults: readonly InlineToolResultCandidate[];
148
+ /** Selected prompt text; undefined when system-prompt imaging is off or empty. */
149
+ systemPrompt: InlineSystemPromptCandidate | undefined;
150
+ /** Whether a user message exists to carry the prompt frames. */
151
+ hasUserMessage: boolean;
152
+ }
153
+
154
+ export interface InlineSwapPlan {
155
+ /** Tool results to swap, oldest first. */
156
+ toolResults: Array<{ id: string; textTokens: number; frames: number }>;
157
+ /** Set when the system prompt should swap to frames (uses leftover budget). */
158
+ systemPrompt: InlineSystemPromptCandidate | undefined;
159
+ }
160
+
161
+ /**
162
+ * Decide which content gets swapped for frames. Pure — the same rules drive
163
+ * the provider-request transform and the /context savings estimate.
164
+ */
165
+ export function planInlineSwaps(input: InlinePlanInput): InlineSwapPlan {
166
+ let budget = input.budget;
167
+
168
+ const toolResults: InlineSwapPlan["toolResults"] = [];
169
+ if (input.options.renderToolResults) {
170
+ // Oldest-first for cache-stable bytes; skip the LAST tool result so the
171
+ // freshest output stays crisp text. A candidate too big for the
172
+ // remaining budget is skipped, not a stop — later smaller ones may fit.
173
+ for (let k = 0; k < input.toolResults.length - 1 && budget > 0; k++) {
174
+ const candidate = input.toolResults[k];
175
+ if (candidate.hasImage) continue;
176
+ if (candidate.textTokens < MIN_TOOL_RESULT_TOKENS) continue;
177
+ if (candidate.frames === 0 || candidate.frames > budget) continue;
178
+ if (!passesSavingsGate(candidate.frames, input.shape, candidate.textTokens)) continue;
179
+ toolResults.push({ id: candidate.id, textTokens: candidate.textTokens, frames: candidate.frames });
180
+ budget -= candidate.frames;
181
+ }
182
+ }
183
+
184
+ let systemPrompt: InlineSystemPromptCandidate | undefined;
185
+ if (
186
+ input.options.renderSystemPrompt !== "none" &&
187
+ input.systemPrompt &&
188
+ budget > 0 &&
189
+ input.systemPrompt.frames > 0 &&
190
+ input.systemPrompt.frames <= Math.min(budget, MAX_SYSTEM_PROMPT_FRAMES) &&
191
+ passesSavingsGate(input.systemPrompt.frames, input.shape, input.systemPrompt.textTokens) &&
192
+ // No user message to carry the frames → leave the prompt as text.
193
+ input.hasUserMessage
194
+ ) {
195
+ systemPrompt = input.systemPrompt;
196
+ }
197
+
198
+ return { toolResults, systemPrompt };
199
+ }
200
+
201
+ // ============================================================================
202
+ // /context savings estimation
203
+ // ============================================================================
204
+
205
+ /**
206
+ * Minimal structural view of a history message — both pi-ai `Message`s (the
207
+ * outgoing context) and agent-core `AgentMessage`s (the live session) satisfy
208
+ * it, so the estimator can read session state without conversion.
209
+ */
210
+ export interface InlineMessageView {
211
+ role: string;
212
+ toolCallId?: string;
213
+ content?: unknown;
214
+ }
215
+
216
+ export interface SnapcompactSavingsEstimate {
217
+ /** Frames only ship on models that accept image input. */
218
+ visionCapable: boolean;
219
+ /** Present iff system-prompt imaging is enabled. */
220
+ systemPrompt?: {
221
+ applied: boolean;
222
+ /** Why the prompt stays text when `applied` is false. */
223
+ reason?: "empty" | "margin" | "budget";
224
+ textTokens: number;
225
+ frames: number;
226
+ /** Estimated billed tokens for the frames (0 when there are none). */
227
+ imageTokens: number;
228
+ savedTokens: number;
229
+ scope: Exclude<SnapcompactSystemPromptMode, "none">;
230
+ };
231
+ /** Present iff tool-result imaging is enabled. */
232
+ toolResults?: {
233
+ /** Tool results currently in history. */
234
+ total: number;
235
+ swapped: number;
236
+ /** Text tokens of the swapped results only. */
237
+ textTokens: number;
238
+ frames: number;
239
+ imageTokens: number;
240
+ savedTokens: number;
241
+ };
242
+ /** Net estimated wire savings for the next request. */
243
+ savedTokens: number;
244
+ }
245
+
246
+ /** Loose block-array view of unknown message content. */
247
+ type BlockViews = ReadonlyArray<{ type?: unknown; text?: unknown }>;
248
+
249
+ /**
250
+ * Estimate what `SnapcompactInlineTransformer.transform` would save on the
251
+ * NEXT request, given the session's live system prompt and message history.
252
+ *
253
+ * Mirrors the transform exactly via `planInlineSwaps`, with one deliberate
254
+ * difference: `hasUserMessage` is assumed true, because the request being
255
+ * estimated is always triggered by a user prompt — even when the current
256
+ * history is still empty.
257
+ */
258
+ export function estimateInlineSavings(input: {
259
+ options: SnapcompactInlineOptions;
260
+ model: Model | undefined;
261
+ systemPrompt: readonly string[];
262
+ messages: readonly InlineMessageView[];
263
+ }): SnapcompactSavingsEstimate {
264
+ const { options, model } = input;
265
+ if (!model?.input.includes("image")) {
266
+ return { visionCapable: false, savedTokens: 0 };
267
+ }
268
+
269
+ const shape = snapcompact.resolveShape(model, options.shape);
270
+ let existingImages = 0;
271
+ for (const message of input.messages) {
272
+ if (!Array.isArray(message.content)) continue;
273
+ for (const block of message.content as BlockViews) {
274
+ if (block.type === "image") existingImages++;
275
+ }
276
+ }
277
+ const budget = snapcompact.providerImageBudget(model.provider) - existingImages;
278
+
279
+ const candidates: InlineToolResultCandidate[] = [];
280
+ if (options.renderToolResults) {
281
+ for (const message of input.messages) {
282
+ if (message.role !== "toolResult" || typeof message.toolCallId !== "string") continue;
283
+ const blocks: BlockViews = Array.isArray(message.content) ? (message.content as BlockViews) : [];
284
+ const hasImage = blocks.some(block => block.type === "image");
285
+ const text = hasImage
286
+ ? ""
287
+ : blocks
288
+ .filter(block => block.type === "text" && typeof block.text === "string")
289
+ .map(block => block.text as string)
290
+ .join("\n");
291
+ const textTokens = text.length > 0 ? countTokens(text) : 0;
292
+ candidates.push({
293
+ id: message.toolCallId,
294
+ textTokens,
295
+ frames: textTokens >= MIN_TOOL_RESULT_TOKENS ? snapcompact.frames(text, { shape }) : 0,
296
+ hasImage,
297
+ });
298
+ }
299
+ }
300
+
301
+ let systemPromptTarget: SystemPromptImageTarget | undefined;
302
+ let systemPromptCandidate: InlineSystemPromptCandidate | undefined;
303
+ if (options.renderSystemPrompt !== "none") {
304
+ systemPromptTarget = selectSystemPromptImageTarget(input.systemPrompt, options.renderSystemPrompt);
305
+ if (systemPromptTarget) {
306
+ systemPromptCandidate = {
307
+ textTokens: countTokens(systemPromptTarget.text),
308
+ frames: snapcompact.frames(systemPromptTarget.text, { shape }),
309
+ };
310
+ }
311
+ }
312
+
313
+ const plan = planInlineSwaps({
314
+ options,
315
+ shape,
316
+ budget,
317
+ toolResults: candidates,
318
+ systemPrompt: systemPromptCandidate,
319
+ hasUserMessage: true,
320
+ });
321
+
322
+ let savedTokens = 0;
323
+ let systemPromptEstimate: SnapcompactSavingsEstimate["systemPrompt"];
324
+ if (options.renderSystemPrompt !== "none") {
325
+ const candidate = systemPromptCandidate ?? { textTokens: 0, frames: 0 };
326
+ const applied = plan.systemPrompt !== undefined;
327
+ const imageTokens = candidate.frames * shape.frameTokenEstimate;
328
+ const saved = applied ? Math.max(0, candidate.textTokens - imageTokens) : 0;
329
+ let reason: "empty" | "margin" | "budget" | undefined;
330
+ if (!applied) {
331
+ const leftover = budget - plan.toolResults.reduce((sum, swap) => sum + swap.frames, 0);
332
+ if (candidate.frames === 0) reason = "empty";
333
+ else if (candidate.frames > Math.min(leftover, MAX_SYSTEM_PROMPT_FRAMES)) reason = "budget";
334
+ else reason = "margin";
335
+ }
336
+ systemPromptEstimate = {
337
+ applied,
338
+ ...(reason ? { reason } : {}),
339
+ textTokens: candidate.textTokens,
340
+ frames: candidate.frames,
341
+ imageTokens,
342
+ savedTokens: saved,
343
+ scope: systemPromptTarget?.scope ?? options.renderSystemPrompt,
344
+ };
345
+ savedTokens += saved;
346
+ }
347
+
348
+ let toolResultsEstimate: SnapcompactSavingsEstimate["toolResults"];
349
+ if (options.renderToolResults) {
350
+ let textTokens = 0;
351
+ let frames = 0;
352
+ for (const swap of plan.toolResults) {
353
+ textTokens += swap.textTokens;
354
+ frames += swap.frames;
355
+ }
356
+ const imageTokens = frames * shape.frameTokenEstimate;
357
+ const saved = Math.max(0, textTokens - imageTokens);
358
+ toolResultsEstimate = {
359
+ total: candidates.length,
360
+ swapped: plan.toolResults.length,
361
+ textTokens,
362
+ frames,
363
+ imageTokens,
364
+ savedTokens: saved,
365
+ };
366
+ savedTokens += saved;
367
+ }
368
+
369
+ return {
370
+ visionCapable: true,
371
+ ...(systemPromptEstimate ? { systemPrompt: systemPromptEstimate } : {}),
372
+ ...(toolResultsEstimate ? { toolResults: toolResultsEstimate } : {}),
373
+ savedTokens,
374
+ };
375
+ }
376
+
377
+ // ============================================================================
378
+ // Provider-request transform
379
+ // ============================================================================
380
+
68
381
  interface FrameCacheEntry {
69
382
  hash: number | bigint;
70
383
  frames: ImageContent[];
@@ -87,44 +400,72 @@ export class SnapcompactInlineTransformer {
87
400
  // rendering would lose the content entirely.
88
401
  if (!model.input.includes("image")) return context;
89
402
 
90
- const shape = snapcompact.resolveShape(model.api);
91
- let budget =
92
- (INLINE_IMAGE_BUDGET_BY_PROVIDER[model.provider] ?? DEFAULT_INLINE_IMAGE_BUDGET) - countContextImages(context);
403
+ const shape = snapcompact.resolveShape(model, this.options.shape);
404
+ const budget = snapcompact.providerImageBudget(model.provider) - countContextImages(context);
93
405
  if (budget <= 0) return context;
94
406
 
95
407
  const messages = [...context.messages];
96
- let changed = false;
97
408
 
409
+ // Collect tool-result candidates (in order) for the planner, plus the
410
+ // text/index needed to apply swaps and the live ids for cache eviction.
411
+ const candidates: InlineToolResultCandidate[] = [];
412
+ const targets = new Map<string, { index: number; message: ToolResultMessage; text: string }>();
413
+ const liveToolCallIds = new Set<string>();
98
414
  if (this.options.renderToolResults) {
99
- const toolResultIndices: number[] = [];
100
- const liveToolCallIds = new Set<string>();
101
415
  for (let i = 0; i < messages.length; i++) {
102
416
  const message = messages[i];
103
417
  if (message.role !== "toolResult") continue;
104
- toolResultIndices.push(i);
105
418
  liveToolCallIds.add(message.toolCallId);
106
- }
107
- // Oldest-first for cache-stable bytes; skip the LAST tool result so
108
- // the freshest output stays crisp text.
109
- for (let k = 0; k < toolResultIndices.length - 1 && budget > 0; k++) {
110
- const index = toolResultIndices[k];
111
- const message = messages[index] as ToolResultMessage;
112
419
  // Don't re-image results that already carry images (screenshots etc.).
113
- if (message.content.some(block => block.type === "image")) continue;
114
- const text = message.content
115
- .filter(isTextContent)
116
- .map(block => block.text)
117
- .join("\n");
118
- const textTokens = countTokens(text);
119
- if (textTokens < MIN_TOOL_RESULT_TOKENS) continue;
120
- const needed = snapcompact.frames(text, { shape });
121
- if (needed === 0 || needed > budget) continue;
122
- if (!passesSavingsGate(needed, shape, textTokens)) continue;
123
- const frames = this.#framesFor(this.#toolCache, message.toolCallId, text, shape);
124
- messages[index] = { ...message, content: [{ type: "text", text: toolResultNote }, ...frames] };
125
- budget -= frames.length;
126
- changed = true;
420
+ const hasImage = message.content.some(block => block.type === "image");
421
+ const text = hasImage
422
+ ? ""
423
+ : message.content
424
+ .filter(isTextContent)
425
+ .map(block => block.text)
426
+ .join("\n");
427
+ const textTokens = text.length > 0 ? countTokens(text) : 0;
428
+ candidates.push({
429
+ id: message.toolCallId,
430
+ textTokens,
431
+ frames: textTokens >= MIN_TOOL_RESULT_TOKENS ? snapcompact.frames(text, { shape }) : 0,
432
+ hasImage,
433
+ });
434
+ targets.set(message.toolCallId, { index: i, message, text });
127
435
  }
436
+ }
437
+
438
+ let systemPromptTarget: SystemPromptImageTarget | undefined;
439
+ let systemPromptCandidate: InlineSystemPromptCandidate | undefined;
440
+ if (this.options.renderSystemPrompt !== "none") {
441
+ systemPromptTarget = selectSystemPromptImageTarget(context.systemPrompt, this.options.renderSystemPrompt);
442
+ if (systemPromptTarget) {
443
+ systemPromptCandidate = {
444
+ textTokens: countTokens(systemPromptTarget.text),
445
+ frames: snapcompact.frames(systemPromptTarget.text, { shape }),
446
+ };
447
+ }
448
+ }
449
+
450
+ const userIndex = messages.findIndex(message => message.role === "user");
451
+ const plan = planInlineSwaps({
452
+ options: this.options,
453
+ shape,
454
+ budget,
455
+ toolResults: candidates,
456
+ systemPrompt: systemPromptCandidate,
457
+ hasUserMessage: userIndex >= 0,
458
+ });
459
+
460
+ let changed = false;
461
+ for (const swap of plan.toolResults) {
462
+ const target = targets.get(swap.id);
463
+ if (!target) continue;
464
+ const frames = this.#framesFor(this.#toolCache, swap.id, target.text, shape);
465
+ messages[target.index] = { ...target.message, content: [{ type: "text", text: toolResultNote }, ...frames] };
466
+ changed = true;
467
+ }
468
+ if (this.options.renderToolResults) {
128
469
  // Drop cache entries for tool calls no longer in the context
129
470
  // (compacted away) so the cache stays bounded by live history.
130
471
  for (const key of this.#toolCache.keys()) {
@@ -133,38 +474,26 @@ export class SnapcompactInlineTransformer {
133
474
  }
134
475
 
135
476
  let systemPrompt = context.systemPrompt;
136
- if (this.options.renderSystemPrompt && context.systemPrompt?.length && budget > 0) {
137
- const joined = context.systemPrompt.join("\n\n");
138
- const needed = snapcompact.frames(joined, { shape });
139
- const userIndex = messages.findIndex(message => message.role === "user");
140
- if (
141
- needed > 0 &&
142
- needed <= Math.min(budget, MAX_SYSTEM_PROMPT_FRAMES) &&
143
- passesSavingsGate(needed, shape, countTokens(joined)) &&
144
- // No user message to carry the frames → leave the prompt as text.
145
- userIndex >= 0
146
- ) {
147
- const hash = Bun.hash(joined);
148
- let cached = this.#systemCache;
149
- if (!cached || cached.hash !== hash) {
150
- cached = {
151
- hash,
152
- frames: snapcompact.renderMany(joined, { shape, maxFrames: MAX_SYSTEM_PROMPT_FRAMES }),
153
- };
154
- this.#systemCache = cached;
155
- }
156
- const frames = cached.frames;
157
- const original = messages[userIndex] as UserMessage;
158
- const originalContent: (TextContent | ImageContent)[] =
159
- typeof original.content === "string" ? [{ type: "text", text: original.content }] : original.content;
160
- messages[userIndex] = {
161
- ...original,
162
- content: [{ type: "text", text: systemFramesNote }, ...frames, ...originalContent],
477
+ if (plan.systemPrompt && userIndex >= 0 && systemPromptTarget) {
478
+ const hash = Bun.hash(systemPromptTarget.text);
479
+ let cached = this.#systemCache;
480
+ if (!cached || cached.hash !== hash) {
481
+ cached = {
482
+ hash,
483
+ frames: snapcompact.renderMany(systemPromptTarget.text, { shape, maxFrames: MAX_SYSTEM_PROMPT_FRAMES }),
163
484
  };
164
- systemPrompt = [systemStub];
165
- budget -= frames.length;
166
- changed = true;
485
+ this.#systemCache = cached;
167
486
  }
487
+ const frames = cached.frames;
488
+ const original = messages[userIndex] as UserMessage;
489
+ const originalContent: (TextContent | ImageContent)[] =
490
+ typeof original.content === "string" ? [{ type: "text", text: original.content }] : original.content;
491
+ messages[userIndex] = {
492
+ ...original,
493
+ content: [{ type: "text", text: systemPromptTarget.userNote }, ...frames, ...originalContent],
494
+ };
495
+ systemPrompt = systemPromptTarget.replacement;
496
+ changed = true;
168
497
  }
169
498
 
170
499
  if (!changed) return context;