toc-ocra 0.2.34 → 0.2.35

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.
@@ -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 join12 } from "node:path";
10
+ import { delimiter as delimiter5, join as join13 } from "node:path";
11
11
 
12
12
  // src/config.ts
13
13
  import { randomUUID } from "node:crypto";
@@ -20928,6 +20928,145 @@ var grokProvider = {
20928
20928
  // src/providers/cli/kiro.ts
20929
20929
  import { execFile } from "node:child_process";
20930
20930
  import { promisify } from "node:util";
20931
+
20932
+ // src/providers/cli/kiro-session-log.ts
20933
+ import { open as open2, readdir, readFile as readFile3, stat } from "node:fs/promises";
20934
+ import { homedir as homedir5 } from "node:os";
20935
+ import { join as join6 } from "node:path";
20936
+ var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
20937
+ function kiroSessionsDirectory() {
20938
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join6(homedir5(), ".kiro", "sessions", "cli");
20939
+ }
20940
+ var KiroSessionLog = class {
20941
+ constructor(options) {
20942
+ this.options = options;
20943
+ }
20944
+ options;
20945
+ path;
20946
+ offset = 0;
20947
+ partial = "";
20948
+ steps = [];
20949
+ results = /* @__PURE__ */ new Map();
20950
+ claimed = /* @__PURE__ */ new Set();
20951
+ get directory() {
20952
+ return this.options.directory ?? kiroSessionsDirectory();
20953
+ }
20954
+ /** Called before the CLI starts: a resumed log is followed from its current end. */
20955
+ async begin() {
20956
+ if (!this.options.sessionId) return;
20957
+ this.path = join6(this.directory, `${this.options.sessionId}.jsonl`);
20958
+ this.offset = await stat(this.path).then((info) => info.size, () => 0);
20959
+ }
20960
+ /**
20961
+ * A fresh turn's chat has no known id: the one log for this folder created
20962
+ * after the turn started. Several candidates (another turn starting a chat
20963
+ * in the same folder) leave it unknown.
20964
+ */
20965
+ async findFreshLog() {
20966
+ const names = await readdir(this.directory).catch(() => []);
20967
+ const found = [];
20968
+ for (const name of names) {
20969
+ if (!name.endsWith(".json")) continue;
20970
+ const meta3 = await readFile3(join6(this.directory, name), "utf8").then((text) => JSON.parse(text), () => void 0);
20971
+ const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
20972
+ if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
20973
+ }
20974
+ if (found.length === 1) this.path = join6(this.directory, `${found[0]}.jsonl`);
20975
+ }
20976
+ /** Reads entries appended since the last call. */
20977
+ async refresh() {
20978
+ if (!this.path) await this.findFreshLog();
20979
+ if (!this.path) return;
20980
+ const file2 = await open2(this.path, "r").catch(() => void 0);
20981
+ if (!file2) return;
20982
+ try {
20983
+ const { size } = await file2.stat();
20984
+ if (size <= this.offset) return;
20985
+ const buffer = Buffer.alloc(size - this.offset);
20986
+ await file2.read(buffer, 0, buffer.length, this.offset);
20987
+ this.offset = size;
20988
+ const lines = (this.partial + buffer.toString("utf8")).split("\n");
20989
+ this.partial = lines.pop() ?? "";
20990
+ for (const line of lines) this.take(line);
20991
+ } finally {
20992
+ await file2.close();
20993
+ }
20994
+ }
20995
+ take(line) {
20996
+ let entry;
20997
+ try {
20998
+ entry = JSON.parse(line);
20999
+ } catch {
21000
+ return;
21001
+ }
21002
+ for (const part of entry.data?.content ?? []) {
21003
+ const data = part.data ?? {};
21004
+ if (part.kind === "toolUse" && SHELL_TOOLS.has(String(data.name))) {
21005
+ const command = data.input?.command;
21006
+ if (typeof data.toolUseId === "string" && typeof command === "string") this.steps.push({ id: data.toolUseId, command });
21007
+ } else if (part.kind === "toolResult" && typeof data.toolUseId === "string") {
21008
+ this.results.set(data.toolUseId, resultOf(data));
21009
+ }
21010
+ }
21011
+ }
21012
+ /** The shell step a `[tool] Running:` row announced (its text may be cut short). */
21013
+ async step(shown, waitMs = 2e3) {
21014
+ const prefix = shown.replace(/\.\.\.$|…$/, "").trim();
21015
+ const deadline = Date.now() + waitMs;
21016
+ for (; ; ) {
21017
+ await this.refresh();
21018
+ const step = this.steps.find((item) => !this.claimed.has(item.id) && item.command.trim().startsWith(prefix));
21019
+ if (step) {
21020
+ this.claimed.add(step.id);
21021
+ return step;
21022
+ }
21023
+ if (Date.now() >= deadline) return void 0;
21024
+ await new Promise((resolve7) => setTimeout(resolve7, 150));
21025
+ }
21026
+ }
21027
+ /** The first of `ids` whose result is in the log, waiting up to `waitMs`. */
21028
+ async firstFinished(ids, waitMs) {
21029
+ const deadline = Date.now() + waitMs;
21030
+ for (; ; ) {
21031
+ await this.refresh();
21032
+ const id = ids.find((item) => this.results.has(item));
21033
+ if (id || Date.now() >= deadline) return id;
21034
+ await new Promise((resolve7) => setTimeout(resolve7, 150));
21035
+ }
21036
+ }
21037
+ async result(id, waitMs = 3e3) {
21038
+ const deadline = Date.now() + waitMs;
21039
+ for (; ; ) {
21040
+ await this.refresh();
21041
+ const result = this.results.get(id);
21042
+ if (result || Date.now() >= deadline) return result;
21043
+ await new Promise((resolve7) => setTimeout(resolve7, 200));
21044
+ }
21045
+ }
21046
+ };
21047
+ function resultOf(data) {
21048
+ const parts = Array.isArray(data.content) ? data.content : [];
21049
+ const texts = [];
21050
+ let exitCode;
21051
+ for (const part of parts) {
21052
+ if (part.kind === "json" && part.data && typeof part.data === "object") {
21053
+ const value = part.data;
21054
+ const code = /(-?\d+)/.exec(String(value.exit_status ?? ""))?.[1];
21055
+ if (code !== void 0) exitCode = Number(code);
21056
+ for (const text of [value.stdout, value.stderr]) if (typeof text === "string" && text.trim()) texts.push(text.replace(/\s+$/, ""));
21057
+ } else if (part.kind === "text" && typeof part.data === "string" && part.data.trim()) {
21058
+ texts.push(part.data.replace(/\s+$/, ""));
21059
+ }
21060
+ }
21061
+ if (exitCode === void 0 && data.status === "error") exitCode = 1;
21062
+ return { ...exitCode === void 0 ? {} : { exitCode }, output: texts.join("\n") };
21063
+ }
21064
+ function sameFolder(a, b) {
21065
+ const normal = (path) => path.replace(/\/+$/, "").replace(/^\/private(?=\/)/, "");
21066
+ return normal(a) === normal(b);
21067
+ }
21068
+
21069
+ // src/providers/cli/kiro.ts
20931
21070
  var execFileAsync = promisify(execFile);
20932
21071
  var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
20933
21072
  function kiroLaunch(args) {
@@ -20951,7 +21090,7 @@ function describeListSessionsError(error62, timeoutMs) {
20951
21090
  return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
20952
21091
  }
20953
21092
  async function listKiroSessions(workdir, options = {}) {
20954
- const timeoutMs = options.timeoutMs ?? KIRO_LIST_SESSIONS_TIMEOUT_MS;
21093
+ const timeoutMs = options.timeoutMs ?? (Number(process.env.TOC_OCRA_KIRO_LIST_TIMEOUT_MS) || KIRO_LIST_SESSIONS_TIMEOUT_MS);
20955
21094
  const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20956
21095
  let lastError;
20957
21096
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -20985,10 +21124,32 @@ function kiroToolRows(text) {
20985
21124
  function isKiroNoise(text) {
20986
21125
  return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text);
20987
21126
  }
20988
- function kiroRunParser() {
21127
+ function kiroRunParser(context) {
20989
21128
  let pending = "";
20990
21129
  let started = false;
20991
21130
  let segment = [];
21131
+ const log = context ? new KiroSessionLog({ sessionId: context.sessionId, workdir: context.workdir, startedAt: context.startedAt }) : void 0;
21132
+ const ready = log?.begin().catch(() => void 0);
21133
+ let queue = Promise.resolve();
21134
+ const openSteps = [];
21135
+ let lastHeader;
21136
+ const out = (parsed) => {
21137
+ if (!context) return typeof parsed === "function" ? { display: [] } : parsed;
21138
+ queue = queue.then(async () => {
21139
+ const value = typeof parsed === "function" ? await parsed().catch(() => ({ display: [] })) : parsed;
21140
+ if (value.display.length && typeof parsed !== "function") lastHeader = void 0;
21141
+ context.emit(value);
21142
+ });
21143
+ return { display: [] };
21144
+ };
21145
+ const finishShell = async (step, status) => {
21146
+ const found = await step.shell.lookup;
21147
+ const result = found ? await log.result(found.id, 1e3) : void 0;
21148
+ const header = step.shell.headerShown && lastHeader === step ? [] : [runLog.command(found?.command ?? step.shell.shown)];
21149
+ lastHeader = void 0;
21150
+ if (!result) return { display: [...header, ...status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : []] };
21151
+ return { display: [...header, ...runLog.commandOutput(result.output), runLog.commandExit(result.exitCode ?? (status === "failed" ? 1 : 0))] };
21152
+ };
20992
21153
  const replyRows = (lines) => {
20993
21154
  const display = [];
20994
21155
  for (const raw of lines) {
@@ -21016,16 +21177,55 @@ function kiroRunParser() {
21016
21177
  stdout(chunk) {
21017
21178
  const lines = (pending + chunk).split(/\r?\n/);
21018
21179
  pending = lines.pop() ?? "";
21019
- return replyRows(lines);
21180
+ return out(replyRows(lines));
21020
21181
  },
21021
21182
  stderr(raw) {
21022
21183
  const text = raw.replace(ANSI, "").trim();
21023
21184
  if (!text || isKiroNoise(text)) return { display: [] };
21024
- const rows = kiroToolRows(text) ?? [runLog.error(text)];
21025
21185
  const closed = closeSegment();
21026
- return { ...closed, display: [...closed.display, ...rows] };
21186
+ const status = /^\[tool\]\s*status:\s*(\w+)/i.exec(text)?.[1]?.toLowerCase();
21187
+ if (!log) {
21188
+ const rows2 = kiroToolRows(text) ?? [runLog.error(text)];
21189
+ return out({ ...closed, display: [...closed.display, ...rows2] });
21190
+ }
21191
+ out(closed);
21192
+ const running = /^\[tool\]\s*Running:\s*(.+)$/.exec(text)?.[1]?.trim();
21193
+ if (running && !running.startsWith("@")) {
21194
+ const step = { shell: { shown: running, lookup: (async () => {
21195
+ await ready;
21196
+ return log.step(running);
21197
+ })(), headerShown: !openSteps.some((item) => item.shell) } };
21198
+ openSteps.push(step);
21199
+ if (!step.shell.headerShown) return { display: [] };
21200
+ return out(async () => {
21201
+ const found = await step.shell.lookup;
21202
+ lastHeader = step;
21203
+ return { display: [runLog.command(found?.command ?? running)] };
21204
+ });
21205
+ }
21206
+ if (status) {
21207
+ return out(async () => {
21208
+ const shells = openSteps.filter((item) => item.shell);
21209
+ const ids = (await Promise.all(shells.map((item) => item.shell.lookup))).map((found) => found?.id ?? "");
21210
+ const others = openSteps.some((item) => !item.shell);
21211
+ const id = shells.length ? await log.firstFinished(ids.filter(Boolean), others ? 1200 : 3e3) : void 0;
21212
+ const step = id ? shells[ids.indexOf(id)] : openSteps.find((item) => !item.shell) ?? openSteps[0];
21213
+ if (step) openSteps.splice(openSteps.indexOf(step), 1);
21214
+ if (step?.shell) return finishShell(step, status);
21215
+ lastHeader = void 0;
21216
+ return { display: status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [] };
21217
+ });
21218
+ }
21219
+ if (/^\[tool\]/.test(text)) openSteps.push({});
21220
+ const rows = kiroToolRows(text) ?? [runLog.error(text)];
21221
+ return out({ display: rows });
21027
21222
  },
21028
- end: closeSegment
21223
+ end: async () => {
21224
+ const rest = out(closeSegment());
21225
+ if (!context) return rest;
21226
+ await queue;
21227
+ return { display: [] };
21228
+ }
21029
21229
  };
21030
21230
  }
21031
21231
  var kiroProvider = {
@@ -21051,7 +21251,7 @@ var kiroProvider = {
21051
21251
  return kiroRunParser().stdout(`${line}
21052
21252
  `);
21053
21253
  },
21054
- createRunParser: () => kiroRunParser()
21254
+ createRunParser: (context) => kiroRunParser(context)
21055
21255
  };
21056
21256
  function kiroStderrError(stderrLines) {
21057
21257
  const text = stderrLines.join("\n");
@@ -21227,7 +21427,7 @@ var cliDetection = new CliDetectionService();
21227
21427
 
21228
21428
  // src/runtime/agent-runtime.ts
21229
21429
  import { randomUUID as randomUUID3 } from "node:crypto";
21230
- import { join as join11 } from "node:path";
21430
+ import { join as join12 } from "node:path";
21231
21431
 
21232
21432
  // src/exec/script-runner.ts
21233
21433
  import { spawn as spawn3 } from "node:child_process";
@@ -21632,13 +21832,13 @@ function resolveChatProvider(type, request, attachments) {
21632
21832
 
21633
21833
  // src/providers/model-catalog-collector.ts
21634
21834
  import { createHash } from "node:crypto";
21635
- import { stat } from "node:fs/promises";
21835
+ import { stat as stat2 } from "node:fs/promises";
21636
21836
 
21637
21837
  // src/providers/model-catalog.ts
21638
21838
  import { spawn as spawn5 } from "node:child_process";
21639
- import { readFile as readFile3 } from "node:fs/promises";
21640
- import { homedir as homedir5 } from "node:os";
21641
- import { isAbsolute, join as join6, resolve as resolve2 } from "node:path";
21839
+ import { readFile as readFile4 } from "node:fs/promises";
21840
+ import { homedir as homedir6 } from "node:os";
21841
+ import { isAbsolute, join as join7, resolve as resolve2 } from "node:path";
21642
21842
 
21643
21843
  // src/providers/kiro-models.ts
21644
21844
  import { spawn as spawn4 } from "node:child_process";
@@ -21760,15 +21960,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
21760
21960
  if (defaultModel) catalog.default_model = defaultModel;
21761
21961
  return catalog;
21762
21962
  }
21763
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir5(), ".claude");
21764
- var codexHome = () => process.env.CODEX_HOME?.trim() || join6(homedir5(), ".codex");
21765
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join6(homedir5(), ".gemini");
21766
- var grokHome = () => process.env.GROK_HOME?.trim() || join6(homedir5(), ".grok");
21767
- var opencodeHome = () => join6(process.env.XDG_CONFIG_HOME?.trim() || join6(homedir5(), ".config"), "opencode");
21768
- var kiroHome = () => join6(homedir5(), ".kiro");
21963
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir6(), ".claude");
21964
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join7(homedir6(), ".codex");
21965
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join7(homedir6(), ".gemini");
21966
+ var grokHome = () => process.env.GROK_HOME?.trim() || join7(homedir6(), ".grok");
21967
+ var opencodeHome = () => join7(process.env.XDG_CONFIG_HOME?.trim() || join7(homedir6(), ".config"), "opencode");
21968
+ var kiroHome = () => join7(homedir6(), ".kiro");
21769
21969
  async function readClaudeModelCatalog() {
21770
21970
  const home = claudeHome();
21771
- const content = await readFile3(join6(home, "settings.json"), "utf8").catch(() => "");
21971
+ const content = await readFile4(join7(home, "settings.json"), "utf8").catch(() => "");
21772
21972
  let settings = {};
21773
21973
  if (content) {
21774
21974
  try {
@@ -21824,16 +22024,16 @@ async function readCodexModels(codexHome2, config2) {
21824
22024
  const configuredCatalog = configValue(config2, "model_catalog_json");
21825
22025
  if (configuredCatalog) {
21826
22026
  const catalogPath = isAbsolute(configuredCatalog) ? configuredCatalog : resolve2(codexHome2, configuredCatalog);
21827
- const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
22027
+ const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
21828
22028
  if (configuredModels?.length) return configuredModels;
21829
22029
  }
21830
22030
  return parseCodexModels(
21831
- await readFile3(join6(codexHome2, "models_cache.json"), "utf8").catch(() => "")
22031
+ await readFile4(join7(codexHome2, "models_cache.json"), "utf8").catch(() => "")
21832
22032
  ) ?? [];
21833
22033
  }
21834
22034
  async function readCodexModelCatalog() {
21835
22035
  const home = codexHome();
21836
- const config2 = await readFile3(join6(home, "config.toml"), "utf8").catch(() => "");
22036
+ const config2 = await readFile4(join7(home, "config.toml"), "utf8").catch(() => "");
21837
22037
  const models = await readCodexModels(home, config2);
21838
22038
  const defaultModel = configValue(config2, "model");
21839
22039
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -21923,8 +22123,8 @@ async function readKiroModelCatalog() {
21923
22123
  };
21924
22124
  const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
21925
22125
  const [payload, content] = await Promise.all([
21926
- readKiroNativeModels(launch, homedir5(), { catalog: base }),
21927
- readFile3(join6(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
22126
+ readKiroNativeModels(launch, homedir6(), { catalog: base }),
22127
+ readFile4(join7(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21928
22128
  ]);
21929
22129
  let settings;
21930
22130
  try {
@@ -21981,7 +22181,7 @@ function geminiModelsUrl(baseUrl) {
21981
22181
  }
21982
22182
  async function readGeminiModelCatalog() {
21983
22183
  const fileEnvironment = parseEnvFile(
21984
- await readFile3(join6(geminiHome(), ".env"), "utf8").catch(() => "")
22184
+ await readFile4(join7(geminiHome(), ".env"), "utf8").catch(() => "")
21985
22185
  );
21986
22186
  const environment = { ...fileEnvironment, ...process.env };
21987
22187
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -22026,7 +22226,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
22026
22226
  return catalog;
22027
22227
  }
22028
22228
  async function readGrokModelCatalog() {
22029
- const config2 = await readFile3(join6(grokHome(), "config.toml"), "utf8").catch(() => "");
22229
+ const config2 = await readFile4(join7(grokHome(), "config.toml"), "utf8").catch(() => "");
22030
22230
  const output2 = await runModelListCommand(resolveCliCommand("grok"), ["models"], "grok");
22031
22231
  const catalog = parseGrokModelCatalog(output2, config2);
22032
22232
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22045,7 +22245,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
22045
22245
  return catalog;
22046
22246
  }
22047
22247
  async function readOpencodeModelCatalog() {
22048
- const config2 = await readFile3(join6(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join6(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22248
+ const config2 = await readFile4(join7(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join7(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22049
22249
  const output2 = await runModelListCommand(resolveCliCommand("opencode"), ["models"], "opencode");
22050
22250
  const catalog = parseOpencodeModelCatalog(output2, config2);
22051
22251
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22053,22 +22253,22 @@ async function readOpencodeModelCatalog() {
22053
22253
  }
22054
22254
  var TEN_MINUTES = 10 * 60 * 1e3;
22055
22255
  var MODEL_SOURCES = {
22056
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join6(claudeHome(), "settings.json")] },
22256
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join7(claudeHome(), "settings.json")] },
22057
22257
  codex: {
22058
22258
  read: readCodexModelCatalog,
22059
22259
  watchFiles: () => {
22060
22260
  const home = codexHome();
22061
- return [join6(home, "config.toml"), join6(home, "models_cache.json")];
22261
+ return [join7(home, "config.toml"), join7(home, "models_cache.json")];
22062
22262
  },
22063
22263
  // model_catalog_json may point anywhere; a periodic re-read covers it.
22064
22264
  refreshEveryMs: TEN_MINUTES
22065
22265
  },
22066
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join6(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22067
- grok: { read: readGrokModelCatalog, watchFiles: () => [join6(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22068
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join6(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22266
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join7(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22267
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join7(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22268
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join7(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22069
22269
  opencode: {
22070
22270
  read: readOpencodeModelCatalog,
22071
- watchFiles: () => [join6(opencodeHome(), "opencode.json"), join6(opencodeHome(), "opencode.jsonc")],
22271
+ watchFiles: () => [join7(opencodeHome(), "opencode.json"), join7(opencodeHome(), "opencode.jsonc")],
22072
22272
  refreshEveryMs: TEN_MINUTES
22073
22273
  }
22074
22274
  };
@@ -22076,7 +22276,7 @@ var MODEL_SOURCES = {
22076
22276
  // src/providers/model-catalog-collector.ts
22077
22277
  async function fileStamp(path) {
22078
22278
  try {
22079
- const info = await stat(path);
22279
+ const info = await stat2(path);
22080
22280
  return `${path}:${info.mtimeMs}:${info.size}`;
22081
22281
  } catch {
22082
22282
  return `${path}:-`;
@@ -22311,16 +22511,16 @@ async function readCLIQuotaReport(agentType) {
22311
22511
  }
22312
22512
 
22313
22513
  // src/providers/tb-switch-control.ts
22314
- import { readFile as readFile4 } from "node:fs/promises";
22315
- import { homedir as homedir6 } from "node:os";
22316
- import { join as join7 } from "node:path";
22514
+ import { readFile as readFile5 } from "node:fs/promises";
22515
+ import { homedir as homedir7 } from "node:os";
22516
+ import { join as join8 } from "node:path";
22317
22517
  function dataDir() {
22318
- return process.env.TB_SWITCH_HOME?.trim() || join7(homedir6(), ".tb-switch");
22518
+ return process.env.TB_SWITCH_HOME?.trim() || join8(homedir7(), ".tb-switch");
22319
22519
  }
22320
22520
  async function readLocalService() {
22321
22521
  let discovery;
22322
22522
  try {
22323
- discovery = JSON.parse(await readFile4(join7(dataDir(), "api.json"), "utf8"));
22523
+ discovery = JSON.parse(await readFile5(join8(dataDir(), "api.json"), "utf8"));
22324
22524
  } catch {
22325
22525
  throw new Error("\u8FD9\u53F0\u8BBE\u5907\u4E0A\u7684 TB Switch \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u8BF7\u6253\u5F00\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
22326
22526
  }
@@ -22336,7 +22536,7 @@ async function readLocalService() {
22336
22536
  }
22337
22537
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
22338
22538
  try {
22339
- token = (await readFile4(join7(dataDir(), "api-token"), "utf8")).trim();
22539
+ token = (await readFile5(join8(dataDir(), "api-token"), "utf8")).trim();
22340
22540
  } catch {
22341
22541
  }
22342
22542
  if (!token) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 TB Switch \u672C\u673A\u670D\u52A1\u51ED\u636E\uFF0C\u8BF7\u91CD\u542F\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
@@ -22427,7 +22627,7 @@ async function controlTbSwitch(payload) {
22427
22627
 
22428
22628
  // src/runs/orphan-registry.ts
22429
22629
  import { execFile as execFile4 } from "node:child_process";
22430
- import { mkdir as mkdir3, readFile as readFile5, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22630
+ import { mkdir as mkdir3, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22431
22631
  import { basename, dirname as dirname5 } from "node:path";
22432
22632
 
22433
22633
  // src/runs/process-tree.ts
@@ -22523,7 +22723,7 @@ var OrphanRegistry = class {
22523
22723
  async reapPrevious() {
22524
22724
  let previous = [];
22525
22725
  try {
22526
- previous = JSON.parse(await readFile5(this.file, "utf8"));
22726
+ previous = JSON.parse(await readFile6(this.file, "utf8"));
22527
22727
  } catch {
22528
22728
  return [];
22529
22729
  }
@@ -22553,8 +22753,8 @@ function commandOf(pid) {
22553
22753
 
22554
22754
  // src/runs/run-supervisor.ts
22555
22755
  import { spawn as spawn8 } from "node:child_process";
22556
- import { mkdir as mkdir5, realpath as realpath2, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
22557
- import { basename as basename3, isAbsolute as isAbsolute3, join as join9, relative as relative2, resolve as resolve3 } from "node:path";
22756
+ import { mkdir as mkdir5, realpath as realpath2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
22757
+ import { basename as basename3, isAbsolute as isAbsolute3, join as join10, relative as relative2, resolve as resolve3 } from "node:path";
22558
22758
  import { createInterface as createInterface3 } from "node:readline";
22559
22759
 
22560
22760
  // src/session/terminal-line-sanitizer.ts
@@ -22680,8 +22880,8 @@ function clipToCharacterBudget(rows, budget) {
22680
22880
  // src/runs/task-attachments.ts
22681
22881
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
22682
22882
  import { constants as constants2 } from "node:fs";
22683
- import { lstat, mkdir as mkdir4, open as open2, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22684
- import { basename as basename2, isAbsolute as isAbsolute2, join as join8, relative } from "node:path";
22883
+ import { lstat, mkdir as mkdir4, open as open3, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22884
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join9, relative } from "node:path";
22685
22885
  function within(root, path) {
22686
22886
  const segment = relative(root, path);
22687
22887
  return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
@@ -22689,7 +22889,7 @@ function within(root, path) {
22689
22889
  async function attachmentDirectory(workdir, messageId) {
22690
22890
  let directory = workdir;
22691
22891
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
22692
- directory = join8(directory, segment);
22892
+ directory = join9(directory, segment);
22693
22893
  await mkdir4(directory, { mode: 448 }).catch((error62) => {
22694
22894
  if (error62.code !== "EEXIST") throw error62;
22695
22895
  });
@@ -22697,7 +22897,7 @@ async function attachmentDirectory(workdir, messageId) {
22697
22897
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
22698
22898
  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");
22699
22899
  }
22700
- if (segment === ".echo") await writeFile4(join8(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
22900
+ if (segment === ".echo") await writeFile4(join9(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
22701
22901
  if (error62.code !== "EEXIST") throw error62;
22702
22902
  });
22703
22903
  }
@@ -22706,7 +22906,7 @@ async function attachmentDirectory(workdir, messageId) {
22706
22906
  async function matches(path, size, sha256, signal2) {
22707
22907
  const metadata = await lstat(path).catch(() => void 0);
22708
22908
  if (!metadata?.isFile() || metadata.isSymbolicLink() || metadata.size !== size) return false;
22709
- const file2 = await open2(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
22909
+ const file2 = await open3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
22710
22910
  try {
22711
22911
  const hash2 = createHash2("sha256");
22712
22912
  let read = 0;
@@ -22734,9 +22934,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
22734
22934
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
22735
22935
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
22736
22936
  const name = characters.join("") || "attachment";
22737
- const path = join8(directory, `${file2.file_id}-${name}`);
22937
+ const path = join9(directory, `${file2.file_id}-${name}`);
22738
22938
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
22739
- const temporary = join8(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
22939
+ const temporary = join9(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
22740
22940
  try {
22741
22941
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
22742
22942
  signal2.throwIfAborted();
@@ -22977,7 +23177,6 @@ var RunSupervisor = class {
22977
23177
  agentType: provider.id,
22978
23178
  provider,
22979
23179
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
22980
- ...provider.createRunParser ? { stream: provider.createRunParser() } : {},
22981
23180
  ...sessionsBefore ? { sessionsBefore } : {},
22982
23181
  ...unverifiedResume ? { unverifiedResume: payload } : {},
22983
23182
  prompt: payload.prompt,
@@ -23000,6 +23199,16 @@ var RunSupervisor = class {
23000
23199
  lastLine: "",
23001
23200
  lastOutputAt: Date.now()
23002
23201
  };
23202
+ if (provider.createRunParser) {
23203
+ run.stream = provider.createRunParser({
23204
+ workdir,
23205
+ sessionId,
23206
+ startedAt: run.startedAt,
23207
+ emit: (parsed) => {
23208
+ if (this.active.has(run.runId)) this.applyParsed(run, parsed, "");
23209
+ }
23210
+ });
23211
+ }
23003
23212
  this.active.set(run.runId, run);
23004
23213
  this.preparing.delete(run.runId);
23005
23214
  this.unreported.add(run.runId);
@@ -23115,7 +23324,7 @@ var RunSupervisor = class {
23115
23324
  }
23116
23325
  async onExit(run, code, signal2, spawnError) {
23117
23326
  for (const timer of run.timers) clearTimeout(timer);
23118
- if (run.stream) this.applyParsed(run, run.stream.end(), "");
23327
+ if (run.stream) this.applyParsed(run, await run.stream.end(), "");
23119
23328
  this.active.delete(run.runId);
23120
23329
  this.orphans?.remove(run.runId);
23121
23330
  if (run.eventTimer) clearTimeout(run.eventTimer);
@@ -23251,13 +23460,13 @@ var RunSupervisor = class {
23251
23460
  async prepareChatAttachments(payload) {
23252
23461
  if (!payload.attachments?.length) return [];
23253
23462
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
23254
- const directory = join9(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23463
+ const directory = join10(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23255
23464
  await mkdir5(directory, { recursive: true, mode: 448 });
23256
23465
  const files = [];
23257
23466
  for (const attachment of payload.attachments) {
23258
23467
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
23259
- const path = join9(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23260
- const existing = await stat2(path).catch(() => void 0);
23468
+ const path = join10(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23469
+ const existing = await stat3(path).catch(() => void 0);
23261
23470
  if (!existing?.isFile()) {
23262
23471
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
23263
23472
  await writeFile5(path, data, { mode: 384 });
@@ -23295,10 +23504,15 @@ var RunSupervisor = class {
23295
23504
  if (live) return live;
23296
23505
  return [...this.recent.values()].filter((run) => run.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
23297
23506
  };
23298
- const target = byId(query.runId) ?? byWorkstation(query.workstationId);
23299
- if (!target) {
23300
- return { status: "idle", lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23301
- }
23507
+ const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23508
+ if (query.runId) {
23509
+ const run = byId(query.runId);
23510
+ if (!run) return { ...empty, status: this.preparing.has(query.runId) ? "running" : "idle", run_id: query.runId };
23511
+ const read2 = run.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23512
+ return { ...read2, status: this.active.has(run.runId) ? "running" : "finished", run_id: run.runId };
23513
+ }
23514
+ const target = byWorkstation(query.workstationId);
23515
+ if (!target) return { ...empty, status: "idle" };
23302
23516
  const read = target.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23303
23517
  return { ...read, status: this.active.has(target.runId) ? "running" : "finished", run_id: target.runId };
23304
23518
  }
@@ -23488,17 +23702,17 @@ var GatewayClient = class {
23488
23702
  };
23489
23703
 
23490
23704
  // src/workspace/directory-browser.ts
23491
- import { readdir, realpath as realpath3, stat as stat3 } from "node:fs/promises";
23492
- import { homedir as homedir7 } from "node:os";
23705
+ import { readdir as readdir2, realpath as realpath3, stat as stat4 } from "node:fs/promises";
23706
+ import { homedir as homedir8 } from "node:os";
23493
23707
  import { dirname as dirname6, parse as parse3, resolve as resolve4 } from "node:path";
23494
23708
  var MAX_ENTRIES = 1e3;
23495
23709
  async function listDirectory(requested, allowedRoots) {
23496
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir7()) || homedir7();
23710
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir8()) || homedir8();
23497
23711
  const directory = await realpath3(resolve4(raw)).catch(() => {
23498
23712
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
23499
23713
  });
23500
- if (!(await stat3(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23501
- const entries = await readdir(directory, { withFileTypes: true }).catch((error62) => {
23714
+ if (!(await stat4(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23715
+ const entries = await readdir2(directory, { withFileTypes: true }).catch((error62) => {
23502
23716
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
23503
23717
  });
23504
23718
  const byName = (a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base", numeric: true });
@@ -23511,8 +23725,8 @@ async function listDirectory(requested, allowedRoots) {
23511
23725
  else if (entry.isFile()) files.push(item);
23512
23726
  }
23513
23727
  const parent = dirname6(directory);
23514
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir7() }];
23515
- for (const root of allowedRoots) if (root !== homedir7()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23728
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir8() }];
23729
+ for (const root of allowedRoots) if (root !== homedir8()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23516
23730
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
23517
23731
  return {
23518
23732
  path: directory,
@@ -23526,9 +23740,9 @@ async function listDirectory(requested, allowedRoots) {
23526
23740
 
23527
23741
  // src/workspace/workspace-manager.ts
23528
23742
  import { spawn as spawn9 } from "node:child_process";
23529
- import { chmod as chmod3, mkdir as mkdir6, mkdtemp, opendir, realpath as realpath4, rm as rm3, stat as stat4, writeFile as writeFile6 } from "node:fs/promises";
23530
- import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
23531
- import { isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5 } from "node:path";
23743
+ 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";
23744
+ import { homedir as homedir9, tmpdir as tmpdir2 } from "node:os";
23745
+ import { isAbsolute as isAbsolute4, join as join11, relative as relative3, resolve as resolve5 } from "node:path";
23532
23746
  var MAX_NODES = 2e3;
23533
23747
  var MAX_DIRECTORY_ENTRIES = 12e3;
23534
23748
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -23576,7 +23790,7 @@ var WorkspaceManager = class {
23576
23790
  };
23577
23791
  }
23578
23792
  validateRootPath(value) {
23579
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir8());
23793
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir9());
23580
23794
  const root = resolve5(raw);
23581
23795
  if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
23582
23796
  if (relative3(root, resolve5(root, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -23593,7 +23807,7 @@ var WorkspaceManager = class {
23593
23807
  requestedPaths.add(relativePath);
23594
23808
  const target = this.resolveWithinRoot(rootPath, relativePath);
23595
23809
  try {
23596
- const metadata = await stat4(target).catch(() => void 0);
23810
+ const metadata = await stat5(target).catch(() => void 0);
23597
23811
  if (metadata) {
23598
23812
  if (!metadata.isDirectory()) {
23599
23813
  throw new Error("The existing workspace path is not a directory");
@@ -23651,7 +23865,7 @@ var WorkspaceManager = class {
23651
23865
  let created = false;
23652
23866
  let metadata;
23653
23867
  try {
23654
- metadata = await stat4(target);
23868
+ metadata = await stat5(target);
23655
23869
  } catch {
23656
23870
  }
23657
23871
  if (!metadata) {
@@ -23751,7 +23965,7 @@ var WorkspaceManager = class {
23751
23965
  }
23752
23966
  async scanTree(rootPath, maxDepth, scanRoots) {
23753
23967
  const resolvedRoot = await realpath4(rootPath);
23754
- const rootMetadata = await stat4(resolvedRoot);
23968
+ const rootMetadata = await stat5(resolvedRoot);
23755
23969
  if (!rootMetadata.isDirectory()) throw new Error("The workspace root is not a directory");
23756
23970
  const nodes = [];
23757
23971
  let entriesRead = 0;
@@ -23806,7 +24020,7 @@ var WorkspaceManager = class {
23806
24020
  const target = this.resolveWithinRoot(resolvedRoot, relativePath);
23807
24021
  let metadata;
23808
24022
  try {
23809
- metadata = await stat4(target);
24023
+ metadata = await stat5(target);
23810
24024
  } catch (error62) {
23811
24025
  this.logger.warn("workspace-scan-root-missing", {
23812
24026
  rootPath: target,
@@ -23903,12 +24117,12 @@ var WorkspaceManager = class {
23903
24117
  }
23904
24118
  async createGitAuthEnvironment(auth) {
23905
24119
  if (!auth) return void 0;
23906
- const directory = await mkdtemp(join10(tmpdir2(), "toc-ocra-git-auth-"));
24120
+ const directory = await mkdtemp(join11(tmpdir2(), "toc-ocra-git-auth-"));
23907
24121
  const isWindows = process.platform === "win32";
23908
- const scriptPath = join10(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24122
+ const scriptPath = join11(directory, isWindows ? "askpass.cmd" : "askpass.sh");
23909
24123
  let script;
23910
24124
  if (isWindows) {
23911
- const helperPath = join10(directory, "askpass.cjs");
24125
+ const helperPath = join11(directory, "askpass.cjs");
23912
24126
  await writeFile6(
23913
24127
  helperPath,
23914
24128
  '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',
@@ -24058,7 +24272,7 @@ var AgentRuntime = class {
24058
24272
  }
24059
24273
  };
24060
24274
  this.workspaces = new WorkspaceManager(config2, this.logger);
24061
- this.orphans = new OrphanRegistry(join11(config2.dataDir, "active-runs.json"));
24275
+ this.orphans = new OrphanRegistry(join12(config2.dataDir, "active-runs.json"));
24062
24276
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
24063
24277
  }
24064
24278
  config;
@@ -24776,7 +24990,7 @@ function preferSystemNode() {
24776
24990
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
24777
24991
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
24778
24992
  for (const name of names) {
24779
- const candidate = directory && join12(directory, name);
24993
+ const candidate = directory && join13(directory, name);
24780
24994
  if (candidate && existsSync6(candidate)) {
24781
24995
  process.env.TOC_OCRA_NODE_PATH = candidate;
24782
24996
  return;