@celljs/ta-agents 0.0.0-stage → 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.
@@ -0,0 +1,1756 @@
1
+ // src/extension.ts
2
+ import { readFileSync as readFileSync2 } from "node:fs";
3
+ import { homedir as homedir3 } from "node:os";
4
+ import { join as join3, resolve } from "node:path";
5
+
6
+ // src/acp-protocol.ts
7
+ var Acp;
8
+ ((Acp) => {
9
+ Acp.PROTOCOL_VERSION = 1;
10
+ Acp.AUTH_REQUIRED = -32000;
11
+ function text(block) {
12
+ if (!block) {
13
+ return "";
14
+ }
15
+ switch (block.type) {
16
+ case "text":
17
+ return block.text ?? "";
18
+ case "resource":
19
+ return block.resource?.text ?? block.resource?.uri ?? "";
20
+ case "resource_link":
21
+ return block.uri ?? block.name ?? "";
22
+ default:
23
+ return `[${block.type}]`;
24
+ }
25
+ }
26
+ Acp.text = text;
27
+ function values(option) {
28
+ return (option?.options ?? []).flatMap((item) => ("options" in item) && Array.isArray(item.options) ? item.options : [item]);
29
+ }
30
+ Acp.values = values;
31
+ function optionOf(options, category) {
32
+ return options?.find((option) => option.category === category) ?? options?.find((option) => option.id === category);
33
+ }
34
+ Acp.optionOf = optionOf;
35
+ })(Acp ||= {});
36
+
37
+ // src/agent-bindings.ts
38
+ import { realpathSync } from "node:fs";
39
+ import { homedir } from "node:os";
40
+ import { join, sep } from "node:path";
41
+
42
+ // src/acp-agent.ts
43
+ import { spawn } from "node:child_process";
44
+
45
+ // src/agent-turn.ts
46
+ var OUTPUT_CHARS = 8000;
47
+ var WRITING_KINDS = new Set(["edit", "delete", "move"]);
48
+ var PATH_KEYS = ["file_path", "path", "filePath", "notebook_path", "destination"];
49
+ function str(value) {
50
+ return typeof value === "string" && value.trim() ? value : undefined;
51
+ }
52
+ function num(value) {
53
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
54
+ }
55
+
56
+ class AgentTurn {
57
+ unsolicited;
58
+ command;
59
+ onWrite;
60
+ tools = new Map;
61
+ usage = {};
62
+ ended = false;
63
+ produced = false;
64
+ items = [];
65
+ listeners = new Set;
66
+ written = new Set;
67
+ constructor(unsolicited = false, command, onWrite) {
68
+ this.unsolicited = unsolicited;
69
+ this.command = command;
70
+ this.onWrite = onWrite;
71
+ }
72
+ update(update) {
73
+ if (this.ended) {
74
+ return;
75
+ }
76
+ switch (update.sessionUpdate) {
77
+ case "agent_message_chunk":
78
+ this.pushText("text", Acp.text(update.content));
79
+ break;
80
+ case "agent_thought_chunk":
81
+ this.pushText("thinking", Acp.text(update.content));
82
+ break;
83
+ case "tool_call":
84
+ case "tool_call_update":
85
+ this.tool(update);
86
+ break;
87
+ case "plan":
88
+ this.pushText("thinking", AgentTurn.plan(update.entries));
89
+ break;
90
+ case "usage_update":
91
+ this.measure(update);
92
+ break;
93
+ }
94
+ }
95
+ end(reason) {
96
+ this.finish({ type: "end", reason });
97
+ }
98
+ fail(message, code) {
99
+ this.finish({ type: "error", message, code });
100
+ }
101
+ async next(signal) {
102
+ while (!this.items.length) {
103
+ if (signal?.aborted) {
104
+ return;
105
+ }
106
+ await this.changed(signal);
107
+ }
108
+ return this.items.shift();
109
+ }
110
+ async whenEnded(timeoutMs) {
111
+ const until = Date.now() + timeoutMs;
112
+ while (!this.ended && Date.now() < until) {
113
+ await this.changed(undefined, until - Date.now());
114
+ }
115
+ }
116
+ peek() {
117
+ return this.items[0];
118
+ }
119
+ shift() {
120
+ return this.items.shift();
121
+ }
122
+ async settle(id, quietMs, signal) {
123
+ for (;; ) {
124
+ const run = this.tools.get(id);
125
+ if (!run || run.complete || this.ended || signal?.aborted || this.items.some((item) => item.type !== "tool")) {
126
+ return;
127
+ }
128
+ const left = run.updatedAt + quietMs - Date.now();
129
+ if (left <= 0) {
130
+ return;
131
+ }
132
+ await this.changed(signal, left);
133
+ }
134
+ }
135
+ async waitTool(id, signal) {
136
+ for (;; ) {
137
+ const run = this.tools.get(id);
138
+ if (!run || run.done || this.ended || signal?.aborted) {
139
+ return run;
140
+ }
141
+ await this.changed(signal);
142
+ }
143
+ }
144
+ pushText(type, text) {
145
+ if (!text) {
146
+ return;
147
+ }
148
+ this.produced = true;
149
+ const last = this.items[this.items.length - 1];
150
+ if (last?.type === type) {
151
+ last.text += text;
152
+ } else {
153
+ this.items.push({ type, text });
154
+ }
155
+ this.notify();
156
+ }
157
+ tool(update) {
158
+ let run = this.tools.get(update.toolCallId);
159
+ if (!run) {
160
+ run = {
161
+ id: update.toolCallId,
162
+ title: "",
163
+ kind: "other",
164
+ input: {},
165
+ locations: [],
166
+ status: "pending",
167
+ output: "",
168
+ done: false,
169
+ complete: false,
170
+ terminal: "",
171
+ updatedAt: Date.now()
172
+ };
173
+ this.tools.set(run.id, run);
174
+ this.items.push({ type: "tool", id: run.id });
175
+ this.produced = true;
176
+ }
177
+ run.title = str(update.title) ?? run.title;
178
+ run.kind = update.kind ?? run.kind;
179
+ run.name = AgentTurn.toolName(update._meta) ?? str(update.name) ?? run.name;
180
+ run.terminal += AgentTurn.terminalOutput(update._meta);
181
+ if (update.rawInput && typeof update.rawInput === "object" && Object.keys(update.rawInput).length) {
182
+ run.input = update.rawInput;
183
+ }
184
+ if (update.locations?.length) {
185
+ run.locations = update.locations.map((location) => location.path);
186
+ }
187
+ if (update.status) {
188
+ run.status = update.status;
189
+ }
190
+ run.complete ||= AgentTurn.argumentsComplete(update._meta) || Object.keys(run.input).length > 0 && update.status === "pending";
191
+ if (run.status === "completed" || run.status === "failed") {
192
+ run.done = true;
193
+ run.complete = true;
194
+ run.output = AgentTurn.contentText(update.content ?? []) || run.terminal || AgentTurn.raw(update.rawOutput);
195
+ run.output = AgentTurn.clip(run.output);
196
+ }
197
+ run.updatedAt = Date.now();
198
+ this.tellWrites(run, update.content ?? []);
199
+ this.notify();
200
+ }
201
+ tellWrites(run, content) {
202
+ if (!this.onWrite) {
203
+ return;
204
+ }
205
+ const tell = (path, before) => {
206
+ const key = `${run.id}\x00${path}`;
207
+ if (!this.written.has(key)) {
208
+ this.written.add(key);
209
+ this.onWrite?.(path, before);
210
+ }
211
+ };
212
+ for (const item of content) {
213
+ if (item.type === "diff" && str(item.path)) {
214
+ tell(item.path, item.oldText ?? null);
215
+ }
216
+ }
217
+ if (WRITING_KINDS.has(run.kind)) {
218
+ for (const path of [...run.locations, ...PATH_KEYS.map((key) => str(run.input[key]))]) {
219
+ if (path) {
220
+ tell(path);
221
+ }
222
+ }
223
+ }
224
+ }
225
+ measure(update) {
226
+ this.usage.used = num(update.used) ?? this.usage.used;
227
+ this.usage.size = num(update.size) ?? this.usage.size;
228
+ const tokens = update._meta?.usage;
229
+ if (tokens && typeof tokens === "object") {
230
+ this.usage.input = num(tokens.prompt_tokens) ?? num(tokens.input_tokens) ?? this.usage.input;
231
+ this.usage.output = num(tokens.completion_tokens) ?? num(tokens.output_tokens) ?? this.usage.output;
232
+ const details = tokens.prompt_tokens_details;
233
+ this.usage.cacheRead = num(tokens.prompt_cache_hit_tokens) || num(details?.cached_tokens) || num(tokens.cached_tokens) || num(tokens.cache_read_input_tokens) || this.usage.cacheRead;
234
+ }
235
+ }
236
+ finish(item) {
237
+ if (this.ended) {
238
+ return;
239
+ }
240
+ this.ended = true;
241
+ this.items.push(item);
242
+ this.notify();
243
+ }
244
+ notify() {
245
+ for (const listener of [...this.listeners]) {
246
+ listener();
247
+ }
248
+ }
249
+ changed(signal, timeoutMs) {
250
+ return new Promise((resolve) => {
251
+ const done = () => {
252
+ this.listeners.delete(done);
253
+ signal?.removeEventListener("abort", done);
254
+ if (timer) {
255
+ clearTimeout(timer);
256
+ }
257
+ resolve();
258
+ };
259
+ const timer = timeoutMs !== undefined ? setTimeout(done, timeoutMs) : undefined;
260
+ this.listeners.add(done);
261
+ signal?.addEventListener("abort", done, { once: true });
262
+ });
263
+ }
264
+ static plan(entries) {
265
+ const mark = { completed: "x", in_progress: "~", pending: " " };
266
+ return `${entries.map((entry) => `- [${mark[entry.status] ?? " "}] ${entry.content}`).join(`
267
+ `)}
268
+ `;
269
+ }
270
+ static output(update) {
271
+ return AgentTurn.clip(AgentTurn.contentText(update.content ?? []) || AgentTurn.raw(update.rawOutput));
272
+ }
273
+ static clip(text) {
274
+ return text.length > OUTPUT_CHARS ? `${text.slice(0, OUTPUT_CHARS)}
275
+ …` : text;
276
+ }
277
+ static terminalOutput(meta) {
278
+ let text = "";
279
+ for (const [key, value] of Object.entries(meta ?? {})) {
280
+ const data = value?.data;
281
+ if (/terminal_output/.test(key) && typeof data === "string") {
282
+ text += data;
283
+ }
284
+ }
285
+ return text;
286
+ }
287
+ static contentText(content) {
288
+ return content.map((item) => {
289
+ if (item.type === "content") {
290
+ return Acp.text(item.content);
291
+ }
292
+ if (item.type === "diff") {
293
+ return `${item.path}
294
+ ${AgentTurn.diff(item.oldText ?? "", item.newText)}`;
295
+ }
296
+ return "";
297
+ }).filter(Boolean).join(`
298
+ `);
299
+ }
300
+ static raw(value) {
301
+ if (value === undefined || value === null) {
302
+ return "";
303
+ }
304
+ if (typeof value === "string") {
305
+ return value;
306
+ }
307
+ const text = value.text;
308
+ if (typeof text === "string") {
309
+ return text;
310
+ }
311
+ try {
312
+ return JSON.stringify(value, undefined, 2);
313
+ } catch {
314
+ return String(value);
315
+ }
316
+ }
317
+ static diff(before, after) {
318
+ const old = before ? before.split(`
319
+ `) : [];
320
+ const lines = after.split(`
321
+ `);
322
+ let start = 0;
323
+ while (start < old.length && start < lines.length && old[start] === lines[start]) {
324
+ start++;
325
+ }
326
+ let end = 0;
327
+ while (end < old.length - start && end < lines.length - start && old[old.length - 1 - end] === lines[lines.length - 1 - end]) {
328
+ end++;
329
+ }
330
+ return [...old.slice(start, old.length - end).map((line) => `- ${line}`), ...lines.slice(start, lines.length - end).map((line) => `+ ${line}`)].join(`
331
+ `);
332
+ }
333
+ static argumentsComplete(meta) {
334
+ return Object.entries(meta ?? {}).some(([key, value]) => /toolArgumentsComplete$/.test(key) && value === true);
335
+ }
336
+ static toolName(meta) {
337
+ for (const [key, value] of Object.entries(meta ?? {})) {
338
+ if (/toolName$/i.test(key) && typeof value === "string") {
339
+ return value;
340
+ }
341
+ if (value && typeof value === "object" && typeof value.toolName === "string") {
342
+ return value.toolName;
343
+ }
344
+ }
345
+ return;
346
+ }
347
+ }
348
+
349
+ // src/agent-session.ts
350
+ var UNSOLICITED_QUIET_MS = 3000;
351
+ var ABANDON_WAIT_MS = 5000;
352
+ var ANSWER_WAIT_MS = 15000;
353
+
354
+ class AgentSession {
355
+ host;
356
+ id;
357
+ turn;
358
+ options = [];
359
+ models;
360
+ title;
361
+ callbacks = { permission: async (request) => AgentSession.allow(request), activity: () => {
362
+ return;
363
+ } };
364
+ queued = [];
365
+ quietTimer;
366
+ abandoned;
367
+ answer;
368
+ working = false;
369
+ requests = new Set;
370
+ earlier = new Set;
371
+ constructor(host, id, setup) {
372
+ this.host = host;
373
+ this.id = id;
374
+ this.apply(setup);
375
+ }
376
+ apply(setup) {
377
+ if (setup.configOptions) {
378
+ this.options = setup.configOptions;
379
+ }
380
+ if (setup.models) {
381
+ this.models = setup.models;
382
+ }
383
+ }
384
+ update(update) {
385
+ const meta = update._meta;
386
+ const ids = AgentSession.requestIds(meta);
387
+ for (const id of ids) {
388
+ this.requests.add(id);
389
+ }
390
+ switch (update.sessionUpdate) {
391
+ case "config_option_update":
392
+ this.options = update.configOptions ?? this.options;
393
+ return;
394
+ case "session_info_update": {
395
+ const title = update.title;
396
+ if (typeof title === "string" && title.trim() && title.trim() !== this.title) {
397
+ this.title = title.trim();
398
+ this.callbacks.title?.(this.title);
399
+ }
400
+ const phase = AgentSession.phase(meta);
401
+ const stale = ids.some((id) => this.earlier.has(id));
402
+ if (phase && !stale && this.turn && !this.turn.unsolicited) {
403
+ if (phase !== "idle") {
404
+ this.working = true;
405
+ } else if (this.working) {
406
+ this.working = false;
407
+ this.turn.end("end_turn");
408
+ }
409
+ }
410
+ if (meta && Object.keys(meta).some((key) => /unsolicitedTurn$/.test(key)) && !this.turn) {
411
+ this.startUnsolicited(false);
412
+ }
413
+ return;
414
+ }
415
+ case "session_end":
416
+ if (this.turn?.unsolicited) {
417
+ this.turn.end("end_turn");
418
+ }
419
+ return;
420
+ case "agent_message_chunk":
421
+ case "agent_thought_chunk":
422
+ case "tool_call":
423
+ case "tool_call_update":
424
+ case "plan":
425
+ if (!this.turn && this.abandoned && !this.abandoned.ended) {
426
+ this.abandoned.update(update);
427
+ return;
428
+ }
429
+ if (!this.turn) {
430
+ this.startUnsolicited(true);
431
+ }
432
+ break;
433
+ }
434
+ this.turn?.update(update);
435
+ if (this.turn?.unsolicited && this.quietTimer) {
436
+ this.quiet(this.turn);
437
+ }
438
+ }
439
+ prompt(prompt) {
440
+ const first = prompt.find((block) => block.type === "text")?.text?.trim() ?? "";
441
+ const turn = new AgentTurn(false, /^\/[\w:.-]+/.exec(first)?.[0], (path, before) => this.callbacks.write?.(path, before));
442
+ this.turn = turn;
443
+ this.working = false;
444
+ this.earlier = new Set(this.requests);
445
+ const answer = this.host.request("session/prompt", { sessionId: this.id, prompt }).then((response) => turn.end(response?.stopReason ?? "end_turn"), (error) => turn.fail(error.message, error.code));
446
+ this.answer = answer;
447
+ return turn;
448
+ }
449
+ queue(prompt) {
450
+ this.queued.push(prompt);
451
+ }
452
+ takeQueued() {
453
+ if (!this.queued.length) {
454
+ return;
455
+ }
456
+ return this.queued.splice(0).flat();
457
+ }
458
+ abandon(turn) {
459
+ this.cancel();
460
+ this.finished(turn);
461
+ this.abandoned = turn;
462
+ }
463
+ async idle() {
464
+ const turn = this.abandoned;
465
+ this.abandoned = undefined;
466
+ await turn?.whenEnded(ABANDON_WAIT_MS);
467
+ const answer = this.answer;
468
+ if (answer) {
469
+ let timer;
470
+ await Promise.race([answer, new Promise((resolve) => timer = setTimeout(resolve, ANSWER_WAIT_MS))]);
471
+ clearTimeout(timer);
472
+ }
473
+ }
474
+ finished(turn) {
475
+ if (this.turn === turn) {
476
+ this.turn = undefined;
477
+ clearTimeout(this.quietTimer);
478
+ this.quietTimer = undefined;
479
+ }
480
+ }
481
+ cancel() {
482
+ this.host.notify("session/cancel", { sessionId: this.id });
483
+ if (this.turn?.unsolicited) {
484
+ this.turn.end("cancelled");
485
+ }
486
+ }
487
+ async select(category, value, signal) {
488
+ if (value === undefined) {
489
+ return;
490
+ }
491
+ const option = Acp.optionOf(this.options, category);
492
+ if (option) {
493
+ if (option.currentValue === value || !Acp.values(option).some((candidate) => candidate.value === value)) {
494
+ return;
495
+ }
496
+ const result = await this.host.request("session/set_config_option", { sessionId: this.id, configId: option.id, value }, signal);
497
+ this.apply(result ?? {});
498
+ option.currentValue = value;
499
+ } else if (category === "model" && this.models && this.models.currentModelId !== value) {
500
+ if (this.models.availableModels.some((model) => model.modelId === value)) {
501
+ await this.host.request("session/set_model", { sessionId: this.id, modelId: value }, signal);
502
+ this.models.currentModelId = value;
503
+ }
504
+ }
505
+ }
506
+ startUnsolicited(quiet) {
507
+ const turn = new AgentTurn(true, undefined, (path, before) => this.callbacks.write?.(path, before));
508
+ this.turn = turn;
509
+ if (quiet) {
510
+ this.quiet(turn);
511
+ }
512
+ this.callbacks.activity(this);
513
+ }
514
+ quiet(turn) {
515
+ clearTimeout(this.quietTimer);
516
+ this.quietTimer = setTimeout(() => turn.end("end_turn"), UNSOLICITED_QUIET_MS);
517
+ this.quietTimer.unref?.();
518
+ }
519
+ static requestIds(meta) {
520
+ return Object.entries(meta ?? {}).filter(([key, value]) => /requestId$/i.test(key) && typeof value === "string" && value).map(([, value]) => value);
521
+ }
522
+ static phase(meta) {
523
+ for (const [key, value] of Object.entries(meta ?? {})) {
524
+ const phase = value?.phase;
525
+ if (/agentPhase$/.test(key) && typeof phase === "string") {
526
+ return phase;
527
+ }
528
+ }
529
+ return;
530
+ }
531
+ static allow(request) {
532
+ const option = request.options.find((candidate) => candidate.kind === "allow_once") ?? request.options.find((candidate) => candidate.kind === "allow_always") ?? request.options[0];
533
+ return option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" };
534
+ }
535
+ }
536
+
537
+ // src/json-rpc.ts
538
+ class JsonRpcError extends Error {
539
+ code;
540
+ data;
541
+ constructor(code, message, data) {
542
+ super(message);
543
+ this.code = code;
544
+ this.data = data;
545
+ this.name = "JsonRpcError";
546
+ }
547
+ }
548
+
549
+ class JsonRpcConnection {
550
+ output;
551
+ onRequest = async (method) => {
552
+ throw new JsonRpcError(-32601, `Method not found: ${method}`);
553
+ };
554
+ onNotification = () => {
555
+ return;
556
+ };
557
+ onClose = () => {
558
+ return;
559
+ };
560
+ nextId = 0;
561
+ pending = new Map;
562
+ buffer = "";
563
+ closed;
564
+ constructor(output, input) {
565
+ this.output = output;
566
+ input.setEncoding("utf8");
567
+ input.on("data", (chunk) => this.receive(chunk));
568
+ input.on("end", () => this.close(new Error("The agent closed its output")));
569
+ output.on("error", (error) => this.close(error));
570
+ }
571
+ get pendingCount() {
572
+ return this.pending.size;
573
+ }
574
+ get isClosed() {
575
+ return this.closed !== undefined;
576
+ }
577
+ request(method, params, signal) {
578
+ if (this.closed) {
579
+ return Promise.reject(this.closed);
580
+ }
581
+ const id = ++this.nextId;
582
+ return new Promise((resolve, reject) => {
583
+ const abort = () => {
584
+ this.pending.delete(id);
585
+ reject(signal?.reason instanceof Error ? signal.reason : new Error("Aborted"));
586
+ };
587
+ if (signal?.aborted) {
588
+ abort();
589
+ return;
590
+ }
591
+ signal?.addEventListener("abort", abort, { once: true });
592
+ this.pending.set(id, {
593
+ resolve: (value) => {
594
+ signal?.removeEventListener("abort", abort);
595
+ resolve(value);
596
+ },
597
+ reject: (error) => {
598
+ signal?.removeEventListener("abort", abort);
599
+ reject(error);
600
+ }
601
+ });
602
+ this.send({ jsonrpc: "2.0", id, method, params });
603
+ });
604
+ }
605
+ notify(method, params) {
606
+ if (!this.closed) {
607
+ this.send({ jsonrpc: "2.0", method, params });
608
+ }
609
+ }
610
+ close(error) {
611
+ if (this.closed) {
612
+ return;
613
+ }
614
+ this.closed = error;
615
+ for (const pending of this.pending.values()) {
616
+ pending.reject(error);
617
+ }
618
+ this.pending.clear();
619
+ this.onClose(error);
620
+ }
621
+ send(message) {
622
+ this.output.write(`${JSON.stringify(message)}
623
+ `);
624
+ }
625
+ receive(chunk) {
626
+ this.buffer += chunk;
627
+ let end = this.buffer.indexOf(`
628
+ `);
629
+ while (end >= 0) {
630
+ const line = this.buffer.slice(0, end).trim();
631
+ this.buffer = this.buffer.slice(end + 1);
632
+ if (line) {
633
+ this.dispatch(line);
634
+ }
635
+ end = this.buffer.indexOf(`
636
+ `);
637
+ }
638
+ }
639
+ dispatch(line) {
640
+ let message;
641
+ try {
642
+ message = JSON.parse(line);
643
+ } catch {
644
+ return;
645
+ }
646
+ if (!message || typeof message !== "object") {
647
+ return;
648
+ }
649
+ if (message.method === undefined) {
650
+ const pending = typeof message.id === "number" ? this.pending.get(message.id) : undefined;
651
+ if (pending) {
652
+ this.pending.delete(message.id);
653
+ if (message.error) {
654
+ pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
655
+ } else {
656
+ pending.resolve(message.result);
657
+ }
658
+ }
659
+ } else if (message.id === undefined || message.id === null) {
660
+ this.onNotification(message.method, message.params);
661
+ } else {
662
+ this.answer(message.id, message.method, message.params);
663
+ }
664
+ }
665
+ async answer(id, method, params) {
666
+ try {
667
+ const result = await this.onRequest(method, params);
668
+ this.send({ jsonrpc: "2.0", id, result: result ?? null });
669
+ } catch (error) {
670
+ const code = error instanceof JsonRpcError ? error.code : -32603;
671
+ this.send({ jsonrpc: "2.0", id, error: { code, message: error instanceof Error ? error.message : String(error) } });
672
+ }
673
+ }
674
+ }
675
+
676
+ // src/texts.ts
677
+ var TEXTS = {
678
+ remote: {
679
+ en: (agent) => `${agent} works in directories of this computer; it cannot work in a remote directory yet.`,
680
+ zh: (agent) => `${agent} 只能在这台电脑上的目录里工作,暂不支持远程目录。`
681
+ },
682
+ signIn: {
683
+ en: (agent, command) => `${agent} is not signed in. Run \`${command}\` in a terminal to sign in, then try again.`,
684
+ zh: (agent, command) => `${agent} 还没有登录。请在终端里运行 \`${command}\` 登录后再试。`
685
+ },
686
+ notFound: {
687
+ en: (agent, command) => `${agent}: \`${command}\` was not found. Install it, or set its command in \`agents\` of settings.json.`,
688
+ zh: (agent, command) => `${agent}:找不到命令 \`${command}\`。请先安装,或在 settings.json 的 \`agents\` 里指定它的命令。`
689
+ },
690
+ exited: {
691
+ en: (agent, code, last) => `${agent} exited (${code})${last ? `: ${last}` : ""}`,
692
+ zh: (agent, code, last) => `${agent} 已退出(${code})${last ? `:${last}` : ""}`
693
+ },
694
+ commandDone: {
695
+ en: (agent, command) => `${agent} ran \`${command}\` and said nothing back; it may only show in ${agent}'s own interface.`,
696
+ zh: (agent, command) => `${agent} 已执行 \`${command}\`,没有返回内容(这个命令可能只在 ${agent} 自己的界面里有显示)。`
697
+ },
698
+ unfinished: {
699
+ en: (agent) => `${agent} ended its turn before this call finished.`,
700
+ zh: (agent) => `${agent} 在这次调用完成前结束了这一轮。`
701
+ }
702
+ };
703
+ function language(env = process.env) {
704
+ const locale = env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || Intl.DateTimeFormat().resolvedOptions().locale;
705
+ return /^zh/i.test(locale) ? "zh" : "en";
706
+ }
707
+ function text(key, ...args) {
708
+ return TEXTS[key][language()](...args);
709
+ }
710
+
711
+ // src/acp-agent.ts
712
+ var STDERR_CHARS = 2000;
713
+ function agentEnv(extra) {
714
+ const env = {};
715
+ for (const [key, value] of Object.entries(process.env)) {
716
+ if (!key.startsWith("PI_") && key !== "ELECTRON_RUN_AS_NODE" && key !== "AI_AGENT") {
717
+ env[key] = value;
718
+ }
719
+ }
720
+ return { ...env, ...extra };
721
+ }
722
+
723
+ class AcpAgent {
724
+ name;
725
+ program;
726
+ idleMs;
727
+ sessions = new Map;
728
+ initialized;
729
+ child;
730
+ connection;
731
+ starting;
732
+ stderr = "";
733
+ idleTimer;
734
+ constructor(name, program, idleMs = 10 * 60000) {
735
+ this.name = name;
736
+ this.program = program;
737
+ this.idleMs = idleMs;
738
+ }
739
+ get running() {
740
+ return !!this.connection && !this.connection.isClosed;
741
+ }
742
+ start() {
743
+ if (this.starting && this.running) {
744
+ return this.starting;
745
+ }
746
+ this.starting = this.launch();
747
+ this.starting.catch(() => this.starting = undefined);
748
+ return this.starting;
749
+ }
750
+ async newSession(cwd, signal) {
751
+ await this.start();
752
+ const setup = await this.request("session/new", { cwd, mcpServers: [] }, signal);
753
+ if (!setup?.sessionId) {
754
+ throw new Error(`${this.name} did not open a session`);
755
+ }
756
+ return this.add(setup.sessionId, setup);
757
+ }
758
+ async loadSession(id, cwd, signal) {
759
+ const known = this.sessions.get(id);
760
+ if (known) {
761
+ return known;
762
+ }
763
+ const init = await this.start();
764
+ if (!init.agentCapabilities?.loadSession) {
765
+ return;
766
+ }
767
+ try {
768
+ const setup = await this.request("session/load", { sessionId: id, cwd, mcpServers: [] }, signal);
769
+ return this.add(id, setup ?? {});
770
+ } catch (error) {
771
+ if (error instanceof JsonRpcError && error.code !== Acp.AUTH_REQUIRED) {
772
+ return;
773
+ }
774
+ throw error;
775
+ }
776
+ }
777
+ request(method, params, signal) {
778
+ this.touch();
779
+ if (!this.connection || this.connection.isClosed) {
780
+ return Promise.reject(new Error(`${this.name} is not running`));
781
+ }
782
+ const connection = this.connection;
783
+ this.reference(true);
784
+ return connection.request(method, params, signal).catch((error) => {
785
+ throw this.explain(error);
786
+ }).finally(() => this.reference(connection.pendingCount > 0));
787
+ }
788
+ notify(method, params) {
789
+ this.connection?.notify(method, params);
790
+ }
791
+ stop() {
792
+ clearTimeout(this.idleTimer);
793
+ const child = this.child;
794
+ this.child = undefined;
795
+ this.connection?.close(new Error(`${this.name} stopped`));
796
+ this.connection = undefined;
797
+ this.starting = undefined;
798
+ if (child && child.exitCode === null) {
799
+ child.stdin?.end();
800
+ child.kill();
801
+ }
802
+ }
803
+ reference(on) {
804
+ const child = this.child;
805
+ for (const handle of [child, child?.stdin, child?.stdout, child?.stderr]) {
806
+ if (on) {
807
+ handle?.ref?.();
808
+ } else {
809
+ handle?.unref?.();
810
+ }
811
+ }
812
+ }
813
+ touch() {
814
+ clearTimeout(this.idleTimer);
815
+ this.idleTimer = setTimeout(() => {
816
+ if ([...this.sessions.values()].some((session) => session.turn)) {
817
+ this.touch();
818
+ } else {
819
+ this.stop();
820
+ }
821
+ }, this.idleMs);
822
+ this.idleTimer.unref?.();
823
+ }
824
+ add(id, setup) {
825
+ const session = new AgentSession(this, id, setup);
826
+ this.sessions.set(id, session);
827
+ return session;
828
+ }
829
+ async launch() {
830
+ this.stop();
831
+ this.stderr = "";
832
+ const child = spawn(this.program.command, this.program.args, {
833
+ cwd: this.program.cwd,
834
+ env: agentEnv(this.program.env),
835
+ stdio: ["pipe", "pipe", "pipe"],
836
+ shell: process.platform === "win32",
837
+ windowsHide: true
838
+ });
839
+ this.child = child;
840
+ const { stdin, stdout } = child;
841
+ if (!stdin || !stdout) {
842
+ throw new Error(`${this.name} has no standard input or output`);
843
+ }
844
+ const connection = new JsonRpcConnection(stdin, stdout);
845
+ this.connection = connection;
846
+ child.stderr?.setEncoding("utf8");
847
+ child.stderr?.on("data", (chunk) => this.stderr = (this.stderr + chunk).slice(-STDERR_CHARS));
848
+ child.on("error", (error) => connection.close(error.code === "ENOENT" ? new Error(text("notFound", this.name, this.program.command)) : error));
849
+ child.on("exit", (code) => connection.close(new Error(text("exited", this.name, String(code ?? "signal"), this.lastError()))));
850
+ connection.onNotification = (method, params) => this.notified(method, params);
851
+ connection.onRequest = (method, params) => this.requested(method, params);
852
+ connection.onClose = (error) => {
853
+ for (const session of this.sessions.values()) {
854
+ session.turn?.fail(error.message);
855
+ }
856
+ this.sessions.clear();
857
+ };
858
+ this.reference(true);
859
+ const init = await connection.request("initialize", {
860
+ protocolVersion: Acp.PROTOCOL_VERSION,
861
+ clientCapabilities: {
862
+ fs: { readTextFile: false, writeTextFile: false },
863
+ terminal: false,
864
+ ...this.program.clientMeta ? { _meta: this.program.clientMeta } : {}
865
+ },
866
+ clientInfo: { name: "ta", version: "1" }
867
+ }).finally(() => this.reference(false));
868
+ this.initialized = init;
869
+ return init;
870
+ }
871
+ notified(method, params) {
872
+ this.touch();
873
+ if (method !== "session/update") {
874
+ return;
875
+ }
876
+ const { sessionId, update } = params ?? {};
877
+ if (sessionId && update) {
878
+ this.sessions.get(sessionId)?.update(update);
879
+ }
880
+ }
881
+ async requested(method, params) {
882
+ if (method === "session/request_permission") {
883
+ const request = params;
884
+ const session = this.sessions.get(request.sessionId);
885
+ const outcome = session ? await session.callbacks.permission(request) : AgentSession.allow(request);
886
+ return { outcome };
887
+ }
888
+ throw new JsonRpcError(-32601, `Method not found: ${method}`);
889
+ }
890
+ explain(error) {
891
+ if (error instanceof JsonRpcError && error.code === Acp.AUTH_REQUIRED) {
892
+ return Object.assign(new Error(`${this.name} is not signed in`), { code: error.code });
893
+ }
894
+ return error instanceof Error ? error : new Error(String(error));
895
+ }
896
+ lastError() {
897
+ const lines = this.stderr.trim().split(`
898
+ `).filter(Boolean);
899
+ return lines[lines.length - 1] ?? "";
900
+ }
901
+ }
902
+
903
+ // src/agent-bindings.ts
904
+ var BINDING_ENTRY = "ta-agents.session";
905
+ var POOL = Symbol.for("ta-agents.pool");
906
+ var AgentPool;
907
+ ((AgentPool) => {
908
+ function of(config, cwd) {
909
+ const global = globalThis;
910
+ const pool = global[POOL] ?? create();
911
+ global[POOL] = pool;
912
+ const key = JSON.stringify([config.command, config.args, config.env ?? {}, config.clientMeta ?? {}, cwd]);
913
+ let agent = pool.get(key);
914
+ if (!agent) {
915
+ agent = new AcpAgent(config.name, { command: config.command, args: config.args, env: config.env, clientMeta: config.clientMeta, cwd });
916
+ pool.set(key, agent);
917
+ }
918
+ return agent;
919
+ }
920
+ AgentPool.of = of;
921
+ function create() {
922
+ const pool = new Map;
923
+ process.once("exit", () => {
924
+ for (const agent of pool.values()) {
925
+ agent.stop();
926
+ }
927
+ });
928
+ return pool;
929
+ }
930
+ })(AgentPool ||= {});
931
+
932
+ class AgentBindings {
933
+ save;
934
+ prepare;
935
+ agentOf;
936
+ cwd = process.cwd();
937
+ ids = new Map;
938
+ opened = new Map;
939
+ constructor(save, prepare, agentOf = AgentPool.of) {
940
+ this.save = save;
941
+ this.prepare = prepare;
942
+ this.agentOf = agentOf;
943
+ }
944
+ restore(entries, fork) {
945
+ this.ids.clear();
946
+ this.opened.clear();
947
+ if (fork) {
948
+ return;
949
+ }
950
+ for (const entry of entries) {
951
+ const { type, customType, data } = entry ?? {};
952
+ if (type === "custom" && customType === BINDING_ENTRY && typeof data?.agent === "string" && typeof data.session === "string") {
953
+ this.ids.set(data.agent, data.session);
954
+ }
955
+ }
956
+ }
957
+ forget() {
958
+ this.ids.clear();
959
+ this.opened.clear();
960
+ }
961
+ sessionId(agent) {
962
+ return this.ids.get(agent);
963
+ }
964
+ open(config, signal) {
965
+ const agent = this.agentOf(config, this.cwd);
966
+ let opened = this.opened.get(config.id);
967
+ if (opened) {
968
+ opened = opened.then((value) => agent.running && agent.sessions.get(value.session.id) === value.session ? { ...value, fresh: false } : this.connect(config, agent, signal));
969
+ } else {
970
+ opened = this.connect(config, agent, signal);
971
+ }
972
+ opened.catch(() => this.opened.delete(config.id));
973
+ this.opened.set(config.id, opened);
974
+ return opened;
975
+ }
976
+ close() {
977
+ this.opened.clear();
978
+ }
979
+ async connect(config, agent, signal) {
980
+ if (AgentBindings.isRemote(this.cwd)) {
981
+ throw new Error(text("remote", config.name));
982
+ }
983
+ const known = this.ids.get(config.id);
984
+ let session = known ? await agent.loadSession(known, this.cwd, signal) : undefined;
985
+ const fresh = !session;
986
+ if (!session) {
987
+ session = await agent.newSession(this.cwd, signal);
988
+ for (const [option, value] of Object.entries(config.options ?? {})) {
989
+ await session.select(option, value, signal).catch(() => {
990
+ return;
991
+ });
992
+ }
993
+ this.ids.set(config.id, session.id);
994
+ this.save({ agent: config.id, session: session.id });
995
+ }
996
+ this.prepare(config, session);
997
+ return { session, fresh, images: !!agent.initialized?.agentCapabilities?.promptCapabilities?.image, dirs: AgentBindings.dirs(this.cwd) };
998
+ }
999
+ static dirs(cwd) {
1000
+ try {
1001
+ const real = realpathSync(cwd);
1002
+ return real === cwd ? [cwd] : [cwd, real];
1003
+ } catch {
1004
+ return [cwd];
1005
+ }
1006
+ }
1007
+ static isRemote(cwd) {
1008
+ const agentDir = process.env.TA_CODING_AGENT_DIR ?? join(homedir(), ".ta", "agent");
1009
+ return cwd.startsWith(join(agentDir, "remote") + sep);
1010
+ }
1011
+ }
1012
+
1013
+ // src/agent-catalog.ts
1014
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
1015
+ import { homedir as homedir2 } from "node:os";
1016
+ import { delimiter, dirname, join as join2 } from "node:path";
1017
+ var PRESETS = [
1018
+ {
1019
+ id: "codebuddy-code",
1020
+ name: "CodeBuddy Code",
1021
+ command: "cbc",
1022
+ args: ["--acp"],
1023
+ programs: ["cbc", "codebuddy"],
1024
+ login: "cbc",
1025
+ env: { CODEBUDDY_CODE_MODE_ENABLED: "1" },
1026
+ clientMeta: { "codebuddy.ai": { mainAgentSupport: true, toolModeSupport: true } },
1027
+ options: { mode: "fullAccess" }
1028
+ },
1029
+ {
1030
+ id: "claude-code",
1031
+ name: "Claude Code",
1032
+ command: "npx",
1033
+ args: ["-y", "@agentclientprotocol/claude-agent-acp@0.106.0"],
1034
+ programs: ["claude"],
1035
+ login: "claude"
1036
+ },
1037
+ { id: "codex", name: "Codex", command: "npx", args: ["-y", "@agentclientprotocol/codex-acp@2.6.0"], programs: ["codex"], login: "codex login" }
1038
+ ];
1039
+ var AgentCatalog;
1040
+ ((AgentCatalog) => {
1041
+ AgentCatalog.DEFAULT_MODEL = "default";
1042
+ function agents(settings, find = Programs.find) {
1043
+ const configured = settings && typeof settings === "object" ? settings : {};
1044
+ const result = [];
1045
+ for (const preset of PRESETS) {
1046
+ const setting = configured[preset.id];
1047
+ if (setting === false) {
1048
+ continue;
1049
+ }
1050
+ const found = preset.programs.find((program) => find(program));
1051
+ if (!found && !setting) {
1052
+ continue;
1053
+ }
1054
+ const { programs, ...config } = preset;
1055
+ const command = programs.includes(config.command) && found ? found : config.command;
1056
+ const own = setting || {};
1057
+ result.push({
1058
+ ...config,
1059
+ command,
1060
+ ...own,
1061
+ id: preset.id,
1062
+ env: config.env || own.env ? { ...config.env, ...own.env } : undefined,
1063
+ options: config.options || own.options ? { ...config.options, ...own.options } : undefined
1064
+ });
1065
+ }
1066
+ for (const [id, setting] of Object.entries(configured)) {
1067
+ if (setting && typeof setting === "object" && !PRESETS.some((preset) => preset.id === id) && typeof setting.command === "string") {
1068
+ result.push({ name: id, args: [], ...setting, id, command: setting.command });
1069
+ }
1070
+ }
1071
+ return result;
1072
+ }
1073
+ AgentCatalog.agents = agents;
1074
+ })(AgentCatalog ||= {});
1075
+ var Programs;
1076
+ ((Programs) => {
1077
+ function find(program) {
1078
+ const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
1079
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
1080
+ for (const extension of extensions) {
1081
+ if (dir && isFile(join2(dir, program + extension))) {
1082
+ return program;
1083
+ }
1084
+ }
1085
+ }
1086
+ return;
1087
+ }
1088
+ Programs.find = find;
1089
+ function isFile(path) {
1090
+ try {
1091
+ return statSync(path).isFile();
1092
+ } catch {
1093
+ return false;
1094
+ }
1095
+ }
1096
+ })(Programs ||= {});
1097
+
1098
+ class ModelCache {
1099
+ file;
1100
+ entries;
1101
+ constructor(file = ModelCache.defaultFile()) {
1102
+ this.file = file;
1103
+ }
1104
+ get(id) {
1105
+ return this.read()[id];
1106
+ }
1107
+ set(id, models) {
1108
+ const entries = this.read();
1109
+ if (JSON.stringify(entries[id]) === JSON.stringify(models)) {
1110
+ return false;
1111
+ }
1112
+ entries[id] = models;
1113
+ try {
1114
+ mkdirSync(dirname(this.file), { recursive: true });
1115
+ const temp = `${this.file}.${process.pid}.tmp`;
1116
+ writeFileSync(temp, JSON.stringify(entries, undefined, 2));
1117
+ renameSync(temp, this.file);
1118
+ } catch {}
1119
+ return true;
1120
+ }
1121
+ read() {
1122
+ if (!this.entries) {
1123
+ try {
1124
+ this.entries = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : {};
1125
+ } catch {
1126
+ this.entries = {};
1127
+ }
1128
+ }
1129
+ return this.entries ?? {};
1130
+ }
1131
+ static defaultFile() {
1132
+ return join2(process.env.XDG_CACHE_HOME || join2(homedir2(), ".cache"), "ta-agents", "models.json");
1133
+ }
1134
+ }
1135
+
1136
+ // src/agent-prompt.ts
1137
+ var ACTIVITY_TEXT = "[The agent continued on its own]";
1138
+ var TRANSCRIPT_CHARS = 30000;
1139
+ var AgentPrompt;
1140
+ ((AgentPrompt) => {
1141
+ function pending(messages) {
1142
+ const result = [];
1143
+ for (let index = messages.length - 1;index >= 0; index--) {
1144
+ const message = messages[index];
1145
+ if (message.role === "system") {
1146
+ continue;
1147
+ }
1148
+ if (message.role !== "user") {
1149
+ break;
1150
+ }
1151
+ if (text2(message) !== ACTIVITY_TEXT) {
1152
+ result.unshift(message);
1153
+ }
1154
+ }
1155
+ return result;
1156
+ }
1157
+ AgentPrompt.pending = pending;
1158
+ function blocks(messages, images) {
1159
+ const result = [];
1160
+ for (const message of messages) {
1161
+ if (message.role !== "user") {
1162
+ continue;
1163
+ }
1164
+ if (typeof message.content === "string") {
1165
+ result.push({ type: "text", text: message.content });
1166
+ continue;
1167
+ }
1168
+ for (const part of message.content) {
1169
+ if (part.type === "text") {
1170
+ result.push({ type: "text", text: part.text });
1171
+ } else if (images) {
1172
+ result.push({ type: "image", data: part.data, mimeType: part.mimeType });
1173
+ } else {
1174
+ result.push({ type: "text", text: "[An image the agent cannot take was left out]" });
1175
+ }
1176
+ }
1177
+ }
1178
+ return result;
1179
+ }
1180
+ AgentPrompt.blocks = blocks;
1181
+ function transcript(messages, pendingCount) {
1182
+ const earlier = messages.filter((message) => (message.role === "user" || message.role === "assistant") && text2(message) !== ACTIVITY_TEXT);
1183
+ const lines = [];
1184
+ for (const message of earlier.slice(0, Math.max(0, earlier.length - pendingCount))) {
1185
+ const content = text2(message).trim();
1186
+ if (content) {
1187
+ lines.push(`${message.role === "user" ? "User" : "Assistant"}: ${content}`);
1188
+ }
1189
+ }
1190
+ if (!lines.length) {
1191
+ return;
1192
+ }
1193
+ const body = lines.join(`
1194
+
1195
+ `);
1196
+ const kept = body.length > TRANSCRIPT_CHARS ? `…${body.slice(-TRANSCRIPT_CHARS)}` : body;
1197
+ return `<earlier_conversation>
1198
+ The user talked with another assistant before you joined; this is what was said:
1199
+
1200
+ ${kept}
1201
+ </earlier_conversation>`;
1202
+ }
1203
+ AgentPrompt.transcript = transcript;
1204
+ function text2(message) {
1205
+ if (message.role === "user" || message.role === "system") {
1206
+ return typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? part.text : "").join("");
1207
+ }
1208
+ if (message.role === "assistant") {
1209
+ return message.content.map((part) => part.type === "text" ? part.text : "").join("");
1210
+ }
1211
+ return "";
1212
+ }
1213
+ AgentPrompt.text = text2;
1214
+ })(AgentPrompt ||= {});
1215
+
1216
+ // src/agent-tool.ts
1217
+ function relative(path, dirs) {
1218
+ const dir = dirs.find((candidate) => path.startsWith(`${candidate}/`) || path.startsWith(`${candidate}\\`));
1219
+ return dir ? path.slice(dir.length + 1) : path;
1220
+ }
1221
+ function str2(value) {
1222
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
1223
+ }
1224
+ var AgentTool;
1225
+ ((AgentTool) => {
1226
+ AgentTool.NAME = "agent_tool";
1227
+ function args(run, cwd = []) {
1228
+ const input = run.input;
1229
+ const title = run.title || run.name || run.kind;
1230
+ let target;
1231
+ switch (run.kind) {
1232
+ case "execute":
1233
+ target = str2(input.command) ?? title.replace(/^`|`$/g, "");
1234
+ break;
1235
+ case "read":
1236
+ case "edit":
1237
+ case "delete":
1238
+ case "move":
1239
+ target = run.locations[0] ?? str2(input.file_path) ?? str2(input.path) ?? str2(input.filePath);
1240
+ break;
1241
+ case "search":
1242
+ target = str2(input.pattern) ?? str2(input.query);
1243
+ break;
1244
+ case "fetch":
1245
+ target = str2(input.url) ?? str2(input.query);
1246
+ break;
1247
+ }
1248
+ target ??= str2(input.description);
1249
+ return { title, kind: run.kind, target: relative(target ?? title, cwd), ...run.name ? { tool: run.name } : {} };
1250
+ }
1251
+ AgentTool.args = args;
1252
+ function definition(calls) {
1253
+ return {
1254
+ name: AgentTool.NAME,
1255
+ label: "Agent tool",
1256
+ description: "A tool call another coding agent made with its own tools. Only that agent calls it.",
1257
+ parameters: {
1258
+ type: "object",
1259
+ properties: {
1260
+ title: { type: "string" },
1261
+ kind: { type: "string" },
1262
+ target: { type: "string" },
1263
+ tool: { type: "string" }
1264
+ }
1265
+ },
1266
+ exposure: "direct",
1267
+ defaultActive: false,
1268
+ annotations: { readOnlyHint: true },
1269
+ async execute(toolCallId, _params, signal) {
1270
+ const call = calls.get(toolCallId);
1271
+ if (!call) {
1272
+ return { content: [{ type: "text", text: "This call ran in an earlier run of the agent." }], details: {} };
1273
+ }
1274
+ const run = await call.turn.waitTool(toolCallId, signal);
1275
+ if (signal?.aborted) {
1276
+ call.session.abandon(call.turn);
1277
+ calls.delete(toolCallId);
1278
+ throw new Error("Cancelled");
1279
+ }
1280
+ calls.delete(toolCallId);
1281
+ const details = { agent: call.agent, kind: run?.kind, title: run?.title, status: run?.status, locations: run?.locations };
1282
+ if (!run?.done) {
1283
+ return { content: [{ type: "text", text: text("unfinished", call.agent) }], details, isError: true };
1284
+ }
1285
+ return { content: [{ type: "text", text: run.output || "(no output)" }], details, isError: run.status === "failed" };
1286
+ }
1287
+ };
1288
+ }
1289
+ AgentTool.definition = definition;
1290
+ })(AgentTool ||= {});
1291
+
1292
+ // src/message-stream.ts
1293
+ class MessageStream {
1294
+ queue = [];
1295
+ waiting;
1296
+ done = false;
1297
+ resolveResult;
1298
+ final = new Promise((resolve) => this.resolveResult = resolve);
1299
+ push(event) {
1300
+ if (this.done) {
1301
+ return;
1302
+ }
1303
+ if (event.type === "done" || event.type === "error") {
1304
+ this.done = true;
1305
+ this.resolveResult(event.type === "done" ? event.message : event.error);
1306
+ }
1307
+ this.queue.push(event);
1308
+ this.waiting?.();
1309
+ }
1310
+ result() {
1311
+ return this.final;
1312
+ }
1313
+ async* [Symbol.asyncIterator]() {
1314
+ for (;; ) {
1315
+ const event = this.queue.shift();
1316
+ if (event) {
1317
+ yield event;
1318
+ if (event.type === "done" || event.type === "error") {
1319
+ return;
1320
+ }
1321
+ } else {
1322
+ await new Promise((resolve) => this.waiting = resolve);
1323
+ this.waiting = undefined;
1324
+ }
1325
+ }
1326
+ }
1327
+ }
1328
+ function emptyUsage() {
1329
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
1330
+ }
1331
+
1332
+ class MessageBuilder {
1333
+ stream;
1334
+ message;
1335
+ open;
1336
+ ended = false;
1337
+ started = Date.now();
1338
+ constructor(stream, model) {
1339
+ this.stream = stream;
1340
+ this.message = {
1341
+ role: "assistant",
1342
+ content: [],
1343
+ api: model.api,
1344
+ provider: model.provider,
1345
+ model: model.id,
1346
+ usage: emptyUsage(),
1347
+ stopReason: "stop",
1348
+ timestamp: this.started
1349
+ };
1350
+ this.stream.push({ type: "start", partial: this.message });
1351
+ }
1352
+ append(type, delta) {
1353
+ if (!delta) {
1354
+ return;
1355
+ }
1356
+ if (this.open?.type !== type) {
1357
+ this.close();
1358
+ const index2 = this.message.content.length;
1359
+ this.message.content.push(type === "text" ? { type: "text", text: "" } : { type: "thinking", thinking: "" });
1360
+ this.open = { type, index: index2 };
1361
+ this.stream.push({ type: type === "text" ? "text_start" : "thinking_start", contentIndex: index2, partial: this.message });
1362
+ }
1363
+ const index = this.open.index;
1364
+ const block = this.message.content[index];
1365
+ if (block.type === "text") {
1366
+ block.text += delta;
1367
+ this.stream.push({ type: "text_delta", contentIndex: index, delta, partial: this.message });
1368
+ } else if (block.type === "thinking") {
1369
+ block.thinking += delta;
1370
+ this.stream.push({ type: "thinking_delta", contentIndex: index, delta, partial: this.message });
1371
+ }
1372
+ }
1373
+ toolCall(call) {
1374
+ this.close();
1375
+ const index = this.message.content.length;
1376
+ this.message.content.push(call);
1377
+ this.stream.push({ type: "toolcall_start", contentIndex: index, partial: this.message });
1378
+ this.stream.push({ type: "toolcall_delta", contentIndex: index, delta: JSON.stringify(call.arguments), partial: this.message });
1379
+ this.stream.push({ type: "toolcall_end", contentIndex: index, toolCall: call, partial: this.message });
1380
+ }
1381
+ done(reason, usage) {
1382
+ if (this.ended) {
1383
+ return;
1384
+ }
1385
+ this.close();
1386
+ this.ended = true;
1387
+ this.message.stopReason = reason;
1388
+ this.message.usage = usage ?? this.message.usage;
1389
+ this.message.durationMs = Date.now() - this.started;
1390
+ this.stream.push({ type: "done", reason, message: this.message });
1391
+ }
1392
+ error(reason, message) {
1393
+ if (this.ended) {
1394
+ return;
1395
+ }
1396
+ this.close();
1397
+ this.ended = true;
1398
+ this.message.stopReason = reason;
1399
+ this.message.errorMessage = message;
1400
+ this.message.durationMs = Date.now() - this.started;
1401
+ this.stream.push({ type: "error", reason, error: this.message });
1402
+ }
1403
+ close() {
1404
+ if (!this.open) {
1405
+ return;
1406
+ }
1407
+ const { type, index } = this.open;
1408
+ const block = this.message.content[index];
1409
+ this.open = undefined;
1410
+ if (type === "text" && block.type === "text") {
1411
+ this.stream.push({ type: "text_end", contentIndex: index, content: block.text, partial: this.message });
1412
+ } else if (block.type === "thinking") {
1413
+ this.stream.push({ type: "thinking_end", contentIndex: index, content: block.thinking, partial: this.message });
1414
+ }
1415
+ }
1416
+ }
1417
+
1418
+ // src/agent-streamer.ts
1419
+ var SETTLE_MS = 1500;
1420
+ var THINKING = {
1421
+ minimal: ["minimal", "low"],
1422
+ low: ["low"],
1423
+ medium: ["medium"],
1424
+ high: ["high"],
1425
+ xhigh: ["xhigh", "max", "high"]
1426
+ };
1427
+
1428
+ class AgentStreamer {
1429
+ host;
1430
+ constructor(host) {
1431
+ this.host = host;
1432
+ }
1433
+ stream(config, model, context, options) {
1434
+ const stream = new MessageStream;
1435
+ const builder = new MessageBuilder(stream, model);
1436
+ this.run(config, model, context, options, builder).catch((error) => {
1437
+ if (options?.signal?.aborted) {
1438
+ builder.error("aborted", "Aborted");
1439
+ } else {
1440
+ builder.error("error", AgentStreamer.describe(config, error));
1441
+ }
1442
+ });
1443
+ return stream;
1444
+ }
1445
+ async run(config, model, context, options, builder) {
1446
+ const signal = options?.signal;
1447
+ const { session, fresh, images, dirs } = await this.host.open(config, signal);
1448
+ const pending = AgentPrompt.pending(context.messages);
1449
+ let turn = session.turn;
1450
+ if (turn) {
1451
+ if (pending.length) {
1452
+ session.queue(AgentPrompt.blocks(pending, images));
1453
+ }
1454
+ } else {
1455
+ let prompt = pending.length ? AgentPrompt.blocks(pending, images) : session.takeQueued();
1456
+ if (!prompt?.length) {
1457
+ builder.done("stop");
1458
+ return;
1459
+ }
1460
+ const earlier = fresh ? AgentPrompt.transcript(context.messages, pending.length) : undefined;
1461
+ if (earlier) {
1462
+ prompt = [{ type: "text", text: earlier }, ...prompt];
1463
+ }
1464
+ await session.idle();
1465
+ await this.configure(session, model, options, signal);
1466
+ turn = session.prompt(prompt);
1467
+ }
1468
+ for (;; ) {
1469
+ const item = await turn.next(signal);
1470
+ if (!item) {
1471
+ session.abandon(turn);
1472
+ builder.error("aborted", "Aborted");
1473
+ return;
1474
+ }
1475
+ switch (item.type) {
1476
+ case "text":
1477
+ case "thinking":
1478
+ builder.append(item.type, item.text);
1479
+ break;
1480
+ case "tool":
1481
+ await this.tools(config, session, turn, item.id, builder, dirs, signal);
1482
+ return;
1483
+ case "end": {
1484
+ session.finished(turn);
1485
+ this.host.ended(config, session);
1486
+ const queued = session.takeQueued();
1487
+ if (queued) {
1488
+ turn = session.prompt(queued);
1489
+ break;
1490
+ }
1491
+ if (item.reason === "cancelled" && signal?.aborted) {
1492
+ builder.error("aborted", "Aborted");
1493
+ } else {
1494
+ if (turn.command && !turn.produced) {
1495
+ builder.append("text", text("commandDone", config.name, turn.command));
1496
+ }
1497
+ builder.done("stop", AgentStreamer.usage(turn));
1498
+ }
1499
+ return;
1500
+ }
1501
+ case "error":
1502
+ session.finished(turn);
1503
+ builder.error("error", AgentStreamer.describe(config, item));
1504
+ return;
1505
+ }
1506
+ }
1507
+ }
1508
+ async tools(config, session, turn, first, builder, dirs, signal) {
1509
+ const ids = [first];
1510
+ while (turn.peek()?.type === "tool") {
1511
+ ids.push(turn.shift().id);
1512
+ }
1513
+ for (const id of ids) {
1514
+ await turn.settle(id, SETTLE_MS, signal);
1515
+ }
1516
+ if (signal?.aborted) {
1517
+ session.abandon(turn);
1518
+ builder.error("aborted", "Aborted");
1519
+ return;
1520
+ }
1521
+ for (const id of ids) {
1522
+ const run = turn.tools.get(id);
1523
+ if (run) {
1524
+ this.host.calls.set(id, { agent: config.name, session, turn });
1525
+ builder.toolCall({ type: "toolCall", id, name: AgentTool.NAME, arguments: AgentTool.args(run, dirs) });
1526
+ }
1527
+ }
1528
+ builder.done("toolUse");
1529
+ }
1530
+ async configure(session, model, options, signal) {
1531
+ try {
1532
+ if (model.id !== AgentCatalog.DEFAULT_MODEL) {
1533
+ await session.select("model", model.id, signal);
1534
+ }
1535
+ const level = options?.reasoning;
1536
+ if (level && model.reasoning) {
1537
+ const offered = Acp.values(Acp.optionOf(session.options, "thought_level")).map((value) => value.value);
1538
+ await session.select("thought_level", (THINKING[level] ?? [level]).find((value) => offered.includes(value)), signal);
1539
+ }
1540
+ } catch {}
1541
+ }
1542
+ static usage(turn) {
1543
+ const usage = emptyUsage();
1544
+ const { input, output, cacheRead, used } = turn.usage;
1545
+ usage.cacheRead = cacheRead ?? 0;
1546
+ usage.input = input !== undefined ? Math.max(0, input - usage.cacheRead) : used ?? 0;
1547
+ usage.output = output ?? 0;
1548
+ usage.totalTokens = usage.input + usage.output + usage.cacheRead;
1549
+ return usage;
1550
+ }
1551
+ static describe(config, error) {
1552
+ const { message, code } = error ?? {};
1553
+ if (code === Acp.AUTH_REQUIRED) {
1554
+ return text("signIn", config.name, config.login ?? config.command);
1555
+ }
1556
+ return message || String(error);
1557
+ }
1558
+ }
1559
+
1560
+ // src/extension.ts
1561
+ var TA_FILE_WRITE_EVENT = "ta:file-write";
1562
+ var ACTIVITY_ENTRY = "ta-agents.activity";
1563
+ var CONTEXT_WINDOW = 200000;
1564
+ var MAX_TOKENS = 32000;
1565
+ var INSTANCES = Symbol.for("ta-agents.instances");
1566
+ var Sessions;
1567
+ ((Sessions) => {
1568
+ function all() {
1569
+ const global = globalThis;
1570
+ const map = global[INSTANCES] ?? new Map;
1571
+ global[INSTANCES] = map;
1572
+ return map;
1573
+ }
1574
+ function set(id, instance) {
1575
+ all().set(id, instance);
1576
+ }
1577
+ Sessions.set = set;
1578
+ function remove(id, instance) {
1579
+ if (all().get(id) === instance) {
1580
+ all().delete(id);
1581
+ }
1582
+ }
1583
+ Sessions.remove = remove;
1584
+ function get(id) {
1585
+ return id ? all().get(id) : undefined;
1586
+ }
1587
+ Sessions.get = get;
1588
+ })(Sessions ||= {});
1589
+ function activate(pi, options = {}) {
1590
+ const find = options.find ?? Programs.find;
1591
+ const userAgents = options.userAgents ?? (() => {
1592
+ return;
1593
+ });
1594
+ const cache = options.cache ?? new ModelCache;
1595
+ const calls = new Map;
1596
+ let configs = [];
1597
+ let context;
1598
+ const ours = (model) => configs.find((config) => config.id === model?.provider);
1599
+ const providerModels = (config) => {
1600
+ const known = cache.get(config.id);
1601
+ const listed = [
1602
+ { id: AgentCatalog.DEFAULT_MODEL, name: config.name },
1603
+ ...(known?.models ?? []).filter((model) => model.id !== AgentCatalog.DEFAULT_MODEL).map((model) => ({ id: model.id, name: model.name }))
1604
+ ];
1605
+ return listed.map((model) => ({
1606
+ ...model,
1607
+ reasoning: known?.reasoning ?? false,
1608
+ input: ["text", "image"],
1609
+ cost: { ...emptyUsage().cost },
1610
+ contextWindow: known?.contextWindow ?? CONTEXT_WINDOW,
1611
+ maxTokens: MAX_TOKENS
1612
+ }));
1613
+ };
1614
+ const register = (config) => pi.registerProvider(config.id, {
1615
+ name: config.name,
1616
+ baseUrl: `acp://${config.id}`,
1617
+ apiKey: "acp",
1618
+ api: `acp-${config.id}`,
1619
+ streamSimple: (model, transcript, streamOptions) => {
1620
+ const owner = Sessions.get(streamOptions?.sessionId) ?? self;
1621
+ const own = owner.configs().find((candidate) => candidate.id === config.id) ?? config;
1622
+ return owner.streamer.stream(own, model, transcript, streamOptions);
1623
+ },
1624
+ models: providerModels(config)
1625
+ });
1626
+ const offer = (next) => {
1627
+ for (const config of configs) {
1628
+ if (!next.some((candidate) => candidate.id === config.id)) {
1629
+ pi.unregisterProvider(config.id);
1630
+ }
1631
+ }
1632
+ configs = next;
1633
+ configs.forEach(register);
1634
+ };
1635
+ const learn = (config, session, contextWindow) => {
1636
+ const option = Acp.optionOf(session.options, "model");
1637
+ const models = option ? Acp.values(option).map((value) => ({ id: value.value, name: value.name })) : (session.models?.availableModels ?? []).map((model) => ({ id: model.modelId, name: model.name }));
1638
+ const known = cache.get(config.id);
1639
+ const next = {
1640
+ models,
1641
+ reasoning: !!Acp.optionOf(session.options, "thought_level"),
1642
+ contextWindow: contextWindow ?? known?.contextWindow
1643
+ };
1644
+ if (cache.set(config.id, next)) {
1645
+ register(config);
1646
+ }
1647
+ };
1648
+ const toggleTool = (model) => {
1649
+ const active = pi.getActiveTools();
1650
+ const has = active.includes(AgentTool.NAME);
1651
+ if (ours(model) && !has) {
1652
+ pi.setActiveTools([...active, AgentTool.NAME]);
1653
+ } else if (!ours(model) && has) {
1654
+ pi.setActiveTools(active.filter((name) => name !== AgentTool.NAME));
1655
+ }
1656
+ };
1657
+ const bindings = new AgentBindings((binding) => pi.appendEntry(BINDING_ENTRY, binding), (config, session) => {
1658
+ session.callbacks = {
1659
+ permission: async (request) => {
1660
+ const ui = context?.hasUI ? context.ui : undefined;
1661
+ if (config.permissions !== "ask" || !ui) {
1662
+ return AgentSession.allow(request);
1663
+ }
1664
+ const chosen = await ui.select(`${config.name}: ${request.toolCall.title ?? "permission"}`, request.options.map((option2) => option2.name));
1665
+ const option = request.options.find((candidate) => candidate.name === chosen);
1666
+ return option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" };
1667
+ },
1668
+ title: (title) => {
1669
+ if (!pi.getSessionName()) {
1670
+ pi.setSessionName(title);
1671
+ }
1672
+ },
1673
+ activity: () => {
1674
+ if (context?.model?.provider === config.id) {
1675
+ pi.sendMessage({ customType: ACTIVITY_ENTRY, content: ACTIVITY_TEXT, display: false }, { triggerTurn: true });
1676
+ }
1677
+ },
1678
+ write: (path, before) => {
1679
+ const file = { path: resolve(context?.cwd ?? bindings.cwd, path), ...before !== undefined ? { before } : {} };
1680
+ pi.events.emit(TA_FILE_WRITE_EVENT, file);
1681
+ }
1682
+ };
1683
+ learn(config, session);
1684
+ }, options.agentOf);
1685
+ const streamer = new AgentStreamer({
1686
+ open: (config, signal) => bindings.open(config, signal),
1687
+ calls,
1688
+ ended: (config, session) => {
1689
+ if (session.title && !pi.getSessionName()) {
1690
+ pi.setSessionName(session.title);
1691
+ }
1692
+ const size = session.turn?.usage.size;
1693
+ if (size) {
1694
+ learn(config, session, size);
1695
+ }
1696
+ }
1697
+ });
1698
+ const self = { configs: () => configs, streamer };
1699
+ let sessionId;
1700
+ pi.registerTool(AgentTool.definition(calls));
1701
+ offer(AgentCatalog.agents(userAgents(), find));
1702
+ pi.on("session_start", (event, ctx) => {
1703
+ context = ctx;
1704
+ if (sessionId) {
1705
+ Sessions.remove(sessionId, self);
1706
+ }
1707
+ sessionId = ctx.sessionManager.getSessionId();
1708
+ Sessions.set(sessionId, self);
1709
+ bindings.cwd = ctx.cwd;
1710
+ bindings.restore(ctx.sessionManager.getBranch(), event.reason === "fork");
1711
+ const settings = pi.getSettings().agents;
1712
+ offer(AgentCatalog.agents(settings, find));
1713
+ toggleTool(ctx.model);
1714
+ });
1715
+ pi.on("model_select", (event) => toggleTool(event.model));
1716
+ pi.on("session_tree", () => bindings.forget());
1717
+ pi.on("session_before_compact", (event, ctx) => {
1718
+ if (!ours(ctx.model)) {
1719
+ return;
1720
+ }
1721
+ if (event.reason === "manual") {
1722
+ setTimeout(() => pi.sendUserMessage("/compact"), 0);
1723
+ }
1724
+ return { cancel: true };
1725
+ });
1726
+ pi.on("session_shutdown", () => {
1727
+ bindings.close();
1728
+ context = undefined;
1729
+ if (sessionId) {
1730
+ Sessions.remove(sessionId, self);
1731
+ }
1732
+ });
1733
+ }
1734
+ function agentDir(env = process.env) {
1735
+ let config = {};
1736
+ try {
1737
+ config = JSON.parse(readFileSync2(join3(env.PI_PACKAGE_DIR ?? "", "package.json"), "utf8")).piConfig ?? {};
1738
+ } catch {}
1739
+ const name = config.name || "pi";
1740
+ return env[`${name.toUpperCase()}_CODING_AGENT_DIR`] || join3(homedir3(), config.configDir || ".pi", "agent");
1741
+ }
1742
+ function readUserAgents(agentDir2) {
1743
+ try {
1744
+ return JSON.parse(readFileSync2(join3(agentDir2, "settings.json"), "utf8")).agents;
1745
+ } catch {
1746
+ return;
1747
+ }
1748
+ }
1749
+ function extension_default(pi) {
1750
+ activate(pi, { userAgents: () => readUserAgents(agentDir()) });
1751
+ }
1752
+ export {
1753
+ extension_default as default,
1754
+ agentDir,
1755
+ activate
1756
+ };