@f5-sales-demo/xcsh 21.14.0 → 21.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@f5-sales-demo/xcsh",
4
- "version": "21.14.0",
4
+ "version": "21.15.0",
5
5
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://github.com/f5-sales-demo/xcsh",
7
7
  "author": "Can Boluk",
@@ -61,13 +61,13 @@
61
61
  },
62
62
  "dependencies": {
63
63
  "@agentclientprotocol/sdk": "1.3.0",
64
- "@f5-sales-demo/pi-agent-core": "21.14.0",
65
- "@f5-sales-demo/pi-ai": "21.14.0",
66
- "@f5-sales-demo/pi-natives": "21.14.0",
67
- "@f5-sales-demo/pi-resource-management": "21.14.0",
68
- "@f5-sales-demo/pi-tui": "21.14.0",
69
- "@f5-sales-demo/pi-utils": "21.14.0",
70
- "@f5-sales-demo/xcsh-stats": "21.14.0",
64
+ "@f5-sales-demo/pi-agent-core": "21.15.0",
65
+ "@f5-sales-demo/pi-ai": "21.15.0",
66
+ "@f5-sales-demo/pi-natives": "21.15.0",
67
+ "@f5-sales-demo/pi-resource-management": "21.15.0",
68
+ "@f5-sales-demo/pi-tui": "21.15.0",
69
+ "@f5-sales-demo/pi-utils": "21.15.0",
70
+ "@f5-sales-demo/xcsh-stats": "21.15.0",
71
71
  "@mozilla/readability": "^0.6",
72
72
  "@sinclair/typebox": "^0.34",
73
73
  "@xterm/headless": "^6.0",
@@ -150,6 +150,9 @@ export default function herdrReporter(pi: ExtensionAPI): void {
150
150
  // Retains the fixed reason while an interactive prompt awaits the user, so an
151
151
  // agent_end duplicate cannot erase herdr's stored blocked message.
152
152
  let promptBlockedReason: string | undefined;
153
+ // Once the normalized contract is observed it is authoritative. The legacy
154
+ // event mappings remain only for older hosts that load this bundled extension.
155
+ let normalizedPhasesObserved = false;
153
156
  // Last session ref already delivered, so repeated lifecycle events do not
154
157
  // re-send an unchanged ref every turn.
155
158
  let lastSessionRefKey: string | undefined;
@@ -263,9 +266,9 @@ export default function herdrReporter(pi: ExtensionAPI): void {
263
266
  return enqueue(() => sendToHerdrSocket(socketPath, METADATA_METHOD, frame, onError));
264
267
  };
265
268
 
266
- const setPhaseLabel = (label: string): Promise<void> =>
269
+ const setPhaseLabel = (label: string, state: "idle" | "working" | "blocked" = "working"): Promise<void> =>
267
270
  reportMetadata({
268
- state_labels: { working: label },
271
+ state_labels: { [state]: label },
269
272
  ttl_ms: PHASE_LABEL_TTL_MS,
270
273
  });
271
274
 
@@ -353,7 +356,7 @@ export default function herdrReporter(pi: ExtensionAPI): void {
353
356
  // in case the active session file changed (e.g. after /new, /resume, or /fork).
354
357
  pi.on("agent_start", async (_event, ctx) => {
355
358
  clearSettledTurnReconcile();
356
- await report("working");
359
+ if (!normalizedPhasesObserved) await report("working");
357
360
  await reportSession(ctx);
358
361
  });
359
362
 
@@ -361,35 +364,51 @@ export default function herdrReporter(pi: ExtensionAPI): void {
361
364
  // This is also the first point where a lazily-created session file is certain
362
365
  // to exist, so it is the backstop for capturing the resume ref.
363
366
  pi.on("agent_end", async (_event, ctx) => {
364
- await report(promptBlockedReason ? "blocked" : "idle", promptBlockedReason);
367
+ if (!normalizedPhasesObserved) await report(promptBlockedReason ? "blocked" : "idle", promptBlockedReason);
365
368
  await reportSession(ctx);
366
369
  });
367
370
 
368
371
  // Reconcile completion after the UI has had a chance to clear its streaming
369
372
  // flag. This is deliberately non-blocking so it cannot delay the next turn.
370
373
  pi.on("turn_end", (_event, ctx) => {
371
- scheduleSettledTurnReconcile(ctx);
374
+ if (!normalizedPhasesObserved) scheduleSettledTurnReconcile(ctx);
372
375
  });
373
376
 
374
377
  // An interactive prompt (permission gate, ask tool, confirm/input) is
375
378
  // awaiting the user: that is herdr's "needs attention" (blocked) state.
376
379
  pi.on("user_prompt_start", async event => {
377
380
  promptBlockedReason = getPromptBlockedReason(event.kind);
378
- void report("blocked", promptBlockedReason);
379
- await clearPhaseLabel();
381
+ if (!normalizedPhasesObserved) {
382
+ void report("blocked", promptBlockedReason);
383
+ await clearPhaseLabel();
384
+ }
380
385
  });
381
386
 
382
387
  pi.on("user_prompt_end", async (_event, ctx) => {
383
388
  promptBlockedReason = undefined;
384
- await report(ctx.isIdle() ? "idle" : "working");
389
+ if (!normalizedPhasesObserved) await report(ctx.isIdle() ? "idle" : "working");
385
390
  await reportSession(ctx);
386
- if (!ctx.isIdle()) {
391
+ if (!normalizedPhasesObserved && !ctx.isIdle()) {
387
392
  await setPhaseLabel("tool");
388
393
  }
389
394
  });
390
395
 
396
+ pi.on("turn_phase", async (event, ctx) => {
397
+ normalizedPhasesObserved = true;
398
+ const state =
399
+ event.phase === "awaiting_user"
400
+ ? "blocked"
401
+ : event.phase === "submitting" || event.phase === "thinking" || event.phase === "tool_call"
402
+ ? "working"
403
+ : "idle";
404
+ await report(state, event.phase === "awaiting_user" ? "user input required" : undefined);
405
+ await setPhaseLabel(event.phase, state);
406
+ await reportSession(ctx);
407
+ });
408
+
391
409
  // Transient phase-label metadata (thinking / tool / retry / cleanup):
392
410
  pi.on("message_update", async event => {
411
+ if (normalizedPhasesObserved) return;
393
412
  if (event.assistantMessageEvent.type === "thinking_start") {
394
413
  await setPhaseLabel("thinking");
395
414
  } else if (event.assistantMessageEvent.type === "thinking_end") {
@@ -398,26 +417,32 @@ export default function herdrReporter(pi: ExtensionAPI): void {
398
417
  });
399
418
 
400
419
  pi.on("tool_execution_start", async () => {
420
+ if (normalizedPhasesObserved) return;
401
421
  await setPhaseLabel("tool");
402
422
  });
403
423
 
404
424
  pi.on("tool_execution_end", async () => {
425
+ if (normalizedPhasesObserved) return;
405
426
  await clearPhaseLabel();
406
427
  });
407
428
 
408
429
  pi.on("auto_retry_start", async () => {
430
+ if (normalizedPhasesObserved) return;
409
431
  await setPhaseLabel("retry");
410
432
  });
411
433
 
412
434
  pi.on("auto_retry_end", async () => {
435
+ if (normalizedPhasesObserved) return;
413
436
  await clearPhaseLabel();
414
437
  });
415
438
 
416
439
  pi.on("auto_compaction_start", async () => {
440
+ if (normalizedPhasesObserved) return;
417
441
  await setPhaseLabel("cleanup");
418
442
  });
419
443
 
420
444
  pi.on("auto_compaction_end", async () => {
445
+ if (normalizedPhasesObserved) return;
421
446
  await clearPhaseLabel();
422
447
  });
423
448
 
@@ -46,6 +46,7 @@ import type {
46
46
  SessionEntry,
47
47
  SessionManager,
48
48
  } from "../../session/session-manager";
49
+ import type { NormalizedTurnPhase } from "../../session/turn-phase";
49
50
  import type {
50
51
  BashToolDetails,
51
52
  BashToolInput,
@@ -63,6 +64,7 @@ import type { SlashCommandInfo } from "../slash-commands";
63
64
 
64
65
  export type { AppKeybinding, KeybindingsManager } from "../../config/keybindings";
65
66
  export type { ExecOptions, ExecResult } from "../../exec/exec";
67
+ export type { NormalizedTurnPhase } from "../../session/turn-phase";
66
68
  export type { AgentToolResult, AgentToolUpdateCallback };
67
69
 
68
70
  // ============================================================================
@@ -560,6 +562,13 @@ export interface UserPromptEndEvent {
560
562
  kind: UserPromptKind;
561
563
  }
562
564
 
565
+ /** Provider-neutral, payload-free turn status shared by the TUI and external reporters. */
566
+ export interface TurnPhaseEvent {
567
+ type: "turn_phase";
568
+ phase: NormalizedTurnPhase;
569
+ turnId: number;
570
+ }
571
+
563
572
  /** Fired when a tool starts executing */
564
573
  export interface ToolExecutionStartEvent {
565
574
  type: "tool_execution_start";
@@ -838,6 +847,7 @@ export type ExtensionEvent =
838
847
  | MessageEndEvent
839
848
  | UserPromptStartEvent
840
849
  | UserPromptEndEvent
850
+ | TurnPhaseEvent
841
851
  | ToolExecutionStartEvent
842
852
  | ToolExecutionUpdateEvent
843
853
  | ToolExecutionEndEvent
@@ -1034,6 +1044,7 @@ export interface ExtensionAPI {
1034
1044
  on(event: "message_end", handler: ExtensionHandler<MessageEndEvent>): void;
1035
1045
  on(event: "user_prompt_start", handler: ExtensionHandler<UserPromptStartEvent>): void;
1036
1046
  on(event: "user_prompt_end", handler: ExtensionHandler<UserPromptEndEvent>): void;
1047
+ on(event: "turn_phase", handler: ExtensionHandler<TurnPhaseEvent>): void;
1037
1048
  on(event: "tool_execution_start", handler: ExtensionHandler<ToolExecutionStartEvent>): void;
1038
1049
  on(event: "tool_execution_update", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;
1039
1050
  on(event: "tool_execution_end", handler: ExtensionHandler<ToolExecutionEndEvent>): void;
@@ -17,17 +17,17 @@ export interface BuildInfo {
17
17
  }
18
18
 
19
19
  export const BUILD_INFO: BuildInfo = {
20
- "version": "21.14.0",
21
- "commit": "8caf30883aadd53c0489e3930ec73e375afd86e7",
22
- "shortCommit": "8caf308",
20
+ "version": "21.15.0",
21
+ "commit": "70ef59467d07010efc88051c877f5791673452fc",
22
+ "shortCommit": "70ef594",
23
23
  "branch": "main",
24
- "tag": "v21.14.0",
25
- "commitDate": "2026-09-06T15:35:41+00:00",
26
- "buildDate": "2026-09-06T16:30:17.398Z",
24
+ "tag": "v21.15.0",
25
+ "commitDate": "2026-09-06T20:02:40+00:00",
26
+ "buildDate": "2026-09-06T21:04:06.495Z",
27
27
  "dirty": true,
28
28
  "prNumber": "",
29
29
  "repoUrl": "https://github.com/f5-sales-demo/xcsh",
30
30
  "repoSlug": "f5-sales-demo/xcsh",
31
- "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/8caf30883aadd53c0489e3930ec73e375afd86e7",
32
- "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.14.0"
31
+ "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/70ef59467d07010efc88051c877f5791673452fc",
32
+ "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.15.0"
33
33
  };
@@ -9,6 +9,7 @@ import type { StatusLinePreset, StatusLineSegmentId, StatusLineSeparatorStyle }
9
9
  import { theme } from "../../modes/theme/theme";
10
10
  import type { AgentSession } from "../../session/agent-session";
11
11
  import { calculatePromptTokens } from "../../session/compaction/compaction";
12
+ import type { NormalizedTurnPhase } from "../../session/turn-phase";
12
13
  import type { EventBus } from "../../utils/event-bus";
13
14
  import * as git from "../../utils/git";
14
15
  import { queryGitStatus } from "../../utils/gitstatus";
@@ -67,6 +68,7 @@ export class StatusLineComponent implements Component {
67
68
  // chord is pending. Populated by the InputController's ChordDispatcher
68
69
  // callbacks; rendered as a dim right-aligned segment in the top border.
69
70
  #chordPending: string | null = null;
71
+ #turnPhase: NormalizedTurnPhase = "idle";
70
72
 
71
73
  // Git status caching (1s TTL)
72
74
  #cachedGitStatus: {
@@ -149,6 +151,12 @@ export class StatusLineComponent implements Component {
149
151
  this.#onStatusChanged?.();
150
152
  }
151
153
 
154
+ setTurnPhase(phase: NormalizedTurnPhase): void {
155
+ if (this.#turnPhase === phase) return;
156
+ this.#turnPhase = phase;
157
+ this.#onStatusChanged?.();
158
+ }
159
+
152
160
  setHookStatus(key: string, text: string | undefined): void {
153
161
  if (text === undefined) {
154
162
  this.#hookStatuses.delete(key);
@@ -521,6 +529,12 @@ export class StatusLineComponent implements Component {
521
529
  });
522
530
  }
523
531
 
532
+ rightParts.push({
533
+ content: theme.fg("dim", this.#turnPhase),
534
+ bg: defaultBg,
535
+ fg: defaultFg,
536
+ });
537
+
524
538
  // Chord-pending indicator: rightmost segment, dim style. Appended last
525
539
  // so it visually sits at the far right of the top border (after any
526
540
  // background-jobs indicator). Swallowed by truncation-from-right in the
@@ -138,6 +138,11 @@ export class EventController {
138
138
  this.ctx.updateEditorTopBorder();
139
139
 
140
140
  switch (event.type) {
141
+ case "turn_phase":
142
+ this.ctx.statusLine.setTurnPhase(event.phase);
143
+ this.ctx.ui.requestRender();
144
+ break;
145
+
141
146
  case "agent_start":
142
147
  this.#lastIntent = undefined;
143
148
  this.#readToolCallArgs.clear();
@@ -661,7 +661,7 @@ export class ExtensionUiController {
661
661
  * when it resolves. Fire-and-forget: reporting must never disturb the prompt.
662
662
  */
663
663
  #emitPromptSignal(type: "user_prompt_start" | "user_prompt_end", kind: UserPromptKind): void {
664
- this.ctx.session.extensionRunner?.emit({ type, kind }).catch(() => {});
664
+ this.ctx.session.notifyUserPrompt(type === "user_prompt_start" ? "start" : "end", kind);
665
665
  }
666
666
 
667
667
  showHookSelector(
@@ -25,6 +25,7 @@ import {
25
25
  import { DebugSelectorComponent } from "../../debug";
26
26
  import { disableProvider, enableProvider } from "../../discovery";
27
27
  import { clearXcshPluginRootsCache, resolveActiveProjectRegistryPath } from "../../discovery/helpers";
28
+ import type { UserPromptKind } from "../../extensibility/extensions/types";
28
29
  import {
29
30
  formatMarketplaceRefreshWarning,
30
31
  getInstalledPluginsRegistryPath,
@@ -113,6 +114,20 @@ class LoginPromptCancelled extends Error {}
113
114
  export class SelectorController {
114
115
  constructor(private ctx: InteractiveModeContext) {}
115
116
 
117
+ #emitPromptSignal(type: "user_prompt_start" | "user_prompt_end", kind: UserPromptKind): void {
118
+ this.ctx.session.extensionRunner?.emit({ type, kind }).catch(() => {});
119
+ }
120
+
121
+ #beginPromptSignal(kind: UserPromptKind): () => void {
122
+ let open = true;
123
+ this.#emitPromptSignal("user_prompt_start", kind);
124
+ return () => {
125
+ if (!open) return;
126
+ open = false;
127
+ this.#emitPromptSignal("user_prompt_end", kind);
128
+ };
129
+ }
130
+
116
131
  async #refreshOAuthProviderAuthState(): Promise<void> {
117
132
  const oauthProviders = getOAuthProviders().filter(provider => !provider.loginOnly);
118
133
  await Promise.all(
@@ -127,17 +142,23 @@ export class SelectorController {
127
142
  * Shows a selector component in place of the editor.
128
143
  * @param create Factory that receives a `done` callback and returns the component and focus target
129
144
  */
130
- showSelector(create: (done: () => void) => { component: Component; focus: Component }): void {
145
+ showSelector(
146
+ create: (done: () => void) => { component: Component; focus: Component },
147
+ promptKind?: UserPromptKind,
148
+ ): void {
149
+ let endPrompt: (() => void) | undefined;
131
150
  const done = () => {
132
151
  this.ctx.editorContainer.clear();
133
152
  this.ctx.editorContainer.addChild(this.ctx.editor);
134
153
  this.ctx.ui.setFocus(this.ctx.editor);
154
+ endPrompt?.();
135
155
  };
136
156
  const { component, focus } = create(done);
137
157
  this.ctx.editorContainer.clear();
138
158
  this.ctx.editorContainer.addChild(component);
139
159
  this.ctx.ui.setFocus(focus);
140
160
  this.ctx.ui.requestRender();
161
+ if (promptKind) endPrompt = this.#beginPromptSignal(promptKind);
141
162
  }
142
163
 
143
164
  showSettingsSelector(): void {
@@ -600,7 +621,8 @@ export class SelectorController {
600
621
  this.ctx.editorContainer.addChild(input);
601
622
  this.ctx.ui.setFocus(input);
602
623
  this.ctx.ui.requestRender();
603
- return promise;
624
+ const endPrompt = this.#beginPromptSignal("input");
625
+ return promise.finally(endPrompt);
604
626
  }
605
627
 
606
628
  async #showLoginRecovery(
@@ -1274,6 +1296,7 @@ export class SelectorController {
1274
1296
  const useManualInput =
1275
1297
  CALLBACK_SERVER_PROVIDERS.has(providerId as OAuthProvider) || providerId === "openai-codex";
1276
1298
  const shouldOpenBrowser = providerId !== "openai-codex" || openAICodexMethod === "browser";
1299
+ let endAuthorizationWait: (() => void) | undefined;
1277
1300
  const loginCallbacks = {
1278
1301
  method: openAICodexMethod,
1279
1302
  onAuth: (info: {
@@ -1299,6 +1322,7 @@ export class SelectorController {
1299
1322
  }
1300
1323
  this.ctx.ui.requestRender();
1301
1324
  if (shouldOpenBrowser) this.ctx.openInBrowser(info.openUrl ?? info.url);
1325
+ endAuthorizationWait ??= this.#beginPromptSignal("input");
1302
1326
  },
1303
1327
  onPrompt: async (prompt: OAuthPrompt) => {
1304
1328
  this.ctx.chatContainer.addChild(new Spacer(1));
@@ -1333,7 +1357,8 @@ export class SelectorController {
1333
1357
  this.ctx.editorContainer.addChild(codeInput);
1334
1358
  this.ctx.ui.setFocus(codeInput);
1335
1359
  this.ctx.ui.requestRender();
1336
- return promise;
1360
+ const endPrompt = this.#beginPromptSignal("input");
1361
+ return promise.finally(endPrompt);
1337
1362
  },
1338
1363
  onProgress: (message: string) => {
1339
1364
  this.ctx.chatContainer.addChild(new Text(theme.fg("dim", message), 1, 0));
@@ -1412,6 +1437,7 @@ export class SelectorController {
1412
1437
  if (useManualInput) {
1413
1438
  manualInput.clear(`Manual OAuth input cleared for ${providerId}`);
1414
1439
  }
1440
+ endAuthorizationWait?.();
1415
1441
  }
1416
1442
  }
1417
1443
 
@@ -1448,25 +1474,31 @@ export class SelectorController {
1448
1474
  let accessToken = await authStorage.getApiKey("google-vertex");
1449
1475
  if (!accessToken) {
1450
1476
  this.ctx.showStatus("Authenticating Corporate Vertex with the authorized Google enterprise flow…");
1451
- await authStorage.login("google-vertex", {
1452
- onAuth: info => {
1453
- presentAuthLink(this.ctx.chatContainer, info.url);
1454
- if (isHeadlessTerminal(runtime.environment)) {
1455
- this.ctx.chatContainer.addChild(new Text(theme.fg("dim", VERTEX_MANUAL_LOGIN_TIP), 1, 0));
1456
- } else {
1457
- this.ctx.openInBrowser(info.url);
1458
- }
1459
- this.ctx.ui.requestRender();
1460
- },
1461
- onPrompt: prompt =>
1462
- this.#promptLoginValue({
1463
- message: prompt.message,
1464
- placeholder: prompt.placeholder,
1465
- allowEmpty: prompt.allowEmpty,
1466
- }),
1467
- onProgress: message => this.ctx.showStatus(message),
1468
- onManualCodeInput: () => this.ctx.oauthManualInput.waitForInput("google-vertex"),
1469
- });
1477
+ let endAuthorizationWait: (() => void) | undefined;
1478
+ try {
1479
+ await authStorage.login("google-vertex", {
1480
+ onAuth: info => {
1481
+ presentAuthLink(this.ctx.chatContainer, info.url);
1482
+ if (isHeadlessTerminal(runtime.environment)) {
1483
+ this.ctx.chatContainer.addChild(new Text(theme.fg("dim", VERTEX_MANUAL_LOGIN_TIP), 1, 0));
1484
+ } else {
1485
+ this.ctx.openInBrowser(info.url);
1486
+ }
1487
+ this.ctx.ui.requestRender();
1488
+ endAuthorizationWait ??= this.#beginPromptSignal("input");
1489
+ },
1490
+ onPrompt: prompt =>
1491
+ this.#promptLoginValue({
1492
+ message: prompt.message,
1493
+ placeholder: prompt.placeholder,
1494
+ allowEmpty: prompt.allowEmpty,
1495
+ }),
1496
+ onProgress: message => this.ctx.showStatus(message),
1497
+ onManualCodeInput: () => this.ctx.oauthManualInput.waitForInput("google-vertex"),
1498
+ });
1499
+ } finally {
1500
+ endAuthorizationWait?.();
1501
+ }
1470
1502
  accessToken = await authStorage.getApiKey("google-vertex");
1471
1503
  if (!accessToken) throw new Error("Vertex OAuth authentication did not return an access token");
1472
1504
  }
@@ -1575,40 +1607,43 @@ export class SelectorController {
1575
1607
  }
1576
1608
  }
1577
1609
 
1578
- this.showSelector(done => {
1579
- let selector: OAuthSelectorComponent;
1580
- selector = new OAuthSelectorComponent(
1581
- mode,
1582
- this.ctx.session.modelRegistry.authStorage,
1583
- async (selectedProviderId: string) => {
1584
- selector.stopValidation();
1585
- done();
1586
- if (mode === "login") {
1587
- await this.#handleOAuthLogin(selectedProviderId);
1588
- } else {
1589
- await this.#handleOAuthLogout(selectedProviderId);
1590
- }
1591
- },
1592
- () => {
1593
- selector.stopValidation();
1594
- done();
1595
- this.ctx.ui.requestRender();
1596
- },
1597
- {
1598
- validateAuth: async (selectedProviderId: string) => {
1599
- const apiKey = await this.ctx.session.modelRegistry.getApiKeyForProvider(
1600
- selectedProviderId,
1601
- this.ctx.session.sessionId,
1602
- );
1603
- return !!apiKey;
1610
+ this.showSelector(
1611
+ done => {
1612
+ let selector: OAuthSelectorComponent;
1613
+ selector = new OAuthSelectorComponent(
1614
+ mode,
1615
+ this.ctx.session.modelRegistry.authStorage,
1616
+ async (selectedProviderId: string) => {
1617
+ selector.stopValidation();
1618
+ done();
1619
+ if (mode === "login") {
1620
+ await this.#handleOAuthLogin(selectedProviderId);
1621
+ } else {
1622
+ await this.#handleOAuthLogout(selectedProviderId);
1623
+ }
1604
1624
  },
1605
- requestRender: () => {
1625
+ () => {
1626
+ selector.stopValidation();
1627
+ done();
1606
1628
  this.ctx.ui.requestRender();
1607
1629
  },
1608
- },
1609
- );
1610
- return { component: selector, focus: selector };
1611
- });
1630
+ {
1631
+ validateAuth: async (selectedProviderId: string) => {
1632
+ const apiKey = await this.ctx.session.modelRegistry.getApiKeyForProvider(
1633
+ selectedProviderId,
1634
+ this.ctx.session.sessionId,
1635
+ );
1636
+ return !!apiKey;
1637
+ },
1638
+ requestRender: () => {
1639
+ this.ctx.ui.requestRender();
1640
+ },
1641
+ },
1642
+ );
1643
+ return { component: selector, focus: selector };
1644
+ },
1645
+ mode === "login" ? "select" : undefined,
1646
+ );
1612
1647
  }
1613
1648
 
1614
1649
  showDebugSelector(): void {
@@ -4,6 +4,8 @@ import { $ } from "bun";
4
4
 
5
5
  export const VERTEX_LOGIN_MODEL = "gemini-3.7-flash";
6
6
  export const VERTEX_LOGIN_LOCATION = "global";
7
+ const VERTEX_BUILD_CREDENTIALS_UNAVAILABLE =
8
+ "Corporate Vertex OAuth credentials are unavailable in this build. Install an official xcsh binary or provide the licensed build credentials when running from source.";
7
9
 
8
10
  export type VertexProjectSource = "environment" | "adc" | "gcloud";
9
11
  export interface VertexProject {
@@ -36,12 +38,15 @@ export async function detectVertexProject(runtime: VertexLoginRuntime): Promise<
36
38
  }
37
39
 
38
40
  export function isHeadlessTerminal(environment: Record<string, string | undefined>): boolean {
39
- return Boolean(environment.CLOUD_SHELL || environment.SSH_CONNECTION || !environment.DISPLAY);
41
+ return Boolean(
42
+ environment.HERDR_ENV === "1" || environment.CLOUD_SHELL || environment.SSH_CONNECTION || !environment.DISPLAY,
43
+ );
40
44
  }
41
45
 
42
46
  export function vertexFailureGuidance(error: unknown, project?: string): string {
43
47
  const message = error instanceof Error ? error.message : String(error);
44
48
  const projectArg = project ? ` --project ${project}` : "";
49
+ if (message === VERTEX_BUILD_CREDENTIALS_UNAVAILABLE) return VERTEX_BUILD_CREDENTIALS_UNAVAILABLE;
45
50
  if (/credential|unauthenticated|login|access token/i.test(message)) {
46
51
  return "Vertex OAuth credentials are unavailable. Run `/login google-vertex` and sign in again.";
47
52
  }
package/src/sdk.ts CHANGED
@@ -142,6 +142,7 @@ import {
142
142
  ReadTool,
143
143
  ResolveTool,
144
144
  renderSearchToolBm25Description,
145
+ SearchToolBm25Tool,
145
146
  setPreferredImageProvider,
146
147
  setPreferredSearchProvider,
147
148
  type Tool,
@@ -691,6 +692,13 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
691
692
  const modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage);
692
693
 
693
694
  const settings = options.settings ?? (await logger.time("settings", Settings.init, { cwd, agentDir }));
695
+ const configuredContextLoadingMode = settings.get("context.loadingMode");
696
+ const resolveContextLoadingMode = (candidate: Model | undefined): "eager" | "progressive" =>
697
+ configuredContextLoadingMode === "progressive" ||
698
+ (options.toolNames === undefined && candidate?.provider === "anthropic" && modelRegistry.isUsingOAuth(candidate))
699
+ ? "progressive"
700
+ : "eager";
701
+ let contextLoadingMode = resolveContextLoadingMode(options.model);
694
702
  logger.time("initializeWithSettings");
695
703
  initializeWithSettings(settings);
696
704
  if (!options.modelRegistry) {
@@ -943,6 +951,17 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
943
951
  resolveThinkingLevelForModel(resolvedModel, thinkingLevel),
944
952
  );
945
953
  }
954
+ contextLoadingMode = resolveContextLoadingMode(model);
955
+ const toolSettings = new Proxy(settings, {
956
+ get(target, property) {
957
+ if (property === "get") {
958
+ return (path: Parameters<typeof settings.get>[0]) =>
959
+ path === "context.loadingMode" ? contextLoadingMode : settings.get(path);
960
+ }
961
+ const value = Reflect.get(target, property, target);
962
+ return typeof value === "function" ? value.bind(target) : value;
963
+ },
964
+ });
946
965
 
947
966
  let skills: Skill[];
948
967
  let skillWarnings: SkillWarning[];
@@ -1137,7 +1156,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1137
1156
  return {};
1138
1157
  }
1139
1158
  },
1140
- settings,
1159
+ settings: toolSettings,
1141
1160
  authStorage,
1142
1161
  modelRegistry,
1143
1162
  asyncJobManager,
@@ -1214,6 +1233,15 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1214
1233
 
1215
1234
  // Create built-in tools (already wrapped with meta notice formatting)
1216
1235
  const builtinTools = await logger.time("createAllTools", createTools, toolSession, options.toolNames);
1236
+ const providerToolPolicyAvailable =
1237
+ options.toolNames === undefined &&
1238
+ configuredContextLoadingMode === "eager" &&
1239
+ (modelRegistry.authStorage?.hasOAuth("anthropic") ?? false);
1240
+ const injectedProviderDiscoveryTool =
1241
+ providerToolPolicyAvailable && !builtinTools.some(tool => tool.name === "search_tool_bm25");
1242
+ if (injectedProviderDiscoveryTool) {
1243
+ builtinTools.push(new SearchToolBm25Tool(toolSession));
1244
+ }
1217
1245
 
1218
1246
  // Discover MCP tools from .mcp.json files
1219
1247
  let mcpManager: MCPManager | undefined;
@@ -1516,7 +1544,6 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1516
1544
  });
1517
1545
 
1518
1546
  const repeatToolDescriptions = settings.get("repeatToolDescriptions");
1519
- const contextLoadingMode = settings.get("context.loadingMode");
1520
1547
  const contextProfileCollector = new ContextProfileCollector(contextLoadingMode);
1521
1548
  const eagerTasks = settings.get("task.eager");
1522
1549
  const intentField = settings.get("tools.intentTracing") || $flag("PI_INTENT_TRACING") ? INTENT_FIELD : undefined;
@@ -1713,11 +1740,15 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1713
1740
  "xcsh_api",
1714
1741
  "search_tool_bm25",
1715
1742
  ];
1743
+ const eagerRequestedActiveToolNames = requestedActiveToolNames.filter(
1744
+ name => !(providerToolPolicyAvailable && !settings.get("mcp.discoveryMode") && name === "search_tool_bm25"),
1745
+ );
1746
+ const eagerToolNames = eagerRequestedActiveToolNames.filter(name => !defaultInactiveToolNames.has(name));
1716
1747
  const initialRequestedActiveToolNames = options.toolNames
1717
1748
  ? requestedActiveToolNames
1718
1749
  : progressiveLoading
1719
1750
  ? progressiveCoreToolNames.filter(name => toolRegistry.has(name))
1720
- : requestedActiveToolNames.filter(name => !defaultInactiveToolNames.has(name));
1751
+ : eagerToolNames;
1721
1752
  const restoredProgressiveToolNames = existingSession.hasPersistedToolSelection
1722
1753
  ? [
1723
1754
  ...progressiveCoreToolNames.filter(name => toolRegistry.has(name)),
@@ -1777,6 +1808,9 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1777
1808
  initialToolNames.push(name);
1778
1809
  }
1779
1810
  }
1811
+ for (const name of alwaysInclude) {
1812
+ if (toolRegistry.has(name) && !eagerToolNames.includes(name)) eagerToolNames.push(name);
1813
+ }
1780
1814
 
1781
1815
  const systemPrompt = await logger.time("buildSystemPrompt", rebuildSystemPrompt, initialToolNames, toolRegistry);
1782
1816
 
@@ -1971,6 +2005,22 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1971
2005
  skillWarnings,
1972
2006
  skillsSettings: settings.getGroup("skills"),
1973
2007
  modelRegistry,
2008
+ resolveToolPolicyForModel: providerToolPolicyAvailable
2009
+ ? candidate => {
2010
+ const previousLoadingMode = contextLoadingMode;
2011
+ contextLoadingMode = resolveContextLoadingMode(candidate);
2012
+ const progressive = contextLoadingMode === "progressive";
2013
+ return {
2014
+ toolNames:
2015
+ previousLoadingMode === contextLoadingMode
2016
+ ? undefined
2017
+ : progressive
2018
+ ? progressiveCoreToolNames.filter(name => toolRegistry.has(name))
2019
+ : eagerToolNames,
2020
+ mcpDiscoveryEnabled: (settings.get("mcp.discoveryMode") ?? false) || progressive,
2021
+ };
2022
+ }
2023
+ : undefined,
1974
2024
  contextProfileCollector,
1975
2025
  toolRegistry,
1976
2026
  transformContext,
@@ -99,6 +99,7 @@ import type {
99
99
  TreePreparation,
100
100
  TurnEndEvent,
101
101
  TurnStartEvent,
102
+ UserPromptKind,
102
103
  } from "../extensibility/extensions";
103
104
  import type { CompactOptions, ContextUsage } from "../extensibility/extensions/types";
104
105
  import { ExtensionToolWrapper } from "../extensibility/extensions/wrapper";
@@ -184,10 +185,12 @@ import type {
184
185
  } from "./session-manager";
185
186
  import { getLatestCompactionEntry } from "./session-manager";
186
187
  import { ToolChoiceQueue } from "./tool-choice-queue";
188
+ import { TurnPhaseController, type TurnPhaseEvent } from "./turn-phase";
187
189
 
188
190
  /** Session-specific events that extend the core AgentEvent */
189
191
  export type AgentSessionEvent =
190
192
  | AgentEvent
193
+ | TurnPhaseEvent
191
194
  | RoutingEvent
192
195
  | { type: "auto_compaction_start"; reason: "threshold" | "overflow" | "idle"; action: "context-full" | "handoff" }
193
196
  | {
@@ -248,6 +251,8 @@ export interface AgentSessionConfig {
248
251
  skillsSettings?: SkillsSettings;
249
252
  /** Model registry for API key resolution and model discovery */
250
253
  modelRegistry: ModelRegistry;
254
+ /** SDK-owned provider policy for implicit tool selection after model changes. */
255
+ resolveToolPolicyForModel?: (model: Model) => { toolNames?: string[]; mcpDiscoveryEnabled: boolean };
251
256
  /** Privacy-safe numeric context measurements for this session. */
252
257
  contextProfileCollector?: ContextProfileCollector;
253
258
  /** Tool registry for LSP and settings */
@@ -471,6 +476,7 @@ export class AgentSession {
471
476
  // Event subscription state
472
477
  #unsubscribeAgent?: () => void;
473
478
  #eventListeners: AgentSessionEventListener[] = [];
479
+ #turnPhase = new TurnPhaseController(event => this.#publishTurnPhase(event));
474
480
 
475
481
  // Callers (e.g., SDK-level code that registers external listeners) register cleanups here so
476
482
  // dispose() unregisters them. Prevents leaked listeners from mutating dead session state.
@@ -536,6 +542,7 @@ export class AgentSession {
536
542
 
537
543
  // Model registry for API key resolution
538
544
  #modelRegistry: ModelRegistry;
545
+ #resolveToolPolicyForModel: ((model: Model) => { toolNames?: string[]; mcpDiscoveryEnabled: boolean }) | undefined;
539
546
  #contextProfileCollector: ContextProfileCollector;
540
547
 
541
548
  // Tool registry and prompt builder for extensions
@@ -628,6 +635,7 @@ export class AgentSession {
628
635
  this.#customCommands = config.customCommands ?? [];
629
636
  this.#skillsSettings = config.skillsSettings;
630
637
  this.#modelRegistry = config.modelRegistry;
638
+ this.#resolveToolPolicyForModel = config.resolveToolPolicyForModel;
631
639
  this.#contextProfileCollector =
632
640
  config.contextProfileCollector ?? new ContextProfileCollector(this.settings.get("context.loadingMode"));
633
641
  this.#validateRetryFallbackChains();
@@ -779,7 +787,7 @@ export class AgentSession {
779
787
  }
780
788
 
781
789
  async #emitSessionEvent(event: AgentSessionEvent): Promise<void> {
782
- if (event.type === "message_update") {
790
+ if (event.type === "message_update" || event.type === "turn_phase") {
783
791
  this.#emit(event);
784
792
  void this.#queueExtensionEvent(event);
785
793
  return;
@@ -804,6 +812,25 @@ export class AgentSession {
804
812
 
805
813
  /** Internal handler for agent events - shared by subscribe and reconnect */
806
814
  #handleAgentEvent = async (event: AgentEvent): Promise<void> => {
815
+ if (event.type === "agent_start") {
816
+ this.#turnPhase.startAgentLoop();
817
+ } else if (event.type === "turn_start") {
818
+ this.#turnPhase.startModelTurn();
819
+ } else if (event.type === "message_update" && event.assistantMessageEvent.type === "toolcall_start") {
820
+ const content =
821
+ event.message.role === "assistant"
822
+ ? event.message.content[event.assistantMessageEvent.contentIndex]
823
+ : undefined;
824
+ if (content?.type === "toolCall") this.#turnPhase.startTool(content.id);
825
+ } else if (event.type === "message_update" && event.assistantMessageEvent.type === "server_tool_start") {
826
+ this.#turnPhase.startTool(`server:${event.assistantMessageEvent.toolId}`);
827
+ } else if (event.type === "message_update" && event.assistantMessageEvent.type === "server_tool_end") {
828
+ this.#turnPhase.endTool(`server:${event.assistantMessageEvent.toolId}`);
829
+ } else if (event.type === "tool_execution_start") {
830
+ this.#turnPhase.startTool(event.toolCallId);
831
+ } else if (event.type === "tool_execution_end") {
832
+ this.#turnPhase.endTool(event.toolCallId);
833
+ }
807
834
  if (event.type === "message_end" && event.message.role === "assistant" && event.message.usage) {
808
835
  this.#contextProfileCollector.recordProviderUsage(this.agent.state.model, event.message.usage);
809
836
  }
@@ -860,6 +887,23 @@ export class AgentSession {
860
887
 
861
888
  await this.#emitSessionEvent(displayEvent);
862
889
 
890
+ // `agent_end` is the provider-neutral completion boundary. Settle only
891
+ // after subscribers have received it, so interactive consumers can begin
892
+ // clearing provider/tool status before Herdr observes idle. This also
893
+ // covers continuations that call Agent.continue() without #promptWithMessage.
894
+ if (event.type === "agent_end") {
895
+ const lastAssistant = [...event.messages]
896
+ .reverse()
897
+ .find((message): message is AssistantMessage => message.role === "assistant");
898
+ this.#turnPhase.settle(
899
+ lastAssistant?.stopReason === "aborted"
900
+ ? "aborted"
901
+ : lastAssistant?.stopReason === "error"
902
+ ? "error"
903
+ : "stop",
904
+ );
905
+ }
906
+
863
907
  if (event.type === "turn_start") {
864
908
  this.#resetStreamingEditState();
865
909
  // TTSR: Reset buffer on turn start
@@ -1365,7 +1409,7 @@ export class AgentSession {
1365
1409
  this.settings.set("modelRoles", { ...currentRoles });
1366
1410
  this.settings.set("routing.profile", previousProfile);
1367
1411
  if (previousModel) {
1368
- this.#setModelWithProviderSessionReset(previousModel, "runtime-switch");
1412
+ await this.#setModelWithProviderSessionReset(previousModel, "runtime-switch");
1369
1413
  this.setThinkingLevel(previousThinking);
1370
1414
  }
1371
1415
  throw error;
@@ -1478,7 +1522,7 @@ export class AgentSession {
1478
1522
  this.#routingCoordinator.getStateMachine().clearEscalationFloor();
1479
1523
  }
1480
1524
  if (previousModel) {
1481
- this.#setModelWithProviderSessionReset(previousModel, "runtime-switch");
1525
+ await this.#setModelWithProviderSessionReset(previousModel, "runtime-switch");
1482
1526
  this.setThinkingLevel(previousThinkingLevel);
1483
1527
  this.sessionManager.appendModelChange(
1484
1528
  `${previousModel.provider}/${previousModel.id}`,
@@ -1991,7 +2035,9 @@ export class AgentSession {
1991
2035
  /** Emit extension events based on session events */
1992
2036
  async #emitExtensionEvent(event: AgentSessionEvent): Promise<void> {
1993
2037
  if (!this.#extensionRunner) return;
1994
- if (event.type === "agent_start") {
2038
+ if (event.type === "turn_phase") {
2039
+ await this.#extensionRunner.emit(event);
2040
+ } else if (event.type === "agent_start") {
1995
2041
  this.#turnIndex = 0;
1996
2042
  await this.#extensionRunner.emit({ type: "agent_start" });
1997
2043
  } else if (event.type === "agent_end") {
@@ -2102,6 +2148,21 @@ export class AgentSession {
2102
2148
  }
2103
2149
  }
2104
2150
 
2151
+ #publishTurnPhase(event: TurnPhaseEvent): void {
2152
+ void this.#emitSessionEvent(event);
2153
+ }
2154
+
2155
+ notifyUserPrompt(type: "start" | "end", kind: UserPromptKind): void {
2156
+ if (type === "start") this.#turnPhase.startUserPrompt();
2157
+ else this.#turnPhase.endUserPrompt();
2158
+ if (!this.#extensionRunner) return;
2159
+ const emit = async () => {
2160
+ await this.#extensionRunner?.emit({ type: type === "start" ? "user_prompt_start" : "user_prompt_end", kind });
2161
+ };
2162
+ const queued = this.#queuedExtensionEvents.then(emit, emit);
2163
+ this.#queuedExtensionEvents = queued.catch(() => {});
2164
+ }
2165
+
2105
2166
  /**
2106
2167
  * Subscribe to agent events.
2107
2168
  * Session persistence is handled internally (saves messages on message_end).
@@ -3292,7 +3353,10 @@ export class AgentSession {
3292
3353
  },
3293
3354
  ): Promise<void> {
3294
3355
  this.#promptInFlightCount++;
3356
+ this.#turnPhase.startTurn();
3295
3357
  const generation = this.#promptGeneration;
3358
+ let settled = false;
3359
+ let agentLoopStarted = false;
3296
3360
  try {
3297
3361
  // Flush any pending bash messages before the new prompt
3298
3362
  this.#flushPendingBashMessages();
@@ -3410,13 +3474,19 @@ export class AgentSession {
3410
3474
  options?.toolChoice || options?.serverTools
3411
3475
  ? { toolChoice: options?.toolChoice, serverTools: options?.serverTools }
3412
3476
  : undefined;
3477
+ agentLoopStarted = true;
3413
3478
  await logger.ttftAttr("ttft.agent-loop-total", () =>
3414
3479
  this.#promptAgentWithIdleRetry(messages, agentPromptOptions),
3415
3480
  );
3416
3481
  if (!options?.skipPostPromptRecoveryWait) {
3417
3482
  await this.#waitForPostPromptRecovery();
3418
3483
  }
3484
+ } catch (error) {
3485
+ this.#turnPhase.settle(this.#findLastAssistantMessage()?.stopReason === "aborted" ? "aborted" : "error");
3486
+ settled = true;
3487
+ throw error;
3419
3488
  } finally {
3489
+ if (!agentLoopStarted && !settled) this.#turnPhase.settle("aborted");
3420
3490
  this.#promptInFlightCount = Math.max(0, this.#promptInFlightCount - 1);
3421
3491
  }
3422
3492
  }
@@ -4252,7 +4322,7 @@ export class AgentSession {
4252
4322
  const targetThinkingLevel = this.#resolveTargetThinkingLevel(model, options?.thinkingLevel, role);
4253
4323
 
4254
4324
  this.#clearActiveRetryFallback();
4255
- this.#setModelWithProviderSessionReset(model);
4325
+ await this.#setModelWithProviderSessionReset(model);
4256
4326
  if (options?.source !== "routing") {
4257
4327
  this.#routingCoordinator.getStateMachine().setManualPin(`${model.provider}/${model.id}`);
4258
4328
  }
@@ -4281,7 +4351,7 @@ export class AgentSession {
4281
4351
  const targetThinkingLevel = this.#resolveTargetThinkingLevel(model, thinkingLevel);
4282
4352
 
4283
4353
  this.#clearActiveRetryFallback();
4284
- this.#setModelWithProviderSessionReset(model);
4354
+ await this.#setModelWithProviderSessionReset(model);
4285
4355
  this.sessionManager.appendModelChange(`${model.provider}/${model.id}`, "temporary");
4286
4356
  this.settings.getStorage()?.recordModelUsage(`${model.provider}/${model.id}`);
4287
4357
 
@@ -4318,7 +4388,7 @@ export class AgentSession {
4318
4388
  const targetThinkingLevel = this.#resolveTargetThinkingLevel(targetModel, thinkingLevel);
4319
4389
 
4320
4390
  // DO NOT clear active retry fallback - routing is a transient optimization
4321
- this.#setModelWithProviderSessionReset(targetModel, "runtime-switch");
4391
+ await this.#setModelWithProviderSessionReset(targetModel, "runtime-switch");
4322
4392
  this.sessionManager.appendModelChange(`${targetModel.provider}/${targetModel.id}`, "routing_switch");
4323
4393
  this.settings.getStorage()?.recordModelUsage(`${targetModel.provider}/${targetModel.id}`);
4324
4394
 
@@ -4445,7 +4515,7 @@ export class AgentSession {
4445
4515
 
4446
4516
  // Apply model
4447
4517
  this.#clearActiveRetryFallback();
4448
- this.#setModelWithProviderSessionReset(next.model);
4518
+ await this.#setModelWithProviderSessionReset(next.model);
4449
4519
  this.sessionManager.appendModelChange(`${next.model.provider}/${next.model.id}`);
4450
4520
  this.settings.setModelRole("default", this.#formatRoleModelValue("default", next.model));
4451
4521
  this.settings.getStorage()?.recordModelUsage(`${next.model.provider}/${next.model.id}`);
@@ -4477,7 +4547,7 @@ export class AgentSession {
4477
4547
  const targetThinkingLevel = this.#resolveTargetThinkingLevel(nextModel, undefined, "default");
4478
4548
 
4479
4549
  this.#clearActiveRetryFallback();
4480
- this.#setModelWithProviderSessionReset(nextModel);
4550
+ await this.#setModelWithProviderSessionReset(nextModel);
4481
4551
  this.sessionManager.appendModelChange(`${nextModel.provider}/${nextModel.id}`);
4482
4552
  this.settings.setModelRole("default", this.#formatRoleModelValue("default", nextModel));
4483
4553
  this.settings.getStorage()?.recordModelUsage(`${nextModel.provider}/${nextModel.id}`);
@@ -5339,13 +5409,23 @@ export class AgentSession {
5339
5409
  return candidate;
5340
5410
  }
5341
5411
 
5342
- #setModelWithProviderSessionReset(model: Model, source: ModelResolutionSource = "runtime-switch"): void {
5412
+ async #setModelWithProviderSessionReset(
5413
+ model: Model,
5414
+ source: ModelResolutionSource = "runtime-switch",
5415
+ ): Promise<void> {
5343
5416
  const currentModel = this.model;
5344
5417
  if (currentModel) {
5345
5418
  this.#closeProviderSessionsForModelSwitch(currentModel, model);
5346
5419
  }
5347
5420
  this.#modelResolutionSource = source;
5348
5421
  this.agent.setModel(model);
5422
+ const toolPolicy = this.#resolveToolPolicyForModel?.(model);
5423
+ if (toolPolicy) {
5424
+ this.#mcpDiscoveryEnabled = toolPolicy.mcpDiscoveryEnabled;
5425
+ if (toolPolicy.toolNames) {
5426
+ await this.#applyActiveToolsByName(toolPolicy.toolNames, { persistMCPSelection: false });
5427
+ }
5428
+ }
5349
5429
  }
5350
5430
 
5351
5431
  #closeCodexProviderSessionsForHistoryRewrite(): void {
@@ -6179,7 +6259,7 @@ export class AgentSession {
6179
6259
  const currentThinkingLevel = this.thinkingLevel;
6180
6260
  const nextThinkingLevel = selector.thinkingLevel ?? currentThinkingLevel;
6181
6261
 
6182
- this.#setModelWithProviderSessionReset(candidate);
6262
+ await this.#setModelWithProviderSessionReset(candidate);
6183
6263
  this.sessionManager.appendModelChange(`${candidate.provider}/${candidate.id}`, "temporary");
6184
6264
  this.settings.getStorage()?.recordModelUsage(`${candidate.provider}/${candidate.id}`);
6185
6265
  this.setThinkingLevel(nextThinkingLevel);
@@ -6253,7 +6333,7 @@ export class AgentSession {
6253
6333
  const currentThinkingLevel = this.thinkingLevel;
6254
6334
  const thinkingToApply =
6255
6335
  currentThinkingLevel === lastAppliedFallbackThinkingLevel ? originalThinkingLevel : currentThinkingLevel;
6256
- this.#setModelWithProviderSessionReset(primaryModel);
6336
+ await this.#setModelWithProviderSessionReset(primaryModel);
6257
6337
  this.sessionManager.appendModelChange(`${primaryModel.provider}/${primaryModel.id}`, "temporary");
6258
6338
  this.settings.getStorage()?.recordModelUsage(`${primaryModel.provider}/${primaryModel.id}`);
6259
6339
  this.setThinkingLevel(thinkingToApply);
@@ -6867,9 +6947,16 @@ export class AgentSession {
6867
6947
  currentModel.id !== match.id ||
6868
6948
  currentModel.api !== match.api));
6869
6949
  if (shouldResetProviderState) {
6870
- this.#setModelWithProviderSessionReset(match, "config");
6950
+ await this.#setModelWithProviderSessionReset(match, "config");
6871
6951
  } else {
6872
6952
  this.agent.setModel(match);
6953
+ const toolPolicy = this.#resolveToolPolicyForModel?.(match);
6954
+ if (toolPolicy) {
6955
+ this.#mcpDiscoveryEnabled = toolPolicy.mcpDiscoveryEnabled;
6956
+ if (toolPolicy.toolNames) {
6957
+ await this.#applyActiveToolsByName(toolPolicy.toolNames, { persistMCPSelection: false });
6958
+ }
6959
+ }
6873
6960
  }
6874
6961
  }
6875
6962
  }
@@ -0,0 +1,102 @@
1
+ export const NORMALIZED_TURN_PHASES = [
2
+ "submitting",
3
+ "thinking",
4
+ "tool_call",
5
+ "awaiting_user",
6
+ "cancelled",
7
+ "error",
8
+ "idle",
9
+ ] as const;
10
+
11
+ export type NormalizedTurnPhase = (typeof NORMALIZED_TURN_PHASES)[number];
12
+
13
+ /** Safe lifecycle event: deliberately contains no prompt, provider, tool, argument, or result data. */
14
+ export interface TurnPhaseEvent {
15
+ type: "turn_phase";
16
+ phase: NormalizedTurnPhase;
17
+ turnId: number;
18
+ }
19
+
20
+ type TurnSettlement = "stop" | "aborted" | "error";
21
+
22
+ /**
23
+ * Provider-neutral source of truth for the currently visible turn phase.
24
+ * Provider adapters keep emitting their rich text; this controller observes only
25
+ * lifecycle boundaries and publishes a minimal, payload-free status contract.
26
+ */
27
+ export class TurnPhaseController {
28
+ #turnId = 0;
29
+ #phase: NormalizedTurnPhase = "idle";
30
+ #activeTurn = false;
31
+ #activeToolCalls = new Set<string>();
32
+ #userPromptDepth = 0;
33
+
34
+ constructor(private readonly publish: (event: TurnPhaseEvent) => void) {}
35
+
36
+ get current(): TurnPhaseEvent {
37
+ return { type: "turn_phase", phase: this.#phase, turnId: this.#turnId };
38
+ }
39
+
40
+ startTurn(): void {
41
+ this.#turnId++;
42
+ this.#activeTurn = true;
43
+ this.#activeToolCalls.clear();
44
+ this.#userPromptDepth = 0;
45
+ this.#transition("submitting", true);
46
+ }
47
+
48
+ /** Activate an agent loop that was started without a new submitted prompt (for example, a continuation). */
49
+ startAgentLoop(): void {
50
+ if (this.#activeTurn) return;
51
+ this.#turnId++;
52
+ this.#activeTurn = true;
53
+ this.#activeToolCalls.clear();
54
+ this.#userPromptDepth = 0;
55
+ this.#transition("thinking", true);
56
+ }
57
+
58
+ startModelTurn(): void {
59
+ if (this.#activeTurn && this.#userPromptDepth === 0) this.#transition("thinking");
60
+ }
61
+
62
+ startTool(toolCallId: string): void {
63
+ if (!this.#activeTurn) return;
64
+ this.#activeToolCalls.add(toolCallId);
65
+ if (this.#userPromptDepth === 0) this.#transition("tool_call");
66
+ }
67
+
68
+ endTool(toolCallId: string): void {
69
+ if (!this.#activeTurn) return;
70
+ this.#activeToolCalls.delete(toolCallId);
71
+ if (this.#userPromptDepth === 0 && this.#activeToolCalls.size === 0) this.#transition("thinking");
72
+ }
73
+
74
+ startUserPrompt(): void {
75
+ this.#userPromptDepth++;
76
+ this.#transition("awaiting_user");
77
+ }
78
+
79
+ endUserPrompt(): void {
80
+ this.#userPromptDepth = Math.max(0, this.#userPromptDepth - 1);
81
+ if (this.#userPromptDepth > 0) return;
82
+ if (!this.#activeTurn) {
83
+ this.#transition("idle");
84
+ return;
85
+ }
86
+ this.#transition(this.#activeToolCalls.size > 0 ? "tool_call" : "thinking");
87
+ }
88
+
89
+ settle(settlement: TurnSettlement): void {
90
+ if (!this.#activeTurn) return;
91
+ this.#activeTurn = false;
92
+ this.#activeToolCalls.clear();
93
+ this.#userPromptDepth = 0;
94
+ this.#transition(settlement === "aborted" ? "cancelled" : settlement === "error" ? "error" : "idle");
95
+ }
96
+
97
+ #transition(phase: NormalizedTurnPhase, force = false): void {
98
+ if (!force && phase === this.#phase) return;
99
+ this.#phase = phase;
100
+ this.publish(this.current);
101
+ }
102
+ }