agent-director 0.6.2 → 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,17 +14,16 @@ var __export = (target, all) => {
14
14
  });
15
15
  };
16
16
 
17
- // src/internal/platformResolve.ts
18
- import { statSync } from "fs";
19
- import { fileURLToPath } from "url";
20
- 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";
21
21
 
22
22
  // src/errors.ts
23
23
  var exports_errors = {};
24
24
  __export(exports_errors, {
25
25
  errorFromEnvelope: () => errorFromEnvelope,
26
26
  TS_ONLY_ERROR_NAMES: () => TS_ONLY_ERROR_NAMES,
27
- ErrUnsupportedPlatform: () => ErrUnsupportedPlatform,
28
27
  ErrUnknownErrorName: () => ErrUnknownErrorName,
29
28
  ErrTmuxSessionNameTooLong: () => ErrTmuxSessionNameTooLong,
30
29
  ErrTmuxSessionNameInvalid: () => ErrTmuxSessionNameInvalid,
@@ -37,6 +36,9 @@ __export(exports_errors, {
37
36
  ErrTemplateNameUnsafe: () => ErrTemplateNameUnsafe,
38
37
  ErrTemplateMalformed: () => ErrTemplateMalformed,
39
38
  ErrTemplateExists: () => ErrTemplateExists,
39
+ ErrSystemInstallUnreachable: () => ErrSystemInstallUnreachable,
40
+ ErrSystemInstallTooOld: () => ErrSystemInstallTooOld,
41
+ ErrSystemInstallNotFound: () => ErrSystemInstallNotFound,
40
42
  ErrSpawnNotResumable: () => ErrSpawnNotResumable,
41
43
  ErrSpawnNotPausable: () => ErrSpawnNotPausable,
42
44
  ErrSpawnNotInteractive: () => ErrSpawnNotInteractive,
@@ -47,7 +49,6 @@ __export(exports_errors, {
47
49
  ErrRelayModeOff: () => ErrRelayModeOff,
48
50
  ErrRelayModeInvalid: () => ErrRelayModeInvalid,
49
51
  ErrProbeUnsupported: () => ErrProbeUnsupported,
50
- ErrPlatformPackageMissing: () => ErrPlatformPackageMissing,
51
52
  ErrPermissionRequestNotFound: () => ErrPermissionRequestNotFound,
52
53
  ErrPauseTimeout: () => ErrPauseTimeout,
53
54
  ErrNoSessionId: () => ErrNoSessionId,
@@ -64,7 +65,6 @@ __export(exports_errors, {
64
65
  ErrCwdMissing: () => ErrCwdMissing,
65
66
  ErrConsumerSignal: () => ErrConsumerSignal,
66
67
  ErrClientClosed: () => ErrClientClosed,
67
- ErrCliNotExecutable: () => ErrCliNotExecutable,
68
68
  ErrCallTimeout: () => ErrCallTimeout,
69
69
  ErrBunVersionTooOld: () => ErrBunVersionTooOld,
70
70
  ErrAmbiguousRequest: () => ErrAmbiguousRequest,
@@ -75,13 +75,13 @@ __export(exports_errors, {
75
75
  // src/internal/tsOnlyErrors.ts
76
76
  var TS_ONLY_ERROR_NAMES = [
77
77
  "ErrClientClosed",
78
- "ErrUnsupportedPlatform",
79
- "ErrPlatformPackageMissing",
80
78
  "ErrBunVersionTooOld",
81
- "ErrCliNotExecutable",
82
79
  "ErrConsumerSignal",
83
80
  "ErrCallTimeout",
84
- "ErrUnknownErrorName"
81
+ "ErrUnknownErrorName",
82
+ "ErrSystemInstallNotFound",
83
+ "ErrSystemInstallTooOld",
84
+ "ErrSystemInstallUnreachable"
85
85
  ];
86
86
 
87
87
  // src/errors.ts
@@ -107,23 +107,6 @@ class ErrClientClosed extends AgentDirectorError {
107
107
  }
108
108
  }
109
109
 
110
- class ErrUnsupportedPlatform extends AgentDirectorError {
111
- constructor(tuple) {
112
- super("", "ErrUnsupportedPlatform", `platform/arch tuple "${tuple}" is not supported; supported: linux-x64, darwin-arm64`);
113
- this.name = "ErrUnsupportedPlatform";
114
- Object.setPrototypeOf(this, new.target.prototype);
115
- }
116
- }
117
-
118
- class ErrPlatformPackageMissing extends AgentDirectorError {
119
- constructor(pkgName, detail) {
120
- const desc = detail ? `native sub-package "${pkgName}" is not usable: ${detail}` : `native sub-package "${pkgName}" is not installed or its binary is absent`;
121
- super("", "ErrPlatformPackageMissing", desc);
122
- this.name = "ErrPlatformPackageMissing";
123
- Object.setPrototypeOf(this, new.target.prototype);
124
- }
125
- }
126
-
127
110
  class ErrBunVersionTooOld extends AgentDirectorError {
128
111
  constructor(actual, minimum) {
129
112
  super("", "ErrBunVersionTooOld", `Bun ${actual} is below the minimum required version ${minimum}; upgrade Bun to continue`);
@@ -132,14 +115,6 @@ class ErrBunVersionTooOld extends AgentDirectorError {
132
115
  }
133
116
  }
134
117
 
135
- class ErrCliNotExecutable extends AgentDirectorError {
136
- constructor(path) {
137
- super("", "ErrCliNotExecutable", `binary "${path}" exists but lacks execute permission; check file mode (chmod +x)`);
138
- this.name = "ErrCliNotExecutable";
139
- Object.setPrototypeOf(this, new.target.prototype);
140
- }
141
- }
142
-
143
118
  class ErrConsumerSignal extends AgentDirectorError {
144
119
  signal;
145
120
  constructor(verb, signal) {
@@ -174,6 +149,63 @@ class ErrUnknownErrorName extends AgentDirectorError {
174
149
  }
175
150
  }
176
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
+
177
209
  class ErrCwdMissing extends AgentDirectorError {
178
210
  }
179
211
 
@@ -332,12 +364,386 @@ function errorFromEnvelope(verb, err_name, err_description) {
332
364
  return new AgentDirectorError(verb, err_name, err_description);
333
365
  }
334
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
+
335
745
  // src/internal/platformResolve.ts
336
746
  var MIN_BUN_VERSION = "1.0.21";
337
- var SUPPORTED_TUPLES = new Map([
338
- ["linux-x64", "@agent-director/linux-x64"],
339
- ["darwin-arm64", "@agent-director/darwin-arm64"]
340
- ]);
341
747
  function compareSemver(a, b) {
342
748
  const parse = (s) => s.split(".").map((p) => parseInt(p, 10) || 0);
343
749
  const pa = parse(a);
@@ -349,55 +755,15 @@ function compareSemver(a, b) {
349
755
  }
350
756
  return 0;
351
757
  }
352
- function resolveCliPath(opts) {
353
- const platform = opts?.platform ?? process.platform;
354
- const arch = opts?.arch ?? process.arch;
758
+ function checkBunVersion() {
355
759
  if (compareSemver(Bun.version, MIN_BUN_VERSION) < 0) {
356
760
  throw new ErrBunVersionTooOld(Bun.version, MIN_BUN_VERSION);
357
761
  }
358
- const tuple = `${platform}-${arch}`;
359
- const subpkgName = SUPPORTED_TUPLES.get(tuple);
360
- if (subpkgName === undefined) {
361
- throw new ErrUnsupportedPlatform(tuple);
362
- }
363
- let binPath;
364
- if (opts?._requireResolve !== undefined) {
365
- try {
366
- binPath = opts._requireResolve(subpkgName);
367
- } catch {
368
- throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed (DI hook threw); run: npm install ${subpkgName}`);
369
- }
370
- } else {
371
- let pkgDir;
372
- try {
373
- const pkgJsonUrl = import.meta.resolve(`${subpkgName}/package.json`);
374
- pkgDir = dirname(fileURLToPath(pkgJsonUrl));
375
- } catch {
376
- throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed; run: npm install ${subpkgName}`);
377
- }
378
- binPath = join(pkgDir, "bin", "agent-director");
379
- }
380
- let stat;
381
- try {
382
- stat = statSync(binPath);
383
- } catch {
384
- throw new ErrPlatformPackageMissing(subpkgName, `binary not found at "${binPath}"`);
385
- }
386
- const mode = stat.mode;
387
- const fileUid = stat.uid;
388
- const fileGid = stat.gid;
389
- const myUid = process.getuid?.() ?? 0;
390
- const myGid = process.getgid?.() ?? 0;
391
- const execByOwner = (mode & 64) !== 0;
392
- const execByGroup = (mode & 8) !== 0;
393
- const execByOther = (mode & 1) !== 0;
394
- const isExecutable = fileUid === myUid && execByOwner || fileGid === myGid && execByGroup || execByOther;
395
- if (!isExecutable) {
396
- throw new ErrCliNotExecutable(binPath);
397
- }
398
- return binPath;
399
762
  }
400
763
 
764
+ // src/internal/subprocessClient.ts
765
+ import { readFile } from "fs/promises";
766
+
401
767
  // src/internal/tilde.ts
402
768
  import * as os from "os";
403
769
  function expandTilde(p) {
@@ -862,91 +1228,41 @@ function throwFromEnvelope(verb, envelope) {
862
1228
  }
863
1229
  throw new ErrUnknownErrorName(errName, envelope);
864
1230
  }
865
- // package.json
866
- var package_default = {
867
- name: "agent-director",
868
- version: "0.6.2",
869
- type: "module",
870
- os: [
871
- "linux",
872
- "darwin"
873
- ],
874
- cpu: [
875
- "x64",
876
- "arm64"
877
- ],
878
- engines: {
879
- bun: ">=1.0.21"
880
- },
881
- files: [
882
- "dist/**/*.js",
883
- "dist/**/*.d.ts",
884
- "!dist/**/*.test.*",
885
- "README.md",
886
- "scripts/postinstall.ts",
887
- "skills/install-agent-director/**"
888
- ],
889
- exports: {
890
- ".": {
891
- import: "./dist/index.js",
892
- types: "./dist/index.d.ts"
893
- }
894
- },
895
- scripts: {
896
- build: "bun run build.ts",
897
- lint: "eslint src/ --ext .ts",
898
- typecheck: "tsc --noEmit --project tsconfig.typecheck.json",
899
- test: "bun test",
900
- smoke: "bun test test/smoke/ test/smoke-invariants.test.ts",
901
- "envelope-diff": "bun test test/envelope-diff.test.ts test/envelope-diff-invariants.test.ts",
902
- "prepare-platforms": "bun run scripts/prepare-platforms.ts",
903
- "stage-skill": "bun run scripts/stage-skill.ts",
904
- prepack: "bun run build && bun run scripts/stage-skill.ts",
905
- postinstall: "bun run scripts/postinstall.ts",
906
- "version-bump-publish": "bun run scripts/version-bump.ts",
907
- prepublishOnly: "bun run scripts/prepublish-guards.ts",
908
- "verify-installed-pkg": "bun run scripts/verify-installed-pkg.ts"
909
- },
910
- optionalDependencies: {
911
- "@agent-director/linux-x64": "^0.6.2",
912
- "@agent-director/darwin-arm64": "^0.6.2"
913
- },
914
- devDependencies: {
915
- typescript: ">=5.2.0",
916
- "bun-types": "latest",
917
- eslint: "^8.0.0",
918
- "@typescript-eslint/parser": "^7.0.0",
919
- "@typescript-eslint/eslint-plugin": "^7.0.0"
920
- }
921
- };
922
1231
 
923
1232
  // src/internal/subprocessClient.ts
924
1233
  var DEFAULT_CALL_TIMEOUT_MS = 30000;
925
- var SIGKILL_GRACE_MS = 2000;
926
- var NPM_PACKAGE_VERSION = package_default.version;
1234
+ var SIGKILL_GRACE_MS2 = 2000;
1235
+ async function loadNpmPackageVersion() {
1236
+ try {
1237
+ const url = import.meta.resolve("agent-director/package.json");
1238
+ const json = await readFile(new URL(url), "utf8");
1239
+ return JSON.parse(json).version;
1240
+ } catch {
1241
+ const url = new URL("../../package.json", import.meta.url);
1242
+ const json = await readFile(url, "utf8");
1243
+ return JSON.parse(json).version;
1244
+ }
1245
+ }
927
1246
 
928
1247
  class SubprocessClient {
929
- #cliPathOverride;
1248
+ #binaryPath;
1249
+ #binaryVersion;
930
1250
  #callTimeoutMs;
931
1251
  #logger;
932
1252
  #open;
933
1253
  #globalOpts;
934
1254
  _handle = null;
935
1255
  #tail;
936
- constructor(opts) {
1256
+ #npmPkgVersion;
1257
+ constructor(opts, init) {
937
1258
  const rawTimeout = opts.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
938
1259
  if (rawTimeout <= 0) {
939
1260
  throw new Error(`ClientOptions.callTimeoutMs must be positive (got ${rawTimeout}); ` + `omit the field to use the default (${DEFAULT_CALL_TIMEOUT_MS} ms)`);
940
1261
  }
941
1262
  this.#callTimeoutMs = rawTimeout;
942
1263
  this.#logger = opts.logger;
943
- const opts2 = opts;
944
- if (opts2._cliPath !== undefined) {
945
- this.#cliPathOverride = opts2._cliPath;
946
- } else {
947
- resolveCliPath();
948
- this.#cliPathOverride = undefined;
949
- }
1264
+ this.#binaryPath = init.binaryPath;
1265
+ this.#binaryVersion = init.binaryVersion;
950
1266
  const g = {};
951
1267
  if (opts.storePath !== undefined)
952
1268
  g.storePath = expandTilde(opts.storePath);
@@ -958,6 +1274,15 @@ class SubprocessClient {
958
1274
  this.#open = true;
959
1275
  this.#tail = Promise.resolve();
960
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
+ }
961
1286
  close() {
962
1287
  this.#open = false;
963
1288
  }
@@ -989,7 +1314,7 @@ class SubprocessClient {
989
1314
  return callPromise;
990
1315
  }
991
1316
  async#doCall(verb, params) {
992
- const cliPath = this.#cliPathOverride ?? resolveCliPath();
1317
+ const cliPath = this.#binaryPath;
993
1318
  const argv = buildArgv(cliPath, verb, params, this.#globalOpts);
994
1319
  const startMs = Date.now();
995
1320
  const spawnEnv = { ...process.env };
@@ -1008,7 +1333,7 @@ class SubprocessClient {
1008
1333
  proc.kill("SIGTERM");
1009
1334
  const gracefulHandle = setTimeout(() => {
1010
1335
  proc.kill("SIGKILL");
1011
- }, SIGKILL_GRACE_MS);
1336
+ }, SIGKILL_GRACE_MS2);
1012
1337
  proc.exited.then(() => clearTimeout(gracefulHandle), () => clearTimeout(gracefulHandle));
1013
1338
  }, this.#callTimeoutMs);
1014
1339
  let stdoutText;
@@ -1127,13 +1452,90 @@ class SubprocessClient {
1127
1452
  }
1128
1453
  async version(params) {
1129
1454
  this.#assertOpen();
1455
+ if (this.#npmPkgVersion === undefined) {
1456
+ this.#npmPkgVersion = await loadNpmPackageVersion();
1457
+ }
1130
1458
  const cliResp = await this.#enqueue("version", params);
1131
- return { ...cliResp, version: NPM_PACKAGE_VERSION };
1459
+ return { ...cliResp, version: this.#npmPkgVersion };
1460
+ }
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);
1132
1532
  }
1533
+ return { path: binaryPath, version: probe.version };
1133
1534
  }
1134
1535
  export {
1536
+ resolveSystemBinary,
1135
1537
  errorFromEnvelope,
1136
- ErrUnsupportedPlatform,
1538
+ MIN_BINARY_VERSION,
1137
1539
  ErrUnknownErrorName,
1138
1540
  ErrTmuxSessionNameTooLong,
1139
1541
  ErrTmuxSessionNameInvalid,
@@ -1146,6 +1548,9 @@ export {
1146
1548
  ErrTemplateNameUnsafe,
1147
1549
  ErrTemplateMalformed,
1148
1550
  ErrTemplateExists,
1551
+ ErrSystemInstallUnreachable,
1552
+ ErrSystemInstallTooOld,
1553
+ ErrSystemInstallNotFound,
1149
1554
  ErrSpawnNotResumable,
1150
1555
  ErrSpawnNotPausable,
1151
1556
  ErrSpawnNotInteractive,
@@ -1156,7 +1561,6 @@ export {
1156
1561
  ErrRelayModeOff,
1157
1562
  ErrRelayModeInvalid,
1158
1563
  ErrProbeUnsupported,
1159
- ErrPlatformPackageMissing,
1160
1564
  ErrPermissionRequestNotFound,
1161
1565
  ErrPauseTimeout,
1162
1566
  ErrNoSessionId,
@@ -1173,11 +1577,11 @@ export {
1173
1577
  ErrCwdMissing,
1174
1578
  ErrConsumerSignal,
1175
1579
  ErrClientClosed,
1176
- ErrCliNotExecutable,
1177
1580
  ErrCallTimeout,
1178
1581
  ErrBunVersionTooOld,
1179
1582
  ErrAmbiguousRequest,
1180
1583
  ErrAlreadyDecided,
1181
- SubprocessClient as Client,
1584
+ DEV_SENTINEL_VERSION,
1585
+ Client,
1182
1586
  AgentDirectorError
1183
1587
  };