@zswarm/core 0.1.7 → 0.1.8

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.
@@ -1,4 +1,5 @@
1
1
  import type { RoutingContext } from "./routing.js";
2
+ import type { ServeTunnelManager } from "./serve-tunnel.js";
2
3
  export type OpsResult = ({
3
4
  ok: true;
4
5
  data: unknown;
@@ -25,6 +26,54 @@ export type DispatchDeps = {
25
26
  env?: NodeJS.ProcessEnv;
26
27
  /** MCP cancellation; aborted waits stop instead of running to timeout. */
27
28
  signal?: AbortSignal;
29
+ /** Process-owned ssh:// LocalForward manager. CLI disposes; MCP reuses. */
30
+ serveTunnels?: ServeTunnelManager;
31
+ /**
32
+ * Test seam for optional Tailscale `status --json`. Default runs the
33
+ * `tailscale` CLI with a bounded timeout and output cap.
34
+ * Used by doctor (peer mapping) and by serve bind verification.
35
+ */
36
+ tailscaleStatus?: (input: {
37
+ timeoutMs: number;
38
+ signal?: AbortSignal;
39
+ env: NodeJS.ProcessEnv;
40
+ }) => Promise<{
41
+ code: number;
42
+ stdout: string;
43
+ stderr: string;
44
+ }>;
45
+ /** Test seam for OS interface address ownership during Tailscale serve bind. */
46
+ networkInterfaces?: () => NodeJS.Dict<import("node:os").NetworkInterfaceInfo[]>;
47
+ /** Narrow injectables for Windows `serve --install` / `--clear`. */
48
+ serveInstall?: ServeInstallDeps;
49
+ };
50
+ export type ServePowerShellResult = {
51
+ code: number;
52
+ stdout: string;
53
+ stderr: string;
54
+ aborted?: boolean;
55
+ timedOut?: boolean;
56
+ };
57
+ export type ServeInstallDeps = {
58
+ platform?: NodeJS.Platform;
59
+ runPowerShell?: (script: string, options: {
60
+ timeoutMs: number;
61
+ signal?: AbortSignal;
62
+ }) => Promise<ServePowerShellResult>;
63
+ probeServe?: (target: string, options?: {
64
+ token?: string;
65
+ timeoutMs?: number;
66
+ signal?: AbortSignal;
67
+ }) => Promise<OpsResult>;
68
+ callServe?: (target: string, args: Record<string, unknown>, options: {
69
+ timeoutMs: number;
70
+ token?: string;
71
+ signal?: AbortSignal;
72
+ }) => Promise<OpsResult>;
73
+ execPath?: string;
74
+ scriptPath?: string;
75
+ argv?: string[];
76
+ launchId?: string;
28
77
  };
29
78
  export type Clock = {
30
79
  now: () => number;
package/dist/ops/util.js CHANGED
@@ -5,7 +5,14 @@ export const DEFAULT_DUMP_MAX_CHARS = 8_000;
5
5
  export const DEFAULT_WAIT_MAX_CHARS = 2_000;
6
6
  export function fail(err) {
7
7
  if (err instanceof ZellijError) {
8
- return { ok: false, error: { code: err.code, message: err.message } };
8
+ return {
9
+ ok: false,
10
+ error: {
11
+ code: err.code,
12
+ message: err.message,
13
+ ...(err.details ? { details: err.details } : {}),
14
+ },
15
+ };
9
16
  }
10
17
  const message = err instanceof Error ? err.message : String(err);
11
18
  return { ok: false, error: { code: "failed", message } };
package/dist/schema.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * One description of the zswarm surface. The MCP tool schema, the CLI flags,
3
3
  * and the CLI help text are all generated from it, so they cannot drift apart.
4
4
  */
5
- export declare const OP_NAMES: readonly ["list", "sessions", "send", "broadcast", "dump", "tail", "wait", "status", "keys", "interrupt", "spawn", "close", "worktrees", "unworktree", "signal", "signals", "await", "log", "rename", "focus", "tabs", "layout", "stack", "diff", "checkpoint", "bus", "serve"];
5
+ export declare const OP_NAMES: readonly ["list", "sessions", "send", "broadcast", "dump", "tail", "wait", "status", "keys", "interrupt", "spawn", "close", "worktrees", "unworktree", "signal", "signals", "await", "log", "rename", "focus", "tabs", "layout", "stack", "diff", "checkpoint", "bus", "serve", "doctor"];
6
6
  export type OpName = (typeof OP_NAMES)[number];
7
7
  /** Ops that address an existing pane through `to`. */
8
8
  export declare const TARGET_OPS: readonly OpName[];
package/dist/schema.js CHANGED
@@ -31,6 +31,7 @@ export const OP_NAMES = [
31
31
  "checkpoint",
32
32
  "bus",
33
33
  "serve",
34
+ "doctor",
34
35
  ];
35
36
  /** Ops that address an existing pane through `to`. */
36
37
  export const TARGET_OPS = [
@@ -51,7 +52,7 @@ export const PARAMS = [
51
52
  name: "session",
52
53
  type: "string",
53
54
  flags: ["--session", "-s"],
54
- description: "Zellij session name (optional if sole live session or ZSWARM_SESSION / ZELLIJ_SESSION_NAME)",
55
+ description: "Zellij session name (optional if sole live session or ZSWARM_SESSION / ZELLIJ_SESSION_NAME). serve --install: readiness target only — does not change the task's default routing",
55
56
  },
56
57
  {
57
58
  name: "to",
@@ -111,13 +112,13 @@ export const PARAMS = [
111
112
  name: "clear",
112
113
  type: "boolean",
113
114
  flags: ["--clear"],
114
- description: "signal: reset the channel (all channels when none is given); bus: forget the installed plugin; serve: unregister the Windows logon task",
115
+ description: "signal: reset the channel (all channels when none is given); bus: forget the installed plugin; serve: stop and unregister the owned Windows zswarm-serve logon task if present",
115
116
  },
116
117
  {
117
118
  name: "install",
118
119
  type: "boolean",
119
120
  flags: ["--install"],
120
- description: "bus: load the event-bus plugin in a pane so its permission prompt can be answered, then remember it; serve: register a Windows logon task that listens for remote zswarm",
121
+ description: "bus: load the event-bus plugin in a pane so its permission prompt can be answered, then remember it; serve: register the current-user Windows Interactive logon task and wait for authenticated hello plus host session visibility",
121
122
  },
122
123
  {
123
124
  name: "reset",
@@ -147,7 +148,7 @@ export const PARAMS = [
147
148
  name: "serveAddress",
148
149
  type: "string",
149
150
  flags: ["--serve"],
150
- description: "use an existing serve endpoint (e.g. 127.0.0.1:9419 through an SSH tunnel); preferred for frequent status calls; uses ZSWARM_SERVE_TOKEN",
151
+ description: "existing serve endpoint: host:port, tcp://host:port, or ssh://user@host[:sshPort]?servePort=9419. ssh:// opens a process-owned SSH LocalForward and probes hello before ops (desktop serve must already be running). Omit sshPort to use ssh_config Port. tcp:// also names a private Tailscale Serve frontend over loopback (docs/tailscale.md). Uses ZSWARM_SERVE_TOKEN",
151
152
  },
152
153
  {
153
154
  name: "limit",
@@ -257,7 +258,7 @@ export const PARAMS = [
257
258
  name: "timeoutMs",
258
259
  type: "number",
259
260
  flags: ["--timeout-ms"],
260
- description: "wait: timeout (default 60000); status/spawn: overall deadline (default 30000), including setup and observation",
261
+ description: "wait: timeout (default 60000); status/spawn: overall deadline (default 30000); doctor: overall deadline (default 10000), including Tailscale/SSH/hello/host checks; serve --install: overall install/readiness deadline (default 30000)",
261
262
  },
262
263
  {
263
264
  name: "keys",
@@ -434,7 +435,7 @@ export const PARAMS = [
434
435
  name: "listen",
435
436
  type: "string",
436
437
  flags: ["--listen"],
437
- description: "serve: bind address (default 127.0.0.1:9419). Reach it from another machine with ZSWARM_SERVE after an SSH tunnel",
438
+ description: "serve: bind address (default 127.0.0.1:9419). Loopback needs no Tailscale; a non-loopback literal must be a verified local Tailscale IP (see docs/tailscale.md). Reach via ZSWARM_SERVE / --serve (direct host:port, private Tailscale Serve tcp:// frontend, or ssh:// to remote loopback)",
438
439
  },
439
440
  {
440
441
  name: "verbose",
@@ -495,7 +496,7 @@ export function cliUsage() {
495
496
  const value = param.type === "boolean" ? "" : param.type === "number" ? " N" : " VALUE";
496
497
  lines.push(` ${param.flags.join(", ").padEnd(28)}${value.trim().padEnd(6)}${param.description}`);
497
498
  }
498
- lines.push("", "Guards: writes refuse zswarm's own pane (--allow-self) and exited panes (--force). --expect requires the screen to contain a substring first.", "Bus: `zswarm bus --install` once per Zellij session. `--force` closes orphan bus panes and reloads; do not use it as a retry.", "Remote: ZSWARM_SSH (+ ZSWARM_TMP=auto or ZSWARM_SSH_MODE=interactive on Windows). Or run `zswarm serve --listen` next to Zellij and set ZSWARM_SERVE (+ ZSWARM_SERVE_TOKEN). Serve binds loopback only and always requires a token.", "Env: ZSWARM_BIN, ZSWARM_PATH, ZSWARM_SESSION, ZSWARM_SELF_PANE, ZSWARM_FROM, ZELLIJ_PANE_ID, ZELLIJ_SESSION_NAME, ZSWARM_BUS, ZSWARM_BUS_PLUGIN, ZSWARM_SSH, ZSWARM_TMP, ZSWARM_SSH_MODE, ZSWARM_SERVE, ZSWARM_SERVE_TOKEN, ZSWARM_CACHE_TTL_MS", "");
499
+ lines.push("", "Guards: writes refuse zswarm's own pane (--allow-self) and exited panes (--force). --expect requires the screen to contain a substring first.", "Bus: `zswarm bus --install` once per Zellij session. `--force` closes orphan bus panes and reloads; do not use it as a retry.", "Remote: ZSWARM_SSH (+ ZSWARM_TMP=auto or ZSWARM_SSH_MODE=interactive on Windows). Or run `zswarm serve --listen` next to Zellij and set ZSWARM_SERVE / --serve (host:port, tcp://, or ssh://user@host?servePort=9419) plus ZSWARM_SERVE_TOKEN. Serve defaults to loopback and always requires a token; an explicit local Tailscale IP is allowed only after host verification. Private raw TCP Tailscale Serve keeps the backend on 127.0.0.1 behind `tailscale serve --tcp=…` (docs/tailscale.md). ssh:// does not start remote serve. Windows default recipe: `zswarm serve --install` (verified readiness).", "Doctor: `zswarm doctor --session crew` inspects local, --ssh, and --serve routes without installs, pane changes, or plugin launch. See docs/doctor.md and docs/tailscale.md.", "Env: ZSWARM_BIN, ZSWARM_PATH, ZSWARM_SESSION, ZSWARM_SELF_PANE, ZSWARM_FROM, ZELLIJ_PANE_ID, ZELLIJ_SESSION_NAME, ZSWARM_BUS, ZSWARM_BUS_PLUGIN, ZSWARM_SSH, ZSWARM_SSH_BIN, ZSWARM_SSH_OPTS, ZSWARM_TMP, ZSWARM_SSH_MODE, ZSWARM_SERVE, ZSWARM_SERVE_TOKEN, ZSWARM_TAILSCALE_BIN, ZSWARM_CACHE_TTL_MS", "");
499
500
  return lines.join("\n");
500
501
  }
501
502
  /** Turn argv (without the op) into dispatch args, driven by PARAMS. */
package/dist/state.js CHANGED
@@ -1,4 +1,4 @@
1
- import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  const LOG_FILE = "log.jsonl";
@@ -9,9 +9,13 @@ const CURSORS_LOCK = "cursors.lock";
9
9
  const BUS_FILE = "bus.json";
10
10
  /** Keeps the log bounded without needing a rotation daemon. */
11
11
  const LOG_TAIL_BYTES = 512 * 1024;
12
+ /** Bound for waiting on a *live* lock holder before failing. */
12
13
  const LOCK_WAIT_MS = 5_000;
13
- /** A live pid older than this is treated as a recycle of a crashed holder. */
14
- const LOCK_STALE_MS = 30_000;
14
+ /**
15
+ * Fresh empty/malformed lock files this young are treated as an in-flight
16
+ * exclusive create (wait), not as abandoned debris (refuse).
17
+ */
18
+ const LOCK_PENDING_MS = LOCK_WAIT_MS;
15
19
  function sleepSync(ms) {
16
20
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
17
21
  }
@@ -103,32 +107,6 @@ export function createStateStore(options = {}) {
103
107
  return null;
104
108
  }
105
109
  }
106
- /**
107
- * Dead pid → steal now. This process's own leftover (unlink failed, or a
108
- * non-reentrant re-entry) → steal now. A live pid whose `at` is older than
109
- * LOCK_STALE_MS is a recycled pid, not a holder still inside fn().
110
- * Empty leftover from older writers (wx with no owner bytes) → steal once
111
- * mtime is older than the wait, so an in-flight create is not yanked out
112
- * from under the holder.
113
- * Owner is read once: a second read can see a pid that appeared after an
114
- * empty snapshot and would steal a live lock.
115
- */
116
- function lockIsStale(lockPath) {
117
- const owner = readLockOwner(lockPath);
118
- if (owner) {
119
- if (owner.pid === process.pid)
120
- return true;
121
- if (!pidAlive(owner.pid))
122
- return true;
123
- return Date.now() - owner.at >= LOCK_STALE_MS;
124
- }
125
- try {
126
- return Date.now() - statSync(lockPath).mtimeMs >= LOCK_WAIT_MS;
127
- }
128
- catch {
129
- return false;
130
- }
131
- }
132
110
  function lockBusy(code) {
133
111
  // Unix: O_EXCL on an existing file is EEXIST. Windows: a holder that still
134
112
  // has the handle open (or a delete-pending name) is EPERM / EACCES / EBUSY.
@@ -137,43 +115,185 @@ export function createStateStore(options = {}) {
137
115
  code === "EACCES" ||
138
116
  code === "EBUSY");
139
117
  }
140
- function unlinkLock(lockPath) {
118
+ /**
119
+ * Cursor/signal locks: exclusive create (`wx`) + owner stamp; release by
120
+ * generation-matched unlink of the stamp this process published.
121
+ *
122
+ * Foreign / abandoned / empty-old lock files are NOT auto-reclaimed.
123
+ * Portable check-then-rename/unlink reclaim can move a live holder's shared
124
+ * name aside and admit another writer into that critical section (demonstrated
125
+ * with real cooperating writeCursor processes). Prefer bounded fail-closed
126
+ * refusal over unsafe automatic recovery.
127
+ *
128
+ * A dead-looking owner observation is only refused when that same generation
129
+ * is still present. If normal release removed the path or another writer
130
+ * published a new generation between observation and the liveness check,
131
+ * contenders retry exclusive create within the original LOCK_WAIT_MS budget
132
+ * (generation churn does not reset the deadline).
133
+ *
134
+ * Self-pid leftovers (same process, prior unlink failed) may be removed when
135
+ * the on-disk generation still matches — this process is not inside `fn()`.
136
+ *
137
+ * Operator recovery: if acquisition refuses an abandoned lock, confirm the
138
+ * recorded pid is gone and no writer holds the file, then remove the lock
139
+ * path manually and retry.
140
+ */
141
+ function unlinkIfMatchingOwner(lockPath, expected) {
141
142
  const until = Date.now() + 500;
142
143
  while (true) {
144
+ const current = readLockOwner(lockPath);
145
+ if (!current ||
146
+ current.pid !== expected.pid ||
147
+ current.at !== expected.at) {
148
+ return false;
149
+ }
143
150
  try {
144
151
  rmSync(lockPath, { force: true });
145
- return;
152
+ return true;
146
153
  }
147
154
  catch (err) {
148
155
  if (!lockBusy(err.code) || Date.now() >= until) {
149
- return;
156
+ return false;
150
157
  }
151
158
  sleepSync(10);
152
159
  }
153
160
  }
154
161
  }
162
+ /** Only this process may clear its own leftover generation. */
163
+ function tryReclaimSelfLock(lockPath) {
164
+ const owner = readLockOwner(lockPath);
165
+ if (!owner || owner.pid !== process.pid)
166
+ return false;
167
+ return unlinkIfMatchingOwner(lockPath, owner);
168
+ }
169
+ function abandonedLockError(lockName, lockPath, observed) {
170
+ // Use the generation that justified refusal — do not re-read the path and
171
+ // accidentally describe a live successor as needing operator recovery.
172
+ if (observed) {
173
+ return new Error(`refusing automatic reclaim of ${lockName} (dead-or-abandoned owner pid=${observed.pid} at=${observed.at}); ` +
174
+ `remove ${lockPath} only after confirming that process is gone and no writer holds the file, then retry`);
175
+ }
176
+ return new Error(`refusing automatic reclaim of ${lockName} (empty or malformed lock without a safe owner record); ` +
177
+ `remove ${lockPath} only when no writer is using it, then retry`);
178
+ }
179
+ /**
180
+ * Classify a blocking lock against the *current* generation.
181
+ *
182
+ * `wait` = live holder or fresh in-flight create.
183
+ * `refuse` = unchanged abandoned foreign/empty debris — fail closed.
184
+ * `self` = reclaimable same-pid leftover.
185
+ * `retry` = observation went stale during the check (normal release removed
186
+ * the path, or a new generation superseded the departed owner). Contender
187
+ * must retry exclusive create within the original wait budget — not refuse
188
+ * a lock that is no longer abandoned, and not unlink/rename anything.
189
+ */
190
+ function classifyBlockingLock(lockPath) {
191
+ const owner = readLockOwner(lockPath);
192
+ if (owner) {
193
+ if (owner.pid === process.pid)
194
+ return { kind: "self", observed: owner };
195
+ if (pidAlive(owner.pid))
196
+ return { kind: "wait", observed: owner };
197
+ // Dead-looking foreign owner: only refuse if THIS generation is still
198
+ // current. Normal release+exit between read and liveness check leaves
199
+ // the path absent or replaced by a live successor — that is not
200
+ // abandoned debris.
201
+ const still = readLockOwner(lockPath);
202
+ if (!still)
203
+ return { kind: "retry", observed: null };
204
+ if (still.pid !== owner.pid || still.at !== owner.at) {
205
+ return { kind: "retry", observed: still };
206
+ }
207
+ return { kind: "refuse", observed: owner };
208
+ }
209
+ try {
210
+ if (Date.now() - statSync(lockPath).mtimeMs < LOCK_PENDING_MS) {
211
+ return { kind: "wait", observed: null };
212
+ }
213
+ }
214
+ catch {
215
+ // Path disappeared between the busy create and this check.
216
+ return { kind: "retry", observed: null };
217
+ }
218
+ // Old empty/malformed: confirm it is still present and still ownerless
219
+ // before refusing — a successor may have published while we inspected.
220
+ const again = readLockOwner(lockPath);
221
+ if (again) {
222
+ if (again.pid === process.pid)
223
+ return { kind: "self", observed: again };
224
+ if (pidAlive(again.pid))
225
+ return { kind: "wait", observed: again };
226
+ const confirm = readLockOwner(lockPath);
227
+ if (!confirm)
228
+ return { kind: "retry", observed: null };
229
+ if (confirm.pid !== again.pid || confirm.at !== again.at) {
230
+ return { kind: "retry", observed: confirm };
231
+ }
232
+ return { kind: "refuse", observed: again };
233
+ }
234
+ try {
235
+ statSync(lockPath);
236
+ }
237
+ catch {
238
+ return { kind: "retry", observed: null };
239
+ }
240
+ return { kind: "refuse", observed: null };
241
+ }
242
+ /**
243
+ * Drop this process's lock only when the generation we published is still at
244
+ * the well-known path. Under fail-closed foreign reclaim, generations are not
245
+ * stolen while we hold the critical section, so a matching unlink cannot
246
+ * remove a successor published by another cooperating writer.
247
+ */
248
+ function unlinkOwnedLock(lockPath, stamp) {
249
+ unlinkIfMatchingOwner(lockPath, stamp);
250
+ }
155
251
  function withFileLock(lockName, fn) {
156
252
  ensureDir();
157
253
  const lockPath = join(dir, lockName);
158
254
  const deadline = Date.now() + LOCK_WAIT_MS;
159
255
  while (true) {
256
+ const stamp = { pid: process.pid, at: Date.now() };
160
257
  try {
161
- const fd = openSync(lockPath, "wx");
258
+ // Exclusive create (`wx`) plus a write of the owner record. That is
259
+ // not one atomic publish of populated bytes — create and write still
260
+ // have an interval. The UTF-8 fast path keeps that interval in one
261
+ // native writeFileSync rather than two JS turns (openSync then write).
262
+ // Abandoned foreign/empty locks are refused (not renamed or unlinked).
263
+ writeFileSync(lockPath, JSON.stringify(stamp), {
264
+ encoding: "utf8",
265
+ flag: "wx",
266
+ });
162
267
  try {
163
- writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
164
268
  return fn();
165
269
  }
166
270
  finally {
167
- closeSync(fd);
168
- unlinkLock(lockPath);
271
+ unlinkOwnedLock(lockPath, stamp);
169
272
  }
170
273
  }
171
274
  catch (err) {
172
275
  const code = err.code;
173
276
  if (!lockBusy(code))
174
277
  throw err;
175
- if (lockIsStale(lockPath)) {
176
- unlinkLock(lockPath);
278
+ if (tryReclaimSelfLock(lockPath)) {
279
+ continue;
280
+ }
281
+ const { kind, observed } = classifyBlockingLock(lockPath);
282
+ if (kind === "self") {
283
+ if (tryReclaimSelfLock(lockPath))
284
+ continue;
285
+ }
286
+ if (kind === "refuse") {
287
+ throw abandonedLockError(lockName, lockPath, observed);
288
+ }
289
+ if (kind === "retry") {
290
+ // Observation changed (released or superseded). Retry exclusive
291
+ // create within the original budget — do not reset the deadline on
292
+ // generation churn (unbounded handoffs become a timeout).
293
+ if (Date.now() >= deadline) {
294
+ throw new Error(`timed out waiting for ${lockName}`);
295
+ }
296
+ sleepSync(10);
177
297
  continue;
178
298
  }
179
299
  if (Date.now() >= deadline) {
@@ -1,9 +1,16 @@
1
+ import { ZellijError } from "../errors.js";
1
2
  import { createSshExec, NOT_FOUND_EXIT, type ExecFn, type ExecResult, type SshTarget } from "../exec.js";
2
3
  export { createSshExec, type SshTarget };
3
4
  export type ZellijExecResult = ExecResult;
4
5
  export type ZellijExecFn = ExecFn;
6
+ /** Where a missing/wrong-Zellij failure was produced. */
7
+ export type ZellijFailureOrigin = "local_spawn" | "local_preflight" | "remote";
5
8
  export declare const DEFAULT_TIMEOUT_MS = 15000;
6
9
  export { NOT_FOUND_EXIT };
10
+ /** Local Node spawn failure vs a process that actually started. */
11
+ export declare function originFromExecResult(result: ExecResult): Exclude<ZellijFailureOrigin, "local_preflight">;
12
+ export declare function zellijExecDetails(result: ExecResult): Record<string, unknown>;
13
+ export declare function zellijMissingError(zellijPath: string, result: ExecResult): ZellijError;
7
14
  /** Expand a leading `~/` or `~\` using USERPROFILE/HOME. */
8
15
  export declare function expandHomePath(input: string, env?: NodeJS.ProcessEnv): string;
9
16
  /**
@@ -7,6 +7,19 @@ import { applyIpcTmpEnv } from "./ipc.js";
7
7
  export { createSshExec };
8
8
  export const DEFAULT_TIMEOUT_MS = 15_000;
9
9
  export { NOT_FOUND_EXIT };
10
+ /** Local Node spawn failure vs a process that actually started. */
11
+ export function originFromExecResult(result) {
12
+ return result.spawn?.origin === "local" ? "local_spawn" : "remote";
13
+ }
14
+ export function zellijExecDetails(result) {
15
+ const origin = originFromExecResult(result);
16
+ return result.spawn
17
+ ? { origin, spawn: { origin: result.spawn.origin, errno: result.spawn.errno, bin: result.spawn.bin } }
18
+ : { origin };
19
+ }
20
+ export function zellijMissingError(zellijPath, result) {
21
+ return new ZellijError("zellij_missing", `zellij binary not found (${zellijPath}); install Zellij ≥ 0.42, add it to PATH, or set ZSWARM_BIN / ZSWARM_PATH`, zellijExecDetails(result));
22
+ }
10
23
  /** Expand a leading `~/` or `~\` using USERPROFILE/HOME. */
11
24
  export function expandHomePath(input, env = process.env) {
12
25
  const trimmed = input.trim();
@@ -51,7 +64,7 @@ export function looksLikeZswarmBinary(path) {
51
64
  export function assertZellijBinaryPath(path) {
52
65
  if (!looksLikeZswarmBinary(path))
53
66
  return;
54
- throw new ZellijError("zellij_wrong_bin", `ZSWARM_BIN/ZSWARM_PATH points at zswarm (${path}), not Zellij. Set it to the zellij binary (e.g. ~/.local/bin/zellij)`);
67
+ throw new ZellijError("zellij_wrong_bin", `ZSWARM_BIN/ZSWARM_PATH points at zswarm (${path}), not Zellij. Set it to the zellij binary (e.g. ~/.local/bin/zellij)`, { origin: "local_preflight", bin: path });
55
68
  }
56
69
  /**
57
70
  * ZSWARM_SSH is a destination, not a full ssh argv.
@@ -127,10 +140,10 @@ export async function ensureZellijIdentity(exec, zellijPath, timeoutMs = 3_000,
127
140
  });
128
141
  const text = `${result.stdout}\n${result.stderr}`;
129
142
  if (/usage:\s*zswarm/i.test(text) || /unknown arg:/i.test(text)) {
130
- throw new ZellijError("zellij_wrong_bin", `resolved binary is zswarm, not Zellij (${zellijPath}). Set ZSWARM_BIN to the zellij executable`);
143
+ throw new ZellijError("zellij_wrong_bin", `resolved binary is zswarm, not Zellij (${zellijPath}). Set ZSWARM_BIN to the zellij executable`, zellijExecDetails(result));
131
144
  }
132
145
  if (result.code === NOT_FOUND_EXIT) {
133
- throw new ZellijError("zellij_missing", `zellij binary not found (${zellijPath}); install Zellij ≥ 0.42, add it to PATH, or set ZSWARM_BIN / ZSWARM_PATH`);
146
+ throw zellijMissingError(zellijPath, result);
134
147
  }
135
148
  if (result.code === 0) {
136
149
  if (signal?.aborted)
@@ -139,7 +152,7 @@ export async function ensureZellijIdentity(exec, zellijPath, timeoutMs = 3_000,
139
152
  identityCache.add(cacheKey);
140
153
  return true;
141
154
  }
142
- throw new ZellijError("zellij_wrong_bin", `resolved binary is not Zellij (${zellijPath}); --version returned: ${result.stdout.trim() || result.stderr.trim() || "empty"}`);
155
+ throw new ZellijError("zellij_wrong_bin", `resolved binary is not Zellij (${zellijPath}); --version returned: ${result.stdout.trim() || result.stderr.trim() || "empty"}`, zellijExecDetails(result));
143
156
  }
144
157
  // Timeout / transport failure: leave unresolved so a later call retries.
145
158
  return false;
@@ -161,10 +174,10 @@ export async function ensureZellijCapabilities(exec, zellijPath, timeoutMs = 3_0
161
174
  });
162
175
  const text = `${result.stdout}\n${result.stderr}`;
163
176
  if (/usage:\s*zswarm/i.test(text)) {
164
- throw new ZellijError("zellij_wrong_bin", `resolved binary is zswarm, not Zellij (${zellijPath})`);
177
+ throw new ZellijError("zellij_wrong_bin", `resolved binary is zswarm, not Zellij (${zellijPath})`, zellijExecDetails(result));
165
178
  }
166
179
  if (result.code === NOT_FOUND_EXIT) {
167
- throw new ZellijError("zellij_missing", `zellij binary not found (${zellijPath})`);
180
+ throw zellijMissingError(zellijPath, result);
168
181
  }
169
182
  // Require the flags this client always passes.
170
183
  if (result.code === 0 &&
@@ -176,7 +189,7 @@ export async function ensureZellijCapabilities(exec, zellijPath, timeoutMs = 3_0
176
189
  return true;
177
190
  }
178
191
  if (result.code === 0) {
179
- throw new ZellijError("zellij_incompatible", `Zellij at ${zellijPath} does not advertise list-sessions --no-formatting; upgrade Zellij (≥ 0.42) or zswarm`);
192
+ throw new ZellijError("zellij_incompatible", `Zellij at ${zellijPath} does not advertise list-sessions --no-formatting; upgrade Zellij (≥ 0.42) or zswarm`, zellijExecDetails(result));
180
193
  }
181
194
  // Soft: leave unresolved on transport failure.
182
195
  return false;
@@ -4,7 +4,7 @@ import { buildClosePaneArgs, buildDumpArgs, buildDumpLayoutArgs, buildFocusPaneA
4
4
  import { DEFAULT_BUS_TIMEOUT_MS, parseBusReply, parseChangedReply, parseScrollbackReply, parseWaitReply, } from "./bus.js";
5
5
  import { parseTabList, resolveTab } from "./tabs.js";
6
6
  import { createSshExec } from "../exec.js";
7
- import { DEFAULT_TIMEOUT_MS, NOT_FOUND_EXIT, defaultExec, ensureZellijProbes, identityCacheKey, resolveSshTarget, resolveZellijBinary, sanitizeZellijEnv, } from "./binary.js";
7
+ import { DEFAULT_TIMEOUT_MS, NOT_FOUND_EXIT, defaultExec, ensureZellijProbes, identityCacheKey, resolveSshTarget, resolveZellijBinary, sanitizeZellijEnv, zellijExecDetails, zellijMissingError, } from "./binary.js";
8
8
  import { normalizePaneId, parsePaneList, resolvePane, } from "./panes.js";
9
9
  import { isZellijNoSessionsOutput, parseSessionList, resolveSelfPaneId, sessionFromEnv, sessionFromList, } from "./session.js";
10
10
  /** Zellij wrapper with bounded caches of completed discovery observations. */
@@ -119,14 +119,14 @@ export function createZellijClient(options = {}) {
119
119
  await ensureIdentity(remaining);
120
120
  const result = await exec(args, { timeoutMs: remaining() });
121
121
  if (result.code === NOT_FOUND_EXIT) {
122
- throw new ZellijError("zellij_missing", `zellij binary not found (${zellijPath}); install Zellij ≥ 0.42, add it to PATH, or set ZSWARM_BIN / ZSWARM_PATH`);
122
+ throw zellijMissingError(zellijPath, result);
123
123
  }
124
124
  if (result.code !== 0) {
125
125
  const detail = result.stderr.trim() || result.stdout.trim() || "no output";
126
126
  if (/usage:\s*zswarm/i.test(detail) || /unknown arg:/i.test(detail)) {
127
- throw new ZellijError("zellij_wrong_bin", `resolved binary looks like zswarm, not Zellij (${zellijPath}): ${detail}`);
127
+ throw new ZellijError("zellij_wrong_bin", `resolved binary looks like zswarm, not Zellij (${zellijPath}): ${detail}`, zellijExecDetails(result));
128
128
  }
129
- throw new ZellijError("zellij_failed", `${label} failed (exit ${result.code}): ${detail}`);
129
+ throw new ZellijError("zellij_failed", `${label} failed (exit ${result.code}): ${detail}`, zellijExecDetails(result));
130
130
  }
131
131
  return result;
132
132
  }
@@ -159,16 +159,16 @@ export function createZellijClient(options = {}) {
159
159
  timeoutMs: remaining(),
160
160
  });
161
161
  if (result.code === NOT_FOUND_EXIT) {
162
- throw new ZellijError("zellij_missing", `zellij binary not found (${zellijPath}); install Zellij ≥ 0.42, add it to PATH, or set ZSWARM_BIN / ZSWARM_PATH`);
162
+ throw zellijMissingError(zellijPath, result);
163
163
  }
164
164
  if (result.code !== 0) {
165
165
  const detail = result.stderr.trim() || result.stdout.trim() || "no output";
166
166
  if (/usage:\s*zswarm/i.test(detail) || /unknown arg:/i.test(detail)) {
167
- throw new ZellijError("zellij_wrong_bin", `resolved binary looks like zswarm, not Zellij (${zellijPath}): ${detail}`);
167
+ throw new ZellijError("zellij_wrong_bin", `resolved binary looks like zswarm, not Zellij (${zellijPath}): ${detail}`, zellijExecDetails(result));
168
168
  }
169
169
  if (isZellijNoSessionsOutput(result.stdout, result.stderr))
170
170
  return [];
171
- throw new ZellijError("zellij_failed", `zellij list-sessions failed (exit ${result.code}): ${detail}`);
171
+ throw new ZellijError("zellij_failed", `zellij list-sessions failed (exit ${result.code}): ${detail}`, zellijExecDetails(result));
172
172
  }
173
173
  return parseSessionList(result.stdout);
174
174
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zswarm/core",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "description": "zSwarm Zellij client and shared ops dispatch",
6
6
  "exports": {