toc-ocra 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # toc-ocra
2
2
 
3
- 运行在用户电脑上的 CLI 执行端。它接收 echo_admin 派发的任务,在本机以无界面模式运行 codex / claude / grok / gemini / opencode 等 CLI,并把运行状态和结果报回服务端。它也可以在设备开启相应开关后执行脚本和 SQL(SQL 执行器目前是预留接口)。
3
+ 运行在用户电脑上的 CLI 执行端。它接收 echo_admin 派发的任务,在本机以无界面模式运行 codex / claude / kiro / grok / gemini / opencode 等 CLI,并把运行状态和结果报回服务端。它也可以在设备开启相应开关后执行脚本和 SQL(SQL 执行器目前是预留接口)。
4
4
 
5
5
  参照 Orca 和 `api/api_ocra` 重构而来;`api_ocra` 保持原样不动。
6
6
 
@@ -54,6 +54,22 @@ node dist/src/index.js run
54
54
 
55
55
  ## 配置
56
56
 
57
+ ### Kiro CLI 模型与推理档位
58
+
59
+ 本机登录 Kiro 后,代理从 `kiro-cli chat --list-models --format json` 读取当前账号的完整模型列表与默认模型,再通过 Kiro ACP 的原生 `/effort` 选项读取每个模型支持的档位。默认档位还会读取 `~/.kiro/settings/cli.json` 的 `chat.modelDefaults`;修改该文件会触发重新上报。
60
+
61
+ 后台服务会补充继承用户登录终端配置的 HTTP / HTTPS / SOCKS / NO_PROXY 环境,保持模型可见范围一致;后台进程已有的显式配置优先,代理值不写入诊断日志。
62
+
63
+ Echo 工位中选择“默认”并保存会清除 Echo 覆盖值。设备执行权限为完整权限时,无确认启动命令为:
64
+
65
+ ```sh
66
+ kiro-cli chat --no-interactive --trust-all-tools --model gpt-5.6-luna --effort high -- 'test'
67
+ ```
68
+
69
+ 受限权限仅信任 `@doer/echo_report_task_progress`。Kiro 的 `doer` MCP 配置需指向 Echo `/mcp` 并使用有效 Echo Access Token;CLI 登录与 MCP 凭证分别校验。
70
+
71
+ ### 代理配置项
72
+
57
73
  优先级:环境变量 > 配置文件(`enroll` 写入,权限 0600)> 默认值。
58
74
 
59
75
  | 环境变量 | 配置文件键 | 默认 | 说明 |
@@ -20324,6 +20324,8 @@ import { spawn as spawn2 } from "node:child_process";
20324
20324
  import { spawn } from "node:child_process";
20325
20325
  import { delimiter as delimiter2 } from "node:path";
20326
20326
  var DELIMITER = "__ORCA_SHELL_PATH__";
20327
+ var PROXY_DELIMITER = "__ECHO_SHELL_PROXY__";
20328
+ var PROXY_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"];
20327
20329
  var SPAWN_TIMEOUT_MS = 5e3;
20328
20330
  var ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
20329
20331
  var cached2 = null;
@@ -20357,9 +20359,28 @@ function parseCapturedPath(stdout) {
20357
20359
  )
20358
20360
  ];
20359
20361
  }
20362
+ function parseCapturedProxy(stdout) {
20363
+ const start = stdout.indexOf(PROXY_DELIMITER);
20364
+ const end = stdout.indexOf(PROXY_DELIMITER, start + PROXY_DELIMITER.length);
20365
+ if (start < 0 || end < 0) return {};
20366
+ const values = stdout.slice(start + PROXY_DELIMITER.length, end).split("\0");
20367
+ return Object.fromEntries(PROXY_KEYS.flatMap((key, index) => values[index] ? [[key, values[index]]] : []));
20368
+ }
20369
+ function mergeShellProxyEnvironment(hydration, baseline = process.env) {
20370
+ const environment = { ...baseline };
20371
+ if (!hydration.ok) return environment;
20372
+ for (const key of PROXY_KEYS.slice(0, 4)) {
20373
+ const upper = key.toUpperCase();
20374
+ if (baseline[key] !== void 0 || baseline[upper] !== void 0) continue;
20375
+ const value = hydration.proxyEnv?.[key] ?? hydration.proxyEnv?.[upper];
20376
+ if (value) environment[key] = value;
20377
+ }
20378
+ return environment;
20379
+ }
20360
20380
  function spawnShellAndReadPath(shell) {
20361
20381
  return new Promise((resolve7) => {
20362
- const command = `printf '%s' '${DELIMITER}'; printf '%s' "$PATH"; printf '%s' '${DELIMITER}'`;
20382
+ const proxyValues = PROXY_KEYS.map((key) => `"\${${key}-}"`).join(" ");
20383
+ const command = `printf '%s' '${DELIMITER}'; printf '%s' "$PATH"; printf '%s' '${DELIMITER}'; printf '%s' '${PROXY_DELIMITER}'; printf '%s\\0' ${proxyValues}; printf '%s' '${PROXY_DELIMITER}'`;
20363
20384
  let finished = false;
20364
20385
  let stdout = "";
20365
20386
  let timer = null;
@@ -20408,7 +20429,7 @@ function spawnShellAndReadPath(shell) {
20408
20429
  finish({ segments: [], ok: false, failureReason: "empty_path" });
20409
20430
  return;
20410
20431
  }
20411
- finish({ segments, ok: true, failureReason: "none" });
20432
+ finish({ segments, proxyEnv: parseCapturedProxy(stdout), ok: true, failureReason: "none" });
20412
20433
  };
20413
20434
  child.stdout.on("data", onStdoutData);
20414
20435
  child.on("error", onError);
@@ -20805,6 +20826,45 @@ var grokProvider = {
20805
20826
  };
20806
20827
 
20807
20828
  // src/providers/cli/kiro.ts
20829
+ import { execFile, execFileSync } from "node:child_process";
20830
+ import { promisify } from "node:util";
20831
+ var execFileAsync = promisify(execFile);
20832
+ function isNoiseLine(text) {
20833
+ if (!text) return true;
20834
+ if (text.startsWith("\u22EE") || text.startsWith("\u25B8") || text.startsWith("\u25CF")) return true;
20835
+ if (/^Running tool\b/.test(text)) return true;
20836
+ if (/^- Completed in\b/.test(text)) return true;
20837
+ if (/^All tools are now trusted\b/.test(text)) return true;
20838
+ if (/^Agents can sometimes do unexpected things\b/.test(text)) return true;
20839
+ if (/^Learn more at\b/.test(text)) return true;
20840
+ return false;
20841
+ }
20842
+ function kiroLaunch(args) {
20843
+ return resolveExecutable("kiro-cli", args, providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
20844
+ }
20845
+ var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
20846
+ function parseSessions(stdout) {
20847
+ const parsed = JSON.parse(stdout);
20848
+ return parsed.flatMap((entry) => entry.sessions ?? []).filter((entry) => entry.source !== "v3" && !entry.sessionId?.startsWith("sess_")).sort((a, b) => Date.parse(b.updatedAt ?? "") - Date.parse(a.updatedAt ?? ""));
20849
+ }
20850
+ async function latestSessionId(workdir) {
20851
+ const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20852
+ try {
20853
+ const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: 1e4, maxBuffer: 4 * 1024 * 1024 });
20854
+ return str(parseSessions(stdout)[0]?.sessionId);
20855
+ } catch {
20856
+ return void 0;
20857
+ }
20858
+ }
20859
+ function resumableSession(sessionId, workdir) {
20860
+ const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20861
+ try {
20862
+ const stdout = execFileSync(executable, args, { cwd: workdir, env, timeout: 1e4, maxBuffer: 4 * 1024 * 1024, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
20863
+ return parseSessions(stdout).some((entry) => entry.sessionId === sessionId);
20864
+ } catch {
20865
+ return false;
20866
+ }
20867
+ }
20808
20868
  var kiroProvider = {
20809
20869
  id: "kiro",
20810
20870
  buildLaunch(request) {
@@ -20813,35 +20873,56 @@ var kiroProvider = {
20813
20873
  else args.push("--trust-tools=@doer/echo_report_task_progress");
20814
20874
  if (request.model) args.push("--model", request.model);
20815
20875
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20816
- if (request.sessionId) args.push("--resume-id", request.sessionId);
20817
- args.push(request.prompt);
20818
- return resolveExecutable("kiro-cli", args, providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
20876
+ if (request.sessionId && resumableSession(request.sessionId, request.workdir)) args.push("--resume-id", request.sessionId);
20877
+ args.push("--", request.prompt);
20878
+ return kiroLaunch(args);
20879
+ },
20880
+ async inspectExit(context) {
20881
+ const inspection = {};
20882
+ const businessError = kiroStderrError(context.stderr);
20883
+ if (businessError) inspection.turnError = businessError;
20884
+ if (!inspection.turnError) {
20885
+ const sessionId = await latestSessionId(context.workdir);
20886
+ if (sessionId) inspection.sessionId = sessionId;
20887
+ }
20888
+ return inspection;
20819
20889
  },
20820
20890
  parseLine(line) {
20891
+ if (/^\s*⋮/.test(line)) return { display: [] };
20821
20892
  const event = tryJson(line);
20822
20893
  if (event) {
20823
- const sessionId2 = str(event.session_id) ?? str(event.sessionId);
20894
+ const sessionId = str(event.session_id) ?? str(event.sessionId);
20824
20895
  const message = str(event.response) ?? str(event.message) ?? str(event.text);
20825
20896
  const error62 = typeof event.error === "string" ? event.error : event.error && typeof event.error === "object" ? str(event.error.message) : void 0;
20826
20897
  const type = str(event.type) ?? "";
20827
20898
  return {
20828
- ...sessionId2 ? { sessionId: sessionId2 } : {},
20899
+ ...sessionId ? { sessionId } : {},
20829
20900
  ...message ? { message } : {},
20830
20901
  ...error62 ? { turnError: error62 } : {},
20831
20902
  ...message && (type === "result" || type === "turn.completed") ? { turnCompleted: true } : {},
20832
20903
  display: message ? textRows("\u203A ", message) : error62 ? [`\u2717 ${error62}`] : [line]
20833
20904
  };
20834
20905
  }
20835
- const sessionId = line.match(/\b(?:session[_ ]id|sessionId)\s*[:=]\s*([\w.-]+)/i)?.[1];
20836
- const text = line.trim();
20837
- const isSessionLine = Boolean(sessionId && /\b(?:session[_ ]id|sessionId)\s*[:=]/i.test(line));
20838
- return {
20839
- ...sessionId ? { sessionId } : {},
20840
- ...!isSessionLine && text ? { message: text } : {},
20841
- display: text ? [line] : []
20842
- };
20906
+ const text = line.replace(/^λ↯\s*/, "").trim();
20907
+ if (!text) return { display: [] };
20908
+ const answer = text.match(/^>\s?(.*)$/);
20909
+ if (answer && answer[1]?.trim()) {
20910
+ return { message: answer[1].trim(), display: [`\u203A ${answer[1].trim()}`] };
20911
+ }
20912
+ if (isNoiseLine(text)) return { display: [] };
20913
+ return { display: [line.replace(/^λ↯\s*/, "")] };
20843
20914
  }
20844
20915
  };
20916
+ function kiroStderrError(stderrLines) {
20917
+ const text = stderrLines.join("\n");
20918
+ if (/Monthly request limit reached|request limit reached/i.test(text)) {
20919
+ return "Kiro \u672C\u6708\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u5347\u7EA7\u5957\u9910\u6216\u7B49\u5F85\u989D\u5EA6\u91CD\u7F6E\u540E\u518D\u8BD5";
20920
+ }
20921
+ if (/not logged in|please log in|authentication required|unauthorized/i.test(text)) {
20922
+ return "Kiro CLI \u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55\u540E\u518D\u8BD5";
20923
+ }
20924
+ return void 0;
20925
+ }
20845
20926
 
20846
20927
  // src/providers/cli/opencode.ts
20847
20928
  var opencodeProvider = {
@@ -21370,13 +21451,102 @@ import { createHash } from "node:crypto";
21370
21451
  import { stat } from "node:fs/promises";
21371
21452
 
21372
21453
  // src/providers/model-catalog.ts
21373
- import { spawn as spawn4 } from "node:child_process";
21454
+ import { spawn as spawn5 } from "node:child_process";
21374
21455
  import { readFile as readFile3 } from "node:fs/promises";
21375
21456
  import { homedir as homedir5 } from "node:os";
21376
21457
  import { isAbsolute, join as join6, resolve as resolve2 } from "node:path";
21458
+
21459
+ // src/providers/kiro-models.ts
21460
+ import { spawn as spawn4 } from "node:child_process";
21461
+ import { createInterface } from "node:readline";
21462
+ async function readKiroNativeModels(launch, cwd, options = {}) {
21463
+ const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, stdio: ["pipe", "pipe", "pipe"] });
21464
+ const lines = createInterface({ input: child.stdout });
21465
+ let nextId = 0;
21466
+ let failure2;
21467
+ const pending = /* @__PURE__ */ new Map();
21468
+ const fail = (error62) => {
21469
+ failure2 = error62;
21470
+ for (const request2 of pending.values()) request2.reject(error62);
21471
+ pending.clear();
21472
+ };
21473
+ const timer = setTimeout(() => {
21474
+ fail(new Error("Kiro \u6A21\u578B\u548C\u63A8\u7406\u6863\u4F4D\u8BFB\u53D6\u8D85\u65F6"));
21475
+ child.kill("SIGKILL");
21476
+ }, options.timeoutMs ?? 2e4);
21477
+ child.once("error", fail);
21478
+ child.stdin.on("error", fail);
21479
+ child.once("close", () => fail(new Error("Kiro \u6A21\u578B\u67E5\u8BE2\u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u8BF7\u786E\u8BA4\u672C\u673A CLI \u5DF2\u767B\u5F55\u4E14\u652F\u6301 ACP")));
21480
+ child.stderr.resume();
21481
+ lines.on("line", (line) => {
21482
+ let message;
21483
+ try {
21484
+ message = JSON.parse(line);
21485
+ } catch {
21486
+ return;
21487
+ }
21488
+ if (typeof message.id !== "number") return;
21489
+ if (message.method) {
21490
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Model discovery does not support client requests" } }) + "\n");
21491
+ return;
21492
+ }
21493
+ const request2 = pending.get(message.id);
21494
+ if (!request2) return;
21495
+ pending.delete(message.id);
21496
+ if (message.error) request2.reject(new Error(`Kiro \u6A21\u578B\u67E5\u8BE2\u5931\u8D25\uFF1A${message.error.message || "ACP \u8BF7\u6C42\u5931\u8D25"}`));
21497
+ else request2.resolve(message.result);
21498
+ });
21499
+ const request = (method, params) => new Promise((resolve7, reject) => {
21500
+ if (failure2) {
21501
+ reject(failure2);
21502
+ return;
21503
+ }
21504
+ const id = ++nextId;
21505
+ pending.set(id, { resolve: (value) => resolve7(value), reject });
21506
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
21507
+ });
21508
+ try {
21509
+ await request("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "echo-model-catalog", version: "1" } });
21510
+ const session = await request("session/new", { cwd, mcpServers: [] });
21511
+ const available = options.catalog?.models.map((model) => ({ modelId: model.model_id, name: model.model_name, ...model.description ? { description: model.description } : {} })) ?? session.models?.availableModels;
21512
+ if (!session.sessionId || !Array.isArray(available) || available.length === 0) throw new Error("Kiro \u6CA1\u6709\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u767B\u5F55\u72B6\u6001");
21513
+ const defaultModel = options.catalog?.default_model ?? session.models?.currentModelId;
21514
+ const catalog = { ...defaultModel ? { default_model: defaultModel } : {}, models: [] };
21515
+ for (const model of available) {
21516
+ if (typeof model.modelId !== "string" || !model.modelId.trim()) continue;
21517
+ await request("session/set_model", { sessionId: session.sessionId, modelId: model.modelId });
21518
+ const result = await request("_kiro.dev/commands/options", { sessionId: session.sessionId, command: "effort", partial: "" });
21519
+ if (!Array.isArray(result.options)) throw new Error("Kiro \u6CA1\u6709\u8FD4\u56DE\u63A8\u7406\u6863\u4F4D\u9009\u9879\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A CLI");
21520
+ const options2 = result.options.filter((option) => typeof option.value === "string" && /^[a-z]+$/.test(option.value) && option.value !== "default");
21521
+ const active = options2.find((option) => option.current || /\[active\]/i.test(option.label ?? ""));
21522
+ catalog.models.push({
21523
+ model_id: model.modelId,
21524
+ model_name: model.name || model.modelId,
21525
+ ...model.description ? { description: model.description } : {},
21526
+ supported_reasoning_efforts: [...new Set(options2.map((option) => option.value))],
21527
+ ...active?.value ? { default_reasoning_effort: active.value } : {}
21528
+ });
21529
+ }
21530
+ return catalog;
21531
+ } finally {
21532
+ clearTimeout(timer);
21533
+ lines.close();
21534
+ child.stdin.end();
21535
+ child.kill("SIGTERM");
21536
+ const killTimer = setTimeout(() => {
21537
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
21538
+ }, 1e3);
21539
+ killTimer.unref();
21540
+ }
21541
+ }
21542
+
21543
+ // src/providers/model-catalog.ts
21377
21544
  function stringValue(value) {
21378
21545
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
21379
21546
  }
21547
+ function objectValue(value) {
21548
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21549
+ }
21380
21550
  var CLAUDE_REASONING_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
21381
21551
  function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
21382
21552
  const source = settings && typeof settings === "object" ? settings : {};
@@ -21411,6 +21581,7 @@ var codexHome = () => process.env.CODEX_HOME?.trim() || join6(homedir5(), ".code
21411
21581
  var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join6(homedir5(), ".gemini");
21412
21582
  var grokHome = () => process.env.GROK_HOME?.trim() || join6(homedir5(), ".grok");
21413
21583
  var opencodeHome = () => join6(process.env.XDG_CONFIG_HOME?.trim() || join6(homedir5(), ".config"), "opencode");
21584
+ var kiroHome = () => join6(homedir5(), ".kiro");
21414
21585
  async function readClaudeModelCatalog() {
21415
21586
  const home = claudeHome();
21416
21587
  const content = await readFile3(join6(home, "settings.json"), "utf8").catch(() => "");
@@ -21491,8 +21662,9 @@ async function readCodexModelCatalog() {
21491
21662
  if (defaultReasoningEffort) catalog.default_reasoning_effort = defaultReasoningEffort;
21492
21663
  return catalog;
21493
21664
  }
21494
- function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
21665
+ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date()).toISOString(), settings = {}) {
21495
21666
  const source = payload && typeof payload === "object" ? payload : {};
21667
+ const defaults = objectValue(settings["chat.modelDefaults"] ?? objectValue(settings.chat).modelDefaults);
21496
21668
  const models = Array.isArray(source.models) ? source.models.flatMap((item) => {
21497
21669
  const entry = item && typeof item === "object" ? item : {};
21498
21670
  const id = stringValue(entry.model_id) ?? stringValue(entry.model_name);
@@ -21500,8 +21672,11 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
21500
21672
  const model = {
21501
21673
  id,
21502
21674
  name: stringValue(entry.model_name) ?? id,
21503
- supported_reasoning_efforts: []
21675
+ supported_reasoning_efforts: Array.isArray(entry.supported_reasoning_efforts) ? [...new Set(entry.supported_reasoning_efforts.flatMap((value) => stringValue(value) ? [stringValue(value)] : []))].filter((value) => value !== "default") : []
21504
21676
  };
21677
+ const saved = objectValue(defaults[id]);
21678
+ const effort = [objectValue(saved.reasoning).effort, objectValue(saved.output_config).effort, saved.effort, entry.default_reasoning_effort].map(stringValue).find((value) => Boolean(value && model.supported_reasoning_efforts.includes(value)));
21679
+ if (effort) model.default_reasoning_effort = effort;
21505
21680
  const description = stringValue(entry.description);
21506
21681
  if (description) model.description = description;
21507
21682
  return [model];
@@ -21513,12 +21688,14 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
21513
21688
  };
21514
21689
  const defaultModel = stringValue(source.default_model);
21515
21690
  if (defaultModel) catalog.default_model = defaultModel;
21691
+ const defaultEffort = models.find((model) => model.id === defaultModel)?.default_reasoning_effort;
21692
+ if (defaultEffort) catalog.default_reasoning_effort = defaultEffort;
21516
21693
  return catalog;
21517
21694
  }
21518
21695
  var MODEL_LIST_TIMEOUT_MS = 2e4;
21519
- function runModelListCommand(executable, args, label) {
21696
+ function runModelListCommand(executable, args, label, environment) {
21520
21697
  return new Promise((resolve7, reject) => {
21521
- const child = spawn4(executable, [...args], { shell: false, stdio: ["ignore", "pipe", "pipe"] });
21698
+ const child = spawn5(executable, [...args], { shell: false, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
21522
21699
  let stdout = "";
21523
21700
  let stderr = "";
21524
21701
  const timer = setTimeout(() => {
@@ -21545,15 +21722,33 @@ function runModelListCommand(executable, args, label) {
21545
21722
  });
21546
21723
  }
21547
21724
  async function readKiroModelCatalog() {
21548
- const executable = resolveCliCommand("kiro-cli");
21549
- const output2 = await runModelListCommand(executable, ["chat", "--list-models", "--format", "json"], "kiro-cli");
21550
- let payload;
21725
+ const environment = mergeShellProxyEnvironment(await hydrateShellPath(), providerEnvironment());
21726
+ const override = process.env.TOC_OCRA_KIRO_PATH;
21727
+ const listLaunch = resolveExecutable("kiro-cli", ["chat", "--list-models", "--format", "json"], environment, override);
21728
+ const output2 = await runModelListCommand(listLaunch.executable, listLaunch.args, "kiro-cli", environment);
21729
+ let listed;
21730
+ try {
21731
+ listed = parseKiroModelCatalog(JSON.parse(output2));
21732
+ } catch {
21733
+ throw new Error("Kiro \u8FD4\u56DE\u7684\u6A21\u578B\u5217\u8868\u4E0D\u662F\u6709\u6548 JSON");
21734
+ }
21735
+ if (listed.models.length === 0) throw new Error("Kiro \u6CA1\u6709\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u767B\u5F55\u72B6\u6001");
21736
+ const base = {
21737
+ ...listed.default_model ? { default_model: listed.default_model } : {},
21738
+ models: listed.models.map((model) => ({ model_id: model.id, model_name: model.name, ...model.description ? { description: model.description } : {}, supported_reasoning_efforts: [] }))
21739
+ };
21740
+ const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
21741
+ const [payload, content] = await Promise.all([
21742
+ readKiroNativeModels(launch, homedir5(), { catalog: base }),
21743
+ readFile3(join6(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21744
+ ]);
21745
+ let settings;
21551
21746
  try {
21552
- payload = JSON.parse(output2);
21747
+ settings = JSON.parse(content);
21553
21748
  } catch {
21554
- throw new Error("kiro-cli \u8FD4\u56DE\u7684\u6A21\u578B\u76EE\u5F55\u4E0D\u662F\u6709\u6548 JSON");
21749
+ throw new Error("Kiro \u672C\u673A cli.json \u4E0D\u662F\u6709\u6548 JSON");
21555
21750
  }
21556
- return parseKiroModelCatalog(payload);
21751
+ return parseKiroModelCatalog(payload, (/* @__PURE__ */ new Date()).toISOString(), settings ?? {});
21557
21752
  }
21558
21753
  function parseEnvFile(content) {
21559
21754
  const values = {};
@@ -21686,7 +21881,7 @@ var MODEL_SOURCES = {
21686
21881
  },
21687
21882
  gemini: { read: readGeminiModelCatalog, watchFiles: () => [join6(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
21688
21883
  grok: { read: readGrokModelCatalog, watchFiles: () => [join6(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
21689
- kiro: { read: readKiroModelCatalog, watchFiles: () => [], refreshEveryMs: TEN_MINUTES },
21884
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join6(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
21690
21885
  opencode: {
21691
21886
  read: readOpencodeModelCatalog,
21692
21887
  watchFiles: () => [join6(opencodeHome(), "opencode.json"), join6(opencodeHome(), "opencode.jsonc")],
@@ -21747,14 +21942,14 @@ var ModelCatalogCollector = class {
21747
21942
  };
21748
21943
 
21749
21944
  // src/providers/codex-quota.ts
21750
- import { spawn as spawn5 } from "node:child_process";
21751
- import { createInterface } from "node:readline";
21945
+ import { spawn as spawn6 } from "node:child_process";
21946
+ import { createInterface as createInterface2 } from "node:readline";
21752
21947
  async function readCodexQuotaWindows() {
21753
21948
  const launch = resolveExecutable("codex", ["app-server", "--stdio"], providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
21754
- const child = spawn5(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"] });
21949
+ const child = spawn6(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"] });
21755
21950
  let nextId = 0;
21756
21951
  const pending = /* @__PURE__ */ new Map();
21757
- const lines = createInterface({ input: child.stdout });
21952
+ const lines = createInterface2({ input: child.stdout });
21758
21953
  const rejectPending = (error62) => {
21759
21954
  for (const waiter of pending.values()) waiter.reject(error62);
21760
21955
  pending.clear();
@@ -21974,16 +22169,16 @@ async function controlTbSwitch(payload) {
21974
22169
  }
21975
22170
 
21976
22171
  // src/runs/orphan-registry.ts
21977
- import { execFile as execFile2 } from "node:child_process";
22172
+ import { execFile as execFile3 } from "node:child_process";
21978
22173
  import { mkdir as mkdir3, readFile as readFile5, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
21979
22174
  import { basename, dirname as dirname5 } from "node:path";
21980
22175
 
21981
22176
  // src/runs/process-tree.ts
21982
- import { execFile, spawn as spawn6 } from "node:child_process";
22177
+ import { execFile as execFile2, spawn as spawn7 } from "node:child_process";
21983
22178
  var KILL_GRACE_MS = 3e3;
21984
22179
  function readProcessTable() {
21985
22180
  return new Promise((resolve7) => {
21986
- execFile("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
22181
+ execFile2("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
21987
22182
  if (error62) return resolve7([]);
21988
22183
  resolve7(stdout.split("\n").flatMap((line) => {
21989
22184
  const [pid, ppid] = line.trim().split(/\s+/).map(Number);
@@ -22025,7 +22220,7 @@ async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
22025
22220
  if (!Number.isInteger(rootPid) || rootPid <= 1) return;
22026
22221
  if (process.platform === "win32") {
22027
22222
  await new Promise((resolve7) => {
22028
- const child = spawn6("taskkill", ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
22223
+ const child = spawn7("taskkill", ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
22029
22224
  child.once("error", () => resolve7());
22030
22225
  child.once("close", () => resolve7());
22031
22226
  });
@@ -22093,17 +22288,17 @@ var OrphanRegistry = class {
22093
22288
  function commandOf(pid) {
22094
22289
  if (process.platform === "win32") return Promise.resolve(void 0);
22095
22290
  return new Promise((resolve7) => {
22096
- execFile2("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
22291
+ execFile3("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
22097
22292
  resolve7(error62 ? void 0 : stdout.trim() || void 0);
22098
22293
  });
22099
22294
  });
22100
22295
  }
22101
22296
 
22102
22297
  // src/runs/run-supervisor.ts
22103
- import { spawn as spawn7 } from "node:child_process";
22298
+ import { spawn as spawn8 } from "node:child_process";
22104
22299
  import { mkdir as mkdir5, realpath as realpath2, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
22105
22300
  import { basename as basename3, isAbsolute as isAbsolute3, join as join9, relative as relative2, resolve as resolve3 } from "node:path";
22106
- import { createInterface as createInterface2 } from "node:readline";
22301
+ import { createInterface as createInterface3 } from "node:readline";
22107
22302
 
22108
22303
  // src/session/terminal-line-sanitizer.ts
22109
22304
  var TERMINAL_ESCAPE = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
@@ -22435,7 +22630,7 @@ var RunSupervisor = class {
22435
22630
  });
22436
22631
  let child;
22437
22632
  try {
22438
- child = spawn7(launch.executable, launch.args, {
22633
+ child = spawn8(launch.executable, launch.args, {
22439
22634
  cwd: workdir,
22440
22635
  env: launch.env,
22441
22636
  detached: process.platform !== "win32",
@@ -22462,6 +22657,7 @@ var RunSupervisor = class {
22462
22657
  child,
22463
22658
  pid: child.pid ?? 0,
22464
22659
  startedAt: Date.now(),
22660
+ workdir,
22465
22661
  sessionId: payload.session_id,
22466
22662
  finalMessage: "",
22467
22663
  turnCompleted: false,
@@ -22485,8 +22681,8 @@ var RunSupervisor = class {
22485
22681
  child.once("error", (error62) => {
22486
22682
  spawnError = error62.message;
22487
22683
  });
22488
- createInterface2({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
22489
- createInterface2({ input: child.stderr }).on("line", (line) => {
22684
+ createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
22685
+ createInterface3({ input: child.stderr }).on("line", (line) => {
22490
22686
  const clean = sanitizeTerminalLine(line);
22491
22687
  if (!clean.trim()) return;
22492
22688
  run.stderr.push(clean);
@@ -22563,6 +22759,15 @@ var RunSupervisor = class {
22563
22759
  if (run.eventTimer) clearTimeout(run.eventTimer);
22564
22760
  this.flushChatEvents(run);
22565
22761
  await run.eventTail;
22762
+ if (!run.chat && !run.cancelRequested && !spawnError && !run.timedOut && run.provider.inspectExit) {
22763
+ try {
22764
+ const inspection = await run.provider.inspectExit({ exitCode: code, stderr: run.stderr, workdir: run.workdir, sessionId: run.sessionId });
22765
+ if (inspection.turnError && !run.turnError) run.turnError = sanitizeTerminalLine(inspection.turnError);
22766
+ if (inspection.sessionId && inspection.sessionId !== run.sessionId) run.sessionId = inspection.sessionId;
22767
+ } catch (error62) {
22768
+ this.logger.warn("inspect-exit-failed", { runId: run.runId, error: errorMessage(error62) });
22769
+ }
22770
+ }
22566
22771
  const durationMs = Date.now() - run.startedAt;
22567
22772
  let report;
22568
22773
  if (run.cancelRequested) {
@@ -22899,7 +23104,7 @@ async function listDirectory(requested, allowedRoots) {
22899
23104
  }
22900
23105
 
22901
23106
  // src/workspace/workspace-manager.ts
22902
- import { spawn as spawn8 } from "node:child_process";
23107
+ import { spawn as spawn9 } from "node:child_process";
22903
23108
  import { chmod as chmod3, mkdir as mkdir6, mkdtemp, opendir, realpath as realpath4, rm as rm3, stat as stat4, writeFile as writeFile6 } from "node:fs/promises";
22904
23109
  import { homedir as homedir8, tmpdir } from "node:os";
22905
23110
  import { isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5 } from "node:path";
@@ -23243,7 +23448,7 @@ var WorkspaceManager = class {
23243
23448
  }
23244
23449
  runGit(args, cwd, timeoutSeconds, allowFailure = false, environment) {
23245
23450
  return new Promise((resolveCommand, rejectCommand) => {
23246
- const child = spawn8("git", args, {
23451
+ const child = spawn9("git", args, {
23247
23452
  cwd,
23248
23453
  env: environment ?? process.env,
23249
23454
  shell: false,
@@ -23950,6 +24155,7 @@ function agentVersion() {
23950
24155
  async function runService(options = {}) {
23951
24156
  const hydration = await hydrateShellPath();
23952
24157
  if (hydration.ok) mergePathSegments(hydration.segments);
24158
+ Object.assign(process.env, mergeShellProxyEnvironment(hydration));
23953
24159
  const service = new AgentService(agentVersion(), options);
23954
24160
  await service.start();
23955
24161
  let shuttingDown = false;
@@ -2,11 +2,12 @@ import { join } from 'node:path';
2
2
  import { loadAgentConfig } from './config.js';
3
3
  import { AgentRuntime } from './runtime/agent-runtime.js';
4
4
  import { agentVersion } from './runtime/run-service.js';
5
- import { hydrateShellPath, mergePathSegments } from './runtime/cli/hydrate-shell-path.js';
5
+ import { hydrateShellPath, mergePathSegments, mergeShellProxyEnvironment } from './runtime/cli/hydrate-shell-path.js';
6
6
  // A separate leased channel permits upgrading chat without restarting active MCP tasks.
7
7
  const hydration = await hydrateShellPath();
8
8
  if (hydration.ok)
9
9
  mergePathSegments(hydration.segments);
10
+ Object.assign(process.env, mergeShellProxyEnvironment(hydration));
10
11
  const base = loadAgentConfig();
11
12
  const config = { ...base, logFile: join(base.dataDir, 'logs', 'cli-chat.log') };
12
13
  const runtime = new AgentRuntime(config, agentVersion(), undefined, true);
@@ -1 +1 @@
1
- {"version":3,"file":"cli-chat-worker.js","sourceRoot":"","sources":["../../src/cli-chat-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAA;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AACvD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAA;AAEzF,wFAAwF;AACxF,MAAM,SAAS,GAAG,MAAM,gBAAgB,EAAE,CAAA;AAC1C,IAAI,SAAS,CAAC,EAAE;IAAE,iBAAiB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAA;AACvD,MAAM,IAAI,GAAG,eAAe,EAAE,CAAA;AAC9B,MAAM,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,CAAA;AAC/E,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;AACzE,IAAI,QAAQ,GAAG,KAAK,CAAA;AACpB,KAAK,UAAU,IAAI;IACjB,IAAI,QAAQ;QAAE,OAAM;IACpB,QAAQ,GAAG,IAAI,CAAA;IACf,MAAM,OAAO,CAAC,IAAI,EAAE,CAAA;IACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC;AACD,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAA;AACzC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAA;AAC1C,MAAM,OAAO,CAAC,KAAK,EAAE,CAAA"}
1
+ {"version":3,"file":"cli-chat-worker.js","sourceRoot":"","sources":["../../src/cli-chat-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAA;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AACvD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAA;AAErH,wFAAwF;AACxF,MAAM,SAAS,GAAG,MAAM,gBAAgB,EAAE,CAAA;AAC1C,IAAI,SAAS,CAAC,EAAE;IAAE,iBAAiB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAA;AACvD,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,0BAA0B,CAAC,SAAS,CAAC,CAAC,CAAA;AACjE,MAAM,IAAI,GAAG,eAAe,EAAE,CAAA;AAC9B,MAAM,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,CAAA;AAC/E,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;AACzE,IAAI,QAAQ,GAAG,KAAK,CAAA;AACpB,KAAK,UAAU,IAAI;IACjB,IAAI,QAAQ;QAAE,OAAM;IACpB,QAAQ,GAAG,IAAI,CAAA;IACf,MAAM,OAAO,CAAC,IAAI,EAAE,CAAA;IACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC;AACD,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAA;AACzC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAA;AAC1C,MAAM,OAAO,CAAC,KAAK,EAAE,CAAA"}
@@ -1,3 +1,8 @@
1
1
  import type { HeadlessProvider } from '../provider.js';
2
- /** Runs one Kiro CLI turn without opening the interactive terminal UI. */
3
2
  export declare const kiroProvider: HeadlessProvider;
3
+ /**
4
+ * True business-error text to surface when Kiro exits 0 but did nothing
5
+ * (e.g. monthly quota reached, sign-in required). Returns the user-facing
6
+ * reason, or undefined when stderr only holds the trust banner / chrome.
7
+ */
8
+ export declare function kiroStderrError(stderrLines: readonly string[]): string | undefined;