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.
@@ -0,0 +1,160 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ const MAX_SKILLS_PER_CLI = 500;
5
+ const MAX_SKILL_FILE_BYTES = 256 * 1024;
6
+ const MAX_TEXT = 1_000;
7
+ const claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim().split(process.platform === 'win32' ? ';' : ':')[0]?.trim() || join(homedir(), '.claude');
8
+ const codexHome = () => process.env.CODEX_HOME?.trim() || join(homedir(), '.codex');
9
+ export function skillRoots(cli, home = homedir()) {
10
+ const agents = { directory: join(home, '.agents', 'skills'), source: 'user', depth: 2 };
11
+ switch (cli) {
12
+ case 'claude': return [
13
+ { directory: join(claudeHome(), 'skills'), source: 'user', depth: 2 },
14
+ // Installed plugins keep their skills under <plugin>/skills/<name>/SKILL.md, several levels down.
15
+ { directory: join(claudeHome(), 'plugins'), source: 'plugin', depth: 7 }
16
+ ];
17
+ case 'codex': return [
18
+ // Bundled skills live in skills/.system/<name>.
19
+ { directory: join(codexHome(), 'skills'), source: 'user', depth: 3 },
20
+ { directory: join(codexHome(), 'plugins'), source: 'plugin', depth: 7 },
21
+ agents
22
+ ];
23
+ case 'antigravity': return [
24
+ { directory: join(home, '.gemini', 'antigravity', 'skills'), source: 'user', depth: 2 },
25
+ { directory: join(home, '.gemini', 'antigravity-cli', 'skills'), source: 'user', depth: 2 },
26
+ agents
27
+ ];
28
+ }
29
+ }
30
+ const unquote = (value) => {
31
+ const trimmed = value.trim();
32
+ if (trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
33
+ const inner = trimmed.slice(1, -1);
34
+ return trimmed.startsWith('"') ? inner.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\\\/g, '\\') : inner.replace(/''/g, "'");
35
+ }
36
+ return trimmed;
37
+ };
38
+ /**
39
+ * The flat string values of a small YAML document, keyed by dotted path
40
+ * (`description`, `metadata.short-description`, `interface.display_name`).
41
+ * Enough for skill metadata: scalars, quoted strings and `|` / `>` blocks;
42
+ * lists and anything deeper than it understands are skipped.
43
+ */
44
+ export function yamlScalars(source) {
45
+ const out = {};
46
+ const lines = source.split(/\r?\n/);
47
+ const parents = [];
48
+ for (let index = 0; index < lines.length; index++) {
49
+ const line = lines[index];
50
+ if (!line.trim() || line.trimStart().startsWith('#') || line.trimStart().startsWith('- '))
51
+ continue;
52
+ const match = /^(\s*)([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line);
53
+ if (!match)
54
+ continue;
55
+ const indent = match[1].length;
56
+ while (parents.length && parents[parents.length - 1].indent >= indent)
57
+ parents.pop();
58
+ const path = [...parents.map((parent) => parent.key), match[2]].join('.');
59
+ let value = match[3].replace(/\s+#.*$/, '');
60
+ if (value === '') {
61
+ parents.push({ indent, key: match[2] });
62
+ continue;
63
+ }
64
+ if (/^[|>][+-]?$/.test(value)) {
65
+ const folded = value.startsWith('>');
66
+ const block = [];
67
+ while (index + 1 < lines.length && (!lines[index + 1].trim() || lines[index + 1].length - lines[index + 1].trimStart().length > indent)) {
68
+ block.push(lines[++index].trim());
69
+ }
70
+ value = block.join(folded ? ' ' : '\n').trim();
71
+ }
72
+ else
73
+ value = unquote(value);
74
+ out[path] = value;
75
+ }
76
+ return out;
77
+ }
78
+ /** The front matter of a `SKILL.md` (empty when the file has none). */
79
+ export function skillFrontMatter(markdown) {
80
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);
81
+ return match ? yamlScalars(match[1]) : {};
82
+ }
83
+ const clip = (value) => {
84
+ const flat = value?.replace(/\s+/g, ' ').trim();
85
+ return flat ? (flat.length > MAX_TEXT ? `${flat.slice(0, MAX_TEXT)}…` : flat) : undefined;
86
+ };
87
+ async function readSmall(path) {
88
+ try {
89
+ const info = await stat(path);
90
+ if (!info.isFile() || info.size > MAX_SKILL_FILE_BYTES)
91
+ return undefined;
92
+ return await readFile(path, 'utf8');
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ async function readSkill(directory, folder, source) {
99
+ const markdown = await readSmall(join(directory, 'SKILL.md'));
100
+ if (markdown === undefined)
101
+ return undefined;
102
+ const front = skillFrontMatter(markdown);
103
+ const openai = yamlScalars((await readSmall(join(directory, 'agents', 'openai.yaml'))) ?? '');
104
+ const name = (front.name || folder).trim();
105
+ if (!name)
106
+ return undefined;
107
+ const displayName = clip(openai['interface.display_name'] ?? front['metadata.display-name'] ?? front['metadata.display_name'] ?? front['display-name'] ?? front.display_name);
108
+ const description = clip(front.description);
109
+ const shortDescription = clip(openai['interface.short_description'] ?? front['metadata.short-description'] ?? front['metadata.short_description']);
110
+ return {
111
+ name,
112
+ ...(displayName ? { displayName } : {}),
113
+ ...(description ? { description } : {}),
114
+ ...(shortDescription ? { shortDescription } : {}),
115
+ path: join(directory, 'SKILL.md'),
116
+ source,
117
+ enabled: true,
118
+ userInvocable: true
119
+ };
120
+ }
121
+ async function scan(root, found) {
122
+ const walk = async (directory, folder, depth, source) => {
123
+ if (found.size >= MAX_SKILLS_PER_CLI)
124
+ return;
125
+ let entries;
126
+ try {
127
+ entries = await readdir(directory, { withFileTypes: true });
128
+ }
129
+ catch {
130
+ return;
131
+ }
132
+ if (entries.some((entry) => entry.name === 'SKILL.md')) {
133
+ const skill = await readSkill(directory, folder, source);
134
+ // The first root that names a skill wins (user before plugin).
135
+ if (skill && !found.has(skill.name))
136
+ found.set(skill.name, skill);
137
+ return;
138
+ }
139
+ if (depth <= 0)
140
+ return;
141
+ for (const entry of entries) {
142
+ if (entry.name === 'node_modules' || entry.name === '.git')
143
+ continue;
144
+ // Follow links: skills are often symlinked into the skills directory.
145
+ const isDirectory = entry.isDirectory() || (entry.isSymbolicLink() && await stat(join(directory, entry.name)).then((info) => info.isDirectory(), () => false));
146
+ if (!isDirectory)
147
+ continue;
148
+ await walk(join(directory, entry.name), entry.name, depth - 1, entry.name === '.system' ? 'system' : source);
149
+ }
150
+ };
151
+ await walk(root.directory, '', root.depth, root.source);
152
+ }
153
+ /** Every skill of one CLI, sorted by name. Unreadable directories count as empty. */
154
+ export async function readCliSkills(cli, home = homedir()) {
155
+ const found = new Map();
156
+ for (const root of skillRoots(cli, home))
157
+ await scan(root, found);
158
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
159
+ }
160
+ //# sourceMappingURL=skills.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skills.js","sourceRoot":"","sources":["../../../src/t3/skills.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAA;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AA2ChC,MAAM,kBAAkB,GAAG,GAAG,CAAA;AAC9B,MAAM,oBAAoB,GAAG,GAAG,GAAG,IAAI,CAAA;AACvC,MAAM,QAAQ,GAAG,KAAK,CAAA;AAEtB,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;AACvJ,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,QAAQ,CAAC,CAAA;AAEnF,MAAM,UAAU,UAAU,CAAC,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@@ export declare class T3Backend implements DeviceBackend {
18
18
  private readonly live;
19
19
  /** Run id → thread id for every run this process started. */
20
20
  private readonly runThreads;
21
+ /**
22
+ * Runs already reported as interrupted whose CLI process tree is still being
23
+ * ended in the background (run id → release timer). The thread starts no
24
+ * other turn until the supervisor confirms the process is gone.
25
+ */
26
+ private readonly draining;
21
27
  private publisher;
22
28
  constructor(config: AgentConfig, logger: DiagnosticLogger);
23
29
  /** Where events go. Until the link attaches (and while it is down) the link buffers them itself. */
@@ -68,9 +74,28 @@ export declare class T3Backend implements DeviceBackend {
68
74
  private saveAttachments;
69
75
  private launch;
70
76
  private startNextQueued;
77
+ /**
78
+ * `run.interrupt`. The run is reported as interrupted and the command is
79
+ * answered at once; ending the CLI's process tree (a polite signal, a grace
80
+ * period, then a forced kill; `taskkill` on Windows) goes on in the
81
+ * background. The report used to wait for the process to exit and its
82
+ * output pipes to close, so a CLI slow to die kept the page on "running".
83
+ */
71
84
  private interruptRun;
85
+ /** The stopped run's process is gone (or was never there): the thread may run its next turn. */
86
+ private releaseDrain;
72
87
  private runOf;
73
88
  private onRunStarted;
89
+ /** The CLI named the session this turn runs in: the thread continues it, and the run points at it. */
90
+ private noteNativeSession;
91
+ private providerThreads;
92
+ /**
93
+ * `thread.fork`: a new thread on the same CLI and work directory whose first
94
+ * turn continues a native copy of the source CLI session up to the chosen
95
+ * run. The source thread is not touched. Only CLIs that can copy a session
96
+ * are forked (Claude Code, Codex); the others are refused, never imitated.
97
+ */
98
+ private forkThread;
74
99
  private onRunContent;
75
100
  private flushItems;
76
101
  private dropLive;
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { basename, join, resolve } from 'node:path';
5
5
  import { addAllowedRoot } from '../config.js';
6
6
  import { ERROR_TAGS, rpcError } from '../hub/protocol.js';
7
+ import { claudeTranscriptExists } from '../providers/cli/claude.js';
7
8
  import { OrphanRegistry } from '../runs/orphan-registry.js';
8
9
  import { RunSupervisor } from '../runs/run-supervisor.js';
9
10
  import { RunStartPayloadSchema } from '../types/protocol.js';
@@ -34,9 +35,12 @@ const TERMINAL = new Set(['completed', 'failed', 'interrupted', 'cancelled']);
34
35
  const ITEM_FLUSH_MS = 200;
35
36
  /** A thread snapshot carries this many newest runs with their items. */
36
37
  const SNAPSHOT_RUNS = 30;
38
+ /** A stopped run's process is force-killed within seconds; past this the thread stops waiting for it. */
39
+ const DRAIN_TIMEOUT_MS = 15_000;
37
40
  const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
38
41
  /** Model slug meaning "the CLI's own default". */
39
42
  const DEFAULT_MODEL_SENTINELS = new Set(['antigravity-default', 'default']);
43
+ const providerThreadId = (threadId, sessionId) => `${threadId}:${sessionId}`;
40
44
  const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
41
45
  const text = (value) => typeof value === 'string' ? value : '';
42
46
  /** The reasoning level of a model selection (`options` is a list of `{id, value}` or a map). */
@@ -65,6 +69,12 @@ export class T3Backend {
65
69
  live = new Map();
66
70
  /** Run id → thread id for every run this process started. */
67
71
  runThreads = new Map();
72
+ /**
73
+ * Runs already reported as interrupted whose CLI process tree is still being
74
+ * ended in the background (run id → release timer). The thread starts no
75
+ * other turn until the supervisor confirms the process is gone.
76
+ */
77
+ draining = new Map();
68
78
  publisher;
69
79
  constructor(config, logger) {
70
80
  this.config = config;
@@ -108,6 +118,9 @@ export class T3Backend {
108
118
  for (const live of this.live.values())
109
119
  if (live.timer)
110
120
  clearTimeout(live.timer);
121
+ for (const timer of this.draining.values())
122
+ clearTimeout(timer);
123
+ this.draining.clear();
111
124
  this.store.flush();
112
125
  }
113
126
  activeRuns() {
@@ -159,6 +172,8 @@ export class T3Backend {
159
172
  thread: this.threadState(thread),
160
173
  runs: runs.map((entry) => entry.run),
161
174
  turnItems: thread.items.filter((entry) => typeof entry.item.runId !== 'string' || kept.has(entry.item.runId)).map((entry) => entry.item),
175
+ // The CLI sessions the runs ran in; the Hub offers a native fork only from a run with a strong one.
176
+ providerThreads: this.providerThreads(thread),
162
177
  runtimeRequests: []
163
178
  }
164
179
  };
@@ -199,8 +214,7 @@ export class T3Backend {
199
214
  case 'thread.metadata.update': return this.renameThread(command);
200
215
  case 'thread.model-selection.set':
201
216
  case 'provider.switch': return this.selectModel(command);
202
- case 'thread.fork':
203
- throw rpcError(ERROR_TAGS.forkUnsupported, 'ocra 设备包暂不支持会话分叉,请新建会话继续', 'command=thread.fork');
217
+ case 'thread.fork': return this.forkThread(command);
204
218
  case 'runtime-request.respond':
205
219
  // Turns run with full access and never wait for the user.
206
220
  throw rpcError('RuntimeRequestNotFound', '这台设备以完全访问模式运行,没有等待确认的请求', `requestId=${text(command.requestId)}`);
@@ -324,7 +338,7 @@ export class T3Backend {
324
338
  const prompt = body + await this.saveAttachments(thread, messageId, attachments);
325
339
  const now = new Date().toISOString();
326
340
  const runId = randomUUID();
327
- const busy = thread.runs.some((entry) => ACTIVE.has(entry.run.status) || entry.run.status === 'queued');
341
+ const busy = thread.runs.some((entry) => ACTIVE.has(entry.run.status) || entry.run.status === 'queued' || this.draining.has(entry.run.id));
328
342
  const run = {
329
343
  id: runId,
330
344
  threadId: thread.id,
@@ -400,6 +414,16 @@ export class T3Backend {
400
414
  run.status = 'starting';
401
415
  this.emitRun(thread, cli, entry, 'run.updated');
402
416
  }
417
+ // A forked thread's first turn makes the CLI copy the source session (Claude:
418
+ // `--resume <source> --fork-session` under a new id; Codex: app-server
419
+ // `thread/fork`, which needs no id yet). Later turns resume the copy.
420
+ const fork = thread.nativeSessionId ? undefined : thread.fork;
421
+ const sessionId = thread.nativeSessionId || (fork && cli.cli === 'claude' ? randomUUID() : '');
422
+ // Without the source there is nothing to copy; a fresh session must never pass for a fork.
423
+ if (fork && cli.cli === 'claude' && !claudeTranscriptExists(fork.sourceSessionId)) {
424
+ this.onRunFinished(run.id, { status: 'failed', error: '原会话在这台设备上已经不存在(可能被清理或换了设备),无法分叉', failure_kind: 'sessionMissing', duration_ms: 0 });
425
+ return;
426
+ }
403
427
  void (async () => {
404
428
  const payload = RunStartPayloadSchema.parse({
405
429
  // Full access, always: no turn of this device ever waits for a confirmation.
@@ -409,7 +433,8 @@ export class T3Backend {
409
433
  task_chain_id: thread.id,
410
434
  message_id: run.userMessageId,
411
435
  prompt: entry.prompt ?? '',
412
- session_id: thread.nativeSessionId,
436
+ session_id: sessionId,
437
+ ...(fork ? { fork: { source_session_id: fork.sourceSessionId, keep_turns: fork.keepTurns } } : {}),
413
438
  model: DEFAULT_MODEL_SENTINELS.has(model) ? '' : model,
414
439
  reasoning_effort: selectionEffort(thread.modelSelection),
415
440
  workdir: thread.workspaceRoot
@@ -422,13 +447,21 @@ export class T3Backend {
422
447
  });
423
448
  }
424
449
  startNextQueued(thread) {
425
- if (thread.queueHeld || thread.runs.some((entry) => ACTIVE.has(entry.run.status)))
450
+ // A stopped turn whose CLI process is still exiting holds the CLI session: wait for it.
451
+ if (thread.queueHeld || thread.runs.some((entry) => ACTIVE.has(entry.run.status) || this.draining.has(entry.run.id)))
426
452
  return;
427
453
  const next = thread.runs.find((entry) => entry.run.status === 'queued');
428
454
  if (next)
429
455
  this.launch(thread, next);
430
456
  }
431
- async interruptRun(command) {
457
+ /**
458
+ * `run.interrupt`. The run is reported as interrupted and the command is
459
+ * answered at once; ending the CLI's process tree (a polite signal, a grace
460
+ * period, then a forced kill; `taskkill` on Windows) goes on in the
461
+ * background. The report used to wait for the process to exit and its
462
+ * output pipes to close, so a CLI slow to die kept the page on "running".
463
+ */
464
+ interruptRun(command) {
432
465
  const thread = this.requireThread(command.threadId);
433
466
  const wanted = text(command.runId);
434
467
  const entry = wanted
@@ -444,12 +477,34 @@ export class T3Backend {
444
477
  this.closeRun(thread, entry, 'interrupted', '');
445
478
  return { interrupted: true };
446
479
  }
447
- const stopping = await this.supervisor.cancel(entry.run.id);
448
- // Not known to the supervisor (it never started, or just ended): close it here.
449
- if (!stopping && !TERMINAL.has(entry.run.status))
450
- this.closeRun(thread, entry, 'interrupted', '');
480
+ const runId = entry.run.id;
481
+ const live = this.live.get(runId);
482
+ if (live) {
483
+ for (const item of live.folder.finish('interrupted', new Date().toISOString()))
484
+ live.dirty.add(item);
485
+ this.flushItems(runId);
486
+ }
487
+ this.draining.set(runId, setTimeout(() => {
488
+ this.logger.warn('hub-run-stop-unconfirmed', { runId, seconds: DRAIN_TIMEOUT_MS / 1000 });
489
+ this.releaseDrain(runId);
490
+ }, DRAIN_TIMEOUT_MS));
491
+ this.closeRun(thread, entry, 'interrupted', '');
492
+ // Not known to the supervisor (it never started, or just ended): nothing to wait for.
493
+ void this.supervisor.cancel(runId).then((stopping) => { if (!stopping)
494
+ this.releaseDrain(runId); }, () => this.releaseDrain(runId));
451
495
  return { interrupted: true };
452
496
  }
497
+ /** The stopped run's process is gone (or was never there): the thread may run its next turn. */
498
+ releaseDrain(runId) {
499
+ const timer = this.draining.get(runId);
500
+ if (timer === undefined)
501
+ return;
502
+ clearTimeout(timer);
503
+ this.draining.delete(runId);
504
+ const thread = this.store.get(this.runThreads.get(runId) ?? '');
505
+ if (thread)
506
+ this.startNextQueued(thread);
507
+ }
453
508
  // ---- Run reports from the supervisor ----
454
509
  runOf(runId) {
455
510
  const threadId = this.runThreads.get(runId);
@@ -462,15 +517,87 @@ export class T3Backend {
462
517
  if (!found)
463
518
  return;
464
519
  const { thread, entry } = found;
465
- if (report.session_id && report.session_id !== thread.nativeSessionId) {
466
- thread.nativeSessionId = report.session_id;
467
- this.store.touch(thread);
520
+ if (report.session_id)
521
+ this.noteNativeSession(thread, entry, report.session_id);
522
+ if (report.pid) {
523
+ entry.launched = true;
524
+ // Stopped while it was still starting: the process that just appeared is ended too.
525
+ if (this.draining.has(runId))
526
+ void this.supervisor.cancel(runId).catch(() => false);
527
+ if (entry.run.status === 'starting') {
528
+ entry.run.status = 'running';
529
+ entry.run.startedAt = new Date().toISOString();
530
+ this.emitRun(thread, this.cliOf(thread), entry, 'run.updated');
531
+ }
468
532
  }
469
- if (report.pid && entry.run.status === 'starting') {
470
- entry.run.status = 'running';
471
- entry.run.startedAt = new Date().toISOString();
472
- this.emitRun(thread, this.cliOf(thread), entry, 'run.updated');
533
+ }
534
+ /** The CLI named the session this turn runs in: the thread continues it, and the run points at it. */
535
+ noteNativeSession(thread, entry, sessionId) {
536
+ entry.nativeSessionId = sessionId;
537
+ entry.run.providerThreadId = providerThreadId(thread.id, sessionId);
538
+ if (thread.nativeSessionId !== sessionId) {
539
+ thread.nativeSessionId = sessionId;
540
+ // The CLI's own copy exists now; the fork is done.
541
+ delete thread.fork;
542
+ }
543
+ this.store.touch(thread);
544
+ }
545
+ providerThreads(thread) {
546
+ const cli = this.cliOf(thread);
547
+ const sessions = new Set(thread.runs.map((entry) => entry.nativeSessionId).filter((id) => Boolean(id)));
548
+ return [...sessions].map((sessionId) => ({
549
+ id: providerThreadId(thread.id, sessionId),
550
+ threadId: thread.id,
551
+ driver: cli.driver,
552
+ providerInstanceId: cli.instanceId,
553
+ nativeThreadRef: { strength: 'strong', id: sessionId }
554
+ }));
555
+ }
556
+ /**
557
+ * `thread.fork`: a new thread on the same CLI and work directory whose first
558
+ * turn continues a native copy of the source CLI session up to the chosen
559
+ * run. The source thread is not touched. Only CLIs that can copy a session
560
+ * are forked (Claude Code, Codex); the others are refused, never imitated.
561
+ */
562
+ forkThread(command) {
563
+ const source = this.requireThread(command.sourceThreadId);
564
+ const targetId = text(command.targetThreadId);
565
+ if (!targetId)
566
+ throw rpcError(ERROR_TAGS.invalidCommand, 'thread.fork 缺少 targetThreadId');
567
+ if (this.store.get(targetId))
568
+ return { threadId: targetId, created: false };
569
+ const cli = this.cliOf(source);
570
+ if (cli.cli !== 'claude' && cli.cli !== 'codex') {
571
+ throw rpcError(ERROR_TAGS.forkUnsupported, `${cli.displayName} 暂不支持分叉,请新建会话继续`, `thread.fork driver=${cli.driver}`);
473
572
  }
573
+ const point = record(command.sourcePoint);
574
+ const runId = text(point.runId);
575
+ const at = runId
576
+ ? source.runs.find((entry) => entry.run.id === runId)
577
+ : [...source.runs].reverse().find((entry) => entry.run.status === 'completed');
578
+ if (!at)
579
+ throw rpcError(ERROR_TAGS.forkUnsupported, '设备上找不到要分叉的这一轮', `thread.fork run ${runId || '(latest)'} not found`);
580
+ if (!TERMINAL.has(at.run.status))
581
+ throw rpcError(ERROR_TAGS.forkUnsupported, '这一轮还在运行(in-progress),不能分叉,请等它完成后再试', `run ${at.run.id} status=${at.run.status}`);
582
+ if (!at.nativeSessionId)
583
+ throw rpcError(ERROR_TAGS.forkUnsupported, `这一轮没有 ${cli.displayName} 的原生会话,无法分叉,请选择其他轮次`, `run ${at.run.id} has no native session`);
584
+ // Turns of that CLI session up to the chosen run, in the CLI's own count:
585
+ // every turn whose process started is one prompt in the CLI's history.
586
+ const keepTurns = source.runs.filter((entry) => entry.launched && entry.nativeSessionId === at.nativeSessionId && entry.run.ordinal <= at.run.ordinal).length;
587
+ const now = new Date().toISOString();
588
+ const thread = {
589
+ v: 1, id: targetId, projectId: source.projectId, workspaceRoot: source.workspaceRoot,
590
+ title: text(command.title) || `${source.title}(分叉)`,
591
+ cli: source.cli,
592
+ modelSelection: record(at.run.modelSelection).model ? record(at.run.modelSelection) : source.modelSelection,
593
+ runtimeMode: source.runtimeMode, interactionMode: source.interactionMode,
594
+ createdAt: now, updatedAt: now,
595
+ nativeSessionId: '', archived: false, queueHeld: false, seq: 0, nextItemOrdinal: 1, runs: [], items: [],
596
+ fork: { sourceThreadId: source.id, sourceRunId: at.run.id, sourceSessionId: at.nativeSessionId, keepTurns }
597
+ };
598
+ this.store.put(thread);
599
+ this.emitThread(thread, 'thread.created');
600
+ return { threadId: targetId, created: true, forkedFrom: { threadId: source.id, runId: at.run.id, keepTurns } };
474
601
  }
475
602
  onRunContent(runId, events) {
476
603
  const live = this.live.get(runId);
@@ -517,11 +644,16 @@ export class T3Backend {
517
644
  }
518
645
  const { thread, entry } = found;
519
646
  if (TERMINAL.has(entry.run.status)) {
647
+ // Already reported (a stopped run whose process has now exited): never a second
648
+ // end event, but the CLI session it named is still the one the thread continues.
649
+ if (report.session_id)
650
+ this.noteNativeSession(thread, entry, report.session_id);
520
651
  this.dropLive(runId);
652
+ this.releaseDrain(runId);
521
653
  return;
522
654
  }
523
- if (report.session_id && report.session_id !== thread.nativeSessionId)
524
- thread.nativeSessionId = report.session_id;
655
+ if (report.session_id)
656
+ this.noteNativeSession(thread, entry, report.session_id);
525
657
  const outcome = report.status === 'succeeded' ? 'completed' : report.status === 'cancelled' ? 'interrupted' : 'failed';
526
658
  const live = this.live.get(runId);
527
659
  if (live) {
@@ -593,7 +725,9 @@ export class T3Backend {
593
725
  workspaceRoot: thread.workspaceRoot,
594
726
  createdAt: thread.createdAt,
595
727
  updatedAt: thread.updatedAt,
596
- archivedAt: thread.archived ? thread.updatedAt : null
728
+ archived: thread.archived,
729
+ archivedAt: thread.archived ? thread.updatedAt : null,
730
+ ...(thread.fork ? { forkedFrom: { threadId: thread.fork.sourceThreadId, runId: thread.fork.sourceRunId } } : {})
597
731
  };
598
732
  }
599
733
  emitThread(thread, type) {