@pal-code/core 0.0.16 → 0.0.18

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,6 +1,6 @@
1
1
  {
2
2
  "name": "@pal-code/core",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -6,6 +6,8 @@
6
6
  * only renders the events this yields.
7
7
  *
8
8
  * Strategy: same provider first (same rate-limit pool), then cross-provider.
9
+ * Rotation is opt-in (`rotate`); by default a failing turn retries the selected
10
+ * model and then reports the error instead of silently switching models.
9
11
  * - quota exhausted → switch immediately (retrying burns RPM for nothing)
10
12
  * - rate limited → exponential backoff, `maxRetries` attempts, then switch
11
13
  * - other retryable → backoff, `maxRetries` attempts, then switch
@@ -170,6 +172,11 @@ export interface RunWithFallbackOptions {
170
172
  maxRetries?: number;
171
173
  /** Base backoff in ms; doubles each attempt (default 2000). */
172
174
  retryBaseMs?: number;
175
+ /**
176
+ * Try other models/providers when the selected one fails (default false).
177
+ * Core also retries the same model; this only controls rotation.
178
+ */
179
+ rotate?: boolean;
173
180
  keys: ProviderKeys;
174
181
  executeTool: RunAgentOptions['executeTool'];
175
182
  /**
@@ -220,6 +227,7 @@ export async function* runWithFallback(
220
227
  compactionNote,
221
228
  maxRetries = 1,
222
229
  retryBaseMs = 2000,
230
+ rotate = false,
223
231
  keys,
224
232
  executeTool,
225
233
  childExecuteTool,
@@ -232,22 +240,24 @@ export async function* runWithFallback(
232
240
 
233
241
  const {provider: baseDef, model: baseModel} = providerForModel(model, Object.keys(keys));
234
242
 
235
- // Same provider: other models from its live list. Never invented — if the
236
- // fetch failed there are simply no same-provider fallbacks.
237
- const sameProviderModels: string[] = [];
238
- if (providerAccessible(baseDef, keys)) {
239
- const ids = await resolveModelIds(baseDef, keys[baseDef.id] ?? '');
240
- for (const id of ids) {
241
- if (id !== baseModel) sameProviderModels.push(`${baseDef.id}/${id}`);
243
+ const modelsToTry = [model];
244
+ if (rotate) {
245
+ // Same provider: other models from its live list. Never invented — if the
246
+ // fetch failed there are simply no same-provider fallbacks.
247
+ if (providerAccessible(baseDef, keys)) {
248
+ const ids = await resolveModelIds(baseDef, keys[baseDef.id] ?? '');
249
+ for (const id of ids) {
250
+ if (id !== baseModel) modelsToTry.push(`${baseDef.id}/${id}`);
251
+ }
242
252
  }
243
- }
244
253
 
245
- // Cross provider: only accessible providers, at their default model.
246
- const crossProviderModels = PROVIDERS.filter(
247
- (p) => p.id !== baseDef.id && providerAccessible(p, keys),
248
- ).map((p) => `${p.id}/${p.defaultModel}`);
249
-
250
- const modelsToTry = [model, ...sameProviderModels, ...crossProviderModels];
254
+ // Cross provider: only accessible providers, at their default model.
255
+ for (const p of PROVIDERS) {
256
+ if (p.id !== baseDef.id && providerAccessible(p, keys)) {
257
+ modelsToTry.push(`${p.id}/${p.defaultModel}`);
258
+ }
259
+ }
260
+ }
251
261
 
252
262
  // Track consecutive quota exhaustion per provider. If ALL models from a
253
263
  // provider share the same quota pool (e.g. Zen free tier), short-circuit
@@ -315,11 +325,13 @@ export async function* runWithFallback(
315
325
  const msg = err instanceof Error ? err.message : String(err);
316
326
 
317
327
  if (isQuotaExhausted(msg)) {
328
+ quotaExhaustedProviders.add(modelDef.id);
318
329
  yield {
319
330
  type: 'notice',
320
- text: `${modelSpec} quota exhausted — skipping remaining ${modelDef.id} models`,
331
+ text: rotate
332
+ ? `${modelSpec} quota exhausted — skipping remaining ${modelDef.id} models`
333
+ : `${modelSpec} quota exhausted — /rotation switches models automatically`,
321
334
  };
322
- quotaExhaustedProviders.add(modelDef.id);
323
335
  break; // next model (from a different provider)
324
336
  }
325
337
 
@@ -333,7 +345,12 @@ export async function* runWithFallback(
333
345
  await sleep(delay);
334
346
  continue;
335
347
  }
336
- yield {type: 'notice', text: `${modelSpec} exhausted, trying next…`};
348
+ yield {
349
+ type: 'notice',
350
+ text: rotate
351
+ ? `${modelSpec} exhausted, trying next…`
352
+ : `${modelSpec} rate-limited — /rotation tries the next model`,
353
+ };
337
354
  break;
338
355
  }
339
356
 
@@ -342,6 +359,12 @@ export async function* runWithFallback(
342
359
  await sleep(retryBaseMs * 2 ** attempt);
343
360
  continue;
344
361
  }
362
+ yield {
363
+ type: 'notice',
364
+ text: rotate
365
+ ? `${modelSpec} unavailable, trying next…`
366
+ : `${modelSpec} unavailable — /rotation tries the next model`,
367
+ };
345
368
  break;
346
369
  }
347
370
 
@@ -350,6 +373,11 @@ export async function* runWithFallback(
350
373
  }
351
374
  }
352
375
 
353
- yield {type: 'notice', text: 'All models failed (rate limits). Try again in a few minutes.'};
354
- throw new Error('All models failed');
376
+ yield {
377
+ type: 'notice',
378
+ text: rotate
379
+ ? 'All models failed (rate limits). Try again in a few minutes.'
380
+ : `${model} failed — /rotation tries other models automatically`,
381
+ };
382
+ throw new Error(rotate ? 'All models failed' : `Model failed: ${model}`);
355
383
  }
package/src/agent/run.ts CHANGED
@@ -25,6 +25,10 @@ export interface UserMsg {
25
25
  export interface AssistantMsg {
26
26
  role: 'assistant';
27
27
  content: string;
28
+ /** Model thinking text — display-only, never sent back to the provider. */
29
+ thinking?: string;
30
+ /** Thinking-phase elapsed ms, for the resume label. */
31
+ thinkingMs?: number;
28
32
  toolCalls?: Array<{
29
33
  id: string;
30
34
  name: string;
@@ -93,6 +97,7 @@ export type AgentRunEvent =
93
97
  | {type: 'model-start'; model: string}
94
98
  | {type: 'round-start'; round: number; max: number}
95
99
  | {type: 'text-delta'; content: string}
100
+ | {type: 'thinking-delta'; content: string}
96
101
  | {type: 'tool-start'; id: string; name: string; argsSummary: string}
97
102
  | {type: 'tool-end'; id: string; name: string; ok: boolean; content: string; ms: number}
98
103
  | {type: 'notice'; text: string}
@@ -135,7 +140,7 @@ export interface RunAgentOptions {
135
140
  * one).
136
141
  */
137
142
  budget?: {roleName: string; limit: number};
138
- /** Context window used to decide when to compact (default 100_000). */
143
+ /** Context window used to decide when to compact (default 200_000). */
139
144
  contextLimit?: number;
140
145
  /** Reasoning effort forwarded to the provider (default 'medium'). */
141
146
  reasoningEffort?: 'low' | 'medium' | 'high';
@@ -192,7 +197,7 @@ export interface RunAgentOptions {
192
197
  const REPEAT_WARN = 3;
193
198
  const REPEAT_STOP = 6;
194
199
  const DEFAULT_MAX_ROUNDS = 100;
195
- const DEFAULT_CONTEXT_LIMIT = 100_000;
200
+ const DEFAULT_CONTEXT_LIMIT = 200_000;
196
201
  const RESERVED_TOKENS = 12_000;
197
202
  /** Recent messages always kept verbatim when compacting. */
198
203
  const KEEP_RECENT = 5;
@@ -620,8 +625,11 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
620
625
  }
621
626
  }
622
627
 
623
- const apiMessages = buildApiMessages(messages, systemPrompt, compactionNote, compactedUpto);
624
- let textContent = '';
628
+ const apiMessages = buildApiMessages(messages, systemPrompt, compactionNote, compactedUpto);
629
+ let textContent = '';
630
+ let thinkingContent = '';
631
+ let thinkingStart: number | null = null;
632
+ let thinkingMs: number | null = null;
625
633
  const toolCalls: NonNullable<AssistantMsg['toolCalls']> = [];
626
634
 
627
635
  try {
@@ -633,8 +641,13 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
633
641
  ...getEffortParams(model, reasoningEffort),
634
642
  } as never) as AsyncGenerator<StreamEvent>) {
635
643
  if (event.type === 'text' && event.content) {
644
+ if (thinkingMs === null && thinkingStart !== null) thinkingMs = Date.now() - thinkingStart;
636
645
  textContent += event.content;
637
646
  yield {type: 'text-delta', content: event.content};
647
+ } else if (event.type === 'thinking' && event.content) {
648
+ if (thinkingStart === null) thinkingStart = Date.now();
649
+ thinkingContent += event.content;
650
+ yield {type: 'thinking-delta', content: event.content};
638
651
  } else if (event.type === 'tool_use' && event.toolCall) {
639
652
  toolCalls.push(event.toolCall);
640
653
  } else if (event.type === 'error') {
@@ -655,16 +668,20 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
655
668
  }
656
669
 
657
670
  // ── No tool calls → turn complete ──
671
+ if (thinkingMs === null && thinkingStart !== null) thinkingMs = Date.now() - thinkingStart;
672
+ const thinkingMeta = thinkingContent
673
+ ? {thinking: thinkingContent, thinkingMs: thinkingMs ?? 0}
674
+ : {};
658
675
  if (toolCalls.length === 0) {
659
676
  if (!textContent.trim()) {
660
677
  console.warn('pal: empty assistant response (no text and no tool calls)');
661
678
  }
662
- messages.push({role: 'assistant', content: textContent});
679
+ messages.push({role: 'assistant', content: textContent, ...thinkingMeta});
663
680
  yield {type: 'done', model, rounds: roundsRun, usage: usage()};
664
681
  return;
665
682
  }
666
683
 
667
- messages.push({role: 'assistant', content: textContent, toolCalls});
684
+ messages.push({role: 'assistant', content: textContent, toolCalls, ...thinkingMeta});
668
685
 
669
686
  const displays = toolCalls.map((tc) => {
670
687
  let argsSummary = '';
@@ -810,6 +827,8 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
810
827
  yield {type: 'round-start', round: roundsRun + 1, max: roundsRun + 1};
811
828
 
812
829
  let wrapText = '';
830
+ let wrapThinking = '';
831
+ let wrapThinkingStart: number | null = null;
813
832
  try {
814
833
  for await (const event of provider.stream({
815
834
  model,
@@ -821,6 +840,10 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
821
840
  if (event.type === 'text' && event.content) {
822
841
  wrapText += event.content;
823
842
  yield {type: 'text-delta', content: event.content};
843
+ } else if (event.type === 'thinking' && event.content) {
844
+ if (wrapThinkingStart === null) wrapThinkingStart = Date.now();
845
+ wrapThinking += event.content;
846
+ yield {type: 'thinking-delta', content: event.content};
824
847
  } else if (event.type === 'done' && event.usage) {
825
848
  totalInput += event.usage.promptTokens ?? 0;
826
849
  totalOutput += event.usage.completionTokens ?? 0;
@@ -838,7 +861,17 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
838
861
  text: `! wrap-up failed: ${err instanceof Error ? err.message : String(err)}`,
839
862
  };
840
863
  }
841
- if (wrapText) messages.push({role: 'assistant', content: wrapText});
864
+ if (wrapText)
865
+ messages.push({
866
+ role: 'assistant',
867
+ content: wrapText,
868
+ ...(wrapThinking
869
+ ? {
870
+ thinking: wrapThinking,
871
+ thinkingMs: wrapThinkingStart !== null ? Date.now() - wrapThinkingStart : 0,
872
+ }
873
+ : {}),
874
+ });
842
875
  }
843
876
 
844
877
  yield {type: 'done', model, rounds: roundsRun, usage: usage()};
@@ -0,0 +1,380 @@
1
+ /**
2
+ * One agent turn: drive `runWithFallback` and translate its events into a
3
+ * caller-supplied UI port. The orchestrator is UI-agnostic — the TUI and the
4
+ * WebSocket/desktop frontends are both adapters over `AgentUi`.
5
+ */
6
+
7
+ import {importExtensionModule, loadExtensions} from '../extensions.js';
8
+ import type {LoadedExtensions} from '../extensions.js';
9
+ import {registerExtensionLifecycle} from '../lifecycle.js';
10
+ import type {ProviderKeys} from '../provider/auth.js';
11
+ import type {Provider} from '../provider/types.js';
12
+ import type {ExtensionStatus, McpServerStatus} from '../runtime/state.js';
13
+
14
+ export type {ExtensionStatus, McpServerStatus} from '../runtime/state.js';
15
+ import {getExtensionPrompts, registerExtensionPrompts} from '../lifecycle.js';
16
+ import {
17
+ CORE_TOOLS,
18
+ getAllTools,
19
+ getExtensionTools,
20
+ registerExtensionTools,
21
+ validateRequiredArgs,
22
+ } from '../tools/definitions.js';
23
+ import type {ToolDef} from '../tools/definitions.js';
24
+ import {executeTool, registerExtensionHandlers} from '../tools/executor.js';
25
+ import type {ToolResult} from '../tools/executor.js';
26
+ import {clearFileRolesCache} from './file-roles.js';
27
+ import {runWithFallback, shortModel} from './fallback.js';
28
+ import {buildRolesPrompt, defaultPrimaryName, listPrimaries, resolvePrimary} from './roles.js';
29
+ import type {ConversationMessage} from './run.js';
30
+ import {buildSkillsPrompt, clearSkillsCache} from './skills.js';
31
+
32
+ export interface TurnResult {
33
+ inputTokens: number;
34
+ outputTokens: number;
35
+ cachedTokens: number;
36
+ /** The model that actually served this turn (may differ from settings.model after a fallback). */
37
+ model: string;
38
+ /** Checkpoints this turn produced (auto-compaction can fire more than once). */
39
+ compactions: Array<{boundary: number; summarized: number; summary: string}>;
40
+ }
41
+
42
+ /** The configuration a single turn needs. The CLI Config is structurally compatible. */
43
+ export interface TurnSettings {
44
+ model: string;
45
+ systemPrompt: string;
46
+ maxToolRounds: number;
47
+ maxRetries: number;
48
+ retryBaseMs: number;
49
+ contextLimit: number;
50
+ reasoningEffort: 'low' | 'medium' | 'high';
51
+ modelRotation: boolean;
52
+ extensions: string[];
53
+ }
54
+
55
+ /**
56
+ * Everything a turn reports to its frontend. Implementations must be cheap:
57
+ * the loop calls these once per stream event.
58
+ */
59
+ export interface AgentUi {
60
+ startRun(model: string): void;
61
+ setModel(model: string): void;
62
+ beginRound(round: number, max: number): void;
63
+ text(delta: string): void;
64
+ thinking(delta: string): void;
65
+ toolStart(id: string, name: string, argsSummary: string): void;
66
+ toolEnd(id: string, ok: boolean, content: string): void;
67
+ notice(text: string): void;
68
+ aborted(): void;
69
+ extensions?(extensions: ExtensionStatus[]): void;
70
+ mcpServers?(servers: McpServerStatus[]): void;
71
+ primary?(name: string): void;
72
+ /** Called after extension loading finishes, so the frontend can repaint state. */
73
+ ready?(): void;
74
+ }
75
+
76
+ export type ApprovalDecision = 'allow' | 'deny';
77
+
78
+ /** Ask the frontend whether a tool call may run. */
79
+ export type Approval = (
80
+ toolName: string,
81
+ args: Record<string, unknown>,
82
+ ) => Promise<ApprovalDecision>;
83
+
84
+ /** Default extension set when the user hasn't configured one. */
85
+ export const DEFAULT_EXTENSIONS = ['@pal-code/web-search', '@pal-code/agents', '@pal-code/mcp'];
86
+
87
+ let extensionsLoaded = false;
88
+
89
+ /**
90
+ * Apply a successful load to the process: register tools, handlers and
91
+ * lifecycle hooks centrally, then publish the resulting state to the UI port.
92
+ */
93
+ async function applyLoaded(
94
+ requested: string[],
95
+ result: LoadedExtensions,
96
+ ui: AgentUi,
97
+ currentPrimary?: string,
98
+ ): Promise<void> {
99
+ registerExtensionHandlers(result.handlers);
100
+ registerExtensionTools(result.tools);
101
+ registerExtensionLifecycle(result.lifecycle);
102
+ registerExtensionPrompts(result.prompts);
103
+
104
+ const active = new Set(result.loaded);
105
+ const failedByPkg = new Map(result.failed.map((f) => [f.pkg, f.reason]));
106
+ const unavailableByPkg = new Map(result.unavailable.map((u) => [u.pkg, u.reason]));
107
+ ui.extensions?.(
108
+ requested.map((pkg) => {
109
+ // "Loaded but inert" is not a failure: the package worked, it just has
110
+ // nothing to contribute (no key). Kept distinct so the UI does not cry
111
+ // wolf in red about a deliberate state.
112
+ const status = active.has(pkg)
113
+ ? 'active'
114
+ : failedByPkg.has(pkg)
115
+ ? 'failed'
116
+ : 'inactive';
117
+ return {
118
+ name: pkg.replace(/^@pal-code\//, ''),
119
+ active: status === 'active',
120
+ status,
121
+ reason: failedByPkg.get(pkg) ?? unavailableByPkg.get(pkg) ?? undefined,
122
+ };
123
+ }),
124
+ );
125
+
126
+ // Populate MCP server status live from the manager. Resolved through core
127
+ // so `pal add` installs (under ~/.pal/extensions/node_modules) and compiled
128
+ // binaries both resolve correctly.
129
+ try {
130
+ const mcpMod = (await importExtensionModule('@pal-code/mcp')) as {
131
+ mcpManager?: {getServerDetails(): McpServerStatus[]};
132
+ };
133
+ if (mcpMod?.mcpManager) ui.mcpServers?.(mcpMod.mcpManager.getServerDetails());
134
+ } catch {
135
+ // MCP extension not available — skip silently
136
+ }
137
+
138
+ // Primaries are registered by the extension's setup hook during load.
139
+ // Adopt the configured default unless the caller already picked one.
140
+ const primaries = listPrimaries();
141
+ if (primaries.length > 0 && !primaries.some((p) => p.name === currentPrimary)) {
142
+ ui.primary?.(defaultPrimaryName());
143
+ }
144
+
145
+ ui.ready?.();
146
+ }
147
+
148
+ export async function ensureExtensionsLoaded(
149
+ extensions: string[] | undefined,
150
+ ui: AgentUi,
151
+ currentPrimary?: string,
152
+ ): Promise<void> {
153
+ if (extensionsLoaded) return;
154
+
155
+ const requested = extensions ?? DEFAULT_EXTENSIONS;
156
+ const result = await loadExtensions(requested);
157
+ extensionsLoaded = true;
158
+ await applyLoaded(requested, result, ui, currentPrimary);
159
+ }
160
+
161
+ /**
162
+ * Re-import extensions without restarting the process. Uses the loader's
163
+ * `cacheBust` option so edited extension source is picked up.
164
+ */
165
+ export async function reloadExtensions(
166
+ extensions: string[] | undefined,
167
+ ui: AgentUi,
168
+ currentPrimary?: string,
169
+ ): Promise<number> {
170
+ const requested = extensions ?? DEFAULT_EXTENSIONS;
171
+ const result = await loadExtensions(requested, {cacheBust: true});
172
+ extensionsLoaded = true;
173
+ clearFileRolesCache();
174
+ clearSkillsCache();
175
+ await applyLoaded(requested, result, ui, currentPrimary);
176
+ return result.tools.length;
177
+ }
178
+
179
+ /**
180
+ * Compose the system prompt for a turn: the base prompt, an optional primary
181
+ * agent preamble, the role-awareness block, the skill listing (only when
182
+ * skill files exist), and any guidance contributed by loaded extensions.
183
+ * Every piece is skipped when absent, so users with no extensions or skills pay
184
+ * nothing in tokens.
185
+ */
186
+ export function composeSystemPrompt(base: string, primaryName?: string): string {
187
+ const parts: string[] = [];
188
+ const primary = primaryName ? resolvePrimary(primaryName) : null;
189
+ if (primary?.systemPrompt) parts.push(primary.systemPrompt);
190
+ parts.push(base);
191
+ const roles = buildRolesPrompt();
192
+ if (roles) parts.push(roles);
193
+ const skills = buildSkillsPrompt();
194
+ if (skills) parts.push(skills);
195
+ // Placed last on purpose: it is the most specific, most actionable guidance,
196
+ // and it describes tools the model has already seen in its tool list.
197
+ const extensionPrompts = extensionPromptsFor(primary);
198
+ if (extensionPrompts) parts.push(extensionPrompts);
199
+ return parts.join('\n\n');
200
+ }
201
+
202
+ /**
203
+ * Extension guidance for the active primary, or `''` when there is none.
204
+ *
205
+ * A primary that declares a `tools` list is deliberately narrowed (that is how
206
+ * plan mode is enforced). Guidance is withheld unless at least one of the
207
+ * primary's tools actually came from an extension — otherwise a read-only agent
208
+ * would be told about tools it cannot call, which is precisely the wasted
209
+ * attention this mechanism exists to avoid.
210
+ *
211
+ * The narrowing check is coarse by necessity: prompts and tools are collected
212
+ * independently, so this cannot attribute a specific fragment to a specific
213
+ * tool. Extension tools are simply "registered tools that are not core tools".
214
+ */
215
+ function extensionPromptsFor(primary: {
216
+ tools?: readonly string[];
217
+ } | null): string {
218
+ const prompts = getExtensionPrompts();
219
+ if (prompts.length === 0) return '';
220
+
221
+ if (primary?.tools) {
222
+ const coreNames = new Set(CORE_TOOLS.map((t) => t.function.name));
223
+ const extensionTools = getExtensionTools().filter((t) => !coreNames.has(t.function.name));
224
+ const reachesExtensions = extensionTools.some((t) => primary.tools?.includes(t.function.name));
225
+ if (!reachesExtensions) return '';
226
+ }
227
+
228
+ return prompts.join('\n\n');
229
+ }
230
+
231
+ /** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
232
+ export function toolsForPrimary(primaryName?: string): ToolDef[] {
233
+ const all = getAllTools();
234
+ const primary = primaryName ? resolvePrimary(primaryName) : null;
235
+ if (!primary?.tools) return all;
236
+ const allowed = new Set(primary.tools);
237
+ return all.filter((t) => allowed.has(t.function.name));
238
+ }
239
+
240
+ /**
241
+ * Whether the active primary is a read-only agent.
242
+ *
243
+ * A primary that declares a `tools` list is deliberately narrowed (that is how
244
+ * plan mode is enforced); one without is unrestricted. Propagating this stops a
245
+ * read-only turn from reaching a writer through `delegate`.
246
+ */
247
+ export function isReadOnlyPrimary(primaryName?: string): boolean {
248
+ const primary = primaryName ? resolvePrimary(primaryName) : null;
249
+ return Array.isArray(primary?.tools);
250
+ }
251
+
252
+ /**
253
+ * The tool names the turn is permitted to dispatch, or `undefined` when the
254
+ * primary is unrestricted. Returned to core so `executeTool` can enforce it.
255
+ */
256
+ export function allowedToolsForPrimary(primaryName?: string): string[] | undefined {
257
+ return resolvePrimary(primaryName ?? '')?.tools;
258
+ }
259
+
260
+ /** Permission-gated wrapper around `executeTool`. */
261
+ async function gatedExecuteTool(
262
+ name: string,
263
+ argsStr: string,
264
+ toolCallId: string,
265
+ approve: Approval,
266
+ providerConfigOverride?: {
267
+ model: string;
268
+ apiKey: string;
269
+ baseUrl: string;
270
+ keys?: Record<string, string>;
271
+ headers?: Record<string, string>;
272
+ systemPromptAppend?: string;
273
+ readOnly?: boolean;
274
+ allowedTools?: string[];
275
+ },
276
+ signal?: AbortSignal,
277
+ ): Promise<ToolResult> {
278
+ let args: Record<string, unknown> = {};
279
+ try {
280
+ args = argsStr && argsStr.trim() ? JSON.parse(argsStr) : {};
281
+ } catch {
282
+ // If args can't be parsed, let executeTool handle the error.
283
+ }
284
+
285
+ // Reject schema-incomplete calls before the permission gate, so a call
286
+ // missing required arguments can't trigger an approval prompt and then fail.
287
+ const validationError = validateRequiredArgs(name, args);
288
+ if (validationError) {
289
+ return {toolCallId, content: validationError, error: true};
290
+ }
291
+
292
+ const decision = await approve(name, args);
293
+ if (decision === 'deny') {
294
+ return {toolCallId, content: `Error: Permission denied for ${name}.`, error: true};
295
+ }
296
+
297
+ return executeTool(name, argsStr, toolCallId, providerConfigOverride, signal);
298
+ }
299
+
300
+ /**
301
+ * Run one user turn against the shared agent loop. All UI effects go through
302
+ * `ui`; all approval decisions go through `approve`.
303
+ */
304
+ export async function runTurn(
305
+ userMessage: string,
306
+ messages: ConversationMessage[],
307
+ settings: TurnSettings,
308
+ allKeys: ProviderKeys,
309
+ createProvider: (model: string) => Provider,
310
+ ui: AgentUi,
311
+ approve: Approval,
312
+ primaryName?: string,
313
+ compactedSeq = 0,
314
+ compactionNote = '',
315
+ signal?: AbortSignal,
316
+ ): Promise<TurnResult> {
317
+ await ensureExtensionsLoaded(settings.extensions, ui, primaryName);
318
+
319
+ messages.push({role: 'user', content: userMessage});
320
+
321
+ ui.startRun(shortModel(settings.model));
322
+
323
+ let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
324
+ let activeModel = settings.model;
325
+ const compactions: TurnResult['compactions'] = [];
326
+
327
+ for await (const ev of runWithFallback({
328
+ messages,
329
+ tools: toolsForPrimary(primaryName),
330
+ model: settings.model,
331
+ systemPrompt: composeSystemPrompt(settings.systemPrompt, primaryName),
332
+ maxToolRounds: settings.maxToolRounds,
333
+ contextLimit: settings.contextLimit,
334
+ reasoningEffort: settings.reasoningEffort,
335
+ compactedSeq,
336
+ compactionNote,
337
+ maxRetries: settings.maxRetries,
338
+ retryBaseMs: settings.retryBaseMs,
339
+ rotate: settings.modelRotation,
340
+ keys: allKeys,
341
+ executeTool: (name, argsStr, toolCallId, override, signal) =>
342
+ gatedExecuteTool(name, argsStr, toolCallId, approve, override, signal),
343
+ childExecuteTool: (name, argsStr, toolCallId, override, signal) =>
344
+ gatedExecuteTool(name, argsStr, toolCallId, approve, override, signal),
345
+ signal,
346
+ primary: primaryName,
347
+ readOnly: isReadOnlyPrimary(primaryName),
348
+ allowedTools: allowedToolsForPrimary(primaryName),
349
+ createProvider: (spec: string) => createProvider(spec),
350
+ })) {
351
+ if (ev.type === 'model-start') {
352
+ activeModel = ev.model;
353
+ ui.setModel(shortModel(ev.model));
354
+ } else if (ev.type === 'round-start') ui.beginRound(ev.round, ev.max);
355
+ else if (ev.type === 'text-delta') ui.text(ev.content);
356
+ else if (ev.type === 'thinking-delta') ui.thinking(ev.content);
357
+ else if (ev.type === 'tool-start') ui.toolStart(ev.id, ev.name, ev.argsSummary);
358
+ else if (ev.type === 'tool-end') ui.toolEnd(ev.id, ev.ok, ev.content);
359
+ else if (ev.type === 'notice') {
360
+ // The compaction notice is superseded by the caller's green transcript
361
+ // line; the dim inline copy vanished with the run block's collapse.
362
+ if (!ev.text.startsWith('Context compacted')) ui.notice(ev.text);
363
+ } else if (ev.type === 'compacted') {
364
+ compactions.push({
365
+ boundary: ev.boundary,
366
+ summarized: ev.summarized,
367
+ summary: ev.summary,
368
+ });
369
+ } else if (ev.type === 'aborted') ui.aborted();
370
+ else if (ev.type === 'done') usage = ev.usage;
371
+ }
372
+
373
+ return {
374
+ inputTokens: usage.inputTokens,
375
+ outputTokens: usage.outputTokens,
376
+ cachedTokens: usage.cachedTokens,
377
+ model: activeModel,
378
+ compactions,
379
+ };
380
+ }