@celljs/ta-agents 4.8.0 → 4.9.1
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/README.en.md +2 -2
- package/README.md +2 -2
- package/extension/index.mjs +61 -13
- package/package.json +11 -3
- package/fixtures/fake-acp-agent.mjs +0 -183
- package/src/acp-agent.ts +0 -239
- package/src/acp-protocol.ts +0 -135
- package/src/agent-bindings.ts +0 -147
- package/src/agent-catalog.spec.ts +0 -56
- package/src/agent-catalog.ts +0 -176
- package/src/agent-prompt.spec.ts +0 -44
- package/src/agent-prompt.ts +0 -83
- package/src/agent-session.spec.ts +0 -45
- package/src/agent-session.ts +0 -252
- package/src/agent-streamer.ts +0 -196
- package/src/agent-tool.spec.ts +0 -34
- package/src/agent-tool.ts +0 -95
- package/src/agent-turn.spec.ts +0 -122
- package/src/agent-turn.ts +0 -400
- package/src/extension.spec.ts +0 -327
- package/src/extension.ts +0 -273
- package/src/json-rpc.spec.ts +0 -72
- package/src/json-rpc.ts +0 -166
- package/src/message-stream.ts +0 -139
- package/src/pi-types.ts +0 -22
- package/src/texts.spec.ts +0 -11
- package/src/texts.ts +0 -42
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
|
-
}
|
package/src/acp-protocol.ts
DELETED
|
@@ -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
|
-
}
|
package/src/agent-bindings.ts
DELETED
|
@@ -1,147 +0,0 @@
|
|
|
1
|
-
import { realpathSync } from 'node:fs';
|
|
2
|
-
import { homedir } from 'node:os';
|
|
3
|
-
import { join, sep } from 'node:path';
|
|
4
|
-
import { AcpAgent } from './acp-agent';
|
|
5
|
-
import type { AgentConfig } from './agent-catalog';
|
|
6
|
-
import type { AgentSession } from './agent-session';
|
|
7
|
-
import type { OpenedSession } from './agent-streamer';
|
|
8
|
-
import { text } from './texts';
|
|
9
|
-
|
|
10
|
-
/** The custom entry of a pi session that names the session of an agent it talks to. */
|
|
11
|
-
export const BINDING_ENTRY = 'ta-agents.session';
|
|
12
|
-
|
|
13
|
-
export interface Binding {
|
|
14
|
-
agent: string;
|
|
15
|
-
session: string;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const POOL = Symbol.for('ta-agents.pool');
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* The agents' processes of this process, shared by its pi sessions, which load this package each: one
|
|
22
|
-
* per agent and directory, since some agents run commands where they were started.
|
|
23
|
-
*/
|
|
24
|
-
export namespace AgentPool {
|
|
25
|
-
export function of(config: AgentConfig, cwd: string): AcpAgent {
|
|
26
|
-
const global = globalThis as Record<symbol, Map<string, AcpAgent> | undefined>;
|
|
27
|
-
const pool = global[POOL] ?? create();
|
|
28
|
-
global[POOL] = pool;
|
|
29
|
-
const key = JSON.stringify([config.command, config.args, config.env ?? {}, config.clientMeta ?? {}, cwd]);
|
|
30
|
-
let agent = pool.get(key);
|
|
31
|
-
if (!agent) {
|
|
32
|
-
agent = new AcpAgent(config.name, { command: config.command, args: config.args, env: config.env, clientMeta: config.clientMeta, cwd });
|
|
33
|
-
pool.set(key, agent);
|
|
34
|
-
}
|
|
35
|
-
return agent;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function create(): Map<string, AcpAgent> {
|
|
39
|
-
const pool = new Map<string, AcpAgent>();
|
|
40
|
-
process.once('exit', () => {
|
|
41
|
-
for (const agent of pool.values()) {
|
|
42
|
-
agent.stop();
|
|
43
|
-
}
|
|
44
|
-
});
|
|
45
|
-
return pool;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* The sessions of agents one pi session talks to, one per agent. Which session that is stays in the
|
|
51
|
-
* pi session (a custom entry on its branch), so that reopening the conversation loads the agent's
|
|
52
|
-
* session again; a fork, or going back in the conversation, starts a new one.
|
|
53
|
-
*/
|
|
54
|
-
export class AgentBindings {
|
|
55
|
-
cwd = process.cwd();
|
|
56
|
-
|
|
57
|
-
protected readonly ids = new Map<string, string>();
|
|
58
|
-
protected readonly opened = new Map<string, Promise<OpenedSession>>();
|
|
59
|
-
|
|
60
|
-
constructor(
|
|
61
|
-
protected readonly save: (binding: Binding) => void,
|
|
62
|
-
protected readonly prepare: (config: AgentConfig, session: AgentSession) => void,
|
|
63
|
-
protected readonly agentOf: (config: AgentConfig, cwd: string) => AcpAgent = AgentPool.of,
|
|
64
|
-
) {}
|
|
65
|
-
|
|
66
|
-
restore(entries: readonly unknown[], fork: boolean): void {
|
|
67
|
-
this.ids.clear();
|
|
68
|
-
this.opened.clear();
|
|
69
|
-
if (fork) {
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
for (const entry of entries) {
|
|
73
|
-
const { type, customType, data } = (entry ?? {}) as { type?: string; customType?: string; data?: Partial<Binding> };
|
|
74
|
-
if (type === 'custom' && customType === BINDING_ENTRY && typeof data?.agent === 'string' && typeof data.session === 'string') {
|
|
75
|
-
this.ids.set(data.agent, data.session);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* The conversation went back (pi's tree): the agents' sessions remember what came after, so the next
|
|
82
|
-
* prompt starts new ones, with the conversation up to here.
|
|
83
|
-
*/
|
|
84
|
-
forget(): void {
|
|
85
|
-
this.ids.clear();
|
|
86
|
-
this.opened.clear();
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
sessionId(agent: string): string | undefined {
|
|
90
|
-
return this.ids.get(agent);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
open(config: AgentConfig, signal?: AbortSignal): Promise<OpenedSession> {
|
|
94
|
-
const agent = this.agentOf(config, this.cwd);
|
|
95
|
-
let opened = this.opened.get(config.id);
|
|
96
|
-
if (opened) {
|
|
97
|
-
// The program may have stopped since, idle, and its sessions with it.
|
|
98
|
-
// It starts empty only the first time.
|
|
99
|
-
opened = opened.then(value =>
|
|
100
|
-
agent.running && agent.sessions.get(value.session.id) === value.session ? { ...value, fresh: false } : this.connect(config, agent, signal),
|
|
101
|
-
);
|
|
102
|
-
} else {
|
|
103
|
-
opened = this.connect(config, agent, signal);
|
|
104
|
-
}
|
|
105
|
-
opened.catch(() => this.opened.delete(config.id));
|
|
106
|
-
this.opened.set(config.id, opened);
|
|
107
|
-
return opened;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
close(): void {
|
|
111
|
-
this.opened.clear();
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
protected async connect(config: AgentConfig, agent: AcpAgent, signal?: AbortSignal): Promise<OpenedSession> {
|
|
115
|
-
if (AgentBindings.isRemote(this.cwd)) {
|
|
116
|
-
throw new Error(text('remote', config.name));
|
|
117
|
-
}
|
|
118
|
-
const known = this.ids.get(config.id);
|
|
119
|
-
let session = known ? await agent.loadSession(known, this.cwd, signal) : undefined;
|
|
120
|
-
const fresh = !session;
|
|
121
|
-
if (!session) {
|
|
122
|
-
session = await agent.newSession(this.cwd, signal);
|
|
123
|
-
for (const [option, value] of Object.entries(config.options ?? {})) {
|
|
124
|
-
await session.select(option, value, signal).catch(() => undefined);
|
|
125
|
-
}
|
|
126
|
-
this.ids.set(config.id, session.id);
|
|
127
|
-
this.save({ agent: config.id, session: session.id });
|
|
128
|
-
}
|
|
129
|
-
this.prepare(config, session);
|
|
130
|
-
return { session, fresh, images: !!agent.initialized?.agentCapabilities?.promptCapabilities?.image, dirs: AgentBindings.dirs(this.cwd) };
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
static dirs(cwd: string): string[] {
|
|
134
|
-
try {
|
|
135
|
-
const real = realpathSync(cwd);
|
|
136
|
-
return real === cwd ? [cwd] : [cwd, real];
|
|
137
|
-
} catch {
|
|
138
|
-
return [cwd];
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/** Ta works in a remote directory (`ssh://`) through a directory of its own for pi: `<agent directory>/remote`. */
|
|
143
|
-
static isRemote(cwd: string): boolean {
|
|
144
|
-
const agentDir = process.env.TA_CODING_AGENT_DIR ?? join(homedir(), '.ta', 'agent');
|
|
145
|
-
return cwd.startsWith(join(agentDir, 'remote') + sep);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'bun:test';
|
|
2
|
-
import { mkdtempSync, readFileSync } from 'node:fs';
|
|
3
|
-
import { tmpdir } from 'node:os';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import { AgentCatalog, ModelCache } from './agent-catalog';
|
|
6
|
-
|
|
7
|
-
describe('AgentCatalog', () => {
|
|
8
|
-
it('offers the built-in agents whose programs are installed', () => {
|
|
9
|
-
const installed = new Set(['codebuddy', 'codex']);
|
|
10
|
-
const agents = AgentCatalog.agents(undefined, program => (installed.has(program) ? program : undefined));
|
|
11
|
-
expect(agents.map(agent => [agent.id, agent.command, agent.args[0]])).toEqual([
|
|
12
|
-
['codebuddy-code', 'codebuddy', '--acp'],
|
|
13
|
-
['codex', 'npx', '-y'],
|
|
14
|
-
]);
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('takes the settings: an agent turned off, one changed, and one of the user', () => {
|
|
18
|
-
const agents = AgentCatalog.agents(
|
|
19
|
-
{
|
|
20
|
-
'codebuddy-code': false,
|
|
21
|
-
'claude-code': { permissions: 'ask' },
|
|
22
|
-
gemini: { name: 'Gemini', command: 'gemini', args: ['--experimental-acp'] },
|
|
23
|
-
broken: { name: 'No command' },
|
|
24
|
-
},
|
|
25
|
-
() => 'found',
|
|
26
|
-
);
|
|
27
|
-
const named = AgentCatalog.agents({ codex: { env: { CODEX_PATH: 'tcodex' } } }, () => undefined);
|
|
28
|
-
expect(named.map(agent => [agent.id, agent.env])).toEqual([['codex', { CODEX_PATH: 'tcodex' }]]);
|
|
29
|
-
// The settings add to the environment and the options of a built-in agent.
|
|
30
|
-
const [cbc] = AgentCatalog.agents({ 'codebuddy-code': { env: { X: '1' }, options: { mode: 'default' } } }, program =>
|
|
31
|
-
program === 'cbc' ? program : undefined,
|
|
32
|
-
);
|
|
33
|
-
expect([cbc.env, cbc.options, cbc.clientMeta]).toEqual([
|
|
34
|
-
{ CODEBUDDY_CODE_MODE_ENABLED: '1', X: '1' },
|
|
35
|
-
{ mode: 'default' },
|
|
36
|
-
{ 'codebuddy.ai': { mainAgentSupport: true, toolModeSupport: true } },
|
|
37
|
-
]);
|
|
38
|
-
expect(agents.map(agent => [agent.id, agent.name, agent.command, agent.permissions])).toEqual([
|
|
39
|
-
['claude-code', 'Claude Code', 'npx', 'ask'],
|
|
40
|
-
['codex', 'Codex', 'npx', undefined],
|
|
41
|
-
['gemini', 'Gemini', 'gemini', undefined],
|
|
42
|
-
]);
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
describe('ModelCache', () => {
|
|
47
|
-
it('keeps the models of each agent in a file, and says when they changed', () => {
|
|
48
|
-
const file = join(mkdtempSync(join(tmpdir(), 'ta-agents-cache-')), 'models.json');
|
|
49
|
-
const cache = new ModelCache(file);
|
|
50
|
-
const models = { models: [{ id: 'fast', name: 'Fast' }], reasoning: true };
|
|
51
|
-
expect(cache.set('fake', models)).toBe(true);
|
|
52
|
-
expect(cache.set('fake', models)).toBe(false);
|
|
53
|
-
expect(new ModelCache(file).get('fake')).toEqual(models);
|
|
54
|
-
expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ fake: models });
|
|
55
|
-
});
|
|
56
|
-
});
|