@caplets/core 0.20.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.ts CHANGED
@@ -30,8 +30,8 @@ export type GenericAuthTarget = {
30
30
  requestTimeoutMs?: number | undefined;
31
31
  };
32
32
  export declare function staticRemoteHeaders(server: CapletServerConfig): Record<string, string>;
33
- export declare function oauthHeaders(server: CapletServerConfig, authDir?: string): Record<string, string>;
34
- export declare function genericOAuthHeaders(target: GenericAuthTarget, authDir?: string): Record<string, string>;
33
+ export declare function oauthHeaders(server: CapletServerConfig, authDir?: string): Promise<Record<string, string>>;
34
+ export declare function genericOAuthHeaders(target: GenericAuthTarget, authDir?: string): Promise<Record<string, string>>;
35
35
  export declare class FileOAuthProvider implements OAuthClientProvider {
36
36
  readonly server: CapletServerConfig;
37
37
  readonly redirectUrl: string;
@@ -1,4 +1,4 @@
1
- import { St as resolveProjectConfigPath, Y as loadConfigWithSources, bt as resolveConfigPath, mt as DEFAULT_COMPLETION_CACHE_DIR, pt as DEFAULT_AUTH_DIR, vn as __exportAll, yt as resolveCapletsRoot } from "./service-D0MwLNyb.js";
1
+ import { St as resolveProjectConfigPath, Y as loadConfigWithSources, bt as resolveConfigPath, mt as DEFAULT_COMPLETION_CACHE_DIR, pt as DEFAULT_AUTH_DIR, vn as __exportAll, yt as resolveCapletsRoot } from "./service-Bsq7R0mt.js";
2
2
  import { u as CapletsError } from "./validation-CdqbI2zN.js";
3
3
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { $ as parseConfig, $t as ReadResourceRequestSchema, A as QuickJsCodeModeSandbox, At as toJsonSchemaCompat, B as CapletsEngine, Bt as ErrorCode, C as nativeCapletToolName, Ct as ReadBuffer, D as codeModeRunInputSchema, Dt as AjvJsonSchemaValidator, Et as assertToolsCallTaskCapability, F as redactCodeModeLogText, Ft as CreateMessageResultWithToolsSchema, G as handleServerTool, Gt as LATEST_PROTOCOL_VERSION, H as decodeDirectResourceUri, Ht as InitializeRequestSchema, I as codeModeDeclarationHash, It as CreateTaskResultSchema, J as loadConfig, Jt as ListResourcesRequestSchema, K as ServerRegistry, Kt as ListPromptsRequestSchema, L as generateCodeModeDeclarations, M as createCodeModeCapletsApi, Mt as CallToolResultSchema, N as listCodeModeCallableCaplets, Nt as CompleteRequestSchema, O as codeModeRunParamsSchema, Ot as Protocol, P as CodeModeLogStore, Pt as CreateMessageResultSchema, Q as loadProjectConfig, Qt as McpError, R as generateCodeModeRunToolDescription, Rt as ElicitResultSchema, S as nativeCapletToolDescription, St as resolveProjectConfigPath, T as nativeCodeModeToolId, Tt as assertClientRequestTaskCapability, U as findProjectRoot, Ut as InitializedNotificationSchema, V as resolveExposure, Vt as GetPromptRequestSchema, W as fingerprintProjectRoot, Wt as JSONRPCMessageSchema, X as loadGlobalConfig, Xt as ListToolsRequestSchema, Y as loadConfigWithSources, Yt as ListRootsResultSchema, Z as loadLocalOverlayConfigWithSources, Zt as LoggingLevelSchema, _ as controlUrlForBase, _n as safeParseAsync, _t as defaultConfigBaseDir, a as projectBindingError, an as isJSONRPCErrorResponse, at as markdownStructuredContent, b as resolveCapletsServer, bt as resolveConfigPath, c as cloudAuthPath, cn as getLiteralValue, ct as startGenericOAuthFlow, d as CloudAuthClient, dn as getSchemaDescription, dt as isTokenBundleExpired, en as SUPPORTED_PROTOCOL_VERSIONS, et as discoverCapletFiles, fn as isSchemaOptional, ft as readTokenBundle, g as resolveCapletsRemote, gn as safeParse, gt as defaultCacheBaseDir, hn as objectFromShape, ht as DEFAULT_OBSERVED_OUTPUT_SHAPE_CACHE_DIR, i as ProjectBindingError, in as isInitializeRequest, it as markdownCallToolResultContent, j as diagnoseCodeModeTypeScript, jt as CallToolRequestSchema, k as runCodeMode, kt as mergeCapabilities, l as migrateCredentials, ln as getObjectShape, lt as startOAuthFlow, m as buildProjectSyncManifest, mn as normalizeObjectSchema, n as resolveRemoteSelection, nn as assertCompleteRequestPrompt, nt as loadCapletFilesFromMap, o as projectBindingRecovery, on as isJSONRPCRequest, ot as runGenericOAuthFlow, p as createSdkRemoteCapletsClient, pn as isZ4Schema, q as capabilityDescription, qt as ListResourceTemplatesRequestSchema, r as PROJECT_BINDING_ERROR_CODES, rn as assertCompleteRequestResourceTemplate, rt as hasRenderableStructuredContent, s as CloudAuthStore, sn as isJSONRPCResultResponse, st as runOAuthFlow, t as createNativeCapletsService, tn as SetLevelRequestSchema, tt as validateCapletFile, u as redactedCloudAuthStatus, un as getParseErrorMessage, ut as deleteTokenBundle, v as parseServerBaseUrl, vt as defaultStateBaseDir, wt as serializeMessage, x as nativeCapletPromptGuidance, xt as resolveProjectCapletsRoot, y as resolveCapletsMode, yt as resolveCapletsRoot, z as minifyCodeModeDeclarationText, zt as EmptyResultSchema } from "./service-D0MwLNyb.js";
1
+ import { $ as parseConfig, $t as ReadResourceRequestSchema, A as QuickJsCodeModeSandbox, At as toJsonSchemaCompat, B as CapletsEngine, Bt as ErrorCode, C as nativeCapletToolName, Ct as ReadBuffer, D as codeModeRunInputSchema, Dt as AjvJsonSchemaValidator, Et as assertToolsCallTaskCapability, F as redactCodeModeLogText, Ft as CreateMessageResultWithToolsSchema, G as handleServerTool, Gt as LATEST_PROTOCOL_VERSION, H as decodeDirectResourceUri, Ht as InitializeRequestSchema, I as codeModeDeclarationHash, It as CreateTaskResultSchema, J as loadConfig, Jt as ListResourcesRequestSchema, K as ServerRegistry, Kt as ListPromptsRequestSchema, L as generateCodeModeDeclarations, M as createCodeModeCapletsApi, Mt as CallToolResultSchema, N as listCodeModeCallableCaplets, Nt as CompleteRequestSchema, O as codeModeRunParamsSchema, Ot as Protocol, P as CodeModeLogStore, Pt as CreateMessageResultSchema, Q as loadProjectConfig, Qt as McpError, R as generateCodeModeRunToolDescription, Rt as ElicitResultSchema, S as nativeCapletToolDescription, St as resolveProjectConfigPath, T as nativeCodeModeToolId, Tt as assertClientRequestTaskCapability, U as findProjectRoot, Ut as InitializedNotificationSchema, V as resolveExposure, Vt as GetPromptRequestSchema, W as fingerprintProjectRoot, Wt as JSONRPCMessageSchema, X as loadGlobalConfig, Xt as ListToolsRequestSchema, Y as loadConfigWithSources, Yt as ListRootsResultSchema, Z as loadLocalOverlayConfigWithSources, Zt as LoggingLevelSchema, _ as controlUrlForBase, _n as safeParseAsync, _t as defaultConfigBaseDir, a as projectBindingError, an as isJSONRPCErrorResponse, at as markdownStructuredContent, b as resolveCapletsServer, bt as resolveConfigPath, c as cloudAuthPath, cn as getLiteralValue, ct as startGenericOAuthFlow, d as CloudAuthClient, dn as getSchemaDescription, dt as isTokenBundleExpired, en as SUPPORTED_PROTOCOL_VERSIONS, et as discoverCapletFiles, fn as isSchemaOptional, ft as readTokenBundle, g as resolveCapletsRemote, gn as safeParse, gt as defaultCacheBaseDir, hn as objectFromShape, ht as DEFAULT_OBSERVED_OUTPUT_SHAPE_CACHE_DIR, i as ProjectBindingError, in as isInitializeRequest, it as markdownCallToolResultContent, j as diagnoseCodeModeTypeScript, jt as CallToolRequestSchema, k as runCodeMode, kt as mergeCapabilities, l as migrateCredentials, ln as getObjectShape, lt as startOAuthFlow, m as buildProjectSyncManifest, mn as normalizeObjectSchema, n as resolveRemoteSelection, nn as assertCompleteRequestPrompt, nt as loadCapletFilesFromMap, o as projectBindingRecovery, on as isJSONRPCRequest, ot as runGenericOAuthFlow, p as createSdkRemoteCapletsClient, pn as isZ4Schema, q as capabilityDescription, qt as ListResourceTemplatesRequestSchema, r as PROJECT_BINDING_ERROR_CODES, rn as assertCompleteRequestResourceTemplate, rt as hasRenderableStructuredContent, s as CloudAuthStore, sn as isJSONRPCResultResponse, st as runOAuthFlow, t as createNativeCapletsService, tn as SetLevelRequestSchema, tt as validateCapletFile, u as redactedCloudAuthStatus, un as getParseErrorMessage, ut as deleteTokenBundle, v as parseServerBaseUrl, vt as defaultStateBaseDir, wt as serializeMessage, x as nativeCapletPromptGuidance, xt as resolveProjectCapletsRoot, y as resolveCapletsMode, yt as resolveCapletsRoot, z as minifyCodeModeDeclarationText, zt as EmptyResultSchema } from "./service-Bsq7R0mt.js";
2
2
  import { _ as record, b as unknown, d as literal, m as object, n as ZodOptional, o as array, p as number, r as _enum, s as boolean, v as string, x as url } from "./schemas-BZ6BBrh7.js";
3
3
  import { f as redactSecrets, i as SERVER_ID_PATTERN, l as CAPLETS_ERROR_CODES, p as toSafeError, u as CapletsError } from "./validation-CdqbI2zN.js";
4
4
  import { generatedToolInputSchema, generatedToolInputSchemaForCaplet } from "./generated-tool-input-schema.js";
5
5
  import { f as observedOutputShapeKey, i as observeOutputShape, u as FileObservedOutputShapeStore } from "./observed-output-shapes-uzAMQPhg.js";
6
- import { a as formatCapletList, c as resolveCliConfigPaths, l as cliCommands$1, n as completionScript, o as formatConfigPaths, s as listCaplets, t as completeCliWords, u as completionShells } from "./completion-CbazRAiL.js";
6
+ import { a as formatCapletList, c as resolveCliConfigPaths, l as cliCommands$1, n as completionScript, o as formatConfigPaths, s as listCaplets, t as completeCliWords, u as completionShells } from "./completion-D-kuyArL.js";
7
7
  import { n as normalizeCapletSourcePath, t as FilesystemCapletSource } from "./filesystem-Kkg32TOJ.js";
8
8
  import { parseConfig as parseConfig$1 } from "./config-runtime.js";
9
9
  import fs, { accessSync, chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
@@ -1553,7 +1553,7 @@ const EMPTY_COMPLETION_RESULT = { completion: {
1553
1553
  } };
1554
1554
  //#endregion
1555
1555
  //#region package.json
1556
- var version = "0.20.0";
1556
+ var version = "0.20.1";
1557
1557
  //#endregion
1558
1558
  //#region src/serve/session.ts
1559
1559
  var CapletsMcpSession = class {
package/dist/native.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as nativeCapletToolName, E as nativeCodeModeToolName, S as nativeCapletToolDescription, T as nativeCodeModeToolId, f as RemoteNativeCapletsService, h as resolveNativeCapletsServiceOptions, p as createSdkRemoteCapletsClient, t as createNativeCapletsService, w as nativeCapletsSystemGuidance, x as nativeCapletPromptGuidance } from "./service-D0MwLNyb.js";
1
+ import { C as nativeCapletToolName, E as nativeCodeModeToolName, S as nativeCapletToolDescription, T as nativeCodeModeToolId, f as RemoteNativeCapletsService, h as resolveNativeCapletsServiceOptions, p as createSdkRemoteCapletsClient, t as createNativeCapletsService, w as nativeCapletsSystemGuidance, x as nativeCapletPromptGuidance } from "./service-Bsq7R0mt.js";
2
2
  import { generatedToolInputJsonSchema, generatedToolInputSchema } from "./generated-tool-input-schema.js";
3
3
  //#region src/native/process-cleanup.ts
4
4
  function registerNativeCapletsProcessCleanup(service, options = {}) {
@@ -17317,23 +17317,24 @@ function staticRemoteHeaders(server) {
17317
17317
  if (server.auth?.type === "headers") return server.auth.headers;
17318
17318
  return {};
17319
17319
  }
17320
- function genericOAuthHeaders(target, authDir) {
17320
+ async function genericOAuthHeaders(target, authDir) {
17321
17321
  if (target.auth?.type !== "oauth2" && target.auth?.type !== "oidc") return {};
17322
17322
  const authConfig = target.auth;
17323
- const bundle = readTokenBundle(target.server, authDir);
17324
- if (!bundle?.accessToken) throw new CapletsError("AUTH_REQUIRED", `OAuth credentials required for ${target.server}`, {
17323
+ let bundle = readTokenBundle(target.server, authDir);
17324
+ if (!bundle?.accessToken && !bundle?.refreshToken) throw new CapletsError("AUTH_REQUIRED", `OAuth credentials required for ${target.server}`, {
17325
17325
  server: target.server,
17326
17326
  backend: target.backend,
17327
17327
  authType: authConfig.type,
17328
17328
  nextAction: "run_caplets_auth_login"
17329
17329
  });
17330
- if (isTokenBundleExpired(bundle)) throw new CapletsError("AUTH_REFRESH_FAILED", `OAuth token for ${target.server} is expired`, {
17330
+ assertTokenBundleMatchesTarget(bundle, target, authConfig);
17331
+ if (!bundle.accessToken || isTokenBundleExpired(bundle)) bundle = await refreshGenericOAuthBundle(target, authConfig, bundle, authDir);
17332
+ if (!bundle.accessToken || isTokenBundleExpired(bundle)) throw new CapletsError("AUTH_REFRESH_FAILED", `OAuth token for ${target.server} is expired`, {
17331
17333
  server: target.server,
17332
17334
  backend: target.backend,
17333
17335
  authType: authConfig.type,
17334
17336
  nextAction: "run_caplets_auth_login"
17335
17337
  });
17336
- assertTokenBundleMatchesTarget(bundle, target, authConfig);
17337
17338
  return { authorization: `${bundle.tokenType ?? "Bearer"} ${bundle.accessToken}` };
17338
17339
  }
17339
17340
  var FileOAuthProvider = class {
@@ -17768,6 +17769,87 @@ async function resolveGenericClient(target, authConfig, metadata, redirectUri, a
17768
17769
  dynamic: true
17769
17770
  };
17770
17771
  }
17772
+ async function refreshGenericOAuthBundle(target, authConfig, bundle, authDir) {
17773
+ if (!bundle.refreshToken) throw new CapletsError("AUTH_REFRESH_FAILED", `OAuth token for ${target.server} is expired`, {
17774
+ server: target.server,
17775
+ backend: target.backend,
17776
+ authType: authConfig.type,
17777
+ nextAction: "run_caplets_auth_login"
17778
+ });
17779
+ const allowLoopbackHttp = isLoopbackDevelopmentTarget(target, authConfig);
17780
+ let metadata = {};
17781
+ let tokenEndpoint = authConfig.tokenUrl;
17782
+ if (!tokenEndpoint) {
17783
+ metadata = await discoverAuthorizationServer(target, authConfig, allowLoopbackHttp);
17784
+ tokenEndpoint = metadata.token_endpoint;
17785
+ }
17786
+ if (!tokenEndpoint) throw new CapletsError("AUTH_REFRESH_FAILED", "OAuth metadata is missing token endpoint", {
17787
+ server: target.server,
17788
+ backend: target.backend,
17789
+ authType: authConfig.type,
17790
+ nextAction: "run_caplets_auth_login"
17791
+ });
17792
+ assertAllowedAuthUrl(tokenEndpoint, "token endpoint", allowLoopbackHttp);
17793
+ const clientId = authConfig.clientId ?? authConfig.clientMetadataUrl ?? bundle.clientId;
17794
+ if (!clientId) throw new CapletsError("AUTH_REFRESH_FAILED", "OAuth clientId is required to refresh tokens", {
17795
+ server: target.server,
17796
+ backend: target.backend,
17797
+ authType: authConfig.type,
17798
+ nextAction: "run_caplets_auth_login"
17799
+ });
17800
+ const clientSecret = authConfig.clientSecret ?? bundle.clientSecret;
17801
+ const params = new URLSearchParams({
17802
+ grant_type: "refresh_token",
17803
+ refresh_token: bundle.refreshToken,
17804
+ client_id: clientId
17805
+ });
17806
+ if (clientSecret) params.set("client_secret", clientSecret);
17807
+ let tokenResponse;
17808
+ try {
17809
+ tokenResponse = await fetchJson(tokenEndpoint, target.requestTimeoutMs, {
17810
+ method: "POST",
17811
+ headers: { "content-type": "application/x-www-form-urlencoded" },
17812
+ body: params.toString()
17813
+ }, allowLoopbackHttp);
17814
+ } catch (error) {
17815
+ if (error instanceof CapletsError) throw new CapletsError("AUTH_REFRESH_FAILED", `OAuth token refresh failed`, {
17816
+ server: target.server,
17817
+ backend: target.backend,
17818
+ authType: authConfig.type,
17819
+ nextAction: "run_caplets_auth_login",
17820
+ cause: error.details
17821
+ });
17822
+ throw error;
17823
+ }
17824
+ const idToken = asString(tokenResponse.id_token);
17825
+ const idClaims = parseJwtPayload(idToken);
17826
+ if (idToken) {
17827
+ if (!metadata.issuer && !authConfig.issuer) metadata = await discoverAuthorizationServer(target, authConfig, allowLoopbackHttp);
17828
+ validateOidcToken(authConfig, metadata, idToken, idClaims, clientId);
17829
+ }
17830
+ const refreshed = stripUndefined$1({
17831
+ ...bundle,
17832
+ server: target.server,
17833
+ authType: authConfig.type,
17834
+ accessToken: requireString(tokenResponse.access_token, "access_token"),
17835
+ refreshToken: asString(tokenResponse.refresh_token) ?? bundle.refreshToken,
17836
+ tokenType: asString(tokenResponse.token_type) ?? bundle.tokenType,
17837
+ expiresAt: refreshedExpiresAt(tokenResponse.expires_in, bundle.expiresAt),
17838
+ scope: asString(tokenResponse.scope) ?? bundle.scope ?? scopesFor(authConfig),
17839
+ idToken: idToken ?? bundle.idToken,
17840
+ issuer: asString(idClaims?.iss) ?? bundle.issuer ?? metadata.issuer ?? authConfig.issuer,
17841
+ subject: asString(idClaims?.sub) ?? bundle.subject,
17842
+ clientId,
17843
+ clientSecret,
17844
+ protectedResourceOrigin: protectedResourceOrigin(target, authConfig)
17845
+ });
17846
+ writeTokenBundle(refreshed, authDir);
17847
+ return refreshed;
17848
+ }
17849
+ function refreshedExpiresAt(expiresIn, fallback) {
17850
+ if (typeof expiresIn === "number") return new Date(Date.now() + expiresIn * 1e3).toISOString();
17851
+ if (fallback && Date.parse(fallback) > Date.now()) return fallback;
17852
+ }
17771
17853
  async function fetchOptionalJson(url, timeoutMs, allowLoopbackHttp = false) {
17772
17854
  try {
17773
17855
  return await fetchJson(url, timeoutMs, {}, allowLoopbackHttp);
@@ -49327,7 +49409,7 @@ var GraphQLManager = class {
49327
49409
  const headers = new Headers({
49328
49410
  "content-type": "application/json",
49329
49411
  ...staticHeaders(endpoint),
49330
- ...genericOAuthHeaders({
49412
+ ...await genericOAuthHeaders({
49331
49413
  server: endpoint.server,
49332
49414
  backend: "graphql",
49333
49415
  url: endpoint.endpointUrl,
@@ -49630,7 +49712,7 @@ async function postGraphQl(endpoint, url, payload, authDir) {
49630
49712
  headers: {
49631
49713
  "content-type": "application/json",
49632
49714
  ...staticHeaders(endpoint),
49633
- ...genericOAuthHeaders({
49715
+ ...await genericOAuthHeaders({
49634
49716
  server: endpoint.server,
49635
49717
  backend: "graphql",
49636
49718
  url: endpoint.endpointUrl,
@@ -49655,7 +49737,7 @@ async function fetchGraphQlText(endpoint, url, authDir, sendAuth = true) {
49655
49737
  response = await fetch(url, {
49656
49738
  redirect: "manual",
49657
49739
  signal: controller.signal,
49658
- headers: { ...sendAuth ? schemaAuthHeaders(endpoint, authDir) : {} }
49740
+ headers: { ...sendAuth ? await schemaAuthHeaders(endpoint, authDir) : {} }
49659
49741
  });
49660
49742
  } catch (error) {
49661
49743
  if (isAbortError(error)) throw new CapletsError("TOOL_CALL_TIMEOUT", "GraphQL schema request timed out");
@@ -49667,10 +49749,10 @@ async function fetchGraphQlText(endpoint, url, authDir, sendAuth = true) {
49667
49749
  if (!response.ok) throw new CapletsError("DOWNSTREAM_PROTOCOL_ERROR", "GraphQL schema request failed", { status: response.status });
49668
49750
  return readGraphQlText(response);
49669
49751
  }
49670
- function schemaAuthHeaders(endpoint, authDir) {
49752
+ async function schemaAuthHeaders(endpoint, authDir) {
49671
49753
  return {
49672
49754
  ...staticHeaders(endpoint),
49673
- ...genericOAuthHeaders({
49755
+ ...await genericOAuthHeaders({
49674
49756
  server: endpoint.server,
49675
49757
  backend: "graphql",
49676
49758
  url: endpoint.endpointUrl,
@@ -49726,7 +49808,7 @@ var HttpActionManager = class {
49726
49808
  try {
49727
49809
  const operations = operationsFor(api);
49728
49810
  validateBaseUrl(api);
49729
- authHeaders$1(api, this.options.authDir);
49811
+ await authHeaders$1(api, this.options.authDir);
49730
49812
  for (const operation of operations) validateAction(api, operation);
49731
49813
  this.registry.setStatus(api.server, "available");
49732
49814
  return {
@@ -49755,7 +49837,7 @@ var HttpActionManager = class {
49755
49837
  async callTool(api, toolName, args) {
49756
49838
  const operation = getOperation(api, toolName);
49757
49839
  const startedAt = Date.now();
49758
- const request = buildRequest$1(api, operation, args, this.options.authDir);
49840
+ const request = await buildRequest$1(api, operation, args, this.options.authDir);
49759
49841
  const controller = new AbortController();
49760
49842
  const timeout = setTimeout(() => controller.abort(), api.requestTimeoutMs);
49761
49843
  try {
@@ -49836,14 +49918,14 @@ function getOperation(api, toolName) {
49836
49918
  });
49837
49919
  return operation;
49838
49920
  }
49839
- function buildRequest$1(api, operation, args, authDir) {
49921
+ async function buildRequest$1(api, operation, args, authDir) {
49840
49922
  validateBaseUrl(api);
49841
49923
  validateAction(api, operation);
49842
49924
  const url = buildActionUrl(api.baseUrl, substitutePath$1(operation.path, args, operation), { allowEncodedSlash: true });
49843
49925
  const query = resolveMappingToRecord(operation.query, args, "query");
49844
49926
  for (const [key, value] of Object.entries(query)) if (value !== void 0 && value !== null) url.searchParams.append(key, serializeHttpValue$1("query", key, value));
49845
49927
  const headers = new Headers();
49846
- applyAuth$1(headers, api, authDir);
49928
+ await applyAuth$1(headers, api, authDir);
49847
49929
  const resolvedHeaders = resolveMappingToRecord(operation.headers, args, "headers");
49848
49930
  for (const [key, value] of Object.entries(resolvedHeaders)) if (value !== void 0 && value !== null) {
49849
49931
  validateResolvedHeader(api, operation, key);
@@ -49919,16 +50001,16 @@ function serializeHttpValue$1(location, name, value) {
49919
50001
  default: throw new CapletsError("REQUEST_INVALID", `HTTP action ${location} parameter ${name} must be a string, number, or boolean`);
49920
50002
  }
49921
50003
  }
49922
- function applyAuth$1(headers, api, authDir) {
49923
- for (const [key, value] of Object.entries(authHeaders$1(api, authDir))) headers.set(key, value);
50004
+ async function applyAuth$1(headers, api, authDir) {
50005
+ for (const [key, value] of Object.entries(await authHeaders$1(api, authDir))) headers.set(key, value);
49924
50006
  }
49925
- function authHeaders$1(api, authDir) {
50007
+ async function authHeaders$1(api, authDir) {
49926
50008
  switch (api.auth.type) {
49927
50009
  case "none": return {};
49928
50010
  case "bearer": return { authorization: `Bearer ${api.auth.token}` };
49929
50011
  case "headers": return api.auth.headers;
49930
50012
  case "oauth2":
49931
- case "oidc": return genericOAuthHeaders({
50013
+ case "oidc": return await genericOAuthHeaders({
49932
50014
  server: api.server,
49933
50015
  backend: "http",
49934
50016
  baseUrl: api.baseUrl,
@@ -59754,7 +59836,7 @@ var OpenApiManager = class {
59754
59836
  }
59755
59837
  async callTool(endpoint, toolName, args) {
59756
59838
  const operation = await this.getOperation(endpoint, toolName);
59757
- const request = buildRequest(endpoint, operation, args, this.options.authDir);
59839
+ const request = await buildRequest(endpoint, operation, args, this.options.authDir);
59758
59840
  const controller = new AbortController();
59759
59841
  const timeout = setTimeout(() => controller.abort(), endpoint.requestTimeoutMs);
59760
59842
  try {
@@ -59868,7 +59950,7 @@ async function loadOpenApiSource(endpoint, authDir) {
59868
59950
  if (endpoint.specPath) return endpoint.specPath;
59869
59951
  if (!endpoint.specUrl) throw new CapletsError("CONFIG_INVALID", `${endpoint.server} is missing OpenAPI spec source`);
59870
59952
  if (!endpoint.baseUrl) throw new CapletsError("CONFIG_INVALID", `${endpoint.server} must configure baseUrl when using remote specUrl`);
59871
- return parseOpenApiSourceText(await fetchWithLimit(endpoint.specUrl, endpoint.requestTimeoutMs, shouldSendSpecAuth(endpoint) ? authHeaders(endpoint, authDir) : {}));
59953
+ return parseOpenApiSourceText(await fetchWithLimit(endpoint.specUrl, endpoint.requestTimeoutMs, shouldSendSpecAuth(endpoint) ? await authHeaders(endpoint, authDir) : {}));
59872
59954
  }
59873
59955
  function parseOpenApiSourceText(source) {
59874
59956
  let parsed;
@@ -60039,13 +60121,13 @@ function rejectExternalRefs(value) {
60039
60121
  if (typeof object.$ref === "string" && !object.$ref.startsWith("#/")) throw new CapletsError("CONFIG_INVALID", "External OpenAPI $ref values are not supported");
60040
60122
  for (const nested of Object.values(object)) rejectExternalRefs(nested);
60041
60123
  }
60042
- function buildRequest(endpoint, operation, args, authDir) {
60124
+ async function buildRequest(endpoint, operation, args, authDir) {
60043
60125
  const base = endpoint.baseUrl ?? operation.baseUrl;
60044
60126
  validateOperationBaseUrl(endpoint, base);
60045
60127
  const url = buildOperationUrl(base, substitutePath(operation.path, asRecord(args.path), operation));
60046
60128
  for (const [key, value] of Object.entries(asRecord(args.query))) if (value !== void 0 && value !== null) url.searchParams.append(key, serializeHttpValue("query", key, value));
60047
60129
  const headers = new Headers();
60048
- applyAuth(headers, endpoint, authDir);
60130
+ await applyAuth(headers, endpoint, authDir);
60049
60131
  const configuredHeaderNames = configuredAuthHeaderNames(endpoint);
60050
60132
  for (const [key, value] of Object.entries(operation.staticHeaders ?? {})) if (!headers.has(key) && !configuredHeaderNames.has(key.toLowerCase())) headers.set(key, value);
60051
60133
  for (const [key, value] of Object.entries(asRecord(args.header))) if (value !== void 0 && value !== null) {
@@ -60090,19 +60172,19 @@ function serializeHttpValue(location, name, value) {
60090
60172
  function asRecord(value) {
60091
60173
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
60092
60174
  }
60093
- function applyAuth(headers, endpoint, authDir) {
60094
- for (const [key, value] of Object.entries(authHeaders(endpoint, authDir))) headers.set(key, value);
60175
+ async function applyAuth(headers, endpoint, authDir) {
60176
+ for (const [key, value] of Object.entries(await authHeaders(endpoint, authDir))) headers.set(key, value);
60095
60177
  }
60096
60178
  function configuredAuthHeaderNames(endpoint) {
60097
60179
  return endpoint.auth.type === "headers" ? new Set(Object.keys(endpoint.auth.headers).map((key) => key.toLowerCase())) : /* @__PURE__ */ new Set();
60098
60180
  }
60099
- function authHeaders(endpoint, authDir) {
60181
+ async function authHeaders(endpoint, authDir) {
60100
60182
  switch (endpoint.auth.type) {
60101
60183
  case "none": return {};
60102
60184
  case "bearer": return { authorization: `Bearer ${endpoint.auth.token}` };
60103
60185
  case "headers": return endpoint.auth.headers;
60104
60186
  case "oauth2":
60105
- case "oidc": return genericOAuthHeaders(endpoint, authDir);
60187
+ case "oidc": return await genericOAuthHeaders(endpoint, authDir);
60106
60188
  }
60107
60189
  }
60108
60190
  function shouldSendSpecAuth(endpoint) {
@@ -61697,7 +61779,7 @@ var CapletsEngine = class {
61697
61779
  }
61698
61780
  }
61699
61781
  async completeCliWords(words) {
61700
- const { completeCliWords } = await import("./completion-CbazRAiL.js").then((n) => n.r);
61782
+ const { completeCliWords } = await import("./completion-D-kuyArL.js").then((n) => n.r);
61701
61783
  return await completeCliWords(words, {
61702
61784
  config: this.registry.config,
61703
61785
  managers: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caplets/core",
3
- "version": "0.20.0",
3
+ "version": "0.20.1",
4
4
  "description": "Core runtime library for Caplets Code Mode and progressive disclosure gateways.",
5
5
  "keywords": [
6
6
  "caplets",