toc-ocra 0.3.0 → 0.3.1

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.
Files changed (37) hide show
  1. package/README.md +5 -5
  2. package/dist/cli/cli.mjs +438 -52
  3. package/dist/service/agent.mjs +426 -40
  4. package/dist/src/config.d.ts +1 -1
  5. package/dist/src/providers/acp/acp-driver.d.ts +1 -1
  6. package/dist/src/providers/chat/codex-app-server.d.ts +1 -1
  7. package/dist/src/providers/chat/codex-app-server.js +1 -1
  8. package/dist/src/providers/chat/codex-goal.d.ts +17 -0
  9. package/dist/src/providers/chat/codex-goal.js +188 -0
  10. package/dist/src/providers/chat/codex-goal.js.map +1 -0
  11. package/dist/src/providers/cli/claude.d.ts +6 -0
  12. package/dist/src/providers/cli/claude.js +101 -3
  13. package/dist/src/providers/cli/claude.js.map +1 -1
  14. package/dist/src/providers/cli/codex-fork.d.ts +11 -0
  15. package/dist/src/providers/cli/codex-fork.js +84 -0
  16. package/dist/src/providers/cli/codex-fork.js.map +1 -0
  17. package/dist/src/providers/cli/kiro.js +1 -1
  18. package/dist/src/providers/cli-failure.js +1 -1
  19. package/dist/src/providers/provider.d.ts +17 -1
  20. package/dist/src/providers/provider.js.map +1 -1
  21. package/dist/src/providers/registry.d.ts +1 -1
  22. package/dist/src/runs/run-supervisor.d.ts +12 -7
  23. package/dist/src/runs/run-supervisor.js +83 -26
  24. package/dist/src/runs/run-supervisor.js.map +1 -1
  25. package/dist/src/runtime/agent-runtime.js +10 -10
  26. package/dist/src/runtime/agent-runtime.js.map +1 -1
  27. package/dist/src/smoke/cli-smoke.js +1 -1
  28. package/dist/src/smoke/cli-smoke.js.map +1 -1
  29. package/dist/src/transport/gateway-client.d.ts +3 -1
  30. package/dist/src/transport/gateway-client.js +6 -0
  31. package/dist/src/transport/gateway-client.js.map +1 -1
  32. package/dist/src/types/protocol.d.ts +32 -4
  33. package/dist/src/types/protocol.js +14 -3
  34. package/dist/src/types/protocol.js.map +1 -1
  35. package/locales/en.json +1 -1
  36. package/locales/zh-CN.json +1 -1
  37. package/package.json +1 -1
package/dist/cli/cli.mjs CHANGED
@@ -25446,10 +25446,58 @@ function isWriterConflict(message) {
25446
25446
  }
25447
25447
 
25448
25448
  // src/providers/cli/claude.ts
25449
- import { readFileSync as readFileSync4 } from "node:fs";
25449
+ import { readdirSync as readdirSync2, readFileSync as readFileSync4 } from "node:fs";
25450
25450
  import { homedir as homedir4 } from "node:os";
25451
25451
  import { join as join7 } from "node:path";
25452
25452
  var CLAUDE = requireCliSpec("claude");
25453
+ function claudeProjectRoots() {
25454
+ const configured = process.env.CLAUDE_CONFIG_DIR;
25455
+ const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join7(homedir4(), ".claude")];
25456
+ return dirs.map((dir) => join7(dir, "projects"));
25457
+ }
25458
+ function claudeTranscriptExists(sessionId) {
25459
+ return claudeTranscriptPath(sessionId) !== void 0;
25460
+ }
25461
+ function claudeTranscriptPath(sessionId) {
25462
+ const file2 = `${sessionId}.jsonl`;
25463
+ for (const root of claudeProjectRoots()) {
25464
+ let projects;
25465
+ try {
25466
+ projects = readdirSync2(root);
25467
+ } catch {
25468
+ continue;
25469
+ }
25470
+ for (const project of projects) {
25471
+ try {
25472
+ if (readdirSync2(join7(root, project)).includes(file2)) return join7(root, project, file2);
25473
+ } catch {
25474
+ }
25475
+ }
25476
+ }
25477
+ return void 0;
25478
+ }
25479
+ function isPromptEntry(entry) {
25480
+ if (entry.type !== "user" || entry.isSidechain === true || entry.isMeta === true) return false;
25481
+ const content = record2(entry.message).content;
25482
+ if (typeof content === "string") return content.trim().length > 0;
25483
+ return Array.isArray(content) && content.some((part) => record2(part).type === "text");
25484
+ }
25485
+ function claudeForkBoundary(transcript, keepTurns) {
25486
+ if (keepTurns <= 0) return void 0;
25487
+ let prompts = 0;
25488
+ let boundary;
25489
+ for (const line of transcript.split(/\r?\n/)) {
25490
+ const entry = tryJson(line);
25491
+ if (!entry) continue;
25492
+ if (isPromptEntry(entry)) {
25493
+ prompts++;
25494
+ if (prompts > keepTurns) return boundary;
25495
+ continue;
25496
+ }
25497
+ if (entry.type === "assistant" && entry.isSidechain !== true && typeof entry.uuid === "string") boundary = entry.uuid;
25498
+ }
25499
+ return void 0;
25500
+ }
25453
25501
  var claudeProvider = {
25454
25502
  id: "claude",
25455
25503
  buildLaunch(request) {
@@ -25468,7 +25516,21 @@ var claudeProvider = {
25468
25516
  }
25469
25517
  if (request.model) args.push("--model", request.model);
25470
25518
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
25471
- if (request.sessionId) args.push("--resume", request.sessionId);
25519
+ if (request.sessionId && request.fork && !claudeTranscriptExists(request.sessionId)) {
25520
+ args.push("--resume", request.fork.sourceSessionId, "--fork-session");
25521
+ const source = claudeTranscriptPath(request.fork.sourceSessionId);
25522
+ if (source && request.fork.keepTurns > 0) {
25523
+ let text = "";
25524
+ try {
25525
+ text = readFileSync4(source, "utf8");
25526
+ } catch {
25527
+ }
25528
+ const at = claudeForkBoundary(text, request.fork.keepTurns);
25529
+ if (at) args.push("--resume-session-at", at);
25530
+ }
25531
+ } else if (request.sessionId) {
25532
+ args.push(claudeTranscriptExists(request.sessionId) ? "--resume" : "--session-id", request.sessionId);
25533
+ }
25472
25534
  return launchCli({ spec: CLAUDE, args, env, prompt: request.prompt });
25473
25535
  },
25474
25536
  parseLine(line) {
@@ -25788,7 +25850,7 @@ var COPY = {
25788
25850
  notSignedIn: ({ label }) => `${label} \u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5728\u8FD9\u53F0\u7535\u8111\u4E0A\u91CD\u65B0\u767B\u5F55\u540E\u518D\u8BD5`,
25789
25851
  usageLimit: ({ label }) => `${label} \u7684\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7B49\u5F85\u989D\u5EA6\u91CD\u7F6E\u6216\u5347\u7EA7\u5957\u9910\u540E\u518D\u8BD5`,
25790
25852
  rateLimited: ({ label }) => `${label} \u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u5DF2\u88AB\u9650\u6D41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`,
25791
- modelUnavailable: ({ label }) => `${label} \u4E0D\u80FD\u4F7F\u7528\u6240\u9009\u6A21\u578B\uFF0C\u8BF7\u5728\u5DE5\u4F4D\u4E2D\u6362\u4E00\u4E2A\u6A21\u578B\u6216\u6539\u4E3A\u9ED8\u8BA4`,
25853
+ modelUnavailable: ({ label }) => `${label} \u4E0D\u80FD\u4F7F\u7528\u6240\u9009\u6A21\u578B\uFF0C\u8BF7\u5728\u4F1A\u8BDD\u4E2D\u6362\u4E00\u4E2A\u6A21\u578B\u6216\u6539\u4E3A\u9ED8\u8BA4`,
25792
25854
  sessionMissing: ({ label }) => `${label} \u627E\u4E0D\u5230\u8981\u7EE7\u7EED\u7684\u4F1A\u8BDD`,
25793
25855
  promptTooLong: ({ label }) => `\u6D88\u606F\u8FC7\u957F\uFF0C\u8D85\u51FA\u672C\u673A\u547D\u4EE4\u884C\u957F\u5EA6\u4E0A\u9650\uFF0C${label} \u6682\u4E0D\u652F\u6301\u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6\u63D0\u793A\u8BCD\uFF0C\u8BF7\u7F29\u77ED\u6D88\u606F\u540E\u91CD\u8BD5`,
25794
25856
  contextTooLong: ({ label }) => `${label} \u7684\u4F1A\u8BDD\u5185\u5BB9\u5DF2\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u5F00\u59CB\u65B0\u4F1A\u8BDD\u6216\u7CBE\u7B80\u6D88\u606F`,
@@ -27318,10 +27380,10 @@ import { tmpdir as tmpdir2 } from "node:os";
27318
27380
  import { join as join13 } from "node:path";
27319
27381
 
27320
27382
  // src/runs/run-supervisor.ts
27321
- import { spawn as spawn7 } from "node:child_process";
27383
+ import { spawn as spawn8 } from "node:child_process";
27322
27384
  import { mkdir as mkdir4, realpath as realpath2, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
27323
27385
  import { basename as basename2, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3 } from "node:path";
27324
- import { createInterface as createInterface4 } from "node:readline";
27386
+ import { createInterface as createInterface5 } from "node:readline";
27325
27387
 
27326
27388
  // src/providers/chat/index.ts
27327
27389
  function resolveChatProvider(type, request, attachments) {
@@ -27450,6 +27512,269 @@ function clipToCharacterBudget(rows, budget) {
27450
27512
  return { lines: rows, limited: false };
27451
27513
  }
27452
27514
 
27515
+ // src/providers/chat/codex-goal.ts
27516
+ var GOAL_IDLE_END_MS = 18e4;
27517
+ var GOAL_STATUSES = /* @__PURE__ */ new Set(["active", "paused", "blocked", "usageLimited", "budgetLimited", "complete"]);
27518
+ function codexGoalProvider(request, goal) {
27519
+ let write;
27520
+ let threadId = request.sessionId;
27521
+ let nextId = 10;
27522
+ let turnRunning = false;
27523
+ let currentTurn = "";
27524
+ let turnMessage = "";
27525
+ let goalStatus = "active";
27526
+ let goalSet = false;
27527
+ let ended = false;
27528
+ let idleSince = 0;
27529
+ const send = (message) => write?.(`${JSON.stringify(message)}
27530
+ `);
27531
+ const sandboxPolicy = request.permissionMode === "full" ? { type: "dangerFullAccess" } : { type: "readOnly", access: { type: "restricted", includePlatformDefaults: true, readableRoots: [request.workdir] } };
27532
+ const empty = () => ({ display: [] });
27533
+ const end = (rows = []) => {
27534
+ if (ended) return { display: rows };
27535
+ ended = true;
27536
+ return { display: [...rows, runLog.event("\u76EE\u6807\u8FD0\u884C\u7ED3\u675F")], turnCompleted: true, endProcess: true };
27537
+ };
27538
+ const maybeEnd = (rows = []) => {
27539
+ if (!turnRunning && goalSet && goalStatus !== "active") return end(rows);
27540
+ return { display: rows };
27541
+ };
27542
+ const snapshot = (value) => {
27543
+ const status = str(value.status);
27544
+ if (!status || !GOAL_STATUSES.has(status)) return void 0;
27545
+ return {
27546
+ objective: String(value.objective ?? ""),
27547
+ status,
27548
+ ...typeof value.tokenBudget === "number" ? { token_budget: value.tokenBudget } : {},
27549
+ tokens_used: typeof value.tokensUsed === "number" ? value.tokensUsed : 0,
27550
+ time_used_seconds: typeof value.timeUsedSeconds === "number" ? value.timeUsedSeconds : 0
27551
+ };
27552
+ };
27553
+ const startTurn = () => {
27554
+ send({ id: 3, method: "turn/start", params: {
27555
+ threadId,
27556
+ input: [{ type: "text", text: request.prompt }],
27557
+ cwd: request.workdir,
27558
+ approvalPolicy: "never",
27559
+ sandboxPolicy,
27560
+ ...request.model ? { model: request.model } : {},
27561
+ ...request.reasoningEffort ? { effort: request.reasoningEffort } : {}
27562
+ } });
27563
+ };
27564
+ const setGoal = () => {
27565
+ send({ id: 4, method: "thread/goal/set", params: {
27566
+ threadId,
27567
+ objective: goal.objective,
27568
+ status: "active",
27569
+ origin: "user",
27570
+ ...goal.tokenBudget ? { tokenBudget: goal.tokenBudget } : {}
27571
+ } });
27572
+ };
27573
+ return {
27574
+ id: "codex",
27575
+ buildLaunch() {
27576
+ return launchCli({ spec: requireCliSpec("codex"), args: [
27577
+ "app-server",
27578
+ "--listen",
27579
+ "stdio://",
27580
+ ...request.permissionMode === "full" ? [] : ["-c", "mcp_servers={}", "-c", 'web_search="disabled"']
27581
+ ] });
27582
+ },
27583
+ startInput(writer) {
27584
+ write = writer;
27585
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "echo_goal", title: "Echo Goal", version: "1.0" }, capabilities: { experimentalApi: true } } });
27586
+ },
27587
+ tick() {
27588
+ if (!ended && !turnRunning && goalSet && idleSince && Date.now() - idleSince > GOAL_IDLE_END_MS) {
27589
+ return end([runLog.event("\u76EE\u6807\u957F\u65F6\u95F4\u6CA1\u6709\u7EE7\u7EED\uFF0C\u5DF2\u7ED3\u675F\u672C\u6B21\u8FD0\u884C")]);
27590
+ }
27591
+ return void 0;
27592
+ },
27593
+ controlGoal(action) {
27594
+ if (!write || !threadId || ended) return false;
27595
+ if (action === "pause") send({ id: nextId++, method: "thread/goal/set", params: { threadId, status: "paused", origin: "user" } });
27596
+ else send({ id: nextId++, method: "thread/goal/clear", params: { threadId, origin: "user" } });
27597
+ return true;
27598
+ },
27599
+ parseLine(line) {
27600
+ const message = tryJson(line);
27601
+ if (!message) return empty();
27602
+ if (message.id !== void 0 && !message.method) {
27603
+ const error62 = message.error;
27604
+ if (error62) {
27605
+ if (message.id === 4) return { display: [runLog.error(`\u8BBE\u7F6E\u76EE\u6807\u5931\u8D25\uFF1A${str(error62.message) ?? ""}`)], turnError: str(error62.message) ?? "\u8BBE\u7F6E\u76EE\u6807\u5931\u8D25", endProcess: true };
27606
+ if (typeof message.id === "number" && message.id < 10) return { display: [], turnError: str(error62.message) ?? "Codex \u8BF7\u6C42\u5931\u8D25", endProcess: true };
27607
+ return { display: [runLog.error(str(error62.message) ?? "\u76EE\u6807\u64CD\u4F5C\u5931\u8D25")] };
27608
+ }
27609
+ const result = message.result ?? {};
27610
+ if (message.id === 1) {
27611
+ send({ method: "initialized" });
27612
+ send({ id: 2, method: threadId ? "thread/resume" : "thread/start", params: {
27613
+ cwd: request.workdir,
27614
+ approvalPolicy: "never",
27615
+ sandbox: request.permissionMode === "full" ? "danger-full-access" : "read-only",
27616
+ ...request.model ? { model: request.model } : {},
27617
+ ...threadId ? { threadId } : { ephemeral: false }
27618
+ } });
27619
+ return empty();
27620
+ }
27621
+ if (message.id === 2) {
27622
+ const id = str((result.thread ?? {}).id);
27623
+ if (!id) return { display: [], turnError: "Codex \u672A\u8FD4\u56DE\u539F\u751F\u4F1A\u8BDD ID", endProcess: true };
27624
+ threadId = id;
27625
+ startTurn();
27626
+ return { display: [runLog.event(`\u4F1A\u8BDD ${id}`)], sessionId: id };
27627
+ }
27628
+ if (message.id === 3) {
27629
+ setGoal();
27630
+ return empty();
27631
+ }
27632
+ if (message.id === 4) {
27633
+ goalSet = true;
27634
+ const goalSnapshot = snapshot(result.goal ?? {});
27635
+ if (goalSnapshot) goalStatus = goalSnapshot.status;
27636
+ return { display: [runLog.event(`\u76EE\u6807\uFF1A${goal.objective}`)], ...goalSnapshot ? { goal: goalSnapshot } : {} };
27637
+ }
27638
+ return empty();
27639
+ }
27640
+ const params = message.params ?? {};
27641
+ if (params.threadId && params.threadId !== threadId) return empty();
27642
+ if (message.id !== void 0) {
27643
+ send({ id: message.id, error: { code: -32601, message: "\u76EE\u6807\u8FD0\u884C\u4E0D\u652F\u6301\u4EA4\u4E92\u5F0F\u786E\u8BA4" } });
27644
+ return { display: [runLog.error("CLI \u8BF7\u6C42\u4EA4\u4E92\u786E\u8BA4\uFF0C\u76EE\u6807\u8FD0\u884C\u65E0\u6CD5\u56DE\u7B54\uFF0C\u5DF2\u62D2\u7EDD")] };
27645
+ }
27646
+ switch (message.method) {
27647
+ case "turn/started": {
27648
+ turnRunning = true;
27649
+ idleSince = 0;
27650
+ currentTurn = str((params.turn ?? {}).id) ?? currentTurn;
27651
+ turnMessage = "";
27652
+ return { display: [runLog.event("\u5F00\u59CB\u5904\u7406")] };
27653
+ }
27654
+ case "item/completed": {
27655
+ const item = params.item ?? {};
27656
+ if (item.type === "agentMessage") {
27657
+ turnMessage = String(item.text ?? "");
27658
+ return { display: textRows("\u203A ", turnMessage), message: turnMessage };
27659
+ }
27660
+ if (item.type === "commandExecution") return { display: [runLog.command(String(item.command ?? "")), runLog.commandExit(typeof item.exitCode === "number" ? item.exitCode : void 0)] };
27661
+ if (item.type === "fileChange") return { display: [runLog.fileChange()] };
27662
+ return empty();
27663
+ }
27664
+ case "turn/completed": {
27665
+ turnRunning = false;
27666
+ idleSince = Date.now();
27667
+ const turn = params.turn ?? {};
27668
+ const id = str(turn.id) ?? currentTurn;
27669
+ const rows = [runLog.event(turn.status === "completed" ? "\u672C\u8F6E\u5B8C\u6210" : `\u672C\u8F6E\u7ED3\u675F\uFF08${String(turn.status ?? "")}\uFF09`)];
27670
+ const parsed = maybeEnd(rows);
27671
+ return { ...parsed, ...id && turnMessage ? { goalTurn: { turnId: id, message: turnMessage } } : {} };
27672
+ }
27673
+ case "thread/goal/updated": {
27674
+ const goalSnapshot = snapshot(params.goal ?? {});
27675
+ if (!goalSnapshot) return empty();
27676
+ goalStatus = goalSnapshot.status;
27677
+ return { ...maybeEnd(goalSnapshot.status === "active" ? [] : [runLog.event(`\u76EE\u6807\u72B6\u6001\uFF1A${goalSnapshot.status}`)]), goal: goalSnapshot };
27678
+ }
27679
+ case "thread/goal/cleared": {
27680
+ goalStatus = "cleared";
27681
+ return { ...maybeEnd([runLog.event("\u76EE\u6807\u5DF2\u6E05\u9664")]), goal: { objective: "", status: "paused", tokens_used: 0, time_used_seconds: 0, cleared: true } };
27682
+ }
27683
+ default:
27684
+ return empty();
27685
+ }
27686
+ }
27687
+ };
27688
+ }
27689
+
27690
+ // src/providers/cli/codex-fork.ts
27691
+ import { spawn as spawn7 } from "node:child_process";
27692
+ import { createInterface as createInterface4 } from "node:readline";
27693
+
27694
+ // src/runs/process-tree.ts
27695
+ var KILL_GRACE_MS = 3e3;
27696
+ async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
27697
+ if (!Number.isInteger(rootPid) || rootPid <= 1) return;
27698
+ await currentPlatform.killProcessTree(rootPid, graceMs);
27699
+ }
27700
+
27701
+ // src/providers/cli/codex-fork.ts
27702
+ var FORK_TIMEOUT_MS = 9e4;
27703
+ async function forkCodexThread(options) {
27704
+ const launch = launchCli({ spec: requireCliSpec("codex"), args: ["app-server", "--listen", "stdio://"] });
27705
+ const child = spawn7(launch.executable, launch.args, {
27706
+ cwd: options.workdir,
27707
+ env: launch.env,
27708
+ shell: false,
27709
+ windowsHide: true,
27710
+ detached: currentPlatform.runsInOwnProcessGroup,
27711
+ stdio: ["pipe", "pipe", "pipe"]
27712
+ });
27713
+ const stderr = [];
27714
+ createInterface4({ input: child.stderr }).on("line", (line) => {
27715
+ stderr.push(line);
27716
+ if (stderr.length > 20) stderr.shift();
27717
+ });
27718
+ let nextId = 1;
27719
+ const pending = /* @__PURE__ */ new Map();
27720
+ const call = (method, params) => new Promise((resolve8, reject) => {
27721
+ const id = nextId++;
27722
+ pending.set(id, { resolve: resolve8, reject });
27723
+ child.stdin.write(`${JSON.stringify({ id, method, params })}
27724
+ `);
27725
+ });
27726
+ createInterface4({ input: child.stdout }).on("line", (line) => {
27727
+ const message = tryJson(line);
27728
+ if (!message || typeof message.id !== "number" || message.method) return;
27729
+ const waiter = pending.get(message.id);
27730
+ if (!waiter) return;
27731
+ pending.delete(message.id);
27732
+ const error62 = message.error;
27733
+ if (error62) waiter.reject(new Error(String(error62.message ?? "Codex \u8BF7\u6C42\u5931\u8D25")));
27734
+ else waiter.resolve(message.result ?? {});
27735
+ });
27736
+ const failed = new Promise((_, reject) => {
27737
+ child.once("error", (error62) => reject(new Error(`\u65E0\u6CD5\u542F\u52A8 Codex\uFF1A${error62.message}`)));
27738
+ child.once("exit", (code2) => reject(new Error(`Codex \u5DF2\u9000\u51FA\uFF08exit ${code2 ?? "?"}\uFF09${stderr.length ? `\uFF1A${stderr.slice(-3).join(" ")}` : ""}`)));
27739
+ });
27740
+ const timer = setTimeout(() => {
27741
+ void killProcessTree(child.pid ?? 0);
27742
+ }, FORK_TIMEOUT_MS);
27743
+ try {
27744
+ const run2 = async () => {
27745
+ await call("initialize", { clientInfo: { name: "echo_session_fork", title: "Echo Session Fork", version: "1.0" }, capabilities: { experimentalApi: true } });
27746
+ child.stdin.write(`${JSON.stringify({ method: "initialized" })}
27747
+ `);
27748
+ let lastTurnId;
27749
+ if (options.keepTurns > 0) {
27750
+ const ids = [];
27751
+ let cursor;
27752
+ do {
27753
+ const page = await call("thread/turns/list", { threadId: options.sourceThreadId, sortDirection: "asc", limit: 100, ...cursor ? { cursor } : {} });
27754
+ for (const turn of page.data ?? []) if (typeof turn.id === "string") ids.push(turn.id);
27755
+ cursor = typeof page.nextCursor === "string" ? page.nextCursor : void 0;
27756
+ } while (cursor && ids.length < options.keepTurns);
27757
+ if (ids.length > options.keepTurns) lastTurnId = ids[options.keepTurns - 1];
27758
+ }
27759
+ const result = await call("thread/fork", {
27760
+ threadId: options.sourceThreadId,
27761
+ ephemeral: false,
27762
+ excludeTurns: true,
27763
+ cwd: options.workdir,
27764
+ ...lastTurnId ? { lastTurnId } : {}
27765
+ });
27766
+ const thread = result.thread ?? {};
27767
+ if (typeof thread.id !== "string" || !thread.id) throw new Error("Codex \u672A\u8FD4\u56DE\u5206\u53C9\u540E\u7684\u4F1A\u8BDD ID");
27768
+ return thread.id;
27769
+ };
27770
+ return await Promise.race([run2(), failed]);
27771
+ } finally {
27772
+ clearTimeout(timer);
27773
+ child.stdin?.end();
27774
+ void killProcessTree(child.pid ?? 0, 1e3);
27775
+ }
27776
+ }
27777
+
27453
27778
  // src/runs/run-recorder.ts
27454
27779
  import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs";
27455
27780
  import { homedir as homedir7 } from "node:os";
@@ -27478,13 +27803,6 @@ var RunRecorder = class _RunRecorder {
27478
27803
  }
27479
27804
  };
27480
27805
 
27481
- // src/runs/process-tree.ts
27482
- var KILL_GRACE_MS = 3e3;
27483
- async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
27484
- if (!Number.isInteger(rootPid) || rootPid <= 1) return;
27485
- await currentPlatform.killProcessTree(rootPid, graceMs);
27486
- }
27487
-
27488
27806
  // src/runs/task-attachments.ts
27489
27807
  import { createHash, randomUUID as randomUUID2 } from "node:crypto";
27490
27808
  import { constants as constants2 } from "node:fs";
@@ -27643,17 +27961,17 @@ var RunSupervisor = class {
27643
27961
  this.chatRunIds.delete(runId);
27644
27962
  }
27645
27963
  recentRuns() {
27646
- const running = [...this.active.values()].map((run2) => ({ runId: run2.runId, workstationId: run2.workstationId, status: "running", at: run2.startedAt }));
27647
- const done = [...this.recent.values()].map((run2) => ({ runId: run2.runId, workstationId: run2.workstationId, status: run2.status, at: run2.finishedAt }));
27964
+ const running = [...this.active.values()].map((run2) => ({ runId: run2.runId, sessionKey: run2.sessionKey, status: "running", at: run2.startedAt }));
27965
+ const done = [...this.recent.values()].map((run2) => ({ runId: run2.runId, sessionKey: run2.sessionKey, status: run2.status, at: run2.finishedAt }));
27648
27966
  return [...running, ...done].sort((a, b) => b.at - a.at).slice(0, 30);
27649
27967
  }
27650
27968
  /**
27651
- * Starts a turn. Refusals (busy workstation, concurrency limit, bad work
27969
+ * Starts a turn. Refusals (busy session, concurrency limit, bad work
27652
27970
  * directory, unknown CLI) are reported as a failed run, never thrown.
27653
27971
  */
27654
27972
  /**
27655
- * Different workstations run in parallel without a machine-wide cap by
27656
- * default; each workstation still runs one turn at a time. A cap applies
27973
+ * Different sessions run in parallel without a machine-wide cap by
27974
+ * default; each session still runs one turn at a time. A cap applies
27657
27975
  * only when the operator sets TOC_OCRA_MAX_RUNS / maxConcurrentRuns.
27658
27976
  * The run being started is already counted in `preparing`.
27659
27977
  */
@@ -27664,7 +27982,7 @@ var RunSupervisor = class {
27664
27982
  async start(payload) {
27665
27983
  if (this.preparing.has(payload.run_id)) return;
27666
27984
  const controller = new AbortController();
27667
- this.preparing.set(payload.run_id, { workstationId: payload.workstation_id, controller });
27985
+ this.preparing.set(payload.run_id, { sessionKey: sessionKeyOf(payload), controller });
27668
27986
  try {
27669
27987
  await this.startPrepared(payload, controller.signal);
27670
27988
  } finally {
@@ -27677,14 +27995,15 @@ var RunSupervisor = class {
27677
27995
  return;
27678
27996
  }
27679
27997
  if (payload.chat_session_id) this.chatRunIds.add(payload.run_id);
27998
+ const sessionKey = sessionKeyOf(payload);
27680
27999
  const refuse = async (reason) => {
27681
28000
  const failure2 = typeof reason === "string" ? { kind: "hostFault", message: reason } : reason;
27682
28001
  this.logger.warn("run-refused", { runId: payload.run_id, error: failure2.message, kind: failure2.kind });
27683
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "failed", chat: !!payload.chat_session_id });
28002
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "failed", chat: !!payload.chat_session_id });
27684
28003
  await this.report(payload.run_id, { status: "failed", error: failure2.message, failure_kind: failure2.kind, duration_ms: 0 });
27685
28004
  };
27686
- if ([...this.active.values()].some((run3) => run3.workstationId === payload.workstation_id) || [...this.preparing].some(([id, run3]) => id !== payload.run_id && run3.workstationId === payload.workstation_id)) {
27687
- return refuse("\u672C\u673A\u8BE5\u5DE5\u4F4D\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
28005
+ if ([...this.active.values()].some((run3) => run3.sessionKey === sessionKey) || [...this.preparing].some(([id, run3]) => id !== payload.run_id && run3.sessionKey === sessionKey)) {
28006
+ return refuse("\u672C\u673A\u8BE5\u4F1A\u8BDD\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
27688
28007
  }
27689
28008
  if (this.overConcurrencyCap()) {
27690
28009
  return refuse(`\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650\uFF08${this.config.maxConcurrentRuns}\uFF09`);
@@ -27697,7 +28016,7 @@ var RunSupervisor = class {
27697
28016
  let provider = cli.headless;
27698
28017
  let workdir;
27699
28018
  try {
27700
- if (payload.task_attachments?.length && !payload.workdir) throw new Error("\u9644\u4EF6\u9700\u8981\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u5DE5\u4F4D\u5DE5\u4F5C\u76EE\u5F55");
28019
+ if (payload.task_attachments?.length && !payload.workdir) throw new Error("\u9644\u4EF6\u9700\u8981\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u4F1A\u8BDD\u5DE5\u4F5C\u76EE\u5F55");
27701
28020
  workdir = payload.chat_session_id && !payload.workdir ? await this.defaultChatWorkdir() : await this.validateWorkdir(payload.workdir || this.config.allowedRoots[0]);
27702
28021
  } catch (error62) {
27703
28022
  return refuse(errorMessage(error62));
@@ -27707,7 +28026,7 @@ var RunSupervisor = class {
27707
28026
  signal2.throwIfAborted();
27708
28027
  } catch (error62) {
27709
28028
  if (signal2.aborted) {
27710
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "cancelled", chat: !!payload.chat_session_id });
28029
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: "cancelled", chat: !!payload.chat_session_id });
27711
28030
  await this.report(payload.run_id, { status: "cancelled", error: "\u9644\u4EF6\u51C6\u5907\u5DF2\u53D6\u6D88", duration_ms: 0 });
27712
28031
  return;
27713
28032
  }
@@ -27761,7 +28080,24 @@ var RunSupervisor = class {
27761
28080
  sessionsBefore = new Set(saved.map((session) => session.id));
27762
28081
  }
27763
28082
  }
27764
- 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");
28083
+ const fork = payload.fork && !payload.chat_session_id ? { sourceSessionId: payload.fork.source_session_id, keepTurns: payload.fork.keep_turns } : void 0;
28084
+ if (fork && provider.id === "codex" && !sessionId) {
28085
+ try {
28086
+ sessionId = await forkCodexThread({ sourceThreadId: fork.sourceSessionId, keepTurns: fork.keepTurns, workdir, permissionMode });
28087
+ sessionNote += `\u25CF \u5DF2\u4ECE\u4F1A\u8BDD ${fork.sourceSessionId} \u5206\u53C9${fork.keepTurns > 0 ? `\uFF08\u4FDD\u7559\u524D ${fork.keepTurns} \u8F6E\uFF09` : ""}\uFF0C\u65B0\u4F1A\u8BDD ${sessionId}
28088
+ `;
28089
+ } catch (error62) {
28090
+ return refuse({ kind: "startFailed", message: `\u5206\u53C9 Codex \u4F1A\u8BDD\u5931\u8D25\uFF1A${errorMessage(error62)}` });
28091
+ }
28092
+ }
28093
+ if (payload.goal && !payload.chat_session_id) {
28094
+ if (provider.id !== "codex") return refuse("\u76EE\u6807\u6A21\u5F0F\u53EA\u652F\u6301 Codex");
28095
+ provider = codexGoalProvider(
28096
+ { permissionMode, prompt: payload.prompt, sessionId, model: payload.model, reasoningEffort: payload.reasoning_effort, workdir },
28097
+ { objective: payload.goal.objective, ...payload.goal.token_budget ? { tokenBudget: payload.goal.token_budget } : {} }
28098
+ );
28099
+ }
28100
+ if ([...this.active.values()].some((run3) => run3.sessionKey === sessionKey)) return refuse("\u672C\u673A\u8BE5\u4F1A\u8BDD\u5DF2\u6709\u4EFB\u52A1\u5728\u8FD0\u884C");
27765
28101
  if (this.overConcurrencyCap()) return refuse(`\u672C\u673A\u540C\u65F6\u8FD0\u884C\u7684\u4EFB\u52A1\u5DF2\u8FBE\u4E0A\u9650\uFF08${this.config.maxConcurrentRuns}\uFF09`);
27766
28102
  if (provider.forTurn) provider = provider.forTurn();
27767
28103
  const launch = provider.buildLaunch({
@@ -27770,12 +28106,13 @@ var RunSupervisor = class {
27770
28106
  sessionId,
27771
28107
  model: payload.model,
27772
28108
  reasoningEffort: payload.reasoning_effort,
27773
- workdir
28109
+ workdir,
28110
+ ...fork ? { fork } : {}
27774
28111
  });
27775
28112
  if (!fitsCommandLine(launch)) return refuse(cliFailure("promptTooLong", { label: cli.label }));
27776
28113
  let child;
27777
28114
  try {
27778
- child = spawn7(launch.executable, launch.args, {
28115
+ child = spawn8(launch.executable, launch.args, {
27779
28116
  cwd: workdir,
27780
28117
  env: launch.env,
27781
28118
  detached: currentPlatform.runsInOwnProcessGroup,
@@ -27796,7 +28133,7 @@ var RunSupervisor = class {
27796
28133
  queuedBytes: 0,
27797
28134
  forwardingFailed: false,
27798
28135
  runId: payload.run_id,
27799
- workstationId: payload.workstation_id,
28136
+ sessionKey,
27800
28137
  agentType: provider.id,
27801
28138
  cli: { label: cli.label, ...cli.installHint ? { installHint: cli.installHint } : {} },
27802
28139
  provider,
@@ -27818,7 +28155,8 @@ var RunSupervisor = class {
27818
28155
  timedOut: false,
27819
28156
  tail: new TerminalTailBuffer(),
27820
28157
  timers: [],
27821
- ...payload.stall_policy && !payload.chat_session_id ? { stallPolicy: { idleSeconds: payload.stall_policy.idle_seconds, categorySeconds: payload.stall_policy.category_seconds ?? {} } } : {},
28158
+ // A goal run waits between turns while the CLI decides; no stall check.
28159
+ ...payload.stall_policy && !payload.chat_session_id && !payload.goal ? { stallPolicy: { idleSeconds: payload.stall_policy.idle_seconds, categorySeconds: payload.stall_policy.category_seconds ?? {} } } : {},
27822
28160
  lastCategory: "other",
27823
28161
  lastLine: "",
27824
28162
  lastOutputAt: Date.now()
@@ -27865,9 +28203,9 @@ var RunSupervisor = class {
27865
28203
  this.applyParsed(run2, run2.stream.stdout(chunk), chunk);
27866
28204
  });
27867
28205
  } else {
27868
- createInterface4({ input: child.stdout }).on("line", (line) => this.onStdout(run2, line));
28206
+ createInterface5({ input: child.stdout }).on("line", (line) => this.onStdout(run2, line));
27869
28207
  }
27870
- createInterface4({ input: child.stderr }).on("line", (line) => {
28208
+ createInterface5({ input: child.stderr }).on("line", (line) => {
27871
28209
  run2.recorder?.write({ stream: "stderr", data: line });
27872
28210
  const clean = sanitizeTerminalLine(line);
27873
28211
  if (!clean.trim()) return;
@@ -27931,6 +28269,14 @@ var RunSupervisor = class {
27931
28269
  void killProcessTree(run2.pid);
27932
28270
  }, this.config.maxRunSeconds * 1e3));
27933
28271
  }
28272
+ if (provider.tick) {
28273
+ const ticker = setInterval(() => {
28274
+ const parsed = this.active.has(run2.runId) ? run2.provider.tick?.() : void 0;
28275
+ if (parsed) this.applyParsed(run2, parsed, "");
28276
+ }, STALL_CHECK_INTERVAL_MS);
28277
+ ticker.unref?.();
28278
+ run2.timers.push(ticker);
28279
+ }
27934
28280
  if (run2.stallPolicy) {
27935
28281
  const watchdog = setInterval(() => this.checkStall(run2), STALL_CHECK_INTERVAL_MS);
27936
28282
  watchdog.unref?.();
@@ -27958,6 +28304,14 @@ var RunSupervisor = class {
27958
28304
  }
27959
28305
  if (!parsed.display.length && rawLine.trim()) run2.lastOutputAt = Date.now();
27960
28306
  if (parsed.message !== void 0) run2.finalMessage = sanitizeTerminalLine(parsed.message);
28307
+ if (parsed.goal) {
28308
+ const goal = { ...parsed.goal, objective: sanitizeChatText(parsed.goal.objective) };
28309
+ void this.reporter.goal?.(run2.runId, goal).catch((error62) => this.logger.warn("goal-report-failed", { runId: run2.runId, error: errorMessage(error62) }));
28310
+ }
28311
+ if (parsed.goalTurn) {
28312
+ const turn = { turn_id: parsed.goalTurn.turnId, message: sanitizeChatText(parsed.goalTurn.message) };
28313
+ void this.reporter.goalTurn?.(run2.runId, turn).catch((error62) => this.logger.warn("goal-turn-report-failed", { runId: run2.runId, error: errorMessage(error62) }));
28314
+ }
27961
28315
  if (parsed.turnError) {
27962
28316
  run2.turnError = sanitizeTerminalLine(parsed.turnError);
27963
28317
  if (parsed.failureKind) run2.turnFailure = parsed.failureKind;
@@ -28060,7 +28414,7 @@ var RunSupervisor = class {
28060
28414
  run2.tail.append(`\u25CF \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF1A${report.status}${code2 !== null ? `\uFF08exit ${code2}\uFF09` : ""}
28061
28415
  `);
28062
28416
  run2.recorder?.write({ result: { ...report, duration_ms: 0 }, log: run2.tail.read({ limit: 2e3 }).lines });
28063
- this.remember({ runId: run2.runId, workstationId: run2.workstationId, tail: run2.tail, finishedAt: Date.now(), status: report.status, chat: !!run2.chat });
28417
+ this.remember({ runId: run2.runId, sessionKey: run2.sessionKey, tail: run2.tail, finishedAt: Date.now(), status: report.status, chat: !!run2.chat });
28064
28418
  this.logger.info("run-finished", { runId: run2.runId, status: report.status, code: code2, durationMs });
28065
28419
  await this.report(run2.runId, report);
28066
28420
  }
@@ -28176,13 +28530,22 @@ var RunSupervisor = class {
28176
28530
  await killProcessTree(run2.pid);
28177
28531
  return true;
28178
28532
  }
28533
+ /** Pauses or clears the goal of a running goal run; false when there is none. */
28534
+ controlGoal(runId, action) {
28535
+ const run2 = this.active.get(runId);
28536
+ if (!run2?.provider.controlGoal) return false;
28537
+ const applied = run2.provider.controlGoal(action);
28538
+ if (applied) run2.tail.append(`\u25CF \u6536\u5230${action === "pause" ? "\u6682\u505C" : "\u6E05\u9664"}\u76EE\u6807\u6307\u4EE4
28539
+ `);
28540
+ return applied;
28541
+ }
28179
28542
  tail(query, limit, beforeCursor) {
28180
28543
  const byId = (id) => id ? this.active.get(id) ?? this.recent.get(id) : void 0;
28181
- const byWorkstation = (id) => {
28544
+ const bySession = (id) => {
28182
28545
  if (!id) return void 0;
28183
- const live = [...this.active.values()].find((run2) => run2.workstationId === id);
28546
+ const live = [...this.active.values()].find((run2) => run2.sessionKey === id);
28184
28547
  if (live) return live;
28185
- return [...this.recent.values()].filter((run2) => run2.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
28548
+ return [...this.recent.values()].filter((run2) => run2.sessionKey === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
28186
28549
  };
28187
28550
  const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
28188
28551
  if (query.runId) {
@@ -28191,7 +28554,7 @@ var RunSupervisor = class {
28191
28554
  const read2 = run2.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
28192
28555
  return { ...read2, status: this.active.has(run2.runId) ? "running" : "finished", run_id: run2.runId };
28193
28556
  }
28194
- const target = byWorkstation(query.workstationId);
28557
+ const target = bySession(query.taskChainId);
28195
28558
  if (!target) return { ...empty, status: "idle" };
28196
28559
  const read = target.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
28197
28560
  return { ...read, status: this.active.has(target.runId) ? "running" : "finished", run_id: target.runId };
@@ -28235,7 +28598,7 @@ var RunSupervisor = class {
28235
28598
  throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5728\u5141\u8BB8\u8303\u56F4\u5185\uFF1A${input2}`);
28236
28599
  }
28237
28600
  async prepareTaskFiles(payload, signal2 = AbortSignal.timeout(15 * 6e4), workdir) {
28238
- if (!payload.workdir) throw new Error("\u8BF7\u5148\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u5DE5\u4F4D\u5DE5\u4F5C\u76EE\u5F55");
28601
+ if (!payload.workdir) throw new Error("\u8BF7\u5148\u914D\u7F6E\u8BBE\u5907\u9ED8\u8BA4\u76EE\u5F55\u6216\u4F1A\u8BDD\u5DE5\u4F5C\u76EE\u5F55");
28239
28602
  if (!this.reporter.taskFile) throw new Error("\u4EFB\u52A1\u9644\u4EF6\u4E0B\u8F7D\u672A\u914D\u7F6E");
28240
28603
  return prepareTaskAttachments(payload, workdir ?? await this.validateWorkdir(payload.workdir), this.reporter.taskFile, AbortSignal.any([signal2, AbortSignal.timeout(15 * 6e4)]));
28241
28604
  }
@@ -28243,6 +28606,9 @@ var RunSupervisor = class {
28243
28606
  function failedReport(failure2, durationMs) {
28244
28607
  return { status: "failed", error: failure2.message, failure_kind: failure2.kind, duration_ms: durationMs };
28245
28608
  }
28609
+ function sessionKeyOf(payload) {
28610
+ return payload.task_chain_id || payload.chat_session_id || payload.run_id;
28611
+ }
28246
28612
  function errorMessage(error62) {
28247
28613
  return error62 instanceof Error ? error62.message : String(error62);
28248
28614
  }
@@ -28306,10 +28672,8 @@ async function runCliSmoke(options = {}) {
28306
28672
  await supervisor.start({
28307
28673
  cli_policy: { enabled: true, mode, version: 1 },
28308
28674
  run_id: runId,
28309
- workstation_id: `smoke-${id}`,
28310
- workstation_name: "smoke",
28311
28675
  agent_type: id,
28312
- task_chain_id: "",
28676
+ task_chain_id: `smoke-${id}`,
28313
28677
  message_id: "",
28314
28678
  prompt: PROMPTS[scenario],
28315
28679
  session_id: "",
@@ -28719,7 +29083,7 @@ import { randomUUID as randomUUID3 } from "node:crypto";
28719
29083
  import { join as join16 } from "node:path";
28720
29084
 
28721
29085
  // src/exec/script-runner.ts
28722
- import { spawn as spawn8 } from "node:child_process";
29086
+ import { spawn as spawn9 } from "node:child_process";
28723
29087
  var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
28724
29088
  function executeScript(command, workdir, timeoutSeconds) {
28725
29089
  return new Promise((resolveExecution) => {
@@ -28750,7 +29114,7 @@ function executeScript(command, workdir, timeoutSeconds) {
28750
29114
  };
28751
29115
  let child;
28752
29116
  try {
28753
- child = spawn8(executable, args, {
29117
+ child = spawn9(executable, args, {
28754
29118
  cwd: workdir,
28755
29119
  env: process.env,
28756
29120
  detached: ownGroup,
@@ -29171,6 +29535,12 @@ var GatewayClient = class {
29171
29535
  await pipeline(Readable.fromWeb(response.body), verifier, target, { signal: signal2 });
29172
29536
  if (received !== size || hash2.digest("hex") !== sha256) throw new Error("\u9644\u4EF6\u4E0B\u8F7D\u4E0D\u5B8C\u6574\u6216\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
29173
29537
  }
29538
+ runGoal(runId, body) {
29539
+ return this.request("POST", `/runs/${encodeURIComponent(runId)}/goal`, body, 15e3);
29540
+ }
29541
+ runGoalTurn(runId, body) {
29542
+ return this.request("POST", `/runs/${encodeURIComponent(runId)}/goal-turn`, body, 15e3);
29543
+ }
29174
29544
  runFinished(runId, body) {
29175
29545
  return this.request("POST", `/runs/${encodeURIComponent(runId)}/finished`, body, 15e3);
29176
29546
  }
@@ -29214,7 +29584,7 @@ async function listDirectory(requested, allowedRoots) {
29214
29584
  }
29215
29585
 
29216
29586
  // src/workspace/workspace-manager.ts
29217
- import { spawn as spawn9 } from "node:child_process";
29587
+ import { spawn as spawn10 } from "node:child_process";
29218
29588
  import { chmod as chmod3, mkdir as mkdir6, mkdtemp as mkdtemp2, opendir, realpath as realpath5, rm as rm4, stat as stat5, writeFile as writeFile6 } from "node:fs/promises";
29219
29589
  import { homedir as homedir10, tmpdir as tmpdir3 } from "node:os";
29220
29590
  import { isAbsolute as isAbsolute4, join as join15, relative as relative3, resolve as resolve5 } from "node:path";
@@ -29558,7 +29928,7 @@ var WorkspaceManager = class {
29558
29928
  }
29559
29929
  runGit(args, cwd, timeoutSeconds, allowFailure = false, environment) {
29560
29930
  return new Promise((resolveCommand, rejectCommand) => {
29561
- const child = spawn9("git", args, {
29931
+ const child = spawn10("git", args, {
29562
29932
  cwd,
29563
29933
  env: environment ?? process.env,
29564
29934
  shell: false,
@@ -29636,8 +30006,6 @@ var DEFAULT_POLICY = { script: { enabled: false }, sql: { enabled: false } };
29636
30006
  var RunStartPayloadSchema = external_exports.object({
29637
30007
  cli_policy: external_exports.object({ enabled: external_exports.boolean(), mode: external_exports.enum(["restricted", "full"]), version: external_exports.literal(1) }).optional(),
29638
30008
  run_id: external_exports.string().min(1).max(64),
29639
- workstation_id: external_exports.string().min(1).max(64),
29640
- workstation_name: external_exports.string().optional().default(""),
29641
30009
  agent_type: external_exports.string().min(1).max(40),
29642
30010
  task_chain_id: external_exports.string().optional().default(""),
29643
30011
  message_id: external_exports.string().optional().default(""),
@@ -29649,6 +30017,17 @@ var RunStartPayloadSchema = external_exports.object({
29649
30017
  model: external_exports.string().max(100).optional().default(""),
29650
30018
  reasoning_effort: external_exports.string().max(40).optional().default(""),
29651
30019
  workdir: external_exports.string().max(4096).optional().default(""),
30020
+ /**
30021
+ * CLI fork (分叉): before this turn, copy `source_session_id` (its first
30022
+ * `keep_turns` CLI turns; 0 = all) into this session's own CLI session.
30023
+ * Ignored once the session exists on this computer.
30024
+ */
30025
+ fork: external_exports.object({ source_session_id: external_exports.string().min(1).max(200), keep_turns: external_exports.number().int().min(0).max(1e5) }).nullish(),
30026
+ /**
30027
+ * Goal run (目标模式, Codex): after the turn starts, hand the CLI this
30028
+ * objective; the run stays open while the CLI continues by itself.
30029
+ */
30030
+ goal: external_exports.object({ objective: external_exports.string().max(8e3), token_budget: external_exports.number().int().positive().nullish() }).nullish(),
29652
30031
  /** Shown as the first line of this run's log (e.g. why it is an automatic resume). */
29653
30032
  notice: external_exports.string().max(1e3).nullish(),
29654
30033
  /**
@@ -29662,9 +30041,10 @@ var RunStartPayloadSchema = external_exports.object({
29662
30041
  }).nullish()
29663
30042
  });
29664
30043
  var RunCancelPayloadSchema = external_exports.object({ run_id: external_exports.string().min(1).max(64) });
30044
+ var RunGoalPayloadSchema = external_exports.object({ run_id: external_exports.string().min(1).max(64), action: external_exports.enum(["pause", "clear"]) });
29665
30045
  var RunTailPayloadSchema = external_exports.object({
29666
30046
  run_id: external_exports.string().max(64).optional(),
29667
- workstation_id: external_exports.string().max(64).optional(),
30047
+ task_chain_id: external_exports.string().max(64).optional(),
29668
30048
  lines: external_exports.number().int().positive().max(2e3).optional(),
29669
30049
  before_cursor: external_exports.number().int().min(0).optional()
29670
30050
  });
@@ -29744,6 +30124,12 @@ var AgentRuntime = class {
29744
30124
  finished: async (runId, report) => {
29745
30125
  this.pendingReports.set(runId, report);
29746
30126
  await this.flushReport(runId);
30127
+ },
30128
+ goal: async (runId, report) => {
30129
+ await this.retry(() => this.client.runGoal(runId, report), 3);
30130
+ },
30131
+ goalTurn: async (runId, report) => {
30132
+ await this.retry(() => this.client.runGoalTurn(runId, report), 9);
29747
30133
  }
29748
30134
  };
29749
30135
  this.workspaces = new WorkspaceManager(config2, this.logger);
@@ -29816,7 +30202,7 @@ var AgentRuntime = class {
29816
30202
  activeSessions: this.runs.activeCount,
29817
30203
  storedRuns: this.runs.recentRuns().length,
29818
30204
  startedAt: this.startedAt,
29819
- runs: this.runs.recentRuns().map((run2) => ({ runId: run2.runId, status: run2.status, sessionId: run2.workstationId, updatedAt: new Date(run2.at).toISOString() })),
30205
+ runs: this.runs.recentRuns().map((run2) => ({ runId: run2.runId, status: run2.status, sessionId: run2.sessionKey, updatedAt: new Date(run2.at).toISOString() })),
29820
30206
  capabilities: this.detection?.detectedIds ?? [],
29821
30207
  ...this.detection ? { detection: this.detection } : {},
29822
30208
  ...!this.lastHeartbeatOk && this.lastError ? { connectionError: this.lastError } : {},
@@ -29996,15 +30382,15 @@ var AgentRuntime = class {
29996
30382
  const cancelled = await this.runs.cancel(payload.run_id);
29997
30383
  return { success: true, result: { cancelled } };
29998
30384
  }
30385
+ case "run.goal": {
30386
+ const payload = RunGoalPayloadSchema.parse(command.payload);
30387
+ return { success: true, result: { applied: this.runs.controlGoal(payload.run_id, payload.action) } };
30388
+ }
29999
30389
  case "run.tail": {
30000
30390
  const payload = RunTailPayloadSchema.parse(command.payload);
30001
- const tail = this.runs.tail({ ...payload.run_id ? { runId: payload.run_id } : {}, ...payload.workstation_id ? { workstationId: payload.workstation_id } : {} }, payload.lines ?? 200, payload.before_cursor);
30391
+ const tail = this.runs.tail({ ...payload.run_id ? { runId: payload.run_id } : {}, ...payload.task_chain_id ? { taskChainId: payload.task_chain_id } : {} }, payload.lines ?? 200, payload.before_cursor);
30002
30392
  return { success: true, result: tail };
30003
30393
  }
30004
- case "workstation.create": {
30005
- const workstationId = String(command.payload?.workstation_id ?? command.workstation_id);
30006
- return { success: true, session_key: workstationId, result: { ready: true } };
30007
- }
30008
30394
  case "cli.detect":
30009
30395
  this.detection = await cliDetection.detect(true);
30010
30396
  void this.refreshCatalogs({ force: true });