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

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-AT2UYK5U.js";
55
+ } from "./chunk-APRWJKEA.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-LBDK2B4U.js");
233
+ const { bnbPlatformApiUrl: bnbPlatformApiUrl2 } = await import("./deployCli-HCI42S6E.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({
@@ -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";
@@ -7389,7 +7438,8 @@ function cmdNewTurnkey(projectRoot) {
7389
7438
  const signWith = String(process.env.TURNKEY_SIGN_WITH ?? "").trim();
7390
7439
  if (signWith === "") {
7391
7440
  printErr(
7392
- "error: TURNKEY_SIGN_WITH is not set (wallet.kind = 'turnkey').\nCreate a wallet account in the Turnkey dashboard, set the TURNKEY_* credentials in .studio/.env.local (bag auto-loads it), then re-run `bag wallet new` to adopt + anchor the address."
7441
+ `error: TURNKEY_SIGN_WITH is not set (wallet.kind = 'turnkey').
7442
+ ${turnkeySetupGuidance()}`
7393
7443
  );
7394
7444
  return 1;
7395
7445
  }
@@ -10091,8 +10141,8 @@ function printTurnkeyNotice() {
10091
10141
  `
10092
10142
  NOTE \u2014 wallet.kind = "turnkey" (remote signer, keys in Turnkey's AWS Nitro enclave):
10093
10143
  \xB7 WALLET: no key material exists locally \u2014 the Agent signs via the TURNKEY_*
10094
- API credentials in .studio/.env.local (dashboard \u2192 API keys). Set them,
10095
- then run \`(cd app/agent && bag wallet new)\` to adopt + anchor the address.
10144
+ API credentials in .studio/.env.local.
10145
+ ${turnkeySetupGuidance()}
10096
10146
  \xB7 BILLING: every successful signature is billed (free tier: 25/month at
10097
10147
  1 request/second; pay-as-you-go $0.10 each) \u2014 budget accordingly.
10098
10148
  \xB7 PRODUCTION: use a NON-ROOT API user restricted by an explicit ALLOW policy;
@@ -11626,6 +11676,9 @@ async function checkLocalKeystoreExists(root, _target) {
11626
11676
  if (walletCfg.kind === "altana") {
11627
11677
  return [];
11628
11678
  }
11679
+ if (walletCfg.kind === "turnkey") {
11680
+ return [];
11681
+ }
11629
11682
  const signer = walletCfg.signer ?? "local";
11630
11683
  if (signer !== "local") {
11631
11684
  return [];
@@ -11651,6 +11704,9 @@ async function checkWalletPasswordEnvSet(root, _target) {
11651
11704
  if (kind === "altana") {
11652
11705
  return [];
11653
11706
  }
11707
+ if (kind === "turnkey") {
11708
+ return [];
11709
+ }
11654
11710
  if (process.env.WALLET_PASSWORD) {
11655
11711
  return [];
11656
11712
  }
@@ -12274,6 +12330,46 @@ function awsJson(stdout) {
12274
12330
  return null;
12275
12331
  }
12276
12332
  }
12333
+ async function checkAwsAccountMatchesTarget(root, target) {
12334
+ if (target !== "agentcore") {
12335
+ return [];
12336
+ }
12337
+ const [targetAccount, region] = readAwsTarget(root);
12338
+ if (!targetAccount || !region || !await whichBin("aws")) {
12339
+ return [];
12340
+ }
12341
+ const identity = await runCapture("aws", [
12342
+ "sts",
12343
+ "get-caller-identity",
12344
+ "--region",
12345
+ region,
12346
+ "--output",
12347
+ "json"
12348
+ ]);
12349
+ if (identity.code !== 0) {
12350
+ return [];
12351
+ }
12352
+ const rawAccount = awsJson(identity.stdout)?.Account;
12353
+ const credentialAccount = typeof rawAccount === "string" && /^\d{12}$/.test(rawAccount.trim()) ? rawAccount.trim() : null;
12354
+ if (credentialAccount === null || credentialAccount === targetAccount) {
12355
+ return [];
12356
+ }
12357
+ const targetPath = path24.join(root, "agentcore", "aws-targets.json");
12358
+ return [
12359
+ {
12360
+ level: Level.CRITICAL,
12361
+ name: "aws_account_mismatch",
12362
+ 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.`,
12363
+ details: {
12364
+ credential_account: credentialAccount,
12365
+ target_account: targetAccount,
12366
+ region,
12367
+ path: targetPath
12368
+ },
12369
+ fixCmd: `# edit agentcore/aws-targets.json and set the default account to ${credentialAccount}, or switch the active AWS credentials`
12370
+ }
12371
+ ];
12372
+ }
12277
12373
  async function checkAgentcoreQuotaHeadroom(root, target) {
12278
12374
  if (target !== "agentcore") {
12279
12375
  return [];
@@ -12379,6 +12475,7 @@ var allChecks = [
12379
12475
  checkDeployCliRunnable,
12380
12476
  checkRuntimeSecretsInjected,
12381
12477
  checkAwsTargetsPopulated,
12478
+ checkAwsAccountMatchesTarget,
12382
12479
  checkAgentcoreQuotaHeadroom
12383
12480
  ];
12384
12481
 
@@ -15190,6 +15287,15 @@ function printAgentClientPrompt(root, invokeUrl, status) {
15190
15287
  );
15191
15288
  }
15192
15289
  const endpointBlock = endpoints.join("\n");
15290
+ const commerceShapeLines = hasA2aFace(faces) ? [
15291
+ "MESSAGE SHAPES (complete A2A JSON-RPC requests)",
15292
+ '- 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":"..."}}}]}}}',
15293
+ '- 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}}]}}}'
15294
+ ] : [
15295
+ "MCP TOOL ARGUMENTS",
15296
+ '- negotiate: {"task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
15297
+ '- notify_funded: {"job_id":123}'
15298
+ ];
15193
15299
  const lines = [
15194
15300
  "",
15195
15301
  CLIENT_PROMPT_RULE,
@@ -15222,9 +15328,7 @@ function printAgentClientPrompt(root, invokeUrl, status) {
15222
15328
  "- Remote ERC-8183 callers need an OAuth2 access token:",
15223
15329
  tokenSteps,
15224
15330
  "",
15225
- "MESSAGE SHAPES",
15226
- '- negotiate: {"skill":"negotiate","task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
15227
- '- notify_funded: {"skill":"notify_funded","job_id":<int>}'
15331
+ ...commerceShapeLines
15228
15332
  ] : [
15229
15333
  "- The anonymous x402 route does not use the OAuth2 token flow shown for ERC-8183."
15230
15334
  ],
@@ -16671,6 +16775,28 @@ async function printAgentClientPrompt2(root, destination, opts = {}) {
16671
16775
  The invoke URL carries a querystring (?qualifier=...): never
16672
16776
  string-concatenate extra path segments onto it \u2014 that produces
16673
16777
  an invalid URL and an HTTP 405.`;
16778
+ const commerceShapeLines = hasA2aFace(faces) ? [
16779
+ "MESSAGE SHAPES (complete A2A JSON-RPC requests)",
16780
+ '- 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":"..."}}}]}}}',
16781
+ '- 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}}]}}}'
16782
+ ] : [
16783
+ "MCP TOOL ARGUMENTS",
16784
+ '- negotiate: {"task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
16785
+ '- notify_funded: {"job_id":123}'
16786
+ ];
16787
+ const mcpSessionLines = hasA2aFace(faces) && hasMcpFace(faces) ? [
16788
+ "",
16789
+ "MCP SESSION FLOW (A2A+MCP through envelope-v1)",
16790
+ " 1) Keep X-Amzn-Bedrock-AgentCore-Runtime-Session-Id on every outer InvokeAgentRuntime request; this is the outer AgentCore runtime session.",
16791
+ " 2) Send an envelope-v1 POST /mcp whose decoded body is the MCP initialize request, with no inner mcp-session-id header.",
16792
+ ' 3) Decode the envelope response and read headers["mcp-session-id"]; this is the inner MCP session, separate from the outer header.',
16793
+ " 4) Send notifications/initialized, then tools/list or tools/call in new envelopes whose inner headers carry that same mcp-session-id."
16794
+ ] : hasMcpFace(faces) ? [
16795
+ "",
16796
+ "MCP SESSION FLOW",
16797
+ " 1) Send initialize without mcp-session-id and capture the response mcp-session-id header.",
16798
+ " 2) Send notifications/initialized, then tools/list or tools/call with that header."
16799
+ ] : [];
16674
16800
  const lines = [
16675
16801
  "",
16676
16802
  CLIENT_PROMPT_RULE2,
@@ -16700,9 +16826,8 @@ async function printAgentClientPrompt2(root, destination, opts = {}) {
16700
16826
  "- Remote ERC-8183 callers need an OAuth2 access token:",
16701
16827
  tokenSteps,
16702
16828
  "",
16703
- "MESSAGE SHAPES",
16704
- '- negotiate: {"skill":"negotiate","task_description":"<what you want done>","terms":{"deliverables":"...","quality_standards":"..."}}',
16705
- '- notify_funded: {"skill":"notify_funded","job_id":<int>}'
16829
+ ...commerceShapeLines,
16830
+ ...mcpSessionLines
16706
16831
  ] : [
16707
16832
  "- The anonymous x402 route does not use the OAuth2 token flow shown for ERC-8183."
16708
16833
  ],
@@ -17955,7 +18080,7 @@ function checkWalletTurnkey(walletCfg) {
17955
18080
  }
17956
18081
  return out;
17957
18082
  }
17958
- function checkWalletAltana(walletCfg, projectRoot, data) {
18083
+ async function checkWalletAltana(walletCfg, projectRoot, data) {
17959
18084
  const out = [];
17960
18085
  const contracts = erc8183ContractOverrideState(
17961
18086
  erc8183ContractEnvForProject(projectRoot)
@@ -18041,13 +18166,41 @@ function checkWalletAltana(walletCfg, projectRoot, data) {
18041
18166
  out.push({
18042
18167
  name: "[wallet] Altana SDK",
18043
18168
  status: entry === null ? FAIL : PASS,
18044
- detail: entry === null ? "@altananetwork/sdk is not resolvable from this project \u2014 run `pnpm add @altananetwork/sdk@0.5.1`" : entry
18169
+ detail: entry === null ? "@altananetwork/sdk is not resolvable from this project \u2014 run `pnpm add @altananetwork/sdk@0.7.1`" : entry
18045
18170
  });
18046
18171
  } catch (error) {
18047
18172
  out.push({
18048
18173
  name: "[wallet] Altana SDK",
18049
18174
  status: FAIL,
18050
- detail: `${error instanceof Error ? error.message : String(error)} \u2014 run \`pnpm add @altananetwork/sdk@0.5.1\``
18175
+ detail: `${error instanceof Error ? error.message : String(error)} \u2014 run \`pnpm add @altananetwork/sdk@0.7.1\``
18176
+ });
18177
+ }
18178
+ const networkName = String(tableOf14(data, "network").default ?? "bsc-mainnet");
18179
+ try {
18180
+ const allowanceRaw = await readUAllowanceRaw(
18181
+ address,
18182
+ PERMIT2_ADDRESS,
18183
+ networkName
18184
+ );
18185
+ if (allowanceRaw !== null) {
18186
+ const uToken = getNetwork9(networkName).token("U");
18187
+ out.push(
18188
+ allowanceRaw > 0n ? {
18189
+ name: "[wallet] Altana x402 buying",
18190
+ status: PASS,
18191
+ detail: `U\u2192Permit2 allowance ${fromRaw3(allowanceRaw, uToken.decimals)} U on ${networkName} (b402 permit2 rail armed)`
18192
+ } : {
18193
+ name: "[wallet] Altana x402 buying",
18194
+ status: WARN,
18195
+ 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`
18196
+ }
18197
+ );
18198
+ }
18199
+ } catch (error) {
18200
+ out.push({
18201
+ name: "[wallet] Altana x402 buying",
18202
+ status: WARN,
18203
+ detail: `could not read the U\u2192Permit2 allowance on ${networkName}: ${error instanceof Error ? error.message : String(error)}`
18051
18204
  });
18052
18205
  }
18053
18206
  return out;
@@ -21461,16 +21614,21 @@ async function cmdSellStatus(probe) {
21461
21614
  }
21462
21615
  try {
21463
21616
  const supported = await _probeB402Supported(process.env);
21464
- const methodKind = supported?.kinds.find(
21465
- (kind) => kind.x402Version === 2 && kind.scheme === "exact" && kind.network === network && kind.extra.assetTransferMethod === "eip3009"
21617
+ const matching = (method) => supported?.kinds.find(
21618
+ (kind) => kind.x402Version === 2 && kind.scheme === "exact" && kind.network === network && kind.extra.assetTransferMethod === method && kind.extra.name === token.eip712Name && kind.extra.version === token.eip712Version
21466
21619
  );
21467
- if (methodKind && methodKind.extra.name === token.eip712Name && methodKind.extra.version === token.eip712Version) {
21468
- printOut(`B402 probe: exact/eip3009 U available for ${network}`);
21620
+ const available = token.methods.filter(
21621
+ (method) => matching(method) !== void 0
21622
+ );
21623
+ if (available.length > 0) {
21624
+ const missing = token.methods.filter((m) => !available.includes(m));
21625
+ printOut(
21626
+ `B402 probe: exact U available for ${network} (${available.join(", ")})${missing.length > 0 ? ` \u2014 advertised but not offered by the facilitator: ${missing.join(", ")}` : ""}`
21627
+ );
21469
21628
  return 0;
21470
21629
  }
21471
- const observed = methodKind ? `observed name=${String(methodKind.extra.name ?? "(missing)")} version=${String(methodKind.extra.version ?? "(missing)")}` : "no exact/eip3009 kind was returned";
21472
21630
  printOut(
21473
- `B402 probe: mismatch for ${network}; expected name=${token.eip712Name} version=${token.eip712Version}; ${observed}. Check that the credentials belong to the matching B402 environment.`
21631
+ `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.`
21474
21632
  );
21475
21633
  } catch {
21476
21634
  printOut(
@@ -21599,6 +21757,30 @@ async function cmdBuy2(url, opts) {
21599
21757
  );
21600
21758
  return 1;
21601
21759
  }
21760
+ const buyWalletKind = String(tableOf16(cfg, "wallet").kind ?? "evm-local");
21761
+ if (buyWalletKind === "altana") {
21762
+ let allowanceRaw;
21763
+ try {
21764
+ allowanceRaw = await readUAllowanceRaw(
21765
+ wallet.address,
21766
+ PERMIT2_ADDRESS,
21767
+ networkName
21768
+ );
21769
+ } catch (exc) {
21770
+ printErr(`error: permit2 allowance check failed: ${errMsg6(exc)}`);
21771
+ return 1;
21772
+ }
21773
+ if (allowanceRaw !== null && allowanceRaw < neededRaw) {
21774
+ const uToken = getNetwork11(networkName).token("U");
21775
+ printErr(
21776
+ `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}).`
21777
+ );
21778
+ printErr(
21779
+ "fix: bag wallet session x402-setup --allowance-u <amount> (admin key; approves the x402 signature checker and sets the bounded Permit2 allowance)"
21780
+ );
21781
+ return 1;
21782
+ }
21783
+ }
21602
21784
  let result;
21603
21785
  try {
21604
21786
  result = await auditedOp4(
@@ -21638,7 +21820,7 @@ async function cmdBuy2(url, opts) {
21638
21820
  }
21639
21821
  const paidUsd = result.paidUsd ?? 0;
21640
21822
  const envelope = result.txPaymentEnvelope ?? "";
21641
- const envelopePreview = envelope ? `${envelope.slice(0, 40)}...` : "(no payment \u2014 server did not 402)";
21823
+ 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)";
21642
21824
  const ok = result.statusCode >= 200 && result.statusCode < 300;
21643
21825
  if (result.paidUsd === null) {
21644
21826
  if (ok) {
@@ -21,8 +21,15 @@ import { stringify as tomlStringify } from "smol-toml";
21
21
  import { createHash } from "crypto";
22
22
  import * as fs from "fs";
23
23
  import * as path from "path";
24
+ import {
25
+ TURNKEY_SDK_SERVER_PACKAGE,
26
+ TURNKEY_VIEM_PACKAGE
27
+ } from "@bnbagent/sdk/wallets";
24
28
  import { loadStudioToml } from "@bnbagent/studio-runtime/config";
25
- import { resolveProjectAltanaSdkEntry } from "@bnbagent/studio-runtime/wallet";
29
+ import {
30
+ resolveProjectAltanaSdkEntry,
31
+ resolveProjectTurnkeySdkEntry
32
+ } from "@bnbagent/studio-runtime/wallet";
26
33
  import { build as esbuildBuild } from "esbuild";
27
34
 
28
35
  // src/cli/utils/protocol.ts
@@ -141,6 +148,7 @@ async function buildZip(agentDir, outZip, opts = {}) {
141
148
  stageManifest(agentDir, buildRoot, entrypoint);
142
149
  stageStudioToml(agentDir, buildRoot);
143
150
  await stageAltanaSdk(agentDir, buildRoot, opts.bundle ?? bundleEntry);
151
+ await stageTurnkeySdk(agentDir, buildRoot, opts.bundle ?? bundleEntry);
144
152
  assertWithinUncompressedCap(
145
153
  buildRoot,
146
154
  opts.maxUncompressedBytes ?? MAX_UNCOMPRESSED_BYTES
@@ -277,7 +285,7 @@ async function stageAltanaSdk(agentDir, buildRoot, bundle) {
277
285
  }
278
286
  if (entry === null) {
279
287
  throw new Error(
280
- "wallet.kind='altana' but @altananetwork/sdk is not resolvable from the agent project \u2014 the zip runtime could never load the Altana session wallet. Run `pnpm add @altananetwork/sdk@0.5.1` in app/agent, or deploy as a container."
288
+ "wallet.kind='altana' but @altananetwork/sdk is not resolvable from the agent project \u2014 the zip runtime could never load the Altana session wallet. Run `pnpm add @altananetwork/sdk@0.7.1` in app/agent, or deploy as a container."
281
289
  );
282
290
  }
283
291
  const pkgDir = path.join(buildRoot, "node_modules", "@altananetwork", "sdk");
@@ -288,7 +296,7 @@ async function stageAltanaSdk(agentDir, buildRoot, bundle) {
288
296
  `${JSON.stringify(
289
297
  {
290
298
  name: "@altananetwork/sdk",
291
- version: altanaSdkVersionOf(entry),
299
+ version: packageVersionOf(entry, "@altananetwork/sdk"),
292
300
  private: true,
293
301
  type: "module",
294
302
  main: "index.js"
@@ -299,14 +307,76 @@ async function stageAltanaSdk(agentDir, buildRoot, bundle) {
299
307
  `
300
308
  );
301
309
  }
302
- function altanaSdkVersionOf(entry) {
310
+ async function stageTurnkeySdk(agentDir, buildRoot, bundle) {
311
+ let kind = "evm-local";
312
+ try {
313
+ const cfg = loadStudioToml(path.join(agentDir, "studio.toml"));
314
+ const wallet = cfg.wallet;
315
+ if (wallet !== null && typeof wallet === "object" && !Array.isArray(wallet)) {
316
+ kind = String(wallet.kind ?? "evm-local");
317
+ }
318
+ } catch {
319
+ }
320
+ if (kind !== "turnkey") {
321
+ return;
322
+ }
323
+ const packageNames = [
324
+ TURNKEY_SDK_SERVER_PACKAGE,
325
+ TURNKEY_VIEM_PACKAGE
326
+ ];
327
+ const entries = /* @__PURE__ */ new Map();
328
+ try {
329
+ for (const packageName of packageNames) {
330
+ const entry = resolveProjectTurnkeySdkEntry(agentDir, packageName);
331
+ if (entry !== null) {
332
+ entries.set(packageName, entry);
333
+ }
334
+ }
335
+ } catch (exc) {
336
+ throw new Error(
337
+ `wallet.kind='turnkey' zip build: ${exc instanceof Error ? exc.message : exc}`
338
+ );
339
+ }
340
+ if (entries.size !== packageNames.length) {
341
+ const missing = packageNames.filter((name) => !entries.has(name));
342
+ throw new Error(
343
+ `wallet.kind='turnkey' zip build: missing ${missing.join(", ")}; install both Turnkey packages in app/agent: pnpm add ${TURNKEY_SDK_SERVER_PACKAGE} ${TURNKEY_VIEM_PACKAGE}, or deploy as a container.`
344
+ );
345
+ }
346
+ for (const packageName of packageNames) {
347
+ const entry = entries.get(packageName);
348
+ const packageDir = path.join(
349
+ buildRoot,
350
+ "node_modules",
351
+ ...packageName.split("/")
352
+ );
353
+ fs.mkdirSync(packageDir, { recursive: true });
354
+ await bundle(entry, path.join(packageDir, "index.js"));
355
+ fs.writeFileSync(
356
+ path.join(packageDir, "package.json"),
357
+ `${JSON.stringify(
358
+ {
359
+ name: packageName,
360
+ version: packageVersionOf(entry, packageName),
361
+ private: true,
362
+ type: "module",
363
+ main: "index.js"
364
+ },
365
+ null,
366
+ 2
367
+ )}
368
+ `
369
+ );
370
+ }
371
+ }
372
+ function packageVersionOf(entry, packageName) {
303
373
  let cursor = path.dirname(entry);
304
374
  for (let i = 0; i < 4; i += 1) {
305
375
  const manifest = path.join(cursor, "package.json");
306
376
  if (isFile(manifest)) {
307
377
  try {
308
378
  const pkg = JSON.parse(fs.readFileSync(manifest, "utf-8"));
309
- if (pkg.name === "@altananetwork/sdk") {
379
+ if (pkg.name === packageName) {
310
380
  return typeof pkg.version === "string" ? pkg.version : "0.0.0";
311
381
  }
312
382
  } catch {
@@ -686,8 +756,8 @@ function packageRoot() {
686
756
  }
687
757
  }
688
758
  function studioCliVersion() {
689
- if ("0.0.12-alpha.1") {
690
- return "0.0.12-alpha.1";
759
+ if ("0.0.12-alpha.3") {
760
+ return "0.0.12-alpha.3";
691
761
  }
692
762
  const file = path3.join(packageRoot(), "package.json");
693
763
  const pkg = JSON.parse(fs3.readFileSync(file, "utf-8"));
@@ -18,7 +18,7 @@ import {
18
18
  runPlatformAccountCommand,
19
19
  trialFromDeployCliJson,
20
20
  withDeployFiles
21
- } from "./chunk-AT2UYK5U.js";
21
+ } from "./chunk-APRWJKEA.js";
22
22
  import "./chunk-RO726HJG.js";
23
23
  export {
24
24
  BNB_PLATFORM_API_URL,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bnbagent/studio-cli",
3
- "version": "0.0.12-alpha.1",
3
+ "version": "0.0.12-alpha.3",
4
4
  "description": "Skills-first toolkit and bag CLI for BNB Chain seller agents: ERC-8004 identity, ERC-8183 escrowed commerce, and x402 payments.",
5
5
  "keywords": [
6
6
  "bnb-chain",
@@ -42,7 +42,7 @@
42
42
  "bag": "./dist/bag.js"
43
43
  },
44
44
  "dependencies": {
45
- "@bnbagent/sdk": "0.5.1-alpha.2",
45
+ "@bnbagent/sdk": "0.5.1-alpha.3",
46
46
  "ai": "^7.0.29",
47
47
  "archiver": "^8.0.0",
48
48
  "commander": "^15.0.0",
@@ -54,7 +54,7 @@
54
54
  "tar": "^7.4.0",
55
55
  "viem": "^2.54.0",
56
56
  "yaml": "^2.9.0",
57
- "@bnbagent/studio-runtime": "0.0.12-alpha.1"
57
+ "@bnbagent/studio-runtime": "0.0.12-alpha.3"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@a2a-js/sdk": "^0.3.14",
@@ -6,7 +6,7 @@ description = "Configures the agent's wallet: 'evm-local' (default encrypted key
6
6
  node = ["@bnbagent/studio-runtime"]
7
7
 
8
8
  [dependencies.altana]
9
- node = ["@altananetwork/sdk@0.5.1"]
9
+ node = ["@altananetwork/sdk@0.7.1"]
10
10
 
11
11
  [dependencies.turnkey]
12
12
  node = ["@turnkey/sdk-server@8.1.0", "@turnkey/viem@0.14.34"]
@@ -51,6 +51,8 @@ verified = true # studio-reviewed shelf
51
51
 
52
52
  Hard-stop cases: a reviewed merchant whose live payTo drifts from the studio pin (address rotation or tampering - upgrade studio or verify out-of-band and pass `--pay-to`), and `--cap` below the live per-call price.
53
53
 
54
+ Wallet kinds and rails: `evm-local` signs EIP-3009 locally; `twak` and `altana` route through a delegated payer that prefers the merchant's permit2 route. Altana smart-account payments are verified by the B402 facilitator on its permit2 rails (live since 2026-08, CMC field-verified) and need the one-time `bag wallet session x402-setup` arming (checker approval + bounded U→Permit2 allowance) - `bag doctor` shows the arming state as `[wallet] Altana x402 buying`.
55
+
54
56
  ## Step 2 - wire the buyer tools into the agent
55
57
 
56
58
  ```bash
@@ -99,7 +101,8 @@ bag dev # then ask the agent something that needs the paid data
99
101
  | `X402RecipientRequiredError` | No pinned recipient for that host → same fix |
100
102
  | `X402RecipientMismatchError` | Live payTo drifted from the pin - do NOT override casually; re-verify the merchant |
101
103
  | `X402BudgetExhaustedError` | Per-call cap or daily budget hit - raise `per_call_cap_usd` / `[budget].max_per_day_usd` deliberately |
102
- | `x402 402 has no EIP-3009-payable option` | Merchant offers only permit2/other methods for $U on this network - not payable by this buyer today |
104
+ | `x402 402 has no EIP-3009-payable option` | Merchant offers only permit2/other methods for $U on this network - a local-signing (`evm-local`) buyer cannot sign those. Delegated wallets pay permit2 routes through their own client: `twak` (mainnet), or `altana` sessions (ERC-1271; B402 verifies them on the permit2 rails - arm once with `bag wallet session x402-setup`) |
105
+ | `U→Permit2 allowance … cannot cover max_usd` | Altana only: the bounded Permit2 allowance is spent/too small - re-run `bag wallet session x402-setup --allowance-u <amount>` (admin key) |
103
106
  | `X402PolicyError` / `PolicyViolation` | Signing allowlist - see `bnbagent-studio-extending-signing.md` |
104
107
 
105
108
  **Different from**:
@@ -61,7 +61,7 @@ The user wants the agent to pay e.g. `api.example.com` via x402.
61
61
  2. The service uses **EIP-3009 `TransferWithAuthorization`** (or `ReceiveWithAuthorization`). If it uses Permit2 or a custom primary type → goes to Section B.
62
62
  3. The token contract address on BSC is known and the user can confirm it. Don't guess from a token symbol - look up the deployed address.
63
63
 
64
- If any of (1)-(3) fail, **stop and tell the user**. The current release cannot integrate cross-chain services or non-EIP-3009 payment rails. Do not work around it; the SigningPolicy will refuse the request.
64
+ If any of (1)-(3) fail, **stop and tell the user**. The current release cannot integrate cross-chain services or non-EIP-3009 payment rails into the LOCAL signer. Do not work around it; the SigningPolicy will refuse the request. (Merchants that only offer permit2 are still payable without touching SigningPolicy - through a delegated wallet kind: `twak`, or `altana` sessions, whose ERC-1271 signatures B402 verifies on its permit2 rails. That is a wallet-kind choice, not a signing extension.)
65
65
 
66
66
  **Steps when (1)-(3) all pass:**
67
67
 
@@ -144,7 +144,7 @@ When the credentials, IP allowlist, and facilitator environment are ready, run t
144
144
  bag x402 sell status
145
145
  ```
146
146
 
147
- For a sandbox/trial agent, it must find exact/eip3009 U on `eip155:97`. For production it must find the mainnet environment expected by the project. A network mismatch is not safe to ignore.
147
+ For a sandbox/trial agent, it must find an exact U kind on `eip155:97` (the probe lists the offered rails, e.g. `(eip3009, permit2-exact)`). For production it must find the mainnet environment expected by the project. A network mismatch is not safe to ignore.
148
148
 
149
149
  Run the deployment gate, then redeploy to activate the selected mode:
150
150
 
@@ -165,4 +165,5 @@ On the managed platform the deploy summary must say `x402 rail is ACTIVE` (or `A
165
165
  - Settlement happens before work. A later work failure retains the payment and does not trigger an automatic refund.
166
166
  - The rail activates on AgentCore and Azure Foundry targets (managed platform or self-hosted); self-hosted targets have no anonymous URL and need an operator-run envelope-v1 front.
167
167
  - PAID B402 payout wallets must use `wallet.kind` `evm-local` (private-key wallet stored as an encrypted keystore) or `twak`. Altana is unsupported. FREE x402 bypasses B402, has no payout, and must not be described as Altana B402 support.
168
+ - Buyer compatibility: the 402 challenge advertises both `exact` rails - `eip3009` (EOA buyers, no pre-authorization) and `permit2-exact` (B402 verifies ERC-1271 smart-account signatures on this rail, so Altana sessions and ERC-4337 wallets can pay; the buyer needs a bounded U→Permit2 allowance first - see `bnbagent-studio-using-altana-wallet.md`). Rails are filtered against the facilitator's live `/supported`; `bag x402 sell status` prints which rails it actually offers, e.g. `(eip3009, permit2-exact)`. The seller never verifies signatures locally on either rail.
168
169
  - Never describe FREE as a zero-value B402 settlement. It bypasses B402.
@@ -48,6 +48,8 @@ x402 buying remains separate and exact-bounded:
48
48
  bag wallet session x402-setup --allowance-u <U> --yes
49
49
  ```
50
50
 
51
+ Once armed, `bag x402 buy` pays b402-facilitated merchants (e.g. CoinMarketCap) end to end: B402 verifies the session's ERC-1271 signature on its **permit2 rails** (live since 2026-08). Studio's own b402 sellers advertise `permit2-exact` alongside `eip3009`, so Altana wallets can pay studio-hosted merchants too; eip3009-only merchants still need a 65-byte EOA signature and cannot be paid by a smart account. The buy preflight checks the U→Permit2 allowance against the spend cap, and `bag doctor` reports `[wallet] Altana x402 buying`. Use `@altananetwork/sdk` 0.7.1 in the project.
52
+
51
53
  Altana cannot be the b402 **seller** payout wallet for a positive price (paid mode allows `evm-local` and `twak` only); init, `bag x402 sell init`, and deploy readiness reject that paid combination. Explicit `price_usd = "0"` is allowed because FREE passthrough performs no payout and bypasses B402. The outbound buying authority above remains a separate feature.
52
54
 
53
55
  For troubleshooting, run `bag doctor` and `bag wallet session status`. Do not print, parse, or copy the `signer` portion of the serialized session, and never move `.studio/wallets/` under `app/agent/`.