@pal-code/core 0.0.16 → 0.0.17

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.17",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
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()};
package/src/index.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  // Provider abstraction (preferred)
2
- export type {Provider, ProviderConfig, ProviderModel, StreamEvent} from './provider/types.js';
2
+ export type {
3
+ Provider,
4
+ ProviderConfig,
5
+ ProviderModel,
6
+ StreamEvent,
7
+ ModelRoute,
8
+ } from './provider/types.js';
3
9
  export {createOpenRouterProvider} from './provider/openrouter.js';
4
10
  export {
5
11
  resolveAuth,
@@ -18,6 +24,8 @@ export {
18
24
  detectProvider,
19
25
  providerForModel,
20
26
  loadCustomProviders,
27
+ resolveRoute,
28
+ mergeProviders,
21
29
  } from './provider/registry.js';
22
30
  export type {ProviderDef} from './provider/registry.js';
23
31
 
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Chat Completions protocol adapter — the OpenAI-compatible streaming wire
3
+ * format used by every built-in provider. Extracted from the provider class so
4
+ * `stream()` can dispatch to another protocol per model.
5
+ */
6
+
7
+ import type {StreamEvent, Usage} from './types.js';
8
+ import {log} from '../logger.js';
9
+
10
+ export interface ToolDef {
11
+ type: 'function';
12
+ function: {
13
+ name: string;
14
+ description: string;
15
+ parameters: Record<string, unknown>;
16
+ };
17
+ }
18
+
19
+ /** Accumulated tool call state during streaming. */
20
+ interface ToolCallAccum {
21
+ id: string;
22
+ name: string;
23
+ arguments: string;
24
+ extra_content?: Record<string, unknown>;
25
+ /** Insertion order — used to emit parallel calls in the order they arrived. */
26
+ seq: number;
27
+ }
28
+
29
+ export interface ChatStreamOptions {
30
+ id: string;
31
+ baseUrl: string;
32
+ /** Bare model id (prefix already stripped). */
33
+ model: string;
34
+ messages: Array<Record<string, unknown>>;
35
+ tools?: ToolDef[];
36
+ headers: Record<string, string>;
37
+ signal?: AbortSignal;
38
+ }
39
+
40
+ /**
41
+ * Pull cache-hit token counts out of an OpenAI-compatible usage object.
42
+ * Field names differ per provider:
43
+ * - DeepSeek: prompt_cache_hit_tokens
44
+ * - OpenAI: prompt_tokens_details.cached_tokens
45
+ * - OpenRouter: prompt_tokens_details.cached_tokens (or cache_read_input_tokens)
46
+ * - Anthropic: cache_read_input_tokens
47
+ * Returns undefined when the provider reports nothing.
48
+ */
49
+ function extractCachedTokens(usage: Record<string, unknown>): number | undefined {
50
+ const direct =
51
+ usage.prompt_cache_hit_tokens ??
52
+ usage.cache_read_input_tokens ??
53
+ (usage.prompt_tokens_details as Record<string, unknown> | undefined)?.cached_tokens;
54
+ return typeof direct === 'number' ? direct : undefined;
55
+ }
56
+
57
+ export async function* streamChat(opts: ChatStreamOptions): AsyncGenerator<StreamEvent> {
58
+ const body: Record<string, unknown> = {
59
+ model: opts.model,
60
+ messages: opts.messages,
61
+ stream: true,
62
+ stream_options: {include_usage: true},
63
+ };
64
+
65
+ // Forward tools if provided — MUST be included in every request with tools
66
+ if (opts.tools && opts.tools.length > 0) {
67
+ body.tools = opts.tools;
68
+ }
69
+
70
+ log('request', {
71
+ provider: opts.id,
72
+ baseUrl: opts.baseUrl,
73
+ model: body.model,
74
+ messageCount: opts.messages.length,
75
+ toolCount: opts.tools?.length ?? 0,
76
+ messages: opts.messages,
77
+ });
78
+
79
+ const res = await fetch(`${opts.baseUrl}/chat/completions`, {
80
+ method: 'POST',
81
+ headers: opts.headers,
82
+ body: JSON.stringify(body),
83
+ signal: opts.signal,
84
+ });
85
+
86
+ if (!res.ok) {
87
+ const err = await res.text();
88
+ log('response-error', {status: res.status, body: err});
89
+ yield {type: 'error', content: `API ${res.status}: ${err}`};
90
+ return;
91
+ }
92
+
93
+ const reader = res.body?.getReader();
94
+ if (!reader) {
95
+ yield {type: 'error', content: 'No response body'};
96
+ return;
97
+ }
98
+
99
+ const decoder = new TextDecoder();
100
+ let buffer = '';
101
+ const toolCallAccumulators = new Map<string, ToolCallAccum>();
102
+ let toolCallSeq = 0;
103
+ let lastUsage: Usage | undefined;
104
+ let finishSeen = false;
105
+
106
+ /** Emit accumulated tool calls in arrival order. */
107
+ const collectToolCalls = (): StreamEvent[] => {
108
+ const ordered = [...toolCallAccumulators.values()].sort((a, b) => a.seq - b.seq);
109
+ const events: StreamEvent[] = [];
110
+ for (const tc of ordered) {
111
+ if (!tc.name) continue;
112
+ events.push({
113
+ type: 'tool_use',
114
+ toolCall: {
115
+ id: tc.id || `call_${Math.random().toString(36).slice(2, 10)}`,
116
+ name: tc.name,
117
+ arguments: tc.arguments || '{}',
118
+ extraContent: tc.extra_content,
119
+ },
120
+ });
121
+ }
122
+ toolCallAccumulators.clear();
123
+ return events;
124
+ };
125
+
126
+ while (true) {
127
+ const {done, value} = await reader.read();
128
+ if (done) break;
129
+
130
+ buffer += decoder.decode(value, {stream: true});
131
+ const lines = buffer.split('\n');
132
+ buffer = lines.pop() ?? '';
133
+
134
+ for (const line of lines) {
135
+ const trimmed = line.trim();
136
+ if (!trimmed.startsWith('data: ')) continue;
137
+ const data = trimmed.slice(6);
138
+ if (data === '[DONE]') continue;
139
+
140
+ try {
141
+ // Providers/gateways occasionally emit raw NUL bytes, which make
142
+ // JSON.parse throw — the catch below would then drop the whole chunk,
143
+ // losing tool-call argument fragments. Strip them before parsing.
144
+ const parsed = JSON.parse(data.replaceAll('\u0000', ''));
145
+ const choice = parsed.choices?.[0];
146
+
147
+ // Extract usage from chunk (Gemini puts it in the last chunk)
148
+ if (parsed.usage) {
149
+ lastUsage = {
150
+ promptTokens: parsed.usage.prompt_tokens ?? 0,
151
+ completionTokens: parsed.usage.completion_tokens ?? 0,
152
+ totalTokens: parsed.usage.total_tokens ?? 0,
153
+ cachedTokens: extractCachedTokens(parsed.usage),
154
+ };
155
+ log('usage', lastUsage);
156
+ }
157
+
158
+ // Usage can also appear without choices (Gemini style)
159
+ if (!choice && parsed.usage) continue;
160
+
161
+ const delta = choice.delta;
162
+
163
+ // Text content — strip escaped NULs that survive JSON.parse
164
+ // (stray null bytes corrupt rendered text and commands downstream).
165
+ if (delta?.content) {
166
+ yield {type: 'text', content: delta.content.replaceAll('\u0000', '')};
167
+ }
168
+
169
+ // Thinking content — DeepSeek-style `reasoning_content` and gateway
170
+ // `reasoning` (string or content-part array). Display-only downstream.
171
+ const thinking = delta?.reasoning_content ?? delta?.reasoning;
172
+ if (typeof thinking === 'string' && thinking) {
173
+ yield {type: 'thinking', content: thinking.replaceAll('\u0000', '')};
174
+ } else if (Array.isArray(thinking)) {
175
+ const text = thinking
176
+ .map((part) => (typeof part === 'string' ? part : part?.text))
177
+ .filter((t): t is string => typeof t === 'string' && t.length > 0)
178
+ .join('');
179
+ if (text) yield {type: 'thinking', content: text.replaceAll('\u0000', '')};
180
+ }
181
+
182
+ // Tool calls — accumulate arguments across chunks.
183
+ // OpenAI/DeepSeek stream one call as [id+name] then [argument fragments],
184
+ // where only `index` repeats across chunks. Some providers (Gemini) have
185
+ // been observed reusing index 0 across parallel calls, so a *new id* on an
186
+ // already-named index starts a fresh accumulator instead of merging.
187
+ if (delta?.tool_calls) {
188
+ for (const tc of delta.tool_calls) {
189
+ const idxKey = String(tc.index ?? 0);
190
+ let existing = toolCallAccumulators.get(idxKey);
191
+
192
+ if (existing && tc.id && existing.id && tc.id !== existing.id) {
193
+ // Same index, different call — park the previous one under a unique key.
194
+ toolCallAccumulators.delete(idxKey);
195
+ toolCallAccumulators.set(`${idxKey}#${existing.seq}`, existing);
196
+ existing = undefined;
197
+ }
198
+
199
+ if (!existing) {
200
+ existing = {
201
+ id: '',
202
+ name: '',
203
+ arguments: '',
204
+ extra_content: undefined,
205
+ seq: toolCallSeq++,
206
+ };
207
+ toolCallAccumulators.set(idxKey, existing);
208
+ }
209
+
210
+ // Strip NULs at the read point: escaped null bytes survive
211
+ // JSON.parse and would otherwise corrupt ids/names/arguments.
212
+ if (tc.id) existing.id = tc.id.replaceAll('\u0000', '');
213
+ if (tc.function?.name) existing.name = tc.function.name.replaceAll('\u0000', '');
214
+ if (tc.function?.arguments)
215
+ existing.arguments += tc.function.arguments.replaceAll('\u0000', '');
216
+ // Capture Gemini's extra_content (contains thought_signature)
217
+ if (tc.extra_content && !existing.extra_content) {
218
+ existing.extra_content = tc.extra_content;
219
+ }
220
+ }
221
+ }
222
+
223
+ // Finish reason — emit accumulated tool calls once, but keep reading:
224
+ // OpenAI-compatible providers send the usage-only chunk *after* the
225
+ // finish_reason chunk, so returning here would drop token usage.
226
+ if (choice.finish_reason === 'tool_calls') {
227
+ for (const ev of collectToolCalls()) yield ev;
228
+ finishSeen = true;
229
+ continue;
230
+ }
231
+
232
+ // Normal finish — also emit any accumulated tool calls
233
+ // (Gemini sends finish_reason="stop" even with tool calls)
234
+ if (choice.finish_reason && choice.finish_reason !== 'length') {
235
+ for (const ev of collectToolCalls()) yield ev;
236
+ finishSeen = true;
237
+ }
238
+ } catch {
239
+ // skip unparseable
240
+ }
241
+ }
242
+ }
243
+
244
+ // Stream ended — emit any tool calls that arrived without a finish_reason,
245
+ // then close with the last usage we saw (usually from the final chunk).
246
+ if (!finishSeen) {
247
+ for (const ev of collectToolCalls()) yield ev;
248
+ }
249
+ yield {type: 'done', usage: lastUsage};
250
+ }
@@ -1,6 +1,7 @@
1
- export type {Provider, ProviderConfig, ProviderModel, StreamEvent} from './types.js';
1
+ export type {Provider, ProviderConfig, ProviderModel, StreamEvent, ModelRoute} from './types.js';
2
2
  export {createOpenRouterProvider} from './openrouter.js';
3
3
  export {resolveAuth} from './auth.js';
4
4
  export {complete} from './complete.js';
5
5
  export type {CompleteOptions, CompleteResult} from './complete.js';
6
6
  export {pickCheapModel} from './pick-model.js';
7
+ export {resolveRoute, mergeProviders} from './registry.js';
@@ -1,11 +1,20 @@
1
1
  /**
2
2
  * OpenRouter provider — works with free models out of the box.
3
3
  * Supports tool/function calling via OpenAI-compatible format.
4
+ *
5
+ * The wire protocol is chosen per model: chat-completions is the default, and
6
+ * a provider definition may declare `modelRoutes` to send matching models to
7
+ * the Responses adapter instead. A provider with no routes behaves exactly as
8
+ * before.
4
9
  */
5
10
 
6
- import type {Provider, ProviderConfig, ProviderModel, StreamEvent, Usage} from './types.js';
11
+ import type {Provider, ProviderConfig, ProviderModel, StreamEvent, ModelRoute} from './types.js';
7
12
  import {randomBytes} from 'crypto';
8
- import {log} from '../logger.js';
13
+ import {getProvider, resolveRoute} from './registry.js';
14
+ import {streamChat, type ToolDef} from './chat.js';
15
+ import {streamResponses} from './responses.js';
16
+
17
+ export type {ToolDef} from './chat.js';
9
18
 
10
19
  const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
11
20
 
@@ -44,43 +53,6 @@ export function expandRandomValue(val: string): string {
44
53
  return prefix + hex;
45
54
  }
46
55
 
47
- /**
48
- * Pull cache-hit token counts out of an OpenAI-compatible usage object.
49
- * Field names differ per provider:
50
- * - DeepSeek: prompt_cache_hit_tokens
51
- * - OpenAI: prompt_tokens_details.cached_tokens
52
- * - OpenRouter: prompt_tokens_details.cached_tokens (or cache_read_input_tokens)
53
- * - Anthropic: cache_read_input_tokens
54
- * Returns undefined when the provider reports nothing.
55
- */
56
- function extractCachedTokens(usage: Record<string, unknown>): number | undefined {
57
- const direct =
58
- usage.prompt_cache_hit_tokens ??
59
- usage.cache_read_input_tokens ??
60
- (usage.prompt_tokens_details as Record<string, unknown> | undefined)?.cached_tokens;
61
- return typeof direct === 'number' ? direct : undefined;
62
- }
63
-
64
- /** Tool definition in OpenAI function calling format. */
65
- export interface ToolDef {
66
- type: 'function';
67
- function: {
68
- name: string;
69
- description: string;
70
- parameters: Record<string, unknown>;
71
- };
72
- }
73
-
74
- /** Accumulated tool call state during streaming. */
75
- interface ToolCallAccum {
76
- id: string;
77
- name: string;
78
- arguments: string;
79
- extra_content?: Record<string, unknown>;
80
- /** Insertion order — used to emit parallel calls in the order they arrived. */
81
- seq: number;
82
- }
83
-
84
56
  export function createOpenRouterProvider(config: ProviderConfig): Provider {
85
57
  return new OpenRouterProvider(config);
86
58
  }
@@ -90,6 +62,8 @@ class OpenRouterProvider implements Provider {
90
62
  private baseUrl: string;
91
63
  private apiKey: string;
92
64
  private modelPrefix: string;
65
+ private defaultProtocol?: 'chat';
66
+ private modelRoutes: ModelRoute[];
93
67
  /** Static headers (no random tokens). */
94
68
  private baseHeaders: Record<string, string>;
95
69
  /** Headers that may contain __random:…__ tokens — expanded fresh per stream(). */
@@ -107,6 +81,10 @@ class OpenRouterProvider implements Provider {
107
81
  ...(referer ? {'HTTP-Referer': referer} : {}),
108
82
  };
109
83
  this.customHeaders = config.headers ?? {};
84
+ // Routes come from the caller or, for registry providers, the definition.
85
+ const def = getProvider(config.id);
86
+ this.defaultProtocol = config.defaultProtocol ?? def?.defaultProtocol;
87
+ this.modelRoutes = config.modelRoutes ?? def?.modelRoutes ?? [];
110
88
  }
111
89
 
112
90
  /** Compute headers with random tokens expanded fresh (new id per call). */
@@ -116,7 +94,7 @@ class OpenRouterProvider implements Provider {
116
94
  out[k] = expandRandomValue(v);
117
95
  }
118
96
  if (this.apiKey) {
119
- out['Authorization'] = `Bearer ${this.apiKey}`;
97
+ out.Authorization = `Bearer ${this.apiKey}`;
120
98
  }
121
99
  return out;
122
100
  }
@@ -152,184 +130,35 @@ class OpenRouterProvider implements Provider {
152
130
  tools?: ToolDef[];
153
131
  signal?: AbortSignal;
154
132
  }): AsyncGenerator<StreamEvent> {
155
- const body: Record<string, unknown> = {
156
- model: this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model,
157
- messages: opts.messages,
158
- stream: true,
159
- stream_options: {include_usage: true},
160
- };
161
-
162
- // Forward tools if provided — MUST be included in every request with tools
163
- if (opts.tools && opts.tools.length > 0) {
164
- body.tools = opts.tools;
133
+ const model = this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model;
134
+ const route = resolveRoute(
135
+ {defaultProtocol: this.defaultProtocol, modelRoutes: this.modelRoutes},
136
+ model,
137
+ );
138
+ const headers = this.computeHeaders();
139
+
140
+ if (route.protocol === 'responses') {
141
+ yield* streamResponses({
142
+ id: this.id,
143
+ baseUrl: this.baseUrl,
144
+ model,
145
+ messages: opts.messages,
146
+ tools: opts.tools,
147
+ headers,
148
+ signal: opts.signal,
149
+ path: route.path,
150
+ });
151
+ return;
165
152
  }
166
153
 
167
- log('request', {
168
- provider: this.id,
154
+ yield* streamChat({
155
+ id: this.id,
169
156
  baseUrl: this.baseUrl,
170
- model: body.model,
171
- messageCount: opts.messages.length,
172
- toolCount: opts.tools?.length ?? 0,
157
+ model,
173
158
  messages: opts.messages,
174
- });
175
-
176
- const res = await fetch(`${this.baseUrl}/chat/completions`, {
177
- method: 'POST',
178
- headers: this.computeHeaders(),
179
- body: JSON.stringify(body),
159
+ tools: opts.tools,
160
+ headers,
180
161
  signal: opts.signal,
181
162
  });
182
-
183
- if (!res.ok) {
184
- const err = await res.text();
185
- log('response-error', {status: res.status, body: err});
186
- yield {type: 'error', content: `API ${res.status}: ${err}`};
187
- return;
188
- }
189
-
190
- const reader = res.body?.getReader();
191
- if (!reader) {
192
- yield {type: 'error', content: 'No response body'};
193
- return;
194
- }
195
-
196
- const decoder = new TextDecoder();
197
- let buffer = '';
198
- const toolCallAccumulators = new Map<string, ToolCallAccum>();
199
- let toolCallSeq = 0;
200
- let lastUsage: Usage | undefined;
201
- let finishSeen = false;
202
-
203
- /** Emit accumulated tool calls in arrival order. */
204
- const collectToolCalls = (): StreamEvent[] => {
205
- const ordered = [...toolCallAccumulators.values()].sort((a, b) => a.seq - b.seq);
206
- const events: StreamEvent[] = [];
207
- for (const tc of ordered) {
208
- if (!tc.name) continue;
209
- events.push({
210
- type: 'tool_use',
211
- toolCall: {
212
- id: tc.id || `call_${Math.random().toString(36).slice(2, 10)}`,
213
- name: tc.name,
214
- arguments: tc.arguments || '{}',
215
- extraContent: tc.extra_content,
216
- },
217
- });
218
- }
219
- toolCallAccumulators.clear();
220
- return events;
221
- };
222
-
223
- while (true) {
224
- const {done, value} = await reader.read();
225
- if (done) break;
226
-
227
- buffer += decoder.decode(value, {stream: true});
228
- const lines = buffer.split('\n');
229
- buffer = lines.pop() ?? '';
230
-
231
- for (const line of lines) {
232
- const trimmed = line.trim();
233
- if (!trimmed.startsWith('data: ')) continue;
234
- const data = trimmed.slice(6);
235
- if (data === '[DONE]') continue;
236
-
237
- try {
238
- // Providers/gateways occasionally emit raw NUL bytes, which make
239
- // JSON.parse throw — the catch below would then drop the whole chunk,
240
- // losing tool-call argument fragments. Strip them before parsing.
241
- const parsed = JSON.parse(data.replaceAll('\u0000', ''));
242
- const choice = parsed.choices?.[0];
243
-
244
- // Extract usage from chunk (Gemini puts it in the last chunk)
245
- if (parsed.usage) {
246
- lastUsage = {
247
- promptTokens: parsed.usage.prompt_tokens ?? 0,
248
- completionTokens: parsed.usage.completion_tokens ?? 0,
249
- totalTokens: parsed.usage.total_tokens ?? 0,
250
- cachedTokens: extractCachedTokens(parsed.usage),
251
- };
252
- log('usage', lastUsage);
253
- }
254
-
255
- // Usage can also appear without choices (Gemini style)
256
- if (!choice && parsed.usage) continue;
257
-
258
- const delta = choice.delta;
259
-
260
- // Text content — strip escaped NULs that survive JSON.parse
261
- // (stray null bytes corrupt rendered text and commands downstream).
262
- if (delta?.content) {
263
- yield {type: 'text', content: delta.content.replaceAll('\u0000', '')};
264
- }
265
-
266
- // Tool calls — accumulate arguments across chunks.
267
- // OpenAI/DeepSeek stream one call as [id+name] then [argument fragments],
268
- // where only `index` repeats across chunks. Some providers (Gemini) have
269
- // been observed reusing index 0 across parallel calls, so a *new id* on an
270
- // already-named index starts a fresh accumulator instead of merging.
271
- if (delta?.tool_calls) {
272
- for (const tc of delta.tool_calls) {
273
- const idxKey = String(tc.index ?? 0);
274
- let existing = toolCallAccumulators.get(idxKey);
275
-
276
- if (existing && tc.id && existing.id && tc.id !== existing.id) {
277
- // Same index, different call — park the previous one under a unique key.
278
- toolCallAccumulators.delete(idxKey);
279
- toolCallAccumulators.set(`${idxKey}#${existing.seq}`, existing);
280
- existing = undefined;
281
- }
282
-
283
- if (!existing) {
284
- existing = {
285
- id: '',
286
- name: '',
287
- arguments: '',
288
- extra_content: undefined,
289
- seq: toolCallSeq++,
290
- };
291
- toolCallAccumulators.set(idxKey, existing);
292
- }
293
-
294
- // Strip NULs at the read point: escaped null bytes survive
295
- // JSON.parse and would otherwise corrupt ids/names/arguments.
296
- if (tc.id) existing.id = tc.id.replaceAll('\u0000', '');
297
- if (tc.function?.name) existing.name = tc.function.name.replaceAll('\u0000', '');
298
- if (tc.function?.arguments)
299
- existing.arguments += tc.function.arguments.replaceAll('\u0000', '');
300
- // Capture Gemini's extra_content (contains thought_signature)
301
- if (tc.extra_content && !existing.extra_content) {
302
- existing.extra_content = tc.extra_content;
303
- }
304
- }
305
- }
306
-
307
- // Finish reason — emit accumulated tool calls once, but keep reading:
308
- // OpenAI-compatible providers send the usage-only chunk *after* the
309
- // finish_reason chunk, so returning here would drop token usage.
310
- if (choice.finish_reason === 'tool_calls') {
311
- for (const ev of collectToolCalls()) yield ev;
312
- finishSeen = true;
313
- continue;
314
- }
315
-
316
- // Normal finish — also emit any accumulated tool calls
317
- // (Gemini sends finish_reason="stop" even with tool calls)
318
- if (choice.finish_reason && choice.finish_reason !== 'length') {
319
- for (const ev of collectToolCalls()) yield ev;
320
- finishSeen = true;
321
- }
322
- } catch {
323
- // skip unparseable
324
- }
325
- }
326
- }
327
-
328
- // Stream ended — emit any tool calls that arrived without a finish_reason,
329
- // then close with the last usage we saw (usually from the final chunk).
330
- if (!finishSeen) {
331
- for (const ev of collectToolCalls()) yield ev;
332
- }
333
- yield {type: 'done', usage: lastUsage};
334
163
  }
335
164
  }
@@ -16,6 +16,8 @@
16
16
  * expands to a fresh session-shaped id (`ses_` + 12 hex + 14 base62).
17
17
  */
18
18
 
19
+ import type {ModelRoute} from './types.js';
20
+
19
21
  export interface ProviderDef {
20
22
  /** Stable id, also the config key. */
21
23
  id: string;
@@ -51,6 +53,10 @@ export interface ProviderDef {
51
53
  alias?: string;
52
54
  /** Prefix to strip from model names before sending to the API (e.g. "opencode/"). */
53
55
  modelPrefix?: string;
56
+ /** Protocol used when no `modelRoutes` pattern matches (default 'chat'). */
57
+ defaultProtocol?: 'chat';
58
+ /** Per-model wire-protocol routing; regex patterns, first match wins. */
59
+ modelRoutes?: ModelRoute[];
54
60
  }
55
61
 
56
62
  const BUILTIN_PROVIDERS: ProviderDef[] = [
@@ -143,8 +149,50 @@ const PROVIDER_ALIASES: Record<string, string> = {};
143
149
  let _customLoaded = false;
144
150
 
145
151
  /**
146
- * Load custom providers from `~/.pal/providers.json` and append them to
147
- * `PROVIDERS`. Safe to call multiple times — only loads once.
152
+ * Merge user-defined providers over the built-ins: a custom entry with an
153
+ * existing id REPLACES the built-in in place (user-wins), while new ids are
154
+ * appended. Returns the merged list plus the alias table the entries declare.
155
+ */
156
+ export function mergeProviders(
157
+ builtins: ProviderDef[],
158
+ customs: ProviderDef[],
159
+ ): {providers: ProviderDef[]; aliases: Record<string, string>} {
160
+ const providers = [...builtins];
161
+ const aliases: Record<string, string> = {};
162
+ for (const entry of customs) {
163
+ if (!entry || typeof entry.id !== 'string' || typeof entry.baseUrl !== 'string') continue;
164
+ const idx = providers.findIndex((p) => p.id === entry.id);
165
+ if (idx >= 0) providers[idx] = entry;
166
+ else providers.push(entry);
167
+ if (entry.alias) aliases[entry.alias] = entry.id;
168
+ }
169
+ return {providers, aliases};
170
+ }
171
+
172
+ /**
173
+ * Resolve the wire protocol + optional path for a bare model id. The first
174
+ * `modelRoutes` pattern that matches wins; otherwise the provider default.
175
+ */
176
+ export function resolveRoute(
177
+ def: {defaultProtocol?: 'chat'; modelRoutes?: ModelRoute[]},
178
+ model: string,
179
+ ): {protocol: 'chat' | 'responses'; path?: string} {
180
+ for (const route of def.modelRoutes ?? []) {
181
+ let matches = false;
182
+ try {
183
+ matches = new RegExp(route.pattern).test(model);
184
+ } catch {
185
+ matches = false;
186
+ }
187
+ if (matches) return {protocol: route.protocol, path: route.path};
188
+ }
189
+ return {protocol: def.defaultProtocol ?? 'chat', path: undefined};
190
+ }
191
+
192
+ /**
193
+ * Load custom providers from `~/.pal/providers.json` and merge them into
194
+ * `PROVIDERS`. Same-id entries replace built-ins; new ones append.
195
+ * Safe to call multiple times — only loads once.
148
196
  */
149
197
  export function loadCustomProviders(): void {
150
198
  if (_customLoaded) return;
@@ -157,14 +205,10 @@ export function loadCustomProviders(): void {
157
205
  const raw = readFileSync(customPath, 'utf-8');
158
206
  const data = JSON.parse(raw);
159
207
  if (Array.isArray(data)) {
160
- for (const entry of data) {
161
- if (entry && typeof entry.id === 'string' && typeof entry.baseUrl === 'string') {
162
- PROVIDERS.push(entry as ProviderDef);
163
- if (entry.alias) {
164
- PROVIDER_ALIASES[entry.alias] = entry.id;
165
- }
166
- }
167
- }
208
+ const {providers, aliases} = mergeProviders(PROVIDERS, data as ProviderDef[]);
209
+ PROVIDERS.length = 0;
210
+ PROVIDERS.push(...providers);
211
+ Object.assign(PROVIDER_ALIASES, aliases);
168
212
  }
169
213
  } catch {
170
214
  // No custom providers file or invalid JSON — that's fine.
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Responses protocol adapter — the OpenAI "Responses" wire format (flat tool
3
+ * defs, `input` item list, typed SSE events). Selected per model via
4
+ * `modelRoutes`; a provider with no such route never reaches this file.
5
+ */
6
+
7
+ import type {StreamEvent, Usage} from './types.js';
8
+ import {log} from '../logger.js';
9
+ import type {ToolDef} from './chat.js';
10
+
11
+ const DEFAULT_RESPONSES_PATH = '/responses';
12
+
13
+ export interface ResponsesStreamOptions {
14
+ id: string;
15
+ baseUrl: string;
16
+ /** Bare model id (prefix already stripped). */
17
+ model: string;
18
+ messages: Array<Record<string, unknown>>;
19
+ tools?: ToolDef[];
20
+ headers: Record<string, string>;
21
+ signal?: AbortSignal;
22
+ path?: string;
23
+ }
24
+
25
+ /**
26
+ * Map pal's chat-shaped messages onto the Responses `input` item list.
27
+ * Text-first and deliberately simple: text messages become `{role, content}`
28
+ * items, assistant tool calls become `function_call` items, and tool results
29
+ * become `function_call_output` items keyed by `call_id`.
30
+ */
31
+ export function toResponsesInput(
32
+ messages: Array<Record<string, unknown>>,
33
+ ): Array<Record<string, unknown>> {
34
+ const out: Array<Record<string, unknown>> = [];
35
+ for (const m of messages) {
36
+ if (m.role === 'tool') {
37
+ out.push({
38
+ type: 'function_call_output',
39
+ call_id: m.tool_call_id,
40
+ output: typeof m.content === 'string' ? m.content : '',
41
+ });
42
+ continue;
43
+ }
44
+ if (m.role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
45
+ if (typeof m.content === 'string' && m.content.length > 0) {
46
+ out.push({role: 'assistant', content: m.content});
47
+ }
48
+ for (const tc of m.tool_calls as Array<Record<string, unknown>>) {
49
+ const fn = (tc.function ?? {}) as Record<string, unknown>;
50
+ out.push({
51
+ type: 'function_call',
52
+ call_id: tc.id,
53
+ name: fn.name,
54
+ arguments: typeof fn.arguments === 'string' ? fn.arguments : '{}',
55
+ });
56
+ }
57
+ continue;
58
+ }
59
+ out.push({role: m.role, content: typeof m.content === 'string' ? m.content : ''});
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /** Translate chat-shaped tool defs to the flat Responses tool shape. */
65
+ export function toResponsesTools(tools?: ToolDef[]): Array<Record<string, unknown>> | undefined {
66
+ if (!tools || tools.length === 0) return undefined;
67
+ return tools.map((t) => ({
68
+ type: 'function',
69
+ name: t.function.name,
70
+ description: t.function.description,
71
+ parameters: t.function.parameters,
72
+ }));
73
+ }
74
+
75
+ /**
76
+ * Resolve the request URL. A route path is relative to baseUrl (same rule as
77
+ * the chat default `${baseUrl}/chat/completions`): leading slashes are
78
+ * stripped, never replace the base path. A full http(s) URL is used as-is.
79
+ */
80
+ function resolveUrl(baseUrl: string, path?: string): string {
81
+ const p = path ?? DEFAULT_RESPONSES_PATH;
82
+ if (/^https?:\/\//i.test(p)) return p;
83
+ return `${baseUrl.replace(/\/+$/, '')}/${p.replace(/^\/+/, '')}`;
84
+ }
85
+
86
+ export async function* streamResponses(opts: ResponsesStreamOptions): AsyncGenerator<StreamEvent> {
87
+ const body: Record<string, unknown> = {
88
+ model: opts.model,
89
+ input: toResponsesInput(opts.messages),
90
+ stream: true,
91
+ };
92
+
93
+ const tools = toResponsesTools(opts.tools);
94
+ if (tools) body.tools = tools;
95
+
96
+ const url = resolveUrl(opts.baseUrl, opts.path);
97
+
98
+ log('request', {
99
+ provider: opts.id,
100
+ baseUrl: opts.baseUrl,
101
+ url,
102
+ protocol: 'responses',
103
+ model: opts.model,
104
+ messageCount: opts.messages.length,
105
+ toolCount: opts.tools?.length ?? 0,
106
+ messages: opts.messages,
107
+ });
108
+
109
+ const res = await fetch(url, {
110
+ method: 'POST',
111
+ headers: opts.headers,
112
+ body: JSON.stringify(body),
113
+ signal: opts.signal,
114
+ });
115
+
116
+ if (!res.ok) {
117
+ const err = await res.text();
118
+ log('response-error', {status: res.status, body: err});
119
+ yield {type: 'error', content: `API ${res.status}: ${err}`};
120
+ return;
121
+ }
122
+
123
+ const reader = res.body?.getReader();
124
+ if (!reader) {
125
+ yield {type: 'error', content: 'No response body'};
126
+ return;
127
+ }
128
+
129
+ const decoder = new TextDecoder();
130
+ let buffer = '';
131
+ let lastUsage: Usage | undefined;
132
+ const calls = new Map<string, {id: string; name: string; arguments: string; seq: number}>();
133
+ let callSeq = 0;
134
+ const emitted = new Set<string>();
135
+
136
+ const emitCall = (key: string): StreamEvent | null => {
137
+ const c = calls.get(key);
138
+ if (!c || emitted.has(key) || !c.name) return null;
139
+ emitted.add(key);
140
+ return {
141
+ type: 'tool_use',
142
+ toolCall: {
143
+ id: c.id || `call_${Math.random().toString(36).slice(2, 10)}`,
144
+ name: c.name,
145
+ arguments: c.arguments || '{}',
146
+ },
147
+ };
148
+ };
149
+
150
+ while (true) {
151
+ const {done, value} = await reader.read();
152
+ if (done) break;
153
+
154
+ buffer += decoder.decode(value, {stream: true});
155
+ const lines = buffer.split('\n');
156
+ buffer = lines.pop() ?? '';
157
+
158
+ for (const line of lines) {
159
+ const trimmed = line.trim();
160
+ if (!trimmed.startsWith('data: ')) continue;
161
+ const data = trimmed.slice(6);
162
+ if (data === '[DONE]') continue;
163
+
164
+ let parsed: Record<string, unknown>;
165
+ try {
166
+ parsed = JSON.parse(data.replaceAll('\u0000', '')) as Record<string, unknown>;
167
+ } catch {
168
+ continue;
169
+ }
170
+
171
+ const type = parsed.type;
172
+
173
+ if (type === 'response.output_text.delta') {
174
+ if (typeof parsed.delta === 'string' && parsed.delta) {
175
+ yield {type: 'text', content: parsed.delta.replaceAll('\u0000', '')};
176
+ }
177
+ continue;
178
+ }
179
+
180
+ // Reasoning summaries stream as their own deltas. Display-only, like chat thinking.
181
+ if (type === 'response.reasoning_summary_text.delta') {
182
+ if (typeof parsed.delta === 'string' && parsed.delta) {
183
+ yield {type: 'thinking', content: parsed.delta.replaceAll('\u0000', '')};
184
+ }
185
+ continue;
186
+ }
187
+
188
+ if (type === 'response.output_item.added' || type === 'response.output_item.done') {
189
+ const item = parsed.item as Record<string, unknown> | undefined;
190
+ if (item?.type === 'function_call') {
191
+ const key = String(item.id ?? item.call_id ?? callSeq);
192
+ const entry = calls.get(key) ?? {id: '', name: '', arguments: '', seq: callSeq++};
193
+ if (typeof item.call_id === 'string') entry.id = item.call_id;
194
+ if (typeof item.name === 'string') entry.name = item.name;
195
+ if (typeof item.arguments === 'string' && item.arguments)
196
+ entry.arguments = item.arguments;
197
+ calls.set(key, entry);
198
+ if (type === 'response.output_item.done') {
199
+ const ev = emitCall(key);
200
+ if (ev) yield ev;
201
+ }
202
+ }
203
+ if (item?.type === 'reasoning' && type === 'response.output_item.done') {
204
+ const summary = item.summary;
205
+ if (Array.isArray(summary)) {
206
+ const text = summary
207
+ .map((part) => (typeof part === 'string' ? part : part?.text))
208
+ .filter((t): t is string => typeof t === 'string' && t.length > 0)
209
+ .join('');
210
+ if (text) yield {type: 'thinking', content: text.replaceAll('\u0000', '')};
211
+ }
212
+ }
213
+ continue;
214
+ }
215
+
216
+ if (type === 'response.function_call_arguments.delta') {
217
+ const key = String(parsed.item_id ?? parsed.output_index ?? '');
218
+ const c = calls.get(key);
219
+ if (c && typeof parsed.delta === 'string')
220
+ c.arguments += parsed.delta.replaceAll('\u0000', '');
221
+ continue;
222
+ }
223
+
224
+ if (type === 'response.function_call_arguments.done') {
225
+ const key = String(parsed.item_id ?? parsed.output_index ?? '');
226
+ const c = calls.get(key);
227
+ if (c && typeof parsed.arguments === 'string') c.arguments = parsed.arguments;
228
+ continue;
229
+ }
230
+
231
+ if (type === 'response.completed') {
232
+ const response = parsed.response as Record<string, unknown> | undefined;
233
+ const u = response?.usage as Record<string, unknown> | undefined;
234
+ if (u) {
235
+ const details = u.input_tokens_details as Record<string, unknown> | undefined;
236
+ lastUsage = {
237
+ promptTokens: typeof u.input_tokens === 'number' ? u.input_tokens : 0,
238
+ completionTokens: typeof u.output_tokens === 'number' ? u.output_tokens : 0,
239
+ totalTokens: typeof u.total_tokens === 'number' ? u.total_tokens : 0,
240
+ cachedTokens:
241
+ typeof details?.cached_tokens === 'number' ? details.cached_tokens : undefined,
242
+ };
243
+ log('usage', lastUsage);
244
+ }
245
+ for (const key of calls.keys()) {
246
+ const ev = emitCall(key);
247
+ if (ev) yield ev;
248
+ }
249
+ continue;
250
+ }
251
+
252
+ if (type === 'response.failed' || type === 'error') {
253
+ const response = parsed.response as Record<string, unknown> | undefined;
254
+ const respErr = response?.error as Record<string, unknown> | undefined;
255
+ const errObj = parsed.error as Record<string, unknown> | undefined;
256
+ const msg =
257
+ (typeof respErr?.message === 'string' && respErr.message) ||
258
+ (typeof errObj?.message === 'string' && errObj.message) ||
259
+ (typeof parsed.message === 'string' && parsed.message) ||
260
+ 'responses stream error';
261
+ yield {type: 'error', content: msg};
262
+ }
263
+ }
264
+ }
265
+
266
+ for (const key of calls.keys()) {
267
+ const ev = emitCall(key);
268
+ if (ev) yield ev;
269
+ }
270
+ yield {type: 'done', usage: lastUsage};
271
+ }
@@ -5,6 +5,17 @@
5
5
  * The CLI/engine talks to Provider, not directly to HTTP.
6
6
  */
7
7
 
8
+ /**
9
+ * A per-model wire-protocol route. `pattern` is a regex tested against the
10
+ * bare model id; the first matching route wins (declaration order).
11
+ */
12
+ export interface ModelRoute {
13
+ pattern: string;
14
+ protocol: 'chat' | 'responses';
15
+ /** Endpoint path for this protocol. Leading '/' resolves against the baseUrl origin. */
16
+ path?: string;
17
+ }
18
+
8
19
  export interface ProviderConfig {
9
20
  id: string;
10
21
  baseUrl: string;
@@ -12,6 +23,10 @@ export interface ProviderConfig {
12
23
  headers?: Record<string, string>;
13
24
  /** Prefix to strip from model names before sending to the API (e.g. "opencode/"). */
14
25
  modelPrefix?: string;
26
+ /** Protocol used when no `modelRoutes` pattern matches (default 'chat'). */
27
+ defaultProtocol?: 'chat';
28
+ /** Per-model protocol routing (regex, first match wins). */
29
+ modelRoutes?: ModelRoute[];
15
30
  }
16
31
 
17
32
  export interface ProviderModel {
@@ -32,7 +47,10 @@ export interface Usage {
32
47
  }
33
48
 
34
49
  export interface StreamEvent {
35
- type: 'text' | 'tool_use' | 'done' | 'error';
50
+ // `thinking` is display-only reasoning content (DeepSeek `reasoning_content`,
51
+ // gateway `reasoning`, Responses reasoning summaries). Consumers must never
52
+ // merge it into text or history — it is excluded from context by construction.
53
+ type: 'text' | 'thinking' | 'tool_use' | 'done' | 'error';
36
54
  content?: string;
37
55
  toolCall?: {id: string; name: string; arguments: string; extraContent?: Record<string, unknown>};
38
56
  usage?: Usage;
@@ -25,7 +25,7 @@ const EMPTY_TOKENOMICS: SessionTokenomics = {
25
25
  * v2 repairs `sessions.messages_backup`, which `RENAME COLUMN` left `NOT NULL`
26
26
  * and so rejected every future INSERT — see `relaxMessagesBackup`.
27
27
  */
28
- const SCHEMA_VERSION = 2;
28
+ const SCHEMA_VERSION = 3;
29
29
 
30
30
  /** Row shape of the `sessions` table. */
31
31
  interface SessionRow {
@@ -52,6 +52,8 @@ interface MessageRow {
52
52
  tool_name: string | null;
53
53
  tool_status: string | null;
54
54
  agent_role: string | null;
55
+ thinking: string | null;
56
+ thinking_ms: number | null;
55
57
  created_at: number;
56
58
  }
57
59
 
@@ -131,6 +133,8 @@ export class SessionStore {
131
133
  tool_name TEXT,
132
134
  tool_status TEXT,
133
135
  agent_role TEXT,
136
+ thinking TEXT,
137
+ thinking_ms INTEGER,
134
138
  created_at INTEGER NOT NULL,
135
139
  UNIQUE(session_id, seq)
136
140
  );
@@ -210,6 +214,17 @@ export class SessionStore {
210
214
  // v1 → v2: relax the constraint the rename above carried over.
211
215
  if (version < 2) this.relaxMessagesBackup();
212
216
 
217
+ // v2 → v3: persist model thinking for resume repaint.
218
+ if (version < 3) {
219
+ const msgCols = this.db
220
+ .query<{name: string}, []>('PRAGMA table_info(messages)')
221
+ .all()
222
+ .map((col) => col.name);
223
+ if (!msgCols.includes('thinking')) this.db.exec('ALTER TABLE messages ADD COLUMN thinking TEXT');
224
+ if (!msgCols.includes('thinking_ms'))
225
+ this.db.exec('ALTER TABLE messages ADD COLUMN thinking_ms INTEGER');
226
+ }
227
+
213
228
  this.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
214
229
  });
215
230
 
@@ -468,7 +483,7 @@ export class SessionStore {
468
483
  const toolCallId = m.role === 'tool' ? m.tool_call_id : null;
469
484
 
470
485
  this.db.run(
471
- 'INSERT INTO messages (id, session_id, seq, role, content, tool_calls, tool_call_id, tool_name, tool_status, agent_role, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
486
+ 'INSERT INTO messages (id, session_id, seq, role, content, tool_calls, tool_call_id, tool_name, tool_status, agent_role, thinking, thinking_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
472
487
  [
473
488
  randomUUID(),
474
489
  sessionId,
@@ -480,6 +495,8 @@ export class SessionStore {
480
495
  meta_i?.toolName ?? null,
481
496
  meta_i?.toolStatus ?? null,
482
497
  meta_i?.agentRole ?? null,
498
+ meta_i?.thinking ?? null,
499
+ meta_i?.thinkingMs ?? null,
483
500
  createdAt,
484
501
  ],
485
502
  );
@@ -509,6 +526,8 @@ export class SessionStore {
509
526
  toolName: r.tool_name ?? undefined,
510
527
  toolStatus: (r.tool_status as MessageMeta['toolStatus']) ?? undefined,
511
528
  agentRole: r.agent_role ?? undefined,
529
+ thinking: r.thinking ?? undefined,
530
+ thinkingMs: r.thinking_ms ?? undefined,
512
531
  },
513
532
  createdAt: r.created_at,
514
533
  }));
@@ -644,9 +663,16 @@ function rowToMessage(row: StoredMessage): Message {
644
663
  return {role: 'tool', tool_call_id: row.toolCallId ?? '', content: row.content};
645
664
  }
646
665
  if (row.role === 'assistant') {
666
+ // Reattach thinking so a resumed session keeps it in memory: the next
667
+ // save re-derives meta from these messages, and without this the thought
668
+ // would evaporate one turn after resume.
669
+ const thinking =
670
+ row.meta.thinking !== undefined
671
+ ? {thinking: row.meta.thinking, thinkingMs: row.meta.thinkingMs}
672
+ : {};
647
673
  return row.toolCalls?.length
648
- ? {role: 'assistant', content: row.content, toolCalls: row.toolCalls}
649
- : {role: 'assistant', content: row.content};
674
+ ? {role: 'assistant', content: row.content, toolCalls: row.toolCalls, ...thinking}
675
+ : {role: 'assistant', content: row.content, ...thinking};
650
676
  }
651
677
  return {role: 'user', content: row.content};
652
678
  }
@@ -663,8 +689,11 @@ function rowToMessage(row: StoredMessage): Message {
663
689
  export function deriveMessageMeta(messages: readonly Message[]): MessageMeta[] {
664
690
  const nameByCallId = new Map<string, string>();
665
691
  return messages.map((m) => {
666
- if (m.role === 'assistant' && m.toolCalls?.length) {
667
- for (const tc of m.toolCalls) nameByCallId.set(tc.id, tc.name);
692
+ if (m.role === 'assistant') {
693
+ if (m.toolCalls?.length) {
694
+ for (const tc of m.toolCalls) nameByCallId.set(tc.id, tc.name);
695
+ }
696
+ if (m.thinking) return {thinking: m.thinking, thinkingMs: m.thinkingMs};
668
697
  return {};
669
698
  }
670
699
  if (m.role === 'tool') {
@@ -14,6 +14,10 @@ export interface MessageMeta {
14
14
  toolStatus?: 'ok' | 'error';
15
15
  /** Which agent produced the message, for message-box coloring. */
16
16
  agentRole?: string;
17
+ /** Model thinking text, for repainting dim thought blocks on session resume. */
18
+ thinking?: string;
19
+ /** Thinking-phase elapsed ms, for the `Thought · Xs` resume label. */
20
+ thinkingMs?: number;
17
21
  }
18
22
 
19
23
  /** A persisted message row (normalized storage). */
@@ -69,10 +69,13 @@ async function execCommand(
69
69
  command: string,
70
70
  timeoutMs: number,
71
71
  cwdOverride?: string,
72
+ signal?: AbortSignal,
72
73
  ): Promise<{stdout: string; stderr: string; exitCode: number}> {
73
74
  const isWin = process.platform === 'win32';
74
75
  const workdir = cwdOverride ?? shellCwd;
75
76
 
77
+ if (signal?.aborted) throw new Error('Command cancelled (aborted by user).');
78
+
76
79
  const proc = Bun.spawn(isWin ? ['cmd', '/d', '/c', command] : ['bash', '-c', command], {
77
80
  stdout: 'pipe',
78
81
  stderr: 'pipe',
@@ -90,17 +93,44 @@ async function execCommand(
90
93
  }
91
94
  }, timeoutMs);
92
95
 
93
- const [stdout, stderr] = await Promise.all([
96
+ let aborted = false;
97
+ let settleAbort: (() => void) | null = null;
98
+ const onAbort = (): void => {
99
+ aborted = true;
100
+ try {
101
+ // SIGTERM gives the child a chance to flush and exit on its own; Windows
102
+ // has no graceful process kill, so it degrades to TerminateProcess there.
103
+ proc.kill(isWin ? undefined : 'SIGTERM');
104
+ } catch {
105
+ // already dead
106
+ }
107
+ settleAbort?.();
108
+ };
109
+ signal?.addEventListener('abort', onAbort, {once: true});
110
+
111
+ const readPipes = Promise.all([
94
112
  new Response(proc.stdout as ReadableStream<Uint8Array>).text(),
95
113
  new Response(proc.stderr as ReadableStream<Uint8Array>).text(),
96
114
  ]);
97
- const exitCode = await proc.exited;
115
+ // Resolves only once an abort lands, so the pipe read can lose the race.
116
+ const abortRace = new Promise<null>((resolve) => {
117
+ if (aborted) resolve(null);
118
+ else settleAbort = () => resolve(null);
119
+ });
120
+
121
+ const pipes = await Promise.race([readPipes, abortRace]);
122
+ const exitCode = aborted ? 143 : await proc.exited;
123
+
98
124
  clearTimeout(timer);
125
+ signal?.removeEventListener('abort', onAbort);
99
126
 
127
+ if (aborted) throw new Error('Command cancelled (aborted by user).');
100
128
  if (timedOut) {
101
129
  throw new Error(`Command timed out after ${timeoutMs}ms`);
102
130
  }
103
131
 
132
+ const [stdout, stderr] = pipes ?? ['', ''];
133
+
104
134
  // Track cwd changes for subsequent calls (only if cd succeeded, no override)
105
135
  const cdMatch = command.match(/^\s*cd\s+(?:\/d\s+)?["']?([^"'\s;&]+)["']?\s*(?:;|&&|$)/);
106
136
  if (cdMatch && exitCode === 0 && !cwdOverride) {
@@ -419,7 +449,7 @@ const tools: Record<
419
449
  return errors.length ? `${result}\n${errors.join('\n')}` : result;
420
450
  },
421
451
 
422
- async bash(args, _config) {
452
+ async bash(args, config) {
423
453
  // This tool already runs every command inside a shell (cmd.exe on Windows,
424
454
  // bash elsewhere). Models frequently add their own wrapper, which breaks on
425
455
  // nested quoting — e.g. `cmd /c "dir /a"` becomes `cmd /d /c cmd /c "dir /a"`
@@ -440,7 +470,7 @@ const tools: Record<
440
470
  }
441
471
 
442
472
  try {
443
- const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS);
473
+ const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS, undefined, config.signal);
444
474
 
445
475
  let output = '';
446
476
  if (stdout) output += stdout;
@@ -455,7 +485,7 @@ const tools: Record<
455
485
  }
456
486
  },
457
487
 
458
- async verify(args, _config) {
488
+ async verify(args, config) {
459
489
  const projectPath = args.path ? resolve(String(args.path)) : shellCwd;
460
490
  const requested = Array.isArray(args.checks) ? args.checks.map(String) : [];
461
491
 
@@ -516,6 +546,7 @@ const tools: Record<
516
546
  'bunx tsc --noEmit 2>&1',
517
547
  120_000,
518
548
  checkRoot,
549
+ config.signal,
519
550
  );
520
551
  const out = (stdout + stderr).trim();
521
552
  if (exitCode === 0) {
@@ -528,7 +559,7 @@ const tools: Record<
528
559
  }
529
560
 
530
561
  if (runTest) {
531
- const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot);
562
+ const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot, config.signal);
532
563
  const out = (stdout + stderr).trim();
533
564
  if (exitCode === 0) {
534
565
  lines.push('✓ test: passed');