@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.
- package/LICENSE +21 -0
- package/README.md +295 -2
- package/dist/bin/sidecar-dashboard.js +27 -0
- package/dist/bin/sidecar-mcp.js +35 -0
- package/dist/bin/sidecar.js +70 -0
- package/dist/src/adapters/claude-code.js +333 -0
- package/dist/src/adapters/claude-desktop.js +184 -0
- package/dist/src/adapters/codex.js +383 -0
- package/dist/src/adapters/index.js +38 -0
- package/dist/src/adapters/installed.js +25 -0
- package/dist/src/adapters/outcome.js +30 -0
- package/dist/src/adapters/registration.js +69 -0
- package/dist/src/adapters/types.js +1 -0
- package/dist/src/cases/events.js +9 -0
- package/dist/src/cases/items.js +120 -0
- package/dist/src/cases/lock.js +80 -0
- package/dist/src/cases/opinion.js +58 -0
- package/dist/src/cases/state.js +121 -0
- package/dist/src/cases/store.js +181 -0
- package/dist/src/cases/usage.js +36 -0
- package/dist/src/cli/deps.js +18 -0
- package/dist/src/cli/lines.js +11 -0
- package/dist/src/cli/list.js +44 -0
- package/dist/src/cli/setup.js +202 -0
- package/dist/src/cli/status.js +111 -0
- package/dist/src/cli/style.js +26 -0
- package/dist/src/cli/ui.js +170 -0
- package/dist/src/cli/uninstall.js +73 -0
- package/dist/src/config.js +108 -0
- package/dist/src/dashboard/cases.js +109 -0
- package/dist/src/dashboard/html.js +31 -0
- package/dist/src/dashboard/links.js +35 -0
- package/dist/src/dashboard/marks.js +16 -0
- package/dist/src/dashboard/pages.js +516 -0
- package/dist/src/dashboard/server.js +305 -0
- package/dist/src/dashboard/service.js +138 -0
- package/dist/src/dashboard/static/agents/NOTICE +32 -0
- package/dist/src/dashboard/static/agents/claude-code.svg +1 -0
- package/dist/src/dashboard/static/agents/claude-desktop.svg +1 -0
- package/dist/src/dashboard/static/agents/codex.svg +1 -0
- package/dist/src/dashboard/static/app.css +1121 -0
- package/dist/src/dashboard/static/app.js +256 -0
- package/dist/src/dashboard/static/times.js +44 -0
- package/dist/src/dashboard/view.js +25 -0
- package/dist/src/lib/agent-process.js +57 -0
- package/dist/src/lib/atomic-write.js +35 -0
- package/dist/src/lib/command.js +20 -0
- package/dist/src/lib/failpoint.js +14 -0
- package/dist/src/lib/git.js +14 -0
- package/dist/src/lib/json.js +2 -0
- package/dist/src/lib/paths.js +19 -0
- package/dist/src/lib/proc.js +80 -0
- package/dist/src/lib/version.js +43 -0
- package/dist/src/mcp/server.js +800 -0
- package/dist/src/mcp/stdio.js +31 -0
- package/dist/src/mcp/tools.js +180 -0
- package/dist/src/turns/dispatch.js +188 -0
- package/dist/src/turns/knobs.js +14 -0
- package/dist/src/turns/prompt.js +284 -0
- package/dist/src/turns/runner.js +283 -0
- package/package.json +44 -4
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { DEFAULTS } from "../config.js";
|
|
2
|
+
import { decisionState, unsettled } from "../cases/items.js";
|
|
3
|
+
const ROLE = `You are the navigator in a sidecar case. The driver, another coding agent, works on a task in this workspace and asks you for an independent opinion, one question at a time. You are read-only: you read and search; you never change anything.
|
|
4
|
+
|
|
5
|
+
How to work
|
|
6
|
+
- Check the driver's claim against the source yourself. Re-read every file:line the driver cites; do not trust its summary.
|
|
7
|
+
- Your value is dissent. Look for the case where the claim fails before you agree with it. Do not restate the driver's position.
|
|
8
|
+
- Answer the question that was asked. Put each point into its own entry of flags: the driver accepts or rejects each point on its own, and you review each decision.
|
|
9
|
+
- Separate what you read from what you infer, and mark inference as inference. An opinion that cites nothing will be discounted.
|
|
10
|
+
|
|
11
|
+
Reply with the JSON object the output schema requires:
|
|
12
|
+
- verdict: "agree" when you checked and the claim holds; "disagree" when you found a specific defect; "needs-info" when one specific fact decides it and you cannot get it — name that fact. When one part of a claim fails, disagree.
|
|
13
|
+
- body: the verdict in one sentence, then the evidence that decides it, one line per source as path:line; when no file applies, the fact, the reasoning or a named source instead. Never invent a citation. Five lines or fewer. Do not repeat the points in flags. No preamble; do not restate the question.
|
|
14
|
+
- flags: one entry per point — a defect, a gap, or a fact the driver has wrong — whether it answers the question or goes beyond it. Each entry holds one concern the driver can act on, with its evidence. Do not join points in one entry. severity: "high": correctness, data loss, security, or a wire-format or protocol violation. "med": a real defect with limited reach. "low": a minor gap. An empty array when you found nothing to act on.
|
|
15
|
+
- limits: what you could not check, for example tests not run or a file you could not read. Not a point: the driver does not decide on it. An empty array if none.
|
|
16
|
+
- reviews: one entry per point under "Awaiting your review", before you answer the new ask. ref is the id shown in brackets, without the brackets. An empty array if there is none. body: the reason for the status in one or two sentences, with its evidence as path:line where a file applies. Check the driver's decision against the source, as you check a claim:
|
|
17
|
+
- "confirmed": the decision settles your point — the fix is in the code (cite it), or the driver's reason holds.
|
|
18
|
+
- "reopened": it does not settle it; say what is still missing.
|
|
19
|
+
- "held": the driver rejected your point and you still stand by it. Say why, briefly; the user decides from here.
|
|
20
|
+
A decision marked "deferred" moves the point out of this case. Confirm it when that is reasonable — the point stays listed as deferred, not settled — or hold it when the point must be resolved here.
|
|
21
|
+
A point or decision marked "…(truncated)" is shown in part. Confirm only what the shown text lets you check; otherwise reopen it and say what is missing.`;
|
|
22
|
+
/** Why a review turn ends without spawning: an earlier turn settled every point it was for. */
|
|
23
|
+
export const NOTHING_AWAITED = "nothing awaited review when the turn started";
|
|
24
|
+
/** The outcome of a review turn that ends that way. It spent nothing and failed nothing. */
|
|
25
|
+
export const NOTHING_TO_REVIEW = "nothing-to-review";
|
|
26
|
+
/**
|
|
27
|
+
* Whether a turn-failed event ends a review turn that found nothing to review. A log may record it
|
|
28
|
+
* as cancelled, with NOTHING_AWAITED as its detail.
|
|
29
|
+
*/
|
|
30
|
+
export const foundNothingToReview = (e) => e.outcome === NOTHING_TO_REVIEW || (e.outcome === "cancelled" && e.detail === NOTHING_AWAITED);
|
|
31
|
+
/** The ask a review turn carries: no new question, only the points awaiting review. */
|
|
32
|
+
export const REVIEW_ASK = 'No new question. Review every point under "Awaiting your review". Set verdict to "agree" when you confirm them all, otherwise "disagree", with the reason in body.';
|
|
33
|
+
const REBRIEFED = "Your previous session on this case was lost. Below is the case record so far; treat it as what you already know.";
|
|
34
|
+
/**
|
|
35
|
+
* Limits on what the driver writes, enforced by the MCP tools. With them, the mandatory part of any
|
|
36
|
+
* prompt — role, brief, ask, one review item — fits the smallest allowed bound (MIN_SEED_BOUND).
|
|
37
|
+
*/
|
|
38
|
+
export const BRIEF_MAX = 16_000;
|
|
39
|
+
export const ASK_MAX = 8_000;
|
|
40
|
+
export const RECORD_MAX = 8_000;
|
|
41
|
+
/**
|
|
42
|
+
* The navigator's input for one turn. A resumed session gets the driver's updates, the items
|
|
43
|
+
* awaiting review, and the ask. A fresh session — the case's first, or a re-brief — gets the role,
|
|
44
|
+
* the brief and a seed of the case instead of the updates. The whole text stays within `bound`:
|
|
45
|
+
* the mandatory part is never cut; the other sections take the newest entries that fit and say
|
|
46
|
+
* how many earlier ones they leave out. See docs/design.md → Navigator turn, Re-brief, Review.
|
|
47
|
+
*/
|
|
48
|
+
export function buildPrompt(state, ask, opts) {
|
|
49
|
+
const bound = opts.bound ?? DEFAULTS.seedBound;
|
|
50
|
+
const review = opts.review ?? [];
|
|
51
|
+
// A decision under review is shown with its item, not a second time among the updates.
|
|
52
|
+
const shown = new Set(review.map((i) => i.decision.n));
|
|
53
|
+
const { head, tail, parts } = layout(state, ask, opts.fresh, opts.rebrief ?? false, review, shown, opts.git);
|
|
54
|
+
const size = fixedSize(head, tail, parts);
|
|
55
|
+
if (size > bound)
|
|
56
|
+
return { ok: false, size, bound };
|
|
57
|
+
let budget = bound - size;
|
|
58
|
+
const seeded = opts.fresh ? [(state.brief ?? state.opened).n, ...shown] : [];
|
|
59
|
+
const sections = [];
|
|
60
|
+
for (const part of parts) {
|
|
61
|
+
const kept = [];
|
|
62
|
+
for (const entry of [...part.entries].reverse()) {
|
|
63
|
+
const cost = entry.text.length + part.joiner.length;
|
|
64
|
+
if (cost > budget)
|
|
65
|
+
break;
|
|
66
|
+
budget -= cost;
|
|
67
|
+
kept.unshift(entry);
|
|
68
|
+
}
|
|
69
|
+
const left = part.entries.slice(0, part.entries.length - kept.length);
|
|
70
|
+
const lines = [...(left.length > 0 ? [omitted(left)] : []), ...kept.map((e) => e.text)];
|
|
71
|
+
sections.push(section(part.title, lines.join(part.joiner)));
|
|
72
|
+
seeded.push(...kept.flatMap((e) => e.seeded));
|
|
73
|
+
}
|
|
74
|
+
// A point and the exchange that raised it may both be kept: one opinion, listed once.
|
|
75
|
+
return {
|
|
76
|
+
ok: true,
|
|
77
|
+
text: [...head, ...sections, ...tail].join("\n\n"),
|
|
78
|
+
seeded: [...new Set(seeded)].sort((a, b) => a - b),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The room a turn's review section may take: what the bound leaves after the mandatory part of a
|
|
83
|
+
* re-brief, the larger of the two prompts, so the targets claimed for the turn fit either.
|
|
84
|
+
*/
|
|
85
|
+
export function reviewRoom(state, ask, bound, git) {
|
|
86
|
+
const { head, tail, parts } = layout(state, ask, true, true, [], new Set(), git);
|
|
87
|
+
return bound - fixedSize(head, tail, parts) - "\n\n".length;
|
|
88
|
+
}
|
|
89
|
+
function layout(state, ask, fresh, rebrief, review, shown, git) {
|
|
90
|
+
// A resumed session raised every point after its start itself; a fresh one holds none.
|
|
91
|
+
const reviewSection = renderReview(review, fresh ? undefined : (i) => i.raisedN > state.sessionStart);
|
|
92
|
+
const tail = [
|
|
93
|
+
...(reviewSection ? [reviewSection] : []),
|
|
94
|
+
...(fresh ? [] : [reRead(state, git)]),
|
|
95
|
+
section("Ask", String(ask.event.body)),
|
|
96
|
+
];
|
|
97
|
+
if (!fresh) {
|
|
98
|
+
const updates = state.driverNotes.filter((e) => e.n > state.watermark && !shown.has(e.n));
|
|
99
|
+
return {
|
|
100
|
+
head: [],
|
|
101
|
+
tail,
|
|
102
|
+
parts: nonEmpty([
|
|
103
|
+
{
|
|
104
|
+
title: "Driver updates since your last opinion",
|
|
105
|
+
entries: updates.map(noteEntry),
|
|
106
|
+
joiner: "\n",
|
|
107
|
+
},
|
|
108
|
+
]),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const head = [
|
|
112
|
+
ROLE,
|
|
113
|
+
...(rebrief ? [REBRIEFED] : []),
|
|
114
|
+
workspaceLine(state, git),
|
|
115
|
+
section("Brief", renderBrief(state.brief ?? state.opened)),
|
|
116
|
+
];
|
|
117
|
+
const notes = state.driverNotes.filter((e) => !shown.has(e.n));
|
|
118
|
+
const failedAsks = [...state.asks.values()].filter((a) => a !== ask && a.terminal?.kind !== "opinion");
|
|
119
|
+
// Unsettled points survive a re-brief; the ones under review this turn are listed with their decisions.
|
|
120
|
+
const pending = unsettled(state.items).filter((i) => !(i.decision && shown.has(i.decision.n)));
|
|
121
|
+
const exchanges = [...state.asks.values()].flatMap((a) => {
|
|
122
|
+
const opinion = a.terminal?.kind === "opinion" ? a.terminal : undefined;
|
|
123
|
+
if (!opinion || a === ask)
|
|
124
|
+
return [];
|
|
125
|
+
return [
|
|
126
|
+
{
|
|
127
|
+
text: `### Ask #${a.event.n}\n${capped(String(a.event.body))}\n\n### Your opinion (${[opinion.verdict, opinion.severity].filter((v) => v !== undefined).join(", ")})\n${capped(String(opinion.body))}`,
|
|
128
|
+
n: a.event.n,
|
|
129
|
+
seeded: [a.event.n, opinion.n],
|
|
130
|
+
},
|
|
131
|
+
];
|
|
132
|
+
});
|
|
133
|
+
return {
|
|
134
|
+
head,
|
|
135
|
+
tail,
|
|
136
|
+
parts: nonEmpty([
|
|
137
|
+
{ title: "Driver decisions and notes", entries: notes.map(noteEntry), joiner: "\n" },
|
|
138
|
+
{
|
|
139
|
+
title: "Earlier asks that got no opinion",
|
|
140
|
+
entries: failedAsks.map((a) => ({
|
|
141
|
+
text: `- #${a.event.n} ${capped(String(a.event.body))}`,
|
|
142
|
+
n: a.event.n,
|
|
143
|
+
seeded: [a.event.n],
|
|
144
|
+
})),
|
|
145
|
+
joiner: "\n",
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
title: "Your points not yet settled",
|
|
149
|
+
entries: pending.map((i) => ({
|
|
150
|
+
text: `- [${i.ref}] ${[i.status, i.severity].filter((v) => v !== undefined).join(", ")}: ${capped(i.point)}`,
|
|
151
|
+
n: i.raisedN,
|
|
152
|
+
seeded: [i.raisedN],
|
|
153
|
+
})),
|
|
154
|
+
joiner: "\n",
|
|
155
|
+
},
|
|
156
|
+
{ title: "Earlier exchanges", entries: exchanges, joiner: "\n\n" },
|
|
157
|
+
]),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
const nonEmpty = (parts) => parts.filter((p) => p.entries.length > 0);
|
|
161
|
+
/**
|
|
162
|
+
* The case's workspace is the navigator's working directory, but a navigator does not assume it,
|
|
163
|
+
* nor that it is a git repository: throwaway research folders often are not.
|
|
164
|
+
*/
|
|
165
|
+
function workspaceLine(state, git) {
|
|
166
|
+
const repo = git === undefined
|
|
167
|
+
? ""
|
|
168
|
+
: git
|
|
169
|
+
? " It is inside a git repository."
|
|
170
|
+
: " It is not in a git repository: git commands do not apply.";
|
|
171
|
+
return `Workspace: ${String(state.opened.workspace)}. It is your working directory.${repo} A relative path from the driver is relative to it.`;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* What may have changed since the session's last turn. The time is local, with its offset, in the
|
|
175
|
+
* form `ls -l --time-style=full-iso` prints, so the navigator can compare it with a file's.
|
|
176
|
+
*/
|
|
177
|
+
function reRead(state, git) {
|
|
178
|
+
const started = lastTurnStart(state);
|
|
179
|
+
const since = started
|
|
180
|
+
? `Your last turn started at ${localTime(started)}. The workspace may have changed since then: re-read a file before citing it if it was modified after that time (\`ls -l --time-style=full-iso\` shows when).`
|
|
181
|
+
: "The workspace may have changed since your last turn. Re-read a file before citing it if it may have changed.";
|
|
182
|
+
return git ? `${since} \`git status\` lists the files that differ from the last commit.` : since;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* When the turn of the latest opinion started. Not when it ended: the driver may edit a file during
|
|
186
|
+
* the turn, after the navigator read it.
|
|
187
|
+
*/
|
|
188
|
+
function lastTurnStart(state) {
|
|
189
|
+
let last;
|
|
190
|
+
for (const a of state.asks.values()) {
|
|
191
|
+
const opinion = a.terminal?.kind === "opinion" ? a.terminal : undefined;
|
|
192
|
+
const started = opinion && a.attempts.find((t) => t.attemptId === opinion.attemptId)?.started;
|
|
193
|
+
if (opinion && started && (!last || opinion.n > last.n))
|
|
194
|
+
last = { n: opinion.n, ts: started.ts };
|
|
195
|
+
}
|
|
196
|
+
return last?.ts;
|
|
197
|
+
}
|
|
198
|
+
/** `2026-10-17 15:04:05 +0200`: an ISO timestamp in the runner's local zone, the navigator's too. */
|
|
199
|
+
function localTime(iso) {
|
|
200
|
+
const d = new Date(iso);
|
|
201
|
+
const pad = (v) => String(Math.abs(v)).padStart(2, "0");
|
|
202
|
+
const offset = -d.getTimezoneOffset();
|
|
203
|
+
const zone = `${offset < 0 ? "-" : "+"}${pad(Math.trunc(offset / 60))}${pad(offset % 60)}`;
|
|
204
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())} ${zone}`;
|
|
205
|
+
}
|
|
206
|
+
/** The mandatory text, plus each section's header and room for its omission notice. */
|
|
207
|
+
function fixedSize(head, tail, parts) {
|
|
208
|
+
const reserved = parts.reduce((sum, p) => sum + "\n\n".length + section(p.title, "").length + NOTICE_MAX + p.joiner.length, 0);
|
|
209
|
+
return [...head, ...tail].join("\n\n").length + reserved;
|
|
210
|
+
}
|
|
211
|
+
const omitted = (left) => notice(left.length, left[0].n, left.at(-1).n);
|
|
212
|
+
const notice = (count, first, last) => `(${count} earlier ${count === 1 ? "entry" : "entries"} not shown: events #${first}–#${last}. They are not automatically replayed on later resumed turns. If you need one to answer, reply needs-info and name what the driver should resend.)`;
|
|
213
|
+
const NOTICE_MAX = notice(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER).length;
|
|
214
|
+
function noteEntry(e) {
|
|
215
|
+
const state = e.kind === "decision" && decisionState(e) !== "ready" ? decisionState(e) : null;
|
|
216
|
+
const tags = [...(e.ref ? [`re ${String(e.ref)}`] : []), ...(state ? [state] : [])];
|
|
217
|
+
const ref = tags.length > 0 ? ` (${tags.join(", ")})` : "";
|
|
218
|
+
return { text: `- #${e.n} ${e.kind}${ref}: ${capped(String(e.body))}`, n: e.n, seeded: [e.n] };
|
|
219
|
+
}
|
|
220
|
+
/** The brief as the navigator reads it. Its length is what BRIEF_MAX limits. */
|
|
221
|
+
export function renderBrief(brief) {
|
|
222
|
+
const field = (name, value) => {
|
|
223
|
+
if (value === undefined ||
|
|
224
|
+
value === null ||
|
|
225
|
+
value === "" ||
|
|
226
|
+
(Array.isArray(value) && value.length === 0))
|
|
227
|
+
return null;
|
|
228
|
+
const text = Array.isArray(value)
|
|
229
|
+
? value.map((v) => `- ${String(v)}`).join("\n")
|
|
230
|
+
: String(value);
|
|
231
|
+
return `${name}:\n${text}`;
|
|
232
|
+
};
|
|
233
|
+
const rendered = [
|
|
234
|
+
field("Problem", brief.problem),
|
|
235
|
+
field("Goals", brief.goals),
|
|
236
|
+
field("Constraints", brief.constraints),
|
|
237
|
+
].filter((part) => part !== null);
|
|
238
|
+
return rendered.length > 0 ? rendered.join("\n\n") : "(no brief)";
|
|
239
|
+
}
|
|
240
|
+
/** One entry's text is capped, so one long point, note or decision cannot crowd out the rest. */
|
|
241
|
+
const ITEM_TEXT_CAP = 2_000;
|
|
242
|
+
const capped = (text) => text.length > ITEM_TEXT_CAP ? `${text.slice(0, ITEM_TEXT_CAP)} …(truncated)` : text;
|
|
243
|
+
/** A point's first line, short enough to recognise. Not marked truncated: the session holds the rest. */
|
|
244
|
+
const RECALL_CAP = 200;
|
|
245
|
+
function recall(point) {
|
|
246
|
+
const line = point.split("\n", 1)[0];
|
|
247
|
+
return line.length > RECALL_CAP ? `${line.slice(0, RECALL_CAP)}…` : line;
|
|
248
|
+
}
|
|
249
|
+
function renderItem(item, text) {
|
|
250
|
+
const severity = item.severity !== undefined ? ` (${item.severity})` : "";
|
|
251
|
+
const head = text === "recalled"
|
|
252
|
+
? `- [${item.ref}] your ${item.kind === "flag" ? "point" : "opinion"}${severity}, raised earlier in this session: ${recall(item.point)}`
|
|
253
|
+
: item.kind === "flag"
|
|
254
|
+
? `- [${item.ref}] your point${severity}: ${capped(item.point)}`
|
|
255
|
+
: `- [${item.ref}] your opinion${severity} on the ask "${capped(item.question ?? "")}": ${capped(item.point)}`;
|
|
256
|
+
const deferred = item.decision && decisionState(item.decision) === "deferred" ? " (deferred)" : "";
|
|
257
|
+
return `${head}\n The driver's decision${deferred}: ${capped(String(item.decision?.body))}`;
|
|
258
|
+
}
|
|
259
|
+
/** The review section. Without `recalled`, every point is shown in full: the size a re-brief needs. */
|
|
260
|
+
function renderReview(items, recalled) {
|
|
261
|
+
if (items.length === 0)
|
|
262
|
+
return "";
|
|
263
|
+
return section("Awaiting your review", items.map((i) => renderItem(i, recalled?.(i) ? "recalled" : "full")).join("\n"));
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The items a turn reviews: in order, as many as fit `room` once rendered, and always the first,
|
|
267
|
+
* whose text the cap keeps small: a room too small for any item still offers one, so a small room
|
|
268
|
+
* slows review rather than starving it. A prompt whose mandatory part then exceeds its bound still
|
|
269
|
+
* fails the turn, explicitly.
|
|
270
|
+
*/
|
|
271
|
+
export function fitReview(items, room) {
|
|
272
|
+
const fitted = [];
|
|
273
|
+
// renderReview's length, summed per item: each item renders once, so a large backlog stays linear.
|
|
274
|
+
let size = section("Awaiting your review", "").length;
|
|
275
|
+
for (const item of items) {
|
|
276
|
+
const next = size + (fitted.length > 0 ? 1 : 0) + renderItem(item, "full").length;
|
|
277
|
+
if (fitted.length > 0 && next > room)
|
|
278
|
+
break;
|
|
279
|
+
fitted.push(item);
|
|
280
|
+
size = next;
|
|
281
|
+
}
|
|
282
|
+
return fitted;
|
|
283
|
+
}
|
|
284
|
+
const section = (title, body) => `## ${title}\n\n${body}`;
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { getNavigator } from "../adapters/index.js";
|
|
5
|
+
import { startAgent } from "../lib/agent-process.js";
|
|
6
|
+
import { failpoint, failpointActive } from "../lib/failpoint.js";
|
|
7
|
+
import { inGitRepo } from "../lib/git.js";
|
|
8
|
+
import { OPINION_SCHEMA } from "../cases/opinion.js";
|
|
9
|
+
import { startTime } from "../lib/proc.js";
|
|
10
|
+
import { SIDECAR_VERSION } from "../lib/version.js";
|
|
11
|
+
import { loadConfig } from "../config.js";
|
|
12
|
+
import { SERVER_VERSION_ENV } from "./dispatch.js";
|
|
13
|
+
import { testMs } from "./knobs.js";
|
|
14
|
+
import { buildPrompt, fitReview, NOTHING_AWAITED, NOTHING_TO_REVIEW, reviewRoom, } from "./prompt.js";
|
|
15
|
+
import { acceptReviews, awaitingReview } from "../cases/items.js";
|
|
16
|
+
import { fold } from "../cases/state.js";
|
|
17
|
+
import { defaultStoreOptions, Store } from "../cases/store.js";
|
|
18
|
+
// Executes one navigator turn and records its result. Started detached by the server, so it leads
|
|
19
|
+
// its own process group (pgid = its pid) and survives the server. See docs/design.md → Turn
|
|
20
|
+
// lifecycle — the runner.
|
|
21
|
+
//
|
|
22
|
+
// node src/turns/runner.ts <case-id> <ask-id>
|
|
23
|
+
const config = loadConfig();
|
|
24
|
+
const KILL_GRACE_MS = testMs("SIDECAR_TEST_KILL_GRACE_MS") ?? 2_000;
|
|
25
|
+
/** Each navigator sets its own hard deadline; only a test overrides it. */
|
|
26
|
+
const TEST_TURN_TIMEOUT_MS = testMs("SIDECAR_TEST_TURN_TIMEOUT_MS");
|
|
27
|
+
const [caseId, askId] = process.argv.slice(2);
|
|
28
|
+
const serverVersion = process.env[SERVER_VERSION_ENV];
|
|
29
|
+
const store = new Store(defaultStoreOptions());
|
|
30
|
+
let stopReason = null;
|
|
31
|
+
let current = null;
|
|
32
|
+
const stop = (reason) => {
|
|
33
|
+
stopReason ??= reason;
|
|
34
|
+
current?.stop();
|
|
35
|
+
};
|
|
36
|
+
// The server cancels a turn by signalling the runner. Installed before the claim: a close right
|
|
37
|
+
// after turn-started must end the turn as cancelled, not kill the runner.
|
|
38
|
+
process.on("SIGTERM", () => stop("cancelled"));
|
|
39
|
+
// A pause point for tests: the runner says it is ready, then waits for its signal, so a test
|
|
40
|
+
// cancels it before the claim without timing.
|
|
41
|
+
if (failpointActive("runner.before-claim")) {
|
|
42
|
+
process.stdout.write("ready\n");
|
|
43
|
+
// A signal listener does not keep the process alive; the interval does.
|
|
44
|
+
const alive = setInterval(() => { }, 1 << 30);
|
|
45
|
+
await once(process, "SIGTERM");
|
|
46
|
+
clearInterval(alive);
|
|
47
|
+
}
|
|
48
|
+
const claim = await store.transact(caseId, (events, append) => {
|
|
49
|
+
const state = fold(events);
|
|
50
|
+
const ask = state.asks.get(askId);
|
|
51
|
+
if (!ask || ask.terminal || ask.attempts.length > 0 || state.closed)
|
|
52
|
+
return null;
|
|
53
|
+
// Its own terminal event, without an attempt: unclaimed, the ask would end as interrupted only after
|
|
54
|
+
// the spawn bound, with no word of the cause.
|
|
55
|
+
if (serverVersion !== SIDECAR_VERSION) {
|
|
56
|
+
append({
|
|
57
|
+
author: "sidecar",
|
|
58
|
+
kind: "turn-failed",
|
|
59
|
+
attemptId: null,
|
|
60
|
+
askId,
|
|
61
|
+
outcome: "version-mismatch",
|
|
62
|
+
detail: `sidecar ${SIDECAR_VERSION} is installed, but this agent session's sidecar server runs ${serverVersion ?? "an older version"}; restart the agent session`,
|
|
63
|
+
});
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
const attemptId = randomUUID();
|
|
67
|
+
const turnTimeoutMs = TEST_TURN_TIMEOUT_MS ?? getNavigator(String(state.opened.navigator)).turnTimeoutMs;
|
|
68
|
+
const hardDeadline = Date.now() + turnTimeoutMs;
|
|
69
|
+
const git = inGitRepo(String(state.opened.workspace));
|
|
70
|
+
// Snapshotted with the claim: a review applies to the decision this turn was shown, never to a
|
|
71
|
+
// newer one recorded while the turn runs. Sized for a re-brief, so the targets fit if the resume
|
|
72
|
+
// turns into one. The room alone limits how many: a backlog is reviewed in as few turns as fit.
|
|
73
|
+
const review = fitReview(awaitingReview(state.items, config.reviewBudget), reviewRoom(state, ask, config.seedBound, git));
|
|
74
|
+
const reviewTargets = review.map((i) => ({ ref: i.ref, decisionN: i.decision.n }));
|
|
75
|
+
// A review turn whose points were all settled by an earlier turn has nothing to do: no spawn.
|
|
76
|
+
if (ask.event.review && review.length === 0) {
|
|
77
|
+
append({
|
|
78
|
+
author: "sidecar",
|
|
79
|
+
kind: "turn-failed",
|
|
80
|
+
attemptId: null,
|
|
81
|
+
askId,
|
|
82
|
+
outcome: NOTHING_TO_REVIEW,
|
|
83
|
+
detail: NOTHING_AWAITED,
|
|
84
|
+
});
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
append({
|
|
88
|
+
author: "sidecar",
|
|
89
|
+
kind: "turn-started",
|
|
90
|
+
attemptId,
|
|
91
|
+
askId,
|
|
92
|
+
runnerPid: process.pid,
|
|
93
|
+
runnerStart: startTime(process.pid),
|
|
94
|
+
sessionId: state.sessionId ?? null,
|
|
95
|
+
generation: state.generation,
|
|
96
|
+
hardDeadline,
|
|
97
|
+
watermark: state.watermark,
|
|
98
|
+
reviewTargets,
|
|
99
|
+
});
|
|
100
|
+
return { attemptId, hardDeadline, state, ask, review, reviewTargets, git };
|
|
101
|
+
});
|
|
102
|
+
if (!claim)
|
|
103
|
+
process.exit(0);
|
|
104
|
+
failpoint("runner.after-turn-started");
|
|
105
|
+
const { attemptId, hardDeadline, state, ask, review, reviewTargets, git } = claim;
|
|
106
|
+
const navigator = getNavigator(String(state.opened.navigator));
|
|
107
|
+
const opts = {
|
|
108
|
+
...(state.opened.model ? { model: String(state.opened.model) } : {}),
|
|
109
|
+
...(state.opened.effort ? { effort: String(state.opened.effort) } : {}),
|
|
110
|
+
};
|
|
111
|
+
const timer = setTimeout(() => stop("timeout"), Math.max(0, hardDeadline - Date.now()));
|
|
112
|
+
let call = null;
|
|
113
|
+
let run = {};
|
|
114
|
+
let outcome;
|
|
115
|
+
let rebrief = null;
|
|
116
|
+
let lastSeeded = [];
|
|
117
|
+
/** Every agent invocation of this turn with what it reported, a resume that a re-brief replaced included. */
|
|
118
|
+
const invocations = [];
|
|
119
|
+
if (state.sessionId === undefined) {
|
|
120
|
+
({ call, run, outcome } = await fresh(false));
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
const prompt = buildPrompt(state, ask, { fresh: false, bound: config.seedBound, review, git });
|
|
124
|
+
({ call, run, outcome } = prompt.ok
|
|
125
|
+
? await attempt(navigator.resume(state.sessionId, opts, OPINION_SCHEMA, prompt.text), false)
|
|
126
|
+
: { call: null, run: {}, outcome: overBound("resumed prompt", prompt) });
|
|
127
|
+
// Re-brief only on the adapter's explicit missing-session message.
|
|
128
|
+
if (outcome.kind === "failed" && outcome.outcome === "session-missing" && !stopReason) {
|
|
129
|
+
const oldSessionId = state.sessionId;
|
|
130
|
+
({ call, run, outcome } = await fresh(true));
|
|
131
|
+
if (call)
|
|
132
|
+
rebrief = { oldSessionId, seeded: lastSeeded };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
failpoint("runner.before-terminal");
|
|
137
|
+
const learnedSession = navigator.sessionIdFrom(run.result?.stdout ?? "") ??
|
|
138
|
+
(outcome.kind === "opinion" ? (call?.sessionId ?? null) : null);
|
|
139
|
+
await store.transact(caseId, (events, append) => {
|
|
140
|
+
const latest = fold(events);
|
|
141
|
+
let generation = latest.generation;
|
|
142
|
+
if (rebrief) {
|
|
143
|
+
generation += 1;
|
|
144
|
+
append({
|
|
145
|
+
author: "sidecar",
|
|
146
|
+
kind: "session-reset",
|
|
147
|
+
oldSessionId: rebrief.oldSessionId,
|
|
148
|
+
newSessionId: learnedSession,
|
|
149
|
+
generation,
|
|
150
|
+
cause: "session-missing",
|
|
151
|
+
seededEventIds: rebrief.seeded,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (learnedSession && (rebrief || latest.sessionId !== learnedSession)) {
|
|
155
|
+
append({ author: "sidecar", kind: "navigator-session", sessionId: learnedSession, generation });
|
|
156
|
+
}
|
|
157
|
+
const latestAsk = latest.asks.get(askId);
|
|
158
|
+
if (!latestAsk || latestAsk.terminal)
|
|
159
|
+
return;
|
|
160
|
+
if (latest.closed && outcome.kind === "opinion") {
|
|
161
|
+
append({
|
|
162
|
+
author: "sidecar",
|
|
163
|
+
kind: "turn-failed",
|
|
164
|
+
attemptId,
|
|
165
|
+
askId,
|
|
166
|
+
outcome: "cancelled",
|
|
167
|
+
detail: "case closed during the turn",
|
|
168
|
+
invocations,
|
|
169
|
+
});
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (outcome.kind === "opinion") {
|
|
173
|
+
const { flags, reviews, ...rest } = outcome.opinion;
|
|
174
|
+
append({
|
|
175
|
+
author: "navigator",
|
|
176
|
+
kind: "opinion",
|
|
177
|
+
attemptId,
|
|
178
|
+
askId,
|
|
179
|
+
...rest,
|
|
180
|
+
flags: flags.map((flag, i) => ({ id: `${askId}.${i + 1}`, ...flag })),
|
|
181
|
+
reviews: acceptReviews(reviews, reviewTargets),
|
|
182
|
+
// What the turn was shown: the review budget counts it, reviewed or not.
|
|
183
|
+
reviewTargets,
|
|
184
|
+
invocations,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
append({
|
|
189
|
+
author: "sidecar",
|
|
190
|
+
kind: "turn-failed",
|
|
191
|
+
attemptId,
|
|
192
|
+
askId,
|
|
193
|
+
outcome: outcome.outcome,
|
|
194
|
+
detail: outcome.detail ?? null,
|
|
195
|
+
hint: outcome.hint ?? null,
|
|
196
|
+
exitCode: run.result?.exitCode ?? null,
|
|
197
|
+
signal: run.result?.signal ?? null,
|
|
198
|
+
invocations,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
// Last act: take down anything this turn left in the process group, the runner included.
|
|
203
|
+
process.kill(-process.pid, "SIGKILL");
|
|
204
|
+
/**
|
|
205
|
+
* Starts a fresh session seeded from the case. A prompt whose mandatory part exceeds its bound fails
|
|
206
|
+
* the ask without spawning: the navigator would start without its brief or the question.
|
|
207
|
+
*/
|
|
208
|
+
async function fresh(isRebrief) {
|
|
209
|
+
const prompt = buildPrompt(state, ask, {
|
|
210
|
+
fresh: true,
|
|
211
|
+
rebrief: isRebrief,
|
|
212
|
+
bound: config.seedBound,
|
|
213
|
+
review,
|
|
214
|
+
git,
|
|
215
|
+
});
|
|
216
|
+
if (!prompt.ok)
|
|
217
|
+
return {
|
|
218
|
+
call: null,
|
|
219
|
+
run: {},
|
|
220
|
+
outcome: overBound(isRebrief ? "re-brief seed" : "seed", prompt),
|
|
221
|
+
};
|
|
222
|
+
lastSeeded = prompt.seeded;
|
|
223
|
+
return attempt(navigator.start(opts, OPINION_SCHEMA, prompt.text), true);
|
|
224
|
+
}
|
|
225
|
+
async function attempt(call, isFresh) {
|
|
226
|
+
// Stopped before the agent exists, e.g. while the claim waited for the store lock: never spawn it.
|
|
227
|
+
if (stopReason)
|
|
228
|
+
return { call, run: {}, outcome: { kind: "failed", outcome: stopReason } };
|
|
229
|
+
current = startAgent(call.invocation, String(state.opened.workspace), KILL_GRACE_MS);
|
|
230
|
+
failpoint("runner.after-spawn");
|
|
231
|
+
const run = await current.done;
|
|
232
|
+
const stdout = run.result?.stdout ?? "";
|
|
233
|
+
const { usage, scope, toolCalls, models } = run.result
|
|
234
|
+
? navigator.measure(stdout)
|
|
235
|
+
: { usage: null, scope: "turn", toolCalls: null, models: null };
|
|
236
|
+
invocations.push({
|
|
237
|
+
sessionId: navigator.sessionIdFrom(stdout) ?? call.sessionId,
|
|
238
|
+
fresh: isFresh,
|
|
239
|
+
promptChars: call.invocation.input?.length ?? 0,
|
|
240
|
+
usage,
|
|
241
|
+
scope,
|
|
242
|
+
toolCalls,
|
|
243
|
+
models,
|
|
244
|
+
});
|
|
245
|
+
return { call, run, outcome: classify(call, run) };
|
|
246
|
+
}
|
|
247
|
+
function overBound(what, prompt) {
|
|
248
|
+
return {
|
|
249
|
+
kind: "failed",
|
|
250
|
+
outcome: "failed",
|
|
251
|
+
detail: `the ${what}'s mandatory part takes ${prompt.size} characters, over the bound of ${prompt.bound}`,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
function classify(call, run) {
|
|
255
|
+
if (stopReason)
|
|
256
|
+
return { kind: "failed", outcome: stopReason };
|
|
257
|
+
if (run.spawnError) {
|
|
258
|
+
// A missing cwd also fails the spawn with ENOENT, and names the executable as its path.
|
|
259
|
+
const workspace = String(state.opened.workspace);
|
|
260
|
+
if (run.spawnError.code === "ENOENT" && !existsSync(workspace)) {
|
|
261
|
+
return {
|
|
262
|
+
kind: "failed",
|
|
263
|
+
outcome: "failed",
|
|
264
|
+
detail: `the workspace ${workspace} does not exist`,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
return run.spawnError.code === "ENOENT" && run.spawnError.path === call.invocation.command
|
|
268
|
+
? { kind: "failed", outcome: "not-installed", detail: `${call.invocation.command} not found` }
|
|
269
|
+
: { kind: "failed", outcome: "failed", detail: run.spawnError.message };
|
|
270
|
+
}
|
|
271
|
+
if (run.result.signal)
|
|
272
|
+
return { kind: "failed", outcome: "killed", detail: `agent ended by ${run.result.signal}` };
|
|
273
|
+
const outcome = navigator.classify(run.result);
|
|
274
|
+
// An agent that failed on its own may have stopped reading early; its own failure says more.
|
|
275
|
+
if (run.inputError && outcome.kind !== "failed") {
|
|
276
|
+
return {
|
|
277
|
+
kind: "failed",
|
|
278
|
+
outcome: "failed",
|
|
279
|
+
detail: `the prompt could not be written to the agent: ${run.inputError.message}`,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
return outcome;
|
|
283
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lysyi3m/sidecar",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.6.1",
|
|
4
|
+
"description": "Lets one coding agent consult another mid-task: a driver asks, a read-only navigator answers",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/lysyi3m/sidecar.git"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"sidecar": "dist/bin/sidecar.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"sidecar": "node bin/sidecar.ts",
|
|
22
|
+
"prepack": "rm -rf dist && tsc -p tsconfig.build.json && cp -R src/dashboard/static dist/src/dashboard/",
|
|
23
|
+
"test": "node --test \"test/**/*.test.ts\"",
|
|
24
|
+
"typecheck": "tsc --noEmit",
|
|
25
|
+
"lint": "oxlint --deny-warnings",
|
|
26
|
+
"format": "oxfmt",
|
|
27
|
+
"format:check": "oxfmt --check"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@clack/prompts": "1.8.1",
|
|
31
|
+
"@hono/node-server": "2.1.5",
|
|
32
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
33
|
+
"fast-string-truncated-width": "3.0.3",
|
|
34
|
+
"hono": "4.13.13",
|
|
35
|
+
"zod": "4.6.7"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/node": "^26.6.5",
|
|
39
|
+
"oxfmt": "^0.73.0",
|
|
40
|
+
"oxlint": "^1.88.0",
|
|
41
|
+
"typescript": "^7.0.2"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=24.14.0"
|
|
45
|
+
}
|
|
46
|
+
}
|