@gvnrdao/dh-mcp 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/connector.js CHANGED
@@ -617,7 +617,7 @@ var require_utils = __commonJS({
617
617
  exports2.createHasher = createHasher2;
618
618
  exports2.createOptHasher = createOptHasher;
619
619
  exports2.createXOFer = createXOFer;
620
- exports2.randomBytes = randomBytes4;
620
+ exports2.randomBytes = randomBytes5;
621
621
  var crypto_1 = require_cryptoNode();
622
622
  function isBytes2(a) {
623
623
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -815,7 +815,7 @@ var require_utils = __commonJS({
815
815
  exports2.wrapConstructor = createHasher2;
816
816
  exports2.wrapConstructorWithOpts = createOptHasher;
817
817
  exports2.wrapXOFConstructorWithOpts = createXOFer;
818
- function randomBytes4(bytesLength = 32) {
818
+ function randomBytes5(bytesLength = 32) {
819
819
  if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
820
820
  return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
821
821
  }
@@ -40619,19 +40619,428 @@ var net = __toESM(require("net"));
40619
40619
 
40620
40620
  // src/connector/service.ts
40621
40621
  var import_node_http = require("http");
40622
- var import_node_crypto9 = require("crypto");
40622
+ var import_node_crypto10 = require("crypto");
40623
40623
  var import_express = __toESM(require("express"));
40624
40624
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
40625
40625
  var import_router = require("@modelcontextprotocol/sdk/server/auth/router.js");
40626
40626
  var import_types4 = require("@modelcontextprotocol/sdk/types.js");
40627
40627
 
40628
- // src/connector/siwe-oauth.ts
40628
+ // src/connector/auth-md.ts
40629
+ var CHAIN_IDS = { mainnet: 1, sepolia: 11155111 };
40630
+ function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled }) {
40631
+ const origin2 = publicOrigin.replace(/\/+$/, "");
40632
+ const launchNetwork = networks2[0];
40633
+ if (launchNetwork === void 0) {
40634
+ throw new Error("renderAuthMd: networks must name at least one network");
40635
+ }
40636
+ const chainId = CHAIN_IDS[launchNetwork];
40637
+ if (chainId === void 0) {
40638
+ throw new Error(
40639
+ `renderAuthMd: no chain id known for network '${launchNetwork}' \u2014 allowed: ${Object.keys(CHAIN_IDS).join(", ")}`
40640
+ );
40641
+ }
40642
+ const isMainnet = launchNetwork === "mainnet";
40643
+ const wcLine = walletConnectEnabled ? "" : " **Mobile WalletConnect sign-in is not enabled on this deployment** \u2014 browser extension or own-key only.";
40644
+ const agentAuth = {
40645
+ agent_auth: {
40646
+ skill: "operate-position",
40647
+ register_uri: `${origin2}/register`,
40648
+ authorization_servers: [`${origin2}/`],
40649
+ resource: `${origin2}/mcp`,
40650
+ methods: [
40651
+ {
40652
+ type: "oauth2",
40653
+ registration: "rfc7591-dynamic-client-registration",
40654
+ register_uri: `${origin2}/register`,
40655
+ authorization_uri: `${origin2}/authorize`,
40656
+ token_uri: `${origin2}/token`,
40657
+ revocation_uri: `${origin2}/revoke`,
40658
+ grant_types_supported: ["authorization_code", "refresh_token"],
40659
+ response_types_supported: ["code"],
40660
+ code_challenge_methods_supported: ["S256"],
40661
+ token_endpoint_auth_methods_supported: ["client_secret_post", "none"],
40662
+ bearer_methods_supported: ["header"],
40663
+ identity_types_supported: ["wallet_signature"],
40664
+ wallet_signature: {
40665
+ standard: "EIP-4361",
40666
+ chain_id: chainId,
40667
+ credential_types_supported: ["access_token", "refresh_token"]
40668
+ }
40669
+ }
40670
+ ]
40671
+ }
40672
+ };
40673
+ return `# auth.md
40674
+
40675
+ > Agent authentication and registration for Diamond Hands \u2014 a self-custodial Bitcoin
40676
+ > line of credit. Lock native BTC in an isolated L1 vault, mint UCD against it, keep
40677
+ > the Bitcoin.
40678
+
40679
+ This document is for **autonomous agents** that operate a Bitcoin-collateralized UCD
40680
+ position on behalf of the person who owns the wallet. It is generated from this
40681
+ deployment's live configuration, so the endpoints and the chain id below are the ones
40682
+ actually being served.
40683
+
40684
+ ## Agent service
40685
+
40686
+ | | |
40687
+ |---|---|
40688
+ | Protocol | Model Context Protocol (MCP), streamable HTTP |
40689
+ | Endpoint | \`${origin2}/mcp\` |
40690
+ | Network | ${isMainnet ? "Ethereum mainnet (chain id 1) \u2014 real BTC, real UCD" : `${launchNetwork} (chain id ${chainId}) \u2014 test network, test funds`} |
40691
+ | Protected resource metadata | ${origin2}/.well-known/oauth-protected-resource |
40692
+ | Authorization server metadata | ${origin2}/.well-known/oauth-authorization-server |
40693
+
40694
+ \`\`\`json
40695
+ {
40696
+ "mcpServers": {
40697
+ "diamond-hands": {
40698
+ "type": "http",
40699
+ "url": "${origin2}/mcp"
40700
+ }
40701
+ }
40702
+ }
40703
+ \`\`\`
40704
+
40705
+ ## agent_auth
40706
+
40707
+ \`\`\`json
40708
+ ${JSON.stringify(agentAuth, null, 2)}
40709
+ \`\`\`
40710
+
40711
+ ### The registration flow, end to end
40712
+
40713
+ 1. **Register.** \`POST ${origin2}/register\` \u2014 RFC 7591 dynamic client registration,
40714
+ open, no pre-shared credential. You receive a \`client_id\`.
40715
+ 2. **Authorize.** Send the user to \`${origin2}/authorize\` with \`response_type=code\`,
40716
+ your \`client_id\`, \`redirect_uri\`, and a PKCE \`code_challenge\` (\`S256\` \u2014
40717
+ required).
40718
+ 3. **Sign in.** One Sign-In-with-Ethereum signature (EIP-4361) over a message this
40719
+ server minted for that flow. Nothing you supply is parsed back \u2014 the server verifies
40720
+ against its own canonical text, and pins the chain id itself. A person signs this in
40721
+ a browser wallet extension; an agent holding its own key signs the same message
40722
+ through the flow's JSON endpoints.${wcLine}
40723
+ 4. **Exchange.** \`POST ${origin2}/token\` with the code and your \`code_verifier\`. You
40724
+ get an access token and a refresh token.
40725
+ 5. **Call.** Send the access token to \`${origin2}/mcp\` as
40726
+ \`Authorization: Bearer <token>\`. Unauthenticated calls answer \`401\` with a
40727
+ JSON-RPC error, not a redirect.
40728
+
40729
+ ### What the credential is, and is not
40730
+
40731
+ The **wallet address is the account.** There are no passwords, no email addresses, and
40732
+ no user database. Registration creates an OAuth client, not a Diamond Hands account \u2014
40733
+ there is nothing to delete, and no personal data is collected.
40734
+
40735
+ The access token proves **session identity only**. It can read what that address could
40736
+ already read, and it can *stage* a fund-moving operation \u2014 arm a mint, a repayment, a
40737
+ withdrawal \u2014 but it can never complete one: each of those terminates in a wallet
40738
+ signature over that specific operation, which the token cannot produce. So it is not a
40739
+ read-only credential, and it is not a spending one either. A stolen token cannot spend.
40740
+
40741
+ - Access token: ~1 hour. Refresh token: rotating, expires after inactivity.
40742
+ - All authorization state is held **in memory**. A service restart ends every session
40743
+ and the user signs in again. Nothing is persisted at rest.
40744
+ - \`scopes_supported\` is empty and tokens are minted with no scopes \u2014 this
40745
+ authorization server does not implement scoped access. Do not request a scope; you
40746
+ will not receive one.
40747
+
40748
+ ### Who holds the wallet \u2014 read this before you rely on the approval step
40749
+
40750
+ This protocol authenticates **addresses, not people**. It cannot tell whether a
40751
+ signature came from a person clicking a wallet extension or from software holding a key,
40752
+ and it does not try to. Two arrangements are supported, and they have **materially
40753
+ different guarantees**. Be clear which one you are.
40754
+
40755
+ **1. You act for a person, on their wallet.** The human owns the position and signs each
40756
+ operation themselves. This is the arrangement the approval page is designed for: every
40757
+ fund-moving step raises a card the person reads and approves, and you cannot proceed
40758
+ without them. Your token gives you reads and the ability to *stage* a ceremony \u2014 never
40759
+ to complete one.
40760
+
40761
+ **2. You hold your own key and own your own position.** Nothing here treats you
40762
+ differently: you sign in with your key, you create and fund your own vault, you borrow
40763
+ against your own BTC. But then **you are the approver.** The approval card's "Approve
40764
+ ONLY if you initiated this exact BTC withdrawal" is addressed to a human reader, and
40765
+ there is no human in this arrangement. Do not present that step to your operator as
40766
+ independent oversight \u2014 it is not; you are satisfying it yourself.
40767
+
40768
+ What actually bounds arrangement 2 is **on-chain, not in this service**: a BTC
40769
+ withdrawal can only go to an address already on the position's on-chain allowlist, and
40770
+ adding one takes a separate, fully decodable transaction plus the registry's delay \u2014
40771
+ read live from the contract at execution${isMainnet ? " (24 hours on mainnet today)" : ""}.
40772
+ Treat that allowlist as your real safety boundary, and put an address on it
40773
+ deliberately.
40774
+
40775
+ **3. Acting on someone else's position with your own key** \u2014 a delegated agent key \u2014 is
40776
+ **not offered on this endpoint yet.** If you need it, do not attempt to approximate it
40777
+ by holding a person's key; contact us.
40778
+
40779
+ If your operator has asked you to run unattended, you are in arrangement 2. Say so
40780
+ plainly to them, and do not describe the approval step as human review.
40781
+
40782
+ ### Flows this service does not offer
40783
+
40784
+ Stated plainly so a scanner does not infer otherwise: there is **no** ID-JAG
40785
+ (\`urn:ietf:params:oauth:token-type:id-jag\`) identity-assertion flow, **no**
40786
+ verified-email flow, and **no** anonymous flow. The only identity type is a wallet
40787
+ signature.
40788
+
40789
+ ## Public data needs no credential
40790
+
40791
+ Protocol data \u2014 live loans, terms, the peg stability module \u2014 is public. Start at
40792
+ <https://app.diamondhands.credit/llms.txt>, or request any app page with
40793
+ \`Accept: text/markdown\`.
40794
+
40795
+ ## Local alternative
40796
+
40797
+ An agent on the user's own machine can skip this service and talk to the protocol
40798
+ directly through the published MCP server, which carries the same tools:
40799
+
40800
+ - \`npx -y @gvnrdao/dh-mcp\` (requires Node \u2265 18)
40801
+ - \`curl -fsSL https://assets.gvnr.xyz/dh-mcp/install.sh | sh\` (self-contained binary)
40802
+ - Claude Desktop bundle and checksums: <https://assets.gvnr.xyz/dh-mcp/>
40803
+
40804
+ ## Contact
40805
+
40806
+ Security contact and disclosure policy:
40807
+ <https://app.diamondhands.credit/.well-known/security.txt>
40808
+
40809
+ Do not probe \`POST /register\` or \`/authorize\` during passive scans. This document,
40810
+ the protected-resource metadata, and the authorization-server metadata are the safe
40811
+ source of truth.
40812
+ `;
40813
+ }
40814
+
40815
+ // src/connector/landing-page.ts
40816
+ var FAVICON_SVG = `<svg width="512" height="512" viewBox="-6 -11 88 88" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Diamond Hands"><path d="M1.08325 20.7041L37.9038 64.4967L74.2886 20.7041L61.8699 0.877686H13.502L1.08325 20.7041Z" fill="#C9F284" stroke="#34440E" stroke-width="1.75559"/><path d="M13.9385 0.877441L37.9045 64.2785" stroke="#34440E" stroke-width="1.75559"/><path d="M61.6553 0.877441L37.9071 64.4964" stroke="#34440E" stroke-width="1.75559"/><path d="M1.08276 20.7029H74.2882" stroke="#34440E" stroke-width="1.75559"/></svg>`;
40817
+ var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).replace(/'/g, "%27")}`;
40818
+ var BACKGROUND_IMAGE_ORIGIN = "https://images.gvnr.xyz";
40819
+ var BACKGROUND_IMAGE_URL = `${BACKGROUND_IMAGE_ORIGIN}/images/layout/backgroundCorleoneb.jpg`;
40820
+ var escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
40821
+ function moneyReality(networks2) {
40822
+ const mainnet = networks2.includes("mainnet");
40823
+ const sepolia = networks2.includes("sepolia");
40824
+ if (mainnet && sepolia) {
40825
+ return {
40826
+ label: "REAL MONEY on mainnet \xB7 practice funds on sepolia",
40827
+ detail: "This deployment serves both networks. Mainnet moves real BTC and real UCD; sepolia is the test network and its funds are not real. Ask which network you are on before acting."
40828
+ };
40829
+ }
40830
+ if (mainnet) {
40831
+ return {
40832
+ label: "REAL MONEY \u2014 Ethereum mainnet",
40833
+ detail: "This deployment serves mainnet only. Every fund-moving operation moves real BTC and real UCD, and each one needs a fresh signature from your own wallet."
40834
+ };
40835
+ }
40836
+ return {
40837
+ label: "PRACTICE FUNDS \u2014 sepolia test network",
40838
+ detail: "This deployment serves sepolia only. The contracts and ceremonies are real, the money is not. Nothing here can move mainnet funds."
40839
+ };
40840
+ }
40841
+ function renderLandingPage(input) {
40842
+ const { publicOrigin, networks: networks2, version: version2, nonce } = input;
40843
+ const origin2 = escapeHtml(publicOrigin);
40844
+ const money = moneyReality(networks2);
40845
+ const config = JSON.stringify({ mcpServers: { "diamond-hands": { type: "http", url: `${publicOrigin}/mcp` } } }, null, 2);
40846
+ return `<!doctype html>
40847
+ <html lang="en">
40848
+ <head>
40849
+ <meta charset="utf-8">
40850
+ <meta name="viewport" content="width=device-width,initial-scale=1">
40851
+ <title>Diamond Hands \u2014 MCP endpoint</title>
40852
+ <link rel="icon" type="image/svg+xml" href="${FAVICON_DATA_URI}">
40853
+ <link rel="apple-touch-icon" href="${FAVICON_DATA_URI}">
40854
+ <style>
40855
+ * { margin:0; padding:0; box-sizing:border-box; }
40856
+ /* House treatment (ops.gvnr.xyz, brando.gvnr.xyz): the image fills the viewport,
40857
+ centred and cropped, and the PAGE never scrolls. */
40858
+ html, body { width:100%; height:100%; overflow:hidden; }
40859
+ body {
40860
+ background: url('${BACKGROUND_IMAGE_URL}') center center / cover no-repeat fixed;
40861
+ color:#f3f4f6;
40862
+ font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
40863
+ }
40864
+ /* NO full-page scrim: the photograph is the point, so darkness lives only behind the
40865
+ text that needs to stay legible. The content scrolls INSIDE the viewport rather than
40866
+ the page scrolling, so a short window never clips anything and the image never moves. */
40867
+ .scroll { height:100%; overflow-y:auto; overscroll-behavior:contain; }
40868
+ main { max-width:41rem; margin:0 auto; padding:1.9rem 1.25rem 2rem;
40869
+ text-shadow:0 1px 3px rgba(0,0,0,.85); }
40870
+ /* Wide viewports: the lower half goes side-by-side so the whole page fits without the
40871
+ viewport scrolling \u2014 the house treatment is a full-bleed image, not a long page. */
40872
+ @media (min-width: 62rem) and (min-height: 34rem) {
40873
+ main { max-width:62rem; }
40874
+ .cols { display:grid; grid-template-columns:1fr 1fr; gap:0 1.6rem; align-items:start; }
40875
+ .cols h2:first-child { margin-top:0; }
40876
+ }
40877
+ h1 { font-size:1.35rem; margin:0 0 .25rem; letter-spacing:-.01em; }
40878
+ .sub { color:#dfe3ea; margin:0 0 1.1rem; font-size:14px; }
40879
+ .card { background:rgba(6,8,12,.62); border:1px solid rgba(255,255,255,.16);
40880
+ border-radius:10px; padding:.75rem .95rem; margin:0 0 .8rem;
40881
+ backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px); }
40882
+ .money { border-left:3px solid #f59e0b; }
40883
+ .money strong { display:block; margin-bottom:.15rem; }
40884
+ h2 { font-size:.72rem; text-transform:uppercase; letter-spacing:.08em; color:#cbd2dc;
40885
+ margin:1.1rem 0 .45rem; font-weight:600; }
40886
+ pre { margin:0; padding:.7rem .9rem; background:rgba(0,0,0,.66);
40887
+ border:1px solid rgba(255,255,255,.16); border-radius:8px; overflow-x:auto;
40888
+ font-size:12.5px; line-height:1.45; text-shadow:none;
40889
+ font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
40890
+ code { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:.92em; }
40891
+ table { border-collapse:collapse; width:100%; font-size:13.5px; }
40892
+ td { padding:.3rem .6rem .3rem 0; border-bottom:1px solid rgba(255,255,255,.12); vertical-align:top; }
40893
+ td:first-child { color:#cbd2dc; white-space:nowrap; width:10.5rem; }
40894
+ tr:last-child td { border-bottom:0; }
40895
+ a { color:inherit; text-decoration:underline; text-underline-offset:2px; }
40896
+ .row { display:flex; align-items:center; gap:.6rem; margin-bottom:.4rem; font-size:13px; }
40897
+ button { font:inherit; font-size:12.5px; padding:.25rem .65rem;
40898
+ border:1px solid rgba(255,255,255,.24); border-radius:6px;
40899
+ background:rgba(0,0,0,.55); color:#f3f4f6; cursor:pointer; text-shadow:none; }
40900
+ button:hover { background:rgba(0,0,0,.75); }
40901
+ footer { color:#cbd2dc; font-size:12.5px; margin-top:1.1rem; padding-top:.7rem;
40902
+ border-top:1px solid rgba(255,255,255,.14); }
40903
+ [hidden] { display:none !important; }
40904
+ #reveal-wrap { margin:0 0 .4rem; }
40905
+ #reveal { display:inline-block; padding:.4rem .85rem; border-radius:6px;
40906
+ border:1px solid rgba(255,255,255,.26); background:rgba(6,8,12,.62);
40907
+ backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px);
40908
+ text-decoration:none; font-size:13.5px; text-shadow:none; cursor:pointer; }
40909
+ #reveal:hover { background:rgba(6,8,12,.85); border-color:rgba(255,255,255,.4); }
40910
+ #reveal::after { content:" \u2193"; opacity:.7; }
40911
+ </style>
40912
+ </head>
40913
+ <body>
40914
+ <div class="scroll">
40915
+ <main>
40916
+ <h1>Diamond Hands \u2014 MCP endpoint</h1>
40917
+ <p class="sub">This host is a <strong>Model Context Protocol</strong> server, not a website.
40918
+ There is no app to use here. If you are a person, the app is at
40919
+ <a href="https://app.diamondhands.credit/">app.diamondhands.credit</a>.</p>
40920
+
40921
+ <!-- Revealed BY SCRIPT, hidden in the served markup \u2014 the inverse of #details below.
40922
+ With no JS this stays hidden and the details stay open, so the page degrades to
40923
+ everything-visible rather than to a trigger that does nothing. -->
40924
+ <p id="reveal-wrap" hidden><a href="#details" id="reveal" role="button">View MCP installation details</a></p>
40925
+
40926
+ <div id="details">
40927
+ <div class="card money">
40928
+ <strong>${escapeHtml(money.label)}</strong>
40929
+ ${escapeHtml(money.detail)}
40930
+ </div>
40931
+
40932
+ <div class="cols">
40933
+ <section>
40934
+ <h2>Connect an agent</h2>
40935
+ <div class="row">
40936
+ <span style="color:var(--muted);font-size:13px">Add this to your MCP client configuration:</span>
40937
+ <button id="copy" type="button">Copy</button>
40938
+ </div>
40939
+ <pre id="cfg">${escapeHtml(config)}</pre>
40940
+
40941
+ <h2>How authorization works</h2>
40942
+ <div class="card">
40943
+ Identity is a <strong>wallet</strong>, not an account: OAuth 2.1 with dynamic client
40944
+ registration (RFC 7591) and PKCE, where the login is an Ethereum signature (EIP-4361).
40945
+ No passwords, no user database. The bearer token proves <em>session identity only</em> \u2014
40946
+ it signs nothing and can never move funds; every fund-moving step raises its own approval
40947
+ in your own wallet. Session state is in memory, so a restart means signing in again.
40948
+ </div>
40949
+ </section>
40950
+
40951
+ <section>
40952
+ <h2>Endpoints</h2>
40953
+ <div class="card">
40954
+ <table>
40955
+ <tr><td>MCP</td><td><code>${origin2}/mcp</code> \u2014 streamable HTTP</td></tr>
40956
+ <tr><td>Networks served</td><td><code>${escapeHtml(networks2.join(", "))}</code></td></tr>
40957
+ <tr><td>Registration</td><td><a href="/auth.md">/auth.md</a> \u2014 how an agent registers and signs in</td></tr>
40958
+ <tr><td>Resource metadata</td><td><a href="/.well-known/oauth-protected-resource">/.well-known/oauth-protected-resource</a></td></tr>
40959
+ <tr><td>Auth server metadata</td><td><a href="/.well-known/oauth-authorization-server">/.well-known/oauth-authorization-server</a></td></tr>
40960
+ </table>
40961
+ </div>
40962
+
40963
+ </section>
40964
+ </div>
40965
+
40966
+ <footer>
40967
+ <code>@gvnrdao/dh-mcp</code> v${escapeHtml(version2)} \xB7 origin <code>${origin2}</code>
40968
+ </footer>
40969
+ </div>
40970
+ </main>
40971
+ </div>
40972
+ <script nonce="${escapeHtml(nonce)}">
40973
+ // Progressive disclosure, applied by SCRIPT rather than baked into the markup: the
40974
+ // details ship visible, and only a browser that can re-open them is allowed to close
40975
+ // them. A page whose whole content sits behind a trigger that needs JS is a page that
40976
+ // shows two sentences and nothing else when the script does not run.
40977
+ (function () {
40978
+ var details = document.getElementById('details');
40979
+ var wrap = document.getElementById('reveal-wrap');
40980
+ var link = document.getElementById('reveal');
40981
+ if (!details || !wrap || !link) return;
40982
+ details.hidden = true;
40983
+ wrap.hidden = false;
40984
+ link.addEventListener('click', function (e) {
40985
+ e.preventDefault();
40986
+ wrap.hidden = true;
40987
+ details.hidden = false;
40988
+ });
40989
+ })();
40990
+
40991
+ document.getElementById('copy').addEventListener('click', function () {
40992
+ var t = document.getElementById('cfg').textContent;
40993
+ navigator.clipboard.writeText(t).then(function () {
40994
+ var b = document.getElementById('copy');
40995
+ b.textContent = 'Copied'; setTimeout(function () { b.textContent = 'Copy'; }, 1400);
40996
+ });
40997
+ });
40998
+ </script>
40999
+ </body>
41000
+ </html>
41001
+ `;
41002
+ }
41003
+
41004
+ // src/util/page-headers.ts
40629
41005
  var import_node_crypto = require("crypto");
41006
+ function htmlPageSecurityHeaders(extra) {
41007
+ const nonce = (0, import_node_crypto.randomBytes)(16).toString("base64");
41008
+ const base = [
41009
+ `default-src 'none'`,
41010
+ `script-src 'nonce-${nonce}'`,
41011
+ `style-src 'unsafe-inline'`,
41012
+ `connect-src 'self'`,
41013
+ `base-uri 'none'`,
41014
+ `form-action 'none'`,
41015
+ `frame-ancestors 'none'`
41016
+ ];
41017
+ for (const [directive, sources] of Object.entries(extra ?? {})) {
41018
+ if (sources.length === 0) continue;
41019
+ base.push(`${directive} ${sources.join(" ")}`);
41020
+ }
41021
+ return {
41022
+ nonce,
41023
+ headers: {
41024
+ "Content-Security-Policy": base.join("; "),
41025
+ "X-Frame-Options": "DENY",
41026
+ "Referrer-Policy": "no-referrer",
41027
+ "X-Content-Type-Options": "nosniff"
41028
+ }
41029
+ };
41030
+ }
41031
+
41032
+ // src/version.ts
41033
+ var SERVER_VERSION = "0.5.12";
41034
+
41035
+ // src/connector/siwe-oauth.ts
41036
+ var import_node_crypto2 = require("crypto");
40630
41037
  var import_ethers = require("ethers");
40631
41038
  var import_errors = require("@modelcontextprotocol/sdk/server/auth/errors.js");
40632
41039
 
40633
41040
  // src/connector/siwe-page.ts
40634
- function renderSiwePage(flowId, clientName) {
41041
+ function renderSiwePage(opts) {
41042
+ const { flowId, redirectHost, nonce } = opts;
41043
+ const clientName = clampClientName(opts.clientName);
40635
41044
  return `<!DOCTYPE html>
40636
41045
  <html>
40637
41046
  <head>
@@ -40645,6 +41054,26 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
40645
41054
  #status { margin-top: 1rem; color: #444; min-height: 1.5rem; }
40646
41055
  .err { color: #b00020; }
40647
41056
  .note { font-size: 0.85rem; color: #666; margin-top: 2rem; }
41057
+ /* "position: relative" is load-bearing, not cosmetic: it puts the consent box in its
41058
+ own stacking context so it paints ABOVE the inline content of the paragraph before
41059
+ it. Without it, a client name built from stacked combining marks overflows its line
41060
+ box downward and paints over this text \u2014 the CSS painting order draws every block
41061
+ background first, then all inline content in tree order. */
41062
+ .dest { background: #fff8e1; border-left: 3px solid #c77700; padding: 0.7rem 0.9rem; font-size: 0.9rem; position: relative; }
41063
+ /* The destination must stay legible under a host the attacker chose the length of:
41064
+ "overflow-wrap: anywhere" lets it wrap mid-label (a dot is not a break opportunity),
41065
+ and the isolate keeps any bidi control inside from reordering the sentence around
41066
+ it. splitRedirectHost has already bounded the length; this bounds the geometry. */
41067
+ .dest code { font-family: ui-monospace, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
41068
+ .dest .host-head { color: #5a5a5a; }
41069
+ .dest .host-tail { font-weight: 700; color: #000; }
41070
+ /* The elision is NOT decoration \u2014 it is the page admitting it withheld characters, so
41071
+ it must be as visible as the text it replaced. */
41072
+ .dest .host-cut { color: #c77700; font-weight: 700; font-style: normal; }
41073
+ /* The attacker-chosen name is clipped to a fixed box: bounded characters alone do not
41074
+ bound HEIGHT (combining marks stack vertically), and an isolate stops an unpaired
41075
+ RTL override inside the name from reversing the rest of the sentence. */
41076
+ .cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 700; }
40648
41077
  #qr { max-width: 16rem; margin-top: 1rem; }
40649
41078
  #qr svg { width: 100%; height: auto; }
40650
41079
  #wc-uri { font-size: 0.7rem; word-break: break-all; color: #888; }
@@ -40652,14 +41081,15 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
40652
41081
  </head>
40653
41082
  <body>
40654
41083
  <h1>Sign in to Diamond Hands</h1>
40655
- <p><b>${escapeHtml(clientName)}</b> is asking to connect. Signing in proves you own a wallet address \u2014 it authorizes nothing on-chain and can never move funds.</p>
41084
+ <p><span class="cname" dir="ltr">${escapeHtml2(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>
41085
+ <p class="dest">When you sign, this connection is handed to <code dir="ltr">${renderRedirectHost(redirectHost)}</code>. Anyone can register a client under any name, so read the host, not the name \u2014 and read it from the <b>bold end</b>, which is the part that decides who actually owns it. If you do not recognize it, close this page; nothing has happened yet.</p>
40656
41086
  <button id="connect">Browser wallet</button>
40657
41087
  <button id="wc">Mobile wallet (QR)</button>
40658
41088
  <div id="status"></div>
40659
41089
  <div id="qr"></div>
40660
41090
  <p id="wc-uri"></p>
40661
41091
  <p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect).</p>
40662
- <script>
41092
+ <script nonce="${nonce}">
40663
41093
  const FLOW = ${JSON.stringify(flowId)};
40664
41094
  const statusEl = document.getElementById("status");
40665
41095
  function show(text, isErr) { statusEl.textContent = text; statusEl.className = isErr ? "err" : ""; }
@@ -40727,9 +41157,34 @@ document.getElementById("wc").addEventListener("click", async () => {
40727
41157
  </body>
40728
41158
  </html>`;
40729
41159
  }
40730
- function escapeHtml(s) {
41160
+ function escapeHtml2(s) {
40731
41161
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
40732
41162
  }
41163
+ var MAX_CLIENT_NAME_CHARS = 64;
41164
+ var HOST_TAIL_CHARS = 48;
41165
+ var HOST_HEAD_CHARS = 12;
41166
+ var HOST_TAIL_LABELS = 3;
41167
+ var HOST_ELISION_FLOOR = 12;
41168
+ var MAX_HOST_DISPLAY_CHARS = HOST_HEAD_CHARS + HOST_TAIL_CHARS + 24;
41169
+ function splitRedirectHost(host) {
41170
+ const labels = host.split(".");
41171
+ const labelTail = labels.slice(-HOST_TAIL_LABELS).join(".");
41172
+ const tailStart = Math.max(host.length - labelTail.length, host.length - HOST_TAIL_CHARS, 0);
41173
+ const tail = host.slice(tailStart);
41174
+ const fullHead = host.slice(0, tailStart);
41175
+ if (fullHead.length <= HOST_HEAD_CHARS + HOST_ELISION_FLOOR) return { head: fullHead, elided: 0, tail };
41176
+ return { head: fullHead.slice(0, HOST_HEAD_CHARS), elided: fullHead.length - HOST_HEAD_CHARS, tail };
41177
+ }
41178
+ function renderRedirectHost(host) {
41179
+ const { head, elided, tail } = splitRedirectHost(host);
41180
+ const cut = elided === 0 ? "" : `<span class="host-cut">\u2026+${elided} chars\u2026</span>`;
41181
+ return `<span class="host-head">${escapeHtml2(head)}</span>${cut}<span class="host-tail">${escapeHtml2(tail)}</span>`;
41182
+ }
41183
+ function clampClientName(name) {
41184
+ const points = [...name];
41185
+ if (points.length <= MAX_CLIENT_NAME_CHARS) return name;
41186
+ return `${points.slice(0, MAX_CLIENT_NAME_CHARS - 1).join("")}\u2026`;
41187
+ }
40733
41188
 
40734
41189
  // src/connector/siwe-oauth.ts
40735
41190
  var FLOW_TTL_MS = 10 * 60 * 1e3;
@@ -40758,6 +41213,12 @@ var SiweOAuthProvider = class {
40758
41213
  return {
40759
41214
  getClient: (clientId) => clients.get(clientId),
40760
41215
  registerClient: (client) => {
41216
+ const name = client.client_name;
41217
+ if (name !== void 0 && [...name].length > MAX_CLIENT_NAME_CHARS) {
41218
+ throw new import_errors.InvalidClientMetadataError(
41219
+ `client_name is ${[...name].length} characters \u2014 this authorization server displays it on a consent screen and accepts at most ${MAX_CLIENT_NAME_CHARS}`
41220
+ );
41221
+ }
40761
41222
  while (clients.size >= maxClients) {
40762
41223
  const oldest = clients.keys().next().value;
40763
41224
  if (oldest === void 0) break;
@@ -40768,12 +41229,28 @@ var SiweOAuthProvider = class {
40768
41229
  }
40769
41230
  };
40770
41231
  }
40771
- /** SDK authorize handler → we render the SIWE sign-in page for this flow. */
41232
+ /** SDK authorize handler → we render the SIWE sign-in page for this flow.
41233
+ *
41234
+ * C-45: the page is a PUBLIC sign-in surface served ahead of any host helmet, so this
41235
+ * response carries its own security headers, and the page names the redirect HOST —
41236
+ * the consent fact that open registration makes `client_name` unable to carry. */
40772
41237
  async authorize(client, params, res) {
40773
41238
  this.sweep();
40774
- const flowId = (0, import_node_crypto.randomBytes)(16).toString("hex");
41239
+ const flowId = (0, import_node_crypto2.randomBytes)(16).toString("hex");
40775
41240
  this.flows.set(flowId, { clientId: client.client_id, params, createdAt: this.clock() });
40776
- res.status(200).type("html").send(renderSiwePage(flowId, client.client_name ?? client.client_id));
41241
+ const page = htmlPageSecurityHeaders();
41242
+ for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
41243
+ res.status(200).type("html").send(
41244
+ renderSiwePage({
41245
+ flowId,
41246
+ clientName: client.client_name ?? client.client_id,
41247
+ // Parseable by the time authorize() runs: the SDK validates every registered
41248
+ // redirect_uri (SafeUrlSchema) and, for a request-supplied one, URL.canParse
41249
+ // plus a registered-URI match — so this constructor cannot throw here.
41250
+ redirectHost: new URL(params.redirectUri).host,
41251
+ nonce: page.nonce
41252
+ })
41253
+ );
40777
41254
  }
40778
41255
  /** Page step 1: the wallet reported its address — mint the CANONICAL SIWE message.
40779
41256
  * Re-calling rebinds (the user switched wallet accounts before signing). The chain id
@@ -40790,7 +41267,7 @@ var SiweOAuthProvider = class {
40790
41267
  mintSiweMessage(checksummedAddress) {
40791
41268
  const origin2 = this.opts.origin();
40792
41269
  const domain = new URL(origin2).host;
40793
- const nonce = (0, import_node_crypto.randomBytes)(8).toString("hex");
41270
+ const nonce = (0, import_node_crypto2.randomBytes)(8).toString("hex");
40794
41271
  return `${domain} wants you to sign in with your Ethereum account:
40795
41272
  ${checksummedAddress}
40796
41273
 
@@ -40889,7 +41366,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
40889
41366
  void transport.close().catch(() => void 0);
40890
41367
  return;
40891
41368
  }
40892
- const code = (0, import_node_crypto.randomBytes)(24).toString("hex");
41369
+ const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
40893
41370
  this.codes.set(code, {
40894
41371
  clientId: flow.clientId,
40895
41372
  address: checksummed,
@@ -40956,7 +41433,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
40956
41433
  return { ok: false, status: 401, reason: "the signature does not match the connected wallet address" };
40957
41434
  }
40958
41435
  this.deleteFlow(flowId, flow);
40959
- const code = (0, import_node_crypto.randomBytes)(24).toString("hex");
41436
+ const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
40960
41437
  this.codes.set(code, {
40961
41438
  clientId: flow.clientId,
40962
41439
  address: flow.siwe.address,
@@ -41014,8 +41491,8 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41014
41491
  if (r && r.clientId === client.client_id) this.refresh.delete(request.token);
41015
41492
  }
41016
41493
  mintTokens(address, clientId) {
41017
- const accessToken = (0, import_node_crypto.randomBytes)(32).toString("hex");
41018
- const refreshToken = (0, import_node_crypto.randomBytes)(32).toString("hex");
41494
+ const accessToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41495
+ const refreshToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41019
41496
  this.access.set(accessToken, { address, clientId, expiresAt: Math.floor(this.clock() / 1e3) + ACCESS_TTL_S });
41020
41497
  this.refresh.set(refreshToken, { address, clientId, lastUsed: this.clock() });
41021
41498
  return { access_token: accessToken, token_type: "bearer", expires_in: ACCESS_TTL_S, refresh_token: refreshToken };
@@ -41070,7 +41547,11 @@ var NETWORK_DEFAULTS = {
41070
41547
  },
41071
41548
  mainnet: {
41072
41549
  rpcUrl: "https://ethereum-rpc.publicnode.com",
41073
- serviceEndpoint: "https://ops.gvnr.xyz",
41550
+ // Cutover 2026-09-08 — see sdk/src/constants/chunks/network-configs.ts for the full
41551
+ // reasoning. Widening, not a rename: ops.gvnr.xyz serves the same broker and cannot be
41552
+ // retired while installed copies call it. The sepolia entry above deliberately stays on
41553
+ // ops-test.gvnr.xyz — there is no ops-test.diamondhands.credit twin (open decision 2).
41554
+ serviceEndpoint: "https://ops.diamondhands.credit",
41074
41555
  litNetwork: "chipotle",
41075
41556
  // On-chain PKPValidation generation, mainnet (validatorForVersion(3) is the ONLY
41076
41557
  // registered validator — verified live 2026-08-05). Without this the SDK defaults
@@ -41261,7 +41742,7 @@ var fs6 = __toESM(require("fs"));
41261
41742
  var import_ethers40 = require("ethers");
41262
41743
 
41263
41744
  // src/boundary/index.ts
41264
- var import_node_crypto8 = require("crypto");
41745
+ var import_node_crypto9 = require("crypto");
41265
41746
  var fs5 = __toESM(require("fs"));
41266
41747
  var os2 = __toESM(require("os"));
41267
41748
  var path4 = __toESM(require("path"));
@@ -42285,7 +42766,7 @@ var DEFAULT_SEED = {
42285
42766
  };
42286
42767
 
42287
42768
  // src/boundary/upstream/mock/world.ts
42288
- var import_node_crypto2 = require("crypto");
42769
+ var import_node_crypto3 = require("crypto");
42289
42770
  var import_ethers3 = require("ethers");
42290
42771
 
42291
42772
  // src/signer/safe.ts
@@ -42489,7 +42970,7 @@ var World = class {
42489
42970
  nextId(prefix) {
42490
42971
  this.state.counter += 1;
42491
42972
  const n = this.state.counter;
42492
- const hash = (0, import_node_crypto2.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
42973
+ const hash = (0, import_node_crypto3.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
42493
42974
  return { n, hash };
42494
42975
  }
42495
42976
  nextTxRef() {
@@ -43368,7 +43849,7 @@ var WorldStore = class {
43368
43849
  };
43369
43850
 
43370
43851
  // src/boundary/upstream/mock/signer.ts
43371
- var import_node_crypto3 = require("crypto");
43852
+ var import_node_crypto4 = require("crypto");
43372
43853
  function mockSign(op, borrower, stance) {
43373
43854
  if (stance === "decline") {
43374
43855
  return {
@@ -43383,7 +43864,7 @@ function mockSign(op, borrower, stance) {
43383
43864
  signer: borrower,
43384
43865
  action: op.action,
43385
43866
  card: op.card,
43386
- digest: (0, import_node_crypto3.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
43867
+ digest: (0, import_node_crypto4.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
43387
43868
  }
43388
43869
  };
43389
43870
  }
@@ -44655,7 +45136,7 @@ var MockUpstreamPlugin = class {
44655
45136
  };
44656
45137
 
44657
45138
  // src/boundary/upstream/mock/external-ceremony.ts
44658
- var import_node_crypto4 = require("crypto");
45139
+ var import_node_crypto5 = require("crypto");
44659
45140
  var import_node_child_process = require("child_process");
44660
45141
  var import_ethers10 = require("ethers");
44661
45142
 
@@ -44848,7 +45329,7 @@ var ExternalCeremony = class {
44848
45329
  validateUnsignedTx({ ...p.tx }, p.expected, this.deps.vctx);
44849
45330
  const card = cardForTx(p.tx);
44850
45331
  const outcome = await this.request({
44851
- id: (0, import_node_crypto4.randomUUID)(),
45332
+ id: (0, import_node_crypto5.randomUUID)(),
44852
45333
  kind: "transaction",
44853
45334
  action: p.action,
44854
45335
  card,
@@ -44893,7 +45374,7 @@ var ExternalCeremony = class {
44893
45374
  message
44894
45375
  };
44895
45376
  const outcome = await this.request({
44896
- id: (0, import_node_crypto4.randomUUID)(),
45377
+ id: (0, import_node_crypto5.randomUUID)(),
44897
45378
  kind: "typed-data",
44898
45379
  action: "login",
44899
45380
  card: cardForTypedData("login", typedData),
@@ -44921,7 +45402,7 @@ var ExternalCeremony = class {
44921
45402
  });
44922
45403
  const card = cardForTypedData(p.action, typedData);
44923
45404
  const outcome = await this.request({
44924
- id: (0, import_node_crypto4.randomUUID)(),
45405
+ id: (0, import_node_crypto5.randomUUID)(),
44925
45406
  kind: "typed-data",
44926
45407
  action: p.action,
44927
45408
  card,
@@ -45096,7 +45577,7 @@ var KeystoreCeremony = class {
45096
45577
  };
45097
45578
 
45098
45579
  // src/boundary/upstream/mock/safe-ceremony.ts
45099
- var import_node_crypto5 = require("crypto");
45580
+ var import_node_crypto6 = require("crypto");
45100
45581
  var import_ethers12 = require("ethers");
45101
45582
  init_tx_validator();
45102
45583
 
@@ -45397,7 +45878,7 @@ var SafeCeremony = class {
45397
45878
  const primaryType = Object.keys(build.payload.types)[0];
45398
45879
  const outcome = await bridge.requestSignatureCollection(
45399
45880
  {
45400
- id: (0, import_node_crypto5.randomUUID)(),
45881
+ id: (0, import_node_crypto6.randomUUID)(),
45401
45882
  kind: "typed-data",
45402
45883
  action,
45403
45884
  card: build.card,
@@ -57343,7 +57824,17 @@ function getSepoliaConfig() {
57343
57824
  function getMainnetConfig() {
57344
57825
  return {
57345
57826
  mode: "service",
57346
- serviceEndpoint: "https://ops.gvnr.xyz",
57827
+ // Cutover 2026-09-08: the product's own domain. `ops.gvnr.xyz` still serves the same
57828
+ // broker and always will — every already-installed copy of this package calls it, so
57829
+ // it can never be retired. This changes what NEW installs default to, nothing else.
57830
+ //
57831
+ // Safe only because the server accepts the new audience ALREADY: the SDK derives the
57832
+ // login audience from this endpoint (`server-session.ts` — `loginAudience ??
57833
+ // serviceEndpoint`) and lit-ops-server FAILS CLOSED on an unknown one. Verified live
57834
+ // before this edit: DH_ACCEPTED_LOGIN_AUDIENCES on the deployed revision lists
57835
+ // https://ops.diamondhands.credit. Publishing this ahead of that would lock out every
57836
+ // client that installed it.
57837
+ serviceEndpoint: "https://ops.diamondhands.credit",
57347
57838
  chainId: 1,
57348
57839
  name: "mainnet",
57349
57840
  // No default RPC: mainnet runs in service mode (serviceEndpoint above), so
@@ -80000,7 +80491,7 @@ var EoaDHSigner = class {
80000
80491
  };
80001
80492
 
80002
80493
  // src/signer/external-eoa.ts
80003
- var import_node_crypto6 = require("crypto");
80494
+ var import_node_crypto7 = require("crypto");
80004
80495
  var import_ethers38 = require("ethers");
80005
80496
 
80006
80497
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
@@ -80094,7 +80585,7 @@ var ExternalEoaDHSigner = class {
80094
80585
  let used = { quantumTs: initialTs, fields: initial.fields };
80095
80586
  const outcome = await this.deps.bridge.requestSignature(
80096
80587
  {
80097
- id: (0, import_node_crypto6.randomUUID)(),
80588
+ id: (0, import_node_crypto7.randomUUID)(),
80098
80589
  kind: "personal-sign",
80099
80590
  action: spec.action,
80100
80591
  card: initial.card,
@@ -80128,7 +80619,7 @@ var ExternalEoaDHSigner = class {
80128
80619
  const approved = toApprovedTx(outerTx, this.deps.chainId);
80129
80620
  const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
80130
80621
  const outcome = await this.deps.bridge.requestSignature({
80131
- id: (0, import_node_crypto6.randomUUID)(),
80622
+ id: (0, import_node_crypto7.randomUUID)(),
80132
80623
  kind: "transaction",
80133
80624
  action: ctx.action,
80134
80625
  card: ctx.card,
@@ -80179,15 +80670,22 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80179
80670
  }
80180
80671
  const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
80181
80672
  const outcome = await this.deps.bridge.requestSignature({
80182
- id: (0, import_node_crypto6.randomUUID)(),
80673
+ id: (0, import_node_crypto7.randomUUID)(),
80183
80674
  kind: "personal-sign",
80184
- action: "btc-withdrawal authorization (blind hash)",
80675
+ action: "btc-withdrawal EXECUTE step (blind hash)",
80185
80676
  card: [
80186
- "BLIND SIGNATURE \u2014 BTC withdrawal authorization step",
80677
+ "BLIND SIGNATURE \u2014 BTC withdrawal, EXECUTE step",
80187
80678
  `hash: ${hashHex}`,
80188
80679
  "This hash is built inside the SDK and its contents CANNOT be decoded or verified by this page",
80189
80680
  "(identical to how diamondhands.credit signs withdrawals).",
80190
- "Approve ONLY if you initiated this exact BTC withdrawal in the conversation."
80681
+ "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80682
+ "",
80683
+ "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
80684
+ `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
80685
+ "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
80686
+ "itself allows. If it expires the signature is refused, the withdrawal does not",
80687
+ "complete, and the reserved coins stay reserved until that is cleared. Decline and",
80688
+ "start again rather than signing something you have not finished reading."
80191
80689
  ],
80192
80690
  expectedSigner: this.deps.borrower,
80193
80691
  chainId: this.deps.chainId,
@@ -80210,7 +80708,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80210
80708
  message: value
80211
80709
  };
80212
80710
  const outcome = await this.deps.bridge.requestSignature({
80213
- id: (0, import_node_crypto6.randomUUID)(),
80711
+ id: (0, import_node_crypto7.randomUUID)(),
80214
80712
  kind: "typed-data",
80215
80713
  action: "login",
80216
80714
  card: cardForTypedData("login", typedData),
@@ -80236,7 +80734,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80236
80734
  const card = cardForTx(approved);
80237
80735
  const gas = tx2.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
80238
80736
  const outcome = await this.deps.bridge.requestSignature({
80239
- id: (0, import_node_crypto6.randomUUID)(),
80737
+ id: (0, import_node_crypto7.randomUUID)(),
80240
80738
  kind: "transaction",
80241
80739
  action: describeFn(approved.data),
80242
80740
  card,
@@ -81120,10 +81618,10 @@ var RealUpstreamPlugin = class {
81120
81618
  // src/boundary/upstream/shared/external-bridge/bridge.ts
81121
81619
  var fs4 = __toESM(require("fs"));
81122
81620
  var http3 = __toESM(require("http"));
81123
- var import_node_crypto7 = require("crypto");
81621
+ var import_node_crypto8 = require("crypto");
81124
81622
 
81125
81623
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
81126
- function renderApprovalPage(sessionId) {
81624
+ function renderApprovalPage(sessionId, nonce) {
81127
81625
  return `<!doctype html>
81128
81626
  <html lang="en">
81129
81627
  <head>
@@ -81173,15 +81671,17 @@ function renderApprovalPage(sessionId) {
81173
81671
  </div>
81174
81672
  </div>
81175
81673
  </main>
81176
- <script>
81674
+ <script nonce="${nonce}">
81177
81675
  ${PAGE_CRYPTO_JS}
81178
81676
  </script>
81179
- <script>
81677
+ <script nonce="${nonce}">
81180
81678
  "use strict";
81181
81679
  const SESSION = ${JSON.stringify(sessionId)};
81182
81680
  // One-time token leaves the address bar (and history) immediately.
81183
81681
  // Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
81184
81682
  // at loopback root ("/") and under a hosted tenant mount ("/approval/<id>/").
81683
+ // EVERY endpoint reference goes through BASE \u2014 an origin-absolute "/x" resolves to the
81684
+ // ORIGIN root, which on a mount is the host, not the bridge, and 404s silently.
81185
81685
  const BASE = location.pathname.replace(/[^/]*$/, "");
81186
81686
  history.replaceState(null, "", location.pathname);
81187
81687
 
@@ -81253,14 +81753,14 @@ async function connect() {
81253
81753
  // wallet's own state transition and can report the stale value.
81254
81754
  async function onAccountsChanged(accounts) {
81255
81755
  account = (accounts && accounts[0]) || null;
81256
- await post("/wallet-event", { account: account, chainId: chainId });
81756
+ await post(BASE + "wallet-event", { account: account, chainId: chainId });
81257
81757
  showWallet();
81258
81758
  clearRequest("Wallet changed \u2014 pending request invalidated.");
81259
81759
  }
81260
81760
 
81261
81761
  async function onChainChanged(cid) {
81262
81762
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81263
- await post("/wallet-event", { account: account, chainId: chainId });
81763
+ await post(BASE + "wallet-event", { account: account, chainId: chainId });
81264
81764
  showWallet();
81265
81765
  clearRequest("Network changed \u2014 pending request invalidated.");
81266
81766
  }
@@ -81368,7 +81868,7 @@ connect();
81368
81868
  </body>
81369
81869
  </html>`;
81370
81870
  }
81371
- function renderUnlockPage(sessionId) {
81871
+ function renderUnlockPage(sessionId, nonce) {
81372
81872
  return `<!doctype html>
81373
81873
  <html lang="en">
81374
81874
  <head>
@@ -81410,7 +81910,7 @@ function renderUnlockPage(sessionId) {
81410
81910
  <div id="status" class="status"></div>
81411
81911
  </div>
81412
81912
  </main>
81413
- <script>
81913
+ <script nonce="${nonce}">
81414
81914
  "use strict";
81415
81915
  const SESSION = ${JSON.stringify(sessionId)};
81416
81916
  // Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
@@ -81468,7 +81968,7 @@ var SignatureBridge = class {
81468
81968
  /** Started state independent of the transport binding (mounted bridges own no server). */
81469
81969
  started = false;
81470
81970
  mount;
81471
- token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81971
+ token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81472
81972
  /** Hosted mounts: when the current page token was minted (rotation basis). */
81473
81973
  tokenMintedAt = 0;
81474
81974
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
@@ -81505,7 +82005,7 @@ var SignatureBridge = class {
81505
82005
  unlockUrl() {
81506
82006
  if (!this.started) throw new Error("bridge is not started");
81507
82007
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
81508
- this.unlockToken = (0, import_node_crypto7.randomBytes)(24).toString("hex");
82008
+ this.unlockToken = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81509
82009
  return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
81510
82010
  }
81511
82011
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
@@ -81546,7 +82046,7 @@ var SignatureBridge = class {
81546
82046
  if (this.mount) {
81547
82047
  const now = this.clock();
81548
82048
  if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
81549
- this.token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
82049
+ this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81550
82050
  this.tokenMintedAt = now;
81551
82051
  }
81552
82052
  return `${this.mount.baseUrl}/?t=${this.token}`;
@@ -81762,7 +82262,7 @@ var SignatureBridge = class {
81762
82262
  this.server = null;
81763
82263
  this.started = false;
81764
82264
  this.wallet = null;
81765
- this.token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
82265
+ this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81766
82266
  this.tokenMintedAt = 0;
81767
82267
  if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
81768
82268
  void this.wcTransport?.close().catch(() => void 0);
@@ -81832,10 +82332,11 @@ var SignatureBridge = class {
81832
82332
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
81833
82333
  return;
81834
82334
  }
81835
- const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
82335
+ const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
81836
82336
  this.sessions.set(sessionId, { wallet: null, sse: null });
81837
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
81838
- res.end(renderApprovalPage(sessionId));
82337
+ const page = htmlPageSecurityHeaders();
82338
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82339
+ res.end(renderApprovalPage(sessionId, page.nonce));
81839
82340
  }
81840
82341
  /** Target-network hints for the page's chain self-heal (session-gated). */
81841
82342
  serveConfig(url2, res) {
@@ -81895,9 +82396,10 @@ var SignatureBridge = class {
81895
82396
  return;
81896
82397
  }
81897
82398
  this.unlockToken = null;
81898
- this.unlockSession = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81899
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
81900
- res.end(renderUnlockPage(this.unlockSession));
82399
+ this.unlockSession = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82400
+ const page = htmlPageSecurityHeaders();
82401
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82402
+ res.end(renderUnlockPage(this.unlockSession, page.nonce));
81901
82403
  }
81902
82404
  async onUnlockSubmit(body, res) {
81903
82405
  if (!this.keystoreUnlock) {
@@ -82143,7 +82645,7 @@ function createBoundary(config, opts) {
82143
82645
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
82144
82646
  );
82145
82647
  }
82146
- const configFingerprint = (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
82648
+ const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
82147
82649
  if (opts?.ceremony) {
82148
82650
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
82149
82651
  const boundary2 = new BoundaryCore({
@@ -82312,7 +82814,7 @@ async function createRealBoundary(config, wallet, overrides) {
82312
82814
  }
82313
82815
  const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
82314
82816
  await plugin.initWriteSdk();
82315
- const configFingerprint = (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
82817
+ const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
82316
82818
  const capabilities = () => ({
82317
82819
  reads: {
82318
82820
  public: true,
@@ -82412,1231 +82914,398 @@ async function buildBoundary(configResult, overrides) {
82412
82914
  return { boundaryResult: { ok: true, boundary }, signer, dispose };
82413
82915
  }
82414
82916
 
82415
- // src/network-switch.ts
82416
- var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
82417
- function createNetworkSwitchRuntime(opts) {
82418
- return {
82419
- current() {
82420
- const b = opts.getBoot().boundaryResult;
82421
- if (!b.ok) return null;
82422
- const w = b.boundary.world();
82423
- return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
82424
- },
82425
- async switchTo(network) {
82426
- const allowed = opts.overrides?.allowedNetworks;
82427
- if (allowed && !allowed.includes(network)) {
82428
- return {
82429
- ok: false,
82430
- error: boundaryError(
82431
- "VALIDATION_FAILED",
82432
- `this deployment serves ${allowed.join(", ")} \u2014 '${network}' is not enabled on this service. Mainnet service enablement is a rollout step of the deployment, not a session setting.`
82433
- )
82434
- };
82435
- }
82436
- const targetEnv = { ...opts.env, DH_NETWORK: network };
82437
- const configResult = resolveBoundaryConfig(targetEnv);
82438
- if (!configResult.ok) return { ok: false, error: configResult.error };
82439
- const next = await buildBoundary(configResult, opts.overrides);
82440
- if (!next.boundaryResult.ok) {
82441
- next.dispose();
82442
- return { ok: false, error: next.boundaryResult.error };
82443
- }
82444
- opts.swap(next);
82445
- return { ok: true };
82446
- }
82447
- };
82448
- }
82449
- function assembleWorld(opts) {
82450
- let boot = opts.boot;
82451
- const deps = {
82452
- boundaryResult: boot.boundaryResult,
82453
- ...boot.mockControl ? { mockControl: boot.mockControl } : {},
82454
- ...boot.signer ? { signer: boot.signer } : {},
82455
- ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
82456
- ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
82457
- };
82458
- if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
82459
- deps.networkSwitch = createNetworkSwitchRuntime({
82460
- env: opts.env,
82461
- getBoot: () => boot,
82462
- ...opts.overrides ? { overrides: opts.overrides } : {},
82463
- swap: (next) => {
82464
- const old = boot;
82465
- boot = next;
82466
- deps.boundaryResult = next.boundaryResult;
82467
- if (next.signer) deps.signer = next.signer;
82468
- else delete deps.signer;
82469
- old.dispose();
82470
- const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
82471
- opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
82472
- }
82473
- });
82474
- }
82475
- return { deps, dispose: () => boot.dispose() };
82917
+ // src/boundary/field-glossary.ts
82918
+ var FIELD_GLOSSARY = {
82919
+ // ---- identity / envelope structure ----
82920
+ positionId: "the position's 32-byte id (0x\u202664 hex) \u2014 the input every position_* tool takes",
82921
+ borrower: "the Ethereum address that owns the position (the borrowing identity)",
82922
+ vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
82923
+ pkpId: "internal id of the programmable key pair holding BTC custody for this position",
82924
+ id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
82925
+ kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
82926
+ fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
82927
+ // ---- position facts (chain) ----
82928
+ 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",
82929
+ termMonths: "the current term length in months",
82930
+ totalTermMonths: "cumulative months across the original term plus every extension",
82931
+ createdAt: "ISO timestamp the position was created",
82932
+ expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
82933
+ previousExpiryAt: "the expiry before the latest extension (null when never extended)",
82934
+ lastUpdatedAt: "ISO timestamp of the last state change",
82935
+ debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
82936
+ // ---- indexed health (indexer snapshot) ----
82937
+ indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
82938
+ collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
82939
+ healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
82940
+ asOf: "ISO timestamp the indexer snapshot was computed",
82941
+ basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
82942
+ // ---- collateral (live BTC view) ----
82943
+ collateral: "the live Bitcoin-side view of the position's vault",
82944
+ 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",
82945
+ availableSource: "which source served availableSats (null when degraded)",
82946
+ 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",
82947
+ txid: "Bitcoin transaction id",
82948
+ sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
82949
+ confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
82950
+ minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
82951
+ pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
82952
+ maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
82953
+ // ---- valuation ----
82954
+ valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
82955
+ btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82956
+ priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82957
+ priceSource: "which oracle served the price",
82958
+ collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
82959
+ currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
82960
+ maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
82961
+ liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
82962
+ maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
82963
+ maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
82964
+ liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
82965
+ 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",
82966
+ // ---- list envelope ----
82967
+ items: "the rows of this page",
82968
+ page: "1-based page number of this response",
82969
+ pageSize: "requested rows per page",
82970
+ total: "total rows matching the filter across all pages",
82971
+ // ---- events ----
82972
+ positionCreated: "creation events (seq, time, selected term)",
82973
+ seq: "the event's sequence number within the position's history (ordering key)",
82974
+ at: "ISO timestamp of the event",
82975
+ selectedTerm: "term length chosen, in months",
82976
+ mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
82977
+ amountUcdWei: "the event's UCD amount in wei",
82978
+ feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
82979
+ payments: "repayment events: when and how much UCD was paid back",
82980
+ type: "the payment's kind label as indexed (e.g. partial/full)",
82981
+ renewals: "extension events: added term, extension fee, and the new expiry",
82982
+ extensionTerm: "months added by this extension",
82983
+ extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
82984
+ newExpiryAt: "the expiry after this extension (ISO)",
82985
+ withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
82986
+ amountSats: "the withdrawal amount in satoshis",
82987
+ networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
82988
+ targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
82989
+ liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
82990
+ other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
82991
+ totalEvents: "total events across all groups",
82992
+ // ---- pending withdrawals ----
82993
+ vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
82994
+ satoshis: "the reserved amount in satoshis",
82995
+ // ---- protocol status / terms ----
82996
+ paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
82997
+ ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
82998
+ btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
82999
+ terms: "the offered term tiers with their fee rates",
83000
+ months: "the tier's term length in months",
83001
+ originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
83002
+ extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
83003
+ // ---- psm quote ----
83004
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
83005
+ contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
83006
+ amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
83007
+ amountInToken: "the token you pay with",
83008
+ amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
83009
+ amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
83010
+ amountOutToken: "the token you receive",
83011
+ amountOutUnit: "the smallest-unit name of amountOut",
83012
+ fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
83013
+ amount: "the amount of the item it sits on, in that item's stated unit/token",
83014
+ token: "the token the amount is denominated in",
83015
+ bps: "the rate in basis points (100 bps = 1%)",
83016
+ reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
83017
+ available: "how much of the reserve is available, in its stated unit",
83018
+ unit: "the smallest-unit name for the amount it sits on",
83019
+ human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
83020
+ executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
83021
+ };
83022
+ function fieldGuide(...fields) {
83023
+ const lines = fields.map((f) => {
83024
+ const meaning = FIELD_GLOSSARY[f];
83025
+ if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
83026
+ return `${f} = ${meaning}`;
83027
+ });
83028
+ return ` Field guide: ${lines.join("; ")}.`;
82476
83029
  }
83030
+ function renderFieldGlossaryTopic() {
83031
+ const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
83032
+ return `# Reading the data \u2014 every field, its exact meaning
82477
83033
 
82478
- // src/server.ts
82479
- var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
82480
-
82481
- // src/tools/loan.ts
82482
- var import_zod = require("zod");
82483
- var import_ethers41 = require("ethers");
83034
+ The payload's fields and notes are AUTHORITATIVE. State what they say; never speculate
83035
+ past them; when the data does not carry something, say "the data does not carry X".
83036
+ Conditional \`reading\` notes in a payload are instructions for interpreting that exact
83037
+ response \u2014 follow them over any prior assumption.
82484
83038
 
82485
- // src/util/format.ts
82486
- function bigintReplacer(_key, value) {
82487
- if (typeof value === "bigint") return value.toString();
82488
- return value;
82489
- }
82490
- function serialize(data) {
82491
- return JSON.stringify(data, bigintReplacer, 2);
83039
+ ${lines.join("\n")}`;
82492
83040
  }
82493
83041
 
82494
- // src/tools/_helpers.ts
82495
- function registerBoundaryTool(server, name, config, handler) {
82496
- server.registerTool(name, config, handler);
83042
+ // src/guide/content.ts
83043
+ var GUIDE_TOPICS = [
83044
+ "getting-started",
83045
+ "first-setup",
83046
+ "connect-wallet",
83047
+ "lifecycle",
83048
+ "fees",
83049
+ "psm",
83050
+ "authorization",
83051
+ "safe",
83052
+ "delegation",
83053
+ "safety",
83054
+ "switch-network",
83055
+ "connector",
83056
+ "troubleshooting",
83057
+ "glossary",
83058
+ "reading-data"
83059
+ ];
83060
+ var GUIDE_SIGNER_MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
83061
+ var EXTERNAL_ONLY_SIGNER_MODES = ["external"];
83062
+ function offers(d, mode) {
83063
+ return d.signerModes.includes(mode);
82497
83064
  }
82498
- function renderError(error) {
82499
- const lines = [`ERROR [${error.code}]: ${error.message}`];
82500
- if (error.source) lines.push(`source: ${error.source}`);
82501
- return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
83065
+ function signerModeSourceClause(d) {
83066
+ return offers(d, "keystore") ? "the set `signer_setup` offers. `boundary://info` reports the NARROWER set the active adapter actually constructs under `capabilities.writes.signerModes` (the real adapter builds `external` + `keystore`; the practice ceremonies are mock-adapter only) \u2014 when the two differ, `boundary://info` is authoritative" : "the same set `signer_setup` offers and `boundary://info` reports under `capabilities.writes.signerModes`";
82502
83067
  }
82503
- function renderEnvelope(env) {
82504
- if (!env.ok) return renderError(env.error);
82505
- const parts = [serialize(env.data)];
82506
- if (env.warnings.length > 0) {
82507
- parts.push(
82508
- "WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
82509
- );
83068
+ var LOCAL_GUIDE_DEPLOYMENT = {
83069
+ tier: "local",
83070
+ networks: ["sepolia", "mainnet"],
83071
+ // A local install constructs the whole signer runtime: the real adapter offers
83072
+ // external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
83073
+ // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83074
+ // on the real adapter these modes refuse") carry the narrower adapter axis.
83075
+ signerModes: GUIDE_SIGNER_MODES
83076
+ };
83077
+ function servedNetworks(d) {
83078
+ if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
83079
+ const mainnet = d.networks.includes("mainnet");
83080
+ const sepolia = d.networks.includes("sepolia");
83081
+ if (mainnet && sepolia) {
83082
+ return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
82510
83083
  }
82511
- parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
82512
- return { content: [{ type: "text", text: parts.join("\n\n") }] };
83084
+ if (mainnet) {
83085
+ 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";
83086
+ }
83087
+ return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
82513
83088
  }
82514
- function validationFailed(problem) {
82515
- return renderError(boundaryError("VALIDATION_FAILED", problem));
83089
+ function connectorStatusTruth(d) {
83090
+ if (d.tier === "hosted") {
83091
+ return `**STATUS TRUTH (say this first when asked):** this session IS the hosted
83092
+ connector \u2014 the user is already on it, so there is nothing to install and no URL to hand
83093
+ out. It serves ${servedNetworks(d)}. State that money reality unprompted, and never
83094
+ promise a network, a tier or a timing this deployment does not already serve.`;
83095
+ }
83096
+ return `**STATUS TRUTH (say this first when asked):** this session is a LOCAL install,
83097
+ not the hosted connector. Whether a public connector URL is being served today is the
83098
+ operator's rollout decision and this build cannot see it \u2014 so never assert that one is
83099
+ available, and never assert that one is not. If the user already has a URL, everything
83100
+ below describes what they get; otherwise the local install paths (\`first-setup\`) are the
83101
+ way in. Never promise availability or timing.`;
82516
83102
  }
82517
- function resourceJson(env) {
82518
- if (!env.ok) return serialize({ error: env.error });
82519
- return serialize({ data: env.data, warnings: env.warnings, source: env.source });
83103
+ function connectorNetworkTruth(d) {
83104
+ if (d.tier === "hosted") {
83105
+ return `And it serves only the networks its deployment is rolled out to \u2014 this one
83106
+ serves ${servedNetworks(d)}. Which networks a deployment is rolled out to is the
83107
+ operator's deploy decision, never a hidden knob \u2014 and it is not a field of
83108
+ \`boundary://info\`, whose capabilities block reports the world THIS session is on right
83109
+ now (network, chainId, practiceWorld) plus the read/write/signer planes. \`network_switch\`
83110
+ is what states the rollout: asked for a network this deployment is not rolled out to, it
83111
+ refuses and names the ones it is.`;
83112
+ }
83113
+ return `And any connector deployment serves only the networks it is rolled out to \u2014
83114
+ which ones is the operator's deploy decision, never a hidden knob. Do not go looking for
83115
+ that list in \`boundary://info\`: its capabilities block reports the world THIS session is
83116
+ on (network, chainId, practiceWorld) plus the read/write/signer planes, never another
83117
+ deployment's rollout. \`network_switch\` is what states it \u2014 asked for a network a
83118
+ deployment is not rolled out to, it refuses and names the ones it is. This local build
83119
+ cannot see another deployment's rollout at all: ask that server, never assume.`;
82520
83120
  }
82521
- function resourceErrorJson(error) {
82522
- return serialize({ error });
83121
+ function connectorInstallNote(d) {
83122
+ if (d.tier === "hosted") {
83123
+ return `(The user is ALREADY on the fourth, zero-install path \u2014 the claude.ai
83124
+ connector \u2014 so none of the above is needed HERE; those paths are for other machines.
83125
+ Truth and trust model: \`guide connector\`.)`;
83126
+ }
83127
+ return `(A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented in this
83128
+ build. Whether it is publicly served today is the operator's rollout decision and this
83129
+ session cannot see it: do not assert either way. Truth and trust model:
83130
+ \`guide connector\`.)`;
82523
83131
  }
82524
- function requireConfirmation(confirmed, actionLabel) {
82525
- if (confirmed === true) return null;
82526
- return {
82527
- content: [
82528
- {
82529
- type: "text",
82530
- text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
82531
- This is an irreversible, fund-moving action. A human must explicitly authorize it.
82532
- Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
82533
- }
82534
- ],
82535
- isError: true
82536
- };
83132
+ function connectorTroubleshootingRow(d) {
83133
+ if (d.tier === "hosted") {
83134
+ return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 that is THIS
83135
+ session. Nothing to install, no URL to look up; it serves ${servedNetworks(d)}. Full
83136
+ truth: \`guide connector\`.`;
83137
+ }
83138
+ return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 this session is
83139
+ a local install, not that tier. Whether a public URL is being served today is the
83140
+ operator's rollout decision and this build cannot see it: do not assert either way. The
83141
+ local install paths work regardless. Full truth: \`guide connector\`.`;
82537
83142
  }
82538
- function envStamp(b) {
82539
- if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
82540
- const w = b.boundary.world();
82541
- const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
82542
- return `environment: ${w.network} \u2014 ${money}`;
83143
+ function approvalPageLocation(d) {
83144
+ if (d.tier === "hosted") {
83145
+ return `its URL is ALSO in the tool result. On this hosted tier the page is served by
83146
+ the connector itself over HTTPS on its own public origin, so ANY browser reaches it,
83147
+ including a phone's. The link carries a one-time session token \u2014 treat it as a secret,
83148
+ never forward it, and check the address bar shows that same origin before connecting a
83149
+ wallet.`;
83150
+ }
83151
+ return `its URL is ALSO in the tool result. On this local install the page is served by
83152
+ the server's own loopback listener (127.0.0.1): it exists only on the machine the
83153
+ server runs on, so open it there \u2014 no other device can reach it.`;
82543
83154
  }
82544
- async function guardedWrite(getB, fn) {
82545
- const result = await guarded(fn);
82546
- const stamp = envStamp(getB());
82547
- const content = result.content.map(
82548
- (c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
82549
-
82550
- ${stamp}` } : c
82551
- );
82552
- return { ...result, content };
83155
+ function switchNetworkHeadline(d) {
83156
+ return d.networks.length > 1 ? "sepolia \u2194 mainnet by conversation (real adapter)" : `${d.networks[0]} ONLY on this deployment (real adapter)`;
82553
83157
  }
82554
- async function guarded(fn) {
82555
- try {
82556
- return await fn();
82557
- } catch (e) {
82558
- return renderError(
82559
- boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
82560
- details: { stack: e.stack }
82561
- })
82562
- );
82563
- }
83158
+ function switchNetworkRules(d) {
83159
+ if (d.networks.length > 1) {
83160
+ return `- \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
83161
+ the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83162
+ - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83163
+ A sepolia position does not exist on mainnet and vice versa.
83164
+ - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83165
+ and every one still requires the user's explicit confirmation plus the signer
83166
+ ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
83167
+ }
83168
+ const only = d.networks[0];
83169
+ const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83170
+ 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.";
83171
+ return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
83172
+ network this deployment is rolled out to \u2014 every other target is REFUSED with that
83173
+ rollout truth. There is nothing to switch TO here; never offer the user another world.
83174
+ Money reality: ${money}.
83175
+ - State is per-network by construction: positions, vaults, signer bindings and logins
83176
+ belong to ${only} and would not exist anywhere else.
83177
+ - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
83178
+ confirmation plus the signer ceremony.
83179
+ - ${psm}`;
82564
83180
  }
82565
-
82566
- // src/util/validate.ts
82567
- var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
82568
- var SATS_SANITY_CAP = 1e10;
82569
- var UCD_SANITY_CAP = 1e9;
82570
- function checkPositionIdHex(id, label = "Position ID") {
82571
- if (!POSITION_ID_RE.test(id)) {
82572
- return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
83181
+ function wrongNetworkTroubleshootingRow(d) {
83182
+ if (d.networks.length > 1) {
83183
+ return `- **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
83184
+ (human-confirmed card; nothing carries across networks). Mock: the world is pinned by
83185
+ config \u2014 no switch exists there.`;
82573
83186
  }
82574
- return null;
83187
+ return `- **Wrong network / asks for another one** \u2014 this deployment is rolled out to
83188
+ ${d.networks[0]} alone, so \`network_switch\` refuses every other target with that
83189
+ rollout truth. Relay the refusal; do not suggest a world this service does not serve.`;
82575
83190
  }
82576
- function checkUcdAmount(amount, label = "Amount") {
82577
- if (!Number.isFinite(amount) || amount <= 0) {
82578
- return `${label} must be a positive finite number (got ${amount}).`;
82579
- }
82580
- if (amount > UCD_SANITY_CAP) {
82581
- return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
82582
- }
82583
- if (amount > 0 && amount < 1e-6) {
82584
- return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
82585
- }
82586
- const decimals = amount.toString().split(".")[1];
82587
- if (decimals && decimals.length > 6) {
82588
- return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
83191
+ function switchNetworkIndexLine(d) {
83192
+ if (d.networks.length > 1) {
83193
+ return "- switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated";
82589
83194
  }
82590
- return null;
83195
+ const only = d.networks[0];
83196
+ const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83197
+ return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
82591
83198
  }
82592
- function checkSatsAmount(sats, label = "Amount") {
82593
- if (!Number.isInteger(sats) || sats <= 0) {
82594
- return `${label} must be a positive integer (satoshis), got ${sats}.`;
82595
- }
82596
- if (sats > SATS_SANITY_CAP) {
82597
- return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
82598
- }
82599
- return null;
83199
+ function psmAvailabilityNote(d) {
83200
+ if (d.networks.includes("sepolia")) return "";
83201
+ return `**Not executable on this deployment.** The PSM write port refuses on every network
83202
+ but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
83203
+ \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
83204
+ the mechanism, not an offer: say so before a user plans around it.
83205
+
83206
+ `;
82600
83207
  }
82601
- function checkSelectedTerm(months, label = "Term") {
82602
- if (!Number.isInteger(months) || months <= 0) {
82603
- return `${label} must be a positive integer (months), got ${months}.`;
82604
- }
82605
- if (months > 120) {
82606
- return `${label} ${months} months exceeds the 10-year sanity cap.`;
82607
- }
82608
- return null;
83208
+ function authorizationModeBullets(d) {
83209
+ const bullets = [];
83210
+ if (offers(d, "external")) {
83211
+ bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
83212
+ mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
83213
+ is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
83214
+ The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
83215
+ approval page states plainly it CANNOT decode. Never extend the card promise over
83216
+ that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
83217
+ }
83218
+ if (offers(d, "keystore")) {
83219
+ bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
83220
+ Real adapter and mock.`);
83221
+ }
83222
+ if (offers(d, "safe") || offers(d, "safe-module")) {
83223
+ bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
83224
+ refuse with that true reason (their planes ship in their own deliveries).`);
83225
+ }
83226
+ if (offers(d, "mock-simulated")) {
83227
+ bullets.push(` - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).`);
83228
+ }
83229
+ return bullets.join("\n");
83230
+ }
83231
+ function keystoreAbsenceParagraph(d) {
83232
+ if (offers(d, "keystore")) return "";
83233
+ return `
83234
+ **There is no keystore mode on this build.** It is ABSENT, not disabled: the provider
83235
+ is never constructed, so no key material can exist server-side and there is nothing to
83236
+ unlock. "Sign automatically, without popups" is impossible here \u2014 say that true reason
83237
+ instead of describing a keystore, and never ask for a password.
83238
+ `;
82609
83239
  }
83240
+ function keystoreAbsenceBullet() {
83241
+ return `- **"Sign automatically / no popups" cannot happen here** \u2014 there is no keystore mode
83242
+ on this build. It is ABSENT, not disabled: the provider is never constructed, so no key
83243
+ material can exist server-side and nothing can be unlocked. Give that true reason, and
83244
+ never ask for a password.`;
83245
+ }
83246
+ var GUIDE_TOPIC_SOURCES = {
83247
+ "getting-started": `# Diamond Hands \u2014 what this is
82610
83248
 
82611
- // src/tools/loan.ts
82612
- var LATENCY_NOTES = {
82613
- mock: "Instant in this practice world.",
82614
- real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
82615
- };
82616
- var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
82617
- var confirmedSchema = import_zod.z.boolean().optional().describe(
82618
- "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
82619
- );
82620
- var DESTRUCTIVE_WRITE_ANNOTATIONS = {
82621
- readOnlyHint: false,
82622
- destructiveHint: true,
82623
- idempotentHint: false,
82624
- openWorldHint: true
82625
- };
82626
- function registerLoanTools(server, getB, adapter2 = "real") {
82627
- const LATENCY_NOTE = LATENCY_NOTES[adapter2];
82628
- registerBoundaryTool(
82629
- server,
82630
- "loan_create",
82631
- {
82632
- title: "Create a new lending position",
82633
- description: `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82634
- inputSchema: {
82635
- selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
82636
- confirmed: confirmedSchema
82637
- },
82638
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82639
- },
82640
- async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
82641
- const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
82642
- if (gate) return gate;
82643
- const problem = checkSelectedTerm(selectedTerm);
82644
- if (problem) return validationFailed(problem);
82645
- const b = getB();
82646
- if (!b.ok) return renderError(b.error);
82647
- return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
82648
- })
82649
- );
82650
- registerBoundaryTool(
82651
- server,
82652
- "loan_mint",
82653
- {
82654
- title: "Mint UCD against a position",
82655
- description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82656
- inputSchema: {
82657
- positionId: positionIdSchema,
82658
- amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
82659
- confirmed: confirmedSchema
82660
- },
82661
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82662
- },
82663
- async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
82664
- const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
82665
- if (gate) return gate;
82666
- const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
82667
- if (problem) return validationFailed(problem);
82668
- const b = getB();
82669
- if (!b.ok) return renderError(b.error);
82670
- return renderEnvelope(
82671
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
82672
- );
82673
- })
82674
- );
82675
- registerBoundaryTool(
82676
- server,
82677
- "loan_pay",
82678
- {
82679
- title: "Make a UCD payment toward a position's debt",
82680
- description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82681
- inputSchema: {
82682
- positionId: positionIdSchema,
82683
- amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
82684
- repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
82685
- confirmed: confirmedSchema
82686
- },
82687
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82688
- },
82689
- async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
82690
- if (repayAll === true === (amountUcd !== void 0)) {
82691
- return validationFailed("provide exactly one of amountUcd or repayAll: true");
82692
- }
82693
- const gate = requireConfirmation(
82694
- confirmed,
82695
- repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
82696
- );
82697
- if (gate) return gate;
82698
- const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
82699
- if (problem) return validationFailed(problem);
82700
- const b = getB();
82701
- if (!b.ok) return renderError(b.error);
82702
- let amountUcdWei;
82703
- if (repayAll) {
82704
- const detail = await b.boundary.getPosition(positionId);
82705
- if (!detail.ok) return renderError(detail.error);
82706
- if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
82707
- amountUcdWei = detail.data.debtUcdWei;
82708
- } else {
82709
- amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
82710
- }
82711
- return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
82712
- })
82713
- );
82714
- registerBoundaryTool(
82715
- server,
82716
- "loan_extend",
82717
- {
82718
- title: "Extend / renew a position's term",
82719
- description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82720
- inputSchema: {
82721
- positionId: positionIdSchema,
82722
- selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
82723
- confirmed: confirmedSchema
82724
- },
82725
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82726
- },
82727
- async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
82728
- const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
82729
- if (gate) return gate;
82730
- const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
82731
- if (problem) return validationFailed(problem);
82732
- const b = getB();
82733
- if (!b.ok) return renderError(b.error);
82734
- return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
82735
- })
82736
- );
82737
- registerBoundaryTool(
82738
- server,
82739
- "loan_withdraw",
82740
- {
82741
- title: "Withdraw BTC from a position vault",
82742
- description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82743
- inputSchema: {
82744
- positionId: positionIdSchema,
82745
- btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
82746
- amountSats: import_zod.z.number().int().positive().describe(
82747
- "GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. amountSats may be up to the whole available balance (a full sweep leaves 0 sats; anything above available reverts TargetExceedsInputValue). position_status.maxWithdrawableSats is a ready-to-use value that already leaves the default fee aside."
82748
- ),
82749
- networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
82750
- confirmed: confirmedSchema
82751
- },
82752
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82753
- },
82754
- async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
82755
- const gate = requireConfirmation(
82756
- confirmed,
82757
- `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
82758
- );
82759
- if (gate) return gate;
82760
- const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
82761
- if (problem) return validationFailed(problem);
82762
- const b = getB();
82763
- if (!b.ok) return renderError(b.error);
82764
- return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
82765
- })
82766
- );
82767
- registerBoundaryTool(
82768
- server,
82769
- "loan_allowlist_destination",
82770
- {
82771
- title: "Allowlist a BTC withdrawal destination",
82772
- description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
82773
- inputSchema: {
82774
- btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
82775
- confirmed: confirmedSchema
82776
- },
82777
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82778
- },
82779
- async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
82780
- const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
82781
- if (gate) return gate;
82782
- const b = getB();
82783
- if (!b.ok) return renderError(b.error);
82784
- return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
82785
- })
82786
- );
82787
- registerBoundaryTool(
82788
- server,
82789
- "loan_delegation_setup",
82790
- {
82791
- title: "Install delegation on the Safe (one owner ceremony)",
82792
- description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
82793
- inputSchema: {
82794
- btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
82795
- confirmed: confirmedSchema
82796
- },
82797
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82798
- },
82799
- async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
82800
- const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
82801
- if (gate) return gate;
82802
- const b = getB();
82803
- if (!b.ok) return renderError(b.error);
82804
- return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
82805
- })
82806
- );
82807
- registerBoundaryTool(
82808
- server,
82809
- "loan_delegation_grant",
82810
- {
82811
- title: "Grant the agent per-position scopes (owners sign)",
82812
- description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
82813
- inputSchema: {
82814
- positionId: positionIdSchema,
82815
- renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
82816
- repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
82817
- mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
82818
- confirmed: confirmedSchema
82819
- },
82820
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82821
- },
82822
- async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
82823
- const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
82824
- if (gate) return gate;
82825
- const b = getB();
82826
- if (!b.ok) return renderError(b.error);
82827
- return renderEnvelope(
82828
- await b.boundary.delegationGrant({
82829
- positionId,
82830
- renew: renew ?? false,
82831
- repay: repay ?? false,
82832
- mintFloorBps: mintFloorBps ?? null
82833
- })
82834
- );
82835
- })
82836
- );
82837
- registerBoundaryTool(
82838
- server,
82839
- "loan_recover_stale_spend",
82840
- {
82841
- title: "Recover a stale BTC reservation via LIT-attested proof",
82842
- description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
82843
- inputSchema: {
82844
- positionId: positionIdSchema,
82845
- utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
82846
- utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
82847
- invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
82848
- minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
82849
- },
82850
- annotations: {
82851
- readOnlyHint: false,
82852
- destructiveHint: false,
82853
- idempotentHint: true,
82854
- openWorldHint: true
82855
- }
82856
- },
82857
- async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
82858
- const problem = checkPositionIdHex(positionId);
82859
- if (problem) return validationFailed(problem);
82860
- const b = getB();
82861
- if (!b.ok) return renderError(b.error);
82862
- return renderEnvelope(
82863
- await b.boundary.recoverStaleSpend({
82864
- positionId,
82865
- utxoTxid,
82866
- utxoVout,
82867
- invalidatorTxid,
82868
- ...minConfirmations !== void 0 ? { minConfirmations } : {}
82869
- })
82870
- );
82871
- })
82872
- );
82873
- }
83249
+ Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
83250
+ without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
83251
+ against it, pay it back whenever you like, and take your BTC out again.
82874
83252
 
82875
- // src/tools/position.ts
82876
- var import_zod2 = require("zod");
83253
+ **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
83254
+ topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
83255
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
83256
+ are enabled (and the true reason when not), and which signer modes this build offers;
83257
+ never promise a capability it does not list. The money truth has THREE cases:
83258
+ - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
83259
+ - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
83260
+ the test network: real ceremonies and signatures, PRACTICE money (test funds).
83261
+ - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
83262
+ explicitly arms them; the capabilities block states which applies.
83263
+ SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
82877
83264
 
82878
- // src/boundary/field-glossary.ts
82879
- var FIELD_GLOSSARY = {
82880
- // ---- identity / envelope structure ----
82881
- positionId: "the position's 32-byte id (0x\u202664 hex) \u2014 the input every position_* tool takes",
82882
- borrower: "the Ethereum address that owns the position (the borrowing identity)",
82883
- vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
82884
- pkpId: "internal id of the programmable key pair holding BTC custody for this position",
82885
- id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
82886
- kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
82887
- fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
82888
- // ---- position facts (chain) ----
82889
- state: "lifecycle state. On position_status it is read from the CHAIN (authoritative); on position_list rows it is an INDEXER snapshot that can lag the chain. PENDING_DEPOSIT/PENDING_MINT mean 'not yet minted' \u2014 activation happens on the FIRST mint, never on deposit confirmation alone",
82890
- termMonths: "the current term length in months",
82891
- totalTermMonths: "cumulative months across the original term plus every extension",
82892
- createdAt: "ISO timestamp the position was created",
82893
- expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
82894
- previousExpiryAt: "the expiry before the latest extension (null when never extended)",
82895
- lastUpdatedAt: "ISO timestamp of the last state change",
82896
- debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
82897
- // ---- indexed health (indexer snapshot) ----
82898
- indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
82899
- collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
82900
- healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
82901
- asOf: "ISO timestamp the indexer snapshot was computed",
82902
- basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
82903
- // ---- collateral (live BTC view) ----
82904
- collateral: "the live Bitcoin-side view of the position's vault",
82905
- availableSats: "CONFIRMED collateral in satoshis, minus authorized (reserved) spends \u2014 deposits count only once their confirmations reach minConfirmations. null ONLY alongside a SOURCE_DEGRADED warning, never a fabricated zero",
82906
- availableSource: "which source served availableSats (null when degraded)",
82907
- pendingDeposits: "the LIVE per-transaction list of unconfirmed deposits \u2014 each entry carries its own confirmations count. EMPTY ARRAY = nothing unconfirmed in flight (not an error). null ONLY with a SOURCE_DEGRADED warning",
82908
- txid: "Bitcoin transaction id",
82909
- sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
82910
- confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
82911
- minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
82912
- pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
82913
- maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
82914
- // ---- valuation ----
82915
- valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
82916
- btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82917
- priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
82918
- priceSource: "which oracle served the price",
82919
- collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
82920
- currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
82921
- maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
82922
- liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
82923
- maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
82924
- maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
82925
- liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
82926
- reading: "conditional reading notes emitted by the server ONLY while a known misreading trap is live \u2014 treat them as authoritative instructions for interpreting this exact payload",
82927
- // ---- list envelope ----
82928
- items: "the rows of this page",
82929
- page: "1-based page number of this response",
82930
- pageSize: "requested rows per page",
82931
- total: "total rows matching the filter across all pages",
82932
- // ---- events ----
82933
- positionCreated: "creation events (seq, time, selected term)",
82934
- seq: "the event's sequence number within the position's history (ordering key)",
82935
- at: "ISO timestamp of the event",
82936
- selectedTerm: "term length chosen, in months",
82937
- mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
82938
- amountUcdWei: "the event's UCD amount in wei",
82939
- feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
82940
- payments: "repayment events: when and how much UCD was paid back",
82941
- type: "the payment's kind label as indexed (e.g. partial/full)",
82942
- renewals: "extension events: added term, extension fee, and the new expiry",
82943
- extensionTerm: "months added by this extension",
82944
- extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
82945
- newExpiryAt: "the expiry after this extension (ISO)",
82946
- withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
82947
- amountSats: "the withdrawal amount in satoshis",
82948
- networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
82949
- targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
82950
- liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
82951
- other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
82952
- totalEvents: "total events across all groups",
82953
- // ---- pending withdrawals ----
82954
- vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
82955
- satoshis: "the reserved amount in satoshis",
82956
- // ---- protocol status / terms ----
82957
- paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
82958
- ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
82959
- btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
82960
- terms: "the offered term tiers with their fee rates",
82961
- months: "the tier's term length in months",
82962
- originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
82963
- extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
82964
- // ---- psm quote ----
82965
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
82966
- contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
82967
- amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
82968
- amountInToken: "the token you pay with",
82969
- amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
82970
- amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
82971
- amountOutToken: "the token you receive",
82972
- amountOutUnit: "the smallest-unit name of amountOut",
82973
- fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
82974
- amount: "the amount of the item it sits on, in that item's stated unit/token",
82975
- token: "the token the amount is denominated in",
82976
- bps: "the rate in basis points (100 bps = 1%)",
82977
- reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
82978
- available: "how much of the reserve is available, in its stated unit",
82979
- unit: "the smallest-unit name for the amount it sits on",
82980
- human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
82981
- executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
82982
- };
82983
- function fieldGuide(...fields) {
82984
- const lines = fields.map((f) => {
82985
- const meaning = FIELD_GLOSSARY[f];
82986
- if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
82987
- return `${f} = ${meaning}`;
82988
- });
82989
- return ` Field guide: ${lines.join("; ")}.`;
82990
- }
82991
- function renderFieldGlossaryTopic() {
82992
- const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
82993
- return `# Reading the data \u2014 every field, its exact meaning
83265
+ A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
83266
+ authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
83267
+ calls. Every operation that moves funds requires the user's explicit confirmation
83268
+ (\`confirmed: true\`) \u2014 nothing is ever silent.`,
83269
+ "first-setup": (d) => `# First setup \u2014 from zero to ready, by conversation only
82994
83270
 
82995
- The payload's fields and notes are AUTHORITATIVE. State what they say; never speculate
82996
- past them; when the data does not carry something, say "the data does not carry X".
82997
- Conditional \`reading\` notes in a payload are instructions for interpreting that exact
82998
- response \u2014 follow them over any prior assumption.
83271
+ Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
83272
+ \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
83273
+ host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
83274
+ developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
83275
+ install matrix. ${connectorInstallNote(d)}
82999
83276
 
83000
- ${lines.join("\n")}`;
83001
- }
83277
+ Nothing needs a config file. Three steps:
83002
83278
 
83003
- // src/tools/position.ts
83004
- var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
83005
- var POSITION_STATES = [
83006
- "PENDING_DEPOSIT",
83007
- "PENDING_MINT",
83008
- "ACTIVE",
83009
- "EXPIRED",
83010
- "LIQUIDATABLE",
83011
- "LIQUIDATED",
83012
- "REPAID",
83013
- "CLOSED"
83014
- ];
83015
- function registerPositionTools(server, getB) {
83016
- registerBoundaryTool(
83017
- server,
83018
- "position_status",
83019
- {
83020
- title: "Get a position's full status",
83021
- description: "Return detailed status for a single position: chain facts (debt, term, expiry, state), live collateral (confirmed sats + per-transaction pending deposits, plus maxWithdrawableSats \u2014 directly usable as a withdrawal amountSats), and a basis-carrying valuation (maxMintableUcd is directly usable as amountUcd). If a withdrawal reservation was already spent on Bitcoin but availableSats still shows it deducted, run loan_recover_stale_spend to release the redundant hold. Any `reading` notes in the result are authoritative interpretation instructions for that exact payload \u2014 follow them." + fieldGuide("state", "availableSats", "minConfirmations", "pendingDeposits", "maxWithdrawableSats", "maxMintableUcd", "debtUcdWei"),
83022
- inputSchema: {
83023
- id: positionIdSchema2
83024
- }
83025
- },
83026
- async ({ id }) => guarded(async () => {
83027
- const problem = checkPositionIdHex(id);
83028
- if (problem) return validationFailed(problem);
83029
- const b = getB();
83030
- if (!b.ok) return renderError(b.error);
83031
- return renderEnvelope(await b.boundary.getPosition(id));
83032
- })
83033
- );
83034
- registerBoundaryTool(
83035
- server,
83036
- "position_list",
83037
- {
83038
- title: "List lending positions",
83039
- description: "List positions with optional filters. `borrower` and `state` COMBINE (logical AND); with no filter, returns active positions. Rows are the INDEXER's view \u2014 `state` here is an indexer snapshot that can lag the chain; position_status reads the chain and is authoritative for one position." + fieldGuide("state", "debtUcdWei", "indexedHealth"),
83040
- inputSchema: {
83041
- borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
83042
- state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
83043
- page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
83044
- pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
83045
- }
83046
- },
83047
- async ({ borrower, state, page, pageSize }) => guarded(async () => {
83048
- if (state !== void 0 && !POSITION_STATES.includes(state)) {
83049
- return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
83050
- }
83051
- const b = getB();
83052
- if (!b.ok) return renderError(b.error);
83053
- const filter2 = {
83054
- page,
83055
- pageSize,
83056
- ...borrower !== void 0 ? { borrower } : {},
83057
- ...state !== void 0 ? { state } : {}
83058
- };
83059
- if (filter2.borrower === void 0 && filter2.state === void 0) {
83060
- return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
83061
- }
83062
- return renderEnvelope(await b.boundary.listPositions(filter2));
83063
- })
83064
- );
83065
- registerBoundaryTool(
83066
- server,
83067
- "position_events",
83068
- {
83069
- title: "Get a position's event history",
83070
- description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
83071
- inputSchema: {
83072
- id: positionIdSchema2
83073
- }
83074
- },
83075
- async ({ id }) => guarded(async () => {
83076
- const problem = checkPositionIdHex(id);
83077
- if (problem) return validationFailed(problem);
83078
- const b = getB();
83079
- if (!b.ok) return renderError(b.error);
83080
- return renderEnvelope(await b.boundary.getPositionEvents(id));
83081
- })
83082
- );
83083
- registerBoundaryTool(
83084
- server,
83085
- "position_pending_withdrawals",
83086
- {
83087
- title: "List a position's pending BTC withdrawal reservations",
83088
- description: "Query the spend authorizer for BTC withdrawal reservations on a position. Each entry has txid/vout, satoshis, and target address (txid/vout feed recovery).",
83089
- inputSchema: {
83090
- id: positionIdSchema2
83091
- }
83092
- },
83093
- async ({ id }) => guarded(async () => {
83094
- const problem = checkPositionIdHex(id);
83095
- if (problem) return validationFailed(problem);
83096
- const b = getB();
83097
- if (!b.ok) return renderError(b.error);
83098
- return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
83099
- })
83100
- );
83101
- }
83279
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83280
+ \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83281
+ (practice money) or mainnet (real money); whether writes are enabled here and which
83282
+ signer modes exist; current terms (\`protocol_terms\`).
83102
83283
 
83103
- // src/tools/btc.ts
83104
- var import_zod3 = require("zod");
83105
- function registerBtcTools(server, getB) {
83106
- registerBoundaryTool(
83107
- server,
83108
- "btc_balance",
83109
- {
83110
- title: "Get BTC balance for an address",
83111
- description: "Query the confirmed BTC balance for an address (source-tagged).",
83112
- inputSchema: {
83113
- address: import_zod3.z.string().min(1).describe("BTC address to query")
83114
- }
83115
- },
83116
- async ({ address }) => guarded(async () => {
83117
- const b = getB();
83118
- if (!b.ok) return renderError(b.error);
83119
- return renderEnvelope(await b.boundary.getBitcoinBalance(address));
83120
- })
83121
- );
83122
- registerBoundaryTool(
83123
- server,
83124
- "btc_price",
83125
- {
83126
- title: "Get the current BTC price",
83127
- description: "Return the current BTC price (USD, 8 decimals) from the price oracle.",
83128
- inputSchema: {}
83129
- },
83130
- async () => guarded(async () => {
83131
- const b = getB();
83132
- if (!b.ok) return renderError(b.error);
83133
- return renderEnvelope(await b.boundary.getBitcoinPrice());
83134
- })
83135
- );
83136
- }
83137
-
83138
- // src/tools/protocol.ts
83139
- function registerProtocolTools(server, getB) {
83140
- registerBoundaryTool(
83141
- server,
83142
- "protocol_status",
83143
- {
83144
- title: "Get protocol configuration and status",
83145
- description: "Return protocol status: pause flag, mint LTV limit (ltvBps), liquidation threshold (liquidationThresholdBps \u2014 a COLLATERAL RATIO in bps, i.e. collateralValue/debt, so 11000 = 110%; note this is the inverse basis of ltvBps which is debt/collateral), deposit confirmation threshold, BTC network.",
83146
- inputSchema: {}
83147
- },
83148
- async () => guarded(async () => {
83149
- const b = getB();
83150
- if (!b.ok) return renderError(b.error);
83151
- return renderEnvelope(await b.boundary.getProtocolStatus());
83152
- })
83153
- );
83154
- registerBoundaryTool(
83155
- server,
83156
- "protocol_terms",
83157
- {
83158
- title: "List available loan terms with fees",
83159
- description: "Return all configured loan terms (in months) with their fees. Term length: 12 months = exactly 365 days; any other term = N \xD7 30-day months. originationFeeBps: % of a mint, ADDED to debt. extensionFeeRateBps: the renewal fee CEILING as % of outstanding debt PER RENEWAL (a flat rate, NOT per month); the charged fee is ADDED TO DEBT and reduced by origination fees already paid this term.",
83160
- inputSchema: {}
83161
- },
83162
- async () => guarded(async () => {
83163
- const b = getB();
83164
- if (!b.ok) return renderError(b.error);
83165
- return renderEnvelope(await b.boundary.getTerms());
83166
- })
83167
- );
83168
- }
83169
-
83170
- // src/tools/psm.ts
83171
- var import_zod4 = require("zod");
83172
- var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
83173
- "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
83174
- );
83175
- var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
83176
- readOnlyHint: false,
83177
- destructiveHint: true,
83178
- idempotentHint: false,
83179
- openWorldHint: true
83180
- };
83181
- function registerPsmTools(server, getB) {
83182
- registerBoundaryTool(
83183
- server,
83184
- "psm_quote",
83185
- {
83186
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
83187
- description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
83188
- inputSchema: {
83189
- direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = get UCD for USDC (contract swap); 'to-usdc' = get USDC back for UCD (contract redeem)"),
83190
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
83191
- },
83192
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
83193
- },
83194
- async ({ direction, amount }) => guarded(async () => {
83195
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
83196
- const problem = checkUcdAmount(amount, label);
83197
- if (problem) return validationFailed(problem);
83198
- const b = getB();
83199
- if (!b.ok) return renderError(b.error);
83200
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
83201
- })
83202
- );
83203
- registerBoundaryTool(
83204
- server,
83205
- "psm_swap",
83206
- {
83207
- title: "Exchange UCD \u2194 USDC through the PSM",
83208
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
83209
- inputSchema: {
83210
- direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = pay USDC, get UCD (contract swap); 'to-usdc' = pay UCD, get USDC back (contract redeem)"),
83211
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
83212
- confirmed: confirmedSchema2
83213
- },
83214
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
83215
- },
83216
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
83217
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
83218
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
83219
- const gate = requireConfirmation(
83220
- confirmed,
83221
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
83222
- );
83223
- if (gate) return gate;
83224
- const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
83225
- if (problem) return validationFailed(problem);
83226
- const b = getB();
83227
- if (!b.ok) return renderError(b.error);
83228
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
83229
- })
83230
- );
83231
- }
83232
-
83233
- // src/tools/mock-control.ts
83234
- var import_zod5 = require("zod");
83235
- var ACTIONS = [
83236
- "submit-deposit",
83237
- "confirm-deposit",
83238
- "confirm-spend-consumed",
83239
- "advance-time",
83240
- "set-btc-price",
83241
- "set-paused",
83242
- "set-wallet",
83243
- "liquidate",
83244
- "deploy-safe",
83245
- "revoke-agent",
83246
- "inject-fault",
83247
- "clear-fault",
83248
- "psm-set-paused",
83249
- "psm-set-redeem-enabled",
83250
- "psm-set-reserves",
83251
- "psm-set-fees",
83252
- "psm-mint-usdc"
83253
- ];
83254
- function requireField(value, name, action) {
83255
- if (value === void 0) {
83256
- throw new Error(`action '${action}' requires '${name}'`);
83257
- }
83258
- return value;
83259
- }
83260
- function run(control, a, chainId) {
83261
- switch (a.action) {
83262
- case "submit-deposit": {
83263
- const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
83264
- return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
83265
- }
83266
- case "confirm-deposit": {
83267
- const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
83268
- return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
83269
- }
83270
- case "confirm-spend-consumed": {
83271
- control.confirmSpendConsumed(
83272
- requireField(a.txid, "txid", a.action),
83273
- requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
83274
- requireField(a.confirmations, "confirmations", a.action)
83275
- );
83276
- return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
83277
- }
83278
- case "advance-time": {
83279
- control.advanceTime(requireField(a.seconds, "seconds", a.action));
83280
- return { simulated: "virtual clock advanced", seconds: a.seconds };
83281
- }
83282
- case "set-btc-price": {
83283
- control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
83284
- return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
83285
- }
83286
- case "set-paused": {
83287
- control.setPaused(requireField(a.paused, "paused", a.action));
83288
- return { simulated: "protocol pause flag set", paused: a.paused };
83289
- }
83290
- case "set-wallet": {
83291
- control.setWalletStance(requireField(a.stance, "stance", a.action));
83292
- return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
83293
- }
83294
- case "liquidate": {
83295
- control.liquidate(requireField(a.positionId, "positionId", a.action));
83296
- return { simulated: "liquidation executed", positionId: a.positionId };
83297
- }
83298
- case "deploy-safe": {
83299
- const safe = control.deploySafe({
83300
- owners: requireField(a.owners, "owners", a.action),
83301
- threshold: requireField(a.threshold, "threshold", a.action),
83302
- chainId
83303
- });
83304
- return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
83305
- }
83306
- case "revoke-agent": {
83307
- const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
83308
- return {
83309
- simulated: "agent revoked and BURNED forever (AR-1 \u2014 plan 09 test lever; on the real protocol the owners or the deny-only registrar revoke)",
83310
- ...r
83311
- };
83312
- }
83313
- case "inject-fault": {
83314
- control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
83315
- return { simulated: "fault armed", faultKey: a.faultKey };
83316
- }
83317
- case "clear-fault": {
83318
- control.clearFault(requireField(a.faultKey, "faultKey", a.action));
83319
- return { simulated: "fault cleared", faultKey: a.faultKey };
83320
- }
83321
- case "psm-set-paused": {
83322
- control.psmSetPaused(requireField(a.paused, "paused", a.action));
83323
- return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
83324
- }
83325
- case "psm-set-redeem-enabled": {
83326
- control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
83327
- return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
83328
- }
83329
- case "psm-set-reserves": {
83330
- control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
83331
- return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
83332
- }
83333
- case "psm-mint-usdc": {
83334
- const r = control.psmMintUsdc(
83335
- requireField(a.holder, "holder", a.action),
83336
- requireField(a.usdcUnits, "usdcUnits", a.action)
83337
- );
83338
- return {
83339
- simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
83340
- holder: a.holder,
83341
- minted: a.usdcUnits,
83342
- newBalanceUnits: r.newBalanceUnits
83343
- };
83344
- }
83345
- case "psm-set-fees": {
83346
- control.psmSetFees({
83347
- ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
83348
- ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
83349
- });
83350
- return {
83351
- simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
83352
- ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
83353
- ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
83354
- };
83355
- }
83356
- }
83357
- }
83358
- function registerMockControlTool(server, control, chainId = 1337) {
83359
- registerBoundaryTool(
83360
- server,
83361
- "mock_control",
83362
- {
83363
- title: "SIMULATOR control (mock world only)",
83364
- description: "Drive the simulated rest-of-the-world of the MOCK protocol: broadcast/confirm BTC deposits, confirm reserved spends, advance the virtual clock, set the oracle price, pause the protocol, liquidate, arm/clear faults, and drive the simulated PSM (pause, redeemEnabled, reserves, fees, practice-USDC mint). This tool exists ONLY against the mock adapter \u2014 nothing here touches or ever exists on the real protocol.",
83365
- inputSchema: {
83366
- action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
83367
- positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
83368
- txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
83369
- sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
83370
- confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
83371
- invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
83372
- seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
83373
- priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
83374
- paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
83375
- stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
83376
- owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
83377
- threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
83378
- safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
83379
- faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
83380
- faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
83381
- enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
83382
- reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
83383
- entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
83384
- exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
83385
- holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
83386
- usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
83387
- },
83388
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
83389
- },
83390
- async (args) => guarded(async () => {
83391
- let result;
83392
- try {
83393
- result = run(control, args, chainId);
83394
- } catch (e) {
83395
- return validationFailed(e.message);
83396
- }
83397
- if (result === void 0) {
83398
- return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
83399
- }
83400
- return { content: [{ type: "text", text: serialize(result) }] };
83401
- })
83402
- );
83403
- }
83404
-
83405
- // src/tools/signer.ts
83406
- var import_zod6 = require("zod");
83407
- var import_ethers42 = require("ethers");
83408
- var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
83409
- var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
83410
- var EXTERNAL_ONLY_MODES = ["external"];
83411
- var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
83412
- function looksSecretShaped(value) {
83413
- return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
83414
- }
83415
- var SECRET_REFUSAL = "That value looks like a password or key. NEVER paste secrets into the conversation \u2014 they would enter the model context and transcripts. To provide keystore material, say 'unlock my keystore' (a secure local page opens and the password goes directly to the server), or set DH_KEYSTORE_PATH/DH_KEYSTORE_PASSWORD in the server environment.";
83416
- function registerSignerTool(server, getRuntime, opts) {
83417
- const externalOnly = opts?.externalOnly === true;
83418
- const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
83419
- const description = externalOnly ? "Inspect or manage how operations are authorized. This build is EXTERNAL-WALLET-ONLY: every operation is approved in YOUR OWN wallet (browser wallet, or mobile via WalletConnect); the server can never sign by itself. Actions: 'status' (what is active, what is connected \u2014 start here), 'use' (mode 'external' \u2014 the only mode this build offers), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'connect' (run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out: the FULL wallet flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect." : "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat), 'connect' (external mode, real protocol: run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out of the external wallet: the FULL flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect.";
83420
- registerBoundaryTool(
83421
- server,
83422
- "signer_setup",
83423
- {
83424
- title: "Choose how operations are authorized",
83425
- description,
83426
- inputSchema: {
83427
- action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
83428
- mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
83429
- ...externalOnly ? {} : {
83430
- safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
83431
- }
83432
- },
83433
- annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
83434
- },
83435
- async ({ action, mode, safeAddress }) => guarded(async () => {
83436
- const runtime = getRuntime();
83437
- if (!runtime) {
83438
- return renderError(
83439
- boundaryError(
83440
- "SIGNER_UNAVAILABLE",
83441
- "no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
83442
- )
83443
- );
83444
- }
83445
- const { manager, bridge } = runtime;
83446
- if (mode !== void 0 && !offeredModes.includes(mode)) {
83447
- return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
83448
- }
83449
- if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
83450
- return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
83451
- }
83452
- if (action === "status") {
83453
- await bridge.start();
83454
- const s = manager.status();
83455
- return ok({
83456
- ...s,
83457
- // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
83458
- // identity is known. borrower = a persisted binding; candidate = a live
83459
- // wallet connection in THIS process only.
83460
- identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
83461
- approvalPageUrl: bridge.url(),
83462
- hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
83463
- });
83464
- }
83465
- if (action === "use") {
83466
- if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
83467
- const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
83468
- if (!r.ok) return validationFailed(r.reason);
83469
- if (mode === "safe-module") {
83470
- const s = manager.status();
83471
- return ok({
83472
- mode,
83473
- safe: s.safe,
83474
- agent: s.keystoreAddress,
83475
- next: "This session operates AS the Safe with DELEGATION: the keystore key is the AGENT. One owner ceremony installs it (loan_delegation_setup \u2014 enables the module, binds the agent, pre-approves BTC destinations); afterwards create/mint/pay/extend run agent-solo (per-position grants via loan_delegation_grant, a quorum signature). The agent can NEVER withdraw alone, add destinations, or manage the module \u2014 withdrawals still gather the owners for a short signing burst. See guide topic 'delegation'."
83476
- });
83477
- }
83478
- if (mode === "safe") {
83479
- const s = manager.status();
83480
- return ok({
83481
- mode,
83482
- safe: s.safe,
83483
- next: "This session now operates AS the Safe. Operations are authorized by owner signatures (this phase: the local keystore owner signs; it also submits transactions). BTC withdrawals additionally need the destination allowlisted first \u2014 see loan_allowlist_destination."
83484
- });
83485
- }
83486
- if (mode === "external") {
83487
- await bridge.start();
83488
- return ok({
83489
- mode,
83490
- approvalPageUrl: bridge.url(),
83491
- next: "Open the approval page and connect your wallet (browser extension, or 'Use a mobile wallet' for WalletConnect). Each operation will then ask for your approval there."
83492
- });
83493
- }
83494
- return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
83495
- }
83496
- if (action === "connect") {
83497
- if (!runtime.connect) {
83498
- return validationFailed(
83499
- "action 'connect' applies to the real protocol's external mode (lit-ops login). This adapter has no separate login step \u2014 pick a mode with 'use' and writes will ceremony as needed."
83500
- );
83501
- }
83502
- const r = await runtime.connect();
83503
- if (!r.ok) return validationFailed(r.reason);
83504
- const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
83505
- return ok({
83506
- connected: true,
83507
- address: r.address,
83508
- login,
83509
- next: (login === "cached-session" ? "Logged in via a still-valid CACHED session \u2014 no wallet signature was requested. To force a full logout first, use 'disconnect'. " : "Logged in with a FRESH wallet signature. ") + "Authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
83510
- });
83511
- }
83512
- if (action === "disconnect") {
83513
- if (!runtime.disconnect) {
83514
- return validationFailed(
83515
- "this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
83516
- );
83517
- }
83518
- const report = await runtime.disconnect();
83519
- const f = report.flushed;
83520
- const tokenLine = !report.hadLogin ? "login token: none existed" : f.upstreamRevoked >= f.loginSessions ? `login token: discarded from memory AND revoked at the service (${f.upstreamRevoked} revoked)` : `login token: discarded from this process's memory; ${f.upstreamRevoked}/${f.loginSessions} could be revoked at the service \u2014 an unrevoked token stays valid upstream until its natural expiry (it was never stored on disk)`;
83521
- return ok({
83522
- disconnected: true,
83523
- mode: manager.mode(),
83524
- flushed: {
83525
- ...f,
83526
- note: tokenLine
83527
- },
83528
- whatThisServerCannotRevoke: "Your wallet's own site permission for the approval-page origin \u2014 revoke it wallet-side (MetaMask: Settings \u2192 Connections / Connected sites \u2192 remove this site).",
83529
- // Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
83530
- // relationship; the OAuth session is a separate thing with its own revocation.
83531
- // Neither claims to do the other's job.
83532
- ...bridge.isHosted() ? {
83533
- oauthSession: "This disconnect ends the WALLET relationship only. Your assistant's connection to this MCP server (the OAuth session) stays alive until you revoke it on the claude.ai side (connector settings) \u2014 and revoking THAT does not disconnect your wallet here."
83534
- } : {},
83535
- next: `Wallet disconnected \u2014 mode stays '${manager.mode()}'. Reconnecting requires opening the approval page again (signer_setup 'status' shows the link) and a fresh wallet signature ('connect').`
83536
- });
83537
- }
83538
- if (action === "reset-borrower") {
83539
- manager.resetBorrower();
83540
- return ok({
83541
- reset: true,
83542
- next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower. NOTE: this is an identity swap, NOT a disconnect \u2014 any wallet connection and login session remain alive; use 'disconnect' to log out fully."
83543
- });
83544
- }
83545
- await bridge.start();
83546
- const unlockUrl = bridge.unlockUrl();
83547
- return ok({
83548
- unlockPageUrl: unlockUrl,
83549
- next: "Open this local page and enter the keystore password THERE (never in chat). Paste an encrypted keystore JSON or generate a fresh one, then say 'use keystore'."
83550
- });
83551
- })
83552
- );
83553
- }
83554
- function ok(data) {
83555
- return { content: [{ type: "text", text: serialize(data) }] };
83556
- }
83557
-
83558
- // src/tools/guide.ts
83559
- var import_zod7 = require("zod");
83560
-
83561
- // src/guide/content.ts
83562
- var GUIDE_TOPICS = [
83563
- "getting-started",
83564
- "first-setup",
83565
- "connect-wallet",
83566
- "lifecycle",
83567
- "fees",
83568
- "psm",
83569
- "authorization",
83570
- "safe",
83571
- "delegation",
83572
- "safety",
83573
- "switch-network",
83574
- "connector",
83575
- "troubleshooting",
83576
- "glossary",
83577
- "reading-data"
83578
- ];
83579
- var GUIDE_CONTENT = {
83580
- "getting-started": `# Diamond Hands \u2014 what this is
83581
-
83582
- Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
83583
- without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
83584
- against it, pay it back whenever you like, and take your BTC out again.
83585
-
83586
- **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
83587
- topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
83588
- \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
83589
- are enabled (and the true reason when not), and which signer modes this build offers;
83590
- never promise a capability it does not list. The money truth has THREE cases:
83591
- - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
83592
- - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
83593
- the test network: real ceremonies and signatures, PRACTICE money (test funds).
83594
- - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
83595
- explicitly arms them; the capabilities block states which applies.
83596
- SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
83597
-
83598
- A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
83599
- authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
83600
- calls. Every operation that moves funds requires the user's explicit confirmation
83601
- (\`confirmed: true\`) \u2014 nothing is ever silent.`,
83602
- "first-setup": `# First setup \u2014 from zero to ready, by conversation only
83603
-
83604
- Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
83605
- \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
83606
- host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
83607
- developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
83608
- install matrix. (A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented
83609
- but NOT yet publicly served; its rollout is operator-gated. Truth and trust model:
83610
- \`guide connector\`.)
83611
-
83612
- Nothing needs a config file. Three steps:
83613
-
83614
- **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83615
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83616
- (practice money) or mainnet (real money); whether writes are enabled here and which
83617
- signer modes exist; current terms (\`protocol_terms\`).
83618
-
83619
- **2. Choose HOW to authorize operations** (the user's choice, made by talking):
83620
- - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
83621
- on the real adapter and the mock. The approval page auto-opens in the browser (its URL
83622
- is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
83623
- / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
83624
- their own wallet. The first verified signature binds their wallet address as the
83625
- borrower. Full walkthrough: \`guide connect-wallet\`.
83626
- - **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
83627
- signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
83628
- \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
83629
- LOCAL PAGE opens where the user types the password or generates a fresh keystore.
83630
- NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
83631
- them to use the unlock page instead.
83632
- - **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
83633
- real adapter they refuse with that true reason. Try them in a mock world.
83634
- - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
83635
- - **No signer is also a valid start:** every public read works without one \u2014
83636
- \`position_list {borrower}\` with the user's address needs no signer and no login.
83637
- - **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
83638
- talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
83639
- the money reality after any switch.
83284
+ **2. Choose HOW to authorize operations** (the user's choice, made by talking):
83285
+ - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
83286
+ on the real adapter and the mock. The approval page auto-opens in the browser (its URL
83287
+ is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
83288
+ / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
83289
+ their own wallet. The first verified signature binds their wallet address as the
83290
+ borrower. Full walkthrough: \`guide connect-wallet\`.
83291
+ ${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
83292
+ signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
83293
+ \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
83294
+ LOCAL PAGE opens where the user types the password or generates a fresh keystore.
83295
+ NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
83296
+ them to use the unlock page instead.` : keystoreAbsenceBullet()}
83297
+ ${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
83298
+ 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
83299
+ surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
83300
+ \`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
83301
+ - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
83302
+ - **No signer is also a valid start:** every public read works without one \u2014
83303
+ \`position_list {borrower}\` with the user's address needs no signer and no login.
83304
+ ${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
83305
+ talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
83306
+ the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
83307
+ \`network_switch\` refuses every other target with that rollout truth. See
83308
+ \`guide switch-network\`; never offer a world this service does not serve.`}
83640
83309
 
83641
83310
  **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
83642
83311
  \`confirmed: true\` from the user). Then deposit BTC to the vault address
@@ -83644,7 +83313,7 @@ signer modes exist; current terms (\`protocol_terms\`).
83644
83313
  and mint with \`loan_mint\`.
83645
83314
 
83646
83315
  The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
83647
- "connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
83316
+ "connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
83648
83317
 
83649
83318
  External mode means the user approves every operation in their OWN wallet \u2014 a browser
83650
83319
  extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
@@ -83652,17 +83321,19 @@ the mock.
83652
83321
 
83653
83322
  **The walkthrough:**
83654
83323
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83655
- desktop browser; its URL is ALSO in the tool result (loopback-only \u2014 open it on the
83656
- same machine the server runs on).
83324
+ desktop browser; ${approvalPageLocation(d)}
83657
83325
  2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
83658
83326
  WalletConnect QR code or paste the pairing code.
83659
83327
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83660
83328
  login ceremony explicitly (one typed-data signature in the wallet).
83661
83329
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
83662
83330
  across sessions (\`signer_setup reset-borrower\` unbinds it).
83663
- 5. From then on, every fund-moving operation shows an approval card in the wallet,
83664
- decoded from the exact transaction bytes \u2014 what you read IS what executes. Declining
83665
- always safely cancels.
83331
+ 5. From then on, every fund-moving operation shows an approval card in the wallet. For
83332
+ TRANSACTIONS that card is decoded from the exact bytes being signed \u2014 what you read
83333
+ IS what executes. The ONE exception is the BTC withdrawal, which signs an opaque
83334
+ 32-byte hash the page states plainly it CANNOT decode (honesty note below); say so
83335
+ before those popups, never "what you read is what executes". Declining always safely
83336
+ cancels.
83666
83337
 
83667
83338
  **Popup cadence \u2014 exactly this many wallet interactions per operation:**
83668
83339
 
@@ -83674,7 +83345,7 @@ the mock.
83674
83345
  | repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
83675
83346
  | extend | 1 personal-sign + 1 tx |
83676
83347
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
83677
- | withdraw BTC | not available in external mode yet (refuses with that reason); keystore mode works, no popups |
83348
+ | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
83678
83349
  | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
83679
83350
 
83680
83351
  **Honesty notes (say these plainly):**
@@ -83685,10 +83356,19 @@ the mock.
83685
83356
  authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
83686
83357
  surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
83687
83358
  login means "wait and retry", not a wallet failure.
83688
- - **Withdraw-BTC under external mode is a BLIND signature** \u2014 the SDK builds the two
83689
- withdrawal auth hashes internally, so the approval page shows the bare hash and says
83690
- plainly it cannot decode the contents (the production web app signs the same way).
83691
- Tell the user this before the popups: two hash signatures, then the BTC moves.
83359
+ - **Withdraw-BTC under external mode has ONE blind signature, not two.** The
83360
+ authorization phase is EIP-712 typed data \u2014 the wallet renders position, amount and
83361
+ destination and the user can read it. Only the EXECUTE phase signs an opaque 32-byte
83362
+ hash the SDK builds internally, which the approval page shows bare and says plainly it
83363
+ cannot decode (the production web app signs the same way). Tell the user before that
83364
+ ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
83365
+ expect an unreadable card and click through the readable one.
83366
+ - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83367
+ valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83368
+ attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83369
+ back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83370
+ charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83371
+ signature. The blind execute popup happens once.
83692
83372
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83693
83373
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83694
83374
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83744,9 +83424,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83744
83424
 
83745
83425
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83746
83426
  signed, amounts included. Read it back when the user asks what happened.`,
83747
- psm: `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83427
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83748
83428
 
83749
- The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83429
+ ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83750
83430
  directions, in user words:
83751
83431
 
83752
83432
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83793,24 +83473,18 @@ own address. If you approve step 1 but decline step 2, the exact-amount allowanc
83793
83473
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83794
83474
  On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83795
83475
  (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
83796
- authorization: `# Authorization \u2014 who signs, and what a signature means
83476
+ authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83797
83477
 
83798
83478
  Every fund-moving operation needs TWO things, always in this order:
83799
83479
  1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
83800
83480
  must ask, never assume.
83801
- 2. **A cryptographic authorization** by the chosen signer mode:
83802
- - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
83803
- mobile via QR/paste-code). Real adapter and mock. The approval card in the wallet
83804
- shows EXACTLY what executes \u2014 amounts are decoded from the transaction itself, never
83805
- re-formatted. Walkthrough: \`guide connect-wallet\`.
83806
- - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
83807
- Real adapter and mock.
83808
- - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
83809
- refuse with that true reason (their planes ship in their own deliveries).
83810
- - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
83811
-
83481
+ 2. **A cryptographic authorization** by the chosen signer mode. This build offers
83482
+ exactly ${d.signerModes.map((m) => `\`${m}\``).join(", ")} \u2014 ${signerModeSourceClause(d)}. Never
83483
+ describe a mode outside it:
83484
+ ${authorizationModeBullets(d)}
83485
+ ${keystoreAbsenceParagraph(d)}
83812
83486
  **Reads never summon the wallet.** Public reads need no signer at all. Authenticated
83813
- reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
83487
+ reads need a login \u2014 ${offers(d, "keystore") ? "the keystore env pair, or " : ""}an explicit "connect my wallet"
83814
83488
  (\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
83815
83489
  only ever caused by a write ceremony or that explicit connect. The login (one typed-data
83816
83490
  signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
@@ -83826,9 +83500,28 @@ BOUND by the first verified signature (it persists across sessions). Connected \
83826
83500
  picking external mode is a preference \u2014 a wallet still has to connect on the approval
83827
83501
  page, and the page link comes from \`signer_setup status\`.
83828
83502
 
83829
- Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat;
83830
- keystore passwords go only into the secure unlock page.`,
83831
- safe: `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
83503
+ 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."}`,
83504
+ // Rendered on the capability axis: a build that constructs no Safe-shaped mode must not
83505
+ // hand a user a setup walkthrough its `signer_setup` cannot accept (the F1/F2 class,
83506
+ // one topic over). The concepts a Safe owner still needs stay; the instructions go.
83507
+ safe: (d) => !offers(d, "safe") ? `# Safe accounts \u2014 not offered by this build
83508
+
83509
+ A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
83510
+ signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Diamond Hands can
83511
+ treat a Safe AS THE BORROWER \u2014 but not from here. This build's authorization surface is
83512
+ the wallet ceremony alone; \`signer_setup\` lists no Safe-shaped option, so there is
83513
+ nothing to set up. Say that plainly instead of walking a user through a ceremony this
83514
+ service cannot run.
83515
+
83516
+ **What still holds for a Safe's position anywhere:** its BTC withdrawal destination must
83517
+ be ALLOWLISTED first, and the allowlist delay is READ LIVE from the chain \u2014 24 hours on
83518
+ mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS. Owner authorizations
83519
+ for mint/pay/renew expire in minutes and withdrawal authorizations within the minute, so
83520
+ a multi-owner signing session happens TOGETHER, live.
83521
+
83522
+ **Where it does exist:** the local install's practice worlds run the Safe borrower plane
83523
+ end to end, and the web app (diamondhands.credit) speaks to the same chain state. A user
83524
+ who needs it is not blocked \u2014 they are on the wrong surface for it.` : `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
83832
83525
 
83833
83526
  A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
83834
83527
  signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companies and
@@ -83864,7 +83557,24 @@ expire after ~3 minutes, and withdrawal authorizations within the minute \u2014
83864
83557
  owner signing session happens TOGETHER, live ("gather first, sign in one burst").
83865
83558
  Creating a position and allowlisting a destination have NO expiry \u2014 owners can sign
83866
83559
  those at their own pace. The ceremony guides this; never widen a window.`,
83867
- delegation: `# Delegation \u2014 one owner ceremony, then day-to-day solo
83560
+ delegation: (d) => !offers(d, "safe-module") ? `# Delegation \u2014 not offered by this build
83561
+
83562
+ Delegation is the protocol's answer to multi-owner Safes: the owners sign ONCE to install
83563
+ a tightly-caged AGENT key, and day-to-day work then runs without disturbing them. It is a
83564
+ Safe-shaped authorization plane, and this build constructs none \u2014 \`signer_setup\` lists
83565
+ no such option and \`loan_delegation_setup\` has no plane to install into here. Say that
83566
+ plainly rather than describing a ceremony this service cannot run.
83567
+
83568
+ **The cage, for a user who asks what it would mean:** an agent may create a position and
83569
+ \u2014 only after the owners grant it, per position \u2014 repay, renew, and mint while the
83570
+ post-mint collateral ratio stays at or above the floor the owners set. It can NEVER
83571
+ withdraw Bitcoin alone, never add or change withdrawal destinations, never touch the
83572
+ module or the registry, never move ETH. A stolen agent key can shuffle money WITHIN a
83573
+ position \u2014 never out. Revoking an agent BURNS its address forever, which is why
83574
+ revocation is always safe.
83575
+
83576
+ **Where it does exist:** the local install's practice worlds, pending the plane's own
83577
+ delivery on the real adapter. The web app and the SDK reach the same chain state.` : `# Delegation \u2014 one owner ceremony, then day-to-day solo
83868
83578
 
83869
83579
  Multi-owner Safes cannot practically sign every operation inside the protocol's short
83870
83580
  signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
@@ -83908,8 +83618,11 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
83908
83618
 
83909
83619
  - **Nothing moves without you.** Every write needs \`confirmed: true\` AND the signer
83910
83620
  ceremony. A decline anywhere cleanly cancels \u2014 declining is always safe.
83911
- - **The card is the truth.** In external mode the wallet card is decoded from the exact
83912
- transaction bytes being signed \u2014 what you read IS what executes.
83621
+ - **The card is the truth \u2014 with one named exception.** In external mode the wallet card
83622
+ is decoded from the exact TRANSACTION bytes being signed: what you read IS what
83623
+ executes. The exception is the BTC-withdraw blind signature \u2014 an opaque 32-byte hash
83624
+ the approval page says plainly it cannot decode (\`guide connect-wallet\`). Never
83625
+ extend the "what you read is what executes" promise over that one.
83913
83626
  - **Liquidation:** if collateral value falls so the collateral ratio drops under the
83914
83627
  liquidation threshold (\`protocol_status.liquidationThresholdBps\`, e.g. 110%), the
83915
83628
  position can be liquidated. Watch \`position_status.valuation\` \u2014 \`currentLtvBps\` vs the
@@ -83922,23 +83635,21 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
83922
83635
  withdrawing to a wrong address. Repaid-in-full positions release all collateral.
83923
83636
  - **Practice vs real:** mock worlds are stated as such (\`boundary://info\`). Never let a
83924
83637
  user believe practice gains/losses are real, or vice versa.`,
83925
- "switch-network": `# Switch network \u2014 sepolia \u2194 mainnet by conversation (real adapter)
83638
+ "switch-network": (d) => `# Switch network \u2014 ${switchNetworkHeadline(d)}
83926
83639
 
83927
83640
  The \`network_switch\` tool moves THIS SESSION between worlds. Check
83928
83641
  \`boundary://info\` capabilities first: \`networkSwitch: true\` means it is available
83929
83642
  (real adapter); in a practice sandbox (mock) the world is pinned by config \u2014 there is
83930
83643
  no switch, and that is by design.
83931
83644
 
83645
+ **Served here:** ${servedNetworks(d)}. A network this deployment does not serve is
83646
+ refused with that reason \u2014 the tool existing is not a promise that both worlds are
83647
+ reachable, so never offer the user a network this deployment does not serve.
83648
+
83932
83649
  **The rules, plainly:**
83933
83650
  - \`network_switch status\` \u2014 which network is active and whether money is real. Say
83934
83651
  this to the user BEFORE and AFTER any switch, always.
83935
- - \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
83936
- the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83937
- - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83938
- A sepolia position does not exist on mainnet and vice versa.
83939
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83940
- and every one still requires the user's explicit confirmation plus the signer
83941
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.
83652
+ ${switchNetworkRules(d)}
83942
83653
  - A pending signing ceremony blocks the switch (finish or decline it first).
83943
83654
  - The switch is session-scoped: when the server restarts, the configured default
83944
83655
  network returns.
@@ -83948,12 +83659,9 @@ reality in your next message. The user must never have to ask which world they a
83948
83659
  // Plan 17 B1 — the hosted tier's truth, in user language. The trust ledger below is
83949
83660
  // the plan-12 Part 0 ledger (BINDING, archive/12-remote-connector.md) — all six
83950
83661
  // entries, verbatim-equivalent; G-CONN pins anchor phrases from every entry.
83951
- connector: `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
83662
+ connector: (d) => `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
83952
83663
 
83953
- **STATUS TRUTH (say this first when asked):** the connector is IMPLEMENTED but NOT yet
83954
- publicly served \u2014 the operator's rollout gates (a security audit, then a URL) come
83955
- first. Until then there is no URL to give out, and the local install paths
83956
- (\`first-setup\`) are the way in. Never promise availability or timing.
83664
+ ${connectorStatusTruth(d)}
83957
83665
 
83958
83666
  **What it is:** instead of installing anything, the user adds Diamond Hands to
83959
83667
  claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
@@ -83980,9 +83688,17 @@ honestly when asked "is this safe"):
83980
83688
  is never written to disk. A breach here is privacy-class, never money-class.
83981
83689
  3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
83982
83690
  a security concern is filed and audited for exactly this channel.
83983
- 4. **Tenant separation.** Your identity \u2194 wallet \u2194 session binding is isolated from
83984
- every other user's; a failure here would be privacy-class, never signing-class,
83985
- because no key material exists server-side to leak.
83691
+ 4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
83692
+ gets its own world: its own boundary, its own signer state, its own approval-page
83693
+ mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
83694
+ world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
83695
+ plus an earlier connection would make a different wallet this session's signer. That
83696
+ is signing-class, not merely privacy-class; do not tell a user it cannot be. What
83697
+ contains it: the mount id is freshly random per world and travels only in the user's
83698
+ own tool result (treat the link as a secret), and EVERY fund movement verifies the
83699
+ signature against that bound borrower \u2014 no key material exists server-side, so
83700
+ whoever reaches the page still cannot sign for anyone else. The gap is filed and
83701
+ audited; state it this way rather than claiming a binding that isn't there.
83986
83702
  5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
83987
83703
  version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
83988
83704
  reports the exact server version.
@@ -83994,30 +83710,37 @@ honestly when asked "is this safe"):
83994
83710
 
83995
83711
  **What it structurally CANNOT do:** hold keys or custody \u2014 keystore mode is ABSENT
83996
83712
  from the connector build (not disabled: never constructed), so every fund-moving
83997
- action needs a fresh signature from the user's own wallet. And it serves only the
83998
- networks its deployment is rolled out to \u2014 this deployment serves sepolia during
83999
- rollout; mainnet enablement is the operator's deploy decision, stated in capabilities
84000
- by reason, never a hidden knob.
83713
+ action needs a fresh signature from the user's own wallet. ${connectorNetworkTruth(d)}
84001
83714
 
84002
83715
  **Independent exits:** the web app (diamondhands.credit) and the SDK speak to the SAME
84003
83716
  chain state. The connector going down strands nothing and gates nothing.`,
84004
- troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
83717
+ troubleshooting: (d) => `# Troubleshooting \u2014 what error codes mean, in plain words
84005
83718
 
84006
- - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
83719
+ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
84007
83720
  keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
84008
83721
  "connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
84009
83722
  status\` explains what is active; \`first-setup\` step 2 has the full choice.
84010
83723
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
84011
83724
  the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
84012
- EXPIRED login refuses the same way \u2014 reconnect on the user's word.
84013
- - **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
84014
- not a bug); loan operations work on mainnet. Reads keep working everywhere.
84015
- - **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
84016
- (human-confirmed card; nothing carries across networks). Mock: the world is pinned by
84017
- config \u2014 no switch exists there.
83725
+ 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
83726
+ ONE remedy: the user says "connect my wallet" \u2192 \`signer_setup\` action \`connect\`
83727
+ (external mode). There is no keystore here to configure and no password to supply \u2014
83728
+ saying otherwise sends the user hunting for a setting that does not exist.
83729
+ \`signer_setup status\` explains what is active; \`first-setup\` step 2 has the choice.
83730
+ - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83731
+ the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
83732
+ the same way \u2014 reconnect on the user's word.`}
83733
+ ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83734
+ 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
83735
+ anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
83736
+ ${wrongNetworkTroubleshootingRow(d)}
84018
83737
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
84019
- SDK builds the withdrawal auth hashes internally, so the page cannot decode them.
84020
- Two blind hash signatures per withdrawal; warn the user before triggering them.
83738
+ SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
83739
+ signature per withdrawal, not two: the authorization phase is EIP-712 typed data
83740
+ (\`WithdrawRequest\` \u2014 the wallet renders position, amount and destination), and only
83741
+ the execute phase is opaque. Warn the user before that one popup, and do not describe
83742
+ the typed one as blind \u2014 overstating it teaches them to expect an unreadable card and
83743
+ click through the readable one.
84021
83744
  - **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
84022
83745
  That is the broker throttle, not a wallet failure.
84023
83746
  - **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
@@ -84032,9 +83755,7 @@ chain state. The connector going down strands nothing and gates nothing.`,
84032
83755
  which source and when from. Prefer chain-sourced values; re-read before acting.
84033
83756
  - Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
84034
83757
  Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
84035
- - **Asked for the claude.ai connector / remote / hosted tier** \u2014 implemented, NOT yet
84036
- publicly served (the operator's audit + rollout gates come first). There is no URL to
84037
- give out; the local install paths work today. Full truth: \`guide connector\`.
83758
+ ${connectorTroubleshootingRow(d)}
84038
83759
  - **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
84039
83760
  the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
84040
83761
  Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
@@ -84054,7 +83775,8 @@ Synonym sets (treat these as the SAME intent):
84054
83775
  - **UCD** = the dollar-pegged token you borrow ("the dollars")
84055
83776
  - **sats** = satoshis, 1 BTC = 100,000,000 sats
84056
83777
  - **connector** = remote = hosted tier = "claude.ai integration" = "use it without
84057
- installing" \u2192 \`guide connector\` (status: implemented, not yet publicly served)
83778
+ installing" \u2192 \`guide connector\` (it states which tier THIS session is, and the
83779
+ trust model that comes with it)
84058
83780
 
84059
83781
  Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
84060
83782
  - **vault** \u2014 the position's BTC custody address. Its balance is your COLLATERAL, not
@@ -84065,39 +83787,1099 @@ Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
84065
83787
  - **interest** \u2014 Diamond Hands charges FEES (origination/extension), not running
84066
83788
  interest; see \`fees\`.
84067
83789
 
84068
- Language: answer in the user's language, whatever it is. These mappings apply to meaning,
84069
- not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
84070
- "emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
84071
- // Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
84072
- // the same entries the anchor test pins against the actually-serialized fields.
84073
- "reading-data": renderFieldGlossaryTopic()
83790
+ Language: answer in the user's language, whatever it is. These mappings apply to meaning,
83791
+ not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
83792
+ "emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
83793
+ // Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
83794
+ // the same entries the anchor test pins against the actually-serialized fields.
83795
+ "reading-data": renderFieldGlossaryTopic()
83796
+ };
83797
+ function renderGuideContent(deployment) {
83798
+ const content = {};
83799
+ for (const topic of GUIDE_TOPICS) {
83800
+ const source = GUIDE_TOPIC_SOURCES[topic];
83801
+ content[topic] = typeof source === "string" ? source : source(deployment);
83802
+ }
83803
+ return content;
83804
+ }
83805
+ function renderGuideIndex(deployment) {
83806
+ 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";
83807
+ return `# Diamond Hands guide \u2014 topics
83808
+
83809
+ - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
83810
+ - first-setup \u2014 zero to ready by conversation (authorization choice included)
83811
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
83812
+ - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
83813
+ - fees \u2014 the two fee models, plainly
83814
+ - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
83815
+ - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
83816
+ ${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"}
83817
+ ${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"}
83818
+ - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
83819
+ ${switchNetworkIndexLine(deployment)}
83820
+ ${connectorLine}
83821
+ - troubleshooting \u2014 error codes in plain words, with the real remedies
83822
+ - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
83823
+ - reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
83824
+
83825
+ Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
83826
+ selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
83827
+ signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
83828
+ and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
83829
+ only mainnet is real money.`;
83830
+ }
83831
+ var deploymentKey = (d) => `${d.tier}|${d.networks.join(",")}|${d.signerModes.join(",")}`;
83832
+ var RENDERED = /* @__PURE__ */ new Map();
83833
+ function renderedGuide(deployment) {
83834
+ const key = deploymentKey(deployment);
83835
+ let rendered = RENDERED.get(key);
83836
+ if (!rendered) {
83837
+ rendered = Object.freeze({
83838
+ content: Object.freeze(renderGuideContent(deployment)),
83839
+ index: renderGuideIndex(deployment)
83840
+ });
83841
+ RENDERED.set(key, rendered);
83842
+ }
83843
+ return rendered;
83844
+ }
83845
+ function buildGuideContent(deployment) {
83846
+ return renderedGuide(deployment).content;
83847
+ }
83848
+ function buildGuideIndex(deployment) {
83849
+ return renderedGuide(deployment).index;
83850
+ }
83851
+ var GUIDE_CONTENT = buildGuideContent(LOCAL_GUIDE_DEPLOYMENT);
83852
+ var GUIDE_INDEX = buildGuideIndex(LOCAL_GUIDE_DEPLOYMENT);
83853
+
83854
+ // src/network-switch.ts
83855
+ var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
83856
+ function createNetworkSwitchRuntime(opts) {
83857
+ return {
83858
+ current() {
83859
+ const b = opts.getBoot().boundaryResult;
83860
+ if (!b.ok) return null;
83861
+ const w = b.boundary.world();
83862
+ return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
83863
+ },
83864
+ async switchTo(network) {
83865
+ const allowed = opts.overrides?.allowedNetworks;
83866
+ if (allowed && !allowed.includes(network)) {
83867
+ return {
83868
+ ok: false,
83869
+ error: boundaryError(
83870
+ "VALIDATION_FAILED",
83871
+ `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.`
83872
+ )
83873
+ };
83874
+ }
83875
+ const targetEnv = { ...opts.env, DH_NETWORK: network };
83876
+ const configResult = resolveBoundaryConfig(targetEnv);
83877
+ if (!configResult.ok) return { ok: false, error: configResult.error };
83878
+ const next = await buildBoundary(configResult, opts.overrides);
83879
+ if (!next.boundaryResult.ok) {
83880
+ next.dispose();
83881
+ return { ok: false, error: next.boundaryResult.error };
83882
+ }
83883
+ opts.swap(next);
83884
+ return { ok: true };
83885
+ }
83886
+ };
83887
+ }
83888
+ function guideDeployment(overrides) {
83889
+ return {
83890
+ tier: overrides?.bridgeMount ? "hosted" : "local",
83891
+ networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
83892
+ signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
83893
+ };
83894
+ }
83895
+ function assembleWorld(opts) {
83896
+ let boot = opts.boot;
83897
+ const deps = {
83898
+ boundaryResult: boot.boundaryResult,
83899
+ ...boot.mockControl ? { mockControl: boot.mockControl } : {},
83900
+ ...boot.signer ? { signer: boot.signer } : {},
83901
+ ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
83902
+ deployment: guideDeployment(opts.overrides),
83903
+ ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
83904
+ };
83905
+ if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
83906
+ deps.networkSwitch = createNetworkSwitchRuntime({
83907
+ env: opts.env,
83908
+ getBoot: () => boot,
83909
+ ...opts.overrides ? { overrides: opts.overrides } : {},
83910
+ swap: (next) => {
83911
+ const old = boot;
83912
+ boot = next;
83913
+ deps.boundaryResult = next.boundaryResult;
83914
+ if (next.signer) deps.signer = next.signer;
83915
+ else delete deps.signer;
83916
+ old.dispose();
83917
+ const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
83918
+ opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
83919
+ }
83920
+ });
83921
+ }
83922
+ return { deps, dispose: () => boot.dispose() };
83923
+ }
83924
+
83925
+ // src/server.ts
83926
+ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
83927
+
83928
+ // src/tools/loan.ts
83929
+ var import_zod = require("zod");
83930
+ var import_ethers41 = require("ethers");
83931
+
83932
+ // src/util/format.ts
83933
+ function bigintReplacer(_key, value) {
83934
+ if (typeof value === "bigint") return value.toString();
83935
+ return value;
83936
+ }
83937
+ function serialize(data) {
83938
+ return JSON.stringify(data, bigintReplacer, 2);
83939
+ }
83940
+
83941
+ // src/tools/_helpers.ts
83942
+ function registerBoundaryTool(server, name, config, handler) {
83943
+ server.registerTool(name, config, handler);
83944
+ }
83945
+ function renderError(error) {
83946
+ const lines = [`ERROR [${error.code}]: ${error.message}`];
83947
+ if (error.source) lines.push(`source: ${error.source}`);
83948
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
83949
+ }
83950
+ function renderEnvelope(env) {
83951
+ if (!env.ok) return renderError(env.error);
83952
+ const parts = [serialize(env.data)];
83953
+ if (env.warnings.length > 0) {
83954
+ parts.push(
83955
+ "WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
83956
+ );
83957
+ }
83958
+ parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
83959
+ return { content: [{ type: "text", text: parts.join("\n\n") }] };
83960
+ }
83961
+ function validationFailed(problem) {
83962
+ return renderError(boundaryError("VALIDATION_FAILED", problem));
83963
+ }
83964
+ function resourceJson(env) {
83965
+ if (!env.ok) return serialize({ error: env.error });
83966
+ return serialize({ data: env.data, warnings: env.warnings, source: env.source });
83967
+ }
83968
+ function resourceErrorJson(error) {
83969
+ return serialize({ error });
83970
+ }
83971
+ function requireConfirmation(confirmed, actionLabel) {
83972
+ if (confirmed === true) return null;
83973
+ return {
83974
+ content: [
83975
+ {
83976
+ type: "text",
83977
+ text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
83978
+ This is an irreversible, fund-moving action. A human must explicitly authorize it.
83979
+ Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
83980
+ }
83981
+ ],
83982
+ isError: true
83983
+ };
83984
+ }
83985
+ function envStamp(b) {
83986
+ if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
83987
+ const w = b.boundary.world();
83988
+ const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
83989
+ return `environment: ${w.network} \u2014 ${money}`;
83990
+ }
83991
+ async function guardedWrite(getB, fn) {
83992
+ const result = await guarded(fn);
83993
+ const stamp = envStamp(getB());
83994
+ const content = result.content.map(
83995
+ (c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
83996
+
83997
+ ${stamp}` } : c
83998
+ );
83999
+ return { ...result, content };
84000
+ }
84001
+ async function guarded(fn) {
84002
+ try {
84003
+ return await fn();
84004
+ } catch (e) {
84005
+ return renderError(
84006
+ boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
84007
+ details: { stack: e.stack }
84008
+ })
84009
+ );
84010
+ }
84011
+ }
84012
+
84013
+ // src/util/validate.ts
84014
+ var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
84015
+ var SATS_SANITY_CAP = 1e10;
84016
+ var UCD_SANITY_CAP = 1e9;
84017
+ function checkPositionIdHex(id, label = "Position ID") {
84018
+ if (!POSITION_ID_RE.test(id)) {
84019
+ return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
84020
+ }
84021
+ return null;
84022
+ }
84023
+ function checkUcdAmount(amount, label = "Amount") {
84024
+ if (!Number.isFinite(amount) || amount <= 0) {
84025
+ return `${label} must be a positive finite number (got ${amount}).`;
84026
+ }
84027
+ if (amount > UCD_SANITY_CAP) {
84028
+ return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
84029
+ }
84030
+ if (amount > 0 && amount < 1e-6) {
84031
+ return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
84032
+ }
84033
+ const decimals = amount.toString().split(".")[1];
84034
+ if (decimals && decimals.length > 6) {
84035
+ return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
84036
+ }
84037
+ return null;
84038
+ }
84039
+ function checkSatsAmount(sats, label = "Amount") {
84040
+ if (!Number.isInteger(sats) || sats <= 0) {
84041
+ return `${label} must be a positive integer (satoshis), got ${sats}.`;
84042
+ }
84043
+ if (sats > SATS_SANITY_CAP) {
84044
+ return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
84045
+ }
84046
+ return null;
84047
+ }
84048
+ function checkSelectedTerm(months, label = "Term") {
84049
+ if (!Number.isInteger(months) || months <= 0) {
84050
+ return `${label} must be a positive integer (months), got ${months}.`;
84051
+ }
84052
+ if (months > 120) {
84053
+ return `${label} ${months} months exceeds the 10-year sanity cap.`;
84054
+ }
84055
+ return null;
84056
+ }
84057
+
84058
+ // src/tools/loan.ts
84059
+ var LATENCY_NOTES = {
84060
+ mock: "Instant in this practice world.",
84061
+ real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
84062
+ };
84063
+ var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
84064
+ var confirmedSchema = import_zod.z.boolean().optional().describe(
84065
+ "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
84066
+ );
84067
+ var DESTRUCTIVE_WRITE_ANNOTATIONS = {
84068
+ readOnlyHint: false,
84069
+ destructiveHint: true,
84070
+ idempotentHint: false,
84071
+ openWorldHint: true
84072
+ };
84073
+ function registerLoanTools(server, getB, adapter2 = "real") {
84074
+ const LATENCY_NOTE = LATENCY_NOTES[adapter2];
84075
+ registerBoundaryTool(
84076
+ server,
84077
+ "loan_create",
84078
+ {
84079
+ title: "Create a new lending position",
84080
+ 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).`,
84081
+ inputSchema: {
84082
+ selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
84083
+ confirmed: confirmedSchema
84084
+ },
84085
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84086
+ },
84087
+ async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
84088
+ const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
84089
+ if (gate) return gate;
84090
+ const problem = checkSelectedTerm(selectedTerm);
84091
+ if (problem) return validationFailed(problem);
84092
+ const b = getB();
84093
+ if (!b.ok) return renderError(b.error);
84094
+ return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
84095
+ })
84096
+ );
84097
+ registerBoundaryTool(
84098
+ server,
84099
+ "loan_mint",
84100
+ {
84101
+ title: "Mint UCD against a position",
84102
+ 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).`,
84103
+ inputSchema: {
84104
+ positionId: positionIdSchema,
84105
+ amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
84106
+ confirmed: confirmedSchema
84107
+ },
84108
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84109
+ },
84110
+ async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
84111
+ const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
84112
+ if (gate) return gate;
84113
+ const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
84114
+ if (problem) return validationFailed(problem);
84115
+ const b = getB();
84116
+ if (!b.ok) return renderError(b.error);
84117
+ return renderEnvelope(
84118
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
84119
+ );
84120
+ })
84121
+ );
84122
+ registerBoundaryTool(
84123
+ server,
84124
+ "loan_pay",
84125
+ {
84126
+ title: "Make a UCD payment toward a position's debt",
84127
+ 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).`,
84128
+ inputSchema: {
84129
+ positionId: positionIdSchema,
84130
+ amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
84131
+ repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
84132
+ confirmed: confirmedSchema
84133
+ },
84134
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84135
+ },
84136
+ async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
84137
+ if (repayAll === true === (amountUcd !== void 0)) {
84138
+ return validationFailed("provide exactly one of amountUcd or repayAll: true");
84139
+ }
84140
+ const gate = requireConfirmation(
84141
+ confirmed,
84142
+ repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
84143
+ );
84144
+ if (gate) return gate;
84145
+ const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
84146
+ if (problem) return validationFailed(problem);
84147
+ const b = getB();
84148
+ if (!b.ok) return renderError(b.error);
84149
+ let amountUcdWei;
84150
+ if (repayAll) {
84151
+ const detail = await b.boundary.getPosition(positionId);
84152
+ if (!detail.ok) return renderError(detail.error);
84153
+ if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
84154
+ amountUcdWei = detail.data.debtUcdWei;
84155
+ } else {
84156
+ amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
84157
+ }
84158
+ return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
84159
+ })
84160
+ );
84161
+ registerBoundaryTool(
84162
+ server,
84163
+ "loan_extend",
84164
+ {
84165
+ title: "Extend / renew a position's term",
84166
+ 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).`,
84167
+ inputSchema: {
84168
+ positionId: positionIdSchema,
84169
+ selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
84170
+ confirmed: confirmedSchema
84171
+ },
84172
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84173
+ },
84174
+ async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
84175
+ const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
84176
+ if (gate) return gate;
84177
+ const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
84178
+ if (problem) return validationFailed(problem);
84179
+ const b = getB();
84180
+ if (!b.ok) return renderError(b.error);
84181
+ return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
84182
+ })
84183
+ );
84184
+ registerBoundaryTool(
84185
+ server,
84186
+ "loan_withdraw",
84187
+ {
84188
+ title: "Withdraw BTC from a position vault",
84189
+ 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).`,
84190
+ inputSchema: {
84191
+ positionId: positionIdSchema,
84192
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
84193
+ amountSats: import_zod.z.number().int().positive().describe(
84194
+ "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."
84195
+ ),
84196
+ 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"),
84197
+ confirmed: confirmedSchema
84198
+ },
84199
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84200
+ },
84201
+ async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
84202
+ const gate = requireConfirmation(
84203
+ confirmed,
84204
+ `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
84205
+ );
84206
+ if (gate) return gate;
84207
+ const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
84208
+ if (problem) return validationFailed(problem);
84209
+ const b = getB();
84210
+ if (!b.ok) return renderError(b.error);
84211
+ return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
84212
+ })
84213
+ );
84214
+ registerBoundaryTool(
84215
+ server,
84216
+ "loan_allowlist_destination",
84217
+ {
84218
+ title: "Allowlist a BTC withdrawal destination",
84219
+ 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).`,
84220
+ inputSchema: {
84221
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
84222
+ confirmed: confirmedSchema
84223
+ },
84224
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84225
+ },
84226
+ async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
84227
+ const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
84228
+ if (gate) return gate;
84229
+ const b = getB();
84230
+ if (!b.ok) return renderError(b.error);
84231
+ return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
84232
+ })
84233
+ );
84234
+ registerBoundaryTool(
84235
+ server,
84236
+ "loan_delegation_setup",
84237
+ {
84238
+ title: "Install delegation on the Safe (one owner ceremony)",
84239
+ 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).`,
84240
+ inputSchema: {
84241
+ 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)"),
84242
+ confirmed: confirmedSchema
84243
+ },
84244
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84245
+ },
84246
+ async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
84247
+ const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
84248
+ if (gate) return gate;
84249
+ const b = getB();
84250
+ if (!b.ok) return renderError(b.error);
84251
+ return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
84252
+ })
84253
+ );
84254
+ registerBoundaryTool(
84255
+ server,
84256
+ "loan_delegation_grant",
84257
+ {
84258
+ title: "Grant the agent per-position scopes (owners sign)",
84259
+ 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).`,
84260
+ inputSchema: {
84261
+ positionId: positionIdSchema,
84262
+ renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
84263
+ repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
84264
+ 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"),
84265
+ confirmed: confirmedSchema
84266
+ },
84267
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84268
+ },
84269
+ async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
84270
+ const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
84271
+ if (gate) return gate;
84272
+ const b = getB();
84273
+ if (!b.ok) return renderError(b.error);
84274
+ return renderEnvelope(
84275
+ await b.boundary.delegationGrant({
84276
+ positionId,
84277
+ renew: renew ?? false,
84278
+ repay: repay ?? false,
84279
+ mintFloorBps: mintFloorBps ?? null
84280
+ })
84281
+ );
84282
+ })
84283
+ );
84284
+ registerBoundaryTool(
84285
+ server,
84286
+ "loan_recover_stale_spend",
84287
+ {
84288
+ title: "Recover a stale BTC reservation via LIT-attested proof",
84289
+ 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.",
84290
+ inputSchema: {
84291
+ positionId: positionIdSchema,
84292
+ utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
84293
+ utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
84294
+ invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
84295
+ minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
84296
+ },
84297
+ annotations: {
84298
+ readOnlyHint: false,
84299
+ destructiveHint: false,
84300
+ idempotentHint: true,
84301
+ openWorldHint: true
84302
+ }
84303
+ },
84304
+ async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
84305
+ const problem = checkPositionIdHex(positionId);
84306
+ if (problem) return validationFailed(problem);
84307
+ const b = getB();
84308
+ if (!b.ok) return renderError(b.error);
84309
+ return renderEnvelope(
84310
+ await b.boundary.recoverStaleSpend({
84311
+ positionId,
84312
+ utxoTxid,
84313
+ utxoVout,
84314
+ invalidatorTxid,
84315
+ ...minConfirmations !== void 0 ? { minConfirmations } : {}
84316
+ })
84317
+ );
84318
+ })
84319
+ );
84320
+ }
84321
+
84322
+ // src/tools/position.ts
84323
+ var import_zod2 = require("zod");
84324
+ var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
84325
+ var POSITION_STATES = [
84326
+ "PENDING_DEPOSIT",
84327
+ "PENDING_MINT",
84328
+ "ACTIVE",
84329
+ "EXPIRED",
84330
+ "LIQUIDATABLE",
84331
+ "LIQUIDATED",
84332
+ "REPAID",
84333
+ "CLOSED"
84334
+ ];
84335
+ function registerPositionTools(server, getB) {
84336
+ registerBoundaryTool(
84337
+ server,
84338
+ "position_status",
84339
+ {
84340
+ title: "Get a position's full status",
84341
+ 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"),
84342
+ inputSchema: {
84343
+ id: positionIdSchema2
84344
+ }
84345
+ },
84346
+ async ({ id }) => guarded(async () => {
84347
+ const problem = checkPositionIdHex(id);
84348
+ if (problem) return validationFailed(problem);
84349
+ const b = getB();
84350
+ if (!b.ok) return renderError(b.error);
84351
+ return renderEnvelope(await b.boundary.getPosition(id));
84352
+ })
84353
+ );
84354
+ registerBoundaryTool(
84355
+ server,
84356
+ "position_list",
84357
+ {
84358
+ title: "List lending positions",
84359
+ 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"),
84360
+ inputSchema: {
84361
+ borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
84362
+ state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
84363
+ page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
84364
+ pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
84365
+ }
84366
+ },
84367
+ async ({ borrower, state, page, pageSize }) => guarded(async () => {
84368
+ if (state !== void 0 && !POSITION_STATES.includes(state)) {
84369
+ return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
84370
+ }
84371
+ const b = getB();
84372
+ if (!b.ok) return renderError(b.error);
84373
+ const filter2 = {
84374
+ page,
84375
+ pageSize,
84376
+ ...borrower !== void 0 ? { borrower } : {},
84377
+ ...state !== void 0 ? { state } : {}
84378
+ };
84379
+ if (filter2.borrower === void 0 && filter2.state === void 0) {
84380
+ return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
84381
+ }
84382
+ return renderEnvelope(await b.boundary.listPositions(filter2));
84383
+ })
84384
+ );
84385
+ registerBoundaryTool(
84386
+ server,
84387
+ "position_events",
84388
+ {
84389
+ title: "Get a position's event history",
84390
+ description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
84391
+ inputSchema: {
84392
+ id: positionIdSchema2
84393
+ }
84394
+ },
84395
+ async ({ id }) => guarded(async () => {
84396
+ const problem = checkPositionIdHex(id);
84397
+ if (problem) return validationFailed(problem);
84398
+ const b = getB();
84399
+ if (!b.ok) return renderError(b.error);
84400
+ return renderEnvelope(await b.boundary.getPositionEvents(id));
84401
+ })
84402
+ );
84403
+ registerBoundaryTool(
84404
+ server,
84405
+ "position_pending_withdrawals",
84406
+ {
84407
+ title: "List a position's pending BTC withdrawal reservations",
84408
+ 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).",
84409
+ inputSchema: {
84410
+ id: positionIdSchema2
84411
+ }
84412
+ },
84413
+ async ({ id }) => guarded(async () => {
84414
+ const problem = checkPositionIdHex(id);
84415
+ if (problem) return validationFailed(problem);
84416
+ const b = getB();
84417
+ if (!b.ok) return renderError(b.error);
84418
+ return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
84419
+ })
84420
+ );
84421
+ }
84422
+
84423
+ // src/tools/btc.ts
84424
+ var import_zod3 = require("zod");
84425
+ function registerBtcTools(server, getB) {
84426
+ registerBoundaryTool(
84427
+ server,
84428
+ "btc_balance",
84429
+ {
84430
+ title: "Get BTC balance for an address",
84431
+ description: "Query the confirmed BTC balance for an address (source-tagged).",
84432
+ inputSchema: {
84433
+ address: import_zod3.z.string().min(1).describe("BTC address to query")
84434
+ }
84435
+ },
84436
+ async ({ address }) => guarded(async () => {
84437
+ const b = getB();
84438
+ if (!b.ok) return renderError(b.error);
84439
+ return renderEnvelope(await b.boundary.getBitcoinBalance(address));
84440
+ })
84441
+ );
84442
+ registerBoundaryTool(
84443
+ server,
84444
+ "btc_price",
84445
+ {
84446
+ title: "Get the current BTC price",
84447
+ description: "Return the current BTC price (USD, 8 decimals) from the price oracle.",
84448
+ inputSchema: {}
84449
+ },
84450
+ async () => guarded(async () => {
84451
+ const b = getB();
84452
+ if (!b.ok) return renderError(b.error);
84453
+ return renderEnvelope(await b.boundary.getBitcoinPrice());
84454
+ })
84455
+ );
84456
+ }
84457
+
84458
+ // src/tools/protocol.ts
84459
+ function registerProtocolTools(server, getB) {
84460
+ registerBoundaryTool(
84461
+ server,
84462
+ "protocol_status",
84463
+ {
84464
+ title: "Get protocol configuration and status",
84465
+ 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.",
84466
+ inputSchema: {}
84467
+ },
84468
+ async () => guarded(async () => {
84469
+ const b = getB();
84470
+ if (!b.ok) return renderError(b.error);
84471
+ return renderEnvelope(await b.boundary.getProtocolStatus());
84472
+ })
84473
+ );
84474
+ registerBoundaryTool(
84475
+ server,
84476
+ "protocol_terms",
84477
+ {
84478
+ title: "List available loan terms with fees",
84479
+ 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.",
84480
+ inputSchema: {}
84481
+ },
84482
+ async () => guarded(async () => {
84483
+ const b = getB();
84484
+ if (!b.ok) return renderError(b.error);
84485
+ return renderEnvelope(await b.boundary.getTerms());
84486
+ })
84487
+ );
84488
+ }
84489
+
84490
+ // src/tools/psm.ts
84491
+ var import_zod4 = require("zod");
84492
+ var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
84493
+ "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
84494
+ );
84495
+ var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
84496
+ readOnlyHint: false,
84497
+ destructiveHint: true,
84498
+ idempotentHint: false,
84499
+ openWorldHint: true
84074
84500
  };
84075
- var GUIDE_INDEX = `# Diamond Hands guide \u2014 topics
84501
+ function registerPsmTools(server, getB) {
84502
+ registerBoundaryTool(
84503
+ server,
84504
+ "psm_quote",
84505
+ {
84506
+ title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
84507
+ 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.",
84508
+ inputSchema: {
84509
+ 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)"),
84510
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
84511
+ },
84512
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84513
+ },
84514
+ async ({ direction, amount }) => guarded(async () => {
84515
+ const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
84516
+ const problem = checkUcdAmount(amount, label);
84517
+ if (problem) return validationFailed(problem);
84518
+ const b = getB();
84519
+ if (!b.ok) return renderError(b.error);
84520
+ return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
84521
+ })
84522
+ );
84523
+ registerBoundaryTool(
84524
+ server,
84525
+ "psm_swap",
84526
+ {
84527
+ title: "Exchange UCD \u2194 USDC through the PSM",
84528
+ 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).",
84529
+ inputSchema: {
84530
+ 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)"),
84531
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
84532
+ confirmed: confirmedSchema2
84533
+ },
84534
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84535
+ },
84536
+ async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84537
+ const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84538
+ const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
84539
+ const gate = requireConfirmation(
84540
+ confirmed,
84541
+ `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
84542
+ );
84543
+ if (gate) return gate;
84544
+ const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
84545
+ if (problem) return validationFailed(problem);
84546
+ const b = getB();
84547
+ if (!b.ok) return renderError(b.error);
84548
+ return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
84549
+ })
84550
+ );
84551
+ }
84076
84552
 
84077
- - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
84078
- - first-setup \u2014 zero to ready by conversation (authorization choice included)
84079
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
84080
- - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
84081
- - fees \u2014 the two fee models, plainly
84082
- - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
84083
- - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
84084
- - safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today
84085
- - delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today
84086
- - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
84087
- - switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated
84088
- - connector \u2014 the hosted claude.ai tier (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. Status: implemented, NOT yet publicly served
84089
- - troubleshooting \u2014 error codes in plain words, with the real remedies
84090
- - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
84091
- - reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
84553
+ // src/tools/mock-control.ts
84554
+ var import_zod5 = require("zod");
84555
+ var ACTIONS = [
84556
+ "submit-deposit",
84557
+ "confirm-deposit",
84558
+ "confirm-spend-consumed",
84559
+ "advance-time",
84560
+ "set-btc-price",
84561
+ "set-paused",
84562
+ "set-wallet",
84563
+ "liquidate",
84564
+ "deploy-safe",
84565
+ "revoke-agent",
84566
+ "inject-fault",
84567
+ "clear-fault",
84568
+ "psm-set-paused",
84569
+ "psm-set-redeem-enabled",
84570
+ "psm-set-reserves",
84571
+ "psm-set-fees",
84572
+ "psm-mint-usdc"
84573
+ ];
84574
+ function requireField(value, name, action) {
84575
+ if (value === void 0) {
84576
+ throw new Error(`action '${action}' requires '${name}'`);
84577
+ }
84578
+ return value;
84579
+ }
84580
+ function run(control, a, chainId) {
84581
+ switch (a.action) {
84582
+ case "submit-deposit": {
84583
+ const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
84584
+ return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
84585
+ }
84586
+ case "confirm-deposit": {
84587
+ const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
84588
+ return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
84589
+ }
84590
+ case "confirm-spend-consumed": {
84591
+ control.confirmSpendConsumed(
84592
+ requireField(a.txid, "txid", a.action),
84593
+ requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
84594
+ requireField(a.confirmations, "confirmations", a.action)
84595
+ );
84596
+ return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
84597
+ }
84598
+ case "advance-time": {
84599
+ control.advanceTime(requireField(a.seconds, "seconds", a.action));
84600
+ return { simulated: "virtual clock advanced", seconds: a.seconds };
84601
+ }
84602
+ case "set-btc-price": {
84603
+ control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
84604
+ return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
84605
+ }
84606
+ case "set-paused": {
84607
+ control.setPaused(requireField(a.paused, "paused", a.action));
84608
+ return { simulated: "protocol pause flag set", paused: a.paused };
84609
+ }
84610
+ case "set-wallet": {
84611
+ control.setWalletStance(requireField(a.stance, "stance", a.action));
84612
+ return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
84613
+ }
84614
+ case "liquidate": {
84615
+ control.liquidate(requireField(a.positionId, "positionId", a.action));
84616
+ return { simulated: "liquidation executed", positionId: a.positionId };
84617
+ }
84618
+ case "deploy-safe": {
84619
+ const safe = control.deploySafe({
84620
+ owners: requireField(a.owners, "owners", a.action),
84621
+ threshold: requireField(a.threshold, "threshold", a.action),
84622
+ chainId
84623
+ });
84624
+ return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
84625
+ }
84626
+ case "revoke-agent": {
84627
+ const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
84628
+ return {
84629
+ 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)",
84630
+ ...r
84631
+ };
84632
+ }
84633
+ case "inject-fault": {
84634
+ control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
84635
+ return { simulated: "fault armed", faultKey: a.faultKey };
84636
+ }
84637
+ case "clear-fault": {
84638
+ control.clearFault(requireField(a.faultKey, "faultKey", a.action));
84639
+ return { simulated: "fault cleared", faultKey: a.faultKey };
84640
+ }
84641
+ case "psm-set-paused": {
84642
+ control.psmSetPaused(requireField(a.paused, "paused", a.action));
84643
+ return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
84644
+ }
84645
+ case "psm-set-redeem-enabled": {
84646
+ control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
84647
+ return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
84648
+ }
84649
+ case "psm-set-reserves": {
84650
+ control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
84651
+ return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
84652
+ }
84653
+ case "psm-mint-usdc": {
84654
+ const r = control.psmMintUsdc(
84655
+ requireField(a.holder, "holder", a.action),
84656
+ requireField(a.usdcUnits, "usdcUnits", a.action)
84657
+ );
84658
+ return {
84659
+ simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
84660
+ holder: a.holder,
84661
+ minted: a.usdcUnits,
84662
+ newBalanceUnits: r.newBalanceUnits
84663
+ };
84664
+ }
84665
+ case "psm-set-fees": {
84666
+ control.psmSetFees({
84667
+ ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
84668
+ ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
84669
+ });
84670
+ return {
84671
+ simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
84672
+ ...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
84673
+ ...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
84674
+ };
84675
+ }
84676
+ }
84677
+ }
84678
+ function registerMockControlTool(server, control, chainId = 1337) {
84679
+ registerBoundaryTool(
84680
+ server,
84681
+ "mock_control",
84682
+ {
84683
+ title: "SIMULATOR control (mock world only)",
84684
+ 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.",
84685
+ inputSchema: {
84686
+ action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
84687
+ positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
84688
+ txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
84689
+ sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
84690
+ confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
84691
+ invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
84692
+ seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
84693
+ priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
84694
+ paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
84695
+ stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
84696
+ owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
84697
+ threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
84698
+ safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
84699
+ faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
84700
+ faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
84701
+ enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
84702
+ reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
84703
+ entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
84704
+ exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
84705
+ holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
84706
+ usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
84707
+ },
84708
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
84709
+ },
84710
+ async (args) => guarded(async () => {
84711
+ let result;
84712
+ try {
84713
+ result = run(control, args, chainId);
84714
+ } catch (e) {
84715
+ return validationFailed(e.message);
84716
+ }
84717
+ if (result === void 0) {
84718
+ return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
84719
+ }
84720
+ return { content: [{ type: "text", text: serialize(result) }] };
84721
+ })
84722
+ );
84723
+ }
84092
84724
 
84093
- Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
84094
- selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
84095
- signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
84096
- and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
84097
- only mainnet is real money.`;
84725
+ // src/tools/signer.ts
84726
+ var import_zod6 = require("zod");
84727
+ var import_ethers42 = require("ethers");
84728
+ var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
84729
+ var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
84730
+ var EXTERNAL_ONLY_MODES = ["external"];
84731
+ var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
84732
+ function looksSecretShaped(value) {
84733
+ return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
84734
+ }
84735
+ 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.";
84736
+ function registerSignerTool(server, getRuntime, opts) {
84737
+ const externalOnly = opts?.externalOnly === true;
84738
+ const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
84739
+ 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.";
84740
+ registerBoundaryTool(
84741
+ server,
84742
+ "signer_setup",
84743
+ {
84744
+ title: "Choose how operations are authorized",
84745
+ description,
84746
+ inputSchema: {
84747
+ action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
84748
+ mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
84749
+ ...externalOnly ? {} : {
84750
+ safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
84751
+ }
84752
+ },
84753
+ annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
84754
+ },
84755
+ async ({ action, mode, safeAddress }) => guarded(async () => {
84756
+ const runtime = getRuntime();
84757
+ if (!runtime) {
84758
+ return renderError(
84759
+ boundaryError(
84760
+ "SIGNER_UNAVAILABLE",
84761
+ "no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
84762
+ )
84763
+ );
84764
+ }
84765
+ const { manager, bridge } = runtime;
84766
+ if (mode !== void 0 && !offeredModes.includes(mode)) {
84767
+ return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
84768
+ }
84769
+ if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
84770
+ return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
84771
+ }
84772
+ if (action === "status") {
84773
+ await bridge.start();
84774
+ const s = manager.status();
84775
+ return ok({
84776
+ ...s,
84777
+ // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
84778
+ // identity is known. borrower = a persisted binding; candidate = a live
84779
+ // wallet connection in THIS process only.
84780
+ 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",
84781
+ approvalPageUrl: bridge.url(),
84782
+ 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.`
84783
+ });
84784
+ }
84785
+ if (action === "use") {
84786
+ if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
84787
+ const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
84788
+ if (!r.ok) return validationFailed(r.reason);
84789
+ if (mode === "safe-module") {
84790
+ const s = manager.status();
84791
+ return ok({
84792
+ mode,
84793
+ safe: s.safe,
84794
+ agent: s.keystoreAddress,
84795
+ 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'."
84796
+ });
84797
+ }
84798
+ if (mode === "safe") {
84799
+ const s = manager.status();
84800
+ return ok({
84801
+ mode,
84802
+ safe: s.safe,
84803
+ 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."
84804
+ });
84805
+ }
84806
+ if (mode === "external") {
84807
+ await bridge.start();
84808
+ return ok({
84809
+ mode,
84810
+ approvalPageUrl: bridge.url(),
84811
+ 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."
84812
+ });
84813
+ }
84814
+ return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
84815
+ }
84816
+ if (action === "connect") {
84817
+ if (!runtime.connect) {
84818
+ return validationFailed(
84819
+ "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."
84820
+ );
84821
+ }
84822
+ const r = await runtime.connect();
84823
+ if (!r.ok) return validationFailed(r.reason);
84824
+ const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
84825
+ return ok({
84826
+ connected: true,
84827
+ address: r.address,
84828
+ login,
84829
+ 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."
84830
+ });
84831
+ }
84832
+ if (action === "disconnect") {
84833
+ if (!runtime.disconnect) {
84834
+ return validationFailed(
84835
+ "this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
84836
+ );
84837
+ }
84838
+ const report = await runtime.disconnect();
84839
+ const f = report.flushed;
84840
+ 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)`;
84841
+ return ok({
84842
+ disconnected: true,
84843
+ mode: manager.mode(),
84844
+ flushed: {
84845
+ ...f,
84846
+ note: tokenLine
84847
+ },
84848
+ 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).",
84849
+ // Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
84850
+ // relationship; the OAuth session is a separate thing with its own revocation.
84851
+ // Neither claims to do the other's job.
84852
+ ...bridge.isHosted() ? {
84853
+ 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."
84854
+ } : {},
84855
+ 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').`
84856
+ });
84857
+ }
84858
+ if (action === "reset-borrower") {
84859
+ manager.resetBorrower();
84860
+ return ok({
84861
+ reset: true,
84862
+ 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."
84863
+ });
84864
+ }
84865
+ await bridge.start();
84866
+ const unlockUrl = bridge.unlockUrl();
84867
+ return ok({
84868
+ unlockPageUrl: unlockUrl,
84869
+ 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'."
84870
+ });
84871
+ })
84872
+ );
84873
+ }
84874
+ function ok(data) {
84875
+ return { content: [{ type: "text", text: serialize(data) }] };
84876
+ }
84098
84877
 
84099
84878
  // src/tools/guide.ts
84100
- function registerGuideTool(server) {
84879
+ var import_zod7 = require("zod");
84880
+ function registerGuideTool(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
84881
+ const content = buildGuideContent(deployment);
84882
+ const index = buildGuideIndex(deployment);
84101
84883
  registerBoundaryTool(
84102
84884
  server,
84103
84885
  "guide",
@@ -84111,26 +84893,31 @@ function registerGuideTool(server) {
84111
84893
  },
84112
84894
  async ({ topic }) => guarded(async () => {
84113
84895
  if (topic === void 0 || topic === "") {
84114
- return { content: [{ type: "text", text: GUIDE_INDEX }] };
84896
+ return { content: [{ type: "text", text: index }] };
84115
84897
  }
84116
84898
  if (!GUIDE_TOPICS.includes(topic)) {
84117
84899
  return validationFailed(`unknown guide topic '${topic}' \u2014 available: ${GUIDE_TOPICS.join(" | ")}`);
84118
84900
  }
84119
- return { content: [{ type: "text", text: GUIDE_CONTENT[topic] }] };
84901
+ return { content: [{ type: "text", text: content[topic] }] };
84120
84902
  })
84121
84903
  );
84122
84904
  }
84123
- function registerGuideResources(server) {
84905
+ function registerGuideResources(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
84906
+ const content = buildGuideContent(deployment);
84907
+ const index = buildGuideIndex(deployment);
84124
84908
  for (const topic of GUIDE_TOPICS) {
84125
84909
  server.resource(`guide-${topic}`, `guide://${topic}`, async () => ({
84126
- contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: GUIDE_CONTENT[topic] }]
84910
+ contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: content[topic] }]
84127
84911
  }));
84128
84912
  }
84129
84913
  server.resource("guide-index", "guide://index", async () => ({
84130
- contents: [{ uri: "guide://index", mimeType: "text/markdown", text: GUIDE_INDEX }]
84914
+ contents: [{ uri: "guide://index", mimeType: "text/markdown", text: index }]
84131
84915
  }));
84132
84916
  }
84133
- function registerGuidePrompts(server) {
84917
+ function onboardAuthorizationLine(deployment) {
84918
+ 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. ";
84919
+ }
84920
+ function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
84134
84921
  server.prompt(
84135
84922
  "onboard-me",
84136
84923
  "Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
@@ -84140,7 +84927,7 @@ function registerGuidePrompts(server) {
84140
84927
  role: "user",
84141
84928
  content: {
84142
84929
  type: "text",
84143
- text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. Ask before every operation; never assume confirmation."
84930
+ text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; " + onboardAuthorizationLine(deployment) + "Ask before every operation; never assume confirmation."
84144
84931
  }
84145
84932
  }
84146
84933
  ]
@@ -84377,7 +85164,6 @@ function registerBoundaryInfoResource(server, getB) {
84377
85164
  }
84378
85165
 
84379
85166
  // src/server.ts
84380
- var SERVER_VERSION = "0.5.9";
84381
85167
  var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
84382
85168
  var CONNECTOR_INSTRUCTIONS = SERVER_INSTRUCTIONS + " HOSTED CONNECTOR TIER: this server is the hosted claude.ai connector. Signer modes are external-wallet ONLY \u2014 keystore mode is ABSENT from this build (structurally, not disabled); the server never holds a key, and every fund-moving action needs a fresh signature from the user's own wallet. Each tenant's world is isolated by wallet identity; network_switch moves ONLY this tenant, within the networks this deployment serves (the refusal states the rollout truth). The login session lives in server memory only \u2014 a server restart or idle eviction means signing in again; that is the no-data-at-rest property, not a fault. Trust ledger and cadence: guide topic 'connector'.";
84383
85169
  function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
@@ -84397,9 +85183,9 @@ function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
84397
85183
  registerPositionResource(server, getB);
84398
85184
  registerProtocolResources(server, getB);
84399
85185
  registerBoundaryInfoResource(server, getB);
84400
- registerGuideTool(server);
84401
- registerGuideResources(server);
84402
- registerGuidePrompts(server);
85186
+ registerGuideTool(server, deps.deployment);
85187
+ registerGuideResources(server, deps.deployment);
85188
+ registerGuidePrompts(server, deps.deployment);
84403
85189
  if (deps.mockControl) {
84404
85190
  registerMockControlTool(server, deps.mockControl, deps.chainId);
84405
85191
  }
@@ -84417,8 +85203,43 @@ var DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1e3;
84417
85203
  var DEFAULT_WORLD_IDLE_MS = 60 * 60 * 1e3;
84418
85204
  var DEFAULT_TENANT_PER_MIN = 120;
84419
85205
  var DEFAULT_GLOBAL_PER_MIN = 600;
85206
+ var DEFAULT_MAX_TENANTS = 200;
85207
+ var DEFAULT_MAX_SESSIONS_PER_TENANT = 16;
85208
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
85209
+ var DEFAULT_TRUST_PROXY_HOPS = 1;
85210
+ function normalizePublicOrigin(raw) {
85211
+ const trimmed = raw.trim().replace(/\/+$/, "");
85212
+ let url2;
85213
+ try {
85214
+ url2 = new URL(trimmed);
85215
+ } catch {
85216
+ throw new Error(
85217
+ `connector: publicOrigin is not a valid URL (${trimmed.length} chars). The value is not echoed here \u2014 see below for why.`
85218
+ );
85219
+ }
85220
+ const problems = [];
85221
+ if (url2.protocol !== "https:" && url2.protocol !== "http:") problems.push(`scheme '${url2.protocol}' (want http or https)`);
85222
+ if (url2.username !== "" || url2.password !== "") problems.push("embedded credentials");
85223
+ if (url2.pathname !== "/" && url2.pathname !== "") problems.push("a path");
85224
+ if (url2.search !== "") problems.push("a query string");
85225
+ if (url2.hash !== "") problems.push("a fragment");
85226
+ if (problems.length > 0) {
85227
+ throw new Error(
85228
+ `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.`
85229
+ );
85230
+ }
85231
+ return url2.origin;
85232
+ }
85233
+ function requireSafeCount(value, fallback, name, min) {
85234
+ if (value === void 0) return fallback;
85235
+ if (!Number.isSafeInteger(value) || value < min) {
85236
+ throw new Error(`connector: ${name}=${String(value)} must be a safe integer >= ${min}`);
85237
+ }
85238
+ return value;
85239
+ }
84420
85240
  var RATE_WINDOW_MS = 60 * 1e3;
84421
- function composeConnector(opts, publicOrigin) {
85241
+ function composeConnector(opts, rawPublicOrigin) {
85242
+ const publicOrigin = normalizePublicOrigin(rawPublicOrigin);
84422
85243
  const allowedNetworks = opts.allowedNetworks ?? ["sepolia"];
84423
85244
  if (allowedNetworks.length === 0) throw new Error("connector service: allowedNetworks must name at least one network");
84424
85245
  const launchNetwork = allowedNetworks[0];
@@ -84427,6 +85248,10 @@ function composeConnector(opts, publicOrigin) {
84427
85248
  const worldIdleMs = opts.idle?.worldMs ?? DEFAULT_WORLD_IDLE_MS;
84428
85249
  const tenantPerMin = opts.rateLimits?.tenantPerMin ?? DEFAULT_TENANT_PER_MIN;
84429
85250
  const globalPerMin = opts.rateLimits?.globalPerMin ?? DEFAULT_GLOBAL_PER_MIN;
85251
+ const maxTenants = requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
85252
+ const trustProxyHops = requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
85253
+ const maxSessionsPerTenant = requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
85254
+ const maxBodyBytes = requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
84430
85255
  const worlds = /* @__PURE__ */ new Map();
84431
85256
  const readyWorlds = /* @__PURE__ */ new Map();
84432
85257
  const sessions = /* @__PURE__ */ new Map();
@@ -84456,7 +85281,7 @@ function composeConnector(opts, publicOrigin) {
84456
85281
  }
84457
85282
  async function buildWorld(tenantKey) {
84458
85283
  const stores = /* @__PURE__ */ new Map();
84459
- const mountId = (0, import_node_crypto9.randomUUID)().replaceAll("-", "");
85284
+ const mountId = (0, import_node_crypto10.randomUUID)().replaceAll("-", "");
84460
85285
  const overrides = {
84461
85286
  externalOnly: true,
84462
85287
  allowedNetworks,
@@ -84498,6 +85323,17 @@ function composeConnector(opts, publicOrigin) {
84498
85323
  process.stderr.write(`[dh-mcp-connector] ${why}: world for tenant ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} disposed
84499
85324
  `);
84500
85325
  }
85326
+ function tenantsWithSessions() {
85327
+ const held = /* @__PURE__ */ new Set();
85328
+ for (const session of sessions.values()) held.add(session.tenant);
85329
+ return held;
85330
+ }
85331
+ function isReclaimable(tenantKey, world, held) {
85332
+ if (held.has(tenantKey)) return false;
85333
+ const bridge = world.deps.signer?.bridge;
85334
+ if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85335
+ return true;
85336
+ }
84501
85337
  function sweepService() {
84502
85338
  const now = clock();
84503
85339
  for (const [sid, session] of [...sessions]) {
@@ -84506,18 +85342,43 @@ function composeConnector(opts, publicOrigin) {
84506
85342
  void session.transport.close().catch(() => void 0);
84507
85343
  }
84508
85344
  }
85345
+ const held = tenantsWithSessions();
84509
85346
  for (const [tenantKey, world] of [...readyWorlds]) {
84510
- const hasSession = [...sessions.values()].some((s) => s.tenant === tenantKey);
84511
- if (hasSession) continue;
84512
- const bridge = world.deps.signer?.bridge;
84513
- if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) continue;
85347
+ if (!isReclaimable(tenantKey, world, held)) continue;
84514
85348
  if (now - (lastActivity.get(tenantKey) ?? 0) <= worldIdleMs) continue;
84515
85349
  dropWorld(tenantKey, world, "idle eviction");
84516
85350
  }
84517
85351
  }
85352
+ function reclaimIdleWorld() {
85353
+ const held = tenantsWithSessions();
85354
+ let victimKey = null;
85355
+ let victim = null;
85356
+ let oldest = Number.POSITIVE_INFINITY;
85357
+ for (const [tenantKey, world] of readyWorlds) {
85358
+ if (!isReclaimable(tenantKey, world, held)) continue;
85359
+ const activeAt = lastActivity.get(tenantKey) ?? 0;
85360
+ if (activeAt < oldest) {
85361
+ oldest = activeAt;
85362
+ victimKey = tenantKey;
85363
+ victim = world;
85364
+ }
85365
+ }
85366
+ if (victimKey === null || victim === null) return false;
85367
+ dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
85368
+ return true;
85369
+ }
85370
+ class TenantCapacityError extends Error {
85371
+ }
84518
85372
  function worldFor(tenantKey) {
84519
85373
  let w = worlds.get(tenantKey);
84520
85374
  if (!w) {
85375
+ if (worlds.size >= maxTenants && !reclaimIdleWorld()) {
85376
+ return Promise.reject(
85377
+ new TenantCapacityError(
85378
+ `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`
85379
+ )
85380
+ );
85381
+ }
84521
85382
  w = buildWorld(tenantKey).catch((e) => {
84522
85383
  worlds.delete(tenantKey);
84523
85384
  throw e;
@@ -84526,16 +85387,75 @@ function composeConnector(opts, publicOrigin) {
84526
85387
  }
84527
85388
  return w;
84528
85389
  }
85390
+ function evictExcessSessions(tenantKey) {
85391
+ const mine = [...sessions].filter(([, s]) => s.tenant === tenantKey).sort((a, b) => a[1].lastSeen - b[1].lastSeen);
85392
+ for (let i = 0; i <= mine.length - maxSessionsPerTenant; i += 1) {
85393
+ const [sid, session] = mine[i];
85394
+ sessions.delete(sid);
85395
+ void session.transport.close().catch(() => void 0);
85396
+ process.stderr.write(
85397
+ `[dh-mcp-connector] session cap (${maxSessionsPerTenant}/tenant): oldest session for ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} closed to admit a new one
85398
+ `
85399
+ );
85400
+ }
85401
+ }
84529
85402
  function deny(res, status, message) {
84530
85403
  res.writeHead(status, { "content-type": "application/json" }).end(
84531
85404
  JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message }, id: null })
84532
85405
  );
84533
85406
  }
84534
- async function readJsonBody(req) {
84535
- let raw = "";
84536
- req.setEncoding("utf8");
84537
- for await (const chunk of req) raw += chunk;
84538
- return raw.length === 0 ? void 0 : JSON.parse(raw);
85407
+ function readBodyText(req) {
85408
+ return new Promise((resolve, reject) => {
85409
+ let raw = "";
85410
+ let bytes = 0;
85411
+ let settled = false;
85412
+ req.setEncoding("utf8");
85413
+ req.on("data", (chunk) => {
85414
+ if (settled) return;
85415
+ bytes += Buffer.byteLength(chunk, "utf8");
85416
+ if (bytes > maxBodyBytes) {
85417
+ settled = true;
85418
+ req.pause();
85419
+ resolve({ overflow: bytes });
85420
+ return;
85421
+ }
85422
+ raw += chunk;
85423
+ });
85424
+ req.on("end", () => {
85425
+ if (settled) return;
85426
+ settled = true;
85427
+ resolve({ text: raw });
85428
+ });
85429
+ req.on("error", (e) => {
85430
+ if (settled) return;
85431
+ settled = true;
85432
+ reject(e);
85433
+ });
85434
+ });
85435
+ }
85436
+ function refuseOversizedBody(req, res, why) {
85437
+ res.setHeader("Connection", "close");
85438
+ deny(res, 413, `request body too large (${why}) \u2014 this MCP endpoint accepts at most ${maxBodyBytes} bytes per JSON-RPC message`);
85439
+ res.once("finish", () => req.destroy());
85440
+ }
85441
+ async function readCappedBody(req, res) {
85442
+ const declared = Number(req.headers["content-length"]);
85443
+ if (Number.isFinite(declared) && declared > maxBodyBytes) {
85444
+ refuseOversizedBody(req, res, `declared ${declared} bytes`);
85445
+ return null;
85446
+ }
85447
+ const read = await readBodyText(req);
85448
+ if ("overflow" in read) {
85449
+ refuseOversizedBody(req, res, `exceeded the cap after ${read.overflow} bytes`);
85450
+ return null;
85451
+ }
85452
+ if (read.text.length === 0) return { body: void 0 };
85453
+ try {
85454
+ return { body: JSON.parse(read.text) };
85455
+ } catch {
85456
+ deny(res, 400, "request body is not valid JSON");
85457
+ return null;
85458
+ }
84539
85459
  }
84540
85460
  async function handle(req, res) {
84541
85461
  const url2 = new URL(req.url ?? "/", "http://connector.local");
@@ -84584,6 +85504,12 @@ function composeConnector(opts, publicOrigin) {
84584
85504
  return;
84585
85505
  }
84586
85506
  session.lastSeen = clock();
85507
+ if (req.method === "POST") {
85508
+ const read2 = await readCappedBody(req, res);
85509
+ if (!read2) return;
85510
+ await session.transport.handleRequest(req, res, read2.body);
85511
+ return;
85512
+ }
84587
85513
  await session.transport.handleRequest(req, res);
84588
85514
  return;
84589
85515
  }
@@ -84591,22 +85517,29 @@ function composeConnector(opts, publicOrigin) {
84591
85517
  deny(res, 400, "missing mcp-session-id \u2014 initialize first");
84592
85518
  return;
84593
85519
  }
84594
- let body;
84595
- try {
84596
- body = await readJsonBody(req);
84597
- } catch {
84598
- deny(res, 400, "request body is not valid JSON");
84599
- return;
84600
- }
85520
+ const read = await readCappedBody(req, res);
85521
+ if (!read) return;
85522
+ const body = read.body;
84601
85523
  if (!(0, import_types4.isInitializeRequest)(body)) {
84602
85524
  deny(res, 400, "missing mcp-session-id \u2014 the only session-less request is initialize");
84603
85525
  return;
84604
85526
  }
84605
- const world = await worldFor(tenantKey);
85527
+ let world;
85528
+ try {
85529
+ world = await worldFor(tenantKey);
85530
+ } catch (e) {
85531
+ if (e instanceof TenantCapacityError) {
85532
+ res.setHeader("Retry-After", "60");
85533
+ deny(res, 503, e.message);
85534
+ return;
85535
+ }
85536
+ throw e;
85537
+ }
84606
85538
  const mcp = createServer2(world.deps, CONNECTOR_INSTRUCTIONS);
84607
85539
  const transport = new import_streamableHttp.StreamableHTTPServerTransport({
84608
- sessionIdGenerator: () => (0, import_node_crypto9.randomUUID)(),
85540
+ sessionIdGenerator: () => (0, import_node_crypto10.randomUUID)(),
84609
85541
  onsessioninitialized: (sessionId) => {
85542
+ evictExcessSessions(tenantKey);
84610
85543
  sessions.set(sessionId, { transport, tenant: tenantKey, lastSeen: clock() });
84611
85544
  }
84612
85545
  });
@@ -84629,6 +85562,7 @@ function composeConnector(opts, publicOrigin) {
84629
85562
  });
84630
85563
  }
84631
85564
  const app = (0, import_express.default)();
85565
+ app.set("trust proxy", trustProxyHops);
84632
85566
  app.use((_req, res, next) => {
84633
85567
  if (!allowGlobal()) {
84634
85568
  deny(res, 429, `rate limit: this connector exceeded ${globalPerMin} requests/minute across all clients \u2014 a shared-capacity protection; wait for the minute window to pass and retry`);
@@ -84687,6 +85621,17 @@ function composeConnector(opts, publicOrigin) {
84687
85621
  const r = siwe.wcStatus(String(req.query["flowId"] ?? ""));
84688
85622
  res.status(r.status).json(r.body);
84689
85623
  });
85624
+ const authMd = renderAuthMd({
85625
+ publicOrigin,
85626
+ networks: allowedNetworks,
85627
+ walletConnectEnabled: wcLeg !== void 0
85628
+ });
85629
+ app.get("/auth.md", (_req, res) => {
85630
+ res.setHeader("X-Content-Type-Options", "nosniff");
85631
+ res.setHeader("Referrer-Policy", "no-referrer");
85632
+ res.setHeader("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'; base-uri 'none'");
85633
+ res.type("text/markdown; charset=utf-8").send(authMd);
85634
+ });
84690
85635
  app.get("/.well-known/oauth-protected-resource", (_req, res) => {
84691
85636
  res.json({
84692
85637
  resource: `${publicOrigin}/mcp`,
@@ -84718,6 +85663,13 @@ function composeConnector(opts, publicOrigin) {
84718
85663
  }
84719
85664
  };
84720
85665
  }
85666
+ if (opts.serveLandingPage) {
85667
+ app.get("/", (_req, res) => {
85668
+ const { nonce, headers } = htmlPageSecurityHeaders({ "img-src": [BACKGROUND_IMAGE_ORIGIN, "data:"] });
85669
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
85670
+ res.type("text/html; charset=utf-8").send(renderLandingPage({ publicOrigin, networks: allowedNetworks, version: SERVER_VERSION, nonce }));
85671
+ });
85672
+ }
84721
85673
  app.use((_req, res) => deny(res, 404, "not found \u2014 the MCP endpoint is /mcp"));
84722
85674
  const sweeper = setInterval(() => sweepService(), 6e4);
84723
85675
  sweeper.unref();
@@ -84747,6 +85699,11 @@ function composeConnector(opts, publicOrigin) {
84747
85699
  };
84748
85700
  }
84749
85701
  async function startConnectorService(opts) {
85702
+ if (opts.publicOrigin !== void 0) normalizePublicOrigin(opts.publicOrigin);
85703
+ requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
85704
+ requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
85705
+ requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
85706
+ requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
84750
85707
  const httpServer = (0, import_node_http.createServer)();
84751
85708
  const host = opts.host ?? "127.0.0.1";
84752
85709
  await new Promise((resolve, reject) => {
@@ -84755,8 +85712,9 @@ async function startConnectorService(opts) {
84755
85712
  });
84756
85713
  const addr = httpServer.address();
84757
85714
  if (addr === null || typeof addr === "string") throw new Error("connector service: no bound address");
84758
- const publicOrigin = opts.publicOrigin ?? `http://${host}:${addr.port}`;
84759
- const composed = composeConnector(opts, publicOrigin);
85715
+ const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
85716
+ const publicOrigin = opts.publicOrigin ?? `http://${authority}:${addr.port}`;
85717
+ const composed = composeConnector({ ...opts, serveLandingPage: true }, publicOrigin);
84760
85718
  httpServer.on("request", composed.app);
84761
85719
  return {
84762
85720
  url: `http://${host}:${addr.port}/mcp`,
@@ -84792,11 +85750,20 @@ async function main() {
84792
85750
  }
84793
85751
  }
84794
85752
  const publicOrigin = process.env["DH_CONNECTOR_PUBLIC_ORIGIN"];
85753
+ const rawHops = process.env["DH_CONNECTOR_TRUST_PROXY_HOPS"]?.trim();
85754
+ let trustProxyHops;
85755
+ if (rawHops !== void 0 && rawHops !== "") {
85756
+ trustProxyHops = Number(rawHops);
85757
+ if (!Number.isSafeInteger(trustProxyHops) || trustProxyHops < 0) {
85758
+ throw new Error(`DH_CONNECTOR_TRUST_PROXY_HOPS='${rawHops}' must be a non-negative integer`);
85759
+ }
85760
+ }
84795
85761
  const service = await startConnectorService({
84796
85762
  env: process.env,
84797
85763
  port,
84798
85764
  ...process.env["DH_CONNECTOR_HOST"] ? { host: process.env["DH_CONNECTOR_HOST"] } : {},
84799
85765
  ...publicOrigin ? { publicOrigin } : {},
85766
+ ...trustProxyHops !== void 0 ? { trustProxyHops } : {},
84800
85767
  allowedNetworks: networks2
84801
85768
  });
84802
85769
  process.stderr.write(