@bnbagent/studio-cli 0.0.12 → 0.0.13-alpha.1

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/bag.js CHANGED
@@ -52,7 +52,7 @@ import {
52
52
  x402SellerIsFree,
53
53
  x402SellerPricingState,
54
54
  x402SellerUsesB402
55
- } from "./chunk-RNWAADXU.js";
55
+ } from "./chunk-RSM3RMDD.js";
56
56
  import {
57
57
  TWAK_CLI_MIN_VERSION,
58
58
  TWAK_CLI_VERSION,
@@ -230,7 +230,7 @@ import {
230
230
  var CAMPAIGN_DOC_URL = "https://www.bnbchain.org/en/blog/bnb-agent-studio-is-live-on-bnb-chain-ai-agents-from-one-prompt";
231
231
  var CAMPAIGN_CHECK_TIMEOUT_MS = 6e3;
232
232
  async function fetchCampaignActive() {
233
- const { bnbPlatformApiUrl: bnbPlatformApiUrl2 } = await import("./deployCli-RWRR6XWO.js");
233
+ const { bnbPlatformApiUrl: bnbPlatformApiUrl2 } = await import("./deployCli-BY3ILBEP.js");
234
234
  const controller = new AbortController();
235
235
  const timer = setTimeout(() => controller.abort(), CAMPAIGN_CHECK_TIMEOUT_MS);
236
236
  try {
@@ -2823,6 +2823,19 @@ var ERC20_BALANCE_ABI = [
2823
2823
  outputs: [{ name: "", type: "uint256" }]
2824
2824
  }
2825
2825
  ];
2826
+ var ERC20_ALLOWANCE_ABI = [
2827
+ {
2828
+ type: "function",
2829
+ name: "allowance",
2830
+ stateMutability: "view",
2831
+ inputs: [
2832
+ { name: "owner", type: "address" },
2833
+ { name: "spender", type: "address" }
2834
+ ],
2835
+ outputs: [{ name: "", type: "uint256" }]
2836
+ }
2837
+ ];
2838
+ var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
2826
2839
  function client(networkName) {
2827
2840
  const net2 = getNetwork(networkName);
2828
2841
  return createPublicClient({ transport: http(net2.rpcUrl) });
@@ -2851,6 +2864,20 @@ async function readUBalanceRaw(address, networkName) {
2851
2864
  });
2852
2865
  return raw;
2853
2866
  }
2867
+ async function readUAllowanceRaw(owner, spender, networkName) {
2868
+ const net2 = getNetwork(networkName);
2869
+ const uToken = net2.tokens.U;
2870
+ if (uToken === void 0) {
2871
+ return null;
2872
+ }
2873
+ const raw = await client(networkName).readContract({
2874
+ address: getAddress(uToken.address),
2875
+ abi: ERC20_ALLOWANCE_ABI,
2876
+ functionName: "allowance",
2877
+ args: [getAddress(owner), getAddress(spender)]
2878
+ });
2879
+ return raw;
2880
+ }
2854
2881
  async function readTransactionSeen(txHash, networkName) {
2855
2882
  try {
2856
2883
  await client(networkName).getTransaction({
@@ -2937,7 +2964,7 @@ function canBuildWallet(root, data) {
2937
2964
  const cfg = data ?? loadAgentToml(root);
2938
2965
  const walletCfg = tableOf2(cfg, "wallet");
2939
2966
  const kind = walletCfg.kind;
2940
- if (kind === "twak" || kind === "altana") {
2967
+ if (kind === "twak" || kind === "altana" || kind === "turnkey") {
2941
2968
  return false;
2942
2969
  }
2943
2970
  if (!process.env.WALLET_PASSWORD) {
@@ -2955,7 +2982,7 @@ function canBuildWallet(root, data) {
2955
2982
  function walletAddressForChecks(root, data) {
2956
2983
  const cfg = data ?? loadAgentToml(root);
2957
2984
  const walletCfg = tableOf2(cfg, "wallet");
2958
- if (walletCfg.kind === "twak" || walletCfg.kind === "altana") {
2985
+ if (walletCfg.kind === "twak" || walletCfg.kind === "altana" || walletCfg.kind === "turnkey") {
2959
2986
  const addr = String(walletCfg.address ?? "").trim();
2960
2987
  return addr || null;
2961
2988
  }
@@ -3729,7 +3756,7 @@ function checkAltanaSdkResolvable(root, _target) {
3729
3756
  level: Level.CRITICAL,
3730
3757
  name: "altana_sdk_resolvable",
3731
3758
  message: `@altananetwork/sdk is not resolvable from the agent project${failure ? ` (${failure})` : ""} \u2014 the deployed runtime cannot build the Altana session wallet at cold start.`,
3732
- fixCmd: "pnpm add @altananetwork/sdk@0.5.1",
3759
+ fixCmd: "pnpm add @altananetwork/sdk@0.7.1",
3733
3760
  details: failure ? { error: failure } : {}
3734
3761
  }
3735
3762
  ];
@@ -4708,6 +4735,28 @@ var managedAzureFoundryChecks = [
4708
4735
  checkAltanaSessionNotInsideAgent
4709
4736
  ];
4710
4737
 
4738
+ // src/cli/_turnkeyGuidance.ts
4739
+ function turnkeySetupGuidance() {
4740
+ return `
4741
+ Turnkey setup (official CLI: https://docs.turnkey.com/sdks/cli):
4742
+ 1. In the dashboard's top-right user menu, copy the Organization ID into
4743
+ TURNKEY_ORG_ID.
4744
+ 2. Generate a P-256 API key locally, then register its public key under
4745
+ User Details -> Create API keys:
4746
+ turnkey generate api-key --organization "$TURNKEY_ORG_ID" --key-name bnbagent-studio
4747
+ Set TURNKEY_API_PUBLIC_KEY to the generated public key and
4748
+ TURNKEY_API_PRIVATE_KEY to its locally generated private key. Keep the
4749
+ private key out of argv, logs, and source control.
4750
+ 3. Create a wallet and an Ethereum account:
4751
+ turnkey wallets create --name bnbagent-studio --key-name bnbagent-studio
4752
+ turnkey wallets accounts create --wallet bnbagent-studio --address-format ADDRESS_FORMAT_ETHEREUM --key-name bnbagent-studio
4753
+ 4. Set TURNKEY_SIGN_WITH to the returned 0x Ethereum account address. It is
4754
+ not a Turnkey wallet id (UUID).
4755
+ 5. Store all four TURNKEY_* values in the owner-only .studio/.env.local,
4756
+ then run \`(cd app/agent && bag wallet new)\` to validate and anchor the
4757
+ address. No signing key is created or downloaded by bag.`;
4758
+ }
4759
+
4711
4760
  // src/cli/llm.ts
4712
4761
  import * as fs18 from "fs";
4713
4762
  import * as path17 from "path";
@@ -5909,18 +5958,15 @@ async function cmdUsage(daysArg) {
5909
5958
 
5910
5959
  // src/cli/recipes/deps.ts
5911
5960
  var CORE_PKG = "@bnbagent/studio-runtime";
5912
- var VERSION_RE = /^(\d+)\.(\d+)\.\d+(?:-[0-9A-Za-z.-]+)?$/;
5961
+ var VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
5913
5962
  function coreRequirement() {
5914
5963
  const version = cliVersion();
5915
- const m = VERSION_RE.exec(version);
5916
- if (m === null) {
5964
+ if (!VERSION_RE.test(version)) {
5917
5965
  throw new Error(
5918
5966
  `cannot derive a core constraint from CLI version '${version}'; expected X.Y.Z or X.Y.Z-<prerelease>`
5919
5967
  );
5920
5968
  }
5921
- const major = Number.parseInt(m[1], 10);
5922
- const minor = Number.parseInt(m[2], 10);
5923
- return `${CORE_PKG}@>=${version} <${major}.${minor + 1}.0`;
5969
+ return `${CORE_PKG}@${version}`;
5924
5970
  }
5925
5971
  function normalizeNodeDeps(deps) {
5926
5972
  return deps.map((d) => d.trim() === CORE_PKG ? coreRequirement() : d);
@@ -6587,6 +6633,7 @@ import {
6587
6633
  } from "@bnbagent/studio-runtime/config";
6588
6634
  import { tbnbFaucetHint as tbnbFaucetHint2 } from "@bnbagent/studio-runtime/networks";
6589
6635
  import { buildPolicy, buildWallet } from "@bnbagent/studio-runtime/wallet";
6636
+ import { getAddress as toChecksumAddress } from "viem";
6590
6637
 
6591
6638
  // src/cli/walletSession.ts
6592
6639
  import * as fs21 from "fs";
@@ -7318,6 +7365,9 @@ async function cmdNew(opts) {
7318
7365
  if (kind === "twak") {
7319
7366
  return cmdNewTwak(projectRoot, walletCfg);
7320
7367
  }
7368
+ if (kind === "turnkey") {
7369
+ return cmdNewTurnkey(projectRoot);
7370
+ }
7321
7371
  const privateKey = await resolvePrivateKeyArg(opts.privateKey);
7322
7372
  const password = requireDurablePassword(projectRoot);
7323
7373
  const keystoreDir = resolveKeystoreDir2(
@@ -7381,6 +7431,28 @@ Install it (Node >=22): npm install -g @trustwallet/cli@${TWAK_CLI_VERSION}`
7381
7431
  printNextAfterNew(projectRoot, address);
7382
7432
  return 0;
7383
7433
  }
7434
+ function cmdNewTurnkey(projectRoot) {
7435
+ const signWith = String(process.env.TURNKEY_SIGN_WITH ?? "").trim();
7436
+ if (signWith === "") {
7437
+ printErr(
7438
+ `error: TURNKEY_SIGN_WITH is not set (wallet.kind = 'turnkey').
7439
+ ${turnkeySetupGuidance()}`
7440
+ );
7441
+ return 1;
7442
+ }
7443
+ let address;
7444
+ try {
7445
+ address = toChecksumAddress(signWith);
7446
+ } catch {
7447
+ printErr(
7448
+ `error: TURNKEY_SIGN_WITH must be the wallet account's Ethereum address (0x + 40 hex chars), not a Turnkey wallet id \u2014 copy it from the dashboard wallet-account view. Got: '${signWith}'`
7449
+ );
7450
+ return 1;
7451
+ }
7452
+ printOut(address);
7453
+ persistAddress(projectRoot, address);
7454
+ return 0;
7455
+ }
7384
7456
  function ensureTwakCredentials(walletFile, homeDir) {
7385
7457
  const twakDir = path21.dirname(walletFile);
7386
7458
  const target = path21.join(twakDir, "credentials.json");
@@ -7558,6 +7630,33 @@ function cmdShow5(projectRootArg2) {
7558
7630
  );
7559
7631
  return 0;
7560
7632
  }
7633
+ if (kind === "turnkey") {
7634
+ const anchored = String(walletCfg.address ?? "").trim();
7635
+ const signWith = String(process.env.TURNKEY_SIGN_WITH ?? "").trim();
7636
+ const address2 = anchored || signWith;
7637
+ if (!address2) {
7638
+ throw new Error(
7639
+ "cannot resolve the Turnkey wallet address: no [wallet].address is anchored in studio.toml and TURNKEY_SIGN_WITH is not set \u2014 fill .studio/.env.local, then run `bag wallet new`."
7640
+ );
7641
+ }
7642
+ const requiredEnv = [
7643
+ "TURNKEY_API_PUBLIC_KEY",
7644
+ "TURNKEY_API_PRIVATE_KEY",
7645
+ "TURNKEY_ORG_ID",
7646
+ "TURNKEY_SIGN_WITH"
7647
+ ];
7648
+ const present = requiredEnv.filter((key) => process.env[key]).length;
7649
+ const baseUrl = process.env.TURNKEY_API_BASE_URL || "https://api.turnkey.com";
7650
+ printOut(`address: ${address2}`);
7651
+ printOut("source: turnkey");
7652
+ printOut(
7653
+ `key_location: remote:turnkey (${baseUrl}; key held in AWS Nitro enclave, never leaves)`
7654
+ );
7655
+ printOut(
7656
+ `credentials: ${present}/${requiredEnv.length} TURNKEY_* env vars set`
7657
+ );
7658
+ return 0;
7659
+ }
7561
7660
  const password = requirePassword2();
7562
7661
  const keystoreDir = resolveKeystoreDir2(projectRoot, null, walletCfg);
7563
7662
  const provider = new EVMWalletProvider({
@@ -7650,7 +7749,14 @@ async function cmdSign(msg, projectRootArg2) {
7650
7749
  );
7651
7750
  }
7652
7751
  let provider;
7653
- if (kind === "twak") {
7752
+ if (kind === "turnkey") {
7753
+ printErr(
7754
+ "note: Turnkey signatures are billed (free tier 25/month at 1 req/s; pay-as-you-go $0.10 each)."
7755
+ );
7756
+ provider = buildWallet(walletCfg, projectRoot, {
7757
+ network: projectNetwork(projectRoot)
7758
+ });
7759
+ } else if (kind === "twak") {
7654
7760
  provider = twakProvider(projectRoot, walletCfg);
7655
7761
  } else {
7656
7762
  const password = requirePassword2();
@@ -7675,10 +7781,10 @@ async function cmdBalance(opts) {
7675
7781
  const walletCfg = data.wallet !== null && typeof data.wallet === "object" ? data.wallet : {};
7676
7782
  let address;
7677
7783
  const kind = walletKind(walletCfg);
7678
- if (kind === "twak" || kind === "altana") {
7784
+ if (kind === "twak" || kind === "altana" || kind === "turnkey") {
7679
7785
  address = String(walletCfg.address ?? "").trim();
7680
7786
  if (!address) {
7681
- const nextStep = kind === "twak" ? "(adopts the twak wallet's address) first." : "to create the Altana admin keystore first.";
7787
+ const nextStep = kind === "twak" ? "(adopts the twak wallet's address) first." : kind === "turnkey" ? "(set TURNKEY_SIGN_WITH in .studio/.env.local first \u2014 `bag wallet new` adopts it)." : "to create the Altana admin keystore first.";
7682
7788
  throw new Error(
7683
7789
  `no [wallet].address anchored in studio.toml \u2014 run bag wallet new ${nextStep}`
7684
7790
  );
@@ -8044,7 +8150,7 @@ function registerInit(program) {
8044
8150
  ).addOption(
8045
8151
  new Option2(
8046
8152
  "--rails <rails>",
8047
- "Commerce rail(s) to scaffold: 8183, b402, or both (default; Altana defaults to 8183)."
8153
+ "Commerce rail(s) to scaffold: 8183, b402, or both (default)."
8048
8154
  ).choices(["8183", "b402", "both"])
8049
8155
  ).option(
8050
8156
  "--erc8183-price <base-units>",
@@ -8068,8 +8174,8 @@ function registerInit(program) {
8068
8174
  ).addOption(
8069
8175
  new Option2(
8070
8176
  "--wallet-kind <kind>",
8071
- "Wallet backend for the Agent (default: evm-local = encrypted local keystore at the workspace root .studio/wallets/; CodeZip deploy). altana \u2014 encrypted local admin keystore plus a bounded runtime session; deploys ship ONLY the session (ALTANA_SESSION secret). twak \u2014 FULLY SUPPORTED, opt in: Trust Wallet Agent Kit CLI, self-custody encrypted mnemonic in a PROJECT-DEDICATED home (.studio/twak); deploys as a container image."
8072
- ).choices(["twak", "evm-local", "altana"])
8177
+ "Wallet backend for the Agent (default: evm-local = encrypted local keystore at the workspace root .studio/wallets/; CodeZip deploy). altana \u2014 encrypted local admin keystore plus a bounded runtime session; deploys ship ONLY the session (ALTANA_SESSION secret). twak \u2014 FULLY SUPPORTED, opt in: Trust Wallet Agent Kit CLI, self-custody encrypted mnemonic in a PROJECT-DEDICATED home (.studio/twak); deploys as a container image. turnkey \u2014 remote signer: the key lives in Turnkey's AWS Nitro enclave and the Agent signs via TURNKEY_* API credentials; CodeZip deploy; every successful signature is billed."
8178
+ ).choices(["twak", "evm-local", "altana", "turnkey"])
8073
8179
  ).option(
8074
8180
  "--twak-home <path>",
8075
8181
  "twak only: point this project at an EXISTING twak wallet home (the HOME-STYLE PARENT dir that contains .twak/wallet.json \u2014 NOT the .twak dir itself; a .twak path holding a wallet is auto-corrected to its parent) instead of the dedicated .studio/twak. Written to [wallet].twak_home."
@@ -8237,7 +8343,7 @@ async function cmdInitFlow(nameArg, opts) {
8237
8343
  if (llmProvider === null) {
8238
8344
  return 2;
8239
8345
  }
8240
- const inferredRails = opts.rails ?? (facesExplicit ? hasX402Face(faces) ? "both" : "8183" : walletKind2 === "altana" ? "8183" : void 0);
8346
+ const inferredRails = opts.rails ?? (facesExplicit ? hasX402Face(faces) ? "both" : "8183" : void 0);
8241
8347
  let rails = await resolveRails(inferredRails, isTty);
8242
8348
  if (!facesExplicit) {
8243
8349
  faces = normalizeProtocolFaces(
@@ -8382,9 +8488,9 @@ async function cmdInitFlow(nameArg, opts) {
8382
8488
  }
8383
8489
  const budgetFlag = opts.enableAutoTopup ? "enable" : opts.autoTopup === false ? "disable" : null;
8384
8490
  const budgetChoice = llmProvider === "pieverse-llm" || budgetFlag !== null ? await resolveBudgetChoice(budgetFlag) : null;
8385
- if ((rails === "b402" || rails === "both") && x402SellerPricingState({ price_usd: b402Price }).kind === "paid" && !["evm-local", "twak"].includes(walletKind2)) {
8491
+ if ((rails === "b402" || rails === "both") && x402SellerPricingState({ price_usd: b402Price }).kind === "paid" && !["evm-local", "twak", "turnkey", "altana"].includes(walletKind2)) {
8386
8492
  printErr(
8387
- `error: the b402 seller rail supports wallet.kind evm-local or twak only; '${walletKind2}' cannot act as the b402 payout wallet. Re-run with --rails 8183 or a supported --wallet-kind.`
8493
+ `error: the b402 seller rail supports wallet.kind evm-local, twak, turnkey or altana only; '${walletKind2}' cannot act as the b402 payout wallet. Re-run with --rails 8183 or a supported --wallet-kind.`
8388
8494
  );
8389
8495
  fs23.rmSync(target, { recursive: true, force: true });
8390
8496
  return 2;
@@ -8481,6 +8587,8 @@ async function cmdInitFlow(nameArg, opts) {
8481
8587
  }
8482
8588
  } else if (walletKind2 === "altana") {
8483
8589
  printAltanaNotice();
8590
+ } else if (walletKind2 === "turnkey") {
8591
+ printTurnkeyNotice();
8484
8592
  } else {
8485
8593
  printEvmLocalNotice(
8486
8594
  derivePackaging(walletKind2, destination, platformArtifact2, runtime)
@@ -8717,6 +8825,9 @@ function computeAgentNodeDeps(runtime, provider, protocols = "A2A", walletKind2
8717
8825
  if (walletKind2 === "altana") {
8718
8826
  raw.push(...readRecipeNodeDeps("wallet", "altana"));
8719
8827
  }
8828
+ if (walletKind2 === "turnkey") {
8829
+ raw.push(...readRecipeNodeDeps("wallet", "turnkey"));
8830
+ }
8720
8831
  const out = {};
8721
8832
  const core = splitDep(coreRequirement());
8722
8833
  for (const dep of raw) {
@@ -8890,6 +9001,18 @@ kind = "altana"
8890
9001
  keystore_dir = "../../.studio/wallets"
8891
9002
  session_file = "../../.studio/wallets/altana-session.json"
8892
9003
  # address = "0x..." # filled by \`bag wallet new\`; session must match it`;
9004
+ }
9005
+ if (walletKind2 === "turnkey") {
9006
+ return `[wallet]
9007
+ # Turnkey remote signer. The key is generated and held in Turnkey's AWS Nitro
9008
+ # enclave \u2014 no key material ever exists in this project or its deploys. The
9009
+ # Agent signs via the Turnkey API using the TURNKEY_* credentials in
9010
+ # .studio/.env.local. Billing: every successful signature is billed (free
9011
+ # tier: 25 signatures/month at 1 request/second; pay-as-you-go $0.10 each).
9012
+ # PRODUCTION: use a NON-ROOT API user restricted by an explicit ALLOW
9013
+ # policy \u2014 a root user's API key bypasses ALL Turnkey server-side policies.
9014
+ kind = "turnkey"
9015
+ # address = "0x..." # filled by \`bag wallet new\` (adopts TURNKEY_SIGN_WITH)`;
8893
9016
  }
8894
9017
  return `[wallet]
8895
9018
  # Local keystore signer. The Agent is the SOLE key-holder/signer.
@@ -9088,6 +9211,23 @@ function renderAgentEnvLocal(provider, storageProvider, walletKind2, rails, b402
9088
9211
  "# TWAK_ACCESS_ID=",
9089
9212
  "# TWAK_HMAC_SECRET="
9090
9213
  );
9214
+ } else if (walletKind2 === "turnkey") {
9215
+ lines.push(
9216
+ "",
9217
+ "# Turnkey API credentials (dashboard \u2192 API keys). The P-256 API key",
9218
+ "# pair authenticates this Agent to the enclave; the wallet's signing",
9219
+ "# key never leaves Turnkey. Use a NON-ROOT API user + explicit ALLOW",
9220
+ "# policy in production (root keys bypass all Turnkey policies).",
9221
+ "TURNKEY_API_PUBLIC_KEY=",
9222
+ "TURNKEY_API_PRIVATE_KEY=",
9223
+ "# Organization id (dashboard \u2192 settings):",
9224
+ "TURNKEY_ORG_ID=",
9225
+ "# Account to sign with \u2014 MUST be the 0x Ethereum ADDRESS itself, not",
9226
+ "# a Turnkey wallet id. `bag wallet new` anchors it into studio.toml.",
9227
+ "TURNKEY_SIGN_WITH=",
9228
+ "# Optional API host override (default https://api.turnkey.com):",
9229
+ "# TURNKEY_API_BASE_URL="
9230
+ );
9091
9231
  } else if (walletKind2 === "evm-local" || walletKind2 === "altana") {
9092
9232
  lines.push(
9093
9233
  "",
@@ -9202,7 +9342,7 @@ entrypoint code in \`src/signing.ts\` \u2014 never an LLM-callable tool.
9202
9342
  ${mode === "both" ? filesBoth : mode === "mcp" ? filesMcp : filesA2a}
9203
9343
  ${shared}
9204
9344
  - \`.env.local\` \u2014 Agent secrets; on deploy they are sent to the **operator's**
9205
- Secrets Manager (the scoped, consented commitment-#2 exception). ${walletKind2 === "altana" ? "Only the\n bounded session ships (as `ALTANA_SESSION`); tighten it with\n `bag wallet session grant --force` \u2014 do not create a new wallet." : "Use a\n THROWAWAY testnet wallet \u2014 `(cd app/agent && bag wallet new)`."}
9345
+ Secrets Manager (the scoped, consented commitment-#2 exception). ${walletKind2 === "altana" ? "Only the\n bounded session ships (as `ALTANA_SESSION`); tighten it with\n `bag wallet session grant --force` \u2014 do not create a new wallet." : walletKind2 === "turnkey" ? "No key\n material exists locally \u2014 only the TURNKEY_* API credentials ship; the\n signing key stays in Turnkey's enclave. Fund the TURNKEY_SIGN_WITH\n address with a little tBNB; every successful signature is billed." : "Use a\n THROWAWAY testnet wallet \u2014 `(cd app/agent && bag wallet new)`."}
9206
9346
 
9207
9347
  ## Run locally
9208
9348
 
@@ -9311,12 +9451,12 @@ function ensureCursorGitignore(gitignore) {
9311
9451
  ${addition}`);
9312
9452
  }
9313
9453
  async function resolveWalletKind(flagValue, isTty) {
9314
- if (flagValue === "evm-local" || flagValue === "twak" || flagValue === "altana") {
9454
+ if (flagValue === "evm-local" || flagValue === "twak" || flagValue === "altana" || flagValue === "turnkey") {
9315
9455
  return flagValue;
9316
9456
  }
9317
9457
  if (!isTty) {
9318
9458
  printErr(
9319
- "info: wallet backend defaulting to 'evm-local' (non-interactive). To choose explicitly, re-run with --wallet-kind evm-local or --wallet-kind twak or --wallet-kind altana."
9459
+ "info: wallet backend defaulting to 'evm-local' (non-interactive). To choose explicitly, re-run with --wallet-kind evm-local or --wallet-kind twak, --wallet-kind altana or --wallet-kind turnkey."
9320
9460
  );
9321
9461
  return "evm-local";
9322
9462
  }
@@ -9328,11 +9468,15 @@ async function resolveWalletKind(flagValue, isTty) {
9328
9468
  " 2. twak \u2014 Trust Wallet CLI wallet; forces container packaging for deploys"
9329
9469
  );
9330
9470
  printOut(
9331
- " 3. altana \u2014 bounded session signer; incompatible with pieverse-llm and paid b402 selling"
9471
+ " 3. altana \u2014 bounded session signer; incompatible with pieverse-llm"
9472
+ );
9473
+ printOut(
9474
+ " 4. turnkey \u2014 remote signer; key held in Turnkey's AWS Nitro enclave; billable signatures"
9332
9475
  );
9333
- const answer = (await promptUser("Wallet backend [1-3, Enter = evm-local]: ")).trim().toLowerCase();
9476
+ const answer = (await promptUser("Wallet backend [1-4, Enter = evm-local]: ")).trim().toLowerCase();
9334
9477
  if (answer === "2" || answer === "twak") return "twak";
9335
9478
  if (answer === "3" || answer === "altana") return "altana";
9479
+ if (answer === "4" || answer === "turnkey") return "turnkey";
9336
9480
  if (answer !== "" && answer !== "1" && answer !== "evm-local") {
9337
9481
  printErr(`hint: unknown wallet backend '${answer}' \u2014 using evm-local.`);
9338
9482
  }
@@ -9614,6 +9758,12 @@ async function runOnboarding(o) {
9614
9758
  if (o.walletKind === "twak") {
9615
9759
  return runOnboardingTwak(o);
9616
9760
  }
9761
+ if (o.walletKind === "turnkey") {
9762
+ printOut(
9763
+ "turnkey onboarding: no local key is created. Fill the TURNKEY_* credentials in .studio/.env.local (Turnkey dashboard \u2192 API keys / settings / wallet account), then run `(cd app/agent && bag wallet new)` to adopt + anchor the signing address."
9764
+ );
9765
+ return false;
9766
+ }
9617
9767
  const password = await promptPassword();
9618
9768
  if (password === null) {
9619
9769
  return false;
@@ -9983,7 +10133,33 @@ NOTE \u2014 wallet.kind = "altana" (bounded runtime session):
9983
10133
  \`bag wallet session grant --force\` and redeploy.`
9984
10134
  );
9985
10135
  }
10136
+ function printTurnkeyNotice() {
10137
+ printOut(
10138
+ `
10139
+ NOTE \u2014 wallet.kind = "turnkey" (remote signer, keys in Turnkey's AWS Nitro enclave):
10140
+ \xB7 WALLET: no key material exists locally \u2014 the Agent signs via the TURNKEY_*
10141
+ API credentials in .studio/.env.local.
10142
+ ${turnkeySetupGuidance()}
10143
+ \xB7 BILLING: every successful signature is billed (free tier: 25/month at
10144
+ 1 request/second; pay-as-you-go $0.10 each) \u2014 budget accordingly.
10145
+ \xB7 PRODUCTION: use a NON-ROOT API user restricted by an explicit ALLOW policy;
10146
+ a root user's API key bypasses ALL Turnkey server-side policies.`
10147
+ );
10148
+ }
9986
10149
  function printPlatformWalletSuggestion(walletKind2) {
10150
+ if (walletKind2 === "turnkey") {
10151
+ printOut(
10152
+ `
10153
+ NOTE \u2014 destination = "platform" (48h TESTNET TRIAL on the BNB Chain managed platform):
10154
+ \xB7 This is a sandbox, not a production seller \u2014 the runtime is auto-reclaimed at 48h.
10155
+ \xB7 To sign, ONLY the TURNKEY_* API credentials are transmitted to the operator's
10156
+ Secrets Manager on deploy \u2014 the signing key never leaves Turnkey's enclave.
10157
+ \xB7 Want a smaller blast radius? Use a NON-ROOT API user whose ALLOW policy
10158
+ covers only this Agent's operations, and revoke it from the Turnkey
10159
+ dashboard when the trial ends.`
10160
+ );
10161
+ return;
10162
+ }
9987
10163
  if (walletKind2 === "altana") {
9988
10164
  printOut(
9989
10165
  `
@@ -10214,6 +10390,17 @@ function printNextSteps(name, provider, o = {}) {
10214
10390
  printOut(
10215
10391
  " (cd app/agent && bag wallet session status) # local, secret-free summary"
10216
10392
  );
10393
+ } else if (walletKind2 === "turnkey") {
10394
+ printOut(
10395
+ " # 1. edit .studio/.env.local and set the TURNKEY_* credentials (Turnkey dashboard \u2192 API keys / settings / wallet account)"
10396
+ );
10397
+ printOut(
10398
+ " # use a NON-ROOT API user + explicit ALLOW policy; TURNKEY_SIGN_WITH is the 0x ADDRESS, not a wallet id"
10399
+ );
10400
+ printOut(
10401
+ " # 2. adopt + anchor the Turnkey address (no local key is created):"
10402
+ );
10403
+ printOut(" (cd app/agent && bag wallet new)");
10217
10404
  } else {
10218
10405
  printOut(
10219
10406
  " # 1. edit .studio/.env.local and set WALLET_PASSWORD (encrypts the keystore + signs all on-chain ops)"
@@ -10437,6 +10624,10 @@ function printConfigSummary(agentRoot2) {
10437
10624
  ".studio/wallets/altana-session.json"
10438
10625
  )}`
10439
10626
  );
10627
+ } else if (walletKind2 === "turnkey") {
10628
+ printOut(
10629
+ " wallet : Turnkey remote signer (key in AWS Nitro enclave; TURNKEY_* credentials in .studio/.env.local) \u2014 the sole signer; receives your $U"
10630
+ );
10440
10631
  } else {
10441
10632
  printOut(
10442
10633
  ` wallet : local keystore (${shown(
@@ -10557,6 +10748,16 @@ function runtimeEnvKeysCore(cfg, resolvable) {
10557
10748
  }
10558
10749
  } else if (walletKind2 === "altana") {
10559
10750
  keys = [];
10751
+ } else if (walletKind2 === "turnkey") {
10752
+ keys = [
10753
+ "TURNKEY_API_PUBLIC_KEY",
10754
+ "TURNKEY_API_PRIVATE_KEY",
10755
+ "TURNKEY_ORG_ID",
10756
+ "TURNKEY_SIGN_WITH"
10757
+ ];
10758
+ if (resolvable("TURNKEY_API_BASE_URL")) {
10759
+ keys.push("TURNKEY_API_BASE_URL");
10760
+ }
10560
10761
  } else {
10561
10762
  keys = ["WALLET_PASSWORD"];
10562
10763
  }
@@ -11081,10 +11282,17 @@ async function cmdDev(opts) {
11081
11282
  );
11082
11283
  return 2;
11083
11284
  }
11084
- const pwEnv = walletKind2 === "twak" ? "TWAK_WALLET_PASSWORD" : "WALLET_PASSWORD";
11085
- if (walletKind2 !== "altana" && !process.env[pwEnv]) {
11285
+ const requiredWalletEnv = walletKind2 === "twak" ? ["TWAK_WALLET_PASSWORD"] : walletKind2 === "altana" ? [] : walletKind2 === "turnkey" ? [
11286
+ "TURNKEY_API_PUBLIC_KEY",
11287
+ "TURNKEY_API_PRIVATE_KEY",
11288
+ "TURNKEY_ORG_ID",
11289
+ "TURNKEY_SIGN_WITH"
11290
+ ] : ["WALLET_PASSWORD"];
11291
+ const missingWalletEnv = requiredWalletEnv.filter((key) => !process.env[key]);
11292
+ if (missingWalletEnv.length > 0) {
11293
+ const plural = missingWalletEnv.length > 1 ? "vars are" : "var is";
11086
11294
  printErr(
11087
- `error: ${pwEnv} env var is required to run \`bag dev\` (the Agent is the sole signer). Set it in .studio/.env.local or your shell.`
11295
+ `error: ${missingWalletEnv.join(", ")} env ${plural} required to run \`bag dev\` with wallet.kind='${walletKind2}' (the Agent is the sole signer). Set ${missingWalletEnv.length > 1 ? "them" : "it"} in .studio/.env.local or your shell.`
11088
11296
  );
11089
11297
  return 2;
11090
11298
  }
@@ -11465,6 +11673,9 @@ async function checkLocalKeystoreExists(root, _target) {
11465
11673
  if (walletCfg.kind === "altana") {
11466
11674
  return [];
11467
11675
  }
11676
+ if (walletCfg.kind === "turnkey") {
11677
+ return [];
11678
+ }
11468
11679
  const signer = walletCfg.signer ?? "local";
11469
11680
  if (signer !== "local") {
11470
11681
  return [];
@@ -11490,6 +11701,9 @@ async function checkWalletPasswordEnvSet(root, _target) {
11490
11701
  if (kind === "altana") {
11491
11702
  return [];
11492
11703
  }
11704
+ if (kind === "turnkey") {
11705
+ return [];
11706
+ }
11493
11707
  if (process.env.WALLET_PASSWORD) {
11494
11708
  return [];
11495
11709
  }
@@ -11832,11 +12046,11 @@ function x402SellerRailChecks(agentRoot2, cfg, target) {
11832
12046
  }
11833
12047
  }
11834
12048
  const walletKind2 = String(tableOf2(cfg, "wallet").kind ?? "evm-local");
11835
- if (paid && !["evm-local", "twak"].includes(walletKind2)) {
12049
+ if (paid && !["evm-local", "twak", "turnkey", "altana"].includes(walletKind2)) {
11836
12050
  out.push({
11837
12051
  level: Level.CRITICAL,
11838
12052
  name: "x402_wallet_kind_unsupported",
11839
- message: `[wallet].kind = "${walletKind2}" cannot run the b402 seller rail; supported kinds are evm-local and twak.`,
12053
+ message: `[wallet].kind = "${walletKind2}" cannot run the b402 seller rail; supported kinds are evm-local, twak, turnkey, and altana.`,
11840
12054
  details: { walletKind: walletKind2 }
11841
12055
  });
11842
12056
  }
@@ -12113,6 +12327,46 @@ function awsJson(stdout) {
12113
12327
  return null;
12114
12328
  }
12115
12329
  }
12330
+ async function checkAwsAccountMatchesTarget(root, target) {
12331
+ if (target !== "agentcore") {
12332
+ return [];
12333
+ }
12334
+ const [targetAccount, region] = readAwsTarget(root);
12335
+ if (!targetAccount || !region || !await whichBin("aws")) {
12336
+ return [];
12337
+ }
12338
+ const identity = await runCapture("aws", [
12339
+ "sts",
12340
+ "get-caller-identity",
12341
+ "--region",
12342
+ region,
12343
+ "--output",
12344
+ "json"
12345
+ ]);
12346
+ if (identity.code !== 0) {
12347
+ return [];
12348
+ }
12349
+ const rawAccount = awsJson(identity.stdout)?.Account;
12350
+ const credentialAccount = typeof rawAccount === "string" && /^\d{12}$/.test(rawAccount.trim()) ? rawAccount.trim() : null;
12351
+ if (credentialAccount === null || credentialAccount === targetAccount) {
12352
+ return [];
12353
+ }
12354
+ const targetPath = path24.join(root, "agentcore", "aws-targets.json");
12355
+ return [
12356
+ {
12357
+ level: Level.CRITICAL,
12358
+ name: "aws_account_mismatch",
12359
+ message: `active AWS credentials resolve to account ${credentialAccount}, but agentcore/aws-targets.json pins account ${targetAccount}. The delegated deploy rejects this mismatch before provisioning. Switch credentials, or update the local target file after confirming which account should own the deployment.`,
12360
+ details: {
12361
+ credential_account: credentialAccount,
12362
+ target_account: targetAccount,
12363
+ region,
12364
+ path: targetPath
12365
+ },
12366
+ fixCmd: `# edit agentcore/aws-targets.json and set the default account to ${credentialAccount}, or switch the active AWS credentials`
12367
+ }
12368
+ ];
12369
+ }
12116
12370
  async function checkAgentcoreQuotaHeadroom(root, target) {
12117
12371
  if (target !== "agentcore") {
12118
12372
  return [];
@@ -12218,6 +12472,7 @@ var allChecks = [
12218
12472
  checkDeployCliRunnable,
12219
12473
  checkRuntimeSecretsInjected,
12220
12474
  checkAwsTargetsPopulated,
12475
+ checkAwsAccountMatchesTarget,
12221
12476
  checkAgentcoreQuotaHeadroom
12222
12477
  ];
12223
12478
 
@@ -12353,7 +12608,7 @@ function collectRuntimeSecretsDetailed(root) {
12353
12608
  sources[KEYSTORE_JSON_ENV] = "wallet-file";
12354
12609
  }
12355
12610
  }
12356
- if (walletKind2 !== "altana" && !(KEYSTORE_JSON_ENV in payload) && !(TWAK_WALLET_JSON_ENV in payload)) {
12611
+ if (walletKind2 !== "altana" && walletKind2 !== "turnkey" && !(KEYSTORE_JSON_ENV in payload) && !(TWAK_WALLET_JSON_ENV in payload)) {
12357
12612
  printErr(
12358
12613
  `WARNING: no wallet signing material found (${KEYSTORE_JSON_ENV} for evm-local / ${TWAK_WALLET_JSON_ENV} for twak). The deployed runtime won't be able to sign quotes or deliveries. Create/adopt a wallet first (e.g. \`bag wallet new\`) and redeploy.`
12359
12614
  );
@@ -15029,6 +15284,15 @@ function printAgentClientPrompt(root, invokeUrl, status) {
15029
15284
  );
15030
15285
  }
15031
15286
  const endpointBlock = endpoints.join("\n");
15287
+ const commerceShapeLines = hasA2aFace(faces) ? [
15288
+ "MESSAGE SHAPES (complete A2A JSON-RPC requests)",
15289
+ '- negotiate: {"jsonrpc":"2.0","id":"request-1","method":"message/send","params":{"message":{"messageId":"message-1","role":"user","parts":[{"kind":"data","data":{"skill":"negotiate","task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}}]}}}',
15290
+ '- notify_funded: {"jsonrpc":"2.0","id":"request-2","method":"message/send","params":{"message":{"messageId":"message-2","role":"user","parts":[{"kind":"data","data":{"skill":"notify_funded","job_id":123}}]}}}'
15291
+ ] : [
15292
+ "MCP TOOL ARGUMENTS",
15293
+ '- negotiate: {"task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
15294
+ '- notify_funded: {"job_id":123}'
15295
+ ];
15032
15296
  const lines = [
15033
15297
  "",
15034
15298
  CLIENT_PROMPT_RULE,
@@ -15061,9 +15325,7 @@ function printAgentClientPrompt(root, invokeUrl, status) {
15061
15325
  "- Remote ERC-8183 callers need an OAuth2 access token:",
15062
15326
  tokenSteps,
15063
15327
  "",
15064
- "MESSAGE SHAPES",
15065
- '- negotiate: {"skill":"negotiate","task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
15066
- '- notify_funded: {"skill":"notify_funded","job_id":<int>}'
15328
+ ...commerceShapeLines
15067
15329
  ] : [
15068
15330
  "- The anonymous x402 route does not use the OAuth2 token flow shown for ERC-8183."
15069
15331
  ],
@@ -16510,6 +16772,28 @@ async function printAgentClientPrompt2(root, destination, opts = {}) {
16510
16772
  The invoke URL carries a querystring (?qualifier=...): never
16511
16773
  string-concatenate extra path segments onto it \u2014 that produces
16512
16774
  an invalid URL and an HTTP 405.`;
16775
+ const commerceShapeLines = hasA2aFace(faces) ? [
16776
+ "MESSAGE SHAPES (complete A2A JSON-RPC requests)",
16777
+ '- negotiate: {"jsonrpc":"2.0","id":"request-1","method":"message/send","params":{"message":{"messageId":"message-1","role":"user","parts":[{"kind":"data","data":{"skill":"negotiate","task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}}]}}}',
16778
+ '- notify_funded: {"jsonrpc":"2.0","id":"request-2","method":"message/send","params":{"message":{"messageId":"message-2","role":"user","parts":[{"kind":"data","data":{"skill":"notify_funded","job_id":123}}]}}}'
16779
+ ] : [
16780
+ "MCP TOOL ARGUMENTS",
16781
+ '- negotiate: {"task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
16782
+ '- notify_funded: {"job_id":123}'
16783
+ ];
16784
+ const mcpSessionLines = hasA2aFace(faces) && hasMcpFace(faces) ? [
16785
+ "",
16786
+ "MCP SESSION FLOW (A2A+MCP through envelope-v1)",
16787
+ " 1) Keep X-Amzn-Bedrock-AgentCore-Runtime-Session-Id on every outer InvokeAgentRuntime request; this is the outer AgentCore runtime session.",
16788
+ " 2) Send an envelope-v1 POST /mcp whose decoded body is the MCP initialize request, with no inner mcp-session-id header.",
16789
+ ' 3) Decode the envelope response and read headers["mcp-session-id"]; this is the inner MCP session, separate from the outer header.',
16790
+ " 4) Send notifications/initialized, then tools/list or tools/call in new envelopes whose inner headers carry that same mcp-session-id."
16791
+ ] : hasMcpFace(faces) ? [
16792
+ "",
16793
+ "MCP SESSION FLOW",
16794
+ " 1) Send initialize without mcp-session-id and capture the response mcp-session-id header.",
16795
+ " 2) Send notifications/initialized, then tools/list or tools/call with that header."
16796
+ ] : [];
16513
16797
  const lines = [
16514
16798
  "",
16515
16799
  CLIENT_PROMPT_RULE2,
@@ -16539,9 +16823,8 @@ async function printAgentClientPrompt2(root, destination, opts = {}) {
16539
16823
  "- Remote ERC-8183 callers need an OAuth2 access token:",
16540
16824
  tokenSteps,
16541
16825
  "",
16542
- "MESSAGE SHAPES",
16543
- '- negotiate: {"skill":"negotiate","task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
16544
- '- notify_funded: {"skill":"notify_funded","job_id":<int>}'
16826
+ ...commerceShapeLines,
16827
+ ...mcpSessionLines
16545
16828
  ] : [
16546
16829
  "- The anonymous x402 route does not use the OAuth2 token flow shown for ERC-8183."
16547
16830
  ],
@@ -17438,7 +17721,8 @@ var SECRET_ENV_KEYS = [
17438
17721
  "PIEVERSE_LLM_API_KEY",
17439
17722
  "STORAGE_API_KEY",
17440
17723
  "TWAK_ACCESS_ID",
17441
- "TWAK_HMAC_SECRET"
17724
+ "TWAK_HMAC_SECRET",
17725
+ "TURNKEY_API_PRIVATE_KEY"
17442
17726
  ];
17443
17727
  function tableOf14(cfg, key) {
17444
17728
  const v = cfg[key];
@@ -17685,6 +17969,9 @@ async function checkWallet(projectRoot, data) {
17685
17969
  if (walletCfg.kind === "altana") {
17686
17970
  return checkWalletAltana(walletCfg, projectRoot, data);
17687
17971
  }
17972
+ if (walletCfg.kind === "turnkey") {
17973
+ return checkWalletTurnkey(walletCfg);
17974
+ }
17688
17975
  if (!isLocalEvmWallet(walletCfg)) {
17689
17976
  return [
17690
17977
  {
@@ -17738,7 +18025,59 @@ async function checkWallet(projectRoot, data) {
17738
18025
  }
17739
18026
  return out;
17740
18027
  }
17741
- function checkWalletAltana(walletCfg, projectRoot, data) {
18028
+ var TURNKEY_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
18029
+ var TURNKEY_REQUIRED_ENV = [
18030
+ "TURNKEY_API_PUBLIC_KEY",
18031
+ "TURNKEY_API_PRIVATE_KEY",
18032
+ "TURNKEY_ORG_ID",
18033
+ "TURNKEY_SIGN_WITH"
18034
+ ];
18035
+ function checkWalletTurnkey(walletCfg) {
18036
+ const out = [];
18037
+ const missing = TURNKEY_REQUIRED_ENV.filter((key) => !process.env[key]);
18038
+ out.push(
18039
+ missing.length === 0 ? {
18040
+ name: "[wallet] turnkey credentials",
18041
+ status: PASS,
18042
+ detail: "API key pair + org id + sign-with address set; reminder: production should use a non-root API user with an explicit ALLOW policy (root keys bypass all Turnkey policies)"
18043
+ } : {
18044
+ name: "[wallet] turnkey credentials",
18045
+ status: FAIL,
18046
+ detail: `missing: ${missing.join(", ")} \u2014 set them in .studio/.env.local (Turnkey dashboard \u2192 API keys / settings / wallet account)`
18047
+ }
18048
+ );
18049
+ const signWith = String(process.env.TURNKEY_SIGN_WITH ?? "").trim();
18050
+ if (signWith !== "" && !TURNKEY_ADDRESS_RE.test(signWith)) {
18051
+ out.push({
18052
+ name: "TURNKEY_SIGN_WITH format",
18053
+ status: FAIL,
18054
+ detail: "must be the wallet account's Ethereum address (0x + 40 hex chars), not a Turnkey wallet id \u2014 copy it from the dashboard wallet-account view"
18055
+ });
18056
+ }
18057
+ const anchored = String(walletCfg.address ?? "").trim();
18058
+ if (anchored === "") {
18059
+ out.push({
18060
+ name: "[wallet] address anchor",
18061
+ status: WARN,
18062
+ detail: "no [wallet].address \u2014 run `bag wallet new` to adopt TURNKEY_SIGN_WITH"
18063
+ });
18064
+ } else if (signWith !== "" && TURNKEY_ADDRESS_RE.test(signWith)) {
18065
+ const matches = anchored.toLowerCase() === signWith.toLowerCase();
18066
+ out.push(
18067
+ matches ? {
18068
+ name: "[wallet] address anchor",
18069
+ status: PASS,
18070
+ detail: `${anchored} matches TURNKEY_SIGN_WITH`
18071
+ } : {
18072
+ name: "[wallet] address anchor",
18073
+ status: FAIL,
18074
+ detail: `[wallet].address ${anchored} does not match TURNKEY_SIGN_WITH ${signWith} \u2014 stale anchor or different Turnkey credentials; fix .studio/.env.local, then re-run \`bag wallet new\``
18075
+ }
18076
+ );
18077
+ }
18078
+ return out;
18079
+ }
18080
+ async function checkWalletAltana(walletCfg, projectRoot, data) {
17742
18081
  const out = [];
17743
18082
  const contracts = erc8183ContractOverrideState(
17744
18083
  erc8183ContractEnvForProject(projectRoot)
@@ -17824,13 +18163,41 @@ function checkWalletAltana(walletCfg, projectRoot, data) {
17824
18163
  out.push({
17825
18164
  name: "[wallet] Altana SDK",
17826
18165
  status: entry === null ? FAIL : PASS,
17827
- detail: entry === null ? "@altananetwork/sdk is not resolvable from this project \u2014 run `pnpm add @altananetwork/sdk@0.5.1`" : entry
18166
+ detail: entry === null ? "@altananetwork/sdk is not resolvable from this project \u2014 run `pnpm add @altananetwork/sdk@0.7.1`" : entry
17828
18167
  });
17829
18168
  } catch (error) {
17830
18169
  out.push({
17831
18170
  name: "[wallet] Altana SDK",
17832
18171
  status: FAIL,
17833
- detail: `${error instanceof Error ? error.message : String(error)} \u2014 run \`pnpm add @altananetwork/sdk@0.5.1\``
18172
+ detail: `${error instanceof Error ? error.message : String(error)} \u2014 run \`pnpm add @altananetwork/sdk@0.7.1\``
18173
+ });
18174
+ }
18175
+ const networkName = String(tableOf14(data, "network").default ?? "bsc-mainnet");
18176
+ try {
18177
+ const allowanceRaw = await readUAllowanceRaw(
18178
+ address,
18179
+ PERMIT2_ADDRESS,
18180
+ networkName
18181
+ );
18182
+ if (allowanceRaw !== null) {
18183
+ const uToken = getNetwork9(networkName).token("U");
18184
+ out.push(
18185
+ allowanceRaw > 0n ? {
18186
+ name: "[wallet] Altana x402 buying",
18187
+ status: PASS,
18188
+ detail: `U\u2192Permit2 allowance ${fromRaw3(allowanceRaw, uToken.decimals)} U on ${networkName} (b402 permit2 rail armed)`
18189
+ } : {
18190
+ name: "[wallet] Altana x402 buying",
18191
+ status: WARN,
18192
+ detail: `no U\u2192Permit2 allowance on ${networkName} \u2014 outbound x402 buying is not armed; run \`bag wallet session x402-setup --allowance-u <amount>\` (admin key) if this agent should pay b402 merchants`
18193
+ }
18194
+ );
18195
+ }
18196
+ } catch (error) {
18197
+ out.push({
18198
+ name: "[wallet] Altana x402 buying",
18199
+ status: WARN,
18200
+ detail: `could not read the U\u2192Permit2 allowance on ${networkName}: ${error instanceof Error ? error.message : String(error)}`
17834
18201
  });
17835
18202
  }
17836
18203
  return out;
@@ -17930,6 +18297,20 @@ function checkPassword(data) {
17930
18297
  }
17931
18298
  ];
17932
18299
  }
18300
+ if (walletKind2 === "turnkey") {
18301
+ const missing = TURNKEY_REQUIRED_ENV.filter((key) => !process.env[key]);
18302
+ return [
18303
+ missing.length === 0 ? {
18304
+ name: "TURNKEY_* env",
18305
+ status: PASS,
18306
+ detail: "all Turnkey credentials set (WALLET_PASSWORD is not used for this kind)"
18307
+ } : {
18308
+ name: "TURNKEY_* env",
18309
+ status: WARN,
18310
+ detail: `missing: ${missing.join(", ")} \u2014 signing will fail (set in .studio/.env.local)`
18311
+ }
18312
+ ];
18313
+ }
17933
18314
  if (process.env.WALLET_PASSWORD) {
17934
18315
  return [{ name: "WALLET_PASSWORD env", status: PASS, detail: "set" }];
17935
18316
  }
@@ -18298,11 +18679,11 @@ function checkX402Seller(data, agentRoot2) {
18298
18679
  }
18299
18680
  ];
18300
18681
  const walletKind2 = String(tableOf14(data, "wallet").kind ?? "evm-local");
18301
- if (!["evm-local", "twak"].includes(walletKind2)) {
18682
+ if (!["evm-local", "twak", "turnkey", "altana"].includes(walletKind2)) {
18302
18683
  out.push({
18303
18684
  name: "x402 payout wallet",
18304
18685
  status: FAIL,
18305
- detail: `PAID B402 supports evm-local or twak, not ${walletKind2}.`
18686
+ detail: `PAID B402 supports evm-local, twak, turnkey or altana, not ${walletKind2}.`
18306
18687
  });
18307
18688
  }
18308
18689
  const credentials = b402Credentials(agentRoot2);
@@ -18376,7 +18757,7 @@ function checkStorage(data) {
18376
18757
  }
18377
18758
  function balanceAddress(projectRoot, data) {
18378
18759
  const walletCfg = tableOf14(data, "wallet");
18379
- if (walletCfg.kind === "twak" || walletCfg.kind === "altana") {
18760
+ if (walletCfg.kind === "twak" || walletCfg.kind === "altana" || walletCfg.kind === "turnkey") {
18380
18761
  const addr = String(walletCfg.address ?? "").trim();
18381
18762
  return addr || null;
18382
18763
  }
@@ -21102,9 +21483,9 @@ async function cmdSellInit(priceFlag) {
21102
21483
  }
21103
21484
  const free = x402SellerPricingState({ price_usd: priceUsd }).kind === "free";
21104
21485
  const walletKind2 = String(tableOf16(cfg, "wallet").kind ?? "evm-local");
21105
- if (!free && !["evm-local", "twak"].includes(walletKind2)) {
21486
+ if (!free && !["evm-local", "twak", "turnkey", "altana"].includes(walletKind2)) {
21106
21487
  printErr(
21107
- `error: the b402 seller rail supports wallet.kind evm-local or twak only; '${walletKind2}' cannot act as the b402 payout wallet.`
21488
+ `error: the b402 seller rail supports wallet.kind evm-local, twak, turnkey or altana only; '${walletKind2}' cannot act as the b402 payout wallet.`
21108
21489
  );
21109
21490
  return 1;
21110
21491
  }
@@ -21230,16 +21611,21 @@ async function cmdSellStatus(probe) {
21230
21611
  }
21231
21612
  try {
21232
21613
  const supported = await _probeB402Supported(process.env);
21233
- const methodKind = supported?.kinds.find(
21234
- (kind) => kind.x402Version === 2 && kind.scheme === "exact" && kind.network === network && kind.extra.assetTransferMethod === "eip3009"
21614
+ const matching = (method) => supported?.kinds.find(
21615
+ (kind) => kind.x402Version === 2 && kind.scheme === "exact" && kind.network === network && kind.extra.assetTransferMethod === method && kind.extra.name === token.eip712Name && kind.extra.version === token.eip712Version
21616
+ );
21617
+ const available = token.methods.filter(
21618
+ (method) => matching(method) !== void 0
21235
21619
  );
21236
- if (methodKind && methodKind.extra.name === token.eip712Name && methodKind.extra.version === token.eip712Version) {
21237
- printOut(`B402 probe: exact/eip3009 U available for ${network}`);
21620
+ if (available.length > 0) {
21621
+ const missing = token.methods.filter((m) => !available.includes(m));
21622
+ printOut(
21623
+ `B402 probe: exact U available for ${network} (${available.join(", ")})${missing.length > 0 ? ` \u2014 advertised but not offered by the facilitator: ${missing.join(", ")}` : ""}`
21624
+ );
21238
21625
  return 0;
21239
21626
  }
21240
- const observed = methodKind ? `observed name=${String(methodKind.extra.name ?? "(missing)")} version=${String(methodKind.extra.version ?? "(missing)")}` : "no exact/eip3009 kind was returned";
21241
21627
  printOut(
21242
- `B402 probe: mismatch for ${network}; expected name=${token.eip712Name} version=${token.eip712Version}; ${observed}. Check that the credentials belong to the matching B402 environment.`
21628
+ `B402 probe: mismatch for ${network}; expected an exact kind (${token.methods.join(" or ")}) with name=${token.eip712Name} version=${token.eip712Version}; none was returned. Check that the credentials belong to the matching B402 environment.`
21243
21629
  );
21244
21630
  } catch {
21245
21631
  printOut(
@@ -21368,6 +21754,30 @@ async function cmdBuy2(url, opts) {
21368
21754
  );
21369
21755
  return 1;
21370
21756
  }
21757
+ const buyWalletKind = String(tableOf16(cfg, "wallet").kind ?? "evm-local");
21758
+ if (buyWalletKind === "altana") {
21759
+ let allowanceRaw;
21760
+ try {
21761
+ allowanceRaw = await readUAllowanceRaw(
21762
+ wallet.address,
21763
+ PERMIT2_ADDRESS,
21764
+ networkName
21765
+ );
21766
+ } catch (exc) {
21767
+ printErr(`error: permit2 allowance check failed: ${errMsg6(exc)}`);
21768
+ return 1;
21769
+ }
21770
+ if (allowanceRaw !== null && allowanceRaw < neededRaw) {
21771
+ const uToken = getNetwork11(networkName).token("U");
21772
+ printErr(
21773
+ `error: U\u2192Permit2 allowance ${fromRaw5(allowanceRaw, uToken.decimals)} U cannot cover max_usd $${opts.maxUsd.toFixed(2)}: b402 settles Altana payments by pulling through Permit2 (${PERMIT2_ADDRESS}).`
21774
+ );
21775
+ printErr(
21776
+ "fix: bag wallet session x402-setup --allowance-u <amount> (admin key; approves the x402 signature checker and sets the bounded Permit2 allowance)"
21777
+ );
21778
+ return 1;
21779
+ }
21780
+ }
21371
21781
  let result;
21372
21782
  try {
21373
21783
  result = await auditedOp4(
@@ -21407,7 +21817,7 @@ async function cmdBuy2(url, opts) {
21407
21817
  }
21408
21818
  const paidUsd = result.paidUsd ?? 0;
21409
21819
  const envelope = result.txPaymentEnvelope ?? "";
21410
- const envelopePreview = envelope ? `${envelope.slice(0, 40)}...` : "(no payment \u2014 server did not 402)";
21820
+ const envelopePreview = envelope ? `${envelope.slice(0, 40)}...` : result.paidUsd !== null ? "(delegated x402 client \u2014 the envelope never leaves the wallet client)" : "(no payment \u2014 server did not 402)";
21411
21821
  const ok = result.statusCode >= 200 && result.statusCode < 300;
21412
21822
  if (result.paidUsd === null) {
21413
21823
  if (ok) {