@oh-my-pi-zen/pi-wire 16.3.6-zen.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,40 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [16.3.0] - 2026-07-02
6
+
7
+ ### Breaking Changes
8
+
9
+ - Upgraded the collaboration protocol to version 3. Guests using version 2 will now be rejected during the handshake with a protocol-mismatch error.
10
+
11
+ ### Added
12
+
13
+ - Added support for interactive UI request and response frames, enabling browser guests to respond to prompts initiated by the host.
14
+
15
+ ## [16.1.8] - 2026-06-20
16
+
17
+ ### Breaking Changes
18
+
19
+ - Bumped `COLLAB_PROTO` to `2`. The `welcome` host frame now carries metadata only (`header`, `state`, `agents`, `entryCount`, optional `readOnly`) — the transcript moves to a new `snapshot-chunk` host frame (`{ entries: SessionEntry[]; final: boolean }`) sent immediately after the welcome. Hosts split large snapshots into multiple chunks; the last chunk carries `final: true`. Old guests speaking proto v1 are rejected with the existing protocol-mismatch error. ([#3144](https://github.com/cagedbird043/oh-my-pi-zen/issues/3144))
20
+
21
+ ## [15.12.4] - 2026-06-13
22
+
23
+ ### Changed
24
+
25
+ - Changed `WireModel.contextWindow` and `ContextUsage.contextWindow` to `number | null` to allow representing unavailable context-window values
26
+
27
+ ## [15.12.0] - 2026-06-12
28
+
29
+ ### Added
30
+
31
+ - Added `readOnly` flags to participant and session payload types to indicate when a guest is connected via a read-only (view) link
32
+ - Added `writeToken` to `GuestFrame` hello payloads and parsed collaboration links so full-access links can carry and expose a write-capability token
33
+ - Added `ROOM_KEY_BYTES` and `WRITE_TOKEN_BYTES` constants for room key and write-token sizing in the wire protocol
34
+ - Added `DEFAULT_SHARE_URL` (`https://my.omp.sh/s`), the default share viewer/upload base for `/share` links
35
+
36
+ ## [15.11.8] - 2026-06-12
37
+
38
+ ### Added
39
+
40
+ - Added shared collab live-session wire contracts for the host CLI and browser guest client.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @oh-my-pi-zen/pi-wire
2
+
3
+ Shared TypeScript wire contracts for omp collab live sessions.
4
+
5
+ The package contains only JSON-safe protocol shapes and constants. It has no runtime dependencies and is consumed by both the host CLI (`@oh-my-pi-zen/pi-coding-agent`) and browser guest (`@oh-my-pi-zen/collab-web`).
6
+
7
+ ## Exports
8
+
9
+ ```ts
10
+ import type { GuestFrame, HostFrame, SessionEntry } from "@oh-my-pi-zen/pi-wire";
11
+ import { COLLAB_PROTO, DEFAULT_RELAY_URL, ENVELOPE_HEADER_LENGTH } from "@oh-my-pi-zen/pi-wire";
12
+ ```
13
+
14
+ Key groups:
15
+
16
+ - message and transcript entry shapes rendered by collab guests,
17
+ - live agent event and task-subagent bus payload shapes,
18
+ - `GuestFrame`, `HostFrame`, and `WireFrame` unions for AES-GCM sealed payloads,
19
+ - relay control TEXT messages,
20
+ - link/envelope constants shared by host, guest, and local relay code.
21
+
22
+ ## Protocol boundary
23
+
24
+ `pi-wire` does not encode, decode, validate, encrypt, or route frames. It defines the shared contract used at those boundaries:
25
+
26
+ 1. callers build a `GuestFrame` or `HostFrame`,
27
+ 2. transport code serializes it as JSON inside an encrypted payload,
28
+ 3. relay code routes opaque envelopes using the plaintext peer-id prefix,
29
+ 4. receivers switch on `frame.t` and tolerate unknown future fields.
30
+
31
+ Keep protocol changes backward-aware: bump `COLLAB_PROTO` only when old hosts and guests must reject each other.
@@ -0,0 +1,456 @@
1
+ /**
2
+ * Shared wire types for the omp collab live-session protocol.
3
+ *
4
+ * Dependency-free JSON shapes produced by `@oh-my-pi-zen/pi-coding-agent`
5
+ * (`src/collab/protocol.ts` and friends). Browser and test clients import this
6
+ * package instead of depending on the coding-agent runtime; conformance is
7
+ * asserted type-only in `packages/coding-agent/test/collab/web-wire.types.ts`.
8
+ *
9
+ * Unknown entry/event variants arrive over the wire as plain JSON. The unions
10
+ * below cover only the variants this client renders; consumers cast at the
11
+ * JSON boundary and every `switch` keeps a tolerant `default:` branch.
12
+ */
13
+ export interface TextContent {
14
+ type: "text";
15
+ text: string;
16
+ }
17
+ export interface ImageContent {
18
+ type: "image";
19
+ /** Base64-encoded image data. */
20
+ data: string;
21
+ /** e.g. "image/png". */
22
+ mimeType: string;
23
+ }
24
+ export interface ThinkingContent {
25
+ type: "thinking";
26
+ thinking: string;
27
+ }
28
+ export interface RedactedThinkingContent {
29
+ type: "redactedThinking";
30
+ data: string;
31
+ }
32
+ export interface ToolCallContent {
33
+ type: "toolCall";
34
+ id: string;
35
+ name: string;
36
+ arguments: Record<string, unknown>;
37
+ intent?: string;
38
+ }
39
+ export type AssistantContent = TextContent | ThinkingContent | RedactedThinkingContent | ToolCallContent;
40
+ export type StopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
41
+ export interface WireUsage {
42
+ input: number;
43
+ output: number;
44
+ cacheRead: number;
45
+ cacheWrite: number;
46
+ totalTokens: number;
47
+ cost: {
48
+ total: number;
49
+ };
50
+ }
51
+ export interface UserMessage {
52
+ role: "user";
53
+ content: string | (TextContent | ImageContent)[];
54
+ /** True if the message was injected by the system (e.g. auto-continue). */
55
+ synthetic?: boolean;
56
+ /** Unix timestamp in milliseconds. */
57
+ timestamp: number;
58
+ }
59
+ export interface DeveloperMessage {
60
+ role: "developer";
61
+ content: string | (TextContent | ImageContent)[];
62
+ timestamp: number;
63
+ }
64
+ export interface AssistantMessage {
65
+ role: "assistant";
66
+ content: AssistantContent[];
67
+ model: string;
68
+ usage: WireUsage;
69
+ stopReason: StopReason;
70
+ errorMessage?: string;
71
+ timestamp: number;
72
+ }
73
+ export interface ToolResultMessage {
74
+ role: "toolResult";
75
+ toolCallId: string;
76
+ toolName: string;
77
+ content: (TextContent | ImageContent)[];
78
+ details?: unknown;
79
+ isError: boolean;
80
+ timestamp: number;
81
+ }
82
+ export type WireMessage = UserMessage | DeveloperMessage | AssistantMessage | ToolResultMessage;
83
+ export interface SessionHeader {
84
+ type: "session";
85
+ id: string;
86
+ title?: string;
87
+ timestamp: string;
88
+ cwd: string;
89
+ }
90
+ export interface EntryBase {
91
+ id: string;
92
+ parentId: string | null;
93
+ timestamp: string;
94
+ }
95
+ export interface MessageEntry extends EntryBase {
96
+ type: "message";
97
+ message: WireMessage;
98
+ }
99
+ export interface CustomMessageEntry extends EntryBase {
100
+ type: "custom_message";
101
+ customType: string;
102
+ content: string | (TextContent | ImageContent)[];
103
+ details?: unknown;
104
+ display: boolean;
105
+ }
106
+ export interface CompactionEntry extends EntryBase {
107
+ type: "compaction";
108
+ summary: string;
109
+ shortSummary?: string;
110
+ firstKeptEntryId: string;
111
+ tokensBefore: number;
112
+ }
113
+ export interface BranchSummaryEntry extends EntryBase {
114
+ type: "branch_summary";
115
+ fromId: string;
116
+ summary: string;
117
+ }
118
+ export interface ModelChangeEntry extends EntryBase {
119
+ type: "model_change";
120
+ /** Model in "provider/modelId" format. */
121
+ model: string;
122
+ role?: string;
123
+ }
124
+ export interface ThinkingLevelChangeEntry extends EntryBase {
125
+ type: "thinking_level_change";
126
+ thinkingLevel?: string | null;
127
+ }
128
+ export type SessionEntry = MessageEntry | CustomMessageEntry | CompactionEntry | BranchSummaryEntry | ModelChangeEntry | ThinkingLevelChangeEntry;
129
+ /** customType of collab guest prompts injected on the host. */
130
+ export declare const COLLAB_PROMPT_MESSAGE_TYPE = "collab-prompt";
131
+ /** `details` shape of `custom_message` entries with `customType === "collab-prompt"`. */
132
+ export interface CollabPromptDetails {
133
+ from?: string;
134
+ }
135
+ export type AgentEvent = {
136
+ type: "agent_start";
137
+ } | {
138
+ type: "agent_end";
139
+ } | {
140
+ type: "turn_start";
141
+ } | {
142
+ type: "turn_end";
143
+ } | {
144
+ type: "message_start";
145
+ message: WireMessage;
146
+ }
147
+ /** Carries the FULL accumulating partial message — no delta tracking needed. */
148
+ | {
149
+ type: "message_update";
150
+ message: WireMessage;
151
+ } | {
152
+ type: "message_end";
153
+ message: WireMessage;
154
+ } | {
155
+ type: "tool_execution_start";
156
+ toolCallId: string;
157
+ toolName: string;
158
+ args: unknown;
159
+ intent?: string;
160
+ } | {
161
+ type: "tool_execution_update";
162
+ toolCallId: string;
163
+ toolName: string;
164
+ args: unknown;
165
+ partialResult: unknown;
166
+ } | {
167
+ type: "tool_execution_end";
168
+ toolCallId: string;
169
+ toolName: string;
170
+ result: unknown;
171
+ isError?: boolean;
172
+ } | {
173
+ type: "notice";
174
+ level: "info" | "warning" | "error";
175
+ message: string;
176
+ source?: string;
177
+ } | {
178
+ type: "auto_compaction_start";
179
+ reason: string;
180
+ action: string;
181
+ } | {
182
+ type: "auto_compaction_end";
183
+ aborted: boolean;
184
+ willRetry: boolean;
185
+ errorMessage?: string;
186
+ skipped?: boolean;
187
+ } | {
188
+ type: "auto_retry_start";
189
+ attempt: number;
190
+ maxAttempts: number;
191
+ delayMs: number;
192
+ errorMessage: string;
193
+ } | {
194
+ type: "auto_retry_end";
195
+ success: boolean;
196
+ attempt: number;
197
+ finalError?: string;
198
+ } | {
199
+ type: "thinking_level_changed";
200
+ thinkingLevel?: string;
201
+ };
202
+ export interface WireModel {
203
+ id: string;
204
+ name: string;
205
+ provider: string;
206
+ contextWindow: number | null;
207
+ }
208
+ export interface ContextUsage {
209
+ tokens: number | null;
210
+ contextWindow: number | null;
211
+ percent: number | null;
212
+ }
213
+ export interface Participant {
214
+ name: string;
215
+ role: "host" | "guest";
216
+ /** True when the guest joined through a read-only (view) link. */
217
+ readOnly?: boolean;
218
+ }
219
+ /** Debounced footer snapshot broadcast by the host. */
220
+ export interface SessionState {
221
+ isStreaming: boolean;
222
+ queuedMessageCount: number;
223
+ sessionName?: string;
224
+ /** Host cwd — display only; the guest never chdirs. */
225
+ cwd: string;
226
+ model?: WireModel;
227
+ thinkingLevel?: string;
228
+ contextUsage?: ContextUsage;
229
+ participants: Participant[];
230
+ isAborting?: boolean;
231
+ }
232
+ export interface AgentSnapshot {
233
+ id: string;
234
+ displayName: string;
235
+ kind: "main" | "sub";
236
+ parentId?: string;
237
+ status: "running" | "idle" | "parked" | "aborted";
238
+ /** Whether the host has a transcript file for this agent (gates remote transcript fetch). */
239
+ hasSessionFile: boolean;
240
+ createdAt: number;
241
+ lastActivity: number;
242
+ }
243
+ export interface AgentProgress {
244
+ index: number;
245
+ id: string;
246
+ agent: string;
247
+ status: "pending" | "running" | "completed" | "failed" | "aborted";
248
+ task: string;
249
+ description?: string;
250
+ lastIntent?: string;
251
+ currentTool?: string;
252
+ currentToolArgs?: string;
253
+ currentToolStartMs?: number;
254
+ recentTools: {
255
+ tool: string;
256
+ args: string;
257
+ endMs: number;
258
+ }[];
259
+ recentOutput: string[];
260
+ toolCount: number;
261
+ requests: number;
262
+ tokens: number;
263
+ contextTokens?: number;
264
+ contextWindow?: number;
265
+ cost: number;
266
+ durationMs: number;
267
+ resolvedModel?: string;
268
+ }
269
+ export interface SubagentProgressPayload {
270
+ index: number;
271
+ agent: string;
272
+ task: string;
273
+ parentToolCallId?: string;
274
+ assignment?: string;
275
+ progress: AgentProgress;
276
+ sessionFile?: string;
277
+ }
278
+ export interface SubagentLifecyclePayload {
279
+ id: string;
280
+ agent: string;
281
+ description?: string;
282
+ status: "started" | "completed" | "failed" | "aborted";
283
+ sessionFile?: string;
284
+ parentToolCallId?: string;
285
+ index: number;
286
+ }
287
+ export type CollabUiSelectItem = string | {
288
+ label: string;
289
+ description?: string;
290
+ };
291
+ export type CollabUiResponseValue = string | undefined;
292
+ export type CollabUiRequestDraft = {
293
+ kind: "select";
294
+ title: string;
295
+ options: CollabUiSelectItem[];
296
+ initialIndex?: number;
297
+ selectionMarker?: "radio" | "checkbox";
298
+ checkedIndices?: number[];
299
+ markableCount?: number;
300
+ helpText?: string;
301
+ } | {
302
+ kind: "editor";
303
+ title: string;
304
+ prefill?: string;
305
+ };
306
+ export type CollabUiRequest = CollabUiRequestDraft & {
307
+ reqId: number;
308
+ };
309
+ export type GuestFrame = {
310
+ t: "hello";
311
+ proto: number;
312
+ name: string;
313
+ /**
314
+ * base64url write token proving full-link possession; absent for
315
+ * read-only (view) links. The host marks peers without a valid token
316
+ * read-only and rejects their mutating frames.
317
+ */
318
+ writeToken?: string;
319
+ } | {
320
+ t: "prompt";
321
+ text: string;
322
+ images?: ImageContent[];
323
+ } | {
324
+ t: "ui-response";
325
+ reqId: number;
326
+ value?: CollabUiResponseValue;
327
+ } | {
328
+ t: "abort";
329
+ } | {
330
+ t: "agent-cmd";
331
+ cmd: "chat" | "kill" | "revive";
332
+ agentId: string;
333
+ text?: string;
334
+ } | {
335
+ t: "fetch-transcript";
336
+ reqId: number;
337
+ agentId: string;
338
+ fromByte: number;
339
+ };
340
+ /** EventBus channels mirrored to guests (task subagent traffic only). */
341
+ export type BusChannel = "task:subagent:progress" | "task:subagent:lifecycle";
342
+ export type HostFrame = {
343
+ t: "welcome";
344
+ proto: number;
345
+ header: SessionHeader;
346
+ state: SessionState;
347
+ agents: AgentSnapshot[];
348
+ /**
349
+ * Total number of `SessionEntry` items the host will deliver in the
350
+ * `snapshot-chunk` frames that follow. Guests stay in the loading
351
+ * phase until they have accumulated all of them (or a chunk arrives
352
+ * with `final: true`).
353
+ */
354
+ entryCount: number;
355
+ /** True when this peer joined through a read-only (view) link. */
356
+ readOnly?: boolean;
357
+ }
358
+ /**
359
+ * Targeted snapshot fragment delivered after `welcome`. Hosts split the
360
+ * transcript into chunks bounded by byte size so a multi-MB session is not
361
+ * forced through one giant frame the relay may stall on. The last chunk
362
+ * carries `final: true`; guests finalize the replica on that frame.
363
+ */
364
+ | {
365
+ t: "snapshot-chunk";
366
+ entries: SessionEntry[];
367
+ final: boolean;
368
+ } | {
369
+ t: "entry";
370
+ entry: SessionEntry;
371
+ } | {
372
+ t: "event";
373
+ event: AgentEvent;
374
+ } | {
375
+ t: "state";
376
+ state: SessionState;
377
+ }
378
+ /** Mirrored EventBus traffic (task subagent lifecycle/progress channels only). */
379
+ | {
380
+ t: "bus";
381
+ channel: BusChannel;
382
+ data: unknown;
383
+ } | {
384
+ t: "agents";
385
+ agents: AgentSnapshot[];
386
+ } | {
387
+ t: "ui-request";
388
+ request: CollabUiRequest;
389
+ } | {
390
+ t: "ui-request-end";
391
+ reqId: number;
392
+ }
393
+ /** Targeted reply to fetch-transcript; `text` is decoded JSONL from `fromByte`, `newSize` the next offset base. */
394
+ | {
395
+ t: "transcript";
396
+ reqId: number;
397
+ text: string;
398
+ newSize: number;
399
+ error?: string;
400
+ } | {
401
+ t: "bye";
402
+ reason: string;
403
+ } | {
404
+ t: "error";
405
+ message: string;
406
+ };
407
+ export type WireFrame = GuestFrame | HostFrame;
408
+ /**
409
+ * Wire protocol version carried in `hello`; the host rejects mismatches.
410
+ *
411
+ * - `1` (legacy): `welcome` carried the full `entries` array inline.
412
+ * - `2`: `welcome` carries only metadata (header/state/agents/entryCount);
413
+ * transcript entries follow in `snapshot-chunk` frames, so multi-MB
414
+ * sessions are not gated on a single welcome frame fitting under the
415
+ * guest's first-welcome timeout.
416
+ * - `3`: host asks guests through `ui-request`/`ui-request-end` host frames
417
+ * answered by the `ui-response` guest frame. Guests that predate the
418
+ * grammar would silently drop `ui-request` (asks hang forever on the
419
+ * host), so they must be rejected at hello.
420
+ */
421
+ export declare const COLLAB_PROTO = 3;
422
+ /** Parameter key used for intent tracing (e.g. prompt explanation/reasoning) */
423
+ export declare const INTENT_FIELD = "i";
424
+ /** Plaintext envelope prefix: `[4B uint32 BE peerId][sealed payload]`. */
425
+ export declare const ENVELOPE_HEADER_LENGTH = 4;
426
+ export declare const ROOM_ID_BYTES = 16;
427
+ /** AES-256-GCM room key; the seal key for every collab frame. */
428
+ export declare const ROOM_KEY_BYTES = 32;
429
+ /**
430
+ * Random write token appended to the room key in full links
431
+ * (`base64url(key ∥ token)`); view links carry the bare key. Possession
432
+ * proves prompt/abort/agent-cmd capability to the host.
433
+ */
434
+ export declare const WRITE_TOKEN_BYTES = 16;
435
+ /** Default public relay; bare `<roomId>.<key>` links resolve against it. */
436
+ export declare const DEFAULT_RELAY_URL = "wss://my.omp.sh";
437
+ /** Default share viewer/upload base; `/share` links resolve against `<base>/<id>#<key>`. */
438
+ export declare const DEFAULT_SHARE_URL = "https://my.omp.sh/s";
439
+ export interface ParsedCollabLink {
440
+ /** wss://host[:port]/r/<roomId> — no query, no fragment. */
441
+ wsUrl: string;
442
+ roomId: string;
443
+ key: Uint8Array;
444
+ /** Write token from a full link; absent for read-only (view) links. */
445
+ writeToken?: Uint8Array;
446
+ }
447
+ /** Relay → host control message. */
448
+ export type RelayControlToHost = {
449
+ t: "peer-joined" | "peer-left";
450
+ peer: number;
451
+ };
452
+ /** Relay → guest control message. */
453
+ export type RelayControlToGuest = {
454
+ t: "room-closed";
455
+ };
456
+ export type RelayControlMessage = RelayControlToHost | RelayControlToGuest;
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "type": "module",
3
+ "name": "@oh-my-pi-zen/pi-wire",
4
+ "version": "16.3.6-zen.1",
5
+ "description": "Shared wire protocol types for Oh My Pi packages",
6
+ "homepage": "https://omp.sh",
7
+ "author": "Can Boluk",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/cagedbird043/oh-my-pi-zen.git",
12
+ "directory": "packages/wire"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/cagedbird043/oh-my-pi-zen/issues"
16
+ },
17
+ "keywords": [
18
+ "wire",
19
+ "protocol",
20
+ "types",
21
+ "collab"
22
+ ],
23
+ "main": "./src/index.ts",
24
+ "types": "./dist/types/index.d.ts",
25
+ "scripts": {
26
+ "check": "biome check . && bun run check:types",
27
+ "check:types": "tsgo -p tsconfig.json --noEmit",
28
+ "lint": "biome lint .",
29
+ "fix": "biome check --write --unsafe .",
30
+ "fmt": "biome format --write .",
31
+ "test": "bun test --parallel"
32
+ },
33
+ "devDependencies": {
34
+ "@types/bun": "^1.3.14"
35
+ },
36
+ "engines": {
37
+ "bun": ">=1.3.14"
38
+ },
39
+ "files": [
40
+ "src",
41
+ "README.md",
42
+ "CHANGELOG.md",
43
+ "dist/types"
44
+ ],
45
+ "exports": {
46
+ ".": {
47
+ "types": "./dist/types/index.d.ts",
48
+ "import": "./src/index.ts"
49
+ },
50
+ "./*": {
51
+ "types": "./dist/types/*.d.ts",
52
+ "import": "./src/*.ts"
53
+ },
54
+ "./*.js": "./src/*.ts"
55
+ }
56
+ }
package/src/index.ts ADDED
@@ -0,0 +1,444 @@
1
+ /**
2
+ * Shared wire types for the omp collab live-session protocol.
3
+ *
4
+ * Dependency-free JSON shapes produced by `@oh-my-pi-zen/pi-coding-agent`
5
+ * (`src/collab/protocol.ts` and friends). Browser and test clients import this
6
+ * package instead of depending on the coding-agent runtime; conformance is
7
+ * asserted type-only in `packages/coding-agent/test/collab/web-wire.types.ts`.
8
+ *
9
+ * Unknown entry/event variants arrive over the wire as plain JSON. The unions
10
+ * below cover only the variants this client renders; consumers cast at the
11
+ * JSON boundary and every `switch` keeps a tolerant `default:` branch.
12
+ */
13
+
14
+ // ═══════════════════════════════════════════════════════════════════════════
15
+ // Content blocks
16
+ // ═══════════════════════════════════════════════════════════════════════════
17
+
18
+ export interface TextContent {
19
+ type: "text";
20
+ text: string;
21
+ }
22
+
23
+ export interface ImageContent {
24
+ type: "image";
25
+ /** Base64-encoded image data. */
26
+ data: string;
27
+ /** e.g. "image/png". */
28
+ mimeType: string;
29
+ }
30
+
31
+ export interface ThinkingContent {
32
+ type: "thinking";
33
+ thinking: string;
34
+ }
35
+
36
+ export interface RedactedThinkingContent {
37
+ type: "redactedThinking";
38
+ data: string;
39
+ }
40
+
41
+ export interface ToolCallContent {
42
+ type: "toolCall";
43
+ id: string;
44
+ name: string;
45
+ arguments: Record<string, unknown>;
46
+ intent?: string;
47
+ }
48
+
49
+ export type AssistantContent = TextContent | ThinkingContent | RedactedThinkingContent | ToolCallContent;
50
+
51
+ export type StopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
52
+
53
+ export interface WireUsage {
54
+ input: number;
55
+ output: number;
56
+ cacheRead: number;
57
+ cacheWrite: number;
58
+ totalTokens: number;
59
+ cost: { total: number };
60
+ }
61
+
62
+ // ═══════════════════════════════════════════════════════════════════════════
63
+ // Messages
64
+ // ═══════════════════════════════════════════════════════════════════════════
65
+
66
+ export interface UserMessage {
67
+ role: "user";
68
+ content: string | (TextContent | ImageContent)[];
69
+ /** True if the message was injected by the system (e.g. auto-continue). */
70
+ synthetic?: boolean;
71
+ /** Unix timestamp in milliseconds. */
72
+ timestamp: number;
73
+ }
74
+
75
+ export interface DeveloperMessage {
76
+ role: "developer";
77
+ content: string | (TextContent | ImageContent)[];
78
+ timestamp: number;
79
+ }
80
+
81
+ export interface AssistantMessage {
82
+ role: "assistant";
83
+ content: AssistantContent[];
84
+ model: string;
85
+ usage: WireUsage;
86
+ stopReason: StopReason;
87
+ errorMessage?: string;
88
+ timestamp: number;
89
+ }
90
+
91
+ export interface ToolResultMessage {
92
+ role: "toolResult";
93
+ toolCallId: string;
94
+ toolName: string;
95
+ content: (TextContent | ImageContent)[];
96
+ details?: unknown;
97
+ isError: boolean;
98
+ timestamp: number;
99
+ }
100
+
101
+ export type WireMessage = UserMessage | DeveloperMessage | AssistantMessage | ToolResultMessage;
102
+
103
+ // ═══════════════════════════════════════════════════════════════════════════
104
+ // Session entries (rendered subset; cast `as SessionEntry` at the JSON
105
+ // boundary and skip unknown `type`s in a tolerant `default:`)
106
+ // ═══════════════════════════════════════════════════════════════════════════
107
+
108
+ export interface SessionHeader {
109
+ type: "session";
110
+ id: string;
111
+ title?: string;
112
+ timestamp: string;
113
+ cwd: string;
114
+ }
115
+
116
+ export interface EntryBase {
117
+ id: string;
118
+ parentId: string | null;
119
+ timestamp: string;
120
+ }
121
+
122
+ export interface MessageEntry extends EntryBase {
123
+ type: "message";
124
+ message: WireMessage;
125
+ }
126
+
127
+ export interface CustomMessageEntry extends EntryBase {
128
+ type: "custom_message";
129
+ customType: string;
130
+ content: string | (TextContent | ImageContent)[];
131
+ details?: unknown;
132
+ display: boolean;
133
+ }
134
+
135
+ export interface CompactionEntry extends EntryBase {
136
+ type: "compaction";
137
+ summary: string;
138
+ shortSummary?: string;
139
+ firstKeptEntryId: string;
140
+ tokensBefore: number;
141
+ }
142
+
143
+ export interface BranchSummaryEntry extends EntryBase {
144
+ type: "branch_summary";
145
+ fromId: string;
146
+ summary: string;
147
+ }
148
+
149
+ export interface ModelChangeEntry extends EntryBase {
150
+ type: "model_change";
151
+ /** Model in "provider/modelId" format. */
152
+ model: string;
153
+ role?: string;
154
+ }
155
+
156
+ export interface ThinkingLevelChangeEntry extends EntryBase {
157
+ type: "thinking_level_change";
158
+ thinkingLevel?: string | null;
159
+ }
160
+
161
+ export type SessionEntry =
162
+ | MessageEntry
163
+ | CustomMessageEntry
164
+ | CompactionEntry
165
+ | BranchSummaryEntry
166
+ | ModelChangeEntry
167
+ | ThinkingLevelChangeEntry;
168
+
169
+ /** customType of collab guest prompts injected on the host. */
170
+ export const COLLAB_PROMPT_MESSAGE_TYPE = "collab-prompt";
171
+
172
+ /** `details` shape of `custom_message` entries with `customType === "collab-prompt"`. */
173
+ export interface CollabPromptDetails {
174
+ from?: string;
175
+ }
176
+
177
+ // ═══════════════════════════════════════════════════════════════════════════
178
+ // Events (handled subset)
179
+ // ═══════════════════════════════════════════════════════════════════════════
180
+
181
+ export type AgentEvent =
182
+ | { type: "agent_start" }
183
+ | { type: "agent_end" }
184
+ | { type: "turn_start" }
185
+ | { type: "turn_end" }
186
+ | { type: "message_start"; message: WireMessage }
187
+ /** Carries the FULL accumulating partial message — no delta tracking needed. */
188
+ | { type: "message_update"; message: WireMessage }
189
+ | { type: "message_end"; message: WireMessage }
190
+ | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: unknown; intent?: string }
191
+ | { type: "tool_execution_update"; toolCallId: string; toolName: string; args: unknown; partialResult: unknown }
192
+ | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: unknown; isError?: boolean }
193
+ | { type: "notice"; level: "info" | "warning" | "error"; message: string; source?: string }
194
+ | { type: "auto_compaction_start"; reason: string; action: string }
195
+ | { type: "auto_compaction_end"; aborted: boolean; willRetry: boolean; errorMessage?: string; skipped?: boolean }
196
+ | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
197
+ | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
198
+ | { type: "thinking_level_changed"; thinkingLevel?: string };
199
+
200
+ // ═══════════════════════════════════════════════════════════════════════════
201
+ // State & agents
202
+ // ═══════════════════════════════════════════════════════════════════════════
203
+
204
+ export interface WireModel {
205
+ id: string;
206
+ name: string;
207
+ provider: string;
208
+ contextWindow: number | null;
209
+ }
210
+
211
+ export interface ContextUsage {
212
+ tokens: number | null;
213
+ contextWindow: number | null;
214
+ percent: number | null;
215
+ }
216
+
217
+ export interface Participant {
218
+ name: string;
219
+ role: "host" | "guest";
220
+ /** True when the guest joined through a read-only (view) link. */
221
+ readOnly?: boolean;
222
+ }
223
+
224
+ /** Debounced footer snapshot broadcast by the host. */
225
+ export interface SessionState {
226
+ isStreaming: boolean;
227
+ queuedMessageCount: number;
228
+ sessionName?: string;
229
+ /** Host cwd — display only; the guest never chdirs. */
230
+ cwd: string;
231
+ model?: WireModel;
232
+ thinkingLevel?: string;
233
+ contextUsage?: ContextUsage;
234
+ participants: Participant[];
235
+ isAborting?: boolean;
236
+ }
237
+
238
+ export interface AgentSnapshot {
239
+ id: string;
240
+ displayName: string;
241
+ kind: "main" | "sub";
242
+ parentId?: string;
243
+ status: "running" | "idle" | "parked" | "aborted";
244
+ /** Whether the host has a transcript file for this agent (gates remote transcript fetch). */
245
+ hasSessionFile: boolean;
246
+ createdAt: number;
247
+ lastActivity: number;
248
+ }
249
+
250
+ // ═══════════════════════════════════════════════════════════════════════════
251
+ // Bus payloads (task subagent lifecycle/progress channels)
252
+ // ═══════════════════════════════════════════════════════════════════════════
253
+
254
+ export interface AgentProgress {
255
+ index: number;
256
+ id: string;
257
+ agent: string;
258
+ status: "pending" | "running" | "completed" | "failed" | "aborted";
259
+ task: string;
260
+ description?: string;
261
+ lastIntent?: string;
262
+ currentTool?: string;
263
+ currentToolArgs?: string;
264
+ currentToolStartMs?: number;
265
+ recentTools: { tool: string; args: string; endMs: number }[];
266
+ recentOutput: string[];
267
+ toolCount: number;
268
+ requests: number;
269
+ tokens: number;
270
+ contextTokens?: number;
271
+ contextWindow?: number;
272
+ cost: number;
273
+ durationMs: number;
274
+ resolvedModel?: string;
275
+ }
276
+
277
+ export interface SubagentProgressPayload {
278
+ index: number;
279
+ agent: string;
280
+ task: string;
281
+ parentToolCallId?: string;
282
+ assignment?: string;
283
+ progress: AgentProgress;
284
+ sessionFile?: string;
285
+ }
286
+
287
+ export interface SubagentLifecyclePayload {
288
+ id: string;
289
+ agent: string;
290
+ description?: string;
291
+ status: "started" | "completed" | "failed" | "aborted";
292
+ sessionFile?: string;
293
+ parentToolCallId?: string;
294
+ index: number;
295
+ }
296
+
297
+ // ═══════════════════════════════════════════════════════════════════════════
298
+ // Frames (JSON inside the AES-GCM seal)
299
+ // ═══════════════════════════════════════════════════════════════════════════
300
+
301
+ export type CollabUiSelectItem = string | { label: string; description?: string };
302
+
303
+ export type CollabUiResponseValue = string | undefined;
304
+
305
+ export type CollabUiRequestDraft =
306
+ | {
307
+ kind: "select";
308
+ title: string;
309
+ options: CollabUiSelectItem[];
310
+ initialIndex?: number;
311
+ selectionMarker?: "radio" | "checkbox";
312
+ checkedIndices?: number[];
313
+ markableCount?: number;
314
+ helpText?: string;
315
+ }
316
+ | {
317
+ kind: "editor";
318
+ title: string;
319
+ prefill?: string;
320
+ };
321
+
322
+ export type CollabUiRequest = CollabUiRequestDraft & { reqId: number };
323
+
324
+ export type GuestFrame =
325
+ | {
326
+ t: "hello";
327
+ proto: number;
328
+ name: string;
329
+ /**
330
+ * base64url write token proving full-link possession; absent for
331
+ * read-only (view) links. The host marks peers without a valid token
332
+ * read-only and rejects their mutating frames.
333
+ */
334
+ writeToken?: string;
335
+ }
336
+ | { t: "prompt"; text: string; images?: ImageContent[] }
337
+ | { t: "ui-response"; reqId: number; value?: CollabUiResponseValue }
338
+ | { t: "abort" }
339
+ | { t: "agent-cmd"; cmd: "chat" | "kill" | "revive"; agentId: string; text?: string }
340
+ | { t: "fetch-transcript"; reqId: number; agentId: string; fromByte: number };
341
+
342
+ /** EventBus channels mirrored to guests (task subagent traffic only). */
343
+ export type BusChannel = "task:subagent:progress" | "task:subagent:lifecycle";
344
+
345
+ export type HostFrame =
346
+ | {
347
+ t: "welcome";
348
+ proto: number;
349
+ header: SessionHeader;
350
+ state: SessionState;
351
+ agents: AgentSnapshot[];
352
+ /**
353
+ * Total number of `SessionEntry` items the host will deliver in the
354
+ * `snapshot-chunk` frames that follow. Guests stay in the loading
355
+ * phase until they have accumulated all of them (or a chunk arrives
356
+ * with `final: true`).
357
+ */
358
+ entryCount: number;
359
+ /** True when this peer joined through a read-only (view) link. */
360
+ readOnly?: boolean;
361
+ }
362
+ /**
363
+ * Targeted snapshot fragment delivered after `welcome`. Hosts split the
364
+ * transcript into chunks bounded by byte size so a multi-MB session is not
365
+ * forced through one giant frame the relay may stall on. The last chunk
366
+ * carries `final: true`; guests finalize the replica on that frame.
367
+ */
368
+ | { t: "snapshot-chunk"; entries: SessionEntry[]; final: boolean }
369
+ | { t: "entry"; entry: SessionEntry }
370
+ | { t: "event"; event: AgentEvent }
371
+ | { t: "state"; state: SessionState }
372
+ /** Mirrored EventBus traffic (task subagent lifecycle/progress channels only). */
373
+ | { t: "bus"; channel: BusChannel; data: unknown }
374
+ | { t: "agents"; agents: AgentSnapshot[] }
375
+ | { t: "ui-request"; request: CollabUiRequest }
376
+ | { t: "ui-request-end"; reqId: number }
377
+ /** Targeted reply to fetch-transcript; `text` is decoded JSONL from `fromByte`, `newSize` the next offset base. */
378
+ | { t: "transcript"; reqId: number; text: string; newSize: number; error?: string }
379
+ | { t: "bye"; reason: string }
380
+ | { t: "error"; message: string };
381
+
382
+ export type WireFrame = GuestFrame | HostFrame;
383
+
384
+ /**
385
+ * Wire protocol version carried in `hello`; the host rejects mismatches.
386
+ *
387
+ * - `1` (legacy): `welcome` carried the full `entries` array inline.
388
+ * - `2`: `welcome` carries only metadata (header/state/agents/entryCount);
389
+ * transcript entries follow in `snapshot-chunk` frames, so multi-MB
390
+ * sessions are not gated on a single welcome frame fitting under the
391
+ * guest's first-welcome timeout.
392
+ * - `3`: host asks guests through `ui-request`/`ui-request-end` host frames
393
+ * answered by the `ui-response` guest frame. Guests that predate the
394
+ * grammar would silently drop `ui-request` (asks hang forever on the
395
+ * host), so they must be rejected at hello.
396
+ */
397
+ export const COLLAB_PROTO = 3;
398
+
399
+ /** Parameter key used for intent tracing (e.g. prompt explanation/reasoning) */
400
+ export const INTENT_FIELD = "i";
401
+
402
+ // ═══════════════════════════════════════════════════════════════════════════
403
+ // Envelope & link constants
404
+ // ═══════════════════════════════════════════════════════════════════════════
405
+
406
+ /** Plaintext envelope prefix: `[4B uint32 BE peerId][sealed payload]`. */
407
+ export const ENVELOPE_HEADER_LENGTH = 4;
408
+
409
+ export const ROOM_ID_BYTES = 16;
410
+
411
+ /** AES-256-GCM room key; the seal key for every collab frame. */
412
+ export const ROOM_KEY_BYTES = 32;
413
+
414
+ /**
415
+ * Random write token appended to the room key in full links
416
+ * (`base64url(key ∥ token)`); view links carry the bare key. Possession
417
+ * proves prompt/abort/agent-cmd capability to the host.
418
+ */
419
+ export const WRITE_TOKEN_BYTES = 16;
420
+
421
+ /** Default public relay; bare `<roomId>.<key>` links resolve against it. */
422
+ export const DEFAULT_RELAY_URL = "wss://my.omp.sh";
423
+
424
+ /** Default share viewer/upload base; `/share` links resolve against `<base>/<id>#<key>`. */
425
+ export const DEFAULT_SHARE_URL = "https://my.omp.sh/s";
426
+
427
+ export interface ParsedCollabLink {
428
+ /** wss://host[:port]/r/<roomId> — no query, no fragment. */
429
+ wsUrl: string;
430
+ roomId: string;
431
+ key: Uint8Array;
432
+ /** Write token from a full link; absent for read-only (view) links. */
433
+ writeToken?: Uint8Array;
434
+ }
435
+
436
+ // ═══════════════════════════════════════════════════════════════════════════
437
+ // Relay control messages (TEXT JSON, unencrypted, no session data)
438
+ // ═══════════════════════════════════════════════════════════════════════════
439
+
440
+ /** Relay → host control message. */
441
+ export type RelayControlToHost = { t: "peer-joined" | "peer-left"; peer: number };
442
+ /** Relay → guest control message. */
443
+ export type RelayControlToGuest = { t: "room-closed" };
444
+ export type RelayControlMessage = RelayControlToHost | RelayControlToGuest;