@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.
@@ -1,176 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { delimiter, dirname, join } from 'node:path';
4
-
5
- /** An agent to offer: pi's provider `id`, and how to start it. */
6
- export interface AgentConfig {
7
- id: string;
8
- name: string;
9
- command: string;
10
- args: string[];
11
- env?: Record<string, string>;
12
- /** What signs the user in, to run in a terminal. */
13
- login?: string;
14
- /** `ask` shows the agent's permission requests to the user; by default they are allowed, as pi does not ask. */
15
- permissions?: 'allow' | 'ask';
16
- /** `_meta` of the client's capabilities in `initialize`: what the client opts in to, in the agent's own words. */
17
- clientMeta?: Record<string, unknown>;
18
- /** Settings of a new session, by the id or category of the agent's option (`mode`, `model`...). */
19
- options?: Record<string, string>;
20
- }
21
-
22
- /** An agent of `agents` in pi's settings.json; `false` turns a built-in one off. */
23
- export type AgentSetting = false | Partial<AgentConfig>;
24
-
25
- interface Preset extends AgentConfig {
26
- /** Offered when one of these programs is installed; the first found is the command when `command` is one of them. */
27
- programs: string[];
28
- }
29
-
30
- /**
31
- * The agents that come with the package. CodeBuddy Code speaks ACP itself; Claude Code and Codex
32
- * through the adapters of the ACP project, which use the login of the user's own CLI; npx fetches them
33
- * the first time.
34
- */
35
- const PRESETS: readonly Preset[] = [
36
- {
37
- id: 'codebuddy-code',
38
- name: 'CodeBuddy Code',
39
- command: 'cbc',
40
- args: ['--acp'],
41
- programs: ['cbc', 'codebuddy'],
42
- login: 'cbc',
43
- // As in its own terminal: the client takes its main-agent modes, PTC (code mode) included, which
44
- // ACP clients that do not say so never get; full access, as pi does not ask.
45
- env: { CODEBUDDY_CODE_MODE_ENABLED: '1' },
46
- clientMeta: { 'codebuddy.ai': { mainAgentSupport: true, toolModeSupport: true } },
47
- options: { mode: 'fullAccess' },
48
- },
49
- {
50
- id: 'claude-code',
51
- name: 'Claude Code',
52
- command: 'npx',
53
- args: ['-y', '@agentclientprotocol/claude-agent-acp@0.106.0'],
54
- programs: ['claude'],
55
- login: 'claude',
56
- },
57
- { id: 'codex', name: 'Codex', command: 'npx', args: ['-y', '@agentclientprotocol/codex-acp@2.6.0'], programs: ['codex'], login: 'codex login' },
58
- ];
59
-
60
- /** A model of an agent, as it listed it last. */
61
- export interface AgentModel {
62
- id: string;
63
- name: string;
64
- }
65
-
66
- export interface AgentModels {
67
- models: AgentModel[];
68
- reasoning: boolean;
69
- contextWindow?: number;
70
- }
71
-
72
- export namespace AgentCatalog {
73
- /** The model that leaves the choice to the agent: what the user set up in it. */
74
- export const DEFAULT_MODEL = 'default';
75
-
76
- /** The built-in agents that are installed and not turned off, then those of the settings. */
77
- export function agents(settings: Record<string, AgentSetting> | undefined, find: (program: string) => string | undefined = Programs.find): AgentConfig[] {
78
- const configured = settings && typeof settings === 'object' ? settings : {};
79
- const result: AgentConfig[] = [];
80
- for (const preset of PRESETS) {
81
- const setting = configured[preset.id];
82
- if (setting === false) {
83
- continue;
84
- }
85
- const found = preset.programs.find(program => find(program));
86
- // Named in the settings, it is wanted: its program may be another one (`env`, `command`).
87
- if (!found && !setting) {
88
- continue;
89
- }
90
- const { programs, ...config } = preset;
91
- const command = programs.includes(config.command) && found ? found : config.command;
92
- const own = setting || {};
93
- result.push({
94
- ...config,
95
- command,
96
- ...own,
97
- id: preset.id,
98
- env: config.env || own.env ? { ...config.env, ...own.env } : undefined,
99
- options: config.options || own.options ? { ...config.options, ...own.options } : undefined,
100
- });
101
- }
102
- for (const [id, setting] of Object.entries(configured)) {
103
- if (setting && typeof setting === 'object' && !PRESETS.some(preset => preset.id === id) && typeof setting.command === 'string') {
104
- result.push({ name: id, args: [], ...setting, id, command: setting.command });
105
- }
106
- }
107
- return result;
108
- }
109
- }
110
-
111
- export namespace Programs {
112
- /** The name of `program` if it is on the PATH; only `stat`s, nothing runs. */
113
- export function find(program: string): string | undefined {
114
- const extensions = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];
115
- for (const dir of (process.env.PATH ?? '').split(delimiter)) {
116
- for (const extension of extensions) {
117
- if (dir && isFile(join(dir, program + extension))) {
118
- return program;
119
- }
120
- }
121
- }
122
- return undefined;
123
- }
124
-
125
- function isFile(path: string): boolean {
126
- try {
127
- return statSync(path).isFile();
128
- } catch {
129
- return false;
130
- }
131
- }
132
- }
133
-
134
- /** The models each agent listed last, so that pi offers them before the agent runs again. */
135
- export class ModelCache {
136
- protected entries?: Record<string, AgentModels>;
137
-
138
- constructor(readonly file = ModelCache.defaultFile()) {}
139
-
140
- get(id: string): AgentModels | undefined {
141
- return this.read()[id];
142
- }
143
-
144
- /** Keeps `models`; false when they were known. */
145
- set(id: string, models: AgentModels): boolean {
146
- const entries = this.read();
147
- if (JSON.stringify(entries[id]) === JSON.stringify(models)) {
148
- return false;
149
- }
150
- entries[id] = models;
151
- try {
152
- mkdirSync(dirname(this.file), { recursive: true });
153
- const temp = `${this.file}.${process.pid}.tmp`;
154
- writeFileSync(temp, JSON.stringify(entries, undefined, 2));
155
- renameSync(temp, this.file);
156
- } catch {
157
- // A cache: without it the agent lists its models again next time.
158
- }
159
- return true;
160
- }
161
-
162
- protected read(): Record<string, AgentModels> {
163
- if (!this.entries) {
164
- try {
165
- this.entries = existsSync(this.file) ? JSON.parse(readFileSync(this.file, 'utf8')) : {};
166
- } catch {
167
- this.entries = {};
168
- }
169
- }
170
- return this.entries ?? {};
171
- }
172
-
173
- static defaultFile(): string {
174
- return join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'ta-agents', 'models.json');
175
- }
176
- }
@@ -1,44 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { ACTIVITY_TEXT, AgentPrompt } from './agent-prompt';
3
- import type { Message } from './pi-types';
4
-
5
- const at = 0;
6
- const answer = (text: string) => ({ role: 'assistant', content: [{ type: 'text', text }] }) as unknown as Message;
7
-
8
- describe('AgentPrompt', () => {
9
- const messages: Message[] = [
10
- { role: 'system', content: 'pi prompt' } as Message,
11
- { role: 'user', content: 'first', timestamp: at },
12
- answer('ok'),
13
- { role: 'user', content: 'second', timestamp: at },
14
- { role: 'system', content: 'tools changed' } as Message,
15
- {
16
- role: 'user',
17
- content: [
18
- { type: 'text', text: 'third' },
19
- { type: 'image', data: 'AA', mimeType: 'image/png' },
20
- ],
21
- timestamp: at,
22
- },
23
- { role: 'user', content: ACTIVITY_TEXT, timestamp: at },
24
- ];
25
-
26
- it('sends what the user said since the last answer, images when the agent takes them', () => {
27
- const pending = AgentPrompt.pending(messages);
28
- expect(pending.map(AgentPrompt.text)).toEqual(['second', 'third']);
29
- expect(AgentPrompt.blocks(pending, true)).toEqual([
30
- { type: 'text', text: 'second' },
31
- { type: 'text', text: 'third' },
32
- { type: 'image', data: 'AA', mimeType: 'image/png' },
33
- ]);
34
- expect(AgentPrompt.blocks(pending, false)[2]).toEqual({ type: 'text', text: '[An image the agent cannot take was left out]' });
35
- expect(AgentPrompt.pending([...messages, answer('done')])).toEqual([]);
36
- });
37
-
38
- it('tells an agent that joins what was said before', () => {
39
- const transcript = AgentPrompt.transcript(messages, 2);
40
- expect(transcript).toContain('User: first\n\nAssistant: ok');
41
- expect(transcript).not.toContain('second');
42
- expect(AgentPrompt.transcript(messages.slice(0, 2), 1)).toBeUndefined();
43
- });
44
- });
@@ -1,83 +0,0 @@
1
- import type { Acp } from './acp-protocol';
2
- import type { Message } from './pi-types';
3
-
4
- /** The text of the message pi adds to start a turn when the agent began one on its own; not sent to the agent. */
5
- export const ACTIVITY_TEXT = '[The agent continued on its own]';
6
-
7
- const TRANSCRIPT_CHARS = 30_000;
8
-
9
- /** What of pi's transcript goes to an agent, which keeps its own history: only what the user said since it last answered. */
10
- export namespace AgentPrompt {
11
- /** The user messages at the end of the transcript, after the last answer or tool result. */
12
- export function pending(messages: readonly Message[]): Message[] {
13
- const result: Message[] = [];
14
- for (let index = messages.length - 1; index >= 0; index--) {
15
- const message = messages[index];
16
- if (message.role === 'system') {
17
- continue;
18
- }
19
- if (message.role !== 'user') {
20
- break;
21
- }
22
- if (text(message) !== ACTIVITY_TEXT) {
23
- result.unshift(message);
24
- }
25
- }
26
- return result;
27
- }
28
-
29
- /** The messages as a prompt; images when the agent takes them. */
30
- export function blocks(messages: readonly Message[], images: boolean): Acp.ContentBlock[] {
31
- const result: Acp.ContentBlock[] = [];
32
- for (const message of messages) {
33
- if (message.role !== 'user') {
34
- continue;
35
- }
36
- if (typeof message.content === 'string') {
37
- result.push({ type: 'text', text: message.content });
38
- continue;
39
- }
40
- for (const part of message.content) {
41
- if (part.type === 'text') {
42
- result.push({ type: 'text', text: part.text });
43
- } else if (images) {
44
- result.push({ type: 'image', data: part.data, mimeType: part.mimeType });
45
- } else {
46
- result.push({ type: 'text', text: '[An image the agent cannot take was left out]' });
47
- }
48
- }
49
- }
50
- return result;
51
- }
52
-
53
- /**
54
- * The conversation before `pending`, for an agent that joins it: a session of its own starts empty,
55
- * and the user may have talked with another model first. Text only, the latest part.
56
- */
57
- export function transcript(messages: readonly Message[], pendingCount: number): string | undefined {
58
- const earlier = messages.filter(message => (message.role === 'user' || message.role === 'assistant') && text(message) !== ACTIVITY_TEXT);
59
- const lines: string[] = [];
60
- for (const message of earlier.slice(0, Math.max(0, earlier.length - pendingCount))) {
61
- const content = text(message).trim();
62
- if (content) {
63
- lines.push(`${message.role === 'user' ? 'User' : 'Assistant'}: ${content}`);
64
- }
65
- }
66
- if (!lines.length) {
67
- return undefined;
68
- }
69
- const body = lines.join('\n\n');
70
- const kept = body.length > TRANSCRIPT_CHARS ? `…${body.slice(-TRANSCRIPT_CHARS)}` : body;
71
- return `<earlier_conversation>\nThe user talked with another assistant before you joined; this is what was said:\n\n${kept}\n</earlier_conversation>`;
72
- }
73
-
74
- export function text(message: Message): string {
75
- if (message.role === 'user' || message.role === 'system') {
76
- return typeof message.content === 'string' ? message.content : message.content.map(part => (part.type === 'text' ? part.text : '')).join('');
77
- }
78
- if (message.role === 'assistant') {
79
- return message.content.map(part => (part.type === 'text' ? part.text : '')).join('');
80
- }
81
- return '';
82
- }
83
- }
@@ -1,45 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { AgentSession } from './agent-session';
3
-
4
- /** A host whose prompts are answered only when the test says. */
5
- function host() {
6
- const answers: (() => void)[] = [];
7
- return {
8
- answers,
9
- request: <T>() => new Promise<T>(resolve => answers.push(() => resolve({ stopReason: 'end_turn' } as T))),
10
- notify: () => undefined,
11
- };
12
- }
13
-
14
- const phase = (value: string, request: string) => ({
15
- sessionUpdate: 'session_info_update',
16
- _meta: { 'x/agentPhase': { phase: value }, 'x/requestId': request },
17
- });
18
-
19
- describe('AgentSession', () => {
20
- it('ends a turn when the agent goes back to idle, but not on what it still says of an earlier request', async () => {
21
- const session = new AgentSession(host(), 's', {});
22
- const first = session.prompt([{ type: 'text', text: '/compact' }]);
23
- session.update(phase('model_streaming', 'a'));
24
- session.update(phase('idle', 'a'));
25
- expect(first.ended).toBe(true);
26
- session.finished(first);
27
- const second = session.prompt([{ type: 'text', text: '/cost' }]);
28
- // The compaction goes on after it said idle.
29
- session.update(phase('model_streaming', 'a'));
30
- session.update(phase('idle', 'a'));
31
- expect(second.ended).toBe(false);
32
- session.update(phase('model_streaming', 'b'));
33
- session.update(phase('idle', 'b'));
34
- expect(second.ended).toBe(true);
35
- });
36
-
37
- it('names the session once, when the agent gives a title', () => {
38
- const titles: string[] = [];
39
- const session = new AgentSession(host(), 's', {});
40
- session.callbacks = { ...session.callbacks, title: title => titles.push(title) };
41
- session.update({ sessionUpdate: 'session_info_update', title: 'Fix the build' });
42
- session.update({ sessionUpdate: 'session_info_update', title: 'Fix the build' });
43
- expect(titles).toEqual(['Fix the build']);
44
- });
45
- });
@@ -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
- }