@celljs/ta-agents 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  // src/extension.ts
2
- import { readFileSync as readFileSync2 } from "node:fs";
2
+ import { readFileSync as readFileSync3 } from "node:fs";
3
3
  import { homedir as homedir3 } from "node:os";
4
- import { join as join3, resolve } from "node:path";
4
+ import { join as join4, resolve } from "node:path";
5
5
 
6
6
  // src/acp-protocol.ts
7
7
  var Acp;
@@ -55,6 +55,8 @@ import { spawn } from "node:child_process";
55
55
  import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
56
56
  import { homedir } from "node:os";
57
57
  import { delimiter, dirname, join } from "node:path";
58
+ var CLAUDE_ADAPTER = "@agentclientprotocol/claude-agent-acp@0.106.0";
59
+ var CODEX_ADAPTER = "@agentclientprotocol/codex-acp@2.6.0";
58
60
  var PRESETS = [
59
61
  {
60
62
  id: "codebuddy-code",
@@ -66,22 +68,42 @@ var PRESETS = [
66
68
  env: { CODEBUDDY_CODE_MODE_ENABLED: "1" },
67
69
  clientMeta: { "codebuddy.ai": { mainAgentSupport: true, toolModeSupport: true } },
68
70
  options: { mode: "fullAccess" },
69
- processPerSession: true
71
+ processPerSession: true,
72
+ install: { packages: ["@tencent-ai/codebuddy-code"], bin: "cbc", args: ["--acp"], login: ["cbc"] }
70
73
  },
71
74
  {
72
75
  id: "claude-code",
73
76
  name: "Claude Code",
74
77
  command: "npx",
75
- args: ["-y", "@agentclientprotocol/claude-agent-acp@0.106.0"],
78
+ args: ["-y", CLAUDE_ADAPTER],
76
79
  programs: ["claude"],
77
- login: "claude"
80
+ login: "claude",
81
+ install: {
82
+ packages: ["@anthropic-ai/claude-code", CLAUDE_ADAPTER],
83
+ bin: "claude-agent-acp",
84
+ args: [],
85
+ programs: { CLAUDE_CODE_EXECUTABLE: "claude" },
86
+ login: ["claude"]
87
+ }
78
88
  },
79
- { id: "codex", name: "Codex", command: "npx", args: ["-y", "@agentclientprotocol/codex-acp@2.6.0"], programs: ["codex"], login: "codex login" }
89
+ {
90
+ id: "codex",
91
+ name: "Codex",
92
+ command: "npx",
93
+ args: ["-y", CODEX_ADAPTER],
94
+ programs: ["codex"],
95
+ login: "codex login",
96
+ install: { packages: ["@openai/codex", CODEX_ADAPTER], bin: "codex-acp", args: [], programs: { CODEX_PATH: "codex" }, login: ["codex", "login"] }
97
+ }
80
98
  ];
81
99
  var AgentCatalog;
82
100
  ((AgentCatalog) => {
83
101
  AgentCatalog.DEFAULT_MODEL = "default";
84
- function agents(settings, find = Programs.find) {
102
+ function presets() {
103
+ return PRESETS.map(({ id, name, programs, install }) => ({ id, name, programs, install }));
104
+ }
105
+ AgentCatalog.presets = presets;
106
+ function agents(settings, find = Programs.find, local) {
85
107
  const configured = settings && typeof settings === "object" ? settings : {};
86
108
  const result = [];
87
109
  for (const preset of PRESETS) {
@@ -90,10 +112,12 @@ var AgentCatalog;
90
112
  continue;
91
113
  }
92
114
  const found = preset.programs.find((program) => find(program));
93
- if (!found && !setting) {
115
+ const installed = found ? undefined : localConfig(preset, local);
116
+ if (!found && !installed && !setting) {
94
117
  continue;
95
118
  }
96
- const { programs, ...config } = preset;
119
+ const { programs, install, ...plain } = preset;
120
+ const config = installed ?? plain;
97
121
  const command = programs.includes(config.command) && found ? found : config.command;
98
122
  const own = setting || {};
99
123
  result.push({
@@ -113,9 +137,45 @@ var AgentCatalog;
113
137
  return result;
114
138
  }
115
139
  AgentCatalog.agents = agents;
140
+ function localConfig(preset, local) {
141
+ const { programs, install, command: _npx, ...config } = preset;
142
+ const command = local?.bin(install.bin);
143
+ if (!local || !command) {
144
+ return;
145
+ }
146
+ const env = { ...config.env };
147
+ for (const [name, program] of Object.entries(install.programs ?? {})) {
148
+ const path2 = local.bin(program);
149
+ if (path2) {
150
+ env[name] = path2;
151
+ }
152
+ }
153
+ const path = local.path();
154
+ if (path) {
155
+ env.PATH = path;
156
+ }
157
+ const [login, ...loginArgs] = install.login;
158
+ const loginPath = local.bin(login);
159
+ return {
160
+ ...config,
161
+ command,
162
+ args: install.args,
163
+ env,
164
+ login: loginPath ? Programs.commandLine([loginPath, ...loginArgs]) : config.login
165
+ };
166
+ }
116
167
  })(AgentCatalog ||= {});
117
168
  var Programs;
118
169
  ((Programs) => {
170
+ function commandLine(words, platform = process.platform) {
171
+ return words.map((word) => {
172
+ if (/^[\w@%+=:,./\\-]+$/.test(word)) {
173
+ return word;
174
+ }
175
+ return platform === "win32" ? `"${word}"` : `'${word.replace(/'/g, `'\\''`)}'`;
176
+ }).join(" ");
177
+ }
178
+ Programs.commandLine = commandLine;
119
179
  function find(program, path = process.env.PATH) {
120
180
  const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
121
181
  for (const dir of (path ?? "").split(delimiter)) {
@@ -175,6 +235,116 @@ class ModelCache {
175
235
  }
176
236
  }
177
237
 
238
+ // src/agent-prompt.ts
239
+ var ACTIVITY_TEXT = "[The agent continued on its own]";
240
+ var TRANSCRIPT_CHARS = 30000;
241
+ var AgentPrompt;
242
+ ((AgentPrompt) => {
243
+ function pending(messages) {
244
+ const result = [];
245
+ for (let index = messages.length - 1;index >= 0; index--) {
246
+ const message = messages[index];
247
+ if (message.role === "system") {
248
+ continue;
249
+ }
250
+ if (message.role !== "user") {
251
+ break;
252
+ }
253
+ if (text(message) !== ACTIVITY_TEXT) {
254
+ result.unshift(message);
255
+ }
256
+ }
257
+ return result;
258
+ }
259
+ AgentPrompt.pending = pending;
260
+ function written(messages, at) {
261
+ return messages.filter((message) => message.role === "user" && at.includes(message.timestamp ?? -1));
262
+ }
263
+ AgentPrompt.written = written;
264
+ function toolsNote(server) {
265
+ return `<ta-tools>
266
+ The tools of Ta named in these notes and in your role are those of the MCP server "${server}" you have (mcp__${server}__<name>): call them as your own.
267
+ </ta-tools>`;
268
+ }
269
+ AgentPrompt.toolsNote = toolsNote;
270
+ function resume(error) {
271
+ return `Your last turn stopped with an error before it finished: ${error}
272
+ Continue where you left off.`;
273
+ }
274
+ AgentPrompt.resume = resume;
275
+ function blocks(messages, images) {
276
+ const result = [];
277
+ for (const message of messages) {
278
+ if (message.role !== "user") {
279
+ continue;
280
+ }
281
+ if (typeof message.content === "string") {
282
+ result.push({ type: "text", text: message.content });
283
+ continue;
284
+ }
285
+ for (const part of message.content) {
286
+ if (part.type === "text") {
287
+ result.push({ type: "text", text: part.text });
288
+ } else if (images) {
289
+ result.push({ type: "image", data: part.data, mimeType: part.mimeType });
290
+ } else {
291
+ result.push({ type: "text", text: "[An image the agent cannot take was left out]" });
292
+ }
293
+ }
294
+ }
295
+ return result;
296
+ }
297
+ AgentPrompt.blocks = blocks;
298
+ function transcript(messages, pendingCount) {
299
+ const earlier = messages.filter((message) => (message.role === "user" || message.role === "assistant") && text(message) !== ACTIVITY_TEXT);
300
+ const lines = [];
301
+ for (const message of earlier.slice(0, Math.max(0, earlier.length - pendingCount))) {
302
+ const content = text(message).trim();
303
+ if (content) {
304
+ lines.push(`${message.role === "user" ? "User" : "Assistant"}: ${content}`);
305
+ }
306
+ }
307
+ if (!lines.length) {
308
+ return;
309
+ }
310
+ const body = lines.join(`
311
+
312
+ `);
313
+ const kept = body.length > TRANSCRIPT_CHARS ? `…${body.slice(-TRANSCRIPT_CHARS)}` : body;
314
+ return `<earlier_conversation>
315
+ The user talked with another assistant before you joined; this is what was said:
316
+
317
+ ${kept}
318
+ </earlier_conversation>`;
319
+ }
320
+ AgentPrompt.transcript = transcript;
321
+ function noteTitle(title) {
322
+ return /^<(?:ta-[\w-]+|skills|addendum|earlier_conversation|context)>/.test(title.trim());
323
+ }
324
+ AgentPrompt.noteTitle = noteTitle;
325
+ function notes(messages) {
326
+ const system = messages.filter((message) => message.role === "system").map((message) => [text(message), ...sections(message)].join(`
327
+ `)).join(`
328
+ `);
329
+ return [...system.matchAll(/^<(ta-[\w-]+|skills|addendum)>[\s\S]*?<\/\1>$/gm)].map((match) => match[0]);
330
+ }
331
+ AgentPrompt.notes = notes;
332
+ function sections(message) {
333
+ const parts = message.sections ?? {};
334
+ return Object.values(parts).filter((part) => typeof part === "string");
335
+ }
336
+ function text(message) {
337
+ if (message.role === "user" || message.role === "system") {
338
+ return typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? part.text : "").join("");
339
+ }
340
+ if (message.role === "assistant") {
341
+ return message.content.map((part) => part.type === "text" ? part.text : "").join("");
342
+ }
343
+ return "";
344
+ }
345
+ AgentPrompt.text = text;
346
+ })(AgentPrompt ||= {});
347
+
178
348
  // src/agent-turn.ts
179
349
  var OUTPUT_CHARS = 8000;
180
350
  var WRITING_KINDS = new Set(["edit", "delete", "move"]);
@@ -581,7 +751,7 @@ class AgentSession {
581
751
  return;
582
752
  case "session_info_update": {
583
753
  const title = update.title;
584
- if (typeof title === "string" && title.trim() && title.trim() !== this.title) {
754
+ if (typeof title === "string" && title.trim() && title.trim() !== this.title && !AgentPrompt.noteTitle(title)) {
585
755
  this.title = title.trim();
586
756
  this.callbacks.title?.(this.title);
587
757
  }
@@ -1010,6 +1180,12 @@ var TEXTS = {
1010
1180
  "zh-TW": (agent) => `${agent} 只能在這台電腦上的目錄裡工作,暫不支援遠端目錄。`,
1011
1181
  "ja-JP": (agent) => `${agent} はこのコンピュータのディレクトリでのみ動作します。リモートディレクトリはまだサポートしていません。`
1012
1182
  },
1183
+ narrowed: {
1184
+ "en-US": (agent) => `${agent} works with its own tools (files, commands), and this conversation may use only some of Ta's: pick a model of Ta for it.`,
1185
+ "zh-CN": (agent) => `${agent} 用自己的工具读写文件、跑命令,这个对话只能用 Ta 给的几样工具,所以用不了它:请给它换一个 Ta 的模型。`,
1186
+ "zh-TW": (agent) => `${agent} 用自己的工具讀寫檔案、執行命令,這個對話只能用 Ta 給的幾樣工具,所以用不了它:請給它換一個 Ta 的模型。`,
1187
+ "ja-JP": (agent) => `${agent} は自分のツールでファイルやコマンドを扱います。この会話は Ta のツールの一部しか使えないため、${agent} は使えません。Ta のモデルに切り替えてください。`
1188
+ },
1013
1189
  signIn: {
1014
1190
  "en-US": (agent, command) => `${agent} is not signed in. Run \`${command}\` in a terminal to sign in, then try again.`,
1015
1191
  "zh-CN": (agent, command) => `${agent} 还没有登录。请在终端里运行 \`${command}\` 登录后再试。`,
@@ -1064,6 +1240,28 @@ var TEXTS = {
1064
1240
  "zh-TW": (agent, command) => `${agent}:找不到指令 \`${command}\`。請先安裝,或在 settings.json 的 \`agents\` 裡指定它的指令。`,
1065
1241
  "ja-JP": (agent, command) => `${agent}:コマンド \`${command}\` が見つかりません。インストールするか、settings.json の \`agents\` でそのコマンドを設定してください。`
1066
1242
  },
1243
+ needNode: {
1244
+ "en-US": (major) => `Installing needs Node.js ${major} or newer, which this computer does not have. Install Node.js from nodejs.org, then try again.`,
1245
+ "zh-CN": (major) => `安装需要 Node.js ${major} 或更新版本,这台电脑上没有。请先从 nodejs.org 安装 Node.js,再试一次。`,
1246
+ "zh-TW": (major) => `安裝需要 Node.js ${major} 或更新版本,這台電腦上沒有。請先從 nodejs.org 安裝 Node.js,再試一次。`,
1247
+ "ja-JP": (major) => `インストールには Node.js ${major} 以降が必要ですが、このコンピュータにはありません。nodejs.org から Node.js をインストールしてから、もう一度試してください。`
1248
+ },
1249
+ installFailed: {
1250
+ "en-US": (detail) => `Could not install it. npm said:
1251
+ ${detail}`,
1252
+ "zh-CN": (detail) => `没能装上。npm 的输出:
1253
+ ${detail}`,
1254
+ "zh-TW": (detail) => `沒能裝上。npm 的輸出:
1255
+ ${detail}`,
1256
+ "ja-JP": (detail) => `インストールできませんでした。npm の出力:
1257
+ ${detail}`
1258
+ },
1259
+ unknownAgent: {
1260
+ "en-US": (id) => `Ta cannot install the agent ${id}.`,
1261
+ "zh-CN": (id) => `Ta 不能安装 ${id} 这个 Agent。`,
1262
+ "zh-TW": (id) => `Ta 不能安裝 ${id} 這個 Agent。`,
1263
+ "ja-JP": (id) => `Ta はエージェント ${id} をインストールできません。`
1264
+ },
1067
1265
  exited: {
1068
1266
  "en-US": (agent, code, last) => `${agent} exited (${code})${last ? `: ${last}` : ""}`,
1069
1267
  "zh-CN": (agent, code, last) => `${agent} 已退出(${code})${last ? `:${last}` : ""}`,
@@ -1166,15 +1364,15 @@ class AcpAgent {
1166
1364
  this.starting.catch(() => this.starting = undefined);
1167
1365
  return this.starting;
1168
1366
  }
1169
- async newSession(cwd, signal) {
1170
- await this.start();
1171
- const setup = await this.request("session/new", { cwd, mcpServers: [] }, signal);
1367
+ async newSession(cwd, signal, servers = []) {
1368
+ const init = await this.start();
1369
+ const setup = await this.request("session/new", { cwd, mcpServers: AcpAgent.reachable(init, servers) }, signal);
1172
1370
  if (!setup?.sessionId) {
1173
1371
  throw new Error(`${this.name} did not open a session`);
1174
1372
  }
1175
1373
  return this.add(setup.sessionId, setup);
1176
1374
  }
1177
- async loadSession(id, cwd, signal) {
1375
+ async loadSession(id, cwd, signal, servers = []) {
1178
1376
  const known = this.sessions.get(id);
1179
1377
  if (known) {
1180
1378
  return known;
@@ -1184,7 +1382,7 @@ class AcpAgent {
1184
1382
  return;
1185
1383
  }
1186
1384
  try {
1187
- const setup = await this.request("session/load", { sessionId: id, cwd, mcpServers: [] }, signal);
1385
+ const setup = await this.request("session/load", { sessionId: id, cwd, mcpServers: AcpAgent.reachable(init, servers) }, signal);
1188
1386
  return this.add(id, setup ?? {});
1189
1387
  } catch (error) {
1190
1388
  if (error instanceof JsonRpcError && error.code !== Acp.AUTH_REQUIRED) {
@@ -1193,6 +1391,9 @@ class AcpAgent {
1193
1391
  throw error;
1194
1392
  }
1195
1393
  }
1394
+ static reachable(init, servers) {
1395
+ return init?.agentCapabilities?.mcpCapabilities?.http ? servers : [];
1396
+ }
1196
1397
  async authenticate(methodId, page, signal) {
1197
1398
  await this.start();
1198
1399
  this.signInPage = page;
@@ -1393,6 +1594,7 @@ class AgentBindings {
1393
1594
  release;
1394
1595
  cwd = process.cwd();
1395
1596
  owner;
1597
+ servers = async () => [];
1396
1598
  ids = new Map;
1397
1599
  waiting = new Map;
1398
1600
  opened = new Map;
@@ -1461,10 +1663,11 @@ class AgentBindings {
1461
1663
  throw new Error(text("remote", config.name));
1462
1664
  }
1463
1665
  const known = this.ids.get(config.id);
1464
- let session = known ? await agent.loadSession(known, this.cwd, signal) : undefined;
1666
+ const servers = await this.servers();
1667
+ let session = known ? await agent.loadSession(known, this.cwd, signal, servers) : undefined;
1465
1668
  const fresh = !session;
1466
1669
  if (!session) {
1467
- session = await agent.newSession(this.cwd, signal);
1670
+ session = await agent.newSession(this.cwd, signal, servers);
1468
1671
  for (const [option, value] of Object.entries(config.options ?? {})) {
1469
1672
  await session.select(option, value, signal).catch(() => {
1470
1673
  return;
@@ -1493,105 +1696,213 @@ class AgentBindings {
1493
1696
  }
1494
1697
  }
1495
1698
 
1496
- // src/agent-prompt.ts
1497
- var ACTIVITY_TEXT = "[The agent continued on its own]";
1498
- var TRANSCRIPT_CHARS = 30000;
1499
- var AgentPrompt;
1500
- ((AgentPrompt) => {
1501
- function pending(messages) {
1502
- const result = [];
1503
- for (let index = messages.length - 1;index >= 0; index--) {
1504
- const message = messages[index];
1505
- if (message.role === "system") {
1506
- continue;
1507
- }
1508
- if (message.role !== "user") {
1509
- break;
1510
- }
1511
- if (text2(message) !== ACTIVITY_TEXT) {
1512
- result.unshift(message);
1513
- }
1699
+ // src/agent-installs.ts
1700
+ import { readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
1701
+ import { delimiter as delimiter2, join as join3 } from "node:path";
1702
+
1703
+ class AgentInstalls {
1704
+ dir;
1705
+ platform;
1706
+ static DIR = "coding-agents";
1707
+ constructor(dir, platform = process.platform) {
1708
+ this.dir = dir;
1709
+ this.platform = platform;
1710
+ }
1711
+ static of(agentDir) {
1712
+ return new AgentInstalls(join3(agentDir, AgentInstalls.DIR));
1713
+ }
1714
+ get binDir() {
1715
+ return join3(this.dir, "node_modules", ".bin");
1716
+ }
1717
+ get nodeDir() {
1718
+ return join3(this.dir, "node");
1719
+ }
1720
+ bin(name) {
1721
+ const file = join3(this.binDir, this.platform === "win32" ? `${name}.cmd` : name);
1722
+ return isFile(file) ? file : undefined;
1723
+ }
1724
+ nodeBin() {
1725
+ const bin = join3(this.nodeDir, "bin");
1726
+ return isFile(join3(bin, "node")) ? bin : undefined;
1727
+ }
1728
+ path(env = process.env) {
1729
+ const bin = this.nodeBin();
1730
+ return bin ? [bin, env.PATH].filter(Boolean).join(delimiter2) : undefined;
1731
+ }
1732
+ version(spec) {
1733
+ try {
1734
+ return JSON.parse(readFileSync2(join3(this.dir, "node_modules", AgentInstalls.packageName(spec), "package.json"), "utf8")).version;
1735
+ } catch {
1736
+ return;
1514
1737
  }
1515
- return result;
1516
1738
  }
1517
- AgentPrompt.pending = pending;
1518
- function written(messages, at) {
1519
- return messages.filter((message) => message.role === "user" && at.includes(message.timestamp ?? -1));
1739
+ static packageName(spec) {
1740
+ const at = spec.indexOf("@", 1);
1741
+ return at > 0 ? spec.slice(0, at) : spec;
1520
1742
  }
1521
- AgentPrompt.written = written;
1522
- function resume(error) {
1523
- return `Your last turn stopped with an error before it finished: ${error}
1524
- Continue where you left off.`;
1743
+ }
1744
+ function isFile(path) {
1745
+ try {
1746
+ return statSync2(path).isFile();
1747
+ } catch {
1748
+ return false;
1525
1749
  }
1526
- AgentPrompt.resume = resume;
1527
- function blocks(messages, images) {
1528
- const result = [];
1529
- for (const message of messages) {
1530
- if (message.role !== "user") {
1531
- continue;
1532
- }
1533
- if (typeof message.content === "string") {
1534
- result.push({ type: "text", text: message.content });
1535
- continue;
1536
- }
1537
- for (const part of message.content) {
1538
- if (part.type === "text") {
1539
- result.push({ type: "text", text: part.text });
1540
- } else if (images) {
1541
- result.push({ type: "image", data: part.data, mimeType: part.mimeType });
1542
- } else {
1543
- result.push({ type: "text", text: "[An image the agent cannot take was left out]" });
1544
- }
1545
- }
1750
+ }
1751
+
1752
+ // src/agent-mcp.ts
1753
+ import { randomBytes } from "node:crypto";
1754
+ import { createServer } from "node:http";
1755
+ var MAX_BODY = 1 << 20;
1756
+ var PROTOCOL = "2025-06-18";
1757
+
1758
+ class AgentMcp {
1759
+ static NAME = "ta";
1760
+ server;
1761
+ listening;
1762
+ sessions = new Map;
1763
+ async add(tools) {
1764
+ const port = await this.listen();
1765
+ const token = randomBytes(24).toString("base64url");
1766
+ this.sessions.set(token, tools);
1767
+ return {
1768
+ server: { type: "http", name: AgentMcp.NAME, url: `http://127.0.0.1:${port}/mcp/${token}`, headers: [] },
1769
+ remove: () => this.sessions.delete(token)
1770
+ };
1771
+ }
1772
+ close() {
1773
+ this.server?.closeAllConnections();
1774
+ this.server?.close();
1775
+ this.server = undefined;
1776
+ this.listening = undefined;
1777
+ }
1778
+ listen() {
1779
+ if (!this.listening) {
1780
+ this.listening = new Promise((resolve, reject) => {
1781
+ const server = createServer((request, response) => void this.handle(request, response));
1782
+ server.once("error", reject);
1783
+ server.listen(0, "127.0.0.1", () => resolve(server.address().port));
1784
+ server.unref();
1785
+ this.server = server;
1786
+ });
1787
+ this.listening.catch(() => this.listening = undefined);
1546
1788
  }
1547
- return result;
1789
+ return this.listening;
1548
1790
  }
1549
- AgentPrompt.blocks = blocks;
1550
- function transcript(messages, pendingCount) {
1551
- const earlier = messages.filter((message) => (message.role === "user" || message.role === "assistant") && text2(message) !== ACTIVITY_TEXT);
1552
- const lines = [];
1553
- for (const message of earlier.slice(0, Math.max(0, earlier.length - pendingCount))) {
1554
- const content = text2(message).trim();
1555
- if (content) {
1556
- lines.push(`${message.role === "user" ? "User" : "Assistant"}: ${content}`);
1557
- }
1791
+ async handle(request, response) {
1792
+ const tools = this.sessions.get(AgentMcp.token(request.url));
1793
+ const port = this.server?.address()?.port;
1794
+ if (!tools || request.headers.origin !== undefined || request.headers.host !== `127.0.0.1:${port}`) {
1795
+ response.writeHead(404).end();
1796
+ return;
1558
1797
  }
1559
- if (!lines.length) {
1798
+ if (request.method !== "POST") {
1799
+ response.writeHead(405, { allow: "POST" }).end();
1560
1800
  return;
1561
1801
  }
1562
- const body = lines.join(`
1563
-
1564
- `);
1565
- const kept = body.length > TRANSCRIPT_CHARS ? `…${body.slice(-TRANSCRIPT_CHARS)}` : body;
1566
- return `<earlier_conversation>
1567
- The user talked with another assistant before you joined; this is what was said:
1568
-
1569
- ${kept}
1570
- </earlier_conversation>`;
1802
+ let message;
1803
+ try {
1804
+ message = JSON.parse(await AgentMcp.body(request));
1805
+ } catch {
1806
+ AgentMcp.reply(response, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
1807
+ return;
1808
+ }
1809
+ if (message.id === undefined) {
1810
+ response.writeHead(202).end();
1811
+ return;
1812
+ }
1813
+ const answer = (result) => AgentMcp.reply(response, { jsonrpc: "2.0", id: message.id, result });
1814
+ const fail = (code, text2) => AgentMcp.reply(response, { jsonrpc: "2.0", id: message.id, error: { code, message: text2 } });
1815
+ switch (message.method) {
1816
+ case "initialize": {
1817
+ const asked = message.params?.protocolVersion;
1818
+ answer({
1819
+ protocolVersion: typeof asked === "string" ? asked : PROTOCOL,
1820
+ capabilities: { tools: {} },
1821
+ serverInfo: { name: "Ta", version: "1" }
1822
+ });
1823
+ return;
1824
+ }
1825
+ case "ping":
1826
+ answer({});
1827
+ return;
1828
+ case "tools/list":
1829
+ answer({ tools: tools.list() });
1830
+ return;
1831
+ case "tools/call": {
1832
+ const name = message.params?.name;
1833
+ const args = message.params?.arguments;
1834
+ if (typeof name !== "string" || !tools.list().some((tool) => tool.name === name)) {
1835
+ fail(-32602, `Unknown tool: ${String(name)}`);
1836
+ return;
1837
+ }
1838
+ const aborted = new AbortController;
1839
+ const stop = () => aborted.abort();
1840
+ response.once("close", stop);
1841
+ try {
1842
+ answer(await tools.call(name, args && typeof args === "object" ? args : {}, aborted.signal));
1843
+ } catch (error) {
1844
+ answer({ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true });
1845
+ } finally {
1846
+ response.off("close", stop);
1847
+ }
1848
+ return;
1849
+ }
1850
+ default:
1851
+ fail(-32601, `Method not found: ${String(message.method)}`);
1852
+ }
1571
1853
  }
1572
- AgentPrompt.transcript = transcript;
1573
- function notes(messages) {
1574
- const system = messages.filter((message) => message.role === "system").map((message) => [text2(message), ...sections(message)].join(`
1575
- `)).join(`
1576
- `);
1577
- return [...system.matchAll(/^<(ta-[\w-]+|skills)>[\s\S]*?<\/\1>$/gm)].map((match) => match[0]);
1854
+ static token(url) {
1855
+ const match = /^\/mcp\/([\w-]+)$/.exec((url ?? "").split("?")[0]);
1856
+ return match?.[1] ?? "";
1578
1857
  }
1579
- AgentPrompt.notes = notes;
1580
- function sections(message) {
1581
- const parts = message.sections ?? {};
1582
- return Object.values(parts).filter((part) => typeof part === "string");
1858
+ static body(request) {
1859
+ return new Promise((resolve, reject) => {
1860
+ const chunks = [];
1861
+ let size = 0;
1862
+ request.on("data", (chunk) => {
1863
+ size += chunk.length;
1864
+ if (size > MAX_BODY) {
1865
+ reject(new Error("Too large"));
1866
+ request.destroy();
1867
+ return;
1868
+ }
1869
+ chunks.push(chunk);
1870
+ });
1871
+ request.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
1872
+ request.on("error", reject);
1873
+ });
1583
1874
  }
1584
- function text2(message) {
1585
- if (message.role === "user" || message.role === "system") {
1586
- return typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? part.text : "").join("");
1875
+ static reply(response, body) {
1876
+ if (!response.writableEnded && !response.destroyed) {
1877
+ response.writeHead(200, { "content-type": "application/json", connection: "close" }).end(JSON.stringify(body));
1587
1878
  }
1588
- if (message.role === "assistant") {
1589
- return message.content.map((part) => part.type === "text" ? part.text : "").join("");
1879
+ }
1880
+ }
1881
+
1882
+ // src/agent-refresh.ts
1883
+ var REFRESH = Symbol.for("ta-agents.refresh");
1884
+ var AgentRefresh;
1885
+ ((AgentRefresh) => {
1886
+ function all() {
1887
+ const global = globalThis;
1888
+ const set = global[REFRESH] ?? new Set;
1889
+ global[REFRESH] = set;
1890
+ return set;
1891
+ }
1892
+ function add(refresh) {
1893
+ all().add(refresh);
1894
+ return () => all().delete(refresh);
1895
+ }
1896
+ AgentRefresh.add = add;
1897
+ function run() {
1898
+ for (const refresh of all()) {
1899
+ try {
1900
+ refresh();
1901
+ } catch {}
1590
1902
  }
1591
- return "";
1592
1903
  }
1593
- AgentPrompt.text = text2;
1594
- })(AgentPrompt ||= {});
1904
+ AgentRefresh.run = run;
1905
+ })(AgentRefresh ||= {});
1595
1906
 
1596
1907
  // src/agent-sign-in.ts
1597
1908
  class AgentSignIn {
@@ -1707,7 +2018,7 @@ var AgentTool;
1707
2018
  return result;
1708
2019
  }
1709
2020
  AgentTool.input = input;
1710
- function definition(calls) {
2021
+ function definition(calls, tools) {
1711
2022
  return {
1712
2023
  name: AgentTool.NAME,
1713
2024
  label: "Agent tool",
@@ -1724,12 +2035,17 @@ var AgentTool;
1724
2035
  exposure: "direct",
1725
2036
  defaultActive: false,
1726
2037
  annotations: { readOnlyHint: true },
1727
- async execute(toolCallId, _params, signal) {
2038
+ async execute(toolCallId, _params, signal, _update, ctx) {
1728
2039
  const call = calls.get(toolCallId);
1729
2040
  if (!call) {
1730
2041
  return { content: [{ type: "text", text: "This call ran in an earlier run of the agent." }], details: {} };
1731
2042
  }
1732
- const run = await call.turn.waitTool(toolCallId, signal);
2043
+ const waited = call.turn.waitTool(toolCallId, signal);
2044
+ const execute = ctx?.executeTool;
2045
+ if (tools && execute) {
2046
+ await tools.serve((name, args2, aborted) => execute.call(ctx, name, args2, { signal: aborted }), waited, signal);
2047
+ }
2048
+ const run = await waited;
1733
2049
  if (signal?.aborted) {
1734
2050
  call.session.abandon(call.turn);
1735
2051
  calls.delete(toolCallId);
@@ -1909,6 +2225,9 @@ class AgentStreamer {
1909
2225
  }
1910
2226
  async run(config, model, context, options, builder) {
1911
2227
  const signal = options?.signal;
2228
+ if (this.host.narrowed?.()) {
2229
+ throw new Error(text("narrowed", config.name));
2230
+ }
1912
2231
  let signedIn = false;
1913
2232
  const signIn = async (error) => {
1914
2233
  if (signedIn || !AgentSignIn.required(error) || !await this.host.signIn?.(config, signal)) {
@@ -1957,7 +2276,7 @@ class AgentStreamer {
1957
2276
  if (earlier) {
1958
2277
  prompt = [{ type: "text", text: earlier }, ...prompt];
1959
2278
  }
1960
- const notes = AgentPrompt.notes(context.messages).filter((note) => !session.told.has(note));
2279
+ const notes = [...AgentPrompt.notes(context.messages), ...this.host.notes?.() ?? []].filter((note) => !session.told.has(note));
1961
2280
  if (notes.length) {
1962
2281
  for (const note of notes) {
1963
2282
  session.told.add(note);
@@ -2072,12 +2391,127 @@ class AgentStreamer {
2072
2391
  }
2073
2392
  }
2074
2393
 
2394
+ // src/agent-tool-calls.ts
2395
+ var UNTAKEN_MS = 60000;
2396
+
2397
+ class AgentToolCalls {
2398
+ tools;
2399
+ active;
2400
+ waiting = [];
2401
+ wakers = new Set;
2402
+ constructor(tools, active) {
2403
+ this.tools = tools;
2404
+ this.active = active;
2405
+ }
2406
+ list() {
2407
+ const active = new Set(this.active());
2408
+ return this.tools().filter((tool) => AgentToolCalls.offered(tool, active)).map((tool) => ({
2409
+ name: tool.name,
2410
+ description: tool.description ?? "",
2411
+ inputSchema: AgentToolCalls.schema(tool.parameters)
2412
+ }));
2413
+ }
2414
+ call(name, args, signal) {
2415
+ return new Promise((resolve) => {
2416
+ const timer = setTimeout(() => settle({ content: [{ type: "text", text: `Ta could not run ${name} now: no turn of Ta is waiting for you.` }], isError: true }), UNTAKEN_MS);
2417
+ timer.unref?.();
2418
+ const waiting = { name, args, signal, resolve: (result) => settle(result) };
2419
+ const settle = (result) => {
2420
+ clearTimeout(timer);
2421
+ const index = this.waiting.indexOf(waiting);
2422
+ if (index >= 0) {
2423
+ this.waiting.splice(index, 1);
2424
+ }
2425
+ resolve(result);
2426
+ };
2427
+ signal.addEventListener("abort", () => settle({ content: [{ type: "text", text: "Cancelled" }], isError: true }), { once: true });
2428
+ this.waiting.push(waiting);
2429
+ for (const wake of this.wakers) {
2430
+ wake();
2431
+ }
2432
+ });
2433
+ }
2434
+ get pending() {
2435
+ return this.waiting.length > 0;
2436
+ }
2437
+ async serve(run, until, signal) {
2438
+ let done = false;
2439
+ until.finally(() => done = true).catch(() => {
2440
+ return;
2441
+ });
2442
+ const taken = [];
2443
+ while (!done && !signal?.aborted) {
2444
+ const next = this.waiting.shift();
2445
+ if (next) {
2446
+ taken.push(this.runOne(run, next));
2447
+ continue;
2448
+ }
2449
+ let wake = () => {
2450
+ return;
2451
+ };
2452
+ const woken = new Promise((resolve) => {
2453
+ wake = resolve;
2454
+ });
2455
+ this.wakers.add(wake);
2456
+ try {
2457
+ await Promise.race([
2458
+ until.then(() => {
2459
+ return;
2460
+ }, () => {
2461
+ return;
2462
+ }),
2463
+ woken
2464
+ ]);
2465
+ } finally {
2466
+ this.wakers.delete(wake);
2467
+ }
2468
+ }
2469
+ await Promise.all(taken);
2470
+ }
2471
+ async runOne(run, call) {
2472
+ if (call.signal.aborted) {
2473
+ return;
2474
+ }
2475
+ try {
2476
+ const outcome = await run(call.name, call.args, call.signal);
2477
+ const content = (outcome.result?.content ?? []).filter((part) => part.type === "text" || part.type === "image");
2478
+ call.resolve({ content: content.length ? content : [{ type: "text", text: "(no output)" }], ...outcome.isError ? { isError: true } : {} });
2479
+ } catch (error) {
2480
+ call.resolve({ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true });
2481
+ }
2482
+ }
2483
+ static offered(tool, active) {
2484
+ if (tool.name === AgentTool.NAME || tool.sourceInfo?.source === "builtin") {
2485
+ return false;
2486
+ }
2487
+ switch (tool.exposure ?? "direct") {
2488
+ case "direct":
2489
+ return active.has(tool.name);
2490
+ case "codemode":
2491
+ case "deferred":
2492
+ return true;
2493
+ default:
2494
+ return false;
2495
+ }
2496
+ }
2497
+ static schema(parameters) {
2498
+ const schema = parameters && typeof parameters === "object" ? JSON.parse(JSON.stringify(parameters)) : {};
2499
+ return schema.type === "object" ? schema : { type: "object", properties: {} };
2500
+ }
2501
+ }
2502
+
2075
2503
  // src/extension.ts
2076
2504
  var TA_FILE_WRITE_EVENT = "ta:file-write";
2077
2505
  var ACTIVITY_ENTRY = "ta-agents.activity";
2078
2506
  var CONTEXT_WINDOW = 200000;
2079
2507
  var MAX_TOKENS = 32000;
2080
2508
  var INSTANCES = Symbol.for("ta-agents.instances");
2509
+ var MCP = Symbol.for("ta-agents.mcp");
2510
+ function mcp() {
2511
+ const global = globalThis;
2512
+ global[MCP] ??= new AgentMcp;
2513
+ return global[MCP];
2514
+ }
2081
2515
  var Sessions;
2082
2516
  ((Sessions) => {
2083
2517
  function all() {
@@ -2110,6 +2544,7 @@ function activate(pi, options = {}) {
2110
2544
  const calls = new Map;
2111
2545
  let configs = [];
2112
2546
  let context;
2547
+ let settings = userAgents;
2113
2548
  const ours = (model) => configs.find((config) => config.id === model?.provider);
2114
2549
  const providerModels = (config) => {
2115
2550
  const known = cache.get(config.id);
@@ -2228,6 +2663,8 @@ function activate(pi, options = {}) {
2228
2663
  const ui = context?.hasUI ? context.ui : undefined;
2229
2664
  return ui ? new AgentSignIn(config, bindings.agent(config), ui).run(signal) : Promise.resolve(false);
2230
2665
  },
2666
+ narrowed: () => !pi.getActiveTools().includes(AgentTool.NAME),
2667
+ notes: () => served && tools.list().length ? [AgentPrompt.toolsNote(AgentMcp.NAME)] : [],
2231
2668
  ended: (config, session) => {
2232
2669
  if (session.title && !pi.getSessionName()) {
2233
2670
  pi.setSessionName(session.title);
@@ -2240,8 +2677,22 @@ function activate(pi, options = {}) {
2240
2677
  });
2241
2678
  const self = { configs: () => configs, streamer };
2242
2679
  let sessionId;
2243
- pi.registerTool(AgentTool.definition(calls));
2244
- offer(AgentCatalog.agents(userAgents(), find));
2680
+ const tools = new AgentToolCalls(() => pi.getAllTools(), () => pi.getActiveTools());
2681
+ let served;
2682
+ bindings.servers = async () => {
2683
+ served ??= (options.mcp ?? mcp()).add(tools);
2684
+ return [(await served).server];
2685
+ };
2686
+ const unserve = () => {
2687
+ served?.then(({ remove }) => remove()).catch(() => {
2688
+ return;
2689
+ });
2690
+ served = undefined;
2691
+ };
2692
+ pi.registerTool(AgentTool.definition(calls, tools));
2693
+ const offerAll = () => offer(AgentCatalog.agents(settings(), find, options.local));
2694
+ offerAll();
2695
+ const stopRefresh = AgentRefresh.add(offerAll);
2245
2696
  pi.on("session_start", (event, ctx) => {
2246
2697
  context = ctx;
2247
2698
  if (sessionId) {
@@ -2255,8 +2706,12 @@ function activate(pi, options = {}) {
2255
2706
  }
2256
2707
  bindings.cwd = ctx.cwd;
2257
2708
  bindings.restore(ctx.sessionManager.getBranch(), event.reason === "fork");
2258
- const settings = pi.getSettings().agents;
2259
- offer(AgentCatalog.agents(settings, find));
2709
+ const name = pi.getSessionName();
2710
+ if (name && AgentPrompt.noteTitle(name)) {
2711
+ pi.setSessionName("");
2712
+ }
2713
+ settings = () => pi.getSettings().agents;
2714
+ offerAll();
2260
2715
  toggleTool(ctx.model);
2261
2716
  });
2262
2717
  pi.on("model_select", (event) => toggleTool(event.model));
@@ -2271,7 +2726,9 @@ function activate(pi, options = {}) {
2271
2726
  return { cancel: true };
2272
2727
  });
2273
2728
  pi.on("session_shutdown", () => {
2729
+ stopRefresh();
2274
2730
  bindings.close();
2731
+ unserve();
2275
2732
  context = undefined;
2276
2733
  if (sessionId) {
2277
2734
  Sessions.remove(sessionId, self);
@@ -2281,20 +2738,21 @@ function activate(pi, options = {}) {
2281
2738
  function agentDir(env = process.env) {
2282
2739
  let config = {};
2283
2740
  try {
2284
- config = JSON.parse(readFileSync2(join3(env.PI_PACKAGE_DIR ?? "", "package.json"), "utf8")).piConfig ?? {};
2741
+ config = JSON.parse(readFileSync3(join4(env.PI_PACKAGE_DIR ?? "", "package.json"), "utf8")).piConfig ?? {};
2285
2742
  } catch {}
2286
2743
  const name = config.name || "pi";
2287
- return env[`${name.toUpperCase()}_CODING_AGENT_DIR`] || join3(homedir3(), config.configDir || ".pi", "agent");
2744
+ return env[`${name.toUpperCase()}_CODING_AGENT_DIR`] || join4(homedir3(), config.configDir || ".pi", "agent");
2288
2745
  }
2289
2746
  function readUserAgents(agentDir2) {
2290
2747
  try {
2291
- return JSON.parse(readFileSync2(join3(agentDir2, "settings.json"), "utf8")).agents;
2748
+ return JSON.parse(readFileSync3(join4(agentDir2, "settings.json"), "utf8")).agents;
2292
2749
  } catch {
2293
2750
  return;
2294
2751
  }
2295
2752
  }
2296
2753
  function extension_default(pi) {
2297
- activate(pi, { userAgents: () => readUserAgents(agentDir()) });
2754
+ const dir = agentDir();
2755
+ activate(pi, { userAgents: () => readUserAgents(dir), local: AgentInstalls.of(dir) });
2298
2756
  }
2299
2757
  export {
2300
2758
  extension_default as default,