@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 +1 -1
- package/src/agent/fallback.ts +47 -19
- package/src/agent/run.ts +40 -7
- package/src/agent/turn.ts +380 -0
- package/src/app-config.ts +148 -0
- package/src/extensions.ts +73 -14
- package/src/index.ts +38 -2
- package/src/lifecycle.ts +16 -0
- package/src/provider/auth.ts +1 -0
- package/src/provider/chat.ts +250 -0
- package/src/provider/index.ts +2 -1
- package/src/provider/openrouter.ts +55 -222
- package/src/provider/registry.ts +80 -10
- package/src/provider/responses.ts +271 -0
- package/src/provider/types.ts +19 -1
- package/src/registry.ts +9 -0
- package/src/runtime/state.ts +81 -0
- package/src/session/store.ts +35 -6
- package/src/session/types.ts +4 -0
- package/src/tools/executor.ts +43 -7
|
@@ -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
|
+
}
|
package/src/provider/types.ts
CHANGED
|
@@ -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
|
-
|
|
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;
|
package/src/registry.ts
CHANGED
|
@@ -46,6 +46,14 @@ export interface CoreRegistry {
|
|
|
46
46
|
extensionHandlers: Record<string, ToolHandlerFn>;
|
|
47
47
|
/** Lifecycle hooks declared by loaded extensions (roadmap #6). */
|
|
48
48
|
lifecycleHooks: LifecycleHandlers[];
|
|
49
|
+
/**
|
|
50
|
+
* System-prompt fragments from loaded, available extensions.
|
|
51
|
+
*
|
|
52
|
+
* Lives here rather than in a module-level variable for the reason in the
|
|
53
|
+
* file header: `composeSystemPrompt()` runs in pal's copy of core, while the
|
|
54
|
+
* extension that contributed the fragment resolved its own copy.
|
|
55
|
+
*/
|
|
56
|
+
extensionPrompts: string[];
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
const KEY = '__pal_core_registry__';
|
|
@@ -61,4 +69,5 @@ export const registry: CoreRegistry = (store[KEY] ??= {
|
|
|
61
69
|
extensionTools: [],
|
|
62
70
|
extensionHandlers: {},
|
|
63
71
|
lifecycleHooks: [],
|
|
72
|
+
extensionPrompts: [],
|
|
64
73
|
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared, frontend-agnostic app state.
|
|
3
|
+
*
|
|
4
|
+
* The TUI and the WebSocket/desktop frontends each own an instance of this
|
|
5
|
+
* shape. Contract types live here so no frontend has to import another's state
|
|
6
|
+
* module or re-declare the same interfaces.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type {SessionTokenomics} from '../session/types.js';
|
|
10
|
+
|
|
11
|
+
export interface BackgroundAgent {
|
|
12
|
+
id: string;
|
|
13
|
+
task: string;
|
|
14
|
+
status: 'running' | 'done' | 'error';
|
|
15
|
+
startedAt: number;
|
|
16
|
+
finishedAt?: number;
|
|
17
|
+
result?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface TodoItem {
|
|
21
|
+
content: string;
|
|
22
|
+
status: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ExtensionStatus {
|
|
26
|
+
/** Extension package name without the scope (e.g. 'web-search'). */
|
|
27
|
+
name: string;
|
|
28
|
+
/** True when the extension loaded and contributed something. */
|
|
29
|
+
active: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Why the extension is not active, if it is not.
|
|
32
|
+
*
|
|
33
|
+
* - `'inactive'` — loaded fine but reported itself unavailable (no key, no
|
|
34
|
+
* server). Not an error; nothing for the user to fix except configuration.
|
|
35
|
+
* - `'failed'` — the package could not be imported, or its setup threw.
|
|
36
|
+
*
|
|
37
|
+
* Only meaningful when `active` is false.
|
|
38
|
+
*/
|
|
39
|
+
status: 'active' | 'inactive' | 'failed';
|
|
40
|
+
/** Human-readable detail for `status`, when there is one. */
|
|
41
|
+
reason?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface McpServerStatus {
|
|
45
|
+
name: string;
|
|
46
|
+
status: 'connected' | 'error' | 'starting';
|
|
47
|
+
toolCount: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface SharedState {
|
|
51
|
+
/** Title of the current session, shown by the frontend. */
|
|
52
|
+
sessionTitle: string | null;
|
|
53
|
+
/** Latest todo list from the `todos-updated` event. */
|
|
54
|
+
currentTodos: readonly TodoItem[];
|
|
55
|
+
/** Sub-agents spawned by `delegate`. */
|
|
56
|
+
backgroundAgents: BackgroundAgent[];
|
|
57
|
+
/** Loaded extensions and their status. */
|
|
58
|
+
extensions: ExtensionStatus[];
|
|
59
|
+
/** MCP servers discovered during startup. */
|
|
60
|
+
mcpServers: McpServerStatus[];
|
|
61
|
+
/** Currently selected primary agent. */
|
|
62
|
+
currentAgentRole: string;
|
|
63
|
+
/** Session-scoped "always allow" permission entries. Cleared on /new. */
|
|
64
|
+
permissionWhitelist: Array<{tool: string; pattern: string}>;
|
|
65
|
+
/** Accumulated token usage and cost for the current session. */
|
|
66
|
+
sessionTokenomics: SessionTokenomics;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Fresh state with independent arrays/objects — safe for a new frontend. */
|
|
70
|
+
export function createSharedState(): SharedState {
|
|
71
|
+
return {
|
|
72
|
+
sessionTitle: null,
|
|
73
|
+
currentTodos: [],
|
|
74
|
+
backgroundAgents: [],
|
|
75
|
+
extensions: [],
|
|
76
|
+
mcpServers: [],
|
|
77
|
+
currentAgentRole: 'pal',
|
|
78
|
+
permissionWhitelist: [],
|
|
79
|
+
sessionTokenomics: {inputTokens: 0, outputTokens: 0, cachedTokens: 0, cost: 0},
|
|
80
|
+
};
|
|
81
|
+
}
|
package/src/session/store.ts
CHANGED
|
@@ -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 =
|
|
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'
|
|
667
|
-
|
|
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') {
|
package/src/session/types.ts
CHANGED
|
@@ -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). */
|
package/src/tools/executor.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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) {
|
|
@@ -316,7 +346,12 @@ const tools: Record<
|
|
|
316
346
|
throw new Error(`Cannot write to ${filePath} — matches ignore patterns`);
|
|
317
347
|
}
|
|
318
348
|
|
|
319
|
-
|
|
349
|
+
// A bare relative path (`pal.json`, `.check.cjs`) has dirname `'.'`, and Bun
|
|
350
|
+
// throws `EEXIST` on `mkdir('.')` — the directory obviously already exists.
|
|
351
|
+
// Left unguarded this turns every such write into a failed tool call the
|
|
352
|
+
// model then retries, which reads as a stuck agent rather than a bad path.
|
|
353
|
+
const dir = dirname(filePath);
|
|
354
|
+
if (dir !== '' && dir !== '.') await mkdir(dir, {recursive: true});
|
|
320
355
|
snapshotFile(filePath, 'write');
|
|
321
356
|
await writeFile(filePath, content, 'utf-8');
|
|
322
357
|
return `Wrote ${content.length} bytes to ${filePath}`;
|
|
@@ -419,7 +454,7 @@ const tools: Record<
|
|
|
419
454
|
return errors.length ? `${result}\n${errors.join('\n')}` : result;
|
|
420
455
|
},
|
|
421
456
|
|
|
422
|
-
async bash(args,
|
|
457
|
+
async bash(args, config) {
|
|
423
458
|
// This tool already runs every command inside a shell (cmd.exe on Windows,
|
|
424
459
|
// bash elsewhere). Models frequently add their own wrapper, which breaks on
|
|
425
460
|
// nested quoting — e.g. `cmd /c "dir /a"` becomes `cmd /d /c cmd /c "dir /a"`
|
|
@@ -440,7 +475,7 @@ const tools: Record<
|
|
|
440
475
|
}
|
|
441
476
|
|
|
442
477
|
try {
|
|
443
|
-
const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS);
|
|
478
|
+
const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS, undefined, config.signal);
|
|
444
479
|
|
|
445
480
|
let output = '';
|
|
446
481
|
if (stdout) output += stdout;
|
|
@@ -455,7 +490,7 @@ const tools: Record<
|
|
|
455
490
|
}
|
|
456
491
|
},
|
|
457
492
|
|
|
458
|
-
async verify(args,
|
|
493
|
+
async verify(args, config) {
|
|
459
494
|
const projectPath = args.path ? resolve(String(args.path)) : shellCwd;
|
|
460
495
|
const requested = Array.isArray(args.checks) ? args.checks.map(String) : [];
|
|
461
496
|
|
|
@@ -516,6 +551,7 @@ const tools: Record<
|
|
|
516
551
|
'bunx tsc --noEmit 2>&1',
|
|
517
552
|
120_000,
|
|
518
553
|
checkRoot,
|
|
554
|
+
config.signal,
|
|
519
555
|
);
|
|
520
556
|
const out = (stdout + stderr).trim();
|
|
521
557
|
if (exitCode === 0) {
|
|
@@ -528,7 +564,7 @@ const tools: Record<
|
|
|
528
564
|
}
|
|
529
565
|
|
|
530
566
|
if (runTest) {
|
|
531
|
-
const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot);
|
|
567
|
+
const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot, config.signal);
|
|
532
568
|
const out = (stdout + stderr).trim();
|
|
533
569
|
if (exitCode === 0) {
|
|
534
570
|
lines.push('✓ test: passed');
|