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.
@@ -20938,90 +20938,94 @@ function parseKiroSessions(stdout) {
20938
20938
  const parsed = JSON.parse(stdout);
20939
20939
  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 } : {} }));
20940
20940
  }
20941
- function isChrome(text) {
20942
- 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);
20943
- }
20944
- function kiroLineParser() {
20945
- let mode = "none";
20946
- let command = "";
20947
- let commandLast = false;
20948
- let reply = [];
20949
- const commandRows = (text) => {
20950
- const rows = commandLast ? [] : [runLog.command(command)];
20951
- commandLast = true;
20952
- return [...rows, ...runLog.commandOutput(text)];
20953
- };
20954
- const parse4 = (raw) => {
20955
- const event = tryJson(raw);
20956
- if (event && raw.trim().startsWith("{")) return jsonLine(event, raw);
20957
- const text = raw.replace(ANSI, "").replace(/^λ↯\s*/, "").replace(/\s+$/, "");
20958
- const trimmed = text.trim();
20959
- if (!trimmed) {
20960
- if (mode === "reply") reply.push("");
20961
- return { display: [] };
20962
- }
20963
- const answer = /^>\s?(.*)$/.exec(trimmed);
20964
- if (answer && !(command && !raw.includes("\x1B"))) {
20965
- mode = "reply";
20966
- commandLast = false;
20967
- reply = [answer[1] ?? ""];
20968
- return { message: reply.join("\n").trim(), display: runLog.reply(answer[1] ?? "") };
20969
- }
20970
- const using = /^(.*?)\s*\(using tool: ([\w@/.-]+)\)(.*)$/.exec(trimmed);
20971
- if (using) {
20972
- const [, head = "", tool = "", rest = ""] = using;
20973
- mode = "tool";
20974
- let rows;
20975
- if (tool === "shell" || tool === "execute_bash") {
20976
- command = head.replace(/^I will run the following command:\s*/i, "").trim();
20977
- commandLast = false;
20978
- rows = commandRows("");
20941
+ var KIRO_LIST_SESSIONS_TIMEOUT_MS = 6e4;
20942
+ var LIST_SESSIONS_RETRY_DELAY_MS = 1e3;
20943
+ function describeListSessionsError(error62, timeoutMs) {
20944
+ const failure2 = error62;
20945
+ if (error62 instanceof SyntaxError) return "\u4F1A\u8BDD\u5217\u8868\u4E0D\u662F\u6709\u6548\u7684 JSON";
20946
+ if (failure2?.code === "ENOENT") return "\u627E\u4E0D\u5230 kiro-cli";
20947
+ if (failure2?.killed || failure2?.signal === "SIGTERM") return `\u8BFB\u53D6\u4F1A\u8BDD\u5217\u8868\u8D85\u65F6\uFF08${Math.round(timeoutMs / 1e3)} \u79D2\uFF09`;
20948
+ if (failure2?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "\u4F1A\u8BDD\u5217\u8868\u8FC7\u5927";
20949
+ const detail = String(failure2?.stderr ?? "").replace(ANSI, "").split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
20950
+ if (typeof failure2?.code === "number") return `kiro-cli \u9000\u51FA\u7801 ${failure2.code}${detail ? `\uFF1A${detail.slice(0, 160)}` : ""}`;
20951
+ return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
20952
+ }
20953
+ async function listKiroSessions(workdir, options = {}) {
20954
+ const timeoutMs = options.timeoutMs ?? KIRO_LIST_SESSIONS_TIMEOUT_MS;
20955
+ const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20956
+ let lastError;
20957
+ for (let attempt = 0; attempt < 2; attempt++) {
20958
+ if (attempt) await new Promise((resolve7) => setTimeout(resolve7, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
20959
+ try {
20960
+ const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
20961
+ return parseKiroSessions(stdout);
20962
+ } catch (error62) {
20963
+ lastError = error62;
20964
+ if (error62?.code === "ENOENT") break;
20965
+ }
20966
+ }
20967
+ throw new Error(describeListSessionsError(lastError, timeoutMs));
20968
+ }
20969
+ function isKiroMissingSession(stderr) {
20970
+ return stderr.some((line) => /\bSession '[^']*' not found\b/i.test(line.replace(ANSI, "")));
20971
+ }
20972
+ function kiroToolRows(text) {
20973
+ const step = /^\[tool\]\s*(.*)$/.exec(text.trim())?.[1];
20974
+ if (step === void 0) return void 0;
20975
+ const status = /^status:\s*(\w+)/i.exec(step)?.[1]?.toLowerCase();
20976
+ if (status) return status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [];
20977
+ const running = /^Running:\s*(.+)$/.exec(step)?.[1]?.trim();
20978
+ if (running) return running.startsWith("@") ? [runLog.tool("mcp_tool_call")] : [runLog.command(running)];
20979
+ const changed = /^(?:Creating|Editing|Writing|Replacing|Appending to|Deleting)\s+(.+)$/i.exec(step)?.[1];
20980
+ if (changed) return [runLog.fileChange(changed.trim())];
20981
+ if (/^Searching the web\b|^Fetching\b/i.test(step)) return [runLog.tool("web_search")];
20982
+ if (/^(Reading|Searching|Finding|Listing)\b/i.test(step)) return [];
20983
+ return [runLog.tool("tool_call")];
20984
+ }
20985
+ function isKiroNoise(text) {
20986
+ return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text);
20987
+ }
20988
+ function kiroRunParser() {
20989
+ let pending = "";
20990
+ let started = false;
20991
+ let segment = [];
20992
+ const replyRows = (lines) => {
20993
+ const display = [];
20994
+ for (const raw of lines) {
20995
+ const line = raw.replace(ANSI, "").replace(/\s+$/, "");
20996
+ if (!started) {
20997
+ if (!line.trim()) continue;
20998
+ started = true;
20999
+ segment = [line];
21000
+ display.push(...runLog.reply(line));
20979
21001
  } else {
20980
- const path = /:\s*(\S+?)(?:,|$)/.exec(head)?.[1];
20981
- rows = toolCallRows(tool, path);
20982
- if (rows.length) commandLast = false;
20983
- }
20984
- const more = rest.trim() ? parse4(rest).display : [];
20985
- return { display: [...rows, ...more] };
20986
- }
20987
- if (/^Running tool\b/.test(trimmed)) {
20988
- mode = "tool";
20989
- commandLast = false;
20990
- return { display: [/\(from mcp server:/.test(trimmed) ? runLog.tool("mcp_tool_call") : runLog.tool("tool_call")] };
20991
- }
20992
- if (/^- Completed in\b/.test(trimmed)) {
20993
- const done = command && commandLast ? [runLog.commandExit(0)] : [];
20994
- if (command && commandLast) {
20995
- command = "";
20996
- commandLast = false;
20997
- }
20998
- mode = "none";
20999
- return { display: done };
21000
- }
21001
- if (isChrome(trimmed)) return { display: [] };
21002
- if (/^✓/.test(trimmed)) return { display: [] };
21003
- if (/^[✗❗]/.test(trimmed) && mode !== "reply" && !command) return { display: [runLog.error(trimmed.replace(/^[✗❗]\s*/, ""))] };
21004
- if (mode === "reply") {
21005
- reply.push(text);
21006
- return { message: reply.join("\n").trim(), display: runLog.replyMore(text) };
21007
- }
21008
- if (command) return { display: commandRows(text) };
21009
- if (mode === "tool") return { display: [] };
21010
- return { display: [text] };
21011
- };
21012
- return parse4;
21013
- }
21014
- function jsonLine(event, line) {
21015
- const sessionId = str(event.session_id) ?? str(event.sessionId);
21016
- const message = str(event.response) ?? str(event.message) ?? str(event.text);
21017
- const error62 = typeof event.error === "string" ? event.error : event.error && typeof event.error === "object" ? str(event.error.message) : void 0;
21018
- const type = str(event.type) ?? "";
21002
+ segment.push(line);
21003
+ display.push(...runLog.replyMore(line));
21004
+ }
21005
+ }
21006
+ return started ? { message: segment.join("\n").trim(), display } : { display };
21007
+ };
21008
+ const closeSegment = () => {
21009
+ const rest = pending;
21010
+ pending = "";
21011
+ const parsed = rest ? replyRows([rest]) : { display: [] };
21012
+ started = false;
21013
+ return parsed;
21014
+ };
21019
21015
  return {
21020
- ...sessionId ? { sessionId } : {},
21021
- ...message ? { message } : {},
21022
- ...error62 ? { turnError: error62 } : {},
21023
- ...message && (type === "result" || type === "turn.completed") ? { turnCompleted: true } : {},
21024
- display: message ? runLog.reply(message) : error62 ? [runLog.error(error62)] : [line]
21016
+ stdout(chunk) {
21017
+ const lines = (pending + chunk).split(/\r?\n/);
21018
+ pending = lines.pop() ?? "";
21019
+ return replyRows(lines);
21020
+ },
21021
+ stderr(raw) {
21022
+ const text = raw.replace(ANSI, "").trim();
21023
+ if (!text || isKiroNoise(text)) return { display: [] };
21024
+ const rows = kiroToolRows(text) ?? [runLog.error(text)];
21025
+ const closed = closeSegment();
21026
+ return { ...closed, display: [...closed.display, ...rows] };
21027
+ },
21028
+ end: closeSegment
21025
21029
  };
21026
21030
  }
21027
21031
  var kiroProvider = {
@@ -21036,30 +21040,18 @@ var kiroProvider = {
21036
21040
  args.push("--", request.prompt);
21037
21041
  return kiroLaunch(args);
21038
21042
  },
21039
- async listSessions(workdir) {
21040
- const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
21041
- try {
21042
- const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: 15e3, maxBuffer: 8 * 1024 * 1024 });
21043
- return parseKiroSessions(stdout);
21044
- } catch {
21045
- return void 0;
21046
- }
21047
- },
21043
+ listSessions: (workdir) => listKiroSessions(workdir),
21044
+ isMissingSession: (stderr) => isKiroMissingSession(stderr),
21048
21045
  inspectExit(context) {
21049
21046
  const businessError = kiroStderrError(context.stderr);
21050
- if (businessError) return { turnError: businessError };
21051
- const credits = context.stderr.map((line) => /^\s*▸\s*(Credits:.*)$/.exec(line.replace(ANSI, ""))?.[1]).find(Boolean);
21052
- return credits ? { display: [runLog.event(`\u672C\u8F6E\u5B8C\u6210\uFF08${credits.trim().replace(/\s*•\s*/g, " \xB7 ")}\uFF09`)] } : {};
21047
+ return businessError ? { turnError: businessError } : {};
21053
21048
  },
21049
+ /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
21054
21050
  parseLine(line) {
21055
- return kiroLineParser()(line);
21051
+ return kiroRunParser().stdout(`${line}
21052
+ `);
21056
21053
  },
21057
- createLineParser: () => kiroLineParser(),
21058
- stderrDisplay(line) {
21059
- const text = line.replace(ANSI, "").trim();
21060
- if (!text || isChrome(text)) return [];
21061
- return [line];
21062
- }
21054
+ createRunParser: () => kiroRunParser()
21063
21055
  };
21064
21056
  function kiroStderrError(stderrLines) {
21065
21057
  const text = stderrLines.join("\n");
@@ -22920,12 +22912,25 @@ var RunSupervisor = class {
22920
22912
  let sessionId = payload.session_id;
22921
22913
  let sessionsBefore;
22922
22914
  let sessionNote = "";
22915
+ let unverifiedResume = false;
22923
22916
  if (!payload.chat_session_id && provider.listSessions) {
22924
- const saved = await provider.listSessions(workdir);
22917
+ let saved;
22918
+ let listError = "";
22919
+ try {
22920
+ saved = await provider.listSessions(workdir);
22921
+ } catch (error62) {
22922
+ listError = errorMessage(error62);
22923
+ }
22925
22924
  if (!saved) {
22926
- if (sessionId) sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22925
+ this.logger.warn("list-sessions-failed", { runId: payload.run_id, agentType: provider.id, error: listError });
22926
+ if (sessionId) {
22927
+ unverifiedResume = true;
22928
+ 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
22927
22929
  `;
22928
- sessionId = "";
22930
+ } else {
22931
+ 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
22932
+ `;
22933
+ }
22929
22934
  } else if (sessionId && !saved.some((session) => session.id === sessionId)) {
22930
22935
  sessionNote = `\u25CF \u539F\u4F1A\u8BDD ${sessionId} \u4E0D\u5728\u6B64\u76EE\u5F55\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22931
22936
  `;
@@ -22972,7 +22977,9 @@ var RunSupervisor = class {
22972
22977
  agentType: provider.id,
22973
22978
  provider,
22974
22979
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
22980
+ ...provider.createRunParser ? { stream: provider.createRunParser() } : {},
22975
22981
  ...sessionsBefore ? { sessionsBefore } : {},
22982
+ ...unverifiedResume ? { unverifiedResume: payload } : {},
22976
22983
  prompt: payload.prompt,
22977
22984
  child,
22978
22985
  pid: child.pid ?? 0,
@@ -23008,12 +23015,21 @@ var RunSupervisor = class {
23008
23015
  child.once("error", (error62) => {
23009
23016
  spawnError = error62.message;
23010
23017
  });
23011
- createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
23018
+ if (run.stream) {
23019
+ child.stdout.setEncoding("utf8");
23020
+ child.stdout.on("data", (chunk) => this.applyParsed(run, run.stream.stdout(chunk), chunk));
23021
+ } else {
23022
+ createInterface3({ input: child.stdout }).on("line", (line) => this.onStdout(run, line));
23023
+ }
23012
23024
  createInterface3({ input: child.stderr }).on("line", (line) => {
23013
23025
  const clean = sanitizeTerminalLine(line);
23014
23026
  if (!clean.trim()) return;
23015
23027
  run.stderr.push(clean);
23016
23028
  if (run.stderr.length > MAX_ERROR_ROWS) run.stderr.shift();
23029
+ if (run.stream) {
23030
+ this.applyParsed(run, run.stream.stderr(line), line);
23031
+ return;
23032
+ }
23017
23033
  for (const row of provider.stderrDisplay ? provider.stderrDisplay(line) : [clean]) {
23018
23034
  const shown = sanitizeTerminalLine(row);
23019
23035
  if (shown.trim()) {
@@ -23059,7 +23075,9 @@ var RunSupervisor = class {
23059
23075
  });
23060
23076
  }
23061
23077
  onStdout(run, rawLine) {
23062
- const parsed = run.parse(rawLine);
23078
+ this.applyParsed(run, run.parse(rawLine), rawLine);
23079
+ }
23080
+ applyParsed(run, parsed, rawLine) {
23063
23081
  if (run.chat && !run.forwardingFailed) {
23064
23082
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run, sanitizeChatEvent(event));
23065
23083
  if (parsed.sessionId) run.chatReady = true;
@@ -23097,11 +23115,21 @@ var RunSupervisor = class {
23097
23115
  }
23098
23116
  async onExit(run, code, signal2, spawnError) {
23099
23117
  for (const timer of run.timers) clearTimeout(timer);
23118
+ if (run.stream) this.applyParsed(run, run.stream.end(), "");
23100
23119
  this.active.delete(run.runId);
23101
23120
  this.orphans?.remove(run.runId);
23102
23121
  if (run.eventTimer) clearTimeout(run.eventTimer);
23103
23122
  this.flushChatEvents(run);
23104
23123
  await run.eventTail;
23124
+ const retry = run.unverifiedResume;
23125
+ if (retry && code !== 0 && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && run.provider.isMissingSession?.(run.stderr)) {
23126
+ this.logger.warn("resume-session-missing", { runId: run.runId, agentType: run.agentType, sessionId: run.sessionId });
23127
+ const { task_attachments: _prepared, ...rest } = retry;
23128
+ const missing = `\u539F\u4F1A\u8BDD ${run.sessionId} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u672C\u8F6E\u6539\u4E3A\u5F00\u59CB\u65B0\u4F1A\u8BDD`;
23129
+ const notice = retry.notice ? `${retry.notice}\uFF1B${missing}` : missing;
23130
+ await this.start({ ...rest, session_id: "", notice });
23131
+ return;
23132
+ }
23105
23133
  if (!run.chat && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && run.provider.inspectExit) {
23106
23134
  try {
23107
23135
  const inspection = await run.provider.inspectExit({ exitCode: code, stderr: run.stderr, workdir: run.workdir, sessionId: run.sessionId });
@@ -23114,7 +23142,14 @@ var RunSupervisor = class {
23114
23142
  }
23115
23143
  }
23116
23144
  if (run.sessionsBefore && !run.sessionId && !spawnError && run.provider.listSessions) {
23117
- const after = await run.provider.listSessions(run.workdir).catch(() => void 0);
23145
+ let after;
23146
+ try {
23147
+ after = await run.provider.listSessions(run.workdir);
23148
+ } catch (error62) {
23149
+ run.tail.append(`\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${run.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
23150
+ `);
23151
+ this.logger.warn("list-sessions-failed", { runId: run.runId, agentType: run.agentType, error: errorMessage(error62) });
23152
+ }
23118
23153
  const created = after ? pickCreatedSession(run.sessionsBefore, after, run.prompt) : void 0;
23119
23154
  if (created) run.sessionId = created;
23120
23155
  else if (after?.some((session) => !run.sessionsBefore.has(session.id))) {
@@ -1,4 +1,4 @@
1
- import type { HeadlessProvider, SavedSession } from '../provider.js';
1
+ import type { HeadlessProvider, RunStreamParser, SavedSession } from '../provider.js';
2
2
  /**
3
3
  * Saved chats for the directory, limited to ones headless
4
4
  * `chat --no-interactive` can resume. `v3` entries are Kiro IDE / ACP sessions
@@ -6,6 +6,32 @@ import type { HeadlessProvider, SavedSession } from '../provider.js';
6
6
  * rejects the trust flags, and would also write into someone's IDE chat.
7
7
  */
8
8
  export declare function parseKiroSessions(stdout: string): SavedSession[];
9
+ /**
10
+ * `--list-sessions` loads every chat saved for the folder, so it slows down
11
+ * as chats pile up and on a busy machine (5–14 s measured with ~90 chats).
12
+ */
13
+ export declare const KIRO_LIST_SESSIONS_TIMEOUT_MS = 60000;
14
+ /** One-line, user-facing reason a session listing failed. */
15
+ export declare function describeListSessionsError(error: unknown, timeoutMs: number): string;
16
+ /**
17
+ * Saved chats for `workdir`, retried once. Rejects with a user-facing reason
18
+ * (see `describeListSessionsError`) when both attempts fail.
19
+ */
20
+ export declare function listKiroSessions(workdir: string, options?: {
21
+ timeoutMs?: number;
22
+ retryDelayMs?: number;
23
+ }): Promise<SavedSession[]>;
24
+ /** `Error: Session '<id>' not found` — Kiro has no such chat for this folder. */
25
+ export declare function isKiroMissingSession(stderr: readonly string[]): boolean;
26
+ /** One `[tool] …` stderr row → its run-log rows; undefined when it is not one. */
27
+ export declare function kiroToolRows(text: string): string[] | undefined;
28
+ /**
29
+ * One turn's parser over both streams. stdout is the reply text, written in
30
+ * segments with no break between them: a segment ends where a tool step
31
+ * starts (on stderr) or the turn ends. Each segment becomes one reply row
32
+ * (later lines indented), and `message` is the last segment — the answer.
33
+ */
34
+ export declare function kiroRunParser(): RunStreamParser;
9
35
  export declare const kiroProvider: HeadlessProvider;
10
36
  /**
11
37
  * True business-error text to surface when Kiro exits 0 but did nothing