toc-ocra 0.4.0 → 0.5.0

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";
@@ -25583,14 +25583,14 @@ function parseCodexModels(content) {
25583
25583
  return void 0;
25584
25584
  }
25585
25585
  }
25586
- async function readCodexModels(codexHome3, config2) {
25586
+ async function readCodexModels(codexHome4, config2) {
25587
25587
  const configuredCatalog = configValue(config2, "model_catalog_json");
25588
25588
  if (configuredCatalog) {
25589
- const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve3(codexHome3, configuredCatalog);
25589
+ const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve3(codexHome4, configuredCatalog);
25590
25590
  const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
25591
25591
  if (configuredModels?.length) return configuredModels;
25592
25592
  }
25593
- const cached3 = parseCodexModels(await readFile4(join11(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25593
+ const cached3 = parseCodexModels(await readFile4(join11(codexHome4, "models_cache.json"), "utf8").catch(() => ""));
25594
25594
  if (cached3?.length) return cached3;
25595
25595
  return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
25596
25596
  }
@@ -29749,7 +29749,7 @@ var CliDetectionService = class {
29749
29749
  var cliDetection = new CliDetectionService();
29750
29750
 
29751
29751
  // src/runtime/hub-runtime.ts
29752
- import { join as join25 } from "node:path";
29752
+ import { join as join26 } from "node:path";
29753
29753
 
29754
29754
  // node_modules/ws/wrapper.mjs
29755
29755
  var import_stream = __toESM(require_stream(), 1);
@@ -30684,7 +30684,7 @@ var HubLink = class {
30684
30684
  return;
30685
30685
  default:
30686
30686
  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}`) });
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\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
30688
  }
30689
30689
  }
30690
30690
  }
@@ -30695,9 +30695,9 @@ function errorMessage(error62) {
30695
30695
 
30696
30696
  // src/t3/t3-backend.ts
30697
30697
  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";
30698
+ import { mkdir as mkdir9, stat as stat9, writeFile as writeFile11 } from "node:fs/promises";
30699
+ import { homedir as homedir15 } from "node:os";
30700
+ import { basename as basename4, join as join25, resolve as resolve7 } from "node:path";
30701
30701
 
30702
30702
  // src/runs/orphan-registry.ts
30703
30703
  import { mkdir as mkdir5, readFile as readFile7, rename as rename6, writeFile as writeFile6 } from "node:fs/promises";
@@ -34103,6 +34103,144 @@ var ModelCatalogCollector = class {
34103
34103
  }
34104
34104
  };
34105
34105
 
34106
+ // src/t3/skills.ts
34107
+ import { readdir as readdir5, readFile as readFile10, stat as stat8 } from "node:fs/promises";
34108
+ import { homedir as homedir14 } from "node:os";
34109
+ import { join as join23 } from "node:path";
34110
+ var MAX_SKILLS_PER_CLI = 500;
34111
+ var MAX_SKILL_FILE_BYTES = 256 * 1024;
34112
+ var MAX_TEXT = 1e3;
34113
+ var claudeHome3 = () => process.env.CLAUDE_CONFIG_DIR?.trim().split(process.platform === "win32" ? ";" : ":")[0]?.trim() || join23(homedir14(), ".claude");
34114
+ var codexHome3 = () => process.env.CODEX_HOME?.trim() || join23(homedir14(), ".codex");
34115
+ function skillRoots(cli, home = homedir14()) {
34116
+ const agents = { directory: join23(home, ".agents", "skills"), source: "user", depth: 2 };
34117
+ switch (cli) {
34118
+ case "claude":
34119
+ return [
34120
+ { directory: join23(claudeHome3(), "skills"), source: "user", depth: 2 },
34121
+ // Installed plugins keep their skills under <plugin>/skills/<name>/SKILL.md, several levels down.
34122
+ { directory: join23(claudeHome3(), "plugins"), source: "plugin", depth: 7 }
34123
+ ];
34124
+ case "codex":
34125
+ return [
34126
+ // Bundled skills live in skills/.system/<name>.
34127
+ { directory: join23(codexHome3(), "skills"), source: "user", depth: 3 },
34128
+ { directory: join23(codexHome3(), "plugins"), source: "plugin", depth: 7 },
34129
+ agents
34130
+ ];
34131
+ case "antigravity":
34132
+ return [
34133
+ { directory: join23(home, ".gemini", "antigravity", "skills"), source: "user", depth: 2 },
34134
+ { directory: join23(home, ".gemini", "antigravity-cli", "skills"), source: "user", depth: 2 },
34135
+ agents
34136
+ ];
34137
+ }
34138
+ }
34139
+ var unquote = (value) => {
34140
+ const trimmed = value.trim();
34141
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
34142
+ const inner = trimmed.slice(1, -1);
34143
+ return trimmed.startsWith('"') ? inner.replace(/\\"/g, '"').replace(/\\n/g, "\n").replace(/\\\\/g, "\\") : inner.replace(/''/g, "'");
34144
+ }
34145
+ return trimmed;
34146
+ };
34147
+ function yamlScalars(source) {
34148
+ const out = {};
34149
+ const lines = source.split(/\r?\n/);
34150
+ const parents = [];
34151
+ for (let index = 0; index < lines.length; index++) {
34152
+ const line = lines[index];
34153
+ if (!line.trim() || line.trimStart().startsWith("#") || line.trimStart().startsWith("- ")) continue;
34154
+ const match = /^(\s*)([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line);
34155
+ if (!match) continue;
34156
+ const indent = match[1].length;
34157
+ while (parents.length && parents[parents.length - 1].indent >= indent) parents.pop();
34158
+ const path = [...parents.map((parent) => parent.key), match[2]].join(".");
34159
+ let value = match[3].replace(/\s+#.*$/, "");
34160
+ if (value === "") {
34161
+ parents.push({ indent, key: match[2] });
34162
+ continue;
34163
+ }
34164
+ if (/^[|>][+-]?$/.test(value)) {
34165
+ const folded = value.startsWith(">");
34166
+ const block = [];
34167
+ while (index + 1 < lines.length && (!lines[index + 1].trim() || lines[index + 1].length - lines[index + 1].trimStart().length > indent)) {
34168
+ block.push(lines[++index].trim());
34169
+ }
34170
+ value = block.join(folded ? " " : "\n").trim();
34171
+ } else value = unquote(value);
34172
+ out[path] = value;
34173
+ }
34174
+ return out;
34175
+ }
34176
+ function skillFrontMatter(markdown) {
34177
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);
34178
+ return match ? yamlScalars(match[1]) : {};
34179
+ }
34180
+ var clip3 = (value) => {
34181
+ const flat = value?.replace(/\s+/g, " ").trim();
34182
+ return flat ? flat.length > MAX_TEXT ? `${flat.slice(0, MAX_TEXT)}\u2026` : flat : void 0;
34183
+ };
34184
+ async function readSmall(path) {
34185
+ try {
34186
+ const info = await stat8(path);
34187
+ if (!info.isFile() || info.size > MAX_SKILL_FILE_BYTES) return void 0;
34188
+ return await readFile10(path, "utf8");
34189
+ } catch {
34190
+ return void 0;
34191
+ }
34192
+ }
34193
+ async function readSkill(directory, folder, source) {
34194
+ const markdown = await readSmall(join23(directory, "SKILL.md"));
34195
+ if (markdown === void 0) return void 0;
34196
+ const front = skillFrontMatter(markdown);
34197
+ const openai = yamlScalars(await readSmall(join23(directory, "agents", "openai.yaml")) ?? "");
34198
+ const name = (front.name || folder).trim();
34199
+ if (!name) return void 0;
34200
+ const displayName = clip3(openai["interface.display_name"] ?? front["metadata.display-name"] ?? front["metadata.display_name"] ?? front["display-name"] ?? front.display_name);
34201
+ const description = clip3(front.description);
34202
+ const shortDescription = clip3(openai["interface.short_description"] ?? front["metadata.short-description"] ?? front["metadata.short_description"]);
34203
+ return {
34204
+ name,
34205
+ ...displayName ? { displayName } : {},
34206
+ ...description ? { description } : {},
34207
+ ...shortDescription ? { shortDescription } : {},
34208
+ path: join23(directory, "SKILL.md"),
34209
+ source,
34210
+ enabled: true,
34211
+ userInvocable: true
34212
+ };
34213
+ }
34214
+ async function scan(root2, found) {
34215
+ const walk = async (directory, folder, depth, source) => {
34216
+ if (found.size >= MAX_SKILLS_PER_CLI) return;
34217
+ let entries;
34218
+ try {
34219
+ entries = await readdir5(directory, { withFileTypes: true });
34220
+ } catch {
34221
+ return;
34222
+ }
34223
+ if (entries.some((entry) => entry.name === "SKILL.md")) {
34224
+ const skill = await readSkill(directory, folder, source);
34225
+ if (skill && !found.has(skill.name)) found.set(skill.name, skill);
34226
+ return;
34227
+ }
34228
+ if (depth <= 0) return;
34229
+ for (const entry of entries) {
34230
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
34231
+ const isDirectory = entry.isDirectory() || entry.isSymbolicLink() && await stat8(join23(directory, entry.name)).then((info) => info.isDirectory(), () => false);
34232
+ if (!isDirectory) continue;
34233
+ await walk(join23(directory, entry.name), entry.name, depth - 1, entry.name === ".system" ? "system" : source);
34234
+ }
34235
+ };
34236
+ await walk(root2.directory, "", root2.depth, root2.source);
34237
+ }
34238
+ async function readCliSkills(cli, home = homedir14()) {
34239
+ const found = /* @__PURE__ */ new Map();
34240
+ for (const root2 of skillRoots(cli, home)) await scan(root2, found);
34241
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
34242
+ }
34243
+
34106
34244
  // src/t3/provider-catalog.ts
34107
34245
  var HUB_CLIS = [
34108
34246
  { cli: "codex", instanceId: "codex", driver: "codex", displayName: "Codex", effortOptionId: "reasoning_effort" },
@@ -34141,7 +34279,7 @@ function models2(cli, item) {
34141
34279
  function usageWindows(windows) {
34142
34280
  return windows.filter((window) => typeof window.used_percent === "number").map((window) => {
34143
34281
  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";
34282
+ const kind = minutes === void 0 ? "other" : minutes >= 25 * 24 * 60 ? "monthly" : minutes >= 6 * 24 * 60 ? "weekly" : minutes <= 24 * 60 ? "session" : "other";
34145
34283
  return {
34146
34284
  id: window.key,
34147
34285
  kind,
@@ -34185,6 +34323,10 @@ var ProviderCatalog = class {
34185
34323
  const detected = HUB_CLIS.filter((cli) => detection.providers.some((provider) => provider.id === cli.cli && provider.installed)).map((cli) => cli.cli);
34186
34324
  const report = await this.collector.collect(detected, { force: Boolean(options.force) });
34187
34325
  if (options.quota) await this.readQuotas(detected, options.providerId);
34326
+ const skills = new Map(await Promise.all(HUB_CLIS.map(async (cli) => [
34327
+ cli.cli,
34328
+ detected.includes(cli.cli) ? await readCliSkills(cli.cli).catch(() => []) : []
34329
+ ])));
34188
34330
  const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
34189
34331
  this.last = HUB_CLIS.map((cli) => {
34190
34332
  const found = detection.providers.find((provider) => provider.id === cli.cli);
@@ -34207,7 +34349,7 @@ var ProviderCatalog = class {
34207
34349
  checkedAt,
34208
34350
  models: list,
34209
34351
  ...usage && runnable ? { usageLimits: usage } : {},
34210
- skills: [],
34352
+ skills: skills.get(cli.cli) ?? [],
34211
34353
  slashCommands: []
34212
34354
  };
34213
34355
  });
@@ -34218,16 +34360,18 @@ var ProviderCatalog = class {
34218
34360
  await Promise.all(detected.filter((cli) => !only || cli === only).map(async (cli) => {
34219
34361
  const read = catalogEntry(cli)?.quota;
34220
34362
  if (!read) return;
34363
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
34221
34364
  try {
34222
34365
  const windows = await Promise.race([
34223
34366
  read(),
34224
34367
  new Promise((_resolve, reject) => {
34225
- setTimeout(() => reject(new Error("timeout")), QUOTA_TIMEOUT_MS).unref?.();
34368
+ setTimeout(() => reject(new Error("\u8BFB\u53D6\u989D\u5EA6\u8D85\u65F6")), QUOTA_TIMEOUT_MS).unref?.();
34226
34369
  })
34227
34370
  ]);
34228
34371
  const shaped = usageWindows(windows);
34229
- if (shaped.length) this.quotas.set(cli, { checkedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: shaped });
34230
- } catch {
34372
+ 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" } });
34373
+ } catch (error62) {
34374
+ this.quotas.set(cli, { checkedAt, windows: [], unavailable: { reason: "probeFailed", message: (error62 instanceof Error ? error62.message : String(error62)).slice(0, 300) } });
34231
34375
  }
34232
34376
  }));
34233
34377
  }
@@ -34237,7 +34381,7 @@ var ProviderCatalog = class {
34237
34381
  import { createHash as createHash5 } from "node:crypto";
34238
34382
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync9, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync4 } from "node:fs";
34239
34383
  import { rename as rename9, writeFile as writeFile10 } from "node:fs/promises";
34240
- import { join as join23 } from "node:path";
34384
+ import { join as join24 } from "node:path";
34241
34385
  var ITEM_RUNS_KEPT = 40;
34242
34386
  var SEQUENCE_BLOCK = 500;
34243
34387
  var SAVE_DEBOUNCE_MS = 800;
@@ -34250,9 +34394,9 @@ function writeAtomicSync(path, text5) {
34250
34394
  var ThreadStore = class {
34251
34395
  constructor(dataDir, onError = () => void 0) {
34252
34396
  this.onError = onError;
34253
- this.root = join23(dataDir, "hub");
34254
- this.threadsDir = join23(this.root, "threads");
34255
- this.statePath = join23(this.root, "state.json");
34397
+ this.root = join24(dataDir, "hub");
34398
+ this.threadsDir = join24(this.root, "threads");
34399
+ this.statePath = join24(this.root, "state.json");
34256
34400
  mkdirSync4(this.threadsDir, { recursive: true, mode: 448 });
34257
34401
  try {
34258
34402
  const state = JSON.parse(readFileSync9(this.statePath, "utf8"));
@@ -34264,7 +34408,7 @@ var ThreadStore = class {
34264
34408
  for (const name of readdirSync5(this.threadsDir)) {
34265
34409
  if (!name.endsWith(".json")) continue;
34266
34410
  try {
34267
- const thread = JSON.parse(readFileSync9(join23(this.threadsDir, name), "utf8"));
34411
+ const thread = JSON.parse(readFileSync9(join24(this.threadsDir, name), "utf8"));
34268
34412
  if (thread?.v === 1 && typeof thread.id === "string" && Array.isArray(thread.runs) && Array.isArray(thread.items)) this.threads.set(thread.id, thread);
34269
34413
  } catch {
34270
34414
  }
@@ -34336,7 +34480,7 @@ var ThreadStore = class {
34336
34480
  clearTimeout(timer);
34337
34481
  this.timers.delete(threadId);
34338
34482
  }
34339
- if (safeId(threadId)) rmSync(join23(this.threadsDir, `${threadId}.json`), { force: true });
34483
+ if (safeId(threadId)) rmSync(join24(this.threadsDir, `${threadId}.json`), { force: true });
34340
34484
  }
34341
34485
  /** Marks the thread changed; it is written shortly after (and on `flush`). */
34342
34486
  touch(thread) {
@@ -34347,7 +34491,7 @@ var ThreadStore = class {
34347
34491
  const current = this.threads.get(thread.id);
34348
34492
  if (!current) return;
34349
34493
  this.trim(current);
34350
- const path = join23(this.threadsDir, `${current.id}.json`);
34494
+ const path = join24(this.threadsDir, `${current.id}.json`);
34351
34495
  const temporary = `${path}.${process.pid}.tmp`;
34352
34496
  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
34497
  }, SAVE_DEBOUNCE_MS);
@@ -34362,7 +34506,7 @@ var ThreadStore = class {
34362
34506
  if (!thread) continue;
34363
34507
  this.trim(thread);
34364
34508
  try {
34365
- writeAtomicSync(join23(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
34509
+ writeAtomicSync(join24(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
34366
34510
  } catch (error62) {
34367
34511
  this.onError(error62 instanceof Error ? error62.message : String(error62));
34368
34512
  }
@@ -34379,10 +34523,10 @@ var ThreadStore = class {
34379
34523
  };
34380
34524
 
34381
34525
  // src/t3/turn-items.ts
34382
- var MAX_TEXT = 2e5;
34526
+ var MAX_TEXT2 = 2e5;
34383
34527
  var MAX_OUTPUT = 16e3;
34384
34528
  var MAX_DIFF = 24e3;
34385
- var clip3 = (text5, max) => text5.length > max ? `${text5.slice(0, max)}\u2026` : text5;
34529
+ var clip4 = (text5, max) => text5.length > max ? `${text5.slice(0, max)}\u2026` : text5;
34386
34530
  var record10 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
34387
34531
  var text3 = (value) => typeof value === "string" ? value : "";
34388
34532
  var STATUS = { pending: "pending", in_progress: "running", completed: "completed", failed: "failed" };
@@ -34415,7 +34559,7 @@ var TurnItemFolder = class {
34415
34559
  }
34416
34560
  this.open.delete(kind === "assistant_message" ? "reasoning" : "assistant_message");
34417
34561
  const item = this.upsert(key2, kind, { streaming: true });
34418
- item.text = clip3(text3(item.text) + event.text, MAX_TEXT);
34562
+ item.text = clip4(text3(item.text) + event.text, MAX_TEXT2);
34419
34563
  item.status = "running";
34420
34564
  return this.touch(item);
34421
34565
  }
@@ -34426,7 +34570,7 @@ var TurnItemFolder = class {
34426
34570
  case "text":
34427
34571
  case "thought": {
34428
34572
  const item = this.upsert(key, source.type === "text" ? "assistant_message" : "reasoning", { streaming: true });
34429
- item.text = clip3(text3(source.text), MAX_TEXT);
34573
+ item.text = clip4(text3(source.text), MAX_TEXT2);
34430
34574
  item.status = "running";
34431
34575
  return this.touch(item);
34432
34576
  }
@@ -34440,7 +34584,7 @@ var TurnItemFolder = class {
34440
34584
  }
34441
34585
  case "proposed_plan": {
34442
34586
  const item = this.upsert(key, "proposed_plan", { planId: text3(source.turnId) || key });
34443
- item.markdown = clip3(text3(source.markdown), MAX_TEXT);
34587
+ item.markdown = clip4(text3(source.markdown), MAX_TEXT2);
34444
34588
  item.status = "completed";
34445
34589
  return this.touch(item);
34446
34590
  }
@@ -34507,7 +34651,7 @@ var TurnItemFolder = class {
34507
34651
  const exitCode = record10(output2?.exitStatus).exitCode;
34508
34652
  item = this.upsert(key, "command_execution", {});
34509
34653
  item.input = text3(command?.command) || title;
34510
- if (output2) item.output = clip3(text3(output2.output), MAX_OUTPUT);
34654
+ if (output2) item.output = clip4(text3(output2.output), MAX_OUTPUT);
34511
34655
  if (typeof exitCode === "number") item.exitCode = exitCode;
34512
34656
  } else if (kind === "edit") {
34513
34657
  const paths = [...new Set([...diffs.map((part) => text3(part.path)), ...locations].filter(Boolean))];
@@ -34516,8 +34660,8 @@ var TurnItemFolder = class {
34516
34660
  if (paths.length) item.changes = paths.slice(0, 200).map((path) => ({ operation: "edit", path }));
34517
34661
  const first = diffs[0];
34518
34662
  if (first) {
34519
- if (typeof first.oldText === "string") item.oldStr = clip3(first.oldText, MAX_DIFF);
34520
- item.newStr = clip3(text3(first.newText), MAX_DIFF);
34663
+ if (typeof first.oldText === "string") item.oldStr = clip4(first.oldText, MAX_DIFF);
34664
+ item.newStr = clip4(text3(first.newText), MAX_DIFF);
34521
34665
  }
34522
34666
  } else if (kind === "search") {
34523
34667
  item = this.upsert(key, "file_search", {});
@@ -34531,7 +34675,7 @@ var TurnItemFolder = class {
34531
34675
  if (source.rawInput !== void 0) item.input = source.rawInput;
34532
34676
  if (source.rawOutput !== void 0) item.output = source.rawOutput;
34533
34677
  }
34534
- if (title) item.title = clip3(title, 400);
34678
+ if (title) item.title = clip4(title, 400);
34535
34679
  item.status = status;
34536
34680
  if (status === "completed" || status === "failed") item.completedAt = (/* @__PURE__ */ new Date()).toISOString();
34537
34681
  return this.touch(item);
@@ -34545,6 +34689,7 @@ var ITEM_FLUSH_MS = 200;
34545
34689
  var SNAPSHOT_RUNS = 30;
34546
34690
  var MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
34547
34691
  var DEFAULT_MODEL_SENTINELS = /* @__PURE__ */ new Set(["antigravity-default", "default"]);
34692
+ var providerThreadId = (threadId, sessionId) => `${threadId}:${sessionId}`;
34548
34693
  var record11 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
34549
34694
  var text4 = (value) => typeof value === "string" ? value : "";
34550
34695
  function selectionEffort(selection) {
@@ -34562,7 +34707,7 @@ var T3Backend = class {
34562
34707
  this.config = config2;
34563
34708
  this.logger = logger;
34564
34709
  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"));
34710
+ this.orphans = new OrphanRegistry(join25(config2.dataDir, "active-runs.json"));
34566
34711
  const reporter = {
34567
34712
  started: async (runId, report) => this.onRunStarted(runId, report),
34568
34713
  content: (runId, events) => this.onRunContent(runId, events),
@@ -34627,12 +34772,12 @@ var T3Backend = class {
34627
34772
  // ---- DeviceBackend: projects and snapshots ----
34628
34773
  async ensureProject(workspaceRoot) {
34629
34774
  let target = (workspaceRoot ?? "").trim();
34630
- if (!target || target === "~") target = homedir14();
34631
- else if (target.startsWith("~/") || target.startsWith("~\\")) target = join24(homedir14(), target.slice(2));
34775
+ if (!target || target === "~") target = homedir15();
34776
+ else if (target.startsWith("~/") || target.startsWith("~\\")) target = join25(homedir15(), target.slice(2));
34632
34777
  const root2 = resolve7(target);
34633
34778
  try {
34634
34779
  await mkdir9(root2, { recursive: true });
34635
- if (!(await stat8(root2)).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
34780
+ if (!(await stat9(root2)).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
34636
34781
  } catch (error62) {
34637
34782
  throw rpcError("ProjectMutationError", `\u65E0\u6CD5\u4F7F\u7528\u5DE5\u4F5C\u76EE\u5F55 ${root2}\uFF1A${error62 instanceof Error ? error62.message : String(error62)}`, `workspaceRoot=${root2}`);
34638
34783
  }
@@ -34651,6 +34796,8 @@ var T3Backend = class {
34651
34796
  thread: this.threadState(thread),
34652
34797
  runs: runs.map((entry) => entry.run),
34653
34798
  turnItems: thread.items.filter((entry) => typeof entry.item.runId !== "string" || kept.has(entry.item.runId)).map((entry) => entry.item),
34799
+ // The CLI sessions the runs ran in; the Hub offers a native fork only from a run with a strong one.
34800
+ providerThreads: this.providerThreads(thread),
34654
34801
  runtimeRequests: []
34655
34802
  }
34656
34803
  };
@@ -34698,7 +34845,7 @@ var T3Backend = class {
34698
34845
  case "provider.switch":
34699
34846
  return this.selectModel(command);
34700
34847
  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");
34848
+ return this.forkThread(command);
34702
34849
  case "runtime-request.respond":
34703
34850
  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
34851
  default:
@@ -34855,7 +35002,7 @@ var T3Backend = class {
34855
35002
  async saveAttachments(thread, messageId, attachments) {
34856
35003
  if (!attachments.length) return "";
34857
35004
  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, "_"));
35005
+ const directory = join25(this.config.dataDir, "hub", "attachments", thread.id.replace(/[^A-Za-z0-9_.-]/g, "_"), messageId.replace(/[^A-Za-z0-9_.-]/g, "_"));
34859
35006
  for (const [index, attachment] of attachments.entries()) {
34860
35007
  const name = (text4(attachment.name) || `attachment-${index + 1}`).replace(/[^\p{L}\p{N}_.-]/gu, "_").slice(0, 120);
34861
35008
  const dataUrl = text4(attachment.dataUrl);
@@ -34868,7 +35015,7 @@ var T3Backend = class {
34868
35015
  }
34869
35016
  try {
34870
35017
  await mkdir9(directory, { recursive: true, mode: 448 });
34871
- const path = join24(directory, `${index + 1}-${name}`);
35018
+ const path = join25(directory, `${index + 1}-${name}`);
34872
35019
  await writeFile11(path, bytes, { mode: 384 });
34873
35020
  lines.push(`- ${path}`);
34874
35021
  } catch (error62) {
@@ -34897,6 +35044,12 @@ ${lines.join("\n")}` : "";
34897
35044
  run.status = "starting";
34898
35045
  this.emitRun(thread, cli, entry, "run.updated");
34899
35046
  }
35047
+ const fork = thread.nativeSessionId ? void 0 : thread.fork;
35048
+ const sessionId = thread.nativeSessionId || (fork && cli.cli === "claude" ? randomUUID5() : "");
35049
+ if (fork && cli.cli === "claude" && !claudeTranscriptExists(fork.sourceSessionId)) {
35050
+ 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 });
35051
+ return;
35052
+ }
34900
35053
  void (async () => {
34901
35054
  const payload = RunStartPayloadSchema.parse({
34902
35055
  // Full access, always: no turn of this device ever waits for a confirmation.
@@ -34906,7 +35059,8 @@ ${lines.join("\n")}` : "";
34906
35059
  task_chain_id: thread.id,
34907
35060
  message_id: run.userMessageId,
34908
35061
  prompt: entry.prompt ?? "",
34909
- session_id: thread.nativeSessionId,
35062
+ session_id: sessionId,
35063
+ ...fork ? { fork: { source_session_id: fork.sourceSessionId, keep_turns: fork.keepTurns } } : {},
34910
35064
  model: DEFAULT_MODEL_SENTINELS.has(model) ? "" : model,
34911
35065
  reasoning_effort: selectionEffort(thread.modelSelection),
34912
35066
  workdir: thread.workspaceRoot
@@ -34949,15 +35103,84 @@ ${lines.join("\n")}` : "";
34949
35103
  const found = this.runOf(runId);
34950
35104
  if (!found) return;
34951
35105
  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);
35106
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35107
+ if (report.pid) {
35108
+ entry.launched = true;
35109
+ if (entry.run.status === "starting") {
35110
+ entry.run.status = "running";
35111
+ entry.run.startedAt = (/* @__PURE__ */ new Date()).toISOString();
35112
+ this.emitRun(thread, this.cliOf(thread), entry, "run.updated");
35113
+ }
34955
35114
  }
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");
35115
+ }
35116
+ /** The CLI named the session this turn runs in: the thread continues it, and the run points at it. */
35117
+ noteNativeSession(thread, entry, sessionId) {
35118
+ entry.nativeSessionId = sessionId;
35119
+ entry.run.providerThreadId = providerThreadId(thread.id, sessionId);
35120
+ if (thread.nativeSessionId !== sessionId) {
35121
+ thread.nativeSessionId = sessionId;
35122
+ delete thread.fork;
34960
35123
  }
35124
+ this.store.touch(thread);
35125
+ }
35126
+ providerThreads(thread) {
35127
+ const cli = this.cliOf(thread);
35128
+ const sessions = new Set(thread.runs.map((entry) => entry.nativeSessionId).filter((id) => Boolean(id)));
35129
+ return [...sessions].map((sessionId) => ({
35130
+ id: providerThreadId(thread.id, sessionId),
35131
+ threadId: thread.id,
35132
+ driver: cli.driver,
35133
+ providerInstanceId: cli.instanceId,
35134
+ nativeThreadRef: { strength: "strong", id: sessionId }
35135
+ }));
35136
+ }
35137
+ /**
35138
+ * `thread.fork`: a new thread on the same CLI and work directory whose first
35139
+ * turn continues a native copy of the source CLI session up to the chosen
35140
+ * run. The source thread is not touched. Only CLIs that can copy a session
35141
+ * are forked (Claude Code, Codex); the others are refused, never imitated.
35142
+ */
35143
+ forkThread(command) {
35144
+ const source = this.requireThread(command.sourceThreadId);
35145
+ const targetId = text4(command.targetThreadId);
35146
+ if (!targetId) throw rpcError(ERROR_TAGS.invalidCommand, "thread.fork \u7F3A\u5C11 targetThreadId");
35147
+ if (this.store.get(targetId)) return { threadId: targetId, created: false };
35148
+ const cli = this.cliOf(source);
35149
+ if (cli.cli !== "claude" && cli.cli !== "codex") {
35150
+ 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}`);
35151
+ }
35152
+ const point = record11(command.sourcePoint);
35153
+ const runId = text4(point.runId);
35154
+ const at = runId ? source.runs.find((entry) => entry.run.id === runId) : [...source.runs].reverse().find((entry) => entry.run.status === "completed");
35155
+ 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`);
35156
+ 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}`);
35157
+ 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`);
35158
+ const keepTurns = source.runs.filter((entry) => entry.launched && entry.nativeSessionId === at.nativeSessionId && entry.run.ordinal <= at.run.ordinal).length;
35159
+ const now = (/* @__PURE__ */ new Date()).toISOString();
35160
+ const thread = {
35161
+ v: 1,
35162
+ id: targetId,
35163
+ projectId: source.projectId,
35164
+ workspaceRoot: source.workspaceRoot,
35165
+ title: text4(command.title) || `${source.title}\uFF08\u5206\u53C9\uFF09`,
35166
+ cli: source.cli,
35167
+ modelSelection: record11(at.run.modelSelection).model ? record11(at.run.modelSelection) : source.modelSelection,
35168
+ runtimeMode: source.runtimeMode,
35169
+ interactionMode: source.interactionMode,
35170
+ createdAt: now,
35171
+ updatedAt: now,
35172
+ nativeSessionId: "",
35173
+ archived: false,
35174
+ queueHeld: false,
35175
+ seq: 0,
35176
+ nextItemOrdinal: 1,
35177
+ runs: [],
35178
+ items: [],
35179
+ fork: { sourceThreadId: source.id, sourceRunId: at.run.id, sourceSessionId: at.nativeSessionId, keepTurns }
35180
+ };
35181
+ this.store.put(thread);
35182
+ this.emitThread(thread, "thread.created");
35183
+ return { threadId: targetId, created: true, forkedFrom: { threadId: source.id, runId: at.run.id, keepTurns } };
34961
35184
  }
34962
35185
  onRunContent(runId, events) {
34963
35186
  const live = this.live.get(runId);
@@ -35001,7 +35224,7 @@ ${lines.join("\n")}` : "";
35001
35224
  this.dropLive(runId);
35002
35225
  return;
35003
35226
  }
35004
- if (report.session_id && report.session_id !== thread.nativeSessionId) thread.nativeSessionId = report.session_id;
35227
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35005
35228
  const outcome = report.status === "succeeded" ? "completed" : report.status === "cancelled" ? "interrupted" : "failed";
35006
35229
  const live = this.live.get(runId);
35007
35230
  if (live) {
@@ -35066,7 +35289,9 @@ ${lines.join("\n")}` : "";
35066
35289
  workspaceRoot: thread.workspaceRoot,
35067
35290
  createdAt: thread.createdAt,
35068
35291
  updatedAt: thread.updatedAt,
35069
- archivedAt: thread.archived ? thread.updatedAt : null
35292
+ archived: thread.archived,
35293
+ archivedAt: thread.archived ? thread.updatedAt : null,
35294
+ ...thread.fork ? { forkedFrom: { threadId: thread.fork.sourceThreadId, runId: thread.fork.sourceRunId } } : {}
35070
35295
  };
35071
35296
  }
35072
35297
  emitThread(thread, type) {
@@ -35095,7 +35320,7 @@ var HubRuntime = class {
35095
35320
  },
35096
35321
  backend: this.backend,
35097
35322
  appVersion: hubAppVersion(version2),
35098
- eventStatePath: join25(config2.dataDir, "hub-events.json"),
35323
+ eventStatePath: join26(config2.dataDir, "hub-events.json"),
35099
35324
  logger: this.logger
35100
35325
  });
35101
35326
  this.backend.attach({ event: (envelope) => this.link.publishEvent(envelope) });
@@ -35536,7 +35761,7 @@ function preferSystemNode() {
35536
35761
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
35537
35762
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
35538
35763
  for (const name of names) {
35539
- const candidate = directory && join26(directory, name);
35764
+ const candidate = directory && join27(directory, name);
35540
35765
  if (candidate && existsSync8(candidate)) {
35541
35766
  process.env.TOC_OCRA_NODE_PATH = candidate;
35542
35767
  return;
@@ -602,9 +602,10 @@ export class HubLink {
602
602
  this.logger.warn('hub-error-frame', { data: JSON.stringify(frame.data ?? null).slice(0, 500) });
603
603
  return;
604
604
  default:
605
- // Web terminal is not part of this device package: say so with a tag the Hub can show.
605
+ // Web terminal is not part of this device package (the Hub's device exec runs through
606
+ // the same terminal frames): say so with a tag the Hub can show.
606
607
  if (frame.type.startsWith('terminal.')) {
607
- this.reply(frame.type, frame.id, { ok: false, error: rpcError(ERROR_TAGS.terminalUnsupported, 'ocra 设备包暂不支持 Web 终端,请在设备本机打开终端', `frame=${frame.type}`) });
608
+ this.reply(frame.type, frame.id, { ok: false, error: rpcError(ERROR_TAGS.terminalUnsupported, 'ocra 设备包暂不支持 Web 终端和设备命令执行(exec),请在设备本机的终端里操作', `frame=${frame.type}`) });
608
609
  }
609
610
  // Other unknown types are ignored on purpose, as the protocol requires.
610
611
  }