toc-ocra 0.4.0 → 0.5.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.
@@ -3786,7 +3786,7 @@ var require_websocket_server = __commonJS({
3786
3786
 
3787
3787
  // src/plugin-service.ts
3788
3788
  import { existsSync as existsSync8 } from "node:fs";
3789
- import { delimiter as delimiter5, join as join26 } from "node:path";
3789
+ import { delimiter as delimiter5, join as join27 } from "node:path";
3790
3790
 
3791
3791
  // src/config.ts
3792
3792
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -24556,11 +24556,40 @@ function resolveWindowsCommandShim(shimPath) {
24556
24556
  }
24557
24557
  return void 0;
24558
24558
  }
24559
+ var TASKKILL_TIMEOUT_MS = 5e3;
24560
+ function processAlive(pid) {
24561
+ try {
24562
+ process.kill(pid, 0);
24563
+ return true;
24564
+ } catch (error62) {
24565
+ return error62.code === "EPERM";
24566
+ }
24567
+ }
24559
24568
  function taskkillTree(rootPid) {
24560
24569
  return new Promise((resolve9) => {
24570
+ let settled = false;
24571
+ const finish = () => {
24572
+ if (settled) return;
24573
+ settled = true;
24574
+ clearTimeout(timer);
24575
+ if (processAlive(rootPid)) {
24576
+ try {
24577
+ process.kill(rootPid, "SIGKILL");
24578
+ } catch {
24579
+ }
24580
+ }
24581
+ resolve9();
24582
+ };
24561
24583
  const child = spawn2(join5(SYSTEM_ROOT, "System32", "taskkill.exe"), ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
24562
- child.once("error", () => resolve9());
24563
- child.once("close", () => resolve9());
24584
+ const timer = setTimeout(() => {
24585
+ try {
24586
+ child.kill();
24587
+ } catch {
24588
+ }
24589
+ finish();
24590
+ }, TASKKILL_TIMEOUT_MS);
24591
+ child.once("error", finish);
24592
+ child.once("close", finish);
24564
24593
  });
24565
24594
  }
24566
24595
  function runPowerShell(script) {
@@ -25583,14 +25612,14 @@ function parseCodexModels(content) {
25583
25612
  return void 0;
25584
25613
  }
25585
25614
  }
25586
- async function readCodexModels(codexHome3, config2) {
25615
+ async function readCodexModels(codexHome4, config2) {
25587
25616
  const configuredCatalog = configValue(config2, "model_catalog_json");
25588
25617
  if (configuredCatalog) {
25589
- const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve3(codexHome3, configuredCatalog);
25618
+ const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve3(codexHome4, configuredCatalog);
25590
25619
  const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
25591
25620
  if (configuredModels?.length) return configuredModels;
25592
25621
  }
25593
- const cached3 = parseCodexModels(await readFile4(join11(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25622
+ const cached3 = parseCodexModels(await readFile4(join11(codexHome4, "models_cache.json"), "utf8").catch(() => ""));
25594
25623
  if (cached3?.length) return cached3;
25595
25624
  return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
25596
25625
  }
@@ -29749,7 +29778,7 @@ var CliDetectionService = class {
29749
29778
  var cliDetection = new CliDetectionService();
29750
29779
 
29751
29780
  // src/runtime/hub-runtime.ts
29752
- import { join as join25 } from "node:path";
29781
+ import { join as join26 } from "node:path";
29753
29782
 
29754
29783
  // node_modules/ws/wrapper.mjs
29755
29784
  var import_stream = __toESM(require_stream(), 1);
@@ -30684,7 +30713,7 @@ var HubLink = class {
30684
30713
  return;
30685
30714
  default:
30686
30715
  if (frame.type.startsWith("terminal.")) {
30687
- this.reply(frame.type, frame.id, { ok: false, error: rpcError(ERROR_TAGS.terminalUnsupported, "ocra \u8BBE\u5907\u5305\u6682\u4E0D\u652F\u6301 Web \u7EC8\u7AEF\uFF0C\u8BF7\u5728\u8BBE\u5907\u672C\u673A\u6253\u5F00\u7EC8\u7AEF", `frame=${frame.type}`) });
30716
+ this.reply(frame.type, frame.id, { ok: false, error: rpcError(ERROR_TAGS.terminalUnsupported, "ocra \u8BBE\u5907\u5305\u6682\u4E0D\u652F\u6301 Web \u7EC8\u7AEF\u548C\u8BBE\u5907\u547D\u4EE4\u6267\u884C\uFF08exec\uFF09\uFF0C\u8BF7\u5728\u8BBE\u5907\u672C\u673A\u7684\u7EC8\u7AEF\u91CC\u64CD\u4F5C", `frame=${frame.type}`) });
30688
30717
  }
30689
30718
  }
30690
30719
  }
@@ -30695,9 +30724,9 @@ function errorMessage(error62) {
30695
30724
 
30696
30725
  // src/t3/t3-backend.ts
30697
30726
  import { randomUUID as randomUUID5 } from "node:crypto";
30698
- import { mkdir as mkdir9, stat as stat8, writeFile as writeFile11 } from "node:fs/promises";
30699
- import { homedir as homedir14 } from "node:os";
30700
- import { basename as basename4, join as join24, resolve as resolve7 } from "node:path";
30727
+ import { mkdir as mkdir9, stat as stat9, writeFile as writeFile11 } from "node:fs/promises";
30728
+ import { homedir as homedir15 } from "node:os";
30729
+ import { basename as basename4, join as join25, resolve as resolve7 } from "node:path";
30701
30730
 
30702
30731
  // src/runs/orphan-registry.ts
30703
30732
  import { mkdir as mkdir5, readFile as readFile7, rename as rename6, writeFile as writeFile6 } from "node:fs/promises";
@@ -34103,6 +34132,144 @@ var ModelCatalogCollector = class {
34103
34132
  }
34104
34133
  };
34105
34134
 
34135
+ // src/t3/skills.ts
34136
+ import { readdir as readdir5, readFile as readFile10, stat as stat8 } from "node:fs/promises";
34137
+ import { homedir as homedir14 } from "node:os";
34138
+ import { join as join23 } from "node:path";
34139
+ var MAX_SKILLS_PER_CLI = 500;
34140
+ var MAX_SKILL_FILE_BYTES = 256 * 1024;
34141
+ var MAX_TEXT = 1e3;
34142
+ var claudeHome3 = () => process.env.CLAUDE_CONFIG_DIR?.trim().split(process.platform === "win32" ? ";" : ":")[0]?.trim() || join23(homedir14(), ".claude");
34143
+ var codexHome3 = () => process.env.CODEX_HOME?.trim() || join23(homedir14(), ".codex");
34144
+ function skillRoots(cli, home = homedir14()) {
34145
+ const agents = { directory: join23(home, ".agents", "skills"), source: "user", depth: 2 };
34146
+ switch (cli) {
34147
+ case "claude":
34148
+ return [
34149
+ { directory: join23(claudeHome3(), "skills"), source: "user", depth: 2 },
34150
+ // Installed plugins keep their skills under <plugin>/skills/<name>/SKILL.md, several levels down.
34151
+ { directory: join23(claudeHome3(), "plugins"), source: "plugin", depth: 7 }
34152
+ ];
34153
+ case "codex":
34154
+ return [
34155
+ // Bundled skills live in skills/.system/<name>.
34156
+ { directory: join23(codexHome3(), "skills"), source: "user", depth: 3 },
34157
+ { directory: join23(codexHome3(), "plugins"), source: "plugin", depth: 7 },
34158
+ agents
34159
+ ];
34160
+ case "antigravity":
34161
+ return [
34162
+ { directory: join23(home, ".gemini", "antigravity", "skills"), source: "user", depth: 2 },
34163
+ { directory: join23(home, ".gemini", "antigravity-cli", "skills"), source: "user", depth: 2 },
34164
+ agents
34165
+ ];
34166
+ }
34167
+ }
34168
+ var unquote = (value) => {
34169
+ const trimmed = value.trim();
34170
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
34171
+ const inner = trimmed.slice(1, -1);
34172
+ return trimmed.startsWith('"') ? inner.replace(/\\"/g, '"').replace(/\\n/g, "\n").replace(/\\\\/g, "\\") : inner.replace(/''/g, "'");
34173
+ }
34174
+ return trimmed;
34175
+ };
34176
+ function yamlScalars(source) {
34177
+ const out = {};
34178
+ const lines = source.split(/\r?\n/);
34179
+ const parents = [];
34180
+ for (let index = 0; index < lines.length; index++) {
34181
+ const line = lines[index];
34182
+ if (!line.trim() || line.trimStart().startsWith("#") || line.trimStart().startsWith("- ")) continue;
34183
+ const match = /^(\s*)([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line);
34184
+ if (!match) continue;
34185
+ const indent = match[1].length;
34186
+ while (parents.length && parents[parents.length - 1].indent >= indent) parents.pop();
34187
+ const path = [...parents.map((parent) => parent.key), match[2]].join(".");
34188
+ let value = match[3].replace(/\s+#.*$/, "");
34189
+ if (value === "") {
34190
+ parents.push({ indent, key: match[2] });
34191
+ continue;
34192
+ }
34193
+ if (/^[|>][+-]?$/.test(value)) {
34194
+ const folded = value.startsWith(">");
34195
+ const block = [];
34196
+ while (index + 1 < lines.length && (!lines[index + 1].trim() || lines[index + 1].length - lines[index + 1].trimStart().length > indent)) {
34197
+ block.push(lines[++index].trim());
34198
+ }
34199
+ value = block.join(folded ? " " : "\n").trim();
34200
+ } else value = unquote(value);
34201
+ out[path] = value;
34202
+ }
34203
+ return out;
34204
+ }
34205
+ function skillFrontMatter(markdown) {
34206
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);
34207
+ return match ? yamlScalars(match[1]) : {};
34208
+ }
34209
+ var clip3 = (value) => {
34210
+ const flat = value?.replace(/\s+/g, " ").trim();
34211
+ return flat ? flat.length > MAX_TEXT ? `${flat.slice(0, MAX_TEXT)}\u2026` : flat : void 0;
34212
+ };
34213
+ async function readSmall(path) {
34214
+ try {
34215
+ const info = await stat8(path);
34216
+ if (!info.isFile() || info.size > MAX_SKILL_FILE_BYTES) return void 0;
34217
+ return await readFile10(path, "utf8");
34218
+ } catch {
34219
+ return void 0;
34220
+ }
34221
+ }
34222
+ async function readSkill(directory, folder, source) {
34223
+ const markdown = await readSmall(join23(directory, "SKILL.md"));
34224
+ if (markdown === void 0) return void 0;
34225
+ const front = skillFrontMatter(markdown);
34226
+ const openai = yamlScalars(await readSmall(join23(directory, "agents", "openai.yaml")) ?? "");
34227
+ const name = (front.name || folder).trim();
34228
+ if (!name) return void 0;
34229
+ const displayName = clip3(openai["interface.display_name"] ?? front["metadata.display-name"] ?? front["metadata.display_name"] ?? front["display-name"] ?? front.display_name);
34230
+ const description = clip3(front.description);
34231
+ const shortDescription = clip3(openai["interface.short_description"] ?? front["metadata.short-description"] ?? front["metadata.short_description"]);
34232
+ return {
34233
+ name,
34234
+ ...displayName ? { displayName } : {},
34235
+ ...description ? { description } : {},
34236
+ ...shortDescription ? { shortDescription } : {},
34237
+ path: join23(directory, "SKILL.md"),
34238
+ source,
34239
+ enabled: true,
34240
+ userInvocable: true
34241
+ };
34242
+ }
34243
+ async function scan(root2, found) {
34244
+ const walk = async (directory, folder, depth, source) => {
34245
+ if (found.size >= MAX_SKILLS_PER_CLI) return;
34246
+ let entries;
34247
+ try {
34248
+ entries = await readdir5(directory, { withFileTypes: true });
34249
+ } catch {
34250
+ return;
34251
+ }
34252
+ if (entries.some((entry) => entry.name === "SKILL.md")) {
34253
+ const skill = await readSkill(directory, folder, source);
34254
+ if (skill && !found.has(skill.name)) found.set(skill.name, skill);
34255
+ return;
34256
+ }
34257
+ if (depth <= 0) return;
34258
+ for (const entry of entries) {
34259
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
34260
+ const isDirectory = entry.isDirectory() || entry.isSymbolicLink() && await stat8(join23(directory, entry.name)).then((info) => info.isDirectory(), () => false);
34261
+ if (!isDirectory) continue;
34262
+ await walk(join23(directory, entry.name), entry.name, depth - 1, entry.name === ".system" ? "system" : source);
34263
+ }
34264
+ };
34265
+ await walk(root2.directory, "", root2.depth, root2.source);
34266
+ }
34267
+ async function readCliSkills(cli, home = homedir14()) {
34268
+ const found = /* @__PURE__ */ new Map();
34269
+ for (const root2 of skillRoots(cli, home)) await scan(root2, found);
34270
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
34271
+ }
34272
+
34106
34273
  // src/t3/provider-catalog.ts
34107
34274
  var HUB_CLIS = [
34108
34275
  { cli: "codex", instanceId: "codex", driver: "codex", displayName: "Codex", effortOptionId: "reasoning_effort" },
@@ -34141,7 +34308,7 @@ function models2(cli, item) {
34141
34308
  function usageWindows(windows) {
34142
34309
  return windows.filter((window) => typeof window.used_percent === "number").map((window) => {
34143
34310
  const minutes = window.window_seconds ? Math.round(window.window_seconds / 60) : void 0;
34144
- const kind = minutes === void 0 ? "other" : minutes <= 6 * 60 ? "session" : minutes <= 8 * 24 * 60 ? "weekly" : minutes <= 32 * 24 * 60 ? "monthly" : "other";
34311
+ const kind = minutes === void 0 ? "other" : minutes >= 25 * 24 * 60 ? "monthly" : minutes >= 6 * 24 * 60 ? "weekly" : minutes <= 24 * 60 ? "session" : "other";
34145
34312
  return {
34146
34313
  id: window.key,
34147
34314
  kind,
@@ -34185,6 +34352,10 @@ var ProviderCatalog = class {
34185
34352
  const detected = HUB_CLIS.filter((cli) => detection.providers.some((provider) => provider.id === cli.cli && provider.installed)).map((cli) => cli.cli);
34186
34353
  const report = await this.collector.collect(detected, { force: Boolean(options.force) });
34187
34354
  if (options.quota) await this.readQuotas(detected, options.providerId);
34355
+ const skills = new Map(await Promise.all(HUB_CLIS.map(async (cli) => [
34356
+ cli.cli,
34357
+ detected.includes(cli.cli) ? await readCliSkills(cli.cli).catch(() => []) : []
34358
+ ])));
34188
34359
  const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
34189
34360
  this.last = HUB_CLIS.map((cli) => {
34190
34361
  const found = detection.providers.find((provider) => provider.id === cli.cli);
@@ -34207,7 +34378,7 @@ var ProviderCatalog = class {
34207
34378
  checkedAt,
34208
34379
  models: list,
34209
34380
  ...usage && runnable ? { usageLimits: usage } : {},
34210
- skills: [],
34381
+ skills: skills.get(cli.cli) ?? [],
34211
34382
  slashCommands: []
34212
34383
  };
34213
34384
  });
@@ -34218,16 +34389,18 @@ var ProviderCatalog = class {
34218
34389
  await Promise.all(detected.filter((cli) => !only || cli === only).map(async (cli) => {
34219
34390
  const read = catalogEntry(cli)?.quota;
34220
34391
  if (!read) return;
34392
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
34221
34393
  try {
34222
34394
  const windows = await Promise.race([
34223
34395
  read(),
34224
34396
  new Promise((_resolve, reject) => {
34225
- setTimeout(() => reject(new Error("timeout")), QUOTA_TIMEOUT_MS).unref?.();
34397
+ setTimeout(() => reject(new Error("\u8BFB\u53D6\u989D\u5EA6\u8D85\u65F6")), QUOTA_TIMEOUT_MS).unref?.();
34226
34398
  })
34227
34399
  ]);
34228
34400
  const shaped = usageWindows(windows);
34229
- if (shaped.length) this.quotas.set(cli, { checkedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: shaped });
34230
- } catch {
34401
+ this.quotas.set(cli, shaped.length ? { checkedAt, windows: shaped } : { checkedAt, windows: [], unavailable: { reason: "unsupported", message: "\u8BE5\u8D26\u53F7\u6CA1\u6709\u6309\u767E\u5206\u6BD4\u8BA1\u7684\u989D\u5EA6\u7A97\u53E3" } });
34402
+ } catch (error62) {
34403
+ this.quotas.set(cli, { checkedAt, windows: [], unavailable: { reason: "probeFailed", message: (error62 instanceof Error ? error62.message : String(error62)).slice(0, 300) } });
34231
34404
  }
34232
34405
  }));
34233
34406
  }
@@ -34237,7 +34410,7 @@ var ProviderCatalog = class {
34237
34410
  import { createHash as createHash5 } from "node:crypto";
34238
34411
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync9, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync4 } from "node:fs";
34239
34412
  import { rename as rename9, writeFile as writeFile10 } from "node:fs/promises";
34240
- import { join as join23 } from "node:path";
34413
+ import { join as join24 } from "node:path";
34241
34414
  var ITEM_RUNS_KEPT = 40;
34242
34415
  var SEQUENCE_BLOCK = 500;
34243
34416
  var SAVE_DEBOUNCE_MS = 800;
@@ -34250,9 +34423,9 @@ function writeAtomicSync(path, text5) {
34250
34423
  var ThreadStore = class {
34251
34424
  constructor(dataDir, onError = () => void 0) {
34252
34425
  this.onError = onError;
34253
- this.root = join23(dataDir, "hub");
34254
- this.threadsDir = join23(this.root, "threads");
34255
- this.statePath = join23(this.root, "state.json");
34426
+ this.root = join24(dataDir, "hub");
34427
+ this.threadsDir = join24(this.root, "threads");
34428
+ this.statePath = join24(this.root, "state.json");
34256
34429
  mkdirSync4(this.threadsDir, { recursive: true, mode: 448 });
34257
34430
  try {
34258
34431
  const state = JSON.parse(readFileSync9(this.statePath, "utf8"));
@@ -34264,7 +34437,7 @@ var ThreadStore = class {
34264
34437
  for (const name of readdirSync5(this.threadsDir)) {
34265
34438
  if (!name.endsWith(".json")) continue;
34266
34439
  try {
34267
- const thread = JSON.parse(readFileSync9(join23(this.threadsDir, name), "utf8"));
34440
+ const thread = JSON.parse(readFileSync9(join24(this.threadsDir, name), "utf8"));
34268
34441
  if (thread?.v === 1 && typeof thread.id === "string" && Array.isArray(thread.runs) && Array.isArray(thread.items)) this.threads.set(thread.id, thread);
34269
34442
  } catch {
34270
34443
  }
@@ -34336,7 +34509,7 @@ var ThreadStore = class {
34336
34509
  clearTimeout(timer);
34337
34510
  this.timers.delete(threadId);
34338
34511
  }
34339
- if (safeId(threadId)) rmSync(join23(this.threadsDir, `${threadId}.json`), { force: true });
34512
+ if (safeId(threadId)) rmSync(join24(this.threadsDir, `${threadId}.json`), { force: true });
34340
34513
  }
34341
34514
  /** Marks the thread changed; it is written shortly after (and on `flush`). */
34342
34515
  touch(thread) {
@@ -34347,7 +34520,7 @@ var ThreadStore = class {
34347
34520
  const current = this.threads.get(thread.id);
34348
34521
  if (!current) return;
34349
34522
  this.trim(current);
34350
- const path = join23(this.threadsDir, `${current.id}.json`);
34523
+ const path = join24(this.threadsDir, `${current.id}.json`);
34351
34524
  const temporary = `${path}.${process.pid}.tmp`;
34352
34525
  void writeFile10(temporary, JSON.stringify(current), { encoding: "utf8", mode: 384 }).then(() => rename9(temporary, path)).catch((error62) => this.onError(error62 instanceof Error ? error62.message : String(error62)));
34353
34526
  }, SAVE_DEBOUNCE_MS);
@@ -34362,7 +34535,7 @@ var ThreadStore = class {
34362
34535
  if (!thread) continue;
34363
34536
  this.trim(thread);
34364
34537
  try {
34365
- writeAtomicSync(join23(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
34538
+ writeAtomicSync(join24(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
34366
34539
  } catch (error62) {
34367
34540
  this.onError(error62 instanceof Error ? error62.message : String(error62));
34368
34541
  }
@@ -34379,10 +34552,10 @@ var ThreadStore = class {
34379
34552
  };
34380
34553
 
34381
34554
  // src/t3/turn-items.ts
34382
- var MAX_TEXT = 2e5;
34555
+ var MAX_TEXT2 = 2e5;
34383
34556
  var MAX_OUTPUT = 16e3;
34384
34557
  var MAX_DIFF = 24e3;
34385
- var clip3 = (text5, max) => text5.length > max ? `${text5.slice(0, max)}\u2026` : text5;
34558
+ var clip4 = (text5, max) => text5.length > max ? `${text5.slice(0, max)}\u2026` : text5;
34386
34559
  var record10 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
34387
34560
  var text3 = (value) => typeof value === "string" ? value : "";
34388
34561
  var STATUS = { pending: "pending", in_progress: "running", completed: "completed", failed: "failed" };
@@ -34415,7 +34588,7 @@ var TurnItemFolder = class {
34415
34588
  }
34416
34589
  this.open.delete(kind === "assistant_message" ? "reasoning" : "assistant_message");
34417
34590
  const item = this.upsert(key2, kind, { streaming: true });
34418
- item.text = clip3(text3(item.text) + event.text, MAX_TEXT);
34591
+ item.text = clip4(text3(item.text) + event.text, MAX_TEXT2);
34419
34592
  item.status = "running";
34420
34593
  return this.touch(item);
34421
34594
  }
@@ -34426,7 +34599,7 @@ var TurnItemFolder = class {
34426
34599
  case "text":
34427
34600
  case "thought": {
34428
34601
  const item = this.upsert(key, source.type === "text" ? "assistant_message" : "reasoning", { streaming: true });
34429
- item.text = clip3(text3(source.text), MAX_TEXT);
34602
+ item.text = clip4(text3(source.text), MAX_TEXT2);
34430
34603
  item.status = "running";
34431
34604
  return this.touch(item);
34432
34605
  }
@@ -34440,7 +34613,7 @@ var TurnItemFolder = class {
34440
34613
  }
34441
34614
  case "proposed_plan": {
34442
34615
  const item = this.upsert(key, "proposed_plan", { planId: text3(source.turnId) || key });
34443
- item.markdown = clip3(text3(source.markdown), MAX_TEXT);
34616
+ item.markdown = clip4(text3(source.markdown), MAX_TEXT2);
34444
34617
  item.status = "completed";
34445
34618
  return this.touch(item);
34446
34619
  }
@@ -34507,7 +34680,7 @@ var TurnItemFolder = class {
34507
34680
  const exitCode = record10(output2?.exitStatus).exitCode;
34508
34681
  item = this.upsert(key, "command_execution", {});
34509
34682
  item.input = text3(command?.command) || title;
34510
- if (output2) item.output = clip3(text3(output2.output), MAX_OUTPUT);
34683
+ if (output2) item.output = clip4(text3(output2.output), MAX_OUTPUT);
34511
34684
  if (typeof exitCode === "number") item.exitCode = exitCode;
34512
34685
  } else if (kind === "edit") {
34513
34686
  const paths = [...new Set([...diffs.map((part) => text3(part.path)), ...locations].filter(Boolean))];
@@ -34516,8 +34689,8 @@ var TurnItemFolder = class {
34516
34689
  if (paths.length) item.changes = paths.slice(0, 200).map((path) => ({ operation: "edit", path }));
34517
34690
  const first = diffs[0];
34518
34691
  if (first) {
34519
- if (typeof first.oldText === "string") item.oldStr = clip3(first.oldText, MAX_DIFF);
34520
- item.newStr = clip3(text3(first.newText), MAX_DIFF);
34692
+ if (typeof first.oldText === "string") item.oldStr = clip4(first.oldText, MAX_DIFF);
34693
+ item.newStr = clip4(text3(first.newText), MAX_DIFF);
34521
34694
  }
34522
34695
  } else if (kind === "search") {
34523
34696
  item = this.upsert(key, "file_search", {});
@@ -34531,7 +34704,7 @@ var TurnItemFolder = class {
34531
34704
  if (source.rawInput !== void 0) item.input = source.rawInput;
34532
34705
  if (source.rawOutput !== void 0) item.output = source.rawOutput;
34533
34706
  }
34534
- if (title) item.title = clip3(title, 400);
34707
+ if (title) item.title = clip4(title, 400);
34535
34708
  item.status = status;
34536
34709
  if (status === "completed" || status === "failed") item.completedAt = (/* @__PURE__ */ new Date()).toISOString();
34537
34710
  return this.touch(item);
@@ -34543,8 +34716,10 @@ var ACTIVE = /* @__PURE__ */ new Set(["starting", "running"]);
34543
34716
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "interrupted", "cancelled"]);
34544
34717
  var ITEM_FLUSH_MS = 200;
34545
34718
  var SNAPSHOT_RUNS = 30;
34719
+ var DRAIN_TIMEOUT_MS = 15e3;
34546
34720
  var MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
34547
34721
  var DEFAULT_MODEL_SENTINELS = /* @__PURE__ */ new Set(["antigravity-default", "default"]);
34722
+ var providerThreadId = (threadId, sessionId) => `${threadId}:${sessionId}`;
34548
34723
  var record11 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
34549
34724
  var text4 = (value) => typeof value === "string" ? value : "";
34550
34725
  function selectionEffort(selection) {
@@ -34562,7 +34737,7 @@ var T3Backend = class {
34562
34737
  this.config = config2;
34563
34738
  this.logger = logger;
34564
34739
  this.store = new ThreadStore(config2.dataDir, (message) => logger.warn("hub-thread-save-failed", { error: message }));
34565
- this.orphans = new OrphanRegistry(join24(config2.dataDir, "active-runs.json"));
34740
+ this.orphans = new OrphanRegistry(join25(config2.dataDir, "active-runs.json"));
34566
34741
  const reporter = {
34567
34742
  started: async (runId, report) => this.onRunStarted(runId, report),
34568
34743
  content: (runId, events) => this.onRunContent(runId, events),
@@ -34579,6 +34754,12 @@ var T3Backend = class {
34579
34754
  live = /* @__PURE__ */ new Map();
34580
34755
  /** Run id → thread id for every run this process started. */
34581
34756
  runThreads = /* @__PURE__ */ new Map();
34757
+ /**
34758
+ * Runs already reported as interrupted whose CLI process tree is still being
34759
+ * ended in the background (run id → release timer). The thread starts no
34760
+ * other turn until the supervisor confirms the process is gone.
34761
+ */
34762
+ draining = /* @__PURE__ */ new Map();
34582
34763
  publisher;
34583
34764
  /** Where events go. Until the link attaches (and while it is down) the link buffers them itself. */
34584
34765
  attach(publisher) {
@@ -34605,6 +34786,8 @@ var T3Backend = class {
34605
34786
  async stop() {
34606
34787
  await this.supervisor.disposeAll();
34607
34788
  for (const live of this.live.values()) if (live.timer) clearTimeout(live.timer);
34789
+ for (const timer of this.draining.values()) clearTimeout(timer);
34790
+ this.draining.clear();
34608
34791
  this.store.flush();
34609
34792
  }
34610
34793
  activeRuns() {
@@ -34627,12 +34810,12 @@ var T3Backend = class {
34627
34810
  // ---- DeviceBackend: projects and snapshots ----
34628
34811
  async ensureProject(workspaceRoot) {
34629
34812
  let target = (workspaceRoot ?? "").trim();
34630
- if (!target || target === "~") target = homedir14();
34631
- else if (target.startsWith("~/") || target.startsWith("~\\")) target = join24(homedir14(), target.slice(2));
34813
+ if (!target || target === "~") target = homedir15();
34814
+ else if (target.startsWith("~/") || target.startsWith("~\\")) target = join25(homedir15(), target.slice(2));
34632
34815
  const root2 = resolve7(target);
34633
34816
  try {
34634
34817
  await mkdir9(root2, { recursive: true });
34635
- if (!(await stat8(root2)).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
34818
+ if (!(await stat9(root2)).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
34636
34819
  } catch (error62) {
34637
34820
  throw rpcError("ProjectMutationError", `\u65E0\u6CD5\u4F7F\u7528\u5DE5\u4F5C\u76EE\u5F55 ${root2}\uFF1A${error62 instanceof Error ? error62.message : String(error62)}`, `workspaceRoot=${root2}`);
34638
34821
  }
@@ -34651,6 +34834,8 @@ var T3Backend = class {
34651
34834
  thread: this.threadState(thread),
34652
34835
  runs: runs.map((entry) => entry.run),
34653
34836
  turnItems: thread.items.filter((entry) => typeof entry.item.runId !== "string" || kept.has(entry.item.runId)).map((entry) => entry.item),
34837
+ // The CLI sessions the runs ran in; the Hub offers a native fork only from a run with a strong one.
34838
+ providerThreads: this.providerThreads(thread),
34654
34839
  runtimeRequests: []
34655
34840
  }
34656
34841
  };
@@ -34698,7 +34883,7 @@ var T3Backend = class {
34698
34883
  case "provider.switch":
34699
34884
  return this.selectModel(command);
34700
34885
  case "thread.fork":
34701
- throw rpcError(ERROR_TAGS.forkUnsupported, "ocra \u8BBE\u5907\u5305\u6682\u4E0D\u652F\u6301\u4F1A\u8BDD\u5206\u53C9\uFF0C\u8BF7\u65B0\u5EFA\u4F1A\u8BDD\u7EE7\u7EED", "command=thread.fork");
34886
+ return this.forkThread(command);
34702
34887
  case "runtime-request.respond":
34703
34888
  throw rpcError("RuntimeRequestNotFound", "\u8FD9\u53F0\u8BBE\u5907\u4EE5\u5B8C\u5168\u8BBF\u95EE\u6A21\u5F0F\u8FD0\u884C\uFF0C\u6CA1\u6709\u7B49\u5F85\u786E\u8BA4\u7684\u8BF7\u6C42", `requestId=${text4(command.requestId)}`);
34704
34889
  default:
@@ -34815,7 +35000,7 @@ var T3Backend = class {
34815
35000
  const prompt = body + await this.saveAttachments(thread, messageId, attachments);
34816
35001
  const now = (/* @__PURE__ */ new Date()).toISOString();
34817
35002
  const runId = randomUUID5();
34818
- const busy = thread.runs.some((entry2) => ACTIVE.has(entry2.run.status) || entry2.run.status === "queued");
35003
+ const busy = thread.runs.some((entry2) => ACTIVE.has(entry2.run.status) || entry2.run.status === "queued" || this.draining.has(entry2.run.id));
34819
35004
  const run = {
34820
35005
  id: runId,
34821
35006
  threadId: thread.id,
@@ -34855,7 +35040,7 @@ var T3Backend = class {
34855
35040
  async saveAttachments(thread, messageId, attachments) {
34856
35041
  if (!attachments.length) return "";
34857
35042
  const lines = [];
34858
- const directory = join24(this.config.dataDir, "hub", "attachments", thread.id.replace(/[^A-Za-z0-9_.-]/g, "_"), messageId.replace(/[^A-Za-z0-9_.-]/g, "_"));
35043
+ const directory = join25(this.config.dataDir, "hub", "attachments", thread.id.replace(/[^A-Za-z0-9_.-]/g, "_"), messageId.replace(/[^A-Za-z0-9_.-]/g, "_"));
34859
35044
  for (const [index, attachment] of attachments.entries()) {
34860
35045
  const name = (text4(attachment.name) || `attachment-${index + 1}`).replace(/[^\p{L}\p{N}_.-]/gu, "_").slice(0, 120);
34861
35046
  const dataUrl = text4(attachment.dataUrl);
@@ -34868,7 +35053,7 @@ var T3Backend = class {
34868
35053
  }
34869
35054
  try {
34870
35055
  await mkdir9(directory, { recursive: true, mode: 448 });
34871
- const path = join24(directory, `${index + 1}-${name}`);
35056
+ const path = join25(directory, `${index + 1}-${name}`);
34872
35057
  await writeFile11(path, bytes, { mode: 384 });
34873
35058
  lines.push(`- ${path}`);
34874
35059
  } catch (error62) {
@@ -34897,6 +35082,12 @@ ${lines.join("\n")}` : "";
34897
35082
  run.status = "starting";
34898
35083
  this.emitRun(thread, cli, entry, "run.updated");
34899
35084
  }
35085
+ const fork = thread.nativeSessionId ? void 0 : thread.fork;
35086
+ const sessionId = thread.nativeSessionId || (fork && cli.cli === "claude" ? randomUUID5() : "");
35087
+ if (fork && cli.cli === "claude" && !claudeTranscriptExists(fork.sourceSessionId)) {
35088
+ this.onRunFinished(run.id, { status: "failed", error: "\u539F\u4F1A\u8BDD\u5728\u8FD9\u53F0\u8BBE\u5907\u4E0A\u5DF2\u7ECF\u4E0D\u5B58\u5728\uFF08\u53EF\u80FD\u88AB\u6E05\u7406\u6216\u6362\u4E86\u8BBE\u5907\uFF09\uFF0C\u65E0\u6CD5\u5206\u53C9", failure_kind: "sessionMissing", duration_ms: 0 });
35089
+ return;
35090
+ }
34900
35091
  void (async () => {
34901
35092
  const payload = RunStartPayloadSchema.parse({
34902
35093
  // Full access, always: no turn of this device ever waits for a confirmation.
@@ -34906,7 +35097,8 @@ ${lines.join("\n")}` : "";
34906
35097
  task_chain_id: thread.id,
34907
35098
  message_id: run.userMessageId,
34908
35099
  prompt: entry.prompt ?? "",
34909
- session_id: thread.nativeSessionId,
35100
+ session_id: sessionId,
35101
+ ...fork ? { fork: { source_session_id: fork.sourceSessionId, keep_turns: fork.keepTurns } } : {},
34910
35102
  model: DEFAULT_MODEL_SENTINELS.has(model) ? "" : model,
34911
35103
  reasoning_effort: selectionEffort(thread.modelSelection),
34912
35104
  workdir: thread.workspaceRoot
@@ -34918,11 +35110,18 @@ ${lines.join("\n")}` : "";
34918
35110
  });
34919
35111
  }
34920
35112
  startNextQueued(thread) {
34921
- if (thread.queueHeld || thread.runs.some((entry) => ACTIVE.has(entry.run.status))) return;
35113
+ if (thread.queueHeld || thread.runs.some((entry) => ACTIVE.has(entry.run.status) || this.draining.has(entry.run.id))) return;
34922
35114
  const next = thread.runs.find((entry) => entry.run.status === "queued");
34923
35115
  if (next) this.launch(thread, next);
34924
35116
  }
34925
- async interruptRun(command) {
35117
+ /**
35118
+ * `run.interrupt`. The run is reported as interrupted and the command is
35119
+ * answered at once; ending the CLI's process tree (a polite signal, a grace
35120
+ * period, then a forced kill; `taskkill` on Windows) goes on in the
35121
+ * background. The report used to wait for the process to exit and its
35122
+ * output pipes to close, so a CLI slow to die kept the page on "running".
35123
+ */
35124
+ interruptRun(command) {
34926
35125
  const thread = this.requireThread(command.threadId);
34927
35126
  const wanted = text4(command.runId);
34928
35127
  const entry = wanted ? thread.runs.find((candidate) => candidate.run.id === wanted) : [...thread.runs].reverse().find((candidate) => ACTIVE.has(candidate.run.status));
@@ -34934,10 +35133,31 @@ ${lines.join("\n")}` : "";
34934
35133
  this.closeRun(thread, entry, "interrupted", "");
34935
35134
  return { interrupted: true };
34936
35135
  }
34937
- const stopping = await this.supervisor.cancel(entry.run.id);
34938
- if (!stopping && !TERMINAL.has(entry.run.status)) this.closeRun(thread, entry, "interrupted", "");
35136
+ const runId = entry.run.id;
35137
+ const live = this.live.get(runId);
35138
+ if (live) {
35139
+ for (const item of live.folder.finish("interrupted", (/* @__PURE__ */ new Date()).toISOString())) live.dirty.add(item);
35140
+ this.flushItems(runId);
35141
+ }
35142
+ this.draining.set(runId, setTimeout(() => {
35143
+ this.logger.warn("hub-run-stop-unconfirmed", { runId, seconds: DRAIN_TIMEOUT_MS / 1e3 });
35144
+ this.releaseDrain(runId);
35145
+ }, DRAIN_TIMEOUT_MS));
35146
+ this.closeRun(thread, entry, "interrupted", "");
35147
+ void this.supervisor.cancel(runId).then((stopping) => {
35148
+ if (!stopping) this.releaseDrain(runId);
35149
+ }, () => this.releaseDrain(runId));
34939
35150
  return { interrupted: true };
34940
35151
  }
35152
+ /** The stopped run's process is gone (or was never there): the thread may run its next turn. */
35153
+ releaseDrain(runId) {
35154
+ const timer = this.draining.get(runId);
35155
+ if (timer === void 0) return;
35156
+ clearTimeout(timer);
35157
+ this.draining.delete(runId);
35158
+ const thread = this.store.get(this.runThreads.get(runId) ?? "");
35159
+ if (thread) this.startNextQueued(thread);
35160
+ }
34941
35161
  // ---- Run reports from the supervisor ----
34942
35162
  runOf(runId) {
34943
35163
  const threadId = this.runThreads.get(runId);
@@ -34949,15 +35169,85 @@ ${lines.join("\n")}` : "";
34949
35169
  const found = this.runOf(runId);
34950
35170
  if (!found) return;
34951
35171
  const { thread, entry } = found;
34952
- if (report.session_id && report.session_id !== thread.nativeSessionId) {
34953
- thread.nativeSessionId = report.session_id;
34954
- this.store.touch(thread);
35172
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35173
+ if (report.pid) {
35174
+ entry.launched = true;
35175
+ if (this.draining.has(runId)) void this.supervisor.cancel(runId).catch(() => false);
35176
+ if (entry.run.status === "starting") {
35177
+ entry.run.status = "running";
35178
+ entry.run.startedAt = (/* @__PURE__ */ new Date()).toISOString();
35179
+ this.emitRun(thread, this.cliOf(thread), entry, "run.updated");
35180
+ }
34955
35181
  }
34956
- if (report.pid && entry.run.status === "starting") {
34957
- entry.run.status = "running";
34958
- entry.run.startedAt = (/* @__PURE__ */ new Date()).toISOString();
34959
- this.emitRun(thread, this.cliOf(thread), entry, "run.updated");
35182
+ }
35183
+ /** The CLI named the session this turn runs in: the thread continues it, and the run points at it. */
35184
+ noteNativeSession(thread, entry, sessionId) {
35185
+ entry.nativeSessionId = sessionId;
35186
+ entry.run.providerThreadId = providerThreadId(thread.id, sessionId);
35187
+ if (thread.nativeSessionId !== sessionId) {
35188
+ thread.nativeSessionId = sessionId;
35189
+ delete thread.fork;
34960
35190
  }
35191
+ this.store.touch(thread);
35192
+ }
35193
+ providerThreads(thread) {
35194
+ const cli = this.cliOf(thread);
35195
+ const sessions = new Set(thread.runs.map((entry) => entry.nativeSessionId).filter((id) => Boolean(id)));
35196
+ return [...sessions].map((sessionId) => ({
35197
+ id: providerThreadId(thread.id, sessionId),
35198
+ threadId: thread.id,
35199
+ driver: cli.driver,
35200
+ providerInstanceId: cli.instanceId,
35201
+ nativeThreadRef: { strength: "strong", id: sessionId }
35202
+ }));
35203
+ }
35204
+ /**
35205
+ * `thread.fork`: a new thread on the same CLI and work directory whose first
35206
+ * turn continues a native copy of the source CLI session up to the chosen
35207
+ * run. The source thread is not touched. Only CLIs that can copy a session
35208
+ * are forked (Claude Code, Codex); the others are refused, never imitated.
35209
+ */
35210
+ forkThread(command) {
35211
+ const source = this.requireThread(command.sourceThreadId);
35212
+ const targetId = text4(command.targetThreadId);
35213
+ if (!targetId) throw rpcError(ERROR_TAGS.invalidCommand, "thread.fork \u7F3A\u5C11 targetThreadId");
35214
+ if (this.store.get(targetId)) return { threadId: targetId, created: false };
35215
+ const cli = this.cliOf(source);
35216
+ if (cli.cli !== "claude" && cli.cli !== "codex") {
35217
+ throw rpcError(ERROR_TAGS.forkUnsupported, `${cli.displayName} \u6682\u4E0D\u652F\u6301\u5206\u53C9\uFF0C\u8BF7\u65B0\u5EFA\u4F1A\u8BDD\u7EE7\u7EED`, `thread.fork driver=${cli.driver}`);
35218
+ }
35219
+ const point = record11(command.sourcePoint);
35220
+ const runId = text4(point.runId);
35221
+ const at = runId ? source.runs.find((entry) => entry.run.id === runId) : [...source.runs].reverse().find((entry) => entry.run.status === "completed");
35222
+ if (!at) throw rpcError(ERROR_TAGS.forkUnsupported, "\u8BBE\u5907\u4E0A\u627E\u4E0D\u5230\u8981\u5206\u53C9\u7684\u8FD9\u4E00\u8F6E", `thread.fork run ${runId || "(latest)"} not found`);
35223
+ if (!TERMINAL.has(at.run.status)) throw rpcError(ERROR_TAGS.forkUnsupported, "\u8FD9\u4E00\u8F6E\u8FD8\u5728\u8FD0\u884C\uFF08in-progress\uFF09\uFF0C\u4E0D\u80FD\u5206\u53C9\uFF0C\u8BF7\u7B49\u5B83\u5B8C\u6210\u540E\u518D\u8BD5", `run ${at.run.id} status=${at.run.status}`);
35224
+ if (!at.nativeSessionId) throw rpcError(ERROR_TAGS.forkUnsupported, `\u8FD9\u4E00\u8F6E\u6CA1\u6709 ${cli.displayName} \u7684\u539F\u751F\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u5206\u53C9\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6\u8F6E\u6B21`, `run ${at.run.id} has no native session`);
35225
+ const keepTurns = source.runs.filter((entry) => entry.launched && entry.nativeSessionId === at.nativeSessionId && entry.run.ordinal <= at.run.ordinal).length;
35226
+ const now = (/* @__PURE__ */ new Date()).toISOString();
35227
+ const thread = {
35228
+ v: 1,
35229
+ id: targetId,
35230
+ projectId: source.projectId,
35231
+ workspaceRoot: source.workspaceRoot,
35232
+ title: text4(command.title) || `${source.title}\uFF08\u5206\u53C9\uFF09`,
35233
+ cli: source.cli,
35234
+ modelSelection: record11(at.run.modelSelection).model ? record11(at.run.modelSelection) : source.modelSelection,
35235
+ runtimeMode: source.runtimeMode,
35236
+ interactionMode: source.interactionMode,
35237
+ createdAt: now,
35238
+ updatedAt: now,
35239
+ nativeSessionId: "",
35240
+ archived: false,
35241
+ queueHeld: false,
35242
+ seq: 0,
35243
+ nextItemOrdinal: 1,
35244
+ runs: [],
35245
+ items: [],
35246
+ fork: { sourceThreadId: source.id, sourceRunId: at.run.id, sourceSessionId: at.nativeSessionId, keepTurns }
35247
+ };
35248
+ this.store.put(thread);
35249
+ this.emitThread(thread, "thread.created");
35250
+ return { threadId: targetId, created: true, forkedFrom: { threadId: source.id, runId: at.run.id, keepTurns } };
34961
35251
  }
34962
35252
  onRunContent(runId, events) {
34963
35253
  const live = this.live.get(runId);
@@ -34998,10 +35288,12 @@ ${lines.join("\n")}` : "";
34998
35288
  }
34999
35289
  const { thread, entry } = found;
35000
35290
  if (TERMINAL.has(entry.run.status)) {
35291
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35001
35292
  this.dropLive(runId);
35293
+ this.releaseDrain(runId);
35002
35294
  return;
35003
35295
  }
35004
- if (report.session_id && report.session_id !== thread.nativeSessionId) thread.nativeSessionId = report.session_id;
35296
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35005
35297
  const outcome = report.status === "succeeded" ? "completed" : report.status === "cancelled" ? "interrupted" : "failed";
35006
35298
  const live = this.live.get(runId);
35007
35299
  if (live) {
@@ -35066,7 +35358,9 @@ ${lines.join("\n")}` : "";
35066
35358
  workspaceRoot: thread.workspaceRoot,
35067
35359
  createdAt: thread.createdAt,
35068
35360
  updatedAt: thread.updatedAt,
35069
- archivedAt: thread.archived ? thread.updatedAt : null
35361
+ archived: thread.archived,
35362
+ archivedAt: thread.archived ? thread.updatedAt : null,
35363
+ ...thread.fork ? { forkedFrom: { threadId: thread.fork.sourceThreadId, runId: thread.fork.sourceRunId } } : {}
35070
35364
  };
35071
35365
  }
35072
35366
  emitThread(thread, type) {
@@ -35095,7 +35389,7 @@ var HubRuntime = class {
35095
35389
  },
35096
35390
  backend: this.backend,
35097
35391
  appVersion: hubAppVersion(version2),
35098
- eventStatePath: join25(config2.dataDir, "hub-events.json"),
35392
+ eventStatePath: join26(config2.dataDir, "hub-events.json"),
35099
35393
  logger: this.logger
35100
35394
  });
35101
35395
  this.backend.attach({ event: (envelope) => this.link.publishEvent(envelope) });
@@ -35536,7 +35830,7 @@ function preferSystemNode() {
35536
35830
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
35537
35831
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
35538
35832
  for (const name of names) {
35539
- const candidate = directory && join26(directory, name);
35833
+ const candidate = directory && join27(directory, name);
35540
35834
  if (candidate && existsSync8(candidate)) {
35541
35835
  process.env.TOC_OCRA_NODE_PATH = candidate;
35542
35836
  return;