@lysyi3m/sidecar 0.0.0-stage → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -2
  3. package/dist/bin/sidecar-dashboard.js +27 -0
  4. package/dist/bin/sidecar-mcp.js +35 -0
  5. package/dist/bin/sidecar.js +70 -0
  6. package/dist/src/adapters/claude-code.js +333 -0
  7. package/dist/src/adapters/claude-desktop.js +184 -0
  8. package/dist/src/adapters/codex.js +383 -0
  9. package/dist/src/adapters/index.js +38 -0
  10. package/dist/src/adapters/installed.js +25 -0
  11. package/dist/src/adapters/outcome.js +30 -0
  12. package/dist/src/adapters/registration.js +69 -0
  13. package/dist/src/adapters/types.js +1 -0
  14. package/dist/src/cases/events.js +9 -0
  15. package/dist/src/cases/items.js +120 -0
  16. package/dist/src/cases/lock.js +80 -0
  17. package/dist/src/cases/opinion.js +58 -0
  18. package/dist/src/cases/state.js +121 -0
  19. package/dist/src/cases/store.js +181 -0
  20. package/dist/src/cases/usage.js +36 -0
  21. package/dist/src/cli/deps.js +18 -0
  22. package/dist/src/cli/lines.js +11 -0
  23. package/dist/src/cli/list.js +44 -0
  24. package/dist/src/cli/setup.js +202 -0
  25. package/dist/src/cli/status.js +111 -0
  26. package/dist/src/cli/style.js +26 -0
  27. package/dist/src/cli/ui.js +170 -0
  28. package/dist/src/cli/uninstall.js +73 -0
  29. package/dist/src/config.js +108 -0
  30. package/dist/src/dashboard/cases.js +109 -0
  31. package/dist/src/dashboard/html.js +31 -0
  32. package/dist/src/dashboard/links.js +35 -0
  33. package/dist/src/dashboard/marks.js +16 -0
  34. package/dist/src/dashboard/pages.js +516 -0
  35. package/dist/src/dashboard/server.js +305 -0
  36. package/dist/src/dashboard/service.js +138 -0
  37. package/dist/src/dashboard/static/agents/NOTICE +32 -0
  38. package/dist/src/dashboard/static/agents/claude-code.svg +1 -0
  39. package/dist/src/dashboard/static/agents/claude-desktop.svg +1 -0
  40. package/dist/src/dashboard/static/agents/codex.svg +1 -0
  41. package/dist/src/dashboard/static/app.css +1121 -0
  42. package/dist/src/dashboard/static/app.js +256 -0
  43. package/dist/src/dashboard/static/times.js +44 -0
  44. package/dist/src/dashboard/view.js +25 -0
  45. package/dist/src/lib/agent-process.js +57 -0
  46. package/dist/src/lib/atomic-write.js +35 -0
  47. package/dist/src/lib/command.js +20 -0
  48. package/dist/src/lib/failpoint.js +14 -0
  49. package/dist/src/lib/git.js +14 -0
  50. package/dist/src/lib/json.js +2 -0
  51. package/dist/src/lib/paths.js +19 -0
  52. package/dist/src/lib/proc.js +80 -0
  53. package/dist/src/lib/version.js +43 -0
  54. package/dist/src/mcp/server.js +800 -0
  55. package/dist/src/mcp/stdio.js +31 -0
  56. package/dist/src/mcp/tools.js +180 -0
  57. package/dist/src/turns/dispatch.js +188 -0
  58. package/dist/src/turns/knobs.js +14 -0
  59. package/dist/src/turns/prompt.js +284 -0
  60. package/dist/src/turns/runner.js +283 -0
  61. package/package.json +44 -4
@@ -0,0 +1,516 @@
1
+ import { homedir } from "node:os";
2
+ import { effortLabel, modelLabel } from "../adapters/index.js";
3
+ import { html, raw } from "./html.js";
4
+ import { MARKS, markUrl } from "./marks.js";
5
+ import { decisionState, flagsOf, reviewsOf } from "../cases/items.js";
6
+ import { foundNothingToReview } from "../turns/prompt.js";
7
+ // The dashboard's markup, rendered on the server from the view model. Every element the live
8
+ // stream may replace carries a stable id: the case header, and one id per timeline entry.
9
+ /* ---------------------------------------------------------------- formatting */
10
+ /*
11
+ * Timestamps keep the ISO layout, so they sort by eye, align in a column, and cannot be misread
12
+ * between locales. The server renders them in UTC; the page shows them in the browser's time zone.
13
+ */
14
+ const clock = (iso) => iso.slice(11, 19);
15
+ const stamp = (iso) => iso.slice(0, 16).replace("T", " ");
16
+ /** An absolute time; `zoned` names the zone, shown once per view rather than on every row. */
17
+ const time = (iso, format) => html `<time datetime="${iso}" data-format="${format}">${format === "clock" ? clock(iso) : `${stamp(iso)}${format === "zoned" ? " UTC" : ""}`}</time>`;
18
+ /** A relative time. The server renders the absolute stamp; the page turns it relative and keeps it fresh. */
19
+ const ago = (iso) => iso ? html `<time class="ago" datetime="${iso}">${stamp(iso)}</time>` : "—";
20
+ const duration = (fromIso, toIso) => {
21
+ const seconds = Math.round((Date.parse(toIso) - Date.parse(fromIso)) / 1000);
22
+ return seconds < 90 ? `${seconds} s` : `${Math.round(seconds / 60)} min`;
23
+ };
24
+ const tokens = (n) => n < 1_000
25
+ ? String(n)
26
+ : n < 1_000_000
27
+ ? `${(n / 1_000).toFixed(1)}k`
28
+ : `${(n / 1_000_000).toFixed(2)}M`;
29
+ /**
30
+ * What the navigator's turn spent, as the foot of its own card. Nothing for a turn recorded without
31
+ * its invocations. Input leads with the tokens not read from the cache: every model request re-sends
32
+ * the whole session, so total input grows with the session while most of it is cheap cache reads.
33
+ */
34
+ function turnFoot(usage, navigator) {
35
+ if (!usage)
36
+ return "";
37
+ // The model that ran, which a configured alias such as "opus" does not name; its id on hover.
38
+ const head = html `navigator turn${usage.models
39
+ ? html ` · <span title="${usage.models.join(", ")}">${usage.models.map((m) => modelLabel(navigator, m)).join(", ")}</span>`
40
+ : ""}`;
41
+ if (!usage.usage)
42
+ return html `<div class="card-foot">${head} · tokens unknown</div>`;
43
+ const { input, cachedInput, output, reasoning } = usage.usage;
44
+ return html `<div class="card-foot">${head} · ${tokens(input - cachedInput)} new input · ${tokens(output)} output${reasoning ? ` (${tokens(reasoning)} reasoning)` : ""} · ${tokens(cachedInput)} cache reads${usage.toolCalls !== null
45
+ ? ` · ${usage.toolCalls} tool call${usage.toolCalls === 1 ? "" : "s"}`
46
+ : ""}</div>`;
47
+ }
48
+ /**
49
+ * A path, optionally with :line, :line-line or a comma list — the evidence format agents use.
50
+ * Bounded so the scan stays linear in the text: a match starts only where a run of path characters
51
+ * starts, since from inside a long run, such as a pasted base64 blob, each start would rescan the
52
+ * rest of the run; and it takes at most 64 directories, since in a long `a/a/a/…` chain each
53
+ * directory starts a match that would otherwise rescan the rest of the chain. A deeper path is set
54
+ * in monospace from its 64th directory before the file name on.
55
+ */
56
+ const PATH = /(?<![\w@.-])(?:[\w@.-]+\/){1,64}[\w@.-]+\.\w+(?::\d+(?:-\d+)?(?:,\s?\d+(?:-\d+)?)*)?/g;
57
+ /** Prose with `code` spans and file paths set in monospace. Newlines are kept by the CSS (pre-wrap). */
58
+ function prose(text) {
59
+ return String(text ?? "")
60
+ .split(/(`[^`\n]+`)/)
61
+ .flatMap((part) => {
62
+ if (part.startsWith("`") && part.endsWith("`") && part.length > 2)
63
+ return [html `<code>${part.slice(1, -1)}</code>`];
64
+ const out = [];
65
+ let last = 0;
66
+ for (const match of part.matchAll(PATH)) {
67
+ out.push(html `${part.slice(last, match.index)}<span class="path">${match[0]}</span>`);
68
+ last = match.index + match[0].length;
69
+ }
70
+ out.push(html `${part.slice(last)}`);
71
+ return out;
72
+ });
73
+ }
74
+ /** A path with the home directory as `~`: the dashboard runs as the user whose cases it shows. */
75
+ export function homeRelative(path, home = homedir()) {
76
+ if (home.length < 2)
77
+ return path;
78
+ return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
79
+ }
80
+ /**
81
+ * A path on one line, the home directory as `~`. When it still does not fit, its middle gives way
82
+ * to an ellipsis: the start says where it lives, the end names the project (app.css). The title
83
+ * keeps it in full.
84
+ */
85
+ const pathLine = (path) => {
86
+ const full = String(path ?? "");
87
+ const shown = homeRelative(full);
88
+ const half = Math.ceil(shown.length / 2);
89
+ return html `<span class="path-line" title="${full}"><span class="path-head">${shown.slice(0, half)}</span><span class="path-tail"><span>${shown.slice(half)}</span></span></span>`;
90
+ };
91
+ const stateChip = (state) => html `<span class="chip ${state === "open" ? "is-solid" : "is-quiet"}">${state}</span>`;
92
+ /* ---------------------------------------------------------------- agents */
93
+ /**
94
+ * The agent's mark by adapter id, labelled for hover and screen readers. An id without a mark, such
95
+ * as a client name a log records as its driver, shows as text; anything but a string as "unknown".
96
+ * Drawn as a CSS mask of the cached file (app.css), so it takes the theme's text colour.
97
+ */
98
+ function agentMark(agent) {
99
+ const id = typeof agent === "string" ? agent : "unknown";
100
+ const mark = MARKS.get(id);
101
+ if (!mark)
102
+ return html `<span class="agent-name">${id}</span>`;
103
+ return html `<span class="agent-mark" role="img" aria-label="${mark.title}" title="${mark.title}" style="--mark: url(${markUrl(id)})"></span>`;
104
+ }
105
+ /**
106
+ * "<mark> model (effort)", the way the header and the case list name an agent: the labels its
107
+ * adapter gives the ids, with the ids as logged on hover. `unreported` stands in for a model no one
108
+ * reported, as a dash that says why on hover, so a missing one reads as missing.
109
+ */
110
+ function agentLine(agent, model, effort, unreported) {
111
+ const id = typeof agent === "string" ? agent : "";
112
+ const ids = [model, effort].filter(Boolean).map(String);
113
+ const detail = [
114
+ model && modelLabel(id, String(model)),
115
+ effort && `(${effortLabel(id, String(effort))})`,
116
+ ]
117
+ .filter(Boolean)
118
+ .join(" ");
119
+ const missing = !model && unreported ? html `<span class="dim" title="${unreported}">—</span>` : "";
120
+ const shown = detail
121
+ ? html `<span class="dim mono" title="${ids.join(" · ")}">${detail}</span>`
122
+ : "";
123
+ return html `<span class="agent-line">${agentMark(agent)}${missing}${shown}</span>`;
124
+ }
125
+ /** A driver's model comes from the client or the driver itself; either may report none. */
126
+ const driverLine = (agent, model, effort) => agentLine(agent, model, effort, "model not reported");
127
+ /* ---------------------------------------------------------------- shell */
128
+ const FAVICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'%3E%3Crect x='8' y='8' width='9' height='9' rx='2' fill='none' stroke='%231f4fd8' stroke-width='1.6'/%3E%3Crect x='1' y='1' width='9' height='9' rx='2' fill='%230c0e12'/%3E%3C/svg%3E";
129
+ /** A driver over its navigator: the filled square covers the outlined one's corner. */
130
+ const BRAND_MARK = raw('<svg viewBox="0 0 18 18" class="brand-mark" aria-hidden="true"><rect x="8" y="8" width="9" height="9" rx="2" fill="none" stroke="var(--accent)" stroke-width="1.6"/><rect x="1" y="1" width="9" height="9" rx="2" fill="currentColor" stroke="none"/></svg>');
131
+ const SIDEBAR_ICON = raw('<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M2.5 3.5h11v9h-11zM6 3.5v9"/></svg>');
132
+ /** A tray with an arrow into it: save. */
133
+ const EXPORT_ICON = raw('<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2.5v7.5M5 7l3 3 3-3M2.5 10.5v2.5h11v-2.5"/></svg>');
134
+ /** The page around its content: the sidebar with the case list, and the main column. */
135
+ function shell(opts) {
136
+ return html `<!doctype html>
137
+ <html lang="en">
138
+ <head>
139
+ <meta charset="utf-8">
140
+ <meta name="viewport" content="width=device-width, initial-scale=1">
141
+ <title>${opts.title}</title>
142
+ <link rel="icon" href="${FAVICON}">
143
+ <link rel="stylesheet" href="/assets/app.css">
144
+ <script type="module" src="/assets/app.js"></script>
145
+ </head>
146
+ <body>
147
+ <div class="shell${opts.chrome.collapsed ? " is-collapsed" : ""}">
148
+ <aside class="sidebar">
149
+ <div class="sidebar-head"><a class="brand" href="/">${BRAND_MARK}sidecar</a></div>
150
+ ${sideList(opts.cases, opts.activeCase)}
151
+ </aside>
152
+ <main class="main"><div class="page">
153
+ <div class="topbar"><button class="icon-button sidebar-toggle" type="button" aria-label="Toggle the case list" data-toggle-sidebar>${SIDEBAR_ICON}</button><div class="crumbs">${opts.crumbs}</div>${opts.actions ? html `<div class="topbar-actions">${opts.actions}</div>` : ""}</div>
154
+ ${opts.content}
155
+ </div></main>
156
+ </div>
157
+ </body>
158
+ </html>`;
159
+ }
160
+ const isUnreadable = (c) => c.state === "unreadable";
161
+ /** The sidebar's case list. The page refreshes it from /fragments/sidebar. */
162
+ export function sideList(cases, activeCase) {
163
+ const open = cases.filter((c) => c.state === "open");
164
+ // An unreadable case is listed with the closed ones, never hidden.
165
+ const closed = cases.filter((c) => c.state === "closed" || isUnreadable(c));
166
+ const current = (c) => (c.case_id === activeCase ? raw(' aria-current="page"') : "");
167
+ const item = (c) => isUnreadable(c)
168
+ ? html `<a class="side-case" href="/cases/${c.case_id}"${current(c)}>
169
+ <div class="side-title">${c.case_id}</div>
170
+ <div class="side-meta"><span class="mono">${c.case_id}</span><span class="side-tag">unreadable</span></div>
171
+ </a>`
172
+ : html `<a class="side-case" href="/cases/${c.case_id}"${current(c)}>
173
+ <div class="side-title">${c.title || c.case_id}</div>
174
+ <div class="side-meta"><span class="mono">${c.case_id}</span><span>${ago(c.updated)}</span>${
175
+ // The section heading already says active or closed; only a state worth noticing gets a tag.
176
+ c.in_flight ? html `<span class="side-tag is-accent">asking</span>` : ""}</div>
177
+ </a>`;
178
+ const query = activeCase ? `?active=${activeCase}` : "";
179
+ return html `<nav class="side-list" id="side-list" aria-label="Cases" data-refresh="/fragments/sidebar${query}">${cases.length === 0 ? html `<div class="side-empty">No cases yet.</div>` : ""}${open.length ? [html `<div class="side-section label">Active</div>`, ...open.map(item)] : ""}${closed.length ? [html `<div class="side-section label">Closed</div>`, ...closed.map(item)] : ""}</nav>`;
180
+ }
181
+ /* ---------------------------------------------------------------- index */
182
+ const FILTERS = ["all", "open", "closed"];
183
+ export function indexPage(cases, query, chrome = { collapsed: false }) {
184
+ const filter = FILTERS.find((f) => f === query.state) ?? "all";
185
+ const content = html `<h1 class="title">Cases</h1>
186
+ <div class="toolbar">
187
+ <div class="segmented" role="group" aria-label="Case state">${FILTERS.map((name) => html `<button type="button" class="label" data-filter="${name}" aria-pressed="${String(filter === name)}">${name} <span data-count></span></button>`)}</div>
188
+ <div class="search-group"><input type="search" data-search placeholder="Filter by title, id or directory…" aria-label="Filter cases" value="${query.search ?? ""}"><span class="result-count" data-result-count></span></div>
189
+ </div>
190
+ <div class="table-scroll"><table data-cases data-filter-state="${filter}">
191
+ <thead><tr><th>Case</th><th class="col-state">State</th><th>Driver</th><th>Navigator</th><th>Last activity</th></tr></thead>
192
+ ${caseRows(cases)}
193
+ </table></div>
194
+ <p class="message" data-message hidden></p>`;
195
+ return shell({
196
+ title: "sidecar — cases",
197
+ cases,
198
+ activeCase: null,
199
+ chrome,
200
+ crumbs: html `<span class="here label">Cases</span>`,
201
+ content,
202
+ });
203
+ }
204
+ /** The index's rows. The page refreshes them from /fragments/cases and filters them in place. */
205
+ export function caseRows(cases) {
206
+ return html `<tbody id="case-rows" data-refresh="/fragments/cases">${cases.map((c) => {
207
+ if (isUnreadable(c)) {
208
+ return html `<tr data-href="/cases/${c.case_id}" data-state="unreadable" data-haystack="${c.case_id}">
209
+ <td><span class="case-title">${c.case_id}</span><div class="case-sub mono">${c.error}</div></td>
210
+ <td class="col-state">${stateChip("unreadable")}</td><td></td><td></td><td></td>
211
+ </tr>`;
212
+ }
213
+ const haystack = [c.title, c.case_id, c.workspace].join(" ").toLowerCase();
214
+ return html `<tr data-href="/cases/${c.case_id}" data-state="${c.state}" data-haystack="${haystack}">
215
+ <td><a class="case-title" href="/cases/${c.case_id}">${c.title || c.case_id}</a><div class="case-sub case-where mono"><span>${c.case_id}</span><span>·</span>${pathLine(c.workspace)}</div></td>
216
+ <td class="col-state">${stateChip(c.state)}</td>
217
+ <td>${driverLine(c.driver, c.driver_model, c.driver_effort)}</td>
218
+ <td>${agentLine(c.navigator, c.model, c.effort)}</td>
219
+ <td><div>${ago(c.updated)}</div><div class="case-sub mono">${time(c.updated, "stamp")}</div></td>
220
+ </tr>`;
221
+ })}</tbody>`;
222
+ }
223
+ /* ---------------------------------------------------------------- case */
224
+ export function casePage(model, cases, chrome = { collapsed: false }) {
225
+ const { opened } = model.state;
226
+ const last = model.events.at(-1).n;
227
+ const content = html `${caseHead(model)}
228
+ ${brief(model)}
229
+ <p class="message problem" role="alert" data-problem hidden></p>
230
+ <div class="timeline" id="timeline" data-stream="/api/cases/${model.caseId}/stream?after=${last}">${timelineUnits(model).map((u) => u.html)}</div>`;
231
+ return shell({
232
+ title: `${String(opened.title)} — sidecar`,
233
+ cases,
234
+ activeCase: model.caseId,
235
+ chrome,
236
+ crumbs: html `<a class="label" href="/">Cases</a><span>/</span><span class="here">${opened.title}</span>`,
237
+ // Built in the browser from the page as it stands: see exportCase in static/app.js.
238
+ actions: html `<button class="icon-button" type="button" aria-label="Export this case as an HTML file" title="Export as HTML" data-export="${model.caseId}">${EXPORT_ICON}</button>`,
239
+ content,
240
+ });
241
+ }
242
+ function caseHead(model) {
243
+ const { state, status, items, caseId } = model;
244
+ const { opened } = state;
245
+ const views = [...items.values()];
246
+ const flagCount = views.filter((v) => v.item.kind === "flag").length;
247
+ const unsettledCount = views.filter((v) => v.status !== "confirmed").length;
248
+ const held = views.filter((v) => v.status === "held").length;
249
+ // Amber asks for action while the case is in progress; a closed case keeps its counts, plain.
250
+ const alert = status === "closed" ? "stat" : "stat is-alert";
251
+ const opinions = [...state.asks.values()].filter((a) => a.terminal?.kind === "opinion").length;
252
+ const fact = (name, value) => html `<div class="fact"><dt class="label">${name}</dt><dd>${value}</dd></div>`;
253
+ return html `<header class="case-head" id="case-head">
254
+ <div class="title-row"><span class="case-id mono">${caseId}</span><h1 class="title">${opened.title}</h1>${stateChip(status)}</div>
255
+ <div class="case-path mono">${pathLine(opened.workspace)}</div>
256
+ <dl class="facts">${[
257
+ fact("Driver", driverLine(opened.driver, state.driverModel, state.driverEffort)),
258
+ fact("Navigator", agentLine(opened.navigator, opened.model, opened.effort)),
259
+ fact("Opened", html `<span class="mono">${time(opened.ts, "zoned")}</span>`),
260
+ fact("Last activity", ago(model.events.at(-1)?.ts)),
261
+ ]}</dl>
262
+ <div class="stats"><span class="stat"><b>${state.asks.size}</b>asks</span><span class="stat"><b>${opinions}</b>opinions</span><span class="stat"><b>${flagCount}</b>raised flags</span>${unsettledCount > 0 ? html `<span class="${alert}"><b>${unsettledCount}</b>unsettled</span>` : ""}${held > 0 ? html `<span class="${alert}"><b>${held}</b>standing disagreement${held > 1 ? "s" : ""}</span>` : ""}${state.inFlight ? html `<span class="stat"><b>1</b>ask in flight</span>` : ""}</div>
263
+ </header>`;
264
+ }
265
+ function brief(model) {
266
+ const e = model.state.brief;
267
+ if (!e)
268
+ return html ``;
269
+ const list = (items) => html `<ul>${(Array.isArray(items) ? items : []).map((item) => html `<li>${prose(item)}</li>`)}</ul>`;
270
+ const goals = Array.isArray(e.goals) && e.goals.length
271
+ ? html `<section><h3>Goals</h3>${list(e.goals)}</section>`
272
+ : "";
273
+ const constraints = Array.isArray(e.constraints) && e.constraints.length
274
+ ? html `<section><h3>Constraints</h3>${list(e.constraints)}</section>`
275
+ : "";
276
+ return html `<section class="brief"><h2 class="label">Brief</h2><section><h3>Problem</h3><div class="card-text">${prose(e.problem)}</div></section>${goals}${constraints}</section>`;
277
+ }
278
+ /* ---------------------------------------------------------------- timeline */
279
+ const ref = (href, text) => html `<a class="ref" href="${href}">${text}</a>`;
280
+ /**
281
+ * A link to where a point is shown: a flag in its opinion, a main point on its opinion card.
282
+ * `label` shortens the text; the title keeps the full id.
283
+ */
284
+ const refFor = (id, model, label) => {
285
+ const kind = model.items.get(id)?.item.kind;
286
+ const href = kind === "flag" ? `#flag-${id}` : kind === "opinion" ? `#ask-${id}-opinion` : `#ask-${id}`;
287
+ return label === undefined
288
+ ? ref(href, id)
289
+ : html `<a class="ref" href="${href}" title="${id}">${label}</a>`;
290
+ };
291
+ /** The entry that shows an event: an opinion lives under its ask's id, everything else under e<n>. */
292
+ const anchorOf = (n, model) => {
293
+ const e = model.events[n];
294
+ return e?.kind === "opinion" ? `#ask-${String(e.askId)}-opinion` : `#e${n}`;
295
+ };
296
+ const ITEM_CHIP = {
297
+ open: { label: "open", tone: "alert" },
298
+ planned: { label: "planned", tone: "quiet" },
299
+ addressed: { label: "awaiting navigator", tone: "quiet" },
300
+ confirmed: { label: "confirmed", tone: "ok" },
301
+ deferred: { label: "deferred", tone: "alert" },
302
+ reopened: { label: "reopened", tone: "alert" },
303
+ held: { label: "standing disagreement", tone: "alert" },
304
+ exhausted: { label: "left for the user", tone: "alert" },
305
+ };
306
+ /** Where a point of the navigator's stands: its status, the decision on it, and the review of that decision. */
307
+ function itemState(id, model) {
308
+ const view = model.items.get(id);
309
+ if (!view)
310
+ return html ``;
311
+ const chip = ITEM_CHIP[view.status];
312
+ const tone = chip.tone === "ok"
313
+ ? "is-ok"
314
+ : chip.tone === "alert" && model.status !== "closed"
315
+ ? "is-alert"
316
+ : "is-quiet";
317
+ const { decision, reviews } = view.item;
318
+ const review = reviews.at(-1);
319
+ return html `<span class="chip ${tone}">${chip.label}</span>${decision ? ref(`#e${decision.n}`, "decision ↓") : ""}${review && view.status !== "addressed" && view.status !== "open" && view.status !== "planned"
320
+ ? ref(anchorOf(review.opinionN, model), "review ↓")
321
+ : ""}`;
322
+ }
323
+ function entry(e, opts, body) {
324
+ return html `<article class="entry${opts.service ? " service" : ""}${opts.notable ? " notable" : ""}" id="${opts.id}">
325
+ <div class="entry-time mono">${time(e.ts, "clock")}</div>
326
+ <div class="entry-rail"><span class="marker ${opts.marker}"></span></div>
327
+ <div class="entry-body">${body}</div>
328
+ </article>`;
329
+ }
330
+ /** A card's head. `agent` null: sidecar's own card, with no agent mark. */
331
+ function cardHead(role, agent, kind, refs = []) {
332
+ return html `<div class="card-head"><span class="who"><span class="role label">${role}</span>${agent === null ? "" : agentMark(agent)}</span><span class="kind label">${kind}</span>${refs.length ? html `<span class="refs">${refs}</span>` : ""}</div>`;
333
+ }
334
+ const severityChip = (severity) => html `<span class="chip${severity === "high" ? " is-alert" : " is-quiet"}">${severity}</span>`;
335
+ const VERDICT_CLASS = {
336
+ agree: "is-ok",
337
+ disagree: "is-alert",
338
+ "needs-info": "is-accent",
339
+ };
340
+ function askEntry(e, model) {
341
+ const ask = model.state.asks.get(String(e.askId));
342
+ const terminal = ask?.terminal;
343
+ const targets = ask?.attempts.at(-1)?.reviewTargets ?? [];
344
+ let foot;
345
+ if (terminal?.kind === "opinion") {
346
+ foot = html `<div class="card-foot">answered in ${duration(e.ts, terminal.ts)}${ref(`#ask-${String(e.askId)}-opinion`, "opinion ↓")}</div>`;
347
+ }
348
+ else if (terminal && foundNothingToReview(terminal)) {
349
+ foot = html `<div class="card-foot">nothing to review${ref(`#e${terminal.n}`, "details ↓")}</div>`;
350
+ }
351
+ else if (terminal) {
352
+ foot = html `<div class="card-foot is-alert">${terminal.outcome === "failed" ? "failed" : `failed: ${String(terminal.outcome)}`}${ref(`#e${terminal.n}`, "details ↓")}</div>`;
353
+ }
354
+ else {
355
+ foot = html `<div class="card-foot">${ask?.attempts.length ? "the navigator is working…" : "queued"}</div>`;
356
+ }
357
+ return entry(e, { id: `ask-${String(e.askId)}`, marker: "driver" }, html `<div class="card">
358
+ ${cardHead("Driver", model.state.opened.driver, e.review ? "Review request" : "Ask", [html `<span class="mono">${e.askId}</span>`])}
359
+ <div class="card-text">${e.review
360
+ ? html `The navigator reviews the decisions awaiting it${targets.length ? html `: ${targets.map((t, i) => html `${i ? ", " : ""}${refFor(t.ref, model)}`)}` : ""}.`
361
+ : prose(e.body)}</div>
362
+ ${foot}
363
+ </div>`);
364
+ }
365
+ function opinionEntry(e, model) {
366
+ const askId = String(e.askId);
367
+ const isReview = model.state.asks.get(askId)?.event.review === true;
368
+ const flags = flagsOf(e).map((flag) => html `<div class="flag" id="flag-${flag.id}"><span class="flag-id">${flag.id}</span><div class="flag-text">${prose(flag.body)}</div><div class="flag-status">${severityChip(flag.severity)}${itemState(flag.id, model)}</div></div>`);
369
+ const limits = Array.isArray(e.limits) ? e.limits : [];
370
+ const reviews = reviewsOf(e).map((r) => {
371
+ // A review of a decision since replaced is history: it says nothing about the point now.
372
+ const applied = model.items.get(r.ref)?.item.reviews.find((h) => h.opinionN === e.n)?.applied ?? false;
373
+ return html `<div class="flag"><span class="flag-id">${refFor(r.ref, model)}</span><div class="flag-text">${prose(r.body)}</div><div class="flag-status"><span class="chip ${!applied ? "is-quiet" : r.status === "confirmed" ? "is-ok" : "is-alert"}">${r.status}</span>${applied ? "" : html `<span class="dim">of an earlier decision</span>`}</div></div>`;
374
+ });
375
+ return entry(e, { id: `ask-${askId}-opinion`, marker: "navigator" }, html `<div class="card navigator">
376
+ ${cardHead("Navigator", model.state.opened.navigator, isReview ? "Review" : "Opinion", [html `<span>re</span>`, ref(`#ask-${askId}`, e.askId)])}
377
+ <div class="verdict"><span class="chip ${VERDICT_CLASS[String(e.verdict)] ?? ""}">${e.verdict}</span>${e.severity !== undefined ? severityChip(e.severity) : ""}${model.items.has(askId) ? itemState(askId, model) : ""}</div>
378
+ <div class="card-text">${prose(e.body)}</div>
379
+ ${reviews.length ? html `<section class="flags"><h3 class="flags-title"><span class="label">Reviews</span><span class="dim">of the driver's decisions on earlier points</span></h3>${reviews}</section>` : ""}
380
+ ${flags.length ? html `<section class="flags"><h3 class="flags-title"><span class="label">Flags</span><span class="dim">one per finding; each stays open until the navigator confirms a decision on it</span></h3>${flags}</section>` : ""}
381
+ ${limits.length ? html `<section class="flags"><h3 class="flags-title"><span class="label">Limits</span><span class="dim">what the navigator could not check</span></h3><ul class="limits">${limits.map((l) => html `<li>${prose(l)}</li>`)}</ul></section>` : ""}
382
+ ${turnFoot(model.state.asks.get(askId)?.usage, String(model.state.opened.navigator))}
383
+ </div>`);
384
+ }
385
+ /**
386
+ * A decision or note, or several that one `sidecar_record` call wrote for several refs: the log
387
+ * keeps one event per ref, the card shows the text once. A later ref that shares the first one's
388
+ * ask shows as `.n`. Each event keeps an anchor, so a link to any of them lands on this card.
389
+ */
390
+ function noteEntry(events, model) {
391
+ const e = events[0];
392
+ const ids = events.flatMap((x) => (typeof x.ref === "string" ? [x.ref] : []));
393
+ const first = ids[0];
394
+ const refs = first
395
+ ? [
396
+ html `<span>re</span>`,
397
+ ...ids.map((id, i) => {
398
+ const ask = first.slice(0, first.lastIndexOf(".") + 1);
399
+ const short = i > 0 && ask && id.startsWith(ask) ? id.slice(ask.length - 1) : undefined;
400
+ return html `${i ? html `<span>·</span>` : ""}${refFor(id, model, short)}`;
401
+ }),
402
+ ]
403
+ : [];
404
+ const state = e.kind === "decision" ? decisionState(e) : "ready";
405
+ const kind = [
406
+ e.kind === "decision" ? "Decision" : "Note",
407
+ ...(state === "ready" ? [] : [state]),
408
+ ...(events.length > 1 ? [`${events.length} points`] : []),
409
+ ].join(" · ");
410
+ return entry(e, { id: `e${e.n}`, marker: "driver" }, html `${events.slice(1).map((x) => html `<span class="anchor" id="e${x.n}"></span>`)}<div class="card compact">
411
+ ${cardHead("Driver", model.state.opened.driver, kind, refs)}
412
+ <div class="card-text">${prose(e.body)}</div>
413
+ </div>`);
414
+ }
415
+ /**
416
+ * Whether `next` belongs to the same `sidecar_record` call as `group`: the call appends one event
417
+ * per ref, back to back, with the same kind, state and text.
418
+ */
419
+ function sameRecord(group, next) {
420
+ const first = group[0];
421
+ const last = group.at(-1);
422
+ return ((next.kind === "decision" || next.kind === "note") &&
423
+ next.kind === first.kind &&
424
+ next.n === last.n + 1 &&
425
+ typeof first.ref === "string" &&
426
+ typeof next.ref === "string" &&
427
+ next.body === first.body &&
428
+ (next.kind !== "decision" || decisionState(next) === decisionState(first)) &&
429
+ Date.parse(next.ts) - Date.parse(first.ts) < 1000);
430
+ }
431
+ function failedEntry(e, model) {
432
+ const ask = model.state.asks.get(String(e.askId));
433
+ return entry(e, { id: `e${e.n}`, marker: "sidecar alert" }, html `<div class="card alert compact">
434
+ ${cardHead("sidecar", null, e.outcome === "failed" ? "Turn failed" : `Turn failed · ${String(e.outcome)}`, [html `<span>re</span>`, ref(`#ask-${String(e.askId)}`, e.askId)])}
435
+ <div class="card-text">${e.hint ? `hint: ${String(e.hint)}\n` : ""}${prose(e.detail ?? "no detail")}</div>
436
+ ${ask?.terminal === e ? turnFoot(ask.usage, String(model.state.opened.navigator)) : ""}
437
+ </div>`);
438
+ }
439
+ /** Bookkeeping events, as one quiet line each; a text detail cut short keeps its whole text on hover. */
440
+ function serviceEntry(e, model) {
441
+ const line = (what, ...detail) => entry(e, { id: `e${e.n}`, marker: "sidecar", service: true, notable: e.kind === "session-reset" }, html `<div class="service-line"><span class="what">${what}</span>${detail
442
+ .filter(Boolean)
443
+ .map((d) => typeof d === "string"
444
+ ? html `<span title="${d}">· ${d}</span>`
445
+ : html `<span>· ${d}</span>`)}</div>`);
446
+ switch (e.kind) {
447
+ case "turn-started":
448
+ return line("turn started", html `${model.state.asks.get(String(e.askId))?.event.review ? "review request" : "ask"} ${ref(`#ask-${String(e.askId)}`, e.askId)}`);
449
+ case "navigator-session":
450
+ return line("navigator session started", `session id ${String(e.sessionId)}`);
451
+ case "session-reset":
452
+ return line("re-brief", e.cause, `seeded ${Array.isArray(e.seededEventIds) ? e.seededEventIds.length : 0} events`, e.newSessionId && `new session ${String(e.newSessionId).slice(0, 8)}`);
453
+ case "closed":
454
+ return line("case closed", e.reason);
455
+ case "reopened":
456
+ return line("case reopened", e.reason);
457
+ case "turn-failed":
458
+ return line("nothing to review", html `review request ${ref(`#ask-${String(e.askId)}`, e.askId)}`);
459
+ // An old log's paused and resumed lines among them, shown as they were.
460
+ default:
461
+ return line(e.kind);
462
+ }
463
+ }
464
+ function timelineEntry(e, model) {
465
+ switch (e.kind) {
466
+ case "ask":
467
+ return askEntry(e, model);
468
+ case "opinion":
469
+ return opinionEntry(e, model);
470
+ case "decision":
471
+ case "note":
472
+ return noteEntry([e], model);
473
+ case "turn-failed":
474
+ // A review turn that found nothing to review failed nothing: a quiet line, not an alert.
475
+ return foundNothingToReview(e) ? serviceEntry(e, model) : failedEntry(e, model);
476
+ default:
477
+ return serviceEntry(e, model);
478
+ }
479
+ }
480
+ const idOf = (markup) => /\sid="([^"]+)"/.exec(markup.value)[1];
481
+ /** Events with no timeline entry. */
482
+ export const HIDDEN = new Set(["opened", "brief", "driver-reported", "attached", "detached"]);
483
+ /**
484
+ * One unit per timeline entry. The events of one multi-ref `sidecar_record` call form one entry,
485
+ * under the first event's id: a later event of the call changes that unit, so the live page
486
+ * replaces the card instead of adding one.
487
+ */
488
+ function timelineUnits(model) {
489
+ const groups = [];
490
+ for (const e of model.events) {
491
+ // The header and the brief already show what these hold, and which session holds the case
492
+ // tells the reader nothing. The log keeps them all.
493
+ if (HIDDEN.has(e.kind))
494
+ continue;
495
+ const group = groups.at(-1);
496
+ if (group && sameRecord(group, e))
497
+ group.push(e);
498
+ else
499
+ groups.push([e]);
500
+ }
501
+ return groups.map((group) => {
502
+ const markup = group.length > 1 ? noteEntry(group, model) : timelineEntry(group[0], model);
503
+ return { id: idOf(markup), html: markup };
504
+ });
505
+ }
506
+ /**
507
+ * Every part of a case page the live stream may replace, in page order: the header, then one unit
508
+ * per timeline entry. The stream diffs these between two versions of the log and sends the ones
509
+ * that changed; the page replaces each by id, or appends a new entry.
510
+ */
511
+ export function caseUnits(model) {
512
+ return [{ id: "case-head", html: caseHead(model) }, ...timelineUnits(model)].map((u) => ({
513
+ id: u.id,
514
+ html: u.html.value,
515
+ }));
516
+ }