toc-ocra 0.2.32 → 0.2.34

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
@@ -20602,90 +20602,94 @@ function parseKiroSessions(stdout) {
20602
20602
  const parsed = JSON.parse(stdout);
20603
20603
  return parsed.flatMap((entry) => entry.sessions ?? []).filter((entry) => entry.source !== "v3" && entry.sessionId && !entry.sessionId.startsWith("sess_")).map((entry) => ({ id: entry.sessionId, ...entry.title ? { title: entry.title } : {} }));
20604
20604
  }
20605
- function isChrome(text) {
20606
- 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);
20607
- }
20608
- function kiroLineParser() {
20609
- let mode = "none";
20610
- let command = "";
20611
- let commandLast = false;
20612
- let reply = [];
20613
- const commandRows = (text) => {
20614
- const rows = commandLast ? [] : [runLog.command(command)];
20615
- commandLast = true;
20616
- return [...rows, ...runLog.commandOutput(text)];
20617
- };
20618
- const parse4 = (raw) => {
20619
- const event = tryJson(raw);
20620
- if (event && raw.trim().startsWith("{")) return jsonLine(event, raw);
20621
- const text = raw.replace(ANSI, "").replace(/^λ↯\s*/, "").replace(/\s+$/, "");
20622
- const trimmed = text.trim();
20623
- if (!trimmed) {
20624
- if (mode === "reply") reply.push("");
20625
- return { display: [] };
20626
- }
20627
- const answer = /^>\s?(.*)$/.exec(trimmed);
20628
- if (answer && !(command && !raw.includes("\x1B"))) {
20629
- mode = "reply";
20630
- commandLast = false;
20631
- reply = [answer[1] ?? ""];
20632
- return { message: reply.join("\n").trim(), display: runLog.reply(answer[1] ?? "") };
20633
- }
20634
- const using = /^(.*?)\s*\(using tool: ([\w@/.-]+)\)(.*)$/.exec(trimmed);
20635
- if (using) {
20636
- const [, head = "", tool = "", rest = ""] = using;
20637
- mode = "tool";
20638
- let rows;
20639
- if (tool === "shell" || tool === "execute_bash") {
20640
- command = head.replace(/^I will run the following command:\s*/i, "").trim();
20641
- commandLast = false;
20642
- rows = commandRows("");
20605
+ var KIRO_LIST_SESSIONS_TIMEOUT_MS = 6e4;
20606
+ var LIST_SESSIONS_RETRY_DELAY_MS = 1e3;
20607
+ function describeListSessionsError(error62, timeoutMs) {
20608
+ const failure2 = error62;
20609
+ if (error62 instanceof SyntaxError) return "\u4F1A\u8BDD\u5217\u8868\u4E0D\u662F\u6709\u6548\u7684 JSON";
20610
+ if (failure2?.code === "ENOENT") return "\u627E\u4E0D\u5230 kiro-cli";
20611
+ if (failure2?.killed || failure2?.signal === "SIGTERM") return `\u8BFB\u53D6\u4F1A\u8BDD\u5217\u8868\u8D85\u65F6\uFF08${Math.round(timeoutMs / 1e3)} \u79D2\uFF09`;
20612
+ if (failure2?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "\u4F1A\u8BDD\u5217\u8868\u8FC7\u5927";
20613
+ const detail = String(failure2?.stderr ?? "").replace(ANSI, "").split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
20614
+ if (typeof failure2?.code === "number") return `kiro-cli \u9000\u51FA\u7801 ${failure2.code}${detail ? `\uFF1A${detail.slice(0, 160)}` : ""}`;
20615
+ return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
20616
+ }
20617
+ async function listKiroSessions(workdir, options = {}) {
20618
+ const timeoutMs = options.timeoutMs ?? KIRO_LIST_SESSIONS_TIMEOUT_MS;
20619
+ const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20620
+ let lastError;
20621
+ for (let attempt = 0; attempt < 2; attempt++) {
20622
+ if (attempt) await new Promise((resolve8) => setTimeout(resolve8, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
20623
+ try {
20624
+ const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
20625
+ return parseKiroSessions(stdout);
20626
+ } catch (error62) {
20627
+ lastError = error62;
20628
+ if (error62?.code === "ENOENT") break;
20629
+ }
20630
+ }
20631
+ throw new Error(describeListSessionsError(lastError, timeoutMs));
20632
+ }
20633
+ function isKiroMissingSession(stderr) {
20634
+ return stderr.some((line) => /\bSession '[^']*' not found\b/i.test(line.replace(ANSI, "")));
20635
+ }
20636
+ function kiroToolRows(text) {
20637
+ const step = /^\[tool\]\s*(.*)$/.exec(text.trim())?.[1];
20638
+ if (step === void 0) return void 0;
20639
+ const status = /^status:\s*(\w+)/i.exec(step)?.[1]?.toLowerCase();
20640
+ if (status) return status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [];
20641
+ const running = /^Running:\s*(.+)$/.exec(step)?.[1]?.trim();
20642
+ if (running) return running.startsWith("@") ? [runLog.tool("mcp_tool_call")] : [runLog.command(running)];
20643
+ const changed = /^(?:Creating|Editing|Writing|Replacing|Appending to|Deleting)\s+(.+)$/i.exec(step)?.[1];
20644
+ if (changed) return [runLog.fileChange(changed.trim())];
20645
+ if (/^Searching the web\b|^Fetching\b/i.test(step)) return [runLog.tool("web_search")];
20646
+ if (/^(Reading|Searching|Finding|Listing)\b/i.test(step)) return [];
20647
+ return [runLog.tool("tool_call")];
20648
+ }
20649
+ function isKiroNoise(text) {
20650
+ return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text);
20651
+ }
20652
+ function kiroRunParser() {
20653
+ let pending = "";
20654
+ let started = false;
20655
+ let segment = [];
20656
+ const replyRows = (lines) => {
20657
+ const display = [];
20658
+ for (const raw of lines) {
20659
+ const line = raw.replace(ANSI, "").replace(/\s+$/, "");
20660
+ if (!started) {
20661
+ if (!line.trim()) continue;
20662
+ started = true;
20663
+ segment = [line];
20664
+ display.push(...runLog.reply(line));
20643
20665
  } else {
20644
- const path = /:\s*(\S+?)(?:,|$)/.exec(head)?.[1];
20645
- rows = toolCallRows(tool, path);
20646
- if (rows.length) commandLast = false;
20647
- }
20648
- const more = rest.trim() ? parse4(rest).display : [];
20649
- return { display: [...rows, ...more] };
20650
- }
20651
- if (/^Running tool\b/.test(trimmed)) {
20652
- mode = "tool";
20653
- commandLast = false;
20654
- return { display: [/\(from mcp server:/.test(trimmed) ? runLog.tool("mcp_tool_call") : runLog.tool("tool_call")] };
20655
- }
20656
- if (/^- Completed in\b/.test(trimmed)) {
20657
- const done = command && commandLast ? [runLog.commandExit(0)] : [];
20658
- if (command && commandLast) {
20659
- command = "";
20660
- commandLast = false;
20661
- }
20662
- mode = "none";
20663
- return { display: done };
20664
- }
20665
- if (isChrome(trimmed)) return { display: [] };
20666
- if (/^✓/.test(trimmed)) return { display: [] };
20667
- if (/^[✗❗]/.test(trimmed) && mode !== "reply" && !command) return { display: [runLog.error(trimmed.replace(/^[✗❗]\s*/, ""))] };
20668
- if (mode === "reply") {
20669
- reply.push(text);
20670
- return { message: reply.join("\n").trim(), display: runLog.replyMore(text) };
20671
- }
20672
- if (command) return { display: commandRows(text) };
20673
- if (mode === "tool") return { display: [] };
20674
- return { display: [text] };
20675
- };
20676
- return parse4;
20677
- }
20678
- function jsonLine(event, line) {
20679
- const sessionId = str(event.session_id) ?? str(event.sessionId);
20680
- const message = str(event.response) ?? str(event.message) ?? str(event.text);
20681
- const error62 = typeof event.error === "string" ? event.error : event.error && typeof event.error === "object" ? str(event.error.message) : void 0;
20682
- const type = str(event.type) ?? "";
20666
+ segment.push(line);
20667
+ display.push(...runLog.replyMore(line));
20668
+ }
20669
+ }
20670
+ return started ? { message: segment.join("\n").trim(), display } : { display };
20671
+ };
20672
+ const closeSegment = () => {
20673
+ const rest = pending;
20674
+ pending = "";
20675
+ const parsed = rest ? replyRows([rest]) : { display: [] };
20676
+ started = false;
20677
+ return parsed;
20678
+ };
20683
20679
  return {
20684
- ...sessionId ? { sessionId } : {},
20685
- ...message ? { message } : {},
20686
- ...error62 ? { turnError: error62 } : {},
20687
- ...message && (type === "result" || type === "turn.completed") ? { turnCompleted: true } : {},
20688
- display: message ? runLog.reply(message) : error62 ? [runLog.error(error62)] : [line]
20680
+ stdout(chunk) {
20681
+ const lines = (pending + chunk).split(/\r?\n/);
20682
+ pending = lines.pop() ?? "";
20683
+ return replyRows(lines);
20684
+ },
20685
+ stderr(raw) {
20686
+ const text = raw.replace(ANSI, "").trim();
20687
+ if (!text || isKiroNoise(text)) return { display: [] };
20688
+ const rows = kiroToolRows(text) ?? [runLog.error(text)];
20689
+ const closed = closeSegment();
20690
+ return { ...closed, display: [...closed.display, ...rows] };
20691
+ },
20692
+ end: closeSegment
20689
20693
  };
20690
20694
  }
20691
20695
  var kiroProvider = {
@@ -20700,30 +20704,18 @@ var kiroProvider = {
20700
20704
  args.push("--", request.prompt);
20701
20705
  return kiroLaunch(args);
20702
20706
  },
20703
- async listSessions(workdir) {
20704
- const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20705
- try {
20706
- const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: 15e3, maxBuffer: 8 * 1024 * 1024 });
20707
- return parseKiroSessions(stdout);
20708
- } catch {
20709
- return void 0;
20710
- }
20711
- },
20707
+ listSessions: (workdir) => listKiroSessions(workdir),
20708
+ isMissingSession: (stderr) => isKiroMissingSession(stderr),
20712
20709
  inspectExit(context) {
20713
20710
  const businessError = kiroStderrError(context.stderr);
20714
- if (businessError) return { turnError: businessError };
20715
- const credits = context.stderr.map((line) => /^\s*▸\s*(Credits:.*)$/.exec(line.replace(ANSI, ""))?.[1]).find(Boolean);
20716
- return credits ? { display: [runLog.event(`\u672C\u8F6E\u5B8C\u6210\uFF08${credits.trim().replace(/\s*•\s*/g, " \xB7 ")}\uFF09`)] } : {};
20711
+ return businessError ? { turnError: businessError } : {};
20717
20712
  },
20713
+ /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
20718
20714
  parseLine(line) {
20719
- return kiroLineParser()(line);
20715
+ return kiroRunParser().stdout(`${line}
20716
+ `);
20720
20717
  },
20721
- createLineParser: () => kiroLineParser(),
20722
- stderrDisplay(line) {
20723
- const text = line.replace(ANSI, "").trim();
20724
- if (!text || isChrome(text)) return [];
20725
- return [line];
20726
- }
20718
+ createRunParser: () => kiroRunParser()
20727
20719
  };
20728
20720
  function kiroStderrError(stderrLines) {
20729
20721
  const text = stderrLines.join("\n");
@@ -22946,12 +22938,25 @@ var RunSupervisor = class {
22946
22938
  let sessionId = payload.session_id;
22947
22939
  let sessionsBefore;
22948
22940
  let sessionNote = "";
22941
+ let unverifiedResume = false;
22949
22942
  if (!payload.chat_session_id && provider.listSessions) {
22950
- const saved = await provider.listSessions(workdir);
22943
+ let saved;
22944
+ let listError = "";
22945
+ try {
22946
+ saved = await provider.listSessions(workdir);
22947
+ } catch (error62) {
22948
+ listError = errorMessage(error62);
22949
+ }
22951
22950
  if (!saved) {
22952
- if (sessionId) sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22951
+ this.logger.warn("list-sessions-failed", { runId: payload.run_id, agentType: provider.id, error: listError });
22952
+ if (sessionId) {
22953
+ unverifiedResume = true;
22954
+ sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF08${listError}\uFF09\uFF0C\u7EE7\u7EED\u4F7F\u7528\u539F\u4F1A\u8BDD
22953
22955
  `;
22954
- sessionId = "";
22956
+ } else {
22957
+ sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF08${listError}\uFF09\uFF0C\u672C\u8F6E\u65B0\u4F1A\u8BDD\u7ED3\u675F\u540E\u53EF\u80FD\u65E0\u6CD5\u8BB0\u5F55
22958
+ `;
22959
+ }
22955
22960
  } else if (sessionId && !saved.some((session) => session.id === sessionId)) {
22956
22961
  sessionNote = `\u25CF \u539F\u4F1A\u8BDD ${sessionId} \u4E0D\u5728\u6B64\u76EE\u5F55\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22957
22962
  `;
@@ -22998,7 +23003,9 @@ var RunSupervisor = class {
22998
23003
  agentType: provider.id,
22999
23004
  provider,
23000
23005
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
23006
+ ...provider.createRunParser ? { stream: provider.createRunParser() } : {},
23001
23007
  ...sessionsBefore ? { sessionsBefore } : {},
23008
+ ...unverifiedResume ? { unverifiedResume: payload } : {},
23002
23009
  prompt: payload.prompt,
23003
23010
  child,
23004
23011
  pid: child.pid ?? 0,
@@ -23034,12 +23041,21 @@ var RunSupervisor = class {
23034
23041
  child.once("error", (error62) => {
23035
23042
  spawnError = error62.message;
23036
23043
  });
23037
- createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run2, line));
23044
+ if (run2.stream) {
23045
+ child.stdout.setEncoding("utf8");
23046
+ child.stdout.on("data", (chunk) => this.applyParsed(run2, run2.stream.stdout(chunk), chunk));
23047
+ } else {
23048
+ createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run2, line));
23049
+ }
23038
23050
  createInterface3({ input: child.stderr }).on("line", (line) => {
23039
23051
  const clean = sanitizeTerminalLine(line);
23040
23052
  if (!clean.trim()) return;
23041
23053
  run2.stderr.push(clean);
23042
23054
  if (run2.stderr.length > MAX_ERROR_ROWS) run2.stderr.shift();
23055
+ if (run2.stream) {
23056
+ this.applyParsed(run2, run2.stream.stderr(line), line);
23057
+ return;
23058
+ }
23043
23059
  for (const row of provider.stderrDisplay ? provider.stderrDisplay(line) : [clean]) {
23044
23060
  const shown = sanitizeTerminalLine(row);
23045
23061
  if (shown.trim()) {
@@ -23085,7 +23101,9 @@ var RunSupervisor = class {
23085
23101
  });
23086
23102
  }
23087
23103
  onStdout(run2, rawLine) {
23088
- const parsed = run2.parse(rawLine);
23104
+ this.applyParsed(run2, run2.parse(rawLine), rawLine);
23105
+ }
23106
+ applyParsed(run2, parsed, rawLine) {
23089
23107
  if (run2.chat && !run2.forwardingFailed) {
23090
23108
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run2, sanitizeChatEvent(event));
23091
23109
  if (parsed.sessionId) run2.chatReady = true;
@@ -23123,11 +23141,21 @@ var RunSupervisor = class {
23123
23141
  }
23124
23142
  async onExit(run2, code2, signal2, spawnError) {
23125
23143
  for (const timer of run2.timers) clearTimeout(timer);
23144
+ if (run2.stream) this.applyParsed(run2, run2.stream.end(), "");
23126
23145
  this.active.delete(run2.runId);
23127
23146
  this.orphans?.remove(run2.runId);
23128
23147
  if (run2.eventTimer) clearTimeout(run2.eventTimer);
23129
23148
  this.flushChatEvents(run2);
23130
23149
  await run2.eventTail;
23150
+ const retry = run2.unverifiedResume;
23151
+ if (retry && code2 !== 0 && !run2.cancelRequested && !spawnError && !run2.timedOut && !run2.stalled && run2.provider.isMissingSession?.(run2.stderr)) {
23152
+ this.logger.warn("resume-session-missing", { runId: run2.runId, agentType: run2.agentType, sessionId: run2.sessionId });
23153
+ const { task_attachments: _prepared, ...rest } = retry;
23154
+ const missing = `\u539F\u4F1A\u8BDD ${run2.sessionId} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`;
23155
+ const notice = retry.notice ? `${retry.notice}\uFF1B${missing}` : missing;
23156
+ await this.start({ ...rest, session_id: "", notice });
23157
+ return;
23158
+ }
23131
23159
  if (!run2.chat && !run2.cancelRequested && !spawnError && !run2.timedOut && !run2.stalled && run2.provider.inspectExit) {
23132
23160
  try {
23133
23161
  const inspection = await run2.provider.inspectExit({ exitCode: code2, stderr: run2.stderr, workdir: run2.workdir, sessionId: run2.sessionId });
@@ -23140,7 +23168,14 @@ var RunSupervisor = class {
23140
23168
  }
23141
23169
  }
23142
23170
  if (run2.sessionsBefore && !run2.sessionId && !spawnError && run2.provider.listSessions) {
23143
- const after = await run2.provider.listSessions(run2.workdir).catch(() => void 0);
23171
+ let after;
23172
+ try {
23173
+ after = await run2.provider.listSessions(run2.workdir);
23174
+ } catch (error62) {
23175
+ run2.tail.append(`\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${run2.agentType} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF08${errorMessage(error62)}\uFF09\uFF0C\u672C\u8F6E\u4F1A\u8BDD\u672A\u80FD\u8BB0\u5F55\uFF0C\u4E0B\u8F6E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD
23176
+ `);
23177
+ this.logger.warn("list-sessions-failed", { runId: run2.runId, agentType: run2.agentType, error: errorMessage(error62) });
23178
+ }
23144
23179
  const created = after ? pickCreatedSession(run2.sessionsBefore, after, run2.prompt) : void 0;
23145
23180
  if (created) run2.sessionId = created;
23146
23181
  else if (after?.some((session) => !run2.sessionsBefore.has(session.id))) {