toc-ocra 0.3.18 → 0.3.20

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.
@@ -6,8 +6,8 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // src/plugin-service.ts
9
- import { existsSync as existsSync7 } from "node:fs";
10
- import { delimiter as delimiter5, join as join22 } from "node:path";
9
+ import { existsSync as existsSync8 } from "node:fs";
10
+ import { delimiter as delimiter5, join as join24 } from "node:path";
11
11
 
12
12
  // src/config.ts
13
13
  import { randomUUID } from "node:crypto";
@@ -21011,15 +21011,32 @@ function textRows(prefix, text3, maxRows = 40) {
21011
21011
 
21012
21012
  // src/acp/acp-launch-specs.ts
21013
21013
  import { realpathSync as realpathSync2 } from "node:fs";
21014
- import { join as join12 } from "node:path";
21014
+ import { join as join13 } from "node:path";
21015
+
21016
+ // src/providers/claude-sessions.ts
21017
+ import { existsSync as existsSync5, readdirSync as readdirSync3 } from "node:fs";
21018
+ import { homedir as homedir4 } from "node:os";
21019
+ import { join as join7 } from "node:path";
21020
+ function claudeSessionSaved(sessionId, env = process.env) {
21021
+ const id = sessionId.trim();
21022
+ if (!id || /[/\\]/.test(id) || id.includes("..")) return false;
21023
+ const projects = join7(env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir4(), ".claude"), "projects");
21024
+ let folders;
21025
+ try {
21026
+ folders = readdirSync3(projects);
21027
+ } catch (error62) {
21028
+ return error62.code !== "ENOENT";
21029
+ }
21030
+ return folders.some((folder) => existsSync5(join7(projects, folder, `${id}.jsonl`)));
21031
+ }
21015
21032
 
21016
21033
  // src/providers/cli/codex-catalog.ts
21017
21034
  import { spawn as spawn3 } from "node:child_process";
21018
21035
  import { statSync as statSync4 } from "node:fs";
21019
21036
  import { chmod as chmod3, mkdir as mkdir3, readFile as readFile3, rename as rename3, stat, writeFile as writeFile3 } from "node:fs/promises";
21020
- import { homedir as homedir4 } from "node:os";
21021
- import { dirname as dirname6, isAbsolute, join as join7, resolve as resolve2 } from "node:path";
21022
- var codexHome = () => process.env.CODEX_HOME?.trim() || join7(homedir4(), ".codex");
21037
+ import { homedir as homedir5 } from "node:os";
21038
+ import { dirname as dirname6, isAbsolute, join as join8, resolve as resolve2 } from "node:path";
21039
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join8(homedir5(), ".codex");
21023
21040
  var BUNDLED_TIMEOUT_MS = 1e4;
21024
21041
  function configuredCatalogPath(config2, home = codexHome()) {
21025
21042
  const value = config2.match(/^\s*model_catalog_json\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m)?.[1]?.trim();
@@ -21097,11 +21114,11 @@ function fileStamp(path) {
21097
21114
  }
21098
21115
  var stampOf = (configPath, sourcePath) => `${fileStamp(configPath)}|${fileStamp(sourcePath)}`;
21099
21116
  function overlayPath() {
21100
- return join7(agentDataDir(), "codex", "model-catalog.json");
21117
+ return join8(agentDataDir(), "codex", "model-catalog.json");
21101
21118
  }
21102
21119
  async function rebuild() {
21103
21120
  const home = codexHome();
21104
- const configPath = join7(home, "config.toml");
21121
+ const configPath = join8(home, "config.toml");
21105
21122
  const config2 = await readFile3(configPath, "utf8").catch(() => "");
21106
21123
  const sourcePath = configuredCatalogPath(config2, home);
21107
21124
  if (!sourcePath) {
@@ -21155,21 +21172,21 @@ function codexCatalogArgs() {
21155
21172
 
21156
21173
  // src/providers/model-catalog.ts
21157
21174
  import { spawn as spawn5 } from "node:child_process";
21158
- import { readFile as readFile4 } from "node:fs/promises";
21159
- import { homedir as homedir6 } from "node:os";
21160
- import { isAbsolute as isAbsolute2, join as join9, resolve as resolve3 } from "node:path";
21175
+ import { readdir, readFile as readFile4 } from "node:fs/promises";
21176
+ import { homedir as homedir7 } from "node:os";
21177
+ import { isAbsolute as isAbsolute2, join as join10, resolve as resolve3 } from "node:path";
21161
21178
 
21162
21179
  // src/providers/kiro-auth.ts
21163
21180
  import { execFile as execFile3 } from "node:child_process";
21164
- import { homedir as homedir5 } from "node:os";
21165
- import { join as join8 } from "node:path";
21181
+ import { homedir as homedir6 } from "node:os";
21182
+ import { join as join9 } from "node:path";
21166
21183
  import { promisify } from "node:util";
21167
21184
  var execFileAsync = promisify(execFile3);
21168
21185
  var NOT_AUTHENTICATED = "Kiro CLI \u672A\u767B\u5F55\u6216\u65E0\u6CD5\u786E\u8BA4\u767B\u5F55\u72B6\u6001\uFF0C\u8BF7\u5728\u672C\u673A\u767B\u5F55\u540E\u91CD\u8BD5";
21169
21186
  var knownUnauthenticated = false;
21170
21187
  async function hasStoredAuthentication(environment) {
21171
21188
  if (environment.KIRO_API_KEY?.trim()) return true;
21172
- const database = process.platform === "darwin" ? join8(homedir5(), "Library", "Application Support", "kiro-cli", "data.sqlite3") : process.platform === "win32" ? join8(environment.LOCALAPPDATA || join8(homedir5(), "AppData", "Local"), "Kiro-Cli", "data.sqlite3") : join8(environment.XDG_DATA_HOME || join8(homedir5(), ".local", "share"), "kiro-cli", "data.sqlite3");
21189
+ const database = process.platform === "darwin" ? join9(homedir6(), "Library", "Application Support", "kiro-cli", "data.sqlite3") : process.platform === "win32" ? join9(environment.LOCALAPPDATA || join9(homedir6(), "AppData", "Local"), "Kiro-Cli", "data.sqlite3") : join9(environment.XDG_DATA_HOME || join9(homedir6(), ".local", "share"), "kiro-cli", "data.sqlite3");
21173
21190
  const sql = "SELECT 1 FROM auth_kv WHERE key IN ('kirocli:odic:token', 'codewhisperer:odic:token', 'kirocli:external-idp:token', 'kirocli:social:token') AND (json_extract(value, '$.expires_at') IS NULL OR julianday(json_extract(value, '$.expires_at')) > julianday('now')) LIMIT 1;";
21174
21191
  try {
21175
21192
  const { stdout } = await execFileAsync("sqlite3", ["-readonly", database, sql], {
@@ -21288,9 +21305,40 @@ var CLAUDE_REASONING_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
21288
21305
  var CLAUDE_BUILTIN_MODELS = [
21289
21306
  { id: "opus", name: "Opus" },
21290
21307
  { id: "sonnet", name: "Sonnet" },
21291
- { id: "haiku", name: "Haiku" }
21308
+ { id: "haiku", name: "Haiku" },
21309
+ { id: "fable", name: "Fable" }
21292
21310
  ];
21293
- function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
21311
+ function parseClaudeCachedModels(cache) {
21312
+ const listed = objectValue(objectValue(objectValue(cache).catalog).config).models;
21313
+ if (!Array.isArray(listed)) return [];
21314
+ const entries = [];
21315
+ const seen = /* @__PURE__ */ new Set();
21316
+ for (const raw of listed) {
21317
+ const model = objectValue(raw);
21318
+ const id = stringValue(model.id);
21319
+ if (!id || model.disabled === true || seen.has(id)) continue;
21320
+ seen.add(id);
21321
+ const runtime = objectValue(model.runtime);
21322
+ const efforts = Array.isArray(runtime.effort_levels) ? runtime.effort_levels.filter((value) => typeof value === "string" && value.trim() !== "") : [];
21323
+ const name = stringValue(model.name);
21324
+ const description = stringValue(model.description);
21325
+ const defaultEffort = stringValue(runtime.default_effort);
21326
+ const section = stringValue(model.section);
21327
+ entries.push({
21328
+ ...section && { section },
21329
+ entry: {
21330
+ id,
21331
+ name: name ?? id,
21332
+ ...description && { description },
21333
+ ...defaultEffort && efforts.includes(defaultEffort) && { default_reasoning_effort: defaultEffort },
21334
+ supported_reasoning_efforts: efforts
21335
+ }
21336
+ });
21337
+ }
21338
+ const main2 = entries.filter((item) => item.section === "main");
21339
+ return (main2.length ? main2 : entries).map((item) => item.entry);
21340
+ }
21341
+ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt = (/* @__PURE__ */ new Date()).toISOString(), cachedModels = []) {
21294
21342
  const source = objectValue(settings);
21295
21343
  const mergedEnv = { ...objectValue(source.env), ...environment };
21296
21344
  const models2 = /* @__PURE__ */ new Map();
@@ -21314,8 +21362,18 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
21314
21362
  }
21315
21363
  const defaultModel = stringValue(mergedEnv.ANTHROPIC_MODEL) ?? stringValue(source.model);
21316
21364
  if (models2.size === 0) {
21317
- if (defaultModel) addModel(defaultModel);
21318
- for (const model of CLAUDE_BUILTIN_MODELS) addModel(model.id, model.name);
21365
+ if (cachedModels.length) {
21366
+ for (const model of cachedModels) if (!models2.has(model.id)) models2.set(model.id, model);
21367
+ if (defaultModel && !models2.has(defaultModel)) {
21368
+ const rest = [...models2.values()];
21369
+ models2.clear();
21370
+ addModel(defaultModel);
21371
+ for (const model of rest) models2.set(model.id, model);
21372
+ }
21373
+ } else {
21374
+ if (defaultModel) addModel(defaultModel);
21375
+ for (const model of CLAUDE_BUILTIN_MODELS) addModel(model.id, model.name);
21376
+ }
21319
21377
  }
21320
21378
  return {
21321
21379
  agent_type: "claude",
@@ -21324,15 +21382,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
21324
21382
  models: [...models2.values()]
21325
21383
  };
21326
21384
  }
21327
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir6(), ".claude");
21328
- var codexHome2 = () => process.env.CODEX_HOME?.trim() || join9(homedir6(), ".codex");
21329
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join9(homedir6(), ".gemini");
21330
- var grokHome = () => process.env.GROK_HOME?.trim() || join9(homedir6(), ".grok");
21331
- var opencodeHome = () => join9(process.env.XDG_CONFIG_HOME?.trim() || join9(homedir6(), ".config"), "opencode");
21332
- var kiroHome = () => join9(homedir6(), ".kiro");
21385
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join10(homedir7(), ".claude");
21386
+ var codexHome2 = () => process.env.CODEX_HOME?.trim() || join10(homedir7(), ".codex");
21387
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join10(homedir7(), ".gemini");
21388
+ var grokHome = () => process.env.GROK_HOME?.trim() || join10(homedir7(), ".grok");
21389
+ var opencodeHome = () => join10(process.env.XDG_CONFIG_HOME?.trim() || join10(homedir7(), ".config"), "opencode");
21390
+ var kiroHome = () => join10(homedir7(), ".kiro");
21333
21391
  async function readClaudeModelCatalog() {
21334
21392
  const home = claudeHome();
21335
- const content = await readFile4(join9(home, "settings.json"), "utf8").catch(() => "");
21393
+ const content = await readFile4(join10(home, "settings.json"), "utf8").catch(() => "");
21336
21394
  let settings = {};
21337
21395
  if (content) {
21338
21396
  try {
@@ -21341,7 +21399,23 @@ async function readClaudeModelCatalog() {
21341
21399
  throw new Error("Claude \u672C\u673A settings.json \u4E0D\u662F\u6709\u6548 JSON");
21342
21400
  }
21343
21401
  }
21344
- return parseClaudeModelCatalog(settings);
21402
+ return parseClaudeModelCatalog(settings, process.env, (/* @__PURE__ */ new Date()).toISOString(), await readClaudeCachedModels(home));
21403
+ }
21404
+ async function readClaudeCachedModels(home) {
21405
+ const dir = join10(home, "cache", "model-catalog");
21406
+ const names = await readdir(dir).catch(() => []);
21407
+ let newest;
21408
+ for (const name of names) {
21409
+ if (!name.endsWith(".json")) continue;
21410
+ try {
21411
+ const cache = JSON.parse(await readFile4(join10(dir, name), "utf8"));
21412
+ const models2 = parseClaudeCachedModels(cache);
21413
+ const fetchedAt = Number(objectValue(cache).fetchedAt) || 0;
21414
+ if (models2.length && (!newest || fetchedAt > newest.fetchedAt)) newest = { fetchedAt, models: models2 };
21415
+ } catch {
21416
+ }
21417
+ }
21418
+ return newest?.models ?? [];
21345
21419
  }
21346
21420
  function configValue(content, key) {
21347
21421
  const match = content.match(new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']+)["']\\s*(?:#.*)?$`, "m"));
@@ -21390,13 +21464,13 @@ async function readCodexModels(codexHome3, config2) {
21390
21464
  const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
21391
21465
  if (configuredModels?.length) return configuredModels;
21392
21466
  }
21393
- const cached3 = parseCodexModels(await readFile4(join9(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
21467
+ const cached3 = parseCodexModels(await readFile4(join10(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
21394
21468
  if (cached3?.length) return cached3;
21395
21469
  return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
21396
21470
  }
21397
21471
  async function readCodexModelCatalog() {
21398
21472
  const home = codexHome2();
21399
- const config2 = await readFile4(join9(home, "config.toml"), "utf8").catch(() => "");
21473
+ const config2 = await readFile4(join10(home, "config.toml"), "utf8").catch(() => "");
21400
21474
  const models2 = await readCodexModels(home, config2);
21401
21475
  const defaultModel = configValue(config2, "model");
21402
21476
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -21510,7 +21584,7 @@ async function readKiroModelCatalog(options = {}) {
21510
21584
  if (current) return known.catalog;
21511
21585
  try {
21512
21586
  const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
21513
- const catalog = await readKiroNativeModels(launch, homedir6(), { catalog: base });
21587
+ const catalog = await readKiroNativeModels(launch, homedir7(), { catalog: base });
21514
21588
  kiroEfforts = { signature, readAt: Date.now(), catalog };
21515
21589
  return catalog;
21516
21590
  } catch {
@@ -21519,7 +21593,7 @@ async function readKiroModelCatalog(options = {}) {
21519
21593
  };
21520
21594
  const [payload, content] = await Promise.all([
21521
21595
  readEfforts(),
21522
- readFile4(join9(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21596
+ readFile4(join10(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21523
21597
  ]);
21524
21598
  let settings;
21525
21599
  try {
@@ -21576,7 +21650,7 @@ function geminiModelsUrl(baseUrl) {
21576
21650
  }
21577
21651
  async function readGeminiModelCatalog() {
21578
21652
  const fileEnvironment = parseEnvFile(
21579
- await readFile4(join9(geminiHome(), ".env"), "utf8").catch(() => "")
21653
+ await readFile4(join10(geminiHome(), ".env"), "utf8").catch(() => "")
21580
21654
  );
21581
21655
  const environment = { ...fileEnvironment, ...process.env };
21582
21656
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -21621,7 +21695,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
21621
21695
  return catalog;
21622
21696
  }
21623
21697
  async function readGrokModelCatalog() {
21624
- const config2 = await readFile4(join9(grokHome(), "config.toml"), "utf8").catch(() => "");
21698
+ const config2 = await readFile4(join10(grokHome(), "config.toml"), "utf8").catch(() => "");
21625
21699
  const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
21626
21700
  const catalog = parseGrokModelCatalog(output2, config2);
21627
21701
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -21640,7 +21714,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
21640
21714
  return catalog;
21641
21715
  }
21642
21716
  async function readOpencodeModelCatalog() {
21643
- const config2 = await readFile4(join9(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join9(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
21717
+ const config2 = await readFile4(join10(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join10(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
21644
21718
  const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
21645
21719
  const catalog = parseOpencodeModelCatalog(output2, config2);
21646
21720
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -21648,22 +21722,22 @@ async function readOpencodeModelCatalog() {
21648
21722
  }
21649
21723
  var TEN_MINUTES = 10 * 60 * 1e3;
21650
21724
  var MODEL_SOURCES = {
21651
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join9(claudeHome(), "settings.json")] },
21725
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join10(claudeHome(), "settings.json"), join10(claudeHome(), "cache", "model-catalog")] },
21652
21726
  codex: {
21653
21727
  read: readCodexModelCatalog,
21654
21728
  watchFiles: () => {
21655
21729
  const home = codexHome2();
21656
- return [join9(home, "config.toml"), join9(home, "models_cache.json")];
21730
+ return [join10(home, "config.toml"), join10(home, "models_cache.json")];
21657
21731
  },
21658
21732
  // model_catalog_json may point anywhere; a periodic re-read covers it.
21659
21733
  refreshEveryMs: TEN_MINUTES
21660
21734
  },
21661
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join9(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
21662
- grok: { read: readGrokModelCatalog, watchFiles: () => [join9(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
21663
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join9(kiroHome(), "settings", "cli.json")] },
21735
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join10(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
21736
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join10(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
21737
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join10(kiroHome(), "settings", "cli.json")] },
21664
21738
  opencode: {
21665
21739
  read: readOpencodeModelCatalog,
21666
- watchFiles: () => [join9(opencodeHome(), "opencode.json"), join9(opencodeHome(), "opencode.jsonc")],
21740
+ watchFiles: () => [join10(opencodeHome(), "opencode.json"), join10(opencodeHome(), "opencode.jsonc")],
21667
21741
  refreshEveryMs: TEN_MINUTES
21668
21742
  }
21669
21743
  };
@@ -21776,12 +21850,12 @@ function classifySpawnError(error62, context) {
21776
21850
  }
21777
21851
 
21778
21852
  // src/providers/cli/kiro-session-log.ts
21779
- import { open as open2, readdir, readFile as readFile5, stat as stat2 } from "node:fs/promises";
21780
- import { homedir as homedir7 } from "node:os";
21781
- import { join as join10 } from "node:path";
21853
+ import { open as open2, readdir as readdir2, readFile as readFile5, stat as stat2 } from "node:fs/promises";
21854
+ import { homedir as homedir8 } from "node:os";
21855
+ import { join as join11 } from "node:path";
21782
21856
  var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
21783
21857
  function kiroSessionsDirectory() {
21784
- return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join10(homedir7(), ".kiro", "sessions", "cli");
21858
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join11(homedir8(), ".kiro", "sessions", "cli");
21785
21859
  }
21786
21860
  var KiroSessionLog = class {
21787
21861
  constructor(options) {
@@ -21800,7 +21874,7 @@ var KiroSessionLog = class {
21800
21874
  /** Called before the CLI starts: a resumed log is followed from its current end. */
21801
21875
  async begin() {
21802
21876
  if (!this.options.sessionId) return;
21803
- this.path = join10(this.directory, `${this.options.sessionId}.jsonl`);
21877
+ this.path = join11(this.directory, `${this.options.sessionId}.jsonl`);
21804
21878
  this.offset = await stat2(this.path).then((info) => info.size, () => 0);
21805
21879
  }
21806
21880
  /**
@@ -21809,15 +21883,15 @@ var KiroSessionLog = class {
21809
21883
  * in the same folder) leave it unknown.
21810
21884
  */
21811
21885
  async findFreshLog() {
21812
- const names = await readdir(this.directory).catch(() => []);
21886
+ const names = await readdir2(this.directory).catch(() => []);
21813
21887
  const found = [];
21814
21888
  for (const name of names) {
21815
21889
  if (!name.endsWith(".json")) continue;
21816
- const meta3 = await readFile5(join10(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
21890
+ const meta3 = await readFile5(join11(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
21817
21891
  const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
21818
21892
  if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
21819
21893
  }
21820
- if (found.length === 1) this.path = join10(this.directory, `${found[0]}.jsonl`);
21894
+ if (found.length === 1) this.path = join11(this.directory, `${found[0]}.jsonl`);
21821
21895
  }
21822
21896
  /** Reads entries appended since the last call. */
21823
21897
  async refresh() {
@@ -22186,9 +22260,9 @@ var OPENCODE_ACP_DIALECT = {
22186
22260
  // src/acp/vendor.ts
22187
22261
  import { spawn as spawn6 } from "node:child_process";
22188
22262
  import { createHash } from "node:crypto";
22189
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
22263
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
22190
22264
  import { copyFile, mkdir as mkdir4, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22191
- import { dirname as dirname7, join as join11, resolve as resolve4 } from "node:path";
22265
+ import { dirname as dirname7, join as join12, resolve as resolve4 } from "node:path";
22192
22266
  import { fileURLToPath } from "node:url";
22193
22267
  var AcpRuntimeUnavailable = class extends Error {
22194
22268
  constructor(message) {
@@ -22201,7 +22275,7 @@ function packageRoot() {
22201
22275
  let directory = dirname7(fileURLToPath(import.meta.url));
22202
22276
  while (true) {
22203
22277
  const path = resolve4(directory, "package.json");
22204
- if (existsSync5(path)) {
22278
+ if (existsSync6(path)) {
22205
22279
  try {
22206
22280
  if (JSON.parse(readFileSync5(path, "utf8")).name === "toc-ocra") return directory;
22207
22281
  } catch {
@@ -22221,21 +22295,21 @@ function agentPackageVersion() {
22221
22295
  const directory = agentRoot();
22222
22296
  if (!directory) return "0";
22223
22297
  try {
22224
- return JSON.parse(readFileSync5(join11(directory, "package.json"), "utf8")).version ?? "0";
22298
+ return JSON.parse(readFileSync5(join12(directory, "package.json"), "utf8")).version ?? "0";
22225
22299
  } catch {
22226
22300
  return "0";
22227
22301
  }
22228
22302
  }
22229
22303
  function vendoredAdapter(name) {
22230
22304
  const directory = agentRoot();
22231
- const entry = directory ? join11(directory, "assets", "acp", name, "index.mjs") : void 0;
22232
- return entry && existsSync5(entry) ? entry : void 0;
22305
+ const entry = directory ? join12(directory, "assets", "acp", name, "index.mjs") : void 0;
22306
+ return entry && existsSync6(entry) ? entry : void 0;
22233
22307
  }
22234
22308
  var installs = /* @__PURE__ */ new Map();
22235
22309
  function ensureClaudeRuntime(dataDir2) {
22236
22310
  const entry = vendoredAdapter("claude");
22237
22311
  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"));
22238
- const manifestPath = join11(dirname7(entry), "runtime.json");
22312
+ const manifestPath = join12(dirname7(entry), "runtime.json");
22239
22313
  let manifest;
22240
22314
  try {
22241
22315
  manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
@@ -22243,7 +22317,7 @@ function ensureClaudeRuntime(dataDir2) {
22243
22317
  return Promise.reject(new AcpRuntimeUnavailable("Claude ACP \u9002\u914D\u5668\u7F3A\u5C11 runtime.json"));
22244
22318
  }
22245
22319
  const hash2 = createHash("sha256").update(readFileSync5(entry)).digest("hex").slice(0, 12);
22246
- const directory = join11(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
22320
+ const directory = join12(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
22247
22321
  const existing = installs.get(directory);
22248
22322
  if (existing) return existing;
22249
22323
  const install = installClaudeRuntime(directory, entry, manifest).catch((error62) => {
@@ -22254,19 +22328,19 @@ function ensureClaudeRuntime(dataDir2) {
22254
22328
  return install;
22255
22329
  }
22256
22330
  async function installClaudeRuntime(directory, entry, manifest) {
22257
- const sdkPackage = join11(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
22258
- if (existsSync5(sdkPackage) && existsSync5(join11(directory, "index.mjs"))) return directory;
22331
+ const sdkPackage = join12(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
22332
+ if (existsSync6(sdkPackage) && existsSync6(join12(directory, "index.mjs"))) return directory;
22259
22333
  const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`;
22260
22334
  await mkdir4(temporary, { recursive: true, mode: 448 });
22261
22335
  try {
22262
- await writeFile4(join11(temporary, "package.json"), JSON.stringify({
22336
+ await writeFile4(join12(temporary, "package.json"), JSON.stringify({
22263
22337
  name: "toc-ocra-claude-acp-runtime",
22264
22338
  private: true,
22265
22339
  type: "module",
22266
22340
  dependencies: { [manifest.sdk.name]: manifest.sdk.version }
22267
22341
  }, null, 2));
22268
22342
  await runNpm(["install", "--omit=optional", "--no-audit", "--no-fund", "--no-package-lock", "--loglevel=error"], temporary);
22269
- await copyFile(entry, join11(temporary, "index.mjs"));
22343
+ await copyFile(entry, join12(temporary, "index.mjs"));
22270
22344
  await rm2(directory, { recursive: true, force: true });
22271
22345
  await rename4(temporary, directory);
22272
22346
  } catch (error62) {
@@ -22389,13 +22463,15 @@ var CLAUDE_LAUNCH_SPEC = {
22389
22463
  const executable = installedCli(claude);
22390
22464
  const runtime = await ensureClaudeRuntime(dataDir2);
22391
22465
  return {
22392
- launch: { executable: process.execPath, args: [join12(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
22466
+ launch: { executable: process.execPath, args: [join13(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
22393
22467
  fingerprint: `claude:${runtime}:${executable}`
22394
22468
  };
22395
22469
  },
22396
22470
  // Manual mode asks for every edit and command; the user or the level's policy answers.
22397
22471
  permissionModeConfig: { values: { ask: "default", acceptEdits: "acceptEdits", bypassPermissions: "bypassPermissions", plan: "plan" } },
22398
22472
  resumePreference: "resume",
22473
+ // The adapter accepts `session/resume` of a conversation Claude no longer has; only the prompt fails.
22474
+ resumable: (sessionId) => claudeSessionSaved(sessionId, providerEnvironment()),
22399
22475
  dialect: { failureRules: [{ kind: "sessionMissing", pattern: /No conversation found with session ID|session[^\n]{0,40}not found/i }] },
22400
22476
  modelDiscovery: { kind: "reader", source: MODEL_SOURCES.claude }
22401
22477
  };
@@ -22506,7 +22582,7 @@ var ACP_CHAT_IDS = [...ACP_CHAT.keys()];
22506
22582
  // src/acp/acp-model-catalog-probe.ts
22507
22583
  import { mkdtemp, rm as rm3 } from "node:fs/promises";
22508
22584
  import { tmpdir } from "node:os";
22509
- import { join as join13 } from "node:path";
22585
+ import { join as join14 } from "node:path";
22510
22586
 
22511
22587
  // src/acp/acp-options.ts
22512
22588
  var text = (value) => typeof value === "string" && value ? value : void 0;
@@ -23139,9 +23215,9 @@ async function readSessionModels(row, clientVersion = "1") {
23139
23215
  const discovery = row.modelDiscovery;
23140
23216
  if (discovery.kind !== "session") throw new Error(`${row.agent} does not list its models in a session`);
23141
23217
  const cli = requireCliSpec(row.agent);
23142
- const folder = await mkdtemp(join13(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
23218
+ const folder = await mkdtemp(join14(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
23143
23219
  try {
23144
- const folderArgs = discovery.sessionFolderArgs?.(join13(folder, "sessions")) ?? [];
23220
+ const folderArgs = discovery.sessionFolderArgs?.(join14(folder, "sessions")) ?? [];
23145
23221
  const args = [...row.args({ access: "read-only", model: "", reasoningEffort: "" }), ...folderArgs];
23146
23222
  const launch = launchCli({ spec: cli, args, env: { ...providerEnvironment(), ...row.env } });
23147
23223
  const connection = await AcpConnection.open({ executable: launch.executable, args: launch.args, env: launch.env, cwd: folder }, {
@@ -23770,14 +23846,14 @@ function isWriterConflict(message) {
23770
23846
  }
23771
23847
 
23772
23848
  // src/providers/cli/claude.ts
23773
- import { readdirSync as readdirSync3, readFileSync as readFileSync6 } from "node:fs";
23774
- import { homedir as homedir8 } from "node:os";
23775
- import { join as join14 } from "node:path";
23849
+ import { readdirSync as readdirSync4, readFileSync as readFileSync6 } from "node:fs";
23850
+ import { homedir as homedir9 } from "node:os";
23851
+ import { join as join15 } from "node:path";
23776
23852
  var CLAUDE = requireCliSpec("claude");
23777
23853
  function claudeProjectRoots() {
23778
23854
  const configured = process.env.CLAUDE_CONFIG_DIR;
23779
- const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join14(homedir8(), ".claude")];
23780
- return dirs.map((dir) => join14(dir, "projects"));
23855
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join15(homedir9(), ".claude")];
23856
+ return dirs.map((dir) => join15(dir, "projects"));
23781
23857
  }
23782
23858
  function claudeTranscriptExists(sessionId) {
23783
23859
  return claudeTranscriptPath(sessionId) !== void 0;
@@ -23787,13 +23863,13 @@ function claudeTranscriptPath(sessionId) {
23787
23863
  for (const root2 of claudeProjectRoots()) {
23788
23864
  let projects;
23789
23865
  try {
23790
- projects = readdirSync3(root2);
23866
+ projects = readdirSync4(root2);
23791
23867
  } catch {
23792
23868
  continue;
23793
23869
  }
23794
23870
  for (const project of projects) {
23795
23871
  try {
23796
- if (readdirSync3(join14(root2, project)).includes(file2)) return join14(root2, project, file2);
23872
+ if (readdirSync4(join15(root2, project)).includes(file2)) return join15(root2, project, file2);
23797
23873
  } catch {
23798
23874
  }
23799
23875
  }
@@ -23837,7 +23913,7 @@ var claudeProvider = {
23837
23913
  settings.disableAllHooks = true;
23838
23914
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*");
23839
23915
  try {
23840
- const userSettings = JSON.parse(readFileSync6(join14(homedir8(), ".claude", "settings.json"), "utf8"));
23916
+ const userSettings = JSON.parse(readFileSync6(join15(homedir9(), ".claude", "settings.json"), "utf8"));
23841
23917
  for (const [key, value] of Object.entries(userSettings.env ?? {})) {
23842
23918
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
23843
23919
  }
@@ -24647,6 +24723,82 @@ var opencodeProvider = {
24647
24723
  }
24648
24724
  };
24649
24725
 
24726
+ // src/providers/claude-quota.ts
24727
+ import { execFile as execFile5 } from "node:child_process";
24728
+ import { readFile as readFile6 } from "node:fs/promises";
24729
+ import { homedir as homedir10 } from "node:os";
24730
+ import { join as join16 } from "node:path";
24731
+ import { promisify as promisify3 } from "node:util";
24732
+ var execFileAsync3 = promisify3(execFile5);
24733
+ var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
24734
+ var WINDOWS = [
24735
+ { key: "five_hour", label: "5 \u5C0F\u65F6\u989D\u5EA6", seconds: 5 * 3600 },
24736
+ { key: "seven_day", label: "\u6BCF\u5468\u989D\u5EA6", seconds: 7 * 86400 },
24737
+ { key: "seven_day_opus", label: "Opus \xB7 \u6BCF\u5468\u989D\u5EA6", seconds: 7 * 86400 },
24738
+ { key: "seven_day_sonnet", label: "Sonnet \xB7 \u6BCF\u5468\u989D\u5EA6", seconds: 7 * 86400 }
24739
+ ];
24740
+ function objectValue2(value) {
24741
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
24742
+ }
24743
+ function resetSeconds(value) {
24744
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return Math.floor(value > 1e10 ? value / 1e3 : value);
24745
+ if (typeof value === "string" && value.trim()) {
24746
+ const parsed = Date.parse(value);
24747
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
24748
+ }
24749
+ return 0;
24750
+ }
24751
+ function parseClaudeQuota(body) {
24752
+ const source = objectValue2(body);
24753
+ const windows = [];
24754
+ for (const { key, label, seconds } of WINDOWS) {
24755
+ const raw = source[key];
24756
+ if (!raw || typeof raw !== "object") continue;
24757
+ const window = objectValue2(raw);
24758
+ const utilization = Number(window.utilization);
24759
+ windows.push({
24760
+ key: `claude:${key}`,
24761
+ label,
24762
+ resets_at: resetSeconds(window.resets_at),
24763
+ window_seconds: seconds,
24764
+ ...window.utilization !== null && Number.isFinite(utilization) && utilization >= 0 ? { used_percent: Math.min(100, Math.round(utilization * 100) / 100) } : {}
24765
+ });
24766
+ }
24767
+ return windows;
24768
+ }
24769
+ var claudeHome2 = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join16(homedir10(), ".claude");
24770
+ function tokenFrom(content) {
24771
+ try {
24772
+ const token = objectValue2(objectValue2(JSON.parse(content)).claudeAiOauth).accessToken;
24773
+ return typeof token === "string" && token.trim() ? token.trim() : void 0;
24774
+ } catch {
24775
+ return void 0;
24776
+ }
24777
+ }
24778
+ async function readClaudeAccessToken() {
24779
+ const fromEnv = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
24780
+ if (fromEnv) return fromEnv;
24781
+ const fromFile = tokenFrom(await readFile6(join16(claudeHome2(), ".credentials.json"), "utf8").catch(() => ""));
24782
+ if (fromFile) return fromFile;
24783
+ if (process.platform !== "darwin") return void 0;
24784
+ const { stdout } = await execFileAsync3("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 1e4 }).catch(() => ({ stdout: "" }));
24785
+ return tokenFrom(String(stdout).trim());
24786
+ }
24787
+ async function readClaudeQuotaWindows() {
24788
+ const token = await readClaudeAccessToken();
24789
+ if (!token) throw new Error("Claude Code \u672A\u4F7F\u7528 Claude \u8D26\u53F7\u767B\u5F55\uFF08API Key \u65B9\u5F0F\u6CA1\u6709\u5957\u9910\u989D\u5EA6\uFF09\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C claude \u5E76 /login");
24790
+ const response = await fetch(CLAUDE_USAGE_URL, {
24791
+ headers: { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20", accept: "application/json" },
24792
+ redirect: "error",
24793
+ signal: AbortSignal.timeout(15e3)
24794
+ });
24795
+ if (response.status === 401 || response.status === 403) throw new Error("Claude Code \u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C\u4E00\u6B21 claude \u5237\u65B0\u767B\u5F55\u540E\u518D\u8BD5");
24796
+ if (!response.ok) throw new Error(`Claude \u989D\u5EA6\u63A5\u53E3\u8BF7\u6C42\u5931\u8D25 (${response.status})`);
24797
+ const windows = parseClaudeQuota(await response.json());
24798
+ if (!windows.length) throw new Error("Claude \u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u989D\u5EA6\u7A97\u53E3");
24799
+ return windows;
24800
+ }
24801
+
24650
24802
  // src/providers/codex-quota.ts
24651
24803
  import { spawn as spawn8 } from "node:child_process";
24652
24804
  import { createInterface as createInterface3 } from "node:readline";
@@ -24745,10 +24897,10 @@ async function readCodexQuotaWindows() {
24745
24897
  }
24746
24898
 
24747
24899
  // src/providers/kiro-quota.ts
24748
- import { execFile as execFile5 } from "node:child_process";
24900
+ import { execFile as execFile6 } from "node:child_process";
24749
24901
  import { tmpdir as tmpdir2 } from "node:os";
24750
- import { promisify as promisify3, stripVTControlCharacters } from "node:util";
24751
- var execFileAsync3 = promisify3(execFile5);
24902
+ import { promisify as promisify4, stripVTControlCharacters } from "node:util";
24903
+ var execFileAsync4 = promisify4(execFile6);
24752
24904
  var amount = (value) => Number(value.replace(/,/g, ""));
24753
24905
  var rounded = (value) => Math.round(value * 100) / 100;
24754
24906
  function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
@@ -24808,7 +24960,7 @@ async function readKiroQuotaWindows() {
24808
24960
  const launch = launchCli({ spec: requireCliSpec("kiro"), args: ["chat", "--no-interactive", "/usage"] });
24809
24961
  await requireKiroAuthentication(launch.env);
24810
24962
  try {
24811
- const { stdout, stderr } = await execFileAsync3(launch.executable, launch.args, { env: launch.env, cwd: tmpdir2(), timeout: 3e4, maxBuffer: 1024 * 1024, windowsHide: true });
24963
+ const { stdout, stderr } = await execFileAsync4(launch.executable, launch.args, { env: launch.env, cwd: tmpdir2(), timeout: 3e4, maxBuffer: 1024 * 1024, windowsHide: true });
24812
24964
  return parseKiroQuota(`${stdout}
24813
24965
  ${stderr}`);
24814
24966
  } catch (error62) {
@@ -24821,7 +24973,7 @@ ${stderr}`);
24821
24973
  var ALL_LEVELS = ["read-only", "acceptEdits", "bypassPermissions"];
24822
24974
  var NATIVE = {
24823
24975
  codex: { headless: codexProvider, chat: codexChatProvider, models: MODEL_SOURCES.codex, quota: readCodexQuotaWindows, runSettings: { permissionModes: ALL_LEVELS, plan: "prompt", fast: true } },
24824
- claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude, runSettings: { permissionModes: ALL_LEVELS, plan: "native", fast: true } }
24976
+ claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude, quota: readClaudeQuotaWindows, runSettings: { permissionModes: ALL_LEVELS, plan: "native", fast: true } }
24825
24977
  };
24826
24978
  var ACP_EXTRAS = {
24827
24979
  kiro: { quota: readKiroQuotaWindows, legacy: { headless: kiroProvider, restrictedPermission: true, runSettings: { permissionModes: ["read-only", "bypassPermissions"], plan: "prompt" } } },
@@ -25007,7 +25159,7 @@ var cliDetection = new CliDetectionService();
25007
25159
 
25008
25160
  // src/runtime/agent-runtime.ts
25009
25161
  import { randomUUID as randomUUID4 } from "node:crypto";
25010
- import { join as join21 } from "node:path";
25162
+ import { join as join23 } from "node:path";
25011
25163
 
25012
25164
  // src/exec/script-runner.ts
25013
25165
  import { spawn as spawn10 } from "node:child_process";
@@ -25118,7 +25270,7 @@ function resolveChatProvider(type, request, attachments) {
25118
25270
  }
25119
25271
 
25120
25272
  // src/memory/providers.ts
25121
- import { execFile as execFile6 } from "node:child_process";
25273
+ import { execFile as execFile7 } from "node:child_process";
25122
25274
  var MemoryCreateInputSchema = external_exports.object({
25123
25275
  id: external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/),
25124
25276
  name: external_exports.string().trim().min(1).max(200),
@@ -25140,7 +25292,7 @@ var runNmem = (args) => {
25140
25292
  const env = providerEnvironment();
25141
25293
  const launch = resolveExecutable("nmem", args, env, process.env.TOC_OCRA_NMEM_PATH);
25142
25294
  return new Promise((resolve9) => {
25143
- execFile6(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true }, (error62, stdout) => {
25295
+ execFile7(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true }, (error62, stdout) => {
25144
25296
  if (!error62) {
25145
25297
  resolve9({ stdout: String(stdout) });
25146
25298
  return;
@@ -25295,16 +25447,16 @@ async function readCLIQuotaReport(agentType) {
25295
25447
  }
25296
25448
 
25297
25449
  // src/providers/tb-switch-control.ts
25298
- import { readFile as readFile6 } from "node:fs/promises";
25299
- import { homedir as homedir9 } from "node:os";
25300
- import { join as join15 } from "node:path";
25450
+ import { readFile as readFile7 } from "node:fs/promises";
25451
+ import { homedir as homedir11 } from "node:os";
25452
+ import { join as join17 } from "node:path";
25301
25453
  function dataDir() {
25302
- return process.env.TB_SWITCH_HOME?.trim() || join15(homedir9(), ".tb-switch");
25454
+ return process.env.TB_SWITCH_HOME?.trim() || join17(homedir11(), ".tb-switch");
25303
25455
  }
25304
25456
  async function readLocalService() {
25305
25457
  let discovery;
25306
25458
  try {
25307
- discovery = JSON.parse(await readFile6(join15(dataDir(), "api.json"), "utf8"));
25459
+ discovery = JSON.parse(await readFile7(join17(dataDir(), "api.json"), "utf8"));
25308
25460
  } catch {
25309
25461
  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");
25310
25462
  }
@@ -25320,7 +25472,7 @@ async function readLocalService() {
25320
25472
  }
25321
25473
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
25322
25474
  try {
25323
- token = (await readFile6(join15(dataDir(), "api-token"), "utf8")).trim();
25475
+ token = (await readFile7(join17(dataDir(), "api-token"), "utf8")).trim();
25324
25476
  } catch {
25325
25477
  }
25326
25478
  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");
@@ -25410,7 +25562,7 @@ async function controlTbSwitch(payload) {
25410
25562
  }
25411
25563
 
25412
25564
  // src/runs/orphan-registry.ts
25413
- import { mkdir as mkdir5, readFile as readFile7, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
25565
+ import { mkdir as mkdir5, readFile as readFile8, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
25414
25566
  import { basename, dirname as dirname8 } from "node:path";
25415
25567
  var OrphanRegistry = class {
25416
25568
  constructor(file2) {
@@ -25439,7 +25591,7 @@ var OrphanRegistry = class {
25439
25591
  async reapPrevious() {
25440
25592
  let previous = [];
25441
25593
  try {
25442
- previous = JSON.parse(await readFile7(this.file, "utf8"));
25594
+ previous = JSON.parse(await readFile8(this.file, "utf8"));
25443
25595
  } catch {
25444
25596
  return [];
25445
25597
  }
@@ -25465,7 +25617,7 @@ function commandOf(pid) {
25465
25617
  // src/runs/run-supervisor.ts
25466
25618
  import { spawn as spawn12 } from "node:child_process";
25467
25619
  import { mkdir as mkdir8, realpath as realpath2, stat as stat6, writeFile as writeFile8 } from "node:fs/promises";
25468
- import { basename as basename3, isAbsolute as isAbsolute4, join as join19, relative as relative2, resolve as resolve5 } from "node:path";
25620
+ import { basename as basename3, isAbsolute as isAbsolute4, join as join21, relative as relative2, resolve as resolve5 } from "node:path";
25469
25621
  import { createInterface as createInterface5 } from "node:readline";
25470
25622
 
25471
25623
  // src/session/terminal-tail-buffer.ts
@@ -25827,19 +25979,19 @@ async function forkCodexThread(options) {
25827
25979
 
25828
25980
  // src/runs/run-recorder.ts
25829
25981
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3 } from "node:fs";
25830
- import { homedir as homedir10 } from "node:os";
25831
- import { join as join16 } from "node:path";
25982
+ import { homedir as homedir12 } from "node:os";
25983
+ import { join as join18 } from "node:path";
25832
25984
  var RunRecorder = class _RunRecorder {
25833
25985
  constructor(path) {
25834
25986
  this.path = path;
25835
25987
  }
25836
25988
  path;
25837
- home = homedir10();
25989
+ home = homedir12();
25838
25990
  static fromEnvironment(runId, meta3) {
25839
25991
  const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
25840
25992
  if (!directory) return void 0;
25841
25993
  mkdirSync3(directory, { recursive: true });
25842
- const recorder = new _RunRecorder(join16(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
25994
+ const recorder = new _RunRecorder(join18(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
25843
25995
  recorder.write({ meta: meta3 });
25844
25996
  return recorder;
25845
25997
  }
@@ -25854,8 +26006,8 @@ var RunRecorder = class _RunRecorder {
25854
26006
  };
25855
26007
 
25856
26008
  // src/runs/run-transcript.ts
25857
- 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";
25858
- import { join as join17 } from "node:path";
26009
+ import { chmod as chmod4, mkdir as mkdir6, readdir as readdir3, readFile as readFile9, rename as rename6, stat as stat4, unlink, writeFile as writeFile6 } from "node:fs/promises";
26010
+ import { join as join19 } from "node:path";
25859
26011
  var MAX_TRANSCRIPT_ITEMS = 5e3;
25860
26012
  var MAX_TRANSCRIPT_TEXT = 2e5;
25861
26013
  var MAX_TRANSCRIPT_LINES = 2e4;
@@ -26120,7 +26272,7 @@ function transcriptFileName(runId) {
26120
26272
  var TranscriptStore = class {
26121
26273
  constructor(dataDir2, logger, env = process.env) {
26122
26274
  this.logger = logger;
26123
- this.directory = dataDir2 ? join17(dataDir2, "transcripts") : "";
26275
+ this.directory = dataDir2 ? join19(dataDir2, "transcripts") : "";
26124
26276
  this.enabled = Boolean(dataDir2) && transcriptsOnDisk(env);
26125
26277
  }
26126
26278
  logger;
@@ -26175,7 +26327,7 @@ var TranscriptStore = class {
26175
26327
  await this.writes.get(runId);
26176
26328
  let text3;
26177
26329
  try {
26178
- text3 = await readFile8(join17(this.directory, name), "utf8");
26330
+ text3 = await readFile9(join19(this.directory, name), "utf8");
26179
26331
  } catch (error62) {
26180
26332
  if (errorCode(error62) !== "ENOENT") this.logger.warn("run-transcript-read-failed", { runId, error: errorMessage(error62) });
26181
26333
  return void 0;
@@ -26240,7 +26392,7 @@ var TranscriptStore = class {
26240
26392
  transcript.dirty = false;
26241
26393
  const body = JSON.stringify(transcript.toFile());
26242
26394
  await this.ensureDirectory();
26243
- const file2 = join17(this.directory, name);
26395
+ const file2 = join19(this.directory, name);
26244
26396
  const temporary = `${file2}.${process.pid}.tmp`;
26245
26397
  await writeFile6(temporary, body, { mode: 384 });
26246
26398
  await rename6(temporary, file2);
@@ -26269,7 +26421,7 @@ var TranscriptStore = class {
26269
26421
  async pruneOnce() {
26270
26422
  let names;
26271
26423
  try {
26272
- names = await readdir2(this.directory);
26424
+ names = await readdir3(this.directory);
26273
26425
  } catch (error62) {
26274
26426
  if (errorCode(error62) === "ENOENT") return;
26275
26427
  throw error62;
@@ -26277,7 +26429,7 @@ var TranscriptStore = class {
26277
26429
  const now = Date.now();
26278
26430
  const files = [];
26279
26431
  for (const name of names) {
26280
- const path = join17(this.directory, name);
26432
+ const path = join19(this.directory, name);
26281
26433
  if (name.endsWith(".tmp")) {
26282
26434
  const info2 = await stat4(path).catch(() => void 0);
26283
26435
  if (info2?.isFile() && now - info2.mtimeMs > STALE_TEMPORARY_MS) await unlink(path).catch(() => void 0);
@@ -26327,7 +26479,7 @@ function errorMessage(error62) {
26327
26479
  import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
26328
26480
  import { constants as constants2 } from "node:fs";
26329
26481
  import { lstat, mkdir as mkdir7, open as open3, realpath, rename as rename7, rm as rm4, writeFile as writeFile7 } from "node:fs/promises";
26330
- import { basename as basename2, isAbsolute as isAbsolute3, join as join18, relative } from "node:path";
26482
+ import { basename as basename2, isAbsolute as isAbsolute3, join as join20, relative } from "node:path";
26331
26483
  function within(root2, path) {
26332
26484
  const segment = relative(root2, path);
26333
26485
  return segment === "" || !segment.startsWith("..") && !isAbsolute3(segment);
@@ -26335,7 +26487,7 @@ function within(root2, path) {
26335
26487
  async function attachmentDirectory(workdir, messageId) {
26336
26488
  let directory = workdir;
26337
26489
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
26338
- directory = join18(directory, segment);
26490
+ directory = join20(directory, segment);
26339
26491
  await mkdir7(directory, { mode: 448 }).catch((error62) => {
26340
26492
  if (error62.code !== "EEXIST") throw error62;
26341
26493
  });
@@ -26343,7 +26495,7 @@ async function attachmentDirectory(workdir, messageId) {
26343
26495
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
26344
26496
  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");
26345
26497
  }
26346
- if (segment === ".echo") await writeFile7(join18(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
26498
+ if (segment === ".echo") await writeFile7(join20(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
26347
26499
  if (error62.code !== "EEXIST") throw error62;
26348
26500
  });
26349
26501
  }
@@ -26380,9 +26532,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
26380
26532
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
26381
26533
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
26382
26534
  const name = characters.join("") || "attachment";
26383
- const path = join18(directory, `${file2.file_id}-${name}`);
26535
+ const path = join20(directory, `${file2.file_id}-${name}`);
26384
26536
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
26385
- const temporary = join18(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
26537
+ const temporary = join20(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
26386
26538
  try {
26387
26539
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
26388
26540
  signal2.throwIfAborted();
@@ -26497,7 +26649,7 @@ var ChatEventForwarder = class {
26497
26649
 
26498
26650
  // src/acp/chat-session.ts
26499
26651
  import { randomUUID as randomUUID3 } from "node:crypto";
26500
- import { readFile as readFile9, stat as stat5 } from "node:fs/promises";
26652
+ import { readFile as readFile10, stat as stat5 } from "node:fs/promises";
26501
26653
  import { extname } from "node:path";
26502
26654
  import { pathToFileURL } from "node:url";
26503
26655
 
@@ -26782,6 +26934,7 @@ var QUESTION_OPTIONS = [
26782
26934
  { optionId: "answer", name: "Submit answers", kind: "allow_once" },
26783
26935
  { optionId: "cancel", name: "Cancel", kind: "reject_once" }
26784
26936
  ];
26937
+ var TURN_OUTPUT = /* @__PURE__ */ new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);
26785
26938
  var CANCEL_GRACE_MS = 1e4;
26786
26939
  var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
26787
26940
  var IMAGE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp" };
@@ -26814,14 +26967,15 @@ var AcpChatSession = class {
26814
26967
  this.clearIdle();
26815
26968
  this.lastUsedAt = Date.now();
26816
26969
  const transcript = new TurnTranscript((events) => sink.events(events), (rows) => sink.rows(rows));
26817
- 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() };
26970
+ 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(), output: false };
26818
26971
  this.turn = turn;
26819
26972
  for (const note of request.notes) transcript.note(note);
26820
26973
  let result;
26821
26974
  try {
26822
26975
  result = await this.execute(turn, launch);
26823
26976
  } catch (error62) {
26824
- result = this.failed(turn, this.classify(error62));
26977
+ const failure2 = this.classify(error62);
26978
+ result = this.startsFresh(turn, failure2) ? await this.runFresh(turn, launch) : this.failed(turn, failure2);
26825
26979
  } finally {
26826
26980
  if (turn.cancelTimer) clearTimeout(turn.cancelTimer);
26827
26981
  }
@@ -26840,6 +26994,28 @@ var AcpChatSession = class {
26840
26994
  this.scheduleIdle();
26841
26995
  return result;
26842
26996
  }
26997
+ /**
26998
+ * Whether a failed turn runs again in a new session: the saved session it
26999
+ * reopened turned out to be gone before the agent answered anything (Claude
27000
+ * Code accepts `session/resume` of a conversation it no longer has and fails
27001
+ * only at the prompt).
27002
+ */
27003
+ startsFresh(turn, failure2) {
27004
+ return Boolean(turn.reopened) && !turn.output && !turn.cancelRequested && failure2.kind === "sessionMissing";
27005
+ }
27006
+ async runFresh(turn, launch) {
27007
+ turn.transcript.note(`\u539F\u4F1A\u8BDD ${turn.reopened} \u5DF2\u65E0\u6CD5\u7EE7\u7EED\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD`);
27008
+ this.deps.logger.info("acp-session-missing-restart", { session: this.key, sessionId: turn.reopened });
27009
+ turn.request = { ...turn.request, sessionId: "" };
27010
+ turn.reopened = void 0;
27011
+ turn.phase = "starting";
27012
+ this.session = void 0;
27013
+ try {
27014
+ return await this.execute(turn, launch);
27015
+ } catch (error62) {
27016
+ return this.failed(turn, this.classify(error62));
27017
+ }
27018
+ }
26843
27019
  /** Stops the running turn: `session/cancel`, then the process if the agent does not stop. */
26844
27020
  cancel() {
26845
27021
  const turn = this.turn;
@@ -27025,6 +27201,7 @@ var AcpChatSession = class {
27025
27201
  transcript.note(`\u4F1A\u8BDD ${wanted} \u5DF2\u53D6\u6D88\u5F52\u6863`);
27026
27202
  this.session = await connection.openSaved(wanted, request.workdir, reopen);
27027
27203
  }
27204
+ turn.reopened = wanted;
27028
27205
  transcript.note(`\u7EE7\u7EED\u4F1A\u8BDD ${wanted}`);
27029
27206
  return this.session;
27030
27207
  } catch (error62) {
@@ -27080,7 +27257,7 @@ var AcpChatSession = class {
27080
27257
  if (file2.kind === "image" && mimeType && connection.imagePrompts) {
27081
27258
  const size = await stat5(file2.path).then((info) => info.size).catch(() => 0);
27082
27259
  if (size > 0 && size <= MAX_IMAGE_BYTES) {
27083
- blocks.push({ type: "image", mimeType, data: (await readFile9(file2.path)).toString("base64") });
27260
+ blocks.push({ type: "image", mimeType, data: (await readFile10(file2.path)).toString("base64") });
27084
27261
  continue;
27085
27262
  }
27086
27263
  }
@@ -27098,6 +27275,7 @@ var AcpChatSession = class {
27098
27275
  const sessionLevel = kind === "available_commands_update" || kind === "current_mode_update" || kind === "config_option_update";
27099
27276
  if (this.session ? sessionId !== this.session.sessionId : !sessionLevel) return;
27100
27277
  if (turn.loading && !sessionLevel) return;
27278
+ if (typeof kind === "string" && TURN_OUTPUT.has(kind)) turn.output = true;
27101
27279
  const normalize = this.spec.dialect?.normalizeToolUpdate;
27102
27280
  turn.transcript.update(normalize && (kind === "tool_call" || kind === "tool_call_update") ? normalize(update) : update);
27103
27281
  }
@@ -28311,12 +28489,12 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
28311
28489
  async prepareChatAttachments(payload) {
28312
28490
  if (!payload.attachments?.length) return [];
28313
28491
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
28314
- const directory = join19(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
28492
+ const directory = join21(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
28315
28493
  await mkdir8(directory, { recursive: true, mode: 448 });
28316
28494
  const files = [];
28317
28495
  for (const attachment of payload.attachments) {
28318
28496
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
28319
- const path = join19(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
28497
+ const path = join21(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
28320
28498
  const existing = await stat6(path).catch(() => void 0);
28321
28499
  if (!existing?.isFile()) {
28322
28500
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
@@ -28629,17 +28807,17 @@ var GatewayClient = class {
28629
28807
  };
28630
28808
 
28631
28809
  // src/workspace/directory-browser.ts
28632
- import { mkdir as mkdir9, readdir as readdir3, realpath as realpath3, stat as stat7 } from "node:fs/promises";
28633
- import { homedir as homedir11 } from "node:os";
28810
+ import { mkdir as mkdir9, readdir as readdir4, realpath as realpath3, stat as stat7 } from "node:fs/promises";
28811
+ import { homedir as homedir13 } from "node:os";
28634
28812
  import { dirname as dirname9, isAbsolute as isAbsolute5, parse as parse3, resolve as resolve6 } from "node:path";
28635
28813
  var MAX_ENTRIES = 1e3;
28636
28814
  async function listDirectory(requested, allowedRoots) {
28637
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir11()) || homedir11();
28815
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir13()) || homedir13();
28638
28816
  const directory = await realpath3(resolve6(raw)).catch(() => {
28639
28817
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
28640
28818
  });
28641
28819
  if (!(await stat7(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
28642
- const entries = await readdir3(directory, { withFileTypes: true }).catch((error62) => {
28820
+ const entries = await readdir4(directory, { withFileTypes: true }).catch((error62) => {
28643
28821
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
28644
28822
  });
28645
28823
  const byName = (a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base", numeric: true });
@@ -28652,8 +28830,8 @@ async function listDirectory(requested, allowedRoots) {
28652
28830
  else if (entry.isFile()) files.push(item);
28653
28831
  }
28654
28832
  const parent = dirname9(directory);
28655
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir11() }];
28656
- for (const root2 of allowedRoots) if (root2 !== homedir11()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
28833
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir13() }];
28834
+ for (const root2 of allowedRoots) if (root2 !== homedir13()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
28657
28835
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
28658
28836
  return {
28659
28837
  path: directory,
@@ -28691,7 +28869,7 @@ async function createDirectory(parentRequested, name) {
28691
28869
  // src/workspace/workspace-manager.ts
28692
28870
  import { spawn as spawn13 } from "node:child_process";
28693
28871
  import { opendir, realpath as realpath4, stat as stat8 } from "node:fs/promises";
28694
- import { homedir as homedir12 } from "node:os";
28872
+ import { homedir as homedir14 } from "node:os";
28695
28873
  import { isAbsolute as isAbsolute6, relative as relative3, resolve as resolve7 } from "node:path";
28696
28874
  var MAX_NODES = 2e3;
28697
28875
  var MAX_DIRECTORY_ENTRIES = 12e3;
@@ -28727,7 +28905,7 @@ var WorkspaceManager = class {
28727
28905
  return { root_path: rootPath, nodes, truncated: nodes.length >= MAX_NODES, duration_ms: Date.now() - startedAt };
28728
28906
  }
28729
28907
  validateRootPath(value) {
28730
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir12());
28908
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir14());
28731
28909
  const root2 = resolve7(raw);
28732
28910
  if (!isAbsolute6(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
28733
28911
  if (relative3(root2, resolve7(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -29067,7 +29245,7 @@ var AgentRuntime = class {
29067
29245
  }
29068
29246
  };
29069
29247
  this.workspaces = new WorkspaceManager(config2, this.logger);
29070
- this.orphans = new OrphanRegistry(join21(config2.dataDir, "active-runs.json"));
29248
+ this.orphans = new OrphanRegistry(join23(config2.dataDir, "active-runs.json"));
29071
29249
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
29072
29250
  }
29073
29251
  config;
@@ -29772,7 +29950,7 @@ function errorMessage3(error62) {
29772
29950
  }
29773
29951
 
29774
29952
  // src/runtime/run-service.ts
29775
- import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
29953
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
29776
29954
  import { dirname as dirname10, resolve as resolve8 } from "node:path";
29777
29955
  import { fileURLToPath as fileURLToPath2 } from "node:url";
29778
29956
  var PACKAGE_NAME = "toc-ocra";
@@ -29780,7 +29958,7 @@ function agentPackageRoot() {
29780
29958
  let directory = dirname10(fileURLToPath2(import.meta.url));
29781
29959
  while (true) {
29782
29960
  const packagePath = resolve8(directory, "package.json");
29783
- if (existsSync6(packagePath)) {
29961
+ if (existsSync7(packagePath)) {
29784
29962
  try {
29785
29963
  const info = JSON.parse(readFileSync7(packagePath, "utf8"));
29786
29964
  if (info.name === PACKAGE_NAME && typeof info.version === "string") return directory;
@@ -29850,8 +30028,8 @@ function preferSystemNode() {
29850
30028
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
29851
30029
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
29852
30030
  for (const name of names) {
29853
- const candidate = directory && join22(directory, name);
29854
- if (candidate && existsSync7(candidate)) {
30031
+ const candidate = directory && join24(directory, name);
30032
+ if (candidate && existsSync8(candidate)) {
29855
30033
  process.env.TOC_OCRA_NODE_PATH = candidate;
29856
30034
  return;
29857
30035
  }