@muhaven/mcp 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unlink, readFile, mkdir, chmod, writeFile, stat } from 'fs/promises';
1
+ import { unlink, readFile, mkdir, chmod, writeFile, rename, readdir, stat } from 'fs/promises';
2
2
  import 'fs';
3
3
  import { join, dirname } from 'path';
4
4
  import { fileURLToPath } from 'url';
@@ -6,9 +6,13 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
7
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
8
8
  import { z, ZodError } from 'zod';
9
+ import { zodToJsonSchema } from 'zod-to-json-schema';
9
10
  import { platform, homedir } from 'os';
10
11
  import { connect, createServer } from 'net';
11
- import { createHash } from 'crypto';
12
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
13
+ import { parseAbi, toFunctionSelector, encodeFunctionData, encodePacked, pad, concatHex, decodeAbiParameters } from 'viem';
14
+ import { createHash, randomBytes } from 'crypto';
15
+ import { getUserOperationHash } from 'viem/account-abstraction';
12
16
  import { privateKeyToAccount } from 'viem/accounts';
13
17
 
14
18
  // src/server.ts
@@ -18,6 +22,10 @@ var DEFAULT_REQUEST_TIMEOUT_MS = 15e3;
18
22
  var DEFAULT_BROKER_TIMEOUT_MS = 5e3;
19
23
  var DEFAULT_BROKER_MAX_BYTES = 64 * 1024;
20
24
  var DEFAULT_JWT_CACHE_TTL_SEC = 30;
25
+ var DEFAULT_BUNDLER_TIMEOUT_MS = 2e4;
26
+ var DEFAULT_CHAIN_ID = 421614;
27
+ var DEFAULT_ENTRY_POINT_ADDRESS = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
28
+ var ADDRESS_HEX_RE = /^0x[0-9a-fA-F]{40}$/;
21
29
  function defaultBrokerEndpoint() {
22
30
  if (platform() === "win32") {
23
31
  const user = process.env.USERNAME ?? "default";
@@ -93,6 +101,35 @@ function loadMcpConfig(env = process.env) {
93
101
  const requestTimeoutMs = readEnvInt("MUHAVEN_REQUEST_TIMEOUT_MS", DEFAULT_REQUEST_TIMEOUT_MS, env);
94
102
  const brokerTimeoutMs = readEnvInt("MUHAVEN_BROKER_TIMEOUT_MS", DEFAULT_BROKER_TIMEOUT_MS, env);
95
103
  const jwtCacheTtlSec = readEnvInt("MUHAVEN_JWT_CACHE_TTL_SEC", DEFAULT_JWT_CACHE_TTL_SEC, env);
104
+ const bundlerUrlRaw = readEnv("MUHAVEN_BUNDLER_URL", env);
105
+ let bundlerUrl;
106
+ if (bundlerUrlRaw !== void 0) {
107
+ const validationErr = validatePublicUrlEnv("MUHAVEN_BUNDLER_URL", bundlerUrlRaw);
108
+ if (validationErr) throw new Error(validationErr);
109
+ bundlerUrl = trimTrailingSlash(bundlerUrlRaw);
110
+ }
111
+ const bundlerTimeoutMs = readEnvInt("MUHAVEN_BUNDLER_TIMEOUT_MS", DEFAULT_BUNDLER_TIMEOUT_MS, env);
112
+ const chainId = readEnvInt("MUHAVEN_CHAIN_ID", DEFAULT_CHAIN_ID, env);
113
+ const subscriptionAddressRaw = readEnv("MUHAVEN_SUBSCRIPTION_ADDRESS", env);
114
+ let subscriptionAddress;
115
+ if (subscriptionAddressRaw !== void 0) {
116
+ if (!ADDRESS_HEX_RE.test(subscriptionAddressRaw)) {
117
+ throw new Error(
118
+ `MUHAVEN_SUBSCRIPTION_ADDRESS must be a 0x-prefixed 20-byte hex string (got ${JSON.stringify(subscriptionAddressRaw)})`
119
+ );
120
+ }
121
+ subscriptionAddress = subscriptionAddressRaw.toLowerCase();
122
+ }
123
+ const entryPointAddressRaw = readEnv("MUHAVEN_ENTRY_POINT", env);
124
+ let entryPointAddress = DEFAULT_ENTRY_POINT_ADDRESS;
125
+ if (entryPointAddressRaw !== void 0) {
126
+ if (!ADDRESS_HEX_RE.test(entryPointAddressRaw)) {
127
+ throw new Error(
128
+ `MUHAVEN_ENTRY_POINT must be a 0x-prefixed 20-byte hex string (got ${JSON.stringify(entryPointAddressRaw)})`
129
+ );
130
+ }
131
+ entryPointAddress = entryPointAddressRaw.toLowerCase();
132
+ }
96
133
  return {
97
134
  backendBaseUrl,
98
135
  dashboardBaseUrl,
@@ -101,7 +138,12 @@ function loadMcpConfig(env = process.env) {
101
138
  requestTimeoutMs,
102
139
  brokerTimeoutMs,
103
140
  allowedBackendHosts: deriveAllowedHosts(backendBaseUrl),
104
- jwtCacheTtlSec
141
+ jwtCacheTtlSec,
142
+ bundlerUrl,
143
+ bundlerTimeoutMs,
144
+ chainId,
145
+ subscriptionAddress,
146
+ entryPointAddress
105
147
  };
106
148
  }
107
149
  var PRIVKEY_HEX_RE = /^0x[0-9a-fA-F]{64}$/;
@@ -136,16 +178,366 @@ function loadBrokerConfig(env = process.env) {
136
178
  dashboardBaseUrl
137
179
  };
138
180
  }
181
+
182
+ // src/broker/protocol.ts
183
+ var BROKER_PROTOCOL_VERSION = "0.4.0";
184
+ var HASH_HEX_RE = /^0x[0-9a-fA-F]{64}$/;
185
+ var ADDRESS_HEX_RE2 = /^0x[0-9a-fA-F]{40}$/;
186
+ var SELECTOR_HEX_RE = /^0x[0-9a-fA-F]{8}$/;
187
+ var HEX_PREFIXED_RE = /^0x[0-9a-fA-F]*$/;
188
+ var JWT_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
189
+ var SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
190
+ var UINT256_DEC_RE = /^(0|[1-9][0-9]{0,77})$/;
191
+ var MAX_CALLDATA_HEX_LEN = 2e5;
192
+ function isHashHex(value) {
193
+ return typeof value === "string" && HASH_HEX_RE.test(value);
194
+ }
195
+ function isAddressHex(value) {
196
+ return typeof value === "string" && ADDRESS_HEX_RE2.test(value);
197
+ }
198
+ function isSelectorHex(value) {
199
+ return typeof value === "string" && SELECTOR_HEX_RE.test(value);
200
+ }
201
+ function isHexPrefixed(value) {
202
+ return typeof value === "string" && HEX_PREFIXED_RE.test(value);
203
+ }
204
+ function isJwtShape(value) {
205
+ return typeof value === "string" && value.length <= 8192 && JWT_RE.test(value);
206
+ }
207
+ function isSessionIdShape(value) {
208
+ return typeof value === "string" && SESSION_ID_RE.test(value);
209
+ }
210
+ function isUint256DecString(value) {
211
+ return typeof value === "string" && UINT256_DEC_RE.test(value);
212
+ }
213
+ var UINT256_MAX = (1n << 256n) - 1n;
214
+ function isUint256InRange(value) {
215
+ if (!isUint256DecString(value)) return false;
216
+ return BigInt(value) <= UINT256_MAX;
217
+ }
218
+ function parseSelectorCap(raw) {
219
+ if (typeof raw !== "object" || raw === null) {
220
+ return { error: "selectorCap must be an object" };
221
+ }
222
+ const obj = raw;
223
+ if (!isSelectorHex(obj.selector)) {
224
+ return { error: "selectorCap.selector must be a 4-byte 0x-hex" };
225
+ }
226
+ const capArgIndex = obj.capArgIndex;
227
+ const maxAmount = obj.maxAmount;
228
+ const indexIsNull = capArgIndex === null;
229
+ const amountIsNull = maxAmount === null;
230
+ if (indexIsNull !== amountIsNull) {
231
+ return {
232
+ error: "selectorCap.capArgIndex and selectorCap.maxAmount must both be null or both non-null"
233
+ };
234
+ }
235
+ if (!indexIsNull) {
236
+ if (typeof capArgIndex !== "number" || !Number.isInteger(capArgIndex) || capArgIndex < 0 || capArgIndex > 31) {
237
+ return {
238
+ error: "selectorCap.capArgIndex must be an integer in [0, 31] (max 32 ABI words)"
239
+ };
240
+ }
241
+ if (typeof maxAmount !== "string" || !isUint256InRange(maxAmount)) {
242
+ return { error: "selectorCap.maxAmount must be a uint256 decimal string \u2264 2^256-1" };
243
+ }
244
+ }
245
+ return {
246
+ selector: obj.selector.toLowerCase(),
247
+ capArgIndex: indexIsNull ? null : capArgIndex,
248
+ maxAmount: indexIsNull ? null : maxAmount
249
+ };
250
+ }
251
+ function isOptionalHash32(value) {
252
+ return value === void 0 || isHashHex(value);
253
+ }
254
+ function isOptionalPermissionId(value) {
255
+ return value === void 0 || isSelectorHex(value);
256
+ }
257
+ function parsePolicySnapshot(raw) {
258
+ if (typeof raw !== "object" || raw === null) {
259
+ return { error: "snapshot must be a JSON object" };
260
+ }
261
+ const obj = raw;
262
+ if (!isSessionIdShape(obj.sessionId)) {
263
+ return { error: "snapshot.sessionId must be 1-128 chars [A-Za-z0-9_-]" };
264
+ }
265
+ if (obj.mode !== "scoped") {
266
+ return { error: "snapshot.mode must be 'scoped' (wildcard ships in Slice 4)" };
267
+ }
268
+ if (!isAddressHex(obj.signerAddress)) {
269
+ return { error: "snapshot.signerAddress must be a 0x-prefixed 20-byte hex" };
270
+ }
271
+ const targetContracts = obj.targetContracts;
272
+ if (!Array.isArray(targetContracts) || targetContracts.length === 0 || targetContracts.length > 32 || !targetContracts.every(isAddressHex)) {
273
+ return {
274
+ error: "snapshot.targetContracts must be a 1..32-element array of 0x-addresses"
275
+ };
276
+ }
277
+ const rawCaps = obj.selectorCaps;
278
+ if (!Array.isArray(rawCaps) || rawCaps.length === 0 || rawCaps.length > 32) {
279
+ return { error: "snapshot.selectorCaps must be a 1..32-element array" };
280
+ }
281
+ const parsedCaps = [];
282
+ const seenSelectors = /* @__PURE__ */ new Set();
283
+ for (const c of rawCaps) {
284
+ const parsed = parseSelectorCap(c);
285
+ if ("error" in parsed) return { error: `selectorCaps: ${parsed.error}` };
286
+ if (seenSelectors.has(parsed.selector)) {
287
+ return { error: `selectorCaps: duplicate selector ${parsed.selector}` };
288
+ }
289
+ seenSelectors.add(parsed.selector);
290
+ parsedCaps.push(parsed);
291
+ }
292
+ if (typeof obj.validUntilSec !== "number" || !Number.isFinite(obj.validUntilSec) || obj.validUntilSec <= 0) {
293
+ return { error: "snapshot.validUntilSec must be a positive number" };
294
+ }
295
+ if (typeof obj.mintedAtSec !== "number" || !Number.isFinite(obj.mintedAtSec) || obj.mintedAtSec <= 0) {
296
+ return { error: "snapshot.mintedAtSec must be a positive number" };
297
+ }
298
+ if (!isOptionalHash32(obj.consentActionHash)) {
299
+ return { error: "snapshot.consentActionHash must be a 0x-prefixed 32-byte hex when provided" };
300
+ }
301
+ if (!isOptionalHash32(obj.consentTextSha256)) {
302
+ return { error: "snapshot.consentTextSha256 must be a 0x-prefixed 32-byte hex when provided" };
303
+ }
304
+ if (!isOptionalPermissionId(obj.permissionId)) {
305
+ return { error: "snapshot.permissionId must be a 0x-prefixed 4-byte hex when provided" };
306
+ }
307
+ return {
308
+ sessionId: obj.sessionId,
309
+ mode: "scoped",
310
+ signerAddress: obj.signerAddress.toLowerCase(),
311
+ targetContracts: targetContracts.map(
312
+ (a) => a.toLowerCase()
313
+ ),
314
+ selectorCaps: parsedCaps,
315
+ validUntilSec: obj.validUntilSec,
316
+ mintedAtSec: obj.mintedAtSec,
317
+ ...obj.consentActionHash === void 0 ? {} : { consentActionHash: obj.consentActionHash.toLowerCase() },
318
+ ...obj.consentTextSha256 === void 0 ? {} : { consentTextSha256: obj.consentTextSha256.toLowerCase() },
319
+ ...obj.permissionId === void 0 ? {} : { permissionId: obj.permissionId.toLowerCase() }
320
+ };
321
+ }
322
+ function parseBrokerRequest(line) {
323
+ let parsed;
324
+ try {
325
+ parsed = JSON.parse(line);
326
+ } catch {
327
+ return { type: "error", code: "invalid_request", message: "request is not valid JSON" };
328
+ }
329
+ if (typeof parsed !== "object" || parsed === null) {
330
+ return { type: "error", code: "invalid_request", message: "request must be a JSON object" };
331
+ }
332
+ const obj = parsed;
333
+ switch (obj.type) {
334
+ case "hello":
335
+ return { type: "hello" };
336
+ case "sign_hash": {
337
+ const hash = obj.hash;
338
+ if (!isHashHex(hash)) {
339
+ return {
340
+ type: "error",
341
+ code: "invalid_request",
342
+ message: "sign_hash.hash must be a 0x-prefixed 32-byte hex string"
343
+ };
344
+ }
345
+ const intent = obj.intent;
346
+ const intentValid = intent === void 0 || typeof intent === "object" && intent !== null && typeof intent.tool === "string";
347
+ if (!intentValid) {
348
+ return {
349
+ type: "error",
350
+ code: "invalid_request",
351
+ message: "sign_hash.intent.tool must be a string when provided"
352
+ };
353
+ }
354
+ return {
355
+ type: "sign_hash",
356
+ hash,
357
+ ...intent === void 0 ? {} : { intent }
358
+ };
359
+ }
360
+ case "store_jwt": {
361
+ const jwt = obj.jwt;
362
+ if (!isJwtShape(jwt)) {
363
+ return {
364
+ type: "error",
365
+ code: "invalid_request",
366
+ message: "store_jwt.jwt must be a JWT-shaped string \u22648192 chars"
367
+ };
368
+ }
369
+ const expiresAtSec = obj.expiresAtSec;
370
+ const expiresValid = expiresAtSec === void 0 || typeof expiresAtSec === "number" && Number.isFinite(expiresAtSec) && expiresAtSec > 0;
371
+ if (!expiresValid) {
372
+ return {
373
+ type: "error",
374
+ code: "invalid_request",
375
+ message: "store_jwt.expiresAtSec must be a positive number when provided"
376
+ };
377
+ }
378
+ return {
379
+ type: "store_jwt",
380
+ jwt,
381
+ ...expiresAtSec === void 0 ? {} : { expiresAtSec }
382
+ };
383
+ }
384
+ case "get_jwt":
385
+ return { type: "get_jwt" };
386
+ case "clear_jwt":
387
+ return { type: "clear_jwt" };
388
+ case "sign_userop": {
389
+ const sessionId = obj.sessionId;
390
+ if (!isSessionIdShape(sessionId)) {
391
+ return {
392
+ type: "error",
393
+ code: "invalid_request",
394
+ message: "sign_userop.sessionId must be 1-128 chars [A-Za-z0-9_-]"
395
+ };
396
+ }
397
+ const userOpHash = obj.userOpHash;
398
+ if (!isHashHex(userOpHash)) {
399
+ return {
400
+ type: "error",
401
+ code: "invalid_request",
402
+ message: "sign_userop.userOpHash must be a 0x-prefixed 32-byte hex string"
403
+ };
404
+ }
405
+ const innerCall = obj.innerCall;
406
+ if (typeof innerCall !== "object" || innerCall === null) {
407
+ return {
408
+ type: "error",
409
+ code: "invalid_request",
410
+ message: "sign_userop.innerCall must be an object with { target, callData }"
411
+ };
412
+ }
413
+ const ic = innerCall;
414
+ if (!isAddressHex(ic.target)) {
415
+ return {
416
+ type: "error",
417
+ code: "invalid_request",
418
+ message: "sign_userop.innerCall.target must be a 0x-prefixed 20-byte hex"
419
+ };
420
+ }
421
+ if (!isHexPrefixed(ic.callData) || ic.callData.length < 74 || ic.callData.length % 2 !== 0 || ic.callData.length > MAX_CALLDATA_HEX_LEN) {
422
+ return {
423
+ type: "error",
424
+ code: "invalid_request",
425
+ message: "sign_userop.innerCall.callData must be 0x-prefixed even-length hex \u226574 chars (selector + first uint256 arg) and \u2264200000 chars"
426
+ };
427
+ }
428
+ const intent = obj.intent;
429
+ let safeIntent;
430
+ if (intent !== void 0) {
431
+ if (typeof intent !== "object" || intent === null) {
432
+ return {
433
+ type: "error",
434
+ code: "invalid_request",
435
+ message: "sign_userop.intent must be an object when provided"
436
+ };
437
+ }
438
+ const intentObj = intent;
439
+ if (typeof intentObj.tool !== "string" || intentObj.tool.length > 64) {
440
+ return {
441
+ type: "error",
442
+ code: "invalid_request",
443
+ message: "sign_userop.intent.tool must be a string \u226464 chars"
444
+ };
445
+ }
446
+ if (intentObj.summary !== void 0 && (typeof intentObj.summary !== "string" || intentObj.summary.length > 256)) {
447
+ return {
448
+ type: "error",
449
+ code: "invalid_request",
450
+ message: "sign_userop.intent.summary must be a string \u2264256 chars when provided"
451
+ };
452
+ }
453
+ safeIntent = {
454
+ tool: intentObj.tool,
455
+ ...typeof intentObj.summary === "string" ? { summary: intentObj.summary } : {}
456
+ };
457
+ }
458
+ return {
459
+ type: "sign_userop",
460
+ sessionId,
461
+ userOpHash,
462
+ innerCall: {
463
+ target: ic.target.toLowerCase(),
464
+ callData: ic.callData.toLowerCase()
465
+ },
466
+ ...safeIntent === void 0 ? {} : { intent: safeIntent }
467
+ };
468
+ }
469
+ case "store_policy_snapshot": {
470
+ const parsed2 = parsePolicySnapshot(obj.snapshot);
471
+ if ("error" in parsed2) {
472
+ return { type: "error", code: "invalid_request", message: parsed2.error };
473
+ }
474
+ return { type: "store_policy_snapshot", snapshot: parsed2 };
475
+ }
476
+ case "get_policy_snapshot": {
477
+ if (!isSessionIdShape(obj.sessionId)) {
478
+ return {
479
+ type: "error",
480
+ code: "invalid_request",
481
+ message: "get_policy_snapshot.sessionId must be 1-128 chars [A-Za-z0-9_-]"
482
+ };
483
+ }
484
+ return { type: "get_policy_snapshot", sessionId: obj.sessionId };
485
+ }
486
+ case "clear_policy_snapshot": {
487
+ if (!isSessionIdShape(obj.sessionId)) {
488
+ return {
489
+ type: "error",
490
+ code: "invalid_request",
491
+ message: "clear_policy_snapshot.sessionId must be 1-128 chars [A-Za-z0-9_-]"
492
+ };
493
+ }
494
+ return { type: "clear_policy_snapshot", sessionId: obj.sessionId };
495
+ }
496
+ case "get_active_session_id":
497
+ return { type: "get_active_session_id" };
498
+ default:
499
+ return {
500
+ type: "error",
501
+ code: "unsupported_type",
502
+ message: `unsupported request type: ${String(obj.type)}`
503
+ };
504
+ }
505
+ }
506
+ function serializeResponse(res) {
507
+ return JSON.stringify(res) + "\n";
508
+ }
509
+
510
+ // src/clients/broker-client.ts
139
511
  var BrokerClientError = class extends Error {
140
- constructor(code, message, cause) {
512
+ constructor(code, message, cause, brokerCode) {
141
513
  super(message);
142
514
  this.code = code;
143
515
  this.cause = cause;
516
+ this.brokerCode = brokerCode;
144
517
  this.name = "BrokerClientError";
145
518
  }
146
519
  code;
147
520
  cause;
521
+ brokerCode;
148
522
  };
523
+ function semverGte(a, b) {
524
+ const re = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
525
+ const ma = re.exec(a);
526
+ const mb = re.exec(b);
527
+ if (!ma || !mb) {
528
+ throw new BrokerClientError(
529
+ "protocol_error",
530
+ `semverGte: malformed version (got ${JSON.stringify(a)} vs ${JSON.stringify(b)})`
531
+ );
532
+ }
533
+ for (let i = 1; i <= 3; i++) {
534
+ const ai = Number(ma[i]);
535
+ const bi = Number(mb[i]);
536
+ if (ai > bi) return true;
537
+ if (ai < bi) return false;
538
+ }
539
+ return true;
540
+ }
149
541
  var BrokerClient = class {
150
542
  constructor(options) {
151
543
  this.options = options;
@@ -205,6 +597,109 @@ var BrokerClient = class {
205
597
  );
206
598
  }
207
599
  }
600
+ // ── Wave 5 Path D Slice 1 (Commit 3) — policy snapshot CRUD + sign_userop ──
601
+ async signUserOp(args) {
602
+ const res = await this.exchange({
603
+ type: "sign_userop",
604
+ sessionId: args.sessionId,
605
+ userOpHash: args.userOpHash,
606
+ innerCall: args.innerCall,
607
+ ...args.intent ? { intent: args.intent } : {}
608
+ });
609
+ if (res.type !== "sign_userop") {
610
+ throw new BrokerClientError(
611
+ "protocol_error",
612
+ `expected sign_userop response, got ${res.type}`
613
+ );
614
+ }
615
+ return res;
616
+ }
617
+ async storePolicySnapshot(snapshot) {
618
+ const res = await this.exchange({ type: "store_policy_snapshot", snapshot });
619
+ if (res.type !== "store_policy_snapshot") {
620
+ throw new BrokerClientError(
621
+ "protocol_error",
622
+ `expected store_policy_snapshot response, got ${res.type}`
623
+ );
624
+ }
625
+ return res;
626
+ }
627
+ async getPolicySnapshot(sessionId) {
628
+ const res = await this.exchange({ type: "get_policy_snapshot", sessionId });
629
+ if (res.type !== "get_policy_snapshot") {
630
+ throw new BrokerClientError(
631
+ "protocol_error",
632
+ `expected get_policy_snapshot response, got ${res.type}`
633
+ );
634
+ }
635
+ return res;
636
+ }
637
+ async clearPolicySnapshot(sessionId) {
638
+ const res = await this.exchange({ type: "clear_policy_snapshot", sessionId });
639
+ if (res.type !== "clear_policy_snapshot") {
640
+ throw new BrokerClientError(
641
+ "protocol_error",
642
+ `expected clear_policy_snapshot response, got ${res.type}`
643
+ );
644
+ }
645
+ return res;
646
+ }
647
+ async getActiveSessionId() {
648
+ const res = await this.exchange({ type: "get_active_session_id" });
649
+ if (res.type !== "get_active_session_id") {
650
+ throw new BrokerClientError(
651
+ "protocol_error",
652
+ `expected get_active_session_id response, got ${res.type}`
653
+ );
654
+ }
655
+ return res;
656
+ }
657
+ /**
658
+ * Detect whether the running daemon speaks Path D (protocol 0.4.0+).
659
+ * Wraps `hello()` with a semver-gte comparison so the MCP tool layer
660
+ * can short-circuit to Path C with a clear `version_too_old` reason
661
+ * instead of surfacing the opaque `unsupported_type` error a stale
662
+ * 0.3.0 daemon would emit on `sign_userop` / `get_active_session_id`
663
+ * (Backend Architect H-2, round 2).
664
+ *
665
+ * Returns `{ supported: false }` on broker connect failure too — the
666
+ * caller treats "daemon down" identically to "version too old": Path D
667
+ * not available, fall through to Path C.
668
+ */
669
+ async preflight() {
670
+ let hello;
671
+ try {
672
+ hello = await this.hello();
673
+ } catch (err2) {
674
+ return {
675
+ supported: false,
676
+ reason: "broker_unreachable",
677
+ message: err2 instanceof BrokerClientError ? `broker.${err2.code}: ${err2.message}` : err2 instanceof Error ? err2.message : "broker unreachable",
678
+ requiredVersion: BROKER_PROTOCOL_VERSION
679
+ };
680
+ }
681
+ if (!semverGte(hello.version, BROKER_PROTOCOL_VERSION)) {
682
+ return {
683
+ supported: false,
684
+ reason: "version_too_old",
685
+ daemonVersion: hello.version,
686
+ requiredVersion: BROKER_PROTOCOL_VERSION
687
+ };
688
+ }
689
+ if (hello.hasSessionKey === false) {
690
+ return {
691
+ supported: false,
692
+ reason: "session_key_unavailable",
693
+ daemonVersion: hello.version,
694
+ requiredVersion: BROKER_PROTOCOL_VERSION
695
+ };
696
+ }
697
+ return {
698
+ supported: true,
699
+ daemonVersion: hello.version,
700
+ signerAddress: hello.sessionKeyAddress
701
+ };
702
+ }
208
703
  exchange(request) {
209
704
  return new Promise((resolve, reject) => {
210
705
  let socket;
@@ -245,7 +740,12 @@ var BrokerClient = class {
245
740
  const parsed = JSON.parse(line);
246
741
  if (parsed.type === "error") {
247
742
  settleErr(
248
- new BrokerClientError("broker_error", `${parsed.code}: ${parsed.message}`)
743
+ new BrokerClientError(
744
+ "broker_error",
745
+ `${parsed.code}: ${parsed.message}`,
746
+ void 0,
747
+ parsed.code
748
+ )
249
749
  );
250
750
  return;
251
751
  }
@@ -373,6 +873,23 @@ var BackendClient = class {
373
873
  false
374
874
  );
375
875
  }
876
+ /**
877
+ * GET variant that sends no Authorization header. Use for backend
878
+ * endpoints that are intentionally public (e.g. `/api/v1/tokens`
879
+ * which the marketplace + the 0.2.1 `positionBuy` NAV-conversion
880
+ * both read). Avoids triggering the AUTH_REQUIRED branch for the
881
+ * "not yet logged in" case on read paths that don't need auth.
882
+ */
883
+ async getUnauth(path, query) {
884
+ const url = this.buildUrl(path, query);
885
+ return this.exchange(
886
+ "GET",
887
+ url,
888
+ void 0,
889
+ /* withAuth */
890
+ false
891
+ );
892
+ }
376
893
  buildUrl(path, query) {
377
894
  if (!path.startsWith("/")) {
378
895
  throw new BackendError("bad_request", `path must start with "/": ${path}`);
@@ -465,12 +982,413 @@ function mapStatus(status) {
465
982
  if (status >= 500) return "server_error";
466
983
  return "invalid_response";
467
984
  }
468
- var TOOL_DESCRIPTORS = [
469
- {
470
- name: "muhaven.read.portfolio",
471
- group: "read",
472
- description: "Return the authenticated investor's encrypted-balance portfolio summary. Output exposes only public aggregates (token list, ebool isOverexposed / isUnderYield handles); decrypted balances are NEVER included in the response. The LLM should call muhaven.read.portfolio for fact-checks about the user's state, not estimate from chat history.",
473
- sensitive: false
985
+ var ENTRY_POINT_GET_NONCE_ABI = parseAbi([
986
+ "function getNonce(address sender, uint192 key) view returns (uint256)"
987
+ ]);
988
+ var BundlerClientError = class extends Error {
989
+ constructor(code, message, detail) {
990
+ super(message);
991
+ this.code = code;
992
+ this.detail = detail;
993
+ this.name = "BundlerClientError";
994
+ }
995
+ code;
996
+ detail;
997
+ };
998
+ var BundlerClient = class {
999
+ constructor(options) {
1000
+ this.options = options;
1001
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
1002
+ }
1003
+ options;
1004
+ fetchImpl;
1005
+ nextRpcId = 1;
1006
+ /**
1007
+ * Submit a signed UserOperation. Returns the userOpHash the bundler
1008
+ * computed (which must match the hash the broker signed — caller is
1009
+ * responsible for the consistency check; broker policy snapshot
1010
+ * captures the signer-binding piece).
1011
+ */
1012
+ async sendUserOp(userOp, entryPoint) {
1013
+ const result = await this.rpc("eth_sendUserOperation", [userOp, entryPoint]);
1014
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(result)) {
1015
+ throw new BundlerClientError(
1016
+ "invalid_response",
1017
+ `eth_sendUserOperation returned non-hash result: ${JSON.stringify(result).slice(0, 80)}`
1018
+ );
1019
+ }
1020
+ return result.toLowerCase();
1021
+ }
1022
+ /** Return the receipt for a userOpHash, or null when the UserOp has
1023
+ * not yet been bundled. */
1024
+ async getReceipt(userOpHash) {
1025
+ const result = await this.rpc("eth_getUserOperationReceipt", [userOpHash]);
1026
+ if (result === null || result === void 0) return null;
1027
+ return parseReceipt(result);
1028
+ }
1029
+ /**
1030
+ * Poll until the bundler returns a receipt, or `timeoutMs` elapses.
1031
+ * Caller decides retry / fallback behaviour on `receipt_timeout`.
1032
+ *
1033
+ * Poll interval grows linearly from `initialIntervalMs` to
1034
+ * `maxIntervalMs` to avoid burning the bundler quota when blocks are
1035
+ * slow. Default tuning: 500ms → 2000ms over the first 6 polls; then
1036
+ * pinned at 2000ms.
1037
+ */
1038
+ async waitForReceipt(userOpHash, opts) {
1039
+ const clock = opts.clockMs ?? (() => Date.now());
1040
+ const sleep = opts.sleep ?? ((ms) => setTimeout$1(ms));
1041
+ const initial = opts.initialIntervalMs ?? 500;
1042
+ const max = opts.maxIntervalMs ?? 2e3;
1043
+ const deadline = clock() + opts.timeoutMs;
1044
+ let attempt = 0;
1045
+ while (true) {
1046
+ const receipt = await this.getReceipt(userOpHash);
1047
+ if (receipt) return receipt;
1048
+ const now = clock();
1049
+ if (now >= deadline) {
1050
+ throw new BundlerClientError(
1051
+ "receipt_timeout",
1052
+ `no receipt for userOp ${userOpHash} within ${opts.timeoutMs}ms`
1053
+ );
1054
+ }
1055
+ const interval = Math.min(max, initial + attempt * 250);
1056
+ const remaining = Math.max(0, deadline - now);
1057
+ await sleep(Math.min(interval, remaining));
1058
+ attempt++;
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Wave 5 Path D Slice 1 Commit 3.5 — `pm_sponsorUserOperation`.
1063
+ * ZeroDev's bundler URL serves both bundler RPCs AND paymaster RPCs
1064
+ * at the same endpoint, so we don't need a separate paymaster URL.
1065
+ * Returns the paymaster fields + the gas limits the paymaster's
1066
+ * simulation computed (the caller doesn't need a separate
1067
+ * `estimateUserOpGas` round-trip on the happy path).
1068
+ */
1069
+ async sponsorUserOp(userOp, entryPoint) {
1070
+ const result = await this.rpc("pm_sponsorUserOperation", [userOp, entryPoint]);
1071
+ return parseSponsoredFields(result);
1072
+ }
1073
+ /**
1074
+ * Wave 5 Path D Slice 1 Commit 3.5 — `eth_estimateUserOperationGas`.
1075
+ * Not used in the happy path (sponsorship returns gas), but lives as
1076
+ * a fallback for unsponsored flows OR if the operator's paymaster
1077
+ * goes down. Reading gas separately also makes the failure modes
1078
+ * distinguishable for the LLM-facing fallback reasons.
1079
+ */
1080
+ async estimateUserOpGas(userOp, entryPoint) {
1081
+ const result = await this.rpc("eth_estimateUserOperationGas", [userOp, entryPoint]);
1082
+ if (typeof result !== "object" || result === null) {
1083
+ throw new BundlerClientError(
1084
+ "invalid_response",
1085
+ "eth_estimateUserOperationGas returned non-object"
1086
+ );
1087
+ }
1088
+ const obj = result;
1089
+ return {
1090
+ callGasLimit: assertHex(obj.callGasLimit, "estimateUserOpGas.callGasLimit"),
1091
+ verificationGasLimit: assertHex(
1092
+ obj.verificationGasLimit,
1093
+ "estimateUserOpGas.verificationGasLimit"
1094
+ ),
1095
+ preVerificationGas: assertHex(
1096
+ obj.preVerificationGas,
1097
+ "estimateUserOpGas.preVerificationGas"
1098
+ )
1099
+ };
1100
+ }
1101
+ /**
1102
+ * Wave 5 Path D Slice 1 Commit 3.5 — `eth_call` against the
1103
+ * EntryPoint's `getNonce(sender, key)`. Uses the bundler URL as a
1104
+ * full Arb Sepolia node (ZeroDev's bundler accepts read-side RPCs).
1105
+ *
1106
+ * Pass `key = 0n` for the default nonce key — Path D never uses a
1107
+ * non-default key in Slice 1; reserved for batched UserOps in
1108
+ * later slices.
1109
+ */
1110
+ async getNonce(sender, entryPoint, key = 0n) {
1111
+ const data = encodeFunctionData({
1112
+ abi: ENTRY_POINT_GET_NONCE_ABI,
1113
+ functionName: "getNonce",
1114
+ args: [sender, key]
1115
+ });
1116
+ const result = await this.rpc("eth_call", [
1117
+ { to: entryPoint, data },
1118
+ "latest"
1119
+ ]);
1120
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]*$/.test(result)) {
1121
+ throw new BundlerClientError(
1122
+ "invalid_response",
1123
+ `eth_call returned non-hex: ${JSON.stringify(result).slice(0, 80)}`
1124
+ );
1125
+ }
1126
+ const [nonce] = decodeAbiParameters([{ type: "uint256" }], result);
1127
+ return nonce;
1128
+ }
1129
+ /**
1130
+ * Wave 5 Path D Slice 1 Commit 3.5 — fetch the fee market via
1131
+ * `eth_gasPrice` (returns a single value the bundler will accept for
1132
+ * both maxFee + maxPriorityFee on Arb Sepolia, which has effectively
1133
+ * no priority-vs-base distinction).
1134
+ *
1135
+ * Simple-on-purpose: a full EIP-1559 fee market read would need two
1136
+ * RPCs (`eth_maxPriorityFeePerGas` + `eth_getBlock`); Arb Sepolia's
1137
+ * fee dynamics don't require that precision and the paymaster pays
1138
+ * either way. A future caller wanting EIP-1559 precision can add a
1139
+ * sibling method.
1140
+ */
1141
+ async getFeeData() {
1142
+ const result = await this.rpc("eth_gasPrice", []);
1143
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result)) {
1144
+ throw new BundlerClientError(
1145
+ "invalid_response",
1146
+ `eth_gasPrice returned non-hex: ${JSON.stringify(result).slice(0, 80)}`
1147
+ );
1148
+ }
1149
+ const base = BigInt(result);
1150
+ const margined = base * 2n;
1151
+ const hex = `0x${margined.toString(16)}`;
1152
+ return { maxFeePerGas: hex, maxPriorityFeePerGas: hex };
1153
+ }
1154
+ /**
1155
+ * Verify the bundler's reported chainId matches `expectedChainId`. Cheap
1156
+ * to call once at MCP server boot (or lazily before the first send) so
1157
+ * a misconfigured bundler URL surfaces as `chain_mismatch` before any
1158
+ * user-facing send rather than after a guaranteed-failing submit.
1159
+ *
1160
+ * Throws `BundlerClientError(config)` if no `expectedChainId` is set —
1161
+ * caller asked for an assert without configuring the expectation.
1162
+ */
1163
+ async assertChainId() {
1164
+ if (this.options.expectedChainId === void 0) {
1165
+ throw new BundlerClientError(
1166
+ "config",
1167
+ "assertChainId called without expectedChainId configured"
1168
+ );
1169
+ }
1170
+ const result = await this.rpc("eth_chainId", []);
1171
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result)) {
1172
+ throw new BundlerClientError(
1173
+ "invalid_response",
1174
+ `eth_chainId returned non-hex result: ${JSON.stringify(result).slice(0, 80)}`
1175
+ );
1176
+ }
1177
+ const reported = Number.parseInt(result, 16);
1178
+ if (reported !== this.options.expectedChainId) {
1179
+ throw new BundlerClientError(
1180
+ "chain_mismatch",
1181
+ `bundler reports chainId ${reported}, MCP expected ${this.options.expectedChainId}`,
1182
+ { reportedChainId: reported, expectedChainId: this.options.expectedChainId }
1183
+ );
1184
+ }
1185
+ }
1186
+ async rpc(method, params) {
1187
+ const id = this.nextRpcId++;
1188
+ const body = JSON.stringify({ jsonrpc: "2.0", id, method, params });
1189
+ const ctrl = new AbortController();
1190
+ const timer = setTimeout(() => ctrl.abort(), this.options.requestTimeoutMs);
1191
+ let res;
1192
+ try {
1193
+ res = await this.fetchImpl(this.options.endpoint, {
1194
+ method: "POST",
1195
+ headers: { "content-type": "application/json", accept: "application/json" },
1196
+ body,
1197
+ signal: ctrl.signal
1198
+ });
1199
+ } catch (err2) {
1200
+ clearTimeout(timer);
1201
+ if (err2.name === "AbortError") {
1202
+ throw new BundlerClientError("timeout", `bundler ${method} timed out`);
1203
+ }
1204
+ throw new BundlerClientError(
1205
+ "network",
1206
+ `bundler ${method} network error: ${err2 instanceof Error ? err2.message : String(err2)}`,
1207
+ err2
1208
+ );
1209
+ } finally {
1210
+ clearTimeout(timer);
1211
+ }
1212
+ if (!res.ok) {
1213
+ let text = "";
1214
+ try {
1215
+ text = (await res.text()).slice(0, 256);
1216
+ } catch {
1217
+ }
1218
+ throw new BundlerClientError(
1219
+ "http_error",
1220
+ `bundler ${method} \u2192 HTTP ${res.status}: ${text}`
1221
+ );
1222
+ }
1223
+ let parsed;
1224
+ try {
1225
+ parsed = await res.json();
1226
+ } catch (err2) {
1227
+ throw new BundlerClientError(
1228
+ "invalid_response",
1229
+ `bundler ${method} returned non-JSON: ${err2 instanceof Error ? err2.message : String(err2)}`
1230
+ );
1231
+ }
1232
+ if (typeof parsed !== "object" || parsed === null) {
1233
+ throw new BundlerClientError(
1234
+ "invalid_response",
1235
+ `bundler ${method} returned non-object`
1236
+ );
1237
+ }
1238
+ const obj = parsed;
1239
+ if (obj.error !== void 0 && obj.error !== null) {
1240
+ const err2 = obj.error;
1241
+ throw new BundlerClientError(
1242
+ "rpc_error",
1243
+ `bundler ${method} rpc error: ${typeof err2.message === "string" ? err2.message : "<no message>"}`,
1244
+ { code: err2.code, message: err2.message, data: err2.data }
1245
+ );
1246
+ }
1247
+ return obj.result;
1248
+ }
1249
+ };
1250
+ function parseReceipt(raw) {
1251
+ if (typeof raw !== "object" || raw === null) {
1252
+ throw new BundlerClientError("invalid_response", "receipt is not an object");
1253
+ }
1254
+ const obj = raw;
1255
+ const userOpHash = obj.userOpHash;
1256
+ if (typeof userOpHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(userOpHash)) {
1257
+ throw new BundlerClientError("invalid_response", "receipt.userOpHash malformed");
1258
+ }
1259
+ const sender = obj.sender;
1260
+ if (typeof sender !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(sender)) {
1261
+ throw new BundlerClientError("invalid_response", "receipt.sender malformed");
1262
+ }
1263
+ if (typeof obj.success !== "boolean") {
1264
+ throw new BundlerClientError("invalid_response", "receipt.success must be a boolean");
1265
+ }
1266
+ const inner = obj.receipt;
1267
+ if (typeof inner !== "object" || inner === null) {
1268
+ throw new BundlerClientError("invalid_response", "receipt.receipt missing");
1269
+ }
1270
+ const innerObj = inner;
1271
+ const txHash = innerObj.transactionHash;
1272
+ if (typeof txHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(txHash)) {
1273
+ throw new BundlerClientError(
1274
+ "invalid_response",
1275
+ "receipt.receipt.transactionHash malformed"
1276
+ );
1277
+ }
1278
+ const blockNumber = innerObj.blockNumber;
1279
+ if (typeof blockNumber !== "string" || !/^0x[0-9a-fA-F]+$/.test(blockNumber)) {
1280
+ throw new BundlerClientError(
1281
+ "invalid_response",
1282
+ "receipt.receipt.blockNumber malformed"
1283
+ );
1284
+ }
1285
+ const blockHash = innerObj.blockHash;
1286
+ if (typeof blockHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(blockHash)) {
1287
+ throw new BundlerClientError(
1288
+ "invalid_response",
1289
+ "receipt.receipt.blockHash malformed"
1290
+ );
1291
+ }
1292
+ return {
1293
+ userOpHash: userOpHash.toLowerCase(),
1294
+ sender: sender.toLowerCase(),
1295
+ success: obj.success,
1296
+ ...typeof obj.reason === "string" ? { reason: obj.reason } : {},
1297
+ receipt: {
1298
+ transactionHash: txHash.toLowerCase(),
1299
+ blockNumber: blockNumber.toLowerCase(),
1300
+ blockHash: blockHash.toLowerCase()
1301
+ }
1302
+ };
1303
+ }
1304
+ function parseSponsoredFields(raw) {
1305
+ if (typeof raw !== "object" || raw === null) {
1306
+ throw new BundlerClientError(
1307
+ "invalid_response",
1308
+ "pm_sponsorUserOperation returned non-object"
1309
+ );
1310
+ }
1311
+ const obj = raw;
1312
+ return {
1313
+ paymaster: assertHexAddress(obj.paymaster, "sponsoredFields.paymaster"),
1314
+ paymasterVerificationGasLimit: assertHexNonZero(
1315
+ obj.paymasterVerificationGasLimit,
1316
+ "sponsoredFields.paymasterVerificationGasLimit",
1317
+ MAX_PAYMASTER_GAS_LIMIT
1318
+ ),
1319
+ paymasterPostOpGasLimit: assertHexNonZero(
1320
+ obj.paymasterPostOpGasLimit,
1321
+ "sponsoredFields.paymasterPostOpGasLimit",
1322
+ MAX_PAYMASTER_GAS_LIMIT
1323
+ ),
1324
+ // paymasterData is the only sponsored field that can legitimately
1325
+ // be empty (`0x`) — paymasters with no per-op data return that.
1326
+ paymasterData: assertHex(obj.paymasterData, "sponsoredFields.paymasterData"),
1327
+ callGasLimit: assertHexNonZero(
1328
+ obj.callGasLimit,
1329
+ "sponsoredFields.callGasLimit",
1330
+ MAX_CALL_GAS_LIMIT
1331
+ ),
1332
+ verificationGasLimit: assertHexNonZero(
1333
+ obj.verificationGasLimit,
1334
+ "sponsoredFields.verificationGasLimit",
1335
+ MAX_VERIFICATION_GAS_LIMIT
1336
+ ),
1337
+ preVerificationGas: assertHexNonZero(
1338
+ obj.preVerificationGas,
1339
+ "sponsoredFields.preVerificationGas",
1340
+ MAX_PRE_VERIFICATION_GAS
1341
+ )
1342
+ };
1343
+ }
1344
+ function assertHex(value, label) {
1345
+ if (typeof value !== "string" || !/^0x([0-9a-fA-F]{2})*$/.test(value)) {
1346
+ const repr = value === void 0 ? "undefined" : JSON.stringify(value);
1347
+ const safe = typeof repr === "string" ? repr.slice(0, 80) : "unknown";
1348
+ throw new BundlerClientError(
1349
+ "invalid_response",
1350
+ `${label} must be a 0x-prefixed hex string (got ${safe})`
1351
+ );
1352
+ }
1353
+ return value;
1354
+ }
1355
+ function assertHexNonZero(value, label, maxValue) {
1356
+ const hex = assertHex(value, label);
1357
+ if (hex.length === 2 || BigInt(hex) === 0n) {
1358
+ throw new BundlerClientError(
1359
+ "invalid_response",
1360
+ `${label} must be a non-zero hex value (got "${hex}")`
1361
+ );
1362
+ }
1363
+ if (maxValue !== void 0 && BigInt(hex) > maxValue) {
1364
+ throw new BundlerClientError(
1365
+ "invalid_response",
1366
+ `${label} = ${BigInt(hex)} exceeds plausible ceiling ${maxValue} \u2014 refusing to sign + submit`
1367
+ );
1368
+ }
1369
+ return hex;
1370
+ }
1371
+ var MAX_CALL_GAS_LIMIT = 20000000n;
1372
+ var MAX_VERIFICATION_GAS_LIMIT = 20000000n;
1373
+ var MAX_PRE_VERIFICATION_GAS = 5000000n;
1374
+ var MAX_PAYMASTER_GAS_LIMIT = 5000000n;
1375
+ function assertHexAddress(value, label) {
1376
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) {
1377
+ const repr = value === void 0 ? "undefined" : JSON.stringify(value);
1378
+ const safe = typeof repr === "string" ? repr.slice(0, 80) : "unknown";
1379
+ throw new BundlerClientError(
1380
+ "invalid_response",
1381
+ `${label} must be a 0x-prefixed 20-byte hex address (got ${safe})`
1382
+ );
1383
+ }
1384
+ return value;
1385
+ }
1386
+ var TOOL_DESCRIPTORS = [
1387
+ {
1388
+ name: "muhaven.read.portfolio",
1389
+ group: "read",
1390
+ description: "Return the authenticated investor's encrypted-balance portfolio summary. Output exposes only public aggregates (token list, ebool isOverexposed / isUnderYield handles); decrypted balances are NEVER included in the response. The LLM should call muhaven.read.portfolio for fact-checks about the user's state, not estimate from chat history.",
1391
+ sensitive: false
474
1392
  },
475
1393
  {
476
1394
  name: "muhaven.read.yields",
@@ -496,16 +1414,22 @@ var TOOL_DESCRIPTORS = [
496
1414
  description: `Return the authenticated user's tiered-autonomy audit log entries. Cursor-paginated. Useful for forensic review ("why was I paused?") and grant-reviewer demos. Read-only \u2014 never exposes other users' data.`,
497
1415
  sensitive: false
498
1416
  },
1417
+ {
1418
+ name: "muhaven.read.activity",
1419
+ group: "read",
1420
+ description: "Return the authenticated investor's on-chain activity feed (buys / sells / wraps / unwraps / yield claims / transfers). Each row carries token address, tx hash, block timestamp, and event type \u2014 but NEVER cleartext amounts (encrypted handles only, decryptable client-side via permit). USE THIS to verify a Path C dashboard action settled: after position.buy / position.sell / cash.wrap, the user opens the deep-link, taps Authorize, the on-chain tx lands \u2192 a new row appears here. Far more reliable than re-calling read.portfolio (which only changes shape when a NEW token enters the catalog).",
1421
+ sensitive: false
1422
+ },
499
1423
  {
500
1424
  name: "muhaven.position.buy",
501
1425
  group: "position",
502
- description: 'Prepare a Subscription buy. Returns a dashboard deep-link URL (muhaven.app/trade?mode=buy&...) the user opens to review the pre-filled form, then taps Authorize. The user\'s passkey + ZeroDev kernel sign on the dashboard \u2014 this MCP tool never holds or submits a signing key. Use after the user names a clear amount + token (e.g. "Buy 5 mhUSDC of TBILL1" \u2192 `amountUsdc: "5"`). Token accepts either a symbol ("TBILL1") or 0x-address. The `amountUsdc` field is HUMAN-DECIMAL mhUSDC ("5" = 5 mhUSDC, "0.5" = half a mhUSDC) \u2014 NOT base-6 integer. Max 6 fractional digits. Settlement is NOT observable from MCP \u2014 verify by calling muhaven.read.portfolio after the user confirms done.',
1426
+ description: 'Prepare a Subscription buy. Returns a dashboard deep-link URL (muhaven.app/trade?mode=buy&...) the user opens to review the pre-filled form, then taps Authorize. The user\'s passkey + ZeroDev kernel sign on the dashboard \u2014 this MCP tool never holds or submits a signing key. Use after the user names a clear amount + token (e.g. "Buy 5 mhUSDC of TBILL1" \u2192 `amountUsdc: "5"`). Token accepts either a symbol ("TBILL1") or 0x-address. The `amountUsdc` field is HUMAN-DECIMAL mhUSDC ("5" = 5 mhUSDC, "0.5" = half a mhUSDC) \u2014 NOT base-6 integer. Max 6 fractional digits. The tool fetches the current on-chain NAV for the token and converts the notional to integer shares (floor) before building the URL \u2014 so "Buy 3 mhUSDC of GOLD1" at NAV $0.01 becomes "Buy 300 GOLD1 shares (~3 mhUSDC)". Refuses with `amount_too_small_for_share` when the notional won\'t buy at least 1 share at current NAV; the error message tells the user the minimum mhUSDC needed. Settlement is NOT observable from MCP \u2014 verify by calling muhaven.read.activity after the user confirms done (a new "buy" row with the tx hash will appear).',
503
1427
  sensitive: true
504
1428
  },
505
1429
  {
506
1430
  name: "muhaven.position.sell",
507
1431
  group: "position",
508
- description: "Prepare a Subscription sell. Returns a dashboard deep-link URL (muhaven.app/trade?mode=sell&...) with the form pre-filled. Same passkey + verify-after pattern as muhaven.position.buy. Input is amountShares (raw POSITIVE INTEGER share count, NOT mhUSDC notional) \u2014 fhERC-20 shares have no decimals so fractional inputs are rejected.",
1432
+ description: 'Prepare a Subscription sell. Returns a dashboard deep-link URL (muhaven.app/trade?mode=sell&...) with the form pre-filled. Same passkey + verify-after pattern as muhaven.position.buy. Input is amountShares (raw POSITIVE INTEGER share count, NOT mhUSDC notional) \u2014 fhERC-20 shares have no decimals so fractional inputs are rejected. Verify settlement by calling muhaven.read.activity (look for a "sell" or "sell-queued" row with the tx hash).',
509
1433
  sensitive: true
510
1434
  },
511
1435
  {
@@ -524,7 +1448,7 @@ var TOOL_DESCRIPTORS = [
524
1448
  {
525
1449
  name: "muhaven.cash.wrap",
526
1450
  group: "cash",
527
- description: 'Prepare a USDC \u2192 mhUSDC wrap (the encrypted-balance conversion that funds buys). Returns a dashboard deep-link URL (muhaven.app/cash?action=wrap&...) with the amount pre-filled. Input amountUsdc is human-readable USDC ("100" = $100). Common LLM chain: read.portfolio \u2192 notice 0 mhUSDC \u2192 cash.wrap \u2192 then position.buy (each is its own user-confirmed deep-link). Settlement not observable from MCP \u2014 re-call read.portfolio to verify.',
1451
+ description: 'Prepare a USDC \u2192 mhUSDC wrap (the encrypted-balance conversion that funds buys). Returns a dashboard deep-link URL (muhaven.app/cash?action=wrap&...) with the amount pre-filled. Input amountUsdc is human-readable USDC ("100" = $100). Common LLM chain: read.portfolio \u2192 notice 0 mhUSDC \u2192 cash.wrap \u2192 then position.buy (each is its own user-confirmed deep-link). Verify settlement by calling muhaven.read.activity (a new "wrap" row will appear with the tx hash).',
528
1452
  sensitive: true
529
1453
  },
530
1454
  {
@@ -692,6 +1616,10 @@ var ReadAuditInputSchema = z.object({
692
1616
  cursor: z.string().min(1).max(512).optional(),
693
1617
  limit: z.number().int().min(1).max(200).optional()
694
1618
  }).strict();
1619
+ var ReadActivityInputSchema = z.object({
1620
+ limit: z.number().int().min(1).max(50).optional(),
1621
+ offset: z.number().int().min(0).max(1e3).optional()
1622
+ }).strict();
695
1623
  var decimalUsdcAmountSchema = z.string().regex(
696
1624
  /^(0|[1-9]\d*)(\.\d{1,6})?$/,
697
1625
  'must be a positive decimal mhUSDC amount with at most 6 fractional digits (e.g. "5", "0.5", "1234.567")'
@@ -802,6 +1730,119 @@ var GovernanceCastVoteInputSchema = z.object({
802
1730
  voteYes: z.boolean()
803
1731
  }).strict();
804
1732
 
1733
+ // src/auth/jwt-decode.ts
1734
+ var JwtDecodeError = class extends Error {
1735
+ code;
1736
+ constructor(code, message) {
1737
+ super(message);
1738
+ this.name = "JwtDecodeError";
1739
+ this.code = code;
1740
+ }
1741
+ };
1742
+ function decodeJwtPayload(jwt) {
1743
+ const segments = jwt.split(".");
1744
+ if (segments.length !== 3) {
1745
+ throw new JwtDecodeError(
1746
+ "malformed_segments",
1747
+ `expected 3 dot-separated segments, got ${segments.length}`
1748
+ );
1749
+ }
1750
+ const payloadSegment = segments[1];
1751
+ if (payloadSegment === void 0) {
1752
+ throw new JwtDecodeError("malformed_segments", "payload segment missing");
1753
+ }
1754
+ let payloadJson;
1755
+ try {
1756
+ payloadJson = Buffer.from(payloadSegment, "base64url").toString("utf8");
1757
+ } catch (err2) {
1758
+ throw new JwtDecodeError(
1759
+ "malformed_base64",
1760
+ `payload segment is not valid base64url: ${err2 instanceof Error ? err2.message : String(err2)}`
1761
+ );
1762
+ }
1763
+ let parsed;
1764
+ try {
1765
+ parsed = JSON.parse(payloadJson);
1766
+ } catch (err2) {
1767
+ throw new JwtDecodeError(
1768
+ "malformed_json",
1769
+ `payload is not valid JSON: ${err2 instanceof Error ? err2.message : String(err2)}`
1770
+ );
1771
+ }
1772
+ if (parsed === null || typeof parsed !== "object") {
1773
+ throw new JwtDecodeError(
1774
+ "malformed_json",
1775
+ `payload is not a JSON object (got ${parsed === null ? "null" : typeof parsed})`
1776
+ );
1777
+ }
1778
+ const obj = parsed;
1779
+ return {
1780
+ sub: typeof obj.sub === "string" ? obj.sub : null,
1781
+ scope: Array.isArray(obj.scope) ? obj.scope.filter((s) => typeof s === "string") : [],
1782
+ expSec: typeof obj.exp === "number" ? obj.exp : null,
1783
+ iss: typeof obj.iss === "string" ? obj.iss : null
1784
+ };
1785
+ }
1786
+ function truncateSubject(sub) {
1787
+ if (!sub) return "(missing)";
1788
+ const sanitized = sub.replace(/[^\x20-\x7e]/g, "?");
1789
+ if (sanitized.length <= 12) return sanitized;
1790
+ return `${sanitized.slice(0, 8)}\u2026${sanitized.slice(-4)}`;
1791
+ }
1792
+ var KERNEL_EXECUTE_ABI = parseAbi([
1793
+ "function execute(bytes32 mode, bytes calldata executionCalldata)"
1794
+ ]);
1795
+ var KERNEL_V3_SINGLE_CALL_MODE_DEFAULT = `0x${"00".repeat(32)}`;
1796
+ function encodeKernelExecuteSingleCall(input) {
1797
+ const executionCalldata = encodePacked(
1798
+ ["address", "uint256", "bytes"],
1799
+ [input.target, input.value, input.callData]
1800
+ );
1801
+ return encodeFunctionData({
1802
+ abi: KERNEL_EXECUTE_ABI,
1803
+ functionName: "execute",
1804
+ args: [KERNEL_V3_SINGLE_CALL_MODE_DEFAULT, executionCalldata]
1805
+ });
1806
+ }
1807
+ var ECDSA_SIG_HEX_RE = /^0x[0-9a-fA-F]{130}$/;
1808
+ var PERMISSION_USE_PREFIX = "0xff";
1809
+ function buildKernelSessionKeySignature(input) {
1810
+ if (!ECDSA_SIG_HEX_RE.test(input.ecdsaSignature)) {
1811
+ throw new Error(
1812
+ `buildKernelSessionKeySignature: ecdsaSignature must be a 0x-prefixed 65-byte hex (got ${input.ecdsaSignature.length} chars)`
1813
+ );
1814
+ }
1815
+ return concatHex([PERMISSION_USE_PREFIX, input.ecdsaSignature]);
1816
+ }
1817
+ var VALIDATOR_MODE_DEFAULT = "0x00";
1818
+ var VALIDATOR_TYPE_PERMISSION = "0x02";
1819
+ var PERMISSION_ID_HEX_RE = /^0x[0-9a-fA-F]{8}$/;
1820
+ function composeKernelV3NonceKey(args) {
1821
+ if (!PERMISSION_ID_HEX_RE.test(args.permissionId)) {
1822
+ throw new Error(
1823
+ `composeKernelV3NonceKey: permissionId must be a 0x-prefixed 4-byte hex (got ${args.permissionId.length} chars)`
1824
+ );
1825
+ }
1826
+ const customKey = args.customKey ?? 0n;
1827
+ if (customKey < 0n || customKey > 0xffffn) {
1828
+ throw new Error(
1829
+ `composeKernelV3NonceKey: customKey must fit in 2 bytes (0..0xffff), got ${customKey}`
1830
+ );
1831
+ }
1832
+ const paddedPermissionId = pad(args.permissionId, { size: 20, dir: "right" });
1833
+ const customKeyHex = pad(`0x${customKey.toString(16)}`, { size: 2 });
1834
+ const composite = pad(
1835
+ concatHex([
1836
+ VALIDATOR_MODE_DEFAULT,
1837
+ VALIDATOR_TYPE_PERMISSION,
1838
+ paddedPermissionId,
1839
+ customKeyHex
1840
+ ]),
1841
+ { size: 24 }
1842
+ );
1843
+ return BigInt(composite);
1844
+ }
1845
+
805
1846
  // src/tools/auth-required.ts
806
1847
  function authRequiredPayload() {
807
1848
  return {
@@ -812,7 +1853,45 @@ function authRequiredPayload() {
812
1853
  };
813
1854
  }
814
1855
 
1856
+ // src/tools/decimal.ts
1857
+ function parseDecimalToUsd6(decimal) {
1858
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(decimal);
1859
+ if (!m) {
1860
+ throw new Error(`Invalid decimal price: ${JSON.stringify(decimal)}`);
1861
+ }
1862
+ const intPart = m[1];
1863
+ const fracPart = m[2] ?? "";
1864
+ const fracPadded = (fracPart + "000000").slice(0, 6);
1865
+ return BigInt(intPart + fracPadded);
1866
+ }
1867
+ function computeSharesFromUsd6(notionalUsd6, navUsd6) {
1868
+ if (navUsd6 <= 0n) {
1869
+ throw new Error("navUsd6 must be positive");
1870
+ }
1871
+ if (notionalUsd6 < 0n) {
1872
+ throw new Error("notionalUsd6 must be non-negative");
1873
+ }
1874
+ return notionalUsd6 / navUsd6;
1875
+ }
1876
+ function formatUsd6AsDecimal(usd6) {
1877
+ if (usd6 < 0n) {
1878
+ throw new Error("usd6 must be non-negative");
1879
+ }
1880
+ const whole = usd6 / 1000000n;
1881
+ const frac = usd6 % 1000000n;
1882
+ if (frac === 0n) return whole.toString();
1883
+ const fracStr = frac.toString().padStart(6, "0").replace(/0+$/, "");
1884
+ return `${whole.toString()}.${fracStr}`;
1885
+ }
1886
+
815
1887
  // src/tools/handlers.ts
1888
+ var SUBSCRIPTION_PURCHASE_SELECTOR = toFunctionSelector(
1889
+ "function purchase(address,(uint256,uint8,uint8,bytes),uint128,address)"
1890
+ ).toLowerCase();
1891
+ var SUBSCRIPTION_PURCHASE_ABI = parseAbi([
1892
+ "function purchase(address token, (uint256 ctHash, uint8 securityZone, uint8 utype, bytes signature) encShares, uint128 maxSharesHint, address ephemeralEOA)"
1893
+ ]);
1894
+ var PLACEHOLDER_SIGNATURE = "0x" + "fe".repeat(86);
816
1895
  function ok(data) {
817
1896
  return { ok: true, data };
818
1897
  }
@@ -824,85 +1903,775 @@ function mapBackendError(e) {
824
1903
  if (e.code === "unauthorized") return authRequiredPayload();
825
1904
  return err(`backend.${e.code}`, e.message);
826
1905
  }
827
- if (e instanceof Error) return err("backend.network", e.message);
828
- return err("backend.network", "unknown backend error");
829
- }
830
- async function readPortfolio(_input, deps) {
1906
+ if (e instanceof Error) return err("backend.network", e.message);
1907
+ return err("backend.network", "unknown backend error");
1908
+ }
1909
+ async function readPortfolio(_input, deps) {
1910
+ try {
1911
+ const data = await deps.backend.get("/api/v1/portfolio");
1912
+ return ok(data);
1913
+ } catch (e) {
1914
+ return mapBackendError(e);
1915
+ }
1916
+ }
1917
+ async function readYields(input, deps) {
1918
+ try {
1919
+ const data = await deps.backend.get("/api/v1/yields", {
1920
+ token: input.token,
1921
+ limit: input.limit
1922
+ });
1923
+ return ok(data);
1924
+ } catch (e) {
1925
+ return mapBackendError(e);
1926
+ }
1927
+ }
1928
+ async function readDistribution(input, deps) {
1929
+ try {
1930
+ const data = await deps.backend.get("/api/v1/distributions", {
1931
+ token: input.token,
1932
+ epoch: input.epoch
1933
+ });
1934
+ return ok(data);
1935
+ } catch (e) {
1936
+ return mapBackendError(e);
1937
+ }
1938
+ }
1939
+ async function readTokens(_input, deps) {
1940
+ try {
1941
+ const data = await deps.backend.get("/api/v1/tokens");
1942
+ return ok(data);
1943
+ } catch (e) {
1944
+ return mapBackendError(e);
1945
+ }
1946
+ }
1947
+ async function readAudit(input, deps) {
1948
+ try {
1949
+ const data = await deps.backend.get("/api/v1/agent/policy/audit", {
1950
+ surface: input.surface,
1951
+ eventTypes: input.eventTypes?.join(","),
1952
+ since: input.since,
1953
+ until: input.until,
1954
+ cursor: input.cursor,
1955
+ limit: input.limit
1956
+ });
1957
+ return ok(data);
1958
+ } catch (e) {
1959
+ return mapBackendError(e);
1960
+ }
1961
+ }
1962
+ async function readActivity(input, deps) {
1963
+ try {
1964
+ const data = await deps.backend.get("/api/v1/activity", {
1965
+ limit: input.limit,
1966
+ offset: input.offset
1967
+ });
1968
+ return ok(data);
1969
+ } catch (e) {
1970
+ return mapBackendError(e);
1971
+ }
1972
+ }
1973
+ function buildPositionDeeplink(dashboardBaseUrl, action, params) {
1974
+ const base = dashboardBaseUrl.replace(/\/+$/, "");
1975
+ const path = action === "buy" || action === "sell" ? "/trade" : action === "claim" ? "/yields" : "/cash";
1976
+ const search = new URLSearchParams();
1977
+ if (action === "buy" || action === "sell") search.set("mode", action);
1978
+ for (const [k, v] of Object.entries(params)) search.set(k, v);
1979
+ search.set("from", "mcp");
1980
+ return `${base}${path}?${search.toString()}`;
1981
+ }
1982
+ function resolveDashboardBaseUrl(deps) {
1983
+ return deps.dashboardBaseUrl ?? "https://muhaven.app";
1984
+ }
1985
+ function resolveTokenInCatalog(identifier, catalog) {
1986
+ const needle = identifier.toLowerCase();
1987
+ return catalog.find(
1988
+ (t) => t.address.toLowerCase() === needle || t.symbol.toLowerCase() === needle
1989
+ ) ?? null;
1990
+ }
1991
+ function sanitizeSymbolForLlmContext(raw) {
1992
+ const cleaned = raw.replace(/[^A-Za-z0-9_-]/g, "?");
1993
+ return cleaned.length > 16 ? cleaned.slice(0, 16) : cleaned;
1994
+ }
1995
+ function sanitizeRpcMessageForLlmContext(raw) {
1996
+ const cleaned = raw.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/\s+/g, " ").trim();
1997
+ return cleaned.length > 120 ? cleaned.slice(0, 120) + "\u2026" : cleaned;
1998
+ }
1999
+ function mapBrokerCallFailure(err2, verb, defaultReason = "broker_internal") {
2000
+ if (err2 instanceof BrokerClientError && err2.brokerCode === "unsupported_type") {
2001
+ return {
2002
+ kind: "fallback",
2003
+ reason: "version_too_old",
2004
+ message: `broker daemon rejected ${verb} as unsupported_type \u2014 daemon is likely older than protocol 0.4.0; upgrade @muhaven/mcp and restart the broker`
2005
+ };
2006
+ }
2007
+ return {
2008
+ kind: "fallback",
2009
+ reason: defaultReason,
2010
+ message: `broker rejected ${verb} (${typedErrorCode(err2)})`
2011
+ };
2012
+ }
2013
+ var MCP_HEX_20_BYTE_RE = /^0x[0-9a-fA-F]{40}$/;
2014
+ var MCP_HEX_4_BYTE_RE = /^0x[0-9a-fA-F]{8}$/;
2015
+ var MCP_HEX_32_BYTE_RE = /^0x[0-9a-fA-F]{64}$/;
2016
+ var MCP_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
2017
+ var MirrorDtoMalformedError = class extends Error {
2018
+ constructor(message) {
2019
+ super(message);
2020
+ this.name = "MirrorDtoMalformedError";
2021
+ }
2022
+ };
2023
+ function mirrorDtoToPolicySnapshot(dto) {
2024
+ if (dto.mode !== "scoped") {
2025
+ throw new MirrorDtoMalformedError(
2026
+ `mode must be 'scoped' (got ${JSON.stringify(dto.mode)}); wildcard mirror auto-sync ships in Slice 4`
2027
+ );
2028
+ }
2029
+ if (dto.status !== "active") {
2030
+ throw new MirrorDtoMalformedError(
2031
+ `status must be 'active' for auto-sync (got ${JSON.stringify(dto.status)}); backend mirror should have filtered this row out`
2032
+ );
2033
+ }
2034
+ if (typeof dto.sessionId !== "string" || !MCP_SESSION_ID_RE.test(dto.sessionId)) {
2035
+ throw new MirrorDtoMalformedError(
2036
+ `sessionId must match /^[A-Za-z0-9_-]{1,128}$/`
2037
+ );
2038
+ }
2039
+ if (!MCP_HEX_20_BYTE_RE.test(dto.signerAddress)) {
2040
+ throw new MirrorDtoMalformedError(
2041
+ `signerAddress is not a 0x-prefixed 20-byte hex`
2042
+ );
2043
+ }
2044
+ if (!Array.isArray(dto.targetContracts) || dto.targetContracts.length === 0) {
2045
+ throw new MirrorDtoMalformedError(
2046
+ `targetContracts must be a non-empty array`
2047
+ );
2048
+ }
2049
+ for (const t of dto.targetContracts) {
2050
+ if (typeof t !== "string" || !MCP_HEX_20_BYTE_RE.test(t)) {
2051
+ throw new MirrorDtoMalformedError(
2052
+ `targetContracts entry is not a 0x-prefixed 20-byte hex`
2053
+ );
2054
+ }
2055
+ }
2056
+ if (!Array.isArray(dto.selectorCaps) || dto.selectorCaps.length === 0) {
2057
+ throw new MirrorDtoMalformedError(`selectorCaps must be a non-empty array`);
2058
+ }
2059
+ for (const c of dto.selectorCaps) {
2060
+ if (typeof c?.selector !== "string" || !MCP_HEX_4_BYTE_RE.test(c.selector)) {
2061
+ throw new MirrorDtoMalformedError(
2062
+ `selectorCaps entry has a malformed selector`
2063
+ );
2064
+ }
2065
+ }
2066
+ if (dto.permissionId != null && !MCP_HEX_4_BYTE_RE.test(dto.permissionId)) {
2067
+ throw new MirrorDtoMalformedError(
2068
+ `permissionId is not a 0x-prefixed 4-byte hex`
2069
+ );
2070
+ }
2071
+ if (dto.consentActionHash != null && !MCP_HEX_32_BYTE_RE.test(dto.consentActionHash)) {
2072
+ throw new MirrorDtoMalformedError(
2073
+ `consentActionHash is not a 0x-prefixed 32-byte hex`
2074
+ );
2075
+ }
2076
+ if (dto.consentTextSha256 != null && !MCP_HEX_32_BYTE_RE.test(dto.consentTextSha256)) {
2077
+ throw new MirrorDtoMalformedError(
2078
+ `consentTextSha256 is not a 0x-prefixed 32-byte hex`
2079
+ );
2080
+ }
2081
+ return {
2082
+ sessionId: dto.sessionId,
2083
+ mode: "scoped",
2084
+ signerAddress: dto.signerAddress.toLowerCase(),
2085
+ targetContracts: dto.targetContracts.map(
2086
+ (a) => a.toLowerCase()
2087
+ ),
2088
+ selectorCaps: dto.selectorCaps.map((c) => ({
2089
+ selector: c.selector.toLowerCase(),
2090
+ capArgIndex: c.capArgIndex,
2091
+ maxAmount: c.maxAmount
2092
+ })),
2093
+ validUntilSec: dto.validUntilSec,
2094
+ mintedAtSec: dto.mintedAtSec,
2095
+ ...dto.consentActionHash ? { consentActionHash: dto.consentActionHash.toLowerCase() } : {},
2096
+ ...dto.consentTextSha256 ? { consentTextSha256: dto.consentTextSha256.toLowerCase() } : {},
2097
+ ...dto.permissionId ? { permissionId: dto.permissionId.toLowerCase() } : {}
2098
+ };
2099
+ }
2100
+ function typedErrorCode(err2) {
2101
+ if (err2 instanceof BackendError) return `backend.${err2.code}`;
2102
+ if (err2 instanceof BrokerClientError) {
2103
+ return err2.brokerCode ? `broker.${err2.brokerCode}` : `broker.${err2.code}`;
2104
+ }
2105
+ if (err2 instanceof MirrorDtoMalformedError) return "malformed_mirror_row";
2106
+ return "unknown";
2107
+ }
2108
+ async function fetchJwtSubjectHint(deps) {
2109
+ if (!deps.broker) return null;
2110
+ try {
2111
+ const res = await deps.broker.getJwt();
2112
+ if (!res.jwt) return null;
2113
+ const decoded = decodeJwtPayload(res.jwt);
2114
+ return truncateSubject(decoded.sub);
2115
+ } catch {
2116
+ return null;
2117
+ }
2118
+ }
2119
+ async function syncSnapshotFromMirror(deps, brokerSignerAddress) {
2120
+ if (!deps.broker) {
2121
+ return {
2122
+ kind: "fallback",
2123
+ reason: "mirror_sync_failed",
2124
+ message: "auto-sync invoked without a broker dep \u2014 pipeline bug"
2125
+ };
2126
+ }
2127
+ let mirror;
2128
+ try {
2129
+ mirror = await deps.backend.get(
2130
+ "/api/v1/agent/policy/scoped-session",
2131
+ { surface: "mcp" }
2132
+ );
2133
+ } catch (err2) {
2134
+ return {
2135
+ kind: "fallback",
2136
+ reason: "mirror_sync_failed",
2137
+ message: `backend mirror lookup failed (${typedErrorCode(err2)})`
2138
+ };
2139
+ }
2140
+ if (!mirror || mirror.session == null) {
2141
+ const subjectHint = await fetchJwtSubjectHint(deps);
2142
+ const hintSuffix = subjectHint ? ` (broker JWT subject: ${subjectHint} \u2014 verify this matches the userId of the wallet you used to mint the scoped tier; if not, run \`muhaven-broker logout && muhaven-broker login\` and re-authorize with the correct passkey)` : "";
2143
+ return {
2144
+ kind: "fallback",
2145
+ reason: "no_active_session_key",
2146
+ message: "no active scoped session \u2014 visit /agent/policy/transition to mint one, then retry. (Mirror also empty; nothing to auto-sync.)" + hintSuffix
2147
+ };
2148
+ }
2149
+ let snapshot;
2150
+ try {
2151
+ snapshot = mirrorDtoToPolicySnapshot(mirror.session);
2152
+ } catch (err2) {
2153
+ return {
2154
+ kind: "fallback",
2155
+ reason: "mirror_sync_failed",
2156
+ message: `mirror returned a malformed scoped-session row (${typedErrorCode(err2)})`
2157
+ };
2158
+ }
2159
+ if (snapshot.signerAddress.toLowerCase() !== brokerSignerAddress.toLowerCase()) {
2160
+ return {
2161
+ kind: "fallback",
2162
+ reason: "signer_mismatch",
2163
+ message: `mirror snapshot is bound to signer ${snapshot.signerAddress}, broker is currently signing as ${brokerSignerAddress} \u2014 re-mint the scoped tier from the dashboard against the broker's current session key, OR restart the broker with the session key matching the mirror snapshot`
2164
+ };
2165
+ }
2166
+ try {
2167
+ await deps.broker.storePolicySnapshot(snapshot);
2168
+ } catch (err2) {
2169
+ return {
2170
+ kind: "fallback",
2171
+ reason: "mirror_sync_failed",
2172
+ message: `broker rejected store_policy_snapshot (${typedErrorCode(err2)})`
2173
+ };
2174
+ }
2175
+ let activeId;
2176
+ try {
2177
+ const res = await deps.broker.getActiveSessionId();
2178
+ activeId = res.sessionId;
2179
+ } catch (err2) {
2180
+ return {
2181
+ kind: "fallback",
2182
+ reason: "mirror_sync_failed",
2183
+ message: `broker re-probe after store_policy_snapshot failed (${typedErrorCode(err2)})`
2184
+ };
2185
+ }
2186
+ if (!activeId) {
2187
+ return {
2188
+ kind: "fallback",
2189
+ reason: "mirror_sync_failed",
2190
+ message: "broker accepted store_policy_snapshot but get_active_session_id returned null \u2014 most likely cause: multiple non-expired snapshots for the same signer collapse to ambiguous. Clear stale snapshots via the muhaven-broker CLI before retrying. (Snapshot signer was pre-validated to match the broker; signer mismatch already filtered upstream.)"
2191
+ };
2192
+ }
2193
+ return { kind: "ok", sessionId: activeId };
2194
+ }
2195
+ async function attemptPathD(args, deps) {
2196
+ const { shares, tokenAddress, tokenSymbol } = args;
2197
+ if (!deps.broker || !deps.bundler) {
2198
+ return { kind: "unconfigured" };
2199
+ }
2200
+ if (!deps.subscriptionAddress) {
2201
+ return {
2202
+ kind: "fallback",
2203
+ reason: "subscription_address_unset",
2204
+ message: "MUHAVEN_SUBSCRIPTION_ADDRESS not configured \u2014 Path D autonomous-buy disabled until the operator sets it in the MCP env"
2205
+ };
2206
+ }
2207
+ if (!deps.entryPointAddress) {
2208
+ return {
2209
+ kind: "fallback",
2210
+ reason: "entry_point_unset",
2211
+ message: "MUHAVEN_ENTRY_POINT resolved to undefined \u2014 Path D requires the EntryPoint v0.7 address"
2212
+ };
2213
+ }
2214
+ if (typeof deps.chainId !== "number") {
2215
+ return {
2216
+ kind: "fallback",
2217
+ reason: "chain_id_unset",
2218
+ message: "MUHAVEN_CHAIN_ID not configured \u2014 Path D autonomous-buy requires a chain id for userOpHash"
2219
+ };
2220
+ }
2221
+ const subscriptionAddress = deps.subscriptionAddress;
2222
+ const entryPointAddress = deps.entryPointAddress;
2223
+ const chainId = deps.chainId;
2224
+ const preflight = await deps.broker.preflight();
2225
+ if (!preflight.supported) {
2226
+ if (preflight.reason === "broker_unreachable") {
2227
+ return {
2228
+ kind: "fallback",
2229
+ reason: "broker_unreachable",
2230
+ message: `broker daemon not reachable (${preflight.message}) \u2014 falling back to Path C dashboard deep-link`
2231
+ };
2232
+ }
2233
+ if (preflight.reason === "version_too_old") {
2234
+ return {
2235
+ kind: "fallback",
2236
+ reason: "version_too_old",
2237
+ message: `broker speaks ${preflight.daemonVersion}, Path D requires \u2265${preflight.requiredVersion} \u2014 upgrade @muhaven/mcp and restart the broker`
2238
+ };
2239
+ }
2240
+ return {
2241
+ kind: "fallback",
2242
+ reason: "session_key_unavailable",
2243
+ message: "broker is running in read-only posture (no MUHAVEN_BROKER_SESSION_KEY set) \u2014 Path D requires a loaded session key"
2244
+ };
2245
+ }
2246
+ let activeId;
2247
+ try {
2248
+ const res = await deps.broker.getActiveSessionId();
2249
+ activeId = res.sessionId;
2250
+ } catch (err2) {
2251
+ return mapBrokerCallFailure(err2, "get_active_session_id");
2252
+ }
2253
+ if (!activeId) {
2254
+ const synced = await syncSnapshotFromMirror(deps, preflight.signerAddress);
2255
+ if (synced.kind === "fallback") {
2256
+ return synced;
2257
+ }
2258
+ activeId = synced.sessionId;
2259
+ }
2260
+ let snapshot;
2261
+ try {
2262
+ const res = await deps.broker.getPolicySnapshot(activeId);
2263
+ snapshot = res.snapshot;
2264
+ } catch (err2) {
2265
+ return mapBrokerCallFailure(err2, "get_policy_snapshot", "snapshot_lookup_failed");
2266
+ }
2267
+ if (!snapshot) {
2268
+ return {
2269
+ kind: "fallback",
2270
+ reason: "no_active_snapshot",
2271
+ message: `broker reported session ${activeId} active but get_policy_snapshot returned null (race? \u2014 refresh tier from dashboard)`
2272
+ };
2273
+ }
2274
+ if (snapshot.signerAddress.toLowerCase() !== preflight.signerAddress.toLowerCase()) {
2275
+ return {
2276
+ kind: "fallback",
2277
+ reason: "signer_mismatch",
2278
+ message: `snapshot ${activeId} is bound to signer ${snapshot.signerAddress}, broker is currently signing as ${preflight.signerAddress} \u2014 broker session-key likely rotated mid-flight; re-mint the scoped tier from the dashboard`
2279
+ };
2280
+ }
2281
+ const purchaseCap = snapshot.selectorCaps.find(
2282
+ (c) => c.selector.toLowerCase() === SUBSCRIPTION_PURCHASE_SELECTOR
2283
+ );
2284
+ if (!purchaseCap) {
2285
+ return {
2286
+ kind: "fallback",
2287
+ reason: "selector_not_in_snapshot",
2288
+ message: "active scoped session does not authorize subscription.purchase \u2014 re-mint the session with a purchase cap"
2289
+ };
2290
+ }
2291
+ if (purchaseCap.maxAmount === null) {
2292
+ return {
2293
+ kind: "fallback",
2294
+ reason: "selector_uncapped",
2295
+ message: "active scoped session lists subscription.purchase but with no per-op cap (capArgIndex/maxAmount both null) \u2014 Slice 1 refuses to autonomy-buy without an explicit ceiling; re-mint with a maxAmount"
2296
+ };
2297
+ }
2298
+ const maxShares = BigInt(purchaseCap.maxAmount);
2299
+ if (shares > maxShares) {
2300
+ return {
2301
+ kind: "fallback",
2302
+ reason: "out_of_scope",
2303
+ message: `requested ${shares} shares exceeds the active session's per-op cap of ${maxShares} shares \u2014 fall back to Path C dashboard deep-link for this larger buy`
2304
+ };
2305
+ }
2306
+ if (!snapshot.targetContracts.some(
2307
+ (t) => t.toLowerCase() === subscriptionAddress.toLowerCase()
2308
+ )) {
2309
+ return {
2310
+ kind: "fallback",
2311
+ reason: "target_not_in_snapshot",
2312
+ message: `subscription target ${subscriptionAddress} not in active session's target allowlist \u2014 re-mint the session with subscription in scope`
2313
+ };
2314
+ }
2315
+ let accountAddress;
831
2316
  try {
832
- const data = await deps.backend.get("/api/v1/portfolio");
833
- return ok(data);
834
- } catch (e) {
835
- return mapBackendError(e);
2317
+ const stateDto = await deps.backend.get("/api/v1/agent/policy/state", {
2318
+ surface: "mcp"
2319
+ });
2320
+ if (!stateDto.accountAddress || !/^0x[0-9a-fA-F]{40}$/.test(stateDto.accountAddress)) {
2321
+ return {
2322
+ kind: "fallback",
2323
+ reason: "no_validator_registered",
2324
+ message: "backend /agent/policy/state returned no accountAddress \u2014 re-login the MCP"
2325
+ };
2326
+ }
2327
+ accountAddress = stateDto.accountAddress.toLowerCase();
2328
+ } catch (err2) {
2329
+ return {
2330
+ kind: "fallback",
2331
+ reason: "no_validator_registered",
2332
+ message: `backend /agent/policy/state lookup failed: ${err2 instanceof Error ? err2.message : String(err2)}`
2333
+ };
836
2334
  }
837
- }
838
- async function readYields(input, deps) {
2335
+ if (!snapshot.permissionId) {
2336
+ return {
2337
+ kind: "fallback",
2338
+ reason: "no_permission_id_in_snapshot",
2339
+ message: "active scoped session snapshot lacks permissionId \u2014 frontend storePolicySnapshot wire-up is a Slice 2 prerequisite; falling back to Path C"
2340
+ };
2341
+ }
2342
+ const permissionId = snapshot.permissionId;
2343
+ let encShares;
2344
+ let ephemeralEOA;
839
2345
  try {
840
- const data = await deps.backend.get("/api/v1/yields", {
841
- token: input.token,
842
- limit: input.limit
2346
+ const enc = await deps.backend.post("/api/v1/agent/path-d/encrypt-shares", {
2347
+ tokenAddress,
2348
+ sharesAmount: shares.toString()
843
2349
  });
844
- return ok(data);
845
- } catch (e) {
846
- return mapBackendError(e);
2350
+ if (!enc.encShares || typeof enc.encShares.ctHash !== "string" || typeof enc.encShares.securityZone !== "number" || typeof enc.encShares.utype !== "number" || typeof enc.encShares.signature !== "string" || typeof enc.ephemeralEOA !== "string") {
2351
+ return {
2352
+ kind: "fallback",
2353
+ reason: "encrypt_shares_server_error",
2354
+ message: "backend /agent/path-d/encrypt-shares returned malformed payload"
2355
+ };
2356
+ }
2357
+ encShares = {
2358
+ ctHash: enc.encShares.ctHash,
2359
+ securityZone: enc.encShares.securityZone,
2360
+ utype: enc.encShares.utype,
2361
+ signature: enc.encShares.signature
2362
+ };
2363
+ ephemeralEOA = enc.ephemeralEOA;
2364
+ } catch (err2) {
2365
+ if (err2 instanceof BackendError) {
2366
+ const is4xx = typeof err2.status === "number" && err2.status < 500;
2367
+ return {
2368
+ kind: "fallback",
2369
+ reason: is4xx ? "encrypt_shares_rejected" : "encrypt_shares_server_error",
2370
+ message: `backend rejected encrypt-shares (backend.${err2.code})`
2371
+ };
2372
+ }
2373
+ return {
2374
+ kind: "fallback",
2375
+ reason: "encrypt_shares_server_error",
2376
+ message: `backend /agent/path-d/encrypt-shares failed: ${err2 instanceof Error ? err2.message : String(err2)}`
2377
+ };
847
2378
  }
848
- }
849
- async function readDistribution(input, deps) {
2379
+ const innerCallData = encodeFunctionData({
2380
+ abi: SUBSCRIPTION_PURCHASE_ABI,
2381
+ functionName: "purchase",
2382
+ args: [
2383
+ tokenAddress,
2384
+ {
2385
+ ctHash: BigInt(encShares.ctHash),
2386
+ securityZone: encShares.securityZone,
2387
+ utype: encShares.utype,
2388
+ signature: encShares.signature
2389
+ },
2390
+ shares,
2391
+ // maxSharesHint — tight per spec
2392
+ ephemeralEOA
2393
+ ]
2394
+ });
2395
+ const kernelCallData = encodeKernelExecuteSingleCall({
2396
+ target: subscriptionAddress,
2397
+ value: 0n,
2398
+ callData: innerCallData
2399
+ });
2400
+ let nonce;
2401
+ let feeData;
850
2402
  try {
851
- const data = await deps.backend.get("/api/v1/distributions", {
852
- token: input.token,
853
- epoch: input.epoch
2403
+ const nonceKey = composeKernelV3NonceKey({ permissionId });
2404
+ nonce = await deps.bundler.getNonce(accountAddress, entryPointAddress, nonceKey);
2405
+ feeData = await deps.bundler.getFeeData();
2406
+ } catch (err2) {
2407
+ return {
2408
+ kind: "fallback",
2409
+ reason: "bundler_setup_failed",
2410
+ message: `bundler bootstrap failed: ${err2 instanceof BundlerClientError ? `${err2.code}: ${err2.message}` : String(err2)}`
2411
+ };
2412
+ }
2413
+ const partial = {
2414
+ sender: accountAddress,
2415
+ nonce: `0x${nonce.toString(16)}`,
2416
+ callData: kernelCallData,
2417
+ maxFeePerGas: feeData.maxFeePerGas,
2418
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
2419
+ signature: PLACEHOLDER_SIGNATURE
2420
+ };
2421
+ let sponsored;
2422
+ try {
2423
+ sponsored = await deps.bundler.sponsorUserOp(partial, entryPointAddress);
2424
+ } catch (err2) {
2425
+ const detail = err2 instanceof BundlerClientError && err2.detail && typeof err2.detail === "object" ? ` (rpc code=${err2.detail.code ?? "unknown"})` : "";
2426
+ const safeMsg = sanitizeRpcMessageForLlmContext(
2427
+ err2 instanceof Error ? err2.message : String(err2)
2428
+ );
2429
+ return {
2430
+ kind: "fallback",
2431
+ reason: "paymaster_rejected",
2432
+ message: `pm_sponsorUserOperation rejected${detail}: ${safeMsg}`
2433
+ };
2434
+ }
2435
+ const userOpForHash = {
2436
+ sender: accountAddress,
2437
+ nonce,
2438
+ factory: void 0,
2439
+ factoryData: void 0,
2440
+ callData: kernelCallData,
2441
+ callGasLimit: BigInt(sponsored.callGasLimit),
2442
+ verificationGasLimit: BigInt(sponsored.verificationGasLimit),
2443
+ preVerificationGas: BigInt(sponsored.preVerificationGas),
2444
+ maxFeePerGas: BigInt(feeData.maxFeePerGas),
2445
+ maxPriorityFeePerGas: BigInt(feeData.maxPriorityFeePerGas),
2446
+ paymaster: sponsored.paymaster,
2447
+ paymasterVerificationGasLimit: BigInt(sponsored.paymasterVerificationGasLimit),
2448
+ paymasterPostOpGasLimit: BigInt(sponsored.paymasterPostOpGasLimit),
2449
+ paymasterData: sponsored.paymasterData,
2450
+ signature: PLACEHOLDER_SIGNATURE
2451
+ };
2452
+ const userOpHash = getUserOperationHash({
2453
+ userOperation: userOpForHash,
2454
+ entryPointAddress,
2455
+ entryPointVersion: "0.7",
2456
+ chainId
2457
+ });
2458
+ let brokerSig;
2459
+ try {
2460
+ const signed = await deps.broker.signUserOp({
2461
+ sessionId: activeId,
2462
+ userOpHash,
2463
+ innerCall: { target: subscriptionAddress, callData: innerCallData },
2464
+ intent: {
2465
+ tool: "muhaven.position.buy",
2466
+ summary: `${shares.toString()} shares of ${sanitizeSymbolForLlmContext(tokenSymbol)}`
2467
+ }
854
2468
  });
855
- return ok(data);
856
- } catch (e) {
857
- return mapBackendError(e);
2469
+ brokerSig = signed.signature;
2470
+ } catch (err2) {
2471
+ if (err2 instanceof BrokerClientError && err2.brokerCode) {
2472
+ const code = err2.brokerCode;
2473
+ if (code === "policy_violation") {
2474
+ return {
2475
+ kind: "fallback",
2476
+ reason: "broker_policy_violation",
2477
+ message: "broker rejected sign_userop: policy_violation (innerCall vs snapshot mismatch)"
2478
+ };
2479
+ }
2480
+ if (code === "scope_violation") {
2481
+ return {
2482
+ kind: "fallback",
2483
+ reason: "broker_scope_violation",
2484
+ message: "broker rejected sign_userop: scope_violation (snapshot expired between gate and sign)"
2485
+ };
2486
+ }
2487
+ if (code === "max_spend_exceeded") {
2488
+ return {
2489
+ kind: "fallback",
2490
+ reason: "broker_max_spend_exceeded",
2491
+ message: "broker rejected sign_userop: max_spend_exceeded (innerCall maxSharesHint over cap)"
2492
+ };
2493
+ }
2494
+ if (code === "no_active_snapshot") {
2495
+ return {
2496
+ kind: "fallback",
2497
+ reason: "broker_no_active_snapshot_at_sign",
2498
+ message: "broker reported no_active_snapshot at sign time \u2014 likely GC race after our snapshot read"
2499
+ };
2500
+ }
2501
+ }
2502
+ return mapBrokerCallFailure(err2, "sign_userop", "broker_internal");
2503
+ }
2504
+ const signedUserOpWire = {
2505
+ sender: accountAddress,
2506
+ nonce: partial.nonce,
2507
+ callData: kernelCallData,
2508
+ callGasLimit: sponsored.callGasLimit,
2509
+ verificationGasLimit: sponsored.verificationGasLimit,
2510
+ preVerificationGas: sponsored.preVerificationGas,
2511
+ maxFeePerGas: feeData.maxFeePerGas,
2512
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
2513
+ paymaster: sponsored.paymaster,
2514
+ paymasterVerificationGasLimit: sponsored.paymasterVerificationGasLimit,
2515
+ paymasterPostOpGasLimit: sponsored.paymasterPostOpGasLimit,
2516
+ paymasterData: sponsored.paymasterData,
2517
+ signature: buildKernelSessionKeySignature({ ecdsaSignature: brokerSig })
2518
+ };
2519
+ let submittedHash;
2520
+ try {
2521
+ submittedHash = await deps.bundler.sendUserOp(signedUserOpWire, entryPointAddress);
2522
+ } catch (err2) {
2523
+ const detail = err2 instanceof BundlerClientError && err2.detail && typeof err2.detail === "object" ? ` (rpc code=${err2.detail.code ?? "unknown"})` : "";
2524
+ return {
2525
+ kind: "fallback",
2526
+ reason: "bundler_submit_rejected",
2527
+ message: `bundler eth_sendUserOperation rejected${detail}: ${err2 instanceof Error ? err2.message : String(err2)}`
2528
+ };
2529
+ }
2530
+ if (submittedHash.toLowerCase() !== userOpHash.toLowerCase()) {
2531
+ return {
2532
+ kind: "fallback",
2533
+ reason: "userop_hash_mismatch",
2534
+ message: `bundler reported userOpHash ${submittedHash} but we signed ${userOpHash} \u2014 refusing to wait for receipt`
2535
+ };
2536
+ }
2537
+ try {
2538
+ const receipt = await deps.bundler.waitForReceipt(userOpHash, { timeoutMs: 12e3 });
2539
+ return {
2540
+ kind: "ok",
2541
+ data: {
2542
+ action: "buy",
2543
+ status: "submitted",
2544
+ txHash: receipt.receipt.transactionHash,
2545
+ userOpHash,
2546
+ path: "D"
2547
+ }
2548
+ };
2549
+ } catch (err2) {
2550
+ try {
2551
+ const lateReceipt = await deps.bundler.getReceipt(userOpHash);
2552
+ if (lateReceipt) {
2553
+ return {
2554
+ kind: "ok",
2555
+ data: {
2556
+ action: "buy",
2557
+ status: "submitted",
2558
+ txHash: lateReceipt.receipt.transactionHash,
2559
+ userOpHash,
2560
+ path: "D"
2561
+ }
2562
+ };
2563
+ }
2564
+ } catch {
2565
+ }
2566
+ return {
2567
+ kind: "fallback",
2568
+ reason: "bundler_receipt_timeout",
2569
+ message: `no receipt for userOp ${userOpHash} within 12s. The userOp may still mine. BEFORE proposing another position.buy for this intent, call muhaven.read.activity to verify whether the prior submit settled \u2014 re-issuing without that check risks double-filling.`,
2570
+ submittedUserOpHash: userOpHash
2571
+ };
858
2572
  }
859
2573
  }
860
- async function readTokens(_input, deps) {
2574
+ async function positionBuy(input, deps) {
2575
+ let catalog;
861
2576
  try {
862
- const data = await deps.backend.get("/api/v1/tokens");
863
- return ok(data);
2577
+ catalog = await deps.backend.getUnauth("/api/v1/tokens");
864
2578
  } catch (e) {
865
2579
  return mapBackendError(e);
866
2580
  }
867
- }
868
- async function readAudit(input, deps) {
2581
+ const token = resolveTokenInCatalog(input.token, catalog.tokens ?? []);
2582
+ if (!token) {
2583
+ return err(
2584
+ "token_not_found",
2585
+ `Token "${sanitizeSymbolForLlmContext(input.token)}" is not in the MuHaven catalog. Call muhaven.read.tokens for the canonical symbol list.`
2586
+ );
2587
+ }
2588
+ const safeSymbol = sanitizeSymbolForLlmContext(token.symbol);
2589
+ if (!token.latest_nav || !token.latest_nav.nav) {
2590
+ return err(
2591
+ "nav_unavailable",
2592
+ `No NAV snapshot available for ${safeSymbol} yet. The nav-worker may not have written one \u2014 retry shortly, or use the dashboard /trade page directly.`
2593
+ );
2594
+ }
2595
+ let navUsd6;
869
2596
  try {
870
- const data = await deps.backend.get("/api/v1/agent/policy/audit", {
871
- surface: input.surface,
872
- eventTypes: input.eventTypes?.join(","),
873
- since: input.since,
874
- until: input.until,
875
- cursor: input.cursor,
876
- limit: input.limit
877
- });
878
- return ok(data);
2597
+ navUsd6 = parseDecimalToUsd6(token.latest_nav.nav);
879
2598
  } catch (e) {
880
- return mapBackendError(e);
2599
+ return err(
2600
+ "nav_malformed",
2601
+ `NAV for ${safeSymbol} is not a valid decimal price. Open the dashboard /trade page directly.`
2602
+ );
2603
+ }
2604
+ if (navUsd6 <= 0n) {
2605
+ return err(
2606
+ "nav_non_positive",
2607
+ `NAV for ${safeSymbol} is non-positive. Cannot quote a buy.`
2608
+ );
2609
+ }
2610
+ let notionalUsd6;
2611
+ try {
2612
+ notionalUsd6 = parseDecimalToUsd6(input.amountUsdc);
2613
+ } catch (e) {
2614
+ return err(
2615
+ "invalid_amount",
2616
+ `amountUsdc "${input.amountUsdc}" is not a valid decimal mhUSDC amount.`
2617
+ );
2618
+ }
2619
+ if (notionalUsd6 <= 0n) {
2620
+ return err(
2621
+ "invalid_amount",
2622
+ "amountUsdc must be greater than zero."
2623
+ );
2624
+ }
2625
+ const shares = computeSharesFromUsd6(notionalUsd6, navUsd6);
2626
+ if (shares <= 0n) {
2627
+ const navDisplay2 = formatUsd6AsDecimal(navUsd6);
2628
+ return err(
2629
+ "amount_too_small_for_share",
2630
+ `${input.amountUsdc} mhUSDC isn't enough to buy 1 share of ${safeSymbol} at the current NAV of $${navDisplay2}/share. Need at least ${navDisplay2} mhUSDC to buy 1 share. Ask the user for a larger amount, or chain muhaven.cash.wrap first if they're short on mhUSDC.`
2631
+ );
2632
+ }
2633
+ const effectiveNotionalUsd6 = shares * navUsd6;
2634
+ const effectiveNotionalDisplay = formatUsd6AsDecimal(effectiveNotionalUsd6);
2635
+ const navDisplay = formatUsd6AsDecimal(navUsd6);
2636
+ const sharesStr = shares.toString();
2637
+ let pathDFallbackReason;
2638
+ let pathDSubmittedUserOpHash;
2639
+ const pathD = await attemptPathD(
2640
+ { shares, tokenAddress: token.address, tokenSymbol: token.symbol },
2641
+ deps
2642
+ );
2643
+ if (pathD.kind === "ok") {
2644
+ return ok(pathD.data);
2645
+ }
2646
+ if (pathD.kind === "fallback") {
2647
+ pathDFallbackReason = pathD.reason;
2648
+ if (pathD.submittedUserOpHash) {
2649
+ pathDSubmittedUserOpHash = pathD.submittedUserOpHash;
2650
+ }
881
2651
  }
882
- }
883
- function buildPositionDeeplink(dashboardBaseUrl, action, params) {
884
- const base = dashboardBaseUrl.replace(/\/+$/, "");
885
- const path = action === "buy" || action === "sell" ? "/trade" : action === "claim" ? "/yields" : "/cash";
886
- const search = new URLSearchParams();
887
- if (action === "buy" || action === "sell") search.set("mode", action);
888
- for (const [k, v] of Object.entries(params)) search.set(k, v);
889
- search.set("from", "mcp");
890
- return `${base}${path}?${search.toString()}`;
891
- }
892
- function resolveDashboardBaseUrl(deps) {
893
- return deps.dashboardBaseUrl ?? "https://muhaven.app";
894
- }
895
- async function positionBuy(input, deps) {
896
2652
  const dashboardUrl = buildPositionDeeplink(resolveDashboardBaseUrl(deps), "buy", {
897
- token: input.token,
898
- amount: input.amountUsdc
2653
+ token: token.symbol,
2654
+ amount: sharesStr
899
2655
  });
900
2656
  return ok({
901
2657
  dashboardUrl,
902
2658
  action: "buy",
903
- instructions: `Open this link to review and authorize the buy of ${input.amountUsdc} mhUSDC of ${input.token}:
2659
+ instructions: `Open this link to review and authorize the buy of ${sharesStr} ${safeSymbol} shares (~${effectiveNotionalDisplay} mhUSDC at current NAV $${navDisplay}/share):
904
2660
  ${dashboardUrl}`,
905
- echo: { action: "buy", token: input.token, amount: input.amountUsdc }
2661
+ echo: {
2662
+ action: "buy",
2663
+ token: token.symbol,
2664
+ amount: sharesStr,
2665
+ shares: sharesStr,
2666
+ // Carry the original request + the conversion math so the LLM
2667
+ // (and a human auditor reading the trace) can see why the URL
2668
+ // shows the share count instead of the user-stated notional.
2669
+ amountUsdc: input.amountUsdc,
2670
+ effectiveNotionalUsd6: effectiveNotionalUsd6.toString(),
2671
+ navUsd6: navUsd6.toString(),
2672
+ ...pathDFallbackReason ? { pathDFallbackReason } : {},
2673
+ ...pathDSubmittedUserOpHash ? { pathDSubmittedUserOpHash } : {}
2674
+ }
906
2675
  });
907
2676
  }
908
2677
  async function positionSell(input, deps) {
@@ -1144,6 +2913,10 @@ var HANDLERS = {
1144
2913
  schema: ReadAuditInputSchema,
1145
2914
  handler: readAudit
1146
2915
  },
2916
+ "muhaven.read.activity": {
2917
+ schema: ReadActivityInputSchema,
2918
+ handler: readActivity
2919
+ },
1147
2920
  "muhaven.position.buy": {
1148
2921
  schema: PositionBuyInputSchema,
1149
2922
  handler: positionBuy
@@ -1248,14 +3021,20 @@ var SERVER_NAME = "@muhaven/mcp";
1248
3021
  var SERVER_VERSION = resolveServerVersion();
1249
3022
  function resolveServerVersion() {
1250
3023
  {
1251
- return "0.2.0";
3024
+ return "0.2.2";
1252
3025
  }
1253
3026
  }
1254
3027
  function toJsonInputSchema(schema) {
1255
- return {
1256
- type: "object",
1257
- additionalProperties: false
1258
- };
3028
+ const json = zodToJsonSchema(schema, {
3029
+ target: "jsonSchema7",
3030
+ $refStrategy: "none",
3031
+ removeAdditionalStrategy: "strict"
3032
+ });
3033
+ if ("$schema" in json) {
3034
+ const { $schema: _drop, ...rest } = json;
3035
+ return rest;
3036
+ }
3037
+ return json;
1259
3038
  }
1260
3039
  async function loadPinnedToolHashes() {
1261
3040
  const here = dirname(fileURLToPath(import.meta.url));
@@ -1324,8 +3103,12 @@ function buildMcpServer(opts) {
1324
3103
  const result = await entry.handler(parsed, {
1325
3104
  backend: opts.backend,
1326
3105
  broker: opts.broker,
3106
+ bundler: opts.bundler,
1327
3107
  surface: "mcp",
1328
- dashboardBaseUrl: opts.dashboardBaseUrl
3108
+ dashboardBaseUrl: opts.dashboardBaseUrl,
3109
+ chainId: opts.chainId,
3110
+ subscriptionAddress: opts.subscriptionAddress,
3111
+ entryPointAddress: opts.entryPointAddress
1329
3112
  });
1330
3113
  return toolJsonResponse(result);
1331
3114
  } catch (err2) {
@@ -1376,6 +3159,11 @@ async function runMcpStdioCli(opts = {}) {
1376
3159
  timeoutMs: config.requestTimeoutMs,
1377
3160
  allowedHosts: config.allowedBackendHosts
1378
3161
  });
3162
+ const bundler = config.bundlerUrl ? new BundlerClient({
3163
+ endpoint: config.bundlerUrl,
3164
+ requestTimeoutMs: config.bundlerTimeoutMs,
3165
+ expectedChainId: config.chainId
3166
+ }) : void 0;
1379
3167
  const baseRegistry = selectRegistry(config.readOnly);
1380
3168
  const registry = opts.filterRegistry ? opts.filterRegistry(baseRegistry) : baseRegistry;
1381
3169
  if (registry.length === 0) {
@@ -1388,8 +3176,20 @@ async function runMcpStdioCli(opts = {}) {
1388
3176
  registry,
1389
3177
  backend,
1390
3178
  broker: config.readOnly ? void 0 : broker,
1391
- dashboardBaseUrl: config.dashboardBaseUrl
3179
+ bundler: config.readOnly ? void 0 : bundler,
3180
+ dashboardBaseUrl: config.dashboardBaseUrl,
3181
+ chainId: config.chainId,
3182
+ subscriptionAddress: config.subscriptionAddress,
3183
+ entryPointAddress: config.entryPointAddress
1392
3184
  });
3185
+ if (bundler && !config.readOnly) {
3186
+ void bundler.assertChainId().catch((err2) => {
3187
+ process.stderr.write(
3188
+ `[muhaven-mcp] bundler chain-id assert failed: ${err2 instanceof Error ? err2.message : String(err2)} \u2014 Path D autonomous-buys will fail until MUHAVEN_BUNDLER_URL + MUHAVEN_CHAIN_ID agree
3189
+ `
3190
+ );
3191
+ });
3192
+ }
1393
3193
  const transport = new StdioServerTransport();
1394
3194
  await server.connect(transport);
1395
3195
  await new Promise((resolve) => {
@@ -1494,140 +3294,52 @@ var DeviceFlowClient = class {
1494
3294
  const body2 = await safeJson(res);
1495
3295
  throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body: body2 });
1496
3296
  }
1497
- const body = await safeJson(res);
1498
- if (!body || !body.deviceCode || !body.userCode) {
1499
- throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
1500
- }
1501
- const verificationUri = `${trim(this.options.dashboardBaseUrl)}/link`;
1502
- const verificationUriComplete = `${verificationUri}?code=${encodeURIComponent(body.userCode)}`;
1503
- return {
1504
- deviceCode: body.deviceCode,
1505
- userCode: body.userCode,
1506
- verificationUri,
1507
- verificationUriComplete,
1508
- expiresInSec: body.expiresInSec ?? 300,
1509
- pollIntervalSec: body.pollIntervalSec ?? Math.floor(DEFAULT_POLL_INTERVAL_MS / 1e3)
1510
- };
1511
- }
1512
- async pollOnce(deviceCode) {
1513
- const url = new URL("/api/v1/auth/device/token", this.options.backendBaseUrl);
1514
- let res;
1515
- try {
1516
- res = await this.fetchImpl(url, {
1517
- method: "POST",
1518
- headers: { "content-type": "application/json", accept: "application/json" },
1519
- body: JSON.stringify({ deviceCode })
1520
- });
1521
- } catch (err2) {
1522
- throw new DeviceFlowAbortedError({ code: "network", cause: err2 });
1523
- }
1524
- if (res.status === 429) {
1525
- return { state: "pending" };
1526
- }
1527
- const body = await safeJson(res);
1528
- if (!body || typeof body.state !== "string") {
1529
- throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
1530
- }
1531
- return body;
1532
- }
1533
- };
1534
- function trim(s) {
1535
- return s.endsWith("/") ? s.slice(0, -1) : s;
1536
- }
1537
- async function safeJson(res) {
1538
- try {
1539
- return await res.json();
1540
- } catch {
1541
- return null;
1542
- }
1543
- }
1544
-
1545
- // src/broker/protocol.ts
1546
- var BROKER_PROTOCOL_VERSION = "0.3.0";
1547
- var HASH_HEX_RE = /^0x[0-9a-fA-F]{64}$/;
1548
- var JWT_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
1549
- function isHashHex(value) {
1550
- return typeof value === "string" && HASH_HEX_RE.test(value);
1551
- }
1552
- function isJwtShape(value) {
1553
- return typeof value === "string" && value.length <= 8192 && JWT_RE.test(value);
1554
- }
1555
- function parseBrokerRequest(line) {
1556
- let parsed;
1557
- try {
1558
- parsed = JSON.parse(line);
1559
- } catch {
1560
- return { type: "error", code: "invalid_request", message: "request is not valid JSON" };
1561
- }
1562
- if (typeof parsed !== "object" || parsed === null) {
1563
- return { type: "error", code: "invalid_request", message: "request must be a JSON object" };
1564
- }
1565
- const obj = parsed;
1566
- switch (obj.type) {
1567
- case "hello":
1568
- return { type: "hello" };
1569
- case "sign_hash": {
1570
- const hash = obj.hash;
1571
- if (!isHashHex(hash)) {
1572
- return {
1573
- type: "error",
1574
- code: "invalid_request",
1575
- message: "sign_hash.hash must be a 0x-prefixed 32-byte hex string"
1576
- };
1577
- }
1578
- const intent = obj.intent;
1579
- const intentValid = intent === void 0 || typeof intent === "object" && intent !== null && typeof intent.tool === "string";
1580
- if (!intentValid) {
1581
- return {
1582
- type: "error",
1583
- code: "invalid_request",
1584
- message: "sign_hash.intent.tool must be a string when provided"
1585
- };
1586
- }
1587
- return {
1588
- type: "sign_hash",
1589
- hash,
1590
- ...intent === void 0 ? {} : { intent }
1591
- };
3297
+ const body = await safeJson(res);
3298
+ if (!body || !body.deviceCode || !body.userCode) {
3299
+ throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
1592
3300
  }
1593
- case "store_jwt": {
1594
- const jwt = obj.jwt;
1595
- if (!isJwtShape(jwt)) {
1596
- return {
1597
- type: "error",
1598
- code: "invalid_request",
1599
- message: "store_jwt.jwt must be a JWT-shaped string \u22648192 chars"
1600
- };
1601
- }
1602
- const expiresAtSec = obj.expiresAtSec;
1603
- const expiresValid = expiresAtSec === void 0 || typeof expiresAtSec === "number" && Number.isFinite(expiresAtSec) && expiresAtSec > 0;
1604
- if (!expiresValid) {
1605
- return {
1606
- type: "error",
1607
- code: "invalid_request",
1608
- message: "store_jwt.expiresAtSec must be a positive number when provided"
1609
- };
1610
- }
1611
- return {
1612
- type: "store_jwt",
1613
- jwt,
1614
- ...expiresAtSec === void 0 ? {} : { expiresAtSec }
1615
- };
3301
+ const verificationUri = `${trim(this.options.dashboardBaseUrl)}/link`;
3302
+ const verificationUriComplete = `${verificationUri}?code=${encodeURIComponent(body.userCode)}`;
3303
+ return {
3304
+ deviceCode: body.deviceCode,
3305
+ userCode: body.userCode,
3306
+ verificationUri,
3307
+ verificationUriComplete,
3308
+ expiresInSec: body.expiresInSec ?? 300,
3309
+ pollIntervalSec: body.pollIntervalSec ?? Math.floor(DEFAULT_POLL_INTERVAL_MS / 1e3)
3310
+ };
3311
+ }
3312
+ async pollOnce(deviceCode) {
3313
+ const url = new URL("/api/v1/auth/device/token", this.options.backendBaseUrl);
3314
+ let res;
3315
+ try {
3316
+ res = await this.fetchImpl(url, {
3317
+ method: "POST",
3318
+ headers: { "content-type": "application/json", accept: "application/json" },
3319
+ body: JSON.stringify({ deviceCode })
3320
+ });
3321
+ } catch (err2) {
3322
+ throw new DeviceFlowAbortedError({ code: "network", cause: err2 });
1616
3323
  }
1617
- case "get_jwt":
1618
- return { type: "get_jwt" };
1619
- case "clear_jwt":
1620
- return { type: "clear_jwt" };
1621
- default:
1622
- return {
1623
- type: "error",
1624
- code: "unsupported_type",
1625
- message: `unsupported request type: ${String(obj.type)}`
1626
- };
3324
+ if (res.status === 429) {
3325
+ return { state: "pending" };
3326
+ }
3327
+ const body = await safeJson(res);
3328
+ if (!body || typeof body.state !== "string") {
3329
+ throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
3330
+ }
3331
+ return body;
1627
3332
  }
3333
+ };
3334
+ function trim(s) {
3335
+ return s.endsWith("/") ? s.slice(0, -1) : s;
1628
3336
  }
1629
- function serializeResponse(res) {
1630
- return JSON.stringify(res) + "\n";
3337
+ async function safeJson(res) {
3338
+ try {
3339
+ return await res.json();
3340
+ } catch {
3341
+ return null;
3342
+ }
1631
3343
  }
1632
3344
  var MissingSessionKeyError = class extends Error {
1633
3345
  constructor() {
@@ -1643,6 +3355,9 @@ var NullSigner = class {
1643
3355
  async signHash(_hash) {
1644
3356
  throw new MissingSessionKeyError();
1645
3357
  }
3358
+ async signRawMessage(_hash) {
3359
+ throw new MissingSessionKeyError();
3360
+ }
1646
3361
  };
1647
3362
  var ViemSigner = class {
1648
3363
  account;
@@ -1655,6 +3370,9 @@ var ViemSigner = class {
1655
3370
  async signHash(hash) {
1656
3371
  return this.account.sign({ hash });
1657
3372
  }
3373
+ async signRawMessage(hash) {
3374
+ return this.account.signMessage({ message: { raw: hash } });
3375
+ }
1658
3376
  };
1659
3377
  var KEYRING_SERVICE = "muhaven.mcp";
1660
3378
  var KEYRING_ACCOUNT = "jwt";
@@ -1811,11 +3529,293 @@ async function openKeystore(options = {}) {
1811
3529
  }
1812
3530
  return { keystore: new OsKeystore(entry), fallbackReason: null };
1813
3531
  }
3532
+ var PolicyStoreError = class extends Error {
3533
+ constructor(code, message, cause) {
3534
+ super(message);
3535
+ this.code = code;
3536
+ this.cause = cause;
3537
+ this.name = "PolicyStoreError";
3538
+ }
3539
+ code;
3540
+ cause;
3541
+ };
3542
+ var SESSION_ID_RE2 = /^[A-Za-z0-9_-]{1,128}$/;
3543
+ var UINT256_MAX_LOCAL = (1n << 256n) - 1n;
3544
+ function validateSessionId(sessionId) {
3545
+ if (!SESSION_ID_RE2.test(sessionId)) {
3546
+ throw new PolicyStoreError(
3547
+ "invalid_session_id",
3548
+ `sessionId "${sessionId}" must be 1-128 chars [A-Za-z0-9_-] (path-traversal guard)`
3549
+ );
3550
+ }
3551
+ }
3552
+ var FilePolicyStore = class {
3553
+ constructor(dir) {
3554
+ this.dir = dir;
3555
+ }
3556
+ dir;
3557
+ static defaultDir() {
3558
+ return join(homedir(), ".muhaven", "policy-snapshots");
3559
+ }
3560
+ snapshotPath(sessionId) {
3561
+ return join(this.dir, `${sessionId}.json`);
3562
+ }
3563
+ async get(sessionId, nowSec) {
3564
+ validateSessionId(sessionId);
3565
+ let raw;
3566
+ try {
3567
+ raw = await readFile(this.snapshotPath(sessionId), "utf8");
3568
+ } catch (err2) {
3569
+ if (err2.code === "ENOENT") return null;
3570
+ throw new PolicyStoreError(
3571
+ "read_failed",
3572
+ `failed to read snapshot ${sessionId}: ${asMessage2(err2)}`,
3573
+ err2
3574
+ );
3575
+ }
3576
+ let parsed;
3577
+ try {
3578
+ const obj = JSON.parse(raw);
3579
+ parsed = coerceFromDisk(obj);
3580
+ } catch (err2) {
3581
+ throw new PolicyStoreError(
3582
+ "malformed_record",
3583
+ `snapshot ${sessionId} is not valid JSON: ${asMessage2(err2)}`,
3584
+ err2
3585
+ );
3586
+ }
3587
+ if (parsed.validUntilSec <= nowSec) return null;
3588
+ return parsed;
3589
+ }
3590
+ async put(snapshot) {
3591
+ validateSessionId(snapshot.sessionId);
3592
+ const dest = this.snapshotPath(snapshot.sessionId);
3593
+ const tmp = `${dest}.tmp-${randomBytes(6).toString("hex")}`;
3594
+ try {
3595
+ await mkdir(this.dir, { recursive: true, mode: 448 });
3596
+ await chmod(this.dir, 448).catch(() => void 0);
3597
+ await writeFile(tmp, JSON.stringify(snapshot), { mode: 384 });
3598
+ await chmod(tmp, 384).catch(() => void 0);
3599
+ await rename(tmp, dest);
3600
+ } catch (err2) {
3601
+ await unlink(tmp).catch(() => void 0);
3602
+ throw new PolicyStoreError(
3603
+ "write_failed",
3604
+ `failed to write snapshot ${snapshot.sessionId}: ${asMessage2(err2)}`,
3605
+ err2
3606
+ );
3607
+ }
3608
+ }
3609
+ async delete(sessionId) {
3610
+ validateSessionId(sessionId);
3611
+ try {
3612
+ await unlink(this.snapshotPath(sessionId));
3613
+ } catch (err2) {
3614
+ if (err2.code === "ENOENT") return;
3615
+ throw new PolicyStoreError(
3616
+ "delete_failed",
3617
+ `failed to delete snapshot ${sessionId}: ${asMessage2(err2)}`,
3618
+ err2
3619
+ );
3620
+ }
3621
+ }
3622
+ async list() {
3623
+ let entries;
3624
+ try {
3625
+ entries = await readdir(this.dir);
3626
+ } catch (err2) {
3627
+ if (err2.code === "ENOENT") return [];
3628
+ throw new PolicyStoreError(
3629
+ "read_failed",
3630
+ `failed to enumerate snapshot dir: ${asMessage2(err2)}`,
3631
+ err2
3632
+ );
3633
+ }
3634
+ const out = [];
3635
+ for (const entry of entries) {
3636
+ if (!entry.endsWith(".json")) continue;
3637
+ const sessionId = entry.slice(0, -".json".length);
3638
+ if (!SESSION_ID_RE2.test(sessionId)) continue;
3639
+ try {
3640
+ const raw = await readFile(join(this.dir, entry), "utf8");
3641
+ out.push(coerceFromDisk(JSON.parse(raw)));
3642
+ } catch {
3643
+ continue;
3644
+ }
3645
+ }
3646
+ return out;
3647
+ }
3648
+ async activeSessionId(activeSignerAddress, nowSec) {
3649
+ const all = await this.list();
3650
+ const needle = activeSignerAddress.toLowerCase();
3651
+ const matches = all.filter(
3652
+ (s) => s.validUntilSec > nowSec && s.signerAddress.toLowerCase() === needle
3653
+ );
3654
+ return matches.length === 1 ? matches[0].sessionId : null;
3655
+ }
3656
+ };
3657
+ function coerceFromDisk(obj) {
3658
+ if (typeof obj !== "object" || obj === null) throw new Error("snapshot not an object");
3659
+ const o = obj;
3660
+ if (typeof o.sessionId !== "string" || !SESSION_ID_RE2.test(o.sessionId)) {
3661
+ throw new Error("snapshot.sessionId malformed");
3662
+ }
3663
+ if (o.mode !== "scoped") throw new Error('snapshot.mode must be "scoped"');
3664
+ if (typeof o.signerAddress !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(o.signerAddress)) {
3665
+ throw new Error("snapshot.signerAddress malformed");
3666
+ }
3667
+ if (!Array.isArray(o.targetContracts) || !o.targetContracts.every((t) => typeof t === "string" && /^0x[0-9a-fA-F]{40}$/.test(t))) {
3668
+ throw new Error("snapshot.targetContracts malformed");
3669
+ }
3670
+ if (!Array.isArray(o.selectorCaps) || o.selectorCaps.length === 0) {
3671
+ throw new Error("snapshot.selectorCaps malformed");
3672
+ }
3673
+ const caps = [];
3674
+ for (const c of o.selectorCaps) {
3675
+ if (typeof c !== "object" || c === null) throw new Error("selectorCap not an object");
3676
+ const cap = c;
3677
+ if (typeof cap.selector !== "string" || !/^0x[0-9a-fA-F]{8}$/.test(cap.selector)) {
3678
+ throw new Error("selectorCap.selector malformed");
3679
+ }
3680
+ const indexNull = cap.capArgIndex === null;
3681
+ const amountNull = cap.maxAmount === null;
3682
+ if (indexNull !== amountNull) {
3683
+ throw new Error("selectorCap.capArgIndex/maxAmount must both be null or both non-null");
3684
+ }
3685
+ if (!indexNull) {
3686
+ if (typeof cap.capArgIndex !== "number" || !Number.isInteger(cap.capArgIndex) || cap.capArgIndex < 0 || cap.capArgIndex > 31) {
3687
+ throw new Error("selectorCap.capArgIndex must be an integer in [0, 31]");
3688
+ }
3689
+ if (typeof cap.maxAmount !== "string" || !/^(0|[1-9][0-9]{0,77})$/.test(cap.maxAmount)) {
3690
+ throw new Error("selectorCap.maxAmount malformed (length)");
3691
+ }
3692
+ if (BigInt(cap.maxAmount) > UINT256_MAX_LOCAL) {
3693
+ throw new Error("selectorCap.maxAmount exceeds uint256 max");
3694
+ }
3695
+ }
3696
+ caps.push({
3697
+ selector: cap.selector.toLowerCase(),
3698
+ capArgIndex: indexNull ? null : cap.capArgIndex,
3699
+ maxAmount: indexNull ? null : cap.maxAmount
3700
+ });
3701
+ }
3702
+ if (typeof o.validUntilSec !== "number" || o.validUntilSec <= 0) {
3703
+ throw new Error("snapshot.validUntilSec malformed");
3704
+ }
3705
+ if (typeof o.mintedAtSec !== "number" || o.mintedAtSec <= 0) {
3706
+ throw new Error("snapshot.mintedAtSec malformed");
3707
+ }
3708
+ if (o.consentActionHash !== void 0) {
3709
+ if (typeof o.consentActionHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(o.consentActionHash)) {
3710
+ throw new Error("snapshot.consentActionHash malformed");
3711
+ }
3712
+ }
3713
+ if (o.consentTextSha256 !== void 0) {
3714
+ if (typeof o.consentTextSha256 !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(o.consentTextSha256)) {
3715
+ throw new Error("snapshot.consentTextSha256 malformed");
3716
+ }
3717
+ }
3718
+ if (o.permissionId !== void 0) {
3719
+ if (typeof o.permissionId !== "string" || !/^0x[0-9a-fA-F]{8}$/.test(o.permissionId)) {
3720
+ throw new Error("snapshot.permissionId malformed (must be 0x-prefixed 4-byte hex)");
3721
+ }
3722
+ }
3723
+ return {
3724
+ sessionId: o.sessionId,
3725
+ mode: "scoped",
3726
+ signerAddress: o.signerAddress.toLowerCase(),
3727
+ targetContracts: o.targetContracts.map(
3728
+ (t) => t.toLowerCase()
3729
+ ),
3730
+ selectorCaps: caps,
3731
+ validUntilSec: o.validUntilSec,
3732
+ mintedAtSec: o.mintedAtSec,
3733
+ ...o.consentActionHash === void 0 ? {} : { consentActionHash: o.consentActionHash.toLowerCase() },
3734
+ ...o.consentTextSha256 === void 0 ? {} : { consentTextSha256: o.consentTextSha256.toLowerCase() },
3735
+ ...o.permissionId === void 0 ? {} : { permissionId: o.permissionId.toLowerCase() }
3736
+ };
3737
+ }
3738
+ function asMessage2(err2) {
3739
+ return err2 instanceof Error ? err2.message : String(err2);
3740
+ }
3741
+ function decodeUint256ArgAt(callDataHex, wordIndex) {
3742
+ if (!Number.isInteger(wordIndex) || wordIndex < 0) {
3743
+ throw new Error(`wordIndex must be a non-negative integer (got ${wordIndex})`);
3744
+ }
3745
+ const requiredLen = 2 + 8 + (wordIndex + 1) * 64;
3746
+ if (callDataHex.length < requiredLen) {
3747
+ throw new Error(
3748
+ `callData length ${callDataHex.length} too short to carry word ${wordIndex} (need \u2265${requiredLen} chars)`
3749
+ );
3750
+ }
3751
+ const wordStart = 2 + 8 + wordIndex * 64;
3752
+ const argHex = callDataHex.slice(wordStart, wordStart + 64);
3753
+ return BigInt(`0x${argHex}`);
3754
+ }
3755
+ function selectorOf(callDataHex) {
3756
+ return callDataHex.slice(0, 10).toLowerCase();
3757
+ }
3758
+ function checkPolicy(input) {
3759
+ const { snapshot, innerCall, activeSigner, nowSec } = input;
3760
+ if (snapshot.validUntilSec <= nowSec) {
3761
+ return {
3762
+ ok: false,
3763
+ code: "scope_violation",
3764
+ message: `snapshot ${snapshot.sessionId} expired at ${snapshot.validUntilSec} (now ${nowSec})`
3765
+ };
3766
+ }
3767
+ if (snapshot.signerAddress.toLowerCase() !== activeSigner.toLowerCase()) {
3768
+ return {
3769
+ ok: false,
3770
+ code: "policy_violation",
3771
+ message: `snapshot ${snapshot.sessionId} bound to signer ${snapshot.signerAddress}, broker active signer is ${activeSigner}`
3772
+ };
3773
+ }
3774
+ const targetLower = innerCall.target.toLowerCase();
3775
+ const targetMatch = snapshot.targetContracts.some((t) => t === targetLower);
3776
+ if (!targetMatch) {
3777
+ return {
3778
+ ok: false,
3779
+ code: "policy_violation",
3780
+ message: `target ${innerCall.target} not in allowlist for session ${snapshot.sessionId}`
3781
+ };
3782
+ }
3783
+ const selector = selectorOf(innerCall.callData);
3784
+ const rule = snapshot.selectorCaps.find((c) => c.selector === selector);
3785
+ if (!rule) {
3786
+ return {
3787
+ ok: false,
3788
+ code: "policy_violation",
3789
+ message: `selector ${selector} not in selectorCaps for session ${snapshot.sessionId}`
3790
+ };
3791
+ }
3792
+ if (rule.capArgIndex !== null && rule.maxAmount !== null) {
3793
+ let argValue;
3794
+ try {
3795
+ argValue = decodeUint256ArgAt(innerCall.callData, rule.capArgIndex);
3796
+ } catch (err2) {
3797
+ return {
3798
+ ok: false,
3799
+ code: "policy_violation",
3800
+ message: `callData decode failed at wordIndex ${rule.capArgIndex}: ${asMessage2(err2)}`
3801
+ };
3802
+ }
3803
+ const cap = BigInt(rule.maxAmount);
3804
+ if (argValue > cap) {
3805
+ return {
3806
+ ok: false,
3807
+ code: "max_spend_exceeded",
3808
+ message: `arg word[${rule.capArgIndex}] = ${argValue} exceeds maxAmount ${cap} for selector ${selector} (session ${snapshot.sessionId})`
3809
+ };
3810
+ }
3811
+ }
3812
+ return { ok: true };
3813
+ }
1814
3814
 
1815
3815
  // src/broker/daemon.ts
1816
3816
  var noopLogger = (_e) => {
1817
3817
  };
1818
- async function handleBrokerRequest(req, signer, keystore, nowSec = () => Math.floor(Date.now() / 1e3), options = {}) {
3818
+ async function handleBrokerRequest(req, signer, keystore, nowSec = () => Math.floor(Date.now() / 1e3), options = {}, policyStore) {
1819
3819
  switch (req.type) {
1820
3820
  case "hello": {
1821
3821
  let hasJwt = false;
@@ -1888,6 +3888,141 @@ async function handleBrokerRequest(req, signer, keystore, nowSec = () => Math.fl
1888
3888
  );
1889
3889
  }
1890
3890
  }
3891
+ case "sign_userop": {
3892
+ if (!policyStore) {
3893
+ return errorResponse(
3894
+ "internal",
3895
+ "broker daemon is not configured with a policy store"
3896
+ );
3897
+ }
3898
+ const now = nowSec();
3899
+ let snapshot;
3900
+ try {
3901
+ snapshot = await policyStore.get(req.sessionId, now);
3902
+ } catch (err2) {
3903
+ return errorResponse(
3904
+ "internal",
3905
+ err2 instanceof Error ? err2.message : "policy store read failed"
3906
+ );
3907
+ }
3908
+ if (!snapshot) {
3909
+ return errorResponse(
3910
+ "no_active_snapshot",
3911
+ `no active snapshot for session ${req.sessionId}`
3912
+ );
3913
+ }
3914
+ const check = checkPolicy({
3915
+ snapshot,
3916
+ innerCall: req.innerCall,
3917
+ activeSigner: signer.address,
3918
+ nowSec: now
3919
+ });
3920
+ if (!check.ok) {
3921
+ return errorResponse(check.code, check.message);
3922
+ }
3923
+ try {
3924
+ const signature = await signer.signRawMessage(req.userOpHash);
3925
+ return {
3926
+ type: "sign_userop",
3927
+ signature,
3928
+ signerAddress: signer.address,
3929
+ sessionId: req.sessionId
3930
+ };
3931
+ } catch (err2) {
3932
+ if (err2 instanceof MissingSessionKeyError) {
3933
+ return errorResponse("session_key_unavailable", err2.message);
3934
+ }
3935
+ throw err2;
3936
+ }
3937
+ }
3938
+ case "store_policy_snapshot": {
3939
+ if (!policyStore) {
3940
+ return errorResponse(
3941
+ "internal",
3942
+ "broker daemon is not configured with a policy store"
3943
+ );
3944
+ }
3945
+ try {
3946
+ await policyStore.put(req.snapshot);
3947
+ return {
3948
+ type: "store_policy_snapshot",
3949
+ stored: true,
3950
+ sessionId: req.snapshot.sessionId
3951
+ };
3952
+ } catch (err2) {
3953
+ if (err2 instanceof PolicyStoreError) {
3954
+ return errorResponse("internal", err2.message);
3955
+ }
3956
+ return errorResponse(
3957
+ "internal",
3958
+ err2 instanceof Error ? err2.message : "policy store write failed"
3959
+ );
3960
+ }
3961
+ }
3962
+ case "get_policy_snapshot": {
3963
+ if (!policyStore) {
3964
+ return errorResponse(
3965
+ "internal",
3966
+ "broker daemon is not configured with a policy store"
3967
+ );
3968
+ }
3969
+ try {
3970
+ const snapshot = await policyStore.get(req.sessionId, nowSec());
3971
+ return { type: "get_policy_snapshot", snapshot };
3972
+ } catch (err2) {
3973
+ if (err2 instanceof PolicyStoreError) {
3974
+ return errorResponse("internal", err2.message);
3975
+ }
3976
+ return errorResponse(
3977
+ "internal",
3978
+ err2 instanceof Error ? err2.message : "policy store read failed"
3979
+ );
3980
+ }
3981
+ }
3982
+ case "clear_policy_snapshot": {
3983
+ if (!policyStore) {
3984
+ return errorResponse(
3985
+ "internal",
3986
+ "broker daemon is not configured with a policy store"
3987
+ );
3988
+ }
3989
+ try {
3990
+ await policyStore.delete(req.sessionId);
3991
+ return {
3992
+ type: "clear_policy_snapshot",
3993
+ cleared: true,
3994
+ sessionId: req.sessionId
3995
+ };
3996
+ } catch (err2) {
3997
+ if (err2 instanceof PolicyStoreError) {
3998
+ return errorResponse("internal", err2.message);
3999
+ }
4000
+ return errorResponse(
4001
+ "internal",
4002
+ err2 instanceof Error ? err2.message : "policy store clear failed"
4003
+ );
4004
+ }
4005
+ }
4006
+ case "get_active_session_id": {
4007
+ if (!policyStore) {
4008
+ return errorResponse(
4009
+ "internal",
4010
+ "broker daemon is not configured with a policy store"
4011
+ );
4012
+ }
4013
+ try {
4014
+ const sessionId = await policyStore.activeSessionId(signer.address, nowSec());
4015
+ return { type: "get_active_session_id", sessionId };
4016
+ } catch (err2) {
4017
+ if (err2 instanceof PolicyStoreError) {
4018
+ return errorResponse("internal", err2.message);
4019
+ }
4020
+ return errorResponse(
4021
+ "internal",
4022
+ err2 instanceof Error ? err2.message : "policy store enumerate failed"
4023
+ );
4024
+ }
4025
+ }
1891
4026
  }
1892
4027
  }
1893
4028
  function errorResponse(code, message) {
@@ -1917,6 +4052,7 @@ var BrokerDaemon = class {
1917
4052
  log;
1918
4053
  config;
1919
4054
  keystore;
4055
+ policyStore;
1920
4056
  /**
1921
4057
  * Whether a session-key private half is actually loaded. `false` =
1922
4058
  * daemon booted in read-only posture (no `MUHAVEN_BROKER_SESSION_KEY`
@@ -1936,6 +4072,7 @@ var BrokerDaemon = class {
1936
4072
  this.hasSessionKey = false;
1937
4073
  }
1938
4074
  this.keystore = options.keystore ?? null;
4075
+ this.policyStore = options.policyStore ?? new FilePolicyStore(FilePolicyStore.defaultDir());
1939
4076
  this.log = options.logger ?? noopLogger;
1940
4077
  this.server = createServer((socket) => this.onConnection(socket));
1941
4078
  }
@@ -1951,6 +4088,7 @@ var BrokerDaemon = class {
1951
4088
  });
1952
4089
  }
1953
4090
  }
4091
+ if (this.policyStore.init) await this.policyStore.init();
1954
4092
  await prepareEndpoint(this.config.endpoint);
1955
4093
  await new Promise((resolve, reject) => {
1956
4094
  const onError = (err2) => {
@@ -2066,7 +4204,8 @@ var BrokerDaemon = class {
2066
4204
  dashboardBaseUrl: this.config.dashboardBaseUrl
2067
4205
  },
2068
4206
  pid: process.pid
2069
- }
4207
+ },
4208
+ this.policyStore
2070
4209
  );
2071
4210
  socket.end(serializeResponse(res));
2072
4211
  } catch (err2) {
@@ -2082,4 +4221,4 @@ var BrokerDaemon = class {
2082
4221
  }
2083
4222
  };
2084
4223
 
2085
- export { BROKER_PROTOCOL_VERSION, BackendClient, BackendError, BrokerClient, BrokerClientError, BrokerDaemon, DeviceFlowAbortedError, DeviceFlowClient, JwtSource, KeystoreError, MissingSessionKeyError, NoJwtAvailableError, NullSigner, SERVER_VERSION, TOOL_DESCRIPTORS, ViemSigner, ZERO_ADDRESS, buildMcpServer, buildToolHashTable, defaultBrokerEndpoint, fullToolRegistry, handleBrokerRequest, hashToolDescriptor, loadBrokerConfig, loadMcpConfig, openKeystore, parseBrokerRequest, registryForReadOnly, runMcpStdioCli, selectRegistry, serializeResponse, verifyDescriptorAgainstPin };
4224
+ export { BROKER_PROTOCOL_VERSION, BackendClient, BackendError, BrokerClient, BrokerClientError, BrokerDaemon, BundlerClient, BundlerClientError, DeviceFlowAbortedError, DeviceFlowClient, JwtSource, KeystoreError, MissingSessionKeyError, NoJwtAvailableError, NullSigner, SERVER_VERSION, TOOL_DESCRIPTORS, ViemSigner, ZERO_ADDRESS, buildMcpServer, buildToolHashTable, defaultBrokerEndpoint, fullToolRegistry, handleBrokerRequest, hashToolDescriptor, loadBrokerConfig, loadMcpConfig, openKeystore, parseBrokerRequest, registryForReadOnly, runMcpStdioCli, selectRegistry, semverGte, serializeResponse, verifyDescriptorAgainstPin };