agent-director 0.4.5 → 0.5.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/dist/index.js CHANGED
@@ -1,25 +1,84 @@
1
1
  // @bun
2
- // src/internal/tilde.ts
3
- import * as os from "os";
4
- function expandTilde(p) {
5
- if (p === "")
6
- return "";
7
- if (p !== "~" && !p.startsWith("~/"))
8
- return p;
9
- const home = process.env["HOME"] ?? os.homedir();
10
- if (p === "~")
11
- return home;
12
- return home + p.slice(1);
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
13
6
  }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
14
16
 
15
- // src/internal/bootstrapFfi.ts
16
- import { dlopen as dlopen2, FFIType as FFIType2, CString, ptr } from "bun:ffi";
17
-
18
- // src/platform.ts
19
- import { existsSync } from "fs";
17
+ // src/internal/platformResolve.ts
18
+ import { statSync } from "fs";
20
19
  import { fileURLToPath } from "url";
21
20
  import { join, dirname } from "path";
22
- import { dlopen } from "bun:ffi";
21
+
22
+ // src/errors.ts
23
+ var exports_errors = {};
24
+ __export(exports_errors, {
25
+ errorFromEnvelope: () => errorFromEnvelope,
26
+ TS_ONLY_ERROR_NAMES: () => TS_ONLY_ERROR_NAMES,
27
+ ErrUnsupportedPlatform: () => ErrUnsupportedPlatform,
28
+ ErrUnknownErrorName: () => ErrUnknownErrorName,
29
+ ErrTmuxSessionNameTooLong: () => ErrTmuxSessionNameTooLong,
30
+ ErrTmuxSessionNameInvalid: () => ErrTmuxSessionNameInvalid,
31
+ ErrTmuxSessionNameEmpty: () => ErrTmuxSessionNameEmpty,
32
+ ErrTmuxSessionCreate: () => ErrTmuxSessionCreate,
33
+ ErrTmuxSendKeys: () => ErrTmuxSendKeys,
34
+ ErrTmuxNotAvailable: () => ErrTmuxNotAvailable,
35
+ ErrTmuxCaptureFailed: () => ErrTmuxCaptureFailed,
36
+ ErrTemplateNotFound: () => ErrTemplateNotFound,
37
+ ErrTemplateNameUnsafe: () => ErrTemplateNameUnsafe,
38
+ ErrTemplateMalformed: () => ErrTemplateMalformed,
39
+ ErrTemplateExists: () => ErrTemplateExists,
40
+ ErrSpawnNotResumable: () => ErrSpawnNotResumable,
41
+ ErrSpawnNotPausable: () => ErrSpawnNotPausable,
42
+ ErrSpawnNotInteractive: () => ErrSpawnNotInteractive,
43
+ ErrSpawnNotFound: () => ErrSpawnNotFound,
44
+ ErrSpawnDeniedFlag: () => ErrSpawnDeniedFlag,
45
+ ErrSendKeysWhileRelayed: () => ErrSendKeysWhileRelayed,
46
+ ErrReservedEnvKey: () => ErrReservedEnvKey,
47
+ ErrRelayModeOff: () => ErrRelayModeOff,
48
+ ErrRelayModeInvalid: () => ErrRelayModeInvalid,
49
+ ErrProbeUnsupported: () => ErrProbeUnsupported,
50
+ ErrPlatformPackageMissing: () => ErrPlatformPackageMissing,
51
+ ErrPauseTimeout: () => ErrPauseTimeout,
52
+ ErrNoSessionId: () => ErrNoSessionId,
53
+ ErrNoOpenPermissionRequest: () => ErrNoOpenPermissionRequest,
54
+ ErrListInvalidLabel: () => ErrListInvalidLabel,
55
+ ErrJsonlMissing: () => ErrJsonlMissing,
56
+ ErrInvalidDecision: () => ErrInvalidDecision,
57
+ ErrInstanceIdCollision: () => ErrInstanceIdCollision,
58
+ ErrCwdNotFound: () => ErrCwdNotFound,
59
+ ErrCwdNotAPath: () => ErrCwdNotAPath,
60
+ ErrCwdNotADirectory: () => ErrCwdNotADirectory,
61
+ ErrCwdMissing: () => ErrCwdMissing,
62
+ ErrConsumerSignal: () => ErrConsumerSignal,
63
+ ErrClientClosed: () => ErrClientClosed,
64
+ ErrCliNotExecutable: () => ErrCliNotExecutable,
65
+ ErrCallTimeout: () => ErrCallTimeout,
66
+ ErrBunVersionTooOld: () => ErrBunVersionTooOld,
67
+ ErrAlreadyDecided: () => ErrAlreadyDecided,
68
+ AgentDirectorError: () => AgentDirectorError
69
+ });
70
+
71
+ // src/internal/tsOnlyErrors.ts
72
+ var TS_ONLY_ERROR_NAMES = [
73
+ "ErrClientClosed",
74
+ "ErrUnsupportedPlatform",
75
+ "ErrPlatformPackageMissing",
76
+ "ErrBunVersionTooOld",
77
+ "ErrCliNotExecutable",
78
+ "ErrConsumerSignal",
79
+ "ErrCallTimeout",
80
+ "ErrUnknownErrorName"
81
+ ];
23
82
 
24
83
  // src/errors.ts
25
84
  class AgentDirectorError extends Error {
@@ -69,6 +128,48 @@ class ErrBunVersionTooOld extends AgentDirectorError {
69
128
  }
70
129
  }
71
130
 
131
+ class ErrCliNotExecutable extends AgentDirectorError {
132
+ constructor(path) {
133
+ super("", "ErrCliNotExecutable", `binary "${path}" exists but lacks execute permission; check file mode (chmod +x)`);
134
+ this.name = "ErrCliNotExecutable";
135
+ Object.setPrototypeOf(this, new.target.prototype);
136
+ }
137
+ }
138
+
139
+ class ErrConsumerSignal extends AgentDirectorError {
140
+ signal;
141
+ constructor(verb, signal) {
142
+ super(verb, "ErrConsumerSignal", `subprocess was killed by signal ${signal}`);
143
+ this.signal = signal;
144
+ this.name = "ErrConsumerSignal";
145
+ Object.setPrototypeOf(this, new.target.prototype);
146
+ }
147
+ }
148
+
149
+ class ErrCallTimeout extends AgentDirectorError {
150
+ elapsedMs;
151
+ timeoutMs;
152
+ constructor(verb, elapsedMs, timeoutMs) {
153
+ super(verb, "ErrCallTimeout", `call timed out after ${elapsedMs}ms (configured limit: ${timeoutMs}ms)`);
154
+ this.elapsedMs = elapsedMs;
155
+ this.timeoutMs = timeoutMs;
156
+ this.name = "ErrCallTimeout";
157
+ Object.setPrototypeOf(this, new.target.prototype);
158
+ }
159
+ }
160
+
161
+ class ErrUnknownErrorName extends AgentDirectorError {
162
+ unknownName;
163
+ envelope;
164
+ constructor(unknownName, envelope) {
165
+ super("", "ErrUnknownErrorName", `unknown err_name "${unknownName}" in subprocess envelope; TS catalog may be out of sync with Go catalog`);
166
+ this.unknownName = unknownName;
167
+ this.envelope = envelope;
168
+ this.name = "ErrUnknownErrorName";
169
+ Object.setPrototypeOf(this, new.target.prototype);
170
+ }
171
+ }
172
+
72
173
  class ErrCwdMissing extends AgentDirectorError {
73
174
  }
74
175
 
@@ -167,9 +268,6 @@ class ErrNoOpenPermissionRequest extends AgentDirectorError {
167
268
 
168
269
  class ErrAlreadyDecided extends AgentDirectorError {
169
270
  }
170
-
171
- class ErrUnknownHandle extends AgentDirectorError {
172
- }
173
271
  var ERROR_TABLE = {
174
272
  ErrCwdMissing,
175
273
  ErrCwdNotAPath,
@@ -203,8 +301,7 @@ var ERROR_TABLE = {
203
301
  ErrTemplateNotFound,
204
302
  ErrTemplateMalformed,
205
303
  ErrTemplateExists,
206
- ErrProbeUnsupported,
207
- ErrUnknownHandle
304
+ ErrProbeUnsupported
208
305
  };
209
306
  function errorFromEnvelope(verb, err_name, err_description) {
210
307
  const Ctor = ERROR_TABLE[err_name];
@@ -215,58 +312,7 @@ function errorFromEnvelope(verb, err_name, err_description) {
215
312
  return new AgentDirectorError(verb, err_name, err_description);
216
313
  }
217
314
 
218
- // src/internal/bindingSpec.ts
219
- import { FFIType } from "bun:ffi";
220
-
221
- // src/internal/verbs.ts
222
- var VERBS = [
223
- "spawn",
224
- "status",
225
- "get",
226
- "send-keys",
227
- "read-pane",
228
- "kill",
229
- "decide",
230
- "resume",
231
- "find-missing",
232
- "expire",
233
- "delete",
234
- "make-template",
235
- "list",
236
- "pause",
237
- "version"
238
- ];
239
- function kebabToUnderscore(v) {
240
- return v.replace(/-/g, "_");
241
- }
242
- var HANDLE_FREE_VERBS = new Set(["version"]);
243
- function isHandleFree(verb) {
244
- return HANDLE_FREE_VERBS.has(verb);
245
- }
246
-
247
- // src/internal/bindingSpec.ts
248
- var BINDING_SYMBOL_NAMES = [
249
- "ad_open",
250
- "ad_close",
251
- "ad_free_cstring",
252
- ...VERBS.map((v) => "ad_" + kebabToUnderscore(v))
253
- ];
254
- function buildBindingSpec() {
255
- const spec = {
256
- ad_open: { args: [FFIType.cstring], returns: FFIType.ptr },
257
- ad_close: { args: [FFIType.cstring], returns: FFIType.ptr },
258
- ad_free_cstring: { args: [FFIType.ptr], returns: FFIType.void }
259
- };
260
- for (const verb of VERBS) {
261
- spec["ad_" + kebabToUnderscore(verb)] = {
262
- args: [FFIType.cstring],
263
- returns: FFIType.ptr
264
- };
265
- }
266
- return spec;
267
- }
268
-
269
- // src/platform.ts
315
+ // src/internal/platformResolve.ts
270
316
  var MIN_BUN_VERSION = "1.0.21";
271
317
  var SUPPORTED_TUPLES = new Map([
272
318
  ["linux-x64", "@agent-director/linux-x64"],
@@ -283,318 +329,750 @@ function compareSemver(a, b) {
283
329
  }
284
330
  return 0;
285
331
  }
286
- function resolveNativePath(opts = {}) {
287
- const platform = opts.platform ?? process.platform;
288
- const arch = opts.arch ?? process.arch;
289
- const bunVersion = opts.bunVersion ?? Bun.version;
290
- if (compareSemver(bunVersion, MIN_BUN_VERSION) < 0) {
291
- throw new ErrBunVersionTooOld(bunVersion, MIN_BUN_VERSION);
332
+ function resolveCliPath(opts) {
333
+ const platform = opts?.platform ?? process.platform;
334
+ const arch = opts?.arch ?? process.arch;
335
+ if (compareSemver(Bun.version, MIN_BUN_VERSION) < 0) {
336
+ throw new ErrBunVersionTooOld(Bun.version, MIN_BUN_VERSION);
292
337
  }
293
338
  const tuple = `${platform}-${arch}`;
294
339
  const subpkgName = SUPPORTED_TUPLES.get(tuple);
295
- if (!subpkgName) {
340
+ if (subpkgName === undefined) {
296
341
  throw new ErrUnsupportedPlatform(tuple);
297
342
  }
298
- const binaryExt = platform === "darwin" ? "dylib" : "so";
299
- const binaryName = `libagent_director.${binaryExt}`;
300
- const cabiDir = process.env.AD_CABI_DIR;
301
- if (cabiDir) {
302
- const cabiPath = join(cabiDir, binaryName);
303
- if (!existsSync(cabiPath)) {
304
- throw new ErrPlatformPackageMissing(subpkgName, `AD_CABI_DIR is set but "${binaryName}" not found in ${cabiDir}`);
343
+ let binPath;
344
+ if (opts?._requireResolve !== undefined) {
345
+ try {
346
+ binPath = opts._requireResolve(subpkgName);
347
+ } catch {
348
+ throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed (DI hook threw); run: npm install ${subpkgName}`);
305
349
  }
306
- return cabiPath;
350
+ } else {
351
+ let pkgDir;
352
+ try {
353
+ const pkgJsonUrl = import.meta.resolve(`${subpkgName}/package.json`);
354
+ pkgDir = dirname(fileURLToPath(pkgJsonUrl));
355
+ } catch {
356
+ throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed; run: npm install ${subpkgName}`);
357
+ }
358
+ binPath = join(pkgDir, "bin", "agent-director");
307
359
  }
308
- let pkgDir;
360
+ let stat;
309
361
  try {
310
- const resolved = import.meta.resolve(`${subpkgName}/package.json`);
311
- pkgDir = dirname(fileURLToPath(resolved));
362
+ stat = statSync(binPath);
312
363
  } catch {
313
- throw new ErrPlatformPackageMissing(subpkgName);
364
+ throw new ErrPlatformPackageMissing(subpkgName, `binary not found at "${binPath}"`);
365
+ }
366
+ const mode = stat.mode;
367
+ const fileUid = stat.uid;
368
+ const fileGid = stat.gid;
369
+ const myUid = process.getuid?.() ?? 0;
370
+ const myGid = process.getgid?.() ?? 0;
371
+ const execByOwner = (mode & 64) !== 0;
372
+ const execByGroup = (mode & 8) !== 0;
373
+ const execByOther = (mode & 1) !== 0;
374
+ const isExecutable = fileUid === myUid && execByOwner || fileGid === myGid && execByGroup || execByOther;
375
+ if (!isExecutable) {
376
+ throw new ErrCliNotExecutable(binPath);
377
+ }
378
+ return binPath;
379
+ }
380
+
381
+ // src/internal/tilde.ts
382
+ import * as os from "os";
383
+ function expandTilde(p) {
384
+ if (p === "")
385
+ return "";
386
+ if (p !== "~" && !p.startsWith("~/"))
387
+ return p;
388
+ const home = process.env["HOME"] ?? os.homedir();
389
+ if (p === "~")
390
+ return home;
391
+ return home + p.slice(1);
392
+ }
393
+
394
+ // src/internal/argv.ts
395
+ function buildArgv(cliPath, verb, params, globalOpts) {
396
+ const globalFlags = buildGlobalFlags(globalOpts);
397
+ const verbFlags = buildVerbFlags(verb, params);
398
+ return [cliPath, ...globalFlags, ...verbFlags];
399
+ }
400
+ function buildGlobalFlags(opts) {
401
+ if (!opts)
402
+ return [];
403
+ const f = [];
404
+ if (opts.storePath !== undefined)
405
+ f.push("--store-path", opts.storePath);
406
+ if (opts.home !== undefined)
407
+ f.push("--home", opts.home);
408
+ if (opts.tmuxCommand !== undefined)
409
+ f.push("--tmux-command", opts.tmuxCommand);
410
+ return f;
411
+ }
412
+ function buildVerbFlags(verb, params) {
413
+ switch (verb) {
414
+ case "version":
415
+ return buildVersion();
416
+ case "spawn":
417
+ return buildSpawn(params);
418
+ case "status":
419
+ return buildStatus(params);
420
+ case "get":
421
+ return buildGet(params);
422
+ case "send-keys":
423
+ return buildSendKeys(params);
424
+ case "read-pane":
425
+ return buildReadPane(params);
426
+ case "kill":
427
+ return buildKill(params);
428
+ case "decide":
429
+ return buildDecide(params);
430
+ case "resume":
431
+ return buildResume(params);
432
+ case "find-missing":
433
+ return buildFindMissing();
434
+ case "expire":
435
+ return buildExpire(params);
436
+ case "delete":
437
+ return buildDelete(params);
438
+ case "make-template":
439
+ return buildMakeTemplate(params);
440
+ case "list":
441
+ return buildList(params);
442
+ case "pause":
443
+ return buildPause(params);
444
+ default: {
445
+ const _exhaustive = verb;
446
+ throw new Error(`buildVerbFlags: unhandled verb "${String(_exhaustive)}"`);
447
+ }
448
+ }
449
+ }
450
+ function buildVersion() {
451
+ return ["version"];
452
+ }
453
+ function buildSpawn(p) {
454
+ const f = ["spawn"];
455
+ f.push("--cwd", p.cwd);
456
+ if (p.template !== undefined)
457
+ f.push("--template", p.template);
458
+ if (p.claude_instance_id !== undefined)
459
+ f.push("--claude-instance-id", p.claude_instance_id);
460
+ if (p.tmux_session_name !== undefined)
461
+ f.push("--tmux-session-name", p.tmux_session_name);
462
+ if (p.relay_mode !== undefined && p.relay_mode !== "")
463
+ f.push("--relay-mode", p.relay_mode);
464
+ if (p.no_pre_trust === true)
465
+ f.push("--no-pre-trust");
466
+ if (p.label) {
467
+ for (const lv of p.label)
468
+ f.push("--label", lv);
469
+ }
470
+ if (p.extra_env) {
471
+ for (const [k, v] of Object.entries(p.extra_env))
472
+ f.push("--extra-env", `${k}=${v}`);
473
+ }
474
+ if (p.allow) {
475
+ for (const a of p.allow)
476
+ f.push("--allow", a);
477
+ }
478
+ if (p.deny) {
479
+ for (const d of p.deny)
480
+ f.push("--deny", d);
481
+ }
482
+ if (p.ask) {
483
+ for (const a of p.ask)
484
+ f.push("--ask", a);
485
+ }
486
+ if (p.claude_args && p.claude_args.length > 0) {
487
+ f.push("--", ...p.claude_args);
488
+ }
489
+ return f;
490
+ }
491
+ function buildStatus(p) {
492
+ return ["status", "--claude-instance-id", p.claude_instance_id];
493
+ }
494
+ function buildGet(p) {
495
+ return ["get", "--claude-instance-id", p.claude_instance_id];
496
+ }
497
+ function buildSendKeys(p) {
498
+ return [
499
+ "send-keys",
500
+ "--claude-instance-id",
501
+ p.claude_instance_id,
502
+ "--text",
503
+ p.text
504
+ ];
505
+ }
506
+ function buildReadPane(p) {
507
+ const f = ["read-pane", "--claude-instance-id", p.claude_instance_id];
508
+ if (p.n_lines !== undefined && p.n_lines > 0)
509
+ f.push("--n-lines", String(p.n_lines));
510
+ if (p.ansi === true)
511
+ f.push("--ansi");
512
+ return f;
513
+ }
514
+ function buildKill(p) {
515
+ return ["kill", "--claude-instance-id", p.claude_instance_id];
516
+ }
517
+ function buildDecide(p) {
518
+ const f = [
519
+ "decide",
520
+ "--claude-instance-id",
521
+ p.claude_instance_id,
522
+ "--decision",
523
+ p.decision
524
+ ];
525
+ if (p.reason !== undefined)
526
+ f.push("--reason", p.reason);
527
+ return f;
528
+ }
529
+ function buildResume(p) {
530
+ return ["resume", "--claude-instance-id", p.claude_instance_id];
531
+ }
532
+ function buildFindMissing() {
533
+ return ["find-missing"];
534
+ }
535
+ function buildExpire(p) {
536
+ const f = ["expire"];
537
+ if (p.older_than !== undefined)
538
+ f.push("--older-than", p.older_than);
539
+ return f;
540
+ }
541
+ function buildDelete(p) {
542
+ const f = ["delete"];
543
+ for (const id of p.claude_instance_id)
544
+ f.push("--claude-instance-id", id);
545
+ return f;
546
+ }
547
+ function buildMakeTemplate(p) {
548
+ const f = ["make-template", "--name", p.name];
549
+ if (p.cwd !== undefined)
550
+ f.push("--cwd", p.cwd);
551
+ if (p.relay_mode !== undefined && p.relay_mode !== "")
552
+ f.push("--relay-mode", p.relay_mode);
553
+ if (p.overwrite === true)
554
+ f.push("--overwrite");
555
+ if (p.label) {
556
+ for (const lv of p.label)
557
+ f.push("--label", lv);
558
+ }
559
+ if (p.extra_env) {
560
+ for (const [k, v] of Object.entries(p.extra_env))
561
+ f.push("--extra-env", `${k}=${v}`);
562
+ }
563
+ if (p.allow) {
564
+ for (const a of p.allow)
565
+ f.push("--allow", a);
314
566
  }
315
- const libPath = join(pkgDir, binaryName);
316
- if (!existsSync(libPath)) {
317
- throw new ErrPlatformPackageMissing(subpkgName, `binary "${binaryName}" not found in package directory ${pkgDir}`);
567
+ if (p.deny) {
568
+ for (const d of p.deny)
569
+ f.push("--deny", d);
318
570
  }
319
- return libPath;
571
+ if (p.ask) {
572
+ for (const a of p.ask)
573
+ f.push("--ask", a);
574
+ }
575
+ if (p.claude_args) {
576
+ for (const a of p.claude_args)
577
+ f.push("--claude-args", a);
578
+ }
579
+ return f;
320
580
  }
321
- function _loadNativeInternal(opts = {}) {
322
- const libPath = resolveNativePath(opts);
323
- const bindingSpec = buildBindingSpec();
324
- const loaded = dlopen(libPath, bindingSpec);
325
- return { lib: loaded.symbols, libPath };
581
+ function buildList(p) {
582
+ const f = ["list"];
583
+ if (p.state && p.state.length > 0)
584
+ f.push("--state", p.state.join(","));
585
+ if (p.label) {
586
+ for (const lv of p.label)
587
+ f.push("--label", lv);
588
+ }
589
+ if (p.parent !== undefined)
590
+ f.push("--parent", p.parent);
591
+ if (p.cwd !== undefined)
592
+ f.push("--cwd", p.cwd);
593
+ if (p.tmux_session_name !== undefined)
594
+ f.push("--tmux-session-name", p.tmux_session_name);
595
+ if (p.limit !== undefined && p.limit > 0)
596
+ f.push("--limit", String(p.limit));
597
+ return f;
326
598
  }
327
- function loadNative() {
328
- return _loadNativeInternal();
599
+ function buildPause(p) {
600
+ return ["pause", "--claude-instance-id", p.claude_instance_id];
329
601
  }
330
602
 
331
- // src/internal/bootstrapFfi.ts
332
- var _soPath = resolveNativePath();
333
- var _lib = dlopen2(_soPath, {
334
- ad_open: {
335
- args: [FFIType2.cstring],
336
- returns: FFIType2.ptr
603
+ // src/internal/spawner.ts
604
+ class ErrSubprocessCrash extends Error {
605
+ exitCode;
606
+ signalCode;
607
+ stderrFull;
608
+ constructor(exitCode, signalCode, stderrFull) {
609
+ const reason = signalCode !== null ? `killed by signal ${signalCode}` : `exited with code ${exitCode ?? "null"}`;
610
+ const snippet = stderrFull.slice(0, 1024);
611
+ super(`subprocess ${reason}${snippet ? `; stderr: ${snippet}` : ""}`);
612
+ this.exitCode = exitCode;
613
+ this.signalCode = signalCode;
614
+ this.stderrFull = stderrFull;
615
+ this.name = "ErrSubprocessCrash";
616
+ Object.setPrototypeOf(this, new.target.prototype);
617
+ }
618
+ }
619
+
620
+ // ../api/errnames/catalog.json
621
+ var catalog_default = [
622
+ {
623
+ name: "ErrCwdMissing",
624
+ package: "spawn",
625
+ description: ""
626
+ },
627
+ {
628
+ name: "ErrCwdNotAPath",
629
+ package: "spawn",
630
+ description: ""
631
+ },
632
+ {
633
+ name: "ErrCwdNotFound",
634
+ package: "spawn",
635
+ description: ""
636
+ },
637
+ {
638
+ name: "ErrCwdNotADirectory",
639
+ package: "spawn",
640
+ description: ""
641
+ },
642
+ {
643
+ name: "ErrRelayModeInvalid",
644
+ package: "spawn",
645
+ description: ""
646
+ },
647
+ {
648
+ name: "ErrSpawnDeniedFlag",
649
+ package: "spawn",
650
+ description: ""
651
+ },
652
+ {
653
+ name: "ErrReservedEnvKey",
654
+ package: "spawn",
655
+ description: ""
656
+ },
657
+ {
658
+ name: "ErrInstanceIdCollision",
659
+ package: "spawn",
660
+ description: ""
661
+ },
662
+ {
663
+ name: "ErrTmuxSessionNameEmpty",
664
+ package: "spawn",
665
+ description: ""
666
+ },
667
+ {
668
+ name: "ErrTmuxSessionNameInvalid",
669
+ package: "spawn",
670
+ description: ""
671
+ },
672
+ {
673
+ name: "ErrTmuxSessionNameTooLong",
674
+ package: "spawn",
675
+ description: ""
676
+ },
677
+ {
678
+ name: "ErrSpawnNotFound",
679
+ package: "store",
680
+ description: ""
681
+ },
682
+ {
683
+ name: "ErrTmuxNotAvailable",
684
+ package: "tmux",
685
+ description: ""
686
+ },
687
+ {
688
+ name: "ErrTmuxSessionCreate",
689
+ package: "tmux",
690
+ description: ""
691
+ },
692
+ {
693
+ name: "ErrTmuxSendKeys",
694
+ package: "tmux",
695
+ description: ""
696
+ },
697
+ {
698
+ name: "ErrTmuxCaptureFailed",
699
+ package: "tmux",
700
+ description: ""
337
701
  },
338
- ad_close: {
339
- args: [FFIType2.cstring],
340
- returns: FFIType2.ptr
702
+ {
703
+ name: "ErrSpawnNotInteractive",
704
+ package: "api",
705
+ description: ""
341
706
  },
342
- ad_free_cstring: {
343
- args: [FFIType2.ptr],
344
- returns: FFIType2.void
707
+ {
708
+ name: "ErrSendKeysWhileRelayed",
709
+ package: "api",
710
+ description: ""
711
+ },
712
+ {
713
+ name: "ErrSpawnNotPausable",
714
+ package: "api",
715
+ description: ""
716
+ },
717
+ {
718
+ name: "ErrPauseTimeout",
719
+ package: "api",
720
+ description: ""
721
+ },
722
+ {
723
+ name: "ErrListInvalidLabel",
724
+ package: "api",
725
+ description: ""
726
+ },
727
+ {
728
+ name: "ErrTemplateNameUnsafe",
729
+ package: "config",
730
+ description: ""
731
+ },
732
+ {
733
+ name: "ErrTemplateNotFound",
734
+ package: "config",
735
+ description: ""
736
+ },
737
+ {
738
+ name: "ErrTemplateMalformed",
739
+ package: "config",
740
+ description: ""
741
+ },
742
+ {
743
+ name: "ErrTemplateExists",
744
+ package: "config",
745
+ description: ""
746
+ },
747
+ {
748
+ name: "ErrProbeUnsupported",
749
+ package: "probe",
750
+ description: ""
751
+ },
752
+ {
753
+ name: "ErrSpawnNotResumable",
754
+ package: "api",
755
+ description: ""
756
+ },
757
+ {
758
+ name: "ErrNoSessionId",
759
+ package: "api",
760
+ description: ""
761
+ },
762
+ {
763
+ name: "ErrJsonlMissing",
764
+ package: "api",
765
+ description: ""
766
+ },
767
+ {
768
+ name: "ErrRelayModeOff",
769
+ package: "api",
770
+ description: ""
771
+ },
772
+ {
773
+ name: "ErrInvalidDecision",
774
+ package: "api",
775
+ description: ""
776
+ },
777
+ {
778
+ name: "ErrNoOpenPermissionRequest",
779
+ package: "store",
780
+ description: ""
781
+ },
782
+ {
783
+ name: "ErrAlreadyDecided",
784
+ package: "store",
785
+ description: ""
345
786
  }
346
- });
347
- function callOpen(params) {
348
- const jsonBytes = Buffer.from(JSON.stringify(params) + "\x00");
349
- const rawPtr = _lib.symbols.ad_open(ptr(jsonBytes));
350
- return _readAndFree(rawPtr);
351
- }
352
- function callClose(params) {
353
- const jsonBytes = Buffer.from(JSON.stringify(params) + "\x00");
354
- const rawPtr = _lib.symbols.ad_close(ptr(jsonBytes));
355
- return _readAndFree(rawPtr);
356
- }
357
- function _readAndFree(rawPtr) {
358
- if (rawPtr === null || rawPtr === 0) {
359
- throw new Error("bootstrapFfi: ad_* returned a null pointer");
360
- }
361
- const result = new CString(rawPtr).toString();
362
- _lib.symbols.ad_free_cstring(rawPtr);
363
- return result;
364
- }
365
-
366
- // src/internal/workerProxy.ts
367
- import { Worker } from "worker_threads";
368
- function isErrorEnvelope(v) {
369
- return typeof v === "object" && v !== null && typeof v.err_name === "string";
370
- }
371
- var _worker = null;
372
- var _nextId = 1;
373
- var _pending = new Map;
374
- var _readyResolve = null;
375
- var _readyReject = null;
376
- var _readyPromise = null;
377
- function _rejectAll(reason) {
378
- for (const entry of _pending.values()) {
379
- entry.reject(reason);
380
- }
381
- _pending.clear();
382
- }
383
- function _resolveWorkerURL() {
384
- return import.meta.url.endsWith("workerProxy.ts") ? new URL("./worker.ts", import.meta.url) : new URL("./internal/worker.js", import.meta.url);
385
- }
386
- function _spawnWorker() {
387
- const worker = new Worker(_resolveWorkerURL());
388
- if (typeof worker.unref === "function") {
389
- worker.unref();
390
- }
391
- _readyPromise = new Promise((resolve, reject) => {
392
- _readyResolve = resolve;
393
- _readyReject = reject;
394
- });
395
- worker.on("message", (msg) => {
396
- if (msg.type === "ready") {
397
- _readyResolve?.();
398
- _readyResolve = null;
399
- _readyReject = null;
400
- return;
401
- }
402
- if (msg.type === "startup-error") {
403
- const err = new Error(`agent-director worker failed to start: ${msg.message ?? "(unknown)"}`);
404
- _readyReject?.(err);
405
- _readyResolve = null;
406
- _readyReject = null;
407
- _rejectAll(err);
408
- return;
409
- }
410
- const entry = _pending.get(msg.id);
411
- if (!entry)
412
- return;
413
- _pending.delete(msg.id);
414
- if (msg.type === "ffi-error") {
415
- entry.reject(new Error(`FFI error: ${msg.message ?? "(unknown)"}`));
416
- return;
417
- }
418
- const jsonString = msg.jsonString ?? "";
419
- let parsed;
420
- try {
421
- parsed = JSON.parse(jsonString);
422
- } catch (e) {
423
- entry.reject(new Error(`Failed to parse C-ABI response JSON: ${e instanceof Error ? e.message : String(e)}`));
424
- return;
425
- }
426
- if (isErrorEnvelope(parsed)) {
427
- entry.reject(errorFromEnvelope(entry.op, parsed.err_name, parsed.err_description));
428
- return;
429
- }
430
- entry.resolve(parsed);
431
- });
432
- worker.on("error", (err) => {
433
- const reason = new Error(`agent-director worker error: ${err.message}`);
434
- _readyReject?.(reason);
435
- _readyResolve = null;
436
- _readyReject = null;
437
- _rejectAll(reason);
438
- });
439
- worker.on("exit", (code) => {
440
- const reason = new Error(`agent-director worker exited with code ${code}`);
441
- _readyReject?.(reason);
442
- _readyResolve = null;
443
- _readyReject = null;
444
- if (_pending.size > 0) {
445
- _rejectAll(reason);
787
+ ];
788
+
789
+ // src/internal/errorMap.ts
790
+ var _catalog = catalog_default;
791
+ var errorMap = new Map(_catalog.flatMap((entry) => {
792
+ const errorsRecord = exports_errors;
793
+ const Ctor = errorsRecord[entry.name];
794
+ if (typeof Ctor !== "function") {
795
+ return [];
796
+ }
797
+ return [[entry.name, Ctor]];
798
+ }));
799
+ function isErrorEnvelope(envelope) {
800
+ return typeof envelope === "object" && envelope !== null && "err_name" in envelope && typeof envelope.err_name === "string";
801
+ }
802
+ function throwFromEnvelope(verb, envelope) {
803
+ const env = envelope;
804
+ const errName = env.err_name;
805
+ const envelopeRecord = envelope;
806
+ const errDescription = typeof envelopeRecord["err_description"] === "string" ? envelopeRecord["err_description"] : "";
807
+ const Ctor = errorMap.get(errName);
808
+ if (Ctor !== undefined) {
809
+ throw new Ctor(verb, errName, errDescription);
810
+ }
811
+ throw new ErrUnknownErrorName(errName, envelope);
812
+ }
813
+ // package.json
814
+ var package_default = {
815
+ name: "agent-director",
816
+ version: "0.5.1",
817
+ type: "module",
818
+ os: [
819
+ "linux",
820
+ "darwin"
821
+ ],
822
+ cpu: [
823
+ "x64",
824
+ "arm64"
825
+ ],
826
+ engines: {
827
+ bun: ">=1.0.21"
828
+ },
829
+ files: [
830
+ "dist/**/*.js",
831
+ "dist/**/*.d.ts",
832
+ "!dist/**/*.test.*",
833
+ "README.md",
834
+ "scripts/postinstall.ts",
835
+ "skills/install-agent-director/**"
836
+ ],
837
+ exports: {
838
+ ".": {
839
+ import: "./dist/index.js",
840
+ types: "./dist/index.d.ts"
446
841
  }
447
- _worker = null;
448
- _readyPromise = null;
449
- });
450
- _worker = worker;
451
- }
452
- async function _ensureWorker() {
453
- if (_worker === null) {
454
- _spawnWorker();
455
- }
456
- await _readyPromise;
457
- }
458
- var workerProxy = {
459
- async dispatch(op, handle, params) {
460
- await _ensureWorker();
461
- const id = _nextId++;
462
- const paramsJSON = JSON.stringify(params ?? {});
463
- return new Promise((resolve, reject) => {
464
- _pending.set(id, { resolve, reject, op });
465
- _worker.postMessage({ id, op, handle, paramsJSON });
466
- });
842
+ },
843
+ scripts: {
844
+ build: "bun run build.ts",
845
+ lint: "eslint src/ --ext .ts",
846
+ typecheck: "tsc --noEmit --project tsconfig.typecheck.json",
847
+ test: "bun test",
848
+ smoke: "bun test test/smoke/ test/smoke-invariants.test.ts",
849
+ "envelope-diff": "bun test test/envelope-diff.test.ts test/envelope-diff-invariants.test.ts",
850
+ "prepare-platforms": "bun run scripts/prepare-platforms.ts",
851
+ "stage-skill": "bun run scripts/stage-skill.ts",
852
+ prepack: "bun run build && bun run scripts/stage-skill.ts",
853
+ postinstall: "bun run scripts/postinstall.ts",
854
+ "version-bump-publish": "bun run scripts/version-bump.ts",
855
+ prepublishOnly: "bun run scripts/prepublish-guards.ts",
856
+ "verify-installed-pkg": "bun run scripts/verify-installed-pkg.ts"
857
+ },
858
+ optionalDependencies: {
859
+ "@agent-director/linux-x64": "^0.5.1",
860
+ "@agent-director/darwin-arm64": "^0.5.1"
861
+ },
862
+ devDependencies: {
863
+ typescript: ">=5.2.0",
864
+ "bun-types": "latest",
865
+ eslint: "^8.0.0",
866
+ "@typescript-eslint/parser": "^7.0.0",
867
+ "@typescript-eslint/eslint-plugin": "^7.0.0"
467
868
  }
468
869
  };
469
870
 
470
- // src/ffi.ts
471
- async function callVerb(verb, handle, params) {
472
- return workerProxy.dispatch(verb, handle, params);
473
- }
474
-
475
- // src/client.ts
476
- function isErrorEnvelope2(env) {
477
- return typeof env === "object" && env !== null && "err_name" in env && typeof env.err_name === "string";
478
- }
871
+ // src/internal/subprocessClient.ts
872
+ var DEFAULT_CALL_TIMEOUT_MS = 30000;
873
+ var SIGKILL_GRACE_MS = 2000;
874
+ var NPM_PACKAGE_VERSION = package_default.version;
479
875
 
480
- class Client {
481
- _handle;
482
- _open;
483
- _logger;
876
+ class SubprocessClient {
877
+ #cliPath;
878
+ #callTimeoutMs;
879
+ #logger;
880
+ #open;
881
+ #globalOpts;
882
+ _handle = null;
883
+ #tail;
484
884
  constructor(opts) {
485
- this._handle = null;
486
- this._open = false;
487
- this._logger = opts.logger;
488
- const storePath = expandTilde(opts.storePath);
489
- const configPath = opts.configPath !== undefined ? expandTilde(opts.configPath) : undefined;
490
- const params = { store_path: storePath };
491
- if (configPath !== undefined)
492
- params.config_path = configPath;
493
- if (opts.tmuxCommand !== undefined)
494
- params.tmux_command = opts.tmuxCommand;
495
- if (opts.createIfMissing !== undefined)
496
- params.create_if_missing = opts.createIfMissing;
497
- const envelopeJSON = callOpen(params);
498
- const env = JSON.parse(envelopeJSON);
499
- if (isErrorEnvelope2(env)) {
500
- throw errorFromEnvelope("open", env.err_name, env.err_description);
885
+ const rawTimeout = opts.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
886
+ if (rawTimeout <= 0) {
887
+ throw new Error(`ClientOptions.callTimeoutMs must be positive (got ${rawTimeout}); ` + `omit the field to use the default (${DEFAULT_CALL_TIMEOUT_MS} ms)`);
501
888
  }
502
- this._handle = env.handle;
503
- this._open = true;
889
+ this.#callTimeoutMs = rawTimeout;
890
+ this.#logger = opts.logger;
891
+ const opts2 = opts;
892
+ this.#cliPath = opts2._cliPath ?? resolveCliPath();
893
+ const g = {};
894
+ if (opts.storePath !== undefined)
895
+ g.storePath = expandTilde(opts.storePath);
896
+ if (opts.tmuxCommand !== undefined)
897
+ g.tmuxCommand = expandTilde(opts.tmuxCommand);
898
+ if (opts.home !== undefined)
899
+ g.home = expandTilde(opts.home);
900
+ this.#globalOpts = g;
901
+ this.#open = true;
902
+ this.#tail = Promise.resolve();
504
903
  }
505
- _assertOpen() {
506
- if (!this._open) {
904
+ close() {
905
+ this.#open = false;
906
+ }
907
+ [Symbol.dispose]() {
908
+ this.close();
909
+ }
910
+ #assertOpen() {
911
+ if (!this.#open)
507
912
  throw new ErrClientClosed;
508
- }
509
913
  }
510
- close() {
511
- if (!this._open)
512
- return;
513
- const handle = this._handle;
514
- try {
515
- const envelopeJSON = callClose({ handle });
516
- const env = JSON.parse(envelopeJSON);
517
- if (isErrorEnvelope2(env)) {
518
- this._logger?.warn?.(`Client.close(): ad_close returned error envelope`, { err_name: env.err_name, err_description: env.err_description });
914
+ _assertOpenForTests() {
915
+ this.#assertOpen();
916
+ }
917
+ #enqueue(verb, params) {
918
+ let callResolve;
919
+ let callReject;
920
+ const callPromise = new Promise((res, rej) => {
921
+ callResolve = res;
922
+ callReject = rej;
923
+ });
924
+ this.#tail = this.#tail.then(async () => {
925
+ try {
926
+ const result = await this.#doCall(verb, params);
927
+ callResolve(result);
928
+ } catch (err) {
929
+ callReject(err);
519
930
  }
520
- } catch (e) {
521
- this._logger?.warn?.("Client.close(): unexpected error calling ad_close", e);
931
+ });
932
+ return callPromise;
933
+ }
934
+ async#doCall(verb, params) {
935
+ const argv = buildArgv(this.#cliPath, verb, params, this.#globalOpts);
936
+ const startMs = Date.now();
937
+ const spawnEnv = { ...process.env };
938
+ const proc = Bun.spawn({
939
+ cmd: argv,
940
+ stdin: "pipe",
941
+ stdout: "pipe",
942
+ stderr: "pipe",
943
+ detached: false,
944
+ env: spawnEnv
945
+ });
946
+ proc.stdin.end();
947
+ let timedOut = false;
948
+ const timeoutHandle = setTimeout(() => {
949
+ timedOut = true;
950
+ proc.kill("SIGTERM");
951
+ const gracefulHandle = setTimeout(() => {
952
+ proc.kill("SIGKILL");
953
+ }, SIGKILL_GRACE_MS);
954
+ proc.exited.then(() => clearTimeout(gracefulHandle), () => clearTimeout(gracefulHandle));
955
+ }, this.#callTimeoutMs);
956
+ let stdoutText;
957
+ let stderrText;
958
+ try {
959
+ [stdoutText, stderrText] = await Promise.all([
960
+ new Response(proc.stdout).text(),
961
+ new Response(proc.stderr).text(),
962
+ proc.exited
963
+ ]).then(([out, err]) => [out, err]);
522
964
  } finally {
523
- this._handle = null;
524
- this._open = false;
965
+ clearTimeout(timeoutHandle);
525
966
  }
526
- }
527
- [Symbol.dispose]() {
528
- this.close();
967
+ const signalCode = proc.signalCode;
968
+ const exitCode = proc.exitCode;
969
+ const elapsedMs = Date.now() - startMs;
970
+ if (timedOut) {
971
+ await proc.exited.catch(() => {});
972
+ throw new ErrCallTimeout(verb, elapsedMs, this.#callTimeoutMs);
973
+ }
974
+ if (signalCode !== null) {
975
+ throw new ErrConsumerSignal(verb, signalCode);
976
+ }
977
+ if (exitCode !== 0) {
978
+ const stderrLines = stderrText.trimEnd().split(`
979
+ `);
980
+ for (let i = stderrLines.length - 1;i >= 0; i--) {
981
+ const line = stderrLines[i].trim();
982
+ if (!line.startsWith("{"))
983
+ continue;
984
+ let parsed;
985
+ try {
986
+ parsed = JSON.parse(line);
987
+ } catch {
988
+ continue;
989
+ }
990
+ if (isErrorEnvelope(parsed)) {
991
+ throwFromEnvelope(verb, parsed);
992
+ }
993
+ }
994
+ throw new ErrSubprocessCrash(exitCode, null, stderrText);
995
+ }
996
+ let envelope;
997
+ try {
998
+ envelope = JSON.parse(stdoutText);
999
+ } catch {
1000
+ throw new ErrSubprocessCrash(0, null, stderrText);
1001
+ }
1002
+ if (isErrorEnvelope(envelope)) {
1003
+ throwFromEnvelope(verb, envelope);
1004
+ }
1005
+ if (this.#logger?.debug) {
1006
+ this.#logger.debug(`SubprocessClient: ${verb} ok`, { elapsedMs });
1007
+ }
1008
+ return envelope;
529
1009
  }
530
1010
  async spawn(params) {
531
- this._assertOpen();
532
- return callVerb("spawn", this._handle, params);
1011
+ this.#assertOpen();
1012
+ return this.#enqueue("spawn", params);
533
1013
  }
534
1014
  async status(params) {
535
- this._assertOpen();
536
- return callVerb("status", this._handle, params);
1015
+ this.#assertOpen();
1016
+ return this.#enqueue("status", params);
537
1017
  }
538
1018
  async get(params) {
539
- this._assertOpen();
540
- return callVerb("get", this._handle, params);
1019
+ this.#assertOpen();
1020
+ return this.#enqueue("get", params);
541
1021
  }
542
1022
  async sendKeys(params) {
543
- this._assertOpen();
544
- return callVerb("send-keys", this._handle, params);
1023
+ this.#assertOpen();
1024
+ return this.#enqueue("send-keys", params);
545
1025
  }
546
1026
  async readPane(params) {
547
- this._assertOpen();
548
- return callVerb("read-pane", this._handle, params);
1027
+ this.#assertOpen();
1028
+ return this.#enqueue("read-pane", params);
549
1029
  }
550
1030
  async kill(params) {
551
- this._assertOpen();
552
- return callVerb("kill", this._handle, params);
1031
+ this.#assertOpen();
1032
+ return this.#enqueue("kill", params);
553
1033
  }
554
1034
  async decide(params) {
555
- this._assertOpen();
556
- return callVerb("decide", this._handle, params);
1035
+ this.#assertOpen();
1036
+ return this.#enqueue("decide", params);
557
1037
  }
558
1038
  async resume(params) {
559
- this._assertOpen();
560
- return callVerb("resume", this._handle, params);
1039
+ this.#assertOpen();
1040
+ return this.#enqueue("resume", params);
561
1041
  }
562
1042
  async findMissing(params) {
563
- this._assertOpen();
564
- return callVerb("find-missing", this._handle, params);
1043
+ this.#assertOpen();
1044
+ return this.#enqueue("find-missing", params);
565
1045
  }
566
1046
  async expire(params) {
567
- this._assertOpen();
568
- return callVerb("expire", this._handle, params);
1047
+ this.#assertOpen();
1048
+ return this.#enqueue("expire", params);
569
1049
  }
570
1050
  async delete(params) {
571
- this._assertOpen();
572
- return callVerb("delete", this._handle, params);
1051
+ this.#assertOpen();
1052
+ return this.#enqueue("delete", params);
573
1053
  }
574
1054
  async makeTemplate(params) {
575
- this._assertOpen();
576
- return callVerb("make-template", this._handle, params);
1055
+ this.#assertOpen();
1056
+ return this.#enqueue("make-template", params);
577
1057
  }
578
1058
  async list(params) {
579
- this._assertOpen();
580
- return callVerb("list", this._handle, params);
1059
+ this.#assertOpen();
1060
+ return this.#enqueue("list", params);
581
1061
  }
582
1062
  async pause(params) {
583
- this._assertOpen();
584
- return callVerb("pause", this._handle, params);
1063
+ this.#assertOpen();
1064
+ return this.#enqueue("pause", params);
585
1065
  }
586
1066
  async version(params) {
587
- this._assertOpen();
588
- return callVerb("version", null, params);
589
- }
590
- _assertOpenForTests() {
591
- this._assertOpen();
1067
+ this.#assertOpen();
1068
+ const cliResp = await this.#enqueue("version", params);
1069
+ return { ...cliResp, version: NPM_PACKAGE_VERSION };
592
1070
  }
593
1071
  }
594
1072
  export {
595
1073
  errorFromEnvelope,
596
1074
  ErrUnsupportedPlatform,
597
- ErrUnknownHandle,
1075
+ ErrUnknownErrorName,
598
1076
  ErrTmuxSessionNameTooLong,
599
1077
  ErrTmuxSessionNameInvalid,
600
1078
  ErrTmuxSessionNameEmpty,
@@ -628,9 +1106,12 @@ export {
628
1106
  ErrCwdNotAPath,
629
1107
  ErrCwdNotADirectory,
630
1108
  ErrCwdMissing,
1109
+ ErrConsumerSignal,
631
1110
  ErrClientClosed,
1111
+ ErrCliNotExecutable,
1112
+ ErrCallTimeout,
632
1113
  ErrBunVersionTooOld,
633
1114
  ErrAlreadyDecided,
634
- Client,
1115
+ SubprocessClient as Client,
635
1116
  AgentDirectorError
636
1117
  };