agent-director 0.4.4 → 0.5.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
@@ -1,25 +1,88 @@
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
+ // src/internal/subprocessClient.ts
18
+ import { dirname as dirname2, basename } from "path";
17
19
 
18
- // src/platform.ts
19
- import { existsSync } from "fs";
20
+ // src/internal/platformResolve.ts
21
+ import { statSync } from "fs";
20
22
  import { fileURLToPath } from "url";
21
23
  import { join, dirname } from "path";
22
- import { dlopen } from "bun:ffi";
24
+
25
+ // src/errors.ts
26
+ var exports_errors = {};
27
+ __export(exports_errors, {
28
+ errorFromEnvelope: () => errorFromEnvelope,
29
+ TS_ONLY_ERROR_NAMES: () => TS_ONLY_ERROR_NAMES,
30
+ ErrUnsupportedPlatform: () => ErrUnsupportedPlatform,
31
+ ErrUnknownHandle: () => ErrUnknownHandle,
32
+ ErrUnknownErrorName: () => ErrUnknownErrorName,
33
+ ErrTmuxSessionNameTooLong: () => ErrTmuxSessionNameTooLong,
34
+ ErrTmuxSessionNameInvalid: () => ErrTmuxSessionNameInvalid,
35
+ ErrTmuxSessionNameEmpty: () => ErrTmuxSessionNameEmpty,
36
+ ErrTmuxSessionCreate: () => ErrTmuxSessionCreate,
37
+ ErrTmuxSendKeys: () => ErrTmuxSendKeys,
38
+ ErrTmuxNotAvailable: () => ErrTmuxNotAvailable,
39
+ ErrTmuxCaptureFailed: () => ErrTmuxCaptureFailed,
40
+ ErrTemplateNotFound: () => ErrTemplateNotFound,
41
+ ErrTemplateNameUnsafe: () => ErrTemplateNameUnsafe,
42
+ ErrTemplateMalformed: () => ErrTemplateMalformed,
43
+ ErrTemplateExists: () => ErrTemplateExists,
44
+ ErrSpawnNotResumable: () => ErrSpawnNotResumable,
45
+ ErrSpawnNotPausable: () => ErrSpawnNotPausable,
46
+ ErrSpawnNotInteractive: () => ErrSpawnNotInteractive,
47
+ ErrSpawnNotFound: () => ErrSpawnNotFound,
48
+ ErrSpawnDeniedFlag: () => ErrSpawnDeniedFlag,
49
+ ErrSendKeysWhileRelayed: () => ErrSendKeysWhileRelayed,
50
+ ErrReservedEnvKey: () => ErrReservedEnvKey,
51
+ ErrRelayModeOff: () => ErrRelayModeOff,
52
+ ErrRelayModeInvalid: () => ErrRelayModeInvalid,
53
+ ErrProbeUnsupported: () => ErrProbeUnsupported,
54
+ ErrPlatformPackageMissing: () => ErrPlatformPackageMissing,
55
+ ErrPauseTimeout: () => ErrPauseTimeout,
56
+ ErrNoSessionId: () => ErrNoSessionId,
57
+ ErrNoOpenPermissionRequest: () => ErrNoOpenPermissionRequest,
58
+ ErrListInvalidLabel: () => ErrListInvalidLabel,
59
+ ErrJsonlMissing: () => ErrJsonlMissing,
60
+ ErrInvalidDecision: () => ErrInvalidDecision,
61
+ ErrInstanceIdCollision: () => ErrInstanceIdCollision,
62
+ ErrCwdNotFound: () => ErrCwdNotFound,
63
+ ErrCwdNotAPath: () => ErrCwdNotAPath,
64
+ ErrCwdNotADirectory: () => ErrCwdNotADirectory,
65
+ ErrCwdMissing: () => ErrCwdMissing,
66
+ ErrConsumerSignal: () => ErrConsumerSignal,
67
+ ErrClientClosed: () => ErrClientClosed,
68
+ ErrCliNotExecutable: () => ErrCliNotExecutable,
69
+ ErrCallTimeout: () => ErrCallTimeout,
70
+ ErrBunVersionTooOld: () => ErrBunVersionTooOld,
71
+ ErrAlreadyDecided: () => ErrAlreadyDecided,
72
+ AgentDirectorError: () => AgentDirectorError
73
+ });
74
+
75
+ // src/internal/tsOnlyErrors.ts
76
+ var TS_ONLY_ERROR_NAMES = [
77
+ "ErrClientClosed",
78
+ "ErrUnsupportedPlatform",
79
+ "ErrPlatformPackageMissing",
80
+ "ErrBunVersionTooOld",
81
+ "ErrCliNotExecutable",
82
+ "ErrConsumerSignal",
83
+ "ErrCallTimeout",
84
+ "ErrUnknownErrorName"
85
+ ];
23
86
 
24
87
  // src/errors.ts
25
88
  class AgentDirectorError extends Error {
@@ -69,6 +132,48 @@ class ErrBunVersionTooOld extends AgentDirectorError {
69
132
  }
70
133
  }
71
134
 
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
+ class ErrConsumerSignal extends AgentDirectorError {
144
+ signal;
145
+ constructor(verb, signal) {
146
+ super(verb, "ErrConsumerSignal", `subprocess was killed by signal ${signal}`);
147
+ this.signal = signal;
148
+ this.name = "ErrConsumerSignal";
149
+ Object.setPrototypeOf(this, new.target.prototype);
150
+ }
151
+ }
152
+
153
+ class ErrCallTimeout extends AgentDirectorError {
154
+ elapsedMs;
155
+ timeoutMs;
156
+ constructor(verb, elapsedMs, timeoutMs) {
157
+ super(verb, "ErrCallTimeout", `call timed out after ${elapsedMs}ms (configured limit: ${timeoutMs}ms)`);
158
+ this.elapsedMs = elapsedMs;
159
+ this.timeoutMs = timeoutMs;
160
+ this.name = "ErrCallTimeout";
161
+ Object.setPrototypeOf(this, new.target.prototype);
162
+ }
163
+ }
164
+
165
+ class ErrUnknownErrorName extends AgentDirectorError {
166
+ unknownName;
167
+ envelope;
168
+ constructor(unknownName, envelope) {
169
+ super("", "ErrUnknownErrorName", `unknown err_name "${unknownName}" in subprocess envelope; TS catalog may be out of sync with Go catalog`);
170
+ this.unknownName = unknownName;
171
+ this.envelope = envelope;
172
+ this.name = "ErrUnknownErrorName";
173
+ Object.setPrototypeOf(this, new.target.prototype);
174
+ }
175
+ }
176
+
72
177
  class ErrCwdMissing extends AgentDirectorError {
73
178
  }
74
179
 
@@ -215,58 +320,7 @@ function errorFromEnvelope(verb, err_name, err_description) {
215
320
  return new AgentDirectorError(verb, err_name, err_description);
216
321
  }
217
322
 
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
323
+ // src/internal/platformResolve.ts
270
324
  var MIN_BUN_VERSION = "1.0.21";
271
325
  var SUPPORTED_TUPLES = new Map([
272
326
  ["linux-x64", "@agent-director/linux-x64"],
@@ -283,318 +337,689 @@ function compareSemver(a, b) {
283
337
  }
284
338
  return 0;
285
339
  }
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);
340
+ function resolveCliPath(opts) {
341
+ const platform = opts?.platform ?? process.platform;
342
+ const arch = opts?.arch ?? process.arch;
343
+ if (compareSemver(Bun.version, MIN_BUN_VERSION) < 0) {
344
+ throw new ErrBunVersionTooOld(Bun.version, MIN_BUN_VERSION);
292
345
  }
293
346
  const tuple = `${platform}-${arch}`;
294
347
  const subpkgName = SUPPORTED_TUPLES.get(tuple);
295
- if (!subpkgName) {
348
+ if (subpkgName === undefined) {
296
349
  throw new ErrUnsupportedPlatform(tuple);
297
350
  }
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}`);
351
+ let binPath;
352
+ if (opts?._requireResolve !== undefined) {
353
+ try {
354
+ binPath = opts._requireResolve(subpkgName);
355
+ } catch {
356
+ throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed (DI hook threw); run: npm install ${subpkgName}`);
357
+ }
358
+ } else {
359
+ let pkgDir;
360
+ try {
361
+ const pkgJsonUrl = import.meta.resolve(`${subpkgName}/package.json`);
362
+ pkgDir = dirname(fileURLToPath(pkgJsonUrl));
363
+ } catch {
364
+ throw new ErrPlatformPackageMissing(subpkgName, `platform package not installed; run: npm install ${subpkgName}`);
305
365
  }
306
- return cabiPath;
366
+ binPath = join(pkgDir, "bin", "agent-director");
307
367
  }
308
- let pkgDir;
368
+ let stat;
309
369
  try {
310
- const resolved = import.meta.resolve(`${subpkgName}/package.json`);
311
- pkgDir = dirname(fileURLToPath(resolved));
370
+ stat = statSync(binPath);
312
371
  } catch {
313
- throw new ErrPlatformPackageMissing(subpkgName);
372
+ throw new ErrPlatformPackageMissing(subpkgName, `binary not found at "${binPath}"`);
314
373
  }
315
- const libPath = join(pkgDir, binaryName);
316
- if (!existsSync(libPath)) {
317
- throw new ErrPlatformPackageMissing(subpkgName, `binary "${binaryName}" not found in package directory ${pkgDir}`);
374
+ const mode = stat.mode;
375
+ const fileUid = stat.uid;
376
+ const fileGid = stat.gid;
377
+ const myUid = process.getuid?.() ?? 0;
378
+ const myGid = process.getgid?.() ?? 0;
379
+ const execByOwner = (mode & 64) !== 0;
380
+ const execByGroup = (mode & 8) !== 0;
381
+ const execByOther = (mode & 1) !== 0;
382
+ const isExecutable = fileUid === myUid && execByOwner || fileGid === myGid && execByGroup || execByOther;
383
+ if (!isExecutable) {
384
+ throw new ErrCliNotExecutable(binPath);
318
385
  }
319
- return libPath;
386
+ return binPath;
320
387
  }
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 };
388
+
389
+ // src/internal/tilde.ts
390
+ import * as os from "os";
391
+ function expandTilde(p) {
392
+ if (p === "")
393
+ return "";
394
+ if (p !== "~" && !p.startsWith("~/"))
395
+ return p;
396
+ const home = process.env["HOME"] ?? os.homedir();
397
+ if (p === "~")
398
+ return home;
399
+ return home + p.slice(1);
400
+ }
401
+
402
+ // src/internal/argv.ts
403
+ function buildArgv(cliPath, verb, params) {
404
+ const verbFlags = buildVerbFlags(verb, params);
405
+ return [cliPath, ...verbFlags];
406
+ }
407
+ function buildVerbFlags(verb, params) {
408
+ switch (verb) {
409
+ case "version":
410
+ return buildVersion();
411
+ case "spawn":
412
+ return buildSpawn(params);
413
+ case "status":
414
+ return buildStatus(params);
415
+ case "get":
416
+ return buildGet(params);
417
+ case "send-keys":
418
+ return buildSendKeys(params);
419
+ case "read-pane":
420
+ return buildReadPane(params);
421
+ case "kill":
422
+ return buildKill(params);
423
+ case "decide":
424
+ return buildDecide(params);
425
+ case "resume":
426
+ return buildResume(params);
427
+ case "find-missing":
428
+ return buildFindMissing();
429
+ case "expire":
430
+ return buildExpire(params);
431
+ case "delete":
432
+ return buildDelete(params);
433
+ case "make-template":
434
+ return buildMakeTemplate(params);
435
+ case "list":
436
+ return buildList(params);
437
+ case "pause":
438
+ return buildPause(params);
439
+ default: {
440
+ const _exhaustive = verb;
441
+ throw new Error(`buildVerbFlags: unhandled verb "${String(_exhaustive)}"`);
442
+ }
443
+ }
444
+ }
445
+ function buildVersion() {
446
+ return ["version"];
447
+ }
448
+ function buildSpawn(p) {
449
+ const f = ["spawn"];
450
+ f.push("--cwd", p.cwd);
451
+ if (p.template !== undefined)
452
+ f.push("--template", p.template);
453
+ if (p.claude_instance_id !== undefined)
454
+ f.push("--claude-instance-id", p.claude_instance_id);
455
+ if (p.tmux_session_name !== undefined)
456
+ f.push("--tmux-session-name", p.tmux_session_name);
457
+ if (p.relay_mode !== undefined && p.relay_mode !== "")
458
+ f.push("--relay-mode", p.relay_mode);
459
+ if (p.no_pre_trust === true)
460
+ f.push("--no-pre-trust");
461
+ if (p.label) {
462
+ for (const lv of p.label)
463
+ f.push("--label", lv);
464
+ }
465
+ if (p.extra_env) {
466
+ for (const [k, v] of Object.entries(p.extra_env))
467
+ f.push("--extra-env", `${k}=${v}`);
468
+ }
469
+ if (p.allow) {
470
+ for (const a of p.allow)
471
+ f.push("--allow", a);
472
+ }
473
+ if (p.deny) {
474
+ for (const d of p.deny)
475
+ f.push("--deny", d);
476
+ }
477
+ if (p.ask) {
478
+ for (const a of p.ask)
479
+ f.push("--ask", a);
480
+ }
481
+ if (p.claude_args && p.claude_args.length > 0) {
482
+ f.push("--", ...p.claude_args);
483
+ }
484
+ return f;
485
+ }
486
+ function buildStatus(p) {
487
+ return ["status", "--claude-instance-id", p.claude_instance_id];
488
+ }
489
+ function buildGet(p) {
490
+ return ["get", "--claude-instance-id", p.claude_instance_id];
491
+ }
492
+ function buildSendKeys(p) {
493
+ return [
494
+ "send-keys",
495
+ "--claude-instance-id",
496
+ p.claude_instance_id,
497
+ "--text",
498
+ p.text
499
+ ];
500
+ }
501
+ function buildReadPane(p) {
502
+ const f = ["read-pane", "--claude-instance-id", p.claude_instance_id];
503
+ if (p.n_lines !== undefined && p.n_lines > 0)
504
+ f.push("--n-lines", String(p.n_lines));
505
+ if (p.ansi === true)
506
+ f.push("--ansi");
507
+ return f;
508
+ }
509
+ function buildKill(p) {
510
+ return ["kill", "--claude-instance-id", p.claude_instance_id];
511
+ }
512
+ function buildDecide(p) {
513
+ const f = [
514
+ "decide",
515
+ "--claude-instance-id",
516
+ p.claude_instance_id,
517
+ "--decision",
518
+ p.decision
519
+ ];
520
+ if (p.reason !== undefined)
521
+ f.push("--reason", p.reason);
522
+ return f;
523
+ }
524
+ function buildResume(p) {
525
+ return ["resume", "--claude-instance-id", p.claude_instance_id];
326
526
  }
327
- function loadNative() {
328
- return _loadNativeInternal();
527
+ function buildFindMissing() {
528
+ return ["find-missing"];
529
+ }
530
+ function buildExpire(p) {
531
+ const f = ["expire"];
532
+ if (p.older_than !== undefined)
533
+ f.push("--older-than", p.older_than);
534
+ return f;
535
+ }
536
+ function buildDelete(p) {
537
+ const f = ["delete"];
538
+ for (const id of p.claude_instance_id)
539
+ f.push("--claude-instance-id", id);
540
+ return f;
541
+ }
542
+ function buildMakeTemplate(p) {
543
+ const f = ["make-template", "--name", p.name];
544
+ if (p.cwd !== undefined)
545
+ f.push("--cwd", p.cwd);
546
+ if (p.relay_mode !== undefined && p.relay_mode !== "")
547
+ f.push("--relay-mode", p.relay_mode);
548
+ if (p.overwrite === true)
549
+ f.push("--overwrite");
550
+ if (p.label) {
551
+ for (const lv of p.label)
552
+ f.push("--label", lv);
553
+ }
554
+ if (p.extra_env) {
555
+ for (const [k, v] of Object.entries(p.extra_env))
556
+ f.push("--extra-env", `${k}=${v}`);
557
+ }
558
+ if (p.allow) {
559
+ for (const a of p.allow)
560
+ f.push("--allow", a);
561
+ }
562
+ if (p.deny) {
563
+ for (const d of p.deny)
564
+ f.push("--deny", d);
565
+ }
566
+ if (p.ask) {
567
+ for (const a of p.ask)
568
+ f.push("--ask", a);
569
+ }
570
+ if (p.claude_args) {
571
+ for (const a of p.claude_args)
572
+ f.push("--claude-args", a);
573
+ }
574
+ return f;
575
+ }
576
+ function buildList(p) {
577
+ const f = ["list"];
578
+ if (p.state && p.state.length > 0)
579
+ f.push("--state", p.state.join(","));
580
+ if (p.label) {
581
+ for (const lv of p.label)
582
+ f.push("--label", lv);
583
+ }
584
+ if (p.parent !== undefined)
585
+ f.push("--parent", p.parent);
586
+ if (p.cwd !== undefined)
587
+ f.push("--cwd", p.cwd);
588
+ if (p.tmux_session_name !== undefined)
589
+ f.push("--tmux-session-name", p.tmux_session_name);
590
+ if (p.limit !== undefined && p.limit > 0)
591
+ f.push("--limit", String(p.limit));
592
+ return f;
593
+ }
594
+ function buildPause(p) {
595
+ return ["pause", "--claude-instance-id", p.claude_instance_id];
596
+ }
597
+
598
+ // src/internal/spawner.ts
599
+ class ErrSubprocessCrash extends Error {
600
+ exitCode;
601
+ signalCode;
602
+ stderrFull;
603
+ constructor(exitCode, signalCode, stderrFull) {
604
+ const reason = signalCode !== null ? `killed by signal ${signalCode}` : `exited with code ${exitCode ?? "null"}`;
605
+ const snippet = stderrFull.slice(0, 1024);
606
+ super(`subprocess ${reason}${snippet ? `; stderr: ${snippet}` : ""}`);
607
+ this.exitCode = exitCode;
608
+ this.signalCode = signalCode;
609
+ this.stderrFull = stderrFull;
610
+ this.name = "ErrSubprocessCrash";
611
+ Object.setPrototypeOf(this, new.target.prototype);
612
+ }
329
613
  }
330
614
 
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
615
+ // ../api/errnames/catalog.json
616
+ var catalog_default = [
617
+ {
618
+ name: "ErrCwdMissing",
619
+ package: "spawn",
620
+ description: ""
337
621
  },
338
- ad_close: {
339
- args: [FFIType2.cstring],
340
- returns: FFIType2.ptr
622
+ {
623
+ name: "ErrCwdNotAPath",
624
+ package: "spawn",
625
+ description: ""
341
626
  },
342
- ad_free_cstring: {
343
- args: [FFIType2.ptr],
344
- returns: FFIType2.void
345
- }
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);
446
- }
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
- });
627
+ {
628
+ name: "ErrCwdNotFound",
629
+ package: "spawn",
630
+ description: ""
631
+ },
632
+ {
633
+ name: "ErrCwdNotADirectory",
634
+ package: "spawn",
635
+ description: ""
636
+ },
637
+ {
638
+ name: "ErrRelayModeInvalid",
639
+ package: "spawn",
640
+ description: ""
641
+ },
642
+ {
643
+ name: "ErrSpawnDeniedFlag",
644
+ package: "spawn",
645
+ description: ""
646
+ },
647
+ {
648
+ name: "ErrReservedEnvKey",
649
+ package: "spawn",
650
+ description: ""
651
+ },
652
+ {
653
+ name: "ErrInstanceIdCollision",
654
+ package: "spawn",
655
+ description: ""
656
+ },
657
+ {
658
+ name: "ErrTmuxSessionNameEmpty",
659
+ package: "spawn",
660
+ description: ""
661
+ },
662
+ {
663
+ name: "ErrTmuxSessionNameInvalid",
664
+ package: "spawn",
665
+ description: ""
666
+ },
667
+ {
668
+ name: "ErrTmuxSessionNameTooLong",
669
+ package: "spawn",
670
+ description: ""
671
+ },
672
+ {
673
+ name: "ErrSpawnNotFound",
674
+ package: "store",
675
+ description: ""
676
+ },
677
+ {
678
+ name: "ErrTmuxNotAvailable",
679
+ package: "tmux",
680
+ description: ""
681
+ },
682
+ {
683
+ name: "ErrTmuxSessionCreate",
684
+ package: "tmux",
685
+ description: ""
686
+ },
687
+ {
688
+ name: "ErrTmuxSendKeys",
689
+ package: "tmux",
690
+ description: ""
691
+ },
692
+ {
693
+ name: "ErrTmuxCaptureFailed",
694
+ package: "tmux",
695
+ description: ""
696
+ },
697
+ {
698
+ name: "ErrSpawnNotInteractive",
699
+ package: "api",
700
+ description: ""
701
+ },
702
+ {
703
+ name: "ErrSendKeysWhileRelayed",
704
+ package: "api",
705
+ description: ""
706
+ },
707
+ {
708
+ name: "ErrSpawnNotPausable",
709
+ package: "api",
710
+ description: ""
711
+ },
712
+ {
713
+ name: "ErrPauseTimeout",
714
+ package: "api",
715
+ description: ""
716
+ },
717
+ {
718
+ name: "ErrListInvalidLabel",
719
+ package: "api",
720
+ description: ""
721
+ },
722
+ {
723
+ name: "ErrTemplateNameUnsafe",
724
+ package: "config",
725
+ description: ""
726
+ },
727
+ {
728
+ name: "ErrTemplateNotFound",
729
+ package: "config",
730
+ description: ""
731
+ },
732
+ {
733
+ name: "ErrTemplateMalformed",
734
+ package: "config",
735
+ description: ""
736
+ },
737
+ {
738
+ name: "ErrTemplateExists",
739
+ package: "config",
740
+ description: ""
741
+ },
742
+ {
743
+ name: "ErrProbeUnsupported",
744
+ package: "probe",
745
+ description: ""
746
+ },
747
+ {
748
+ name: "ErrSpawnNotResumable",
749
+ package: "api",
750
+ description: ""
751
+ },
752
+ {
753
+ name: "ErrNoSessionId",
754
+ package: "api",
755
+ description: ""
756
+ },
757
+ {
758
+ name: "ErrJsonlMissing",
759
+ package: "api",
760
+ description: ""
761
+ },
762
+ {
763
+ name: "ErrRelayModeOff",
764
+ package: "api",
765
+ description: ""
766
+ },
767
+ {
768
+ name: "ErrInvalidDecision",
769
+ package: "api",
770
+ description: ""
771
+ },
772
+ {
773
+ name: "ErrNoOpenPermissionRequest",
774
+ package: "store",
775
+ description: ""
776
+ },
777
+ {
778
+ name: "ErrAlreadyDecided",
779
+ package: "store",
780
+ description: ""
781
+ },
782
+ {
783
+ name: "ErrUnknownHandle",
784
+ package: "cabi",
785
+ description: "",
786
+ scope: "cabi"
467
787
  }
468
- };
788
+ ];
469
789
 
470
- // src/ffi.ts
471
- async function callVerb(verb, handle, params) {
472
- return workerProxy.dispatch(verb, handle, params);
790
+ // src/internal/errorMap.ts
791
+ var _catalog = catalog_default;
792
+ var errorMap = new Map(_catalog.flatMap((entry) => {
793
+ const errorsRecord = exports_errors;
794
+ const Ctor = errorsRecord[entry.name];
795
+ if (typeof Ctor !== "function") {
796
+ return [];
797
+ }
798
+ return [[entry.name, Ctor]];
799
+ }));
800
+ function isErrorEnvelope(envelope) {
801
+ return typeof envelope === "object" && envelope !== null && "err_name" in envelope && typeof envelope.err_name === "string";
473
802
  }
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";
803
+ function throwFromEnvelope(verb, envelope) {
804
+ const env = envelope;
805
+ const errName = env.err_name;
806
+ const envelopeRecord = envelope;
807
+ const errDescription = typeof envelopeRecord["err_description"] === "string" ? envelopeRecord["err_description"] : "";
808
+ const Ctor = errorMap.get(errName);
809
+ if (Ctor !== undefined) {
810
+ throw new Ctor(verb, errName, errDescription);
811
+ }
812
+ throw new ErrUnknownErrorName(errName, envelope);
478
813
  }
479
814
 
480
- class Client {
481
- _handle;
482
- _open;
483
- _logger;
815
+ // src/internal/subprocessClient.ts
816
+ var DEFAULT_CALL_TIMEOUT_MS = 30000;
817
+ var SIGKILL_GRACE_MS = 2000;
818
+
819
+ class SubprocessClient {
820
+ #cliPath;
821
+ #callTimeoutMs;
822
+ #logger;
823
+ #open;
824
+ #homeOverride;
825
+ #tmuxDir;
826
+ _handle = null;
827
+ #tail;
484
828
  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);
829
+ const rawTimeout = opts.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
830
+ if (rawTimeout <= 0) {
831
+ throw new Error(`ClientOptions.callTimeoutMs must be positive (got ${rawTimeout}); ` + `omit the field to use the default (${DEFAULT_CALL_TIMEOUT_MS} ms)`);
501
832
  }
502
- this._handle = env.handle;
503
- this._open = true;
833
+ this.#callTimeoutMs = rawTimeout;
834
+ this.#logger = opts.logger;
835
+ const opts2 = opts;
836
+ this.#cliPath = opts2._cliPath ?? resolveCliPath();
837
+ const expandedStore = expandTilde(opts.storePath);
838
+ const storeParent = dirname2(expandedStore);
839
+ this.#homeOverride = basename(storeParent) === ".agent-director" ? dirname2(storeParent) : null;
840
+ this.#tmuxDir = opts.tmuxCommand ? dirname2(expandTilde(opts.tmuxCommand)) : null;
841
+ this.#open = true;
842
+ this.#tail = Promise.resolve();
504
843
  }
505
- _assertOpen() {
506
- if (!this._open) {
844
+ close() {
845
+ this.#open = false;
846
+ }
847
+ [Symbol.dispose]() {
848
+ this.close();
849
+ }
850
+ #assertOpen() {
851
+ if (!this.#open)
507
852
  throw new ErrClientClosed;
508
- }
509
853
  }
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 });
854
+ _assertOpenForTests() {
855
+ this.#assertOpen();
856
+ }
857
+ #enqueue(verb, params) {
858
+ let callResolve;
859
+ let callReject;
860
+ const callPromise = new Promise((res, rej) => {
861
+ callResolve = res;
862
+ callReject = rej;
863
+ });
864
+ this.#tail = this.#tail.then(async () => {
865
+ try {
866
+ const result = await this.#doCall(verb, params);
867
+ callResolve(result);
868
+ } catch (err) {
869
+ callReject(err);
519
870
  }
520
- } catch (e) {
521
- this._logger?.warn?.("Client.close(): unexpected error calling ad_close", e);
871
+ });
872
+ return callPromise;
873
+ }
874
+ async#doCall(verb, params) {
875
+ const argv = buildArgv(this.#cliPath, verb, params);
876
+ const startMs = Date.now();
877
+ const spawnEnv = { ...process.env };
878
+ if (this.#homeOverride !== null) {
879
+ spawnEnv["HOME"] = this.#homeOverride;
880
+ }
881
+ if (this.#tmuxDir !== null) {
882
+ const priorPath = spawnEnv["PATH"] ?? "";
883
+ spawnEnv["PATH"] = priorPath ? `${this.#tmuxDir}:${priorPath}` : this.#tmuxDir;
884
+ }
885
+ const proc = Bun.spawn({
886
+ cmd: argv,
887
+ stdin: "pipe",
888
+ stdout: "pipe",
889
+ stderr: "pipe",
890
+ detached: false,
891
+ env: spawnEnv
892
+ });
893
+ proc.stdin.end();
894
+ let timedOut = false;
895
+ const timeoutHandle = setTimeout(() => {
896
+ timedOut = true;
897
+ proc.kill("SIGTERM");
898
+ const gracefulHandle = setTimeout(() => {
899
+ proc.kill("SIGKILL");
900
+ }, SIGKILL_GRACE_MS);
901
+ proc.exited.then(() => clearTimeout(gracefulHandle), () => clearTimeout(gracefulHandle));
902
+ }, this.#callTimeoutMs);
903
+ let stdoutText;
904
+ let stderrText;
905
+ try {
906
+ [stdoutText, stderrText] = await Promise.all([
907
+ new Response(proc.stdout).text(),
908
+ new Response(proc.stderr).text(),
909
+ proc.exited
910
+ ]).then(([out, err]) => [out, err]);
522
911
  } finally {
523
- this._handle = null;
524
- this._open = false;
912
+ clearTimeout(timeoutHandle);
525
913
  }
526
- }
527
- [Symbol.dispose]() {
528
- this.close();
914
+ const signalCode = proc.signalCode;
915
+ const exitCode = proc.exitCode;
916
+ const elapsedMs = Date.now() - startMs;
917
+ if (timedOut) {
918
+ await proc.exited.catch(() => {});
919
+ throw new ErrCallTimeout(verb, elapsedMs, this.#callTimeoutMs);
920
+ }
921
+ if (signalCode !== null) {
922
+ throw new ErrConsumerSignal(verb, signalCode);
923
+ }
924
+ if (exitCode !== 0) {
925
+ const stderrLines = stderrText.trimEnd().split(`
926
+ `);
927
+ for (let i = stderrLines.length - 1;i >= 0; i--) {
928
+ const line = stderrLines[i].trim();
929
+ if (!line.startsWith("{"))
930
+ continue;
931
+ let parsed;
932
+ try {
933
+ parsed = JSON.parse(line);
934
+ } catch {
935
+ continue;
936
+ }
937
+ if (isErrorEnvelope(parsed)) {
938
+ throwFromEnvelope(verb, parsed);
939
+ }
940
+ }
941
+ throw new ErrSubprocessCrash(exitCode, null, stderrText);
942
+ }
943
+ let envelope;
944
+ try {
945
+ envelope = JSON.parse(stdoutText);
946
+ } catch {
947
+ throw new ErrSubprocessCrash(0, null, stderrText);
948
+ }
949
+ if (isErrorEnvelope(envelope)) {
950
+ throwFromEnvelope(verb, envelope);
951
+ }
952
+ if (this.#logger?.debug) {
953
+ this.#logger.debug(`SubprocessClient: ${verb} ok`, { elapsedMs });
954
+ }
955
+ return envelope;
529
956
  }
530
957
  async spawn(params) {
531
- this._assertOpen();
532
- return callVerb("spawn", this._handle, params);
958
+ this.#assertOpen();
959
+ return this.#enqueue("spawn", params);
533
960
  }
534
961
  async status(params) {
535
- this._assertOpen();
536
- return callVerb("status", this._handle, params);
962
+ this.#assertOpen();
963
+ return this.#enqueue("status", params);
537
964
  }
538
965
  async get(params) {
539
- this._assertOpen();
540
- return callVerb("get", this._handle, params);
966
+ this.#assertOpen();
967
+ return this.#enqueue("get", params);
541
968
  }
542
969
  async sendKeys(params) {
543
- this._assertOpen();
544
- return callVerb("send-keys", this._handle, params);
970
+ this.#assertOpen();
971
+ return this.#enqueue("send-keys", params);
545
972
  }
546
973
  async readPane(params) {
547
- this._assertOpen();
548
- return callVerb("read-pane", this._handle, params);
974
+ this.#assertOpen();
975
+ return this.#enqueue("read-pane", params);
549
976
  }
550
977
  async kill(params) {
551
- this._assertOpen();
552
- return callVerb("kill", this._handle, params);
978
+ this.#assertOpen();
979
+ return this.#enqueue("kill", params);
553
980
  }
554
981
  async decide(params) {
555
- this._assertOpen();
556
- return callVerb("decide", this._handle, params);
982
+ this.#assertOpen();
983
+ return this.#enqueue("decide", params);
557
984
  }
558
985
  async resume(params) {
559
- this._assertOpen();
560
- return callVerb("resume", this._handle, params);
986
+ this.#assertOpen();
987
+ return this.#enqueue("resume", params);
561
988
  }
562
989
  async findMissing(params) {
563
- this._assertOpen();
564
- return callVerb("find-missing", this._handle, params);
990
+ this.#assertOpen();
991
+ return this.#enqueue("find-missing", params);
565
992
  }
566
993
  async expire(params) {
567
- this._assertOpen();
568
- return callVerb("expire", this._handle, params);
994
+ this.#assertOpen();
995
+ return this.#enqueue("expire", params);
569
996
  }
570
997
  async delete(params) {
571
- this._assertOpen();
572
- return callVerb("delete", this._handle, params);
998
+ this.#assertOpen();
999
+ return this.#enqueue("delete", params);
573
1000
  }
574
1001
  async makeTemplate(params) {
575
- this._assertOpen();
576
- return callVerb("make-template", this._handle, params);
1002
+ this.#assertOpen();
1003
+ return this.#enqueue("make-template", params);
577
1004
  }
578
1005
  async list(params) {
579
- this._assertOpen();
580
- return callVerb("list", this._handle, params);
1006
+ this.#assertOpen();
1007
+ return this.#enqueue("list", params);
581
1008
  }
582
1009
  async pause(params) {
583
- this._assertOpen();
584
- return callVerb("pause", this._handle, params);
1010
+ this.#assertOpen();
1011
+ return this.#enqueue("pause", params);
585
1012
  }
586
1013
  async version(params) {
587
- this._assertOpen();
588
- return callVerb("version", null, params);
589
- }
590
- _assertOpenForTests() {
591
- this._assertOpen();
1014
+ this.#assertOpen();
1015
+ return this.#enqueue("version", params);
592
1016
  }
593
1017
  }
594
1018
  export {
595
1019
  errorFromEnvelope,
596
1020
  ErrUnsupportedPlatform,
597
1021
  ErrUnknownHandle,
1022
+ ErrUnknownErrorName,
598
1023
  ErrTmuxSessionNameTooLong,
599
1024
  ErrTmuxSessionNameInvalid,
600
1025
  ErrTmuxSessionNameEmpty,
@@ -628,9 +1053,12 @@ export {
628
1053
  ErrCwdNotAPath,
629
1054
  ErrCwdNotADirectory,
630
1055
  ErrCwdMissing,
1056
+ ErrConsumerSignal,
631
1057
  ErrClientClosed,
1058
+ ErrCliNotExecutable,
1059
+ ErrCallTimeout,
632
1060
  ErrBunVersionTooOld,
633
1061
  ErrAlreadyDecided,
634
- Client,
1062
+ SubprocessClient as Client,
635
1063
  AgentDirectorError
636
1064
  };