@sayknow-cli/coding-agent 0.6.8 → 0.7.1

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.
@@ -1,6 +1,7 @@
1
1
  import type { ThinkingLevel } from "@sayknow-cli/agent-core";
2
2
  import {
3
3
  type Component,
4
+ PARA_PARA_STEPS,
4
5
  type PetSkinId,
5
6
  padding,
6
7
  renderPetHalfBlocks,
@@ -51,8 +52,19 @@ export interface WelcomeComponentOptions {
51
52
  continueKey?: string;
52
53
  /** Which Sayknow pet stands on the card (default red). */
53
54
  petSkin?: PetSkinId;
55
+ /**
56
+ * Sayo as an image in the card's text (kitty Unicode placeholders, already uploaded):
57
+ * the rows of each pose. Without it the card draws the pixel octopus in half blocks.
58
+ */
59
+ petImage?: { rows: number; line(pose: SayknowPixelFrameName, row: number): string };
54
60
  /** Called when a session row is opened by click or Enter. */
55
61
  onOpenSession?: (session: RecentSession) => void;
62
+ /**
63
+ * Whether a line of this card is on screen right now. When given, the pet keeps
64
+ * dancing after the intro for as long as its top row is visible, and stops for good
65
+ * once it scrolls away (changing a line above the viewport forces a full redraw).
66
+ */
67
+ isLineVisible?: (line: number) => boolean;
56
68
  }
57
69
 
58
70
  /** Left margin of the card, and the widest the card grows on wide terminals. */
@@ -89,6 +101,8 @@ const SECTION_STAGGER_MS = 55;
89
101
  const SECTION_SETTLE_MS = 90;
90
102
  const WAVE_STEP_MS = 140;
91
103
  const INTRO_MS = INTRO_POSES.length * WAVE_STEP_MS;
104
+ /** After the intro the pet does the composer pet's working dance, on loop. */
105
+ const DANCE_LOOP_MS = PARA_PARA_STEPS.reduce((sum, [, ms]) => sum + ms, 0);
92
106
 
93
107
  /** A block of rows that takes its colors together during the intro. */
94
108
  interface Section {
@@ -108,6 +122,10 @@ interface Section {
108
122
  export class WelcomeComponent implements Component {
109
123
  #animStart: number | null = null;
110
124
  #animTimer: NodeJS.Timeout | null = null;
125
+ #danceStart: number | null = null;
126
+ #danceTimer: NodeJS.Timeout | null = null;
127
+ /** Card line holding the pet's top row in the last frame; undefined when no pet is drawn. */
128
+ #markLine: number | undefined;
111
129
  #snapshot: WelcomeSnapshot;
112
130
  /** Highlighted session row while picking with the keyboard; undefined when not picking. */
113
131
  #selected: number | undefined;
@@ -142,14 +160,72 @@ export class WelcomeComponent implements Component {
142
160
  requestRender();
143
161
  this.#animTimer = setInterval(() => {
144
162
  const elapsed = performance.now() - (this.#animStart ?? 0);
145
- if (elapsed >= INTRO_MS) this.#stopAnimation();
163
+ if (elapsed >= INTRO_MS) {
164
+ this.#stopAnimation();
165
+ this.#startDance(requestRender);
166
+ }
146
167
  requestRender();
147
168
  }, INTRO_TICK_MS);
148
169
  this.#animTimer.unref?.();
149
170
  }
150
171
 
172
+ /** True while the pet is dancing after the intro. */
173
+ get dancing(): boolean {
174
+ return this.#danceTimer !== null;
175
+ }
176
+
177
+ /**
178
+ * Loop the working dance while the pet is on screen. Timers land on frame changes
179
+ * only (five per 1.6 s loop), so an idle card costs a handful of renders per second.
180
+ */
181
+ #startDance(requestRender: () => void): void {
182
+ if (!this.options.isLineVisible || this.#markLine === undefined) return;
183
+ this.#danceStart = performance.now();
184
+ const next = (): void => {
185
+ if (this.#markLine === undefined || !this.options.isLineVisible?.(this.#markLine)) {
186
+ this.#stopDance();
187
+ requestRender();
188
+ return;
189
+ }
190
+ requestRender();
191
+ this.#danceTimer = setTimeout(next, this.#msToNextDanceFrame());
192
+ this.#danceTimer.unref?.();
193
+ };
194
+ this.#danceTimer = setTimeout(next, this.#msToNextDanceFrame());
195
+ this.#danceTimer.unref?.();
196
+ }
197
+
198
+ #stopDance(): void {
199
+ if (this.#danceTimer !== null) clearTimeout(this.#danceTimer);
200
+ this.#danceTimer = null;
201
+ this.#danceStart = null;
202
+ }
203
+
204
+ #danceOffset(): number {
205
+ return this.#danceStart === null ? 0 : (performance.now() - this.#danceStart) % DANCE_LOOP_MS;
206
+ }
207
+
208
+ #msToNextDanceFrame(): number {
209
+ let t = this.#danceOffset();
210
+ for (const [, ms] of PARA_PARA_STEPS) {
211
+ if (t < ms) return Math.max(16, ms - t);
212
+ t -= ms;
213
+ }
214
+ return 16;
215
+ }
216
+
217
+ #dancePose(): SayknowPixelFrameName {
218
+ let t = this.#danceOffset();
219
+ for (const [frame, ms] of PARA_PARA_STEPS) {
220
+ if (t < ms) return frame;
221
+ t -= ms;
222
+ }
223
+ return "base";
224
+ }
225
+
151
226
  dispose(): void {
152
227
  this.#stopAnimation();
228
+ this.#stopDance();
153
229
  }
154
230
 
155
231
  #stopAnimation(): void {
@@ -247,6 +323,7 @@ export class WelcomeComponent implements Component {
247
323
 
248
324
  render(termWidth: number): string[] {
249
325
  this.#lineSessions = [];
326
+ this.#markLine = undefined;
250
327
  const gutterWidth = this.#rightGutterWidth(termWidth);
251
328
  const width = Math.max(0, termWidth - gutterWidth);
252
329
  if (width < 4) return [];
@@ -326,6 +403,8 @@ export class WelcomeComponent implements Component {
326
403
  const mark = this.#markRows();
327
404
  const markWidth = Math.max(0, ...mark.map(row => visibleWidth(row)));
328
405
  const withMark = cardWidth >= markWidth + MARK_GAP + WORDMARK_WIDTH;
406
+ // The card opens with one blank row, so the pet's top row is card line 1.
407
+ this.#markLine = withMark ? 1 : undefined;
329
408
  const withWordmark = this.logoMode !== "ascii" && cardWidth >= WORDMARK_WIDTH;
330
409
  const indent = withMark ? markWidth + MARK_GAP : 0;
331
410
  const infoWidth = Math.max(1, cardWidth - indent);
@@ -368,11 +447,22 @@ export class WelcomeComponent implements Component {
368
447
  const step = this.#animStart == null ? -1 : Math.floor((performance.now() - this.#animStart) / WAVE_STEP_MS);
369
448
  if (this.logoMode === "ascii") {
370
449
  const rows: string[] = [...MARK_ASCII];
371
- if (step >= 0 && step < INTRO_POSES.length - 1 && step % 2 === 1) rows[3] = MARK_ASCII_WAVE;
450
+ const wave =
451
+ step >= 0
452
+ ? step < INTRO_POSES.length - 1 && step % 2 === 1
453
+ : this.#danceStart !== null && this.#dancePose() === "danceR";
454
+ if (wave) rows[3] = MARK_ASCII_WAVE;
372
455
  return rows.map(row => theme.fg("accent", row));
373
456
  }
374
- const pose = step >= 0 && step < INTRO_POSES.length ? INTRO_POSES[step]! : "base";
375
- return renderPetHalfBlocks(pose, this.options.petSkin ?? "red", theme.getColorMode(), { scale: "compact" });
457
+ const pose =
458
+ step >= 0 && step < INTRO_POSES.length
459
+ ? INTRO_POSES[step]!
460
+ : this.#danceStart !== null
461
+ ? this.#dancePose()
462
+ : "base";
463
+ const image = this.options.petImage;
464
+ if (image) return Array.from({ length: image.rows }, (_, row) => image.line(pose, row));
465
+ return renderPetHalfBlocks(pose, this.options.petSkin ?? "orange", theme.getColorMode(), { scale: "compact" });
376
466
  }
377
467
 
378
468
  /** One-line title for layouts without room for the wordmark. */
@@ -7,13 +7,17 @@ import type { Component, EditorTheme, SlashCommand } from "@sayknow-cli/tui";
7
7
  import {
8
8
  Container,
9
9
  clearRenderCache,
10
+ getCellDimensions,
10
11
  getRenderCacheRetainedBytes,
11
12
  isKeyRelease,
13
+ isUnderTmux,
12
14
  Loader,
13
15
  matchesKey,
14
16
  onImageProtocolChanged,
15
17
  ProcessTerminal,
18
+ prepareSayoPlaceholderImages,
16
19
  Spacer,
20
+ TERMINAL_ID,
17
21
  Text,
18
22
  TUI,
19
23
  } from "@sayknow-cli/tui";
@@ -68,6 +72,7 @@ import type { HookInputComponent } from "./components/hook-input";
68
72
  import type { HookSelectorComponent } from "./components/hook-selector";
69
73
  import { computeIrcSplitWidths, getIrcSidebarSemanticToken, IrcSplitViewComponent } from "./components/irc-sidebar";
70
74
  import {
75
+ getPetPixelProtocol,
71
76
  getPetUnavailableWarning,
72
77
  isPetAvailable,
73
78
  isPetCapabilityProbePending,
@@ -78,7 +83,13 @@ import { resolveCurrentBranch } from "./components/status-line/git-utils";
78
83
  import type { ToolExecutionHandle } from "./components/tool-execution";
79
84
  import { StatusLineComponent } from "./components/tool-status-header";
80
85
  import { composeToolText } from "./components/tool-transcript-format";
81
- import { type RecentSession, WelcomeComponent, type WelcomeLogoMode, type WelcomeSnapshot } from "./components/welcome";
86
+ import {
87
+ type RecentSession,
88
+ WelcomeComponent,
89
+ type WelcomeComponentOptions,
90
+ type WelcomeLogoMode,
91
+ type WelcomeSnapshot,
92
+ } from "./components/welcome";
82
93
  import { BtwController } from "./controllers/btw-controller";
83
94
  import { CommandController } from "./controllers/command-controller";
84
95
  import { EventController } from "./controllers/event-controller";
@@ -216,9 +227,14 @@ function getShellInputPrefix(isNoContext: boolean): string {
216
227
  * The pet on the launch card: the one the user keeps beside the composer, or —
217
228
  * with the pet off — the skin that matches the theme (blue for blue-octopus).
218
229
  */
230
+ /** Height of Sayo on the launch card in terminal rows (the wordmark block is 5 rows). */
231
+ const WELCOME_PET_IMAGE_ROWS = 5;
232
+ /** Kitty image ids for the launch card poses ("SY" + index; 24-bit, carried as a color). */
233
+ const WELCOME_PET_IMAGE_ID_BASE = 0x535901;
234
+
219
235
  export function resolveWelcomePetSkin(petMode: PetMode, themeName: string | undefined): PetSkinId {
220
236
  if (petMode !== "off") return petMode;
221
- return themeName?.startsWith("blue") ? "blue" : "red";
237
+ return themeName?.startsWith("blue") ? "blue" : "orange";
222
238
  }
223
239
 
224
240
  /**
@@ -788,7 +804,15 @@ export class InteractiveMode implements InteractiveModeContext {
788
804
  resumeKey: this.keybindings.getKeys("app.session.resume")[0],
789
805
  continueKey: this.keybindings.getKeys("app.session.continue")[0],
790
806
  petSkin: resolveWelcomePetSkin(settings.get("pet.mode"), getCurrentThemeName()),
807
+ petImage:
808
+ welcomeLogoMode === "unicode"
809
+ ? this.#prepareWelcomePetImage(
810
+ resolveWelcomePetSkin(settings.get("pet.mode"), getCurrentThemeName()),
811
+ )
812
+ : undefined,
791
813
  onOpenSession: session => void this.#openWelcomeSession(session),
814
+ isLineVisible: line =>
815
+ this.#welcomeComponent !== undefined && this.ui.isChildLineVisible(this.#welcomeComponent, line),
792
816
  },
793
817
  );
794
818
 
@@ -2215,6 +2239,34 @@ export class InteractiveMode implements InteractiveModeContext {
2215
2239
  this.#selectorController.showSessionSelector();
2216
2240
  }
2217
2241
 
2242
+ /**
2243
+ * Sayo as an image on the launch card, where the terminal draws kitty Unicode
2244
+ * placeholders (Ghostty, kitty outside a multiplexer: the placeholder carries the
2245
+ * image id as a 24-bit color, which tmux may not pass through). Uploads the card's
2246
+ * poses once; the card's text then refers to them. Undefined keeps the pixel octopus.
2247
+ */
2248
+ #prepareWelcomePetImage(skin: PetSkinId): WelcomeComponentOptions["petImage"] {
2249
+ if (getPetPixelProtocol() !== "kitty") return undefined;
2250
+ if (TERMINAL_ID !== "ghostty" && TERMINAL_ID !== "kitty") return undefined;
2251
+ if (isUnderTmux()) return undefined;
2252
+ try {
2253
+ const cell = getCellDimensions();
2254
+ const images = prepareSayoPlaceholderImages({
2255
+ tint: skin,
2256
+ rows: WELCOME_PET_IMAGE_ROWS,
2257
+ cellWidthPx: cell.widthPx,
2258
+ cellHeightPx: cell.heightPx,
2259
+ poses: ["base", "danceL", "danceR", "flex"],
2260
+ idBase: WELCOME_PET_IMAGE_ID_BASE,
2261
+ });
2262
+ this.ui.terminal.write(images.upload);
2263
+ return images;
2264
+ } catch (error) {
2265
+ logger.debug("Launch card pet image unavailable", { error: String(error) });
2266
+ return undefined;
2267
+ }
2268
+ }
2269
+
2218
2270
  #currentSessionFileCanonical(): string | undefined {
2219
2271
  const currentFile = this.sessionManager.getSessionFile();
2220
2272
  return currentFile ? canonicalPath(currentFile) : undefined;
@@ -1,10 +1,6 @@
1
1
  import type { AgentMessage } from "@sayknow-cli/agent-core";
2
2
  import type { CompactionSettings } from "@sayknow-cli/agent-core/compaction";
3
- import {
4
- effectiveReserveTokens,
5
- estimateMessageTokensHeuristic,
6
- resolveThresholdTokens,
7
- } from "@sayknow-cli/agent-core/compaction";
3
+ import { effectiveReserveTokens, estimateMessageTokensHeuristic } from "@sayknow-cli/agent-core/compaction";
8
4
  import type { Model } from "@sayknow-cli/ai";
9
5
  import { formatNumber } from "@sayknow-cli/utils";
10
6
  import type { AgentSession } from "../../session/agent-session";
@@ -135,7 +131,7 @@ export function computeContextBreakdown(
135
131
  if (contextWindow > 0) {
136
132
  const compactionSettings = session.settings.getGroup("compaction") as CompactionSettings;
137
133
  if (compactionSettings.enabled && compactionSettings.strategy !== "off") {
138
- const threshold = resolveThresholdTokens(contextWindow, compactionSettings);
134
+ const threshold = session.getAutoCompactionThresholdTokens(tokensForFreeSpace);
139
135
  autoCompactBufferTokens = Math.max(0, contextWindow - threshold);
140
136
  } else {
141
137
  autoCompactBufferTokens = 0;
@@ -4288,6 +4288,17 @@
4288
4288
  "packages/coding-agent/test/sdk-operation-inventory.test.ts"
4289
4289
  ]
4290
4290
  },
4291
+ {
4292
+ "sourceId": "agent_session:getAutoCompactionThresholdTokens",
4293
+ "sourceFile": "packages/coding-agent/src/session/agent-session.ts",
4294
+ "sourceKind": "agent_session",
4295
+ "decision": "exclude",
4296
+ "rationale": "internal compaction-threshold accessor feeding the /context breakdown; exposed through context.get, not an independent SDK operation",
4297
+ "exclusionMetadata": {
4298
+ "adapterMappings": "not_applicable",
4299
+ "testIds": "not_applicable"
4300
+ }
4301
+ },
4291
4302
  {
4292
4303
  "sourceId": "agent_session:compact",
4293
4304
  "sourceFile": "packages/coding-agent/src/session/agent-session.ts",
@@ -54,15 +54,18 @@ import {
54
54
  collectEntriesForBranchSummary,
55
55
  compact,
56
56
  type EmergencyCompactionSample,
57
+ effectiveReserveTokens,
57
58
  emergencyCompactionReason,
58
59
  estimateMessageTokensHeuristic,
59
60
  estimateTextTokensHeuristic,
60
61
  generateBranchSummary,
61
62
  generateHandoff,
62
63
  IMAGE_TOKEN_ESTIMATE,
64
+ isDefaultAutoThresholdCeilingApplied,
63
65
  prepareCompaction,
64
66
  type RemoteCompactionFallbackHealthEvent,
65
67
  type RemoteCompactionFallbackHealthHooks,
68
+ resolveThresholdTokens,
66
69
  type SummaryOptions,
67
70
  shouldCompact,
68
71
  } from "@sayknow-cli/agent-core/compaction";
@@ -11016,11 +11019,30 @@ export class AgentSession {
11016
11019
  const adaptive = this.#adaptiveCompactionOptions();
11017
11020
  const windowMinutes = Number.isFinite(adaptive.turnWindow) ? Math.max(1, adaptive.turnWindow) : 15;
11018
11021
  this.#adaptiveCompaction.setWindowMs(windowMinutes * 60_000);
11019
- return {
11022
+ return this.#compactionSettingsForContextPromotion({
11020
11023
  ...this.settings.getGroup("compaction"),
11021
11024
  adaptive,
11022
11025
  adaptiveState: this.#adaptiveCompaction.decisionState(),
11023
- };
11026
+ });
11027
+ }
11028
+
11029
+ /**
11030
+ * Context promotion is opt-in and exists to use the larger model's headroom. On the
11031
+ * promoted model, keep the reserve-based limit instead of compacting at the same
11032
+ * 300K default ceiling that triggered the promotion.
11033
+ */
11034
+ /** The auto-compaction threshold in tokens this session uses now (adaptive and promotion included). */
11035
+ getAutoCompactionThresholdTokens(contextTokens?: number): number {
11036
+ const contextWindow = this.model?.contextWindow ?? 0;
11037
+ if (contextWindow <= 0) return 0;
11038
+ return resolveThresholdTokens(contextWindow, this.#compactionSettingsWithAdaptive(), 0, contextTokens);
11039
+ }
11040
+
11041
+ #compactionSettingsForContextPromotion<T extends CoreCompactionSettings>(settings: T): T {
11042
+ const contextWindow = this.model?.contextWindow ?? 0;
11043
+ const promoted = this.#temporaryProviderSessionScopes.some(scope => scope.token.reason === "context-promotion");
11044
+ if (!promoted || !isDefaultAutoThresholdCeilingApplied(contextWindow, settings)) return settings;
11045
+ return { ...settings, thresholdTokens: contextWindow - effectiveReserveTokens(contextWindow, settings) };
11024
11046
  }
11025
11047
 
11026
11048
  /**
@@ -11094,10 +11116,14 @@ export class AgentSession {
11094
11116
  const compactionSettings = this.settings.getGroup("compaction");
11095
11117
  const pathEntries = this.#withoutEphemeralCustomMessageEntries(this.sessionManager.getBranch());
11096
11118
 
11097
- const preparation = prepareCompaction(pathEntries, compactionSettings, {
11098
- contextWindow: this.model.contextWindow,
11099
- tokenCorrectionRatio: this.#computeCompactionTokenCorrectionRatio(),
11100
- });
11119
+ const preparation = prepareCompaction(
11120
+ pathEntries,
11121
+ this.#compactionSettingsForContextPromotion(compactionSettings),
11122
+ {
11123
+ contextWindow: this.model.contextWindow,
11124
+ tokenCorrectionRatio: this.#computeCompactionTokenCorrectionRatio(),
11125
+ },
11126
+ );
11101
11127
  if (!preparation) {
11102
11128
  // Check why we can't compact
11103
11129
  const lastEntry = pathEntries[pathEntries.length - 1];
@@ -13224,10 +13250,14 @@ export class AgentSession {
13224
13250
  // correction only when it SHRINKS the keep window (ratio >= 1), never when
13225
13251
  // it would grow it, so recovery cannot re-overflow the provider window.
13226
13252
  const overflowRatio = this.#computeCompactionTokenCorrectionRatio();
13227
- const preparation = prepareCompaction(pathEntries, compactionSettings, {
13228
- contextWindow: this.model?.contextWindow,
13229
- tokenCorrectionRatio: overflowRatio !== undefined ? Math.max(1, overflowRatio) : undefined,
13230
- });
13253
+ const preparation = prepareCompaction(
13254
+ pathEntries,
13255
+ this.#compactionSettingsForContextPromotion(compactionSettings),
13256
+ {
13257
+ contextWindow: this.model?.contextWindow,
13258
+ tokenCorrectionRatio: overflowRatio !== undefined ? Math.max(1, overflowRatio) : undefined,
13259
+ },
13260
+ );
13231
13261
  if (autoCompactionSignal.aborted) return await emitAborted();
13232
13262
 
13233
13263
  if (!preparation) {
@@ -14303,13 +14333,25 @@ export class AgentSession {
14303
14333
  : legacyUnbounded || attemptsUsed <= retrySettings.maxRetries
14304
14334
  ? "retry"
14305
14335
  : "exhausted";
14306
- const credentialRotated =
14307
- managedFallback &&
14308
- outcome === "advance" &&
14309
- (trigger.class === "quota" || trigger.class === "rate_limit") &&
14310
- (await this.#markFailedManagedCredential(trigger));
14311
- if (credentialRotated && controller.restorePreviousEntryForRetry()) {
14312
- outcome = "retry";
14336
+ const usageLimited = trigger.class === "quota" || trigger.class === "rate_limit";
14337
+ let credentialMarked = false;
14338
+ let credentialRotated = false;
14339
+ if (managedFallback && usageLimited && outcome === "advance") {
14340
+ credentialMarked = true;
14341
+ credentialRotated = await this.#markFailedManagedCredential(trigger);
14342
+ if (credentialRotated && controller.restorePreviousEntryForRetry()) outcome = "retry";
14343
+ } else if (managedFallback && usageLimited && outcome === "retry" && this.model) {
14344
+ // Mark before retrying the same model. A pool of accounts that is now fully
14345
+ // blocked would only hand the retry another exhausted account (a wasted request
14346
+ // on a known-dead account), so move on to the next model instead. A single
14347
+ // account keeps the usual retry budget: its limit may be a short burst.
14348
+ const poolSize = this.#modelRegistry.authStorage.getSessionCredentialPoolSize(
14349
+ this.model.provider,
14350
+ this.sessionId,
14351
+ );
14352
+ credentialMarked = true;
14353
+ credentialRotated = await this.#markFailedManagedCredential(trigger);
14354
+ if (!credentialRotated && poolSize > 1) outcome = controller.advance() ? "advance" : "exhausted";
14313
14355
  }
14314
14356
  if (outcome === "exhausted") {
14315
14357
  if (managedFallback) {
@@ -14341,7 +14383,7 @@ export class AgentSession {
14341
14383
  }
14342
14384
 
14343
14385
  const retry = async (ownership?: ManagedAttemptContinuationOwnership): Promise<void> => {
14344
- if (managedFallback && !credentialRotated) await this.#markFailedManagedCredential(trigger);
14386
+ if (managedFallback && !credentialMarked) await this.#markFailedManagedCredential(trigger);
14345
14387
  let advanced = outcome !== "advance";
14346
14388
  let resolutionError: unknown;
14347
14389
  if (outcome === "advance") {
@@ -558,6 +558,10 @@ export function formatTruncationMetaNotice(truncation: TruncationMeta): string {
558
558
  } else {
559
559
  notice = `Showing ${truncation.outputLines} of ${rangeTotal}${truncation.rangeBase === "window" ? "" : " lines"}; middle elided`;
560
560
  }
561
+ // A read window cut again by the inline backstop still says where to continue.
562
+ if (truncation.nextOffset != null) {
563
+ notice += `. Use :${truncation.nextOffset} to continue`;
564
+ }
561
565
  if (truncation.artifactId != null) {
562
566
  notice += `. ${formatFullOutputReference(truncation.artifactId)}`;
563
567
  }
@@ -808,14 +812,8 @@ async function spillLargeResultToArtifact(
808
812
  maxLines: tailLines,
809
813
  });
810
814
 
811
- // Replace text blocks with single truncated block, keep images
812
- const newContent: (TextContent | ImageContent)[] = [];
813
- for (const block of result.content) {
814
- if (block.type !== "text") {
815
- newContent.push(block);
816
- }
817
- }
818
- newContent.push({ type: "text", text: truncated.content });
815
+ // Replace the text with the truncated view, keeping images where they were.
816
+ const newContent = replaceTextKeepingOrder(result.content, truncated.content);
819
817
 
820
818
  // Build truncation meta
821
819
  const outputLines = truncated.outputLines ?? truncated.totalLines;
@@ -865,6 +863,21 @@ async function spillLargeResultToArtifact(
865
863
  return { ...result, content: newContent, details: newDetails };
866
864
  }
867
865
 
866
+ /** Replace the first text block with `text`, keeping every other block in its place. */
867
+ function replaceTextKeepingOrder(content: AgentToolResult["content"], text: string): (TextContent | ImageContent)[] {
868
+ const out: (TextContent | ImageContent)[] = [];
869
+ let replaced = false;
870
+ for (const block of content) {
871
+ if (block.type !== "text") out.push(block);
872
+ else if (!replaced) {
873
+ out.push({ type: "text", text });
874
+ replaced = true;
875
+ }
876
+ }
877
+ if (!replaced) out.push({ type: "text", text });
878
+ return out;
879
+ }
880
+
868
881
  const BODY_TRUNCATION_FOOTER_KEY = "__bodyTruncationFooter";
869
882
 
870
883
  function stripBodyOwnedTruncationFooter(text: string, details: unknown): string {
@@ -885,8 +898,9 @@ function stripBodyOwnedTruncationFooter(text: string, details: unknown): string
885
898
  * closes those gaps: when `tools.maxInlineResultBytes` is configured (> 0), any
886
899
  * final result whose inline text exceeds the cap is force-saved to an artifact
887
900
  * (reusing an existing artifactId to avoid double-artifacting) and truncated to a
888
- * head+tail view that fits the cap. Disabled by default (opt-in pending
889
- * measurement); a 0 cap returns the result untouched.
901
+ * head+tail view that fits the cap. Defaults to 12 KB, chosen by the live
902
+ * tool-result A/B in gajae #5945; a 0 cap, or a context that cannot store an
903
+ * artifact, returns the result untouched.
890
904
  */
891
905
  async function enforceInlineResultBackstop(
892
906
  result: AgentToolResult,
@@ -917,6 +931,9 @@ async function enforceInlineResultBackstop(
917
931
  if (!artifactId && artifactCapability) {
918
932
  artifactId = (await artifactCapability.saveArtifact(fullText, toolName)) ?? undefined;
919
933
  }
934
+ // Without an artifact the elided text would be unrecoverable (e.g. standalone
935
+ // `skc read` has no session store), so an uncapped result beats silent loss.
936
+ if (!artifactId) return result;
920
937
 
921
938
  // Budget head+tail below the cap, reserving room for the elision marker so the
922
939
  // composed `<head>\n<marker>\n<tail>` view never exceeds the configured cap.
@@ -937,40 +954,43 @@ async function enforceInlineResultBackstop(
937
954
  truncated = truncateTail(fullText, { maxBytes: maxInlineBytes, maxLines: tailLines });
938
955
  }
939
956
 
940
- const newContent: (TextContent | ImageContent)[] = [];
941
- for (const block of result.content) {
942
- if (block.type !== "text") {
943
- newContent.push(block);
944
- }
945
- }
946
- newContent.push({ type: "text", text: truncated.content });
957
+ const newContent = replaceTextKeepingOrder(result.content, truncated.content);
947
958
 
948
959
  const outputLines = truncated.outputLines ?? truncated.totalLines;
949
960
  const outputBytes = truncated.outputBytes ?? truncated.totalBytes;
961
+ // A result already cut by the spill step, or a read window, carries the real totals;
962
+ // the intermediate view this backstop cut again does not. Keep the prior totals and a
963
+ // read window's continuation offset.
964
+ const priorTruncation = existingMeta?.truncation;
965
+ const realTotalLines = priorTruncation?.totalLines ?? truncated.totalLines;
966
+ const realTotalBytes = priorTruncation?.totalBytes ?? truncated.totalBytes;
967
+ const nextOffsetProp = priorTruncation?.nextOffset !== undefined ? { nextOffset: priorTruncation.nextOffset } : {};
950
968
  const truncationMeta: TruncationMeta =
951
969
  truncated.truncatedBy === "middle"
952
970
  ? {
953
971
  direction: "middle",
954
972
  truncatedBy: "middle",
955
- totalLines: truncated.totalLines,
956
- totalBytes: truncated.totalBytes,
973
+ totalLines: realTotalLines,
974
+ totalBytes: realTotalBytes,
957
975
  outputLines,
958
976
  outputBytes,
959
977
  maxBytes: maxInlineBytes,
960
- elidedLines: truncated.elidedLines ?? Math.max(0, truncated.totalLines - outputLines),
961
- elidedBytes: truncated.elidedBytes ?? Math.max(0, truncated.totalBytes - outputBytes),
978
+ elidedLines: Math.max(0, realTotalLines - outputLines),
979
+ elidedBytes: Math.max(0, realTotalBytes - outputBytes),
962
980
  artifactId,
981
+ ...nextOffsetProp,
963
982
  }
964
983
  : {
965
984
  direction: "tail",
966
985
  truncatedBy: truncated.truncatedBy ?? "bytes",
967
- totalLines: truncated.totalLines,
968
- totalBytes: truncated.totalBytes,
986
+ totalLines: realTotalLines,
987
+ totalBytes: realTotalBytes,
969
988
  outputLines,
970
989
  outputBytes,
971
990
  maxBytes: maxInlineBytes,
972
- shownRange: { start: truncated.totalLines - outputLines + 1, end: truncated.totalLines },
991
+ shownRange: { start: realTotalLines - outputLines + 1, end: realTotalLines },
973
992
  artifactId,
993
+ ...nextOffsetProp,
974
994
  };
975
995
 
976
996
  const newMeta: OutputMeta = { ...(existingMeta ?? {}), truncation: truncationMeta };