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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-director",
3
- "version": "0.4.5",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "os": [
6
6
  "linux",
@@ -39,11 +39,12 @@
39
39
  "prepack": "bun run build && bun run scripts/stage-skill.ts",
40
40
  "postinstall": "bun run scripts/postinstall.ts",
41
41
  "version-bump-publish": "bun run scripts/version-bump.ts",
42
- "prepublishOnly": "bun run scripts/prepublish-guards.ts"
42
+ "prepublishOnly": "bun run scripts/prepublish-guards.ts",
43
+ "verify-installed-pkg": "bun run scripts/verify-installed-pkg.ts"
43
44
  },
44
45
  "optionalDependencies": {
45
- "@agent-director/linux-x64": "^0.4.5",
46
- "@agent-director/darwin-arm64": "^0.4.5"
46
+ "@agent-director/linux-x64": "^0.5.1",
47
+ "@agent-director/darwin-arm64": "^0.5.1"
47
48
  },
48
49
  "devDependencies": {
49
50
  "typescript": ">=5.2.0",
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: install-agent-director
3
3
  description: Install (or upgrade) agent-director on this machine. Runs the bundled install.sh against the user's ~/ — creates ~/.agent-director/ with the binary, warms up state.db, and injects two persistent `agent-director help` hooks into ~/.claude/settings.json (SessionStart + SessionEnd reason=compact). Use this skill when the user says "install agent-director", "set up agent-director", or "upgrade agent-director on this machine".
4
- version: 0.4.5
4
+ version: 0.5.1
5
5
  ---
6
6
 
7
7
  ## When to invoke
package/dist/ffi.d.ts DELETED
@@ -1,42 +0,0 @@
1
- /**
2
- * ffi.ts — public facade for the C-ABI call recipe.
3
- *
4
- * The six-step FFI recipe is split across three files:
5
- *
6
- * src/internal/worker.ts — steps 1–4 (runs inside the worker thread)
7
- * 1. Encode params as null-terminated UTF-8 JSON
8
- * 2. Call the C symbol via Bun dlopen
9
- * 3. Copy the returned CString to a JS string
10
- * 4. Free the C pointer via ad_free_cstring (try/finally — error path frees too)
11
- *
12
- * src/internal/workerProxy.ts — steps 5–6 (main thread, post-worker)
13
- * 5. Parse the raw JSON string
14
- * 6. If err_name present → throw typed error via errorFromEnvelope;
15
- * else → return parsed result
16
- *
17
- * src/ffi.ts (this file) — thin public facade
18
- * Exposes callVerb<P, R> that routes to workerProxy.dispatch and casts.
19
- *
20
- * WHY a worker?
21
- * Bun FFI has no per-symbol `async: true` marker. Without the worker, every
22
- * C call would block the JS event loop. The worker runs in a separate thread
23
- * so verb calls are off-main-thread and the event loop stays responsive.
24
- * See src/internal/workerProxy.ts for the singleton design rationale.
25
- *
26
- * Internal — NOT re-exported from src/index.ts.
27
- */
28
- export { VERBS, KEBAB_TO_CAMEL } from "./internal/verbs.js";
29
- export type { VerbName } from "./internal/verbs.js";
30
- export { BINDING_SYMBOL_NAMES } from "./internal/bindingSpec.js";
31
- export { shutdown as shutdownWorker } from "./internal/workerProxy.js";
32
- /**
33
- * callVerb dispatches a verb call through the dedicated worker thread and
34
- * returns a Promise that resolves with the typed result R or rejects with a
35
- * typed AgentDirectorError.
36
- *
37
- * @param verb Kebab-case verb name (e.g. "send-keys", "make-template")
38
- * @param handle Opaque Client handle from ad_open, or null for handle-free
39
- * verbs (currently only "version")
40
- * @param params Verb-specific params object; JSON-serialized inside dispatch
41
- */
42
- export declare function callVerb<P, R>(verb: string, handle: string | null, params: P): Promise<R>;
@@ -1,37 +0,0 @@
1
- /**
2
- * bindingSpec — canonical set of C-ABI symbol names expected in the dlopen
3
- * binding object, plus a factory that builds the runtime FFI binding spec.
4
- *
5
- * BINDING_SYMBOL_NAMES is exported as a plain string array so the
6
- * binding-coverage test can import it WITHOUT spawning a worker or loading
7
- * the native library.
8
- *
9
- * buildBindingSpec() returns the full FFI binding object suitable for passing
10
- * directly to Bun's dlopen(). It is the single source of truth consumed by
11
- * platform.ts::loadNative() so that worker.ts and bootstrapFfi.ts both
12
- * resolve the same symbols without duplication.
13
- *
14
- * Any drift between BINDING_SYMBOL_NAMES and buildBindingSpec() is caught
15
- * by test/ffi-binding-coverage.test.ts.
16
- */
17
- import { FFIType } from "bun:ffi";
18
- /**
19
- * BINDING_SYMBOL_NAMES is the exhaustive list of C symbols that the worker's
20
- * dlopen binding object must declare.
21
- */
22
- export declare const BINDING_SYMBOL_NAMES: readonly string[];
23
- /** A single FFI function declaration (args + return type). */
24
- export interface FFISymbolDef {
25
- args: FFIType[];
26
- returns: FFIType;
27
- }
28
- /** The full dlopen binding spec as a plain object — pass to Bun's dlopen(). */
29
- export type BindingSpec = Record<string, FFISymbolDef>;
30
- /**
31
- * buildBindingSpec constructs the full FFI binding map for the native library.
32
- *
33
- * Includes lifecycle symbols (ad_open, ad_close, ad_free_cstring) plus one
34
- * entry per callable verb. All verb symbols take a single cstring argument and
35
- * return a ptr (raw pointer, freed via ad_free_cstring).
36
- */
37
- export declare function buildBindingSpec(): BindingSpec;
@@ -1,37 +0,0 @@
1
- /**
2
- * bootstrapFfi — thin synchronous dlopen wrapper used by the Client
3
- * constructor and close().
4
- *
5
- * Only three symbols are needed here: ad_open, ad_close, ad_free_cstring.
6
- * The full binding spec (all 18 symbols) is used by worker.ts via loadNative().
7
- *
8
- * Library path resolution delegates to platform.ts::resolveNativePath() so
9
- * that all platforms (linux-x64, darwin-arm64) resolve their binary from the
10
- * correct optional sub-package, and so this file shares the same path logic
11
- * as the worker.
12
- *
13
- * Internal — NOT re-exported from src/index.ts.
14
- */
15
- /**
16
- * callOpen encodes params as JSON, calls ad_open, copies the returned C
17
- * string into a JS string, frees the C pointer, and returns the envelope
18
- * JSON string.
19
- *
20
- * Throws if the library call itself fails (i.e. the function pointer is
21
- * null) — normal Go-level errors are returned as error envelopes, not
22
- * thrown.
23
- */
24
- export declare function callOpen(params: {
25
- store_path: string;
26
- config_path?: string;
27
- tmux_command?: string;
28
- create_if_missing?: boolean;
29
- }): string;
30
- /**
31
- * callClose encodes params as JSON, calls ad_close, copies the returned C
32
- * string into a JS string, frees the C pointer, and returns the envelope
33
- * JSON string.
34
- */
35
- export declare function callClose(params: {
36
- handle: string;
37
- }): string;
@@ -1,39 +0,0 @@
1
- /**
2
- * FreeGuard — single-free wrapper for native pointers.
3
- *
4
- * Every C-ABI call that returns a pointer must pass it to `ad_free_cstring`
5
- * exactly once. FreeGuard enforces this:
6
- *
7
- * const guard = new FreeGuard(rawPtr, (p) => lib.symbols.ad_free_cstring(p));
8
- * try {
9
- * const str = new CString(guard.ptr!).toString();
10
- * return str;
11
- * } finally {
12
- * guard.free(); // safe to call even on error path; no-op on second call
13
- * }
14
- *
15
- * Design constraints:
16
- * - No bun:ffi imports — accepts the free function as a constructor arg so
17
- * tests can stub it without loading a native library.
18
- * - Generic over T so the same guard works for Pointer (branded number) or
19
- * any other pointer-like primitive without widening to `any`.
20
- * - `free()` nulls the internal reference before calling the underlying
21
- * free function, so a synchronous exception inside the free function
22
- * cannot cause a double-free on a subsequent call.
23
- */
24
- export declare class FreeGuard<T> {
25
- private _ptr;
26
- private readonly _free;
27
- constructor(ptr: T, free: (p: T) => void);
28
- /**
29
- * ptr returns the guarded pointer, or null if `free()` has already been
30
- * called. Callers must check for null before dereferencing.
31
- */
32
- get ptr(): T | null;
33
- /**
34
- * free calls the underlying free function with the guarded pointer exactly
35
- * once. After the first call, the internal reference is nulled and
36
- * subsequent calls are silent no-ops.
37
- */
38
- free(): void;
39
- }
@@ -1,36 +0,0 @@
1
- /**
2
- * worker.ts — worker-thread entry-point for all C-ABI FFI calls.
3
- *
4
- * This module runs INSIDE a node:worker_threads Worker. It is never imported
5
- * by the main thread. Its sole job is:
6
- *
7
- * 1. At startup: resolve the native library path via loadNative(), post {type:"ready"}.
8
- * 2. On every message: receive {id, op, handle, paramsJSON}, build the
9
- * single-arg JSON for the C symbol, call it, copy the returned C string
10
- * to JS, free the native pointer (try/finally so the error path also
11
- * frees), and post the raw JSON string back to the main thread.
12
- *
13
- * WHY a dedicated worker?
14
- * ───────────────────────
15
- * Bun's dlopen has no per-symbol `async: true` marker. Calling a C function
16
- * directly on the main thread blocks the JS event loop for the duration of
17
- * that call. By running all FFI in a dedicated worker, verb calls are truly
18
- * off-main-thread — the event loop remains responsive during long-running
19
- * Go-side operations.
20
- *
21
- * One worker per process (singleton, not a pool): the Go runtime inside the
22
- * shared library carries process-global state (the handle registry). Multiple
23
- * parallel dlopen handles would split that state and break audit-trail
24
- * invariants. A single serialized worker is the correct model.
25
- *
26
- * Wire format for C calls
27
- * ───────────────────────
28
- * Every C-ABI function takes exactly ONE `char* params_json` argument and
29
- * returns `char* result_json` (which the caller must release via
30
- * ad_free_cstring). The handle field is embedded inside the JSON:
31
- * - ad_open → paramsJSON (no handle)
32
- * - ad_close → {"handle":"<token>"}
33
- * - ad_<verb> → {"handle":"<token>", ...verb-params}
34
- * - ad_version → {} (handle-free)
35
- */
36
- export {};
@@ -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;