@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,800 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { statSync } from "node:fs";
3
+ import { isAbsolute, resolve } from "node:path";
4
+ import { adapters, findAdapter, getNavigator, preferredNavigator, selectableNavigatorIds, } from "../adapters/index.js";
5
+ import { loadConfig } from "../config.js";
6
+ import { processAlive, startTime } from "../lib/proc.js";
7
+ import { SIDECAR_VERSION } from "../lib/version.js";
8
+ import { awaitingReview, flagsOf, itemStatus, reviewsOf, reviewTargetsOf, unsettled, } from "../cases/items.js";
9
+ import { caseStatus, fold } from "../cases/state.js";
10
+ import { Store } from "../cases/store.js";
11
+ import { cancelTurn, dispatchAsk, reconcile, waitForOutcome, } from "../turns/dispatch.js";
12
+ import { BRIEF_MAX, foundNothingToReview, renderBrief, REVIEW_ASK } from "../turns/prompt.js";
13
+ import { isInstalled } from "../adapters/installed.js";
14
+ // The driver-facing logic behind the MCP tools. One instance per MCP server process. It may own
15
+ // several cases: a client can share one server among its chats. A call names its case, or acts on
16
+ // the only case the server owns. See docs/design.md → Driver interface, Ownership.
17
+ /** An expected refusal, with a message for the driver. On the wire it is a tool error like any other. */
18
+ export class ToolError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = "ToolError";
22
+ }
23
+ }
24
+ const ELICIT_TIMEOUT_MS = 120_000;
25
+ class Mutex {
26
+ #tail = Promise.resolve();
27
+ run(fn) {
28
+ const result = this.#tail.then(fn);
29
+ this.#tail = result.then(() => { }, () => { });
30
+ return result;
31
+ }
32
+ }
33
+ export class SidecarServer {
34
+ /** Set by the transport when the client supports MCP elicitation. */
35
+ elicit;
36
+ #owner;
37
+ #store;
38
+ #opts;
39
+ #mutex = new Mutex();
40
+ #cases = new Set();
41
+ /** Case id → opening call id, for cases this server opened whose turn awaits `turnOf`. */
42
+ #unreported = new Map();
43
+ /** The adapter this server drives for, named at launch. The case log records its id. */
44
+ #adapter;
45
+ #driver;
46
+ constructor(opts) {
47
+ const adapter = (opts.adapters ?? adapters()).find((a) => a.id === opts.driver);
48
+ if (!adapter?.driver)
49
+ throw new Error(`--driver ${opts.driver}: no adapter of that id has a driver role`);
50
+ this.#adapter = adapter;
51
+ this.#driver = adapter.driver;
52
+ this.#opts = opts;
53
+ this.#store = new Store(opts.store);
54
+ this.#owner = {
55
+ token: randomBytes(8).toString("hex"),
56
+ pid: process.pid,
57
+ start: startTime(process.pid),
58
+ driver: adapter.id,
59
+ };
60
+ }
61
+ navigators() {
62
+ const available = this.#candidates();
63
+ return {
64
+ available,
65
+ suggested_for_this_driver: preferredNavigator(this.#adapter, available) ?? null,
66
+ };
67
+ }
68
+ open(input) {
69
+ return this.#mutex.run(async () => {
70
+ const briefSize = renderBrief(input).length;
71
+ if (briefSize > BRIEF_MAX) {
72
+ throw new ToolError(`the brief (problem, goals, constraints) takes ${briefSize} characters, over the limit of ${BRIEF_MAX}; shorten it`);
73
+ }
74
+ // Checked before the navigator choice, so a bad open never shows the user a form.
75
+ const requested = this.#workspace(input.workspace);
76
+ const scratch = requested === undefined;
77
+ const config = loadConfig(this.#opts.store.home);
78
+ const { navigator, chosenBy } = await this.#chooseNavigator(input.navigator, input.title);
79
+ if (!selectableNavigatorIds().includes(navigator)) {
80
+ throw new ToolError(`no navigator ${navigator}; available: ${this.#candidates().join(", ")}`);
81
+ }
82
+ // Model and effort are fixed for the case's lifetime: recorded once, passed on every turn.
83
+ const model = input.model ?? config.navigators[navigator]?.model;
84
+ const effort = input.effort ?? config.navigators[navigator]?.effort;
85
+ // The client's report wins over the model's own: the client knows what runs.
86
+ const reported = this.#driver.reported?.(input.clientMeta) ?? {};
87
+ const driverModel = reported.model ?? input.driverModel;
88
+ const driverEffort = reported.effort ?? input.driverEffort;
89
+ // A client that records the turn only after this call returns: a later call looks it up.
90
+ const driverCall = this.#driver.turnOf ? this.#driver.callId?.(input.clientMeta) : undefined;
91
+ // One create: no other server can attach between the case appearing and this server owning it.
92
+ const { caseId, workspace } = await this.#store.createCase({
93
+ title: input.title,
94
+ ...(scratch ? {} : { workspace: requested }),
95
+ driver: this.#adapter.id,
96
+ ...(driverModel ? { driverModel } : {}),
97
+ ...(driverEffort ? { driverEffort } : {}),
98
+ ...(driverCall ? { driverCall } : {}),
99
+ navigator,
100
+ ...(model ? { model } : {}),
101
+ ...(effort ? { effort } : {}),
102
+ sidecarVersion: SIDECAR_VERSION,
103
+ }, [
104
+ {
105
+ author: "driver",
106
+ kind: "brief",
107
+ problem: input.problem,
108
+ goals: input.goals ?? [],
109
+ constraints: input.constraints ?? [],
110
+ },
111
+ { author: "sidecar", kind: "attached", owner: this.#owner },
112
+ ], { scratch });
113
+ this.#cases.add(caseId);
114
+ if (driverCall)
115
+ this.#unreported.set(caseId, driverCall);
116
+ return {
117
+ case_id: caseId,
118
+ navigator,
119
+ navigator_chosen_by: chosenBy,
120
+ model: model ?? null,
121
+ effort: effort ?? null,
122
+ workspace,
123
+ dashboard: this.#dashboardLink(caseId),
124
+ next: scratch
125
+ ? "No workspace was given, so the navigator starts in an empty scratch directory, with no project to read. If the question is about files, close this case and open it again with workspace set to their folder's absolute path."
126
+ : `The navigator works in ${String(workspace)}. If the case is about another directory, close this case and open it again with workspace set.`,
127
+ };
128
+ });
129
+ }
130
+ /**
131
+ * The case's workspace: the one the driver names, or else what the driver adapter says. "cwd":
132
+ * the server's working directory, wherever the user started the app. "scratch": the app's working
133
+ * directory is no project, so a named workspace must be absolute, and none means an empty scratch
134
+ * directory in the case (undefined), never a broad default.
135
+ */
136
+ #workspace(requested) {
137
+ const scratch = this.#driver.workspace === "scratch";
138
+ if (scratch && requested === undefined)
139
+ return undefined;
140
+ if (scratch && !isAbsolute(requested)) {
141
+ throw new ToolError(`workspace ${requested} must be an absolute path for this client`);
142
+ }
143
+ const workspace = resolve(this.#opts.workspace, requested ?? ".");
144
+ if (!statSync(workspace, { throwIfNoEntry: false })?.isDirectory()) {
145
+ throw new ToolError(`workspace ${workspace} is not a directory`);
146
+ }
147
+ return workspace;
148
+ }
149
+ /**
150
+ * The driver's explicit choice wins. Otherwise the user picks through an elicitation form, with
151
+ * another agent than the driver preselected; without an answer, that suggestion stands. A client
152
+ * with no form gets a refusal that tells the driver to ask the user in the conversation.
153
+ */
154
+ async #chooseNavigator(requested, title) {
155
+ if (requested)
156
+ return { navigator: requested, chosenBy: "driver" };
157
+ const candidates = this.#candidates();
158
+ const suggested = preferredNavigator(this.#adapter, candidates);
159
+ if (!suggested) {
160
+ throw new ToolError("no navigator is available: none of the supported agent CLIs is installed; run `sidecar status`");
161
+ }
162
+ const fallback = (why) => ({
163
+ navigator: suggested,
164
+ chosenBy: `default: the other agent (${why})`,
165
+ });
166
+ if (candidates.length === 1)
167
+ return fallback("the only one available");
168
+ // No form in this client: the choice is still the user's, so the driver puts it to them.
169
+ if (!this.elicit) {
170
+ throw new ToolError(`this client cannot show the user a form: ask the user which navigator to use ` +
171
+ `(${candidates.join(", ")}; suggested: ${suggested}, another app than you), ` +
172
+ `then call sidecar_open again with navigator set to their pick`);
173
+ }
174
+ const timeout = this.#opts.elicitTimeoutMs ?? ELICIT_TIMEOUT_MS;
175
+ let timer;
176
+ const answer = await Promise.race([
177
+ this.elicit(`Which navigator should review "${title}"?`, {
178
+ type: "object",
179
+ properties: {
180
+ navigator: {
181
+ type: "string",
182
+ title: "Navigator",
183
+ enum: candidates,
184
+ default: suggested,
185
+ description: "The read-only agent that gives the second opinion. Another agent than the driver is preselected.",
186
+ },
187
+ },
188
+ required: ["navigator"],
189
+ }, timeout).catch(() => null),
190
+ new Promise((resolve) => {
191
+ timer = setTimeout(() => resolve(null), timeout);
192
+ }),
193
+ ]);
194
+ clearTimeout(timer);
195
+ if (!answer)
196
+ return fallback("no answer from the user");
197
+ // Headless Claude Code (-p) cancels every form at once, so cancel cannot mean "do not open".
198
+ if (answer.action === "cancel")
199
+ return fallback("the form was cancelled");
200
+ if (answer.action === "decline")
201
+ return fallback("the user declined to choose");
202
+ const picked = answer.content?.navigator;
203
+ if (typeof picked === "string" && candidates.includes(picked))
204
+ return { navigator: picked, chosenBy: "user" };
205
+ return fallback("the answer was not an available navigator");
206
+ }
207
+ /** Navigators whose CLI is installed. A CLI removed after open fails its ask as not-installed. */
208
+ #candidates() {
209
+ const installed = this.#opts.installed ?? ((id) => isInstalled(getNavigator(id)));
210
+ return selectableNavigatorIds().filter(installed);
211
+ }
212
+ attach(input) {
213
+ return this.#mutex.run(async () => {
214
+ await reconcile(this.#store, input.case_id);
215
+ const { state, reopened } = await this.#store.transact(input.case_id, (events, append) => {
216
+ const s = fold(events);
217
+ // Close cancels the ask in flight at that moment only, so no ask may run across a reopen.
218
+ if (s.closed && s.inFlight) {
219
+ const askId = s.inFlight.askId;
220
+ throw new ToolError(`case ${input.case_id} is closed and its ask ${askId} is still ending; ` +
221
+ `call sidecar_wait with case_id=${input.case_id} ask_id=${askId}, then attach again`);
222
+ }
223
+ // Every refusal comes before the first append: an append is written at once.
224
+ const foreign = s.owner && s.owner.token !== this.#owner.token ? s.owner : undefined;
225
+ // No lease and no takeover: a live owner is an agent session still open somewhere.
226
+ if (foreign && processAlive(foreign.pid, foreign.start)) {
227
+ const who = foreign.driver ? `${foreign.driver} session` : "session";
228
+ throw new ToolError(`case ${input.case_id} is attached to a live ${who} (sidecar MCP server pid ${foreign.pid}). ` +
229
+ `Detach or close the case from that session, or exit it; if the process is hung, \`kill ${foreign.pid}\`.`);
230
+ }
231
+ const appended = [];
232
+ if (s.closed) {
233
+ appended.push(append({
234
+ author: "sidecar",
235
+ kind: "reopened",
236
+ token: this.#owner.token,
237
+ ...(input.reason ? { reason: input.reason } : {}),
238
+ }));
239
+ }
240
+ if (foreign) {
241
+ appended.push(append({
242
+ author: "sidecar",
243
+ kind: "detached",
244
+ token: foreign.token,
245
+ reason: "owner-gone",
246
+ }));
247
+ }
248
+ if (s.owner?.token !== this.#owner.token)
249
+ appended.push(append({ author: "sidecar", kind: "attached", owner: this.#owner }));
250
+ // Taken inside the transaction, so a failure after it cannot leave the case owned but unknown here.
251
+ this.#cases.add(input.case_id);
252
+ // Summarise the case as this attach left it, not as it found it.
253
+ return { state: fold([...events, ...appended]), reopened: s.closed };
254
+ });
255
+ return {
256
+ ...summary(input.case_id, state, true),
257
+ ...(reopened
258
+ ? {
259
+ reopened: true,
260
+ next: "The case was closed and is open again. Tell the user, then call sidecar_read to rebuild the case context.",
261
+ }
262
+ : { next: "call sidecar_read to rebuild the case context" }),
263
+ };
264
+ });
265
+ }
266
+ async ask(input) {
267
+ const result = await this.#turn(input);
268
+ if ("unsettled" in result)
269
+ throw new Error("an ask is never refused for having nothing to review");
270
+ return result;
271
+ }
272
+ /** How long a turn call waits for its outcome before it returns pending. */
273
+ get askBudgetMs() {
274
+ return this.#opts.budgetMs ?? this.#driver.askBudgetMs;
275
+ }
276
+ /** A turn with no new question: the navigator reviews the decisions awaiting it. */
277
+ review(input) {
278
+ return this.#turn({ ...input, body: REVIEW_ASK, review: true });
279
+ }
280
+ async #turn(input) {
281
+ const deadline = Date.now() + this.askBudgetMs;
282
+ // The case is resolved inside the mutex: a detach or open queued before this call may change it.
283
+ const outcome = await this.#mutex.run(async () => {
284
+ const caseId = await this.#target(input.case_id);
285
+ await this.#reportDriver(caseId);
286
+ try {
287
+ const dispatched = await dispatchAsk(this.#store, caseId, { body: input.body, key: input.key, ...(input.review ? { review: true } : {}) }, this.#opts.runnerEnv ?? {}, (s) => {
288
+ this.#checkOwner(caseId, s);
289
+ // Checked in the dispatch transaction, so no turn that settled the last point can slip in
290
+ // between. A reused key still returns its original ask or review.
291
+ const reused = [...s.asks.values()].some((a) => a.key === input.key);
292
+ if (reused)
293
+ return;
294
+ // A case opened with an adapter sidecar no longer has could take no turn: refuse before
295
+ // the ask is appended, rather than let its runner fail.
296
+ const navigator = String(s.opened.navigator);
297
+ if (!findAdapter(navigator)?.navigator) {
298
+ throw new ToolError(`case ${caseId}'s navigator ${navigator} is no longer supported; read or close the case, and open a new one`);
299
+ }
300
+ if (!input.review)
301
+ return;
302
+ const reviewBudget = this.#reviewBudget();
303
+ if (awaitingReview(s.items, reviewBudget).length === 0)
304
+ throw new NothingToReview(this.#unsettled(s, reviewBudget));
305
+ });
306
+ return { caseId, dispatched };
307
+ }
308
+ catch (err) {
309
+ if (err instanceof NothingToReview)
310
+ return { caseId, nothing: nothingToReview(err.unsettled) };
311
+ throw err;
312
+ }
313
+ });
314
+ if ("nothing" in outcome)
315
+ return { case_id: outcome.caseId, ...outcome.nothing };
316
+ const { caseId, dispatched } = outcome;
317
+ if (dispatched.status === "busy") {
318
+ return {
319
+ case_id: caseId,
320
+ status: "busy",
321
+ ask_id: dispatched.askId,
322
+ next: "Another ask is in flight. Call sidecar_wait on it first.",
323
+ };
324
+ }
325
+ // Waiting happens outside the mutex, so close and EOF stay actionable meanwhile.
326
+ return this.#render(caseId, await waitForOutcome(this.#store, caseId, dispatched.askId, deadline));
327
+ }
328
+ /** Waiting changes nothing, so it needs no ownership: any case may be named. */
329
+ async wait(input) {
330
+ const deadline = Date.now() + this.askBudgetMs;
331
+ const caseId = input.case_id ?? this.#only();
332
+ // An unknown id would otherwise wait out the budget and read as a turn still running.
333
+ if (!fold(await this.#store.read(caseId)).asks.has(input.ask_id)) {
334
+ throw new ToolError(`case ${caseId} has no ask ${input.ask_id}`);
335
+ }
336
+ return this.#render(caseId, await waitForOutcome(this.#store, caseId, input.ask_id, deadline));
337
+ }
338
+ /**
339
+ * A turn's outcome, with what the driver must do next. Reads the case for the items it touched.
340
+ * Every outcome names its case: a retry or a wait passes it back.
341
+ */
342
+ async #render(caseId, result) {
343
+ if (result.status === "pending") {
344
+ return {
345
+ case_id: caseId,
346
+ status: "pending",
347
+ ask_id: result.askId,
348
+ next: "The navigator is still working. Call sidecar_wait, or first do work that does not depend on this ask and then call sidecar_wait.",
349
+ };
350
+ }
351
+ const e = result.event;
352
+ const state = fold(await this.#store.read(caseId));
353
+ // A review turn finds its points settled by an earlier turn when it starts; nothing was spent.
354
+ if (result.status === "failed" &&
355
+ foundNothingToReview(e) &&
356
+ state.asks.get(String(e.askId))?.event.review) {
357
+ return {
358
+ case_id: caseId,
359
+ ...nothingToReview(this.#unsettled(state)),
360
+ ask_id: String(e.askId),
361
+ };
362
+ }
363
+ if (result.status === "failed")
364
+ return {
365
+ case_id: caseId,
366
+ ...unavailable(String(e.askId), String(e.outcome), e.detail, e.hint),
367
+ };
368
+ return { case_id: caseId, ...renderOpinion(e, state, this.#reviewBudget()) };
369
+ }
370
+ /** Read per call, so a changed config applies at once. */
371
+ #reviewBudget() {
372
+ return loadConfig(this.#opts.store.home).reviewBudget;
373
+ }
374
+ /** The items not settled, as the driver sees them in tool results. Reads the config once per call. */
375
+ #unsettled(state, budget = this.#reviewBudget()) {
376
+ return unsettled(state.items).map((i) => itemSummary(i, budget));
377
+ }
378
+ /**
379
+ * Records a decision or a note. Several refs record the same text once per ref: one decision may
380
+ * settle several points, and each point is still reviewed on its own. A bad ref records nothing;
381
+ * the events are appended one by one, so a crash between appends can leave a prefix recorded.
382
+ */
383
+ async record(input) {
384
+ if (input.kind === "note" && input.state !== undefined)
385
+ throw new ToolError("state applies to decisions only");
386
+ const refs = input.ref === undefined
387
+ ? [undefined]
388
+ : [...new Set(Array.isArray(input.ref) ? input.ref : [input.ref])];
389
+ return this.#mutex.run(async () => {
390
+ const caseId = await this.#target(input.case_id);
391
+ await this.#reportDriver(caseId);
392
+ const recorded = await this.#owned(caseId, (s, append) => {
393
+ // Every ref is checked before the first append, so a bad ref records nothing.
394
+ const items = refs.map((ref) => {
395
+ const item = ref !== undefined ? s.items.get(ref) : undefined;
396
+ if (input.kind === "decision")
397
+ checkDecisionRef(caseId, s, ref, item, input.state);
398
+ else if (ref !== undefined && !item && !s.asks.has(ref))
399
+ throw new ToolError(`case ${caseId} has no point or ask ${ref}`);
400
+ return input.kind === "decision" ? item : undefined;
401
+ });
402
+ const state = input.kind === "decision" ? { state: input.state ?? "ready" } : {};
403
+ return refs.map((ref, i) => ({
404
+ n: append({
405
+ author: "driver",
406
+ kind: input.kind,
407
+ body: input.body,
408
+ ...(ref !== undefined ? { ref } : {}),
409
+ ...state,
410
+ }).n,
411
+ item: items[i],
412
+ }));
413
+ });
414
+ const points = recorded.flatMap((r) => (r.item ? [r.item] : []));
415
+ const reviewBudget = this.#reviewBudget();
416
+ const n = Array.isArray(input.ref) ? recorded.map((r) => r.n) : recorded[0].n;
417
+ const many = (list, one, more) => (list.length > 1 ? more : one);
418
+ if (input.state === "planned" && points.length > 0) {
419
+ const planned = points.map((i) => i.ref);
420
+ return {
421
+ n,
422
+ next: `${planned.join(", ")} ${many(planned, "is", "are")} planned: the navigator does not review ${many(planned, "it", "them")} until you record a ready decision on ${many(planned, "it", "them")}.`,
423
+ };
424
+ }
425
+ const spent = points.filter((i) => i.reviewTurns >= reviewBudget).map((i) => i.ref);
426
+ if (spent.length > 0) {
427
+ return {
428
+ n,
429
+ next: `${spent.join(", ")} ${many(spent, "has", "have")} used ${many(spent, "its", "their")} ${reviewBudget} reviews; the navigator will not review this decision. Tell the user ${many(spent, "it is", "they are")} left for them.`,
430
+ };
431
+ }
432
+ return { n };
433
+ });
434
+ }
435
+ async read(input) {
436
+ const caseId = input.case_id ?? this.#only();
437
+ const limit = Math.min(Math.max(input.limit ?? 100, 1), 500);
438
+ const events = (await this.#store.read(caseId)).filter((e) => e.n > (input.since_n ?? -1));
439
+ const page = events.slice(0, limit);
440
+ return {
441
+ case_id: caseId,
442
+ events: page,
443
+ more: events.length > page.length,
444
+ next_since_n: page.at(-1)?.n ?? input.since_n ?? -1,
445
+ };
446
+ }
447
+ /**
448
+ * One case in detail when the driver names it or the server owns exactly one. Otherwise the cases
449
+ * the server owns, so a driver whose open or attach result was lost can find its case.
450
+ */
451
+ async status(input = {}) {
452
+ if (input.case_id !== undefined)
453
+ return this.#details(input.case_id);
454
+ // Captured once: a detach and an open may change the attached cases while the reads wait.
455
+ // Attachment is what each log says, not what this server remembers.
456
+ const held = [...this.#cases];
457
+ if (held.length === 1) {
458
+ const details = await this.#details(held[0]);
459
+ const { unsettled: _, ...brief } = details;
460
+ return { ...details, cases: details.attached ? [brief] : [] };
461
+ }
462
+ const cases = [];
463
+ for (const caseId of held) {
464
+ const { unsettled: _, ...brief } = await this.#details(caseId);
465
+ if (brief.attached)
466
+ cases.push(brief);
467
+ }
468
+ return { attached: cases.length > 0, cases };
469
+ }
470
+ async #details(caseId) {
471
+ const state = fold(await this.#store.read(caseId));
472
+ return {
473
+ ...summary(caseId, state, state.owner?.token === this.#owner.token),
474
+ dashboard: this.#dashboardLink(caseId),
475
+ unsettled: this.#unsettled(state),
476
+ };
477
+ }
478
+ async list(input) {
479
+ const cases = [];
480
+ for (const caseId of this.#store.listCaseIds()) {
481
+ try {
482
+ const s = fold(await this.#store.read(caseId));
483
+ cases.push(summary(caseId, s, s.owner?.token === this.#owner.token));
484
+ }
485
+ catch (err) {
486
+ cases.push({ case_id: caseId, state: "unreadable", error: err.message });
487
+ }
488
+ }
489
+ return {
490
+ cases: cases
491
+ .filter((c) => !input.state || c.state === input.state)
492
+ .filter((c) => !input.workspace || ("workspace" in c && c.workspace === input.workspace))
493
+ .sort((a, b) => ("created" in b ? b.created : "").localeCompare("created" in a ? a.created : "")),
494
+ };
495
+ }
496
+ /** Releases the case without closing it, so another session can attach it. */
497
+ detach(input = {}) {
498
+ return this.#mutex.run(async () => {
499
+ const caseId = await this.#target(input.case_id);
500
+ // Another server that attaches later cannot look the opening turn up: this one does it now.
501
+ await this.#reportDriver(caseId);
502
+ await this.#owned(caseId, (_s, append) => {
503
+ append({
504
+ author: "sidecar",
505
+ kind: "detached",
506
+ token: this.#owner.token,
507
+ reason: "detached",
508
+ });
509
+ });
510
+ this.#cases.delete(caseId);
511
+ return {
512
+ case_id: caseId,
513
+ state: "open",
514
+ next: "A running turn continues, and its result is recorded. Call sidecar_attach to continue the case.",
515
+ };
516
+ });
517
+ }
518
+ close(input) {
519
+ return this.#mutex.run(async () => {
520
+ const caseId = await this.#target(input.case_id);
521
+ await this.#reportDriver(caseId);
522
+ const { left, askId } = await this.#owned(caseId, (s, append) => {
523
+ append({
524
+ author: "sidecar",
525
+ kind: "closed",
526
+ reason: input.reason ?? "closed by the driver",
527
+ });
528
+ append({ author: "sidecar", kind: "detached", token: this.#owner.token, reason: "closed" });
529
+ return { left: this.#unsettled(s), askId: s.inFlight?.askId };
530
+ });
531
+ this.#cases.delete(caseId);
532
+ // Only the ask in flight at close: after a reopen, another one may be running.
533
+ await cancelTurn(this.#store, caseId, askId);
534
+ // Advisory: closing never waits for reviews, but the driver reports what was left unsettled.
535
+ return left.length > 0
536
+ ? {
537
+ case_id: caseId,
538
+ state: "closed",
539
+ unsettled: left,
540
+ next: "Tell the user which of the navigator's points were left unsettled, and why.",
541
+ }
542
+ : { case_id: caseId, state: "closed" };
543
+ });
544
+ }
545
+ /** The driver session ended: release every case. A running turn continues; the next attach finds its result. */
546
+ async disconnect() {
547
+ for (const caseId of this.#cases) {
548
+ await this.#reportDriver(caseId);
549
+ try {
550
+ await this.#owned(caseId, (_s, append) => {
551
+ append({
552
+ author: "sidecar",
553
+ kind: "detached",
554
+ token: this.#owner.token,
555
+ reason: "driver-disconnected",
556
+ });
557
+ });
558
+ }
559
+ catch {
560
+ // Ownership already lost, or the store is unreachable; nothing left to release.
561
+ }
562
+ this.#cases.delete(caseId);
563
+ }
564
+ }
565
+ #dashboardLink(caseId) {
566
+ return new URL(`cases/${caseId}`, this.#opts.dashboardUrl).href;
567
+ }
568
+ /**
569
+ * The case a change acts on: the one it names, which this server must own, or else the only case
570
+ * it owns. Runs inside the mutex. Among several cases, those another driver has taken are dropped
571
+ * first, so they never become the default; inside the mutex, no attach can interleave.
572
+ */
573
+ async #target(caseId) {
574
+ if (caseId !== undefined) {
575
+ if (!this.#cases.has(caseId))
576
+ throw new ToolError(`this server is not attached to case ${caseId}; call sidecar_attach first`);
577
+ return caseId;
578
+ }
579
+ if (this.#cases.size > 1)
580
+ await this.#prune();
581
+ return this.#only();
582
+ }
583
+ /**
584
+ * The only case this server holds. Reads and waits use it without pruning: they run outside the
585
+ * mutex, where a prune could drop a case an attach has just restored.
586
+ */
587
+ #only() {
588
+ const owned = [...this.#cases];
589
+ if (owned.length === 0)
590
+ throw new ToolError("no case attached; call sidecar_open or sidecar_attach first");
591
+ if (owned.length > 1)
592
+ throw new ToolError(`attached to several cases (${owned.join(", ")}); pass case_id`);
593
+ return owned[0];
594
+ }
595
+ /** Drops the cases whose log names another owner. An unreadable log keeps its case. */
596
+ async #prune() {
597
+ for (const caseId of this.#cases) {
598
+ try {
599
+ if (fold(await this.#store.read(caseId)).owner?.token !== this.#owner.token)
600
+ this.#cases.delete(caseId);
601
+ }
602
+ catch {
603
+ // The next call on that case reports the store error itself.
604
+ }
605
+ }
606
+ }
607
+ #checkOwner(caseId, state) {
608
+ if (state.owner?.token === this.#owner.token)
609
+ return;
610
+ this.#cases.delete(caseId);
611
+ throw new ToolError(`this server is no longer attached to case ${caseId}; another driver attached to it`);
612
+ }
613
+ /**
614
+ * Looks up, once, the turn that opened a case this server opened, now that the client has
615
+ * recorded it (see Driver.turnOf), and records what it names. Runs before the call's own work, and
616
+ * before the server lets the case go (detach, disconnect): a server that attaches later cannot look
617
+ * it up. Best effort: a failure costs the call nothing, and no lookup is retried.
618
+ */
619
+ async #reportDriver(caseId) {
620
+ const call = this.#unreported.get(caseId);
621
+ if (call === undefined)
622
+ return;
623
+ this.#unreported.delete(caseId);
624
+ try {
625
+ const turn = this.#driver.turnOf?.(call) ?? null;
626
+ await this.#owned(caseId, (_s, append) => {
627
+ append({
628
+ author: "sidecar",
629
+ kind: "driver-reported",
630
+ call,
631
+ ...(turn?.model ? { model: turn.model } : {}),
632
+ ...(turn?.effort ? { effort: turn.effort } : {}),
633
+ });
634
+ });
635
+ }
636
+ catch {
637
+ // The call's own work reports any problem with the case.
638
+ }
639
+ }
640
+ /** A transaction that runs only while this server still owns the case. */
641
+ #owned(caseId, fn) {
642
+ return this.#store.transact(caseId, (events, append) => {
643
+ const state = fold(events);
644
+ this.#checkOwner(caseId, state);
645
+ return fn(state, append);
646
+ });
647
+ }
648
+ }
649
+ function summary(caseId, s, attached) {
650
+ return {
651
+ case_id: caseId,
652
+ title: String(s.opened.title ?? ""),
653
+ state: caseStatus(s),
654
+ workspace: String(s.opened.workspace ?? ""),
655
+ navigator: String(s.opened.navigator ?? ""),
656
+ created: s.opened.ts,
657
+ in_flight_ask: s.inFlight?.askId ?? null,
658
+ attached,
659
+ };
660
+ }
661
+ function unavailable(askId, outcome, detail, hint) {
662
+ return {
663
+ status: "failed",
664
+ ask_id: askId,
665
+ outcome,
666
+ detail: detail ?? null,
667
+ hint: hint ?? null,
668
+ message: `navigator unavailable: ${outcome}, proceeding`,
669
+ next: `Tell the user the message and continue without the opinion. Record your own conclusion as a note with ref=${askId}. Ask again later with a new key if you still need the opinion.`,
670
+ };
671
+ }
672
+ /**
673
+ * A decision answers an opinion: it refs a point, or an ask the navigator answered without raising
674
+ * one. A conclusion on an ask with no opinion — failed or still running — is a note.
675
+ */
676
+ function checkDecisionRef(caseId, s, ref, item, state) {
677
+ if (ref === undefined)
678
+ throw new ToolError("a decision needs ref: the id of the point or ask it answers");
679
+ if (item)
680
+ return;
681
+ const ask = s.asks.get(ref);
682
+ if (!ask)
683
+ throw new ToolError(`case ${caseId} has no point or ask ${ref}`);
684
+ if (ask.terminal?.kind !== "opinion") {
685
+ throw new ToolError(`ask ${ref} has no opinion to decide on; record your own conclusion as kind=note ref=${ref}`);
686
+ }
687
+ // Its points would stay open and unreviewed under a decision on the ask.
688
+ const flags = flagsOf(ask.terminal).map((f) => f.id);
689
+ if (flags.length > 0)
690
+ throw new ToolError(`ask ${ref} raised points; decide each by its own ref (${flags.join(", ")})`);
691
+ if (state !== undefined && state !== "ready")
692
+ throw new ToolError(`ask ${ref} raised no point; state applies to points only`);
693
+ }
694
+ /** An item as the driver sees it in tool results. */
695
+ function itemSummary(i, budget) {
696
+ return {
697
+ ref: i.ref,
698
+ kind: i.kind,
699
+ status: itemStatus(i, budget),
700
+ severity: i.severity ?? null,
701
+ point: i.point,
702
+ reviews_used: i.reviewTurns,
703
+ };
704
+ }
705
+ function renderOpinion(e, state, budget) {
706
+ const askId = String(e.askId);
707
+ const isReview = state.asks.get(askId)?.event.review === true;
708
+ const flagIds = flagsOf(e).map((f) => f.id);
709
+ const targets = reviewTargetsOf(e);
710
+ // Each review with whether it applied: a review of a decision since superseded is history only.
711
+ const reviews = reviewsOf(e).map((r) => ({
712
+ ref: r.ref,
713
+ status: r.status,
714
+ body: r.body,
715
+ decision_n: r.decisionN,
716
+ applied: state.items.get(r.ref)?.reviews.find((h) => h.opinionN === e.n)?.applied ?? false,
717
+ }));
718
+ // A replayed result may predate the driver's latest decision: only a review of that one asks for action.
719
+ const current = (r) => r.applied && state.items.get(r.ref)?.decision?.n === r.decision_n;
720
+ const next = [];
721
+ // A standing disagreement goes to the user at once: they may intervene.
722
+ for (const r of reviews.filter((r) => current(r) && r.status === "held")) {
723
+ next.push(`Tell the user now: the navigator holds its point on ${r.ref} against your decision; its reason is in reviews. The user may decide.`);
724
+ }
725
+ for (const r of reviews.filter((r) => current(r) && r.status === "reopened")) {
726
+ next.push(`The navigator reopened ${r.ref}; what is missing is in reviews. Record a new decision with ref=${r.ref}, or leave it for the user.`);
727
+ }
728
+ // A newer decision may have been recorded during the turn: say what each point awaits now.
729
+ const now = (ref) => {
730
+ const item = state.items.get(ref);
731
+ return item ? itemStatus(item, budget) : undefined;
732
+ };
733
+ const stale = reviews.filter((r) => !current(r)).map((r) => r.ref);
734
+ if (stale.length > 0) {
735
+ next.push(`The navigator reviewed an earlier decision on ${stale.join(", ")}, not your newer one; ${awaits(stale, now)}`);
736
+ }
737
+ const omitted = targets.map((t) => t.ref).filter((ref) => !reviews.some((r) => r.ref === ref));
738
+ if (omitted.length > 0)
739
+ next.push(`The navigator did not review ${omitted.join(", ")}; ${awaits(omitted, now)}`);
740
+ // Without a decision that refs its id, an item stays open: on the dashboard and in a re-brief seed.
741
+ if (!isReview) {
742
+ const point = state.items.has(askId) ? [askId] : [];
743
+ const refs = [...point, ...flagIds];
744
+ next.push(refs.length > 0
745
+ ? `Record a decision on each point with sidecar_record kind=decision (${refs.join(", ")}); one decision may name several refs when it settles them the same way. The navigator reviews each point.`
746
+ : `Record your decision on the opinion with sidecar_record kind=decision ref=${askId}.`);
747
+ }
748
+ else if (flagIds.length > 0) {
749
+ next.push(`Record a decision on each new point with sidecar_record kind=decision (${flagIds.join(", ")}).`);
750
+ }
751
+ const waiting = awaitingReview(state.items, budget).map((i) => i.ref);
752
+ if (waiting.length > 0) {
753
+ next.push(`Awaiting the navigator's review: ${waiting.join(", ")}. They ride along with your next ask, or call sidecar_review before sidecar_close.`);
754
+ }
755
+ return {
756
+ status: "opinion",
757
+ ask_id: askId,
758
+ verdict: e.verdict,
759
+ ...(e.severity !== undefined ? { severity: e.severity } : {}),
760
+ body: e.body,
761
+ flags: e.flags,
762
+ limits: Array.isArray(e.limits) ? e.limits : [],
763
+ reviews,
764
+ next: next.join(" "),
765
+ };
766
+ }
767
+ /** Where each point stands now, for a review that did not settle it. */
768
+ function awaits(refs, now) {
769
+ return (refs
770
+ .map((ref) => {
771
+ const status = now(ref);
772
+ if (status === "addressed")
773
+ return `${ref} still awaits review`;
774
+ if (status === "planned")
775
+ return `${ref} is planned: it is not reviewed until you record a ready decision on it`;
776
+ return `${ref} is ${status ?? "unknown"}`;
777
+ })
778
+ .join("; ") + ".");
779
+ }
780
+ /** A review with nothing to do. Planned points are why, when there are some: the driver may not know. */
781
+ function nothingToReview(left) {
782
+ const planned = left.filter((i) => i.status === "planned").map((i) => i.ref);
783
+ return {
784
+ status: "nothing-to-review",
785
+ unsettled: left,
786
+ ...(planned.length > 0
787
+ ? {
788
+ next: `${planned.join(", ")} ${planned.length > 1 ? "are" : "is"} planned: record a ready decision once the change exists, then review.`,
789
+ }
790
+ : {}),
791
+ };
792
+ }
793
+ /** Thrown inside the dispatch transaction when a review turn would have nothing to review. */
794
+ class NothingToReview extends Error {
795
+ unsettled;
796
+ constructor(unsettled) {
797
+ super("nothing awaits review");
798
+ this.unsettled = unsettled;
799
+ }
800
+ }