toc-ocra 0.3.18 → 0.3.19

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.
package/dist/cli/cli.mjs CHANGED
@@ -4576,10 +4576,10 @@ var require_lib = __commonJS({
4576
4576
  // src/index.ts
4577
4577
  import { spawnSync } from "node:child_process";
4578
4578
  import { createHash as createHash5 } from "node:crypto";
4579
- import { existsSync as existsSync7, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
4579
+ import { existsSync as existsSync8, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
4580
4580
  import { tmpdir as tmpdir4 } from "node:os";
4581
4581
  import { createRequire } from "node:module";
4582
- import { dirname as dirname11, join as join23, resolve as resolve9 } from "node:path";
4582
+ import { dirname as dirname11, join as join24, resolve as resolve9 } from "node:path";
4583
4583
  import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL2 } from "node:url";
4584
4584
 
4585
4585
  // src/config.ts
@@ -25374,15 +25374,32 @@ function textRows(prefix, text3, maxRows = 40) {
25374
25374
 
25375
25375
  // src/acp/acp-launch-specs.ts
25376
25376
  import { realpathSync as realpathSync2 } from "node:fs";
25377
- import { join as join12 } from "node:path";
25377
+ import { join as join13 } from "node:path";
25378
+
25379
+ // src/providers/claude-sessions.ts
25380
+ import { existsSync as existsSync4, readdirSync as readdirSync3 } from "node:fs";
25381
+ import { homedir as homedir4 } from "node:os";
25382
+ import { join as join7 } from "node:path";
25383
+ function claudeSessionSaved(sessionId, env = process.env) {
25384
+ const id = sessionId.trim();
25385
+ if (!id || /[/\\]/.test(id) || id.includes("..")) return false;
25386
+ const projects = join7(env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir4(), ".claude"), "projects");
25387
+ let folders;
25388
+ try {
25389
+ folders = readdirSync3(projects);
25390
+ } catch (error62) {
25391
+ return error62.code !== "ENOENT";
25392
+ }
25393
+ return folders.some((folder) => existsSync4(join7(projects, folder, `${id}.jsonl`)));
25394
+ }
25378
25395
 
25379
25396
  // src/providers/cli/codex-catalog.ts
25380
25397
  import { spawn as spawn3 } from "node:child_process";
25381
25398
  import { statSync as statSync3 } from "node:fs";
25382
25399
  import { chmod as chmod3, mkdir as mkdir3, readFile as readFile2, rename as rename3, stat, writeFile as writeFile3 } from "node:fs/promises";
25383
- import { homedir as homedir4 } from "node:os";
25384
- import { dirname as dirname5, isAbsolute, join as join7, resolve as resolve2 } from "node:path";
25385
- var codexHome = () => process.env.CODEX_HOME?.trim() || join7(homedir4(), ".codex");
25400
+ import { homedir as homedir5 } from "node:os";
25401
+ import { dirname as dirname5, isAbsolute, join as join8, resolve as resolve2 } from "node:path";
25402
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join8(homedir5(), ".codex");
25386
25403
  var BUNDLED_TIMEOUT_MS = 1e4;
25387
25404
  function configuredCatalogPath(config2, home = codexHome()) {
25388
25405
  const value = config2.match(/^\s*model_catalog_json\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m)?.[1]?.trim();
@@ -25460,11 +25477,11 @@ function fileStamp(path) {
25460
25477
  }
25461
25478
  var stampOf = (configPath, sourcePath) => `${fileStamp(configPath)}|${fileStamp(sourcePath)}`;
25462
25479
  function overlayPath() {
25463
- return join7(agentDataDir(), "codex", "model-catalog.json");
25480
+ return join8(agentDataDir(), "codex", "model-catalog.json");
25464
25481
  }
25465
25482
  async function rebuild() {
25466
25483
  const home = codexHome();
25467
- const configPath = join7(home, "config.toml");
25484
+ const configPath = join8(home, "config.toml");
25468
25485
  const config2 = await readFile2(configPath, "utf8").catch(() => "");
25469
25486
  const sourcePath = configuredCatalogPath(config2, home);
25470
25487
  if (!sourcePath) {
@@ -25519,20 +25536,20 @@ function codexCatalogArgs() {
25519
25536
  // src/providers/model-catalog.ts
25520
25537
  import { spawn as spawn5 } from "node:child_process";
25521
25538
  import { readFile as readFile3 } from "node:fs/promises";
25522
- import { homedir as homedir6 } from "node:os";
25523
- import { isAbsolute as isAbsolute2, join as join9, resolve as resolve3 } from "node:path";
25539
+ import { homedir as homedir7 } from "node:os";
25540
+ import { isAbsolute as isAbsolute2, join as join10, resolve as resolve3 } from "node:path";
25524
25541
 
25525
25542
  // src/providers/kiro-auth.ts
25526
25543
  import { execFile as execFile3 } from "node:child_process";
25527
- import { homedir as homedir5 } from "node:os";
25528
- import { join as join8 } from "node:path";
25544
+ import { homedir as homedir6 } from "node:os";
25545
+ import { join as join9 } from "node:path";
25529
25546
  import { promisify } from "node:util";
25530
25547
  var execFileAsync = promisify(execFile3);
25531
25548
  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";
25532
25549
  var knownUnauthenticated = false;
25533
25550
  async function hasStoredAuthentication(environment) {
25534
25551
  if (environment.KIRO_API_KEY?.trim()) return true;
25535
- 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");
25552
+ 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");
25536
25553
  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;";
25537
25554
  try {
25538
25555
  const { stdout } = await execFileAsync("sqlite3", ["-readonly", database, sql], {
@@ -25687,15 +25704,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
25687
25704
  models: [...models2.values()]
25688
25705
  };
25689
25706
  }
25690
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir6(), ".claude");
25691
- var codexHome2 = () => process.env.CODEX_HOME?.trim() || join9(homedir6(), ".codex");
25692
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join9(homedir6(), ".gemini");
25693
- var grokHome = () => process.env.GROK_HOME?.trim() || join9(homedir6(), ".grok");
25694
- var opencodeHome = () => join9(process.env.XDG_CONFIG_HOME?.trim() || join9(homedir6(), ".config"), "opencode");
25695
- var kiroHome = () => join9(homedir6(), ".kiro");
25707
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join10(homedir7(), ".claude");
25708
+ var codexHome2 = () => process.env.CODEX_HOME?.trim() || join10(homedir7(), ".codex");
25709
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join10(homedir7(), ".gemini");
25710
+ var grokHome = () => process.env.GROK_HOME?.trim() || join10(homedir7(), ".grok");
25711
+ var opencodeHome = () => join10(process.env.XDG_CONFIG_HOME?.trim() || join10(homedir7(), ".config"), "opencode");
25712
+ var kiroHome = () => join10(homedir7(), ".kiro");
25696
25713
  async function readClaudeModelCatalog() {
25697
25714
  const home = claudeHome();
25698
- const content = await readFile3(join9(home, "settings.json"), "utf8").catch(() => "");
25715
+ const content = await readFile3(join10(home, "settings.json"), "utf8").catch(() => "");
25699
25716
  let settings = {};
25700
25717
  if (content) {
25701
25718
  try {
@@ -25753,13 +25770,13 @@ async function readCodexModels(codexHome3, config2) {
25753
25770
  const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
25754
25771
  if (configuredModels?.length) return configuredModels;
25755
25772
  }
25756
- const cached3 = parseCodexModels(await readFile3(join9(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25773
+ const cached3 = parseCodexModels(await readFile3(join10(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25757
25774
  if (cached3?.length) return cached3;
25758
25775
  return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
25759
25776
  }
25760
25777
  async function readCodexModelCatalog() {
25761
25778
  const home = codexHome2();
25762
- const config2 = await readFile3(join9(home, "config.toml"), "utf8").catch(() => "");
25779
+ const config2 = await readFile3(join10(home, "config.toml"), "utf8").catch(() => "");
25763
25780
  const models2 = await readCodexModels(home, config2);
25764
25781
  const defaultModel = configValue(config2, "model");
25765
25782
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -25873,7 +25890,7 @@ async function readKiroModelCatalog(options = {}) {
25873
25890
  if (current) return known.catalog;
25874
25891
  try {
25875
25892
  const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
25876
- const catalog = await readKiroNativeModels(launch, homedir6(), { catalog: base });
25893
+ const catalog = await readKiroNativeModels(launch, homedir7(), { catalog: base });
25877
25894
  kiroEfforts = { signature, readAt: Date.now(), catalog };
25878
25895
  return catalog;
25879
25896
  } catch {
@@ -25882,7 +25899,7 @@ async function readKiroModelCatalog(options = {}) {
25882
25899
  };
25883
25900
  const [payload, content] = await Promise.all([
25884
25901
  readEfforts(),
25885
- readFile3(join9(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
25902
+ readFile3(join10(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
25886
25903
  ]);
25887
25904
  let settings;
25888
25905
  try {
@@ -25939,7 +25956,7 @@ function geminiModelsUrl(baseUrl) {
25939
25956
  }
25940
25957
  async function readGeminiModelCatalog() {
25941
25958
  const fileEnvironment = parseEnvFile(
25942
- await readFile3(join9(geminiHome(), ".env"), "utf8").catch(() => "")
25959
+ await readFile3(join10(geminiHome(), ".env"), "utf8").catch(() => "")
25943
25960
  );
25944
25961
  const environment = { ...fileEnvironment, ...process.env };
25945
25962
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -25984,7 +26001,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
25984
26001
  return catalog;
25985
26002
  }
25986
26003
  async function readGrokModelCatalog() {
25987
- const config2 = await readFile3(join9(grokHome(), "config.toml"), "utf8").catch(() => "");
26004
+ const config2 = await readFile3(join10(grokHome(), "config.toml"), "utf8").catch(() => "");
25988
26005
  const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
25989
26006
  const catalog = parseGrokModelCatalog(output2, config2);
25990
26007
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -26003,7 +26020,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
26003
26020
  return catalog;
26004
26021
  }
26005
26022
  async function readOpencodeModelCatalog() {
26006
- const config2 = await readFile3(join9(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join9(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
26023
+ const config2 = await readFile3(join10(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join10(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
26007
26024
  const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
26008
26025
  const catalog = parseOpencodeModelCatalog(output2, config2);
26009
26026
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -26011,22 +26028,22 @@ async function readOpencodeModelCatalog() {
26011
26028
  }
26012
26029
  var TEN_MINUTES = 10 * 60 * 1e3;
26013
26030
  var MODEL_SOURCES = {
26014
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join9(claudeHome(), "settings.json")] },
26031
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join10(claudeHome(), "settings.json")] },
26015
26032
  codex: {
26016
26033
  read: readCodexModelCatalog,
26017
26034
  watchFiles: () => {
26018
26035
  const home = codexHome2();
26019
- return [join9(home, "config.toml"), join9(home, "models_cache.json")];
26036
+ return [join10(home, "config.toml"), join10(home, "models_cache.json")];
26020
26037
  },
26021
26038
  // model_catalog_json may point anywhere; a periodic re-read covers it.
26022
26039
  refreshEveryMs: TEN_MINUTES
26023
26040
  },
26024
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join9(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
26025
- grok: { read: readGrokModelCatalog, watchFiles: () => [join9(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
26026
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join9(kiroHome(), "settings", "cli.json")] },
26041
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join10(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
26042
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join10(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
26043
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join10(kiroHome(), "settings", "cli.json")] },
26027
26044
  opencode: {
26028
26045
  read: readOpencodeModelCatalog,
26029
- watchFiles: () => [join9(opencodeHome(), "opencode.json"), join9(opencodeHome(), "opencode.jsonc")],
26046
+ watchFiles: () => [join10(opencodeHome(), "opencode.json"), join10(opencodeHome(), "opencode.jsonc")],
26030
26047
  refreshEveryMs: TEN_MINUTES
26031
26048
  }
26032
26049
  };
@@ -26140,11 +26157,11 @@ function classifySpawnError(error62, context) {
26140
26157
 
26141
26158
  // src/providers/cli/kiro-session-log.ts
26142
26159
  import { open as open2, readdir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
26143
- import { homedir as homedir7 } from "node:os";
26144
- import { join as join10 } from "node:path";
26160
+ import { homedir as homedir8 } from "node:os";
26161
+ import { join as join11 } from "node:path";
26145
26162
  var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
26146
26163
  function kiroSessionsDirectory() {
26147
- return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join10(homedir7(), ".kiro", "sessions", "cli");
26164
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join11(homedir8(), ".kiro", "sessions", "cli");
26148
26165
  }
26149
26166
  var KiroSessionLog = class {
26150
26167
  constructor(options) {
@@ -26163,7 +26180,7 @@ var KiroSessionLog = class {
26163
26180
  /** Called before the CLI starts: a resumed log is followed from its current end. */
26164
26181
  async begin() {
26165
26182
  if (!this.options.sessionId) return;
26166
- this.path = join10(this.directory, `${this.options.sessionId}.jsonl`);
26183
+ this.path = join11(this.directory, `${this.options.sessionId}.jsonl`);
26167
26184
  this.offset = await stat2(this.path).then((info) => info.size, () => 0);
26168
26185
  }
26169
26186
  /**
@@ -26176,11 +26193,11 @@ var KiroSessionLog = class {
26176
26193
  const found = [];
26177
26194
  for (const name of names) {
26178
26195
  if (!name.endsWith(".json")) continue;
26179
- const meta3 = await readFile4(join10(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
26196
+ const meta3 = await readFile4(join11(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
26180
26197
  const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
26181
26198
  if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
26182
26199
  }
26183
- if (found.length === 1) this.path = join10(this.directory, `${found[0]}.jsonl`);
26200
+ if (found.length === 1) this.path = join11(this.directory, `${found[0]}.jsonl`);
26184
26201
  }
26185
26202
  /** Reads entries appended since the last call. */
26186
26203
  async refresh() {
@@ -26549,9 +26566,9 @@ var OPENCODE_ACP_DIALECT = {
26549
26566
  // src/acp/vendor.ts
26550
26567
  import { spawn as spawn6 } from "node:child_process";
26551
26568
  import { createHash } from "node:crypto";
26552
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
26569
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
26553
26570
  import { copyFile, mkdir as mkdir4, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
26554
- import { dirname as dirname6, join as join11, resolve as resolve4 } from "node:path";
26571
+ import { dirname as dirname6, join as join12, resolve as resolve4 } from "node:path";
26555
26572
  import { fileURLToPath } from "node:url";
26556
26573
  var AcpRuntimeUnavailable = class extends Error {
26557
26574
  constructor(message) {
@@ -26564,7 +26581,7 @@ function packageRoot() {
26564
26581
  let directory = dirname6(fileURLToPath(import.meta.url));
26565
26582
  while (true) {
26566
26583
  const path = resolve4(directory, "package.json");
26567
- if (existsSync4(path)) {
26584
+ if (existsSync5(path)) {
26568
26585
  try {
26569
26586
  if (JSON.parse(readFileSync4(path, "utf8")).name === "toc-ocra") return directory;
26570
26587
  } catch {
@@ -26584,21 +26601,21 @@ function agentPackageVersion() {
26584
26601
  const directory = agentRoot();
26585
26602
  if (!directory) return "0";
26586
26603
  try {
26587
- return JSON.parse(readFileSync4(join11(directory, "package.json"), "utf8")).version ?? "0";
26604
+ return JSON.parse(readFileSync4(join12(directory, "package.json"), "utf8")).version ?? "0";
26588
26605
  } catch {
26589
26606
  return "0";
26590
26607
  }
26591
26608
  }
26592
26609
  function vendoredAdapter(name) {
26593
26610
  const directory = agentRoot();
26594
- const entry = directory ? join11(directory, "assets", "acp", name, "index.mjs") : void 0;
26595
- return entry && existsSync4(entry) ? entry : void 0;
26611
+ const entry = directory ? join12(directory, "assets", "acp", name, "index.mjs") : void 0;
26612
+ return entry && existsSync5(entry) ? entry : void 0;
26596
26613
  }
26597
26614
  var installs = /* @__PURE__ */ new Map();
26598
26615
  function ensureClaudeRuntime(dataDir2) {
26599
26616
  const entry = vendoredAdapter("claude");
26600
26617
  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"));
26601
- const manifestPath = join11(dirname6(entry), "runtime.json");
26618
+ const manifestPath = join12(dirname6(entry), "runtime.json");
26602
26619
  let manifest;
26603
26620
  try {
26604
26621
  manifest = JSON.parse(readFileSync4(manifestPath, "utf8"));
@@ -26606,7 +26623,7 @@ function ensureClaudeRuntime(dataDir2) {
26606
26623
  return Promise.reject(new AcpRuntimeUnavailable("Claude ACP \u9002\u914D\u5668\u7F3A\u5C11 runtime.json"));
26607
26624
  }
26608
26625
  const hash2 = createHash("sha256").update(readFileSync4(entry)).digest("hex").slice(0, 12);
26609
- const directory = join11(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
26626
+ const directory = join12(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
26610
26627
  const existing = installs.get(directory);
26611
26628
  if (existing) return existing;
26612
26629
  const install = installClaudeRuntime(directory, entry, manifest).catch((error62) => {
@@ -26617,19 +26634,19 @@ function ensureClaudeRuntime(dataDir2) {
26617
26634
  return install;
26618
26635
  }
26619
26636
  async function installClaudeRuntime(directory, entry, manifest) {
26620
- const sdkPackage = join11(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
26621
- if (existsSync4(sdkPackage) && existsSync4(join11(directory, "index.mjs"))) return directory;
26637
+ const sdkPackage = join12(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
26638
+ if (existsSync5(sdkPackage) && existsSync5(join12(directory, "index.mjs"))) return directory;
26622
26639
  const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`;
26623
26640
  await mkdir4(temporary, { recursive: true, mode: 448 });
26624
26641
  try {
26625
- await writeFile4(join11(temporary, "package.json"), JSON.stringify({
26642
+ await writeFile4(join12(temporary, "package.json"), JSON.stringify({
26626
26643
  name: "toc-ocra-claude-acp-runtime",
26627
26644
  private: true,
26628
26645
  type: "module",
26629
26646
  dependencies: { [manifest.sdk.name]: manifest.sdk.version }
26630
26647
  }, null, 2));
26631
26648
  await runNpm(["install", "--omit=optional", "--no-audit", "--no-fund", "--no-package-lock", "--loglevel=error"], temporary);
26632
- await copyFile(entry, join11(temporary, "index.mjs"));
26649
+ await copyFile(entry, join12(temporary, "index.mjs"));
26633
26650
  await rm2(directory, { recursive: true, force: true });
26634
26651
  await rename4(temporary, directory);
26635
26652
  } catch (error62) {
@@ -26752,13 +26769,15 @@ var CLAUDE_LAUNCH_SPEC = {
26752
26769
  const executable = installedCli(claude);
26753
26770
  const runtime = await ensureClaudeRuntime(dataDir2);
26754
26771
  return {
26755
- launch: { executable: process.execPath, args: [join12(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
26772
+ launch: { executable: process.execPath, args: [join13(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
26756
26773
  fingerprint: `claude:${runtime}:${executable}`
26757
26774
  };
26758
26775
  },
26759
26776
  // Manual mode asks for every edit and command; the user or the level's policy answers.
26760
26777
  permissionModeConfig: { values: { ask: "default", acceptEdits: "acceptEdits", bypassPermissions: "bypassPermissions", plan: "plan" } },
26761
26778
  resumePreference: "resume",
26779
+ // The adapter accepts `session/resume` of a conversation Claude no longer has; only the prompt fails.
26780
+ resumable: (sessionId) => claudeSessionSaved(sessionId, providerEnvironment()),
26762
26781
  dialect: { failureRules: [{ kind: "sessionMissing", pattern: /No conversation found with session ID|session[^\n]{0,40}not found/i }] },
26763
26782
  modelDiscovery: { kind: "reader", source: MODEL_SOURCES.claude }
26764
26783
  };
@@ -26869,7 +26888,7 @@ var ACP_CHAT_IDS = [...ACP_CHAT.keys()];
26869
26888
  // src/acp/acp-model-catalog-probe.ts
26870
26889
  import { mkdtemp, rm as rm3 } from "node:fs/promises";
26871
26890
  import { tmpdir } from "node:os";
26872
- import { join as join13 } from "node:path";
26891
+ import { join as join14 } from "node:path";
26873
26892
 
26874
26893
  // src/acp/acp-options.ts
26875
26894
  var text = (value) => typeof value === "string" && value ? value : void 0;
@@ -27502,9 +27521,9 @@ async function readSessionModels(row, clientVersion = "1") {
27502
27521
  const discovery = row.modelDiscovery;
27503
27522
  if (discovery.kind !== "session") throw new Error(`${row.agent} does not list its models in a session`);
27504
27523
  const cli = requireCliSpec(row.agent);
27505
- const folder = await mkdtemp(join13(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
27524
+ const folder = await mkdtemp(join14(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
27506
27525
  try {
27507
- const folderArgs = discovery.sessionFolderArgs?.(join13(folder, "sessions")) ?? [];
27526
+ const folderArgs = discovery.sessionFolderArgs?.(join14(folder, "sessions")) ?? [];
27508
27527
  const args = [...row.args({ access: "read-only", model: "", reasoningEffort: "" }), ...folderArgs];
27509
27528
  const launch = launchCli({ spec: cli, args, env: { ...providerEnvironment(), ...row.env } });
27510
27529
  const connection = await AcpConnection.open({ executable: launch.executable, args: launch.args, env: launch.env, cwd: folder }, {
@@ -28133,14 +28152,14 @@ function isWriterConflict(message) {
28133
28152
  }
28134
28153
 
28135
28154
  // src/providers/cli/claude.ts
28136
- import { readdirSync as readdirSync3, readFileSync as readFileSync5 } from "node:fs";
28137
- import { homedir as homedir8 } from "node:os";
28138
- import { join as join14 } from "node:path";
28155
+ import { readdirSync as readdirSync4, readFileSync as readFileSync5 } from "node:fs";
28156
+ import { homedir as homedir9 } from "node:os";
28157
+ import { join as join15 } from "node:path";
28139
28158
  var CLAUDE = requireCliSpec("claude");
28140
28159
  function claudeProjectRoots() {
28141
28160
  const configured = process.env.CLAUDE_CONFIG_DIR;
28142
- const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join14(homedir8(), ".claude")];
28143
- return dirs.map((dir) => join14(dir, "projects"));
28161
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join15(homedir9(), ".claude")];
28162
+ return dirs.map((dir) => join15(dir, "projects"));
28144
28163
  }
28145
28164
  function claudeTranscriptExists(sessionId) {
28146
28165
  return claudeTranscriptPath(sessionId) !== void 0;
@@ -28150,13 +28169,13 @@ function claudeTranscriptPath(sessionId) {
28150
28169
  for (const root2 of claudeProjectRoots()) {
28151
28170
  let projects;
28152
28171
  try {
28153
- projects = readdirSync3(root2);
28172
+ projects = readdirSync4(root2);
28154
28173
  } catch {
28155
28174
  continue;
28156
28175
  }
28157
28176
  for (const project of projects) {
28158
28177
  try {
28159
- if (readdirSync3(join14(root2, project)).includes(file2)) return join14(root2, project, file2);
28178
+ if (readdirSync4(join15(root2, project)).includes(file2)) return join15(root2, project, file2);
28160
28179
  } catch {
28161
28180
  }
28162
28181
  }
@@ -28200,7 +28219,7 @@ var claudeProvider = {
28200
28219
  settings.disableAllHooks = true;
28201
28220
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*");
28202
28221
  try {
28203
- const userSettings = JSON.parse(readFileSync5(join14(homedir8(), ".claude", "settings.json"), "utf8"));
28222
+ const userSettings = JSON.parse(readFileSync5(join15(homedir9(), ".claude", "settings.json"), "utf8"));
28204
28223
  for (const [key, value] of Object.entries(userSettings.env ?? {})) {
28205
28224
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
28206
28225
  }
@@ -29371,12 +29390,12 @@ var cliDetection = new CliDetectionService();
29371
29390
  // src/smoke/cli-smoke.ts
29372
29391
  import { mkdtemp as mkdtemp2, realpath as realpath3, rm as rm5 } from "node:fs/promises";
29373
29392
  import { tmpdir as tmpdir3 } from "node:os";
29374
- import { join as join19 } from "node:path";
29393
+ import { join as join20 } from "node:path";
29375
29394
 
29376
29395
  // src/runs/run-supervisor.ts
29377
29396
  import { spawn as spawn11 } from "node:child_process";
29378
29397
  import { mkdir as mkdir7, realpath as realpath2, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
29379
- import { basename as basename2, isAbsolute as isAbsolute4, join as join18, relative as relative2, resolve as resolve5 } from "node:path";
29398
+ import { basename as basename2, isAbsolute as isAbsolute4, join as join19, relative as relative2, resolve as resolve5 } from "node:path";
29380
29399
  import { createInterface as createInterface6 } from "node:readline";
29381
29400
 
29382
29401
  // src/providers/chat/index.ts
@@ -29745,19 +29764,19 @@ async function forkCodexThread(options) {
29745
29764
 
29746
29765
  // src/runs/run-recorder.ts
29747
29766
  import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs";
29748
- import { homedir as homedir9 } from "node:os";
29749
- import { join as join15 } from "node:path";
29767
+ import { homedir as homedir10 } from "node:os";
29768
+ import { join as join16 } from "node:path";
29750
29769
  var RunRecorder = class _RunRecorder {
29751
29770
  constructor(path) {
29752
29771
  this.path = path;
29753
29772
  }
29754
29773
  path;
29755
- home = homedir9();
29774
+ home = homedir10();
29756
29775
  static fromEnvironment(runId, meta3) {
29757
29776
  const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
29758
29777
  if (!directory) return void 0;
29759
29778
  mkdirSync2(directory, { recursive: true });
29760
- const recorder = new _RunRecorder(join15(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
29779
+ const recorder = new _RunRecorder(join16(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
29761
29780
  recorder.write({ meta: meta3 });
29762
29781
  return recorder;
29763
29782
  }
@@ -29773,7 +29792,7 @@ var RunRecorder = class _RunRecorder {
29773
29792
 
29774
29793
  // src/runs/run-transcript.ts
29775
29794
  import { chmod as chmod4, mkdir as mkdir5, readdir as readdir2, readFile as readFile5, rename as rename5, stat as stat3, unlink, writeFile as writeFile5 } from "node:fs/promises";
29776
- import { join as join16 } from "node:path";
29795
+ import { join as join17 } from "node:path";
29777
29796
  var MAX_TRANSCRIPT_ITEMS = 5e3;
29778
29797
  var MAX_TRANSCRIPT_TEXT = 2e5;
29779
29798
  var MAX_TRANSCRIPT_LINES = 2e4;
@@ -30038,7 +30057,7 @@ function transcriptFileName(runId) {
30038
30057
  var TranscriptStore = class {
30039
30058
  constructor(dataDir2, logger, env = process.env) {
30040
30059
  this.logger = logger;
30041
- this.directory = dataDir2 ? join16(dataDir2, "transcripts") : "";
30060
+ this.directory = dataDir2 ? join17(dataDir2, "transcripts") : "";
30042
30061
  this.enabled = Boolean(dataDir2) && transcriptsOnDisk(env);
30043
30062
  }
30044
30063
  logger;
@@ -30093,7 +30112,7 @@ var TranscriptStore = class {
30093
30112
  await this.writes.get(runId);
30094
30113
  let text3;
30095
30114
  try {
30096
- text3 = await readFile5(join16(this.directory, name), "utf8");
30115
+ text3 = await readFile5(join17(this.directory, name), "utf8");
30097
30116
  } catch (error62) {
30098
30117
  if (errorCode(error62) !== "ENOENT") this.logger.warn("run-transcript-read-failed", { runId, error: errorMessage(error62) });
30099
30118
  return void 0;
@@ -30158,7 +30177,7 @@ var TranscriptStore = class {
30158
30177
  transcript.dirty = false;
30159
30178
  const body = JSON.stringify(transcript.toFile());
30160
30179
  await this.ensureDirectory();
30161
- const file2 = join16(this.directory, name);
30180
+ const file2 = join17(this.directory, name);
30162
30181
  const temporary = `${file2}.${process.pid}.tmp`;
30163
30182
  await writeFile5(temporary, body, { mode: 384 });
30164
30183
  await rename5(temporary, file2);
@@ -30195,7 +30214,7 @@ var TranscriptStore = class {
30195
30214
  const now = Date.now();
30196
30215
  const files = [];
30197
30216
  for (const name of names) {
30198
- const path = join16(this.directory, name);
30217
+ const path = join17(this.directory, name);
30199
30218
  if (name.endsWith(".tmp")) {
30200
30219
  const info2 = await stat3(path).catch(() => void 0);
30201
30220
  if (info2?.isFile() && now - info2.mtimeMs > STALE_TEMPORARY_MS) await unlink(path).catch(() => void 0);
@@ -30245,7 +30264,7 @@ function errorMessage(error62) {
30245
30264
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
30246
30265
  import { constants as constants2 } from "node:fs";
30247
30266
  import { lstat, mkdir as mkdir6, open as open3, realpath, rename as rename6, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
30248
- import { basename, isAbsolute as isAbsolute3, join as join17, relative } from "node:path";
30267
+ import { basename, isAbsolute as isAbsolute3, join as join18, relative } from "node:path";
30249
30268
  function within(root2, path) {
30250
30269
  const segment = relative(root2, path);
30251
30270
  return segment === "" || !segment.startsWith("..") && !isAbsolute3(segment);
@@ -30253,7 +30272,7 @@ function within(root2, path) {
30253
30272
  async function attachmentDirectory(workdir, messageId) {
30254
30273
  let directory = workdir;
30255
30274
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
30256
- directory = join17(directory, segment);
30275
+ directory = join18(directory, segment);
30257
30276
  await mkdir6(directory, { mode: 448 }).catch((error62) => {
30258
30277
  if (error62.code !== "EEXIST") throw error62;
30259
30278
  });
@@ -30261,7 +30280,7 @@ async function attachmentDirectory(workdir, messageId) {
30261
30280
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
30262
30281
  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");
30263
30282
  }
30264
- if (segment === ".echo") await writeFile6(join17(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
30283
+ if (segment === ".echo") await writeFile6(join18(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
30265
30284
  if (error62.code !== "EEXIST") throw error62;
30266
30285
  });
30267
30286
  }
@@ -30298,9 +30317,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
30298
30317
  const characters = Array.from(basename(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
30299
30318
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
30300
30319
  const name = characters.join("") || "attachment";
30301
- const path = join17(directory, `${file2.file_id}-${name}`);
30320
+ const path = join18(directory, `${file2.file_id}-${name}`);
30302
30321
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
30303
- const temporary = join17(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
30322
+ const temporary = join18(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
30304
30323
  try {
30305
30324
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
30306
30325
  signal2.throwIfAborted();
@@ -30700,6 +30719,7 @@ var QUESTION_OPTIONS = [
30700
30719
  { optionId: "answer", name: "Submit answers", kind: "allow_once" },
30701
30720
  { optionId: "cancel", name: "Cancel", kind: "reject_once" }
30702
30721
  ];
30722
+ var TURN_OUTPUT = /* @__PURE__ */ new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);
30703
30723
  var CANCEL_GRACE_MS = 1e4;
30704
30724
  var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
30705
30725
  var IMAGE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp" };
@@ -30732,14 +30752,15 @@ var AcpChatSession = class {
30732
30752
  this.clearIdle();
30733
30753
  this.lastUsedAt = Date.now();
30734
30754
  const transcript = new TurnTranscript((events) => sink.events(events), (rows) => sink.rows(rows));
30735
- 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() };
30755
+ 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 };
30736
30756
  this.turn = turn;
30737
30757
  for (const note of request.notes) transcript.note(note);
30738
30758
  let result;
30739
30759
  try {
30740
30760
  result = await this.execute(turn, launch);
30741
30761
  } catch (error62) {
30742
- result = this.failed(turn, this.classify(error62));
30762
+ const failure2 = this.classify(error62);
30763
+ result = this.startsFresh(turn, failure2) ? await this.runFresh(turn, launch) : this.failed(turn, failure2);
30743
30764
  } finally {
30744
30765
  if (turn.cancelTimer) clearTimeout(turn.cancelTimer);
30745
30766
  }
@@ -30758,6 +30779,28 @@ var AcpChatSession = class {
30758
30779
  this.scheduleIdle();
30759
30780
  return result;
30760
30781
  }
30782
+ /**
30783
+ * Whether a failed turn runs again in a new session: the saved session it
30784
+ * reopened turned out to be gone before the agent answered anything (Claude
30785
+ * Code accepts `session/resume` of a conversation it no longer has and fails
30786
+ * only at the prompt).
30787
+ */
30788
+ startsFresh(turn, failure2) {
30789
+ return Boolean(turn.reopened) && !turn.output && !turn.cancelRequested && failure2.kind === "sessionMissing";
30790
+ }
30791
+ async runFresh(turn, launch) {
30792
+ turn.transcript.note(`\u539F\u4F1A\u8BDD ${turn.reopened} \u5DF2\u65E0\u6CD5\u7EE7\u7EED\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD`);
30793
+ this.deps.logger.info("acp-session-missing-restart", { session: this.key, sessionId: turn.reopened });
30794
+ turn.request = { ...turn.request, sessionId: "" };
30795
+ turn.reopened = void 0;
30796
+ turn.phase = "starting";
30797
+ this.session = void 0;
30798
+ try {
30799
+ return await this.execute(turn, launch);
30800
+ } catch (error62) {
30801
+ return this.failed(turn, this.classify(error62));
30802
+ }
30803
+ }
30761
30804
  /** Stops the running turn: `session/cancel`, then the process if the agent does not stop. */
30762
30805
  cancel() {
30763
30806
  const turn = this.turn;
@@ -30943,6 +30986,7 @@ var AcpChatSession = class {
30943
30986
  transcript.note(`\u4F1A\u8BDD ${wanted} \u5DF2\u53D6\u6D88\u5F52\u6863`);
30944
30987
  this.session = await connection.openSaved(wanted, request.workdir, reopen);
30945
30988
  }
30989
+ turn.reopened = wanted;
30946
30990
  transcript.note(`\u7EE7\u7EED\u4F1A\u8BDD ${wanted}`);
30947
30991
  return this.session;
30948
30992
  } catch (error62) {
@@ -31016,6 +31060,7 @@ var AcpChatSession = class {
31016
31060
  const sessionLevel = kind === "available_commands_update" || kind === "current_mode_update" || kind === "config_option_update";
31017
31061
  if (this.session ? sessionId !== this.session.sessionId : !sessionLevel) return;
31018
31062
  if (turn.loading && !sessionLevel) return;
31063
+ if (typeof kind === "string" && TURN_OUTPUT.has(kind)) turn.output = true;
31019
31064
  const normalize = this.spec.dialect?.normalizeToolUpdate;
31020
31065
  turn.transcript.update(normalize && (kind === "tool_call" || kind === "tool_call_update") ? normalize(update2) : update2);
31021
31066
  }
@@ -32339,12 +32384,12 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
32339
32384
  async prepareChatAttachments(payload) {
32340
32385
  if (!payload.attachments?.length) return [];
32341
32386
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
32342
- const directory = join18(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
32387
+ const directory = join19(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
32343
32388
  await mkdir7(directory, { recursive: true, mode: 448 });
32344
32389
  const files = [];
32345
32390
  for (const attachment of payload.attachments) {
32346
32391
  const name = basename2(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
32347
- const path = join18(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
32392
+ const path = join19(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
32348
32393
  const existing = await stat5(path).catch(() => void 0);
32349
32394
  if (!existing?.isFile()) {
32350
32395
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
@@ -32545,7 +32590,7 @@ var silent = { debug() {
32545
32590
  async function runCliSmoke(options = {}) {
32546
32591
  const detection = await cliDetection.detect(true);
32547
32592
  const ids = options.only?.length ? options.only.map((id) => catalogEntry(id)?.id ?? id) : CLI_CATALOG.filter((entry) => entry.headless && detection.detectedIds.includes(entry.id)).map((entry) => entry.id);
32548
- const root2 = await realpath3(await mkdtemp2(join19(tmpdir3(), "toc-ocra-smoke-")));
32593
+ const root2 = await realpath3(await mkdtemp2(join20(tmpdir3(), "toc-ocra-smoke-")));
32549
32594
  const finished = /* @__PURE__ */ new Map();
32550
32595
  const config2 = { allowedRoots: [root2], maxConcurrentRuns: 0, maxRunSeconds: options.timeoutSeconds ?? 300, dataDir: root2 };
32551
32596
  const supervisor = new RunSupervisor(config2, silent, {
@@ -32617,7 +32662,7 @@ async function runCliSmoke(options = {}) {
32617
32662
  }
32618
32663
 
32619
32664
  // src/runtime/run-service.ts
32620
- import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
32665
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
32621
32666
  import { dirname as dirname10, resolve as resolve8 } from "node:path";
32622
32667
  import { fileURLToPath as fileURLToPath2 } from "node:url";
32623
32668
 
@@ -32860,7 +32905,7 @@ async function readJson(request) {
32860
32905
  import {
32861
32906
  appendFileSync as appendFileSync2,
32862
32907
  chmodSync,
32863
- existsSync as existsSync5,
32908
+ existsSync as existsSync6,
32864
32909
  mkdirSync as mkdirSync3,
32865
32910
  readFileSync as readFileSync6,
32866
32911
  renameSync,
@@ -32894,7 +32939,7 @@ function createDiagnosticLogger(filePath, options = {}) {
32894
32939
  try {
32895
32940
  mkdirSync3(dirname7(filePath), { recursive: true });
32896
32941
  pruneExpired();
32897
- currentBytes = existsSync5(filePath) ? statSync4(filePath).size : 0;
32942
+ currentBytes = existsSync6(filePath) ? statSync4(filePath).size : 0;
32898
32943
  } catch {
32899
32944
  disabled = true;
32900
32945
  }
@@ -32904,8 +32949,8 @@ function createDiagnosticLogger(filePath, options = {}) {
32904
32949
  for (let index = maxRotatedFiles; index >= 1; index -= 1) {
32905
32950
  const source = index === 1 ? filePath : `${filePath}.${index - 1}`;
32906
32951
  const destination = `${filePath}.${index}`;
32907
- if (!existsSync5(source)) continue;
32908
- if (existsSync5(destination)) unlinkSync(destination);
32952
+ if (!existsSync6(source)) continue;
32953
+ if (existsSync6(destination)) unlinkSync(destination);
32909
32954
  renameSync(source, destination);
32910
32955
  }
32911
32956
  currentBytes = 0;
@@ -32919,7 +32964,7 @@ function createDiagnosticLogger(filePath, options = {}) {
32919
32964
  try {
32920
32965
  for (let index = 0; index <= maxRotatedFiles; index += 1) {
32921
32966
  const path = index === 0 ? filePath : `${filePath}.${index}`;
32922
- if (!existsSync5(path)) continue;
32967
+ if (!existsSync6(path)) continue;
32923
32968
  const kept = readFileSync6(path, "utf8").split("\n").filter((line) => {
32924
32969
  if (!line.trim()) return false;
32925
32970
  try {
@@ -32980,7 +33025,7 @@ function createDiagnosticLogger(filePath, options = {}) {
32980
33025
 
32981
33026
  // src/runtime/agent-runtime.ts
32982
33027
  import { randomUUID as randomUUID4 } from "node:crypto";
32983
- import { join as join22 } from "node:path";
33028
+ import { join as join23 } from "node:path";
32984
33029
 
32985
33030
  // src/exec/script-runner.ts
32986
33031
  import { spawn as spawn12 } from "node:child_process";
@@ -33152,15 +33197,15 @@ async function readCLIQuotaReport(agentType) {
33152
33197
 
33153
33198
  // src/providers/tb-switch-control.ts
33154
33199
  import { readFile as readFile8 } from "node:fs/promises";
33155
- import { homedir as homedir10 } from "node:os";
33156
- import { join as join20 } from "node:path";
33200
+ import { homedir as homedir11 } from "node:os";
33201
+ import { join as join21 } from "node:path";
33157
33202
  function dataDir() {
33158
- return process.env.TB_SWITCH_HOME?.trim() || join20(homedir10(), ".tb-switch");
33203
+ return process.env.TB_SWITCH_HOME?.trim() || join21(homedir11(), ".tb-switch");
33159
33204
  }
33160
33205
  async function readLocalService() {
33161
33206
  let discovery;
33162
33207
  try {
33163
- discovery = JSON.parse(await readFile8(join20(dataDir(), "api.json"), "utf8"));
33208
+ discovery = JSON.parse(await readFile8(join21(dataDir(), "api.json"), "utf8"));
33164
33209
  } catch {
33165
33210
  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");
33166
33211
  }
@@ -33176,7 +33221,7 @@ async function readLocalService() {
33176
33221
  }
33177
33222
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
33178
33223
  try {
33179
- token = (await readFile8(join20(dataDir(), "api-token"), "utf8")).trim();
33224
+ token = (await readFile8(join21(dataDir(), "api-token"), "utf8")).trim();
33180
33225
  } catch {
33181
33226
  }
33182
33227
  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");
@@ -33448,11 +33493,11 @@ var GatewayClient = class {
33448
33493
 
33449
33494
  // src/workspace/directory-browser.ts
33450
33495
  import { mkdir as mkdir9, readdir as readdir3, realpath as realpath4, stat as stat7 } from "node:fs/promises";
33451
- import { homedir as homedir11 } from "node:os";
33496
+ import { homedir as homedir12 } from "node:os";
33452
33497
  import { dirname as dirname9, isAbsolute as isAbsolute5, parse as parse3, resolve as resolve6 } from "node:path";
33453
33498
  var MAX_ENTRIES = 1e3;
33454
33499
  async function listDirectory(requested, allowedRoots) {
33455
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir11()) || homedir11();
33500
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir12()) || homedir12();
33456
33501
  const directory = await realpath4(resolve6(raw)).catch(() => {
33457
33502
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
33458
33503
  });
@@ -33470,8 +33515,8 @@ async function listDirectory(requested, allowedRoots) {
33470
33515
  else if (entry.isFile()) files.push(item);
33471
33516
  }
33472
33517
  const parent = dirname9(directory);
33473
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir11() }];
33474
- for (const root2 of allowedRoots) if (root2 !== homedir11()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
33518
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir12() }];
33519
+ for (const root2 of allowedRoots) if (root2 !== homedir12()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
33475
33520
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
33476
33521
  return {
33477
33522
  path: directory,
@@ -33509,7 +33554,7 @@ async function createDirectory(parentRequested, name) {
33509
33554
  // src/workspace/workspace-manager.ts
33510
33555
  import { spawn as spawn13 } from "node:child_process";
33511
33556
  import { opendir, realpath as realpath5, stat as stat8 } from "node:fs/promises";
33512
- import { homedir as homedir12 } from "node:os";
33557
+ import { homedir as homedir13 } from "node:os";
33513
33558
  import { isAbsolute as isAbsolute6, relative as relative3, resolve as resolve7 } from "node:path";
33514
33559
  var MAX_NODES = 2e3;
33515
33560
  var MAX_DIRECTORY_ENTRIES = 12e3;
@@ -33545,7 +33590,7 @@ var WorkspaceManager = class {
33545
33590
  return { root_path: rootPath, nodes, truncated: nodes.length >= MAX_NODES, duration_ms: Date.now() - startedAt };
33546
33591
  }
33547
33592
  validateRootPath(value) {
33548
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir12());
33593
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir13());
33549
33594
  const root2 = resolve7(raw);
33550
33595
  if (!isAbsolute6(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
33551
33596
  if (relative3(root2, resolve7(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -33885,7 +33930,7 @@ var AgentRuntime = class {
33885
33930
  }
33886
33931
  };
33887
33932
  this.workspaces = new WorkspaceManager(config2, this.logger);
33888
- this.orphans = new OrphanRegistry(join22(config2.dataDir, "active-runs.json"));
33933
+ this.orphans = new OrphanRegistry(join23(config2.dataDir, "active-runs.json"));
33889
33934
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
33890
33935
  }
33891
33936
  config;
@@ -34595,7 +34640,7 @@ function agentPackageRoot() {
34595
34640
  let directory = dirname10(fileURLToPath2(import.meta.url));
34596
34641
  while (true) {
34597
34642
  const packagePath = resolve8(directory, "package.json");
34598
- if (existsSync6(packagePath)) {
34643
+ if (existsSync7(packagePath)) {
34599
34644
  try {
34600
34645
  const info = JSON.parse(readFileSync7(packagePath, "utf8"));
34601
34646
  if (info.name === PACKAGE_NAME && typeof info.version === "string") return directory;
@@ -34658,7 +34703,7 @@ async function runService(options = {}) {
34658
34703
  }
34659
34704
 
34660
34705
  // src/index.ts
34661
- var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join23(agentPackageRoot(), "scripts", "installation.cjs"));
34706
+ var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join24(agentPackageRoot(), "scripts", "installation.cjs"));
34662
34707
  async function run() {
34663
34708
  try {
34664
34709
  await runService();
@@ -34771,7 +34816,7 @@ async function setup(args) {
34771
34816
  }
34772
34817
  function manageService(action, args) {
34773
34818
  const script = resolve9(dirname11(fileURLToPath3(import.meta.url)), "../../scripts/service.mjs");
34774
- if (!existsSync7(script)) throw new Error(`service manager is missing: ${script}`);
34819
+ if (!existsSync8(script)) throw new Error(`service manager is missing: ${script}`);
34775
34820
  const result = spawnSync(process.execPath, [script, action, ...args], { stdio: "inherit", shell: false });
34776
34821
  if (result.error) throw result.error;
34777
34822
  if (result.status !== 0) {
@@ -34785,7 +34830,7 @@ async function update(args) {
34785
34830
  if (customConfig) process.env.TOC_OCRA_CONFIG = resolve9(customConfig);
34786
34831
  await ensureIdle();
34787
34832
  const npmPath = resolveCliCommand("npm");
34788
- const temporary = mkdtempSync(join23(tmpdir4(), "toc-ocra-update-"));
34833
+ const temporary = mkdtempSync(join24(tmpdir4(), "toc-ocra-update-"));
34789
34834
  try {
34790
34835
  const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
34791
34836
  if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -34812,7 +34857,7 @@ async function update(args) {
34812
34857
  }
34813
34858
  const archive = Buffer.concat(chunks);
34814
34859
  if (`sha512-${createHash5("sha512").update(archive).digest("base64")}` !== dist.integrity) throw new Error("\u8BBE\u5907\u4EE3\u7406\u5B89\u88C5\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u5347\u7EA7");
34815
- const archivePath = join23(temporary, "toc-ocra.tgz");
34860
+ const archivePath = join24(temporary, "toc-ocra.tgz");
34816
34861
  writeFileSync3(archivePath, archive, { mode: 384 });
34817
34862
  const npm = directLaunch2(npmPath, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath]);
34818
34863
  const install = spawnSync(npm.executable, npm.args, { stdio: "inherit", shell: false, windowsHide: true });
@@ -34822,7 +34867,7 @@ async function update(args) {
34822
34867
  return;
34823
34868
  }
34824
34869
  const previousVersion = agentVersion();
34825
- const current = await installShared(join23(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync7(defaultConfigPath()) });
34870
+ const current = await installShared(join24(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync8(defaultConfigPath()) });
34826
34871
  if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
34827
34872
  `);
34828
34873
  else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
@@ -34850,7 +34895,7 @@ async function main() {
34850
34895
  const selected = !shared || compareVersions2(agentVersion(), shared.version) > 0 ? await installShared(root2) : shared;
34851
34896
  const same = (a, b) => process.platform === "win32" ? resolve9(a).toLowerCase() === resolve9(b).toLowerCase() : resolve9(a) === resolve9(b);
34852
34897
  if (!same(selected.root, root2)) {
34853
- await import(pathToFileURL2(join23(selected.root, "dist", "cli", "cli.mjs")).href);
34898
+ await import(pathToFileURL2(join24(selected.root, "dist", "cli", "cli.mjs")).href);
34854
34899
  return;
34855
34900
  }
34856
34901
  }