@pal-code/core 0.0.15 → 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.
@@ -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). */
@@ -66,7 +66,7 @@ export function getExtensionTools(): ToolDef[] {
66
66
  * Fail-open by design: an unknown tool is the executor's unknown-tool branch
67
67
  * (no schema here to check against), and a schema without `required` has
68
68
  * nothing to check. A key present with any value — including `null` — counts
69
- * as provided; this only catches *absent* keys, e.g. `edit_file` dispatched
69
+ * as provided; this only catches *absent* keys, e.g. `edit` dispatched
70
70
  * without `path` (the `ENOENT ... open 'undefined'` failure mode).
71
71
  */
72
72
  export function validateRequiredArgs(name: string, args: Record<string, unknown>): string | null {
@@ -201,7 +201,7 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
201
201
  type: 'array',
202
202
  items: {type: 'string'},
203
203
  description:
204
- 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
204
+ 'Tool names the child may use. Default: read-only tools (read, ls, grep_search, ast_grep, glob).',
205
205
  },
206
206
  max_rounds: {
207
207
  type: 'number',
@@ -244,11 +244,20 @@ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
244
244
  };
245
245
  }
246
246
 
247
+ // Old Zen-era tool names → current names; applied to user-supplied tool lists.
248
+ export const TOOL_NAME_ALIASES: Record<string, string> = {
249
+ read_file: 'read',
250
+ write_file: 'write',
251
+ edit_file: 'edit',
252
+ glob_search: 'glob',
253
+ list_directory: 'ls',
254
+ };
255
+
247
256
  export const CORE_TOOLS: ToolDef[] = [
248
257
  {
249
258
  type: 'function',
250
259
  function: {
251
- name: 'read_file',
260
+ name: 'read',
252
261
  description: 'Read file with line numbers.',
253
262
  parameters: {
254
263
  type: 'object',
@@ -264,7 +273,7 @@ export const CORE_TOOLS: ToolDef[] = [
264
273
  {
265
274
  type: 'function',
266
275
  function: {
267
- name: 'write_file',
276
+ name: 'write',
268
277
  description: 'Create or overwrite file.',
269
278
  parameters: {
270
279
  type: 'object',
@@ -279,7 +288,7 @@ export const CORE_TOOLS: ToolDef[] = [
279
288
  {
280
289
  type: 'function',
281
290
  function: {
282
- name: 'edit_file',
291
+ name: 'edit',
283
292
  description:
284
293
  'Replace exact string in file; structural pattern+rewrite fallback when exact text unknown.',
285
294
  parameters: {
@@ -339,7 +348,7 @@ export const CORE_TOOLS: ToolDef[] = [
339
348
  {
340
349
  type: 'function',
341
350
  function: {
342
- name: 'list_directory',
351
+ name: 'ls',
343
352
  description: 'List directory contents.',
344
353
  parameters: {
345
354
  type: 'object',
@@ -387,7 +396,7 @@ export const CORE_TOOLS: ToolDef[] = [
387
396
  {
388
397
  type: 'function',
389
398
  function: {
390
- name: 'glob_search',
399
+ name: 'glob',
391
400
  description: 'Find files by glob pattern.',
392
401
  parameters: {
393
402
  type: 'object',