toc-ocra 0.2.28 → 0.2.29

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.
@@ -16669,8 +16669,8 @@ function rewriteKeyNames(ctx) {
16669
16669
  bySchema.set(entry.schema, entry);
16670
16670
  }
16671
16671
  const rewrites = /* @__PURE__ */ new Map();
16672
- for (const record3 of pendingRecords.get(ctx) ?? []) {
16673
- const seen = ctx.seen.get(record3);
16672
+ for (const record4 of pendingRecords.get(ctx) ?? []) {
16673
+ const seen = ctx.seen.get(record4);
16674
16674
  const names = (seen?.def ?? seen?.schema)?.propertyNames;
16675
16675
  if (!names || names === true || rewrites.has(names))
16676
16676
  continue;
@@ -20622,6 +20622,42 @@ function getVersionManagerBinPaths(options = {}) {
20622
20622
  }
20623
20623
 
20624
20624
  // src/providers/provider.ts
20625
+ function pickCreatedSession(before, after, prompt) {
20626
+ const created = after.filter((session) => !before.has(session.id));
20627
+ if (created.length <= 1) return created[0]?.id;
20628
+ const flat = (text) => text.replace(/\s+/g, " ").trim();
20629
+ const wanted = flat(prompt);
20630
+ const titled = created.filter((session) => {
20631
+ const title = flat(session.title ?? "").replace(/(\.\.\.|…)$/, "").trim();
20632
+ return title.length > 0 && wanted.startsWith(title);
20633
+ });
20634
+ return titled.length === 1 ? titled[0].id : void 0;
20635
+ }
20636
+ var runLog = {
20637
+ event: (text) => `\u25CF ${text}`,
20638
+ error: (text) => `\u2717 ${clip(text)}`,
20639
+ reply: (text) => textRows("\u203A ", text),
20640
+ /** Rows continuing the previous reply. */
20641
+ replyMore: (text) => text.split(/\r?\n/).map((row) => ` ${row}`),
20642
+ thinking: (text) => textRows("\u2026 ", clip(text, 600), 8),
20643
+ command: (command) => `$ ${clip(command)}`,
20644
+ commandOutput: (output2) => output2 ? textRows(" ", clip(output2, 2e3), 20) : [],
20645
+ commandExit: (code) => ` (exit ${typeof code === "number" ? code : "?"})`,
20646
+ fileChange: (path) => `\u270E \u4FEE\u6539\u6587\u4EF6${path ? ` ${path}` : ""}`,
20647
+ /** A tool call without its own row type, by the kinds the clients name. */
20648
+ tool: (kind) => `\xB7 ${kind}`
20649
+ };
20650
+ var EDIT_TOOLS = /^(edit|multiedit|write|notebookedit|fs_write|write_file|edit_file|create_file|str_replace|apply_patch|create)$/;
20651
+ var READ_TOOLS = /^(read|fs_read|glob|grep|ls|list|code|view|search_files|find|read_file|list_directory)$/;
20652
+ function toolCallRows(name, path) {
20653
+ const tool = name.trim().toLowerCase();
20654
+ if (EDIT_TOOLS.test(tool)) return [runLog.fileChange(path)];
20655
+ if (READ_TOOLS.test(tool)) return [];
20656
+ if (tool.startsWith("mcp__") || tool.startsWith("@")) return [runLog.tool("mcp_tool_call")];
20657
+ if (/web_?(search|fetch)/.test(tool)) return [runLog.tool("web_search")];
20658
+ if (/todo/.test(tool)) return [runLog.tool("todo_list")];
20659
+ return [runLog.tool("tool_call")];
20660
+ }
20625
20661
  function providerEnvironment() {
20626
20662
  const env = { ...process.env };
20627
20663
  const commandPaths = [
@@ -20695,32 +20731,92 @@ var claudeProvider = {
20695
20731
  return resolveExecutable("claude", args, env, process.env.TOC_OCRA_CLAUDE_PATH);
20696
20732
  },
20697
20733
  parseLine(line) {
20734
+ return claudeLineParser()(line);
20735
+ },
20736
+ createLineParser: () => claudeLineParser()
20737
+ };
20738
+ var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
20739
+ function toolResultText(content) {
20740
+ if (typeof content === "string") return content;
20741
+ if (Array.isArray(content)) return content.map((part) => str(record2(part).text) ?? "").filter(Boolean).join("\n");
20742
+ return "";
20743
+ }
20744
+ function claudeLineParser() {
20745
+ const shells = /* @__PURE__ */ new Map();
20746
+ let lastShell = "";
20747
+ let started = false;
20748
+ return (line) => {
20698
20749
  const event = tryJson(line);
20699
20750
  if (!event) return { display: line.trim() ? [line] : [] };
20751
+ if (event.parent_tool_use_id) return { display: [] };
20700
20752
  const sessionId = str(event.session_id);
20701
20753
  const base = sessionId ? { sessionId } : {};
20702
20754
  switch (str(event.type)) {
20703
- case "result": {
20704
- const text = str(event.result) ?? "";
20705
- if (event.is_error === true) return { ...base, turnError: text || "claude failed", display: [`\u2717 ${clip(text)}`] };
20706
- return { ...base, message: text, turnCompleted: true, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"] };
20755
+ case "system": {
20756
+ if (started || str(event.subtype) !== "init") return { ...base, display: [] };
20757
+ started = true;
20758
+ return { ...base, display: [`\u25CF \u4F1A\u8BDD ${sessionId ?? ""}`, runLog.event("\u5F00\u59CB\u5904\u7406")] };
20707
20759
  }
20708
20760
  case "assistant": {
20709
- const content = event.message?.content ?? [];
20710
- const rows = content.flatMap((part) => {
20711
- if (part.type === "text") return textRows("\u203A ", str(part.text) ?? "");
20712
- if (part.type === "tool_use") return [`$ ${str(part.name) ?? "tool"} ${clip(JSON.stringify(part.input ?? {}), 200)}`];
20713
- return [];
20714
- });
20761
+ const content = record2(event.message).content ?? [];
20762
+ const rows = [];
20763
+ for (const value of Array.isArray(content) ? content : []) {
20764
+ const part = record2(value);
20765
+ if (part.type === "text") {
20766
+ if (str(part.text)) rows.push(...runLog.reply(String(part.text)));
20767
+ lastShell = "";
20768
+ continue;
20769
+ }
20770
+ if (part.type === "thinking") {
20771
+ if (str(part.thinking)) rows.push(...runLog.thinking(String(part.thinking)));
20772
+ lastShell = "";
20773
+ continue;
20774
+ }
20775
+ if (part.type !== "tool_use") continue;
20776
+ const name = str(part.name) ?? "tool";
20777
+ const input2 = record2(part.input);
20778
+ const id = str(part.id) ?? "";
20779
+ if (name === "Bash") {
20780
+ const command = str(input2.command) ?? "";
20781
+ shells.set(id, command);
20782
+ rows.push(runLog.command(command));
20783
+ lastShell = id;
20784
+ continue;
20785
+ }
20786
+ rows.push(...toolCallRows(name, str(input2.file_path) ?? str(input2.notebook_path)));
20787
+ lastShell = "";
20788
+ }
20715
20789
  return { ...base, display: rows };
20716
20790
  }
20717
- case "system":
20718
- return { ...base, display: sessionId ? [`\u25CF \u4F1A\u8BDD ${sessionId}`] : [] };
20791
+ case "user": {
20792
+ const content = record2(event.message).content ?? [];
20793
+ const rows = [];
20794
+ for (const value of Array.isArray(content) ? content : []) {
20795
+ const part = record2(value);
20796
+ if (part.type !== "tool_result") continue;
20797
+ const id = str(part.tool_use_id) ?? "";
20798
+ const command = shells.get(id);
20799
+ if (command === void 0) {
20800
+ if (part.is_error === true) rows.push(runLog.error(toolResultText(part.content) || "\u5DE5\u5177\u8C03\u7528\u5931\u8D25"));
20801
+ continue;
20802
+ }
20803
+ shells.delete(id);
20804
+ if (lastShell !== id) rows.push(runLog.command(command));
20805
+ rows.push(...runLog.commandOutput(toolResultText(part.content)), runLog.commandExit(part.is_error === true ? 1 : 0));
20806
+ lastShell = "";
20807
+ }
20808
+ return { ...base, display: rows };
20809
+ }
20810
+ case "result": {
20811
+ const text = str(event.result) ?? "";
20812
+ if (event.is_error === true) return { ...base, turnError: text || "claude failed", display: [runLog.error(text || "Claude \u672C\u8F6E\u6267\u884C\u5931\u8D25")] };
20813
+ return { ...base, message: text, turnCompleted: true, display: [runLog.event("\u672C\u8F6E\u5B8C\u6210")] };
20814
+ }
20719
20815
  default:
20720
20816
  return { ...base, display: [] };
20721
20817
  }
20722
- }
20723
- };
20818
+ };
20819
+ }
20724
20820
 
20725
20821
  // src/providers/cli/codex.ts
20726
20822
  var codexProvider = {
@@ -20830,44 +20926,103 @@ var grokProvider = {
20830
20926
  };
20831
20927
 
20832
20928
  // src/providers/cli/kiro.ts
20833
- import { execFile, execFileSync } from "node:child_process";
20929
+ import { execFile } from "node:child_process";
20834
20930
  import { promisify } from "node:util";
20835
20931
  var execFileAsync = promisify(execFile);
20836
- function isNoiseLine(text) {
20837
- if (!text) return true;
20838
- if (text.startsWith("\u22EE") || text.startsWith("\u25B8") || text.startsWith("\u25CF")) return true;
20839
- if (/^Running tool\b/.test(text)) return true;
20840
- if (/^- Completed in\b/.test(text)) return true;
20841
- if (/^All tools are now trusted\b/.test(text)) return true;
20842
- if (/^Agents can sometimes do unexpected things\b/.test(text)) return true;
20843
- if (/^Learn more at\b/.test(text)) return true;
20844
- return false;
20845
- }
20932
+ var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
20846
20933
  function kiroLaunch(args) {
20847
20934
  return resolveExecutable("kiro-cli", args, providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
20848
20935
  }
20849
20936
  var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
20850
- function parseSessions(stdout) {
20937
+ function parseKiroSessions(stdout) {
20851
20938
  const parsed = JSON.parse(stdout);
20852
- return parsed.flatMap((entry) => entry.sessions ?? []).filter((entry) => entry.source !== "v3" && !entry.sessionId?.startsWith("sess_")).sort((a, b) => Date.parse(b.updatedAt ?? "") - Date.parse(a.updatedAt ?? ""));
20853
- }
20854
- async function latestSessionId(workdir) {
20855
- const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20856
- try {
20857
- const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: 1e4, maxBuffer: 4 * 1024 * 1024 });
20858
- return str(parseSessions(stdout)[0]?.sessionId);
20859
- } catch {
20860
- return void 0;
20861
- }
20862
- }
20863
- function resumableSession(sessionId, workdir) {
20864
- const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20865
- try {
20866
- const stdout = execFileSync(executable, args, { cwd: workdir, env, timeout: 1e4, maxBuffer: 4 * 1024 * 1024, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
20867
- return parseSessions(stdout).some((entry) => entry.sessionId === sessionId);
20868
- } catch {
20869
- return false;
20870
- }
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
+ }
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("");
20979
+ } 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) ?? "";
21019
+ 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]
21025
+ };
20871
21026
  }
20872
21027
  var kiroProvider = {
20873
21028
  id: "kiro",
@@ -20877,44 +21032,33 @@ var kiroProvider = {
20877
21032
  else args.push("--trust-tools=@doer/echo_report_task_progress");
20878
21033
  if (request.model) args.push("--model", request.model);
20879
21034
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20880
- if (request.sessionId && resumableSession(request.sessionId, request.workdir)) args.push("--resume-id", request.sessionId);
21035
+ if (request.sessionId && !request.sessionId.startsWith("sess_")) args.push("--resume-id", request.sessionId);
20881
21036
  args.push("--", request.prompt);
20882
21037
  return kiroLaunch(args);
20883
21038
  },
20884
- async inspectExit(context) {
20885
- const inspection = {};
20886
- const businessError = kiroStderrError(context.stderr);
20887
- if (businessError) inspection.turnError = businessError;
20888
- if (!inspection.turnError) {
20889
- const sessionId = await latestSessionId(context.workdir);
20890
- if (sessionId) inspection.sessionId = sessionId;
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;
20891
21046
  }
20892
- return inspection;
21047
+ },
21048
+ inspectExit(context) {
21049
+ 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`)] } : {};
20893
21053
  },
20894
21054
  parseLine(line) {
20895
- if (/^\s*⋮/.test(line)) return { display: [] };
20896
- const event = tryJson(line);
20897
- if (event) {
20898
- const sessionId = str(event.session_id) ?? str(event.sessionId);
20899
- const message = str(event.response) ?? str(event.message) ?? str(event.text);
20900
- const error62 = typeof event.error === "string" ? event.error : event.error && typeof event.error === "object" ? str(event.error.message) : void 0;
20901
- const type = str(event.type) ?? "";
20902
- return {
20903
- ...sessionId ? { sessionId } : {},
20904
- ...message ? { message } : {},
20905
- ...error62 ? { turnError: error62 } : {},
20906
- ...message && (type === "result" || type === "turn.completed") ? { turnCompleted: true } : {},
20907
- display: message ? textRows("\u203A ", message) : error62 ? [`\u2717 ${error62}`] : [line]
20908
- };
20909
- }
20910
- const text = line.replace(/^λ↯\s*/, "").trim();
20911
- if (!text) return { display: [] };
20912
- const answer = text.match(/^>\s?(.*)$/);
20913
- if (answer && answer[1]?.trim()) {
20914
- return { message: answer[1].trim(), display: [`\u203A ${answer[1].trim()}`] };
20915
- }
20916
- if (isNoiseLine(text)) return { display: [] };
20917
- return { display: [line.replace(/^λ↯\s*/, "")] };
21055
+ return kiroLineParser()(line);
21056
+ },
21057
+ createLineParser: () => kiroLineParser(),
21058
+ stderrDisplay(line) {
21059
+ const text = line.replace(ANSI, "").trim();
21060
+ if (!text || isChrome(text)) return [];
21061
+ return [line];
20918
21062
  }
20919
21063
  };
20920
21064
  function kiroStderrError(stderrLines) {
@@ -21337,8 +21481,8 @@ function codexChatProvider(request, attachments) {
21337
21481
  }
21338
21482
 
21339
21483
  // src/providers/chat/claude-stream-json.ts
21340
- var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21341
- var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record2(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21484
+ var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21485
+ var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record3(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21342
21486
  function claudeChatProvider(attachments) {
21343
21487
  let messageID = "";
21344
21488
  let messageSequence = 0;
@@ -21368,14 +21512,14 @@ function claudeChatProvider(attachments) {
21368
21512
  const events = [];
21369
21513
  if (envelope.parent_tool_use_id) return { ...base, display: [] };
21370
21514
  if (envelope.type === "stream_event") {
21371
- const event = record2(envelope.event);
21515
+ const event = record3(envelope.event);
21372
21516
  const index = Number(event.index ?? 0);
21373
21517
  if (event.type === "message_start") {
21374
- messageID = str(record2(event.message).id) ?? `message:${++messageSequence}`;
21518
+ messageID = str(record3(event.message).id) ?? `message:${++messageSequence}`;
21375
21519
  blocks.clear();
21376
21520
  } else if (event.type === "content_block_start") {
21377
21521
  if (!messageID) messageID = `message:${++messageSequence}`;
21378
- const part = record2(event.content_block);
21522
+ const part = record3(event.content_block);
21379
21523
  const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21380
21524
  if (!["tool_use", "thinking", "text"].includes(String(part.type))) return { ...base, display: [] };
21381
21525
  const block = { id: type === "tool_call" ? str(part.id) ?? `${messageID}:${index}` : `${messageID}:${index}`, type, name: str(part.name) ?? "tool", text: String(part.text ?? part.thinking ?? ""), input: part.input ?? {}, partialInput: "" };
@@ -21384,7 +21528,7 @@ function claudeChatProvider(attachments) {
21384
21528
  events.push(asItem(block, "in_progress"));
21385
21529
  } else if (event.type === "content_block_delta") {
21386
21530
  const block = blocks.get(index);
21387
- const delta = record2(event.delta);
21531
+ const delta = record3(event.delta);
21388
21532
  if (!block) return { ...base, display: [] };
21389
21533
  if (delta.type === "text_delta" || delta.type === "thinking_delta") {
21390
21534
  const text = String(delta.text ?? delta.thinking ?? "");
@@ -21401,11 +21545,11 @@ function claudeChatProvider(attachments) {
21401
21545
  if (block && block.type !== "tool_call") events.push(asItem(block, "completed"));
21402
21546
  }
21403
21547
  } else if (envelope.type === "assistant") {
21404
- const message = record2(envelope.message);
21548
+ const message = record3(envelope.message);
21405
21549
  const id = str(message.id) || messageID || `message:${++messageSequence}`;
21406
21550
  const parts = Array.isArray(message.content) ? message.content : [];
21407
21551
  parts.forEach((value, index) => {
21408
- const part = record2(value);
21552
+ const part = record3(value);
21409
21553
  if (!["text", "thinking", "tool_use"].includes(String(part.type))) return;
21410
21554
  const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21411
21555
  const block = { id: type === "tool_call" ? str(part.id) ?? `${id}:${index}` : `${id}:${index}`, type, name: str(part.name) ?? "tool", text: String(part.text ?? part.thinking ?? ""), input: part.input ?? {}, partialInput: "" };
@@ -21414,9 +21558,9 @@ function claudeChatProvider(attachments) {
21414
21558
  events.push(asItem(block, type === "tool_call" ? "in_progress" : "completed"));
21415
21559
  });
21416
21560
  } else if (envelope.type === "user") {
21417
- const message = record2(envelope.message);
21561
+ const message = record3(envelope.message);
21418
21562
  for (const value of Array.isArray(message.content) ? message.content : []) {
21419
- const part = record2(value);
21563
+ const part = record3(value);
21420
21564
  if (part.type !== "tool_result") continue;
21421
21565
  const id = str(part.tool_use_id);
21422
21566
  if (!id) continue;
@@ -22323,8 +22467,8 @@ var OrphanRegistry = class {
22323
22467
  file;
22324
22468
  records = /* @__PURE__ */ new Map();
22325
22469
  writing = Promise.resolve();
22326
- add(record3) {
22327
- this.records.set(record3.runId, record3);
22470
+ add(record4) {
22471
+ this.records.set(record4.runId, record4);
22328
22472
  this.persist();
22329
22473
  }
22330
22474
  remove(runId) {
@@ -22348,12 +22492,12 @@ var OrphanRegistry = class {
22348
22492
  return [];
22349
22493
  }
22350
22494
  const reaped = [];
22351
- for (const record3 of previous) {
22352
- if (!record3 || typeof record3.pid !== "number" || record3.pid <= 1) continue;
22353
- const command = await commandOf(record3.pid);
22354
- if (command && command.includes(basename(record3.executable))) {
22355
- await killProcessTree(record3.pid);
22356
- reaped.push(record3);
22495
+ for (const record4 of previous) {
22496
+ if (!record4 || typeof record4.pid !== "number" || record4.pid <= 1) continue;
22497
+ const command = await commandOf(record4.pid);
22498
+ if (command && command.includes(basename(record4.executable))) {
22499
+ await killProcessTree(record4.pid);
22500
+ reaped.push(record4);
22357
22501
  }
22358
22502
  }
22359
22503
  this.records.clear();
@@ -22695,12 +22839,30 @@ var RunSupervisor = class {
22695
22839
  }
22696
22840
  }
22697
22841
  if (!payload.prompt && !payload.attachments?.length) return refuse("\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A");
22842
+ let sessionId = payload.session_id;
22843
+ let sessionsBefore;
22844
+ let sessionNote = "";
22845
+ if (!payload.chat_session_id && provider.listSessions) {
22846
+ const saved = await provider.listSessions(workdir);
22847
+ if (!saved) {
22848
+ if (sessionId) sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22849
+ `;
22850
+ sessionId = "";
22851
+ } else if (sessionId && !saved.some((session) => session.id === sessionId)) {
22852
+ sessionNote = `\u25CF \u539F\u4F1A\u8BDD ${sessionId} \u4E0D\u5728\u6B64\u76EE\u5F55\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22853
+ `;
22854
+ sessionId = "";
22855
+ sessionsBefore = new Set(saved.map((session) => session.id));
22856
+ } else if (!sessionId) {
22857
+ sessionsBefore = new Set(saved.map((session) => session.id));
22858
+ }
22859
+ }
22698
22860
  if ([...this.active.values()].some((run2) => run2.workstationId === payload.workstation_id)) return refuse("\u672C\u673A\u8BE5\u5DE5\u4F4D\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
22699
22861
  if (this.active.size + this.preparing.size > this.config.maxConcurrentRuns) return refuse("\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650");
22700
22862
  const launch = provider.buildLaunch({
22701
22863
  permissionMode,
22702
22864
  prompt: payload.prompt,
22703
- sessionId: payload.session_id,
22865
+ sessionId,
22704
22866
  model: payload.model,
22705
22867
  reasoningEffort: payload.reasoning_effort,
22706
22868
  workdir
@@ -22731,11 +22893,14 @@ var RunSupervisor = class {
22731
22893
  workstationId: payload.workstation_id,
22732
22894
  agentType: provider.id,
22733
22895
  provider,
22896
+ parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
22897
+ ...sessionsBefore ? { sessionsBefore } : {},
22898
+ prompt: payload.prompt,
22734
22899
  child,
22735
22900
  pid: child.pid ?? 0,
22736
22901
  startedAt: Date.now(),
22737
22902
  workdir,
22738
- sessionId: payload.session_id,
22903
+ sessionId,
22739
22904
  finalMessage: "",
22740
22905
  turnCompleted: false,
22741
22906
  turnError: "",
@@ -22750,9 +22915,10 @@ var RunSupervisor = class {
22750
22915
  this.preparing.delete(run.runId);
22751
22916
  this.unreported.add(run.runId);
22752
22917
  if (run.pid > 1) this.orphans?.add({ runId: run.runId, pid: run.pid, executable: launch.executable, startedAt: run.startedAt });
22753
- run.tail.append(`\u25CF ${provider.id} \u542F\u52A8\u4E8E ${workdir}${payload.session_id ? `\uFF08\u7EE7\u7EED\u4F1A\u8BDD ${payload.session_id}\uFF09` : ""}
22918
+ if (sessionNote) run.tail.append(sessionNote);
22919
+ run.tail.append(`\u25CF ${provider.id} \u542F\u52A8\u4E8E ${workdir}${sessionId ? `\uFF08\u7EE7\u7EED\u4F1A\u8BDD ${sessionId}\uFF09` : ""}
22754
22920
  `);
22755
- this.logger.info("run-started", { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(payload.session_id) });
22921
+ this.logger.info("run-started", { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
22756
22922
  let spawnError = "";
22757
22923
  child.stdin?.on("error", () => void 0);
22758
22924
  child.once("error", (error62) => {
@@ -22764,8 +22930,11 @@ var RunSupervisor = class {
22764
22930
  if (!clean.trim()) return;
22765
22931
  run.stderr.push(clean);
22766
22932
  if (run.stderr.length > MAX_ERROR_ROWS) run.stderr.shift();
22767
- run.tail.append(`${clean}
22933
+ for (const row of provider.stderrDisplay ? provider.stderrDisplay(line) : [clean]) {
22934
+ const shown = sanitizeTerminalLine(row);
22935
+ if (shown.trim()) run.tail.append(`${shown}
22768
22936
  `);
22937
+ }
22769
22938
  });
22770
22939
  child.once("close", (code, signal3) => void this.onExit(run, code, signal3, spawnError));
22771
22940
  if (provider.startInput) {
@@ -22798,7 +22967,7 @@ var RunSupervisor = class {
22798
22967
  });
22799
22968
  }
22800
22969
  onStdout(run, rawLine) {
22801
- const parsed = run.provider.parseLine(rawLine);
22970
+ const parsed = run.parse(rawLine);
22802
22971
  if (run.chat && !run.forwardingFailed) {
22803
22972
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run, sanitizeChatEvent(event));
22804
22973
  if (parsed.sessionId) run.chatReady = true;
@@ -22840,11 +23009,22 @@ var RunSupervisor = class {
22840
23009
  try {
22841
23010
  const inspection = await run.provider.inspectExit({ exitCode: code, stderr: run.stderr, workdir: run.workdir, sessionId: run.sessionId });
22842
23011
  if (inspection.turnError && !run.turnError) run.turnError = sanitizeTerminalLine(inspection.turnError);
23012
+ for (const row of inspection.display ?? []) run.tail.append(`${sanitizeTerminalLine(row)}
23013
+ `);
22843
23014
  if (inspection.sessionId && inspection.sessionId !== run.sessionId) run.sessionId = inspection.sessionId;
22844
23015
  } catch (error62) {
22845
23016
  this.logger.warn("inspect-exit-failed", { runId: run.runId, error: errorMessage(error62) });
22846
23017
  }
22847
23018
  }
23019
+ if (run.sessionsBefore && !run.sessionId && !spawnError && run.provider.listSessions) {
23020
+ const after = await run.provider.listSessions(run.workdir).catch(() => void 0);
23021
+ const created = after ? pickCreatedSession(run.sessionsBefore, after, run.prompt) : void 0;
23022
+ if (created) run.sessionId = created;
23023
+ else if (after?.some((session) => !run.sessionsBefore.has(session.id))) {
23024
+ run.tail.append("\u25CF \u540C\u76EE\u5F55\u6709\u5176\u4ED6\u4F1A\u8BDD\u540C\u65F6\u65B0\u5EFA\uFF0C\u65E0\u6CD5\u786E\u8BA4\u672C\u8F6E\u4F1A\u8BDD\uFF0C\u4E0B\u8F6E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\n");
23025
+ this.logger.warn("session-ambiguous", { runId: run.runId, agentType: run.agentType });
23026
+ }
23027
+ }
22848
23028
  const durationMs = Date.now() - run.startedAt;
22849
23029
  let report;
22850
23030
  if (run.cancelRequested) {