toc-ocra 0.2.37 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +147 -139
  3. package/assets/icon.svg +1 -1
  4. package/dist/cli/cli.mjs +3211 -2573
  5. package/dist/plugin/renderer.css.map +1 -1
  6. package/dist/plugin/renderer.js.map +1 -1
  7. package/dist/service/agent.mjs +1477 -963
  8. package/dist/src/config.d.ts +4 -2
  9. package/dist/src/config.js +6 -6
  10. package/dist/src/config.js.map +1 -1
  11. package/dist/src/health/server.js +8 -8
  12. package/dist/src/index.js +50 -3
  13. package/dist/src/index.js.map +1 -1
  14. package/dist/src/providers/acp/acp-agents.d.ts +5 -0
  15. package/dist/src/providers/acp/acp-agents.js +55 -0
  16. package/dist/src/providers/acp/acp-agents.js.map +1 -0
  17. package/dist/src/providers/acp/acp-driver.d.ts +60 -0
  18. package/dist/src/providers/acp/acp-driver.js +317 -0
  19. package/dist/src/providers/acp/acp-driver.js.map +1 -0
  20. package/dist/src/providers/chat/codex-app-server.js +3 -2
  21. package/dist/src/providers/chat/codex-app-server.js.map +1 -1
  22. package/dist/src/providers/chat/index.d.ts +4 -2
  23. package/dist/src/providers/chat/index.js +7 -8
  24. package/dist/src/providers/chat/index.js.map +1 -1
  25. package/dist/src/providers/cli/claude.js +6 -2
  26. package/dist/src/providers/cli/claude.js.map +1 -1
  27. package/dist/src/providers/cli/codex.js +5 -1
  28. package/dist/src/providers/cli/codex.js.map +1 -1
  29. package/dist/src/providers/cli/gemini.js +3 -1
  30. package/dist/src/providers/cli/gemini.js.map +1 -1
  31. package/dist/src/providers/cli/grok.js +3 -1
  32. package/dist/src/providers/cli/grok.js.map +1 -1
  33. package/dist/src/providers/cli/kiro.d.ts +10 -4
  34. package/dist/src/providers/cli/kiro.js +37 -37
  35. package/dist/src/providers/cli/kiro.js.map +1 -1
  36. package/dist/src/providers/cli/opencode.js +3 -1
  37. package/dist/src/providers/cli/opencode.js.map +1 -1
  38. package/dist/src/providers/cli-failure.d.ts +66 -0
  39. package/dist/src/providers/cli-failure.js +128 -0
  40. package/dist/src/providers/cli-failure.js.map +1 -0
  41. package/dist/src/providers/cli-specs.d.ts +58 -0
  42. package/dist/src/providers/cli-specs.js +37 -0
  43. package/dist/src/providers/cli-specs.js.map +1 -0
  44. package/dist/src/providers/codex-quota.js +3 -2
  45. package/dist/src/providers/codex-quota.js.map +1 -1
  46. package/dist/src/providers/kiro-quota.js +3 -2
  47. package/dist/src/providers/kiro-quota.js.map +1 -1
  48. package/dist/src/providers/model-catalog-collector.d.ts +1 -1
  49. package/dist/src/providers/model-catalog-collector.js +3 -3
  50. package/dist/src/providers/model-catalog-collector.js.map +1 -1
  51. package/dist/src/providers/model-catalog.d.ts +0 -2
  52. package/dist/src/providers/model-catalog.js +12 -13
  53. package/dist/src/providers/model-catalog.js.map +1 -1
  54. package/dist/src/providers/provider.d.ts +21 -45
  55. package/dist/src/providers/provider.js +6 -4
  56. package/dist/src/providers/provider.js.map +1 -1
  57. package/dist/src/providers/quota-reader.d.ts +1 -1
  58. package/dist/src/providers/quota-reader.js +5 -10
  59. package/dist/src/providers/quota-reader.js.map +1 -1
  60. package/dist/src/providers/registry.d.ts +46 -9
  61. package/dist/src/providers/registry.js +73 -21
  62. package/dist/src/providers/registry.js.map +1 -1
  63. package/dist/src/runs/run-recorder.d.ts +32 -0
  64. package/dist/src/runs/run-recorder.js +27 -0
  65. package/dist/src/runs/run-recorder.js.map +1 -0
  66. package/dist/src/runs/run-supervisor.d.ts +13 -0
  67. package/dist/src/runs/run-supervisor.js +124 -57
  68. package/dist/src/runs/run-supervisor.js.map +1 -1
  69. package/dist/src/smoke/cli-smoke.d.ts +30 -0
  70. package/dist/src/smoke/cli-smoke.js +92 -0
  71. package/dist/src/smoke/cli-smoke.js.map +1 -0
  72. package/dist/src/types/protocol.d.ts +3 -0
  73. package/dist/src/types/protocol.js.map +1 -1
  74. package/locales/en.json +202 -202
  75. package/locales/zh-CN.json +202 -202
  76. package/package.json +102 -102
  77. package/scripts/installation.cjs +260 -239
  78. package/scripts/postinstall.cjs +22 -22
  79. package/scripts/service.mjs +253 -253
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
 
8
8
  // src/plugin-service.ts
9
9
  import { existsSync as existsSync6 } from "node:fs";
10
- import { delimiter as delimiter5, join as join15 } from "node:path";
10
+ import { delimiter as delimiter5, join as join16 } from "node:path";
11
11
 
12
12
  // src/config.ts
13
13
  import { randomUUID } from "node:crypto";
@@ -16669,8 +16669,8 @@ function rewriteKeyNames(ctx) {
16669
16669
  bySchema.set(entry.schema, entry);
16670
16670
  }
16671
16671
  const rewrites = /* @__PURE__ */ new Map();
16672
- for (const record4 of pendingRecords.get(ctx) ?? []) {
16673
- const seen = ctx.seen.get(record4);
16672
+ for (const record5 of pendingRecords.get(ctx) ?? []) {
16673
+ const seen = ctx.seen.get(record5);
16674
16674
  const names = (seen?.def ?? seen?.schema)?.propertyNames;
16675
16675
  if (!names || names === true || rewrites.has(names))
16676
16676
  continue;
@@ -19743,8 +19743,8 @@ var FileConfigSchema = external_exports.object({
19743
19743
  /** Stable id of this installation; lets any server recognise the same computer. */
19744
19744
  machineId: external_exports.string().min(8).max(64).optional(),
19745
19745
  allowedRoots: external_exports.array(external_exports.string()).optional(),
19746
- maxConcurrentRuns: external_exports.number().int().positive().max(64).optional(),
19747
- maxRunSeconds: external_exports.number().int().positive().max(7 * 86400).optional(),
19746
+ maxConcurrentRuns: external_exports.number().int().min(0).max(64).optional(),
19747
+ maxRunSeconds: external_exports.number().int().min(0).max(7 * 86400).optional(),
19748
19748
  disableScript: external_exports.boolean().optional(),
19749
19749
  disableSql: external_exports.boolean().optional(),
19750
19750
  healthHost: external_exports.string().optional(),
@@ -19863,8 +19863,8 @@ function loadBaseConfig() {
19863
19863
  hostname: hostname3(),
19864
19864
  platform: platform(),
19865
19865
  allowedRoots: roots.map((root) => resolve(root)),
19866
- maxConcurrentRuns: envInt("TOC_OCRA_MAX_RUNS") ?? file2.maxConcurrentRuns ?? 4,
19867
- maxRunSeconds: envInt("TOC_OCRA_MAX_RUN_SECONDS") ?? file2.maxRunSeconds ?? 4 * 3600,
19866
+ maxConcurrentRuns: envInt("TOC_OCRA_MAX_RUNS") ?? file2.maxConcurrentRuns ?? 0,
19867
+ maxRunSeconds: envInt("TOC_OCRA_MAX_RUN_SECONDS") ?? file2.maxRunSeconds ?? 0,
19868
19868
  disableScript: envBool("TOC_OCRA_DISABLE_SCRIPT") ?? file2.disableScript ?? false,
19869
19869
  disableSql: envBool("TOC_OCRA_DISABLE_SQL") ?? file2.disableSql ?? false,
19870
19870
  dataDir: dataDir2,
@@ -20328,7 +20328,7 @@ function createDiagnosticLogger(filePath, options = {}) {
20328
20328
  }
20329
20329
 
20330
20330
  // src/providers/detection.ts
20331
- import { spawn as spawn3 } from "node:child_process";
20331
+ import { spawn as spawn6 } from "node:child_process";
20332
20332
 
20333
20333
  // src/runtime/cli/hydrate-shell-path.ts
20334
20334
  import { delimiter as delimiter3 } from "node:path";
@@ -20706,11 +20706,6 @@ function mergePathSegments(segments) {
20706
20706
  return added;
20707
20707
  }
20708
20708
 
20709
- // src/providers/cli/claude.ts
20710
- import { readFileSync as readFileSync5 } from "node:fs";
20711
- import { homedir as homedir4 } from "node:os";
20712
- import { join as join7 } from "node:path";
20713
-
20714
20709
  // src/providers/provider.ts
20715
20710
  import { realpathSync } from "node:fs";
20716
20711
  import { homedir as homedir3 } from "node:os";
@@ -20790,6 +20785,40 @@ function getVersionManagerBinPaths(options = {}) {
20790
20785
  return getVersionManagerDirectories(platform2, homePath, platform2.executableNames("node"));
20791
20786
  }
20792
20787
 
20788
+ // src/providers/cli-specs.ts
20789
+ var SOURCES = [
20790
+ { id: "codex", label: "Codex", command: "codex", versionArguments: ["--version"], promptStdin: { replaceWith: "-" }, restrictedPermission: true, installHint: "npm i -g @openai/codex" },
20791
+ { 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" },
20792
+ { id: "grok", label: "Grok CLI", command: "grok", versionArguments: ["--version"] },
20793
+ { id: "gemini", label: "Gemini CLI", command: "gemini", versionArguments: ["--version"], restrictedPermission: true, installHint: "npm i -g @google/gemini-cli" },
20794
+ { id: "opencode", label: "OpenCode", command: "opencode", versionArguments: ["--version"], installHint: "npm i -g opencode-ai" },
20795
+ { id: "kiro", label: "Kiro CLI", aliases: ["kiro-cli"], command: "kiro-cli", commandAliases: ["kiro"], versionArguments: ["--version"], promptStdin: "omit", restrictedPermission: true },
20796
+ { id: "cursor", label: "Cursor Agent", command: "cursor-agent", commandAliases: ["cursor"] },
20797
+ { id: "copilot", label: "GitHub Copilot CLI", command: "copilot" },
20798
+ { id: "aider", label: "Aider", command: "aider" },
20799
+ { id: "goose", label: "Goose", command: "goose" },
20800
+ { id: "cline", label: "Cline", command: "cline" }
20801
+ ];
20802
+ function resolveSpec(source) {
20803
+ return { ...source, overrideEnv: source.overrideEnv ?? `TOC_OCRA_${source.id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_PATH` };
20804
+ }
20805
+ var CLI_SPECS = SOURCES.map(resolveSpec);
20806
+ function cliSpec(idOrAlias) {
20807
+ const normalized = idOrAlias.trim().toLowerCase();
20808
+ return CLI_SPECS.find((spec) => spec.id === normalized || spec.aliases?.includes(normalized));
20809
+ }
20810
+ function requireCliSpec(id) {
20811
+ const spec = cliSpec(id);
20812
+ if (!spec) throw new Error(`CLI \u914D\u7F6E\u7F3A\u5931\uFF1A${id}`);
20813
+ return spec;
20814
+ }
20815
+ function cliCommand(spec, platform2 = currentPlatform.id) {
20816
+ return spec.commandByPlatform?.[platform2] ?? spec.command;
20817
+ }
20818
+ function supportsPlatform(spec, platform2 = currentPlatform.id) {
20819
+ return !spec.unsupportedPlatforms?.includes(platform2);
20820
+ }
20821
+
20793
20822
  // src/providers/provider.ts
20794
20823
  function pickCreatedSession(before, after, prompt) {
20795
20824
  const created = after.filter((session) => !before.has(session.id));
@@ -20849,8 +20878,9 @@ function resolveExecutable(command, args, env, override) {
20849
20878
  return { ...directLaunch2(resolved, args, process.env.TOC_OCRA_NODE_PATH || process.execPath), env };
20850
20879
  }
20851
20880
  function launchCli(options) {
20852
- const launch = resolveExecutable(options.command, options.args, options.env ?? providerEnvironment(), process.env[options.overrideEnv]);
20853
- return options.prompt && options.promptStdin ? fitPromptOnCommandLine(launch, options.prompt, options.promptStdin) : launch;
20881
+ const { spec } = options;
20882
+ const launch = resolveExecutable(cliCommand(spec), options.args, options.env ?? providerEnvironment(), process.env[spec.overrideEnv]);
20883
+ return options.prompt && spec.promptStdin ? fitPromptOnCommandLine(launch, options.prompt, spec.promptStdin) : launch;
20854
20884
  }
20855
20885
  function fitsCommandLine(launch) {
20856
20886
  return commandLineLength(launch.executable, launch.args) <= currentPlatform.maxCommandLineLength;
@@ -20890,7 +20920,173 @@ function textRows(prefix, text, maxRows = 40) {
20890
20920
  return shown;
20891
20921
  }
20892
20922
 
20923
+ // src/providers/chat/codex-app-server.ts
20924
+ function codexChatProvider(request, attachments) {
20925
+ let write;
20926
+ let threadId = request.sessionId;
20927
+ let hasStartedTurn = false;
20928
+ const send = (message) => write?.(`${JSON.stringify(message)}
20929
+ `);
20930
+ const options = {
20931
+ cwd: request.workdir,
20932
+ approvalPolicy: "never",
20933
+ sandbox: request.permissionMode === "full" ? "danger-full-access" : "read-only",
20934
+ ...request.model ? { model: request.model } : {}
20935
+ };
20936
+ const threadRequest = () => send({
20937
+ id: 2,
20938
+ method: threadId ? "thread/resume" : "thread/start",
20939
+ params: { ...options, ...threadId ? { threadId } : { ephemeral: false } }
20940
+ });
20941
+ let forked = false;
20942
+ const forkRequest = () => send({
20943
+ id: 4,
20944
+ method: "thread/fork",
20945
+ params: { ...options, threadId, ephemeral: false, excludeTurns: true }
20946
+ });
20947
+ const startTurn = () => {
20948
+ if (hasStartedTurn) return;
20949
+ hasStartedTurn = true;
20950
+ const input2 = [];
20951
+ if (request.prompt) input2.push({ type: "text", text: request.prompt });
20952
+ for (const attachment of attachments) {
20953
+ if (attachment.kind === "image") input2.push({ type: "localImage", path: attachment.path });
20954
+ else input2.push({ type: "text", text: `\u9644\u4EF6\u6587\u4EF6\uFF1A${attachment.name}
20955
+ \u672C\u673A\u8DEF\u5F84\uFF1A${attachment.path}` });
20956
+ }
20957
+ send({ id: 3, method: "turn/start", params: {
20958
+ threadId,
20959
+ input: input2,
20960
+ cwd: request.workdir,
20961
+ approvalPolicy: "never",
20962
+ sandboxPolicy: request.permissionMode === "full" ? { type: "dangerFullAccess" } : { type: "readOnly", access: { type: "restricted", includePlatformDefaults: true, readableRoots: [request.workdir] } },
20963
+ ...request.model ? { model: request.model } : {},
20964
+ ...request.reasoningEffort ? { effort: request.reasoningEffort } : {}
20965
+ } });
20966
+ };
20967
+ const empty = () => ({ display: [] });
20968
+ return {
20969
+ id: "codex",
20970
+ buildLaunch() {
20971
+ return launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--listen", "stdio://", ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"']] });
20972
+ },
20973
+ startInput(writer) {
20974
+ write = writer;
20975
+ send({ id: 1, method: "initialize", params: {
20976
+ clientInfo: { name: "echo_cli_chat", title: "Echo CLI Chat", version: "1.0" },
20977
+ capabilities: { experimentalApi: true }
20978
+ } });
20979
+ },
20980
+ parseLine(line) {
20981
+ const message = tryJson(line);
20982
+ if (!message) return empty();
20983
+ if (message.id !== void 0 && !message.method) {
20984
+ const error62 = message.error;
20985
+ if (error62 && message.id === 2 && threadId && !forked && isWriterConflict(str(error62.message))) {
20986
+ forked = true;
20987
+ forkRequest();
20988
+ return { display: [`\u25CF \u4F1A\u8BDD ${threadId} \u6B63\u88AB\u5176\u4ED6 Codex \u7A97\u53E3\u5360\u7528\uFF0C\u5DF2\u590D\u5236\u5386\u53F2\u7EE7\u7EED`] };
20989
+ }
20990
+ if (error62) return { display: [], turnError: str(error62.message) ?? "Codex \u4F1A\u8BDD\u8BF7\u6C42\u5931\u8D25", endProcess: true };
20991
+ if (message.id === 1) {
20992
+ send({ method: "initialized" });
20993
+ threadRequest();
20994
+ return empty();
20995
+ }
20996
+ if (message.id === 2 || message.id === 4) {
20997
+ const result = message.result;
20998
+ const thread = result?.thread;
20999
+ const id = str(thread?.id);
21000
+ if (!id) return { display: [], turnError: "Codex \u672A\u8FD4\u56DE\u539F\u751F\u4F1A\u8BDD ID", endProcess: true };
21001
+ threadId = id;
21002
+ startTurn();
21003
+ return { display: [`\u25CF \u4F1A\u8BDD ${id}`], sessionId: id };
21004
+ }
21005
+ return empty();
21006
+ }
21007
+ const params = message.params ?? {};
21008
+ if (params.threadId && params.threadId !== threadId) return empty();
21009
+ if (message.id !== void 0) {
21010
+ send({ id: message.id, error: { code: -32601, message: "\u5F53\u524D\u804A\u5929\u5C1A\u672A\u63A5\u5165\u4EA4\u4E92\u5F0F\u6743\u9650\u6216\u95EE\u7B54" } });
21011
+ return { display: [], turnError: "CLI \u6B63\u5728\u8BF7\u6C42\u4EA4\u4E92\u786E\u8BA4\uFF0C\u5F53\u524D\u804A\u5929\u5C1A\u672A\u63A5\u5165\u6B64\u64CD\u4F5C\u3002", endProcess: true };
21012
+ }
21013
+ const itemId = str(params.itemId) ?? "";
21014
+ switch (message.method) {
21015
+ case "item/agentMessage/delta":
21016
+ case "item/reasoning/textDelta":
21017
+ case "item/reasoning/summaryTextDelta": {
21018
+ const text = typeof params.delta === "string" ? params.delta : "";
21019
+ return { display: [], chatEvents: itemId && text ? [{ event: message.method === "item/agentMessage/delta" ? "text_delta" : "thought_delta", item_id: itemId, text }] : [] };
21020
+ }
21021
+ case "turn/plan/updated": {
21022
+ const plan = Array.isArray(params.plan) ? params.plan : [];
21023
+ return { display: [], chatEvents: [{ event: "item", item: {
21024
+ itemId: "plan",
21025
+ type: "plan",
21026
+ entries: plan.map((entry) => ({ content: String(entry.step ?? ""), status: String(entry.status ?? "pending") }))
21027
+ } }] };
21028
+ }
21029
+ case "item/started":
21030
+ case "item/completed": {
21031
+ const item = params.item ?? {};
21032
+ const id = str(item.id);
21033
+ if (!id || item.type === "userMessage") return empty();
21034
+ const completed = message.method === "item/completed";
21035
+ const status = completed ? item.status === "failed" ? "failed" : "completed" : "in_progress";
21036
+ let normalized;
21037
+ switch (item.type) {
21038
+ case "agentMessage":
21039
+ normalized = { itemId: id, type: "text", text: String(item.text ?? ""), status };
21040
+ break;
21041
+ case "reasoning": {
21042
+ const summary = Array.isArray(item.summary) ? item.summary.map(String).join("\n\n") : "";
21043
+ normalized = { itemId: id, type: "thought", text: summary, status };
21044
+ break;
21045
+ }
21046
+ case "plan":
21047
+ normalized = { itemId: id, type: "text", text: String(item.text ?? ""), status };
21048
+ break;
21049
+ case "commandExecution":
21050
+ normalized = { itemId: id, type: "tool_call", name: "shell", kind: "execute", title: String(item.command ?? "\u6267\u884C\u547D\u4EE4"), input: String(item.command ?? ""), output: clip(String(item.aggregatedOutput ?? ""), 64e3), text: clip(String(item.aggregatedOutput ?? ""), 64e3), status };
21051
+ break;
21052
+ case "fileChange":
21053
+ normalized = { itemId: id, type: "tool_call", name: "file_change", kind: "edit", title: "\u4FEE\u6539\u6587\u4EF6", input: clip(JSON.stringify(item.changes ?? []), 64e3), text: clip(JSON.stringify(item.changes ?? []), 64e3), status };
21054
+ break;
21055
+ case "mcpToolCall":
21056
+ normalized = { itemId: id, type: "tool_call", name: String(item.tool ?? "MCP"), kind: "call", title: String(item.tool ?? "\u5DE5\u5177\u8C03\u7528"), input: clip(JSON.stringify(item.arguments ?? {}), 64e3), ...completed ? { output: clip(JSON.stringify(item.result ?? item.error ?? {}), 64e3) } : {}, text: clip(JSON.stringify(item.result ?? item.arguments ?? {}), 64e3), status };
21057
+ break;
21058
+ default:
21059
+ normalized = { itemId: id, type: "tool_call", name: String(item.type ?? "tool"), title: String(item.type ?? "\u6267\u884C\u8FC7\u7A0B"), status };
21060
+ break;
21061
+ }
21062
+ if (completed && normalized.type === "thought" && !normalized.text) return empty();
21063
+ return {
21064
+ display: [],
21065
+ chatEvents: [{ event: "item", item: normalized }],
21066
+ ...completed && item.type === "agentMessage" ? { message: String(item.text ?? "") } : {}
21067
+ };
21068
+ }
21069
+ case "turn/completed": {
21070
+ const turn = params.turn ?? {};
21071
+ const error62 = turn.error ?? {};
21072
+ if (turn.status !== "completed") return { display: [], turnError: str(error62.message) ?? (turn.status === "interrupted" ? "\u6267\u884C\u5DF2\u4E2D\u65AD" : "Codex \u672C\u8F6E\u6267\u884C\u5931\u8D25"), endProcess: true };
21073
+ return { display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"], turnCompleted: true, endProcess: true };
21074
+ }
21075
+ default:
21076
+ return empty();
21077
+ }
21078
+ }
21079
+ };
21080
+ }
21081
+ function isWriterConflict(message) {
21082
+ return !!message && /active writer|thread-store conflict/i.test(message);
21083
+ }
21084
+
20893
21085
  // src/providers/cli/claude.ts
21086
+ import { readFileSync as readFileSync5 } from "node:fs";
21087
+ import { homedir as homedir4 } from "node:os";
21088
+ import { join as join7 } from "node:path";
21089
+ var CLAUDE = requireCliSpec("claude");
20894
21090
  var claudeProvider = {
20895
21091
  id: "claude",
20896
21092
  buildLaunch(request) {
@@ -20910,12 +21106,14 @@ var claudeProvider = {
20910
21106
  if (request.model) args.push("--model", request.model);
20911
21107
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20912
21108
  if (request.sessionId) args.push("--resume", request.sessionId);
20913
- return launchCli({ command: "claude", overrideEnv: "TOC_OCRA_CLAUDE_PATH", args, env, prompt: request.prompt, promptStdin: "omit" });
21109
+ return launchCli({ spec: CLAUDE, args, env, prompt: request.prompt });
20914
21110
  },
20915
21111
  parseLine(line) {
20916
21112
  return claudeLineParser()(line);
20917
21113
  },
20918
- createLineParser: () => claudeLineParser()
21114
+ createLineParser: () => claudeLineParser(),
21115
+ // `--resume <id>` for a chat this computer no longer has.
21116
+ failureRules: [{ kind: "sessionMissing", pattern: /No conversation found with session ID/i }]
20919
21117
  };
20920
21118
  var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
20921
21119
  function toolResultText(content) {
@@ -21000,109 +21198,216 @@ function claudeLineParser() {
21000
21198
  };
21001
21199
  }
21002
21200
 
21003
- // src/providers/cli/codex.ts
21004
- var codexProvider = {
21005
- id: "codex",
21006
- buildLaunch(request) {
21007
- const args = ["exec", "--json", "--skip-git-repo-check"];
21008
- if (request.permissionMode === "full") args.push("--dangerously-bypass-approvals-and-sandbox");
21009
- else args.push("--sandbox", "read-only", "-c", 'approval_policy="never"', "-c", "mcp_servers={}", "-c", 'web_search="disabled"');
21010
- if (request.model) args.push("--model", request.model);
21011
- if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
21012
- if (request.sessionId) args.push("resume", request.sessionId);
21013
- args.push("--", request.prompt);
21014
- return launchCli({ command: "codex", overrideEnv: "TOC_OCRA_CODEX_PATH", args, prompt: request.prompt, promptStdin: { replaceWith: "-" } });
21015
- },
21016
- parseLine(line) {
21017
- const event = tryJson(line);
21018
- if (!event) return { display: line.trim() ? [line] : [] };
21019
- const type = str(event.type) ?? "";
21020
- const item = event.item && typeof event.item === "object" ? event.item : {};
21021
- const itemType = str(item.type) ?? str(item.item_type) ?? "";
21022
- switch (type) {
21023
- case "thread.started": {
21024
- const sessionId = str(event.thread_id);
21025
- return { ...sessionId ? { sessionId } : {}, display: [`\u25CF \u4F1A\u8BDD ${sessionId ?? ""}`] };
21026
- }
21027
- case "turn.started":
21028
- return { display: ["\u25CF \u5F00\u59CB\u5904\u7406"] };
21029
- case "turn.completed":
21030
- return { turnCompleted: true, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"] };
21031
- case "turn.failed": {
21032
- const error62 = event.error;
21033
- const message = str(error62?.message) ?? "\u672C\u8F6E\u5931\u8D25";
21034
- return { turnError: message, display: [`\u2717 ${message}`] };
21035
- }
21036
- case "error": {
21037
- const message = str(event.message) ?? "error";
21038
- return { display: [`\u2717 ${message}`] };
21039
- }
21040
- case "item.started":
21041
- if (itemType === "command_execution") return { display: [`$ ${clip(str(item.command) ?? "")}`] };
21042
- return { display: [] };
21043
- case "item.completed": {
21044
- if (itemType === "agent_message") {
21045
- const text = str(item.text) ?? "";
21046
- return { message: text, display: textRows("\u203A ", text) };
21047
- }
21048
- if (itemType === "reasoning") return { display: textRows("\u2026 ", clip(str(item.text) ?? "", 600), 8) };
21049
- if (itemType === "command_execution") {
21050
- const output2 = str(item.aggregated_output);
21051
- const code = item.exit_code;
21052
- return { display: [...output2 ? textRows(" ", clip(output2, 2e3), 20) : [], ` (exit ${typeof code === "number" ? code : "?"})`] };
21053
- }
21054
- if (itemType === "file_change") return { display: [`\u270E \u4FEE\u6539\u6587\u4EF6`] };
21055
- return { display: itemType ? [`\xB7 ${itemType}`] : [] };
21056
- }
21057
- default:
21058
- return { display: [] };
21059
- }
21060
- }
21201
+ // src/providers/chat/claude-stream-json.ts
21202
+ var TOOL_KINDS = {
21203
+ bash: "execute",
21204
+ read: "read",
21205
+ notebookread: "read",
21206
+ glob: "search",
21207
+ grep: "search",
21208
+ ls: "read",
21209
+ edit: "edit",
21210
+ multiedit: "edit",
21211
+ write: "write",
21212
+ notebookedit: "edit",
21213
+ webfetch: "fetch",
21214
+ websearch: "fetch",
21215
+ todowrite: "other",
21216
+ task: "other"
21061
21217
  };
21062
-
21063
- // src/providers/cli/gemini.ts
21064
- var geminiProvider = {
21065
- id: "gemini",
21218
+ function toolKind(name) {
21219
+ const key = name.toLowerCase();
21220
+ if (key.startsWith("mcp__")) return "mcp";
21221
+ return TOOL_KINDS[key] ?? "other";
21222
+ }
21223
+ function toolPath(input2, partial2) {
21224
+ const parsed = input2 && typeof input2 === "object" && Object.keys(input2).length ? input2 : tryJson(partial2) ?? {};
21225
+ return str(parsed.file_path) ?? str(parsed.notebook_path) ?? str(parsed.path);
21226
+ }
21227
+ var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21228
+ var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record3(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21229
+ function claudeChatProvider(attachments) {
21230
+ let messageID = "";
21231
+ let messageSequence = 0;
21232
+ let hasText = false;
21233
+ const blocks = /* @__PURE__ */ new Map();
21234
+ const tools = /* @__PURE__ */ new Map();
21235
+ const asItem = (block, status, output2) => ({ event: "item", item: {
21236
+ itemId: block.id,
21237
+ type: block.type,
21238
+ status,
21239
+ ...block.type === "tool_call" ? { name: block.name, title: block.name, kind: toolKind(block.name), ...toolPath(block.input, block.partialInput) ? { path: toolPath(block.input, block.partialInput) } : {}, input: clip(block.partialInput || JSON.stringify(block.input), 64e3), ...output2 !== void 0 ? { output: clip(output2, 64e3), text: clip(output2, 64e3) } : {} } : { text: block.text }
21240
+ } });
21241
+ return {
21242
+ id: "claude",
21243
+ buildLaunch(request) {
21244
+ const files = attachments.map((file2) => `\u9644\u4EF6\u6587\u4EF6\uFF1A${file2.name}
21245
+ \u672C\u673A\u8DEF\u5F84\uFF1A${file2.path}`).join("\n\n");
21246
+ const launch = claudeProvider.buildLaunch({ ...request, prompt: [request.prompt, files].filter(Boolean).join("\n\n") });
21247
+ launch.args.push("--include-partial-messages");
21248
+ return launch;
21249
+ },
21250
+ parseLine(line) {
21251
+ const envelope = tryJson(line);
21252
+ if (!envelope) return { display: line.trim() ? [line] : [] };
21253
+ const sessionId = str(envelope.session_id);
21254
+ const base = sessionId ? { sessionId } : {};
21255
+ const events = [];
21256
+ if (envelope.parent_tool_use_id) return { ...base, display: [] };
21257
+ if (envelope.type === "stream_event") {
21258
+ const event = record3(envelope.event);
21259
+ const index = Number(event.index ?? 0);
21260
+ if (event.type === "message_start") {
21261
+ messageID = str(record3(event.message).id) ?? `message:${++messageSequence}`;
21262
+ blocks.clear();
21263
+ } else if (event.type === "content_block_start") {
21264
+ if (!messageID) messageID = `message:${++messageSequence}`;
21265
+ const part = record3(event.content_block);
21266
+ const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21267
+ if (!["tool_use", "thinking", "text"].includes(String(part.type))) return { ...base, display: [] };
21268
+ const block = { id: type === "tool_call" ? str(part.id) ?? `${messageID}:${index}` : `${messageID}:${index}`, type, name: str(part.name) ?? "tool", text: String(part.text ?? part.thinking ?? ""), input: part.input ?? {}, partialInput: "" };
21269
+ blocks.set(index, block);
21270
+ if (type === "tool_call") tools.set(block.id, block);
21271
+ events.push(asItem(block, "in_progress"));
21272
+ } else if (event.type === "content_block_delta") {
21273
+ const block = blocks.get(index);
21274
+ const delta = record3(event.delta);
21275
+ if (!block) return { ...base, display: [] };
21276
+ if (delta.type === "text_delta" || delta.type === "thinking_delta") {
21277
+ const text = String(delta.text ?? delta.thinking ?? "");
21278
+ block.text += text;
21279
+ if (delta.type === "text_delta") hasText ||= !!text;
21280
+ events.push({ event: delta.type === "text_delta" ? "text_delta" : "thought_delta", item_id: block.id, text });
21281
+ } else if (delta.type === "input_json_delta") {
21282
+ block.partialInput += String(delta.partial_json ?? "");
21283
+ if (block.partialInput.length > 64e3) block.partialInput = block.partialInput.slice(0, 64e3);
21284
+ events.push(asItem(block, "in_progress"));
21285
+ }
21286
+ } else if (event.type === "content_block_stop") {
21287
+ const block = blocks.get(index);
21288
+ if (block && block.type !== "tool_call") events.push(asItem(block, "completed"));
21289
+ }
21290
+ } else if (envelope.type === "assistant") {
21291
+ const message = record3(envelope.message);
21292
+ const id = str(message.id) || messageID || `message:${++messageSequence}`;
21293
+ const parts = Array.isArray(message.content) ? message.content : [];
21294
+ parts.forEach((value, index) => {
21295
+ const part = record3(value);
21296
+ if (!["text", "thinking", "tool_use"].includes(String(part.type))) return;
21297
+ const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21298
+ const block = { id: type === "tool_call" ? str(part.id) ?? `${id}:${index}` : `${id}:${index}`, type, name: str(part.name) ?? "tool", text: String(part.text ?? part.thinking ?? ""), input: part.input ?? {}, partialInput: "" };
21299
+ if (type === "tool_call") tools.set(block.id, block);
21300
+ if (type === "text") hasText ||= !!block.text;
21301
+ events.push(asItem(block, type === "tool_call" ? "in_progress" : "completed"));
21302
+ });
21303
+ } else if (envelope.type === "user") {
21304
+ const message = record3(envelope.message);
21305
+ for (const value of Array.isArray(message.content) ? message.content : []) {
21306
+ const part = record3(value);
21307
+ if (part.type !== "tool_result") continue;
21308
+ const id = str(part.tool_use_id);
21309
+ if (!id) continue;
21310
+ const block = tools.get(id) ?? { id, type: "tool_call", name: "tool", text: "", input: {}, partialInput: "" };
21311
+ events.push(asItem(block, part.is_error === true ? "failed" : "completed", textContent(part.content)));
21312
+ }
21313
+ } else if (envelope.type === "result") {
21314
+ const text = str(envelope.result) ?? "";
21315
+ if (envelope.is_error === true) {
21316
+ const errors = Array.isArray(envelope.errors) ? envelope.errors.map(String).join("\n") : "";
21317
+ return { ...base, display: [], turnError: text || errors || "Claude \u672C\u8F6E\u6267\u884C\u5931\u8D25", endProcess: true };
21318
+ }
21319
+ if (!hasText && text) events.push({ event: "item", item: { itemId: "answer", type: "text", text, status: "completed" } });
21320
+ return { ...base, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"], message: text, turnCompleted: true, chatEvents: events, endProcess: true };
21321
+ }
21322
+ return { ...base, display: [], chatEvents: events };
21323
+ }
21324
+ };
21325
+ }
21326
+
21327
+ // src/providers/cli/codex.ts
21328
+ var CODEX = requireCliSpec("codex");
21329
+ var codexProvider = {
21330
+ id: "codex",
21331
+ // `exec resume <id>` for a thread this computer does not have.
21332
+ failureRules: [{ kind: "sessionMissing", pattern: /no rollout found for thread id|thread not found/i }],
21066
21333
  buildLaunch(request) {
21067
- const args = ["-p", request.prompt, "--output-format", "json", "--yolo"];
21334
+ const args = ["exec", "--json", "--skip-git-repo-check"];
21335
+ if (request.permissionMode === "full") args.push("--dangerously-bypass-approvals-and-sandbox");
21336
+ else args.push("--sandbox", "read-only", "-c", 'approval_policy="never"', "-c", "mcp_servers={}", "-c", 'web_search="disabled"');
21068
21337
  if (request.model) args.push("--model", request.model);
21069
- if (request.sessionId) args.push("--resume", request.sessionId);
21070
- return launchCli({ command: "gemini", overrideEnv: "TOC_OCRA_GEMINI_PATH", args });
21338
+ if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
21339
+ if (request.sessionId) args.push("resume", request.sessionId);
21340
+ args.push("--", request.prompt);
21341
+ return launchCli({ spec: CODEX, args, prompt: request.prompt });
21071
21342
  },
21072
21343
  parseLine(line) {
21073
21344
  const event = tryJson(line);
21074
21345
  if (!event) return { display: line.trim() ? [line] : [] };
21075
- const sessionId = str(event.session_id) ?? str(event.sessionId);
21076
- const text = str(event.response);
21077
- const error62 = event.error;
21078
- if (error62) return { ...sessionId ? { sessionId } : {}, turnError: str(error62.message) ?? "gemini failed", display: [`\u2717 ${clip(JSON.stringify(error62))}`] };
21079
- return {
21080
- ...sessionId ? { sessionId } : {},
21081
- ...text ? { message: text, turnCompleted: true } : {},
21082
- display: text ? textRows("\u203A ", text) : []
21083
- };
21346
+ const type = str(event.type) ?? "";
21347
+ const item = event.item && typeof event.item === "object" ? event.item : {};
21348
+ const itemType = str(item.type) ?? str(item.item_type) ?? "";
21349
+ switch (type) {
21350
+ case "thread.started": {
21351
+ const sessionId = str(event.thread_id);
21352
+ return { ...sessionId ? { sessionId } : {}, display: [`\u25CF \u4F1A\u8BDD ${sessionId ?? ""}`] };
21353
+ }
21354
+ case "turn.started":
21355
+ return { display: ["\u25CF \u5F00\u59CB\u5904\u7406"] };
21356
+ case "turn.completed":
21357
+ return { turnCompleted: true, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"] };
21358
+ case "turn.failed": {
21359
+ const error62 = event.error;
21360
+ const message = str(error62?.message) ?? "\u672C\u8F6E\u5931\u8D25";
21361
+ return { turnError: message, display: [`\u2717 ${message}`] };
21362
+ }
21363
+ case "error": {
21364
+ const message = str(event.message) ?? "error";
21365
+ return { display: [`\u2717 ${message}`] };
21366
+ }
21367
+ case "item.started":
21368
+ if (itemType === "command_execution") return { display: [`$ ${clip(str(item.command) ?? "")}`] };
21369
+ return { display: [] };
21370
+ case "item.completed": {
21371
+ if (itemType === "agent_message") {
21372
+ const text = str(item.text) ?? "";
21373
+ return { message: text, display: textRows("\u203A ", text) };
21374
+ }
21375
+ if (itemType === "reasoning") return { display: textRows("\u2026 ", clip(str(item.text) ?? "", 600), 8) };
21376
+ if (itemType === "command_execution") {
21377
+ const output2 = str(item.aggregated_output);
21378
+ const code = item.exit_code;
21379
+ return { display: [...output2 ? textRows(" ", clip(output2, 2e3), 20) : [], ` (exit ${typeof code === "number" ? code : "?"})`] };
21380
+ }
21381
+ if (itemType === "file_change") return { display: [`\u270E \u4FEE\u6539\u6587\u4EF6`] };
21382
+ return { display: itemType ? [`\xB7 ${itemType}`] : [] };
21383
+ }
21384
+ default:
21385
+ return { display: [] };
21386
+ }
21084
21387
  }
21085
21388
  };
21086
21389
 
21087
- // src/providers/cli/grok.ts
21088
- var grokProvider = {
21089
- id: "grok",
21390
+ // src/providers/cli/gemini.ts
21391
+ var GEMINI = requireCliSpec("gemini");
21392
+ var geminiProvider = {
21393
+ id: "gemini",
21090
21394
  buildLaunch(request) {
21091
- const args = [`--single=${request.prompt}`, "--output-format", "json", "--always-approve", "--no-subagents"];
21395
+ const args = ["-p", request.prompt, "--output-format", "json", "--yolo"];
21092
21396
  if (request.model) args.push("--model", request.model);
21093
- if (request.reasoningEffort) args.push("--reasoning-effort", request.reasoningEffort);
21094
21397
  if (request.sessionId) args.push("--resume", request.sessionId);
21095
- return launchCli({ command: "grok", overrideEnv: "TOC_OCRA_GROK_PATH", args });
21398
+ return launchCli({ spec: GEMINI, args });
21096
21399
  },
21097
21400
  parseLine(line) {
21098
21401
  const event = tryJson(line);
21099
21402
  if (!event) return { display: line.trim() ? [line] : [] };
21100
- const sessionId = str(event.sessionId) ?? str(event.session_id);
21101
- const text = str(event.text) ?? str(event.response) ?? str(event.result) ?? str(event.content);
21403
+ const sessionId = str(event.session_id) ?? str(event.sessionId);
21404
+ const text = str(event.response);
21405
+ const error62 = event.error;
21406
+ if (error62) return { ...sessionId ? { sessionId } : {}, turnError: str(error62.message) ?? "gemini failed", display: [`\u2717 ${clip(JSON.stringify(error62))}`] };
21102
21407
  return {
21103
21408
  ...sessionId ? { sessionId } : {},
21104
21409
  ...text ? { message: text, turnCompleted: true } : {},
21105
- display: text ? textRows("\u203A ", text) : [clip(line, 300)]
21410
+ display: text ? textRows("\u203A ", text) : []
21106
21411
  };
21107
21412
  }
21108
21413
  };
@@ -21111,6 +21416,70 @@ var grokProvider = {
21111
21416
  import { execFile as execFile3 } from "node:child_process";
21112
21417
  import { promisify } from "node:util";
21113
21418
 
21419
+ // src/providers/cli-failure.ts
21420
+ var COPY = {
21421
+ cliMissing: ({ label, installHint }) => `\u672C\u673A\u627E\u4E0D\u5230 ${label}\uFF0C\u8BF7\u5148\u5B89\u88C5${installHint ? `\uFF08${installHint}\uFF09` : ""}\uFF0C\u6216\u5728\u8BBE\u5907\u914D\u7F6E\u4E2D\u6307\u5B9A\u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84`,
21422
+ platformUnsupported: ({ label }) => `${label} \u4E0D\u652F\u6301\u8FD9\u53F0\u7535\u8111\u7684\u64CD\u4F5C\u7CFB\u7EDF`,
21423
+ permissionUnsupported: ({ label }) => `${label} \u5C1A\u672A\u652F\u6301\u53D7\u9650\u6743\u9650\uFF0C\u8BF7\u7531\u7535\u8111\u6240\u6709\u8005\u660E\u786E\u9009\u62E9\u5B8C\u6574\u6743\u9650\u540E\u518D\u6267\u884C`,
21424
+ cliUnsupported: ({ label }) => `\u4E0D\u652F\u6301\u7684 CLI \u7C7B\u578B\uFF1A${label}`,
21425
+ notSignedIn: ({ label }) => `${label} \u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5728\u8FD9\u53F0\u7535\u8111\u4E0A\u91CD\u65B0\u767B\u5F55\u540E\u518D\u8BD5`,
21426
+ usageLimit: ({ label }) => `${label} \u7684\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7B49\u5F85\u989D\u5EA6\u91CD\u7F6E\u6216\u5347\u7EA7\u5957\u9910\u540E\u518D\u8BD5`,
21427
+ rateLimited: ({ label }) => `${label} \u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u5DF2\u88AB\u9650\u6D41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`,
21428
+ modelUnavailable: ({ label }) => `${label} \u4E0D\u80FD\u4F7F\u7528\u6240\u9009\u6A21\u578B\uFF0C\u8BF7\u5728\u5DE5\u4F4D\u4E2D\u6362\u4E00\u4E2A\u6A21\u578B\u6216\u6539\u4E3A\u9ED8\u8BA4`,
21429
+ sessionMissing: ({ label }) => `${label} \u627E\u4E0D\u5230\u8981\u7EE7\u7EED\u7684\u4F1A\u8BDD`,
21430
+ promptTooLong: ({ label }) => `\u6D88\u606F\u8FC7\u957F\uFF0C\u8D85\u51FA\u672C\u673A\u547D\u4EE4\u884C\u957F\u5EA6\u4E0A\u9650\uFF0C${label} \u6682\u4E0D\u652F\u6301\u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6\u63D0\u793A\u8BCD\uFF0C\u8BF7\u7F29\u77ED\u6D88\u606F\u540E\u91CD\u8BD5`,
21431
+ contextTooLong: ({ label }) => `${label} \u7684\u4F1A\u8BDD\u5185\u5BB9\u5DF2\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u5F00\u59CB\u65B0\u4F1A\u8BDD\u6216\u7CBE\u7B80\u6D88\u606F`,
21432
+ networkError: ({ label }) => `${label} \u65E0\u6CD5\u8FDE\u63A5\u6A21\u578B\u670D\u52A1\uFF0C\u8BF7\u68C0\u67E5\u8FD9\u53F0\u7535\u8111\u7684\u7F51\u7EDC\u6216\u4EE3\u7406\u8BBE\u7F6E`,
21433
+ serviceRejected: ({ label }) => `${label} \u7684\u6A21\u578B\u670D\u52A1\u62D2\u7EDD\u4E86\u672C\u6B21\u8BF7\u6C42`,
21434
+ timedOut: ({ seconds }) => `\u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${seconds ?? "?"} \u79D2`,
21435
+ stalled: ({ label }) => `${label} \u957F\u65F6\u95F4\u6CA1\u6709\u65B0\u8F93\u51FA\uFF0C\u5DF2\u81EA\u52A8\u505C\u6B62`,
21436
+ startFailed: ({ label }) => `\u65E0\u6CD5\u542F\u52A8 ${label}`,
21437
+ turnFailed: ({ label }) => `${label} \u672C\u8F6E\u6267\u884C\u5931\u8D25`,
21438
+ exited: ({ label }) => `${label} \u5F02\u5E38\u9000\u51FA`,
21439
+ hostFault: () => "\u8BBE\u5907\u4EE3\u7406\u5904\u7406\u5931\u8D25"
21440
+ };
21441
+ var MAX_DETAIL = 600;
21442
+ function failureMessage(kind, context) {
21443
+ const lead = COPY[kind](context);
21444
+ const detail = context.detail?.trim();
21445
+ if (!detail || lead.includes(detail)) return lead;
21446
+ return `${lead}\uFF1A${detail.length > MAX_DETAIL ? `${detail.slice(0, MAX_DETAIL)}\u2026` : detail}`;
21447
+ }
21448
+ function cliFailure(kind, context) {
21449
+ return { kind, message: failureMessage(kind, context) };
21450
+ }
21451
+ var COMMON_FAILURE_RULES = [
21452
+ { kind: "usageLimit", pattern: /insufficient_quota|quota (?:exceeded|exhausted)|usage limit|(?:monthly|request) limit reached|credit balance is too low|out of credits/i },
21453
+ { kind: "rateLimited", pattern: /rate[ _-]?limit|too many requests|\b429\b/i },
21454
+ { kind: "notSignedIn", pattern: /not (?:logged|signed) in|please (?:log|sign) ?in|login required|authentication (?:required|failed)|unauthori[sz]ed|invalid api key|\b401\b/i },
21455
+ { kind: "contextTooLong", pattern: /context (?:length|window)|maximum context|prompt is too long|too many tokens/i },
21456
+ { kind: "modelUnavailable", pattern: /(?:unknown|invalid|unsupported) model|model[^\n]{0,80}(?:not found|not available|unavailable|does not exist|is not supported)/i },
21457
+ { kind: "networkError", pattern: /ECONNREFUSED|ENOTFOUND|ETIMEDOUT|ECONNRESET|EAI_AGAIN|getaddrinfo|fetch failed|network error|socket hang up/i }
21458
+ ];
21459
+ var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
21460
+ function stripAnsi(text) {
21461
+ return text.replace(ANSI, "");
21462
+ }
21463
+ function matchingLine(text, pattern) {
21464
+ return text.split(/\r?\n/).map((line) => line.trim()).find((line) => pattern.test(line));
21465
+ }
21466
+ function classifyCliOutput(output2, rules, context, options = {}) {
21467
+ const text = stripAnsi(typeof output2 === "string" ? output2 : output2.join("\n"));
21468
+ if (!text.trim()) return void 0;
21469
+ const candidates = options.successfulExit ? (rules ?? []).filter((rule) => rule.evenOnSuccess) : [...rules ?? [], ...COMMON_FAILURE_RULES];
21470
+ for (const rule of candidates) {
21471
+ if (!rule.pattern.test(text)) continue;
21472
+ if (rule.message) return { kind: rule.kind, message: rule.message(text), rule };
21473
+ const detail = rule.detail ? rule.detail(text) : matchingLine(text, rule.pattern);
21474
+ return { kind: rule.kind, message: failureMessage(rule.kind, { ...context, ...detail ? { detail } : {} }), rule };
21475
+ }
21476
+ return void 0;
21477
+ }
21478
+ function classifySpawnError(error62, context) {
21479
+ if (/\bENOENT\b/.test(error62)) return cliFailure("cliMissing", context);
21480
+ return cliFailure("startFailed", { ...context, detail: error62 });
21481
+ }
21482
+
21114
21483
  // src/providers/cli/kiro-session-log.ts
21115
21484
  import { open as open2, readdir, readFile as readFile3, stat } from "node:fs/promises";
21116
21485
  import { homedir as homedir5 } from "node:os";
@@ -21249,10 +21618,11 @@ function sameFolder(a, b) {
21249
21618
  }
21250
21619
 
21251
21620
  // src/providers/cli/kiro.ts
21621
+ var KIRO = requireCliSpec("kiro");
21252
21622
  var execFileAsync = promisify(execFile3);
21253
- var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
21623
+ var ANSI2 = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
21254
21624
  function kiroLaunch(args) {
21255
- return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args });
21625
+ return launchCli({ spec: KIRO, args });
21256
21626
  }
21257
21627
  var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
21258
21628
  function parseKiroSessions(stdout) {
@@ -21267,7 +21637,7 @@ function describeListSessionsError(error62, timeoutMs) {
21267
21637
  if (failure2?.code === "ENOENT") return "\u627E\u4E0D\u5230 kiro-cli";
21268
21638
  if (failure2?.killed || failure2?.signal === "SIGTERM") return `\u8BFB\u53D6\u4F1A\u8BDD\u5217\u8868\u8D85\u65F6\uFF08${Math.round(timeoutMs / 1e3)} \u79D2\uFF09`;
21269
21639
  if (failure2?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "\u4F1A\u8BDD\u5217\u8868\u8FC7\u5927";
21270
- const detail = String(failure2?.stderr ?? "").replace(ANSI, "").split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
21640
+ const detail = String(failure2?.stderr ?? "").replace(ANSI2, "").split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
21271
21641
  if (typeof failure2?.code === "number") return `kiro-cli \u9000\u51FA\u7801 ${failure2.code}${detail ? `\uFF1A${detail.slice(0, 160)}` : ""}`;
21272
21642
  return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
21273
21643
  }
@@ -21287,9 +21657,6 @@ async function listKiroSessions(workdir, options = {}) {
21287
21657
  }
21288
21658
  throw new Error(describeListSessionsError(lastError, timeoutMs));
21289
21659
  }
21290
- function isKiroMissingSession(stderr) {
21291
- return stderr.some((line) => /\bSession '[^']*' not found\b/i.test(line.replace(ANSI, "")));
21292
- }
21293
21660
  function kiroToolRows(text) {
21294
21661
  const step = /^\[tool\]\s*(.*)$/.exec(text.trim())?.[1];
21295
21662
  if (step === void 0) return void 0;
@@ -21335,7 +21702,7 @@ function kiroRunParser(context) {
21335
21702
  const replyRows = (lines) => {
21336
21703
  const display = [];
21337
21704
  for (const raw of lines) {
21338
- const line = raw.replace(ANSI, "").replace(/\s+$/, "");
21705
+ const line = raw.replace(ANSI2, "").replace(/\s+$/, "");
21339
21706
  if (!started) {
21340
21707
  if (!line.trim()) continue;
21341
21708
  started = true;
@@ -21362,7 +21729,7 @@ function kiroRunParser(context) {
21362
21729
  return out(replyRows(lines));
21363
21730
  },
21364
21731
  stderr(raw) {
21365
- const text = raw.replace(ANSI, "").trim();
21732
+ const text = raw.replace(ANSI2, "").trim();
21366
21733
  if (!text || isKiroNoise(text)) return { display: [] };
21367
21734
  const closed = closeSegment();
21368
21735
  const status = /^\[tool\]\s*status:\s*(\w+)/i.exec(text)?.[1]?.toLowerCase();
@@ -21411,6 +21778,23 @@ function kiroRunParser(context) {
21411
21778
  };
21412
21779
  }
21413
21780
  var KIRO_IMAGE_LIMIT = "\u56FE\u7247\u8D85\u9650\uFF1A\u8FD9\u4E2A\u4F1A\u8BDD\u91CC\u7D2F\u8BA1\u7684\u56FE\u7247\u5DF2\u8D85\u8FC7\u6A21\u578B\u5355\u6B21\u5BF9\u8BDD\u7684\u4E0A\u9650\uFF08100 \u5F20\uFF09\uFF0C\u5728\u8FD9\u4E2A\u4F1A\u8BDD\u91CC\u7EE7\u7EED\u67E5\u770B\u56FE\u7247\u90FD\u4F1A\u5931\u8D25";
21781
+ var KIRO_FAILURE_RULES = [
21782
+ // `chat --resume-id` says `Session '<id>' not found`; ACP `session/load` says `Session not found: <id>`.
21783
+ { kind: "sessionMissing", pattern: /\bSession '[^']*' not found\b|\bSession not found\b|\bNo session found\b/i },
21784
+ { kind: "contextTooLong", pattern: /too many inline media segments/i, message: () => KIRO_IMAGE_LIMIT, evenOnSuccess: true, showInLog: true },
21785
+ { kind: "usageLimit", pattern: /Monthly request limit reached|request limit reached/i, message: () => "Kiro \u672C\u6708\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u5347\u7EA7\u5957\u9910\u6216\u7B49\u5F85\u989D\u5EA6\u91CD\u7F6E\u540E\u518D\u8BD5", evenOnSuccess: true },
21786
+ { kind: "notSignedIn", pattern: /not logged in|please log in|authentication required|unauthorized/i, message: () => "Kiro CLI \u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55\u540E\u518D\u8BD5", evenOnSuccess: true },
21787
+ {
21788
+ kind: "serviceRejected",
21789
+ pattern: /having trouble responding/i,
21790
+ evenOnSuccess: true,
21791
+ message: (text) => {
21792
+ const detail = text.match(/message:\s*"([^"]+)"/)?.[1] ?? text.match(/Failed to send the request:\s*(.+)/)?.[1]?.trim();
21793
+ const hint = detail && /input_schema/i.test(detail) ? "\uFF08\u67D0\u4E2A MCP \u5DE5\u5177\u7684\u53C2\u6570\u5B9A\u4E49\u4E0D\u88AB Kiro \u63A5\u53D7\uFF0C\u8BF7\u68C0\u67E5 MCP \u670D\u52A1\u7AEF\u7684\u5DE5\u5177\u5B9A\u4E49\uFF09" : "";
21794
+ return `Kiro \u670D\u52A1\u62D2\u7EDD\u4E86\u672C\u6B21\u8BF7\u6C42\uFF1A${detail ?? "\u672A\u77E5\u9519\u8BEF"}${hint}`;
21795
+ }
21796
+ }
21797
+ ];
21414
21798
  var kiroProvider = {
21415
21799
  id: "kiro",
21416
21800
  buildLaunch(request) {
@@ -21421,15 +21805,10 @@ var kiroProvider = {
21421
21805
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
21422
21806
  if (request.sessionId && !request.sessionId.startsWith("sess_")) args.push("--resume-id", request.sessionId);
21423
21807
  args.push("--", request.prompt);
21424
- return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args, prompt: request.prompt, promptStdin: "omit" });
21808
+ return launchCli({ spec: KIRO, args, prompt: request.prompt });
21425
21809
  },
21426
21810
  listSessions: (workdir) => listKiroSessions(workdir),
21427
- isMissingSession: (stderr) => isKiroMissingSession(stderr),
21428
- inspectExit(context) {
21429
- const businessError = kiroStderrError(context.stderr);
21430
- if (!businessError) return {};
21431
- return businessError === KIRO_IMAGE_LIMIT ? { turnError: businessError, display: [runLog.error(businessError)] } : { turnError: businessError };
21432
- },
21811
+ failureRules: KIRO_FAILURE_RULES,
21433
21812
  /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
21434
21813
  parseLine(line) {
21435
21814
  return kiroRunParser().stdout(`${line}
@@ -21437,38 +21816,361 @@ var kiroProvider = {
21437
21816
  },
21438
21817
  createRunParser: (context) => kiroRunParser(context)
21439
21818
  };
21440
- function kiroStderrError(stderrLines) {
21441
- const text = stderrLines.join("\n");
21442
- if (/too many inline media segments/i.test(text)) return KIRO_IMAGE_LIMIT;
21443
- if (/Monthly request limit reached|request limit reached/i.test(text)) {
21444
- 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";
21445
- }
21446
- if (/not logged in|please log in|authentication required|unauthorized/i.test(text)) {
21447
- return "Kiro CLI \u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55\u540E\u518D\u8BD5";
21448
- }
21449
- if (/having trouble responding/i.test(text)) {
21450
- const detail = text.match(/message:\s*"([^"]+)"/)?.[1] ?? text.match(/Failed to send the request:\s*(.+)/)?.[1]?.trim();
21451
- const hint = detail && /input_schema/i.test(detail) ? "\uFF08\u67D0\u4E2A MCP \u5DE5\u5177\u7684\u53C2\u6570\u5B9A\u4E49\u4E0D\u88AB Kiro \u63A5\u53D7\uFF0C\u8BF7\u68C0\u67E5 MCP \u670D\u52A1\u7AEF\u7684\u5DE5\u5177\u5B9A\u4E49\uFF09" : "";
21452
- return `Kiro \u670D\u52A1\u62D2\u7EDD\u4E86\u672C\u6B21\u8BF7\u6C42\uFF1A${detail ?? "\u672A\u77E5\u9519\u8BEF"}${hint}`;
21453
- }
21454
- return void 0;
21819
+
21820
+ // src/providers/acp/acp-driver.ts
21821
+ var PROTOCOL_VERSION = 1;
21822
+ var AUTH_REQUIRED = -32e3;
21823
+ var READ_ONLY_KINDS = /* @__PURE__ */ new Set(["read", "search", "think"]);
21824
+ var record4 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21825
+ function acpErrorText(error62) {
21826
+ const message = str(error62?.message) ?? "ACP \u8BF7\u6C42\u5931\u8D25";
21827
+ const data = error62?.data;
21828
+ const detail = typeof data === "string" ? data : data !== void 0 ? JSON.stringify(data) : "";
21829
+ if (!detail || message.includes(detail)) return message;
21830
+ return /^internal error$/i.test(message) ? detail : `${message}: ${detail}`;
21831
+ }
21832
+ function contentText(content) {
21833
+ if (!Array.isArray(content)) return "";
21834
+ return content.map((item) => {
21835
+ const part = record4(item);
21836
+ const inner = record4(part.content);
21837
+ return str(inner.text) ?? str(part.text) ?? "";
21838
+ }).filter(Boolean).join("\n");
21839
+ }
21840
+ function reportedExitCode(rawOutput) {
21841
+ const text = rawOutput === void 0 ? "" : JSON.stringify(rawOutput);
21842
+ const match = /exit status:\s*(-?\d+)/i.exec(text) ?? /"exit_?code"\s*:\s*(-?\d+)/i.exec(text);
21843
+ return match ? Number(match[1]) : void 0;
21844
+ }
21845
+ function rawStdout(rawOutput) {
21846
+ const found = [];
21847
+ const walk = (value) => {
21848
+ if (Array.isArray(value)) value.forEach(walk);
21849
+ else if (value && typeof value === "object") {
21850
+ for (const [key, item] of Object.entries(value)) {
21851
+ if ((key === "stdout" || key === "output") && typeof item === "string") found.push(item);
21852
+ else walk(item);
21853
+ }
21854
+ }
21855
+ };
21856
+ walk(rawOutput);
21857
+ return found.join("\n");
21858
+ }
21859
+ function permissionOutcome(params, request, spec) {
21860
+ const options = Array.isArray(params.options) ? params.options.map(record4) : [];
21861
+ const call = record4(params.toolCall);
21862
+ const title = str(call.title) ?? "";
21863
+ const allowed = request.permissionMode === "full" || READ_ONLY_KINDS.has(str(call.kind) ?? "") || Boolean(spec.restrictedTools?.test(title));
21864
+ const pick2 = (prefix) => options.find((option2) => str(option2.kind) === `${prefix}_once`) ?? options.find((option2) => str(option2.kind)?.startsWith(prefix));
21865
+ const option = allowed ? pick2("allow") : pick2("reject");
21866
+ return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
21867
+ }
21868
+ function acpProvider(spec) {
21869
+ return { ...createAcpProvider(spec), forTurn: () => createAcpProvider(spec) };
21870
+ }
21871
+ function createAcpProvider(spec) {
21872
+ let request;
21873
+ let write;
21874
+ let nextId = 0;
21875
+ const phases = /* @__PURE__ */ new Map();
21876
+ let sessionId = "";
21877
+ let loading = false;
21878
+ let finished = false;
21879
+ let reply = "";
21880
+ let thought = "";
21881
+ let lastReply = "";
21882
+ const tools = /* @__PURE__ */ new Map();
21883
+ let lastShell = "";
21884
+ const send = (message) => write?.(`${JSON.stringify({ jsonrpc: "2.0", ...message })}
21885
+ `);
21886
+ const call = (phase, method, params) => {
21887
+ const id = ++nextId;
21888
+ phases.set(id, phase);
21889
+ send({ id, method, params });
21890
+ };
21891
+ const answer = (id, result) => send({ id, result });
21892
+ const refuse = (id, message) => send({ id, error: { code: -32601, message } });
21893
+ const flush = () => {
21894
+ const display = [];
21895
+ const out = { display };
21896
+ if (thought.trim()) display.push(...runLog.thinking(thought.trim()));
21897
+ thought = "";
21898
+ if (reply.trim()) {
21899
+ lastReply = reply.trim();
21900
+ display.push(...runLog.reply(lastReply));
21901
+ out.message = lastReply;
21902
+ }
21903
+ reply = "";
21904
+ return out;
21905
+ };
21906
+ const merge2 = (...parts) => parts.reduce((all, part) => ({
21907
+ ...all,
21908
+ ...part,
21909
+ display: [...all.display, ...part.display],
21910
+ ...all.chatEvents || part.chatEvents ? { chatEvents: [...all.chatEvents ?? [], ...part.chatEvents ?? []] } : {}
21911
+ }), { display: [] });
21912
+ const fail = (text, kind) => {
21913
+ finished = true;
21914
+ const error62 = kind ? { turnError: failureMessage(kind, { label: spec.cli.label, detail: text }), failureKind: kind } : { turnError: text };
21915
+ return merge2(flush(), { ...error62, endProcess: true, display: [] });
21916
+ };
21917
+ const prompt = () => call("prompt", "session/prompt", { sessionId, prompt: [{ type: "text", text: request.prompt }] });
21918
+ const startSession = () => {
21919
+ const params = { cwd: request.workdir, mcpServers: [] };
21920
+ if (request.sessionId && (spec.resumable?.(request.sessionId) ?? true)) {
21921
+ loading = true;
21922
+ call("load", "session/load", { ...params, sessionId: request.sessionId });
21923
+ } else call("new", "session/new", params);
21924
+ };
21925
+ const afterSession = (loaded) => {
21926
+ if (loaded && spec.setModelOnLoad && request.model) call("set_model", "session/set_model", { sessionId, modelId: request.model });
21927
+ else prompt();
21928
+ };
21929
+ const onResponse = (message) => {
21930
+ const phase = typeof message.id === "number" ? phases.get(message.id) : void 0;
21931
+ if (!phase) return { display: [] };
21932
+ phases.delete(message.id);
21933
+ if (message.error) {
21934
+ const text = acpErrorText(message.error);
21935
+ if (phase === "load") {
21936
+ loading = false;
21937
+ if (classifyCliOutput(text, spec.failureRules, spec.cli)?.kind === "sessionMissing") {
21938
+ const missing = request.sessionId;
21939
+ call("new", "session/new", { cwd: request.workdir, mcpServers: [] });
21940
+ return { display: [runLog.event(`\u539F\u4F1A\u8BDD ${missing} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`)] };
21941
+ }
21942
+ }
21943
+ return fail(text, message.error.code === AUTH_REQUIRED ? "notSignedIn" : void 0);
21944
+ }
21945
+ const result = record4(message.result);
21946
+ switch (phase) {
21947
+ case "initialize":
21948
+ startSession();
21949
+ return { display: [] };
21950
+ case "load":
21951
+ loading = false;
21952
+ sessionId = request.sessionId;
21953
+ afterSession(true);
21954
+ return { sessionId, display: [] };
21955
+ case "new": {
21956
+ sessionId = str(result.sessionId) ?? "";
21957
+ if (!sessionId) return fail("ACP session/new \u6CA1\u6709\u8FD4\u56DE\u4F1A\u8BDD ID");
21958
+ afterSession(false);
21959
+ return { sessionId, display: [runLog.event(`\u4F1A\u8BDD ${sessionId}`)] };
21960
+ }
21961
+ case "set_model":
21962
+ prompt();
21963
+ return { display: [] };
21964
+ case "prompt": {
21965
+ finished = true;
21966
+ const stopReason = str(result.stopReason) ?? "end_turn";
21967
+ const rows = flush();
21968
+ if (stopReason === "refusal") return merge2(rows, { turnError: "model refused to answer (stopReason: refusal)", endProcess: true, display: [] });
21969
+ if (stopReason === "cancelled") return merge2(rows, { turnError: "\u672C\u8F6E\u88AB CLI \u53D6\u6D88", endProcess: true, display: [] });
21970
+ const note = stopReason === "end_turn" ? "\u672C\u8F6E\u5B8C\u6210" : `\u672C\u8F6E\u7ED3\u675F\uFF08${stopReason}\uFF09`;
21971
+ return merge2(rows, { turnCompleted: true, endProcess: true, display: [runLog.event(note)] });
21972
+ }
21973
+ }
21974
+ };
21975
+ const onToolCall = (update) => {
21976
+ const id = str(update.toolCallId) ?? "";
21977
+ const known = tools.get(id);
21978
+ const input2 = record4(update.rawInput);
21979
+ const locations = Array.isArray(update.locations) ? update.locations.map(record4) : [];
21980
+ const tool = known ?? { kind: "other", title: "tool" };
21981
+ tool.kind = str(update.kind) ?? tool.kind;
21982
+ if (!known) tool.title = str(update.title) ?? tool.title;
21983
+ if (tool.kind === "execute" && !tool.command) {
21984
+ const command = str(input2.command) ?? str(update.title)?.replace(/^Running:\s*/i, "");
21985
+ if (command && command !== "shell") tool.command = command;
21986
+ }
21987
+ const path = tool.path ?? str(locations[0]?.path) ?? str(input2.path) ?? str(input2.file_path);
21988
+ if (path) tool.path = path;
21989
+ const output2 = contentText(update.content);
21990
+ if (output2) tool.output = output2;
21991
+ tools.set(id, tool);
21992
+ if (known) return { display: [] };
21993
+ const rows = flush();
21994
+ if (tool.kind === "execute") {
21995
+ lastShell = id;
21996
+ return merge2(rows, { display: [runLog.command(tool.command ?? tool.title)] });
21997
+ }
21998
+ lastShell = "";
21999
+ if (tool.kind === "edit" || tool.kind === "delete" || tool.kind === "move") return merge2(rows, { display: [runLog.fileChange(tool.path)] });
22000
+ if (READ_ONLY_KINDS.has(tool.kind)) return rows;
22001
+ if (tool.kind === "fetch") return merge2(rows, { display: [runLog.tool("web_search")] });
22002
+ const meta3 = record4(record4(update._meta).kiro);
22003
+ return merge2(rows, { display: toolCallRows(str(meta3.toolName) ?? tool.title, tool.path) });
22004
+ };
22005
+ const onToolUpdate = (update) => {
22006
+ const id = str(update.toolCallId) ?? "";
22007
+ const first = onToolCall(update);
22008
+ const tool = tools.get(id);
22009
+ const status = str(update.status);
22010
+ if (status !== "completed" && status !== "failed") return first;
22011
+ if (tool.kind === "execute") {
22012
+ const header = lastShell === id ? [] : [runLog.command(tool.command ?? tool.title)];
22013
+ lastShell = "";
22014
+ const code = reportedExitCode(update.rawOutput) ?? (status === "failed" ? 1 : 0);
22015
+ const output2 = tool.output ?? rawStdout(update.rawOutput);
22016
+ return { display: [...header, ...runLog.commandOutput(output2), runLog.commandExit(code)] };
22017
+ }
22018
+ if (status === "failed") {
22019
+ lastShell = "";
22020
+ return merge2(first, { display: [runLog.error(`${tool.title}${tool.output ? `\uFF1A${tool.output}` : " \u5931\u8D25"}`)] });
22021
+ }
22022
+ return first;
22023
+ };
22024
+ const onUpdate = (params) => {
22025
+ if (loading) return { display: [] };
22026
+ const update = record4(params.update);
22027
+ const text = str(record4(update.content).text);
22028
+ switch (str(update.sessionUpdate)) {
22029
+ case "agent_message_chunk": {
22030
+ if (!text) return { display: [] };
22031
+ const rows = thought ? flush() : { display: [] };
22032
+ reply += text;
22033
+ return merge2(rows, { chatEvents: [{ event: "text_delta", text }], display: [] });
22034
+ }
22035
+ case "agent_thought_chunk": {
22036
+ if (!text) return { display: [] };
22037
+ const rows = reply ? flush() : { display: [] };
22038
+ thought += text;
22039
+ return merge2(rows, { chatEvents: [{ event: "thought_delta", text }], display: [] });
22040
+ }
22041
+ case "tool_call":
22042
+ return onToolCall(update);
22043
+ case "tool_call_update":
22044
+ return onToolUpdate(update);
22045
+ default:
22046
+ return { display: [] };
22047
+ }
22048
+ };
22049
+ const onRequest = (message) => {
22050
+ const params = record4(message.params);
22051
+ if (message.method === "session/request_permission") {
22052
+ answer(message.id, permissionOutcome(params, request, spec));
22053
+ return { display: [] };
22054
+ }
22055
+ refuse(message.id, `${message.method} is not supported by this client`);
22056
+ return { display: [] };
22057
+ };
22058
+ return {
22059
+ id: spec.cli.id,
22060
+ ...spec.failureRules ? { failureRules: spec.failureRules } : {},
22061
+ ...spec.stderrDisplay ? { stderrDisplay: spec.stderrDisplay } : {},
22062
+ buildLaunch(turn) {
22063
+ request = turn;
22064
+ return launchCli({ spec: spec.cli, args: spec.args(turn) });
22065
+ },
22066
+ startInput(writer) {
22067
+ write = writer;
22068
+ call("initialize", "initialize", {
22069
+ protocolVersion: PROTOCOL_VERSION,
22070
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
22071
+ clientInfo: { name: "toc-ocra", title: "Echo device agent", version: "1" }
22072
+ });
22073
+ },
22074
+ parseLine(line) {
22075
+ const message = tryJson(line);
22076
+ if (!message) return { display: line.trim() ? [clip(line, 400)] : [] };
22077
+ if (finished && message.id === void 0) return { display: [] };
22078
+ if (message.method && message.id !== void 0) return onRequest(message);
22079
+ if (message.method) {
22080
+ const params = record4(message.params);
22081
+ if (message.method === "session/update") return onUpdate(params);
22082
+ const rows = spec.notification?.(message.method, params);
22083
+ return { display: rows ?? [] };
22084
+ }
22085
+ return onResponse(message);
22086
+ }
22087
+ };
21455
22088
  }
21456
22089
 
21457
- // src/providers/cli/opencode.ts
21458
- var opencodeProvider = {
21459
- id: "opencode",
22090
+ // src/providers/acp/acp-agents.ts
22091
+ var ECHO_CALLBACK = /echo_report_task_progress/;
22092
+ var KIRO_ACP = {
22093
+ cli: requireCliSpec("kiro"),
22094
+ args: (request) => [
22095
+ "acp",
22096
+ // Restricted: only Echo's callback is trusted; every other permission
22097
+ // request is answered by the driver (read-only kinds allowed, rest denied).
22098
+ request.permissionMode === "full" ? "--trust-all-tools" : "--trust-tools=@doer/echo_report_task_progress",
22099
+ ...request.model ? ["--model", request.model] : [],
22100
+ ...request.reasoningEffort ? ["--effort", request.reasoningEffort] : []
22101
+ ],
22102
+ restrictedTools: ECHO_CALLBACK,
22103
+ // `--model` only reaches a new session.
22104
+ setModelOnLoad: true,
22105
+ // `sess_…` ids are Kiro IDE (v3 engine) chats: never write into someone's IDE chat.
22106
+ resumable: (sessionId) => !sessionId.startsWith("sess_"),
22107
+ failureRules: KIRO_FAILURE_RULES,
22108
+ stderrDisplay: (line) => isKiroNoise(line.trim()) ? [] : [line],
22109
+ notification(method, params) {
22110
+ if (method !== "_kiro.dev/session/update") return void 0;
22111
+ const update = params;
22112
+ if (update.sessionUpdate === "retry_warning" && typeof update.message === "string") return [runLog.event(`Kiro \u670D\u52A1\u91CD\u8BD5\uFF1A${update.message}`)];
22113
+ return [];
22114
+ }
22115
+ };
22116
+ var GEMINI_FAILURE_RULES = [
22117
+ { kind: "sessionMissing", pattern: /session[^\n]{0,60}(?:not found|does not exist)|no session found|invalid session/i },
22118
+ { kind: "notSignedIn", pattern: /api key is missing|not configured|login required|please (?:log|sign) ?in/i }
22119
+ ];
22120
+ var GEMINI_ACP = {
22121
+ cli: requireCliSpec("gemini"),
22122
+ args: (request) => [
22123
+ "--acp",
22124
+ // Restricted: Gemini asks before editing or running anything, and the driver denies it.
22125
+ ...request.permissionMode === "full" ? ["--yolo"] : ["--approval-mode", "default"],
22126
+ ...request.model ? ["--model", request.model] : []
22127
+ ],
22128
+ restrictedTools: ECHO_CALLBACK,
22129
+ failureRules: GEMINI_FAILURE_RULES
22130
+ };
22131
+ var kiroAcpProvider = acpProvider(KIRO_ACP);
22132
+ var geminiAcpProvider = acpProvider(GEMINI_ACP);
22133
+
22134
+ // src/providers/cli/grok.ts
22135
+ var GROK = requireCliSpec("grok");
22136
+ var grokProvider = {
22137
+ id: "grok",
21460
22138
  buildLaunch(request) {
21461
- const args = ["run", "--format", "json"];
22139
+ const args = [`--single=${request.prompt}`, "--output-format", "json", "--always-approve", "--no-subagents"];
21462
22140
  if (request.model) args.push("--model", request.model);
21463
- if (request.sessionId) args.push("--session", request.sessionId);
21464
- args.push(request.prompt);
21465
- return launchCli({ command: "opencode", overrideEnv: "TOC_OCRA_OPENCODE_PATH", args });
22141
+ if (request.reasoningEffort) args.push("--reasoning-effort", request.reasoningEffort);
22142
+ if (request.sessionId) args.push("--resume", request.sessionId);
22143
+ return launchCli({ spec: GROK, args });
21466
22144
  },
21467
22145
  parseLine(line) {
21468
22146
  const event = tryJson(line);
21469
22147
  if (!event) return { display: line.trim() ? [line] : [] };
21470
- const sessionId = str(event.sessionID) ?? str(event.session_id);
21471
- const part = event.part && typeof event.part === "object" ? event.part : {};
22148
+ const sessionId = str(event.sessionId) ?? str(event.session_id);
22149
+ const text = str(event.text) ?? str(event.response) ?? str(event.result) ?? str(event.content);
22150
+ return {
22151
+ ...sessionId ? { sessionId } : {},
22152
+ ...text ? { message: text, turnCompleted: true } : {},
22153
+ display: text ? textRows("\u203A ", text) : [clip(line, 300)]
22154
+ };
22155
+ }
22156
+ };
22157
+
22158
+ // src/providers/cli/opencode.ts
22159
+ var OPENCODE = requireCliSpec("opencode");
22160
+ var opencodeProvider = {
22161
+ id: "opencode",
22162
+ buildLaunch(request) {
22163
+ const args = ["run", "--format", "json"];
22164
+ if (request.model) args.push("--model", request.model);
22165
+ if (request.sessionId) args.push("--session", request.sessionId);
22166
+ args.push(request.prompt);
22167
+ return launchCli({ spec: OPENCODE, args });
22168
+ },
22169
+ parseLine(line) {
22170
+ const event = tryJson(line);
22171
+ if (!event) return { display: line.trim() ? [line] : [] };
22172
+ const sessionId = str(event.sessionID) ?? str(event.session_id);
22173
+ const part = event.part && typeof event.part === "object" ? event.part : {};
21472
22174
  const text = str(event.type) === "text" ? str(part.text) : void 0;
21473
22175
  return {
21474
22176
  ...sessionId ? { sessionId } : {},
@@ -21478,570 +22180,187 @@ var opencodeProvider = {
21478
22180
  }
21479
22181
  };
21480
22182
 
21481
- // src/providers/registry.ts
21482
- var CLI_CATALOG = [
21483
- { id: "codex", detectCmd: "codex", versionArguments: ["--version"], headless: codexProvider },
21484
- { id: "claude", aliases: ["claude-code"], detectCmd: "claude", detectCmdAliases: ["claude-code"], versionArguments: ["--version"], headless: claudeProvider },
21485
- { id: "grok", detectCmd: "grok", versionArguments: ["--version"], headless: grokProvider },
21486
- { id: "gemini", detectCmd: "gemini", versionArguments: ["--version"], headless: geminiProvider },
21487
- { id: "opencode", detectCmd: "opencode", versionArguments: ["--version"], headless: opencodeProvider },
21488
- { id: "kiro", aliases: ["kiro-cli"], detectCmd: "kiro-cli", detectCmdAliases: ["kiro"], versionArguments: ["--version"], headless: kiroProvider },
21489
- { id: "cursor", detectCmd: "cursor-agent", detectCmdAliases: ["cursor"] },
21490
- { id: "copilot", detectCmd: "copilot" },
21491
- { id: "aider", detectCmd: "aider" },
21492
- { id: "goose", detectCmd: "goose" },
21493
- { id: "cline", detectCmd: "cline" }
21494
- ];
21495
- function catalogEntry(idOrAlias) {
21496
- const normalized = idOrAlias.trim().toLowerCase();
21497
- return CLI_CATALOG.find((entry) => entry.id === normalized || entry.aliases?.includes(normalized));
21498
- }
21499
- function resolveHeadlessProvider(agentType) {
21500
- const entry = catalogEntry(agentType);
21501
- if (!entry) throw new Error(`\u4E0D\u652F\u6301\u7684 CLI \u7C7B\u578B\uFF1A${agentType}`);
21502
- if (!entry.headless) throw new Error(`${entry.id} \u6682\u4E0D\u652F\u6301\u65E0\u754C\u9762\u6267\u884C`);
21503
- return entry.headless;
21504
- }
21505
- function buildProviderDetectionCommands(configs = CLI_CATALOG) {
21506
- return configs.flatMap(
21507
- (config2) => [config2.detectCmd, ...config2.detectCmdAliases ?? []].map((cmd) => ({
21508
- id: config2.id,
21509
- cmd,
21510
- ...config2.detectRequiredCommands?.length ? { requiredCommands: config2.detectRequiredCommands } : {},
21511
- ...config2.detectUnsupportedRuntimes?.length ? { unsupportedRuntimes: config2.detectUnsupportedRuntimes } : {}
21512
- }))
21513
- );
21514
- }
21515
- var DETECTION_COMMANDS = buildProviderDetectionCommands();
21516
- function getProviderDetectionProbeCommands(commands = DETECTION_COMMANDS, runtime = process.platform) {
21517
- return [...new Set(commands.filter((command) => !command.unsupportedRuntimes?.includes(runtime)).flatMap((command) => [command.cmd, ...command.requiredCommands ?? []]))];
21518
- }
21519
- function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COMMANDS, runtime = process.platform) {
21520
- const detected = /* @__PURE__ */ new Map();
21521
- for (const command of commands) {
21522
- if (command.unsupportedRuntimes?.includes(runtime)) continue;
21523
- if (!foundCommands.has(command.cmd)) continue;
21524
- if (!(command.requiredCommands ?? []).every((required2) => foundCommands.has(required2))) continue;
21525
- if (!detected.has(command.id)) detected.set(command.id, command.cmd);
21526
- }
21527
- return detected;
21528
- }
21529
-
21530
- // src/providers/detection.ts
21531
- function probeVersion(path, args) {
21532
- if (args.length === 0) return Promise.resolve({});
21533
- return new Promise((resolve7) => {
21534
- const launch = directLaunch2(path, args);
21535
- const child = spawn3(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
21536
- let stdout = "";
21537
- let stderr = "";
21538
- let settled = false;
21539
- let timer;
21540
- const finish = (result) => {
21541
- if (settled) return;
21542
- settled = true;
21543
- if (timer) clearTimeout(timer);
21544
- resolve7(result);
21545
- };
21546
- timer = setTimeout(() => {
21547
- child.kill("SIGKILL");
21548
- finish({ detail: "version probe timeout" });
21549
- }, 5e3);
21550
- child.stdout.on("data", (chunk) => {
21551
- stdout += chunk.toString();
21552
- });
21553
- child.stderr.on("data", (chunk) => {
21554
- stderr += chunk.toString();
21555
- });
21556
- child.on("error", (error62) => finish({ detail: error62.message }));
21557
- child.on("close", (code) => {
21558
- const detail = (stdout || stderr || `exit ${code ?? "unknown"}`).trim().slice(0, 200);
21559
- const version2 = stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
21560
- finish(version2 ? { version: version2, detail } : { detail });
21561
- });
22183
+ // src/providers/codex-quota.ts
22184
+ import { spawn as spawn3 } from "node:child_process";
22185
+ import { createInterface } from "node:readline";
22186
+ async function readCodexQuotaWindows() {
22187
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--stdio"] });
22188
+ const child = spawn3(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
22189
+ let nextId = 0;
22190
+ const pending = /* @__PURE__ */ new Map();
22191
+ const lines = createInterface({ input: child.stdout });
22192
+ const rejectPending = (error62) => {
22193
+ for (const waiter of pending.values()) waiter.reject(error62);
22194
+ pending.clear();
22195
+ };
22196
+ child.once("error", (error62) => rejectPending(error62));
22197
+ child.once("exit", (code) => {
22198
+ if (pending.size) rejectPending(new Error(`Codex app-server \u5DF2\u9000\u51FA\uFF08${code ?? "unknown"}\uFF09`));
21562
22199
  });
21563
- }
21564
- var CliDetectionService = class {
21565
- snapshot;
21566
- pending;
21567
- async detect(forceRefresh = false) {
21568
- if (this.pending) return this.pending;
21569
- if (!forceRefresh && this.snapshot) return this.snapshot;
21570
- this.pending = this.detectNow(forceRefresh).finally(() => {
21571
- this.pending = void 0;
22200
+ lines.on("line", (line) => {
22201
+ let message;
22202
+ try {
22203
+ message = JSON.parse(line);
22204
+ } catch {
22205
+ return;
22206
+ }
22207
+ if (typeof message.id !== "number") return;
22208
+ const waiter = pending.get(message.id);
22209
+ if (!waiter) return;
22210
+ pending.delete(message.id);
22211
+ if (message.error) waiter.reject(new Error(message.error.message || "Codex \u989D\u5EA6\u63A5\u53E3\u8C03\u7528\u5931\u8D25"));
22212
+ else waiter.resolve(message.result);
22213
+ });
22214
+ const request = (method, params) => {
22215
+ const id = ++nextId;
22216
+ return new Promise((resolve7, reject) => {
22217
+ const timer = setTimeout(() => {
22218
+ pending.delete(id);
22219
+ reject(new Error(`Codex \u989D\u5EA6\u8BFB\u53D6\u8D85\u65F6\uFF08${method}\uFF09`));
22220
+ }, 2e4);
22221
+ pending.set(id, {
22222
+ resolve: (value) => {
22223
+ clearTimeout(timer);
22224
+ resolve7(value);
22225
+ },
22226
+ reject: (error62) => {
22227
+ clearTimeout(timer);
22228
+ reject(error62);
22229
+ }
22230
+ });
22231
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, id, params })}
22232
+ `, (error62) => {
22233
+ if (!error62) return;
22234
+ const waiter = pending.get(id);
22235
+ if (waiter) {
22236
+ pending.delete(id);
22237
+ clearTimeout(timer);
22238
+ waiter.reject(error62);
22239
+ }
22240
+ });
21572
22241
  });
21573
- return this.pending;
21574
- }
21575
- async detectNow(forceRefresh) {
21576
- const hydration = await hydrateShellPath({ force: forceRefresh });
21577
- const addedPathSegments = hydration.ok ? mergePathSegments(hydration.segments) : [];
21578
- const commands = getProviderDetectionProbeCommands(DETECTION_COMMANDS);
21579
- const resolved = new Map(commands.map((command) => [command, resolveCliCommandDetailed(command)]));
21580
- const foundCommands = new Set(commands.filter((command) => resolved.get(command)?.found));
21581
- const detected = resolveDetectedProviderCommands(foundCommands, DETECTION_COMMANDS);
21582
- const providers = await Promise.all(CLI_CATALOG.map(async (config2) => {
21583
- const matchedDetectionCommand = detected.get(config2.id);
21584
- const result = matchedDetectionCommand ? resolved.get(matchedDetectionCommand) : void 0;
21585
- const executablePath = result?.found ? result.path : void 0;
21586
- const installed = Boolean(executablePath);
21587
- const unsupported = config2.detectUnsupportedRuntimes?.includes(process.platform) ?? false;
21588
- const diagnostic = executablePath ? await probeVersion(executablePath, config2.versionArguments ?? []) : {};
21589
- const detail = installed ? diagnostic.detail : unsupported ? "unsupported runtime" : config2.detectRequiredCommands?.length ? "command or required command not found" : "command not found";
21590
- return {
21591
- id: config2.id,
21592
- installed,
21593
- available: installed && Boolean(config2.headless),
21594
- ...matchedDetectionCommand ? { matchedDetectionCommand } : {},
21595
- ...result?.path ? { resolvedPath: result.path } : {},
21596
- ...diagnostic.version ? { version: diagnostic.version } : {},
21597
- ...detail ? { detail } : {}
22242
+ };
22243
+ try {
22244
+ await request("initialize", {
22245
+ clientInfo: { name: "toc-ocra", title: "Echo device agent", version: "0.2.3" },
22246
+ capabilities: { experimentalApi: true }
22247
+ });
22248
+ child.stdin.write('{"jsonrpc":"2.0","method":"initialized","params":{}}\n');
22249
+ const result = await request("account/rateLimits/read", {});
22250
+ const buckets = Object.entries(result?.rateLimitsByLimitId ?? {});
22251
+ if (!buckets.length && result?.rateLimits) buckets.push([String(result.rateLimits.limitId || "codex"), result.rateLimits]);
22252
+ const windows = buckets.flatMap(([limitId, snapshot]) => ["primary", "secondary"].flatMap((key) => {
22253
+ const window = snapshot[key];
22254
+ if (!window) return [];
22255
+ const resetRaw = Number(window.resetsAt);
22256
+ const resetsAt = Number.isFinite(resetRaw) && resetRaw > 0 ? Math.floor(resetRaw > 1e10 ? resetRaw / 1e3 : resetRaw) : 0;
22257
+ const durationMins = Number(window.windowDurationMins);
22258
+ const usedRaw = Number(window.usedPercent);
22259
+ const windowLabel = durationMins === 300 ? "5 \u5C0F\u65F6\u989D\u5EA6" : durationMins >= 1e4 ? "\u6BCF\u5468\u989D\u5EA6" : durationMins > 0 ? `${durationMins} \u5206\u949F\u989D\u5EA6` : key === "primary" ? "\u4E3B\u8981\u989D\u5EA6" : "\u6B21\u8981\u989D\u5EA6";
22260
+ const bucketName = typeof snapshot.limitName === "string" && snapshot.limitName.trim() ? snapshot.limitName.trim() : limitId === "codex" ? "" : limitId;
22261
+ const item = {
22262
+ key: `${limitId}:${key}`,
22263
+ label: bucketName ? `${bucketName} \xB7 ${windowLabel}` : windowLabel,
22264
+ resets_at: resetsAt,
22265
+ ...Number.isFinite(usedRaw) && usedRaw >= 0 && usedRaw <= 100 ? { used_percent: usedRaw } : {},
22266
+ ...Number.isFinite(durationMins) && durationMins > 0 ? { window_seconds: Math.floor(durationMins * 60) } : {}
21598
22267
  };
22268
+ return [item];
21599
22269
  }));
21600
- this.snapshot = {
21601
- providers,
21602
- detectedIds: providers.filter((provider) => provider.installed).map((provider) => provider.id),
21603
- addedPathSegments,
21604
- shellHydrationOk: hydration.ok,
21605
- pathSource: hydration.ok ? "shell_hydrated" : "process_path",
21606
- pathFailureReason: hydration.failureReason,
21607
- refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
21608
- };
21609
- return this.snapshot;
22270
+ if (!windows.length || !windows.some((window) => window.resets_at > 0)) throw new Error("Codex \u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u989D\u5EA6\u7A97\u53E3");
22271
+ return windows;
22272
+ } finally {
22273
+ for (const waiter of pending.values()) waiter.reject(new Error("Codex app-server \u5DF2\u5173\u95ED"));
22274
+ pending.clear();
22275
+ lines.close();
22276
+ currentPlatform.stopHelper(child);
21610
22277
  }
21611
- };
21612
- var cliDetection = new CliDetectionService();
21613
-
21614
- // src/runtime/agent-runtime.ts
21615
- import { randomUUID as randomUUID3 } from "node:crypto";
21616
- import { join as join14 } from "node:path";
21617
-
21618
- // src/exec/script-runner.ts
21619
- import { spawn as spawn4 } from "node:child_process";
21620
-
21621
- // src/runs/process-tree.ts
21622
- var KILL_GRACE_MS = 3e3;
21623
- async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
21624
- if (!Number.isInteger(rootPid) || rootPid <= 1) return;
21625
- await currentPlatform.killProcessTree(rootPid, graceMs);
21626
22278
  }
21627
22279
 
21628
- // src/exec/script-runner.ts
21629
- var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
21630
- function executeScript(command, workdir, timeoutSeconds) {
21631
- return new Promise((resolveExecution) => {
21632
- const ownGroup = currentPlatform.runsInOwnProcessGroup;
21633
- const { executable, args } = currentPlatform.scriptShell(command);
21634
- const startedAt = Date.now();
21635
- const stdout = [];
21636
- const stderr = [];
21637
- let stdoutBytes = 0;
21638
- let stderrBytes = 0;
21639
- let outputTruncated = false;
21640
- let timedOut = false;
21641
- let spawnError = "";
21642
- let settled = false;
21643
- const append = (target, chunk, currentBytes) => {
21644
- const remaining = MAX_SCRIPT_OUTPUT_BYTES - currentBytes;
21645
- if (remaining <= 0) {
21646
- outputTruncated = true;
21647
- return currentBytes;
21648
- }
21649
- if (chunk.length > remaining) {
21650
- target.push(chunk.subarray(0, remaining));
21651
- outputTruncated = true;
21652
- return MAX_SCRIPT_OUTPUT_BYTES;
21653
- }
21654
- target.push(chunk);
21655
- return currentBytes + chunk.length;
21656
- };
21657
- let child;
21658
- try {
21659
- child = spawn4(executable, args, {
21660
- cwd: workdir,
21661
- env: process.env,
21662
- detached: ownGroup,
21663
- shell: false,
21664
- windowsHide: true,
21665
- stdio: ["ignore", "pipe", "pipe"]
21666
- });
21667
- } catch (error62) {
21668
- resolveExecution({
21669
- exitCode: -1,
21670
- stdout: "",
21671
- stderr: error62 instanceof Error ? error62.message : String(error62),
21672
- durationMs: Date.now() - startedAt,
21673
- outputTruncated: false,
21674
- timedOut: false
21675
- });
21676
- return;
21677
- }
21678
- const kill = () => {
21679
- if (child.exitCode !== null || child.killed) return;
21680
- try {
21681
- if (ownGroup && child.pid) process.kill(-child.pid, "SIGKILL");
21682
- else if (child.pid) void killProcessTree(child.pid, 0);
21683
- else child.kill("SIGKILL");
21684
- } catch {
21685
- try {
21686
- child.kill("SIGKILL");
21687
- } catch {
21688
- }
21689
- }
21690
- };
21691
- const timeout = setTimeout(() => {
21692
- timedOut = true;
21693
- kill();
21694
- }, timeoutSeconds * 1e3);
21695
- child.stdout.on("data", (chunk) => {
21696
- stdoutBytes = append(stdout, Buffer.from(chunk), stdoutBytes);
21697
- });
21698
- child.stderr.on("data", (chunk) => {
21699
- stderrBytes = append(stderr, Buffer.from(chunk), stderrBytes);
21700
- });
21701
- child.once("error", (error62) => {
21702
- spawnError = error62.message;
21703
- });
21704
- child.once("close", (code) => {
21705
- if (settled) return;
21706
- settled = true;
21707
- clearTimeout(timeout);
21708
- let stderrText = Buffer.concat(stderr).toString("utf8");
21709
- if (spawnError) stderrText = `${stderrText}${stderrText ? "\n" : ""}${spawnError}`;
21710
- if (timedOut) {
21711
- stderrText = `${stderrText}${stderrText ? "\n" : ""}Command timed out after ${timeoutSeconds} seconds.`;
21712
- }
21713
- if (outputTruncated) {
21714
- stderrText = `${stderrText}${stderrText ? "\n" : ""}[Output truncated to 112 KiB per stream.]`;
21715
- }
21716
- resolveExecution({
21717
- exitCode: timedOut || spawnError ? -1 : code ?? -1,
21718
- stdout: Buffer.concat(stdout).toString("utf8"),
21719
- stderr: stderrText,
21720
- durationMs: Date.now() - startedAt,
21721
- outputTruncated,
21722
- timedOut
21723
- });
21724
- });
21725
- });
21726
- }
21727
-
21728
- // src/providers/chat/codex-app-server.ts
21729
- function codexChatProvider(request, attachments) {
21730
- let write;
21731
- let threadId = request.sessionId;
21732
- let hasStartedTurn = false;
21733
- const send = (message) => write?.(`${JSON.stringify(message)}
21734
- `);
21735
- const options = {
21736
- cwd: request.workdir,
21737
- approvalPolicy: "never",
21738
- sandbox: request.permissionMode === "full" ? "danger-full-access" : "read-only",
21739
- ...request.model ? { model: request.model } : {}
21740
- };
21741
- const threadRequest = () => send({
21742
- id: 2,
21743
- method: threadId ? "thread/resume" : "thread/start",
21744
- params: { ...options, ...threadId ? { threadId } : { ephemeral: false } }
21745
- });
21746
- let forked = false;
21747
- const forkRequest = () => send({
21748
- id: 4,
21749
- method: "thread/fork",
21750
- params: { ...options, threadId, ephemeral: false, excludeTurns: true }
21751
- });
21752
- const startTurn = () => {
21753
- if (hasStartedTurn) return;
21754
- hasStartedTurn = true;
21755
- const input2 = [];
21756
- if (request.prompt) input2.push({ type: "text", text: request.prompt });
21757
- for (const attachment of attachments) {
21758
- if (attachment.kind === "image") input2.push({ type: "localImage", path: attachment.path });
21759
- else input2.push({ type: "text", text: `\u9644\u4EF6\u6587\u4EF6\uFF1A${attachment.name}
21760
- \u672C\u673A\u8DEF\u5F84\uFF1A${attachment.path}` });
21761
- }
21762
- send({ id: 3, method: "turn/start", params: {
21763
- threadId,
21764
- input: input2,
21765
- cwd: request.workdir,
21766
- approvalPolicy: "never",
21767
- sandboxPolicy: request.permissionMode === "full" ? { type: "dangerFullAccess" } : { type: "readOnly", access: { type: "restricted", includePlatformDefaults: true, readableRoots: [request.workdir] } },
21768
- ...request.model ? { model: request.model } : {},
21769
- ...request.reasoningEffort ? { effort: request.reasoningEffort } : {}
21770
- } });
21771
- };
21772
- const empty = () => ({ display: [] });
21773
- return {
21774
- id: "codex",
21775
- buildLaunch() {
21776
- return resolveExecutable("codex", ["app-server", "--listen", "stdio://", ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"']], providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
21777
- },
21778
- startInput(writer) {
21779
- write = writer;
21780
- send({ id: 1, method: "initialize", params: {
21781
- clientInfo: { name: "echo_cli_chat", title: "Echo CLI Chat", version: "1.0" },
21782
- capabilities: { experimentalApi: true }
21783
- } });
21784
- },
21785
- parseLine(line) {
21786
- const message = tryJson(line);
21787
- if (!message) return empty();
21788
- if (message.id !== void 0 && !message.method) {
21789
- const error62 = message.error;
21790
- if (error62 && message.id === 2 && threadId && !forked && isWriterConflict(str(error62.message))) {
21791
- forked = true;
21792
- forkRequest();
21793
- return { display: [`\u25CF \u4F1A\u8BDD ${threadId} \u6B63\u88AB\u5176\u4ED6 Codex \u7A97\u53E3\u5360\u7528\uFF0C\u5DF2\u590D\u5236\u5386\u53F2\u7EE7\u7EED`] };
21794
- }
21795
- if (error62) return { display: [], turnError: str(error62.message) ?? "Codex \u4F1A\u8BDD\u8BF7\u6C42\u5931\u8D25", endProcess: true };
21796
- if (message.id === 1) {
21797
- send({ method: "initialized" });
21798
- threadRequest();
21799
- return empty();
21800
- }
21801
- if (message.id === 2 || message.id === 4) {
21802
- const result = message.result;
21803
- const thread = result?.thread;
21804
- const id = str(thread?.id);
21805
- if (!id) return { display: [], turnError: "Codex \u672A\u8FD4\u56DE\u539F\u751F\u4F1A\u8BDD ID", endProcess: true };
21806
- threadId = id;
21807
- startTurn();
21808
- return { display: [`\u25CF \u4F1A\u8BDD ${id}`], sessionId: id };
21809
- }
21810
- return empty();
21811
- }
21812
- const params = message.params ?? {};
21813
- if (params.threadId && params.threadId !== threadId) return empty();
21814
- if (message.id !== void 0) {
21815
- send({ id: message.id, error: { code: -32601, message: "\u5F53\u524D\u804A\u5929\u5C1A\u672A\u63A5\u5165\u4EA4\u4E92\u5F0F\u6743\u9650\u6216\u95EE\u7B54" } });
21816
- return { display: [], turnError: "CLI \u6B63\u5728\u8BF7\u6C42\u4EA4\u4E92\u786E\u8BA4\uFF0C\u5F53\u524D\u804A\u5929\u5C1A\u672A\u63A5\u5165\u6B64\u64CD\u4F5C\u3002", endProcess: true };
21817
- }
21818
- const itemId = str(params.itemId) ?? "";
21819
- switch (message.method) {
21820
- case "item/agentMessage/delta":
21821
- case "item/reasoning/textDelta":
21822
- case "item/reasoning/summaryTextDelta": {
21823
- const text = typeof params.delta === "string" ? params.delta : "";
21824
- return { display: [], chatEvents: itemId && text ? [{ event: message.method === "item/agentMessage/delta" ? "text_delta" : "thought_delta", item_id: itemId, text }] : [] };
21825
- }
21826
- case "turn/plan/updated": {
21827
- const plan = Array.isArray(params.plan) ? params.plan : [];
21828
- return { display: [], chatEvents: [{ event: "item", item: {
21829
- itemId: "plan",
21830
- type: "plan",
21831
- entries: plan.map((entry) => ({ content: String(entry.step ?? ""), status: String(entry.status ?? "pending") }))
21832
- } }] };
21833
- }
21834
- case "item/started":
21835
- case "item/completed": {
21836
- const item = params.item ?? {};
21837
- const id = str(item.id);
21838
- if (!id || item.type === "userMessage") return empty();
21839
- const completed = message.method === "item/completed";
21840
- const status = completed ? item.status === "failed" ? "failed" : "completed" : "in_progress";
21841
- let normalized;
21842
- switch (item.type) {
21843
- case "agentMessage":
21844
- normalized = { itemId: id, type: "text", text: String(item.text ?? ""), status };
21845
- break;
21846
- case "reasoning": {
21847
- const summary = Array.isArray(item.summary) ? item.summary.map(String).join("\n\n") : "";
21848
- normalized = { itemId: id, type: "thought", text: summary, status };
21849
- break;
21850
- }
21851
- case "plan":
21852
- normalized = { itemId: id, type: "text", text: String(item.text ?? ""), status };
21853
- break;
21854
- case "commandExecution":
21855
- normalized = { itemId: id, type: "tool_call", name: "shell", kind: "execute", title: String(item.command ?? "\u6267\u884C\u547D\u4EE4"), input: String(item.command ?? ""), output: clip(String(item.aggregatedOutput ?? ""), 64e3), text: clip(String(item.aggregatedOutput ?? ""), 64e3), status };
21856
- break;
21857
- case "fileChange":
21858
- normalized = { itemId: id, type: "tool_call", name: "file_change", kind: "edit", title: "\u4FEE\u6539\u6587\u4EF6", input: clip(JSON.stringify(item.changes ?? []), 64e3), text: clip(JSON.stringify(item.changes ?? []), 64e3), status };
21859
- break;
21860
- case "mcpToolCall":
21861
- normalized = { itemId: id, type: "tool_call", name: String(item.tool ?? "MCP"), kind: "call", title: String(item.tool ?? "\u5DE5\u5177\u8C03\u7528"), input: clip(JSON.stringify(item.arguments ?? {}), 64e3), ...completed ? { output: clip(JSON.stringify(item.result ?? item.error ?? {}), 64e3) } : {}, text: clip(JSON.stringify(item.result ?? item.arguments ?? {}), 64e3), status };
21862
- break;
21863
- default:
21864
- normalized = { itemId: id, type: "tool_call", name: String(item.type ?? "tool"), title: String(item.type ?? "\u6267\u884C\u8FC7\u7A0B"), status };
21865
- break;
21866
- }
21867
- if (completed && normalized.type === "thought" && !normalized.text) return empty();
21868
- return {
21869
- display: [],
21870
- chatEvents: [{ event: "item", item: normalized }],
21871
- ...completed && item.type === "agentMessage" ? { message: String(item.text ?? "") } : {}
21872
- };
21873
- }
21874
- case "turn/completed": {
21875
- const turn = params.turn ?? {};
21876
- const error62 = turn.error ?? {};
21877
- if (turn.status !== "completed") return { display: [], turnError: str(error62.message) ?? (turn.status === "interrupted" ? "\u6267\u884C\u5DF2\u4E2D\u65AD" : "Codex \u672C\u8F6E\u6267\u884C\u5931\u8D25"), endProcess: true };
21878
- return { display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"], turnCompleted: true, endProcess: true };
21879
- }
21880
- default:
21881
- return empty();
21882
- }
21883
- }
21884
- };
21885
- }
21886
- function isWriterConflict(message) {
21887
- return !!message && /active writer|thread-store conflict/i.test(message);
21888
- }
21889
-
21890
- // src/providers/chat/claude-stream-json.ts
21891
- var TOOL_KINDS = {
21892
- bash: "execute",
21893
- read: "read",
21894
- notebookread: "read",
21895
- glob: "search",
21896
- grep: "search",
21897
- ls: "read",
21898
- edit: "edit",
21899
- multiedit: "edit",
21900
- write: "write",
21901
- notebookedit: "edit",
21902
- webfetch: "fetch",
21903
- websearch: "fetch",
21904
- todowrite: "other",
21905
- task: "other"
21906
- };
21907
- function toolKind(name) {
21908
- const key = name.toLowerCase();
21909
- if (key.startsWith("mcp__")) return "mcp";
21910
- return TOOL_KINDS[key] ?? "other";
21911
- }
21912
- function toolPath(input2, partial2) {
21913
- const parsed = input2 && typeof input2 === "object" && Object.keys(input2).length ? input2 : tryJson(partial2) ?? {};
21914
- return str(parsed.file_path) ?? str(parsed.notebook_path) ?? str(parsed.path);
21915
- }
21916
- var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21917
- var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record3(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21918
- function claudeChatProvider(attachments) {
21919
- let messageID = "";
21920
- let messageSequence = 0;
21921
- let hasText = false;
21922
- const blocks = /* @__PURE__ */ new Map();
21923
- const tools = /* @__PURE__ */ new Map();
21924
- const asItem = (block, status, output2) => ({ event: "item", item: {
21925
- itemId: block.id,
21926
- type: block.type,
21927
- status,
21928
- ...block.type === "tool_call" ? { name: block.name, title: block.name, kind: toolKind(block.name), ...toolPath(block.input, block.partialInput) ? { path: toolPath(block.input, block.partialInput) } : {}, input: clip(block.partialInput || JSON.stringify(block.input), 64e3), ...output2 !== void 0 ? { output: clip(output2, 64e3), text: clip(output2, 64e3) } : {} } : { text: block.text }
21929
- } });
21930
- return {
21931
- id: "claude",
21932
- buildLaunch(request) {
21933
- const files = attachments.map((file2) => `\u9644\u4EF6\u6587\u4EF6\uFF1A${file2.name}
21934
- \u672C\u673A\u8DEF\u5F84\uFF1A${file2.path}`).join("\n\n");
21935
- const launch = claudeProvider.buildLaunch({ ...request, prompt: [request.prompt, files].filter(Boolean).join("\n\n") });
21936
- launch.args.push("--include-partial-messages");
21937
- return launch;
21938
- },
21939
- parseLine(line) {
21940
- const envelope = tryJson(line);
21941
- if (!envelope) return { display: line.trim() ? [line] : [] };
21942
- const sessionId = str(envelope.session_id);
21943
- const base = sessionId ? { sessionId } : {};
21944
- const events = [];
21945
- if (envelope.parent_tool_use_id) return { ...base, display: [] };
21946
- if (envelope.type === "stream_event") {
21947
- const event = record3(envelope.event);
21948
- const index = Number(event.index ?? 0);
21949
- if (event.type === "message_start") {
21950
- messageID = str(record3(event.message).id) ?? `message:${++messageSequence}`;
21951
- blocks.clear();
21952
- } else if (event.type === "content_block_start") {
21953
- if (!messageID) messageID = `message:${++messageSequence}`;
21954
- const part = record3(event.content_block);
21955
- const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21956
- if (!["tool_use", "thinking", "text"].includes(String(part.type))) return { ...base, display: [] };
21957
- const block = { id: type === "tool_call" ? str(part.id) ?? `${messageID}:${index}` : `${messageID}:${index}`, type, name: str(part.name) ?? "tool", text: String(part.text ?? part.thinking ?? ""), input: part.input ?? {}, partialInput: "" };
21958
- blocks.set(index, block);
21959
- if (type === "tool_call") tools.set(block.id, block);
21960
- events.push(asItem(block, "in_progress"));
21961
- } else if (event.type === "content_block_delta") {
21962
- const block = blocks.get(index);
21963
- const delta = record3(event.delta);
21964
- if (!block) return { ...base, display: [] };
21965
- if (delta.type === "text_delta" || delta.type === "thinking_delta") {
21966
- const text = String(delta.text ?? delta.thinking ?? "");
21967
- block.text += text;
21968
- if (delta.type === "text_delta") hasText ||= !!text;
21969
- events.push({ event: delta.type === "text_delta" ? "text_delta" : "thought_delta", item_id: block.id, text });
21970
- } else if (delta.type === "input_json_delta") {
21971
- block.partialInput += String(delta.partial_json ?? "");
21972
- if (block.partialInput.length > 64e3) block.partialInput = block.partialInput.slice(0, 64e3);
21973
- events.push(asItem(block, "in_progress"));
21974
- }
21975
- } else if (event.type === "content_block_stop") {
21976
- const block = blocks.get(index);
21977
- if (block && block.type !== "tool_call") events.push(asItem(block, "completed"));
21978
- }
21979
- } else if (envelope.type === "assistant") {
21980
- const message = record3(envelope.message);
21981
- const id = str(message.id) || messageID || `message:${++messageSequence}`;
21982
- const parts = Array.isArray(message.content) ? message.content : [];
21983
- parts.forEach((value, index) => {
21984
- const part = record3(value);
21985
- if (!["text", "thinking", "tool_use"].includes(String(part.type))) return;
21986
- const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21987
- const block = { id: type === "tool_call" ? str(part.id) ?? `${id}:${index}` : `${id}:${index}`, type, name: str(part.name) ?? "tool", text: String(part.text ?? part.thinking ?? ""), input: part.input ?? {}, partialInput: "" };
21988
- if (type === "tool_call") tools.set(block.id, block);
21989
- if (type === "text") hasText ||= !!block.text;
21990
- events.push(asItem(block, type === "tool_call" ? "in_progress" : "completed"));
21991
- });
21992
- } else if (envelope.type === "user") {
21993
- const message = record3(envelope.message);
21994
- for (const value of Array.isArray(message.content) ? message.content : []) {
21995
- const part = record3(value);
21996
- if (part.type !== "tool_result") continue;
21997
- const id = str(part.tool_use_id);
21998
- if (!id) continue;
21999
- const block = tools.get(id) ?? { id, type: "tool_call", name: "tool", text: "", input: {}, partialInput: "" };
22000
- events.push(asItem(block, part.is_error === true ? "failed" : "completed", textContent(part.content)));
22001
- }
22002
- } else if (envelope.type === "result") {
22003
- const text = str(envelope.result) ?? "";
22004
- if (envelope.is_error === true) {
22005
- const errors = Array.isArray(envelope.errors) ? envelope.errors.map(String).join("\n") : "";
22006
- return { ...base, display: [], turnError: text || errors || "Claude \u672C\u8F6E\u6267\u884C\u5931\u8D25", endProcess: true };
22007
- }
22008
- if (!hasText && text) events.push({ event: "item", item: { itemId: "answer", type: "text", text, status: "completed" } });
22009
- return { ...base, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"], message: text, turnCompleted: true, chatEvents: events, endProcess: true };
22010
- }
22011
- return { ...base, display: [], chatEvents: events };
22280
+ // src/providers/kiro-quota.ts
22281
+ import { execFile as execFile4 } from "node:child_process";
22282
+ import { tmpdir } from "node:os";
22283
+ import { promisify as promisify2, stripVTControlCharacters } from "node:util";
22284
+ var execFileAsync2 = promisify2(execFile4);
22285
+ var amount = (value) => Number(value.replace(/,/g, ""));
22286
+ var rounded = (value) => Math.round(value * 100) / 100;
22287
+ function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
22288
+ const text = stripVTControlCharacters(stdout).replace(/\r/g, "");
22289
+ const usage = text.match(/^\s*Credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+covered in plan\s*\)/im);
22290
+ if (!usage) throw new Error("Kiro \u672A\u8FD4\u56DE\u53EF\u8BC6\u522B\u7684\u79EF\u5206\u6570\u636E\uFF0C\u8BF7\u786E\u8BA4 CLI \u5DF2\u767B\u5F55\u4E14 /usage \u53EF\u7528");
22291
+ const used = amount(usage[1]);
22292
+ const total = amount(usage[2]);
22293
+ if (!Number.isFinite(used) || !Number.isFinite(total) || used < 0 || total < 0) throw new Error("Kiro \u8FD4\u56DE\u7684\u79EF\u5206\u6570\u503C\u65E0\u6548");
22294
+ const date5 = text.match(/resets on\s+(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2})/i)?.[1];
22295
+ let resetDate;
22296
+ if (date5) {
22297
+ resetDate = date5.includes("-") ? date5 : `${now.getFullYear()}-${date5.replace("/", "-")}`;
22298
+ if (!date5.includes("-") && (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() < new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) {
22299
+ resetDate = `${now.getFullYear() + 1}-${date5.replace("/", "-")}`;
22012
22300
  }
22013
- };
22301
+ }
22302
+ const reset = resetDate ? (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() : NaN;
22303
+ const plan = text.match(/Estimated Usage[^\n]*\|\s*(KIRO[^|\n]*)/i)?.[1]?.trim();
22304
+ const windows = [{
22305
+ key: "kiro:plan",
22306
+ label: plan ? `\u5957\u9910\u79EF\u5206 \xB7 ${plan}` : "\u5957\u9910\u79EF\u5206",
22307
+ kind: "credits",
22308
+ total,
22309
+ used,
22310
+ remaining: rounded(Math.max(0, total - used)),
22311
+ unit: "credits",
22312
+ used_percent: total > 0 ? Math.min(100, rounded(used / total * 100)) : 100,
22313
+ resets_at: Number.isFinite(reset) ? Math.floor(reset / 1e3) : 0,
22314
+ ...resetDate && Number.isFinite(reset) ? { reset_date: resetDate } : {},
22315
+ estimated: true
22316
+ }];
22317
+ const pools = /^\s*(Bonus|Trial|Free trial|Add[ -]on|Purchased) credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+(?:used|consumed|covered)[^)]*\)([^\n]*)/gim;
22318
+ for (const match of text.matchAll(pools)) {
22319
+ const poolUsed = amount(match[2]);
22320
+ const poolTotal = amount(match[3]);
22321
+ if (![poolUsed, poolTotal].every((value) => Number.isFinite(value) && value >= 0)) throw new Error("Kiro \u8FD4\u56DE\u7684\u989D\u5916\u79EF\u5206\u6570\u503C\u65E0\u6548");
22322
+ const expires = match[4]?.match(/expir(?:es?|y|ation)(?: on| at|:)?\s+(\d{4}-\d{2}-\d{2})/i)?.[1];
22323
+ const expiresAt = expires ? (/* @__PURE__ */ new Date(`${expires}T00:00:00`)).getTime() : NaN;
22324
+ const key = match[1].toLowerCase().replace(/[ -]/g, "");
22325
+ windows.push({
22326
+ key: `kiro:${key}`,
22327
+ label: /bonus|trial/i.test(key) ? "\u8D60\u9001\u79EF\u5206" : "\u52A0\u8D2D\u79EF\u5206",
22328
+ kind: "credits",
22329
+ total: poolTotal,
22330
+ used: poolUsed,
22331
+ remaining: rounded(Math.max(0, poolTotal - poolUsed)),
22332
+ unit: "credits",
22333
+ resets_at: 0,
22334
+ estimated: true,
22335
+ ...Number.isFinite(expiresAt) ? { expires_at: Math.floor(expiresAt / 1e3) } : {}
22336
+ });
22337
+ }
22338
+ return windows;
22014
22339
  }
22015
-
22016
- // src/providers/chat/index.ts
22017
- var CHAT_PROVIDERS = ["codex", "claude"];
22018
- function resolveChatProvider(type, request, attachments) {
22019
- switch (type) {
22020
- case "codex":
22021
- return codexChatProvider(request, attachments);
22022
- case "claude":
22023
- return claudeChatProvider(attachments);
22024
- default:
22025
- throw new Error(`\u6B64 CLI \u7684\u5B9E\u65F6\u804A\u5929\u9A71\u52A8\u5C1A\u672A\u542F\u7528\uFF1A${type}`);
22340
+ async function readKiroQuotaWindows() {
22341
+ const launch = launchCli({ spec: requireCliSpec("kiro"), args: ["chat", "--no-interactive", "/usage"] });
22342
+ try {
22343
+ const { stdout, stderr } = await execFileAsync2(launch.executable, launch.args, { env: launch.env, cwd: tmpdir(), timeout: 3e4, maxBuffer: 1024 * 1024, windowsHide: true });
22344
+ return parseKiroQuota(`${stdout}
22345
+ ${stderr}`);
22346
+ } catch (error62) {
22347
+ if (error62 instanceof Error && error62.message.startsWith("Kiro ")) throw error62;
22348
+ throw new Error("Kiro \u79EF\u5206\u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A CLI \u767B\u5F55\u72B6\u6001\u3001\u7F51\u7EDC\u53CA /usage \u547D\u4EE4");
22026
22349
  }
22027
22350
  }
22028
22351
 
22029
- // src/providers/model-catalog-collector.ts
22030
- import { createHash } from "node:crypto";
22031
- import { stat as stat2 } from "node:fs/promises";
22032
-
22033
22352
  // src/providers/model-catalog.ts
22034
- import { spawn as spawn6 } from "node:child_process";
22353
+ import { spawn as spawn5 } from "node:child_process";
22035
22354
  import { readFile as readFile4 } from "node:fs/promises";
22036
22355
  import { homedir as homedir6 } from "node:os";
22037
22356
  import { isAbsolute, join as join9, resolve as resolve2 } from "node:path";
22038
22357
 
22039
22358
  // src/providers/kiro-models.ts
22040
- import { spawn as spawn5 } from "node:child_process";
22041
- import { createInterface } from "node:readline";
22359
+ import { spawn as spawn4 } from "node:child_process";
22360
+ import { createInterface as createInterface2 } from "node:readline";
22042
22361
  async function readKiroNativeModels(launch, cwd, options = {}) {
22043
- const child = spawn5(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
22044
- const lines = createInterface({ input: child.stdout });
22362
+ const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
22363
+ const lines = createInterface2({ input: child.stdout });
22045
22364
  let nextId = 0;
22046
22365
  let failure2;
22047
22366
  const pending = /* @__PURE__ */ new Map();
@@ -22273,10 +22592,14 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
22273
22592
  return catalog;
22274
22593
  }
22275
22594
  var MODEL_LIST_TIMEOUT_MS = 2e4;
22595
+ function cliExecutable(id) {
22596
+ const spec = requireCliSpec(id);
22597
+ return process.env[spec.overrideEnv]?.trim() || resolveCliCommand(cliCommand(spec));
22598
+ }
22276
22599
  function runModelListCommand(executable, args, label, environment) {
22277
22600
  return new Promise((resolve7, reject) => {
22278
22601
  const launch = directLaunch2(executable, args);
22279
- const child = spawn6(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
22602
+ const child = spawn5(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
22280
22603
  let stdout = "";
22281
22604
  let stderr = "";
22282
22605
  const timer = setTimeout(() => {
@@ -22304,8 +22627,8 @@ function runModelListCommand(executable, args, label, environment) {
22304
22627
  }
22305
22628
  async function readKiroModelCatalog() {
22306
22629
  const environment = mergeShellProxyEnvironment(await hydrateShellPath(), providerEnvironment());
22307
- const override = process.env.TOC_OCRA_KIRO_PATH;
22308
- const listLaunch = resolveExecutable("kiro-cli", ["chat", "--list-models", "--format", "json"], environment, override);
22630
+ const kiro = requireCliSpec("kiro");
22631
+ const listLaunch = launchCli({ spec: kiro, args: ["chat", "--list-models", "--format", "json"], env: environment });
22309
22632
  const output2 = await runModelListCommand(listLaunch.executable, listLaunch.args, "kiro-cli", environment);
22310
22633
  let listed;
22311
22634
  try {
@@ -22318,7 +22641,7 @@ async function readKiroModelCatalog() {
22318
22641
  ...listed.default_model ? { default_model: listed.default_model } : {},
22319
22642
  models: listed.models.map((model) => ({ model_id: model.id, model_name: model.name, ...model.description ? { description: model.description } : {}, supported_reasoning_efforts: [] }))
22320
22643
  };
22321
- const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
22644
+ const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
22322
22645
  const [payload, content] = await Promise.all([
22323
22646
  readKiroNativeModels(launch, homedir6(), { catalog: base }),
22324
22647
  readFile4(join9(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
@@ -22424,7 +22747,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
22424
22747
  }
22425
22748
  async function readGrokModelCatalog() {
22426
22749
  const config2 = await readFile4(join9(grokHome(), "config.toml"), "utf8").catch(() => "");
22427
- const output2 = await runModelListCommand(resolveCliCommand("grok"), ["models"], "grok");
22750
+ const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
22428
22751
  const catalog = parseGrokModelCatalog(output2, config2);
22429
22752
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
22430
22753
  return catalog;
@@ -22441,36 +22764,315 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
22441
22764
  if (defaultModel) catalog.default_model = defaultModel;
22442
22765
  return catalog;
22443
22766
  }
22444
- async function readOpencodeModelCatalog() {
22445
- const config2 = await readFile4(join9(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join9(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22446
- const output2 = await runModelListCommand(resolveCliCommand("opencode"), ["models"], "opencode");
22447
- const catalog = parseOpencodeModelCatalog(output2, config2);
22448
- if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
22449
- return catalog;
22767
+ async function readOpencodeModelCatalog() {
22768
+ const config2 = await readFile4(join9(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join9(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22769
+ const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
22770
+ const catalog = parseOpencodeModelCatalog(output2, config2);
22771
+ if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
22772
+ return catalog;
22773
+ }
22774
+ var TEN_MINUTES = 10 * 60 * 1e3;
22775
+ var MODEL_SOURCES = {
22776
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join9(claudeHome(), "settings.json")] },
22777
+ codex: {
22778
+ read: readCodexModelCatalog,
22779
+ watchFiles: () => {
22780
+ const home = codexHome();
22781
+ return [join9(home, "config.toml"), join9(home, "models_cache.json")];
22782
+ },
22783
+ // model_catalog_json may point anywhere; a periodic re-read covers it.
22784
+ refreshEveryMs: TEN_MINUTES
22785
+ },
22786
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join9(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22787
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join9(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22788
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join9(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22789
+ opencode: {
22790
+ read: readOpencodeModelCatalog,
22791
+ watchFiles: () => [join9(opencodeHome(), "opencode.json"), join9(opencodeHome(), "opencode.jsonc")],
22792
+ refreshEveryMs: TEN_MINUTES
22793
+ }
22794
+ };
22795
+
22796
+ // src/providers/registry.ts
22797
+ var ADAPTERS = {
22798
+ codex: { headless: codexProvider, chat: codexChatProvider, models: MODEL_SOURCES.codex, quota: readCodexQuotaWindows },
22799
+ claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude },
22800
+ grok: { headless: grokProvider, models: MODEL_SOURCES.grok },
22801
+ // ACP CLIs: one shared driver (acp/acp-driver.ts), one launch spec each (acp/acp-agents.ts).
22802
+ gemini: { headless: geminiAcpProvider, models: MODEL_SOURCES.gemini, legacy: { headless: geminiProvider, restrictedPermission: false } },
22803
+ opencode: { headless: opencodeProvider, models: MODEL_SOURCES.opencode },
22804
+ kiro: { headless: kiroAcpProvider, models: MODEL_SOURCES.kiro, quota: readKiroQuotaWindows, legacy: { headless: kiroProvider, restrictedPermission: true } }
22805
+ };
22806
+ function catalogRow(spec) {
22807
+ return {
22808
+ ...spec,
22809
+ ...ADAPTERS[spec.id],
22810
+ detectCmd: cliCommand(spec),
22811
+ ...spec.commandAliases?.length ? { detectCmdAliases: spec.commandAliases } : {},
22812
+ ...spec.requiredCommands?.length ? { detectRequiredCommands: spec.requiredCommands } : {},
22813
+ ...spec.unsupportedPlatforms?.length ? { detectUnsupportedRuntimes: spec.unsupportedPlatforms } : {}
22814
+ };
22815
+ }
22816
+ var CLI_CATALOG = CLI_SPECS.map(catalogRow);
22817
+ function catalogEntry(idOrAlias) {
22818
+ const id = cliSpec(idOrAlias)?.id;
22819
+ return id ? CLI_CATALOG.find((entry) => entry.id === id) : void 0;
22820
+ }
22821
+ var CHAT_PROVIDERS = CLI_CATALOG.filter((entry) => entry.chat).map((entry) => entry.id);
22822
+ function modelSources() {
22823
+ return Object.fromEntries(CLI_CATALOG.flatMap((entry) => entry.models ? [[entry.id, entry.models]] : []));
22824
+ }
22825
+ function resolveRunnableCli(agentType, mode, platform2 = currentPlatform.id) {
22826
+ const row = catalogEntry(agentType);
22827
+ const entry = row ? withDriverChoice(row) : void 0;
22828
+ if (!entry) return { failure: cliFailure("cliUnsupported", { label: agentType }) };
22829
+ const context = { label: entry.label };
22830
+ if (!supportsPlatform(entry, platform2)) return { failure: cliFailure("platformUnsupported", context) };
22831
+ if (mode.chat ? !entry.chat : !entry.headless) {
22832
+ return { failure: { kind: "cliUnsupported", message: mode.chat ? `${entry.label} \u7684\u5B9E\u65F6\u804A\u5929\u9A71\u52A8\u5C1A\u672A\u542F\u7528` : `${entry.label} \u6682\u4E0D\u652F\u6301\u65E0\u754C\u9762\u6267\u884C` } };
22833
+ }
22834
+ if (mode.permissionMode !== "full" && !entry.restrictedPermission) return { failure: cliFailure("permissionUnsupported", context) };
22835
+ return { entry };
22836
+ }
22837
+ function withDriverChoice(entry) {
22838
+ const variable = `TOC_OCRA_${entry.id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_DRIVER`;
22839
+ if (!entry.legacy || process.env[variable]?.trim().toLowerCase() !== "legacy") return entry;
22840
+ const { restrictedPermission: _acp, ...rest } = entry;
22841
+ return { ...rest, headless: entry.legacy.headless, ...entry.legacy.restrictedPermission ? { restrictedPermission: true } : {} };
22842
+ }
22843
+ function buildProviderDetectionCommands(configs = CLI_CATALOG) {
22844
+ return configs.flatMap(
22845
+ (config2) => [config2.detectCmd, ...config2.detectCmdAliases ?? []].map((cmd) => ({
22846
+ id: config2.id,
22847
+ cmd,
22848
+ ...config2.detectRequiredCommands?.length ? { requiredCommands: config2.detectRequiredCommands } : {},
22849
+ ...config2.detectUnsupportedRuntimes?.length ? { unsupportedRuntimes: config2.detectUnsupportedRuntimes } : {}
22850
+ }))
22851
+ );
22852
+ }
22853
+ var DETECTION_COMMANDS = buildProviderDetectionCommands();
22854
+ function getProviderDetectionProbeCommands(commands = DETECTION_COMMANDS, runtime = process.platform) {
22855
+ return [...new Set(commands.filter((command) => !command.unsupportedRuntimes?.includes(runtime)).flatMap((command) => [command.cmd, ...command.requiredCommands ?? []]))];
22856
+ }
22857
+ function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COMMANDS, runtime = process.platform) {
22858
+ const detected = /* @__PURE__ */ new Map();
22859
+ for (const command of commands) {
22860
+ if (command.unsupportedRuntimes?.includes(runtime)) continue;
22861
+ if (!foundCommands.has(command.cmd)) continue;
22862
+ if (!(command.requiredCommands ?? []).every((required2) => foundCommands.has(required2))) continue;
22863
+ if (!detected.has(command.id)) detected.set(command.id, command.cmd);
22864
+ }
22865
+ return detected;
22866
+ }
22867
+
22868
+ // src/providers/detection.ts
22869
+ function probeVersion(path, args) {
22870
+ if (args.length === 0) return Promise.resolve({});
22871
+ return new Promise((resolve7) => {
22872
+ const launch = directLaunch2(path, args);
22873
+ const child = spawn6(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
22874
+ let stdout = "";
22875
+ let stderr = "";
22876
+ let settled = false;
22877
+ let timer;
22878
+ const finish = (result) => {
22879
+ if (settled) return;
22880
+ settled = true;
22881
+ if (timer) clearTimeout(timer);
22882
+ resolve7(result);
22883
+ };
22884
+ timer = setTimeout(() => {
22885
+ child.kill("SIGKILL");
22886
+ finish({ detail: "version probe timeout" });
22887
+ }, 5e3);
22888
+ child.stdout.on("data", (chunk) => {
22889
+ stdout += chunk.toString();
22890
+ });
22891
+ child.stderr.on("data", (chunk) => {
22892
+ stderr += chunk.toString();
22893
+ });
22894
+ child.on("error", (error62) => finish({ detail: error62.message }));
22895
+ child.on("close", (code) => {
22896
+ const detail = (stdout || stderr || `exit ${code ?? "unknown"}`).trim().slice(0, 200);
22897
+ const version2 = stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
22898
+ finish(version2 ? { version: version2, detail } : { detail });
22899
+ });
22900
+ });
22901
+ }
22902
+ var CliDetectionService = class {
22903
+ snapshot;
22904
+ pending;
22905
+ async detect(forceRefresh = false) {
22906
+ if (this.pending) return this.pending;
22907
+ if (!forceRefresh && this.snapshot) return this.snapshot;
22908
+ this.pending = this.detectNow(forceRefresh).finally(() => {
22909
+ this.pending = void 0;
22910
+ });
22911
+ return this.pending;
22912
+ }
22913
+ async detectNow(forceRefresh) {
22914
+ const hydration = await hydrateShellPath({ force: forceRefresh });
22915
+ const addedPathSegments = hydration.ok ? mergePathSegments(hydration.segments) : [];
22916
+ const commands = getProviderDetectionProbeCommands(DETECTION_COMMANDS);
22917
+ const resolved = new Map(commands.map((command) => [command, resolveCliCommandDetailed(command)]));
22918
+ const foundCommands = new Set(commands.filter((command) => resolved.get(command)?.found));
22919
+ const detected = resolveDetectedProviderCommands(foundCommands, DETECTION_COMMANDS);
22920
+ const providers = await Promise.all(CLI_CATALOG.map(async (config2) => {
22921
+ const matchedDetectionCommand = detected.get(config2.id);
22922
+ const result = matchedDetectionCommand ? resolved.get(matchedDetectionCommand) : void 0;
22923
+ const executablePath = result?.found ? result.path : void 0;
22924
+ const installed = Boolean(executablePath);
22925
+ const unsupported = config2.detectUnsupportedRuntimes?.includes(process.platform) ?? false;
22926
+ const diagnostic = executablePath ? await probeVersion(executablePath, config2.versionArguments ?? []) : {};
22927
+ const detail = installed ? diagnostic.detail : unsupported ? "unsupported runtime" : config2.detectRequiredCommands?.length ? "command or required command not found" : "command not found";
22928
+ return {
22929
+ id: config2.id,
22930
+ installed,
22931
+ available: installed && Boolean(config2.headless),
22932
+ ...matchedDetectionCommand ? { matchedDetectionCommand } : {},
22933
+ ...result?.path ? { resolvedPath: result.path } : {},
22934
+ ...diagnostic.version ? { version: diagnostic.version } : {},
22935
+ ...detail ? { detail } : {}
22936
+ };
22937
+ }));
22938
+ this.snapshot = {
22939
+ providers,
22940
+ detectedIds: providers.filter((provider) => provider.installed).map((provider) => provider.id),
22941
+ addedPathSegments,
22942
+ shellHydrationOk: hydration.ok,
22943
+ pathSource: hydration.ok ? "shell_hydrated" : "process_path",
22944
+ pathFailureReason: hydration.failureReason,
22945
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
22946
+ };
22947
+ return this.snapshot;
22948
+ }
22949
+ };
22950
+ var cliDetection = new CliDetectionService();
22951
+
22952
+ // src/runtime/agent-runtime.ts
22953
+ import { randomUUID as randomUUID3 } from "node:crypto";
22954
+ import { join as join15 } from "node:path";
22955
+
22956
+ // src/exec/script-runner.ts
22957
+ import { spawn as spawn7 } from "node:child_process";
22958
+
22959
+ // src/runs/process-tree.ts
22960
+ var KILL_GRACE_MS = 3e3;
22961
+ async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
22962
+ if (!Number.isInteger(rootPid) || rootPid <= 1) return;
22963
+ await currentPlatform.killProcessTree(rootPid, graceMs);
22964
+ }
22965
+
22966
+ // src/exec/script-runner.ts
22967
+ var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
22968
+ function executeScript(command, workdir, timeoutSeconds) {
22969
+ return new Promise((resolveExecution) => {
22970
+ const ownGroup = currentPlatform.runsInOwnProcessGroup;
22971
+ const { executable, args } = currentPlatform.scriptShell(command);
22972
+ const startedAt = Date.now();
22973
+ const stdout = [];
22974
+ const stderr = [];
22975
+ let stdoutBytes = 0;
22976
+ let stderrBytes = 0;
22977
+ let outputTruncated = false;
22978
+ let timedOut = false;
22979
+ let spawnError = "";
22980
+ let settled = false;
22981
+ const append = (target, chunk, currentBytes) => {
22982
+ const remaining = MAX_SCRIPT_OUTPUT_BYTES - currentBytes;
22983
+ if (remaining <= 0) {
22984
+ outputTruncated = true;
22985
+ return currentBytes;
22986
+ }
22987
+ if (chunk.length > remaining) {
22988
+ target.push(chunk.subarray(0, remaining));
22989
+ outputTruncated = true;
22990
+ return MAX_SCRIPT_OUTPUT_BYTES;
22991
+ }
22992
+ target.push(chunk);
22993
+ return currentBytes + chunk.length;
22994
+ };
22995
+ let child;
22996
+ try {
22997
+ child = spawn7(executable, args, {
22998
+ cwd: workdir,
22999
+ env: process.env,
23000
+ detached: ownGroup,
23001
+ shell: false,
23002
+ windowsHide: true,
23003
+ stdio: ["ignore", "pipe", "pipe"]
23004
+ });
23005
+ } catch (error62) {
23006
+ resolveExecution({
23007
+ exitCode: -1,
23008
+ stdout: "",
23009
+ stderr: error62 instanceof Error ? error62.message : String(error62),
23010
+ durationMs: Date.now() - startedAt,
23011
+ outputTruncated: false,
23012
+ timedOut: false
23013
+ });
23014
+ return;
23015
+ }
23016
+ const kill = () => {
23017
+ if (child.exitCode !== null || child.killed) return;
23018
+ try {
23019
+ if (ownGroup && child.pid) process.kill(-child.pid, "SIGKILL");
23020
+ else if (child.pid) void killProcessTree(child.pid, 0);
23021
+ else child.kill("SIGKILL");
23022
+ } catch {
23023
+ try {
23024
+ child.kill("SIGKILL");
23025
+ } catch {
23026
+ }
23027
+ }
23028
+ };
23029
+ const timeout = setTimeout(() => {
23030
+ timedOut = true;
23031
+ kill();
23032
+ }, timeoutSeconds * 1e3);
23033
+ child.stdout.on("data", (chunk) => {
23034
+ stdoutBytes = append(stdout, Buffer.from(chunk), stdoutBytes);
23035
+ });
23036
+ child.stderr.on("data", (chunk) => {
23037
+ stderrBytes = append(stderr, Buffer.from(chunk), stderrBytes);
23038
+ });
23039
+ child.once("error", (error62) => {
23040
+ spawnError = error62.message;
23041
+ });
23042
+ child.once("close", (code) => {
23043
+ if (settled) return;
23044
+ settled = true;
23045
+ clearTimeout(timeout);
23046
+ let stderrText = Buffer.concat(stderr).toString("utf8");
23047
+ if (spawnError) stderrText = `${stderrText}${stderrText ? "\n" : ""}${spawnError}`;
23048
+ if (timedOut) {
23049
+ stderrText = `${stderrText}${stderrText ? "\n" : ""}Command timed out after ${timeoutSeconds} seconds.`;
23050
+ }
23051
+ if (outputTruncated) {
23052
+ stderrText = `${stderrText}${stderrText ? "\n" : ""}[Output truncated to 112 KiB per stream.]`;
23053
+ }
23054
+ resolveExecution({
23055
+ exitCode: timedOut || spawnError ? -1 : code ?? -1,
23056
+ stdout: Buffer.concat(stdout).toString("utf8"),
23057
+ stderr: stderrText,
23058
+ durationMs: Date.now() - startedAt,
23059
+ outputTruncated,
23060
+ timedOut
23061
+ });
23062
+ });
23063
+ });
23064
+ }
23065
+
23066
+ // src/providers/chat/index.ts
23067
+ function resolveChatProvider(type, request, attachments) {
23068
+ const chat = catalogEntry(type)?.chat;
23069
+ if (!chat) throw new Error(`\u6B64 CLI \u7684\u5B9E\u65F6\u804A\u5929\u9A71\u52A8\u5C1A\u672A\u542F\u7528\uFF1A${type}`);
23070
+ return chat(request, attachments);
22450
23071
  }
22451
- var TEN_MINUTES = 10 * 60 * 1e3;
22452
- var MODEL_SOURCES = {
22453
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join9(claudeHome(), "settings.json")] },
22454
- codex: {
22455
- read: readCodexModelCatalog,
22456
- watchFiles: () => {
22457
- const home = codexHome();
22458
- return [join9(home, "config.toml"), join9(home, "models_cache.json")];
22459
- },
22460
- // model_catalog_json may point anywhere; a periodic re-read covers it.
22461
- refreshEveryMs: TEN_MINUTES
22462
- },
22463
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join9(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22464
- grok: { read: readGrokModelCatalog, watchFiles: () => [join9(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22465
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join9(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22466
- opencode: {
22467
- read: readOpencodeModelCatalog,
22468
- watchFiles: () => [join9(opencodeHome(), "opencode.json"), join9(opencodeHome(), "opencode.jsonc")],
22469
- refreshEveryMs: TEN_MINUTES
22470
- }
22471
- };
22472
23072
 
22473
23073
  // src/providers/model-catalog-collector.ts
23074
+ import { createHash } from "node:crypto";
23075
+ import { stat as stat2 } from "node:fs/promises";
22474
23076
  async function fileStamp(path) {
22475
23077
  try {
22476
23078
  const info = await stat2(path);
@@ -22488,14 +23090,14 @@ function reportHash(items) {
22488
23090
  return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
22489
23091
  }
22490
23092
  var ModelCatalogCollector = class {
22491
- constructor(sources = MODEL_SOURCES) {
23093
+ constructor(sources = modelSources()) {
22492
23094
  this.sources = sources;
22493
23095
  }
22494
23096
  sources;
22495
23097
  cache = /* @__PURE__ */ new Map();
22496
23098
  /** CLI ids that have a model source, among the detected ones. */
22497
23099
  supported(detectedIds) {
22498
- return [...new Set(detectedIds.map((id) => id === "claude-code" ? "claude" : id))].filter((id) => id in this.sources).sort();
23100
+ return [...new Set(detectedIds.map((id) => catalogEntry(id)?.id ?? id))].filter((id) => id in this.sources).sort();
22499
23101
  }
22500
23102
  async collect(detectedIds, options = {}) {
22501
23103
  const ids = this.supported(detectedIds);
@@ -22522,183 +23124,11 @@ var ModelCatalogCollector = class {
22522
23124
  }
22523
23125
  };
22524
23126
 
22525
- // src/providers/codex-quota.ts
22526
- import { spawn as spawn7 } from "node:child_process";
22527
- import { createInterface as createInterface2 } from "node:readline";
22528
- async function readCodexQuotaWindows() {
22529
- const launch = resolveExecutable("codex", ["app-server", "--stdio"], providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
22530
- const child = spawn7(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
22531
- let nextId = 0;
22532
- const pending = /* @__PURE__ */ new Map();
22533
- const lines = createInterface2({ input: child.stdout });
22534
- const rejectPending = (error62) => {
22535
- for (const waiter of pending.values()) waiter.reject(error62);
22536
- pending.clear();
22537
- };
22538
- child.once("error", (error62) => rejectPending(error62));
22539
- child.once("exit", (code) => {
22540
- if (pending.size) rejectPending(new Error(`Codex app-server \u5DF2\u9000\u51FA\uFF08${code ?? "unknown"}\uFF09`));
22541
- });
22542
- lines.on("line", (line) => {
22543
- let message;
22544
- try {
22545
- message = JSON.parse(line);
22546
- } catch {
22547
- return;
22548
- }
22549
- if (typeof message.id !== "number") return;
22550
- const waiter = pending.get(message.id);
22551
- if (!waiter) return;
22552
- pending.delete(message.id);
22553
- if (message.error) waiter.reject(new Error(message.error.message || "Codex \u989D\u5EA6\u63A5\u53E3\u8C03\u7528\u5931\u8D25"));
22554
- else waiter.resolve(message.result);
22555
- });
22556
- const request = (method, params) => {
22557
- const id = ++nextId;
22558
- return new Promise((resolve7, reject) => {
22559
- const timer = setTimeout(() => {
22560
- pending.delete(id);
22561
- reject(new Error(`Codex \u989D\u5EA6\u8BFB\u53D6\u8D85\u65F6\uFF08${method}\uFF09`));
22562
- }, 2e4);
22563
- pending.set(id, {
22564
- resolve: (value) => {
22565
- clearTimeout(timer);
22566
- resolve7(value);
22567
- },
22568
- reject: (error62) => {
22569
- clearTimeout(timer);
22570
- reject(error62);
22571
- }
22572
- });
22573
- child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, id, params })}
22574
- `, (error62) => {
22575
- if (!error62) return;
22576
- const waiter = pending.get(id);
22577
- if (waiter) {
22578
- pending.delete(id);
22579
- clearTimeout(timer);
22580
- waiter.reject(error62);
22581
- }
22582
- });
22583
- });
22584
- };
22585
- try {
22586
- await request("initialize", {
22587
- clientInfo: { name: "toc-ocra", title: "Echo device agent", version: "0.2.3" },
22588
- capabilities: { experimentalApi: true }
22589
- });
22590
- child.stdin.write('{"jsonrpc":"2.0","method":"initialized","params":{}}\n');
22591
- const result = await request("account/rateLimits/read", {});
22592
- const buckets = Object.entries(result?.rateLimitsByLimitId ?? {});
22593
- if (!buckets.length && result?.rateLimits) buckets.push([String(result.rateLimits.limitId || "codex"), result.rateLimits]);
22594
- const windows = buckets.flatMap(([limitId, snapshot]) => ["primary", "secondary"].flatMap((key) => {
22595
- const window = snapshot[key];
22596
- if (!window) return [];
22597
- const resetRaw = Number(window.resetsAt);
22598
- const resetsAt = Number.isFinite(resetRaw) && resetRaw > 0 ? Math.floor(resetRaw > 1e10 ? resetRaw / 1e3 : resetRaw) : 0;
22599
- const durationMins = Number(window.windowDurationMins);
22600
- const usedRaw = Number(window.usedPercent);
22601
- const windowLabel = durationMins === 300 ? "5 \u5C0F\u65F6\u989D\u5EA6" : durationMins >= 1e4 ? "\u6BCF\u5468\u989D\u5EA6" : durationMins > 0 ? `${durationMins} \u5206\u949F\u989D\u5EA6` : key === "primary" ? "\u4E3B\u8981\u989D\u5EA6" : "\u6B21\u8981\u989D\u5EA6";
22602
- const bucketName = typeof snapshot.limitName === "string" && snapshot.limitName.trim() ? snapshot.limitName.trim() : limitId === "codex" ? "" : limitId;
22603
- const item = {
22604
- key: `${limitId}:${key}`,
22605
- label: bucketName ? `${bucketName} \xB7 ${windowLabel}` : windowLabel,
22606
- resets_at: resetsAt,
22607
- ...Number.isFinite(usedRaw) && usedRaw >= 0 && usedRaw <= 100 ? { used_percent: usedRaw } : {},
22608
- ...Number.isFinite(durationMins) && durationMins > 0 ? { window_seconds: Math.floor(durationMins * 60) } : {}
22609
- };
22610
- return [item];
22611
- }));
22612
- if (!windows.length || !windows.some((window) => window.resets_at > 0)) throw new Error("Codex \u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u989D\u5EA6\u7A97\u53E3");
22613
- return windows;
22614
- } finally {
22615
- for (const waiter of pending.values()) waiter.reject(new Error("Codex app-server \u5DF2\u5173\u95ED"));
22616
- pending.clear();
22617
- lines.close();
22618
- currentPlatform.stopHelper(child);
22619
- }
22620
- }
22621
-
22622
- // src/providers/kiro-quota.ts
22623
- import { execFile as execFile4 } from "node:child_process";
22624
- import { tmpdir } from "node:os";
22625
- import { promisify as promisify2, stripVTControlCharacters } from "node:util";
22626
- var execFileAsync2 = promisify2(execFile4);
22627
- var amount = (value) => Number(value.replace(/,/g, ""));
22628
- var rounded = (value) => Math.round(value * 100) / 100;
22629
- function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
22630
- const text = stripVTControlCharacters(stdout).replace(/\r/g, "");
22631
- const usage = text.match(/^\s*Credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+covered in plan\s*\)/im);
22632
- if (!usage) throw new Error("Kiro \u672A\u8FD4\u56DE\u53EF\u8BC6\u522B\u7684\u79EF\u5206\u6570\u636E\uFF0C\u8BF7\u786E\u8BA4 CLI \u5DF2\u767B\u5F55\u4E14 /usage \u53EF\u7528");
22633
- const used = amount(usage[1]);
22634
- const total = amount(usage[2]);
22635
- if (!Number.isFinite(used) || !Number.isFinite(total) || used < 0 || total < 0) throw new Error("Kiro \u8FD4\u56DE\u7684\u79EF\u5206\u6570\u503C\u65E0\u6548");
22636
- const date5 = text.match(/resets on\s+(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2})/i)?.[1];
22637
- let resetDate;
22638
- if (date5) {
22639
- resetDate = date5.includes("-") ? date5 : `${now.getFullYear()}-${date5.replace("/", "-")}`;
22640
- if (!date5.includes("-") && (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() < new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) {
22641
- resetDate = `${now.getFullYear() + 1}-${date5.replace("/", "-")}`;
22642
- }
22643
- }
22644
- const reset = resetDate ? (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() : NaN;
22645
- const plan = text.match(/Estimated Usage[^\n]*\|\s*(KIRO[^|\n]*)/i)?.[1]?.trim();
22646
- const windows = [{
22647
- key: "kiro:plan",
22648
- label: plan ? `\u5957\u9910\u79EF\u5206 \xB7 ${plan}` : "\u5957\u9910\u79EF\u5206",
22649
- kind: "credits",
22650
- total,
22651
- used,
22652
- remaining: rounded(Math.max(0, total - used)),
22653
- unit: "credits",
22654
- used_percent: total > 0 ? Math.min(100, rounded(used / total * 100)) : 100,
22655
- resets_at: Number.isFinite(reset) ? Math.floor(reset / 1e3) : 0,
22656
- ...resetDate && Number.isFinite(reset) ? { reset_date: resetDate } : {},
22657
- estimated: true
22658
- }];
22659
- const pools = /^\s*(Bonus|Trial|Free trial|Add[ -]on|Purchased) credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+(?:used|consumed|covered)[^)]*\)([^\n]*)/gim;
22660
- for (const match of text.matchAll(pools)) {
22661
- const poolUsed = amount(match[2]);
22662
- const poolTotal = amount(match[3]);
22663
- if (![poolUsed, poolTotal].every((value) => Number.isFinite(value) && value >= 0)) throw new Error("Kiro \u8FD4\u56DE\u7684\u989D\u5916\u79EF\u5206\u6570\u503C\u65E0\u6548");
22664
- const expires = match[4]?.match(/expir(?:es?|y|ation)(?: on| at|:)?\s+(\d{4}-\d{2}-\d{2})/i)?.[1];
22665
- const expiresAt = expires ? (/* @__PURE__ */ new Date(`${expires}T00:00:00`)).getTime() : NaN;
22666
- const key = match[1].toLowerCase().replace(/[ -]/g, "");
22667
- windows.push({
22668
- key: `kiro:${key}`,
22669
- label: /bonus|trial/i.test(key) ? "\u8D60\u9001\u79EF\u5206" : "\u52A0\u8D2D\u79EF\u5206",
22670
- kind: "credits",
22671
- total: poolTotal,
22672
- used: poolUsed,
22673
- remaining: rounded(Math.max(0, poolTotal - poolUsed)),
22674
- unit: "credits",
22675
- resets_at: 0,
22676
- estimated: true,
22677
- ...Number.isFinite(expiresAt) ? { expires_at: Math.floor(expiresAt / 1e3) } : {}
22678
- });
22679
- }
22680
- return windows;
22681
- }
22682
- async function readKiroQuotaWindows() {
22683
- const launch = resolveExecutable("kiro-cli", ["chat", "--no-interactive", "/usage"], providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
22684
- try {
22685
- const { stdout, stderr } = await execFileAsync2(launch.executable, launch.args, { env: launch.env, cwd: tmpdir(), timeout: 3e4, maxBuffer: 1024 * 1024, windowsHide: true });
22686
- return parseKiroQuota(`${stdout}
22687
- ${stderr}`);
22688
- } catch (error62) {
22689
- if (error62 instanceof Error && error62.message.startsWith("Kiro ")) throw error62;
22690
- throw new Error("Kiro \u79EF\u5206\u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A CLI \u767B\u5F55\u72B6\u6001\u3001\u7F51\u7EDC\u53CA /usage \u547D\u4EE4");
22691
- }
22692
- }
22693
-
22694
23127
  // src/providers/quota-reader.ts
22695
- var quotaReaders = {
22696
- codex: readCodexQuotaWindows,
22697
- kiro: readKiroQuotaWindows
22698
- };
22699
23128
  async function readCLIQuotaReport(agentType) {
22700
- const provider = agentType.trim().toLowerCase();
22701
- const read = quotaReaders[provider];
23129
+ const entry = catalogEntry(agentType);
23130
+ const provider = entry?.id ?? agentType.trim().toLowerCase();
23131
+ const read = entry?.quota;
22702
23132
  if (!read) throw new Error(`${provider || "\u8BE5 CLI"} \u6682\u4E0D\u652F\u6301\u81EA\u52A8\u8BFB\u53D6\u989D\u5EA6\uFF0C\u8BF7\u4F7F\u7528\u624B\u52A8\u7EF4\u62A4`);
22703
23133
  const quotaWindows = await read();
22704
23134
  const now = Math.floor(Date.now() / 1e3);
@@ -22832,8 +23262,8 @@ var OrphanRegistry = class {
22832
23262
  file;
22833
23263
  records = /* @__PURE__ */ new Map();
22834
23264
  writing = Promise.resolve();
22835
- add(record4) {
22836
- this.records.set(record4.runId, record4);
23265
+ add(record5) {
23266
+ this.records.set(record5.runId, record5);
22837
23267
  this.persist();
22838
23268
  }
22839
23269
  remove(runId) {
@@ -22857,12 +23287,12 @@ var OrphanRegistry = class {
22857
23287
  return [];
22858
23288
  }
22859
23289
  const reaped = [];
22860
- for (const record4 of previous) {
22861
- if (!record4 || typeof record4.pid !== "number" || record4.pid <= 1) continue;
22862
- const command = await commandOf(record4.pid);
22863
- if (command && command.includes(basename(record4.executable))) {
22864
- await killProcessTree(record4.pid);
22865
- reaped.push(record4);
23290
+ for (const record5 of previous) {
23291
+ if (!record5 || typeof record5.pid !== "number" || record5.pid <= 1) continue;
23292
+ const command = await commandOf(record5.pid);
23293
+ if (command && command.includes(basename(record5.executable))) {
23294
+ await killProcessTree(record5.pid);
23295
+ reaped.push(record5);
22866
23296
  }
22867
23297
  }
22868
23298
  this.records.clear();
@@ -22878,7 +23308,7 @@ function commandOf(pid) {
22878
23308
  // src/runs/run-supervisor.ts
22879
23309
  import { spawn as spawn8 } from "node:child_process";
22880
23310
  import { mkdir as mkdir5, realpath as realpath2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
22881
- import { basename as basename3, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3 } from "node:path";
23311
+ import { basename as basename3, isAbsolute as isAbsolute3, join as join13, relative as relative2, resolve as resolve3 } from "node:path";
22882
23312
  import { createInterface as createInterface3 } from "node:readline";
22883
23313
 
22884
23314
  // src/session/terminal-line-sanitizer.ts
@@ -23001,11 +23431,39 @@ function clipToCharacterBudget(rows, budget) {
23001
23431
  return { lines: rows, limited: false };
23002
23432
  }
23003
23433
 
23434
+ // src/runs/run-recorder.ts
23435
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3 } from "node:fs";
23436
+ import { homedir as homedir8 } from "node:os";
23437
+ import { join as join11 } from "node:path";
23438
+ var RunRecorder = class _RunRecorder {
23439
+ constructor(path) {
23440
+ this.path = path;
23441
+ }
23442
+ path;
23443
+ home = homedir8();
23444
+ static fromEnvironment(runId, meta3) {
23445
+ const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
23446
+ if (!directory) return void 0;
23447
+ mkdirSync3(directory, { recursive: true });
23448
+ const recorder = new _RunRecorder(join11(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
23449
+ recorder.write({ meta: meta3 });
23450
+ return recorder;
23451
+ }
23452
+ write(frame) {
23453
+ const line = JSON.stringify(frame).split(this.home).join("~");
23454
+ try {
23455
+ appendFileSync2(this.path, `${line}
23456
+ `, { mode: 384 });
23457
+ } catch {
23458
+ }
23459
+ }
23460
+ };
23461
+
23004
23462
  // src/runs/task-attachments.ts
23005
23463
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
23006
23464
  import { constants as constants2 } from "node:fs";
23007
23465
  import { lstat, mkdir as mkdir4, open as open3, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
23008
- import { basename as basename2, isAbsolute as isAbsolute2, join as join11, relative } from "node:path";
23466
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join12, relative } from "node:path";
23009
23467
  function within(root, path) {
23010
23468
  const segment = relative(root, path);
23011
23469
  return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
@@ -23013,7 +23471,7 @@ function within(root, path) {
23013
23471
  async function attachmentDirectory(workdir, messageId) {
23014
23472
  let directory = workdir;
23015
23473
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
23016
- directory = join11(directory, segment);
23474
+ directory = join12(directory, segment);
23017
23475
  await mkdir4(directory, { mode: 448 }).catch((error62) => {
23018
23476
  if (error62.code !== "EEXIST") throw error62;
23019
23477
  });
@@ -23021,7 +23479,7 @@ async function attachmentDirectory(workdir, messageId) {
23021
23479
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
23022
23480
  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");
23023
23481
  }
23024
- if (segment === ".echo") await writeFile4(join11(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
23482
+ if (segment === ".echo") await writeFile4(join12(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
23025
23483
  if (error62.code !== "EEXIST") throw error62;
23026
23484
  });
23027
23485
  }
@@ -23058,9 +23516,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
23058
23516
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
23059
23517
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
23060
23518
  const name = characters.join("") || "attachment";
23061
- const path = join11(directory, `${file2.file_id}-${name}`);
23519
+ const path = join12(directory, `${file2.file_id}-${name}`);
23062
23520
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
23063
- const temporary = join11(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
23521
+ const temporary = join12(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
23064
23522
  try {
23065
23523
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
23066
23524
  signal2.throwIfAborted();
@@ -23089,6 +23547,7 @@ var EXIT_OUTPUT_GRACE_MS = 2e3;
23089
23547
  var RECENT_RUN_TTL_MS = 10 * 6e4;
23090
23548
  var MAX_RECENT_RUNS = 100;
23091
23549
  var MAX_ERROR_ROWS = 40;
23550
+ var SESSION_START_TIMEOUT_MS = 12e4;
23092
23551
  var STALL_CHECK_INTERVAL_MS = 5e3;
23093
23552
  function rowCategory(row) {
23094
23553
  switch (row.trimStart().charAt(0)) {
@@ -23166,6 +23625,16 @@ var RunSupervisor = class {
23166
23625
  * Starts a turn. Refusals (busy workstation, concurrency limit, bad work
23167
23626
  * directory, unknown CLI) are reported as a failed run, never thrown.
23168
23627
  */
23628
+ /**
23629
+ * Different workstations run in parallel without a machine-wide cap by
23630
+ * default; each workstation still runs one turn at a time. A cap applies
23631
+ * only when the operator sets TOC_OCRA_MAX_RUNS / maxConcurrentRuns.
23632
+ * The run being started is already counted in `preparing`.
23633
+ */
23634
+ overConcurrencyCap() {
23635
+ const cap = this.config.maxConcurrentRuns;
23636
+ return cap > 0 && this.active.size + this.preparing.size > cap;
23637
+ }
23169
23638
  async start(payload) {
23170
23639
  if (this.preparing.has(payload.run_id)) return;
23171
23640
  const controller = new AbortController();
@@ -23182,24 +23651,26 @@ var RunSupervisor = class {
23182
23651
  return;
23183
23652
  }
23184
23653
  if (payload.chat_session_id) this.chatRunIds.add(payload.run_id);
23185
- const refuse = async (error62) => {
23186
- this.logger.warn("run-refused", { runId: payload.run_id, error: error62 });
23654
+ const refuse = async (reason) => {
23655
+ const failure2 = typeof reason === "string" ? { kind: "hostFault", message: reason } : reason;
23656
+ this.logger.warn("run-refused", { runId: payload.run_id, error: failure2.message, kind: failure2.kind });
23187
23657
  this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "failed", chat: !!payload.chat_session_id });
23188
- await this.report(payload.run_id, { status: "failed", error: error62, duration_ms: 0 });
23658
+ await this.report(payload.run_id, { status: "failed", error: failure2.message, failure_kind: failure2.kind, duration_ms: 0 });
23189
23659
  };
23190
23660
  if ([...this.active.values()].some((run2) => run2.workstationId === payload.workstation_id) || [...this.preparing].some(([id, run2]) => id !== payload.run_id && run2.workstationId === payload.workstation_id)) {
23191
23661
  return refuse("\u672C\u673A\u8BE5\u5DE5\u4F4D\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
23192
23662
  }
23193
- if (this.active.size + this.preparing.size > this.config.maxConcurrentRuns) {
23663
+ if (this.overConcurrencyCap()) {
23194
23664
  return refuse(`\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650\uFF08${this.config.maxConcurrentRuns}\uFF09`);
23195
23665
  }
23196
23666
  if (!payload.cli_policy?.enabled || payload.cli_policy.version !== 1) return refuse("\u8FD9\u53F0\u7535\u8111\u5C1A\u672A\u6388\u6743\u8FDC\u7A0B\u6267\u884C\uFF0C\u8BF7\u5728 Echo \u7684\u7535\u8111\u6267\u884C\u6743\u9650\u4E2D\u5F00\u542F\u5E76\u5347\u7EA7\u670D\u52A1\u7AEF");
23197
- if (payload.cli_policy.mode !== "full" && !["codex", "claude", "claude-code", "kiro"].includes(payload.agent_type.toLowerCase())) return refuse("\u6B64 CLI \u5C1A\u672A\u652F\u6301\u53D7\u9650\u6743\u9650\uFF0C\u8BF7\u7531\u7535\u8111\u6240\u6709\u8005\u660E\u786E\u9009\u62E9\u5B8C\u6574\u6743\u9650\u540E\u518D\u6267\u884C");
23198
23667
  const permissionMode = payload.cli_policy.mode;
23199
- let provider;
23668
+ const runnable = resolveRunnableCli(payload.agent_type, { chat: Boolean(payload.chat_session_id), permissionMode });
23669
+ if ("failure" in runnable) return refuse(runnable.failure);
23670
+ const cli = runnable.entry;
23671
+ let provider = cli.headless;
23200
23672
  let workdir;
23201
23673
  try {
23202
- provider = resolveHeadlessProvider(payload.agent_type);
23203
23674
  if (payload.task_attachments?.length && !payload.workdir) throw new Error("\u9644\u4EF6\u9700\u8981\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u5DE5\u4F4D\u5DE5\u4F5C\u76EE\u5F55");
23204
23675
  workdir = payload.chat_session_id && !payload.workdir ? await this.defaultChatWorkdir() : await this.validateWorkdir(payload.workdir || this.config.allowedRoots[0]);
23205
23676
  } catch (error62) {
@@ -23233,11 +23704,11 @@ var RunSupervisor = class {
23233
23704
  return refuse(errorMessage(error62));
23234
23705
  }
23235
23706
  }
23707
+ if (!provider) return refuse(cliFailure("cliUnsupported", { label: cli.label }));
23236
23708
  if (!payload.prompt && !payload.attachments?.length) return refuse("\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A");
23237
23709
  let sessionId = payload.session_id;
23238
23710
  let sessionsBefore;
23239
23711
  let sessionNote = "";
23240
- let unverifiedResume = false;
23241
23712
  if (!payload.chat_session_id && provider.listSessions) {
23242
23713
  let saved;
23243
23714
  let listError = "";
@@ -23249,7 +23720,6 @@ var RunSupervisor = class {
23249
23720
  if (!saved) {
23250
23721
  this.logger.warn("list-sessions-failed", { runId: payload.run_id, agentType: provider.id, error: listError });
23251
23722
  if (sessionId) {
23252
- unverifiedResume = true;
23253
23723
  sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF08${listError}\uFF09\uFF0C\u7EE7\u7EED\u4F7F\u7528\u539F\u4F1A\u8BDD
23254
23724
  `;
23255
23725
  } else {
@@ -23266,7 +23736,8 @@ var RunSupervisor = class {
23266
23736
  }
23267
23737
  }
23268
23738
  if ([...this.active.values()].some((run2) => run2.workstationId === payload.workstation_id)) return refuse("\u672C\u673A\u8BE5\u5DE5\u4F4D\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
23269
- if (this.active.size + this.preparing.size > this.config.maxConcurrentRuns) return refuse("\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650");
23739
+ if (this.overConcurrencyCap()) return refuse(`\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650\uFF08${this.config.maxConcurrentRuns}\uFF09`);
23740
+ if (provider.forTurn) provider = provider.forTurn();
23270
23741
  const launch = provider.buildLaunch({
23271
23742
  permissionMode,
23272
23743
  prompt: payload.prompt,
@@ -23275,7 +23746,7 @@ var RunSupervisor = class {
23275
23746
  reasoningEffort: payload.reasoning_effort,
23276
23747
  workdir
23277
23748
  });
23278
- if (!fitsCommandLine(launch)) return refuse(`\u6D88\u606F\u8FC7\u957F\uFF0C\u8D85\u51FA\u672C\u673A\u547D\u4EE4\u884C\u957F\u5EA6\u4E0A\u9650\uFF0C${provider.id} \u6682\u4E0D\u652F\u6301\u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6\u63D0\u793A\u8BCD\uFF0C\u8BF7\u7F29\u77ED\u6D88\u606F\u540E\u91CD\u8BD5`);
23749
+ if (!fitsCommandLine(launch)) return refuse(cliFailure("promptTooLong", { label: cli.label }));
23279
23750
  let child;
23280
23751
  try {
23281
23752
  child = spawn8(launch.executable, launch.args, {
@@ -23287,7 +23758,7 @@ var RunSupervisor = class {
23287
23758
  stdio: [provider.startInput || launch.stdin !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
23288
23759
  });
23289
23760
  } catch (error62) {
23290
- return refuse(`\u65E0\u6CD5\u542F\u52A8 ${provider.id}\uFF1A${errorMessage(error62)}`);
23761
+ return refuse(classifySpawnError(errorMessage(error62), cli));
23291
23762
  }
23292
23763
  const run = {
23293
23764
  chat: Boolean(payload.chat_session_id),
@@ -23301,10 +23772,11 @@ var RunSupervisor = class {
23301
23772
  runId: payload.run_id,
23302
23773
  workstationId: payload.workstation_id,
23303
23774
  agentType: provider.id,
23775
+ cli: { label: cli.label, ...cli.installHint ? { installHint: cli.installHint } : {} },
23304
23776
  provider,
23305
23777
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
23306
23778
  ...sessionsBefore ? { sessionsBefore } : {},
23307
- ...unverifiedResume ? { unverifiedResume: payload } : {},
23779
+ ...sessionId && !payload.chat_session_id ? { resumeRetry: payload } : {},
23308
23780
  prompt: payload.prompt,
23309
23781
  child,
23310
23782
  pid: child.pid ?? 0,
@@ -23335,6 +23807,12 @@ var RunSupervisor = class {
23335
23807
  }
23336
23808
  });
23337
23809
  }
23810
+ const recorder = RunRecorder.fromEnvironment(run.runId, {
23811
+ agent: provider.id,
23812
+ args: launch.args,
23813
+ request: { session_id: sessionId, model: payload.model, reasoning_effort: payload.reasoning_effort, permission: permissionMode, prompt: payload.prompt }
23814
+ });
23815
+ if (recorder) run.recorder = recorder;
23338
23816
  this.active.set(run.runId, run);
23339
23817
  this.preparing.delete(run.runId);
23340
23818
  this.unreported.add(run.runId);
@@ -23347,17 +23825,24 @@ var RunSupervisor = class {
23347
23825
  this.logger.info("run-started", { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
23348
23826
  let spawnError = "";
23349
23827
  child.stdin?.on("error", () => void 0);
23350
- if (launch.stdin !== void 0 && !provider.startInput) child.stdin?.end(launch.stdin, "utf8");
23828
+ if (launch.stdin !== void 0 && !provider.startInput) {
23829
+ run.recorder?.write({ stream: "stdin", data: launch.stdin });
23830
+ child.stdin?.end(launch.stdin, "utf8");
23831
+ }
23351
23832
  child.once("error", (error62) => {
23352
23833
  spawnError = error62.message;
23353
23834
  });
23354
23835
  if (run.stream) {
23355
23836
  child.stdout.setEncoding("utf8");
23356
- child.stdout.on("data", (chunk) => this.applyParsed(run, run.stream.stdout(chunk), chunk));
23837
+ child.stdout.on("data", (chunk) => {
23838
+ run.recorder?.write({ stream: "stdout", data: chunk });
23839
+ this.applyParsed(run, run.stream.stdout(chunk), chunk);
23840
+ });
23357
23841
  } else {
23358
23842
  createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
23359
23843
  }
23360
23844
  createInterface3({ input: child.stderr }).on("line", (line) => {
23845
+ run.recorder?.write({ stream: "stderr", data: line });
23361
23846
  const clean = sanitizeTerminalLine(line);
23362
23847
  if (!clean.trim()) return;
23363
23848
  run.stderr.push(clean);
@@ -23395,27 +23880,31 @@ var RunSupervisor = class {
23395
23880
  child.once("spawn", () => {
23396
23881
  try {
23397
23882
  provider.startInput?.((message) => {
23883
+ run.recorder?.write({ stream: "stdin", data: message });
23398
23884
  child.stdin?.write(message);
23399
23885
  });
23400
23886
  } catch (error62) {
23401
23887
  run.turnError = errorMessage(error62);
23888
+ run.turnFailure = "startFailed";
23402
23889
  void killProcessTree(run.pid);
23403
23890
  }
23404
23891
  });
23405
23892
  run.timers.push(setTimeout(() => {
23406
23893
  if (!run.chatReady && this.active.has(run.runId)) {
23407
- run.turnError = "CLI \u5B9E\u65F6\u4F1A\u8BDD\u521D\u59CB\u5316\u8D85\u65F6";
23894
+ run.turnError = `${run.cli.label} \u4F1A\u8BDD\u521D\u59CB\u5316\u8D85\u65F6`;
23895
+ run.turnFailure = "startFailed";
23408
23896
  void killProcessTree(run.pid);
23409
23897
  }
23410
- }, 6e4));
23898
+ }, SESSION_START_TIMEOUT_MS));
23411
23899
  }
23412
- const maxMs = this.config.maxRunSeconds * 1e3;
23413
- run.timers.push(setTimeout(() => {
23414
- run.timedOut = true;
23415
- run.tail.append(`\u2717 \u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${this.config.maxRunSeconds} \u79D2\uFF0C\u5DF2\u7EC8\u6B62
23900
+ if (this.config.maxRunSeconds > 0) {
23901
+ run.timers.push(setTimeout(() => {
23902
+ run.timedOut = true;
23903
+ run.tail.append(`\u2717 \u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${this.config.maxRunSeconds} \u79D2\uFF0C\u5DF2\u7EC8\u6B62
23416
23904
  `);
23417
- void killProcessTree(run.pid);
23418
- }, maxMs));
23905
+ void killProcessTree(run.pid);
23906
+ }, this.config.maxRunSeconds * 1e3));
23907
+ }
23419
23908
  if (run.stallPolicy) {
23420
23909
  const watchdog = setInterval(() => this.checkStall(run), STALL_CHECK_INTERVAL_MS);
23421
23910
  watchdog.unref?.();
@@ -23426,13 +23915,15 @@ var RunSupervisor = class {
23426
23915
  });
23427
23916
  }
23428
23917
  onStdout(run, rawLine) {
23918
+ run.recorder?.write({ stream: "stdout", data: `${rawLine}
23919
+ ` });
23429
23920
  this.applyParsed(run, run.parse(rawLine), rawLine);
23430
23921
  }
23431
23922
  applyParsed(run, parsed, rawLine) {
23432
23923
  if (run.chat && !run.forwardingFailed) {
23433
23924
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run, sanitizeChatEvent(event));
23434
- if (parsed.sessionId) run.chatReady = true;
23435
23925
  }
23926
+ if (parsed.sessionId) run.chatReady = true;
23436
23927
  for (const row of parsed.display) {
23437
23928
  const shown = sanitizeTerminalLine(row);
23438
23929
  run.tail.append(`${shown}
@@ -23441,7 +23932,10 @@ var RunSupervisor = class {
23441
23932
  }
23442
23933
  if (!parsed.display.length && rawLine.trim()) run.lastOutputAt = Date.now();
23443
23934
  if (parsed.message !== void 0) run.finalMessage = sanitizeTerminalLine(parsed.message);
23444
- if (parsed.turnError) run.turnError = sanitizeTerminalLine(parsed.turnError);
23935
+ if (parsed.turnError) {
23936
+ run.turnError = sanitizeTerminalLine(parsed.turnError);
23937
+ if (parsed.failureKind) run.turnFailure = parsed.failureKind;
23938
+ }
23445
23939
  if (parsed.sessionId && parsed.sessionId !== run.sessionId) {
23446
23940
  run.sessionId = parsed.sessionId;
23447
23941
  void this.reporter.started(run.runId, { session_id: parsed.sessionId }).catch(() => void 0);
@@ -23467,30 +23961,30 @@ var RunSupervisor = class {
23467
23961
  async onExit(run, code, signal2, spawnError) {
23468
23962
  for (const timer of run.timers) clearTimeout(timer);
23469
23963
  run.timers = [];
23964
+ run.recorder?.write({ exit: code });
23470
23965
  if (run.stream) this.applyParsed(run, await run.stream.end(), "");
23471
23966
  this.active.delete(run.runId);
23472
23967
  this.orphans?.remove(run.runId);
23473
23968
  if (run.eventTimer) clearTimeout(run.eventTimer);
23474
23969
  this.flushChatEvents(run);
23475
23970
  await run.eventTail;
23476
- const retry = run.unverifiedResume;
23477
- if (retry && code !== 0 && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && run.provider.isMissingSession?.(run.stderr)) {
23971
+ const retry = run.resumeRetry;
23972
+ const missing = retry && (code !== 0 || run.turnError) && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && classifyCliOutput([...run.stderr, run.turnError], run.provider.failureRules, run.cli)?.kind === "sessionMissing";
23973
+ if (retry && missing) {
23478
23974
  this.logger.warn("resume-session-missing", { runId: run.runId, agentType: run.agentType, sessionId: run.sessionId });
23479
23975
  const { task_attachments: _prepared, ...rest } = retry;
23480
- const missing = `\u539F\u4F1A\u8BDD ${run.sessionId} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`;
23481
- const notice = retry.notice ? `${retry.notice}\uFF1B${missing}` : missing;
23976
+ const gone = `\u539F\u4F1A\u8BDD ${retry.session_id} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`;
23977
+ const notice = retry.notice ? `${retry.notice}\uFF1B${gone}` : gone;
23482
23978
  await this.start({ ...rest, session_id: "", notice });
23483
23979
  return;
23484
23980
  }
23485
- if (!run.chat && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && run.provider.inspectExit) {
23486
- try {
23487
- const inspection = await run.provider.inspectExit({ exitCode: code, stderr: run.stderr, workdir: run.workdir, sessionId: run.sessionId });
23488
- if (inspection.turnError && !run.turnError) run.turnError = sanitizeTerminalLine(inspection.turnError);
23489
- for (const row of inspection.display ?? []) run.tail.append(`${sanitizeTerminalLine(row)}
23981
+ if (!run.chat && !run.turnError && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled) {
23982
+ const hidden = classifyCliOutput(run.stderr, run.provider.failureRules, run.cli, { successfulExit: true });
23983
+ if (hidden) {
23984
+ run.turnError = sanitizeTerminalLine(hidden.message);
23985
+ run.turnFailure = hidden.kind;
23986
+ if (hidden.rule.showInLog) run.tail.append(`\u2717 ${run.turnError}
23490
23987
  `);
23491
- if (inspection.sessionId && inspection.sessionId !== run.sessionId) run.sessionId = inspection.sessionId;
23492
- } catch (error62) {
23493
- this.logger.warn("inspect-exit-failed", { runId: run.runId, error: errorMessage(error62) });
23494
23988
  }
23495
23989
  }
23496
23990
  if (run.sessionsBefore && !run.sessionId && !spawnError && run.provider.listSessions) {
@@ -23514,35 +24008,50 @@ var RunSupervisor = class {
23514
24008
  if (run.cancelRequested) {
23515
24009
  report = { status: "cancelled", duration_ms: durationMs };
23516
24010
  } else if (spawnError) {
23517
- report = { status: "failed", error: `\u65E0\u6CD5\u542F\u52A8 ${run.agentType}\uFF1A${spawnError}`, duration_ms: durationMs };
24011
+ report = failedReport(classifySpawnError(spawnError, run.cli), durationMs);
23518
24012
  } else if (run.stalled) {
23519
24013
  const stall = run.stalled;
23520
24014
  report = {
23521
24015
  status: "failed",
23522
24016
  failure_reason: "stalled",
24017
+ failure_kind: "stalled",
23523
24018
  stall,
23524
24019
  duration_ms: durationMs,
23525
24020
  error: `CLI \u5DF2 ${formatDuration(stall.idle_seconds)}\u6CA1\u6709\u65B0\u8F93\u51FA\uFF08\u5361\u5728\uFF1A${STALL_CATEGORY_LABELS[stall.category]}${stall.last_line ? `\uFF08${stall.last_line}\uFF09` : ""}\uFF09\uFF0C\u5DF2\u81EA\u52A8\u505C\u6B62`
23526
24021
  };
23527
24022
  } else if (run.timedOut) {
23528
- report = { status: "failed", error: `\u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${this.config.maxRunSeconds} \u79D2`, duration_ms: durationMs };
24023
+ report = failedReport(cliFailure("timedOut", { label: run.cli.label, seconds: this.config.maxRunSeconds }), durationMs);
23529
24024
  } else if (run.turnError) {
23530
- report = { status: "failed", error: run.turnError, duration_ms: durationMs };
24025
+ report = failedReport(this.turnFailure(run), durationMs);
23531
24026
  } else if (code === 0 || run.killedAfterCompletion) {
23532
24027
  report = { status: "succeeded", duration_ms: durationMs };
23533
24028
  } else {
23534
- const detail = run.stderr.slice(-8).join("\n").trim();
23535
- report = { status: "failed", error: detail || `${run.agentType} \u5F02\u5E38\u9000\u51FA${signal2 ? `\uFF08${signal2}\uFF09` : ""}`, duration_ms: durationMs };
24029
+ report = failedReport(this.exitFailure(run, signal2), durationMs);
23536
24030
  }
23537
24031
  if (code !== null) report.exit_code = code;
23538
24032
  if (run.sessionId) report.session_id = run.sessionId;
23539
24033
  if (run.finalMessage) report.final_message = run.finalMessage;
23540
24034
  run.tail.append(`\u25CF \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF1A${report.status}${code !== null ? `\uFF08exit ${code}\uFF09` : ""}
23541
24035
  `);
24036
+ run.recorder?.write({ result: { ...report, duration_ms: 0 }, log: run.tail.read({ limit: 2e3 }).lines });
23542
24037
  this.remember({ runId: run.runId, workstationId: run.workstationId, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
23543
24038
  this.logger.info("run-finished", { runId: run.runId, status: report.status, code, durationMs });
23544
24039
  await this.report(run.runId, report);
23545
24040
  }
24041
+ /** The CLI declared the turn failed: name the kind, keep its own words. */
24042
+ turnFailure(run) {
24043
+ if (run.turnFailure) return { kind: run.turnFailure, message: run.turnError };
24044
+ const known = classifyCliOutput(run.turnError, run.provider.failureRules, run.cli);
24045
+ if (!known) return { kind: "turnFailed", message: run.turnError };
24046
+ return known.rule.message ? known : cliFailure(known.kind, { ...run.cli, detail: run.turnError });
24047
+ }
24048
+ /** Non-zero exit with no declared error: classify stderr, else show its tail. */
24049
+ exitFailure(run, signal2) {
24050
+ const known = classifyCliOutput(run.stderr, run.provider.failureRules, run.cli);
24051
+ if (known) return known;
24052
+ const detail = run.stderr.slice(-8).join("\n").trim();
24053
+ return cliFailure("exited", { label: run.cli.label, detail: detail || (signal2 ? `\uFF08${signal2}\uFF09` : "") });
24054
+ }
23546
24055
  noteOutput(run, row) {
23547
24056
  run.lastOutputAt = Date.now();
23548
24057
  run.lastCategory = rowCategory(row);
@@ -23567,6 +24076,7 @@ var RunSupervisor = class {
23567
24076
  if (run.queuedBytes + bytes > 8 * 1024 * 1024) {
23568
24077
  run.forwardingFailed = true;
23569
24078
  run.turnError = "\u5B9E\u65F6\u8F93\u51FA\u8F6C\u53D1\u79EF\u538B\uFF0C\u8BF7\u68C0\u67E5\u8BBE\u5907\u7F51\u7EDC";
24079
+ run.turnFailure = "hostFault";
23570
24080
  void killProcessTree(run.pid);
23571
24081
  return;
23572
24082
  }
@@ -23594,6 +24104,7 @@ var RunSupervisor = class {
23594
24104
  }).catch((error62) => {
23595
24105
  run.forwardingFailed = true;
23596
24106
  run.turnError = `\u5B9E\u65F6\u8F93\u51FA\u8F6C\u53D1\u5931\u8D25\uFF1A${errorMessage(error62)}`;
24107
+ run.turnFailure = "hostFault";
23597
24108
  this.logger.warn("chat-events-failed", { runId: run.runId, error: errorMessage(error62) });
23598
24109
  if (this.active.has(run.runId)) void killProcessTree(run.pid);
23599
24110
  }).finally(() => {
@@ -23603,12 +24114,12 @@ var RunSupervisor = class {
23603
24114
  async prepareChatAttachments(payload) {
23604
24115
  if (!payload.attachments?.length) return [];
23605
24116
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
23606
- const directory = join12(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
24117
+ const directory = join13(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23607
24118
  await mkdir5(directory, { recursive: true, mode: 448 });
23608
24119
  const files = [];
23609
24120
  for (const attachment of payload.attachments) {
23610
24121
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
23611
- const path = join12(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
24122
+ const path = join13(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23612
24123
  const existing = await stat3(path).catch(() => void 0);
23613
24124
  if (!existing?.isFile()) {
23614
24125
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
@@ -23703,6 +24214,9 @@ var RunSupervisor = class {
23703
24214
  return prepareTaskAttachments(payload, workdir ?? await this.validateWorkdir(payload.workdir), this.reporter.taskFile, AbortSignal.any([signal2, AbortSignal.timeout(15 * 6e4)]));
23704
24215
  }
23705
24216
  };
24217
+ function failedReport(failure2, durationMs) {
24218
+ return { status: "failed", error: failure2.message, failure_kind: failure2.kind, duration_ms: durationMs };
24219
+ }
23706
24220
  function errorMessage(error62) {
23707
24221
  return error62 instanceof Error ? error62.message : String(error62);
23708
24222
  }
@@ -23846,11 +24360,11 @@ var GatewayClient = class {
23846
24360
 
23847
24361
  // src/workspace/directory-browser.ts
23848
24362
  import { readdir as readdir2, realpath as realpath3, stat as stat4 } from "node:fs/promises";
23849
- import { homedir as homedir8 } from "node:os";
24363
+ import { homedir as homedir9 } from "node:os";
23850
24364
  import { dirname as dirname6, parse as parse3, resolve as resolve4 } from "node:path";
23851
24365
  var MAX_ENTRIES = 1e3;
23852
24366
  async function listDirectory(requested, allowedRoots) {
23853
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir8()) || homedir8();
24367
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir9()) || homedir9();
23854
24368
  const directory = await realpath3(resolve4(raw)).catch(() => {
23855
24369
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
23856
24370
  });
@@ -23868,8 +24382,8 @@ async function listDirectory(requested, allowedRoots) {
23868
24382
  else if (entry.isFile()) files.push(item);
23869
24383
  }
23870
24384
  const parent = dirname6(directory);
23871
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir8() }];
23872
- for (const root of allowedRoots) if (root !== homedir8()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
24385
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir9() }];
24386
+ for (const root of allowedRoots) if (root !== homedir9()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23873
24387
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
23874
24388
  return {
23875
24389
  path: directory,
@@ -23884,8 +24398,8 @@ async function listDirectory(requested, allowedRoots) {
23884
24398
  // src/workspace/workspace-manager.ts
23885
24399
  import { spawn as spawn9 } from "node:child_process";
23886
24400
  import { chmod as chmod3, mkdir as mkdir6, mkdtemp, opendir, realpath as realpath4, rm as rm3, stat as stat5, writeFile as writeFile6 } from "node:fs/promises";
23887
- import { homedir as homedir9, tmpdir as tmpdir2 } from "node:os";
23888
- import { isAbsolute as isAbsolute4, join as join13, relative as relative3, resolve as resolve5 } from "node:path";
24401
+ import { homedir as homedir10, tmpdir as tmpdir2 } from "node:os";
24402
+ import { isAbsolute as isAbsolute4, join as join14, relative as relative3, resolve as resolve5 } from "node:path";
23889
24403
  var MAX_NODES = 2e3;
23890
24404
  var MAX_DIRECTORY_ENTRIES = 12e3;
23891
24405
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -23933,7 +24447,7 @@ var WorkspaceManager = class {
23933
24447
  };
23934
24448
  }
23935
24449
  validateRootPath(value) {
23936
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir9());
24450
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir10());
23937
24451
  const root = resolve5(raw);
23938
24452
  if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
23939
24453
  if (relative3(root, resolve5(root, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -24260,12 +24774,12 @@ var WorkspaceManager = class {
24260
24774
  }
24261
24775
  async createGitAuthEnvironment(auth) {
24262
24776
  if (!auth) return void 0;
24263
- const directory = await mkdtemp(join13(tmpdir2(), "toc-ocra-git-auth-"));
24777
+ const directory = await mkdtemp(join14(tmpdir2(), "toc-ocra-git-auth-"));
24264
24778
  const isWindows = process.platform === "win32";
24265
- const scriptPath = join13(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24779
+ const scriptPath = join14(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24266
24780
  let script;
24267
24781
  if (isWindows) {
24268
- const helperPath = join13(directory, "askpass.cjs");
24782
+ const helperPath = join14(directory, "askpass.cjs");
24269
24783
  await writeFile6(
24270
24784
  helperPath,
24271
24785
  'const prompt = process.argv.slice(2).join(" ");\nprocess.stdout.write(/username/i.test(prompt) ? process.env.ECHO_GIT_USERNAME ?? "" : process.env.ECHO_GIT_PASSWORD ?? "");\n',
@@ -24415,7 +24929,7 @@ var AgentRuntime = class {
24415
24929
  }
24416
24930
  };
24417
24931
  this.workspaces = new WorkspaceManager(config2, this.logger);
24418
- this.orphans = new OrphanRegistry(join14(config2.dataDir, "active-runs.json"));
24932
+ this.orphans = new OrphanRegistry(join15(config2.dataDir, "active-runs.json"));
24419
24933
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
24420
24934
  }
24421
24935
  config;
@@ -25133,7 +25647,7 @@ function preferSystemNode() {
25133
25647
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
25134
25648
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
25135
25649
  for (const name of names) {
25136
- const candidate = directory && join15(directory, name);
25650
+ const candidate = directory && join16(directory, name);
25137
25651
  if (candidate && existsSync6(candidate)) {
25138
25652
  process.env.TOC_OCRA_NODE_PATH = candidate;
25139
25653
  return;