@lysyi3m/sidecar 0.0.0-stage → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +285 -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,31 @@
1
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
+ import { createMcpServer } from "./tools.js";
3
+ // The MCP transport: the SDK's stdio transport, newline-delimited JSON-RPC on stdin/stdout. stdout
4
+ // carries only protocol messages, so nothing else may print to it. The driver session ends with
5
+ // stdin EOF, or with SIGINT (Claude Code) or SIGTERM (codex) and stdin left open; the SDK transport
6
+ // watches for none of them, so this does.
7
+ export async function serveStdio(server) {
8
+ const mcp = createMcpServer(server);
9
+ mcp.server.oninitialized = () => {
10
+ if (mcp.server.getClientCapabilities()?.elicitation) {
11
+ server.elicit = async (message, requestedSchema, timeoutMs) => (await mcp.server.elicitInput({
12
+ mode: "form",
13
+ message,
14
+ requestedSchema: requestedSchema,
15
+ }, { timeout: timeoutMs }));
16
+ }
17
+ };
18
+ let ending = false;
19
+ const shutdown = async () => {
20
+ if (ending)
21
+ return;
22
+ ending = true;
23
+ await server.disconnect();
24
+ await mcp.close();
25
+ process.exit(0);
26
+ };
27
+ process.stdin.once("end", shutdown);
28
+ process.once("SIGINT", shutdown);
29
+ process.once("SIGTERM", shutdown);
30
+ await mcp.connect(new StdioServerTransport());
31
+ }
@@ -0,0 +1,180 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { DECISION_STATES } from "../cases/items.js";
4
+ import { CASE_STATUSES } from "../cases/state.js";
5
+ import { SIDECAR_VERSION } from "../lib/version.js";
6
+ import { ASK_MAX, RECORD_MAX } from "../turns/prompt.js";
7
+ // What drivers see: the protocol instructions and the tools, wired to SidecarServer. The SDK
8
+ // validates every call against these schemas before a handler runs.
9
+ /**
10
+ * Claude Code drops server instructions past 4,096 characters (code.claude.com/docs/en/mcp.md), so
11
+ * these hold only the protocol that spans tools, most consequential first; each tool's own rules
12
+ * live in its description. INSTRUCTIONS_MAX leaves room below the cap, and a test enforces it,
13
+ * with the client limits on tool descriptions and schemas (docs/design.md → Driver interface).
14
+ */
15
+ export const INSTRUCTIONS_MAX = 3_500;
16
+ const INSTRUCTIONS = `sidecar connects you, the driver, to a navigator: a second, read-only coding agent that checks your work and gives an independent opinion. A case holds one problem: your brief, your asks, the navigator's opinions and your decisions. The navigator keeps its memory for the whole case; the user follows the case live on the dashboard.
17
+
18
+ When to use it
19
+ - sidecar is the user's chosen way to get a second opinion. When you need one, or the user asks for one, use sidecar, not one-off delegation tools.
20
+ - Open the case when you start a task you expect to consult on. Ask as each conclusion forms, while the navigator can still change your course: before you commit to an approach, when the same error comes back, and before you call non-trivial work done. Skip trivial steps: every ask uses the user's quota.
21
+
22
+ The loop
23
+ 1. sidecar_open with a brief that stands alone. Share the dashboard link with the user once.
24
+ 2. sidecar_ask one question at a time. Do not act on it until the outcome arrives.
25
+ 3. Decide every point the result's next names, with sidecar_record kind=decision: what you accept, reject or defer, and why. Never drop a point silently. Before you accept a point that matters, read the cited lines yourself.
26
+ 4. The navigator reviews your decisions with your next ask, or with sidecar_review when no ask is coming. A point is settled only when the navigator confirms your decision. On reopened, decide again or leave the point for the user.
27
+ 5. Close the case with sidecar_close when the work is done; before that, call sidecar_review if decisions still await the navigator. When the same work continues later, a review round on the same PR included, sidecar_attach the case again, closed or not; a new problem gets a new case.
28
+
29
+ Tell the user
30
+ - On failed: "navigator unavailable: <outcome>, proceeding". Then continue without the opinion, and record your own conclusion as a note with ref=<ask id>.
31
+ - On held: the navigator stands by a point you rejected. Tell the user at once, with both positions, so they can intervene; do not argue it further.
32
+ - The points left for the user, the confirmed deferrals (they stay listed, not settled), and the points sidecar_close lists as unsettled.
33
+ - In your report, where the navigator disagreed with you and what you did about it. Report the case state accurately, for example "design agreed; implementation pending": do not say the navigator agrees while its points are open, planned or reopened.`;
34
+ const text = z.string().trim().min(1, "must be a non-empty string");
35
+ const upTo = (max) => text.max(max, `must be at most ${max} characters`);
36
+ const caseId = text
37
+ .optional()
38
+ .describe("The case to act on. Defaults to the only case you are attached to. Pass it when you are attached to several, and when you retry a call.");
39
+ /** A tool's result, as the JSON the driver reads. */
40
+ const reply = async (result) => ({
41
+ content: [{ type: "text", text: JSON.stringify(await result, null, 2) }],
42
+ });
43
+ /** Drops undefined values, which exactOptionalPropertyTypes forbids in optional fields. */
44
+ function defined(record) {
45
+ return Object.fromEntries(Object.entries(record).filter(([, v]) => v !== undefined));
46
+ }
47
+ /** The MCP server for one client connection: one session, or every chat of a client that shares it. The transport is connected by the caller. */
48
+ export function createMcpServer(server) {
49
+ const mcp = new McpServer({ name: "sidecar", version: SIDECAR_VERSION }, { instructions: INSTRUCTIONS });
50
+ /**
51
+ * The results that start work carry the instructions too: some clients never show them to the
52
+ * model (the Claude desktop app), and repeating them costs the others little.
53
+ */
54
+ const withProtocol = async (result) => ({
55
+ ...(await result),
56
+ protocol: INSTRUCTIONS,
57
+ });
58
+ mcp.registerTool("sidecar_navigators", {
59
+ description: "List the navigators available to open a case with: the supported agent CLIs that are installed. The choice is the user's: the suggestion is what to offer them, not a pick for you.",
60
+ }, () => reply(server.navigators()));
61
+ mcp.registerTool("sidecar_open", {
62
+ description: "Start a second-opinion case: open a case with a navigator and attach to it. Open it when you start the task, not after the work is done. Starts no turn. The brief (problem, goals, constraints) is the navigator's only briefing: write it for a reader who knows nothing else, with the evidence for each constraint and decision, and paths relative to the workspace. Check the workspace in the result, and share the dashboard link with the user once. If an open's result was lost, call sidecar_status before you open again.",
63
+ inputSchema: {
64
+ navigator: text
65
+ .optional()
66
+ .describe("Adapter id from sidecar_navigators, e.g. claude-code or codex. Pass it when the user named a navigator, or after sidecar_open told you to ask them; otherwise leave it out, and the user is asked, with another agent than you preselected. Never choose one yourself."),
67
+ title: text.describe("Short case title."),
68
+ problem: text.describe("The task and the problem, self-contained."),
69
+ goals: z.array(z.string()).optional().describe("What this case must settle."),
70
+ constraints: z
71
+ .array(z.string())
72
+ .optional()
73
+ .describe("Decisions already made and constraints found, each with its evidence."),
74
+ model: text
75
+ .optional()
76
+ .describe("Navigator model, overriding the user's configured default. Pass it only when the user asked. Fixed for the case."),
77
+ effort: text
78
+ .optional()
79
+ .describe("Navigator effort, overriding the user's configured default. Pass it only when the user asked: a higher effort makes every turn slower and uses more quota; ask a narrower question instead. Fixed for the case."),
80
+ workspace: text
81
+ .optional()
82
+ .describe("The directory the case is about, when it is not your own working directory: a repository's root, or the common parent of the repositories its evidence spans. The navigator works there; relative paths in the brief and asks are relative to it. Defaults to this session's working directory. In a chat app, which shares one sidecar server among its chats, pass it as an absolute path, for example a folder connected to the chat; without it, the navigator starts in an empty scratch directory, with no project to read."),
83
+ driver_model: text
84
+ .optional()
85
+ .describe("Pass your own model id, e.g. claude-opus-5-5, whenever your instructions or settings state it. Shown to the user beside the case; sidecar detects it for some clients only. Never guess one."),
86
+ driver_effort: text
87
+ .optional()
88
+ .describe("Pass your own reasoning effort, e.g. high, whenever your instructions or settings state it. Shown beside your model. Never guess one."),
89
+ },
90
+ }, ({ driver_model, driver_effort, ...args }, extra) => reply(withProtocol(server.open(defined({
91
+ ...args,
92
+ driverModel: driver_model,
93
+ driverEffort: driver_effort,
94
+ clientMeta: extra._meta,
95
+ })))));
96
+ mcp.registerTool("sidecar_ask", {
97
+ description: `Get a second opinion: ask the navigator one question, as the conclusion forms, and wait for its opinion within the ask budget (${Math.round(server.askBudgetMs / 1000)} s). Do not act on the question until it resolves. Returns opinion; pending (call sidecar_wait, or do other work first and come back); busy; or failed (tell the user "navigator unavailable: <outcome>, proceeding", continue without the opinion, and record your own conclusion as a note with ref=<ask id>; you may ask again later with a new key). If the call times out in your client, retrying with the same case_id, key and body never starts a second turn; if it reports that this server is no longer attached to the case, sidecar_wait or sidecar_read with case_id still recover the answer.`,
98
+ inputSchema: {
99
+ body: upTo(ASK_MAX).describe("One question. Lead with your claim or question, then your evidence as path:line, and ask the navigator to challenge it. Ask for a check, not for code. Self-contained."),
100
+ key: text.describe("Idempotency key. Use a new key for each new question; reuse a key only to retry the same ask."),
101
+ case_id: caseId,
102
+ },
103
+ }, (args) => reply(server.ask(defined(args))));
104
+ mcp.registerTool("sidecar_review", {
105
+ description: "Ask the navigator to review your decisions on its points, with no new question. Use it when decisions await review and no further ask is coming, especially before sidecar_close. Returns nothing-to-review without starting a turn when none await. Results are as for sidecar_ask.",
106
+ inputSchema: {
107
+ key: text.describe("Idempotency key. Reusing it returns the same review; use a new key to review again."),
108
+ case_id: caseId,
109
+ },
110
+ }, (args) => reply(server.review(defined(args))));
111
+ mcp.registerTool("sidecar_wait", {
112
+ description: "Keep waiting for a pending ask's outcome, within the ask budget.",
113
+ inputSchema: {
114
+ ask_id: text.describe("The ask_id of the pending result."),
115
+ case_id: caseId,
116
+ },
117
+ }, (args) => reply(server.wait(defined(args))));
118
+ mcp.registerTool("sidecar_record", {
119
+ description: "Record a decision or a note in the case. Starts no turn. The navigator sees it with the next ask. A decision needs ref: a point the result's next names, or an answered ask. Each point an opinion raises has its own flag id, <ask id>.<n> (e.g. a1b2c3d4.1), and gets its own decision; an opinion that raises none is decided as one point, with ref=<ask id>. A review result needs decisions only on the points it reopens and on its new points. The opinion's limits are not points: weigh them when you rely on the opinion. A decision does not settle a point by itself: the navigator reviews a ready or deferred decision and confirms, reopens, or holds the point. Each point gets a limited number of reviews; past that, it is left for the user. A note may ref any point or ask.",
120
+ inputSchema: {
121
+ kind: z.enum(["decision", "note"]),
122
+ body: upTo(RECORD_MAX).describe("For a decision: what you accept or reject, and why. When you disagree with the navigator, say so and give your reason."),
123
+ ref: z
124
+ .union([text, z.array(text).min(1)])
125
+ .optional()
126
+ .describe("A point's flag id or an ask id. Pass several ids when one decision settles them the same way; each is recorded and reviewed on its own. Decide points separately when your answers differ."),
127
+ state: z
128
+ .enum(DECISION_STATES)
129
+ .optional()
130
+ .describe("Decisions only. ready (default): the resolution exists — the change is in the workspace, or you reject or explain the point. planned: you accept it, but the change is not made yet; the navigator does not review it until you record a ready decision on the same ref. deferred: the point moves out of this case, for later work or for the user; say why."),
131
+ case_id: caseId,
132
+ },
133
+ }, (args) => reply(server.record(defined(args))));
134
+ mcp.registerTool("sidecar_read", {
135
+ description: "Read case events after since_n, paginated. Use it to rebuild context after sidecar_attach.",
136
+ inputSchema: {
137
+ case_id: caseId,
138
+ since_n: z
139
+ .number()
140
+ .int()
141
+ .optional()
142
+ .describe("Return the events after this n. Pass the last result's next_since_n."),
143
+ limit: z.number().int().optional().describe("At most 500; default 100."),
144
+ },
145
+ }, (args) => reply(server.read(defined(args))));
146
+ mcp.registerTool("sidecar_status", {
147
+ description: "Show the attached case: its state, the in-flight ask, and the navigator's points not yet settled. Attached to several cases, it lists them; pass case_id for one in detail. Call it to find your case when an open or attach result was lost.",
148
+ inputSchema: {
149
+ case_id: text.optional().describe("The case to show. Any case, attached or not."),
150
+ },
151
+ }, (args) => reply(withProtocol(server.status(defined(args)))));
152
+ mcp.registerTool("sidecar_list", {
153
+ description: "List cases, newest first.",
154
+ inputSchema: {
155
+ state: z.enum(CASE_STATUSES).optional().describe("Only the cases in this state."),
156
+ workspace: text
157
+ .optional()
158
+ .describe("Only the cases in this workspace: an absolute path, as sidecar_open returned it."),
159
+ },
160
+ }, (args) => reply(server.list(defined(args))));
161
+ mcp.registerTool("sidecar_attach", {
162
+ description: "Attach to an existing case, open or closed; attaching a closed case reopens it with the same navigator session, for the same work only. Fails if another live driver session is attached to it, including a server a client shares among its chats; find the case with sidecar_status and detach or close it from that session first.",
163
+ inputSchema: {
164
+ case_id: text,
165
+ reason: text.optional().describe("Why a closed case reopens, for the record."),
166
+ },
167
+ }, (args) => reply(withProtocol(server.attach(defined(args)))));
168
+ mcp.registerTool("sidecar_detach", {
169
+ description: "Release the attached case without closing it, so another session can attach it. A running turn continues and its result is recorded.",
170
+ inputSchema: { case_id: caseId },
171
+ }, (args) => reply(server.detach(defined(args))));
172
+ mcp.registerTool("sidecar_close", {
173
+ description: "Close the attached case when the work is done. Cancels a running turn. A closed case reopens with sidecar_attach. Call sidecar_review first if decisions still await the navigator. The result lists the points left unsettled: report them to the user.",
174
+ inputSchema: {
175
+ reason: text.optional().describe("Why the case closes, for the record."),
176
+ case_id: caseId,
177
+ },
178
+ }, (args) => reply(server.close(defined(args))));
179
+ return mcp;
180
+ }
@@ -0,0 +1,188 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { modulePath } from "../lib/paths.js";
4
+ import { SIDECAR_VERSION } from "../lib/version.js";
5
+ import { groupExists, killGroup, processAlive, startTime } from "../lib/proc.js";
6
+ import { fold } from "../cases/state.js";
7
+ import { testMs } from "./knobs.js";
8
+ const RUNNER = modulePath("./runner", import.meta.url);
9
+ /**
10
+ * The version of the server that starts a runner. An upgrade replaces the runner on disk while a
11
+ * running server keeps its old code; the runner refuses a turn for a server of another version.
12
+ */
13
+ export const SERVER_VERSION_ENV = "SIDECAR_SERVER_VERSION";
14
+ const POLL_MS = 150;
15
+ /** An ask with no turn-started after this long has lost its runner before it began. */
16
+ const spawnBoundMs = () => testMs("SIDECAR_TEST_SPAWN_BOUND_MS") ?? 10_000;
17
+ /** A live runner this far past its hard deadline is stuck (e.g. stopped); its group is killed. */
18
+ const OVERDUE_MS = 30_000;
19
+ export class IdempotencyConflictError extends Error {
20
+ constructor(key) {
21
+ super(`idempotency key ${key} was already used for a different ask; use a new key to retry`);
22
+ this.name = "IdempotencyConflictError";
23
+ }
24
+ }
25
+ class CaseClosedError extends Error {
26
+ constructor(caseId) {
27
+ super(`case ${caseId} is closed`);
28
+ this.name = "CaseClosedError";
29
+ }
30
+ }
31
+ /**
32
+ * Appends an ask and starts its runner. A repeated key with the same body returns the existing ask
33
+ * instead of appending; deduplication is checked before `busy`.
34
+ */
35
+ export async function dispatchAsk(store, caseId, input, runnerEnv = {},
36
+ /** Runs inside the transaction before anything else; throws to refuse (e.g. not the owner). */
37
+ guard = () => { }) {
38
+ const bodyHash = createHash("sha256").update(input.body).digest("hex");
39
+ const result = await store.transact(caseId, (events, append) => {
40
+ const state = fold(events);
41
+ guard(state);
42
+ if (state.closed)
43
+ throw new CaseClosedError(caseId);
44
+ for (const ask of state.asks.values()) {
45
+ if (ask.key !== input.key)
46
+ continue;
47
+ if (ask.bodyHash !== bodyHash)
48
+ throw new IdempotencyConflictError(input.key);
49
+ return { status: "existing", askId: ask.askId };
50
+ }
51
+ if (state.inFlight)
52
+ return { status: "busy", askId: state.inFlight.askId };
53
+ let askId;
54
+ do
55
+ askId = randomUUID().slice(0, 8);
56
+ while (state.asks.has(askId));
57
+ append({
58
+ author: "driver",
59
+ kind: "ask",
60
+ askId,
61
+ key: input.key,
62
+ bodyHash,
63
+ body: input.body,
64
+ ...(input.review ? { review: true } : {}),
65
+ });
66
+ return { status: "dispatched", askId };
67
+ });
68
+ if (result.status === "dispatched")
69
+ startRunner(store, caseId, result.askId, runnerEnv);
70
+ return result;
71
+ }
72
+ function startRunner(store, caseId, askId, runnerEnv) {
73
+ const runner = spawn(process.execPath, [RUNNER, caseId, askId], {
74
+ // detached: the runner leads a new process group and outlives this server.
75
+ detached: true,
76
+ stdio: "ignore",
77
+ env: {
78
+ ...process.env,
79
+ SIDECAR_HOME: store.options.home,
80
+ SIDECAR_LOCK_PORT: String(store.options.lockPort),
81
+ [SERVER_VERSION_ENV]: SIDECAR_VERSION,
82
+ ...runnerEnv,
83
+ },
84
+ });
85
+ // A failed spawn leaves the ask without an attempt; reconcile settles it after the spawn bound.
86
+ runner.on("error", () => { });
87
+ runner.unref();
88
+ }
89
+ /** Waits for the ask's terminal event until the absolute deadline. Reconciles on every poll. */
90
+ export async function waitForOutcome(store, caseId, askId, deadline) {
91
+ for (;;) {
92
+ const state = await reconcile(store, caseId);
93
+ const terminal = state.asks.get(askId)?.terminal;
94
+ if (terminal)
95
+ return { status: terminal.kind === "opinion" ? "opinion" : "failed", event: terminal };
96
+ const remaining = deadline - Date.now();
97
+ if (remaining <= 0)
98
+ return { status: "pending", askId };
99
+ await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_MS, remaining)));
100
+ }
101
+ }
102
+ /**
103
+ * Settles an in-flight ask whose runner is gone. The ask's terminal event is recorded only once no
104
+ * process of its turn can still use the navigator session.
105
+ */
106
+ export function reconcile(store, caseId) {
107
+ return store.transact(caseId, (events, append) => {
108
+ const state = fold(events);
109
+ const ask = state.inFlight;
110
+ if (!ask)
111
+ return state;
112
+ const attempt = ask.attempts.at(-1);
113
+ if (!attempt) {
114
+ // A closed case never starts the turn: its runner declines to claim the ask.
115
+ if (state.closed) {
116
+ ask.terminal = append({
117
+ author: "sidecar",
118
+ kind: "turn-failed",
119
+ attemptId: null,
120
+ askId: ask.askId,
121
+ outcome: "cancelled",
122
+ detail: "case closed before the turn started",
123
+ });
124
+ return state;
125
+ }
126
+ if (Date.now() - Date.parse(ask.event.ts) < spawnBoundMs())
127
+ return state;
128
+ ask.terminal = append({
129
+ author: "sidecar",
130
+ kind: "turn-failed",
131
+ attemptId: null,
132
+ askId: ask.askId,
133
+ outcome: "interrupted",
134
+ detail: "the runner never started the turn",
135
+ });
136
+ return state;
137
+ }
138
+ if (processAlive(attempt.runnerPid, attempt.runnerStart)) {
139
+ if (Date.now() > attempt.hardDeadline + OVERDUE_MS)
140
+ killGroup(attempt.runnerPid);
141
+ return state;
142
+ }
143
+ // The runner's pid is its process group id; the group outlives the runner while the agent runs.
144
+ // POSIX never reuses a pid while its group exists: another live process at that pid means our
145
+ // group is gone, and the group with that id belongs to someone else.
146
+ if (startTime(attempt.runnerPid) === null && groupExists(attempt.runnerPid)) {
147
+ killGroup(attempt.runnerPid);
148
+ return state;
149
+ }
150
+ // Closing signals the runner; a runner that died of it still ends its turn as cancelled.
151
+ const outcome = state.closed
152
+ ? "cancelled"
153
+ : Date.now() > attempt.hardDeadline
154
+ ? "timeout"
155
+ : "interrupted";
156
+ ask.terminal = append({
157
+ author: "sidecar",
158
+ kind: "turn-failed",
159
+ attemptId: attempt.attemptId,
160
+ askId: ask.askId,
161
+ outcome,
162
+ detail: "the runner died before recording a result",
163
+ });
164
+ return state;
165
+ });
166
+ }
167
+ /**
168
+ * Cancels the turn of `askId` while it is the one in flight: signals its runner, or reconciles if
169
+ * the runner is gone. Another ask, started after a reopen, is left alone.
170
+ */
171
+ export async function cancelTurn(store, caseId, askId) {
172
+ const state = fold(await store.read(caseId));
173
+ if (askId === undefined || state.inFlight?.askId !== askId)
174
+ return;
175
+ const attempt = state.inFlight.attempts.at(-1);
176
+ if (attempt && processAlive(attempt.runnerPid, attempt.runnerStart)) {
177
+ try {
178
+ process.kill(attempt.runnerPid, "SIGTERM");
179
+ return;
180
+ }
181
+ catch (err) {
182
+ // The runner exited after the check; reconcile settles the ask.
183
+ if (err.code !== "ESRCH")
184
+ throw err;
185
+ }
186
+ }
187
+ await reconcile(store, caseId);
188
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A test-only duration from the environment, in ms, so a test reaches a bound without waiting out
3
+ * the real one. Unset, the real bound applies. A value that is no whole number of ms in range
4
+ * throws, so a typo never turns a bound into NaN.
5
+ */
6
+ export function testMs(name) {
7
+ const raw = process.env[name];
8
+ if (raw === undefined)
9
+ return undefined;
10
+ const ms = Number(raw);
11
+ if (!Number.isInteger(ms) || ms <= 0 || ms > 24 * 60 * 60_000)
12
+ throw new Error(`${name} must be 1 to 86400000 ms, not ${raw}`);
13
+ return ms;
14
+ }