@nimbus-dev/client 0.18.0 → 0.20.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.
Files changed (48) hide show
  1. package/README.md +74 -5
  2. package/dist/agents.d.ts +28 -5
  3. package/dist/agents.d.ts.map +1 -1
  4. package/dist/agents.js +20 -0
  5. package/dist/agents.js.map +1 -1
  6. package/dist/ask-stream.d.ts.map +1 -1
  7. package/dist/ask-stream.js +25 -45
  8. package/dist/ask-stream.js.map +1 -1
  9. package/dist/event-queue.d.ts +29 -0
  10. package/dist/event-queue.d.ts.map +1 -0
  11. package/dist/event-queue.js +42 -0
  12. package/dist/event-queue.js.map +1 -0
  13. package/dist/index.cjs +586 -317
  14. package/dist/index.d.ts +3 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -1
  17. package/dist/index.js.map +1 -1
  18. package/dist/ipc-proof.d.ts +40 -0
  19. package/dist/ipc-proof.d.ts.map +1 -0
  20. package/dist/ipc-proof.js +146 -0
  21. package/dist/ipc-proof.js.map +1 -0
  22. package/dist/ipc-transport.d.ts +23 -0
  23. package/dist/ipc-transport.d.ts.map +1 -1
  24. package/dist/ipc-transport.js +90 -13
  25. package/dist/ipc-transport.js.map +1 -1
  26. package/dist/mock-client.d.ts +12 -17
  27. package/dist/mock-client.d.ts.map +1 -1
  28. package/dist/mock-client.js +142 -131
  29. package/dist/mock-client.js.map +1 -1
  30. package/dist/nimbus-client.d.ts +45 -30
  31. package/dist/nimbus-client.d.ts.map +1 -1
  32. package/dist/nimbus-client.js +49 -38
  33. package/dist/nimbus-client.js.map +1 -1
  34. package/dist/proving-ipc-client.d.ts +38 -0
  35. package/dist/proving-ipc-client.d.ts.map +1 -0
  36. package/dist/proving-ipc-client.js +94 -0
  37. package/dist/proving-ipc-client.js.map +1 -0
  38. package/dist/stream-events.d.ts +7 -0
  39. package/dist/stream-events.d.ts.map +1 -1
  40. package/dist/validate.d.ts +2 -8
  41. package/dist/validate.d.ts.map +1 -1
  42. package/dist/validate.js +24 -21
  43. package/dist/validate.js.map +1 -1
  44. package/dist/workflow-stream.d.ts +8 -1
  45. package/dist/workflow-stream.d.ts.map +1 -1
  46. package/dist/workflow-stream.js +29 -41
  47. package/dist/workflow-stream.js.map +1 -1
  48. package/package.json +5 -5
package/dist/index.cjs CHANGED
@@ -18,13 +18,15 @@ var __toESM = (mod, isNodeMode, target) => {
18
18
  return cached;
19
19
  }
20
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
- });
21
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ if (mod && typeof mod === "object" || typeof mod === "function") {
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ }
28
30
  if (canCache)
29
31
  cache.set(mod, to);
30
32
  return to;
@@ -63,24 +65,33 @@ var __export = (target, all) => {
63
65
  // src/index.ts
64
66
  var exports_src = {};
65
67
  __export(exports_src, {
66
- readGatewayState: () => readGatewayState,
67
- jsonRpcErrorData: () => jsonRpcErrorData,
68
- jsonRpcErrorCode: () => jsonRpcErrorCode,
69
- isJsonRpcError: () => isJsonRpcError,
70
- getNimbusPaths: () => getNimbusPaths,
71
- gatewayStatePath: () => gatewayStatePath,
72
- discoverSocketPath: () => discoverSocketPath,
73
- NimbusClient: () => NimbusClient,
74
- NO_EGRESS_COVERAGE: () => NO_EGRESS_COVERAGE,
75
- MockClient: () => MockClient,
76
- JsonRpcError: () => JsonRpcError,
77
- IpcResponseError: () => IpcResponseError,
78
- IPCClient: () => IPCClient,
79
- EGRESS_GRANULARITIES: () => EGRESS_GRANULARITIES,
80
- EGRESS_COVERAGE_CLASSES: () => EGRESS_COVERAGE_CLASSES,
81
- DEFAULT_AGENT_TIMEOUT_MS: () => DEFAULT_AGENT_TIMEOUT_MS,
68
+ AgentBriefError: () => AgentBriefError,
82
69
  AgentTimeoutError: () => AgentTimeoutError,
83
- AgentBriefError: () => AgentBriefError
70
+ CONSENT_ANSWER_SOURCES: () => CONSENT_ANSWER_SOURCES,
71
+ DEFAULT_AGENT_TIMEOUT_MS: () => DEFAULT_AGENT_TIMEOUT_MS,
72
+ EGRESS_COVERAGE_CLASSES: () => EGRESS_COVERAGE_CLASSES,
73
+ EGRESS_GRANULARITIES: () => EGRESS_GRANULARITIES,
74
+ GatewayProofError: () => GatewayProofError,
75
+ IPCClient: () => IPCClient,
76
+ IpcResponseError: () => IpcResponseError,
77
+ JsonRpcError: () => JsonRpcError,
78
+ MockClient: () => MockClient,
79
+ NO_EGRESS_COVERAGE: () => NO_EGRESS_COVERAGE,
80
+ NimbusClient: () => NimbusClient,
81
+ PROOF_LABEL_CLIENT: () => PROOF_LABEL_CLIENT,
82
+ PROOF_LABEL_SERVER: () => PROOF_LABEL_SERVER,
83
+ ProvingIPCClient: () => ProvingIPCClient,
84
+ SECRET_IPC_METHODS: () => SECRET_IPC_METHODS,
85
+ computeProof: () => computeProof,
86
+ discoverSocketPath: () => discoverSocketPath,
87
+ gatewayStatePath: () => gatewayStatePath,
88
+ getNimbusPaths: () => getNimbusPaths,
89
+ isJsonRpcError: () => isJsonRpcError,
90
+ jsonRpcErrorCode: () => jsonRpcErrorCode,
91
+ jsonRpcErrorData: () => jsonRpcErrorData,
92
+ parseHex32: () => parseHex32,
93
+ proofKeyFileName: () => proofKeyFileName,
94
+ readGatewayState: () => readGatewayState
84
95
  });
85
96
  module.exports = __toCommonJS(exports_src);
86
97
  // node_modules/@nimbus-dev/sdk/src/agents/guard-factory.ts
@@ -112,6 +123,9 @@ var isHuddleBrief = createBriefGuard("huddle", (b) => Array.isArray(b["contribut
112
123
  var isJanitorBrief = createBriefGuard("janitor", (b) => typeof b["idle"] === "boolean" && Array.isArray(b["peersTouched"]), STRICT);
113
124
  var isPreflightBrief = createBriefGuard("preflight", (b) => Array.isArray(b["downstreams"]) && typeof b["anyFailed"] === "boolean" && typeof b["anyIncomplete"] === "boolean", STRICT);
114
125
  var isWhyBrief = createBriefGuard("why", (b) => Array.isArray(b["findings"]), STRICT);
126
+ var isGlossaryBrief = createBriefGuard("glossary", (b) => Array.isArray(b["entries"]) && Array.isArray(b["suggestions"]), STRICT);
127
+ var isDecisionsBrief = createBriefGuard("decisions", (b) => Array.isArray(b["entries"]), STRICT);
128
+ var isOwnershipBrief = createBriefGuard("ownership", (b) => typeof b["coverage"] === "object" && b["coverage"] !== null, STRICT);
115
129
  var BRIEF_GUARDS = {
116
130
  expert: isExpertBrief,
117
131
  impact: isImpactBrief,
@@ -121,7 +135,10 @@ var BRIEF_GUARDS = {
121
135
  huddle: isHuddleBrief,
122
136
  janitor: isJanitorBrief,
123
137
  preflight: isPreflightBrief,
124
- why: isWhyBrief
138
+ why: isWhyBrief,
139
+ glossary: isGlossaryBrief,
140
+ decisions: isDecisionsBrief,
141
+ ownership: isOwnershipBrief
125
142
  };
126
143
  // node_modules/@nimbus-dev/sdk/src/contract-version.ts
127
144
  var CONTRACT_VERSION_PATTERN = /^[1-9][0-9]*$/;
@@ -537,6 +554,18 @@ var NETWORK_BLOCKED_CODES = new Set([
537
554
  var FS_DENIED_CODES = new Set(["EACCES", "EPERM", "EBUSY"]);
538
555
  // src/agents.ts
539
556
  var DEFAULT_AGENT_TIMEOUT_MS = 30000;
557
+ var SUPPORTED_AGENTS = {
558
+ expert: true,
559
+ impact: true,
560
+ catchup: true,
561
+ ghost: true,
562
+ conflicts: true,
563
+ huddle: true,
564
+ janitor: true,
565
+ preflight: true,
566
+ why: true
567
+ };
568
+ var SUPPORTED_AGENT_NAMES = Object.keys(SUPPORTED_AGENTS);
540
569
 
541
570
  class AgentBriefError extends Error {
542
571
  agent;
@@ -684,9 +713,12 @@ async function discoverSocketPath(opts) {
684
713
  }
685
714
  return { socketPath: paths.socketPath, source: "default" };
686
715
  }
716
+ // src/ipc-proof.ts
717
+ var import_node_crypto2 = require("node:crypto");
718
+
687
719
  // src/ipc-transport.ts
688
720
  var import_node_crypto = require("node:crypto");
689
- var import_node_net = __toESM(require("node:net"));
721
+ var import_node_net = __toESM(require("node:net"), 1);
690
722
  var import_node_os2 = require("node:os");
691
723
  var HAS_BUN = globalThis.Bun !== undefined;
692
724
  var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
@@ -748,6 +780,9 @@ function tryParseJsonRecord(line) {
748
780
  return;
749
781
  }
750
782
  }
783
+ function supersededDial() {
784
+ return new Error("IPC connect superseded by a disconnect or a newer connect");
785
+ }
751
786
 
752
787
  class IPCClient {
753
788
  socketPath;
@@ -759,31 +794,58 @@ class IPCClient {
759
794
  bunSocket = null;
760
795
  netSocket = null;
761
796
  connected = false;
797
+ generation = 0;
762
798
  requestTimeoutMs;
763
799
  constructor(socketPath, opts) {
764
800
  this.socketPath = socketPath;
765
801
  this.requestTimeoutMs = opts?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
766
802
  }
803
+ get transportConnected() {
804
+ return this.connected;
805
+ }
806
+ get transportGeneration() {
807
+ return this.generation;
808
+ }
809
+ abortConnection(err) {
810
+ if (!this.connected)
811
+ return;
812
+ this.connected = false;
813
+ this.generation += 1;
814
+ this.failAll(err);
815
+ this.endWindowsTransport();
816
+ this.endUnixTransport();
817
+ this.notifyClosed(err);
818
+ }
767
819
  async connect() {
768
820
  if (this.connected) {
769
821
  return;
770
822
  }
771
823
  this.reader = new NdjsonLineReader;
772
824
  this.closeNotified = false;
825
+ this.generation += 1;
826
+ const gen = this.generation;
773
827
  if (import_node_os2.platform() === "win32") {
774
- await this.connectWindows();
828
+ await this.connectWindows(gen);
775
829
  return;
776
830
  }
777
- await this.connectUnix();
831
+ await this.connectUnix(gen);
832
+ }
833
+ isCurrent(gen) {
834
+ return gen === this.generation;
778
835
  }
779
- async connectWindows() {
836
+ async connectWindows(gen) {
780
837
  await new Promise((resolve, reject) => {
781
838
  const sock = import_node_net.default.createConnection(this.socketPath);
782
- this.attachNetSocket(sock, resolve, reject);
839
+ this.attachNetSocket(sock, gen, resolve, reject);
783
840
  });
784
841
  }
785
- attachNetSocket(sock, resolve, reject) {
842
+ attachNetSocket(sock, gen, resolve, reject) {
786
843
  sock.on("connect", () => {
844
+ if (!this.isCurrent(gen)) {
845
+ sock.destroy();
846
+ reject(supersededDial());
847
+ return;
848
+ }
787
849
  this.netSocket = sock;
788
850
  this.connected = true;
789
851
  resolve();
@@ -792,40 +854,55 @@ class IPCClient {
792
854
  reject(err);
793
855
  });
794
856
  sock.on("data", (buf) => {
857
+ if (!this.isCurrent(gen))
858
+ return;
795
859
  this.onTransportData(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
796
860
  });
797
861
  sock.on("close", () => {
862
+ if (!this.isCurrent(gen))
863
+ return;
798
864
  this.onNetSocketClosed();
799
865
  });
800
866
  }
801
- async connectUnix() {
867
+ async connectUnix(gen) {
802
868
  if (HAS_BUN) {
803
- await this.connectUnixBun();
869
+ await this.connectUnixBun(gen);
804
870
  return;
805
871
  }
806
- await this.connectUnixNode();
872
+ await this.connectUnixNode(gen);
807
873
  }
808
- async connectUnixBun() {
809
- this.bunSocket = await Bun.connect({
874
+ async connectUnixBun(gen) {
875
+ const socket = await Bun.connect({
810
876
  unix: this.socketPath,
811
877
  socket: {
812
878
  data: (_socket, chunk) => {
879
+ if (!this.isCurrent(gen))
880
+ return;
813
881
  this.onTransportData(chunk);
814
882
  },
815
883
  close: () => {
884
+ if (!this.isCurrent(gen))
885
+ return;
816
886
  this.onUnixClosed(new Error("IPC connection closed"));
817
887
  },
818
888
  error: () => {
889
+ if (!this.isCurrent(gen))
890
+ return;
819
891
  this.onUnixClosed(new Error("IPC connection error"));
820
892
  }
821
893
  }
822
894
  });
895
+ if (!this.isCurrent(gen)) {
896
+ socket.end();
897
+ throw supersededDial();
898
+ }
899
+ this.bunSocket = socket;
823
900
  this.connected = true;
824
901
  }
825
- async connectUnixNode() {
902
+ async connectUnixNode(gen) {
826
903
  await new Promise((resolve, reject) => {
827
904
  const sock = import_node_net.default.createConnection({ path: this.socketPath });
828
- this.attachNetSocket(sock, resolve, reject);
905
+ this.attachNetSocket(sock, gen, resolve, reject);
829
906
  });
830
907
  }
831
908
  onTransportData(chunk) {
@@ -930,12 +1007,14 @@ class IPCClient {
930
1007
  offClose(handler) {
931
1008
  this.closeHandlers.delete(handler);
932
1009
  }
933
- async disconnect() {
1010
+ disconnect() {
934
1011
  this.connected = false;
1012
+ this.generation += 1;
935
1013
  this.closeNotified = true;
936
1014
  this.failAll(new Error("IPC disconnected"));
937
1015
  this.endWindowsTransport();
938
1016
  this.endUnixTransport();
1017
+ return Promise.resolve();
939
1018
  }
940
1019
  endWindowsTransport() {
941
1020
  if (this.netSocket === null) {
@@ -1023,37 +1102,176 @@ class IPCClient {
1023
1102
  this.pending.clear();
1024
1103
  }
1025
1104
  }
1105
+
1106
+ // src/ipc-proof.ts
1107
+ var SECRET_IPC_METHODS = new Set([
1108
+ "connector.auth",
1109
+ "vault.set",
1110
+ "vault.get",
1111
+ "extension.credentialSet",
1112
+ "toolgen.credentialSet",
1113
+ "toolgen.create",
1114
+ "scim.setToken",
1115
+ "teamvault.put",
1116
+ "clip.pair",
1117
+ "lan.openPairingWindow"
1118
+ ]);
1119
+ var PROOF_LABEL_SERVER = "nimbus-ipc-v1/server";
1120
+ var PROOF_LABEL_CLIENT = "nimbus-ipc-v1/client";
1121
+ var HEX32 = /^[0-9a-f]{64}$/;
1122
+ function parseHex32(value) {
1123
+ if (typeof value !== "string" || !HEX32.test(value))
1124
+ return;
1125
+ return Uint8Array.from(Buffer.from(value, "hex"));
1126
+ }
1127
+ function toHex(bytes) {
1128
+ return Buffer.from(bytes).toString("hex");
1129
+ }
1130
+ function computeProof(key, label, clientNonce, serverNonce) {
1131
+ const mac = import_node_crypto2.createHmac("sha256", key);
1132
+ mac.update(Buffer.from(label, "utf8"));
1133
+ mac.update(Uint8Array.of(0));
1134
+ mac.update(clientNonce);
1135
+ mac.update(serverNonce);
1136
+ return Uint8Array.from(mac.digest());
1137
+ }
1138
+ function proofMatches(expected, received) {
1139
+ return expected.length === received.length && import_node_crypto2.timingSafeEqual(expected, received);
1140
+ }
1141
+ function proofKeyFileName(socketPath, platform) {
1142
+ const canonical = platform === "win32" ? socketPath.toLowerCase() : socketPath;
1143
+ const id = import_node_crypto2.createHash("sha256").update(canonical, "utf8").digest("hex").slice(0, 16);
1144
+ return `ipc-proof-${id}.key`;
1145
+ }
1146
+ var MESSAGES = {
1147
+ "key-missing": "Could not verify the Nimbus gateway: its proof key is missing or unreadable, so the secret was not sent. If the gateway was started by an older Nimbus, restart it (nimbus stop, then nimbus start). If the gateway keeps its data somewhere else, pass the keyPath option.",
1148
+ impostor: "Something other than your Nimbus gateway is answering on the gateway's socket. The secret was not sent and the connection was closed.",
1149
+ restarted: "The Nimbus gateway restarted while connecting. The secret was not sent and the connection was closed; reconnect (open a new client) and try again.",
1150
+ refused: "The Nimbus gateway refused the proof. The secret was not sent.",
1151
+ unavailable: 'The Nimbus gateway could not publish its proof key; its log says why, on a line starting "ipc proof: unavailable". The secret was not sent.',
1152
+ outdated: "The Nimbus gateway running now predates the proof, so the secret was not sent. Restart it (nimbus stop, then nimbus start).",
1153
+ "no-answer": "The process on the gateway's socket did not answer the proof in time. The secret was not sent and the connection was closed.",
1154
+ "connection-lost": "The connection to the Nimbus gateway closed during the proof. The secret was not sent."
1155
+ };
1156
+
1157
+ class GatewayProofError extends Error {
1158
+ kind;
1159
+ constructor(kind) {
1160
+ super(MESSAGES[kind]);
1161
+ this.name = "GatewayProofError";
1162
+ this.kind = kind;
1163
+ }
1164
+ }
1165
+ var TIMED_OUT = Symbol("proof step timed out");
1166
+ async function proofStep(io, method, params, timeoutMs) {
1167
+ let timer;
1168
+ const timedOut = new Promise((resolve) => {
1169
+ timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs);
1170
+ });
1171
+ let r;
1172
+ try {
1173
+ r = await Promise.race([io.call(method, params), timedOut]);
1174
+ } catch (e) {
1175
+ if (io.isTimeout(e))
1176
+ r = TIMED_OUT;
1177
+ else
1178
+ throw failureOf(e);
1179
+ } finally {
1180
+ clearTimeout(timer);
1181
+ }
1182
+ if (r === TIMED_OUT) {
1183
+ await io.disconnect();
1184
+ throw new GatewayProofError("no-answer");
1185
+ }
1186
+ return typeof r === "object" && r !== null ? r : undefined;
1187
+ }
1188
+ function failureOf(e) {
1189
+ if (!isJsonRpcError(e))
1190
+ return new GatewayProofError("connection-lost");
1191
+ if (e.code === -32601)
1192
+ return new GatewayProofError("outdated");
1193
+ if (e.message === "ERR_PROOF_UNAVAILABLE")
1194
+ return new GatewayProofError("unavailable");
1195
+ return new GatewayProofError("refused");
1196
+ }
1197
+ async function proveGateway(io, opts) {
1198
+ const key = io.readKey();
1199
+ if (key === undefined)
1200
+ throw new GatewayProofError("key-missing");
1201
+ const clientNonce = Uint8Array.from(import_node_crypto2.randomBytes(32));
1202
+ const reply = await proofStep(io, "session.prove", { clientNonce: toHex(clientNonce) }, opts.timeoutMs);
1203
+ const serverNonce = parseHex32(reply?.["serverNonce"]);
1204
+ const serverProof = parseHex32(reply?.["serverProof"]);
1205
+ if (serverNonce === undefined || serverProof === undefined || !proofMatches(computeProof(key, PROOF_LABEL_SERVER, clientNonce, serverNonce), serverProof)) {
1206
+ await io.disconnect();
1207
+ const again = io.readKey();
1208
+ if (again !== undefined && !proofMatches(again, key)) {
1209
+ throw new GatewayProofError("restarted");
1210
+ }
1211
+ throw new GatewayProofError("impostor");
1212
+ }
1213
+ const clientProof = toHex(computeProof(key, PROOF_LABEL_CLIENT, clientNonce, serverNonce));
1214
+ const done = await proofStep(io, "session.proveClient", { clientProof }, opts.timeoutMs);
1215
+ if (done?.["proven"] !== true)
1216
+ throw new GatewayProofError("refused");
1217
+ }
1218
+ // src/event-queue.ts
1219
+ function createEventQueue() {
1220
+ const buffer = [];
1221
+ const waiters = [];
1222
+ let closed = false;
1223
+ return {
1224
+ push(ev) {
1225
+ if (closed)
1226
+ return;
1227
+ const waiter = waiters.shift();
1228
+ if (waiter !== undefined) {
1229
+ waiter({ value: ev, done: false });
1230
+ return;
1231
+ }
1232
+ buffer.push(ev);
1233
+ },
1234
+ close(teardown) {
1235
+ if (closed)
1236
+ return;
1237
+ closed = true;
1238
+ teardown?.();
1239
+ let waiter = waiters.shift();
1240
+ while (waiter !== undefined) {
1241
+ waiter({ value: undefined, done: true });
1242
+ waiter = waiters.shift();
1243
+ }
1244
+ },
1245
+ get closed() {
1246
+ return closed;
1247
+ },
1248
+ next() {
1249
+ if (buffer.length > 0) {
1250
+ return Promise.resolve({ value: buffer.shift(), done: false });
1251
+ }
1252
+ if (closed)
1253
+ return Promise.resolve({ value: undefined, done: true });
1254
+ return new Promise((resolve) => {
1255
+ waiters.push(resolve);
1256
+ });
1257
+ }
1258
+ };
1259
+ }
1260
+
1026
1261
  // src/ask-stream.ts
1027
1262
  function createAskStream(ipc, input, opts = {}) {
1028
- const queue = [];
1029
- const waiters = [];
1030
- let done = false;
1263
+ const events = createEventQueue();
1031
1264
  let streamIdResolved;
1032
1265
  let cancelled = false;
1033
1266
  let unsubscribers = [];
1034
1267
  let early = [];
1035
- const push = (ev) => {
1036
- if (done)
1037
- return;
1038
- if (waiters.length > 0) {
1039
- const w = waiters.shift();
1040
- w.resolve({ value: ev, done: false });
1041
- return;
1042
- }
1043
- queue.push(ev);
1044
- };
1045
1268
  const finish = () => {
1046
- if (done)
1047
- return;
1048
- done = true;
1049
- early = [];
1050
- for (const u of unsubscribers)
1051
- u();
1052
- unsubscribers = [];
1053
- while (waiters.length > 0) {
1054
- const w = waiters.shift();
1055
- w.resolve({ value: undefined, done: true });
1056
- }
1269
+ events.close(() => {
1270
+ early = [];
1271
+ for (const u of unsubscribers)
1272
+ u();
1273
+ unsubscribers = [];
1274
+ });
1057
1275
  };
1058
1276
  const cancelUpstream = async (sid) => {
1059
1277
  await ipc.call("engine.cancelStream", { streamId: sid }).catch(() => {
@@ -1077,20 +1295,20 @@ function createAskStream(ipc, input, opts = {}) {
1077
1295
  const onToken = whenMatched((params) => {
1078
1296
  const text = params.text;
1079
1297
  if (typeof text === "string")
1080
- push({ type: "token", text });
1298
+ events.push({ type: "token", text });
1081
1299
  });
1082
1300
  const onDone = whenMatched((params) => {
1083
1301
  const meta = params.meta ?? {};
1084
1302
  const reply = typeof meta.reply === "string" ? meta.reply : "";
1085
1303
  const sessionId = typeof meta.sessionId === "string" ? meta.sessionId : "";
1086
- push({ type: "done", reply, sessionId });
1304
+ events.push({ type: "done", reply, sessionId });
1087
1305
  finish();
1088
1306
  });
1089
1307
  const onError = whenMatched((params) => {
1090
1308
  const p = params;
1091
1309
  const code = typeof p.code === "string" ? p.code : "stream_error";
1092
1310
  const message = typeof p.error === "string" ? p.error : "Stream error";
1093
- push({ type: "error", code, message });
1311
+ events.push({ type: "error", code, message });
1094
1312
  finish();
1095
1313
  });
1096
1314
  const onSubTask = whenMatched((params) => {
@@ -1103,13 +1321,18 @@ function createAskStream(ipc, input, opts = {}) {
1103
1321
  status: p.status,
1104
1322
  progress: p.progress
1105
1323
  } : { type: "subTaskProgress", subTaskId: p.subTaskId, status: p.status };
1106
- push(ev);
1324
+ events.push(ev);
1107
1325
  });
1108
1326
  const onHitl = whenMatched((params) => {
1109
1327
  const p = params;
1110
1328
  if (typeof p.requestId !== "string" || typeof p.prompt !== "string")
1111
1329
  return;
1112
- push({ type: "hitlBatch", requestId: p.requestId, prompt: p.prompt, details: p.details });
1330
+ events.push({
1331
+ type: "hitlBatch",
1332
+ requestId: p.requestId,
1333
+ prompt: p.prompt,
1334
+ details: p.details
1335
+ });
1113
1336
  });
1114
1337
  const register = (method, handler) => {
1115
1338
  ipc.onNotification(method, handler);
@@ -1121,7 +1344,7 @@ function createAskStream(ipc, input, opts = {}) {
1121
1344
  register("agent.subTaskProgress", onSubTask);
1122
1345
  register("agent.hitlBatch", onHitl);
1123
1346
  const onTransportClose = (err) => {
1124
- push({ type: "error", code: "transport_closed", message: err.message });
1347
+ events.push({ type: "error", code: "transport_closed", message: err.message });
1125
1348
  finish();
1126
1349
  };
1127
1350
  ipc.onClose(onTransportClose);
@@ -1142,7 +1365,7 @@ function createAskStream(ipc, input, opts = {}) {
1142
1365
  const result = await ipc.call("engine.askStream", params);
1143
1366
  const sid = result?.streamId;
1144
1367
  if (typeof sid !== "string") {
1145
- push({ type: "error", code: "no_stream_id", message: "Gateway returned no streamId" });
1368
+ events.push({ type: "error", code: "no_stream_id", message: "Gateway returned no streamId" });
1146
1369
  finish();
1147
1370
  throw new Error("no_stream_id");
1148
1371
  }
@@ -1156,7 +1379,7 @@ function createAskStream(ipc, input, opts = {}) {
1156
1379
  finish();
1157
1380
  return sid;
1158
1381
  }
1159
- if (done)
1382
+ if (events.closed)
1160
1383
  return sid;
1161
1384
  if (opts.signal !== undefined) {
1162
1385
  const signal = opts.signal;
@@ -1171,7 +1394,7 @@ function createAskStream(ipc, input, opts = {}) {
1171
1394
  return sid;
1172
1395
  })();
1173
1396
  startPromise.catch((err) => {
1174
- push({
1397
+ events.push({
1175
1398
  type: "error",
1176
1399
  code: "stream_start_failed",
1177
1400
  message: err instanceof Error ? err.message : String(err)
@@ -1192,16 +1415,7 @@ function createAskStream(ipc, input, opts = {}) {
1192
1415
  [Symbol.asyncIterator]() {
1193
1416
  return {
1194
1417
  next() {
1195
- if (queue.length > 0) {
1196
- const ev = queue.shift();
1197
- return Promise.resolve({ value: ev, done: false });
1198
- }
1199
- if (done) {
1200
- return Promise.resolve({ value: undefined, done: true });
1201
- }
1202
- return new Promise((resolve, reject) => {
1203
- waiters.push({ resolve, reject });
1204
- });
1418
+ return events.next();
1205
1419
  },
1206
1420
  return() {
1207
1421
  cancelled = true;
@@ -1217,6 +1431,78 @@ function createAskStream(ipc, input, opts = {}) {
1217
1431
  return handle;
1218
1432
  }
1219
1433
 
1434
+ // src/proving-ipc-client.ts
1435
+ var import_node_fs2 = require("node:fs");
1436
+ var import_node_path3 = require("node:path");
1437
+ var DEFAULT_PROOF_TIMEOUT_MS = 1e4;
1438
+
1439
+ class ProvingIPCClient extends IPCClient {
1440
+ proofSocketPath;
1441
+ keyPathOption;
1442
+ resolveDataDir;
1443
+ proofTimeoutMs;
1444
+ proof;
1445
+ proofGeneration = -1;
1446
+ constructor(socketPath, opts = {}) {
1447
+ const { keyPath, proofTimeoutMs, resolveDataDir, ...base } = opts;
1448
+ super(socketPath, base);
1449
+ this.proofSocketPath = socketPath;
1450
+ this.keyPathOption = keyPath;
1451
+ this.resolveDataDir = resolveDataDir ?? (() => getNimbusPaths().dataDir);
1452
+ this.proofTimeoutMs = proofTimeoutMs ?? DEFAULT_PROOF_TIMEOUT_MS;
1453
+ this.onClose(() => {
1454
+ this.proof = undefined;
1455
+ });
1456
+ }
1457
+ async call(method, params) {
1458
+ if (SECRET_IPC_METHODS.has(method) && this.transportConnected) {
1459
+ await this.ensureProven();
1460
+ }
1461
+ return super.call(method, params);
1462
+ }
1463
+ async disconnect() {
1464
+ this.proof = undefined;
1465
+ await super.disconnect();
1466
+ }
1467
+ ensureProven() {
1468
+ if (this.proof !== undefined && this.proofGeneration !== this.transportGeneration) {
1469
+ this.proof = undefined;
1470
+ }
1471
+ if (this.proof === undefined) {
1472
+ this.proofGeneration = this.transportGeneration;
1473
+ const attempt = this.runProof();
1474
+ this.proof = attempt;
1475
+ attempt.catch(() => {
1476
+ if (this.proof === attempt)
1477
+ this.proof = undefined;
1478
+ });
1479
+ }
1480
+ return this.proof;
1481
+ }
1482
+ runProof() {
1483
+ const generation = this.transportGeneration;
1484
+ return proveGateway({
1485
+ call: (method, params) => super.call(method, params),
1486
+ readKey: () => this.readKey(),
1487
+ disconnect: async () => {
1488
+ if (this.transportGeneration !== generation)
1489
+ return;
1490
+ this.proof = undefined;
1491
+ this.abortConnection(new Error("IPC connection closed: the gateway proof failed"));
1492
+ },
1493
+ isTimeout: (e) => e instanceof Error && e.message.startsWith("IPC request timed out")
1494
+ }, { timeoutMs: this.proofTimeoutMs });
1495
+ }
1496
+ readKey() {
1497
+ try {
1498
+ const path = this.keyPathOption ?? import_node_path3.join(this.resolveDataDir(), proofKeyFileName(this.proofSocketPath, process.platform));
1499
+ return parseHex32(import_node_fs2.readFileSync(path, "utf8"));
1500
+ } catch {
1501
+ return;
1502
+ }
1503
+ }
1504
+ }
1505
+
1220
1506
  // src/validate.ts
1221
1507
  class IpcResponseError extends Error {
1222
1508
  constructor(method, detail) {
@@ -1256,6 +1542,18 @@ function arr(method, v) {
1256
1542
  throw new IpcResponseError(method, "expected an array");
1257
1543
  return v;
1258
1544
  }
1545
+ function strArr(method, o, key) {
1546
+ return arr(method, o[key]).map((s) => {
1547
+ if (typeof s !== "string") {
1548
+ throw new IpcResponseError(method, `"${key}" must contain only strings`);
1549
+ }
1550
+ return s;
1551
+ });
1552
+ }
1553
+ function requireOk(method, o) {
1554
+ if (!bool(method, o, "ok"))
1555
+ throw new IpcResponseError(method, `"ok" must be true`);
1556
+ }
1259
1557
  function optStr(o, key) {
1260
1558
  const v = o[key];
1261
1559
  return typeof v === "string" ? v : undefined;
@@ -2057,15 +2355,8 @@ function validateConnectorReindex(method, v) {
2057
2355
  }
2058
2356
  function validateConnectorAuth(method, v) {
2059
2357
  const o = record(method, v);
2060
- if (!bool(method, o, "ok")) {
2061
- throw new IpcResponseError(method, `"ok" must be true`);
2062
- }
2063
- const scopesGranted = arr(method, o["scopesGranted"]).map((s) => {
2064
- if (typeof s !== "string") {
2065
- throw new IpcResponseError(method, `"scopesGranted" must contain only strings`);
2066
- }
2067
- return s;
2068
- });
2358
+ requireOk(method, o);
2359
+ const scopesGranted = strArr(method, o, "scopesGranted");
2069
2360
  return { ok: true, serviceId: str(method, o, "serviceId"), scopesGranted };
2070
2361
  }
2071
2362
  function validateGatedOrElse(method, v, validateSuccess) {
@@ -2077,23 +2368,14 @@ function validateGatedOrElse(method, v, validateSuccess) {
2077
2368
  }
2078
2369
  function validateConnectorAddMcp(method, v) {
2079
2370
  return validateGatedOrElse(method, v, (m, o) => {
2080
- if (!bool(m, o, "ok")) {
2081
- throw new IpcResponseError(m, `"ok" must be true`);
2082
- }
2371
+ requireOk(m, o);
2083
2372
  return { ok: true, serviceId: str(m, o, "serviceId") };
2084
2373
  });
2085
2374
  }
2086
2375
  function validateConnectorRemove(method, v) {
2087
2376
  return validateGatedOrElse(method, v, (m, o) => {
2088
- if (!bool(m, o, "ok")) {
2089
- throw new IpcResponseError(m, `"ok" must be true`);
2090
- }
2091
- const vaultKeysRemoved = arr(m, o["vaultKeysRemoved"]).map((k) => {
2092
- if (typeof k !== "string") {
2093
- throw new IpcResponseError(m, `"vaultKeysRemoved" must contain only strings`);
2094
- }
2095
- return k;
2096
- });
2377
+ requireOk(m, o);
2378
+ const vaultKeysRemoved = strArr(m, o, "vaultKeysRemoved");
2097
2379
  return { ok: true, itemsDeleted: num(m, o, "itemsDeleted"), vaultKeysRemoved };
2098
2380
  });
2099
2381
  }
@@ -2211,34 +2493,28 @@ function validateWhyPeek(method, v) {
2211
2493
  }
2212
2494
 
2213
2495
  // src/workflow-stream.ts
2214
- var import_node_crypto2 = require("node:crypto");
2496
+ var import_node_crypto3 = require("node:crypto");
2497
+ function workflowRunWireParams(params) {
2498
+ return {
2499
+ name: params.name,
2500
+ triggeredBy: params.triggeredBy,
2501
+ dryRun: params.dryRun,
2502
+ stream: params.stream,
2503
+ sessionId: params.sessionId,
2504
+ agent: params.agent,
2505
+ paramsOverride: params.paramsOverride,
2506
+ streamId: params.streamId
2507
+ };
2508
+ }
2215
2509
  function createWorkflowRunStream(ipc, params, validate) {
2216
- const queue = [];
2217
- const waiters = [];
2218
- let done = false;
2510
+ const events = createEventQueue();
2219
2511
  let detach;
2220
- const streamId = params.streamId ?? import_node_crypto2.randomUUID();
2221
- const push = (ev) => {
2222
- if (done)
2223
- return;
2224
- const w = waiters.shift();
2225
- if (w !== undefined) {
2226
- w.resolve({ value: ev, done: false });
2227
- return;
2228
- }
2229
- queue.push(ev);
2230
- };
2512
+ const streamId = params.streamId ?? import_node_crypto3.randomUUID();
2231
2513
  const finish = () => {
2232
- if (done)
2233
- return;
2234
- done = true;
2235
- detach?.();
2236
- detach = undefined;
2237
- let w = waiters.shift();
2238
- while (w !== undefined) {
2239
- w.resolve({ value: undefined, done: true });
2240
- w = waiters.shift();
2241
- }
2514
+ events.close(() => {
2515
+ detach?.();
2516
+ detach = undefined;
2517
+ });
2242
2518
  };
2243
2519
  const onChunk = (p) => {
2244
2520
  if (typeof p !== "object" || p === null)
@@ -2248,20 +2524,15 @@ function createWorkflowRunStream(ipc, params, validate) {
2248
2524
  return;
2249
2525
  const text = p.text;
2250
2526
  if (typeof text === "string")
2251
- push({ type: "chunk", text });
2527
+ events.push({ type: "chunk", text });
2252
2528
  };
2253
2529
  ipc.onNotification("agent.chunk", onChunk);
2254
2530
  detach = () => ipc.offNotification("agent.chunk", onChunk);
2255
2531
  const result = (async () => {
2256
2532
  try {
2257
2533
  const raw = await ipc.call("workflow.run", {
2258
- name: params.name,
2259
- triggeredBy: params.triggeredBy,
2260
- dryRun: params.dryRun,
2534
+ ...workflowRunWireParams(params),
2261
2535
  stream: true,
2262
- sessionId: params.sessionId,
2263
- agent: params.agent,
2264
- paramsOverride: params.paramsOverride,
2265
2536
  streamId
2266
2537
  });
2267
2538
  return validate("workflow.run", raw);
@@ -2271,10 +2542,10 @@ function createWorkflowRunStream(ipc, params, validate) {
2271
2542
  }
2272
2543
  })();
2273
2544
  result.then((value) => {
2274
- push({ type: "done", result: value });
2545
+ events.push({ type: "done", result: value });
2275
2546
  finish();
2276
2547
  }, (err) => {
2277
- push({ type: "error", message: err instanceof Error ? err.message : String(err) });
2548
+ events.push({ type: "error", message: err instanceof Error ? err.message : String(err) });
2278
2549
  finish();
2279
2550
  });
2280
2551
  return {
@@ -2292,15 +2563,7 @@ function createWorkflowRunStream(ipc, params, validate) {
2292
2563
  [Symbol.asyncIterator]() {
2293
2564
  return {
2294
2565
  next() {
2295
- const ev = queue.shift();
2296
- if (ev !== undefined)
2297
- return Promise.resolve({ value: ev, done: false });
2298
- if (done) {
2299
- return Promise.resolve({ value: undefined, done: true });
2300
- }
2301
- return new Promise((resolve, reject) => {
2302
- waiters.push({ resolve, reject });
2303
- });
2566
+ return events.next();
2304
2567
  },
2305
2568
  return() {
2306
2569
  finish();
@@ -2312,6 +2575,16 @@ function createWorkflowRunStream(ipc, params, validate) {
2312
2575
  }
2313
2576
 
2314
2577
  // src/nimbus-client.ts
2578
+ function rankedSearchWireParams(params) {
2579
+ return {
2580
+ name: params.name,
2581
+ service: params.service,
2582
+ itemType: params.itemType,
2583
+ limit: params.limit,
2584
+ semantic: params.semantic,
2585
+ contextChunks: params.contextChunks
2586
+ };
2587
+ }
2315
2588
  var EGRESS_COVERAGE_CLASSES = [
2316
2589
  "http",
2317
2590
  "mcp",
@@ -2331,6 +2604,7 @@ var NO_EGRESS_COVERAGE = Object.freeze({
2331
2604
  sync: "none",
2332
2605
  task: "none"
2333
2606
  });
2607
+ var CONSENT_ANSWER_SOURCES = ["human", "auto", "script"];
2334
2608
 
2335
2609
  class NimbusClient {
2336
2610
  ipc;
@@ -2338,8 +2612,9 @@ class NimbusClient {
2338
2612
  this.ipc = ipc;
2339
2613
  }
2340
2614
  static async open(opts) {
2341
- const ipc = new IPCClient(opts.socketPath, {
2342
- ...opts.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: opts.requestTimeoutMs }
2615
+ const ipc = new ProvingIPCClient(opts.socketPath, {
2616
+ ...opts.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: opts.requestTimeoutMs },
2617
+ ...opts.keyPath === undefined ? {} : { keyPath: opts.keyPath }
2343
2618
  });
2344
2619
  await ipc.connect();
2345
2620
  return new NimbusClient(ipc);
@@ -2357,24 +2632,28 @@ class NimbusClient {
2357
2632
  return createAskStream(this.ipc, input, opts);
2358
2633
  }
2359
2634
  subscribeHitl(handler) {
2360
- const onBatch = (params) => {
2635
+ const onRequest = (params) => {
2361
2636
  if (typeof params !== "object" || params === null)
2362
2637
  return;
2363
2638
  const p = params;
2364
2639
  if (typeof p["requestId"] !== "string" || typeof p["prompt"] !== "string")
2365
2640
  return;
2366
- const req = typeof p["streamId"] === "string" ? {
2641
+ const req = {
2367
2642
  requestId: p["requestId"],
2368
2643
  prompt: p["prompt"],
2369
2644
  details: p["details"],
2370
- streamId: p["streamId"]
2371
- } : { requestId: p["requestId"], prompt: p["prompt"], details: p["details"] };
2645
+ ...typeof p["streamId"] === "string" ? { streamId: p["streamId"] } : {},
2646
+ ...typeof p["actionType"] === "string" ? { actionType: p["actionType"] } : {},
2647
+ ...typeof p["confirmText"] === "string" ? { confirmText: p["confirmText"] } : {}
2648
+ };
2372
2649
  handler(req);
2373
2650
  };
2374
- this.ipc.onNotification("agent.hitlBatch", onBatch);
2651
+ this.ipc.onNotification("agent.hitlBatch", onRequest);
2652
+ this.ipc.onNotification("consent.request", onRequest);
2375
2653
  return {
2376
2654
  dispose: () => {
2377
- this.ipc.offNotification("agent.hitlBatch", onBatch);
2655
+ this.ipc.offNotification("agent.hitlBatch", onRequest);
2656
+ this.ipc.offNotification("consent.request", onRequest);
2378
2657
  }
2379
2658
  };
2380
2659
  }
@@ -2552,24 +2831,12 @@ class NimbusClient {
2552
2831
  return validateQueryItems("index.queryItems", raw);
2553
2832
  }
2554
2833
  async searchRanked(params = {}) {
2555
- const raw = await this.ipc.call("index.searchRanked", {
2556
- name: params.name,
2557
- service: params.service,
2558
- itemType: params.itemType,
2559
- limit: params.limit,
2560
- semantic: params.semantic,
2561
- contextChunks: params.contextChunks
2562
- });
2834
+ const raw = await this.ipc.call("index.searchRanked", rankedSearchWireParams(params));
2563
2835
  return validateRankedItems("index.searchRanked", raw);
2564
2836
  }
2565
2837
  async searchRankedWithRetrieval(params = {}) {
2566
2838
  const raw = await this.ipc.call("index.searchRanked", {
2567
- name: params.name,
2568
- service: params.service,
2569
- itemType: params.itemType,
2570
- limit: params.limit,
2571
- semantic: params.semantic,
2572
- contextChunks: params.contextChunks,
2839
+ ...rankedSearchWireParams(params),
2573
2840
  envelope: true
2574
2841
  });
2575
2842
  return validateRankedSearchWithRetrieval("index.searchRanked", raw);
@@ -2624,9 +2891,15 @@ class NimbusClient {
2624
2891
  return validateEgressProveWindow("egress.proveWindow", raw);
2625
2892
  }
2626
2893
  async consentRespond(params) {
2894
+ const { typed, answerSource } = params;
2895
+ if (answerSource !== undefined && !CONSENT_ANSWER_SOURCES.includes(answerSource)) {
2896
+ throw new TypeError(`consentRespond: answerSource must be one of ${CONSENT_ANSWER_SOURCES.join(", ")}`);
2897
+ }
2627
2898
  const raw = await this.ipc.call("consent.respond", {
2628
2899
  requestId: params.requestId,
2629
- approved: params.approved
2900
+ approved: params.approved,
2901
+ ...typed === undefined ? {} : { typed },
2902
+ ...answerSource === undefined ? {} : { answerSource }
2630
2903
  });
2631
2904
  return validateOk("consent.respond", raw);
2632
2905
  }
@@ -2743,16 +3016,7 @@ class NimbusClient {
2743
3016
  return validateWorkflowListRuns("workflow.listRuns", raw);
2744
3017
  }
2745
3018
  async workflowRun(params) {
2746
- const raw = await this.ipc.call("workflow.run", {
2747
- name: params.name,
2748
- triggeredBy: params.triggeredBy,
2749
- dryRun: params.dryRun,
2750
- stream: params.stream,
2751
- sessionId: params.sessionId,
2752
- agent: params.agent,
2753
- paramsOverride: params.paramsOverride,
2754
- streamId: params.streamId
2755
- });
3019
+ const raw = await this.ipc.call("workflow.run", workflowRunWireParams(params));
2756
3020
  return validateWorkflowRun("workflow.run", raw);
2757
3021
  }
2758
3022
  workflowRunStream(params) {
@@ -2773,37 +3037,41 @@ class MockClient {
2773
3037
  constructor(fixtures = {}) {
2774
3038
  this.fixtures = fixtures;
2775
3039
  }
2776
- async agentInvoke(_input, _options) {
2777
- return { reply: this.fixtures.reply ?? "[MockClient] agent.invoke" };
3040
+ agentInvoke(_input, _options) {
3041
+ return Promise.resolve({ reply: this.fixtures.reply ?? "[MockClient] agent.invoke" });
2778
3042
  }
2779
3043
  askStream(_input, _opts) {
2780
3044
  const tokens = this.fixtures.streamTokens ?? ["mock", " token"];
2781
3045
  const reply = this.fixtures.reply ?? tokens.join("");
2782
3046
  let i = 0;
2783
3047
  let cancelled = false;
3048
+ const nextResult = () => {
3049
+ if (cancelled)
3050
+ return { value: undefined, done: true };
3051
+ if (i < tokens.length) {
3052
+ const text = tokens[i];
3053
+ i += 1;
3054
+ return { value: { type: "token", text }, done: false };
3055
+ }
3056
+ if (i === tokens.length) {
3057
+ i += 1;
3058
+ return {
3059
+ value: { type: "done", reply, sessionId: "mock-session" },
3060
+ done: false
3061
+ };
3062
+ }
3063
+ return { value: undefined, done: true };
3064
+ };
2784
3065
  const handle = {
2785
3066
  streamId: "mock-stream",
2786
- async cancel() {
3067
+ cancel() {
2787
3068
  cancelled = true;
3069
+ return Promise.resolve();
2788
3070
  },
2789
3071
  [Symbol.asyncIterator]() {
2790
3072
  return {
2791
- async next() {
2792
- if (cancelled)
2793
- return { value: undefined, done: true };
2794
- if (i < tokens.length) {
2795
- const text = tokens[i];
2796
- i += 1;
2797
- return { value: { type: "token", text }, done: false };
2798
- }
2799
- if (i === tokens.length) {
2800
- i += 1;
2801
- return {
2802
- value: { type: "done", reply, sessionId: "mock-session" },
2803
- done: false
2804
- };
2805
- }
2806
- return { value: undefined, done: true };
3073
+ next() {
3074
+ return Promise.resolve(nextResult());
2807
3075
  }
2808
3076
  };
2809
3077
  }
@@ -2857,71 +3125,71 @@ class MockClient {
2857
3125
  async agentsWhy(_p) {
2858
3126
  return this.brief("why");
2859
3127
  }
2860
- async agentsWhyPeek(_p) {
3128
+ agentsWhyPeek(_p) {
2861
3129
  if (this.fixtures.whyPeek === undefined) {
2862
- throw new Error("MockClient: no whyPeek fixture configured");
3130
+ return Promise.reject(new Error("MockClient: no whyPeek fixture configured"));
2863
3131
  }
2864
- return this.fixtures.whyPeek;
3132
+ return Promise.resolve(this.fixtures.whyPeek);
2865
3133
  }
2866
- async getSessionTranscript(_params) {
2867
- return { sessionId: "mock-session", turns: [], hasMore: false };
3134
+ getSessionTranscript(_params) {
3135
+ return Promise.resolve({ sessionId: "mock-session", turns: [], hasMore: false });
2868
3136
  }
2869
- async cancelStream() {
2870
- return { ok: true };
3137
+ cancelStream() {
3138
+ return Promise.resolve({ ok: true });
2871
3139
  }
2872
- async sessionAppend(_params) {
2873
- return { ok: true };
3140
+ sessionAppend(_params) {
3141
+ return Promise.resolve({ ok: true });
2874
3142
  }
2875
- async sessionRecall(_params) {
2876
- return this.fixtures.sessionRecall ?? { chunks: [] };
3143
+ sessionRecall(_params) {
3144
+ return Promise.resolve(this.fixtures.sessionRecall ?? { chunks: [] });
2877
3145
  }
2878
- async sessionList() {
2879
- return this.fixtures.sessionList ?? { sessions: [] };
3146
+ sessionList() {
3147
+ return Promise.resolve(this.fixtures.sessionList ?? { sessions: [] });
2880
3148
  }
2881
- async sessionClear(_params) {
2882
- return { ok: true, cleared: "all" };
3149
+ sessionClear(_params) {
3150
+ return Promise.resolve({ ok: true, cleared: "all" });
2883
3151
  }
2884
- async queryItems(_params) {
3152
+ queryItems(_params) {
2885
3153
  const items = this.fixtures.items ?? [];
2886
- return { items, meta: { limit: items.length, total: items.length } };
3154
+ return Promise.resolve({ items, meta: { limit: items.length, total: items.length } });
2887
3155
  }
2888
- async searchRanked(_params) {
2889
- return this.fixtures.rankedItems ?? [];
3156
+ searchRanked(_params) {
3157
+ return Promise.resolve(this.fixtures.rankedItems ?? []);
2890
3158
  }
2891
- async searchRankedWithRetrieval(_params) {
3159
+ searchRankedWithRetrieval(_params) {
2892
3160
  const retrieval = this.fixtures.rankedRetrieval === undefined ? { vectorRanked: true, reason: null, partial: null, backfill: null } : this.fixtures.rankedRetrieval;
2893
- return {
3161
+ return Promise.resolve({
2894
3162
  items: this.fixtures.rankedItems ?? [],
2895
3163
  retrieval,
2896
3164
  notes: this.fixtures.rankedNotes ?? []
2897
- };
3165
+ });
2898
3166
  }
2899
- async querySql(_sql) {
2900
- return { rows: this.fixtures.sqlRows ?? [] };
3167
+ querySql(_sql) {
3168
+ return Promise.resolve({ rows: this.fixtures.sqlRows ?? [] });
2901
3169
  }
2902
- async auditList(_limit) {
2903
- return [];
3170
+ auditList(_limit) {
3171
+ return Promise.resolve([]);
2904
3172
  }
2905
- async auditVerify(_params) {
2906
- return this.fixtures.auditVerify ?? { ok: true, verifiedRows: 0, lastVerifiedId: 0 };
3173
+ auditVerify(_params) {
3174
+ return Promise.resolve(this.fixtures.auditVerify ?? { ok: true, verifiedRows: 0, lastVerifiedId: 0 });
2907
3175
  }
2908
- async auditGetSummary() {
2909
- return this.fixtures.auditSummary ?? { byOutcome: {}, byService: {}, total: 0 };
3176
+ auditGetSummary() {
3177
+ return Promise.resolve(this.fixtures.auditSummary ?? { byOutcome: {}, byService: {}, total: 0 });
2910
3178
  }
2911
- async auditToolCalls(_params) {
2912
- return this.fixtures.auditToolCalls ?? { toolCalls: [], hasMore: false, nextCursor: null };
3179
+ auditToolCalls(_params) {
3180
+ return Promise.resolve(this.fixtures.auditToolCalls ?? { toolCalls: [], hasMore: false, nextCursor: null });
2913
3181
  }
2914
- async egressHead() {
2915
- return this.fixtures.egressHead ?? { head: "", count: 0 };
3182
+ egressHead() {
3183
+ return Promise.resolve(this.fixtures.egressHead ?? { head: "", count: 0 });
2916
3184
  }
2917
- async egressList(_params) {
2918
- return { rows: this.fixtures.egressRows ?? [] };
3185
+ egressList(_params) {
3186
+ return Promise.resolve({ rows: this.fixtures.egressRows ?? [] });
2919
3187
  }
2920
- async egressVerify() {
2921
- return this.fixtures.egressVerify ?? { ok: true, verifiedRows: 0 };
3188
+ egressVerify() {
3189
+ return Promise.resolve(this.fixtures.egressVerify ?? { ok: true, verifiedRows: 0 });
2922
3190
  }
2923
- async egressProveWindow(_params) {
2924
- return this.fixtures.egressProveWindow ?? {
3191
+ egressProveWindow(_params) {
3192
+ return Promise.resolve(this.fixtures.egressProveWindow ?? {
2925
3193
  rows: [],
2926
3194
  completeness: {
2927
3195
  coverage: NO_EGRESS_COVERAGE,
@@ -2929,20 +3197,20 @@ class MockClient {
2929
3197
  indeterminate: true
2930
3198
  },
2931
3199
  verify: { ok: true, verifiedRows: 0 }
2932
- };
3200
+ });
2933
3201
  }
2934
- async consentRespond(_params) {
2935
- return { ok: true };
3202
+ consentRespond(_params) {
3203
+ return Promise.resolve({ ok: true });
2936
3204
  }
2937
- async gatewayPing(_params) {
2938
- return this.fixtures.gatewayPing ?? {
3205
+ gatewayPing(_params) {
3206
+ return Promise.resolve(this.fixtures.gatewayPing ?? {
2939
3207
  version: "mock",
2940
3208
  uptime: 0,
2941
3209
  agentLimits: { maxAgentDepth: 5, maxToolCallsPerSession: 50 }
2942
- };
3210
+ });
2943
3211
  }
2944
- async diagGetVersion() {
2945
- return this.fixtures.diagVersion ?? { version: "mock", commit: null, buildId: null, uptimeMs: 0 };
3212
+ diagGetVersion() {
3213
+ return Promise.resolve(this.fixtures.diagVersion ?? { version: "mock", commit: null, buildId: null, uptimeMs: 0 });
2946
3214
  }
2947
3215
  defaultIndexMetrics() {
2948
3216
  return {
@@ -2956,11 +3224,11 @@ class MockClient {
2956
3224
  queryLatencyP99Ms: 0
2957
3225
  };
2958
3226
  }
2959
- async indexMetrics() {
2960
- return this.fixtures.indexMetrics ?? this.defaultIndexMetrics();
3227
+ indexMetrics() {
3228
+ return Promise.resolve(this.fixtures.indexMetrics ?? this.defaultIndexMetrics());
2961
3229
  }
2962
- async diagSnapshot() {
2963
- return this.fixtures.diagSnapshot ?? {
3230
+ diagSnapshot() {
3231
+ return Promise.resolve(this.fixtures.diagSnapshot ?? {
2964
3232
  gateway: { version: "mock", uptimeMs: 0 },
2965
3233
  connectorHealth: [],
2966
3234
  index: this.defaultIndexMetrics(),
@@ -2973,10 +3241,10 @@ class MockClient {
2973
3241
  linux_helper: null,
2974
3242
  stale_rules_count: 0
2975
3243
  }
2976
- };
3244
+ });
2977
3245
  }
2978
- async adminStatus() {
2979
- return this.fixtures.adminStatus ?? {
3246
+ adminStatus() {
3247
+ return Promise.resolve(this.fixtures.adminStatus ?? {
2980
3248
  policy: { signatureValid: true, pendingRestart: false, source: "none" },
2981
3249
  peers: [],
2982
3250
  connectors: [],
@@ -2985,10 +3253,10 @@ class MockClient {
2985
3253
  hitl: { pendingApprovals: 0, pendingQuorum: 0 },
2986
3254
  identity: { operatorValid: true },
2987
3255
  syncFreshnessMs: 0
2988
- };
3256
+ });
2989
3257
  }
2990
- async metricsDora(_params) {
2991
- return this.fixtures.metricsDora ?? {
3258
+ metricsDora(_params) {
3259
+ return Promise.resolve(this.fixtures.metricsDora ?? {
2992
3260
  service: "mock",
2993
3261
  since_ms: 0,
2994
3262
  computed_at: new Date(0).toISOString(),
@@ -3008,10 +3276,10 @@ class MockClient {
3008
3276
  change_failure_rate: { value: null, unit: "ratio", sample: 0, gap: "no_repos" },
3009
3277
  mttr: { value: null, unit: "seconds_median", sample: 0, gap: "no_repos" }
3010
3278
  }
3011
- };
3279
+ });
3012
3280
  }
3013
- async deployPreflight(_params) {
3014
- return this.fixtures.deployPreflight ?? {
3281
+ deployPreflight(_params) {
3282
+ return Promise.resolve(this.fixtures.deployPreflight ?? {
3015
3283
  service: "mock",
3016
3284
  target_ref: "main",
3017
3285
  computed_at: new Date(0).toISOString(),
@@ -3021,10 +3289,10 @@ class MockClient {
3021
3289
  failing_ci_runs: { count: 0, findings: [], gap: "no_repos" },
3022
3290
  merge_conflicts: { count: 0, findings: [], gap: "no_repos" }
3023
3291
  }
3024
- };
3292
+ });
3025
3293
  }
3026
- async connectorListStatus(_params) {
3027
- return this.fixtures.connectorSyncStatuses ?? [];
3294
+ connectorListStatus(_params) {
3295
+ return Promise.resolve(this.fixtures.connectorSyncStatuses ?? []);
3028
3296
  }
3029
3297
  defaultConnectorStatus(serviceId) {
3030
3298
  return {
@@ -3040,100 +3308,101 @@ class MockClient {
3040
3308
  enabled: true
3041
3309
  };
3042
3310
  }
3043
- async connectorStatus(params) {
3044
- return this.fixtures.connectorStatus ?? this.defaultConnectorStatus(params.serviceId);
3311
+ connectorStatus(params) {
3312
+ return Promise.resolve(this.fixtures.connectorStatus ?? this.defaultConnectorStatus(params.serviceId));
3045
3313
  }
3046
- async connectorHealthHistory(_params) {
3047
- return this.fixtures.connectorHealthHistory ?? [];
3314
+ connectorHealthHistory(_params) {
3315
+ return Promise.resolve(this.fixtures.connectorHealthHistory ?? []);
3048
3316
  }
3049
- async connectorPause(_params) {
3050
- return { ok: true };
3317
+ connectorPause(_params) {
3318
+ return Promise.resolve({ ok: true });
3051
3319
  }
3052
- async connectorResume(_params) {
3053
- return { ok: true };
3320
+ connectorResume(_params) {
3321
+ return Promise.resolve({ ok: true });
3054
3322
  }
3055
- async connectorSetInterval(_params) {
3056
- return { ok: true };
3323
+ connectorSetInterval(_params) {
3324
+ return Promise.resolve({ ok: true });
3057
3325
  }
3058
- async connectorSetConfig(params) {
3059
- return this.fixtures.connectorSetConfig ?? {
3326
+ connectorSetConfig(params) {
3327
+ return Promise.resolve(this.fixtures.connectorSetConfig ?? {
3060
3328
  service: params.serviceId,
3061
3329
  intervalMs: params.intervalMs ?? null,
3062
3330
  depth: params.depth ?? null,
3063
3331
  enabled: params.enabled ?? null
3064
- };
3332
+ });
3065
3333
  }
3066
- async connectorSync(_params) {
3067
- return { ok: true };
3334
+ connectorSync(_params) {
3335
+ return Promise.resolve({ ok: true });
3068
3336
  }
3069
- async connectorAuth(params) {
3070
- return this.fixtures.connectorAuth ?? { ok: true, serviceId: params.serviceId, scopesGranted: [] };
3337
+ connectorAuth(params) {
3338
+ return Promise.resolve(this.fixtures.connectorAuth ?? { ok: true, serviceId: params.serviceId, scopesGranted: [] });
3071
3339
  }
3072
- async connectorAddMcp(params) {
3073
- return this.fixtures.connectorAddMcp ?? { ok: true, serviceId: params.serviceId };
3340
+ connectorAddMcp(params) {
3341
+ return Promise.resolve(this.fixtures.connectorAddMcp ?? { ok: true, serviceId: params.serviceId });
3074
3342
  }
3075
- async connectorRemove(_params) {
3076
- return this.fixtures.connectorRemove ?? { ok: true, itemsDeleted: 0, vaultKeysRemoved: [] };
3343
+ connectorRemove(_params) {
3344
+ return Promise.resolve(this.fixtures.connectorRemove ?? { ok: true, itemsDeleted: 0, vaultKeysRemoved: [] });
3077
3345
  }
3078
- async connectorReindex(params) {
3079
- return this.fixtures.connectorReindex ?? {
3346
+ connectorReindex(params) {
3347
+ return Promise.resolve(this.fixtures.connectorReindex ?? {
3080
3348
  itemsAffected: 0,
3081
3349
  depth: params.depth ?? "metadata_only",
3082
3350
  mode: "shallow"
3083
- };
3351
+ });
3084
3352
  }
3085
- async workflowList() {
3086
- return this.fixtures.workflowList ?? { workflows: [] };
3353
+ workflowList() {
3354
+ return Promise.resolve(this.fixtures.workflowList ?? { workflows: [] });
3087
3355
  }
3088
- async workflowSave(_params) {
3089
- return { id: "mock-workflow" };
3356
+ workflowSave(_params) {
3357
+ return Promise.resolve({ id: "mock-workflow" });
3090
3358
  }
3091
- async workflowDelete(_params) {
3092
- return { ok: true };
3359
+ workflowDelete(_params) {
3360
+ return Promise.resolve({ ok: true });
3093
3361
  }
3094
- async workflowListRuns(_params) {
3095
- return this.fixtures.workflowListRuns ?? { runs: [] };
3362
+ workflowListRuns(_params) {
3363
+ return Promise.resolve(this.fixtures.workflowListRuns ?? { runs: [] });
3096
3364
  }
3097
- async workflowRun(params) {
3098
- return this.fixtures.workflowRun ?? {
3365
+ defaultWorkflowRun(params) {
3366
+ return {
3099
3367
  runId: "mock-run",
3100
3368
  status: params.dryRun === true ? "preview" : "done",
3101
3369
  dryRun: params.dryRun ?? false,
3102
3370
  stepResults: []
3103
3371
  };
3104
3372
  }
3105
- async workflowCancel(_params) {
3106
- return this.fixtures.workflowCancel ?? { cancelled: true };
3373
+ workflowRun(params) {
3374
+ return Promise.resolve(this.fixtures.workflowRun ?? this.defaultWorkflowRun(params));
3375
+ }
3376
+ workflowCancel(_params) {
3377
+ return Promise.resolve(this.fixtures.workflowCancel ?? { cancelled: true });
3107
3378
  }
3108
3379
  workflowRunStream(params) {
3109
3380
  const chunks = this.fixtures.workflowRunChunks ?? ["mock ", "workflow"];
3110
- const value = this.fixtures.workflowRun ?? {
3111
- runId: "mock-run",
3112
- status: params.dryRun === true ? "preview" : "done",
3113
- dryRun: params.dryRun ?? false,
3114
- stepResults: []
3115
- };
3381
+ const value = this.fixtures.workflowRun ?? this.defaultWorkflowRun(params);
3116
3382
  const cancelResult = this.fixtures.workflowCancel ?? { cancelled: true };
3117
3383
  let i = 0;
3384
+ const nextResult = () => {
3385
+ if (i < chunks.length) {
3386
+ const text = chunks[i];
3387
+ i += 1;
3388
+ return { value: { type: "chunk", text }, done: false };
3389
+ }
3390
+ if (i === chunks.length) {
3391
+ i += 1;
3392
+ return { value: { type: "done", result: value }, done: false };
3393
+ }
3394
+ return { value: undefined, done: true };
3395
+ };
3118
3396
  return {
3119
3397
  result: Promise.resolve(value),
3120
3398
  streamId: params.streamId ?? "mock-stream",
3121
- async cancel() {
3122
- return cancelResult;
3399
+ cancel() {
3400
+ return Promise.resolve(cancelResult);
3123
3401
  },
3124
3402
  [Symbol.asyncIterator]() {
3125
3403
  return {
3126
- async next() {
3127
- if (i < chunks.length) {
3128
- const text = chunks[i];
3129
- i += 1;
3130
- return { value: { type: "chunk", text }, done: false };
3131
- }
3132
- if (i === chunks.length) {
3133
- i += 1;
3134
- return { value: { type: "done", result: value }, done: false };
3135
- }
3136
- return { value: undefined, done: true };
3404
+ next() {
3405
+ return Promise.resolve(nextResult());
3137
3406
  }
3138
3407
  };
3139
3408
  }