@finchtech/cli 0.3.8 → 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({
@@ -17652,7 +17749,7 @@ var init_schemas = __esm({
17652
17749
  requiresHuman: { type: "boolean" },
17653
17750
  requiresTwitter: { type: "boolean" },
17654
17751
  autoSettle: { type: "boolean" },
17655
- settlementMode: { type: "string", enum: ["merchant_manual", "fcfs_realtime", "weighted_lottery", "delayed_auto_7d"] },
17752
+ settlementMode: { type: "string", enum: ["merchant_manual", "fcfs_realtime", "weighted_lottery", "delayed_auto_7d", "merchant_review_7d"] },
17656
17753
  deadline: nullableString,
17657
17754
  startAt: nullableString,
17658
17755
  goals: { type: "array", maxItems: 5, items: openObjectSchema },
@@ -17665,7 +17762,7 @@ var init_schemas = __esm({
17665
17762
  }, ["content"]);
17666
17763
  taskReviewRequestSchema = strictObjectSchema2({
17667
17764
  submissionIds: { type: "array", minItems: 1, maxItems: 100, uniqueItems: true, items: canonicalUuidSchema2 },
17668
- action: { type: "string", enum: ["approve", "cancel_award", "reject", "spam", "favorite", "unfavorite"] },
17765
+ action: { type: "string", enum: ["approve", "cancel_award", "reject", "review_later", "spam", "favorite", "unfavorite"] },
17669
17766
  spamReason: { type: "string", maxLength: 200 }
17670
17767
  }, ["submissionIds", "action"]);
17671
17768
  signedAwardSchema = strictObjectSchema2({
@@ -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
  }
@@ -55201,6 +55298,18 @@ function jsonObject(value) {
55201
55298
  }
55202
55299
  return value;
55203
55300
  }
55301
+ function includesCapabilities(value, required4) {
55302
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0) && required4.every((item) => value.includes(item));
55303
+ }
55304
+ function sameOriginEndpoint(value, origin2) {
55305
+ if (typeof value !== "string") return false;
55306
+ try {
55307
+ const url2 = new URL(value);
55308
+ return url2.origin === origin2 && url2.username === "" && url2.password === "" && url2.hash === "";
55309
+ } catch {
55310
+ return false;
55311
+ }
55312
+ }
55204
55313
  function protectedResourceMetadataAuthority(authenticate, origin2, resourcePath) {
55205
55314
  const matches = [...authenticate.matchAll(/(?:^|[\s,])resource_metadata="([^"]+)"/gu)];
55206
55315
  if (!/(?:^|[\s,])Bearer(?:[\s,]|$)/iu.test(authenticate) || matches.length !== 1) {
@@ -55338,6 +55447,7 @@ var init_api2 = __esm({
55338
55447
  "src/api.ts"() {
55339
55448
  "use strict";
55340
55449
  import_ajv = __toESM(require_ajv(), 1);
55450
+ init_package();
55341
55451
  init_cli_error();
55342
55452
  init_src2();
55343
55453
  init_v1();
@@ -55465,7 +55575,8 @@ var init_api2 = __esm({
55465
55575
  method: options.method.toUpperCase(),
55466
55576
  headers,
55467
55577
  body,
55468
- redirect: "error"
55578
+ redirect: "error",
55579
+ ...options.signal === void 0 ? {} : { signal: options.signal }
55469
55580
  });
55470
55581
  } catch (cause) {
55471
55582
  throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", null, { cause });
@@ -55534,12 +55645,30 @@ var init_api2 = __esm({
55534
55645
  return await this.fetchImplementation(`${this.origin}${path2}`, {
55535
55646
  method: "GET",
55536
55647
  redirect: "error",
55537
- cache: "no-store"
55648
+ cache: "no-store",
55649
+ signal: AbortSignal.timeout(15e3)
55538
55650
  });
55539
55651
  } catch (cause) {
55540
55652
  throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", null, { cause });
55541
55653
  }
55542
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
+ }
55543
55672
  async inspectRemoteMcp() {
55544
55673
  const mcpUrl = `${this.origin}/mcp`;
55545
55674
  const compatibilityManifestUrl = `${this.origin}/mcp/client-compatibility.json`;
@@ -55563,42 +55692,15 @@ var init_api2 = __esm({
55563
55692
  throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", resourceResponse.status);
55564
55693
  }
55565
55694
  const resource = jsonObject(await readBoundedJson(resourceResponse));
55566
- if (resource.resource !== resourceMetadataAuthority.resource || JSON.stringify(resource.authorization_servers) !== JSON.stringify([this.origin])) {
55695
+ if (resource.resource !== resourceMetadataAuthority.resource || !includesCapabilities(resource.authorization_servers, [this.origin])) {
55567
55696
  throw new CliHttpError("CLI_RESPONSE_INVALID", resourceResponse.status);
55568
55697
  }
55569
- const authorizationResponse = await this.publicFetch("/.well-known/oauth-authorization-server");
55570
- if (authorizationResponse.status !== 200) {
55571
- await authorizationResponse.body?.cancel().catch(() => void 0);
55572
- throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", authorizationResponse.status);
55573
- }
55574
- const authorization = jsonObject(await readBoundedJson(authorizationResponse));
55575
- if (authorization.issuer !== this.origin || authorization.authorization_endpoint !== `${this.origin}/oauth/authorize` || authorization.token_endpoint !== `${this.origin}/oauth/token` || authorization.registration_endpoint !== `${this.origin}/oauth/register` || JSON.stringify(authorization.response_types_supported) !== JSON.stringify(["code"]) || JSON.stringify(authorization.grant_types_supported) !== JSON.stringify(["authorization_code", "refresh_token"]) || JSON.stringify(authorization.token_endpoint_auth_methods_supported) !== JSON.stringify(["none"]) || JSON.stringify(authorization.code_challenge_methods_supported) !== JSON.stringify(["S256"])) {
55576
- throw new CliHttpError("CLI_RESPONSE_INVALID", authorizationResponse.status);
55577
- }
55578
- const manifestResponse = await this.publicFetch("/mcp/client-compatibility.json");
55579
- if (manifestResponse.status !== 200) {
55580
- await manifestResponse.body?.cancel().catch(() => void 0);
55581
- throw new CliHttpError("CLI_REMOTE_UNAVAILABLE", manifestResponse.status);
55582
- }
55583
- const manifest4 = jsonObject(await readBoundedJson(manifestResponse));
55584
- const mcp = jsonObject(manifest4.mcp);
55585
- const source = jsonObject(manifest4.source);
55586
- if (!Array.isArray(manifest4.clients) || manifest4.clients.length !== 1) {
55587
- throw new CliHttpError("CLI_RESPONSE_INVALID", manifestResponse.status);
55588
- }
55589
- const client = jsonObject(manifest4.clients[0]);
55590
- const install = jsonObject(client.install);
55591
- const authorize = jsonObject(client.authorize);
55592
- const verify = jsonObject(client.verify);
55593
- if (manifest4.schemaVersion !== 3 || manifest4.manifestId !== "finch.remote-mcp-clients" || mcp.serverName !== "finch" || mcp.url !== mcpUrl || mcp.transport !== "streamable_http" || mcp.authorization !== "oauth" || source.repository !== "https://github.com/FinchipAI/Finch-Site" || source.path !== "apps/mcp/src/client-compatibility.ts" || client.id !== "codex" || client.supportLevel !== "verified" || install.kind !== "native_cli" || install.executable !== "codex" || JSON.stringify(install.arguments) !== JSON.stringify(["mcp", "add", "finch", "--url", mcpUrl]) || authorize.kind !== "native_cli" || authorize.executable !== "codex" || JSON.stringify(authorize.arguments) !== JSON.stringify(["mcp", "login", "finch"]) || verify.kind !== "harness_ui" || verify.surface !== "mcp_tools" || client.reload !== "new_session") {
55594
- throw new CliHttpError("CLI_RESPONSE_INVALID", manifestResponse.status);
55595
- }
55698
+ await this.authorizationServerMetadata();
55596
55699
  return Object.freeze({
55597
55700
  url: mcpUrl,
55598
55701
  transport: "streamable_http",
55599
55702
  authorization: "oauth",
55600
- compatibilityManifestUrl,
55601
- supportedClients: Object.freeze(["codex"])
55703
+ compatibilityManifestUrl
55602
55704
  });
55603
55705
  }
55604
55706
  async uploadSkillObject(input) {
@@ -55900,7 +56002,7 @@ var init_api2 = __esm({
55900
56002
  if (response.status === 202 && body?.status === "indexing_pending") return "indexing_pending";
55901
56003
  throw new CliHttpError("CLI_RESPONSE_INVALID", response.status);
55902
56004
  }
55903
- getSession(bearer) {
56005
+ getSession(bearer, signal) {
55904
56006
  const operation3 = IDENTITY_V1_OPERATIONS.session;
55905
56007
  return this.request({
55906
56008
  method: operation3.method,
@@ -55908,7 +56010,8 @@ var init_api2 = __esm({
55908
56010
  successStatus: operation3.successStatus,
55909
56011
  errorContract: "identity",
55910
56012
  responseSchema: operation3.responseSchema,
55911
- bearer
56013
+ bearer,
56014
+ ...signal === void 0 ? {} : { signal }
55912
56015
  });
55913
56016
  }
55914
56017
  authorizeMcp(requestPath, bearer) {
@@ -55928,7 +56031,8 @@ var init_api2 = __esm({
55928
56031
  errorContract: "oauth",
55929
56032
  responseSchema: oauthAuthorizationResponseSchema,
55930
56033
  bearer,
55931
- body: {}
56034
+ body: {},
56035
+ headers: { [AGENT_CLI_MCP_AUTHORIZATION_CLIENT.versionHeader]: package_default.version }
55932
56036
  });
55933
56037
  }
55934
56038
  createChallenge(input) {
@@ -56649,6 +56753,84 @@ var init_skill_buyer_intent_journal = __esm({
56649
56753
  }
56650
56754
  });
56651
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
+
56652
56834
  // src/application.ts
56653
56835
  import { createHash as createHash2, randomUUID } from "node:crypto";
56654
56836
  import { open as open2 } from "node:fs/promises";
@@ -56917,7 +57099,7 @@ function parseTaskRecoveryJournal(value, expected) {
56917
57099
  idempotencyKey: journal.idempotencyKey
56918
57100
  });
56919
57101
  }
56920
- var FinchCliApplication;
57102
+ var MAXIMUM_STDIN_AUTHORIZATION_BYTES, FinchCliApplication;
56921
57103
  var init_application = __esm({
56922
57104
  "src/application.ts"() {
56923
57105
  "use strict";
@@ -56931,6 +57113,8 @@ var init_application = __esm({
56931
57113
  init_state();
56932
57114
  init_skill_buyer_intent_journal();
56933
57115
  init_cli_error();
57116
+ init_loopback_callback();
57117
+ MAXIMUM_STDIN_AUTHORIZATION_BYTES = 4098;
56934
57118
  FinchCliApplication = class {
56935
57119
  api;
56936
57120
  state;
@@ -56944,6 +57128,9 @@ var init_application = __esm({
56944
57128
  skillIntentSender;
56945
57129
  skillLocalFlow;
56946
57130
  browserLauncher;
57131
+ callbackDelivery;
57132
+ mcpLoginProcess;
57133
+ stdin;
56947
57134
  constructor(dependencies) {
56948
57135
  this.api = dependencies.api;
56949
57136
  this.state = dependencies.state;
@@ -56957,6 +57144,9 @@ var init_application = __esm({
56957
57144
  this.skillIntentSender = dependencies.skillIntentSender;
56958
57145
  this.skillLocalFlow = dependencies.skillLocalFlow;
56959
57146
  this.browserLauncher = dependencies.browserLauncher;
57147
+ this.callbackDelivery = dependencies.callbackDelivery;
57148
+ this.mcpLoginProcess = dependencies.mcpLoginProcess;
57149
+ this.stdin = dependencies.stdin;
56960
57150
  }
56961
57151
  async authorizedProfile() {
56962
57152
  return this.activeProfile ?? await required2(this.state.readProfile, "state.readProfile").call(this.state);
@@ -57159,8 +57349,8 @@ var init_application = __esm({
57159
57349
  const handoffId = this.randomUuid();
57160
57350
  const token = this.randomBearer();
57161
57351
  const tokenCommitment = `0x${createHash2("sha256").update(token, "utf8").digest("hex")}`;
57162
- const request = { handoffId, tokenCommitment };
57163
- 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);
57164
57354
  const bound = asObject(response, "Browser handoff");
57165
57355
  if (bound.accountId !== input.session.accountId || bound.environment !== input.session.environment || String(bound.walletAddress).toLowerCase() !== input.session.walletAddress.toLowerCase()) {
57166
57356
  throw new CliAuthorityError();
@@ -57192,19 +57382,45 @@ var init_application = __esm({
57192
57382
  const authority = await this.verifiedAgentCliAuthority();
57193
57383
  return this.openBrowserHandoff({ ...authority, requestId: match[1] });
57194
57384
  }
57385
+ /** Layer 3: the shell-safe request token shown on the Finch authorization page. */
57195
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) {
57196
57400
  const profile = await this.authorizedProfile();
57197
- const requestUrl = decodeAgentCliMcpAuthorizationRequest(requestToken);
57198
- let request;
57401
+ await this.verifiedAgentCliAuthority();
57402
+ const session = required2(this.mcpLoginProcess, "MCP login process").start(command, profile.origin);
57199
57403
  try {
57200
- 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);
57201
57417
  } catch {
57202
57418
  throw new TypeError("MCP OAuth request URL is invalid.");
57203
57419
  }
57204
- const redirectValues = request.searchParams.getAll("redirect_uri");
57205
- const stateValues = request.searchParams.getAll("state");
57206
- const scopeValues = request.searchParams.getAll("scope");
57207
- 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) {
57208
57424
  throw new TypeError("MCP OAuth request URL does not match the active profile authority.");
57209
57425
  }
57210
57426
  let registeredRedirect;
@@ -57213,18 +57429,19 @@ var init_application = __esm({
57213
57429
  } catch {
57214
57430
  throw new TypeError("MCP OAuth redirect URI is invalid.");
57215
57431
  }
57216
- if (registeredRedirect.username !== "" || registeredRedirect.password !== "" || registeredRedirect.hash !== "") {
57432
+ if (registeredRedirect.username !== "" || registeredRedirect.password !== "" || registeredRedirect.hash !== "" || registeredRedirect.protocol !== "https:" && !isLoopbackHttpUrl(registeredRedirect)) {
57217
57433
  throw new TypeError("MCP OAuth redirect URI is invalid.");
57218
57434
  }
57219
57435
  const authority = await this.verifiedAgentCliAuthority();
57220
- 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");
57221
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") {
57222
57439
  throw new CliAuthorityError();
57223
57440
  }
57224
- const requestedScopes = scopeValues[0].split(" ").filter(Boolean).sort();
57225
- const returnedScopes = [...response.scopes].sort();
57226
- if (requestedScopes.length < 1 || requestedScopes.length !== returnedScopes.length || requestedScopes.some((scope, index2) => scope !== returnedScopes[index2])) {
57227
- throw new CliAuthorityError();
57441
+ const requestedScopes = [...new Set((scopeValues[0] ?? "").split(" ").filter(Boolean))].sort();
57442
+ const returnedScopes = [...new Set(response.scopes)].sort();
57443
+ if (returnedScopes.length < 1 || requestedScopes.length > 0 && (requestedScopes.length !== returnedScopes.length || requestedScopes.some((scope, index2) => scope !== returnedScopes[index2]))) {
57444
+ throw new TypeError("MCP OAuth granted scopes do not match the authorization request.");
57228
57445
  }
57229
57446
  let callback;
57230
57447
  try {
@@ -57233,22 +57450,36 @@ var init_application = __esm({
57233
57450
  throw new TypeError("MCP OAuth callback is invalid.");
57234
57451
  }
57235
57452
  const codes = callback.searchParams.getAll("code");
57236
- if (codes.length !== 1 || !/^[A-Za-z0-9_-]{43}$/u.test(codes[0])) {
57453
+ if (codes.length !== 1 || codes[0].length < 1 || callback.searchParams.has("error")) {
57237
57454
  throw new TypeError("MCP OAuth callback is invalid.");
57238
57455
  }
57456
+ onAuthorizationCode?.(codes[0]);
57239
57457
  const expectedCallback = new URL(registeredRedirect.href);
57240
57458
  expectedCallback.searchParams.set("code", codes[0]);
57241
57459
  if (stateValues.length === 1) expectedCallback.searchParams.set("state", stateValues[0]);
57242
- if (callback.href !== expectedCallback.href) {
57243
- throw new TypeError("MCP OAuth callback does not match the registered redirect and state.");
57460
+ if (expectedIssuer !== null) expectedCallback.searchParams.set("iss", expectedIssuer);
57461
+ const expectedParameters = new URLSearchParams(expectedCallback.search);
57462
+ const callbackParameters = new URLSearchParams(callback.search);
57463
+ expectedParameters.sort();
57464
+ callbackParameters.sort();
57465
+ if (callback.origin !== registeredRedirect.origin || callback.pathname !== registeredRedirect.pathname || callback.protocol !== registeredRedirect.protocol || callback.username !== "" || callback.password !== "" || callback.hash !== "" || callbackParameters.toString() !== expectedParameters.toString()) {
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() {
@@ -57412,7 +57643,8 @@ var init_application = __esm({
57412
57643
  message: localFailureMessage(cause)
57413
57644
  }];
57414
57645
  } else if (cause instanceof CliHttpError) {
57415
- return [null, { status: cause.status === 401 || cause.status === 403 || cause.code === "CLI_RESPONSE_INVALID" ? "invalid" : "unavailable", message: guidance }];
57646
+ const unavailable = cause.status === 429 || cause.status !== null && cause.status >= 500;
57647
+ return [null, { status: !unavailable && (cause.status === 401 || cause.status === 403 || cause.code === "CLI_RESPONSE_INVALID") ? "invalid" : "unavailable", message: guidance }];
57416
57648
  } else if (cause instanceof TypeError || cause instanceof CliAuthorityError) {
57417
57649
  return [null, { status: "invalid", message: guidance }];
57418
57650
  } else {
@@ -57425,7 +57657,7 @@ var init_application = __esm({
57425
57657
  "Check the protected FINCHTECH_HOME/profile.json endpoint override."
57426
57658
  );
57427
57659
  const [wallet, walletCheck] = await inspect(
57428
- () => required2(this.state.readWalletAddress, "state.readWalletAddress").call(this.state),
57660
+ () => required2(this.state.readWalletAddress, "state.readWalletAddress").call(this.state, { migrateLegacy: false }),
57429
57661
  "Restore the current wallet from backup."
57430
57662
  );
57431
57663
  const [session, sessionCheck] = await inspect(
@@ -57439,7 +57671,7 @@ var init_application = __esm({
57439
57671
  if (session.origin !== profile.origin || wallet.walletAddress !== session.walletAddress) {
57440
57672
  throw new CliAuthorityError();
57441
57673
  }
57442
- const remote = asObject(await required2(this.api.getSession, "api.getSession").call(this.api, session.rawBearer), "MCP doctor Session");
57674
+ const remote = asObject(await required2(this.api.getSession, "api.getSession").call(this.api, session.rawBearer, AbortSignal.timeout(15e3)), "MCP doctor Session");
57443
57675
  if (remote.sessionId !== session.sessionId || remote.accountId !== session.accountId || remote.walletAddress !== session.walletAddress || remote.environment !== session.environment || remote.audience !== "agent_cli" || typeof remote.sessionExpiresAt !== "string" || !Number.isFinite(Date.parse(remote.sessionExpiresAt)) || Date.parse(remote.sessionExpiresAt) <= Date.now()) throw new CliAuthorityError();
57444
57676
  return { sessionExpiresAt: remote.sessionExpiresAt };
57445
57677
  }, "Verify the endpoint and current wallet, then run finch login --help to renew the CLI login. If the server is unavailable, retry later.");
@@ -57451,7 +57683,7 @@ var init_application = __esm({
57451
57683
  if (profile !== null) {
57452
57684
  [mcp, mcpDiscoveryCheck] = await inspect(async () => {
57453
57685
  const discovery = await required2(this.api.inspectRemoteMcp, "api.inspectRemoteMcp").call(this.api);
57454
- if (discovery.url !== `${profile.origin}/mcp` || discovery.authorization !== "oauth" || JSON.stringify(discovery.supportedClients) !== JSON.stringify(["codex"])) {
57686
+ if (discovery.url !== `${profile.origin}/mcp` || discovery.authorization !== "oauth" || discovery.transport !== "streamable_http") {
57455
57687
  throw new TypeError("MCP discovery authority mismatch.");
57456
57688
  }
57457
57689
  return discovery;
@@ -58298,66 +58530,13 @@ var init_application = __esm({
58298
58530
  }
58299
58531
  });
58300
58532
 
58301
- // package.json
58302
- var package_default;
58303
- var init_package = __esm({
58304
- "package.json"() {
58305
- package_default = {
58306
- name: "@finchtech/cli",
58307
- version: "0.3.8",
58308
- description: "Finch Agent CLI for wallet-owned marketplace and MCP workflows.",
58309
- type: "module",
58310
- bin: {
58311
- finch: "dist/finch.js",
58312
- finchtech: "dist/finch.js"
58313
- },
58314
- files: [
58315
- "dist/finch.js",
58316
- "README.md",
58317
- "THIRD_PARTY_LICENSES.txt"
58318
- ],
58319
- engines: {
58320
- node: ">=20"
58321
- },
58322
- publishConfig: {
58323
- access: "public"
58324
- },
58325
- repository: {
58326
- type: "git",
58327
- url: "git+https://github.com/FinchipAI/Finch-Site.git",
58328
- directory: "apps/cli"
58329
- },
58330
- homepage: "https://www.finchtech.ai",
58331
- scripts: {
58332
- build: 'esbuild src/bootstrap.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/finch.js --banner:js="#!/usr/bin/env node"',
58333
- check: "pnpm lint && pnpm typecheck && pnpm test && pnpm build",
58334
- lint: "eslint src vitest.config.ts eslint.config.mjs",
58335
- prepack: "pnpm build",
58336
- test: "vitest run",
58337
- typecheck: "tsc --noEmit"
58338
- },
58339
- devDependencies: {
58340
- "@finch/agent-market-contracts": "workspace:*",
58341
- "@finch/deployment-manifest": "workspace:*",
58342
- "@finch/skill-content": "workspace:*",
58343
- "@finch/skill-market-contracts": "workspace:*",
58344
- "@finch/task-market-contracts": "workspace:*",
58345
- "@eslint/js": "9.39.2",
58346
- "@types/node": "20.19.30",
58347
- ajv: "8.20.0",
58348
- esbuild: "0.28.2",
58349
- eslint: "9.39.2",
58350
- typescript: "5.9.3",
58351
- "typescript-eslint": "8.67.0",
58352
- viem: "2.55.15",
58353
- vitest: "4.1.10"
58354
- }
58355
- };
58356
- }
58357
- });
58358
-
58359
58533
  // src/command-router.ts
58360
- 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);
58361
58540
  if (arguments_[0] === "help" && arguments_.length > 1) return arguments_.slice(1).join(" ");
58362
58541
  if (arguments_.length > 1 && arguments_.at(-1) === "--help" && arguments_.filter((argument) => argument === "--help").length === 1) {
58363
58542
  return arguments_.slice(0, -1).join(" ");
@@ -58481,7 +58660,13 @@ async function routeCommand(arguments_, application) {
58481
58660
  if (first === "mcp" && second === "doctor" && arguments_.length === 2) {
58482
58661
  return result("mcp.doctor", await method(application.doctorMcp, "mcp doctor").call(application));
58483
58662
  }
58484
- 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("--")) {
58485
58670
  return result("mcp.authorize", await method(application.authorizeMcp, "mcp authorize").call(application, third));
58486
58671
  }
58487
58672
  if (first === "mcp" && second === "grant" && third === "create") {
@@ -58804,6 +58989,7 @@ var init_command_router = __esm({
58804
58989
  "site open",
58805
58990
  "site login",
58806
58991
  "mcp doctor",
58992
+ "mcp connect",
58807
58993
  "mcp authorize",
58808
58994
  "mcp grant create",
58809
58995
  "mcp grant show",
@@ -58870,7 +59056,8 @@ var init_command_router = __esm({
58870
59056
  "site open": "finch site open",
58871
59057
  "site login": "finch site login <REQUEST_URL>",
58872
59058
  "mcp doctor": "finch mcp doctor",
58873
- "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>",
58874
59061
  "mcp grant create": "finch mcp grant create --scopes <CSV> --expires-at <ISO-8601>",
58875
59062
  "mcp grant show": "finch mcp grant show <GRANT_ID>",
58876
59063
  "mcp grant revoke": "finch mcp grant revoke <GRANT_ID>",
@@ -58926,6 +59113,735 @@ var init_command_router = __esm({
58926
59113
  }
58927
59114
  });
58928
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
+
58929
59845
  // src/recovery-inventory.ts
58930
59846
  function object3(value, name) {
58931
59847
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -59133,7 +60049,13 @@ function privateKey(value) {
59133
60049
  function validatedWallet(input) {
59134
60050
  const address2 = walletAddress(input.walletAddress);
59135
60051
  const key = privateKey(input.privateKey);
59136
- if (privateKeyToAccount(key).address.toLowerCase() !== address2) {
60052
+ let derivedAddress;
60053
+ try {
60054
+ derivedAddress = privateKeyToAccount(key).address.toLowerCase();
60055
+ } catch (cause) {
60056
+ throw new CliStateError("CLI_STATE_CORRUPT", { cause });
60057
+ }
60058
+ if (derivedAddress !== address2) {
59137
60059
  throw new CliStateError("CLI_STATE_CORRUPT");
59138
60060
  }
59139
60061
  return Object.freeze({ walletAddress: address2, privateKey: key });
@@ -59205,13 +60127,7 @@ var init_wallet_store = __esm({
59205
60127
  await this.writeIndex(nextIndex);
59206
60128
  if (makeCurrent || currentIndex.length === 0) await this.writeCurrent(wallet.walletAddress);
59207
60129
  }
59208
- async migrateLegacyOnce() {
59209
- try {
59210
- await this.files.readJson("wallet/current.json");
59211
- return;
59212
- } catch (cause) {
59213
- if (!(cause instanceof CliStateError) || cause.code !== "CLI_STATE_NOT_FOUND") throw cause;
59214
- }
60130
+ async readLegacy() {
59215
60131
  const readOptional = async (read2) => {
59216
60132
  try {
59217
60133
  return await read2();
@@ -59226,15 +60142,26 @@ var init_wallet_store = __esm({
59226
60142
  ]);
59227
60143
  if (metadata === null && key === null) {
59228
60144
  const index2 = await this.readIndex();
59229
- if (index2.length === 0) return;
60145
+ if (index2.length === 0) return null;
59230
60146
  throw new CliStateError("CLI_STATE_CORRUPT");
59231
60147
  }
59232
60148
  if (metadata === null || key === null) throw new CliStateError("CLI_STATE_CORRUPT");
59233
60149
  const legacy = record4(metadata);
59234
- await this.registerInternal(validatedWallet({
60150
+ return validatedWallet({
59235
60151
  walletAddress: legacy.walletAddress,
59236
60152
  privateKey: key.toString("utf8")
59237
- }), true);
60153
+ });
60154
+ }
60155
+ async migrateLegacyOnce() {
60156
+ try {
60157
+ await this.files.readJson("wallet/current.json");
60158
+ return;
60159
+ } catch (cause) {
60160
+ if (!(cause instanceof CliStateError) || cause.code !== "CLI_STATE_NOT_FOUND") throw cause;
60161
+ }
60162
+ const legacy = await this.readLegacy();
60163
+ if (legacy === null) return;
60164
+ await this.registerInternal(legacy, true);
59238
60165
  await this.files.remove("wallet/private-key");
59239
60166
  await this.files.remove("wallet/metadata.json");
59240
60167
  }
@@ -59267,9 +60194,17 @@ var init_wallet_store = __esm({
59267
60194
  await this.migrateLegacy();
59268
60195
  return this.readIndex();
59269
60196
  }
59270
- async readCurrent() {
59271
- await this.migrateLegacy();
59272
- const current = record4(await this.files.readJson("wallet/current.json"));
60197
+ async readCurrent(options = {}) {
60198
+ if (options.migrateLegacy !== false) await this.migrateLegacy();
60199
+ let current;
60200
+ try {
60201
+ current = record4(await this.files.readJson("wallet/current.json"));
60202
+ } catch (cause) {
60203
+ if (options.migrateLegacy !== false || !(cause instanceof CliStateError) || cause.code !== "CLI_STATE_NOT_FOUND") throw cause;
60204
+ const legacy = await this.readLegacy();
60205
+ if (legacy === null) throw cause;
60206
+ return legacy;
60207
+ }
59273
60208
  if (current.version !== 1) throw new CliStateError("CLI_STATE_CORRUPT");
59274
60209
  try {
59275
60210
  return await this.readRegistered(walletAddress(current.walletAddress));
@@ -59563,16 +60498,16 @@ var init_local_state = __esm({
59563
60498
  async saveWallet(input) {
59564
60499
  await this.wallets.register(input);
59565
60500
  }
59566
- async readWallet() {
60501
+ async readWallet(options) {
59567
60502
  try {
59568
- return await this.wallets.readCurrent();
60503
+ return await this.wallets.readCurrent(options);
59569
60504
  } catch (cause) {
59570
60505
  if (cause instanceof CliStateError) throw new CliStateError(cause.code, { cause, diagnostic: "wallet" });
59571
60506
  throw cause;
59572
60507
  }
59573
60508
  }
59574
- async readWalletAddress() {
59575
- const wallet = await this.readWallet();
60509
+ async readWalletAddress(options) {
60510
+ const wallet = await this.readWallet(options);
59576
60511
  return Object.freeze({ walletAddress: wallet.walletAddress });
59577
60512
  }
59578
60513
  async assertWalletBootstrap() {
@@ -60410,12 +61345,12 @@ function assertCanonicalPlanTransactions(input) {
60410
61345
  }
60411
61346
  })();
60412
61347
  if (decoded.functionName !== "purchase") throw new TypeError("Agent purchase method is invalid.");
60413
- const request = decoded.args[0];
61348
+ const request2 = decoded.args[0];
60414
61349
  const deadline = Date.parse(input.confirmationDeadlineAt);
60415
- 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))) {
60416
61351
  throw new TypeError("Agent purchase arguments do not match the frozen plan.");
60417
61352
  }
60418
- const purchase = encodeFunctionData({ abi: agentPurchaseAbi, functionName: "purchase", args: [request] });
61353
+ const purchase = encodeFunctionData({ abi: agentPurchaseAbi, functionName: "purchase", args: [request2] });
60419
61354
  if (input.approval.data !== approval || input.revokeApproval.data !== revoke || input.purchase.data !== purchase) {
60420
61355
  throw new TypeError("Agent purchase calldata is not canonical for the frozen plan.");
60421
61356
  }
@@ -60905,12 +61840,12 @@ var init_task_protocol_sender = __esm({
60905
61840
  const preparation = record5(input.preparation, "Task pool preparation");
60906
61841
  assertSigningAuthority2(preparation, input.walletAddress, input.accountId);
60907
61842
  const deployment = taskDeployment(preparation.chainId);
60908
- const { vault, token, amount, request } = poolAuthority(preparation, input.taskId, deployment);
61843
+ const { vault, token, amount, request: request2 } = poolAuthority(preparation, input.taskId, deployment);
60909
61844
  const rpc = await this.rpc(input.privateKey, input.walletAddress, deployment);
60910
61845
  const owner = canonicalAddress(input.walletAddress, "Task wallet");
60911
61846
  const credit = await rpc.readCreditBalance(vault, owner, token);
60912
61847
  if (credit >= amount) {
60913
- const data = encodeFunctionData({ abi: taskVaultAbi, functionName: "createPool", args: [request] });
61848
+ const data = encodeFunctionData({ abi: taskVaultAbi, functionName: "createPool", args: [request2] });
60914
61849
  await rpc.simulateTransaction({ to: vault, data, value: 0n });
60915
61850
  const hash5 = await rpc.sendTransaction({ to: vault, data, value: 0n });
60916
61851
  await input.onBroadcast?.({ transactionHash: hash5 });
@@ -60924,7 +61859,7 @@ var init_task_protocol_sender = __esm({
60924
61859
  const createPool = encodeFunctionData({
60925
61860
  abi: taskVaultAbi,
60926
61861
  functionName: "depositAndCreatePool",
60927
- args: [request, depositAmount]
61862
+ args: [request2, depositAmount]
60928
61863
  });
60929
61864
  const allowance = await rpc.readAllowance(token, owner, vault);
60930
61865
  if (allowance < depositAmount) {
@@ -60967,7 +61902,7 @@ var init_task_protocol_sender = __esm({
60967
61902
  const fields = record5(typedData.types, "Task award types").AwardAuthorization;
60968
61903
  const selected = taskDeployment(domain2.chainId);
60969
61904
  deployment ??= selected;
60970
- if (deployment.chainId !== selected.chainId || typedData.primaryType !== "AwardAuthorization" || domain2.name !== "Finch Task Vault" || domain2.version !== "0" || domain2.chainId !== deployment.chainId || JSON.stringify(fields) !== JSON.stringify(awardTypes.AwardAuthorization) || message.awardId !== record5(award.authorization, "Task award authorization").awardId) {
61905
+ if (deployment.chainId !== selected.chainId || typedData.primaryType !== "AwardAuthorization" || domain2.name !== "Finch Task Vault" || domain2.version !== "0" || domain2.chainId !== deployment.chainId || !Array.isArray(fields) || fields.length !== awardTypes.AwardAuthorization.length || fields.some((field, index2) => typeof field !== "object" || field === null || Array.isArray(field) || Object.keys(field).length !== 2 || field.name !== awardTypes.AwardAuthorization[index2].name || field.type !== awardTypes.AwardAuthorization[index2].type) || message.awardId !== record5(award.authorization, "Task award authorization").awardId) {
60971
61906
  throw new TypeError("Task award signing authority is invalid.");
60972
61907
  }
60973
61908
  const canonicalDomain = {
@@ -61089,14 +62024,14 @@ function resolveSkillViemChain(chainId) {
61089
62024
  if (chain !== void 0) return chain;
61090
62025
  throw new TypeError(`Unsupported Skill chain ${String(chainId)}.`);
61091
62026
  }
61092
- function expectedCall(kind, request, deployment) {
61093
- const skillId = () => unsigned2(request.skillId, "Skill id", true);
62027
+ function expectedCall(kind, request2, deployment) {
62028
+ const skillId = () => unsigned2(request2.skillId, "Skill id", true);
61094
62029
  if (kind === "purchase") {
61095
- const quantity = unsigned2(request.quantity, "Skill quantity", true);
61096
- 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");
61097
62032
  return {
61098
62033
  to: getAddress(deployment.skillInstanceAddress),
61099
- 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] }),
61100
62035
  value: unitPrice * quantity
61101
62036
  };
61102
62037
  }
@@ -61104,43 +62039,43 @@ function expectedCall(kind, request, deployment) {
61104
62039
  to: getAddress(deployment.skillInstanceAddress),
61105
62040
  data: encodeFunctionData({ abi: instanceAbi, functionName: "convert", args: [
61106
62041
  skillId(),
61107
- version5(request.fromVersion, "Source version"),
61108
- version5(request.toVersion, "Target version"),
61109
- 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)
61110
62045
  ] }),
61111
62046
  value: 0n
61112
62047
  };
61113
62048
  throw new TypeError("Skill intent kind is invalid.");
61114
62049
  }
61115
- function expectedPreparedCall(action, request, deployment) {
61116
- const skillId = () => unsigned2(request.skillId, "Skill id", true);
62050
+ function expectedPreparedCall(action, request2, deployment) {
62051
+ const skillId = () => unsigned2(request2.skillId, "Skill id", true);
61117
62052
  if (action === "createSkill") {
61118
- 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.");
61119
62054
  return {
61120
62055
  to: getAddress(deployment.skillFactoryAddress),
61121
62056
  value: 0n,
61122
62057
  data: encodeFunctionData({ abi: factoryAbi, functionName: "createSkill", args: [{
61123
- mdHash: hash4(request.mdHash, "Skill primary-document hash"),
61124
- packageHash: hash4(request.packageHash, "Skill package hash"),
61125
- packageURI: textValue(request.packageURI, "Skill package URI"),
61126
- slug: textValue(request.slug, "Skill slug"),
61127
- name: textValue(request.name, "Skill name"),
61128
- category: textValue(request.category, "Skill category", true),
61129
- licenseTypeName: textValue(request.licenseTypeName, "Skill license", true),
61130
- imageURI: textValue(request.imageURI, "Skill image URI", true),
61131
- plaintext: request.plaintext,
61132
- unitPrice: unsigned2(request.unitPrice, "Skill unit price"),
61133
- maxSupply: unsigned2(request.maxSupply, "Skill max supply"),
61134
- royaltyBPS: BigInt(Number(request.royaltyBPS)),
61135
- 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")
61136
62071
  }] })
61137
62072
  };
61138
62073
  }
61139
- 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")] }) };
61140
- if (action === "setSkillURI") return { to: getAddress(deployment.skillTokenAddress), value: 0n, data: encodeFunctionData({ abi: tokenAbi, functionName: "setSkillURI", args: [skillId(), textValue(request.packageURI, "Skill package URI")] }) };
61141
- if (action === "setUnitPrice") return { to: getAddress(deployment.revenueRightAddress), value: 0n, data: encodeFunctionData({ abi: revenueAbi, functionName: "setUnitPrice", args: [skillId(), unsigned2(request.unitPrice, "Skill unit price")] }) };
61142
- if (action === "setMaxSupply") return { to: getAddress(deployment.revenueRightAddress), value: 0n, data: encodeFunctionData({ abi: revenueAbi, functionName: "setMaxSupply", args: [skillId(), unsigned2(request.maxSupply, "Skill max supply")] }) };
61143
- 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")] }) };
61144
62079
  throw new TypeError("Skill prepared action is invalid.");
61145
62080
  }
61146
62081
  function assertIntentMatches(raw, expected, chainId) {
@@ -61251,9 +62186,9 @@ var init_skill_intent_sender = __esm({
61251
62186
  if (typeof input.intent.walletAddress !== "string" || input.intent.walletAddress.toLowerCase() !== input.walletAddress.toLowerCase()) {
61252
62187
  throw new TypeError("Skill intent wallet does not match the active CLI wallet.");
61253
62188
  }
61254
- const request = record6(input.intent.request, "Skill intent request");
61255
- if (request.chainId !== deployment.chainId) throw new TypeError("Skill intent request chain is invalid.");
61256
- 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);
61257
62192
  assertIntentMatches(
61258
62193
  input.intent,
61259
62194
  expected,
@@ -61292,10 +62227,10 @@ var init_skill_intent_sender = __esm({
61292
62227
  return Object.freeze({ transactionHash: transactionHash3, blockNumber: actual.blockNumber.toString() });
61293
62228
  }
61294
62229
  async submitPrepared(input) {
61295
- const request = record6(input.request, "Skill prepared request");
61296
- const deployment = this.authority(request.chainId);
62230
+ const request2 = record6(input.request, "Skill prepared request");
62231
+ const deployment = this.authority(request2.chainId);
61297
62232
  if (input.intent.chainId !== deployment.chainId) throw new TypeError("Skill prepared intent chain is invalid.");
61298
- const expected = expectedPreparedCall(input.action, request, deployment);
62233
+ const expected = expectedPreparedCall(input.action, request2, deployment);
61299
62234
  assertIntentMatches(input.intent, expected, deployment.chainId);
61300
62235
  const rpc = await this.rpc(input.privateKey, input.walletAddress, deployment);
61301
62236
  await rpc.simulateTransaction(expected);
@@ -61306,9 +62241,9 @@ var init_skill_intent_sender = __esm({
61306
62241
  return Object.freeze({ transactionHash: transactionHash3, blockNumber: receipt.blockNumber.toString() });
61307
62242
  }
61308
62243
  async verifyPrepared(input) {
61309
- const request = record6(input.request, "Skill prepared request");
61310
- const deployment = this.authority(request.chainId);
61311
- 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);
61312
62247
  const rpc = await this.rpc(input.privateKey, input.walletAddress, deployment);
61313
62248
  const transactionHash3 = hash4(input.transactionHash, "Skill recovery transaction hash");
61314
62249
  const exactTransaction2 = (actual2) => actual2.from.toLowerCase() === input.walletAddress && actual2.to?.toLowerCase() === expected.to.toLowerCase() && actual2.data === expected.data && actual2.value === expected.value;
@@ -61470,26 +62405,26 @@ function publishPlan(value, context) {
61470
62405
  exact2(plan, ["kind", "sourceCommit", "chainId", "walletAddress", "signingAuthority", "request", "localAction"], "Skill publish plan");
61471
62406
  const chainId = assertAuthority(plan, "publish", context.walletAddress);
61472
62407
  assertLocalAction(plan.localAction, "skill publish-submit");
61473
- const request = object5(plan.request, "Skill publish request");
61474
- exact2(request, ["chainId", "slug", "name", "category", "licenseTypeName", "imageURI", "sourceKind", "contentMode", "unitPrice", "maxSupply", "royaltyBPS", "usageLimit", ...Object.hasOwn(request, "summary") ? ["summary"] : []], "Skill publish request");
61475
- if (request.chainId !== chainId) throw new TypeError("Skill publish request chain is invalid.");
61476
- string4(request.slug, "Skill slug");
61477
- string4(request.name, "Skill name");
61478
- string4(request.category, "Skill category");
61479
- string4(request.licenseTypeName, "Skill license");
61480
- 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") {
61481
62416
  throw new TypeError("Skill publish metadata is invalid.");
61482
62417
  }
61483
- if (Object.hasOwn(request, "summary") && (typeof request.summary !== "string" || request.summary.length > 500)) throw new TypeError("Skill summary is invalid.");
61484
- sourceKind(request.sourceKind);
61485
- contentMode(request.contentMode);
61486
- string4(request.unitPrice, "Skill unitPrice", DECIMAL);
61487
- string4(request.maxSupply, "Skill maxSupply", DECIMAL);
61488
- string4(request.usageLimit, "Skill usageLimit", DECIMAL);
61489
- 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.");
61490
62425
  return {
61491
62426
  chainId,
61492
- request,
62427
+ request: request2,
61493
62428
  signingAuthority: assertPublicationAuthority(signingAuthority(plan.signingAuthority, context.walletAddress), context)
61494
62429
  };
61495
62430
  }
@@ -61499,18 +62434,18 @@ function versionPlan(value, context) {
61499
62434
  const chainId = assertAuthority(plan, "version", context.walletAddress);
61500
62435
  const skillId = string4(plan.skillId, "Skill id", /^[1-9][0-9]*$/u);
61501
62436
  assertLocalAction(plan.localAction, "skill version-submit", skillId);
61502
- 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) };
61503
62438
  const currentVersion = integer2(plan.currentVersion, "Current version");
61504
62439
  const nextVersion = integer2(plan.nextVersion, "Next version");
61505
62440
  if (nextVersion !== currentVersion + 1) throw new TypeError("Skill version plan does not advance exactly one version.");
61506
62441
  return {
61507
62442
  chainId,
61508
- request,
62443
+ request: request2,
61509
62444
  currentVersion,
61510
62445
  nextVersion,
61511
62446
  currentPackageURI: string4(plan.currentManifestURI, "Current manifest URI", IPFS),
61512
- sourceKind: request.sourceKind,
61513
- contentMode: request.contentMode,
62447
+ sourceKind: request2.sourceKind,
62448
+ contentMode: request2.contentMode,
61514
62449
  signingAuthority: assertPublicationAuthority(signingAuthority(plan.signingAuthority, context.walletAddress), context)
61515
62450
  };
61516
62451
  }
@@ -61518,13 +62453,13 @@ function managePlan(value, walletAddress2, kind) {
61518
62453
  const plan = object5(value, `Skill ${kind} plan`);
61519
62454
  exact2(plan, ["kind", "sourceCommit", "chainId", "to", "data", "value", "summary", "walletAddress", "signingAuthority", "request"], `Skill ${kind} plan`);
61520
62455
  const chainId = assertAuthority(plan, kind === "price" ? "set_unit_price" : "set_max_supply", walletAddress2);
61521
- const request = object5(plan.request, `Skill ${kind} request`);
62456
+ const request2 = object5(plan.request, `Skill ${kind} request`);
61522
62457
  const field = kind === "price" ? "unitPrice" : "maxSupply";
61523
- exact2(request, ["chainId", "skillId", field], `Skill ${kind} request`);
61524
- if (request.chainId !== chainId) throw new TypeError(`Skill ${kind} request chain is invalid.`);
61525
- string4(request.skillId, "Skill id", /^[1-9][0-9]*$/u);
61526
- string4(request[field], `Skill ${field}`, DECIMAL);
61527
- 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({
61528
62463
  chainId: plan.chainId,
61529
62464
  to: plan.to,
61530
62465
  data: plan.data,
@@ -61574,9 +62509,9 @@ function assetPlan(value, walletAddress2) {
61574
62509
  ], "Skill asset plan");
61575
62510
  const chainId = assertAuthority(plan, "asset_upload", walletAddress2, false);
61576
62511
  const skillId = string4(plan.skillId, "Skill id", /^[1-9][0-9]*$/u);
61577
- if (plan.assetKind !== "cover" || plan.maxBytes !== 5242880) throw new TypeError("Skill cover authority is invalid.");
62512
+ if (plan.assetKind !== "cover" || typeof plan.maxBytes !== "number" || !Number.isSafeInteger(plan.maxBytes) || plan.maxBytes < 1) throw new TypeError("Skill cover authority is invalid.");
61578
62513
  const accepted = plan.acceptedMediaTypes;
61579
- if (!Array.isArray(accepted) || JSON.stringify(accepted) !== JSON.stringify(["image/png", "image/jpeg", "image/webp", "image/gif"])) {
62514
+ if (!Array.isArray(accepted) || accepted.length < 1 || new Set(accepted).size !== accepted.length || accepted.some((mediaType) => typeof mediaType !== "string" || !/^image\/[a-z0-9.+-]+$/u.test(mediaType))) {
61580
62515
  throw new TypeError("Skill cover media authority is invalid.");
61581
62516
  }
61582
62517
  const action = object5(plan.localAction, "Skill local action");
@@ -61624,11 +62559,11 @@ function recoveryReceipt(value, name) {
61624
62559
  });
61625
62560
  }
61626
62561
  function recoveryRequest(value, action, name, chainId) {
61627
- const request = object5(value, name);
61628
- 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) {
61629
62564
  throw new TypeError(`${name} authority is invalid.`);
61630
62565
  }
61631
- return { ...request, chainId };
62566
+ return { ...request2, chainId };
61632
62567
  }
61633
62568
  function canonical2(value) {
61634
62569
  if (Array.isArray(value)) return `[${value.map(canonical2).join(",")}]`;
@@ -61794,12 +62729,12 @@ var init_skill_local_flow = __esm({
61794
62729
  async recoverPublication(fingerprint2, context) {
61795
62730
  return this.publication((progress) => this.recoverWithProgress(fingerprint2, context, progress));
61796
62731
  }
61797
- async send(context, action, request, prepared, authority, onBroadcast) {
62732
+ async send(context, action, request2, prepared, authority, onBroadcast) {
61798
62733
  return required3(this.sender.submitPrepared, "Skill prepared-intent sender").call(this.sender, {
61799
62734
  privateKey: context.privateKey,
61800
62735
  walletAddress: context.walletAddress,
61801
62736
  action,
61802
- request,
62737
+ request: request2,
61803
62738
  intent: authority === void 0 ? intent(prepared, context.walletAddress) : legacyIntent(prepared, context.walletAddress, authority),
61804
62739
  onBroadcast
61805
62740
  });
@@ -61932,14 +62867,14 @@ var init_skill_local_flow = __esm({
61932
62867
  };
61933
62868
  }
61934
62869
  async settle(read2, name) {
61935
- for (let attempt = 0; attempt < 60; attempt += 1) {
62870
+ for (let attempt2 = 0; attempt2 < 60; attempt2 += 1) {
61936
62871
  if (await read2()) return;
61937
62872
  await this.pause();
61938
62873
  }
61939
62874
  throw new TypeError(`${name} transaction confirmed but the settled chain read did not advance.`);
61940
62875
  }
61941
- async verify(context, action, request, receipt) {
61942
- 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 });
61943
62878
  }
61944
62879
  async save(fingerprint2, journal) {
61945
62880
  await required3(this.recovery, "Skill publication recovery").saveSkillPublicationRecovery(fingerprint2, journal);
@@ -61947,14 +62882,14 @@ var init_skill_local_flow = __esm({
61947
62882
  async project(chainId, transactionHash3, bearer) {
61948
62883
  await this.api.confirmSkillProjection?.(chainId, transactionHash3, bearer);
61949
62884
  }
61950
- async stage(progress, context, fingerprint2, journal, stage, action, request, prepare) {
62885
+ async stage(progress, context, fingerprint2, journal, stage, action, request2, prepare) {
61951
62886
  progress.journal = journal;
61952
62887
  progress.fingerprint = fingerprint2;
61953
62888
  progress.journalSaved = true;
61954
62889
  progress.phase = "transaction";
61955
62890
  const existing = journal.receipts[stage];
61956
62891
  if (existing !== null) {
61957
- journal.receipts[stage] = await this.verify(context, action, request, existing);
62892
+ journal.receipts[stage] = await this.verify(context, action, request2, existing);
61958
62893
  if (journal.pendingStage === stage) journal.pendingStage = null;
61959
62894
  await this.save(fingerprint2, journal);
61960
62895
  progress.uncertain = false;
@@ -61984,7 +62919,7 @@ var init_skill_local_flow = __esm({
61984
62919
  journal.receipts[stage] = await this.send(
61985
62920
  context,
61986
62921
  action,
61987
- request,
62922
+ request2,
61988
62923
  prepared,
61989
62924
  journal.signingAuthority,
61990
62925
  async ({ transactionHash: transactionHash3 }) => {
@@ -62158,7 +63093,7 @@ var init_skill_local_flow = __esm({
62158
63093
  }
62159
63094
  async publishWithProgress(path2, planValue, context, progress) {
62160
63095
  const plan = publishPlan(planValue, context);
62161
- const request = plan.request;
63096
+ const request2 = plan.request;
62162
63097
  const fingerprint2 = recoveryFingerprint2("publish", planValue, context.walletAddress);
62163
63098
  const store = required3(this.recovery, "Skill publication recovery");
62164
63099
  progress.phase = "recovery";
@@ -62170,8 +63105,8 @@ var init_skill_local_flow = __esm({
62170
63105
  }
62171
63106
  progress.phase = "source";
62172
63107
  const selected = await readPublishablePath(path2);
62173
- const expectedSourceKind = sourceKind(request.sourceKind);
62174
- const mode = contentMode(request.contentMode);
63108
+ const expectedSourceKind = sourceKind(request2.sourceKind);
63109
+ const mode = contentMode(request2.contentMode);
62175
63110
  if (selected.sourceKind !== expectedSourceKind) throw new TypeError(`Skill plan requires a ${expectedSourceKind} source.`);
62176
63111
  progress.phase = "packaging";
62177
63112
  const packaged = await this.package(selected.files, prior === null ? mode : "plaintext", selected.excluded);
@@ -62186,14 +63121,14 @@ var init_skill_local_flow = __esm({
62186
63121
  files: selected.files,
62187
63122
  archive: packaged.archive,
62188
63123
  version: 1,
62189
- name: String(request.name),
62190
- summary: request.summary === void 0 ? "" : String(request.summary),
63124
+ name: String(request2.name),
63125
+ summary: request2.summary === void 0 ? "" : String(request2.summary),
62191
63126
  pinBundle: async (bytes) => {
62192
63127
  publishedBytes = bytes;
62193
63128
  progress.phase = "upload";
62194
63129
  return this.upload({
62195
63130
  bytes,
62196
- filename: `${request.slug}.skillroot.zip`,
63131
+ filename: `${request2.slug}.skillroot.zip`,
62197
63132
  bearer: context.bearer,
62198
63133
  objectKind: "package",
62199
63134
  sourceKind: "file",
@@ -62204,12 +63139,12 @@ var init_skill_local_flow = __esm({
62204
63139
  const packageURI = entry2.packageURI;
62205
63140
  const manifestURI = await this.upload({
62206
63141
  bytes: serializeManifest(buildManifest([entry2])),
62207
- filename: `${request.slug}.versions.json`,
63142
+ filename: `${request2.slug}.versions.json`,
62208
63143
  bearer: context.bearer,
62209
63144
  objectKind: "manifest"
62210
63145
  });
62211
63146
  const chainMetadata = Object.fromEntries(
62212
- Object.entries(request).filter(([key]) => key !== "sourceKind" && key !== "contentMode" && key !== "summary")
63147
+ Object.entries(request2).filter(([key]) => key !== "sourceKind" && key !== "contentMode" && key !== "summary")
62213
63148
  );
62214
63149
  const createRequest = {
62215
63150
  action: "createSkill",
@@ -62262,11 +63197,11 @@ var init_skill_local_flow = __esm({
62262
63197
  skillId = await required3(this.api.resolveSkillId, "Skill resolve API").call(
62263
63198
  this.api,
62264
63199
  journal.chainId,
62265
- String(request.slug),
63200
+ String(request2.slug),
62266
63201
  context.bearer
62267
63202
  );
62268
63203
  return skillId !== null;
62269
- }, `Skill ${request.slug} publication`);
63204
+ }, `Skill ${request2.slug} publication`);
62270
63205
  if (skillId === null) throw new TypeError("Published Skill slug did not resolve.");
62271
63206
  if (journal.skillId !== null && journal.skillId !== skillId) throw new TypeError("Skill publication recovery resolved a different Skill id.");
62272
63207
  journal.skillId = skillId;
@@ -62484,15 +63419,15 @@ var init_skill_local_flow = __esm({
62484
63419
  bearer: context.bearer,
62485
63420
  objectKind: "manifest"
62486
63421
  });
62487
- 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 };
62488
63423
  progress.phase = "intent";
62489
- 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);
62490
63425
  progress.phase = "transaction";
62491
63426
  progress.uncertain = true;
62492
63427
  const submission = await this.send(
62493
63428
  context,
62494
63429
  "setSkillURI",
62495
- request,
63430
+ request2,
62496
63431
  prepared,
62497
63432
  plan.signingAuthority,
62498
63433
  async ({ transactionHash: transactionHash3 }) => {
@@ -62513,6 +63448,7 @@ var init_skill_local_flow = __esm({
62513
63448
  if (!stat.isFile() || stat.isSymbolicLink()) throw new TypeError("Skill cover path must be one regular file.");
62514
63449
  if (stat.size < 1 || stat.size > plan.maxBytes) throw new TypeError("Skill cover size is outside the prepared bound.");
62515
63450
  const bytes = new Uint8Array(await readFile2(absolute));
63451
+ if (bytes.byteLength < 1 || bytes.byteLength > plan.maxBytes) throw new TypeError("Skill cover size is outside the prepared bound.");
62516
63452
  const mediaType = detectedImageMediaType(bytes);
62517
63453
  if (mediaType === null || !plan.acceptedMediaTypes.includes(mediaType)) {
62518
63454
  throw new TypeError("Skill cover bytes do not match an accepted image type.");
@@ -62626,12 +63562,14 @@ async function resolveInstalledProfile(readProfile) {
62626
63562
  throw cause;
62627
63563
  }
62628
63564
  }
62629
- function commandNeedsHttp(arguments_) {
63565
+ function commandNeedsHttp(allArguments) {
63566
+ const arguments_ = finchOwnArguments(allArguments);
62630
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;
62631
63568
  return (arguments_[0] !== "wallet" || arguments_[1] === "use") && !(arguments_.length === 2 && arguments_[0] === "logout" && arguments_[1] === "--local");
62632
63569
  }
62633
63570
  async function runInstalledCli(arguments_, environment3 = process.env, authorities = {}) {
62634
- 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;
62635
63573
  if (profileFree) return routeCommand(arguments_, {});
62636
63574
  const home = resolveFinchtechHome(environment3);
62637
63575
  const state = new LocalCliState(home);
@@ -62658,7 +63596,10 @@ async function runInstalledCli(arguments_, environment3 = process.env, authoriti
62658
63596
  taskProtocolSender: new InstalledTaskProtocolSender(),
62659
63597
  skillIntentSender,
62660
63598
  skillLocalFlow: profile === void 0 || skillIntentSender === void 0 ? void 0 : new SkillLocalFlow(api, skillIntentSender, signer, void 0, void 0, state),
62661
- browserLauncher: new InstalledBrowserLauncher()
63599
+ browserLauncher: new InstalledBrowserLauncher(),
63600
+ callbackDelivery: new LoopbackCallbackDelivery(),
63601
+ mcpLoginProcess: new InstalledMcpLoginProcess(),
63602
+ stdin: new ProcessStdinReader()
62662
63603
  });
62663
63604
  return routeCommand(arguments_, application);
62664
63605
  }
@@ -62668,6 +63609,9 @@ var init_main = __esm({
62668
63609
  init_api2();
62669
63610
  init_application();
62670
63611
  init_command_router();
63612
+ init_loopback_callback();
63613
+ init_mcp_login_process();
63614
+ init_stdin_reader();
62671
63615
  init_local_state();
62672
63616
  init_state();
62673
63617
  init_signing();
@@ -62831,6 +63775,22 @@ function emitCliOutcome(outcome, sinks) {
62831
63775
  `);
62832
63776
  return AGENT_CLI_OUTPUT_CONTRACT.exitCodes.remoteOrProviderUnavailable;
62833
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
+ }
62834
63794
  if (outcome instanceof CliHttpError && outcome.envelope !== null && outcome.status !== null) {
62835
63795
  sinks.stdout(`${JSON.stringify(outcome.envelope)}
62836
63796
  `);