toc-ocra 0.2.38 → 0.3.1

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 (93) 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 +3586 -2565
  5. package/dist/plugin/renderer.css.map +1 -1
  6. package/dist/plugin/renderer.js.map +1 -1
  7. package/dist/service/agent.mjs +1901 -1001
  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 +43 -1
  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.d.ts +1 -1
  21. package/dist/src/providers/chat/codex-app-server.js +4 -3
  22. package/dist/src/providers/chat/codex-app-server.js.map +1 -1
  23. package/dist/src/providers/chat/codex-goal.d.ts +17 -0
  24. package/dist/src/providers/chat/codex-goal.js +188 -0
  25. package/dist/src/providers/chat/codex-goal.js.map +1 -0
  26. package/dist/src/providers/chat/index.d.ts +4 -2
  27. package/dist/src/providers/chat/index.js +7 -8
  28. package/dist/src/providers/chat/index.js.map +1 -1
  29. package/dist/src/providers/cli/claude.d.ts +6 -0
  30. package/dist/src/providers/cli/claude.js +107 -5
  31. package/dist/src/providers/cli/claude.js.map +1 -1
  32. package/dist/src/providers/cli/codex-fork.d.ts +11 -0
  33. package/dist/src/providers/cli/codex-fork.js +84 -0
  34. package/dist/src/providers/cli/codex-fork.js.map +1 -0
  35. package/dist/src/providers/cli/codex.js +5 -1
  36. package/dist/src/providers/cli/codex.js.map +1 -1
  37. package/dist/src/providers/cli/gemini.js +3 -1
  38. package/dist/src/providers/cli/gemini.js.map +1 -1
  39. package/dist/src/providers/cli/grok.js +3 -1
  40. package/dist/src/providers/cli/grok.js.map +1 -1
  41. package/dist/src/providers/cli/kiro.d.ts +10 -4
  42. package/dist/src/providers/cli/kiro.js +38 -38
  43. package/dist/src/providers/cli/kiro.js.map +1 -1
  44. package/dist/src/providers/cli/opencode.js +3 -1
  45. package/dist/src/providers/cli/opencode.js.map +1 -1
  46. package/dist/src/providers/cli-failure.d.ts +66 -0
  47. package/dist/src/providers/cli-failure.js +128 -0
  48. package/dist/src/providers/cli-failure.js.map +1 -0
  49. package/dist/src/providers/cli-specs.d.ts +58 -0
  50. package/dist/src/providers/cli-specs.js +37 -0
  51. package/dist/src/providers/cli-specs.js.map +1 -0
  52. package/dist/src/providers/codex-quota.js +3 -2
  53. package/dist/src/providers/codex-quota.js.map +1 -1
  54. package/dist/src/providers/kiro-quota.js +3 -2
  55. package/dist/src/providers/kiro-quota.js.map +1 -1
  56. package/dist/src/providers/model-catalog-collector.d.ts +1 -1
  57. package/dist/src/providers/model-catalog-collector.js +3 -3
  58. package/dist/src/providers/model-catalog-collector.js.map +1 -1
  59. package/dist/src/providers/model-catalog.d.ts +0 -2
  60. package/dist/src/providers/model-catalog.js +12 -13
  61. package/dist/src/providers/model-catalog.js.map +1 -1
  62. package/dist/src/providers/provider.d.ts +38 -46
  63. package/dist/src/providers/provider.js +6 -4
  64. package/dist/src/providers/provider.js.map +1 -1
  65. package/dist/src/providers/quota-reader.d.ts +1 -1
  66. package/dist/src/providers/quota-reader.js +5 -10
  67. package/dist/src/providers/quota-reader.js.map +1 -1
  68. package/dist/src/providers/registry.d.ts +46 -9
  69. package/dist/src/providers/registry.js +73 -21
  70. package/dist/src/providers/registry.js.map +1 -1
  71. package/dist/src/runs/run-recorder.d.ts +32 -0
  72. package/dist/src/runs/run-recorder.js +27 -0
  73. package/dist/src/runs/run-recorder.js.map +1 -0
  74. package/dist/src/runs/run-supervisor.d.ts +23 -5
  75. package/dist/src/runs/run-supervisor.js +205 -81
  76. package/dist/src/runs/run-supervisor.js.map +1 -1
  77. package/dist/src/runtime/agent-runtime.js +10 -10
  78. package/dist/src/runtime/agent-runtime.js.map +1 -1
  79. package/dist/src/smoke/cli-smoke.d.ts +30 -0
  80. package/dist/src/smoke/cli-smoke.js +92 -0
  81. package/dist/src/smoke/cli-smoke.js.map +1 -0
  82. package/dist/src/transport/gateway-client.d.ts +3 -1
  83. package/dist/src/transport/gateway-client.js +6 -0
  84. package/dist/src/transport/gateway-client.js.map +1 -1
  85. package/dist/src/types/protocol.d.ts +35 -4
  86. package/dist/src/types/protocol.js +14 -3
  87. package/dist/src/types/protocol.js.map +1 -1
  88. package/locales/en.json +202 -202
  89. package/locales/zh-CN.json +202 -202
  90. package/package.json +102 -102
  91. package/scripts/installation.cjs +260 -260
  92. package/scripts/postinstall.cjs +22 -22
  93. 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,221 @@ 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 { readdirSync as readdirSync2, 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");
21090
+ function claudeProjectRoots() {
21091
+ const configured = process.env.CLAUDE_CONFIG_DIR;
21092
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join7(homedir4(), ".claude")];
21093
+ return dirs.map((dir) => join7(dir, "projects"));
21094
+ }
21095
+ function claudeTranscriptExists(sessionId) {
21096
+ return claudeTranscriptPath(sessionId) !== void 0;
21097
+ }
21098
+ function claudeTranscriptPath(sessionId) {
21099
+ const file2 = `${sessionId}.jsonl`;
21100
+ for (const root of claudeProjectRoots()) {
21101
+ let projects;
21102
+ try {
21103
+ projects = readdirSync2(root);
21104
+ } catch {
21105
+ continue;
21106
+ }
21107
+ for (const project of projects) {
21108
+ try {
21109
+ if (readdirSync2(join7(root, project)).includes(file2)) return join7(root, project, file2);
21110
+ } catch {
21111
+ }
21112
+ }
21113
+ }
21114
+ return void 0;
21115
+ }
21116
+ function isPromptEntry(entry) {
21117
+ if (entry.type !== "user" || entry.isSidechain === true || entry.isMeta === true) return false;
21118
+ const content = record2(entry.message).content;
21119
+ if (typeof content === "string") return content.trim().length > 0;
21120
+ return Array.isArray(content) && content.some((part) => record2(part).type === "text");
21121
+ }
21122
+ function claudeForkBoundary(transcript, keepTurns) {
21123
+ if (keepTurns <= 0) return void 0;
21124
+ let prompts = 0;
21125
+ let boundary;
21126
+ for (const line of transcript.split(/\r?\n/)) {
21127
+ const entry = tryJson(line);
21128
+ if (!entry) continue;
21129
+ if (isPromptEntry(entry)) {
21130
+ prompts++;
21131
+ if (prompts > keepTurns) return boundary;
21132
+ continue;
21133
+ }
21134
+ if (entry.type === "assistant" && entry.isSidechain !== true && typeof entry.uuid === "string") boundary = entry.uuid;
21135
+ }
21136
+ return void 0;
21137
+ }
20894
21138
  var claudeProvider = {
20895
21139
  id: "claude",
20896
21140
  buildLaunch(request) {
@@ -20909,13 +21153,29 @@ var claudeProvider = {
20909
21153
  }
20910
21154
  if (request.model) args.push("--model", request.model);
20911
21155
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20912
- 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" });
21156
+ if (request.sessionId && request.fork && !claudeTranscriptExists(request.sessionId)) {
21157
+ args.push("--resume", request.fork.sourceSessionId, "--fork-session");
21158
+ const source = claudeTranscriptPath(request.fork.sourceSessionId);
21159
+ if (source && request.fork.keepTurns > 0) {
21160
+ let text = "";
21161
+ try {
21162
+ text = readFileSync5(source, "utf8");
21163
+ } catch {
21164
+ }
21165
+ const at = claudeForkBoundary(text, request.fork.keepTurns);
21166
+ if (at) args.push("--resume-session-at", at);
21167
+ }
21168
+ } else if (request.sessionId) {
21169
+ args.push(claudeTranscriptExists(request.sessionId) ? "--resume" : "--session-id", request.sessionId);
21170
+ }
21171
+ return launchCli({ spec: CLAUDE, args, env, prompt: request.prompt });
20914
21172
  },
20915
21173
  parseLine(line) {
20916
21174
  return claudeLineParser()(line);
20917
21175
  },
20918
- createLineParser: () => claudeLineParser()
21176
+ createLineParser: () => claudeLineParser(),
21177
+ // `--resume <id>` for a chat this computer no longer has.
21178
+ failureRules: [{ kind: "sessionMissing", pattern: /No conversation found with session ID/i }]
20919
21179
  };
20920
21180
  var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
20921
21181
  function toolResultText(content) {
@@ -21000,109 +21260,216 @@ function claudeLineParser() {
21000
21260
  };
21001
21261
  }
21002
21262
 
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
- }
21263
+ // src/providers/chat/claude-stream-json.ts
21264
+ var TOOL_KINDS = {
21265
+ bash: "execute",
21266
+ read: "read",
21267
+ notebookread: "read",
21268
+ glob: "search",
21269
+ grep: "search",
21270
+ ls: "read",
21271
+ edit: "edit",
21272
+ multiedit: "edit",
21273
+ write: "write",
21274
+ notebookedit: "edit",
21275
+ webfetch: "fetch",
21276
+ websearch: "fetch",
21277
+ todowrite: "other",
21278
+ task: "other"
21061
21279
  };
21280
+ function toolKind(name) {
21281
+ const key = name.toLowerCase();
21282
+ if (key.startsWith("mcp__")) return "mcp";
21283
+ return TOOL_KINDS[key] ?? "other";
21284
+ }
21285
+ function toolPath(input2, partial2) {
21286
+ const parsed = input2 && typeof input2 === "object" && Object.keys(input2).length ? input2 : tryJson(partial2) ?? {};
21287
+ return str(parsed.file_path) ?? str(parsed.notebook_path) ?? str(parsed.path);
21288
+ }
21289
+ var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21290
+ var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record3(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21291
+ function claudeChatProvider(attachments) {
21292
+ let messageID = "";
21293
+ let messageSequence = 0;
21294
+ let hasText = false;
21295
+ const blocks = /* @__PURE__ */ new Map();
21296
+ const tools = /* @__PURE__ */ new Map();
21297
+ const asItem = (block, status, output2) => ({ event: "item", item: {
21298
+ itemId: block.id,
21299
+ type: block.type,
21300
+ status,
21301
+ ...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 }
21302
+ } });
21303
+ return {
21304
+ id: "claude",
21305
+ buildLaunch(request) {
21306
+ const files = attachments.map((file2) => `\u9644\u4EF6\u6587\u4EF6\uFF1A${file2.name}
21307
+ \u672C\u673A\u8DEF\u5F84\uFF1A${file2.path}`).join("\n\n");
21308
+ const launch = claudeProvider.buildLaunch({ ...request, prompt: [request.prompt, files].filter(Boolean).join("\n\n") });
21309
+ launch.args.push("--include-partial-messages");
21310
+ return launch;
21311
+ },
21312
+ parseLine(line) {
21313
+ const envelope = tryJson(line);
21314
+ if (!envelope) return { display: line.trim() ? [line] : [] };
21315
+ const sessionId = str(envelope.session_id);
21316
+ const base = sessionId ? { sessionId } : {};
21317
+ const events = [];
21318
+ if (envelope.parent_tool_use_id) return { ...base, display: [] };
21319
+ if (envelope.type === "stream_event") {
21320
+ const event = record3(envelope.event);
21321
+ const index = Number(event.index ?? 0);
21322
+ if (event.type === "message_start") {
21323
+ messageID = str(record3(event.message).id) ?? `message:${++messageSequence}`;
21324
+ blocks.clear();
21325
+ } else if (event.type === "content_block_start") {
21326
+ if (!messageID) messageID = `message:${++messageSequence}`;
21327
+ const part = record3(event.content_block);
21328
+ const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21329
+ if (!["tool_use", "thinking", "text"].includes(String(part.type))) return { ...base, display: [] };
21330
+ 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: "" };
21331
+ blocks.set(index, block);
21332
+ if (type === "tool_call") tools.set(block.id, block);
21333
+ events.push(asItem(block, "in_progress"));
21334
+ } else if (event.type === "content_block_delta") {
21335
+ const block = blocks.get(index);
21336
+ const delta = record3(event.delta);
21337
+ if (!block) return { ...base, display: [] };
21338
+ if (delta.type === "text_delta" || delta.type === "thinking_delta") {
21339
+ const text = String(delta.text ?? delta.thinking ?? "");
21340
+ block.text += text;
21341
+ if (delta.type === "text_delta") hasText ||= !!text;
21342
+ events.push({ event: delta.type === "text_delta" ? "text_delta" : "thought_delta", item_id: block.id, text });
21343
+ } else if (delta.type === "input_json_delta") {
21344
+ block.partialInput += String(delta.partial_json ?? "");
21345
+ if (block.partialInput.length > 64e3) block.partialInput = block.partialInput.slice(0, 64e3);
21346
+ events.push(asItem(block, "in_progress"));
21347
+ }
21348
+ } else if (event.type === "content_block_stop") {
21349
+ const block = blocks.get(index);
21350
+ if (block && block.type !== "tool_call") events.push(asItem(block, "completed"));
21351
+ }
21352
+ } else if (envelope.type === "assistant") {
21353
+ const message = record3(envelope.message);
21354
+ const id = str(message.id) || messageID || `message:${++messageSequence}`;
21355
+ const parts = Array.isArray(message.content) ? message.content : [];
21356
+ parts.forEach((value, index) => {
21357
+ const part = record3(value);
21358
+ if (!["text", "thinking", "tool_use"].includes(String(part.type))) return;
21359
+ const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21360
+ 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: "" };
21361
+ if (type === "tool_call") tools.set(block.id, block);
21362
+ if (type === "text") hasText ||= !!block.text;
21363
+ events.push(asItem(block, type === "tool_call" ? "in_progress" : "completed"));
21364
+ });
21365
+ } else if (envelope.type === "user") {
21366
+ const message = record3(envelope.message);
21367
+ for (const value of Array.isArray(message.content) ? message.content : []) {
21368
+ const part = record3(value);
21369
+ if (part.type !== "tool_result") continue;
21370
+ const id = str(part.tool_use_id);
21371
+ if (!id) continue;
21372
+ const block = tools.get(id) ?? { id, type: "tool_call", name: "tool", text: "", input: {}, partialInput: "" };
21373
+ events.push(asItem(block, part.is_error === true ? "failed" : "completed", textContent(part.content)));
21374
+ }
21375
+ } else if (envelope.type === "result") {
21376
+ const text = str(envelope.result) ?? "";
21377
+ if (envelope.is_error === true) {
21378
+ const errors = Array.isArray(envelope.errors) ? envelope.errors.map(String).join("\n") : "";
21379
+ return { ...base, display: [], turnError: text || errors || "Claude \u672C\u8F6E\u6267\u884C\u5931\u8D25", endProcess: true };
21380
+ }
21381
+ if (!hasText && text) events.push({ event: "item", item: { itemId: "answer", type: "text", text, status: "completed" } });
21382
+ return { ...base, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"], message: text, turnCompleted: true, chatEvents: events, endProcess: true };
21383
+ }
21384
+ return { ...base, display: [], chatEvents: events };
21385
+ }
21386
+ };
21387
+ }
21062
21388
 
21063
- // src/providers/cli/gemini.ts
21064
- var geminiProvider = {
21065
- id: "gemini",
21389
+ // src/providers/cli/codex.ts
21390
+ var CODEX = requireCliSpec("codex");
21391
+ var codexProvider = {
21392
+ id: "codex",
21393
+ // `exec resume <id>` for a thread this computer does not have.
21394
+ failureRules: [{ kind: "sessionMissing", pattern: /no rollout found for thread id|thread not found/i }],
21066
21395
  buildLaunch(request) {
21067
- const args = ["-p", request.prompt, "--output-format", "json", "--yolo"];
21396
+ const args = ["exec", "--json", "--skip-git-repo-check"];
21397
+ if (request.permissionMode === "full") args.push("--dangerously-bypass-approvals-and-sandbox");
21398
+ else args.push("--sandbox", "read-only", "-c", 'approval_policy="never"', "-c", "mcp_servers={}", "-c", 'web_search="disabled"');
21068
21399
  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 });
21400
+ if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
21401
+ if (request.sessionId) args.push("resume", request.sessionId);
21402
+ args.push("--", request.prompt);
21403
+ return launchCli({ spec: CODEX, args, prompt: request.prompt });
21071
21404
  },
21072
21405
  parseLine(line) {
21073
21406
  const event = tryJson(line);
21074
21407
  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
- };
21408
+ const type = str(event.type) ?? "";
21409
+ const item = event.item && typeof event.item === "object" ? event.item : {};
21410
+ const itemType = str(item.type) ?? str(item.item_type) ?? "";
21411
+ switch (type) {
21412
+ case "thread.started": {
21413
+ const sessionId = str(event.thread_id);
21414
+ return { ...sessionId ? { sessionId } : {}, display: [`\u25CF \u4F1A\u8BDD ${sessionId ?? ""}`] };
21415
+ }
21416
+ case "turn.started":
21417
+ return { display: ["\u25CF \u5F00\u59CB\u5904\u7406"] };
21418
+ case "turn.completed":
21419
+ return { turnCompleted: true, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"] };
21420
+ case "turn.failed": {
21421
+ const error62 = event.error;
21422
+ const message = str(error62?.message) ?? "\u672C\u8F6E\u5931\u8D25";
21423
+ return { turnError: message, display: [`\u2717 ${message}`] };
21424
+ }
21425
+ case "error": {
21426
+ const message = str(event.message) ?? "error";
21427
+ return { display: [`\u2717 ${message}`] };
21428
+ }
21429
+ case "item.started":
21430
+ if (itemType === "command_execution") return { display: [`$ ${clip(str(item.command) ?? "")}`] };
21431
+ return { display: [] };
21432
+ case "item.completed": {
21433
+ if (itemType === "agent_message") {
21434
+ const text = str(item.text) ?? "";
21435
+ return { message: text, display: textRows("\u203A ", text) };
21436
+ }
21437
+ if (itemType === "reasoning") return { display: textRows("\u2026 ", clip(str(item.text) ?? "", 600), 8) };
21438
+ if (itemType === "command_execution") {
21439
+ const output2 = str(item.aggregated_output);
21440
+ const code = item.exit_code;
21441
+ return { display: [...output2 ? textRows(" ", clip(output2, 2e3), 20) : [], ` (exit ${typeof code === "number" ? code : "?"})`] };
21442
+ }
21443
+ if (itemType === "file_change") return { display: [`\u270E \u4FEE\u6539\u6587\u4EF6`] };
21444
+ return { display: itemType ? [`\xB7 ${itemType}`] : [] };
21445
+ }
21446
+ default:
21447
+ return { display: [] };
21448
+ }
21084
21449
  }
21085
21450
  };
21086
21451
 
21087
- // src/providers/cli/grok.ts
21088
- var grokProvider = {
21089
- id: "grok",
21452
+ // src/providers/cli/gemini.ts
21453
+ var GEMINI = requireCliSpec("gemini");
21454
+ var geminiProvider = {
21455
+ id: "gemini",
21090
21456
  buildLaunch(request) {
21091
- const args = [`--single=${request.prompt}`, "--output-format", "json", "--always-approve", "--no-subagents"];
21457
+ const args = ["-p", request.prompt, "--output-format", "json", "--yolo"];
21092
21458
  if (request.model) args.push("--model", request.model);
21093
- if (request.reasoningEffort) args.push("--reasoning-effort", request.reasoningEffort);
21094
21459
  if (request.sessionId) args.push("--resume", request.sessionId);
21095
- return launchCli({ command: "grok", overrideEnv: "TOC_OCRA_GROK_PATH", args });
21460
+ return launchCli({ spec: GEMINI, args });
21096
21461
  },
21097
21462
  parseLine(line) {
21098
21463
  const event = tryJson(line);
21099
21464
  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);
21465
+ const sessionId = str(event.session_id) ?? str(event.sessionId);
21466
+ const text = str(event.response);
21467
+ const error62 = event.error;
21468
+ if (error62) return { ...sessionId ? { sessionId } : {}, turnError: str(error62.message) ?? "gemini failed", display: [`\u2717 ${clip(JSON.stringify(error62))}`] };
21102
21469
  return {
21103
21470
  ...sessionId ? { sessionId } : {},
21104
21471
  ...text ? { message: text, turnCompleted: true } : {},
21105
- display: text ? textRows("\u203A ", text) : [clip(line, 300)]
21472
+ display: text ? textRows("\u203A ", text) : []
21106
21473
  };
21107
21474
  }
21108
21475
  };
@@ -21111,6 +21478,70 @@ var grokProvider = {
21111
21478
  import { execFile as execFile3 } from "node:child_process";
21112
21479
  import { promisify } from "node:util";
21113
21480
 
21481
+ // src/providers/cli-failure.ts
21482
+ var COPY = {
21483
+ 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`,
21484
+ platformUnsupported: ({ label }) => `${label} \u4E0D\u652F\u6301\u8FD9\u53F0\u7535\u8111\u7684\u64CD\u4F5C\u7CFB\u7EDF`,
21485
+ 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`,
21486
+ cliUnsupported: ({ label }) => `\u4E0D\u652F\u6301\u7684 CLI \u7C7B\u578B\uFF1A${label}`,
21487
+ 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`,
21488
+ 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`,
21489
+ rateLimited: ({ label }) => `${label} \u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u5DF2\u88AB\u9650\u6D41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`,
21490
+ modelUnavailable: ({ label }) => `${label} \u4E0D\u80FD\u4F7F\u7528\u6240\u9009\u6A21\u578B\uFF0C\u8BF7\u5728\u4F1A\u8BDD\u4E2D\u6362\u4E00\u4E2A\u6A21\u578B\u6216\u6539\u4E3A\u9ED8\u8BA4`,
21491
+ sessionMissing: ({ label }) => `${label} \u627E\u4E0D\u5230\u8981\u7EE7\u7EED\u7684\u4F1A\u8BDD`,
21492
+ 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`,
21493
+ 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`,
21494
+ 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`,
21495
+ serviceRejected: ({ label }) => `${label} \u7684\u6A21\u578B\u670D\u52A1\u62D2\u7EDD\u4E86\u672C\u6B21\u8BF7\u6C42`,
21496
+ timedOut: ({ seconds }) => `\u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${seconds ?? "?"} \u79D2`,
21497
+ stalled: ({ label }) => `${label} \u957F\u65F6\u95F4\u6CA1\u6709\u65B0\u8F93\u51FA\uFF0C\u5DF2\u81EA\u52A8\u505C\u6B62`,
21498
+ startFailed: ({ label }) => `\u65E0\u6CD5\u542F\u52A8 ${label}`,
21499
+ turnFailed: ({ label }) => `${label} \u672C\u8F6E\u6267\u884C\u5931\u8D25`,
21500
+ exited: ({ label }) => `${label} \u5F02\u5E38\u9000\u51FA`,
21501
+ hostFault: () => "\u8BBE\u5907\u4EE3\u7406\u5904\u7406\u5931\u8D25"
21502
+ };
21503
+ var MAX_DETAIL = 600;
21504
+ function failureMessage(kind, context) {
21505
+ const lead = COPY[kind](context);
21506
+ const detail = context.detail?.trim();
21507
+ if (!detail || lead.includes(detail)) return lead;
21508
+ return `${lead}\uFF1A${detail.length > MAX_DETAIL ? `${detail.slice(0, MAX_DETAIL)}\u2026` : detail}`;
21509
+ }
21510
+ function cliFailure(kind, context) {
21511
+ return { kind, message: failureMessage(kind, context) };
21512
+ }
21513
+ var COMMON_FAILURE_RULES = [
21514
+ { kind: "usageLimit", pattern: /insufficient_quota|quota (?:exceeded|exhausted)|usage limit|(?:monthly|request) limit reached|credit balance is too low|out of credits/i },
21515
+ { kind: "rateLimited", pattern: /rate[ _-]?limit|too many requests|\b429\b/i },
21516
+ { 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 },
21517
+ { kind: "contextTooLong", pattern: /context (?:length|window)|maximum context|prompt is too long|too many tokens/i },
21518
+ { kind: "modelUnavailable", pattern: /(?:unknown|invalid|unsupported) model|model[^\n]{0,80}(?:not found|not available|unavailable|does not exist|is not supported)/i },
21519
+ { kind: "networkError", pattern: /ECONNREFUSED|ENOTFOUND|ETIMEDOUT|ECONNRESET|EAI_AGAIN|getaddrinfo|fetch failed|network error|socket hang up/i }
21520
+ ];
21521
+ var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
21522
+ function stripAnsi(text) {
21523
+ return text.replace(ANSI, "");
21524
+ }
21525
+ function matchingLine(text, pattern) {
21526
+ return text.split(/\r?\n/).map((line) => line.trim()).find((line) => pattern.test(line));
21527
+ }
21528
+ function classifyCliOutput(output2, rules, context, options = {}) {
21529
+ const text = stripAnsi(typeof output2 === "string" ? output2 : output2.join("\n"));
21530
+ if (!text.trim()) return void 0;
21531
+ const candidates = options.successfulExit ? (rules ?? []).filter((rule) => rule.evenOnSuccess) : [...rules ?? [], ...COMMON_FAILURE_RULES];
21532
+ for (const rule of candidates) {
21533
+ if (!rule.pattern.test(text)) continue;
21534
+ if (rule.message) return { kind: rule.kind, message: rule.message(text), rule };
21535
+ const detail = rule.detail ? rule.detail(text) : matchingLine(text, rule.pattern);
21536
+ return { kind: rule.kind, message: failureMessage(rule.kind, { ...context, ...detail ? { detail } : {} }), rule };
21537
+ }
21538
+ return void 0;
21539
+ }
21540
+ function classifySpawnError(error62, context) {
21541
+ if (/\bENOENT\b/.test(error62)) return cliFailure("cliMissing", context);
21542
+ return cliFailure("startFailed", { ...context, detail: error62 });
21543
+ }
21544
+
21114
21545
  // src/providers/cli/kiro-session-log.ts
21115
21546
  import { open as open2, readdir, readFile as readFile3, stat } from "node:fs/promises";
21116
21547
  import { homedir as homedir5 } from "node:os";
@@ -21249,10 +21680,11 @@ function sameFolder(a, b) {
21249
21680
  }
21250
21681
 
21251
21682
  // src/providers/cli/kiro.ts
21683
+ var KIRO = requireCliSpec("kiro");
21252
21684
  var execFileAsync = promisify(execFile3);
21253
- var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
21685
+ var ANSI2 = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
21254
21686
  function kiroLaunch(args) {
21255
- return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args });
21687
+ return launchCli({ spec: KIRO, args });
21256
21688
  }
21257
21689
  var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
21258
21690
  function parseKiroSessions(stdout) {
@@ -21267,7 +21699,7 @@ function describeListSessionsError(error62, timeoutMs) {
21267
21699
  if (failure2?.code === "ENOENT") return "\u627E\u4E0D\u5230 kiro-cli";
21268
21700
  if (failure2?.killed || failure2?.signal === "SIGTERM") return `\u8BFB\u53D6\u4F1A\u8BDD\u5217\u8868\u8D85\u65F6\uFF08${Math.round(timeoutMs / 1e3)} \u79D2\uFF09`;
21269
21701
  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);
21702
+ const detail = String(failure2?.stderr ?? "").replace(ANSI2, "").split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
21271
21703
  if (typeof failure2?.code === "number") return `kiro-cli \u9000\u51FA\u7801 ${failure2.code}${detail ? `\uFF1A${detail.slice(0, 160)}` : ""}`;
21272
21704
  return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
21273
21705
  }
@@ -21287,9 +21719,6 @@ async function listKiroSessions(workdir, options = {}) {
21287
21719
  }
21288
21720
  throw new Error(describeListSessionsError(lastError, timeoutMs));
21289
21721
  }
21290
- function isKiroMissingSession(stderr) {
21291
- return stderr.some((line) => /\bSession '[^']*' not found\b/i.test(line.replace(ANSI, "")));
21292
- }
21293
21722
  function kiroToolRows(text) {
21294
21723
  const step = /^\[tool\]\s*(.*)$/.exec(text.trim())?.[1];
21295
21724
  if (step === void 0) return void 0;
@@ -21335,7 +21764,7 @@ function kiroRunParser(context) {
21335
21764
  const replyRows = (lines) => {
21336
21765
  const display = [];
21337
21766
  for (const raw of lines) {
21338
- const line = raw.replace(ANSI, "").replace(/\s+$/, "");
21767
+ const line = raw.replace(ANSI2, "").replace(/\s+$/, "");
21339
21768
  if (!started) {
21340
21769
  if (!line.trim()) continue;
21341
21770
  started = true;
@@ -21362,7 +21791,7 @@ function kiroRunParser(context) {
21362
21791
  return out(replyRows(lines));
21363
21792
  },
21364
21793
  stderr(raw) {
21365
- const text = raw.replace(ANSI, "").trim();
21794
+ const text = raw.replace(ANSI2, "").trim();
21366
21795
  if (!text || isKiroNoise(text)) return { display: [] };
21367
21796
  const closed = closeSegment();
21368
21797
  const status = /^\[tool\]\s*status:\s*(\w+)/i.exec(text)?.[1]?.toLowerCase();
@@ -21411,6 +21840,23 @@ function kiroRunParser(context) {
21411
21840
  };
21412
21841
  }
21413
21842
  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";
21843
+ var KIRO_FAILURE_RULES = [
21844
+ // `chat --resume-id` says `Session '<id>' not found`; ACP `session/load` says `Session not found: <id>`.
21845
+ { kind: "sessionMissing", pattern: /\bSession '[^']*' not found\b|\bSession not found\b|\bNo session found\b/i },
21846
+ { kind: "contextTooLong", pattern: /too many inline media segments/i, message: () => KIRO_IMAGE_LIMIT, evenOnSuccess: true, showInLog: true },
21847
+ { 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 },
21848
+ { 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 },
21849
+ {
21850
+ kind: "serviceRejected",
21851
+ pattern: /having trouble responding/i,
21852
+ evenOnSuccess: true,
21853
+ message: (text) => {
21854
+ const detail = text.match(/message:\s*"([^"]+)"/)?.[1] ?? text.match(/Failed to send the request:\s*(.+)/)?.[1]?.trim();
21855
+ 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" : "";
21856
+ return `Kiro \u670D\u52A1\u62D2\u7EDD\u4E86\u672C\u6B21\u8BF7\u6C42\uFF1A${detail ?? "\u672A\u77E5\u9519\u8BEF"}${hint}`;
21857
+ }
21858
+ }
21859
+ ];
21414
21860
  var kiroProvider = {
21415
21861
  id: "kiro",
21416
21862
  buildLaunch(request) {
@@ -21421,15 +21867,10 @@ var kiroProvider = {
21421
21867
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
21422
21868
  if (request.sessionId && !request.sessionId.startsWith("sess_")) args.push("--resume-id", request.sessionId);
21423
21869
  args.push("--", request.prompt);
21424
- return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args, prompt: request.prompt, promptStdin: "omit" });
21870
+ return launchCli({ spec: KIRO, args, prompt: request.prompt });
21425
21871
  },
21426
21872
  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
- },
21873
+ failureRules: KIRO_FAILURE_RULES,
21433
21874
  /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
21434
21875
  parseLine(line) {
21435
21876
  return kiroRunParser().stdout(`${line}
@@ -21437,32 +21878,355 @@ var kiroProvider = {
21437
21878
  },
21438
21879
  createRunParser: (context) => kiroRunParser(context)
21439
21880
  };
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;
21881
+
21882
+ // src/providers/acp/acp-driver.ts
21883
+ var PROTOCOL_VERSION = 1;
21884
+ var AUTH_REQUIRED = -32e3;
21885
+ var READ_ONLY_KINDS = /* @__PURE__ */ new Set(["read", "search", "think"]);
21886
+ var record4 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21887
+ function acpErrorText(error62) {
21888
+ const message = str(error62?.message) ?? "ACP \u8BF7\u6C42\u5931\u8D25";
21889
+ const data = error62?.data;
21890
+ const detail = typeof data === "string" ? data : data !== void 0 ? JSON.stringify(data) : "";
21891
+ if (!detail || message.includes(detail)) return message;
21892
+ return /^internal error$/i.test(message) ? detail : `${message}: ${detail}`;
21893
+ }
21894
+ function contentText(content) {
21895
+ if (!Array.isArray(content)) return "";
21896
+ return content.map((item) => {
21897
+ const part = record4(item);
21898
+ const inner = record4(part.content);
21899
+ return str(inner.text) ?? str(part.text) ?? "";
21900
+ }).filter(Boolean).join("\n");
21901
+ }
21902
+ function reportedExitCode(rawOutput) {
21903
+ const text = rawOutput === void 0 ? "" : JSON.stringify(rawOutput);
21904
+ const match = /exit status:\s*(-?\d+)/i.exec(text) ?? /"exit_?code"\s*:\s*(-?\d+)/i.exec(text);
21905
+ return match ? Number(match[1]) : void 0;
21906
+ }
21907
+ function rawStdout(rawOutput) {
21908
+ const found = [];
21909
+ const walk = (value) => {
21910
+ if (Array.isArray(value)) value.forEach(walk);
21911
+ else if (value && typeof value === "object") {
21912
+ for (const [key, item] of Object.entries(value)) {
21913
+ if ((key === "stdout" || key === "output") && typeof item === "string") found.push(item);
21914
+ else walk(item);
21915
+ }
21916
+ }
21917
+ };
21918
+ walk(rawOutput);
21919
+ return found.join("\n");
21920
+ }
21921
+ function permissionOutcome(params, request, spec) {
21922
+ const options = Array.isArray(params.options) ? params.options.map(record4) : [];
21923
+ const call = record4(params.toolCall);
21924
+ const title = str(call.title) ?? "";
21925
+ const allowed = request.permissionMode === "full" || READ_ONLY_KINDS.has(str(call.kind) ?? "") || Boolean(spec.restrictedTools?.test(title));
21926
+ const pick2 = (prefix) => options.find((option2) => str(option2.kind) === `${prefix}_once`) ?? options.find((option2) => str(option2.kind)?.startsWith(prefix));
21927
+ const option = allowed ? pick2("allow") : pick2("reject");
21928
+ return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
21929
+ }
21930
+ function acpProvider(spec) {
21931
+ return { ...createAcpProvider(spec), forTurn: () => createAcpProvider(spec) };
21932
+ }
21933
+ function createAcpProvider(spec) {
21934
+ let request;
21935
+ let write;
21936
+ let nextId = 0;
21937
+ const phases = /* @__PURE__ */ new Map();
21938
+ let sessionId = "";
21939
+ let loading = false;
21940
+ let finished = false;
21941
+ let reply = "";
21942
+ let thought = "";
21943
+ let lastReply = "";
21944
+ const tools = /* @__PURE__ */ new Map();
21945
+ let lastShell = "";
21946
+ const send = (message) => write?.(`${JSON.stringify({ jsonrpc: "2.0", ...message })}
21947
+ `);
21948
+ const call = (phase, method, params) => {
21949
+ const id = ++nextId;
21950
+ phases.set(id, phase);
21951
+ send({ id, method, params });
21952
+ };
21953
+ const answer = (id, result) => send({ id, result });
21954
+ const refuse = (id, message) => send({ id, error: { code: -32601, message } });
21955
+ const flush = () => {
21956
+ const display = [];
21957
+ const out = { display };
21958
+ if (thought.trim()) display.push(...runLog.thinking(thought.trim()));
21959
+ thought = "";
21960
+ if (reply.trim()) {
21961
+ lastReply = reply.trim();
21962
+ display.push(...runLog.reply(lastReply));
21963
+ out.message = lastReply;
21964
+ }
21965
+ reply = "";
21966
+ return out;
21967
+ };
21968
+ const merge2 = (...parts) => parts.reduce((all, part) => ({
21969
+ ...all,
21970
+ ...part,
21971
+ display: [...all.display, ...part.display],
21972
+ ...all.chatEvents || part.chatEvents ? { chatEvents: [...all.chatEvents ?? [], ...part.chatEvents ?? []] } : {}
21973
+ }), { display: [] });
21974
+ const fail = (text, kind) => {
21975
+ finished = true;
21976
+ const error62 = kind ? { turnError: failureMessage(kind, { label: spec.cli.label, detail: text }), failureKind: kind } : { turnError: text };
21977
+ return merge2(flush(), { ...error62, endProcess: true, display: [] });
21978
+ };
21979
+ const prompt = () => call("prompt", "session/prompt", { sessionId, prompt: [{ type: "text", text: request.prompt }] });
21980
+ const startSession = () => {
21981
+ const params = { cwd: request.workdir, mcpServers: [] };
21982
+ if (request.sessionId && (spec.resumable?.(request.sessionId) ?? true)) {
21983
+ loading = true;
21984
+ call("load", "session/load", { ...params, sessionId: request.sessionId });
21985
+ } else call("new", "session/new", params);
21986
+ };
21987
+ const afterSession = (loaded) => {
21988
+ if (loaded && spec.setModelOnLoad && request.model) call("set_model", "session/set_model", { sessionId, modelId: request.model });
21989
+ else prompt();
21990
+ };
21991
+ const onResponse = (message) => {
21992
+ const phase = typeof message.id === "number" ? phases.get(message.id) : void 0;
21993
+ if (!phase) return { display: [] };
21994
+ phases.delete(message.id);
21995
+ if (message.error) {
21996
+ const text = acpErrorText(message.error);
21997
+ if (phase === "load") {
21998
+ loading = false;
21999
+ if (classifyCliOutput(text, spec.failureRules, spec.cli)?.kind === "sessionMissing") {
22000
+ const missing = request.sessionId;
22001
+ call("new", "session/new", { cwd: request.workdir, mcpServers: [] });
22002
+ return { display: [runLog.event(`\u539F\u4F1A\u8BDD ${missing} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`)] };
22003
+ }
22004
+ }
22005
+ return fail(text, message.error.code === AUTH_REQUIRED ? "notSignedIn" : void 0);
22006
+ }
22007
+ const result = record4(message.result);
22008
+ switch (phase) {
22009
+ case "initialize":
22010
+ startSession();
22011
+ return { display: [] };
22012
+ case "load":
22013
+ loading = false;
22014
+ sessionId = request.sessionId;
22015
+ afterSession(true);
22016
+ return { sessionId, display: [] };
22017
+ case "new": {
22018
+ sessionId = str(result.sessionId) ?? "";
22019
+ if (!sessionId) return fail("ACP session/new \u6CA1\u6709\u8FD4\u56DE\u4F1A\u8BDD ID");
22020
+ afterSession(false);
22021
+ return { sessionId, display: [runLog.event(`\u4F1A\u8BDD ${sessionId}`)] };
22022
+ }
22023
+ case "set_model":
22024
+ prompt();
22025
+ return { display: [] };
22026
+ case "prompt": {
22027
+ finished = true;
22028
+ const stopReason = str(result.stopReason) ?? "end_turn";
22029
+ const rows = flush();
22030
+ if (stopReason === "refusal") return merge2(rows, { turnError: "model refused to answer (stopReason: refusal)", endProcess: true, display: [] });
22031
+ if (stopReason === "cancelled") return merge2(rows, { turnError: "\u672C\u8F6E\u88AB CLI \u53D6\u6D88", endProcess: true, display: [] });
22032
+ const note = stopReason === "end_turn" ? "\u672C\u8F6E\u5B8C\u6210" : `\u672C\u8F6E\u7ED3\u675F\uFF08${stopReason}\uFF09`;
22033
+ return merge2(rows, { turnCompleted: true, endProcess: true, display: [runLog.event(note)] });
22034
+ }
22035
+ }
22036
+ };
22037
+ const onToolCall = (update) => {
22038
+ const id = str(update.toolCallId) ?? "";
22039
+ const known = tools.get(id);
22040
+ const input2 = record4(update.rawInput);
22041
+ const locations = Array.isArray(update.locations) ? update.locations.map(record4) : [];
22042
+ const tool = known ?? { kind: "other", title: "tool" };
22043
+ tool.kind = str(update.kind) ?? tool.kind;
22044
+ if (!known) tool.title = str(update.title) ?? tool.title;
22045
+ if (tool.kind === "execute" && !tool.command) {
22046
+ const command = str(input2.command) ?? str(update.title)?.replace(/^Running:\s*/i, "");
22047
+ if (command && command !== "shell") tool.command = command;
22048
+ }
22049
+ const path = tool.path ?? str(locations[0]?.path) ?? str(input2.path) ?? str(input2.file_path);
22050
+ if (path) tool.path = path;
22051
+ const output2 = contentText(update.content);
22052
+ if (output2) tool.output = output2;
22053
+ tools.set(id, tool);
22054
+ if (known) return { display: [] };
22055
+ const rows = flush();
22056
+ if (tool.kind === "execute") {
22057
+ lastShell = id;
22058
+ return merge2(rows, { display: [runLog.command(tool.command ?? tool.title)] });
22059
+ }
22060
+ lastShell = "";
22061
+ if (tool.kind === "edit" || tool.kind === "delete" || tool.kind === "move") return merge2(rows, { display: [runLog.fileChange(tool.path)] });
22062
+ if (READ_ONLY_KINDS.has(tool.kind)) return rows;
22063
+ if (tool.kind === "fetch") return merge2(rows, { display: [runLog.tool("web_search")] });
22064
+ const meta3 = record4(record4(update._meta).kiro);
22065
+ return merge2(rows, { display: toolCallRows(str(meta3.toolName) ?? tool.title, tool.path) });
22066
+ };
22067
+ const onToolUpdate = (update) => {
22068
+ const id = str(update.toolCallId) ?? "";
22069
+ const first = onToolCall(update);
22070
+ const tool = tools.get(id);
22071
+ const status = str(update.status);
22072
+ if (status !== "completed" && status !== "failed") return first;
22073
+ if (tool.kind === "execute") {
22074
+ const header = lastShell === id ? [] : [runLog.command(tool.command ?? tool.title)];
22075
+ lastShell = "";
22076
+ const code = reportedExitCode(update.rawOutput) ?? (status === "failed" ? 1 : 0);
22077
+ const output2 = tool.output ?? rawStdout(update.rawOutput);
22078
+ return { display: [...header, ...runLog.commandOutput(output2), runLog.commandExit(code)] };
22079
+ }
22080
+ if (status === "failed") {
22081
+ lastShell = "";
22082
+ return merge2(first, { display: [runLog.error(`${tool.title}${tool.output ? `\uFF1A${tool.output}` : " \u5931\u8D25"}`)] });
22083
+ }
22084
+ return first;
22085
+ };
22086
+ const onUpdate = (params) => {
22087
+ if (loading) return { display: [] };
22088
+ const update = record4(params.update);
22089
+ const text = str(record4(update.content).text);
22090
+ switch (str(update.sessionUpdate)) {
22091
+ case "agent_message_chunk": {
22092
+ if (!text) return { display: [] };
22093
+ const rows = thought ? flush() : { display: [] };
22094
+ reply += text;
22095
+ return merge2(rows, { chatEvents: [{ event: "text_delta", text }], display: [] });
22096
+ }
22097
+ case "agent_thought_chunk": {
22098
+ if (!text) return { display: [] };
22099
+ const rows = reply ? flush() : { display: [] };
22100
+ thought += text;
22101
+ return merge2(rows, { chatEvents: [{ event: "thought_delta", text }], display: [] });
22102
+ }
22103
+ case "tool_call":
22104
+ return onToolCall(update);
22105
+ case "tool_call_update":
22106
+ return onToolUpdate(update);
22107
+ default:
22108
+ return { display: [] };
22109
+ }
22110
+ };
22111
+ const onRequest = (message) => {
22112
+ const params = record4(message.params);
22113
+ if (message.method === "session/request_permission") {
22114
+ answer(message.id, permissionOutcome(params, request, spec));
22115
+ return { display: [] };
22116
+ }
22117
+ refuse(message.id, `${message.method} is not supported by this client`);
22118
+ return { display: [] };
22119
+ };
22120
+ return {
22121
+ id: spec.cli.id,
22122
+ ...spec.failureRules ? { failureRules: spec.failureRules } : {},
22123
+ ...spec.stderrDisplay ? { stderrDisplay: spec.stderrDisplay } : {},
22124
+ buildLaunch(turn) {
22125
+ request = turn;
22126
+ return launchCli({ spec: spec.cli, args: spec.args(turn) });
22127
+ },
22128
+ startInput(writer) {
22129
+ write = writer;
22130
+ call("initialize", "initialize", {
22131
+ protocolVersion: PROTOCOL_VERSION,
22132
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
22133
+ clientInfo: { name: "toc-ocra", title: "Echo device agent", version: "1" }
22134
+ });
22135
+ },
22136
+ parseLine(line) {
22137
+ const message = tryJson(line);
22138
+ if (!message) return { display: line.trim() ? [clip(line, 400)] : [] };
22139
+ if (finished && message.id === void 0) return { display: [] };
22140
+ if (message.method && message.id !== void 0) return onRequest(message);
22141
+ if (message.method) {
22142
+ const params = record4(message.params);
22143
+ if (message.method === "session/update") return onUpdate(params);
22144
+ const rows = spec.notification?.(message.method, params);
22145
+ return { display: rows ?? [] };
22146
+ }
22147
+ return onResponse(message);
22148
+ }
22149
+ };
21455
22150
  }
21456
22151
 
21457
- // src/providers/cli/opencode.ts
21458
- var opencodeProvider = {
21459
- id: "opencode",
22152
+ // src/providers/acp/acp-agents.ts
22153
+ var ECHO_CALLBACK = /echo_report_task_progress/;
22154
+ var KIRO_ACP = {
22155
+ cli: requireCliSpec("kiro"),
22156
+ args: (request) => [
22157
+ "acp",
22158
+ // Restricted: only Echo's callback is trusted; every other permission
22159
+ // request is answered by the driver (read-only kinds allowed, rest denied).
22160
+ request.permissionMode === "full" ? "--trust-all-tools" : "--trust-tools=@doer/echo_report_task_progress",
22161
+ ...request.model ? ["--model", request.model] : [],
22162
+ ...request.reasoningEffort ? ["--effort", request.reasoningEffort] : []
22163
+ ],
22164
+ restrictedTools: ECHO_CALLBACK,
22165
+ // `--model` only reaches a new session.
22166
+ setModelOnLoad: true,
22167
+ // `sess_…` ids are Kiro IDE (v3 engine) chats: never write into someone's IDE chat.
22168
+ resumable: (sessionId) => !sessionId.startsWith("sess_"),
22169
+ failureRules: KIRO_FAILURE_RULES,
22170
+ stderrDisplay: (line) => isKiroNoise(line.trim()) ? [] : [line],
22171
+ notification(method, params) {
22172
+ if (method !== "_kiro.dev/session/update") return void 0;
22173
+ const update = params;
22174
+ if (update.sessionUpdate === "retry_warning" && typeof update.message === "string") return [runLog.event(`Kiro \u670D\u52A1\u91CD\u8BD5\uFF1A${update.message}`)];
22175
+ return [];
22176
+ }
22177
+ };
22178
+ var GEMINI_FAILURE_RULES = [
22179
+ { kind: "sessionMissing", pattern: /session[^\n]{0,60}(?:not found|does not exist)|no session found|invalid session/i },
22180
+ { kind: "notSignedIn", pattern: /api key is missing|not configured|login required|please (?:log|sign) ?in/i }
22181
+ ];
22182
+ var GEMINI_ACP = {
22183
+ cli: requireCliSpec("gemini"),
22184
+ args: (request) => [
22185
+ "--acp",
22186
+ // Restricted: Gemini asks before editing or running anything, and the driver denies it.
22187
+ ...request.permissionMode === "full" ? ["--yolo"] : ["--approval-mode", "default"],
22188
+ ...request.model ? ["--model", request.model] : []
22189
+ ],
22190
+ restrictedTools: ECHO_CALLBACK,
22191
+ failureRules: GEMINI_FAILURE_RULES
22192
+ };
22193
+ var kiroAcpProvider = acpProvider(KIRO_ACP);
22194
+ var geminiAcpProvider = acpProvider(GEMINI_ACP);
22195
+
22196
+ // src/providers/cli/grok.ts
22197
+ var GROK = requireCliSpec("grok");
22198
+ var grokProvider = {
22199
+ id: "grok",
22200
+ buildLaunch(request) {
22201
+ const args = [`--single=${request.prompt}`, "--output-format", "json", "--always-approve", "--no-subagents"];
22202
+ if (request.model) args.push("--model", request.model);
22203
+ if (request.reasoningEffort) args.push("--reasoning-effort", request.reasoningEffort);
22204
+ if (request.sessionId) args.push("--resume", request.sessionId);
22205
+ return launchCli({ spec: GROK, args });
22206
+ },
22207
+ parseLine(line) {
22208
+ const event = tryJson(line);
22209
+ if (!event) return { display: line.trim() ? [line] : [] };
22210
+ const sessionId = str(event.sessionId) ?? str(event.session_id);
22211
+ const text = str(event.text) ?? str(event.response) ?? str(event.result) ?? str(event.content);
22212
+ return {
22213
+ ...sessionId ? { sessionId } : {},
22214
+ ...text ? { message: text, turnCompleted: true } : {},
22215
+ display: text ? textRows("\u203A ", text) : [clip(line, 300)]
22216
+ };
22217
+ }
22218
+ };
22219
+
22220
+ // src/providers/cli/opencode.ts
22221
+ var OPENCODE = requireCliSpec("opencode");
22222
+ var opencodeProvider = {
22223
+ id: "opencode",
21460
22224
  buildLaunch(request) {
21461
22225
  const args = ["run", "--format", "json"];
21462
22226
  if (request.model) args.push("--model", request.model);
21463
22227
  if (request.sessionId) args.push("--session", request.sessionId);
21464
22228
  args.push(request.prompt);
21465
- return launchCli({ command: "opencode", overrideEnv: "TOC_OCRA_OPENCODE_PATH", args });
22229
+ return launchCli({ spec: OPENCODE, args });
21466
22230
  },
21467
22231
  parseLine(line) {
21468
22232
  const event = tryJson(line);
@@ -21478,570 +22242,187 @@ var opencodeProvider = {
21478
22242
  }
21479
22243
  };
21480
22244
 
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
- });
22245
+ // src/providers/codex-quota.ts
22246
+ import { spawn as spawn3 } from "node:child_process";
22247
+ import { createInterface } from "node:readline";
22248
+ async function readCodexQuotaWindows() {
22249
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--stdio"] });
22250
+ const child = spawn3(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
22251
+ let nextId = 0;
22252
+ const pending = /* @__PURE__ */ new Map();
22253
+ const lines = createInterface({ input: child.stdout });
22254
+ const rejectPending = (error62) => {
22255
+ for (const waiter of pending.values()) waiter.reject(error62);
22256
+ pending.clear();
22257
+ };
22258
+ child.once("error", (error62) => rejectPending(error62));
22259
+ child.once("exit", (code) => {
22260
+ if (pending.size) rejectPending(new Error(`Codex app-server \u5DF2\u9000\u51FA\uFF08${code ?? "unknown"}\uFF09`));
21562
22261
  });
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;
22262
+ lines.on("line", (line) => {
22263
+ let message;
22264
+ try {
22265
+ message = JSON.parse(line);
22266
+ } catch {
22267
+ return;
22268
+ }
22269
+ if (typeof message.id !== "number") return;
22270
+ const waiter = pending.get(message.id);
22271
+ if (!waiter) return;
22272
+ pending.delete(message.id);
22273
+ if (message.error) waiter.reject(new Error(message.error.message || "Codex \u989D\u5EA6\u63A5\u53E3\u8C03\u7528\u5931\u8D25"));
22274
+ else waiter.resolve(message.result);
22275
+ });
22276
+ const request = (method, params) => {
22277
+ const id = ++nextId;
22278
+ return new Promise((resolve7, reject) => {
22279
+ const timer = setTimeout(() => {
22280
+ pending.delete(id);
22281
+ reject(new Error(`Codex \u989D\u5EA6\u8BFB\u53D6\u8D85\u65F6\uFF08${method}\uFF09`));
22282
+ }, 2e4);
22283
+ pending.set(id, {
22284
+ resolve: (value) => {
22285
+ clearTimeout(timer);
22286
+ resolve7(value);
22287
+ },
22288
+ reject: (error62) => {
22289
+ clearTimeout(timer);
22290
+ reject(error62);
22291
+ }
22292
+ });
22293
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, id, params })}
22294
+ `, (error62) => {
22295
+ if (!error62) return;
22296
+ const waiter = pending.get(id);
22297
+ if (waiter) {
22298
+ pending.delete(id);
22299
+ clearTimeout(timer);
22300
+ waiter.reject(error62);
22301
+ }
22302
+ });
21572
22303
  });
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 } : {}
22304
+ };
22305
+ try {
22306
+ await request("initialize", {
22307
+ clientInfo: { name: "toc-ocra", title: "Echo device agent", version: "0.2.3" },
22308
+ capabilities: { experimentalApi: true }
22309
+ });
22310
+ child.stdin.write('{"jsonrpc":"2.0","method":"initialized","params":{}}\n');
22311
+ const result = await request("account/rateLimits/read", {});
22312
+ const buckets = Object.entries(result?.rateLimitsByLimitId ?? {});
22313
+ if (!buckets.length && result?.rateLimits) buckets.push([String(result.rateLimits.limitId || "codex"), result.rateLimits]);
22314
+ const windows = buckets.flatMap(([limitId, snapshot]) => ["primary", "secondary"].flatMap((key) => {
22315
+ const window = snapshot[key];
22316
+ if (!window) return [];
22317
+ const resetRaw = Number(window.resetsAt);
22318
+ const resetsAt = Number.isFinite(resetRaw) && resetRaw > 0 ? Math.floor(resetRaw > 1e10 ? resetRaw / 1e3 : resetRaw) : 0;
22319
+ const durationMins = Number(window.windowDurationMins);
22320
+ const usedRaw = Number(window.usedPercent);
22321
+ 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";
22322
+ const bucketName = typeof snapshot.limitName === "string" && snapshot.limitName.trim() ? snapshot.limitName.trim() : limitId === "codex" ? "" : limitId;
22323
+ const item = {
22324
+ key: `${limitId}:${key}`,
22325
+ label: bucketName ? `${bucketName} \xB7 ${windowLabel}` : windowLabel,
22326
+ resets_at: resetsAt,
22327
+ ...Number.isFinite(usedRaw) && usedRaw >= 0 && usedRaw <= 100 ? { used_percent: usedRaw } : {},
22328
+ ...Number.isFinite(durationMins) && durationMins > 0 ? { window_seconds: Math.floor(durationMins * 60) } : {}
21598
22329
  };
22330
+ return [item];
21599
22331
  }));
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;
22332
+ 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");
22333
+ return windows;
22334
+ } finally {
22335
+ for (const waiter of pending.values()) waiter.reject(new Error("Codex app-server \u5DF2\u5173\u95ED"));
22336
+ pending.clear();
22337
+ lines.close();
22338
+ currentPlatform.stopHelper(child);
21610
22339
  }
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
22340
  }
21627
22341
 
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 };
22342
+ // src/providers/kiro-quota.ts
22343
+ import { execFile as execFile4 } from "node:child_process";
22344
+ import { tmpdir } from "node:os";
22345
+ import { promisify as promisify2, stripVTControlCharacters } from "node:util";
22346
+ var execFileAsync2 = promisify2(execFile4);
22347
+ var amount = (value) => Number(value.replace(/,/g, ""));
22348
+ var rounded = (value) => Math.round(value * 100) / 100;
22349
+ function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
22350
+ const text = stripVTControlCharacters(stdout).replace(/\r/g, "");
22351
+ const usage = text.match(/^\s*Credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+covered in plan\s*\)/im);
22352
+ 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");
22353
+ const used = amount(usage[1]);
22354
+ const total = amount(usage[2]);
22355
+ if (!Number.isFinite(used) || !Number.isFinite(total) || used < 0 || total < 0) throw new Error("Kiro \u8FD4\u56DE\u7684\u79EF\u5206\u6570\u503C\u65E0\u6548");
22356
+ const date5 = text.match(/resets on\s+(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2})/i)?.[1];
22357
+ let resetDate;
22358
+ if (date5) {
22359
+ resetDate = date5.includes("-") ? date5 : `${now.getFullYear()}-${date5.replace("/", "-")}`;
22360
+ if (!date5.includes("-") && (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() < new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) {
22361
+ resetDate = `${now.getFullYear() + 1}-${date5.replace("/", "-")}`;
22012
22362
  }
22013
- };
22363
+ }
22364
+ const reset = resetDate ? (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() : NaN;
22365
+ const plan = text.match(/Estimated Usage[^\n]*\|\s*(KIRO[^|\n]*)/i)?.[1]?.trim();
22366
+ const windows = [{
22367
+ key: "kiro:plan",
22368
+ label: plan ? `\u5957\u9910\u79EF\u5206 \xB7 ${plan}` : "\u5957\u9910\u79EF\u5206",
22369
+ kind: "credits",
22370
+ total,
22371
+ used,
22372
+ remaining: rounded(Math.max(0, total - used)),
22373
+ unit: "credits",
22374
+ used_percent: total > 0 ? Math.min(100, rounded(used / total * 100)) : 100,
22375
+ resets_at: Number.isFinite(reset) ? Math.floor(reset / 1e3) : 0,
22376
+ ...resetDate && Number.isFinite(reset) ? { reset_date: resetDate } : {},
22377
+ estimated: true
22378
+ }];
22379
+ const pools = /^\s*(Bonus|Trial|Free trial|Add[ -]on|Purchased) credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+(?:used|consumed|covered)[^)]*\)([^\n]*)/gim;
22380
+ for (const match of text.matchAll(pools)) {
22381
+ const poolUsed = amount(match[2]);
22382
+ const poolTotal = amount(match[3]);
22383
+ 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");
22384
+ const expires = match[4]?.match(/expir(?:es?|y|ation)(?: on| at|:)?\s+(\d{4}-\d{2}-\d{2})/i)?.[1];
22385
+ const expiresAt = expires ? (/* @__PURE__ */ new Date(`${expires}T00:00:00`)).getTime() : NaN;
22386
+ const key = match[1].toLowerCase().replace(/[ -]/g, "");
22387
+ windows.push({
22388
+ key: `kiro:${key}`,
22389
+ label: /bonus|trial/i.test(key) ? "\u8D60\u9001\u79EF\u5206" : "\u52A0\u8D2D\u79EF\u5206",
22390
+ kind: "credits",
22391
+ total: poolTotal,
22392
+ used: poolUsed,
22393
+ remaining: rounded(Math.max(0, poolTotal - poolUsed)),
22394
+ unit: "credits",
22395
+ resets_at: 0,
22396
+ estimated: true,
22397
+ ...Number.isFinite(expiresAt) ? { expires_at: Math.floor(expiresAt / 1e3) } : {}
22398
+ });
22399
+ }
22400
+ return windows;
22014
22401
  }
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}`);
22402
+ async function readKiroQuotaWindows() {
22403
+ const launch = launchCli({ spec: requireCliSpec("kiro"), args: ["chat", "--no-interactive", "/usage"] });
22404
+ try {
22405
+ const { stdout, stderr } = await execFileAsync2(launch.executable, launch.args, { env: launch.env, cwd: tmpdir(), timeout: 3e4, maxBuffer: 1024 * 1024, windowsHide: true });
22406
+ return parseKiroQuota(`${stdout}
22407
+ ${stderr}`);
22408
+ } catch (error62) {
22409
+ if (error62 instanceof Error && error62.message.startsWith("Kiro ")) throw error62;
22410
+ 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
22411
  }
22027
22412
  }
22028
22413
 
22029
- // src/providers/model-catalog-collector.ts
22030
- import { createHash } from "node:crypto";
22031
- import { stat as stat2 } from "node:fs/promises";
22032
-
22033
22414
  // src/providers/model-catalog.ts
22034
- import { spawn as spawn6 } from "node:child_process";
22415
+ import { spawn as spawn5 } from "node:child_process";
22035
22416
  import { readFile as readFile4 } from "node:fs/promises";
22036
22417
  import { homedir as homedir6 } from "node:os";
22037
22418
  import { isAbsolute, join as join9, resolve as resolve2 } from "node:path";
22038
22419
 
22039
22420
  // src/providers/kiro-models.ts
22040
- import { spawn as spawn5 } from "node:child_process";
22041
- import { createInterface } from "node:readline";
22421
+ import { spawn as spawn4 } from "node:child_process";
22422
+ import { createInterface as createInterface2 } from "node:readline";
22042
22423
  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 });
22424
+ const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
22425
+ const lines = createInterface2({ input: child.stdout });
22045
22426
  let nextId = 0;
22046
22427
  let failure2;
22047
22428
  const pending = /* @__PURE__ */ new Map();
@@ -22273,10 +22654,14 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
22273
22654
  return catalog;
22274
22655
  }
22275
22656
  var MODEL_LIST_TIMEOUT_MS = 2e4;
22657
+ function cliExecutable(id) {
22658
+ const spec = requireCliSpec(id);
22659
+ return process.env[spec.overrideEnv]?.trim() || resolveCliCommand(cliCommand(spec));
22660
+ }
22276
22661
  function runModelListCommand(executable, args, label, environment) {
22277
22662
  return new Promise((resolve7, reject) => {
22278
22663
  const launch = directLaunch2(executable, args);
22279
- const child = spawn6(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
22664
+ const child = spawn5(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
22280
22665
  let stdout = "";
22281
22666
  let stderr = "";
22282
22667
  const timer = setTimeout(() => {
@@ -22304,8 +22689,8 @@ function runModelListCommand(executable, args, label, environment) {
22304
22689
  }
22305
22690
  async function readKiroModelCatalog() {
22306
22691
  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);
22692
+ const kiro = requireCliSpec("kiro");
22693
+ const listLaunch = launchCli({ spec: kiro, args: ["chat", "--list-models", "--format", "json"], env: environment });
22309
22694
  const output2 = await runModelListCommand(listLaunch.executable, listLaunch.args, "kiro-cli", environment);
22310
22695
  let listed;
22311
22696
  try {
@@ -22318,7 +22703,7 @@ async function readKiroModelCatalog() {
22318
22703
  ...listed.default_model ? { default_model: listed.default_model } : {},
22319
22704
  models: listed.models.map((model) => ({ model_id: model.id, model_name: model.name, ...model.description ? { description: model.description } : {}, supported_reasoning_efforts: [] }))
22320
22705
  };
22321
- const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
22706
+ const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
22322
22707
  const [payload, content] = await Promise.all([
22323
22708
  readKiroNativeModels(launch, homedir6(), { catalog: base }),
22324
22709
  readFile4(join9(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
@@ -22424,7 +22809,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
22424
22809
  }
22425
22810
  async function readGrokModelCatalog() {
22426
22811
  const config2 = await readFile4(join9(grokHome(), "config.toml"), "utf8").catch(() => "");
22427
- const output2 = await runModelListCommand(resolveCliCommand("grok"), ["models"], "grok");
22812
+ const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
22428
22813
  const catalog = parseGrokModelCatalog(output2, config2);
22429
22814
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
22430
22815
  return catalog;
@@ -22443,7 +22828,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
22443
22828
  }
22444
22829
  async function readOpencodeModelCatalog() {
22445
22830
  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");
22831
+ const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
22447
22832
  const catalog = parseOpencodeModelCatalog(output2, config2);
22448
22833
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
22449
22834
  return catalog;
@@ -22470,235 +22855,342 @@ var MODEL_SOURCES = {
22470
22855
  }
22471
22856
  };
22472
22857
 
22473
- // src/providers/model-catalog-collector.ts
22474
- async function fileStamp(path) {
22475
- try {
22476
- const info = await stat2(path);
22477
- return `${path}:${info.mtimeMs}:${info.size}`;
22478
- } catch {
22479
- return `${path}:-`;
22480
- }
22481
- }
22482
- function reportHash(items) {
22483
- const stable = items.map((item) => ({
22484
- agent_type: item.agent_type,
22485
- error: item.error ?? "",
22486
- ...item.catalog ? { catalog: { ...item.catalog, fetched_at: "" } } : {}
22487
- }));
22488
- return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
22489
- }
22490
- var ModelCatalogCollector = class {
22491
- constructor(sources = MODEL_SOURCES) {
22492
- this.sources = sources;
22493
- }
22494
- sources;
22495
- cache = /* @__PURE__ */ new Map();
22496
- /** CLI ids that have a model source, among the detected ones. */
22497
- supported(detectedIds) {
22498
- return [...new Set(detectedIds.map((id) => id === "claude-code" ? "claude" : id))].filter((id) => id in this.sources).sort();
22499
- }
22500
- async collect(detectedIds, options = {}) {
22501
- const ids = this.supported(detectedIds);
22502
- const items = await Promise.all(ids.map((id) => this.readOne(id, Boolean(options.force && (!options.only || options.only === id)))));
22503
- return { hash: reportHash(items), items };
22504
- }
22505
- async readOne(id, force) {
22506
- const source = this.sources[id];
22507
- const now = Date.now();
22508
- const stamps = await Promise.all(source.watchFiles().map(fileStamp));
22509
- const fingerprint = stamps.join("|");
22510
- const cached3 = this.cache.get(id);
22511
- const expired = source.refreshEveryMs !== void 0 && cached3 !== void 0 && now - cached3.readAt >= source.refreshEveryMs;
22512
- if (cached3 && !force && !expired && cached3.fingerprint === fingerprint) return cached3.item;
22513
- let item;
22514
- try {
22515
- const catalog = await source.read();
22516
- item = { agent_type: id, catalog: { ...catalog, agent_type: id } };
22517
- } catch (error62) {
22518
- item = { agent_type: id, error: error62 instanceof Error ? error62.message : String(error62) };
22519
- }
22520
- this.cache.set(id, { fingerprint, readAt: now, item });
22521
- return item;
22522
- }
22858
+ // src/providers/registry.ts
22859
+ var ADAPTERS = {
22860
+ codex: { headless: codexProvider, chat: codexChatProvider, models: MODEL_SOURCES.codex, quota: readCodexQuotaWindows },
22861
+ claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude },
22862
+ grok: { headless: grokProvider, models: MODEL_SOURCES.grok },
22863
+ // ACP CLIs: one shared driver (acp/acp-driver.ts), one launch spec each (acp/acp-agents.ts).
22864
+ gemini: { headless: geminiAcpProvider, models: MODEL_SOURCES.gemini, legacy: { headless: geminiProvider, restrictedPermission: false } },
22865
+ opencode: { headless: opencodeProvider, models: MODEL_SOURCES.opencode },
22866
+ kiro: { headless: kiroAcpProvider, models: MODEL_SOURCES.kiro, quota: readKiroQuotaWindows, legacy: { headless: kiroProvider, restrictedPermission: true } }
22523
22867
  };
22524
-
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();
22868
+ function catalogRow(spec) {
22869
+ return {
22870
+ ...spec,
22871
+ ...ADAPTERS[spec.id],
22872
+ detectCmd: cliCommand(spec),
22873
+ ...spec.commandAliases?.length ? { detectCmdAliases: spec.commandAliases } : {},
22874
+ ...spec.requiredCommands?.length ? { detectRequiredCommands: spec.requiredCommands } : {},
22875
+ ...spec.unsupportedPlatforms?.length ? { detectUnsupportedRuntimes: spec.unsupportedPlatforms } : {}
22537
22876
  };
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
- });
22877
+ }
22878
+ var CLI_CATALOG = CLI_SPECS.map(catalogRow);
22879
+ function catalogEntry(idOrAlias) {
22880
+ const id = cliSpec(idOrAlias)?.id;
22881
+ return id ? CLI_CATALOG.find((entry) => entry.id === id) : void 0;
22882
+ }
22883
+ var CHAT_PROVIDERS = CLI_CATALOG.filter((entry) => entry.chat).map((entry) => entry.id);
22884
+ function modelSources() {
22885
+ return Object.fromEntries(CLI_CATALOG.flatMap((entry) => entry.models ? [[entry.id, entry.models]] : []));
22886
+ }
22887
+ function resolveRunnableCli(agentType, mode, platform2 = currentPlatform.id) {
22888
+ const row = catalogEntry(agentType);
22889
+ const entry = row ? withDriverChoice(row) : void 0;
22890
+ if (!entry) return { failure: cliFailure("cliUnsupported", { label: agentType }) };
22891
+ const context = { label: entry.label };
22892
+ if (!supportsPlatform(entry, platform2)) return { failure: cliFailure("platformUnsupported", context) };
22893
+ if (mode.chat ? !entry.chat : !entry.headless) {
22894
+ 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` } };
22895
+ }
22896
+ if (mode.permissionMode !== "full" && !entry.restrictedPermission) return { failure: cliFailure("permissionUnsupported", context) };
22897
+ return { entry };
22898
+ }
22899
+ function withDriverChoice(entry) {
22900
+ const variable = `TOC_OCRA_${entry.id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_DRIVER`;
22901
+ if (!entry.legacy || process.env[variable]?.trim().toLowerCase() !== "legacy") return entry;
22902
+ const { restrictedPermission: _acp, ...rest } = entry;
22903
+ return { ...rest, headless: entry.legacy.headless, ...entry.legacy.restrictedPermission ? { restrictedPermission: true } : {} };
22904
+ }
22905
+ function buildProviderDetectionCommands(configs = CLI_CATALOG) {
22906
+ return configs.flatMap(
22907
+ (config2) => [config2.detectCmd, ...config2.detectCmdAliases ?? []].map((cmd) => ({
22908
+ id: config2.id,
22909
+ cmd,
22910
+ ...config2.detectRequiredCommands?.length ? { requiredCommands: config2.detectRequiredCommands } : {},
22911
+ ...config2.detectUnsupportedRuntimes?.length ? { unsupportedRuntimes: config2.detectUnsupportedRuntimes } : {}
22912
+ }))
22913
+ );
22914
+ }
22915
+ var DETECTION_COMMANDS = buildProviderDetectionCommands();
22916
+ function getProviderDetectionProbeCommands(commands = DETECTION_COMMANDS, runtime = process.platform) {
22917
+ return [...new Set(commands.filter((command) => !command.unsupportedRuntimes?.includes(runtime)).flatMap((command) => [command.cmd, ...command.requiredCommands ?? []]))];
22918
+ }
22919
+ function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COMMANDS, runtime = process.platform) {
22920
+ const detected = /* @__PURE__ */ new Map();
22921
+ for (const command of commands) {
22922
+ if (command.unsupportedRuntimes?.includes(runtime)) continue;
22923
+ if (!foundCommands.has(command.cmd)) continue;
22924
+ if (!(command.requiredCommands ?? []).every((required2) => foundCommands.has(required2))) continue;
22925
+ if (!detected.has(command.id)) detected.set(command.id, command.cmd);
22926
+ }
22927
+ return detected;
22928
+ }
22929
+
22930
+ // src/providers/detection.ts
22931
+ function probeVersion(path, args) {
22932
+ if (args.length === 0) return Promise.resolve({});
22933
+ return new Promise((resolve7) => {
22934
+ const launch = directLaunch2(path, args);
22935
+ const child = spawn6(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
22936
+ let stdout = "";
22937
+ let stderr = "";
22938
+ let settled = false;
22939
+ let timer;
22940
+ const finish = (result) => {
22941
+ if (settled) return;
22942
+ settled = true;
22943
+ if (timer) clearTimeout(timer);
22944
+ resolve7(result);
22945
+ };
22946
+ timer = setTimeout(() => {
22947
+ child.kill("SIGKILL");
22948
+ finish({ detail: "version probe timeout" });
22949
+ }, 5e3);
22950
+ child.stdout.on("data", (chunk) => {
22951
+ stdout += chunk.toString();
22583
22952
  });
22584
- };
22585
- try {
22586
- await request("initialize", {
22587
- clientInfo: { name: "toc-ocra", title: "Echo device agent", version: "0.2.3" },
22588
- capabilities: { experimentalApi: true }
22953
+ child.stderr.on("data", (chunk) => {
22954
+ stderr += chunk.toString();
22589
22955
  });
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) } : {}
22956
+ child.on("error", (error62) => finish({ detail: error62.message }));
22957
+ child.on("close", (code) => {
22958
+ const detail = (stdout || stderr || `exit ${code ?? "unknown"}`).trim().slice(0, 200);
22959
+ const version2 = stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
22960
+ finish(version2 ? { version: version2, detail } : { detail });
22961
+ });
22962
+ });
22963
+ }
22964
+ var CliDetectionService = class {
22965
+ snapshot;
22966
+ pending;
22967
+ async detect(forceRefresh = false) {
22968
+ if (this.pending) return this.pending;
22969
+ if (!forceRefresh && this.snapshot) return this.snapshot;
22970
+ this.pending = this.detectNow(forceRefresh).finally(() => {
22971
+ this.pending = void 0;
22972
+ });
22973
+ return this.pending;
22974
+ }
22975
+ async detectNow(forceRefresh) {
22976
+ const hydration = await hydrateShellPath({ force: forceRefresh });
22977
+ const addedPathSegments = hydration.ok ? mergePathSegments(hydration.segments) : [];
22978
+ const commands = getProviderDetectionProbeCommands(DETECTION_COMMANDS);
22979
+ const resolved = new Map(commands.map((command) => [command, resolveCliCommandDetailed(command)]));
22980
+ const foundCommands = new Set(commands.filter((command) => resolved.get(command)?.found));
22981
+ const detected = resolveDetectedProviderCommands(foundCommands, DETECTION_COMMANDS);
22982
+ const providers = await Promise.all(CLI_CATALOG.map(async (config2) => {
22983
+ const matchedDetectionCommand = detected.get(config2.id);
22984
+ const result = matchedDetectionCommand ? resolved.get(matchedDetectionCommand) : void 0;
22985
+ const executablePath = result?.found ? result.path : void 0;
22986
+ const installed = Boolean(executablePath);
22987
+ const unsupported = config2.detectUnsupportedRuntimes?.includes(process.platform) ?? false;
22988
+ const diagnostic = executablePath ? await probeVersion(executablePath, config2.versionArguments ?? []) : {};
22989
+ const detail = installed ? diagnostic.detail : unsupported ? "unsupported runtime" : config2.detectRequiredCommands?.length ? "command or required command not found" : "command not found";
22990
+ return {
22991
+ id: config2.id,
22992
+ installed,
22993
+ available: installed && Boolean(config2.headless),
22994
+ ...matchedDetectionCommand ? { matchedDetectionCommand } : {},
22995
+ ...result?.path ? { resolvedPath: result.path } : {},
22996
+ ...diagnostic.version ? { version: diagnostic.version } : {},
22997
+ ...detail ? { detail } : {}
22609
22998
  };
22610
- return [item];
22611
22999
  }));
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);
23000
+ this.snapshot = {
23001
+ providers,
23002
+ detectedIds: providers.filter((provider) => provider.installed).map((provider) => provider.id),
23003
+ addedPathSegments,
23004
+ shellHydrationOk: hydration.ok,
23005
+ pathSource: hydration.ok ? "shell_hydrated" : "process_path",
23006
+ pathFailureReason: hydration.failureReason,
23007
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
23008
+ };
23009
+ return this.snapshot;
22619
23010
  }
23011
+ };
23012
+ var cliDetection = new CliDetectionService();
23013
+
23014
+ // src/runtime/agent-runtime.ts
23015
+ import { randomUUID as randomUUID3 } from "node:crypto";
23016
+ import { join as join15 } from "node:path";
23017
+
23018
+ // src/exec/script-runner.ts
23019
+ import { spawn as spawn7 } from "node:child_process";
23020
+
23021
+ // src/runs/process-tree.ts
23022
+ var KILL_GRACE_MS = 3e3;
23023
+ async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
23024
+ if (!Number.isInteger(rootPid) || rootPid <= 1) return;
23025
+ await currentPlatform.killProcessTree(rootPid, graceMs);
22620
23026
  }
22621
23027
 
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("/", "-")}`;
23028
+ // src/exec/script-runner.ts
23029
+ var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
23030
+ function executeScript(command, workdir, timeoutSeconds) {
23031
+ return new Promise((resolveExecution) => {
23032
+ const ownGroup = currentPlatform.runsInOwnProcessGroup;
23033
+ const { executable, args } = currentPlatform.scriptShell(command);
23034
+ const startedAt = Date.now();
23035
+ const stdout = [];
23036
+ const stderr = [];
23037
+ let stdoutBytes = 0;
23038
+ let stderrBytes = 0;
23039
+ let outputTruncated = false;
23040
+ let timedOut = false;
23041
+ let spawnError = "";
23042
+ let settled = false;
23043
+ const append = (target, chunk, currentBytes) => {
23044
+ const remaining = MAX_SCRIPT_OUTPUT_BYTES - currentBytes;
23045
+ if (remaining <= 0) {
23046
+ outputTruncated = true;
23047
+ return currentBytes;
23048
+ }
23049
+ if (chunk.length > remaining) {
23050
+ target.push(chunk.subarray(0, remaining));
23051
+ outputTruncated = true;
23052
+ return MAX_SCRIPT_OUTPUT_BYTES;
23053
+ }
23054
+ target.push(chunk);
23055
+ return currentBytes + chunk.length;
23056
+ };
23057
+ let child;
23058
+ try {
23059
+ child = spawn7(executable, args, {
23060
+ cwd: workdir,
23061
+ env: process.env,
23062
+ detached: ownGroup,
23063
+ shell: false,
23064
+ windowsHide: true,
23065
+ stdio: ["ignore", "pipe", "pipe"]
23066
+ });
23067
+ } catch (error62) {
23068
+ resolveExecution({
23069
+ exitCode: -1,
23070
+ stdout: "",
23071
+ stderr: error62 instanceof Error ? error62.message : String(error62),
23072
+ durationMs: Date.now() - startedAt,
23073
+ outputTruncated: false,
23074
+ timedOut: false
23075
+ });
23076
+ return;
22642
23077
  }
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) } : {}
23078
+ const kill = () => {
23079
+ if (child.exitCode !== null || child.killed) return;
23080
+ try {
23081
+ if (ownGroup && child.pid) process.kill(-child.pid, "SIGKILL");
23082
+ else if (child.pid) void killProcessTree(child.pid, 0);
23083
+ else child.kill("SIGKILL");
23084
+ } catch {
23085
+ try {
23086
+ child.kill("SIGKILL");
23087
+ } catch {
23088
+ }
23089
+ }
23090
+ };
23091
+ const timeout = setTimeout(() => {
23092
+ timedOut = true;
23093
+ kill();
23094
+ }, timeoutSeconds * 1e3);
23095
+ child.stdout.on("data", (chunk) => {
23096
+ stdoutBytes = append(stdout, Buffer.from(chunk), stdoutBytes);
22678
23097
  });
22679
- }
22680
- return windows;
23098
+ child.stderr.on("data", (chunk) => {
23099
+ stderrBytes = append(stderr, Buffer.from(chunk), stderrBytes);
23100
+ });
23101
+ child.once("error", (error62) => {
23102
+ spawnError = error62.message;
23103
+ });
23104
+ child.once("close", (code) => {
23105
+ if (settled) return;
23106
+ settled = true;
23107
+ clearTimeout(timeout);
23108
+ let stderrText = Buffer.concat(stderr).toString("utf8");
23109
+ if (spawnError) stderrText = `${stderrText}${stderrText ? "\n" : ""}${spawnError}`;
23110
+ if (timedOut) {
23111
+ stderrText = `${stderrText}${stderrText ? "\n" : ""}Command timed out after ${timeoutSeconds} seconds.`;
23112
+ }
23113
+ if (outputTruncated) {
23114
+ stderrText = `${stderrText}${stderrText ? "\n" : ""}[Output truncated to 112 KiB per stream.]`;
23115
+ }
23116
+ resolveExecution({
23117
+ exitCode: timedOut || spawnError ? -1 : code ?? -1,
23118
+ stdout: Buffer.concat(stdout).toString("utf8"),
23119
+ stderr: stderrText,
23120
+ durationMs: Date.now() - startedAt,
23121
+ outputTruncated,
23122
+ timedOut
23123
+ });
23124
+ });
23125
+ });
22681
23126
  }
22682
- async function readKiroQuotaWindows() {
22683
- const launch = resolveExecutable("kiro-cli", ["chat", "--no-interactive", "/usage"], providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
23127
+
23128
+ // src/providers/chat/index.ts
23129
+ function resolveChatProvider(type, request, attachments) {
23130
+ const chat = catalogEntry(type)?.chat;
23131
+ if (!chat) throw new Error(`\u6B64 CLI \u7684\u5B9E\u65F6\u804A\u5929\u9A71\u52A8\u5C1A\u672A\u542F\u7528\uFF1A${type}`);
23132
+ return chat(request, attachments);
23133
+ }
23134
+
23135
+ // src/providers/model-catalog-collector.ts
23136
+ import { createHash } from "node:crypto";
23137
+ import { stat as stat2 } from "node:fs/promises";
23138
+ async function fileStamp(path) {
22684
23139
  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");
23140
+ const info = await stat2(path);
23141
+ return `${path}:${info.mtimeMs}:${info.size}`;
23142
+ } catch {
23143
+ return `${path}:-`;
22691
23144
  }
22692
23145
  }
23146
+ function reportHash(items) {
23147
+ const stable = items.map((item) => ({
23148
+ agent_type: item.agent_type,
23149
+ error: item.error ?? "",
23150
+ ...item.catalog ? { catalog: { ...item.catalog, fetched_at: "" } } : {}
23151
+ }));
23152
+ return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
23153
+ }
23154
+ var ModelCatalogCollector = class {
23155
+ constructor(sources = modelSources()) {
23156
+ this.sources = sources;
23157
+ }
23158
+ sources;
23159
+ cache = /* @__PURE__ */ new Map();
23160
+ /** CLI ids that have a model source, among the detected ones. */
23161
+ supported(detectedIds) {
23162
+ return [...new Set(detectedIds.map((id) => catalogEntry(id)?.id ?? id))].filter((id) => id in this.sources).sort();
23163
+ }
23164
+ async collect(detectedIds, options = {}) {
23165
+ const ids = this.supported(detectedIds);
23166
+ const items = await Promise.all(ids.map((id) => this.readOne(id, Boolean(options.force && (!options.only || options.only === id)))));
23167
+ return { hash: reportHash(items), items };
23168
+ }
23169
+ async readOne(id, force) {
23170
+ const source = this.sources[id];
23171
+ const now = Date.now();
23172
+ const stamps = await Promise.all(source.watchFiles().map(fileStamp));
23173
+ const fingerprint = stamps.join("|");
23174
+ const cached3 = this.cache.get(id);
23175
+ const expired = source.refreshEveryMs !== void 0 && cached3 !== void 0 && now - cached3.readAt >= source.refreshEveryMs;
23176
+ if (cached3 && !force && !expired && cached3.fingerprint === fingerprint) return cached3.item;
23177
+ let item;
23178
+ try {
23179
+ const catalog = await source.read();
23180
+ item = { agent_type: id, catalog: { ...catalog, agent_type: id } };
23181
+ } catch (error62) {
23182
+ item = { agent_type: id, error: error62 instanceof Error ? error62.message : String(error62) };
23183
+ }
23184
+ this.cache.set(id, { fingerprint, readAt: now, item });
23185
+ return item;
23186
+ }
23187
+ };
22693
23188
 
22694
23189
  // src/providers/quota-reader.ts
22695
- var quotaReaders = {
22696
- codex: readCodexQuotaWindows,
22697
- kiro: readKiroQuotaWindows
22698
- };
22699
23190
  async function readCLIQuotaReport(agentType) {
22700
- const provider = agentType.trim().toLowerCase();
22701
- const read = quotaReaders[provider];
23191
+ const entry = catalogEntry(agentType);
23192
+ const provider = entry?.id ?? agentType.trim().toLowerCase();
23193
+ const read = entry?.quota;
22702
23194
  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
23195
  const quotaWindows = await read();
22704
23196
  const now = Math.floor(Date.now() / 1e3);
@@ -22832,8 +23324,8 @@ var OrphanRegistry = class {
22832
23324
  file;
22833
23325
  records = /* @__PURE__ */ new Map();
22834
23326
  writing = Promise.resolve();
22835
- add(record4) {
22836
- this.records.set(record4.runId, record4);
23327
+ add(record5) {
23328
+ this.records.set(record5.runId, record5);
22837
23329
  this.persist();
22838
23330
  }
22839
23331
  remove(runId) {
@@ -22857,12 +23349,12 @@ var OrphanRegistry = class {
22857
23349
  return [];
22858
23350
  }
22859
23351
  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);
23352
+ for (const record5 of previous) {
23353
+ if (!record5 || typeof record5.pid !== "number" || record5.pid <= 1) continue;
23354
+ const command = await commandOf(record5.pid);
23355
+ if (command && command.includes(basename(record5.executable))) {
23356
+ await killProcessTree(record5.pid);
23357
+ reaped.push(record5);
22866
23358
  }
22867
23359
  }
22868
23360
  this.records.clear();
@@ -22876,10 +23368,10 @@ function commandOf(pid) {
22876
23368
  }
22877
23369
 
22878
23370
  // src/runs/run-supervisor.ts
22879
- import { spawn as spawn8 } from "node:child_process";
23371
+ import { spawn as spawn9 } from "node:child_process";
22880
23372
  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";
22882
- import { createInterface as createInterface3 } from "node:readline";
23373
+ import { basename as basename3, isAbsolute as isAbsolute3, join as join13, relative as relative2, resolve as resolve3 } from "node:path";
23374
+ import { createInterface as createInterface4 } from "node:readline";
22883
23375
 
22884
23376
  // src/session/terminal-line-sanitizer.ts
22885
23377
  var TERMINAL_ESCAPE = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
@@ -23001,11 +23493,293 @@ function clipToCharacterBudget(rows, budget) {
23001
23493
  return { lines: rows, limited: false };
23002
23494
  }
23003
23495
 
23496
+ // src/providers/chat/codex-goal.ts
23497
+ var GOAL_IDLE_END_MS = 18e4;
23498
+ var GOAL_STATUSES = /* @__PURE__ */ new Set(["active", "paused", "blocked", "usageLimited", "budgetLimited", "complete"]);
23499
+ function codexGoalProvider(request, goal) {
23500
+ let write;
23501
+ let threadId = request.sessionId;
23502
+ let nextId = 10;
23503
+ let turnRunning = false;
23504
+ let currentTurn = "";
23505
+ let turnMessage = "";
23506
+ let goalStatus = "active";
23507
+ let goalSet = false;
23508
+ let ended = false;
23509
+ let idleSince = 0;
23510
+ const send = (message) => write?.(`${JSON.stringify(message)}
23511
+ `);
23512
+ const sandboxPolicy = request.permissionMode === "full" ? { type: "dangerFullAccess" } : { type: "readOnly", access: { type: "restricted", includePlatformDefaults: true, readableRoots: [request.workdir] } };
23513
+ const empty = () => ({ display: [] });
23514
+ const end = (rows = []) => {
23515
+ if (ended) return { display: rows };
23516
+ ended = true;
23517
+ return { display: [...rows, runLog.event("\u76EE\u6807\u8FD0\u884C\u7ED3\u675F")], turnCompleted: true, endProcess: true };
23518
+ };
23519
+ const maybeEnd = (rows = []) => {
23520
+ if (!turnRunning && goalSet && goalStatus !== "active") return end(rows);
23521
+ return { display: rows };
23522
+ };
23523
+ const snapshot = (value) => {
23524
+ const status = str(value.status);
23525
+ if (!status || !GOAL_STATUSES.has(status)) return void 0;
23526
+ return {
23527
+ objective: String(value.objective ?? ""),
23528
+ status,
23529
+ ...typeof value.tokenBudget === "number" ? { token_budget: value.tokenBudget } : {},
23530
+ tokens_used: typeof value.tokensUsed === "number" ? value.tokensUsed : 0,
23531
+ time_used_seconds: typeof value.timeUsedSeconds === "number" ? value.timeUsedSeconds : 0
23532
+ };
23533
+ };
23534
+ const startTurn = () => {
23535
+ send({ id: 3, method: "turn/start", params: {
23536
+ threadId,
23537
+ input: [{ type: "text", text: request.prompt }],
23538
+ cwd: request.workdir,
23539
+ approvalPolicy: "never",
23540
+ sandboxPolicy,
23541
+ ...request.model ? { model: request.model } : {},
23542
+ ...request.reasoningEffort ? { effort: request.reasoningEffort } : {}
23543
+ } });
23544
+ };
23545
+ const setGoal = () => {
23546
+ send({ id: 4, method: "thread/goal/set", params: {
23547
+ threadId,
23548
+ objective: goal.objective,
23549
+ status: "active",
23550
+ origin: "user",
23551
+ ...goal.tokenBudget ? { tokenBudget: goal.tokenBudget } : {}
23552
+ } });
23553
+ };
23554
+ return {
23555
+ id: "codex",
23556
+ buildLaunch() {
23557
+ return launchCli({ spec: requireCliSpec("codex"), args: [
23558
+ "app-server",
23559
+ "--listen",
23560
+ "stdio://",
23561
+ ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"']
23562
+ ] });
23563
+ },
23564
+ startInput(writer) {
23565
+ write = writer;
23566
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "echo_goal", title: "Echo Goal", version: "1.0" }, capabilities: { experimentalApi: true } } });
23567
+ },
23568
+ tick() {
23569
+ if (!ended && !turnRunning && goalSet && idleSince && Date.now() - idleSince > GOAL_IDLE_END_MS) {
23570
+ return end([runLog.event("\u76EE\u6807\u957F\u65F6\u95F4\u6CA1\u6709\u7EE7\u7EED\uFF0C\u5DF2\u7ED3\u675F\u672C\u6B21\u8FD0\u884C")]);
23571
+ }
23572
+ return void 0;
23573
+ },
23574
+ controlGoal(action) {
23575
+ if (!write || !threadId || ended) return false;
23576
+ if (action === "pause") send({ id: nextId++, method: "thread/goal/set", params: { threadId, status: "paused", origin: "user" } });
23577
+ else send({ id: nextId++, method: "thread/goal/clear", params: { threadId, origin: "user" } });
23578
+ return true;
23579
+ },
23580
+ parseLine(line) {
23581
+ const message = tryJson(line);
23582
+ if (!message) return empty();
23583
+ if (message.id !== void 0 && !message.method) {
23584
+ const error62 = message.error;
23585
+ if (error62) {
23586
+ if (message.id === 4) return { display: [runLog.error(`\u8BBE\u7F6E\u76EE\u6807\u5931\u8D25\uFF1A${str(error62.message) ?? ""}`)], turnError: str(error62.message) ?? "\u8BBE\u7F6E\u76EE\u6807\u5931\u8D25", endProcess: true };
23587
+ if (typeof message.id === "number" && message.id < 10) return { display: [], turnError: str(error62.message) ?? "Codex \u8BF7\u6C42\u5931\u8D25", endProcess: true };
23588
+ return { display: [runLog.error(str(error62.message) ?? "\u76EE\u6807\u64CD\u4F5C\u5931\u8D25")] };
23589
+ }
23590
+ const result = message.result ?? {};
23591
+ if (message.id === 1) {
23592
+ send({ method: "initialized" });
23593
+ send({ id: 2, method: threadId ? "thread/resume" : "thread/start", params: {
23594
+ cwd: request.workdir,
23595
+ approvalPolicy: "never",
23596
+ sandbox: request.permissionMode === "full" ? "danger-full-access" : "read-only",
23597
+ ...request.model ? { model: request.model } : {},
23598
+ ...threadId ? { threadId } : { ephemeral: false }
23599
+ } });
23600
+ return empty();
23601
+ }
23602
+ if (message.id === 2) {
23603
+ const id = str((result.thread ?? {}).id);
23604
+ if (!id) return { display: [], turnError: "Codex \u672A\u8FD4\u56DE\u539F\u751F\u4F1A\u8BDD ID", endProcess: true };
23605
+ threadId = id;
23606
+ startTurn();
23607
+ return { display: [runLog.event(`\u4F1A\u8BDD ${id}`)], sessionId: id };
23608
+ }
23609
+ if (message.id === 3) {
23610
+ setGoal();
23611
+ return empty();
23612
+ }
23613
+ if (message.id === 4) {
23614
+ goalSet = true;
23615
+ const goalSnapshot = snapshot(result.goal ?? {});
23616
+ if (goalSnapshot) goalStatus = goalSnapshot.status;
23617
+ return { display: [runLog.event(`\u76EE\u6807\uFF1A${goal.objective}`)], ...goalSnapshot ? { goal: goalSnapshot } : {} };
23618
+ }
23619
+ return empty();
23620
+ }
23621
+ const params = message.params ?? {};
23622
+ if (params.threadId && params.threadId !== threadId) return empty();
23623
+ if (message.id !== void 0) {
23624
+ send({ id: message.id, error: { code: -32601, message: "\u76EE\u6807\u8FD0\u884C\u4E0D\u652F\u6301\u4EA4\u4E92\u5F0F\u786E\u8BA4" } });
23625
+ return { display: [runLog.error("CLI \u8BF7\u6C42\u4EA4\u4E92\u786E\u8BA4\uFF0C\u76EE\u6807\u8FD0\u884C\u65E0\u6CD5\u56DE\u7B54\uFF0C\u5DF2\u62D2\u7EDD")] };
23626
+ }
23627
+ switch (message.method) {
23628
+ case "turn/started": {
23629
+ turnRunning = true;
23630
+ idleSince = 0;
23631
+ currentTurn = str((params.turn ?? {}).id) ?? currentTurn;
23632
+ turnMessage = "";
23633
+ return { display: [runLog.event("\u5F00\u59CB\u5904\u7406")] };
23634
+ }
23635
+ case "item/completed": {
23636
+ const item = params.item ?? {};
23637
+ if (item.type === "agentMessage") {
23638
+ turnMessage = String(item.text ?? "");
23639
+ return { display: textRows("\u203A ", turnMessage), message: turnMessage };
23640
+ }
23641
+ if (item.type === "commandExecution") return { display: [runLog.command(String(item.command ?? "")), runLog.commandExit(typeof item.exitCode === "number" ? item.exitCode : void 0)] };
23642
+ if (item.type === "fileChange") return { display: [runLog.fileChange()] };
23643
+ return empty();
23644
+ }
23645
+ case "turn/completed": {
23646
+ turnRunning = false;
23647
+ idleSince = Date.now();
23648
+ const turn = params.turn ?? {};
23649
+ const id = str(turn.id) ?? currentTurn;
23650
+ const rows = [runLog.event(turn.status === "completed" ? "\u672C\u8F6E\u5B8C\u6210" : `\u672C\u8F6E\u7ED3\u675F\uFF08${String(turn.status ?? "")}\uFF09`)];
23651
+ const parsed = maybeEnd(rows);
23652
+ return { ...parsed, ...id && turnMessage ? { goalTurn: { turnId: id, message: turnMessage } } : {} };
23653
+ }
23654
+ case "thread/goal/updated": {
23655
+ const goalSnapshot = snapshot(params.goal ?? {});
23656
+ if (!goalSnapshot) return empty();
23657
+ goalStatus = goalSnapshot.status;
23658
+ return { ...maybeEnd(goalSnapshot.status === "active" ? [] : [runLog.event(`\u76EE\u6807\u72B6\u6001\uFF1A${goalSnapshot.status}`)]), goal: goalSnapshot };
23659
+ }
23660
+ case "thread/goal/cleared": {
23661
+ goalStatus = "cleared";
23662
+ return { ...maybeEnd([runLog.event("\u76EE\u6807\u5DF2\u6E05\u9664")]), goal: { objective: "", status: "paused", tokens_used: 0, time_used_seconds: 0, cleared: true } };
23663
+ }
23664
+ default:
23665
+ return empty();
23666
+ }
23667
+ }
23668
+ };
23669
+ }
23670
+
23671
+ // src/providers/cli/codex-fork.ts
23672
+ import { spawn as spawn8 } from "node:child_process";
23673
+ import { createInterface as createInterface3 } from "node:readline";
23674
+ var FORK_TIMEOUT_MS = 9e4;
23675
+ async function forkCodexThread(options) {
23676
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--listen", "stdio://"] });
23677
+ const child = spawn8(launch.executable, launch.args, {
23678
+ cwd: options.workdir,
23679
+ env: launch.env,
23680
+ shell: false,
23681
+ windowsHide: true,
23682
+ detached: currentPlatform.runsInOwnProcessGroup,
23683
+ stdio: ["pipe", "pipe", "pipe"]
23684
+ });
23685
+ const stderr = [];
23686
+ createInterface3({ input: child.stderr }).on("line", (line) => {
23687
+ stderr.push(line);
23688
+ if (stderr.length > 20) stderr.shift();
23689
+ });
23690
+ let nextId = 1;
23691
+ const pending = /* @__PURE__ */ new Map();
23692
+ const call = (method, params) => new Promise((resolve7, reject) => {
23693
+ const id = nextId++;
23694
+ pending.set(id, { resolve: resolve7, reject });
23695
+ child.stdin.write(`${JSON.stringify({ id, method, params })}
23696
+ `);
23697
+ });
23698
+ createInterface3({ input: child.stdout }).on("line", (line) => {
23699
+ const message = tryJson(line);
23700
+ if (!message || typeof message.id !== "number" || message.method) return;
23701
+ const waiter = pending.get(message.id);
23702
+ if (!waiter) return;
23703
+ pending.delete(message.id);
23704
+ const error62 = message.error;
23705
+ if (error62) waiter.reject(new Error(String(error62.message ?? "Codex \u8BF7\u6C42\u5931\u8D25")));
23706
+ else waiter.resolve(message.result ?? {});
23707
+ });
23708
+ const failed = new Promise((_, reject) => {
23709
+ child.once("error", (error62) => reject(new Error(`\u65E0\u6CD5\u542F\u52A8 Codex\uFF1A${error62.message}`)));
23710
+ child.once("exit", (code) => reject(new Error(`Codex \u5DF2\u9000\u51FA\uFF08exit ${code ?? "?"}\uFF09${stderr.length ? `\uFF1A${stderr.slice(-3).join(" ")}` : ""}`)));
23711
+ });
23712
+ const timer = setTimeout(() => {
23713
+ void killProcessTree(child.pid ?? 0);
23714
+ }, FORK_TIMEOUT_MS);
23715
+ try {
23716
+ const run = async () => {
23717
+ await call("initialize", { clientInfo: { name: "echo_session_fork", title: "Echo Session Fork", version: "1.0" }, capabilities: { experimentalApi: true } });
23718
+ child.stdin.write(`${JSON.stringify({ method: "initialized" })}
23719
+ `);
23720
+ let lastTurnId;
23721
+ if (options.keepTurns > 0) {
23722
+ const ids = [];
23723
+ let cursor;
23724
+ do {
23725
+ const page = await call("thread/turns/list", { threadId: options.sourceThreadId, sortDirection: "asc", limit: 100, ...cursor ? { cursor } : {} });
23726
+ for (const turn of page.data ?? []) if (typeof turn.id === "string") ids.push(turn.id);
23727
+ cursor = typeof page.nextCursor === "string" ? page.nextCursor : void 0;
23728
+ } while (cursor && ids.length < options.keepTurns);
23729
+ if (ids.length > options.keepTurns) lastTurnId = ids[options.keepTurns - 1];
23730
+ }
23731
+ const result = await call("thread/fork", {
23732
+ threadId: options.sourceThreadId,
23733
+ ephemeral: false,
23734
+ excludeTurns: true,
23735
+ cwd: options.workdir,
23736
+ ...lastTurnId ? { lastTurnId } : {}
23737
+ });
23738
+ const thread = result.thread ?? {};
23739
+ if (typeof thread.id !== "string" || !thread.id) throw new Error("Codex \u672A\u8FD4\u56DE\u5206\u53C9\u540E\u7684\u4F1A\u8BDD ID");
23740
+ return thread.id;
23741
+ };
23742
+ return await Promise.race([run(), failed]);
23743
+ } finally {
23744
+ clearTimeout(timer);
23745
+ child.stdin?.end();
23746
+ void killProcessTree(child.pid ?? 0, 1e3);
23747
+ }
23748
+ }
23749
+
23750
+ // src/runs/run-recorder.ts
23751
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3 } from "node:fs";
23752
+ import { homedir as homedir8 } from "node:os";
23753
+ import { join as join11 } from "node:path";
23754
+ var RunRecorder = class _RunRecorder {
23755
+ constructor(path) {
23756
+ this.path = path;
23757
+ }
23758
+ path;
23759
+ home = homedir8();
23760
+ static fromEnvironment(runId, meta3) {
23761
+ const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
23762
+ if (!directory) return void 0;
23763
+ mkdirSync3(directory, { recursive: true });
23764
+ const recorder = new _RunRecorder(join11(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
23765
+ recorder.write({ meta: meta3 });
23766
+ return recorder;
23767
+ }
23768
+ write(frame) {
23769
+ const line = JSON.stringify(frame).split(this.home).join("~");
23770
+ try {
23771
+ appendFileSync2(this.path, `${line}
23772
+ `, { mode: 384 });
23773
+ } catch {
23774
+ }
23775
+ }
23776
+ };
23777
+
23004
23778
  // src/runs/task-attachments.ts
23005
23779
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
23006
23780
  import { constants as constants2 } from "node:fs";
23007
23781
  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";
23782
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join12, relative } from "node:path";
23009
23783
  function within(root, path) {
23010
23784
  const segment = relative(root, path);
23011
23785
  return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
@@ -23013,7 +23787,7 @@ function within(root, path) {
23013
23787
  async function attachmentDirectory(workdir, messageId) {
23014
23788
  let directory = workdir;
23015
23789
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
23016
- directory = join11(directory, segment);
23790
+ directory = join12(directory, segment);
23017
23791
  await mkdir4(directory, { mode: 448 }).catch((error62) => {
23018
23792
  if (error62.code !== "EEXIST") throw error62;
23019
23793
  });
@@ -23021,7 +23795,7 @@ async function attachmentDirectory(workdir, messageId) {
23021
23795
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
23022
23796
  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
23797
  }
23024
- if (segment === ".echo") await writeFile4(join11(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
23798
+ if (segment === ".echo") await writeFile4(join12(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
23025
23799
  if (error62.code !== "EEXIST") throw error62;
23026
23800
  });
23027
23801
  }
@@ -23058,9 +23832,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
23058
23832
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
23059
23833
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
23060
23834
  const name = characters.join("") || "attachment";
23061
- const path = join11(directory, `${file2.file_id}-${name}`);
23835
+ const path = join12(directory, `${file2.file_id}-${name}`);
23062
23836
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
23063
- const temporary = join11(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
23837
+ const temporary = join12(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
23064
23838
  try {
23065
23839
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
23066
23840
  signal2.throwIfAborted();
@@ -23089,6 +23863,7 @@ var EXIT_OUTPUT_GRACE_MS = 2e3;
23089
23863
  var RECENT_RUN_TTL_MS = 10 * 6e4;
23090
23864
  var MAX_RECENT_RUNS = 100;
23091
23865
  var MAX_ERROR_ROWS = 40;
23866
+ var SESSION_START_TIMEOUT_MS = 12e4;
23092
23867
  var STALL_CHECK_INTERVAL_MS = 5e3;
23093
23868
  function rowCategory(row) {
23094
23869
  switch (row.trimStart().charAt(0)) {
@@ -23158,18 +23933,28 @@ var RunSupervisor = class {
23158
23933
  this.chatRunIds.delete(runId);
23159
23934
  }
23160
23935
  recentRuns() {
23161
- const running = [...this.active.values()].map((run) => ({ runId: run.runId, workstationId: run.workstationId, status: "running", at: run.startedAt }));
23162
- const done = [...this.recent.values()].map((run) => ({ runId: run.runId, workstationId: run.workstationId, status: run.status, at: run.finishedAt }));
23936
+ const running = [...this.active.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: "running", at: run.startedAt }));
23937
+ const done = [...this.recent.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: run.status, at: run.finishedAt }));
23163
23938
  return [...running, ...done].sort((a, b) => b.at - a.at).slice(0, 30);
23164
23939
  }
23165
23940
  /**
23166
- * Starts a turn. Refusals (busy workstation, concurrency limit, bad work
23941
+ * Starts a turn. Refusals (busy session, concurrency limit, bad work
23167
23942
  * directory, unknown CLI) are reported as a failed run, never thrown.
23168
23943
  */
23944
+ /**
23945
+ * Different sessions run in parallel without a machine-wide cap by
23946
+ * default; each session still runs one turn at a time. A cap applies
23947
+ * only when the operator sets TOC_OCRA_MAX_RUNS / maxConcurrentRuns.
23948
+ * The run being started is already counted in `preparing`.
23949
+ */
23950
+ overConcurrencyCap() {
23951
+ const cap = this.config.maxConcurrentRuns;
23952
+ return cap > 0 && this.active.size + this.preparing.size > cap;
23953
+ }
23169
23954
  async start(payload) {
23170
23955
  if (this.preparing.has(payload.run_id)) return;
23171
23956
  const controller = new AbortController();
23172
- this.preparing.set(payload.run_id, { workstationId: payload.workstation_id, controller });
23957
+ this.preparing.set(payload.run_id, { sessionKey: sessionKeyOf(payload), controller });
23173
23958
  try {
23174
23959
  await this.startPrepared(payload, controller.signal);
23175
23960
  } finally {
@@ -23182,25 +23967,28 @@ var RunSupervisor = class {
23182
23967
  return;
23183
23968
  }
23184
23969
  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 });
23187
- 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 });
23970
+ const sessionKey = sessionKeyOf(payload);
23971
+ const refuse = async (reason) => {
23972
+ const failure2 = typeof reason === "string" ? { kind: "hostFault", message: reason } : reason;
23973
+ this.logger.warn("run-refused", { runId: payload.run_id, error: failure2.message, kind: failure2.kind });
23974
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "failed", chat: !!payload.chat_session_id });
23975
+ await this.report(payload.run_id, { status: "failed", error: failure2.message, failure_kind: failure2.kind, duration_ms: 0 });
23189
23976
  };
23190
- 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
- return refuse("\u672C\u673A\u8BE5\u5DE5\u4F4D\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
23977
+ if ([...this.active.values()].some((run2) => run2.sessionKey === sessionKey) || [...this.preparing].some(([id, run2]) => id !== payload.run_id && run2.sessionKey === sessionKey)) {
23978
+ return refuse("\u672C\u673A\u8BE5\u4F1A\u8BDD\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
23192
23979
  }
23193
- if (this.active.size + this.preparing.size > this.config.maxConcurrentRuns) {
23980
+ if (this.overConcurrencyCap()) {
23194
23981
  return refuse(`\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650\uFF08${this.config.maxConcurrentRuns}\uFF09`);
23195
23982
  }
23196
23983
  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
23984
  const permissionMode = payload.cli_policy.mode;
23199
- let provider;
23985
+ const runnable = resolveRunnableCli(payload.agent_type, { chat: Boolean(payload.chat_session_id), permissionMode });
23986
+ if ("failure" in runnable) return refuse(runnable.failure);
23987
+ const cli = runnable.entry;
23988
+ let provider = cli.headless;
23200
23989
  let workdir;
23201
23990
  try {
23202
- provider = resolveHeadlessProvider(payload.agent_type);
23203
- 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");
23991
+ if (payload.task_attachments?.length && !payload.workdir) throw new Error("\u9644\u4EF6\u9700\u8981\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u4F1A\u8BDD\u5DE5\u4F5C\u76EE\u5F55");
23204
23992
  workdir = payload.chat_session_id && !payload.workdir ? await this.defaultChatWorkdir() : await this.validateWorkdir(payload.workdir || this.config.allowedRoots[0]);
23205
23993
  } catch (error62) {
23206
23994
  return refuse(errorMessage(error62));
@@ -23210,7 +23998,7 @@ var RunSupervisor = class {
23210
23998
  signal2.throwIfAborted();
23211
23999
  } catch (error62) {
23212
24000
  if (signal2.aborted) {
23213
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "cancelled", chat: !!payload.chat_session_id });
24001
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "cancelled", chat: !!payload.chat_session_id });
23214
24002
  await this.report(payload.run_id, { status: "cancelled", error: "\u9644\u4EF6\u51C6\u5907\u5DF2\u53D6\u6D88", duration_ms: 0 });
23215
24003
  return;
23216
24004
  }
@@ -23233,11 +24021,11 @@ var RunSupervisor = class {
23233
24021
  return refuse(errorMessage(error62));
23234
24022
  }
23235
24023
  }
24024
+ if (!provider) return refuse(cliFailure("cliUnsupported", { label: cli.label }));
23236
24025
  if (!payload.prompt && !payload.attachments?.length) return refuse("\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A");
23237
24026
  let sessionId = payload.session_id;
23238
24027
  let sessionsBefore;
23239
24028
  let sessionNote = "";
23240
- let unverifiedResume = false;
23241
24029
  if (!payload.chat_session_id && provider.listSessions) {
23242
24030
  let saved;
23243
24031
  let listError = "";
@@ -23249,7 +24037,6 @@ var RunSupervisor = class {
23249
24037
  if (!saved) {
23250
24038
  this.logger.warn("list-sessions-failed", { runId: payload.run_id, agentType: provider.id, error: listError });
23251
24039
  if (sessionId) {
23252
- unverifiedResume = true;
23253
24040
  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
24041
  `;
23255
24042
  } else {
@@ -23265,20 +24052,39 @@ var RunSupervisor = class {
23265
24052
  sessionsBefore = new Set(saved.map((session) => session.id));
23266
24053
  }
23267
24054
  }
23268
- 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");
24055
+ const fork = payload.fork && !payload.chat_session_id ? { sourceSessionId: payload.fork.source_session_id, keepTurns: payload.fork.keep_turns } : void 0;
24056
+ if (fork && provider.id === "codex" && !sessionId) {
24057
+ try {
24058
+ sessionId = await forkCodexThread({ sourceThreadId: fork.sourceSessionId, keepTurns: fork.keepTurns, workdir, permissionMode });
24059
+ sessionNote += `\u25CF \u5DF2\u4ECE\u4F1A\u8BDD ${fork.sourceSessionId} \u5206\u53C9${fork.keepTurns > 0 ? `\uFF08\u4FDD\u7559\u524D ${fork.keepTurns} \u8F6E\uFF09` : ""}\uFF0C\u65B0\u4F1A\u8BDD ${sessionId}
24060
+ `;
24061
+ } catch (error62) {
24062
+ return refuse({ kind: "startFailed", message: `\u5206\u53C9 Codex \u4F1A\u8BDD\u5931\u8D25\uFF1A${errorMessage(error62)}` });
24063
+ }
24064
+ }
24065
+ if (payload.goal && !payload.chat_session_id) {
24066
+ if (provider.id !== "codex") return refuse("\u76EE\u6807\u6A21\u5F0F\u53EA\u652F\u6301 Codex");
24067
+ provider = codexGoalProvider(
24068
+ { permissionMode, prompt: payload.prompt, sessionId, model: payload.model, reasoningEffort: payload.reasoning_effort, workdir },
24069
+ { objective: payload.goal.objective, ...payload.goal.token_budget ? { tokenBudget: payload.goal.token_budget } : {} }
24070
+ );
24071
+ }
24072
+ if ([...this.active.values()].some((run2) => run2.sessionKey === sessionKey)) return refuse("\u672C\u673A\u8BE5\u4F1A\u8BDD\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
24073
+ if (this.overConcurrencyCap()) return refuse(`\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650\uFF08${this.config.maxConcurrentRuns}\uFF09`);
24074
+ if (provider.forTurn) provider = provider.forTurn();
23270
24075
  const launch = provider.buildLaunch({
23271
24076
  permissionMode,
23272
24077
  prompt: payload.prompt,
23273
24078
  sessionId,
23274
24079
  model: payload.model,
23275
24080
  reasoningEffort: payload.reasoning_effort,
23276
- workdir
24081
+ workdir,
24082
+ ...fork ? { fork } : {}
23277
24083
  });
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`);
24084
+ if (!fitsCommandLine(launch)) return refuse(cliFailure("promptTooLong", { label: cli.label }));
23279
24085
  let child;
23280
24086
  try {
23281
- child = spawn8(launch.executable, launch.args, {
24087
+ child = spawn9(launch.executable, launch.args, {
23282
24088
  cwd: workdir,
23283
24089
  env: launch.env,
23284
24090
  detached: currentPlatform.runsInOwnProcessGroup,
@@ -23287,7 +24093,7 @@ var RunSupervisor = class {
23287
24093
  stdio: [provider.startInput || launch.stdin !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
23288
24094
  });
23289
24095
  } catch (error62) {
23290
- return refuse(`\u65E0\u6CD5\u542F\u52A8 ${provider.id}\uFF1A${errorMessage(error62)}`);
24096
+ return refuse(classifySpawnError(errorMessage(error62), cli));
23291
24097
  }
23292
24098
  const run = {
23293
24099
  chat: Boolean(payload.chat_session_id),
@@ -23299,12 +24105,13 @@ var RunSupervisor = class {
23299
24105
  queuedBytes: 0,
23300
24106
  forwardingFailed: false,
23301
24107
  runId: payload.run_id,
23302
- workstationId: payload.workstation_id,
24108
+ sessionKey,
23303
24109
  agentType: provider.id,
24110
+ cli: { label: cli.label, ...cli.installHint ? { installHint: cli.installHint } : {} },
23304
24111
  provider,
23305
24112
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
23306
24113
  ...sessionsBefore ? { sessionsBefore } : {},
23307
- ...unverifiedResume ? { unverifiedResume: payload } : {},
24114
+ ...sessionId && !payload.chat_session_id ? { resumeRetry: payload } : {},
23308
24115
  prompt: payload.prompt,
23309
24116
  child,
23310
24117
  pid: child.pid ?? 0,
@@ -23320,7 +24127,8 @@ var RunSupervisor = class {
23320
24127
  timedOut: false,
23321
24128
  tail: new TerminalTailBuffer(),
23322
24129
  timers: [],
23323
- ...payload.stall_policy && !payload.chat_session_id ? { stallPolicy: { idleSeconds: payload.stall_policy.idle_seconds, categorySeconds: payload.stall_policy.category_seconds ?? {} } } : {},
24130
+ // A goal run waits between turns while the CLI decides; no stall check.
24131
+ ...payload.stall_policy && !payload.chat_session_id && !payload.goal ? { stallPolicy: { idleSeconds: payload.stall_policy.idle_seconds, categorySeconds: payload.stall_policy.category_seconds ?? {} } } : {},
23324
24132
  lastCategory: "other",
23325
24133
  lastLine: "",
23326
24134
  lastOutputAt: Date.now()
@@ -23335,6 +24143,12 @@ var RunSupervisor = class {
23335
24143
  }
23336
24144
  });
23337
24145
  }
24146
+ const recorder = RunRecorder.fromEnvironment(run.runId, {
24147
+ agent: provider.id,
24148
+ args: launch.args,
24149
+ request: { session_id: sessionId, model: payload.model, reasoning_effort: payload.reasoning_effort, permission: permissionMode, prompt: payload.prompt }
24150
+ });
24151
+ if (recorder) run.recorder = recorder;
23338
24152
  this.active.set(run.runId, run);
23339
24153
  this.preparing.delete(run.runId);
23340
24154
  this.unreported.add(run.runId);
@@ -23347,17 +24161,24 @@ var RunSupervisor = class {
23347
24161
  this.logger.info("run-started", { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
23348
24162
  let spawnError = "";
23349
24163
  child.stdin?.on("error", () => void 0);
23350
- if (launch.stdin !== void 0 && !provider.startInput) child.stdin?.end(launch.stdin, "utf8");
24164
+ if (launch.stdin !== void 0 && !provider.startInput) {
24165
+ run.recorder?.write({ stream: "stdin", data: launch.stdin });
24166
+ child.stdin?.end(launch.stdin, "utf8");
24167
+ }
23351
24168
  child.once("error", (error62) => {
23352
24169
  spawnError = error62.message;
23353
24170
  });
23354
24171
  if (run.stream) {
23355
24172
  child.stdout.setEncoding("utf8");
23356
- child.stdout.on("data", (chunk) => this.applyParsed(run, run.stream.stdout(chunk), chunk));
24173
+ child.stdout.on("data", (chunk) => {
24174
+ run.recorder?.write({ stream: "stdout", data: chunk });
24175
+ this.applyParsed(run, run.stream.stdout(chunk), chunk);
24176
+ });
23357
24177
  } else {
23358
- createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
24178
+ createInterface4({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
23359
24179
  }
23360
- createInterface3({ input: child.stderr }).on("line", (line) => {
24180
+ createInterface4({ input: child.stderr }).on("line", (line) => {
24181
+ run.recorder?.write({ stream: "stderr", data: line });
23361
24182
  const clean = sanitizeTerminalLine(line);
23362
24183
  if (!clean.trim()) return;
23363
24184
  run.stderr.push(clean);
@@ -23395,27 +24216,39 @@ var RunSupervisor = class {
23395
24216
  child.once("spawn", () => {
23396
24217
  try {
23397
24218
  provider.startInput?.((message) => {
24219
+ run.recorder?.write({ stream: "stdin", data: message });
23398
24220
  child.stdin?.write(message);
23399
24221
  });
23400
24222
  } catch (error62) {
23401
24223
  run.turnError = errorMessage(error62);
24224
+ run.turnFailure = "startFailed";
23402
24225
  void killProcessTree(run.pid);
23403
24226
  }
23404
24227
  });
23405
24228
  run.timers.push(setTimeout(() => {
23406
24229
  if (!run.chatReady && this.active.has(run.runId)) {
23407
- run.turnError = "CLI \u5B9E\u65F6\u4F1A\u8BDD\u521D\u59CB\u5316\u8D85\u65F6";
24230
+ run.turnError = `${run.cli.label} \u4F1A\u8BDD\u521D\u59CB\u5316\u8D85\u65F6`;
24231
+ run.turnFailure = "startFailed";
23408
24232
  void killProcessTree(run.pid);
23409
24233
  }
23410
- }, 6e4));
24234
+ }, SESSION_START_TIMEOUT_MS));
23411
24235
  }
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
24236
+ if (this.config.maxRunSeconds > 0) {
24237
+ run.timers.push(setTimeout(() => {
24238
+ run.timedOut = true;
24239
+ run.tail.append(`\u2717 \u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${this.config.maxRunSeconds} \u79D2\uFF0C\u5DF2\u7EC8\u6B62
23416
24240
  `);
23417
- void killProcessTree(run.pid);
23418
- }, maxMs));
24241
+ void killProcessTree(run.pid);
24242
+ }, this.config.maxRunSeconds * 1e3));
24243
+ }
24244
+ if (provider.tick) {
24245
+ const ticker = setInterval(() => {
24246
+ const parsed = this.active.has(run.runId) ? run.provider.tick?.() : void 0;
24247
+ if (parsed) this.applyParsed(run, parsed, "");
24248
+ }, STALL_CHECK_INTERVAL_MS);
24249
+ ticker.unref?.();
24250
+ run.timers.push(ticker);
24251
+ }
23419
24252
  if (run.stallPolicy) {
23420
24253
  const watchdog = setInterval(() => this.checkStall(run), STALL_CHECK_INTERVAL_MS);
23421
24254
  watchdog.unref?.();
@@ -23426,13 +24259,15 @@ var RunSupervisor = class {
23426
24259
  });
23427
24260
  }
23428
24261
  onStdout(run, rawLine) {
24262
+ run.recorder?.write({ stream: "stdout", data: `${rawLine}
24263
+ ` });
23429
24264
  this.applyParsed(run, run.parse(rawLine), rawLine);
23430
24265
  }
23431
24266
  applyParsed(run, parsed, rawLine) {
23432
24267
  if (run.chat && !run.forwardingFailed) {
23433
24268
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run, sanitizeChatEvent(event));
23434
- if (parsed.sessionId) run.chatReady = true;
23435
24269
  }
24270
+ if (parsed.sessionId) run.chatReady = true;
23436
24271
  for (const row of parsed.display) {
23437
24272
  const shown = sanitizeTerminalLine(row);
23438
24273
  run.tail.append(`${shown}
@@ -23441,7 +24276,18 @@ var RunSupervisor = class {
23441
24276
  }
23442
24277
  if (!parsed.display.length && rawLine.trim()) run.lastOutputAt = Date.now();
23443
24278
  if (parsed.message !== void 0) run.finalMessage = sanitizeTerminalLine(parsed.message);
23444
- if (parsed.turnError) run.turnError = sanitizeTerminalLine(parsed.turnError);
24279
+ if (parsed.goal) {
24280
+ const goal = { ...parsed.goal, objective: sanitizeChatText(parsed.goal.objective) };
24281
+ void this.reporter.goal?.(run.runId, goal).catch((error62) => this.logger.warn("goal-report-failed", { runId: run.runId, error: errorMessage(error62) }));
24282
+ }
24283
+ if (parsed.goalTurn) {
24284
+ const turn = { turn_id: parsed.goalTurn.turnId, message: sanitizeChatText(parsed.goalTurn.message) };
24285
+ void this.reporter.goalTurn?.(run.runId, turn).catch((error62) => this.logger.warn("goal-turn-report-failed", { runId: run.runId, error: errorMessage(error62) }));
24286
+ }
24287
+ if (parsed.turnError) {
24288
+ run.turnError = sanitizeTerminalLine(parsed.turnError);
24289
+ if (parsed.failureKind) run.turnFailure = parsed.failureKind;
24290
+ }
23445
24291
  if (parsed.sessionId && parsed.sessionId !== run.sessionId) {
23446
24292
  run.sessionId = parsed.sessionId;
23447
24293
  void this.reporter.started(run.runId, { session_id: parsed.sessionId }).catch(() => void 0);
@@ -23467,30 +24313,30 @@ var RunSupervisor = class {
23467
24313
  async onExit(run, code, signal2, spawnError) {
23468
24314
  for (const timer of run.timers) clearTimeout(timer);
23469
24315
  run.timers = [];
24316
+ run.recorder?.write({ exit: code });
23470
24317
  if (run.stream) this.applyParsed(run, await run.stream.end(), "");
23471
24318
  this.active.delete(run.runId);
23472
24319
  this.orphans?.remove(run.runId);
23473
24320
  if (run.eventTimer) clearTimeout(run.eventTimer);
23474
24321
  this.flushChatEvents(run);
23475
24322
  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)) {
24323
+ const retry = run.resumeRetry;
24324
+ 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";
24325
+ if (retry && missing) {
23478
24326
  this.logger.warn("resume-session-missing", { runId: run.runId, agentType: run.agentType, sessionId: run.sessionId });
23479
24327
  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;
24328
+ const gone = `\u539F\u4F1A\u8BDD ${retry.session_id} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`;
24329
+ const notice = retry.notice ? `${retry.notice}\uFF1B${gone}` : gone;
23482
24330
  await this.start({ ...rest, session_id: "", notice });
23483
24331
  return;
23484
24332
  }
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)}
24333
+ if (!run.chat && !run.turnError && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled) {
24334
+ const hidden = classifyCliOutput(run.stderr, run.provider.failureRules, run.cli, { successfulExit: true });
24335
+ if (hidden) {
24336
+ run.turnError = sanitizeTerminalLine(hidden.message);
24337
+ run.turnFailure = hidden.kind;
24338
+ if (hidden.rule.showInLog) run.tail.append(`\u2717 ${run.turnError}
23490
24339
  `);
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
24340
  }
23495
24341
  }
23496
24342
  if (run.sessionsBefore && !run.sessionId && !spawnError && run.provider.listSessions) {
@@ -23514,35 +24360,50 @@ var RunSupervisor = class {
23514
24360
  if (run.cancelRequested) {
23515
24361
  report = { status: "cancelled", duration_ms: durationMs };
23516
24362
  } else if (spawnError) {
23517
- report = { status: "failed", error: `\u65E0\u6CD5\u542F\u52A8 ${run.agentType}\uFF1A${spawnError}`, duration_ms: durationMs };
24363
+ report = failedReport(classifySpawnError(spawnError, run.cli), durationMs);
23518
24364
  } else if (run.stalled) {
23519
24365
  const stall = run.stalled;
23520
24366
  report = {
23521
24367
  status: "failed",
23522
24368
  failure_reason: "stalled",
24369
+ failure_kind: "stalled",
23523
24370
  stall,
23524
24371
  duration_ms: durationMs,
23525
24372
  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
24373
  };
23527
24374
  } else if (run.timedOut) {
23528
- report = { status: "failed", error: `\u8D85\u8FC7\u6700\u957F\u8FD0\u884C\u65F6\u95F4 ${this.config.maxRunSeconds} \u79D2`, duration_ms: durationMs };
24375
+ report = failedReport(cliFailure("timedOut", { label: run.cli.label, seconds: this.config.maxRunSeconds }), durationMs);
23529
24376
  } else if (run.turnError) {
23530
- report = { status: "failed", error: run.turnError, duration_ms: durationMs };
24377
+ report = failedReport(this.turnFailure(run), durationMs);
23531
24378
  } else if (code === 0 || run.killedAfterCompletion) {
23532
24379
  report = { status: "succeeded", duration_ms: durationMs };
23533
24380
  } 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 };
24381
+ report = failedReport(this.exitFailure(run, signal2), durationMs);
23536
24382
  }
23537
24383
  if (code !== null) report.exit_code = code;
23538
24384
  if (run.sessionId) report.session_id = run.sessionId;
23539
24385
  if (run.finalMessage) report.final_message = run.finalMessage;
23540
24386
  run.tail.append(`\u25CF \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF1A${report.status}${code !== null ? `\uFF08exit ${code}\uFF09` : ""}
23541
24387
  `);
23542
- this.remember({ runId: run.runId, workstationId: run.workstationId, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
24388
+ run.recorder?.write({ result: { ...report, duration_ms: 0 }, log: run.tail.read({ limit: 2e3 }).lines });
24389
+ this.remember({ runId: run.runId, sessionKey: run.sessionKey, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
23543
24390
  this.logger.info("run-finished", { runId: run.runId, status: report.status, code, durationMs });
23544
24391
  await this.report(run.runId, report);
23545
24392
  }
24393
+ /** The CLI declared the turn failed: name the kind, keep its own words. */
24394
+ turnFailure(run) {
24395
+ if (run.turnFailure) return { kind: run.turnFailure, message: run.turnError };
24396
+ const known = classifyCliOutput(run.turnError, run.provider.failureRules, run.cli);
24397
+ if (!known) return { kind: "turnFailed", message: run.turnError };
24398
+ return known.rule.message ? known : cliFailure(known.kind, { ...run.cli, detail: run.turnError });
24399
+ }
24400
+ /** Non-zero exit with no declared error: classify stderr, else show its tail. */
24401
+ exitFailure(run, signal2) {
24402
+ const known = classifyCliOutput(run.stderr, run.provider.failureRules, run.cli);
24403
+ if (known) return known;
24404
+ const detail = run.stderr.slice(-8).join("\n").trim();
24405
+ return cliFailure("exited", { label: run.cli.label, detail: detail || (signal2 ? `\uFF08${signal2}\uFF09` : "") });
24406
+ }
23546
24407
  noteOutput(run, row) {
23547
24408
  run.lastOutputAt = Date.now();
23548
24409
  run.lastCategory = rowCategory(row);
@@ -23567,6 +24428,7 @@ var RunSupervisor = class {
23567
24428
  if (run.queuedBytes + bytes > 8 * 1024 * 1024) {
23568
24429
  run.forwardingFailed = true;
23569
24430
  run.turnError = "\u5B9E\u65F6\u8F93\u51FA\u8F6C\u53D1\u79EF\u538B\uFF0C\u8BF7\u68C0\u67E5\u8BBE\u5907\u7F51\u7EDC";
24431
+ run.turnFailure = "hostFault";
23570
24432
  void killProcessTree(run.pid);
23571
24433
  return;
23572
24434
  }
@@ -23594,6 +24456,7 @@ var RunSupervisor = class {
23594
24456
  }).catch((error62) => {
23595
24457
  run.forwardingFailed = true;
23596
24458
  run.turnError = `\u5B9E\u65F6\u8F93\u51FA\u8F6C\u53D1\u5931\u8D25\uFF1A${errorMessage(error62)}`;
24459
+ run.turnFailure = "hostFault";
23597
24460
  this.logger.warn("chat-events-failed", { runId: run.runId, error: errorMessage(error62) });
23598
24461
  if (this.active.has(run.runId)) void killProcessTree(run.pid);
23599
24462
  }).finally(() => {
@@ -23603,12 +24466,12 @@ var RunSupervisor = class {
23603
24466
  async prepareChatAttachments(payload) {
23604
24467
  if (!payload.attachments?.length) return [];
23605
24468
  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));
24469
+ const directory = join13(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23607
24470
  await mkdir5(directory, { recursive: true, mode: 448 });
23608
24471
  const files = [];
23609
24472
  for (const attachment of payload.attachments) {
23610
24473
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
23611
- const path = join12(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
24474
+ const path = join13(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23612
24475
  const existing = await stat3(path).catch(() => void 0);
23613
24476
  if (!existing?.isFile()) {
23614
24477
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
@@ -23639,13 +24502,22 @@ var RunSupervisor = class {
23639
24502
  await killProcessTree(run.pid);
23640
24503
  return true;
23641
24504
  }
24505
+ /** Pauses or clears the goal of a running goal run; false when there is none. */
24506
+ controlGoal(runId, action) {
24507
+ const run = this.active.get(runId);
24508
+ if (!run?.provider.controlGoal) return false;
24509
+ const applied = run.provider.controlGoal(action);
24510
+ if (applied) run.tail.append(`\u25CF \u6536\u5230${action === "pause" ? "\u6682\u505C" : "\u6E05\u9664"}\u76EE\u6807\u6307\u4EE4
24511
+ `);
24512
+ return applied;
24513
+ }
23642
24514
  tail(query, limit, beforeCursor) {
23643
24515
  const byId = (id) => id ? this.active.get(id) ?? this.recent.get(id) : void 0;
23644
- const byWorkstation = (id) => {
24516
+ const bySession = (id) => {
23645
24517
  if (!id) return void 0;
23646
- const live = [...this.active.values()].find((run) => run.workstationId === id);
24518
+ const live = [...this.active.values()].find((run) => run.sessionKey === id);
23647
24519
  if (live) return live;
23648
- return [...this.recent.values()].filter((run) => run.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
24520
+ return [...this.recent.values()].filter((run) => run.sessionKey === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
23649
24521
  };
23650
24522
  const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23651
24523
  if (query.runId) {
@@ -23654,7 +24526,7 @@ var RunSupervisor = class {
23654
24526
  const read2 = run.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23655
24527
  return { ...read2, status: this.active.has(run.runId) ? "running" : "finished", run_id: run.runId };
23656
24528
  }
23657
- const target = byWorkstation(query.workstationId);
24529
+ const target = bySession(query.taskChainId);
23658
24530
  if (!target) return { ...empty, status: "idle" };
23659
24531
  const read = target.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23660
24532
  return { ...read, status: this.active.has(target.runId) ? "running" : "finished", run_id: target.runId };
@@ -23698,11 +24570,17 @@ var RunSupervisor = class {
23698
24570
  throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5728\u5141\u8BB8\u8303\u56F4\u5185\uFF1A${input2}`);
23699
24571
  }
23700
24572
  async prepareTaskFiles(payload, signal2 = AbortSignal.timeout(15 * 6e4), workdir) {
23701
- if (!payload.workdir) throw new Error("\u8BF7\u5148\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u5DE5\u4F4D\u5DE5\u4F5C\u76EE\u5F55");
24573
+ if (!payload.workdir) throw new Error("\u8BF7\u5148\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u4F1A\u8BDD\u5DE5\u4F5C\u76EE\u5F55");
23702
24574
  if (!this.reporter.taskFile) throw new Error("\u4EFB\u52A1\u9644\u4EF6\u4E0B\u8F7D\u672A\u914D\u7F6E");
23703
24575
  return prepareTaskAttachments(payload, workdir ?? await this.validateWorkdir(payload.workdir), this.reporter.taskFile, AbortSignal.any([signal2, AbortSignal.timeout(15 * 6e4)]));
23704
24576
  }
23705
24577
  };
24578
+ function failedReport(failure2, durationMs) {
24579
+ return { status: "failed", error: failure2.message, failure_kind: failure2.kind, duration_ms: durationMs };
24580
+ }
24581
+ function sessionKeyOf(payload) {
24582
+ return payload.task_chain_id || payload.chat_session_id || payload.run_id;
24583
+ }
23706
24584
  function errorMessage(error62) {
23707
24585
  return error62 instanceof Error ? error62.message : String(error62);
23708
24586
  }
@@ -23839,6 +24717,12 @@ var GatewayClient = class {
23839
24717
  await pipeline(Readable.fromWeb(response.body), verifier, target, { signal: signal2 });
23840
24718
  if (received !== size || hash2.digest("hex") !== sha256) throw new Error("\u9644\u4EF6\u4E0B\u8F7D\u4E0D\u5B8C\u6574\u6216\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
23841
24719
  }
24720
+ runGoal(runId, body) {
24721
+ return this.request("POST", `/runs/${encodeURIComponent(runId)}/goal`, body, 15e3);
24722
+ }
24723
+ runGoalTurn(runId, body) {
24724
+ return this.request("POST", `/runs/${encodeURIComponent(runId)}/goal-turn`, body, 15e3);
24725
+ }
23842
24726
  runFinished(runId, body) {
23843
24727
  return this.request("POST", `/runs/${encodeURIComponent(runId)}/finished`, body, 15e3);
23844
24728
  }
@@ -23846,11 +24730,11 @@ var GatewayClient = class {
23846
24730
 
23847
24731
  // src/workspace/directory-browser.ts
23848
24732
  import { readdir as readdir2, realpath as realpath3, stat as stat4 } from "node:fs/promises";
23849
- import { homedir as homedir8 } from "node:os";
24733
+ import { homedir as homedir9 } from "node:os";
23850
24734
  import { dirname as dirname6, parse as parse3, resolve as resolve4 } from "node:path";
23851
24735
  var MAX_ENTRIES = 1e3;
23852
24736
  async function listDirectory(requested, allowedRoots) {
23853
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir8()) || homedir8();
24737
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir9()) || homedir9();
23854
24738
  const directory = await realpath3(resolve4(raw)).catch(() => {
23855
24739
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
23856
24740
  });
@@ -23868,8 +24752,8 @@ async function listDirectory(requested, allowedRoots) {
23868
24752
  else if (entry.isFile()) files.push(item);
23869
24753
  }
23870
24754
  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 });
24755
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir9() }];
24756
+ for (const root of allowedRoots) if (root !== homedir9()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23873
24757
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
23874
24758
  return {
23875
24759
  path: directory,
@@ -23882,10 +24766,10 @@ async function listDirectory(requested, allowedRoots) {
23882
24766
  }
23883
24767
 
23884
24768
  // src/workspace/workspace-manager.ts
23885
- import { spawn as spawn9 } from "node:child_process";
24769
+ import { spawn as spawn10 } from "node:child_process";
23886
24770
  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";
24771
+ import { homedir as homedir10, tmpdir as tmpdir2 } from "node:os";
24772
+ import { isAbsolute as isAbsolute4, join as join14, relative as relative3, resolve as resolve5 } from "node:path";
23889
24773
  var MAX_NODES = 2e3;
23890
24774
  var MAX_DIRECTORY_ENTRIES = 12e3;
23891
24775
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -23933,7 +24817,7 @@ var WorkspaceManager = class {
23933
24817
  };
23934
24818
  }
23935
24819
  validateRootPath(value) {
23936
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir9());
24820
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir10());
23937
24821
  const root = resolve5(raw);
23938
24822
  if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
23939
24823
  if (relative3(root, resolve5(root, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -24226,7 +25110,7 @@ var WorkspaceManager = class {
24226
25110
  }
24227
25111
  runGit(args, cwd, timeoutSeconds, allowFailure = false, environment) {
24228
25112
  return new Promise((resolveCommand, rejectCommand) => {
24229
- const child = spawn9("git", args, {
25113
+ const child = spawn10("git", args, {
24230
25114
  cwd,
24231
25115
  env: environment ?? process.env,
24232
25116
  shell: false,
@@ -24260,12 +25144,12 @@ var WorkspaceManager = class {
24260
25144
  }
24261
25145
  async createGitAuthEnvironment(auth) {
24262
25146
  if (!auth) return void 0;
24263
- const directory = await mkdtemp(join13(tmpdir2(), "toc-ocra-git-auth-"));
25147
+ const directory = await mkdtemp(join14(tmpdir2(), "toc-ocra-git-auth-"));
24264
25148
  const isWindows = process.platform === "win32";
24265
- const scriptPath = join13(directory, isWindows ? "askpass.cmd" : "askpass.sh");
25149
+ const scriptPath = join14(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24266
25150
  let script;
24267
25151
  if (isWindows) {
24268
- const helperPath = join13(directory, "askpass.cjs");
25152
+ const helperPath = join14(directory, "askpass.cjs");
24269
25153
  await writeFile6(
24270
25154
  helperPath,
24271
25155
  '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',
@@ -24304,8 +25188,6 @@ var DEFAULT_POLICY = { script: { enabled: false }, sql: { enabled: false } };
24304
25188
  var RunStartPayloadSchema = external_exports.object({
24305
25189
  cli_policy: external_exports.object({ enabled: external_exports.boolean(), mode: external_exports.enum(["restricted", "full"]), version: external_exports.literal(1) }).optional(),
24306
25190
  run_id: external_exports.string().min(1).max(64),
24307
- workstation_id: external_exports.string().min(1).max(64),
24308
- workstation_name: external_exports.string().optional().default(""),
24309
25191
  agent_type: external_exports.string().min(1).max(40),
24310
25192
  task_chain_id: external_exports.string().optional().default(""),
24311
25193
  message_id: external_exports.string().optional().default(""),
@@ -24317,6 +25199,17 @@ var RunStartPayloadSchema = external_exports.object({
24317
25199
  model: external_exports.string().max(100).optional().default(""),
24318
25200
  reasoning_effort: external_exports.string().max(40).optional().default(""),
24319
25201
  workdir: external_exports.string().max(4096).optional().default(""),
25202
+ /**
25203
+ * CLI fork (分叉): before this turn, copy `source_session_id` (its first
25204
+ * `keep_turns` CLI turns; 0 = all) into this session's own CLI session.
25205
+ * Ignored once the session exists on this computer.
25206
+ */
25207
+ fork: external_exports.object({ source_session_id: external_exports.string().min(1).max(200), keep_turns: external_exports.number().int().min(0).max(1e5) }).nullish(),
25208
+ /**
25209
+ * Goal run (目标模式, Codex): after the turn starts, hand the CLI this
25210
+ * objective; the run stays open while the CLI continues by itself.
25211
+ */
25212
+ goal: external_exports.object({ objective: external_exports.string().max(8e3), token_budget: external_exports.number().int().positive().nullish() }).nullish(),
24320
25213
  /** Shown as the first line of this run's log (e.g. why it is an automatic resume). */
24321
25214
  notice: external_exports.string().max(1e3).nullish(),
24322
25215
  /**
@@ -24330,9 +25223,10 @@ var RunStartPayloadSchema = external_exports.object({
24330
25223
  }).nullish()
24331
25224
  });
24332
25225
  var RunCancelPayloadSchema = external_exports.object({ run_id: external_exports.string().min(1).max(64) });
25226
+ var RunGoalPayloadSchema = external_exports.object({ run_id: external_exports.string().min(1).max(64), action: external_exports.enum(["pause", "clear"]) });
24333
25227
  var RunTailPayloadSchema = external_exports.object({
24334
25228
  run_id: external_exports.string().max(64).optional(),
24335
- workstation_id: external_exports.string().max(64).optional(),
25229
+ task_chain_id: external_exports.string().max(64).optional(),
24336
25230
  lines: external_exports.number().int().positive().max(2e3).optional(),
24337
25231
  before_cursor: external_exports.number().int().min(0).optional()
24338
25232
  });
@@ -24412,10 +25306,16 @@ var AgentRuntime = class {
24412
25306
  finished: async (runId, report) => {
24413
25307
  this.pendingReports.set(runId, report);
24414
25308
  await this.flushReport(runId);
25309
+ },
25310
+ goal: async (runId, report) => {
25311
+ await this.retry(() => this.client.runGoal(runId, report), 3);
25312
+ },
25313
+ goalTurn: async (runId, report) => {
25314
+ await this.retry(() => this.client.runGoalTurn(runId, report), 9);
24415
25315
  }
24416
25316
  };
24417
25317
  this.workspaces = new WorkspaceManager(config2, this.logger);
24418
- this.orphans = new OrphanRegistry(join14(config2.dataDir, "active-runs.json"));
25318
+ this.orphans = new OrphanRegistry(join15(config2.dataDir, "active-runs.json"));
24419
25319
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
24420
25320
  }
24421
25321
  config;
@@ -24484,7 +25384,7 @@ var AgentRuntime = class {
24484
25384
  activeSessions: this.runs.activeCount,
24485
25385
  storedRuns: this.runs.recentRuns().length,
24486
25386
  startedAt: this.startedAt,
24487
- runs: this.runs.recentRuns().map((run) => ({ runId: run.runId, status: run.status, sessionId: run.workstationId, updatedAt: new Date(run.at).toISOString() })),
25387
+ runs: this.runs.recentRuns().map((run) => ({ runId: run.runId, status: run.status, sessionId: run.sessionKey, updatedAt: new Date(run.at).toISOString() })),
24488
25388
  capabilities: this.detection?.detectedIds ?? [],
24489
25389
  ...this.detection ? { detection: this.detection } : {},
24490
25390
  ...!this.lastHeartbeatOk && this.lastError ? { connectionError: this.lastError } : {},
@@ -24664,15 +25564,15 @@ var AgentRuntime = class {
24664
25564
  const cancelled = await this.runs.cancel(payload.run_id);
24665
25565
  return { success: true, result: { cancelled } };
24666
25566
  }
25567
+ case "run.goal": {
25568
+ const payload = RunGoalPayloadSchema.parse(command.payload);
25569
+ return { success: true, result: { applied: this.runs.controlGoal(payload.run_id, payload.action) } };
25570
+ }
24667
25571
  case "run.tail": {
24668
25572
  const payload = RunTailPayloadSchema.parse(command.payload);
24669
- const tail = this.runs.tail({ ...payload.run_id ? { runId: payload.run_id } : {}, ...payload.workstation_id ? { workstationId: payload.workstation_id } : {} }, payload.lines ?? 200, payload.before_cursor);
25573
+ const tail = this.runs.tail({ ...payload.run_id ? { runId: payload.run_id } : {}, ...payload.task_chain_id ? { taskChainId: payload.task_chain_id } : {} }, payload.lines ?? 200, payload.before_cursor);
24670
25574
  return { success: true, result: tail };
24671
25575
  }
24672
- case "workstation.create": {
24673
- const workstationId = String(command.payload?.workstation_id ?? command.workstation_id);
24674
- return { success: true, session_key: workstationId, result: { ready: true } };
24675
- }
24676
25576
  case "cli.detect":
24677
25577
  this.detection = await cliDetection.detect(true);
24678
25578
  void this.refreshCatalogs({ force: true });
@@ -25133,7 +26033,7 @@ function preferSystemNode() {
25133
26033
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
25134
26034
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
25135
26035
  for (const name of names) {
25136
- const candidate = directory && join15(directory, name);
26036
+ const candidate = directory && join16(directory, name);
25137
26037
  if (candidate && existsSync6(candidate)) {
25138
26038
  process.env.TOC_OCRA_NODE_PATH = candidate;
25139
26039
  return;