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