@finchtech/cli 0.3.9 → 0.4.0

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/finch.js CHANGED
@@ -1,10 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire as createBundleRequire } from 'node:module'; const require = createBundleRequire(import.meta.url);
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x2)(function(x2) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x2 + '" is not supported');
14
+ });
8
15
  var __esm = (fn, res, err2) => function __init() {
9
16
  if (err2) throw err2[0];
10
17
  try {
@@ -13,7 +20,7 @@ var __esm = (fn, res, err2) => function __init() {
13
20
  throw err2 = [e], e;
14
21
  }
15
22
  };
16
- var __commonJS = (cb, mod2) => function __require() {
23
+ var __commonJS = (cb, mod2) => function __require2() {
17
24
  try {
18
25
  return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
19
26
  } catch (e) {
@@ -3315,8 +3322,8 @@ var require_utils = __commonJS({
3315
3322
  var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };
3316
3323
  var HOST_DELIM_RE = /[@/?#:]/g;
3317
3324
  var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
3318
- function reescapeHostDelimiters(host, isIP) {
3319
- const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
3325
+ function reescapeHostDelimiters(host, isIP2) {
3326
+ const re = isIP2 ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
3320
3327
  re.lastIndex = 0;
3321
3328
  return host.replace(re, (ch) => HOST_DELIMS[ch]);
3322
3329
  }
@@ -3805,7 +3812,7 @@ var require_fast_uri = __commonJS({
3805
3812
  fragment: void 0
3806
3813
  };
3807
3814
  let malformedAuthorityOrPort = false;
3808
- let isIP = false;
3815
+ let isIP2 = false;
3809
3816
  if (options.reference === "suffix") {
3810
3817
  if (options.scheme) {
3811
3818
  uri = options.scheme + ":" + uri;
@@ -3854,9 +3861,9 @@ var require_fast_uri = __commonJS({
3854
3861
  if (ipv4result === false) {
3855
3862
  const ipv6result = normalizeIPv6(parsed2.host);
3856
3863
  parsed2.host = ipv6result.host.toLowerCase();
3857
- isIP = ipv6result.isIPV6;
3864
+ isIP2 = ipv6result.isIPV6;
3858
3865
  } else {
3859
- isIP = true;
3866
+ isIP2 = true;
3860
3867
  }
3861
3868
  }
3862
3869
  if (parsed2.scheme === void 0 && parsed2.userinfo === void 0 && parsed2.host === void 0 && parsed2.port === void 0 && parsed2.query === void 0 && !parsed2.path) {
@@ -3873,7 +3880,7 @@ var require_fast_uri = __commonJS({
3873
3880
  }
3874
3881
  const schemeHandler = getSchemeHandler(options.scheme || parsed2.scheme);
3875
3882
  if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
3876
- if (parsed2.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed2.host)) {
3883
+ if (parsed2.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP2 === false && nonSimpleDomain(parsed2.host)) {
3877
3884
  try {
3878
3885
  parsed2.host = new URL("http://" + parsed2.host).hostname;
3879
3886
  } catch (e) {
@@ -3887,7 +3894,7 @@ var require_fast_uri = __commonJS({
3887
3894
  parsed2.scheme = unescape(parsed2.scheme);
3888
3895
  }
3889
3896
  if (parsed2.host !== void 0) {
3890
- parsed2.host = reescapeHostDelimiters(unescape(parsed2.host), isIP);
3897
+ parsed2.host = reescapeHostDelimiters(unescape(parsed2.host), isIP2);
3891
3898
  }
3892
3899
  }
3893
3900
  if (parsed2.path) {
@@ -6606,6 +6613,66 @@ var require_ajv = __commonJS({
6606
6613
  }
6607
6614
  });
6608
6615
 
6616
+ // package.json
6617
+ var package_default;
6618
+ var init_package = __esm({
6619
+ "package.json"() {
6620
+ package_default = {
6621
+ name: "@finchtech/cli",
6622
+ version: "0.4.0",
6623
+ description: "Finch Agent CLI for wallet-owned marketplace and MCP workflows.",
6624
+ type: "module",
6625
+ bin: {
6626
+ finch: "dist/finch.js",
6627
+ finchtech: "dist/finch.js"
6628
+ },
6629
+ files: [
6630
+ "dist/finch.js",
6631
+ "README.md",
6632
+ "THIRD_PARTY_LICENSES.txt"
6633
+ ],
6634
+ engines: {
6635
+ node: ">=20"
6636
+ },
6637
+ publishConfig: {
6638
+ access: "public"
6639
+ },
6640
+ repository: {
6641
+ type: "git",
6642
+ url: "git+https://github.com/FinchipAI/Finch-Site.git",
6643
+ directory: "apps/cli"
6644
+ },
6645
+ homepage: "https://www.finchtech.ai",
6646
+ scripts: {
6647
+ build: `esbuild src/bootstrap.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/finch.js --banner:js="import { createRequire as createBundleRequire } from 'node:module'; const require = createBundleRequire(import.meta.url);"`,
6648
+ check: "pnpm lint && pnpm typecheck && pnpm test && pnpm build",
6649
+ lint: "eslint src vitest.config.ts eslint.config.mjs",
6650
+ prepack: "pnpm build",
6651
+ test: "vitest run",
6652
+ typecheck: "tsc --noEmit"
6653
+ },
6654
+ devDependencies: {
6655
+ "@eslint/js": "9.39.2",
6656
+ "@finch/agent-market-contracts": "workspace:*",
6657
+ "@finch/deployment-manifest": "workspace:*",
6658
+ "@finch/skill-content": "workspace:*",
6659
+ "@finch/skill-market-contracts": "workspace:*",
6660
+ "@finch/task-market-contracts": "workspace:*",
6661
+ "@types/cross-spawn": "6.0.6",
6662
+ "@types/node": "20.19.30",
6663
+ ajv: "8.20.0",
6664
+ "cross-spawn": "7.0.6",
6665
+ esbuild: "0.28.2",
6666
+ eslint: "9.39.2",
6667
+ typescript: "5.9.3",
6668
+ "typescript-eslint": "8.67.0",
6669
+ viem: "2.55.15",
6670
+ vitest: "4.1.10"
6671
+ }
6672
+ };
6673
+ }
6674
+ });
6675
+
6609
6676
  // src/state.ts
6610
6677
  import { execFile } from "node:child_process";
6611
6678
  import { constants } from "node:fs";
@@ -7086,7 +7153,7 @@ function localFailureMessage(error51) {
7086
7153
  }
7087
7154
  return "Command input does not match the expected schema. Check finch help for this command.";
7088
7155
  }
7089
- var CliAuthorityError, CliProductionUnavailableError, BrowserOpenError, PUBLIC_RECOVERY_COMMAND, CliRecoveryBlockedError, CliSkillSourceError, CliSkillPresentationStaleError, CliSkillRecoveryUncertainError, CliSkillPublicationError;
7156
+ var CliAuthorityError, CliProductionUnavailableError, BrowserOpenError, MCP_AUTHORIZATION_FLOW_GUIDANCE, McpAuthorizationFlowError, PUBLIC_RECOVERY_COMMAND, CliRecoveryBlockedError, CliSkillSourceError, CliSkillPresentationStaleError, CliSkillRecoveryUncertainError, CliSkillPublicationError;
7090
7157
  var init_cli_error = __esm({
7091
7158
  "src/cli-error.ts"() {
7092
7159
  "use strict";
@@ -7112,6 +7179,30 @@ var init_cli_error = __esm({
7112
7179
  this.name = "BrowserOpenError";
7113
7180
  }
7114
7181
  };
7182
+ MCP_AUTHORIZATION_FLOW_GUIDANCE = Object.freeze({
7183
+ login_command_not_started: "The login command after -- could not be started. Check that the MCP client is installed and the command is correct, or use finch mcp authorize --stdin with the URL its native login prints.",
7184
+ request_url_not_found: "The login command did not print a Finch authorization URL in time and was stopped; its callback listener is gone. Start the MCP client native login again, keep it running, and pass the new URL to finch mcp authorize --stdin, or run the command shown on the Finch authorization page.",
7185
+ second_authorization_request: "The login command started a second authorization request, which was not approved and the command was stopped. Start the MCP client native login again.",
7186
+ login_command_failed: "The authorization was approved, but the login command exited unsuccessfully. Read its output above, then start the MCP client native login again.",
7187
+ login_command_timeout: "The authorization was approved and the callback delivered, but the login command did not exit in time and was stopped. Check the MCP client connection; if it is not authorized, start its native login again.",
7188
+ callback_rejected: "The authorization was approved, but the MCP client callback rejected it. Start the MCP client native login again.",
7189
+ callback_delivery_unknown: "The authorization was approved, but whether the MCP client received the callback is unknown. Check the MCP client connection before starting its native login again.",
7190
+ callback_unreachable: "The authorization was approved, but no MCP client callback listener was reachable on this machine. Keep the MCP client native login running on the same machine as Finch CLI and try again.",
7191
+ stdin_invalid: "Pass exactly one Finch authorization URL on standard input, for example printf '%s' '<URL>' | finch mcp authorize --stdin."
7192
+ });
7193
+ McpAuthorizationFlowError = class extends Error {
7194
+ constructor(reason, detail = {}, options) {
7195
+ super("MCP_AUTHORIZATION_FLOW_FAILED", options);
7196
+ this.reason = reason;
7197
+ this.detail = detail;
7198
+ this.name = "McpAuthorizationFlowError";
7199
+ this.guidance = MCP_AUTHORIZATION_FLOW_GUIDANCE[reason];
7200
+ }
7201
+ reason;
7202
+ detail;
7203
+ code = "MCP_AUTHORIZATION_FLOW_FAILED";
7204
+ guidance;
7205
+ };
7115
7206
  PUBLIC_RECOVERY_COMMAND = /^(?:finch purchase (?:submit|recover-approval) [0-9a-f-]+(?: --transaction-hash 0x[0-9a-f]{64})?|finch task recover [0-9a-f-]+ (?:publish|award|reclaim)|finch skill recover (?:publication|intent) [0-9a-f]{64})$/u;
7116
7207
  CliRecoveryBlockedError = class extends Error {
7117
7208
  code = "CLI_RECOVERY_BLOCKED";
@@ -12571,7 +12662,7 @@ function decodeAgentCliMcpAuthorizationRequest(requestToken) {
12571
12662
  }
12572
12663
  return requestUrl;
12573
12664
  }
12574
- var booleanSchema, timestampSchema, agentCliMcpAuthorizationRequestTokenPrefix, agentCliMcpAuthorizationRequestMaximumUrlBytes, agentCliMcpAuthorizationRequestMaximumPayloadCharacters, base64UrlAlphabet, AGENT_CLI_MCP_AUTHORIZATION_REQUEST_TOKEN, LOCAL_SIGNING_ABANDON_CONTRACT, localSigningAbandonReceiptSchema, authorizationBase, browserAuthorizationBase, signingStatusSchema, agentCliSigningIntentSchema, browserPublicationSigningIntentSchema, browserPurchaseSigningIntentSchema, agentCliSigningApproveRequestSchema, agentCliSigningDenyRequestSchema, agentCliSigningDecisionResponseSchema, agentCliCredentialClaimSchema, agentCliCredentialSetupSchema, agentCliCredentialFulfillmentReceiptSchema, CLI_AGENTON_CREDENTIAL_MATERIAL_DOWNLOAD_CONTRACT, AGENT_CLI_V1_HTTP_OPERATIONS, AGENT_CLI_OUTPUT_CONTRACT, agentCliErrorEnvelopeSchema, cliHttpErrorCodes, agentCliLocalErrorCodes, nullableCliStringSchema, cliLocalErrorEnvelopeSchema, AGENT_CLI_RECOVERY_CONTRACT;
12665
+ var booleanSchema, timestampSchema, agentCliMcpAuthorizationRequestTokenPrefix, agentCliMcpAuthorizationRequestMaximumUrlBytes, agentCliMcpAuthorizationRequestMaximumPayloadCharacters, base64UrlAlphabet, AGENT_CLI_MCP_AUTHORIZATION_REQUEST_TOKEN, AGENT_CLI_MCP_AUTHORIZATION_CLIENT, LOCAL_SIGNING_ABANDON_CONTRACT, localSigningAbandonReceiptSchema, authorizationBase, browserAuthorizationBase, signingStatusSchema, agentCliSigningIntentSchema, browserPublicationSigningIntentSchema, browserPurchaseSigningIntentSchema, agentCliSigningApproveRequestSchema, agentCliSigningDenyRequestSchema, agentCliSigningDecisionResponseSchema, agentCliCredentialClaimSchema, agentCliCredentialSetupSchema, agentCliCredentialFulfillmentReceiptSchema, CLI_AGENTON_CREDENTIAL_MATERIAL_DOWNLOAD_CONTRACT, AGENT_CLI_V1_HTTP_OPERATIONS, AGENT_CLI_OUTPUT_CONTRACT, agentCliErrorEnvelopeSchema, cliHttpErrorCodes, agentCliLocalErrorCodes, nullableCliStringSchema, cliLocalErrorEnvelopeSchema, AGENT_CLI_RECOVERY_CONTRACT;
12575
12666
  var init_agent_cli = __esm({
12576
12667
  "../../packages/agent-market-contracts/src/v1/agent-cli.ts"() {
12577
12668
  "use strict";
@@ -12593,6 +12684,11 @@ var init_agent_cli = __esm({
12593
12684
  maximumUrlBytes: agentCliMcpAuthorizationRequestMaximumUrlBytes,
12594
12685
  shellMetacharacters: false
12595
12686
  });
12687
+ AGENT_CLI_MCP_AUTHORIZATION_CLIENT = Object.freeze({
12688
+ versionHeader: "x-finch-cli-version",
12689
+ minimumVersion: "0.4.0",
12690
+ packageName: "@finchtech/cli"
12691
+ });
12596
12692
  LOCAL_SIGNING_ABANDON_CONTRACT = Object.freeze({
12597
12693
  transport: "local_only",
12598
12694
  networkCalls: 0,
@@ -12821,7 +12917,8 @@ var init_agent_cli = __esm({
12821
12917
  agentCliLocalErrorCodes = Object.freeze([
12822
12918
  ...agentMarketErrorCodes,
12823
12919
  ...cliHttpErrorCodes,
12824
- "BROWSER_OPEN_FAILED"
12920
+ "BROWSER_OPEN_FAILED",
12921
+ "MCP_AUTHORIZATION_FLOW_FAILED"
12825
12922
  ]);
12826
12923
  nullableCliStringSchema = { type: ["string", "null"] };
12827
12924
  cliLocalErrorEnvelopeSchema = strictObjectSchema({
@@ -42339,44 +42436,44 @@ var init_formatter = __esm({
42339
42436
  });
42340
42437
 
42341
42438
  // ../../node_modules/.pnpm/viem@2.55.15_bufferutil@4.1_ce20031be19c56210207d462110a7a29/node_modules/viem/_esm/utils/formatters/transactionRequest.js
42342
- function formatTransactionRequest(request, _) {
42439
+ function formatTransactionRequest(request2, _) {
42343
42440
  const rpcRequest = {};
42344
- if (typeof request.authorizationList !== "undefined")
42345
- rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList);
42346
- if (typeof request.accessList !== "undefined")
42347
- rpcRequest.accessList = request.accessList;
42348
- if (typeof request.blobVersionedHashes !== "undefined")
42349
- rpcRequest.blobVersionedHashes = request.blobVersionedHashes;
42350
- if (typeof request.blobs !== "undefined") {
42351
- if (typeof request.blobs[0] !== "string")
42352
- rpcRequest.blobs = request.blobs.map((x2) => bytesToHex(x2));
42441
+ if (typeof request2.authorizationList !== "undefined")
42442
+ rpcRequest.authorizationList = formatAuthorizationList(request2.authorizationList);
42443
+ if (typeof request2.accessList !== "undefined")
42444
+ rpcRequest.accessList = request2.accessList;
42445
+ if (typeof request2.blobVersionedHashes !== "undefined")
42446
+ rpcRequest.blobVersionedHashes = request2.blobVersionedHashes;
42447
+ if (typeof request2.blobs !== "undefined") {
42448
+ if (typeof request2.blobs[0] !== "string")
42449
+ rpcRequest.blobs = request2.blobs.map((x2) => bytesToHex(x2));
42353
42450
  else
42354
- rpcRequest.blobs = request.blobs;
42355
- }
42356
- if (typeof request.data !== "undefined")
42357
- rpcRequest.data = request.data;
42358
- if (request.account)
42359
- rpcRequest.from = request.account.address;
42360
- if (typeof request.from !== "undefined")
42361
- rpcRequest.from = request.from;
42362
- if (typeof request.gas !== "undefined")
42363
- rpcRequest.gas = numberToHex(request.gas);
42364
- if (typeof request.gasPrice !== "undefined")
42365
- rpcRequest.gasPrice = numberToHex(request.gasPrice);
42366
- if (typeof request.maxFeePerBlobGas !== "undefined")
42367
- rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas);
42368
- if (typeof request.maxFeePerGas !== "undefined")
42369
- rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas);
42370
- if (typeof request.maxPriorityFeePerGas !== "undefined")
42371
- rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas);
42372
- if (typeof request.nonce !== "undefined")
42373
- rpcRequest.nonce = numberToHex(request.nonce);
42374
- if (typeof request.to !== "undefined")
42375
- rpcRequest.to = request.to;
42376
- if (typeof request.type !== "undefined")
42377
- rpcRequest.type = rpcTransactionType[request.type];
42378
- if (typeof request.value !== "undefined")
42379
- rpcRequest.value = numberToHex(request.value);
42451
+ rpcRequest.blobs = request2.blobs;
42452
+ }
42453
+ if (typeof request2.data !== "undefined")
42454
+ rpcRequest.data = request2.data;
42455
+ if (request2.account)
42456
+ rpcRequest.from = request2.account.address;
42457
+ if (typeof request2.from !== "undefined")
42458
+ rpcRequest.from = request2.from;
42459
+ if (typeof request2.gas !== "undefined")
42460
+ rpcRequest.gas = numberToHex(request2.gas);
42461
+ if (typeof request2.gasPrice !== "undefined")
42462
+ rpcRequest.gasPrice = numberToHex(request2.gasPrice);
42463
+ if (typeof request2.maxFeePerBlobGas !== "undefined")
42464
+ rpcRequest.maxFeePerBlobGas = numberToHex(request2.maxFeePerBlobGas);
42465
+ if (typeof request2.maxFeePerGas !== "undefined")
42466
+ rpcRequest.maxFeePerGas = numberToHex(request2.maxFeePerGas);
42467
+ if (typeof request2.maxPriorityFeePerGas !== "undefined")
42468
+ rpcRequest.maxPriorityFeePerGas = numberToHex(request2.maxPriorityFeePerGas);
42469
+ if (typeof request2.nonce !== "undefined")
42470
+ rpcRequest.nonce = numberToHex(request2.nonce);
42471
+ if (typeof request2.to !== "undefined")
42472
+ rpcRequest.to = request2.to;
42473
+ if (typeof request2.type !== "undefined")
42474
+ rpcRequest.type = rpcTransactionType[request2.type];
42475
+ if (typeof request2.value !== "undefined")
42476
+ rpcRequest.value = numberToHex(request2.value);
42380
42477
  return rpcRequest;
42381
42478
  }
42382
42479
  function formatAuthorizationList(authorizationList) {
@@ -42798,7 +42895,7 @@ async function estimateMaxPriorityFeePerGas(client, args) {
42798
42895
  return internal_estimateMaxPriorityFeePerGas(client, args);
42799
42896
  }
42800
42897
  async function internal_estimateMaxPriorityFeePerGas(client, args) {
42801
- const { block: block_, chain = client.chain, request } = args || {};
42898
+ const { block: block_, chain = client.chain, request: request2 } = args || {};
42802
42899
  try {
42803
42900
  const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee;
42804
42901
  if (typeof maxPriorityFeePerGas === "function") {
@@ -42806,7 +42903,7 @@ async function internal_estimateMaxPriorityFeePerGas(client, args) {
42806
42903
  const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({
42807
42904
  block,
42808
42905
  client,
42809
- request
42906
+ request: request2
42810
42907
  });
42811
42908
  if (maxPriorityFeePerGas_ === null)
42812
42909
  throw new Error();
@@ -42846,13 +42943,13 @@ async function estimateFeesPerGas(client, args) {
42846
42943
  return internal_estimateFeesPerGas(client, args);
42847
42944
  }
42848
42945
  async function internal_estimateFeesPerGas(client, args) {
42849
- const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {};
42946
+ const { block: block_, chain = client.chain, request: request2, type = "eip1559" } = args || {};
42850
42947
  const baseFeeMultiplier = await (async () => {
42851
42948
  if (typeof chain?.fees?.baseFeeMultiplier === "function")
42852
42949
  return chain.fees.baseFeeMultiplier({
42853
42950
  block: block_,
42854
42951
  client,
42855
- request
42952
+ request: request2
42856
42953
  });
42857
42954
  return chain?.fees?.baseFeeMultiplier ?? 1.2;
42858
42955
  })();
@@ -42867,7 +42964,7 @@ async function internal_estimateFeesPerGas(client, args) {
42867
42964
  block: block_,
42868
42965
  client,
42869
42966
  multiply,
42870
- request,
42967
+ request: request2,
42871
42968
  type
42872
42969
  });
42873
42970
  if (fees !== null)
@@ -42876,19 +42973,19 @@ async function internal_estimateFeesPerGas(client, args) {
42876
42973
  if (type === "eip1559") {
42877
42974
  if (typeof block.baseFeePerGas !== "bigint")
42878
42975
  throw new Eip1559FeesNotSupportedError();
42879
- const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, {
42976
+ const maxPriorityFeePerGas = typeof request2?.maxPriorityFeePerGas === "bigint" ? request2.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, {
42880
42977
  block,
42881
42978
  chain,
42882
- request
42979
+ request: request2
42883
42980
  });
42884
42981
  const baseFeePerGas = multiply(block.baseFeePerGas);
42885
- const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas;
42982
+ const maxFeePerGas = request2?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas;
42886
42983
  return {
42887
42984
  maxFeePerGas,
42888
42985
  maxPriorityFeePerGas
42889
42986
  };
42890
42987
  }
42891
- const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({}));
42988
+ const gasPrice = request2?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({}));
42892
42989
  return {
42893
42990
  gasPrice
42894
42991
  };
@@ -43253,7 +43350,7 @@ async function fillTransaction(client, parameters) {
43253
43350
  assertRequest(parameters);
43254
43351
  const chainFormat = chain?.formatters?.transactionRequest?.format;
43255
43352
  const format3 = chainFormat || formatTransactionRequest;
43256
- const request = format3({
43353
+ const request2 = format3({
43257
43354
  // Pick out extra data that might exist on the chain's transaction request type.
43258
43355
  ...extract(rest, { format: chainFormat }),
43259
43356
  account: account ? parseAccount(account) : void 0,
@@ -43275,7 +43372,7 @@ async function fillTransaction(client, parameters) {
43275
43372
  try {
43276
43373
  const response = await client.request({
43277
43374
  method: "eth_fillTransaction",
43278
- params: [request]
43375
+ params: [request2]
43279
43376
  });
43280
43377
  const format4 = chain?.formatters?.transaction?.format || formatTransaction;
43281
43378
  const transaction2 = format4(response.tx);
@@ -43324,7 +43421,7 @@ async function fillTransaction(client, parameters) {
43324
43421
  return {
43325
43422
  raw: response.raw,
43326
43423
  transaction: {
43327
- from: request.from,
43424
+ from: request2.from,
43328
43425
  ...transaction2
43329
43426
  },
43330
43427
  ...response.capabilities ? { capabilities: response.capabilities } : {}
@@ -43353,10 +43450,10 @@ var init_fillTransaction = __esm({
43353
43450
 
43354
43451
  // ../../node_modules/.pnpm/viem@2.55.15_bufferutil@4.1_ce20031be19c56210207d462110a7a29/node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js
43355
43452
  async function prepareTransactionRequest(client, args) {
43356
- let request = args;
43357
- request.account ??= client.account;
43358
- request.parameters ??= defaultParameters;
43359
- const { account: account_, chain = client.chain, nonceManager, parameters } = request;
43453
+ let request2 = args;
43454
+ request2.account ??= client.account;
43455
+ request2.parameters ??= defaultParameters;
43456
+ const { account: account_, chain = client.chain, nonceManager, parameters } = request2;
43360
43457
  const prepareTransactionRequest2 = (() => {
43361
43458
  if (typeof chain?.prepareTransactionRequest === "function")
43362
43459
  return {
@@ -43374,8 +43471,8 @@ async function prepareTransactionRequest(client, args) {
43374
43471
  async function getChainId2() {
43375
43472
  if (chainId)
43376
43473
  return chainId;
43377
- if (typeof request.chainId !== "undefined")
43378
- return request.chainId;
43474
+ if (typeof request2.chainId !== "undefined")
43475
+ return request2.chainId;
43379
43476
  if (chain)
43380
43477
  return chain.id;
43381
43478
  const chainId_ = await getAction(client, getChainId, "getChainId")({});
@@ -43383,14 +43480,14 @@ async function prepareTransactionRequest(client, args) {
43383
43480
  return chainId;
43384
43481
  }
43385
43482
  let account = account_ ? parseAccount(account_) : account_;
43386
- let nonce = request.nonce;
43483
+ let nonce = request2.nonce;
43387
43484
  if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillTransaction")) {
43388
- request = await prepareTransactionRequest2.fn({ ...request, chain }, {
43485
+ request2 = await prepareTransactionRequest2.fn({ ...request2, chain }, {
43389
43486
  client,
43390
43487
  phase: "beforeFillTransaction"
43391
43488
  });
43392
- nonce ??= request.nonce;
43393
- const sender = request.account ?? request.from;
43489
+ nonce ??= request2.nonce;
43490
+ const sender = request2.account ?? request2.from;
43394
43491
  account = sender ? parseAccount(sender) : void 0;
43395
43492
  }
43396
43493
  if (parameters.includes("nonce") && typeof nonce === "undefined" && account && nonceManager) {
@@ -43402,44 +43499,44 @@ async function prepareTransactionRequest(client, args) {
43402
43499
  });
43403
43500
  }
43404
43501
  const attemptFill = (() => {
43405
- if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && request.kzg && request.blobs)
43502
+ if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && request2.kzg && request2.blobs)
43406
43503
  return false;
43407
- if (parameters.length > 0 && "feePayer" in request && request.feePayer && !("feePayerSignature" in request && request.feePayerSignature))
43504
+ if (parameters.length > 0 && "feePayer" in request2 && request2.feePayer && !("feePayerSignature" in request2 && request2.feePayerSignature))
43408
43505
  return true;
43409
43506
  if (supportsFillTransaction.get(client.uid) === false)
43410
43507
  return false;
43411
43508
  const shouldAttempt = ["fees", "gas"].some((parameter) => parameters.includes(parameter));
43412
43509
  if (!shouldAttempt)
43413
43510
  return false;
43414
- if (parameters.includes("chainId") && typeof request.chainId !== "number")
43511
+ if (parameters.includes("chainId") && typeof request2.chainId !== "number")
43415
43512
  return true;
43416
43513
  if (parameters.includes("nonce") && typeof nonce !== "number")
43417
43514
  return true;
43418
- if (parameters.includes("fees") && typeof request.gasPrice !== "bigint" && (typeof request.maxFeePerGas !== "bigint" || typeof request.maxPriorityFeePerGas !== "bigint"))
43515
+ if (parameters.includes("fees") && typeof request2.gasPrice !== "bigint" && (typeof request2.maxFeePerGas !== "bigint" || typeof request2.maxPriorityFeePerGas !== "bigint"))
43419
43516
  return true;
43420
- if (parameters.includes("gas") && typeof request.gas !== "bigint")
43517
+ if (parameters.includes("gas") && typeof request2.gas !== "bigint")
43421
43518
  return true;
43422
43519
  return false;
43423
43520
  })();
43424
- const fillResult = attemptFill ? await getAction(client, fillTransaction, "fillTransaction")({ ...request, nonce }).then((result2) => {
43521
+ const fillResult = attemptFill ? await getAction(client, fillTransaction, "fillTransaction")({ ...request2, nonce }).then((result2) => {
43425
43522
  const { chainId: chainId2, from: from16, gas: gas2, gasPrice, nonce: nonce2, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, type: type2, ...rest } = result2.transaction;
43426
43523
  const feeToken = "feeToken" in rest ? rest.feeToken : void 0;
43427
43524
  const hasFilledFeePayerSignature = "feePayerSignature" in rest && rest.feePayerSignature !== null && typeof rest.feePayerSignature !== "undefined";
43428
- const shouldUseFilledFeeToken = typeof feeToken !== "undefined" && feeToken !== null && (!("feeToken" in request) || hasFilledFeePayerSignature);
43525
+ const shouldUseFilledFeeToken = typeof feeToken !== "undefined" && feeToken !== null && (!("feeToken" in request2) || hasFilledFeePayerSignature);
43429
43526
  supportsFillTransaction.set(client.uid, true);
43430
43527
  return {
43431
- ...request,
43528
+ ...request2,
43432
43529
  ...from16 ? { from: from16 } : {},
43433
- ...type2 && !request.type ? { type: type2 } : {},
43530
+ ...type2 && !request2.type ? { type: type2 } : {},
43434
43531
  ...typeof chainId2 !== "undefined" ? { chainId: chainId2 } : {},
43435
43532
  ...typeof gas2 !== "undefined" ? { gas: gas2 } : {},
43436
43533
  ...typeof gasPrice !== "undefined" ? { gasPrice } : {},
43437
43534
  ...typeof nonce2 !== "undefined" ? { nonce: nonce2 } : {},
43438
- ...typeof maxFeePerBlobGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerBlobGas } : {},
43439
- ...typeof maxFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerGas } : {},
43440
- ...typeof maxPriorityFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxPriorityFeePerGas } : {},
43535
+ ...typeof maxFeePerBlobGas !== "undefined" && request2.type !== "legacy" && request2.type !== "eip2930" ? { maxFeePerBlobGas } : {},
43536
+ ...typeof maxFeePerGas !== "undefined" && request2.type !== "legacy" && request2.type !== "eip2930" ? { maxFeePerGas } : {},
43537
+ ...typeof maxPriorityFeePerGas !== "undefined" && request2.type !== "legacy" && request2.type !== "eip2930" ? { maxPriorityFeePerGas } : {},
43441
43538
  ..."nonceKey" in rest && typeof rest.nonceKey !== "undefined" ? { nonceKey: rest.nonceKey } : {},
43442
- ..."keyAuthorization" in rest && typeof rest.keyAuthorization !== "undefined" && rest.keyAuthorization !== null && !("keyAuthorization" in request) ? { keyAuthorization: rest.keyAuthorization } : {},
43539
+ ..."keyAuthorization" in rest && typeof rest.keyAuthorization !== "undefined" && rest.keyAuthorization !== null && !("keyAuthorization" in request2) ? { keyAuthorization: rest.keyAuthorization } : {},
43443
43540
  ..."feePayerSignature" in rest && typeof rest.feePayerSignature !== "undefined" && rest.feePayerSignature !== null ? { feePayerSignature: rest.feePayerSignature } : {},
43444
43541
  ...shouldUseFilledFeeToken ? { feeToken } : {},
43445
43542
  ...result2.capabilities ? { _capabilities: result2.capabilities } : {}
@@ -43447,7 +43544,7 @@ async function prepareTransactionRequest(client, args) {
43447
43544
  }).catch((e) => {
43448
43545
  const error51 = e;
43449
43546
  if (error51.name !== "TransactionExecutionError")
43450
- return request;
43547
+ return request2;
43451
43548
  const executionReverted = error51.walk?.((e2) => {
43452
43549
  const error52 = e2;
43453
43550
  return error52.name === "ExecutionRevertedError";
@@ -43460,17 +43557,17 @@ async function prepareTransactionRequest(client, args) {
43460
43557
  });
43461
43558
  if (unsupported)
43462
43559
  supportsFillTransaction.set(client.uid, false);
43463
- return request;
43464
- }) : request;
43560
+ return request2;
43561
+ }) : request2;
43465
43562
  nonce ??= fillResult.nonce;
43466
- request = {
43563
+ request2 = {
43467
43564
  ...fillResult,
43468
43565
  ...account ? { from: account?.address } : {},
43469
43566
  ...typeof nonce !== "undefined" ? { nonce } : {}
43470
43567
  };
43471
- const { blobs, gas, kzg, type } = request;
43568
+ const { blobs, gas, kzg, type } = request2;
43472
43569
  if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillParameters")) {
43473
- request = await prepareTransactionRequest2.fn({ ...request, chain }, {
43570
+ request2 = await prepareTransactionRequest2.fn({ ...request2, chain }, {
43474
43571
  client,
43475
43572
  phase: "beforeFillParameters"
43476
43573
  });
@@ -43483,7 +43580,7 @@ async function prepareTransactionRequest(client, args) {
43483
43580
  return block;
43484
43581
  }
43485
43582
  if (parameters.includes("nonce") && typeof nonce === "undefined" && account && !nonceManager)
43486
- request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
43583
+ request2.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
43487
43584
  address: account.address,
43488
43585
  blockTag: "pending"
43489
43586
  });
@@ -43494,7 +43591,7 @@ async function prepareTransactionRequest(client, args) {
43494
43591
  commitments,
43495
43592
  to: "hex"
43496
43593
  });
43497
- request.blobVersionedHashes = versionedHashes;
43594
+ request2.blobVersionedHashes = versionedHashes;
43498
43595
  }
43499
43596
  if (parameters.includes("sidecars")) {
43500
43597
  const proofs = blobsToProofs({ blobs, commitments, kzg });
@@ -43504,14 +43601,14 @@ async function prepareTransactionRequest(client, args) {
43504
43601
  proofs,
43505
43602
  to: "hex"
43506
43603
  });
43507
- request.sidecars = sidecars;
43604
+ request2.sidecars = sidecars;
43508
43605
  }
43509
43606
  }
43510
43607
  if (parameters.includes("chainId"))
43511
- request.chainId = await getChainId2();
43608
+ request2.chainId = await getChainId2();
43512
43609
  if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") {
43513
43610
  try {
43514
- request.type = getTransactionType(request);
43611
+ request2.type = getTransactionType(request2);
43515
43612
  } catch {
43516
43613
  let isEip1559Network = eip1559NetworkCache.get(client.uid);
43517
43614
  if (typeof isEip1559Network === "undefined") {
@@ -43519,54 +43616,54 @@ async function prepareTransactionRequest(client, args) {
43519
43616
  isEip1559Network = typeof block2?.baseFeePerGas === "bigint";
43520
43617
  eip1559NetworkCache.set(client.uid, isEip1559Network);
43521
43618
  }
43522
- request.type = isEip1559Network ? "eip1559" : "legacy";
43619
+ request2.type = isEip1559Network ? "eip1559" : "legacy";
43523
43620
  }
43524
43621
  }
43525
43622
  if (parameters.includes("fees")) {
43526
- if (request.type !== "legacy" && request.type !== "eip2930") {
43527
- if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") {
43623
+ if (request2.type !== "legacy" && request2.type !== "eip2930") {
43624
+ if (typeof request2.maxFeePerGas === "undefined" || typeof request2.maxPriorityFeePerGas === "undefined") {
43528
43625
  const block2 = await getBlock2();
43529
43626
  const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, {
43530
43627
  block: block2,
43531
43628
  chain,
43532
- request
43629
+ request: request2
43533
43630
  });
43534
- if (typeof request.maxPriorityFeePerGas === "undefined" && request.maxFeePerGas && request.maxFeePerGas < maxPriorityFeePerGas)
43631
+ if (typeof request2.maxPriorityFeePerGas === "undefined" && request2.maxFeePerGas && request2.maxFeePerGas < maxPriorityFeePerGas)
43535
43632
  throw new MaxFeePerGasTooLowError({
43536
43633
  maxPriorityFeePerGas
43537
43634
  });
43538
- request.maxPriorityFeePerGas = maxPriorityFeePerGas;
43539
- request.maxFeePerGas = maxFeePerGas;
43635
+ request2.maxPriorityFeePerGas = maxPriorityFeePerGas;
43636
+ request2.maxFeePerGas = maxFeePerGas;
43540
43637
  }
43541
43638
  } else {
43542
- if (typeof request.maxFeePerGas !== "undefined" || typeof request.maxPriorityFeePerGas !== "undefined")
43639
+ if (typeof request2.maxFeePerGas !== "undefined" || typeof request2.maxPriorityFeePerGas !== "undefined")
43543
43640
  throw new Eip1559FeesNotSupportedError();
43544
- if (typeof request.gasPrice === "undefined") {
43641
+ if (typeof request2.gasPrice === "undefined") {
43545
43642
  const block2 = await getBlock2();
43546
43643
  const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, {
43547
43644
  block: block2,
43548
43645
  chain,
43549
- request,
43646
+ request: request2,
43550
43647
  type: "legacy"
43551
43648
  });
43552
- request.gasPrice = gasPrice_;
43649
+ request2.gasPrice = gasPrice_;
43553
43650
  }
43554
43651
  }
43555
43652
  }
43556
43653
  if (parameters.includes("gas") && typeof gas === "undefined")
43557
- request.gas = await getAction(client, estimateGas, "estimateGas")({
43558
- ...request,
43654
+ request2.gas = await getAction(client, estimateGas, "estimateGas")({
43655
+ ...request2,
43559
43656
  account,
43560
43657
  prepare: account?.type === "local" ? [] : ["blobVersionedHashes"]
43561
43658
  });
43562
43659
  if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("afterFillParameters"))
43563
- request = await prepareTransactionRequest2.fn({ ...request, chain }, {
43660
+ request2 = await prepareTransactionRequest2.fn({ ...request2, chain }, {
43564
43661
  client,
43565
43662
  phase: "afterFillParameters"
43566
43663
  });
43567
- assertRequest(request);
43568
- delete request.parameters;
43569
- return request;
43664
+ assertRequest(request2);
43665
+ delete request2.parameters;
43666
+ return request2;
43570
43667
  }
43571
43668
  var defaultParameters, eip1559NetworkCache, supportsFillTransaction;
43572
43669
  var init_prepareTransactionRequest = __esm({
@@ -43636,7 +43733,7 @@ async function estimateGas(client, args) {
43636
43733
  assertRequest(args);
43637
43734
  const chainFormat = client.chain?.formatters?.transactionRequest?.format;
43638
43735
  const format3 = chainFormat || formatTransactionRequest;
43639
- const request = format3({
43736
+ const request2 = format3({
43640
43737
  // Pick out extra data that might exist on the chain's transaction request type.
43641
43738
  ...extract(rest, { format: chainFormat }),
43642
43739
  account,
@@ -43656,10 +43753,10 @@ async function estimateGas(client, args) {
43656
43753
  return BigInt(await client.request({
43657
43754
  method: "eth_estimateGas",
43658
43755
  params: rpcStateOverride ? [
43659
- request,
43756
+ request2,
43660
43757
  block ?? client.experimental_blockTag ?? "latest",
43661
43758
  rpcStateOverride
43662
- ] : block ? [request, block] : [request]
43759
+ ] : block ? [request2, block] : [request2]
43663
43760
  }));
43664
43761
  } catch (err2) {
43665
43762
  throw getEstimateGasError(err2, {
@@ -43686,7 +43783,7 @@ var init_estimateGas2 = __esm({
43686
43783
 
43687
43784
  // ../../node_modules/.pnpm/viem@2.55.15_bufferutil@4.1_ce20031be19c56210207d462110a7a29/node_modules/viem/_esm/actions/public/estimateContractGas.js
43688
43785
  async function estimateContractGas(client, parameters) {
43689
- const { abi: abi2, address: address2, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request } = parameters;
43786
+ const { abi: abi2, address: address2, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request2 } = parameters;
43690
43787
  const data = encodeFunctionData({
43691
43788
  abi: abi2,
43692
43789
  args,
@@ -43696,11 +43793,11 @@ async function estimateContractGas(client, parameters) {
43696
43793
  const gas = await getAction(client, estimateGas, "estimateGas")({
43697
43794
  data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
43698
43795
  to: address2,
43699
- ...request
43796
+ ...request2
43700
43797
  });
43701
43798
  return gas;
43702
43799
  } catch (error51) {
43703
- const account = request.account ? parseAccount(request.account) : void 0;
43800
+ const account = request2.account ? parseAccount(request2.account) : void 0;
43704
43801
  throw getContractError(error51, {
43705
43802
  abi: abi2,
43706
43803
  address: address2,
@@ -45970,7 +46067,7 @@ async function call(client, args) {
45970
46067
  const rpcStateOverride = serializeStateOverride(stateOverride);
45971
46068
  const chainFormat = client.chain?.formatters?.transactionRequest?.format;
45972
46069
  const format3 = chainFormat || formatTransactionRequest;
45973
- const request = format3({
46070
+ const request2 = format3({
45974
46071
  // Pick out extra data that might exist on the chain's transaction request type.
45975
46072
  ...extract(rest, { format: chainFormat }),
45976
46073
  accessList,
@@ -45987,7 +46084,7 @@ async function call(client, args) {
45987
46084
  to: deploylessCall ? void 0 : to,
45988
46085
  value
45989
46086
  }, "call");
45990
- if (batch && shouldPerformMulticall({ request }) && !rpcBlockOverrides && blockHash === void 0) {
46087
+ if (batch && shouldPerformMulticall({ request: request2 }) && !rpcBlockOverrides && blockHash === void 0) {
45991
46088
  try {
45992
46089
  const { deployless = false } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {};
45993
46090
  const multicallAddress = getMulticallAddress(client, {
@@ -45996,7 +46093,7 @@ async function call(client, args) {
45996
46093
  });
45997
46094
  if (!multicallAddress || !hasStateOverrideForAddress(rpcStateOverride, multicallAddress))
45998
46095
  return await scheduleMulticall(client, {
45999
- ...request,
46096
+ ...request2,
46000
46097
  blockHash,
46001
46098
  blockNumber: blockNumber2,
46002
46099
  blockTag,
@@ -46012,7 +46109,7 @@ async function call(client, args) {
46012
46109
  }
46013
46110
  const params = (() => {
46014
46111
  const base3 = [
46015
- request,
46112
+ request2,
46016
46113
  block
46017
46114
  ];
46018
46115
  if (rpcStateOverride && rpcBlockOverrides)
@@ -46050,8 +46147,8 @@ async function call(client, args) {
46050
46147
  });
46051
46148
  }
46052
46149
  }
46053
- function shouldPerformMulticall({ request }) {
46054
- const { data, to, ...request_ } = request;
46150
+ function shouldPerformMulticall({ request: request2 }) {
46151
+ const { data, to, ...request_ } = request2;
46055
46152
  if (!data)
46056
46153
  return false;
46057
46154
  if (data.startsWith(aggregate3Signature))
@@ -46095,10 +46192,10 @@ async function scheduleMulticall(client, args) {
46095
46192
  return size5 > batchSize * 2;
46096
46193
  },
46097
46194
  fn: async (requests) => {
46098
- const calls = requests.map((request) => ({
46195
+ const calls = requests.map((request2) => ({
46099
46196
  allowFailure: true,
46100
- callData: request.data,
46101
- target: request.to
46197
+ callData: request2.data,
46198
+ target: request2.to
46102
46199
  }));
46103
46200
  const calldata = encodeFunctionData({
46104
46201
  abi: multicall3Abi,
@@ -46790,7 +46887,7 @@ async function sendTransaction(client, parameters) {
46790
46887
  }
46791
46888
  const chainFormat = client.chain?.formatters?.transactionRequest?.format;
46792
46889
  const format3 = chainFormat || formatTransactionRequest;
46793
- const request = format3({
46890
+ const request2 = format3({
46794
46891
  // Pick out extra data that might exist on the chain's transaction request type.
46795
46892
  ...extract(rest, { format: chainFormat }),
46796
46893
  accessList,
@@ -46814,7 +46911,7 @@ async function sendTransaction(client, parameters) {
46814
46911
  try {
46815
46912
  return await client.request({
46816
46913
  method: method2,
46817
- params: [request]
46914
+ params: [request2]
46818
46915
  }, { retryCount: 0 });
46819
46916
  } catch (e) {
46820
46917
  if (isWalletNamespaceSupported === false)
@@ -46823,7 +46920,7 @@ async function sendTransaction(client, parameters) {
46823
46920
  if (error51.name === "InvalidInputRpcError" || error51.name === "InvalidParamsRpcError" || error51.name === "MethodNotFoundRpcError" || error51.name === "MethodNotSupportedRpcError") {
46824
46921
  return await client.request({
46825
46922
  method: "wallet_sendTransaction",
46826
- params: [request]
46923
+ params: [request2]
46827
46924
  }, { retryCount: 0 }).then((hash5) => {
46828
46925
  supportsWalletNamespace.set(client.uid, true);
46829
46926
  return hash5;
@@ -46863,7 +46960,7 @@ async function sendTransaction(client, parameters) {
46863
46960
  }
46864
46961
  };
46865
46962
  })();
46866
- const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({
46963
+ const request2 = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({
46867
46964
  account,
46868
46965
  accessList,
46869
46966
  authorizationList,
@@ -46884,7 +46981,7 @@ async function sendTransaction(client, parameters) {
46884
46981
  to
46885
46982
  });
46886
46983
  const serializer = chain?.serializers?.transaction;
46887
- const serializedTransaction = await account.signTransaction(request, {
46984
+ const serializedTransaction = await account.signTransaction(request2, {
46888
46985
  serializer
46889
46986
  });
46890
46987
  return await getAction(client, sendRawTransaction, "sendRawTransaction")({
@@ -46951,7 +47048,7 @@ var init_writeContract = __esm({
46951
47048
  init_sendTransaction();
46952
47049
  (function(writeContract2) {
46953
47050
  async function internal(client, actionFn, name, parameters) {
46954
- const { abi: abi2, account: account_ = client.account, address: address2, args, functionName, ...request } = parameters;
47051
+ const { abi: abi2, account: account_ = client.account, address: address2, args, functionName, ...request2 } = parameters;
46955
47052
  if (typeof account_ === "undefined")
46956
47053
  throw new AccountNotFoundError({
46957
47054
  docsPath: "/docs/contract/writeContract"
@@ -46967,7 +47064,7 @@ var init_writeContract = __esm({
46967
47064
  data,
46968
47065
  to: address2,
46969
47066
  account,
46970
- ...request
47067
+ ...request2
46971
47068
  });
46972
47069
  } catch (error51) {
46973
47070
  throw getContractError(error51, {
@@ -47393,7 +47490,7 @@ function createClient(parameters) {
47393
47490
  const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval;
47394
47491
  const cacheTime = parameters.cacheTime ?? pollingInterval;
47395
47492
  const account = parameters.account ? parseAccount(parameters.account) : void 0;
47396
- const { config: config2, request, value } = parameters.transport({
47493
+ const { config: config2, request: request2, value } = parameters.transport({
47397
47494
  account,
47398
47495
  chain,
47399
47496
  pollingInterval
@@ -47409,7 +47506,7 @@ function createClient(parameters) {
47409
47506
  key,
47410
47507
  name,
47411
47508
  pollingInterval,
47412
- request,
47509
+ request: request2,
47413
47510
  tokens,
47414
47511
  transport,
47415
47512
  type,
@@ -48144,7 +48241,7 @@ async function createAccessList(client, args) {
48144
48241
  const block = blockNumberHex || blockTag;
48145
48242
  const chainFormat = client.chain?.formatters?.transactionRequest?.format;
48146
48243
  const format3 = chainFormat || formatTransactionRequest;
48147
- const request = format3({
48244
+ const request2 = format3({
48148
48245
  // Pick out extra data that might exist on the chain's transaction request type.
48149
48246
  ...extract(rest, { format: chainFormat }),
48150
48247
  account,
@@ -48160,7 +48257,7 @@ async function createAccessList(client, args) {
48160
48257
  }, "createAccessList");
48161
48258
  const response = await client.request({
48162
48259
  method: "eth_createAccessList",
48163
- params: [request, block]
48260
+ params: [request2, block]
48164
48261
  });
48165
48262
  if (response.error)
48166
48263
  throw new BaseError2(response.error, { details: response.error });
@@ -48937,7 +49034,7 @@ var init_withDedupe = __esm({
48937
49034
  });
48938
49035
 
48939
49036
  // ../../node_modules/.pnpm/viem@2.55.15_bufferutil@4.1_ce20031be19c56210207d462110a7a29/node_modules/viem/_esm/utils/buildRequest.js
48940
- function buildRequest(request, options = {}) {
49037
+ function buildRequest(request2, options = {}) {
48941
49038
  return async (args, overrideOptions = {}) => {
48942
49039
  const { dedupe = false, methods, retryDelay = 150, retryCount = 3, signal, uid: uid2 } = {
48943
49040
  ...options,
@@ -48957,7 +49054,7 @@ function buildRequest(request, options = {}) {
48957
49054
  const requestId = dedupe ? hashString(`${uid2}.${stringify(args)}`) : void 0;
48958
49055
  return withDedupe(() => withRetry(async () => {
48959
49056
  try {
48960
- return await request(args, signal ? { signal } : void 0);
49057
+ return await request2(args, signal ? { signal } : void 0);
48961
49058
  } catch (err_) {
48962
49059
  if (signal?.aborted)
48963
49060
  throw getAbortError(signal);
@@ -49243,8 +49340,8 @@ function getHttpRpcClient(url_, options = {}) {
49243
49340
  method: method2 || "POST",
49244
49341
  signal: signal_ || (timeout > 0 ? signal : null)
49245
49342
  };
49246
- const request = new Request(url2, init);
49247
- const args = await onRequest?.(request, init) ?? { ...init, url: url2 };
49343
+ const request2 = new Request(url2, init);
49344
+ const args = await onRequest?.(request2, init) ?? { ...init, url: url2 };
49248
49345
  const response2 = await fetchFn(args.url ?? url2, args);
49249
49346
  return response2;
49250
49347
  }, {
@@ -51803,14 +51900,14 @@ async function simulateBlocks(client, parameters) {
51803
51900
  const call2 = call_;
51804
51901
  const account = call2.account ? parseAccount(call2.account) : void 0;
51805
51902
  const data = call2.abi ? encodeFunctionData(call2) : call2.data;
51806
- const request = {
51903
+ const request2 = {
51807
51904
  ...call2,
51808
51905
  account,
51809
51906
  data: call2.dataSuffix ? concat2([data || "0x", call2.dataSuffix]) : data,
51810
51907
  from: call2.from ?? account?.address
51811
51908
  };
51812
- assertRequest(request);
51813
- return formatTransactionRequest(request);
51909
+ assertRequest(request2);
51910
+ return formatTransactionRequest(request2);
51814
51911
  });
51815
51912
  const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : void 0;
51816
51913
  blockStateCalls.push({
@@ -53882,7 +53979,7 @@ async function sendTransactionSync(client, parameters) {
53882
53979
  }
53883
53980
  const chainFormat = client.chain?.formatters?.transactionRequest?.format;
53884
53981
  const format3 = chainFormat || formatTransactionRequest;
53885
- const request = format3({
53982
+ const request2 = format3({
53886
53983
  // Pick out extra data that might exist on the chain's transaction request type.
53887
53984
  ...extract(rest, { format: chainFormat }),
53888
53985
  accessList,
@@ -53907,7 +54004,7 @@ async function sendTransactionSync(client, parameters) {
53907
54004
  try {
53908
54005
  return await client.request({
53909
54006
  method: method2,
53910
- params: [request]
54007
+ params: [request2]
53911
54008
  }, { retryCount: 0 });
53912
54009
  } catch (e) {
53913
54010
  if (isWalletNamespaceSupported === false)
@@ -53916,7 +54013,7 @@ async function sendTransactionSync(client, parameters) {
53916
54013
  if (error51.name === "InvalidInputRpcError" || error51.name === "InvalidParamsRpcError" || error51.name === "MethodNotFoundRpcError" || error51.name === "MethodNotSupportedRpcError") {
53917
54014
  return await client.request({
53918
54015
  method: "wallet_sendTransaction",
53919
- params: [request]
54016
+ params: [request2]
53920
54017
  }, { retryCount: 0 }).then((hash6) => {
53921
54018
  supportsWalletNamespace2.set(client.uid, true);
53922
54019
  return hash6;
@@ -53966,7 +54063,7 @@ async function sendTransactionSync(client, parameters) {
53966
54063
  }
53967
54064
  };
53968
54065
  })();
53969
- const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({
54066
+ const request2 = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({
53970
54067
  account,
53971
54068
  accessList,
53972
54069
  authorizationList,
@@ -53987,7 +54084,7 @@ async function sendTransactionSync(client, parameters) {
53987
54084
  to
53988
54085
  });
53989
54086
  const serializer = chain?.serializers?.transaction;
53990
- const serializedTransaction = await account.signTransaction(request, {
54087
+ const serializedTransaction = await account.signTransaction(request2, {
53991
54088
  serializer
53992
54089
  });
53993
54090
  return await getAction(client, sendRawTransactionSync, "sendRawTransactionSync")({
@@ -54524,11 +54621,11 @@ var init_addChain = __esm({
54524
54621
 
54525
54622
  // ../../node_modules/.pnpm/viem@2.55.15_bufferutil@4.1_ce20031be19c56210207d462110a7a29/node_modules/viem/_esm/actions/wallet/deployContract.js
54526
54623
  function deployContract(walletClient, parameters) {
54527
- const { abi: abi2, args, bytecode, ...request } = parameters;
54624
+ const { abi: abi2, args, bytecode, ...request2 } = parameters;
54528
54625
  const calldata = encodeDeployData({ abi: abi2, args, bytecode });
54529
54626
  return sendTransaction(walletClient, {
54530
- ...request,
54531
- ...request.authorizationList ? { to: null } : {},
54627
+ ...request2,
54628
+ ...request2.authorizationList ? { to: null } : {},
54532
54629
  data: calldata
54533
54630
  });
54534
54631
  }
@@ -54951,20 +55048,20 @@ var init_createWalletClient = __esm({
54951
55048
  });
54952
55049
 
54953
55050
  // ../../node_modules/.pnpm/viem@2.55.15_bufferutil@4.1_ce20031be19c56210207d462110a7a29/node_modules/viem/_esm/clients/transports/createTransport.js
54954
- function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) {
55051
+ function createTransport({ key, methods, name, request: request2, retryCount = 3, retryDelay = 150, timeout, type }, value) {
54955
55052
  const uid2 = uid();
54956
55053
  return {
54957
55054
  config: {
54958
55055
  key,
54959
55056
  methods,
54960
55057
  name,
54961
- request,
55058
+ request: request2,
54962
55059
  retryCount,
54963
55060
  retryDelay,
54964
55061
  timeout,
54965
55062
  type
54966
55063
  },
54967
- request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }),
55064
+ request: buildRequest(request2, { methods, retryCount, retryDelay, uid: uid2 }),
54968
55065
  value
54969
55066
  };
54970
55067
  }
@@ -55350,6 +55447,7 @@ var init_api2 = __esm({
55350
55447
  "src/api.ts"() {
55351
55448
  "use strict";
55352
55449
  import_ajv = __toESM(require_ajv(), 1);
55450
+ init_package();
55353
55451
  init_cli_error();
55354
55452
  init_src2();
55355
55453
  init_v1();
@@ -55554,6 +55652,23 @@ var init_api2 = __esm({
55554
55652
  throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", null, { cause });
55555
55653
  }
55556
55654
  }
55655
+ async authorizationServerMetadata() {
55656
+ const authorizationResponse = await this.publicFetch("/.well-known/oauth-authorization-server");
55657
+ if (authorizationResponse.status !== 200) {
55658
+ await authorizationResponse.body?.cancel().catch(() => void 0);
55659
+ throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", authorizationResponse.status);
55660
+ }
55661
+ const authorization = jsonObject(await readBoundedJson(authorizationResponse));
55662
+ if (authorization.issuer !== this.origin || authorization.authorization_endpoint !== `${this.origin}/oauth/authorize` || !sameOriginEndpoint(authorization.token_endpoint, this.origin) || !sameOriginEndpoint(authorization.registration_endpoint, this.origin) || !includesCapabilities(authorization.response_types_supported, ["code"]) || !includesCapabilities(authorization.grant_types_supported, ["authorization_code", "refresh_token"]) || !includesCapabilities(authorization.token_endpoint_auth_methods_supported, ["none"]) || !includesCapabilities(authorization.code_challenge_methods_supported, ["S256"]) || !["boolean", "undefined"].includes(typeof authorization.authorization_response_iss_parameter_supported)) {
55663
+ throw new CliHttpError("CLI_RESPONSE_INVALID", authorizationResponse.status);
55664
+ }
55665
+ return authorization;
55666
+ }
55667
+ /** The issuer every authorization response must carry as `iss` (RFC 9207), or null when none is advertised. */
55668
+ async authorizationResponseIssuer() {
55669
+ const metadata = await this.authorizationServerMetadata();
55670
+ return metadata.authorization_response_iss_parameter_supported === true ? this.origin : null;
55671
+ }
55557
55672
  async inspectRemoteMcp() {
55558
55673
  const mcpUrl = `${this.origin}/mcp`;
55559
55674
  const compatibilityManifestUrl = `${this.origin}/mcp/client-compatibility.json`;
@@ -55580,15 +55695,7 @@ var init_api2 = __esm({
55580
55695
  if (resource.resource !== resourceMetadataAuthority.resource || !includesCapabilities(resource.authorization_servers, [this.origin])) {
55581
55696
  throw new CliHttpError("CLI_RESPONSE_INVALID", resourceResponse.status);
55582
55697
  }
55583
- const authorizationResponse = await this.publicFetch("/.well-known/oauth-authorization-server");
55584
- if (authorizationResponse.status !== 200) {
55585
- await authorizationResponse.body?.cancel().catch(() => void 0);
55586
- throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", authorizationResponse.status);
55587
- }
55588
- const authorization = jsonObject(await readBoundedJson(authorizationResponse));
55589
- if (authorization.issuer !== this.origin || authorization.authorization_endpoint !== `${this.origin}/oauth/authorize` || !sameOriginEndpoint(authorization.token_endpoint, this.origin) || !sameOriginEndpoint(authorization.registration_endpoint, this.origin) || !includesCapabilities(authorization.response_types_supported, ["code"]) || !includesCapabilities(authorization.grant_types_supported, ["authorization_code", "refresh_token"]) || !includesCapabilities(authorization.token_endpoint_auth_methods_supported, ["none"]) || !includesCapabilities(authorization.code_challenge_methods_supported, ["S256"])) {
55590
- throw new CliHttpError("CLI_RESPONSE_INVALID", authorizationResponse.status);
55591
- }
55698
+ await this.authorizationServerMetadata();
55592
55699
  return Object.freeze({
55593
55700
  url: mcpUrl,
55594
55701
  transport: "streamable_http",
@@ -55924,7 +56031,8 @@ var init_api2 = __esm({
55924
56031
  errorContract: "oauth",
55925
56032
  responseSchema: oauthAuthorizationResponseSchema,
55926
56033
  bearer,
55927
- body: {}
56034
+ body: {},
56035
+ headers: { [AGENT_CLI_MCP_AUTHORIZATION_CLIENT.versionHeader]: package_default.version }
55928
56036
  });
55929
56037
  }
55930
56038
  createChallenge(input) {
@@ -56645,6 +56753,84 @@ var init_skill_buyer_intent_journal = __esm({
56645
56753
  }
56646
56754
  });
56647
56755
 
56756
+ // src/loopback-callback.ts
56757
+ import { lookup } from "node:dns/promises";
56758
+ import { request } from "node:http";
56759
+ import { isIP } from "node:net";
56760
+ function isLoopbackHttpUrl(url2) {
56761
+ return url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname);
56762
+ }
56763
+ function isLoopbackAddress(address2) {
56764
+ return address2 === "::1" || /^127\./u.test(address2);
56765
+ }
56766
+ function attempt(url2, address2, port) {
56767
+ return new Promise((resolve4, reject5) => {
56768
+ let connected = false;
56769
+ const outgoing = request({
56770
+ host: address2,
56771
+ port,
56772
+ method: "GET",
56773
+ path: `${url2.pathname}${url2.search}`,
56774
+ family: isIP(address2),
56775
+ headers: { host: url2.host, connection: "close" },
56776
+ timeout: DELIVERY_TIMEOUT_MILLISECONDS
56777
+ }, (response) => {
56778
+ let received = 0;
56779
+ response.on("data", (chunk) => {
56780
+ received += chunk.byteLength;
56781
+ if (received > MAXIMUM_RESPONSE_BYTES) response.destroy();
56782
+ });
56783
+ response.on("close", () => {
56784
+ const status = response.statusCode ?? 0;
56785
+ if (status >= 200 && status < 400) resolve4("delivered");
56786
+ else reject5(new McpAuthorizationFlowError("callback_rejected", { callbackStatus: status }));
56787
+ });
56788
+ });
56789
+ outgoing.on("socket", (socket) => {
56790
+ socket.once("connect", () => {
56791
+ connected = true;
56792
+ });
56793
+ });
56794
+ outgoing.on("timeout", () => outgoing.destroy(new Error("timeout")));
56795
+ outgoing.on("error", (cause) => {
56796
+ if (!connected) resolve4("not_connected");
56797
+ else reject5(new McpAuthorizationFlowError("callback_delivery_unknown", {}, { cause }));
56798
+ });
56799
+ outgoing.end();
56800
+ });
56801
+ }
56802
+ var DELIVERY_TIMEOUT_MILLISECONDS, MAXIMUM_RESPONSE_BYTES, LoopbackCallbackDelivery;
56803
+ var init_loopback_callback = __esm({
56804
+ "src/loopback-callback.ts"() {
56805
+ "use strict";
56806
+ init_cli_error();
56807
+ DELIVERY_TIMEOUT_MILLISECONDS = 15e3;
56808
+ MAXIMUM_RESPONSE_BYTES = 65536;
56809
+ LoopbackCallbackDelivery = class {
56810
+ constructor(resolve4 = async (hostname3) => (await lookup(hostname3, { all: true, verbatim: true })).map((entry2) => entry2.address), send = attempt) {
56811
+ this.resolve = resolve4;
56812
+ this.send = send;
56813
+ }
56814
+ resolve;
56815
+ send;
56816
+ async deliver(callbackUrl) {
56817
+ const url2 = new URL(callbackUrl);
56818
+ if (!isLoopbackHttpUrl(url2)) throw new TypeError("OAuth callback is not a loopback HTTP address.");
56819
+ const addresses = url2.hostname === "localhost" ? await this.resolve("localhost") : [url2.hostname === "[::1]" ? "::1" : url2.hostname];
56820
+ const loopback = addresses.filter(isLoopbackAddress);
56821
+ if (loopback.length === 0 || loopback.length !== addresses.length) {
56822
+ throw new McpAuthorizationFlowError("callback_unreachable");
56823
+ }
56824
+ const port = url2.port === "" ? 80 : Number(url2.port);
56825
+ for (const address2 of loopback) {
56826
+ if (await this.send(url2, address2, port) === "delivered") return;
56827
+ }
56828
+ throw new McpAuthorizationFlowError("callback_unreachable");
56829
+ }
56830
+ };
56831
+ }
56832
+ });
56833
+
56648
56834
  // src/application.ts
56649
56835
  import { createHash as createHash2, randomUUID } from "node:crypto";
56650
56836
  import { open as open2 } from "node:fs/promises";
@@ -56913,7 +57099,7 @@ function parseTaskRecoveryJournal(value, expected) {
56913
57099
  idempotencyKey: journal.idempotencyKey
56914
57100
  });
56915
57101
  }
56916
- var FinchCliApplication;
57102
+ var MAXIMUM_STDIN_AUTHORIZATION_BYTES, FinchCliApplication;
56917
57103
  var init_application = __esm({
56918
57104
  "src/application.ts"() {
56919
57105
  "use strict";
@@ -56927,6 +57113,8 @@ var init_application = __esm({
56927
57113
  init_state();
56928
57114
  init_skill_buyer_intent_journal();
56929
57115
  init_cli_error();
57116
+ init_loopback_callback();
57117
+ MAXIMUM_STDIN_AUTHORIZATION_BYTES = 4098;
56930
57118
  FinchCliApplication = class {
56931
57119
  api;
56932
57120
  state;
@@ -56940,6 +57128,9 @@ var init_application = __esm({
56940
57128
  skillIntentSender;
56941
57129
  skillLocalFlow;
56942
57130
  browserLauncher;
57131
+ callbackDelivery;
57132
+ mcpLoginProcess;
57133
+ stdin;
56943
57134
  constructor(dependencies) {
56944
57135
  this.api = dependencies.api;
56945
57136
  this.state = dependencies.state;
@@ -56953,6 +57144,9 @@ var init_application = __esm({
56953
57144
  this.skillIntentSender = dependencies.skillIntentSender;
56954
57145
  this.skillLocalFlow = dependencies.skillLocalFlow;
56955
57146
  this.browserLauncher = dependencies.browserLauncher;
57147
+ this.callbackDelivery = dependencies.callbackDelivery;
57148
+ this.mcpLoginProcess = dependencies.mcpLoginProcess;
57149
+ this.stdin = dependencies.stdin;
56956
57150
  }
56957
57151
  async authorizedProfile() {
56958
57152
  return this.activeProfile ?? await required2(this.state.readProfile, "state.readProfile").call(this.state);
@@ -57155,8 +57349,8 @@ var init_application = __esm({
57155
57349
  const handoffId = this.randomUuid();
57156
57350
  const token = this.randomBearer();
57157
57351
  const tokenCommitment = `0x${createHash2("sha256").update(token, "utf8").digest("hex")}`;
57158
- const request = { handoffId, tokenCommitment };
57159
- const response = input.requestId === void 0 ? await required2(this.api.createBrowserHandoff, "api.createBrowserHandoff").call(this.api, request, input.session.rawBearer) : await required2(this.api.bindBrowserHandoff, "api.bindBrowserHandoff").call(this.api, { ...request, requestId: input.requestId }, input.session.rawBearer);
57352
+ const request2 = { handoffId, tokenCommitment };
57353
+ const response = input.requestId === void 0 ? await required2(this.api.createBrowserHandoff, "api.createBrowserHandoff").call(this.api, request2, input.session.rawBearer) : await required2(this.api.bindBrowserHandoff, "api.bindBrowserHandoff").call(this.api, { ...request2, requestId: input.requestId }, input.session.rawBearer);
57160
57354
  const bound = asObject(response, "Browser handoff");
57161
57355
  if (bound.accountId !== input.session.accountId || bound.environment !== input.session.environment || String(bound.walletAddress).toLowerCase() !== input.session.walletAddress.toLowerCase()) {
57162
57356
  throw new CliAuthorityError();
@@ -57188,19 +57382,45 @@ var init_application = __esm({
57188
57382
  const authority = await this.verifiedAgentCliAuthority();
57189
57383
  return this.openBrowserHandoff({ ...authority, requestId: match[1] });
57190
57384
  }
57385
+ /** Layer 3: the shell-safe request token shown on the Finch authorization page. */
57191
57386
  async authorizeMcp(requestToken) {
57387
+ return this.authorizeMcpRequest(decodeAgentCliMcpAuthorizationRequest(requestToken));
57388
+ }
57389
+ /** Layer 2: one raw authorization URL on standard input, which argv cannot carry intact on Windows. */
57390
+ async authorizeMcpFromStdin() {
57391
+ const input = await required2(this.stdin, "stdin").readAll(MAXIMUM_STDIN_AUTHORIZATION_BYTES);
57392
+ const requestUrl = input.replace(/\r?\n$/u, "");
57393
+ if (requestUrl.length === 0 || /\s/u.test(requestUrl)) {
57394
+ throw new McpAuthorizationFlowError("stdin_invalid");
57395
+ }
57396
+ return this.authorizeMcpRequest(requestUrl);
57397
+ }
57398
+ /** Layer 1: run the MCP client's own login command and approve the URL it prints. */
57399
+ async connectMcp(command) {
57192
57400
  const profile = await this.authorizedProfile();
57193
- const requestUrl = decodeAgentCliMcpAuthorizationRequest(requestToken);
57194
- let request;
57401
+ await this.verifiedAgentCliAuthority();
57402
+ const session = required2(this.mcpLoginProcess, "MCP login process").start(command, profile.origin);
57195
57403
  try {
57196
- request = new URL(requestUrl);
57404
+ const requestUrl = await session.authorizationUrl();
57405
+ const result2 = await this.authorizeMcpRequest(requestUrl, (code) => session.redact(code));
57406
+ await session.waitForExit();
57407
+ return Object.freeze({ ...result2, loginCommandExitCode: 0 });
57408
+ } finally {
57409
+ session.close();
57410
+ }
57411
+ }
57412
+ async authorizeMcpRequest(requestUrl, onAuthorizationCode) {
57413
+ const profile = await this.authorizedProfile();
57414
+ let request2;
57415
+ try {
57416
+ request2 = new URL(requestUrl);
57197
57417
  } catch {
57198
57418
  throw new TypeError("MCP OAuth request URL is invalid.");
57199
57419
  }
57200
- const redirectValues = request.searchParams.getAll("redirect_uri");
57201
- const stateValues = request.searchParams.getAll("state");
57202
- const scopeValues = request.searchParams.getAll("scope");
57203
- if (request.origin !== profile.origin || request.pathname !== "/oauth/authorize" || request.username !== "" || request.password !== "" || request.hash !== "" || requestUrl !== `${profile.origin}${request.pathname}${request.search}` || redirectValues.length !== 1 || stateValues.length > 1 || scopeValues.length > 1) {
57420
+ const redirectValues = request2.searchParams.getAll("redirect_uri");
57421
+ const stateValues = request2.searchParams.getAll("state");
57422
+ const scopeValues = request2.searchParams.getAll("scope");
57423
+ if (request2.origin !== profile.origin || request2.pathname !== "/oauth/authorize" || request2.username !== "" || request2.password !== "" || request2.hash !== "" || requestUrl !== `${profile.origin}${request2.pathname}${request2.search}` || redirectValues.length !== 1 || stateValues.length > 1 || scopeValues.length > 1) {
57204
57424
  throw new TypeError("MCP OAuth request URL does not match the active profile authority.");
57205
57425
  }
57206
57426
  let registeredRedirect;
@@ -57209,11 +57429,12 @@ var init_application = __esm({
57209
57429
  } catch {
57210
57430
  throw new TypeError("MCP OAuth redirect URI is invalid.");
57211
57431
  }
57212
- if (registeredRedirect.username !== "" || registeredRedirect.password !== "" || registeredRedirect.hash !== "") {
57432
+ if (registeredRedirect.username !== "" || registeredRedirect.password !== "" || registeredRedirect.hash !== "" || registeredRedirect.protocol !== "https:" && !isLoopbackHttpUrl(registeredRedirect)) {
57213
57433
  throw new TypeError("MCP OAuth redirect URI is invalid.");
57214
57434
  }
57215
57435
  const authority = await this.verifiedAgentCliAuthority();
57216
- const response = asObject(await required2(this.api.authorizeMcp, "api.authorizeMcp").call(this.api, `${request.pathname}${request.search}`, authority.session.rawBearer), "MCP authorization");
57436
+ const expectedIssuer = await required2(this.api.authorizationResponseIssuer, "api.authorizationResponseIssuer").call(this.api);
57437
+ const response = asObject(await required2(this.api.authorizeMcp, "api.authorizeMcp").call(this.api, `${request2.pathname}${request2.search}`, authority.session.rawBearer), "MCP authorization");
57217
57438
  if (response.authorized !== true || response.accountId !== authority.session.accountId || String(response.walletAddress).toLowerCase() !== authority.walletAddress || typeof response.clientName !== "string" || response.clientName.length < 1 || response.clientName.length > 128 || !Array.isArray(response.scopes) || response.scopes.some((scope) => typeof scope !== "string" || scope.length < 1) || typeof response.callbackUrl !== "string") {
57218
57439
  throw new CliAuthorityError();
57219
57440
  }
@@ -57232,23 +57453,33 @@ var init_application = __esm({
57232
57453
  if (codes.length !== 1 || codes[0].length < 1 || callback.searchParams.has("error")) {
57233
57454
  throw new TypeError("MCP OAuth callback is invalid.");
57234
57455
  }
57456
+ onAuthorizationCode?.(codes[0]);
57235
57457
  const expectedCallback = new URL(registeredRedirect.href);
57236
57458
  expectedCallback.searchParams.set("code", codes[0]);
57237
57459
  if (stateValues.length === 1) expectedCallback.searchParams.set("state", stateValues[0]);
57460
+ if (expectedIssuer !== null) expectedCallback.searchParams.set("iss", expectedIssuer);
57238
57461
  const expectedParameters = new URLSearchParams(expectedCallback.search);
57239
57462
  const callbackParameters = new URLSearchParams(callback.search);
57240
57463
  expectedParameters.sort();
57241
57464
  callbackParameters.sort();
57242
57465
  if (callback.origin !== registeredRedirect.origin || callback.pathname !== registeredRedirect.pathname || callback.protocol !== registeredRedirect.protocol || callback.username !== "" || callback.password !== "" || callback.hash !== "" || callbackParameters.toString() !== expectedParameters.toString()) {
57243
- throw new TypeError("MCP OAuth callback does not match the registered redirect and state.");
57466
+ throw new TypeError("MCP OAuth callback does not match the registered redirect, state, and issuer.");
57467
+ }
57468
+ let callbackDelivery;
57469
+ if (isLoopbackHttpUrl(callback)) {
57470
+ await required2(this.callbackDelivery, "callback delivery").deliver(callback.href);
57471
+ callbackDelivery = "loopback_http";
57472
+ } else {
57473
+ await required2(this.browserLauncher, "browser launcher").open(callback.href);
57474
+ callbackDelivery = "browser";
57244
57475
  }
57245
- await required2(this.browserLauncher, "browser launcher").open(callback.href);
57246
57476
  return Object.freeze({
57247
57477
  authorized: true,
57248
57478
  clientName: response.clientName,
57249
57479
  walletAddress: authority.walletAddress,
57250
57480
  environment: authority.session.environment,
57251
- scopes: Object.freeze([...returnedScopes])
57481
+ scopes: Object.freeze([...returnedScopes]),
57482
+ callbackDelivery
57252
57483
  });
57253
57484
  }
57254
57485
  async createWallet() {
@@ -58299,66 +58530,13 @@ var init_application = __esm({
58299
58530
  }
58300
58531
  });
58301
58532
 
58302
- // package.json
58303
- var package_default;
58304
- var init_package = __esm({
58305
- "package.json"() {
58306
- package_default = {
58307
- name: "@finchtech/cli",
58308
- version: "0.3.9",
58309
- description: "Finch Agent CLI for wallet-owned marketplace and MCP workflows.",
58310
- type: "module",
58311
- bin: {
58312
- finch: "dist/finch.js",
58313
- finchtech: "dist/finch.js"
58314
- },
58315
- files: [
58316
- "dist/finch.js",
58317
- "README.md",
58318
- "THIRD_PARTY_LICENSES.txt"
58319
- ],
58320
- engines: {
58321
- node: ">=20"
58322
- },
58323
- publishConfig: {
58324
- access: "public"
58325
- },
58326
- repository: {
58327
- type: "git",
58328
- url: "git+https://github.com/FinchipAI/Finch-Site.git",
58329
- directory: "apps/cli"
58330
- },
58331
- homepage: "https://www.finchtech.ai",
58332
- scripts: {
58333
- build: 'esbuild src/bootstrap.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/finch.js --banner:js="#!/usr/bin/env node"',
58334
- check: "pnpm lint && pnpm typecheck && pnpm test && pnpm build",
58335
- lint: "eslint src vitest.config.ts eslint.config.mjs",
58336
- prepack: "pnpm build",
58337
- test: "vitest run",
58338
- typecheck: "tsc --noEmit"
58339
- },
58340
- devDependencies: {
58341
- "@finch/agent-market-contracts": "workspace:*",
58342
- "@finch/deployment-manifest": "workspace:*",
58343
- "@finch/skill-content": "workspace:*",
58344
- "@finch/skill-market-contracts": "workspace:*",
58345
- "@finch/task-market-contracts": "workspace:*",
58346
- "@eslint/js": "9.39.2",
58347
- "@types/node": "20.19.30",
58348
- ajv: "8.20.0",
58349
- esbuild: "0.28.2",
58350
- eslint: "9.39.2",
58351
- typescript: "5.9.3",
58352
- "typescript-eslint": "8.67.0",
58353
- viem: "2.55.15",
58354
- vitest: "4.1.10"
58355
- }
58356
- };
58357
- }
58358
- });
58359
-
58360
58533
  // src/command-router.ts
58361
- function helpTopic(arguments_) {
58534
+ function finchOwnArguments(arguments_) {
58535
+ const separator = arguments_.indexOf("--");
58536
+ return separator < 0 ? arguments_ : arguments_.slice(0, separator);
58537
+ }
58538
+ function helpTopic(allArguments) {
58539
+ const arguments_ = finchOwnArguments(allArguments);
58362
58540
  if (arguments_[0] === "help" && arguments_.length > 1) return arguments_.slice(1).join(" ");
58363
58541
  if (arguments_.length > 1 && arguments_.at(-1) === "--help" && arguments_.filter((argument) => argument === "--help").length === 1) {
58364
58542
  return arguments_.slice(0, -1).join(" ");
@@ -58482,7 +58660,13 @@ async function routeCommand(arguments_, application) {
58482
58660
  if (first === "mcp" && second === "doctor" && arguments_.length === 2) {
58483
58661
  return result("mcp.doctor", await method(application.doctorMcp, "mcp doctor").call(application));
58484
58662
  }
58485
- if (first === "mcp" && second === "authorize" && arguments_.length === 3 && third !== void 0) {
58663
+ if (first === "mcp" && second === "connect" && third === "--" && arguments_.length > 3) {
58664
+ return result("mcp.connect", await method(application.connectMcp, "mcp connect").call(application, Object.freeze(arguments_.slice(3))));
58665
+ }
58666
+ if (first === "mcp" && second === "authorize" && arguments_.length === 3 && third === "--stdin") {
58667
+ return result("mcp.authorize", await method(application.authorizeMcpFromStdin, "mcp authorize").call(application));
58668
+ }
58669
+ if (first === "mcp" && second === "authorize" && arguments_.length === 3 && third !== void 0 && !third.startsWith("--")) {
58486
58670
  return result("mcp.authorize", await method(application.authorizeMcp, "mcp authorize").call(application, third));
58487
58671
  }
58488
58672
  if (first === "mcp" && second === "grant" && third === "create") {
@@ -58805,6 +58989,7 @@ var init_command_router = __esm({
58805
58989
  "site open",
58806
58990
  "site login",
58807
58991
  "mcp doctor",
58992
+ "mcp connect",
58808
58993
  "mcp authorize",
58809
58994
  "mcp grant create",
58810
58995
  "mcp grant show",
@@ -58871,7 +59056,8 @@ var init_command_router = __esm({
58871
59056
  "site open": "finch site open",
58872
59057
  "site login": "finch site login <REQUEST_URL>",
58873
59058
  "mcp doctor": "finch mcp doctor",
58874
- "mcp authorize": "finch mcp authorize <REQUEST_TOKEN>",
59059
+ "mcp connect": "finch mcp connect -- <MCP_CLIENT_LOGIN_COMMAND...>",
59060
+ "mcp authorize": "finch mcp authorize --stdin | finch mcp authorize <REQUEST_TOKEN>",
58875
59061
  "mcp grant create": "finch mcp grant create --scopes <CSV> --expires-at <ISO-8601>",
58876
59062
  "mcp grant show": "finch mcp grant show <GRANT_ID>",
58877
59063
  "mcp grant revoke": "finch mcp grant revoke <GRANT_ID>",
@@ -58927,6 +59113,735 @@ var init_command_router = __esm({
58927
59113
  }
58928
59114
  });
58929
59115
 
59116
+ // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
59117
+ var require_windows = __commonJS({
59118
+ "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
59119
+ module.exports = isexe;
59120
+ isexe.sync = sync;
59121
+ var fs = __require("fs");
59122
+ function checkPathExt(path2, options) {
59123
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
59124
+ if (!pathext) {
59125
+ return true;
59126
+ }
59127
+ pathext = pathext.split(";");
59128
+ if (pathext.indexOf("") !== -1) {
59129
+ return true;
59130
+ }
59131
+ for (var i2 = 0; i2 < pathext.length; i2++) {
59132
+ var p = pathext[i2].toLowerCase();
59133
+ if (p && path2.substr(-p.length).toLowerCase() === p) {
59134
+ return true;
59135
+ }
59136
+ }
59137
+ return false;
59138
+ }
59139
+ function checkStat(stat, path2, options) {
59140
+ if (!stat.isSymbolicLink() && !stat.isFile()) {
59141
+ return false;
59142
+ }
59143
+ return checkPathExt(path2, options);
59144
+ }
59145
+ function isexe(path2, options, cb) {
59146
+ fs.stat(path2, function(er, stat) {
59147
+ cb(er, er ? false : checkStat(stat, path2, options));
59148
+ });
59149
+ }
59150
+ function sync(path2, options) {
59151
+ return checkStat(fs.statSync(path2), path2, options);
59152
+ }
59153
+ }
59154
+ });
59155
+
59156
+ // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
59157
+ var require_mode = __commonJS({
59158
+ "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
59159
+ module.exports = isexe;
59160
+ isexe.sync = sync;
59161
+ var fs = __require("fs");
59162
+ function isexe(path2, options, cb) {
59163
+ fs.stat(path2, function(er, stat) {
59164
+ cb(er, er ? false : checkStat(stat, options));
59165
+ });
59166
+ }
59167
+ function sync(path2, options) {
59168
+ return checkStat(fs.statSync(path2), options);
59169
+ }
59170
+ function checkStat(stat, options) {
59171
+ return stat.isFile() && checkMode(stat, options);
59172
+ }
59173
+ function checkMode(stat, options) {
59174
+ var mod2 = stat.mode;
59175
+ var uid2 = stat.uid;
59176
+ var gid = stat.gid;
59177
+ var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
59178
+ var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
59179
+ var u = parseInt("100", 8);
59180
+ var g = parseInt("010", 8);
59181
+ var o = parseInt("001", 8);
59182
+ var ug = u | g;
59183
+ var ret = mod2 & o || mod2 & g && gid === myGid || mod2 & u && uid2 === myUid || mod2 & ug && myUid === 0;
59184
+ return ret;
59185
+ }
59186
+ }
59187
+ });
59188
+
59189
+ // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
59190
+ var require_isexe = __commonJS({
59191
+ "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
59192
+ var fs = __require("fs");
59193
+ var core;
59194
+ if (process.platform === "win32" || global.TESTING_WINDOWS) {
59195
+ core = require_windows();
59196
+ } else {
59197
+ core = require_mode();
59198
+ }
59199
+ module.exports = isexe;
59200
+ isexe.sync = sync;
59201
+ function isexe(path2, options, cb) {
59202
+ if (typeof options === "function") {
59203
+ cb = options;
59204
+ options = {};
59205
+ }
59206
+ if (!cb) {
59207
+ if (typeof Promise !== "function") {
59208
+ throw new TypeError("callback not provided");
59209
+ }
59210
+ return new Promise(function(resolve4, reject5) {
59211
+ isexe(path2, options || {}, function(er, is2) {
59212
+ if (er) {
59213
+ reject5(er);
59214
+ } else {
59215
+ resolve4(is2);
59216
+ }
59217
+ });
59218
+ });
59219
+ }
59220
+ core(path2, options || {}, function(er, is2) {
59221
+ if (er) {
59222
+ if (er.code === "EACCES" || options && options.ignoreErrors) {
59223
+ er = null;
59224
+ is2 = false;
59225
+ }
59226
+ }
59227
+ cb(er, is2);
59228
+ });
59229
+ }
59230
+ function sync(path2, options) {
59231
+ try {
59232
+ return core.sync(path2, options || {});
59233
+ } catch (er) {
59234
+ if (options && options.ignoreErrors || er.code === "EACCES") {
59235
+ return false;
59236
+ } else {
59237
+ throw er;
59238
+ }
59239
+ }
59240
+ }
59241
+ }
59242
+ });
59243
+
59244
+ // ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
59245
+ var require_which = __commonJS({
59246
+ "../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
59247
+ var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
59248
+ var path2 = __require("path");
59249
+ var COLON = isWindows ? ";" : ":";
59250
+ var isexe = require_isexe();
59251
+ var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
59252
+ var getPathInfo = (cmd, opt) => {
59253
+ const colon = opt.colon || COLON;
59254
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
59255
+ // windows always checks the cwd first
59256
+ ...isWindows ? [process.cwd()] : [],
59257
+ ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
59258
+ "").split(colon)
59259
+ ];
59260
+ const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
59261
+ const pathExt = isWindows ? pathExtExe.split(colon) : [""];
59262
+ if (isWindows) {
59263
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
59264
+ pathExt.unshift("");
59265
+ }
59266
+ return {
59267
+ pathEnv,
59268
+ pathExt,
59269
+ pathExtExe
59270
+ };
59271
+ };
59272
+ var which = (cmd, opt, cb) => {
59273
+ if (typeof opt === "function") {
59274
+ cb = opt;
59275
+ opt = {};
59276
+ }
59277
+ if (!opt)
59278
+ opt = {};
59279
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
59280
+ const found = [];
59281
+ const step = (i2) => new Promise((resolve4, reject5) => {
59282
+ if (i2 === pathEnv.length)
59283
+ return opt.all && found.length ? resolve4(found) : reject5(getNotFoundError(cmd));
59284
+ const ppRaw = pathEnv[i2];
59285
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
59286
+ const pCmd = path2.join(pathPart, cmd);
59287
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
59288
+ resolve4(subStep(p, i2, 0));
59289
+ });
59290
+ const subStep = (p, i2, ii) => new Promise((resolve4, reject5) => {
59291
+ if (ii === pathExt.length)
59292
+ return resolve4(step(i2 + 1));
59293
+ const ext = pathExt[ii];
59294
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is2) => {
59295
+ if (!er && is2) {
59296
+ if (opt.all)
59297
+ found.push(p + ext);
59298
+ else
59299
+ return resolve4(p + ext);
59300
+ }
59301
+ return resolve4(subStep(p, i2, ii + 1));
59302
+ });
59303
+ });
59304
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
59305
+ };
59306
+ var whichSync = (cmd, opt) => {
59307
+ opt = opt || {};
59308
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
59309
+ const found = [];
59310
+ for (let i2 = 0; i2 < pathEnv.length; i2++) {
59311
+ const ppRaw = pathEnv[i2];
59312
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
59313
+ const pCmd = path2.join(pathPart, cmd);
59314
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
59315
+ for (let j = 0; j < pathExt.length; j++) {
59316
+ const cur = p + pathExt[j];
59317
+ try {
59318
+ const is2 = isexe.sync(cur, { pathExt: pathExtExe });
59319
+ if (is2) {
59320
+ if (opt.all)
59321
+ found.push(cur);
59322
+ else
59323
+ return cur;
59324
+ }
59325
+ } catch (ex) {
59326
+ }
59327
+ }
59328
+ }
59329
+ if (opt.all && found.length)
59330
+ return found;
59331
+ if (opt.nothrow)
59332
+ return null;
59333
+ throw getNotFoundError(cmd);
59334
+ };
59335
+ module.exports = which;
59336
+ which.sync = whichSync;
59337
+ }
59338
+ });
59339
+
59340
+ // ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
59341
+ var require_path_key = __commonJS({
59342
+ "../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(exports, module) {
59343
+ "use strict";
59344
+ var pathKey = (options = {}) => {
59345
+ const environment3 = options.env || process.env;
59346
+ const platform = options.platform || process.platform;
59347
+ if (platform !== "win32") {
59348
+ return "PATH";
59349
+ }
59350
+ return Object.keys(environment3).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
59351
+ };
59352
+ module.exports = pathKey;
59353
+ module.exports.default = pathKey;
59354
+ }
59355
+ });
59356
+
59357
+ // ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
59358
+ var require_resolveCommand = __commonJS({
59359
+ "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
59360
+ "use strict";
59361
+ var path2 = __require("path");
59362
+ var which = require_which();
59363
+ var getPathKey = require_path_key();
59364
+ function resolveCommandAttempt(parsed2, withoutPathExt) {
59365
+ const env = parsed2.options.env || process.env;
59366
+ const cwd = process.cwd();
59367
+ const hasCustomCwd = parsed2.options.cwd != null;
59368
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
59369
+ if (shouldSwitchCwd) {
59370
+ try {
59371
+ process.chdir(parsed2.options.cwd);
59372
+ } catch (err2) {
59373
+ }
59374
+ }
59375
+ let resolved;
59376
+ try {
59377
+ resolved = which.sync(parsed2.command, {
59378
+ path: env[getPathKey({ env })],
59379
+ pathExt: withoutPathExt ? path2.delimiter : void 0
59380
+ });
59381
+ } catch (e) {
59382
+ } finally {
59383
+ if (shouldSwitchCwd) {
59384
+ process.chdir(cwd);
59385
+ }
59386
+ }
59387
+ if (resolved) {
59388
+ resolved = path2.resolve(hasCustomCwd ? parsed2.options.cwd : "", resolved);
59389
+ }
59390
+ return resolved;
59391
+ }
59392
+ function resolveCommand(parsed2) {
59393
+ return resolveCommandAttempt(parsed2) || resolveCommandAttempt(parsed2, true);
59394
+ }
59395
+ module.exports = resolveCommand;
59396
+ }
59397
+ });
59398
+
59399
+ // ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
59400
+ var require_escape = __commonJS({
59401
+ "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
59402
+ "use strict";
59403
+ var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
59404
+ function escapeCommand(arg) {
59405
+ arg = arg.replace(metaCharsRegExp, "^$1");
59406
+ return arg;
59407
+ }
59408
+ function escapeArgument(arg, doubleEscapeMetaChars) {
59409
+ arg = `${arg}`;
59410
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
59411
+ arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
59412
+ arg = `"${arg}"`;
59413
+ arg = arg.replace(metaCharsRegExp, "^$1");
59414
+ if (doubleEscapeMetaChars) {
59415
+ arg = arg.replace(metaCharsRegExp, "^$1");
59416
+ }
59417
+ return arg;
59418
+ }
59419
+ module.exports.command = escapeCommand;
59420
+ module.exports.argument = escapeArgument;
59421
+ }
59422
+ });
59423
+
59424
+ // ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
59425
+ var require_shebang_regex = __commonJS({
59426
+ "../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(exports, module) {
59427
+ "use strict";
59428
+ module.exports = /^#!(.*)/;
59429
+ }
59430
+ });
59431
+
59432
+ // ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
59433
+ var require_shebang_command = __commonJS({
59434
+ "../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(exports, module) {
59435
+ "use strict";
59436
+ var shebangRegex = require_shebang_regex();
59437
+ module.exports = (string5 = "") => {
59438
+ const match = string5.match(shebangRegex);
59439
+ if (!match) {
59440
+ return null;
59441
+ }
59442
+ const [path2, argument] = match[0].replace(/#! ?/, "").split(" ");
59443
+ const binary = path2.split("/").pop();
59444
+ if (binary === "env") {
59445
+ return argument;
59446
+ }
59447
+ return argument ? `${binary} ${argument}` : binary;
59448
+ };
59449
+ }
59450
+ });
59451
+
59452
+ // ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
59453
+ var require_readShebang = __commonJS({
59454
+ "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
59455
+ "use strict";
59456
+ var fs = __require("fs");
59457
+ var shebangCommand = require_shebang_command();
59458
+ function readShebang(command) {
59459
+ const size5 = 150;
59460
+ const buffer3 = Buffer.alloc(size5);
59461
+ let fd2;
59462
+ try {
59463
+ fd2 = fs.openSync(command, "r");
59464
+ fs.readSync(fd2, buffer3, 0, size5, 0);
59465
+ fs.closeSync(fd2);
59466
+ } catch (e) {
59467
+ }
59468
+ return shebangCommand(buffer3.toString());
59469
+ }
59470
+ module.exports = readShebang;
59471
+ }
59472
+ });
59473
+
59474
+ // ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
59475
+ var require_parse = __commonJS({
59476
+ "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
59477
+ "use strict";
59478
+ var path2 = __require("path");
59479
+ var resolveCommand = require_resolveCommand();
59480
+ var escape2 = require_escape();
59481
+ var readShebang = require_readShebang();
59482
+ var isWin = process.platform === "win32";
59483
+ var isExecutableRegExp = /\.(?:com|exe)$/i;
59484
+ var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
59485
+ function detectShebang(parsed2) {
59486
+ parsed2.file = resolveCommand(parsed2);
59487
+ const shebang = parsed2.file && readShebang(parsed2.file);
59488
+ if (shebang) {
59489
+ parsed2.args.unshift(parsed2.file);
59490
+ parsed2.command = shebang;
59491
+ return resolveCommand(parsed2);
59492
+ }
59493
+ return parsed2.file;
59494
+ }
59495
+ function parseNonShell(parsed2) {
59496
+ if (!isWin) {
59497
+ return parsed2;
59498
+ }
59499
+ const commandFile = detectShebang(parsed2);
59500
+ const needsShell = !isExecutableRegExp.test(commandFile);
59501
+ if (parsed2.options.forceShell || needsShell) {
59502
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
59503
+ parsed2.command = path2.normalize(parsed2.command);
59504
+ parsed2.command = escape2.command(parsed2.command);
59505
+ parsed2.args = parsed2.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
59506
+ const shellCommand = [parsed2.command].concat(parsed2.args).join(" ");
59507
+ parsed2.args = ["/d", "/s", "/c", `"${shellCommand}"`];
59508
+ parsed2.command = process.env.comspec || "cmd.exe";
59509
+ parsed2.options.windowsVerbatimArguments = true;
59510
+ }
59511
+ return parsed2;
59512
+ }
59513
+ function parse4(command, args, options) {
59514
+ if (args && !Array.isArray(args)) {
59515
+ options = args;
59516
+ args = null;
59517
+ }
59518
+ args = args ? args.slice(0) : [];
59519
+ options = Object.assign({}, options);
59520
+ const parsed2 = {
59521
+ command,
59522
+ args,
59523
+ options,
59524
+ file: void 0,
59525
+ original: {
59526
+ command,
59527
+ args
59528
+ }
59529
+ };
59530
+ return options.shell ? parsed2 : parseNonShell(parsed2);
59531
+ }
59532
+ module.exports = parse4;
59533
+ }
59534
+ });
59535
+
59536
+ // ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
59537
+ var require_enoent = __commonJS({
59538
+ "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(exports, module) {
59539
+ "use strict";
59540
+ var isWin = process.platform === "win32";
59541
+ function notFoundError(original, syscall) {
59542
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
59543
+ code: "ENOENT",
59544
+ errno: "ENOENT",
59545
+ syscall: `${syscall} ${original.command}`,
59546
+ path: original.command,
59547
+ spawnargs: original.args
59548
+ });
59549
+ }
59550
+ function hookChildProcess(cp, parsed2) {
59551
+ if (!isWin) {
59552
+ return;
59553
+ }
59554
+ const originalEmit = cp.emit;
59555
+ cp.emit = function(name, arg1) {
59556
+ if (name === "exit") {
59557
+ const err2 = verifyENOENT(arg1, parsed2);
59558
+ if (err2) {
59559
+ return originalEmit.call(cp, "error", err2);
59560
+ }
59561
+ }
59562
+ return originalEmit.apply(cp, arguments);
59563
+ };
59564
+ }
59565
+ function verifyENOENT(status, parsed2) {
59566
+ if (isWin && status === 1 && !parsed2.file) {
59567
+ return notFoundError(parsed2.original, "spawn");
59568
+ }
59569
+ return null;
59570
+ }
59571
+ function verifyENOENTSync(status, parsed2) {
59572
+ if (isWin && status === 1 && !parsed2.file) {
59573
+ return notFoundError(parsed2.original, "spawnSync");
59574
+ }
59575
+ return null;
59576
+ }
59577
+ module.exports = {
59578
+ hookChildProcess,
59579
+ verifyENOENT,
59580
+ verifyENOENTSync,
59581
+ notFoundError
59582
+ };
59583
+ }
59584
+ });
59585
+
59586
+ // ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js
59587
+ var require_cross_spawn = __commonJS({
59588
+ "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
59589
+ "use strict";
59590
+ var cp = __require("child_process");
59591
+ var parse4 = require_parse();
59592
+ var enoent = require_enoent();
59593
+ function spawn2(command, args, options) {
59594
+ const parsed2 = parse4(command, args, options);
59595
+ const spawned = cp.spawn(parsed2.command, parsed2.args, parsed2.options);
59596
+ enoent.hookChildProcess(spawned, parsed2);
59597
+ return spawned;
59598
+ }
59599
+ function spawnSync2(command, args, options) {
59600
+ const parsed2 = parse4(command, args, options);
59601
+ const result2 = cp.spawnSync(parsed2.command, parsed2.args, parsed2.options);
59602
+ result2.error = result2.error || enoent.verifyENOENTSync(result2.status, parsed2);
59603
+ return result2;
59604
+ }
59605
+ module.exports = spawn2;
59606
+ module.exports.spawn = spawn2;
59607
+ module.exports.sync = spawnSync2;
59608
+ module.exports._parse = parse4;
59609
+ module.exports._enoent = enoent;
59610
+ }
59611
+ });
59612
+
59613
+ // src/authorization-url-scanner.ts
59614
+ function escapeRegExp(value) {
59615
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
59616
+ }
59617
+ var MAXIMUM_BUFFERED_LINE_CHARACTERS, URL_CHARACTERS, OSC8_HYPERLINK, ESCAPE_SEQUENCE, AuthorizationUrlScanner;
59618
+ var init_authorization_url_scanner = __esm({
59619
+ "src/authorization-url-scanner.ts"() {
59620
+ "use strict";
59621
+ MAXIMUM_BUFFERED_LINE_CHARACTERS = 16384;
59622
+ URL_CHARACTERS = '[^\\s"<>`{}|\\\\^]+';
59623
+ OSC8_HYPERLINK = /\u001b\]8;[^;\u0007\u001b]*;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/gu;
59624
+ ESCAPE_SEQUENCE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[@-_]/gu;
59625
+ AuthorizationUrlScanner = class {
59626
+ pattern;
59627
+ buffers = /* @__PURE__ */ new Map();
59628
+ seen = /* @__PURE__ */ new Set();
59629
+ constructor(origin2) {
59630
+ this.pattern = new RegExp(`${escapeRegExp(`${origin2}/oauth/authorize?`)}${URL_CHARACTERS}`, "gu");
59631
+ }
59632
+ /**
59633
+ * Adds one chunk of one stream. Returns the complete lines it closed, for forwarding, and every
59634
+ * authorization URL those lines introduced that was not seen before on any stream.
59635
+ */
59636
+ feed(stream, chunk) {
59637
+ const buffered = `${this.buffers.get(stream) ?? ""}${chunk}`;
59638
+ const parts = buffered.split(/\r\n|\n|\r/u);
59639
+ let remainder = parts.pop();
59640
+ if (remainder.length > MAXIMUM_BUFFERED_LINE_CHARACTERS) {
59641
+ parts.push(remainder);
59642
+ remainder = "";
59643
+ }
59644
+ this.buffers.set(stream, remainder);
59645
+ return this.scan(parts);
59646
+ }
59647
+ /** Closes one stream, treating any unterminated text as its final line. */
59648
+ end(stream) {
59649
+ const remainder = this.buffers.get(stream) ?? "";
59650
+ this.buffers.delete(stream);
59651
+ return this.scan(remainder === "" ? [] : [remainder]);
59652
+ }
59653
+ scan(lines) {
59654
+ const urls = [];
59655
+ for (const line of lines) {
59656
+ const hyperlinkTargets = [...line.matchAll(OSC8_HYPERLINK)].map((match) => match[1]);
59657
+ const visible = line.replace(ESCAPE_SEQUENCE, "");
59658
+ for (const text3 of [...hyperlinkTargets, visible]) {
59659
+ for (const match of text3.matchAll(this.pattern)) {
59660
+ const url2 = match[0];
59661
+ if (!this.seen.has(url2)) {
59662
+ this.seen.add(url2);
59663
+ urls.push(url2);
59664
+ }
59665
+ }
59666
+ }
59667
+ }
59668
+ return Object.freeze({ lines: Object.freeze([...lines]), urls: Object.freeze(urls) });
59669
+ }
59670
+ };
59671
+ }
59672
+ });
59673
+
59674
+ // src/mcp-login-process.ts
59675
+ import { spawn as spawnSync } from "node:child_process";
59676
+ function terminate(child) {
59677
+ if (child.exitCode !== null || child.signalCode !== null || child.pid === void 0) return;
59678
+ if (process.platform === "win32") {
59679
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
59680
+ } else {
59681
+ child.kill("SIGTERM");
59682
+ }
59683
+ }
59684
+ var import_cross_spawn, AUTHORIZATION_URL_TIMEOUT_MILLISECONDS, LOGIN_EXIT_TIMEOUT_MILLISECONDS, spawnLoginCommand, InstalledMcpLoginSession, InstalledMcpLoginProcess;
59685
+ var init_mcp_login_process = __esm({
59686
+ "src/mcp-login-process.ts"() {
59687
+ "use strict";
59688
+ import_cross_spawn = __toESM(require_cross_spawn(), 1);
59689
+ init_authorization_url_scanner();
59690
+ init_cli_error();
59691
+ AUTHORIZATION_URL_TIMEOUT_MILLISECONDS = 12e4;
59692
+ LOGIN_EXIT_TIMEOUT_MILLISECONDS = 6e4;
59693
+ spawnLoginCommand = (command, arguments_) => (0, import_cross_spawn.default)(command, [...arguments_], {
59694
+ // stdin stays an open pipe that is never written: clients that also accept a pasted callback
59695
+ // treat end-of-input as a failed login.
59696
+ stdio: ["pipe", "pipe", "pipe"],
59697
+ windowsHide: true
59698
+ });
59699
+ InstalledMcpLoginSession = class {
59700
+ constructor(child, origin2, diagnostics, timeouts) {
59701
+ this.child = child;
59702
+ this.diagnostics = diagnostics;
59703
+ this.timeouts = timeouts;
59704
+ this.scanner = new AuthorizationUrlScanner(origin2);
59705
+ this.firstUrlPromise = new Promise((resolve4, reject5) => {
59706
+ this.firstUrl = resolve4;
59707
+ this.firstUrlFailed = reject5;
59708
+ });
59709
+ this.firstUrlPromise.catch(() => void 0);
59710
+ for (const [name, stream] of [["stdout", child.stdout], ["stderr", child.stderr]]) {
59711
+ stream?.setEncoding("utf8");
59712
+ stream?.on("data", (chunk) => this.accept(this.scanner.feed(name, chunk)));
59713
+ stream?.on("end", () => this.accept(this.scanner.end(name)));
59714
+ }
59715
+ this.exited = new Promise((resolve4) => {
59716
+ child.once("error", (cause) => {
59717
+ this.firstUrlFailed?.(new McpAuthorizationFlowError("login_command_not_started", {}, { cause }));
59718
+ resolve4(-1);
59719
+ });
59720
+ child.once("close", (code) => resolve4(code ?? -1));
59721
+ });
59722
+ void this.exited.then((code) => this.firstUrlFailed?.(new McpAuthorizationFlowError(
59723
+ "request_url_not_found",
59724
+ { loginCommandExitCode: code }
59725
+ )));
59726
+ }
59727
+ child;
59728
+ diagnostics;
59729
+ timeouts;
59730
+ scanner;
59731
+ secrets = [];
59732
+ exited;
59733
+ firstUrl;
59734
+ firstUrlFailed;
59735
+ firstUrlPromise;
59736
+ authorizationUrlCount = 0;
59737
+ accept(scan) {
59738
+ for (const line of scan.lines) {
59739
+ this.diagnostics(`${this.secrets.reduce((text3, secret) => text3.split(secret).join("[REDACTED]"), line)}
59740
+ `);
59741
+ }
59742
+ for (const url2 of scan.urls) {
59743
+ this.authorizationUrlCount += 1;
59744
+ if (this.authorizationUrlCount === 1) this.firstUrl?.(url2);
59745
+ }
59746
+ }
59747
+ async authorizationUrl() {
59748
+ let timer;
59749
+ const timeout = new Promise((_resolve, reject5) => {
59750
+ timer = setTimeout(
59751
+ () => reject5(new McpAuthorizationFlowError("request_url_not_found")),
59752
+ this.timeouts.authorizationUrl
59753
+ );
59754
+ });
59755
+ try {
59756
+ return await Promise.race([this.firstUrlPromise, timeout]);
59757
+ } finally {
59758
+ clearTimeout(timer);
59759
+ }
59760
+ }
59761
+ redact(secret) {
59762
+ if (secret.length > 0) this.secrets.push(secret);
59763
+ }
59764
+ async waitForExit() {
59765
+ let timer;
59766
+ const timeout = new Promise((resolve4) => {
59767
+ timer = setTimeout(() => resolve4("timeout"), this.timeouts.exit);
59768
+ });
59769
+ try {
59770
+ const code = await Promise.race([this.exited, timeout]);
59771
+ if (this.authorizationUrlCount > 1) {
59772
+ throw new McpAuthorizationFlowError("second_authorization_request");
59773
+ }
59774
+ if (code === "timeout") throw new McpAuthorizationFlowError("login_command_timeout");
59775
+ if (code !== 0) throw new McpAuthorizationFlowError("login_command_failed", { loginCommandExitCode: code });
59776
+ return code;
59777
+ } finally {
59778
+ clearTimeout(timer);
59779
+ }
59780
+ }
59781
+ close() {
59782
+ terminate(this.child);
59783
+ this.child.stdin?.end();
59784
+ }
59785
+ };
59786
+ InstalledMcpLoginProcess = class {
59787
+ constructor(spawn2 = spawnLoginCommand, diagnostics = (text3) => {
59788
+ process.stderr.write(text3);
59789
+ }, timeouts = {
59790
+ authorizationUrl: AUTHORIZATION_URL_TIMEOUT_MILLISECONDS,
59791
+ exit: LOGIN_EXIT_TIMEOUT_MILLISECONDS
59792
+ }) {
59793
+ this.spawn = spawn2;
59794
+ this.diagnostics = diagnostics;
59795
+ this.timeouts = timeouts;
59796
+ }
59797
+ spawn;
59798
+ diagnostics;
59799
+ timeouts;
59800
+ start(command, origin2) {
59801
+ const [executable, ...arguments_] = command;
59802
+ if (executable === void 0 || executable.length === 0) {
59803
+ throw new TypeError("finch mcp connect requires an MCP client login command after --.");
59804
+ }
59805
+ return new InstalledMcpLoginSession(this.spawn(executable, arguments_), origin2, this.diagnostics, this.timeouts);
59806
+ }
59807
+ };
59808
+ }
59809
+ });
59810
+
59811
+ // src/stdin-reader.ts
59812
+ var ProcessStdinReader;
59813
+ var init_stdin_reader = __esm({
59814
+ "src/stdin-reader.ts"() {
59815
+ "use strict";
59816
+ init_cli_error();
59817
+ ProcessStdinReader = class {
59818
+ constructor(input = process.stdin) {
59819
+ this.input = input;
59820
+ }
59821
+ input;
59822
+ async readAll(maximumBytes) {
59823
+ if (this.input.isTTY === true) throw new McpAuthorizationFlowError("stdin_invalid");
59824
+ const chunks = [];
59825
+ let total = 0;
59826
+ for await (const chunk of this.input) {
59827
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
59828
+ total += bytes.byteLength;
59829
+ if (total > maximumBytes) {
59830
+ this.input.destroy();
59831
+ throw new McpAuthorizationFlowError("stdin_invalid");
59832
+ }
59833
+ chunks.push(bytes);
59834
+ }
59835
+ try {
59836
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
59837
+ } catch (cause) {
59838
+ throw new McpAuthorizationFlowError("stdin_invalid", {}, { cause });
59839
+ }
59840
+ }
59841
+ };
59842
+ }
59843
+ });
59844
+
58930
59845
  // src/recovery-inventory.ts
58931
59846
  function object3(value, name) {
58932
59847
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -60430,12 +61345,12 @@ function assertCanonicalPlanTransactions(input) {
60430
61345
  }
60431
61346
  })();
60432
61347
  if (decoded.functionName !== "purchase") throw new TypeError("Agent purchase method is invalid.");
60433
- const request = decoded.args[0];
61348
+ const request2 = decoded.args[0];
60434
61349
  const deadline = Date.parse(input.confirmationDeadlineAt);
60435
- if (!Number.isSafeInteger(deadline) || deadline <= Date.now() || request.purchaseId !== uuidBytes32(input.operationId) || request.payToken.toLowerCase() !== token || request.unitPrice * request.units !== amount || request.validUntil !== BigInt(Math.floor(deadline / 1e3))) {
61350
+ if (!Number.isSafeInteger(deadline) || deadline <= Date.now() || request2.purchaseId !== uuidBytes32(input.operationId) || request2.payToken.toLowerCase() !== token || request2.unitPrice * request2.units !== amount || request2.validUntil !== BigInt(Math.floor(deadline / 1e3))) {
60436
61351
  throw new TypeError("Agent purchase arguments do not match the frozen plan.");
60437
61352
  }
60438
- const purchase = encodeFunctionData({ abi: agentPurchaseAbi, functionName: "purchase", args: [request] });
61353
+ const purchase = encodeFunctionData({ abi: agentPurchaseAbi, functionName: "purchase", args: [request2] });
60439
61354
  if (input.approval.data !== approval || input.revokeApproval.data !== revoke || input.purchase.data !== purchase) {
60440
61355
  throw new TypeError("Agent purchase calldata is not canonical for the frozen plan.");
60441
61356
  }
@@ -60925,12 +61840,12 @@ var init_task_protocol_sender = __esm({
60925
61840
  const preparation = record5(input.preparation, "Task pool preparation");
60926
61841
  assertSigningAuthority2(preparation, input.walletAddress, input.accountId);
60927
61842
  const deployment = taskDeployment(preparation.chainId);
60928
- const { vault, token, amount, request } = poolAuthority(preparation, input.taskId, deployment);
61843
+ const { vault, token, amount, request: request2 } = poolAuthority(preparation, input.taskId, deployment);
60929
61844
  const rpc = await this.rpc(input.privateKey, input.walletAddress, deployment);
60930
61845
  const owner = canonicalAddress(input.walletAddress, "Task wallet");
60931
61846
  const credit = await rpc.readCreditBalance(vault, owner, token);
60932
61847
  if (credit >= amount) {
60933
- const data = encodeFunctionData({ abi: taskVaultAbi, functionName: "createPool", args: [request] });
61848
+ const data = encodeFunctionData({ abi: taskVaultAbi, functionName: "createPool", args: [request2] });
60934
61849
  await rpc.simulateTransaction({ to: vault, data, value: 0n });
60935
61850
  const hash5 = await rpc.sendTransaction({ to: vault, data, value: 0n });
60936
61851
  await input.onBroadcast?.({ transactionHash: hash5 });
@@ -60944,7 +61859,7 @@ var init_task_protocol_sender = __esm({
60944
61859
  const createPool = encodeFunctionData({
60945
61860
  abi: taskVaultAbi,
60946
61861
  functionName: "depositAndCreatePool",
60947
- args: [request, depositAmount]
61862
+ args: [request2, depositAmount]
60948
61863
  });
60949
61864
  const allowance = await rpc.readAllowance(token, owner, vault);
60950
61865
  if (allowance < depositAmount) {
@@ -61109,14 +62024,14 @@ function resolveSkillViemChain(chainId) {
61109
62024
  if (chain !== void 0) return chain;
61110
62025
  throw new TypeError(`Unsupported Skill chain ${String(chainId)}.`);
61111
62026
  }
61112
- function expectedCall(kind, request, deployment) {
61113
- const skillId = () => unsigned2(request.skillId, "Skill id", true);
62027
+ function expectedCall(kind, request2, deployment) {
62028
+ const skillId = () => unsigned2(request2.skillId, "Skill id", true);
61114
62029
  if (kind === "purchase") {
61115
- const quantity = unsigned2(request.quantity, "Skill quantity", true);
61116
- const unitPrice = unsigned2(request.unitPrice, "Skill unit price");
62030
+ const quantity = unsigned2(request2.quantity, "Skill quantity", true);
62031
+ const unitPrice = unsigned2(request2.unitPrice, "Skill unit price");
61117
62032
  return {
61118
62033
  to: getAddress(deployment.skillInstanceAddress),
61119
- data: encodeFunctionData({ abi: instanceAbi, functionName: "purchase", args: [skillId(), version5(request.version, "Skill version"), quantity] }),
62034
+ data: encodeFunctionData({ abi: instanceAbi, functionName: "purchase", args: [skillId(), version5(request2.version, "Skill version"), quantity] }),
61120
62035
  value: unitPrice * quantity
61121
62036
  };
61122
62037
  }
@@ -61124,43 +62039,43 @@ function expectedCall(kind, request, deployment) {
61124
62039
  to: getAddress(deployment.skillInstanceAddress),
61125
62040
  data: encodeFunctionData({ abi: instanceAbi, functionName: "convert", args: [
61126
62041
  skillId(),
61127
- version5(request.fromVersion, "Source version"),
61128
- version5(request.toVersion, "Target version"),
61129
- unsigned2(request.quantity, "Skill quantity", true)
62042
+ version5(request2.fromVersion, "Source version"),
62043
+ version5(request2.toVersion, "Target version"),
62044
+ unsigned2(request2.quantity, "Skill quantity", true)
61130
62045
  ] }),
61131
62046
  value: 0n
61132
62047
  };
61133
62048
  throw new TypeError("Skill intent kind is invalid.");
61134
62049
  }
61135
- function expectedPreparedCall(action, request, deployment) {
61136
- const skillId = () => unsigned2(request.skillId, "Skill id", true);
62050
+ function expectedPreparedCall(action, request2, deployment) {
62051
+ const skillId = () => unsigned2(request2.skillId, "Skill id", true);
61137
62052
  if (action === "createSkill") {
61138
- if (typeof request.plaintext !== "boolean" || !Number.isInteger(request.royaltyBPS) || Number(request.royaltyBPS) < 0 || Number(request.royaltyBPS) > 1e3) throw new TypeError("Skill create request is invalid.");
62053
+ if (typeof request2.plaintext !== "boolean" || !Number.isInteger(request2.royaltyBPS) || Number(request2.royaltyBPS) < 0 || Number(request2.royaltyBPS) > 1e3) throw new TypeError("Skill create request is invalid.");
61139
62054
  return {
61140
62055
  to: getAddress(deployment.skillFactoryAddress),
61141
62056
  value: 0n,
61142
62057
  data: encodeFunctionData({ abi: factoryAbi, functionName: "createSkill", args: [{
61143
- mdHash: hash4(request.mdHash, "Skill primary-document hash"),
61144
- packageHash: hash4(request.packageHash, "Skill package hash"),
61145
- packageURI: textValue(request.packageURI, "Skill package URI"),
61146
- slug: textValue(request.slug, "Skill slug"),
61147
- name: textValue(request.name, "Skill name"),
61148
- category: textValue(request.category, "Skill category", true),
61149
- licenseTypeName: textValue(request.licenseTypeName, "Skill license", true),
61150
- imageURI: textValue(request.imageURI, "Skill image URI", true),
61151
- plaintext: request.plaintext,
61152
- unitPrice: unsigned2(request.unitPrice, "Skill unit price"),
61153
- maxSupply: unsigned2(request.maxSupply, "Skill max supply"),
61154
- royaltyBPS: BigInt(Number(request.royaltyBPS)),
61155
- usageLimit: unsigned2(request.usageLimit, "Skill usage limit")
62058
+ mdHash: hash4(request2.mdHash, "Skill primary-document hash"),
62059
+ packageHash: hash4(request2.packageHash, "Skill package hash"),
62060
+ packageURI: textValue(request2.packageURI, "Skill package URI"),
62061
+ slug: textValue(request2.slug, "Skill slug"),
62062
+ name: textValue(request2.name, "Skill name"),
62063
+ category: textValue(request2.category, "Skill category", true),
62064
+ licenseTypeName: textValue(request2.licenseTypeName, "Skill license", true),
62065
+ imageURI: textValue(request2.imageURI, "Skill image URI", true),
62066
+ plaintext: request2.plaintext,
62067
+ unitPrice: unsigned2(request2.unitPrice, "Skill unit price"),
62068
+ maxSupply: unsigned2(request2.maxSupply, "Skill max supply"),
62069
+ royaltyBPS: BigInt(Number(request2.royaltyBPS)),
62070
+ usageLimit: unsigned2(request2.usageLimit, "Skill usage limit")
61156
62071
  }] })
61157
62072
  };
61158
62073
  }
61159
- if (action === "updateSkill") return { to: getAddress(deployment.skillTokenAddress), value: 0n, data: encodeFunctionData({ abi: tokenAbi, functionName: "updateSkill", args: [skillId(), hash4(request.mdHash, "Skill primary-document hash"), hash4(request.packageHash, "Skill package hash")] }) };
61160
- if (action === "setSkillURI") return { to: getAddress(deployment.skillTokenAddress), value: 0n, data: encodeFunctionData({ abi: tokenAbi, functionName: "setSkillURI", args: [skillId(), textValue(request.packageURI, "Skill package URI")] }) };
61161
- if (action === "setUnitPrice") return { to: getAddress(deployment.revenueRightAddress), value: 0n, data: encodeFunctionData({ abi: revenueAbi, functionName: "setUnitPrice", args: [skillId(), unsigned2(request.unitPrice, "Skill unit price")] }) };
61162
- if (action === "setMaxSupply") return { to: getAddress(deployment.revenueRightAddress), value: 0n, data: encodeFunctionData({ abi: revenueAbi, functionName: "setMaxSupply", args: [skillId(), unsigned2(request.maxSupply, "Skill max supply")] }) };
61163
- if (action === "setLitData") return { to: getAddress(deployment.skillInstanceAddress), value: 0n, data: encodeFunctionData({ abi: instanceAbi, functionName: "setLitData", args: [skillId(), version5(request.version, "Skill version"), textValue(request.ciphertext, "Skill ciphertext"), textValue(request.scheme, "Skill envelope scheme"), textValue(request.chain, "Skill chain tag")] }) };
62074
+ if (action === "updateSkill") return { to: getAddress(deployment.skillTokenAddress), value: 0n, data: encodeFunctionData({ abi: tokenAbi, functionName: "updateSkill", args: [skillId(), hash4(request2.mdHash, "Skill primary-document hash"), hash4(request2.packageHash, "Skill package hash")] }) };
62075
+ if (action === "setSkillURI") return { to: getAddress(deployment.skillTokenAddress), value: 0n, data: encodeFunctionData({ abi: tokenAbi, functionName: "setSkillURI", args: [skillId(), textValue(request2.packageURI, "Skill package URI")] }) };
62076
+ if (action === "setUnitPrice") return { to: getAddress(deployment.revenueRightAddress), value: 0n, data: encodeFunctionData({ abi: revenueAbi, functionName: "setUnitPrice", args: [skillId(), unsigned2(request2.unitPrice, "Skill unit price")] }) };
62077
+ if (action === "setMaxSupply") return { to: getAddress(deployment.revenueRightAddress), value: 0n, data: encodeFunctionData({ abi: revenueAbi, functionName: "setMaxSupply", args: [skillId(), unsigned2(request2.maxSupply, "Skill max supply")] }) };
62078
+ if (action === "setLitData") return { to: getAddress(deployment.skillInstanceAddress), value: 0n, data: encodeFunctionData({ abi: instanceAbi, functionName: "setLitData", args: [skillId(), version5(request2.version, "Skill version"), textValue(request2.ciphertext, "Skill ciphertext"), textValue(request2.scheme, "Skill envelope scheme"), textValue(request2.chain, "Skill chain tag")] }) };
61164
62079
  throw new TypeError("Skill prepared action is invalid.");
61165
62080
  }
61166
62081
  function assertIntentMatches(raw, expected, chainId) {
@@ -61271,9 +62186,9 @@ var init_skill_intent_sender = __esm({
61271
62186
  if (typeof input.intent.walletAddress !== "string" || input.intent.walletAddress.toLowerCase() !== input.walletAddress.toLowerCase()) {
61272
62187
  throw new TypeError("Skill intent wallet does not match the active CLI wallet.");
61273
62188
  }
61274
- const request = record6(input.intent.request, "Skill intent request");
61275
- if (request.chainId !== deployment.chainId) throw new TypeError("Skill intent request chain is invalid.");
61276
- const expected = expectedCall(input.expectedKind, request, deployment);
62189
+ const request2 = record6(input.intent.request, "Skill intent request");
62190
+ if (request2.chainId !== deployment.chainId) throw new TypeError("Skill intent request chain is invalid.");
62191
+ const expected = expectedCall(input.expectedKind, request2, deployment);
61277
62192
  assertIntentMatches(
61278
62193
  input.intent,
61279
62194
  expected,
@@ -61312,10 +62227,10 @@ var init_skill_intent_sender = __esm({
61312
62227
  return Object.freeze({ transactionHash: transactionHash3, blockNumber: actual.blockNumber.toString() });
61313
62228
  }
61314
62229
  async submitPrepared(input) {
61315
- const request = record6(input.request, "Skill prepared request");
61316
- const deployment = this.authority(request.chainId);
62230
+ const request2 = record6(input.request, "Skill prepared request");
62231
+ const deployment = this.authority(request2.chainId);
61317
62232
  if (input.intent.chainId !== deployment.chainId) throw new TypeError("Skill prepared intent chain is invalid.");
61318
- const expected = expectedPreparedCall(input.action, request, deployment);
62233
+ const expected = expectedPreparedCall(input.action, request2, deployment);
61319
62234
  assertIntentMatches(input.intent, expected, deployment.chainId);
61320
62235
  const rpc = await this.rpc(input.privateKey, input.walletAddress, deployment);
61321
62236
  await rpc.simulateTransaction(expected);
@@ -61326,9 +62241,9 @@ var init_skill_intent_sender = __esm({
61326
62241
  return Object.freeze({ transactionHash: transactionHash3, blockNumber: receipt.blockNumber.toString() });
61327
62242
  }
61328
62243
  async verifyPrepared(input) {
61329
- const request = record6(input.request, "Skill prepared request");
61330
- const deployment = this.authority(request.chainId);
61331
- const expected = expectedPreparedCall(input.action, request, deployment);
62244
+ const request2 = record6(input.request, "Skill prepared request");
62245
+ const deployment = this.authority(request2.chainId);
62246
+ const expected = expectedPreparedCall(input.action, request2, deployment);
61332
62247
  const rpc = await this.rpc(input.privateKey, input.walletAddress, deployment);
61333
62248
  const transactionHash3 = hash4(input.transactionHash, "Skill recovery transaction hash");
61334
62249
  const exactTransaction2 = (actual2) => actual2.from.toLowerCase() === input.walletAddress && actual2.to?.toLowerCase() === expected.to.toLowerCase() && actual2.data === expected.data && actual2.value === expected.value;
@@ -61490,26 +62405,26 @@ function publishPlan(value, context) {
61490
62405
  exact2(plan, ["kind", "sourceCommit", "chainId", "walletAddress", "signingAuthority", "request", "localAction"], "Skill publish plan");
61491
62406
  const chainId = assertAuthority(plan, "publish", context.walletAddress);
61492
62407
  assertLocalAction(plan.localAction, "skill publish-submit");
61493
- const request = object5(plan.request, "Skill publish request");
61494
- exact2(request, ["chainId", "slug", "name", "category", "licenseTypeName", "imageURI", "sourceKind", "contentMode", "unitPrice", "maxSupply", "royaltyBPS", "usageLimit", ...Object.hasOwn(request, "summary") ? ["summary"] : []], "Skill publish request");
61495
- if (request.chainId !== chainId) throw new TypeError("Skill publish request chain is invalid.");
61496
- string4(request.slug, "Skill slug");
61497
- string4(request.name, "Skill name");
61498
- string4(request.category, "Skill category");
61499
- string4(request.licenseTypeName, "Skill license");
61500
- if (typeof request.imageURI !== "string") {
62408
+ const request2 = object5(plan.request, "Skill publish request");
62409
+ exact2(request2, ["chainId", "slug", "name", "category", "licenseTypeName", "imageURI", "sourceKind", "contentMode", "unitPrice", "maxSupply", "royaltyBPS", "usageLimit", ...Object.hasOwn(request2, "summary") ? ["summary"] : []], "Skill publish request");
62410
+ if (request2.chainId !== chainId) throw new TypeError("Skill publish request chain is invalid.");
62411
+ string4(request2.slug, "Skill slug");
62412
+ string4(request2.name, "Skill name");
62413
+ string4(request2.category, "Skill category");
62414
+ string4(request2.licenseTypeName, "Skill license");
62415
+ if (typeof request2.imageURI !== "string") {
61501
62416
  throw new TypeError("Skill publish metadata is invalid.");
61502
62417
  }
61503
- if (Object.hasOwn(request, "summary") && (typeof request.summary !== "string" || request.summary.length > 500)) throw new TypeError("Skill summary is invalid.");
61504
- sourceKind(request.sourceKind);
61505
- contentMode(request.contentMode);
61506
- string4(request.unitPrice, "Skill unitPrice", DECIMAL);
61507
- string4(request.maxSupply, "Skill maxSupply", DECIMAL);
61508
- string4(request.usageLimit, "Skill usageLimit", DECIMAL);
61509
- if (!Number.isInteger(request.royaltyBPS) || Number(request.royaltyBPS) < 0 || Number(request.royaltyBPS) > 1e3) throw new TypeError("Skill royaltyBPS is invalid.");
62418
+ if (Object.hasOwn(request2, "summary") && (typeof request2.summary !== "string" || request2.summary.length > 500)) throw new TypeError("Skill summary is invalid.");
62419
+ sourceKind(request2.sourceKind);
62420
+ contentMode(request2.contentMode);
62421
+ string4(request2.unitPrice, "Skill unitPrice", DECIMAL);
62422
+ string4(request2.maxSupply, "Skill maxSupply", DECIMAL);
62423
+ string4(request2.usageLimit, "Skill usageLimit", DECIMAL);
62424
+ if (!Number.isInteger(request2.royaltyBPS) || Number(request2.royaltyBPS) < 0 || Number(request2.royaltyBPS) > 1e3) throw new TypeError("Skill royaltyBPS is invalid.");
61510
62425
  return {
61511
62426
  chainId,
61512
- request,
62427
+ request: request2,
61513
62428
  signingAuthority: assertPublicationAuthority(signingAuthority(plan.signingAuthority, context.walletAddress), context)
61514
62429
  };
61515
62430
  }
@@ -61519,18 +62434,18 @@ function versionPlan(value, context) {
61519
62434
  const chainId = assertAuthority(plan, "version", context.walletAddress);
61520
62435
  const skillId = string4(plan.skillId, "Skill id", /^[1-9][0-9]*$/u);
61521
62436
  assertLocalAction(plan.localAction, "skill version-submit", skillId);
61522
- const request = { chainId, skillId, sourceKind: sourceKind(plan.sourceKind), contentMode: contentMode(plan.contentMode) };
62437
+ const request2 = { chainId, skillId, sourceKind: sourceKind(plan.sourceKind), contentMode: contentMode(plan.contentMode) };
61523
62438
  const currentVersion = integer2(plan.currentVersion, "Current version");
61524
62439
  const nextVersion = integer2(plan.nextVersion, "Next version");
61525
62440
  if (nextVersion !== currentVersion + 1) throw new TypeError("Skill version plan does not advance exactly one version.");
61526
62441
  return {
61527
62442
  chainId,
61528
- request,
62443
+ request: request2,
61529
62444
  currentVersion,
61530
62445
  nextVersion,
61531
62446
  currentPackageURI: string4(plan.currentManifestURI, "Current manifest URI", IPFS),
61532
- sourceKind: request.sourceKind,
61533
- contentMode: request.contentMode,
62447
+ sourceKind: request2.sourceKind,
62448
+ contentMode: request2.contentMode,
61534
62449
  signingAuthority: assertPublicationAuthority(signingAuthority(plan.signingAuthority, context.walletAddress), context)
61535
62450
  };
61536
62451
  }
@@ -61538,13 +62453,13 @@ function managePlan(value, walletAddress2, kind) {
61538
62453
  const plan = object5(value, `Skill ${kind} plan`);
61539
62454
  exact2(plan, ["kind", "sourceCommit", "chainId", "to", "data", "value", "summary", "walletAddress", "signingAuthority", "request"], `Skill ${kind} plan`);
61540
62455
  const chainId = assertAuthority(plan, kind === "price" ? "set_unit_price" : "set_max_supply", walletAddress2);
61541
- const request = object5(plan.request, `Skill ${kind} request`);
62456
+ const request2 = object5(plan.request, `Skill ${kind} request`);
61542
62457
  const field = kind === "price" ? "unitPrice" : "maxSupply";
61543
- exact2(request, ["chainId", "skillId", field], `Skill ${kind} request`);
61544
- if (request.chainId !== chainId) throw new TypeError(`Skill ${kind} request chain is invalid.`);
61545
- string4(request.skillId, "Skill id", /^[1-9][0-9]*$/u);
61546
- string4(request[field], `Skill ${field}`, DECIMAL);
61547
- return { chainId, request, intent: intent({
62458
+ exact2(request2, ["chainId", "skillId", field], `Skill ${kind} request`);
62459
+ if (request2.chainId !== chainId) throw new TypeError(`Skill ${kind} request chain is invalid.`);
62460
+ string4(request2.skillId, "Skill id", /^[1-9][0-9]*$/u);
62461
+ string4(request2[field], `Skill ${field}`, DECIMAL);
62462
+ return { chainId, request: request2, intent: intent({
61548
62463
  chainId: plan.chainId,
61549
62464
  to: plan.to,
61550
62465
  data: plan.data,
@@ -61644,11 +62559,11 @@ function recoveryReceipt(value, name) {
61644
62559
  });
61645
62560
  }
61646
62561
  function recoveryRequest(value, action, name, chainId) {
61647
- const request = object5(value, name);
61648
- if (request.action !== action || request.chainId !== void 0 && request.chainId !== chainId) {
62562
+ const request2 = object5(value, name);
62563
+ if (request2.action !== action || request2.chainId !== void 0 && request2.chainId !== chainId) {
61649
62564
  throw new TypeError(`${name} authority is invalid.`);
61650
62565
  }
61651
- return { ...request, chainId };
62566
+ return { ...request2, chainId };
61652
62567
  }
61653
62568
  function canonical2(value) {
61654
62569
  if (Array.isArray(value)) return `[${value.map(canonical2).join(",")}]`;
@@ -61814,12 +62729,12 @@ var init_skill_local_flow = __esm({
61814
62729
  async recoverPublication(fingerprint2, context) {
61815
62730
  return this.publication((progress) => this.recoverWithProgress(fingerprint2, context, progress));
61816
62731
  }
61817
- async send(context, action, request, prepared, authority, onBroadcast) {
62732
+ async send(context, action, request2, prepared, authority, onBroadcast) {
61818
62733
  return required3(this.sender.submitPrepared, "Skill prepared-intent sender").call(this.sender, {
61819
62734
  privateKey: context.privateKey,
61820
62735
  walletAddress: context.walletAddress,
61821
62736
  action,
61822
- request,
62737
+ request: request2,
61823
62738
  intent: authority === void 0 ? intent(prepared, context.walletAddress) : legacyIntent(prepared, context.walletAddress, authority),
61824
62739
  onBroadcast
61825
62740
  });
@@ -61952,14 +62867,14 @@ var init_skill_local_flow = __esm({
61952
62867
  };
61953
62868
  }
61954
62869
  async settle(read2, name) {
61955
- for (let attempt = 0; attempt < 60; attempt += 1) {
62870
+ for (let attempt2 = 0; attempt2 < 60; attempt2 += 1) {
61956
62871
  if (await read2()) return;
61957
62872
  await this.pause();
61958
62873
  }
61959
62874
  throw new TypeError(`${name} transaction confirmed but the settled chain read did not advance.`);
61960
62875
  }
61961
- async verify(context, action, request, receipt) {
61962
- return required3(this.sender.verifyPrepared, "Skill transaction verifier").call(this.sender, { privateKey: context.privateKey, walletAddress: context.walletAddress, action, request, ...receipt });
62876
+ async verify(context, action, request2, receipt) {
62877
+ return required3(this.sender.verifyPrepared, "Skill transaction verifier").call(this.sender, { privateKey: context.privateKey, walletAddress: context.walletAddress, action, request: request2, ...receipt });
61963
62878
  }
61964
62879
  async save(fingerprint2, journal) {
61965
62880
  await required3(this.recovery, "Skill publication recovery").saveSkillPublicationRecovery(fingerprint2, journal);
@@ -61967,14 +62882,14 @@ var init_skill_local_flow = __esm({
61967
62882
  async project(chainId, transactionHash3, bearer) {
61968
62883
  await this.api.confirmSkillProjection?.(chainId, transactionHash3, bearer);
61969
62884
  }
61970
- async stage(progress, context, fingerprint2, journal, stage, action, request, prepare) {
62885
+ async stage(progress, context, fingerprint2, journal, stage, action, request2, prepare) {
61971
62886
  progress.journal = journal;
61972
62887
  progress.fingerprint = fingerprint2;
61973
62888
  progress.journalSaved = true;
61974
62889
  progress.phase = "transaction";
61975
62890
  const existing = journal.receipts[stage];
61976
62891
  if (existing !== null) {
61977
- journal.receipts[stage] = await this.verify(context, action, request, existing);
62892
+ journal.receipts[stage] = await this.verify(context, action, request2, existing);
61978
62893
  if (journal.pendingStage === stage) journal.pendingStage = null;
61979
62894
  await this.save(fingerprint2, journal);
61980
62895
  progress.uncertain = false;
@@ -62004,7 +62919,7 @@ var init_skill_local_flow = __esm({
62004
62919
  journal.receipts[stage] = await this.send(
62005
62920
  context,
62006
62921
  action,
62007
- request,
62922
+ request2,
62008
62923
  prepared,
62009
62924
  journal.signingAuthority,
62010
62925
  async ({ transactionHash: transactionHash3 }) => {
@@ -62178,7 +63093,7 @@ var init_skill_local_flow = __esm({
62178
63093
  }
62179
63094
  async publishWithProgress(path2, planValue, context, progress) {
62180
63095
  const plan = publishPlan(planValue, context);
62181
- const request = plan.request;
63096
+ const request2 = plan.request;
62182
63097
  const fingerprint2 = recoveryFingerprint2("publish", planValue, context.walletAddress);
62183
63098
  const store = required3(this.recovery, "Skill publication recovery");
62184
63099
  progress.phase = "recovery";
@@ -62190,8 +63105,8 @@ var init_skill_local_flow = __esm({
62190
63105
  }
62191
63106
  progress.phase = "source";
62192
63107
  const selected = await readPublishablePath(path2);
62193
- const expectedSourceKind = sourceKind(request.sourceKind);
62194
- const mode = contentMode(request.contentMode);
63108
+ const expectedSourceKind = sourceKind(request2.sourceKind);
63109
+ const mode = contentMode(request2.contentMode);
62195
63110
  if (selected.sourceKind !== expectedSourceKind) throw new TypeError(`Skill plan requires a ${expectedSourceKind} source.`);
62196
63111
  progress.phase = "packaging";
62197
63112
  const packaged = await this.package(selected.files, prior === null ? mode : "plaintext", selected.excluded);
@@ -62206,14 +63121,14 @@ var init_skill_local_flow = __esm({
62206
63121
  files: selected.files,
62207
63122
  archive: packaged.archive,
62208
63123
  version: 1,
62209
- name: String(request.name),
62210
- summary: request.summary === void 0 ? "" : String(request.summary),
63124
+ name: String(request2.name),
63125
+ summary: request2.summary === void 0 ? "" : String(request2.summary),
62211
63126
  pinBundle: async (bytes) => {
62212
63127
  publishedBytes = bytes;
62213
63128
  progress.phase = "upload";
62214
63129
  return this.upload({
62215
63130
  bytes,
62216
- filename: `${request.slug}.skillroot.zip`,
63131
+ filename: `${request2.slug}.skillroot.zip`,
62217
63132
  bearer: context.bearer,
62218
63133
  objectKind: "package",
62219
63134
  sourceKind: "file",
@@ -62224,12 +63139,12 @@ var init_skill_local_flow = __esm({
62224
63139
  const packageURI = entry2.packageURI;
62225
63140
  const manifestURI = await this.upload({
62226
63141
  bytes: serializeManifest(buildManifest([entry2])),
62227
- filename: `${request.slug}.versions.json`,
63142
+ filename: `${request2.slug}.versions.json`,
62228
63143
  bearer: context.bearer,
62229
63144
  objectKind: "manifest"
62230
63145
  });
62231
63146
  const chainMetadata = Object.fromEntries(
62232
- Object.entries(request).filter(([key]) => key !== "sourceKind" && key !== "contentMode" && key !== "summary")
63147
+ Object.entries(request2).filter(([key]) => key !== "sourceKind" && key !== "contentMode" && key !== "summary")
62233
63148
  );
62234
63149
  const createRequest = {
62235
63150
  action: "createSkill",
@@ -62282,11 +63197,11 @@ var init_skill_local_flow = __esm({
62282
63197
  skillId = await required3(this.api.resolveSkillId, "Skill resolve API").call(
62283
63198
  this.api,
62284
63199
  journal.chainId,
62285
- String(request.slug),
63200
+ String(request2.slug),
62286
63201
  context.bearer
62287
63202
  );
62288
63203
  return skillId !== null;
62289
- }, `Skill ${request.slug} publication`);
63204
+ }, `Skill ${request2.slug} publication`);
62290
63205
  if (skillId === null) throw new TypeError("Published Skill slug did not resolve.");
62291
63206
  if (journal.skillId !== null && journal.skillId !== skillId) throw new TypeError("Skill publication recovery resolved a different Skill id.");
62292
63207
  journal.skillId = skillId;
@@ -62504,15 +63419,15 @@ var init_skill_local_flow = __esm({
62504
63419
  bearer: context.bearer,
62505
63420
  objectKind: "manifest"
62506
63421
  });
62507
- const request = { action: "setSkillURI", chainId: plan.chainId, skillId: plan.skillId, packageURI: manifestURI };
63422
+ const request2 = { action: "setSkillURI", chainId: plan.chainId, skillId: plan.skillId, packageURI: manifestURI };
62508
63423
  progress.phase = "intent";
62509
- const prepared = await required3(this.api.requestSkillIntent, "Skill intent API").call(this.api, request, context.bearer);
63424
+ const prepared = await required3(this.api.requestSkillIntent, "Skill intent API").call(this.api, request2, context.bearer);
62510
63425
  progress.phase = "transaction";
62511
63426
  progress.uncertain = true;
62512
63427
  const submission = await this.send(
62513
63428
  context,
62514
63429
  "setSkillURI",
62515
- request,
63430
+ request2,
62516
63431
  prepared,
62517
63432
  plan.signingAuthority,
62518
63433
  async ({ transactionHash: transactionHash3 }) => {
@@ -62647,12 +63562,14 @@ async function resolveInstalledProfile(readProfile) {
62647
63562
  throw cause;
62648
63563
  }
62649
63564
  }
62650
- function commandNeedsHttp(arguments_) {
63565
+ function commandNeedsHttp(allArguments) {
63566
+ const arguments_ = finchOwnArguments(allArguments);
62651
63567
  if (arguments_.length === 0 || arguments_.length === 1 && ["--help", "help", "--version"].includes(arguments_[0]) || arguments_[0] === "help" && arguments_.length > 1 || arguments_.length > 1 && arguments_.at(-1) === "--help" && arguments_.filter((argument) => argument === "--help").length === 1) return false;
62652
63568
  return (arguments_[0] !== "wallet" || arguments_[1] === "use") && !(arguments_.length === 2 && arguments_[0] === "logout" && arguments_[1] === "--local");
62653
63569
  }
62654
63570
  async function runInstalledCli(arguments_, environment3 = process.env, authorities = {}) {
62655
- const profileFree = arguments_.length === 0 || arguments_.length === 1 && ["--help", "help", "--version"].includes(arguments_[0]) || arguments_[0] === "help" && arguments_.length > 1 || arguments_.length > 1 && arguments_.at(-1) === "--help" && arguments_.filter((argument) => argument === "--help").length === 1;
63571
+ const own = finchOwnArguments(arguments_);
63572
+ const profileFree = own.length === 0 || own.length === 1 && ["--help", "help", "--version"].includes(own[0]) || own[0] === "help" && own.length > 1 || own.length > 1 && own.at(-1) === "--help" && own.filter((argument) => argument === "--help").length === 1;
62656
63573
  if (profileFree) return routeCommand(arguments_, {});
62657
63574
  const home = resolveFinchtechHome(environment3);
62658
63575
  const state = new LocalCliState(home);
@@ -62679,7 +63596,10 @@ async function runInstalledCli(arguments_, environment3 = process.env, authoriti
62679
63596
  taskProtocolSender: new InstalledTaskProtocolSender(),
62680
63597
  skillIntentSender,
62681
63598
  skillLocalFlow: profile === void 0 || skillIntentSender === void 0 ? void 0 : new SkillLocalFlow(api, skillIntentSender, signer, void 0, void 0, state),
62682
- browserLauncher: new InstalledBrowserLauncher()
63599
+ browserLauncher: new InstalledBrowserLauncher(),
63600
+ callbackDelivery: new LoopbackCallbackDelivery(),
63601
+ mcpLoginProcess: new InstalledMcpLoginProcess(),
63602
+ stdin: new ProcessStdinReader()
62683
63603
  });
62684
63604
  return routeCommand(arguments_, application);
62685
63605
  }
@@ -62689,6 +63609,9 @@ var init_main = __esm({
62689
63609
  init_api2();
62690
63610
  init_application();
62691
63611
  init_command_router();
63612
+ init_loopback_callback();
63613
+ init_mcp_login_process();
63614
+ init_stdin_reader();
62692
63615
  init_local_state();
62693
63616
  init_state();
62694
63617
  init_signing();
@@ -62852,6 +63775,22 @@ function emitCliOutcome(outcome, sinks) {
62852
63775
  `);
62853
63776
  return AGENT_CLI_OUTPUT_CONTRACT.exitCodes.remoteOrProviderUnavailable;
62854
63777
  }
63778
+ if (outcome instanceof McpAuthorizationFlowError) {
63779
+ sinks.stdout(`${JSON.stringify({ error: {
63780
+ code: outcome.code,
63781
+ message: outcome.guidance,
63782
+ reasonCode: null,
63783
+ retryable: false,
63784
+ nextAction: "none",
63785
+ state: JSON.stringify({ reason: outcome.reason, ...outcome.detail }),
63786
+ operationId: null,
63787
+ currentRevision: null,
63788
+ currentEtag: null,
63789
+ traceId: null
63790
+ } })}
63791
+ `);
63792
+ return AGENT_CLI_OUTPUT_CONTRACT.exitCodes.conflictOrPrecondition;
63793
+ }
62855
63794
  if (outcome instanceof CliHttpError && outcome.envelope !== null && outcome.status !== null) {
62856
63795
  sinks.stdout(`${JSON.stringify(outcome.envelope)}
62857
63796
  `);