@vibefield/rosetta-room 0.1.10 → 0.1.12

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 (100) hide show
  1. package/README.md +65 -3
  2. package/dist/components/Transcript.js +6 -2
  3. package/dist/components/file-viewer/FileViewerDialog.js +3 -2
  4. package/dist/components/file-viewer/diff/parse.js +7 -0
  5. package/dist/components/file-viewer/kinds.d.ts +22 -0
  6. package/dist/components/file-viewer/kinds.js +57 -0
  7. package/dist/components/file-viewer/markdown/render.d.ts +7 -1
  8. package/dist/components/file-viewer/markdown/render.js +16 -12
  9. package/dist/components/file-viewer/registry.d.ts +2 -2
  10. package/dist/components/file-viewer/registry.js +20 -59
  11. package/dist/components/file-viewer/views/DiffBody.js +7 -2
  12. package/dist/components/git/CommitViewer.js +3 -2
  13. package/dist/components/transcript/Activity.d.ts +10 -4
  14. package/dist/components/transcript/Activity.js +36 -11
  15. package/dist/components/transcript/Anchor.js +3 -2
  16. package/dist/components/transcript/Compaction.d.ts +9 -0
  17. package/dist/components/transcript/Compaction.js +10 -5
  18. package/dist/components/transcript/Document.js +150 -208
  19. package/dist/components/transcript/PromptJump.js +28 -8
  20. package/dist/components/transcript/Prose.d.ts +5 -1
  21. package/dist/components/transcript/Prose.js +7 -6
  22. package/dist/components/transcript/ReadingBlocks.d.ts +71 -0
  23. package/dist/components/transcript/ReadingBlocks.js +279 -0
  24. package/dist/components/transcript/activity-plan.d.ts +38 -7
  25. package/dist/components/transcript/activity-plan.js +198 -28
  26. package/dist/components/transcript/attachment-file-source.d.ts +1 -2
  27. package/dist/components/transcript/attachment-file-source.js +7 -5
  28. package/dist/components/transcript/disclosure-state.d.ts +2 -0
  29. package/dist/components/transcript/disclosure-state.js +6 -2
  30. package/dist/components/transcript/document-model.js +53 -9
  31. package/dist/components/transcript/document-plan.js +263 -98
  32. package/dist/components/transcript/reading-identity.d.ts +14 -1
  33. package/dist/components/transcript/reading-identity.js +126 -10
  34. package/dist/components/worktree/WorktreeColumn.js +12 -1
  35. package/dist/components/worktree/WorktreeList.d.ts +8 -2
  36. package/dist/components/worktree/WorktreeList.js +200 -5
  37. package/dist/components/worktree/worktree-ledger.d.ts +40 -0
  38. package/dist/components/worktree/worktree-ledger.js +68 -0
  39. package/dist/conversation/ConversationGallery.d.ts +11 -0
  40. package/dist/conversation/ConversationGallery.js +14 -0
  41. package/dist/conversation/ConversationMedia.d.ts +44 -0
  42. package/dist/conversation/ConversationMedia.js +210 -0
  43. package/dist/conversation/ConversationProse.d.ts +13 -0
  44. package/dist/conversation/ConversationProse.js +6 -0
  45. package/dist/conversation/ConversationRunRows.d.ts +57 -0
  46. package/dist/conversation/ConversationRunRows.js +84 -0
  47. package/dist/conversation/ConversationTurnView.d.ts +64 -0
  48. package/dist/conversation/ConversationTurnView.js +169 -0
  49. package/dist/conversation/ConversationView.d.ts +3 -0
  50. package/dist/conversation/ConversationView.js +257 -0
  51. package/dist/conversation/feed-reads.d.ts +36 -0
  52. package/dist/conversation/feed-reads.js +155 -0
  53. package/dist/conversation/feed.d.ts +106 -0
  54. package/dist/conversation/feed.js +884 -0
  55. package/dist/conversation/index.d.ts +11 -0
  56. package/dist/conversation/index.js +25 -0
  57. package/dist/conversation/model.d.ts +108 -0
  58. package/dist/conversation/model.js +257 -0
  59. package/dist/conversation/ports.d.ts +194 -0
  60. package/dist/conversation/ports.js +9 -0
  61. package/dist/conversation/rosetta-client.d.ts +8 -0
  62. package/dist/conversation/rosetta-client.js +1 -0
  63. package/dist/conversation/use-conversation-feed.d.ts +16 -0
  64. package/dist/conversation/use-conversation-feed.js +41 -0
  65. package/dist/conversation/use-conversation-window.d.ts +50 -0
  66. package/dist/conversation/use-conversation-window.js +336 -0
  67. package/dist/conversation/words.d.ts +51 -0
  68. package/dist/conversation/words.js +79 -0
  69. package/dist/fixtures/conversation.d.ts +34 -0
  70. package/dist/fixtures/conversation.js +723 -0
  71. package/dist/fixtures/index.d.ts +2 -0
  72. package/dist/fixtures/index.js +1 -0
  73. package/dist/index.d.ts +1 -1
  74. package/dist/lib/hooks.js +6 -1
  75. package/dist/lib/session-leases.d.ts +11 -8
  76. package/dist/lib/transcript/collaboration.js +53 -19
  77. package/dist/lib/transcript/head-of-document.js +9 -3
  78. package/dist/lib/transcript/index.d.ts +1 -1
  79. package/dist/lib/transcript/index.js +1 -1
  80. package/dist/lib/transcript/prompt-jump.d.ts +2 -0
  81. package/dist/lib/transcript/prompt-jump.js +5 -1
  82. package/dist/lib/transcript/sittings.d.ts +2 -1
  83. package/dist/lib/transcript/sittings.js +72 -10
  84. package/dist/lib/transcript/tail-state.d.ts +9 -0
  85. package/dist/lib/transcript/tail-state.js +25 -1
  86. package/dist/lib/transcript/turns.d.ts +5 -0
  87. package/dist/lib/transcript/turns.js +221 -57
  88. package/dist/lib/transcript/use-transcript-tail.js +17 -3
  89. package/dist/lib/transcript/vocabulary.d.ts +2 -1
  90. package/dist/lib/transcript/vocabulary.js +11 -1
  91. package/dist/parts-context.d.ts +25 -0
  92. package/dist/parts-context.js +32 -0
  93. package/dist/ports.d.ts +36 -0
  94. package/dist/room-context.d.ts +1 -2
  95. package/dist/room-context.js +11 -9
  96. package/dist/styles/conversation-turn.css +147 -0
  97. package/dist/styles/conversation.css +45 -0
  98. package/dist/styles/room.css +102 -12
  99. package/dist/styles/transcript.css +11 -2
  100. package/package.json +9 -4
@@ -0,0 +1,723 @@
1
+ // A synthetic conversation for the conversation view: a chain of sessions of
2
+ // plain prompts and replies, read by turns through a port that answers as the
3
+ // daemon's turn reads do, so a harness, a bench or a host's catalog can draw
4
+ // the view with no daemon. Deterministic: the same options (seed and now
5
+ // included) give the same rows, turns, outlines and pages. Nothing here knows
6
+ // a host; every word is a plain sentence from the fixed lists below.
7
+ //
8
+ // What the port answers, as the daemon's reads do:
9
+ // - `turns` pages a session's turns oldest first, newest `limit` before a
10
+ // point, `more_before` while older turns exist; a watermark that is not the
11
+ // session's current one rejects with `CursorExpiredError`.
12
+ // - `turnOutline` lists every turn; `turnRows` reads a turn's rows inside a
13
+ // range clamped to the turn's own, newest `limit` first, paged by a cursor.
14
+ // - `subscribeTurns` sends one snapshot of the newest `limit` turns (the
15
+ // outline too when asked), then each turn an `append` changes or adds.
16
+ // - `readAsset` and `readTextAsset` answer the demo's own members: small PNG
17
+ // pictures it draws itself, and a compaction's stored summary.
18
+ import { ApiRequestError, CursorExpiredError } from "@vibefield/rosetta-protocol";
19
+ const MINUTE = 60_000;
20
+ const HOUR = 60 * MINUTE;
21
+ const DEFAULT_NOW = Date.UTC(2025, 9, 1, 12, 0, 0);
22
+ /** As the daemon's turn read: at most 64 parts, 16 media per run, 160 bytes of preview. */
23
+ const PARTS_MAX = 64;
24
+ const RUN_MEDIA_MAX = 16;
25
+ const PREVIEW_MAX_BYTES = 160;
26
+ const PROMPTS = [
27
+ "Read the notes in the folder and tell me what changed this week.",
28
+ "Sort the list by date and keep the newest entries first.",
29
+ "Rename the helper so its name says what it returns.",
30
+ "Write a short summary of the three longest files.",
31
+ "Check that every link in the guide still opens.",
32
+ "Add a test for the empty case.",
33
+ "Keep the table's header in view while it scrolls.",
34
+ "Why does the second step take so long?",
35
+ "Draw a small chart of the counts by day.",
36
+ "Split the long function into two.",
37
+ "Find where the old name is still used.",
38
+ "Turn the paragraph into a list of steps.",
39
+ ];
40
+ const REPLIES = [
41
+ "Done. The list is sorted by date, newest first.",
42
+ "Three files changed this week: the index, the guide and the changelog.",
43
+ "The helper is now `latestEntry`, and every caller uses the new name.",
44
+ "The second step reads every file twice. Reading each file once halves its time.",
45
+ "Here is the chart of the counts by day. Tuesday is the busiest.",
46
+ "I added a test for the empty case. It fails before the change and passes after it.",
47
+ "Every link opens. Two of them now redirect to a newer address.",
48
+ "The function is two now: one reads the file, the other writes it.",
49
+ "The old name is still used in two places:\n\n- `src/list.ts`, in the sort\n- `docs/guide.md`, in an example",
50
+ "The steps:\n\n1. Read the file.\n2. Sort its lines.\n3. Write it back.",
51
+ ];
52
+ const THOUGHTS = ["Reading the files first.", "The order matters here.", "Two of these can wait."];
53
+ const FILES = ["notes/week.md", "src/list.ts", "src/table.ts", "docs/guide.md", "test/list.test.ts"];
54
+ const COMMANDS = ["npm test", "npm run build", "ls notes", "git status"];
55
+ const FAILURE = "The service was busy. Try again in a moment.";
56
+ const PROVENANCE = { agent_version: null, src_cursor: null, src_offset: null };
57
+ const NO_USAGE = {
58
+ input: null, output: null, cache_read: null, cache_write: null, thinking: null, cache_write_1h: null,
59
+ web_searches: null, service_tier: null, route: null, billed_pico_usd: null, scope: "request", requests: null,
60
+ };
61
+ /* ── determinism ─────────────────────────────────────────────────────────── */
62
+ /** A small seeded generator (mulberry32): the same seed, the same numbers. */
63
+ function seeded(seed) {
64
+ let state = seed >>> 0;
65
+ return () => {
66
+ state = (state + 0x6d2b79f5) >>> 0;
67
+ let t = state;
68
+ t = Math.imul(t ^ (t >>> 15), t | 1);
69
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
70
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
71
+ };
72
+ }
73
+ function pick(list, next) {
74
+ return list[Math.floor(next() * list.length)];
75
+ }
76
+ /** A 64-hex name for a member, the same for the same seed (FNV-1a, eight
77
+ * rounds). Not a content hash. */
78
+ function digestOf(seed) {
79
+ let hex = "";
80
+ for (let round = 0; hex.length < 64; round += 1) {
81
+ let hash = (0x811c9dc5 ^ round) >>> 0;
82
+ for (let i = 0; i < seed.length; i += 1) {
83
+ hash ^= seed.charCodeAt(i);
84
+ hash = Math.imul(hash, 0x01000193) >>> 0;
85
+ }
86
+ hex += hash.toString(16).padStart(8, "0");
87
+ }
88
+ return hex.slice(0, 64);
89
+ }
90
+ /* ── the members: pictures and a summary ─────────────────────────────────── */
91
+ let crcTable = null;
92
+ function crc32(bytes) {
93
+ if (crcTable === null) {
94
+ crcTable = new Uint32Array(256);
95
+ for (let n = 0; n < 256; n += 1) {
96
+ let c = n;
97
+ for (let k = 0; k < 8; k += 1)
98
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
99
+ crcTable[n] = c >>> 0;
100
+ }
101
+ }
102
+ let crc = 0xffffffff;
103
+ for (const byte of bytes)
104
+ crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
105
+ return (crc ^ 0xffffffff) >>> 0;
106
+ }
107
+ /** A real PNG of two flat colours (sky over ground), stored uncompressed: a
108
+ * zlib stream of one stored block, so no compressor is needed. */
109
+ function pngOf(width, height, hue) {
110
+ const sky = rgbOf(hue, 0.55, 0.62);
111
+ const ground = rgbOf(hue, 0.45, 0.34);
112
+ const raw = new Uint8Array(height * (1 + width * 3));
113
+ for (let y = 0; y < height; y += 1) {
114
+ const colour = y < height * 0.6 ? sky : ground;
115
+ const at = y * (1 + width * 3);
116
+ for (let x = 0; x < width; x += 1)
117
+ raw.set(colour, at + 1 + x * 3);
118
+ }
119
+ let a = 1;
120
+ let b = 0;
121
+ for (const byte of raw) {
122
+ a = (a + byte) % 65521;
123
+ b = (b + a) % 65521;
124
+ }
125
+ const len = raw.length;
126
+ const idat = new Uint8Array(2 + 5 + len + 4);
127
+ idat.set([0x78, 0x01, 0x01, len & 0xff, len >>> 8, ~len & 0xff, (~len >>> 8) & 0xff]);
128
+ idat.set(raw, 7);
129
+ writeU32(idat, 7 + len, ((b << 16) | a) >>> 0);
130
+ const ihdr = new Uint8Array(13);
131
+ writeU32(ihdr, 0, width);
132
+ writeU32(ihdr, 4, height);
133
+ ihdr.set([8, 2, 0, 0, 0], 8);
134
+ const chunks = [chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", new Uint8Array(0))];
135
+ const out = new Uint8Array(8 + chunks.reduce((sum, each) => sum + each.length, 0));
136
+ out.set([137, 80, 78, 71, 13, 10, 26, 10]);
137
+ let offset = 8;
138
+ for (const each of chunks) {
139
+ out.set(each, offset);
140
+ offset += each.length;
141
+ }
142
+ return out;
143
+ }
144
+ function chunk(type, data) {
145
+ const out = new Uint8Array(12 + data.length);
146
+ writeU32(out, 0, data.length);
147
+ for (let i = 0; i < 4; i += 1)
148
+ out[4 + i] = type.charCodeAt(i);
149
+ out.set(data, 8);
150
+ writeU32(out, 8 + data.length, crc32(out.subarray(4, 8 + data.length)));
151
+ return out;
152
+ }
153
+ function writeU32(bytes, at, value) {
154
+ bytes[at] = (value >>> 24) & 0xff;
155
+ bytes[at + 1] = (value >>> 16) & 0xff;
156
+ bytes[at + 2] = (value >>> 8) & 0xff;
157
+ bytes[at + 3] = value & 0xff;
158
+ }
159
+ function rgbOf(hue, saturation, lightness) {
160
+ const k = (n) => (n + hue / 30) % 12;
161
+ const amount = saturation * Math.min(lightness, 1 - lightness);
162
+ const channel = (n) => Math.round(255 * (lightness - amount * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))));
163
+ return [channel(0), channel(8), channel(4)];
164
+ }
165
+ /** A picture's address: a tile drawn from its digest, inline, as the room's
166
+ * own demo draws its pictures. */
167
+ function placeholderSvg(digest) {
168
+ const hue = (Number.parseInt(digest.slice(0, 2), 16) * 1.4).toFixed(0);
169
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 10"><rect width="16" height="10" fill="hsl(${hue} 55% 55%)"/><circle cx="11" cy="3.5" r="1.6" fill="hsl(${hue} 60% 85%)"/><path d="M0 10 6 4l4 4 2-2 4 4z" fill="hsl(${hue} 45% 35%)"/></svg>`;
170
+ }
171
+ function rowOf(session, body, kind, group, at) {
172
+ const ordinal = session.rows.length + 1;
173
+ const timelineId = `${session.id}-r${ordinal}`;
174
+ const row = {
175
+ timeline_id: timelineId, session_id: session.id, ordinal,
176
+ group: { id: kind === "human_turn" ? timelineId : group, kind, derivation: "native" },
177
+ response: null, block_index: null, native_id: null, parent_native_id: null, at, model: null, effort: null, body,
178
+ parent_tool_native_id: null, usage: NO_USAGE, provenance: PROVENANCE,
179
+ };
180
+ session.rows.push(row);
181
+ return row;
182
+ }
183
+ function toolBody(session, name, action, status, mcp, attachments) {
184
+ return {
185
+ type: "tool_use",
186
+ tool: {
187
+ correlation: { key: `${session.id}-k${session.rows.length + 1}`, derivation: "native_id" },
188
+ native: { id: null, namespace: mcp === null ? null : "mcp", name, provider: mcp },
189
+ status: { value: status, basis: "native_state" },
190
+ action,
191
+ ...(attachments.length === 0 ? {} : { attachments: [...attachments] }),
192
+ failure: status === "failed" ? { kind: "exit_non_zero", summary: "Exited with 1", diagnostic: null } : null,
193
+ timing: null,
194
+ },
195
+ };
196
+ }
197
+ const readOf = (path) => ({
198
+ type: "file_read", targets: [{ resource: { type: "file", path, resolved: true }, range: null, media_kind: null }],
199
+ outcome: { truncated: false },
200
+ });
201
+ const shellOf = (command, finished) => ({
202
+ type: "shell", command: { type: "inline", text: command }, cwd: null, timeout_ms: null, background: false,
203
+ outcome: finished ? { exit_code: 0, signal: null, process_id: null } : null,
204
+ });
205
+ const editOf = (path) => ({
206
+ type: "file_change",
207
+ changes: [{ operation: "update", path: { type: "file", path, resolved: true }, destination: null, diff: null, lines_added: 4, lines_removed: 2 }],
208
+ });
209
+ const searchOf = (query) => ({
210
+ type: "file_search", query, mode: "content", roots: [], filters: [],
211
+ outcome: { match_count: 2, file_count: 2, paths: [], total_paths: 2 },
212
+ });
213
+ const noteOf = (subject) => ({
214
+ type: "external", provider: "notes", operation: "add", subject, fields: [], resources: [],
215
+ });
216
+ const sendOf = (count) => ({
217
+ type: "artifact", operation: "send", artifact_kind: "image", name: null,
218
+ description: { type: "inline", text: count === 1 ? "The picture" : "The pictures" }, resources: [], media: null,
219
+ });
220
+ const askOf = (prompt) => ({
221
+ type: "question",
222
+ questions: [{ id: "q1", prompt: { type: "inline", text: prompt }, header: null, allow_multiple: false, options: [
223
+ { id: "a", label: "Yes", description: null }, { id: "b", label: "No", description: null },
224
+ ] }],
225
+ answers: [{ question_id: "q1", values: [{ type: "inline", text: "Yes" }] }],
226
+ });
227
+ /* ── a turn, read from its rows as the daemon reads it ───────────────────── */
228
+ function isOpener(row) {
229
+ return row.body.type === "user" || row.group.kind === "human_turn" || row.group.kind === "parent_invocation";
230
+ }
231
+ function attachmentsOf(row) {
232
+ return row.body.type === "tool_use" ? row.body.tool.attachments ?? [] : [];
233
+ }
234
+ function emptyDigest() {
235
+ return { tools: 0, mcp: new Map(), kinds: new Map(), thoughts: 0, failed: 0, running: 0, firstAt: null, lastAt: null };
236
+ }
237
+ function count(digest, row) {
238
+ if (row.at !== null) {
239
+ digest.firstAt = digest.firstAt === null ? row.at : Math.min(digest.firstAt, row.at);
240
+ digest.lastAt = digest.lastAt === null ? row.at : Math.max(digest.lastAt, row.at);
241
+ }
242
+ const body = row.body;
243
+ if (body.type === "thinking")
244
+ digest.thoughts += 1;
245
+ if (body.type === "notice" && body.notice.type === "runtime_error")
246
+ digest.failed += 1;
247
+ if (body.type !== "tool_use")
248
+ return;
249
+ const tool = body.tool;
250
+ digest.tools += 1;
251
+ digest.kinds.set(tool.action.type, (digest.kinds.get(tool.action.type) ?? 0) + 1);
252
+ if (tool.native.namespace === "mcp" && tool.native.provider !== null) {
253
+ digest.mcp.set(tool.native.provider, (digest.mcp.get(tool.native.provider) ?? 0) + 1);
254
+ }
255
+ const status = tool.status.value;
256
+ if (status === "failed" || status === "denied" || status === "timed_out")
257
+ digest.failed += 1;
258
+ if (status === "pending" || status === "running")
259
+ digest.running += 1;
260
+ }
261
+ const mcpOf = (digest) => [...digest.mcp].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([server, calls]) => ({ server, calls }));
262
+ const kindsOf = (digest) => [...digest.kinds].map(([kind, n]) => ({ kind, count: n }));
263
+ function runOf(rows) {
264
+ const digest = emptyDigest();
265
+ const media = [];
266
+ for (const row of rows) {
267
+ count(digest, row);
268
+ for (const attachment of attachmentsOf(row))
269
+ media.push({ timeline_id: row.timeline_id, attachment });
270
+ }
271
+ return {
272
+ first_ordinal: rows[0].ordinal, last_ordinal: rows[rows.length - 1].ordinal,
273
+ first_at: digest.firstAt, last_at: digest.lastAt, tools: digest.tools, mcp: mcpOf(digest), kinds: kindsOf(digest),
274
+ thoughts: digest.thoughts, failed: digest.failed, running: digest.running,
275
+ media: media.slice(-RUN_MEDIA_MAX), media_omitted: Math.max(0, media.length - RUN_MEDIA_MAX),
276
+ };
277
+ }
278
+ function stateOf(session, index, end) {
279
+ if (end !== null && end.body.type === "notice" && end.body.notice.type === "turn_ended") {
280
+ return { state: end.body.notice.outcome, reason: end.body.notice.reason, at: end.at };
281
+ }
282
+ const state = index === session.turns.length - 1 ? "open" : session.lastEnded > index ? "cut_off" : "unknown";
283
+ return { state, reason: null, at: null };
284
+ }
285
+ function bodyOf(session, index) {
286
+ const turn = session.turns[index];
287
+ if (turn.body !== null)
288
+ return turn.body;
289
+ const rows = session.rows.slice(turn.first - 1, turn.last);
290
+ const opener = rows[0];
291
+ const prompt = isOpener(opener) ? opener : null;
292
+ const parts = [];
293
+ const digest = emptyDigest();
294
+ let run = [];
295
+ let end = null;
296
+ const closeRun = () => {
297
+ if (run.length > 0)
298
+ parts.push({ kind: "run", run: runOf(run) });
299
+ run = [];
300
+ };
301
+ for (const row of rows) {
302
+ count(digest, row);
303
+ if (row === prompt)
304
+ continue;
305
+ const body = row.body;
306
+ if (body.type === "notice" && body.notice.type === "turn_ended") {
307
+ end = row;
308
+ continue;
309
+ }
310
+ const whole = body.type === "agent" ? "reply"
311
+ : (body.type === "tool_use" && body.tool.action.type === "question")
312
+ || (body.type === "notice" && body.notice.type === "permission_requested") ? "request"
313
+ : body.type === "summary" && body.purpose === "compaction" ? "compaction"
314
+ : null;
315
+ if (whole === null) {
316
+ run.push(row);
317
+ continue;
318
+ }
319
+ closeRun();
320
+ parts.push({ kind: whole, row });
321
+ }
322
+ closeRun();
323
+ turn.body = {
324
+ key: turn.key, session_id: session.id, first_ordinal: turn.first, last_ordinal: turn.last, prompt,
325
+ parts: parts.slice(-PARTS_MAX), parts_omitted: Math.max(0, parts.length - PARTS_MAX),
326
+ tools: digest.tools, mcp: mcpOf(digest), kinds: kindsOf(digest), thoughts: digest.thoughts, failed: digest.failed,
327
+ running: digest.running, first_at: digest.firstAt, last_at: digest.lastAt, outcome: stateOf(session, index, end),
328
+ };
329
+ return turn.body;
330
+ }
331
+ /** At most 160 bytes of the prompt, cut on a character boundary. */
332
+ function previewOf(prompt) {
333
+ if (prompt === null || prompt.body.type !== "user" || prompt.body.text === null)
334
+ return null;
335
+ const text = prompt.body.text.type === "inline" ? prompt.body.text.text : prompt.body.text.preview;
336
+ const encoder = new TextEncoder();
337
+ let bytes = 0;
338
+ let out = "";
339
+ for (const char of text) {
340
+ bytes += encoder.encode(char).length;
341
+ if (bytes > PREVIEW_MAX_BYTES)
342
+ break;
343
+ out += char;
344
+ }
345
+ return out === "" ? null : out;
346
+ }
347
+ function markOf(session, index) {
348
+ const turn = session.turns[index];
349
+ if (turn.mark !== null)
350
+ return turn.mark;
351
+ const body = bodyOf(session, index);
352
+ let media = 0;
353
+ for (const row of session.rows.slice(turn.first - 1, turn.last))
354
+ media += attachmentsOf(row).length;
355
+ turn.mark = {
356
+ key: turn.key, first_ordinal: turn.first, last_ordinal: turn.last, first_at: body.first_at, last_at: body.last_at,
357
+ preview: previewOf(body.prompt), state: body.outcome.state, media,
358
+ };
359
+ return turn.mark;
360
+ }
361
+ /* ── the demo ────────────────────────────────────────────────────────────── */
362
+ function notFound(message) {
363
+ return new ApiRequestError(404, "not_found", message);
364
+ }
365
+ function badLimit(limit, most) {
366
+ return Number.isInteger(limit) && limit >= 1 && limit <= most
367
+ ? null
368
+ : new ApiRequestError(400, "bad_request", `limit must be between 1 and ${most}`);
369
+ }
370
+ export function createConversationDemo(o = {}) {
371
+ const turnCount = Math.max(0, Math.floor(o.turns ?? 12));
372
+ const sessionCount = Math.max(1, Math.floor(o.sessions ?? 1));
373
+ const media = o.media ?? false;
374
+ const live = o.live ?? false;
375
+ const seed = o.seed ?? 1;
376
+ const now = o.now ?? DEFAULT_NOW;
377
+ const next = seeded(seed);
378
+ const members = new Map();
379
+ const sessions = Array.from({ length: sessionCount }, (_, index) => ({
380
+ id: `c${index + 1}`, index, rows: [], turns: [], lastEnded: -1,
381
+ }));
382
+ const byId = new Map(sessions.map((session) => [session.id, session]));
383
+ let generation = 1;
384
+ let pictures = 0;
385
+ let runs = 0;
386
+ let appended = 0;
387
+ const picture = () => {
388
+ pictures += 1;
389
+ const digest = digestOf(`conversation:${seed}:picture:${pictures}`);
390
+ const [width, height] = pictures % 3 === 0 ? [20, 32] : [32, 20];
391
+ const bytes = pngOf(width, height, Number.parseInt(digest.slice(0, 2), 16) * 1.4);
392
+ members.set(digest, { bytes, text: null });
393
+ const asset = { url: `/api/assets/${digest}.png`, digest, media_type: "image/png", byte_len: bytes.length };
394
+ return {
395
+ id: String(pictures), kind: "image", label: null, name: `picture-${pictures}.png`, media_type: "image/png",
396
+ byte_len: bytes.length, source: { type: "asset", asset }, dimensions: { width, height }, message_ranges: [],
397
+ };
398
+ };
399
+ const summary = (turn) => {
400
+ const text = `The conversation so far, in short: ${pick(PROMPTS, next).toLowerCase()} It was done, and checked.`;
401
+ const bytes = new TextEncoder().encode(text);
402
+ const digest = digestOf(`conversation:${seed}:summary:${turn}`);
403
+ members.set(digest, { bytes, text });
404
+ const asset = { url: `/api/assets/${digest}.txt`, digest, media_type: "text/plain", byte_len: bytes.length };
405
+ return { type: "summary", purpose: "compaction", text: { type: "member", asset, preview: text.slice(0, 48), byte_len: bytes.length } };
406
+ };
407
+ /**
408
+ * One turn's rows from `at`; answers its span in ms. A turn is a prompt and
409
+ * one of four shapes: a reply; a run, then a reply; a reply, a run and a
410
+ * second reply; a run, a question, then a reply. Now and then a compaction
411
+ * opens it. Most turns finish; some fail (no reply, the end says why), some
412
+ * are stopped (no reply), and a few record no end (cut off). The chain's
413
+ * newest turn always records an end, unless it is left at work (`open`).
414
+ */
415
+ const writeTurn = (session, turn, at, prompt, open, newest) => {
416
+ const first = session.rows.length + 1;
417
+ const group = `${session.id}-g${session.turns.length + 1}`;
418
+ let clock = at;
419
+ const tick = () => (clock += 15_000 + Math.floor(next() * 45_000));
420
+ rowOf(session, { type: "user", text: { type: "inline", text: prompt }, attachments: [] }, "human_turn", group, at);
421
+ if (turn % 11 === 7)
422
+ rowOf(session, summary(turn), "system_cycle", group, tick());
423
+ const tool = (name, action, status = "succeeded", mcp = null, attachments = []) => rowOf(session, toolBody(session, name, action, status, mcp, attachments), "agent_cycle", group, tick());
424
+ const runRows = (failing) => {
425
+ for (let i = Math.floor(next() * 3); i > 0; i -= 1) {
426
+ rowOf(session, { type: "thinking", text: { type: "inline", text: pick(THOUGHTS, next) } }, "agent_cycle", group, tick());
427
+ }
428
+ for (let i = 1 + Math.floor(next() * 6); i > 0; i -= 1) {
429
+ const roll = next();
430
+ if (roll < 0.3)
431
+ tool("Read", readOf(pick(FILES, next)));
432
+ else if (roll < 0.55)
433
+ tool("Bash", shellOf(pick(COMMANDS, next), true), failing && i === 1 ? "failed" : "succeeded");
434
+ else if (roll < 0.75)
435
+ tool("Edit", editOf(pick(FILES, next)));
436
+ else if (roll < 0.9)
437
+ tool("Grep", searchOf("oldName"));
438
+ else
439
+ tool("mcp__notes__add", noteOf("a note"), "succeeded", "notes");
440
+ }
441
+ // Pictures by a fixed rhythm, so both draws appear early whatever the
442
+ // seed: one picture on every third run, several on every fifth.
443
+ runs += 1;
444
+ const shown = !media ? 0 : runs % 5 === 2 ? 2 + (runs % 3) : runs % 3 === 1 ? 1 : 0;
445
+ if (shown > 0)
446
+ tool("SendFile", sendOf(shown), "succeeded", null, Array.from({ length: shown }, picture));
447
+ };
448
+ if (open) {
449
+ runRows(false);
450
+ tool("Bash", shellOf(pick(COMMANDS, next), false), "running");
451
+ }
452
+ else {
453
+ const shape = next();
454
+ const ending = next();
455
+ const outcome = ending < 0.86 || newest ? "finished" : ending < 0.92 ? "failed" : ending < 0.96 ? "stopped" : null;
456
+ const reply = (last) => {
457
+ if (last && (outcome === "failed" || outcome === "stopped"))
458
+ return;
459
+ rowOf(session, { type: "agent", text: { type: "inline", text: pick(REPLIES, next) }, attachments: [], citations: [] }, "agent_cycle", group, tick());
460
+ };
461
+ if (shape < 0.25)
462
+ reply(true);
463
+ else if (shape < 0.65) {
464
+ runRows(next() < 0.15);
465
+ reply(true);
466
+ }
467
+ else if (shape < 0.85) {
468
+ reply(false);
469
+ runRows(false);
470
+ reply(true);
471
+ }
472
+ else {
473
+ runRows(false);
474
+ tool("AskUserQuestion", askOf("Should the old file stay?"));
475
+ reply(true);
476
+ }
477
+ if (outcome !== null) {
478
+ const reason = outcome === "failed" ? FAILURE : null;
479
+ rowOf(session, { type: "notice", notice: { type: "turn_ended", outcome, reason } }, "system_cycle", group, tick());
480
+ session.lastEnded = session.turns.length;
481
+ }
482
+ }
483
+ session.turns.push({ key: `${session.id}-r${first}`, first, last: session.rows.length, body: null, mark: null });
484
+ return clock - at;
485
+ };
486
+ // The chain: turns shared out over the sessions, written forward from 0,
487
+ // then moved so the newest turn begins at `now`.
488
+ const starts = [];
489
+ let clock = 0;
490
+ let written = 0;
491
+ for (const session of sessions) {
492
+ const share = Math.floor(((session.index + 1) * turnCount) / sessionCount) - Math.floor((session.index * turnCount) / sessionCount);
493
+ if (session.index > 0)
494
+ clock += HOUR + Math.floor(next() * 2 * HOUR);
495
+ for (let i = 0; i < share; i += 1) {
496
+ written += 1;
497
+ const isNewest = written === turnCount;
498
+ starts.push(clock);
499
+ clock += writeTurn(session, written, clock, pick(PROMPTS, next), live && isNewest, isNewest);
500
+ clock += next() < 0.08 ? 14 * HOUR + Math.floor(next() * 26 * HOUR) : 2 * MINUTE + Math.floor(next() * 38 * MINUTE);
501
+ }
502
+ }
503
+ const shift = now - (starts[starts.length - 1] ?? 0);
504
+ for (const session of sessions) {
505
+ for (const [index, row] of session.rows.entries())
506
+ session.rows[index] = { ...row, at: row.at === null ? null : row.at + shift };
507
+ }
508
+ const subscriptions = new Set();
509
+ const watermarkOf = (session) => `${generation}.${session.index + 1}`;
510
+ const sessionOf = (sessionId) => {
511
+ const session = byId.get(sessionId);
512
+ if (session === undefined)
513
+ throw notFound(`No session ${sessionId} in this conversation`);
514
+ return session;
515
+ };
516
+ const outlineOf = (session) => ({
517
+ session_id: session.id, watermark: watermarkOf(session), withheld: false,
518
+ turns: session.turns.map((_, index) => markOf(session, index)),
519
+ });
520
+ const newest = (session, limit) => {
521
+ const from = Math.max(0, session.turns.length - limit);
522
+ return session.turns.slice(from).map((_, i) => bodyOf(session, from + i));
523
+ };
524
+ const snapshot = (subscription) => {
525
+ const session = byId.get(subscription.sessionId);
526
+ if (session === undefined || !subscription.open)
527
+ return;
528
+ subscription.handlers.onSnapshot?.({
529
+ turns: newest(session, subscription.limit), outline: subscription.outline ? outlineOf(session) : null,
530
+ watermark: watermarkOf(session), moreBefore: session.turns.length > subscription.limit, withheld: false,
531
+ });
532
+ };
533
+ const client = {
534
+ subscribeTurns(sessionId, handlers, options) {
535
+ const subscription = {
536
+ sessionId, handlers, limit: Math.max(1, Math.min(100, Math.floor(options?.limit ?? 20))),
537
+ outline: options?.outline ?? false, open: true,
538
+ };
539
+ queueMicrotask(() => {
540
+ if (!subscription.open)
541
+ return;
542
+ if (!byId.has(sessionId)) {
543
+ handlers.onError?.({ code: "not_found", message: `No session ${sessionId} in this conversation` });
544
+ return;
545
+ }
546
+ subscriptions.add(subscription);
547
+ handlers.onStatus?.("live");
548
+ snapshot(subscription);
549
+ });
550
+ return {
551
+ close() {
552
+ subscription.open = false;
553
+ subscriptions.delete(subscription);
554
+ },
555
+ };
556
+ },
557
+ async turnOutline(sessionId, signal) {
558
+ signal?.throwIfAborted();
559
+ return outlineOf(sessionOf(sessionId));
560
+ },
561
+ async turns(sessionId, options, signal) {
562
+ signal?.throwIfAborted();
563
+ const session = sessionOf(sessionId);
564
+ const limit = options?.limit ?? 20;
565
+ const refused = badLimit(limit, 100);
566
+ if (refused !== null)
567
+ throw refused;
568
+ if (options?.watermark !== undefined && options.watermark !== watermarkOf(session)) {
569
+ throw new CursorExpiredError("The session was read again since that page: read it from the newest");
570
+ }
571
+ const before = options?.before ?? Number.POSITIVE_INFINITY;
572
+ const since = options?.since ?? Number.NEGATIVE_INFINITY;
573
+ const within = [];
574
+ for (const [index, turn] of session.turns.entries())
575
+ if (turn.first < before && turn.first >= since)
576
+ within.push(index);
577
+ const shown = within.slice(-limit);
578
+ return {
579
+ session_id: session.id, watermark: watermarkOf(session), withheld: false,
580
+ turns: shown.map((index) => bodyOf(session, index)), more_before: within.length > shown.length,
581
+ };
582
+ },
583
+ async turnRows(sessionId, key, options, signal) {
584
+ signal?.throwIfAborted();
585
+ const session = sessionOf(sessionId);
586
+ const turn = session.turns.find((each) => each.key === key);
587
+ if (turn === undefined)
588
+ throw notFound(`No turn ${key} in session ${sessionId}`);
589
+ const limit = options?.limit ?? 200;
590
+ const refused = badLimit(limit, 1000);
591
+ if (refused !== null)
592
+ throw refused;
593
+ const low = Math.max(turn.first, options?.first ?? turn.first);
594
+ let high = Math.min(turn.last, options?.last ?? turn.last);
595
+ if (options?.cursor !== undefined) {
596
+ const [mark, before] = options.cursor.split("|");
597
+ const below = Number(before);
598
+ if (before === undefined || !Number.isInteger(below))
599
+ throw new ApiRequestError(400, "bad_request", "That cursor is not one this conversation gave");
600
+ if (mark !== watermarkOf(session))
601
+ throw new CursorExpiredError("The session was read again since that page: read it from the newest");
602
+ high = Math.min(high, below - 1);
603
+ }
604
+ const rows = low > high ? [] : session.rows.slice(low - 1, high);
605
+ const entries = rows.slice(-limit);
606
+ const more = entries.length < rows.length;
607
+ return {
608
+ entries, watermark: watermarkOf(session), cursor: more ? `${watermarkOf(session)}|${entries[0].ordinal}` : null,
609
+ };
610
+ },
611
+ async readAsset(asset, signal) {
612
+ signal?.throwIfAborted();
613
+ const member = members.get(asset.digest);
614
+ if (member === undefined)
615
+ throw notFound("This conversation holds no such member");
616
+ return member.bytes.slice();
617
+ },
618
+ async readTextAsset(asset, signal) {
619
+ signal?.throwIfAborted();
620
+ const member = members.get(asset.digest);
621
+ if (member === undefined)
622
+ throw notFound("This conversation holds no such member");
623
+ return member.text ?? new TextDecoder().decode(member.bytes);
624
+ },
625
+ };
626
+ // A client over a daemon with no turn reads: the parts' two reads, nothing else.
627
+ const withoutTurns = { readAsset: client.readAsset, readTextAsset: client.readTextAsset };
628
+ let unsupported = false;
629
+ const leases = new Map();
630
+ const sessionPort = {
631
+ open(sessionId) {
632
+ leases.set(sessionId, (leases.get(sessionId) ?? 0) + 1);
633
+ return unsupported ? withoutTurns : client;
634
+ },
635
+ close(sessionId) {
636
+ const held = leases.get(sessionId) ?? 0;
637
+ if (held === 0)
638
+ throw new Error(`The demo's port closed ${sessionId}, which it had not opened`);
639
+ if (held === 1)
640
+ leases.delete(sessionId);
641
+ else
642
+ leases.set(sessionId, held - 1);
643
+ },
644
+ };
645
+ const assets = {
646
+ imageAssetUrl: (asset) => `data:image/svg+xml,${encodeURIComponent(placeholderSvg(asset.digest))}`,
647
+ attachmentAssetUrl: (asset) => asset.url,
648
+ };
649
+ return {
650
+ sessionPort,
651
+ assets,
652
+ chain: sessions.map((session) => session.id),
653
+ append(text) {
654
+ const session = sessions[sessions.length - 1];
655
+ appended += 1;
656
+ const before = session.turns.length - 1;
657
+ // The turns whose state an end may change: every one after the last
658
+ // recorded end (unknown, or open), and the turn before the new one.
659
+ const from = Math.max(0, Math.min(before, session.lastEnded + 1));
660
+ const last = session.rows[session.rows.length - 1];
661
+ let at = (last?.at ?? now) + MINUTE;
662
+ // The newest turn ends, if it was still at work: its running tool
663
+ // finishes, it answers if it had not, and its end is recorded.
664
+ if (before >= 0 && session.lastEnded < before) {
665
+ const turn = session.turns[before];
666
+ const group = session.rows[turn.last - 1].group.id;
667
+ for (let ordinal = turn.first; ordinal <= turn.last; ordinal += 1) {
668
+ const row = session.rows[ordinal - 1];
669
+ if (row.body.type === "tool_use" && row.body.tool.status.value === "running") {
670
+ session.rows[ordinal - 1] = { ...row, body: { ...row.body, tool: { ...row.body.tool, status: { value: "succeeded", basis: "native_state" } } } };
671
+ }
672
+ }
673
+ const rows = session.rows.slice(turn.first - 1, turn.last);
674
+ if (!rows.some((row) => row.body.type === "agent")) {
675
+ rowOf(session, { type: "agent", text: { type: "inline", text: REPLIES[(seed + appended) % REPLIES.length] }, attachments: [], citations: [] }, "agent_cycle", group, at);
676
+ at += 20_000;
677
+ }
678
+ rowOf(session, { type: "notice", notice: { type: "turn_ended", outcome: "finished", reason: null } }, "system_cycle", group, at);
679
+ at += MINUTE;
680
+ turn.last = session.rows.length;
681
+ session.lastEnded = before;
682
+ }
683
+ // The new turn: the person's words and a reply, left open while live.
684
+ const first = session.rows.length + 1;
685
+ const group = `${session.id}-g${session.turns.length + 1}`;
686
+ rowOf(session, { type: "user", text: { type: "inline", text }, attachments: [] }, "human_turn", group, at);
687
+ rowOf(session, { type: "agent", text: { type: "inline", text: REPLIES[(seed + appended + 3) % REPLIES.length] }, attachments: [], citations: [] }, "agent_cycle", group, at + 20_000);
688
+ if (!live)
689
+ rowOf(session, { type: "notice", notice: { type: "turn_ended", outcome: "finished", reason: null } }, "system_cycle", group, at + 25_000);
690
+ session.turns.push({ key: `${session.id}-r${first}`, first, last: session.rows.length, body: null, mark: null });
691
+ if (!live)
692
+ session.lastEnded = session.turns.length - 1;
693
+ // An arriving opener changes the turn before it and the new one, oldest
694
+ // first, one frame each.
695
+ const told = [];
696
+ for (let index = from; index < session.turns.length; index += 1) {
697
+ session.turns[index].body = null;
698
+ session.turns[index].mark = null;
699
+ told.push(bodyOf(session, index));
700
+ }
701
+ for (const subscription of [...subscriptions]) {
702
+ if (subscription.sessionId !== session.id || !subscription.open)
703
+ continue;
704
+ for (const turn of told)
705
+ subscription.handlers.onTurn?.(turn);
706
+ }
707
+ },
708
+ reset() {
709
+ generation += 1;
710
+ for (const subscription of [...subscriptions]) {
711
+ if (!subscription.open)
712
+ continue;
713
+ subscription.handlers.onReset?.();
714
+ subscription.handlers.onStatus?.("resyncing");
715
+ snapshot(subscription);
716
+ subscription.handlers.onStatus?.("live");
717
+ }
718
+ },
719
+ unsupported() {
720
+ unsupported = true;
721
+ },
722
+ };
723
+ }