toc-ocra 0.3.23 → 0.4.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.
Files changed (69) hide show
  1. package/README.md +43 -26
  2. package/dist/cli/cli.mjs +6278 -5980
  3. package/dist/service/agent.mjs +6784 -1840
  4. package/dist/src/config.d.ts +18 -22
  5. package/dist/src/config.js +66 -49
  6. package/dist/src/config.js.map +1 -1
  7. package/dist/src/hub/dpop.d.ts +61 -0
  8. package/dist/src/hub/dpop.js +131 -0
  9. package/dist/src/hub/dpop.js.map +1 -0
  10. package/dist/src/hub/event-store.d.ts +33 -0
  11. package/dist/src/hub/event-store.js +109 -0
  12. package/dist/src/hub/event-store.js.map +1 -0
  13. package/dist/src/hub/fs-list.d.ts +11 -0
  14. package/dist/src/hub/fs-list.js +40 -0
  15. package/dist/src/hub/fs-list.js.map +1 -0
  16. package/dist/src/hub/hub-link.d.ts +138 -0
  17. package/dist/src/hub/hub-link.js +616 -0
  18. package/dist/src/hub/hub-link.js.map +1 -0
  19. package/dist/src/hub/link-guard.d.ts +22 -0
  20. package/dist/src/hub/link-guard.js +37 -0
  21. package/dist/src/hub/link-guard.js.map +1 -0
  22. package/dist/src/hub/protocol.d.ts +59 -0
  23. package/dist/src/hub/protocol.js +40 -0
  24. package/dist/src/hub/protocol.js.map +1 -0
  25. package/dist/src/hub/proxy.d.ts +23 -0
  26. package/dist/src/hub/proxy.js +292 -0
  27. package/dist/src/hub/proxy.js.map +1 -0
  28. package/dist/src/index.js +84 -28
  29. package/dist/src/index.js.map +1 -1
  30. package/dist/src/providers/claude-quota.d.ts +9 -0
  31. package/dist/src/providers/claude-quota.js +168 -25
  32. package/dist/src/providers/claude-quota.js.map +1 -1
  33. package/dist/src/providers/tb-switch-control.d.ts +1 -1
  34. package/dist/src/runs/run-supervisor.d.ts +6 -0
  35. package/dist/src/runs/run-supervisor.js +2 -0
  36. package/dist/src/runs/run-supervisor.js.map +1 -1
  37. package/dist/src/runtime/agent-service.d.ts +3 -2
  38. package/dist/src/runtime/agent-service.js +20 -17
  39. package/dist/src/runtime/agent-service.js.map +1 -1
  40. package/dist/src/runtime/hub-runtime.d.ts +37 -0
  41. package/dist/src/runtime/hub-runtime.js +109 -0
  42. package/dist/src/runtime/hub-runtime.js.map +1 -0
  43. package/dist/src/t3/provider-catalog.d.ts +75 -0
  44. package/dist/src/t3/provider-catalog.js +145 -0
  45. package/dist/src/t3/provider-catalog.js.map +1 -0
  46. package/dist/src/t3/t3-backend.d.ts +86 -0
  47. package/dist/src/t3/t3-backend.js +604 -0
  48. package/dist/src/t3/t3-backend.js.map +1 -0
  49. package/dist/src/t3/thread-store.d.ts +81 -0
  50. package/dist/src/t3/thread-store.js +162 -0
  51. package/dist/src/t3/thread-store.js.map +1 -0
  52. package/dist/src/t3/turn-items.d.ts +39 -0
  53. package/dist/src/t3/turn-items.js +180 -0
  54. package/dist/src/t3/turn-items.js.map +1 -0
  55. package/dist/src/types/protocol.d.ts +1 -1
  56. package/package.json +4 -4
  57. package/scripts/service.mjs +3 -3
  58. package/dist/src/control/device-link.d.ts +0 -13
  59. package/dist/src/control/device-link.js +0 -113
  60. package/dist/src/control/device-link.js.map +0 -1
  61. package/dist/src/control/terminal-qr.d.ts +0 -1
  62. package/dist/src/control/terminal-qr.js +0 -27
  63. package/dist/src/control/terminal-qr.js.map +0 -1
  64. package/dist/src/runtime/agent-runtime.d.ts +0 -81
  65. package/dist/src/runtime/agent-runtime.js +0 -523
  66. package/dist/src/runtime/agent-runtime.js.map +0 -1
  67. package/dist/src/transport/gateway-client.d.ts +0 -53
  68. package/dist/src/transport/gateway-client.js +0 -138
  69. package/dist/src/transport/gateway-client.js.map +0 -1
@@ -0,0 +1,81 @@
1
+ import type { TurnItem } from './turn-items.js';
2
+ /**
3
+ * The device's own record of Hub threads: which CLI, model and work
4
+ * directory a thread is bound to, the CLI's native session to resume, and
5
+ * the thread's runs and turn items. It is what `snapshot` answers from, what
6
+ * a replay after the Hub's cursor re-emits, and what survives a restart.
7
+ *
8
+ * Files (0600, written atomically) under `<data dir>/hub/`:
9
+ * state.json reserved event sequence, known projects
10
+ * threads/<id>.json one thread
11
+ */
12
+ export type StoredRun = Record<string, unknown> & {
13
+ id: string;
14
+ ordinal: number;
15
+ status: string;
16
+ userMessageId: string;
17
+ requestedAt: string;
18
+ };
19
+ /** `seq`: sequence of the last event emitted for the entity (0: never emitted). */
20
+ export type RunEntry = {
21
+ seq: number;
22
+ run: StoredRun;
23
+ prompt?: string;
24
+ };
25
+ export type ItemEntry = {
26
+ seq: number;
27
+ item: TurnItem;
28
+ };
29
+ export type ThreadRecord = {
30
+ v: 1;
31
+ id: string;
32
+ projectId: string;
33
+ workspaceRoot: string;
34
+ title: string;
35
+ /** ocra CLI id; fixed when the thread is created. */
36
+ cli: string;
37
+ modelSelection: Record<string, unknown>;
38
+ runtimeMode: string;
39
+ interactionMode: string;
40
+ createdAt: string;
41
+ updatedAt: string;
42
+ /** The CLI's own session, continued by every later turn. */
43
+ nativeSessionId: string;
44
+ archived: boolean;
45
+ /** A stop asked to hold queued turns until the next message. */
46
+ queueHeld: boolean;
47
+ seq: number;
48
+ nextItemOrdinal: number;
49
+ runs: RunEntry[];
50
+ items: ItemEntry[];
51
+ };
52
+ export declare class ThreadStore {
53
+ private readonly onError;
54
+ private readonly root;
55
+ private readonly threadsDir;
56
+ private readonly statePath;
57
+ private readonly threads;
58
+ private projects;
59
+ private sequence;
60
+ private reserved;
61
+ private readonly timers;
62
+ constructor(dataDir: string, onError?: (message: string) => void);
63
+ /** The next device-global event sequence; never repeats across restarts. */
64
+ nextSequence(): number;
65
+ currentSequence(): number;
66
+ /** The Hub already stored events up to `cursor` for this device (another device package may have issued them). */
67
+ raiseSequence(cursor: number): void;
68
+ private reserve;
69
+ private saveState;
70
+ projectFor(workspaceRoot: string): string;
71
+ projectRoot(projectId: string): string | undefined;
72
+ get(threadId: string): ThreadRecord | undefined;
73
+ all(): ThreadRecord[];
74
+ put(thread: ThreadRecord): void;
75
+ remove(threadId: string): void;
76
+ /** Marks the thread changed; it is written shortly after (and on `flush`). */
77
+ touch(thread: ThreadRecord): void;
78
+ /** Synchronous write of everything pending (shutdown). */
79
+ flush(): void;
80
+ private trim;
81
+ }
@@ -0,0 +1,162 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { rename, writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ /** Items are kept for this many newest runs; older runs keep only their run record. */
6
+ const ITEM_RUNS_KEPT = 40;
7
+ const SEQUENCE_BLOCK = 500;
8
+ const SAVE_DEBOUNCE_MS = 800;
9
+ const safeId = (id) => /^[A-Za-z0-9_.-]{1,128}$/.test(id);
10
+ function writeAtomicSync(path, text) {
11
+ const temporary = `${path}.${process.pid}.tmp`;
12
+ writeFileSync(temporary, text, { encoding: 'utf8', mode: 0o600 });
13
+ renameSync(temporary, path);
14
+ }
15
+ export class ThreadStore {
16
+ onError;
17
+ root;
18
+ threadsDir;
19
+ statePath;
20
+ threads = new Map();
21
+ projects = {};
22
+ sequence = 0;
23
+ reserved = 0;
24
+ timers = new Map();
25
+ constructor(dataDir, onError = () => undefined) {
26
+ this.onError = onError;
27
+ this.root = join(dataDir, 'hub');
28
+ this.threadsDir = join(this.root, 'threads');
29
+ this.statePath = join(this.root, 'state.json');
30
+ mkdirSync(this.threadsDir, { recursive: true, mode: 0o700 });
31
+ try {
32
+ const state = JSON.parse(readFileSync(this.statePath, 'utf8'));
33
+ if (typeof state.reservedSequence === 'number' && Number.isFinite(state.reservedSequence))
34
+ this.reserved = state.reservedSequence;
35
+ if (state.projects && typeof state.projects === 'object')
36
+ this.projects = state.projects;
37
+ }
38
+ catch { /* first start */ }
39
+ // Start above everything a previous process may have issued without saving.
40
+ this.sequence = this.reserved;
41
+ for (const name of readdirSync(this.threadsDir)) {
42
+ if (!name.endsWith('.json'))
43
+ continue;
44
+ try {
45
+ const thread = JSON.parse(readFileSync(join(this.threadsDir, name), 'utf8'));
46
+ if (thread?.v === 1 && typeof thread.id === 'string' && Array.isArray(thread.runs) && Array.isArray(thread.items))
47
+ this.threads.set(thread.id, thread);
48
+ }
49
+ catch { /* an unreadable thread file is skipped, never fatal */ }
50
+ }
51
+ }
52
+ // ---- Sequence ----
53
+ /** The next device-global event sequence; never repeats across restarts. */
54
+ nextSequence() {
55
+ this.sequence += 1;
56
+ if (this.sequence > this.reserved)
57
+ this.reserve(this.sequence + SEQUENCE_BLOCK);
58
+ return this.sequence;
59
+ }
60
+ currentSequence() {
61
+ return this.sequence;
62
+ }
63
+ /** The Hub already stored events up to `cursor` for this device (another device package may have issued them). */
64
+ raiseSequence(cursor) {
65
+ if (!Number.isFinite(cursor) || cursor <= this.sequence)
66
+ return;
67
+ this.sequence = Math.floor(cursor);
68
+ this.reserve(this.sequence + SEQUENCE_BLOCK);
69
+ }
70
+ reserve(upTo) {
71
+ this.reserved = upTo;
72
+ this.saveState();
73
+ }
74
+ saveState() {
75
+ try {
76
+ writeAtomicSync(this.statePath, JSON.stringify({ v: 1, reservedSequence: this.reserved, projects: this.projects }));
77
+ }
78
+ catch (error) {
79
+ this.onError(error instanceof Error ? error.message : String(error));
80
+ }
81
+ }
82
+ // ---- Projects (a work directory the Hub knows by id) ----
83
+ projectFor(workspaceRoot) {
84
+ const id = `proj_${createHash('sha1').update(workspaceRoot).digest('hex').slice(0, 24)}`;
85
+ if (this.projects[id] !== workspaceRoot) {
86
+ this.projects[id] = workspaceRoot;
87
+ this.saveState();
88
+ }
89
+ return id;
90
+ }
91
+ projectRoot(projectId) {
92
+ return this.projects[projectId];
93
+ }
94
+ // ---- Threads ----
95
+ get(threadId) {
96
+ return this.threads.get(threadId);
97
+ }
98
+ all() {
99
+ return [...this.threads.values()];
100
+ }
101
+ put(thread) {
102
+ this.threads.set(thread.id, thread);
103
+ this.touch(thread);
104
+ }
105
+ remove(threadId) {
106
+ this.threads.delete(threadId);
107
+ const timer = this.timers.get(threadId);
108
+ if (timer) {
109
+ clearTimeout(timer);
110
+ this.timers.delete(threadId);
111
+ }
112
+ if (safeId(threadId))
113
+ rmSync(join(this.threadsDir, `${threadId}.json`), { force: true });
114
+ }
115
+ /** Marks the thread changed; it is written shortly after (and on `flush`). */
116
+ touch(thread) {
117
+ thread.updatedAt = new Date().toISOString();
118
+ if (this.timers.has(thread.id) || !safeId(thread.id))
119
+ return;
120
+ const timer = setTimeout(() => {
121
+ this.timers.delete(thread.id);
122
+ const current = this.threads.get(thread.id);
123
+ if (!current)
124
+ return;
125
+ this.trim(current);
126
+ const path = join(this.threadsDir, `${current.id}.json`);
127
+ const temporary = `${path}.${process.pid}.tmp`;
128
+ void writeFile(temporary, JSON.stringify(current), { encoding: 'utf8', mode: 0o600 })
129
+ .then(() => rename(temporary, path))
130
+ .catch((error) => this.onError(error instanceof Error ? error.message : String(error)));
131
+ }, SAVE_DEBOUNCE_MS);
132
+ timer.unref?.();
133
+ this.timers.set(thread.id, timer);
134
+ }
135
+ /** Synchronous write of everything pending (shutdown). */
136
+ flush() {
137
+ for (const [threadId, timer] of this.timers) {
138
+ clearTimeout(timer);
139
+ const thread = this.threads.get(threadId);
140
+ if (!thread)
141
+ continue;
142
+ this.trim(thread);
143
+ try {
144
+ writeAtomicSync(join(this.threadsDir, `${threadId}.json`), JSON.stringify(thread));
145
+ }
146
+ catch (error) {
147
+ this.onError(error instanceof Error ? error.message : String(error));
148
+ }
149
+ }
150
+ this.timers.clear();
151
+ // The exact position: the next start does not skip a block needlessly.
152
+ this.reserved = this.sequence;
153
+ this.saveState();
154
+ }
155
+ trim(thread) {
156
+ if (thread.runs.length <= ITEM_RUNS_KEPT)
157
+ return;
158
+ const kept = new Set(thread.runs.slice(-ITEM_RUNS_KEPT).map((entry) => entry.run.id));
159
+ thread.items = thread.items.filter((entry) => typeof entry.item.runId !== 'string' || kept.has(entry.item.runId));
160
+ }
161
+ }
162
+ //# sourceMappingURL=thread-store.js.map
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A;QACnB,uEAAuE;QACvE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAA;QAC7B,IAAI,CAAC,SAAS,EAAE,CAAA;IAClB,CAAC;IAEO,IAAI,CAAC,MAAoB;QAC/B,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,cAAc;YAAE,OAAM;QAChD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,cAAc,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAA;QACrF,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,QAAQ,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IACnH,CAAC;CACF"}
@@ -0,0 +1,39 @@
1
+ import type { ChatContentEvent } from '../providers/provider.js';
2
+ /**
3
+ * Maps ocra's turn content (the ACP-shaped chat events every driver emits:
4
+ * text / thinking deltas and whole items replaced by id) to the turn items
5
+ * the Hub projects from `turn-item.updated` events
6
+ * (`service/t3/projection.go`, echo_web `T3TurnItem`). An event always
7
+ * carries the whole item: the Hub and the web replace an item by id.
8
+ */
9
+ export type TurnItem = Record<string, unknown> & {
10
+ id: string;
11
+ type: string;
12
+ status: string;
13
+ ordinal: number;
14
+ };
15
+ export type ItemContext = {
16
+ threadId: string;
17
+ runId: string;
18
+ /** The next ordinal on the thread; called once per new item. */
19
+ nextOrdinal(): number;
20
+ };
21
+ /** Folds one run's content events into turn items; `apply` returns the items that changed. */
22
+ export declare class TurnItemFolder {
23
+ private readonly context;
24
+ private readonly items;
25
+ /** Per kind, the item id implicit deltas (without `item_id`) append to. */
26
+ private readonly open;
27
+ private autoSequence;
28
+ constructor(context: ItemContext);
29
+ all(): TurnItem[];
30
+ hasAssistantText(): boolean;
31
+ apply(event: ChatContentEvent): TurnItem | undefined;
32
+ /** Ends the run's items: nothing stays streaming or running. Returns the items that changed. */
33
+ finish(outcome: 'completed' | 'failed' | 'interrupted', at: string): TurnItem[];
34
+ /** An item this folder did not produce from content (the final answer, an error). */
35
+ add(key: string, type: string, fields: Record<string, unknown>, status?: string): TurnItem;
36
+ private upsert;
37
+ private touch;
38
+ private tool;
39
+ }
@@ -0,0 +1,180 @@
1
+ const MAX_TEXT = 200_000;
2
+ const MAX_OUTPUT = 16_000;
3
+ const MAX_DIFF = 24_000;
4
+ const clip = (text, max) => text.length > max ? `${text.slice(0, max)}…` : text;
5
+ const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
6
+ const text = (value) => typeof value === 'string' ? value : '';
7
+ const STATUS = { pending: 'pending', in_progress: 'running', completed: 'completed', failed: 'failed' };
8
+ /** Folds one run's content events into turn items; `apply` returns the items that changed. */
9
+ export class TurnItemFolder {
10
+ context;
11
+ items = new Map();
12
+ /** Per kind, the item id implicit deltas (without `item_id`) append to. */
13
+ open = new Map();
14
+ autoSequence = 0;
15
+ constructor(context) {
16
+ this.context = context;
17
+ }
18
+ all() {
19
+ return [...this.items.values()];
20
+ }
21
+ hasAssistantText() {
22
+ return this.all().some((item) => item.type === 'assistant_message' && text(item.text).trim() !== '');
23
+ }
24
+ apply(event) {
25
+ if (event.event === 'text_delta' || event.event === 'thought_delta') {
26
+ const kind = event.event === 'text_delta' ? 'assistant_message' : 'reasoning';
27
+ if (!event.text)
28
+ return undefined;
29
+ let key = event.item_id;
30
+ if (!key) {
31
+ key = this.open.get(kind);
32
+ if (!key) {
33
+ key = `auto:${kind === 'assistant_message' ? 'm' : 't'}${++this.autoSequence}`;
34
+ this.open.set(kind, key);
35
+ }
36
+ }
37
+ // A reply after thinking (or the reverse) starts a new implicit item next time.
38
+ this.open.delete(kind === 'assistant_message' ? 'reasoning' : 'assistant_message');
39
+ const item = this.upsert(key, kind, { streaming: true });
40
+ item.text = clip(text(item.text) + event.text, MAX_TEXT);
41
+ item.status = 'running';
42
+ return this.touch(item);
43
+ }
44
+ const source = record(event.item);
45
+ const key = text(source.itemId);
46
+ if (!key)
47
+ return undefined;
48
+ switch (source.type) {
49
+ case 'text':
50
+ case 'thought': {
51
+ const item = this.upsert(key, source.type === 'text' ? 'assistant_message' : 'reasoning', { streaming: true });
52
+ item.text = clip(text(source.text), MAX_TEXT);
53
+ item.status = 'running';
54
+ return this.touch(item);
55
+ }
56
+ case 'tool_call': return this.tool(key, source);
57
+ case 'plan': {
58
+ const item = this.upsert(key, 'todo_list', {});
59
+ item.steps = (Array.isArray(source.entries) ? source.entries : []).map(record).map((entry) => ({ step: text(entry.content), status: text(entry.status) || 'pending' }));
60
+ item.status = 'completed';
61
+ return this.touch(item);
62
+ }
63
+ case 'proposed_plan': {
64
+ const item = this.upsert(key, 'proposed_plan', { planId: text(source.turnId) || key });
65
+ item.markdown = clip(text(source.markdown), MAX_TEXT);
66
+ item.status = 'completed';
67
+ return this.touch(item);
68
+ }
69
+ default:
70
+ // Composer state (available commands, session config, usage) is not part of the timeline.
71
+ return undefined;
72
+ }
73
+ }
74
+ /** Ends the run's items: nothing stays streaming or running. Returns the items that changed. */
75
+ finish(outcome, at) {
76
+ const changed = [];
77
+ for (const item of this.items.values()) {
78
+ const streaming = item.streaming === true;
79
+ const running = item.status === 'running' || item.status === 'pending';
80
+ if (!streaming && !running)
81
+ continue;
82
+ if (streaming)
83
+ item.streaming = false;
84
+ if (running)
85
+ item.status = item.type === 'assistant_message' || item.type === 'reasoning' || outcome === 'completed' ? 'completed' : outcome;
86
+ item.completedAt = at;
87
+ item.updatedAt = at;
88
+ changed.push(item);
89
+ }
90
+ return changed;
91
+ }
92
+ /** An item this folder did not produce from content (the final answer, an error). */
93
+ add(key, type, fields, status = 'completed') {
94
+ const item = this.upsert(key, type, fields);
95
+ Object.assign(item, fields);
96
+ item.status = status;
97
+ if (status !== 'running')
98
+ item.completedAt = new Date().toISOString();
99
+ return this.touch(item);
100
+ }
101
+ upsert(key, type, initial) {
102
+ const existing = this.items.get(key);
103
+ if (existing && existing.type === type)
104
+ return existing;
105
+ const now = new Date().toISOString();
106
+ const item = {
107
+ id: `${this.context.runId}:${key}`,
108
+ threadId: this.context.threadId,
109
+ runId: this.context.runId,
110
+ type,
111
+ ordinal: existing?.ordinal ?? this.context.nextOrdinal(),
112
+ status: 'running',
113
+ startedAt: now,
114
+ updatedAt: now,
115
+ ...initial
116
+ };
117
+ this.items.set(key, item);
118
+ return item;
119
+ }
120
+ touch(item) {
121
+ item.updatedAt = new Date().toISOString();
122
+ return item;
123
+ }
124
+ tool(key, source) {
125
+ const kind = text(source.kind) || 'other';
126
+ const title = text(source.title);
127
+ const status = STATUS[text(source.status)] ?? 'running';
128
+ const content = (Array.isArray(source.content) ? source.content : []).map(record);
129
+ const command = content.find((part) => part.type === 'terminal_command');
130
+ const diffs = content.filter((part) => part.type === 'diff');
131
+ const locations = (Array.isArray(source.locations) ? source.locations : []).map(record).map((location) => text(location.path)).filter(Boolean);
132
+ let item;
133
+ if (kind === 'execute' || command) {
134
+ const output = content.find((part) => part.type === 'terminal_output');
135
+ const exitCode = record(output?.exitStatus).exitCode;
136
+ item = this.upsert(key, 'command_execution', {});
137
+ item.input = text(command?.command) || title;
138
+ if (output)
139
+ item.output = clip(text(output.output), MAX_OUTPUT);
140
+ if (typeof exitCode === 'number')
141
+ item.exitCode = exitCode;
142
+ }
143
+ else if (kind === 'edit') {
144
+ const paths = [...new Set([...diffs.map((part) => text(part.path)), ...locations].filter(Boolean))];
145
+ item = this.upsert(key, 'file_change', {});
146
+ item.fileName = paths[0] ?? title;
147
+ if (paths.length)
148
+ item.changes = paths.slice(0, 200).map((path) => ({ operation: 'edit', path }));
149
+ const first = diffs[0];
150
+ if (first) {
151
+ if (typeof first.oldText === 'string')
152
+ item.oldStr = clip(first.oldText, MAX_DIFF);
153
+ item.newStr = clip(text(first.newText), MAX_DIFF);
154
+ }
155
+ }
156
+ else if (kind === 'search') {
157
+ item = this.upsert(key, 'file_search', {});
158
+ item.pattern = title;
159
+ }
160
+ else if (kind === 'fetch') {
161
+ item = this.upsert(key, 'web_search', {});
162
+ item.patterns = title ? [title] : [];
163
+ }
164
+ else {
165
+ item = this.upsert(key, 'dynamic_tool', {});
166
+ item.toolName = title || kind;
167
+ if (source.rawInput !== undefined)
168
+ item.input = source.rawInput;
169
+ if (source.rawOutput !== undefined)
170
+ item.output = source.rawOutput;
171
+ }
172
+ if (title)
173
+ item.title = clip(title, 400);
174
+ item.status = status;
175
+ if (status === 'completed' || status === 'failed')
176
+ item.completedAt = new Date().toISOString();
177
+ return this.touch(item);
178
+ }
179
+ }
180
+ //# sourceMappingURL=turn-items.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn-items.js","sourceRoot":"","sources":["../../../src/t3/turn-items.ts"],"names":[],"mappings":"AAmBA,MAAM,QAAQ,GAAG,OAAO,CAAA;AACxB,MAAM,UAAU,GAAG,MAAM,CAAA;AACzB,MAAM,QAAQ,GAAG,MAAM,CAAA;AAEvB,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,GAAW,EAAU,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAA;AACvG,MAAM,MAAM,GAAG,CAAC,KAAc,EAA2B,EAAE,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,EAAE,CAAA;AAC/J,MAAM,IAAI,GAAG,CAAC,KAAc,EAAU,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,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ayload = z.infer<typeof CliQuotaPayloadSchema>;
280
280
  export declare const CliProviderControlPayloadSchema: z.ZodObject<{
281
281
  app: z.ZodEnum<{
282
- claude: "claude";
283
282
  codex: "codex";
283
+ claude: "claude";
284
284
  gemini: "gemini";
285
285
  }>;
286
286
  action: z.ZodEnum<{
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toc-ocra",
3
- "version": "0.3.23",
4
- "description": "Echo device agent: local CLI execution service plus its desktop plugin (heartbeat + long-poll, headless CLIs)",
3
+ "version": "0.4.0",
4
+ "description": "Echo device package without T3 Code: connects to the Echo Hub device protocol (/api/t3/device) and runs Claude Code, Codex and Antigravity locally; includes the desktop plugin",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "toc-ocra": "dist/cli/cli.mjs"
@@ -41,14 +41,14 @@
41
41
  "node": ">=20"
42
42
  },
43
43
  "dependencies": {
44
- "qrcode": "^1.5.4",
44
+ "ws": "^8.23.1",
45
45
  "zod": "^4.1.12"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@toc-starter/plugin-sdk": "file:../echo_web/packages/plugin-sdk",
49
49
  "@types/node": "^22.15.0",
50
- "@types/qrcode": "^1.5.6",
51
50
  "@types/react": "18.3.12",
51
+ "@types/ws": "^8.18.2",
52
52
  "esbuild": "0.28.2",
53
53
  "tsx": "^4.20.0",
54
54
  "typescript": "^5.8.0",
@@ -194,10 +194,10 @@ async function verifyStartedService() {
194
194
  if (responses.some(response => !response.ok)) throw new Error('无法读取本机服务状态')
195
195
  const [info, status] = await Promise.all(responses.map(response => response.json()))
196
196
  if (info.name !== SERVICE_NAME || info.version !== version) reason = '本机仍在运行另一版本的设备代理'
197
- else if (expected.token && (!info.paired || status.deviceId !== expected.deviceId)) reason = '后台服务未读取刚保存的设备凭据'
198
- else if (expected.token && expected.serverUrl && normalizeServer(status.serverUrl ?? '') !== normalizeServer(expected.serverUrl)) reason = '后台服务的服务器地址与配对地址不一致,请检查 TOC_OCRA_SERVER_URL'
197
+ else if (expected.hub && (!info.paired || status.deviceId !== expected.hub.environmentId)) reason = '后台服务未读取刚保存的设备凭据'
198
+ else if (expected.hub && normalizeServer(status.serverUrl ?? '') !== normalizeServer(expected.hub.serverUrl)) reason = '后台服务的服务器地址与配对地址不一致'
199
199
  else {
200
- process.stdout.write(info.paired ? `已确认后台服务读取服务器绑定:${status.serverUrl}\n` : '已确认本机服务启动,等待在「设备代理」插件中绑定服务器\n')
200
+ process.stdout.write(info.paired ? `已确认后台服务读取服务器绑定:${status.serverUrl}\n` : '已确认本机服务启动,尚未配对:运行 toc-ocra pair <配对码>\n')
201
201
  return
202
202
  }
203
203
  } catch (error) {
@@ -1,13 +0,0 @@
1
- import { type EnrollmentResult } from '../config.js';
2
- export type LinkOptions = {
3
- serverUrl?: string;
4
- configPath?: string;
5
- agentVersion: string;
6
- /** Accept the approver without asking (needed when stdin is not a terminal). */
7
- assumeYes?: boolean;
8
- out?: NodeJS.WriteStream;
9
- pollMs?: number;
10
- };
11
- /** The web page that approves `code`; the QR code carries it. */
12
- export declare function linkPageUrl(serverUrl: string, code: string): string;
13
- export declare function linkDevice(options: LinkOptions): Promise<EnrollmentResult>;