@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.
- package/extension/index.mjs +11 -1
- 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/agent-turn.spec.ts
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'bun:test';
|
|
2
|
-
import { AgentTurn } from './agent-turn';
|
|
3
|
-
|
|
4
|
-
describe('AgentTurn', () => {
|
|
5
|
-
it('tells of the files calls change as soon as they name them, once each, with their text before from a diff', () => {
|
|
6
|
-
const told: [string, (string | null)?][] = [];
|
|
7
|
-
const turn = new AgentTurn(false, undefined, (path, before) => told.push(before === undefined ? [path] : [path, before]));
|
|
8
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 'r', title: 'Read', kind: 'read', status: 'pending', rawInput: { file_path: '/w/read.txt' } });
|
|
9
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 'e', title: 'Edit', kind: 'edit', status: 'pending', rawInput: null });
|
|
10
|
-
expect(told).toEqual([]);
|
|
11
|
-
turn.update({ sessionUpdate: 'tool_call_update', toolCallId: 'e', status: 'pending', rawInput: { file_path: '/w/a.txt' } });
|
|
12
|
-
turn.update({ sessionUpdate: 'tool_call_update', toolCallId: 'e', status: 'completed', locations: [{ path: '/w/a.txt' }] });
|
|
13
|
-
turn.update({
|
|
14
|
-
sessionUpdate: 'tool_call',
|
|
15
|
-
toolCallId: 'w',
|
|
16
|
-
title: 'Write',
|
|
17
|
-
kind: 'edit',
|
|
18
|
-
status: 'pending',
|
|
19
|
-
content: [
|
|
20
|
-
{ type: 'diff', path: '/w/new.txt', oldText: null, newText: 'x' },
|
|
21
|
-
{ type: 'diff', path: '/w/old.txt', oldText: 'before', newText: 'after' },
|
|
22
|
-
],
|
|
23
|
-
});
|
|
24
|
-
expect(told).toEqual([['/w/a.txt'], ['/w/new.txt', null], ['/w/old.txt', 'before']]);
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
it('queues text and thinking, joined while they go on, and the end', async () => {
|
|
28
|
-
const turn = new AgentTurn();
|
|
29
|
-
turn.update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'hm' } });
|
|
30
|
-
turn.update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Hel' } });
|
|
31
|
-
turn.update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'lo' } });
|
|
32
|
-
turn.update({
|
|
33
|
-
sessionUpdate: 'plan',
|
|
34
|
-
entries: [
|
|
35
|
-
{ content: 'Read', status: 'completed' },
|
|
36
|
-
{ content: 'Fix', status: 'pending' },
|
|
37
|
-
],
|
|
38
|
-
});
|
|
39
|
-
turn.end('end_turn');
|
|
40
|
-
turn.update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'late' } });
|
|
41
|
-
const items = [];
|
|
42
|
-
for (let item = await turn.next(); item; item = turn.peek() ? await turn.next() : undefined) {
|
|
43
|
-
items.push(item);
|
|
44
|
-
}
|
|
45
|
-
expect(items).toEqual([
|
|
46
|
-
{ type: 'thinking', text: 'hm' },
|
|
47
|
-
{ type: 'text', text: 'Hello' },
|
|
48
|
-
{ type: 'thinking', text: '- [x] Read\n- [ ] Fix\n' },
|
|
49
|
-
{ type: 'end', reason: 'end_turn' },
|
|
50
|
-
]);
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
it('follows a tool call through its updates to its output', async () => {
|
|
54
|
-
const turn = new AgentTurn();
|
|
55
|
-
turn.update({
|
|
56
|
-
sessionUpdate: 'tool_call',
|
|
57
|
-
toolCallId: 't',
|
|
58
|
-
title: 'Bash',
|
|
59
|
-
kind: 'other',
|
|
60
|
-
status: 'in_progress',
|
|
61
|
-
rawInput: {},
|
|
62
|
-
_meta: { 'x.ai/toolName': 'Bash' },
|
|
63
|
-
});
|
|
64
|
-
turn.update({ sessionUpdate: 'tool_call_update', toolCallId: 't', content: [{ type: 'content', content: { type: 'text', text: '{"command": "l' } }] });
|
|
65
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 't', title: '`ls`', kind: 'execute', status: 'pending', rawInput: { command: 'ls' } });
|
|
66
|
-
expect(turn.tools.get('t')).toMatchObject({ title: '`ls`', kind: 'execute', name: 'Bash', input: { command: 'ls' }, done: false });
|
|
67
|
-
const done = turn.waitTool('t');
|
|
68
|
-
turn.update({ sessionUpdate: 'tool_call_update', toolCallId: 't', status: 'completed', rawOutput: { type: 'text', text: 'a\nb' } });
|
|
69
|
-
expect(await done).toMatchObject({ status: 'completed', output: 'a\nb', done: true });
|
|
70
|
-
expect(await turn.next()).toEqual({ type: 'tool', id: 't' });
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
it('takes the arguments of a call as complete once it is quiet, or the agent says something else', async () => {
|
|
74
|
-
const turn = new AgentTurn();
|
|
75
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 't', title: 'Read', kind: 'read', status: 'pending' });
|
|
76
|
-
const started = Date.now();
|
|
77
|
-
await turn.settle('t', 60);
|
|
78
|
-
expect(Date.now() - started).toBeGreaterThanOrEqual(50);
|
|
79
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 'u', title: 'Bash', kind: 'other', status: 'in_progress', rawInput: {} });
|
|
80
|
-
const settling = turn.settle('u', 5000);
|
|
81
|
-
turn.update({ sessionUpdate: 'tool_call_update', toolCallId: 'u', rawInput: { command: 'l' } });
|
|
82
|
-
expect(turn.tools.get('u')?.complete).toBe(false);
|
|
83
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 'u', title: '`ls`', kind: 'execute', status: 'pending', rawInput: { command: 'ls' } });
|
|
84
|
-
await settling;
|
|
85
|
-
expect(turn.tools.get('u')?.complete).toBe(true);
|
|
86
|
-
turn.update({
|
|
87
|
-
sessionUpdate: 'tool_call',
|
|
88
|
-
toolCallId: 'v',
|
|
89
|
-
title: 'Read',
|
|
90
|
-
kind: 'other',
|
|
91
|
-
status: 'in_progress',
|
|
92
|
-
_meta: { 'x/toolArgumentsComplete': true },
|
|
93
|
-
});
|
|
94
|
-
expect(turn.tools.get('v')?.complete).toBe(true);
|
|
95
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 'w', title: 'Grep', kind: 'search', status: 'in_progress' });
|
|
96
|
-
const moved = turn.settle('w', 5000);
|
|
97
|
-
turn.update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'meanwhile' } });
|
|
98
|
-
await moved;
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
it('takes the output of a terminal the agent reports in pieces, and its name of the tool', async () => {
|
|
102
|
-
const turn = new AgentTurn();
|
|
103
|
-
turn.update({ sessionUpdate: 'tool_call', toolCallId: 'x', name: 'exec_command', title: 'List', kind: 'execute', status: 'in_progress' } as never);
|
|
104
|
-
turn.update({ sessionUpdate: 'tool_call_update', toolCallId: 'x', _meta: { terminal_output_delta: { data: 'a\n' } } });
|
|
105
|
-
turn.update({
|
|
106
|
-
sessionUpdate: 'tool_call_update',
|
|
107
|
-
toolCallId: 'x',
|
|
108
|
-
status: 'completed',
|
|
109
|
-
rawOutput: { exit_code: 0 },
|
|
110
|
-
_meta: { terminal_output_delta: { data: 'b\n' } },
|
|
111
|
-
});
|
|
112
|
-
expect(turn.tools.get('x')).toMatchObject({ name: 'exec_command', output: 'a\nb\n' });
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
it('shows a diff and reads usage from what the agent reports', () => {
|
|
116
|
-
expect(AgentTurn.output({ toolCallId: 'e', content: [{ type: 'diff', path: 'a.ts', oldText: 'a\nb\nc', newText: 'a\nB\nc' }] })).toBe('a.ts\n- b\n+ B');
|
|
117
|
-
expect(AgentTurn.raw({ exitCode: 0 })).toBe('{\n "exitCode": 0\n}');
|
|
118
|
-
const turn = new AgentTurn();
|
|
119
|
-
turn.update({ sessionUpdate: 'usage_update', used: 10, size: 100, _meta: { usage: { input_tokens: 7, output_tokens: 3 } } });
|
|
120
|
-
expect(turn.usage).toEqual({ used: 10, size: 100, input: 7, output: 3, cacheRead: undefined });
|
|
121
|
-
});
|
|
122
|
-
});
|
package/src/agent-turn.ts
DELETED
|
@@ -1,400 +0,0 @@
|
|
|
1
|
-
import { Acp } from './acp-protocol';
|
|
2
|
-
|
|
3
|
-
/** What a turn of the agent produced, in order. */
|
|
4
|
-
export type TurnItem =
|
|
5
|
-
| { type: 'text'; text: string }
|
|
6
|
-
| { type: 'thinking'; text: string }
|
|
7
|
-
| { type: 'tool'; id: string }
|
|
8
|
-
| { type: 'end'; reason: Acp.StopReason }
|
|
9
|
-
| { type: 'error'; message: string; code?: number };
|
|
10
|
-
|
|
11
|
-
/** A tool call the agent made with its own tools, as its updates describe it so far. */
|
|
12
|
-
export interface ToolRun {
|
|
13
|
-
id: string;
|
|
14
|
-
title: string;
|
|
15
|
-
kind: Acp.ToolKind;
|
|
16
|
-
/** The agent's name of the tool, when it says. */
|
|
17
|
-
name?: string;
|
|
18
|
-
input: Record<string, unknown>;
|
|
19
|
-
locations: string[];
|
|
20
|
-
status: Acp.ToolStatus;
|
|
21
|
-
output: string;
|
|
22
|
-
done: boolean;
|
|
23
|
-
/** Its arguments are all there: the agent said so, or announced the call with them before running it. */
|
|
24
|
-
complete: boolean;
|
|
25
|
-
/** What its terminal printed, as some agents report it (Codex: `_meta.terminal_output_delta`). */
|
|
26
|
-
terminal: string;
|
|
27
|
-
/** When the agent last said something about it, to know when its arguments are complete. */
|
|
28
|
-
updatedAt: number;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** The usage of the turn as the agent reported it last. */
|
|
32
|
-
export interface TurnUsage {
|
|
33
|
-
input?: number;
|
|
34
|
-
output?: number;
|
|
35
|
-
cacheRead?: number;
|
|
36
|
-
/** Tokens in the context, and the size of the window. */
|
|
37
|
-
used?: number;
|
|
38
|
-
size?: number;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const OUTPUT_CHARS = 8000;
|
|
42
|
-
/** The kinds of calls that change the files they name. */
|
|
43
|
-
const WRITING_KINDS = new Set<Acp.ToolKind>(['edit', 'delete', 'move']);
|
|
44
|
-
/** Where calls name the file they change, in the arguments of agents' tools. */
|
|
45
|
-
const PATH_KEYS = ['file_path', 'path', 'filePath', 'notebook_path', 'destination'];
|
|
46
|
-
|
|
47
|
-
/** A file a call of the agent is about to change, or changed: `before`, its text before, when the agent said (an ACP diff; null: there was none). */
|
|
48
|
-
export type WriteListener = (path: string, before?: string | null) => void;
|
|
49
|
-
|
|
50
|
-
function str(value: unknown): string | undefined {
|
|
51
|
-
return typeof value === 'string' && value.trim() ? value : undefined;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function num(value: unknown): number | undefined {
|
|
55
|
-
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* One prompt of an agent, from `session/prompt` to its answer, or a turn the agent started on its own
|
|
60
|
-
* (`unsolicited`, after a background task). Its updates are queued until the provider streams them,
|
|
61
|
-
* which may be over several of pi's assistant messages: each tool call ends one.
|
|
62
|
-
*/
|
|
63
|
-
export class AgentTurn {
|
|
64
|
-
readonly tools = new Map<string, ToolRun>();
|
|
65
|
-
usage: TurnUsage = {};
|
|
66
|
-
ended = false;
|
|
67
|
-
/** The agent said or did something in the turn: text, thinking or a tool call. */
|
|
68
|
-
produced = false;
|
|
69
|
-
|
|
70
|
-
protected readonly items: TurnItem[] = [];
|
|
71
|
-
protected readonly listeners = new Set<() => void>();
|
|
72
|
-
/** Each file of each call, told once. */
|
|
73
|
-
protected readonly written = new Set<string>();
|
|
74
|
-
|
|
75
|
-
/** `command`: the slash command the prompt is, if it is one; `onWrite` hears of the files its calls change. */
|
|
76
|
-
constructor(
|
|
77
|
-
readonly unsolicited = false,
|
|
78
|
-
readonly command?: string,
|
|
79
|
-
protected readonly onWrite?: WriteListener,
|
|
80
|
-
) {}
|
|
81
|
-
|
|
82
|
-
update(update: Acp.SessionUpdate): void {
|
|
83
|
-
if (this.ended) {
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
switch (update.sessionUpdate) {
|
|
87
|
-
case 'agent_message_chunk':
|
|
88
|
-
this.pushText('text', Acp.text((update as { content: Acp.ContentBlock }).content));
|
|
89
|
-
break;
|
|
90
|
-
case 'agent_thought_chunk':
|
|
91
|
-
this.pushText('thinking', Acp.text((update as { content: Acp.ContentBlock }).content));
|
|
92
|
-
break;
|
|
93
|
-
case 'tool_call':
|
|
94
|
-
case 'tool_call_update':
|
|
95
|
-
this.tool(update as Acp.ToolCallUpdate);
|
|
96
|
-
break;
|
|
97
|
-
case 'plan':
|
|
98
|
-
this.pushText('thinking', AgentTurn.plan((update as { entries: Acp.PlanEntry[] }).entries));
|
|
99
|
-
break;
|
|
100
|
-
case 'usage_update':
|
|
101
|
-
this.measure(update as { used?: number; size?: number; _meta?: Record<string, unknown> });
|
|
102
|
-
break;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
end(reason: Acp.StopReason): void {
|
|
107
|
-
this.finish({ type: 'end', reason });
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
fail(message: string, code?: number): void {
|
|
111
|
-
this.finish({ type: 'error', message, code });
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** The next item, once there is one; `undefined` when `signal` aborts first. */
|
|
115
|
-
async next(signal?: AbortSignal): Promise<TurnItem | undefined> {
|
|
116
|
-
while (!this.items.length) {
|
|
117
|
-
if (signal?.aborted) {
|
|
118
|
-
return undefined;
|
|
119
|
-
}
|
|
120
|
-
await this.changed(signal);
|
|
121
|
-
}
|
|
122
|
-
return this.items.shift();
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/** Resolves once the agent answered the prompt, or `timeoutMs` passed. */
|
|
126
|
-
async whenEnded(timeoutMs: number): Promise<void> {
|
|
127
|
-
const until = Date.now() + timeoutMs;
|
|
128
|
-
while (!this.ended && Date.now() < until) {
|
|
129
|
-
await this.changed(undefined, until - Date.now());
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** The next item if it is already there. */
|
|
134
|
-
peek(): TurnItem | undefined {
|
|
135
|
-
return this.items[0];
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
shift(): TurnItem | undefined {
|
|
139
|
-
return this.items.shift();
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Waits until the call's arguments are complete (see {@link ToolRun.complete}), the agent went on to
|
|
144
|
-
* say something else, or nothing was said about the call for `quietMs`.
|
|
145
|
-
*/
|
|
146
|
-
async settle(id: string, quietMs: number, signal?: AbortSignal): Promise<void> {
|
|
147
|
-
for (;;) {
|
|
148
|
-
const run = this.tools.get(id);
|
|
149
|
-
if (!run || run.complete || this.ended || signal?.aborted || this.items.some(item => item.type !== 'tool')) {
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
const left = run.updatedAt + quietMs - Date.now();
|
|
153
|
-
if (left <= 0) {
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
await this.changed(signal, left);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** The call once it ended, or the turn did. */
|
|
161
|
-
async waitTool(id: string, signal?: AbortSignal): Promise<ToolRun | undefined> {
|
|
162
|
-
for (;;) {
|
|
163
|
-
const run = this.tools.get(id);
|
|
164
|
-
if (!run || run.done || this.ended || signal?.aborted) {
|
|
165
|
-
return run;
|
|
166
|
-
}
|
|
167
|
-
await this.changed(signal);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
protected pushText(type: 'text' | 'thinking', text: string): void {
|
|
172
|
-
if (!text) {
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
this.produced = true;
|
|
176
|
-
const last = this.items[this.items.length - 1];
|
|
177
|
-
if (last?.type === type) {
|
|
178
|
-
last.text += text;
|
|
179
|
-
} else {
|
|
180
|
-
this.items.push({ type, text });
|
|
181
|
-
}
|
|
182
|
-
this.notify();
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
protected tool(update: Acp.ToolCallUpdate): void {
|
|
186
|
-
let run = this.tools.get(update.toolCallId);
|
|
187
|
-
if (!run) {
|
|
188
|
-
run = {
|
|
189
|
-
id: update.toolCallId,
|
|
190
|
-
title: '',
|
|
191
|
-
kind: 'other',
|
|
192
|
-
input: {},
|
|
193
|
-
locations: [],
|
|
194
|
-
status: 'pending',
|
|
195
|
-
output: '',
|
|
196
|
-
done: false,
|
|
197
|
-
complete: false,
|
|
198
|
-
terminal: '',
|
|
199
|
-
updatedAt: Date.now(),
|
|
200
|
-
};
|
|
201
|
-
this.tools.set(run.id, run);
|
|
202
|
-
this.items.push({ type: 'tool', id: run.id });
|
|
203
|
-
this.produced = true;
|
|
204
|
-
}
|
|
205
|
-
run.title = str(update.title) ?? run.title;
|
|
206
|
-
run.kind = update.kind ?? run.kind;
|
|
207
|
-
run.name = AgentTurn.toolName(update._meta) ?? str((update as { name?: unknown }).name) ?? run.name;
|
|
208
|
-
run.terminal += AgentTurn.terminalOutput(update._meta);
|
|
209
|
-
if (update.rawInput && typeof update.rawInput === 'object' && Object.keys(update.rawInput).length) {
|
|
210
|
-
run.input = update.rawInput as Record<string, unknown>;
|
|
211
|
-
}
|
|
212
|
-
if (update.locations?.length) {
|
|
213
|
-
run.locations = update.locations.map(location => location.path);
|
|
214
|
-
}
|
|
215
|
-
if (update.status) {
|
|
216
|
-
run.status = update.status;
|
|
217
|
-
}
|
|
218
|
-
// An agent that streams the arguments first runs the call (in_progress) with none yet, then says
|
|
219
|
-
// when they are complete; one that does not announces the call (pending) with them.
|
|
220
|
-
run.complete ||= AgentTurn.argumentsComplete(update._meta) || (Object.keys(run.input).length > 0 && update.status === 'pending');
|
|
221
|
-
if (run.status === 'completed' || run.status === 'failed') {
|
|
222
|
-
run.done = true;
|
|
223
|
-
run.complete = true;
|
|
224
|
-
// Content before the end may be the arguments being streamed (CodeBuddy Code), not output.
|
|
225
|
-
run.output = AgentTurn.contentText(update.content ?? []) || run.terminal || AgentTurn.raw(update.rawOutput);
|
|
226
|
-
run.output = AgentTurn.clip(run.output);
|
|
227
|
-
}
|
|
228
|
-
run.updatedAt = Date.now();
|
|
229
|
-
this.tellWrites(run, update.content ?? []);
|
|
230
|
-
this.notify();
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Tells `onWrite` of the files a call changes as soon as it names them, before the agent runs it if it
|
|
235
|
-
* can (the agent runs it on its own), with their text before when the agent sends a diff.
|
|
236
|
-
*/
|
|
237
|
-
protected tellWrites(run: ToolRun, content: Acp.ToolCallContent[]): void {
|
|
238
|
-
if (!this.onWrite) {
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
const tell = (path: string, before?: string | null) => {
|
|
242
|
-
const key = `${run.id}\0${path}`;
|
|
243
|
-
if (!this.written.has(key)) {
|
|
244
|
-
this.written.add(key);
|
|
245
|
-
this.onWrite?.(path, before);
|
|
246
|
-
}
|
|
247
|
-
};
|
|
248
|
-
for (const item of content) {
|
|
249
|
-
if (item.type === 'diff' && str(item.path)) {
|
|
250
|
-
tell(item.path, item.oldText ?? null);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
if (WRITING_KINDS.has(run.kind)) {
|
|
254
|
-
for (const path of [...run.locations, ...PATH_KEYS.map(key => str(run.input[key]))]) {
|
|
255
|
-
if (path) {
|
|
256
|
-
tell(path);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
protected measure(update: { used?: number; size?: number; _meta?: Record<string, unknown> }): void {
|
|
263
|
-
this.usage.used = num(update.used) ?? this.usage.used;
|
|
264
|
-
this.usage.size = num(update.size) ?? this.usage.size;
|
|
265
|
-
// Agents that report tokens put them in `_meta`, in the words of the API they call.
|
|
266
|
-
const tokens = update._meta?.usage as Record<string, unknown> | undefined;
|
|
267
|
-
if (tokens && typeof tokens === 'object') {
|
|
268
|
-
this.usage.input = num(tokens.prompt_tokens) ?? num(tokens.input_tokens) ?? this.usage.input;
|
|
269
|
-
this.usage.output = num(tokens.completion_tokens) ?? num(tokens.output_tokens) ?? this.usage.output;
|
|
270
|
-
const details = tokens.prompt_tokens_details as Record<string, unknown> | undefined;
|
|
271
|
-
this.usage.cacheRead =
|
|
272
|
-
num(tokens.prompt_cache_hit_tokens) ||
|
|
273
|
-
num(details?.cached_tokens) ||
|
|
274
|
-
num(tokens.cached_tokens) ||
|
|
275
|
-
num(tokens.cache_read_input_tokens) ||
|
|
276
|
-
this.usage.cacheRead;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
protected finish(item: TurnItem): void {
|
|
281
|
-
if (this.ended) {
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
this.ended = true;
|
|
285
|
-
this.items.push(item);
|
|
286
|
-
this.notify();
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
protected notify(): void {
|
|
290
|
-
for (const listener of [...this.listeners]) {
|
|
291
|
-
listener();
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
protected changed(signal?: AbortSignal, timeoutMs?: number): Promise<void> {
|
|
296
|
-
return new Promise<void>(resolve => {
|
|
297
|
-
const done = () => {
|
|
298
|
-
this.listeners.delete(done);
|
|
299
|
-
signal?.removeEventListener('abort', done);
|
|
300
|
-
if (timer) {
|
|
301
|
-
clearTimeout(timer);
|
|
302
|
-
}
|
|
303
|
-
resolve();
|
|
304
|
-
};
|
|
305
|
-
const timer = timeoutMs !== undefined ? setTimeout(done, timeoutMs) : undefined;
|
|
306
|
-
this.listeners.add(done);
|
|
307
|
-
signal?.addEventListener('abort', done, { once: true });
|
|
308
|
-
});
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
static plan(entries: Acp.PlanEntry[]): string {
|
|
312
|
-
const mark = { completed: 'x', in_progress: '~', pending: ' ' } as const;
|
|
313
|
-
return `${entries.map(entry => `- [${mark[entry.status] ?? ' '}] ${entry.content}`).join('\n')}\n`;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/** What a call returned: the content of its last update, else its raw output, as text. */
|
|
317
|
-
static output(update: Acp.ToolCallUpdate): string {
|
|
318
|
-
return AgentTurn.clip(AgentTurn.contentText(update.content ?? []) || AgentTurn.raw(update.rawOutput));
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
static clip(text: string): string {
|
|
322
|
-
return text.length > OUTPUT_CHARS ? `${text.slice(0, OUTPUT_CHARS)}\n…` : text;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
static terminalOutput(meta: Record<string, unknown> | undefined): string {
|
|
326
|
-
let text = '';
|
|
327
|
-
for (const [key, value] of Object.entries(meta ?? {})) {
|
|
328
|
-
const data = (value as { data?: unknown } | undefined)?.data;
|
|
329
|
-
if (/terminal_output/.test(key) && typeof data === 'string') {
|
|
330
|
-
text += data;
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
return text;
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
static contentText(content: Acp.ToolCallContent[]): string {
|
|
337
|
-
return content
|
|
338
|
-
.map(item => {
|
|
339
|
-
if (item.type === 'content') {
|
|
340
|
-
return Acp.text(item.content);
|
|
341
|
-
}
|
|
342
|
-
if (item.type === 'diff') {
|
|
343
|
-
return `${item.path}\n${AgentTurn.diff(item.oldText ?? '', item.newText)}`;
|
|
344
|
-
}
|
|
345
|
-
return '';
|
|
346
|
-
})
|
|
347
|
-
.filter(Boolean)
|
|
348
|
-
.join('\n');
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
static raw(value: unknown): string {
|
|
352
|
-
if (value === undefined || value === null) {
|
|
353
|
-
return '';
|
|
354
|
-
}
|
|
355
|
-
if (typeof value === 'string') {
|
|
356
|
-
return value;
|
|
357
|
-
}
|
|
358
|
-
const text = (value as { text?: unknown }).text;
|
|
359
|
-
if (typeof text === 'string') {
|
|
360
|
-
return text;
|
|
361
|
-
}
|
|
362
|
-
try {
|
|
363
|
-
return JSON.stringify(value, undefined, 2);
|
|
364
|
-
} catch {
|
|
365
|
-
return String(value);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/** The lines that differ, marked; enough to read what an edit did. */
|
|
370
|
-
static diff(before: string, after: string): string {
|
|
371
|
-
const old = before ? before.split('\n') : [];
|
|
372
|
-
const lines = after.split('\n');
|
|
373
|
-
let start = 0;
|
|
374
|
-
while (start < old.length && start < lines.length && old[start] === lines[start]) {
|
|
375
|
-
start++;
|
|
376
|
-
}
|
|
377
|
-
let end = 0;
|
|
378
|
-
while (end < old.length - start && end < lines.length - start && old[old.length - 1 - end] === lines[lines.length - 1 - end]) {
|
|
379
|
-
end++;
|
|
380
|
-
}
|
|
381
|
-
return [...old.slice(start, old.length - end).map(line => `- ${line}`), ...lines.slice(start, lines.length - end).map(line => `+ ${line}`)].join('\n');
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
static argumentsComplete(meta: Record<string, unknown> | undefined): boolean {
|
|
385
|
-
return Object.entries(meta ?? {}).some(([key, value]) => /toolArgumentsComplete$/.test(key) && value === true);
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
/** Agents name their own tool in `_meta`, under a key of their own (`<agent>/toolName`). */
|
|
389
|
-
static toolName(meta: Record<string, unknown> | undefined): string | undefined {
|
|
390
|
-
for (const [key, value] of Object.entries(meta ?? {})) {
|
|
391
|
-
if (/toolName$/i.test(key) && typeof value === 'string') {
|
|
392
|
-
return value;
|
|
393
|
-
}
|
|
394
|
-
if (value && typeof value === 'object' && typeof (value as { toolName?: unknown }).toolName === 'string') {
|
|
395
|
-
return (value as { toolName: string }).toolName;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
return undefined;
|
|
399
|
-
}
|
|
400
|
-
}
|