toc-ocra 0.3.3 → 0.3.7

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 (51) hide show
  1. package/README.md +3 -1
  2. package/dist/cli/cli.mjs +624 -295
  3. package/dist/service/agent.mjs +593 -264
  4. package/dist/src/acp/chat-agents.js +12 -2
  5. package/dist/src/acp/chat-agents.js.map +1 -1
  6. package/dist/src/acp/chat-host.d.ts +10 -0
  7. package/dist/src/acp/chat-host.js +35 -0
  8. package/dist/src/acp/chat-host.js.map +1 -1
  9. package/dist/src/acp/chat-session.d.ts +11 -0
  10. package/dist/src/acp/chat-session.js +37 -3
  11. package/dist/src/acp/chat-session.js.map +1 -1
  12. package/dist/src/acp/connection.d.ts +4 -0
  13. package/dist/src/acp/connection.js +6 -0
  14. package/dist/src/acp/connection.js.map +1 -1
  15. package/dist/src/acp/usage-tally.d.ts +26 -0
  16. package/dist/src/acp/usage-tally.js +43 -0
  17. package/dist/src/acp/usage-tally.js.map +1 -0
  18. package/dist/src/acp/vendor.d.ts +5 -2
  19. package/dist/src/acp/vendor.js +6 -3
  20. package/dist/src/acp/vendor.js.map +1 -1
  21. package/dist/src/config.d.ts +2 -0
  22. package/dist/src/config.js +4 -0
  23. package/dist/src/config.js.map +1 -1
  24. package/dist/src/index.js +0 -0
  25. package/dist/src/providers/cli/codex-catalog.d.ts +26 -0
  26. package/dist/src/providers/cli/codex-catalog.js +179 -0
  27. package/dist/src/providers/cli/codex-catalog.js.map +1 -0
  28. package/dist/src/providers/cli/codex.js +4 -2
  29. package/dist/src/providers/cli/codex.js.map +1 -1
  30. package/dist/src/providers/model-catalog-collector.js +1 -1
  31. package/dist/src/providers/model-catalog-collector.js.map +1 -1
  32. package/dist/src/providers/model-catalog.d.ts +19 -4
  33. package/dist/src/providers/model-catalog.js +76 -14
  34. package/dist/src/providers/model-catalog.js.map +1 -1
  35. package/dist/src/runs/run-supervisor.d.ts +14 -0
  36. package/dist/src/runs/run-supervisor.js +31 -1
  37. package/dist/src/runs/run-supervisor.js.map +1 -1
  38. package/dist/src/runtime/agent-runtime.d.ts +3 -0
  39. package/dist/src/runtime/agent-runtime.js +20 -2
  40. package/dist/src/runtime/agent-runtime.js.map +1 -1
  41. package/dist/src/types/protocol.d.ts +23 -0
  42. package/dist/src/types/protocol.js +13 -0
  43. package/dist/src/types/protocol.js.map +1 -1
  44. package/package.json +1 -2
  45. package/scripts/installation.cjs +14 -1
  46. /package/{vendor → assets}/acp/claude/LICENSE +0 -0
  47. /package/{vendor → assets}/acp/claude/index.mjs +0 -0
  48. /package/{vendor → assets}/acp/claude/runtime.json +0 -0
  49. /package/{vendor → assets}/acp/codex/LICENSE +0 -0
  50. /package/{vendor → assets}/acp/codex/index.mjs +0 -0
  51. /package/{vendor → assets}/acp/codex/runtime.json +0 -0
package/dist/cli/cli.mjs CHANGED
@@ -1956,19 +1956,19 @@ var require_chunkstream = __commonJS({
1956
1956
  ChunkStream.prototype._processRead = function(read) {
1957
1957
  this._reads.shift();
1958
1958
  let pos = 0;
1959
- let count = 0;
1959
+ let count2 = 0;
1960
1960
  let data = Buffer.alloc(read.length);
1961
1961
  while (pos < read.length) {
1962
- let buf = this._buffers[count++];
1962
+ let buf = this._buffers[count2++];
1963
1963
  let len = Math.min(buf.length, read.length - pos);
1964
1964
  buf.copy(data, pos, 0, len);
1965
1965
  pos += len;
1966
1966
  if (len !== buf.length) {
1967
- this._buffers[--count] = buf.slice(len);
1967
+ this._buffers[--count2] = buf.slice(len);
1968
1968
  }
1969
1969
  }
1970
- if (count > 0) {
1971
- this._buffers.splice(0, count);
1970
+ if (count2 > 0) {
1971
+ this._buffers.splice(0, count2);
1972
1972
  }
1973
1973
  this._buffered -= read.length;
1974
1974
  read.func.call(this, data);
@@ -2700,12 +2700,12 @@ var require_bitmapper = __commonJS({
2700
2700
  }
2701
2701
  }
2702
2702
  return {
2703
- get: function(count) {
2704
- while (leftOver.length < count) {
2703
+ get: function(count2) {
2704
+ while (leftOver.length < count2) {
2705
2705
  split();
2706
2706
  }
2707
- let returner = leftOver.slice(0, count);
2708
- leftOver = leftOver.slice(count);
2707
+ let returner = leftOver.slice(0, count2);
2708
+ leftOver = leftOver.slice(count2);
2709
2709
  return returner;
2710
2710
  },
2711
2711
  resetAfterLine: function() {
@@ -4421,10 +4421,10 @@ var require_browser = __commonJS({
4421
4421
  text2 = canvas;
4422
4422
  canvas = void 0;
4423
4423
  }
4424
- return new Promise(function(resolve9, reject) {
4424
+ return new Promise(function(resolve10, reject) {
4425
4425
  try {
4426
4426
  const data = QRCode2.create(text2, opts);
4427
- resolve9(renderFunc(data, canvas, opts));
4427
+ resolve10(renderFunc(data, canvas, opts));
4428
4428
  } catch (e) {
4429
4429
  reject(e);
4430
4430
  }
@@ -4505,11 +4505,11 @@ var require_server = __commonJS({
4505
4505
  }
4506
4506
  function render(renderFunc, text2, params) {
4507
4507
  if (!params.cb) {
4508
- return new Promise(function(resolve9, reject) {
4508
+ return new Promise(function(resolve10, reject) {
4509
4509
  try {
4510
4510
  const data = QRCode2.create(text2, params.opts);
4511
4511
  return renderFunc(data, params.opts, function(err, data2) {
4512
- return err ? reject(err) : resolve9(data2);
4512
+ return err ? reject(err) : resolve10(data2);
4513
4513
  });
4514
4514
  } catch (e) {
4515
4515
  reject(e);
@@ -4579,7 +4579,7 @@ import { createHash as createHash5 } from "node:crypto";
4579
4579
  import { existsSync as existsSync7, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
4580
4580
  import { tmpdir as tmpdir4 } from "node:os";
4581
4581
  import { createRequire } from "node:module";
4582
- import { dirname as dirname9, join as join20, resolve as resolve8 } from "node:path";
4582
+ import { dirname as dirname10, join as join21, resolve as resolve9 } from "node:path";
4583
4583
  import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL2 } from "node:url";
4584
4584
 
4585
4585
  // src/config.ts
@@ -5816,14 +5816,14 @@ function codePointLength(str2) {
5816
5816
  const units = str2.length;
5817
5817
  if (!highSurrogate.test(str2))
5818
5818
  return units;
5819
- let count = units;
5819
+ let count2 = units;
5820
5820
  for (let i = 0; i < units - 1; i++) {
5821
5821
  if ((str2.charCodeAt(i) & 64512) === 55296 && (str2.charCodeAt(i + 1) & 64512) === 56320) {
5822
- count--;
5822
+ count2--;
5823
5823
  i++;
5824
5824
  }
5825
5825
  }
5826
- return count;
5826
+ return count2;
5827
5827
  }
5828
5828
  function getLengthableOrigin(input2) {
5829
5829
  if (Array.isArray(input2))
@@ -9656,7 +9656,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
9656
9656
  var NONE = 0;
9657
9657
  var ASSUMED = 1;
9658
9658
  var PROVEN = 2;
9659
- function isRecursive(inst, stack, resolve9) {
9659
+ function isRecursive(inst, stack, resolve10) {
9660
9660
  const cached3 = recursive.get(inst);
9661
9661
  if (cached3 !== void 0)
9662
9662
  return cached3 ? PROVEN : NONE;
@@ -9666,7 +9666,7 @@ function isRecursive(inst, stack, resolve9) {
9666
9666
  let result = NONE;
9667
9667
  const check2 = (child) => {
9668
9668
  if (result !== PROVEN && child?._zod) {
9669
- const answer = isRecursive(child, stack, resolve9);
9669
+ const answer = isRecursive(child, stack, resolve10);
9670
9670
  if (answer > result)
9671
9671
  result = answer;
9672
9672
  }
@@ -9677,7 +9677,7 @@ function isRecursive(inst, stack, resolve9) {
9677
9677
  const desc = Object.getOwnPropertyDescriptor(sh, key);
9678
9678
  if (spread && !desc.enumerable)
9679
9679
  continue;
9680
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve9) : NONE;
9680
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve10) : NONE;
9681
9681
  if (child > answer)
9682
9682
  answer = child;
9683
9683
  }
@@ -9741,7 +9741,7 @@ function isRecursive(inst, stack, resolve9) {
9741
9741
  break;
9742
9742
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
9743
9743
  case "lazy": {
9744
- const inner = def._cachedInner ?? (resolve9 ? inst._zod.innerType : void 0);
9744
+ const inner = def._cachedInner ?? (resolve10 ? inst._zod.innerType : void 0);
9745
9745
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
9746
9746
  break;
9747
9747
  }
@@ -10206,8 +10206,8 @@ function az_default() {
10206
10206
  }
10207
10207
 
10208
10208
  // node_modules/zod/v4/locales/be.js
10209
- function getBelarusianPlural(count, one, few, many) {
10210
- const absCount = Math.abs(count);
10209
+ function getBelarusianPlural(count2, one, few, many) {
10210
+ const absCount = Math.abs(count2);
10211
10211
  const lastDigit = absCount % 10;
10212
10212
  const lastTwoDigits = absCount % 100;
10213
10213
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -12854,8 +12854,8 @@ function hu_default() {
12854
12854
  }
12855
12855
 
12856
12856
  // node_modules/zod/v4/locales/hy.js
12857
- function getArmenianPlural(count, one, many) {
12858
- return Math.abs(count) === 1 ? one : many;
12857
+ function getArmenianPlural(count2, one, many) {
12858
+ return Math.abs(count2) === 1 ? one : many;
12859
12859
  }
12860
12860
  function withDefiniteArticle(word) {
12861
12861
  if (!word)
@@ -15593,8 +15593,8 @@ function ro_default() {
15593
15593
  }
15594
15594
 
15595
15595
  // node_modules/zod/v4/locales/ru.js
15596
- function getRussianPlural(count, one, few, many) {
15597
- const absCount = Math.abs(count);
15596
+ function getRussianPlural(count2, one, few, many) {
15597
+ const absCount = Math.abs(count2);
15598
15598
  const lastDigit = absCount % 10;
15599
15599
  const lastTwoDigits = absCount % 100;
15600
15600
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -24332,6 +24332,9 @@ function defaultDataDir() {
24332
24332
  function dataDirFromEnv() {
24333
24333
  return resolve(process.env.TOC_OCRA_DATA_DIR ?? defaultDataDir());
24334
24334
  }
24335
+ function agentDataDir() {
24336
+ return dataDirFromEnv();
24337
+ }
24335
24338
  function defaultConfigPath(dataDir2 = dataDirFromEnv()) {
24336
24339
  return resolve(process.env.TOC_OCRA_CONFIG ?? join(dataDir2, "config.json"));
24337
24340
  }
@@ -24618,7 +24621,7 @@ async function askYesNo(question) {
24618
24621
  rl.close();
24619
24622
  }
24620
24623
  }
24621
- var sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
24624
+ var sleep = (ms) => new Promise((resolve10) => setTimeout(resolve10, ms));
24622
24625
  async function linkDevice(options) {
24623
24626
  const out = options.out ?? process.stdout;
24624
24627
  const interactive = Boolean(process.stdin.isTTY);
@@ -24691,7 +24694,7 @@ Echo \u8D26\u53F7 ${who} \u786E\u8BA4\u5C06\u8FD9\u53F0\u7535\u8111\u6DFB\u52A0\
24691
24694
  }
24692
24695
 
24693
24696
  // src/providers/detection.ts
24694
- import { spawn as spawn8 } from "node:child_process";
24697
+ import { spawn as spawn9 } from "node:child_process";
24695
24698
 
24696
24699
  // src/runtime/cli/hydrate-shell-path.ts
24697
24700
  import { delimiter as delimiter3 } from "node:path";
@@ -24730,10 +24733,10 @@ import { execFile, spawn } from "node:child_process";
24730
24733
  import { accessSync, constants, statSync } from "node:fs";
24731
24734
  import { delimiter as delimiter2, join as join4 } from "node:path";
24732
24735
  function readProcessTable() {
24733
- return new Promise((resolve9) => {
24736
+ return new Promise((resolve10) => {
24734
24737
  execFile("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
24735
- if (error62) return resolve9([]);
24736
- resolve9(stdout.split("\n").flatMap((line) => {
24738
+ if (error62) return resolve10([]);
24739
+ resolve10(stdout.split("\n").flatMap((line) => {
24737
24740
  const [pid, ppid] = line.trim().split(/\s+/).map(Number);
24738
24741
  return pid && ppid !== void 0 && Number.isFinite(ppid) ? [{ pid, ppid }] : [];
24739
24742
  }));
@@ -24768,7 +24771,7 @@ function alive(pid) {
24768
24771
  return false;
24769
24772
  }
24770
24773
  }
24771
- var sleep2 = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
24774
+ var sleep2 = (ms) => new Promise((resolve10) => setTimeout(resolve10, ms));
24772
24775
  async function killPosixTree(rootPid, graceMs) {
24773
24776
  const descendants = await listDescendants(rootPid);
24774
24777
  signal(-rootPid, "SIGTERM");
@@ -24803,7 +24806,7 @@ function parseCapturedProxy(stdout) {
24803
24806
  return Object.fromEntries(PROXY_KEYS.flatMap((key, index) => values[index] ? [[key, values[index]]] : []));
24804
24807
  }
24805
24808
  function readLoginShell(shell) {
24806
- return new Promise((resolve9) => {
24809
+ return new Promise((resolve10) => {
24807
24810
  const proxyValues = PROXY_KEYS.map((key) => `"\${${key}-}"`).join(" ");
24808
24811
  const command = `printf '%s' '${PATH_DELIMITER}'; printf '%s' "$PATH"; printf '%s' '${PATH_DELIMITER}'; printf '%s' '${PROXY_DELIMITER}'; printf '%s\\0' ${proxyValues}; printf '%s' '${PROXY_DELIMITER}'`;
24809
24812
  let finished = false;
@@ -24824,7 +24827,7 @@ function readLoginShell(shell) {
24824
24827
  child.stdout.removeAllListeners("data");
24825
24828
  child.removeAllListeners("error");
24826
24829
  child.removeAllListeners("close");
24827
- resolve9(result);
24830
+ resolve10(result);
24828
24831
  };
24829
24832
  timer = setTimeout(() => {
24830
24833
  try {
@@ -24880,9 +24883,9 @@ function createPosixPlatform(id) {
24880
24883
  child.kill("SIGTERM");
24881
24884
  },
24882
24885
  processCommandLine(pid) {
24883
- return new Promise((resolve9) => {
24886
+ return new Promise((resolve10) => {
24884
24887
  execFile("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
24885
- resolve9(error62 ? void 0 : stdout.trim() || void 0);
24888
+ resolve10(error62 ? void 0 : stdout.trim() || void 0);
24886
24889
  });
24887
24890
  });
24888
24891
  },
@@ -24925,23 +24928,23 @@ function resolveWindowsCommandShim(shimPath) {
24925
24928
  return void 0;
24926
24929
  }
24927
24930
  function taskkillTree(rootPid) {
24928
- return new Promise((resolve9) => {
24931
+ return new Promise((resolve10) => {
24929
24932
  const child = spawn2(join5(SYSTEM_ROOT, "System32", "taskkill.exe"), ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
24930
- child.once("error", () => resolve9());
24931
- child.once("close", () => resolve9());
24933
+ child.once("error", () => resolve10());
24934
+ child.once("close", () => resolve10());
24932
24935
  });
24933
24936
  }
24934
24937
  function runPowerShell(script) {
24935
24938
  const prelude = '$ProgressPreference="SilentlyContinue";[Console]::OutputEncoding=[Text.Encoding]::UTF8;';
24936
24939
  const encoded = Buffer.from(prelude + script, "utf16le").toString("base64");
24937
- return new Promise((resolve9) => {
24940
+ return new Promise((resolve10) => {
24938
24941
  execFile2(
24939
24942
  POWERSHELL,
24940
24943
  ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
24941
24944
  { timeout: HELPER_TIMEOUT_MS, windowsHide: true, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 },
24942
24945
  (error62, stdout) => {
24943
- if (!error62) return resolve9({ ok: true, stdout });
24944
- resolve9({ ok: false, reason: error62.killed ? "timeout" : "spawn_error" });
24946
+ if (!error62) return resolve10({ ok: true, stdout });
24947
+ resolve10({ ok: false, reason: error62.killed ? "timeout" : "spawn_error" });
24945
24948
  }
24946
24949
  );
24947
24950
  });
@@ -25071,7 +25074,7 @@ function mergePathSegments(segments) {
25071
25074
 
25072
25075
  // src/acp/chat-agents.ts
25073
25076
  import { realpathSync as realpathSync2 } from "node:fs";
25074
- import { join as join9 } from "node:path";
25077
+ import { join as join10 } from "node:path";
25075
25078
 
25076
25079
  // src/providers/cli-specs.ts
25077
25080
  var SOURCES = [
@@ -25267,7 +25270,7 @@ var KiroSessionLog = class {
25267
25270
  return step;
25268
25271
  }
25269
25272
  if (Date.now() >= deadline) return void 0;
25270
- await new Promise((resolve9) => setTimeout(resolve9, 150));
25273
+ await new Promise((resolve10) => setTimeout(resolve10, 150));
25271
25274
  }
25272
25275
  }
25273
25276
  /** The first of `ids` whose result is in the log, waiting up to `waitMs`. */
@@ -25277,7 +25280,7 @@ var KiroSessionLog = class {
25277
25280
  await this.refresh();
25278
25281
  const id = ids.find((item) => this.results.has(item));
25279
25282
  if (id || Date.now() >= deadline) return id;
25280
- await new Promise((resolve9) => setTimeout(resolve9, 150));
25283
+ await new Promise((resolve10) => setTimeout(resolve10, 150));
25281
25284
  }
25282
25285
  }
25283
25286
  async result(id, waitMs = 3e3) {
@@ -25286,7 +25289,7 @@ var KiroSessionLog = class {
25286
25289
  await this.refresh();
25287
25290
  const result = this.results.get(id);
25288
25291
  if (result || Date.now() >= deadline) return result;
25289
- await new Promise((resolve9) => setTimeout(resolve9, 200));
25292
+ await new Promise((resolve10) => setTimeout(resolve10, 200));
25290
25293
  }
25291
25294
  }
25292
25295
  };
@@ -25529,7 +25532,7 @@ async function listKiroSessions(workdir, options = {}) {
25529
25532
  const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
25530
25533
  let lastError;
25531
25534
  for (let attempt = 0; attempt < 2; attempt++) {
25532
- if (attempt) await new Promise((resolve9) => setTimeout(resolve9, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
25535
+ if (attempt) await new Promise((resolve10) => setTimeout(resolve10, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
25533
25536
  try {
25534
25537
  const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
25535
25538
  return parseKiroSessions(stdout);
@@ -25744,7 +25747,7 @@ var AgentProcess = class _AgentProcess {
25744
25747
  constructor(child, onLine, onStderr) {
25745
25748
  this.child = child;
25746
25749
  let spawnError = "";
25747
- this.exited = new Promise((resolve9) => {
25750
+ this.exited = new Promise((resolve10) => {
25748
25751
  child.once("error", (error62) => {
25749
25752
  spawnError = error62.message;
25750
25753
  });
@@ -25753,7 +25756,7 @@ var AgentProcess = class _AgentProcess {
25753
25756
  if (settled) return;
25754
25757
  settled = true;
25755
25758
  this.exit = { code: code2, signal: signal2, ...spawnError ? { error: spawnError } : {} };
25756
- resolve9(this.exit);
25759
+ resolve10(this.exit);
25757
25760
  };
25758
25761
  child.once("exit", (code2, signal2) => {
25759
25762
  setTimeout(() => {
@@ -25812,7 +25815,7 @@ var AgentProcess = class _AgentProcess {
25812
25815
  this.child.stdin?.end();
25813
25816
  if (this.pid > 1) await killProcessTree(this.pid, graceMs);
25814
25817
  else this.child.kill("SIGKILL");
25815
- await Promise.race([this.exited, new Promise((resolve9) => setTimeout(resolve9, 5e3).unref())]);
25818
+ await Promise.race([this.exited, new Promise((resolve10) => setTimeout(resolve10, 5e3).unref())]);
25816
25819
  }
25817
25820
  };
25818
25821
 
@@ -25848,8 +25851,8 @@ var JsonRpcPeer = class {
25848
25851
  request(method, params) {
25849
25852
  if (this.closedWith) return Promise.reject(this.closedWith);
25850
25853
  const id = ++this.nextId;
25851
- return new Promise((resolve9, reject) => {
25852
- this.pending.set(id, { resolve: resolve9, reject });
25854
+ return new Promise((resolve10, reject) => {
25855
+ this.pending.set(id, { resolve: resolve10, reject });
25853
25856
  try {
25854
25857
  this.send({ id, method, params });
25855
25858
  } catch (error62) {
@@ -25943,6 +25946,7 @@ function rpcErrorText(error62) {
25943
25946
  var PROTOCOL_VERSION = 1;
25944
25947
  var INITIALIZE_TIMEOUT_MS = 12e4;
25945
25948
  var SESSION_OPEN_TIMEOUT_MS = 18e4;
25949
+ var EXT_REQUEST_TIMEOUT_MS = 6e4;
25946
25950
  var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
25947
25951
  var text = (value) => typeof value === "string" && value ? value : void 0;
25948
25952
  var AcpConnection = class _AcpConnection {
@@ -26040,6 +26044,10 @@ var AcpConnection = class _AcpConnection {
26040
26044
  const result = record2(await this.peer.request("_lody/session/steer", { sessionId, prompt, steerId }));
26041
26045
  return result.outcome === "injected" ? "injected" : "failed";
26042
26046
  }
26047
+ /** An adapter extension request (`_session/archive`, `_session/unarchive`, …) with a time limit. */
26048
+ extRequest(method, params, timeoutMs = EXT_REQUEST_TIMEOUT_MS) {
26049
+ return this.call(method, params, timeoutMs);
26050
+ }
26043
26051
  async dispose() {
26044
26052
  this.peer.close(new Error("ACP \u8FDE\u63A5\u5DF2\u5173\u95ED"));
26045
26053
  await this.process.terminate();
@@ -26081,16 +26089,16 @@ var AcpConnection = class _AcpConnection {
26081
26089
  };
26082
26090
  function sessionState(sessionId, result) {
26083
26091
  const modes = record2(result.modes);
26084
- const models = record2(result.models);
26092
+ const models2 = record2(result.models);
26085
26093
  const ids = (list, key) => Array.isArray(list) ? list.map((item) => text(record2(item)[key])).filter((id) => !!id) : [];
26086
26094
  const currentModeId = text(modes.currentModeId);
26087
- const currentModelId = text(models.currentModelId);
26095
+ const currentModelId = text(models2.currentModelId);
26088
26096
  return {
26089
26097
  sessionId,
26090
26098
  ...currentModeId ? { currentModeId } : {},
26091
26099
  modeIds: ids(modes.availableModes, "id"),
26092
26100
  ...currentModelId ? { currentModelId } : {},
26093
- modelIds: ids(models.availableModels, "modelId"),
26101
+ modelIds: ids(models2.availableModels, "modelId"),
26094
26102
  configOptions: Array.isArray(result.configOptions) ? configOptions(result.configOptions) : []
26095
26103
  };
26096
26104
  }
@@ -26728,12 +26736,152 @@ var GEMINI_ACP = {
26728
26736
  var kiroAcpProvider = acpProvider(KIRO_ACP);
26729
26737
  var geminiAcpProvider = acpProvider(GEMINI_ACP);
26730
26738
 
26731
- // src/acp/vendor.ts
26739
+ // src/providers/cli/codex-catalog.ts
26732
26740
  import { spawn as spawn4 } from "node:child_process";
26741
+ import { statSync as statSync3 } from "node:fs";
26742
+ import { chmod as chmod3, mkdir as mkdir3, readFile as readFile3, rename as rename3, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
26743
+ import { homedir as homedir5 } from "node:os";
26744
+ import { dirname as dirname4, isAbsolute, join as join8, resolve as resolve2 } from "node:path";
26745
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join8(homedir5(), ".codex");
26746
+ var BUNDLED_TIMEOUT_MS = 1e4;
26747
+ function configuredCatalogPath(config2, home = codexHome()) {
26748
+ const value = config2.match(/^\s*model_catalog_json\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m)?.[1]?.trim();
26749
+ if (!value) return void 0;
26750
+ return isAbsolute(value) ? value : resolve2(home, value);
26751
+ }
26752
+ var nonEmpty = (value) => Array.isArray(value) && value.length > 0;
26753
+ function models(catalog) {
26754
+ const list = catalog && typeof catalog === "object" ? catalog.models : void 0;
26755
+ return Array.isArray(list) ? list.filter((entry) => Boolean(entry) && typeof entry === "object") : void 0;
26756
+ }
26757
+ function withBundledSpeedTiers(catalog, bundled) {
26758
+ const listed = models(catalog);
26759
+ if (!listed?.length) return void 0;
26760
+ const known = new Map((models(bundled) ?? []).flatMap((entry) => typeof entry.slug === "string" ? [[entry.slug, entry]] : []));
26761
+ let changed = false;
26762
+ const filled = listed.map((entry) => {
26763
+ const source = typeof entry.slug === "string" ? known.get(entry.slug) : void 0;
26764
+ if (!source) return entry;
26765
+ const next = { ...entry };
26766
+ for (const key of ["service_tiers", "additional_speed_tiers"]) {
26767
+ if (!nonEmpty(entry[key]) && nonEmpty(source[key])) {
26768
+ next[key] = source[key];
26769
+ changed = true;
26770
+ }
26771
+ }
26772
+ return next;
26773
+ });
26774
+ return changed ? { ...catalog, models: filled } : void 0;
26775
+ }
26776
+ var bundledCache;
26777
+ function runBundled() {
26778
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: ["debug", "models", "--bundled"] });
26779
+ return new Promise((resolveOutput, reject) => {
26780
+ const child = spawn4(launch.executable, launch.args, { env: launch.env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
26781
+ let stdout = "";
26782
+ const timer = setTimeout(() => {
26783
+ child.kill("SIGKILL");
26784
+ reject(new Error("codex debug models timed out"));
26785
+ }, BUNDLED_TIMEOUT_MS);
26786
+ child.stdout.setEncoding("utf8");
26787
+ child.stdout.on("data", (chunk) => {
26788
+ stdout += chunk;
26789
+ });
26790
+ child.once("error", (error62) => {
26791
+ clearTimeout(timer);
26792
+ reject(error62);
26793
+ });
26794
+ child.once("close", (code2) => {
26795
+ clearTimeout(timer);
26796
+ if (code2 === 0) resolveOutput(stdout);
26797
+ else reject(new Error(`codex debug models exited with code ${code2 ?? "unknown"}`));
26798
+ });
26799
+ });
26800
+ }
26801
+ async function codexBundledCatalog() {
26802
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: [] });
26803
+ const binary = launch.args[0] ?? launch.executable;
26804
+ const info = await stat2(binary).catch(() => void 0);
26805
+ const stamp = `${binary}:${info?.mtimeMs ?? "-"}:${info?.size ?? "-"}`;
26806
+ if (bundledCache?.stamp === stamp) return bundledCache.catalog;
26807
+ const catalog = JSON.parse(await runBundled());
26808
+ bundledCache = { stamp, catalog };
26809
+ return catalog;
26810
+ }
26811
+ var overlay;
26812
+ var refreshing;
26813
+ function fileStamp(path) {
26814
+ try {
26815
+ const info = statSync3(path);
26816
+ return `${info.mtimeMs}:${info.size}`;
26817
+ } catch {
26818
+ return "-";
26819
+ }
26820
+ }
26821
+ var stampOf = (configPath, sourcePath) => `${fileStamp(configPath)}|${fileStamp(sourcePath)}`;
26822
+ function overlayPath() {
26823
+ return join8(agentDataDir(), "codex", "model-catalog.json");
26824
+ }
26825
+ async function rebuild() {
26826
+ const home = codexHome();
26827
+ const configPath = join8(home, "config.toml");
26828
+ const config2 = await readFile3(configPath, "utf8").catch(() => "");
26829
+ const sourcePath = configuredCatalogPath(config2, home);
26830
+ if (!sourcePath) {
26831
+ overlay = void 0;
26832
+ return;
26833
+ }
26834
+ const stamp = stampOf(configPath, sourcePath);
26835
+ if (overlay && overlay.sourcePath === sourcePath && overlay.stamp === stamp) return;
26836
+ let source;
26837
+ try {
26838
+ source = JSON.parse(await readFile3(sourcePath, "utf8"));
26839
+ } catch {
26840
+ overlay = void 0;
26841
+ return;
26842
+ }
26843
+ if (models(source)?.every((entry) => nonEmpty(entry.service_tiers) && nonEmpty(entry.additional_speed_tiers))) {
26844
+ overlay = void 0;
26845
+ return;
26846
+ }
26847
+ const filled = withBundledSpeedTiers(source, await codexBundledCatalog());
26848
+ if (!filled) {
26849
+ overlay = void 0;
26850
+ return;
26851
+ }
26852
+ const path = overlayPath();
26853
+ await mkdir3(dirname4(path), { recursive: true, mode: 448 });
26854
+ const temporary = `${path}.${process.pid}.tmp`;
26855
+ await writeFile3(temporary, JSON.stringify(filled), { mode: 384 });
26856
+ await rename3(temporary, path);
26857
+ await chmod3(path, 384);
26858
+ overlay = { path, configPath, sourcePath, stamp };
26859
+ }
26860
+ async function prepareCodexCatalog() {
26861
+ refreshing ??= rebuild().catch(() => {
26862
+ overlay = void 0;
26863
+ }).finally(() => {
26864
+ refreshing = void 0;
26865
+ });
26866
+ await refreshing;
26867
+ }
26868
+ function codexCatalogOverlay() {
26869
+ if (!overlay) return void 0;
26870
+ if (stampOf(overlay.configPath, overlay.sourcePath) === overlay.stamp) return { path: overlay.path, stamp: overlay.stamp };
26871
+ void prepareCodexCatalog();
26872
+ return void 0;
26873
+ }
26874
+ function codexCatalogArgs() {
26875
+ const copy = codexCatalogOverlay();
26876
+ return copy ? ["-c", `model_catalog_json=${JSON.stringify(copy.path)}`] : [];
26877
+ }
26878
+
26879
+ // src/acp/vendor.ts
26880
+ import { spawn as spawn5 } from "node:child_process";
26733
26881
  import { createHash } from "node:crypto";
26734
26882
  import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
26735
- import { copyFile, mkdir as mkdir3, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
26736
- import { dirname as dirname4, join as join8, resolve as resolve2 } from "node:path";
26883
+ import { copyFile, mkdir as mkdir4, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
26884
+ import { dirname as dirname5, join as join9, resolve as resolve3 } from "node:path";
26737
26885
  import { fileURLToPath } from "node:url";
26738
26886
  var AcpRuntimeUnavailable = class extends Error {
26739
26887
  constructor(message) {
@@ -26743,16 +26891,16 @@ var AcpRuntimeUnavailable = class extends Error {
26743
26891
  };
26744
26892
  var NPM_INSTALL_TIMEOUT_MS = 10 * 6e4;
26745
26893
  function packageRoot() {
26746
- let directory = dirname4(fileURLToPath(import.meta.url));
26894
+ let directory = dirname5(fileURLToPath(import.meta.url));
26747
26895
  while (true) {
26748
- const path = resolve2(directory, "package.json");
26896
+ const path = resolve3(directory, "package.json");
26749
26897
  if (existsSync4(path)) {
26750
26898
  try {
26751
26899
  if (JSON.parse(readFileSync4(path, "utf8")).name === "toc-ocra") return directory;
26752
26900
  } catch {
26753
26901
  }
26754
26902
  }
26755
- const parent = dirname4(directory);
26903
+ const parent = dirname5(directory);
26756
26904
  if (parent === directory) return void 0;
26757
26905
  directory = parent;
26758
26906
  }
@@ -26766,21 +26914,21 @@ function agentPackageVersion() {
26766
26914
  const directory = agentRoot();
26767
26915
  if (!directory) return "0";
26768
26916
  try {
26769
- return JSON.parse(readFileSync4(join8(directory, "package.json"), "utf8")).version ?? "0";
26917
+ return JSON.parse(readFileSync4(join9(directory, "package.json"), "utf8")).version ?? "0";
26770
26918
  } catch {
26771
26919
  return "0";
26772
26920
  }
26773
26921
  }
26774
26922
  function vendoredAdapter(name) {
26775
26923
  const directory = agentRoot();
26776
- const entry = directory ? join8(directory, "vendor", "acp", name, "index.mjs") : void 0;
26924
+ const entry = directory ? join9(directory, "assets", "acp", name, "index.mjs") : void 0;
26777
26925
  return entry && existsSync4(entry) ? entry : void 0;
26778
26926
  }
26779
26927
  var installs = /* @__PURE__ */ new Map();
26780
26928
  function ensureClaudeRuntime(dataDir2) {
26781
26929
  const entry = vendoredAdapter("claude");
26782
26930
  if (!entry) return Promise.reject(new AcpRuntimeUnavailable("\u8FD9\u4E2A\u7248\u672C\u7684\u8BBE\u5907\u4EE3\u7406\u6CA1\u6709\u9644\u5E26 Claude ACP \u9002\u914D\u5668"));
26783
- const manifestPath = join8(dirname4(entry), "runtime.json");
26931
+ const manifestPath = join9(dirname5(entry), "runtime.json");
26784
26932
  let manifest;
26785
26933
  try {
26786
26934
  manifest = JSON.parse(readFileSync4(manifestPath, "utf8"));
@@ -26788,7 +26936,7 @@ function ensureClaudeRuntime(dataDir2) {
26788
26936
  return Promise.reject(new AcpRuntimeUnavailable("Claude ACP \u9002\u914D\u5668\u7F3A\u5C11 runtime.json"));
26789
26937
  }
26790
26938
  const hash2 = createHash("sha256").update(readFileSync4(entry)).digest("hex").slice(0, 12);
26791
- const directory = join8(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
26939
+ const directory = join9(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
26792
26940
  const existing = installs.get(directory);
26793
26941
  if (existing) return existing;
26794
26942
  const install = installClaudeRuntime(directory, entry, manifest).catch((error62) => {
@@ -26799,21 +26947,21 @@ function ensureClaudeRuntime(dataDir2) {
26799
26947
  return install;
26800
26948
  }
26801
26949
  async function installClaudeRuntime(directory, entry, manifest) {
26802
- const sdkPackage = join8(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
26803
- if (existsSync4(sdkPackage) && existsSync4(join8(directory, "index.mjs"))) return directory;
26950
+ const sdkPackage = join9(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
26951
+ if (existsSync4(sdkPackage) && existsSync4(join9(directory, "index.mjs"))) return directory;
26804
26952
  const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`;
26805
- await mkdir3(temporary, { recursive: true, mode: 448 });
26953
+ await mkdir4(temporary, { recursive: true, mode: 448 });
26806
26954
  try {
26807
- await writeFile3(join8(temporary, "package.json"), JSON.stringify({
26955
+ await writeFile4(join9(temporary, "package.json"), JSON.stringify({
26808
26956
  name: "toc-ocra-claude-acp-runtime",
26809
26957
  private: true,
26810
26958
  type: "module",
26811
26959
  dependencies: { [manifest.sdk.name]: manifest.sdk.version }
26812
26960
  }, null, 2));
26813
26961
  await runNpm(["install", "--omit=optional", "--no-audit", "--no-fund", "--no-package-lock", "--loglevel=error"], temporary);
26814
- await copyFile(entry, join8(temporary, "index.mjs"));
26962
+ await copyFile(entry, join9(temporary, "index.mjs"));
26815
26963
  await rm2(directory, { recursive: true, force: true });
26816
- await rename3(temporary, directory);
26964
+ await rename4(temporary, directory);
26817
26965
  } catch (error62) {
26818
26966
  await rm2(temporary, { recursive: true, force: true }).catch(() => void 0);
26819
26967
  throw error62;
@@ -26824,7 +26972,7 @@ function runNpm(args, cwd) {
26824
26972
  const env = providerEnvironment();
26825
26973
  const launch = resolveExecutable("npm", args, env, process.env.TOC_OCRA_NPM_PATH);
26826
26974
  return new Promise((resolvePromise, reject) => {
26827
- const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] });
26975
+ const child = spawn5(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] });
26828
26976
  const stderr = [];
26829
26977
  child.stderr.setEncoding("utf8").on("data", (chunk) => {
26830
26978
  stderr.push(chunk);
@@ -26908,7 +27056,7 @@ var CLAUDE_CHAT = {
26908
27056
  return {
26909
27057
  launch: {
26910
27058
  executable: process.execPath,
26911
- args: [join9(runtime, "index.mjs")],
27059
+ args: [join10(runtime, "index.mjs")],
26912
27060
  env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable },
26913
27061
  cwd: workdir
26914
27062
  },
@@ -26926,14 +27074,20 @@ var CODEX_CHAT = {
26926
27074
  const entry = vendoredAdapter("codex");
26927
27075
  if (!entry) throw new AcpRuntimeUnavailable("\u8FD9\u4E2A\u7248\u672C\u7684\u8BBE\u5907\u4EE3\u7406\u6CA1\u6709\u9644\u5E26 Codex ACP \u9002\u914D\u5668");
26928
27076
  const executable = installedCli(CODEX);
27077
+ await prepareCodexCatalog();
27078
+ const catalog = codexCatalogOverlay();
26929
27079
  return {
26930
27080
  launch: {
26931
27081
  executable: process.execPath,
26932
27082
  args: [entry, "-c", "shell_environment_policy.ignore_default_excludes=true"],
26933
- env: { ...providerEnvironment(), CODEX_PATH: executable },
27083
+ env: {
27084
+ ...providerEnvironment(),
27085
+ CODEX_PATH: executable,
27086
+ ...catalog ? { LODY_CODEX_PROFILE_CONFIG: JSON.stringify({ model_catalog_json: catalog.path }) } : {}
27087
+ },
26934
27088
  cwd: workdir
26935
27089
  },
26936
- fingerprint: `codex:${entry}:${executable}`
27090
+ fingerprint: `codex:${entry}:${executable}${catalog ? `:${catalog.path}@${catalog.stamp}` : ""}`
26937
27091
  };
26938
27092
  },
26939
27093
  // Codex's presets: read-only sandbox, workspace write, full access. `read-only`
@@ -27057,7 +27211,7 @@ function codexTurnSandboxPolicy(request) {
27057
27211
  return { type: "readOnly", access: { type: "restricted", includePlatformDefaults: true, readableRoots: [request.workdir] } };
27058
27212
  }
27059
27213
  function codexAppServerArgs(request) {
27060
- return ["app-server", "--listen", "stdio://", ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"'], ...codexFastArgs(request)];
27214
+ return ["app-server", "--listen", "stdio://", ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"'], ...codexCatalogArgs(), ...codexFastArgs(request)];
27061
27215
  }
27062
27216
  var codexProvider = {
27063
27217
  id: "codex",
@@ -27070,7 +27224,7 @@ var codexProvider = {
27070
27224
  else if (level === "acceptEdits") args.push("--sandbox", "workspace-write", "-c", 'approval_policy="never"');
27071
27225
  else if (level === "read-only") args.push("--sandbox", "read-only", "-c", 'approval_policy="never"');
27072
27226
  else args.push("--sandbox", "read-only", "-c", 'approval_policy="never"', "-c", "mcp_servers={}", "-c", 'web_search="disabled"');
27073
- args.push(...codexFastArgs(request));
27227
+ args.push(...codexCatalogArgs(), ...codexFastArgs(request));
27074
27228
  if (request.model) args.push("--model", request.model);
27075
27229
  if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
27076
27230
  if (request.sessionId) args.push("resume", request.sessionId);
@@ -27294,13 +27448,13 @@ function isWriterConflict(message) {
27294
27448
 
27295
27449
  // src/providers/cli/claude.ts
27296
27450
  import { readdirSync as readdirSync2, readFileSync as readFileSync5 } from "node:fs";
27297
- import { homedir as homedir5 } from "node:os";
27298
- import { join as join10 } from "node:path";
27451
+ import { homedir as homedir6 } from "node:os";
27452
+ import { join as join11 } from "node:path";
27299
27453
  var CLAUDE2 = requireCliSpec("claude");
27300
27454
  function claudeProjectRoots() {
27301
27455
  const configured = process.env.CLAUDE_CONFIG_DIR;
27302
- const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join10(homedir5(), ".claude")];
27303
- return dirs.map((dir) => join10(dir, "projects"));
27456
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join11(homedir6(), ".claude")];
27457
+ return dirs.map((dir) => join11(dir, "projects"));
27304
27458
  }
27305
27459
  function claudeTranscriptExists(sessionId) {
27306
27460
  return claudeTranscriptPath(sessionId) !== void 0;
@@ -27316,7 +27470,7 @@ function claudeTranscriptPath(sessionId) {
27316
27470
  }
27317
27471
  for (const project of projects) {
27318
27472
  try {
27319
- if (readdirSync2(join10(root2, project)).includes(file2)) return join10(root2, project, file2);
27473
+ if (readdirSync2(join11(root2, project)).includes(file2)) return join11(root2, project, file2);
27320
27474
  } catch {
27321
27475
  }
27322
27476
  }
@@ -27360,7 +27514,7 @@ var claudeProvider = {
27360
27514
  settings.disableAllHooks = true;
27361
27515
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*");
27362
27516
  try {
27363
- const userSettings = JSON.parse(readFileSync5(join10(homedir5(), ".claude", "settings.json"), "utf8"));
27517
+ const userSettings = JSON.parse(readFileSync5(join11(homedir6(), ".claude", "settings.json"), "utf8"));
27364
27518
  for (const [key, value] of Object.entries(userSettings.env ?? {})) {
27365
27519
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
27366
27520
  }
@@ -27819,11 +27973,11 @@ var opencodeProvider = {
27819
27973
  };
27820
27974
 
27821
27975
  // src/providers/codex-quota.ts
27822
- import { spawn as spawn5 } from "node:child_process";
27976
+ import { spawn as spawn6 } from "node:child_process";
27823
27977
  import { createInterface as createInterface3 } from "node:readline";
27824
27978
  async function readCodexQuotaWindows() {
27825
27979
  const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--stdio"] });
27826
- const child = spawn5(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
27980
+ const child = spawn6(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
27827
27981
  let nextId = 0;
27828
27982
  const pending = /* @__PURE__ */ new Map();
27829
27983
  const lines = createInterface3({ input: child.stdout });
@@ -27851,7 +28005,7 @@ async function readCodexQuotaWindows() {
27851
28005
  });
27852
28006
  const request = (method, params) => {
27853
28007
  const id = ++nextId;
27854
- return new Promise((resolve9, reject) => {
28008
+ return new Promise((resolve10, reject) => {
27855
28009
  const timer = setTimeout(() => {
27856
28010
  pending.delete(id);
27857
28011
  reject(new Error(`Codex \u989D\u5EA6\u8BFB\u53D6\u8D85\u65F6\uFF08${method}\uFF09`));
@@ -27859,7 +28013,7 @@ async function readCodexQuotaWindows() {
27859
28013
  pending.set(id, {
27860
28014
  resolve: (value) => {
27861
28015
  clearTimeout(timer);
27862
- resolve9(value);
28016
+ resolve10(value);
27863
28017
  },
27864
28018
  reject: (error62) => {
27865
28019
  clearTimeout(timer);
@@ -27988,16 +28142,16 @@ ${stderr}`);
27988
28142
  }
27989
28143
 
27990
28144
  // src/providers/model-catalog.ts
27991
- import { spawn as spawn7 } from "node:child_process";
27992
- import { readFile as readFile3 } from "node:fs/promises";
27993
- import { homedir as homedir6 } from "node:os";
27994
- import { isAbsolute, join as join11, resolve as resolve3 } from "node:path";
28145
+ import { spawn as spawn8 } from "node:child_process";
28146
+ import { readFile as readFile4 } from "node:fs/promises";
28147
+ import { homedir as homedir7 } from "node:os";
28148
+ import { isAbsolute as isAbsolute2, join as join12, resolve as resolve4 } from "node:path";
27995
28149
 
27996
28150
  // src/providers/kiro-models.ts
27997
- import { spawn as spawn6 } from "node:child_process";
28151
+ import { spawn as spawn7 } from "node:child_process";
27998
28152
  import { createInterface as createInterface4 } from "node:readline";
27999
28153
  async function readKiroNativeModels(launch, cwd, options = {}) {
28000
- const child = spawn6(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
28154
+ const child = spawn7(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
28001
28155
  const lines = createInterface4({ input: child.stdout });
28002
28156
  let nextId = 0;
28003
28157
  let failure2;
@@ -28033,13 +28187,13 @@ async function readKiroNativeModels(launch, cwd, options = {}) {
28033
28187
  if (message.error) request2.reject(new Error(`Kiro \u6A21\u578B\u67E5\u8BE2\u5931\u8D25\uFF1A${message.error.message || "ACP \u8BF7\u6C42\u5931\u8D25"}`));
28034
28188
  else request2.resolve(message.result);
28035
28189
  });
28036
- const request = (method, params) => new Promise((resolve9, reject) => {
28190
+ const request = (method, params) => new Promise((resolve10, reject) => {
28037
28191
  if (failure2) {
28038
28192
  reject(failure2);
28039
28193
  return;
28040
28194
  }
28041
28195
  const id = ++nextId;
28042
- pending.set(id, { resolve: (value) => resolve9(value), reject });
28196
+ pending.set(id, { resolve: (value) => resolve10(value), reject });
28043
28197
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
28044
28198
  });
28045
28199
  try {
@@ -28089,15 +28243,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
28089
28243
  const source = settings && typeof settings === "object" ? settings : {};
28090
28244
  const configuredEnv = source.env && typeof source.env === "object" ? source.env : {};
28091
28245
  const mergedEnv = { ...configuredEnv, ...environment };
28092
- const models = /* @__PURE__ */ new Map();
28246
+ const models2 = /* @__PURE__ */ new Map();
28093
28247
  for (const [key, rawModel] of Object.entries(mergedEnv)) {
28094
28248
  const match = key.match(/^ANTHROPIC_DEFAULT_([A-Z0-9_]+)_MODEL$/);
28095
28249
  const id = stringValue(rawModel);
28096
28250
  if (!match || !id) continue;
28097
28251
  const configuredName = stringValue(mergedEnv[`${key}_NAME`]);
28098
- const existing = models.get(id);
28252
+ const existing = models2.get(id);
28099
28253
  if (!existing) {
28100
- models.set(id, {
28254
+ models2.set(id, {
28101
28255
  id,
28102
28256
  name: configuredName ?? id,
28103
28257
  supported_reasoning_efforts: [...CLAUDE_REASONING_EFFORTS]
@@ -28107,21 +28261,21 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
28107
28261
  const catalog = {
28108
28262
  agent_type: "claude",
28109
28263
  fetched_at: fetchedAt,
28110
- models: [...models.values()]
28264
+ models: [...models2.values()]
28111
28265
  };
28112
28266
  const defaultModel = stringValue(mergedEnv.ANTHROPIC_MODEL);
28113
28267
  if (defaultModel) catalog.default_model = defaultModel;
28114
28268
  return catalog;
28115
28269
  }
28116
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join11(homedir6(), ".claude");
28117
- var codexHome = () => process.env.CODEX_HOME?.trim() || join11(homedir6(), ".codex");
28118
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join11(homedir6(), ".gemini");
28119
- var grokHome = () => process.env.GROK_HOME?.trim() || join11(homedir6(), ".grok");
28120
- var opencodeHome = () => join11(process.env.XDG_CONFIG_HOME?.trim() || join11(homedir6(), ".config"), "opencode");
28121
- var kiroHome = () => join11(homedir6(), ".kiro");
28270
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join12(homedir7(), ".claude");
28271
+ var codexHome2 = () => process.env.CODEX_HOME?.trim() || join12(homedir7(), ".codex");
28272
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join12(homedir7(), ".gemini");
28273
+ var grokHome = () => process.env.GROK_HOME?.trim() || join12(homedir7(), ".grok");
28274
+ var opencodeHome = () => join12(process.env.XDG_CONFIG_HOME?.trim() || join12(homedir7(), ".config"), "opencode");
28275
+ var kiroHome = () => join12(homedir7(), ".kiro");
28122
28276
  async function readClaudeModelCatalog() {
28123
28277
  const home = claudeHome();
28124
- const content = await readFile3(join11(home, "settings.json"), "utf8").catch(() => "");
28278
+ const content = await readFile4(join12(home, "settings.json"), "utf8").catch(() => "");
28125
28279
  let settings = {};
28126
28280
  if (content) {
28127
28281
  try {
@@ -28158,42 +28312,45 @@ function toModel(entry) {
28158
28312
  if (defaultReasoning) model.default_reasoning_effort = defaultReasoning;
28159
28313
  return model;
28160
28314
  }
28315
+ function codexModelsFrom(parsed, options = {}) {
28316
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.models)) {
28317
+ return void 0;
28318
+ }
28319
+ return parsed.models.flatMap((entry) => {
28320
+ if (options.listedOnly && entry.visibility === "hide") return [];
28321
+ const model = toModel(entry);
28322
+ return model ? [model] : [];
28323
+ });
28324
+ }
28161
28325
  function parseCodexModels(content) {
28162
28326
  if (!content) return void 0;
28163
28327
  try {
28164
- const parsed = JSON.parse(content);
28165
- if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.models)) {
28166
- return void 0;
28167
- }
28168
- return parsed.models.flatMap((entry) => {
28169
- const model = toModel(entry);
28170
- return model ? [model] : [];
28171
- });
28328
+ return codexModelsFrom(JSON.parse(content));
28172
28329
  } catch {
28173
28330
  return void 0;
28174
28331
  }
28175
28332
  }
28176
- async function readCodexModels(codexHome2, config2) {
28333
+ async function readCodexModels(codexHome3, config2) {
28177
28334
  const configuredCatalog = configValue(config2, "model_catalog_json");
28178
28335
  if (configuredCatalog) {
28179
- const catalogPath = isAbsolute(configuredCatalog) ? configuredCatalog : resolve3(codexHome2, configuredCatalog);
28180
- const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
28336
+ const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve4(codexHome3, configuredCatalog);
28337
+ const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
28181
28338
  if (configuredModels?.length) return configuredModels;
28182
28339
  }
28183
- return parseCodexModels(
28184
- await readFile3(join11(codexHome2, "models_cache.json"), "utf8").catch(() => "")
28185
- ) ?? [];
28340
+ const cached3 = parseCodexModels(await readFile4(join12(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
28341
+ if (cached3?.length) return cached3;
28342
+ return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
28186
28343
  }
28187
28344
  async function readCodexModelCatalog() {
28188
- const home = codexHome();
28189
- const config2 = await readFile3(join11(home, "config.toml"), "utf8").catch(() => "");
28190
- const models = await readCodexModels(home, config2);
28345
+ const home = codexHome2();
28346
+ const config2 = await readFile4(join12(home, "config.toml"), "utf8").catch(() => "");
28347
+ const models2 = await readCodexModels(home, config2);
28191
28348
  const defaultModel = configValue(config2, "model");
28192
28349
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
28193
28350
  const catalog = {
28194
28351
  agent_type: "codex",
28195
28352
  fetched_at: (/* @__PURE__ */ new Date()).toISOString(),
28196
- models
28353
+ models: models2
28197
28354
  };
28198
28355
  if (defaultModel) catalog.default_model = defaultModel;
28199
28356
  if (defaultReasoningEffort) catalog.default_reasoning_effort = defaultReasoningEffort;
@@ -28202,7 +28359,7 @@ async function readCodexModelCatalog() {
28202
28359
  function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date()).toISOString(), settings = {}) {
28203
28360
  const source = payload && typeof payload === "object" ? payload : {};
28204
28361
  const defaults = objectValue(settings["chat.modelDefaults"] ?? objectValue(settings.chat).modelDefaults);
28205
- const models = Array.isArray(source.models) ? source.models.flatMap((item) => {
28362
+ const models2 = Array.isArray(source.models) ? source.models.flatMap((item) => {
28206
28363
  const entry = item && typeof item === "object" ? item : {};
28207
28364
  const id = stringValue(entry.model_id) ?? stringValue(entry.model_name);
28208
28365
  if (!id) return [];
@@ -28221,11 +28378,11 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
28221
28378
  const catalog = {
28222
28379
  agent_type: "kiro",
28223
28380
  fetched_at: fetchedAt,
28224
- models
28381
+ models: models2
28225
28382
  };
28226
28383
  const defaultModel = stringValue(source.default_model);
28227
28384
  if (defaultModel) catalog.default_model = defaultModel;
28228
- const defaultEffort = models.find((model) => model.id === defaultModel)?.default_reasoning_effort;
28385
+ const defaultEffort = models2.find((model) => model.id === defaultModel)?.default_reasoning_effort;
28229
28386
  if (defaultEffort) catalog.default_reasoning_effort = defaultEffort;
28230
28387
  return catalog;
28231
28388
  }
@@ -28235,9 +28392,9 @@ function cliExecutable(id) {
28235
28392
  return process.env[spec.overrideEnv]?.trim() || resolveCliCommand(cliCommand(spec));
28236
28393
  }
28237
28394
  function runModelListCommand(executable, args, label, environment) {
28238
- return new Promise((resolve9, reject) => {
28395
+ return new Promise((resolve10, reject) => {
28239
28396
  const launch = directLaunch2(executable, args);
28240
- const child = spawn7(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
28397
+ const child = spawn8(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
28241
28398
  let stdout = "";
28242
28399
  let stderr = "";
28243
28400
  const timer = setTimeout(() => {
@@ -28258,12 +28415,25 @@ function runModelListCommand(executable, args, label, environment) {
28258
28415
  });
28259
28416
  child.once("close", (code2) => {
28260
28417
  clearTimeout(timer);
28261
- if (code2 === 0) resolve9(stdout);
28418
+ if (code2 === 0) resolve10(stdout);
28262
28419
  else reject(new Error((stderr || stdout || `${label} exited with code ${code2 ?? "unknown"}`).trim()));
28263
28420
  });
28264
28421
  });
28265
28422
  }
28266
- async function readKiroModelCatalog() {
28423
+ var kiroEfforts;
28424
+ var KIRO_EFFORTS_MAX_AGE_MS = 60 * 60 * 1e3;
28425
+ var kiroListSignature = (list) => JSON.stringify([list.default_model ?? "", list.models.map((model) => [model.model_id, model.model_name, model.description ?? ""])]);
28426
+ function withKnownEfforts(base, known) {
28427
+ const efforts = new Map((known?.models ?? []).map((model) => [model.model_id, model]));
28428
+ return {
28429
+ ...base,
28430
+ models: base.models.map((model) => {
28431
+ const read = efforts.get(model.model_id);
28432
+ return read ? { ...model, supported_reasoning_efforts: read.supported_reasoning_efforts, ...read.default_reasoning_effort ? { default_reasoning_effort: read.default_reasoning_effort } : {} } : model;
28433
+ })
28434
+ };
28435
+ }
28436
+ async function readKiroModelCatalog(options = {}) {
28267
28437
  const environment = mergeShellProxyEnvironment(await hydrateShellPath(), providerEnvironment());
28268
28438
  const kiro = requireCliSpec("kiro");
28269
28439
  const listLaunch = launchCli({ spec: kiro, args: ["chat", "--list-models", "--format", "json"], env: environment });
@@ -28279,10 +28449,23 @@ async function readKiroModelCatalog() {
28279
28449
  ...listed.default_model ? { default_model: listed.default_model } : {},
28280
28450
  models: listed.models.map((model) => ({ model_id: model.id, model_name: model.name, ...model.description ? { description: model.description } : {}, supported_reasoning_efforts: [] }))
28281
28451
  };
28282
- const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
28452
+ const signature = kiroListSignature(base);
28453
+ const known = kiroEfforts;
28454
+ const current = !options.force && known?.signature === signature && Date.now() - known.readAt < KIRO_EFFORTS_MAX_AGE_MS;
28455
+ const readEfforts = async () => {
28456
+ if (current) return known.catalog;
28457
+ try {
28458
+ const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
28459
+ const catalog = await readKiroNativeModels(launch, homedir7(), { catalog: base });
28460
+ kiroEfforts = { signature, readAt: Date.now(), catalog };
28461
+ return catalog;
28462
+ } catch {
28463
+ return withKnownEfforts(base, known?.catalog);
28464
+ }
28465
+ };
28283
28466
  const [payload, content] = await Promise.all([
28284
- readKiroNativeModels(launch, homedir6(), { catalog: base }),
28285
- readFile3(join11(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
28467
+ readEfforts(),
28468
+ readFile4(join12(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
28286
28469
  ]);
28287
28470
  let settings;
28288
28471
  try {
@@ -28308,7 +28491,7 @@ function parseEnvFile(content) {
28308
28491
  }
28309
28492
  function parseGeminiModelCatalog(payload, defaultModel, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
28310
28493
  const source = payload && typeof payload === "object" ? payload : {};
28311
- const models = Array.isArray(source.models) ? source.models.flatMap((item) => {
28494
+ const models2 = Array.isArray(source.models) ? source.models.flatMap((item) => {
28312
28495
  const entry = item && typeof item === "object" ? item : {};
28313
28496
  const rawId = stringValue(entry.name);
28314
28497
  if (!rawId) return [];
@@ -28325,7 +28508,7 @@ function parseGeminiModelCatalog(payload, defaultModel, fetchedAt = (/* @__PURE_
28325
28508
  const catalog = {
28326
28509
  agent_type: "gemini",
28327
28510
  fetched_at: fetchedAt,
28328
- models
28511
+ models: models2
28329
28512
  };
28330
28513
  if (defaultModel?.trim()) catalog.default_model = defaultModel.trim();
28331
28514
  return catalog;
@@ -28339,7 +28522,7 @@ function geminiModelsUrl(baseUrl) {
28339
28522
  }
28340
28523
  async function readGeminiModelCatalog() {
28341
28524
  const fileEnvironment = parseEnvFile(
28342
- await readFile3(join11(geminiHome(), ".env"), "utf8").catch(() => "")
28525
+ await readFile4(join12(geminiHome(), ".env"), "utf8").catch(() => "")
28343
28526
  );
28344
28527
  const environment = { ...fileEnvironment, ...process.env };
28345
28528
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -28384,7 +28567,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
28384
28567
  return catalog;
28385
28568
  }
28386
28569
  async function readGrokModelCatalog() {
28387
- const config2 = await readFile3(join11(grokHome(), "config.toml"), "utf8").catch(() => "");
28570
+ const config2 = await readFile4(join12(grokHome(), "config.toml"), "utf8").catch(() => "");
28388
28571
  const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
28389
28572
  const catalog = parseGrokModelCatalog(output2, config2);
28390
28573
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -28403,30 +28586,31 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
28403
28586
  return catalog;
28404
28587
  }
28405
28588
  async function readOpencodeModelCatalog() {
28406
- const config2 = await readFile3(join11(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join11(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
28589
+ const config2 = await readFile4(join12(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join12(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
28407
28590
  const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
28408
28591
  const catalog = parseOpencodeModelCatalog(output2, config2);
28409
28592
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
28410
28593
  return catalog;
28411
28594
  }
28412
28595
  var TEN_MINUTES = 10 * 60 * 1e3;
28596
+ var TWO_MINUTES = 2 * 60 * 1e3;
28413
28597
  var MODEL_SOURCES = {
28414
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join11(claudeHome(), "settings.json")] },
28598
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join12(claudeHome(), "settings.json")] },
28415
28599
  codex: {
28416
28600
  read: readCodexModelCatalog,
28417
28601
  watchFiles: () => {
28418
- const home = codexHome();
28419
- return [join11(home, "config.toml"), join11(home, "models_cache.json")];
28602
+ const home = codexHome2();
28603
+ return [join12(home, "config.toml"), join12(home, "models_cache.json")];
28420
28604
  },
28421
28605
  // model_catalog_json may point anywhere; a periodic re-read covers it.
28422
28606
  refreshEveryMs: TEN_MINUTES
28423
28607
  },
28424
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join11(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
28425
- grok: { read: readGrokModelCatalog, watchFiles: () => [join11(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
28426
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join11(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
28608
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join12(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
28609
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join12(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
28610
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join12(kiroHome(), "settings", "cli.json")], refreshEveryMs: TWO_MINUTES },
28427
28611
  opencode: {
28428
28612
  read: readOpencodeModelCatalog,
28429
- watchFiles: () => [join11(opencodeHome(), "opencode.json"), join11(opencodeHome(), "opencode.jsonc")],
28613
+ watchFiles: () => [join12(opencodeHome(), "opencode.json"), join12(opencodeHome(), "opencode.jsonc")],
28430
28614
  refreshEveryMs: TEN_MINUTES
28431
28615
  }
28432
28616
  };
@@ -28525,9 +28709,9 @@ function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COM
28525
28709
  // src/providers/detection.ts
28526
28710
  function probeVersion(path, args) {
28527
28711
  if (args.length === 0) return Promise.resolve({});
28528
- return new Promise((resolve9) => {
28712
+ return new Promise((resolve10) => {
28529
28713
  const launch = directLaunch2(path, args);
28530
- const child = spawn8(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
28714
+ const child = spawn9(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
28531
28715
  let stdout = "";
28532
28716
  let stderr = "";
28533
28717
  let settled = false;
@@ -28536,7 +28720,7 @@ function probeVersion(path, args) {
28536
28720
  if (settled) return;
28537
28721
  settled = true;
28538
28722
  if (timer) clearTimeout(timer);
28539
- resolve9(result);
28723
+ resolve10(result);
28540
28724
  };
28541
28725
  timer = setTimeout(() => {
28542
28726
  child.kill("SIGKILL");
@@ -28609,12 +28793,12 @@ var cliDetection = new CliDetectionService();
28609
28793
  // src/smoke/cli-smoke.ts
28610
28794
  import { mkdtemp, realpath as realpath3, rm as rm4 } from "node:fs/promises";
28611
28795
  import { tmpdir as tmpdir2 } from "node:os";
28612
- import { join as join16 } from "node:path";
28796
+ import { join as join17 } from "node:path";
28613
28797
 
28614
28798
  // src/runs/run-supervisor.ts
28615
- import { spawn as spawn10 } from "node:child_process";
28616
- import { mkdir as mkdir6, realpath as realpath2, stat as stat4, writeFile as writeFile6 } from "node:fs/promises";
28617
- import { basename as basename2, isAbsolute as isAbsolute3, join as join15, relative as relative2, resolve as resolve4 } from "node:path";
28799
+ import { spawn as spawn11 } from "node:child_process";
28800
+ import { mkdir as mkdir7, realpath as realpath2, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
28801
+ import { basename as basename2, isAbsolute as isAbsolute4, join as join16, relative as relative2, resolve as resolve5 } from "node:path";
28618
28802
  import { createInterface as createInterface6 } from "node:readline";
28619
28803
 
28620
28804
  // src/providers/chat/index.ts
@@ -28903,12 +29087,12 @@ function codexGoalProvider(request, goal) {
28903
29087
  }
28904
29088
 
28905
29089
  // src/providers/cli/codex-fork.ts
28906
- import { spawn as spawn9 } from "node:child_process";
29090
+ import { spawn as spawn10 } from "node:child_process";
28907
29091
  import { createInterface as createInterface5 } from "node:readline";
28908
29092
  var FORK_TIMEOUT_MS = 9e4;
28909
29093
  async function forkCodexThread(options) {
28910
29094
  const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--listen", "stdio://"] });
28911
- const child = spawn9(launch.executable, launch.args, {
29095
+ const child = spawn10(launch.executable, launch.args, {
28912
29096
  cwd: options.workdir,
28913
29097
  env: launch.env,
28914
29098
  shell: false,
@@ -28923,9 +29107,9 @@ async function forkCodexThread(options) {
28923
29107
  });
28924
29108
  let nextId = 1;
28925
29109
  const pending = /* @__PURE__ */ new Map();
28926
- const call = (method, params) => new Promise((resolve9, reject) => {
29110
+ const call = (method, params) => new Promise((resolve10, reject) => {
28927
29111
  const id = nextId++;
28928
- pending.set(id, { resolve: resolve9, reject });
29112
+ pending.set(id, { resolve: resolve10, reject });
28929
29113
  child.stdin.write(`${JSON.stringify({ id, method, params })}
28930
29114
  `);
28931
29115
  });
@@ -28983,19 +29167,19 @@ async function forkCodexThread(options) {
28983
29167
 
28984
29168
  // src/runs/run-recorder.ts
28985
29169
  import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs";
28986
- import { homedir as homedir7 } from "node:os";
28987
- import { join as join12 } from "node:path";
29170
+ import { homedir as homedir8 } from "node:os";
29171
+ import { join as join13 } from "node:path";
28988
29172
  var RunRecorder = class _RunRecorder {
28989
29173
  constructor(path) {
28990
29174
  this.path = path;
28991
29175
  }
28992
29176
  path;
28993
- home = homedir7();
29177
+ home = homedir8();
28994
29178
  static fromEnvironment(runId, meta3) {
28995
29179
  const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
28996
29180
  if (!directory) return void 0;
28997
29181
  mkdirSync2(directory, { recursive: true });
28998
- const recorder = new _RunRecorder(join12(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
29182
+ const recorder = new _RunRecorder(join13(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
28999
29183
  recorder.write({ meta: meta3 });
29000
29184
  return recorder;
29001
29185
  }
@@ -29010,8 +29194,8 @@ var RunRecorder = class _RunRecorder {
29010
29194
  };
29011
29195
 
29012
29196
  // src/runs/run-transcript.ts
29013
- import { chmod as chmod3, mkdir as mkdir4, readdir as readdir2, readFile as readFile4, rename as rename4, stat as stat2, unlink, writeFile as writeFile4 } from "node:fs/promises";
29014
- import { join as join13 } from "node:path";
29197
+ import { chmod as chmod4, mkdir as mkdir5, readdir as readdir2, readFile as readFile5, rename as rename5, stat as stat3, unlink, writeFile as writeFile5 } from "node:fs/promises";
29198
+ import { join as join14 } from "node:path";
29015
29199
  var MAX_TRANSCRIPT_ITEMS = 5e3;
29016
29200
  var MAX_TRANSCRIPT_TEXT = 2e5;
29017
29201
  var MAX_TRANSCRIPT_LINES = 2e4;
@@ -29276,7 +29460,7 @@ function transcriptFileName(runId) {
29276
29460
  var TranscriptStore = class {
29277
29461
  constructor(dataDir2, logger, env = process.env) {
29278
29462
  this.logger = logger;
29279
- this.directory = dataDir2 ? join13(dataDir2, "transcripts") : "";
29463
+ this.directory = dataDir2 ? join14(dataDir2, "transcripts") : "";
29280
29464
  this.enabled = Boolean(dataDir2) && transcriptsOnDisk(env);
29281
29465
  }
29282
29466
  logger;
@@ -29331,7 +29515,7 @@ var TranscriptStore = class {
29331
29515
  await this.writes.get(runId);
29332
29516
  let text2;
29333
29517
  try {
29334
- text2 = await readFile4(join13(this.directory, name), "utf8");
29518
+ text2 = await readFile5(join14(this.directory, name), "utf8");
29335
29519
  } catch (error62) {
29336
29520
  if (errorCode(error62) !== "ENOENT") this.logger.warn("run-transcript-read-failed", { runId, error: errorMessage(error62) });
29337
29521
  return void 0;
@@ -29396,10 +29580,10 @@ var TranscriptStore = class {
29396
29580
  transcript.dirty = false;
29397
29581
  const body = JSON.stringify(transcript.toFile());
29398
29582
  await this.ensureDirectory();
29399
- const file2 = join13(this.directory, name);
29583
+ const file2 = join14(this.directory, name);
29400
29584
  const temporary = `${file2}.${process.pid}.tmp`;
29401
- await writeFile4(temporary, body, { mode: 384 });
29402
- await rename4(temporary, file2);
29585
+ await writeFile5(temporary, body, { mode: 384 });
29586
+ await rename5(temporary, file2);
29403
29587
  this.cache.delete(runId);
29404
29588
  }).catch((error62) => {
29405
29589
  transcript.dirty = true;
@@ -29418,8 +29602,8 @@ var TranscriptStore = class {
29418
29602
  }
29419
29603
  async ensureDirectory() {
29420
29604
  if (this.directoryReady) return;
29421
- await mkdir4(this.directory, { recursive: true, mode: 448 });
29422
- await chmod3(this.directory, 448).catch(() => void 0);
29605
+ await mkdir5(this.directory, { recursive: true, mode: 448 });
29606
+ await chmod4(this.directory, 448).catch(() => void 0);
29423
29607
  this.directoryReady = true;
29424
29608
  }
29425
29609
  async pruneOnce() {
@@ -29433,29 +29617,29 @@ var TranscriptStore = class {
29433
29617
  const now = Date.now();
29434
29618
  const files = [];
29435
29619
  for (const name of names) {
29436
- const path = join13(this.directory, name);
29620
+ const path = join14(this.directory, name);
29437
29621
  if (name.endsWith(".tmp")) {
29438
- const info2 = await stat2(path).catch(() => void 0);
29622
+ const info2 = await stat3(path).catch(() => void 0);
29439
29623
  if (info2?.isFile() && now - info2.mtimeMs > STALE_TEMPORARY_MS) await unlink(path).catch(() => void 0);
29440
29624
  continue;
29441
29625
  }
29442
29626
  if (!name.endsWith(".json")) continue;
29443
- const info = await stat2(path).catch(() => void 0);
29627
+ const info = await stat3(path).catch(() => void 0);
29444
29628
  if (info?.isFile()) files.push({ runId: name.slice(0, -".json".length), path, mtime: info.mtimeMs, size: info.size });
29445
29629
  }
29446
29630
  files.sort((a, b) => b.mtime - a.mtime);
29447
- let count = 0;
29631
+ let count2 = 0;
29448
29632
  let bytes = 0;
29449
29633
  let full = false;
29450
29634
  for (const file2 of files) {
29451
29635
  const live = this.tracked.has(file2.runId) || this.writes.has(file2.runId);
29452
- if (!live && (full || count + 1 > MAX_FILES || bytes + file2.size > MAX_TOTAL_BYTES)) {
29636
+ if (!live && (full || count2 + 1 > MAX_FILES || bytes + file2.size > MAX_TOTAL_BYTES)) {
29453
29637
  full = true;
29454
29638
  await unlink(file2.path).catch(() => void 0);
29455
29639
  this.cache.delete(file2.runId);
29456
29640
  continue;
29457
29641
  }
29458
- count += 1;
29642
+ count2 += 1;
29459
29643
  bytes += file2.size;
29460
29644
  }
29461
29645
  }
@@ -29482,24 +29666,24 @@ function errorMessage(error62) {
29482
29666
  // src/runs/task-attachments.ts
29483
29667
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
29484
29668
  import { constants as constants2 } from "node:fs";
29485
- import { lstat, mkdir as mkdir5, open as open3, realpath, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
29486
- import { basename, isAbsolute as isAbsolute2, join as join14, relative } from "node:path";
29669
+ import { lstat, mkdir as mkdir6, open as open3, realpath, rename as rename6, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";
29670
+ import { basename, isAbsolute as isAbsolute3, join as join15, relative } from "node:path";
29487
29671
  function within(root2, path) {
29488
29672
  const segment = relative(root2, path);
29489
- return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
29673
+ return segment === "" || !segment.startsWith("..") && !isAbsolute3(segment);
29490
29674
  }
29491
29675
  async function attachmentDirectory(workdir, messageId) {
29492
29676
  let directory = workdir;
29493
29677
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
29494
- directory = join14(directory, segment);
29495
- await mkdir5(directory, { mode: 448 }).catch((error62) => {
29678
+ directory = join15(directory, segment);
29679
+ await mkdir6(directory, { mode: 448 }).catch((error62) => {
29496
29680
  if (error62.code !== "EEXIST") throw error62;
29497
29681
  });
29498
29682
  const metadata = await lstat(directory);
29499
29683
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
29500
29684
  throw new Error("\u9644\u4EF6\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E CLI \u5DE5\u4F5C\u76EE\u5F55\u5185\uFF0C\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5");
29501
29685
  }
29502
- if (segment === ".echo") await writeFile5(join14(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
29686
+ if (segment === ".echo") await writeFile6(join15(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
29503
29687
  if (error62.code !== "EEXIST") throw error62;
29504
29688
  });
29505
29689
  }
@@ -29536,14 +29720,14 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
29536
29720
  const characters = Array.from(basename(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
29537
29721
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
29538
29722
  const name = characters.join("") || "attachment";
29539
- const path = join14(directory, `${file2.file_id}-${name}`);
29723
+ const path = join15(directory, `${file2.file_id}-${name}`);
29540
29724
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
29541
- const temporary = join14(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
29725
+ const temporary = join15(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
29542
29726
  try {
29543
29727
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
29544
29728
  signal2.throwIfAborted();
29545
29729
  if (!within(workdir, await realpath(directory))) throw new Error("\u9644\u4EF6\u76EE\u5F55\u5DF2\u6539\u53D8\uFF0C\u8BF7\u91CD\u8BD5");
29546
- await rename5(temporary, path);
29730
+ await rename6(temporary, path);
29547
29731
  } finally {
29548
29732
  await rm3(temporary, { force: true });
29549
29733
  }
@@ -29653,7 +29837,7 @@ var ChatEventForwarder = class {
29653
29837
 
29654
29838
  // src/acp/chat-session.ts
29655
29839
  import { randomUUID as randomUUID3 } from "node:crypto";
29656
- import { readFile as readFile5, stat as stat3 } from "node:fs/promises";
29840
+ import { readFile as readFile6, stat as stat4 } from "node:fs/promises";
29657
29841
  import { extname } from "node:path";
29658
29842
  import { pathToFileURL } from "node:url";
29659
29843
 
@@ -29892,6 +30076,46 @@ function redactSecretAnswers(elicitation, outcome) {
29892
30076
  return { ...outcome, _meta: { ...outcome._meta, lody: { ...lody, elicitation: { ...elicitationMeta, answers } } } };
29893
30077
  }
29894
30078
 
30079
+ // src/acp/usage-tally.ts
30080
+ var MAX_MODELS = 20;
30081
+ function count(value) {
30082
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
30083
+ }
30084
+ var UsageTally = class {
30085
+ models = /* @__PURE__ */ new Map();
30086
+ /** One `_lody/session/usage_update` params object. */
30087
+ add(params) {
30088
+ const delta = params.delta;
30089
+ if (!delta || typeof delta !== "object") return;
30090
+ const modelUsage = delta.modelUsage;
30091
+ if (!modelUsage || typeof modelUsage !== "object") return;
30092
+ for (const [rawModel, raw] of Object.entries(modelUsage)) {
30093
+ if (!raw || typeof raw !== "object") continue;
30094
+ const usage = raw;
30095
+ const model = rawModel.trim().slice(0, 200) || "unknown";
30096
+ let entry = this.models.get(model);
30097
+ if (!entry) {
30098
+ if (this.models.size >= MAX_MODELS) continue;
30099
+ entry = { model, input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0, cost_usd: 0 };
30100
+ this.models.set(model, entry);
30101
+ }
30102
+ entry.input_tokens += count(usage.inputTokens);
30103
+ entry.output_tokens += count(usage.outputTokens);
30104
+ entry.cache_read_tokens += count(usage.cacheReadInputTokens);
30105
+ entry.cache_write_tokens += count(usage.cacheCreationInputTokens);
30106
+ entry.reasoning_tokens += count(usage.reasoningOutputTokens);
30107
+ const cost = usage.costUSD;
30108
+ if (entry.cost_usd !== null) {
30109
+ entry.cost_usd = typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? entry.cost_usd + cost : null;
30110
+ }
30111
+ }
30112
+ }
30113
+ /** The models that counted anything. */
30114
+ list() {
30115
+ return [...this.models.values()].filter((entry) => entry.input_tokens + entry.output_tokens + entry.cache_read_tokens + entry.cache_write_tokens + entry.reasoning_tokens > 0);
30116
+ }
30117
+ };
30118
+
29895
30119
  // src/acp/chat-session.ts
29896
30120
  var CANCELLED_PERMISSION = { outcome: { outcome: "cancelled" } };
29897
30121
  var QUESTION_OPTIONS = [
@@ -29930,7 +30154,7 @@ var AcpChatSession = class {
29930
30154
  this.clearIdle();
29931
30155
  this.lastUsedAt = Date.now();
29932
30156
  const transcript = new TurnTranscript((events) => sink.events(events), (rows) => sink.rows(rows));
29933
- const turn = { runId: request.runId, phase: "starting", request, transcript, sink, cancelRequested: false, loading: false, queued: [], awaiting: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map() };
30157
+ const turn = { runId: request.runId, phase: "starting", request, transcript, sink, cancelRequested: false, loading: false, queued: [], awaiting: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), usage: new UsageTally() };
29934
30158
  this.turn = turn;
29935
30159
  for (const note of request.notes) transcript.note(note);
29936
30160
  let result;
@@ -29949,6 +30173,8 @@ var AcpChatSession = class {
29949
30173
  turn.awaiting.clear();
29950
30174
  transcript.flushRows();
29951
30175
  result.finalMessage = transcript.finalMessage;
30176
+ const usage = turn.usage.list();
30177
+ if (usage.length) result.usage = usage;
29952
30178
  this.turn = void 0;
29953
30179
  this.lastUsedAt = Date.now();
29954
30180
  this.scheduleIdle();
@@ -30123,7 +30349,14 @@ var AcpChatSession = class {
30123
30349
  if (wanted && connection.canOpenSaved && (this.spec.resumable?.(wanted) ?? true)) {
30124
30350
  turn.loading = true;
30125
30351
  try {
30126
- this.session = await connection.openSaved(wanted, request.workdir);
30352
+ try {
30353
+ this.session = await connection.openSaved(wanted, request.workdir);
30354
+ } catch (error62) {
30355
+ if (!(connection.alive && isArchivedSessionError(error62))) throw error62;
30356
+ await connection.extRequest("_session/unarchive", { sessionId: wanted });
30357
+ transcript.note(`\u4F1A\u8BDD ${wanted} \u5DF2\u53D6\u6D88\u5F52\u6863`);
30358
+ this.session = await connection.openSaved(wanted, request.workdir);
30359
+ }
30127
30360
  transcript.note(`\u7EE7\u7EED\u4F1A\u8BDD ${wanted}`);
30128
30361
  return this.session;
30129
30362
  } catch (error62) {
@@ -30180,8 +30413,9 @@ var AcpChatSession = class {
30180
30413
  const value = option2 ? matchChoice(option2, request.reasoningEffort) : void 0;
30181
30414
  if (option2 && value && option2.currentValue !== value) await attempt("\u63A8\u7406\u5F3A\u5EA6", () => this.setOption(connection, session, option2, value));
30182
30415
  }
30183
- const fast = session.configOptions.find((option2) => option2.id === "fast" && option2.options.some((choice) => choice.value === "on"));
30416
+ const fast = fastOption(session.configOptions);
30184
30417
  if (fast && (request.fast ? "on" : "off") !== fast.currentValue) await attempt("\u5FEB\u901F\u6A21\u5F0F", () => this.setOption(connection, session, fast, request.fast ? "on" : "off"));
30418
+ else if (!fast && request.fast) transcript.note(`${this.spec.cli.label} \u7684\u5F53\u524D\u6A21\u578B\u6CA1\u6709\u5FEB\u901F\u6A21\u5F0F\uFF0C\u672C\u8F6E\u6309\u666E\u901A\u901F\u5EA6\u8FD0\u884C`);
30185
30419
  turn.transcript.sessionConfig({ ...session.currentModeId ? { currentModeId: session.currentModeId } : {}, configOptions: session.configOptions });
30186
30420
  }
30187
30421
  async setOption(connection, session, option2, value) {
@@ -30196,9 +30430,9 @@ var AcpChatSession = class {
30196
30430
  for (const file2 of request.attachments) {
30197
30431
  const mimeType = IMAGE_TYPES[extname(file2.path).toLowerCase()];
30198
30432
  if (file2.kind === "image" && mimeType && connection.imagePrompts) {
30199
- const size = await stat3(file2.path).then((info) => info.size).catch(() => 0);
30433
+ const size = await stat4(file2.path).then((info) => info.size).catch(() => 0);
30200
30434
  if (size > 0 && size <= MAX_IMAGE_BYTES) {
30201
- blocks.push({ type: "image", mimeType, data: (await readFile5(file2.path)).toString("base64") });
30435
+ blocks.push({ type: "image", mimeType, data: (await readFile6(file2.path)).toString("base64") });
30202
30436
  continue;
30203
30437
  }
30204
30438
  }
@@ -30290,7 +30524,7 @@ var AcpChatSession = class {
30290
30524
  const shown = turn.transcript.permissionRequest(toolCall, { requestId, options, ...meta3 ? { _meta: meta3 } : {}, outcome: null });
30291
30525
  const title = elicitation ? String(toolCall.title) : shown.title ?? (typeof toolCall.title === "string" && toolCall.title ? toolCall.title : "\u5DE5\u5177\u8C03\u7528");
30292
30526
  turn.transcript.note(elicitation ? `\u7B49\u5F85\u56DE\u7B54\u95EE\u9898\uFF1A${title}` : `\u7B49\u5F85\u6388\u6743\uFF1A${title}`);
30293
- return new Promise((resolve9) => {
30527
+ return new Promise((resolve10) => {
30294
30528
  const withdrawn = () => {
30295
30529
  if (!turn.pending.has(requestId)) return;
30296
30530
  turn.transcript.note(this.connection?.alive ? `CLI \u5DF2\u64A4\u56DE\u8BF7\u6C42\uFF1A${title}` : `CLI \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u5DF2\u53D6\u6D88${elicitation ? "\u95EE\u9898" : "\u6388\u6743\u8BF7\u6C42"}\uFF1A${title}`);
@@ -30307,7 +30541,7 @@ var AcpChatSession = class {
30307
30541
  turn.pending.delete(requestId);
30308
30542
  signal2.removeEventListener("abort", withdrawn);
30309
30543
  turn.transcript.permissionOutcome(toolCallId, requestId, elicitation ? redactSecretAnswers(elicitation, outcome) : outcome);
30310
- resolve9(outcome);
30544
+ resolve10(outcome);
30311
30545
  }
30312
30546
  };
30313
30547
  turn.pending.set(requestId, pending);
@@ -30335,6 +30569,7 @@ var AcpChatSession = class {
30335
30569
  }
30336
30570
  if (!turn) return;
30337
30571
  if (method === "_lody/session/usage_update") {
30572
+ if (!turn.loading) turn.usage.add(params);
30338
30573
  turn.transcript.usage(params);
30339
30574
  return;
30340
30575
  }
@@ -30395,10 +30630,18 @@ var AcpChatSession = class {
30395
30630
  if (connection) await connection.dispose().catch(() => void 0);
30396
30631
  }
30397
30632
  };
30633
+ function isArchivedSessionError(error62) {
30634
+ if (!(error62 instanceof JsonRpcError)) return false;
30635
+ const data = error62.data && typeof error62.data === "object" ? error62.data : {};
30636
+ return data.reason === "archived" || /^Session is archived\b/.test(error62.message);
30637
+ }
30398
30638
  function permissionOptions(value) {
30399
30639
  if (!Array.isArray(value)) return [];
30400
30640
  return value.map(record2).flatMap((option2) => typeof option2.optionId === "string" && option2.optionId ? [{ optionId: option2.optionId, name: typeof option2.name === "string" ? option2.name : option2.optionId, kind: typeof option2.kind === "string" ? option2.kind : "" }] : []);
30401
30641
  }
30642
+ function fastOption(options) {
30643
+ return options.find((option2) => (option2.id === "fast" || option2.id === "fast-mode") && option2.options.some((choice) => choice.value === "on"));
30644
+ }
30402
30645
  function findOption(options, category) {
30403
30646
  const ids = { thought_level: ["effort", "reasoning_effort", "thought_level"], model: ["model"], mode: ["mode"] };
30404
30647
  return options.find((option2) => option2.category === category && option2.options.length) ?? options.find((option2) => (ids[category] ?? [category]).includes(option2.id) && option2.options.length);
@@ -30486,6 +30729,40 @@ var AcpChatHost = class {
30486
30729
  if (!session || session.runId !== runId) return { outcome: "not-found" };
30487
30730
  return session.answerPermission(requestId, outcome);
30488
30731
  }
30732
+ /** Stops the live process of one Echo session (archived): a running turn is cancelled first. */
30733
+ async closeSession(key) {
30734
+ const session = this.sessions.get(key);
30735
+ if (!session) return false;
30736
+ this.sessions.delete(key);
30737
+ await session.close();
30738
+ this.options.logger.info("acp-session-closed", { session: key });
30739
+ return true;
30740
+ }
30741
+ /**
30742
+ * Archives or restores the CLI's own session (Lody's archive), through the
30743
+ * adapter's `_session/archive` / `_session/unarchive`: Codex moves the
30744
+ * thread to its archived sessions, Claude marks the transcript. The Echo
30745
+ * session's live process stops first, so nothing holds the session open;
30746
+ * a short-lived adapter process makes the call.
30747
+ */
30748
+ async setArchived(key, sessionId, archived, launch) {
30749
+ if (key) await this.closeSession(key);
30750
+ const connection = await AcpConnection.open(launch.launch, {
30751
+ update: () => {
30752
+ },
30753
+ permission: () => ({ outcome: { outcome: "cancelled" } }),
30754
+ notification: () => {
30755
+ },
30756
+ stderr: () => {
30757
+ }
30758
+ }, this.options.clientVersion);
30759
+ try {
30760
+ await connection.extRequest(archived ? "_session/archive" : "_session/unarchive", { sessionId });
30761
+ this.options.logger.info(archived ? "acp-session-archived" : "acp-session-unarchived", { session: key ?? "", sessionId });
30762
+ } finally {
30763
+ await connection.dispose();
30764
+ }
30765
+ }
30489
30766
  async disposeAll() {
30490
30767
  const sessions = [...this.sessions.values()];
30491
30768
  this.sessions.clear();
@@ -30527,14 +30804,14 @@ var MAX_OUTPUT_BYTES = 1024 * 1024;
30527
30804
  var runNmem = (args) => {
30528
30805
  const env = providerEnvironment();
30529
30806
  const launch = resolveExecutable("nmem", args, env, process.env.TOC_OCRA_NMEM_PATH);
30530
- return new Promise((resolve9) => {
30807
+ return new Promise((resolve10) => {
30531
30808
  execFile5(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true }, (error62, stdout) => {
30532
30809
  if (!error62) {
30533
- resolve9({ stdout: String(stdout) });
30810
+ resolve10({ stdout: String(stdout) });
30534
30811
  return;
30535
30812
  }
30536
30813
  const failure2 = error62;
30537
- resolve9({ stdout: String(stdout ?? ""), code: failure2.code ?? "failed" });
30814
+ resolve10({ stdout: String(stdout ?? ""), code: failure2.code ?? "failed" });
30538
30815
  });
30539
30816
  });
30540
30817
  };
@@ -30816,6 +31093,7 @@ var RunSupervisor = class {
30816
31093
  } catch (error62) {
30817
31094
  return refuse({ kind: "hostFault", message: `${errorMessage2(error62)}\uFF0C\u8BF7\u5347\u7EA7\u8BBE\u5907\u4EE3\u7406` });
30818
31095
  }
31096
+ if (cli.id === "codex") await prepareCodexCatalog();
30819
31097
  let provider = cli.headless;
30820
31098
  let workdir;
30821
31099
  try {
@@ -30928,7 +31206,7 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
30928
31206
  if (!fitsCommandLine(launch)) return refuse(cliFailure("promptTooLong", { label: cli.label }));
30929
31207
  let child;
30930
31208
  try {
30931
- child = spawn10(launch.executable, launch.args, {
31209
+ child = spawn11(launch.executable, launch.args, {
30932
31210
  cwd: workdir,
30933
31211
  env: Object.keys(memoryEnv).length ? { ...launch.env, ...memoryEnv } : launch.env,
30934
31212
  detached: currentPlatform.runsInOwnProcessGroup,
@@ -31219,6 +31497,7 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
31219
31497
  else report = failedReport(result.failure ?? cliFailure("turnFailed", { label: cli.label }), durationMs);
31220
31498
  if (result.sessionId) report.session_id = result.sessionId;
31221
31499
  if (result.finalMessage) report.final_message = sanitizeChatText(result.finalMessage);
31500
+ if (result.usage?.length) report.token_usage = result.usage;
31222
31501
  this.log(run2, `\u25CF \u672C\u8F6E\u7ED3\u675F\uFF1A${report.status}
31223
31502
  `);
31224
31503
  await this.settleTranscript(transcript, report.status);
@@ -31460,16 +31739,16 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
31460
31739
  async prepareChatAttachments(payload) {
31461
31740
  if (!payload.attachments?.length) return [];
31462
31741
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
31463
- const directory = join15(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
31464
- await mkdir6(directory, { recursive: true, mode: 448 });
31742
+ const directory = join16(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
31743
+ await mkdir7(directory, { recursive: true, mode: 448 });
31465
31744
  const files = [];
31466
31745
  for (const attachment of payload.attachments) {
31467
31746
  const name = basename2(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
31468
- const path = join15(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
31469
- const existing = await stat4(path).catch(() => void 0);
31747
+ const path = join16(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
31748
+ const existing = await stat5(path).catch(() => void 0);
31470
31749
  if (!existing?.isFile()) {
31471
31750
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
31472
- await writeFile6(path, data, { mode: 384 });
31751
+ await writeFile7(path, data, { mode: 384 });
31473
31752
  }
31474
31753
  files.push({ path, name: attachment.name, kind: attachment.kind });
31475
31754
  }
@@ -31479,6 +31758,28 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
31479
31758
  this.unreported.add(runId);
31480
31759
  await this.reporter.finished(runId, report);
31481
31760
  }
31761
+ /**
31762
+ * `cli.session.archive` (Lody's 归档): the Echo session's live process stops,
31763
+ * then the CLI archives or restores its own session. `native: false` when
31764
+ * this CLI has no ACP adapter here (nothing to archive on its side).
31765
+ */
31766
+ async setCliSessionArchived(input2) {
31767
+ const id = catalogEntry(input2.agentType)?.id;
31768
+ const spec = id ? acpChatSpec(id) : void 0;
31769
+ if (!spec) {
31770
+ if (input2.key) await this.acpChats.closeSession(input2.key);
31771
+ return { native: false };
31772
+ }
31773
+ let workdir;
31774
+ try {
31775
+ workdir = input2.workdir ? await this.validateWorkdir(input2.workdir) : await this.defaultChatWorkdir();
31776
+ } catch {
31777
+ workdir = await this.defaultChatWorkdir();
31778
+ }
31779
+ const launch = await this.acpChats.prepare(spec, { access: "default", reasoningEffort: "", model: "", workdir });
31780
+ await this.acpChats.setArchived(input2.key, input2.sessionId, input2.archived, launch);
31781
+ return { native: true };
31782
+ }
31482
31783
  /** Stops a run: the whole process tree, then a `cancelled` report. */
31483
31784
  async cancel(runId) {
31484
31785
  const acp = this.acpRuns.get(runId);
@@ -31594,14 +31895,14 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
31594
31895
  if (!input2) throw new Error("\u6CA1\u6709\u914D\u7F6E\u5141\u8BB8\u7684\u5DE5\u4F5C\u76EE\u5F55");
31595
31896
  let candidate;
31596
31897
  try {
31597
- candidate = await realpath2(isAbsolute3(input2) ? input2 : resolve4(input2));
31898
+ candidate = await realpath2(isAbsolute4(input2) ? input2 : resolve5(input2));
31598
31899
  } catch {
31599
31900
  throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${input2}`);
31600
31901
  }
31601
31902
  for (const root2 of this.config.allowedRoots) {
31602
- const allowed = await realpath2(root2).catch(() => resolve4(root2));
31903
+ const allowed = await realpath2(root2).catch(() => resolve5(root2));
31603
31904
  const segment = relative2(allowed, candidate);
31604
- if (segment === "" || !segment.startsWith("..") && !isAbsolute3(segment)) return candidate;
31905
+ if (segment === "" || !segment.startsWith("..") && !isAbsolute4(segment)) return candidate;
31605
31906
  }
31606
31907
  throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5728\u5141\u8BB8\u8303\u56F4\u5185\uFF1A${input2}`);
31607
31908
  }
@@ -31638,7 +31939,7 @@ var silent = { debug() {
31638
31939
  async function runCliSmoke(options = {}) {
31639
31940
  const detection = await cliDetection.detect(true);
31640
31941
  const ids = options.only?.length ? options.only.map((id) => catalogEntry(id)?.id ?? id) : CLI_CATALOG.filter((entry) => entry.headless && detection.detectedIds.includes(entry.id)).map((entry) => entry.id);
31641
- const root2 = await realpath3(await mkdtemp(join16(tmpdir2(), "toc-ocra-smoke-")));
31942
+ const root2 = await realpath3(await mkdtemp(join17(tmpdir2(), "toc-ocra-smoke-")));
31642
31943
  const finished = /* @__PURE__ */ new Map();
31643
31944
  const config2 = { allowedRoots: [root2], maxConcurrentRuns: 0, maxRunSeconds: options.timeoutSeconds ?? 300, dataDir: root2 };
31644
31945
  const supervisor = new RunSupervisor(config2, silent, {
@@ -31675,7 +31976,7 @@ async function runCliSmoke(options = {}) {
31675
31976
  workdir: root2,
31676
31977
  ...extra
31677
31978
  });
31678
- while (!finished.has(runId)) await new Promise((resolve9) => setTimeout(resolve9, 200));
31979
+ while (!finished.has(runId)) await new Promise((resolve10) => setTimeout(resolve10, 200));
31679
31980
  const report = finished.get(runId);
31680
31981
  supervisor.markReported(runId);
31681
31982
  const result = {
@@ -31711,11 +32012,11 @@ async function runCliSmoke(options = {}) {
31711
32012
 
31712
32013
  // src/runtime/run-service.ts
31713
32014
  import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
31714
- import { dirname as dirname8, resolve as resolve7 } from "node:path";
32015
+ import { dirname as dirname9, resolve as resolve8 } from "node:path";
31715
32016
  import { fileURLToPath as fileURLToPath2 } from "node:url";
31716
32017
 
31717
32018
  // src/health/server.ts
31718
- import { readFile as readFile6 } from "node:fs/promises";
32019
+ import { readFile as readFile7 } from "node:fs/promises";
31719
32020
  import { createServer } from "node:http";
31720
32021
  var ControlError = class extends Error {
31721
32022
  constructor(status, message, code2 = "bad_request") {
@@ -31896,7 +32197,7 @@ var HealthServer = class {
31896
32197
  }
31897
32198
  async recentEvents() {
31898
32199
  try {
31899
- const raw = await readFile6(this.logFile, "utf8");
32200
+ const raw = await readFile7(this.logFile, "utf8");
31900
32201
  return raw.trim().split("\n").slice(-60).flatMap((line) => {
31901
32202
  try {
31902
32203
  const parsed = JSON.parse(line);
@@ -31957,11 +32258,11 @@ import {
31957
32258
  mkdirSync as mkdirSync3,
31958
32259
  readFileSync as readFileSync6,
31959
32260
  renameSync,
31960
- statSync as statSync3,
32261
+ statSync as statSync4,
31961
32262
  unlinkSync,
31962
32263
  writeFileSync as writeFileSync2
31963
32264
  } from "node:fs";
31964
- import { dirname as dirname5 } from "node:path";
32265
+ import { dirname as dirname6 } from "node:path";
31965
32266
  var DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
31966
32267
  var DEFAULT_MAX_ROTATED_FILES = 2;
31967
32268
  var PRIVATE_FILE_MODE = 384;
@@ -31985,9 +32286,9 @@ function createDiagnosticLogger(filePath, options = {}) {
31985
32286
  let disabled = false;
31986
32287
  let currentBytes = 0;
31987
32288
  try {
31988
- mkdirSync3(dirname5(filePath), { recursive: true });
32289
+ mkdirSync3(dirname6(filePath), { recursive: true });
31989
32290
  pruneExpired();
31990
- currentBytes = existsSync5(filePath) ? statSync3(filePath).size : 0;
32291
+ currentBytes = existsSync5(filePath) ? statSync4(filePath).size : 0;
31991
32292
  } catch {
31992
32293
  disabled = true;
31993
32294
  }
@@ -32073,10 +32374,10 @@ function createDiagnosticLogger(filePath, options = {}) {
32073
32374
 
32074
32375
  // src/runtime/agent-runtime.ts
32075
32376
  import { randomUUID as randomUUID4 } from "node:crypto";
32076
- import { join as join19 } from "node:path";
32377
+ import { join as join20 } from "node:path";
32077
32378
 
32078
32379
  // src/exec/script-runner.ts
32079
- import { spawn as spawn11 } from "node:child_process";
32380
+ import { spawn as spawn12 } from "node:child_process";
32080
32381
  var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
32081
32382
  function executeScript(command, workdir, timeoutSeconds) {
32082
32383
  return new Promise((resolveExecution) => {
@@ -32107,7 +32408,7 @@ function executeScript(command, workdir, timeoutSeconds) {
32107
32408
  };
32108
32409
  let child;
32109
32410
  try {
32110
- child = spawn11(executable, args, {
32411
+ child = spawn12(executable, args, {
32111
32412
  cwd: workdir,
32112
32413
  env: process.env,
32113
32414
  detached: ownGroup,
@@ -32178,10 +32479,10 @@ function executeScript(command, workdir, timeoutSeconds) {
32178
32479
 
32179
32480
  // src/providers/model-catalog-collector.ts
32180
32481
  import { createHash as createHash3 } from "node:crypto";
32181
- import { stat as stat5 } from "node:fs/promises";
32182
- async function fileStamp(path) {
32482
+ import { stat as stat6 } from "node:fs/promises";
32483
+ async function fileStamp2(path) {
32183
32484
  try {
32184
- const info = await stat5(path);
32485
+ const info = await stat6(path);
32185
32486
  return `${path}:${info.mtimeMs}:${info.size}`;
32186
32487
  } catch {
32187
32488
  return `${path}:-`;
@@ -32213,14 +32514,14 @@ var ModelCatalogCollector = class {
32213
32514
  async readOne(id, force) {
32214
32515
  const source = this.sources[id];
32215
32516
  const now = Date.now();
32216
- const stamps = await Promise.all(source.watchFiles().map(fileStamp));
32517
+ const stamps = await Promise.all(source.watchFiles().map(fileStamp2));
32217
32518
  const fingerprint = stamps.join("|");
32218
32519
  const cached3 = this.cache.get(id);
32219
32520
  const expired = source.refreshEveryMs !== void 0 && cached3 !== void 0 && now - cached3.readAt >= source.refreshEveryMs;
32220
32521
  if (cached3 && !force && !expired && cached3.fingerprint === fingerprint) return cached3.item;
32221
32522
  let item;
32222
32523
  try {
32223
- const catalog = await source.read();
32524
+ const catalog = await source.read({ force });
32224
32525
  item = { agent_type: id, catalog: { ...catalog, agent_type: id } };
32225
32526
  } catch (error62) {
32226
32527
  item = { agent_type: id, error: error62 instanceof Error ? error62.message : String(error62) };
@@ -32244,16 +32545,16 @@ async function readCLIQuotaReport(agentType) {
32244
32545
  }
32245
32546
 
32246
32547
  // src/providers/tb-switch-control.ts
32247
- import { readFile as readFile7 } from "node:fs/promises";
32248
- import { homedir as homedir8 } from "node:os";
32249
- import { join as join17 } from "node:path";
32548
+ import { readFile as readFile8 } from "node:fs/promises";
32549
+ import { homedir as homedir9 } from "node:os";
32550
+ import { join as join18 } from "node:path";
32250
32551
  function dataDir() {
32251
- return process.env.TB_SWITCH_HOME?.trim() || join17(homedir8(), ".tb-switch");
32552
+ return process.env.TB_SWITCH_HOME?.trim() || join18(homedir9(), ".tb-switch");
32252
32553
  }
32253
32554
  async function readLocalService() {
32254
32555
  let discovery;
32255
32556
  try {
32256
- discovery = JSON.parse(await readFile7(join17(dataDir(), "api.json"), "utf8"));
32557
+ discovery = JSON.parse(await readFile8(join18(dataDir(), "api.json"), "utf8"));
32257
32558
  } catch {
32258
32559
  throw new Error("\u8FD9\u53F0\u8BBE\u5907\u4E0A\u7684 TB Switch \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u8BF7\u6253\u5F00\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
32259
32560
  }
@@ -32269,7 +32570,7 @@ async function readLocalService() {
32269
32570
  }
32270
32571
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
32271
32572
  try {
32272
- token = (await readFile7(join17(dataDir(), "api-token"), "utf8")).trim();
32573
+ token = (await readFile8(join18(dataDir(), "api-token"), "utf8")).trim();
32273
32574
  } catch {
32274
32575
  }
32275
32576
  if (!token) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 TB Switch \u672C\u673A\u670D\u52A1\u51ED\u636E\uFF0C\u8BF7\u91CD\u542F\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
@@ -32359,8 +32660,8 @@ async function controlTbSwitch(payload) {
32359
32660
  }
32360
32661
 
32361
32662
  // src/runs/orphan-registry.ts
32362
- import { mkdir as mkdir7, readFile as readFile8, rename as rename6, writeFile as writeFile7 } from "node:fs/promises";
32363
- import { basename as basename3, dirname as dirname6 } from "node:path";
32663
+ import { mkdir as mkdir8, readFile as readFile9, rename as rename7, writeFile as writeFile8 } from "node:fs/promises";
32664
+ import { basename as basename3, dirname as dirname7 } from "node:path";
32364
32665
  var OrphanRegistry = class {
32365
32666
  constructor(file2) {
32366
32667
  this.file = file2;
@@ -32378,17 +32679,17 @@ var OrphanRegistry = class {
32378
32679
  persist() {
32379
32680
  const snapshot = JSON.stringify([...this.records.values()]);
32380
32681
  this.writing = this.writing.then(async () => {
32381
- await mkdir7(dirname6(this.file), { recursive: true, mode: 448 });
32682
+ await mkdir8(dirname7(this.file), { recursive: true, mode: 448 });
32382
32683
  const temporary = `${this.file}.${process.pid}.tmp`;
32383
- await writeFile7(temporary, snapshot, { mode: 384 });
32384
- await rename6(temporary, this.file);
32684
+ await writeFile8(temporary, snapshot, { mode: 384 });
32685
+ await rename7(temporary, this.file);
32385
32686
  }).catch(() => void 0);
32386
32687
  }
32387
32688
  /** Kills leftovers from a previous agent process; returns what was stopped. */
32388
32689
  async reapPrevious() {
32389
32690
  let previous = [];
32390
32691
  try {
32391
- previous = JSON.parse(await readFile8(this.file, "utf8"));
32692
+ previous = JSON.parse(await readFile9(this.file, "utf8"));
32392
32693
  } catch {
32393
32694
  return [];
32394
32695
  }
@@ -32540,16 +32841,16 @@ var GatewayClient = class {
32540
32841
  };
32541
32842
 
32542
32843
  // src/workspace/directory-browser.ts
32543
- import { readdir as readdir3, realpath as realpath4, stat as stat6 } from "node:fs/promises";
32544
- import { homedir as homedir9 } from "node:os";
32545
- import { dirname as dirname7, parse as parse3, resolve as resolve5 } from "node:path";
32844
+ import { readdir as readdir3, realpath as realpath4, stat as stat7 } from "node:fs/promises";
32845
+ import { homedir as homedir10 } from "node:os";
32846
+ import { dirname as dirname8, parse as parse3, resolve as resolve6 } from "node:path";
32546
32847
  var MAX_ENTRIES = 1e3;
32547
32848
  async function listDirectory(requested, allowedRoots) {
32548
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir9()) || homedir9();
32549
- const directory = await realpath4(resolve5(raw)).catch(() => {
32849
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir10()) || homedir10();
32850
+ const directory = await realpath4(resolve6(raw)).catch(() => {
32550
32851
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
32551
32852
  });
32552
- if (!(await stat6(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
32853
+ if (!(await stat7(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
32553
32854
  const entries = await readdir3(directory, { withFileTypes: true }).catch((error62) => {
32554
32855
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
32555
32856
  });
@@ -32558,13 +32859,13 @@ async function listDirectory(requested, allowedRoots) {
32558
32859
  const files = [];
32559
32860
  for (const entry of entries) {
32560
32861
  if (entry.isSymbolicLink()) continue;
32561
- const item = { name: entry.name, path: resolve5(directory, entry.name), hidden: entry.name.startsWith(".") };
32862
+ const item = { name: entry.name, path: resolve6(directory, entry.name), hidden: entry.name.startsWith(".") };
32562
32863
  if (entry.isDirectory()) directories.push(item);
32563
32864
  else if (entry.isFile()) files.push(item);
32564
32865
  }
32565
- const parent = dirname7(directory);
32566
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir9() }];
32567
- for (const root2 of allowedRoots) if (root2 !== homedir9()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
32866
+ const parent = dirname8(directory);
32867
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir10() }];
32868
+ for (const root2 of allowedRoots) if (root2 !== homedir10()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
32568
32869
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
32569
32870
  return {
32570
32871
  path: directory,
@@ -32577,10 +32878,10 @@ async function listDirectory(requested, allowedRoots) {
32577
32878
  }
32578
32879
 
32579
32880
  // src/workspace/workspace-manager.ts
32580
- import { spawn as spawn12 } from "node:child_process";
32581
- import { chmod as chmod4, mkdir as mkdir8, mkdtemp as mkdtemp2, opendir, realpath as realpath5, rm as rm5, stat as stat7, writeFile as writeFile8 } from "node:fs/promises";
32582
- import { homedir as homedir10, tmpdir as tmpdir3 } from "node:os";
32583
- import { isAbsolute as isAbsolute4, join as join18, relative as relative3, resolve as resolve6 } from "node:path";
32881
+ import { spawn as spawn13 } from "node:child_process";
32882
+ import { chmod as chmod5, mkdir as mkdir9, mkdtemp as mkdtemp2, opendir, realpath as realpath5, rm as rm5, stat as stat8, writeFile as writeFile9 } from "node:fs/promises";
32883
+ import { homedir as homedir11, tmpdir as tmpdir3 } from "node:os";
32884
+ import { isAbsolute as isAbsolute5, join as join19, relative as relative3, resolve as resolve7 } from "node:path";
32584
32885
  var MAX_NODES = 2e3;
32585
32886
  var MAX_DIRECTORY_ENTRIES = 12e3;
32586
32887
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -32628,14 +32929,14 @@ var WorkspaceManager = class {
32628
32929
  };
32629
32930
  }
32630
32931
  validateRootPath(value) {
32631
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir10());
32632
- const root2 = resolve6(raw);
32633
- if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
32634
- if (relative3(root2, resolve6(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
32932
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir11());
32933
+ const root2 = resolve7(raw);
32934
+ if (!isAbsolute5(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
32935
+ if (relative3(root2, resolve7(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
32635
32936
  return root2;
32636
32937
  }
32637
32938
  async syncTree(rootPath, request) {
32638
- await mkdir8(rootPath, { recursive: true });
32939
+ await mkdir9(rootPath, { recursive: true });
32639
32940
  await addAllowedRoot(this.config, rootPath);
32640
32941
  const results = [];
32641
32942
  const requestedPaths = /* @__PURE__ */ new Set();
@@ -32645,7 +32946,7 @@ var WorkspaceManager = class {
32645
32946
  requestedPaths.add(relativePath);
32646
32947
  const target = this.resolveWithinRoot(rootPath, relativePath);
32647
32948
  try {
32648
- const metadata = await stat7(target).catch(() => void 0);
32949
+ const metadata = await stat8(target).catch(() => void 0);
32649
32950
  if (metadata) {
32650
32951
  if (!metadata.isDirectory()) {
32651
32952
  throw new Error("The existing workspace path is not a directory");
@@ -32659,7 +32960,7 @@ var WorkspaceManager = class {
32659
32960
  });
32660
32961
  continue;
32661
32962
  }
32662
- await mkdir8(target, { recursive: true });
32963
+ await mkdir9(target, { recursive: true });
32663
32964
  results.push({
32664
32965
  relative_path: relativePath,
32665
32966
  status: "created",
@@ -32703,12 +33004,12 @@ var WorkspaceManager = class {
32703
33004
  let created = false;
32704
33005
  let metadata;
32705
33006
  try {
32706
- metadata = await stat7(target);
33007
+ metadata = await stat8(target);
32707
33008
  } catch {
32708
33009
  }
32709
33010
  if (!metadata) {
32710
33011
  if (!gitUrl) throw new Error("A missing repository needs a Git remote URL");
32711
- await mkdir8(resolve6(target, ".."), { recursive: true });
33012
+ await mkdir9(resolve7(target, ".."), { recursive: true });
32712
33013
  const cloneArgs = branch ? ["clone", "--branch", branch, "--single-branch", gitUrl, target] : ["clone", gitUrl, target];
32713
33014
  await this.runGit(cloneArgs, rootPath, timeoutSeconds, false, gitEnvironment);
32714
33015
  created = true;
@@ -32803,7 +33104,7 @@ var WorkspaceManager = class {
32803
33104
  }
32804
33105
  async scanTree(rootPath, maxDepth, scanRoots) {
32805
33106
  const resolvedRoot = await realpath5(rootPath);
32806
- const rootMetadata = await stat7(resolvedRoot);
33107
+ const rootMetadata = await stat8(resolvedRoot);
32807
33108
  if (!rootMetadata.isDirectory()) throw new Error("The workspace root is not a directory");
32808
33109
  const nodes = [];
32809
33110
  let entriesRead = 0;
@@ -32837,7 +33138,7 @@ var WorkspaceManager = class {
32837
33138
  for await (const entry of entries) {
32838
33139
  if (nodes.length >= MAX_NODES || entriesRead++ >= MAX_DIRECTORY_ENTRIES) return;
32839
33140
  if (!entry.isDirectory() || IGNORED_DIRECTORIES.has(entry.name)) continue;
32840
- const target = resolve6(directory, entry.name);
33141
+ const target = resolve7(directory, entry.name);
32841
33142
  const nodeType = await appendNode(target);
32842
33143
  if (!nodeType || nodeType === "repo") continue;
32843
33144
  if (remainingDepth === void 0 || remainingDepth > 1) {
@@ -32858,7 +33159,7 @@ var WorkspaceManager = class {
32858
33159
  const target = this.resolveWithinRoot(resolvedRoot, relativePath);
32859
33160
  let metadata;
32860
33161
  try {
32861
- metadata = await stat7(target);
33162
+ metadata = await stat8(target);
32862
33163
  } catch (error62) {
32863
33164
  this.logger.warn("workspace-scan-root-missing", {
32864
33165
  rootPath: target,
@@ -32912,16 +33213,16 @@ var WorkspaceManager = class {
32912
33213
  return !value.startsWith("/") && !parts.some((part) => !part || part === "." || part === ".." || part.includes(":"));
32913
33214
  }
32914
33215
  resolveWithinRoot(rootPath, relativePath) {
32915
- const target = resolve6(rootPath, relativePath);
33216
+ const target = resolve7(rootPath, relativePath);
32916
33217
  const relativeToRoot = relative3(rootPath, target);
32917
- if (relativeToRoot.startsWith("..") || isAbsolute4(relativeToRoot)) {
33218
+ if (relativeToRoot.startsWith("..") || isAbsolute5(relativeToRoot)) {
32918
33219
  throw new Error("A workspace path must remain under the configured workspace root");
32919
33220
  }
32920
33221
  return target;
32921
33222
  }
32922
33223
  runGit(args, cwd, timeoutSeconds, allowFailure = false, environment) {
32923
33224
  return new Promise((resolveCommand, rejectCommand) => {
32924
- const child = spawn12("git", args, {
33225
+ const child = spawn13("git", args, {
32925
33226
  cwd,
32926
33227
  env: environment ?? process.env,
32927
33228
  shell: false,
@@ -32955,13 +33256,13 @@ var WorkspaceManager = class {
32955
33256
  }
32956
33257
  async createGitAuthEnvironment(auth) {
32957
33258
  if (!auth) return void 0;
32958
- const directory = await mkdtemp2(join18(tmpdir3(), "toc-ocra-git-auth-"));
33259
+ const directory = await mkdtemp2(join19(tmpdir3(), "toc-ocra-git-auth-"));
32959
33260
  const isWindows = process.platform === "win32";
32960
- const scriptPath = join18(directory, isWindows ? "askpass.cmd" : "askpass.sh");
33261
+ const scriptPath = join19(directory, isWindows ? "askpass.cmd" : "askpass.sh");
32961
33262
  let script;
32962
33263
  if (isWindows) {
32963
- const helperPath = join18(directory, "askpass.cjs");
32964
- await writeFile8(
33264
+ const helperPath = join19(directory, "askpass.cjs");
33265
+ await writeFile9(
32965
33266
  helperPath,
32966
33267
  'const prompt = process.argv.slice(2).join(" ");\nprocess.stdout.write(/username/i.test(prompt) ? process.env.ECHO_GIT_USERNAME ?? "" : process.env.ECHO_GIT_PASSWORD ?? "");\n',
32967
33268
  { mode: 448 }
@@ -32970,8 +33271,8 @@ var WorkspaceManager = class {
32970
33271
  } else {
32971
33272
  script = '#!/bin/sh\ncase "$1" in *Username*|*username*) printf "%s\\n" "$ECHO_GIT_USERNAME" ;; *) printf "%s\\n" "$ECHO_GIT_PASSWORD" ;; esac\n';
32972
33273
  }
32973
- await writeFile8(scriptPath, script, { mode: 448 });
32974
- if (!isWindows) await chmod4(scriptPath, 448);
33274
+ await writeFile9(scriptPath, script, { mode: 448 });
33275
+ if (!isWindows) await chmod5(scriptPath, 448);
32975
33276
  return {
32976
33277
  env: {
32977
33278
  ...process.env,
@@ -33092,6 +33393,14 @@ var SqlRunPayloadSchema = external_exports.object({
33092
33393
  });
33093
33394
  var CliModelsPayloadSchema = external_exports.object({ agent_type: external_exports.string().max(40).optional().default("") });
33094
33395
  var CliQuotaPayloadSchema = external_exports.object({ agent_type: external_exports.string().min(1).max(40) });
33396
+ var CliSessionArchivePayloadSchema = external_exports.object({
33397
+ agent_type: external_exports.string().min(1).max(40),
33398
+ session_id: external_exports.string().min(1).max(200),
33399
+ archived: external_exports.boolean(),
33400
+ workdir: external_exports.string().max(1e3).optional(),
33401
+ task_chain_id: external_exports.string().max(64).optional(),
33402
+ chat_session_id: external_exports.string().max(64).optional()
33403
+ });
33095
33404
  var CliProviderControlPayloadSchema = external_exports.object({
33096
33405
  app: external_exports.enum(["claude", "codex", "gemini"]),
33097
33406
  action: external_exports.enum(["state", "switch_provider", "set_mode", "select_route"]),
@@ -33119,15 +33428,15 @@ var WorkspaceSyncPayloadSchema = external_exports.object({
33119
33428
  });
33120
33429
 
33121
33430
  // src/runtime/agent-runtime.ts
33122
- var sleep3 = (ms, signal2) => new Promise((resolve9) => {
33431
+ var sleep3 = (ms, signal2) => new Promise((resolve10) => {
33123
33432
  if (signal2?.aborted) {
33124
- resolve9();
33433
+ resolve10();
33125
33434
  return;
33126
33435
  }
33127
33436
  const done = () => {
33128
33437
  clearTimeout(timer);
33129
33438
  signal2?.removeEventListener("abort", done);
33130
- resolve9();
33439
+ resolve10();
33131
33440
  };
33132
33441
  const timer = setTimeout(done, ms);
33133
33442
  signal2?.addEventListener("abort", done, { once: true });
@@ -33163,7 +33472,7 @@ var AgentRuntime = class {
33163
33472
  }
33164
33473
  };
33165
33474
  this.workspaces = new WorkspaceManager(config2, this.logger);
33166
- this.orphans = new OrphanRegistry(join19(config2.dataDir, "active-runs.json"));
33475
+ this.orphans = new OrphanRegistry(join20(config2.dataDir, "active-runs.json"));
33167
33476
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
33168
33477
  }
33169
33478
  config;
@@ -33197,6 +33506,9 @@ var AgentRuntime = class {
33197
33506
  models = new ModelCatalogCollector();
33198
33507
  catalogReport;
33199
33508
  catalogRefresh;
33509
+ /** Order of catalog reads: a read that started earlier never replaces a later one's report. */
33510
+ catalogReadSeq = 0;
33511
+ catalogReportSeq = 0;
33200
33512
  /** Hash of the catalogs the server has stored (from its heartbeat reply). */
33201
33513
  serverCatalogHash;
33202
33514
  heartbeatInFlight;
@@ -33313,9 +33625,14 @@ var AgentRuntime = class {
33313
33625
  /** Re-reads catalogs whose sources changed; concurrent calls share one run. */
33314
33626
  refreshCatalogs(options = {}) {
33315
33627
  if (this.catalogRefresh && !options.force) return this.catalogRefresh;
33628
+ const seq = ++this.catalogReadSeq;
33316
33629
  const run2 = (async () => {
33317
33630
  try {
33318
- this.catalogReport = await this.models.collect(this.detection?.detectedIds ?? [], options);
33631
+ const report = await this.models.collect(this.detection?.detectedIds ?? [], options);
33632
+ if (seq > this.catalogReportSeq) {
33633
+ this.catalogReportSeq = seq;
33634
+ this.catalogReport = report;
33635
+ }
33319
33636
  } catch (error62) {
33320
33637
  this.logger.warn("model-catalog-failed", { error: error62 instanceof Error ? error62.message : String(error62) });
33321
33638
  }
@@ -33472,6 +33789,18 @@ var AgentRuntime = class {
33472
33789
  return { success: false, error: error62 instanceof Error ? error62.message : String(error62) };
33473
33790
  }
33474
33791
  }
33792
+ case "cli.session.archive": {
33793
+ const payload = CliSessionArchivePayloadSchema.parse(command.payload);
33794
+ const key = payload.task_chain_id || payload.chat_session_id || void 0;
33795
+ const result = await this.runs.setCliSessionArchived({
33796
+ agentType: payload.agent_type,
33797
+ sessionId: payload.session_id,
33798
+ archived: payload.archived,
33799
+ ...payload.workdir ? { workdir: payload.workdir } : {},
33800
+ ...key ? { key } : {}
33801
+ });
33802
+ return { success: true, result: { archived: payload.archived, ...result } };
33803
+ }
33475
33804
  case "cli.providers": {
33476
33805
  const payload = CliProviderControlPayloadSchema.parse(command.payload);
33477
33806
  const run2 = this.providerControlTail.then(() => controlTbSwitch(payload));
@@ -33582,12 +33911,12 @@ var AgentInstanceLock = class _AgentInstanceLock {
33582
33911
  for (let attempt = 0; attempt < 2; attempt++) {
33583
33912
  const lock = new _AgentInstanceLock(version2);
33584
33913
  try {
33585
- await new Promise((resolve9, reject) => {
33914
+ await new Promise((resolve10, reject) => {
33586
33915
  const failed = (error62) => reject(error62);
33587
33916
  lock.server.once("error", failed);
33588
33917
  lock.server.listen({ host: INSTANCE_LOCK_HOST, port: INSTANCE_LOCK_PORT, exclusive: true }, () => {
33589
33918
  lock.server.removeListener("error", failed);
33590
- resolve9();
33919
+ resolve10();
33591
33920
  });
33592
33921
  });
33593
33922
  return lock;
@@ -33601,14 +33930,14 @@ var AgentInstanceLock = class _AgentInstanceLock {
33601
33930
  throw new Error("\u65E0\u6CD5\u83B7\u53D6\u672C\u673A\u8BBE\u5907\u4EE3\u7406\u5355\u5B9E\u4F8B\u9501");
33602
33931
  }
33603
33932
  release() {
33604
- return this.releasePromise ??= new Promise((resolve9) => {
33933
+ return this.releasePromise ??= new Promise((resolve10) => {
33605
33934
  for (const client of this.clients) client.destroy();
33606
- this.server.close(() => resolve9());
33935
+ this.server.close(() => resolve10());
33607
33936
  });
33608
33937
  }
33609
33938
  };
33610
33939
  async function readInstanceOwner() {
33611
- return new Promise((resolve9) => {
33940
+ return new Promise((resolve10) => {
33612
33941
  const socket = createConnection({ host: INSTANCE_LOCK_HOST, port: INSTANCE_LOCK_PORT });
33613
33942
  let data = "";
33614
33943
  const finish = () => {
@@ -33616,12 +33945,12 @@ async function readInstanceOwner() {
33616
33945
  try {
33617
33946
  const owner = JSON.parse(data);
33618
33947
  if (owner.name === "toc-ocra" && owner.protocol === 1 && typeof owner.pid === "number" && Number.isInteger(owner.pid) && owner.pid > 0 && typeof owner.version === "string") {
33619
- resolve9(owner);
33948
+ resolve10(owner);
33620
33949
  return;
33621
33950
  }
33622
33951
  } catch {
33623
33952
  }
33624
- resolve9(void 0);
33953
+ resolve10(void 0);
33625
33954
  };
33626
33955
  socket.setEncoding("utf8");
33627
33956
  socket.setTimeout(1e3, finish);
@@ -33838,9 +34167,9 @@ function errorMessage3(error62) {
33838
34167
  // src/runtime/run-service.ts
33839
34168
  var PACKAGE_NAME = "toc-ocra";
33840
34169
  function agentPackageRoot() {
33841
- let directory = dirname8(fileURLToPath2(import.meta.url));
34170
+ let directory = dirname9(fileURLToPath2(import.meta.url));
33842
34171
  while (true) {
33843
- const packagePath = resolve7(directory, "package.json");
34172
+ const packagePath = resolve8(directory, "package.json");
33844
34173
  if (existsSync6(packagePath)) {
33845
34174
  try {
33846
34175
  const info = JSON.parse(readFileSync7(packagePath, "utf8"));
@@ -33848,14 +34177,14 @@ function agentPackageRoot() {
33848
34177
  } catch {
33849
34178
  }
33850
34179
  }
33851
- const parent = dirname8(directory);
34180
+ const parent = dirname9(directory);
33852
34181
  if (parent === directory) return void 0;
33853
34182
  directory = parent;
33854
34183
  }
33855
34184
  }
33856
34185
  function agentVersion() {
33857
34186
  const root2 = agentPackageRoot();
33858
- return root2 ? JSON.parse(readFileSync7(resolve7(root2, "package.json"), "utf8")).version : "unknown";
34187
+ return root2 ? JSON.parse(readFileSync7(resolve8(root2, "package.json"), "utf8")).version : "unknown";
33859
34188
  }
33860
34189
  async function runService(options = {}) {
33861
34190
  const version2 = agentVersion();
@@ -33904,7 +34233,7 @@ async function runService(options = {}) {
33904
34233
  }
33905
34234
 
33906
34235
  // src/index.ts
33907
- var { currentInstallation, installShared, ensureIdle, compareVersions } = createRequire(import.meta.url)(join20(agentPackageRoot(), "scripts", "installation.cjs"));
34236
+ var { currentInstallation, installShared, ensureIdle, compareVersions } = createRequire(import.meta.url)(join21(agentPackageRoot(), "scripts", "installation.cjs"));
33908
34237
  async function run() {
33909
34238
  try {
33910
34239
  await runService();
@@ -33924,7 +34253,7 @@ async function smoke(args) {
33924
34253
  const arg = args[index];
33925
34254
  if (arg === "--full") full = true;
33926
34255
  else if (arg === "--json") json2 = true;
33927
- else if (arg === "--record") record8 = resolve8(args[++index] ?? "recordings");
34256
+ else if (arg === "--record") record8 = resolve9(args[++index] ?? "recordings");
33928
34257
  else if (arg === "--timeout") timeout = Number(args[++index]) || void 0;
33929
34258
  else if (arg !== "--smoke") only.push(arg);
33930
34259
  }
@@ -34017,7 +34346,7 @@ async function setup(args) {
34017
34346
  }
34018
34347
  }
34019
34348
  function manageService(action, args) {
34020
- const script = resolve8(dirname9(fileURLToPath3(import.meta.url)), "../../scripts/service.mjs");
34349
+ const script = resolve9(dirname10(fileURLToPath3(import.meta.url)), "../../scripts/service.mjs");
34021
34350
  if (!existsSync7(script)) throw new Error(`service manager is missing: ${script}`);
34022
34351
  const result = spawnSync(process.execPath, [script, action, ...args], { stdio: "inherit", shell: false });
34023
34352
  if (result.error) throw result.error;
@@ -34029,10 +34358,10 @@ function manageService(action, args) {
34029
34358
  }
34030
34359
  async function update(args) {
34031
34360
  const customConfig = option(args, "--config");
34032
- if (customConfig) process.env.TOC_OCRA_CONFIG = resolve8(customConfig);
34361
+ if (customConfig) process.env.TOC_OCRA_CONFIG = resolve9(customConfig);
34033
34362
  await ensureIdle();
34034
34363
  const npmPath = resolveCliCommand("npm");
34035
- const temporary = mkdtempSync(join20(tmpdir4(), "toc-ocra-update-"));
34364
+ const temporary = mkdtempSync(join21(tmpdir4(), "toc-ocra-update-"));
34036
34365
  try {
34037
34366
  const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
34038
34367
  if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -34059,7 +34388,7 @@ async function update(args) {
34059
34388
  }
34060
34389
  const archive = Buffer.concat(chunks);
34061
34390
  if (`sha512-${createHash5("sha512").update(archive).digest("base64")}` !== dist.integrity) throw new Error("\u8BBE\u5907\u4EE3\u7406\u5B89\u88C5\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u5347\u7EA7");
34062
- const archivePath = join20(temporary, "toc-ocra.tgz");
34391
+ const archivePath = join21(temporary, "toc-ocra.tgz");
34063
34392
  writeFileSync3(archivePath, archive, { mode: 384 });
34064
34393
  const npm = directLaunch2(npmPath, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath]);
34065
34394
  const install = spawnSync(npm.executable, npm.args, { stdio: "inherit", shell: false, windowsHide: true });
@@ -34069,7 +34398,7 @@ async function update(args) {
34069
34398
  return;
34070
34399
  }
34071
34400
  const previousVersion = agentVersion();
34072
- const current = await installShared(join20(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync7(defaultConfigPath()) });
34401
+ const current = await installShared(join21(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync7(defaultConfigPath()) });
34073
34402
  if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
34074
34403
  `);
34075
34404
  else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
@@ -34095,9 +34424,9 @@ async function main() {
34095
34424
  const shared = currentInstallation();
34096
34425
  if (root2 && root2.split(/[\\/]/).includes("node_modules") && root2 !== shared?.root) {
34097
34426
  const selected = !shared || compareVersions(agentVersion(), shared.version) > 0 ? await installShared(root2) : shared;
34098
- const same = (a, b) => process.platform === "win32" ? resolve8(a).toLowerCase() === resolve8(b).toLowerCase() : resolve8(a) === resolve8(b);
34427
+ const same = (a, b) => process.platform === "win32" ? resolve9(a).toLowerCase() === resolve9(b).toLowerCase() : resolve9(a) === resolve9(b);
34099
34428
  if (!same(selected.root, root2)) {
34100
- await import(pathToFileURL2(join20(selected.root, "dist", "cli", "cli.mjs")).href);
34429
+ await import(pathToFileURL2(join21(selected.root, "dist", "cli", "cli.mjs")).href);
34101
34430
  return;
34102
34431
  }
34103
34432
  }