@taco-ai/cli 0.1.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/lib/paths.ts ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Path constants for taco CLI / daemon layout under $TACO_HOME.
3
+ *
4
+ * Shared user data lives under $TACO_HOME. Daemon coordination state lives
5
+ * under $TACO_RUNTIME_DIR when it is set, otherwise $TACO_HOME/run:
6
+ * runtime/ # socket, control socket, pid, and start lock (Unix)
7
+ * bin/ # launcher wrapper scripts (taco-sidecar-daemon[.cmd])
8
+ * logs/ # service stdout/stderr targets
9
+ * staging/ # upgrade staging area
10
+ * jobs/ # scheduler job definitions
11
+ * taco.json # user config
12
+ * desktop.json # desktop-only config (sidecar reads via $TACO_HOME)
13
+ *
14
+ * $TACO_HOME resolution matches the sidecar's `tacoHome()` helper so CLI and
15
+ * sidecar agree on the root:
16
+ * 1. $TACO_HOME env (absolute, non-empty)
17
+ * 2. $HOME/.taco
18
+ */
19
+
20
+ import { mkdir } from "node:fs/promises";
21
+ import { homedir } from "node:os";
22
+ import { join } from "node:path";
23
+
24
+ /** Resolve the absolute $TACO_HOME directory (env > $HOME/.taco). Empty/whitespace env is treated as unset. */
25
+ export function resolveTacoHome(): string {
26
+ const raw = process.env.TACO_HOME?.trim();
27
+ if (raw && raw.length > 0) {
28
+ return raw;
29
+ }
30
+ return join(homedir(), ".taco");
31
+ }
32
+
33
+ export const TACO_HOME = resolveTacoHome();
34
+
35
+ /** Default daemon runtime directory for a user-data home. */
36
+ export function defaultRuntimeDir(home: string = TACO_HOME): string {
37
+ return join(home, "run");
38
+ }
39
+
40
+ /** Resolve daemon runtime state independently from the shared user-data home. */
41
+ export function resolveTacoRuntimeDir(
42
+ home: string = TACO_HOME,
43
+ runtimeOverride: string | undefined = process.env.TACO_RUNTIME_DIR,
44
+ ): string {
45
+ const raw = runtimeOverride?.trim();
46
+ return raw && raw.length > 0 ? raw : defaultRuntimeDir(home);
47
+ }
48
+
49
+ /** Current process daemon runtime directory. */
50
+ export const RUNTIME_DIR = resolveTacoRuntimeDir();
51
+ export const BIN_DIR = join(TACO_HOME, "bin");
52
+
53
+ /** NDJSON socket path. Unix: filesystem path under the runtime directory. Windows: named pipe. */
54
+ export function ndjsonSocketPath(runtimeDir: string = RUNTIME_DIR): string {
55
+ if (process.platform === "win32") {
56
+ return "\\\\.\\pipe\\taco-sidecar";
57
+ }
58
+ return join(runtimeDir, "sidecar.sock");
59
+ }
60
+
61
+ /** Control socket path. Unix: filesystem path under the runtime directory. Windows: named pipe. */
62
+ export function controlSocketPath(runtimeDir: string = RUNTIME_DIR): string {
63
+ if (process.platform === "win32") {
64
+ return "\\\\.\\pipe\\taco-sidecar-ctl";
65
+ }
66
+ return join(runtimeDir, "sidecar-ctl.sock");
67
+ }
68
+
69
+ /** Daemon pid file (Unix only; Windows uses service control manager in PR3). */
70
+ export function runtimePidFile(runtimeDir: string = RUNTIME_DIR): string {
71
+ return join(runtimeDir, "sidecar.pid");
72
+ }
73
+
74
+ /** Upgrade marker file (PR4). */
75
+ export const UPGRADE_MARKER = join(TACO_HOME, "upgrade-marker.json");
76
+
77
+ /** Logs root — launchd/schtasks redirect the daemon's stdout/stderr here. */
78
+ export const LOG_DIR = join(TACO_HOME, "logs");
79
+
80
+ /** Upgrade staging area — PR4 downloads the new bundle here before swapping. */
81
+ export const STAGING_DIR = join(TACO_HOME, "staging");
82
+
83
+ /** Scheduler job definitions root (PR4). */
84
+ export const JOBS_DIR = join(TACO_HOME, "jobs");
85
+
86
+ /** Create the directory tree under $TACO_HOME that `taco install` + later PRs rely on.
87
+ * Idempotent (recursive mkdir). Modes are 0o755 so launchd / schtasks can read
88
+ * the wrapper script but a multi-user system doesn't accidentally inherit
89
+ * world-writable state. The helper takes an explicit `home` so callers can
90
+ * override $TACO_HOME for tests / dry-run scenarios. */
91
+ export async function ensureDirs(
92
+ home: string = TACO_HOME,
93
+ runtimeDir: string = resolveTacoRuntimeDir(home),
94
+ ): Promise<void> {
95
+ await mkdir(runtimeDir, { recursive: true, mode: 0o755 });
96
+ await mkdir(join(home, "bin"), { recursive: true, mode: 0o755 });
97
+ await mkdir(join(home, "logs"), { recursive: true, mode: 0o755 });
98
+ await mkdir(join(home, "staging"), { recursive: true, mode: 0o755 });
99
+ await mkdir(join(home, "jobs"), { recursive: true, mode: 0o755 });
100
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Locate the sidecar bundle and spawn it with the right env to enter daemon mode.
3
+ *
4
+ * Two launch modes:
5
+ * - dev (TACO_SIDECAR_DEV=1 or this file is in repo's packages/cli): spawn
6
+ * `tsx <repo>/packages/sidecar/src/index.ts` so the developer gets hot
7
+ * reload + TypeScript source.
8
+ * - prod: locate the platform-specific optional dep
9
+ * (`@taco-ai/sidecar-<platform>`) via `createRequire`, read its
10
+ * `manifest.json` to find the node binary + bundle, spawn them.
11
+ *
12
+ * The spawn always sets:
13
+ * TACO_DAEMON_MODE=1 — bundle listens on sockets instead of stdio
14
+ * TACO_SOCKET=<path> — NDJSON socket
15
+ * TACO_CONTROL_SOCKET=<path> — control socket
16
+ * TACO_HOME=<path> — config / log root
17
+ * TACO_SIDECAR_RESOURCES=<p> — agents/ + skills/ root (only prod has bundled resources)
18
+ */
19
+
20
+ import { type ChildProcess, spawn } from "node:child_process";
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { createRequire } from "node:module";
23
+ import { dirname, join } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ import { PLATFORM_KEYS } from "./upgradePlatform.ts";
26
+
27
+ interface LaunchedBundle {
28
+ program: string;
29
+ args: string[];
30
+ cwd?: string;
31
+ }
32
+
33
+ interface BundlePaths {
34
+ nodeBin: string;
35
+ bundle: string;
36
+ resources: string;
37
+ }
38
+
39
+ /** 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 {
42
+ let dir = dirname(fileURLToPath(import.meta.url));
43
+ for (let i = 0; i < 8; i++) {
44
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) {
45
+ return dir;
46
+ }
47
+ const parent = dirname(dir);
48
+ if (parent === dir) break;
49
+ dir = parent;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /** When the CLI is launched from a development checkout (sibling of `packages/`),
55
+ * prefer `tsx <repo>/packages/sidecar/src/index.ts` over the bundled platform pkg
56
+ * so devs see hot-reload + line numbers in stack traces. */
57
+ function devLauncher(repoRoot: string): LaunchedBundle {
58
+ const repoTsx = join(
59
+ repoRoot,
60
+ "node_modules",
61
+ ".bin",
62
+ process.platform === "win32" ? "tsx.cmd" : "tsx",
63
+ );
64
+ const program = existsSync(repoTsx) ? repoTsx : "tsx";
65
+ return {
66
+ program,
67
+ args: [join(repoRoot, "packages", "sidecar", "src", "index.ts")],
68
+ cwd: repoRoot,
69
+ };
70
+ }
71
+
72
+ /** Locate the @taco-ai/sidecar-<platform>/lib/index.mjs + bundled node binary. */
73
+ function prodBundlePaths(): BundlePaths | null {
74
+ const req = createRequire(import.meta.url);
75
+ for (const key of PLATFORM_KEYS) {
76
+ try {
77
+ const pkgJsonPath = req.resolve(`@taco-ai/sidecar-${key}/package.json`);
78
+ const pkgDir = dirname(pkgJsonPath);
79
+ const manifestPath = join(pkgDir, "manifest.json");
80
+ if (!existsSync(manifestPath)) continue;
81
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { target?: string };
82
+ const nodeBin = join(
83
+ pkgDir,
84
+ "bin",
85
+ manifest.target?.endsWith("-pc-windows-msvc")
86
+ ? "taco-sidecar-node.exe"
87
+ : "taco-sidecar-node",
88
+ );
89
+ if (!existsSync(nodeBin)) continue;
90
+ const bundle = join(pkgDir, "lib", "index.mjs");
91
+ if (!existsSync(bundle)) continue;
92
+ return { nodeBin, bundle, resources: pkgDir };
93
+ } catch {
94
+ // not installed / wrong platform — try next
95
+ }
96
+ }
97
+ return null;
98
+ }
99
+
100
+ export interface LaunchOptions {
101
+ /** NDJSON socket path the bundle should bind. */
102
+ socketPath: string;
103
+ /** Control socket path the bundle should bind. */
104
+ controlSocketPath: string;
105
+ /** TACO_HOME to forward to the bundle. */
106
+ tacoHome: string;
107
+ /** Daemon socket, pid, and lock runtime directory. */
108
+ runtimeDir: string;
109
+ /** Extra env vars to pass through (e.g. PATH, HOME). */
110
+ extraEnv?: Record<string, string>;
111
+ /** When true, force dev mode even if the platform pkg is installed. */
112
+ forceDev?: boolean;
113
+ }
114
+
115
+ export interface LaunchResult {
116
+ child: ChildProcess;
117
+ /** Set to true if the child is running in dev mode (tsx + source). */
118
+ dev: boolean;
119
+ }
120
+
121
+ /** Spawn the sidecar bundle in daemon mode. Returns the child handle so the caller can
122
+ * forward signals / wait for exit. The child is spawned detached: on POSIX it gets
123
+ * its own process group (terminal signals aimed at the launcher don't reach the
124
+ * daemon) and is reparented to init once the launcher exits; on Windows detaching
125
+ * releases it from the launcher's job object so it outlives the launcher (PR3 wraps
126
+ * the daemon in a service anyway). */
127
+ export function launchSidecar(opts: LaunchOptions): LaunchResult {
128
+ const repoRoot = findRepoRoot();
129
+ const useDev =
130
+ opts.forceDev === true || (repoRoot !== null && process.env.TACO_SIDECAR_DEV !== "0");
131
+
132
+ let bundle: LaunchedBundle;
133
+ let resourcesRoot: string | undefined;
134
+
135
+ if (useDev && repoRoot) {
136
+ bundle = devLauncher(repoRoot);
137
+ resourcesRoot = join(repoRoot, "packages", "sidecar", "src");
138
+ } else {
139
+ const prod = prodBundlePaths();
140
+ if (!prod) {
141
+ throw new Error(
142
+ "no @taco-ai/sidecar-<platform> bundle installed. " +
143
+ "Run `pnpm install` on a supported platform " +
144
+ `(${PLATFORM_KEYS.join(", ")}) or set TACO_SIDECAR_DEV=1.`,
145
+ );
146
+ }
147
+ bundle = { program: prod.nodeBin, args: [prod.bundle] };
148
+ resourcesRoot = prod.resources;
149
+ }
150
+
151
+ const env: NodeJS.ProcessEnv = {
152
+ ...process.env,
153
+ ...(opts.extraEnv ?? {}),
154
+ TACO_DAEMON_MODE: "1",
155
+ TACO_SOCKET: opts.socketPath,
156
+ TACO_CONTROL_SOCKET: opts.controlSocketPath,
157
+ TACO_HOME: opts.tacoHome,
158
+ TACO_RUNTIME_DIR: opts.runtimeDir,
159
+ TACO_SIDECAR_RESOURCES: resourcesRoot,
160
+ };
161
+
162
+ const child = spawn(bundle.program, bundle.args, {
163
+ cwd: bundle.cwd,
164
+ env,
165
+ // Detached daemon: own process group on POSIX, released from the
166
+ // launcher's job object on Windows. Paired with child.unref() in
167
+ // start.ts so the daemon's lifetime is fully decoupled from whoever
168
+ // ran `taco start`.
169
+ detached: true,
170
+ // Daemon mode: NDJSON goes via the socket, stderr goes to the daemon's
171
+ // own log file (sidecar opens LogFiles at $TACO_HOME/logs/), stdin is
172
+ // ignored (control socket is the inbound path).
173
+ stdio: ["ignore", "ignore", "inherit"],
174
+ // Windows: don't pop a conhost window for the daemon.
175
+ ...(process.platform === "win32" ? { windowsHide: true } : {}),
176
+ });
177
+
178
+ return { child, dev: useDev };
179
+ }
package/lib/start.ts ADDED
@@ -0,0 +1,381 @@
1
+ /**
2
+ * `taco start` — ensure a daemon is running and report its socket path.
3
+ *
4
+ * Idempotent by design: the desktop can reach this through two independent
5
+ * paths (the setup hook's `taco install`, and `workspace_ensure`'s launcher
6
+ * spawn), and macOS launchd `RunAtLoad=true` adds a third. Spawning
7
+ * unconditionally meant two daemons racing to bind the same control socket,
8
+ * where the loser exited non-zero and launchd restarted it forever.
9
+ *
10
+ * Flow:
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.
14
+ * 3. Otherwise elect a spawner via `start.lock`. The winner spawns and waits
15
+ * for readiness; losers skip the spawn and wait on the same socket.
16
+ * 4. Print the NDJSON socket path to stdout (single line) so callers
17
+ * (Tauri UI / scripts) can read it via `Command::output()`.
18
+ *
19
+ * Why exit after ready: this CLI is a launcher, not a supervisor. Keeping it
20
+ * alive would tie the daemon's lifetime to whoever ran `taco start`.
21
+ */
22
+
23
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
24
+ import { createRequire } from "node:module";
25
+ import { connect, type Socket } from "node:net";
26
+ import * as path from "node:path";
27
+ import { join } from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+ import { findPlatformPkg } from "./installHelpers.ts";
30
+ import { computeInstallId, parsePidFile } from "./installId.ts";
31
+ import {
32
+ controlSocketPath,
33
+ ensureDirs,
34
+ ndjsonSocketPath,
35
+ resolveTacoRuntimeDir,
36
+ TACO_HOME,
37
+ } from "./paths.ts";
38
+ import { launchSidecar } from "./sidecarLauncher.ts";
39
+ import { acquireStartLock, readStartLock } from "./startLock.ts";
40
+ import { upgradeApplyCommand } from "./upgradeApply.ts";
41
+ import { markerTargetsInstall, readUpgradeMarker } from "./upgradeMarker.ts";
42
+
43
+ const READY_TIMEOUT_MS = 15_000;
44
+ const PROBE_INTERVAL_MS = 50;
45
+ /** How long a lock loser waits for the winner's daemon. Longer than
46
+ * READY_TIMEOUT_MS because the winner may only just have started spawning. */
47
+ const FOLLOWER_WAIT_MS = 20_000;
48
+ /** Grace window between SIGTERM and SIGKILL when reaping a wedged daemon. */
49
+ const KILL_GRACE_MS = 3_000;
50
+
51
+ /** Result of probing the NDJSON socket for a live, serving daemon. */
52
+ type DaemonProbe = "ready" | "absent" | "wedged";
53
+
54
+ /** True readiness probe: connect to the NDJSON socket and wait for the
55
+ * daemon's one-shot `sidecar.hello` frame. A bare TCP connect is NOT a
56
+ * valid probe — the kernel completes connections from the listen backlog
57
+ * even when the daemon's event loop is wedged, and the control socket is
58
+ * bound early in boot (long before the NDJSON listener exists), so both
59
+ * older probes reported "ready" against daemons that couldn't serve a
60
+ * single frame. The desktop then timed out waiting for a hello that was
61
+ * never going to come.
62
+ *
63
+ * Deliberately self-contained rather than imported from the sidecar: the
64
+ * CLI does not depend on sidecar TS source (only the bundled platform pkg
65
+ * ships at runtime). Same reasoning as the note atop `upgradeMarker.ts`. */
66
+ function probeDaemonHello(path: string, timeoutMs = 5_000): Promise<DaemonProbe> {
67
+ return new Promise((resolve) => {
68
+ const sock: Socket = connect(path);
69
+ let buf = "";
70
+ const timer = setTimeout(() => finish("wedged"), timeoutMs);
71
+ function finish(result: DaemonProbe): void {
72
+ clearTimeout(timer);
73
+ sock.destroy();
74
+ resolve(result);
75
+ }
76
+ sock.on("data", (chunk) => {
77
+ buf += chunk.toString("utf8");
78
+ const nl = buf.indexOf("\n");
79
+ if (nl === -1) return;
80
+ try {
81
+ const frame = JSON.parse(buf.slice(0, nl)) as { method?: unknown };
82
+ finish(frame.method === "sidecar.hello" ? "ready" : "wedged");
83
+ } catch {
84
+ finish("wedged");
85
+ }
86
+ });
87
+ sock.once("error", () => finish("absent"));
88
+ });
89
+ }
90
+
91
+ function pidAlive(pid: number): boolean {
92
+ try {
93
+ process.kill(pid, 0);
94
+ return true;
95
+ } catch (err) {
96
+ return (err as NodeJS.ErrnoException)?.code === "EPERM";
97
+ }
98
+ }
99
+
100
+ /** Reap a daemon that accepts connections but won't serve them.
101
+ *
102
+ * Order matters:
103
+ * 1. Read pid file with `parsePidFile` (JSON record preferred, bare-int
104
+ * legacy accepted for backward compat).
105
+ * 2. Skip reap if the file's `install_id` (when present) does not match
106
+ * this CLI's own install id — otherwise we'd kill a sibling taco
107
+ * install that happens to share $TACO_HOME.
108
+ * 3. SIGTERM via the pid, grace window, then SIGKILL — SIGKILL skips
109
+ * the daemon's exit handlers so we unlink sockets + pid file
110
+ * ourselves, otherwise the next daemon's single-instance probe
111
+ * would see a ghost listener and exit.
112
+ *
113
+ * Without this path a wedged daemon made every subsequent launch fail
114
+ * until the machine was rebooted. */
115
+ async function killWedgedDaemon(
116
+ runtimeDir: string,
117
+ socket: string,
118
+ control: string,
119
+ ownInstallId: string,
120
+ ): Promise<void> {
121
+ const pidFile = join(runtimeDir, "sidecar.pid");
122
+ let parsed: ReturnType<typeof parsePidFile> | null = null;
123
+ try {
124
+ parsed = parsePidFile(readFileSync(pidFile, "utf8"));
125
+ } catch {
126
+ parsed = null;
127
+ }
128
+ // install_id is null for legacy bare-int files. We reap those — a
129
+ // pre-PR-A daemon is the only thing that could have written them,
130
+ // and the migration to the new format happens naturally on the next
131
+ // fresh spawn.
132
+ const ownerMatches =
133
+ parsed !== null && (parsed.installId === null || parsed.installId === ownInstallId);
134
+ if (parsed !== null && ownerMatches) {
135
+ const pid = parsed.pid;
136
+ try {
137
+ process.kill(pid, "SIGTERM");
138
+ } catch {
139
+ /* already dead */
140
+ }
141
+ const deadline = Date.now() + KILL_GRACE_MS;
142
+ while (Date.now() < deadline && pidAlive(pid)) {
143
+ await new Promise((r) => setTimeout(r, 100));
144
+ }
145
+ if (pidAlive(pid)) {
146
+ try {
147
+ process.kill(pid, "SIGKILL");
148
+ } catch {
149
+ /* already dead */
150
+ }
151
+ }
152
+ }
153
+ for (const p of [socket, control, pidFile]) {
154
+ try {
155
+ unlinkSync(p);
156
+ } catch {
157
+ /* absent — fine */
158
+ }
159
+ }
160
+ }
161
+
162
+ async function waitForSocket(path: string, timeoutMs: number): Promise<void> {
163
+ const deadline = Date.now() + timeoutMs;
164
+ let lastError: unknown;
165
+ while (Date.now() < deadline) {
166
+ try {
167
+ await new Promise<void>((resolve, reject) => {
168
+ const sock: Socket = connect(path);
169
+ sock.once("connect", () => {
170
+ sock.destroy();
171
+ resolve();
172
+ });
173
+ sock.once("error", reject);
174
+ });
175
+ return;
176
+ } catch (e) {
177
+ lastError = e;
178
+ await new Promise((r) => setTimeout(r, PROBE_INTERVAL_MS));
179
+ }
180
+ }
181
+ throw new Error(`socket ${path} did not become ready in ${timeoutMs}ms (${String(lastError)})`);
182
+ }
183
+
184
+ export interface StartOptions {
185
+ /** Override $TACO_HOME (defaults to env / ~/.taco). */
186
+ tacoHome?: string;
187
+ /** Override the daemon runtime directory (defaults to $TACO_RUNTIME_DIR or $TACO_HOME/run). */
188
+ runtimeDir?: string;
189
+ }
190
+
191
+ /** If an upgrade marker targets this CLI's own install root, apply it.
192
+ * Best-effort: a failed apply (e.g. staging dir wiped) must not block the
193
+ * daemon from starting on the old bundle — the marker-clearing policy
194
+ * lives in upgradeApplyCommand. */
195
+ /** Resolve the resources root the daemon would use when started by this CLI.
196
+ * Mirrors `sidecarLauncher.ts::launchSidecar`'s dev/prod branch so the
197
+ * install_id we stamp on the reap check matches the id the daemon will
198
+ * stamp on its own pid file (sidecar/index.ts computes its id from
199
+ * TACO_SIDECAR_RESOURCES). Without this symmetry, standalone \`taco start\`
200
+ * (npm global) — whose own process doesn't see TACO_SIDECAR_RESOURCES —
201
+ * computed hash("") and skipped every wedged reap as ForeignInstall,
202
+ * leaving the wedged daemon alive until the next start. */
203
+ function resolveDaemonResourcesRoot(): string | undefined {
204
+ const repoRoot = (() => {
205
+ try {
206
+ // Replicate sidecarLauncher.ts:findRepoRoot's pnpm-workspace.yaml walk.
207
+ const url = new URL(import.meta.url);
208
+ let dir = path.dirname(fileURLToPath(url));
209
+ for (let i = 0; i < 8; i++) {
210
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
211
+ const parent = path.dirname(dir);
212
+ if (parent === dir) break;
213
+ dir = parent;
214
+ }
215
+ return null;
216
+ } catch {
217
+ return null;
218
+ }
219
+ })();
220
+ const useDev = repoRoot !== null && process.env.TACO_SIDECAR_DEV !== "0";
221
+ if (useDev && repoRoot) {
222
+ return join(repoRoot, "packages", "sidecar", "src");
223
+ }
224
+ // Prod: walk @taco-ai/sidecar-<platform>/ optional deps.
225
+ try {
226
+ const req = createRequire(import.meta.url);
227
+ for (const key of [
228
+ "@taco-ai/sidecar-darwin-arm64",
229
+ "@taco-ai/sidecar-darwin-x64",
230
+ "@taco-ai/sidecar-linux-arm64",
231
+ "@taco-ai/sidecar-linux-x64",
232
+ "@taco-ai/sidecar-win32-arm64",
233
+ "@taco-ai/sidecar-win32-x64",
234
+ ]) {
235
+ try {
236
+ const pkgJsonPath = req.resolve(`${key}/package.json`);
237
+ return path.dirname(pkgJsonPath);
238
+ } catch {
239
+ /* try next platform */
240
+ }
241
+ }
242
+ } catch {
243
+ /* no platform pkg installed */
244
+ }
245
+ return undefined;
246
+ }
247
+
248
+ async function applyOwnedPendingUpgrade(tacoHome: string): Promise<void> {
249
+ const marker = await readUpgradeMarker(join(tacoHome, "upgrade-marker.json"));
250
+ if (!marker) return;
251
+ if (!markerTargetsInstall(marker, findPlatformPkg()?.resources)) return;
252
+ try {
253
+ const { version } = await upgradeApplyCommand({ tacoHome });
254
+ process.stderr.write(`[taco] applied pending upgrade → ${version}\n`);
255
+ } catch (err) {
256
+ process.stderr.write(
257
+ `[taco] pending upgrade could not be applied (${String(err)}); starting existing version\n`,
258
+ );
259
+ }
260
+ }
261
+
262
+ export async function startCommand(opts: StartOptions = {}): Promise<void> {
263
+ const tacoHome = opts.tacoHome ?? TACO_HOME;
264
+ const runtimeDir = resolveTacoRuntimeDir(tacoHome, opts.runtimeDir);
265
+ await ensureDirs(tacoHome, runtimeDir);
266
+
267
+ const socket = ndjsonSocketPath(runtimeDir);
268
+ const control = controlSocketPath(runtimeDir);
269
+
270
+ // Fast path: a healthy daemon already owns this runtime directory. The desktop
271
+ // reaches `taco start` from more than one place, so this is the common
272
+ // case, not an edge case. The probe reads the NDJSON hello rather than
273
+ // touching the control socket, which is bound long before the daemon
274
+ // can serve (see probeDaemonHello).
275
+ let probe = await probeDaemonHello(socket);
276
+ if (probe === "wedged") {
277
+ // A daemon mid-initialization or serving a burst of connections can
278
+ // miss one probe. Killing on a single miss turned slow boots into a
279
+ // kill/restart loop, so re-probe once before declaring it wedged.
280
+ await new Promise((r) => setTimeout(r, 500));
281
+ probe = await probeDaemonHello(socket);
282
+ }
283
+ if (probe === "ready") {
284
+ process.stdout.write(`${socket}\n`);
285
+ process.stderr.write(`[taco] sidecar daemon already running (socket=${socket})\n`);
286
+ return;
287
+ }
288
+ if (probe === "wedged") {
289
+ // The socket answers connects but no hello arrives across two probes —
290
+ // the daemon is alive at the kernel level and dead at the application
291
+ // level. Reap it and fall through to a fresh spawn, or every launch
292
+ // from here on would attach to the same unresponsive process.
293
+ process.stderr.write(
294
+ "[taco] sidecar daemon accepts connections but does not serve; killing it\n",
295
+ );
296
+ const daemonResourcesRoot = resolveDaemonResourcesRoot();
297
+ const ownInstallId = computeInstallId(daemonResourcesRoot ?? "", tacoHome);
298
+ await killWedgedDaemon(runtimeDir, socket, control, ownInstallId);
299
+ }
300
+
301
+ // Belt-and-braces: reap any leftover pid file even when probe was
302
+ // "absent". A pid file pointing at a dead pid doesn't show up as
303
+ // "wedged" (no listener) but it does mean our subsequent spawn
304
+ // could race with cleanup. Force-reap for a deterministic baseline.
305
+ // Belt-and-braces: at this point probe is narrowed to "absent".
306
+ // A pid file pointing at a dead pid doesn't show up as "wedged" (no
307
+ // listener) but it does mean our subsequent spawn could race with
308
+ // cleanup. Force-reap for a deterministic baseline.
309
+ const daemonResourcesRoot = resolveDaemonResourcesRoot();
310
+ const ownInstallId = computeInstallId(daemonResourcesRoot ?? "", tacoHome);
311
+ await killWedgedDaemon(runtimeDir, socket, control, ownInstallId);
312
+
313
+ const lock = await acquireStartLock(runtimeDir);
314
+ if (!lock) {
315
+ // Another process is mid-spawn. Wait for its daemon rather than racing
316
+ // it to bind the same socket.
317
+ const holder = await readStartLock(`${runtimeDir}/start.lock`);
318
+ try {
319
+ await waitForSocket(socket, FOLLOWER_WAIT_MS);
320
+ } catch (err) {
321
+ throw new Error(
322
+ `another process (pid=${holder?.pid ?? "unknown"}) holds the start lock but its daemon did not become ready: ${String(err)}`,
323
+ );
324
+ }
325
+ process.stdout.write(`${socket}\n`);
326
+ process.stderr.write(`[taco] sidecar daemon started by pid=${holder?.pid ?? "unknown"}\n`);
327
+ return;
328
+ }
329
+
330
+ try {
331
+ // Apply a pending upgrade that targets THIS installation before
332
+ // spawning, so the fresh daemon boots the swapped-in bundle. The
333
+ // daemon exits itself when its orchestrator sees the marker; this is
334
+ // the apply step that completes the loop for standalone (npm)
335
+ // installs — the desktop only applies markers for its own bundled
336
+ // sidecar. Markers owned by other installations sharing $TACO_HOME
337
+ // are left untouched.
338
+ await applyOwnedPendingUpgrade(tacoHome);
339
+
340
+ const { child, dev } = launchSidecar({
341
+ socketPath: socket,
342
+ controlSocketPath: control,
343
+ tacoHome,
344
+ runtimeDir,
345
+ });
346
+
347
+ // If the bundle exits before binding the socket, surface its stderr
348
+ // (already inherited) and a clear error rather than letting the caller
349
+ // hang on the ready timeout.
350
+ const exitedEarly = new Promise<never>((_, reject) => {
351
+ child.once("exit", (code, sig) => {
352
+ reject(new Error(`sidecar exited before binding socket (code=${code} sig=${sig})`));
353
+ });
354
+ });
355
+
356
+ try {
357
+ await Promise.race([waitForSocket(socket, READY_TIMEOUT_MS), exitedEarly]);
358
+ } catch (err) {
359
+ // Detach: if the child is still alive we let it run (it might
360
+ // recover), but the caller has already failed so we surface it.
361
+ if (!child.killed) child.kill();
362
+ throw err;
363
+ }
364
+
365
+ // Detach from the child: stop forwarding signals / exit codes. The
366
+ // spawn is already detached (own process group / job object), so
367
+ // after unref the daemon fully outlives this launcher on every OS.
368
+ child.unref();
369
+
370
+ // Last line of stdout = NDJSON socket path. The Rust side parses this
371
+ // with .lines().last() — do not add trailing stdout output.
372
+ process.stdout.write(`${socket}\n`);
373
+ process.stderr.write(
374
+ `[taco] sidecar daemon started (dev=${dev}, socket=${socket}, control=${control}, tacoHome=${tacoHome})\n`,
375
+ );
376
+ } finally {
377
+ // Release on every exit path, including the early throw above —
378
+ // otherwise a failed start wedges every later attempt until the TTL.
379
+ await lock.release();
380
+ }
381
+ }