toc-ocra 0.2.28 → 0.2.30

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
@@ -16675,8 +16675,8 @@ function rewriteKeyNames(ctx) {
16675
16675
  bySchema.set(entry.schema, entry);
16676
16676
  }
16677
16677
  const rewrites = /* @__PURE__ */ new Map();
16678
- for (const record3 of pendingRecords.get(ctx) ?? []) {
16679
- const seen = ctx.seen.get(record3);
16678
+ for (const record4 of pendingRecords.get(ctx) ?? []) {
16679
+ const seen = ctx.seen.get(record4);
16680
16680
  const names = (seen?.def ?? seen?.schema)?.propertyNames;
16681
16681
  if (!names || names === true || rewrites.has(names))
16682
16682
  continue;
@@ -20286,6 +20286,42 @@ function getVersionManagerBinPaths(options = {}) {
20286
20286
  }
20287
20287
 
20288
20288
  // src/providers/provider.ts
20289
+ function pickCreatedSession(before, after, prompt) {
20290
+ const created = after.filter((session) => !before.has(session.id));
20291
+ if (created.length <= 1) return created[0]?.id;
20292
+ const flat = (text) => text.replace(/\s+/g, " ").trim();
20293
+ const wanted = flat(prompt);
20294
+ const titled = created.filter((session) => {
20295
+ const title = flat(session.title ?? "").replace(/(\.\.\.|…)$/, "").trim();
20296
+ return title.length > 0 && wanted.startsWith(title);
20297
+ });
20298
+ return titled.length === 1 ? titled[0].id : void 0;
20299
+ }
20300
+ var runLog = {
20301
+ event: (text) => `\u25CF ${text}`,
20302
+ error: (text) => `\u2717 ${clip(text)}`,
20303
+ reply: (text) => textRows("\u203A ", text),
20304
+ /** Rows continuing the previous reply. */
20305
+ replyMore: (text) => text.split(/\r?\n/).map((row) => ` ${row}`),
20306
+ thinking: (text) => textRows("\u2026 ", clip(text, 600), 8),
20307
+ command: (command) => `$ ${clip(command)}`,
20308
+ commandOutput: (output2) => output2 ? textRows(" ", clip(output2, 2e3), 20) : [],
20309
+ commandExit: (code2) => ` (exit ${typeof code2 === "number" ? code2 : "?"})`,
20310
+ fileChange: (path) => `\u270E \u4FEE\u6539\u6587\u4EF6${path ? ` ${path}` : ""}`,
20311
+ /** A tool call without its own row type, by the kinds the clients name. */
20312
+ tool: (kind) => `\xB7 ${kind}`
20313
+ };
20314
+ var EDIT_TOOLS = /^(edit|multiedit|write|notebookedit|fs_write|write_file|edit_file|create_file|str_replace|apply_patch|create)$/;
20315
+ var READ_TOOLS = /^(read|fs_read|glob|grep|ls|list|code|view|search_files|find|read_file|list_directory)$/;
20316
+ function toolCallRows(name, path) {
20317
+ const tool = name.trim().toLowerCase();
20318
+ if (EDIT_TOOLS.test(tool)) return [runLog.fileChange(path)];
20319
+ if (READ_TOOLS.test(tool)) return [];
20320
+ if (tool.startsWith("mcp__") || tool.startsWith("@")) return [runLog.tool("mcp_tool_call")];
20321
+ if (/web_?(search|fetch)/.test(tool)) return [runLog.tool("web_search")];
20322
+ if (/todo/.test(tool)) return [runLog.tool("todo_list")];
20323
+ return [runLog.tool("tool_call")];
20324
+ }
20289
20325
  function providerEnvironment() {
20290
20326
  const env = { ...process.env };
20291
20327
  const commandPaths = [
@@ -20359,32 +20395,92 @@ var claudeProvider = {
20359
20395
  return resolveExecutable("claude", args, env, process.env.TOC_OCRA_CLAUDE_PATH);
20360
20396
  },
20361
20397
  parseLine(line) {
20398
+ return claudeLineParser()(line);
20399
+ },
20400
+ createLineParser: () => claudeLineParser()
20401
+ };
20402
+ var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
20403
+ function toolResultText(content) {
20404
+ if (typeof content === "string") return content;
20405
+ if (Array.isArray(content)) return content.map((part) => str(record2(part).text) ?? "").filter(Boolean).join("\n");
20406
+ return "";
20407
+ }
20408
+ function claudeLineParser() {
20409
+ const shells = /* @__PURE__ */ new Map();
20410
+ let lastShell = "";
20411
+ let started = false;
20412
+ return (line) => {
20362
20413
  const event = tryJson(line);
20363
20414
  if (!event) return { display: line.trim() ? [line] : [] };
20415
+ if (event.parent_tool_use_id) return { display: [] };
20364
20416
  const sessionId = str(event.session_id);
20365
20417
  const base = sessionId ? { sessionId } : {};
20366
20418
  switch (str(event.type)) {
20367
- case "result": {
20368
- const text = str(event.result) ?? "";
20369
- if (event.is_error === true) return { ...base, turnError: text || "claude failed", display: [`\u2717 ${clip(text)}`] };
20370
- return { ...base, message: text, turnCompleted: true, display: ["\u25CF \u672C\u8F6E\u5B8C\u6210"] };
20419
+ case "system": {
20420
+ if (started || str(event.subtype) !== "init") return { ...base, display: [] };
20421
+ started = true;
20422
+ return { ...base, display: [`\u25CF \u4F1A\u8BDD ${sessionId ?? ""}`, runLog.event("\u5F00\u59CB\u5904\u7406")] };
20371
20423
  }
20372
20424
  case "assistant": {
20373
- const content = event.message?.content ?? [];
20374
- const rows = content.flatMap((part) => {
20375
- if (part.type === "text") return textRows("\u203A ", str(part.text) ?? "");
20376
- if (part.type === "tool_use") return [`$ ${str(part.name) ?? "tool"} ${clip(JSON.stringify(part.input ?? {}), 200)}`];
20377
- return [];
20378
- });
20425
+ const content = record2(event.message).content ?? [];
20426
+ const rows = [];
20427
+ for (const value of Array.isArray(content) ? content : []) {
20428
+ const part = record2(value);
20429
+ if (part.type === "text") {
20430
+ if (str(part.text)) rows.push(...runLog.reply(String(part.text)));
20431
+ lastShell = "";
20432
+ continue;
20433
+ }
20434
+ if (part.type === "thinking") {
20435
+ if (str(part.thinking)) rows.push(...runLog.thinking(String(part.thinking)));
20436
+ lastShell = "";
20437
+ continue;
20438
+ }
20439
+ if (part.type !== "tool_use") continue;
20440
+ const name = str(part.name) ?? "tool";
20441
+ const input2 = record2(part.input);
20442
+ const id = str(part.id) ?? "";
20443
+ if (name === "Bash") {
20444
+ const command = str(input2.command) ?? "";
20445
+ shells.set(id, command);
20446
+ rows.push(runLog.command(command));
20447
+ lastShell = id;
20448
+ continue;
20449
+ }
20450
+ rows.push(...toolCallRows(name, str(input2.file_path) ?? str(input2.notebook_path)));
20451
+ lastShell = "";
20452
+ }
20379
20453
  return { ...base, display: rows };
20380
20454
  }
20381
- case "system":
20382
- return { ...base, display: sessionId ? [`\u25CF \u4F1A\u8BDD ${sessionId}`] : [] };
20455
+ case "user": {
20456
+ const content = record2(event.message).content ?? [];
20457
+ const rows = [];
20458
+ for (const value of Array.isArray(content) ? content : []) {
20459
+ const part = record2(value);
20460
+ if (part.type !== "tool_result") continue;
20461
+ const id = str(part.tool_use_id) ?? "";
20462
+ const command = shells.get(id);
20463
+ if (command === void 0) {
20464
+ if (part.is_error === true) rows.push(runLog.error(toolResultText(part.content) || "\u5DE5\u5177\u8C03\u7528\u5931\u8D25"));
20465
+ continue;
20466
+ }
20467
+ shells.delete(id);
20468
+ if (lastShell !== id) rows.push(runLog.command(command));
20469
+ rows.push(...runLog.commandOutput(toolResultText(part.content)), runLog.commandExit(part.is_error === true ? 1 : 0));
20470
+ lastShell = "";
20471
+ }
20472
+ return { ...base, display: rows };
20473
+ }
20474
+ case "result": {
20475
+ const text = str(event.result) ?? "";
20476
+ if (event.is_error === true) return { ...base, turnError: text || "claude failed", display: [runLog.error(text || "Claude \u672C\u8F6E\u6267\u884C\u5931\u8D25")] };
20477
+ return { ...base, message: text, turnCompleted: true, display: [runLog.event("\u672C\u8F6E\u5B8C\u6210")] };
20478
+ }
20383
20479
  default:
20384
20480
  return { ...base, display: [] };
20385
20481
  }
20386
- }
20387
- };
20482
+ };
20483
+ }
20388
20484
 
20389
20485
  // src/providers/cli/codex.ts
20390
20486
  var codexProvider = {
@@ -20494,44 +20590,103 @@ var grokProvider = {
20494
20590
  };
20495
20591
 
20496
20592
  // src/providers/cli/kiro.ts
20497
- import { execFile, execFileSync } from "node:child_process";
20593
+ import { execFile } from "node:child_process";
20498
20594
  import { promisify } from "node:util";
20499
20595
  var execFileAsync = promisify(execFile);
20500
- function isNoiseLine(text) {
20501
- if (!text) return true;
20502
- if (text.startsWith("\u22EE") || text.startsWith("\u25B8") || text.startsWith("\u25CF")) return true;
20503
- if (/^Running tool\b/.test(text)) return true;
20504
- if (/^- Completed in\b/.test(text)) return true;
20505
- if (/^All tools are now trusted\b/.test(text)) return true;
20506
- if (/^Agents can sometimes do unexpected things\b/.test(text)) return true;
20507
- if (/^Learn more at\b/.test(text)) return true;
20508
- return false;
20509
- }
20596
+ var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
20510
20597
  function kiroLaunch(args) {
20511
20598
  return resolveExecutable("kiro-cli", args, providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
20512
20599
  }
20513
20600
  var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
20514
- function parseSessions(stdout) {
20601
+ function parseKiroSessions(stdout) {
20515
20602
  const parsed = JSON.parse(stdout);
20516
- 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 ?? ""));
20517
- }
20518
- async function latestSessionId(workdir) {
20519
- const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20520
- try {
20521
- const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: 1e4, maxBuffer: 4 * 1024 * 1024 });
20522
- return str(parseSessions(stdout)[0]?.sessionId);
20523
- } catch {
20524
- return void 0;
20525
- }
20526
- }
20527
- function resumableSession(sessionId, workdir) {
20528
- const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20529
- try {
20530
- const stdout = execFileSync(executable, args, { cwd: workdir, env, timeout: 1e4, maxBuffer: 4 * 1024 * 1024, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
20531
- return parseSessions(stdout).some((entry) => entry.sessionId === sessionId);
20532
- } catch {
20533
- return false;
20534
- }
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
+ }
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("");
20643
+ } 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) ?? "";
20683
+ 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]
20689
+ };
20535
20690
  }
20536
20691
  var kiroProvider = {
20537
20692
  id: "kiro",
@@ -20541,44 +20696,33 @@ var kiroProvider = {
20541
20696
  else args.push("--trust-tools=@doer/echo_report_task_progress");
20542
20697
  if (request.model) args.push("--model", request.model);
20543
20698
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20544
- if (request.sessionId && resumableSession(request.sessionId, request.workdir)) args.push("--resume-id", request.sessionId);
20699
+ if (request.sessionId && !request.sessionId.startsWith("sess_")) args.push("--resume-id", request.sessionId);
20545
20700
  args.push("--", request.prompt);
20546
20701
  return kiroLaunch(args);
20547
20702
  },
20548
- async inspectExit(context) {
20549
- const inspection = {};
20550
- const businessError = kiroStderrError(context.stderr);
20551
- if (businessError) inspection.turnError = businessError;
20552
- if (!inspection.turnError) {
20553
- const sessionId = await latestSessionId(context.workdir);
20554
- if (sessionId) inspection.sessionId = sessionId;
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;
20555
20710
  }
20556
- return inspection;
20711
+ },
20712
+ inspectExit(context) {
20713
+ 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`)] } : {};
20557
20717
  },
20558
20718
  parseLine(line) {
20559
- if (/^\s*⋮/.test(line)) return { display: [] };
20560
- const event = tryJson(line);
20561
- if (event) {
20562
- const sessionId = str(event.session_id) ?? str(event.sessionId);
20563
- const message = str(event.response) ?? str(event.message) ?? str(event.text);
20564
- const error62 = typeof event.error === "string" ? event.error : event.error && typeof event.error === "object" ? str(event.error.message) : void 0;
20565
- const type = str(event.type) ?? "";
20566
- return {
20567
- ...sessionId ? { sessionId } : {},
20568
- ...message ? { message } : {},
20569
- ...error62 ? { turnError: error62 } : {},
20570
- ...message && (type === "result" || type === "turn.completed") ? { turnCompleted: true } : {},
20571
- display: message ? textRows("\u203A ", message) : error62 ? [`\u2717 ${error62}`] : [line]
20572
- };
20573
- }
20574
- const text = line.replace(/^λ↯\s*/, "").trim();
20575
- if (!text) return { display: [] };
20576
- const answer = text.match(/^>\s?(.*)$/);
20577
- if (answer && answer[1]?.trim()) {
20578
- return { message: answer[1].trim(), display: [`\u203A ${answer[1].trim()}`] };
20579
- }
20580
- if (isNoiseLine(text)) return { display: [] };
20581
- return { display: [line.replace(/^λ↯\s*/, "")] };
20719
+ return kiroLineParser()(line);
20720
+ },
20721
+ createLineParser: () => kiroLineParser(),
20722
+ stderrDisplay(line) {
20723
+ const text = line.replace(ANSI, "").trim();
20724
+ if (!text || isChrome(text)) return [];
20725
+ return [line];
20582
20726
  }
20583
20727
  };
20584
20728
  function kiroStderrError(stderrLines) {
@@ -20589,6 +20733,11 @@ function kiroStderrError(stderrLines) {
20589
20733
  if (/not logged in|please log in|authentication required|unauthorized/i.test(text)) {
20590
20734
  return "Kiro CLI \u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55\u540E\u518D\u8BD5";
20591
20735
  }
20736
+ if (/having trouble responding/i.test(text)) {
20737
+ const detail = text.match(/message:\s*"([^"]+)"/)?.[1] ?? text.match(/Failed to send the request:\s*(.+)/)?.[1]?.trim();
20738
+ const hint = detail && /input_schema/i.test(detail) ? "\uFF08\u67D0\u4E2A MCP \u5DE5\u5177\u7684\u53C2\u6570\u5B9A\u4E49\u4E0D\u88AB Kiro \u63A5\u53D7\uFF0C\u8BF7\u68C0\u67E5 MCP \u670D\u52A1\u7AEF\u7684\u5DE5\u5177\u5B9A\u4E49\uFF09" : "";
20739
+ return `Kiro \u670D\u52A1\u62D2\u7EDD\u4E86\u672C\u6B21\u8BF7\u6C42\uFF1A${detail ?? "\u672A\u77E5\u9519\u8BEF"}${hint}`;
20740
+ }
20592
20741
  return void 0;
20593
20742
  }
20594
20743
 
@@ -21363,8 +21512,8 @@ function codexChatProvider(request, attachments) {
21363
21512
  }
21364
21513
 
21365
21514
  // src/providers/chat/claude-stream-json.ts
21366
- var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21367
- var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record2(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21515
+ var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
21516
+ var textContent = (value) => typeof value === "string" ? value : Array.isArray(value) ? value.map((part) => str(record3(part).text) ?? "").filter(Boolean).join("\n") : JSON.stringify(value ?? "");
21368
21517
  function claudeChatProvider(attachments) {
21369
21518
  let messageID = "";
21370
21519
  let messageSequence = 0;
@@ -21394,14 +21543,14 @@ function claudeChatProvider(attachments) {
21394
21543
  const events = [];
21395
21544
  if (envelope.parent_tool_use_id) return { ...base, display: [] };
21396
21545
  if (envelope.type === "stream_event") {
21397
- const event = record2(envelope.event);
21546
+ const event = record3(envelope.event);
21398
21547
  const index = Number(event.index ?? 0);
21399
21548
  if (event.type === "message_start") {
21400
- messageID = str(record2(event.message).id) ?? `message:${++messageSequence}`;
21549
+ messageID = str(record3(event.message).id) ?? `message:${++messageSequence}`;
21401
21550
  blocks.clear();
21402
21551
  } else if (event.type === "content_block_start") {
21403
21552
  if (!messageID) messageID = `message:${++messageSequence}`;
21404
- const part = record2(event.content_block);
21553
+ const part = record3(event.content_block);
21405
21554
  const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21406
21555
  if (!["tool_use", "thinking", "text"].includes(String(part.type))) return { ...base, display: [] };
21407
21556
  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: "" };
@@ -21410,7 +21559,7 @@ function claudeChatProvider(attachments) {
21410
21559
  events.push(asItem(block, "in_progress"));
21411
21560
  } else if (event.type === "content_block_delta") {
21412
21561
  const block = blocks.get(index);
21413
- const delta = record2(event.delta);
21562
+ const delta = record3(event.delta);
21414
21563
  if (!block) return { ...base, display: [] };
21415
21564
  if (delta.type === "text_delta" || delta.type === "thinking_delta") {
21416
21565
  const text = String(delta.text ?? delta.thinking ?? "");
@@ -21427,11 +21576,11 @@ function claudeChatProvider(attachments) {
21427
21576
  if (block && block.type !== "tool_call") events.push(asItem(block, "completed"));
21428
21577
  }
21429
21578
  } else if (envelope.type === "assistant") {
21430
- const message = record2(envelope.message);
21579
+ const message = record3(envelope.message);
21431
21580
  const id = str(message.id) || messageID || `message:${++messageSequence}`;
21432
21581
  const parts = Array.isArray(message.content) ? message.content : [];
21433
21582
  parts.forEach((value, index) => {
21434
- const part = record2(value);
21583
+ const part = record3(value);
21435
21584
  if (!["text", "thinking", "tool_use"].includes(String(part.type))) return;
21436
21585
  const type = part.type === "tool_use" ? "tool_call" : part.type === "thinking" ? "thought" : "text";
21437
21586
  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: "" };
@@ -21440,9 +21589,9 @@ function claudeChatProvider(attachments) {
21440
21589
  events.push(asItem(block, type === "tool_call" ? "in_progress" : "completed"));
21441
21590
  });
21442
21591
  } else if (envelope.type === "user") {
21443
- const message = record2(envelope.message);
21592
+ const message = record3(envelope.message);
21444
21593
  for (const value of Array.isArray(message.content) ? message.content : []) {
21445
- const part = record2(value);
21594
+ const part = record3(value);
21446
21595
  if (part.type !== "tool_result") continue;
21447
21596
  const id = str(part.tool_use_id);
21448
21597
  if (!id) continue;
@@ -22349,8 +22498,8 @@ var OrphanRegistry = class {
22349
22498
  file;
22350
22499
  records = /* @__PURE__ */ new Map();
22351
22500
  writing = Promise.resolve();
22352
- add(record3) {
22353
- this.records.set(record3.runId, record3);
22501
+ add(record4) {
22502
+ this.records.set(record4.runId, record4);
22354
22503
  this.persist();
22355
22504
  }
22356
22505
  remove(runId) {
@@ -22374,12 +22523,12 @@ var OrphanRegistry = class {
22374
22523
  return [];
22375
22524
  }
22376
22525
  const reaped = [];
22377
- for (const record3 of previous) {
22378
- if (!record3 || typeof record3.pid !== "number" || record3.pid <= 1) continue;
22379
- const command = await commandOf(record3.pid);
22380
- if (command && command.includes(basename(record3.executable))) {
22381
- await killProcessTree(record3.pid);
22382
- reaped.push(record3);
22526
+ for (const record4 of previous) {
22527
+ if (!record4 || typeof record4.pid !== "number" || record4.pid <= 1) continue;
22528
+ const command = await commandOf(record4.pid);
22529
+ if (command && command.includes(basename(record4.executable))) {
22530
+ await killProcessTree(record4.pid);
22531
+ reaped.push(record4);
22383
22532
  }
22384
22533
  }
22385
22534
  this.records.clear();
@@ -22721,12 +22870,30 @@ var RunSupervisor = class {
22721
22870
  }
22722
22871
  }
22723
22872
  if (!payload.prompt && !payload.attachments?.length) return refuse("\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A");
22873
+ let sessionId = payload.session_id;
22874
+ let sessionsBefore;
22875
+ let sessionNote = "";
22876
+ if (!payload.chat_session_id && provider.listSessions) {
22877
+ const saved = await provider.listSessions(workdir);
22878
+ if (!saved) {
22879
+ if (sessionId) sessionNote = `\u25CF \u65E0\u6CD5\u8BFB\u53D6 ${provider.id} \u7684\u5DF2\u4FDD\u5B58\u4F1A\u8BDD\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22880
+ `;
22881
+ sessionId = "";
22882
+ } else if (sessionId && !saved.some((session) => session.id === sessionId)) {
22883
+ sessionNote = `\u25CF \u539F\u4F1A\u8BDD ${sessionId} \u4E0D\u5728\u6B64\u76EE\u5F55\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD
22884
+ `;
22885
+ sessionId = "";
22886
+ sessionsBefore = new Set(saved.map((session) => session.id));
22887
+ } else if (!sessionId) {
22888
+ sessionsBefore = new Set(saved.map((session) => session.id));
22889
+ }
22890
+ }
22724
22891
  if ([...this.active.values()].some((run3) => run3.workstationId === payload.workstation_id)) return refuse("\u672C\u673A\u8BE5\u5DE5\u4F4D\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
22725
22892
  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");
22726
22893
  const launch = provider.buildLaunch({
22727
22894
  permissionMode,
22728
22895
  prompt: payload.prompt,
22729
- sessionId: payload.session_id,
22896
+ sessionId,
22730
22897
  model: payload.model,
22731
22898
  reasoningEffort: payload.reasoning_effort,
22732
22899
  workdir
@@ -22757,11 +22924,14 @@ var RunSupervisor = class {
22757
22924
  workstationId: payload.workstation_id,
22758
22925
  agentType: provider.id,
22759
22926
  provider,
22927
+ parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
22928
+ ...sessionsBefore ? { sessionsBefore } : {},
22929
+ prompt: payload.prompt,
22760
22930
  child,
22761
22931
  pid: child.pid ?? 0,
22762
22932
  startedAt: Date.now(),
22763
22933
  workdir,
22764
- sessionId: payload.session_id,
22934
+ sessionId,
22765
22935
  finalMessage: "",
22766
22936
  turnCompleted: false,
22767
22937
  turnError: "",
@@ -22776,9 +22946,10 @@ var RunSupervisor = class {
22776
22946
  this.preparing.delete(run2.runId);
22777
22947
  this.unreported.add(run2.runId);
22778
22948
  if (run2.pid > 1) this.orphans?.add({ runId: run2.runId, pid: run2.pid, executable: launch.executable, startedAt: run2.startedAt });
22779
- run2.tail.append(`\u25CF ${provider.id} \u542F\u52A8\u4E8E ${workdir}${payload.session_id ? `\uFF08\u7EE7\u7EED\u4F1A\u8BDD ${payload.session_id}\uFF09` : ""}
22949
+ if (sessionNote) run2.tail.append(sessionNote);
22950
+ run2.tail.append(`\u25CF ${provider.id} \u542F\u52A8\u4E8E ${workdir}${sessionId ? `\uFF08\u7EE7\u7EED\u4F1A\u8BDD ${sessionId}\uFF09` : ""}
22780
22951
  `);
22781
- this.logger.info("run-started", { runId: run2.runId, agentType: provider.id, pid: run2.pid, resume: Boolean(payload.session_id) });
22952
+ this.logger.info("run-started", { runId: run2.runId, agentType: provider.id, pid: run2.pid, resume: Boolean(sessionId) });
22782
22953
  let spawnError = "";
22783
22954
  child.stdin?.on("error", () => void 0);
22784
22955
  child.once("error", (error62) => {
@@ -22790,8 +22961,11 @@ var RunSupervisor = class {
22790
22961
  if (!clean.trim()) return;
22791
22962
  run2.stderr.push(clean);
22792
22963
  if (run2.stderr.length > MAX_ERROR_ROWS) run2.stderr.shift();
22793
- run2.tail.append(`${clean}
22964
+ for (const row of provider.stderrDisplay ? provider.stderrDisplay(line) : [clean]) {
22965
+ const shown = sanitizeTerminalLine(row);
22966
+ if (shown.trim()) run2.tail.append(`${shown}
22794
22967
  `);
22968
+ }
22795
22969
  });
22796
22970
  child.once("close", (code2, signal3) => void this.onExit(run2, code2, signal3, spawnError));
22797
22971
  if (provider.startInput) {
@@ -22824,7 +22998,7 @@ var RunSupervisor = class {
22824
22998
  });
22825
22999
  }
22826
23000
  onStdout(run2, rawLine) {
22827
- const parsed = run2.provider.parseLine(rawLine);
23001
+ const parsed = run2.parse(rawLine);
22828
23002
  if (run2.chat && !run2.forwardingFailed) {
22829
23003
  for (const event of parsed.chatEvents ?? []) this.queueChatEvent(run2, sanitizeChatEvent(event));
22830
23004
  if (parsed.sessionId) run2.chatReady = true;
@@ -22866,11 +23040,22 @@ var RunSupervisor = class {
22866
23040
  try {
22867
23041
  const inspection = await run2.provider.inspectExit({ exitCode: code2, stderr: run2.stderr, workdir: run2.workdir, sessionId: run2.sessionId });
22868
23042
  if (inspection.turnError && !run2.turnError) run2.turnError = sanitizeTerminalLine(inspection.turnError);
23043
+ for (const row of inspection.display ?? []) run2.tail.append(`${sanitizeTerminalLine(row)}
23044
+ `);
22869
23045
  if (inspection.sessionId && inspection.sessionId !== run2.sessionId) run2.sessionId = inspection.sessionId;
22870
23046
  } catch (error62) {
22871
23047
  this.logger.warn("inspect-exit-failed", { runId: run2.runId, error: errorMessage(error62) });
22872
23048
  }
22873
23049
  }
23050
+ if (run2.sessionsBefore && !run2.sessionId && !spawnError && run2.provider.listSessions) {
23051
+ const after = await run2.provider.listSessions(run2.workdir).catch(() => void 0);
23052
+ const created = after ? pickCreatedSession(run2.sessionsBefore, after, run2.prompt) : void 0;
23053
+ if (created) run2.sessionId = created;
23054
+ else if (after?.some((session) => !run2.sessionsBefore.has(session.id))) {
23055
+ run2.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");
23056
+ this.logger.warn("session-ambiguous", { runId: run2.runId, agentType: run2.agentType });
23057
+ }
23058
+ }
22874
23059
  const durationMs = Date.now() - run2.startedAt;
22875
23060
  let report;
22876
23061
  if (run2.cancelRequested) {