@gvnrdao/dh-mcp 0.5.10 → 0.5.11

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/connector.js CHANGED
@@ -617,7 +617,7 @@ var require_utils = __commonJS({
617
617
  exports2.createHasher = createHasher2;
618
618
  exports2.createOptHasher = createOptHasher;
619
619
  exports2.createXOFer = createXOFer;
620
- exports2.randomBytes = randomBytes4;
620
+ exports2.randomBytes = randomBytes5;
621
621
  var crypto_1 = require_cryptoNode();
622
622
  function isBytes2(a) {
623
623
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -815,7 +815,7 @@ var require_utils = __commonJS({
815
815
  exports2.wrapConstructor = createHasher2;
816
816
  exports2.wrapConstructorWithOpts = createOptHasher;
817
817
  exports2.wrapXOFConstructorWithOpts = createXOFer;
818
- function randomBytes4(bytesLength = 32) {
818
+ function randomBytes5(bytesLength = 32) {
819
819
  if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
820
820
  return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
821
821
  }
@@ -40619,19 +40619,208 @@ var net = __toESM(require("net"));
40619
40619
 
40620
40620
  // src/connector/service.ts
40621
40621
  var import_node_http = require("http");
40622
- var import_node_crypto9 = require("crypto");
40622
+ var import_node_crypto10 = require("crypto");
40623
40623
  var import_express = __toESM(require("express"));
40624
40624
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
40625
40625
  var import_router = require("@modelcontextprotocol/sdk/server/auth/router.js");
40626
40626
  var import_types4 = require("@modelcontextprotocol/sdk/types.js");
40627
40627
 
40628
+ // src/connector/auth-md.ts
40629
+ var CHAIN_IDS = { mainnet: 1, sepolia: 11155111 };
40630
+ function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled }) {
40631
+ const origin2 = publicOrigin.replace(/\/+$/, "");
40632
+ const launchNetwork = networks2[0];
40633
+ if (launchNetwork === void 0) {
40634
+ throw new Error("renderAuthMd: networks must name at least one network");
40635
+ }
40636
+ const chainId = CHAIN_IDS[launchNetwork];
40637
+ if (chainId === void 0) {
40638
+ throw new Error(
40639
+ `renderAuthMd: no chain id known for network '${launchNetwork}' \u2014 allowed: ${Object.keys(CHAIN_IDS).join(", ")}`
40640
+ );
40641
+ }
40642
+ const isMainnet = launchNetwork === "mainnet";
40643
+ const wcLine = walletConnectEnabled ? "" : " **Mobile WalletConnect sign-in is not enabled on this deployment** \u2014 browser extension or own-key only.";
40644
+ const agentAuth = {
40645
+ agent_auth: {
40646
+ skill: "operate-position",
40647
+ register_uri: `${origin2}/register`,
40648
+ authorization_servers: [`${origin2}/`],
40649
+ resource: `${origin2}/mcp`,
40650
+ methods: [
40651
+ {
40652
+ type: "oauth2",
40653
+ registration: "rfc7591-dynamic-client-registration",
40654
+ register_uri: `${origin2}/register`,
40655
+ authorization_uri: `${origin2}/authorize`,
40656
+ token_uri: `${origin2}/token`,
40657
+ revocation_uri: `${origin2}/revoke`,
40658
+ grant_types_supported: ["authorization_code", "refresh_token"],
40659
+ response_types_supported: ["code"],
40660
+ code_challenge_methods_supported: ["S256"],
40661
+ token_endpoint_auth_methods_supported: ["client_secret_post", "none"],
40662
+ bearer_methods_supported: ["header"],
40663
+ identity_types_supported: ["wallet_signature"],
40664
+ wallet_signature: {
40665
+ standard: "EIP-4361",
40666
+ chain_id: chainId,
40667
+ credential_types_supported: ["access_token", "refresh_token"]
40668
+ }
40669
+ }
40670
+ ]
40671
+ }
40672
+ };
40673
+ return `# auth.md
40674
+
40675
+ > Agent authentication and registration for Diamond Hands \u2014 a self-custodial Bitcoin
40676
+ > line of credit. Lock native BTC in an isolated L1 vault, mint UCD against it, keep
40677
+ > the Bitcoin.
40678
+
40679
+ This document is for **autonomous agents** that operate a Bitcoin-collateralized UCD
40680
+ position on behalf of the person who owns the wallet. It is generated from this
40681
+ deployment's live configuration, so the endpoints and the chain id below are the ones
40682
+ actually being served.
40683
+
40684
+ ## Agent service
40685
+
40686
+ | | |
40687
+ |---|---|
40688
+ | Protocol | Model Context Protocol (MCP), streamable HTTP |
40689
+ | Endpoint | \`${origin2}/mcp\` |
40690
+ | Network | ${isMainnet ? "Ethereum mainnet (chain id 1) \u2014 real BTC, real UCD" : `${launchNetwork} (chain id ${chainId}) \u2014 test network, test funds`} |
40691
+ | Protected resource metadata | ${origin2}/.well-known/oauth-protected-resource |
40692
+ | Authorization server metadata | ${origin2}/.well-known/oauth-authorization-server |
40693
+
40694
+ \`\`\`json
40695
+ {
40696
+ "mcpServers": {
40697
+ "diamond-hands": {
40698
+ "type": "http",
40699
+ "url": "${origin2}/mcp"
40700
+ }
40701
+ }
40702
+ }
40703
+ \`\`\`
40704
+
40705
+ ## agent_auth
40706
+
40707
+ \`\`\`json
40708
+ ${JSON.stringify(agentAuth, null, 2)}
40709
+ \`\`\`
40710
+
40711
+ ### The registration flow, end to end
40712
+
40713
+ 1. **Register.** \`POST ${origin2}/register\` \u2014 RFC 7591 dynamic client registration,
40714
+ open, no pre-shared credential. You receive a \`client_id\`.
40715
+ 2. **Authorize.** Send the user to \`${origin2}/authorize\` with \`response_type=code\`,
40716
+ your \`client_id\`, \`redirect_uri\`, and a PKCE \`code_challenge\` (\`S256\` \u2014
40717
+ required).
40718
+ 3. **Sign in.** One Sign-In-with-Ethereum signature (EIP-4361) over a message this
40719
+ server minted for that flow. Nothing you supply is parsed back \u2014 the server verifies
40720
+ against its own canonical text, and pins the chain id itself. A person signs this in
40721
+ a browser wallet extension; an agent holding its own key signs the same message
40722
+ through the flow's JSON endpoints.${wcLine}
40723
+ 4. **Exchange.** \`POST ${origin2}/token\` with the code and your \`code_verifier\`. You
40724
+ get an access token and a refresh token.
40725
+ 5. **Call.** Send the access token to \`${origin2}/mcp\` as
40726
+ \`Authorization: Bearer <token>\`. Unauthenticated calls answer \`401\` with a
40727
+ JSON-RPC error, not a redirect.
40728
+
40729
+ ### What the credential is, and is not
40730
+
40731
+ The **wallet address is the account.** There are no passwords, no email addresses, and
40732
+ no user database. Registration creates an OAuth client, not a Diamond Hands account \u2014
40733
+ there is nothing to delete, and no personal data is collected.
40734
+
40735
+ The access token proves **session identity only**. It can read what that address could
40736
+ already read, and it can *stage* a fund-moving operation \u2014 arm a mint, a repayment, a
40737
+ withdrawal \u2014 but it can never complete one: each of those terminates in a wallet
40738
+ signature over that specific operation, which the token cannot produce. So it is not a
40739
+ read-only credential, and it is not a spending one either. A stolen token cannot spend.
40740
+
40741
+ - Access token: ~1 hour. Refresh token: rotating, expires after inactivity.
40742
+ - All authorization state is held **in memory**. A service restart ends every session
40743
+ and the user signs in again. Nothing is persisted at rest.
40744
+ - \`scopes_supported\` is empty and tokens are minted with no scopes \u2014 this
40745
+ authorization server does not implement scoped access. Do not request a scope; you
40746
+ will not receive one.
40747
+
40748
+ ### Who holds the wallet \u2014 read this before you rely on the approval step
40749
+
40750
+ This protocol authenticates **addresses, not people**. It cannot tell whether a
40751
+ signature came from a person clicking a wallet extension or from software holding a key,
40752
+ and it does not try to. Two arrangements are supported, and they have **materially
40753
+ different guarantees**. Be clear which one you are.
40754
+
40755
+ **1. You act for a person, on their wallet.** The human owns the position and signs each
40756
+ operation themselves. This is the arrangement the approval page is designed for: every
40757
+ fund-moving step raises a card the person reads and approves, and you cannot proceed
40758
+ without them. Your token gives you reads and the ability to *stage* a ceremony \u2014 never
40759
+ to complete one.
40760
+
40761
+ **2. You hold your own key and own your own position.** Nothing here treats you
40762
+ differently: you sign in with your key, you create and fund your own vault, you borrow
40763
+ against your own BTC. But then **you are the approver.** The approval card's "Approve
40764
+ ONLY if you initiated this exact BTC withdrawal" is addressed to a human reader, and
40765
+ there is no human in this arrangement. Do not present that step to your operator as
40766
+ independent oversight \u2014 it is not; you are satisfying it yourself.
40767
+
40768
+ What actually bounds arrangement 2 is **on-chain, not in this service**: a BTC
40769
+ withdrawal can only go to an address already on the position's on-chain allowlist, and
40770
+ adding one takes a separate, fully decodable transaction plus the registry's delay \u2014
40771
+ read live from the contract at execution${isMainnet ? " (24 hours on mainnet today)" : ""}.
40772
+ Treat that allowlist as your real safety boundary, and put an address on it
40773
+ deliberately.
40774
+
40775
+ **3. Acting on someone else's position with your own key** \u2014 a delegated agent key \u2014 is
40776
+ **not offered on this endpoint yet.** If you need it, do not attempt to approximate it
40777
+ by holding a person's key; contact us.
40778
+
40779
+ If your operator has asked you to run unattended, you are in arrangement 2. Say so
40780
+ plainly to them, and do not describe the approval step as human review.
40781
+
40782
+ ### Flows this service does not offer
40783
+
40784
+ Stated plainly so a scanner does not infer otherwise: there is **no** ID-JAG
40785
+ (\`urn:ietf:params:oauth:token-type:id-jag\`) identity-assertion flow, **no**
40786
+ verified-email flow, and **no** anonymous flow. The only identity type is a wallet
40787
+ signature.
40788
+
40789
+ ## Public data needs no credential
40790
+
40791
+ Protocol data \u2014 live loans, terms, the peg stability module \u2014 is public. Start at
40792
+ <https://app.diamondhands.credit/llms.txt>, or request any app page with
40793
+ \`Accept: text/markdown\`.
40794
+
40795
+ ## Local alternative
40796
+
40797
+ An agent on the user's own machine can skip this service and talk to the protocol
40798
+ directly through the published MCP server, which carries the same tools:
40799
+
40800
+ - \`npx -y @gvnrdao/dh-mcp\` (requires Node \u2265 18)
40801
+ - \`curl -fsSL https://assets.gvnr.xyz/dh-mcp/install.sh | sh\` (self-contained binary)
40802
+ - Claude Desktop bundle and checksums: <https://assets.gvnr.xyz/dh-mcp/>
40803
+
40804
+ ## Contact
40805
+
40806
+ Security contact and disclosure policy:
40807
+ <https://app.diamondhands.credit/.well-known/security.txt>
40808
+
40809
+ Do not probe \`POST /register\` or \`/authorize\` during passive scans. This document,
40810
+ the protected-resource metadata, and the authorization-server metadata are the safe
40811
+ source of truth.
40812
+ `;
40813
+ }
40814
+
40628
40815
  // src/connector/siwe-oauth.ts
40629
- var import_node_crypto = require("crypto");
40816
+ var import_node_crypto2 = require("crypto");
40630
40817
  var import_ethers = require("ethers");
40631
40818
  var import_errors = require("@modelcontextprotocol/sdk/server/auth/errors.js");
40632
40819
 
40633
40820
  // src/connector/siwe-page.ts
40634
- function renderSiwePage(flowId, clientName) {
40821
+ function renderSiwePage(opts) {
40822
+ const { flowId, redirectHost, nonce } = opts;
40823
+ const clientName = clampClientName(opts.clientName);
40635
40824
  return `<!DOCTYPE html>
40636
40825
  <html>
40637
40826
  <head>
@@ -40645,6 +40834,26 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
40645
40834
  #status { margin-top: 1rem; color: #444; min-height: 1.5rem; }
40646
40835
  .err { color: #b00020; }
40647
40836
  .note { font-size: 0.85rem; color: #666; margin-top: 2rem; }
40837
+ /* "position: relative" is load-bearing, not cosmetic: it puts the consent box in its
40838
+ own stacking context so it paints ABOVE the inline content of the paragraph before
40839
+ it. Without it, a client name built from stacked combining marks overflows its line
40840
+ box downward and paints over this text \u2014 the CSS painting order draws every block
40841
+ background first, then all inline content in tree order. */
40842
+ .dest { background: #fff8e1; border-left: 3px solid #c77700; padding: 0.7rem 0.9rem; font-size: 0.9rem; position: relative; }
40843
+ /* The destination must stay legible under a host the attacker chose the length of:
40844
+ "overflow-wrap: anywhere" lets it wrap mid-label (a dot is not a break opportunity),
40845
+ and the isolate keeps any bidi control inside from reordering the sentence around
40846
+ it. splitRedirectHost has already bounded the length; this bounds the geometry. */
40847
+ .dest code { font-family: ui-monospace, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
40848
+ .dest .host-head { color: #5a5a5a; }
40849
+ .dest .host-tail { font-weight: 700; color: #000; }
40850
+ /* The elision is NOT decoration \u2014 it is the page admitting it withheld characters, so
40851
+ it must be as visible as the text it replaced. */
40852
+ .dest .host-cut { color: #c77700; font-weight: 700; font-style: normal; }
40853
+ /* The attacker-chosen name is clipped to a fixed box: bounded characters alone do not
40854
+ bound HEIGHT (combining marks stack vertically), and an isolate stops an unpaired
40855
+ RTL override inside the name from reversing the rest of the sentence. */
40856
+ .cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 700; }
40648
40857
  #qr { max-width: 16rem; margin-top: 1rem; }
40649
40858
  #qr svg { width: 100%; height: auto; }
40650
40859
  #wc-uri { font-size: 0.7rem; word-break: break-all; color: #888; }
@@ -40652,14 +40861,15 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
40652
40861
  </head>
40653
40862
  <body>
40654
40863
  <h1>Sign in to Diamond Hands</h1>
40655
- <p><b>${escapeHtml(clientName)}</b> is asking to connect. Signing in proves you own a wallet address \u2014 it authorizes nothing on-chain and can never move funds.</p>
40864
+ <p><span class="cname" dir="ltr">${escapeHtml(clientName)}</span> is asking to connect. Signing in proves you own a wallet address \u2014 it authorizes nothing on-chain and can never move funds.</p>
40865
+ <p class="dest">When you sign, this connection is handed to <code dir="ltr">${renderRedirectHost(redirectHost)}</code>. Anyone can register a client under any name, so read the host, not the name \u2014 and read it from the <b>bold end</b>, which is the part that decides who actually owns it. If you do not recognize it, close this page; nothing has happened yet.</p>
40656
40866
  <button id="connect">Browser wallet</button>
40657
40867
  <button id="wc">Mobile wallet (QR)</button>
40658
40868
  <div id="status"></div>
40659
40869
  <div id="qr"></div>
40660
40870
  <p id="wc-uri"></p>
40661
40871
  <p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect).</p>
40662
- <script>
40872
+ <script nonce="${nonce}">
40663
40873
  const FLOW = ${JSON.stringify(flowId)};
40664
40874
  const statusEl = document.getElementById("status");
40665
40875
  function show(text, isErr) { statusEl.textContent = text; statusEl.className = isErr ? "err" : ""; }
@@ -40730,6 +40940,46 @@ document.getElementById("wc").addEventListener("click", async () => {
40730
40940
  function escapeHtml(s) {
40731
40941
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
40732
40942
  }
40943
+ var MAX_CLIENT_NAME_CHARS = 64;
40944
+ var HOST_TAIL_CHARS = 48;
40945
+ var HOST_HEAD_CHARS = 12;
40946
+ var HOST_TAIL_LABELS = 3;
40947
+ var HOST_ELISION_FLOOR = 12;
40948
+ var MAX_HOST_DISPLAY_CHARS = HOST_HEAD_CHARS + HOST_TAIL_CHARS + 24;
40949
+ function splitRedirectHost(host) {
40950
+ const labels = host.split(".");
40951
+ const labelTail = labels.slice(-HOST_TAIL_LABELS).join(".");
40952
+ const tailStart = Math.max(host.length - labelTail.length, host.length - HOST_TAIL_CHARS, 0);
40953
+ const tail = host.slice(tailStart);
40954
+ const fullHead = host.slice(0, tailStart);
40955
+ if (fullHead.length <= HOST_HEAD_CHARS + HOST_ELISION_FLOOR) return { head: fullHead, elided: 0, tail };
40956
+ return { head: fullHead.slice(0, HOST_HEAD_CHARS), elided: fullHead.length - HOST_HEAD_CHARS, tail };
40957
+ }
40958
+ function renderRedirectHost(host) {
40959
+ const { head, elided, tail } = splitRedirectHost(host);
40960
+ const cut = elided === 0 ? "" : `<span class="host-cut">\u2026+${elided} chars\u2026</span>`;
40961
+ return `<span class="host-head">${escapeHtml(head)}</span>${cut}<span class="host-tail">${escapeHtml(tail)}</span>`;
40962
+ }
40963
+ function clampClientName(name) {
40964
+ const points = [...name];
40965
+ if (points.length <= MAX_CLIENT_NAME_CHARS) return name;
40966
+ return `${points.slice(0, MAX_CLIENT_NAME_CHARS - 1).join("")}\u2026`;
40967
+ }
40968
+
40969
+ // src/util/page-headers.ts
40970
+ var import_node_crypto = require("crypto");
40971
+ function htmlPageSecurityHeaders() {
40972
+ const nonce = (0, import_node_crypto.randomBytes)(16).toString("base64");
40973
+ return {
40974
+ nonce,
40975
+ headers: {
40976
+ "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
40977
+ "X-Frame-Options": "DENY",
40978
+ "Referrer-Policy": "no-referrer",
40979
+ "X-Content-Type-Options": "nosniff"
40980
+ }
40981
+ };
40982
+ }
40733
40983
 
40734
40984
  // src/connector/siwe-oauth.ts
40735
40985
  var FLOW_TTL_MS = 10 * 60 * 1e3;
@@ -40758,6 +41008,12 @@ var SiweOAuthProvider = class {
40758
41008
  return {
40759
41009
  getClient: (clientId) => clients.get(clientId),
40760
41010
  registerClient: (client) => {
41011
+ const name = client.client_name;
41012
+ if (name !== void 0 && [...name].length > MAX_CLIENT_NAME_CHARS) {
41013
+ throw new import_errors.InvalidClientMetadataError(
41014
+ `client_name is ${[...name].length} characters \u2014 this authorization server displays it on a consent screen and accepts at most ${MAX_CLIENT_NAME_CHARS}`
41015
+ );
41016
+ }
40761
41017
  while (clients.size >= maxClients) {
40762
41018
  const oldest = clients.keys().next().value;
40763
41019
  if (oldest === void 0) break;
@@ -40768,12 +41024,28 @@ var SiweOAuthProvider = class {
40768
41024
  }
40769
41025
  };
40770
41026
  }
40771
- /** SDK authorize handler → we render the SIWE sign-in page for this flow. */
41027
+ /** SDK authorize handler → we render the SIWE sign-in page for this flow.
41028
+ *
41029
+ * C-45: the page is a PUBLIC sign-in surface served ahead of any host helmet, so this
41030
+ * response carries its own security headers, and the page names the redirect HOST —
41031
+ * the consent fact that open registration makes `client_name` unable to carry. */
40772
41032
  async authorize(client, params, res) {
40773
41033
  this.sweep();
40774
- const flowId = (0, import_node_crypto.randomBytes)(16).toString("hex");
41034
+ const flowId = (0, import_node_crypto2.randomBytes)(16).toString("hex");
40775
41035
  this.flows.set(flowId, { clientId: client.client_id, params, createdAt: this.clock() });
40776
- res.status(200).type("html").send(renderSiwePage(flowId, client.client_name ?? client.client_id));
41036
+ const page = htmlPageSecurityHeaders();
41037
+ for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
41038
+ res.status(200).type("html").send(
41039
+ renderSiwePage({
41040
+ flowId,
41041
+ clientName: client.client_name ?? client.client_id,
41042
+ // Parseable by the time authorize() runs: the SDK validates every registered
41043
+ // redirect_uri (SafeUrlSchema) and, for a request-supplied one, URL.canParse
41044
+ // plus a registered-URI match — so this constructor cannot throw here.
41045
+ redirectHost: new URL(params.redirectUri).host,
41046
+ nonce: page.nonce
41047
+ })
41048
+ );
40777
41049
  }
40778
41050
  /** Page step 1: the wallet reported its address — mint the CANONICAL SIWE message.
40779
41051
  * Re-calling rebinds (the user switched wallet accounts before signing). The chain id
@@ -40790,7 +41062,7 @@ var SiweOAuthProvider = class {
40790
41062
  mintSiweMessage(checksummedAddress) {
40791
41063
  const origin2 = this.opts.origin();
40792
41064
  const domain = new URL(origin2).host;
40793
- const nonce = (0, import_node_crypto.randomBytes)(8).toString("hex");
41065
+ const nonce = (0, import_node_crypto2.randomBytes)(8).toString("hex");
40794
41066
  return `${domain} wants you to sign in with your Ethereum account:
40795
41067
  ${checksummedAddress}
40796
41068
 
@@ -40889,7 +41161,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
40889
41161
  void transport.close().catch(() => void 0);
40890
41162
  return;
40891
41163
  }
40892
- const code = (0, import_node_crypto.randomBytes)(24).toString("hex");
41164
+ const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
40893
41165
  this.codes.set(code, {
40894
41166
  clientId: flow.clientId,
40895
41167
  address: checksummed,
@@ -40956,7 +41228,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
40956
41228
  return { ok: false, status: 401, reason: "the signature does not match the connected wallet address" };
40957
41229
  }
40958
41230
  this.deleteFlow(flowId, flow);
40959
- const code = (0, import_node_crypto.randomBytes)(24).toString("hex");
41231
+ const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
40960
41232
  this.codes.set(code, {
40961
41233
  clientId: flow.clientId,
40962
41234
  address: flow.siwe.address,
@@ -41014,8 +41286,8 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41014
41286
  if (r && r.clientId === client.client_id) this.refresh.delete(request.token);
41015
41287
  }
41016
41288
  mintTokens(address, clientId) {
41017
- const accessToken = (0, import_node_crypto.randomBytes)(32).toString("hex");
41018
- const refreshToken = (0, import_node_crypto.randomBytes)(32).toString("hex");
41289
+ const accessToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41290
+ const refreshToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41019
41291
  this.access.set(accessToken, { address, clientId, expiresAt: Math.floor(this.clock() / 1e3) + ACCESS_TTL_S });
41020
41292
  this.refresh.set(refreshToken, { address, clientId, lastUsed: this.clock() });
41021
41293
  return { access_token: accessToken, token_type: "bearer", expires_in: ACCESS_TTL_S, refresh_token: refreshToken };
@@ -41261,7 +41533,7 @@ var fs6 = __toESM(require("fs"));
41261
41533
  var import_ethers40 = require("ethers");
41262
41534
 
41263
41535
  // src/boundary/index.ts
41264
- var import_node_crypto8 = require("crypto");
41536
+ var import_node_crypto9 = require("crypto");
41265
41537
  var fs5 = __toESM(require("fs"));
41266
41538
  var os2 = __toESM(require("os"));
41267
41539
  var path4 = __toESM(require("path"));
@@ -42285,7 +42557,7 @@ var DEFAULT_SEED = {
42285
42557
  };
42286
42558
 
42287
42559
  // src/boundary/upstream/mock/world.ts
42288
- var import_node_crypto2 = require("crypto");
42560
+ var import_node_crypto3 = require("crypto");
42289
42561
  var import_ethers3 = require("ethers");
42290
42562
 
42291
42563
  // src/signer/safe.ts
@@ -42489,7 +42761,7 @@ var World = class {
42489
42761
  nextId(prefix) {
42490
42762
  this.state.counter += 1;
42491
42763
  const n = this.state.counter;
42492
- const hash = (0, import_node_crypto2.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
42764
+ const hash = (0, import_node_crypto3.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
42493
42765
  return { n, hash };
42494
42766
  }
42495
42767
  nextTxRef() {
@@ -43368,7 +43640,7 @@ var WorldStore = class {
43368
43640
  };
43369
43641
 
43370
43642
  // src/boundary/upstream/mock/signer.ts
43371
- var import_node_crypto3 = require("crypto");
43643
+ var import_node_crypto4 = require("crypto");
43372
43644
  function mockSign(op, borrower, stance) {
43373
43645
  if (stance === "decline") {
43374
43646
  return {
@@ -43383,7 +43655,7 @@ function mockSign(op, borrower, stance) {
43383
43655
  signer: borrower,
43384
43656
  action: op.action,
43385
43657
  card: op.card,
43386
- digest: (0, import_node_crypto3.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
43658
+ digest: (0, import_node_crypto4.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
43387
43659
  }
43388
43660
  };
43389
43661
  }
@@ -44655,7 +44927,7 @@ var MockUpstreamPlugin = class {
44655
44927
  };
44656
44928
 
44657
44929
  // src/boundary/upstream/mock/external-ceremony.ts
44658
- var import_node_crypto4 = require("crypto");
44930
+ var import_node_crypto5 = require("crypto");
44659
44931
  var import_node_child_process = require("child_process");
44660
44932
  var import_ethers10 = require("ethers");
44661
44933
 
@@ -44848,7 +45120,7 @@ var ExternalCeremony = class {
44848
45120
  validateUnsignedTx({ ...p.tx }, p.expected, this.deps.vctx);
44849
45121
  const card = cardForTx(p.tx);
44850
45122
  const outcome = await this.request({
44851
- id: (0, import_node_crypto4.randomUUID)(),
45123
+ id: (0, import_node_crypto5.randomUUID)(),
44852
45124
  kind: "transaction",
44853
45125
  action: p.action,
44854
45126
  card,
@@ -44893,7 +45165,7 @@ var ExternalCeremony = class {
44893
45165
  message
44894
45166
  };
44895
45167
  const outcome = await this.request({
44896
- id: (0, import_node_crypto4.randomUUID)(),
45168
+ id: (0, import_node_crypto5.randomUUID)(),
44897
45169
  kind: "typed-data",
44898
45170
  action: "login",
44899
45171
  card: cardForTypedData("login", typedData),
@@ -44921,7 +45193,7 @@ var ExternalCeremony = class {
44921
45193
  });
44922
45194
  const card = cardForTypedData(p.action, typedData);
44923
45195
  const outcome = await this.request({
44924
- id: (0, import_node_crypto4.randomUUID)(),
45196
+ id: (0, import_node_crypto5.randomUUID)(),
44925
45197
  kind: "typed-data",
44926
45198
  action: p.action,
44927
45199
  card,
@@ -45096,7 +45368,7 @@ var KeystoreCeremony = class {
45096
45368
  };
45097
45369
 
45098
45370
  // src/boundary/upstream/mock/safe-ceremony.ts
45099
- var import_node_crypto5 = require("crypto");
45371
+ var import_node_crypto6 = require("crypto");
45100
45372
  var import_ethers12 = require("ethers");
45101
45373
  init_tx_validator();
45102
45374
 
@@ -45397,7 +45669,7 @@ var SafeCeremony = class {
45397
45669
  const primaryType = Object.keys(build.payload.types)[0];
45398
45670
  const outcome = await bridge.requestSignatureCollection(
45399
45671
  {
45400
- id: (0, import_node_crypto5.randomUUID)(),
45672
+ id: (0, import_node_crypto6.randomUUID)(),
45401
45673
  kind: "typed-data",
45402
45674
  action,
45403
45675
  card: build.card,
@@ -80000,7 +80272,7 @@ var EoaDHSigner = class {
80000
80272
  };
80001
80273
 
80002
80274
  // src/signer/external-eoa.ts
80003
- var import_node_crypto6 = require("crypto");
80275
+ var import_node_crypto7 = require("crypto");
80004
80276
  var import_ethers38 = require("ethers");
80005
80277
 
80006
80278
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
@@ -80094,7 +80366,7 @@ var ExternalEoaDHSigner = class {
80094
80366
  let used = { quantumTs: initialTs, fields: initial.fields };
80095
80367
  const outcome = await this.deps.bridge.requestSignature(
80096
80368
  {
80097
- id: (0, import_node_crypto6.randomUUID)(),
80369
+ id: (0, import_node_crypto7.randomUUID)(),
80098
80370
  kind: "personal-sign",
80099
80371
  action: spec.action,
80100
80372
  card: initial.card,
@@ -80128,7 +80400,7 @@ var ExternalEoaDHSigner = class {
80128
80400
  const approved = toApprovedTx(outerTx, this.deps.chainId);
80129
80401
  const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
80130
80402
  const outcome = await this.deps.bridge.requestSignature({
80131
- id: (0, import_node_crypto6.randomUUID)(),
80403
+ id: (0, import_node_crypto7.randomUUID)(),
80132
80404
  kind: "transaction",
80133
80405
  action: ctx.action,
80134
80406
  card: ctx.card,
@@ -80179,15 +80451,22 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80179
80451
  }
80180
80452
  const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
80181
80453
  const outcome = await this.deps.bridge.requestSignature({
80182
- id: (0, import_node_crypto6.randomUUID)(),
80454
+ id: (0, import_node_crypto7.randomUUID)(),
80183
80455
  kind: "personal-sign",
80184
- action: "btc-withdrawal authorization (blind hash)",
80456
+ action: "btc-withdrawal EXECUTE step (blind hash)",
80185
80457
  card: [
80186
- "BLIND SIGNATURE \u2014 BTC withdrawal authorization step",
80458
+ "BLIND SIGNATURE \u2014 BTC withdrawal, EXECUTE step",
80187
80459
  `hash: ${hashHex}`,
80188
80460
  "This hash is built inside the SDK and its contents CANNOT be decoded or verified by this page",
80189
80461
  "(identical to how diamondhands.credit signs withdrawals).",
80190
- "Approve ONLY if you initiated this exact BTC withdrawal in the conversation."
80462
+ "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80463
+ "",
80464
+ "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
80465
+ `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
80466
+ "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
80467
+ "itself allows. If it expires the signature is refused, the withdrawal does not",
80468
+ "complete, and the reserved coins stay reserved until that is cleared. Decline and",
80469
+ "start again rather than signing something you have not finished reading."
80191
80470
  ],
80192
80471
  expectedSigner: this.deps.borrower,
80193
80472
  chainId: this.deps.chainId,
@@ -80210,7 +80489,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80210
80489
  message: value
80211
80490
  };
80212
80491
  const outcome = await this.deps.bridge.requestSignature({
80213
- id: (0, import_node_crypto6.randomUUID)(),
80492
+ id: (0, import_node_crypto7.randomUUID)(),
80214
80493
  kind: "typed-data",
80215
80494
  action: "login",
80216
80495
  card: cardForTypedData("login", typedData),
@@ -80236,7 +80515,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80236
80515
  const card = cardForTx(approved);
80237
80516
  const gas = tx2.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
80238
80517
  const outcome = await this.deps.bridge.requestSignature({
80239
- id: (0, import_node_crypto6.randomUUID)(),
80518
+ id: (0, import_node_crypto7.randomUUID)(),
80240
80519
  kind: "transaction",
80241
80520
  action: describeFn(approved.data),
80242
80521
  card,
@@ -81120,10 +81399,10 @@ var RealUpstreamPlugin = class {
81120
81399
  // src/boundary/upstream/shared/external-bridge/bridge.ts
81121
81400
  var fs4 = __toESM(require("fs"));
81122
81401
  var http3 = __toESM(require("http"));
81123
- var import_node_crypto7 = require("crypto");
81402
+ var import_node_crypto8 = require("crypto");
81124
81403
 
81125
81404
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
81126
- function renderApprovalPage(sessionId) {
81405
+ function renderApprovalPage(sessionId, nonce) {
81127
81406
  return `<!doctype html>
81128
81407
  <html lang="en">
81129
81408
  <head>
@@ -81173,15 +81452,17 @@ function renderApprovalPage(sessionId) {
81173
81452
  </div>
81174
81453
  </div>
81175
81454
  </main>
81176
- <script>
81455
+ <script nonce="${nonce}">
81177
81456
  ${PAGE_CRYPTO_JS}
81178
81457
  </script>
81179
- <script>
81458
+ <script nonce="${nonce}">
81180
81459
  "use strict";
81181
81460
  const SESSION = ${JSON.stringify(sessionId)};
81182
81461
  // One-time token leaves the address bar (and history) immediately.
81183
81462
  // Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
81184
81463
  // at loopback root ("/") and under a hosted tenant mount ("/approval/<id>/").
81464
+ // EVERY endpoint reference goes through BASE \u2014 an origin-absolute "/x" resolves to the
81465
+ // ORIGIN root, which on a mount is the host, not the bridge, and 404s silently.
81185
81466
  const BASE = location.pathname.replace(/[^/]*$/, "");
81186
81467
  history.replaceState(null, "", location.pathname);
81187
81468
 
@@ -81253,14 +81534,14 @@ async function connect() {
81253
81534
  // wallet's own state transition and can report the stale value.
81254
81535
  async function onAccountsChanged(accounts) {
81255
81536
  account = (accounts && accounts[0]) || null;
81256
- await post("/wallet-event", { account: account, chainId: chainId });
81537
+ await post(BASE + "wallet-event", { account: account, chainId: chainId });
81257
81538
  showWallet();
81258
81539
  clearRequest("Wallet changed \u2014 pending request invalidated.");
81259
81540
  }
81260
81541
 
81261
81542
  async function onChainChanged(cid) {
81262
81543
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81263
- await post("/wallet-event", { account: account, chainId: chainId });
81544
+ await post(BASE + "wallet-event", { account: account, chainId: chainId });
81264
81545
  showWallet();
81265
81546
  clearRequest("Network changed \u2014 pending request invalidated.");
81266
81547
  }
@@ -81368,7 +81649,7 @@ connect();
81368
81649
  </body>
81369
81650
  </html>`;
81370
81651
  }
81371
- function renderUnlockPage(sessionId) {
81652
+ function renderUnlockPage(sessionId, nonce) {
81372
81653
  return `<!doctype html>
81373
81654
  <html lang="en">
81374
81655
  <head>
@@ -81410,7 +81691,7 @@ function renderUnlockPage(sessionId) {
81410
81691
  <div id="status" class="status"></div>
81411
81692
  </div>
81412
81693
  </main>
81413
- <script>
81694
+ <script nonce="${nonce}">
81414
81695
  "use strict";
81415
81696
  const SESSION = ${JSON.stringify(sessionId)};
81416
81697
  // Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
@@ -81468,7 +81749,7 @@ var SignatureBridge = class {
81468
81749
  /** Started state independent of the transport binding (mounted bridges own no server). */
81469
81750
  started = false;
81470
81751
  mount;
81471
- token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81752
+ token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81472
81753
  /** Hosted mounts: when the current page token was minted (rotation basis). */
81473
81754
  tokenMintedAt = 0;
81474
81755
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
@@ -81505,7 +81786,7 @@ var SignatureBridge = class {
81505
81786
  unlockUrl() {
81506
81787
  if (!this.started) throw new Error("bridge is not started");
81507
81788
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
81508
- this.unlockToken = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81789
+ this.unlockToken = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81509
81790
  return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
81510
81791
  }
81511
81792
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
@@ -81546,7 +81827,7 @@ var SignatureBridge = class {
81546
81827
  if (this.mount) {
81547
81828
  const now = this.clock();
81548
81829
  if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
81549
- this.token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81830
+ this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81550
81831
  this.tokenMintedAt = now;
81551
81832
  }
81552
81833
  return `${this.mount.baseUrl}/?t=${this.token}`;
@@ -81762,7 +82043,7 @@ var SignatureBridge = class {
81762
82043
  this.server = null;
81763
82044
  this.started = false;
81764
82045
  this.wallet = null;
81765
- this.token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
82046
+ this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81766
82047
  this.tokenMintedAt = 0;
81767
82048
  if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
81768
82049
  void this.wcTransport?.close().catch(() => void 0);
@@ -81832,10 +82113,11 @@ var SignatureBridge = class {
81832
82113
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
81833
82114
  return;
81834
82115
  }
81835
- const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
82116
+ const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81836
82117
  this.sessions.set(sessionId, { wallet: null, sse: null });
81837
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
81838
- res.end(renderApprovalPage(sessionId));
82118
+ const page = htmlPageSecurityHeaders();
82119
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82120
+ res.end(renderApprovalPage(sessionId, page.nonce));
81839
82121
  }
81840
82122
  /** Target-network hints for the page's chain self-heal (session-gated). */
81841
82123
  serveConfig(url2, res) {
@@ -81895,9 +82177,10 @@ var SignatureBridge = class {
81895
82177
  return;
81896
82178
  }
81897
82179
  this.unlockToken = null;
81898
- this.unlockSession = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81899
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
81900
- res.end(renderUnlockPage(this.unlockSession));
82180
+ this.unlockSession = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82181
+ const page = htmlPageSecurityHeaders();
82182
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82183
+ res.end(renderUnlockPage(this.unlockSession, page.nonce));
81901
82184
  }
81902
82185
  async onUnlockSubmit(body, res) {
81903
82186
  if (!this.keystoreUnlock) {
@@ -82143,7 +82426,7 @@ function createBoundary(config, opts) {
82143
82426
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
82144
82427
  );
82145
82428
  }
82146
- const configFingerprint = (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
82429
+ const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
82147
82430
  if (opts?.ceremony) {
82148
82431
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
82149
82432
  const boundary2 = new BoundaryCore({
@@ -82312,7 +82595,7 @@ async function createRealBoundary(config, wallet, overrides) {
82312
82595
  }
82313
82596
  const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
82314
82597
  await plugin.initWriteSdk();
82315
- const configFingerprint = (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
82598
+ const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
82316
82599
  const capabilities = () => ({
82317
82600
  reads: {
82318
82601
  public: true,
@@ -82412,1239 +82695,406 @@ async function buildBoundary(configResult, overrides) {
82412
82695
  return { boundaryResult: { ok: true, boundary }, signer, dispose };
82413
82696
  }
82414
82697
 
82415
- // src/network-switch.ts
82416
- var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
82417
- function createNetworkSwitchRuntime(opts) {
82418
- return {
82419
- current() {
82420
- const b = opts.getBoot().boundaryResult;
82421
- if (!b.ok) return null;
82422
- const w = b.boundary.world();
82423
- return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
82424
- },
82425
- async switchTo(network) {
82426
- const allowed = opts.overrides?.allowedNetworks;
82427
- if (allowed && !allowed.includes(network)) {
82428
- return {
82429
- ok: false,
82430
- error: boundaryError(
82431
- "VALIDATION_FAILED",
82432
- `this deployment serves ${allowed.join(", ")} \u2014 '${network}' is not enabled on this service. Mainnet service enablement is a rollout step of the deployment, not a session setting.`
82433
- )
82434
- };
82435
- }
82436
- const targetEnv = { ...opts.env, DH_NETWORK: network };
82437
- const configResult = resolveBoundaryConfig(targetEnv);
82438
- if (!configResult.ok) return { ok: false, error: configResult.error };
82439
- const next = await buildBoundary(configResult, opts.overrides);
82440
- if (!next.boundaryResult.ok) {
82441
- next.dispose();
82442
- return { ok: false, error: next.boundaryResult.error };
82443
- }
82444
- opts.swap(next);
82445
- return { ok: true };
82446
- }
82447
- };
82448
- }
82449
- function assembleWorld(opts) {
82450
- let boot = opts.boot;
82451
- const deps = {
82452
- boundaryResult: boot.boundaryResult,
82453
- ...boot.mockControl ? { mockControl: boot.mockControl } : {},
82454
- ...boot.signer ? { signer: boot.signer } : {},
82455
- ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
82456
- ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
82457
- };
82458
- if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
82459
- deps.networkSwitch = createNetworkSwitchRuntime({
82460
- env: opts.env,
82461
- getBoot: () => boot,
82462
- ...opts.overrides ? { overrides: opts.overrides } : {},
82463
- swap: (next) => {
82464
- const old = boot;
82465
- boot = next;
82466
- deps.boundaryResult = next.boundaryResult;
82467
- if (next.signer) deps.signer = next.signer;
82468
- else delete deps.signer;
82469
- old.dispose();
82470
- const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
82471
- opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
82472
- }
82473
- });
82474
- }
82475
- return { deps, dispose: () => boot.dispose() };
82698
+ // src/boundary/field-glossary.ts
82699
+ var FIELD_GLOSSARY = {
82700
+ // ---- identity / envelope structure ----
82701
+ positionId: "the position's 32-byte id (0x\u202664 hex) \u2014 the input every position_* tool takes",
82702
+ borrower: "the Ethereum address that owns the position (the borrowing identity)",
82703
+ vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
82704
+ pkpId: "internal id of the programmable key pair holding BTC custody for this position",
82705
+ id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
82706
+ kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
82707
+ fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
82708
+ // ---- position facts (chain) ----
82709
+ state: "lifecycle state. On position_status it is read from the CHAIN (authoritative); on position_list rows it is an INDEXER snapshot that can lag the chain. PENDING_DEPOSIT/PENDING_MINT mean 'not yet minted' \u2014 activation happens on the FIRST mint, never on deposit confirmation alone",
82710
+ termMonths: "the current term length in months",
82711
+ totalTermMonths: "cumulative months across the original term plus every extension",
82712
+ createdAt: "ISO timestamp the position was created",
82713
+ expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
82714
+ previousExpiryAt: "the expiry before the latest extension (null when never extended)",
82715
+ lastUpdatedAt: "ISO timestamp of the last state change",
82716
+ debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
82717
+ // ---- indexed health (indexer snapshot) ----
82718
+ indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
82719
+ collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
82720
+ healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
82721
+ asOf: "ISO timestamp the indexer snapshot was computed",
82722
+ basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
82723
+ // ---- collateral (live BTC view) ----
82724
+ collateral: "the live Bitcoin-side view of the position's vault",
82725
+ availableSats: "CONFIRMED collateral in satoshis, minus authorized (reserved) spends \u2014 deposits count only once their confirmations reach minConfirmations. null ONLY alongside a SOURCE_DEGRADED warning, never a fabricated zero",
82726
+ availableSource: "which source served availableSats (null when degraded)",
82727
+ pendingDeposits: "the LIVE per-transaction list of unconfirmed deposits \u2014 each entry carries its own confirmations count. EMPTY ARRAY = nothing unconfirmed in flight (not an error). null ONLY with a SOURCE_DEGRADED warning",
82728
+ txid: "Bitcoin transaction id",
82729
+ sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
82730
+ confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
82731
+ minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
82732
+ pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
82733
+ maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
82734
+ // ---- valuation ----
82735
+ valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
82736
+ btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82737
+ priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82738
+ priceSource: "which oracle served the price",
82739
+ collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
82740
+ currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
82741
+ maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
82742
+ liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
82743
+ maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
82744
+ maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
82745
+ liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
82746
+ reading: "conditional reading notes emitted by the server ONLY while a known misreading trap is live \u2014 treat them as authoritative instructions for interpreting this exact payload",
82747
+ // ---- list envelope ----
82748
+ items: "the rows of this page",
82749
+ page: "1-based page number of this response",
82750
+ pageSize: "requested rows per page",
82751
+ total: "total rows matching the filter across all pages",
82752
+ // ---- events ----
82753
+ positionCreated: "creation events (seq, time, selected term)",
82754
+ seq: "the event's sequence number within the position's history (ordering key)",
82755
+ at: "ISO timestamp of the event",
82756
+ selectedTerm: "term length chosen, in months",
82757
+ mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
82758
+ amountUcdWei: "the event's UCD amount in wei",
82759
+ feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
82760
+ payments: "repayment events: when and how much UCD was paid back",
82761
+ type: "the payment's kind label as indexed (e.g. partial/full)",
82762
+ renewals: "extension events: added term, extension fee, and the new expiry",
82763
+ extensionTerm: "months added by this extension",
82764
+ extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
82765
+ newExpiryAt: "the expiry after this extension (ISO)",
82766
+ withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
82767
+ amountSats: "the withdrawal amount in satoshis",
82768
+ networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
82769
+ targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
82770
+ liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
82771
+ other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
82772
+ totalEvents: "total events across all groups",
82773
+ // ---- pending withdrawals ----
82774
+ vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
82775
+ satoshis: "the reserved amount in satoshis",
82776
+ // ---- protocol status / terms ----
82777
+ paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
82778
+ ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
82779
+ btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
82780
+ terms: "the offered term tiers with their fee rates",
82781
+ months: "the tier's term length in months",
82782
+ originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
82783
+ extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
82784
+ // ---- psm quote ----
82785
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
82786
+ contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
82787
+ amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
82788
+ amountInToken: "the token you pay with",
82789
+ amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
82790
+ amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
82791
+ amountOutToken: "the token you receive",
82792
+ amountOutUnit: "the smallest-unit name of amountOut",
82793
+ fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
82794
+ amount: "the amount of the item it sits on, in that item's stated unit/token",
82795
+ token: "the token the amount is denominated in",
82796
+ bps: "the rate in basis points (100 bps = 1%)",
82797
+ reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
82798
+ available: "how much of the reserve is available, in its stated unit",
82799
+ unit: "the smallest-unit name for the amount it sits on",
82800
+ human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
82801
+ executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
82802
+ };
82803
+ function fieldGuide(...fields) {
82804
+ const lines = fields.map((f) => {
82805
+ const meaning = FIELD_GLOSSARY[f];
82806
+ if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
82807
+ return `${f} = ${meaning}`;
82808
+ });
82809
+ return ` Field guide: ${lines.join("; ")}.`;
82476
82810
  }
82811
+ function renderFieldGlossaryTopic() {
82812
+ const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
82813
+ return `# Reading the data \u2014 every field, its exact meaning
82477
82814
 
82478
- // src/server.ts
82479
- var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
82480
-
82481
- // src/tools/loan.ts
82482
- var import_zod = require("zod");
82483
- var import_ethers41 = require("ethers");
82815
+ The payload's fields and notes are AUTHORITATIVE. State what they say; never speculate
82816
+ past them; when the data does not carry something, say "the data does not carry X".
82817
+ Conditional \`reading\` notes in a payload are instructions for interpreting that exact
82818
+ response \u2014 follow them over any prior assumption.
82484
82819
 
82485
- // src/util/format.ts
82486
- function bigintReplacer(_key, value) {
82487
- if (typeof value === "bigint") return value.toString();
82488
- return value;
82489
- }
82490
- function serialize(data) {
82491
- return JSON.stringify(data, bigintReplacer, 2);
82820
+ ${lines.join("\n")}`;
82492
82821
  }
82493
82822
 
82494
- // src/tools/_helpers.ts
82495
- function registerBoundaryTool(server, name, config, handler) {
82496
- server.registerTool(name, config, handler);
82823
+ // src/guide/content.ts
82824
+ var GUIDE_TOPICS = [
82825
+ "getting-started",
82826
+ "first-setup",
82827
+ "connect-wallet",
82828
+ "lifecycle",
82829
+ "fees",
82830
+ "psm",
82831
+ "authorization",
82832
+ "safe",
82833
+ "delegation",
82834
+ "safety",
82835
+ "switch-network",
82836
+ "connector",
82837
+ "troubleshooting",
82838
+ "glossary",
82839
+ "reading-data"
82840
+ ];
82841
+ var GUIDE_SIGNER_MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
82842
+ var EXTERNAL_ONLY_SIGNER_MODES = ["external"];
82843
+ function offers(d, mode) {
82844
+ return d.signerModes.includes(mode);
82497
82845
  }
82498
- function renderError(error) {
82499
- const lines = [`ERROR [${error.code}]: ${error.message}`];
82500
- if (error.source) lines.push(`source: ${error.source}`);
82501
- return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
82846
+ function signerModeSourceClause(d) {
82847
+ return offers(d, "keystore") ? "the set `signer_setup` offers. `boundary://info` reports the NARROWER set the active adapter actually constructs under `capabilities.writes.signerModes` (the real adapter builds `external` + `keystore`; the practice ceremonies are mock-adapter only) \u2014 when the two differ, `boundary://info` is authoritative" : "the same set `signer_setup` offers and `boundary://info` reports under `capabilities.writes.signerModes`";
82502
82848
  }
82503
- function renderEnvelope(env) {
82504
- if (!env.ok) return renderError(env.error);
82505
- const parts = [serialize(env.data)];
82506
- if (env.warnings.length > 0) {
82507
- parts.push(
82508
- "WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
82509
- );
82849
+ var LOCAL_GUIDE_DEPLOYMENT = {
82850
+ tier: "local",
82851
+ networks: ["sepolia", "mainnet"],
82852
+ // A local install constructs the whole signer runtime: the real adapter offers
82853
+ // external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
82854
+ // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
82855
+ // on the real adapter these modes refuse") carry the narrower adapter axis.
82856
+ signerModes: GUIDE_SIGNER_MODES
82857
+ };
82858
+ function servedNetworks(d) {
82859
+ if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
82860
+ const mainnet = d.networks.includes("mainnet");
82861
+ const sepolia = d.networks.includes("sepolia");
82862
+ if (mainnet && sepolia) {
82863
+ return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
82510
82864
  }
82511
- parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
82512
- return { content: [{ type: "text", text: parts.join("\n\n") }] };
82865
+ if (mainnet) {
82866
+ return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing, and PSM swaps are refused on mainnet), and there is no practice network on this deployment to fall back to";
82867
+ }
82868
+ return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
82513
82869
  }
82514
- function validationFailed(problem) {
82515
- return renderError(boundaryError("VALIDATION_FAILED", problem));
82870
+ function connectorStatusTruth(d) {
82871
+ if (d.tier === "hosted") {
82872
+ return `**STATUS TRUTH (say this first when asked):** this session IS the hosted
82873
+ connector \u2014 the user is already on it, so there is nothing to install and no URL to hand
82874
+ out. It serves ${servedNetworks(d)}. State that money reality unprompted, and never
82875
+ promise a network, a tier or a timing this deployment does not already serve.`;
82876
+ }
82877
+ return `**STATUS TRUTH (say this first when asked):** this session is a LOCAL install,
82878
+ not the hosted connector. Whether a public connector URL is being served today is the
82879
+ operator's rollout decision and this build cannot see it \u2014 so never assert that one is
82880
+ available, and never assert that one is not. If the user already has a URL, everything
82881
+ below describes what they get; otherwise the local install paths (\`first-setup\`) are the
82882
+ way in. Never promise availability or timing.`;
82516
82883
  }
82517
- function resourceJson(env) {
82518
- if (!env.ok) return serialize({ error: env.error });
82519
- return serialize({ data: env.data, warnings: env.warnings, source: env.source });
82884
+ function connectorNetworkTruth(d) {
82885
+ if (d.tier === "hosted") {
82886
+ return `And it serves only the networks its deployment is rolled out to \u2014 this one
82887
+ serves ${servedNetworks(d)}. Which networks a deployment is rolled out to is the
82888
+ operator's deploy decision, never a hidden knob \u2014 and it is not a field of
82889
+ \`boundary://info\`, whose capabilities block reports the world THIS session is on right
82890
+ now (network, chainId, practiceWorld) plus the read/write/signer planes. \`network_switch\`
82891
+ is what states the rollout: asked for a network this deployment is not rolled out to, it
82892
+ refuses and names the ones it is.`;
82893
+ }
82894
+ return `And any connector deployment serves only the networks it is rolled out to \u2014
82895
+ which ones is the operator's deploy decision, never a hidden knob. Do not go looking for
82896
+ that list in \`boundary://info\`: its capabilities block reports the world THIS session is
82897
+ on (network, chainId, practiceWorld) plus the read/write/signer planes, never another
82898
+ deployment's rollout. \`network_switch\` is what states it \u2014 asked for a network a
82899
+ deployment is not rolled out to, it refuses and names the ones it is. This local build
82900
+ cannot see another deployment's rollout at all: ask that server, never assume.`;
82520
82901
  }
82521
- function resourceErrorJson(error) {
82522
- return serialize({ error });
82902
+ function connectorInstallNote(d) {
82903
+ if (d.tier === "hosted") {
82904
+ return `(The user is ALREADY on the fourth, zero-install path \u2014 the claude.ai
82905
+ connector \u2014 so none of the above is needed HERE; those paths are for other machines.
82906
+ Truth and trust model: \`guide connector\`.)`;
82907
+ }
82908
+ return `(A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented in this
82909
+ build. Whether it is publicly served today is the operator's rollout decision and this
82910
+ session cannot see it: do not assert either way. Truth and trust model:
82911
+ \`guide connector\`.)`;
82523
82912
  }
82524
- function requireConfirmation(confirmed, actionLabel) {
82525
- if (confirmed === true) return null;
82526
- return {
82527
- content: [
82528
- {
82529
- type: "text",
82530
- text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
82531
- This is an irreversible, fund-moving action. A human must explicitly authorize it.
82532
- Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
82533
- }
82534
- ],
82535
- isError: true
82536
- };
82913
+ function connectorTroubleshootingRow(d) {
82914
+ if (d.tier === "hosted") {
82915
+ return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 that is THIS
82916
+ session. Nothing to install, no URL to look up; it serves ${servedNetworks(d)}. Full
82917
+ truth: \`guide connector\`.`;
82918
+ }
82919
+ return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 this session is
82920
+ a local install, not that tier. Whether a public URL is being served today is the
82921
+ operator's rollout decision and this build cannot see it: do not assert either way. The
82922
+ local install paths work regardless. Full truth: \`guide connector\`.`;
82537
82923
  }
82538
- function envStamp(b) {
82539
- if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
82540
- const w = b.boundary.world();
82541
- const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
82542
- return `environment: ${w.network} \u2014 ${money}`;
82924
+ function approvalPageLocation(d) {
82925
+ if (d.tier === "hosted") {
82926
+ return `its URL is ALSO in the tool result. On this hosted tier the page is served by
82927
+ the connector itself over HTTPS on its own public origin, so ANY browser reaches it,
82928
+ including a phone's. The link carries a one-time session token \u2014 treat it as a secret,
82929
+ never forward it, and check the address bar shows that same origin before connecting a
82930
+ wallet.`;
82931
+ }
82932
+ return `its URL is ALSO in the tool result. On this local install the page is served by
82933
+ the server's own loopback listener (127.0.0.1): it exists only on the machine the
82934
+ server runs on, so open it there \u2014 no other device can reach it.`;
82543
82935
  }
82544
- async function guardedWrite(getB, fn) {
82545
- const result = await guarded(fn);
82546
- const stamp = envStamp(getB());
82547
- const content = result.content.map(
82548
- (c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
82549
-
82550
- ${stamp}` } : c
82551
- );
82552
- return { ...result, content };
82936
+ function switchNetworkHeadline(d) {
82937
+ return d.networks.length > 1 ? "sepolia \u2194 mainnet by conversation (real adapter)" : `${d.networks[0]} ONLY on this deployment (real adapter)`;
82553
82938
  }
82554
- async function guarded(fn) {
82555
- try {
82556
- return await fn();
82557
- } catch (e) {
82558
- return renderError(
82559
- boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
82560
- details: { stack: e.stack }
82561
- })
82562
- );
82563
- }
82939
+ function switchNetworkRules(d) {
82940
+ if (d.networks.length > 1) {
82941
+ return `- \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
82942
+ the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
82943
+ - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
82944
+ A sepolia position does not exist on mainnet and vice versa.
82945
+ - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
82946
+ and every one still requires the user's explicit confirmation plus the signer
82947
+ ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
82948
+ }
82949
+ const only = d.networks[0];
82950
+ const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82951
+ const psm = d.networks.includes("mainnet") ? "The exception is PSM swaps \u2014 the write port refuses them here." : "PSM swaps run here, and are refused on every other network.";
82952
+ return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
82953
+ network this deployment is rolled out to \u2014 every other target is REFUSED with that
82954
+ rollout truth. There is nothing to switch TO here; never offer the user another world.
82955
+ Money reality: ${money}.
82956
+ - State is per-network by construction: positions, vaults, signer bindings and logins
82957
+ belong to ${only} and would not exist anywhere else.
82958
+ - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
82959
+ confirmation plus the signer ceremony.
82960
+ - ${psm}`;
82564
82961
  }
82565
-
82566
- // src/util/validate.ts
82567
- var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
82568
- var SATS_SANITY_CAP = 1e10;
82569
- var UCD_SANITY_CAP = 1e9;
82570
- function checkPositionIdHex(id, label = "Position ID") {
82571
- if (!POSITION_ID_RE.test(id)) {
82572
- return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
82962
+ function wrongNetworkTroubleshootingRow(d) {
82963
+ if (d.networks.length > 1) {
82964
+ return `- **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
82965
+ (human-confirmed card; nothing carries across networks). Mock: the world is pinned by
82966
+ config \u2014 no switch exists there.`;
82573
82967
  }
82574
- return null;
82968
+ return `- **Wrong network / asks for another one** \u2014 this deployment is rolled out to
82969
+ ${d.networks[0]} alone, so \`network_switch\` refuses every other target with that
82970
+ rollout truth. Relay the refusal; do not suggest a world this service does not serve.`;
82575
82971
  }
82576
- function checkUcdAmount(amount, label = "Amount") {
82577
- if (!Number.isFinite(amount) || amount <= 0) {
82578
- return `${label} must be a positive finite number (got ${amount}).`;
82579
- }
82580
- if (amount > UCD_SANITY_CAP) {
82581
- return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
82582
- }
82583
- if (amount > 0 && amount < 1e-6) {
82584
- return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
82585
- }
82586
- const decimals = amount.toString().split(".")[1];
82587
- if (decimals && decimals.length > 6) {
82588
- return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
82972
+ function switchNetworkIndexLine(d) {
82973
+ if (d.networks.length > 1) {
82974
+ return "- switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated";
82589
82975
  }
82590
- return null;
82976
+ const only = d.networks[0];
82977
+ const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82978
+ return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
82591
82979
  }
82592
- function checkSatsAmount(sats, label = "Amount") {
82593
- if (!Number.isInteger(sats) || sats <= 0) {
82594
- return `${label} must be a positive integer (satoshis), got ${sats}.`;
82595
- }
82596
- if (sats > SATS_SANITY_CAP) {
82597
- return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
82598
- }
82599
- return null;
82980
+ function psmAvailabilityNote(d) {
82981
+ if (d.networks.includes("sepolia")) return "";
82982
+ return `**Not executable on this deployment.** The PSM write port refuses on every network
82983
+ but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
82984
+ \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
82985
+ the mechanism, not an offer: say so before a user plans around it.
82986
+
82987
+ `;
82600
82988
  }
82601
- function checkSelectedTerm(months, label = "Term") {
82602
- if (!Number.isInteger(months) || months <= 0) {
82603
- return `${label} must be a positive integer (months), got ${months}.`;
82604
- }
82605
- if (months > 120) {
82606
- return `${label} ${months} months exceeds the 10-year sanity cap.`;
82607
- }
82608
- return null;
82989
+ function authorizationModeBullets(d) {
82990
+ const bullets = [];
82991
+ if (offers(d, "external")) {
82992
+ bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
82993
+ mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
82994
+ is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
82995
+ The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
82996
+ approval page states plainly it CANNOT decode. Never extend the card promise over
82997
+ that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
82998
+ }
82999
+ if (offers(d, "keystore")) {
83000
+ bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
83001
+ Real adapter and mock.`);
83002
+ }
83003
+ if (offers(d, "safe") || offers(d, "safe-module")) {
83004
+ bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
83005
+ refuse with that true reason (their planes ship in their own deliveries).`);
83006
+ }
83007
+ if (offers(d, "mock-simulated")) {
83008
+ bullets.push(` - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).`);
83009
+ }
83010
+ return bullets.join("\n");
83011
+ }
83012
+ function keystoreAbsenceParagraph(d) {
83013
+ if (offers(d, "keystore")) return "";
83014
+ return `
83015
+ **There is no keystore mode on this build.** It is ABSENT, not disabled: the provider
83016
+ is never constructed, so no key material can exist server-side and there is nothing to
83017
+ unlock. "Sign automatically, without popups" is impossible here \u2014 say that true reason
83018
+ instead of describing a keystore, and never ask for a password.
83019
+ `;
83020
+ }
83021
+ function keystoreAbsenceBullet() {
83022
+ return `- **"Sign automatically / no popups" cannot happen here** \u2014 there is no keystore mode
83023
+ on this build. It is ABSENT, not disabled: the provider is never constructed, so no key
83024
+ material can exist server-side and nothing can be unlocked. Give that true reason, and
83025
+ never ask for a password.`;
82609
83026
  }
83027
+ var GUIDE_TOPIC_SOURCES = {
83028
+ "getting-started": `# Diamond Hands \u2014 what this is
82610
83029
 
82611
- // src/tools/loan.ts
82612
- var LATENCY_NOTES = {
82613
- mock: "Instant in this practice world.",
82614
- real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
82615
- };
82616
- var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
82617
- var confirmedSchema = import_zod.z.boolean().optional().describe(
82618
- "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
82619
- );
82620
- var DESTRUCTIVE_WRITE_ANNOTATIONS = {
82621
- readOnlyHint: false,
82622
- destructiveHint: true,
82623
- idempotentHint: false,
82624
- openWorldHint: true
82625
- };
82626
- function registerLoanTools(server, getB, adapter2 = "real") {
82627
- const LATENCY_NOTE = LATENCY_NOTES[adapter2];
82628
- registerBoundaryTool(
82629
- server,
82630
- "loan_create",
82631
- {
82632
- title: "Create a new lending position",
82633
- description: `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82634
- inputSchema: {
82635
- selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
82636
- confirmed: confirmedSchema
82637
- },
82638
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82639
- },
82640
- async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
82641
- const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
82642
- if (gate) return gate;
82643
- const problem = checkSelectedTerm(selectedTerm);
82644
- if (problem) return validationFailed(problem);
82645
- const b = getB();
82646
- if (!b.ok) return renderError(b.error);
82647
- return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
82648
- })
82649
- );
82650
- registerBoundaryTool(
82651
- server,
82652
- "loan_mint",
82653
- {
82654
- title: "Mint UCD against a position",
82655
- description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82656
- inputSchema: {
82657
- positionId: positionIdSchema,
82658
- amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
82659
- confirmed: confirmedSchema
82660
- },
82661
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82662
- },
82663
- async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
82664
- const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
82665
- if (gate) return gate;
82666
- const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
82667
- if (problem) return validationFailed(problem);
82668
- const b = getB();
82669
- if (!b.ok) return renderError(b.error);
82670
- return renderEnvelope(
82671
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
82672
- );
82673
- })
82674
- );
82675
- registerBoundaryTool(
82676
- server,
82677
- "loan_pay",
82678
- {
82679
- title: "Make a UCD payment toward a position's debt",
82680
- description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82681
- inputSchema: {
82682
- positionId: positionIdSchema,
82683
- amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
82684
- repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
82685
- confirmed: confirmedSchema
82686
- },
82687
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82688
- },
82689
- async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
82690
- if (repayAll === true === (amountUcd !== void 0)) {
82691
- return validationFailed("provide exactly one of amountUcd or repayAll: true");
82692
- }
82693
- const gate = requireConfirmation(
82694
- confirmed,
82695
- repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
82696
- );
82697
- if (gate) return gate;
82698
- const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
82699
- if (problem) return validationFailed(problem);
82700
- const b = getB();
82701
- if (!b.ok) return renderError(b.error);
82702
- let amountUcdWei;
82703
- if (repayAll) {
82704
- const detail = await b.boundary.getPosition(positionId);
82705
- if (!detail.ok) return renderError(detail.error);
82706
- if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
82707
- amountUcdWei = detail.data.debtUcdWei;
82708
- } else {
82709
- amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
82710
- }
82711
- return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
82712
- })
82713
- );
82714
- registerBoundaryTool(
82715
- server,
82716
- "loan_extend",
82717
- {
82718
- title: "Extend / renew a position's term",
82719
- description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82720
- inputSchema: {
82721
- positionId: positionIdSchema,
82722
- selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
82723
- confirmed: confirmedSchema
82724
- },
82725
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82726
- },
82727
- async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
82728
- const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
82729
- if (gate) return gate;
82730
- const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
82731
- if (problem) return validationFailed(problem);
82732
- const b = getB();
82733
- if (!b.ok) return renderError(b.error);
82734
- return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
82735
- })
82736
- );
82737
- registerBoundaryTool(
82738
- server,
82739
- "loan_withdraw",
82740
- {
82741
- title: "Withdraw BTC from a position vault",
82742
- description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82743
- inputSchema: {
82744
- positionId: positionIdSchema,
82745
- btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
82746
- amountSats: import_zod.z.number().int().positive().describe(
82747
- "GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. amountSats may be up to the whole available balance (a full sweep leaves 0 sats; anything above available reverts TargetExceedsInputValue). position_status.maxWithdrawableSats is a ready-to-use value that already leaves the default fee aside."
82748
- ),
82749
- networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
82750
- confirmed: confirmedSchema
82751
- },
82752
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82753
- },
82754
- async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
82755
- const gate = requireConfirmation(
82756
- confirmed,
82757
- `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
82758
- );
82759
- if (gate) return gate;
82760
- const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
82761
- if (problem) return validationFailed(problem);
82762
- const b = getB();
82763
- if (!b.ok) return renderError(b.error);
82764
- return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
82765
- })
82766
- );
82767
- registerBoundaryTool(
82768
- server,
82769
- "loan_allowlist_destination",
82770
- {
82771
- title: "Allowlist a BTC withdrawal destination",
82772
- description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
82773
- inputSchema: {
82774
- btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
82775
- confirmed: confirmedSchema
82776
- },
82777
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82778
- },
82779
- async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
82780
- const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
82781
- if (gate) return gate;
82782
- const b = getB();
82783
- if (!b.ok) return renderError(b.error);
82784
- return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
82785
- })
82786
- );
82787
- registerBoundaryTool(
82788
- server,
82789
- "loan_delegation_setup",
82790
- {
82791
- title: "Install delegation on the Safe (one owner ceremony)",
82792
- description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
82793
- inputSchema: {
82794
- btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
82795
- confirmed: confirmedSchema
82796
- },
82797
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82798
- },
82799
- async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
82800
- const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
82801
- if (gate) return gate;
82802
- const b = getB();
82803
- if (!b.ok) return renderError(b.error);
82804
- return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
82805
- })
82806
- );
82807
- registerBoundaryTool(
82808
- server,
82809
- "loan_delegation_grant",
82810
- {
82811
- title: "Grant the agent per-position scopes (owners sign)",
82812
- description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
82813
- inputSchema: {
82814
- positionId: positionIdSchema,
82815
- renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
82816
- repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
82817
- mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
82818
- confirmed: confirmedSchema
82819
- },
82820
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82821
- },
82822
- async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
82823
- const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
82824
- if (gate) return gate;
82825
- const b = getB();
82826
- if (!b.ok) return renderError(b.error);
82827
- return renderEnvelope(
82828
- await b.boundary.delegationGrant({
82829
- positionId,
82830
- renew: renew ?? false,
82831
- repay: repay ?? false,
82832
- mintFloorBps: mintFloorBps ?? null
82833
- })
82834
- );
82835
- })
82836
- );
82837
- registerBoundaryTool(
82838
- server,
82839
- "loan_recover_stale_spend",
82840
- {
82841
- title: "Recover a stale BTC reservation via LIT-attested proof",
82842
- description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
82843
- inputSchema: {
82844
- positionId: positionIdSchema,
82845
- utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
82846
- utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
82847
- invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
82848
- minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
82849
- },
82850
- annotations: {
82851
- readOnlyHint: false,
82852
- destructiveHint: false,
82853
- idempotentHint: true,
82854
- openWorldHint: true
82855
- }
82856
- },
82857
- async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
82858
- const problem = checkPositionIdHex(positionId);
82859
- if (problem) return validationFailed(problem);
82860
- const b = getB();
82861
- if (!b.ok) return renderError(b.error);
82862
- return renderEnvelope(
82863
- await b.boundary.recoverStaleSpend({
82864
- positionId,
82865
- utxoTxid,
82866
- utxoVout,
82867
- invalidatorTxid,
82868
- ...minConfirmations !== void 0 ? { minConfirmations } : {}
82869
- })
82870
- );
82871
- })
82872
- );
82873
- }
83030
+ Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
83031
+ without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
83032
+ against it, pay it back whenever you like, and take your BTC out again.
82874
83033
 
82875
- // src/tools/position.ts
82876
- var import_zod2 = require("zod");
83034
+ **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
83035
+ topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
83036
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
83037
+ are enabled (and the true reason when not), and which signer modes this build offers;
83038
+ never promise a capability it does not list. The money truth has THREE cases:
83039
+ - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
83040
+ - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
83041
+ the test network: real ceremonies and signatures, PRACTICE money (test funds).
83042
+ - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
83043
+ explicitly arms them; the capabilities block states which applies.
83044
+ SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
82877
83045
 
82878
- // src/boundary/field-glossary.ts
82879
- var FIELD_GLOSSARY = {
82880
- // ---- identity / envelope structure ----
82881
- positionId: "the position's 32-byte id (0x\u202664 hex) \u2014 the input every position_* tool takes",
82882
- borrower: "the Ethereum address that owns the position (the borrowing identity)",
82883
- vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
82884
- pkpId: "internal id of the programmable key pair holding BTC custody for this position",
82885
- id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
82886
- kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
82887
- fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
82888
- // ---- position facts (chain) ----
82889
- state: "lifecycle state. On position_status it is read from the CHAIN (authoritative); on position_list rows it is an INDEXER snapshot that can lag the chain. PENDING_DEPOSIT/PENDING_MINT mean 'not yet minted' \u2014 activation happens on the FIRST mint, never on deposit confirmation alone",
82890
- termMonths: "the current term length in months",
82891
- totalTermMonths: "cumulative months across the original term plus every extension",
82892
- createdAt: "ISO timestamp the position was created",
82893
- expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
82894
- previousExpiryAt: "the expiry before the latest extension (null when never extended)",
82895
- lastUpdatedAt: "ISO timestamp of the last state change",
82896
- debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
82897
- // ---- indexed health (indexer snapshot) ----
82898
- indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
82899
- collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
82900
- healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
82901
- asOf: "ISO timestamp the indexer snapshot was computed",
82902
- basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
82903
- // ---- collateral (live BTC view) ----
82904
- collateral: "the live Bitcoin-side view of the position's vault",
82905
- availableSats: "CONFIRMED collateral in satoshis, minus authorized (reserved) spends \u2014 deposits count only once their confirmations reach minConfirmations. null ONLY alongside a SOURCE_DEGRADED warning, never a fabricated zero",
82906
- availableSource: "which source served availableSats (null when degraded)",
82907
- pendingDeposits: "the LIVE per-transaction list of unconfirmed deposits \u2014 each entry carries its own confirmations count. EMPTY ARRAY = nothing unconfirmed in flight (not an error). null ONLY with a SOURCE_DEGRADED warning",
82908
- txid: "Bitcoin transaction id",
82909
- sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
82910
- confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
82911
- minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
82912
- pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
82913
- maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
82914
- // ---- valuation ----
82915
- valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
82916
- btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82917
- priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82918
- priceSource: "which oracle served the price",
82919
- collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
82920
- currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
82921
- maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
82922
- liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
82923
- maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
82924
- maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
82925
- liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
82926
- reading: "conditional reading notes emitted by the server ONLY while a known misreading trap is live \u2014 treat them as authoritative instructions for interpreting this exact payload",
82927
- // ---- list envelope ----
82928
- items: "the rows of this page",
82929
- page: "1-based page number of this response",
82930
- pageSize: "requested rows per page",
82931
- total: "total rows matching the filter across all pages",
82932
- // ---- events ----
82933
- positionCreated: "creation events (seq, time, selected term)",
82934
- seq: "the event's sequence number within the position's history (ordering key)",
82935
- at: "ISO timestamp of the event",
82936
- selectedTerm: "term length chosen, in months",
82937
- mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
82938
- amountUcdWei: "the event's UCD amount in wei",
82939
- feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
82940
- payments: "repayment events: when and how much UCD was paid back",
82941
- type: "the payment's kind label as indexed (e.g. partial/full)",
82942
- renewals: "extension events: added term, extension fee, and the new expiry",
82943
- extensionTerm: "months added by this extension",
82944
- extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
82945
- newExpiryAt: "the expiry after this extension (ISO)",
82946
- withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
82947
- amountSats: "the withdrawal amount in satoshis",
82948
- networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
82949
- targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
82950
- liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
82951
- other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
82952
- totalEvents: "total events across all groups",
82953
- // ---- pending withdrawals ----
82954
- vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
82955
- satoshis: "the reserved amount in satoshis",
82956
- // ---- protocol status / terms ----
82957
- paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
82958
- ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
82959
- btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
82960
- terms: "the offered term tiers with their fee rates",
82961
- months: "the tier's term length in months",
82962
- originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
82963
- extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
82964
- // ---- psm quote ----
82965
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
82966
- contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
82967
- amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
82968
- amountInToken: "the token you pay with",
82969
- amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
82970
- amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
82971
- amountOutToken: "the token you receive",
82972
- amountOutUnit: "the smallest-unit name of amountOut",
82973
- fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
82974
- amount: "the amount of the item it sits on, in that item's stated unit/token",
82975
- token: "the token the amount is denominated in",
82976
- bps: "the rate in basis points (100 bps = 1%)",
82977
- reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
82978
- available: "how much of the reserve is available, in its stated unit",
82979
- unit: "the smallest-unit name for the amount it sits on",
82980
- human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
82981
- executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
82982
- };
82983
- function fieldGuide(...fields) {
82984
- const lines = fields.map((f) => {
82985
- const meaning = FIELD_GLOSSARY[f];
82986
- if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
82987
- return `${f} = ${meaning}`;
82988
- });
82989
- return ` Field guide: ${lines.join("; ")}.`;
82990
- }
82991
- function renderFieldGlossaryTopic() {
82992
- const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
82993
- return `# Reading the data \u2014 every field, its exact meaning
83046
+ A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
83047
+ authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
83048
+ calls. Every operation that moves funds requires the user's explicit confirmation
83049
+ (\`confirmed: true\`) \u2014 nothing is ever silent.`,
83050
+ "first-setup": (d) => `# First setup \u2014 from zero to ready, by conversation only
82994
83051
 
82995
- The payload's fields and notes are AUTHORITATIVE. State what they say; never speculate
82996
- past them; when the data does not carry something, say "the data does not carry X".
82997
- Conditional \`reading\` notes in a payload are instructions for interpreting that exact
82998
- response \u2014 follow them over any prior assumption.
83052
+ Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
83053
+ \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
83054
+ host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
83055
+ developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
83056
+ install matrix. ${connectorInstallNote(d)}
82999
83057
 
83000
- ${lines.join("\n")}`;
83001
- }
83058
+ Nothing needs a config file. Three steps:
83002
83059
 
83003
- // src/tools/position.ts
83004
- var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
83005
- var POSITION_STATES = [
83006
- "PENDING_DEPOSIT",
83007
- "PENDING_MINT",
83008
- "ACTIVE",
83009
- "EXPIRED",
83010
- "LIQUIDATABLE",
83011
- "LIQUIDATED",
83012
- "REPAID",
83013
- "CLOSED"
83014
- ];
83015
- function registerPositionTools(server, getB) {
83016
- registerBoundaryTool(
83017
- server,
83018
- "position_status",
83019
- {
83020
- title: "Get a position's full status",
83021
- description: "Return detailed status for a single position: chain facts (debt, term, expiry, state), live collateral (confirmed sats + per-transaction pending deposits, plus maxWithdrawableSats \u2014 directly usable as a withdrawal amountSats), and a basis-carrying valuation (maxMintableUcd is directly usable as amountUcd). If a withdrawal reservation was already spent on Bitcoin but availableSats still shows it deducted, run loan_recover_stale_spend to release the redundant hold. Any `reading` notes in the result are authoritative interpretation instructions for that exact payload \u2014 follow them." + fieldGuide("state", "availableSats", "minConfirmations", "pendingDeposits", "maxWithdrawableSats", "maxMintableUcd", "debtUcdWei"),
83022
- inputSchema: {
83023
- id: positionIdSchema2
83024
- }
83025
- },
83026
- async ({ id }) => guarded(async () => {
83027
- const problem = checkPositionIdHex(id);
83028
- if (problem) return validationFailed(problem);
83029
- const b = getB();
83030
- if (!b.ok) return renderError(b.error);
83031
- return renderEnvelope(await b.boundary.getPosition(id));
83032
- })
83033
- );
83034
- registerBoundaryTool(
83035
- server,
83036
- "position_list",
83037
- {
83038
- title: "List lending positions",
83039
- description: "List positions with optional filters. `borrower` and `state` COMBINE (logical AND); with no filter, returns active positions. Rows are the INDEXER's view \u2014 `state` here is an indexer snapshot that can lag the chain; position_status reads the chain and is authoritative for one position." + fieldGuide("state", "debtUcdWei", "indexedHealth"),
83040
- inputSchema: {
83041
- borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
83042
- state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
83043
- page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
83044
- pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
83045
- }
83046
- },
83047
- async ({ borrower, state, page, pageSize }) => guarded(async () => {
83048
- if (state !== void 0 && !POSITION_STATES.includes(state)) {
83049
- return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
83050
- }
83051
- const b = getB();
83052
- if (!b.ok) return renderError(b.error);
83053
- const filter2 = {
83054
- page,
83055
- pageSize,
83056
- ...borrower !== void 0 ? { borrower } : {},
83057
- ...state !== void 0 ? { state } : {}
83058
- };
83059
- if (filter2.borrower === void 0 && filter2.state === void 0) {
83060
- return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
83061
- }
83062
- return renderEnvelope(await b.boundary.listPositions(filter2));
83063
- })
83064
- );
83065
- registerBoundaryTool(
83066
- server,
83067
- "position_events",
83068
- {
83069
- title: "Get a position's event history",
83070
- description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
83071
- inputSchema: {
83072
- id: positionIdSchema2
83073
- }
83074
- },
83075
- async ({ id }) => guarded(async () => {
83076
- const problem = checkPositionIdHex(id);
83077
- if (problem) return validationFailed(problem);
83078
- const b = getB();
83079
- if (!b.ok) return renderError(b.error);
83080
- return renderEnvelope(await b.boundary.getPositionEvents(id));
83081
- })
83082
- );
83083
- registerBoundaryTool(
83084
- server,
83085
- "position_pending_withdrawals",
83086
- {
83087
- title: "List a position's pending BTC withdrawal reservations",
83088
- description: "Query the spend authorizer for BTC withdrawal reservations on a position. Each entry has txid/vout, satoshis, and target address (txid/vout feed recovery).",
83089
- inputSchema: {
83090
- id: positionIdSchema2
83091
- }
83092
- },
83093
- async ({ id }) => guarded(async () => {
83094
- const problem = checkPositionIdHex(id);
83095
- if (problem) return validationFailed(problem);
83096
- const b = getB();
83097
- if (!b.ok) return renderError(b.error);
83098
- return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
83099
- })
83100
- );
83101
- }
83060
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83061
+ \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83062
+ (practice money) or mainnet (real money); whether writes are enabled here and which
83063
+ signer modes exist; current terms (\`protocol_terms\`).
83102
83064
 
83103
- // src/tools/btc.ts
83104
- var import_zod3 = require("zod");
83105
- function registerBtcTools(server, getB) {
83106
- registerBoundaryTool(
83107
- server,
83108
- "btc_balance",
83109
- {
83110
- title: "Get BTC balance for an address",
83111
- description: "Query the confirmed BTC balance for an address (source-tagged).",
83112
- inputSchema: {
83113
- address: import_zod3.z.string().min(1).describe("BTC address to query")
83114
- }
83115
- },
83116
- async ({ address }) => guarded(async () => {
83117
- const b = getB();
83118
- if (!b.ok) return renderError(b.error);
83119
- return renderEnvelope(await b.boundary.getBitcoinBalance(address));
83120
- })
83121
- );
83122
- registerBoundaryTool(
83123
- server,
83124
- "btc_price",
83125
- {
83126
- title: "Get the current BTC price",
83127
- description: "Return the current BTC price (USD, 8 decimals) from the price oracle.",
83128
- inputSchema: {}
83129
- },
83130
- async () => guarded(async () => {
83131
- const b = getB();
83132
- if (!b.ok) return renderError(b.error);
83133
- return renderEnvelope(await b.boundary.getBitcoinPrice());
83134
- })
83135
- );
83136
- }
83065
+ **2. Choose HOW to authorize operations** (the user's choice, made by talking):
83066
+ - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
83067
+ on the real adapter and the mock. The approval page auto-opens in the browser (its URL
83068
+ is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
83069
+ / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
83070
+ their own wallet. The first verified signature binds their wallet address as the
83071
+ borrower. Full walkthrough: \`guide connect-wallet\`.
83072
+ ${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
83073
+ signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
83074
+ \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
83075
+ LOCAL PAGE opens where the user types the password or generates a fresh keystore.
83076
+ NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
83077
+ them to use the unlock page instead.` : keystoreAbsenceBullet()}
83078
+ ${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
83079
+ real adapter they refuse with that true reason. Try them in a mock world.` : `- **Safe / delegation borrowing is not offered by this build** \u2014 its authorization
83080
+ surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
83081
+ \`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
83082
+ - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
83083
+ - **No signer is also a valid start:** every public read works without one \u2014
83084
+ \`position_list {borrower}\` with the user's address needs no signer and no login.
83085
+ ${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
83086
+ talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
83087
+ the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
83088
+ \`network_switch\` refuses every other target with that rollout truth. See
83089
+ \`guide switch-network\`; never offer a world this service does not serve.`}
83137
83090
 
83138
- // src/tools/protocol.ts
83139
- function registerProtocolTools(server, getB) {
83140
- registerBoundaryTool(
83141
- server,
83142
- "protocol_status",
83143
- {
83144
- title: "Get protocol configuration and status",
83145
- description: "Return protocol status: pause flag, mint LTV limit (ltvBps), liquidation threshold (liquidationThresholdBps \u2014 a COLLATERAL RATIO in bps, i.e. collateralValue/debt, so 11000 = 110%; note this is the inverse basis of ltvBps which is debt/collateral), deposit confirmation threshold, BTC network.",
83146
- inputSchema: {}
83147
- },
83148
- async () => guarded(async () => {
83149
- const b = getB();
83150
- if (!b.ok) return renderError(b.error);
83151
- return renderEnvelope(await b.boundary.getProtocolStatus());
83152
- })
83153
- );
83154
- registerBoundaryTool(
83155
- server,
83156
- "protocol_terms",
83157
- {
83158
- title: "List available loan terms with fees",
83159
- description: "Return all configured loan terms (in months) with their fees. Term length: 12 months = exactly 365 days; any other term = N \xD7 30-day months. originationFeeBps: % of a mint, ADDED to debt. extensionFeeRateBps: the renewal fee CEILING as % of outstanding debt PER RENEWAL (a flat rate, NOT per month); the charged fee is ADDED TO DEBT and reduced by origination fees already paid this term.",
83160
- inputSchema: {}
83161
- },
83162
- async () => guarded(async () => {
83163
- const b = getB();
83164
- if (!b.ok) return renderError(b.error);
83165
- return renderEnvelope(await b.boundary.getTerms());
83166
- })
83167
- );
83168
- }
83169
-
83170
- // src/tools/psm.ts
83171
- var import_zod4 = require("zod");
83172
- var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
83173
- "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
83174
- );
83175
- var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
83176
- readOnlyHint: false,
83177
- destructiveHint: true,
83178
- idempotentHint: false,
83179
- openWorldHint: true
83180
- };
83181
- function registerPsmTools(server, getB) {
83182
- registerBoundaryTool(
83183
- server,
83184
- "psm_quote",
83185
- {
83186
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
83187
- description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
83188
- inputSchema: {
83189
- direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = get UCD for USDC (contract swap); 'to-usdc' = get USDC back for UCD (contract redeem)"),
83190
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
83191
- },
83192
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
83193
- },
83194
- async ({ direction, amount }) => guarded(async () => {
83195
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
83196
- const problem = checkUcdAmount(amount, label);
83197
- if (problem) return validationFailed(problem);
83198
- const b = getB();
83199
- if (!b.ok) return renderError(b.error);
83200
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
83201
- })
83202
- );
83203
- registerBoundaryTool(
83204
- server,
83205
- "psm_swap",
83206
- {
83207
- title: "Exchange UCD \u2194 USDC through the PSM",
83208
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
83209
- inputSchema: {
83210
- direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = pay USDC, get UCD (contract swap); 'to-usdc' = pay UCD, get USDC back (contract redeem)"),
83211
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
83212
- confirmed: confirmedSchema2
83213
- },
83214
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
83215
- },
83216
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
83217
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
83218
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
83219
- const gate = requireConfirmation(
83220
- confirmed,
83221
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
83222
- );
83223
- if (gate) return gate;
83224
- const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
83225
- if (problem) return validationFailed(problem);
83226
- const b = getB();
83227
- if (!b.ok) return renderError(b.error);
83228
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
83229
- })
83230
- );
83231
- }
83232
-
83233
- // src/tools/mock-control.ts
83234
- var import_zod5 = require("zod");
83235
- var ACTIONS = [
83236
- "submit-deposit",
83237
- "confirm-deposit",
83238
- "confirm-spend-consumed",
83239
- "advance-time",
83240
- "set-btc-price",
83241
- "set-paused",
83242
- "set-wallet",
83243
- "liquidate",
83244
- "deploy-safe",
83245
- "revoke-agent",
83246
- "inject-fault",
83247
- "clear-fault",
83248
- "psm-set-paused",
83249
- "psm-set-redeem-enabled",
83250
- "psm-set-reserves",
83251
- "psm-set-fees",
83252
- "psm-mint-usdc"
83253
- ];
83254
- function requireField(value, name, action) {
83255
- if (value === void 0) {
83256
- throw new Error(`action '${action}' requires '${name}'`);
83257
- }
83258
- return value;
83259
- }
83260
- function run(control, a, chainId) {
83261
- switch (a.action) {
83262
- case "submit-deposit": {
83263
- const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
83264
- return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
83265
- }
83266
- case "confirm-deposit": {
83267
- const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
83268
- return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
83269
- }
83270
- case "confirm-spend-consumed": {
83271
- control.confirmSpendConsumed(
83272
- requireField(a.txid, "txid", a.action),
83273
- requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
83274
- requireField(a.confirmations, "confirmations", a.action)
83275
- );
83276
- return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
83277
- }
83278
- case "advance-time": {
83279
- control.advanceTime(requireField(a.seconds, "seconds", a.action));
83280
- return { simulated: "virtual clock advanced", seconds: a.seconds };
83281
- }
83282
- case "set-btc-price": {
83283
- control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
83284
- return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
83285
- }
83286
- case "set-paused": {
83287
- control.setPaused(requireField(a.paused, "paused", a.action));
83288
- return { simulated: "protocol pause flag set", paused: a.paused };
83289
- }
83290
- case "set-wallet": {
83291
- control.setWalletStance(requireField(a.stance, "stance", a.action));
83292
- return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
83293
- }
83294
- case "liquidate": {
83295
- control.liquidate(requireField(a.positionId, "positionId", a.action));
83296
- return { simulated: "liquidation executed", positionId: a.positionId };
83297
- }
83298
- case "deploy-safe": {
83299
- const safe = control.deploySafe({
83300
- owners: requireField(a.owners, "owners", a.action),
83301
- threshold: requireField(a.threshold, "threshold", a.action),
83302
- chainId
83303
- });
83304
- return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
83305
- }
83306
- case "revoke-agent": {
83307
- const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
83308
- return {
83309
- simulated: "agent revoked and BURNED forever (AR-1 \u2014 plan 09 test lever; on the real protocol the owners or the deny-only registrar revoke)",
83310
- ...r
83311
- };
83312
- }
83313
- case "inject-fault": {
83314
- control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
83315
- return { simulated: "fault armed", faultKey: a.faultKey };
83316
- }
83317
- case "clear-fault": {
83318
- control.clearFault(requireField(a.faultKey, "faultKey", a.action));
83319
- return { simulated: "fault cleared", faultKey: a.faultKey };
83320
- }
83321
- case "psm-set-paused": {
83322
- control.psmSetPaused(requireField(a.paused, "paused", a.action));
83323
- return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
83324
- }
83325
- case "psm-set-redeem-enabled": {
83326
- control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
83327
- return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
83328
- }
83329
- case "psm-set-reserves": {
83330
- control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
83331
- return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
83332
- }
83333
- case "psm-mint-usdc": {
83334
- const r = control.psmMintUsdc(
83335
- requireField(a.holder, "holder", a.action),
83336
- requireField(a.usdcUnits, "usdcUnits", a.action)
83337
- );
83338
- return {
83339
- simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
83340
- holder: a.holder,
83341
- minted: a.usdcUnits,
83342
- newBalanceUnits: r.newBalanceUnits
83343
- };
83344
- }
83345
- case "psm-set-fees": {
83346
- control.psmSetFees({
83347
- ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
83348
- ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
83349
- });
83350
- return {
83351
- simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
83352
- ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
83353
- ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
83354
- };
83355
- }
83356
- }
83357
- }
83358
- function registerMockControlTool(server, control, chainId = 1337) {
83359
- registerBoundaryTool(
83360
- server,
83361
- "mock_control",
83362
- {
83363
- title: "SIMULATOR control (mock world only)",
83364
- description: "Drive the simulated rest-of-the-world of the MOCK protocol: broadcast/confirm BTC deposits, confirm reserved spends, advance the virtual clock, set the oracle price, pause the protocol, liquidate, arm/clear faults, and drive the simulated PSM (pause, redeemEnabled, reserves, fees, practice-USDC mint). This tool exists ONLY against the mock adapter \u2014 nothing here touches or ever exists on the real protocol.",
83365
- inputSchema: {
83366
- action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
83367
- positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
83368
- txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
83369
- sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
83370
- confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
83371
- invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
83372
- seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
83373
- priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
83374
- paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
83375
- stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
83376
- owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
83377
- threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
83378
- safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
83379
- faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
83380
- faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
83381
- enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
83382
- reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
83383
- entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
83384
- exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
83385
- holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
83386
- usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
83387
- },
83388
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
83389
- },
83390
- async (args) => guarded(async () => {
83391
- let result;
83392
- try {
83393
- result = run(control, args, chainId);
83394
- } catch (e) {
83395
- return validationFailed(e.message);
83396
- }
83397
- if (result === void 0) {
83398
- return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
83399
- }
83400
- return { content: [{ type: "text", text: serialize(result) }] };
83401
- })
83402
- );
83403
- }
83404
-
83405
- // src/tools/signer.ts
83406
- var import_zod6 = require("zod");
83407
- var import_ethers42 = require("ethers");
83408
- var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
83409
- var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
83410
- var EXTERNAL_ONLY_MODES = ["external"];
83411
- var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
83412
- function looksSecretShaped(value) {
83413
- return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
83414
- }
83415
- var SECRET_REFUSAL = "That value looks like a password or key. NEVER paste secrets into the conversation \u2014 they would enter the model context and transcripts. To provide keystore material, say 'unlock my keystore' (a secure local page opens and the password goes directly to the server), or set DH_KEYSTORE_PATH/DH_KEYSTORE_PASSWORD in the server environment.";
83416
- function registerSignerTool(server, getRuntime, opts) {
83417
- const externalOnly = opts?.externalOnly === true;
83418
- const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
83419
- const description = externalOnly ? "Inspect or manage how operations are authorized. This build is EXTERNAL-WALLET-ONLY: every operation is approved in YOUR OWN wallet (browser wallet, or mobile via WalletConnect); the server can never sign by itself. Actions: 'status' (what is active, what is connected \u2014 start here), 'use' (mode 'external' \u2014 the only mode this build offers), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'connect' (run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out: the FULL wallet flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect." : "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat), 'connect' (external mode, real protocol: run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out of the external wallet: the FULL flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect.";
83420
- registerBoundaryTool(
83421
- server,
83422
- "signer_setup",
83423
- {
83424
- title: "Choose how operations are authorized",
83425
- description,
83426
- inputSchema: {
83427
- action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
83428
- mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
83429
- ...externalOnly ? {} : {
83430
- safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
83431
- }
83432
- },
83433
- annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
83434
- },
83435
- async ({ action, mode, safeAddress }) => guarded(async () => {
83436
- const runtime = getRuntime();
83437
- if (!runtime) {
83438
- return renderError(
83439
- boundaryError(
83440
- "SIGNER_UNAVAILABLE",
83441
- "no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
83442
- )
83443
- );
83444
- }
83445
- const { manager, bridge } = runtime;
83446
- if (mode !== void 0 && !offeredModes.includes(mode)) {
83447
- return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
83448
- }
83449
- if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
83450
- return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
83451
- }
83452
- if (action === "status") {
83453
- await bridge.start();
83454
- const s = manager.status();
83455
- return ok({
83456
- ...s,
83457
- // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
83458
- // identity is known. borrower = a persisted binding; candidate = a live
83459
- // wallet connection in THIS process only.
83460
- identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
83461
- approvalPageUrl: bridge.url(),
83462
- hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
83463
- });
83464
- }
83465
- if (action === "use") {
83466
- if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
83467
- const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
83468
- if (!r.ok) return validationFailed(r.reason);
83469
- if (mode === "safe-module") {
83470
- const s = manager.status();
83471
- return ok({
83472
- mode,
83473
- safe: s.safe,
83474
- agent: s.keystoreAddress,
83475
- next: "This session operates AS the Safe with DELEGATION: the keystore key is the AGENT. One owner ceremony installs it (loan_delegation_setup \u2014 enables the module, binds the agent, pre-approves BTC destinations); afterwards create/mint/pay/extend run agent-solo (per-position grants via loan_delegation_grant, a quorum signature). The agent can NEVER withdraw alone, add destinations, or manage the module \u2014 withdrawals still gather the owners for a short signing burst. See guide topic 'delegation'."
83476
- });
83477
- }
83478
- if (mode === "safe") {
83479
- const s = manager.status();
83480
- return ok({
83481
- mode,
83482
- safe: s.safe,
83483
- next: "This session now operates AS the Safe. Operations are authorized by owner signatures (this phase: the local keystore owner signs; it also submits transactions). BTC withdrawals additionally need the destination allowlisted first \u2014 see loan_allowlist_destination."
83484
- });
83485
- }
83486
- if (mode === "external") {
83487
- await bridge.start();
83488
- return ok({
83489
- mode,
83490
- approvalPageUrl: bridge.url(),
83491
- next: "Open the approval page and connect your wallet (browser extension, or 'Use a mobile wallet' for WalletConnect). Each operation will then ask for your approval there."
83492
- });
83493
- }
83494
- return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
83495
- }
83496
- if (action === "connect") {
83497
- if (!runtime.connect) {
83498
- return validationFailed(
83499
- "action 'connect' applies to the real protocol's external mode (lit-ops login). This adapter has no separate login step \u2014 pick a mode with 'use' and writes will ceremony as needed."
83500
- );
83501
- }
83502
- const r = await runtime.connect();
83503
- if (!r.ok) return validationFailed(r.reason);
83504
- const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
83505
- return ok({
83506
- connected: true,
83507
- address: r.address,
83508
- login,
83509
- next: (login === "cached-session" ? "Logged in via a still-valid CACHED session \u2014 no wallet signature was requested. To force a full logout first, use 'disconnect'. " : "Logged in with a FRESH wallet signature. ") + "Authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
83510
- });
83511
- }
83512
- if (action === "disconnect") {
83513
- if (!runtime.disconnect) {
83514
- return validationFailed(
83515
- "this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
83516
- );
83517
- }
83518
- const report = await runtime.disconnect();
83519
- const f = report.flushed;
83520
- const tokenLine = !report.hadLogin ? "login token: none existed" : f.upstreamRevoked >= f.loginSessions ? `login token: discarded from memory AND revoked at the service (${f.upstreamRevoked} revoked)` : `login token: discarded from this process's memory; ${f.upstreamRevoked}/${f.loginSessions} could be revoked at the service \u2014 an unrevoked token stays valid upstream until its natural expiry (it was never stored on disk)`;
83521
- return ok({
83522
- disconnected: true,
83523
- mode: manager.mode(),
83524
- flushed: {
83525
- ...f,
83526
- note: tokenLine
83527
- },
83528
- whatThisServerCannotRevoke: "Your wallet's own site permission for the approval-page origin \u2014 revoke it wallet-side (MetaMask: Settings \u2192 Connections / Connected sites \u2192 remove this site).",
83529
- // Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
83530
- // relationship; the OAuth session is a separate thing with its own revocation.
83531
- // Neither claims to do the other's job.
83532
- ...bridge.isHosted() ? {
83533
- oauthSession: "This disconnect ends the WALLET relationship only. Your assistant's connection to this MCP server (the OAuth session) stays alive until you revoke it on the claude.ai side (connector settings) \u2014 and revoking THAT does not disconnect your wallet here."
83534
- } : {},
83535
- next: `Wallet disconnected \u2014 mode stays '${manager.mode()}'. Reconnecting requires opening the approval page again (signer_setup 'status' shows the link) and a fresh wallet signature ('connect').`
83536
- });
83537
- }
83538
- if (action === "reset-borrower") {
83539
- manager.resetBorrower();
83540
- return ok({
83541
- reset: true,
83542
- next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower. NOTE: this is an identity swap, NOT a disconnect \u2014 any wallet connection and login session remain alive; use 'disconnect' to log out fully."
83543
- });
83544
- }
83545
- await bridge.start();
83546
- const unlockUrl = bridge.unlockUrl();
83547
- return ok({
83548
- unlockPageUrl: unlockUrl,
83549
- next: "Open this local page and enter the keystore password THERE (never in chat). Paste an encrypted keystore JSON or generate a fresh one, then say 'use keystore'."
83550
- });
83551
- })
83552
- );
83553
- }
83554
- function ok(data) {
83555
- return { content: [{ type: "text", text: serialize(data) }] };
83556
- }
83557
-
83558
- // src/tools/guide.ts
83559
- var import_zod7 = require("zod");
83560
-
83561
- // src/guide/content.ts
83562
- var GUIDE_TOPICS = [
83563
- "getting-started",
83564
- "first-setup",
83565
- "connect-wallet",
83566
- "lifecycle",
83567
- "fees",
83568
- "psm",
83569
- "authorization",
83570
- "safe",
83571
- "delegation",
83572
- "safety",
83573
- "switch-network",
83574
- "connector",
83575
- "troubleshooting",
83576
- "glossary",
83577
- "reading-data"
83578
- ];
83579
- var GUIDE_CONTENT = {
83580
- "getting-started": `# Diamond Hands \u2014 what this is
83581
-
83582
- Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
83583
- without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
83584
- against it, pay it back whenever you like, and take your BTC out again.
83585
-
83586
- **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
83587
- topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
83588
- \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
83589
- are enabled (and the true reason when not), and which signer modes this build offers;
83590
- never promise a capability it does not list. The money truth has THREE cases:
83591
- - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
83592
- - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
83593
- the test network: real ceremonies and signatures, PRACTICE money (test funds).
83594
- - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
83595
- explicitly arms them; the capabilities block states which applies.
83596
- SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
83597
-
83598
- A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
83599
- authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
83600
- calls. Every operation that moves funds requires the user's explicit confirmation
83601
- (\`confirmed: true\`) \u2014 nothing is ever silent.`,
83602
- "first-setup": `# First setup \u2014 from zero to ready, by conversation only
83603
-
83604
- Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
83605
- \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
83606
- host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
83607
- developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
83608
- install matrix. (A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented
83609
- but NOT yet publicly served; its rollout is operator-gated. Truth and trust model:
83610
- \`guide connector\`.)
83611
-
83612
- Nothing needs a config file. Three steps:
83613
-
83614
- **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83615
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83616
- (practice money) or mainnet (real money); whether writes are enabled here and which
83617
- signer modes exist; current terms (\`protocol_terms\`).
83618
-
83619
- **2. Choose HOW to authorize operations** (the user's choice, made by talking):
83620
- - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
83621
- on the real adapter and the mock. The approval page auto-opens in the browser (its URL
83622
- is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
83623
- / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
83624
- their own wallet. The first verified signature binds their wallet address as the
83625
- borrower. Full walkthrough: \`guide connect-wallet\`.
83626
- - **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
83627
- signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
83628
- \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
83629
- LOCAL PAGE opens where the user types the password or generates a fresh keystore.
83630
- NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
83631
- them to use the unlock page instead.
83632
- - **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
83633
- real adapter they refuse with that true reason. Try them in a mock world.
83634
- - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
83635
- - **No signer is also a valid start:** every public read works without one \u2014
83636
- \`position_list {borrower}\` with the user's address needs no signer and no login.
83637
- - **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
83638
- talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
83639
- the money reality after any switch.
83640
-
83641
- **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
83642
- \`confirmed: true\` from the user). Then deposit BTC to the vault address
83643
- (practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
83644
- and mint with \`loan_mint\`.
83091
+ **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
83092
+ \`confirmed: true\` from the user). Then deposit BTC to the vault address
83093
+ (practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
83094
+ and mint with \`loan_mint\`.
83645
83095
 
83646
83096
  The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
83647
- "connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
83097
+ "connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
83648
83098
 
83649
83099
  External mode means the user approves every operation in their OWN wallet \u2014 a browser
83650
83100
  extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
@@ -83652,17 +83102,19 @@ the mock.
83652
83102
 
83653
83103
  **The walkthrough:**
83654
83104
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83655
- desktop browser; its URL is ALSO in the tool result (loopback-only \u2014 open it on the
83656
- same machine the server runs on).
83105
+ desktop browser; ${approvalPageLocation(d)}
83657
83106
  2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
83658
83107
  WalletConnect QR code or paste the pairing code.
83659
83108
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83660
83109
  login ceremony explicitly (one typed-data signature in the wallet).
83661
83110
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
83662
83111
  across sessions (\`signer_setup reset-borrower\` unbinds it).
83663
- 5. From then on, every fund-moving operation shows an approval card in the wallet,
83664
- decoded from the exact transaction bytes \u2014 what you read IS what executes. Declining
83665
- always safely cancels.
83112
+ 5. From then on, every fund-moving operation shows an approval card in the wallet. For
83113
+ TRANSACTIONS that card is decoded from the exact bytes being signed \u2014 what you read
83114
+ IS what executes. The ONE exception is the BTC withdrawal, which signs an opaque
83115
+ 32-byte hash the page states plainly it CANNOT decode (honesty note below); say so
83116
+ before those popups, never "what you read is what executes". Declining always safely
83117
+ cancels.
83666
83118
 
83667
83119
  **Popup cadence \u2014 exactly this many wallet interactions per operation:**
83668
83120
 
@@ -83674,7 +83126,7 @@ the mock.
83674
83126
  | repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
83675
83127
  | extend | 1 personal-sign + 1 tx |
83676
83128
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
83677
- | withdraw BTC | not available in external mode yet (refuses with that reason); keystore mode works, no popups |
83129
+ | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
83678
83130
  | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
83679
83131
 
83680
83132
  **Honesty notes (say these plainly):**
@@ -83685,10 +83137,19 @@ the mock.
83685
83137
  authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
83686
83138
  surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
83687
83139
  login means "wait and retry", not a wallet failure.
83688
- - **Withdraw-BTC under external mode is a BLIND signature** \u2014 the SDK builds the two
83689
- withdrawal auth hashes internally, so the approval page shows the bare hash and says
83690
- plainly it cannot decode the contents (the production web app signs the same way).
83691
- Tell the user this before the popups: two hash signatures, then the BTC moves.
83140
+ - **Withdraw-BTC under external mode has ONE blind signature, not two.** The
83141
+ authorization phase is EIP-712 typed data \u2014 the wallet renders position, amount and
83142
+ destination and the user can read it. Only the EXECUTE phase signs an opaque 32-byte
83143
+ hash the SDK builds internally, which the approval page shows bare and says plainly it
83144
+ cannot decode (the production web app signs the same way). Tell the user before that
83145
+ ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
83146
+ expect an unreadable card and click through the readable one.
83147
+ - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83148
+ valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83149
+ attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83150
+ back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83151
+ charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83152
+ signature. The blind execute popup happens once.
83692
83153
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83693
83154
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83694
83155
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83744,9 +83205,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83744
83205
 
83745
83206
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83746
83207
  signed, amounts included. Read it back when the user asks what happened.`,
83747
- psm: `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83208
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83748
83209
 
83749
- The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83210
+ ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83750
83211
  directions, in user words:
83751
83212
 
83752
83213
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83793,24 +83254,18 @@ own address. If you approve step 1 but decline step 2, the exact-amount allowanc
83793
83254
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83794
83255
  On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83795
83256
  (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
83796
- authorization: `# Authorization \u2014 who signs, and what a signature means
83257
+ authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83797
83258
 
83798
83259
  Every fund-moving operation needs TWO things, always in this order:
83799
83260
  1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
83800
83261
  must ask, never assume.
83801
- 2. **A cryptographic authorization** by the chosen signer mode:
83802
- - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
83803
- mobile via QR/paste-code). Real adapter and mock. The approval card in the wallet
83804
- shows EXACTLY what executes \u2014 amounts are decoded from the transaction itself, never
83805
- re-formatted. Walkthrough: \`guide connect-wallet\`.
83806
- - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
83807
- Real adapter and mock.
83808
- - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
83809
- refuse with that true reason (their planes ship in their own deliveries).
83810
- - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
83811
-
83262
+ 2. **A cryptographic authorization** by the chosen signer mode. This build offers
83263
+ exactly ${d.signerModes.map((m) => `\`${m}\``).join(", ")} \u2014 ${signerModeSourceClause(d)}. Never
83264
+ describe a mode outside it:
83265
+ ${authorizationModeBullets(d)}
83266
+ ${keystoreAbsenceParagraph(d)}
83812
83267
  **Reads never summon the wallet.** Public reads need no signer at all. Authenticated
83813
- reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
83268
+ reads need a login \u2014 ${offers(d, "keystore") ? "the keystore env pair, or " : ""}an explicit "connect my wallet"
83814
83269
  (\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
83815
83270
  only ever caused by a write ceremony or that explicit connect. The login (one typed-data
83816
83271
  signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
@@ -83826,9 +83281,28 @@ BOUND by the first verified signature (it persists across sessions). Connected \
83826
83281
  picking external mode is a preference \u2014 a wallet still has to connect on the approval
83827
83282
  page, and the page link comes from \`signer_setup status\`.
83828
83283
 
83829
- Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat;
83830
- keystore passwords go only into the secure unlock page.`,
83831
- safe: `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
83284
+ Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat${offers(d, "keystore") ? ";\nkeystore passwords go only into the secure unlock page." : " \u2014\nand this build has no password to ask for in the first place."}`,
83285
+ // Rendered on the capability axis: a build that constructs no Safe-shaped mode must not
83286
+ // hand a user a setup walkthrough its `signer_setup` cannot accept (the F1/F2 class,
83287
+ // one topic over). The concepts a Safe owner still needs stay; the instructions go.
83288
+ safe: (d) => !offers(d, "safe") ? `# Safe accounts \u2014 not offered by this build
83289
+
83290
+ A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
83291
+ signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Diamond Hands can
83292
+ treat a Safe AS THE BORROWER \u2014 but not from here. This build's authorization surface is
83293
+ the wallet ceremony alone; \`signer_setup\` lists no Safe-shaped option, so there is
83294
+ nothing to set up. Say that plainly instead of walking a user through a ceremony this
83295
+ service cannot run.
83296
+
83297
+ **What still holds for a Safe's position anywhere:** its BTC withdrawal destination must
83298
+ be ALLOWLISTED first, and the allowlist delay is READ LIVE from the chain \u2014 24 hours on
83299
+ mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS. Owner authorizations
83300
+ for mint/pay/renew expire in minutes and withdrawal authorizations within the minute, so
83301
+ a multi-owner signing session happens TOGETHER, live.
83302
+
83303
+ **Where it does exist:** the local install's practice worlds run the Safe borrower plane
83304
+ end to end, and the web app (diamondhands.credit) speaks to the same chain state. A user
83305
+ who needs it is not blocked \u2014 they are on the wrong surface for it.` : `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
83832
83306
 
83833
83307
  A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
83834
83308
  signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companies and
@@ -83864,7 +83338,24 @@ expire after ~3 minutes, and withdrawal authorizations within the minute \u2014
83864
83338
  owner signing session happens TOGETHER, live ("gather first, sign in one burst").
83865
83339
  Creating a position and allowlisting a destination have NO expiry \u2014 owners can sign
83866
83340
  those at their own pace. The ceremony guides this; never widen a window.`,
83867
- delegation: `# Delegation \u2014 one owner ceremony, then day-to-day solo
83341
+ delegation: (d) => !offers(d, "safe-module") ? `# Delegation \u2014 not offered by this build
83342
+
83343
+ Delegation is the protocol's answer to multi-owner Safes: the owners sign ONCE to install
83344
+ a tightly-caged AGENT key, and day-to-day work then runs without disturbing them. It is a
83345
+ Safe-shaped authorization plane, and this build constructs none \u2014 \`signer_setup\` lists
83346
+ no such option and \`loan_delegation_setup\` has no plane to install into here. Say that
83347
+ plainly rather than describing a ceremony this service cannot run.
83348
+
83349
+ **The cage, for a user who asks what it would mean:** an agent may create a position and
83350
+ \u2014 only after the owners grant it, per position \u2014 repay, renew, and mint while the
83351
+ post-mint collateral ratio stays at or above the floor the owners set. It can NEVER
83352
+ withdraw Bitcoin alone, never add or change withdrawal destinations, never touch the
83353
+ module or the registry, never move ETH. A stolen agent key can shuffle money WITHIN a
83354
+ position \u2014 never out. Revoking an agent BURNS its address forever, which is why
83355
+ revocation is always safe.
83356
+
83357
+ **Where it does exist:** the local install's practice worlds, pending the plane's own
83358
+ delivery on the real adapter. The web app and the SDK reach the same chain state.` : `# Delegation \u2014 one owner ceremony, then day-to-day solo
83868
83359
 
83869
83360
  Multi-owner Safes cannot practically sign every operation inside the protocol's short
83870
83361
  signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
@@ -83908,8 +83399,11 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
83908
83399
 
83909
83400
  - **Nothing moves without you.** Every write needs \`confirmed: true\` AND the signer
83910
83401
  ceremony. A decline anywhere cleanly cancels \u2014 declining is always safe.
83911
- - **The card is the truth.** In external mode the wallet card is decoded from the exact
83912
- transaction bytes being signed \u2014 what you read IS what executes.
83402
+ - **The card is the truth \u2014 with one named exception.** In external mode the wallet card
83403
+ is decoded from the exact TRANSACTION bytes being signed: what you read IS what
83404
+ executes. The exception is the BTC-withdraw blind signature \u2014 an opaque 32-byte hash
83405
+ the approval page says plainly it cannot decode (\`guide connect-wallet\`). Never
83406
+ extend the "what you read is what executes" promise over that one.
83913
83407
  - **Liquidation:** if collateral value falls so the collateral ratio drops under the
83914
83408
  liquidation threshold (\`protocol_status.liquidationThresholdBps\`, e.g. 110%), the
83915
83409
  position can be liquidated. Watch \`position_status.valuation\` \u2014 \`currentLtvBps\` vs the
@@ -83922,23 +83416,21 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
83922
83416
  withdrawing to a wrong address. Repaid-in-full positions release all collateral.
83923
83417
  - **Practice vs real:** mock worlds are stated as such (\`boundary://info\`). Never let a
83924
83418
  user believe practice gains/losses are real, or vice versa.`,
83925
- "switch-network": `# Switch network \u2014 sepolia \u2194 mainnet by conversation (real adapter)
83419
+ "switch-network": (d) => `# Switch network \u2014 ${switchNetworkHeadline(d)}
83926
83420
 
83927
83421
  The \`network_switch\` tool moves THIS SESSION between worlds. Check
83928
83422
  \`boundary://info\` capabilities first: \`networkSwitch: true\` means it is available
83929
83423
  (real adapter); in a practice sandbox (mock) the world is pinned by config \u2014 there is
83930
83424
  no switch, and that is by design.
83931
83425
 
83426
+ **Served here:** ${servedNetworks(d)}. A network this deployment does not serve is
83427
+ refused with that reason \u2014 the tool existing is not a promise that both worlds are
83428
+ reachable, so never offer the user a network this deployment does not serve.
83429
+
83932
83430
  **The rules, plainly:**
83933
83431
  - \`network_switch status\` \u2014 which network is active and whether money is real. Say
83934
83432
  this to the user BEFORE and AFTER any switch, always.
83935
- - \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
83936
- the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83937
- - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83938
- A sepolia position does not exist on mainnet and vice versa.
83939
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83940
- and every one still requires the user's explicit confirmation plus the signer
83941
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.
83433
+ ${switchNetworkRules(d)}
83942
83434
  - A pending signing ceremony blocks the switch (finish or decline it first).
83943
83435
  - The switch is session-scoped: when the server restarts, the configured default
83944
83436
  network returns.
@@ -83948,12 +83440,9 @@ reality in your next message. The user must never have to ask which world they a
83948
83440
  // Plan 17 B1 — the hosted tier's truth, in user language. The trust ledger below is
83949
83441
  // the plan-12 Part 0 ledger (BINDING, archive/12-remote-connector.md) — all six
83950
83442
  // entries, verbatim-equivalent; G-CONN pins anchor phrases from every entry.
83951
- connector: `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
83443
+ connector: (d) => `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
83952
83444
 
83953
- **STATUS TRUTH (say this first when asked):** the connector is IMPLEMENTED but NOT yet
83954
- publicly served \u2014 the operator's rollout gates (a security audit, then a URL) come
83955
- first. Until then there is no URL to give out, and the local install paths
83956
- (\`first-setup\`) are the way in. Never promise availability or timing.
83445
+ ${connectorStatusTruth(d)}
83957
83446
 
83958
83447
  **What it is:** instead of installing anything, the user adds Diamond Hands to
83959
83448
  claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
@@ -83980,9 +83469,17 @@ honestly when asked "is this safe"):
83980
83469
  is never written to disk. A breach here is privacy-class, never money-class.
83981
83470
  3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
83982
83471
  a security concern is filed and audited for exactly this channel.
83983
- 4. **Tenant separation.** Your identity \u2194 wallet \u2194 session binding is isolated from
83984
- every other user's; a failure here would be privacy-class, never signing-class,
83985
- because no key material exists server-side to leak.
83472
+ 4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
83473
+ gets its own world: its own boundary, its own signer state, its own approval-page
83474
+ mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
83475
+ world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
83476
+ plus an earlier connection would make a different wallet this session's signer. That
83477
+ is signing-class, not merely privacy-class; do not tell a user it cannot be. What
83478
+ contains it: the mount id is freshly random per world and travels only in the user's
83479
+ own tool result (treat the link as a secret), and EVERY fund movement verifies the
83480
+ signature against that bound borrower \u2014 no key material exists server-side, so
83481
+ whoever reaches the page still cannot sign for anyone else. The gap is filed and
83482
+ audited; state it this way rather than claiming a binding that isn't there.
83986
83483
  5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
83987
83484
  version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
83988
83485
  reports the exact server version.
@@ -83994,30 +83491,37 @@ honestly when asked "is this safe"):
83994
83491
 
83995
83492
  **What it structurally CANNOT do:** hold keys or custody \u2014 keystore mode is ABSENT
83996
83493
  from the connector build (not disabled: never constructed), so every fund-moving
83997
- action needs a fresh signature from the user's own wallet. And it serves only the
83998
- networks its deployment is rolled out to \u2014 this deployment serves sepolia during
83999
- rollout; mainnet enablement is the operator's deploy decision, stated in capabilities
84000
- by reason, never a hidden knob.
83494
+ action needs a fresh signature from the user's own wallet. ${connectorNetworkTruth(d)}
84001
83495
 
84002
83496
  **Independent exits:** the web app (diamondhands.credit) and the SDK speak to the SAME
84003
83497
  chain state. The connector going down strands nothing and gates nothing.`,
84004
- troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
83498
+ troubleshooting: (d) => `# Troubleshooting \u2014 what error codes mean, in plain words
84005
83499
 
84006
- - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
83500
+ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
84007
83501
  keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
84008
83502
  "connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
84009
83503
  status\` explains what is active; \`first-setup\` step 2 has the full choice.
84010
83504
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
84011
83505
  the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
84012
- EXPIRED login refuses the same way \u2014 reconnect on the user's word.
84013
- - **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
84014
- not a bug); loan operations work on mainnet. Reads keep working everywhere.
84015
- - **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
84016
- (human-confirmed card; nothing carries across networks). Mock: the world is pinned by
84017
- config \u2014 no switch exists there.
83506
+ EXPIRED login refuses the same way \u2014 reconnect on the user's word.` : `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. This build has exactly
83507
+ ONE remedy: the user says "connect my wallet" \u2192 \`signer_setup\` action \`connect\`
83508
+ (external mode). There is no keystore here to configure and no password to supply \u2014
83509
+ saying otherwise sends the user hunting for a setting that does not exist.
83510
+ \`signer_setup status\` explains what is active; \`first-setup\` step 2 has the choice.
83511
+ - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83512
+ the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
83513
+ the same way \u2014 reconnect on the user's word.`}
83514
+ ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83515
+ not a bug); loan operations work on mainnet. Reads keep working everywhere.` : `- **PSM write refused** \u2014 the PSM write port answers on sepolia alone (a deliberate
83516
+ anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
83517
+ ${wrongNetworkTroubleshootingRow(d)}
84018
83518
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
84019
- SDK builds the withdrawal auth hashes internally, so the page cannot decode them.
84020
- Two blind hash signatures per withdrawal; warn the user before triggering them.
83519
+ SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
83520
+ signature per withdrawal, not two: the authorization phase is EIP-712 typed data
83521
+ (\`WithdrawRequest\` \u2014 the wallet renders position, amount and destination), and only
83522
+ the execute phase is opaque. Warn the user before that one popup, and do not describe
83523
+ the typed one as blind \u2014 overstating it teaches them to expect an unreadable card and
83524
+ click through the readable one.
84021
83525
  - **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
84022
83526
  That is the broker throttle, not a wallet failure.
84023
83527
  - **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
@@ -84032,9 +83536,7 @@ chain state. The connector going down strands nothing and gates nothing.`,
84032
83536
  which source and when from. Prefer chain-sourced values; re-read before acting.
84033
83537
  - Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
84034
83538
  Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
84035
- - **Asked for the claude.ai connector / remote / hosted tier** \u2014 implemented, NOT yet
84036
- publicly served (the operator's audit + rollout gates come first). There is no URL to
84037
- give out; the local install paths work today. Full truth: \`guide connector\`.
83539
+ ${connectorTroubleshootingRow(d)}
84038
83540
  - **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
84039
83541
  the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
84040
83542
  Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
@@ -84054,7 +83556,8 @@ Synonym sets (treat these as the SAME intent):
84054
83556
  - **UCD** = the dollar-pegged token you borrow ("the dollars")
84055
83557
  - **sats** = satoshis, 1 BTC = 100,000,000 sats
84056
83558
  - **connector** = remote = hosted tier = "claude.ai integration" = "use it without
84057
- installing" \u2192 \`guide connector\` (status: implemented, not yet publicly served)
83559
+ installing" \u2192 \`guide connector\` (it states which tier THIS session is, and the
83560
+ trust model that comes with it)
84058
83561
 
84059
83562
  Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
84060
83563
  - **vault** \u2014 the position's BTC custody address. Its balance is your COLLATERAL, not
@@ -84065,39 +83568,1099 @@ Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
84065
83568
  - **interest** \u2014 Diamond Hands charges FEES (origination/extension), not running
84066
83569
  interest; see \`fees\`.
84067
83570
 
84068
- Language: answer in the user's language, whatever it is. These mappings apply to meaning,
84069
- not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
84070
- "emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
84071
- // Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
84072
- // the same entries the anchor test pins against the actually-serialized fields.
84073
- "reading-data": renderFieldGlossaryTopic()
83571
+ Language: answer in the user's language, whatever it is. These mappings apply to meaning,
83572
+ not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
83573
+ "emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
83574
+ // Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
83575
+ // the same entries the anchor test pins against the actually-serialized fields.
83576
+ "reading-data": renderFieldGlossaryTopic()
83577
+ };
83578
+ function renderGuideContent(deployment) {
83579
+ const content = {};
83580
+ for (const topic of GUIDE_TOPICS) {
83581
+ const source = GUIDE_TOPIC_SOURCES[topic];
83582
+ content[topic] = typeof source === "string" ? source : source(deployment);
83583
+ }
83584
+ return content;
83585
+ }
83586
+ function renderGuideIndex(deployment) {
83587
+ const connectorLine = deployment.tier === "hosted" ? `- connector \u2014 the hosted claude.ai tier THIS session is running on (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. Serves ${servedNetworks(deployment)}` : "- connector \u2014 the hosted claude.ai tier (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. THIS session is a local install, not that tier";
83588
+ return `# Diamond Hands guide \u2014 topics
83589
+
83590
+ - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
83591
+ - first-setup \u2014 zero to ready by conversation (authorization choice included)
83592
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
83593
+ - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
83594
+ - fees \u2014 the two fee models, plainly
83595
+ - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
83596
+ - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
83597
+ ${offers(deployment, "safe") ? "- safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today" : "- safe \u2014 borrowing as a Safe smart-account: NOT offered by this build (no Safe-shaped mode exists here), and what still holds wherever it is"}
83598
+ ${offers(deployment, "safe-module") ? "- delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today" : "- delegation \u2014 the caged agent key for multi-owner Safes: NOT offered by this build, and what the cage would mean where it is"}
83599
+ - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
83600
+ ${switchNetworkIndexLine(deployment)}
83601
+ ${connectorLine}
83602
+ - troubleshooting \u2014 error codes in plain words, with the real remedies
83603
+ - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
83604
+ - reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
83605
+
83606
+ Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
83607
+ selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
83608
+ signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
83609
+ and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
83610
+ only mainnet is real money.`;
83611
+ }
83612
+ var deploymentKey = (d) => `${d.tier}|${d.networks.join(",")}|${d.signerModes.join(",")}`;
83613
+ var RENDERED = /* @__PURE__ */ new Map();
83614
+ function renderedGuide(deployment) {
83615
+ const key = deploymentKey(deployment);
83616
+ let rendered = RENDERED.get(key);
83617
+ if (!rendered) {
83618
+ rendered = Object.freeze({
83619
+ content: Object.freeze(renderGuideContent(deployment)),
83620
+ index: renderGuideIndex(deployment)
83621
+ });
83622
+ RENDERED.set(key, rendered);
83623
+ }
83624
+ return rendered;
83625
+ }
83626
+ function buildGuideContent(deployment) {
83627
+ return renderedGuide(deployment).content;
83628
+ }
83629
+ function buildGuideIndex(deployment) {
83630
+ return renderedGuide(deployment).index;
83631
+ }
83632
+ var GUIDE_CONTENT = buildGuideContent(LOCAL_GUIDE_DEPLOYMENT);
83633
+ var GUIDE_INDEX = buildGuideIndex(LOCAL_GUIDE_DEPLOYMENT);
83634
+
83635
+ // src/network-switch.ts
83636
+ var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
83637
+ function createNetworkSwitchRuntime(opts) {
83638
+ return {
83639
+ current() {
83640
+ const b = opts.getBoot().boundaryResult;
83641
+ if (!b.ok) return null;
83642
+ const w = b.boundary.world();
83643
+ return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
83644
+ },
83645
+ async switchTo(network) {
83646
+ const allowed = opts.overrides?.allowedNetworks;
83647
+ if (allowed && !allowed.includes(network)) {
83648
+ return {
83649
+ ok: false,
83650
+ error: boundaryError(
83651
+ "VALIDATION_FAILED",
83652
+ `this deployment serves ${allowed.join(", ")} \u2014 '${network}' is not enabled on this service. Mainnet service enablement is a rollout step of the deployment, not a session setting.`
83653
+ )
83654
+ };
83655
+ }
83656
+ const targetEnv = { ...opts.env, DH_NETWORK: network };
83657
+ const configResult = resolveBoundaryConfig(targetEnv);
83658
+ if (!configResult.ok) return { ok: false, error: configResult.error };
83659
+ const next = await buildBoundary(configResult, opts.overrides);
83660
+ if (!next.boundaryResult.ok) {
83661
+ next.dispose();
83662
+ return { ok: false, error: next.boundaryResult.error };
83663
+ }
83664
+ opts.swap(next);
83665
+ return { ok: true };
83666
+ }
83667
+ };
83668
+ }
83669
+ function guideDeployment(overrides) {
83670
+ return {
83671
+ tier: overrides?.bridgeMount ? "hosted" : "local",
83672
+ networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
83673
+ signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
83674
+ };
83675
+ }
83676
+ function assembleWorld(opts) {
83677
+ let boot = opts.boot;
83678
+ const deps = {
83679
+ boundaryResult: boot.boundaryResult,
83680
+ ...boot.mockControl ? { mockControl: boot.mockControl } : {},
83681
+ ...boot.signer ? { signer: boot.signer } : {},
83682
+ ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
83683
+ deployment: guideDeployment(opts.overrides),
83684
+ ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
83685
+ };
83686
+ if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
83687
+ deps.networkSwitch = createNetworkSwitchRuntime({
83688
+ env: opts.env,
83689
+ getBoot: () => boot,
83690
+ ...opts.overrides ? { overrides: opts.overrides } : {},
83691
+ swap: (next) => {
83692
+ const old = boot;
83693
+ boot = next;
83694
+ deps.boundaryResult = next.boundaryResult;
83695
+ if (next.signer) deps.signer = next.signer;
83696
+ else delete deps.signer;
83697
+ old.dispose();
83698
+ const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
83699
+ opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
83700
+ }
83701
+ });
83702
+ }
83703
+ return { deps, dispose: () => boot.dispose() };
83704
+ }
83705
+
83706
+ // src/server.ts
83707
+ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
83708
+
83709
+ // src/tools/loan.ts
83710
+ var import_zod = require("zod");
83711
+ var import_ethers41 = require("ethers");
83712
+
83713
+ // src/util/format.ts
83714
+ function bigintReplacer(_key, value) {
83715
+ if (typeof value === "bigint") return value.toString();
83716
+ return value;
83717
+ }
83718
+ function serialize(data) {
83719
+ return JSON.stringify(data, bigintReplacer, 2);
83720
+ }
83721
+
83722
+ // src/tools/_helpers.ts
83723
+ function registerBoundaryTool(server, name, config, handler) {
83724
+ server.registerTool(name, config, handler);
83725
+ }
83726
+ function renderError(error) {
83727
+ const lines = [`ERROR [${error.code}]: ${error.message}`];
83728
+ if (error.source) lines.push(`source: ${error.source}`);
83729
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
83730
+ }
83731
+ function renderEnvelope(env) {
83732
+ if (!env.ok) return renderError(env.error);
83733
+ const parts = [serialize(env.data)];
83734
+ if (env.warnings.length > 0) {
83735
+ parts.push(
83736
+ "WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
83737
+ );
83738
+ }
83739
+ parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
83740
+ return { content: [{ type: "text", text: parts.join("\n\n") }] };
83741
+ }
83742
+ function validationFailed(problem) {
83743
+ return renderError(boundaryError("VALIDATION_FAILED", problem));
83744
+ }
83745
+ function resourceJson(env) {
83746
+ if (!env.ok) return serialize({ error: env.error });
83747
+ return serialize({ data: env.data, warnings: env.warnings, source: env.source });
83748
+ }
83749
+ function resourceErrorJson(error) {
83750
+ return serialize({ error });
83751
+ }
83752
+ function requireConfirmation(confirmed, actionLabel) {
83753
+ if (confirmed === true) return null;
83754
+ return {
83755
+ content: [
83756
+ {
83757
+ type: "text",
83758
+ text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
83759
+ This is an irreversible, fund-moving action. A human must explicitly authorize it.
83760
+ Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
83761
+ }
83762
+ ],
83763
+ isError: true
83764
+ };
83765
+ }
83766
+ function envStamp(b) {
83767
+ if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
83768
+ const w = b.boundary.world();
83769
+ const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
83770
+ return `environment: ${w.network} \u2014 ${money}`;
83771
+ }
83772
+ async function guardedWrite(getB, fn) {
83773
+ const result = await guarded(fn);
83774
+ const stamp = envStamp(getB());
83775
+ const content = result.content.map(
83776
+ (c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
83777
+
83778
+ ${stamp}` } : c
83779
+ );
83780
+ return { ...result, content };
83781
+ }
83782
+ async function guarded(fn) {
83783
+ try {
83784
+ return await fn();
83785
+ } catch (e) {
83786
+ return renderError(
83787
+ boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
83788
+ details: { stack: e.stack }
83789
+ })
83790
+ );
83791
+ }
83792
+ }
83793
+
83794
+ // src/util/validate.ts
83795
+ var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
83796
+ var SATS_SANITY_CAP = 1e10;
83797
+ var UCD_SANITY_CAP = 1e9;
83798
+ function checkPositionIdHex(id, label = "Position ID") {
83799
+ if (!POSITION_ID_RE.test(id)) {
83800
+ return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
83801
+ }
83802
+ return null;
83803
+ }
83804
+ function checkUcdAmount(amount, label = "Amount") {
83805
+ if (!Number.isFinite(amount) || amount <= 0) {
83806
+ return `${label} must be a positive finite number (got ${amount}).`;
83807
+ }
83808
+ if (amount > UCD_SANITY_CAP) {
83809
+ return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
83810
+ }
83811
+ if (amount > 0 && amount < 1e-6) {
83812
+ return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
83813
+ }
83814
+ const decimals = amount.toString().split(".")[1];
83815
+ if (decimals && decimals.length > 6) {
83816
+ return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
83817
+ }
83818
+ return null;
83819
+ }
83820
+ function checkSatsAmount(sats, label = "Amount") {
83821
+ if (!Number.isInteger(sats) || sats <= 0) {
83822
+ return `${label} must be a positive integer (satoshis), got ${sats}.`;
83823
+ }
83824
+ if (sats > SATS_SANITY_CAP) {
83825
+ return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
83826
+ }
83827
+ return null;
83828
+ }
83829
+ function checkSelectedTerm(months, label = "Term") {
83830
+ if (!Number.isInteger(months) || months <= 0) {
83831
+ return `${label} must be a positive integer (months), got ${months}.`;
83832
+ }
83833
+ if (months > 120) {
83834
+ return `${label} ${months} months exceeds the 10-year sanity cap.`;
83835
+ }
83836
+ return null;
83837
+ }
83838
+
83839
+ // src/tools/loan.ts
83840
+ var LATENCY_NOTES = {
83841
+ mock: "Instant in this practice world.",
83842
+ real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
83843
+ };
83844
+ var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
83845
+ var confirmedSchema = import_zod.z.boolean().optional().describe(
83846
+ "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
83847
+ );
83848
+ var DESTRUCTIVE_WRITE_ANNOTATIONS = {
83849
+ readOnlyHint: false,
83850
+ destructiveHint: true,
83851
+ idempotentHint: false,
83852
+ openWorldHint: true
83853
+ };
83854
+ function registerLoanTools(server, getB, adapter2 = "real") {
83855
+ const LATENCY_NOTE = LATENCY_NOTES[adapter2];
83856
+ registerBoundaryTool(
83857
+ server,
83858
+ "loan_create",
83859
+ {
83860
+ title: "Create a new lending position",
83861
+ description: `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83862
+ inputSchema: {
83863
+ selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
83864
+ confirmed: confirmedSchema
83865
+ },
83866
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83867
+ },
83868
+ async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
83869
+ const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
83870
+ if (gate) return gate;
83871
+ const problem = checkSelectedTerm(selectedTerm);
83872
+ if (problem) return validationFailed(problem);
83873
+ const b = getB();
83874
+ if (!b.ok) return renderError(b.error);
83875
+ return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
83876
+ })
83877
+ );
83878
+ registerBoundaryTool(
83879
+ server,
83880
+ "loan_mint",
83881
+ {
83882
+ title: "Mint UCD against a position",
83883
+ description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83884
+ inputSchema: {
83885
+ positionId: positionIdSchema,
83886
+ amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
83887
+ confirmed: confirmedSchema
83888
+ },
83889
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83890
+ },
83891
+ async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
83892
+ const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
83893
+ if (gate) return gate;
83894
+ const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
83895
+ if (problem) return validationFailed(problem);
83896
+ const b = getB();
83897
+ if (!b.ok) return renderError(b.error);
83898
+ return renderEnvelope(
83899
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
83900
+ );
83901
+ })
83902
+ );
83903
+ registerBoundaryTool(
83904
+ server,
83905
+ "loan_pay",
83906
+ {
83907
+ title: "Make a UCD payment toward a position's debt",
83908
+ description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83909
+ inputSchema: {
83910
+ positionId: positionIdSchema,
83911
+ amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
83912
+ repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
83913
+ confirmed: confirmedSchema
83914
+ },
83915
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83916
+ },
83917
+ async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
83918
+ if (repayAll === true === (amountUcd !== void 0)) {
83919
+ return validationFailed("provide exactly one of amountUcd or repayAll: true");
83920
+ }
83921
+ const gate = requireConfirmation(
83922
+ confirmed,
83923
+ repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
83924
+ );
83925
+ if (gate) return gate;
83926
+ const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
83927
+ if (problem) return validationFailed(problem);
83928
+ const b = getB();
83929
+ if (!b.ok) return renderError(b.error);
83930
+ let amountUcdWei;
83931
+ if (repayAll) {
83932
+ const detail = await b.boundary.getPosition(positionId);
83933
+ if (!detail.ok) return renderError(detail.error);
83934
+ if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
83935
+ amountUcdWei = detail.data.debtUcdWei;
83936
+ } else {
83937
+ amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
83938
+ }
83939
+ return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
83940
+ })
83941
+ );
83942
+ registerBoundaryTool(
83943
+ server,
83944
+ "loan_extend",
83945
+ {
83946
+ title: "Extend / renew a position's term",
83947
+ description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83948
+ inputSchema: {
83949
+ positionId: positionIdSchema,
83950
+ selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
83951
+ confirmed: confirmedSchema
83952
+ },
83953
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83954
+ },
83955
+ async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
83956
+ const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
83957
+ if (gate) return gate;
83958
+ const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
83959
+ if (problem) return validationFailed(problem);
83960
+ const b = getB();
83961
+ if (!b.ok) return renderError(b.error);
83962
+ return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
83963
+ })
83964
+ );
83965
+ registerBoundaryTool(
83966
+ server,
83967
+ "loan_withdraw",
83968
+ {
83969
+ title: "Withdraw BTC from a position vault",
83970
+ description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83971
+ inputSchema: {
83972
+ positionId: positionIdSchema,
83973
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
83974
+ amountSats: import_zod.z.number().int().positive().describe(
83975
+ "GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. amountSats may be up to the whole available balance (a full sweep leaves 0 sats; anything above available reverts TargetExceedsInputValue). position_status.maxWithdrawableSats is a ready-to-use value that already leaves the default fee aside."
83976
+ ),
83977
+ networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
83978
+ confirmed: confirmedSchema
83979
+ },
83980
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83981
+ },
83982
+ async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
83983
+ const gate = requireConfirmation(
83984
+ confirmed,
83985
+ `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
83986
+ );
83987
+ if (gate) return gate;
83988
+ const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
83989
+ if (problem) return validationFailed(problem);
83990
+ const b = getB();
83991
+ if (!b.ok) return renderError(b.error);
83992
+ return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
83993
+ })
83994
+ );
83995
+ registerBoundaryTool(
83996
+ server,
83997
+ "loan_allowlist_destination",
83998
+ {
83999
+ title: "Allowlist a BTC withdrawal destination",
84000
+ description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
84001
+ inputSchema: {
84002
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
84003
+ confirmed: confirmedSchema
84004
+ },
84005
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84006
+ },
84007
+ async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
84008
+ const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
84009
+ if (gate) return gate;
84010
+ const b = getB();
84011
+ if (!b.ok) return renderError(b.error);
84012
+ return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
84013
+ })
84014
+ );
84015
+ registerBoundaryTool(
84016
+ server,
84017
+ "loan_delegation_setup",
84018
+ {
84019
+ title: "Install delegation on the Safe (one owner ceremony)",
84020
+ description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
84021
+ inputSchema: {
84022
+ btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
84023
+ confirmed: confirmedSchema
84024
+ },
84025
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84026
+ },
84027
+ async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
84028
+ const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
84029
+ if (gate) return gate;
84030
+ const b = getB();
84031
+ if (!b.ok) return renderError(b.error);
84032
+ return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
84033
+ })
84034
+ );
84035
+ registerBoundaryTool(
84036
+ server,
84037
+ "loan_delegation_grant",
84038
+ {
84039
+ title: "Grant the agent per-position scopes (owners sign)",
84040
+ description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
84041
+ inputSchema: {
84042
+ positionId: positionIdSchema,
84043
+ renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
84044
+ repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
84045
+ mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
84046
+ confirmed: confirmedSchema
84047
+ },
84048
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84049
+ },
84050
+ async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
84051
+ const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
84052
+ if (gate) return gate;
84053
+ const b = getB();
84054
+ if (!b.ok) return renderError(b.error);
84055
+ return renderEnvelope(
84056
+ await b.boundary.delegationGrant({
84057
+ positionId,
84058
+ renew: renew ?? false,
84059
+ repay: repay ?? false,
84060
+ mintFloorBps: mintFloorBps ?? null
84061
+ })
84062
+ );
84063
+ })
84064
+ );
84065
+ registerBoundaryTool(
84066
+ server,
84067
+ "loan_recover_stale_spend",
84068
+ {
84069
+ title: "Recover a stale BTC reservation via LIT-attested proof",
84070
+ description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
84071
+ inputSchema: {
84072
+ positionId: positionIdSchema,
84073
+ utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
84074
+ utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
84075
+ invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
84076
+ minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
84077
+ },
84078
+ annotations: {
84079
+ readOnlyHint: false,
84080
+ destructiveHint: false,
84081
+ idempotentHint: true,
84082
+ openWorldHint: true
84083
+ }
84084
+ },
84085
+ async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
84086
+ const problem = checkPositionIdHex(positionId);
84087
+ if (problem) return validationFailed(problem);
84088
+ const b = getB();
84089
+ if (!b.ok) return renderError(b.error);
84090
+ return renderEnvelope(
84091
+ await b.boundary.recoverStaleSpend({
84092
+ positionId,
84093
+ utxoTxid,
84094
+ utxoVout,
84095
+ invalidatorTxid,
84096
+ ...minConfirmations !== void 0 ? { minConfirmations } : {}
84097
+ })
84098
+ );
84099
+ })
84100
+ );
84101
+ }
84102
+
84103
+ // src/tools/position.ts
84104
+ var import_zod2 = require("zod");
84105
+ var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
84106
+ var POSITION_STATES = [
84107
+ "PENDING_DEPOSIT",
84108
+ "PENDING_MINT",
84109
+ "ACTIVE",
84110
+ "EXPIRED",
84111
+ "LIQUIDATABLE",
84112
+ "LIQUIDATED",
84113
+ "REPAID",
84114
+ "CLOSED"
84115
+ ];
84116
+ function registerPositionTools(server, getB) {
84117
+ registerBoundaryTool(
84118
+ server,
84119
+ "position_status",
84120
+ {
84121
+ title: "Get a position's full status",
84122
+ description: "Return detailed status for a single position: chain facts (debt, term, expiry, state), live collateral (confirmed sats + per-transaction pending deposits, plus maxWithdrawableSats \u2014 directly usable as a withdrawal amountSats), and a basis-carrying valuation (maxMintableUcd is directly usable as amountUcd). If a withdrawal reservation was already spent on Bitcoin but availableSats still shows it deducted, run loan_recover_stale_spend to release the redundant hold. Any `reading` notes in the result are authoritative interpretation instructions for that exact payload \u2014 follow them." + fieldGuide("state", "availableSats", "minConfirmations", "pendingDeposits", "maxWithdrawableSats", "maxMintableUcd", "debtUcdWei"),
84123
+ inputSchema: {
84124
+ id: positionIdSchema2
84125
+ }
84126
+ },
84127
+ async ({ id }) => guarded(async () => {
84128
+ const problem = checkPositionIdHex(id);
84129
+ if (problem) return validationFailed(problem);
84130
+ const b = getB();
84131
+ if (!b.ok) return renderError(b.error);
84132
+ return renderEnvelope(await b.boundary.getPosition(id));
84133
+ })
84134
+ );
84135
+ registerBoundaryTool(
84136
+ server,
84137
+ "position_list",
84138
+ {
84139
+ title: "List lending positions",
84140
+ description: "List positions with optional filters. `borrower` and `state` COMBINE (logical AND); with no filter, returns active positions. Rows are the INDEXER's view \u2014 `state` here is an indexer snapshot that can lag the chain; position_status reads the chain and is authoritative for one position." + fieldGuide("state", "debtUcdWei", "indexedHealth"),
84141
+ inputSchema: {
84142
+ borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
84143
+ state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
84144
+ page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
84145
+ pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
84146
+ }
84147
+ },
84148
+ async ({ borrower, state, page, pageSize }) => guarded(async () => {
84149
+ if (state !== void 0 && !POSITION_STATES.includes(state)) {
84150
+ return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
84151
+ }
84152
+ const b = getB();
84153
+ if (!b.ok) return renderError(b.error);
84154
+ const filter2 = {
84155
+ page,
84156
+ pageSize,
84157
+ ...borrower !== void 0 ? { borrower } : {},
84158
+ ...state !== void 0 ? { state } : {}
84159
+ };
84160
+ if (filter2.borrower === void 0 && filter2.state === void 0) {
84161
+ return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
84162
+ }
84163
+ return renderEnvelope(await b.boundary.listPositions(filter2));
84164
+ })
84165
+ );
84166
+ registerBoundaryTool(
84167
+ server,
84168
+ "position_events",
84169
+ {
84170
+ title: "Get a position's event history",
84171
+ description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
84172
+ inputSchema: {
84173
+ id: positionIdSchema2
84174
+ }
84175
+ },
84176
+ async ({ id }) => guarded(async () => {
84177
+ const problem = checkPositionIdHex(id);
84178
+ if (problem) return validationFailed(problem);
84179
+ const b = getB();
84180
+ if (!b.ok) return renderError(b.error);
84181
+ return renderEnvelope(await b.boundary.getPositionEvents(id));
84182
+ })
84183
+ );
84184
+ registerBoundaryTool(
84185
+ server,
84186
+ "position_pending_withdrawals",
84187
+ {
84188
+ title: "List a position's pending BTC withdrawal reservations",
84189
+ description: "Query the spend authorizer for BTC withdrawal reservations on a position. Each entry has txid/vout, satoshis, and target address (txid/vout feed recovery).",
84190
+ inputSchema: {
84191
+ id: positionIdSchema2
84192
+ }
84193
+ },
84194
+ async ({ id }) => guarded(async () => {
84195
+ const problem = checkPositionIdHex(id);
84196
+ if (problem) return validationFailed(problem);
84197
+ const b = getB();
84198
+ if (!b.ok) return renderError(b.error);
84199
+ return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
84200
+ })
84201
+ );
84202
+ }
84203
+
84204
+ // src/tools/btc.ts
84205
+ var import_zod3 = require("zod");
84206
+ function registerBtcTools(server, getB) {
84207
+ registerBoundaryTool(
84208
+ server,
84209
+ "btc_balance",
84210
+ {
84211
+ title: "Get BTC balance for an address",
84212
+ description: "Query the confirmed BTC balance for an address (source-tagged).",
84213
+ inputSchema: {
84214
+ address: import_zod3.z.string().min(1).describe("BTC address to query")
84215
+ }
84216
+ },
84217
+ async ({ address }) => guarded(async () => {
84218
+ const b = getB();
84219
+ if (!b.ok) return renderError(b.error);
84220
+ return renderEnvelope(await b.boundary.getBitcoinBalance(address));
84221
+ })
84222
+ );
84223
+ registerBoundaryTool(
84224
+ server,
84225
+ "btc_price",
84226
+ {
84227
+ title: "Get the current BTC price",
84228
+ description: "Return the current BTC price (USD, 8 decimals) from the price oracle.",
84229
+ inputSchema: {}
84230
+ },
84231
+ async () => guarded(async () => {
84232
+ const b = getB();
84233
+ if (!b.ok) return renderError(b.error);
84234
+ return renderEnvelope(await b.boundary.getBitcoinPrice());
84235
+ })
84236
+ );
84237
+ }
84238
+
84239
+ // src/tools/protocol.ts
84240
+ function registerProtocolTools(server, getB) {
84241
+ registerBoundaryTool(
84242
+ server,
84243
+ "protocol_status",
84244
+ {
84245
+ title: "Get protocol configuration and status",
84246
+ description: "Return protocol status: pause flag, mint LTV limit (ltvBps), liquidation threshold (liquidationThresholdBps \u2014 a COLLATERAL RATIO in bps, i.e. collateralValue/debt, so 11000 = 110%; note this is the inverse basis of ltvBps which is debt/collateral), deposit confirmation threshold, BTC network.",
84247
+ inputSchema: {}
84248
+ },
84249
+ async () => guarded(async () => {
84250
+ const b = getB();
84251
+ if (!b.ok) return renderError(b.error);
84252
+ return renderEnvelope(await b.boundary.getProtocolStatus());
84253
+ })
84254
+ );
84255
+ registerBoundaryTool(
84256
+ server,
84257
+ "protocol_terms",
84258
+ {
84259
+ title: "List available loan terms with fees",
84260
+ description: "Return all configured loan terms (in months) with their fees. Term length: 12 months = exactly 365 days; any other term = N \xD7 30-day months. originationFeeBps: % of a mint, ADDED to debt. extensionFeeRateBps: the renewal fee CEILING as % of outstanding debt PER RENEWAL (a flat rate, NOT per month); the charged fee is ADDED TO DEBT and reduced by origination fees already paid this term.",
84261
+ inputSchema: {}
84262
+ },
84263
+ async () => guarded(async () => {
84264
+ const b = getB();
84265
+ if (!b.ok) return renderError(b.error);
84266
+ return renderEnvelope(await b.boundary.getTerms());
84267
+ })
84268
+ );
84269
+ }
84270
+
84271
+ // src/tools/psm.ts
84272
+ var import_zod4 = require("zod");
84273
+ var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
84274
+ "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
84275
+ );
84276
+ var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
84277
+ readOnlyHint: false,
84278
+ destructiveHint: true,
84279
+ idempotentHint: false,
84280
+ openWorldHint: true
84074
84281
  };
84075
- var GUIDE_INDEX = `# Diamond Hands guide \u2014 topics
84282
+ function registerPsmTools(server, getB) {
84283
+ registerBoundaryTool(
84284
+ server,
84285
+ "psm_quote",
84286
+ {
84287
+ title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
84288
+ description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
84289
+ inputSchema: {
84290
+ direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = get UCD for USDC (contract swap); 'to-usdc' = get USDC back for UCD (contract redeem)"),
84291
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
84292
+ },
84293
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84294
+ },
84295
+ async ({ direction, amount }) => guarded(async () => {
84296
+ const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
84297
+ const problem = checkUcdAmount(amount, label);
84298
+ if (problem) return validationFailed(problem);
84299
+ const b = getB();
84300
+ if (!b.ok) return renderError(b.error);
84301
+ return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
84302
+ })
84303
+ );
84304
+ registerBoundaryTool(
84305
+ server,
84306
+ "psm_swap",
84307
+ {
84308
+ title: "Exchange UCD \u2194 USDC through the PSM",
84309
+ description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
84310
+ inputSchema: {
84311
+ direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = pay USDC, get UCD (contract swap); 'to-usdc' = pay UCD, get USDC back (contract redeem)"),
84312
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
84313
+ confirmed: confirmedSchema2
84314
+ },
84315
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84316
+ },
84317
+ async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84318
+ const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84319
+ const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
84320
+ const gate = requireConfirmation(
84321
+ confirmed,
84322
+ `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
84323
+ );
84324
+ if (gate) return gate;
84325
+ const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
84326
+ if (problem) return validationFailed(problem);
84327
+ const b = getB();
84328
+ if (!b.ok) return renderError(b.error);
84329
+ return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
84330
+ })
84331
+ );
84332
+ }
84076
84333
 
84077
- - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
84078
- - first-setup \u2014 zero to ready by conversation (authorization choice included)
84079
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
84080
- - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
84081
- - fees \u2014 the two fee models, plainly
84082
- - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
84083
- - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
84084
- - safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today
84085
- - delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today
84086
- - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
84087
- - switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated
84088
- - connector \u2014 the hosted claude.ai tier (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. Status: implemented, NOT yet publicly served
84089
- - troubleshooting \u2014 error codes in plain words, with the real remedies
84090
- - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
84091
- - reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
84334
+ // src/tools/mock-control.ts
84335
+ var import_zod5 = require("zod");
84336
+ var ACTIONS = [
84337
+ "submit-deposit",
84338
+ "confirm-deposit",
84339
+ "confirm-spend-consumed",
84340
+ "advance-time",
84341
+ "set-btc-price",
84342
+ "set-paused",
84343
+ "set-wallet",
84344
+ "liquidate",
84345
+ "deploy-safe",
84346
+ "revoke-agent",
84347
+ "inject-fault",
84348
+ "clear-fault",
84349
+ "psm-set-paused",
84350
+ "psm-set-redeem-enabled",
84351
+ "psm-set-reserves",
84352
+ "psm-set-fees",
84353
+ "psm-mint-usdc"
84354
+ ];
84355
+ function requireField(value, name, action) {
84356
+ if (value === void 0) {
84357
+ throw new Error(`action '${action}' requires '${name}'`);
84358
+ }
84359
+ return value;
84360
+ }
84361
+ function run(control, a, chainId) {
84362
+ switch (a.action) {
84363
+ case "submit-deposit": {
84364
+ const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
84365
+ return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
84366
+ }
84367
+ case "confirm-deposit": {
84368
+ const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
84369
+ return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
84370
+ }
84371
+ case "confirm-spend-consumed": {
84372
+ control.confirmSpendConsumed(
84373
+ requireField(a.txid, "txid", a.action),
84374
+ requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
84375
+ requireField(a.confirmations, "confirmations", a.action)
84376
+ );
84377
+ return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
84378
+ }
84379
+ case "advance-time": {
84380
+ control.advanceTime(requireField(a.seconds, "seconds", a.action));
84381
+ return { simulated: "virtual clock advanced", seconds: a.seconds };
84382
+ }
84383
+ case "set-btc-price": {
84384
+ control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
84385
+ return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
84386
+ }
84387
+ case "set-paused": {
84388
+ control.setPaused(requireField(a.paused, "paused", a.action));
84389
+ return { simulated: "protocol pause flag set", paused: a.paused };
84390
+ }
84391
+ case "set-wallet": {
84392
+ control.setWalletStance(requireField(a.stance, "stance", a.action));
84393
+ return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
84394
+ }
84395
+ case "liquidate": {
84396
+ control.liquidate(requireField(a.positionId, "positionId", a.action));
84397
+ return { simulated: "liquidation executed", positionId: a.positionId };
84398
+ }
84399
+ case "deploy-safe": {
84400
+ const safe = control.deploySafe({
84401
+ owners: requireField(a.owners, "owners", a.action),
84402
+ threshold: requireField(a.threshold, "threshold", a.action),
84403
+ chainId
84404
+ });
84405
+ return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
84406
+ }
84407
+ case "revoke-agent": {
84408
+ const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
84409
+ return {
84410
+ simulated: "agent revoked and BURNED forever (AR-1 \u2014 plan 09 test lever; on the real protocol the owners or the deny-only registrar revoke)",
84411
+ ...r
84412
+ };
84413
+ }
84414
+ case "inject-fault": {
84415
+ control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
84416
+ return { simulated: "fault armed", faultKey: a.faultKey };
84417
+ }
84418
+ case "clear-fault": {
84419
+ control.clearFault(requireField(a.faultKey, "faultKey", a.action));
84420
+ return { simulated: "fault cleared", faultKey: a.faultKey };
84421
+ }
84422
+ case "psm-set-paused": {
84423
+ control.psmSetPaused(requireField(a.paused, "paused", a.action));
84424
+ return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
84425
+ }
84426
+ case "psm-set-redeem-enabled": {
84427
+ control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
84428
+ return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
84429
+ }
84430
+ case "psm-set-reserves": {
84431
+ control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
84432
+ return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
84433
+ }
84434
+ case "psm-mint-usdc": {
84435
+ const r = control.psmMintUsdc(
84436
+ requireField(a.holder, "holder", a.action),
84437
+ requireField(a.usdcUnits, "usdcUnits", a.action)
84438
+ );
84439
+ return {
84440
+ simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
84441
+ holder: a.holder,
84442
+ minted: a.usdcUnits,
84443
+ newBalanceUnits: r.newBalanceUnits
84444
+ };
84445
+ }
84446
+ case "psm-set-fees": {
84447
+ control.psmSetFees({
84448
+ ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
84449
+ ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
84450
+ });
84451
+ return {
84452
+ simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
84453
+ ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
84454
+ ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
84455
+ };
84456
+ }
84457
+ }
84458
+ }
84459
+ function registerMockControlTool(server, control, chainId = 1337) {
84460
+ registerBoundaryTool(
84461
+ server,
84462
+ "mock_control",
84463
+ {
84464
+ title: "SIMULATOR control (mock world only)",
84465
+ description: "Drive the simulated rest-of-the-world of the MOCK protocol: broadcast/confirm BTC deposits, confirm reserved spends, advance the virtual clock, set the oracle price, pause the protocol, liquidate, arm/clear faults, and drive the simulated PSM (pause, redeemEnabled, reserves, fees, practice-USDC mint). This tool exists ONLY against the mock adapter \u2014 nothing here touches or ever exists on the real protocol.",
84466
+ inputSchema: {
84467
+ action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
84468
+ positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
84469
+ txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
84470
+ sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
84471
+ confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
84472
+ invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
84473
+ seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
84474
+ priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
84475
+ paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
84476
+ stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
84477
+ owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
84478
+ threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
84479
+ safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
84480
+ faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
84481
+ faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
84482
+ enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
84483
+ reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
84484
+ entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
84485
+ exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
84486
+ holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
84487
+ usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
84488
+ },
84489
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
84490
+ },
84491
+ async (args) => guarded(async () => {
84492
+ let result;
84493
+ try {
84494
+ result = run(control, args, chainId);
84495
+ } catch (e) {
84496
+ return validationFailed(e.message);
84497
+ }
84498
+ if (result === void 0) {
84499
+ return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
84500
+ }
84501
+ return { content: [{ type: "text", text: serialize(result) }] };
84502
+ })
84503
+ );
84504
+ }
84092
84505
 
84093
- Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
84094
- selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
84095
- signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
84096
- and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
84097
- only mainnet is real money.`;
84506
+ // src/tools/signer.ts
84507
+ var import_zod6 = require("zod");
84508
+ var import_ethers42 = require("ethers");
84509
+ var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
84510
+ var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
84511
+ var EXTERNAL_ONLY_MODES = ["external"];
84512
+ var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
84513
+ function looksSecretShaped(value) {
84514
+ return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
84515
+ }
84516
+ var SECRET_REFUSAL = "That value looks like a password or key. NEVER paste secrets into the conversation \u2014 they would enter the model context and transcripts. To provide keystore material, say 'unlock my keystore' (a secure local page opens and the password goes directly to the server), or set DH_KEYSTORE_PATH/DH_KEYSTORE_PASSWORD in the server environment.";
84517
+ function registerSignerTool(server, getRuntime, opts) {
84518
+ const externalOnly = opts?.externalOnly === true;
84519
+ const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
84520
+ const description = externalOnly ? "Inspect or manage how operations are authorized. This build is EXTERNAL-WALLET-ONLY: every operation is approved in YOUR OWN wallet (browser wallet, or mobile via WalletConnect); the server can never sign by itself. Actions: 'status' (what is active, what is connected \u2014 start here), 'use' (mode 'external' \u2014 the only mode this build offers), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'connect' (run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out: the FULL wallet flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect." : "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat), 'connect' (external mode, real protocol: run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out of the external wallet: the FULL flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect.";
84521
+ registerBoundaryTool(
84522
+ server,
84523
+ "signer_setup",
84524
+ {
84525
+ title: "Choose how operations are authorized",
84526
+ description,
84527
+ inputSchema: {
84528
+ action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
84529
+ mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
84530
+ ...externalOnly ? {} : {
84531
+ safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
84532
+ }
84533
+ },
84534
+ annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
84535
+ },
84536
+ async ({ action, mode, safeAddress }) => guarded(async () => {
84537
+ const runtime = getRuntime();
84538
+ if (!runtime) {
84539
+ return renderError(
84540
+ boundaryError(
84541
+ "SIGNER_UNAVAILABLE",
84542
+ "no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
84543
+ )
84544
+ );
84545
+ }
84546
+ const { manager, bridge } = runtime;
84547
+ if (mode !== void 0 && !offeredModes.includes(mode)) {
84548
+ return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
84549
+ }
84550
+ if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
84551
+ return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
84552
+ }
84553
+ if (action === "status") {
84554
+ await bridge.start();
84555
+ const s = manager.status();
84556
+ return ok({
84557
+ ...s,
84558
+ // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
84559
+ // identity is known. borrower = a persisted binding; candidate = a live
84560
+ // wallet connection in THIS process only.
84561
+ identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
84562
+ approvalPageUrl: bridge.url(),
84563
+ hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
84564
+ });
84565
+ }
84566
+ if (action === "use") {
84567
+ if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
84568
+ const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
84569
+ if (!r.ok) return validationFailed(r.reason);
84570
+ if (mode === "safe-module") {
84571
+ const s = manager.status();
84572
+ return ok({
84573
+ mode,
84574
+ safe: s.safe,
84575
+ agent: s.keystoreAddress,
84576
+ next: "This session operates AS the Safe with DELEGATION: the keystore key is the AGENT. One owner ceremony installs it (loan_delegation_setup \u2014 enables the module, binds the agent, pre-approves BTC destinations); afterwards create/mint/pay/extend run agent-solo (per-position grants via loan_delegation_grant, a quorum signature). The agent can NEVER withdraw alone, add destinations, or manage the module \u2014 withdrawals still gather the owners for a short signing burst. See guide topic 'delegation'."
84577
+ });
84578
+ }
84579
+ if (mode === "safe") {
84580
+ const s = manager.status();
84581
+ return ok({
84582
+ mode,
84583
+ safe: s.safe,
84584
+ next: "This session now operates AS the Safe. Operations are authorized by owner signatures (this phase: the local keystore owner signs; it also submits transactions). BTC withdrawals additionally need the destination allowlisted first \u2014 see loan_allowlist_destination."
84585
+ });
84586
+ }
84587
+ if (mode === "external") {
84588
+ await bridge.start();
84589
+ return ok({
84590
+ mode,
84591
+ approvalPageUrl: bridge.url(),
84592
+ next: "Open the approval page and connect your wallet (browser extension, or 'Use a mobile wallet' for WalletConnect). Each operation will then ask for your approval there."
84593
+ });
84594
+ }
84595
+ return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
84596
+ }
84597
+ if (action === "connect") {
84598
+ if (!runtime.connect) {
84599
+ return validationFailed(
84600
+ "action 'connect' applies to the real protocol's external mode (lit-ops login). This adapter has no separate login step \u2014 pick a mode with 'use' and writes will ceremony as needed."
84601
+ );
84602
+ }
84603
+ const r = await runtime.connect();
84604
+ if (!r.ok) return validationFailed(r.reason);
84605
+ const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
84606
+ return ok({
84607
+ connected: true,
84608
+ address: r.address,
84609
+ login,
84610
+ next: (login === "cached-session" ? "Logged in via a still-valid CACHED session \u2014 no wallet signature was requested. To force a full logout first, use 'disconnect'. " : "Logged in with a FRESH wallet signature. ") + "Authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
84611
+ });
84612
+ }
84613
+ if (action === "disconnect") {
84614
+ if (!runtime.disconnect) {
84615
+ return validationFailed(
84616
+ "this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
84617
+ );
84618
+ }
84619
+ const report = await runtime.disconnect();
84620
+ const f = report.flushed;
84621
+ const tokenLine = !report.hadLogin ? "login token: none existed" : f.upstreamRevoked >= f.loginSessions ? `login token: discarded from memory AND revoked at the service (${f.upstreamRevoked} revoked)` : `login token: discarded from this process's memory; ${f.upstreamRevoked}/${f.loginSessions} could be revoked at the service \u2014 an unrevoked token stays valid upstream until its natural expiry (it was never stored on disk)`;
84622
+ return ok({
84623
+ disconnected: true,
84624
+ mode: manager.mode(),
84625
+ flushed: {
84626
+ ...f,
84627
+ note: tokenLine
84628
+ },
84629
+ whatThisServerCannotRevoke: "Your wallet's own site permission for the approval-page origin \u2014 revoke it wallet-side (MetaMask: Settings \u2192 Connections / Connected sites \u2192 remove this site).",
84630
+ // Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
84631
+ // relationship; the OAuth session is a separate thing with its own revocation.
84632
+ // Neither claims to do the other's job.
84633
+ ...bridge.isHosted() ? {
84634
+ oauthSession: "This disconnect ends the WALLET relationship only. Your assistant's connection to this MCP server (the OAuth session) stays alive until you revoke it on the claude.ai side (connector settings) \u2014 and revoking THAT does not disconnect your wallet here."
84635
+ } : {},
84636
+ next: `Wallet disconnected \u2014 mode stays '${manager.mode()}'. Reconnecting requires opening the approval page again (signer_setup 'status' shows the link) and a fresh wallet signature ('connect').`
84637
+ });
84638
+ }
84639
+ if (action === "reset-borrower") {
84640
+ manager.resetBorrower();
84641
+ return ok({
84642
+ reset: true,
84643
+ next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower. NOTE: this is an identity swap, NOT a disconnect \u2014 any wallet connection and login session remain alive; use 'disconnect' to log out fully."
84644
+ });
84645
+ }
84646
+ await bridge.start();
84647
+ const unlockUrl = bridge.unlockUrl();
84648
+ return ok({
84649
+ unlockPageUrl: unlockUrl,
84650
+ next: "Open this local page and enter the keystore password THERE (never in chat). Paste an encrypted keystore JSON or generate a fresh one, then say 'use keystore'."
84651
+ });
84652
+ })
84653
+ );
84654
+ }
84655
+ function ok(data) {
84656
+ return { content: [{ type: "text", text: serialize(data) }] };
84657
+ }
84098
84658
 
84099
84659
  // src/tools/guide.ts
84100
- function registerGuideTool(server) {
84660
+ var import_zod7 = require("zod");
84661
+ function registerGuideTool(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
84662
+ const content = buildGuideContent(deployment);
84663
+ const index = buildGuideIndex(deployment);
84101
84664
  registerBoundaryTool(
84102
84665
  server,
84103
84666
  "guide",
@@ -84111,26 +84674,31 @@ function registerGuideTool(server) {
84111
84674
  },
84112
84675
  async ({ topic }) => guarded(async () => {
84113
84676
  if (topic === void 0 || topic === "") {
84114
- return { content: [{ type: "text", text: GUIDE_INDEX }] };
84677
+ return { content: [{ type: "text", text: index }] };
84115
84678
  }
84116
84679
  if (!GUIDE_TOPICS.includes(topic)) {
84117
84680
  return validationFailed(`unknown guide topic '${topic}' \u2014 available: ${GUIDE_TOPICS.join(" | ")}`);
84118
84681
  }
84119
- return { content: [{ type: "text", text: GUIDE_CONTENT[topic] }] };
84682
+ return { content: [{ type: "text", text: content[topic] }] };
84120
84683
  })
84121
84684
  );
84122
84685
  }
84123
- function registerGuideResources(server) {
84686
+ function registerGuideResources(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
84687
+ const content = buildGuideContent(deployment);
84688
+ const index = buildGuideIndex(deployment);
84124
84689
  for (const topic of GUIDE_TOPICS) {
84125
84690
  server.resource(`guide-${topic}`, `guide://${topic}`, async () => ({
84126
- contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: GUIDE_CONTENT[topic] }]
84691
+ contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: content[topic] }]
84127
84692
  }));
84128
84693
  }
84129
84694
  server.resource("guide-index", "guide://index", async () => ({
84130
- contents: [{ uri: "guide://index", mimeType: "text/markdown", text: GUIDE_INDEX }]
84695
+ contents: [{ uri: "guide://index", mimeType: "text/markdown", text: index }]
84131
84696
  }));
84132
84697
  }
84133
- function registerGuidePrompts(server) {
84698
+ function onboardAuthorizationLine(deployment) {
84699
+ return deployment.signerModes.includes("keystore") ? "if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. " : "this build authorizes with MY OWN WALLET and nothing else, so offer the wallet walkthrough (guide 'connect-wallet') \u2014 never an automatic-signing alternative it does not have \u2014 and then help me open my first position. ";
84700
+ }
84701
+ function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
84134
84702
  server.prompt(
84135
84703
  "onboard-me",
84136
84704
  "Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
@@ -84140,7 +84708,7 @@ function registerGuidePrompts(server) {
84140
84708
  role: "user",
84141
84709
  content: {
84142
84710
  type: "text",
84143
- text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. Ask before every operation; never assume confirmation."
84711
+ text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; " + onboardAuthorizationLine(deployment) + "Ask before every operation; never assume confirmation."
84144
84712
  }
84145
84713
  }
84146
84714
  ]
@@ -84376,8 +84944,10 @@ function registerBoundaryInfoResource(server, getB) {
84376
84944
  );
84377
84945
  }
84378
84946
 
84947
+ // src/version.ts
84948
+ var SERVER_VERSION = "0.5.11";
84949
+
84379
84950
  // src/server.ts
84380
- var SERVER_VERSION = "0.5.9";
84381
84951
  var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
84382
84952
  var CONNECTOR_INSTRUCTIONS = SERVER_INSTRUCTIONS + " HOSTED CONNECTOR TIER: this server is the hosted claude.ai connector. Signer modes are external-wallet ONLY \u2014 keystore mode is ABSENT from this build (structurally, not disabled); the server never holds a key, and every fund-moving action needs a fresh signature from the user's own wallet. Each tenant's world is isolated by wallet identity; network_switch moves ONLY this tenant, within the networks this deployment serves (the refusal states the rollout truth). The login session lives in server memory only \u2014 a server restart or idle eviction means signing in again; that is the no-data-at-rest property, not a fault. Trust ledger and cadence: guide topic 'connector'.";
84383
84953
  function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
@@ -84397,9 +84967,9 @@ function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
84397
84967
  registerPositionResource(server, getB);
84398
84968
  registerProtocolResources(server, getB);
84399
84969
  registerBoundaryInfoResource(server, getB);
84400
- registerGuideTool(server);
84401
- registerGuideResources(server);
84402
- registerGuidePrompts(server);
84970
+ registerGuideTool(server, deps.deployment);
84971
+ registerGuideResources(server, deps.deployment);
84972
+ registerGuidePrompts(server, deps.deployment);
84403
84973
  if (deps.mockControl) {
84404
84974
  registerMockControlTool(server, deps.mockControl, deps.chainId);
84405
84975
  }
@@ -84417,8 +84987,43 @@ var DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1e3;
84417
84987
  var DEFAULT_WORLD_IDLE_MS = 60 * 60 * 1e3;
84418
84988
  var DEFAULT_TENANT_PER_MIN = 120;
84419
84989
  var DEFAULT_GLOBAL_PER_MIN = 600;
84990
+ var DEFAULT_MAX_TENANTS = 200;
84991
+ var DEFAULT_MAX_SESSIONS_PER_TENANT = 16;
84992
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
84993
+ var DEFAULT_TRUST_PROXY_HOPS = 1;
84994
+ function normalizePublicOrigin(raw) {
84995
+ const trimmed = raw.trim().replace(/\/+$/, "");
84996
+ let url2;
84997
+ try {
84998
+ url2 = new URL(trimmed);
84999
+ } catch {
85000
+ throw new Error(
85001
+ `connector: publicOrigin is not a valid URL (${trimmed.length} chars). The value is not echoed here \u2014 see below for why.`
85002
+ );
85003
+ }
85004
+ const problems = [];
85005
+ if (url2.protocol !== "https:" && url2.protocol !== "http:") problems.push(`scheme '${url2.protocol}' (want http or https)`);
85006
+ if (url2.username !== "" || url2.password !== "") problems.push("embedded credentials");
85007
+ if (url2.pathname !== "/" && url2.pathname !== "") problems.push("a path");
85008
+ if (url2.search !== "") problems.push("a query string");
85009
+ if (url2.hash !== "") problems.push("a fragment");
85010
+ if (problems.length > 0) {
85011
+ throw new Error(
85012
+ `connector: publicOrigin must be a bare origin (scheme + host only) \u2014 found ${problems.join(", ")} in '${url2.protocol}//${url2.host}\u2026' (value redacted). It becomes the OAuth issuer and the base of every approval-page URL, so a wrong shape mints links that fail their own Host check rather than degrading.`
85013
+ );
85014
+ }
85015
+ return url2.origin;
85016
+ }
85017
+ function requireSafeCount(value, fallback, name, min) {
85018
+ if (value === void 0) return fallback;
85019
+ if (!Number.isSafeInteger(value) || value < min) {
85020
+ throw new Error(`connector: ${name}=${String(value)} must be a safe integer >= ${min}`);
85021
+ }
85022
+ return value;
85023
+ }
84420
85024
  var RATE_WINDOW_MS = 60 * 1e3;
84421
- function composeConnector(opts, publicOrigin) {
85025
+ function composeConnector(opts, rawPublicOrigin) {
85026
+ const publicOrigin = normalizePublicOrigin(rawPublicOrigin);
84422
85027
  const allowedNetworks = opts.allowedNetworks ?? ["sepolia"];
84423
85028
  if (allowedNetworks.length === 0) throw new Error("connector service: allowedNetworks must name at least one network");
84424
85029
  const launchNetwork = allowedNetworks[0];
@@ -84427,6 +85032,10 @@ function composeConnector(opts, publicOrigin) {
84427
85032
  const worldIdleMs = opts.idle?.worldMs ?? DEFAULT_WORLD_IDLE_MS;
84428
85033
  const tenantPerMin = opts.rateLimits?.tenantPerMin ?? DEFAULT_TENANT_PER_MIN;
84429
85034
  const globalPerMin = opts.rateLimits?.globalPerMin ?? DEFAULT_GLOBAL_PER_MIN;
85035
+ const maxTenants = requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
85036
+ const trustProxyHops = requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
85037
+ const maxSessionsPerTenant = requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
85038
+ const maxBodyBytes = requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
84430
85039
  const worlds = /* @__PURE__ */ new Map();
84431
85040
  const readyWorlds = /* @__PURE__ */ new Map();
84432
85041
  const sessions = /* @__PURE__ */ new Map();
@@ -84456,7 +85065,7 @@ function composeConnector(opts, publicOrigin) {
84456
85065
  }
84457
85066
  async function buildWorld(tenantKey) {
84458
85067
  const stores = /* @__PURE__ */ new Map();
84459
- const mountId = (0, import_node_crypto9.randomUUID)().replaceAll("-", "");
85068
+ const mountId = (0, import_node_crypto10.randomUUID)().replaceAll("-", "");
84460
85069
  const overrides = {
84461
85070
  externalOnly: true,
84462
85071
  allowedNetworks,
@@ -84498,6 +85107,17 @@ function composeConnector(opts, publicOrigin) {
84498
85107
  process.stderr.write(`[dh-mcp-connector] ${why}: world for tenant ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} disposed
84499
85108
  `);
84500
85109
  }
85110
+ function tenantsWithSessions() {
85111
+ const held = /* @__PURE__ */ new Set();
85112
+ for (const session of sessions.values()) held.add(session.tenant);
85113
+ return held;
85114
+ }
85115
+ function isReclaimable(tenantKey, world, held) {
85116
+ if (held.has(tenantKey)) return false;
85117
+ const bridge = world.deps.signer?.bridge;
85118
+ if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85119
+ return true;
85120
+ }
84501
85121
  function sweepService() {
84502
85122
  const now = clock();
84503
85123
  for (const [sid, session] of [...sessions]) {
@@ -84506,18 +85126,43 @@ function composeConnector(opts, publicOrigin) {
84506
85126
  void session.transport.close().catch(() => void 0);
84507
85127
  }
84508
85128
  }
85129
+ const held = tenantsWithSessions();
84509
85130
  for (const [tenantKey, world] of [...readyWorlds]) {
84510
- const hasSession = [...sessions.values()].some((s) => s.tenant === tenantKey);
84511
- if (hasSession) continue;
84512
- const bridge = world.deps.signer?.bridge;
84513
- if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) continue;
85131
+ if (!isReclaimable(tenantKey, world, held)) continue;
84514
85132
  if (now - (lastActivity.get(tenantKey) ?? 0) <= worldIdleMs) continue;
84515
85133
  dropWorld(tenantKey, world, "idle eviction");
84516
85134
  }
84517
85135
  }
85136
+ function reclaimIdleWorld() {
85137
+ const held = tenantsWithSessions();
85138
+ let victimKey = null;
85139
+ let victim = null;
85140
+ let oldest = Number.POSITIVE_INFINITY;
85141
+ for (const [tenantKey, world] of readyWorlds) {
85142
+ if (!isReclaimable(tenantKey, world, held)) continue;
85143
+ const activeAt = lastActivity.get(tenantKey) ?? 0;
85144
+ if (activeAt < oldest) {
85145
+ oldest = activeAt;
85146
+ victimKey = tenantKey;
85147
+ victim = world;
85148
+ }
85149
+ }
85150
+ if (victimKey === null || victim === null) return false;
85151
+ dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
85152
+ return true;
85153
+ }
85154
+ class TenantCapacityError extends Error {
85155
+ }
84518
85156
  function worldFor(tenantKey) {
84519
85157
  let w = worlds.get(tenantKey);
84520
85158
  if (!w) {
85159
+ if (worlds.size >= maxTenants && !reclaimIdleWorld()) {
85160
+ return Promise.reject(
85161
+ new TenantCapacityError(
85162
+ `this connector is at its tenant ceiling (${maxTenants} concurrent wallets) and every slot is held by an ACTIVE tenant \u2014 an open MCP session, a live approval page, or a pending signature. Idle slots are reclaimed automatically as soon as one frees; retry shortly`
85163
+ )
85164
+ );
85165
+ }
84521
85166
  w = buildWorld(tenantKey).catch((e) => {
84522
85167
  worlds.delete(tenantKey);
84523
85168
  throw e;
@@ -84526,16 +85171,75 @@ function composeConnector(opts, publicOrigin) {
84526
85171
  }
84527
85172
  return w;
84528
85173
  }
85174
+ function evictExcessSessions(tenantKey) {
85175
+ const mine = [...sessions].filter(([, s]) => s.tenant === tenantKey).sort((a, b) => a[1].lastSeen - b[1].lastSeen);
85176
+ for (let i = 0; i <= mine.length - maxSessionsPerTenant; i += 1) {
85177
+ const [sid, session] = mine[i];
85178
+ sessions.delete(sid);
85179
+ void session.transport.close().catch(() => void 0);
85180
+ process.stderr.write(
85181
+ `[dh-mcp-connector] session cap (${maxSessionsPerTenant}/tenant): oldest session for ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} closed to admit a new one
85182
+ `
85183
+ );
85184
+ }
85185
+ }
84529
85186
  function deny(res, status, message) {
84530
85187
  res.writeHead(status, { "content-type": "application/json" }).end(
84531
85188
  JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message }, id: null })
84532
85189
  );
84533
85190
  }
84534
- async function readJsonBody(req) {
84535
- let raw = "";
84536
- req.setEncoding("utf8");
84537
- for await (const chunk of req) raw += chunk;
84538
- return raw.length === 0 ? void 0 : JSON.parse(raw);
85191
+ function readBodyText(req) {
85192
+ return new Promise((resolve, reject) => {
85193
+ let raw = "";
85194
+ let bytes = 0;
85195
+ let settled = false;
85196
+ req.setEncoding("utf8");
85197
+ req.on("data", (chunk) => {
85198
+ if (settled) return;
85199
+ bytes += Buffer.byteLength(chunk, "utf8");
85200
+ if (bytes > maxBodyBytes) {
85201
+ settled = true;
85202
+ req.pause();
85203
+ resolve({ overflow: bytes });
85204
+ return;
85205
+ }
85206
+ raw += chunk;
85207
+ });
85208
+ req.on("end", () => {
85209
+ if (settled) return;
85210
+ settled = true;
85211
+ resolve({ text: raw });
85212
+ });
85213
+ req.on("error", (e) => {
85214
+ if (settled) return;
85215
+ settled = true;
85216
+ reject(e);
85217
+ });
85218
+ });
85219
+ }
85220
+ function refuseOversizedBody(req, res, why) {
85221
+ res.setHeader("Connection", "close");
85222
+ deny(res, 413, `request body too large (${why}) \u2014 this MCP endpoint accepts at most ${maxBodyBytes} bytes per JSON-RPC message`);
85223
+ res.once("finish", () => req.destroy());
85224
+ }
85225
+ async function readCappedBody(req, res) {
85226
+ const declared = Number(req.headers["content-length"]);
85227
+ if (Number.isFinite(declared) && declared > maxBodyBytes) {
85228
+ refuseOversizedBody(req, res, `declared ${declared} bytes`);
85229
+ return null;
85230
+ }
85231
+ const read = await readBodyText(req);
85232
+ if ("overflow" in read) {
85233
+ refuseOversizedBody(req, res, `exceeded the cap after ${read.overflow} bytes`);
85234
+ return null;
85235
+ }
85236
+ if (read.text.length === 0) return { body: void 0 };
85237
+ try {
85238
+ return { body: JSON.parse(read.text) };
85239
+ } catch {
85240
+ deny(res, 400, "request body is not valid JSON");
85241
+ return null;
85242
+ }
84539
85243
  }
84540
85244
  async function handle(req, res) {
84541
85245
  const url2 = new URL(req.url ?? "/", "http://connector.local");
@@ -84584,6 +85288,12 @@ function composeConnector(opts, publicOrigin) {
84584
85288
  return;
84585
85289
  }
84586
85290
  session.lastSeen = clock();
85291
+ if (req.method === "POST") {
85292
+ const read2 = await readCappedBody(req, res);
85293
+ if (!read2) return;
85294
+ await session.transport.handleRequest(req, res, read2.body);
85295
+ return;
85296
+ }
84587
85297
  await session.transport.handleRequest(req, res);
84588
85298
  return;
84589
85299
  }
@@ -84591,22 +85301,29 @@ function composeConnector(opts, publicOrigin) {
84591
85301
  deny(res, 400, "missing mcp-session-id \u2014 initialize first");
84592
85302
  return;
84593
85303
  }
84594
- let body;
84595
- try {
84596
- body = await readJsonBody(req);
84597
- } catch {
84598
- deny(res, 400, "request body is not valid JSON");
84599
- return;
84600
- }
85304
+ const read = await readCappedBody(req, res);
85305
+ if (!read) return;
85306
+ const body = read.body;
84601
85307
  if (!(0, import_types4.isInitializeRequest)(body)) {
84602
85308
  deny(res, 400, "missing mcp-session-id \u2014 the only session-less request is initialize");
84603
85309
  return;
84604
85310
  }
84605
- const world = await worldFor(tenantKey);
85311
+ let world;
85312
+ try {
85313
+ world = await worldFor(tenantKey);
85314
+ } catch (e) {
85315
+ if (e instanceof TenantCapacityError) {
85316
+ res.setHeader("Retry-After", "60");
85317
+ deny(res, 503, e.message);
85318
+ return;
85319
+ }
85320
+ throw e;
85321
+ }
84606
85322
  const mcp = createServer2(world.deps, CONNECTOR_INSTRUCTIONS);
84607
85323
  const transport = new import_streamableHttp.StreamableHTTPServerTransport({
84608
- sessionIdGenerator: () => (0, import_node_crypto9.randomUUID)(),
85324
+ sessionIdGenerator: () => (0, import_node_crypto10.randomUUID)(),
84609
85325
  onsessioninitialized: (sessionId) => {
85326
+ evictExcessSessions(tenantKey);
84610
85327
  sessions.set(sessionId, { transport, tenant: tenantKey, lastSeen: clock() });
84611
85328
  }
84612
85329
  });
@@ -84629,6 +85346,7 @@ function composeConnector(opts, publicOrigin) {
84629
85346
  });
84630
85347
  }
84631
85348
  const app = (0, import_express.default)();
85349
+ app.set("trust proxy", trustProxyHops);
84632
85350
  app.use((_req, res, next) => {
84633
85351
  if (!allowGlobal()) {
84634
85352
  deny(res, 429, `rate limit: this connector exceeded ${globalPerMin} requests/minute across all clients \u2014 a shared-capacity protection; wait for the minute window to pass and retry`);
@@ -84687,6 +85405,17 @@ function composeConnector(opts, publicOrigin) {
84687
85405
  const r = siwe.wcStatus(String(req.query["flowId"] ?? ""));
84688
85406
  res.status(r.status).json(r.body);
84689
85407
  });
85408
+ const authMd = renderAuthMd({
85409
+ publicOrigin,
85410
+ networks: allowedNetworks,
85411
+ walletConnectEnabled: wcLeg !== void 0
85412
+ });
85413
+ app.get("/auth.md", (_req, res) => {
85414
+ res.setHeader("X-Content-Type-Options", "nosniff");
85415
+ res.setHeader("Referrer-Policy", "no-referrer");
85416
+ res.setHeader("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'; base-uri 'none'");
85417
+ res.type("text/markdown; charset=utf-8").send(authMd);
85418
+ });
84690
85419
  app.get("/.well-known/oauth-protected-resource", (_req, res) => {
84691
85420
  res.json({
84692
85421
  resource: `${publicOrigin}/mcp`,
@@ -84747,6 +85476,11 @@ function composeConnector(opts, publicOrigin) {
84747
85476
  };
84748
85477
  }
84749
85478
  async function startConnectorService(opts) {
85479
+ if (opts.publicOrigin !== void 0) normalizePublicOrigin(opts.publicOrigin);
85480
+ requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
85481
+ requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
85482
+ requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
85483
+ requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
84750
85484
  const httpServer = (0, import_node_http.createServer)();
84751
85485
  const host = opts.host ?? "127.0.0.1";
84752
85486
  await new Promise((resolve, reject) => {
@@ -84755,7 +85489,8 @@ async function startConnectorService(opts) {
84755
85489
  });
84756
85490
  const addr = httpServer.address();
84757
85491
  if (addr === null || typeof addr === "string") throw new Error("connector service: no bound address");
84758
- const publicOrigin = opts.publicOrigin ?? `http://${host}:${addr.port}`;
85492
+ const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
85493
+ const publicOrigin = opts.publicOrigin ?? `http://${authority}:${addr.port}`;
84759
85494
  const composed = composeConnector(opts, publicOrigin);
84760
85495
  httpServer.on("request", composed.app);
84761
85496
  return {
@@ -84792,11 +85527,20 @@ async function main() {
84792
85527
  }
84793
85528
  }
84794
85529
  const publicOrigin = process.env["DH_CONNECTOR_PUBLIC_ORIGIN"];
85530
+ const rawHops = process.env["DH_CONNECTOR_TRUST_PROXY_HOPS"]?.trim();
85531
+ let trustProxyHops;
85532
+ if (rawHops !== void 0 && rawHops !== "") {
85533
+ trustProxyHops = Number(rawHops);
85534
+ if (!Number.isSafeInteger(trustProxyHops) || trustProxyHops < 0) {
85535
+ throw new Error(`DH_CONNECTOR_TRUST_PROXY_HOPS='${rawHops}' must be a non-negative integer`);
85536
+ }
85537
+ }
84795
85538
  const service = await startConnectorService({
84796
85539
  env: process.env,
84797
85540
  port,
84798
85541
  ...process.env["DH_CONNECTOR_HOST"] ? { host: process.env["DH_CONNECTOR_HOST"] } : {},
84799
85542
  ...publicOrigin ? { publicOrigin } : {},
85543
+ ...trustProxyHops !== void 0 ? { trustProxyHops } : {},
84800
85544
  allowedNetworks: networks2
84801
85545
  });
84802
85546
  process.stderr.write(