@agent-native/core 0.32.18 → 0.35.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.
Files changed (137) hide show
  1. package/dist/agent/context-xray/actions/context-evict.d.ts +3 -0
  2. package/dist/agent/context-xray/actions/context-evict.d.ts.map +1 -0
  3. package/dist/agent/context-xray/actions/context-evict.js +35 -0
  4. package/dist/agent/context-xray/actions/context-evict.js.map +1 -0
  5. package/dist/agent/context-xray/actions/context-manifest-get.d.ts +3 -0
  6. package/dist/agent/context-xray/actions/context-manifest-get.d.ts.map +1 -0
  7. package/dist/agent/context-xray/actions/context-manifest-get.js +67 -0
  8. package/dist/agent/context-xray/actions/context-manifest-get.js.map +1 -0
  9. package/dist/agent/context-xray/actions/context-pin.d.ts +3 -0
  10. package/dist/agent/context-xray/actions/context-pin.d.ts.map +1 -0
  11. package/dist/agent/context-xray/actions/context-pin.js +35 -0
  12. package/dist/agent/context-xray/actions/context-pin.js.map +1 -0
  13. package/dist/agent/context-xray/actions/context-report.d.ts +3 -0
  14. package/dist/agent/context-xray/actions/context-report.d.ts.map +1 -0
  15. package/dist/agent/context-xray/actions/context-report.js +59 -0
  16. package/dist/agent/context-xray/actions/context-report.js.map +1 -0
  17. package/dist/agent/context-xray/actions/context-restore.d.ts +3 -0
  18. package/dist/agent/context-xray/actions/context-restore.d.ts.map +1 -0
  19. package/dist/agent/context-xray/actions/context-restore.js +33 -0
  20. package/dist/agent/context-xray/actions/context-restore.js.map +1 -0
  21. package/dist/agent/context-xray/actions/errors.d.ts +7 -0
  22. package/dist/agent/context-xray/actions/errors.d.ts.map +1 -0
  23. package/dist/agent/context-xray/actions/errors.js +15 -0
  24. package/dist/agent/context-xray/actions/errors.js.map +1 -0
  25. package/dist/agent/context-xray/apply-directives.d.ts +10 -0
  26. package/dist/agent/context-xray/apply-directives.d.ts.map +1 -0
  27. package/dist/agent/context-xray/apply-directives.js +100 -0
  28. package/dist/agent/context-xray/apply-directives.js.map +1 -0
  29. package/dist/agent/context-xray/directives-store.d.ts +26 -0
  30. package/dist/agent/context-xray/directives-store.d.ts.map +1 -0
  31. package/dist/agent/context-xray/directives-store.js +131 -0
  32. package/dist/agent/context-xray/directives-store.js.map +1 -0
  33. package/dist/agent/context-xray/identity.d.ts +5 -0
  34. package/dist/agent/context-xray/identity.d.ts.map +1 -0
  35. package/dist/agent/context-xray/identity.js +33 -0
  36. package/dist/agent/context-xray/identity.js.map +1 -0
  37. package/dist/agent/context-xray/manifest.d.ts +19 -0
  38. package/dist/agent/context-xray/manifest.d.ts.map +1 -0
  39. package/dist/agent/context-xray/manifest.js +115 -0
  40. package/dist/agent/context-xray/manifest.js.map +1 -0
  41. package/dist/agent/context-xray/migrations.d.ts +3 -0
  42. package/dist/agent/context-xray/migrations.d.ts.map +1 -0
  43. package/dist/agent/context-xray/migrations.js +31 -0
  44. package/dist/agent/context-xray/migrations.js.map +1 -0
  45. package/dist/agent/context-xray/plugin.d.ts +5 -0
  46. package/dist/agent/context-xray/plugin.d.ts.map +1 -0
  47. package/dist/agent/context-xray/plugin.js +15 -0
  48. package/dist/agent/context-xray/plugin.js.map +1 -0
  49. package/dist/agent/context-xray/schema.d.ts +249 -0
  50. package/dist/agent/context-xray/schema.d.ts.map +1 -0
  51. package/dist/agent/context-xray/schema.js +17 -0
  52. package/dist/agent/context-xray/schema.js.map +1 -0
  53. package/dist/agent/context-xray/segments.d.ts +19 -0
  54. package/dist/agent/context-xray/segments.d.ts.map +1 -0
  55. package/dist/agent/context-xray/segments.js +154 -0
  56. package/dist/agent/context-xray/segments.js.map +1 -0
  57. package/dist/agent/context-xray/tokenize.d.ts +10 -0
  58. package/dist/agent/context-xray/tokenize.d.ts.map +1 -0
  59. package/dist/agent/context-xray/tokenize.js +70 -0
  60. package/dist/agent/context-xray/tokenize.js.map +1 -0
  61. package/dist/agent/production-agent.d.ts +2 -0
  62. package/dist/agent/production-agent.d.ts.map +1 -1
  63. package/dist/agent/production-agent.js +45 -5
  64. package/dist/agent/production-agent.js.map +1 -1
  65. package/dist/cli/context-xray-local.d.ts +16 -0
  66. package/dist/cli/context-xray-local.d.ts.map +1 -0
  67. package/dist/cli/context-xray-local.js +738 -0
  68. package/dist/cli/context-xray-local.js.map +1 -0
  69. package/dist/cli/skills.d.ts +3 -0
  70. package/dist/cli/skills.d.ts.map +1 -1
  71. package/dist/cli/skills.js +200 -73
  72. package/dist/cli/skills.js.map +1 -1
  73. package/dist/cli/templates-meta.js +5 -5
  74. package/dist/cli/templates-meta.js.map +1 -1
  75. package/dist/client/AssistantChat.d.ts.map +1 -1
  76. package/dist/client/AssistantChat.js +2 -1
  77. package/dist/client/AssistantChat.js.map +1 -1
  78. package/dist/client/components/ui/sheet.d.ts +16 -0
  79. package/dist/client/components/ui/sheet.d.ts.map +1 -0
  80. package/dist/client/components/ui/sheet.js +23 -0
  81. package/dist/client/components/ui/sheet.js.map +1 -0
  82. package/dist/client/context-xray/ContextMeter.d.ts +4 -0
  83. package/dist/client/context-xray/ContextMeter.d.ts.map +1 -0
  84. package/dist/client/context-xray/ContextMeter.js +76 -0
  85. package/dist/client/context-xray/ContextMeter.js.map +1 -0
  86. package/dist/client/context-xray/ContextSegmentRow.d.ts +9 -0
  87. package/dist/client/context-xray/ContextSegmentRow.d.ts.map +1 -0
  88. package/dist/client/context-xray/ContextSegmentRow.js +22 -0
  89. package/dist/client/context-xray/ContextSegmentRow.js.map +1 -0
  90. package/dist/client/context-xray/ContextTreemap.d.ts +6 -0
  91. package/dist/client/context-xray/ContextTreemap.d.ts.map +1 -0
  92. package/dist/client/context-xray/ContextTreemap.js +49 -0
  93. package/dist/client/context-xray/ContextTreemap.js.map +1 -0
  94. package/dist/client/context-xray/ContextXRayPanel.d.ts +11 -0
  95. package/dist/client/context-xray/ContextXRayPanel.d.ts.map +1 -0
  96. package/dist/client/context-xray/ContextXRayPanel.js +87 -0
  97. package/dist/client/context-xray/ContextXRayPanel.js.map +1 -0
  98. package/dist/client/context-xray/SegmentProvenancePopover.d.ts +7 -0
  99. package/dist/client/context-xray/SegmentProvenancePopover.d.ts.map +1 -0
  100. package/dist/client/context-xray/SegmentProvenancePopover.js +7 -0
  101. package/dist/client/context-xray/SegmentProvenancePopover.js.map +1 -0
  102. package/dist/client/context-xray/format.d.ts +7 -0
  103. package/dist/client/context-xray/format.d.ts.map +1 -0
  104. package/dist/client/context-xray/format.js +47 -0
  105. package/dist/client/context-xray/format.js.map +1 -0
  106. package/dist/deploy/route-discovery.d.ts.map +1 -1
  107. package/dist/deploy/route-discovery.js +1 -0
  108. package/dist/deploy/route-discovery.js.map +1 -1
  109. package/dist/deploy/workspace-core.d.ts +1 -1
  110. package/dist/deploy/workspace-core.d.ts.map +1 -1
  111. package/dist/deploy/workspace-core.js +1 -0
  112. package/dist/deploy/workspace-core.js.map +1 -1
  113. package/dist/provider-api/index.d.ts +237 -0
  114. package/dist/provider-api/index.d.ts.map +1 -0
  115. package/dist/provider-api/index.js +1533 -0
  116. package/dist/provider-api/index.js.map +1 -0
  117. package/dist/server/action-discovery.d.ts.map +1 -1
  118. package/dist/server/action-discovery.js +20 -0
  119. package/dist/server/action-discovery.js.map +1 -1
  120. package/dist/server/framework-request-handler.d.ts.map +1 -1
  121. package/dist/server/framework-request-handler.js +2 -0
  122. package/dist/server/framework-request-handler.js.map +1 -1
  123. package/dist/server/index.d.ts +1 -0
  124. package/dist/server/index.d.ts.map +1 -1
  125. package/dist/server/index.js +1 -0
  126. package/dist/server/index.js.map +1 -1
  127. package/dist/shared/context-xray.d.ts +58 -0
  128. package/dist/shared/context-xray.d.ts.map +1 -0
  129. package/dist/shared/context-xray.js +17 -0
  130. package/dist/shared/context-xray.js.map +1 -0
  131. package/dist/vite/action-types-plugin.d.ts.map +1 -1
  132. package/dist/vite/action-types-plugin.js +20 -0
  133. package/dist/vite/action-types-plugin.js.map +1 -1
  134. package/dist/vite/client.d.ts.map +1 -1
  135. package/dist/vite/client.js +1 -0
  136. package/dist/vite/client.js.map +1 -1
  137. package/package.json +10 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/provider-api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,iBAAiB,GAElB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,wBAAwB,EACxB,eAAe,GAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,0CAA0C,EAAE,MAAM,yCAAyC,CAAC;AAGrG,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,WAAW;IACX,QAAQ;IACR,UAAU;IACV,YAAY;IACZ,YAAY;IACZ,KAAK;IACL,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,MAAM;IACN,iBAAiB;IACjB,cAAc;IACd,SAAS;IACT,SAAS;IACT,SAAS;IACT,MAAM;IACN,UAAU;IACV,QAAQ;IACR,SAAS;IACT,YAAY;IACZ,OAAO;IACP,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;CACD,CAAC;AA8JX,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,iBAAiB,GAAG,IAAI,GAAG,IAAI,CAAC;AACtC,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACtC,MAAM,cAAc,GAAG,+BAA+B,CAAC;AACvD,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC;IACvC,YAAY;IACZ,gBAAgB;IAChB,QAAQ;IACR,WAAW;IACX,MAAM;IACN,YAAY;IACZ,QAAQ;IACR,oBAAoB;IACpB,qBAAqB;IACrB,SAAS;IACT,YAAY;IACZ,IAAI;IACJ,SAAS;IACT,mBAAmB;IACnB,SAAS;I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AAK,EAAE,CAAC;IAC5C,MAAM,YAAY,GAAG,GAAG,qBAAqB,CAC3C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CACvB,IAAI,qBAAqB,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;IAEtD,MAAM,GAAG,GAAG,MAAM,cAAc,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CACxC,mBAAmB,EACnB,GAAG,EACH,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,YAAY,CAAiB,CACvD,CAAC;IAEF,OAAO,GAAG,YAAY,IAAI,eAAe,CAAC,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;AACzE,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n resolveCredential,\n type CredentialContext,\n} from \"../credentials/index.js\";\nimport {\n createSsrfSafeDispatcher,\n isBlockedExtensionUrlWithDns,\n} from \"../extensions/url-safety.js\";\nimport {\n listOAuthAccountsByOwner,\n saveOAuthTokens,\n} from \"../oauth-tokens/index.js\";\nimport { getCredentialContext } from \"../server/request-context.js\";\nimport { resolveWorkspaceConnectionCredentialForApp } from \"../workspace-connections/credentials.js\";\nimport type { WorkspaceConnectionTemplateUse } from \"../connections/catalog.js\";\n\nexport const PROVIDER_API_IDS = [\n \"amplitude\",\n \"apollo\",\n \"bigquery\",\n \"commonroom\",\n \"dataforseo\",\n \"ga4\",\n \"gcloud\",\n \"github\",\n \"gmail\",\n \"gong\",\n \"google_calendar\",\n \"google_drive\",\n \"granola\",\n \"grafana\",\n \"hubspot\",\n \"jira\",\n \"mixpanel\",\n \"notion\",\n \"posthog\",\n \"prometheus\",\n \"pylon\",\n \"sentry\",\n \"slack\",\n \"stripe\",\n \"twitter\",\n] as const;\n\nexport type ProviderApiId = (typeof PROVIDER_API_IDS)[number];\n\nexport type ProviderApiMethod =\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\"\n | \"HEAD\";\n\nexport interface ProviderApiRequestArgs {\n provider: ProviderApiId | string;\n method?: ProviderApiMethod;\n path: string;\n query?: unknown;\n headers?: Record<string, unknown>;\n body?: unknown;\n auth?: \"default\" | \"none\";\n timeoutMs?: number;\n maxBytes?: number;\n connectionId?: string | null;\n accountId?: string | null;\n}\n\nexport type ProviderApiAuthKind =\n | { type: \"none\" }\n | {\n type: \"bearer\";\n keys: readonly string[];\n workspaceProvider?: string;\n }\n | {\n type: \"basic\";\n usernameKey: string;\n passwordKey: string;\n workspaceProvider?: string;\n }\n | {\n type: \"basic-raw\";\n key: string;\n workspaceProvider?: string;\n }\n | {\n type: \"api-key-header\";\n key: string;\n header: string;\n workspaceProvider?: string;\n }\n | {\n type: \"google-service-account\";\n scopes: readonly string[];\n }\n | {\n type: \"oauth-bearer\";\n oauthProvider: string;\n tokenLabel: string;\n }\n | {\n type: \"prometheus\";\n };\n\nexport interface ProviderApiConfig {\n id: ProviderApiId;\n label: string;\n defaultBaseUrl: string;\n baseUrlCredentialKey?: string;\n auth: ProviderApiAuthKind;\n credentialKeys: readonly string[];\n docsUrls: readonly string[];\n specUrls?: readonly string[];\n allowedHostSuffixes?: readonly string[];\n defaultHeaders?: Record<string, string>;\n placeholders?: readonly ProviderApiPlaceholder[];\n examples?: readonly ProviderApiExample[];\n notes?: readonly string[];\n templateUses?: readonly WorkspaceConnectionTemplateUse[];\n}\n\nexport interface ProviderApiPlaceholder {\n name: string;\n credentialKey: string;\n label: string;\n}\n\nexport interface ProviderApiExample {\n label: string;\n method: ProviderApiMethod;\n path: string;\n body?: unknown;\n}\n\nexport interface ProviderApiResolvedCredential {\n key: string;\n value: string;\n source: string;\n provider: string;\n connectionId?: string;\n connectionLabel?: string;\n accountId?: string;\n accountLabel?: string | null;\n scope?: string;\n}\n\nexport interface ProviderApiCredentialLookupOptions {\n appId: string;\n provider: string;\n key: string;\n ctx: CredentialContext;\n workspaceProvider?: string;\n connectionId?: string | null;\n localCredentialSource: string;\n}\n\nexport type ProviderApiCredentialResolver = (\n options: ProviderApiCredentialLookupOptions,\n) => Promise<ProviderApiResolvedCredential | null>;\n\nexport interface ProviderApiRuntimeOptions {\n appId: string;\n providerIds?: readonly (ProviderApiId | string)[];\n localCredentialSource?: string;\n getCredentialContext?: () => CredentialContext | null;\n resolveCredential?: ProviderApiCredentialResolver;\n}\n\ninterface ProviderApiRuntime {\n providerIds: readonly ProviderApiId[];\n listCatalog(\n provider?: ProviderApiId | string,\n ): ReturnType<typeof listProviderApiCatalog>;\n fetchDocs(options: {\n provider: ProviderApiId | string;\n url?: string;\n maxBytes?: number;\n }): Promise<unknown>;\n executeRequest(args: ProviderApiRequestArgs): Promise<unknown>;\n}\n\ninterface ResolvedAuth {\n headers: Record<string, string>;\n credentialSources: Array<Omit<ProviderApiResolvedCredential, \"value\">>;\n secretValues: string[];\n}\n\ninterface OAuthTokens {\n access_token?: string;\n accessToken?: string;\n refresh_token?: string;\n refreshToken?: string;\n expiry_date?: number;\n expiresAt?: number;\n expires_in?: number;\n token_type?: string;\n scope?: string;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst DEFAULT_MAX_BYTES = 1024 * 1024;\nconst MAX_MAX_BYTES = 4 * 1024 * 1024;\nconst HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nconst BLOCKED_OUTBOUND_HEADERS = new Set([\n \"connection\",\n \"content-length\",\n \"cookie\",\n \"forwarded\",\n \"host\",\n \"keep-alive\",\n \"origin\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"referer\",\n \"set-cookie\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n]);\n\nconst PROVIDER_CONFIGS: Record<ProviderApiId, ProviderApiConfig> = {\n amplitude: {\n id: \"amplitude\",\n label: \"Amplitude\",\n defaultBaseUrl: \"https://amplitude.com/api/2\",\n auth: {\n type: \"basic\",\n usernameKey: \"AMPLITUDE_API_KEY\",\n passwordKey: \"AMPLITUDE_SECRET_KEY\",\n },\n credentialKeys: [\"AMPLITUDE_API_KEY\", \"AMPLITUDE_SECRET_KEY\"],\n docsUrls: [\"https://amplitude.com/docs/apis\"],\n allowedHostSuffixes: [\"amplitude.com\"],\n templateUses: [\"analytics\"],\n examples: [\n {\n label: \"Export events\",\n method: \"GET\",\n path: \"/export?start=20260601T00&end=20260602T00\",\n },\n ],\n },\n apollo: {\n id: \"apollo\",\n label: \"Apollo\",\n defaultBaseUrl: \"https://api.apollo.io\",\n auth: {\n type: \"api-key-header\",\n key: \"APOLLO_API_KEY\",\n header: \"x-api-key\",\n },\n credentialKeys: [\"APOLLO_API_KEY\"],\n docsUrls: [\"https://docs.apollo.io/reference/api-reference\"],\n templateUses: [\"analytics\"],\n examples: [\n {\n label: \"Search people\",\n method: \"POST\",\n path: \"/api/v1/mixed_people/search\",\n body: { q_keywords: \"vp marketing\", page: 1, per_page: 10 },\n },\n ],\n },\n bigquery: {\n id: \"bigquery\",\n label: \"BigQuery REST API\",\n defaultBaseUrl: \"https://bigquery.googleapis.com/bigquery/v2\",\n auth: {\n type: \"google-service-account\",\n scopes: [\n \"https://www.googleapis.com/auth/cloud-platform\",\n \"https://www.googleapis.com/auth/bigquery\",\n ],\n },\n credentialKeys: [\n \"GOOGLE_APPLICATION_CREDENTIALS_JSON\",\n \"BIGQUERY_PROJECT_ID\",\n ],\n docsUrls: [\"https://cloud.google.com/bigquery/docs/reference/rest\"],\n specUrls: [\"https://bigquery.googleapis.com/$discovery/rest?version=v2\"],\n allowedHostSuffixes: [\"googleapis.com\"],\n templateUses: [\"analytics\"],\n placeholders: [\n {\n name: \"projectId\",\n credentialKey: \"BIGQUERY_PROJECT_ID\",\n label: \"Configured BigQuery project ID\",\n },\n ],\n examples: [\n {\n label: \"List datasets\",\n method: \"GET\",\n path: \"/projects/{projectId}/datasets\",\n },\n {\n label: \"Run query\",\n method: \"POST\",\n path: \"/projects/{projectId}/queries\",\n body: { query: \"SELECT 1\", useLegacySql: false },\n },\n ],\n },\n commonroom: {\n id: \"commonroom\",\n label: \"Common Room\",\n defaultBaseUrl: \"https://api.commonroom.io/community/v1\",\n auth: {\n type: \"bearer\",\n keys: [\"COMMONROOM_API_TOKEN\"],\n },\n credentialKeys: [\"COMMONROOM_API_TOKEN\"],\n docsUrls: [\"https://developer.commonroom.io/reference/overview\"],\n templateUses: [\"analytics\"],\n examples: [{ label: \"List members\", method: \"GET\", path: \"/members\" }],\n },\n dataforseo: {\n id: \"dataforseo\",\n label: \"DataForSEO\",\n defaultBaseUrl: \"https://api.dataforseo.com/v3\",\n auth: {\n type: \"basic\",\n usernameKey: \"DATAFORSEO_LOGIN\",\n passwordKey: \"DATAFORSEO_PASSWORD\",\n },\n credentialKeys: [\"DATAFORSEO_LOGIN\", \"DATAFORSEO_PASSWORD\"],\n docsUrls: [\"https://docs.dataforseo.com/v3/\"],\n templateUses: [\"analytics\"],\n examples: [\n {\n label: \"SERP task post\",\n method: \"POST\",\n path: \"/serp/google/organic/task_post\",\n body: [\n { keyword: \"builder.io\", location_code: 2840, language_code: \"en\" },\n ],\n },\n ],\n },\n ga4: {\n id: \"ga4\",\n label: \"Google Analytics Data API\",\n defaultBaseUrl: \"https://analyticsdata.googleapis.com/v1beta\",\n auth: {\n type: \"google-service-account\",\n scopes: [\"https://www.googleapis.com/auth/analytics.readonly\"],\n },\n credentialKeys: [\"GOOGLE_APPLICATION_CREDENTIALS_JSON\", \"GA4_PROPERTY_ID\"],\n docsUrls: [\n \"https://developers.google.com/analytics/devguides/reporting/data/v1/rest\",\n ],\n specUrls: [\n \"https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta\",\n ],\n allowedHostSuffixes: [\"googleapis.com\"],\n templateUses: [\"analytics\"],\n placeholders: [\n {\n name: \"propertyId\",\n credentialKey: \"GA4_PROPERTY_ID\",\n label: \"Configured GA4 property ID\",\n },\n ],\n examples: [\n {\n label: \"Run report\",\n method: \"POST\",\n path: \"/properties/{propertyId}:runReport\",\n body: {\n dateRanges: [{ startDate: \"30daysAgo\", endDate: \"today\" }],\n metrics: [{ name: \"activeUsers\" }],\n },\n },\n ],\n },\n gcloud: {\n id: \"gcloud\",\n label: \"Google Cloud APIs\",\n defaultBaseUrl: \"https://cloudresourcemanager.googleapis.com\",\n auth: {\n type: \"google-service-account\",\n scopes: [\n \"https://www.googleapis.com/auth/cloud-platform\",\n \"https://www.googleapis.com/auth/monitoring.read\",\n \"https://www.googleapis.com/auth/logging.read\",\n \"https://www.googleapis.com/auth/bigquery\",\n ],\n },\n credentialKeys: [\n \"GOOGLE_APPLICATION_CREDENTIALS_JSON\",\n \"BIGQUERY_PROJECT_ID\",\n ],\n docsUrls: [\"https://cloud.google.com/apis/docs/overview\"],\n specUrls: [\"https://www.googleapis.com/discovery/v1/apis\"],\n allowedHostSuffixes: [\"googleapis.com\"],\n templateUses: [\"analytics\"],\n placeholders: [\n {\n name: \"projectId\",\n credentialKey: \"BIGQUERY_PROJECT_ID\",\n label: \"Configured Google Cloud project ID\",\n },\n ],\n examples: [\n {\n label: \"Get project\",\n method: \"GET\",\n path: \"https://cloudresourcemanager.googleapis.com/v1/projects/{projectId}\",\n },\n ],\n },\n github: {\n id: \"github\",\n label: \"GitHub REST API\",\n defaultBaseUrl: \"https://api.github.com\",\n auth: {\n type: \"bearer\",\n keys: [\"GITHUB_TOKEN\"],\n workspaceProvider: \"github\",\n },\n credentialKeys: [\"GITHUB_TOKEN\"],\n docsUrls: [\"https://docs.github.com/rest\"],\n specUrls: [\n \"https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json\",\n ],\n defaultHeaders: {\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n templateUses: [\"analytics\", \"brain\", \"dispatch\"],\n examples: [\n { label: \"Authenticated user\", method: \"GET\", path: \"/user\" },\n { label: \"Search issues\", method: \"GET\", path: \"/search/issues\" },\n ],\n },\n gmail: {\n id: \"gmail\",\n label: \"Gmail API\",\n defaultBaseUrl: \"https://gmail.googleapis.com/gmail/v1\",\n auth: {\n type: \"oauth-bearer\",\n oauthProvider: \"google\",\n tokenLabel: \"Google OAuth token\",\n },\n credentialKeys: [\"GOOGLE_OAUTH_ACCOUNT\"],\n docsUrls: [\"https://developers.google.com/gmail/api/reference/rest\"],\n specUrls: [\"https://gmail.googleapis.com/$discovery/rest?version=v1\"],\n allowedHostSuffixes: [\"googleapis.com\"],\n templateUses: [\"brain\", \"mail\", \"dispatch\"],\n examples: [\n {\n label: \"List messages\",\n method: \"GET\",\n path: \"/users/me/messages\",\n },\n {\n label: \"Search messages\",\n method: \"GET\",\n path: \"/users/me/messages\",\n body: undefined,\n },\n ],\n notes: [\n \"Uses the current user's stored Google OAuth account. Pass accountId when the user has multiple Google accounts connected.\",\n ],\n },\n gong: {\n id: \"gong\",\n label: \"Gong\",\n defaultBaseUrl: \"https://api.gong.io/v2\",\n baseUrlCredentialKey: \"GONG_API_BASE\",\n auth: {\n type: \"basic\",\n usernameKey: \"GONG_ACCESS_KEY\",\n passwordKey: \"GONG_ACCESS_SECRET\",\n },\n credentialKeys: [\"GONG_ACCESS_KEY\", \"GONG_ACCESS_SECRET\", \"GONG_API_BASE\"],\n docsUrls: [\"https://gong.app.gong.io/settings/api/documentation\"],\n templateUses: [\"analytics\"],\n examples: [\n { label: \"List calls\", method: \"GET\", path: \"/calls\" },\n {\n label: \"Call transcript\",\n method: \"POST\",\n path: \"/calls/transcript\",\n body: { filter: { callIds: [\"<call-id>\"] } },\n },\n ],\n },\n google_calendar: {\n id: \"google_calendar\",\n label: \"Google Calendar API\",\n defaultBaseUrl: \"https://www.googleapis.com/calendar/v3\",\n auth: {\n type: \"oauth-bearer\",\n oauthProvider: \"google\",\n tokenLabel: \"Google OAuth token\",\n },\n credentialKeys: [\"GOOGLE_OAUTH_ACCOUNT\"],\n docsUrls: [\"https://developers.google.com/calendar/api/v3/reference\"],\n specUrls: [\"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest\"],\n allowedHostSuffixes: [\"googleapis.com\"],\n templateUses: [\"brain\", \"calendar\", \"dispatch\"],\n examples: [\n {\n label: \"List calendars\",\n method: \"GET\",\n path: \"/users/me/calendarList\",\n },\n {\n label: \"Search events\",\n method: \"GET\",\n path: \"/calendars/primary/events\",\n },\n ],\n notes: [\n \"Uses the current user's stored Google OAuth account. Pass accountId when the user has multiple Google accounts connected.\",\n ],\n },\n google_drive: {\n id: \"google_drive\",\n label: \"Google Drive API\",\n defaultBaseUrl: \"https://www.googleapis.com/drive/v3\",\n auth: {\n type: \"oauth-bearer\",\n oauthProvider: \"google\",\n tokenLabel: \"Google OAuth token\",\n },\n credentialKeys: [\"GOOGLE_OAUTH_ACCOUNT\"],\n docsUrls: [\"https://developers.google.com/drive/api/reference/rest/v3\"],\n specUrls: [\"https://www.googleapis.com/discovery/v1/apis/drive/v3/rest\"],\n allowedHostSuffixes: [\"googleapis.com\"],\n templateUses: [\"brain\", \"content\", \"slides\", \"dispatch\"],\n examples: [\n { label: \"List files\", method: \"GET\", path: \"/files\" },\n { label: \"Get file metadata\", method: \"GET\", path: \"/files/{fileId}\" },\n ],\n notes: [\n \"Uses the current user's stored Google OAuth account. Pass accountId when the user has multiple Google accounts connected.\",\n ],\n },\n granola: {\n id: \"granola\",\n label: \"Granola Public API\",\n defaultBaseUrl: \"https://public-api.granola.ai/v1\",\n auth: {\n type: \"bearer\",\n keys: [\"GRANOLA_API_KEY\"],\n workspaceProvider: \"granola\",\n },\n credentialKeys: [\"GRANOLA_API_KEY\"],\n docsUrls: [\"https://docs.granola.ai/\"],\n templateUses: [\"brain\", \"dispatch\"],\n examples: [\n { label: \"List notes\", method: \"GET\", path: \"/notes\" },\n { label: \"Get note\", method: \"GET\", path: \"/notes/<note-id>\" },\n ],\n },\n grafana: {\n id: \"grafana\",\n label: \"Grafana\",\n defaultBaseUrl: \"https://grafana.example.com\",\n baseUrlCredentialKey: \"GRAFANA_URL\",\n auth: {\n type: \"bearer\",\n keys: [\"GRAFANA_API_TOKEN\"],\n },\n credentialKeys: [\"GRAFANA_URL\", \"GRAFANA_API_TOKEN\"],\n docsUrls: [\"https://grafana.com/docs/grafana/latest/developers/http_api/\"],\n templateUses: [\"analytics\"],\n examples: [\n { label: \"List dashboards\", method: \"GET\", path: \"/api/search\" },\n ],\n },\n hubspot: {\n id: \"hubspot\",\n label: \"HubSpot\",\n defaultBaseUrl: \"https://api.hubapi.com\",\n auth: {\n type: \"bearer\",\n keys: [\"HUBSPOT_PRIVATE_APP_TOKEN\", \"HUBSPOT_ACCESS_TOKEN\"],\n workspaceProvider: \"hubspot\",\n },\n credentialKeys: [\"HUBSPOT_PRIVATE_APP_TOKEN\", \"HUBSPOT_ACCESS_TOKEN\"],\n docsUrls: [\"https://developers.hubspot.com/docs/api/overview\"],\n templateUses: [\"analytics\", \"brain\", \"mail\", \"dispatch\"],\n examples: [\n {\n label: \"Search deals with any HubSpot CRM filter\",\n method: \"POST\",\n path: \"/crm/v3/objects/deals/search\",\n body: {\n filterGroups: [\n {\n filters: [\n {\n propertyName: \"products\",\n operator: \"CONTAINS_TOKEN\",\n value: \"Publish\",\n },\n ],\n },\n ],\n properties: [\"dealname\", \"products\", \"dealstage\", \"closedate\"],\n limit: 100,\n },\n },\n {\n label: \"List deal property metadata\",\n method: \"GET\",\n path: \"/crm/v3/properties/deals\",\n },\n ],\n },\n jira: {\n id: \"jira\",\n label: \"Jira Cloud\",\n defaultBaseUrl: \"https://example.atlassian.net\",\n baseUrlCredentialKey: \"JIRA_BASE_URL\",\n auth: {\n type: \"basic\",\n usernameKey: \"JIRA_USER_EMAIL\",\n passwordKey: \"JIRA_API_TOKEN\",\n },\n credentialKeys: [\"JIRA_BASE_URL\", \"JIRA_USER_EMAIL\", \"JIRA_API_TOKEN\"],\n docsUrls: [\n \"https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro/\",\n ],\n specUrls: [\n \"https://dac-static.atlassian.com/cloud/jira/platform/swagger-v3.v3.json\",\n ],\n templateUses: [\"analytics\"],\n examples: [\n {\n label: \"JQL search\",\n method: \"GET\",\n path: \"/rest/api/3/search/jql\",\n },\n ],\n },\n mixpanel: {\n id: \"mixpanel\",\n label: \"Mixpanel\",\n defaultBaseUrl: \"https://mixpanel.com/api/query\",\n auth: {\n type: \"basic-raw\",\n key: \"MIXPANEL_SERVICE_ACCOUNT\",\n },\n credentialKeys: [\"MIXPANEL_PROJECT_ID\", \"MIXPANEL_SERVICE_ACCOUNT\"],\n docsUrls: [\"https://developer.mixpanel.com/reference/overview\"],\n allowedHostSuffixes: [\"mixpanel.com\"],\n templateUses: [\"analytics\"],\n placeholders: [\n {\n name: \"projectId\",\n credentialKey: \"MIXPANEL_PROJECT_ID\",\n label: \"Configured Mixpanel project ID\",\n },\n ],\n examples: [\n {\n label: \"Query events\",\n method: \"GET\",\n path: \"/events\",\n },\n ],\n notes: [\n \"Mixpanel uses multiple API hosts. You may pass full URLs for mixpanel.com or data.mixpanel.com endpoints.\",\n ],\n },\n notion: {\n id: \"notion\",\n label: \"Notion\",\n defaultBaseUrl: \"https://api.notion.com/v1\",\n auth: {\n type: \"bearer\",\n keys: [\"NOTION_API_KEY\"],\n workspaceProvider: \"notion\",\n },\n credentialKeys: [\"NOTION_API_KEY\"],\n docsUrls: [\"https://developers.notion.com/reference/intro\"],\n defaultHeaders: { \"Notion-Version\": \"2022-06-28\" },\n templateUses: [\"analytics\", \"brain\", \"content\", \"dispatch\"],\n examples: [{ label: \"Search\", method: \"POST\", path: \"/search\", body: {} }],\n },\n posthog: {\n id: \"posthog\",\n label: \"PostHog\",\n defaultBaseUrl: \"https://app.posthog.com\",\n baseUrlCredentialKey: \"POSTHOG_HOST\",\n auth: {\n type: \"bearer\",\n keys: [\"POSTHOG_API_KEY\"],\n },\n credentialKeys: [\"POSTHOG_API_KEY\", \"POSTHOG_PROJECT_ID\", \"POSTHOG_HOST\"],\n docsUrls: [\"https://posthog.com/docs/api\"],\n templateUses: [\"analytics\"],\n placeholders: [\n {\n name: \"projectId\",\n credentialKey: \"POSTHOG_PROJECT_ID\",\n label: \"Configured PostHog project ID\",\n },\n ],\n examples: [\n {\n label: \"List events\",\n method: \"GET\",\n path: \"/api/projects/{projectId}/events/\",\n },\n ],\n },\n prometheus: {\n id: \"prometheus\",\n label: \"Prometheus\",\n defaultBaseUrl: \"https://prometheus.example.com\",\n baseUrlCredentialKey: \"PROMETHEUS_URL\",\n auth: { type: \"prometheus\" },\n credentialKeys: [\n \"PROMETHEUS_URL\",\n \"PROMETHEUS_USERNAME\",\n \"PROMETHEUS_PASSWORD\",\n \"PROMETHEUS_BEARER_TOKEN\",\n ],\n docsUrls: [\"https://prometheus.io/docs/prometheus/latest/querying/api/\"],\n templateUses: [\"analytics\"],\n examples: [\n {\n label: \"Instant query\",\n method: \"GET\",\n path: \"/api/v1/query\",\n },\n ],\n },\n pylon: {\n id: \"pylon\",\n label: \"Pylon\",\n defaultBaseUrl: \"https://api.usepylon.com\",\n auth: {\n type: \"bearer\",\n keys: [\"PYLON_API_KEY\"],\n },\n credentialKeys: [\"PYLON_API_KEY\"],\n docsUrls: [\"https://docs.usepylon.com/pylon-docs/developer/api-reference\"],\n templateUses: [\"analytics\"],\n examples: [{ label: \"List issues\", method: \"GET\", path: \"/issues\" }],\n },\n sentry: {\n id: \"sentry\",\n label: \"Sentry\",\n defaultBaseUrl: \"https://sentry.io/api/0\",\n auth: {\n type: \"bearer\",\n keys: [\"SENTRY_AUTH_TOKEN\", \"SENTRY_SERVER_TOKEN\"],\n },\n credentialKeys: [\n \"SENTRY_AUTH_TOKEN\",\n \"SENTRY_SERVER_TOKEN\",\n \"SENTRY_ORG_SLUG\",\n ],\n docsUrls: [\"https://docs.sentry.io/api/\"],\n templateUses: [\"analytics\"],\n placeholders: [\n {\n name: \"orgSlug\",\n credentialKey: \"SENTRY_ORG_SLUG\",\n label: \"Configured Sentry organization slug\",\n },\n ],\n examples: [\n {\n label: \"List issues for org\",\n method: \"GET\",\n path: \"/organizations/{orgSlug}/issues/\",\n },\n ],\n },\n slack: {\n id: \"slack\",\n label: \"Slack Web API\",\n defaultBaseUrl: \"https://slack.com/api\",\n auth: {\n type: \"bearer\",\n keys: [\"SLACK_BOT_TOKEN\"],\n workspaceProvider: \"slack\",\n },\n credentialKeys: [\"SLACK_BOT_TOKEN\", \"SLACK_BOT_TOKEN_2\"],\n docsUrls: [\"https://api.slack.com/web\"],\n specUrls: [\n \"https://api.slack.com/specs/openapi/v2/slack_web_openapi_v2_without_examples.json\",\n ],\n templateUses: [\"analytics\", \"brain\", \"dispatch\"],\n examples: [\n { label: \"Search messages\", method: \"GET\", path: \"/search.messages\" },\n { label: \"Post message\", method: \"POST\", path: \"/chat.postMessage\" },\n ],\n },\n stripe: {\n id: \"stripe\",\n label: \"Stripe\",\n defaultBaseUrl: \"https://api.stripe.com/v1\",\n auth: {\n type: \"bearer\",\n keys: [\"STRIPE_SECRET_KEY\"],\n },\n credentialKeys: [\"STRIPE_SECRET_KEY\"],\n docsUrls: [\"https://docs.stripe.com/api\"],\n specUrls: [\n \"https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json\",\n ],\n templateUses: [\"analytics\"],\n examples: [{ label: \"List customers\", method: \"GET\", path: \"/customers\" }],\n },\n twitter: {\n id: \"twitter\",\n label: \"Twitter/X via twitterapi.io\",\n defaultBaseUrl: \"https://api.twitterapi.io\",\n auth: {\n type: \"api-key-header\",\n key: \"TWITTER_BEARER_TOKEN\",\n header: \"X-API-Key\",\n },\n credentialKeys: [\"TWITTER_BEARER_TOKEN\"],\n docsUrls: [\"https://twitterapi.io/docs\"],\n templateUses: [\"analytics\"],\n examples: [\n {\n label: \"User tweets\",\n method: \"GET\",\n path: \"/twitter/user/last_tweets\",\n },\n ],\n },\n};\n\nexport function getProviderApiConfig(\n provider: ProviderApiId | string,\n): ProviderApiConfig {\n const config = PROVIDER_CONFIGS[provider as ProviderApiId];\n if (!config) throw new Error(`Unsupported provider API: ${provider}`);\n return config;\n}\n\nexport function isProviderApiId(provider: string): provider is ProviderApiId {\n return Object.prototype.hasOwnProperty.call(PROVIDER_CONFIGS, provider);\n}\n\nexport function listProviderApiIdsForTemplateUse(\n templateUse: WorkspaceConnectionTemplateUse,\n): ProviderApiId[] {\n return PROVIDER_API_IDS.filter((id) =>\n (PROVIDER_CONFIGS[id].templateUses ?? []).includes(templateUse),\n );\n}\n\nexport function listProviderApiCatalog(\n provider?: ProviderApiId | string,\n options: { providerIds?: readonly (ProviderApiId | string)[] } = {},\n) {\n const providerIds = normalizeProviderIds(options.providerIds);\n const configs = provider\n ? [getProviderApiConfig(provider)]\n : providerIds.map((id) => getProviderApiConfig(id));\n return configs.map((config) => ({\n id: config.id,\n label: config.label,\n defaultBaseUrl: config.defaultBaseUrl,\n baseUrlCredentialKey: config.baseUrlCredentialKey ?? null,\n auth: describeAuth(config.auth),\n credentialKeys: config.credentialKeys,\n docsUrls: config.docsUrls,\n specUrls: config.specUrls ?? [],\n allowedHostSuffixes: config.allowedHostSuffixes ?? [],\n placeholders: config.placeholders ?? [],\n defaultHeaders: config.defaultHeaders ?? {},\n examples: config.examples ?? [],\n notes: config.notes ?? [],\n templateUses: config.templateUses ?? [],\n }));\n}\n\nexport function createProviderApiRuntime(\n options: ProviderApiRuntimeOptions,\n): ProviderApiRuntime {\n const providerIds = normalizeProviderIds(options.providerIds);\n const runtimeOptions: Required<\n Pick<ProviderApiRuntimeOptions, \"appId\" | \"localCredentialSource\">\n > &\n Omit<ProviderApiRuntimeOptions, \"appId\" | \"localCredentialSource\"> = {\n ...options,\n providerIds,\n localCredentialSource: options.localCredentialSource ?? \"app_local\",\n };\n return {\n providerIds,\n listCatalog: (provider) =>\n listProviderApiCatalog(provider, { providerIds }),\n fetchDocs: (docsOptions) =>\n fetchProviderApiDocs(docsOptions, runtimeOptions),\n executeRequest: (args) => executeProviderApiRequest(args, runtimeOptions),\n };\n}\n\nexport async function fetchProviderApiDocs(\n options: {\n provider: ProviderApiId | string;\n url?: string;\n maxBytes?: number;\n },\n runtime: ProviderApiRuntimeOptions = { appId: \"app\" },\n) {\n assertProviderAllowed(options.provider, runtime.providerIds);\n const config = getProviderApiConfig(options.provider);\n const catalog = listProviderApiCatalog(options.provider)[0];\n if (!options.url) return { provider: config.id, catalog };\n\n const url = new URL(options.url);\n const allowed = [\n ...config.docsUrls,\n ...(config.specUrls ?? []),\n config.defaultBaseUrl,\n ].some((allowedUrl) => sameOriginOrChild(url, new URL(allowedUrl)));\n if (!allowed) {\n throw new Error(\n `Docs URL must be one of the registered ${config.label} docs/spec origins.`,\n );\n }\n if (await isBlockedExtensionUrlWithDns(url.href)) {\n throw new Error(`Blocked private/internal docs URL: ${url.href}`);\n }\n\n const response = await fetchWithTimeout(url.href, {\n method: \"GET\",\n maxBytes: clampMaxBytes(options.maxBytes),\n });\n return {\n provider: config.id,\n catalog,\n request: { url: url.href },\n response,\n };\n}\n\nexport async function executeProviderApiRequest(\n args: ProviderApiRequestArgs,\n runtime: ProviderApiRuntimeOptions,\n) {\n assertProviderAllowed(args.provider, runtime.providerIds);\n const config = getProviderApiConfig(args.provider);\n const ctx = requireRuntimeCredentialContext(\n runtime,\n config.credentialKeys[0] ?? config.id,\n );\n const baseUrl = await resolveBaseUrl(config, runtime, ctx, args);\n const placeholders = await resolvePlaceholders(config, runtime, ctx, args);\n const method = normalizeMethod(args.method);\n const url = buildProviderUrl({\n config,\n baseUrl,\n rawPath: substituteString(args.path, placeholders),\n query: substituteUnknown(args.query, placeholders),\n });\n if (await isBlockedExtensionUrlWithDns(url.href)) {\n throw new Error(`Blocked private/internal provider URL: ${url.href}`);\n }\n\n const auth =\n args.auth === \"none\"\n ? emptyAuth()\n : await resolveAuth(config, runtime, ctx, args);\n const extraHeaders = substituteUnknown(args.headers ?? {}, placeholders);\n const headers = sanitizeOutboundHeaders({\n ...(config.defaultHeaders ?? {}),\n ...(isPlainRecord(extraHeaders) ? extraHeaders : {}),\n ...auth.headers,\n });\n const body = prepareBody(substituteUnknown(args.body, placeholders), headers);\n const response = await fetchWithTimeout(url.href, {\n method,\n headers,\n body,\n maxBytes: clampMaxBytes(args.maxBytes),\n timeoutMs: clampTimeout(args.timeoutMs),\n secretValues: auth.secretValues,\n });\n\n return {\n provider: {\n id: config.id,\n label: config.label,\n docsUrls: config.docsUrls,\n specUrls: config.specUrls ?? [],\n },\n request: {\n method,\n url: redactString(url.href, auth.secretValues),\n path: redactString(`${url.pathname}${url.search}`, auth.secretValues),\n auth: args.auth === \"none\" ? \"none\" : describeAuth(config.auth),\n credentialSources: auth.credentialSources.map((source) => ({\n ...source,\n fingerprint: fingerprint(source.key),\n })),\n headerNames: Object.keys(headers).filter(\n (name) => name.toLowerCase() !== \"authorization\",\n ),\n ...(args.accountId ? { accountId: args.accountId } : {}),\n ...(args.connectionId ? { connectionId: args.connectionId } : {}),\n },\n response,\n guidance:\n \"This was a raw provider API request. Use provider docs/spec URLs to choose endpoints and include method/path/status plus relevant filters in the methodology. Prefer this escape hatch whenever canned actions are too narrow.\",\n };\n}\n\nexport async function defaultProviderApiCredentialResolver(\n options: ProviderApiCredentialLookupOptions,\n): Promise<ProviderApiResolvedCredential | null> {\n if (options.workspaceProvider) {\n const result = await resolveWorkspaceConnectionCredentialForApp({\n appId: options.appId,\n provider: options.workspaceProvider,\n key: options.key,\n connectionId: options.connectionId,\n userEmail: options.ctx.userEmail,\n orgId: options.ctx.orgId,\n });\n if (result.available && result.value) {\n return {\n key: result.provenance?.resolvedKey ?? result.key,\n value: result.value,\n source: \"workspace_connection\",\n provider: result.provider,\n connectionId: result.provenance?.connectionId,\n connectionLabel: result.provenance?.connectionLabel,\n scope:\n typeof result.provenance?.secretScope === \"string\"\n ? result.provenance.secretScope\n : undefined,\n };\n }\n }\n\n const value = await resolveCredential(options.key, options.ctx);\n if (!value) return null;\n return {\n key: options.key,\n value,\n source: options.localCredentialSource,\n provider: options.provider,\n };\n}\n\nfunction normalizeProviderIds(\n providerIds?: readonly (ProviderApiId | string)[],\n): ProviderApiId[] {\n if (!providerIds) return [...PROVIDER_API_IDS];\n const result: ProviderApiId[] = [];\n const seen = new Set<string>();\n for (const providerId of providerIds) {\n if (!isProviderApiId(providerId)) {\n throw new Error(`Unsupported provider API: ${providerId}`);\n }\n if (seen.has(providerId)) continue;\n seen.add(providerId);\n result.push(providerId);\n }\n return result;\n}\n\nfunction assertProviderAllowed(\n provider: ProviderApiId | string,\n providerIds?: readonly (ProviderApiId | string)[],\n) {\n const allowed = normalizeProviderIds(providerIds);\n if (!allowed.includes(provider as ProviderApiId)) {\n throw new Error(`Provider API ${provider} is not enabled for this app.`);\n }\n}\n\nfunction describeAuth(auth: ProviderApiAuthKind): string {\n if (auth.type === \"none\") return \"none\";\n if (auth.type === \"bearer\") return \"bearer\";\n if (auth.type === \"basic\") return \"basic\";\n if (auth.type === \"basic-raw\") return \"basic\";\n if (auth.type === \"api-key-header\") return `api-key-header:${auth.header}`;\n if (auth.type === \"google-service-account\") return \"google-service-account\";\n if (auth.type === \"oauth-bearer\") return `oauth-bearer:${auth.oauthProvider}`;\n return \"prometheus-basic-or-bearer\";\n}\n\nfunction requireRuntimeCredentialContext(\n runtime: ProviderApiRuntimeOptions,\n credentialKey: string,\n): CredentialContext {\n const ctx = runtime.getCredentialContext?.() ?? getCredentialContext();\n if (!ctx) {\n throw new Error(\n `Cannot resolve credential \"${credentialKey}\" outside an authenticated request context.`,\n );\n }\n return ctx;\n}\n\nasync function resolveBaseUrl(\n config: ProviderApiConfig,\n runtime: ProviderApiRuntimeOptions,\n ctx: CredentialContext,\n args: ProviderApiRequestArgs,\n): Promise<string> {\n if (!config.baseUrlCredentialKey) return config.defaultBaseUrl;\n const configured = await resolveCredentialValue({\n config,\n runtime,\n ctx,\n key: config.baseUrlCredentialKey,\n args,\n });\n return (configured || config.defaultBaseUrl).replace(/\\/+$/, \"\");\n}\n\nasync function resolvePlaceholders(\n config: ProviderApiConfig,\n runtime: ProviderApiRuntimeOptions,\n ctx: CredentialContext,\n args: ProviderApiRequestArgs,\n): Promise<Record<string, string>> {\n const placeholders: Record<string, string> = {};\n for (const placeholder of config.placeholders ?? []) {\n const value = await resolveCredentialValue({\n config,\n runtime,\n ctx,\n key: placeholder.credentialKey,\n args,\n });\n if (value) placeholders[placeholder.name] = value;\n }\n return placeholders;\n}\n\nasync function resolveCredentialValue(options: {\n config: ProviderApiConfig;\n runtime: ProviderApiRuntimeOptions;\n ctx: CredentialContext;\n key: string;\n args: ProviderApiRequestArgs;\n workspaceProvider?: string;\n}): Promise<string | undefined> {\n const credential = await resolveOptionalCredential({\n provider: options.config.id,\n workspaceProvider: options.workspaceProvider,\n key: options.key,\n ctx: options.ctx,\n runtime: options.runtime,\n connectionId: options.args.connectionId,\n });\n return credential?.value;\n}\n\nfunction substituteString(\n value: string,\n placeholders: Record<string, string>,\n): string {\n let result = value;\n for (const [name, replacement] of Object.entries(placeholders)) {\n result = result.split(`{${name}}`).join(replacement);\n }\n return result;\n}\n\nfunction substituteUnknown(\n value: unknown,\n placeholders: Record<string, string>,\n): unknown {\n if (typeof value === \"string\") return substituteString(value, placeholders);\n if (Array.isArray(value)) {\n return value.map((item) => substituteUnknown(item, placeholders));\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [\n key,\n substituteUnknown(entry, placeholders),\n ]),\n );\n }\n return value;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction buildProviderUrl(options: {\n config: ProviderApiConfig;\n baseUrl: string;\n rawPath: string;\n query: unknown;\n}): URL {\n const base = new URL(options.baseUrl);\n const rawPath = options.rawPath.trim();\n const url = /^https?:\\/\\//i.test(rawPath)\n ? new URL(rawPath)\n : new URL(rawPath.startsWith(\"/\") ? rawPath : `/${rawPath}`, base);\n\n if (!isAllowedProviderUrl(url, base, options.config)) {\n throw new Error(\n `${options.config.label} API requests must stay on the configured provider host or registered provider host suffix.`,\n );\n }\n\n for (const [key, value] of queryEntries(options.query)) {\n url.searchParams.append(key, value);\n }\n\n return url;\n}\n\nfunction isAllowedProviderUrl(\n url: URL,\n base: URL,\n config: ProviderApiConfig,\n): boolean {\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return false;\n if (url.origin === base.origin) return true;\n const host = url.hostname.toLowerCase();\n return (config.allowedHostSuffixes ?? []).some((suffix) => {\n const normalized = suffix.toLowerCase().replace(/^\\./, \"\");\n return host === normalized || host.endsWith(`.${normalized}`);\n });\n}\n\nfunction sameOriginOrChild(candidate: URL, allowed: URL): boolean {\n return (\n candidate.origin === allowed.origin &&\n (candidate.pathname === allowed.pathname ||\n candidate.pathname.startsWith(allowed.pathname.replace(/\\/?$/, \"/\")))\n );\n}\n\nfunction queryEntries(value: unknown): Array<[string, string]> {\n if (!value) return [];\n if (typeof value === \"string\") {\n const params = new URLSearchParams(value.replace(/^\\?/, \"\"));\n return Array.from(params.entries());\n }\n if (typeof value !== \"object\" || Array.isArray(value)) return [];\n const entries: Array<[string, string]> = [];\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n if (Array.isArray(raw)) {\n for (const item of raw) entries.push([key, String(item)]);\n } else {\n entries.push([key, String(raw)]);\n }\n }\n return entries;\n}\n\nasync function resolveAuth(\n config: ProviderApiConfig,\n runtime: ProviderApiRuntimeOptions,\n ctx: CredentialContext,\n args: ProviderApiRequestArgs,\n): Promise<ResolvedAuth> {\n const auth = config.auth;\n if (auth.type === \"none\") return emptyAuth();\n if (auth.type === \"bearer\") {\n const credential = await resolveAnyCredential({\n provider: config.id,\n workspaceProvider: auth.workspaceProvider,\n keys: auth.keys,\n ctx,\n runtime,\n connectionId: args.connectionId,\n });\n return {\n headers: { Authorization: `Bearer ${credential.value}` },\n credentialSources: [omitCredentialValue(credential)],\n secretValues: [credential.value],\n };\n }\n if (auth.type === \"basic\") {\n const username = await resolveRequiredCredential({\n provider: config.id,\n workspaceProvider: auth.workspaceProvider,\n key: auth.usernameKey,\n ctx,\n runtime,\n connectionId: args.connectionId,\n });\n const password =\n auth.passwordKey === auth.usernameKey\n ? username\n : await resolveRequiredCredential({\n provider: config.id,\n workspaceProvider: auth.workspaceProvider,\n key: auth.passwordKey,\n ctx,\n runtime,\n connectionId: args.connectionId,\n });\n const encoded = Buffer.from(`${username.value}:${password.value}`).toString(\n \"base64\",\n );\n return {\n headers: { Authorization: `Basic ${encoded}` },\n credentialSources: [\n omitCredentialValue(username),\n ...(password.key === username.key\n ? []\n : [omitCredentialValue(password)]),\n ],\n secretValues: [username.value, password.value, encoded],\n };\n }\n if (auth.type === \"basic-raw\") {\n const credential = await resolveRequiredCredential({\n provider: config.id,\n workspaceProvider: auth.workspaceProvider,\n key: auth.key,\n ctx,\n runtime,\n connectionId: args.connectionId,\n });\n const encoded = Buffer.from(credential.value).toString(\"base64\");\n return {\n headers: { Authorization: `Basic ${encoded}` },\n credentialSources: [omitCredentialValue(credential)],\n secretValues: [credential.value, encoded],\n };\n }\n if (auth.type === \"api-key-header\") {\n const credential = await resolveRequiredCredential({\n provider: config.id,\n workspaceProvider: auth.workspaceProvider,\n key: auth.key,\n ctx,\n runtime,\n connectionId: args.connectionId,\n });\n return {\n headers: { [auth.header]: credential.value },\n credentialSources: [omitCredentialValue(credential)],\n secretValues: [credential.value],\n };\n }\n if (auth.type === \"google-service-account\") {\n const token = await getGoogleServiceAccountToken(auth.scopes, runtime, ctx);\n return {\n headers: { Authorization: `Bearer ${token}` },\n credentialSources: [\n {\n key: \"GOOGLE_APPLICATION_CREDENTIALS_JSON\",\n provider: config.id,\n source: runtime.localCredentialSource ?? \"app_local\",\n },\n ],\n secretValues: [token],\n };\n }\n if (auth.type === \"oauth-bearer\") {\n const credential = await resolveOAuthBearerToken({\n auth,\n ctx,\n accountId: args.accountId,\n });\n return {\n headers: { Authorization: `Bearer ${credential.value}` },\n credentialSources: [omitCredentialValue(credential)],\n secretValues: [credential.value],\n };\n }\n\n const bearer = await resolveCredentialValue({\n config,\n runtime,\n ctx,\n key: \"PROMETHEUS_BEARER_TOKEN\",\n args,\n });\n if (bearer) {\n return {\n headers: { Authorization: `Bearer ${bearer}` },\n credentialSources: [\n {\n key: \"PROMETHEUS_BEARER_TOKEN\",\n provider: config.id,\n source: runtime.localCredentialSource ?? \"app_local\",\n },\n ],\n secretValues: [bearer],\n };\n }\n const username = await resolveCredentialValue({\n config,\n runtime,\n ctx,\n key: \"PROMETHEUS_USERNAME\",\n args,\n });\n const password = await resolveCredentialValue({\n config,\n runtime,\n ctx,\n key: \"PROMETHEUS_PASSWORD\",\n args,\n });\n if (username && password) {\n const encoded = Buffer.from(`${username}:${password}`).toString(\"base64\");\n return {\n headers: { Authorization: `Basic ${encoded}` },\n credentialSources: [\n {\n key: \"PROMETHEUS_USERNAME\",\n provider: config.id,\n source: runtime.localCredentialSource ?? \"app_local\",\n },\n {\n key: \"PROMETHEUS_PASSWORD\",\n provider: config.id,\n source: runtime.localCredentialSource ?? \"app_local\",\n },\n ],\n secretValues: [username, password, encoded],\n };\n }\n return emptyAuth();\n}\n\nfunction emptyAuth(): ResolvedAuth {\n return { headers: {}, credentialSources: [], secretValues: [] };\n}\n\nasync function resolveAnyCredential(options: {\n provider: ProviderApiId;\n workspaceProvider: string | undefined;\n keys: readonly string[];\n ctx: CredentialContext;\n runtime: ProviderApiRuntimeOptions;\n connectionId?: string | null;\n}): Promise<ProviderApiResolvedCredential> {\n for (const key of options.keys) {\n const credential = await resolveOptionalCredential({ ...options, key });\n if (credential?.value) return credential;\n }\n throw new Error(\n `${options.provider} credential not configured. Tried: ${options.keys.join(\n \", \",\n )}`,\n );\n}\n\nasync function resolveRequiredCredential(options: {\n provider: ProviderApiId;\n workspaceProvider: string | undefined;\n key: string;\n ctx: CredentialContext;\n runtime: ProviderApiRuntimeOptions;\n connectionId?: string | null;\n}): Promise<ProviderApiResolvedCredential> {\n const credential = await resolveOptionalCredential(options);\n if (!credential?.value) throw new Error(`${options.key} not configured`);\n return credential;\n}\n\nasync function resolveOptionalCredential(options: {\n provider: ProviderApiId;\n workspaceProvider: string | undefined;\n key: string;\n ctx: CredentialContext;\n runtime: ProviderApiRuntimeOptions;\n connectionId?: string | null;\n}): Promise<ProviderApiResolvedCredential | null> {\n const localCredentialSource =\n options.runtime.localCredentialSource ?? \"app_local\";\n const lookup: ProviderApiCredentialLookupOptions = {\n appId: options.runtime.appId,\n provider: options.provider,\n key: options.key,\n ctx: options.ctx,\n workspaceProvider: options.workspaceProvider,\n connectionId: options.connectionId,\n localCredentialSource,\n };\n const customCredential = await options.runtime.resolveCredential?.(lookup);\n if (customCredential?.value) return customCredential;\n return defaultProviderApiCredentialResolver(lookup);\n}\n\nfunction omitCredentialValue(\n credential: ProviderApiResolvedCredential,\n): Omit<ProviderApiResolvedCredential, \"value\"> {\n const { value: _value, ...rest } = credential;\n return rest;\n}\n\nconst googleServiceTokenCache = new Map<\n string,\n { token: string; expiresAt: number }\n>();\n\nasync function getGoogleServiceAccountToken(\n scopes: readonly string[],\n runtime: ProviderApiRuntimeOptions,\n ctx: CredentialContext,\n): Promise<string> {\n const cacheKey = createHash(\"sha256\")\n .update(\n `${runtime.appId}:${ctx.orgId ?? ctx.userEmail}:${scopes.join(\" \")}`,\n )\n .digest(\"hex\");\n const cached = googleServiceTokenCache.get(cacheKey);\n if (cached && Date.now() < cached.expiresAt - 30_000) return cached.token;\n\n const credsJson = await resolveCredentialValue({\n config: getProviderApiConfig(\"gcloud\"),\n runtime,\n ctx,\n key: \"GOOGLE_APPLICATION_CREDENTIALS_JSON\",\n args: { provider: \"gcloud\", path: \"/\" },\n });\n if (!credsJson) {\n throw new Error(\"GOOGLE_APPLICATION_CREDENTIALS_JSON not configured\");\n }\n let creds: {\n type?: string;\n client_email?: string;\n private_key?: string;\n token_uri?: string;\n };\n try {\n creds = JSON.parse(credsJson) as typeof creds;\n } catch {\n throw new Error(\n \"GOOGLE_APPLICATION_CREDENTIALS_JSON is not valid JSON. Upload a service account JSON key.\",\n );\n }\n if (!creds.client_email || !creds.private_key) {\n throw new Error(\n \"GOOGLE_APPLICATION_CREDENTIALS_JSON must be a service account JSON key.\",\n );\n }\n\n const now = Math.floor(Date.now() / 1000);\n const aud = creds.token_uri || \"https://oauth2.googleapis.com/token\";\n const jwt = await signRs256Jwt(\n {\n iss: creds.client_email,\n scope: scopes.join(\" \"),\n aud,\n iat: now,\n exp: now + 3600,\n },\n creds.private_key,\n );\n const res = await fetch(aud, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n assertion: jwt,\n }),\n });\n if (!res.ok) {\n throw new Error(`Google OAuth error ${res.status}: ${await res.text()}`);\n }\n const data = (await res.json()) as {\n access_token: string;\n expires_in?: number;\n };\n googleServiceTokenCache.set(cacheKey, {\n token: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000,\n });\n return data.access_token;\n}\n\nasync function resolveOAuthBearerToken(options: {\n auth: Extract<ProviderApiAuthKind, { type: \"oauth-bearer\" }>;\n ctx: CredentialContext;\n accountId?: string | null;\n}): Promise<ProviderApiResolvedCredential> {\n const accounts = await listOAuthAccountsByOwner(\n options.auth.oauthProvider,\n options.ctx.userEmail,\n );\n if (accounts.length === 0) {\n throw new Error(\n `${options.auth.tokenLabel} is not connected for ${options.ctx.userEmail}.`,\n );\n }\n const accountId = options.accountId?.trim();\n const account = accountId\n ? accounts.find((entry) => entry.accountId === accountId)\n : accounts[0];\n if (!account) {\n throw new Error(\n `${options.auth.tokenLabel} account ${accountId} is not available to ${options.ctx.userEmail}.`,\n );\n }\n const tokens = account.tokens as OAuthTokens;\n const token = await getValidOAuthAccessToken({\n oauthProvider: options.auth.oauthProvider,\n accountId: account.accountId,\n ownerEmail: options.ctx.userEmail,\n tokens,\n });\n return {\n key: `${options.auth.oauthProvider.toUpperCase()}_OAUTH_TOKEN`,\n value: token,\n source: \"oauth_token\",\n provider: options.auth.oauthProvider,\n accountId: account.accountId,\n accountLabel: account.displayName,\n };\n}\n\nasync function getValidOAuthAccessToken(options: {\n oauthProvider: string;\n accountId: string;\n ownerEmail: string;\n tokens: OAuthTokens;\n}): Promise<string> {\n const accessToken =\n options.tokens.access_token ?? options.tokens.accessToken ?? \"\";\n if (!accessToken) {\n throw new Error(\n `${options.oauthProvider} OAuth account has no access token.`,\n );\n }\n const expiresAt = options.tokens.expiry_date ?? options.tokens.expiresAt;\n if (\n !expiresAt ||\n !Number.isFinite(expiresAt) ||\n expiresAt > Date.now() + 60_000\n ) {\n return accessToken;\n }\n\n const refreshToken =\n options.tokens.refresh_token ?? options.tokens.refreshToken;\n if (!refreshToken) return accessToken;\n if (options.oauthProvider === \"google\") {\n return refreshGoogleOAuthToken(options, refreshToken);\n }\n throw new Error(\n `${options.oauthProvider} OAuth token is expired and automatic refresh is not configured for provider-api.`,\n );\n}\n\nasync function refreshGoogleOAuthToken(\n options: {\n oauthProvider: string;\n accountId: string;\n ownerEmail: string;\n tokens: OAuthTokens;\n },\n refreshToken: string,\n): Promise<string> {\n const clientId = process.env.GOOGLE_CLIENT_ID;\n const clientSecret = process.env.GOOGLE_CLIENT_SECRET;\n if (!clientId || !clientSecret) {\n throw new Error(\n \"GOOGLE_CLIENT_ID/SECRET not set for Google OAuth refresh.\",\n );\n }\n const res = await fetch(\"https://oauth2.googleapis.com/token\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n refresh_token: refreshToken,\n client_id: clientId,\n client_secret: clientSecret,\n grant_type: \"refresh_token\",\n }),\n });\n const data = (await res.json()) as {\n access_token?: string;\n expires_in?: number;\n token_type?: string;\n scope?: string;\n error?: string;\n error_description?: string;\n };\n if (!res.ok || !data.access_token) {\n const detail = data.error_description ?? data.error ?? res.statusText;\n throw new Error(`Google OAuth refresh failed: ${detail}`);\n }\n const merged: OAuthTokens = {\n ...options.tokens,\n access_token: data.access_token,\n expiry_date: Date.now() + (data.expires_in ?? 3600) * 1000,\n token_type: data.token_type ?? options.tokens.token_type,\n scope: data.scope ?? options.tokens.scope,\n };\n await saveOAuthTokens(\n options.oauthProvider,\n options.accountId,\n merged as unknown as Record<string, unknown>,\n options.ownerEmail,\n );\n return data.access_token;\n}\n\nfunction normalizeMethod(\n method: ProviderApiMethod | undefined,\n): ProviderApiMethod {\n const normalized = String(method || \"GET\").toUpperCase();\n if (\n normalized === \"GET\" ||\n normalized === \"POST\" ||\n normalized === \"PUT\" ||\n normalized === \"PATCH\" ||\n normalized === \"DELETE\" ||\n normalized === \"HEAD\"\n ) {\n return normalized;\n }\n throw new Error(`Unsupported HTTP method: ${method}`);\n}\n\nfunction sanitizeOutboundHeaders(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const headers: Record<string, string> = {};\n for (const [name, rawValue] of Object.entries(value)) {\n const lower = name.toLowerCase();\n if (!HEADER_NAME_RE.test(name) || BLOCKED_OUTBOUND_HEADERS.has(lower)) {\n continue;\n }\n if (rawValue === undefined || rawValue === null) continue;\n const headerValue = String(rawValue);\n if (/[\\r\\n]/.test(headerValue)) continue;\n headers[name] = headerValue;\n }\n return headers;\n}\n\nfunction prepareBody(\n body: unknown,\n headers: Record<string, string>,\n): BodyInit | undefined {\n if (body === undefined || body === null) return undefined;\n if (typeof body === \"string\") return body;\n const hasContentType = Object.keys(headers).some(\n (name) => name.toLowerCase() === \"content-type\",\n );\n if (!hasContentType) headers[\"Content-Type\"] = \"application/json\";\n return JSON.stringify(body);\n}\n\nasync function fetchWithTimeout(\n optionsUrl: string,\n options: {\n method?: ProviderApiMethod;\n headers?: Record<string, string>;\n body?: BodyInit;\n timeoutMs?: number;\n maxBytes?: number;\n secretValues?: string[];\n },\n) {\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n clampTimeout(options.timeoutMs),\n );\n try {\n const dispatcher = (await createSsrfSafeDispatcher()) ?? undefined;\n const fetchOptions: RequestInit & { dispatcher?: unknown } = {\n method: options.method ?? \"GET\",\n headers: options.headers,\n body: options.body,\n signal: controller.signal,\n redirect: \"manual\",\n };\n if (dispatcher) fetchOptions.dispatcher = dispatcher;\n const startedAt = Date.now();\n const res = await fetch(optionsUrl, fetchOptions);\n const elapsedMs = Date.now() - startedAt;\n const rawText = await readResponseTextWithLimit(\n res,\n clampMaxBytes(options.maxBytes),\n );\n const secretValues = options.secretValues ?? [];\n const redactedText = redactString(rawText.text, secretValues);\n const parsed = tryParseJson(redactedText);\n return {\n status: res.status,\n statusText: res.statusText,\n ok: res.ok,\n elapsedMs,\n headers: redactSecrets(headersToObject(res.headers), secretValues),\n contentType: res.headers.get(\"content-type\") ?? null,\n size: rawText.size,\n truncated: rawText.truncated,\n text: parsed === undefined ? redactedText : undefined,\n json: parsed,\n };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function readResponseTextWithLimit(\n response: Response,\n maxBytes: number,\n): Promise<{ text: string; truncated: boolean; size: number }> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength && Number(contentLength) > maxBytes) {\n return {\n text: `(response too large - ${contentLength} bytes, max ${maxBytes})`,\n truncated: true,\n size: Number(contentLength),\n };\n }\n const buffer = await response.arrayBuffer();\n const size = buffer.byteLength;\n const bytes = new Uint8Array(buffer.slice(0, maxBytes));\n return {\n text: new TextDecoder().decode(bytes),\n truncated: size > maxBytes,\n size,\n };\n}\n\nfunction headersToObject(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"set-cookie\") result[key] = value;\n });\n return result;\n}\n\nfunction tryParseJson(text: string): unknown | undefined {\n const trimmed = text.trim();\n if (!trimmed || !/^[{[]/.test(trimmed)) return undefined;\n try {\n return JSON.parse(trimmed);\n } catch {\n return undefined;\n }\n}\n\nfunction redactSecrets<T>(value: T, secretValues: string[]): T {\n if (secretValues.length === 0) return value;\n if (typeof value === \"string\") return redactString(value, secretValues) as T;\n if (Array.isArray(value)) {\n return value.map((item) => redactSecrets(item, secretValues)) as T;\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [\n key,\n redactSecrets(entry, secretValues),\n ]),\n ) as T;\n }\n return value;\n}\n\nfunction redactString(text: string, secretValues: string[]): string {\n let output = text;\n for (const secret of [...secretValues].sort((a, b) => b.length - a.length)) {\n if (!secret) continue;\n output = output.split(secret).join(\"[redacted]\");\n try {\n output = output.split(encodeURIComponent(secret)).join(\"[redacted]\");\n } catch {}\n }\n return output;\n}\n\nfunction clampTimeout(timeoutMs: number | undefined): number {\n if (!Number.isFinite(timeoutMs)) return DEFAULT_TIMEOUT_MS;\n return Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.floor(timeoutMs!)));\n}\n\nfunction clampMaxBytes(maxBytes: number | undefined): number {\n if (!Number.isFinite(maxBytes)) return DEFAULT_MAX_BYTES;\n return Math.max(1_000, Math.min(MAX_MAX_BYTES, Math.floor(maxBytes!)));\n}\n\nfunction fingerprint(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 12);\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 1) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\nfunction base64UrlEncodeString(value: string): string {\n return base64UrlEncode(new TextEncoder().encode(value));\n}\n\nfunction pemToPkcs8(pem: string): Uint8Array {\n const body = pem\n .replace(/-----BEGIN [^-]+-----/g, \"\")\n .replace(/-----END [^-]+-----/g, \"\")\n .replace(/\\s+/g, \"\");\n const binary = atob(body);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n out[i] = binary.charCodeAt(i);\n }\n return out;\n}\n\nconst keyCache = new Map<string, Promise<CryptoKey>>();\n\nfunction importRs256Key(privateKeyPem: string): Promise<CryptoKey> {\n let cached = keyCache.get(privateKeyPem);\n if (!cached) {\n cached = crypto.subtle.importKey(\n \"pkcs8\",\n pemToPkcs8(privateKeyPem) as BufferSource,\n { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n keyCache.set(privateKeyPem, cached);\n }\n return cached;\n}\n\nasync function signRs256Jwt(\n payload: Record<string, unknown>,\n privateKeyPem: string,\n): Promise<string> {\n const header = { alg: \"RS256\", typ: \"JWT\" };\n const signingInput = `${base64UrlEncodeString(\n JSON.stringify(header),\n )}.${base64UrlEncodeString(JSON.stringify(payload))}`;\n\n const key = await importRs256Key(privateKeyPem);\n const signature = await crypto.subtle.sign(\n \"RSASSA-PKCS1-v1_5\",\n key,\n new TextEncoder().encode(signingInput) as BufferSource,\n );\n\n return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"action-discovery.d.ts","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AA4ChE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACnC,IAAI,CAKN;AA6OD;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAqC7B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAgGtC;AAED,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACpC,OAAO,CAAC,IAAI,CAAC,CA2Cf;AAED,oDAAoD;AACpD,eAAO,MAAM,mBAAmB,4BAAsB,CAAC"}
1
+ {"version":3,"file":"action-discovery.d.ts","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AA4ChE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACnC,IAAI,CAKN;AA6OD;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAqC7B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAgGtC;AAED,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACpC,OAAO,CAAC,IAAI,CAAC,CA+Df;AAED,oDAAoD;AACpD,eAAO,MAAM,mBAAmB,4BAAsB,CAAC"}
@@ -444,6 +444,26 @@ export async function mergeCoreSharingActions(registry) {
444
444
  () => import("../sharing/actions/set-resource-visibility.js"),
445
445
  ],
446
446
  ["upload-image", () => import("../file-upload/actions/upload-image.js")],
447
+ [
448
+ "context-manifest-get",
449
+ () => import("../agent/context-xray/actions/context-manifest-get.js"),
450
+ ],
451
+ [
452
+ "context-pin",
453
+ () => import("../agent/context-xray/actions/context-pin.js"),
454
+ ],
455
+ [
456
+ "context-evict",
457
+ () => import("../agent/context-xray/actions/context-evict.js"),
458
+ ],
459
+ [
460
+ "context-restore",
461
+ () => import("../agent/context-xray/actions/context-restore.js"),
462
+ ],
463
+ [
464
+ "context-report",
465
+ () => import("../agent/context-xray/actions/context-report.js"),
466
+ ],
447
467
  [
448
468
  "change-appearance",
449
469
  () => import("../appearance/actions/change-appearance.js"),
@@ -1 +1 @@
1
- {"version":3,"file":"action-discovery.js","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AA6BA,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD,sDAAsD;AACtD,yFAAyF;AACzF,IAAI,GAAoC,CAAC;AACzC,KAAK,UAAU,KAAK;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,GAAG,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AACD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,0DAA0D;AAC1D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,SAAS;IACT,KAAK;IACL,YAAY;IACZ,WAAW;IACX,UAAU;CACX,CAAC,CAAC;AAEH,SAAS,mBAAmB,CAAC,QAAgB;IAC3C,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/C,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,yBAAyB,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3D,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,qBAAqB,GAAgC,EAAE,CAAC;AAE9D;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAoC;IAEpC,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AAE,CAAC,MAAM,CAAC,+CAA+C,CAAC;SAC9D;QACD,CAAC,cAAc,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,wCAAwC,CAAC,CAAC;QACxE;YACE,mBAAmB;YACnB,GAAG,EAAE,CAAC,MAAM,CAAC,4CAA4C,CAAC;SAC3D;QACD,CAAC,kBAAkB,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,qCAAqC,CAAC,CAAC;KAC1E,CAAC;IACF,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACrC,IAAI,QAAQ,CAAC,IAAI,CAAC;YAAE,SAAS;QAC7B,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,MAAM,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC;YACxB,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;gBACrD,QAAQ,CAAC,IAAI,CAAC,GAAG;oBACf,IAAI,EAAE,GAAG,CAAC,IAAI;oBACd,GAAG,EAAE,GAAG,CAAC,GAAG;oBACZ,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrD,kEAAkE;oBAClE,gEAAgE;oBAChE,+DAA+D;oBAC/D,2DAA2D;oBAC3D,GAAG,mBAAmB,CAAC,GAAG,CAAC;iBAC5B,CAAC;YACJ,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,gDAAgD;QAClD,CAAC;IACH,CAAC;AACH,CAAC;AAED,oDAAoD;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * Auto-discover actions from a template's actions/ directory.\n *\n * Scans for .ts/.js files and builds an action registry suitable for\n * `createAgentChatPlugin({ actions })`.\n *\n * Supports two action conventions:\n *\n * 1. **Full interface** — exports `tool: ActionTool` and `run(args): Promise<string>`.\n * These are used directly.\n *\n * 2. **CLI-style** — exports only `default async function(args: string[])`.\n * These are wrapped: args are converted from `Record<string, string>` to\n * `[\"--key\", \"value\", ...]`, console output is captured, and a tool\n * definition is synthesized from the action name.\n *\n * 3. **defineAction** — exports `default` from `defineAction()`. Has `tool` and `run`.\n *\n * Usage in agent-chat plugins:\n * ```ts\n * import { autoDiscoverActions } from \"@agent-native/core/server\";\n *\n * export default createAgentChatPlugin({\n * actions: () => autoDiscoverActions(import.meta.url),\n * });\n * ```\n */\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport nodePath from \"node:path\";\nimport { captureCliOutput } from \"./cli-capture.js\";\n\n// Lazy fs — loaded via dynamic import() on first use.\n// Avoids require() which bundlers convert to createRequire() that crashes on CF Workers.\nlet _fs: typeof import(\"fs\") | undefined;\nasync function getFs(): Promise<typeof import(\"fs\")> {\n if (!_fs) {\n _fs = await import(\"node:fs\");\n }\n return _fs;\n}\nimport { fileURLToPath } from \"node:url\";\n\n/** Files to skip during auto-discovery (no extension). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\nfunction isRuntimeSourceFile(filename: string): boolean {\n if (!/\\.(ts|js)$/.test(filename)) return false;\n if (/\\.d\\.ts$/.test(filename)) return false;\n if (/\\.(test|spec)\\.(ts|js)$/.test(filename)) return false;\n return true;\n}\n\n/**\n * Global registry of actions contributed by published packages\n * (e.g. `@agent-native/dispatch`). Populated by `registerPackageActions()`\n * which the package calls from import side effects, then merged into\n * `autoDiscoverActions` after the template's local `actions/` directory.\n *\n * Ordering: template `actions/` files always win on name collision so\n * consumers can override a packaged action by dropping a same-named file\n * in their own `actions/` dir.\n */\nconst packageActionRegistry: Record<string, ActionEntry> = {};\n\n/**\n * Register a map of actions contributed by a published package.\n *\n * Called from a package's server entrypoint via import side effects:\n * ```ts\n * // packages/dispatch/src/server/index.ts\n * import { registerPackageActions } from \"@agent-native/core/server\";\n * import { actions } from \"../actions/index.js\";\n * registerPackageActions(actions);\n * ```\n *\n * Idempotent — re-registering the same name from the same import is a no-op\n * so HMR / repeated dynamic imports don't double-warn.\n */\nexport function registerPackageActions(\n actions: Record<string, ActionEntry>,\n): void {\n for (const [name, entry] of Object.entries(actions)) {\n if (packageActionRegistry[name]) continue;\n packageActionRegistry[name] = entry;\n }\n}\n\n/** Internal — used by `autoDiscoverActions`. Returns a shallow copy. */\nfunction getPackageActions(): Record<string, ActionEntry> {\n return { ...packageActionRegistry };\n}\n\n/**\n * Split a string into shell-like tokens, handling double and single quotes.\n * `--title \"My Page\" --content \"\"` → `[\"--title\", \"My Page\", \"--content\", \"\"]`\n */\nfunction splitShellArgs(input: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n let inDouble = false;\n let inSingle = false;\n let wasQuoted = false;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '\"' && !inSingle) {\n inDouble = !inDouble;\n wasQuoted = true;\n continue;\n }\n if (ch === \"'\" && !inDouble) {\n inSingle = !inSingle;\n wasQuoted = true;\n continue;\n }\n if ((ch === \" \" || ch === \"\\t\") && !inDouble && !inSingle) {\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n current = \"\";\n wasQuoted = false;\n continue;\n }\n current += ch;\n }\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n return tokens;\n}\n\n/**\n * Wrap a CLI-style action (that writes to console.log) as an ActionEntry\n * by capturing stdout/stderr and intercepting process.exit. Uses the\n * shared AsyncLocalStorage-backed capture so concurrent invocations do\n * not corrupt the global `console.log` / `process.stdout.write` /\n * `process.exit` pointers (see `cli-capture.ts`).\n */\nfunction wrapDefaultExport(\n name: string,\n defaultFn: (args: string[]) => Promise<void>,\n): ActionEntry {\n const tool: ActionTool = {\n description: `Run the \"${name}\" action. Pass arguments as key-value pairs.`,\n parameters: {\n type: \"object\",\n properties: {\n args: {\n type: \"string\",\n description:\n \"Space-separated CLI arguments (e.g. '--id abc --title Hello')\",\n },\n },\n },\n };\n\n return {\n tool,\n run: async (args: Record<string, string>): Promise<string> => {\n const cliArgs: string[] = [];\n // If only an \"args\" key was provided, split it into CLI tokens\n if (args.args && Object.keys(args).length === 1) {\n cliArgs.push(...splitShellArgs(args.args));\n } else {\n for (const [k, v] of Object.entries(args)) {\n cliArgs.push(`--${k}`, v);\n }\n }\n return captureCliOutput(() => defaultFn(cliArgs));\n },\n };\n}\n\nfunction preserveActionFlags(entry: Record<string, any>): Partial<ActionEntry> {\n const out: Partial<ActionEntry> = {};\n if (typeof entry.readOnly === \"boolean\") out.readOnly = entry.readOnly;\n if (typeof entry.parallelSafe === \"boolean\") {\n out.parallelSafe = entry.parallelSafe;\n }\n if (typeof entry.toolCallable === \"boolean\") {\n out.toolCallable = entry.toolCallable;\n }\n if (\n entry.publicAgent &&\n typeof entry.publicAgent === \"object\" &&\n !Array.isArray(entry.publicAgent)\n ) {\n out.publicAgent = entry.publicAgent;\n }\n if (typeof entry.link === \"function\") {\n out.link = entry.link;\n }\n if (\n entry.mcpApp &&\n typeof entry.mcpApp === \"object\" &&\n !Array.isArray(entry.mcpApp)\n ) {\n out.mcpApp = entry.mcpApp;\n }\n return out;\n}\n\n/**\n * Resolve the actions directory from the caller's context.\n *\n * @param from - Either an `import.meta.url` (file:// URL from a plugin file),\n * an absolute directory path, or \"auto\" to use `process.cwd() + \"/actions\"`.\n * When an import.meta.url is provided, the actions directory is resolved as\n * `../../actions/` relative to the caller (typically `server/plugins/agent-chat.ts`).\n * If the resolved directory doesn't exist, falls back to `../../scripts/` for\n * backwards compatibility, then to `process.cwd() + \"/actions\"`.\n */\nasync function resolveActionsDir(from: string): Promise<string> {\n const fs = await getFs();\n const exists = (p: string) => {\n try {\n return fs.existsSync(p);\n } catch {\n return false;\n }\n };\n // On edge runtimes (e.g. Cloudflare Workers), import.meta.url may be\n // undefined after bundling. Fall back to cwd-based discovery.\n if (!from) {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerPath = fileURLToPath(from);\n const callerDir = nodePath.dirname(callerPath);\n const actionsResolved = nodePath.resolve(callerDir, \"../../actions\");\n if (exists(actionsResolved)) return actionsResolved;\n const scriptsResolved = nodePath.resolve(callerDir, \"../../scripts\");\n if (exists(scriptsResolved)) return scriptsResolved;\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from === \"auto\") {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n return nodePath.resolve(from);\n}\n\n/**\n * Load actions from a single directory into the given registry. Shared by\n * both the template-actions discovery path and the workspace-core actions\n * layer. When `skipExisting` is true, an entry with the same name that's\n * already in the registry is left untouched (template-wins on collision).\n */\nasync function loadActionsIntoRegistry(\n actionsDir: string,\n registry: Record<string, ActionEntry>,\n skipExisting: boolean,\n): Promise<void> {\n let files: string[];\n try {\n const fs = await getFs();\n if (!fs.existsSync(actionsDir)) return;\n files = fs.readdirSync(actionsDir);\n } catch {\n return;\n }\n\n const actionFiles = files.filter((f) => {\n if (!isRuntimeSourceFile(f)) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n return true;\n });\n\n for (const file of actionFiles) {\n const name = file.replace(/\\.(ts|js)$/, \"\");\n if (skipExisting && registry[name]) continue;\n\n const filePath = nodePath.join(actionsDir, file);\n try {\n const mod = await import(/* @vite-ignore */ filePath);\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n } else if (\n mod.default &&\n typeof mod.default === \"object\" &&\n mod.default.tool &&\n typeof mod.default.run === \"function\"\n ) {\n registry[name] = {\n tool: mod.default.tool,\n run: mod.default.run,\n ...(mod.default.http !== undefined ? { http: mod.default.http } : {}),\n ...preserveActionFlags(mod.default),\n };\n } else if (typeof mod.default === \"function\") {\n registry[name] = wrapDefaultExport(name, mod.default);\n }\n } catch (err) {\n // CLI-style scripts (top-level execution) throw on import — expected,\n // they're available via `pnpm action <name>` / shell instead. But a\n // syntax error, bad import, or malformed defineAction in a real action\n // file lands here too and would silently vanish from the agent's tools.\n // Warn so a broken action file is diagnosable instead of mysteriously\n // missing.\n const msg =\n err instanceof Error ? (err.stack ?? err.message) : String(err);\n console.warn(\n `[action-discovery] Skipped \"${file}\" — failed to import. If this is an ` +\n `agent action (not a CLI script), it will be missing from the agent's tools:\\n${msg}`,\n );\n }\n }\n}\n\n/**\n * Normalize a pre-bundled static action registry (name → raw module) into\n * the `Record<string, ActionEntry>` shape the agent-chat plugin expects.\n *\n * Used by `autoDiscoverActions` when `.generated/actions-registry.ts` is\n * present so that Nitro-bundled serverless functions (Netlify, Vercel,\n * AWS-Lambda) can serve `/_agent-native/actions/*` routes without relying\n * on a filesystem scan that doesn't work in bundled output.\n */\nexport function loadActionsFromStaticRegistry(\n modules: Record<string, unknown>,\n): Record<string, ActionEntry> {\n const registry: Record<string, ActionEntry> = {};\n for (const [name, raw] of Object.entries(modules)) {\n const mod = raw as Record<string, any> | null | undefined;\n if (!mod) continue;\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n continue;\n }\n\n const def = mod.default;\n if (\n def &&\n typeof def === \"object\" &&\n def.tool &&\n typeof def.run === \"function\"\n ) {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...preserveActionFlags(def),\n };\n continue;\n }\n\n if (typeof def === \"function\") {\n registry[name] = wrapDefaultExport(name, def);\n }\n }\n return registry;\n}\n\n/**\n * Auto-discover actions from a directory.\n *\n * Merges in any actions from the enterprise workspace core (if present in\n * the ancestor chain). Template actions take precedence over workspace-core\n * actions on name collision, so an app can override an enterprise-wide\n * action by dropping a same-named file under its own `actions/`.\n *\n * Note: this helper uses a filesystem scan, which works in dev and in\n * non-bundled Node deployments. In bundled serverless functions (Nitro's\n * netlify / vercel / aws-lambda presets) the `actions/` directory is not\n * on disk at runtime; templates should pass the static registry generated\n * by the Vite plugin to `createAgentChatPlugin({ actions })` instead, so\n * the bundler sees static imports and pulls every action into the bundle.\n *\n * @param from - The caller's `import.meta.url` or an absolute path to the\n * actions directory.\n * @returns A record mapping action names to ActionEntry objects, suitable for\n * passing to `createAgentChatPlugin({ actions })`.\n */\nexport async function autoDiscoverActions(\n from: string,\n): Promise<Record<string, ActionEntry>> {\n const actionsDir = await resolveActionsDir(from);\n const registry: Record<string, ActionEntry> = {};\n\n // 1. Template actions first — these are the authoritative layer for the\n // current app and must override any workspace-core entry with the same\n // name.\n try {\n await loadActionsIntoRegistry(actionsDir, registry, false);\n } catch (err: any) {\n console.warn(\n `[autoDiscoverActions] Could not read actions directory: ${actionsDir} — ${err?.message}`,\n );\n }\n\n // 1b. Fallback: if filesystem discovery found no template actions (common\n // in bundled serverless environments like Netlify/Vercel where the\n // actions/ directory doesn't exist on disk), try importing the\n // generated static registry at .generated/actions-registry.\n //\n // This prevents the silent-empty-tools footgun where the agent has no\n // template actions and falls back to generic tools like web-request.\n // Prefer `loadActionsFromStaticRegistry` over `autoDiscoverActions` for\n // production reliability — this fallback is a safety net, not the\n // primary path.\n if (Object.keys(registry).length === 0 && from) {\n try {\n let registryPath: string;\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerDir = nodePath.dirname(fileURLToPath(from));\n registryPath = nodePath.resolve(\n callerDir,\n \"../../.generated/actions-registry.js\",\n );\n } else {\n registryPath = nodePath.resolve(\n from,\n \"../.generated/actions-registry.js\",\n );\n }\n const mod = await import(/* @vite-ignore */ registryPath);\n const staticEntries = loadActionsFromStaticRegistry(mod.default || mod);\n Object.assign(registry, staticEntries);\n if (Object.keys(staticEntries).length > 0) {\n console.log(\n `[autoDiscoverActions] Filesystem scan found 0 actions — loaded ${Object.keys(staticEntries).length} from .generated/actions-registry.ts instead. ` +\n `Consider switching to loadActionsFromStaticRegistry(actionsRegistry) for production reliability.`,\n );\n }\n } catch {\n // No generated registry available — registry stays empty.\n }\n }\n\n // If still empty after all fallbacks, warn loudly.\n if (Object.keys(registry).length === 0) {\n console.warn(\n `[autoDiscoverActions] WARNING: No template actions found! ` +\n `The agent will have no template-specific tools. ` +\n `If in production, switch from autoDiscoverActions to loadActionsFromStaticRegistry. ` +\n `See: https://docs.agent-native.com/actions#static-registry`,\n );\n }\n\n // 1c. Package-registered actions — contributed by published packages\n // (e.g. @agent-native/dispatch) via `registerPackageActions()` from\n // import side effects. Merged with skip-existing so the template's\n // own actions/ files always win on name collision.\n for (const [name, entry] of Object.entries(getPackageActions())) {\n if (registry[name]) continue;\n registry[name] = entry;\n }\n\n // 2. Workspace-core actions — merged in with skipExisting so they can't\n // overwrite template entries.\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(process.cwd());\n if (ws && ws.actionsDir) {\n await loadActionsIntoRegistry(ws.actionsDir, registry, true);\n }\n } catch {\n // workspace-core discovery unavailable (e.g. edge runtime) — skip.\n }\n\n // 3. Framework-level sharing + file-upload actions — always available to any\n // template. Merged with skipExisting so templates can override by\n // providing a same-named file.\n try {\n await mergeCoreSharingActions(registry);\n } catch {\n // Ignore — templates without sharing still work.\n }\n\n return registry;\n}\n\nexport async function mergeCoreSharingActions(\n registry: Record<string, ActionEntry>,\n): Promise<void> {\n const entries: Array<[string, () => Promise<any>]> = [\n [\"share-resource\", () => import(\"../sharing/actions/share-resource.js\")],\n [\n \"unshare-resource\",\n () => import(\"../sharing/actions/unshare-resource.js\"),\n ],\n [\n \"list-resource-shares\",\n () => import(\"../sharing/actions/list-resource-shares.js\"),\n ],\n [\n \"set-resource-visibility\",\n () => import(\"../sharing/actions/set-resource-visibility.js\"),\n ],\n [\"upload-image\", () => import(\"../file-upload/actions/upload-image.js\")],\n [\n \"change-appearance\",\n () => import(\"../appearance/actions/change-appearance.js\"),\n ],\n [\"toggle-demo-mode\", () => import(\"../demo/actions/toggle-demo-mode.js\")],\n ];\n for (const [name, loader] of entries) {\n if (registry[name]) continue;\n try {\n const mod = await loader();\n const def = mod.default;\n if (def && def.tool && typeof def.run === \"function\") {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n // Carry security-relevant flags (toolCallable, publicAgent, link,\n // mcpApp) plus readOnly/parallelSafe. Without this, the sharing\n // actions' `toolCallable: false` (audit-H5) is dropped and the\n // tools-iframe bridge 403 in action-routes.ts never fires.\n ...preserveActionFlags(def),\n };\n }\n } catch {\n // Skip any sharing action that fails to import.\n }\n }\n}\n\n/** @deprecated Use `autoDiscoverActions` instead */\nexport const autoDiscoverScripts = autoDiscoverActions;\n"]}
1
+ {"version":3,"file":"action-discovery.js","sourceRoot":"","sources":["../../src/server/action-discovery.ts"],"names":[],"mappings":"AA6BA,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD,sDAAsD;AACtD,yFAAyF;AACzF,IAAI,GAAoC,CAAC;AACzC,KAAK,UAAU,KAAK;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,GAAG,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AACD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CA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MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACrC,IAAI,QAAQ,CAAC,IAAI,CAAC;YAAE,SAAS;QAC7B,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,MAAM,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC;YACxB,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;gBACrD,QAAQ,CAAC,IAAI,CAAC,GAAG;oBACf,IAAI,EAAE,GAAG,CAAC,IAAI;oBACd,GAAG,EAAE,GAAG,CAAC,GAAG;oBACZ,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrD,kEAAkE;oBAClE,gEAAgE;oBAChE,+DAA+D;oBAC/D,2DAA2D;oBAC3D,GAAG,mBAAmB,CAAC,GAAG,CAAC;iBAC5B,CAAC;YACJ,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,gDAAgD;QAClD,CAAC;IACH,CAAC;AACH,CAAC;AAED,oDAAoD;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * Auto-discover actions from a template's actions/ directory.\n *\n * Scans for .ts/.js files and builds an action registry suitable for\n * `createAgentChatPlugin({ actions })`.\n *\n * Supports two action conventions:\n *\n * 1. **Full interface** — exports `tool: ActionTool` and `run(args): Promise<string>`.\n * These are used directly.\n *\n * 2. **CLI-style** — exports only `default async function(args: string[])`.\n * These are wrapped: args are converted from `Record<string, string>` to\n * `[\"--key\", \"value\", ...]`, console output is captured, and a tool\n * definition is synthesized from the action name.\n *\n * 3. **defineAction** — exports `default` from `defineAction()`. Has `tool` and `run`.\n *\n * Usage in agent-chat plugins:\n * ```ts\n * import { autoDiscoverActions } from \"@agent-native/core/server\";\n *\n * export default createAgentChatPlugin({\n * actions: () => autoDiscoverActions(import.meta.url),\n * });\n * ```\n */\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport nodePath from \"node:path\";\nimport { captureCliOutput } from \"./cli-capture.js\";\n\n// Lazy fs — loaded via dynamic import() on first use.\n// Avoids require() which bundlers convert to createRequire() that crashes on CF Workers.\nlet _fs: typeof import(\"fs\") | undefined;\nasync function getFs(): Promise<typeof import(\"fs\")> {\n if (!_fs) {\n _fs = await import(\"node:fs\");\n }\n return _fs;\n}\nimport { fileURLToPath } from \"node:url\";\n\n/** Files to skip during auto-discovery (no extension). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\nfunction isRuntimeSourceFile(filename: string): boolean {\n if (!/\\.(ts|js)$/.test(filename)) return false;\n if (/\\.d\\.ts$/.test(filename)) return false;\n if (/\\.(test|spec)\\.(ts|js)$/.test(filename)) return false;\n return true;\n}\n\n/**\n * Global registry of actions contributed by published packages\n * (e.g. `@agent-native/dispatch`). Populated by `registerPackageActions()`\n * which the package calls from import side effects, then merged into\n * `autoDiscoverActions` after the template's local `actions/` directory.\n *\n * Ordering: template `actions/` files always win on name collision so\n * consumers can override a packaged action by dropping a same-named file\n * in their own `actions/` dir.\n */\nconst packageActionRegistry: Record<string, ActionEntry> = {};\n\n/**\n * Register a map of actions contributed by a published package.\n *\n * Called from a package's server entrypoint via import side effects:\n * ```ts\n * // packages/dispatch/src/server/index.ts\n * import { registerPackageActions } from \"@agent-native/core/server\";\n * import { actions } from \"../actions/index.js\";\n * registerPackageActions(actions);\n * ```\n *\n * Idempotent — re-registering the same name from the same import is a no-op\n * so HMR / repeated dynamic imports don't double-warn.\n */\nexport function registerPackageActions(\n actions: Record<string, ActionEntry>,\n): void {\n for (const [name, entry] of Object.entries(actions)) {\n if (packageActionRegistry[name]) continue;\n packageActionRegistry[name] = entry;\n }\n}\n\n/** Internal — used by `autoDiscoverActions`. Returns a shallow copy. */\nfunction getPackageActions(): Record<string, ActionEntry> {\n return { ...packageActionRegistry };\n}\n\n/**\n * Split a string into shell-like tokens, handling double and single quotes.\n * `--title \"My Page\" --content \"\"` → `[\"--title\", \"My Page\", \"--content\", \"\"]`\n */\nfunction splitShellArgs(input: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n let inDouble = false;\n let inSingle = false;\n let wasQuoted = false;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '\"' && !inSingle) {\n inDouble = !inDouble;\n wasQuoted = true;\n continue;\n }\n if (ch === \"'\" && !inDouble) {\n inSingle = !inSingle;\n wasQuoted = true;\n continue;\n }\n if ((ch === \" \" || ch === \"\\t\") && !inDouble && !inSingle) {\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n current = \"\";\n wasQuoted = false;\n continue;\n }\n current += ch;\n }\n if (current.length > 0 || wasQuoted) {\n tokens.push(current);\n }\n return tokens;\n}\n\n/**\n * Wrap a CLI-style action (that writes to console.log) as an ActionEntry\n * by capturing stdout/stderr and intercepting process.exit. Uses the\n * shared AsyncLocalStorage-backed capture so concurrent invocations do\n * not corrupt the global `console.log` / `process.stdout.write` /\n * `process.exit` pointers (see `cli-capture.ts`).\n */\nfunction wrapDefaultExport(\n name: string,\n defaultFn: (args: string[]) => Promise<void>,\n): ActionEntry {\n const tool: ActionTool = {\n description: `Run the \"${name}\" action. Pass arguments as key-value pairs.`,\n parameters: {\n type: \"object\",\n properties: {\n args: {\n type: \"string\",\n description:\n \"Space-separated CLI arguments (e.g. '--id abc --title Hello')\",\n },\n },\n },\n };\n\n return {\n tool,\n run: async (args: Record<string, string>): Promise<string> => {\n const cliArgs: string[] = [];\n // If only an \"args\" key was provided, split it into CLI tokens\n if (args.args && Object.keys(args).length === 1) {\n cliArgs.push(...splitShellArgs(args.args));\n } else {\n for (const [k, v] of Object.entries(args)) {\n cliArgs.push(`--${k}`, v);\n }\n }\n return captureCliOutput(() => defaultFn(cliArgs));\n },\n };\n}\n\nfunction preserveActionFlags(entry: Record<string, any>): Partial<ActionEntry> {\n const out: Partial<ActionEntry> = {};\n if (typeof entry.readOnly === \"boolean\") out.readOnly = entry.readOnly;\n if (typeof entry.parallelSafe === \"boolean\") {\n out.parallelSafe = entry.parallelSafe;\n }\n if (typeof entry.toolCallable === \"boolean\") {\n out.toolCallable = entry.toolCallable;\n }\n if (\n entry.publicAgent &&\n typeof entry.publicAgent === \"object\" &&\n !Array.isArray(entry.publicAgent)\n ) {\n out.publicAgent = entry.publicAgent;\n }\n if (typeof entry.link === \"function\") {\n out.link = entry.link;\n }\n if (\n entry.mcpApp &&\n typeof entry.mcpApp === \"object\" &&\n !Array.isArray(entry.mcpApp)\n ) {\n out.mcpApp = entry.mcpApp;\n }\n return out;\n}\n\n/**\n * Resolve the actions directory from the caller's context.\n *\n * @param from - Either an `import.meta.url` (file:// URL from a plugin file),\n * an absolute directory path, or \"auto\" to use `process.cwd() + \"/actions\"`.\n * When an import.meta.url is provided, the actions directory is resolved as\n * `../../actions/` relative to the caller (typically `server/plugins/agent-chat.ts`).\n * If the resolved directory doesn't exist, falls back to `../../scripts/` for\n * backwards compatibility, then to `process.cwd() + \"/actions\"`.\n */\nasync function resolveActionsDir(from: string): Promise<string> {\n const fs = await getFs();\n const exists = (p: string) => {\n try {\n return fs.existsSync(p);\n } catch {\n return false;\n }\n };\n // On edge runtimes (e.g. Cloudflare Workers), import.meta.url may be\n // undefined after bundling. Fall back to cwd-based discovery.\n if (!from) {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerPath = fileURLToPath(from);\n const callerDir = nodePath.dirname(callerPath);\n const actionsResolved = nodePath.resolve(callerDir, \"../../actions\");\n if (exists(actionsResolved)) return actionsResolved;\n const scriptsResolved = nodePath.resolve(callerDir, \"../../scripts\");\n if (exists(scriptsResolved)) return scriptsResolved;\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n if (from === \"auto\") {\n const cwdActions = nodePath.join(process.cwd(), \"actions\");\n if (exists(cwdActions)) return cwdActions;\n return nodePath.join(process.cwd(), \"scripts\");\n }\n return nodePath.resolve(from);\n}\n\n/**\n * Load actions from a single directory into the given registry. Shared by\n * both the template-actions discovery path and the workspace-core actions\n * layer. When `skipExisting` is true, an entry with the same name that's\n * already in the registry is left untouched (template-wins on collision).\n */\nasync function loadActionsIntoRegistry(\n actionsDir: string,\n registry: Record<string, ActionEntry>,\n skipExisting: boolean,\n): Promise<void> {\n let files: string[];\n try {\n const fs = await getFs();\n if (!fs.existsSync(actionsDir)) return;\n files = fs.readdirSync(actionsDir);\n } catch {\n return;\n }\n\n const actionFiles = files.filter((f) => {\n if (!isRuntimeSourceFile(f)) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n return true;\n });\n\n for (const file of actionFiles) {\n const name = file.replace(/\\.(ts|js)$/, \"\");\n if (skipExisting && registry[name]) continue;\n\n const filePath = nodePath.join(actionsDir, file);\n try {\n const mod = await import(/* @vite-ignore */ filePath);\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n } else if (\n mod.default &&\n typeof mod.default === \"object\" &&\n mod.default.tool &&\n typeof mod.default.run === \"function\"\n ) {\n registry[name] = {\n tool: mod.default.tool,\n run: mod.default.run,\n ...(mod.default.http !== undefined ? { http: mod.default.http } : {}),\n ...preserveActionFlags(mod.default),\n };\n } else if (typeof mod.default === \"function\") {\n registry[name] = wrapDefaultExport(name, mod.default);\n }\n } catch (err) {\n // CLI-style scripts (top-level execution) throw on import — expected,\n // they're available via `pnpm action <name>` / shell instead. But a\n // syntax error, bad import, or malformed defineAction in a real action\n // file lands here too and would silently vanish from the agent's tools.\n // Warn so a broken action file is diagnosable instead of mysteriously\n // missing.\n const msg =\n err instanceof Error ? (err.stack ?? err.message) : String(err);\n console.warn(\n `[action-discovery] Skipped \"${file}\" — failed to import. If this is an ` +\n `agent action (not a CLI script), it will be missing from the agent's tools:\\n${msg}`,\n );\n }\n }\n}\n\n/**\n * Normalize a pre-bundled static action registry (name → raw module) into\n * the `Record<string, ActionEntry>` shape the agent-chat plugin expects.\n *\n * Used by `autoDiscoverActions` when `.generated/actions-registry.ts` is\n * present so that Nitro-bundled serverless functions (Netlify, Vercel,\n * AWS-Lambda) can serve `/_agent-native/actions/*` routes without relying\n * on a filesystem scan that doesn't work in bundled output.\n */\nexport function loadActionsFromStaticRegistry(\n modules: Record<string, unknown>,\n): Record<string, ActionEntry> {\n const registry: Record<string, ActionEntry> = {};\n for (const [name, raw] of Object.entries(modules)) {\n const mod = raw as Record<string, any> | null | undefined;\n if (!mod) continue;\n\n if (mod.tool && typeof mod.run === \"function\") {\n registry[name] = {\n tool: mod.tool,\n run: mod.run,\n ...(mod.http !== undefined ? { http: mod.http } : {}),\n ...preserveActionFlags(mod),\n };\n continue;\n }\n\n const def = mod.default;\n if (\n def &&\n typeof def === \"object\" &&\n def.tool &&\n typeof def.run === \"function\"\n ) {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...preserveActionFlags(def),\n };\n continue;\n }\n\n if (typeof def === \"function\") {\n registry[name] = wrapDefaultExport(name, def);\n }\n }\n return registry;\n}\n\n/**\n * Auto-discover actions from a directory.\n *\n * Merges in any actions from the enterprise workspace core (if present in\n * the ancestor chain). Template actions take precedence over workspace-core\n * actions on name collision, so an app can override an enterprise-wide\n * action by dropping a same-named file under its own `actions/`.\n *\n * Note: this helper uses a filesystem scan, which works in dev and in\n * non-bundled Node deployments. In bundled serverless functions (Nitro's\n * netlify / vercel / aws-lambda presets) the `actions/` directory is not\n * on disk at runtime; templates should pass the static registry generated\n * by the Vite plugin to `createAgentChatPlugin({ actions })` instead, so\n * the bundler sees static imports and pulls every action into the bundle.\n *\n * @param from - The caller's `import.meta.url` or an absolute path to the\n * actions directory.\n * @returns A record mapping action names to ActionEntry objects, suitable for\n * passing to `createAgentChatPlugin({ actions })`.\n */\nexport async function autoDiscoverActions(\n from: string,\n): Promise<Record<string, ActionEntry>> {\n const actionsDir = await resolveActionsDir(from);\n const registry: Record<string, ActionEntry> = {};\n\n // 1. Template actions first — these are the authoritative layer for the\n // current app and must override any workspace-core entry with the same\n // name.\n try {\n await loadActionsIntoRegistry(actionsDir, registry, false);\n } catch (err: any) {\n console.warn(\n `[autoDiscoverActions] Could not read actions directory: ${actionsDir} — ${err?.message}`,\n );\n }\n\n // 1b. Fallback: if filesystem discovery found no template actions (common\n // in bundled serverless environments like Netlify/Vercel where the\n // actions/ directory doesn't exist on disk), try importing the\n // generated static registry at .generated/actions-registry.\n //\n // This prevents the silent-empty-tools footgun where the agent has no\n // template actions and falls back to generic tools like web-request.\n // Prefer `loadActionsFromStaticRegistry` over `autoDiscoverActions` for\n // production reliability — this fallback is a safety net, not the\n // primary path.\n if (Object.keys(registry).length === 0 && from) {\n try {\n let registryPath: string;\n if (from.startsWith(\"file://\") || from.startsWith(\"file:///\")) {\n const callerDir = nodePath.dirname(fileURLToPath(from));\n registryPath = nodePath.resolve(\n callerDir,\n \"../../.generated/actions-registry.js\",\n );\n } else {\n registryPath = nodePath.resolve(\n from,\n \"../.generated/actions-registry.js\",\n );\n }\n const mod = await import(/* @vite-ignore */ registryPath);\n const staticEntries = loadActionsFromStaticRegistry(mod.default || mod);\n Object.assign(registry, staticEntries);\n if (Object.keys(staticEntries).length > 0) {\n console.log(\n `[autoDiscoverActions] Filesystem scan found 0 actions — loaded ${Object.keys(staticEntries).length} from .generated/actions-registry.ts instead. ` +\n `Consider switching to loadActionsFromStaticRegistry(actionsRegistry) for production reliability.`,\n );\n }\n } catch {\n // No generated registry available — registry stays empty.\n }\n }\n\n // If still empty after all fallbacks, warn loudly.\n if (Object.keys(registry).length === 0) {\n console.warn(\n `[autoDiscoverActions] WARNING: No template actions found! ` +\n `The agent will have no template-specific tools. ` +\n `If in production, switch from autoDiscoverActions to loadActionsFromStaticRegistry. ` +\n `See: https://docs.agent-native.com/actions#static-registry`,\n );\n }\n\n // 1c. Package-registered actions — contributed by published packages\n // (e.g. @agent-native/dispatch) via `registerPackageActions()` from\n // import side effects. Merged with skip-existing so the template's\n // own actions/ files always win on name collision.\n for (const [name, entry] of Object.entries(getPackageActions())) {\n if (registry[name]) continue;\n registry[name] = entry;\n }\n\n // 2. Workspace-core actions — merged in with skipExisting so they can't\n // overwrite template entries.\n try {\n const { getWorkspaceCoreExports } =\n await import(\"../deploy/workspace-core.js\");\n const ws = await getWorkspaceCoreExports(process.cwd());\n if (ws && ws.actionsDir) {\n await loadActionsIntoRegistry(ws.actionsDir, registry, true);\n }\n } catch {\n // workspace-core discovery unavailable (e.g. edge runtime) — skip.\n }\n\n // 3. Framework-level sharing + file-upload actions — always available to any\n // template. Merged with skipExisting so templates can override by\n // providing a same-named file.\n try {\n await mergeCoreSharingActions(registry);\n } catch {\n // Ignore — templates without sharing still work.\n }\n\n return registry;\n}\n\nexport async function mergeCoreSharingActions(\n registry: Record<string, ActionEntry>,\n): Promise<void> {\n const entries: Array<[string, () => Promise<any>]> = [\n [\"share-resource\", () => import(\"../sharing/actions/share-resource.js\")],\n [\n \"unshare-resource\",\n () => import(\"../sharing/actions/unshare-resource.js\"),\n ],\n [\n \"list-resource-shares\",\n () => import(\"../sharing/actions/list-resource-shares.js\"),\n ],\n [\n \"set-resource-visibility\",\n () => import(\"../sharing/actions/set-resource-visibility.js\"),\n ],\n [\"upload-image\", () => import(\"../file-upload/actions/upload-image.js\")],\n [\n \"context-manifest-get\",\n () => import(\"../agent/context-xray/actions/context-manifest-get.js\"),\n ],\n [\n \"context-pin\",\n () => import(\"../agent/context-xray/actions/context-pin.js\"),\n ],\n [\n \"context-evict\",\n () => import(\"../agent/context-xray/actions/context-evict.js\"),\n ],\n [\n \"context-restore\",\n () => import(\"../agent/context-xray/actions/context-restore.js\"),\n ],\n [\n \"context-report\",\n () => import(\"../agent/context-xray/actions/context-report.js\"),\n ],\n [\n \"change-appearance\",\n () => import(\"../appearance/actions/change-appearance.js\"),\n ],\n [\"toggle-demo-mode\", () => import(\"../demo/actions/toggle-demo-mode.js\")],\n ];\n for (const [name, loader] of entries) {\n if (registry[name]) continue;\n try {\n const mod = await loader();\n const def = mod.default;\n if (def && def.tool && typeof def.run === \"function\") {\n registry[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n // Carry security-relevant flags (toolCallable, publicAgent, link,\n // mcpApp) plus readOnly/parallelSafe. Without this, the sharing\n // actions' `toolCallable: false` (audit-H5) is dropped and the\n // tools-iframe bridge 403 in action-routes.ts never fires.\n ...preserveActionFlags(def),\n };\n }\n } catch {\n // Skip any sharing action that fails to import.\n }\n }\n}\n\n/** @deprecated Use `autoDiscoverActions` instead */\nexport const autoDiscoverScripts = autoDiscoverActions;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"framework-request-handler.d.ts","sourceRoot":"","sources":["../../src/server/framework-request-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,IAAI,CAAC;AAOhD,QAAA,MAAM,gBAAgB,mBAAmB,CAAC;AA0D1C;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IAC/C,GAAG,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CAClC;AAED;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,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MAAM,GAAG,IAAI,CAQ3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,GAAG,GAAG,SAAS,CA0DjD;AA0CD;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjE;AAmBD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,GAAG,EACb,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,EACtB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,GACjC,IAAI,CA0BN;AAmCD;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,GAAG,EACb,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,IAAI,CAAC,CAqBf;AA8SD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,GAAG,CAAC,CAyBd;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -459,11 +459,13 @@ async function bootstrapDefaultPlugins(nitroApp) {
459
459
  const serverModule = await import("./index.js");
460
460
  const terminalModule = await import("../terminal/terminal-plugin.js");
461
461
  const integrationsModule = await import("../integrations/plugin.js");
462
+ const contextXrayModule = await import("../agent/context-xray/plugin.js");
462
463
  const orgModule = await import("../org/plugin.js");
463
464
  const onboardingModule = await import("../onboarding/plugin.js");
464
465
  const frameworkImpls = {
465
466
  "agent-chat": serverModule.defaultAgentChatPlugin,
466
467
  auth: serverModule.defaultAuthPlugin,
468
+ "context-xray": contextXrayModule.defaultContextXrayPlugin,
467
469
  "core-routes": serverModule.defaultCoreRoutesPlugin,
468
470
  integrations: integrationsModule.defaultIntegrationsPlugin,
469
471
  onboarding: onboardingModule.defaultOnboardingPlugin,