toc-ocra 0.3.4 → 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 (41) hide show
  1. package/README.md +2 -0
  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/config.d.ts +2 -0
  19. package/dist/src/config.js +4 -0
  20. package/dist/src/config.js.map +1 -1
  21. package/dist/src/index.js +0 -0
  22. package/dist/src/providers/cli/codex-catalog.d.ts +26 -0
  23. package/dist/src/providers/cli/codex-catalog.js +179 -0
  24. package/dist/src/providers/cli/codex-catalog.js.map +1 -0
  25. package/dist/src/providers/cli/codex.js +4 -2
  26. package/dist/src/providers/cli/codex.js.map +1 -1
  27. package/dist/src/providers/model-catalog-collector.js +1 -1
  28. package/dist/src/providers/model-catalog-collector.js.map +1 -1
  29. package/dist/src/providers/model-catalog.d.ts +19 -4
  30. package/dist/src/providers/model-catalog.js +76 -14
  31. package/dist/src/providers/model-catalog.js.map +1 -1
  32. package/dist/src/runs/run-supervisor.d.ts +14 -0
  33. package/dist/src/runs/run-supervisor.js +31 -1
  34. package/dist/src/runs/run-supervisor.js.map +1 -1
  35. package/dist/src/runtime/agent-runtime.d.ts +3 -0
  36. package/dist/src/runtime/agent-runtime.js +20 -2
  37. package/dist/src/runtime/agent-runtime.js.map +1 -1
  38. package/dist/src/types/protocol.d.ts +23 -0
  39. package/dist/src/types/protocol.js +13 -0
  40. package/dist/src/types/protocol.js.map +1 -1
  41. package/package.json +1 -1
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
 
8
8
  // src/plugin-service.ts
9
9
  import { existsSync as existsSync7 } from "node:fs";
10
- import { delimiter as delimiter5, join as join19 } from "node:path";
10
+ import { delimiter as delimiter5, join as join20 } from "node:path";
11
11
 
12
12
  // src/config.ts
13
13
  import { randomUUID } from "node:crypto";
@@ -1243,14 +1243,14 @@ function codePointLength(str2) {
1243
1243
  const units = str2.length;
1244
1244
  if (!highSurrogate.test(str2))
1245
1245
  return units;
1246
- let count = units;
1246
+ let count2 = units;
1247
1247
  for (let i = 0; i < units - 1; i++) {
1248
1248
  if ((str2.charCodeAt(i) & 64512) === 55296 && (str2.charCodeAt(i + 1) & 64512) === 56320) {
1249
- count--;
1249
+ count2--;
1250
1250
  i++;
1251
1251
  }
1252
1252
  }
1253
- return count;
1253
+ return count2;
1254
1254
  }
1255
1255
  function getLengthableOrigin(input2) {
1256
1256
  if (Array.isArray(input2))
@@ -5083,7 +5083,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5083
5083
  var NONE = 0;
5084
5084
  var ASSUMED = 1;
5085
5085
  var PROVEN = 2;
5086
- function isRecursive(inst, stack, resolve8) {
5086
+ function isRecursive(inst, stack, resolve9) {
5087
5087
  const cached3 = recursive.get(inst);
5088
5088
  if (cached3 !== void 0)
5089
5089
  return cached3 ? PROVEN : NONE;
@@ -5093,7 +5093,7 @@ function isRecursive(inst, stack, resolve8) {
5093
5093
  let result = NONE;
5094
5094
  const check2 = (child) => {
5095
5095
  if (result !== PROVEN && child?._zod) {
5096
- const answer = isRecursive(child, stack, resolve8);
5096
+ const answer = isRecursive(child, stack, resolve9);
5097
5097
  if (answer > result)
5098
5098
  result = answer;
5099
5099
  }
@@ -5104,7 +5104,7 @@ function isRecursive(inst, stack, resolve8) {
5104
5104
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5105
5105
  if (spread && !desc.enumerable)
5106
5106
  continue;
5107
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE;
5107
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve9) : NONE;
5108
5108
  if (child > answer)
5109
5109
  answer = child;
5110
5110
  }
@@ -5168,7 +5168,7 @@ function isRecursive(inst, stack, resolve8) {
5168
5168
  break;
5169
5169
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5170
5170
  case "lazy": {
5171
- const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
5171
+ const inner = def._cachedInner ?? (resolve9 ? inst._zod.innerType : void 0);
5172
5172
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5173
5173
  break;
5174
5174
  }
@@ -5633,8 +5633,8 @@ function az_default() {
5633
5633
  }
5634
5634
 
5635
5635
  // node_modules/zod/v4/locales/be.js
5636
- function getBelarusianPlural(count, one, few, many) {
5637
- const absCount = Math.abs(count);
5636
+ function getBelarusianPlural(count2, one, few, many) {
5637
+ const absCount = Math.abs(count2);
5638
5638
  const lastDigit = absCount % 10;
5639
5639
  const lastTwoDigits = absCount % 100;
5640
5640
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -8281,8 +8281,8 @@ function hu_default() {
8281
8281
  }
8282
8282
 
8283
8283
  // node_modules/zod/v4/locales/hy.js
8284
- function getArmenianPlural(count, one, many) {
8285
- return Math.abs(count) === 1 ? one : many;
8284
+ function getArmenianPlural(count2, one, many) {
8285
+ return Math.abs(count2) === 1 ? one : many;
8286
8286
  }
8287
8287
  function withDefiniteArticle(word) {
8288
8288
  if (!word)
@@ -11020,8 +11020,8 @@ function ro_default() {
11020
11020
  }
11021
11021
 
11022
11022
  // node_modules/zod/v4/locales/ru.js
11023
- function getRussianPlural(count, one, few, many) {
11024
- const absCount = Math.abs(count);
11023
+ function getRussianPlural(count2, one, few, many) {
11024
+ const absCount = Math.abs(count2);
11025
11025
  const lastDigit = absCount % 10;
11026
11026
  const lastTwoDigits = absCount % 100;
11027
11027
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -19759,6 +19759,9 @@ function defaultDataDir() {
19759
19759
  function dataDirFromEnv() {
19760
19760
  return resolve(process.env.TOC_OCRA_DATA_DIR ?? defaultDataDir());
19761
19761
  }
19762
+ function agentDataDir() {
19763
+ return dataDirFromEnv();
19764
+ }
19762
19765
  function defaultConfigPath(dataDir2 = dataDirFromEnv()) {
19763
19766
  return resolve(process.env.TOC_OCRA_CONFIG ?? join(dataDir2, "config.json"));
19764
19767
  }
@@ -20328,7 +20331,7 @@ function createDiagnosticLogger(filePath, options = {}) {
20328
20331
  }
20329
20332
 
20330
20333
  // src/providers/detection.ts
20331
- import { spawn as spawn8 } from "node:child_process";
20334
+ import { spawn as spawn9 } from "node:child_process";
20332
20335
 
20333
20336
  // src/runtime/cli/hydrate-shell-path.ts
20334
20337
  import { delimiter as delimiter3 } from "node:path";
@@ -20367,10 +20370,10 @@ import { execFile, spawn } from "node:child_process";
20367
20370
  import { accessSync, constants, statSync as statSync2 } from "node:fs";
20368
20371
  import { delimiter as delimiter2, join as join4 } from "node:path";
20369
20372
  function readProcessTable() {
20370
- return new Promise((resolve8) => {
20373
+ return new Promise((resolve9) => {
20371
20374
  execFile("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
20372
- if (error62) return resolve8([]);
20373
- resolve8(stdout.split("\n").flatMap((line) => {
20375
+ if (error62) return resolve9([]);
20376
+ resolve9(stdout.split("\n").flatMap((line) => {
20374
20377
  const [pid, ppid] = line.trim().split(/\s+/).map(Number);
20375
20378
  return pid && ppid !== void 0 && Number.isFinite(ppid) ? [{ pid, ppid }] : [];
20376
20379
  }));
@@ -20405,7 +20408,7 @@ function alive(pid) {
20405
20408
  return false;
20406
20409
  }
20407
20410
  }
20408
- var sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
20411
+ var sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
20409
20412
  async function killPosixTree(rootPid, graceMs) {
20410
20413
  const descendants = await listDescendants(rootPid);
20411
20414
  signal(-rootPid, "SIGTERM");
@@ -20440,7 +20443,7 @@ function parseCapturedProxy(stdout) {
20440
20443
  return Object.fromEntries(PROXY_KEYS.flatMap((key, index) => values[index] ? [[key, values[index]]] : []));
20441
20444
  }
20442
20445
  function readLoginShell(shell) {
20443
- return new Promise((resolve8) => {
20446
+ return new Promise((resolve9) => {
20444
20447
  const proxyValues = PROXY_KEYS.map((key) => `"\${${key}-}"`).join(" ");
20445
20448
  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}'`;
20446
20449
  let finished = false;
@@ -20461,7 +20464,7 @@ function readLoginShell(shell) {
20461
20464
  child.stdout.removeAllListeners("data");
20462
20465
  child.removeAllListeners("error");
20463
20466
  child.removeAllListeners("close");
20464
- resolve8(result);
20467
+ resolve9(result);
20465
20468
  };
20466
20469
  timer = setTimeout(() => {
20467
20470
  try {
@@ -20517,9 +20520,9 @@ function createPosixPlatform(id) {
20517
20520
  child.kill("SIGTERM");
20518
20521
  },
20519
20522
  processCommandLine(pid) {
20520
- return new Promise((resolve8) => {
20523
+ return new Promise((resolve9) => {
20521
20524
  execFile("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
20522
- resolve8(error62 ? void 0 : stdout.trim() || void 0);
20525
+ resolve9(error62 ? void 0 : stdout.trim() || void 0);
20523
20526
  });
20524
20527
  });
20525
20528
  },
@@ -20562,23 +20565,23 @@ function resolveWindowsCommandShim(shimPath) {
20562
20565
  return void 0;
20563
20566
  }
20564
20567
  function taskkillTree(rootPid) {
20565
- return new Promise((resolve8) => {
20568
+ return new Promise((resolve9) => {
20566
20569
  const child = spawn2(join5(SYSTEM_ROOT, "System32", "taskkill.exe"), ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
20567
- child.once("error", () => resolve8());
20568
- child.once("close", () => resolve8());
20570
+ child.once("error", () => resolve9());
20571
+ child.once("close", () => resolve9());
20569
20572
  });
20570
20573
  }
20571
20574
  function runPowerShell(script) {
20572
20575
  const prelude = '$ProgressPreference="SilentlyContinue";[Console]::OutputEncoding=[Text.Encoding]::UTF8;';
20573
20576
  const encoded = Buffer.from(prelude + script, "utf16le").toString("base64");
20574
- return new Promise((resolve8) => {
20577
+ return new Promise((resolve9) => {
20575
20578
  execFile2(
20576
20579
  POWERSHELL,
20577
20580
  ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
20578
20581
  { timeout: HELPER_TIMEOUT_MS, windowsHide: true, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 },
20579
20582
  (error62, stdout) => {
20580
- if (!error62) return resolve8({ ok: true, stdout });
20581
- resolve8({ ok: false, reason: error62.killed ? "timeout" : "spawn_error" });
20583
+ if (!error62) return resolve9({ ok: true, stdout });
20584
+ resolve9({ ok: false, reason: error62.killed ? "timeout" : "spawn_error" });
20582
20585
  }
20583
20586
  );
20584
20587
  });
@@ -20708,7 +20711,7 @@ function mergePathSegments(segments) {
20708
20711
 
20709
20712
  // src/acp/chat-agents.ts
20710
20713
  import { realpathSync as realpathSync2 } from "node:fs";
20711
- import { join as join9 } from "node:path";
20714
+ import { join as join10 } from "node:path";
20712
20715
 
20713
20716
  // src/providers/cli-specs.ts
20714
20717
  var SOURCES = [
@@ -20904,7 +20907,7 @@ var KiroSessionLog = class {
20904
20907
  return step;
20905
20908
  }
20906
20909
  if (Date.now() >= deadline) return void 0;
20907
- await new Promise((resolve8) => setTimeout(resolve8, 150));
20910
+ await new Promise((resolve9) => setTimeout(resolve9, 150));
20908
20911
  }
20909
20912
  }
20910
20913
  /** The first of `ids` whose result is in the log, waiting up to `waitMs`. */
@@ -20914,7 +20917,7 @@ var KiroSessionLog = class {
20914
20917
  await this.refresh();
20915
20918
  const id = ids.find((item) => this.results.has(item));
20916
20919
  if (id || Date.now() >= deadline) return id;
20917
- await new Promise((resolve8) => setTimeout(resolve8, 150));
20920
+ await new Promise((resolve9) => setTimeout(resolve9, 150));
20918
20921
  }
20919
20922
  }
20920
20923
  async result(id, waitMs = 3e3) {
@@ -20923,7 +20926,7 @@ var KiroSessionLog = class {
20923
20926
  await this.refresh();
20924
20927
  const result = this.results.get(id);
20925
20928
  if (result || Date.now() >= deadline) return result;
20926
- await new Promise((resolve8) => setTimeout(resolve8, 200));
20929
+ await new Promise((resolve9) => setTimeout(resolve9, 200));
20927
20930
  }
20928
20931
  }
20929
20932
  };
@@ -21166,7 +21169,7 @@ async function listKiroSessions(workdir, options = {}) {
21166
21169
  const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
21167
21170
  let lastError;
21168
21171
  for (let attempt = 0; attempt < 2; attempt++) {
21169
- if (attempt) await new Promise((resolve8) => setTimeout(resolve8, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
21172
+ if (attempt) await new Promise((resolve9) => setTimeout(resolve9, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
21170
21173
  try {
21171
21174
  const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
21172
21175
  return parseKiroSessions(stdout);
@@ -21381,7 +21384,7 @@ var AgentProcess = class _AgentProcess {
21381
21384
  constructor(child, onLine, onStderr) {
21382
21385
  this.child = child;
21383
21386
  let spawnError = "";
21384
- this.exited = new Promise((resolve8) => {
21387
+ this.exited = new Promise((resolve9) => {
21385
21388
  child.once("error", (error62) => {
21386
21389
  spawnError = error62.message;
21387
21390
  });
@@ -21390,7 +21393,7 @@ var AgentProcess = class _AgentProcess {
21390
21393
  if (settled) return;
21391
21394
  settled = true;
21392
21395
  this.exit = { code, signal: signal2, ...spawnError ? { error: spawnError } : {} };
21393
- resolve8(this.exit);
21396
+ resolve9(this.exit);
21394
21397
  };
21395
21398
  child.once("exit", (code, signal2) => {
21396
21399
  setTimeout(() => {
@@ -21449,7 +21452,7 @@ var AgentProcess = class _AgentProcess {
21449
21452
  this.child.stdin?.end();
21450
21453
  if (this.pid > 1) await killProcessTree(this.pid, graceMs);
21451
21454
  else this.child.kill("SIGKILL");
21452
- await Promise.race([this.exited, new Promise((resolve8) => setTimeout(resolve8, 5e3).unref())]);
21455
+ await Promise.race([this.exited, new Promise((resolve9) => setTimeout(resolve9, 5e3).unref())]);
21453
21456
  }
21454
21457
  };
21455
21458
 
@@ -21485,8 +21488,8 @@ var JsonRpcPeer = class {
21485
21488
  request(method, params) {
21486
21489
  if (this.closedWith) return Promise.reject(this.closedWith);
21487
21490
  const id = ++this.nextId;
21488
- return new Promise((resolve8, reject) => {
21489
- this.pending.set(id, { resolve: resolve8, reject });
21491
+ return new Promise((resolve9, reject) => {
21492
+ this.pending.set(id, { resolve: resolve9, reject });
21490
21493
  try {
21491
21494
  this.send({ id, method, params });
21492
21495
  } catch (error62) {
@@ -21580,6 +21583,7 @@ function rpcErrorText(error62) {
21580
21583
  var PROTOCOL_VERSION = 1;
21581
21584
  var INITIALIZE_TIMEOUT_MS = 12e4;
21582
21585
  var SESSION_OPEN_TIMEOUT_MS = 18e4;
21586
+ var EXT_REQUEST_TIMEOUT_MS = 6e4;
21583
21587
  var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21584
21588
  var text = (value) => typeof value === "string" && value ? value : void 0;
21585
21589
  var AcpConnection = class _AcpConnection {
@@ -21677,6 +21681,10 @@ var AcpConnection = class _AcpConnection {
21677
21681
  const result = record2(await this.peer.request("_lody/session/steer", { sessionId, prompt, steerId }));
21678
21682
  return result.outcome === "injected" ? "injected" : "failed";
21679
21683
  }
21684
+ /** An adapter extension request (`_session/archive`, `_session/unarchive`, …) with a time limit. */
21685
+ extRequest(method, params, timeoutMs = EXT_REQUEST_TIMEOUT_MS) {
21686
+ return this.call(method, params, timeoutMs);
21687
+ }
21680
21688
  async dispose() {
21681
21689
  this.peer.close(new Error("ACP \u8FDE\u63A5\u5DF2\u5173\u95ED"));
21682
21690
  await this.process.terminate();
@@ -21718,16 +21726,16 @@ var AcpConnection = class _AcpConnection {
21718
21726
  };
21719
21727
  function sessionState(sessionId, result) {
21720
21728
  const modes = record2(result.modes);
21721
- const models = record2(result.models);
21729
+ const models2 = record2(result.models);
21722
21730
  const ids = (list, key) => Array.isArray(list) ? list.map((item) => text(record2(item)[key])).filter((id) => !!id) : [];
21723
21731
  const currentModeId = text(modes.currentModeId);
21724
- const currentModelId = text(models.currentModelId);
21732
+ const currentModelId = text(models2.currentModelId);
21725
21733
  return {
21726
21734
  sessionId,
21727
21735
  ...currentModeId ? { currentModeId } : {},
21728
21736
  modeIds: ids(modes.availableModes, "id"),
21729
21737
  ...currentModelId ? { currentModelId } : {},
21730
- modelIds: ids(models.availableModels, "modelId"),
21738
+ modelIds: ids(models2.availableModels, "modelId"),
21731
21739
  configOptions: Array.isArray(result.configOptions) ? configOptions(result.configOptions) : []
21732
21740
  };
21733
21741
  }
@@ -22365,12 +22373,152 @@ var GEMINI_ACP = {
22365
22373
  var kiroAcpProvider = acpProvider(KIRO_ACP);
22366
22374
  var geminiAcpProvider = acpProvider(GEMINI_ACP);
22367
22375
 
22368
- // src/acp/vendor.ts
22376
+ // src/providers/cli/codex-catalog.ts
22369
22377
  import { spawn as spawn4 } from "node:child_process";
22378
+ import { statSync as statSync4 } from "node:fs";
22379
+ import { chmod as chmod3, mkdir as mkdir3, readFile as readFile4, rename as rename3, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
22380
+ import { homedir as homedir5 } from "node:os";
22381
+ import { dirname as dirname5, isAbsolute, join as join8, resolve as resolve2 } from "node:path";
22382
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join8(homedir5(), ".codex");
22383
+ var BUNDLED_TIMEOUT_MS = 1e4;
22384
+ function configuredCatalogPath(config2, home = codexHome()) {
22385
+ const value = config2.match(/^\s*model_catalog_json\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m)?.[1]?.trim();
22386
+ if (!value) return void 0;
22387
+ return isAbsolute(value) ? value : resolve2(home, value);
22388
+ }
22389
+ var nonEmpty = (value) => Array.isArray(value) && value.length > 0;
22390
+ function models(catalog) {
22391
+ const list = catalog && typeof catalog === "object" ? catalog.models : void 0;
22392
+ return Array.isArray(list) ? list.filter((entry) => Boolean(entry) && typeof entry === "object") : void 0;
22393
+ }
22394
+ function withBundledSpeedTiers(catalog, bundled) {
22395
+ const listed = models(catalog);
22396
+ if (!listed?.length) return void 0;
22397
+ const known = new Map((models(bundled) ?? []).flatMap((entry) => typeof entry.slug === "string" ? [[entry.slug, entry]] : []));
22398
+ let changed = false;
22399
+ const filled = listed.map((entry) => {
22400
+ const source = typeof entry.slug === "string" ? known.get(entry.slug) : void 0;
22401
+ if (!source) return entry;
22402
+ const next = { ...entry };
22403
+ for (const key of ["service_tiers", "additional_speed_tiers"]) {
22404
+ if (!nonEmpty(entry[key]) && nonEmpty(source[key])) {
22405
+ next[key] = source[key];
22406
+ changed = true;
22407
+ }
22408
+ }
22409
+ return next;
22410
+ });
22411
+ return changed ? { ...catalog, models: filled } : void 0;
22412
+ }
22413
+ var bundledCache;
22414
+ function runBundled() {
22415
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: ["debug", "models", "--bundled"] });
22416
+ return new Promise((resolveOutput, reject) => {
22417
+ const child = spawn4(launch.executable, launch.args, { env: launch.env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
22418
+ let stdout = "";
22419
+ const timer = setTimeout(() => {
22420
+ child.kill("SIGKILL");
22421
+ reject(new Error("codex debug models timed out"));
22422
+ }, BUNDLED_TIMEOUT_MS);
22423
+ child.stdout.setEncoding("utf8");
22424
+ child.stdout.on("data", (chunk) => {
22425
+ stdout += chunk;
22426
+ });
22427
+ child.once("error", (error62) => {
22428
+ clearTimeout(timer);
22429
+ reject(error62);
22430
+ });
22431
+ child.once("close", (code) => {
22432
+ clearTimeout(timer);
22433
+ if (code === 0) resolveOutput(stdout);
22434
+ else reject(new Error(`codex debug models exited with code ${code ?? "unknown"}`));
22435
+ });
22436
+ });
22437
+ }
22438
+ async function codexBundledCatalog() {
22439
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: [] });
22440
+ const binary = launch.args[0] ?? launch.executable;
22441
+ const info = await stat2(binary).catch(() => void 0);
22442
+ const stamp = `${binary}:${info?.mtimeMs ?? "-"}:${info?.size ?? "-"}`;
22443
+ if (bundledCache?.stamp === stamp) return bundledCache.catalog;
22444
+ const catalog = JSON.parse(await runBundled());
22445
+ bundledCache = { stamp, catalog };
22446
+ return catalog;
22447
+ }
22448
+ var overlay;
22449
+ var refreshing;
22450
+ function fileStamp(path) {
22451
+ try {
22452
+ const info = statSync4(path);
22453
+ return `${info.mtimeMs}:${info.size}`;
22454
+ } catch {
22455
+ return "-";
22456
+ }
22457
+ }
22458
+ var stampOf = (configPath, sourcePath) => `${fileStamp(configPath)}|${fileStamp(sourcePath)}`;
22459
+ function overlayPath() {
22460
+ return join8(agentDataDir(), "codex", "model-catalog.json");
22461
+ }
22462
+ async function rebuild() {
22463
+ const home = codexHome();
22464
+ const configPath = join8(home, "config.toml");
22465
+ const config2 = await readFile4(configPath, "utf8").catch(() => "");
22466
+ const sourcePath = configuredCatalogPath(config2, home);
22467
+ if (!sourcePath) {
22468
+ overlay = void 0;
22469
+ return;
22470
+ }
22471
+ const stamp = stampOf(configPath, sourcePath);
22472
+ if (overlay && overlay.sourcePath === sourcePath && overlay.stamp === stamp) return;
22473
+ let source;
22474
+ try {
22475
+ source = JSON.parse(await readFile4(sourcePath, "utf8"));
22476
+ } catch {
22477
+ overlay = void 0;
22478
+ return;
22479
+ }
22480
+ if (models(source)?.every((entry) => nonEmpty(entry.service_tiers) && nonEmpty(entry.additional_speed_tiers))) {
22481
+ overlay = void 0;
22482
+ return;
22483
+ }
22484
+ const filled = withBundledSpeedTiers(source, await codexBundledCatalog());
22485
+ if (!filled) {
22486
+ overlay = void 0;
22487
+ return;
22488
+ }
22489
+ const path = overlayPath();
22490
+ await mkdir3(dirname5(path), { recursive: true, mode: 448 });
22491
+ const temporary = `${path}.${process.pid}.tmp`;
22492
+ await writeFile3(temporary, JSON.stringify(filled), { mode: 384 });
22493
+ await rename3(temporary, path);
22494
+ await chmod3(path, 384);
22495
+ overlay = { path, configPath, sourcePath, stamp };
22496
+ }
22497
+ async function prepareCodexCatalog() {
22498
+ refreshing ??= rebuild().catch(() => {
22499
+ overlay = void 0;
22500
+ }).finally(() => {
22501
+ refreshing = void 0;
22502
+ });
22503
+ await refreshing;
22504
+ }
22505
+ function codexCatalogOverlay() {
22506
+ if (!overlay) return void 0;
22507
+ if (stampOf(overlay.configPath, overlay.sourcePath) === overlay.stamp) return { path: overlay.path, stamp: overlay.stamp };
22508
+ void prepareCodexCatalog();
22509
+ return void 0;
22510
+ }
22511
+ function codexCatalogArgs() {
22512
+ const copy = codexCatalogOverlay();
22513
+ return copy ? ["-c", `model_catalog_json=${JSON.stringify(copy.path)}`] : [];
22514
+ }
22515
+
22516
+ // src/acp/vendor.ts
22517
+ import { spawn as spawn5 } from "node:child_process";
22370
22518
  import { createHash } from "node:crypto";
22371
22519
  import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
22372
- import { copyFile, mkdir as mkdir3, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
22373
- import { dirname as dirname5, join as join8, resolve as resolve2 } from "node:path";
22520
+ import { copyFile, mkdir as mkdir4, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22521
+ import { dirname as dirname6, join as join9, resolve as resolve3 } from "node:path";
22374
22522
  import { fileURLToPath } from "node:url";
22375
22523
  var AcpRuntimeUnavailable = class extends Error {
22376
22524
  constructor(message) {
@@ -22380,16 +22528,16 @@ var AcpRuntimeUnavailable = class extends Error {
22380
22528
  };
22381
22529
  var NPM_INSTALL_TIMEOUT_MS = 10 * 6e4;
22382
22530
  function packageRoot() {
22383
- let directory = dirname5(fileURLToPath(import.meta.url));
22531
+ let directory = dirname6(fileURLToPath(import.meta.url));
22384
22532
  while (true) {
22385
- const path = resolve2(directory, "package.json");
22533
+ const path = resolve3(directory, "package.json");
22386
22534
  if (existsSync5(path)) {
22387
22535
  try {
22388
22536
  if (JSON.parse(readFileSync5(path, "utf8")).name === "toc-ocra") return directory;
22389
22537
  } catch {
22390
22538
  }
22391
22539
  }
22392
- const parent = dirname5(directory);
22540
+ const parent = dirname6(directory);
22393
22541
  if (parent === directory) return void 0;
22394
22542
  directory = parent;
22395
22543
  }
@@ -22403,21 +22551,21 @@ function agentPackageVersion() {
22403
22551
  const directory = agentRoot();
22404
22552
  if (!directory) return "0";
22405
22553
  try {
22406
- return JSON.parse(readFileSync5(join8(directory, "package.json"), "utf8")).version ?? "0";
22554
+ return JSON.parse(readFileSync5(join9(directory, "package.json"), "utf8")).version ?? "0";
22407
22555
  } catch {
22408
22556
  return "0";
22409
22557
  }
22410
22558
  }
22411
22559
  function vendoredAdapter(name) {
22412
22560
  const directory = agentRoot();
22413
- const entry = directory ? join8(directory, "assets", "acp", name, "index.mjs") : void 0;
22561
+ const entry = directory ? join9(directory, "assets", "acp", name, "index.mjs") : void 0;
22414
22562
  return entry && existsSync5(entry) ? entry : void 0;
22415
22563
  }
22416
22564
  var installs = /* @__PURE__ */ new Map();
22417
22565
  function ensureClaudeRuntime(dataDir2) {
22418
22566
  const entry = vendoredAdapter("claude");
22419
22567
  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"));
22420
- const manifestPath = join8(dirname5(entry), "runtime.json");
22568
+ const manifestPath = join9(dirname6(entry), "runtime.json");
22421
22569
  let manifest;
22422
22570
  try {
22423
22571
  manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
@@ -22425,7 +22573,7 @@ function ensureClaudeRuntime(dataDir2) {
22425
22573
  return Promise.reject(new AcpRuntimeUnavailable("Claude ACP \u9002\u914D\u5668\u7F3A\u5C11 runtime.json"));
22426
22574
  }
22427
22575
  const hash2 = createHash("sha256").update(readFileSync5(entry)).digest("hex").slice(0, 12);
22428
- const directory = join8(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
22576
+ const directory = join9(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
22429
22577
  const existing = installs.get(directory);
22430
22578
  if (existing) return existing;
22431
22579
  const install = installClaudeRuntime(directory, entry, manifest).catch((error62) => {
@@ -22436,21 +22584,21 @@ function ensureClaudeRuntime(dataDir2) {
22436
22584
  return install;
22437
22585
  }
22438
22586
  async function installClaudeRuntime(directory, entry, manifest) {
22439
- const sdkPackage = join8(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
22440
- if (existsSync5(sdkPackage) && existsSync5(join8(directory, "index.mjs"))) return directory;
22587
+ const sdkPackage = join9(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
22588
+ if (existsSync5(sdkPackage) && existsSync5(join9(directory, "index.mjs"))) return directory;
22441
22589
  const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`;
22442
- await mkdir3(temporary, { recursive: true, mode: 448 });
22590
+ await mkdir4(temporary, { recursive: true, mode: 448 });
22443
22591
  try {
22444
- await writeFile3(join8(temporary, "package.json"), JSON.stringify({
22592
+ await writeFile4(join9(temporary, "package.json"), JSON.stringify({
22445
22593
  name: "toc-ocra-claude-acp-runtime",
22446
22594
  private: true,
22447
22595
  type: "module",
22448
22596
  dependencies: { [manifest.sdk.name]: manifest.sdk.version }
22449
22597
  }, null, 2));
22450
22598
  await runNpm(["install", "--omit=optional", "--no-audit", "--no-fund", "--no-package-lock", "--loglevel=error"], temporary);
22451
- await copyFile(entry, join8(temporary, "index.mjs"));
22599
+ await copyFile(entry, join9(temporary, "index.mjs"));
22452
22600
  await rm2(directory, { recursive: true, force: true });
22453
- await rename3(temporary, directory);
22601
+ await rename4(temporary, directory);
22454
22602
  } catch (error62) {
22455
22603
  await rm2(temporary, { recursive: true, force: true }).catch(() => void 0);
22456
22604
  throw error62;
@@ -22461,7 +22609,7 @@ function runNpm(args, cwd) {
22461
22609
  const env = providerEnvironment();
22462
22610
  const launch = resolveExecutable("npm", args, env, process.env.TOC_OCRA_NPM_PATH);
22463
22611
  return new Promise((resolvePromise, reject) => {
22464
- const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] });
22612
+ const child = spawn5(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] });
22465
22613
  const stderr = [];
22466
22614
  child.stderr.setEncoding("utf8").on("data", (chunk) => {
22467
22615
  stderr.push(chunk);
@@ -22545,7 +22693,7 @@ var CLAUDE_CHAT = {
22545
22693
  return {
22546
22694
  launch: {
22547
22695
  executable: process.execPath,
22548
- args: [join9(runtime, "index.mjs")],
22696
+ args: [join10(runtime, "index.mjs")],
22549
22697
  env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable },
22550
22698
  cwd: workdir
22551
22699
  },
@@ -22563,14 +22711,20 @@ var CODEX_CHAT = {
22563
22711
  const entry = vendoredAdapter("codex");
22564
22712
  if (!entry) throw new AcpRuntimeUnavailable("\u8FD9\u4E2A\u7248\u672C\u7684\u8BBE\u5907\u4EE3\u7406\u6CA1\u6709\u9644\u5E26 Codex ACP \u9002\u914D\u5668");
22565
22713
  const executable = installedCli(CODEX);
22714
+ await prepareCodexCatalog();
22715
+ const catalog = codexCatalogOverlay();
22566
22716
  return {
22567
22717
  launch: {
22568
22718
  executable: process.execPath,
22569
22719
  args: [entry, "-c", "shell_environment_policy.ignore_default_excludes=true"],
22570
- env: { ...providerEnvironment(), CODEX_PATH: executable },
22720
+ env: {
22721
+ ...providerEnvironment(),
22722
+ CODEX_PATH: executable,
22723
+ ...catalog ? { LODY_CODEX_PROFILE_CONFIG: JSON.stringify({ model_catalog_json: catalog.path }) } : {}
22724
+ },
22571
22725
  cwd: workdir
22572
22726
  },
22573
- fingerprint: `codex:${entry}:${executable}`
22727
+ fingerprint: `codex:${entry}:${executable}${catalog ? `:${catalog.path}@${catalog.stamp}` : ""}`
22574
22728
  };
22575
22729
  },
22576
22730
  // Codex's presets: read-only sandbox, workspace write, full access. `read-only`
@@ -22694,7 +22848,7 @@ function codexTurnSandboxPolicy(request) {
22694
22848
  return { type: "readOnly", access: { type: "restricted", includePlatformDefaults: true, readableRoots: [request.workdir] } };
22695
22849
  }
22696
22850
  function codexAppServerArgs(request) {
22697
- return ["app-server", "--listen", "stdio://", ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"'], ...codexFastArgs(request)];
22851
+ return ["app-server", "--listen", "stdio://", ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"'], ...codexCatalogArgs(), ...codexFastArgs(request)];
22698
22852
  }
22699
22853
  var codexProvider = {
22700
22854
  id: "codex",
@@ -22707,7 +22861,7 @@ var codexProvider = {
22707
22861
  else if (level === "acceptEdits") args.push("--sandbox", "workspace-write", "-c", 'approval_policy="never"');
22708
22862
  else if (level === "read-only") args.push("--sandbox", "read-only", "-c", 'approval_policy="never"');
22709
22863
  else args.push("--sandbox", "read-only", "-c", 'approval_policy="never"', "-c", "mcp_servers={}", "-c", 'web_search="disabled"');
22710
- args.push(...codexFastArgs(request));
22864
+ args.push(...codexCatalogArgs(), ...codexFastArgs(request));
22711
22865
  if (request.model) args.push("--model", request.model);
22712
22866
  if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
22713
22867
  if (request.sessionId) args.push("resume", request.sessionId);
@@ -22931,13 +23085,13 @@ function isWriterConflict(message) {
22931
23085
 
22932
23086
  // src/providers/cli/claude.ts
22933
23087
  import { readdirSync as readdirSync2, readFileSync as readFileSync6 } from "node:fs";
22934
- import { homedir as homedir5 } from "node:os";
22935
- import { join as join10 } from "node:path";
23088
+ import { homedir as homedir6 } from "node:os";
23089
+ import { join as join11 } from "node:path";
22936
23090
  var CLAUDE2 = requireCliSpec("claude");
22937
23091
  function claudeProjectRoots() {
22938
23092
  const configured = process.env.CLAUDE_CONFIG_DIR;
22939
- const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join10(homedir5(), ".claude")];
22940
- return dirs.map((dir) => join10(dir, "projects"));
23093
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join11(homedir6(), ".claude")];
23094
+ return dirs.map((dir) => join11(dir, "projects"));
22941
23095
  }
22942
23096
  function claudeTranscriptExists(sessionId) {
22943
23097
  return claudeTranscriptPath(sessionId) !== void 0;
@@ -22953,7 +23107,7 @@ function claudeTranscriptPath(sessionId) {
22953
23107
  }
22954
23108
  for (const project of projects) {
22955
23109
  try {
22956
- if (readdirSync2(join10(root2, project)).includes(file2)) return join10(root2, project, file2);
23110
+ if (readdirSync2(join11(root2, project)).includes(file2)) return join11(root2, project, file2);
22957
23111
  } catch {
22958
23112
  }
22959
23113
  }
@@ -22997,7 +23151,7 @@ var claudeProvider = {
22997
23151
  settings.disableAllHooks = true;
22998
23152
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*");
22999
23153
  try {
23000
- const userSettings = JSON.parse(readFileSync6(join10(homedir5(), ".claude", "settings.json"), "utf8"));
23154
+ const userSettings = JSON.parse(readFileSync6(join11(homedir6(), ".claude", "settings.json"), "utf8"));
23001
23155
  for (const [key, value] of Object.entries(userSettings.env ?? {})) {
23002
23156
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
23003
23157
  }
@@ -23456,11 +23610,11 @@ var opencodeProvider = {
23456
23610
  };
23457
23611
 
23458
23612
  // src/providers/codex-quota.ts
23459
- import { spawn as spawn5 } from "node:child_process";
23613
+ import { spawn as spawn6 } from "node:child_process";
23460
23614
  import { createInterface as createInterface2 } from "node:readline";
23461
23615
  async function readCodexQuotaWindows() {
23462
23616
  const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--stdio"] });
23463
- const child = spawn5(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
23617
+ const child = spawn6(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
23464
23618
  let nextId = 0;
23465
23619
  const pending = /* @__PURE__ */ new Map();
23466
23620
  const lines = createInterface2({ input: child.stdout });
@@ -23488,7 +23642,7 @@ async function readCodexQuotaWindows() {
23488
23642
  });
23489
23643
  const request = (method, params) => {
23490
23644
  const id = ++nextId;
23491
- return new Promise((resolve8, reject) => {
23645
+ return new Promise((resolve9, reject) => {
23492
23646
  const timer = setTimeout(() => {
23493
23647
  pending.delete(id);
23494
23648
  reject(new Error(`Codex \u989D\u5EA6\u8BFB\u53D6\u8D85\u65F6\uFF08${method}\uFF09`));
@@ -23496,7 +23650,7 @@ async function readCodexQuotaWindows() {
23496
23650
  pending.set(id, {
23497
23651
  resolve: (value) => {
23498
23652
  clearTimeout(timer);
23499
- resolve8(value);
23653
+ resolve9(value);
23500
23654
  },
23501
23655
  reject: (error62) => {
23502
23656
  clearTimeout(timer);
@@ -23625,16 +23779,16 @@ ${stderr}`);
23625
23779
  }
23626
23780
 
23627
23781
  // src/providers/model-catalog.ts
23628
- import { spawn as spawn7 } from "node:child_process";
23629
- import { readFile as readFile4 } from "node:fs/promises";
23630
- import { homedir as homedir6 } from "node:os";
23631
- import { isAbsolute, join as join11, resolve as resolve3 } from "node:path";
23782
+ import { spawn as spawn8 } from "node:child_process";
23783
+ import { readFile as readFile5 } from "node:fs/promises";
23784
+ import { homedir as homedir7 } from "node:os";
23785
+ import { isAbsolute as isAbsolute2, join as join12, resolve as resolve4 } from "node:path";
23632
23786
 
23633
23787
  // src/providers/kiro-models.ts
23634
- import { spawn as spawn6 } from "node:child_process";
23788
+ import { spawn as spawn7 } from "node:child_process";
23635
23789
  import { createInterface as createInterface3 } from "node:readline";
23636
23790
  async function readKiroNativeModels(launch, cwd, options = {}) {
23637
- const child = spawn6(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
23791
+ const child = spawn7(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
23638
23792
  const lines = createInterface3({ input: child.stdout });
23639
23793
  let nextId = 0;
23640
23794
  let failure2;
@@ -23670,13 +23824,13 @@ async function readKiroNativeModels(launch, cwd, options = {}) {
23670
23824
  if (message.error) request2.reject(new Error(`Kiro \u6A21\u578B\u67E5\u8BE2\u5931\u8D25\uFF1A${message.error.message || "ACP \u8BF7\u6C42\u5931\u8D25"}`));
23671
23825
  else request2.resolve(message.result);
23672
23826
  });
23673
- const request = (method, params) => new Promise((resolve8, reject) => {
23827
+ const request = (method, params) => new Promise((resolve9, reject) => {
23674
23828
  if (failure2) {
23675
23829
  reject(failure2);
23676
23830
  return;
23677
23831
  }
23678
23832
  const id = ++nextId;
23679
- pending.set(id, { resolve: (value) => resolve8(value), reject });
23833
+ pending.set(id, { resolve: (value) => resolve9(value), reject });
23680
23834
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
23681
23835
  });
23682
23836
  try {
@@ -23726,15 +23880,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
23726
23880
  const source = settings && typeof settings === "object" ? settings : {};
23727
23881
  const configuredEnv = source.env && typeof source.env === "object" ? source.env : {};
23728
23882
  const mergedEnv = { ...configuredEnv, ...environment };
23729
- const models = /* @__PURE__ */ new Map();
23883
+ const models2 = /* @__PURE__ */ new Map();
23730
23884
  for (const [key, rawModel] of Object.entries(mergedEnv)) {
23731
23885
  const match = key.match(/^ANTHROPIC_DEFAULT_([A-Z0-9_]+)_MODEL$/);
23732
23886
  const id = stringValue(rawModel);
23733
23887
  if (!match || !id) continue;
23734
23888
  const configuredName = stringValue(mergedEnv[`${key}_NAME`]);
23735
- const existing = models.get(id);
23889
+ const existing = models2.get(id);
23736
23890
  if (!existing) {
23737
- models.set(id, {
23891
+ models2.set(id, {
23738
23892
  id,
23739
23893
  name: configuredName ?? id,
23740
23894
  supported_reasoning_efforts: [...CLAUDE_REASONING_EFFORTS]
@@ -23744,21 +23898,21 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
23744
23898
  const catalog = {
23745
23899
  agent_type: "claude",
23746
23900
  fetched_at: fetchedAt,
23747
- models: [...models.values()]
23901
+ models: [...models2.values()]
23748
23902
  };
23749
23903
  const defaultModel = stringValue(mergedEnv.ANTHROPIC_MODEL);
23750
23904
  if (defaultModel) catalog.default_model = defaultModel;
23751
23905
  return catalog;
23752
23906
  }
23753
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join11(homedir6(), ".claude");
23754
- var codexHome = () => process.env.CODEX_HOME?.trim() || join11(homedir6(), ".codex");
23755
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join11(homedir6(), ".gemini");
23756
- var grokHome = () => process.env.GROK_HOME?.trim() || join11(homedir6(), ".grok");
23757
- var opencodeHome = () => join11(process.env.XDG_CONFIG_HOME?.trim() || join11(homedir6(), ".config"), "opencode");
23758
- var kiroHome = () => join11(homedir6(), ".kiro");
23907
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join12(homedir7(), ".claude");
23908
+ var codexHome2 = () => process.env.CODEX_HOME?.trim() || join12(homedir7(), ".codex");
23909
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join12(homedir7(), ".gemini");
23910
+ var grokHome = () => process.env.GROK_HOME?.trim() || join12(homedir7(), ".grok");
23911
+ var opencodeHome = () => join12(process.env.XDG_CONFIG_HOME?.trim() || join12(homedir7(), ".config"), "opencode");
23912
+ var kiroHome = () => join12(homedir7(), ".kiro");
23759
23913
  async function readClaudeModelCatalog() {
23760
23914
  const home = claudeHome();
23761
- const content = await readFile4(join11(home, "settings.json"), "utf8").catch(() => "");
23915
+ const content = await readFile5(join12(home, "settings.json"), "utf8").catch(() => "");
23762
23916
  let settings = {};
23763
23917
  if (content) {
23764
23918
  try {
@@ -23795,42 +23949,45 @@ function toModel(entry) {
23795
23949
  if (defaultReasoning) model.default_reasoning_effort = defaultReasoning;
23796
23950
  return model;
23797
23951
  }
23952
+ function codexModelsFrom(parsed, options = {}) {
23953
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.models)) {
23954
+ return void 0;
23955
+ }
23956
+ return parsed.models.flatMap((entry) => {
23957
+ if (options.listedOnly && entry.visibility === "hide") return [];
23958
+ const model = toModel(entry);
23959
+ return model ? [model] : [];
23960
+ });
23961
+ }
23798
23962
  function parseCodexModels(content) {
23799
23963
  if (!content) return void 0;
23800
23964
  try {
23801
- const parsed = JSON.parse(content);
23802
- if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.models)) {
23803
- return void 0;
23804
- }
23805
- return parsed.models.flatMap((entry) => {
23806
- const model = toModel(entry);
23807
- return model ? [model] : [];
23808
- });
23965
+ return codexModelsFrom(JSON.parse(content));
23809
23966
  } catch {
23810
23967
  return void 0;
23811
23968
  }
23812
23969
  }
23813
- async function readCodexModels(codexHome2, config2) {
23970
+ async function readCodexModels(codexHome3, config2) {
23814
23971
  const configuredCatalog = configValue(config2, "model_catalog_json");
23815
23972
  if (configuredCatalog) {
23816
- const catalogPath = isAbsolute(configuredCatalog) ? configuredCatalog : resolve3(codexHome2, configuredCatalog);
23817
- const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
23973
+ const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve4(codexHome3, configuredCatalog);
23974
+ const configuredModels = parseCodexModels(await readFile5(catalogPath, "utf8").catch(() => ""));
23818
23975
  if (configuredModels?.length) return configuredModels;
23819
23976
  }
23820
- return parseCodexModels(
23821
- await readFile4(join11(codexHome2, "models_cache.json"), "utf8").catch(() => "")
23822
- ) ?? [];
23977
+ const cached3 = parseCodexModels(await readFile5(join12(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
23978
+ if (cached3?.length) return cached3;
23979
+ return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
23823
23980
  }
23824
23981
  async function readCodexModelCatalog() {
23825
- const home = codexHome();
23826
- const config2 = await readFile4(join11(home, "config.toml"), "utf8").catch(() => "");
23827
- const models = await readCodexModels(home, config2);
23982
+ const home = codexHome2();
23983
+ const config2 = await readFile5(join12(home, "config.toml"), "utf8").catch(() => "");
23984
+ const models2 = await readCodexModels(home, config2);
23828
23985
  const defaultModel = configValue(config2, "model");
23829
23986
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
23830
23987
  const catalog = {
23831
23988
  agent_type: "codex",
23832
23989
  fetched_at: (/* @__PURE__ */ new Date()).toISOString(),
23833
- models
23990
+ models: models2
23834
23991
  };
23835
23992
  if (defaultModel) catalog.default_model = defaultModel;
23836
23993
  if (defaultReasoningEffort) catalog.default_reasoning_effort = defaultReasoningEffort;
@@ -23839,7 +23996,7 @@ async function readCodexModelCatalog() {
23839
23996
  function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date()).toISOString(), settings = {}) {
23840
23997
  const source = payload && typeof payload === "object" ? payload : {};
23841
23998
  const defaults = objectValue(settings["chat.modelDefaults"] ?? objectValue(settings.chat).modelDefaults);
23842
- const models = Array.isArray(source.models) ? source.models.flatMap((item) => {
23999
+ const models2 = Array.isArray(source.models) ? source.models.flatMap((item) => {
23843
24000
  const entry = item && typeof item === "object" ? item : {};
23844
24001
  const id = stringValue(entry.model_id) ?? stringValue(entry.model_name);
23845
24002
  if (!id) return [];
@@ -23858,11 +24015,11 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
23858
24015
  const catalog = {
23859
24016
  agent_type: "kiro",
23860
24017
  fetched_at: fetchedAt,
23861
- models
24018
+ models: models2
23862
24019
  };
23863
24020
  const defaultModel = stringValue(source.default_model);
23864
24021
  if (defaultModel) catalog.default_model = defaultModel;
23865
- const defaultEffort = models.find((model) => model.id === defaultModel)?.default_reasoning_effort;
24022
+ const defaultEffort = models2.find((model) => model.id === defaultModel)?.default_reasoning_effort;
23866
24023
  if (defaultEffort) catalog.default_reasoning_effort = defaultEffort;
23867
24024
  return catalog;
23868
24025
  }
@@ -23872,9 +24029,9 @@ function cliExecutable(id) {
23872
24029
  return process.env[spec.overrideEnv]?.trim() || resolveCliCommand(cliCommand(spec));
23873
24030
  }
23874
24031
  function runModelListCommand(executable, args, label, environment) {
23875
- return new Promise((resolve8, reject) => {
24032
+ return new Promise((resolve9, reject) => {
23876
24033
  const launch = directLaunch2(executable, args);
23877
- const child = spawn7(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
24034
+ const child = spawn8(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
23878
24035
  let stdout = "";
23879
24036
  let stderr = "";
23880
24037
  const timer = setTimeout(() => {
@@ -23895,12 +24052,25 @@ function runModelListCommand(executable, args, label, environment) {
23895
24052
  });
23896
24053
  child.once("close", (code) => {
23897
24054
  clearTimeout(timer);
23898
- if (code === 0) resolve8(stdout);
24055
+ if (code === 0) resolve9(stdout);
23899
24056
  else reject(new Error((stderr || stdout || `${label} exited with code ${code ?? "unknown"}`).trim()));
23900
24057
  });
23901
24058
  });
23902
24059
  }
23903
- async function readKiroModelCatalog() {
24060
+ var kiroEfforts;
24061
+ var KIRO_EFFORTS_MAX_AGE_MS = 60 * 60 * 1e3;
24062
+ var kiroListSignature = (list) => JSON.stringify([list.default_model ?? "", list.models.map((model) => [model.model_id, model.model_name, model.description ?? ""])]);
24063
+ function withKnownEfforts(base, known) {
24064
+ const efforts = new Map((known?.models ?? []).map((model) => [model.model_id, model]));
24065
+ return {
24066
+ ...base,
24067
+ models: base.models.map((model) => {
24068
+ const read = efforts.get(model.model_id);
24069
+ return read ? { ...model, supported_reasoning_efforts: read.supported_reasoning_efforts, ...read.default_reasoning_effort ? { default_reasoning_effort: read.default_reasoning_effort } : {} } : model;
24070
+ })
24071
+ };
24072
+ }
24073
+ async function readKiroModelCatalog(options = {}) {
23904
24074
  const environment = mergeShellProxyEnvironment(await hydrateShellPath(), providerEnvironment());
23905
24075
  const kiro = requireCliSpec("kiro");
23906
24076
  const listLaunch = launchCli({ spec: kiro, args: ["chat", "--list-models", "--format", "json"], env: environment });
@@ -23916,10 +24086,23 @@ async function readKiroModelCatalog() {
23916
24086
  ...listed.default_model ? { default_model: listed.default_model } : {},
23917
24087
  models: listed.models.map((model) => ({ model_id: model.id, model_name: model.name, ...model.description ? { description: model.description } : {}, supported_reasoning_efforts: [] }))
23918
24088
  };
23919
- const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
24089
+ const signature = kiroListSignature(base);
24090
+ const known = kiroEfforts;
24091
+ const current = !options.force && known?.signature === signature && Date.now() - known.readAt < KIRO_EFFORTS_MAX_AGE_MS;
24092
+ const readEfforts = async () => {
24093
+ if (current) return known.catalog;
24094
+ try {
24095
+ const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
24096
+ const catalog = await readKiroNativeModels(launch, homedir7(), { catalog: base });
24097
+ kiroEfforts = { signature, readAt: Date.now(), catalog };
24098
+ return catalog;
24099
+ } catch {
24100
+ return withKnownEfforts(base, known?.catalog);
24101
+ }
24102
+ };
23920
24103
  const [payload, content] = await Promise.all([
23921
- readKiroNativeModels(launch, homedir6(), { catalog: base }),
23922
- readFile4(join11(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
24104
+ readEfforts(),
24105
+ readFile5(join12(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
23923
24106
  ]);
23924
24107
  let settings;
23925
24108
  try {
@@ -23945,7 +24128,7 @@ function parseEnvFile(content) {
23945
24128
  }
23946
24129
  function parseGeminiModelCatalog(payload, defaultModel, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
23947
24130
  const source = payload && typeof payload === "object" ? payload : {};
23948
- const models = Array.isArray(source.models) ? source.models.flatMap((item) => {
24131
+ const models2 = Array.isArray(source.models) ? source.models.flatMap((item) => {
23949
24132
  const entry = item && typeof item === "object" ? item : {};
23950
24133
  const rawId = stringValue(entry.name);
23951
24134
  if (!rawId) return [];
@@ -23962,7 +24145,7 @@ function parseGeminiModelCatalog(payload, defaultModel, fetchedAt = (/* @__PURE_
23962
24145
  const catalog = {
23963
24146
  agent_type: "gemini",
23964
24147
  fetched_at: fetchedAt,
23965
- models
24148
+ models: models2
23966
24149
  };
23967
24150
  if (defaultModel?.trim()) catalog.default_model = defaultModel.trim();
23968
24151
  return catalog;
@@ -23976,7 +24159,7 @@ function geminiModelsUrl(baseUrl) {
23976
24159
  }
23977
24160
  async function readGeminiModelCatalog() {
23978
24161
  const fileEnvironment = parseEnvFile(
23979
- await readFile4(join11(geminiHome(), ".env"), "utf8").catch(() => "")
24162
+ await readFile5(join12(geminiHome(), ".env"), "utf8").catch(() => "")
23980
24163
  );
23981
24164
  const environment = { ...fileEnvironment, ...process.env };
23982
24165
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -24021,7 +24204,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
24021
24204
  return catalog;
24022
24205
  }
24023
24206
  async function readGrokModelCatalog() {
24024
- const config2 = await readFile4(join11(grokHome(), "config.toml"), "utf8").catch(() => "");
24207
+ const config2 = await readFile5(join12(grokHome(), "config.toml"), "utf8").catch(() => "");
24025
24208
  const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
24026
24209
  const catalog = parseGrokModelCatalog(output2, config2);
24027
24210
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -24040,30 +24223,31 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
24040
24223
  return catalog;
24041
24224
  }
24042
24225
  async function readOpencodeModelCatalog() {
24043
- const config2 = await readFile4(join11(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join11(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
24226
+ const config2 = await readFile5(join12(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile5(join12(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
24044
24227
  const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
24045
24228
  const catalog = parseOpencodeModelCatalog(output2, config2);
24046
24229
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
24047
24230
  return catalog;
24048
24231
  }
24049
24232
  var TEN_MINUTES = 10 * 60 * 1e3;
24233
+ var TWO_MINUTES = 2 * 60 * 1e3;
24050
24234
  var MODEL_SOURCES = {
24051
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join11(claudeHome(), "settings.json")] },
24235
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join12(claudeHome(), "settings.json")] },
24052
24236
  codex: {
24053
24237
  read: readCodexModelCatalog,
24054
24238
  watchFiles: () => {
24055
- const home = codexHome();
24056
- return [join11(home, "config.toml"), join11(home, "models_cache.json")];
24239
+ const home = codexHome2();
24240
+ return [join12(home, "config.toml"), join12(home, "models_cache.json")];
24057
24241
  },
24058
24242
  // model_catalog_json may point anywhere; a periodic re-read covers it.
24059
24243
  refreshEveryMs: TEN_MINUTES
24060
24244
  },
24061
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join11(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
24062
- grok: { read: readGrokModelCatalog, watchFiles: () => [join11(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
24063
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join11(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
24245
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join12(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
24246
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join12(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
24247
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join12(kiroHome(), "settings", "cli.json")], refreshEveryMs: TWO_MINUTES },
24064
24248
  opencode: {
24065
24249
  read: readOpencodeModelCatalog,
24066
- watchFiles: () => [join11(opencodeHome(), "opencode.json"), join11(opencodeHome(), "opencode.jsonc")],
24250
+ watchFiles: () => [join12(opencodeHome(), "opencode.json"), join12(opencodeHome(), "opencode.jsonc")],
24067
24251
  refreshEveryMs: TEN_MINUTES
24068
24252
  }
24069
24253
  };
@@ -24162,9 +24346,9 @@ function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COM
24162
24346
  // src/providers/detection.ts
24163
24347
  function probeVersion(path, args) {
24164
24348
  if (args.length === 0) return Promise.resolve({});
24165
- return new Promise((resolve8) => {
24349
+ return new Promise((resolve9) => {
24166
24350
  const launch = directLaunch2(path, args);
24167
- const child = spawn8(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
24351
+ const child = spawn9(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
24168
24352
  let stdout = "";
24169
24353
  let stderr = "";
24170
24354
  let settled = false;
@@ -24173,7 +24357,7 @@ function probeVersion(path, args) {
24173
24357
  if (settled) return;
24174
24358
  settled = true;
24175
24359
  if (timer) clearTimeout(timer);
24176
- resolve8(result);
24360
+ resolve9(result);
24177
24361
  };
24178
24362
  timer = setTimeout(() => {
24179
24363
  child.kill("SIGKILL");
@@ -24245,10 +24429,10 @@ var cliDetection = new CliDetectionService();
24245
24429
 
24246
24430
  // src/runtime/agent-runtime.ts
24247
24431
  import { randomUUID as randomUUID4 } from "node:crypto";
24248
- import { join as join18 } from "node:path";
24432
+ import { join as join19 } from "node:path";
24249
24433
 
24250
24434
  // src/exec/script-runner.ts
24251
- import { spawn as spawn9 } from "node:child_process";
24435
+ import { spawn as spawn10 } from "node:child_process";
24252
24436
  var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
24253
24437
  function executeScript(command, workdir, timeoutSeconds) {
24254
24438
  return new Promise((resolveExecution) => {
@@ -24279,7 +24463,7 @@ function executeScript(command, workdir, timeoutSeconds) {
24279
24463
  };
24280
24464
  let child;
24281
24465
  try {
24282
- child = spawn9(executable, args, {
24466
+ child = spawn10(executable, args, {
24283
24467
  cwd: workdir,
24284
24468
  env: process.env,
24285
24469
  detached: ownGroup,
@@ -24377,14 +24561,14 @@ var MAX_OUTPUT_BYTES = 1024 * 1024;
24377
24561
  var runNmem = (args) => {
24378
24562
  const env = providerEnvironment();
24379
24563
  const launch = resolveExecutable("nmem", args, env, process.env.TOC_OCRA_NMEM_PATH);
24380
- return new Promise((resolve8) => {
24564
+ return new Promise((resolve9) => {
24381
24565
  execFile5(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true }, (error62, stdout) => {
24382
24566
  if (!error62) {
24383
- resolve8({ stdout: String(stdout) });
24567
+ resolve9({ stdout: String(stdout) });
24384
24568
  return;
24385
24569
  }
24386
24570
  const failure2 = error62;
24387
- resolve8({ stdout: String(stdout ?? ""), code: failure2.code ?? "failed" });
24571
+ resolve9({ stdout: String(stdout ?? ""), code: failure2.code ?? "failed" });
24388
24572
  });
24389
24573
  });
24390
24574
  };
@@ -24467,10 +24651,10 @@ async function handleMemoryProviderRequest(input2, registry2 = providers) {
24467
24651
 
24468
24652
  // src/providers/model-catalog-collector.ts
24469
24653
  import { createHash as createHash2 } from "node:crypto";
24470
- import { stat as stat2 } from "node:fs/promises";
24471
- async function fileStamp(path) {
24654
+ import { stat as stat3 } from "node:fs/promises";
24655
+ async function fileStamp2(path) {
24472
24656
  try {
24473
- const info = await stat2(path);
24657
+ const info = await stat3(path);
24474
24658
  return `${path}:${info.mtimeMs}:${info.size}`;
24475
24659
  } catch {
24476
24660
  return `${path}:-`;
@@ -24502,14 +24686,14 @@ var ModelCatalogCollector = class {
24502
24686
  async readOne(id, force) {
24503
24687
  const source = this.sources[id];
24504
24688
  const now = Date.now();
24505
- const stamps = await Promise.all(source.watchFiles().map(fileStamp));
24689
+ const stamps = await Promise.all(source.watchFiles().map(fileStamp2));
24506
24690
  const fingerprint = stamps.join("|");
24507
24691
  const cached3 = this.cache.get(id);
24508
24692
  const expired = source.refreshEveryMs !== void 0 && cached3 !== void 0 && now - cached3.readAt >= source.refreshEveryMs;
24509
24693
  if (cached3 && !force && !expired && cached3.fingerprint === fingerprint) return cached3.item;
24510
24694
  let item;
24511
24695
  try {
24512
- const catalog = await source.read();
24696
+ const catalog = await source.read({ force });
24513
24697
  item = { agent_type: id, catalog: { ...catalog, agent_type: id } };
24514
24698
  } catch (error62) {
24515
24699
  item = { agent_type: id, error: error62 instanceof Error ? error62.message : String(error62) };
@@ -24533,16 +24717,16 @@ async function readCLIQuotaReport(agentType) {
24533
24717
  }
24534
24718
 
24535
24719
  // src/providers/tb-switch-control.ts
24536
- import { readFile as readFile5 } from "node:fs/promises";
24537
- import { homedir as homedir7 } from "node:os";
24538
- import { join as join12 } from "node:path";
24720
+ import { readFile as readFile6 } from "node:fs/promises";
24721
+ import { homedir as homedir8 } from "node:os";
24722
+ import { join as join13 } from "node:path";
24539
24723
  function dataDir() {
24540
- return process.env.TB_SWITCH_HOME?.trim() || join12(homedir7(), ".tb-switch");
24724
+ return process.env.TB_SWITCH_HOME?.trim() || join13(homedir8(), ".tb-switch");
24541
24725
  }
24542
24726
  async function readLocalService() {
24543
24727
  let discovery;
24544
24728
  try {
24545
- discovery = JSON.parse(await readFile5(join12(dataDir(), "api.json"), "utf8"));
24729
+ discovery = JSON.parse(await readFile6(join13(dataDir(), "api.json"), "utf8"));
24546
24730
  } catch {
24547
24731
  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");
24548
24732
  }
@@ -24558,7 +24742,7 @@ async function readLocalService() {
24558
24742
  }
24559
24743
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
24560
24744
  try {
24561
- token = (await readFile5(join12(dataDir(), "api-token"), "utf8")).trim();
24745
+ token = (await readFile6(join13(dataDir(), "api-token"), "utf8")).trim();
24562
24746
  } catch {
24563
24747
  }
24564
24748
  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");
@@ -24648,8 +24832,8 @@ async function controlTbSwitch(payload) {
24648
24832
  }
24649
24833
 
24650
24834
  // src/runs/orphan-registry.ts
24651
- import { mkdir as mkdir4, readFile as readFile6, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
24652
- import { basename, dirname as dirname6 } from "node:path";
24835
+ import { mkdir as mkdir5, readFile as readFile7, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
24836
+ import { basename, dirname as dirname7 } from "node:path";
24653
24837
  var OrphanRegistry = class {
24654
24838
  constructor(file2) {
24655
24839
  this.file = file2;
@@ -24667,17 +24851,17 @@ var OrphanRegistry = class {
24667
24851
  persist() {
24668
24852
  const snapshot = JSON.stringify([...this.records.values()]);
24669
24853
  this.writing = this.writing.then(async () => {
24670
- await mkdir4(dirname6(this.file), { recursive: true, mode: 448 });
24854
+ await mkdir5(dirname7(this.file), { recursive: true, mode: 448 });
24671
24855
  const temporary = `${this.file}.${process.pid}.tmp`;
24672
- await writeFile4(temporary, snapshot, { mode: 384 });
24673
- await rename4(temporary, this.file);
24856
+ await writeFile5(temporary, snapshot, { mode: 384 });
24857
+ await rename5(temporary, this.file);
24674
24858
  }).catch(() => void 0);
24675
24859
  }
24676
24860
  /** Kills leftovers from a previous agent process; returns what was stopped. */
24677
24861
  async reapPrevious() {
24678
24862
  let previous = [];
24679
24863
  try {
24680
- previous = JSON.parse(await readFile6(this.file, "utf8"));
24864
+ previous = JSON.parse(await readFile7(this.file, "utf8"));
24681
24865
  } catch {
24682
24866
  return [];
24683
24867
  }
@@ -24701,9 +24885,9 @@ function commandOf(pid) {
24701
24885
  }
24702
24886
 
24703
24887
  // src/runs/run-supervisor.ts
24704
- import { spawn as spawn11 } from "node:child_process";
24705
- import { mkdir as mkdir7, realpath as realpath2, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
24706
- import { basename as basename3, isAbsolute as isAbsolute3, join as join16, relative as relative2, resolve as resolve4 } from "node:path";
24888
+ import { spawn as spawn12 } from "node:child_process";
24889
+ import { mkdir as mkdir8, realpath as realpath2, stat as stat6, writeFile as writeFile8 } from "node:fs/promises";
24890
+ import { basename as basename3, isAbsolute as isAbsolute4, join as join17, relative as relative2, resolve as resolve5 } from "node:path";
24707
24891
  import { createInterface as createInterface5 } from "node:readline";
24708
24892
 
24709
24893
  // src/session/terminal-tail-buffer.ts
@@ -24985,12 +25169,12 @@ function codexGoalProvider(request, goal) {
24985
25169
  }
24986
25170
 
24987
25171
  // src/providers/cli/codex-fork.ts
24988
- import { spawn as spawn10 } from "node:child_process";
25172
+ import { spawn as spawn11 } from "node:child_process";
24989
25173
  import { createInterface as createInterface4 } from "node:readline";
24990
25174
  var FORK_TIMEOUT_MS = 9e4;
24991
25175
  async function forkCodexThread(options) {
24992
25176
  const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--listen", "stdio://"] });
24993
- const child = spawn10(launch.executable, launch.args, {
25177
+ const child = spawn11(launch.executable, launch.args, {
24994
25178
  cwd: options.workdir,
24995
25179
  env: launch.env,
24996
25180
  shell: false,
@@ -25005,9 +25189,9 @@ async function forkCodexThread(options) {
25005
25189
  });
25006
25190
  let nextId = 1;
25007
25191
  const pending = /* @__PURE__ */ new Map();
25008
- const call = (method, params) => new Promise((resolve8, reject) => {
25192
+ const call = (method, params) => new Promise((resolve9, reject) => {
25009
25193
  const id = nextId++;
25010
- pending.set(id, { resolve: resolve8, reject });
25194
+ pending.set(id, { resolve: resolve9, reject });
25011
25195
  child.stdin.write(`${JSON.stringify({ id, method, params })}
25012
25196
  `);
25013
25197
  });
@@ -25065,19 +25249,19 @@ async function forkCodexThread(options) {
25065
25249
 
25066
25250
  // src/runs/run-recorder.ts
25067
25251
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3 } from "node:fs";
25068
- import { homedir as homedir8 } from "node:os";
25069
- import { join as join13 } from "node:path";
25252
+ import { homedir as homedir9 } from "node:os";
25253
+ import { join as join14 } from "node:path";
25070
25254
  var RunRecorder = class _RunRecorder {
25071
25255
  constructor(path) {
25072
25256
  this.path = path;
25073
25257
  }
25074
25258
  path;
25075
- home = homedir8();
25259
+ home = homedir9();
25076
25260
  static fromEnvironment(runId, meta3) {
25077
25261
  const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
25078
25262
  if (!directory) return void 0;
25079
25263
  mkdirSync3(directory, { recursive: true });
25080
- const recorder = new _RunRecorder(join13(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
25264
+ const recorder = new _RunRecorder(join14(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
25081
25265
  recorder.write({ meta: meta3 });
25082
25266
  return recorder;
25083
25267
  }
@@ -25092,8 +25276,8 @@ var RunRecorder = class _RunRecorder {
25092
25276
  };
25093
25277
 
25094
25278
  // src/runs/run-transcript.ts
25095
- import { chmod as chmod3, mkdir as mkdir5, readdir as readdir2, readFile as readFile7, rename as rename5, stat as stat3, unlink, writeFile as writeFile5 } from "node:fs/promises";
25096
- import { join as join14 } from "node:path";
25279
+ import { chmod as chmod4, mkdir as mkdir6, readdir as readdir2, readFile as readFile8, rename as rename6, stat as stat4, unlink, writeFile as writeFile6 } from "node:fs/promises";
25280
+ import { join as join15 } from "node:path";
25097
25281
  var MAX_TRANSCRIPT_ITEMS = 5e3;
25098
25282
  var MAX_TRANSCRIPT_TEXT = 2e5;
25099
25283
  var MAX_TRANSCRIPT_LINES = 2e4;
@@ -25358,7 +25542,7 @@ function transcriptFileName(runId) {
25358
25542
  var TranscriptStore = class {
25359
25543
  constructor(dataDir2, logger, env = process.env) {
25360
25544
  this.logger = logger;
25361
- this.directory = dataDir2 ? join14(dataDir2, "transcripts") : "";
25545
+ this.directory = dataDir2 ? join15(dataDir2, "transcripts") : "";
25362
25546
  this.enabled = Boolean(dataDir2) && transcriptsOnDisk(env);
25363
25547
  }
25364
25548
  logger;
@@ -25413,7 +25597,7 @@ var TranscriptStore = class {
25413
25597
  await this.writes.get(runId);
25414
25598
  let text2;
25415
25599
  try {
25416
- text2 = await readFile7(join14(this.directory, name), "utf8");
25600
+ text2 = await readFile8(join15(this.directory, name), "utf8");
25417
25601
  } catch (error62) {
25418
25602
  if (errorCode(error62) !== "ENOENT") this.logger.warn("run-transcript-read-failed", { runId, error: errorMessage(error62) });
25419
25603
  return void 0;
@@ -25478,10 +25662,10 @@ var TranscriptStore = class {
25478
25662
  transcript.dirty = false;
25479
25663
  const body = JSON.stringify(transcript.toFile());
25480
25664
  await this.ensureDirectory();
25481
- const file2 = join14(this.directory, name);
25665
+ const file2 = join15(this.directory, name);
25482
25666
  const temporary = `${file2}.${process.pid}.tmp`;
25483
- await writeFile5(temporary, body, { mode: 384 });
25484
- await rename5(temporary, file2);
25667
+ await writeFile6(temporary, body, { mode: 384 });
25668
+ await rename6(temporary, file2);
25485
25669
  this.cache.delete(runId);
25486
25670
  }).catch((error62) => {
25487
25671
  transcript.dirty = true;
@@ -25500,8 +25684,8 @@ var TranscriptStore = class {
25500
25684
  }
25501
25685
  async ensureDirectory() {
25502
25686
  if (this.directoryReady) return;
25503
- await mkdir5(this.directory, { recursive: true, mode: 448 });
25504
- await chmod3(this.directory, 448).catch(() => void 0);
25687
+ await mkdir6(this.directory, { recursive: true, mode: 448 });
25688
+ await chmod4(this.directory, 448).catch(() => void 0);
25505
25689
  this.directoryReady = true;
25506
25690
  }
25507
25691
  async pruneOnce() {
@@ -25515,29 +25699,29 @@ var TranscriptStore = class {
25515
25699
  const now = Date.now();
25516
25700
  const files = [];
25517
25701
  for (const name of names) {
25518
- const path = join14(this.directory, name);
25702
+ const path = join15(this.directory, name);
25519
25703
  if (name.endsWith(".tmp")) {
25520
- const info2 = await stat3(path).catch(() => void 0);
25704
+ const info2 = await stat4(path).catch(() => void 0);
25521
25705
  if (info2?.isFile() && now - info2.mtimeMs > STALE_TEMPORARY_MS) await unlink(path).catch(() => void 0);
25522
25706
  continue;
25523
25707
  }
25524
25708
  if (!name.endsWith(".json")) continue;
25525
- const info = await stat3(path).catch(() => void 0);
25709
+ const info = await stat4(path).catch(() => void 0);
25526
25710
  if (info?.isFile()) files.push({ runId: name.slice(0, -".json".length), path, mtime: info.mtimeMs, size: info.size });
25527
25711
  }
25528
25712
  files.sort((a, b) => b.mtime - a.mtime);
25529
- let count = 0;
25713
+ let count2 = 0;
25530
25714
  let bytes = 0;
25531
25715
  let full = false;
25532
25716
  for (const file2 of files) {
25533
25717
  const live = this.tracked.has(file2.runId) || this.writes.has(file2.runId);
25534
- if (!live && (full || count + 1 > MAX_FILES || bytes + file2.size > MAX_TOTAL_BYTES)) {
25718
+ if (!live && (full || count2 + 1 > MAX_FILES || bytes + file2.size > MAX_TOTAL_BYTES)) {
25535
25719
  full = true;
25536
25720
  await unlink(file2.path).catch(() => void 0);
25537
25721
  this.cache.delete(file2.runId);
25538
25722
  continue;
25539
25723
  }
25540
- count += 1;
25724
+ count2 += 1;
25541
25725
  bytes += file2.size;
25542
25726
  }
25543
25727
  }
@@ -25564,24 +25748,24 @@ function errorMessage(error62) {
25564
25748
  // src/runs/task-attachments.ts
25565
25749
  import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
25566
25750
  import { constants as constants2 } from "node:fs";
25567
- import { lstat, mkdir as mkdir6, open as open3, realpath, rename as rename6, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";
25568
- import { basename as basename2, isAbsolute as isAbsolute2, join as join15, relative } from "node:path";
25751
+ import { lstat, mkdir as mkdir7, open as open3, realpath, rename as rename7, rm as rm3, writeFile as writeFile7 } from "node:fs/promises";
25752
+ import { basename as basename2, isAbsolute as isAbsolute3, join as join16, relative } from "node:path";
25569
25753
  function within(root2, path) {
25570
25754
  const segment = relative(root2, path);
25571
- return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
25755
+ return segment === "" || !segment.startsWith("..") && !isAbsolute3(segment);
25572
25756
  }
25573
25757
  async function attachmentDirectory(workdir, messageId) {
25574
25758
  let directory = workdir;
25575
25759
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
25576
- directory = join15(directory, segment);
25577
- await mkdir6(directory, { mode: 448 }).catch((error62) => {
25760
+ directory = join16(directory, segment);
25761
+ await mkdir7(directory, { mode: 448 }).catch((error62) => {
25578
25762
  if (error62.code !== "EEXIST") throw error62;
25579
25763
  });
25580
25764
  const metadata = await lstat(directory);
25581
25765
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
25582
25766
  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");
25583
25767
  }
25584
- if (segment === ".echo") await writeFile6(join15(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
25768
+ if (segment === ".echo") await writeFile7(join16(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
25585
25769
  if (error62.code !== "EEXIST") throw error62;
25586
25770
  });
25587
25771
  }
@@ -25618,14 +25802,14 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
25618
25802
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
25619
25803
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
25620
25804
  const name = characters.join("") || "attachment";
25621
- const path = join15(directory, `${file2.file_id}-${name}`);
25805
+ const path = join16(directory, `${file2.file_id}-${name}`);
25622
25806
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
25623
- const temporary = join15(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
25807
+ const temporary = join16(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
25624
25808
  try {
25625
25809
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
25626
25810
  signal2.throwIfAborted();
25627
25811
  if (!within(workdir, await realpath(directory))) throw new Error("\u9644\u4EF6\u76EE\u5F55\u5DF2\u6539\u53D8\uFF0C\u8BF7\u91CD\u8BD5");
25628
- await rename6(temporary, path);
25812
+ await rename7(temporary, path);
25629
25813
  } finally {
25630
25814
  await rm3(temporary, { force: true });
25631
25815
  }
@@ -25735,7 +25919,7 @@ var ChatEventForwarder = class {
25735
25919
 
25736
25920
  // src/acp/chat-session.ts
25737
25921
  import { randomUUID as randomUUID3 } from "node:crypto";
25738
- import { readFile as readFile8, stat as stat4 } from "node:fs/promises";
25922
+ import { readFile as readFile9, stat as stat5 } from "node:fs/promises";
25739
25923
  import { extname } from "node:path";
25740
25924
  import { pathToFileURL } from "node:url";
25741
25925
 
@@ -25974,6 +26158,46 @@ function redactSecretAnswers(elicitation, outcome) {
25974
26158
  return { ...outcome, _meta: { ...outcome._meta, lody: { ...lody, elicitation: { ...elicitationMeta, answers } } } };
25975
26159
  }
25976
26160
 
26161
+ // src/acp/usage-tally.ts
26162
+ var MAX_MODELS = 20;
26163
+ function count(value) {
26164
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
26165
+ }
26166
+ var UsageTally = class {
26167
+ models = /* @__PURE__ */ new Map();
26168
+ /** One `_lody/session/usage_update` params object. */
26169
+ add(params) {
26170
+ const delta = params.delta;
26171
+ if (!delta || typeof delta !== "object") return;
26172
+ const modelUsage = delta.modelUsage;
26173
+ if (!modelUsage || typeof modelUsage !== "object") return;
26174
+ for (const [rawModel, raw] of Object.entries(modelUsage)) {
26175
+ if (!raw || typeof raw !== "object") continue;
26176
+ const usage = raw;
26177
+ const model = rawModel.trim().slice(0, 200) || "unknown";
26178
+ let entry = this.models.get(model);
26179
+ if (!entry) {
26180
+ if (this.models.size >= MAX_MODELS) continue;
26181
+ entry = { model, input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0, cost_usd: 0 };
26182
+ this.models.set(model, entry);
26183
+ }
26184
+ entry.input_tokens += count(usage.inputTokens);
26185
+ entry.output_tokens += count(usage.outputTokens);
26186
+ entry.cache_read_tokens += count(usage.cacheReadInputTokens);
26187
+ entry.cache_write_tokens += count(usage.cacheCreationInputTokens);
26188
+ entry.reasoning_tokens += count(usage.reasoningOutputTokens);
26189
+ const cost = usage.costUSD;
26190
+ if (entry.cost_usd !== null) {
26191
+ entry.cost_usd = typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? entry.cost_usd + cost : null;
26192
+ }
26193
+ }
26194
+ }
26195
+ /** The models that counted anything. */
26196
+ list() {
26197
+ return [...this.models.values()].filter((entry) => entry.input_tokens + entry.output_tokens + entry.cache_read_tokens + entry.cache_write_tokens + entry.reasoning_tokens > 0);
26198
+ }
26199
+ };
26200
+
25977
26201
  // src/acp/chat-session.ts
25978
26202
  var CANCELLED_PERMISSION = { outcome: { outcome: "cancelled" } };
25979
26203
  var QUESTION_OPTIONS = [
@@ -26012,7 +26236,7 @@ var AcpChatSession = class {
26012
26236
  this.clearIdle();
26013
26237
  this.lastUsedAt = Date.now();
26014
26238
  const transcript = new TurnTranscript((events) => sink.events(events), (rows) => sink.rows(rows));
26015
- const turn = { runId: request.runId, phase: "starting", request, transcript, sink, cancelRequested: false, loading: false, queued: [], awaiting: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map() };
26239
+ 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() };
26016
26240
  this.turn = turn;
26017
26241
  for (const note of request.notes) transcript.note(note);
26018
26242
  let result;
@@ -26031,6 +26255,8 @@ var AcpChatSession = class {
26031
26255
  turn.awaiting.clear();
26032
26256
  transcript.flushRows();
26033
26257
  result.finalMessage = transcript.finalMessage;
26258
+ const usage = turn.usage.list();
26259
+ if (usage.length) result.usage = usage;
26034
26260
  this.turn = void 0;
26035
26261
  this.lastUsedAt = Date.now();
26036
26262
  this.scheduleIdle();
@@ -26205,7 +26431,14 @@ var AcpChatSession = class {
26205
26431
  if (wanted && connection.canOpenSaved && (this.spec.resumable?.(wanted) ?? true)) {
26206
26432
  turn.loading = true;
26207
26433
  try {
26208
- this.session = await connection.openSaved(wanted, request.workdir);
26434
+ try {
26435
+ this.session = await connection.openSaved(wanted, request.workdir);
26436
+ } catch (error62) {
26437
+ if (!(connection.alive && isArchivedSessionError(error62))) throw error62;
26438
+ await connection.extRequest("_session/unarchive", { sessionId: wanted });
26439
+ transcript.note(`\u4F1A\u8BDD ${wanted} \u5DF2\u53D6\u6D88\u5F52\u6863`);
26440
+ this.session = await connection.openSaved(wanted, request.workdir);
26441
+ }
26209
26442
  transcript.note(`\u7EE7\u7EED\u4F1A\u8BDD ${wanted}`);
26210
26443
  return this.session;
26211
26444
  } catch (error62) {
@@ -26262,8 +26495,9 @@ var AcpChatSession = class {
26262
26495
  const value = option ? matchChoice(option, request.reasoningEffort) : void 0;
26263
26496
  if (option && value && option.currentValue !== value) await attempt("\u63A8\u7406\u5F3A\u5EA6", () => this.setOption(connection, session, option, value));
26264
26497
  }
26265
- const fast = session.configOptions.find((option) => option.id === "fast" && option.options.some((choice) => choice.value === "on"));
26498
+ const fast = fastOption(session.configOptions);
26266
26499
  if (fast && (request.fast ? "on" : "off") !== fast.currentValue) await attempt("\u5FEB\u901F\u6A21\u5F0F", () => this.setOption(connection, session, fast, request.fast ? "on" : "off"));
26500
+ 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`);
26267
26501
  turn.transcript.sessionConfig({ ...session.currentModeId ? { currentModeId: session.currentModeId } : {}, configOptions: session.configOptions });
26268
26502
  }
26269
26503
  async setOption(connection, session, option, value) {
@@ -26278,9 +26512,9 @@ var AcpChatSession = class {
26278
26512
  for (const file2 of request.attachments) {
26279
26513
  const mimeType = IMAGE_TYPES[extname(file2.path).toLowerCase()];
26280
26514
  if (file2.kind === "image" && mimeType && connection.imagePrompts) {
26281
- const size = await stat4(file2.path).then((info) => info.size).catch(() => 0);
26515
+ const size = await stat5(file2.path).then((info) => info.size).catch(() => 0);
26282
26516
  if (size > 0 && size <= MAX_IMAGE_BYTES) {
26283
- blocks.push({ type: "image", mimeType, data: (await readFile8(file2.path)).toString("base64") });
26517
+ blocks.push({ type: "image", mimeType, data: (await readFile9(file2.path)).toString("base64") });
26284
26518
  continue;
26285
26519
  }
26286
26520
  }
@@ -26372,7 +26606,7 @@ var AcpChatSession = class {
26372
26606
  const shown = turn.transcript.permissionRequest(toolCall, { requestId, options, ...meta3 ? { _meta: meta3 } : {}, outcome: null });
26373
26607
  const title = elicitation ? String(toolCall.title) : shown.title ?? (typeof toolCall.title === "string" && toolCall.title ? toolCall.title : "\u5DE5\u5177\u8C03\u7528");
26374
26608
  turn.transcript.note(elicitation ? `\u7B49\u5F85\u56DE\u7B54\u95EE\u9898\uFF1A${title}` : `\u7B49\u5F85\u6388\u6743\uFF1A${title}`);
26375
- return new Promise((resolve8) => {
26609
+ return new Promise((resolve9) => {
26376
26610
  const withdrawn = () => {
26377
26611
  if (!turn.pending.has(requestId)) return;
26378
26612
  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}`);
@@ -26389,7 +26623,7 @@ var AcpChatSession = class {
26389
26623
  turn.pending.delete(requestId);
26390
26624
  signal2.removeEventListener("abort", withdrawn);
26391
26625
  turn.transcript.permissionOutcome(toolCallId, requestId, elicitation ? redactSecretAnswers(elicitation, outcome) : outcome);
26392
- resolve8(outcome);
26626
+ resolve9(outcome);
26393
26627
  }
26394
26628
  };
26395
26629
  turn.pending.set(requestId, pending);
@@ -26417,6 +26651,7 @@ var AcpChatSession = class {
26417
26651
  }
26418
26652
  if (!turn) return;
26419
26653
  if (method === "_lody/session/usage_update") {
26654
+ if (!turn.loading) turn.usage.add(params);
26420
26655
  turn.transcript.usage(params);
26421
26656
  return;
26422
26657
  }
@@ -26477,10 +26712,18 @@ var AcpChatSession = class {
26477
26712
  if (connection) await connection.dispose().catch(() => void 0);
26478
26713
  }
26479
26714
  };
26715
+ function isArchivedSessionError(error62) {
26716
+ if (!(error62 instanceof JsonRpcError)) return false;
26717
+ const data = error62.data && typeof error62.data === "object" ? error62.data : {};
26718
+ return data.reason === "archived" || /^Session is archived\b/.test(error62.message);
26719
+ }
26480
26720
  function permissionOptions(value) {
26481
26721
  if (!Array.isArray(value)) return [];
26482
26722
  return value.map(record2).flatMap((option) => typeof option.optionId === "string" && option.optionId ? [{ optionId: option.optionId, name: typeof option.name === "string" ? option.name : option.optionId, kind: typeof option.kind === "string" ? option.kind : "" }] : []);
26483
26723
  }
26724
+ function fastOption(options) {
26725
+ return options.find((option) => (option.id === "fast" || option.id === "fast-mode") && option.options.some((choice) => choice.value === "on"));
26726
+ }
26484
26727
  function findOption(options, category) {
26485
26728
  const ids = { thought_level: ["effort", "reasoning_effort", "thought_level"], model: ["model"], mode: ["mode"] };
26486
26729
  return options.find((option) => option.category === category && option.options.length) ?? options.find((option) => (ids[category] ?? [category]).includes(option.id) && option.options.length);
@@ -26568,6 +26811,40 @@ var AcpChatHost = class {
26568
26811
  if (!session || session.runId !== runId) return { outcome: "not-found" };
26569
26812
  return session.answerPermission(requestId, outcome);
26570
26813
  }
26814
+ /** Stops the live process of one Echo session (archived): a running turn is cancelled first. */
26815
+ async closeSession(key) {
26816
+ const session = this.sessions.get(key);
26817
+ if (!session) return false;
26818
+ this.sessions.delete(key);
26819
+ await session.close();
26820
+ this.options.logger.info("acp-session-closed", { session: key });
26821
+ return true;
26822
+ }
26823
+ /**
26824
+ * Archives or restores the CLI's own session (Lody's archive), through the
26825
+ * adapter's `_session/archive` / `_session/unarchive`: Codex moves the
26826
+ * thread to its archived sessions, Claude marks the transcript. The Echo
26827
+ * session's live process stops first, so nothing holds the session open;
26828
+ * a short-lived adapter process makes the call.
26829
+ */
26830
+ async setArchived(key, sessionId, archived, launch) {
26831
+ if (key) await this.closeSession(key);
26832
+ const connection = await AcpConnection.open(launch.launch, {
26833
+ update: () => {
26834
+ },
26835
+ permission: () => ({ outcome: { outcome: "cancelled" } }),
26836
+ notification: () => {
26837
+ },
26838
+ stderr: () => {
26839
+ }
26840
+ }, this.options.clientVersion);
26841
+ try {
26842
+ await connection.extRequest(archived ? "_session/archive" : "_session/unarchive", { sessionId });
26843
+ this.options.logger.info(archived ? "acp-session-archived" : "acp-session-unarchived", { session: key ?? "", sessionId });
26844
+ } finally {
26845
+ await connection.dispose();
26846
+ }
26847
+ }
26571
26848
  async disposeAll() {
26572
26849
  const sessions = [...this.sessions.values()];
26573
26850
  this.sessions.clear();
@@ -26788,6 +27065,7 @@ var RunSupervisor = class {
26788
27065
  } catch (error62) {
26789
27066
  return refuse({ kind: "hostFault", message: `${errorMessage2(error62)}\uFF0C\u8BF7\u5347\u7EA7\u8BBE\u5907\u4EE3\u7406` });
26790
27067
  }
27068
+ if (cli.id === "codex") await prepareCodexCatalog();
26791
27069
  let provider = cli.headless;
26792
27070
  let workdir;
26793
27071
  try {
@@ -26900,7 +27178,7 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
26900
27178
  if (!fitsCommandLine(launch)) return refuse(cliFailure("promptTooLong", { label: cli.label }));
26901
27179
  let child;
26902
27180
  try {
26903
- child = spawn11(launch.executable, launch.args, {
27181
+ child = spawn12(launch.executable, launch.args, {
26904
27182
  cwd: workdir,
26905
27183
  env: Object.keys(memoryEnv).length ? { ...launch.env, ...memoryEnv } : launch.env,
26906
27184
  detached: currentPlatform.runsInOwnProcessGroup,
@@ -27191,6 +27469,7 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
27191
27469
  else report = failedReport(result.failure ?? cliFailure("turnFailed", { label: cli.label }), durationMs);
27192
27470
  if (result.sessionId) report.session_id = result.sessionId;
27193
27471
  if (result.finalMessage) report.final_message = sanitizeChatText(result.finalMessage);
27472
+ if (result.usage?.length) report.token_usage = result.usage;
27194
27473
  this.log(run, `\u25CF \u672C\u8F6E\u7ED3\u675F\uFF1A${report.status}
27195
27474
  `);
27196
27475
  await this.settleTranscript(transcript, report.status);
@@ -27432,16 +27711,16 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
27432
27711
  async prepareChatAttachments(payload) {
27433
27712
  if (!payload.attachments?.length) return [];
27434
27713
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
27435
- const directory = join16(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
27436
- await mkdir7(directory, { recursive: true, mode: 448 });
27714
+ const directory = join17(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
27715
+ await mkdir8(directory, { recursive: true, mode: 448 });
27437
27716
  const files = [];
27438
27717
  for (const attachment of payload.attachments) {
27439
27718
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
27440
- const path = join16(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
27441
- const existing = await stat5(path).catch(() => void 0);
27719
+ const path = join17(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
27720
+ const existing = await stat6(path).catch(() => void 0);
27442
27721
  if (!existing?.isFile()) {
27443
27722
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
27444
- await writeFile7(path, data, { mode: 384 });
27723
+ await writeFile8(path, data, { mode: 384 });
27445
27724
  }
27446
27725
  files.push({ path, name: attachment.name, kind: attachment.kind });
27447
27726
  }
@@ -27451,6 +27730,28 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
27451
27730
  this.unreported.add(runId);
27452
27731
  await this.reporter.finished(runId, report);
27453
27732
  }
27733
+ /**
27734
+ * `cli.session.archive` (Lody's 归档): the Echo session's live process stops,
27735
+ * then the CLI archives or restores its own session. `native: false` when
27736
+ * this CLI has no ACP adapter here (nothing to archive on its side).
27737
+ */
27738
+ async setCliSessionArchived(input2) {
27739
+ const id = catalogEntry(input2.agentType)?.id;
27740
+ const spec = id ? acpChatSpec(id) : void 0;
27741
+ if (!spec) {
27742
+ if (input2.key) await this.acpChats.closeSession(input2.key);
27743
+ return { native: false };
27744
+ }
27745
+ let workdir;
27746
+ try {
27747
+ workdir = input2.workdir ? await this.validateWorkdir(input2.workdir) : await this.defaultChatWorkdir();
27748
+ } catch {
27749
+ workdir = await this.defaultChatWorkdir();
27750
+ }
27751
+ const launch = await this.acpChats.prepare(spec, { access: "default", reasoningEffort: "", model: "", workdir });
27752
+ await this.acpChats.setArchived(input2.key, input2.sessionId, input2.archived, launch);
27753
+ return { native: true };
27754
+ }
27454
27755
  /** Stops a run: the whole process tree, then a `cancelled` report. */
27455
27756
  async cancel(runId) {
27456
27757
  const acp = this.acpRuns.get(runId);
@@ -27566,14 +27867,14 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
27566
27867
  if (!input2) throw new Error("\u6CA1\u6709\u914D\u7F6E\u5141\u8BB8\u7684\u5DE5\u4F5C\u76EE\u5F55");
27567
27868
  let candidate;
27568
27869
  try {
27569
- candidate = await realpath2(isAbsolute3(input2) ? input2 : resolve4(input2));
27870
+ candidate = await realpath2(isAbsolute4(input2) ? input2 : resolve5(input2));
27570
27871
  } catch {
27571
27872
  throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${input2}`);
27572
27873
  }
27573
27874
  for (const root2 of this.config.allowedRoots) {
27574
- const allowed = await realpath2(root2).catch(() => resolve4(root2));
27875
+ const allowed = await realpath2(root2).catch(() => resolve5(root2));
27575
27876
  const segment = relative2(allowed, candidate);
27576
- if (segment === "" || !segment.startsWith("..") && !isAbsolute3(segment)) return candidate;
27877
+ if (segment === "" || !segment.startsWith("..") && !isAbsolute4(segment)) return candidate;
27577
27878
  }
27578
27879
  throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5728\u5141\u8BB8\u8303\u56F4\u5185\uFF1A${input2}`);
27579
27880
  }
@@ -27722,16 +28023,16 @@ var GatewayClient = class {
27722
28023
  };
27723
28024
 
27724
28025
  // src/workspace/directory-browser.ts
27725
- import { readdir as readdir3, realpath as realpath3, stat as stat6 } from "node:fs/promises";
27726
- import { homedir as homedir9 } from "node:os";
27727
- import { dirname as dirname7, parse as parse3, resolve as resolve5 } from "node:path";
28026
+ import { readdir as readdir3, realpath as realpath3, stat as stat7 } from "node:fs/promises";
28027
+ import { homedir as homedir10 } from "node:os";
28028
+ import { dirname as dirname8, parse as parse3, resolve as resolve6 } from "node:path";
27728
28029
  var MAX_ENTRIES = 1e3;
27729
28030
  async function listDirectory(requested, allowedRoots) {
27730
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir9()) || homedir9();
27731
- const directory = await realpath3(resolve5(raw)).catch(() => {
28031
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir10()) || homedir10();
28032
+ const directory = await realpath3(resolve6(raw)).catch(() => {
27732
28033
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
27733
28034
  });
27734
- if (!(await stat6(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
28035
+ if (!(await stat7(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
27735
28036
  const entries = await readdir3(directory, { withFileTypes: true }).catch((error62) => {
27736
28037
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
27737
28038
  });
@@ -27740,13 +28041,13 @@ async function listDirectory(requested, allowedRoots) {
27740
28041
  const files = [];
27741
28042
  for (const entry of entries) {
27742
28043
  if (entry.isSymbolicLink()) continue;
27743
- const item = { name: entry.name, path: resolve5(directory, entry.name), hidden: entry.name.startsWith(".") };
28044
+ const item = { name: entry.name, path: resolve6(directory, entry.name), hidden: entry.name.startsWith(".") };
27744
28045
  if (entry.isDirectory()) directories.push(item);
27745
28046
  else if (entry.isFile()) files.push(item);
27746
28047
  }
27747
- const parent = dirname7(directory);
27748
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir9() }];
27749
- for (const root2 of allowedRoots) if (root2 !== homedir9()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
28048
+ const parent = dirname8(directory);
28049
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir10() }];
28050
+ for (const root2 of allowedRoots) if (root2 !== homedir10()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
27750
28051
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
27751
28052
  return {
27752
28053
  path: directory,
@@ -27759,10 +28060,10 @@ async function listDirectory(requested, allowedRoots) {
27759
28060
  }
27760
28061
 
27761
28062
  // src/workspace/workspace-manager.ts
27762
- import { spawn as spawn12 } from "node:child_process";
27763
- import { chmod as chmod4, mkdir as mkdir8, mkdtemp, opendir, realpath as realpath4, rm as rm4, stat as stat7, writeFile as writeFile8 } from "node:fs/promises";
27764
- import { homedir as homedir10, tmpdir as tmpdir2 } from "node:os";
27765
- import { isAbsolute as isAbsolute4, join as join17, relative as relative3, resolve as resolve6 } from "node:path";
28063
+ import { spawn as spawn13 } from "node:child_process";
28064
+ import { chmod as chmod5, mkdir as mkdir9, mkdtemp, opendir, realpath as realpath4, rm as rm4, stat as stat8, writeFile as writeFile9 } from "node:fs/promises";
28065
+ import { homedir as homedir11, tmpdir as tmpdir2 } from "node:os";
28066
+ import { isAbsolute as isAbsolute5, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
27766
28067
  var MAX_NODES = 2e3;
27767
28068
  var MAX_DIRECTORY_ENTRIES = 12e3;
27768
28069
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -27810,14 +28111,14 @@ var WorkspaceManager = class {
27810
28111
  };
27811
28112
  }
27812
28113
  validateRootPath(value) {
27813
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir10());
27814
- const root2 = resolve6(raw);
27815
- if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
27816
- if (relative3(root2, resolve6(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
28114
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir11());
28115
+ const root2 = resolve7(raw);
28116
+ if (!isAbsolute5(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
28117
+ if (relative3(root2, resolve7(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
27817
28118
  return root2;
27818
28119
  }
27819
28120
  async syncTree(rootPath, request) {
27820
- await mkdir8(rootPath, { recursive: true });
28121
+ await mkdir9(rootPath, { recursive: true });
27821
28122
  await addAllowedRoot(this.config, rootPath);
27822
28123
  const results = [];
27823
28124
  const requestedPaths = /* @__PURE__ */ new Set();
@@ -27827,7 +28128,7 @@ var WorkspaceManager = class {
27827
28128
  requestedPaths.add(relativePath);
27828
28129
  const target = this.resolveWithinRoot(rootPath, relativePath);
27829
28130
  try {
27830
- const metadata = await stat7(target).catch(() => void 0);
28131
+ const metadata = await stat8(target).catch(() => void 0);
27831
28132
  if (metadata) {
27832
28133
  if (!metadata.isDirectory()) {
27833
28134
  throw new Error("The existing workspace path is not a directory");
@@ -27841,7 +28142,7 @@ var WorkspaceManager = class {
27841
28142
  });
27842
28143
  continue;
27843
28144
  }
27844
- await mkdir8(target, { recursive: true });
28145
+ await mkdir9(target, { recursive: true });
27845
28146
  results.push({
27846
28147
  relative_path: relativePath,
27847
28148
  status: "created",
@@ -27885,12 +28186,12 @@ var WorkspaceManager = class {
27885
28186
  let created = false;
27886
28187
  let metadata;
27887
28188
  try {
27888
- metadata = await stat7(target);
28189
+ metadata = await stat8(target);
27889
28190
  } catch {
27890
28191
  }
27891
28192
  if (!metadata) {
27892
28193
  if (!gitUrl) throw new Error("A missing repository needs a Git remote URL");
27893
- await mkdir8(resolve6(target, ".."), { recursive: true });
28194
+ await mkdir9(resolve7(target, ".."), { recursive: true });
27894
28195
  const cloneArgs = branch ? ["clone", "--branch", branch, "--single-branch", gitUrl, target] : ["clone", gitUrl, target];
27895
28196
  await this.runGit(cloneArgs, rootPath, timeoutSeconds, false, gitEnvironment);
27896
28197
  created = true;
@@ -27985,7 +28286,7 @@ var WorkspaceManager = class {
27985
28286
  }
27986
28287
  async scanTree(rootPath, maxDepth, scanRoots) {
27987
28288
  const resolvedRoot = await realpath4(rootPath);
27988
- const rootMetadata = await stat7(resolvedRoot);
28289
+ const rootMetadata = await stat8(resolvedRoot);
27989
28290
  if (!rootMetadata.isDirectory()) throw new Error("The workspace root is not a directory");
27990
28291
  const nodes = [];
27991
28292
  let entriesRead = 0;
@@ -28019,7 +28320,7 @@ var WorkspaceManager = class {
28019
28320
  for await (const entry of entries) {
28020
28321
  if (nodes.length >= MAX_NODES || entriesRead++ >= MAX_DIRECTORY_ENTRIES) return;
28021
28322
  if (!entry.isDirectory() || IGNORED_DIRECTORIES.has(entry.name)) continue;
28022
- const target = resolve6(directory, entry.name);
28323
+ const target = resolve7(directory, entry.name);
28023
28324
  const nodeType = await appendNode(target);
28024
28325
  if (!nodeType || nodeType === "repo") continue;
28025
28326
  if (remainingDepth === void 0 || remainingDepth > 1) {
@@ -28040,7 +28341,7 @@ var WorkspaceManager = class {
28040
28341
  const target = this.resolveWithinRoot(resolvedRoot, relativePath);
28041
28342
  let metadata;
28042
28343
  try {
28043
- metadata = await stat7(target);
28344
+ metadata = await stat8(target);
28044
28345
  } catch (error62) {
28045
28346
  this.logger.warn("workspace-scan-root-missing", {
28046
28347
  rootPath: target,
@@ -28094,16 +28395,16 @@ var WorkspaceManager = class {
28094
28395
  return !value.startsWith("/") && !parts.some((part) => !part || part === "." || part === ".." || part.includes(":"));
28095
28396
  }
28096
28397
  resolveWithinRoot(rootPath, relativePath) {
28097
- const target = resolve6(rootPath, relativePath);
28398
+ const target = resolve7(rootPath, relativePath);
28098
28399
  const relativeToRoot = relative3(rootPath, target);
28099
- if (relativeToRoot.startsWith("..") || isAbsolute4(relativeToRoot)) {
28400
+ if (relativeToRoot.startsWith("..") || isAbsolute5(relativeToRoot)) {
28100
28401
  throw new Error("A workspace path must remain under the configured workspace root");
28101
28402
  }
28102
28403
  return target;
28103
28404
  }
28104
28405
  runGit(args, cwd, timeoutSeconds, allowFailure = false, environment) {
28105
28406
  return new Promise((resolveCommand, rejectCommand) => {
28106
- const child = spawn12("git", args, {
28407
+ const child = spawn13("git", args, {
28107
28408
  cwd,
28108
28409
  env: environment ?? process.env,
28109
28410
  shell: false,
@@ -28137,13 +28438,13 @@ var WorkspaceManager = class {
28137
28438
  }
28138
28439
  async createGitAuthEnvironment(auth) {
28139
28440
  if (!auth) return void 0;
28140
- const directory = await mkdtemp(join17(tmpdir2(), "toc-ocra-git-auth-"));
28441
+ const directory = await mkdtemp(join18(tmpdir2(), "toc-ocra-git-auth-"));
28141
28442
  const isWindows = process.platform === "win32";
28142
- const scriptPath = join17(directory, isWindows ? "askpass.cmd" : "askpass.sh");
28443
+ const scriptPath = join18(directory, isWindows ? "askpass.cmd" : "askpass.sh");
28143
28444
  let script;
28144
28445
  if (isWindows) {
28145
- const helperPath = join17(directory, "askpass.cjs");
28146
- await writeFile8(
28446
+ const helperPath = join18(directory, "askpass.cjs");
28447
+ await writeFile9(
28147
28448
  helperPath,
28148
28449
  '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',
28149
28450
  { mode: 448 }
@@ -28152,8 +28453,8 @@ var WorkspaceManager = class {
28152
28453
  } else {
28153
28454
  script = '#!/bin/sh\ncase "$1" in *Username*|*username*) printf "%s\\n" "$ECHO_GIT_USERNAME" ;; *) printf "%s\\n" "$ECHO_GIT_PASSWORD" ;; esac\n';
28154
28455
  }
28155
- await writeFile8(scriptPath, script, { mode: 448 });
28156
- if (!isWindows) await chmod4(scriptPath, 448);
28456
+ await writeFile9(scriptPath, script, { mode: 448 });
28457
+ if (!isWindows) await chmod5(scriptPath, 448);
28157
28458
  return {
28158
28459
  env: {
28159
28460
  ...process.env,
@@ -28274,6 +28575,14 @@ var SqlRunPayloadSchema = external_exports.object({
28274
28575
  });
28275
28576
  var CliModelsPayloadSchema = external_exports.object({ agent_type: external_exports.string().max(40).optional().default("") });
28276
28577
  var CliQuotaPayloadSchema = external_exports.object({ agent_type: external_exports.string().min(1).max(40) });
28578
+ var CliSessionArchivePayloadSchema = external_exports.object({
28579
+ agent_type: external_exports.string().min(1).max(40),
28580
+ session_id: external_exports.string().min(1).max(200),
28581
+ archived: external_exports.boolean(),
28582
+ workdir: external_exports.string().max(1e3).optional(),
28583
+ task_chain_id: external_exports.string().max(64).optional(),
28584
+ chat_session_id: external_exports.string().max(64).optional()
28585
+ });
28277
28586
  var CliProviderControlPayloadSchema = external_exports.object({
28278
28587
  app: external_exports.enum(["claude", "codex", "gemini"]),
28279
28588
  action: external_exports.enum(["state", "switch_provider", "set_mode", "select_route"]),
@@ -28301,15 +28610,15 @@ var WorkspaceSyncPayloadSchema = external_exports.object({
28301
28610
  });
28302
28611
 
28303
28612
  // src/runtime/agent-runtime.ts
28304
- var sleep2 = (ms, signal2) => new Promise((resolve8) => {
28613
+ var sleep2 = (ms, signal2) => new Promise((resolve9) => {
28305
28614
  if (signal2?.aborted) {
28306
- resolve8();
28615
+ resolve9();
28307
28616
  return;
28308
28617
  }
28309
28618
  const done = () => {
28310
28619
  clearTimeout(timer);
28311
28620
  signal2?.removeEventListener("abort", done);
28312
- resolve8();
28621
+ resolve9();
28313
28622
  };
28314
28623
  const timer = setTimeout(done, ms);
28315
28624
  signal2?.addEventListener("abort", done, { once: true });
@@ -28345,7 +28654,7 @@ var AgentRuntime = class {
28345
28654
  }
28346
28655
  };
28347
28656
  this.workspaces = new WorkspaceManager(config2, this.logger);
28348
- this.orphans = new OrphanRegistry(join18(config2.dataDir, "active-runs.json"));
28657
+ this.orphans = new OrphanRegistry(join19(config2.dataDir, "active-runs.json"));
28349
28658
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
28350
28659
  }
28351
28660
  config;
@@ -28379,6 +28688,9 @@ var AgentRuntime = class {
28379
28688
  models = new ModelCatalogCollector();
28380
28689
  catalogReport;
28381
28690
  catalogRefresh;
28691
+ /** Order of catalog reads: a read that started earlier never replaces a later one's report. */
28692
+ catalogReadSeq = 0;
28693
+ catalogReportSeq = 0;
28382
28694
  /** Hash of the catalogs the server has stored (from its heartbeat reply). */
28383
28695
  serverCatalogHash;
28384
28696
  heartbeatInFlight;
@@ -28495,9 +28807,14 @@ var AgentRuntime = class {
28495
28807
  /** Re-reads catalogs whose sources changed; concurrent calls share one run. */
28496
28808
  refreshCatalogs(options = {}) {
28497
28809
  if (this.catalogRefresh && !options.force) return this.catalogRefresh;
28810
+ const seq = ++this.catalogReadSeq;
28498
28811
  const run = (async () => {
28499
28812
  try {
28500
- this.catalogReport = await this.models.collect(this.detection?.detectedIds ?? [], options);
28813
+ const report = await this.models.collect(this.detection?.detectedIds ?? [], options);
28814
+ if (seq > this.catalogReportSeq) {
28815
+ this.catalogReportSeq = seq;
28816
+ this.catalogReport = report;
28817
+ }
28501
28818
  } catch (error62) {
28502
28819
  this.logger.warn("model-catalog-failed", { error: error62 instanceof Error ? error62.message : String(error62) });
28503
28820
  }
@@ -28654,6 +28971,18 @@ var AgentRuntime = class {
28654
28971
  return { success: false, error: error62 instanceof Error ? error62.message : String(error62) };
28655
28972
  }
28656
28973
  }
28974
+ case "cli.session.archive": {
28975
+ const payload = CliSessionArchivePayloadSchema.parse(command.payload);
28976
+ const key = payload.task_chain_id || payload.chat_session_id || void 0;
28977
+ const result = await this.runs.setCliSessionArchived({
28978
+ agentType: payload.agent_type,
28979
+ sessionId: payload.session_id,
28980
+ archived: payload.archived,
28981
+ ...payload.workdir ? { workdir: payload.workdir } : {},
28982
+ ...key ? { key } : {}
28983
+ });
28984
+ return { success: true, result: { archived: payload.archived, ...result } };
28985
+ }
28657
28986
  case "cli.providers": {
28658
28987
  const payload = CliProviderControlPayloadSchema.parse(command.payload);
28659
28988
  const run = this.providerControlTail.then(() => controlTbSwitch(payload));
@@ -28764,12 +29093,12 @@ var AgentInstanceLock = class _AgentInstanceLock {
28764
29093
  for (let attempt = 0; attempt < 2; attempt++) {
28765
29094
  const lock = new _AgentInstanceLock(version2);
28766
29095
  try {
28767
- await new Promise((resolve8, reject) => {
29096
+ await new Promise((resolve9, reject) => {
28768
29097
  const failed = (error62) => reject(error62);
28769
29098
  lock.server.once("error", failed);
28770
29099
  lock.server.listen({ host: INSTANCE_LOCK_HOST, port: INSTANCE_LOCK_PORT, exclusive: true }, () => {
28771
29100
  lock.server.removeListener("error", failed);
28772
- resolve8();
29101
+ resolve9();
28773
29102
  });
28774
29103
  });
28775
29104
  return lock;
@@ -28783,14 +29112,14 @@ var AgentInstanceLock = class _AgentInstanceLock {
28783
29112
  throw new Error("\u65E0\u6CD5\u83B7\u53D6\u672C\u673A\u8BBE\u5907\u4EE3\u7406\u5355\u5B9E\u4F8B\u9501");
28784
29113
  }
28785
29114
  release() {
28786
- return this.releasePromise ??= new Promise((resolve8) => {
29115
+ return this.releasePromise ??= new Promise((resolve9) => {
28787
29116
  for (const client of this.clients) client.destroy();
28788
- this.server.close(() => resolve8());
29117
+ this.server.close(() => resolve9());
28789
29118
  });
28790
29119
  }
28791
29120
  };
28792
29121
  async function readInstanceOwner() {
28793
- return new Promise((resolve8) => {
29122
+ return new Promise((resolve9) => {
28794
29123
  const socket = createConnection({ host: INSTANCE_LOCK_HOST, port: INSTANCE_LOCK_PORT });
28795
29124
  let data = "";
28796
29125
  const finish = () => {
@@ -28798,12 +29127,12 @@ async function readInstanceOwner() {
28798
29127
  try {
28799
29128
  const owner = JSON.parse(data);
28800
29129
  if (owner.name === "toc-ocra" && owner.protocol === 1 && typeof owner.pid === "number" && Number.isInteger(owner.pid) && owner.pid > 0 && typeof owner.version === "string") {
28801
- resolve8(owner);
29130
+ resolve9(owner);
28802
29131
  return;
28803
29132
  }
28804
29133
  } catch {
28805
29134
  }
28806
- resolve8(void 0);
29135
+ resolve9(void 0);
28807
29136
  };
28808
29137
  socket.setEncoding("utf8");
28809
29138
  socket.setTimeout(1e3, finish);
@@ -29019,13 +29348,13 @@ function errorMessage3(error62) {
29019
29348
 
29020
29349
  // src/runtime/run-service.ts
29021
29350
  import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
29022
- import { dirname as dirname8, resolve as resolve7 } from "node:path";
29351
+ import { dirname as dirname9, resolve as resolve8 } from "node:path";
29023
29352
  import { fileURLToPath as fileURLToPath2 } from "node:url";
29024
29353
  var PACKAGE_NAME = "toc-ocra";
29025
29354
  function agentPackageRoot() {
29026
- let directory = dirname8(fileURLToPath2(import.meta.url));
29355
+ let directory = dirname9(fileURLToPath2(import.meta.url));
29027
29356
  while (true) {
29028
- const packagePath = resolve7(directory, "package.json");
29357
+ const packagePath = resolve8(directory, "package.json");
29029
29358
  if (existsSync6(packagePath)) {
29030
29359
  try {
29031
29360
  const info = JSON.parse(readFileSync7(packagePath, "utf8"));
@@ -29033,14 +29362,14 @@ function agentPackageRoot() {
29033
29362
  } catch {
29034
29363
  }
29035
29364
  }
29036
- const parent = dirname8(directory);
29365
+ const parent = dirname9(directory);
29037
29366
  if (parent === directory) return void 0;
29038
29367
  directory = parent;
29039
29368
  }
29040
29369
  }
29041
29370
  function agentVersion() {
29042
29371
  const root2 = agentPackageRoot();
29043
- return root2 ? JSON.parse(readFileSync7(resolve7(root2, "package.json"), "utf8")).version : "unknown";
29372
+ return root2 ? JSON.parse(readFileSync7(resolve8(root2, "package.json"), "utf8")).version : "unknown";
29044
29373
  }
29045
29374
  async function runService(options = {}) {
29046
29375
  const version2 = agentVersion();
@@ -29096,7 +29425,7 @@ function preferSystemNode() {
29096
29425
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
29097
29426
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
29098
29427
  for (const name of names) {
29099
- const candidate = directory && join19(directory, name);
29428
+ const candidate = directory && join20(directory, name);
29100
29429
  if (candidate && existsSync7(candidate)) {
29101
29430
  process.env.TOC_OCRA_NODE_PATH = candidate;
29102
29431
  return;