@miadi/companion-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/opener.tsx ADDED
@@ -0,0 +1,268 @@
1
+ "use client"
2
+
3
+ /**
4
+ * "Open Mia for this episode": the door to `tide companion open`, for any page.
5
+ *
6
+ * Pressing Enter (or "show plan") asks for the plan and says it in plain words. The gold
7
+ * button carries out that plan, and only that plan: changing the episode, the seat or the
8
+ * archive choice asks again. Opening takes minutes and a proxy may drop the request before
9
+ * tide answers, so while it runs the opener also asks for the plan every few seconds. tide
10
+ * answering "already listening" is the seat being there, whichever answer arrives first.
11
+ *
12
+ * A host that knows its episode passes `episode`, and the number field is not shown. Moved
13
+ * from Miadi `components/tide/companion-opener.tsx` (jgwill/Miadi#714, jgwill/Miadi#737).
14
+ */
15
+
16
+ import { useEffect, useRef, useState, type CSSProperties } from "react"
17
+ import {
18
+ COMPANION_SEATS,
19
+ LISTENING,
20
+ NOTHING_TO_RUN,
21
+ sayFault,
22
+ sayPlan,
23
+ seatLabel,
24
+ type CompanionAnswer,
25
+ type CompanionPlan,
26
+ type CompanionTransport,
27
+ } from "./seat.js"
28
+
29
+ const POLL_MS = 5000
30
+ const RUN_LIMIT_MS = 8 * 60_000
31
+
32
+ export interface CompanionOpenerTheme {
33
+ accent: string
34
+ background: string
35
+ field: string
36
+ text: string
37
+ textDim: string
38
+ danger: string
39
+ success: string
40
+ warning: string
41
+ mono: string
42
+ }
43
+
44
+ export const OPENER_THEME: CompanionOpenerTheme = {
45
+ accent: "#d4a843",
46
+ background: "#16140e",
47
+ field: "#0e0d09",
48
+ text: "#e8e0c8",
49
+ textDim: "#a89f88",
50
+ danger: "#f87171",
51
+ success: "#4ade80",
52
+ warning: "#e0a030",
53
+ mono: "monospace",
54
+ }
55
+
56
+ export interface CompanionOpenerProps {
57
+ transport: CompanionTransport
58
+ /** The episode (number or vessel folder) when the host knows it; otherwise a number field asks. */
59
+ episode?: string
60
+ /** The seats to offer, the first chosen. Default: the seats tide opens today. */
61
+ seats?: readonly string[]
62
+ /** Where the seat's pane is shown, for the "go to" link. No link when absent or null. */
63
+ paneHref?: (plan: CompanionPlan) => string | null
64
+ /** Told once the seat listens. */
65
+ onOpened?: (plan: CompanionPlan) => void
66
+ theme?: Partial<CompanionOpenerTheme>
67
+ style?: CSSProperties
68
+ }
69
+
70
+ export function CompanionOpener({ transport, episode: fixedEpisode, seats = COMPANION_SEATS, paneHref, onOpened, theme, style }: CompanionOpenerProps) {
71
+ const t = { ...OPENER_THEME, ...theme }
72
+ const [typed, setTyped] = useState("")
73
+ const [seat, setSeat] = useState(seats[0] ?? "mia")
74
+ const [archive, setArchive] = useState(false)
75
+ const [busy, setBusy] = useState<"plan" | "run" | null>(null)
76
+ const [planned, setPlanned] = useState<{ key: string; answer: CompanionAnswer } | null>(null)
77
+ const [ran, setRan] = useState<{ answer: CompanionAnswer; listening: boolean } | null>(null)
78
+ const [elapsed, setElapsed] = useState(0)
79
+ const runId = useRef(0)
80
+
81
+ const ep = (fixedEpisode ?? typed).trim()
82
+ const who = seatLabel(seat)
83
+ const key = `${ep}|${seat}|${archive}`
84
+ const current = planned && planned.key === key ? planned.answer : null
85
+ const plan = current?.plan ?? null
86
+ const canRun = !!plan?.state && !NOTHING_TO_RUN.includes(plan.state) && busy === null && !ran
87
+ const stale = planned !== null && planned.key !== key && ep !== ""
88
+
89
+ useEffect(() => {
90
+ if (busy !== "run") return
91
+ const t0 = Date.now()
92
+ const id = setInterval(() => setElapsed(Math.round((Date.now() - t0) / 1000)), 1000)
93
+ return () => clearInterval(id)
94
+ }, [busy])
95
+
96
+ async function askPlan(next: { seat?: string; archive?: boolean } = {}) {
97
+ const forSeat = next.seat ?? seat
98
+ const forArchive = next.archive ?? archive
99
+ if (!ep || busy) return
100
+ setBusy("plan")
101
+ setRan(null)
102
+ const answer = await transport.open({ episode: ep, seat: forSeat, archive: forArchive })
103
+ setPlanned({ key: `${ep}|${forSeat}|${forArchive}`, answer })
104
+ setBusy(null)
105
+ }
106
+
107
+ async function run() {
108
+ if (!canRun) return
109
+ const id = ++runId.current
110
+ const body = { episode: ep, seat, archive }
111
+ setBusy("run")
112
+ setElapsed(0)
113
+ const started = Date.now()
114
+ let done = false
115
+ const finish = (answer: CompanionAnswer, listening: boolean) => {
116
+ if (done || runId.current !== id) return
117
+ done = true
118
+ setRan({ answer, listening })
119
+ setBusy(null)
120
+ if (listening || answer.plan?.executed) {
121
+ const p = answer.plan ?? plan
122
+ if (p) onOpened?.(p)
123
+ }
124
+ }
125
+ void transport.open({ ...body, run: true }).then((answer) => {
126
+ // The poll can see the seat listening before tide finishes typing the starter prompt.
127
+ // When tide's own answer arrives after that, it replaces the poll's so the steps show.
128
+ if (done && runId.current === id && answer.plan?.executed) { setRan({ answer, listening: true }); return }
129
+ // tide answered (done, refused, failed) or the route refused: that is the outcome.
130
+ // A dropped connection or a proxy timeout is not: the poll below still watches for the seat.
131
+ if (answer.exitCode !== undefined || (answer.status !== undefined && answer.status < 500)) finish(answer, false)
132
+ })
133
+ while (!done && runId.current === id && Date.now() - started < RUN_LIMIT_MS) {
134
+ await new Promise((r) => setTimeout(r, POLL_MS))
135
+ if (done) return
136
+ const look = await transport.open({ episode: ep, seat })
137
+ if (look.plan?.state === LISTENING) finish(look, true)
138
+ }
139
+ finish({ error: `No answer after ${RUN_LIMIT_MS / 60_000} minutes. Look for ${plan?.session} in the panes.` }, false)
140
+ }
141
+
142
+ const shown: CompanionAnswer | null = ran?.answer ?? current
143
+ const shownPlan = shown?.plan ?? null
144
+ const faulted = shown && (shown.error || (shown.status && shown.status >= 400 && shown.status !== 409))
145
+ const openNow = ran && !faulted && (ran.listening || ran.answer.plan?.executed)
146
+ const pane = shownPlan && (openNow || shownPlan.state === LISTENING) ? (paneHref?.(shownPlan) ?? null) : null
147
+
148
+ const box: CSSProperties = {
149
+ padding: "12px 14px", border: `1px solid ${t.accent}55`, borderRadius: 8,
150
+ background: t.background, fontFamily: t.mono, fontSize: 13, color: t.textDim, ...style,
151
+ }
152
+ const primary: CSSProperties = {
153
+ background: t.accent, color: t.background, border: `1px solid ${t.accent}`, borderRadius: 6,
154
+ padding: "0 16px", minHeight: 40, fontFamily: t.mono, fontSize: 13, fontWeight: 700, cursor: "pointer",
155
+ }
156
+ const secondary: CSSProperties = {
157
+ background: "transparent", color: t.accent, border: `1px solid ${t.accent}`, borderRadius: 6,
158
+ padding: "0 14px", minHeight: 40, fontFamily: t.mono, fontSize: 13, cursor: "pointer",
159
+ }
160
+ const fieldId = `companion-episode-${seat}`
161
+
162
+ return (
163
+ <div style={box} data-companion-opener={fixedEpisode ? "episode" : "any"}>
164
+ <form
165
+ onSubmit={(e) => { e.preventDefault(); if (canRun && !stale) void run(); else void askPlan() }}
166
+ style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 8 }}
167
+ >
168
+ {fixedEpisode ? (
169
+ <span style={{ color: t.accent, fontWeight: 700 }}>Open {who} for this episode</span>
170
+ ) : (
171
+ <>
172
+ <label htmlFor={fieldId} style={{ color: t.accent, fontWeight: 700 }}>Open {who} for episode</label>
173
+ <input
174
+ id={fieldId}
175
+ value={typed}
176
+ onChange={(e) => { setTyped(e.target.value); setRan(null) }}
177
+ placeholder="339"
178
+ inputMode="numeric"
179
+ enterKeyHint="go"
180
+ autoComplete="off"
181
+ aria-label="episode number"
182
+ style={{ width: 90, minHeight: 40, background: t.field, color: t.text, border: `1px solid ${t.accent}88`,
183
+ borderRadius: 6, padding: "0 10px", fontFamily: t.mono, fontSize: 15 }}
184
+ />
185
+ </>
186
+ )}
187
+ {seats.length > 1 && (
188
+ <select
189
+ aria-label="companion seat"
190
+ value={seat}
191
+ disabled={busy !== null}
192
+ onChange={(e) => { setSeat(e.target.value); setRan(null); if (fixedEpisode) void askPlan({ seat: e.target.value }) }}
193
+ style={{ minHeight: 40, background: t.field, color: t.text, border: `1px solid ${t.accent}88`, borderRadius: 6, fontFamily: t.mono }}
194
+ >
195
+ {seats.map((s) => <option key={s} value={s}>{seatLabel(s)}</option>)}
196
+ </select>
197
+ )}
198
+ {canRun && !stale ? (
199
+ <button type="submit" style={primary}>
200
+ {plan?.state === "create" || plan?.state === "archive-then-create" ? "▶ open " : "▶ re-arm "}{plan?.session}
201
+ </button>
202
+ ) : (
203
+ <button type="submit" disabled={!ep || busy !== null} style={{ ...(ep ? primary : secondary), opacity: ep ? 1 : 0.75 }}>
204
+ {busy === "plan" ? "asking tide…" : busy === "run" ? `opening… ${elapsed}s` : "show plan ↵"}
205
+ </button>
206
+ )}
207
+ <label style={{ display: "inline-flex", alignItems: "center", gap: 6, color: t.textDim, fontSize: 12 }}
208
+ title="Only on your word: rename the existing session -arch-<yyMMddHHmm> and open a new one">
209
+ <input type="checkbox" checked={archive} disabled={busy !== null}
210
+ onChange={(e) => { setArchive(e.target.checked); void askPlan({ archive: e.target.checked }) }} />
211
+ archive the existing session
212
+ </label>
213
+ </form>
214
+
215
+ {busy === "run" && (
216
+ <div style={{ marginTop: 10, color: t.accent }}>
217
+ Opening {plan?.session}: starting {who}, arming the listener, sending the starter prompt. This takes a minute or two ({elapsed}s).
218
+ </div>
219
+ )}
220
+
221
+ {stale && busy === null && (
222
+ <div style={{ marginTop: 10, color: t.textDim }}>
223
+ Press Enter to see what opening {fixedEpisode ? "this episode" : `episode ${ep}`} will do.
224
+ </div>
225
+ )}
226
+
227
+ {shown && !stale && busy !== "run" && (
228
+ <div style={{ marginTop: 10, whiteSpace: "pre-wrap", wordBreak: "break-word", lineHeight: 1.5 }}>
229
+ {faulted ? <div style={{ color: t.danger }}>{sayFault(shown)}</div> : null}
230
+ {shown.status === 409 && shown.message ? <div style={{ color: t.danger }}>{shown.message}</div> : null}
231
+ {shownPlan && !faulted && (
232
+ <>
233
+ {shownPlan.episode?.title && !fixedEpisode && (
234
+ <div style={{ color: t.text }}>
235
+ episode {shownPlan.episode.number} · {shownPlan.episode.title}
236
+ </div>
237
+ )}
238
+ <div style={{ color: openNow ? t.success : t.text, marginTop: 2 }}>
239
+ {openNow ? `${who} is listening in ${shownPlan.session}.` : sayPlan(shownPlan, seat)}
240
+ </div>
241
+ {pane && (
242
+ <a href={pane} style={{ display: "inline-block", marginTop: 6, color: t.accent, textDecoration: "underline" }}>
243
+ go to {shownPlan.session} →
244
+ </a>
245
+ )}
246
+ {shownPlan.run?.warnings?.map((w) => <div key={w} style={{ color: t.warning }}>warning: {w}</div>)}
247
+ {(shownPlan.commands?.length || shownPlan.run?.steps?.length) ? (
248
+ <details style={{ marginTop: 6, color: t.textDim }}>
249
+ <summary style={{ cursor: "pointer" }}>{shownPlan.run ? "steps taken" : "steps tide will take"}</summary>
250
+ {shownPlan.run?.steps?.length
251
+ ? shownPlan.run.steps.map((s) => <div key={`${s.at}-${s.step}`}>{s.at.slice(11, 19)} {s.step}</div>)
252
+ : (
253
+ <ol style={{ margin: "4px 0 0 18px", padding: 0 }}>
254
+ {shownPlan.commands?.map((c) => <li key={c}>{c}</li>)}
255
+ </ol>
256
+ )}
257
+ {!ran && shownPlan.starter_prompt && canRun && (
258
+ <div style={{ marginTop: 4 }}>starter prompt: {shownPlan.starter_prompt}</div>
259
+ )}
260
+ </details>
261
+ ) : null}
262
+ </>
263
+ )}
264
+ </div>
265
+ )}
266
+ </div>
267
+ )
268
+ }
package/src/seat.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Opening a companion seat, as data: the plan tide answers (`tide companion open
3
+ * --format json`), the states it names, and the transport a host gives the opener.
4
+ *
5
+ * The opener never holds a URL. A host passes a transport: Miadi passes
6
+ * `httpCompanionTransport("/api/tide/companion")`, a terminal host can call tide.
7
+ * jgwill/Miadi#714 (the seat), jgwill/Miadi#737 (the seat as one capability).
8
+ */
9
+
10
+ export type CompanionPlan = {
11
+ /** The seat tide declares: its key, plugin and listener command. */
12
+ seat?: { key?: string; plugin?: string; listener?: string; launcher?: string; session_pattern?: string }
13
+ state?: string
14
+ session?: string
15
+ archive_name?: string | null
16
+ commands?: string[]
17
+ starter_prompt?: string
18
+ episode?: { number?: number; title?: string; folder?: string; path?: string }
19
+ pane?: { pane_id?: string; command?: string } | null
20
+ listener?: { state?: string }
21
+ executed?: boolean
22
+ run?: { steps?: { at: string; step: string }[]; warnings?: string[]; pane_id?: string | null }
23
+ }
24
+
25
+ export type CompanionAnswer = {
26
+ status?: number
27
+ exitCode?: number
28
+ plan?: CompanionPlan | null
29
+ message?: string
30
+ error?: string
31
+ }
32
+
33
+ export interface CompanionOpenRequest {
34
+ /** Episode number or vessel folder name. */
35
+ episode: string
36
+ /** Seat key; tide's default is `mia`. */
37
+ seat?: string
38
+ /** The person's word to rename the existing session and open a new one. */
39
+ archive?: boolean
40
+ /** Act on the plan; without it the answer is the plan. */
41
+ run?: boolean
42
+ }
43
+
44
+ /** How the opener reaches tide. A refusal is an answer with `status` and `error`, never a throw. */
45
+ export interface CompanionTransport {
46
+ open(request: CompanionOpenRequest): Promise<CompanionAnswer>
47
+ }
48
+
49
+ /** A transport over an HTTP route that takes the request as its JSON body (Miadi's `/api/tide/companion`). */
50
+ export function httpCompanionTransport(url: string, init: { headers?: Record<string, string> } = {}): CompanionTransport {
51
+ return {
52
+ async open(request) {
53
+ try {
54
+ const r = await fetch(url, {
55
+ method: "POST",
56
+ headers: { "Content-Type": "application/json", ...(init.headers ?? {}) },
57
+ body: JSON.stringify(request),
58
+ })
59
+ const a = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as CompanionAnswer
60
+ return { ...a, status: r.status }
61
+ } catch (err) {
62
+ return { error: err instanceof Error ? err.message : String(err) }
63
+ }
64
+ },
65
+ }
66
+ }
67
+
68
+ /** The seats tide opens today. */
69
+ export const COMPANION_SEATS: readonly string[] = ["mia"]
70
+
71
+ export const LISTENING = "re-arm: already listening"
72
+
73
+ /** Plan states in which pressing the button would do nothing. */
74
+ export const NOTHING_TO_RUN: readonly string[] = [
75
+ LISTENING,
76
+ "re-arm: another seat listens on this episode",
77
+ "re-arm: pane runs something else",
78
+ "archive refused: the seat still listens",
79
+ ]
80
+
81
+ /** `mia` → `Mia`. */
82
+ export function seatLabel(seat: string): string {
83
+ return seat ? seat[0]!.toUpperCase() + seat.slice(1) : seat
84
+ }
85
+
86
+ /** What the plan will do, in words. tide's own step list stays below it for the detail. */
87
+ export function sayPlan(p: CompanionPlan, seat = p.seat?.key ?? "mia"): string {
88
+ const s = p.session ?? "the seat"
89
+ const who = seatLabel(seat)
90
+ const plugin = p.seat?.plugin ?? `${seat} companion`
91
+ const listener = p.seat?.listener ?? "its listener"
92
+ switch (p.state) {
93
+ case "create":
94
+ return `Creates tmux session ${s} in the episode folder, starts ${who} with the ${plugin} plugin, arms ${listener} and sends the starter prompt.`
95
+ case "archive-then-create":
96
+ return `Renames ${s} to ${p.archive_name ?? "an -arch- name"}, then creates a new ${s} with ${who} listening.`
97
+ case LISTENING:
98
+ return `${who} already listens on this episode in ${s}. Nothing to open.`
99
+ case "re-arm: another seat listens on this episode":
100
+ return `Another seat already listens on this episode. Nothing is done.`
101
+ case "re-arm: start listener":
102
+ return `${s} runs ${who} but the seat is not listening. Arms ${listener}.`
103
+ case "re-arm: relaunch with --resume":
104
+ return `${s} is a bare shell where ${who} ran before. Resumes that session there and arms ${listener}.`
105
+ case "re-arm: launch in the existing shell":
106
+ return `${s} is a bare shell. Starts ${who} there, arms ${listener} and sends the starter prompt.`
107
+ case "re-arm: pane runs something else":
108
+ return `${s} runs ${p.pane?.command ?? "something else"}, so nothing is done. Tick "archive" to rename it and open a new one.`
109
+ case "archive refused: the seat still listens":
110
+ return `${s} still listens, so it is not archived. Close it with /exit first.`
111
+ default:
112
+ return p.state ?? ""
113
+ }
114
+ }
115
+
116
+ /** A refusal from the route, in words the person can act on. */
117
+ export function sayFault(a: CompanionAnswer): string {
118
+ if (a.status === 401) return "Sign in at /me first, from the tailnet or with a writer token."
119
+ return a.error ?? a.message ?? `HTTP ${a.status}`
120
+ }
121
+
122
+ /** The tmux session tide names for a seat: `episode-<N>-<seat>-companion`. */
123
+ export function companionSessionName(episodeNumber: number | string, seat = "mia"): string {
124
+ return `episode-${episodeNumber}-${seat}-companion`
125
+ }
package/src/thread.ts ADDED
@@ -0,0 +1,255 @@
1
+ /**
2
+ * The conversation a person holds with an episode's companion seat, as data.
3
+ *
4
+ * Three sources meet here and nowhere else:
5
+ *
6
+ * - **takes**: what the person said, a recorded take filed in the episode under
7
+ * `captures/<take>/` with its English transcript;
8
+ * - **replies**: what the seat answered, one record per reply as the companion's
9
+ * phone page keeps them (`replies/<episode>.jsonl` in its state directory);
10
+ * - **voices**: the voice ledger's records of those replies. A reply is voiced
11
+ * in parts of at most 900 characters, each its own record, so one reply can be
12
+ * several voices.
13
+ *
14
+ * A voice whose `source` is `phone-capture` is a companion reply. Those voices
15
+ * belong to the conversation, not to the episode's other recordings, and
16
+ * `isCompanionVoice` is the one place that says so.
17
+ *
18
+ * Pure: no React, no DOM, no Node. `./node` reads the files; the host reads the
19
+ * ledger; this module joins them.
20
+ */
21
+
22
+ export type CompanionFeedback = "up" | "down"
23
+
24
+ /** A card under a reply for something it names: a diagram, a review, an issue, a file. */
25
+ export interface CompanionRelated {
26
+ label: string
27
+ /** An absolute http(s) URL, as the phone page keeps it. */
28
+ href: string
29
+ kind?: string
30
+ }
31
+
32
+ /** One recorded take, as the episode files it. */
33
+ export interface CompanionTake {
34
+ /** The 12-digit take id, `yyMMddHHmmss`. */
35
+ id: string
36
+ /** When the take was stored, ISO 8601. */
37
+ at: string
38
+ /** The English transcript, `""` when the take has none yet. */
39
+ text: string
40
+ /** The take's audio, relative to the episode folder. */
41
+ audioPath?: string
42
+ /** What the take was for, when it said (`labelling` takes are not part of the conversation). */
43
+ purpose?: string
44
+ }
45
+
46
+ /** One reply from the seat, as the companion's phone page keeps it. */
47
+ export interface CompanionReply {
48
+ id: string
49
+ /** The take it answers, or null when the seat spoke first. */
50
+ take: string | null
51
+ text: string
52
+ /** Which seat wrote it, as the seat names itself (`claude-code@gaia`). */
53
+ seat: string
54
+ /** The tmux session the seat ran in, from the reply's origin. */
55
+ session?: string
56
+ at: string
57
+ related?: CompanionRelated[]
58
+ /** The person's ruling on the reply, when given. */
59
+ feedback?: CompanionFeedback
60
+ }
61
+
62
+ /** One voice-ledger record, reduced to what the conversation needs. */
63
+ export interface CompanionVoice {
64
+ id: string
65
+ at: string
66
+ text: string
67
+ persona: string
68
+ source?: string | null
69
+ /** A playable URL, or null when the record carries no audio. */
70
+ src: string | null
71
+ /** The tmux session of the voice's origin. */
72
+ session?: string
73
+ }
74
+
75
+ export interface CompanionTakeTurn extends CompanionTake {
76
+ kind: "take"
77
+ }
78
+
79
+ export interface CompanionReplyTurn extends CompanionReply {
80
+ kind: "reply"
81
+ /** Who speaks: the persona that voiced it, else the seat key in its session name. */
82
+ persona: string
83
+ /** Its voice, in the order of the text. Empty when it was never voiced. */
84
+ audio: CompanionVoice[]
85
+ /** True when no reply record was found and the turn was rebuilt from its voices. */
86
+ fromVoices?: boolean
87
+ }
88
+
89
+ export type CompanionTurn = CompanionTakeTurn | CompanionReplyTurn
90
+
91
+ export interface CompanionThread {
92
+ /** Takes and replies in the order they happened. */
93
+ turns: CompanionTurn[]
94
+ takes: number
95
+ replies: number
96
+ /** Sessions that wrote replies, newest last. */
97
+ sessions: string[]
98
+ }
99
+
100
+ /** The ledger `source` the companion's phone page voices its replies with. */
101
+ export const COMPANION_VOICE_SOURCE = "phone-capture"
102
+
103
+ /** True for a ledger voice that is a companion's reply, not another recording of the episode. */
104
+ export function isCompanionVoice(voice: { source?: string | null }): boolean {
105
+ return voice.source === COMPANION_VOICE_SOURCE
106
+ }
107
+
108
+ /** Take purposes that belong to something else than the conversation. */
109
+ const NOT_CONVERSATION = new Set(["labelling"])
110
+
111
+ /**
112
+ * What the phone page sends to the voice layer for a reply: the glyph labels,
113
+ * headings, list marks, emphasis, code ticks and link targets removed. Kept equal
114
+ * to `speakable` in jgwill/miadi-orchestration-kit
115
+ * `claude/mia-episode-companion/phone-capture/server.mjs`, so a voice can be found
116
+ * in the reply it was cut from.
117
+ */
118
+ export function speakable(text: string): string {
119
+ return text
120
+ .split("\n")
121
+ .map((line) => line.replace(/^\s*(🧠|🌸)\s*:?\s*/u, "").replace(/^#+\s*/, "").replace(/^\s*[-*]\s+/, ""))
122
+ .join("\n")
123
+ .replace(/\*\*|__|`/g, "")
124
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
125
+ .replace(/\n{3,}/g, "\n\n")
126
+ .trim()
127
+ }
128
+
129
+ /** Letters and digits only, lower case: what survives every joint between parts. */
130
+ function letters(text: string): string {
131
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "")
132
+ }
133
+
134
+ const SESSION_SEAT = /^episode-\d+-([a-z][a-z0-9]*)-companion(?:-|$)/
135
+
136
+ /** The seat key a companion session name carries: `episode-120-mia-companion` → `mia`. */
137
+ export function seatOfSession(session: string | undefined): string | undefined {
138
+ return session ? SESSION_SEAT.exec(session)?.[1] : undefined
139
+ }
140
+
141
+ function time(at: string): number {
142
+ const t = Date.parse(at)
143
+ return Number.isFinite(t) ? t : 0
144
+ }
145
+
146
+ /** Voices close enough in time and from one session are one reply when no record names it. */
147
+ const VOICE_GAP_MS = 120_000
148
+
149
+ /**
150
+ * The conversation, in order. Every reply gets the voices cut from its text. A
151
+ * companion voice that no reply record holds becomes a reply of its own, so a
152
+ * host that cannot read the phone page's records still shows what the seat said.
153
+ */
154
+ export function buildCompanionThread(input: {
155
+ takes?: readonly CompanionTake[]
156
+ replies?: readonly CompanionReply[]
157
+ voices?: readonly CompanionVoice[]
158
+ }): CompanionThread {
159
+ const takes = (input.takes ?? []).filter((take) => !take.purpose || !NOT_CONVERSATION.has(take.purpose))
160
+ const replies = [...(input.replies ?? [])].sort((a, b) => time(a.at) - time(b.at))
161
+ const voices = (input.voices ?? []).filter(isCompanionVoice).sort((a, b) => time(a.at) - time(b.at))
162
+
163
+ const spoken = replies.map((reply) => letters(speakable(reply.text)))
164
+ const audio = new Map<string, { voice: CompanionVoice; offset: number }[]>()
165
+ const loose: CompanionVoice[] = []
166
+ for (const voice of voices) {
167
+ const said = letters(voice.text)
168
+ let found = -1
169
+ let offset = -1
170
+ if (said) {
171
+ // The latest reply posted before the voice was made that holds its words. A reply
172
+ // can be voiced long after it was posted (Hear Mia renders on demand), never before.
173
+ for (let i = replies.length - 1; i >= 0; i--) {
174
+ const at = spoken[i]!.indexOf(said)
175
+ if (at < 0) continue
176
+ if (found < 0) { found = i; offset = at }
177
+ if (time(replies[i]!.at) <= time(voice.at) + 60_000) { found = i; offset = at; break }
178
+ }
179
+ }
180
+ if (found < 0) { loose.push(voice); continue }
181
+ const id = replies[found]!.id
182
+ audio.set(id, [...(audio.get(id) ?? []), { voice, offset }])
183
+ }
184
+
185
+ const turns: CompanionTurn[] = takes.map((take) => ({ kind: "take", ...take }))
186
+ for (const reply of replies) {
187
+ const parts = (audio.get(reply.id) ?? []).sort((a, b) => a.offset - b.offset)
188
+ // A reply voiced twice keeps one voice per part: the first made.
189
+ const seen = new Set<number>()
190
+ const kept = parts.filter((p) => (seen.has(p.offset) ? false : (seen.add(p.offset), true))).map((p) => p.voice)
191
+ turns.push({
192
+ kind: "reply",
193
+ ...reply,
194
+ persona: kept[0]?.persona || seatOfSession(reply.session) || "companion",
195
+ audio: kept,
196
+ })
197
+ }
198
+ for (const group of groupVoices(loose)) {
199
+ const first = group[0]!
200
+ turns.push({
201
+ kind: "reply",
202
+ id: `voice:${first.id}`,
203
+ take: null,
204
+ text: group.map((v) => v.text).join("\n\n"),
205
+ seat: "",
206
+ ...(first.session ? { session: first.session } : {}),
207
+ at: first.at,
208
+ persona: first.persona || seatOfSession(first.session) || "companion",
209
+ audio: group,
210
+ fromVoices: true,
211
+ })
212
+ }
213
+ turns.sort((a, b) => time(a.at) - time(b.at))
214
+
215
+ const sessions: string[] = []
216
+ for (const turn of turns) {
217
+ if (turn.kind !== "reply" || !turn.session) continue
218
+ const at = sessions.indexOf(turn.session)
219
+ if (at >= 0) sessions.splice(at, 1)
220
+ sessions.push(turn.session)
221
+ }
222
+ return {
223
+ turns,
224
+ takes: turns.filter((t) => t.kind === "take").length,
225
+ replies: turns.filter((t) => t.kind === "reply").length,
226
+ sessions,
227
+ }
228
+ }
229
+
230
+ function groupVoices(voices: readonly CompanionVoice[]): CompanionVoice[][] {
231
+ const groups: CompanionVoice[][] = []
232
+ for (const voice of voices) {
233
+ const last = groups.at(-1)
234
+ const previous = last?.at(-1)
235
+ if (last && previous && previous.session === voice.session && time(voice.at) - time(previous.at) <= VOICE_GAP_MS) last.push(voice)
236
+ else groups.push([voice])
237
+ }
238
+ return groups
239
+ }
240
+
241
+ /** The take a reply answers, when it is in the thread. */
242
+ export function takeOf(thread: CompanionThread, reply: CompanionReplyTurn): CompanionTakeTurn | undefined {
243
+ return reply.take ? (thread.turns.find((t) => t.kind === "take" && t.id === reply.take) as CompanionTakeTurn | undefined) : undefined
244
+ }
245
+
246
+ /** `2026-10-12T15:32:05Z` → `2026-10-12 15:32 UTC`: the same on the server and in every browser. */
247
+ export function stampOf(at: string): string {
248
+ const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(at)
249
+ return m ? `${m[1]} ${m[2]} UTC` : at
250
+ }
251
+
252
+ /** `mia` → `Mia`. */
253
+ export function personaLabel(persona: string): string {
254
+ return persona ? persona[0]!.toUpperCase() + persona.slice(1) : persona
255
+ }