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

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