@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.
@@ -1,252 +0,0 @@
1
- import { Acp } from './acp-protocol';
2
- import { AgentTurn, type WriteListener } from './agent-turn';
3
-
4
- /** How a session reaches the rest: the user for permissions, pi when the agent starts a turn on its own. */
5
- export interface AgentSessionHost {
6
- request<T>(method: string, params: unknown, signal?: AbortSignal): Promise<T>;
7
- notify(method: string, params: unknown): void;
8
- }
9
-
10
- export interface AgentSessionCallbacks {
11
- permission(request: Acp.PermissionRequest): Promise<Acp.PermissionOutcome>;
12
- /** The agent named the session. */
13
- title?(title: string): void;
14
- /** The agent started a turn on its own, for example to report a background task that finished. */
15
- activity(session: AgentSession): void;
16
- /** A call of the agent is about to change a file, or changed it (see WriteListener). */
17
- write?: WriteListener;
18
- }
19
-
20
- /** How long a turn the agent started on its own lasts after its last update, when the agent does not say it ended. */
21
- const UNSOLICITED_QUIET_MS = 3000;
22
- /** How long a prompt waits for the agent to end a turn that was cancelled. */
23
- const ABANDON_WAIT_MS = 5000;
24
- /** How long a prompt waits for the agent to answer the one before, which it may still finish after saying it is idle. */
25
- const ANSWER_WAIT_MS = 15_000;
26
-
27
- /**
28
- * A session of an ACP agent: its settings, and its turn. A prompt starts a turn; what the user says
29
- * while it runs is sent once it ended, since ACP has no way to steer a running turn.
30
- */
31
- export class AgentSession {
32
- /** The turn being streamed: until the provider took its end, even after the agent answered. */
33
- turn?: AgentTurn;
34
- options: Acp.ConfigOption[] = [];
35
- models?: Acp.SessionModels;
36
- title?: string;
37
- callbacks: AgentSessionCallbacks = { permission: async request => AgentSession.allow(request), activity: () => undefined };
38
-
39
- protected readonly queued: Acp.ContentBlock[][] = [];
40
- protected quietTimer?: ReturnType<typeof setTimeout>;
41
- protected abandoned?: AgentTurn;
42
- /** The answer to the last `session/prompt`, settled or not. */
43
- protected answer?: Promise<unknown>;
44
- /** The agent said it works on the turn (a phase other than idle), so its next idle ends it. */
45
- protected working = false;
46
- /** The ids of the requests the agent named in its updates (`_meta` `…requestId`), and those before the current prompt. */
47
- protected readonly requests = new Set<string>();
48
- protected earlier = new Set<string>();
49
-
50
- constructor(
51
- protected readonly host: AgentSessionHost,
52
- readonly id: string,
53
- setup: Acp.SessionSetup,
54
- ) {
55
- this.apply(setup);
56
- }
57
-
58
- apply(setup: Acp.SessionSetup): void {
59
- if (setup.configOptions) {
60
- this.options = setup.configOptions;
61
- }
62
- if (setup.models) {
63
- this.models = setup.models;
64
- }
65
- }
66
-
67
- update(update: Acp.SessionUpdate): void {
68
- const meta = (update as { _meta?: Record<string, unknown> })._meta;
69
- const ids = AgentSession.requestIds(meta);
70
- for (const id of ids) {
71
- this.requests.add(id);
72
- }
73
- switch (update.sessionUpdate) {
74
- case 'config_option_update':
75
- this.options = (update as { configOptions: Acp.ConfigOption[] }).configOptions ?? this.options;
76
- return;
77
- case 'session_info_update': {
78
- const title = (update as { title?: string | null }).title;
79
- if (typeof title === 'string' && title.trim() && title.trim() !== this.title) {
80
- this.title = title.trim();
81
- this.callbacks.title?.(this.title);
82
- }
83
- const phase = AgentSession.phase(meta);
84
- // A phase of a request before this prompt (the end of a compaction, say) is not this turn's.
85
- const stale = ids.some(id => this.earlier.has(id));
86
- if (phase && !stale && this.turn && !this.turn.unsolicited) {
87
- // Some agents (CodeBuddy Code) answer the prompt seconds after they are done, once they named
88
- // the session: their phase says when the turn ended.
89
- if (phase !== 'idle') {
90
- this.working = true;
91
- } else if (this.working) {
92
- this.working = false;
93
- this.turn.end('end_turn');
94
- }
95
- }
96
- if (meta && Object.keys(meta).some(key => /unsolicitedTurn$/.test(key)) && !this.turn) {
97
- this.startUnsolicited(false);
98
- }
99
- return;
100
- }
101
- case 'session_end':
102
- if (this.turn?.unsolicited) {
103
- this.turn.end('end_turn');
104
- }
105
- return;
106
- case 'agent_message_chunk':
107
- case 'agent_thought_chunk':
108
- case 'tool_call':
109
- case 'tool_call_update':
110
- case 'plan':
111
- if (!this.turn) {
112
- this.startUnsolicited(true);
113
- }
114
- break;
115
- }
116
- this.turn?.update(update);
117
- if (this.turn?.unsolicited && this.quietTimer) {
118
- this.quiet(this.turn);
119
- }
120
- }
121
-
122
- /** Starts a turn with `prompt`. */
123
- prompt(prompt: Acp.ContentBlock[]): AgentTurn {
124
- const first = prompt.find(block => block.type === 'text')?.text?.trim() ?? '';
125
- const turn = new AgentTurn(false, /^\/[\w:.-]+/.exec(first)?.[0], (path, before) => this.callbacks.write?.(path, before));
126
- this.turn = turn;
127
- this.working = false;
128
- this.earlier = new Set(this.requests);
129
- const answer = this.host.request<{ stopReason: Acp.StopReason }>('session/prompt', { sessionId: this.id, prompt }).then(
130
- response => turn.end(response?.stopReason ?? 'end_turn'),
131
- (error: Error & { code?: number }) => turn.fail(error.message, error.code),
132
- );
133
- this.answer = answer;
134
- return turn;
135
- }
136
-
137
- /** Keeps `prompt` for when the current turn ended. */
138
- queue(prompt: Acp.ContentBlock[]): void {
139
- this.queued.push(prompt);
140
- }
141
-
142
- /** The prompts kept while a turn ran, as one. */
143
- takeQueued(): Acp.ContentBlock[] | undefined {
144
- if (!this.queued.length) {
145
- return undefined;
146
- }
147
- return this.queued.splice(0).flat();
148
- }
149
-
150
- /**
151
- * Stops streaming `turn`, cancelled: the agent still ends it, and the next prompt waits for that
152
- * (`idle`), since an agent takes one prompt of a session at a time.
153
- */
154
- abandon(turn: AgentTurn): void {
155
- this.cancel();
156
- this.finished(turn);
157
- this.abandoned = turn;
158
- }
159
-
160
- /** Waits for a cancelled turn to end, and for the answer to the prompt before, a few seconds at most. */
161
- async idle(): Promise<void> {
162
- const turn = this.abandoned;
163
- this.abandoned = undefined;
164
- await turn?.whenEnded(ABANDON_WAIT_MS);
165
- const answer = this.answer;
166
- if (answer) {
167
- let timer: ReturnType<typeof setTimeout> | undefined;
168
- await Promise.race([answer, new Promise(resolve => (timer = setTimeout(resolve, ANSWER_WAIT_MS)))]);
169
- clearTimeout(timer);
170
- }
171
- }
172
-
173
- /** The provider took the end of `turn`. */
174
- finished(turn: AgentTurn): void {
175
- if (this.turn === turn) {
176
- this.turn = undefined;
177
- clearTimeout(this.quietTimer);
178
- this.quietTimer = undefined;
179
- }
180
- }
181
-
182
- cancel(): void {
183
- this.host.notify('session/cancel', { sessionId: this.id });
184
- if (this.turn?.unsolicited) {
185
- this.turn.end('cancelled');
186
- }
187
- }
188
-
189
- /** Sets a select option to `value` unless it already is, or the agent does not offer it. */
190
- async select(category: string, value: string | undefined, signal?: AbortSignal): Promise<void> {
191
- if (value === undefined) {
192
- return;
193
- }
194
- const option = Acp.optionOf(this.options, category);
195
- if (option) {
196
- if (option.currentValue === value || !Acp.values(option).some(candidate => candidate.value === value)) {
197
- return;
198
- }
199
- const result = await this.host.request<Acp.SessionSetup>('session/set_config_option', { sessionId: this.id, configId: option.id, value }, signal);
200
- this.apply(result ?? {});
201
- option.currentValue = value;
202
- } else if (category === 'model' && this.models && this.models.currentModelId !== value) {
203
- if (this.models.availableModels.some(model => model.modelId === value)) {
204
- await this.host.request('session/set_model', { sessionId: this.id, modelId: value }, signal);
205
- this.models.currentModelId = value;
206
- }
207
- }
208
- }
209
-
210
- protected startUnsolicited(quiet: boolean): void {
211
- const turn = new AgentTurn(true, undefined, (path, before) => this.callbacks.write?.(path, before));
212
- this.turn = turn;
213
- if (quiet) {
214
- this.quiet(turn);
215
- }
216
- this.callbacks.activity(this);
217
- }
218
-
219
- /** Ends a turn the agent started without saying when it ends, once it is quiet. */
220
- protected quiet(turn: AgentTurn): void {
221
- clearTimeout(this.quietTimer);
222
- this.quietTimer = setTimeout(() => turn.end('end_turn'), UNSOLICITED_QUIET_MS);
223
- this.quietTimer.unref?.();
224
- }
225
-
226
- /** The ids of requests in `_meta`, under keys of the agent's own (`<agent>/requestId`, `<agent>/messageRequestId`). */
227
- static requestIds(meta: Record<string, unknown> | undefined): string[] {
228
- return Object.entries(meta ?? {})
229
- .filter(([key, value]) => /requestId$/i.test(key) && typeof value === 'string' && value)
230
- .map(([, value]) => value as string);
231
- }
232
-
233
- /** What the agent says it is doing, if it says (CodeBuddy Code: `_meta['codebuddy.ai/agentPhase'].phase`). */
234
- static phase(meta: Record<string, unknown> | undefined): string | undefined {
235
- for (const [key, value] of Object.entries(meta ?? {})) {
236
- const phase = (value as { phase?: unknown } | null)?.phase;
237
- if (/agentPhase$/.test(key) && typeof phase === 'string') {
238
- return phase;
239
- }
240
- }
241
- return undefined;
242
- }
243
-
244
- /** Allows once: pi does not ask before tool calls, and neither does Ta for the agents it runs. */
245
- static allow(request: Acp.PermissionRequest): Acp.PermissionOutcome {
246
- const option =
247
- request.options.find(candidate => candidate.kind === 'allow_once') ??
248
- request.options.find(candidate => candidate.kind === 'allow_always') ??
249
- request.options[0];
250
- return option ? { outcome: 'selected', optionId: option.optionId } : { outcome: 'cancelled' };
251
- }
252
- }
@@ -1,196 +0,0 @@
1
- import { Acp } from './acp-protocol';
2
- import { AgentCatalog, type AgentConfig } from './agent-catalog';
3
- import { AgentPrompt } from './agent-prompt';
4
- import type { AgentSession } from './agent-session';
5
- import { type AgentCall, AgentTool } from './agent-tool';
6
- import type { AgentTurn } from './agent-turn';
7
- import { emptyUsage, MessageBuilder, MessageStream } from './message-stream';
8
- import type { Model, SimpleStreamOptions, TranscriptContext, Usage } from './pi-types';
9
- import { text } from './texts';
10
-
11
- /** A session of an agent for the pi session, and whether it starts empty. */
12
- export interface OpenedSession {
13
- session: AgentSession;
14
- fresh: boolean;
15
- images: boolean;
16
- /** The directory of the session, as given and as its real path: agents may report either. */
17
- dirs: string[];
18
- }
19
-
20
- export interface AgentStreamHost {
21
- open(config: AgentConfig, signal?: AbortSignal): Promise<OpenedSession>;
22
- readonly calls: Map<string, AgentCall>;
23
- /** A turn of `session` ended. */
24
- ended(config: AgentConfig, session: AgentSession): void;
25
- }
26
-
27
- /** How long a tool call of the agent may stay silent before its arguments count as complete anyway. */
28
- const SETTLE_MS = 1500;
29
-
30
- /** The values of an agent's `thought_level` that stand for pi's thinking levels, best first. */
31
- const THINKING: Record<string, string[]> = {
32
- minimal: ['minimal', 'low'],
33
- low: ['low'],
34
- medium: ['medium'],
35
- high: ['high'],
36
- xhigh: ['xhigh', 'max', 'high'],
37
- };
38
-
39
- /**
40
- * pi's `streamSimple` for an agent. A pi turn sends what the user said since the agent last answered
41
- * and streams the agent's turn; each tool call of the agent ends the assistant message with a call of
42
- * {@link AgentTool}, and the next `streamSimple`, after pi "ran" it, goes on with the same turn.
43
- */
44
- export class AgentStreamer {
45
- constructor(protected readonly host: AgentStreamHost) {}
46
-
47
- stream(config: AgentConfig, model: Model, context: TranscriptContext, options?: SimpleStreamOptions): MessageStream {
48
- const stream = new MessageStream();
49
- const builder = new MessageBuilder(stream, model);
50
- this.run(config, model, context, options, builder).catch(error => builder.error('error', AgentStreamer.describe(config, error)));
51
- return stream;
52
- }
53
-
54
- protected async run(
55
- config: AgentConfig,
56
- model: Model,
57
- context: TranscriptContext,
58
- options: SimpleStreamOptions | undefined,
59
- builder: MessageBuilder,
60
- ): Promise<void> {
61
- const signal = options?.signal;
62
- const { session, fresh, images, dirs } = await this.host.open(config, signal);
63
- const pending = AgentPrompt.pending(context.messages);
64
- let turn = session.turn;
65
- if (turn) {
66
- // What the user said while the agent works goes once it ended.
67
- if (pending.length) {
68
- session.queue(AgentPrompt.blocks(pending, images));
69
- }
70
- } else {
71
- let prompt = pending.length ? AgentPrompt.blocks(pending, images) : session.takeQueued();
72
- if (!prompt?.length) {
73
- builder.done('stop');
74
- return;
75
- }
76
- const earlier = fresh ? AgentPrompt.transcript(context.messages, pending.length) : undefined;
77
- if (earlier) {
78
- prompt = [{ type: 'text', text: earlier }, ...prompt];
79
- }
80
- await session.idle();
81
- await this.configure(session, model, options, signal);
82
- turn = session.prompt(prompt);
83
- }
84
- for (;;) {
85
- const item = await turn.next(signal);
86
- if (!item) {
87
- session.abandon(turn);
88
- builder.error('aborted', 'Aborted');
89
- return;
90
- }
91
- switch (item.type) {
92
- case 'text':
93
- case 'thinking':
94
- builder.append(item.type, item.text);
95
- break;
96
- case 'tool':
97
- await this.tools(config, session, turn, item.id, builder, dirs, signal);
98
- return;
99
- case 'end': {
100
- session.finished(turn);
101
- this.host.ended(config, session);
102
- const queued = session.takeQueued();
103
- if (queued) {
104
- turn = session.prompt(queued);
105
- break;
106
- }
107
- if (item.reason === 'cancelled' && signal?.aborted) {
108
- builder.error('aborted', 'Aborted');
109
- } else {
110
- if (turn.command && !turn.produced) {
111
- // A command of the agent that only acts in its own interface (a panel, a reset) says nothing.
112
- builder.append('text', text('commandDone', config.name, turn.command));
113
- }
114
- builder.done('stop', AgentStreamer.usage(turn));
115
- }
116
- return;
117
- }
118
- case 'error':
119
- session.finished(turn);
120
- builder.error('error', AgentStreamer.describe(config, item));
121
- return;
122
- }
123
- }
124
- }
125
-
126
- /** Ends the message with the calls the agent started, once their arguments are complete. */
127
- protected async tools(
128
- config: AgentConfig,
129
- session: AgentSession,
130
- turn: AgentTurn,
131
- first: string,
132
- builder: MessageBuilder,
133
- dirs: string[],
134
- signal?: AbortSignal,
135
- ): Promise<void> {
136
- // Calls started together go in one message: each once its arguments are complete.
137
- const ids = [first];
138
- while (turn.peek()?.type === 'tool') {
139
- ids.push((turn.shift() as { id: string }).id);
140
- }
141
- for (const id of ids) {
142
- await turn.settle(id, SETTLE_MS, signal);
143
- }
144
- if (signal?.aborted) {
145
- session.abandon(turn);
146
- builder.error('aborted', 'Aborted');
147
- return;
148
- }
149
- for (const id of ids) {
150
- const run = turn.tools.get(id);
151
- if (run) {
152
- this.host.calls.set(id, { agent: config.name, session, turn });
153
- builder.toolCall({ type: 'toolCall', id, name: AgentTool.NAME, arguments: AgentTool.args(run, dirs) });
154
- }
155
- }
156
- builder.done('toolUse');
157
- }
158
-
159
- /** The model and thinking level pi has, set on the agent; what it does not offer stays as it is. */
160
- protected async configure(session: AgentSession, model: Model, options: SimpleStreamOptions | undefined, signal?: AbortSignal): Promise<void> {
161
- try {
162
- if (model.id !== AgentCatalog.DEFAULT_MODEL) {
163
- await session.select('model', model.id, signal);
164
- }
165
- const level = options?.reasoning;
166
- if (level && model.reasoning) {
167
- const offered = Acp.values(Acp.optionOf(session.options, 'thought_level')).map(value => value.value);
168
- await session.select(
169
- 'thought_level',
170
- (THINKING[level] ?? [level]).find(value => offered.includes(value)),
171
- signal,
172
- );
173
- }
174
- } catch {
175
- // The agent goes on with what it had.
176
- }
177
- }
178
-
179
- static usage(turn: AgentTurn): Usage {
180
- const usage = emptyUsage();
181
- const { input, output, cacheRead, used } = turn.usage;
182
- usage.cacheRead = cacheRead ?? 0;
183
- usage.input = input !== undefined ? Math.max(0, input - usage.cacheRead) : (used ?? 0);
184
- usage.output = output ?? 0;
185
- usage.totalTokens = usage.input + usage.output + usage.cacheRead;
186
- return usage;
187
- }
188
-
189
- static describe(config: AgentConfig, error: { message?: string; code?: number } | unknown): string {
190
- const { message, code } = (error ?? {}) as { message?: string; code?: number };
191
- if (code === Acp.AUTH_REQUIRED) {
192
- return text('signIn', config.name, config.login ?? config.command);
193
- }
194
- return message || String(error);
195
- }
196
- }
@@ -1,34 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { AgentTool } from './agent-tool';
3
- import type { ToolRun } from './agent-turn';
4
-
5
- const run = (fields: Partial<ToolRun>): ToolRun => ({
6
- id: 't',
7
- title: '',
8
- kind: 'other',
9
- input: {},
10
- locations: [],
11
- status: 'completed',
12
- output: '',
13
- done: true,
14
- complete: true,
15
- terminal: '',
16
- updatedAt: 0,
17
- ...fields,
18
- });
19
-
20
- describe('AgentTool', () => {
21
- it('describes a call by its kind and what it is on, paths in the session relative', () => {
22
- const dirs = ['/tmp/w', '/private/tmp/w'];
23
- expect(AgentTool.args(run({ kind: 'read', title: 'Read', locations: ['/private/tmp/w/src/a.ts'], name: 'Read' }), dirs)).toEqual({
24
- title: 'Read',
25
- kind: 'read',
26
- target: 'src/a.ts',
27
- tool: 'Read',
28
- });
29
- expect(AgentTool.args(run({ kind: 'execute', title: '`npm test`' })).target).toBe('npm test');
30
- expect(AgentTool.args(run({ kind: 'search', title: 'Grep', input: { pattern: 'TODO' } })).target).toBe('TODO');
31
- expect(AgentTool.args(run({ kind: 'edit', title: 'Edit /etc/hosts', locations: ['/etc/hosts'] }), dirs).target).toBe('/etc/hosts');
32
- expect(AgentTool.args(run({ title: 'Skill' })).target).toBe('Skill');
33
- });
34
- });
package/src/agent-tool.ts DELETED
@@ -1,95 +0,0 @@
1
- import type { AgentSession } from './agent-session';
2
- import type { AgentTurn, ToolRun } from './agent-turn';
3
- import type { AgentToolResult, ToolDefinition } from './pi-types';
4
- import { text } from './texts';
5
-
6
- /** Where a call the provider showed to pi runs: in a turn of an agent's session. */
7
- export interface AgentCall {
8
- agent: string;
9
- session: AgentSession;
10
- turn: AgentTurn;
11
- }
12
-
13
- function relative(path: string, dirs: string[]): string {
14
- const dir = dirs.find(candidate => path.startsWith(`${candidate}/`) || path.startsWith(`${candidate}\\`));
15
- return dir ? path.slice(dir.length + 1) : path;
16
- }
17
-
18
- function str(value: unknown): string | undefined {
19
- return typeof value === 'string' && value.trim() ? value.trim() : undefined;
20
- }
21
-
22
- /**
23
- * The tool that stands for the tool calls an agent makes with its own tools. The provider ends an
24
- * assistant message with such a call when the agent makes one, so that pi records and shows it as it
25
- * does its own; running it only waits for the agent to finish the call. The arguments describe the
26
- * call for clients: what kind of thing it does, on what.
27
- */
28
- export namespace AgentTool {
29
- export const NAME = 'agent_tool';
30
-
31
- /** `cwd`: the directory of the session (its real path too), for paths in it to show relative. */
32
- export function args(run: ToolRun, cwd: string[] = []): Record<string, string> {
33
- const input = run.input;
34
- const title = run.title || run.name || run.kind;
35
- let target: string | undefined;
36
- switch (run.kind) {
37
- case 'execute':
38
- target = str(input.command) ?? title.replace(/^`|`$/g, '');
39
- break;
40
- case 'read':
41
- case 'edit':
42
- case 'delete':
43
- case 'move':
44
- target = run.locations[0] ?? str(input.file_path) ?? str(input.path) ?? str(input.filePath);
45
- break;
46
- case 'search':
47
- target = str(input.pattern) ?? str(input.query);
48
- break;
49
- case 'fetch':
50
- target = str(input.url) ?? str(input.query);
51
- break;
52
- }
53
- // A call that says what it is for (a script of CodeBuddy Code's code mode, a command) is shown by that.
54
- target ??= str(input.description);
55
- return { title, kind: run.kind, target: relative(target ?? title, cwd), ...(run.name ? { tool: run.name } : {}) };
56
- }
57
-
58
- export function definition(calls: Map<string, AgentCall>): ToolDefinition {
59
- return {
60
- name: NAME,
61
- label: 'Agent tool',
62
- description: 'A tool call another coding agent made with its own tools. Only that agent calls it.',
63
- parameters: {
64
- type: 'object',
65
- properties: {
66
- title: { type: 'string' },
67
- kind: { type: 'string' },
68
- target: { type: 'string' },
69
- tool: { type: 'string' },
70
- },
71
- } as unknown as ToolDefinition['parameters'],
72
- exposure: 'direct',
73
- defaultActive: false,
74
- annotations: { readOnlyHint: true },
75
- async execute(toolCallId, _params, signal): Promise<AgentToolResult> {
76
- const call = calls.get(toolCallId);
77
- if (!call) {
78
- return { content: [{ type: 'text', text: 'This call ran in an earlier run of the agent.' }], details: {} };
79
- }
80
- const run = await call.turn.waitTool(toolCallId, signal);
81
- if (signal?.aborted) {
82
- call.session.abandon(call.turn);
83
- calls.delete(toolCallId);
84
- throw new Error('Cancelled');
85
- }
86
- calls.delete(toolCallId);
87
- const details = { agent: call.agent, kind: run?.kind, title: run?.title, status: run?.status, locations: run?.locations };
88
- if (!run?.done) {
89
- return { content: [{ type: 'text', text: text('unfinished', call.agent) }], details, isError: true };
90
- }
91
- return { content: [{ type: 'text', text: run.output || '(no output)' }], details, isError: run.status === 'failed' };
92
- },
93
- } as ToolDefinition;
94
- }
95
- }