@taco-ai/cli 0.1.2 → 0.2.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.
@@ -4,19 +4,32 @@
4
4
  * schtasks invocation) lives in `install.ts` / `uninstall.ts` so each file
5
5
  * stays under the 1000-line cap.
6
6
  *
7
- * The platform pkg is found the same way `sidecarLauncher.ts`'s prod path
8
- * does: walk the optional deps via `createRequire` and look for one whose
9
- * `manifest.json` declares the right Node binary. We do NOT copy the pkg to
10
- * $TACO_HOME — launchd / schtasks invoke a wrapper that points at the
11
- * pkg's existing install location, so a `pnpm update` of the platform pkg
12
- * propagates without re-running `taco install`.
7
+ * Resolution order, first match wins:
8
+ * 1. TACO_SIDECAR_NODE / _BUNDLE / _RESOURCES env triple — explicit override.
9
+ * 2. An installed `@taco-ai/sidecar-<platform>` package, located via
10
+ * `createRequire` and validated against its `manifest.json`. This is the
11
+ * released path.
12
+ * 3. Dev checkout: `packages/sidecar/dist/runtime/<triple>/`, which
13
+ * `buildRuntime.mjs` emits with the same layout as the platform package
14
+ * (`lib/index.mjs`, `bin/taco-sidecar-node`, `agents/`, `skills/`,
15
+ * `manifest.json`). Needed because the per-platform optionalDependencies
16
+ * were dropped from the sidecar manifest, so a dev checkout has no
17
+ * platform package to resolve at (2).
18
+ *
19
+ * We do NOT copy the resolved tree to $TACO_HOME — launchd / schtasks invoke a
20
+ * wrapper pointing at its existing location. For (2) that means a `pnpm update`
21
+ * propagates without re-running `taco install`; for (3) a `package:runtime`
22
+ * rebuild propagates the same way. The tradeoff is that deleting the resolved
23
+ * tree (`rm -rf node_modules`, wiping `dist/`) leaves the wrapper dangling until
24
+ * `taco install` re-runs.
13
25
  */
14
26
 
15
27
  import { spawn } from "node:child_process";
16
28
  import { existsSync, readFileSync } from "node:fs";
17
29
  import { createRequire } from "node:module";
18
30
  import { dirname, join } from "node:path";
19
- import { PLATFORM_KEYS } from "./upgradePlatform.ts";
31
+ import { findRepoRoot } from "./sidecarLauncher.ts";
32
+ import { currentTriple, PLATFORM_KEYS } from "./upgradePlatform.ts";
20
33
 
21
34
  export interface PlatformPkgPaths {
22
35
  /** Absolute path to the @taco-ai/sidecar-<platform>/ package directory. */
@@ -61,36 +74,59 @@ export function findPlatformPkg(): PlatformPkgPaths | null {
61
74
 
62
75
  const req = createRequire(import.meta.url);
63
76
  for (const key of PLATFORM_KEYS) {
77
+ let pkgDir: string;
64
78
  try {
65
- const pkgJsonPath = req.resolve(`@taco-ai/sidecar-${key}/package.json`);
66
- const pkgDir = dirname(pkgJsonPath);
67
- const manifestPath = join(pkgDir, "manifest.json");
68
- if (!existsSync(manifestPath)) continue;
69
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
70
- target?: string;
71
- daemonMode?: boolean;
72
- };
73
- const nodeBin = join(
74
- pkgDir,
75
- "bin",
76
- manifest.target?.endsWith("-pc-windows-msvc")
77
- ? "taco-sidecar-node.exe"
78
- : "taco-sidecar-node",
79
- );
80
- if (!existsSync(nodeBin)) continue;
81
- const bundle = join(pkgDir, "lib", "index.mjs");
82
- if (!existsSync(bundle)) continue;
83
- // Trust the manifest's flag when present; fall back to a bundle
84
- // grep for older packages that predate the field.
85
- const daemonMode = manifest.daemonMode === true ? true : bundleHasDaemonMode(bundle);
86
- return { pkgDir, nodeBin, bundle, resources: pkgDir, daemonMode };
79
+ pkgDir = dirname(req.resolve(`@taco-ai/sidecar-${key}/package.json`));
87
80
  } catch {
88
- // not installed / wrong platform — try next
81
+ continue; // not installed / wrong platform — try next
89
82
  }
83
+ const probed = probePkgDir(pkgDir);
84
+ if (probed) return probed;
85
+ }
86
+
87
+ // Dev checkout fallback. `buildRuntime.mjs` emits dist/runtime/<triple>/ with
88
+ // the same layout the platform package ships, so the wrapper can point
89
+ // straight at it and skip the staging copy entirely.
90
+ const repoRoot = findRepoRoot();
91
+ if (repoRoot !== null) {
92
+ const distDir = join(repoRoot, "packages", "sidecar", "dist", "runtime", currentTriple());
93
+ const probed = probePkgDir(distDir);
94
+ if (probed) return probed;
90
95
  }
91
96
  return null;
92
97
  }
93
98
 
99
+ /** Validate a directory that claims to hold a sidecar runtime and lift it into
100
+ * `PlatformPkgPaths`. Returns null when any required artifact is missing, so
101
+ * callers can fall through to the next resolution strategy. Shared by the
102
+ * platform-package and dev-checkout branches — they differ only in how the
103
+ * directory is located, not in what makes it valid.
104
+ *
105
+ * Exported for unit tests; production callers should reach for
106
+ * `findPlatformPkg`, which applies the three resolution strategies in order. */
107
+ export function probePkgDir(pkgDir: string): PlatformPkgPaths | null {
108
+ const manifestPath = join(pkgDir, "manifest.json");
109
+ if (!existsSync(manifestPath)) return null;
110
+ let manifest: { target?: string; daemonMode?: boolean };
111
+ try {
112
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as typeof manifest;
113
+ } catch {
114
+ return null;
115
+ }
116
+ const nodeBin = join(
117
+ pkgDir,
118
+ "bin",
119
+ manifest.target?.endsWith("-pc-windows-msvc")
120
+ ? "taco-sidecar-node.exe"
121
+ : "taco-sidecar-node",
122
+ );
123
+ if (!existsSync(nodeBin)) return null;
124
+ const bundle = join(pkgDir, "lib", "index.mjs");
125
+ if (!existsSync(bundle)) return null;
126
+ const daemonMode = manifest.daemonMode === true ? true : bundleHasDaemonMode(bundle);
127
+ return { pkgDir, nodeBin, bundle, resources: pkgDir, daemonMode };
128
+ }
129
+
94
130
  /** Cheap daemon-mode probe: read the bundle and look for the env var the
95
131
  * runtime gates on. Older manifests lack the `daemonMode` field, so
96
132
  * install must fall back to this rather than reject. Bundle read is
package/lib/installId.ts CHANGED
@@ -38,6 +38,9 @@ export interface ParsedPidFile {
38
38
  startedAt: string | null;
39
39
  /** Schema version, when the on-disk format is JSON. null for legacy. */
40
40
  version: number | null;
41
+ /** `sidecar_version` from the JSON record; null for legacy files and for
42
+ * records written by daemons that predate the field. */
43
+ sidecarVersion: string | null;
41
44
  }
42
45
 
43
46
  export function parsePidFile(contents: string): ParsedPidFile | null {
@@ -59,8 +62,10 @@ export function parsePidFile(contents: string): ParsedPidFile | null {
59
62
  const pid = typeof parsed.pid === "number" ? parsed.pid : Number.NaN;
60
63
  const installId = typeof parsed.install_id === "string" ? parsed.install_id : null;
61
64
  const startedAt = typeof parsed.started_at === "string" ? parsed.started_at : null;
65
+ const sidecarVersion =
66
+ typeof parsed.sidecar_version === "string" ? parsed.sidecar_version : null;
62
67
  if (!Number.isFinite(pid) || pid <= 0) return null;
63
- return { pid, installId, startedAt, version: 1 };
68
+ return { pid, installId, startedAt, version: 1, sidecarVersion };
64
69
  } catch {
65
70
  return null;
66
71
  }
@@ -71,5 +76,25 @@ export function parsePidFile(contents: string): ParsedPidFile | null {
71
76
  // sanity-check with isFinite + positive.
72
77
  const pid = Number.parseInt(trimmed, 10);
73
78
  if (!Number.isFinite(pid) || pid <= 0) return null;
74
- return { pid, installId: null, startedAt: null, version: null };
79
+ return { pid, installId: null, startedAt: null, version: null, sidecarVersion: null };
80
+ }
81
+
82
+ /** Decide whether a serving daemon should be reaped for running stale code.
83
+ *
84
+ * Ownership comes first: a record whose install_id names a DIFFERENT
85
+ * install is never ours to kill (sibling installs share $TACO_HOME by
86
+ * design), and an absent/unparseable record gives no ownership claim at
87
+ * all — killing on that basis could hit a daemon we don't own. Only when
88
+ * the record is ours (install_id match, or legacy bare-int which only our
89
+ * predecessors could have written) does the version comparison apply, and
90
+ * a missing sidecar_version counts as stale: pre-field daemons are older
91
+ * than any launcher that knows to compare. */
92
+ export function pidRecordIsStale(
93
+ parsed: ParsedPidFile | null,
94
+ ownInstallId: string,
95
+ expectedVersion: string,
96
+ ): boolean {
97
+ if (parsed === null) return false;
98
+ if (parsed.installId !== null && parsed.installId !== ownInstallId) return false;
99
+ return parsed.sidecarVersion !== expectedVersion;
75
100
  }
@@ -34,11 +34,21 @@ interface BundlePaths {
34
34
  nodeBin: string;
35
35
  bundle: string;
36
36
  resources: string;
37
+ /** `sidecarVersion` from the bundle's manifest.json — the code version a
38
+ * freshly spawned daemon would report. null when the manifest predates
39
+ * the field. */
40
+ sidecarVersion: string | null;
37
41
  }
38
42
 
39
43
  /** Detect dev mode by walking up from this file looking for pnpm-workspace.yaml.
40
- * Returns the repo root (parent of `packages/`) when found, else null. */
41
- function findRepoRoot(): string | null {
44
+ * Returns the repo root (parent of `packages/`) when found, else null.
45
+ *
46
+ * Exported because three call sites need the same dev/prod discrimination
47
+ * (`launchSidecar` here, `resolveDaemonResourcesRoot` in start.ts, and
48
+ * `findPlatformPkg` in installHelpers.ts). Two of them had inlined copies
49
+ * of this walk, which is how the platform-package assumption drifted apart
50
+ * after the per-platform optionalDependencies were dropped. */
51
+ export function findRepoRoot(): string | null {
42
52
  let dir = dirname(fileURLToPath(import.meta.url));
43
53
  for (let i = 0; i < 8; i++) {
44
54
  if (existsSync(join(dir, "pnpm-workspace.yaml"))) {
@@ -51,6 +61,14 @@ function findRepoRoot(): string | null {
51
61
  return null;
52
62
  }
53
63
 
64
+ /** Single source of truth for "this CLI runs from a dev checkout".
65
+ * `launchSidecar` and `start.ts`'s stale-daemon gate must agree on this —
66
+ * when they drifted, a dev `taco start` could decide to reuse a daemon the
67
+ * spawn path was about to replace with tsx source (or vice versa). */
68
+ export function isDevCheckout(repoRoot: string | null = findRepoRoot()): boolean {
69
+ return repoRoot !== null && process.env.TACO_SIDECAR_DEV !== "0";
70
+ }
71
+
54
72
  /** When the CLI is launched from a development checkout (sibling of `packages/`),
55
73
  * prefer `tsx <repo>/packages/sidecar/src/index.ts` over the bundled platform pkg
56
74
  * so devs see hot-reload + line numbers in stack traces. */
@@ -78,7 +96,10 @@ function prodBundlePaths(): BundlePaths | null {
78
96
  const pkgDir = dirname(pkgJsonPath);
79
97
  const manifestPath = join(pkgDir, "manifest.json");
80
98
  if (!existsSync(manifestPath)) continue;
81
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { target?: string };
99
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
100
+ target?: string;
101
+ sidecarVersion?: string;
102
+ };
82
103
  const nodeBin = join(
83
104
  pkgDir,
84
105
  "bin",
@@ -89,7 +110,13 @@ function prodBundlePaths(): BundlePaths | null {
89
110
  if (!existsSync(nodeBin)) continue;
90
111
  const bundle = join(pkgDir, "lib", "index.mjs");
91
112
  if (!existsSync(bundle)) continue;
92
- return { nodeBin, bundle, resources: pkgDir };
113
+ return {
114
+ nodeBin,
115
+ bundle,
116
+ resources: pkgDir,
117
+ sidecarVersion:
118
+ typeof manifest.sidecarVersion === "string" ? manifest.sidecarVersion : null,
119
+ };
93
120
  } catch {
94
121
  // not installed / wrong platform — try next
95
122
  }
@@ -97,6 +124,15 @@ function prodBundlePaths(): BundlePaths | null {
97
124
  return null;
98
125
  }
99
126
 
127
+ /** The sidecar code version a prod spawn would run, per the platform
128
+ * bundle's manifest.json. `start.ts` compares this against a serving
129
+ * daemon's pid-record version and reaps on mismatch. null in dev checkouts
130
+ * (no platform pkg) — dev mode reaps unconditionally instead, since the
131
+ * version string cannot see source edits. */
132
+ export function prodSidecarVersion(): string | null {
133
+ return prodBundlePaths()?.sidecarVersion ?? null;
134
+ }
135
+
100
136
  export interface LaunchOptions {
101
137
  /** NDJSON socket path the bundle should bind. */
102
138
  socketPath: string;
@@ -126,8 +162,7 @@ export interface LaunchResult {
126
162
  * the daemon in a service anyway). */
127
163
  export function launchSidecar(opts: LaunchOptions): LaunchResult {
128
164
  const repoRoot = findRepoRoot();
129
- const useDev =
130
- opts.forceDev === true || (repoRoot !== null && process.env.TACO_SIDECAR_DEV !== "0");
165
+ const useDev = opts.forceDev === true || isDevCheckout(repoRoot);
131
166
 
132
167
  let bundle: LaunchedBundle;
133
168
  let resourcesRoot: string | undefined;
package/lib/start.ts CHANGED
@@ -9,8 +9,11 @@
9
9
  *
10
10
  * Flow:
11
11
  * 1. Resolve shared $TACO_HOME and the daemon runtime directory; create both if missing.
12
- * 2. If a daemon already answers on the control socket, print the NDJSON
13
- * path and return — no spawn.
12
+ * 2. If a daemon already answers on the NDJSON socket AND runs the code
13
+ * this launch would spawn (pid-record version match; dev checkouts
14
+ * never match), print the socket path and return — no spawn. A healthy
15
+ * but stale daemon is reaped first, via the same kill path as a wedged
16
+ * one.
14
17
  * 3. Otherwise elect a spawner via `start.lock`. The winner spawns and waits
15
18
  * for readiness; losers skip the spawn and wait on the same socket.
16
19
  * 4. Print the NDJSON socket path to stdout (single line) so callers
@@ -20,14 +23,13 @@
20
23
  * alive would tie the daemon's lifetime to whoever ran `taco start`.
21
24
  */
22
25
 
23
- import { existsSync, readFileSync, unlinkSync } from "node:fs";
26
+ import { readFileSync, unlinkSync } from "node:fs";
24
27
  import { createRequire } from "node:module";
25
28
  import { connect, type Socket } from "node:net";
26
29
  import * as path from "node:path";
27
30
  import { join } from "node:path";
28
- import { fileURLToPath } from "node:url";
29
31
  import { findPlatformPkg } from "./installHelpers.ts";
30
- import { computeInstallId, parsePidFile } from "./installId.ts";
32
+ import { computeInstallId, parsePidFile, pidRecordIsStale } from "./installId.ts";
31
33
  import {
32
34
  controlSocketPath,
33
35
  ensureDirs,
@@ -35,7 +37,12 @@ import {
35
37
  resolveTacoRuntimeDir,
36
38
  TACO_HOME,
37
39
  } from "./paths.ts";
38
- import { launchSidecar } from "./sidecarLauncher.ts";
40
+ import {
41
+ findRepoRoot,
42
+ isDevCheckout,
43
+ launchSidecar,
44
+ prodSidecarVersion,
45
+ } from "./sidecarLauncher.ts";
39
46
  import { acquireStartLock, readStartLock } from "./startLock.ts";
40
47
  import { upgradeApplyCommand } from "./upgradeApply.ts";
41
48
  import { markerTargetsInstall, readUpgradeMarker } from "./upgradeMarker.ts";
@@ -231,32 +238,17 @@ export interface StartOptions {
231
238
  * daemon from starting on the old bundle — the marker-clearing policy
232
239
  * lives in upgradeApplyCommand. */
233
240
  /** Resolve the resources root the daemon would use when started by this CLI.
234
- * Mirrors `sidecarLauncher.ts::launchSidecar`'s dev/prod branch so the
235
- * install_id we stamp on the reap check matches the id the daemon will
236
- * stamp on its own pid file (sidecar/index.ts computes its id from
237
- * TACO_SIDECAR_RESOURCES). Without this symmetry, standalone \`taco start\`
238
- * (npm global) — whose own process doesn't see TACO_SIDECAR_RESOURCES —
239
- * computed hash("") and skipped every wedged reap as ForeignInstall,
240
- * leaving the wedged daemon alive until the next start. */
241
+ * Uses `sidecarLauncher.ts::findRepoRoot`/`isDevCheckout` so the dev/prod
242
+ * discrimination matches `launchSidecar` exactly — the install_id we stamp
243
+ * on the reap check must match the id the daemon stamps on its own pid file
244
+ * (sidecar/index.ts computes its id from TACO_SIDECAR_RESOURCES). Without
245
+ * this symmetry, standalone \`taco start\` (npm global) — whose own process
246
+ * doesn't see TACO_SIDECAR_RESOURCES — computed hash("") and skipped every
247
+ * wedged reap as ForeignInstall, leaving the wedged daemon alive until the
248
+ * next start. */
241
249
  function resolveDaemonResourcesRoot(): string | undefined {
242
- const repoRoot = (() => {
243
- try {
244
- // Replicate sidecarLauncher.ts:findRepoRoot's pnpm-workspace.yaml walk.
245
- const url = new URL(import.meta.url);
246
- let dir = path.dirname(fileURLToPath(url));
247
- for (let i = 0; i < 8; i++) {
248
- if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
249
- const parent = path.dirname(dir);
250
- if (parent === dir) break;
251
- dir = parent;
252
- }
253
- return null;
254
- } catch {
255
- return null;
256
- }
257
- })();
258
- const useDev = repoRoot !== null && process.env.TACO_SIDECAR_DEV !== "0";
259
- if (useDev && repoRoot) {
250
+ const repoRoot = findRepoRoot();
251
+ if (isDevCheckout(repoRoot) && repoRoot) {
260
252
  return join(repoRoot, "packages", "sidecar", "src");
261
253
  }
262
254
  // Prod: walk @taco-ai/sidecar-<platform>/ optional deps.
@@ -283,6 +275,27 @@ function resolveDaemonResourcesRoot(): string | undefined {
283
275
  return undefined;
284
276
  }
285
277
 
278
+ /** Why a serving daemon fails the freshness gate, or null when it may be
279
+ * reused. Dev checkouts always fail: the version string cannot see source
280
+ * edits, so "same version" says nothing about the code on disk (plan A).
281
+ * Prod compares the pid record's sidecar_version against the platform
282
+ * bundle's manifest version; a record we don't own (or can't parse) never
283
+ * justifies a kill — see pidRecordIsStale. */
284
+ function staleDaemonReason(
285
+ runtimeDir: string,
286
+ ownInstallId: string,
287
+ expectedVersion: string,
288
+ ): string | null {
289
+ let parsed: ReturnType<typeof parsePidFile> | null = null;
290
+ try {
291
+ parsed = parsePidFile(readFileSync(join(runtimeDir, "sidecar.pid"), "utf8"));
292
+ } catch {
293
+ parsed = null;
294
+ }
295
+ if (!pidRecordIsStale(parsed, ownInstallId, expectedVersion)) return null;
296
+ return `pid ${parsed?.pid ?? "?"} runs sidecar ${parsed?.sidecarVersion ?? "unknown"}, expected ${expectedVersion}`;
297
+ }
298
+
286
299
  async function applyOwnedPendingUpgrade(tacoHome: string): Promise<void> {
287
300
  const marker = await readUpgradeMarker(join(tacoHome, "upgrade-marker.json"));
288
301
  if (!marker) return;
@@ -318,10 +331,44 @@ export async function startCommand(opts: StartOptions = {}): Promise<void> {
318
331
  await new Promise((r) => setTimeout(r, 500));
319
332
  probe = await probeDaemonInitialize(socket);
320
333
  }
334
+
335
+ const daemonResourcesRoot = resolveDaemonResourcesRoot();
336
+ const ownInstallId = computeInstallId(daemonResourcesRoot ?? "", tacoHome);
337
+
321
338
  if (probe === "ready") {
322
- process.stdout.write(`${socket}\n`);
323
- process.stderr.write(`[taco] sidecar daemon already running (socket=${socket})\n`);
324
- return;
339
+ // Healthy is not enough — the daemon must also run the code THIS
340
+ // launch would spawn, or every upgrade/source edit would keep
341
+ // attaching to the previous build forever. Dev checkouts reap
342
+ // unconditionally (the version string can't see source edits); prod
343
+ // compares the pid record's sidecar_version against the platform
344
+ // bundle's manifest. Both reuse killWedgedDaemon — its install_id
345
+ // ownership check still applies, so a foreign install's daemon is
346
+ // never touched (pidRecordIsStale likewise refuses foreign records).
347
+ const devMode = isDevCheckout();
348
+ const expectedVersion = devMode ? null : prodSidecarVersion();
349
+ let staleReason: string | null;
350
+ if (devMode) {
351
+ staleReason = "dev checkout always respawns";
352
+ } else if (expectedVersion !== null) {
353
+ staleReason = staleDaemonReason(runtimeDir, ownInstallId, expectedVersion);
354
+ } else {
355
+ // No manifest version to compare against — reuse rather than reap
356
+ // on every launch, but say so: a silently disabled gate looks
357
+ // exactly like a working one until someone debugs why an upgrade
358
+ // never took effect.
359
+ staleReason = null;
360
+ process.stderr.write(
361
+ "[taco] freshness gate disabled: no bundle manifest version; reused daemon may be stale\n",
362
+ );
363
+ }
364
+ if (staleReason === null) {
365
+ process.stdout.write(`${socket}\n`);
366
+ process.stderr.write(`[taco] sidecar daemon already running (socket=${socket})\n`);
367
+ return;
368
+ }
369
+ process.stderr.write(`[taco] sidecar daemon stale (${staleReason}); restarting\n`);
370
+ await killWedgedDaemon(runtimeDir, socket, control, ownInstallId);
371
+ probe = "absent";
325
372
  }
326
373
  if (probe === "wedged") {
327
374
  // The socket answers connects but no RPC response arrives across two
@@ -332,21 +379,14 @@ export async function startCommand(opts: StartOptions = {}): Promise<void> {
332
379
  process.stderr.write(
333
380
  "[taco] sidecar daemon accepts connections but does not serve; killing it\n",
334
381
  );
335
- const daemonResourcesRoot = resolveDaemonResourcesRoot();
336
- const ownInstallId = computeInstallId(daemonResourcesRoot ?? "", tacoHome);
337
382
  await killWedgedDaemon(runtimeDir, socket, control, ownInstallId);
338
383
  }
339
384
 
340
- // Belt-and-braces: reap any leftover pid file even when probe was
341
- // "absent". A pid file pointing at a dead pid doesn't show up as
342
- // "wedged" (no listener) but it does mean our subsequent spawn
343
- // could race with cleanup. Force-reap for a deterministic baseline.
344
385
  // Belt-and-braces: at this point probe is narrowed to "absent".
345
386
  // A pid file pointing at a dead pid doesn't show up as "wedged" (no
346
387
  // listener) but it does mean our subsequent spawn could race with
347
- // cleanup. Force-reap for a deterministic baseline.
348
- const daemonResourcesRoot = resolveDaemonResourcesRoot();
349
- const ownInstallId = computeInstallId(daemonResourcesRoot ?? "", tacoHome);
388
+ // cleanup. Force-reap for a deterministic baseline. Idempotent after the
389
+ // stale/wedged kills above — their unlink leaves nothing to parse.
350
390
  await killWedgedDaemon(runtimeDir, socket, control, ownInstallId);
351
391
 
352
392
  const lock = await acquireStartLock(runtimeDir);
package/lib/status.ts CHANGED
@@ -5,70 +5,18 @@
5
5
  * version / protocol / uptime / pid reply as JSON. Useful for liveness checks
6
6
  * from shell scripts (`taco status >/dev/null || taco start`) and for human
7
7
  * diagnosis of "is the daemon actually up?".
8
+ *
9
+ * Wire format + retry behaviour live in `@taco-ai/shared/controlNode` so
10
+ * `taco stop` and any future control-socket client share a single impl.
8
11
  */
9
12
 
10
- import { connect, type Socket } from "node:net";
13
+ import { controlRequest } from "@taco-ai/shared/controlNode";
11
14
  import { controlSocketPath } from "./paths.ts";
12
15
 
13
16
  const PING_TIMEOUT_MS = 2_000;
14
17
 
15
- interface ControlReplyOk {
16
- result: unknown;
17
- id: number;
18
- }
19
- interface ControlReplyErr {
20
- error: { code: string; message: string };
21
- id: number;
22
- }
23
-
24
- function sendControlRequest(socketPath: string, method: string): Promise<unknown> {
25
- return new Promise((resolve, reject) => {
26
- const sock: Socket = connect(socketPath);
27
- let buf = "";
28
- let done = false;
29
- const finish = (fn: () => void) => {
30
- if (done) return;
31
- done = true;
32
- sock.destroy();
33
- fn();
34
- };
35
- const timer = setTimeout(() => {
36
- finish(() => reject(new Error(`${method} timed out after ${PING_TIMEOUT_MS}ms`)));
37
- }, PING_TIMEOUT_MS);
38
-
39
- sock.once("error", (err) => {
40
- clearTimeout(timer);
41
- finish(() => reject(new Error(`${method}: ${err.message}`)));
42
- });
43
- sock.once("connect", () => {
44
- sock.write(`${JSON.stringify({ method, id: 1 })}\n`);
45
- });
46
- sock.on("data", (chunk) => {
47
- buf += chunk.toString("utf8");
48
- const nl = buf.indexOf("\n");
49
- if (nl < 0) return;
50
- const line = buf.slice(0, nl);
51
- clearTimeout(timer);
52
- try {
53
- const reply = JSON.parse(line) as ControlReplyOk | ControlReplyErr;
54
- if ("error" in reply) {
55
- finish(() => reject(new Error(`${reply.error.code}: ${reply.error.message}`)));
56
- } else {
57
- finish(() => resolve(reply.result));
58
- }
59
- } catch (err) {
60
- finish(() => reject(new Error(`malformed reply: ${String(err)}`)));
61
- }
62
- });
63
- sock.on("close", () => {
64
- clearTimeout(timer);
65
- if (!done) finish(() => reject(new Error("socket closed before reply")));
66
- });
67
- });
68
- }
69
-
70
18
  export async function statusCommand(): Promise<void> {
71
19
  const control = controlSocketPath();
72
- const result = await sendControlRequest(control, "control.ping");
20
+ const result = await controlRequest(control, "control.ping", { timeoutMs: PING_TIMEOUT_MS });
73
21
  process.stdout.write(`${JSON.stringify(result)}\n`);
74
22
  }
package/lib/stop.ts CHANGED
@@ -9,75 +9,18 @@
9
9
  * packages/sidecar/src/index.ts). If it lingers past the deadline, we
10
10
  * report that the daemon accepted shutdown but the cleanup is taking longer
11
11
  * than expected — operator-visible rather than silently broken.
12
+ *
13
+ * Wire format + retry behaviour live in `@taco-ai/shared/controlNode` so
14
+ * `taco status` and any future control-socket client share a single impl.
12
15
  */
13
16
 
14
- import { connect, type Socket } from "node:net";
17
+ import { existsSync } from "node:fs";
18
+ import { controlRequest } from "@taco-ai/shared/controlNode";
15
19
  import { controlSocketPath } from "./paths.ts";
16
20
 
17
21
  const SHUTDOWN_ACK_TIMEOUT_MS = 3_000;
18
22
  const SOCKET_GONE_TIMEOUT_MS = 3_000;
19
23
 
20
- interface ControlReplyOk {
21
- result: unknown;
22
- id: number;
23
- }
24
- interface ControlReplyErr {
25
- error: { code: string; message: string };
26
- id: number;
27
- }
28
-
29
- function sendControlRequest(socketPath: string, method: string): Promise<unknown> {
30
- return new Promise((resolve, reject) => {
31
- const sock: Socket = connect(socketPath);
32
- let buf = "";
33
- let done = false;
34
- const finish = (fn: () => void) => {
35
- if (done) return;
36
- done = true;
37
- sock.destroy();
38
- fn();
39
- };
40
- const timer = setTimeout(() => {
41
- finish(() =>
42
- reject(new Error(`${method} timed out after ${SHUTDOWN_ACK_TIMEOUT_MS}ms`)),
43
- );
44
- }, SHUTDOWN_ACK_TIMEOUT_MS);
45
-
46
- sock.once("error", (err) => {
47
- clearTimeout(timer);
48
- finish(() => reject(new Error(`${method}: ${err.message}`)));
49
- });
50
- sock.once("connect", () => {
51
- sock.write(`${JSON.stringify({ method, id: 1 })}\n`);
52
- });
53
- sock.on("data", (chunk) => {
54
- buf += chunk.toString("utf8");
55
- const nl = buf.indexOf("\n");
56
- if (nl < 0) return;
57
- const line = buf.slice(0, nl);
58
- clearTimeout(timer);
59
- try {
60
- const reply = JSON.parse(line) as ControlReplyOk | ControlReplyErr;
61
- if ("error" in reply) {
62
- finish(() =>
63
- reject(new Error(`${method}: ${reply.error.code} ${reply.error.message}`)),
64
- );
65
- } else {
66
- finish(() => resolve(reply.result));
67
- }
68
- } catch (err) {
69
- finish(() => reject(new Error(`${method}: malformed reply: ${String(err)}`)));
70
- }
71
- });
72
- sock.on("close", () => {
73
- clearTimeout(timer);
74
- if (!done) {
75
- finish(() => reject(new Error(`${method}: socket closed before reply`)));
76
- }
77
- });
78
- });
79
- }
80
-
81
24
  async function waitForSocketGone(path: string): Promise<void> {
82
25
  const start = Date.now();
83
26
  while (Date.now() - start < SOCKET_GONE_TIMEOUT_MS) {
@@ -88,7 +31,7 @@ async function waitForSocketGone(path: string): Promise<void> {
88
31
  // the listener has shut down so subsequent connect attempts will fail.
89
32
  let exists = true;
90
33
  try {
91
- exists = (await import("node:fs")).existsSync(path);
34
+ exists = existsSync(path);
92
35
  } catch {
93
36
  exists = false;
94
37
  }
@@ -100,7 +43,9 @@ async function waitForSocketGone(path: string): Promise<void> {
100
43
 
101
44
  export async function stopCommand(): Promise<void> {
102
45
  const control = controlSocketPath();
103
- const result = await sendControlRequest(control, "control.shutdown");
46
+ const result = await controlRequest(control, "control.shutdown", {
47
+ timeoutMs: SHUTDOWN_ACK_TIMEOUT_MS,
48
+ });
104
49
  // Daemon flushes the reply, then unlinks + exits. Give it a moment to
105
50
  // actually disappear from the filesystem before declaring success.
106
51
  await waitForSocketGone(control);
@@ -16,6 +16,21 @@ export const PLATFORM_KEYS = [
16
16
 
17
17
  export type PlatformKey = (typeof PLATFORM_KEYS)[number];
18
18
 
19
+ /** Node platform-arch key → Rust target triple, naming the `dist/runtime/<triple>/`
20
+ * directory `buildRuntime.mjs` emits. Mirrors `FROM_PROCESS` in
21
+ * `packages/sidecar/scripts/triple.mjs`; duplicated rather than imported because
22
+ * the CLI must not reach into the sidecar's scripts/ dir. The `Record<PlatformKey, …>`
23
+ * type is load-bearing: adding a platform to PLATFORM_KEYS without a triple here
24
+ * becomes a compile error instead of a runtime `undefined` path. */
25
+ const TRIPLE_BY_KEY: Record<PlatformKey, string> = {
26
+ "darwin-arm64": "aarch64-apple-darwin",
27
+ "darwin-x64": "x86_64-apple-darwin",
28
+ "linux-x64": "x86_64-unknown-linux-gnu",
29
+ "linux-arm64": "aarch64-unknown-linux-gnu",
30
+ "win32-x64": "x86_64-pc-windows-msvc",
31
+ "win32-arm64": "aarch64-pc-windows-msvc",
32
+ };
33
+
19
34
  export const PLATFORM_PKG_PREFIX = "@taco-ai/sidecar-";
20
35
 
21
36
  /** npm package name for the current platform, e.g. `@taco-ai/sidecar-darwin-arm64`. */
@@ -24,6 +39,12 @@ export function currentPlatformPkg(): { key: PlatformKey; pkg: string } {
24
39
  return { key, pkg: `${PLATFORM_PKG_PREFIX}${key}` };
25
40
  }
26
41
 
42
+ /** Rust target triple for the current host, e.g. `aarch64-apple-darwin`. Names the
43
+ * `packages/sidecar/dist/runtime/<triple>/` tree a dev checkout builds. */
44
+ export function currentTriple(): string {
45
+ return TRIPLE_BY_KEY[currentPlatformKey()];
46
+ }
47
+
27
48
  export function currentPlatformKey(): PlatformKey {
28
49
  const platform = process.platform;
29
50
  const arch = process.arch;