@celljs/ta-agents 4.10.0 → 4.12.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.
Files changed (2) hide show
  1. package/extension/index.mjs +359 -155
  2. package/package.json +1 -1
@@ -36,12 +36,136 @@ var Acp;
36
36
 
37
37
  // src/agent-bindings.ts
38
38
  import { realpathSync } from "node:fs";
39
- import { homedir } from "node:os";
40
- import { join, sep } from "node:path";
39
+ import { homedir as homedir2 } from "node:os";
40
+ import { join as join2, sep } from "node:path";
41
41
 
42
42
  // src/acp-agent.ts
43
43
  import { spawn } from "node:child_process";
44
44
 
45
+ // src/agent-catalog.ts
46
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
47
+ import { homedir } from "node:os";
48
+ import { delimiter, dirname, join } from "node:path";
49
+ var PRESETS = [
50
+ {
51
+ id: "codebuddy-code",
52
+ name: "CodeBuddy Code",
53
+ command: "cbc",
54
+ args: ["--acp"],
55
+ programs: ["cbc", "codebuddy"],
56
+ login: "cbc",
57
+ env: { CODEBUDDY_CODE_MODE_ENABLED: "1" },
58
+ clientMeta: { "codebuddy.ai": { mainAgentSupport: true, toolModeSupport: true } },
59
+ options: { mode: "fullAccess" },
60
+ processPerSession: true
61
+ },
62
+ {
63
+ id: "claude-code",
64
+ name: "Claude Code",
65
+ command: "npx",
66
+ args: ["-y", "@agentclientprotocol/claude-agent-acp@0.106.0"],
67
+ programs: ["claude"],
68
+ login: "claude"
69
+ },
70
+ { id: "codex", name: "Codex", command: "npx", args: ["-y", "@agentclientprotocol/codex-acp@2.6.0"], programs: ["codex"], login: "codex login" }
71
+ ];
72
+ var AgentCatalog;
73
+ ((AgentCatalog) => {
74
+ AgentCatalog.DEFAULT_MODEL = "default";
75
+ function agents(settings, find = Programs.find) {
76
+ const configured = settings && typeof settings === "object" ? settings : {};
77
+ const result = [];
78
+ for (const preset of PRESETS) {
79
+ const setting = configured[preset.id];
80
+ if (setting === false) {
81
+ continue;
82
+ }
83
+ const found = preset.programs.find((program) => find(program));
84
+ if (!found && !setting) {
85
+ continue;
86
+ }
87
+ const { programs, ...config } = preset;
88
+ const command = programs.includes(config.command) && found ? found : config.command;
89
+ const own = setting || {};
90
+ result.push({
91
+ ...config,
92
+ command,
93
+ ...own,
94
+ id: preset.id,
95
+ env: config.env || own.env ? { ...config.env, ...own.env } : undefined,
96
+ options: config.options || own.options ? { ...config.options, ...own.options } : undefined
97
+ });
98
+ }
99
+ for (const [id, setting] of Object.entries(configured)) {
100
+ if (setting && typeof setting === "object" && !PRESETS.some((preset) => preset.id === id) && typeof setting.command === "string") {
101
+ result.push({ name: id, args: [], ...setting, id, command: setting.command });
102
+ }
103
+ }
104
+ return result;
105
+ }
106
+ AgentCatalog.agents = agents;
107
+ })(AgentCatalog ||= {});
108
+ var Programs;
109
+ ((Programs) => {
110
+ function find(program, path = process.env.PATH) {
111
+ const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
112
+ for (const dir of (path ?? "").split(delimiter)) {
113
+ for (const extension of extensions) {
114
+ if (dir && isFile(join(dir, program + extension))) {
115
+ return program;
116
+ }
117
+ }
118
+ }
119
+ return;
120
+ }
121
+ Programs.find = find;
122
+ function isFile(path) {
123
+ try {
124
+ return statSync(path).isFile();
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+ })(Programs ||= {});
130
+
131
+ class ModelCache {
132
+ file;
133
+ entries;
134
+ constructor(file = ModelCache.defaultFile()) {
135
+ this.file = file;
136
+ }
137
+ get(id) {
138
+ return this.read()[id];
139
+ }
140
+ set(id, models) {
141
+ const entries = this.read();
142
+ if (JSON.stringify(entries[id]) === JSON.stringify(models)) {
143
+ return false;
144
+ }
145
+ entries[id] = models;
146
+ try {
147
+ mkdirSync(dirname(this.file), { recursive: true });
148
+ const temp = `${this.file}.${process.pid}.tmp`;
149
+ writeFileSync(temp, JSON.stringify(entries, undefined, 2));
150
+ renameSync(temp, this.file);
151
+ } catch {}
152
+ return true;
153
+ }
154
+ read() {
155
+ if (!this.entries) {
156
+ try {
157
+ this.entries = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : {};
158
+ } catch {
159
+ this.entries = {};
160
+ }
161
+ }
162
+ return this.entries ?? {};
163
+ }
164
+ static defaultFile() {
165
+ return join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "ta-agents", "models.json");
166
+ }
167
+ }
168
+
45
169
  // src/agent-turn.ts
46
170
  var OUTPUT_CHARS = 8000;
47
171
  var WRITING_KINDS = new Set(["edit", "delete", "move"]);
@@ -122,7 +246,7 @@ class AgentTurn {
122
246
  async settle(id, quietMs, signal) {
123
247
  for (;; ) {
124
248
  const run = this.tools.get(id);
125
- if (!run || run.complete || this.ended || signal?.aborted || this.items.some((item) => item.type !== "tool")) {
249
+ if (!run || run.complete || run.left || this.ended || signal?.aborted || this.items.some((item) => item.type !== "tool")) {
126
250
  return;
127
251
  }
128
252
  const left = run.updatedAt + quietMs - Date.now();
@@ -135,12 +259,32 @@ class AgentTurn {
135
259
  async waitTool(id, signal) {
136
260
  for (;; ) {
137
261
  const run = this.tools.get(id);
138
- if (!run || run.done || this.ended || signal?.aborted) {
262
+ if (!run || run.done || run.left || this.ended || signal?.aborted) {
139
263
  return run;
140
264
  }
141
265
  await this.changed(signal);
142
266
  }
143
267
  }
268
+ open() {
269
+ for (const run of this.tools.values()) {
270
+ if (!run.done && !run.left) {
271
+ return true;
272
+ }
273
+ }
274
+ return false;
275
+ }
276
+ step() {
277
+ let changed = false;
278
+ for (const run of this.tools.values()) {
279
+ if (!run.done && !run.left) {
280
+ run.left = true;
281
+ changed = true;
282
+ }
283
+ }
284
+ if (changed) {
285
+ this.notify();
286
+ }
287
+ }
144
288
  pushText(type, text) {
145
289
  if (!text) {
146
290
  return;
@@ -166,6 +310,7 @@ class AgentTurn {
166
310
  status: "pending",
167
311
  output: "",
168
312
  done: false,
313
+ left: false,
169
314
  complete: false,
170
315
  terminal: "",
171
316
  updatedAt: Date.now()
@@ -347,13 +492,15 @@ ${AgentTurn.diff(item.oldText ?? "", item.newText)}`;
347
492
  }
348
493
 
349
494
  // src/agent-session.ts
350
- var UNSOLICITED_QUIET_MS = 3000;
495
+ var STEP_PHASES = new Set(["preparing", "model_requesting"]);
351
496
  var ABANDON_WAIT_MS = 5000;
352
497
  var ANSWER_WAIT_MS = 15000;
353
498
 
354
499
  class AgentSession {
355
500
  host;
356
501
  id;
502
+ static unfinishedIdleMs = 20000;
503
+ static quietMs = 3000;
357
504
  turn;
358
505
  options = [];
359
506
  models;
@@ -361,11 +508,18 @@ class AgentSession {
361
508
  callbacks = { permission: async (request) => AgentSession.allow(request), activity: () => {
362
509
  return;
363
510
  } };
511
+ told = new Set;
512
+ context;
364
513
  queued = [];
365
514
  quietTimer;
366
515
  abandoned;
367
516
  answer;
368
517
  working = false;
518
+ phaseOf;
519
+ idleTimer;
520
+ retrying;
521
+ failure;
522
+ delivered = 0;
369
523
  requests = new Set;
370
524
  earlier = new Set;
371
525
  constructor(host, id, setup) {
@@ -398,20 +552,17 @@ class AgentSession {
398
552
  this.callbacks.title?.(this.title);
399
553
  }
400
554
  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
- }
555
+ if (phase && !ids.some((id) => this.earlier.has(id)) && AgentSession.own(meta)) {
556
+ this.phase(this.turn, phase, meta);
409
557
  }
410
558
  if (meta && Object.keys(meta).some((key) => /unsolicitedTurn$/.test(key)) && !this.turn) {
411
559
  this.startUnsolicited(false);
412
560
  }
413
561
  return;
414
562
  }
563
+ case "usage_update":
564
+ this.measure(update);
565
+ break;
415
566
  case "session_end":
416
567
  if (this.turn?.unsolicited) {
417
568
  this.turn.end("end_turn");
@@ -441,8 +592,22 @@ class AgentSession {
441
592
  const turn = new AgentTurn(false, /^\/[\w:.-]+/.exec(first)?.[0], (path, before) => this.callbacks.write?.(path, before));
442
593
  this.turn = turn;
443
594
  this.working = false;
595
+ this.phaseOf = undefined;
596
+ this.failure = undefined;
597
+ this.stopWaiting();
444
598
  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));
599
+ const answer = this.host.request("session/prompt", { sessionId: this.id, prompt }).then((response) => {
600
+ this.answered(turn);
601
+ const error = response?.stopReason === "cancelled" ? undefined : AgentSession.errorOf(response?._meta);
602
+ if (error) {
603
+ turn.fail(error);
604
+ } else {
605
+ turn.end(response?.stopReason ?? "end_turn");
606
+ }
607
+ }, (error) => {
608
+ this.answered(turn);
609
+ turn.fail(error.message, error.code);
610
+ });
446
611
  this.answer = answer;
447
612
  return turn;
448
613
  }
@@ -476,6 +641,7 @@ class AgentSession {
476
641
  this.turn = undefined;
477
642
  clearTimeout(this.quietTimer);
478
643
  this.quietTimer = undefined;
644
+ this.stopWaiting();
479
645
  }
480
646
  }
481
647
  cancel() {
@@ -503,6 +669,47 @@ class AgentSession {
503
669
  }
504
670
  }
505
671
  }
672
+ phase(turn, phase, meta) {
673
+ if (phase !== "idle") {
674
+ this.working = true;
675
+ this.stopWaiting();
676
+ this.retried(phase === "retrying" ? AgentSession.retryOf(meta) : undefined);
677
+ if (STEP_PHASES.has(phase)) {
678
+ turn?.step();
679
+ }
680
+ } else if (this.working) {
681
+ this.working = false;
682
+ this.retried(undefined);
683
+ this.stopWaiting();
684
+ if (this.phaseOf === "model_done" && !turn?.open()) {
685
+ turn?.end("end_turn");
686
+ } else if (turn) {
687
+ this.idleTimer = setTimeout(() => {
688
+ this.idleTimer = undefined;
689
+ turn.end("end_turn");
690
+ }, AgentSession.unfinishedIdleMs);
691
+ this.idleTimer.unref?.();
692
+ }
693
+ }
694
+ this.phaseOf = phase;
695
+ }
696
+ stopWaiting() {
697
+ clearTimeout(this.idleTimer);
698
+ this.idleTimer = undefined;
699
+ }
700
+ answered(turn) {
701
+ if (this.turn === turn) {
702
+ this.stopWaiting();
703
+ this.retried(undefined);
704
+ }
705
+ }
706
+ retried(retry) {
707
+ if (retry?.reason === this.retrying?.reason && retry?.attempt === this.retrying?.attempt && !retry === !this.retrying) {
708
+ return;
709
+ }
710
+ this.retrying = retry;
711
+ this.callbacks.retry?.(retry);
712
+ }
506
713
  startUnsolicited(quiet) {
507
714
  const turn = new AgentTurn(true, undefined, (path, before) => this.callbacks.write?.(path, before));
508
715
  this.turn = turn;
@@ -513,12 +720,75 @@ class AgentSession {
513
720
  }
514
721
  quiet(turn) {
515
722
  clearTimeout(this.quietTimer);
516
- this.quietTimer = setTimeout(() => turn.end("end_turn"), UNSOLICITED_QUIET_MS);
723
+ this.quietTimer = setTimeout(() => {
724
+ if (turn.ended) {
725
+ return;
726
+ }
727
+ if (this.working || this.idleTimer || turn.open()) {
728
+ this.quiet(turn);
729
+ } else {
730
+ turn.end("end_turn");
731
+ }
732
+ }, AgentSession.quietMs);
517
733
  this.quietTimer.unref?.();
518
734
  }
735
+ measure(update) {
736
+ const used = AgentSession.contextUsed(update);
737
+ if (used === undefined || Object.keys(update._meta ?? {}).some((key) => /parentToolCallId$/.test(key))) {
738
+ return;
739
+ }
740
+ if (this.context !== undefined && used < this.context / 2) {
741
+ this.told.clear();
742
+ }
743
+ this.context = used;
744
+ }
745
+ static contextUsed(update) {
746
+ if (typeof update.used === "number" && update.used > 0) {
747
+ return update.used;
748
+ }
749
+ const tokens = update._meta?.usage;
750
+ const count = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
751
+ const total = count(tokens?.prompt_tokens) || count(tokens?.input_tokens) + count(tokens?.cache_read_input_tokens) + count(tokens?.cache_creation_input_tokens);
752
+ return total > 0 ? total : undefined;
753
+ }
754
+ static own(meta) {
755
+ return !Object.keys(meta ?? {}).some((key) => /(parentToolCallId|memberEvent)$/.test(key));
756
+ }
519
757
  static requestIds(meta) {
520
758
  return Object.entries(meta ?? {}).filter(([key, value]) => /requestId$/i.test(key) && typeof value === "string" && value).map(([, value]) => value);
521
759
  }
760
+ static retryOf(meta) {
761
+ for (const [key, value] of Object.entries(meta ?? {})) {
762
+ const retry = value?.retry;
763
+ if (/agentPhase$/.test(key) && retry && typeof retry === "object") {
764
+ return {
765
+ ...typeof retry.reason === "string" ? { reason: retry.reason } : {},
766
+ ...typeof retry.attempt === "number" ? { attempt: retry.attempt } : {}
767
+ };
768
+ }
769
+ }
770
+ return {};
771
+ }
772
+ static errorOf(meta) {
773
+ for (const [key, value] of Object.entries(meta ?? {})) {
774
+ if (/errorMessage$/.test(key) && typeof value === "string" && value.trim()) {
775
+ return AgentSession.messageOf(value.trim());
776
+ }
777
+ }
778
+ return;
779
+ }
780
+ static messageOf(text) {
781
+ if (!text.startsWith("{")) {
782
+ return text;
783
+ }
784
+ try {
785
+ const value = JSON.parse(text);
786
+ const message = value.message ?? (typeof value.error === "string" ? value.error : value.error?.message);
787
+ return typeof message === "string" && message.trim() ? message.trim() : text;
788
+ } catch {
789
+ return text;
790
+ }
791
+ }
522
792
  static phase(meta) {
523
793
  for (const [key, value] of Object.entries(meta ?? {})) {
524
794
  const phase = value?.phase;
@@ -703,6 +973,18 @@ var TEXTS = {
703
973
  en: (agent) => `Starting ${agent}…`,
704
974
  zh: (agent) => `正在启动 ${agent}…`
705
975
  },
976
+ refused: {
977
+ en: (agent) => `${agent} declined to go on with this turn.`,
978
+ zh: (agent) => `${agent} 拒绝继续这一轮。`
979
+ },
980
+ retrying: {
981
+ en: (agent, network, attempt) => `${agent}: ${network ? "the connection to its model dropped" : "a request to its model failed"}, retrying${attempt ? ` (attempt ${attempt})` : ""}…`,
982
+ zh: (agent, network, attempt) => `${agent}:${network ? "连接模型的网络中断" : "模型请求失败"},正在重试${attempt ? `(第 ${attempt} 次)` : ""}…`
983
+ },
984
+ dropped: {
985
+ en: (agent) => `${agent} went on without finishing this call.`,
986
+ zh: (agent) => `${agent} 没有完成这次调用就接着往下做了。`
987
+ },
706
988
  unfinished: {
707
989
  en: (agent) => `${agent} ended its turn before this call finished.`,
708
990
  zh: (agent) => `${agent} 在这次调用完成前结束了这一轮。`
@@ -718,6 +1000,8 @@ function text(key, ...args) {
718
1000
 
719
1001
  // src/acp-agent.ts
720
1002
  var STDERR_CHARS = 2000;
1003
+ var LIFELINE = '(read _ <&3; kill $$) </dev/null >/dev/null 2>&1 & exec "$@" 3<&-';
1004
+ var NOT_FOUND = 127;
721
1005
  function agentEnv(extra) {
722
1006
  const env = {};
723
1007
  for (const [key, value] of Object.entries(process.env)) {
@@ -810,7 +1094,7 @@ class AcpAgent {
810
1094
  }
811
1095
  reference(on) {
812
1096
  const child = this.child;
813
- for (const handle of [child, child?.stdin, child?.stdout, child?.stderr]) {
1097
+ for (const handle of [child, child?.stdin, child?.stdout, child?.stderr, child?.stdio[3]]) {
814
1098
  if (on) {
815
1099
  handle?.ref?.();
816
1100
  } else {
@@ -837,13 +1121,14 @@ class AcpAgent {
837
1121
  async launch() {
838
1122
  this.stop();
839
1123
  this.stderr = "";
840
- const child = spawn(this.program.command, this.program.args, {
841
- cwd: this.program.cwd,
842
- env: agentEnv(this.program.env),
843
- stdio: ["pipe", "pipe", "pipe"],
844
- shell: process.platform === "win32",
845
- windowsHide: true
846
- });
1124
+ const posix = process.platform !== "win32";
1125
+ const { command, args, cwd } = this.program;
1126
+ const env = agentEnv(this.program.env);
1127
+ const notFound = () => new Error(text("notFound", this.name, command));
1128
+ if (posix && !command.includes("/") && !Programs.find(command, env.PATH)) {
1129
+ throw notFound();
1130
+ }
1131
+ const child = posix ? spawn("/bin/sh", ["-c", LIFELINE, "sh", command, ...args], { cwd, env, stdio: ["pipe", "pipe", "pipe", "pipe"] }) : spawn(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: true, windowsHide: true });
847
1132
  this.child = child;
848
1133
  const { stdin, stdout } = child;
849
1134
  if (!stdin || !stdout) {
@@ -853,8 +1138,11 @@ class AcpAgent {
853
1138
  this.connection = connection;
854
1139
  child.stderr?.setEncoding("utf8");
855
1140
  child.stderr?.on("data", (chunk) => this.stderr = (this.stderr + chunk).slice(-STDERR_CHARS));
856
- child.on("error", (error) => connection.close(error.code === "ENOENT" ? new Error(text("notFound", this.name, this.program.command)) : error));
857
- child.on("exit", (code) => connection.close(new Error(text("exited", this.name, String(code ?? "signal"), this.lastError()))));
1141
+ child.on("error", (error) => connection.close(error.code === "ENOENT" ? notFound() : error));
1142
+ child.on("exit", (code) => {
1143
+ child.stdio[3]?.destroy();
1144
+ connection.close(posix && code === NOT_FOUND ? notFound() : new Error(text("exited", this.name, String(code ?? "signal"), this.lastError())));
1145
+ });
858
1146
  connection.onNotification = (method, params) => this.notified(method, params);
859
1147
  connection.onRequest = (method, params) => this.requested(method, params);
860
1148
  connection.onClose = (error) => {
@@ -1042,132 +1330,8 @@ class AgentBindings {
1042
1330
  }
1043
1331
  }
1044
1332
  static isRemote(cwd) {
1045
- const agentDir = process.env.TA_CODING_AGENT_DIR ?? join(homedir(), ".ta", "agent");
1046
- return cwd.startsWith(join(agentDir, "remote") + sep);
1047
- }
1048
- }
1049
-
1050
- // src/agent-catalog.ts
1051
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
1052
- import { homedir as homedir2 } from "node:os";
1053
- import { delimiter, dirname, join as join2 } from "node:path";
1054
- var PRESETS = [
1055
- {
1056
- id: "codebuddy-code",
1057
- name: "CodeBuddy Code",
1058
- command: "cbc",
1059
- args: ["--acp"],
1060
- programs: ["cbc", "codebuddy"],
1061
- login: "cbc",
1062
- env: { CODEBUDDY_CODE_MODE_ENABLED: "1" },
1063
- clientMeta: { "codebuddy.ai": { mainAgentSupport: true, toolModeSupport: true } },
1064
- options: { mode: "fullAccess" },
1065
- processPerSession: true
1066
- },
1067
- {
1068
- id: "claude-code",
1069
- name: "Claude Code",
1070
- command: "npx",
1071
- args: ["-y", "@agentclientprotocol/claude-agent-acp@0.106.0"],
1072
- programs: ["claude"],
1073
- login: "claude"
1074
- },
1075
- { id: "codex", name: "Codex", command: "npx", args: ["-y", "@agentclientprotocol/codex-acp@2.6.0"], programs: ["codex"], login: "codex login" }
1076
- ];
1077
- var AgentCatalog;
1078
- ((AgentCatalog) => {
1079
- AgentCatalog.DEFAULT_MODEL = "default";
1080
- function agents(settings, find = Programs.find) {
1081
- const configured = settings && typeof settings === "object" ? settings : {};
1082
- const result = [];
1083
- for (const preset of PRESETS) {
1084
- const setting = configured[preset.id];
1085
- if (setting === false) {
1086
- continue;
1087
- }
1088
- const found = preset.programs.find((program) => find(program));
1089
- if (!found && !setting) {
1090
- continue;
1091
- }
1092
- const { programs, ...config } = preset;
1093
- const command = programs.includes(config.command) && found ? found : config.command;
1094
- const own = setting || {};
1095
- result.push({
1096
- ...config,
1097
- command,
1098
- ...own,
1099
- id: preset.id,
1100
- env: config.env || own.env ? { ...config.env, ...own.env } : undefined,
1101
- options: config.options || own.options ? { ...config.options, ...own.options } : undefined
1102
- });
1103
- }
1104
- for (const [id, setting] of Object.entries(configured)) {
1105
- if (setting && typeof setting === "object" && !PRESETS.some((preset) => preset.id === id) && typeof setting.command === "string") {
1106
- result.push({ name: id, args: [], ...setting, id, command: setting.command });
1107
- }
1108
- }
1109
- return result;
1110
- }
1111
- AgentCatalog.agents = agents;
1112
- })(AgentCatalog ||= {});
1113
- var Programs;
1114
- ((Programs) => {
1115
- function find(program) {
1116
- const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
1117
- for (const dir of (process.env.PATH ?? "").split(delimiter)) {
1118
- for (const extension of extensions) {
1119
- if (dir && isFile(join2(dir, program + extension))) {
1120
- return program;
1121
- }
1122
- }
1123
- }
1124
- return;
1125
- }
1126
- Programs.find = find;
1127
- function isFile(path) {
1128
- try {
1129
- return statSync(path).isFile();
1130
- } catch {
1131
- return false;
1132
- }
1133
- }
1134
- })(Programs ||= {});
1135
-
1136
- class ModelCache {
1137
- file;
1138
- entries;
1139
- constructor(file = ModelCache.defaultFile()) {
1140
- this.file = file;
1141
- }
1142
- get(id) {
1143
- return this.read()[id];
1144
- }
1145
- set(id, models) {
1146
- const entries = this.read();
1147
- if (JSON.stringify(entries[id]) === JSON.stringify(models)) {
1148
- return false;
1149
- }
1150
- entries[id] = models;
1151
- try {
1152
- mkdirSync(dirname(this.file), { recursive: true });
1153
- const temp = `${this.file}.${process.pid}.tmp`;
1154
- writeFileSync(temp, JSON.stringify(entries, undefined, 2));
1155
- renameSync(temp, this.file);
1156
- } catch {}
1157
- return true;
1158
- }
1159
- read() {
1160
- if (!this.entries) {
1161
- try {
1162
- this.entries = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : {};
1163
- } catch {
1164
- this.entries = {};
1165
- }
1166
- }
1167
- return this.entries ?? {};
1168
- }
1169
- static defaultFile() {
1170
- return join2(process.env.XDG_CACHE_HOME || join2(homedir2(), ".cache"), "ta-agents", "models.json");
1333
+ const agentDir = process.env.TA_CODING_AGENT_DIR ?? join2(homedir2(), ".ta", "agent");
1334
+ return cwd.startsWith(join2(agentDir, "remote") + sep);
1171
1335
  }
1172
1336
  }
1173
1337
 
@@ -1193,6 +1357,11 @@ var AgentPrompt;
1193
1357
  return result;
1194
1358
  }
1195
1359
  AgentPrompt.pending = pending;
1360
+ function resume(error) {
1361
+ return `Your last turn stopped with an error before it finished: ${error}
1362
+ Continue where you left off.`;
1363
+ }
1364
+ AgentPrompt.resume = resume;
1196
1365
  function blocks(messages, images) {
1197
1366
  const result = [];
1198
1367
  for (const message of messages) {
@@ -1239,6 +1408,17 @@ ${kept}
1239
1408
  </earlier_conversation>`;
1240
1409
  }
1241
1410
  AgentPrompt.transcript = transcript;
1411
+ function notes(messages) {
1412
+ const system = messages.filter((message) => message.role === "system").map((message) => [text2(message), ...sections(message)].join(`
1413
+ `)).join(`
1414
+ `);
1415
+ return [...system.matchAll(/^<(ta-[\w-]+)>[\s\S]*?<\/\1>$/gm)].map((match) => match[0]);
1416
+ }
1417
+ AgentPrompt.notes = notes;
1418
+ function sections(message) {
1419
+ const parts = message.sections ?? {};
1420
+ return Object.values(parts).filter((part) => typeof part === "string");
1421
+ }
1242
1422
  function text2(message) {
1243
1423
  if (message.role === "user" || message.role === "system") {
1244
1424
  return typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? part.text : "").join("");
@@ -1283,7 +1463,7 @@ var AgentTool;
1283
1463
  target = str2(input.url) ?? str2(input.query);
1284
1464
  break;
1285
1465
  }
1286
- target ??= str2(input.description);
1466
+ target ??= ["description", "subject", "skill", "image_path", "file_path", "path", "url", "query"].map((key) => str2(input[key])).find(Boolean);
1287
1467
  return { title, kind: run.kind, target: relative(target ?? title, cwd), ...run.name ? { tool: run.name } : {} };
1288
1468
  }
1289
1469
  AgentTool.args = args;
@@ -1318,7 +1498,7 @@ var AgentTool;
1318
1498
  calls.delete(toolCallId);
1319
1499
  const details = { agent: call.agent, kind: run?.kind, title: run?.title, status: run?.status, locations: run?.locations };
1320
1500
  if (!run?.done) {
1321
- return { content: [{ type: "text", text: text("unfinished", call.agent) }], details, isError: true };
1501
+ return { content: [{ type: "text", text: text(run?.left ? "dropped" : "unfinished", call.agent) }], details, isError: true };
1322
1502
  }
1323
1503
  return { content: [{ type: "text", text: run.output || "(no output)" }], details, isError: run.status === "failed" };
1324
1504
  }
@@ -1483,7 +1663,10 @@ class AgentStreamer {
1483
1663
  async run(config, model, context, options, builder) {
1484
1664
  const signal = options?.signal;
1485
1665
  const { session, fresh, images, dirs } = await this.host.open(config, signal);
1486
- const pending = AgentPrompt.pending(context.messages);
1666
+ let pending = AgentPrompt.pending(context.messages);
1667
+ if (session.failure !== undefined) {
1668
+ pending = pending.filter((message) => !(message.timestamp <= session.delivered));
1669
+ }
1487
1670
  let turn = session.turn;
1488
1671
  if (turn) {
1489
1672
  if (pending.length) {
@@ -1491,14 +1674,27 @@ class AgentStreamer {
1491
1674
  }
1492
1675
  } else {
1493
1676
  let prompt = pending.length ? AgentPrompt.blocks(pending, images) : session.takeQueued();
1677
+ if (!prompt?.length && session.failure !== undefined) {
1678
+ prompt = [{ type: "text", text: AgentPrompt.resume(session.failure) }];
1679
+ }
1494
1680
  if (!prompt?.length) {
1495
1681
  builder.done("stop");
1496
1682
  return;
1497
1683
  }
1684
+ session.delivered = Math.max(session.delivered, ...pending.map((message) => message.timestamp ?? 0));
1498
1685
  const earlier = fresh ? AgentPrompt.transcript(context.messages, pending.length) : undefined;
1499
1686
  if (earlier) {
1500
1687
  prompt = [{ type: "text", text: earlier }, ...prompt];
1501
1688
  }
1689
+ const notes = AgentPrompt.notes(context.messages).filter((note) => !session.told.has(note));
1690
+ if (notes.length) {
1691
+ for (const note of notes) {
1692
+ session.told.add(note);
1693
+ }
1694
+ prompt = [{ type: "text", text: notes.join(`
1695
+
1696
+ `) }, ...prompt];
1697
+ }
1502
1698
  await session.idle();
1503
1699
  await this.configure(session, model, options, signal);
1504
1700
  turn = session.prompt(prompt);
@@ -1528,6 +1724,9 @@ class AgentStreamer {
1528
1724
  }
1529
1725
  if (item.reason === "cancelled" && signal?.aborted) {
1530
1726
  builder.error("aborted", "Aborted");
1727
+ } else if (item.reason === "refusal") {
1728
+ session.failure = text("refused", config.name);
1729
+ builder.error("error", session.failure);
1531
1730
  } else {
1532
1731
  if (turn.command && !turn.produced) {
1533
1732
  builder.append("text", text("commandDone", config.name, turn.command));
@@ -1538,7 +1737,8 @@ class AgentStreamer {
1538
1737
  }
1539
1738
  case "error":
1540
1739
  session.finished(turn);
1541
- builder.error("error", AgentStreamer.describe(config, item));
1740
+ session.failure = AgentStreamer.describe(config, item);
1741
+ builder.error("error", session.failure);
1542
1742
  return;
1543
1743
  }
1544
1744
  }
@@ -1703,6 +1903,10 @@ function activate(pi, options = {}) {
1703
1903
  const option = request.options.find((candidate) => candidate.name === chosen);
1704
1904
  return option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" };
1705
1905
  },
1906
+ retry: (retry) => {
1907
+ const ui = context?.hasUI ? context.ui : undefined;
1908
+ ui?.setWorkingMessage(retry ? text("retrying", config.name, retry.reason === "network" ? "network" : "", retry.attempt ? String(retry.attempt) : "") : undefined);
1909
+ },
1706
1910
  title: (title) => {
1707
1911
  if (context && !pi.getSessionName()) {
1708
1912
  pi.setSessionName(title);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-agents",
3
- "version": "4.10.0",
3
+ "version": "4.12.0",
4
4
  "description": "A pi package for Ta: other coding agents (CodeBuddy Code, Claude Code, Codex and any agent that speaks ACP) as models to pick, each running a conversation on its own harness",
5
5
  "keywords": [
6
6
  "pi-package"