Skip to content

Commit a00ac46

Browse files
committed
feat(car): surface failures, honour tool idempotency, add recall and preflight
Covers the correctness and observability gaps found in the CAR integration audit. Stop degrading silently (anomalyco#8). Every CAR call falls back rather than failing the turn, which is right — CAR is an augmentation — but the fallbacks were silent: addFact and ingestSkill were piped through Effect.ignore, and buildContext, findSkill, listSkills and factCount swallowed errors into empty values. That is exactly how the memory-sandbox breakage went unnoticed for a whole session, with persistMemory failing on every teardown and nothing saying so. All degradations now log and are counted in a per-instance health tally reported by `opencode debug car`. ingestSkill also no longer marks a skill as ingested when the call failed, which would have masked it permanently for that instance. Honour tool idempotency (anomalyco#9). The proposal hardcoded idempotent:false even though registerToolSchema already carried the tool's real hint, so CAR could never dedupe an idempotent tool. max_retries stays 0 deliberately: a CAR-side retry re-invokes our dispatcher and re-runs the tool for real, so raising it needs CAR's retry semantics verified first (car-releases#76). Weight facts by how they were obtained (anomalyco#9). addFact now passes CAR's confidence argument, which was never supplied. Things observed directly — the user's own words, a tool's actual result or failure — are ground truth; model-generated prose is an assertion and should not outweigh them. Add real recall (anomalyco#10). Memory was write-only: addFact fired constantly but queryFacts was never called and the only read path was buildContext's opaque blob. The service now exposes graph-spreading-activation recall, available as `opencode debug car --recall <text>`. Harden the runner (anomalyco#11). Registration retries with exponential backoff, a dropped socket clears the memoized connection so the next call re-registers rather than hanging on a dead runner, in-flight calls are failed instead of being left to hang, and the host's abort signal now cancels the delegated call — which matters most during the ~5s pre-dispatch window (car-releases#75). Add daemon preflight (anomalyco#12). `opencode debug car` reports reachability, client vs daemon version skew, and whether the running daemon actually knows the delegated model — the three things that otherwise only surface as a confusing mid-inference failure. Note models.list omits delegated models entirely; only models.list_unified reports them, so the obvious check reports a false negative. Full suite with CAR off: 3232 pass, 0 fail — identical to pristine upstream/dev.
1 parent 88ebc3f commit a00ac46

6 files changed

Lines changed: 334 additions & 80 deletions

File tree

‎packages/opencode/src/car/daemon.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as path from "node:path"
1010
import * as fs from "node:fs"
1111
import { spawn } from "node:child_process"
1212
import { createRequire } from "node:module"
13+
import WebSocket from "ws"
1314
import { Effect } from "effect"
1415

1516
// Daemon discovery runs as plain promises outside any Effect runtime, so log
@@ -130,6 +131,119 @@ function ensureDelegatedModelOnDisk(): void {
130131
}
131132
}
132133

134+
// The daemon mints a per-launch token at startup and writes it 0600 to a
135+
// well-known per-user path. `--no-auth` daemons have no file; auth is then
136+
// skipped and the handshake is a no-op.
137+
export function readAuthToken(): string | undefined {
138+
const fromEnv = process.env["CAR_AUTH_TOKEN"]
139+
if (fromEnv) return fromEnv
140+
const file =
141+
process.platform === "darwin"
142+
? path.join(os.homedir(), "Library", "Application Support", "ai.parslee.car", "auth-token")
143+
: process.platform === "win32"
144+
? path.join(process.env["LOCALAPPDATA"] ?? "", "ai.parslee.car", "auth-token")
145+
: path.join(process.env["XDG_RUNTIME_DIR"] ?? path.join(os.homedir(), ".cache"), "ai.parslee.car", "auth-token")
146+
try {
147+
return fs.readFileSync(file, "utf8").trim() || undefined
148+
} catch {
149+
return undefined
150+
}
151+
}
152+
153+
function bundledClientVersion(): string | undefined {
154+
try {
155+
const require = createRequire(import.meta.url)
156+
return (JSON.parse(fs.readFileSync(require.resolve("car-runtime/package.json"), "utf8")) as { version?: string })
157+
.version
158+
} catch {
159+
return undefined
160+
}
161+
}
162+
163+
function runningDaemonVersion(): string | undefined {
164+
try {
165+
const file = path.join(os.homedir(), ".car", "version.json")
166+
return (JSON.parse(fs.readFileSync(file, "utf8")) as { car_version?: string }).car_version
167+
} catch {
168+
return undefined
169+
}
170+
}
171+
172+
export interface DaemonStatus {
173+
readonly reachable: boolean
174+
readonly daemonVersion?: string
175+
readonly clientVersion?: string
176+
/** Client and daemon disagree; the wire contract between them is not guaranteed. */
177+
readonly versionSkew: boolean
178+
/** Whether the running daemon actually knows the delegated model. It only
179+
* loads models at boot (car-releases#39 phase 1), so writing models.json is
180+
* not enough — a daemon started earlier will not have it. */
181+
readonly delegatedModelRegistered?: boolean
182+
}
183+
184+
// Read-only preflight. Answers the three questions that otherwise only surface
185+
// as a confusing mid-inference failure: is anything listening, do the client and
186+
// daemon agree on version, and does the daemon know the delegated model.
187+
export function daemonStatus(): Promise<DaemonStatus> {
188+
return (async () => {
189+
const url = process.env["CAR_DAEMON_URL"] ?? DEFAULT_DAEMON_URL
190+
const { host, port } = parseDaemonUrl(url)
191+
const clientVersion = bundledClientVersion()
192+
const daemonVersion = runningDaemonVersion()
193+
const versionSkew = Boolean(clientVersion && daemonVersion && clientVersion !== daemonVersion)
194+
195+
if (!(await probe(host, port))) return { reachable: false, clientVersion, daemonVersion, versionSkew }
196+
197+
const registered = await hasDelegatedModel(url).catch(() => undefined)
198+
return { reachable: true, clientVersion, daemonVersion, versionSkew, delegatedModelRegistered: registered }
199+
})()
200+
}
201+
202+
function hasDelegatedModel(url: string): Promise<boolean> {
203+
return new Promise((resolve, reject) => {
204+
const socket = new WebSocket(url)
205+
const settle = (fn: () => void) => {
206+
clearTimeout(timer)
207+
socket.close()
208+
fn()
209+
}
210+
const timer = setTimeout(
211+
() => settle(() => reject(new Error("car: models.list_unified timed out"))),
212+
PROBE_TIMEOUT_MS * 25,
213+
)
214+
socket.once("error", (e: Error) => settle(() => reject(e)))
215+
216+
const token = readAuthToken()
217+
// The query must not be sent until `session.auth` has been answered — the
218+
// daemon rejects any other method on an unauthenticated connection, and an
219+
// error reply carries no result, which reads as "model absent".
220+
const AUTH_ID = 1
221+
const QUERY_ID = 2
222+
const query = () =>
223+
socket.send(JSON.stringify({ jsonrpc: "2.0", id: QUERY_ID, method: "models.list_unified", params: {} }))
224+
225+
socket.once("open", () => {
226+
if (token) socket.send(JSON.stringify({ jsonrpc: "2.0", id: AUTH_ID, method: "session.auth", params: { token } }))
227+
else query()
228+
})
229+
230+
socket.on("message", (raw: WebSocket.RawData) => {
231+
const msg = JSON.parse(raw.toString()) as { id?: number; result?: unknown; error?: { message?: string } }
232+
if (msg.id === AUTH_ID) {
233+
if (msg.error) return settle(() => reject(new Error(msg.error?.message ?? "car: session.auth failed")))
234+
return query()
235+
}
236+
if (msg.id !== QUERY_ID) return
237+
if (msg.error) return settle(() => reject(new Error(msg.error?.message ?? "car: models.list_unified failed")))
238+
// models.list omits delegated models entirely; only the unified view
239+
// reports them, so the plain list would always say "not registered".
240+
settle(() => resolve(JSON.stringify(msg.result ?? "").includes(DELEGATED_MODEL_ID)))
241+
})
242+
})
243+
}
244+
245+
export const probeDaemon = () => Effect.promise(() => daemonStatus())
246+
133247
export function ensureCarServer(): Promise<void> {
134248
if (ensured) return ensured
135249
ensured = (async () => {

0 commit comments

Comments
 (0)