toc-ocra 0.3.21 → 0.3.22

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
@@ -185,9 +185,9 @@ var require_bit_buffer = __commonJS({
185
185
  const bufIndex = Math.floor(index / 8);
186
186
  return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1;
187
187
  },
188
- put: function(num, length) {
188
+ put: function(num2, length) {
189
189
  for (let i = 0; i < length; i++) {
190
- this.putBit((num >>> length - i - 1 & 1) === 1);
190
+ this.putBit((num2 >>> length - i - 1 & 1) === 1);
191
191
  }
192
192
  },
193
193
  getLengthInBits: function() {
@@ -920,14 +920,14 @@ var require_regex = __commonJS({
920
920
  var TEST_KANJI = new RegExp("^" + kanji + "$");
921
921
  var TEST_NUMERIC = new RegExp("^" + numeric + "$");
922
922
  var TEST_ALPHANUMERIC = new RegExp("^[A-Z0-9 $%*+\\-./:]+$");
923
- exports.testKanji = function testKanji(str2) {
924
- return TEST_KANJI.test(str2);
923
+ exports.testKanji = function testKanji(str3) {
924
+ return TEST_KANJI.test(str3);
925
925
  };
926
- exports.testNumeric = function testNumeric(str2) {
927
- return TEST_NUMERIC.test(str2);
926
+ exports.testNumeric = function testNumeric(str3) {
927
+ return TEST_NUMERIC.test(str3);
928
928
  };
929
- exports.testAlphanumeric = function testAlphanumeric(str2) {
930
- return TEST_ALPHANUMERIC.test(str2);
929
+ exports.testAlphanumeric = function testAlphanumeric(str3) {
930
+ return TEST_ALPHANUMERIC.test(str3);
931
931
  };
932
932
  }
933
933
  });
@@ -1421,13 +1421,13 @@ var require_segments = __commonJS({
1421
1421
  var Regex = require_regex();
1422
1422
  var Utils = require_utils();
1423
1423
  var dijkstra = require_dijkstra();
1424
- function getStringByteLength(str2) {
1425
- return unescape(encodeURIComponent(str2)).length;
1424
+ function getStringByteLength(str3) {
1425
+ return unescape(encodeURIComponent(str3)).length;
1426
1426
  }
1427
- function getSegments(regex, mode, str2) {
1427
+ function getSegments(regex, mode, str3) {
1428
1428
  const segments = [];
1429
1429
  let result;
1430
- while ((result = regex.exec(str2)) !== null) {
1430
+ while ((result = regex.exec(str3)) !== null) {
1431
1431
  segments.push({
1432
1432
  data: result[0],
1433
1433
  index: result.index,
@@ -4253,13 +4253,13 @@ var require_svg_tag = __commonJS({
4253
4253
  var Utils = require_utils2();
4254
4254
  function getColorAttrib(color, attrib) {
4255
4255
  const alpha = color.a / 255;
4256
- const str2 = attrib + '="' + color.hex + '"';
4257
- return alpha < 1 ? str2 + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str2;
4256
+ const str3 = attrib + '="' + color.hex + '"';
4257
+ return alpha < 1 ? str3 + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str3;
4258
4258
  }
4259
4259
  function svgCmd(cmd, x, y) {
4260
- let str2 = cmd + x;
4261
- if (typeof y !== "undefined") str2 += " " + y;
4262
- return str2;
4260
+ let str3 = cmd + x;
4261
+ if (typeof y !== "undefined") str3 += " " + y;
4262
+ return str3;
4263
4263
  }
4264
4264
  function qrToPath(data, size, margin) {
4265
4265
  let path = "";
@@ -4579,7 +4579,7 @@ import { createHash as createHash5 } from "node:crypto";
4579
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 join25, resolve as resolve9 } from "node:path";
4582
+ import { dirname as dirname11, join as join26, 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
@@ -5424,14 +5424,14 @@ function promiseAllObject(promisesObj) {
5424
5424
  }
5425
5425
  function randomString(length = 10) {
5426
5426
  const chars = "abcdefghijklmnopqrstuvwxyz";
5427
- let str2 = "";
5427
+ let str3 = "";
5428
5428
  for (let i = 0; i < length; i++) {
5429
- str2 += chars[Math.floor(Math.random() * chars.length)];
5429
+ str3 += chars[Math.floor(Math.random() * chars.length)];
5430
5430
  }
5431
- return str2;
5431
+ return str3;
5432
5432
  }
5433
- function esc(str2) {
5434
- return JSON.stringify(str2);
5433
+ function esc(str3) {
5434
+ return JSON.stringify(str3);
5435
5435
  }
5436
5436
  function slugify(input2) {
5437
5437
  return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
@@ -5545,8 +5545,8 @@ var primitiveTypes = /* @__PURE__ */ new Set([
5545
5545
  "symbol",
5546
5546
  "undefined"
5547
5547
  ]);
5548
- function escapeRegex(str2) {
5549
- return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5548
+ function escapeRegex(str3) {
5549
+ return str3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5550
5550
  }
5551
5551
  function clone(inst, def, params) {
5552
5552
  const cl = new inst._zod.constr(def ?? inst._zod.def);
@@ -5812,13 +5812,13 @@ function getSizableOrigin(input2) {
5812
5812
  return "unknown";
5813
5813
  }
5814
5814
  var highSurrogate = /[\uD800-\uDBFF]/;
5815
- function codePointLength(str2) {
5816
- const units = str2.length;
5817
- if (!highSurrogate.test(str2))
5815
+ function codePointLength(str3) {
5816
+ const units = str3.length;
5817
+ if (!highSurrogate.test(str3))
5818
5818
  return units;
5819
5819
  let count2 = units;
5820
5820
  for (let i = 0; i < units - 1; i++) {
5821
- if ((str2.charCodeAt(i) & 64512) === 55296 && (str2.charCodeAt(i + 1) & 64512) === 56320) {
5821
+ if ((str3.charCodeAt(i) & 64512) === 55296 && (str3.charCodeAt(i + 1) & 64512) === 56320) {
5822
5822
  count2--;
5823
5823
  i++;
5824
5824
  }
@@ -24694,7 +24694,7 @@ Echo \u8D26\u53F7 ${who} \u786E\u8BA4\u5C06\u8FD9\u53F0\u7535\u8111\u6DFB\u52A0\
24694
24694
  }
24695
24695
 
24696
24696
  // src/providers/detection.ts
24697
- import { spawn as spawn9 } from "node:child_process";
24697
+ import { spawn as spawn10 } from "node:child_process";
24698
24698
 
24699
24699
  // src/runtime/cli/hydrate-shell-path.ts
24700
24700
  import { delimiter as delimiter3 } from "node:path";
@@ -25144,6 +25144,7 @@ var SOURCES = [
25144
25144
  { id: "claude", label: "Claude Code", aliases: ["claude-code"], command: "claude", commandAliases: ["claude-code"], versionArguments: ["--version"], promptStdin: "omit", restrictedPermission: true, installHint: "npm i -g @anthropic-ai/claude-code" },
25145
25145
  { id: "grok", label: "Grok CLI", command: "grok", versionArguments: ["--version"] },
25146
25146
  { id: "gemini", label: "Gemini CLI", command: "gemini", versionArguments: ["--version"], restrictedPermission: true, installHint: "npm i -g @google/gemini-cli" },
25147
+ { id: "antigravity", label: "Antigravity", aliases: ["agy"], command: "agy", versionArguments: ["--version"], restrictedPermission: true, installHint: "https://antigravity.google/cli" },
25147
25148
  { id: "opencode", label: "OpenCode", command: "opencode", versionArguments: ["--version"], installHint: "npm i -g opencode-ai" },
25148
25149
  { id: "kiro", label: "Kiro CLI", aliases: ["kiro-cli"], command: "kiro-cli", commandAliases: ["kiro"], versionArguments: ["--version"], promptStdin: "omit", restrictedPermission: true },
25149
25150
  { id: "omp", label: "OMP", command: "omp", versionArguments: ["--version"] },
@@ -25374,7 +25375,7 @@ function textRows(prefix, text3, maxRows = 40) {
25374
25375
 
25375
25376
  // src/acp/acp-launch-specs.ts
25376
25377
  import { realpathSync as realpathSync2 } from "node:fs";
25377
- import { join as join13 } from "node:path";
25378
+ import { join as join14 } from "node:path";
25378
25379
 
25379
25380
  // src/providers/claude-sessions.ts
25380
25381
  import { existsSync as existsSync4, readdirSync as readdirSync3 } from "node:fs";
@@ -25536,8 +25537,8 @@ function codexCatalogArgs() {
25536
25537
  // src/providers/model-catalog.ts
25537
25538
  import { spawn as spawn5 } from "node:child_process";
25538
25539
  import { readdir, readFile as readFile3 } from "node:fs/promises";
25539
- import { homedir as homedir7 } from "node:os";
25540
- import { isAbsolute as isAbsolute2, join as join10, resolve as resolve3 } from "node:path";
25540
+ import { homedir as homedir8 } from "node:os";
25541
+ import { isAbsolute as isAbsolute2, join as join11, resolve as resolve3 } from "node:path";
25541
25542
 
25542
25543
  // src/providers/kiro-auth.ts
25543
25544
  import { execFile as execFile3 } from "node:child_process";
@@ -25657,6 +25658,116 @@ async function readKiroNativeModels(launch, cwd, options = {}) {
25657
25658
  }
25658
25659
  }
25659
25660
 
25661
+ // src/acp/acp-dialects/antigravity-dialect.ts
25662
+ import { readFileSync as readFileSync4 } from "node:fs";
25663
+ import { homedir as homedir7 } from "node:os";
25664
+ import { join as join10 } from "node:path";
25665
+
25666
+ // src/acp/acp-dialects/acp-dialect.ts
25667
+ var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
25668
+
25669
+ // src/acp/acp-dialects/antigravity-dialect.ts
25670
+ var str2 = (value) => typeof value === "string" && value ? value : void 0;
25671
+ var num = (value) => typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
25672
+ var ANTIGRAVITY_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
25673
+ var ANTIGRAVITY_LEVEL_SUFFIX = /^(.+)-(low|medium|high|xhigh|max)$/;
25674
+ var CLOUD_CODE_PREFIX = /^Cloud Code Assist API error \(\d{3}\):\s*/;
25675
+ var EXECUTOR_API_ERROR = /^(\u26a0 agent executor error: [^\n]*?Error (\d{3}), Message: ([^\n]*?)), Status: ([A-Z_]+)(?:, Details: ([^\n]*))?$/;
25676
+ var ANTIGRAVITY_FAILURE_RULES = [
25677
+ {
25678
+ kind: "notSignedIn",
25679
+ pattern: /not logged into antigravity|not logged in|not signed in|not authenticated|unauthenticated|authentication required|run agy login|please sign in|api key not valid/i
25680
+ },
25681
+ {
25682
+ kind: "rateLimited",
25683
+ pattern: /resource_exhausted|quota exceeded|rate limit|too many requests|429/i
25684
+ },
25685
+ {
25686
+ kind: "sessionMissing",
25687
+ pattern: /session not found|failed to rebuild agent:/i
25688
+ }
25689
+ ];
25690
+ function antigravityUsesApiKeyProvider(homePath = homedir7()) {
25691
+ try {
25692
+ const raw = readFileSync4(join10(homePath, ".gemini", "antigravity-cli", "settings.json"), "utf8");
25693
+ const parsed = JSON.parse(raw);
25694
+ return Boolean(record2(parsed).modelProvider);
25695
+ } catch {
25696
+ return false;
25697
+ }
25698
+ }
25699
+ function scrubAntigravityEnv(env, homePath = homedir7()) {
25700
+ const next = { ...env };
25701
+ if (!antigravityUsesApiKeyProvider(homePath)) {
25702
+ for (const key of Object.keys(next)) {
25703
+ const normalized = process.platform === "win32" ? key.toUpperCase() : key;
25704
+ if (normalized === "GEMINI_API_KEY" || normalized === "GOOGLE_API_KEY") {
25705
+ delete next[key];
25706
+ }
25707
+ }
25708
+ }
25709
+ if (process.platform === "win32") {
25710
+ for (const key of Object.keys(next)) {
25711
+ if (key.toUpperCase() === "AGY_CLI_DISABLE_AUTO_UPDATE" && key !== "AGY_CLI_DISABLE_AUTO_UPDATE") {
25712
+ delete next[key];
25713
+ }
25714
+ }
25715
+ }
25716
+ next.AGY_CLI_DISABLE_AUTO_UPDATE = "true";
25717
+ return next;
25718
+ }
25719
+ function errorText(error62) {
25720
+ if (typeof error62.data === "string" && error62.data.trim()) return error62.data.trim();
25721
+ const nested = record2(error62.data);
25722
+ const nestedMsg = str2(nested.message) ?? str2(nested.details) ?? str2(nested.error);
25723
+ return nestedMsg ?? error62.message ?? "";
25724
+ }
25725
+ function promptErrorDetail(error62) {
25726
+ const text3 = errorText(error62);
25727
+ if (!text3) return void 0;
25728
+ const prefix = CLOUD_CODE_PREFIX.exec(text3);
25729
+ if (prefix) {
25730
+ try {
25731
+ const parsed = record2(JSON.parse(text3.slice(prefix[0].length)));
25732
+ const msg = str2(record2(parsed.error).message)?.trim();
25733
+ if (msg) return msg;
25734
+ } catch {
25735
+ }
25736
+ }
25737
+ const execMatch = EXECUTOR_API_ERROR.exec(text3);
25738
+ if (execMatch) {
25739
+ const [, , code2, rawMessage, status] = execMatch;
25740
+ const message = rawMessage?.trim();
25741
+ return message || `Google returned error ${code2} (${status}).`;
25742
+ }
25743
+ return void 0;
25744
+ }
25745
+ function normalizeToolUpdate(update2) {
25746
+ const input2 = record2(update2.rawInput);
25747
+ const output2 = record2(update2.rawOutput);
25748
+ const command = str2(input2.CommandLine) ?? str2(input2.command_line) ?? str2(input2.commandLine);
25749
+ const cwd = str2(input2.Cwd) ?? str2(input2.WorkingDirectory) ?? str2(input2.working_dir) ?? str2(input2.workingDir) ?? str2(input2.cwd);
25750
+ const stdout = str2(output2.combinedOutput) ?? str2(output2.combined_output);
25751
+ const exitCode = num(output2.exitCode) ?? num(output2.exit_code);
25752
+ return {
25753
+ ...update2,
25754
+ ...command === void 0 ? {} : { rawInput: { command, ...cwd === void 0 ? {} : { cwd } } },
25755
+ ...stdout === void 0 && exitCode === void 0 ? {} : {
25756
+ rawOutput: {
25757
+ ...stdout === void 0 ? {} : { stdout },
25758
+ ...exitCode === void 0 ? {} : { exitCode }
25759
+ }
25760
+ }
25761
+ };
25762
+ }
25763
+ var ANTIGRAVITY_ACP_DIALECT = {
25764
+ failureRules: ANTIGRAVITY_FAILURE_RULES,
25765
+ failureKind: ({ code: code2 }) => code2 === 401 ? "notSignedIn" : code2 === 429 ? "rateLimited" : void 0,
25766
+ promptErrorDetail,
25767
+ normalizeToolUpdate,
25768
+ toolName: (update2) => update2.kind === "execute" ? "execute" : void 0
25769
+ };
25770
+
25660
25771
  // src/providers/model-catalog.ts
25661
25772
  function stringValue(value) {
25662
25773
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
@@ -25745,15 +25856,16 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
25745
25856
  models: [...models2.values()]
25746
25857
  };
25747
25858
  }
25748
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join10(homedir7(), ".claude");
25749
- var codexHome2 = () => process.env.CODEX_HOME?.trim() || join10(homedir7(), ".codex");
25750
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join10(homedir7(), ".gemini");
25751
- var grokHome = () => process.env.GROK_HOME?.trim() || join10(homedir7(), ".grok");
25752
- var opencodeHome = () => join10(process.env.XDG_CONFIG_HOME?.trim() || join10(homedir7(), ".config"), "opencode");
25753
- var kiroHome = () => join10(homedir7(), ".kiro");
25859
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join11(homedir8(), ".claude");
25860
+ var codexHome2 = () => process.env.CODEX_HOME?.trim() || join11(homedir8(), ".codex");
25861
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join11(homedir8(), ".gemini");
25862
+ var antigravityHome = () => join11(homedir8(), ".gemini", "antigravity-cli");
25863
+ var grokHome = () => process.env.GROK_HOME?.trim() || join11(homedir8(), ".grok");
25864
+ var opencodeHome = () => join11(process.env.XDG_CONFIG_HOME?.trim() || join11(homedir8(), ".config"), "opencode");
25865
+ var kiroHome = () => join11(homedir8(), ".kiro");
25754
25866
  async function readClaudeModelCatalog() {
25755
25867
  const home = claudeHome();
25756
- const content = await readFile3(join10(home, "settings.json"), "utf8").catch(() => "");
25868
+ const content = await readFile3(join11(home, "settings.json"), "utf8").catch(() => "");
25757
25869
  let settings = {};
25758
25870
  if (content) {
25759
25871
  try {
@@ -25765,13 +25877,13 @@ async function readClaudeModelCatalog() {
25765
25877
  return parseClaudeModelCatalog(settings, process.env, (/* @__PURE__ */ new Date()).toISOString(), await readClaudeCachedModels(home));
25766
25878
  }
25767
25879
  async function readClaudeCachedModels(home) {
25768
- const dir = join10(home, "cache", "model-catalog");
25880
+ const dir = join11(home, "cache", "model-catalog");
25769
25881
  const names = await readdir(dir).catch(() => []);
25770
25882
  let newest;
25771
25883
  for (const name of names) {
25772
25884
  if (!name.endsWith(".json")) continue;
25773
25885
  try {
25774
- const cache = JSON.parse(await readFile3(join10(dir, name), "utf8"));
25886
+ const cache = JSON.parse(await readFile3(join11(dir, name), "utf8"));
25775
25887
  const models2 = parseClaudeCachedModels(cache);
25776
25888
  const fetchedAt = Number(objectValue(cache).fetchedAt) || 0;
25777
25889
  if (models2.length && (!newest || fetchedAt > newest.fetchedAt)) newest = { fetchedAt, models: models2 };
@@ -25827,13 +25939,13 @@ async function readCodexModels(codexHome3, config2) {
25827
25939
  const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
25828
25940
  if (configuredModels?.length) return configuredModels;
25829
25941
  }
25830
- const cached3 = parseCodexModels(await readFile3(join10(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25942
+ const cached3 = parseCodexModels(await readFile3(join11(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25831
25943
  if (cached3?.length) return cached3;
25832
25944
  return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
25833
25945
  }
25834
25946
  async function readCodexModelCatalog() {
25835
25947
  const home = codexHome2();
25836
- const config2 = await readFile3(join10(home, "config.toml"), "utf8").catch(() => "");
25948
+ const config2 = await readFile3(join11(home, "config.toml"), "utf8").catch(() => "");
25837
25949
  const models2 = await readCodexModels(home, config2);
25838
25950
  const defaultModel = configValue(config2, "model");
25839
25951
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -25947,7 +26059,7 @@ async function readKiroModelCatalog(options = {}) {
25947
26059
  if (current) return known.catalog;
25948
26060
  try {
25949
26061
  const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
25950
- const catalog = await readKiroNativeModels(launch, homedir7(), { catalog: base });
26062
+ const catalog = await readKiroNativeModels(launch, homedir8(), { catalog: base });
25951
26063
  kiroEfforts = { signature, readAt: Date.now(), catalog };
25952
26064
  return catalog;
25953
26065
  } catch {
@@ -25956,7 +26068,7 @@ async function readKiroModelCatalog(options = {}) {
25956
26068
  };
25957
26069
  const [payload, content] = await Promise.all([
25958
26070
  readEfforts(),
25959
- readFile3(join10(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
26071
+ readFile3(join11(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
25960
26072
  ]);
25961
26073
  let settings;
25962
26074
  try {
@@ -26013,7 +26125,7 @@ function geminiModelsUrl(baseUrl) {
26013
26125
  }
26014
26126
  async function readGeminiModelCatalog() {
26015
26127
  const fileEnvironment = parseEnvFile(
26016
- await readFile3(join10(geminiHome(), ".env"), "utf8").catch(() => "")
26128
+ await readFile3(join11(geminiHome(), ".env"), "utf8").catch(() => "")
26017
26129
  );
26018
26130
  const environment = { ...fileEnvironment, ...process.env };
26019
26131
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -26058,7 +26170,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
26058
26170
  return catalog;
26059
26171
  }
26060
26172
  async function readGrokModelCatalog() {
26061
- const config2 = await readFile3(join10(grokHome(), "config.toml"), "utf8").catch(() => "");
26173
+ const config2 = await readFile3(join11(grokHome(), "config.toml"), "utf8").catch(() => "");
26062
26174
  const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
26063
26175
  const catalog = parseGrokModelCatalog(output2, config2);
26064
26176
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -26077,30 +26189,139 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
26077
26189
  return catalog;
26078
26190
  }
26079
26191
  async function readOpencodeModelCatalog() {
26080
- const config2 = await readFile3(join10(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join10(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
26192
+ const config2 = await readFile3(join11(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join11(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
26081
26193
  const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
26082
26194
  const catalog = parseOpencodeModelCatalog(output2, config2);
26083
26195
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
26084
26196
  return catalog;
26085
26197
  }
26198
+ function parseAntigravityModelCatalog(output2, settingsContent = "", fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
26199
+ const plain = output2.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "");
26200
+ const variants = [];
26201
+ const seenIds = /* @__PURE__ */ new Set();
26202
+ for (const line of plain.split(/\r?\n/)) {
26203
+ const parts = line.split(" ").map((field) => field.trim());
26204
+ const [modelId, name, ...extra] = parts;
26205
+ if (!modelId || !name || extra.length > 0 || seenIds.has(modelId)) continue;
26206
+ seenIds.add(modelId);
26207
+ variants.push({ modelId, name });
26208
+ }
26209
+ const familyLevels = /* @__PURE__ */ new Map();
26210
+ for (const variant of variants) {
26211
+ const match = ANTIGRAVITY_LEVEL_SUFFIX.exec(variant.modelId);
26212
+ const family = match?.[1];
26213
+ const level = match?.[2];
26214
+ if (!family || !level || seenIds.has(family)) continue;
26215
+ const list = familyLevels.get(family) ?? [];
26216
+ if (!list.includes(level)) list.push(level);
26217
+ familyLevels.set(family, list);
26218
+ }
26219
+ const models2 = [];
26220
+ const addedFamilies = /* @__PURE__ */ new Set();
26221
+ for (const variant of variants) {
26222
+ const match = ANTIGRAVITY_LEVEL_SUFFIX.exec(variant.modelId);
26223
+ const family = match?.[1];
26224
+ const levels = family ? familyLevels.get(family) : void 0;
26225
+ if (family && levels && levels.length > 1) {
26226
+ if (addedFamilies.has(family)) continue;
26227
+ addedFamilies.add(family);
26228
+ const ordered = ANTIGRAVITY_EFFORT_LEVELS.filter((level) => levels.includes(level));
26229
+ const firstLevel = levels[0];
26230
+ models2.push({
26231
+ id: family,
26232
+ name: variant.name.replace(/\s*\([^()]+\)$/, ""),
26233
+ supported_reasoning_efforts: [...ordered],
26234
+ ...firstLevel && ordered.includes(firstLevel) ? { default_reasoning_effort: firstLevel } : {}
26235
+ });
26236
+ } else {
26237
+ models2.push({
26238
+ id: variant.modelId,
26239
+ name: variant.name,
26240
+ supported_reasoning_efforts: []
26241
+ });
26242
+ }
26243
+ }
26244
+ let configuredModel;
26245
+ if (settingsContent.trim()) {
26246
+ try {
26247
+ configuredModel = stringValue(objectValue(JSON.parse(settingsContent)).model);
26248
+ } catch {
26249
+ }
26250
+ }
26251
+ let defaultModel;
26252
+ let defaultEffort;
26253
+ if (configuredModel) {
26254
+ const matchedVariant = variants.find(
26255
+ (variant) => variant.modelId === configuredModel || variant.name.toLowerCase() === configuredModel.toLowerCase()
26256
+ );
26257
+ if (matchedVariant) {
26258
+ const match = ANTIGRAVITY_LEVEL_SUFFIX.exec(matchedVariant.modelId);
26259
+ const family = match?.[1];
26260
+ const level = match?.[2];
26261
+ if (family && addedFamilies.has(family)) {
26262
+ defaultModel = family;
26263
+ defaultEffort = level;
26264
+ } else {
26265
+ defaultModel = matchedVariant.modelId;
26266
+ }
26267
+ } else {
26268
+ const matchedFamily = models2.find(
26269
+ (model) => model.id === configuredModel || model.name.toLowerCase() === configuredModel.toLowerCase()
26270
+ );
26271
+ if (matchedFamily) {
26272
+ defaultModel = matchedFamily.id;
26273
+ defaultEffort = matchedFamily.default_reasoning_effort;
26274
+ }
26275
+ }
26276
+ }
26277
+ if (!defaultModel && models2.length > 0) {
26278
+ defaultModel = models2[0].id;
26279
+ defaultEffort = models2[0].default_reasoning_effort;
26280
+ }
26281
+ return {
26282
+ agent_type: "antigravity",
26283
+ fetched_at: fetchedAt,
26284
+ ...defaultModel ? { default_model: defaultModel } : {},
26285
+ ...defaultEffort ? { default_reasoning_effort: defaultEffort } : {},
26286
+ models: models2
26287
+ };
26288
+ }
26289
+ async function readAntigravityModelCatalog() {
26290
+ const baseEnv = mergeShellProxyEnvironment(await hydrateShellPath(), providerEnvironment());
26291
+ const env = scrubAntigravityEnv(baseEnv);
26292
+ const spec = requireCliSpec("antigravity");
26293
+ const launch = launchCli({ spec, args: ["models"], env });
26294
+ const [output2, settings] = await Promise.all([
26295
+ runModelListCommand(launch.executable, launch.args, "agy", launch.env ?? env),
26296
+ readFile3(join11(antigravityHome(), "settings.json"), "utf8").catch(() => "")
26297
+ ]);
26298
+ const catalog = parseAntigravityModelCatalog(output2, settings);
26299
+ if (catalog.models.length === 0) throw new Error("Antigravity \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u767B\u5F55 agy");
26300
+ return catalog;
26301
+ }
26086
26302
  var TEN_MINUTES = 10 * 60 * 1e3;
26087
26303
  var MODEL_SOURCES = {
26088
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join10(claudeHome(), "settings.json"), join10(claudeHome(), "cache", "model-catalog")] },
26304
+ antigravity: {
26305
+ read: readAntigravityModelCatalog,
26306
+ watchFiles: () => [join11(antigravityHome(), "settings.json")],
26307
+ refreshEveryMs: TEN_MINUTES
26308
+ },
26309
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join11(claudeHome(), "settings.json"), join11(claudeHome(), "cache", "model-catalog")] },
26089
26310
  codex: {
26090
26311
  read: readCodexModelCatalog,
26091
26312
  watchFiles: () => {
26092
26313
  const home = codexHome2();
26093
- return [join10(home, "config.toml"), join10(home, "models_cache.json")];
26314
+ return [join11(home, "config.toml"), join11(home, "models_cache.json")];
26094
26315
  },
26095
26316
  // model_catalog_json may point anywhere; a periodic re-read covers it.
26096
26317
  refreshEveryMs: TEN_MINUTES
26097
26318
  },
26098
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join10(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
26099
- grok: { read: readGrokModelCatalog, watchFiles: () => [join10(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
26100
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join10(kiroHome(), "settings", "cli.json")] },
26319
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join11(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
26320
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join11(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
26321
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join11(kiroHome(), "settings", "cli.json")] },
26101
26322
  opencode: {
26102
26323
  read: readOpencodeModelCatalog,
26103
- watchFiles: () => [join10(opencodeHome(), "opencode.json"), join10(opencodeHome(), "opencode.jsonc")],
26324
+ watchFiles: () => [join11(opencodeHome(), "opencode.json"), join11(opencodeHome(), "opencode.jsonc")],
26104
26325
  refreshEveryMs: TEN_MINUTES
26105
26326
  }
26106
26327
  };
@@ -26116,9 +26337,6 @@ var GEMINI_ACP_DIALECT = {
26116
26337
  linksFileMentions: true
26117
26338
  };
26118
26339
 
26119
- // src/acp/acp-dialects/acp-dialect.ts
26120
- var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
26121
-
26122
26340
  // src/acp/acp-dialects/grok-dialect.ts
26123
26341
  function modelEfforts(model) {
26124
26342
  const meta3 = record2(model._meta);
@@ -26218,11 +26436,11 @@ function classifySpawnError(error62, context) {
26218
26436
 
26219
26437
  // src/providers/cli/kiro-session-log.ts
26220
26438
  import { open as open2, readdir as readdir2, readFile as readFile4, stat as stat2 } from "node:fs/promises";
26221
- import { homedir as homedir8 } from "node:os";
26222
- import { join as join11 } from "node:path";
26439
+ import { homedir as homedir9 } from "node:os";
26440
+ import { join as join12 } from "node:path";
26223
26441
  var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
26224
26442
  function kiroSessionsDirectory() {
26225
- return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join11(homedir8(), ".kiro", "sessions", "cli");
26443
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join12(homedir9(), ".kiro", "sessions", "cli");
26226
26444
  }
26227
26445
  var KiroSessionLog = class {
26228
26446
  constructor(options) {
@@ -26241,7 +26459,7 @@ var KiroSessionLog = class {
26241
26459
  /** Called before the CLI starts: a resumed log is followed from its current end. */
26242
26460
  async begin() {
26243
26461
  if (!this.options.sessionId) return;
26244
- this.path = join11(this.directory, `${this.options.sessionId}.jsonl`);
26462
+ this.path = join12(this.directory, `${this.options.sessionId}.jsonl`);
26245
26463
  this.offset = await stat2(this.path).then((info) => info.size, () => 0);
26246
26464
  }
26247
26465
  /**
@@ -26254,11 +26472,11 @@ var KiroSessionLog = class {
26254
26472
  const found = [];
26255
26473
  for (const name of names) {
26256
26474
  if (!name.endsWith(".json")) continue;
26257
- const meta3 = await readFile4(join11(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
26475
+ const meta3 = await readFile4(join12(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
26258
26476
  const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
26259
26477
  if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
26260
26478
  }
26261
- if (found.length === 1) this.path = join11(this.directory, `${found[0]}.jsonl`);
26479
+ if (found.length === 1) this.path = join12(this.directory, `${found[0]}.jsonl`);
26262
26480
  }
26263
26481
  /** Reads entries appended since the last call. */
26264
26482
  async refresh() {
@@ -26569,7 +26787,7 @@ var KIRO_ACP_DIALECT = {
26569
26787
  };
26570
26788
 
26571
26789
  // src/acp/acp-dialects/omp-dialect.ts
26572
- function normalizeToolUpdate(update2) {
26790
+ function normalizeToolUpdate2(update2) {
26573
26791
  const rawOutput = record2(update2.rawOutput);
26574
26792
  if (!Array.isArray(rawOutput.content)) return update2;
26575
26793
  if (["exitCode", "exit_code", "stdout", "stderr"].some((key) => rawOutput[key] !== void 0)) return update2;
@@ -26585,7 +26803,7 @@ function normalizeToolUpdate(update2) {
26585
26803
  };
26586
26804
  }
26587
26805
  var OMP_ACP_DIALECT = {
26588
- normalizeToolUpdate,
26806
+ normalizeToolUpdate: normalizeToolUpdate2,
26589
26807
  promptErrorDetail: (error62) => {
26590
26808
  const details = record2(error62.data).details;
26591
26809
  return typeof details === "string" && details ? details : void 0;
@@ -26597,7 +26815,7 @@ var OMP_ACP_DIALECT = {
26597
26815
  };
26598
26816
 
26599
26817
  // src/acp/acp-dialects/opencode-dialect.ts
26600
- function normalizeToolUpdate2(update2) {
26818
+ function normalizeToolUpdate3(update2) {
26601
26819
  const raw = update2.rawOutput;
26602
26820
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return update2;
26603
26821
  const rawOutput = raw;
@@ -26617,7 +26835,7 @@ function normalizeToolUpdate2(update2) {
26617
26835
  };
26618
26836
  }
26619
26837
  var OPENCODE_ACP_DIALECT = {
26620
- normalizeToolUpdate: normalizeToolUpdate2,
26838
+ normalizeToolUpdate: normalizeToolUpdate3,
26621
26839
  failureRules: [
26622
26840
  { kind: "usageLimit", pattern: /"errorName"\s*:\s*"provider\.quota"/ },
26623
26841
  { kind: "rateLimited", pattern: /"errorName"\s*:\s*"provider\.rate-limit"/ }
@@ -26627,9 +26845,9 @@ var OPENCODE_ACP_DIALECT = {
26627
26845
  // src/acp/vendor.ts
26628
26846
  import { spawn as spawn6 } from "node:child_process";
26629
26847
  import { createHash } from "node:crypto";
26630
- import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
26848
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
26631
26849
  import { copyFile, mkdir as mkdir4, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
26632
- import { dirname as dirname6, join as join12, resolve as resolve4 } from "node:path";
26850
+ import { dirname as dirname6, join as join13, resolve as resolve4 } from "node:path";
26633
26851
  import { fileURLToPath } from "node:url";
26634
26852
  var AcpRuntimeUnavailable = class extends Error {
26635
26853
  constructor(message) {
@@ -26644,7 +26862,7 @@ function packageRoot() {
26644
26862
  const path = resolve4(directory, "package.json");
26645
26863
  if (existsSync5(path)) {
26646
26864
  try {
26647
- if (JSON.parse(readFileSync4(path, "utf8")).name === "toc-ocra") return directory;
26865
+ if (JSON.parse(readFileSync5(path, "utf8")).name === "toc-ocra") return directory;
26648
26866
  } catch {
26649
26867
  }
26650
26868
  }
@@ -26662,29 +26880,29 @@ function agentPackageVersion() {
26662
26880
  const directory = agentRoot();
26663
26881
  if (!directory) return "0";
26664
26882
  try {
26665
- return JSON.parse(readFileSync4(join12(directory, "package.json"), "utf8")).version ?? "0";
26883
+ return JSON.parse(readFileSync5(join13(directory, "package.json"), "utf8")).version ?? "0";
26666
26884
  } catch {
26667
26885
  return "0";
26668
26886
  }
26669
26887
  }
26670
26888
  function vendoredAdapter(name) {
26671
26889
  const directory = agentRoot();
26672
- const entry = directory ? join12(directory, "assets", "acp", name, "index.mjs") : void 0;
26890
+ const entry = directory ? join13(directory, "assets", "acp", name, "index.mjs") : void 0;
26673
26891
  return entry && existsSync5(entry) ? entry : void 0;
26674
26892
  }
26675
26893
  var installs = /* @__PURE__ */ new Map();
26676
26894
  function ensureClaudeRuntime(dataDir2) {
26677
26895
  const entry = vendoredAdapter("claude");
26678
26896
  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"));
26679
- const manifestPath = join12(dirname6(entry), "runtime.json");
26897
+ const manifestPath = join13(dirname6(entry), "runtime.json");
26680
26898
  let manifest;
26681
26899
  try {
26682
- manifest = JSON.parse(readFileSync4(manifestPath, "utf8"));
26900
+ manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
26683
26901
  } catch {
26684
26902
  return Promise.reject(new AcpRuntimeUnavailable("Claude ACP \u9002\u914D\u5668\u7F3A\u5C11 runtime.json"));
26685
26903
  }
26686
- const hash2 = createHash("sha256").update(readFileSync4(entry)).digest("hex").slice(0, 12);
26687
- const directory = join12(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
26904
+ const hash2 = createHash("sha256").update(readFileSync5(entry)).digest("hex").slice(0, 12);
26905
+ const directory = join13(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
26688
26906
  const existing = installs.get(directory);
26689
26907
  if (existing) return existing;
26690
26908
  const install = installClaudeRuntime(directory, entry, manifest).catch((error62) => {
@@ -26695,19 +26913,19 @@ function ensureClaudeRuntime(dataDir2) {
26695
26913
  return install;
26696
26914
  }
26697
26915
  async function installClaudeRuntime(directory, entry, manifest) {
26698
- const sdkPackage = join12(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
26699
- if (existsSync5(sdkPackage) && existsSync5(join12(directory, "index.mjs"))) return directory;
26916
+ const sdkPackage = join13(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
26917
+ if (existsSync5(sdkPackage) && existsSync5(join13(directory, "index.mjs"))) return directory;
26700
26918
  const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`;
26701
26919
  await mkdir4(temporary, { recursive: true, mode: 448 });
26702
26920
  try {
26703
- await writeFile4(join12(temporary, "package.json"), JSON.stringify({
26921
+ await writeFile4(join13(temporary, "package.json"), JSON.stringify({
26704
26922
  name: "toc-ocra-claude-acp-runtime",
26705
26923
  private: true,
26706
26924
  type: "module",
26707
26925
  dependencies: { [manifest.sdk.name]: manifest.sdk.version }
26708
26926
  }, null, 2));
26709
26927
  await runNpm(["install", "--omit=optional", "--no-audit", "--no-fund", "--no-package-lock", "--loglevel=error"], temporary);
26710
- await copyFile(entry, join12(temporary, "index.mjs"));
26928
+ await copyFile(entry, join13(temporary, "index.mjs"));
26711
26929
  await rm2(directory, { recursive: true, force: true });
26712
26930
  await rename4(temporary, directory);
26713
26931
  } catch (error62) {
@@ -26781,6 +26999,22 @@ var GEMINI_LAUNCH_SPEC = {
26781
26999
  dialect: GEMINI_ACP_DIALECT,
26782
27000
  modelDiscovery: { kind: "reader", source: MODEL_SOURCES.gemini }
26783
27001
  };
27002
+ var ANTIGRAVITY_LAUNCH_SPEC = {
27003
+ agent: "antigravity",
27004
+ headless: "acp",
27005
+ // agy has no full-access mode in session/set_mode; its launch flag grants it while plan approvals still reach the chat.
27006
+ args: ({ access }) => ["acp", ...access === "bypassPermissions" ? ["--dangerously-skip-permissions"] : []],
27007
+ env: { AGY_CLI_DISABLE_AUTO_UPDATE: "true" },
27008
+ scrubEnv: (env) => scrubAntigravityEnv(env),
27009
+ minimumVersions: ["1.5.2"],
27010
+ permissionModeConfig: {
27011
+ values: { ask: "default", acceptEdits: "accept-edits", bypassPermissions: "default", plan: "plan" }
27012
+ },
27013
+ resumePreference: "resume",
27014
+ dialect: ANTIGRAVITY_ACP_DIALECT,
27015
+ modelDiscovery: { kind: "reader", source: MODEL_SOURCES.antigravity },
27016
+ runSettings: { permissionModes: ["read-only", "acceptEdits", "bypassPermissions"], plan: "native" }
27017
+ };
26784
27018
  var GROK_LAUNCH_SPEC = {
26785
27019
  agent: "grok",
26786
27020
  headless: "acp",
@@ -26833,7 +27067,7 @@ var CLAUDE_LAUNCH_SPEC = {
26833
27067
  const executable = installedCli(claude);
26834
27068
  const runtime = await ensureClaudeRuntime(dataDir2);
26835
27069
  return {
26836
- launch: { executable: process.execPath, args: [join13(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
27070
+ launch: { executable: process.execPath, args: [join14(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
26837
27071
  fingerprint: `claude:${runtime}:${executable}`
26838
27072
  };
26839
27073
  },
@@ -26881,6 +27115,7 @@ var ACP_LAUNCH_SPECS = [
26881
27115
  KIRO_LAUNCH_SPEC,
26882
27116
  KIMI_LAUNCH_SPEC,
26883
27117
  GEMINI_LAUNCH_SPEC,
27118
+ ANTIGRAVITY_LAUNCH_SPEC,
26884
27119
  GROK_LAUNCH_SPEC,
26885
27120
  OPENCODE_LAUNCH_SPEC,
26886
27121
  OMP_LAUNCH_SPEC,
@@ -26928,7 +27163,9 @@ function chatSpec(row) {
26928
27163
  async launch({ access, model, reasoningEffort, workdir, dataDir: dataDir2 }) {
26929
27164
  if (row.adapter) return row.adapter({ access, model, reasoningEffort, workdir, dataDir: dataDir2 });
26930
27165
  const args = row.args({ access, model, reasoningEffort });
26931
- const spec = launchCli({ spec: cli, args, env: { ...providerEnvironment(), ...row.env } });
27166
+ const baseEnv = { ...providerEnvironment(), ...row.env };
27167
+ const env = row.scrubEnv ? row.scrubEnv(baseEnv) : baseEnv;
27168
+ const spec = launchCli({ spec: cli, args, env });
26932
27169
  return { launch: { executable: spec.executable, args: spec.args, env: spec.env, cwd: workdir }, fingerprint: args.join(" ") };
26933
27170
  },
26934
27171
  ...row.permissionModeConfig ? { modeFor: (access, plan) => acpModeFor(row, access, plan) } : {},
@@ -26952,7 +27189,7 @@ var ACP_CHAT_IDS = [...ACP_CHAT.keys()];
26952
27189
  // src/acp/acp-model-catalog-probe.ts
26953
27190
  import { mkdtemp, rm as rm3 } from "node:fs/promises";
26954
27191
  import { tmpdir } from "node:os";
26955
- import { join as join14 } from "node:path";
27192
+ import { join as join15 } from "node:path";
26956
27193
 
26957
27194
  // src/acp/acp-options.ts
26958
27195
  var text = (value) => typeof value === "string" && value ? value : void 0;
@@ -27031,7 +27268,8 @@ function settingWrite(state, step, settings, cliLabel) {
27031
27268
  if (!model) return {};
27032
27269
  const option2 = findOption(state.configOptions, "model");
27033
27270
  if (option2) {
27034
- const value = matchChoice(option2, model);
27271
+ const stripped = /^(.+)-(?:low|medium|high|xhigh|max)$/i.exec(model)?.[1];
27272
+ const value = matchChoice(option2, model) ?? (stripped ? matchChoice(option2, stripped) : void 0);
27035
27273
  if (!value) return { note: `${cliLabel} \u6CA1\u6709\u6A21\u578B\u300C${model}\u300D\uFF0C\u672C\u8F6E\u4F7F\u7528\u5F53\u524D\u6A21\u578B` };
27036
27274
  return option2.currentValue === value ? {} : config2(option2, value);
27037
27275
  }
@@ -27039,9 +27277,11 @@ function settingWrite(state, step, settings, cliLabel) {
27039
27277
  return state.currentModelId === model ? {} : { write: { step, label: STEP_LABEL[step], method: "session/set_model", params: { modelId: model } } };
27040
27278
  }
27041
27279
  case "effort": {
27042
- if (!settings.reasoningEffort) return {};
27280
+ const inferred = settings.model ? /^.+-(low|medium|high|xhigh|max)$/i.exec(settings.model)?.[1] : void 0;
27281
+ const wantedEffort = settings.reasoningEffort || inferred;
27282
+ if (!wantedEffort) return {};
27043
27283
  const option2 = findOption(state.configOptions, "thought_level");
27044
- const value = option2 ? matchChoice(option2, settings.reasoningEffort) : void 0;
27284
+ const value = option2 ? matchChoice(option2, wantedEffort) : void 0;
27045
27285
  return option2 && value && option2.currentValue !== value ? config2(option2, value) : {};
27046
27286
  }
27047
27287
  case "fast": {
@@ -27585,9 +27825,9 @@ async function readSessionModels(row, clientVersion = "1") {
27585
27825
  const discovery = row.modelDiscovery;
27586
27826
  if (discovery.kind !== "session") throw new Error(`${row.agent} does not list its models in a session`);
27587
27827
  const cli = requireCliSpec(row.agent);
27588
- const folder = await mkdtemp(join14(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
27828
+ const folder = await mkdtemp(join15(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
27589
27829
  try {
27590
- const folderArgs = discovery.sessionFolderArgs?.(join14(folder, "sessions")) ?? [];
27830
+ const folderArgs = discovery.sessionFolderArgs?.(join15(folder, "sessions")) ?? [];
27591
27831
  const args = [...row.args({ access: "read-only", model: "", reasoningEffort: "" }), ...folderArgs];
27592
27832
  const launch = launchCli({ spec: cli, args, env: { ...providerEnvironment(), ...row.env } });
27593
27833
  const connection = await AcpConnection.open({ executable: launch.executable, args: launch.args, env: launch.env, cwd: folder }, {
@@ -28216,14 +28456,14 @@ function isWriterConflict(message) {
28216
28456
  }
28217
28457
 
28218
28458
  // src/providers/cli/claude.ts
28219
- import { readdirSync as readdirSync4, readFileSync as readFileSync5 } from "node:fs";
28220
- import { homedir as homedir9 } from "node:os";
28221
- import { join as join15 } from "node:path";
28459
+ import { readdirSync as readdirSync4, readFileSync as readFileSync6 } from "node:fs";
28460
+ import { homedir as homedir10 } from "node:os";
28461
+ import { join as join16 } from "node:path";
28222
28462
  var CLAUDE = requireCliSpec("claude");
28223
28463
  function claudeProjectRoots() {
28224
28464
  const configured = process.env.CLAUDE_CONFIG_DIR;
28225
- const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join15(homedir9(), ".claude")];
28226
- return dirs.map((dir) => join15(dir, "projects"));
28465
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join16(homedir10(), ".claude")];
28466
+ return dirs.map((dir) => join16(dir, "projects"));
28227
28467
  }
28228
28468
  function claudeTranscriptExists(sessionId) {
28229
28469
  return claudeTranscriptPath(sessionId) !== void 0;
@@ -28239,7 +28479,7 @@ function claudeTranscriptPath(sessionId) {
28239
28479
  }
28240
28480
  for (const project of projects) {
28241
28481
  try {
28242
- if (readdirSync4(join15(root2, project)).includes(file2)) return join15(root2, project, file2);
28482
+ if (readdirSync4(join16(root2, project)).includes(file2)) return join16(root2, project, file2);
28243
28483
  } catch {
28244
28484
  }
28245
28485
  }
@@ -28283,7 +28523,7 @@ var claudeProvider = {
28283
28523
  settings.disableAllHooks = true;
28284
28524
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*");
28285
28525
  try {
28286
- const userSettings = JSON.parse(readFileSync5(join15(homedir9(), ".claude", "settings.json"), "utf8"));
28526
+ const userSettings = JSON.parse(readFileSync6(join16(homedir10(), ".claude", "settings.json"), "utf8"));
28287
28527
  for (const [key, value] of Object.entries(userSettings.env ?? {})) {
28288
28528
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
28289
28529
  }
@@ -28299,7 +28539,7 @@ var claudeProvider = {
28299
28539
  if (source && request.fork.keepTurns > 0) {
28300
28540
  let text3 = "";
28301
28541
  try {
28302
- text3 = readFileSync5(source, "utf8");
28542
+ text3 = readFileSync6(source, "utf8");
28303
28543
  } catch {
28304
28544
  }
28305
28545
  const at = claudeForkBoundary(text3, request.fork.keepTurns);
@@ -29017,7 +29257,8 @@ function createAcpProvider(row) {
29017
29257
  ...turn.reasoningEffort && !row.launchApplies?.reasoningEffort ? { reasoningEffort: turn.reasoningEffort } : {},
29018
29258
  ...row.runSettings?.fast && turn.fast !== void 0 ? { fast: turn.fast } : {}
29019
29259
  };
29020
- const env = { ...providerEnvironment(), ...row.env };
29260
+ const baseEnv = { ...providerEnvironment(), ...row.env };
29261
+ const env = row.scrubEnv ? row.scrubEnv(baseEnv) : baseEnv;
29021
29262
  launchEnv = env;
29022
29263
  return launchCli({ spec: cli, args: row.args({ access, model: turn.model, reasoningEffort: turn.reasoningEffort }), env });
29023
29264
  },
@@ -29094,11 +29335,229 @@ var opencodeProvider = {
29094
29335
  }
29095
29336
  };
29096
29337
 
29338
+ // src/providers/antigravity-quota.ts
29339
+ import { spawn as spawn8 } from "node:child_process";
29340
+ var ANTIGRAVITY_MIN_USAGE_VERSION = "1.1.11";
29341
+ var ANTIGRAVITY_USAGE_ARGS = ["-p", "/usage", "--output-format", "json", "--print-timeout", "20s"];
29342
+ var VERSION_TIMEOUT_MS = 5e3;
29343
+ var USAGE_TIMEOUT_MS = 3e4;
29344
+ var MAX_OUTPUT_BYTES = 512 * 1024;
29345
+ var AGY_ERROR_PREFIX = "AGY_ERROR:";
29346
+ var WEEKLY_WINDOW_SECONDS = 7 * 86400;
29347
+ var SESSION_WINDOW_SECONDS = 5 * 3600;
29348
+ var SIGNED_OUT_PHRASES = [
29349
+ "not logged into antigravity",
29350
+ "not logged in",
29351
+ "not signed in",
29352
+ "not authenticated",
29353
+ "not-authenticated",
29354
+ "unauthenticated",
29355
+ "run agy login",
29356
+ "please sign in",
29357
+ "please log in",
29358
+ "sign in to antigravity",
29359
+ "no credentials",
29360
+ "authentication required"
29361
+ ];
29362
+ var unsupportedUsageLatched = false;
29363
+ function isRecord(value) {
29364
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29365
+ }
29366
+ function readString(value) {
29367
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
29368
+ }
29369
+ function parseResetSeconds(value) {
29370
+ const text3 = readString(value);
29371
+ if (!text3) return 0;
29372
+ const ms = Date.parse(text3);
29373
+ return Number.isFinite(ms) ? Math.floor(ms / 1e3) : 0;
29374
+ }
29375
+ function windowSecondsFor(window) {
29376
+ if (window === "weekly") return WEEKLY_WINDOW_SECONDS;
29377
+ if (window === "5h") return SESSION_WINDOW_SECONDS;
29378
+ return void 0;
29379
+ }
29380
+ function shortGroupLabel(groupName) {
29381
+ const lower = groupName.toLowerCase();
29382
+ if (lower === "gemini models" || lower === "gemini") return "Gemini";
29383
+ if (lower === "claude and gpt models" || lower === "claude & gpt models") return "Claude / GPT";
29384
+ return groupName.replace(/\s+models$/i, "").trim() || groupName;
29385
+ }
29386
+ function shortWindowLabel(window, rawName) {
29387
+ if (window === "weekly") return "\u6BCF\u5468\u989D\u5EA6";
29388
+ if (window === "5h") return "5 \u5C0F\u65F6\u989D\u5EA6";
29389
+ if (!rawName) return "\u989D\u5EA6";
29390
+ return rawName.replace(/\s+(?:remaining|used|left)$/i, "").trim() || rawName;
29391
+ }
29392
+ function formatBucketLabel(groupName, window, rawName, siblings) {
29393
+ const group = shortGroupLabel(groupName);
29394
+ const win = shortWindowLabel(window, rawName);
29395
+ return siblings <= 1 && !window && !rawName ? group : `${group} \xB7 ${win}`;
29396
+ }
29397
+ function findEnvelope(stdout, parse4) {
29398
+ for (const line of stdout.split(/\r?\n/)) {
29399
+ const trimmed = line.trim();
29400
+ if (!trimmed.startsWith("{")) continue;
29401
+ try {
29402
+ const found = parse4(JSON.parse(trimmed));
29403
+ if (found !== null) return found;
29404
+ } catch {
29405
+ continue;
29406
+ }
29407
+ }
29408
+ return null;
29409
+ }
29410
+ function antigravityStdoutShowsModelTurn(stdout) {
29411
+ return findEnvelope(stdout, (value) => {
29412
+ if (!isRecord(value)) return null;
29413
+ if (typeof value.num_turns === "number" && value.num_turns > 0) return true;
29414
+ return readString(value.conversation_id) !== null ? true : null;
29415
+ }) !== null;
29416
+ }
29417
+ function parseAntigravityUsageEnvelope(value) {
29418
+ if (!isRecord(value) || readString(value.status) !== "SUCCESS") return null;
29419
+ const command = value.command;
29420
+ if (!isRecord(command) || readString(command.name) !== "usage") return null;
29421
+ const data = command.data;
29422
+ if (!isRecord(data) || !Array.isArray(data.groups)) return null;
29423
+ const windows = [];
29424
+ for (const rawGroup of data.groups) {
29425
+ if (!isRecord(rawGroup)) continue;
29426
+ const groupName = readString(rawGroup.name);
29427
+ const rawBuckets = Array.isArray(rawGroup.buckets) ? rawGroup.buckets : [];
29428
+ if (!groupName) continue;
29429
+ const enabled = rawBuckets.filter((item) => isRecord(item) && item.disabled !== true);
29430
+ for (const bucket of enabled) {
29431
+ const id = readString(bucket.id);
29432
+ const fraction = bucket.remaining_fraction;
29433
+ if (!id || typeof fraction !== "number" || !Number.isFinite(fraction)) continue;
29434
+ const windowKind = readString(bucket.window);
29435
+ const windowSeconds = windowSecondsFor(windowKind);
29436
+ const usedPercent = Math.min(100, Math.max(0, Math.round((1 - fraction) * 1e4) / 100));
29437
+ windows.push({
29438
+ key: `antigravity:${id}`,
29439
+ label: formatBucketLabel(groupName, windowKind, readString(bucket.name), enabled.length),
29440
+ used_percent: usedPercent,
29441
+ resets_at: parseResetSeconds(bucket.reset_time),
29442
+ ...windowSeconds ? { window_seconds: windowSeconds } : {}
29443
+ });
29444
+ }
29445
+ }
29446
+ if (data.groups.length > 0 && windows.length === 0) return null;
29447
+ return windows;
29448
+ }
29449
+ function parseAntigravityUsageStdout(stdout) {
29450
+ return findEnvelope(stdout, parseAntigravityUsageEnvelope);
29451
+ }
29452
+ function readAgyErrorEnvelope(stdout) {
29453
+ return findEnvelope(
29454
+ stdout,
29455
+ (value) => isRecord(value) && readString(value.status) === "ERROR" ? readString(value.error) : null
29456
+ );
29457
+ }
29458
+ function classifyFailure(output2, stderr) {
29459
+ if (stderr.includes("Authentication required. Please visit the URL")) {
29460
+ return "Antigravity \u672A\u767B\u5F55\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C agy \u5B8C\u6210\u540E\u518D\u540C\u6B65\u989D\u5EA6";
29461
+ }
29462
+ for (const line of output2.split(/\r?\n/)) {
29463
+ const idx = line.indexOf(AGY_ERROR_PREFIX);
29464
+ if (idx === -1) continue;
29465
+ const payload = line.slice(idx + AGY_ERROR_PREFIX.length).trim();
29466
+ if (!payload.startsWith("{")) continue;
29467
+ try {
29468
+ const parsed = JSON.parse(payload);
29469
+ const status = typeof parsed.status === "string" ? parsed.status.toUpperCase() : "";
29470
+ const code2 = typeof parsed.error_code === "number" ? parsed.error_code : null;
29471
+ if (status === "UNAUTHENTICATED" || code2 === 401) return "Antigravity \u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C agy \u91CD\u65B0\u767B\u5F55";
29472
+ if (status === "PERMISSION_DENIED" || code2 === 403) return "\u5F53\u524D Antigravity \u8D26\u53F7\u6CA1\u6709\u53EF\u7528\u7684\u8BA2\u9605\u989D\u5EA6\u6743\u9650";
29473
+ if (status === "RESOURCE_EXHAUSTED" || code2 === 429) return "Antigravity \u989D\u5EA6\u63A5\u53E3\u6682\u65F6\u9650\u6D41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5";
29474
+ if (code2 !== null && code2 >= 500 && code2 < 600) return `Antigravity \u670D\u52A1\u7AEF\u8FD4\u56DE\u9519\u8BEF (${code2})`;
29475
+ } catch {
29476
+ continue;
29477
+ }
29478
+ }
29479
+ const lowered = output2.toLowerCase();
29480
+ if (SIGNED_OUT_PHRASES.some((phrase) => lowered.includes(phrase))) {
29481
+ return "Antigravity \u672A\u767B\u5F55\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C agy \u5B8C\u6210\u540E\u518D\u540C\u6B65\u989D\u5EA6";
29482
+ }
29483
+ return null;
29484
+ }
29485
+ function runCommand(executable, args, env, timeoutMs) {
29486
+ return new Promise((resolve10, reject) => {
29487
+ const child = spawn8(executable, [...args], { env, stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
29488
+ let stdout = "";
29489
+ let stderr = "";
29490
+ let timedOut = false;
29491
+ const append = (current, chunk) => {
29492
+ if (current.length >= MAX_OUTPUT_BYTES) return current;
29493
+ return current + chunk.toString("utf8", 0, Math.max(0, MAX_OUTPUT_BYTES - current.length));
29494
+ };
29495
+ const timer = setTimeout(() => {
29496
+ timedOut = true;
29497
+ child.kill("SIGKILL");
29498
+ }, timeoutMs);
29499
+ child.stdout.on("data", (chunk) => {
29500
+ stdout = append(stdout, chunk);
29501
+ });
29502
+ child.stderr.on("data", (chunk) => {
29503
+ stderr = append(stderr, chunk);
29504
+ });
29505
+ child.on("error", (error62) => {
29506
+ clearTimeout(timer);
29507
+ reject(error62);
29508
+ });
29509
+ child.on("close", (code2) => {
29510
+ clearTimeout(timer);
29511
+ resolve10({ code: code2, stdout, stderr, timedOut });
29512
+ });
29513
+ });
29514
+ }
29515
+ async function readAntigravityQuotaWindows() {
29516
+ if (unsupportedUsageLatched) {
29517
+ throw new Error("\u5F53\u524D\u7248\u672C\u7684 Antigravity CLI \u4E0D\u652F\u6301 /usage \u547D\u4EE4\uFF0C\u8BF7\u5347\u7EA7 agy \u540E\u91CD\u542F\u8BBE\u5907\u4EE3\u7406");
29518
+ }
29519
+ const spec = requireCliSpec("antigravity");
29520
+ const baseEnv = mergeShellProxyEnvironment(await hydrateShellPath(), providerEnvironment());
29521
+ const env = scrubAntigravityEnv(baseEnv);
29522
+ const versionLaunch = launchCli({ spec, args: ["--version"], env });
29523
+ const versionRun = await runCommand(versionLaunch.executable, versionLaunch.args, versionLaunch.env ?? env, VERSION_TIMEOUT_MS).catch((error62) => {
29524
+ const message = error62 instanceof Error ? error62.message : String(error62);
29525
+ if (/ENOENT/i.test(message)) throw new Error("\u672C\u673A\u672A\u5B89\u88C5 Antigravity CLI\uFF08agy\uFF09");
29526
+ throw new Error(`\u65E0\u6CD5\u542F\u52A8 Antigravity CLI\uFF1A${message}`);
29527
+ });
29528
+ const detected = versionRun.code === 0 && !versionRun.timedOut ? versionNumber(versionRun.stdout.trim() || versionRun.stderr.trim()) : void 0;
29529
+ if (!detected || compareVersions(detected, ANTIGRAVITY_MIN_USAGE_VERSION) < 0) {
29530
+ throw new Error(
29531
+ detected ? `Antigravity \u989D\u5EA6\u8BFB\u53D6\u9700\u8981 agy ${ANTIGRAVITY_MIN_USAGE_VERSION} \u6216\u66F4\u65B0\u7248\u672C\uFF08\u5F53\u524D ${detected}\uFF09` : "\u65E0\u6CD5\u8BFB\u53D6 Antigravity CLI \u7248\u672C\uFF0C\u8BF7\u786E\u8BA4 agy \u5DF2\u6B63\u786E\u5B89\u88C5"
29532
+ );
29533
+ }
29534
+ const usageLaunch = launchCli({ spec, args: [...ANTIGRAVITY_USAGE_ARGS], env });
29535
+ const result = await runCommand(usageLaunch.executable, usageLaunch.args, usageLaunch.env ?? env, USAGE_TIMEOUT_MS);
29536
+ const windows = parseAntigravityUsageStdout(result.stdout);
29537
+ if (!windows) {
29538
+ const classified = classifyFailure(`${result.stdout}
29539
+ ${result.stderr}`, result.stderr);
29540
+ if (classified) throw new Error(classified);
29541
+ if (result.timedOut) throw new Error("\u8BFB\u53D6 Antigravity \u989D\u5EA6\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
29542
+ if (antigravityStdoutShowsModelTurn(result.stdout)) {
29543
+ unsupportedUsageLatched = true;
29544
+ throw new Error("\u5F53\u524D\u7248\u672C\u7684 Antigravity CLI \u5C06 /usage \u5F53\u4F5C\u5BF9\u8BDD\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u8BFB\u53D6\u4EE5\u514D\u6D88\u8017\u989D\u5EA6\uFF0C\u8BF7\u5347\u7EA7 agy");
29545
+ }
29546
+ const envelopeError = readAgyErrorEnvelope(result.stdout);
29547
+ if (envelopeError) throw new Error(`Antigravity \u989D\u5EA6\u8BFB\u53D6\u5931\u8D25\uFF1A${envelopeError}`);
29548
+ throw new Error(`Antigravity \u672A\u8FD4\u56DE\u6709\u6548\u989D\u5EA6\u6570\u636E${result.code ? ` (exit ${result.code})` : ""}`);
29549
+ }
29550
+ if (windows.length === 0) {
29551
+ throw new Error("Antigravity \u5F53\u524D\u8D26\u53F7\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u989D\u5EA6\u7A97\u53E3");
29552
+ }
29553
+ return windows;
29554
+ }
29555
+
29097
29556
  // src/providers/claude-quota.ts
29098
29557
  import { execFile as execFile5 } from "node:child_process";
29099
29558
  import { readFile as readFile5 } from "node:fs/promises";
29100
- import { homedir as homedir10 } from "node:os";
29101
- import { join as join16 } from "node:path";
29559
+ import { homedir as homedir11 } from "node:os";
29560
+ import { join as join17 } from "node:path";
29102
29561
  import { promisify as promisify3 } from "node:util";
29103
29562
  var execFileAsync3 = promisify3(execFile5);
29104
29563
  var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
@@ -29137,7 +29596,7 @@ function parseClaudeQuota(body) {
29137
29596
  }
29138
29597
  return windows;
29139
29598
  }
29140
- var claudeHome2 = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join16(homedir10(), ".claude");
29599
+ var claudeHome2 = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join17(homedir11(), ".claude");
29141
29600
  function tokenFrom(content) {
29142
29601
  try {
29143
29602
  const token = objectValue2(objectValue2(JSON.parse(content)).claudeAiOauth).accessToken;
@@ -29149,7 +29608,7 @@ function tokenFrom(content) {
29149
29608
  async function readClaudeAccessToken() {
29150
29609
  const fromEnv = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
29151
29610
  if (fromEnv) return fromEnv;
29152
- const fromFile = tokenFrom(await readFile5(join16(claudeHome2(), ".credentials.json"), "utf8").catch(() => ""));
29611
+ const fromFile = tokenFrom(await readFile5(join17(claudeHome2(), ".credentials.json"), "utf8").catch(() => ""));
29153
29612
  if (fromFile) return fromFile;
29154
29613
  if (process.platform !== "darwin") return void 0;
29155
29614
  const { stdout } = await execFileAsync3("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 1e4 }).catch(() => ({ stdout: "" }));
@@ -29171,11 +29630,11 @@ async function readClaudeQuotaWindows() {
29171
29630
  }
29172
29631
 
29173
29632
  // src/providers/codex-quota.ts
29174
- import { spawn as spawn8 } from "node:child_process";
29633
+ import { spawn as spawn9 } from "node:child_process";
29175
29634
  import { createInterface as createInterface4 } from "node:readline";
29176
29635
  async function readCodexQuotaWindows() {
29177
29636
  const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--stdio"] });
29178
- const child = spawn8(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
29637
+ const child = spawn9(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
29179
29638
  let nextId = 0;
29180
29639
  const pending = /* @__PURE__ */ new Map();
29181
29640
  const lines = createInterface4({ input: child.stdout });
@@ -29347,6 +29806,7 @@ var NATIVE = {
29347
29806
  claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude, quota: readClaudeQuotaWindows, runSettings: { permissionModes: ALL_LEVELS, plan: "native", fast: true } }
29348
29807
  };
29349
29808
  var ACP_EXTRAS = {
29809
+ antigravity: { quota: readAntigravityQuotaWindows },
29350
29810
  kiro: { quota: readKiroQuotaWindows, legacy: { headless: kiroProvider, restrictedPermission: true, runSettings: { permissionModes: ["read-only", "bypassPermissions"], plan: "prompt" } } },
29351
29811
  gemini: { legacy: { headless: geminiProvider, restrictedPermission: false } },
29352
29812
  grok: { legacy: { headless: grokProvider, restrictedPermission: false } },
@@ -29446,7 +29906,7 @@ function probeVersion(path, args) {
29446
29906
  if (args.length === 0) return Promise.resolve({});
29447
29907
  return new Promise((resolve10) => {
29448
29908
  const launch = directLaunch2(path, args, process.env.TOC_OCRA_NODE_PATH || process.execPath);
29449
- const child = spawn9(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
29909
+ const child = spawn10(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
29450
29910
  let stdout = "";
29451
29911
  let stderr = "";
29452
29912
  let settled = false;
@@ -29531,12 +29991,12 @@ var cliDetection = new CliDetectionService();
29531
29991
  // src/smoke/cli-smoke.ts
29532
29992
  import { mkdtemp as mkdtemp2, realpath as realpath3, rm as rm5 } from "node:fs/promises";
29533
29993
  import { tmpdir as tmpdir3 } from "node:os";
29534
- import { join as join21 } from "node:path";
29994
+ import { join as join22 } from "node:path";
29535
29995
 
29536
29996
  // src/runs/run-supervisor.ts
29537
- import { spawn as spawn11 } from "node:child_process";
29997
+ import { spawn as spawn12 } from "node:child_process";
29538
29998
  import { mkdir as mkdir7, realpath as realpath2, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
29539
- import { basename as basename2, isAbsolute as isAbsolute4, join as join20, relative as relative2, resolve as resolve5 } from "node:path";
29999
+ import { basename as basename2, isAbsolute as isAbsolute4, join as join21, relative as relative2, resolve as resolve5 } from "node:path";
29540
30000
  import { createInterface as createInterface6 } from "node:readline";
29541
30001
 
29542
30002
  // src/providers/chat/index.ts
@@ -29825,12 +30285,12 @@ function codexGoalProvider(request, goal) {
29825
30285
  }
29826
30286
 
29827
30287
  // src/providers/cli/codex-fork.ts
29828
- import { spawn as spawn10 } from "node:child_process";
30288
+ import { spawn as spawn11 } from "node:child_process";
29829
30289
  import { createInterface as createInterface5 } from "node:readline";
29830
30290
  var FORK_TIMEOUT_MS = 9e4;
29831
30291
  async function forkCodexThread(options) {
29832
30292
  const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--listen", "stdio://"] });
29833
- const child = spawn10(launch.executable, launch.args, {
30293
+ const child = spawn11(launch.executable, launch.args, {
29834
30294
  cwd: options.workdir,
29835
30295
  env: launch.env,
29836
30296
  shell: false,
@@ -29905,19 +30365,19 @@ async function forkCodexThread(options) {
29905
30365
 
29906
30366
  // src/runs/run-recorder.ts
29907
30367
  import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs";
29908
- import { homedir as homedir11 } from "node:os";
29909
- import { join as join17 } from "node:path";
30368
+ import { homedir as homedir12 } from "node:os";
30369
+ import { join as join18 } from "node:path";
29910
30370
  var RunRecorder = class _RunRecorder {
29911
30371
  constructor(path) {
29912
30372
  this.path = path;
29913
30373
  }
29914
30374
  path;
29915
- home = homedir11();
30375
+ home = homedir12();
29916
30376
  static fromEnvironment(runId, meta3) {
29917
30377
  const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
29918
30378
  if (!directory) return void 0;
29919
30379
  mkdirSync2(directory, { recursive: true });
29920
- const recorder = new _RunRecorder(join17(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
30380
+ const recorder = new _RunRecorder(join18(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
29921
30381
  recorder.write({ meta: meta3 });
29922
30382
  return recorder;
29923
30383
  }
@@ -29933,7 +30393,7 @@ var RunRecorder = class _RunRecorder {
29933
30393
 
29934
30394
  // src/runs/run-transcript.ts
29935
30395
  import { chmod as chmod4, mkdir as mkdir5, readdir as readdir3, readFile as readFile6, rename as rename5, stat as stat3, unlink, writeFile as writeFile5 } from "node:fs/promises";
29936
- import { join as join18 } from "node:path";
30396
+ import { join as join19 } from "node:path";
29937
30397
  var MAX_TRANSCRIPT_ITEMS = 5e3;
29938
30398
  var MAX_TRANSCRIPT_TEXT = 2e5;
29939
30399
  var MAX_TRANSCRIPT_LINES = 2e4;
@@ -30198,7 +30658,7 @@ function transcriptFileName(runId) {
30198
30658
  var TranscriptStore = class {
30199
30659
  constructor(dataDir2, logger, env = process.env) {
30200
30660
  this.logger = logger;
30201
- this.directory = dataDir2 ? join18(dataDir2, "transcripts") : "";
30661
+ this.directory = dataDir2 ? join19(dataDir2, "transcripts") : "";
30202
30662
  this.enabled = Boolean(dataDir2) && transcriptsOnDisk(env);
30203
30663
  }
30204
30664
  logger;
@@ -30253,7 +30713,7 @@ var TranscriptStore = class {
30253
30713
  await this.writes.get(runId);
30254
30714
  let text3;
30255
30715
  try {
30256
- text3 = await readFile6(join18(this.directory, name), "utf8");
30716
+ text3 = await readFile6(join19(this.directory, name), "utf8");
30257
30717
  } catch (error62) {
30258
30718
  if (errorCode(error62) !== "ENOENT") this.logger.warn("run-transcript-read-failed", { runId, error: errorMessage(error62) });
30259
30719
  return void 0;
@@ -30318,7 +30778,7 @@ var TranscriptStore = class {
30318
30778
  transcript.dirty = false;
30319
30779
  const body = JSON.stringify(transcript.toFile());
30320
30780
  await this.ensureDirectory();
30321
- const file2 = join18(this.directory, name);
30781
+ const file2 = join19(this.directory, name);
30322
30782
  const temporary = `${file2}.${process.pid}.tmp`;
30323
30783
  await writeFile5(temporary, body, { mode: 384 });
30324
30784
  await rename5(temporary, file2);
@@ -30355,7 +30815,7 @@ var TranscriptStore = class {
30355
30815
  const now = Date.now();
30356
30816
  const files = [];
30357
30817
  for (const name of names) {
30358
- const path = join18(this.directory, name);
30818
+ const path = join19(this.directory, name);
30359
30819
  if (name.endsWith(".tmp")) {
30360
30820
  const info2 = await stat3(path).catch(() => void 0);
30361
30821
  if (info2?.isFile() && now - info2.mtimeMs > STALE_TEMPORARY_MS) await unlink(path).catch(() => void 0);
@@ -30405,7 +30865,7 @@ function errorMessage(error62) {
30405
30865
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
30406
30866
  import { constants as constants2 } from "node:fs";
30407
30867
  import { lstat, mkdir as mkdir6, open as open3, realpath, rename as rename6, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
30408
- import { basename, isAbsolute as isAbsolute3, join as join19, relative } from "node:path";
30868
+ import { basename, isAbsolute as isAbsolute3, join as join20, relative } from "node:path";
30409
30869
  function within(root2, path) {
30410
30870
  const segment = relative(root2, path);
30411
30871
  return segment === "" || !segment.startsWith("..") && !isAbsolute3(segment);
@@ -30413,7 +30873,7 @@ function within(root2, path) {
30413
30873
  async function attachmentDirectory(workdir, messageId) {
30414
30874
  let directory = workdir;
30415
30875
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
30416
- directory = join19(directory, segment);
30876
+ directory = join20(directory, segment);
30417
30877
  await mkdir6(directory, { mode: 448 }).catch((error62) => {
30418
30878
  if (error62.code !== "EEXIST") throw error62;
30419
30879
  });
@@ -30421,7 +30881,7 @@ async function attachmentDirectory(workdir, messageId) {
30421
30881
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
30422
30882
  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");
30423
30883
  }
30424
- if (segment === ".echo") await writeFile6(join19(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
30884
+ if (segment === ".echo") await writeFile6(join20(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
30425
30885
  if (error62.code !== "EEXIST") throw error62;
30426
30886
  });
30427
30887
  }
@@ -30458,9 +30918,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
30458
30918
  const characters = Array.from(basename(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
30459
30919
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
30460
30920
  const name = characters.join("") || "attachment";
30461
- const path = join19(directory, `${file2.file_id}-${name}`);
30921
+ const path = join20(directory, `${file2.file_id}-${name}`);
30462
30922
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
30463
- const temporary = join19(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
30923
+ const temporary = join20(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
30464
30924
  try {
30465
30925
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
30466
30926
  signal2.throwIfAborted();
@@ -30580,29 +31040,29 @@ import { extname } from "node:path";
30580
31040
  import { pathToFileURL } from "node:url";
30581
31041
 
30582
31042
  // src/acp/ask-user-question.ts
30583
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31043
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30584
31044
  var getLodyMeta = (meta3) => {
30585
- if (!isRecord(meta3)) return null;
30586
- return isRecord(meta3.lody) ? meta3.lody : null;
31045
+ if (!isRecord2(meta3)) return null;
31046
+ return isRecord2(meta3.lody) ? meta3.lody : null;
30587
31047
  };
30588
31048
  var getClaudeCodeMeta = (meta3) => {
30589
- if (!isRecord(meta3)) return null;
30590
- return isRecord(meta3.claudeCode) ? meta3.claudeCode : null;
31049
+ if (!isRecord2(meta3)) return null;
31050
+ return isRecord2(meta3.claudeCode) ? meta3.claudeCode : null;
30591
31051
  };
30592
31052
  var getCodexMeta = (meta3) => {
30593
- if (!isRecord(meta3)) return null;
30594
- return isRecord(meta3.codex) ? meta3.codex : null;
31053
+ if (!isRecord2(meta3)) return null;
31054
+ return isRecord2(meta3.codex) ? meta3.codex : null;
30595
31055
  };
30596
31056
  var getLodyElicitationMeta = (meta3) => {
30597
31057
  const elicitation = getLodyMeta(meta3)?.elicitation;
30598
- return isRecord(elicitation) && elicitation.version === 1 ? elicitation : null;
31058
+ return isRecord2(elicitation) && elicitation.version === 1 ? elicitation : null;
30599
31059
  };
30600
31060
  function isAskUserQuestionPermission(params) {
30601
31061
  const meta3 = params._meta;
30602
31062
  const lody = getLodyElicitationMeta(meta3);
30603
31063
  if (lody && Array.isArray(lody.questions)) return true;
30604
- if (isRecord(getClaudeCodeMeta(meta3)?.askUserQuestion)) return true;
30605
- return isRecord(getCodexMeta(meta3)?.requestUserInput);
31064
+ if (isRecord2(getClaudeCodeMeta(meta3)?.askUserQuestion)) return true;
31065
+ return isRecord2(getCodexMeta(meta3)?.requestUserInput);
30606
31066
  }
30607
31067
  function hasValidNoteKeys(questions) {
30608
31068
  if (!questions.some((question) => question.note)) return true;
@@ -30626,18 +31086,18 @@ function getAskUserQuestionAnswerKey(questions, index) {
30626
31086
  }
30627
31087
  var getLodyOutcomeAnswers = (outcomeMeta) => {
30628
31088
  const elicitation = getLodyMeta(outcomeMeta)?.elicitation;
30629
- return isRecord(elicitation) && isRecord(elicitation.answers) ? elicitation.answers : null;
31089
+ return isRecord2(elicitation) && isRecord2(elicitation.answers) ? elicitation.answers : null;
30630
31090
  };
30631
31091
  var getCodexOutcomeAnswers = (outcomeMeta) => {
30632
31092
  const requestUserInput = getCodexMeta(outcomeMeta)?.requestUserInput;
30633
- return isRecord(requestUserInput) && isRecord(requestUserInput.answers) ? requestUserInput.answers : null;
31093
+ return isRecord2(requestUserInput) && isRecord2(requestUserInput.answers) ? requestUserInput.answers : null;
30634
31094
  };
30635
31095
  var getClaudeOutcomeAnswers = (outcomeMeta) => {
30636
31096
  const askUserQuestion = getClaudeCodeMeta(outcomeMeta)?.askUserQuestion;
30637
- return isRecord(askUserQuestion) && isRecord(askUserQuestion.answers) ? askUserQuestion.answers : null;
31097
+ return isRecord2(askUserQuestion) && isRecord2(askUserQuestion.answers) ? askUserQuestion.answers : null;
30638
31098
  };
30639
31099
  function extractAskUserQuestionAnswersFromOutcome(meta3, outcome) {
30640
- if (!outcome || !isRecord(outcome._meta) || !hasValidNoteKeys(meta3.questions)) return null;
31100
+ if (!outcome || !isRecord2(outcome._meta) || !hasValidNoteKeys(meta3.questions)) return null;
30641
31101
  const answerSources = [
30642
31102
  { source: "lody", answers: getLodyOutcomeAnswers(outcome._meta) },
30643
31103
  { source: "codex", answers: getCodexOutcomeAnswers(outcome._meta) },
@@ -30656,7 +31116,7 @@ function extractAskUserQuestionAnswersFromOutcome(meta3, outcome) {
30656
31116
  const raw = answerSource.answers[sourceKey];
30657
31117
  if (raw === void 0) continue;
30658
31118
  if (answerSource.source === "codex") {
30659
- if (!isRecord(raw) || !Array.isArray(raw.answers)) continue;
31119
+ if (!isRecord2(raw) || !Array.isArray(raw.answers)) continue;
30660
31120
  const values = raw.answers.filter((value) => typeof value === "string");
30661
31121
  if (values.length === 0) continue;
30662
31122
  result[key] = question.multiSelect ? values : values[0] ?? "";
@@ -30670,20 +31130,20 @@ function extractAskUserQuestionAnswersFromOutcome(meta3, outcome) {
30670
31130
  }
30671
31131
  return Object.keys(result).length > 0 ? result : null;
30672
31132
  }
30673
- var isEnumOption = (value) => isRecord(value) && typeof value.const === "string";
31133
+ var isEnumOption = (value) => isRecord2(value) && typeof value.const === "string";
30674
31134
  var getEnumOptionSource = (prop) => {
30675
31135
  if (Array.isArray(prop.oneOf)) return prop.oneOf;
30676
31136
  if (Array.isArray(prop.enum)) return prop.enum;
30677
31137
  const items = prop.items;
30678
- if (isRecord(items)) {
31138
+ if (isRecord2(items)) {
30679
31139
  if (Array.isArray(items.anyOf)) return items.anyOf;
30680
31140
  if (Array.isArray(items.enum)) return items.enum;
30681
31141
  }
30682
31142
  return null;
30683
31143
  };
30684
- var isQuestionProperty = (prop) => isRecord(prop) && getEnumOptionSource(prop) !== null;
30685
- var isFreeTextProperty = (prop) => isRecord(prop) && prop.type === "string" && !Array.isArray(prop.oneOf) && !Array.isArray(prop.enum);
30686
- var isMultiSelectProperty = (prop) => prop.type === "array" || isRecord(prop.items);
31144
+ var isQuestionProperty = (prop) => isRecord2(prop) && getEnumOptionSource(prop) !== null;
31145
+ var isFreeTextProperty = (prop) => isRecord2(prop) && prop.type === "string" && !Array.isArray(prop.oneOf) && !Array.isArray(prop.enum);
31146
+ var isMultiSelectProperty = (prop) => prop.type === "array" || isRecord2(prop.items);
30687
31147
  var parseElicitationOptions = (source) => {
30688
31148
  const options = [];
30689
31149
  for (const entry of source) {
@@ -30702,9 +31162,9 @@ var parseElicitationOptions = (source) => {
30702
31162
  return options;
30703
31163
  };
30704
31164
  function parseAskUserQuestionElicitationRequest(request) {
30705
- if (!isRecord(request) || request.mode !== "form") return null;
31165
+ if (!isRecord2(request) || request.mode !== "form") return null;
30706
31166
  const schema = request.requestedSchema;
30707
- if (!isRecord(schema) || !isRecord(schema.properties)) return null;
31167
+ if (!isRecord2(schema) || !isRecord2(schema.properties)) return null;
30708
31168
  const properties = schema.properties;
30709
31169
  const entries = Object.entries(properties);
30710
31170
  const requestMeta = getLodyElicitationMeta(request._meta);
@@ -30712,9 +31172,9 @@ function parseAskUserQuestionElicitationRequest(request) {
30712
31172
  const noteFieldKeyByQuestionId = /* @__PURE__ */ new Map();
30713
31173
  const associatedFields = /* @__PURE__ */ new Set();
30714
31174
  for (const [key, prop] of entries) {
30715
- if (!isRecord(prop)) continue;
31175
+ if (!isRecord2(prop)) continue;
30716
31176
  const rawMeta = getLodyMeta(prop._meta)?.elicitation;
30717
- if (isRecord(rawMeta) && rawMeta.noteFor !== void 0 && rawMeta.version !== 1) return null;
31177
+ if (isRecord2(rawMeta) && rawMeta.noteFor !== void 0 && rawMeta.version !== 1) return null;
30718
31178
  const meta3 = getLodyElicitationMeta(prop._meta);
30719
31179
  if (!meta3 || meta3.noteFor === void 0 && meta3.customAnswerFor === void 0) continue;
30720
31180
  if (meta3.noteFor !== void 0 && meta3.customAnswerFor !== void 0) return null;
@@ -30727,7 +31187,7 @@ function parseAskUserQuestionElicitationRequest(request) {
30727
31187
  }
30728
31188
  const isLodyForm = requestMeta !== null || associatedFields.size > 0;
30729
31189
  const questionEntries = entries.filter(([key, prop]) => {
30730
- if (!isRecord(prop) || associatedFields.has(key)) return false;
31190
+ if (!isRecord2(prop) || associatedFields.has(key)) return false;
30731
31191
  return isQuestionProperty(prop) || isLodyForm && isFreeTextProperty(prop);
30732
31192
  });
30733
31193
  if (questionEntries.length === 0) return null;
@@ -30737,13 +31197,13 @@ function parseAskUserQuestionElicitationRequest(request) {
30737
31197
  }
30738
31198
  if (associatedFields.size > 0 && questionEntries.some(([key]) => !key.trim())) return null;
30739
31199
  const singleQuestion = questionEntries.length === 1;
30740
- const allowCustomAnswer = isLodyForm ? questionEntries.some(([key, prop]) => isRecord(prop) && (getEnumOptionSource(prop) === null || customFieldKeyByQuestionId.has(key))) : entries.some(([, prop]) => isFreeTextProperty(prop));
31200
+ const allowCustomAnswer = isLodyForm ? questionEntries.some(([key, prop]) => isRecord2(prop) && (getEnumOptionSource(prop) === null || customFieldKeyByQuestionId.has(key))) : entries.some(([, prop]) => isFreeTextProperty(prop));
30741
31201
  const message = typeof request.message === "string" ? request.message : "";
30742
31202
  const questions = [];
30743
31203
  const fieldKeys = [];
30744
31204
  const customFieldKeys = [];
30745
31205
  for (const [key, prop] of questionEntries) {
30746
- if (!isRecord(prop)) continue;
31206
+ if (!isRecord2(prop)) continue;
30747
31207
  const source = getEnumOptionSource(prop);
30748
31208
  const header = typeof prop.title === "string" ? prop.title : "";
30749
31209
  const description = typeof prop.description === "string" ? prop.description : "";
@@ -30758,7 +31218,7 @@ function parseAskUserQuestionElicitationRequest(request) {
30758
31218
  multiSelect: isMultiSelectProperty(prop),
30759
31219
  ...isLodyForm ? { allowCustomAnswer: source === null || customFieldKeyByQuestionId.has(key) } : {},
30760
31220
  ...isLodyForm && getLodyElicitationMeta(prop._meta)?.secret === true ? { isSecret: true } : {},
30761
- ...noteFieldId !== void 0 && isRecord(noteProp) ? {
31221
+ ...noteFieldId !== void 0 && isRecord2(noteProp) ? {
30762
31222
  note: {
30763
31223
  fieldId: noteFieldId,
30764
31224
  ...typeof noteProp.title === "string" ? { title: noteProp.title } : {},
@@ -30781,7 +31241,7 @@ function parseAskUserQuestionElicitationRequest(request) {
30781
31241
  }
30782
31242
  function buildAskUserQuestionElicitationResponse(elicitation, outcome) {
30783
31243
  if (!outcome || outcome.outcome !== "selected" || outcome.optionId === "cancel") return { action: "cancel" };
30784
- const answers = extractAskUserQuestionAnswersFromOutcome(elicitation.meta, { _meta: isRecord(outcome._meta) ? outcome._meta : null });
31244
+ const answers = extractAskUserQuestionAnswersFromOutcome(elicitation.meta, { _meta: isRecord2(outcome._meta) ? outcome._meta : null });
30785
31245
  if (!answers) return { action: "accept", content: {} };
30786
31246
  const content = /* @__PURE__ */ Object.create(null);
30787
31247
  elicitation.meta.questions.forEach((question, index) => {
@@ -30808,8 +31268,8 @@ function redactSecretAnswers(elicitation, outcome) {
30808
31268
  if (question.note?.isSecret) secret.add(question.note.fieldId);
30809
31269
  });
30810
31270
  const lody = getLodyMeta(outcome._meta);
30811
- const elicitationMeta = lody && isRecord(lody.elicitation) ? lody.elicitation : null;
30812
- if (!secret.size || !elicitationMeta || !isRecord(elicitationMeta.answers)) return outcome;
31271
+ const elicitationMeta = lody && isRecord2(lody.elicitation) ? lody.elicitation : null;
31272
+ if (!secret.size || !elicitationMeta || !isRecord2(elicitationMeta.answers)) return outcome;
30813
31273
  const answers = Object.fromEntries(Object.entries(elicitationMeta.answers).map(([key, value]) => [key, secret.has(key) ? "[redacted]" : value]));
30814
31274
  return { ...outcome, _meta: { ...outcome._meta, lody: { ...lody, elicitation: { ...elicitationMeta, answers } } } };
30815
31275
  }
@@ -31235,8 +31695,10 @@ var AcpChatSession = class {
31235
31695
  */
31236
31696
  forwardsPermission(params, prompts) {
31237
31697
  if (isAskUserQuestionPermission(params)) return true;
31698
+ const call = record4(params.toolCall);
31699
+ if (typeof call.toolCallId === "string" && call.toolCallId.startsWith("interaction_")) return true;
31238
31700
  if (prompts.permissions === "none") return false;
31239
- const title = record4(params.toolCall).title;
31701
+ const title = call.title;
31240
31702
  if (ECHO_CALLBACK.test(typeof title === "string" ? title : "")) return false;
31241
31703
  if (prompts.permissions === "all") return true;
31242
31704
  return !permissionAllowed(params, { permissionMode: "full", access: "acceptEdits" });
@@ -31544,12 +32006,12 @@ var MemoryBindingSchema = external_exports.object({
31544
32006
  memory_id: external_exports.string().trim().min(1).max(200)
31545
32007
  });
31546
32008
  var COMMAND_TIMEOUT_MS = 15e3;
31547
- var MAX_OUTPUT_BYTES = 1024 * 1024;
32009
+ var MAX_OUTPUT_BYTES2 = 1024 * 1024;
31548
32010
  var runNmem = (args) => {
31549
32011
  const env = providerEnvironment();
31550
32012
  const launch = resolveExecutable("nmem", args, env, process.env.TOC_OCRA_NMEM_PATH);
31551
32013
  return new Promise((resolve10) => {
31552
- execFile7(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true }, (error62, stdout) => {
32014
+ execFile7(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES2, windowsHide: true }, (error62, stdout) => {
31553
32015
  if (!error62) {
31554
32016
  resolve10({ stdout: String(stdout) });
31555
32017
  return;
@@ -31988,7 +32450,7 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
31988
32450
  if (!fitsCommandLine(launch)) return refuse(cliFailure("promptTooLong", { label: cli.label }));
31989
32451
  let child;
31990
32452
  try {
31991
- child = spawn11(launch.executable, launch.args, {
32453
+ child = spawn12(launch.executable, launch.args, {
31992
32454
  cwd: workdir,
31993
32455
  env: Object.keys(memoryEnv).length ? { ...launch.env, ...memoryEnv } : launch.env,
31994
32456
  detached: currentPlatform.runsInOwnProcessGroup,
@@ -32527,12 +32989,12 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
32527
32989
  async prepareChatAttachments(payload) {
32528
32990
  if (!payload.attachments?.length) return [];
32529
32991
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
32530
- const directory = join20(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
32992
+ const directory = join21(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
32531
32993
  await mkdir7(directory, { recursive: true, mode: 448 });
32532
32994
  const files = [];
32533
32995
  for (const attachment of payload.attachments) {
32534
32996
  const name = basename2(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
32535
- const path = join20(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
32997
+ const path = join21(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
32536
32998
  const existing = await stat5(path).catch(() => void 0);
32537
32999
  if (!existing?.isFile()) {
32538
33000
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
@@ -32733,7 +33195,7 @@ var silent = { debug() {
32733
33195
  async function runCliSmoke(options = {}) {
32734
33196
  const detection = await cliDetection.detect(true);
32735
33197
  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);
32736
- const root2 = await realpath3(await mkdtemp2(join21(tmpdir3(), "toc-ocra-smoke-")));
33198
+ const root2 = await realpath3(await mkdtemp2(join22(tmpdir3(), "toc-ocra-smoke-")));
32737
33199
  const finished = /* @__PURE__ */ new Map();
32738
33200
  const config2 = { allowedRoots: [root2], maxConcurrentRuns: 0, maxRunSeconds: options.timeoutSeconds ?? 300, dataDir: root2 };
32739
33201
  const supervisor = new RunSupervisor(config2, silent, {
@@ -32805,7 +33267,7 @@ async function runCliSmoke(options = {}) {
32805
33267
  }
32806
33268
 
32807
33269
  // src/runtime/run-service.ts
32808
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
33270
+ import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
32809
33271
  import { dirname as dirname10, resolve as resolve8 } from "node:path";
32810
33272
  import { fileURLToPath as fileURLToPath2 } from "node:url";
32811
33273
 
@@ -33050,7 +33512,7 @@ import {
33050
33512
  chmodSync,
33051
33513
  existsSync as existsSync6,
33052
33514
  mkdirSync as mkdirSync3,
33053
- readFileSync as readFileSync6,
33515
+ readFileSync as readFileSync7,
33054
33516
  renameSync,
33055
33517
  statSync as statSync4,
33056
33518
  unlinkSync,
@@ -33108,7 +33570,7 @@ function createDiagnosticLogger(filePath, options = {}) {
33108
33570
  for (let index = 0; index <= maxRotatedFiles; index += 1) {
33109
33571
  const path = index === 0 ? filePath : `${filePath}.${index}`;
33110
33572
  if (!existsSync6(path)) continue;
33111
- const kept = readFileSync6(path, "utf8").split("\n").filter((line) => {
33573
+ const kept = readFileSync7(path, "utf8").split("\n").filter((line) => {
33112
33574
  if (!line.trim()) return false;
33113
33575
  try {
33114
33576
  const timestamp = Date.parse(JSON.parse(line).ts);
@@ -33168,10 +33630,10 @@ function createDiagnosticLogger(filePath, options = {}) {
33168
33630
 
33169
33631
  // src/runtime/agent-runtime.ts
33170
33632
  import { randomUUID as randomUUID4 } from "node:crypto";
33171
- import { join as join24 } from "node:path";
33633
+ import { join as join25 } from "node:path";
33172
33634
 
33173
33635
  // src/exec/script-runner.ts
33174
- import { spawn as spawn12 } from "node:child_process";
33636
+ import { spawn as spawn13 } from "node:child_process";
33175
33637
  var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
33176
33638
  function executeScript(command, workdir, timeoutSeconds) {
33177
33639
  return new Promise((resolveExecution) => {
@@ -33202,7 +33664,7 @@ function executeScript(command, workdir, timeoutSeconds) {
33202
33664
  };
33203
33665
  let child;
33204
33666
  try {
33205
- child = spawn12(executable, args, {
33667
+ child = spawn13(executable, args, {
33206
33668
  cwd: workdir,
33207
33669
  env: process.env,
33208
33670
  detached: ownGroup,
@@ -33340,15 +33802,15 @@ async function readCLIQuotaReport(agentType) {
33340
33802
 
33341
33803
  // src/providers/tb-switch-control.ts
33342
33804
  import { readFile as readFile9 } from "node:fs/promises";
33343
- import { homedir as homedir12 } from "node:os";
33344
- import { join as join22 } from "node:path";
33805
+ import { homedir as homedir13 } from "node:os";
33806
+ import { join as join23 } from "node:path";
33345
33807
  function dataDir() {
33346
- return process.env.TB_SWITCH_HOME?.trim() || join22(homedir12(), ".tb-switch");
33808
+ return process.env.TB_SWITCH_HOME?.trim() || join23(homedir13(), ".tb-switch");
33347
33809
  }
33348
33810
  async function readLocalService() {
33349
33811
  let discovery;
33350
33812
  try {
33351
- discovery = JSON.parse(await readFile9(join22(dataDir(), "api.json"), "utf8"));
33813
+ discovery = JSON.parse(await readFile9(join23(dataDir(), "api.json"), "utf8"));
33352
33814
  } catch {
33353
33815
  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");
33354
33816
  }
@@ -33364,7 +33826,7 @@ async function readLocalService() {
33364
33826
  }
33365
33827
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
33366
33828
  try {
33367
- token = (await readFile9(join22(dataDir(), "api-token"), "utf8")).trim();
33829
+ token = (await readFile9(join23(dataDir(), "api-token"), "utf8")).trim();
33368
33830
  } catch {
33369
33831
  }
33370
33832
  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");
@@ -33636,11 +34098,11 @@ var GatewayClient = class {
33636
34098
 
33637
34099
  // src/workspace/directory-browser.ts
33638
34100
  import { mkdir as mkdir9, readdir as readdir4, realpath as realpath4, stat as stat7 } from "node:fs/promises";
33639
- import { homedir as homedir13 } from "node:os";
34101
+ import { homedir as homedir14 } from "node:os";
33640
34102
  import { dirname as dirname9, isAbsolute as isAbsolute5, parse as parse3, resolve as resolve6 } from "node:path";
33641
34103
  var MAX_ENTRIES = 1e3;
33642
34104
  async function listDirectory(requested, allowedRoots) {
33643
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir13()) || homedir13();
34105
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir14()) || homedir14();
33644
34106
  const directory = await realpath4(resolve6(raw)).catch(() => {
33645
34107
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
33646
34108
  });
@@ -33658,8 +34120,8 @@ async function listDirectory(requested, allowedRoots) {
33658
34120
  else if (entry.isFile()) files.push(item);
33659
34121
  }
33660
34122
  const parent = dirname9(directory);
33661
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir13() }];
33662
- for (const root2 of allowedRoots) if (root2 !== homedir13()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
34123
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir14() }];
34124
+ for (const root2 of allowedRoots) if (root2 !== homedir14()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
33663
34125
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
33664
34126
  return {
33665
34127
  path: directory,
@@ -33695,9 +34157,9 @@ async function createDirectory(parentRequested, name) {
33695
34157
  }
33696
34158
 
33697
34159
  // src/workspace/workspace-manager.ts
33698
- import { spawn as spawn13 } from "node:child_process";
34160
+ import { spawn as spawn14 } from "node:child_process";
33699
34161
  import { opendir, realpath as realpath5, stat as stat8 } from "node:fs/promises";
33700
- import { homedir as homedir14 } from "node:os";
34162
+ import { homedir as homedir15 } from "node:os";
33701
34163
  import { isAbsolute as isAbsolute6, relative as relative3, resolve as resolve7 } from "node:path";
33702
34164
  var MAX_NODES = 2e3;
33703
34165
  var MAX_DIRECTORY_ENTRIES = 12e3;
@@ -33733,7 +34195,7 @@ var WorkspaceManager = class {
33733
34195
  return { root_path: rootPath, nodes, truncated: nodes.length >= MAX_NODES, duration_ms: Date.now() - startedAt };
33734
34196
  }
33735
34197
  validateRootPath(value) {
33736
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir14());
34198
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir15());
33737
34199
  const root2 = resolve7(raw);
33738
34200
  if (!isAbsolute6(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
33739
34201
  if (relative3(root2, resolve7(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -33859,7 +34321,7 @@ var WorkspaceManager = class {
33859
34321
  }
33860
34322
  runGit(args, cwd, timeoutSeconds, allowFailure = false) {
33861
34323
  return new Promise((resolveCommand, rejectCommand) => {
33862
- const child = spawn13("git", args, {
34324
+ const child = spawn14("git", args, {
33863
34325
  cwd,
33864
34326
  env: process.env,
33865
34327
  shell: false,
@@ -34073,7 +34535,7 @@ var AgentRuntime = class {
34073
34535
  }
34074
34536
  };
34075
34537
  this.workspaces = new WorkspaceManager(config2, this.logger);
34076
- this.orphans = new OrphanRegistry(join24(config2.dataDir, "active-runs.json"));
34538
+ this.orphans = new OrphanRegistry(join25(config2.dataDir, "active-runs.json"));
34077
34539
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
34078
34540
  }
34079
34541
  config;
@@ -34785,7 +35247,7 @@ function agentPackageRoot() {
34785
35247
  const packagePath = resolve8(directory, "package.json");
34786
35248
  if (existsSync7(packagePath)) {
34787
35249
  try {
34788
- const info = JSON.parse(readFileSync7(packagePath, "utf8"));
35250
+ const info = JSON.parse(readFileSync8(packagePath, "utf8"));
34789
35251
  if (info.name === PACKAGE_NAME && typeof info.version === "string") return directory;
34790
35252
  } catch {
34791
35253
  }
@@ -34797,7 +35259,7 @@ function agentPackageRoot() {
34797
35259
  }
34798
35260
  function agentVersion() {
34799
35261
  const root2 = agentPackageRoot();
34800
- return root2 ? JSON.parse(readFileSync7(resolve8(root2, "package.json"), "utf8")).version : "unknown";
35262
+ return root2 ? JSON.parse(readFileSync8(resolve8(root2, "package.json"), "utf8")).version : "unknown";
34801
35263
  }
34802
35264
  async function runService(options = {}) {
34803
35265
  const version2 = agentVersion();
@@ -34846,7 +35308,7 @@ async function runService(options = {}) {
34846
35308
  }
34847
35309
 
34848
35310
  // src/index.ts
34849
- var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join25(agentPackageRoot(), "scripts", "installation.cjs"));
35311
+ var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join26(agentPackageRoot(), "scripts", "installation.cjs"));
34850
35312
  async function run() {
34851
35313
  try {
34852
35314
  await runService();
@@ -34973,7 +35435,7 @@ async function update(args) {
34973
35435
  if (customConfig) process.env.TOC_OCRA_CONFIG = resolve9(customConfig);
34974
35436
  await ensureIdle();
34975
35437
  const npmPath = resolveCliCommand("npm");
34976
- const temporary = mkdtempSync(join25(tmpdir4(), "toc-ocra-update-"));
35438
+ const temporary = mkdtempSync(join26(tmpdir4(), "toc-ocra-update-"));
34977
35439
  try {
34978
35440
  const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
34979
35441
  if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -35000,7 +35462,7 @@ async function update(args) {
35000
35462
  }
35001
35463
  const archive = Buffer.concat(chunks);
35002
35464
  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");
35003
- const archivePath = join25(temporary, "toc-ocra.tgz");
35465
+ const archivePath = join26(temporary, "toc-ocra.tgz");
35004
35466
  writeFileSync3(archivePath, archive, { mode: 384 });
35005
35467
  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]);
35006
35468
  const install = spawnSync(npm.executable, npm.args, { stdio: "inherit", shell: false, windowsHide: true });
@@ -35010,7 +35472,7 @@ async function update(args) {
35010
35472
  return;
35011
35473
  }
35012
35474
  const previousVersion = agentVersion();
35013
- const current = await installShared(join25(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync8(defaultConfigPath()) });
35475
+ const current = await installShared(join26(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync8(defaultConfigPath()) });
35014
35476
  if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
35015
35477
  `);
35016
35478
  else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
@@ -35038,7 +35500,7 @@ async function main() {
35038
35500
  const selected = !shared || compareVersions2(agentVersion(), shared.version) > 0 ? await installShared(root2) : shared;
35039
35501
  const same = (a, b) => process.platform === "win32" ? resolve9(a).toLowerCase() === resolve9(b).toLowerCase() : resolve9(a) === resolve9(b);
35040
35502
  if (!same(selected.root, root2)) {
35041
- await import(pathToFileURL2(join25(selected.root, "dist", "cli", "cli.mjs")).href);
35503
+ await import(pathToFileURL2(join26(selected.root, "dist", "cli", "cli.mjs")).href);
35042
35504
  return;
35043
35505
  }
35044
35506
  }