@nimbus-dev/client 0.2.3

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.cjs ADDED
@@ -0,0 +1,774 @@
1
+ var __create = Object.create;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __toCommonJS = (from) => {
33
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
34
+ if (entry)
35
+ return entry;
36
+ entry = __defProp({}, "__esModule", { value: true });
37
+ if (from && typeof from === "object" || typeof from === "function") {
38
+ for (var key of __getOwnPropNames(from))
39
+ if (!__hasOwnProp.call(entry, key))
40
+ __defProp(entry, key, {
41
+ get: __accessProp.bind(from, key),
42
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
43
+ });
44
+ }
45
+ __moduleCache.set(from, entry);
46
+ return entry;
47
+ };
48
+ var __moduleCache;
49
+ var __returnValue = (v) => v;
50
+ function __exportSetter(name, newValue) {
51
+ this[name] = __returnValue.bind(null, newValue);
52
+ }
53
+ var __export = (target, all) => {
54
+ for (var name in all)
55
+ __defProp(target, name, {
56
+ get: all[name],
57
+ enumerable: true,
58
+ configurable: true,
59
+ set: __exportSetter.bind(all, name)
60
+ });
61
+ };
62
+
63
+ // src/index.ts
64
+ var exports_src = {};
65
+ __export(exports_src, {
66
+ readGatewayState: () => readGatewayState,
67
+ getNimbusPaths: () => getNimbusPaths,
68
+ gatewayStatePath: () => gatewayStatePath,
69
+ discoverSocketPath: () => discoverSocketPath,
70
+ NimbusClient: () => NimbusClient,
71
+ MockClient: () => MockClient,
72
+ IPCClient: () => IPCClient
73
+ });
74
+ module.exports = __toCommonJS(exports_src);
75
+
76
+ // src/discovery.ts
77
+ var import_node_fs = require("node:fs");
78
+ var import_promises = require("node:fs/promises");
79
+ var import_node_path2 = require("node:path");
80
+
81
+ // src/paths.ts
82
+ var import_node_os = require("node:os");
83
+ var import_node_path = require("node:path");
84
+ var import_posix = require("node:path/posix");
85
+ function envOrEmpty(key) {
86
+ const v = process.env[key];
87
+ return typeof v === "string" ? v : "";
88
+ }
89
+ function getNimbusPaths() {
90
+ switch (process.platform) {
91
+ case "win32": {
92
+ const appData = envOrEmpty("APPDATA");
93
+ const localAppData = envOrEmpty("LOCALAPPDATA");
94
+ if (appData.length === 0) {
95
+ throw new Error("APPDATA is not set. Nimbus requires a standard Windows user profile.");
96
+ }
97
+ if (localAppData.length === 0) {
98
+ throw new Error("LOCALAPPDATA is not set. Nimbus requires a standard Windows user profile.");
99
+ }
100
+ const configDir = import_node_path.join(appData, "Nimbus");
101
+ const dataDir = import_node_path.join(localAppData, "Nimbus", "data");
102
+ return {
103
+ configDir,
104
+ dataDir,
105
+ logDir: import_node_path.join(dataDir, "logs"),
106
+ socketPath: String.raw`\\.\pipe\nimbus-gateway`,
107
+ extensionsDir: import_node_path.join(localAppData, "Nimbus", "extensions")
108
+ };
109
+ }
110
+ case "darwin": {
111
+ const root = import_posix.join(import_node_os.homedir(), "Library", "Application Support", "Nimbus");
112
+ const tmp = envOrEmpty("TMPDIR") || "/tmp";
113
+ return {
114
+ configDir: root,
115
+ dataDir: root,
116
+ logDir: import_posix.join(root, "logs"),
117
+ socketPath: import_posix.join(tmp, "nimbus-gateway.sock"),
118
+ extensionsDir: import_posix.join(root, "extensions")
119
+ };
120
+ }
121
+ default: {
122
+ const home = import_node_os.homedir();
123
+ const configRoot = envOrEmpty("XDG_CONFIG_HOME") || import_posix.join(home, ".config");
124
+ const dataRoot = envOrEmpty("XDG_DATA_HOME") || import_posix.join(home, ".local", "share");
125
+ const runtimeDir = envOrEmpty("XDG_RUNTIME_DIR") || import_node_os.tmpdir();
126
+ const configDir = import_posix.join(configRoot, "nimbus");
127
+ const dataDir = import_posix.join(dataRoot, "nimbus");
128
+ return {
129
+ configDir,
130
+ dataDir,
131
+ logDir: import_posix.join(dataDir, "logs"),
132
+ socketPath: import_posix.join(runtimeDir, "nimbus-gateway.sock"),
133
+ extensionsDir: import_posix.join(dataDir, "extensions")
134
+ };
135
+ }
136
+ }
137
+ }
138
+
139
+ // src/discovery.ts
140
+ function isGatewayState(raw) {
141
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
142
+ return false;
143
+ const o = raw;
144
+ if (typeof o["pid"] !== "number" || !Number.isFinite(o["pid"]))
145
+ return false;
146
+ if (typeof o["socketPath"] !== "string" || o["socketPath"].length === 0)
147
+ return false;
148
+ if (o["logPath"] !== undefined && typeof o["logPath"] !== "string")
149
+ return false;
150
+ return true;
151
+ }
152
+ function gatewayStatePath(paths) {
153
+ return import_node_path2.join(paths.dataDir, "gateway.json");
154
+ }
155
+ async function readGatewayState(paths) {
156
+ const p = gatewayStatePath(paths);
157
+ if (!import_node_fs.existsSync(p))
158
+ return;
159
+ try {
160
+ const raw = JSON.parse(await import_promises.readFile(p, "utf8"));
161
+ if (!isGatewayState(raw))
162
+ return;
163
+ const logPath = typeof raw.logPath === "string" && raw.logPath !== "" ? raw.logPath : undefined;
164
+ return { pid: raw.pid, socketPath: raw.socketPath, ...logPath !== undefined && { logPath } };
165
+ } catch {
166
+ return;
167
+ }
168
+ }
169
+ async function discoverSocketPath(opts) {
170
+ if (opts?.override !== undefined && opts.override.length > 0) {
171
+ return { socketPath: opts.override, source: "override" };
172
+ }
173
+ const paths = opts?.paths ?? getNimbusPaths();
174
+ const state = await readGatewayState(paths);
175
+ if (state !== undefined) {
176
+ return { socketPath: state.socketPath, source: "stateFile", pid: state.pid };
177
+ }
178
+ return { socketPath: paths.socketPath, source: "default" };
179
+ }
180
+ // src/ipc-transport.ts
181
+ var import_node_crypto = require("node:crypto");
182
+ var import_node_net = __toESM(require("node:net"));
183
+ var import_node_os2 = require("node:os");
184
+
185
+ // ../sdk/src/ipc/ndjson-line-reader.ts
186
+ var IPC_MAX_LINE_BYTES = 1024 * 1024;
187
+ function byteLengthUtf8(s) {
188
+ return new TextEncoder().encode(s).length;
189
+ }
190
+
191
+ class NdjsonLineReader {
192
+ lineLimitCtor;
193
+ decoder = new TextDecoder("utf-8", { fatal: false });
194
+ pending = "";
195
+ constructor(opts = {}) {
196
+ this.lineLimitCtor = opts.lineLimitError ?? Error;
197
+ }
198
+ throwLineTooLong(message) {
199
+ throw new this.lineLimitCtor(message);
200
+ }
201
+ push(chunk) {
202
+ this.pending += this.decoder.decode(chunk, { stream: true });
203
+ const out = [];
204
+ while (true) {
205
+ const nl = this.pending.indexOf(`
206
+ `);
207
+ if (nl < 0) {
208
+ break;
209
+ }
210
+ const line = this.pending.slice(0, nl);
211
+ this.pending = this.pending.slice(nl + 1);
212
+ const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
213
+ if (trimmed.length === 0) {
214
+ continue;
215
+ }
216
+ if (byteLengthUtf8(trimmed) > IPC_MAX_LINE_BYTES) {
217
+ this.throwLineTooLong("Message exceeds 1MB line limit");
218
+ }
219
+ out.push(trimmed);
220
+ }
221
+ if (byteLengthUtf8(this.pending) > IPC_MAX_LINE_BYTES) {
222
+ this.throwLineTooLong("Message exceeds 1MB line limit");
223
+ }
224
+ return out;
225
+ }
226
+ flush() {
227
+ const rest = this.pending + this.decoder.decode();
228
+ this.pending = "";
229
+ if (rest.length === 0) {
230
+ return [];
231
+ }
232
+ if (byteLengthUtf8(rest) > IPC_MAX_LINE_BYTES) {
233
+ this.throwLineTooLong("Message exceeds 1MB line limit");
234
+ }
235
+ return [rest.endsWith("\r") ? rest.slice(0, -1) : rest];
236
+ }
237
+ }
238
+ // src/ipc-transport.ts
239
+ var HAS_BUN = globalThis.Bun !== undefined;
240
+ function idKey(id) {
241
+ return typeof id === "number" ? `n:${id}` : `s:${id}`;
242
+ }
243
+ function jsonRpcErrorMessage(err) {
244
+ if (typeof err !== "object" || err === null) {
245
+ return "JSON-RPC error";
246
+ }
247
+ if (!("message" in err)) {
248
+ return "JSON-RPC error";
249
+ }
250
+ const msg = err.message;
251
+ if (typeof msg !== "string") {
252
+ return "JSON-RPC error";
253
+ }
254
+ return msg;
255
+ }
256
+ function tryParseJsonRecord(line) {
257
+ try {
258
+ return JSON.parse(line);
259
+ } catch {
260
+ return;
261
+ }
262
+ }
263
+
264
+ class IPCClient {
265
+ socketPath;
266
+ reader = new NdjsonLineReader;
267
+ pending = new Map;
268
+ notifHandlers = new Map;
269
+ bunSocket = null;
270
+ netSocket = null;
271
+ connected = false;
272
+ constructor(socketPath) {
273
+ this.socketPath = socketPath;
274
+ }
275
+ async connect() {
276
+ if (this.connected) {
277
+ return;
278
+ }
279
+ this.reader = new NdjsonLineReader;
280
+ if (import_node_os2.platform() === "win32") {
281
+ await this.connectWindows();
282
+ return;
283
+ }
284
+ await this.connectUnix();
285
+ }
286
+ async connectWindows() {
287
+ await new Promise((resolve, reject) => {
288
+ const sock = import_node_net.default.createConnection(this.socketPath);
289
+ this.attachNetSocket(sock, resolve, reject);
290
+ });
291
+ }
292
+ attachNetSocket(sock, resolve, reject) {
293
+ sock.on("connect", () => {
294
+ this.netSocket = sock;
295
+ this.connected = true;
296
+ resolve();
297
+ });
298
+ sock.on("error", (err) => {
299
+ reject(err);
300
+ });
301
+ sock.on("data", (buf) => {
302
+ this.onTransportData(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
303
+ });
304
+ sock.on("close", () => {
305
+ this.onNetSocketClosed();
306
+ });
307
+ }
308
+ async connectUnix() {
309
+ if (HAS_BUN) {
310
+ await this.connectUnixBun();
311
+ return;
312
+ }
313
+ await this.connectUnixNode();
314
+ }
315
+ async connectUnixBun() {
316
+ this.bunSocket = await Bun.connect({
317
+ unix: this.socketPath,
318
+ socket: {
319
+ data: (_socket, chunk) => {
320
+ this.onTransportData(chunk);
321
+ },
322
+ close: () => {
323
+ this.onUnixClosed(new Error("IPC connection closed"));
324
+ },
325
+ error: () => {
326
+ this.onUnixClosed(new Error("IPC connection error"));
327
+ }
328
+ }
329
+ });
330
+ this.connected = true;
331
+ }
332
+ async connectUnixNode() {
333
+ await new Promise((resolve, reject) => {
334
+ const sock = import_node_net.default.createConnection({ path: this.socketPath });
335
+ this.attachNetSocket(sock, resolve, reject);
336
+ });
337
+ }
338
+ onTransportData(chunk) {
339
+ try {
340
+ this.ingest(chunk);
341
+ } catch (e) {
342
+ this.failAll(e);
343
+ }
344
+ }
345
+ onNetSocketClosed() {
346
+ this.connected = false;
347
+ this.netSocket = null;
348
+ this.failAll(new Error("IPC connection closed"));
349
+ }
350
+ onUnixClosed(err) {
351
+ this.connected = false;
352
+ this.bunSocket = null;
353
+ this.failAll(err);
354
+ }
355
+ async call(method, params) {
356
+ if (!this.connected) {
357
+ throw new Error("IPC client is not connected");
358
+ }
359
+ const id = import_node_crypto.randomUUID();
360
+ const body = {
361
+ jsonrpc: "2.0",
362
+ id,
363
+ method
364
+ };
365
+ if (params !== undefined) {
366
+ body.params = params;
367
+ }
368
+ const line = `${JSON.stringify(body)}
369
+ `;
370
+ return await new Promise((resolve, reject) => {
371
+ this.pending.set(idKey(id), {
372
+ resolve: (v) => resolve(v),
373
+ reject
374
+ });
375
+ this.rawWrite(line);
376
+ });
377
+ }
378
+ onNotification(method, handler) {
379
+ let set = this.notifHandlers.get(method);
380
+ if (set === undefined) {
381
+ set = new Set;
382
+ this.notifHandlers.set(method, set);
383
+ }
384
+ set.add(handler);
385
+ }
386
+ async disconnect() {
387
+ this.connected = false;
388
+ this.failAll(new Error("IPC disconnected"));
389
+ this.endWindowsTransport();
390
+ this.endUnixTransport();
391
+ }
392
+ endWindowsTransport() {
393
+ if (this.netSocket === null) {
394
+ return;
395
+ }
396
+ this.netSocket.end();
397
+ this.netSocket = null;
398
+ }
399
+ endUnixTransport() {
400
+ if (this.bunSocket === null) {
401
+ return;
402
+ }
403
+ this.bunSocket.end();
404
+ this.bunSocket = null;
405
+ }
406
+ rawWrite(s) {
407
+ if (this.netSocket !== null) {
408
+ this.netSocket.write(s);
409
+ return;
410
+ }
411
+ if (this.bunSocket !== null) {
412
+ this.bunSocket.write(s);
413
+ }
414
+ }
415
+ ingest(chunk) {
416
+ const lines = this.reader.push(chunk);
417
+ for (const line of lines) {
418
+ this.dispatchLine(line);
419
+ }
420
+ }
421
+ dispatchLine(line) {
422
+ const o = tryParseJsonRecord(line);
423
+ if (o === undefined) {
424
+ return;
425
+ }
426
+ if (o["jsonrpc"] !== "2.0") {
427
+ return;
428
+ }
429
+ if (Object.hasOwn(o, "id")) {
430
+ this.dispatchRpcLine(o);
431
+ return;
432
+ }
433
+ this.dispatchNotificationLine(o);
434
+ }
435
+ dispatchRpcLine(o) {
436
+ const id = o["id"];
437
+ if (typeof id !== "string" && typeof id !== "number") {
438
+ return;
439
+ }
440
+ const pend = this.pending.get(idKey(id));
441
+ if (pend === undefined) {
442
+ return;
443
+ }
444
+ this.pending.delete(idKey(id));
445
+ if (Object.hasOwn(o, "error")) {
446
+ pend.reject(new Error(jsonRpcErrorMessage(o["error"])));
447
+ return;
448
+ }
449
+ pend.resolve(Object.hasOwn(o, "result") ? o["result"] : undefined);
450
+ }
451
+ dispatchNotificationLine(o) {
452
+ if (typeof o["method"] !== "string") {
453
+ return;
454
+ }
455
+ const params = Object.hasOwn(o, "params") ? o["params"] : undefined;
456
+ const set = this.notifHandlers.get(o["method"]);
457
+ if (set === undefined) {
458
+ return;
459
+ }
460
+ for (const h of set) {
461
+ h(params);
462
+ }
463
+ }
464
+ failAll(reason) {
465
+ const err = reason instanceof Error ? reason : new Error(String(reason));
466
+ if (this.pending.size === 0) {
467
+ return;
468
+ }
469
+ for (const p of this.pending.values()) {
470
+ p.reject(err);
471
+ }
472
+ this.pending.clear();
473
+ }
474
+ }
475
+ // src/mock-client.ts
476
+ class MockClient {
477
+ fixtures;
478
+ constructor(fixtures = {}) {
479
+ this.fixtures = fixtures;
480
+ }
481
+ async agentInvoke(_input, _options) {
482
+ return { reply: this.fixtures.reply ?? "[MockClient] agent.invoke" };
483
+ }
484
+ askStream(_input, _opts) {
485
+ const tokens = this.fixtures.streamTokens ?? ["mock", " token"];
486
+ const reply = this.fixtures.reply ?? tokens.join("");
487
+ let i = 0;
488
+ let cancelled = false;
489
+ const handle = {
490
+ streamId: "mock-stream",
491
+ async cancel() {
492
+ cancelled = true;
493
+ },
494
+ [Symbol.asyncIterator]() {
495
+ return {
496
+ async next() {
497
+ if (cancelled)
498
+ return { value: undefined, done: true };
499
+ if (i < tokens.length) {
500
+ const text = tokens[i];
501
+ i += 1;
502
+ return { value: { type: "token", text }, done: false };
503
+ }
504
+ if (i === tokens.length) {
505
+ i += 1;
506
+ return {
507
+ value: { type: "done", reply, sessionId: "mock-session" },
508
+ done: false
509
+ };
510
+ }
511
+ return { value: undefined, done: true };
512
+ }
513
+ };
514
+ }
515
+ };
516
+ return handle;
517
+ }
518
+ subscribeHitl(_handler) {
519
+ return { dispose: () => {
520
+ return;
521
+ } };
522
+ }
523
+ async getSessionTranscript() {
524
+ return { sessionId: "mock-session", turns: [], hasMore: false };
525
+ }
526
+ async cancelStream() {
527
+ return { ok: true };
528
+ }
529
+ async queryItems(_params) {
530
+ const items = this.fixtures.items ?? [];
531
+ return { items, meta: { limit: items.length, total: items.length } };
532
+ }
533
+ async querySql(_sql) {
534
+ return { rows: [] };
535
+ }
536
+ async auditList() {
537
+ return [];
538
+ }
539
+ async close() {}
540
+ }
541
+ // src/ask-stream.ts
542
+ function createAskStream(ipc, input, opts = {}) {
543
+ const queue = [];
544
+ const waiters = [];
545
+ let done = false;
546
+ let streamIdResolved;
547
+ let cancelled = false;
548
+ let unsubscribers = [];
549
+ const push = (ev) => {
550
+ if (done)
551
+ return;
552
+ if (waiters.length > 0) {
553
+ const w = waiters.shift();
554
+ w.resolve({ value: ev, done: false });
555
+ return;
556
+ }
557
+ queue.push(ev);
558
+ };
559
+ const finish = () => {
560
+ if (done)
561
+ return;
562
+ done = true;
563
+ for (const u of unsubscribers)
564
+ u();
565
+ unsubscribers = [];
566
+ while (waiters.length > 0) {
567
+ const w = waiters.shift();
568
+ w.resolve({ value: undefined, done: true });
569
+ }
570
+ };
571
+ const matchesStream = (params) => {
572
+ return typeof params === "object" && params !== null && typeof params.streamId === "string";
573
+ };
574
+ const subscribe = (streamId) => {
575
+ const onToken = (params) => {
576
+ if (!matchesStream(params) || params.streamId !== streamId)
577
+ return;
578
+ const text = params.text;
579
+ if (typeof text === "string")
580
+ push({ type: "token", text });
581
+ };
582
+ const onDone = (params) => {
583
+ if (!matchesStream(params) || params.streamId !== streamId)
584
+ return;
585
+ const meta = params.meta ?? {};
586
+ const reply = typeof meta.reply === "string" ? meta.reply : "";
587
+ const sessionId = typeof meta.sessionId === "string" ? meta.sessionId : "";
588
+ push({ type: "done", reply, sessionId });
589
+ finish();
590
+ };
591
+ const onError = (params) => {
592
+ if (!matchesStream(params) || params.streamId !== streamId)
593
+ return;
594
+ const code = typeof params.code === "string" ? params.code : "stream_error";
595
+ const message = typeof params.error === "string" ? params.error : "Stream error";
596
+ push({ type: "error", code, message });
597
+ finish();
598
+ };
599
+ const onSubTask = (params) => {
600
+ if (!matchesStream(params) || params.streamId !== streamId)
601
+ return;
602
+ const p = params;
603
+ if (typeof p.subTaskId !== "string" || typeof p.status !== "string")
604
+ return;
605
+ const ev = typeof p.progress === "number" ? {
606
+ type: "subTaskProgress",
607
+ subTaskId: p.subTaskId,
608
+ status: p.status,
609
+ progress: p.progress
610
+ } : { type: "subTaskProgress", subTaskId: p.subTaskId, status: p.status };
611
+ push(ev);
612
+ };
613
+ const onHitl = (params) => {
614
+ if (!matchesStream(params) || params.streamId !== streamId)
615
+ return;
616
+ const p = params;
617
+ if (typeof p.requestId !== "string" || typeof p.prompt !== "string")
618
+ return;
619
+ push({ type: "hitlBatch", requestId: p.requestId, prompt: p.prompt, details: p.details });
620
+ };
621
+ ipc.onNotification("engine.streamToken", onToken);
622
+ ipc.onNotification("engine.streamDone", onDone);
623
+ ipc.onNotification("engine.streamError", onError);
624
+ ipc.onNotification("agent.subTaskProgress", onSubTask);
625
+ ipc.onNotification("agent.hitlBatch", onHitl);
626
+ unsubscribers.push(() => {});
627
+ };
628
+ const startPromise = (async () => {
629
+ const params = { input };
630
+ if (opts.sessionId !== undefined)
631
+ params["sessionId"] = opts.sessionId;
632
+ if (opts.agent !== undefined)
633
+ params["agent"] = opts.agent;
634
+ const result = await ipc.call("engine.askStream", params);
635
+ const sid = result?.streamId;
636
+ if (typeof sid !== "string") {
637
+ push({ type: "error", code: "no_stream_id", message: "Gateway returned no streamId" });
638
+ finish();
639
+ throw new Error("no_stream_id");
640
+ }
641
+ streamIdResolved = sid;
642
+ if (cancelled) {
643
+ await ipc.call("engine.cancelStream", { streamId: sid }).catch(() => {
644
+ return;
645
+ });
646
+ finish();
647
+ return sid;
648
+ }
649
+ subscribe(sid);
650
+ if (opts.signal !== undefined) {
651
+ if (opts.signal.aborted) {
652
+ await ipc.call("engine.cancelStream", { streamId: sid }).catch(() => {
653
+ return;
654
+ });
655
+ finish();
656
+ } else {
657
+ opts.signal.addEventListener("abort", () => {
658
+ ipc.call("engine.cancelStream", { streamId: sid }).catch(() => {
659
+ return;
660
+ });
661
+ finish();
662
+ });
663
+ }
664
+ }
665
+ return sid;
666
+ })();
667
+ startPromise.catch(() => {
668
+ finish();
669
+ });
670
+ const handle = {
671
+ get streamId() {
672
+ return streamIdResolved ?? "";
673
+ },
674
+ async cancel() {
675
+ cancelled = true;
676
+ const sid = streamIdResolved;
677
+ if (sid !== undefined) {
678
+ await ipc.call("engine.cancelStream", { streamId: sid }).catch(() => {
679
+ return;
680
+ });
681
+ }
682
+ finish();
683
+ },
684
+ [Symbol.asyncIterator]() {
685
+ return {
686
+ next() {
687
+ if (queue.length > 0) {
688
+ const ev = queue.shift();
689
+ return Promise.resolve({ value: ev, done: false });
690
+ }
691
+ if (done) {
692
+ return Promise.resolve({ value: undefined, done: true });
693
+ }
694
+ return new Promise((resolve, reject) => {
695
+ waiters.push({ resolve, reject });
696
+ });
697
+ },
698
+ return() {
699
+ finish();
700
+ return Promise.resolve({ value: undefined, done: true });
701
+ }
702
+ };
703
+ }
704
+ };
705
+ return handle;
706
+ }
707
+
708
+ // src/nimbus-client.ts
709
+ class NimbusClient {
710
+ ipc;
711
+ constructor(ipc) {
712
+ this.ipc = ipc;
713
+ }
714
+ static async open(opts) {
715
+ const ipc = new IPCClient(opts.socketPath);
716
+ await ipc.connect();
717
+ return new NimbusClient(ipc);
718
+ }
719
+ async agentInvoke(input, options) {
720
+ return await this.ipc.call("agent.invoke", {
721
+ input,
722
+ stream: options?.stream ?? false,
723
+ ...options?.sessionId === undefined ? {} : { sessionId: options.sessionId },
724
+ ...options?.agent === undefined ? {} : { agent: options.agent }
725
+ });
726
+ }
727
+ askStream(input, opts) {
728
+ return createAskStream(this.ipc, input, opts);
729
+ }
730
+ subscribeHitl(handler) {
731
+ const onBatch = (params) => {
732
+ if (typeof params !== "object" || params === null)
733
+ return;
734
+ const p = params;
735
+ if (typeof p["requestId"] !== "string" || typeof p["prompt"] !== "string")
736
+ return;
737
+ const req = typeof p["streamId"] === "string" ? {
738
+ requestId: p["requestId"],
739
+ prompt: p["prompt"],
740
+ details: p["details"],
741
+ streamId: p["streamId"]
742
+ } : { requestId: p["requestId"], prompt: p["prompt"], details: p["details"] };
743
+ handler(req);
744
+ };
745
+ this.ipc.onNotification("agent.hitlBatch", onBatch);
746
+ return {
747
+ dispose: () => {}
748
+ };
749
+ }
750
+ async getSessionTranscript(params) {
751
+ return await this.ipc.call("engine.getSessionTranscript", params);
752
+ }
753
+ async cancelStream(streamId) {
754
+ return await this.ipc.call("engine.cancelStream", { streamId });
755
+ }
756
+ async queryItems(params) {
757
+ return await this.ipc.call("index.queryItems", {
758
+ services: params.services,
759
+ types: params.types,
760
+ sinceMs: params.sinceMs,
761
+ untilMs: params.untilMs,
762
+ limit: params.limit
763
+ });
764
+ }
765
+ async querySql(sql) {
766
+ return await this.ipc.call("index.querySql", { sql });
767
+ }
768
+ async auditList(limit) {
769
+ return await this.ipc.call("audit.list", { limit: limit ?? 50 });
770
+ }
771
+ async close() {
772
+ await this.ipc.disconnect();
773
+ }
774
+ }