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.
package/README.md CHANGED
@@ -6,7 +6,11 @@ Echo 的「免 T3」设备包:装在用户电脑上,通过长连接实时接
6
6
  - 通过这套协议支持三家 CLI:**Claude Code、Codex、Antigravity(agy)**。新建会话、发消息、收回复和执行过程、停止、选工作目录都可用。
7
7
  - 一个会话绑定建会话时选定的 CLI,后续消息用该 CLI 自带的续接功能接着上一轮上下文。
8
8
  - 所有轮次以**完全访问**模式运行(Claude `--dangerously-skip-permissions`、Codex `--dangerously-bypass-approvals-and-sandbox`、Antigravity `--dangerously-skip-permissions`),不会出现需要确认的权限请求。只在你信任的电脑和账号上使用。
9
- - 暂不支持:Web 终端、会话分叉、skills 目录、会话内切换 CLI。
9
+ - 额度:三家 CLI 的套餐额度在网页「同步额度」时读取并上报;读不到的那一家如实显示原因,不影响其他两家。
10
+ - Skills:扫描三家 CLI 在本机的 Skills 目录并上报(Claude Code `~/.claude/skills` 和插件目录;Codex `~/.codex/skills`、插件目录和 `~/.agents/skills`;Antigravity `~/.gemini/antigravity/skills`、`~/.gemini/antigravity-cli/skills`、`~/.agents/skills`),显示名取自 Skill 目录下的 `agents/openai.yaml` 或 `SKILL.md` 的 front matter。
11
+ - 分叉:Claude Code 和 Codex 的会话可以从任意一轮分叉成新会话(用 CLI 自带的分叉能力,保留到那一轮为止的上下文,原会话不受影响);Antigravity 没有分叉能力,会提示「暂不支持分叉」。
12
+ - 会话改名、归档、删除、图片附件、推理强度、同一 CLI 内换模型、运行中排队都可用。
13
+ - 暂不支持:Web 终端和设备执行命令(exec)、slash 命令目录、会话内切换 CLI、Antigravity 分叉。完整对照见 [docs/hub-protocol.md](docs/hub-protocol.md#设备能力对照)。
10
14
 
11
15
  ## 安装与配对
12
16
 
package/dist/cli/cli.mjs CHANGED
@@ -3791,7 +3791,7 @@ import { createHash as createHash6 } from "node:crypto";
3791
3791
  import { existsSync as existsSync8, mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "node:fs";
3792
3792
  import { tmpdir as tmpdir4 } from "node:os";
3793
3793
  import { createRequire } from "node:module";
3794
- import { dirname as dirname11, join as join27, resolve as resolve9 } from "node:path";
3794
+ import { dirname as dirname11, join as join28, resolve as resolve9 } from "node:path";
3795
3795
  import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL2 } from "node:url";
3796
3796
 
3797
3797
  // src/config.ts
@@ -25253,14 +25253,14 @@ function parseCodexModels(content) {
25253
25253
  return void 0;
25254
25254
  }
25255
25255
  }
25256
- async function readCodexModels(codexHome3, config2) {
25256
+ async function readCodexModels(codexHome4, config2) {
25257
25257
  const configuredCatalog = configValue(config2, "model_catalog_json");
25258
25258
  if (configuredCatalog) {
25259
- const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve3(codexHome3, configuredCatalog);
25259
+ const catalogPath = isAbsolute2(configuredCatalog) ? configuredCatalog : resolve3(codexHome4, configuredCatalog);
25260
25260
  const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
25261
25261
  if (configuredModels?.length) return configuredModels;
25262
25262
  }
25263
- const cached3 = parseCodexModels(await readFile3(join11(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
25263
+ const cached3 = parseCodexModels(await readFile3(join11(codexHome4, "models_cache.json"), "utf8").catch(() => ""));
25264
25264
  if (cached3?.length) return cached3;
25265
25265
  return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
25266
25266
  }
@@ -33045,7 +33045,7 @@ function createDiagnosticLogger(filePath, options = {}) {
33045
33045
  }
33046
33046
 
33047
33047
  // src/runtime/hub-runtime.ts
33048
- import { join as join26 } from "node:path";
33048
+ import { join as join27 } from "node:path";
33049
33049
 
33050
33050
  // node_modules/ws/wrapper.mjs
33051
33051
  var import_stream = __toESM(require_stream(), 1);
@@ -33980,7 +33980,7 @@ var HubLink = class {
33980
33980
  return;
33981
33981
  default:
33982
33982
  if (frame.type.startsWith("terminal.")) {
33983
- 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}`) });
33983
+ 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}`) });
33984
33984
  }
33985
33985
  }
33986
33986
  }
@@ -33991,9 +33991,9 @@ function errorMessage3(error62) {
33991
33991
 
33992
33992
  // src/t3/t3-backend.ts
33993
33993
  import { randomUUID as randomUUID5 } from "node:crypto";
33994
- import { mkdir as mkdir9, stat as stat8, writeFile as writeFile11 } from "node:fs/promises";
33995
- import { homedir as homedir14 } from "node:os";
33996
- import { basename as basename4, join as join25, resolve as resolve7 } from "node:path";
33994
+ import { mkdir as mkdir9, stat as stat9, writeFile as writeFile11 } from "node:fs/promises";
33995
+ import { homedir as homedir15 } from "node:os";
33996
+ import { basename as basename4, join as join26, resolve as resolve7 } from "node:path";
33997
33997
 
33998
33998
  // src/runs/orphan-registry.ts
33999
33999
  import { mkdir as mkdir8, readFile as readFile9, rename as rename8, writeFile as writeFile9 } from "node:fs/promises";
@@ -34228,6 +34228,144 @@ var ModelCatalogCollector = class {
34228
34228
  }
34229
34229
  };
34230
34230
 
34231
+ // src/t3/skills.ts
34232
+ import { readdir as readdir5, readFile as readFile10, stat as stat8 } from "node:fs/promises";
34233
+ import { homedir as homedir14 } from "node:os";
34234
+ import { join as join24 } from "node:path";
34235
+ var MAX_SKILLS_PER_CLI = 500;
34236
+ var MAX_SKILL_FILE_BYTES = 256 * 1024;
34237
+ var MAX_TEXT = 1e3;
34238
+ var claudeHome3 = () => process.env.CLAUDE_CONFIG_DIR?.trim().split(process.platform === "win32" ? ";" : ":")[0]?.trim() || join24(homedir14(), ".claude");
34239
+ var codexHome3 = () => process.env.CODEX_HOME?.trim() || join24(homedir14(), ".codex");
34240
+ function skillRoots(cli, home = homedir14()) {
34241
+ const agents = { directory: join24(home, ".agents", "skills"), source: "user", depth: 2 };
34242
+ switch (cli) {
34243
+ case "claude":
34244
+ return [
34245
+ { directory: join24(claudeHome3(), "skills"), source: "user", depth: 2 },
34246
+ // Installed plugins keep their skills under <plugin>/skills/<name>/SKILL.md, several levels down.
34247
+ { directory: join24(claudeHome3(), "plugins"), source: "plugin", depth: 7 }
34248
+ ];
34249
+ case "codex":
34250
+ return [
34251
+ // Bundled skills live in skills/.system/<name>.
34252
+ { directory: join24(codexHome3(), "skills"), source: "user", depth: 3 },
34253
+ { directory: join24(codexHome3(), "plugins"), source: "plugin", depth: 7 },
34254
+ agents
34255
+ ];
34256
+ case "antigravity":
34257
+ return [
34258
+ { directory: join24(home, ".gemini", "antigravity", "skills"), source: "user", depth: 2 },
34259
+ { directory: join24(home, ".gemini", "antigravity-cli", "skills"), source: "user", depth: 2 },
34260
+ agents
34261
+ ];
34262
+ }
34263
+ }
34264
+ var unquote = (value) => {
34265
+ const trimmed = value.trim();
34266
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
34267
+ const inner = trimmed.slice(1, -1);
34268
+ return trimmed.startsWith('"') ? inner.replace(/\\"/g, '"').replace(/\\n/g, "\n").replace(/\\\\/g, "\\") : inner.replace(/''/g, "'");
34269
+ }
34270
+ return trimmed;
34271
+ };
34272
+ function yamlScalars(source) {
34273
+ const out = {};
34274
+ const lines = source.split(/\r?\n/);
34275
+ const parents = [];
34276
+ for (let index = 0; index < lines.length; index++) {
34277
+ const line = lines[index];
34278
+ if (!line.trim() || line.trimStart().startsWith("#") || line.trimStart().startsWith("- ")) continue;
34279
+ const match = /^(\s*)([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line);
34280
+ if (!match) continue;
34281
+ const indent = match[1].length;
34282
+ while (parents.length && parents[parents.length - 1].indent >= indent) parents.pop();
34283
+ const path = [...parents.map((parent) => parent.key), match[2]].join(".");
34284
+ let value = match[3].replace(/\s+#.*$/, "");
34285
+ if (value === "") {
34286
+ parents.push({ indent, key: match[2] });
34287
+ continue;
34288
+ }
34289
+ if (/^[|>][+-]?$/.test(value)) {
34290
+ const folded = value.startsWith(">");
34291
+ const block = [];
34292
+ while (index + 1 < lines.length && (!lines[index + 1].trim() || lines[index + 1].length - lines[index + 1].trimStart().length > indent)) {
34293
+ block.push(lines[++index].trim());
34294
+ }
34295
+ value = block.join(folded ? " " : "\n").trim();
34296
+ } else value = unquote(value);
34297
+ out[path] = value;
34298
+ }
34299
+ return out;
34300
+ }
34301
+ function skillFrontMatter(markdown) {
34302
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);
34303
+ return match ? yamlScalars(match[1]) : {};
34304
+ }
34305
+ var clip3 = (value) => {
34306
+ const flat = value?.replace(/\s+/g, " ").trim();
34307
+ return flat ? flat.length > MAX_TEXT ? `${flat.slice(0, MAX_TEXT)}\u2026` : flat : void 0;
34308
+ };
34309
+ async function readSmall(path) {
34310
+ try {
34311
+ const info = await stat8(path);
34312
+ if (!info.isFile() || info.size > MAX_SKILL_FILE_BYTES) return void 0;
34313
+ return await readFile10(path, "utf8");
34314
+ } catch {
34315
+ return void 0;
34316
+ }
34317
+ }
34318
+ async function readSkill(directory, folder, source) {
34319
+ const markdown = await readSmall(join24(directory, "SKILL.md"));
34320
+ if (markdown === void 0) return void 0;
34321
+ const front = skillFrontMatter(markdown);
34322
+ const openai = yamlScalars(await readSmall(join24(directory, "agents", "openai.yaml")) ?? "");
34323
+ const name = (front.name || folder).trim();
34324
+ if (!name) return void 0;
34325
+ const displayName = clip3(openai["interface.display_name"] ?? front["metadata.display-name"] ?? front["metadata.display_name"] ?? front["display-name"] ?? front.display_name);
34326
+ const description = clip3(front.description);
34327
+ const shortDescription = clip3(openai["interface.short_description"] ?? front["metadata.short-description"] ?? front["metadata.short_description"]);
34328
+ return {
34329
+ name,
34330
+ ...displayName ? { displayName } : {},
34331
+ ...description ? { description } : {},
34332
+ ...shortDescription ? { shortDescription } : {},
34333
+ path: join24(directory, "SKILL.md"),
34334
+ source,
34335
+ enabled: true,
34336
+ userInvocable: true
34337
+ };
34338
+ }
34339
+ async function scan(root2, found) {
34340
+ const walk = async (directory, folder, depth, source) => {
34341
+ if (found.size >= MAX_SKILLS_PER_CLI) return;
34342
+ let entries;
34343
+ try {
34344
+ entries = await readdir5(directory, { withFileTypes: true });
34345
+ } catch {
34346
+ return;
34347
+ }
34348
+ if (entries.some((entry) => entry.name === "SKILL.md")) {
34349
+ const skill = await readSkill(directory, folder, source);
34350
+ if (skill && !found.has(skill.name)) found.set(skill.name, skill);
34351
+ return;
34352
+ }
34353
+ if (depth <= 0) return;
34354
+ for (const entry of entries) {
34355
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
34356
+ const isDirectory = entry.isDirectory() || entry.isSymbolicLink() && await stat8(join24(directory, entry.name)).then((info) => info.isDirectory(), () => false);
34357
+ if (!isDirectory) continue;
34358
+ await walk(join24(directory, entry.name), entry.name, depth - 1, entry.name === ".system" ? "system" : source);
34359
+ }
34360
+ };
34361
+ await walk(root2.directory, "", root2.depth, root2.source);
34362
+ }
34363
+ async function readCliSkills(cli, home = homedir14()) {
34364
+ const found = /* @__PURE__ */ new Map();
34365
+ for (const root2 of skillRoots(cli, home)) await scan(root2, found);
34366
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
34367
+ }
34368
+
34231
34369
  // src/t3/provider-catalog.ts
34232
34370
  var HUB_CLIS = [
34233
34371
  { cli: "codex", instanceId: "codex", driver: "codex", displayName: "Codex", effortOptionId: "reasoning_effort" },
@@ -34266,7 +34404,7 @@ function models2(cli, item) {
34266
34404
  function usageWindows(windows) {
34267
34405
  return windows.filter((window) => typeof window.used_percent === "number").map((window) => {
34268
34406
  const minutes = window.window_seconds ? Math.round(window.window_seconds / 60) : void 0;
34269
- const kind = minutes === void 0 ? "other" : minutes <= 6 * 60 ? "session" : minutes <= 8 * 24 * 60 ? "weekly" : minutes <= 32 * 24 * 60 ? "monthly" : "other";
34407
+ const kind = minutes === void 0 ? "other" : minutes >= 25 * 24 * 60 ? "monthly" : minutes >= 6 * 24 * 60 ? "weekly" : minutes <= 24 * 60 ? "session" : "other";
34270
34408
  return {
34271
34409
  id: window.key,
34272
34410
  kind,
@@ -34310,6 +34448,10 @@ var ProviderCatalog = class {
34310
34448
  const detected = HUB_CLIS.filter((cli) => detection.providers.some((provider) => provider.id === cli.cli && provider.installed)).map((cli) => cli.cli);
34311
34449
  const report = await this.collector.collect(detected, { force: Boolean(options.force) });
34312
34450
  if (options.quota) await this.readQuotas(detected, options.providerId);
34451
+ const skills = new Map(await Promise.all(HUB_CLIS.map(async (cli) => [
34452
+ cli.cli,
34453
+ detected.includes(cli.cli) ? await readCliSkills(cli.cli).catch(() => []) : []
34454
+ ])));
34313
34455
  const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
34314
34456
  this.last = HUB_CLIS.map((cli) => {
34315
34457
  const found = detection.providers.find((provider) => provider.id === cli.cli);
@@ -34332,7 +34474,7 @@ var ProviderCatalog = class {
34332
34474
  checkedAt,
34333
34475
  models: list,
34334
34476
  ...usage && runnable ? { usageLimits: usage } : {},
34335
- skills: [],
34477
+ skills: skills.get(cli.cli) ?? [],
34336
34478
  slashCommands: []
34337
34479
  };
34338
34480
  });
@@ -34343,16 +34485,18 @@ var ProviderCatalog = class {
34343
34485
  await Promise.all(detected.filter((cli) => !only || cli === only).map(async (cli) => {
34344
34486
  const read = catalogEntry(cli)?.quota;
34345
34487
  if (!read) return;
34488
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
34346
34489
  try {
34347
34490
  const windows = await Promise.race([
34348
34491
  read(),
34349
34492
  new Promise((_resolve, reject) => {
34350
- setTimeout(() => reject(new Error("timeout")), QUOTA_TIMEOUT_MS).unref?.();
34493
+ setTimeout(() => reject(new Error("\u8BFB\u53D6\u989D\u5EA6\u8D85\u65F6")), QUOTA_TIMEOUT_MS).unref?.();
34351
34494
  })
34352
34495
  ]);
34353
34496
  const shaped = usageWindows(windows);
34354
- if (shaped.length) this.quotas.set(cli, { checkedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: shaped });
34355
- } catch {
34497
+ 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" } });
34498
+ } catch (error62) {
34499
+ this.quotas.set(cli, { checkedAt, windows: [], unavailable: { reason: "probeFailed", message: (error62 instanceof Error ? error62.message : String(error62)).slice(0, 300) } });
34356
34500
  }
34357
34501
  }));
34358
34502
  }
@@ -34362,7 +34506,7 @@ var ProviderCatalog = class {
34362
34506
  import { createHash as createHash5 } from "node:crypto";
34363
34507
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync9, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync4 } from "node:fs";
34364
34508
  import { rename as rename9, writeFile as writeFile10 } from "node:fs/promises";
34365
- import { join as join24 } from "node:path";
34509
+ import { join as join25 } from "node:path";
34366
34510
  var ITEM_RUNS_KEPT = 40;
34367
34511
  var SEQUENCE_BLOCK = 500;
34368
34512
  var SAVE_DEBOUNCE_MS = 800;
@@ -34375,9 +34519,9 @@ function writeAtomicSync(path, text5) {
34375
34519
  var ThreadStore = class {
34376
34520
  constructor(dataDir, onError = () => void 0) {
34377
34521
  this.onError = onError;
34378
- this.root = join24(dataDir, "hub");
34379
- this.threadsDir = join24(this.root, "threads");
34380
- this.statePath = join24(this.root, "state.json");
34522
+ this.root = join25(dataDir, "hub");
34523
+ this.threadsDir = join25(this.root, "threads");
34524
+ this.statePath = join25(this.root, "state.json");
34381
34525
  mkdirSync4(this.threadsDir, { recursive: true, mode: 448 });
34382
34526
  try {
34383
34527
  const state = JSON.parse(readFileSync9(this.statePath, "utf8"));
@@ -34389,7 +34533,7 @@ var ThreadStore = class {
34389
34533
  for (const name of readdirSync5(this.threadsDir)) {
34390
34534
  if (!name.endsWith(".json")) continue;
34391
34535
  try {
34392
- const thread = JSON.parse(readFileSync9(join24(this.threadsDir, name), "utf8"));
34536
+ const thread = JSON.parse(readFileSync9(join25(this.threadsDir, name), "utf8"));
34393
34537
  if (thread?.v === 1 && typeof thread.id === "string" && Array.isArray(thread.runs) && Array.isArray(thread.items)) this.threads.set(thread.id, thread);
34394
34538
  } catch {
34395
34539
  }
@@ -34461,7 +34605,7 @@ var ThreadStore = class {
34461
34605
  clearTimeout(timer);
34462
34606
  this.timers.delete(threadId);
34463
34607
  }
34464
- if (safeId(threadId)) rmSync(join24(this.threadsDir, `${threadId}.json`), { force: true });
34608
+ if (safeId(threadId)) rmSync(join25(this.threadsDir, `${threadId}.json`), { force: true });
34465
34609
  }
34466
34610
  /** Marks the thread changed; it is written shortly after (and on `flush`). */
34467
34611
  touch(thread) {
@@ -34472,7 +34616,7 @@ var ThreadStore = class {
34472
34616
  const current = this.threads.get(thread.id);
34473
34617
  if (!current) return;
34474
34618
  this.trim(current);
34475
- const path = join24(this.threadsDir, `${current.id}.json`);
34619
+ const path = join25(this.threadsDir, `${current.id}.json`);
34476
34620
  const temporary = `${path}.${process.pid}.tmp`;
34477
34621
  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)));
34478
34622
  }, SAVE_DEBOUNCE_MS);
@@ -34487,7 +34631,7 @@ var ThreadStore = class {
34487
34631
  if (!thread) continue;
34488
34632
  this.trim(thread);
34489
34633
  try {
34490
- writeAtomicSync(join24(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
34634
+ writeAtomicSync(join25(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
34491
34635
  } catch (error62) {
34492
34636
  this.onError(error62 instanceof Error ? error62.message : String(error62));
34493
34637
  }
@@ -34504,10 +34648,10 @@ var ThreadStore = class {
34504
34648
  };
34505
34649
 
34506
34650
  // src/t3/turn-items.ts
34507
- var MAX_TEXT = 2e5;
34651
+ var MAX_TEXT2 = 2e5;
34508
34652
  var MAX_OUTPUT = 16e3;
34509
34653
  var MAX_DIFF = 24e3;
34510
- var clip3 = (text5, max) => text5.length > max ? `${text5.slice(0, max)}\u2026` : text5;
34654
+ var clip4 = (text5, max) => text5.length > max ? `${text5.slice(0, max)}\u2026` : text5;
34511
34655
  var record10 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
34512
34656
  var text3 = (value) => typeof value === "string" ? value : "";
34513
34657
  var STATUS = { pending: "pending", in_progress: "running", completed: "completed", failed: "failed" };
@@ -34540,7 +34684,7 @@ var TurnItemFolder = class {
34540
34684
  }
34541
34685
  this.open.delete(kind === "assistant_message" ? "reasoning" : "assistant_message");
34542
34686
  const item = this.upsert(key2, kind, { streaming: true });
34543
- item.text = clip3(text3(item.text) + event.text, MAX_TEXT);
34687
+ item.text = clip4(text3(item.text) + event.text, MAX_TEXT2);
34544
34688
  item.status = "running";
34545
34689
  return this.touch(item);
34546
34690
  }
@@ -34551,7 +34695,7 @@ var TurnItemFolder = class {
34551
34695
  case "text":
34552
34696
  case "thought": {
34553
34697
  const item = this.upsert(key, source.type === "text" ? "assistant_message" : "reasoning", { streaming: true });
34554
- item.text = clip3(text3(source.text), MAX_TEXT);
34698
+ item.text = clip4(text3(source.text), MAX_TEXT2);
34555
34699
  item.status = "running";
34556
34700
  return this.touch(item);
34557
34701
  }
@@ -34565,7 +34709,7 @@ var TurnItemFolder = class {
34565
34709
  }
34566
34710
  case "proposed_plan": {
34567
34711
  const item = this.upsert(key, "proposed_plan", { planId: text3(source.turnId) || key });
34568
- item.markdown = clip3(text3(source.markdown), MAX_TEXT);
34712
+ item.markdown = clip4(text3(source.markdown), MAX_TEXT2);
34569
34713
  item.status = "completed";
34570
34714
  return this.touch(item);
34571
34715
  }
@@ -34632,7 +34776,7 @@ var TurnItemFolder = class {
34632
34776
  const exitCode = record10(output2?.exitStatus).exitCode;
34633
34777
  item = this.upsert(key, "command_execution", {});
34634
34778
  item.input = text3(command?.command) || title;
34635
- if (output2) item.output = clip3(text3(output2.output), MAX_OUTPUT);
34779
+ if (output2) item.output = clip4(text3(output2.output), MAX_OUTPUT);
34636
34780
  if (typeof exitCode === "number") item.exitCode = exitCode;
34637
34781
  } else if (kind === "edit") {
34638
34782
  const paths = [...new Set([...diffs.map((part) => text3(part.path)), ...locations].filter(Boolean))];
@@ -34641,8 +34785,8 @@ var TurnItemFolder = class {
34641
34785
  if (paths.length) item.changes = paths.slice(0, 200).map((path) => ({ operation: "edit", path }));
34642
34786
  const first = diffs[0];
34643
34787
  if (first) {
34644
- if (typeof first.oldText === "string") item.oldStr = clip3(first.oldText, MAX_DIFF);
34645
- item.newStr = clip3(text3(first.newText), MAX_DIFF);
34788
+ if (typeof first.oldText === "string") item.oldStr = clip4(first.oldText, MAX_DIFF);
34789
+ item.newStr = clip4(text3(first.newText), MAX_DIFF);
34646
34790
  }
34647
34791
  } else if (kind === "search") {
34648
34792
  item = this.upsert(key, "file_search", {});
@@ -34656,7 +34800,7 @@ var TurnItemFolder = class {
34656
34800
  if (source.rawInput !== void 0) item.input = source.rawInput;
34657
34801
  if (source.rawOutput !== void 0) item.output = source.rawOutput;
34658
34802
  }
34659
- if (title) item.title = clip3(title, 400);
34803
+ if (title) item.title = clip4(title, 400);
34660
34804
  item.status = status2;
34661
34805
  if (status2 === "completed" || status2 === "failed") item.completedAt = (/* @__PURE__ */ new Date()).toISOString();
34662
34806
  return this.touch(item);
@@ -34670,6 +34814,7 @@ var ITEM_FLUSH_MS = 200;
34670
34814
  var SNAPSHOT_RUNS = 30;
34671
34815
  var MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
34672
34816
  var DEFAULT_MODEL_SENTINELS = /* @__PURE__ */ new Set(["antigravity-default", "default"]);
34817
+ var providerThreadId = (threadId, sessionId) => `${threadId}:${sessionId}`;
34673
34818
  var record11 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
34674
34819
  var text4 = (value) => typeof value === "string" ? value : "";
34675
34820
  function selectionEffort(selection) {
@@ -34687,7 +34832,7 @@ var T3Backend = class {
34687
34832
  this.config = config2;
34688
34833
  this.logger = logger;
34689
34834
  this.store = new ThreadStore(config2.dataDir, (message) => logger.warn("hub-thread-save-failed", { error: message }));
34690
- this.orphans = new OrphanRegistry(join25(config2.dataDir, "active-runs.json"));
34835
+ this.orphans = new OrphanRegistry(join26(config2.dataDir, "active-runs.json"));
34691
34836
  const reporter = {
34692
34837
  started: async (runId, report) => this.onRunStarted(runId, report),
34693
34838
  content: (runId, events) => this.onRunContent(runId, events),
@@ -34752,12 +34897,12 @@ var T3Backend = class {
34752
34897
  // ---- DeviceBackend: projects and snapshots ----
34753
34898
  async ensureProject(workspaceRoot) {
34754
34899
  let target = (workspaceRoot ?? "").trim();
34755
- if (!target || target === "~") target = homedir14();
34756
- else if (target.startsWith("~/") || target.startsWith("~\\")) target = join25(homedir14(), target.slice(2));
34900
+ if (!target || target === "~") target = homedir15();
34901
+ else if (target.startsWith("~/") || target.startsWith("~\\")) target = join26(homedir15(), target.slice(2));
34757
34902
  const root2 = resolve7(target);
34758
34903
  try {
34759
34904
  await mkdir9(root2, { recursive: true });
34760
- if (!(await stat8(root2)).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
34905
+ if (!(await stat9(root2)).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
34761
34906
  } catch (error62) {
34762
34907
  throw rpcError("ProjectMutationError", `\u65E0\u6CD5\u4F7F\u7528\u5DE5\u4F5C\u76EE\u5F55 ${root2}\uFF1A${error62 instanceof Error ? error62.message : String(error62)}`, `workspaceRoot=${root2}`);
34763
34908
  }
@@ -34776,6 +34921,8 @@ var T3Backend = class {
34776
34921
  thread: this.threadState(thread),
34777
34922
  runs: runs.map((entry) => entry.run),
34778
34923
  turnItems: thread.items.filter((entry) => typeof entry.item.runId !== "string" || kept.has(entry.item.runId)).map((entry) => entry.item),
34924
+ // The CLI sessions the runs ran in; the Hub offers a native fork only from a run with a strong one.
34925
+ providerThreads: this.providerThreads(thread),
34779
34926
  runtimeRequests: []
34780
34927
  }
34781
34928
  };
@@ -34823,7 +34970,7 @@ var T3Backend = class {
34823
34970
  case "provider.switch":
34824
34971
  return this.selectModel(command);
34825
34972
  case "thread.fork":
34826
- 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");
34973
+ return this.forkThread(command);
34827
34974
  case "runtime-request.respond":
34828
34975
  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)}`);
34829
34976
  default:
@@ -34980,7 +35127,7 @@ var T3Backend = class {
34980
35127
  async saveAttachments(thread, messageId, attachments) {
34981
35128
  if (!attachments.length) return "";
34982
35129
  const lines = [];
34983
- const directory = join25(this.config.dataDir, "hub", "attachments", thread.id.replace(/[^A-Za-z0-9_.-]/g, "_"), messageId.replace(/[^A-Za-z0-9_.-]/g, "_"));
35130
+ const directory = join26(this.config.dataDir, "hub", "attachments", thread.id.replace(/[^A-Za-z0-9_.-]/g, "_"), messageId.replace(/[^A-Za-z0-9_.-]/g, "_"));
34984
35131
  for (const [index, attachment] of attachments.entries()) {
34985
35132
  const name = (text4(attachment.name) || `attachment-${index + 1}`).replace(/[^\p{L}\p{N}_.-]/gu, "_").slice(0, 120);
34986
35133
  const dataUrl = text4(attachment.dataUrl);
@@ -34993,7 +35140,7 @@ var T3Backend = class {
34993
35140
  }
34994
35141
  try {
34995
35142
  await mkdir9(directory, { recursive: true, mode: 448 });
34996
- const path = join25(directory, `${index + 1}-${name}`);
35143
+ const path = join26(directory, `${index + 1}-${name}`);
34997
35144
  await writeFile11(path, bytes, { mode: 384 });
34998
35145
  lines.push(`- ${path}`);
34999
35146
  } catch (error62) {
@@ -35022,6 +35169,12 @@ ${lines.join("\n")}` : "";
35022
35169
  run2.status = "starting";
35023
35170
  this.emitRun(thread, cli, entry, "run.updated");
35024
35171
  }
35172
+ const fork = thread.nativeSessionId ? void 0 : thread.fork;
35173
+ const sessionId = thread.nativeSessionId || (fork && cli.cli === "claude" ? randomUUID5() : "");
35174
+ if (fork && cli.cli === "claude" && !claudeTranscriptExists(fork.sourceSessionId)) {
35175
+ this.onRunFinished(run2.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 });
35176
+ return;
35177
+ }
35025
35178
  void (async () => {
35026
35179
  const payload = RunStartPayloadSchema.parse({
35027
35180
  // Full access, always: no turn of this device ever waits for a confirmation.
@@ -35031,7 +35184,8 @@ ${lines.join("\n")}` : "";
35031
35184
  task_chain_id: thread.id,
35032
35185
  message_id: run2.userMessageId,
35033
35186
  prompt: entry.prompt ?? "",
35034
- session_id: thread.nativeSessionId,
35187
+ session_id: sessionId,
35188
+ ...fork ? { fork: { source_session_id: fork.sourceSessionId, keep_turns: fork.keepTurns } } : {},
35035
35189
  model: DEFAULT_MODEL_SENTINELS.has(model) ? "" : model,
35036
35190
  reasoning_effort: selectionEffort(thread.modelSelection),
35037
35191
  workdir: thread.workspaceRoot
@@ -35074,15 +35228,84 @@ ${lines.join("\n")}` : "";
35074
35228
  const found = this.runOf(runId);
35075
35229
  if (!found) return;
35076
35230
  const { thread, entry } = found;
35077
- if (report.session_id && report.session_id !== thread.nativeSessionId) {
35078
- thread.nativeSessionId = report.session_id;
35079
- this.store.touch(thread);
35231
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35232
+ if (report.pid) {
35233
+ entry.launched = true;
35234
+ if (entry.run.status === "starting") {
35235
+ entry.run.status = "running";
35236
+ entry.run.startedAt = (/* @__PURE__ */ new Date()).toISOString();
35237
+ this.emitRun(thread, this.cliOf(thread), entry, "run.updated");
35238
+ }
35080
35239
  }
35081
- if (report.pid && entry.run.status === "starting") {
35082
- entry.run.status = "running";
35083
- entry.run.startedAt = (/* @__PURE__ */ new Date()).toISOString();
35084
- this.emitRun(thread, this.cliOf(thread), entry, "run.updated");
35240
+ }
35241
+ /** The CLI named the session this turn runs in: the thread continues it, and the run points at it. */
35242
+ noteNativeSession(thread, entry, sessionId) {
35243
+ entry.nativeSessionId = sessionId;
35244
+ entry.run.providerThreadId = providerThreadId(thread.id, sessionId);
35245
+ if (thread.nativeSessionId !== sessionId) {
35246
+ thread.nativeSessionId = sessionId;
35247
+ delete thread.fork;
35085
35248
  }
35249
+ this.store.touch(thread);
35250
+ }
35251
+ providerThreads(thread) {
35252
+ const cli = this.cliOf(thread);
35253
+ const sessions = new Set(thread.runs.map((entry) => entry.nativeSessionId).filter((id) => Boolean(id)));
35254
+ return [...sessions].map((sessionId) => ({
35255
+ id: providerThreadId(thread.id, sessionId),
35256
+ threadId: thread.id,
35257
+ driver: cli.driver,
35258
+ providerInstanceId: cli.instanceId,
35259
+ nativeThreadRef: { strength: "strong", id: sessionId }
35260
+ }));
35261
+ }
35262
+ /**
35263
+ * `thread.fork`: a new thread on the same CLI and work directory whose first
35264
+ * turn continues a native copy of the source CLI session up to the chosen
35265
+ * run. The source thread is not touched. Only CLIs that can copy a session
35266
+ * are forked (Claude Code, Codex); the others are refused, never imitated.
35267
+ */
35268
+ forkThread(command) {
35269
+ const source = this.requireThread(command.sourceThreadId);
35270
+ const targetId = text4(command.targetThreadId);
35271
+ if (!targetId) throw rpcError(ERROR_TAGS.invalidCommand, "thread.fork \u7F3A\u5C11 targetThreadId");
35272
+ if (this.store.get(targetId)) return { threadId: targetId, created: false };
35273
+ const cli = this.cliOf(source);
35274
+ if (cli.cli !== "claude" && cli.cli !== "codex") {
35275
+ 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}`);
35276
+ }
35277
+ const point = record11(command.sourcePoint);
35278
+ const runId = text4(point.runId);
35279
+ const at = runId ? source.runs.find((entry) => entry.run.id === runId) : [...source.runs].reverse().find((entry) => entry.run.status === "completed");
35280
+ 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`);
35281
+ 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}`);
35282
+ 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`);
35283
+ const keepTurns = source.runs.filter((entry) => entry.launched && entry.nativeSessionId === at.nativeSessionId && entry.run.ordinal <= at.run.ordinal).length;
35284
+ const now = (/* @__PURE__ */ new Date()).toISOString();
35285
+ const thread = {
35286
+ v: 1,
35287
+ id: targetId,
35288
+ projectId: source.projectId,
35289
+ workspaceRoot: source.workspaceRoot,
35290
+ title: text4(command.title) || `${source.title}\uFF08\u5206\u53C9\uFF09`,
35291
+ cli: source.cli,
35292
+ modelSelection: record11(at.run.modelSelection).model ? record11(at.run.modelSelection) : source.modelSelection,
35293
+ runtimeMode: source.runtimeMode,
35294
+ interactionMode: source.interactionMode,
35295
+ createdAt: now,
35296
+ updatedAt: now,
35297
+ nativeSessionId: "",
35298
+ archived: false,
35299
+ queueHeld: false,
35300
+ seq: 0,
35301
+ nextItemOrdinal: 1,
35302
+ runs: [],
35303
+ items: [],
35304
+ fork: { sourceThreadId: source.id, sourceRunId: at.run.id, sourceSessionId: at.nativeSessionId, keepTurns }
35305
+ };
35306
+ this.store.put(thread);
35307
+ this.emitThread(thread, "thread.created");
35308
+ return { threadId: targetId, created: true, forkedFrom: { threadId: source.id, runId: at.run.id, keepTurns } };
35086
35309
  }
35087
35310
  onRunContent(runId, events) {
35088
35311
  const live = this.live.get(runId);
@@ -35126,7 +35349,7 @@ ${lines.join("\n")}` : "";
35126
35349
  this.dropLive(runId);
35127
35350
  return;
35128
35351
  }
35129
- if (report.session_id && report.session_id !== thread.nativeSessionId) thread.nativeSessionId = report.session_id;
35352
+ if (report.session_id) this.noteNativeSession(thread, entry, report.session_id);
35130
35353
  const outcome = report.status === "succeeded" ? "completed" : report.status === "cancelled" ? "interrupted" : "failed";
35131
35354
  const live = this.live.get(runId);
35132
35355
  if (live) {
@@ -35191,7 +35414,9 @@ ${lines.join("\n")}` : "";
35191
35414
  workspaceRoot: thread.workspaceRoot,
35192
35415
  createdAt: thread.createdAt,
35193
35416
  updatedAt: thread.updatedAt,
35194
- archivedAt: thread.archived ? thread.updatedAt : null
35417
+ archived: thread.archived,
35418
+ archivedAt: thread.archived ? thread.updatedAt : null,
35419
+ ...thread.fork ? { forkedFrom: { threadId: thread.fork.sourceThreadId, runId: thread.fork.sourceRunId } } : {}
35195
35420
  };
35196
35421
  }
35197
35422
  emitThread(thread, type) {
@@ -35220,7 +35445,7 @@ var HubRuntime = class {
35220
35445
  },
35221
35446
  backend: this.backend,
35222
35447
  appVersion: hubAppVersion(version2),
35223
- eventStatePath: join26(config2.dataDir, "hub-events.json"),
35448
+ eventStatePath: join27(config2.dataDir, "hub-events.json"),
35224
35449
  logger: this.logger
35225
35450
  });
35226
35451
  this.backend.attach({ event: (envelope) => this.link.publishEvent(envelope) });
@@ -35651,7 +35876,7 @@ async function runService(options = {}) {
35651
35876
  }
35652
35877
 
35653
35878
  // src/index.ts
35654
- var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join27(agentPackageRoot(), "scripts", "installation.cjs"));
35879
+ var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join28(agentPackageRoot(), "scripts", "installation.cjs"));
35655
35880
  async function run() {
35656
35881
  try {
35657
35882
  await runService();
@@ -35823,7 +36048,7 @@ async function update(args) {
35823
36048
  if (customConfig) process.env.TOC_OCRA_CONFIG = resolve9(customConfig);
35824
36049
  await ensureIdle();
35825
36050
  const npmPath = resolveCliCommand("npm");
35826
- const temporary = mkdtempSync(join27(tmpdir4(), "toc-ocra-update-"));
36051
+ const temporary = mkdtempSync(join28(tmpdir4(), "toc-ocra-update-"));
35827
36052
  try {
35828
36053
  const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
35829
36054
  if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -35850,7 +36075,7 @@ async function update(args) {
35850
36075
  }
35851
36076
  const archive = Buffer.concat(chunks);
35852
36077
  if (`sha512-${createHash6("sha512").update(archive).digest("base64")}` !== dist.integrity) throw new Error("\u8BBE\u5907\u4EE3\u7406\u5B89\u88C5\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u5347\u7EA7");
35853
- const archivePath = join27(temporary, "toc-ocra.tgz");
36078
+ const archivePath = join28(temporary, "toc-ocra.tgz");
35854
36079
  writeFileSync5(archivePath, archive, { mode: 384 });
35855
36080
  const npm = directLaunch2(npmPath, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath]);
35856
36081
  const install = spawnSync(npm.executable, npm.args, { stdio: "inherit", shell: false, windowsHide: true });
@@ -35860,7 +36085,7 @@ async function update(args) {
35860
36085
  return;
35861
36086
  }
35862
36087
  const previousVersion = agentVersion();
35863
- const current = await installShared(join27(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync8(defaultConfigPath()) });
36088
+ const current = await installShared(join28(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync8(defaultConfigPath()) });
35864
36089
  if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
35865
36090
  `);
35866
36091
  else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
@@ -35888,7 +36113,7 @@ async function main() {
35888
36113
  const selected = !shared || compareVersions2(agentVersion(), shared.version) > 0 ? await installShared(root2) : shared;
35889
36114
  const same = (a, b) => process.platform === "win32" ? resolve9(a).toLowerCase() === resolve9(b).toLowerCase() : resolve9(a) === resolve9(b);
35890
36115
  if (!same(selected.root, root2)) {
35891
- await import(pathToFileURL2(join27(selected.root, "dist", "cli", "cli.mjs")).href);
36116
+ await import(pathToFileURL2(join28(selected.root, "dist", "cli", "cli.mjs")).href);
35892
36117
  return;
35893
36118
  }
35894
36119
  }