toc-ocra 0.2.33 → 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.
package/dist/cli/cli.mjs CHANGED
@@ -12,7 +12,7 @@ import { createHash as createHash4 } from "node:crypto";
12
12
  import { existsSync as existsSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
13
13
  import { tmpdir as tmpdir3 } from "node:os";
14
14
  import { createRequire } from "node:module";
15
- import { dirname as dirname8, join as join12, resolve as resolve7 } from "node:path";
15
+ import { dirname as dirname8, join as join13, resolve as resolve7 } from "node:path";
16
16
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
17
17
 
18
18
  // src/config.ts
@@ -20592,6 +20592,145 @@ var grokProvider = {
20592
20592
  // src/providers/cli/kiro.ts
20593
20593
  import { execFile } from "node:child_process";
20594
20594
  import { promisify } from "node:util";
20595
+
20596
+ // src/providers/cli/kiro-session-log.ts
20597
+ import { open as open2, readdir, readFile as readFile2, stat } from "node:fs/promises";
20598
+ import { homedir as homedir5 } from "node:os";
20599
+ import { join as join6 } from "node:path";
20600
+ var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
20601
+ function kiroSessionsDirectory() {
20602
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join6(homedir5(), ".kiro", "sessions", "cli");
20603
+ }
20604
+ var KiroSessionLog = class {
20605
+ constructor(options) {
20606
+ this.options = options;
20607
+ }
20608
+ options;
20609
+ path;
20610
+ offset = 0;
20611
+ partial = "";
20612
+ steps = [];
20613
+ results = /* @__PURE__ */ new Map();
20614
+ claimed = /* @__PURE__ */ new Set();
20615
+ get directory() {
20616
+ return this.options.directory ?? kiroSessionsDirectory();
20617
+ }
20618
+ /** Called before the CLI starts: a resumed log is followed from its current end. */
20619
+ async begin() {
20620
+ if (!this.options.sessionId) return;
20621
+ this.path = join6(this.directory, `${this.options.sessionId}.jsonl`);
20622
+ this.offset = await stat(this.path).then((info) => info.size, () => 0);
20623
+ }
20624
+ /**
20625
+ * A fresh turn's chat has no known id: the one log for this folder created
20626
+ * after the turn started. Several candidates (another turn starting a chat
20627
+ * in the same folder) leave it unknown.
20628
+ */
20629
+ async findFreshLog() {
20630
+ const names = await readdir(this.directory).catch(() => []);
20631
+ const found = [];
20632
+ for (const name of names) {
20633
+ if (!name.endsWith(".json")) continue;
20634
+ const meta3 = await readFile2(join6(this.directory, name), "utf8").then((text) => JSON.parse(text), () => void 0);
20635
+ const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
20636
+ if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
20637
+ }
20638
+ if (found.length === 1) this.path = join6(this.directory, `${found[0]}.jsonl`);
20639
+ }
20640
+ /** Reads entries appended since the last call. */
20641
+ async refresh() {
20642
+ if (!this.path) await this.findFreshLog();
20643
+ if (!this.path) return;
20644
+ const file2 = await open2(this.path, "r").catch(() => void 0);
20645
+ if (!file2) return;
20646
+ try {
20647
+ const { size } = await file2.stat();
20648
+ if (size <= this.offset) return;
20649
+ const buffer = Buffer.alloc(size - this.offset);
20650
+ await file2.read(buffer, 0, buffer.length, this.offset);
20651
+ this.offset = size;
20652
+ const lines = (this.partial + buffer.toString("utf8")).split("\n");
20653
+ this.partial = lines.pop() ?? "";
20654
+ for (const line of lines) this.take(line);
20655
+ } finally {
20656
+ await file2.close();
20657
+ }
20658
+ }
20659
+ take(line) {
20660
+ let entry;
20661
+ try {
20662
+ entry = JSON.parse(line);
20663
+ } catch {
20664
+ return;
20665
+ }
20666
+ for (const part of entry.data?.content ?? []) {
20667
+ const data = part.data ?? {};
20668
+ if (part.kind === "toolUse" && SHELL_TOOLS.has(String(data.name))) {
20669
+ const command = data.input?.command;
20670
+ if (typeof data.toolUseId === "string" && typeof command === "string") this.steps.push({ id: data.toolUseId, command });
20671
+ } else if (part.kind === "toolResult" && typeof data.toolUseId === "string") {
20672
+ this.results.set(data.toolUseId, resultOf(data));
20673
+ }
20674
+ }
20675
+ }
20676
+ /** The shell step a `[tool] Running:` row announced (its text may be cut short). */
20677
+ async step(shown, waitMs = 2e3) {
20678
+ const prefix = shown.replace(/\.\.\.$|…$/, "").trim();
20679
+ const deadline = Date.now() + waitMs;
20680
+ for (; ; ) {
20681
+ await this.refresh();
20682
+ const step = this.steps.find((item) => !this.claimed.has(item.id) && item.command.trim().startsWith(prefix));
20683
+ if (step) {
20684
+ this.claimed.add(step.id);
20685
+ return step;
20686
+ }
20687
+ if (Date.now() >= deadline) return void 0;
20688
+ await new Promise((resolve8) => setTimeout(resolve8, 150));
20689
+ }
20690
+ }
20691
+ /** The first of `ids` whose result is in the log, waiting up to `waitMs`. */
20692
+ async firstFinished(ids, waitMs) {
20693
+ const deadline = Date.now() + waitMs;
20694
+ for (; ; ) {
20695
+ await this.refresh();
20696
+ const id = ids.find((item) => this.results.has(item));
20697
+ if (id || Date.now() >= deadline) return id;
20698
+ await new Promise((resolve8) => setTimeout(resolve8, 150));
20699
+ }
20700
+ }
20701
+ async result(id, waitMs = 3e3) {
20702
+ const deadline = Date.now() + waitMs;
20703
+ for (; ; ) {
20704
+ await this.refresh();
20705
+ const result = this.results.get(id);
20706
+ if (result || Date.now() >= deadline) return result;
20707
+ await new Promise((resolve8) => setTimeout(resolve8, 200));
20708
+ }
20709
+ }
20710
+ };
20711
+ function resultOf(data) {
20712
+ const parts = Array.isArray(data.content) ? data.content : [];
20713
+ const texts = [];
20714
+ let exitCode;
20715
+ for (const part of parts) {
20716
+ if (part.kind === "json" && part.data && typeof part.data === "object") {
20717
+ const value = part.data;
20718
+ const code2 = /(-?\d+)/.exec(String(value.exit_status ?? ""))?.[1];
20719
+ if (code2 !== void 0) exitCode = Number(code2);
20720
+ for (const text of [value.stdout, value.stderr]) if (typeof text === "string" && text.trim()) texts.push(text.replace(/\s+$/, ""));
20721
+ } else if (part.kind === "text" && typeof part.data === "string" && part.data.trim()) {
20722
+ texts.push(part.data.replace(/\s+$/, ""));
20723
+ }
20724
+ }
20725
+ if (exitCode === void 0 && data.status === "error") exitCode = 1;
20726
+ return { ...exitCode === void 0 ? {} : { exitCode }, output: texts.join("\n") };
20727
+ }
20728
+ function sameFolder(a, b) {
20729
+ const normal = (path) => path.replace(/\/+$/, "").replace(/^\/private(?=\/)/, "");
20730
+ return normal(a) === normal(b);
20731
+ }
20732
+
20733
+ // src/providers/cli/kiro.ts
20595
20734
  var execFileAsync = promisify(execFile);
20596
20735
  var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
20597
20736
  function kiroLaunch(args) {
@@ -20615,7 +20754,7 @@ function describeListSessionsError(error62, timeoutMs) {
20615
20754
  return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
20616
20755
  }
20617
20756
  async function listKiroSessions(workdir, options = {}) {
20618
- const timeoutMs = options.timeoutMs ?? KIRO_LIST_SESSIONS_TIMEOUT_MS;
20757
+ const timeoutMs = options.timeoutMs ?? (Number(process.env.TOC_OCRA_KIRO_LIST_TIMEOUT_MS) || KIRO_LIST_SESSIONS_TIMEOUT_MS);
20619
20758
  const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20620
20759
  let lastError;
20621
20760
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -20633,90 +20772,124 @@ async function listKiroSessions(workdir, options = {}) {
20633
20772
  function isKiroMissingSession(stderr) {
20634
20773
  return stderr.some((line) => /\bSession '[^']*' not found\b/i.test(line.replace(ANSI, "")));
20635
20774
  }
20636
- function isChrome(text) {
20637
- return /^(⋮|▸|●)/.test(text) || /^Purpose:/.test(text) || /^All tools are now trusted\b/.test(text) || /^Agents can sometimes do unexpected things\b/.test(text) || /^Learn more at\b/.test(text);
20638
- }
20639
- function kiroLineParser() {
20640
- let mode = "none";
20641
- let command = "";
20642
- let commandLast = false;
20643
- let reply = [];
20644
- const commandRows = (text) => {
20645
- const rows = commandLast ? [] : [runLog.command(command)];
20646
- commandLast = true;
20647
- return [...rows, ...runLog.commandOutput(text)];
20648
- };
20649
- const parse4 = (raw) => {
20650
- const event = tryJson(raw);
20651
- if (event && raw.trim().startsWith("{")) return jsonLine(event, raw);
20652
- const text = raw.replace(ANSI, "").replace(/^λ↯\s*/, "").replace(/\s+$/, "");
20653
- const trimmed = text.trim();
20654
- if (!trimmed) {
20655
- if (mode === "reply") reply.push("");
20656
- return { display: [] };
20657
- }
20658
- const answer = /^>\s?(.*)$/.exec(trimmed);
20659
- if (answer && !(command && !raw.includes("\x1B"))) {
20660
- mode = "reply";
20661
- commandLast = false;
20662
- reply = [answer[1] ?? ""];
20663
- return { message: reply.join("\n").trim(), display: runLog.reply(answer[1] ?? "") };
20664
- }
20665
- const using = /^(.*?)\s*\(using tool: ([\w@/.-]+)\)(.*)$/.exec(trimmed);
20666
- if (using) {
20667
- const [, head = "", tool = "", rest = ""] = using;
20668
- mode = "tool";
20669
- let rows;
20670
- if (tool === "shell" || tool === "execute_bash") {
20671
- command = head.replace(/^I will run the following command:\s*/i, "").trim();
20672
- commandLast = false;
20673
- rows = commandRows("");
20775
+ function kiroToolRows(text) {
20776
+ const step = /^\[tool\]\s*(.*)$/.exec(text.trim())?.[1];
20777
+ if (step === void 0) return void 0;
20778
+ const status = /^status:\s*(\w+)/i.exec(step)?.[1]?.toLowerCase();
20779
+ if (status) return status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [];
20780
+ const running = /^Running:\s*(.+)$/.exec(step)?.[1]?.trim();
20781
+ if (running) return running.startsWith("@") ? [runLog.tool("mcp_tool_call")] : [runLog.command(running)];
20782
+ const changed = /^(?:Creating|Editing|Writing|Replacing|Appending to|Deleting)\s+(.+)$/i.exec(step)?.[1];
20783
+ if (changed) return [runLog.fileChange(changed.trim())];
20784
+ if (/^Searching the web\b|^Fetching\b/i.test(step)) return [runLog.tool("web_search")];
20785
+ if (/^(Reading|Searching|Finding|Listing)\b/i.test(step)) return [];
20786
+ return [runLog.tool("tool_call")];
20787
+ }
20788
+ function isKiroNoise(text) {
20789
+ return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text);
20790
+ }
20791
+ function kiroRunParser(context) {
20792
+ let pending = "";
20793
+ let started = false;
20794
+ let segment = [];
20795
+ const log = context ? new KiroSessionLog({ sessionId: context.sessionId, workdir: context.workdir, startedAt: context.startedAt }) : void 0;
20796
+ const ready = log?.begin().catch(() => void 0);
20797
+ let queue = Promise.resolve();
20798
+ const openSteps = [];
20799
+ let lastHeader;
20800
+ const out = (parsed) => {
20801
+ if (!context) return typeof parsed === "function" ? { display: [] } : parsed;
20802
+ queue = queue.then(async () => {
20803
+ const value = typeof parsed === "function" ? await parsed().catch(() => ({ display: [] })) : parsed;
20804
+ if (value.display.length && typeof parsed !== "function") lastHeader = void 0;
20805
+ context.emit(value);
20806
+ });
20807
+ return { display: [] };
20808
+ };
20809
+ const finishShell = async (step, status) => {
20810
+ const found = await step.shell.lookup;
20811
+ const result = found ? await log.result(found.id, 1e3) : void 0;
20812
+ const header = step.shell.headerShown && lastHeader === step ? [] : [runLog.command(found?.command ?? step.shell.shown)];
20813
+ lastHeader = void 0;
20814
+ if (!result) return { display: [...header, ...status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : []] };
20815
+ return { display: [...header, ...runLog.commandOutput(result.output), runLog.commandExit(result.exitCode ?? (status === "failed" ? 1 : 0))] };
20816
+ };
20817
+ const replyRows = (lines) => {
20818
+ const display = [];
20819
+ for (const raw of lines) {
20820
+ const line = raw.replace(ANSI, "").replace(/\s+$/, "");
20821
+ if (!started) {
20822
+ if (!line.trim()) continue;
20823
+ started = true;
20824
+ segment = [line];
20825
+ display.push(...runLog.reply(line));
20674
20826
  } else {
20675
- const path = /:\s*(\S+?)(?:,|$)/.exec(head)?.[1];
20676
- rows = toolCallRows(tool, path);
20677
- if (rows.length) commandLast = false;
20678
- }
20679
- const more = rest.trim() ? parse4(rest).display : [];
20680
- return { display: [...rows, ...more] };
20681
- }
20682
- if (/^Running tool\b/.test(trimmed)) {
20683
- mode = "tool";
20684
- commandLast = false;
20685
- return { display: [/\(from mcp server:/.test(trimmed) ? runLog.tool("mcp_tool_call") : runLog.tool("tool_call")] };
20686
- }
20687
- if (/^- Completed in\b/.test(trimmed)) {
20688
- const done = command && commandLast ? [runLog.commandExit(0)] : [];
20689
- if (command && commandLast) {
20690
- command = "";
20691
- commandLast = false;
20692
- }
20693
- mode = "none";
20694
- return { display: done };
20695
- }
20696
- if (isChrome(trimmed)) return { display: [] };
20697
- if (/^✓/.test(trimmed)) return { display: [] };
20698
- if (/^[✗❗]/.test(trimmed) && mode !== "reply" && !command) return { display: [runLog.error(trimmed.replace(/^[✗❗]\s*/, ""))] };
20699
- if (mode === "reply") {
20700
- reply.push(text);
20701
- return { message: reply.join("\n").trim(), display: runLog.replyMore(text) };
20702
- }
20703
- if (command) return { display: commandRows(text) };
20704
- if (mode === "tool") return { display: [] };
20705
- return { display: [text] };
20706
- };
20707
- return parse4;
20708
- }
20709
- function jsonLine(event, line) {
20710
- const sessionId = str(event.session_id) ?? str(event.sessionId);
20711
- const message = str(event.response) ?? str(event.message) ?? str(event.text);
20712
- const error62 = typeof event.error === "string" ? event.error : event.error && typeof event.error === "object" ? str(event.error.message) : void 0;
20713
- const type = str(event.type) ?? "";
20827
+ segment.push(line);
20828
+ display.push(...runLog.replyMore(line));
20829
+ }
20830
+ }
20831
+ return started ? { message: segment.join("\n").trim(), display } : { display };
20832
+ };
20833
+ const closeSegment = () => {
20834
+ const rest = pending;
20835
+ pending = "";
20836
+ const parsed = rest ? replyRows([rest]) : { display: [] };
20837
+ started = false;
20838
+ return parsed;
20839
+ };
20714
20840
  return {
20715
- ...sessionId ? { sessionId } : {},
20716
- ...message ? { message } : {},
20717
- ...error62 ? { turnError: error62 } : {},
20718
- ...message && (type === "result" || type === "turn.completed") ? { turnCompleted: true } : {},
20719
- display: message ? runLog.reply(message) : error62 ? [runLog.error(error62)] : [line]
20841
+ stdout(chunk) {
20842
+ const lines = (pending + chunk).split(/\r?\n/);
20843
+ pending = lines.pop() ?? "";
20844
+ return out(replyRows(lines));
20845
+ },
20846
+ stderr(raw) {
20847
+ const text = raw.replace(ANSI, "").trim();
20848
+ if (!text || isKiroNoise(text)) return { display: [] };
20849
+ const closed = closeSegment();
20850
+ const status = /^\[tool\]\s*status:\s*(\w+)/i.exec(text)?.[1]?.toLowerCase();
20851
+ if (!log) {
20852
+ const rows2 = kiroToolRows(text) ?? [runLog.error(text)];
20853
+ return out({ ...closed, display: [...closed.display, ...rows2] });
20854
+ }
20855
+ out(closed);
20856
+ const running = /^\[tool\]\s*Running:\s*(.+)$/.exec(text)?.[1]?.trim();
20857
+ if (running && !running.startsWith("@")) {
20858
+ const step = { shell: { shown: running, lookup: (async () => {
20859
+ await ready;
20860
+ return log.step(running);
20861
+ })(), headerShown: !openSteps.some((item) => item.shell) } };
20862
+ openSteps.push(step);
20863
+ if (!step.shell.headerShown) return { display: [] };
20864
+ return out(async () => {
20865
+ const found = await step.shell.lookup;
20866
+ lastHeader = step;
20867
+ return { display: [runLog.command(found?.command ?? running)] };
20868
+ });
20869
+ }
20870
+ if (status) {
20871
+ return out(async () => {
20872
+ const shells = openSteps.filter((item) => item.shell);
20873
+ const ids = (await Promise.all(shells.map((item) => item.shell.lookup))).map((found) => found?.id ?? "");
20874
+ const others = openSteps.some((item) => !item.shell);
20875
+ const id = shells.length ? await log.firstFinished(ids.filter(Boolean), others ? 1200 : 3e3) : void 0;
20876
+ const step = id ? shells[ids.indexOf(id)] : openSteps.find((item) => !item.shell) ?? openSteps[0];
20877
+ if (step) openSteps.splice(openSteps.indexOf(step), 1);
20878
+ if (step?.shell) return finishShell(step, status);
20879
+ lastHeader = void 0;
20880
+ return { display: status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [] };
20881
+ });
20882
+ }
20883
+ if (/^\[tool\]/.test(text)) openSteps.push({});
20884
+ const rows = kiroToolRows(text) ?? [runLog.error(text)];
20885
+ return out({ display: rows });
20886
+ },
20887
+ end: async () => {
20888
+ const rest = out(closeSegment());
20889
+ if (!context) return rest;
20890
+ await queue;
20891
+ return { display: [] };
20892
+ }
20720
20893
  };
20721
20894
  }
20722
20895
  var kiroProvider = {
@@ -20735,19 +20908,14 @@ var kiroProvider = {
20735
20908
  isMissingSession: (stderr) => isKiroMissingSession(stderr),
20736
20909
  inspectExit(context) {
20737
20910
  const businessError = kiroStderrError(context.stderr);
20738
- if (businessError) return { turnError: businessError };
20739
- const credits = context.stderr.map((line) => /^\s*▸\s*(Credits:.*)$/.exec(line.replace(ANSI, ""))?.[1]).find(Boolean);
20740
- return credits ? { display: [runLog.event(`\u672C\u8F6E\u5B8C\u6210\uFF08${credits.trim().replace(/\s*•\s*/g, " \xB7 ")}\uFF09`)] } : {};
20911
+ return businessError ? { turnError: businessError } : {};
20741
20912
  },
20913
+ /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
20742
20914
  parseLine(line) {
20743
- return kiroLineParser()(line);
20915
+ return kiroRunParser().stdout(`${line}
20916
+ `);
20744
20917
  },
20745
- createLineParser: () => kiroLineParser(),
20746
- stderrDisplay(line) {
20747
- const text = line.replace(ANSI, "").trim();
20748
- if (!text || isChrome(text)) return [];
20749
- return [line];
20750
- }
20918
+ createRunParser: (context) => kiroRunParser(context)
20751
20919
  };
20752
20920
  function kiroStderrError(stderrLines) {
20753
20921
  const text = stderrLines.join("\n");
@@ -20927,7 +21095,7 @@ import { dirname as dirname7, resolve as resolve6 } from "node:path";
20927
21095
  import { fileURLToPath } from "node:url";
20928
21096
 
20929
21097
  // src/health/server.ts
20930
- import { readFile as readFile2 } from "node:fs/promises";
21098
+ import { readFile as readFile3 } from "node:fs/promises";
20931
21099
  import { createServer } from "node:http";
20932
21100
  var ControlError = class extends Error {
20933
21101
  constructor(status, message, code2 = "bad_request") {
@@ -21108,7 +21276,7 @@ var HealthServer = class {
21108
21276
  }
21109
21277
  async recentEvents() {
21110
21278
  try {
21111
- const raw = await readFile2(this.logFile, "utf8");
21279
+ const raw = await readFile3(this.logFile, "utf8");
21112
21280
  return raw.trim().split("\n").slice(-60).flatMap((line) => {
21113
21281
  try {
21114
21282
  const parsed = JSON.parse(line);
@@ -21285,7 +21453,7 @@ function createDiagnosticLogger(filePath, options = {}) {
21285
21453
 
21286
21454
  // src/runtime/agent-runtime.ts
21287
21455
  import { randomUUID as randomUUID3 } from "node:crypto";
21288
- import { join as join11 } from "node:path";
21456
+ import { join as join12 } from "node:path";
21289
21457
 
21290
21458
  // src/exec/script-runner.ts
21291
21459
  import { spawn as spawn3 } from "node:child_process";
@@ -21690,13 +21858,13 @@ function resolveChatProvider(type, request, attachments) {
21690
21858
 
21691
21859
  // src/providers/model-catalog-collector.ts
21692
21860
  import { createHash } from "node:crypto";
21693
- import { stat } from "node:fs/promises";
21861
+ import { stat as stat2 } from "node:fs/promises";
21694
21862
 
21695
21863
  // src/providers/model-catalog.ts
21696
21864
  import { spawn as spawn5 } from "node:child_process";
21697
- import { readFile as readFile3 } from "node:fs/promises";
21698
- import { homedir as homedir5 } from "node:os";
21699
- import { isAbsolute, join as join6, resolve as resolve2 } from "node:path";
21865
+ import { readFile as readFile4 } from "node:fs/promises";
21866
+ import { homedir as homedir6 } from "node:os";
21867
+ import { isAbsolute, join as join7, resolve as resolve2 } from "node:path";
21700
21868
 
21701
21869
  // src/providers/kiro-models.ts
21702
21870
  import { spawn as spawn4 } from "node:child_process";
@@ -21818,15 +21986,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
21818
21986
  if (defaultModel) catalog.default_model = defaultModel;
21819
21987
  return catalog;
21820
21988
  }
21821
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir5(), ".claude");
21822
- var codexHome = () => process.env.CODEX_HOME?.trim() || join6(homedir5(), ".codex");
21823
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join6(homedir5(), ".gemini");
21824
- var grokHome = () => process.env.GROK_HOME?.trim() || join6(homedir5(), ".grok");
21825
- var opencodeHome = () => join6(process.env.XDG_CONFIG_HOME?.trim() || join6(homedir5(), ".config"), "opencode");
21826
- var kiroHome = () => join6(homedir5(), ".kiro");
21989
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir6(), ".claude");
21990
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join7(homedir6(), ".codex");
21991
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join7(homedir6(), ".gemini");
21992
+ var grokHome = () => process.env.GROK_HOME?.trim() || join7(homedir6(), ".grok");
21993
+ var opencodeHome = () => join7(process.env.XDG_CONFIG_HOME?.trim() || join7(homedir6(), ".config"), "opencode");
21994
+ var kiroHome = () => join7(homedir6(), ".kiro");
21827
21995
  async function readClaudeModelCatalog() {
21828
21996
  const home = claudeHome();
21829
- const content = await readFile3(join6(home, "settings.json"), "utf8").catch(() => "");
21997
+ const content = await readFile4(join7(home, "settings.json"), "utf8").catch(() => "");
21830
21998
  let settings = {};
21831
21999
  if (content) {
21832
22000
  try {
@@ -21882,16 +22050,16 @@ async function readCodexModels(codexHome2, config2) {
21882
22050
  const configuredCatalog = configValue(config2, "model_catalog_json");
21883
22051
  if (configuredCatalog) {
21884
22052
  const catalogPath = isAbsolute(configuredCatalog) ? configuredCatalog : resolve2(codexHome2, configuredCatalog);
21885
- const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
22053
+ const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
21886
22054
  if (configuredModels?.length) return configuredModels;
21887
22055
  }
21888
22056
  return parseCodexModels(
21889
- await readFile3(join6(codexHome2, "models_cache.json"), "utf8").catch(() => "")
22057
+ await readFile4(join7(codexHome2, "models_cache.json"), "utf8").catch(() => "")
21890
22058
  ) ?? [];
21891
22059
  }
21892
22060
  async function readCodexModelCatalog() {
21893
22061
  const home = codexHome();
21894
- const config2 = await readFile3(join6(home, "config.toml"), "utf8").catch(() => "");
22062
+ const config2 = await readFile4(join7(home, "config.toml"), "utf8").catch(() => "");
21895
22063
  const models = await readCodexModels(home, config2);
21896
22064
  const defaultModel = configValue(config2, "model");
21897
22065
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -21981,8 +22149,8 @@ async function readKiroModelCatalog() {
21981
22149
  };
21982
22150
  const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
21983
22151
  const [payload, content] = await Promise.all([
21984
- readKiroNativeModels(launch, homedir5(), { catalog: base }),
21985
- readFile3(join6(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
22152
+ readKiroNativeModels(launch, homedir6(), { catalog: base }),
22153
+ readFile4(join7(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21986
22154
  ]);
21987
22155
  let settings;
21988
22156
  try {
@@ -22039,7 +22207,7 @@ function geminiModelsUrl(baseUrl) {
22039
22207
  }
22040
22208
  async function readGeminiModelCatalog() {
22041
22209
  const fileEnvironment = parseEnvFile(
22042
- await readFile3(join6(geminiHome(), ".env"), "utf8").catch(() => "")
22210
+ await readFile4(join7(geminiHome(), ".env"), "utf8").catch(() => "")
22043
22211
  );
22044
22212
  const environment = { ...fileEnvironment, ...process.env };
22045
22213
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -22084,7 +22252,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
22084
22252
  return catalog;
22085
22253
  }
22086
22254
  async function readGrokModelCatalog() {
22087
- const config2 = await readFile3(join6(grokHome(), "config.toml"), "utf8").catch(() => "");
22255
+ const config2 = await readFile4(join7(grokHome(), "config.toml"), "utf8").catch(() => "");
22088
22256
  const output2 = await runModelListCommand(resolveCliCommand("grok"), ["models"], "grok");
22089
22257
  const catalog = parseGrokModelCatalog(output2, config2);
22090
22258
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22103,7 +22271,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
22103
22271
  return catalog;
22104
22272
  }
22105
22273
  async function readOpencodeModelCatalog() {
22106
- const config2 = await readFile3(join6(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join6(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22274
+ const config2 = await readFile4(join7(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join7(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22107
22275
  const output2 = await runModelListCommand(resolveCliCommand("opencode"), ["models"], "opencode");
22108
22276
  const catalog = parseOpencodeModelCatalog(output2, config2);
22109
22277
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22111,22 +22279,22 @@ async function readOpencodeModelCatalog() {
22111
22279
  }
22112
22280
  var TEN_MINUTES = 10 * 60 * 1e3;
22113
22281
  var MODEL_SOURCES = {
22114
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join6(claudeHome(), "settings.json")] },
22282
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join7(claudeHome(), "settings.json")] },
22115
22283
  codex: {
22116
22284
  read: readCodexModelCatalog,
22117
22285
  watchFiles: () => {
22118
22286
  const home = codexHome();
22119
- return [join6(home, "config.toml"), join6(home, "models_cache.json")];
22287
+ return [join7(home, "config.toml"), join7(home, "models_cache.json")];
22120
22288
  },
22121
22289
  // model_catalog_json may point anywhere; a periodic re-read covers it.
22122
22290
  refreshEveryMs: TEN_MINUTES
22123
22291
  },
22124
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join6(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22125
- grok: { read: readGrokModelCatalog, watchFiles: () => [join6(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22126
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join6(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22292
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join7(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22293
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join7(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22294
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join7(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22127
22295
  opencode: {
22128
22296
  read: readOpencodeModelCatalog,
22129
- watchFiles: () => [join6(opencodeHome(), "opencode.json"), join6(opencodeHome(), "opencode.jsonc")],
22297
+ watchFiles: () => [join7(opencodeHome(), "opencode.json"), join7(opencodeHome(), "opencode.jsonc")],
22130
22298
  refreshEveryMs: TEN_MINUTES
22131
22299
  }
22132
22300
  };
@@ -22134,7 +22302,7 @@ var MODEL_SOURCES = {
22134
22302
  // src/providers/model-catalog-collector.ts
22135
22303
  async function fileStamp(path) {
22136
22304
  try {
22137
- const info = await stat(path);
22305
+ const info = await stat2(path);
22138
22306
  return `${path}:${info.mtimeMs}:${info.size}`;
22139
22307
  } catch {
22140
22308
  return `${path}:-`;
@@ -22369,16 +22537,16 @@ async function readCLIQuotaReport(agentType) {
22369
22537
  }
22370
22538
 
22371
22539
  // src/providers/tb-switch-control.ts
22372
- import { readFile as readFile4 } from "node:fs/promises";
22373
- import { homedir as homedir6 } from "node:os";
22374
- import { join as join7 } from "node:path";
22540
+ import { readFile as readFile5 } from "node:fs/promises";
22541
+ import { homedir as homedir7 } from "node:os";
22542
+ import { join as join8 } from "node:path";
22375
22543
  function dataDir() {
22376
- return process.env.TB_SWITCH_HOME?.trim() || join7(homedir6(), ".tb-switch");
22544
+ return process.env.TB_SWITCH_HOME?.trim() || join8(homedir7(), ".tb-switch");
22377
22545
  }
22378
22546
  async function readLocalService() {
22379
22547
  let discovery;
22380
22548
  try {
22381
- discovery = JSON.parse(await readFile4(join7(dataDir(), "api.json"), "utf8"));
22549
+ discovery = JSON.parse(await readFile5(join8(dataDir(), "api.json"), "utf8"));
22382
22550
  } catch {
22383
22551
  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");
22384
22552
  }
@@ -22394,7 +22562,7 @@ async function readLocalService() {
22394
22562
  }
22395
22563
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
22396
22564
  try {
22397
- token = (await readFile4(join7(dataDir(), "api-token"), "utf8")).trim();
22565
+ token = (await readFile5(join8(dataDir(), "api-token"), "utf8")).trim();
22398
22566
  } catch {
22399
22567
  }
22400
22568
  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");
@@ -22485,7 +22653,7 @@ async function controlTbSwitch(payload) {
22485
22653
 
22486
22654
  // src/runs/orphan-registry.ts
22487
22655
  import { execFile as execFile4 } from "node:child_process";
22488
- import { mkdir as mkdir3, readFile as readFile5, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22656
+ import { mkdir as mkdir3, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22489
22657
  import { basename, dirname as dirname5 } from "node:path";
22490
22658
 
22491
22659
  // src/runs/process-tree.ts
@@ -22581,7 +22749,7 @@ var OrphanRegistry = class {
22581
22749
  async reapPrevious() {
22582
22750
  let previous = [];
22583
22751
  try {
22584
- previous = JSON.parse(await readFile5(this.file, "utf8"));
22752
+ previous = JSON.parse(await readFile6(this.file, "utf8"));
22585
22753
  } catch {
22586
22754
  return [];
22587
22755
  }
@@ -22611,8 +22779,8 @@ function commandOf(pid) {
22611
22779
 
22612
22780
  // src/runs/run-supervisor.ts
22613
22781
  import { spawn as spawn8 } from "node:child_process";
22614
- import { mkdir as mkdir5, realpath as realpath2, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
22615
- import { basename as basename3, isAbsolute as isAbsolute3, join as join9, relative as relative2, resolve as resolve3 } from "node:path";
22782
+ import { mkdir as mkdir5, realpath as realpath2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
22783
+ import { basename as basename3, isAbsolute as isAbsolute3, join as join10, relative as relative2, resolve as resolve3 } from "node:path";
22616
22784
  import { createInterface as createInterface3 } from "node:readline";
22617
22785
 
22618
22786
  // src/session/terminal-line-sanitizer.ts
@@ -22738,8 +22906,8 @@ function clipToCharacterBudget(rows, budget) {
22738
22906
  // src/runs/task-attachments.ts
22739
22907
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
22740
22908
  import { constants as constants2 } from "node:fs";
22741
- import { lstat, mkdir as mkdir4, open as open2, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22742
- import { basename as basename2, isAbsolute as isAbsolute2, join as join8, relative } from "node:path";
22909
+ import { lstat, mkdir as mkdir4, open as open3, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22910
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join9, relative } from "node:path";
22743
22911
  function within(root, path) {
22744
22912
  const segment = relative(root, path);
22745
22913
  return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
@@ -22747,7 +22915,7 @@ function within(root, path) {
22747
22915
  async function attachmentDirectory(workdir, messageId) {
22748
22916
  let directory = workdir;
22749
22917
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
22750
- directory = join8(directory, segment);
22918
+ directory = join9(directory, segment);
22751
22919
  await mkdir4(directory, { mode: 448 }).catch((error62) => {
22752
22920
  if (error62.code !== "EEXIST") throw error62;
22753
22921
  });
@@ -22755,7 +22923,7 @@ async function attachmentDirectory(workdir, messageId) {
22755
22923
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
22756
22924
  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");
22757
22925
  }
22758
- if (segment === ".echo") await writeFile4(join8(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
22926
+ if (segment === ".echo") await writeFile4(join9(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
22759
22927
  if (error62.code !== "EEXIST") throw error62;
22760
22928
  });
22761
22929
  }
@@ -22764,7 +22932,7 @@ async function attachmentDirectory(workdir, messageId) {
22764
22932
  async function matches(path, size, sha256, signal2) {
22765
22933
  const metadata = await lstat(path).catch(() => void 0);
22766
22934
  if (!metadata?.isFile() || metadata.isSymbolicLink() || metadata.size !== size) return false;
22767
- const file2 = await open2(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
22935
+ const file2 = await open3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
22768
22936
  try {
22769
22937
  const hash2 = createHash2("sha256");
22770
22938
  let read = 0;
@@ -22792,9 +22960,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
22792
22960
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
22793
22961
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
22794
22962
  const name = characters.join("") || "attachment";
22795
- const path = join8(directory, `${file2.file_id}-${name}`);
22963
+ const path = join9(directory, `${file2.file_id}-${name}`);
22796
22964
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
22797
- const temporary = join8(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
22965
+ const temporary = join9(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
22798
22966
  try {
22799
22967
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
22800
22968
  signal2.throwIfAborted();
@@ -23057,6 +23225,16 @@ var RunSupervisor = class {
23057
23225
  lastLine: "",
23058
23226
  lastOutputAt: Date.now()
23059
23227
  };
23228
+ if (provider.createRunParser) {
23229
+ run2.stream = provider.createRunParser({
23230
+ workdir,
23231
+ sessionId,
23232
+ startedAt: run2.startedAt,
23233
+ emit: (parsed) => {
23234
+ if (this.active.has(run2.runId)) this.applyParsed(run2, parsed, "");
23235
+ }
23236
+ });
23237
+ }
23060
23238
  this.active.set(run2.runId, run2);
23061
23239
  this.preparing.delete(run2.runId);
23062
23240
  this.unreported.add(run2.runId);
@@ -23072,12 +23250,21 @@ var RunSupervisor = class {
23072
23250
  child.once("error", (error62) => {
23073
23251
  spawnError = error62.message;
23074
23252
  });
23075
- createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run2, line));
23253
+ if (run2.stream) {
23254
+ child.stdout.setEncoding("utf8");
23255
+ child.stdout.on("data", (chunk) => this.applyParsed(run2, run2.stream.stdout(chunk), chunk));
23256
+ } else {
23257
+ createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run2, line));
23258
+ }
23076
23259
  createInterface3({ input: child.stderr }).on("line", (line) => {
23077
23260
  const clean = sanitizeTerminalLine(line);
23078
23261
  if (!clean.trim()) return;
23079
23262
  run2.stderr.push(clean);
23080
23263
  if (run2.stderr.length > MAX_ERROR_ROWS) run2.stderr.shift();
23264
+ if (run2.stream) {
23265
+ this.applyParsed(run2, run2.stream.stderr(line), line);
23266
+ return;
23267
+ }
23081
23268
  for (const row of provider.stderrDisplay ? provider.stderrDisplay(line) : [clean]) {
23082
23269
  const shown = sanitizeTerminalLine(row);
23083
23270
  if (shown.trim()) {
@@ -23123,7 +23310,9 @@ var RunSupervisor = class {
23123
23310
  });
23124
23311
  }
23125
23312
  onStdout(run2, rawLine) {
23126
- const parsed = run2.parse(rawLine);
23313
+ this.applyParsed(run2, run2.parse(rawLine), rawLine);
23314
+ }
23315
+ applyParsed(run2, parsed, rawLine) {
23127
23316
  if (run2.chat && !run2.forwardingFailed) {
23128
23317
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run2, sanitizeChatEvent(event));
23129
23318
  if (parsed.sessionId) run2.chatReady = true;
@@ -23161,6 +23350,7 @@ var RunSupervisor = class {
23161
23350
  }
23162
23351
  async onExit(run2, code2, signal2, spawnError) {
23163
23352
  for (const timer of run2.timers) clearTimeout(timer);
23353
+ if (run2.stream) this.applyParsed(run2, await run2.stream.end(), "");
23164
23354
  this.active.delete(run2.runId);
23165
23355
  this.orphans?.remove(run2.runId);
23166
23356
  if (run2.eventTimer) clearTimeout(run2.eventTimer);
@@ -23296,13 +23486,13 @@ var RunSupervisor = class {
23296
23486
  async prepareChatAttachments(payload) {
23297
23487
  if (!payload.attachments?.length) return [];
23298
23488
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
23299
- const directory = join9(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23489
+ const directory = join10(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23300
23490
  await mkdir5(directory, { recursive: true, mode: 448 });
23301
23491
  const files = [];
23302
23492
  for (const attachment of payload.attachments) {
23303
23493
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
23304
- const path = join9(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23305
- const existing = await stat2(path).catch(() => void 0);
23494
+ const path = join10(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23495
+ const existing = await stat3(path).catch(() => void 0);
23306
23496
  if (!existing?.isFile()) {
23307
23497
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
23308
23498
  await writeFile5(path, data, { mode: 384 });
@@ -23340,10 +23530,15 @@ var RunSupervisor = class {
23340
23530
  if (live) return live;
23341
23531
  return [...this.recent.values()].filter((run2) => run2.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
23342
23532
  };
23343
- const target = byId(query.runId) ?? byWorkstation(query.workstationId);
23344
- if (!target) {
23345
- return { status: "idle", lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23346
- }
23533
+ const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23534
+ if (query.runId) {
23535
+ const run2 = byId(query.runId);
23536
+ if (!run2) return { ...empty, status: this.preparing.has(query.runId) ? "running" : "idle", run_id: query.runId };
23537
+ const read2 = run2.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23538
+ return { ...read2, status: this.active.has(run2.runId) ? "running" : "finished", run_id: run2.runId };
23539
+ }
23540
+ const target = byWorkstation(query.workstationId);
23541
+ if (!target) return { ...empty, status: "idle" };
23347
23542
  const read = target.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23348
23543
  return { ...read, status: this.active.has(target.runId) ? "running" : "finished", run_id: target.runId };
23349
23544
  }
@@ -23533,17 +23728,17 @@ var GatewayClient = class {
23533
23728
  };
23534
23729
 
23535
23730
  // src/workspace/directory-browser.ts
23536
- import { readdir, realpath as realpath3, stat as stat3 } from "node:fs/promises";
23537
- import { homedir as homedir7 } from "node:os";
23731
+ import { readdir as readdir2, realpath as realpath3, stat as stat4 } from "node:fs/promises";
23732
+ import { homedir as homedir8 } from "node:os";
23538
23733
  import { dirname as dirname6, parse as parse3, resolve as resolve4 } from "node:path";
23539
23734
  var MAX_ENTRIES = 1e3;
23540
23735
  async function listDirectory(requested, allowedRoots) {
23541
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir7()) || homedir7();
23736
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir8()) || homedir8();
23542
23737
  const directory = await realpath3(resolve4(raw)).catch(() => {
23543
23738
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
23544
23739
  });
23545
- if (!(await stat3(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23546
- const entries = await readdir(directory, { withFileTypes: true }).catch((error62) => {
23740
+ if (!(await stat4(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23741
+ const entries = await readdir2(directory, { withFileTypes: true }).catch((error62) => {
23547
23742
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
23548
23743
  });
23549
23744
  const byName = (a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base", numeric: true });
@@ -23556,8 +23751,8 @@ async function listDirectory(requested, allowedRoots) {
23556
23751
  else if (entry.isFile()) files.push(item);
23557
23752
  }
23558
23753
  const parent = dirname6(directory);
23559
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir7() }];
23560
- for (const root of allowedRoots) if (root !== homedir7()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23754
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir8() }];
23755
+ for (const root of allowedRoots) if (root !== homedir8()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23561
23756
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
23562
23757
  return {
23563
23758
  path: directory,
@@ -23571,9 +23766,9 @@ async function listDirectory(requested, allowedRoots) {
23571
23766
 
23572
23767
  // src/workspace/workspace-manager.ts
23573
23768
  import { spawn as spawn9 } from "node:child_process";
23574
- 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";
23575
- import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
23576
- import { isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5 } from "node:path";
23769
+ 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";
23770
+ import { homedir as homedir9, tmpdir as tmpdir2 } from "node:os";
23771
+ import { isAbsolute as isAbsolute4, join as join11, relative as relative3, resolve as resolve5 } from "node:path";
23577
23772
  var MAX_NODES = 2e3;
23578
23773
  var MAX_DIRECTORY_ENTRIES = 12e3;
23579
23774
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -23621,7 +23816,7 @@ var WorkspaceManager = class {
23621
23816
  };
23622
23817
  }
23623
23818
  validateRootPath(value) {
23624
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir8());
23819
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir9());
23625
23820
  const root = resolve5(raw);
23626
23821
  if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
23627
23822
  if (relative3(root, resolve5(root, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -23638,7 +23833,7 @@ var WorkspaceManager = class {
23638
23833
  requestedPaths.add(relativePath);
23639
23834
  const target = this.resolveWithinRoot(rootPath, relativePath);
23640
23835
  try {
23641
- const metadata = await stat4(target).catch(() => void 0);
23836
+ const metadata = await stat5(target).catch(() => void 0);
23642
23837
  if (metadata) {
23643
23838
  if (!metadata.isDirectory()) {
23644
23839
  throw new Error("The existing workspace path is not a directory");
@@ -23696,7 +23891,7 @@ var WorkspaceManager = class {
23696
23891
  let created = false;
23697
23892
  let metadata;
23698
23893
  try {
23699
- metadata = await stat4(target);
23894
+ metadata = await stat5(target);
23700
23895
  } catch {
23701
23896
  }
23702
23897
  if (!metadata) {
@@ -23796,7 +23991,7 @@ var WorkspaceManager = class {
23796
23991
  }
23797
23992
  async scanTree(rootPath, maxDepth, scanRoots) {
23798
23993
  const resolvedRoot = await realpath4(rootPath);
23799
- const rootMetadata = await stat4(resolvedRoot);
23994
+ const rootMetadata = await stat5(resolvedRoot);
23800
23995
  if (!rootMetadata.isDirectory()) throw new Error("The workspace root is not a directory");
23801
23996
  const nodes = [];
23802
23997
  let entriesRead = 0;
@@ -23851,7 +24046,7 @@ var WorkspaceManager = class {
23851
24046
  const target = this.resolveWithinRoot(resolvedRoot, relativePath);
23852
24047
  let metadata;
23853
24048
  try {
23854
- metadata = await stat4(target);
24049
+ metadata = await stat5(target);
23855
24050
  } catch (error62) {
23856
24051
  this.logger.warn("workspace-scan-root-missing", {
23857
24052
  rootPath: target,
@@ -23948,12 +24143,12 @@ var WorkspaceManager = class {
23948
24143
  }
23949
24144
  async createGitAuthEnvironment(auth) {
23950
24145
  if (!auth) return void 0;
23951
- const directory = await mkdtemp(join10(tmpdir2(), "toc-ocra-git-auth-"));
24146
+ const directory = await mkdtemp(join11(tmpdir2(), "toc-ocra-git-auth-"));
23952
24147
  const isWindows = process.platform === "win32";
23953
- const scriptPath = join10(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24148
+ const scriptPath = join11(directory, isWindows ? "askpass.cmd" : "askpass.sh");
23954
24149
  let script;
23955
24150
  if (isWindows) {
23956
- const helperPath = join10(directory, "askpass.cjs");
24151
+ const helperPath = join11(directory, "askpass.cjs");
23957
24152
  await writeFile6(
23958
24153
  helperPath,
23959
24154
  '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',
@@ -24103,7 +24298,7 @@ var AgentRuntime = class {
24103
24298
  }
24104
24299
  };
24105
24300
  this.workspaces = new WorkspaceManager(config2, this.logger);
24106
- this.orphans = new OrphanRegistry(join11(config2.dataDir, "active-runs.json"));
24301
+ this.orphans = new OrphanRegistry(join12(config2.dataDir, "active-runs.json"));
24107
24302
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
24108
24303
  }
24109
24304
  config;
@@ -24811,7 +25006,7 @@ async function runService(options = {}) {
24811
25006
  }
24812
25007
 
24813
25008
  // src/index.ts
24814
- var { currentInstallation, installShared, ensureIdle, compareVersions } = createRequire(import.meta.url)(join12(agentPackageRoot(), "scripts", "installation.cjs"));
25009
+ var { currentInstallation, installShared, ensureIdle, compareVersions } = createRequire(import.meta.url)(join13(agentPackageRoot(), "scripts", "installation.cjs"));
24815
25010
  async function run() {
24816
25011
  try {
24817
25012
  await runService();
@@ -24914,7 +25109,7 @@ async function update(args) {
24914
25109
  if (customConfig) process.env.TOC_OCRA_CONFIG = resolve7(customConfig);
24915
25110
  await ensureIdle();
24916
25111
  const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
24917
- const temporary = mkdtempSync(join12(tmpdir3(), "toc-ocra-update-"));
25112
+ const temporary = mkdtempSync(join13(tmpdir3(), "toc-ocra-update-"));
24918
25113
  try {
24919
25114
  const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
24920
25115
  if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -24941,7 +25136,7 @@ async function update(args) {
24941
25136
  }
24942
25137
  const archive = Buffer.concat(chunks);
24943
25138
  if (`sha512-${createHash4("sha512").update(archive).digest("base64")}` !== dist.integrity) throw new Error("\u8BBE\u5907\u4EE3\u7406\u5B89\u88C5\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u5347\u7EA7");
24944
- const archivePath = join12(temporary, "toc-ocra.tgz");
25139
+ const archivePath = join13(temporary, "toc-ocra.tgz");
24945
25140
  writeFileSync3(archivePath, archive, { mode: 384 });
24946
25141
  const install = spawnSync(npmCommand, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath], { stdio: "inherit", shell: false });
24947
25142
  if (install.error) throw install.error;
@@ -24950,7 +25145,7 @@ async function update(args) {
24950
25145
  return;
24951
25146
  }
24952
25147
  const previousVersion = agentVersion();
24953
- const current = await installShared(join12(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync6(defaultConfigPath()) });
25148
+ const current = await installShared(join13(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync6(defaultConfigPath()) });
24954
25149
  if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
24955
25150
  `);
24956
25151
  else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
@@ -24976,7 +25171,7 @@ async function main() {
24976
25171
  const shared = currentInstallation();
24977
25172
  if (root && root.split(/[\\/]/).includes("node_modules") && root !== shared?.root) {
24978
25173
  const selected = !shared || compareVersions(agentVersion(), shared.version) > 0 ? await installShared(root) : shared;
24979
- await import(pathToFileURL(join12(selected.root, "dist", "cli", "cli.mjs")).href);
25174
+ await import(pathToFileURL(join13(selected.root, "dist", "cli", "cli.mjs")).href);
24980
25175
  return;
24981
25176
  }
24982
25177
  const command = process.argv[2] ?? "run";