@miadi/companion-ui 0.0.0-stage → 0.2.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/node.ts ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * `@miadi/companion-ui/node` — reads what the companion wrote, on the host that holds it.
3
+ *
4
+ * - Takes are capture bundles in the episode folder: `captures/<take>/capture.json`
5
+ * (`miadi.episode-capture.v1`) and `transcription_<take>_EN.txt` beside it. Only the
6
+ * descriptor and the transcript are read, never the audio and never a digest, so a
7
+ * room with twenty takes of twenty megabytes stays quick.
8
+ * - Replies are the companion phone page's records, one JSON line per reply in
9
+ * `<state>/replies/<episode>.jsonl`, with the person's thumbs in
10
+ * `<state>/replies/feedback/<episode>.jsonl` (jgwill/miadi-orchestration-kit,
11
+ * `claude/mia-episode-companion/phone-capture`). Only id, take, text, seat, session,
12
+ * time, related cards and the thumb leave this module. The reply's origin (user, host,
13
+ * pane, cwd) and its loop record stay on the host.
14
+ * - Forks are the episode's `branches/<name>/` folders that hold a brief: the trunk
15
+ * seat writes the brief when it forks a session to work a branch.
16
+ *
17
+ * Every reader answers an empty list when its folder or file is absent or unreadable.
18
+ */
19
+
20
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
21
+ import { homedir } from "node:os"
22
+ import { join } from "node:path"
23
+ import type { CompanionFeedback, CompanionRelated, CompanionReply, CompanionTake } from "./thread.js"
24
+
25
+ const TAKE_ID = /^\d{12}$/
26
+ const EPISODE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
27
+
28
+ function readJson(file: string): Record<string, unknown> | null {
29
+ try {
30
+ const value = JSON.parse(readFileSync(file, "utf8")) as unknown
31
+ return value && typeof value === "object" ? (value as Record<string, unknown>) : null
32
+ } catch {
33
+ return null
34
+ }
35
+ }
36
+
37
+ function str(value: unknown): string | undefined {
38
+ return typeof value === "string" && value.trim() ? value.trim() : undefined
39
+ }
40
+
41
+ /** The takes filed in one episode folder, oldest first. */
42
+ export function readCompanionTakes(episodeDir: string): CompanionTake[] {
43
+ const captures = join(episodeDir, "captures")
44
+ let names: string[]
45
+ try {
46
+ names = readdirSync(captures, { withFileTypes: true }).filter((e) => e.isDirectory() && TAKE_ID.test(e.name)).map((e) => e.name)
47
+ } catch {
48
+ return []
49
+ }
50
+ const takes: CompanionTake[] = []
51
+ for (const id of names) {
52
+ const folder = join(captures, id)
53
+ const capture = readJson(join(folder, "capture.json"))
54
+ const audio = (capture?.audio ?? null) as Record<string, unknown> | null
55
+ const outputs = Array.isArray((capture?.transcription as Record<string, unknown> | undefined)?.outputs)
56
+ ? ((capture!.transcription as Record<string, unknown>).outputs as Record<string, unknown>[])
57
+ : []
58
+ const english = outputs.find((o) => str(o.language)?.toLowerCase() === "en")
59
+ const transcriptName = str(english?.filename) ?? `transcription_${id}_EN.txt`
60
+ let text = ""
61
+ try {
62
+ text = readFileSync(join(folder, transcriptName.replace(/^.*\//, "")), "utf8").trim()
63
+ } catch {
64
+ text = ""
65
+ }
66
+ let at = str(capture?.storedAt) ?? ""
67
+ if (!at) {
68
+ try {
69
+ at = statSync(folder).mtime.toISOString()
70
+ } catch {
71
+ at = ""
72
+ }
73
+ }
74
+ const purpose = str(readJson(join(folder, "purpose.json"))?.purpose)
75
+ const audioName = str(audio?.filename)
76
+ const audioPath = str(audio?.relativePath) ?? (audioName ? `captures/${id}/${audioName}` : undefined)
77
+ takes.push({
78
+ id,
79
+ at,
80
+ text,
81
+ ...(audioPath && !audioPath.includes("..") && audioPath.startsWith(`captures/${id}/`) ? { audioPath } : {}),
82
+ ...(purpose ? { purpose } : {}),
83
+ })
84
+ }
85
+ return takes.sort((a, b) => a.at.localeCompare(b.at))
86
+ }
87
+
88
+ /**
89
+ * Where the companion phone page keeps its replies: `MIADI_PHONE_CAPTURE_STATE_DIR`,
90
+ * else `$XDG_STATE_HOME/miadi-phone-capture`, else `~/.local/state/miadi-phone-capture`,
91
+ * the same order the page itself reads, plus `/replies`.
92
+ */
93
+ export function companionRepliesDir(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
94
+ const state = env.MIADI_PHONE_CAPTURE_STATE_DIR?.trim()
95
+ || join(env.XDG_STATE_HOME?.trim() || join(home, ".local", "state"), "miadi-phone-capture")
96
+ return join(state, "replies")
97
+ }
98
+
99
+ function jsonLines(file: string): Record<string, unknown>[] {
100
+ let raw: string
101
+ try {
102
+ raw = readFileSync(file, "utf8")
103
+ } catch {
104
+ return []
105
+ }
106
+ const out: Record<string, unknown>[] = []
107
+ for (const line of raw.split("\n")) {
108
+ if (!line.trim()) continue
109
+ try {
110
+ const value = JSON.parse(line) as unknown
111
+ if (value && typeof value === "object") out.push(value as Record<string, unknown>)
112
+ } catch {
113
+ // a torn line
114
+ }
115
+ }
116
+ return out
117
+ }
118
+
119
+ function related(value: unknown): CompanionRelated[] {
120
+ if (!Array.isArray(value)) return []
121
+ return value
122
+ .map((r) => (r && typeof r === "object" ? (r as Record<string, unknown>) : {}))
123
+ .map((r) => ({ label: str(r.label) ?? "", href: str(r.href) ?? "", kind: str(r.kind) }))
124
+ .filter((r) => r.label && /^https?:\/\/\S+$/.test(r.href))
125
+ .map((r) => (r.kind ? { label: r.label, href: r.href, kind: r.kind } : { label: r.label, href: r.href }))
126
+ }
127
+
128
+ /** One episode's replies with the person's latest thumb on each, oldest first. */
129
+ export function readCompanionReplies(repliesDir: string, episode: string): CompanionReply[] {
130
+ if (!EPISODE_NAME.test(episode)) return []
131
+ const thumbs = new Map<string, CompanionFeedback | "">()
132
+ for (const entry of jsonLines(join(repliesDir, "feedback", `${episode}.jsonl`))) {
133
+ const reply = str(entry.reply)
134
+ const value = entry.value
135
+ if (reply && (value === "up" || value === "down" || value === "")) thumbs.set(reply, value)
136
+ }
137
+ const replies: CompanionReply[] = []
138
+ for (const r of jsonLines(join(repliesDir, `${episode}.jsonl`))) {
139
+ const id = str(r.id)
140
+ const text = str(r.text)
141
+ const at = str(r.at)
142
+ if (!id || !text || !at || (r.episode !== undefined && r.episode !== episode)) continue
143
+ const origin = (r.origin && typeof r.origin === "object" ? r.origin : {}) as Record<string, unknown>
144
+ const take = str(r.take)
145
+ const cards = related(r.related)
146
+ const thumb = thumbs.get(id)
147
+ replies.push({
148
+ id,
149
+ take: take && TAKE_ID.test(take) ? take : null,
150
+ text,
151
+ seat: str(r.seat) ?? "",
152
+ ...(str(origin.session) ? { session: str(origin.session)! } : {}),
153
+ at,
154
+ ...(cards.length ? { related: cards } : {}),
155
+ ...(thumb ? { feedback: thumb } : {}),
156
+ })
157
+ }
158
+ return replies.sort((a, b) => a.at.localeCompare(b.at))
159
+ }
160
+
161
+ export interface CompanionFork {
162
+ /** The branch folder's name: `plot-threads`. */
163
+ name: string
164
+ /** Its files, relative to the episode folder, the brief first. */
165
+ brief: string
166
+ /** The latest report, when the fork returned one. */
167
+ report?: string
168
+ }
169
+
170
+ /** The forks the companion drove, read from the episode's `branches/<name>/` folders that hold a brief. */
171
+ export function readCompanionForks(episodeDir: string): CompanionFork[] {
172
+ const branches = join(episodeDir, "branches")
173
+ if (!existsSync(branches)) return []
174
+ const forks: CompanionFork[] = []
175
+ let names: string[]
176
+ try {
177
+ names = readdirSync(branches, { withFileTypes: true }).filter((e) => e.isDirectory() && EPISODE_NAME.test(e.name)).map((e) => e.name)
178
+ } catch {
179
+ return []
180
+ }
181
+ const byNumber = (prefix: string) => (a: string, b: string) => {
182
+ const n = (name: string) => Number(new RegExp(`^${prefix}(?:-(\\d+))?\\.md$`).exec(name)?.[1] ?? 1)
183
+ return n(a) - n(b)
184
+ }
185
+ for (const name of names.sort()) {
186
+ let files: string[]
187
+ try {
188
+ files = readdirSync(join(branches, name))
189
+ } catch {
190
+ continue
191
+ }
192
+ const briefs = files.filter((f) => /^brief(?:-\d+)?\.md$/.test(f)).sort(byNumber("brief"))
193
+ if (briefs.length === 0) continue
194
+ const reports = files.filter((f) => /^report(?:-\d+)?\.md$/.test(f)).sort(byNumber("report"))
195
+ forks.push({
196
+ name,
197
+ brief: `branches/${name}/${briefs[0]}`,
198
+ ...(reports.length ? { report: `branches/${name}/${reports.at(-1)}` } : {}),
199
+ })
200
+ }
201
+ return forks
202
+ }
package/src/opener.tsx ADDED
@@ -0,0 +1,269 @@
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
+ {/* "for episode" went: a companion seat is always an episode's (review a425d070). */}
173
+ <label htmlFor={fieldId} style={{ color: t.accent, fontWeight: 700 }}>Open {who}</label>
174
+ <input
175
+ id={fieldId}
176
+ value={typed}
177
+ onChange={(e) => { setTyped(e.target.value); setRan(null) }}
178
+ placeholder="episode"
179
+ inputMode="numeric"
180
+ enterKeyHint="go"
181
+ autoComplete="off"
182
+ aria-label="episode number"
183
+ style={{ width: 90, minHeight: 40, background: t.field, color: t.text, border: `1px solid ${t.accent}88`,
184
+ borderRadius: 6, padding: "0 10px", fontFamily: t.mono, fontSize: 15 }}
185
+ />
186
+ </>
187
+ )}
188
+ {seats.length > 1 && (
189
+ <select
190
+ aria-label="companion seat"
191
+ value={seat}
192
+ disabled={busy !== null}
193
+ onChange={(e) => { setSeat(e.target.value); setRan(null); if (fixedEpisode) void askPlan({ seat: e.target.value }) }}
194
+ style={{ minHeight: 40, background: t.field, color: t.text, border: `1px solid ${t.accent}88`, borderRadius: 6, fontFamily: t.mono }}
195
+ >
196
+ {seats.map((s) => <option key={s} value={s}>{seatLabel(s)}</option>)}
197
+ </select>
198
+ )}
199
+ {canRun && !stale ? (
200
+ <button type="submit" style={primary}>
201
+ {plan?.state === "create" || plan?.state === "archive-then-create" ? "▶ open " : "▶ re-arm "}{plan?.session}
202
+ </button>
203
+ ) : (
204
+ <button type="submit" disabled={!ep || busy !== null} style={{ ...(ep ? primary : secondary), opacity: ep ? 1 : 0.75 }}>
205
+ {busy === "plan" ? "asking tide…" : busy === "run" ? `opening… ${elapsed}s` : "show plan ↵"}
206
+ </button>
207
+ )}
208
+ <label style={{ display: "inline-flex", alignItems: "center", gap: 6, color: t.textDim, fontSize: 12 }}
209
+ title="Only on your word: rename the existing session -arch-<yyMMddHHmm> and open a new one">
210
+ <input type="checkbox" checked={archive} disabled={busy !== null}
211
+ onChange={(e) => { setArchive(e.target.checked); void askPlan({ archive: e.target.checked }) }} />
212
+ archive the existing session
213
+ </label>
214
+ </form>
215
+
216
+ {busy === "run" && (
217
+ <div style={{ marginTop: 10, color: t.accent }}>
218
+ Opening {plan?.session}: starting {who}, arming the listener, sending the starter prompt. This takes a minute or two ({elapsed}s).
219
+ </div>
220
+ )}
221
+
222
+ {stale && busy === null && (
223
+ <div style={{ marginTop: 10, color: t.textDim }}>
224
+ Press Enter to see what opening {fixedEpisode ? "this episode" : `episode ${ep}`} will do.
225
+ </div>
226
+ )}
227
+
228
+ {shown && !stale && busy !== "run" && (
229
+ <div style={{ marginTop: 10, whiteSpace: "pre-wrap", wordBreak: "break-word", lineHeight: 1.5 }}>
230
+ {faulted ? <div style={{ color: t.danger }}>{sayFault(shown)}</div> : null}
231
+ {shown.status === 409 && shown.message ? <div style={{ color: t.danger }}>{shown.message}</div> : null}
232
+ {shownPlan && !faulted && (
233
+ <>
234
+ {shownPlan.episode?.title && !fixedEpisode && (
235
+ <div style={{ color: t.text }}>
236
+ episode {shownPlan.episode.number} · {shownPlan.episode.title}
237
+ </div>
238
+ )}
239
+ <div style={{ color: openNow ? t.success : t.text, marginTop: 2 }}>
240
+ {openNow ? `${who} is listening in ${shownPlan.session}.` : sayPlan(shownPlan, seat)}
241
+ </div>
242
+ {pane && (
243
+ <a href={pane} style={{ display: "inline-block", marginTop: 6, color: t.accent, textDecoration: "underline" }}>
244
+ go to {shownPlan.session} →
245
+ </a>
246
+ )}
247
+ {shownPlan.run?.warnings?.map((w) => <div key={w} style={{ color: t.warning }}>warning: {w}</div>)}
248
+ {(shownPlan.commands?.length || shownPlan.run?.steps?.length) ? (
249
+ <details style={{ marginTop: 6, color: t.textDim }}>
250
+ <summary style={{ cursor: "pointer" }}>{shownPlan.run ? "steps taken" : "steps tide will take"}</summary>
251
+ {shownPlan.run?.steps?.length
252
+ ? shownPlan.run.steps.map((s) => <div key={`${s.at}-${s.step}`}>{s.at.slice(11, 19)} {s.step}</div>)
253
+ : (
254
+ <ol style={{ margin: "4px 0 0 18px", padding: 0 }}>
255
+ {shownPlan.commands?.map((c) => <li key={c}>{c}</li>)}
256
+ </ol>
257
+ )}
258
+ {!ran && shownPlan.starter_prompt && canRun && (
259
+ <div style={{ marginTop: 4 }}>starter prompt: {shownPlan.starter_prompt}</div>
260
+ )}
261
+ </details>
262
+ ) : null}
263
+ </>
264
+ )}
265
+ </div>
266
+ )}
267
+ </div>
268
+ )
269
+ }
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
+ }