agent-director 0.6.3 → 0.7.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.
package/dist/index.js CHANGED
@@ -14,20 +14,16 @@ var __export = (target, all) => {
14
14
  });
15
15
  };
16
16
 
17
- // src/internal/subprocessClient.ts
18
- import { readFile } from "fs/promises";
19
-
20
- // src/internal/platformResolve.ts
21
- import { statSync } from "fs";
22
- import { fileURLToPath } from "url";
23
- import { join, dirname } from "path";
17
+ // src/internal/discovery.ts
18
+ import { statSync, realpathSync, accessSync, constants as fsConstants } from "fs";
19
+ import { resolve, isAbsolute, join, dirname } from "path";
20
+ import { delimiter } from "path";
24
21
 
25
22
  // src/errors.ts
26
23
  var exports_errors = {};
27
24
  __export(exports_errors, {
28
25
  errorFromEnvelope: () => errorFromEnvelope,
29
26
  TS_ONLY_ERROR_NAMES: () => TS_ONLY_ERROR_NAMES,
30
- ErrUnsupportedPlatform: () => ErrUnsupportedPlatform,
31
27
  ErrUnknownErrorName: () => ErrUnknownErrorName,
32
28
  ErrTmuxSessionNameTooLong: () => ErrTmuxSessionNameTooLong,
33
29
  ErrTmuxSessionNameInvalid: () => ErrTmuxSessionNameInvalid,
@@ -40,6 +36,9 @@ __export(exports_errors, {
40
36
  ErrTemplateNameUnsafe: () => ErrTemplateNameUnsafe,
41
37
  ErrTemplateMalformed: () => ErrTemplateMalformed,
42
38
  ErrTemplateExists: () => ErrTemplateExists,
39
+ ErrSystemInstallUnreachable: () => ErrSystemInstallUnreachable,
40
+ ErrSystemInstallTooOld: () => ErrSystemInstallTooOld,
41
+ ErrSystemInstallNotFound: () => ErrSystemInstallNotFound,
43
42
  ErrSpawnNotResumable: () => ErrSpawnNotResumable,
44
43
  ErrSpawnNotPausable: () => ErrSpawnNotPausable,
45
44
  ErrSpawnNotInteractive: () => ErrSpawnNotInteractive,
@@ -50,7 +49,6 @@ __export(exports_errors, {
50
49
  ErrRelayModeOff: () => ErrRelayModeOff,
51
50
  ErrRelayModeInvalid: () => ErrRelayModeInvalid,
52
51
  ErrProbeUnsupported: () => ErrProbeUnsupported,
53
- ErrPlatformPackageMissing: () => ErrPlatformPackageMissing,
54
52
  ErrPermissionRequestNotFound: () => ErrPermissionRequestNotFound,
55
53
  ErrPauseTimeout: () => ErrPauseTimeout,
56
54
  ErrNoSessionId: () => ErrNoSessionId,
@@ -67,7 +65,6 @@ __export(exports_errors, {
67
65
  ErrCwdMissing: () => ErrCwdMissing,
68
66
  ErrConsumerSignal: () => ErrConsumerSignal,
69
67
  ErrClientClosed: () => ErrClientClosed,
70
- ErrCliNotExecutable: () => ErrCliNotExecutable,
71
68
  ErrCallTimeout: () => ErrCallTimeout,
72
69
  ErrBunVersionTooOld: () => ErrBunVersionTooOld,
73
70
  ErrAmbiguousRequest: () => ErrAmbiguousRequest,
@@ -78,13 +75,13 @@ __export(exports_errors, {
78
75
  // src/internal/tsOnlyErrors.ts
79
76
  var TS_ONLY_ERROR_NAMES = [
80
77
  "ErrClientClosed",
81
- "ErrUnsupportedPlatform",
82
- "ErrPlatformPackageMissing",
83
78
  "ErrBunVersionTooOld",
84
- "ErrCliNotExecutable",
85
79
  "ErrConsumerSignal",
86
80
  "ErrCallTimeout",
87
- "ErrUnknownErrorName"
81
+ "ErrUnknownErrorName",
82
+ "ErrSystemInstallNotFound",
83
+ "ErrSystemInstallTooOld",
84
+ "ErrSystemInstallUnreachable"
88
85
  ];
89
86
 
90
87
  // src/errors.ts
@@ -110,23 +107,6 @@ class ErrClientClosed extends AgentDirectorError {
110
107
  }
111
108
  }
112
109
 
113
- class ErrUnsupportedPlatform extends AgentDirectorError {
114
- constructor(tuple) {
115
- super("", "ErrUnsupportedPlatform", `platform/arch tuple "${tuple}" is not supported; supported: linux-x64, darwin-arm64`);
116
- this.name = "ErrUnsupportedPlatform";
117
- Object.setPrototypeOf(this, new.target.prototype);
118
- }
119
- }
120
-
121
- class ErrPlatformPackageMissing extends AgentDirectorError {
122
- constructor(pkgName, detail) {
123
- const desc = detail ? `native sub-package "${pkgName}" is not usable: ${detail}` : `native sub-package "${pkgName}" is not installed or its binary is absent`;
124
- super("", "ErrPlatformPackageMissing", desc);
125
- this.name = "ErrPlatformPackageMissing";
126
- Object.setPrototypeOf(this, new.target.prototype);
127
- }
128
- }
129
-
130
110
  class ErrBunVersionTooOld extends AgentDirectorError {
131
111
  constructor(actual, minimum) {
132
112
  super("", "ErrBunVersionTooOld", `Bun ${actual} is below the minimum required version ${minimum}; upgrade Bun to continue`);
@@ -135,14 +115,6 @@ class ErrBunVersionTooOld extends AgentDirectorError {
135
115
  }
136
116
  }
137
117
 
138
- class ErrCliNotExecutable extends AgentDirectorError {
139
- constructor(path) {
140
- super("", "ErrCliNotExecutable", `binary "${path}" exists but lacks execute permission; check file mode (chmod +x)`);
141
- this.name = "ErrCliNotExecutable";
142
- Object.setPrototypeOf(this, new.target.prototype);
143
- }
144
- }
145
-
146
118
  class ErrConsumerSignal extends AgentDirectorError {
147
119
  signal;
148
120
  constructor(verb, signal) {
@@ -177,6 +149,63 @@ class ErrUnknownErrorName extends AgentDirectorError {
177
149
  }
178
150
  }
179
151
 
152
+ class ErrSystemInstallNotFound extends AgentDirectorError {
153
+ checkedLocations;
154
+ constructor(checkedLocations) {
155
+ const parts = checkedLocations.map((loc) => {
156
+ if (loc.kind === "standard-install-path") {
157
+ return `standard install path (${loc.detail ?? "HOME unset/empty/non-absolute"})`;
158
+ }
159
+ return `PATH lookup (PATH=${loc.detail ?? "<unset>"})`;
160
+ });
161
+ super("", "ErrSystemInstallNotFound", `no agent-director binary found; checked: ${parts.join("; ")}`);
162
+ this.checkedLocations = checkedLocations;
163
+ this.name = "ErrSystemInstallNotFound";
164
+ Object.setPrototypeOf(this, new.target.prototype);
165
+ }
166
+ }
167
+
168
+ class ErrSystemInstallTooOld extends AgentDirectorError {
169
+ actualVersion;
170
+ requiredVersion;
171
+ binaryPath;
172
+ constructor(actualVersion, requiredVersion, binaryPath) {
173
+ super("", "ErrSystemInstallTooOld", `agent-director ${actualVersion} at ${binaryPath} is older than the required minimum ${requiredVersion}`);
174
+ this.actualVersion = actualVersion;
175
+ this.requiredVersion = requiredVersion;
176
+ this.binaryPath = binaryPath;
177
+ this.name = "ErrSystemInstallTooOld";
178
+ Object.setPrototypeOf(this, new.target.prototype);
179
+ }
180
+ }
181
+
182
+ class ErrSystemInstallUnreachable extends AgentDirectorError {
183
+ binaryPath;
184
+ reason;
185
+ diagnostic;
186
+ exitCode;
187
+ signal;
188
+ constructor(binaryPath, reason, opts) {
189
+ let suffix = "";
190
+ if (reason === "probe-nonzero-exit" && opts?.exitCode != null) {
191
+ suffix = ` (exit ${opts.exitCode})`;
192
+ } else if (reason === "probe-killed-by-signal" && opts?.signal) {
193
+ suffix = ` (signal ${opts.signal})`;
194
+ } else if (opts?.diagnostic) {
195
+ const trimmed = opts.diagnostic.length > 200 ? opts.diagnostic.slice(0, 200) + "\u2026" : opts.diagnostic;
196
+ suffix = `: ${trimmed.replace(/\s+/g, " ").trim()}`;
197
+ }
198
+ super("", "ErrSystemInstallUnreachable", `agent-director at ${binaryPath} is unreachable (${reason})${suffix}`);
199
+ this.binaryPath = binaryPath;
200
+ this.reason = reason;
201
+ this.diagnostic = opts?.diagnostic ?? null;
202
+ this.exitCode = opts?.exitCode ?? null;
203
+ this.signal = opts?.signal ?? null;
204
+ this.name = "ErrSystemInstallUnreachable";
205
+ Object.setPrototypeOf(this, new.target.prototype);
206
+ }
207
+ }
208
+
180
209
  class ErrCwdMissing extends AgentDirectorError {
181
210
  }
182
211
 
@@ -335,12 +364,386 @@ function errorFromEnvelope(verb, err_name, err_description) {
335
364
  return new AgentDirectorError(verb, err_name, err_description);
336
365
  }
337
366
 
367
+ // src/internal/discovery.ts
368
+ var STANDARD_INSTALL_PATH_RELATIVE = ".agent-director/bin/agent-director";
369
+ var CLI_BINARY_NAME = "agent-director";
370
+ function resolveStandardInstallPath(homeEnv) {
371
+ if (homeEnv === undefined || homeEnv === "" || !isAbsolute(homeEnv)) {
372
+ return null;
373
+ }
374
+ return resolve(homeEnv, STANDARD_INSTALL_PATH_RELATIVE);
375
+ }
376
+ function pathLookup(pathEnv) {
377
+ if (pathEnv === undefined || pathEnv === "")
378
+ return null;
379
+ for (const dir of pathEnv.split(delimiter)) {
380
+ if (dir === "")
381
+ continue;
382
+ const candidate = join(dir, CLI_BINARY_NAME);
383
+ try {
384
+ const st = statSync(candidate);
385
+ if (st.isFile() || st.isSymbolicLink()) {
386
+ return candidate;
387
+ }
388
+ } catch {}
389
+ }
390
+ return null;
391
+ }
392
+ function isExecutableFor(st) {
393
+ const mode = st.mode;
394
+ const fileUid = st.uid;
395
+ const fileGid = st.gid;
396
+ const myUid = process.getuid?.() ?? 0;
397
+ const myGid = process.getgid?.() ?? 0;
398
+ if (fileUid === myUid)
399
+ return (mode & 64) !== 0;
400
+ if (fileGid === myGid)
401
+ return (mode & 8) !== 0;
402
+ return (mode & 1) !== 0;
403
+ }
404
+ function validateCandidate(candidatePath) {
405
+ let st;
406
+ try {
407
+ st = statSync(candidatePath);
408
+ } catch {
409
+ throw new ErrSystemInstallUnreachable(candidatePath, "not-a-regular-file");
410
+ }
411
+ if (!st.isFile()) {
412
+ throw new ErrSystemInstallUnreachable(candidatePath, "not-a-regular-file");
413
+ }
414
+ if (!isExecutableFor(st)) {
415
+ throw new ErrSystemInstallUnreachable(candidatePath, "not-executable");
416
+ }
417
+ let canonical;
418
+ try {
419
+ canonical = realpathSync(candidatePath);
420
+ } catch {
421
+ throw new ErrSystemInstallUnreachable(candidatePath, "not-a-regular-file");
422
+ }
423
+ try {
424
+ const stTarget = statSync(canonical);
425
+ if (!stTarget.isFile()) {
426
+ throw new ErrSystemInstallUnreachable(canonical, "not-a-regular-file");
427
+ }
428
+ if (!isExecutableFor(stTarget)) {
429
+ throw new ErrSystemInstallUnreachable(canonical, "not-executable");
430
+ }
431
+ } catch (e) {
432
+ if (e instanceof ErrSystemInstallUnreachable)
433
+ throw e;
434
+ throw new ErrSystemInstallUnreachable(canonical, "not-a-regular-file");
435
+ }
436
+ try {
437
+ accessSync(canonical, fsConstants.X_OK);
438
+ } catch {
439
+ throw new ErrSystemInstallUnreachable(canonical, "not-executable");
440
+ }
441
+ return canonical;
442
+ }
443
+ function canonicalizePath(candidatePath) {
444
+ if (!isAbsolute(candidatePath)) {
445
+ candidatePath = resolve(candidatePath);
446
+ }
447
+ try {
448
+ return realpathSync(candidatePath);
449
+ } catch {
450
+ throw new ErrSystemInstallUnreachable(candidatePath, "not-a-regular-file");
451
+ }
452
+ }
453
+ function discoverSystemBinary(env) {
454
+ const checkedLocations = [];
455
+ const standardPath = resolveStandardInstallPath(env.HOME);
456
+ if (standardPath !== null) {
457
+ let exists = false;
458
+ try {
459
+ statSync(standardPath);
460
+ exists = true;
461
+ } catch {}
462
+ if (exists) {
463
+ const canonical = validateCandidate(standardPath);
464
+ return { path: canonical, kind: "standard-install-path" };
465
+ }
466
+ checkedLocations.push({
467
+ kind: "standard-install-path",
468
+ detail: standardPath
469
+ });
470
+ } else {
471
+ checkedLocations.push({
472
+ kind: "standard-install-path",
473
+ detail: null
474
+ });
475
+ }
476
+ const pathCandidate = pathLookup(env.PATH);
477
+ if (pathCandidate !== null) {
478
+ const canonical = validateCandidate(pathCandidate);
479
+ return { path: canonical, kind: "path-lookup" };
480
+ }
481
+ checkedLocations.push({
482
+ kind: "path-lookup",
483
+ detail: env.PATH ?? null
484
+ });
485
+ throw new ErrSystemInstallNotFound(checkedLocations);
486
+ }
487
+
488
+ // src/internal/semver.ts
489
+ var DEV_SENTINEL = "0.0.0-dev";
490
+ var SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
491
+ function parseVersion(input) {
492
+ if (input === DEV_SENTINEL) {
493
+ return { ok: true, value: { kind: "sentinel" } };
494
+ }
495
+ const m = SEMVER_RE.exec(input);
496
+ if (m === null) {
497
+ return { ok: false };
498
+ }
499
+ const major = Number(m[1]);
500
+ const minor = Number(m[2]);
501
+ const patch = Number(m[3]);
502
+ if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) {
503
+ return { ok: false };
504
+ }
505
+ return {
506
+ ok: true,
507
+ value: {
508
+ kind: "real",
509
+ major,
510
+ minor,
511
+ patch,
512
+ prerelease: m[4] ?? null
513
+ }
514
+ };
515
+ }
516
+ function sign(n) {
517
+ if (n < 0)
518
+ return -1;
519
+ if (n > 0)
520
+ return 1;
521
+ return 0;
522
+ }
523
+ function compareParsed(a, b) {
524
+ if (a.kind === "sentinel" && b.kind === "sentinel")
525
+ return 0;
526
+ if (a.kind === "sentinel")
527
+ return 1;
528
+ if (b.kind === "sentinel")
529
+ return -1;
530
+ const coreDiff = a.major !== b.major ? a.major - b.major : a.minor !== b.minor ? a.minor - b.minor : a.patch - b.patch;
531
+ if (coreDiff !== 0)
532
+ return sign(coreDiff);
533
+ if (a.prerelease === null && b.prerelease === null)
534
+ return 0;
535
+ if (a.prerelease === null)
536
+ return 1;
537
+ if (b.prerelease === null)
538
+ return -1;
539
+ if (a.prerelease < b.prerelease)
540
+ return -1;
541
+ if (a.prerelease > b.prerelease)
542
+ return 1;
543
+ return 0;
544
+ }
545
+
546
+ // src/internal/probe.ts
547
+ var PROBE_TIMEOUT_MS = 5000;
548
+ var SIGKILL_GRACE_MS = 2000;
549
+ var STDOUT_CAP_BYTES = 64 * 1024;
550
+ var STDERR_CAP_BYTES = 64 * 1024;
551
+ var ENV_ALLOWLIST_BASE = ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR", "TZ"];
552
+ var ENV_ALLOWLIST_LINUX = ["LD_LIBRARY_PATH", "LD_PRELOAD"];
553
+ var ENV_ALLOWLIST_DARWIN = ["DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH"];
554
+ function scrubbedEnv(source) {
555
+ const allow = [...ENV_ALLOWLIST_BASE];
556
+ if (process.platform === "linux")
557
+ allow.push(...ENV_ALLOWLIST_LINUX);
558
+ if (process.platform === "darwin")
559
+ allow.push(...ENV_ALLOWLIST_DARWIN);
560
+ const out = {};
561
+ for (const key of allow) {
562
+ const v = source[key];
563
+ if (typeof v === "string")
564
+ out[key] = v;
565
+ }
566
+ return out;
567
+ }
568
+ async function readCapped(stream, capByteSize) {
569
+ const reader = stream.getReader();
570
+ const chunks = [];
571
+ let bytes = 0;
572
+ let capped = false;
573
+ try {
574
+ for (;; ) {
575
+ const { value, done } = await reader.read();
576
+ if (done)
577
+ break;
578
+ if (capped)
579
+ continue;
580
+ if (bytes + value.byteLength > capByteSize) {
581
+ const remaining = capByteSize - bytes;
582
+ if (remaining > 0) {
583
+ chunks.push(value.slice(0, remaining));
584
+ bytes += remaining;
585
+ }
586
+ capped = true;
587
+ continue;
588
+ }
589
+ chunks.push(value);
590
+ bytes += value.byteLength;
591
+ }
592
+ } finally {
593
+ try {
594
+ reader.releaseLock();
595
+ } catch {}
596
+ }
597
+ const total = new Uint8Array(bytes);
598
+ let off = 0;
599
+ for (const c of chunks) {
600
+ total.set(c, off);
601
+ off += c.byteLength;
602
+ }
603
+ return { text: new TextDecoder().decode(total), capped };
604
+ }
605
+ async function runProbe(candidatePath) {
606
+ let proc;
607
+ try {
608
+ proc = Bun.spawn({
609
+ cmd: [candidatePath, "version", "--json"],
610
+ stdin: "pipe",
611
+ stdout: "pipe",
612
+ stderr: "pipe",
613
+ cwd: "/",
614
+ env: scrubbedEnv(process.env),
615
+ detached: false
616
+ });
617
+ } catch (e) {
618
+ const msg = e instanceof Error ? e.message : String(e);
619
+ return {
620
+ ok: false,
621
+ reason: "spawn-failed",
622
+ diagnostic: msg,
623
+ exitCode: null,
624
+ signal: null
625
+ };
626
+ }
627
+ try {
628
+ proc.stdin.end();
629
+ } catch {}
630
+ let timedOut = false;
631
+ let killedByCap = false;
632
+ let killReason = null;
633
+ const sigtermAt = setTimeout(() => {
634
+ timedOut = true;
635
+ killReason = "probe-timeout";
636
+ try {
637
+ proc.kill("SIGTERM");
638
+ } catch {}
639
+ setTimeout(() => {
640
+ try {
641
+ proc.kill("SIGKILL");
642
+ } catch {}
643
+ }, SIGKILL_GRACE_MS);
644
+ }, PROBE_TIMEOUT_MS);
645
+ const [stdoutResult, stderrResult] = await Promise.all([
646
+ readCapped(proc.stdout, STDOUT_CAP_BYTES),
647
+ readCapped(proc.stderr, STDERR_CAP_BYTES)
648
+ ]);
649
+ if ((stdoutResult.capped || stderrResult.capped) && !timedOut) {
650
+ killedByCap = true;
651
+ killReason = stdoutResult.capped ? "unparseable-version" : "other";
652
+ try {
653
+ proc.kill("SIGTERM");
654
+ } catch {}
655
+ setTimeout(() => {
656
+ try {
657
+ proc.kill("SIGKILL");
658
+ } catch {}
659
+ }, SIGKILL_GRACE_MS);
660
+ }
661
+ await proc.exited;
662
+ clearTimeout(sigtermAt);
663
+ const exitCode = proc.exitCode;
664
+ const signalCode = proc.signalCode;
665
+ const stdoutText = stdoutResult.text;
666
+ const stderrText = stderrResult.text;
667
+ if (killedByCap && killReason !== null) {
668
+ return {
669
+ ok: false,
670
+ reason: killReason,
671
+ diagnostic: stderrText || null,
672
+ exitCode: null,
673
+ signal: null
674
+ };
675
+ }
676
+ if (timedOut) {
677
+ return {
678
+ ok: false,
679
+ reason: "probe-timeout",
680
+ diagnostic: stderrText || null,
681
+ exitCode: null,
682
+ signal: null
683
+ };
684
+ }
685
+ if (signalCode !== null) {
686
+ return {
687
+ ok: false,
688
+ reason: "probe-killed-by-signal",
689
+ diagnostic: stderrText || null,
690
+ exitCode: null,
691
+ signal: signalCode
692
+ };
693
+ }
694
+ if (exitCode !== 0) {
695
+ return {
696
+ ok: false,
697
+ reason: "probe-nonzero-exit",
698
+ diagnostic: stderrText || null,
699
+ exitCode: exitCode ?? null,
700
+ signal: null
701
+ };
702
+ }
703
+ let parsed;
704
+ try {
705
+ parsed = JSON.parse(stdoutText);
706
+ } catch {
707
+ return {
708
+ ok: false,
709
+ reason: "unparseable-version",
710
+ diagnostic: stdoutText || null,
711
+ exitCode: null,
712
+ signal: null
713
+ };
714
+ }
715
+ if (typeof parsed.version !== "string") {
716
+ return {
717
+ ok: false,
718
+ reason: "unparseable-version",
719
+ diagnostic: stdoutText || null,
720
+ exitCode: null,
721
+ signal: null
722
+ };
723
+ }
724
+ const semverCheck = parseVersion(parsed.version);
725
+ if (!semverCheck.ok) {
726
+ return {
727
+ ok: false,
728
+ reason: "unparseable-version",
729
+ diagnostic: parsed.version,
730
+ exitCode: null,
731
+ signal: null
732
+ };
733
+ }
734
+ return { ok: true, version: parsed.version };
735
+ }
736
+ // version-floor.json
737
+ var version_floor_default = {
738
+ min_binary_version: "0.7.0"
739
+ };
740
+
741
+ // src/internal/constants.ts
742
+ var MIN_BINARY_VERSION = version_floor_default.min_binary_version;
743
+ var DEV_SENTINEL_VERSION = "0.0.0-dev";
744
+
338
745
  // src/internal/platformResolve.ts
339
746
  var MIN_BUN_VERSION = "1.0.21";
340
- var SUPPORTED_TUPLES = new Map([
341
- ["linux-x64", "@agent-director/linux-x64"],
342
- ["darwin-arm64", "@agent-director/darwin-arm64"]
343
- ]);
344
747
  function compareSemver(a, b) {
345
748
  const parse = (s) => s.split(".").map((p) => parseInt(p, 10) || 0);
346
749
  const pa = parse(a);
@@ -352,55 +755,15 @@ function compareSemver(a, b) {
352
755
  }
353
756
  return 0;
354
757
  }
355
- function resolveCliPath(opts) {
356
- const platform = opts?.platform ?? process.platform;
357
- const arch = opts?.arch ?? process.arch;
758
+ function checkBunVersion() {
358
759
  if (compareSemver(Bun.version, MIN_BUN_VERSION) < 0) {
359
760
  throw new ErrBunVersionTooOld(Bun.version, MIN_BUN_VERSION);
360
761
  }
361
- const tuple = `${platform}-${arch}`;
362
- const subpkgName = SUPPORTED_TUPLES.get(tuple);
363
- if (subpkgName === undefined) {
364
- throw new ErrUnsupportedPlatform(tuple);
365
- }
366
- let binPath;
367
- if (opts?._requireResolve !== undefined) {
368
- try {
369
- binPath = opts._requireResolve(subpkgName);
370
- } catch {
371
- throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed (DI hook threw); run: npm install ${subpkgName}`);
372
- }
373
- } else {
374
- let pkgDir;
375
- try {
376
- const pkgJsonUrl = import.meta.resolve(`${subpkgName}/package.json`);
377
- pkgDir = dirname(fileURLToPath(pkgJsonUrl));
378
- } catch {
379
- throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed; run: npm install ${subpkgName}`);
380
- }
381
- binPath = join(pkgDir, "bin", "agent-director");
382
- }
383
- let stat;
384
- try {
385
- stat = statSync(binPath);
386
- } catch {
387
- throw new ErrPlatformPackageMissing(subpkgName, `binary not found at "${binPath}"`);
388
- }
389
- const mode = stat.mode;
390
- const fileUid = stat.uid;
391
- const fileGid = stat.gid;
392
- const myUid = process.getuid?.() ?? 0;
393
- const myGid = process.getgid?.() ?? 0;
394
- const execByOwner = (mode & 64) !== 0;
395
- const execByGroup = (mode & 8) !== 0;
396
- const execByOther = (mode & 1) !== 0;
397
- const isExecutable = fileUid === myUid && execByOwner || fileGid === myGid && execByGroup || execByOther;
398
- if (!isExecutable) {
399
- throw new ErrCliNotExecutable(binPath);
400
- }
401
- return binPath;
402
762
  }
403
763
 
764
+ // src/internal/subprocessClient.ts
765
+ import { readFile } from "fs/promises";
766
+
404
767
  // src/internal/tilde.ts
405
768
  import * as os from "os";
406
769
  function expandTilde(p) {
@@ -868,7 +1231,7 @@ function throwFromEnvelope(verb, envelope) {
868
1231
 
869
1232
  // src/internal/subprocessClient.ts
870
1233
  var DEFAULT_CALL_TIMEOUT_MS = 30000;
871
- var SIGKILL_GRACE_MS = 2000;
1234
+ var SIGKILL_GRACE_MS2 = 2000;
872
1235
  async function loadNpmPackageVersion() {
873
1236
  try {
874
1237
  const url = import.meta.resolve("agent-director/package.json");
@@ -882,7 +1245,8 @@ async function loadNpmPackageVersion() {
882
1245
  }
883
1246
 
884
1247
  class SubprocessClient {
885
- #cliPathOverride;
1248
+ #binaryPath;
1249
+ #binaryVersion;
886
1250
  #callTimeoutMs;
887
1251
  #logger;
888
1252
  #open;
@@ -890,20 +1254,15 @@ class SubprocessClient {
890
1254
  _handle = null;
891
1255
  #tail;
892
1256
  #npmPkgVersion;
893
- constructor(opts) {
1257
+ constructor(opts, init) {
894
1258
  const rawTimeout = opts.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
895
1259
  if (rawTimeout <= 0) {
896
1260
  throw new Error(`ClientOptions.callTimeoutMs must be positive (got ${rawTimeout}); ` + `omit the field to use the default (${DEFAULT_CALL_TIMEOUT_MS} ms)`);
897
1261
  }
898
1262
  this.#callTimeoutMs = rawTimeout;
899
1263
  this.#logger = opts.logger;
900
- const opts2 = opts;
901
- if (opts2._cliPath !== undefined) {
902
- this.#cliPathOverride = opts2._cliPath;
903
- } else {
904
- resolveCliPath();
905
- this.#cliPathOverride = undefined;
906
- }
1264
+ this.#binaryPath = init.binaryPath;
1265
+ this.#binaryVersion = init.binaryVersion;
907
1266
  const g = {};
908
1267
  if (opts.storePath !== undefined)
909
1268
  g.storePath = expandTilde(opts.storePath);
@@ -915,6 +1274,15 @@ class SubprocessClient {
915
1274
  this.#open = true;
916
1275
  this.#tail = Promise.resolve();
917
1276
  }
1277
+ static _construct(opts, init) {
1278
+ return new SubprocessClient(opts, init);
1279
+ }
1280
+ get binaryPath() {
1281
+ return this.#binaryPath;
1282
+ }
1283
+ get binaryVersion() {
1284
+ return this.#binaryVersion;
1285
+ }
918
1286
  close() {
919
1287
  this.#open = false;
920
1288
  }
@@ -946,7 +1314,7 @@ class SubprocessClient {
946
1314
  return callPromise;
947
1315
  }
948
1316
  async#doCall(verb, params) {
949
- const cliPath = this.#cliPathOverride ?? resolveCliPath();
1317
+ const cliPath = this.#binaryPath;
950
1318
  const argv = buildArgv(cliPath, verb, params, this.#globalOpts);
951
1319
  const startMs = Date.now();
952
1320
  const spawnEnv = { ...process.env };
@@ -965,7 +1333,7 @@ class SubprocessClient {
965
1333
  proc.kill("SIGTERM");
966
1334
  const gracefulHandle = setTimeout(() => {
967
1335
  proc.kill("SIGKILL");
968
- }, SIGKILL_GRACE_MS);
1336
+ }, SIGKILL_GRACE_MS2);
969
1337
  proc.exited.then(() => clearTimeout(gracefulHandle), () => clearTimeout(gracefulHandle));
970
1338
  }, this.#callTimeoutMs);
971
1339
  let stdoutText;
@@ -1091,9 +1459,83 @@ class SubprocessClient {
1091
1459
  return { ...cliResp, version: this.#npmPkgVersion };
1092
1460
  }
1093
1461
  }
1462
+
1463
+ // src/client.ts
1464
+ class Client extends SubprocessClient {
1465
+ static async create(opts = {}) {
1466
+ checkBunVersion();
1467
+ const opts2 = opts;
1468
+ let binaryPath;
1469
+ if (opts2._cliPath !== undefined) {
1470
+ binaryPath = canonicalizePath(opts2._cliPath);
1471
+ } else {
1472
+ const candidate = discoverSystemBinary({
1473
+ HOME: process.env["HOME"],
1474
+ PATH: process.env["PATH"]
1475
+ });
1476
+ binaryPath = candidate.path;
1477
+ }
1478
+ const probe = await runProbe(binaryPath);
1479
+ if (!probe.ok) {
1480
+ throw new ErrSystemInstallUnreachable(binaryPath, probe.reason, {
1481
+ diagnostic: probe.diagnostic,
1482
+ exitCode: probe.exitCode,
1483
+ signal: probe.signal
1484
+ });
1485
+ }
1486
+ const probed = parseVersion(probe.version);
1487
+ if (!probed.ok) {
1488
+ throw new ErrSystemInstallUnreachable(binaryPath, "unparseable-version", {
1489
+ diagnostic: probe.version
1490
+ });
1491
+ }
1492
+ const floor = parseVersion(MIN_BINARY_VERSION);
1493
+ if (!floor.ok) {
1494
+ throw new Error(`internal: MIN_BINARY_VERSION="${MIN_BINARY_VERSION}" failed strict SemVer parse`);
1495
+ }
1496
+ if (compareParsed(probed.value, floor.value) < 0) {
1497
+ throw new ErrSystemInstallTooOld(probe.version, MIN_BINARY_VERSION, binaryPath);
1498
+ }
1499
+ return new Client(opts, {
1500
+ binaryPath,
1501
+ binaryVersion: probe.version
1502
+ });
1503
+ }
1504
+ }
1505
+ async function resolveSystemBinary(_opts = {}) {
1506
+ checkBunVersion();
1507
+ const candidate = discoverSystemBinary({
1508
+ HOME: process.env["HOME"],
1509
+ PATH: process.env["PATH"]
1510
+ });
1511
+ const binaryPath = candidate.path;
1512
+ const probe = await runProbe(binaryPath);
1513
+ if (!probe.ok) {
1514
+ throw new ErrSystemInstallUnreachable(binaryPath, probe.reason, {
1515
+ diagnostic: probe.diagnostic,
1516
+ exitCode: probe.exitCode,
1517
+ signal: probe.signal
1518
+ });
1519
+ }
1520
+ const probed = parseVersion(probe.version);
1521
+ if (!probed.ok) {
1522
+ throw new ErrSystemInstallUnreachable(binaryPath, "unparseable-version", {
1523
+ diagnostic: probe.version
1524
+ });
1525
+ }
1526
+ const floor = parseVersion(MIN_BINARY_VERSION);
1527
+ if (!floor.ok) {
1528
+ throw new Error(`internal: MIN_BINARY_VERSION="${MIN_BINARY_VERSION}" failed strict SemVer parse`);
1529
+ }
1530
+ if (compareParsed(probed.value, floor.value) < 0) {
1531
+ throw new ErrSystemInstallTooOld(probe.version, MIN_BINARY_VERSION, binaryPath);
1532
+ }
1533
+ return { path: binaryPath, version: probe.version };
1534
+ }
1094
1535
  export {
1536
+ resolveSystemBinary,
1095
1537
  errorFromEnvelope,
1096
- ErrUnsupportedPlatform,
1538
+ MIN_BINARY_VERSION,
1097
1539
  ErrUnknownErrorName,
1098
1540
  ErrTmuxSessionNameTooLong,
1099
1541
  ErrTmuxSessionNameInvalid,
@@ -1106,6 +1548,9 @@ export {
1106
1548
  ErrTemplateNameUnsafe,
1107
1549
  ErrTemplateMalformed,
1108
1550
  ErrTemplateExists,
1551
+ ErrSystemInstallUnreachable,
1552
+ ErrSystemInstallTooOld,
1553
+ ErrSystemInstallNotFound,
1109
1554
  ErrSpawnNotResumable,
1110
1555
  ErrSpawnNotPausable,
1111
1556
  ErrSpawnNotInteractive,
@@ -1116,7 +1561,6 @@ export {
1116
1561
  ErrRelayModeOff,
1117
1562
  ErrRelayModeInvalid,
1118
1563
  ErrProbeUnsupported,
1119
- ErrPlatformPackageMissing,
1120
1564
  ErrPermissionRequestNotFound,
1121
1565
  ErrPauseTimeout,
1122
1566
  ErrNoSessionId,
@@ -1133,11 +1577,11 @@ export {
1133
1577
  ErrCwdMissing,
1134
1578
  ErrConsumerSignal,
1135
1579
  ErrClientClosed,
1136
- ErrCliNotExecutable,
1137
1580
  ErrCallTimeout,
1138
1581
  ErrBunVersionTooOld,
1139
1582
  ErrAmbiguousRequest,
1140
1583
  ErrAlreadyDecided,
1141
- SubprocessClient as Client,
1584
+ DEV_SENTINEL_VERSION,
1585
+ Client,
1142
1586
  AgentDirectorError
1143
1587
  };