@getmagical/cli 0.1.13 → 0.1.15

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/README.md CHANGED
@@ -69,10 +69,6 @@ Once installed, users can update from the same channel with:
69
69
  mgcl --update
70
70
  ```
71
71
 
72
- Installed CLIs also check the configured npm dist-tag before running
73
- subcommands. If the local version is behind, `mgcl` blocks the command and
74
- asks the user to run `mgcl update` before rerunning it.
75
-
76
72
  To remove the managed install:
77
73
 
78
74
  ```bash
package/dist/index.js CHANGED
@@ -6885,6 +6885,7 @@ function getErrorMessage(error) {
6885
6885
  }
6886
6886
 
6887
6887
  // src/program.ts
6888
+ import { readFile as readFile4 } from "fs/promises";
6888
6889
  import path6 from "path";
6889
6890
 
6890
6891
  // ../common/dist/src/stdlib/json.util.js
@@ -7714,6 +7715,7 @@ ${agentLimitationsSelection}
7714
7715
  taskQueue
7715
7716
  waitUponQueueing
7716
7717
  queueableAgentIds
7718
+ systemPrompt
7717
7719
  additionalSystemPrompt
7718
7720
  ignoreUnstableSessionState
7719
7721
  }
@@ -7777,6 +7779,7 @@ ${agentLimitationsSelection}
7777
7779
  taskQueue
7778
7780
  waitUponQueueing
7779
7781
  queueableAgentIds
7782
+ systemPrompt
7780
7783
  additionalSystemPrompt
7781
7784
  ignoreUnstableSessionState
7782
7785
  }
@@ -8686,6 +8689,8 @@ import { Command as Command2, InvalidArgumentError as InvalidArgumentError2, Opt
8686
8689
 
8687
8690
  // src/api.ts
8688
8691
  import { z as z3 } from "zod";
8692
+ var OTTO_AUTHORIZATION_HEADER_NAME = "X-Otto-Authorization";
8693
+ var OTTO_AUTHORIZATION_ISSUER = "magical:otto";
8689
8694
  var workosOrganizationsResponseSchema = z3.object({
8690
8695
  organizations: z3.array(
8691
8696
  z3.object({
@@ -8752,6 +8757,50 @@ function getApiErrorDetail(responseBody) {
8752
8757
  function trimTrailingSlash(value) {
8753
8758
  return value.replace(/\/+$/u, "");
8754
8759
  }
8760
+ function isRecord2(value) {
8761
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8762
+ }
8763
+ function decodeJwtPayload(token) {
8764
+ const [, payloadSegment] = token.split(".");
8765
+ if (!payloadSegment) {
8766
+ return null;
8767
+ }
8768
+ const payloadResult = safeJsonParse(
8769
+ Buffer.from(payloadSegment, "base64url").toString("utf8")
8770
+ );
8771
+ if (isErr(payloadResult)) {
8772
+ return null;
8773
+ }
8774
+ return isRecord2(payloadResult.value) ? payloadResult.value : null;
8775
+ }
8776
+ function isOttoAuthorizationToken(token) {
8777
+ return decodeJwtPayload(token)?.["iss"] === OTTO_AUTHORIZATION_ISSUER;
8778
+ }
8779
+ function applyAuthenticationHeaders({
8780
+ accessToken,
8781
+ allowOttoAuthorization,
8782
+ headers,
8783
+ impersonatedOrganizationId,
8784
+ organizationId
8785
+ }) {
8786
+ if (!isOttoAuthorizationToken(accessToken)) {
8787
+ headers.set("authorization", `Bearer ${accessToken}`);
8788
+ if (impersonatedOrganizationId) {
8789
+ headers.set("x-organization-id", impersonatedOrganizationId);
8790
+ }
8791
+ return;
8792
+ }
8793
+ if (!allowOttoAuthorization) {
8794
+ throw new CliError(
8795
+ "Otto authorization is only supported for GraphQL requests."
8796
+ );
8797
+ }
8798
+ if (!organizationId) {
8799
+ throw new CliError("Otto authorization requires an organization ID.");
8800
+ }
8801
+ headers.set(OTTO_AUTHORIZATION_HEADER_NAME, `Bearer ${accessToken}`);
8802
+ headers.set("x-organization-id", organizationId);
8803
+ }
8755
8804
  function createMagicalApiClient({
8756
8805
  apiBaseUrl,
8757
8806
  fetchFn = fetch
@@ -8759,12 +8808,21 @@ function createMagicalApiClient({
8759
8808
  const resolveApiBaseUrl = typeof apiBaseUrl === "string" ? () => apiBaseUrl : apiBaseUrl;
8760
8809
  async function fetchJson({
8761
8810
  accessToken,
8811
+ impersonatedOrganizationId,
8812
+ allowOttoAuthorization,
8762
8813
  path: path7,
8763
- init
8814
+ init,
8815
+ organizationId
8764
8816
  }) {
8765
8817
  const url = `${trimTrailingSlash(await resolveApiBaseUrl())}${path7}`;
8766
8818
  const headers = new Headers(init?.headers);
8767
- headers.set("authorization", `Bearer ${accessToken}`);
8819
+ applyAuthenticationHeaders({
8820
+ accessToken,
8821
+ ...allowOttoAuthorization ? { allowOttoAuthorization } : {},
8822
+ headers,
8823
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
8824
+ ...organizationId ? { organizationId } : {}
8825
+ });
8768
8826
  const response = await fetchFn(url, {
8769
8827
  ...init,
8770
8828
  headers
@@ -8801,6 +8859,8 @@ function createMagicalApiClient({
8801
8859
  return {
8802
8860
  async executeGraphQl({
8803
8861
  accessToken,
8862
+ impersonatedOrganizationId,
8863
+ organizationId,
8804
8864
  query,
8805
8865
  resultKey,
8806
8866
  variables
@@ -8810,6 +8870,9 @@ function createMagicalApiClient({
8810
8870
  const parsedResponse = graphQlResponseSchema.safeParse(
8811
8871
  await fetchJson({
8812
8872
  accessToken,
8873
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
8874
+ allowOttoAuthorization: true,
8875
+ ...organizationId ? { organizationId } : {},
8813
8876
  path: "/graphql",
8814
8877
  init: {
8815
8878
  method: "POST",
@@ -8849,11 +8912,13 @@ function createMagicalApiClient({
8849
8912
  },
8850
8913
  async fetchUser({
8851
8914
  accessToken,
8915
+ organizationId,
8852
8916
  userId
8853
8917
  }) {
8854
8918
  const parsedResponse = workosUserSchema.safeParse(
8855
8919
  await fetchJson({
8856
8920
  accessToken,
8921
+ ...organizationId ? { organizationId } : {},
8857
8922
  path: `/workos/user/${userId}`
8858
8923
  })
8859
8924
  );
@@ -8863,11 +8928,15 @@ function createMagicalApiClient({
8863
8928
  return parsedResponse.data;
8864
8929
  },
8865
8930
  async listNangoIntegrations({
8866
- accessToken
8931
+ accessToken,
8932
+ impersonatedOrganizationId,
8933
+ organizationId
8867
8934
  }) {
8868
8935
  const parsedResponse = nangoIntegrationsResponseSchema.safeParse(
8869
8936
  await fetchJson({
8870
8937
  accessToken,
8938
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
8939
+ ...organizationId ? { organizationId } : {},
8871
8940
  path: "/nango/integrations"
8872
8941
  })
8873
8942
  );
@@ -8877,11 +8946,15 @@ function createMagicalApiClient({
8877
8946
  return parsedResponse.data;
8878
8947
  },
8879
8948
  async listNangoAuthentications({
8880
- accessToken
8949
+ accessToken,
8950
+ impersonatedOrganizationId,
8951
+ organizationId
8881
8952
  }) {
8882
8953
  const parsedResponse = organizationAuthenticationsResponseSchema.safeParse(
8883
8954
  await fetchJson({
8884
8955
  accessToken,
8956
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
8957
+ ...organizationId ? { organizationId } : {},
8885
8958
  path: "/authentications/organization?type=nangoConnection"
8886
8959
  })
8887
8960
  );
@@ -9199,6 +9272,22 @@ function resolveOpenCommand(url) {
9199
9272
 
9200
9273
  // src/program-session.ts
9201
9274
  import { readFile as readFile2, rm as rm2 } from "fs/promises";
9275
+
9276
+ // ../common/dist/src/stdlib/url.utils.js
9277
+ var import_handlebars = __toESM(require_lib(), 1);
9278
+ function safeUrlConstructor(url, baseUrl) {
9279
+ try {
9280
+ return Ok(baseUrl ? new URL(url, baseUrl) : new URL(url));
9281
+ } catch {
9282
+ return Err({
9283
+ type: "invalid-url",
9284
+ message: `Invalid URL`,
9285
+ url
9286
+ });
9287
+ }
9288
+ }
9289
+
9290
+ // src/program-session.ts
9202
9291
  async function withOrgScopedAccessToken({
9203
9292
  dependencies,
9204
9293
  organizationId,
@@ -9263,10 +9352,20 @@ async function loadDirectAccessToken({
9263
9352
  if (!accessTokenFileContents) {
9264
9353
  return null;
9265
9354
  }
9266
- const claims = dependencies.authClient.decodeAccessTokenClaims(
9267
- accessTokenFileContents
9355
+ const claimsResult = fromThrowable(
9356
+ () => dependencies.authClient.decodeAccessTokenClaims(accessTokenFileContents),
9357
+ "decode-otto-session-access-token-failed"
9268
9358
  );
9359
+ if (isErr(claimsResult)) {
9360
+ return null;
9361
+ }
9362
+ const claims = claimsResult.value;
9269
9363
  if (isExpiredAccessTokenClaims(claims)) {
9364
+ if (claims.iss === "magical:otto") {
9365
+ throw new CliError(
9366
+ "The Otto session authorization token expired. Start a new Otto session from Magical."
9367
+ );
9368
+ }
9270
9369
  return null;
9271
9370
  }
9272
9371
  if (claims.org_id && claims.org_id !== organizationId) {
@@ -9288,29 +9387,10 @@ import { spawn as spawn2 } from "child_process";
9288
9387
  import fs from "fs";
9289
9388
  import path3 from "path";
9290
9389
  import { fileURLToPath } from "url";
9291
-
9292
- // ../common/dist/src/stdlib/url.utils.js
9293
- var import_handlebars = __toESM(require_lib(), 1);
9294
- function safeUrlConstructor(url, baseUrl) {
9295
- try {
9296
- return Ok(baseUrl ? new URL(url, baseUrl) : new URL(url));
9297
- } catch {
9298
- return Err({
9299
- type: "invalid-url",
9300
- message: `Invalid URL`,
9301
- url
9302
- });
9303
- }
9304
- }
9305
-
9306
- // src/self-update.ts
9307
9390
  var CLI_PACKAGE_NAME = "@getmagical/cli";
9308
9391
  var DEFAULT_CLI_DIST_TAG2 = "latest";
9309
9392
  var DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org/";
9310
9393
  var MANAGED_NODE_SUBPATH = "runtime/node";
9311
- function isRecord2(value) {
9312
- return typeof value === "object" && value !== null && !Array.isArray(value);
9313
- }
9314
9394
  function resolveInstalledPackageRoot({
9315
9395
  entryFilePath,
9316
9396
  packageName
@@ -9351,154 +9431,6 @@ function resolveInstallPrefixFromPackageRoot(packageRootPath) {
9351
9431
  currentPath = parentPath;
9352
9432
  }
9353
9433
  }
9354
- function readInstalledPackageVersion({
9355
- packageName,
9356
- packageRootPath
9357
- }) {
9358
- const packageManifestPath2 = path3.join(packageRootPath, "package.json");
9359
- if (!fs.existsSync(packageManifestPath2)) {
9360
- throw new CliError(
9361
- `Installed package metadata was not found at ${packageManifestPath2}. Reinstall mgcl and try again.`
9362
- );
9363
- }
9364
- const packageManifestResult2 = safeJsonParse(
9365
- fs.readFileSync(packageManifestPath2, "utf8")
9366
- );
9367
- if (isErr(packageManifestResult2)) {
9368
- throw new CliError(`Failed to parse ${packageManifestPath2}.`, {
9369
- cause: packageManifestResult2.error.cause
9370
- });
9371
- }
9372
- const packageManifest = packageManifestResult2.value;
9373
- if (packageManifest.name !== packageName) {
9374
- throw new CliError(
9375
- `Expected installed package ${packageName} at ${packageManifestPath2}. Reinstall mgcl and try again.`
9376
- );
9377
- }
9378
- if (typeof packageManifest.version !== "string" || !packageManifest.version) {
9379
- throw new CliError(
9380
- `Installed package version is missing from ${packageManifestPath2}. Reinstall mgcl and try again.`
9381
- );
9382
- }
9383
- return packageManifest.version;
9384
- }
9385
- function parseVersionSegment(segment, version) {
9386
- if (!/^\d+$/u.test(segment)) {
9387
- throw new CliError(`Invalid CLI version "${version}".`);
9388
- }
9389
- return Number(segment);
9390
- }
9391
- function parseSemanticVersion(version) {
9392
- const normalizedVersion = version.trim().replace(/^v/u, "");
9393
- const [versionWithoutBuildMetadata = ""] = normalizedVersion.split("+");
9394
- if (!versionWithoutBuildMetadata) {
9395
- throw new CliError(`Invalid CLI version "${version}".`);
9396
- }
9397
- const [releasePart, prereleasePart] = versionWithoutBuildMetadata.split("-");
9398
- if (!releasePart) {
9399
- throw new CliError(`Invalid CLI version "${version}".`);
9400
- }
9401
- return {
9402
- prerelease: prereleasePart ? prereleasePart.split(".") : null,
9403
- release: releasePart.split(".").map((segment) => parseVersionSegment(segment, version))
9404
- };
9405
- }
9406
- function comparePrereleaseIdentifiers(left, right) {
9407
- const leftIsNumeric = /^\d+$/u.test(left);
9408
- const rightIsNumeric = /^\d+$/u.test(right);
9409
- if (leftIsNumeric && rightIsNumeric) {
9410
- return Number(left) - Number(right);
9411
- }
9412
- if (leftIsNumeric) {
9413
- return -1;
9414
- }
9415
- if (rightIsNumeric) {
9416
- return 1;
9417
- }
9418
- return left.localeCompare(right);
9419
- }
9420
- function compareSemanticVersions(leftVersion, rightVersion) {
9421
- const left = parseSemanticVersion(leftVersion);
9422
- const right = parseSemanticVersion(rightVersion);
9423
- const releaseLength = Math.max(left.release.length, right.release.length);
9424
- for (let index = 0; index < releaseLength; index += 1) {
9425
- const difference = (left.release[index] ?? 0) - (right.release[index] ?? 0);
9426
- if (difference !== 0) {
9427
- return difference;
9428
- }
9429
- }
9430
- if (!left.prerelease && !right.prerelease) {
9431
- return 0;
9432
- }
9433
- if (!left.prerelease) {
9434
- return 1;
9435
- }
9436
- if (!right.prerelease) {
9437
- return -1;
9438
- }
9439
- const prereleaseLength = Math.max(
9440
- left.prerelease.length,
9441
- right.prerelease.length
9442
- );
9443
- for (let index = 0; index < prereleaseLength; index += 1) {
9444
- const leftIdentifier = left.prerelease[index];
9445
- const rightIdentifier = right.prerelease[index];
9446
- if (leftIdentifier === void 0) {
9447
- return -1;
9448
- }
9449
- if (rightIdentifier === void 0) {
9450
- return 1;
9451
- }
9452
- const difference = comparePrereleaseIdentifiers(
9453
- leftIdentifier,
9454
- rightIdentifier
9455
- );
9456
- if (difference !== 0) {
9457
- return difference;
9458
- }
9459
- }
9460
- return 0;
9461
- }
9462
- async function fetchPublishedPackageVersion({
9463
- distTag,
9464
- fetchFn = fetch,
9465
- packageName,
9466
- registryUrl
9467
- }) {
9468
- const distTagUrlResult = safeUrlConstructor(
9469
- `${registryUrl.replace(/\/?$/u, "/")}-/package/${encodeURIComponent(packageName)}/dist-tags`
9470
- );
9471
- if (isErr(distTagUrlResult)) {
9472
- throw new CliError(`Invalid npm registry URL "${registryUrl}".`);
9473
- }
9474
- const response = await fetchFn(distTagUrlResult.value, {
9475
- headers: {
9476
- accept: "application/json"
9477
- }
9478
- });
9479
- if (!response.ok) {
9480
- throw new CliError(
9481
- `Could not check the latest published mgcl version (status ${response.status}).`
9482
- );
9483
- }
9484
- const distTagsResult = safeJsonParse(await response.text());
9485
- if (isErr(distTagsResult)) {
9486
- throw new CliError("Could not parse the npm dist-tags response for mgcl.", {
9487
- cause: distTagsResult.error.cause
9488
- });
9489
- }
9490
- if (!isRecord2(distTagsResult.value)) {
9491
- throw new CliError("Could not parse the npm dist-tags response for mgcl.");
9492
- }
9493
- const distTags = distTagsResult.value;
9494
- const publishedVersion = distTags[distTag];
9495
- if (typeof publishedVersion !== "string" || publishedVersion.length === 0) {
9496
- throw new CliError(
9497
- `Could not find npm dist-tag "${distTag}" for ${packageName}.`
9498
- );
9499
- }
9500
- return publishedVersion;
9501
- }
9502
9434
  function resolveNpmCommandFromPath() {
9503
9435
  return {
9504
9436
  argsPrefix: [],
@@ -9612,45 +9544,6 @@ async function selfUpdateInstalledCli({
9612
9544
  registryUrl
9613
9545
  });
9614
9546
  }
9615
- async function getInstalledCliUpdateRequirement({
9616
- distTag = DEFAULT_CLI_DIST_TAG2,
9617
- entryFilePath = fileURLToPath(import.meta.url),
9618
- fetchFn = fetch,
9619
- packageName = CLI_PACKAGE_NAME,
9620
- registryUrl = DEFAULT_NPM_REGISTRY_URL
9621
- } = {}) {
9622
- const packageRootPath = resolveInstalledPackageRoot({
9623
- entryFilePath,
9624
- packageName
9625
- });
9626
- if (!packageRootPath) {
9627
- return null;
9628
- }
9629
- const installedVersion = readInstalledPackageVersion({
9630
- packageName,
9631
- packageRootPath
9632
- });
9633
- const publishedVersionResult = await fromThrowable(
9634
- async () => fetchPublishedPackageVersion({
9635
- distTag,
9636
- fetchFn,
9637
- packageName,
9638
- registryUrl
9639
- }),
9640
- "cli-update-check-failed"
9641
- );
9642
- if (isErr(publishedVersionResult)) {
9643
- return null;
9644
- }
9645
- const publishedVersion = publishedVersionResult.value;
9646
- if (compareSemanticVersions(installedVersion, publishedVersion) >= 0) {
9647
- return null;
9648
- }
9649
- return {
9650
- installedVersion,
9651
- latestVersion: publishedVersion
9652
- };
9653
- }
9654
9547
 
9655
9548
  // src/settings-command.ts
9656
9549
  import { Command, InvalidArgumentError, Option } from "commander";
@@ -9911,6 +9804,7 @@ var tokenErrorSchema = z6.object({
9911
9804
  });
9912
9805
  var accessTokenClaimsSchema = z6.object({
9913
9806
  exp: z6.number().int().positive().optional(),
9807
+ iss: z6.string().min(1).optional(),
9914
9808
  org_id: z6.string().min(1).optional(),
9915
9809
  sid: z6.string().min(1).optional(),
9916
9810
  sub: z6.string().min(1)
@@ -10251,39 +10145,16 @@ async function handleSelfUpdate(dependencies, options) {
10251
10145
  `Updated mgcl via npm (${updateResult.packageSpecifier}) in ${updateResult.installPrefix}.`
10252
10146
  );
10253
10147
  }
10254
- function isRootUpdateCommand(program2, actionCommand) {
10255
- return actionCommand.parent === program2 && actionCommand.name() === "update";
10256
- }
10257
- async function enforceLatestCliVersionIfNeeded({
10258
- dependencies,
10259
- program: program2,
10260
- actionCommand
10261
- }) {
10262
- if (actionCommand === program2 || isRootUpdateCommand(program2, actionCommand)) {
10263
- return;
10264
- }
10265
- const updateRequirement = await dependencies.ensureLatestCliVersion?.();
10266
- if (!updateRequirement) {
10267
- return;
10268
- }
10269
- throw new CliError(
10270
- `mgcl ${updateRequirement.installedVersion} is outdated. Upgrade to ${updateRequirement.latestVersion} with "mgcl update", then rerun your command.`
10271
- );
10272
- }
10273
10148
  async function handleOperationCommand(dependencies, operationSpec, commandOptions) {
10274
- const state = requireLoggedInState(await dependencies.stateStore.load());
10275
- const organization = resolveSelectedOrganization({
10276
- state,
10277
- ...commandOptions.org ? { organizationSelector: commandOptions.org } : {}
10278
- });
10279
- const variables = collectOperationVariables(operationSpec, commandOptions);
10280
- const { accessToken } = await withOrgScopedAccessToken({
10149
+ const { accessToken, impersonatedOrganizationId, organization, state } = await withSelectedOrganizationAndAccessToken({
10281
10150
  dependencies,
10282
- organizationId: organization.id,
10283
- state
10151
+ options: commandOptions
10284
10152
  });
10153
+ const variables = collectOperationVariables(operationSpec, commandOptions);
10285
10154
  const result = await dependencies.apiClient.executeGraphQl({
10286
10155
  accessToken,
10156
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
10157
+ organizationId: organization.id,
10287
10158
  query: operationSpec.document,
10288
10159
  resultKey: operationSpec.cli.resultKey,
10289
10160
  variables
@@ -10307,12 +10178,19 @@ async function withSelectedOrganizationAndAccessToken({
10307
10178
  state,
10308
10179
  ...options.org ? { organizationSelector: options.org } : {}
10309
10180
  });
10181
+ const authenticatedOrganizationId = await resolveDirectAccessTokenOrganizationId({ dependencies });
10182
+ const shouldImpersonateOrganization = authenticatedOrganizationId !== null && organization.id !== authenticatedOrganizationId;
10310
10183
  const { accessToken } = await withOrgScopedAccessToken({
10311
10184
  dependencies,
10312
- organizationId: organization.id,
10185
+ organizationId: shouldImpersonateOrganization && authenticatedOrganizationId ? authenticatedOrganizationId : organization.id,
10313
10186
  state
10314
10187
  });
10315
- return { accessToken, organization, state };
10188
+ return {
10189
+ accessToken,
10190
+ ...shouldImpersonateOrganization ? { impersonatedOrganizationId: organization.id } : {},
10191
+ organization,
10192
+ state
10193
+ };
10316
10194
  }
10317
10195
  function writeCommandOutput({
10318
10196
  dependencies,
@@ -10326,12 +10204,16 @@ function writeCommandOutput({
10326
10204
  dependencies.io.info(formatHumanReadableOutput(result));
10327
10205
  }
10328
10206
  async function handleNangoIntegrationsListCommand(dependencies, options) {
10329
- const { accessToken, organization, state } = await withSelectedOrganizationAndAccessToken({ dependencies, options });
10207
+ const { accessToken, impersonatedOrganizationId, organization, state } = await withSelectedOrganizationAndAccessToken({ dependencies, options });
10330
10208
  const listNangoIntegrations = requireApiClientMethod(
10331
10209
  dependencies.apiClient,
10332
10210
  "listNangoIntegrations"
10333
10211
  );
10334
- const integrations = await listNangoIntegrations({ accessToken });
10212
+ const integrations = await listNangoIntegrations({
10213
+ accessToken,
10214
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
10215
+ organizationId: organization.id
10216
+ });
10335
10217
  await saveLastUsedOrganization({
10336
10218
  dependencies,
10337
10219
  organizationId: organization.id,
@@ -10354,13 +10236,15 @@ function normalizeListedNangoAuthentication(authentication) {
10354
10236
  };
10355
10237
  }
10356
10238
  async function handleNangoAuthsListCommand(dependencies, options) {
10357
- const { accessToken, organization, state } = await withSelectedOrganizationAndAccessToken({ dependencies, options });
10239
+ const { accessToken, impersonatedOrganizationId, organization, state } = await withSelectedOrganizationAndAccessToken({ dependencies, options });
10358
10240
  const listNangoAuthentications = requireApiClientMethod(
10359
10241
  dependencies.apiClient,
10360
10242
  "listNangoAuthentications"
10361
10243
  );
10362
10244
  const organizationAuthentications = await listNangoAuthentications({
10363
- accessToken
10245
+ accessToken,
10246
+ ...impersonatedOrganizationId ? { impersonatedOrganizationId } : {},
10247
+ organizationId: organization.id
10364
10248
  });
10365
10249
  const authentications = organizationAuthentications.filter((authentication) => {
10366
10250
  if (options.integration && authentication.providerConfigKey !== options.integration) {
@@ -10382,6 +10266,29 @@ async function handleNangoAuthsListCommand(dependencies, options) {
10382
10266
  result: authentications
10383
10267
  });
10384
10268
  }
10269
+ async function resolveDirectAccessTokenOrganizationId({
10270
+ dependencies
10271
+ }) {
10272
+ const { accessTokenFilePath } = dependencies.runtimeConfig;
10273
+ if (!accessTokenFilePath) {
10274
+ return null;
10275
+ }
10276
+ const accessToken = await readFile4(accessTokenFilePath, "utf8").then((value) => value.trim()).catch((error) => {
10277
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
10278
+ return null;
10279
+ }
10280
+ throw error;
10281
+ });
10282
+ if (!accessToken) {
10283
+ return null;
10284
+ }
10285
+ try {
10286
+ const claims = dependencies.authClient.decodeAccessTokenClaims(accessToken);
10287
+ return claims.org_id ?? null;
10288
+ } catch {
10289
+ return null;
10290
+ }
10291
+ }
10385
10292
  async function saveLastUsedOrganization({
10386
10293
  dependencies,
10387
10294
  organizationId,
@@ -10507,7 +10414,6 @@ function createDefaultDependencies() {
10507
10414
  accessTokenFilePath
10508
10415
  },
10509
10416
  refreshTokenStore: runtimeConfig.refreshTokenStoreKind === "file" ? createFileRefreshTokenStore(refreshTokenFilePath) : createKeytarRefreshTokenStore(runtimeConfig.keychainServiceName),
10510
- ensureLatestCliVersion: async () => getInstalledCliUpdateRequirement(selfUpdateOptions),
10511
10417
  settingsStore,
10512
10418
  selfUpdateCli: async () => selfUpdateInstalledCli(selfUpdateOptions),
10513
10419
  stateStore: createFileStateStore(runtimeConfig.stateFilePath)
@@ -10542,13 +10448,6 @@ ${formatOutputModesNote()}`
10542
10448
  }
10543
10449
  this.outputHelp();
10544
10450
  });
10545
- program2.hook("preAction", async (_command, actionCommand) => {
10546
- await enforceLatestCliVersionIfNeeded({
10547
- actionCommand,
10548
- dependencies,
10549
- program: program2
10550
- });
10551
- });
10552
10451
  const authCommand = configureCommandPresentation(
10553
10452
  new Command2("auth").description("Manage CLI authentication.")
10554
10453
  ).helpGroup("Workspace:").addHelpText(