@celljs/ta-agents 4.8.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -422,6 +422,10 @@ class AgentSession {
422
422
  case "tool_call":
423
423
  case "tool_call_update":
424
424
  case "plan":
425
+ if (!this.turn && this.abandoned && !this.abandoned.ended) {
426
+ this.abandoned.update(update);
427
+ return;
428
+ }
425
429
  if (!this.turn) {
426
430
  this.startUnsolicited(true);
427
431
  }
@@ -1429,7 +1433,13 @@ class AgentStreamer {
1429
1433
  stream(config, model, context, options) {
1430
1434
  const stream = new MessageStream;
1431
1435
  const builder = new MessageBuilder(stream, model);
1432
- this.run(config, model, context, options, builder).catch((error) => builder.error("error", AgentStreamer.describe(config, error)));
1436
+ this.run(config, model, context, options, builder).catch((error) => {
1437
+ if (options?.signal?.aborted) {
1438
+ builder.error("aborted", "Aborted");
1439
+ } else {
1440
+ builder.error("error", AgentStreamer.describe(config, error));
1441
+ }
1442
+ });
1433
1443
  return stream;
1434
1444
  }
1435
1445
  async run(config, model, context, options, builder) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-agents",
3
- "version": "4.8.0",
3
+ "version": "4.9.0",
4
4
  "description": "A pi package for Ta: other coding agents (CodeBuddy Code, Claude Code, Codex and any agent that speaks ACP) as models to pick, each running a conversation on its own harness",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -17,8 +17,7 @@
17
17
  "files": [
18
18
  "esm",
19
19
  "extension",
20
- "fixtures",
21
- "src"
20
+ "!**/*.map"
22
21
  ],
23
22
  "scripts": {
24
23
  "build": "tsc -b && bun build src/extension.ts --format esm --target node --outfile extension/index.mjs",
@@ -34,6 +33,15 @@
34
33
  "access": "public"
35
34
  },
36
35
  "pi": {
36
+ "title": {
37
+ "en": "Other coding agents",
38
+ "zh-CN": "其他编程 Agent"
39
+ },
40
+ "summary": {
41
+ "en": "Pick Claude Code, Codex, CodeBuddy Code or another ACP agent as the model of a conversation.",
42
+ "zh-CN": "把 Claude Code、Codex、CodeBuddy Code 等 Agent 当作模型,在对话里选用。"
43
+ },
44
+ "icon": "SquareTerminal",
37
45
  "extensions": [
38
46
  "./extension/index.mjs"
39
47
  ]
@@ -1,183 +0,0 @@
1
- // An ACP agent for the tests of @celljs/ta-agents: what it does depends on the words of the prompt.
2
- // Sessions are kept in FAKE_ACP_STATE (a directory), so that another process can load them.
3
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
- import { join } from 'node:path';
5
-
6
- const state = process.env.FAKE_ACP_STATE;
7
- if (state) {
8
- mkdirSync(state, { recursive: true });
9
- }
10
- const sessions = new Map();
11
- const cancelled = new Set();
12
- let nextId = 0;
13
- const waiting = new Map();
14
-
15
- const send = message => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n');
16
- const update = (sessionId, value) => send({ method: 'session/update', params: { sessionId, update: value } });
17
- const ask = (method, params) =>
18
- new Promise(resolve => {
19
- const id = 'c' + ++nextId;
20
- waiting.set(id, resolve);
21
- send({ id, method, params });
22
- });
23
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
24
- const save = session => state && writeFileSync(join(state, session.id + '.json'), JSON.stringify(session));
25
- const options = session => [
26
- { type: 'select', id: 'model', name: 'Model', category: 'model', currentValue: session.model, options: [{ value: 'fast', name: 'Fast' }, { value: 'smart', name: 'Smart' }] },
27
- { type: 'select', id: 'effort', name: 'Effort', category: 'thought_level', currentValue: session.effort, options: [{ value: 'low', name: 'Low' }, { value: 'high', name: 'High' }, { value: 'max', name: 'Max' }] },
28
- ];
29
-
30
- async function prompt(session, blocks) {
31
- const text = blocks.map(block => (block.type === 'text' ? block.text : '[' + block.type + ']')).join(' ');
32
- session.prompts.push(text);
33
- save(session);
34
- const say = value => update(session.id, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: value } });
35
- if (text.startsWith('/silent')) {
36
- return 'end_turn';
37
- }
38
- if (text.includes('auth')) {
39
- throw Object.assign(new Error('Authentication required'), { code: -32000 });
40
- }
41
- if (text.includes('tools')) {
42
- update(session.id, { sessionUpdate: 'tool_call', toolCallId: 't1', title: 'Bash', kind: 'other', status: 'in_progress', rawInput: {}, _meta: { 'fake/toolName': 'Bash' } });
43
- update(session.id, { sessionUpdate: 'tool_call_update', toolCallId: 't1', rawInput: { command: 'ec' } });
44
- update(session.id, { sessionUpdate: 'tool_call', toolCallId: 't1', title: '`echo hi`', kind: 'execute', status: 'pending', rawInput: { command: 'echo hi' } });
45
- update(session.id, { sessionUpdate: 'tool_call', toolCallId: 't2', title: 'Read a.txt', kind: 'read', status: 'pending', locations: [{ path: '/w/a.txt' }] });
46
- await sleep(400);
47
- update(session.id, { sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed', rawOutput: { type: 'text', text: 'hi' } });
48
- update(session.id, { sessionUpdate: 'tool_call_update', toolCallId: 't2', status: 'failed', content: [{ type: 'content', content: { type: 'text', text: 'no such file' } }] });
49
- await sleep(20);
50
- update(session.id, { sessionUpdate: 'usage_update', used: 1200, size: 100000, _meta: { usage: { prompt_tokens: 1000, completion_tokens: 20, cached_tokens: 400 } } });
51
- say('done');
52
- return 'end_turn';
53
- }
54
- if (text.includes('edits')) {
55
- // As CodeBuddy Code: it names the file it edits, then writes it with its own tool. As Claude Code: a diff.
56
- const file = join(session.cwd, 'notes.txt');
57
- update(session.id, { sessionUpdate: 'tool_call', toolCallId: 'e1', title: 'Edit', kind: 'edit', status: 'pending', rawInput: null });
58
- update(session.id, { sessionUpdate: 'tool_call_update', toolCallId: 'e1', status: 'pending', rawInput: { file_path: file } });
59
- await sleep(50);
60
- writeFileSync(file, readFileSync(file, 'utf8').replace('two', 'TWO'));
61
- update(session.id, { sessionUpdate: 'tool_call_update', toolCallId: 'e1', status: 'completed', content: [{ type: 'content', content: { type: 'text', text: 'Edited' } }] });
62
- const created = join(session.cwd, 'made.txt');
63
- writeFileSync(created, 'made\n');
64
- update(session.id, { sessionUpdate: 'tool_call', toolCallId: 'e2', title: 'Write made.txt', kind: 'edit', status: 'completed', content: [{ type: 'diff', path: created, oldText: null, newText: 'made\n' }] });
65
- say('edited');
66
- return 'end_turn';
67
- }
68
- if (text.includes('slow')) {
69
- say('working');
70
- for (let i = 0; i < 100 && !cancelled.has(session.id); i++) {
71
- await sleep(20);
72
- }
73
- cancelled.delete(session.id);
74
- return 'cancelled';
75
- }
76
- if (text.includes('permission')) {
77
- const answer = await ask('session/request_permission', {
78
- sessionId: session.id,
79
- toolCall: { toolCallId: 'p1', title: 'Write b.txt' },
80
- options: [
81
- { optionId: 'yes', name: 'Allow', kind: 'allow_once' },
82
- { optionId: 'no', name: 'Deny', kind: 'reject_once' },
83
- ],
84
- });
85
- say('permission: ' + (answer.outcome.optionId ?? answer.outcome.outcome));
86
- return 'end_turn';
87
- }
88
- if (text.includes('background')) {
89
- say('started');
90
- setTimeout(() => {
91
- update(session.id, { sessionUpdate: 'session_info_update', _meta: { 'fake/unsolicitedTurn': { requestId: 'r1', reason: 'background_drain' } } });
92
- say('background finished');
93
- update(session.id, { sessionUpdate: 'session_end' });
94
- }, 150);
95
- return 'end_turn';
96
- }
97
- if (text.includes('phases')) {
98
- // As CodeBuddy Code: idle once done, and the answer after it named the session.
99
- const request = 'r' + session.prompts.length;
100
- const phase = value => update(session.id, { sessionUpdate: 'session_info_update', _meta: { 'fake/agentPhase': { phase: value }, 'fake/requestId': request } });
101
- phase('idle');
102
- phase('model_streaming');
103
- say('quick');
104
- phase('idle');
105
- // Still working on this request after it said idle (as a compaction does), then answering late.
106
- setTimeout(() => {
107
- phase('model_streaming');
108
- phase('idle');
109
- }, 300);
110
- await sleep(1500);
111
- update(session.id, { sessionUpdate: 'session_info_update', title: 'Named late' });
112
- return 'end_turn';
113
- }
114
- if (text.includes('where')) {
115
- say('cwd ' + process.cwd() + ' session ' + session.cwd);
116
- return 'end_turn';
117
- }
118
- say('model ' + session.model + ' effort ' + session.effort + ' prompts ' + session.prompts.length + ': ' + text);
119
- update(session.id, { sessionUpdate: 'session_info_update', title: 'Fake title' });
120
- return 'end_turn';
121
- }
122
-
123
- async function handle(method, params) {
124
- switch (method) {
125
- case 'initialize':
126
- return { protocolVersion: 1, agentCapabilities: { loadSession: true, promptCapabilities: { image: true } }, authMethods: [] };
127
- case 'session/new': {
128
- const session = { id: 's' + Date.now() + Math.random().toString(16).slice(2, 6), cwd: params.cwd, model: 'fast', effort: 'low', prompts: [] };
129
- sessions.set(session.id, session);
130
- save(session);
131
- return { sessionId: session.id, configOptions: options(session) };
132
- }
133
- case 'session/load': {
134
- const file = state && join(state, params.sessionId + '.json');
135
- if (!file || !existsSync(file)) {
136
- throw Object.assign(new Error('Session not found'), { code: -32602 });
137
- }
138
- const session = JSON.parse(readFileSync(file, 'utf8'));
139
- sessions.set(session.id, session);
140
- for (const text of session.prompts) {
141
- update(session.id, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text } });
142
- update(session.id, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'replayed' } });
143
- }
144
- return { configOptions: options(session) };
145
- }
146
- case 'session/set_config_option': {
147
- const session = sessions.get(params.sessionId);
148
- session[params.configId] = params.value;
149
- save(session);
150
- return { configOptions: options(session) };
151
- }
152
- case 'session/prompt':
153
- return { stopReason: await prompt(sessions.get(params.sessionId), params.prompt) };
154
- default:
155
- throw Object.assign(new Error('Method not found'), { code: -32601 });
156
- }
157
- }
158
-
159
- let buffer = '';
160
- process.stdin.setEncoding('utf8');
161
- process.stdin.on('data', chunk => {
162
- buffer += chunk;
163
- let end;
164
- while ((end = buffer.indexOf('\n')) >= 0) {
165
- const line = buffer.slice(0, end);
166
- buffer = buffer.slice(end + 1);
167
- if (!line.trim()) continue;
168
- const message = JSON.parse(line);
169
- if (message.method === undefined) {
170
- waiting.get(message.id)?.(message.result);
171
- waiting.delete(message.id);
172
- } else if (message.id === undefined) {
173
- if (message.method === 'session/cancel') cancelled.add(message.params.sessionId);
174
- } else {
175
- handle(message.method, message.params).then(
176
- result => send({ id: message.id, result }),
177
- error => send({ id: message.id, error: { code: error.code ?? -32603, message: error.message } }),
178
- );
179
- }
180
- }
181
- });
182
- process.stdin.on('end', () => process.exit(0));
183
- process.stdout.write('not json: a program that logs on stdout\n');
package/src/acp-agent.ts DELETED
@@ -1,239 +0,0 @@
1
- import { type ChildProcess, spawn } from 'node:child_process';
2
- import { Acp } from './acp-protocol';
3
- import { AgentSession } from './agent-session';
4
- import { JsonRpcConnection, JsonRpcError } from './json-rpc';
5
- import { text } from './texts';
6
-
7
- /** How to start an agent that speaks ACP on its standard input and output. */
8
- export interface AgentProgram {
9
- command: string;
10
- args: string[];
11
- env?: Record<string, string>;
12
- /** Where it runs. Some agents run commands there rather than in the directory of a session. */
13
- cwd: string;
14
- /** `_meta` of the client's capabilities. */
15
- clientMeta?: Record<string, unknown>;
16
- }
17
-
18
- const STDERR_CHARS = 2000;
19
-
20
- /** Variables of the process of Ta (or pi) that are not the agent's business. */
21
- function agentEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
22
- const env: NodeJS.ProcessEnv = {};
23
- for (const [key, value] of Object.entries(process.env)) {
24
- if (!key.startsWith('PI_') && key !== 'ELECTRON_RUN_AS_NODE' && key !== 'AI_AGENT') {
25
- env[key] = value;
26
- }
27
- }
28
- return { ...env, ...extra };
29
- }
30
-
31
- /**
32
- * The process of an ACP agent, shared by the sessions of a directory: one program often takes hundreds
33
- * of megabytes. It starts with the first session that needs it and stops after `idleMs` without a turn;
34
- * sessions are loaded again when they need it next. Updates of sessions it does not know, such as the
35
- * history it replays while loading one, are dropped. It keeps the process of pi alive only while a
36
- * request is pending, so that `pi -p` exits once it answered.
37
- */
38
- export class AcpAgent {
39
- readonly sessions = new Map<string, AgentSession>();
40
- initialized?: Acp.InitializeResult;
41
-
42
- protected child?: ChildProcess;
43
- protected connection?: JsonRpcConnection;
44
- protected starting?: Promise<Acp.InitializeResult>;
45
- protected stderr = '';
46
- protected idleTimer?: ReturnType<typeof setTimeout>;
47
-
48
- constructor(
49
- readonly name: string,
50
- readonly program: AgentProgram,
51
- readonly idleMs = 10 * 60_000,
52
- ) {}
53
-
54
- get running(): boolean {
55
- return !!this.connection && !this.connection.isClosed;
56
- }
57
-
58
- start(): Promise<Acp.InitializeResult> {
59
- if (this.starting && this.running) {
60
- return this.starting;
61
- }
62
- this.starting = this.launch();
63
- // A failed start is tried again by the next session.
64
- this.starting.catch(() => (this.starting = undefined));
65
- return this.starting;
66
- }
67
-
68
- async newSession(cwd: string, signal?: AbortSignal): Promise<AgentSession> {
69
- await this.start();
70
- const setup = await this.request<Acp.SessionSetup>('session/new', { cwd, mcpServers: [] }, signal);
71
- if (!setup?.sessionId) {
72
- throw new Error(`${this.name} did not open a session`);
73
- }
74
- return this.add(setup.sessionId, setup);
75
- }
76
-
77
- /** Opens a session it had before; `undefined` when it cannot. */
78
- async loadSession(id: string, cwd: string, signal?: AbortSignal): Promise<AgentSession | undefined> {
79
- const known = this.sessions.get(id);
80
- if (known) {
81
- return known;
82
- }
83
- const init = await this.start();
84
- if (!init.agentCapabilities?.loadSession) {
85
- return undefined;
86
- }
87
- try {
88
- const setup = await this.request<Acp.SessionSetup>('session/load', { sessionId: id, cwd, mcpServers: [] }, signal);
89
- return this.add(id, setup ?? {});
90
- } catch (error) {
91
- if (error instanceof JsonRpcError && error.code !== Acp.AUTH_REQUIRED) {
92
- return undefined;
93
- }
94
- throw error;
95
- }
96
- }
97
-
98
- request<T>(method: string, params: unknown, signal?: AbortSignal): Promise<T> {
99
- this.touch();
100
- if (!this.connection || this.connection.isClosed) {
101
- return Promise.reject(new Error(`${this.name} is not running`));
102
- }
103
- const connection = this.connection;
104
- this.reference(true);
105
- return connection
106
- .request<T>(method, params, signal)
107
- .catch(error => {
108
- throw this.explain(error);
109
- })
110
- .finally(() => this.reference(connection.pendingCount > 0));
111
- }
112
-
113
- notify(method: string, params: unknown): void {
114
- this.connection?.notify(method, params);
115
- }
116
-
117
- stop(): void {
118
- clearTimeout(this.idleTimer);
119
- const child = this.child;
120
- this.child = undefined;
121
- this.connection?.close(new Error(`${this.name} stopped`));
122
- this.connection = undefined;
123
- this.starting = undefined;
124
- if (child && child.exitCode === null) {
125
- child.stdin?.end();
126
- child.kill();
127
- }
128
- }
129
-
130
- protected reference(on: boolean): void {
131
- const child = this.child;
132
- for (const handle of [child, child?.stdin, child?.stdout, child?.stderr] as ({ ref?(): void; unref?(): void } | null | undefined)[]) {
133
- if (on) {
134
- handle?.ref?.();
135
- } else {
136
- handle?.unref?.();
137
- }
138
- }
139
- }
140
-
141
- /** Stops the program `idleMs` after the last turn. */
142
- protected touch(): void {
143
- clearTimeout(this.idleTimer);
144
- this.idleTimer = setTimeout(() => {
145
- if ([...this.sessions.values()].some(session => session.turn)) {
146
- this.touch();
147
- } else {
148
- this.stop();
149
- }
150
- }, this.idleMs);
151
- this.idleTimer.unref?.();
152
- }
153
-
154
- protected add(id: string, setup: Acp.SessionSetup): AgentSession {
155
- const session = new AgentSession(this, id, setup);
156
- this.sessions.set(id, session);
157
- return session;
158
- }
159
-
160
- protected async launch(): Promise<Acp.InitializeResult> {
161
- this.stop();
162
- this.stderr = '';
163
- const child = spawn(this.program.command, this.program.args, {
164
- cwd: this.program.cwd,
165
- env: agentEnv(this.program.env),
166
- stdio: ['pipe', 'pipe', 'pipe'],
167
- shell: process.platform === 'win32',
168
- windowsHide: true,
169
- });
170
- this.child = child;
171
- const { stdin, stdout } = child;
172
- if (!stdin || !stdout) {
173
- throw new Error(`${this.name} has no standard input or output`);
174
- }
175
- const connection = new JsonRpcConnection(stdin, stdout);
176
- this.connection = connection;
177
- child.stderr?.setEncoding('utf8');
178
- child.stderr?.on('data', (chunk: string) => (this.stderr = (this.stderr + chunk).slice(-STDERR_CHARS)));
179
- child.on('error', (error: NodeJS.ErrnoException) =>
180
- connection.close(error.code === 'ENOENT' ? new Error(text('notFound', this.name, this.program.command)) : error),
181
- );
182
- child.on('exit', code => connection.close(new Error(text('exited', this.name, String(code ?? 'signal'), this.lastError()))));
183
- connection.onNotification = (method, params) => this.notified(method, params);
184
- connection.onRequest = (method, params) => this.requested(method, params);
185
- connection.onClose = error => {
186
- for (const session of this.sessions.values()) {
187
- session.turn?.fail(error.message);
188
- }
189
- this.sessions.clear();
190
- };
191
- this.reference(true);
192
- const init = await connection
193
- .request<Acp.InitializeResult>('initialize', {
194
- protocolVersion: Acp.PROTOCOL_VERSION,
195
- clientCapabilities: {
196
- fs: { readTextFile: false, writeTextFile: false },
197
- terminal: false,
198
- ...(this.program.clientMeta ? { _meta: this.program.clientMeta } : {}),
199
- },
200
- clientInfo: { name: 'ta', version: '1' },
201
- })
202
- .finally(() => this.reference(false));
203
- this.initialized = init;
204
- return init;
205
- }
206
-
207
- protected notified(method: string, params: unknown): void {
208
- this.touch();
209
- if (method !== 'session/update') {
210
- return;
211
- }
212
- const { sessionId, update } = (params ?? {}) as { sessionId?: string; update?: Acp.SessionUpdate };
213
- if (sessionId && update) {
214
- this.sessions.get(sessionId)?.update(update);
215
- }
216
- }
217
-
218
- protected async requested(method: string, params: unknown): Promise<unknown> {
219
- if (method === 'session/request_permission') {
220
- const request = params as Acp.PermissionRequest;
221
- const session = this.sessions.get(request.sessionId);
222
- const outcome = session ? await session.callbacks.permission(request) : AgentSession.allow(request);
223
- return { outcome };
224
- }
225
- throw new JsonRpcError(-32601, `Method not found: ${method}`);
226
- }
227
-
228
- protected explain(error: unknown): Error {
229
- if (error instanceof JsonRpcError && error.code === Acp.AUTH_REQUIRED) {
230
- return Object.assign(new Error(`${this.name} is not signed in`), { code: error.code });
231
- }
232
- return error instanceof Error ? error : new Error(String(error));
233
- }
234
-
235
- protected lastError(): string {
236
- const lines = this.stderr.trim().split('\n').filter(Boolean);
237
- return lines[lines.length - 1] ?? '';
238
- }
239
- }
@@ -1,135 +0,0 @@
1
- /**
2
- * The part of the Agent Client Protocol (https://agentclientprotocol.com, version 1) a client that only
3
- * prompts uses: no file system or terminal of the client is offered, so the agent works with its own tools.
4
- */
5
- export namespace Acp {
6
- export const PROTOCOL_VERSION = 1;
7
- /** The error of `session/new` and `session/prompt` when the user has to sign in first. */
8
- export const AUTH_REQUIRED = -32000;
9
-
10
- export interface ContentBlock {
11
- type: 'text' | 'image' | 'audio' | 'resource_link' | 'resource';
12
- text?: string;
13
- data?: string;
14
- mimeType?: string;
15
- uri?: string;
16
- name?: string;
17
- resource?: { uri?: string; text?: string };
18
- }
19
-
20
- export interface InitializeResult {
21
- protocolVersion: number;
22
- agentCapabilities?: {
23
- loadSession?: boolean;
24
- promptCapabilities?: { image?: boolean; audio?: boolean; embeddedContext?: boolean };
25
- };
26
- authMethods?: { id: string; name: string; description?: string | null }[];
27
- }
28
-
29
- export interface SelectValue {
30
- value: string;
31
- name: string;
32
- description?: string | null;
33
- }
34
-
35
- /** A setting of a session: `category` `model`, `thought_level` and `mode` are the ones a client knows. */
36
- export interface ConfigOption {
37
- type: 'select' | 'boolean' | string;
38
- id: string;
39
- name: string;
40
- category?: string;
41
- currentValue: string | boolean;
42
- /** Values, or groups of values. */
43
- options?: (SelectValue | { group?: string; name?: string; options: SelectValue[] })[];
44
- }
45
-
46
- /** The older way agents list their models. */
47
- export interface SessionModels {
48
- currentModelId: string;
49
- availableModels: { modelId: string; name: string; description?: string | null }[];
50
- }
51
-
52
- export interface SessionSetup {
53
- sessionId?: string;
54
- configOptions?: ConfigOption[];
55
- models?: SessionModels;
56
- }
57
-
58
- export type ToolKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'think' | 'fetch' | 'switch_mode' | 'other';
59
- export type ToolStatus = 'pending' | 'in_progress' | 'completed' | 'failed';
60
-
61
- export type ToolCallContent =
62
- | { type: 'content'; content: ContentBlock }
63
- | { type: 'diff'; path: string; oldText?: string | null; newText: string }
64
- | { type: 'terminal'; terminalId: string };
65
-
66
- export interface ToolCallUpdate {
67
- toolCallId: string;
68
- title?: string;
69
- kind?: ToolKind;
70
- status?: ToolStatus;
71
- content?: ToolCallContent[] | null;
72
- locations?: { path: string; line?: number | null }[] | null;
73
- rawInput?: unknown;
74
- rawOutput?: unknown;
75
- _meta?: Record<string, unknown>;
76
- }
77
-
78
- export interface PlanEntry {
79
- content: string;
80
- priority?: string;
81
- status: 'pending' | 'in_progress' | 'completed';
82
- }
83
-
84
- export type SessionUpdate =
85
- | { sessionUpdate: 'user_message_chunk' | 'agent_message_chunk' | 'agent_thought_chunk'; content: ContentBlock; _meta?: Record<string, unknown> }
86
- | ({ sessionUpdate: 'tool_call' | 'tool_call_update' } & ToolCallUpdate)
87
- | { sessionUpdate: 'plan'; entries: PlanEntry[] }
88
- | { sessionUpdate: 'config_option_update'; configOptions: ConfigOption[] }
89
- | { sessionUpdate: 'usage_update'; used?: number; size?: number; _meta?: Record<string, unknown> }
90
- | { sessionUpdate: 'session_info_update'; title?: string | null; _meta?: Record<string, unknown> }
91
- | { sessionUpdate: string; _meta?: Record<string, unknown>; [key: string]: unknown };
92
-
93
- export interface PermissionOption {
94
- optionId: string;
95
- name: string;
96
- kind: 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always';
97
- }
98
-
99
- export interface PermissionRequest {
100
- sessionId: string;
101
- toolCall: ToolCallUpdate;
102
- options: PermissionOption[];
103
- }
104
-
105
- export type PermissionOutcome = { outcome: 'selected'; optionId: string } | { outcome: 'cancelled' };
106
-
107
- export type StopReason = 'end_turn' | 'max_tokens' | 'max_turn_requests' | 'refusal' | 'cancelled';
108
-
109
- /** The text of a block; other blocks are named, not shown. */
110
- export function text(block: ContentBlock | undefined): string {
111
- if (!block) {
112
- return '';
113
- }
114
- switch (block.type) {
115
- case 'text':
116
- return block.text ?? '';
117
- case 'resource':
118
- return block.resource?.text ?? block.resource?.uri ?? '';
119
- case 'resource_link':
120
- return block.uri ?? block.name ?? '';
121
- default:
122
- return `[${block.type}]`;
123
- }
124
- }
125
-
126
- /** The values of a select option, its groups flattened. */
127
- export function values(option: ConfigOption | undefined): SelectValue[] {
128
- return (option?.options ?? []).flatMap(item => ('options' in item && Array.isArray(item.options) ? item.options : [item as SelectValue]));
129
- }
130
-
131
- /** The option of a category: the id is the key the protocol gives, the category what it means. */
132
- export function optionOf(options: ConfigOption[] | undefined, category: string): ConfigOption | undefined {
133
- return options?.find(option => option.category === category) ?? options?.find(option => option.id === category);
134
- }
135
- }