agent-director 0.4.5 → 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.
@@ -1,415 +0,0 @@
1
- // @bun
2
- // src/internal/worker.ts
3
- import { parentPort } from "worker_threads";
4
- import { CString, ptr } from "bun:ffi";
5
-
6
- // src/internal/verbs.ts
7
- var VERBS = [
8
- "spawn",
9
- "status",
10
- "get",
11
- "send-keys",
12
- "read-pane",
13
- "kill",
14
- "decide",
15
- "resume",
16
- "find-missing",
17
- "expire",
18
- "delete",
19
- "make-template",
20
- "list",
21
- "pause",
22
- "version"
23
- ];
24
- function kebabToUnderscore(v) {
25
- return v.replace(/-/g, "_");
26
- }
27
- var HANDLE_FREE_VERBS = new Set(["version"]);
28
- function isHandleFree(verb) {
29
- return HANDLE_FREE_VERBS.has(verb);
30
- }
31
-
32
- // src/internal/freeGuard.ts
33
- class FreeGuard {
34
- _ptr;
35
- _free;
36
- constructor(ptr, free) {
37
- this._ptr = ptr;
38
- this._free = free;
39
- }
40
- get ptr() {
41
- return this._ptr;
42
- }
43
- free() {
44
- if (this._ptr === null)
45
- return;
46
- const p = this._ptr;
47
- this._ptr = null;
48
- this._free(p);
49
- }
50
- }
51
-
52
- // src/platform.ts
53
- import { existsSync } from "fs";
54
- import { fileURLToPath } from "url";
55
- import { join, dirname } from "path";
56
- import { dlopen } from "bun:ffi";
57
-
58
- // src/errors.ts
59
- class AgentDirectorError extends Error {
60
- verb;
61
- errName;
62
- errDescription;
63
- constructor(verb, err_name, err_description) {
64
- super(`${err_name}: ${err_description}`);
65
- this.verb = verb;
66
- this.errName = err_name;
67
- this.errDescription = err_description;
68
- this.name = this.constructor.name;
69
- Object.setPrototypeOf(this, new.target.prototype);
70
- }
71
- }
72
-
73
- class ErrClientClosed extends AgentDirectorError {
74
- constructor() {
75
- super("", "ErrClientClosed", "client is closed: call new Client() to obtain a fresh handle");
76
- this.name = "ErrClientClosed";
77
- Object.setPrototypeOf(this, new.target.prototype);
78
- }
79
- }
80
-
81
- class ErrUnsupportedPlatform extends AgentDirectorError {
82
- constructor(tuple) {
83
- super("", "ErrUnsupportedPlatform", `platform/arch tuple "${tuple}" is not supported; supported: linux-x64, darwin-arm64`);
84
- this.name = "ErrUnsupportedPlatform";
85
- Object.setPrototypeOf(this, new.target.prototype);
86
- }
87
- }
88
-
89
- class ErrPlatformPackageMissing extends AgentDirectorError {
90
- constructor(pkgName, detail) {
91
- const desc = detail ? `native sub-package "${pkgName}" is not usable: ${detail}` : `native sub-package "${pkgName}" is not installed or its binary is absent`;
92
- super("", "ErrPlatformPackageMissing", desc);
93
- this.name = "ErrPlatformPackageMissing";
94
- Object.setPrototypeOf(this, new.target.prototype);
95
- }
96
- }
97
-
98
- class ErrBunVersionTooOld extends AgentDirectorError {
99
- constructor(actual, minimum) {
100
- super("", "ErrBunVersionTooOld", `Bun ${actual} is below the minimum required version ${minimum}; upgrade Bun to continue`);
101
- this.name = "ErrBunVersionTooOld";
102
- Object.setPrototypeOf(this, new.target.prototype);
103
- }
104
- }
105
-
106
- class ErrCwdMissing extends AgentDirectorError {
107
- }
108
-
109
- class ErrCwdNotAPath extends AgentDirectorError {
110
- }
111
-
112
- class ErrCwdNotFound extends AgentDirectorError {
113
- }
114
-
115
- class ErrCwdNotADirectory extends AgentDirectorError {
116
- }
117
-
118
- class ErrRelayModeInvalid extends AgentDirectorError {
119
- }
120
-
121
- class ErrSpawnDeniedFlag extends AgentDirectorError {
122
- }
123
-
124
- class ErrReservedEnvKey extends AgentDirectorError {
125
- }
126
-
127
- class ErrInstanceIdCollision extends AgentDirectorError {
128
- }
129
-
130
- class ErrTmuxSessionNameEmpty extends AgentDirectorError {
131
- }
132
-
133
- class ErrTmuxSessionNameInvalid extends AgentDirectorError {
134
- }
135
-
136
- class ErrTmuxSessionNameTooLong extends AgentDirectorError {
137
- }
138
-
139
- class ErrSpawnNotFound extends AgentDirectorError {
140
- }
141
-
142
- class ErrTmuxNotAvailable extends AgentDirectorError {
143
- }
144
-
145
- class ErrTmuxSessionCreate extends AgentDirectorError {
146
- }
147
-
148
- class ErrTmuxSendKeys extends AgentDirectorError {
149
- }
150
-
151
- class ErrTmuxCaptureFailed extends AgentDirectorError {
152
- }
153
-
154
- class ErrSpawnNotInteractive extends AgentDirectorError {
155
- }
156
-
157
- class ErrSendKeysWhileRelayed extends AgentDirectorError {
158
- }
159
-
160
- class ErrSpawnNotPausable extends AgentDirectorError {
161
- }
162
-
163
- class ErrPauseTimeout extends AgentDirectorError {
164
- }
165
-
166
- class ErrListInvalidLabel extends AgentDirectorError {
167
- }
168
-
169
- class ErrTemplateNameUnsafe extends AgentDirectorError {
170
- }
171
-
172
- class ErrTemplateNotFound extends AgentDirectorError {
173
- }
174
-
175
- class ErrTemplateMalformed extends AgentDirectorError {
176
- }
177
-
178
- class ErrTemplateExists extends AgentDirectorError {
179
- }
180
-
181
- class ErrProbeUnsupported extends AgentDirectorError {
182
- }
183
-
184
- class ErrSpawnNotResumable extends AgentDirectorError {
185
- }
186
-
187
- class ErrNoSessionId extends AgentDirectorError {
188
- }
189
-
190
- class ErrJsonlMissing extends AgentDirectorError {
191
- }
192
-
193
- class ErrRelayModeOff extends AgentDirectorError {
194
- }
195
-
196
- class ErrInvalidDecision extends AgentDirectorError {
197
- }
198
-
199
- class ErrNoOpenPermissionRequest extends AgentDirectorError {
200
- }
201
-
202
- class ErrAlreadyDecided extends AgentDirectorError {
203
- }
204
-
205
- class ErrUnknownHandle extends AgentDirectorError {
206
- }
207
- var ERROR_TABLE = {
208
- ErrCwdMissing,
209
- ErrCwdNotAPath,
210
- ErrCwdNotFound,
211
- ErrCwdNotADirectory,
212
- ErrRelayModeInvalid,
213
- ErrSpawnDeniedFlag,
214
- ErrReservedEnvKey,
215
- ErrInstanceIdCollision,
216
- ErrTmuxSessionNameEmpty,
217
- ErrTmuxSessionNameInvalid,
218
- ErrTmuxSessionNameTooLong,
219
- ErrSpawnNotFound,
220
- ErrNoOpenPermissionRequest,
221
- ErrAlreadyDecided,
222
- ErrTmuxNotAvailable,
223
- ErrTmuxSessionCreate,
224
- ErrTmuxSendKeys,
225
- ErrTmuxCaptureFailed,
226
- ErrSpawnNotInteractive,
227
- ErrSendKeysWhileRelayed,
228
- ErrSpawnNotPausable,
229
- ErrPauseTimeout,
230
- ErrListInvalidLabel,
231
- ErrSpawnNotResumable,
232
- ErrNoSessionId,
233
- ErrJsonlMissing,
234
- ErrRelayModeOff,
235
- ErrInvalidDecision,
236
- ErrTemplateNameUnsafe,
237
- ErrTemplateNotFound,
238
- ErrTemplateMalformed,
239
- ErrTemplateExists,
240
- ErrProbeUnsupported,
241
- ErrUnknownHandle
242
- };
243
- function errorFromEnvelope(verb, err_name, err_description) {
244
- const Ctor = ERROR_TABLE[err_name];
245
- if (Ctor) {
246
- return new Ctor(verb, err_name, err_description);
247
- }
248
- console.warn(`agent-director: unknown err_name "${err_name}" (verb=${verb}); returning base AgentDirectorError`);
249
- return new AgentDirectorError(verb, err_name, err_description);
250
- }
251
-
252
- // src/internal/bindingSpec.ts
253
- import { FFIType } from "bun:ffi";
254
- var BINDING_SYMBOL_NAMES = [
255
- "ad_open",
256
- "ad_close",
257
- "ad_free_cstring",
258
- ...VERBS.map((v) => "ad_" + kebabToUnderscore(v))
259
- ];
260
- function buildBindingSpec() {
261
- const spec = {
262
- ad_open: { args: [FFIType.cstring], returns: FFIType.ptr },
263
- ad_close: { args: [FFIType.cstring], returns: FFIType.ptr },
264
- ad_free_cstring: { args: [FFIType.ptr], returns: FFIType.void }
265
- };
266
- for (const verb of VERBS) {
267
- spec["ad_" + kebabToUnderscore(verb)] = {
268
- args: [FFIType.cstring],
269
- returns: FFIType.ptr
270
- };
271
- }
272
- return spec;
273
- }
274
-
275
- // src/platform.ts
276
- var MIN_BUN_VERSION = "1.0.21";
277
- var SUPPORTED_TUPLES = new Map([
278
- ["linux-x64", "@agent-director/linux-x64"],
279
- ["darwin-arm64", "@agent-director/darwin-arm64"]
280
- ]);
281
- function compareSemver(a, b) {
282
- const parse = (s) => s.split(".").map((p) => parseInt(p, 10) || 0);
283
- const pa = parse(a);
284
- const pb = parse(b);
285
- for (let i = 0;i < 3; i++) {
286
- const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
287
- if (diff !== 0)
288
- return diff;
289
- }
290
- return 0;
291
- }
292
- function resolveNativePath(opts = {}) {
293
- const platform = opts.platform ?? process.platform;
294
- const arch = opts.arch ?? process.arch;
295
- const bunVersion = opts.bunVersion ?? Bun.version;
296
- if (compareSemver(bunVersion, MIN_BUN_VERSION) < 0) {
297
- throw new ErrBunVersionTooOld(bunVersion, MIN_BUN_VERSION);
298
- }
299
- const tuple = `${platform}-${arch}`;
300
- const subpkgName = SUPPORTED_TUPLES.get(tuple);
301
- if (!subpkgName) {
302
- throw new ErrUnsupportedPlatform(tuple);
303
- }
304
- const binaryExt = platform === "darwin" ? "dylib" : "so";
305
- const binaryName = `libagent_director.${binaryExt}`;
306
- const cabiDir = process.env.AD_CABI_DIR;
307
- if (cabiDir) {
308
- const cabiPath = join(cabiDir, binaryName);
309
- if (!existsSync(cabiPath)) {
310
- throw new ErrPlatformPackageMissing(subpkgName, `AD_CABI_DIR is set but "${binaryName}" not found in ${cabiDir}`);
311
- }
312
- return cabiPath;
313
- }
314
- let pkgDir;
315
- try {
316
- const resolved = import.meta.resolve(`${subpkgName}/package.json`);
317
- pkgDir = dirname(fileURLToPath(resolved));
318
- } catch {
319
- throw new ErrPlatformPackageMissing(subpkgName);
320
- }
321
- const libPath = join(pkgDir, binaryName);
322
- if (!existsSync(libPath)) {
323
- throw new ErrPlatformPackageMissing(subpkgName, `binary "${binaryName}" not found in package directory ${pkgDir}`);
324
- }
325
- return libPath;
326
- }
327
- function _loadNativeInternal(opts = {}) {
328
- const libPath = resolveNativePath(opts);
329
- const bindingSpec = buildBindingSpec();
330
- const loaded = dlopen(libPath, bindingSpec);
331
- return { lib: loaded.symbols, libPath };
332
- }
333
- function loadNative() {
334
- return _loadNativeInternal();
335
- }
336
-
337
- // src/internal/worker.ts
338
- if (parentPort === null) {
339
- throw new Error("worker.ts must run inside a node:worker_threads Worker");
340
- }
341
- var port = parentPort;
342
- function fatalStartup(message) {
343
- port.postMessage({ id: -1, type: "startup-error", message });
344
- process.exit(1);
345
- }
346
- function doLoadNative() {
347
- try {
348
- const { lib } = loadNative();
349
- return lib;
350
- } catch (e) {
351
- const msg = e instanceof Error ? e.message : String(e);
352
- fatalStartup(`Failed to load native library: ${msg}`);
353
- }
354
- }
355
- var lib = doLoadNative();
356
- port.postMessage({ id: -1, type: "ready" });
357
- function getSymbol(name) {
358
- const sym = lib[name];
359
- if (typeof sym !== "function") {
360
- throw new Error(`symbol not found in loaded library: ${name}`);
361
- }
362
- return sym;
363
- }
364
- function callSymbol(fn, jsonArg) {
365
- const inputBuf = Buffer.from(jsonArg + "\x00", "utf8");
366
- const rawPtr = fn(ptr(inputBuf));
367
- if (rawPtr === null || rawPtr === 0) {
368
- throw new Error("C-ABI function returned a null pointer");
369
- }
370
- const freeSymbol = getSymbol("ad_free_cstring");
371
- const guard = new FreeGuard(rawPtr, (p) => {
372
- freeSymbol(p);
373
- });
374
- try {
375
- return new CString(guard.ptr).toString();
376
- } finally {
377
- guard.free();
378
- }
379
- }
380
- port.on("message", (msg) => {
381
- const { id, op, handle, paramsJSON } = msg;
382
- let jsonString;
383
- try {
384
- if (op === "open") {
385
- jsonString = callSymbol(getSymbol("ad_open"), paramsJSON);
386
- } else if (op === "close") {
387
- const closeJSON = handle !== null ? JSON.stringify({ handle }) : "{}";
388
- jsonString = callSymbol(getSymbol("ad_close"), closeJSON);
389
- } else {
390
- const symbolName = "ad_" + kebabToUnderscore(op);
391
- const verbFn = getSymbol(symbolName);
392
- let inputJSON;
393
- if (handle !== null && !isHandleFree(op)) {
394
- const parsedParams = JSON.parse(paramsJSON);
395
- parsedParams.handle = handle;
396
- inputJSON = JSON.stringify(parsedParams);
397
- } else {
398
- inputJSON = paramsJSON;
399
- }
400
- jsonString = callSymbol(verbFn, inputJSON);
401
- }
402
- } catch (e) {
403
- port.postMessage({
404
- id,
405
- type: "ffi-error",
406
- message: e instanceof Error ? e.message : String(e)
407
- });
408
- return;
409
- }
410
- port.postMessage({
411
- id,
412
- type: "result",
413
- jsonString
414
- });
415
- });
@@ -1,45 +0,0 @@
1
- /**
2
- * workerProxy.ts — main-thread singleton proxy for the FFI worker.
3
- *
4
- * The six-step C-ABI call recipe splits across two files:
5
- * worker.ts → steps 1–4: encode JSON → call C symbol → copy CString →
6
- * free pointer (try/finally)
7
- * workerProxy.ts → steps 5–6: parse raw JSON string → check err_name →
8
- * throw typed error (via errorFromEnvelope) or return result
9
- *
10
- * See src/ffi.ts for the public callVerb facade that drives this module.
11
- *
12
- * Architecture
13
- * ────────────
14
- * A single dedicated Worker is spawned lazily on the first call to dispatch.
15
- * The Worker lives for the lifetime of the process (or until shutdown() is
16
- * called). All Client instances in the process share the same worker.
17
- *
18
- * Correlation IDs
19
- * ───────────────
20
- * Each dispatch call mints a monotonically increasing id and inserts a
21
- * {resolve, reject} pair into `_pending`. The worker echoes the id back in
22
- * every response so the correct Promise can be settled.
23
- *
24
- * Error envelope decoding
25
- * ───────────────────────
26
- * The worker returns raw JSON strings only. This module parses them and, if
27
- * `err_name` is present, calls errorFromEnvelope() so the error-class graph
28
- * is loaded once (on the main thread), not inside every worker thread.
29
- */
30
- /**
31
- * workerProxy is the mutable singleton used by callVerb (and tests).
32
- * Exporting an object (rather than a bare function) allows tests to replace
33
- * `workerProxy.dispatch` without module-level mocking:
34
- *
35
- * import { workerProxy } from "../src/internal/workerProxy.js";
36
- * workerProxy.dispatch = mock(async () => '{"version":"test"}');
37
- */
38
- export declare const workerProxy: {
39
- dispatch: (op: string, handle: string | null, params: unknown) => Promise<unknown>;
40
- };
41
- /**
42
- * shutdown terminates the worker and rejects all pending dispatches. Call
43
- * this in tests (afterAll) to prevent lingering worker threads.
44
- */
45
- export declare function shutdown(): void;
@@ -1,80 +0,0 @@
1
- /**
2
- * platform — native library resolver for agent-director.
3
- *
4
- * Implements the five-step resolution sequence:
5
- * 1. Check Bun.version against MIN_BUN_VERSION → ErrBunVersionTooOld
6
- * 2. Map process.platform + process.arch to an npm sub-package name →
7
- * ErrUnsupportedPlatform for unknown tuples
8
- * 3. Locate the sub-package on disk via import.meta.resolve →
9
- * ErrPlatformPackageMissing when not installed
10
- * 4. Compute binary path inside the package and verify existence →
11
- * ErrPlatformPackageMissing when binary absent (e.g. CI host mismatch)
12
- * 5. dlopen with the full binding spec → return { lib: symbols, libPath }
13
- *
14
- * resolveNativePath() exports just the path (used by bootstrapFfi.ts which
15
- * keeps its own minimal dlopen).
16
- *
17
- * loadNative() / _loadNativeInternal() dlopen the full binding spec and return
18
- * the symbols object together with the resolved path.
19
- *
20
- * _loadNativeInternal() accepts a PlatformLoadOpts bag for test injection
21
- * (override platform, arch, bunVersion without monkey-patching globals).
22
- *
23
- * Internal — NOT re-exported from src/index.ts.
24
- */
25
- /** Minimum Bun runtime version required by this package (from T1). */
26
- export declare const MIN_BUN_VERSION = "1.0.21";
27
- /**
28
- * PlatformLoadOpts — dependency-injection bag for loadNative / resolveNativePath.
29
- *
30
- * All fields are optional; missing fields fall back to the real process
31
- * globals. Pass these in unit tests to exercise error branches without
32
- * monkey-patching process.platform or Bun.version.
33
- */
34
- export interface PlatformLoadOpts {
35
- /** Override process.platform (e.g. "linux", "darwin"). */
36
- platform?: string;
37
- /** Override process.arch (e.g. "x64", "arm64"). */
38
- arch?: string;
39
- /** Override Bun.version (e.g. "1.0.0" to trigger ErrBunVersionTooOld). */
40
- bunVersion?: string;
41
- }
42
- /**
43
- * resolveNativePath performs the platform check and sub-package lookup,
44
- * returning the absolute path to the native shared library.
45
- *
46
- * If process.env.AD_CABI_DIR is set, the binary is loaded from
47
- * "${AD_CABI_DIR}/libagent_director.{so,dylib}" instead of the npm
48
- * sub-package. release.sh's verify_phase exports this so smoke tests
49
- * can run before the cabi artifacts have been staged into platforms/.
50
- *
51
- * Throws one of:
52
- * ErrBunVersionTooOld — Bun version < MIN_BUN_VERSION
53
- * ErrUnsupportedPlatform — platform/arch tuple not in SUPPORTED_TUPLES
54
- * ErrPlatformPackageMissing — sub-package not installed or binary absent
55
- */
56
- export declare function resolveNativePath(opts?: PlatformLoadOpts): string;
57
- /** Symbols returned by dlopen with the full binding spec. */
58
- export type NativeLib = Record<string, unknown>;
59
- /**
60
- * _loadNativeInternal is the testable core of loadNative().
61
- *
62
- * Accepts PlatformLoadOpts for dependency injection of platform / arch /
63
- * Bun.version so tests can exercise every error branch without live binaries.
64
- *
65
- * @returns { lib, libPath } — lib is the dlopen symbols object; libPath is the
66
- * absolute path to the .so/.dylib that was loaded (useful for logging).
67
- */
68
- export declare function _loadNativeInternal(opts?: PlatformLoadOpts): {
69
- lib: NativeLib;
70
- libPath: string;
71
- };
72
- /**
73
- * loadNative is the public entry point called by worker.ts at startup.
74
- *
75
- * Uses the real process.platform, process.arch, and Bun.version.
76
- */
77
- export declare function loadNative(): {
78
- lib: NativeLib;
79
- libPath: string;
80
- };