@sayknow-cli/coding-agent 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,7 +2,23 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
- ## [0.7.3] - 2026-09-30
5
+ ## [0.7.5] - 2026-10-05
6
+
7
+ ### Fixed
8
+
9
+ - The launch card opens the full session list without a modifier chord: press ↓ past the recent sessions to an "All sessions…" row and Enter (or click it). On macOS the card names `/resume` instead of Option+R, which types a plain `r` on Korean and other non-US layouts.
10
+
11
+ ## [0.7.4] - 2026-10-03
12
+
13
+ ### Changed
14
+
15
+ - Automatic model fallback now switches models only when the current model's quota or credits are spent (`insufficient_quota`, `usage_limit_reached`, or a rate limit whose reset is longer than `retry.maxDelayMs`) or after repeated authentication failures. Network errors, timeouts, server errors and short rate limits retry the same model within its budget and then stop with the real provider error instead of silently switching models.
16
+ - An exhausted account rotates to another logged-in account of the same provider before the model is switched.
17
+
18
+ ### Fixed
19
+
20
+ - Grok Build requests now present client version `1.0.13`; `0.2.33` was rejected by the proxy with HTTP 426. The wrapper's version wins over a stale configured header.
21
+ - Subagents inherit the language of the parent's latest user prompt, so English assignments, resumes and reminders no longer pull their reports into English; IRC auto-replies are written in the same language.
6
22
 
7
23
  ## [0.7.2] - 2026-09-29
8
24
 
@@ -1,4 +1,11 @@
1
1
  import type { Api, AssistantMessageEventStream, Context, Model, SimpleStreamOptions } from '@sayknow-cli/ai';
2
+ /**
3
+ * Client version presented to cli-chat-proxy. The proxy rejects outdated
4
+ * clients with HTTP 426 ("Your Grok CLI version (...) is outdated"), so this
5
+ * must track the minimum accepted Grok CLI release. It is applied after any
6
+ * caller/model headers so a stale configured value can never override it.
7
+ */
8
+ export declare const GROK_CLI_VERSION = "1.0.13";
2
9
  /**
3
10
  * Stream function that adds Grok CLI-specific headers to requests.
4
11
  *
@@ -14,6 +14,7 @@ export declare const en: {
14
14
  readonly "welcome.sessionTrail": "Recent sessions";
15
15
  readonly "welcome.noSessions": "No saved sessions";
16
16
  readonly "welcome.allSessions": "{key} all sessions";
17
+ readonly "welcome.allSessionsRow": "All sessions…";
17
18
  readonly "welcome.continue": "{key} continue";
18
19
  readonly "welcome.pick": "{key} pick";
19
20
  readonly "welcome.pickActive": "↑↓ move · ⏎ open · esc back";
@@ -41,6 +41,12 @@ export interface WelcomeComponentOptions {
41
41
  continueKey?: string;
42
42
  /** Called when a session row is opened by click or Enter. */
43
43
  onOpenSession?: (session: RecentSession) => void;
44
+ /**
45
+ * Opens the full session list. When set, the card ends its session rows with an
46
+ * "all sessions" row reached with ↓/Enter or a click: no modifier chord, so it works in
47
+ * every terminal and keyboard layout (Option+R types a plain `r` on Korean layouts).
48
+ */
49
+ onShowAllSessions?: () => void;
44
50
  }
45
51
  /**
46
52
  * Sayknow-CLI launch card: the wordmark, model and workspace, release note,
@@ -63,7 +69,7 @@ export declare class WelcomeComponent implements Component {
63
69
  setRecentSessions(sessions: RecentSession[]): void;
64
70
  /** Merge newly probed workspace facts into the card. */
65
71
  setSnapshot(patch: WelcomeSnapshot): void;
66
- /** Rows that can be opened right now. Zero once the card stops taking input. */
72
+ /** Rows that can be picked right now (sessions, then "all sessions"). Zero once the card stops taking input. */
67
73
  get openableCount(): number;
68
74
  get selectedIndex(): number | undefined;
69
75
  /** Stop offering the session rows (after the first prompt or a session switch). */
@@ -21,6 +21,7 @@ import { MCPManager } from "../runtime-mcp";
21
21
  import { AgentSession, type ForkContextSeed } from "../session/agent-session";
22
22
  import type { AuthStorage } from "../session/auth-storage";
23
23
  import { discoverAuthStorage } from "../session/auth-storage-discovery";
24
+ import type { DetectedLanguage } from "../session/response-language";
24
25
  import { SessionManager } from "../session/session-manager";
25
26
  import { type BuildSystemPromptResult } from "../system-prompt";
26
27
  import { BashTool, BUILTIN_TOOLS, createTools, EditTool, EvalTool, FindTool, HIDDEN_TOOLS, type LspStartupServerInfo, loadSshTool, ReadTool, ResolveTool, SearchTool, type Tool, type ToolSession, WebSearchTool, WriteTool } from "../tools";
@@ -138,6 +139,8 @@ export interface CreateAgentSessionOptions {
138
139
  parentHindsightSessionState?: HindsightSessionState;
139
140
  /** Pre-allocated agent identity for IRC routing. Default: "0-Main" for top-level, parentTaskPrefix-derived for sub. */
140
141
  agentId?: string;
142
+ /** Language of the parent's latest user prompt; subagents answer in it. */
143
+ responseLanguage?: DetectedLanguage;
141
144
  /** Display name for the agent in IRC. Default: "main" or "sub". */
142
145
  agentDisplayName?: string;
143
146
  /** Compact task label for hidden IRC roster reminders. */
@@ -100,6 +100,7 @@ import type { CheckpointState } from "../tools/checkpoint";
100
100
  import { type TodoItem, type TodoPhase } from "../tools/todo-write";
101
101
  import { type WorkspaceTree } from "../workspace-tree";
102
102
  import { type DefaultModelSelectionResult } from "./default-model-selection";
103
+ import { type DetectedLanguage } from "./response-language";
103
104
  export { DefaultModelSelectionRecoveryError } from "./default-model-selection";
104
105
  import type { ClientBridge, ClientBridgePermissionOption, ClientBridgePermissionOutcome, ClientBridgePermissionToolCall } from "./client-bridge";
105
106
  import { type ContributionPrepOptions, type ContributionPrepResult } from "./contribution-prep";
@@ -317,6 +318,12 @@ export interface AgentSessionConfig {
317
318
  agentId?: string;
318
319
  /** Shared agent registry (for forwarding IRC observations to the main session UI). */
319
320
  agentRegistry?: AgentRegistry;
321
+ /**
322
+ * Language of the user prompt that started this agent (inherited by subagents).
323
+ * Agent-attributed prompts and IRC replies are answered in it, so a delegated
324
+ * task does not drift into the language of its (usually English) assignment.
325
+ */
326
+ responseLanguage?: DetectedLanguage;
320
327
  /**
321
328
  * Override the provider-facing session ID for all API requests from this session.
322
329
  * When absent, `sessionManager.getSessionId()` is used. Needed when benchmark or
@@ -1222,6 +1229,8 @@ export declare class AgentSession {
1222
1229
  /** Test seam: drive the pre-prompt emergency/threshold check directly. */
1223
1230
  runPrePromptContextCheckForTests(pendingMessages?: readonly AgentMessage[]): Promise<void>;
1224
1231
  setRetainedMemorySampler(sampler: (() => RetainedMemorySample) | undefined): void;
1232
+ /** Language user-facing replies should use: latest user prompt, else inherited from the parent. */
1233
+ getResponseLanguage(): DetectedLanguage | undefined;
1225
1234
  /**
1226
1235
  * Toggle auto-compaction setting.
1227
1236
  */
@@ -17,7 +17,12 @@ export interface FallbackFailure {
17
17
  triggerClass: FallbackTriggerClass;
18
18
  reason: string;
19
19
  }
20
- export type FallbackFailureResult = "retry" | "advance" | "exhausted";
20
+ /**
21
+ * `stop`: the current model failed transiently past its retry budget. The run
22
+ * ends with an error but the model stays selected — transient failures never
23
+ * switch models.
24
+ */
25
+ export type FallbackFailureResult = "retry" | "advance" | "stop" | "exhausted";
21
26
  /**
22
27
  * In-memory policy state for one fallback-chain scope. A controller is deliberately
23
28
  * not serializable: configured chain intent is durable, current position is not.
@@ -49,7 +54,17 @@ export declare class FallbackChainController {
49
54
  selector: string;
50
55
  reason: string;
51
56
  }>): void;
52
- onAttemptFailure(triggerClass: FallbackTriggerClass, reason: string): FallbackFailureResult;
57
+ /**
58
+ * Model switching is reserved for failures the current model cannot recover
59
+ * from: exhausted quota/credits (advance at once; the session first rotates to
60
+ * another logged-in account) and authentication failures (after the per-model
61
+ * budget). Network, timeout, server and short rate-limit failures are
62
+ * transient: they retry the SAME model within its budget and then stop with
63
+ * an error instead of silently switching to a different model.
64
+ */
65
+ onAttemptFailure(triggerClass: FallbackTriggerClass, reason: string, options?: {
66
+ credentialRotated?: boolean;
67
+ }): FallbackFailureResult;
53
68
  advance(): boolean;
54
69
  /**
55
70
  * Restore the entry that just advanced for one attempt with a rotated credential.
@@ -15,6 +15,7 @@ import { AgentRegistry } from "../registry/agent-registry";
15
15
  import type { ForkContextSeed } from "../session/agent-session";
16
16
  import type { ArtifactManager } from "../session/artifacts";
17
17
  import type { AuthStorage } from "../session/auth-storage";
18
+ import type { DetectedLanguage } from "../session/response-language";
18
19
  import { SessionManager } from "../session/session-manager";
19
20
  import type { ContextFileEntry } from "../tools";
20
21
  import type { EventBus } from "../utils/event-bus";
@@ -89,6 +90,8 @@ export interface ExecutorOptions {
89
90
  parentArtifactManager?: ArtifactManager;
90
91
  managedPersistence?: ManagedTaskPersistence;
91
92
  parentHindsightSessionState?: HindsightSessionState;
93
+ /** Language of the parent's latest user prompt, inherited by the subagent. */
94
+ responseLanguage?: DetectedLanguage;
92
95
  /**
93
96
  * Parent agent's OpenTelemetry configuration. When defined, the subagent's
94
97
  * loop is started with the same tracer/hooks but its own agent identity
@@ -12,6 +12,7 @@ import type { ForkContextSeed, ForkContextSeedOptions, PurgeQueuedCustomMessages
12
12
  import type { ArtifactManager } from "../session/artifacts";
13
13
  import type { ClientBridge } from "../session/client-bridge";
14
14
  import type { CustomMessage } from "../session/messages";
15
+ import type { DetectedLanguage } from "../session/response-language";
15
16
  import type { ToolChoiceQueue } from "../session/tool-choice-queue";
16
17
  import type { SkillActiveEntry } from "../skill-state/active-state";
17
18
  import type { AgentOutputManager } from "../task/output-manager";
@@ -196,6 +197,8 @@ export interface ToolSession {
196
197
  isManagedSessionDestination?: () => boolean;
197
198
  /** Get Hindsight runtime state for this agent session. */
198
199
  getHindsightSessionState?: () => HindsightSessionState | undefined;
200
+ /** Language of the latest user prompt (for subagent inheritance). */
201
+ getResponseLanguage?: () => DetectedLanguage | undefined;
199
202
  /** Agent identity used for IRC routing. Returns the registry id (e.g. "0-Main", "0-AuthLoader"). */
200
203
  getAgentId?: () => string | null;
201
204
  /** Look up a registered tool by name (used by the eval js backend's tool bridge). */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/coding-agent",
4
- "version": "0.7.3",
4
+ "version": "0.7.5",
5
5
  "description": "Sayknow-CLI CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -54,12 +54,12 @@
54
54
  "@agentclientprotocol/sdk": "1.3.0",
55
55
  "@babel/parser": "^7.29.3",
56
56
  "@mozilla/readability": "^0.6.0",
57
- "@sayknow-cli/stats": "0.7.3",
58
- "@sayknow-cli/agent-core": "0.7.3",
59
- "@sayknow-cli/ai": "0.7.3",
60
- "@sayknow-cli/natives": "0.7.3",
61
- "@sayknow-cli/tui": "0.7.3",
62
- "@sayknow-cli/utils": "0.7.3",
57
+ "@sayknow-cli/stats": "0.7.5",
58
+ "@sayknow-cli/agent-core": "0.7.5",
59
+ "@sayknow-cli/ai": "0.7.5",
60
+ "@sayknow-cli/natives": "0.7.5",
61
+ "@sayknow-cli/tui": "0.7.5",
62
+ "@sayknow-cli/utils": "0.7.5",
63
63
  "@puppeteer/browsers": "^2.13.0",
64
64
  "@types/turndown": "5.0.6",
65
65
  "@xterm/headless": "^6.0.0",
@@ -55,6 +55,7 @@ const LOCKED_EXCLUSIONS: Readonly<Record<string, string>> = {
55
55
  "agent_session:peekStandingResolveHandler": "internal accessor/plumbing, not a user-facing control seam",
56
56
  "agent_session:setStandingResolveHandler": "internal accessor/plumbing, not a user-facing control seam",
57
57
  "agent_session:buildForkContextSeed": "internal accessor/plumbing, not a user-facing control seam",
58
+ "agent_session:getResponseLanguage": "internal accessor/plumbing, not a user-facing control seam",
58
59
  "agent_session:getHindsightSessionState": "internal accessor/plumbing, not a user-facing control seam",
59
60
  "agent_session:setHindsightSessionState": "internal accessor/plumbing, not a user-facing control seam",
60
61
  "agent_session:markPlanCompactAbortPending": "internal accessor/plumbing, not a user-facing control seam",
@@ -10,7 +10,7 @@ providers:
10
10
  headers:
11
11
  x-xai-token-auth: xai-grok-cli
12
12
  x-grok-client-identifier: skc-grok-cli
13
- x-grok-client-version: 0.2.33
13
+ x-grok-client-version: 1.0.13
14
14
  models:
15
15
  - id: grok-composer-2.5-fast
16
16
  name: Composer 2.5 Fast
@@ -7,7 +7,13 @@ import type {
7
7
  } from '@sayknow-cli/ai';
8
8
  import { streamOpenAIResponses } from '@sayknow-cli/ai/providers/openai-responses';
9
9
 
10
- const GROK_CLI_VERSION = '0.2.33';
10
+ /**
11
+ * Client version presented to cli-chat-proxy. The proxy rejects outdated
12
+ * clients with HTTP 426 ("Your Grok CLI version (...) is outdated"), so this
13
+ * must track the minimum accepted Grok CLI release. It is applied after any
14
+ * caller/model headers so a stale configured value can never override it.
15
+ */
16
+ export const GROK_CLI_VERSION = '1.0.13';
11
17
 
12
18
  /**
13
19
  * Stream function that adds Grok CLI-specific headers to requests.
@@ -14,6 +14,7 @@ export const de: Partial<Record<MsgKey, string>> = {
14
14
  "welcome.sessionTrail": "Sitzungsverlauf",
15
15
  "welcome.noSessions": "Keine gespeicherten Verläufe",
16
16
  "welcome.allSessions": "{key} alle Sitzungen",
17
+ "welcome.allSessionsRow": "Alle Sitzungen…",
17
18
  "welcome.continue": "{key} fortsetzen",
18
19
  "welcome.pick": "{key} wählen",
19
20
  "welcome.pickActive": "↑↓ bewegen · ⏎ öffnen · esc zurück",
@@ -19,6 +19,7 @@ export const en = {
19
19
  "welcome.sessionTrail": "Recent sessions",
20
20
  "welcome.noSessions": "No saved sessions",
21
21
  "welcome.allSessions": "{key} all sessions",
22
+ "welcome.allSessionsRow": "All sessions…",
22
23
  "welcome.continue": "{key} continue",
23
24
  "welcome.pick": "{key} pick",
24
25
  "welcome.pickActive": "↑↓ move · ⏎ open · esc back",
@@ -14,6 +14,7 @@ export const es: Partial<Record<MsgKey, string>> = {
14
14
  "welcome.sessionTrail": "Historial de sesión",
15
15
  "welcome.noSessions": "Sin historiales guardados",
16
16
  "welcome.allSessions": "{key} todas las sesiones",
17
+ "welcome.allSessionsRow": "Todas las sesiones…",
17
18
  "welcome.continue": "{key} continuar",
18
19
  "welcome.pick": "{key} elegir",
19
20
  "welcome.pickActive": "↑↓ mover · ⏎ abrir · esc volver",
@@ -14,6 +14,7 @@ export const fr: Partial<Record<MsgKey, string>> = {
14
14
  "welcome.sessionTrail": "Historique de session",
15
15
  "welcome.noSessions": "Aucun historique enregistré",
16
16
  "welcome.allSessions": "{key} toutes les sessions",
17
+ "welcome.allSessionsRow": "Toutes les sessions…",
17
18
  "welcome.continue": "{key} reprendre",
18
19
  "welcome.pick": "{key} choisir",
19
20
  "welcome.pickActive": "↑↓ déplacer · ⏎ ouvrir · esc retour",
@@ -11,6 +11,7 @@ export const ja: Partial<Record<MsgKey, string>> = {
11
11
  "welcome.sessionTrail": "セッション履歴",
12
12
  "welcome.noSessions": "保存されたセッションなし",
13
13
  "welcome.allSessions": "{key} すべて表示",
14
+ "welcome.allSessionsRow": "すべてのセッション…",
14
15
  "welcome.continue": "{key} 続ける",
15
16
  "welcome.pick": "{key} 選択",
16
17
  "welcome.pickActive": "↑↓ 移動 · ⏎ 開く · esc 戻る",
@@ -11,6 +11,7 @@ export const ko: Partial<Record<MsgKey, string>> = {
11
11
  "welcome.sessionTrail": "최근 세션",
12
12
  "welcome.noSessions": "저장된 세션 없음",
13
13
  "welcome.allSessions": "{key} 전체 보기",
14
+ "welcome.allSessionsRow": "전체 세션 보기…",
14
15
  "welcome.continue": "{key} 이어하기",
15
16
  "welcome.pick": "{key} 선택",
16
17
  "welcome.pickActive": "↑↓ 이동 · ⏎ 열기 · esc 닫기",
@@ -11,6 +11,7 @@ export const zh: Partial<Record<MsgKey, string>> = {
11
11
  "welcome.sessionTrail": "会话记录",
12
12
  "welcome.noSessions": "暂无已保存会话",
13
13
  "welcome.allSessions": "{key} 查看全部",
14
+ "welcome.allSessionsRow": "全部会话…",
14
15
  "welcome.continue": "{key} 继续",
15
16
  "welcome.pick": "{key} 选择",
16
17
  "welcome.pickActive": "↑↓ 移动 · ⏎ 打开 · esc 返回",
@@ -43,6 +43,12 @@ export interface WelcomeComponentOptions {
43
43
  continueKey?: string;
44
44
  /** Called when a session row is opened by click or Enter. */
45
45
  onOpenSession?: (session: RecentSession) => void;
46
+ /**
47
+ * Opens the full session list. When set, the card ends its session rows with an
48
+ * "all sessions" row reached with ↓/Enter or a click: no modifier chord, so it works in
49
+ * every terminal and keyboard layout (Option+R types a plain `r` on Korean layouts).
50
+ */
51
+ onShowAllSessions?: () => void;
46
52
  }
47
53
 
48
54
  /** Left margin of the card, and the widest the card grows on wide terminals. */
@@ -155,9 +161,15 @@ export class WelcomeComponent implements Component {
155
161
  return this.recentSessions.slice(0, SESSION_ROWS).filter(session => session.path);
156
162
  }
157
163
 
158
- /** Rows that can be opened right now. Zero once the card stops taking input. */
164
+ /** Whether the card ends with the "all sessions" row. */
165
+ #hasAllSessionsRow(): boolean {
166
+ return !!this.options.onShowAllSessions && this.recentSessions.length > 0;
167
+ }
168
+
169
+ /** Rows that can be picked right now (sessions, then "all sessions"). Zero once the card stops taking input. */
159
170
  get openableCount(): number {
160
- return this.#interactive ? this.#openable().length : 0;
171
+ if (!this.#interactive) return 0;
172
+ return this.#openable().length + (this.#hasAllSessionsRow() ? 1 : 0);
161
173
  }
162
174
 
163
175
  get selectedIndex(): number | undefined {
@@ -200,20 +212,35 @@ export class WelcomeComponent implements Component {
200
212
 
201
213
  /** Open the highlighted row. */
202
214
  openSelected(): boolean {
203
- const session = this.#selected === undefined ? undefined : this.#openable()[this.#selected];
204
- if (!session) return false;
205
- this.options.onOpenSession?.(session);
206
- return true;
215
+ return this.#open(this.#selected);
207
216
  }
208
217
 
209
218
  handleClick(line: number): boolean {
210
219
  if (!this.#interactive) return false;
211
220
  const index = this.#lineSessions[line];
212
- const session = index === undefined ? undefined : this.#openable()[index];
213
- if (!session) return false;
221
+ if (index === undefined) return false;
214
222
  this.#selected = index;
215
- this.options.onOpenSession?.(session);
216
- return true;
223
+ if (this.#open(index)) return true;
224
+ this.#selected = undefined;
225
+ return false;
226
+ }
227
+
228
+ /** Open a picked row: a session, or the full list for the trailing "all sessions" row. */
229
+ #open(index: number | undefined): boolean {
230
+ if (index === undefined) return false;
231
+ const openable = this.#openable();
232
+ const session = openable[index];
233
+ if (session) {
234
+ this.options.onOpenSession?.(session);
235
+ return true;
236
+ }
237
+ if (index === openable.length && this.#hasAllSessionsRow()) {
238
+ // The picker takes over; leave the card un-highlighted for when it closes.
239
+ this.#selected = undefined;
240
+ this.options.onShowAllSessions?.();
241
+ return true;
242
+ }
243
+ return false;
217
244
  }
218
245
 
219
246
  // ── Layout ──────────────────────────────────────────────────────────────
@@ -437,6 +464,17 @@ export class WelcomeComponent implements Component {
437
464
  );
438
465
  sessionRows.push(openIndex >= 0 ? openIndex : undefined);
439
466
  });
467
+ if (this.#hasAllSessionsRow()) {
468
+ const allIndex = openable.length;
469
+ const selected = picking && this.#selected === allIndex;
470
+ const label = t("welcome.allSessionsRow");
471
+ lines.push(
472
+ selected
473
+ ? `${theme.fg("accent", "› ")}${theme.bold(theme.fg("text", label))}`
474
+ : ` ${theme.fg("dim", label)}`,
475
+ );
476
+ sessionRows.push(allIndex);
477
+ }
440
478
  return { lines, sessionRows };
441
479
  }
442
480
 
@@ -454,9 +492,15 @@ export class WelcomeComponent implements Component {
454
492
  return this.#truncate(text, width);
455
493
  }
456
494
 
495
+ /**
496
+ * How the card names the full session list. `/resume` works everywhere; a bound chord is
497
+ * shown only off macOS, where Option often types a character instead of sending Alt.
498
+ */
457
499
  #resumeKey(): string {
458
500
  const context = this.options.keyDisplayContext ?? { platform: process.platform };
459
- return this.options.resumeKey ? formatKeyHint(this.options.resumeKey, context) : "/resume";
501
+ const key = this.options.resumeKey;
502
+ if (!key || (context.platform === "darwin" && /(^|\+)alt\+/.test(key))) return "/resume";
503
+ return formatKeyHint(key, context);
460
504
  }
461
505
 
462
506
  #latestChangelogVersion(markdown: string): string {
@@ -772,6 +772,7 @@ export class InteractiveMode implements InteractiveModeContext {
772
772
  resumeKey: this.keybindings.getKeys("app.session.resume")[0],
773
773
  continueKey: this.keybindings.getKeys("app.session.continue")[0],
774
774
  onOpenSession: session => void this.#openWelcomeSession(session),
775
+ onShowAllSessions: () => this.showSessionSelector(),
775
776
  },
776
777
  );
777
778
 
@@ -4423,6 +4423,17 @@
4423
4423
  "testIds": "not_applicable"
4424
4424
  }
4425
4425
  },
4426
+ {
4427
+ "sourceId": "agent_session:getResponseLanguage",
4428
+ "sourceFile": "packages/coding-agent/src/session/agent-session.ts",
4429
+ "sourceKind": "agent_session",
4430
+ "decision": "exclude",
4431
+ "rationale": "internal accessor/plumbing, not a user-facing control seam",
4432
+ "exclusionMetadata": {
4433
+ "adapterMappings": "not_applicable",
4434
+ "testIds": "not_applicable"
4435
+ }
4436
+ },
4426
4437
  {
4427
4438
  "sourceId": "agent_session:setAutoCompactionEnabled",
4428
4439
  "sourceFile": "packages/coding-agent/src/session/agent-session.ts",
@@ -112,6 +112,7 @@ import { AgentSession, type ForkContextSeed } from "../session/agent-session";
112
112
  import type { AuthStorage } from "../session/auth-storage";
113
113
  import { applyCredentialRankingModeSetting, discoverAuthStorage } from "../session/auth-storage-discovery";
114
114
  import { type CustomMessage, convertToLlm } from "../session/messages";
115
+ import type { DetectedLanguage } from "../session/response-language";
115
116
  import { createReadonlySessionManager, SessionManager } from "../session/session-manager";
116
117
  import { formatNoModelsAvailableFallback } from "../setup/model-onboarding-guidance";
117
118
  import { closeAllConnections } from "../ssh/connection-manager";
@@ -411,6 +412,8 @@ export interface CreateAgentSessionOptions {
411
412
  parentHindsightSessionState?: HindsightSessionState;
412
413
  /** Pre-allocated agent identity for IRC routing. Default: "0-Main" for top-level, parentTaskPrefix-derived for sub. */
413
414
  agentId?: string;
415
+ /** Language of the parent's latest user prompt; subagents answer in it. */
416
+ responseLanguage?: DetectedLanguage;
414
417
  /** Display name for the agent in IRC. Default: "main" or "sub". */
415
418
  agentDisplayName?: string;
416
419
  /** Compact task label for hidden IRC roster reminders. */
@@ -1469,6 +1472,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1469
1472
  getActiveSkillPhase: () => session?.getActiveSkillPhase(),
1470
1473
  getDeepInterviewAskStage: () => session?.getDeepInterviewAskStage(),
1471
1474
  getHindsightSessionState: () => session?.getHindsightSessionState(),
1475
+ getResponseLanguage: () => session?.getResponseLanguage(),
1472
1476
  get model() {
1473
1477
  return agent?.state.model ?? model;
1474
1478
  },
@@ -2672,6 +2676,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
2672
2676
  ttsrManager,
2673
2677
  obfuscator,
2674
2678
  agentId: resolvedAgentId,
2679
+ responseLanguage: options.responseLanguage,
2675
2680
  agentRegistry,
2676
2681
  providerSessionId: options.providerSessionId,
2677
2682
  providerCacheSessionId: providerSessionId,
@@ -382,7 +382,7 @@ import {
382
382
  effectiveFallbackDelay,
383
383
  FallbackChainController,
384
384
  } from "./fallback-chain-controller";
385
- import { buildResponseLanguageReminder, detectResponseLanguage } from "./response-language";
385
+ import { buildResponseLanguageReminder, type DetectedLanguage, detectResponseLanguage } from "./response-language";
386
386
 
387
387
  export { DefaultModelSelectionRecoveryError } from "./default-model-selection";
388
388
 
@@ -644,6 +644,12 @@ export interface AgentSessionConfig {
644
644
  agentId?: string;
645
645
  /** Shared agent registry (for forwarding IRC observations to the main session UI). */
646
646
  agentRegistry?: AgentRegistry;
647
+ /**
648
+ * Language of the user prompt that started this agent (inherited by subagents).
649
+ * Agent-attributed prompts and IRC replies are answered in it, so a delegated
650
+ * task does not drift into the language of its (usually English) assignment.
651
+ */
652
+ responseLanguage?: DetectedLanguage;
647
653
  /**
648
654
  * Override the provider-facing session ID for all API requests from this session.
649
655
  * When absent, `sessionManager.getSessionId()` is used. Needed when benchmark or
@@ -1801,6 +1807,9 @@ export class AgentSession {
1801
1807
  #defaultFallbackController: FallbackChainController | undefined;
1802
1808
  #overflowMaintenanceAttempts = 0;
1803
1809
  #defaultFallbackExhaustedLastTurn = false;
1810
+ #transientStopTimestamp: number | undefined;
1811
+ /** Language of the latest genuine user prompt (or inherited from the parent agent). */
1812
+ #responseLanguage: DetectedLanguage | undefined;
1804
1813
  #fallbackInvocationId = 0;
1805
1814
  #fallbackSuppressedSelectors = new Set<string>();
1806
1815
  // Todo completion reminder state
@@ -2572,6 +2581,7 @@ export class AgentSession {
2572
2581
  this.#ttsrManager = config.ttsrManager;
2573
2582
  this.#obfuscator = config.obfuscator;
2574
2583
  this.#agentId = config.agentId;
2584
+ this.#responseLanguage = config.responseLanguage;
2575
2585
  this.#agentRegistry = config.agentRegistry;
2576
2586
  this.#providerSessionId = config.providerSessionId;
2577
2587
  this.#providerCacheSessionId = config.providerCacheSessionId;
@@ -7845,7 +7855,9 @@ export class AgentSession {
7845
7855
  const eagerTodoPrelude =
7846
7856
  !options?.synthetic && !hasPendingUserDirective ? this.#createEagerTodoPrelude(expandedText) : undefined;
7847
7857
  const uiSkillPrelude = options?.synthetic ? undefined : this.#createUiSkillPrelude(expandedText);
7848
- const languagePrelude = options?.synthetic ? undefined : this.#createResponseLanguagePrelude(expandedText);
7858
+ const languagePrelude = options?.synthetic
7859
+ ? undefined
7860
+ : this.#createResponseLanguagePrelude(expandedText, claimsGenuineUserIntent);
7849
7861
 
7850
7862
  const userContent: (TextContent | ImageContent)[] = [{ type: "text", text: expandedText }];
7851
7863
  if (options?.images) {
@@ -12175,12 +12187,20 @@ export class AgentSession {
12175
12187
  * they match, the model is never asked.
12176
12188
  */
12177
12189
  /**
12178
- * Name the user's language at the start of the turn when their message is clearly in a
12179
- * non-Latin script, so the final report after long English tool output stays in it.
12190
+ * Name the user's language at the start of the turn so the final report after long
12191
+ * English tool output stays in it. A genuine user prompt sets the language (an
12192
+ * English one clears it); agent-attributed prompts — subagent assignments, resumes,
12193
+ * reminders — keep the latest user language instead of the assignment's.
12180
12194
  */
12181
- #createResponseLanguagePrelude(promptText: string): AgentMessage | undefined {
12182
- const language = detectResponseLanguage(promptText);
12183
- if (!language) return undefined;
12195
+ #createResponseLanguagePrelude(promptText: string, fromUser: boolean): AgentMessage | undefined {
12196
+ if (fromUser) this.#responseLanguage = detectResponseLanguage(promptText);
12197
+ const language = fromUser
12198
+ ? this.#responseLanguage
12199
+ : (this.#responseLanguage ?? detectResponseLanguage(promptText));
12200
+ return language ? this.#createLanguageReminderMessage(language) : undefined;
12201
+ }
12202
+
12203
+ #createLanguageReminderMessage(language: DetectedLanguage): AgentMessage {
12184
12204
  return {
12185
12205
  role: "developer",
12186
12206
  content: [{ type: "text", text: buildResponseLanguageReminder(language) }],
@@ -12189,6 +12209,11 @@ export class AgentSession {
12189
12209
  };
12190
12210
  }
12191
12211
 
12212
+ /** Language user-facing replies should use: latest user prompt, else inherited from the parent. */
12213
+ getResponseLanguage(): DetectedLanguage | undefined {
12214
+ return this.#responseLanguage;
12215
+ }
12216
+
12192
12217
  #createUiSkillPrelude(promptText: string): AgentMessage | undefined {
12193
12218
  if (this.#planModeState?.enabled) return undefined;
12194
12219
  const matched = buildUiSkillActivationContext(promptText);
@@ -13679,6 +13704,9 @@ export class AgentSession {
13679
13704
  #isRetryableError(message: AssistantMessage): boolean {
13680
13705
  if (this.#isTerminalProviderFirstEventTimeout(message)) return false;
13681
13706
  if (message.errorMessage?.startsWith("Model fallback chain exhausted;")) return false;
13707
+ // Already gave up on this transient failure; do not start a fresh budget.
13708
+ if (this.#transientStopTimestamp !== undefined && message.timestamp === this.#transientStopTimestamp)
13709
+ return false;
13682
13710
  const transportFailure = message.transportFailure;
13683
13711
  const contextWindow = this.model?.contextWindow ?? 0;
13684
13712
  if (classifyContextOverflow(message, transportFailure, contextWindow)) return false;
@@ -14165,6 +14193,15 @@ export class AgentSession {
14165
14193
  ): { class: FallbackTriggerClass; retryAfterMs?: number } | undefined {
14166
14194
  if (classifyContextOverflow(message, transportFailure, this.model?.contextWindow ?? 0)) return undefined;
14167
14195
  const transport = classifyFallbackTrigger(transportFailure ?? { status: message.errorStatus });
14196
+ if (transport.class === "rate_limit" && transport.retryAfterMs !== undefined) {
14197
+ // A rate limit whose reset is further away than any retry would wait is a
14198
+ // spent usage window (e.g. a weekly/credit limit), not a burst: treat it as
14199
+ // exhausted quota so it rotates accounts/models instead of stalling.
14200
+ const longestRetryWaitMs = this.settings.getGroup("retry").maxDelayMs;
14201
+ if (longestRetryWaitMs > 0 && transport.retryAfterMs > longestRetryWaitMs) {
14202
+ return { class: "quota", retryAfterMs: transport.retryAfterMs };
14203
+ }
14204
+ }
14168
14205
  if (transport.class !== "other") return transport;
14169
14206
  // Managed fallback receives authoritative transport facts from the request
14170
14207
  // boundary. Once those facts classify as other, error prose must not upgrade
@@ -14328,30 +14365,40 @@ export class AgentSession {
14328
14365
  const legacyUnbounded = classification === "transient";
14329
14366
  const attemptsUsed = managedFallback ? controller.attemptsUsed || 1 : this.#retryAttempt + 1;
14330
14367
  const failedSelector = managedFallback ? controller.currentSelector() : undefined;
14331
- let outcome = managedFallback
14332
- ? controller.onAttemptFailure(trigger.class, message.errorMessage || "Unknown error")
14333
- : legacyUnbounded || attemptsUsed <= retrySettings.maxRetries
14334
- ? "retry"
14335
- : "exhausted";
14336
14368
  const usageLimited = trigger.class === "quota" || trigger.class === "rate_limit";
14337
14369
  let credentialMarked = false;
14338
14370
  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
- );
14371
+ if (managedFallback && usageLimited && this.model) {
14372
+ // Rotate to another logged-in account of the same provider first: an
14373
+ // exhausted account or a burst limit on one account is not a reason to
14374
+ // leave the model while another account can still serve it.
14352
14375
  credentialMarked = true;
14353
14376
  credentialRotated = await this.#markFailedManagedCredential(trigger);
14354
- if (!credentialRotated && poolSize > 1) outcome = controller.advance() ? "advance" : "exhausted";
14377
+ }
14378
+ let outcome = managedFallback
14379
+ ? controller.onAttemptFailure(trigger.class, message.errorMessage || "Unknown error", { credentialRotated })
14380
+ : legacyUnbounded || attemptsUsed <= retrySettings.maxRetries
14381
+ ? "retry"
14382
+ : "exhausted";
14383
+ if (managedFallback && credentialRotated && outcome === "advance" && controller.restorePreviousEntryForRetry()) {
14384
+ outcome = "retry";
14385
+ }
14386
+ if (outcome === "stop") {
14387
+ // Transient failure past the same-model retry budget: surface the real
14388
+ // provider error and keep the current model; never switch models for it.
14389
+ const attempt = this.#retryAttempt;
14390
+ this.#retryAttempt = 0;
14391
+ this.#transientStopTimestamp = message.timestamp;
14392
+ if (attempt > 0) {
14393
+ await this.#emitSessionEvent({
14394
+ type: "auto_retry_end",
14395
+ success: false,
14396
+ attempt,
14397
+ finalError: message.errorMessage,
14398
+ });
14399
+ this.#resolveRetry();
14400
+ }
14401
+ return managedOutcome ? { type: "terminal", terminal: { stopReason: "error", messages: [message] } } : false;
14355
14402
  }
14356
14403
  if (outcome === "exhausted") {
14357
14404
  if (managedFallback) {
@@ -14377,7 +14424,9 @@ export class AgentSession {
14377
14424
  ? Math.min(retryAfterMs, retrySettings.maxDelayMs)
14378
14425
  : cappedExponentialWithFullJitter(retrySettings.baseDelayMs, retrySettings.maxDelayMs, attemptsUsed);
14379
14426
 
14380
- if (managedFallback && trigger.class === "rate_limit" && trigger.retryAfterMs !== undefined && failedSelector) {
14427
+ // Only a spent quota window hides the model from later resolution; a burst
14428
+ // rate limit retries the same model and must not push later turns elsewhere.
14429
+ if (managedFallback && trigger.class === "quota" && trigger.retryAfterMs !== undefined && failedSelector) {
14381
14430
  this.#modelRegistry.suppressSelector(failedSelector, Date.now() + trigger.retryAfterMs);
14382
14431
  this.#fallbackSuppressedSelectors.add(failedSelector);
14383
14432
  }
@@ -15051,7 +15100,11 @@ export class AgentSession {
15051
15100
  ? rosterClaim.message
15052
15101
  : undefined;
15053
15102
  const { replyText: generatedReplyText } = await this.runEphemeralTurn({
15054
- promptText: incomingPrompt,
15103
+ // The reply is read by the user (main UI relay) as much as by the peer:
15104
+ // keep it in the user's language rather than the peer's English message.
15105
+ promptText: this.#responseLanguage
15106
+ ? `${incomingPrompt}\n\n${buildResponseLanguageReminder(this.#responseLanguage)}`
15107
+ : incomingPrompt,
15055
15108
  signal: args.signal,
15056
15109
  prependMessages: rosterMessage ? [rosterMessage] : undefined,
15057
15110
  prependMessagesValid: rosterClaim
@@ -20,7 +20,12 @@ export interface FallbackFailure {
20
20
  reason: string;
21
21
  }
22
22
 
23
- export type FallbackFailureResult = "retry" | "advance" | "exhausted";
23
+ /**
24
+ * `stop`: the current model failed transiently past its retry budget. The run
25
+ * ends with an error but the model stays selected — transient failures never
26
+ * switch models.
27
+ */
28
+ export type FallbackFailureResult = "retry" | "advance" | "stop" | "exhausted";
24
29
 
25
30
  /**
26
31
  * In-memory policy state for one fallback-chain scope. A controller is deliberately
@@ -107,7 +112,19 @@ export class FallbackChainController {
107
112
  this.exhaustedForTurn = this.activeIndex >= this.chain.entries.length;
108
113
  }
109
114
 
110
- onAttemptFailure(triggerClass: FallbackTriggerClass, reason: string): FallbackFailureResult {
115
+ /**
116
+ * Model switching is reserved for failures the current model cannot recover
117
+ * from: exhausted quota/credits (advance at once; the session first rotates to
118
+ * another logged-in account) and authentication failures (after the per-model
119
+ * budget). Network, timeout, server and short rate-limit failures are
120
+ * transient: they retry the SAME model within its budget and then stop with
121
+ * an error instead of silently switching to a different model.
122
+ */
123
+ onAttemptFailure(
124
+ triggerClass: FallbackTriggerClass,
125
+ reason: string,
126
+ options?: { credentialRotated?: boolean },
127
+ ): FallbackFailureResult {
111
128
  const selector = this.currentSelector();
112
129
  if (!selector || this.exhaustedForTurn) return "exhausted";
113
130
  if (!this.#attemptStarted) {
@@ -121,8 +138,17 @@ export class FallbackChainController {
121
138
  this.exhaustedForTurn = true;
122
139
  return "exhausted";
123
140
  }
141
+ if (triggerClass === "quota") {
142
+ // Another logged-in account of the same provider is still usable: stay on
143
+ // this model within its budget instead of switching models.
144
+ if (options?.credentialRotated && this.attemptsUsed < this.maxAttempts) return "retry";
145
+ return this.advance() ? "advance" : "exhausted";
146
+ }
124
147
  if (this.attemptsUsed < this.maxAttempts) return "retry";
125
- return this.advance() ? "advance" : "exhausted";
148
+ if (triggerClass === "auth") return this.advance() ? "advance" : "exhausted";
149
+ // Keep the active entry selected; the next request starts a fresh budget.
150
+ this.resetAttemptBudget();
151
+ return "stop";
126
152
  }
127
153
 
128
154
  advance(): boolean {
@@ -39,6 +39,7 @@ import type { AgentSession, AgentSessionEvent, ForkContextSeed } from "../sessio
39
39
  import type { ArtifactManager } from "../session/artifacts";
40
40
  import type { AuthStorage } from "../session/auth-storage";
41
41
  import { SKILL_PROMPT_MESSAGE_TYPE } from "../session/messages";
42
+ import type { DetectedLanguage } from "../session/response-language";
42
43
  import { SessionManager } from "../session/session-manager";
43
44
  import { truncateTail } from "../session/streaming-output";
44
45
  import { sessionRoot } from "../skc-runtime/session-layout";
@@ -251,6 +252,8 @@ export interface ExecutorOptions {
251
252
  parentArtifactManager?: ArtifactManager;
252
253
  managedPersistence?: ManagedTaskPersistence;
253
254
  parentHindsightSessionState?: HindsightSessionState;
255
+ /** Language of the parent's latest user prompt, inherited by the subagent. */
256
+ responseLanguage?: DetectedLanguage;
254
257
  /**
255
258
  * Parent agent's OpenTelemetry configuration. When defined, the subagent's
256
259
  * loop is started with the same tracer/hooks but its own agent identity
@@ -1645,6 +1648,7 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
1645
1648
  phase: "prompt",
1646
1649
  },
1647
1650
  parentHindsightSessionState: options.parentHindsightSessionState,
1651
+ responseLanguage: options.responseLanguage,
1648
1652
  parentTaskPrefix: id,
1649
1653
  agentId: id,
1650
1654
  agentDisplayName: agent.name,
package/src/task/index.ts CHANGED
@@ -1604,6 +1604,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1604
1604
  localProtocolOptions,
1605
1605
  parentArtifactManager,
1606
1606
  parentHindsightSessionState: this.session.getHindsightSessionState?.(),
1607
+ responseLanguage: this.session.getResponseLanguage?.(),
1607
1608
  parentTelemetry: this.session.getTelemetry?.(),
1608
1609
  forkContextSeed,
1609
1610
  });
@@ -1679,6 +1680,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1679
1680
  localProtocolOptions,
1680
1681
  parentArtifactManager,
1681
1682
  parentHindsightSessionState: this.session.getHindsightSessionState?.(),
1683
+ responseLanguage: this.session.getResponseLanguage?.(),
1682
1684
  parentTelemetry: this.session.getTelemetry?.(),
1683
1685
  forkContextSeed,
1684
1686
  });
@@ -22,6 +22,7 @@ import type {
22
22
  import type { ArtifactManager } from "../session/artifacts";
23
23
  import type { ClientBridge } from "../session/client-bridge";
24
24
  import type { CustomMessage } from "../session/messages";
25
+ import type { DetectedLanguage } from "../session/response-language";
25
26
  import type { ToolChoiceQueue } from "../session/tool-choice-queue";
26
27
  import type { SkillActiveEntry } from "../skill-state/active-state";
27
28
  import { TaskTool } from "../task";
@@ -274,6 +275,8 @@ export interface ToolSession {
274
275
  isManagedSessionDestination?: () => boolean;
275
276
  /** Get Hindsight runtime state for this agent session. */
276
277
  getHindsightSessionState?: () => HindsightSessionState | undefined;
278
+ /** Language of the latest user prompt (for subagent inheritance). */
279
+ getResponseLanguage?: () => DetectedLanguage | undefined;
277
280
  /** Agent identity used for IRC routing. Returns the registry id (e.g. "0-Main", "0-AuthLoader"). */
278
281
  getAgentId?: () => string | null;
279
282
  /** Look up a registered tool by name (used by the eval js backend's tool bridge). */