@botpress/adk 1.18.3 → 1.19.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-init/agent-project-generator.d.ts +10 -7
- package/dist/agent-init/agent-project-generator.d.ts.map +1 -1
- package/dist/agent-project/agent-project.d.ts +1 -1
- package/dist/agent-project/agent-project.d.ts.map +1 -1
- package/dist/agent-project/component-files.d.ts +10 -0
- package/dist/agent-project/component-files.d.ts.map +1 -0
- package/dist/agent-project/component-index-writer.d.ts +22 -0
- package/dist/agent-project/component-index-writer.d.ts.map +1 -0
- package/dist/agent-project/config-writer.d.ts +5 -0
- package/dist/agent-project/config-writer.d.ts.map +1 -1
- package/dist/agent-project/index.d.ts +3 -0
- package/dist/agent-project/index.d.ts.map +1 -1
- package/dist/agent-project/lock-to-dependencies.d.ts +11 -0
- package/dist/agent-project/lock-to-dependencies.d.ts.map +1 -0
- package/dist/agent-project/types.d.ts +1 -0
- package/dist/agent-project/types.d.ts.map +1 -1
- package/dist/agent-project/validation-errors.d.ts +1 -0
- package/dist/agent-project/validation-errors.d.ts.map +1 -1
- package/dist/assets/manager.d.ts +0 -2
- package/dist/assets/manager.d.ts.map +1 -1
- package/dist/assets/types.d.ts +3 -1
- package/dist/assets/types.d.ts.map +1 -1
- package/dist/auth/credentials.d.ts.map +1 -1
- package/dist/auth/index.d.ts +29 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/bot-generator/dev-id-manager.d.ts.map +1 -1
- package/dist/bot-generator/generator.d.ts +5 -1
- package/dist/bot-generator/generator.d.ts.map +1 -1
- package/dist/bot-generator/integration-sync.d.ts.map +1 -1
- package/dist/bot-generator/interface-sync.d.ts.map +1 -1
- package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
- package/dist/bot-generator/table-validation.d.ts +17 -0
- package/dist/bot-generator/table-validation.d.ts.map +1 -0
- package/dist/chat-bundle.cjs +31 -0
- package/dist/commands/base-command.d.ts.map +1 -1
- package/dist/commands/bp-add-command.d.ts.map +1 -1
- package/dist/commands/bp-build-command.d.ts.map +1 -1
- package/dist/commands/bp-chat-command.d.ts.map +1 -1
- package/dist/commands/bp-cli.d.ts +1 -0
- package/dist/commands/bp-cli.d.ts.map +1 -1
- package/dist/commands/bp-deploy-command.d.ts.map +1 -1
- package/dist/commands/bp-dev-command.d.ts +5 -0
- package/dist/commands/bp-dev-command.d.ts.map +1 -1
- package/dist/commands/copilot-config-reader.d.ts +2 -11
- package/dist/commands/copilot-config-reader.d.ts.map +1 -1
- package/dist/commands/copilot-config.d.ts +42 -0
- package/dist/commands/copilot-config.d.ts.map +1 -0
- package/dist/commands/copilot-server.d.ts +7 -4
- package/dist/commands/copilot-server.d.ts.map +1 -1
- package/dist/commands/index.d.ts +2 -2
- package/dist/commands/index.d.ts.map +1 -1
- package/dist/commands/opencode-config.d.ts +15 -14
- package/dist/commands/opencode-config.d.ts.map +1 -1
- package/dist/config/manager.d.ts +9 -1
- package/dist/config/manager.d.ts.map +1 -1
- package/dist/constants.d.ts +1 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/dependencies/alias-utils.d.ts +13 -0
- package/dist/dependencies/alias-utils.d.ts.map +1 -0
- package/dist/dependencies/dependency-manager.d.ts +90 -0
- package/dist/dependencies/dependency-manager.d.ts.map +1 -0
- package/dist/dependencies/env-substitution.d.ts +3 -0
- package/dist/dependencies/env-substitution.d.ts.map +1 -0
- package/dist/dependencies/errors.d.ts +16 -0
- package/dist/dependencies/errors.d.ts.map +1 -0
- package/dist/dependencies/index.d.ts +19 -0
- package/dist/dependencies/index.d.ts.map +1 -0
- package/dist/dependencies/index.js +6056 -0
- package/dist/dependencies/index.js.map +61 -0
- package/dist/dependencies/json-utils.d.ts +3 -0
- package/dist/dependencies/json-utils.d.ts.map +1 -0
- package/dist/dependencies/lock-file.d.ts +15 -0
- package/dist/dependencies/lock-file.d.ts.map +1 -0
- package/dist/dependencies/migration.d.ts +10 -0
- package/dist/dependencies/migration.d.ts.map +1 -0
- package/dist/dependencies/registry/integration-registry.d.ts +17 -0
- package/dist/dependencies/registry/integration-registry.d.ts.map +1 -0
- package/dist/dependencies/registry/interface-registry.d.ts +11 -0
- package/dist/dependencies/registry/interface-registry.d.ts.map +1 -0
- package/dist/dependencies/registry/plugin-registry.d.ts +16 -0
- package/dist/dependencies/registry/plugin-registry.d.ts.map +1 -0
- package/dist/dependencies/resolvers/integration-resolver.d.ts +31 -0
- package/dist/dependencies/resolvers/integration-resolver.d.ts.map +1 -0
- package/dist/dependencies/resolvers/plugin-resolver.d.ts +39 -0
- package/dist/dependencies/resolvers/plugin-resolver.d.ts.map +1 -0
- package/dist/dependencies/secrets-rewriter.d.ts +25 -0
- package/dist/dependencies/secrets-rewriter.d.ts.map +1 -0
- package/dist/dependencies/types.d.ts +254 -0
- package/dist/dependencies/types.d.ts.map +1 -0
- package/dist/deploy-manifest/index.d.ts +608 -0
- package/dist/deploy-manifest/index.d.ts.map +1 -0
- package/dist/generators/assets.d.ts +2 -2
- package/dist/generators/assets.d.ts.map +1 -1
- package/dist/generators/tests.d.ts +6 -6
- package/dist/generators/tests.d.ts.map +1 -1
- package/dist/generators/utils.d.ts.map +1 -1
- package/dist/index.d.ts +13 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16546 -4428
- package/dist/index.js.map +74 -56
- package/dist/integrations/config-utils.d.ts.map +1 -1
- package/dist/integrations/index.d.ts +0 -6
- package/dist/integrations/index.d.ts.map +1 -1
- package/dist/integrations/manager.d.ts +17 -1
- package/dist/integrations/manager.d.ts.map +1 -1
- package/dist/interfaces/index.d.ts +0 -2
- package/dist/interfaces/index.d.ts.map +1 -1
- package/dist/interfaces/manager.d.ts +3 -1
- package/dist/interfaces/manager.d.ts.map +1 -1
- package/dist/knowledge/manager.d.ts +3 -1
- package/dist/knowledge/manager.d.ts.map +1 -1
- package/dist/knowledge/types.d.ts +2 -2
- package/dist/knowledge/types.d.ts.map +1 -1
- package/dist/plugins/manager.d.ts +29 -1
- package/dist/plugins/manager.d.ts.map +1 -1
- package/dist/preflight/checker.d.ts +5 -6
- package/dist/preflight/checker.d.ts.map +1 -1
- package/dist/preflight/index.d.ts +2 -2
- package/dist/preflight/index.d.ts.map +1 -1
- package/dist/preflight/types.d.ts +30 -32
- package/dist/preflight/types.d.ts.map +1 -1
- package/dist/runner/script-runner.d.ts +2 -0
- package/dist/runner/script-runner.d.ts.map +1 -1
- package/dist/tables/table-manager.d.ts.map +1 -1
- package/dist/tables/types.d.ts +3 -2
- package/dist/tables/types.d.ts.map +1 -1
- package/dist/templates/README.md +13 -12
- package/dist/templates/blank/agent.config.ts +0 -3
- package/dist/templates/blank/dependencies.dev.lock.json +6 -0
- package/dist/templates/blank/evals/index.eval.ts +30 -0
- package/dist/templates/blank/package.json +1 -0
- package/dist/templates/blank/src/conversations/index.ts +16 -16
- package/dist/templates/botpress-desk/README.md +87 -0
- package/dist/templates/botpress-desk/agent.config.ts +19 -0
- package/dist/templates/botpress-desk/dependencies.dev.lock.json +6 -0
- package/dist/templates/botpress-desk/evals/index.eval.ts +30 -0
- package/dist/templates/botpress-desk/package.json +17 -0
- package/dist/templates/botpress-desk/src/actions/index.ts +19 -0
- package/dist/templates/botpress-desk/src/conversations/index.ts +16 -0
- package/dist/templates/botpress-desk/src/knowledge/index.ts +20 -0
- package/dist/templates/botpress-desk/src/tables/index.ts +16 -0
- package/dist/templates/botpress-desk/src/tools/handToSupport.ts +23 -0
- package/dist/templates/botpress-desk/src/triggers/index.ts +17 -0
- package/dist/templates/botpress-desk/src/workflows/index.ts +21 -0
- package/dist/templates/crm-enrichment/agent.config.ts +0 -3
- package/dist/templates/crm-enrichment/dependencies.dev.lock.json +6 -0
- package/dist/templates/crm-enrichment/evals/example.eval.ts +29 -0
- package/dist/templates/crm-enrichment/package.json +1 -0
- package/dist/templates/hello-world/agent.config.ts +0 -3
- package/dist/templates/hello-world/dependencies.dev.lock.json +6 -0
- package/dist/templates/hello-world/evals/context-retention.eval.ts +37 -0
- package/dist/templates/hello-world/evals/greeting.eval.ts +43 -0
- package/dist/templates/hello-world/package.json +1 -0
- package/dist/templates/knowledge-assistant/agent.config.ts +0 -3
- package/dist/templates/knowledge-assistant/dependencies.dev.lock.json +6 -0
- package/dist/templates/knowledge-assistant/evals/engineering-practices.eval.ts +45 -0
- package/dist/templates/knowledge-assistant/evals/out-of-scope.eval.ts +33 -0
- package/dist/templates/knowledge-assistant/evals/pto-policy.eval.ts +44 -0
- package/dist/templates/knowledge-assistant/package.json +1 -0
- package/dist/templates/slack-triage/agent.config.ts +0 -8
- package/dist/templates/slack-triage/dependencies.dev.lock.json +6 -0
- package/dist/templates/slack-triage/evals/triage-basic.eval.ts +9 -39
- package/dist/templates/slack-triage/package.json +1 -0
- package/dist/templates/slack-triage/src/conversations/slack-dm.ts +4 -1
- package/dist/templates/template.config.json +14 -15
- package/dist/utils/require-chat.d.ts +3 -24
- package/dist/utils/require-chat.d.ts.map +1 -1
- package/dist/utils/search-ranking.d.ts +15 -0
- package/dist/utils/search-ranking.d.ts.map +1 -0
- package/dist/workspace/workspace-cache.d.ts.map +1 -1
- package/package.json +12 -8
- package/dist/integrations/checker.d.ts +0 -41
- package/dist/integrations/checker.d.ts.map +0 -1
- package/dist/integrations/operations.d.ts +0 -140
- package/dist/integrations/operations.d.ts.map +0 -1
- package/dist/integrations/sync-manager.d.ts +0 -19
- package/dist/integrations/sync-manager.d.ts.map +0 -1
- package/dist/interfaces/operations.d.ts +0 -48
- package/dist/interfaces/operations.d.ts.map +0 -1
- package/dist/preflight/formatter.d.ts +0 -12
- package/dist/preflight/formatter.d.ts.map +0 -1
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dependencies/types.ts", "../src/dependencies/errors.ts", "../src/dependencies/json-utils.ts", "../src/dependencies/lock-file.ts", "../src/agent-project/types.ts", "../src/agent-project/validation-errors.ts", "../src/constants.ts", "../src/agent-project/agent-resolver.ts", "../src/auth/credentials.ts", "../src/auth/service.ts", "../src/auth/bp-cli-import.ts", "../src/auth/index.ts", "../src/integrations/enhanced-cache.ts", "../src/agent-project/dependencies-parser.ts", "../src/utils/search-ranking.ts", "../src/integrations/manager.ts", "../src/const.ts", "../src/assets/cache.ts", "../src/assets/manager.ts", "../src/utils/fs.ts", "../src/assets/updater.ts", "../src/assets/index.ts", "../src/integrations/cache.ts", "../src/integrations/hub-cache.ts", "../src/integrations/config-utils.ts", "../src/integrations/index.ts", "../src/interfaces/enhanced-cache.ts", "../src/interfaces/parser.ts", "../src/interfaces/manager.ts", "../src/interfaces/index.ts", "../src/utils/json-ordering.ts", "../src/agent-project/expand-exports.ts", "../src/agent-project/component-files.ts", "../src/agent-project/component-source-resolver.ts", "../src/bot-generator/table-validation.ts", "../src/agent-project/lock-to-dependencies.ts", "../src/agent-project/agent-project.ts", "../src/generators/utils.ts", "../src/dependencies/dependency-manager.ts", "../src/dependencies/alias-utils.ts", "../src/dependencies/resolvers/integration-resolver.ts", "../src/dependencies/env-substitution.ts", "../src/dependencies/resolvers/plugin-resolver.ts", "../src/dependencies/registry/integration-registry.ts", "../src/plugins/manager.ts", "../src/plugins/enhanced-cache.ts", "../src/dependencies/registry/plugin-registry.ts", "../src/dependencies/index.ts", "../src/dependencies/secrets-rewriter.ts", "../src/dependencies/registry/interface-registry.ts", "../src/dependencies/migration.ts", "../src/agent-project/config-writer.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { z } from '@botpress/sdk'\n\nexport type Environment = 'dev' | 'prod'\nexport type ResourceType = 'integration' | 'plugin' | 'interface'\n\nexport const integrationLockEntrySchema = z.object({\n name: z.string(),\n version: z.string(),\n enabled: z.boolean(),\n config: z.record(z.any()).default({}),\n})\nexport type IntegrationLockEntry = z.infer<typeof integrationLockEntrySchema>\n\nexport const pluginDependencyMappingSchema = z.object({\n integrationAlias: z.string(),\n})\nexport type PluginDependencyMapping = z.infer<typeof pluginDependencyMappingSchema>\n\nexport const pluginLockEntrySchema = z.object({\n name: z.string(),\n version: z.string(),\n enabled: z.boolean().default(true),\n config: z.record(z.any()).default({}),\n dependencies: z.record(pluginDependencyMappingSchema).default({}),\n})\nexport type PluginLockEntry = z.infer<typeof pluginLockEntrySchema>\n\nexport const lockFileSchema = z.object({\n $schema: z.string().optional(),\n version: z.literal(1),\n env: z.enum(['dev', 'prod']),\n integrations: z.record(integrationLockEntrySchema).default({}),\n plugins: z.record(pluginLockEntrySchema).default({}),\n})\nexport type LockFileData = z.infer<typeof lockFileSchema>\n\nexport interface AddSpec {\n name: string\n version?: string\n alias?: string\n config?: Record<string, unknown>\n dependencies?: Record<string, PluginDependencyMapping>\n}\n\nexport interface ConfigPatch {\n set?: Record<string, unknown>\n unset?: string[]\n map?: Record<string, PluginDependencyMapping>\n}\n\nexport interface MutationResult {\n ok: boolean\n noop?: boolean\n resource?: { type: ResourceType; alias: string; name: string; version: string }\n lockChange?: { before: unknown; after: unknown }\n /** Populated when installing a plugin with auto-resolved interface dependencies. */\n autoResolved?: Array<{ pluginInterfaceAlias: string; integrationAlias: string }>\n /**\n * Set when an integration was installed but left disabled because Cloud rejected\n * the enable due to missing required configuration. Mirrors the Integration Hub UI behavior.\n */\n installedDisabled?: { missingFields: string[] }\n}\n\nexport interface DiffResult {\n target: Environment\n lockReflectsCloud: boolean\n delta: {\n addedInLock: Array<{ type: ResourceType; alias: string; name: string; version: string }>\n removedInLock: Array<{ type: ResourceType; alias: string; name: string; version: string }>\n changedInLock: Array<{ type: ResourceType; alias: string; field: string }>\n }\n}\n\nexport interface SyncResult {\n target: Environment\n updated: Array<{ type: ResourceType; alias: string }>\n added: Array<{ type: ResourceType; alias: string }>\n removed: Array<{ type: ResourceType; alias: string }>\n dryRun: boolean\n}\n\nexport interface ApplyAction {\n type: ResourceType\n alias: string\n action: 'install' | 'upgrade' | 'reconfigure' | 'enable' | 'disable' | 'uninstall'\n details?: Record<string, unknown>\n}\n\nexport interface ApplyResult {\n target: Environment\n applied: ApplyAction[]\n skipped: ApplyAction[]\n errors: Array<{ action: ApplyAction; code: string; message: string }>\n dryRun: boolean\n}\n\nexport interface MigrationResult {\n migrated: Environment[]\n envVarsToSet: string[]\n warnings: Array<{ code: string; message: string }>\n skipped: Array<{ env: Environment; reason: string }>\n}\n",
|
|
6
|
+
"export const DEPENDENCY_ERROR_CODES = [\n 'AUTH_REQUIRED',\n 'INTEGRATION_NOT_FOUND',\n 'PLUGIN_NOT_FOUND',\n 'INTERFACE_NOT_FOUND',\n 'VERSION_NOT_FOUND',\n 'MISSING_INPUT',\n 'MISSING_DEPENDENCY',\n 'AMBIGUOUS_DEPENDENCY',\n 'INTERFACE_NOT_IMPLEMENTED',\n 'LOCK_DRIFT',\n 'UNINSTALL_REQUIRES_CONFIRMATION',\n 'SAME_SOURCE_TARGET',\n 'SOURCE_LOCK_MISSING',\n 'MIGRATION_CONFLICT',\n 'INVALID_CONFIG',\n 'BOT_NOT_FOUND',\n 'BUILTIN_INTERFACE_IMMUTABLE',\n 'PROD_CONFIRMATION_REQUIRED',\n] as const\n\nexport type DependencyErrorCode = (typeof DEPENDENCY_ERROR_CODES)[number]\n\nexport class DependencyError extends Error {\n readonly code: DependencyErrorCode\n readonly details?: Record<string, unknown>\n readonly suggestion?: string\n\n constructor(opts: {\n code: DependencyErrorCode\n message: string\n details?: Record<string, unknown>\n suggestion?: string\n }) {\n super(opts.message)\n this.name = 'DependencyError'\n this.code = opts.code\n this.details = opts.details\n this.suggestion = opts.suggestion\n }\n}\n\nexport const DEPENDENCY_WARNING_CODES = [\n 'DEPRECATED_COMMAND',\n 'MIGRATED_DEPENDENCIES',\n 'HEURISTIC_SECRET_MASKED',\n 'CLOUD_FETCH_PARTIAL',\n 'NO_PROD_BOT',\n] as const\nexport type DependencyWarningCode = (typeof DEPENDENCY_WARNING_CODES)[number]\n",
|
|
7
|
+
"export function sortKeysDeep<T>(value: T): T {\n if (Array.isArray(value)) return value.map(sortKeysDeep) as unknown as T\n if (value && typeof value === 'object') {\n const obj = value as Record<string, unknown>\n const sorted: Record<string, unknown> = {}\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = sortKeysDeep(obj[key])\n }\n return sorted as unknown as T\n }\n return value\n}\n\nexport function jsonEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(sortKeysDeep(a)) === JSON.stringify(sortKeysDeep(b))\n}\n",
|
|
8
|
+
"import * as path from 'path'\nimport * as fs from 'fs/promises'\nimport { lockFileSchema, type LockFileData, type Environment } from './types.js'\nimport { DependencyError } from './errors.js'\nimport { sortKeysDeep } from './json-utils.js'\n\nexport interface LockFileOptions {\n projectPath: string\n env: Environment\n}\n\nexport class LockFile {\n private readonly filePath: string\n private readonly env: Environment\n\n constructor(opts: LockFileOptions) {\n this.env = opts.env\n this.filePath = path.join(opts.projectPath, `dependencies.${opts.env}.lock.json`)\n }\n\n async read(): Promise<LockFileData> {\n let raw: string\n try {\n raw = await fs.readFile(this.filePath, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return lockFileSchema.parse({ version: 1, env: this.env })\n }\n throw err\n }\n const parsed = JSON.parse(raw)\n try {\n return lockFileSchema.parse(parsed)\n } catch (err) {\n throw new DependencyError({\n code: 'INVALID_CONFIG',\n message: `Lock file at ${this.filePath} failed schema validation`,\n details: { issues: (err as { issues?: unknown }).issues ?? String(err) },\n })\n }\n }\n\n async write(data: LockFileData): Promise<void> {\n const validated = lockFileSchema.parse(data)\n const serialized = JSON.stringify(sortKeysDeep(validated), null, 2) + '\\n'\n const tmp = `${this.filePath}.tmp-${process.pid}-${Date.now()}`\n await fs.writeFile(tmp, serialized, 'utf8')\n await fs.rename(tmp, this.filePath)\n }\n\n async exists(): Promise<boolean> {\n try {\n await fs.access(this.filePath)\n return true\n } catch {\n return false\n }\n }\n\n async delete(): Promise<void> {\n try {\n await fs.unlink(this.filePath)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return\n throw err\n }\n }\n}\n",
|
|
9
|
+
"import { z } from '@botpress/sdk'\nimport { defineConfig } from '@botpress/runtime'\nimport { ValidationErrors } from './validation-errors'\n\nexport type AgentConfig = ReturnType<typeof defineConfig>\n\n// Plugin dependency mapping schema (matches SDK's PluginConfigInstance.dependencies)\nconst pluginDependencyMappingSchema = z.object({\n integrationAlias: z.string(),\n integrationInterfaceAlias: z.string().optional(), // present for interface deps, absent for integration deps\n})\n\n// Dependencies schema\nexport const dependenciesSchema = z.object({\n integrations: z\n .record(\n z.union([\n z.string(), // Shorthand: \"chat@1.0.0\" — server-managed enabled state, disabled on first install\n z.object({\n version: z.string(),\n enabled: z.boolean(), // Whether the integration is enabled\n configurationType: z.string().optional(), // Type of configuration (e.g., \"refreshToken\", \"apiKey\")\n config: z.record(z.any()).optional(), // Local config overrides (non-secret)\n }),\n ])\n )\n .optional(),\n plugins: z\n .record(\n z.object({\n version: z.string(),\n config: z.record(z.any()).optional(),\n dependencies: z.record(pluginDependencyMappingSchema).optional(),\n })\n )\n .optional(),\n})\n\nexport type Dependencies = z.infer<typeof dependenciesSchema>\n\n// Agent deployment info schema\nexport const agentInfoSchema = z.object({\n botId: z.string().describe('The bot ID from Botpress deployment'),\n workspaceId: z.string().describe('The workspace ID where the bot is deployed'),\n apiUrl: z.string().optional().describe('The Botpress API URL (e.g., https://api.botpress.cloud)'),\n devId: z.string().optional().describe('The development ID used during local development'),\n})\n\nexport type AgentInfo = z.infer<typeof agentInfoSchema>\n\n// Agent local info schema (for agent.local.json — gitignored, per-developer overrides)\nexport const agentLocalInfoSchema = z.object({\n botId: z.string().optional().describe('The bot ID (overrides agent.json for local development)'),\n workspaceId: z.string().optional().describe('The workspace ID (overrides agent.json for local development)'),\n apiUrl: z.string().optional().describe('The Botpress API URL (overrides agent.json for local development)'),\n devId: z.string().optional().describe('The development bot ID used during local development'),\n})\nexport type AgentLocalInfo = z.infer<typeof agentLocalInfoSchema>\n\n// File change event types\nexport enum FileChangeType {\n Added = 'added',\n Modified = 'modified',\n Deleted = 'deleted',\n}\n\nexport interface FileChangeEvent {\n type: FileChangeType\n path: string\n relativePath: string\n}\n\n// Build event types\nexport enum BuildEventType {\n Started = 'started',\n Progress = 'progress',\n Success = 'success',\n Error = 'error',\n Warning = 'warning',\n}\n\nexport interface BuildEvent {\n type: BuildEventType\n message?: string\n error?: Error\n warnings?: string[]\n}\n\n// Validation error codes\nexport enum ValidationErrorCode {\n // Project structure errors\n DIRECTORY_NOT_FOUND = 'DIRECTORY_NOT_FOUND',\n DIRECTORY_ACCESS_ERROR = 'DIRECTORY_ACCESS_ERROR',\n REQUIRED_FILE_MISSING = 'REQUIRED_FILE_MISSING',\n INVALID_STRUCTURE = 'INVALID_STRUCTURE',\n\n // Configuration errors\n INVALID_CONFIG_SYNTAX = 'INVALID_CONFIG_SYNTAX',\n INVALID_CONFIG_SCHEMA = 'INVALID_CONFIG_SCHEMA',\n MISSING_REQUIRED_FIELD = 'MISSING_REQUIRED_FIELD',\n AGENT_NOT_LINKED = 'AGENT_NOT_LINKED',\n\n // Dependencies errors\n INVALID_DEPENDENCIES_SYNTAX = 'INVALID_DEPENDENCIES_SYNTAX',\n INVALID_DEPENDENCIES_SCHEMA = 'INVALID_DEPENDENCIES_SCHEMA',\n INVALID_VERSION_FORMAT = 'INVALID_VERSION_FORMAT',\n INVALID_INTEGRATION_ALIAS = 'INVALID_INTEGRATION_ALIAS',\n INVALID_PLUGIN_ALIAS = 'INVALID_PLUGIN_ALIAS',\n UNKNOWN_INTEGRATION = 'UNKNOWN_INTEGRATION',\n UNKNOWN_PLUGIN = 'UNKNOWN_PLUGIN',\n INVALID_PLUGIN_DEPENDENCY = 'INVALID_PLUGIN_DEPENDENCY',\n INCOMPATIBLE_VERSION = 'INCOMPATIBLE_VERSION',\n CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY',\n\n // File errors\n FILE_TOO_LARGE = 'FILE_TOO_LARGE',\n INVALID_FILE_TYPE = 'INVALID_FILE_TYPE',\n INVALID_FILE_NAME = 'INVALID_FILE_NAME',\n DUPLICATE_FILE_NAME = 'DUPLICATE_FILE_NAME',\n DUPLICATE_PRIMITIVE = 'DUPLICATE_PRIMITIVE',\n INVALID_PRIMITIVE_DEFINITION = 'INVALID_PRIMITIVE_DEFINITION',\n TABLE_TOO_MANY_COLUMNS = 'TABLE_TOO_MANY_COLUMNS',\n\n // Runtime errors\n BUILD_FAILED = 'BUILD_FAILED',\n SYNTAX_ERROR = 'SYNTAX_ERROR',\n TYPE_ERROR = 'TYPE_ERROR',\n IMPORT_ERROR = 'IMPORT_ERROR',\n}\n\n// Validation severity levels\nexport enum ValidationSeverity {\n ERROR = 'error',\n WARNING = 'warning',\n INFO = 'info',\n}\n\n// Enhanced validation error interface\nexport interface ValidationError {\n $type: typeof ValidationErrors.$type\n code: ValidationErrorCode\n severity: ValidationSeverity\n message: string\n file?: string\n line?: number\n column?: number\n hint?: string\n documentation?: string\n context?: Record<string, unknown>\n}\n\n// Validation result with categorized errors\nexport interface ValidationResult {\n valid: boolean\n errors: ValidationError[]\n warnings: ValidationError[]\n info: ValidationError[]\n errorCount: number\n warningCount: number\n infoCount: number\n}\n\n// Agent project state\nexport enum ProjectState {\n Unloaded = 'unloaded',\n Loading = 'loading',\n Ready = 'ready',\n Building = 'building',\n Error = 'error',\n}\n\n// Build output types\nexport interface BuildOutput {\n files: Map<string, Buffer | string>\n metadata: {\n buildTime: Date\n version?: string\n checksum?: string\n }\n}\n\n// Watch options\nexport interface WatchOptions {\n ignore?: string[]\n debounce?: number\n autoBuild?: boolean\n}\n\n// Integration types\nexport interface Integration {\n name: string\n version: string\n workspace?: string // Optional workspace name\n config?: Record<string, unknown>\n installed?: boolean\n installedVersion?: string\n hasChannels?: boolean\n}\n\nexport interface IntegrationChange {\n type: 'install' | 'update' | 'uninstall'\n integration: Integration\n from?: string // For updates: from version\n to?: string // For updates: to version\n}\n\nexport interface IntegrationSyncResult {\n changes: IntegrationChange[]\n applied: boolean\n errors?: Error[]\n}\n\nexport interface AgentToolDefinition {\n name: string\n description?: string\n}\n\nexport interface ToolReference {\n path: string\n export: string\n definition: AgentToolDefinition\n}\n\n// Project info\nexport interface ProjectInfo {\n path: string\n config: AgentConfig\n dependencies: Dependencies\n agentInfo?: AgentInfo // Optional deployment information\n state: ProjectState\n lastBuildTime?: Date\n errors: ValidationError[]\n warnings: ValidationError[]\n errorCount: number\n warningCount: number\n infoCount: number\n integrations?: Integration[] // Parsed integrations from dependencies\n}\n\nexport type IntegrationDependency = {\n type: 'integration'\n integration: {\n name: string\n version: string\n enabled: boolean\n }\n}\n\nexport type InterfaceDependency = {\n type: 'interface'\n interface: {\n name: string\n version: string\n }\n}\n\nexport type PluginDependency = {\n type: 'plugin'\n plugin: {\n name: string\n version: string\n }\n}\n\nexport type Dependency = IntegrationDependency | InterfaceDependency | PluginDependency\n",
|
|
10
|
+
"import { ValidationError, ValidationErrorCode, ValidationSeverity } from './types.js'\n\n/**\n * Factory functions for creating consistent validation errors\n */\n\nexport class ValidationErrors {\n static $type = 'ValidationError' as const\n\n /**\n * Type guard to check if an error is a ValidationError\n */\n static isValidationError(error: unknown): error is ValidationError {\n return error !== null && typeof error === 'object' && '$type' in error && error.$type === 'ValidationError'\n }\n\n // Project structure errors\n static directoryNotFound(path: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.DIRECTORY_NOT_FOUND,\n severity: ValidationSeverity.ERROR,\n message: `Project directory not found: ${path}`,\n hint: 'Ensure the directory exists and you have permission to access it',\n context: { path },\n }\n }\n\n static directoryAccessError(path: string, error: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.DIRECTORY_ACCESS_ERROR,\n severity: ValidationSeverity.ERROR,\n message: `Cannot access project directory: ${error}`,\n hint: 'Check file system permissions',\n context: { path, error },\n }\n }\n\n static requiredFileMissing(file: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.REQUIRED_FILE_MISSING,\n severity: ValidationSeverity.ERROR,\n message: `Required file '${file}' not found`,\n file,\n hint: `Create a ${file} file in your project root`,\n documentation: 'https://docs.botpress.com/adk/project-structure',\n }\n }\n\n static invalidStructure(directory: string, expected: 'directory' | 'file'): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_STRUCTURE,\n severity: ValidationSeverity.WARNING,\n message: `Expected '${directory}' to be a ${expected}`,\n file: directory,\n hint: `Ensure ${directory} is a ${expected}, not a ${expected === 'directory' ? 'file' : 'directory'}`,\n }\n }\n\n // Configuration errors\n static invalidConfigSyntax(file: string, error: string, line?: number, column?: number): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_CONFIG_SYNTAX,\n severity: ValidationSeverity.ERROR,\n message: `Invalid syntax in ${file}: ${error}`,\n file,\n line,\n column,\n hint: 'Check for syntax errors like missing commas, brackets, or quotes',\n }\n }\n\n static invalidConfigSchema(file: string, field: string, error: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_CONFIG_SCHEMA,\n severity: ValidationSeverity.ERROR,\n message: `Invalid configuration in ${file}: ${error}`,\n file,\n hint: `Check the '${field}' field matches the expected schema`,\n context: { field, error },\n }\n }\n\n static missingRequiredField(file: string, field: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.MISSING_REQUIRED_FIELD,\n severity: ValidationSeverity.ERROR,\n message: `Missing required field '${field}' in ${file}`,\n file,\n hint: `Add the '${field}' field to your configuration`,\n documentation: 'https://docs.botpress.com/adk/configuration',\n }\n }\n\n static tableTooManyColumns(tableName: string, filePath: string, columnCount: number, max: number): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.TABLE_TOO_MANY_COLUMNS,\n severity: ValidationSeverity.ERROR,\n message: `Table '${tableName}' has ${columnCount} columns (max ${max})`,\n file: filePath,\n hint: `Reduce columns or split into multiple tables. The limit is ${max} columns per table.`,\n context: { tableName, columnCount, max },\n }\n }\n\n // Dependencies errors\n static invalidDependenciesSyntax(error: string, line?: number): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_DEPENDENCIES_SYNTAX,\n severity: ValidationSeverity.ERROR,\n message: `Invalid syntax in agent.config.ts dependencies: ${error}`,\n file: 'agent.config.ts',\n line,\n hint: 'Ensure agent.config.ts exports a valid dependencies object',\n }\n }\n\n static invalidVersionFormat(integration: string, version: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_VERSION_FORMAT,\n severity: ValidationSeverity.ERROR,\n message: `Invalid version format '${version}' for integration '${integration}'`,\n file: 'agent.config.ts',\n hint: 'Use exact versioning (e.g., \"1.2.3\", \"2.0.0\", \"1.5.0\")',\n context: { integration, version },\n }\n }\n\n static invalidIntegrationAlias(alias: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_INTEGRATION_ALIAS,\n severity: ValidationSeverity.ERROR,\n message: `Invalid integration alias '${alias}'`,\n file: 'agent.config.ts',\n hint: 'Integration aliases must be 2-100 characters and contain only lowercase letters, numbers, underscores, and hyphens (e.g., \"slack\", \"my-slack\", \"slack_prod\")',\n context: { alias },\n }\n }\n\n static unknownIntegration(integration: string, source: string, detailedMessage?: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.UNKNOWN_INTEGRATION,\n severity: ValidationSeverity.ERROR,\n message: detailedMessage || `Unknown integration '${integration}' from source '${source}'`,\n file: 'agent.config.ts',\n hint: detailedMessage ? undefined : `Check if the integration name is correct or if it exists in ${source}`,\n context: { integration, source },\n }\n }\n\n static integrationVersionError(integration: string, errorMessage: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.UNKNOWN_INTEGRATION,\n severity: ValidationSeverity.ERROR,\n message: errorMessage,\n file: 'agent.config.ts',\n hint: `Update the version for \"${integration}\" in agent.config.ts dependencies`,\n }\n }\n\n static unknownInterface(errorMessage: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.UNKNOWN_INTEGRATION,\n severity: ValidationSeverity.ERROR,\n message: errorMessage,\n file: 'agent.config.ts',\n }\n }\n\n static incompatibleVersion(integration: string, required: string, available: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INCOMPATIBLE_VERSION,\n severity: ValidationSeverity.ERROR,\n message: `Integration '${integration}' requires version ${required}, but only ${available} is available`,\n file: 'agent.config.ts',\n hint: 'Update the version requirement or check for compatible versions',\n context: { integration, required, available },\n }\n }\n\n // Plugin errors\n static invalidPluginAlias(alias: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_PLUGIN_ALIAS,\n severity: ValidationSeverity.ERROR,\n message: `Invalid plugin alias '${alias}'`,\n file: 'agent.config.ts',\n hint: 'Plugin aliases must be 2-100 characters and contain only lowercase letters, numbers, underscores, and hyphens (e.g., \"hitl\", \"my-plugin\")',\n context: { alias },\n }\n }\n\n static invalidPluginVersionFormat(plugin: string, version: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_VERSION_FORMAT,\n severity: ValidationSeverity.ERROR,\n message: `Invalid version format '${version}' for plugin '${plugin}'`,\n file: 'agent.config.ts',\n hint: 'Use exact versioning (e.g., \"1.2.3\", \"2.0.0\", \"1.5.0\")',\n context: { plugin, version },\n }\n }\n\n static unknownPlugin(plugin: string, source: string, detailedMessage?: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.UNKNOWN_PLUGIN,\n severity: ValidationSeverity.ERROR,\n message: detailedMessage || `Unknown plugin '${plugin}' from source '${source}'`,\n file: 'agent.config.ts',\n hint: detailedMessage ? undefined : `Check if the plugin name is correct or if it exists on the Botpress Hub`,\n context: { plugin, source },\n }\n }\n\n static invalidPluginDependency(\n plugin: string,\n integrationAlias: string,\n availableIntegrations: string[]\n ): ValidationError {\n const available = availableIntegrations.length > 0 ? availableIntegrations.join(', ') : '(none)'\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_PLUGIN_DEPENDENCY,\n severity: ValidationSeverity.ERROR,\n message: `Plugin \"${plugin}\" references integration \"${integrationAlias}\" in its dependencies, but \"${integrationAlias}\" is not declared in dependencies.integrations`,\n file: 'agent.config.ts',\n hint: `Add \"${integrationAlias}\" to dependencies.integrations, or update the plugin dependency to reference one of: ${available}`,\n context: { plugin, integrationAlias, availableIntegrations },\n }\n }\n\n static pluginVersionError(plugin: string, errorMessage: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.UNKNOWN_PLUGIN,\n severity: ValidationSeverity.ERROR,\n message: errorMessage,\n file: 'agent.config.ts',\n hint: `Update the version for \"${plugin}\" in agent.config.ts dependencies`,\n }\n }\n\n // File errors\n static fileTooLarge(file: string, size: number, maxSize: number): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.FILE_TOO_LARGE,\n severity: ValidationSeverity.ERROR,\n message: `File '${file}' is too large (${formatBytes(size)} > ${formatBytes(maxSize)})`,\n file,\n hint: 'Reduce file size or split into smaller files',\n context: { size, maxSize },\n }\n }\n\n static invalidFileType(file: string, type: string, allowedTypes: string[]): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_FILE_TYPE,\n severity: ValidationSeverity.ERROR,\n message: `Invalid file type '${type}' for file '${file}'`,\n file,\n hint: `Allowed file types: ${allowedTypes.join(', ')}`,\n context: { type, allowedTypes },\n }\n }\n\n static invalidFileName(file: string, reason: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_FILE_NAME,\n severity: ValidationSeverity.ERROR,\n message: `Invalid file name '${file}': ${reason}`,\n file,\n hint: 'Use lowercase letters, numbers, and hyphens only',\n }\n }\n\n static duplicateFileName(file: string, existingFile: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.DUPLICATE_FILE_NAME,\n severity: ValidationSeverity.ERROR,\n message: `Duplicate file name '${file}' conflicts with '${existingFile}'`,\n file,\n hint: 'Rename one of the files to avoid conflicts',\n context: { existingFile },\n }\n }\n\n // Runtime errors\n static buildFailed(error: string, file?: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.BUILD_FAILED,\n severity: ValidationSeverity.ERROR,\n message: `Build failed: ${error}`,\n file,\n hint: 'Check the error message and fix any issues in your code',\n }\n }\n\n static syntaxError(file: string, error: string, line?: number, column?: number): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.SYNTAX_ERROR,\n severity: ValidationSeverity.ERROR,\n message: `Syntax error: ${error}`,\n file,\n line,\n column,\n hint: 'Check for missing semicolons, brackets, or other syntax issues',\n }\n }\n\n static typeError(file: string, error: string, line?: number): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.TYPE_ERROR,\n severity: ValidationSeverity.ERROR,\n message: `Type error: ${error}`,\n file,\n line,\n hint: 'Ensure types match expected values and imports are correct',\n }\n }\n\n static importError(file: string, module: string, error: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.IMPORT_ERROR,\n severity: ValidationSeverity.ERROR,\n message: `Cannot import '${module}': ${error}`,\n file,\n hint: 'Check if the module exists and is properly installed',\n context: { module },\n }\n }\n\n // Knowledge errors\n static unsafeKnowledgePath(knowledgeBase: string, pattern: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_FILE_NAME,\n severity: ValidationSeverity.ERROR,\n message: `Knowledge base '${knowledgeBase}' contains unsafe path pattern '${pattern}'`,\n file: `src/knowledge/${knowledgeBase}.ts`,\n hint: 'Knowledge patterns must not reference files outside the agent directory (remove ../ or absolute paths)',\n context: { knowledgeBase, pattern },\n }\n }\n\n // Agent linking errors\n static agentNotLinked(): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.AGENT_NOT_LINKED,\n severity: ValidationSeverity.ERROR,\n message: 'Agent is not linked to a workspace',\n file: 'agent.json',\n hint: 'Please run \"adk link\" to link your agent to a workspace',\n }\n }\n\n static workspaceIdMissing(): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.AGENT_NOT_LINKED,\n severity: ValidationSeverity.ERROR,\n message: 'No workspaceId found in agent.json',\n file: 'agent.json',\n hint: 'Please run \"adk link\" to link your agent to a workspace',\n }\n }\n\n static botIdMissing(): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.AGENT_NOT_LINKED,\n severity: ValidationSeverity.ERROR,\n message: 'No botId found in agent.json',\n file: 'agent.json',\n hint: 'Please run \"adk link\" to link your agent to a bot',\n }\n }\n\n // Utility functions\n static info(message: string, file?: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_STRUCTURE, // Generic code for info\n severity: ValidationSeverity.INFO,\n message,\n file,\n }\n }\n\n static warning(message: string, file?: string, hint?: string): ValidationError {\n return {\n $type: ValidationErrors.$type,\n code: ValidationErrorCode.INVALID_STRUCTURE, // Generic code for warnings\n severity: ValidationSeverity.WARNING,\n message,\n file,\n hint,\n }\n }\n}\n\n// Helper function to format bytes\nfunction formatBytes(bytes: number): string {\n if (bytes === 0) return '0 Bytes'\n const k = 1024\n const sizes = ['Bytes', 'KB', 'MB', 'GB']\n const i = Math.floor(Math.log(bytes) / Math.log(k))\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]\n}\n",
|
|
11
|
+
"/**\n * Default Botpress API URL\n * Used when agent.json doesn't specify an apiUrl (for backwards compatibility)\n */\nexport const DEFAULT_API_URL = 'https://api.botpress.cloud'\n\n/**\n * Built-in interfaces that are always included in ADK projects\n * These are constants and cannot be modified by users\n */\nexport const BUILTIN_INTERFACES = {\n 'typing-indicator': 'typing-indicator@0.0.3',\n llm: 'llm@9.0.0',\n listable: 'listable@0.0.2',\n} as const\n\nexport const MAX_TABLE_COLUMNS = 20\n",
|
|
12
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport { type AgentInfo, type AgentLocalInfo, agentInfoSchema, agentLocalInfoSchema } from './types.js'\nimport { ValidationErrors } from './validation-errors.js'\nimport { DEFAULT_API_URL } from '../constants.js'\n\nexport interface ResolveAgentOptions {\n /**\n * If true, throws an error if agent.json is missing or invalid.\n * If false, returns null when agent.json is not found.\n */\n required?: boolean\n /**\n * If true, validates that workspaceId exists in agent.json\n */\n requireWorkspace?: boolean\n /**\n * If true, validates that botId exists in agent.json\n */\n requireBot?: boolean\n}\n\n/**\n * Try to read and parse agent.local.json, returning the validated data or null.\n */\nasync function readLocalInfo(agentPath: string): Promise<AgentLocalInfo | null> {\n const localPath = path.join(agentPath, 'agent.local.json')\n try {\n const localContent = await fs.readFile(localPath, 'utf-8')\n const localData = JSON.parse(localContent)\n const localResult = agentLocalInfoSchema.safeParse(localData)\n if (!localResult.success) {\n const issue = localResult.error.errors[0]\n throw ValidationErrors.warning(\n `agent.local.json has an invalid field: ${issue?.path.join('.')} — ${issue?.message}`,\n 'agent.local.json'\n )\n }\n return localResult.data\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null\n }\n if (ValidationErrors.isValidationError(error)) {\n throw error\n }\n throw ValidationErrors.warning(`Failed to read agent.local.json: ${(error as Error).message}`, 'agent.local.json')\n }\n}\n\n/**\n * Apply agent.local.json overrides onto an AgentInfo object.\n * Local values take precedence over agent.json values.\n */\nfunction applyLocalOverrides(agentInfo: AgentInfo, localInfo: AgentLocalInfo): void {\n if (localInfo.botId) {\n agentInfo.botId = localInfo.botId\n }\n if (localInfo.workspaceId) {\n agentInfo.workspaceId = localInfo.workspaceId\n }\n if (localInfo.apiUrl) {\n agentInfo.apiUrl = localInfo.apiUrl\n }\n if (localInfo.devId) {\n agentInfo.devId = localInfo.devId\n }\n}\n\n/**\n * Resolve agent information from agent.json and agent.local.json files.\n * agent.local.json fields take precedence over agent.json fields.\n * This is the single source of truth for loading agent configuration.\n */\nexport async function resolveAgent(agentPath: string, options: ResolveAgentOptions = {}): Promise<AgentInfo | null> {\n const { required = false, requireWorkspace = false, requireBot = false } = options\n\n const agentJsonPath = path.join(agentPath, 'agent.json')\n const localInfo = await readLocalInfo(agentPath)\n\n let agentInfo: AgentInfo | null = null\n\n try {\n // Read agent.json\n const agentJsonContent = await fs.readFile(agentJsonPath, 'utf-8')\n\n // Parse JSON\n let agentData: unknown\n try {\n agentData = JSON.parse(agentJsonContent)\n } catch (parseError) {\n throw ValidationErrors.invalidConfigSyntax('agent.json', (parseError as Error).message)\n }\n\n // Validate structure\n const validationResult = agentInfoSchema.safeParse(agentData)\n if (!validationResult.success) {\n const zodError = validationResult.error.errors[0]\n throw ValidationErrors.invalidConfigSchema(\n 'agent.json',\n zodError?.path.join('.') || 'unknown',\n zodError?.message || 'Invalid schema'\n )\n }\n\n agentInfo = validationResult.data\n } catch (error) {\n // Handle file not found — agent.local.json may still provide the info\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // Fall through to check agent.local.json below\n } else if (ValidationErrors.isValidationError(error)) {\n throw error\n } else {\n throw ValidationErrors.warning(`Failed to read agent.json: ${(error as Error).message}`, 'agent.json')\n }\n }\n\n // If agent.json wasn't found, try to construct AgentInfo from agent.local.json alone\n if (!agentInfo) {\n if (localInfo?.botId && localInfo?.workspaceId) {\n agentInfo = {\n botId: localInfo.botId,\n workspaceId: localInfo.workspaceId,\n apiUrl: localInfo.apiUrl,\n devId: localInfo.devId,\n }\n } else if (required || requireWorkspace || requireBot) {\n throw ValidationErrors.requiredFileMissing('agent.json or agent.local.json')\n } else {\n return null\n }\n } else {\n // Apply agent.local.json overrides onto agent.json values\n if (localInfo) {\n applyLocalOverrides(agentInfo, localInfo)\n }\n }\n\n // Default apiUrl to .cloud if missing (for backwards compatibility)\n if (!agentInfo.apiUrl) {\n agentInfo.apiUrl = DEFAULT_API_URL\n }\n\n // Validate workspace requirement\n if (requireWorkspace && !agentInfo.workspaceId) {\n throw ValidationErrors.workspaceIdMissing()\n }\n\n // Validate bot requirement\n if (requireBot && !agentInfo.botId) {\n throw ValidationErrors.botIdMissing()\n }\n\n return agentInfo\n}\n\n/**\n * Check if agent.json exists in the given path\n */\nexport async function hasAgentJson(agentPath: string): Promise<boolean> {\n const agentJsonPath = path.join(agentPath, 'agent.json')\n try {\n await fs.access(agentJsonPath)\n return true\n } catch {\n return false\n }\n}\n",
|
|
13
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { resolveAgent } from '../agent-project/agent-resolver.js'\n\nexport interface Credentials {\n token: string\n apiUrl: string\n workspaceId?: string\n workspaceName?: string\n botId?: string\n}\n\nexport interface Profile {\n name: string\n credentials: Credentials\n apiUrl: string\n lastUsed: string\n email?: string\n displayName?: string\n accountId?: string\n createdAt?: string\n}\n\nexport interface ProfileMetadata {\n lastUsed: string\n accountId?: string\n email?: string\n displayName?: string\n createdAt?: string\n}\n\nexport interface CredentialsStore {\n profiles: Record<string, Credentials>\n profileMetadata: Record<string, ProfileMetadata>\n currentProfile: string\n}\n\nexport class CredentialsManager {\n private credentialsPath: string\n private configDir: string\n private profileOverride: string | undefined\n\n constructor() {\n // Store credentials in ~/.adk/credentials\n this.configDir = path.join(os.homedir(), '.adk')\n this.credentialsPath = path.join(this.configDir, 'credentials')\n }\n\n /**\n * Set a profile override that takes precedence over ADK_PROFILE env var and stored current profile.\n * This is used by the CLI's global --profile flag.\n */\n setProfileOverride(profile: string | undefined): void {\n this.profileOverride = profile\n }\n\n private async ensureConfigDir(): Promise<void> {\n try {\n await fs.mkdir(this.configDir, { recursive: true })\n } catch {\n // Directory might already exist, that's fine\n }\n }\n\n private async readCredentials(): Promise<CredentialsStore> {\n try {\n const data = await fs.readFile(this.credentialsPath, 'utf-8')\n return JSON.parse(data)\n } catch {\n // If file doesn't exist or is invalid, return empty store\n return {\n profiles: {},\n profileMetadata: {},\n currentProfile: 'default',\n }\n }\n }\n\n private async writeCredentials(store: CredentialsStore): Promise<void> {\n await this.ensureConfigDir()\n await fs.writeFile(this.credentialsPath, JSON.stringify(store, null, 2))\n // Set restrictive permissions (read/write for owner only)\n await fs.chmod(this.credentialsPath, 0o600)\n }\n\n async saveCredentials(\n profileName: string,\n credentials: Credentials,\n userInfo?: Partial<ProfileMetadata>\n ): Promise<void> {\n const store = await this.readCredentials()\n store.profiles[profileName] = credentials\n\n // Initialize metadata if it doesn't exist\n if (!store.profileMetadata) {\n store.profileMetadata = {}\n }\n\n // Update metadata with user info\n store.profileMetadata[profileName] = {\n lastUsed: new Date().toISOString(),\n ...userInfo,\n }\n\n // If this is the first profile, make it current\n if (Object.keys(store.profiles).length === 1) {\n store.currentProfile = profileName\n }\n\n await this.writeCredentials(store)\n }\n\n async getCredentials(profileName?: string): Promise<Credentials | null> {\n const store = await this.readCredentials()\n const profile = profileName || store.currentProfile\n\n if (!store.profiles[profile]) {\n return null\n }\n\n return store.profiles[profile]\n }\n\n async listProfiles(): Promise<Profile[]> {\n const store = await this.readCredentials()\n\n // Initialize metadata if it doesn't exist\n if (!store.profileMetadata) {\n store.profileMetadata = {}\n }\n\n return Object.entries(store.profiles).map(([name, credentials]) => {\n const metadata = store.profileMetadata[name] || ({} as ProfileMetadata)\n return {\n name,\n credentials,\n apiUrl: credentials.apiUrl,\n lastUsed: metadata.lastUsed || new Date().toISOString(),\n email: metadata.email,\n displayName: metadata.displayName,\n accountId: metadata.accountId,\n createdAt: metadata.createdAt,\n }\n })\n }\n\n async getCurrentProfile(): Promise<string> {\n const store = await this.readCredentials()\n return store.currentProfile || 'default'\n }\n\n async getCurrentProfileDetails(): Promise<Profile | null> {\n const store = await this.readCredentials()\n const currentProfileName = store.currentProfile || 'default'\n\n if (!store.profiles[currentProfileName]) {\n return null\n }\n\n const credentials = store.profiles[currentProfileName]\n const metadata = store.profileMetadata?.[currentProfileName] || ({} as ProfileMetadata)\n\n return {\n name: currentProfileName,\n credentials,\n apiUrl: credentials.apiUrl,\n lastUsed: metadata.lastUsed || new Date().toISOString(),\n email: metadata.email,\n displayName: metadata.displayName,\n accountId: metadata.accountId,\n createdAt: metadata.createdAt,\n }\n }\n\n async setCurrentProfile(profileName: string): Promise<void> {\n const store = await this.readCredentials()\n\n if (!store.profiles[profileName]) {\n throw new Error(`Profile '${profileName}' not found`)\n }\n\n // Initialize metadata if it doesn't exist\n if (!store.profileMetadata) {\n store.profileMetadata = {}\n }\n\n // Update last used time while preserving other metadata\n store.profileMetadata[profileName] = {\n ...store.profileMetadata[profileName], // Preserve existing metadata\n lastUsed: new Date().toISOString(),\n }\n\n store.currentProfile = profileName\n await this.writeCredentials(store)\n }\n\n async deleteProfile(profileName: string): Promise<void> {\n const store = await this.readCredentials()\n\n if (!store.profiles[profileName]) {\n throw new Error(`Profile '${profileName}' not found`)\n }\n\n delete store.profiles[profileName]\n delete store.profileMetadata?.[profileName]\n\n // If we deleted the current profile, switch to another one\n if (store.currentProfile === profileName) {\n const remainingProfiles = Object.keys(store.profiles)\n store.currentProfile = remainingProfiles.length > 0 ? remainingProfiles[0]! : 'default'\n }\n\n await this.writeCredentials(store)\n }\n\n async getActiveCredentials(): Promise<Credentials> {\n // Priority: 1) profileOverride (--profile flag), 2) ADK_PROFILE env var, 3) stored currentProfile\n const profileName = this.profileOverride || process.env.ADK_PROFILE\n\n const credentials = await this.getCredentials(profileName)\n\n if (!credentials) {\n const displayName = profileName || 'default'\n throw new Error(`No credentials found for profile '${displayName}'. ` + `Please run 'adk login' to authenticate.`)\n }\n\n return credentials\n }\n\n /**\n * Find a profile whose apiUrl matches the given URL.\n * Returns the credentials of the first matching profile, or null if none match.\n * Accepts a pre-loaded store to avoid redundant file reads.\n */\n private findProfileByApiUrl(store: CredentialsStore, apiUrl: string): Credentials | null {\n const normalizedUrl = apiUrl.replace(/\\/+$/, '') // strip trailing slashes\n\n for (const [, credentials] of Object.entries(store.profiles)) {\n if (!credentials.apiUrl) continue\n const profileUrl = credentials.apiUrl.replace(/\\/+$/, '')\n if (profileUrl === normalizedUrl) {\n return credentials\n }\n }\n\n return null\n }\n\n /**\n * Get credentials for agent-specific operations\n * This will prioritize workspaceId and apiUrl from agent.json over credentials file.\n * When no explicit profile is specified, it auto-selects the profile whose apiUrl\n * matches the agent.json apiUrl.\n *\n * @param agentPath - Path to the agent project directory\n * @throws Error if agent.json is missing or doesn't contain workspaceId\n */\n async getAgentCredentials(agentPath: string): Promise<Credentials> {\n // Resolve agent.json first to determine the target API URL\n const agentInfo = await resolveAgent(agentPath, {\n required: true,\n requireWorkspace: true,\n })\n\n // agentInfo is guaranteed to be non-null and have workspaceId due to options above\n // apiUrl is also guaranteed by resolveAgent which defaults it to DEFAULT_API_URL\n const agentApiUrl = agentInfo!.apiUrl!\n\n // Determine base credentials:\n // If user explicitly specified a profile (--profile flag or ADK_PROFILE env), honor that.\n // Otherwise, try to find a profile that matches the agent's API URL.\n let baseCredentials: Credentials\n\n const hasExplicitProfile = !!(this.profileOverride || process.env.ADK_PROFILE)\n\n if (hasExplicitProfile) {\n baseCredentials = await this.getActiveCredentials()\n } else {\n // Read the store once and reuse it for both the profile lookup and the fallback\n const store = await this.readCredentials()\n const matchingCredentials = this.findProfileByApiUrl(store, agentApiUrl)\n if (matchingCredentials) {\n baseCredentials = matchingCredentials\n } else {\n // Fall back to the active profile from the same store read\n const profileName = store.currentProfile || 'default'\n const activeCredentials = store.profiles[profileName]\n if (!activeCredentials) {\n throw new Error(\n `No credentials found for profile '${profileName}'. ` + `Please run 'adk login' to authenticate.`\n )\n }\n baseCredentials = activeCredentials\n }\n }\n\n return {\n ...baseCredentials,\n apiUrl: agentApiUrl,\n workspaceId: agentInfo!.workspaceId,\n botId: agentInfo!.botId,\n }\n }\n}\n",
|
|
14
|
+
"import { Client } from '@botpress/client'\n\nexport interface AuthResult {\n workspaceId?: string\n workspaceName?: string\n botId?: string\n userId?: string\n email?: string\n displayName?: string\n accountId?: string\n createdAt?: string\n}\n\nexport class AuthService {\n private apiUrl: string\n\n constructor(apiUrl?: string) {\n this.apiUrl = apiUrl || 'https://api.botpress.cloud'\n }\n\n async validateToken(token: string): Promise<AuthResult> {\n if (!token || !token.startsWith('bp_')) {\n throw new Error('Invalid token format. Token should start with \"bp_\"')\n }\n\n try {\n // Create a Botpress client with the token\n const client = new Client({\n apiUrl: this.apiUrl,\n token,\n headers: {\n 'x-multiple-integrations': 'true',\n },\n })\n\n // Try to get account details to validate the token\n // This is a lightweight call that will fail if the token is invalid\n const accountResponse = await client.getAccount({})\n const { account } = accountResponse\n\n // Also get workspaces for additional context\n const workspaces = await client.list.workspaces({}).collect()\n\n // If we get here, the token is valid\n return {\n workspaceId: workspaces[0]?.id,\n workspaceName: workspaces[0]?.name,\n accountId: account.id,\n email: account.email,\n displayName: account.displayName,\n createdAt: account.createdAt,\n }\n } catch (error) {\n if (error instanceof Error) {\n // Check for common authentication errors\n if (error.message.includes('401') || error.message.includes('Unauthorized')) {\n throw new Error('Invalid token. Please check your API token and try again.')\n }\n if (error.message.includes('Network') || error.message.includes('ENOTFOUND')) {\n throw new Error(`Unable to connect to ${this.apiUrl}. Please check your internet connection and API URL.`)\n }\n }\n\n // Re-throw the original error if it's not a known authentication error\n throw error\n }\n }\n\n async testConnection(token: string): Promise<boolean> {\n try {\n await this.validateToken(token)\n return true\n } catch {\n return false\n }\n }\n}\n",
|
|
15
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { auth } from './index.js'\n\ninterface BpCliCredentials {\n token: string\n workspaceId: string\n apiUrl: string\n botId?: string\n}\n\nexport class BpCliImporter {\n private bpCachePath: string\n\n constructor() {\n // BP CLI stores credentials in ~/.botpress/global.cache.json\n this.bpCachePath = path.join(os.homedir(), '.botpress', 'global.cache.json')\n }\n\n async hasBpCliCredentials(): Promise<boolean> {\n try {\n await fs.access(this.bpCachePath)\n return true\n } catch {\n return false\n }\n }\n\n async getBpCliCredentials(): Promise<BpCliCredentials | null> {\n try {\n const data = await fs.readFile(this.bpCachePath, 'utf-8')\n const credentials = JSON.parse(data) as BpCliCredentials\n\n // Validate required fields\n if (!credentials.token || !credentials.workspaceId || !credentials.apiUrl) {\n return null\n }\n\n return credentials\n } catch {\n return null\n }\n }\n\n async importFromBpCli(profileName: string = 'default'): Promise<boolean> {\n const bpCredentials = await this.getBpCliCredentials()\n if (!bpCredentials) {\n return false\n }\n\n try {\n // Login with BP CLI credentials\n await auth.login(bpCredentials.token, {\n profile: profileName,\n apiUrl: bpCredentials.apiUrl,\n })\n\n // The login process will have saved basic credentials\n // Now we need to update them with the workspace ID from BP CLI\n // We'll do this by creating a new CredentialsManager instance\n const credentialsManager = new (await import('./credentials.js')).CredentialsManager()\n\n // Read current credentials\n const store = await credentialsManager['readCredentials']()\n\n if (store.profiles[profileName]) {\n store.profiles[profileName].workspaceId = bpCredentials.workspaceId\n if (bpCredentials.botId) {\n store.profiles[profileName].botId = bpCredentials.botId\n }\n await credentialsManager['writeCredentials'](store)\n }\n\n return true\n } catch {\n return false\n }\n }\n}\n\nexport const bpCliImporter = new BpCliImporter()\n",
|
|
16
|
+
"import { Client } from '@botpress/client'\nimport { CredentialsManager, Credentials, Profile } from './credentials.js'\nimport { AuthService } from './service.js'\nimport type { AgentInfo } from '../agent-project/types.js'\nimport { resolveAgent } from '../agent-project/agent-resolver.js'\n\nexport interface LoginOptions {\n profile?: string\n apiUrl?: string\n}\n\nexport interface AuthAPI {\n login(token: string, options?: LoginOptions): Promise<void>\n logout(profile?: string): Promise<void>\n listProfiles(): Promise<Profile[]>\n getCurrentProfile(): Promise<string>\n getCurrentProfileDetails(): Promise<Profile | null>\n setCurrentProfile(profileName: string): Promise<void>\n setProfileOverride(profile: string | undefined): void\n getActiveCredentials(): Promise<Credentials>\n getAgentCredentials(agentPath: string): Promise<Credentials>\n validateToken(token: string, apiUrl?: string): Promise<boolean>\n}\n\nclass Auth implements AuthAPI {\n private credentialsManager: CredentialsManager\n\n constructor() {\n this.credentialsManager = new CredentialsManager()\n }\n\n async login(token: string, options: LoginOptions = {}): Promise<void> {\n const { profile = 'default', apiUrl = 'https://api.botpress.cloud' } = options\n\n // Validate the token first\n const authService = new AuthService(apiUrl)\n const authResult = await authService.validateToken(token)\n\n // Set account preference to indicate ADK CLI is connected (best effort, don't fail login)\n try {\n const client = new Client({ apiUrl, token })\n await client.setAccountPreference({ key: 'adkCliConnected', value: true })\n } catch {\n // Silently ignore - this is a non-critical operation\n }\n\n // Save credentials with user info\n await this.credentialsManager.saveCredentials(\n profile,\n {\n token,\n apiUrl,\n workspaceId: authResult.workspaceId,\n workspaceName: authResult.workspaceName,\n botId: authResult.botId,\n },\n {\n email: authResult.email,\n displayName: authResult.displayName,\n accountId: authResult.accountId,\n createdAt: authResult.createdAt,\n }\n )\n clearProjectClientCache()\n }\n\n async logout(profile?: string): Promise<void> {\n if (profile) {\n await this.credentialsManager.deleteProfile(profile)\n } else {\n // Delete current profile\n const currentProfile = await this.credentialsManager.getCurrentProfile()\n await this.credentialsManager.deleteProfile(currentProfile)\n }\n clearProjectClientCache()\n }\n\n async listProfiles(): Promise<Profile[]> {\n return this.credentialsManager.listProfiles()\n }\n\n async getCurrentProfile(): Promise<string> {\n return this.credentialsManager.getCurrentProfile()\n }\n\n async getCurrentProfileDetails(): Promise<Profile | null> {\n return this.credentialsManager.getCurrentProfileDetails()\n }\n\n async setCurrentProfile(profileName: string): Promise<void> {\n await this.credentialsManager.setCurrentProfile(profileName)\n clearProjectClientCache()\n }\n\n setProfileOverride(profile: string | undefined): void {\n this.credentialsManager.setProfileOverride(profile)\n clearProjectClientCache()\n }\n\n async getActiveCredentials(): Promise<Credentials> {\n return this.credentialsManager.getActiveCredentials()\n }\n\n async getAgentCredentials(agentPath: string): Promise<Credentials> {\n return this.credentialsManager.getAgentCredentials(agentPath)\n }\n\n async validateToken(token: string, apiUrl?: string): Promise<boolean> {\n const authService = new AuthService(apiUrl)\n return authService.testConnection(token)\n }\n}\n\n// Export singleton instance\nexport const auth = new Auth()\n\nexport interface ProjectCredentialsContext {\n path?: string\n agentInfo?: AgentInfo | null\n}\n\nexport interface ResolveProjectCredentialsOptions {\n project?: ProjectCredentialsContext\n credentials?: Credentials\n apiUrl?: string\n workspaceId?: string\n botId?: string\n}\n\nexport type WorkspaceCredentials = Credentials & { workspaceId: string }\nexport type BotCredentials = WorkspaceCredentials & { botId: string }\n\nexport async function resolveProjectCredentials(options: ResolveProjectCredentialsOptions = {}): Promise<Credentials> {\n const { project, credentials: providedCredentials } = options\n\n const agentInfo = project?.agentInfo ?? (project?.path ? await resolveAgent(project.path) : undefined)\n const baseCredentials =\n providedCredentials ||\n (project?.path && agentInfo?.workspaceId\n ? await auth.getAgentCredentials(project.path)\n : await auth.getActiveCredentials())\n const workspaceId = options.workspaceId || agentInfo?.workspaceId || baseCredentials.workspaceId\n const botId = options.botId || agentInfo?.botId || baseCredentials.botId\n\n return {\n ...baseCredentials,\n apiUrl: options.apiUrl || agentInfo?.apiUrl || baseCredentials.apiUrl,\n ...(workspaceId ? { workspaceId } : {}),\n ...(botId ? { botId } : {}),\n }\n}\n\nexport async function resolveWorkspaceCredentials(\n options: ResolveProjectCredentialsOptions = {}\n): Promise<WorkspaceCredentials> {\n const credentials = await resolveProjectCredentials(options)\n\n if (!credentials.workspaceId) {\n throw new Error('No workspace ID found. Please login again with \"adk login\" or link your agent first.')\n }\n\n return {\n ...credentials,\n workspaceId: credentials.workspaceId,\n }\n}\n\nexport async function resolveBotCredentials(options: ResolveProjectCredentialsOptions = {}): Promise<BotCredentials> {\n const credentials = await resolveWorkspaceCredentials(options)\n\n if (!credentials.botId) {\n throw new Error('No bot ID found. Please link your agent first.')\n }\n\n return {\n ...credentials,\n botId: credentials.botId,\n }\n}\n\nexport interface GetProjectClientOptions extends ResolveProjectCredentialsOptions {\n integrationId?: string\n integrationAlias?: string\n headers?: Record<string, string | string[]>\n}\n\nconst projectClientCache = new Map<string, Client>()\nconst MAX_PROJECT_CLIENT_CACHE_ENTRIES = 32\n\nconst stableStringify = (value: unknown): string => {\n if (value === undefined) {\n return 'undefined'\n }\n\n if (!value || typeof value !== 'object') {\n return JSON.stringify(value)!\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`\n }\n\n const record = value as Record<string, unknown>\n return `{${Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(',')}}`\n}\n\nexport async function getProjectClient(options: GetProjectClientOptions = {}): Promise<Client> {\n const credentials = await resolveWorkspaceCredentials(options)\n const botId = options.botId\n const headers = {\n 'x-multiple-integrations': 'true',\n ...(options.headers ?? {}),\n }\n const cacheKey = stableStringify({\n token: credentials.token,\n apiUrl: credentials.apiUrl,\n workspaceId: credentials.workspaceId,\n botId,\n integrationId: options.integrationId,\n integrationAlias: options.integrationAlias,\n headers,\n })\n\n const cached = projectClientCache.get(cacheKey)\n if (cached) {\n projectClientCache.delete(cacheKey)\n projectClientCache.set(cacheKey, cached)\n return cached\n }\n\n const client = new Client({\n token: credentials.token,\n apiUrl: credentials.apiUrl,\n workspaceId: credentials.workspaceId,\n ...(botId ? { botId } : {}),\n ...(options.integrationId ? { integrationId: options.integrationId } : {}),\n ...(options.integrationAlias ? { integrationAlias: options.integrationAlias } : {}),\n headers,\n })\n\n if (projectClientCache.size >= MAX_PROJECT_CLIENT_CACHE_ENTRIES) {\n const oldestKey = projectClientCache.keys().next().value\n if (oldestKey) {\n projectClientCache.delete(oldestKey)\n }\n }\n\n projectClientCache.set(cacheKey, client)\n return client\n}\n\nexport function clearProjectClientCache(): void {\n projectClientCache.clear()\n}\n\n// Export types\nexport type { Credentials, Profile } from './credentials.js'\nexport type { AuthResult } from './service.js'\n\n// Export classes\nexport { CredentialsManager } from './credentials.js'\n\n// Export BP CLI importer\nexport { bpCliImporter } from './bp-cli-import.js'\n",
|
|
17
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { IntegrationDefinition } from './types.js'\n\ninterface VersionResolution {\n integrationId: string\n updatedAt: string\n cachedAt: string\n}\n\ninterface CachedDefinition {\n definition: IntegrationDefinition\n cachedAt: string\n}\n\nexport class EnhancedIntegrationCache {\n private cacheDir: string\n private resolutionsDir: string\n private definitionsDir: string\n private noCache: boolean\n\n constructor(noCache: boolean = false) {\n this.noCache = noCache\n // Global cache in ~/.adk/cache\n this.cacheDir = path.join(os.homedir(), '.adk', 'cache', 'integrations')\n this.resolutionsDir = path.join(this.cacheDir, 'resolutions')\n this.definitionsDir = path.join(this.cacheDir, 'definitions')\n }\n\n private async ensureCacheDirs(): Promise<void> {\n await fs.mkdir(this.resolutionsDir, { recursive: true })\n await fs.mkdir(this.definitionsDir, { recursive: true })\n }\n\n /**\n * Get version resolution from cache (name@version → intver + updatedAt)\n * Returns null if cache miss or expired (5 minutes)\n */\n async getResolution(name: string, version: string, workspace?: string): Promise<VersionResolution | null> {\n if (this.noCache) {\n return null\n }\n\n try {\n const key = this.getResolutionKey(name, version, workspace)\n const cachePath = path.join(this.resolutionsDir, `${key}.json`)\n\n const data = await fs.readFile(cachePath, 'utf-8')\n const resolution: VersionResolution = JSON.parse(data)\n\n // Check if cache is expired (5 minutes)\n const cachedAt = new Date(resolution.cachedAt)\n const now = new Date()\n const ageMinutes = (now.getTime() - cachedAt.getTime()) / (1000 * 60)\n\n if (ageMinutes > 5) {\n // Cache expired\n return null\n }\n\n return resolution\n } catch {\n // Cache miss or error\n return null\n }\n }\n\n /**\n * Cache version resolution (name@version → intver + updatedAt)\n */\n async setResolution(\n name: string,\n version: string,\n workspace: string | undefined,\n integrationId: string,\n updatedAt: string\n ): Promise<void> {\n await this.ensureCacheDirs()\n\n const key = this.getResolutionKey(name, version, workspace)\n const cachePath = path.join(this.resolutionsDir, `${key}.json`)\n\n const resolution: VersionResolution = {\n integrationId,\n updatedAt,\n cachedAt: new Date().toISOString(),\n }\n\n await fs.writeFile(cachePath, JSON.stringify(resolution, null, 2))\n }\n\n /**\n * Get integration definition from cache (intver + updatedAt → definition)\n * Never expires for same intver + updatedAt (immutable)\n */\n async getDefinition(integrationId: string, updatedAt: string): Promise<IntegrationDefinition | null> {\n if (this.noCache) {\n return null\n }\n\n try {\n const key = this.getDefinitionKey(integrationId, updatedAt)\n const cachePath = path.join(this.definitionsDir, `${key}.json`)\n\n const data = await fs.readFile(cachePath, 'utf-8')\n const cached: CachedDefinition = JSON.parse(data)\n\n return cached.definition\n } catch {\n // Cache miss or error\n return null\n }\n }\n\n /**\n * Cache integration definition (intver + updatedAt → definition)\n */\n async setDefinition(integrationId: string, updatedAt: string, definition: IntegrationDefinition): Promise<void> {\n await this.ensureCacheDirs()\n\n const key = this.getDefinitionKey(integrationId, updatedAt)\n const cachePath = path.join(this.definitionsDir, `${key}.json`)\n\n const cached: CachedDefinition = {\n definition,\n cachedAt: new Date().toISOString(),\n }\n\n await fs.writeFile(cachePath, JSON.stringify(cached, null, 2))\n }\n\n /**\n * Clear all caches\n */\n async clear(): Promise<void> {\n try {\n // Clear resolutions\n const resolutionFiles = await fs.readdir(this.resolutionsDir)\n await Promise.all(resolutionFiles.map((file) => fs.unlink(path.join(this.resolutionsDir, file))))\n\n // Clear definitions\n const definitionFiles = await fs.readdir(this.definitionsDir)\n await Promise.all(definitionFiles.map((file) => fs.unlink(path.join(this.definitionsDir, file))))\n } catch {\n // Ignore errors if directories don't exist\n }\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<{\n resolutions: { count: number; sizeBytes: number }\n definitions: { count: number; sizeBytes: number }\n }> {\n const getDirectoryStats = async (dir: string) => {\n try {\n const files = await fs.readdir(dir)\n let totalSize = 0\n\n for (const file of files) {\n const stats = await fs.stat(path.join(dir, file))\n totalSize += stats.size\n }\n\n return {\n count: files.length,\n sizeBytes: totalSize,\n }\n } catch {\n return { count: 0, sizeBytes: 0 }\n }\n }\n\n const [resolutions, definitions] = await Promise.all([\n getDirectoryStats(this.resolutionsDir),\n getDirectoryStats(this.definitionsDir),\n ])\n\n return { resolutions, definitions }\n }\n\n private getResolutionKey(name: string, version: string, workspace?: string): string {\n // Create a safe filesystem key from name@version\n const prefix = workspace ? `${workspace}_` : ''\n const key = `${prefix}${name}_${version}`\n return key.replace(/[^a-zA-Z0-9_-]/g, '_')\n }\n\n private getDefinitionKey(integrationId: string, updatedAt: string): string {\n // Create a safe filesystem key from intver_xxx + updatedAt\n const key = `${integrationId}_${updatedAt}`\n return key.replace(/[^a-zA-Z0-9_-]/g, '_')\n }\n}\n",
|
|
18
|
+
"import { z } from '@botpress/sdk'\nimport { Dependencies } from './types.js'\nimport { IntegrationRef, ParsedIntegration } from '../integrations/types.js'\nimport { PluginRef, ParsedPlugin } from '../plugins/types.js'\nimport { ValidationErrors } from './validation-errors.js'\nimport { ValidationError } from './types.js'\n\n// Integration alias validation constants (matching Botpress API requirements)\nconst INTEGRATION_ALIAS_MIN_LENGTH = 2\nconst INTEGRATION_ALIAS_MAX_LENGTH = 100\n\n// Regex for valid integration alias: lowercase alphanumeric with optional workspace prefix\n// Matches: \"slack\", \"my-slack\", \"slack_prod\", \"workspace/slack\", \"my-workspace/my-integration\"\nconst INTEGRATION_ALIAS_REGEX = /^(?:[a-z][a-z0-9_-]*\\/)?[a-z][a-z0-9_-]*$/\n\n/**\n * Validates an integration alias according to Botpress API requirements\n */\nfunction isIntegrationAliasValid(alias: string): boolean {\n return (\n alias.length >= INTEGRATION_ALIAS_MIN_LENGTH &&\n alias.length <= INTEGRATION_ALIAS_MAX_LENGTH &&\n INTEGRATION_ALIAS_REGEX.test(alias)\n )\n}\n\n// Integration reference schema\nconst integrationRefSchema = z.string().transform((val, ctx) => {\n // Match pattern: [workspace/]name@version\n const match = val.match(/^(?:([^/]+)\\/)?([^@]+)@(.+)$/)\n\n if (!match) {\n ctx.addIssue({\n code: 'custom',\n message: `Invalid integration version format: ${val}. Expected format: 'name@version' or 'workspace/name@version'`,\n })\n return undefined as never\n }\n\n const [, workspace, name, version] = match\n\n return {\n workspace: workspace || undefined,\n name: name!,\n version: version!,\n fullName: workspace ? `${workspace}/${name}` : name!,\n }\n})\n\n// Version validation schema\nconst versionSchema = z.string().refine(\n (version) => {\n if (version === 'latest') return true\n const semverPattern = /^(\\d+)\\.(\\d+)\\.(\\d+)(-[\\w.]+)?(\\+[\\w.]+)?$/\n return semverPattern.test(version)\n },\n { message: \"Version must be exact semver (e.g., 1.2.3) or 'latest'\" }\n)\n\nexport class IntegrationParser {\n /**\n * Parse an integration version string into its components\n * Examples:\n * - \"slack@1.2.0\" -> { name: 'slack', version: '1.2.0', fullName: 'slack' }\n * - \"myworkspace/slack@latest\" -> { workspace: 'myworkspace', name: 'slack', version: 'latest', fullName: 'myworkspace/slack' }\n */\n static parseIntegrationRef(versionString: string): IntegrationRef {\n const result = integrationRefSchema.safeParse(versionString)\n if (!result.success) {\n throw new Error(result.error.errors[0]?.message || 'Invalid integration version format')\n }\n return result.data\n }\n\n /**\n * Parse integrations from dependencies object\n */\n static parseIntegrations(dependencies: Dependencies): {\n integrations: ParsedIntegration[]\n errors: ValidationError[]\n } {\n const integrations: ParsedIntegration[] = []\n const errors: ValidationError[] = []\n\n if (!dependencies.integrations) {\n return { integrations, errors }\n }\n\n for (const [alias, value] of Object.entries(dependencies.integrations)) {\n try {\n // Validate alias format\n if (!isIntegrationAliasValid(alias)) {\n errors.push(ValidationErrors.invalidIntegrationAlias(alias))\n continue // Skip this integration, alias is invalid\n }\n\n // Normalize: string shorthand → object with defaults\n const normalized = typeof value === 'string' ? { version: value } : value\n\n // Parse the integration reference\n const ref = this.parseIntegrationRef(normalized.version)\n\n // Validate version format\n const versionResult = versionSchema.safeParse(ref.version)\n if (!versionResult.success) {\n errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version))\n }\n\n integrations.push({\n alias,\n ref,\n enabled: 'enabled' in normalized ? normalized.enabled : undefined,\n configurationType: 'configurationType' in normalized ? normalized.configurationType : undefined,\n config: 'config' in normalized ? normalized.config : undefined,\n })\n } catch (error) {\n errors.push(\n ValidationErrors.invalidDependenciesSyntax(\n `Invalid integration '${alias}': ${error instanceof Error ? error.message : String(error)}`\n )\n )\n }\n }\n\n return { integrations, errors }\n }\n\n /**\n * Check for duplicate integration names with identical configs (different aliases pointing to same integration)\n */\n static checkDuplicates(integrations: ParsedIntegration[]): ValidationError[] {\n const errors: ValidationError[] = []\n const seen = new Map<string, ParsedIntegration[]>()\n\n for (const integration of integrations) {\n const key = integration.ref.fullName\n const group = seen.get(key) || []\n group.push(integration)\n seen.set(key, group)\n }\n\n // Report duplicates only if they have the same configuration\n for (const [integrationName, group] of seen.entries()) {\n if (group.length > 1) {\n // Check if any two have identical configs\n const duplicateConfigs: string[] = []\n for (let i = 0; i < group.length; i++) {\n for (let j = i + 1; j < group.length; j++) {\n const configA = JSON.stringify(group[i]!.config ?? {})\n const configB = JSON.stringify(group[j]!.config ?? {})\n if (configA === configB) {\n // Add both aliases if not already in the list\n if (!duplicateConfigs.includes(group[i]!.alias)) {\n duplicateConfigs.push(group[i]!.alias)\n }\n if (!duplicateConfigs.includes(group[j]!.alias)) {\n duplicateConfigs.push(group[j]!.alias)\n }\n }\n }\n }\n\n if (duplicateConfigs.length > 0) {\n errors.push(\n ValidationErrors.warning(\n `Integration '${integrationName}' has aliases with identical configurations: ${duplicateConfigs.join(', ')}. Consider using different configs or removing duplicates.`,\n 'agent.config.ts'\n )\n )\n }\n }\n }\n\n return errors\n }\n}\n\n// Plugin alias validation constants\nconst PLUGIN_ALIAS_MIN_LENGTH = 2\nconst PLUGIN_ALIAS_MAX_LENGTH = 100\n\n// Regex for valid plugin alias: lowercase alphanumeric, no workspace prefix\n// Matches: \"hitl\", \"my-plugin\", \"some_plugin\"\nconst PLUGIN_ALIAS_REGEX = /^[a-z][a-z0-9_-]*$/\n\n/**\n * Validates a plugin alias (same rules as integrations, but no workspace prefix allowed)\n */\nfunction isPluginAliasValid(alias: string): boolean {\n return (\n alias.length >= PLUGIN_ALIAS_MIN_LENGTH && alias.length <= PLUGIN_ALIAS_MAX_LENGTH && PLUGIN_ALIAS_REGEX.test(alias)\n )\n}\n\n// Plugin reference schema: name@version only, no workspace prefix\nconst pluginRefSchema = z.string().transform((val, ctx) => {\n // Match pattern: name@version (no workspace prefix allowed)\n const match = val.match(/^([^/@]+)@(.+)$/)\n\n if (!match) {\n ctx.addIssue({\n code: 'custom',\n message: `Invalid plugin version format: ${val}. Expected format: 'name@version' (no workspace prefix)`,\n })\n return undefined as never\n }\n\n const [, name, version] = match\n\n return {\n name: name!,\n version: version!,\n fullName: name!,\n }\n})\n\nexport class PluginParser {\n /**\n * Parse a plugin version string into its components\n * Examples:\n * - \"hitl@1.3.0\" -> { name: 'hitl', version: '1.3.0', fullName: 'hitl' }\n * - \"myworkspace/hitl@1.0.0\" -> error (no workspace prefix)\n */\n static parsePluginRef(versionString: string): PluginRef {\n const result = pluginRefSchema.safeParse(versionString)\n if (!result.success) {\n throw new Error(result.error.errors[0]?.message || 'Invalid plugin version format')\n }\n return result.data\n }\n\n /**\n * Parse plugins from dependencies object\n */\n static parsePlugins(dependencies: Dependencies): {\n plugins: ParsedPlugin[]\n errors: ValidationError[]\n } {\n const plugins: ParsedPlugin[] = []\n const errors: ValidationError[] = []\n\n if (!dependencies.plugins) {\n return { plugins, errors }\n }\n\n for (const [alias, value] of Object.entries(dependencies.plugins)) {\n try {\n if (!isPluginAliasValid(alias)) {\n errors.push(ValidationErrors.invalidPluginAlias(alias))\n continue\n }\n\n const ref = this.parsePluginRef(value.version)\n\n const versionResult = versionSchema.safeParse(ref.version)\n if (!versionResult.success) {\n errors.push(ValidationErrors.invalidPluginVersionFormat(alias, ref.version))\n }\n\n plugins.push({\n alias,\n ref,\n config: value.config,\n dependencies: value.dependencies,\n })\n } catch (error) {\n errors.push(\n ValidationErrors.invalidDependenciesSyntax(\n `Invalid plugin '${alias}': ${error instanceof Error ? error.message : String(error)}`\n )\n )\n }\n }\n\n return { plugins, errors }\n }\n\n /**\n * Validate that plugin dependency integrationAlias values reference integrations\n * that are actually declared in dependencies.integrations\n */\n static validateDependencyReferences(dependencies: Dependencies): ValidationError[] {\n const errors: ValidationError[] = []\n\n if (!dependencies.plugins) {\n return errors\n }\n\n const integrationAliases = Object.keys(dependencies.integrations || {})\n\n for (const [alias, pluginConfig] of Object.entries(dependencies.plugins)) {\n if (!pluginConfig.dependencies) {\n continue\n }\n\n for (const [_depAlias, depMapping] of Object.entries(pluginConfig.dependencies)) {\n if (!integrationAliases.includes(depMapping.integrationAlias)) {\n errors.push(ValidationErrors.invalidPluginDependency(alias, depMapping.integrationAlias, integrationAliases))\n }\n }\n }\n\n return errors\n }\n\n /**\n * Check for duplicate plugin names (different aliases pointing to same plugin)\n */\n static checkDuplicates(plugins: ParsedPlugin[]): ValidationError[] {\n const errors: ValidationError[] = []\n const seen = new Map<string, ParsedPlugin[]>()\n\n for (const plugin of plugins) {\n const key = plugin.ref.fullName\n const group = seen.get(key) || []\n group.push(plugin)\n seen.set(key, group)\n }\n\n for (const [pluginName, group] of seen.entries()) {\n if (group.length > 1) {\n const duplicateConfigs: string[] = []\n for (let i = 0; i < group.length; i++) {\n for (let j = i + 1; j < group.length; j++) {\n const configA = JSON.stringify(group[i]!.config ?? {})\n const configB = JSON.stringify(group[j]!.config ?? {})\n if (configA === configB) {\n if (!duplicateConfigs.includes(group[i]!.alias)) {\n duplicateConfigs.push(group[i]!.alias)\n }\n if (!duplicateConfigs.includes(group[j]!.alias)) {\n duplicateConfigs.push(group[j]!.alias)\n }\n }\n }\n }\n\n if (duplicateConfigs.length > 0) {\n errors.push(\n ValidationErrors.warning(\n `Plugin '${pluginName}' has aliases with identical configurations: ${duplicateConfigs.join(', ')}. Consider using different configs or removing duplicates.`,\n 'agent.config.ts'\n )\n )\n }\n }\n }\n\n return errors\n }\n}\n",
|
|
19
|
+
"import * as semver from 'semver'\n\nexport interface SearchableCatalogEntry {\n name: string\n version: string\n updatedAt?: string\n title?: string\n description?: string\n}\n\nexport interface RankedCatalogEntry<T extends SearchableCatalogEntry> {\n entry: T\n rank: number\n}\n\nexport function collectCatalogSearchResult<T extends SearchableCatalogEntry>(\n results: Map<string, RankedCatalogEntry<T>>,\n entry: T,\n query: string\n): void {\n const rank = getCatalogSearchRank(entry, query)\n if (rank === undefined) {\n return\n }\n\n const key = entry.name.toLowerCase()\n const existing = results.get(key)\n if (!existing || isBetterCatalogResult({ entry, rank }, existing)) {\n results.set(key, { entry, rank })\n }\n}\n\nexport function getSortedCatalogSearchResults<T extends SearchableCatalogEntry>(\n results: Map<string, RankedCatalogEntry<T>>,\n limit: number\n): T[] {\n return [...results.values()]\n .sort(\n (a, b) =>\n a.rank - b.rank || a.entry.name.localeCompare(b.entry.name) || compareVersions(b.entry.version, a.entry.version)\n )\n .slice(0, limit)\n .map(({ entry }) => entry)\n}\n\nexport function getSortedVersions(versions: Iterable<string>): string[] {\n return [...versions].sort((a, b) => compareVersions(b, a))\n}\n\nfunction getCatalogSearchRank(entry: SearchableCatalogEntry, query: string): number | undefined {\n const q = normalize(query)\n if (!q) {\n return 0\n }\n\n const name = normalize(entry.name)\n const title = normalize(entry.title)\n const description = normalize(entry.description)\n\n if (name === q) return 0\n if (title === q) return 1\n if (name.startsWith(q)) return 2\n if (title.startsWith(q)) return 3\n if (name.includes(q)) return 4\n if (title.includes(q)) return 5\n if (description.includes(q)) return 6\n\n return undefined\n}\n\nfunction isBetterCatalogResult<T extends SearchableCatalogEntry>(\n candidate: RankedCatalogEntry<T>,\n existing: RankedCatalogEntry<T>\n): boolean {\n if (candidate.rank !== existing.rank) {\n return candidate.rank < existing.rank\n }\n\n const versionComparison = compareVersions(candidate.entry.version, existing.entry.version)\n if (versionComparison !== 0) {\n return versionComparison > 0\n }\n\n return (candidate.entry.updatedAt ?? '').localeCompare(existing.entry.updatedAt ?? '') > 0\n}\n\nfunction compareVersions(a: string, b: string): number {\n const validA = semver.valid(a)\n const validB = semver.valid(b)\n\n if (validA && validB) {\n return semver.compare(validA, validB)\n }\n\n return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })\n}\n\nfunction normalize(value: string | undefined): string {\n return (value ?? '').trim().toLowerCase()\n}\n",
|
|
20
|
+
"import type { Client } from '@botpress/client'\nimport {\n getProjectClient,\n resolveWorkspaceCredentials,\n type Credentials,\n type ProjectCredentialsContext,\n} from '../auth/index.js'\nimport { Dependencies, ValidationError } from '../agent-project/types.js'\nimport { IntegrationDefinition, ParsedIntegration, IntegrationValidationResult, IntegrationRef } from './types.js'\nimport { EnhancedIntegrationCache } from './enhanced-cache.js'\nimport { IntegrationParser } from '../agent-project/dependencies-parser.js'\nimport { ValidationErrors } from '../agent-project/validation-errors.js'\nimport type { HubCacheEntry } from './hub-cache.js'\nimport {\n collectCatalogSearchResult,\n getSortedCatalogSearchResults,\n getSortedVersions,\n type RankedCatalogEntry,\n} from '../utils/search-ranking.js'\n\nexport interface IntegrationManagerOptions {\n noCache?: boolean\n project?: ProjectCredentialsContext\n apiUrl?: string\n workspaceId?: string\n credentials?: Credentials\n}\n\nexport class IntegrationManager {\n private cache: EnhancedIntegrationCache\n private options: IntegrationManagerOptions\n private client?: Client\n\n constructor(options: IntegrationManagerOptions = {}) {\n this.options = options\n this.cache = new EnhancedIntegrationCache(options.noCache || false)\n }\n\n private async getClient(): Promise<Client> {\n if (!this.client) {\n this.client = await getProjectClient({\n project: this.options.project,\n credentials: this.options.credentials,\n apiUrl: this.options.apiUrl,\n workspaceId: this.options.workspaceId,\n headers: {\n 'x-multiple-integrations': 'true',\n },\n })\n }\n return this.client\n }\n\n /**\n * Load and validate all integrations from dependencies\n */\n async loadIntegrations(dependencies: Dependencies): Promise<{\n integrations: ParsedIntegration[]\n errors: ValidationError[]\n warnings: ValidationError[]\n }> {\n const errors: ValidationError[] = []\n const warnings: ValidationError[] = []\n\n // Parse integrations from dependencies\n const parseResult = IntegrationParser.parseIntegrations(dependencies)\n const integrations = parseResult.integrations\n errors.push(...parseResult.errors)\n\n // Check for duplicates\n const duplicateWarnings = IntegrationParser.checkDuplicates(integrations)\n warnings.push(...duplicateWarnings)\n\n // Fetch integration definitions in parallel\n const fetchPromises = integrations.map(async (integration) => {\n try {\n const definition = await this.fetchIntegration(integration.ref)\n integration.definition = definition\n\n // Validate the integration\n const validation = this.validateIntegration(integration)\n integration.validationResult = validation\n\n if (!validation.valid) {\n validation.errors.forEach(() => {\n errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName))\n })\n }\n\n if (validation.warnings.length > 0) {\n validation.warnings.forEach((warn) => {\n warnings.push(ValidationErrors.warning(warn, 'agent.config.ts'))\n })\n }\n } catch (error) {\n // Use the specific error message if available\n if (error instanceof Error && error.message.includes('version')) {\n // Version-specific error\n errors.push(ValidationErrors.integrationVersionError(integration.alias, error.message))\n } else {\n // Integration not found - use detailed error message if available\n const errorMessage = error instanceof Error ? error.message : undefined\n errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName, errorMessage))\n }\n }\n })\n\n await Promise.all(fetchPromises)\n\n // Check if any integration has channels\n const hasChannels = integrations.some(\n (i) => i.definition?.channels && Object.keys(i.definition.channels).length > 0\n )\n\n if (!hasChannels && integrations.length > 0) {\n warnings.push(\n ValidationErrors.warning(\n 'No integrations with channels found. Your agent may not be able to receive messages.',\n 'agent.config.ts',\n 'Add an integration with channels (e.g., slack, webchat) to enable conversations'\n )\n )\n }\n\n return { integrations, errors, warnings }\n }\n\n /**\n * Fetch integration definition from API or cache\n */\n public async fetchIntegration(ref: IntegrationRef): Promise<IntegrationDefinition> {\n // Level 1: Check version resolution cache (name@version → intver + updatedAt)\n const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace)\n\n if (cachedResolution) {\n // Level 2: Check definition cache (intver + updatedAt → definition)\n const cachedDefinition = await this.cache.getDefinition(\n cachedResolution.integrationId,\n cachedResolution.updatedAt\n )\n\n if (cachedDefinition) {\n return cachedDefinition\n }\n }\n\n // No cache hit, fetch from API\n const client = await this.getClient()\n\n // Try to find the integration (private first, then public)\n const integration = await this._findPrivateOrPublicIntegration(client, ref)\n if (!integration) {\n throw await this._buildIntegrationNotFoundError(client, ref)\n }\n\n // Cache Level 1: Version resolution (name@version → intver + updatedAt)\n await this.cache.setResolution(ref.name, ref.version, ref.workspace, integration.id, integration.updatedAt)\n\n // Cache Level 2: Definition (intver + updatedAt → definition)\n const definition: IntegrationDefinition = integration\n await this.cache.setDefinition(integration.id, integration.updatedAt, definition)\n\n return definition\n }\n\n /**\n * Search public integrations in the Botpress hub.\n */\n public async searchIntegrations(query: string, limit: number = 20): Promise<HubCacheEntry[]> {\n const client = await this.getClient()\n const results = new Map<string, RankedCatalogEntry<HubCacheEntry>>()\n const scanLimit = Math.max(limit * 5, 50)\n\n for await (const integration of client.list.publicIntegrations({\n name: query,\n sortBy: 'updatedAt',\n direction: 'desc',\n })) {\n collectCatalogSearchResult(results, toHubCacheEntry(integration), query)\n }\n\n let scanned = 0\n for await (const integration of client.list.publicIntegrations({\n search: query,\n sortBy: 'popularity',\n direction: 'desc',\n limit: scanLimit,\n })) {\n collectCatalogSearchResult(results, toHubCacheEntry(integration), query)\n scanned += 1\n if (scanned >= scanLimit) break\n }\n\n return getSortedCatalogSearchResults(results, limit)\n }\n\n /**\n * Find public integrations that implement a given interface (by interface name).\n * Returns the latest version per integration name, ranked by Cloud's popularity.\n */\n public async findImplementersOfInterface(interfaceName: string, limit: number = 10): Promise<HubCacheEntry[]> {\n const client = await this.getClient()\n const seen = new Map<string, HubCacheEntry>()\n for await (const integration of client.list.publicIntegrations({\n interfaceName,\n sortBy: 'popularity',\n direction: 'desc',\n limit,\n })) {\n const entry = toHubCacheEntry(integration)\n if (!seen.has(entry.name)) seen.set(entry.name, entry)\n if (seen.size >= limit) break\n }\n return [...seen.values()]\n }\n\n /**\n * List known public versions for an integration name.\n */\n public async listIntegrationVersions(name: string): Promise<string[]> {\n const client = await this.getClient()\n const versions = new Set<string>()\n\n for await (const integration of client.list.publicIntegrations({\n name,\n sortBy: 'updatedAt',\n direction: 'desc',\n })) {\n versions.add(integration.version)\n }\n\n return getSortedVersions(versions)\n }\n\n /**\n * Find integration in private workspace first, then public hub\n * Similar to ApiClient.findPublicOrPrivateIntegration from @botpress/cli\n */\n private async _findPrivateOrPublicIntegration(\n client: Client,\n ref: IntegrationRef\n ): Promise<IntegrationDefinition | undefined> {\n // Try private/workspace integration first\n const privateIntegration = await this._findPrivateIntegration(client, ref)\n if (privateIntegration) {\n return privateIntegration\n }\n\n // Try public integration\n const publicIntegration = await this._findPublicIntegration(client, ref)\n if (publicIntegration) {\n return publicIntegration\n }\n\n return undefined\n }\n\n /**\n * Find private/workspace integration\n */\n private async _findPrivateIntegration(\n client: Client,\n ref: IntegrationRef\n ): Promise<IntegrationDefinition | undefined> {\n try {\n // For workspace integrations, always use \"latest\" as they don't support version pinning\n const version = ref.workspace && ref.version !== 'latest' ? 'latest' : ref.version\n\n const response = await client.getIntegrationByName({\n name: ref.fullName,\n version,\n })\n return response.integration\n } catch (error) {\n // Return undefined on ResourceNotFound, throw on other errors\n if (this._isResourceNotFoundError(error)) {\n return undefined\n }\n throw error\n }\n }\n\n /**\n * Find public integration\n */\n private async _findPublicIntegration(\n client: Client,\n ref: IntegrationRef\n ): Promise<IntegrationDefinition | undefined> {\n try {\n const response = await client.getPublicIntegration({\n name: ref.fullName,\n version: ref.version,\n })\n return response.integration\n } catch (error) {\n // Return undefined on ResourceNotFound, throw on other errors\n if (this._isResourceNotFoundError(error)) {\n return undefined\n }\n throw error\n }\n }\n\n /**\n * Check if error is a ResourceNotFound error\n */\n private _isResourceNotFoundError(error: unknown): boolean {\n if (error && typeof error === 'object' && 'type' in error) {\n return (error as { type: unknown }).type === 'ResourceNotFound'\n }\n return false\n }\n\n /**\n * Build a helpful error message when integration is not found\n */\n private async _buildIntegrationNotFoundError(client: Client, ref: IntegrationRef): Promise<Error> {\n // If a specific version was requested, retry with 'latest' to disambiguate\n // \"integration doesn't exist\" from \"this version doesn't exist\".\n if (ref.version !== 'latest') {\n const latestExists = await this._findPrivateOrPublicIntegration(client, { ...ref, version: 'latest' })\n if (latestExists) {\n const scope = ref.workspace ? `workspace \"${ref.workspace}\"` : 'the official Botpress hub'\n return new Error(\n `Integration \"${ref.name}\" version \"${ref.version}\" not found in ${scope} ` +\n `(latest is ${latestExists.version}). Run 'adk info ${ref.fullName}' to see available versions.`\n )\n }\n }\n\n // If no workspace prefix, simple error\n if (!ref.workspace) {\n return new Error(`Integration \"${ref.name}\" not found in the official Botpress hub`)\n }\n\n // Get current workspace info to compare handles\n let currentWorkspaceHandle: string | undefined\n let workspaceId: string | undefined\n try {\n const credentials = await resolveWorkspaceCredentials({\n project: this.options.project,\n credentials: this.options.credentials,\n apiUrl: this.options.apiUrl,\n workspaceId: this.options.workspaceId,\n })\n workspaceId = credentials.workspaceId\n\n if (workspaceId) {\n // List workspaces to find current workspace and get its handle\n const currentWorkspace = await client.getWorkspace({ id: workspaceId })\n currentWorkspaceHandle = currentWorkspace?.handle\n }\n } catch {\n // If we can't get workspace info, use generic error\n return new Error(`Integration \"${ref.name}\" not found in workspace \"${ref.workspace}\"`)\n }\n\n // Case 1: Trying to install from the same workspace\n if (currentWorkspaceHandle === ref.workspace) {\n return new Error(\n `Integration \"${ref.name}\" not found in workspace \"${ref.workspace}\" (workspaceId: ${workspaceId}). ` +\n `Are you sure you published the integration? ` +\n `Run 'adk deploy' to publish it to your workspace.`\n )\n }\n\n // Case 2: Trying to install from a different workspace (likely private)\n return new Error(\n `Integration \"${ref.name}\" not found in workspace \"${ref.workspace}\" (current workspaceId: ${workspaceId}). ` +\n `This integration may be private. Private integrations can only be installed in the same workspace. ` +\n `If you want to share this integration with other workspaces, deploy it with --visibility=\"unlisted\" or --visibility=\"public\".`\n )\n }\n\n /**\n * Validate an integration definition\n */\n private validateIntegration(integration: ParsedIntegration): IntegrationValidationResult {\n const errors: string[] = []\n const warnings: string[] = []\n\n if (!integration.definition) {\n errors.push(`Integration definition not found for ${integration.alias}`)\n return { valid: false, errors, warnings }\n }\n\n // Check if integration has channels\n const hasChannels = integration.definition.channels && Object.keys(integration.definition.channels).length > 0\n\n // Check if integration requires configuration (only for object-format integrations with explicit enabled)\n if (!integration.config && integration.enabled !== undefined) {\n let requiresConfig = false\n\n // Check modern configurations (plural)\n if (integration.definition.configurations) {\n requiresConfig = Object.values(integration.definition.configurations).some(\n (config) => config.identifier?.required === true\n )\n }\n\n // Check legacy configuration (singular) - if it has required fields in schema\n if (!requiresConfig && integration.definition.configuration) {\n const config = integration.definition.configuration\n const schema = config.schema\n requiresConfig = schema?.required && schema.required.length > 0\n }\n\n if (requiresConfig) {\n warnings.push(\n `Integration '${integration.alias}' requires configuration. Add a config object in agent.config.ts dependencies`\n )\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n missingChannels: !hasChannels,\n }\n }\n\n /**\n * Get cache statistics\n */\n async getCacheStats(): Promise<{ count: number; sizeBytes: number }> {\n const stats = await this.cache.getStats()\n // Combine resolution and definition cache stats\n return {\n count: stats.resolutions.count + stats.definitions.count,\n sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes,\n }\n }\n\n /**\n * Clear integration cache\n */\n async clearCache(): Promise<void> {\n await this.cache.clear()\n }\n}\n\nfunction toHubCacheEntry(integration: {\n id: string\n name: string\n version: string\n updatedAt: string\n createdAt: string\n title?: string\n description?: string\n iconUrl?: string\n public: boolean\n visibility: 'public' | 'private' | 'unlisted'\n ownerWorkspace?: { id: string; name: string }\n verificationStatus?: 'unapproved' | 'approved' | 'pending' | 'rejected'\n}): HubCacheEntry {\n return {\n id: integration.id,\n name: integration.name,\n version: integration.version,\n updatedAt: integration.updatedAt,\n createdAt: integration.createdAt,\n title: integration.title,\n description: integration.description,\n iconUrl: integration.iconUrl,\n public: integration.public,\n visibility: integration.visibility,\n ownerWorkspace: integration.ownerWorkspace\n ? { id: integration.ownerWorkspace.id, name: integration.ownerWorkspace.name }\n : undefined,\n verificationStatus: integration.verificationStatus,\n }\n}\n",
|
|
21
|
+
"export const defaultAdkFolder = '.adk'\n//\n",
|
|
22
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport { AssetFile } from './types.js'\nimport { defaultAdkFolder } from '../const.js'\n\nexport interface AssetsCacheEntry {\n path: string\n localHash: string\n remoteHash: string\n metadata: AssetFile\n lastUpdated: string\n}\n\nexport interface AssetsCache {\n version: string\n entries: Record<string, AssetsCacheEntry>\n}\n\nexport class AssetsCacheManager {\n private cachePath: string\n private cache: AssetsCache | null = null\n\n constructor(private projectPath: string) {\n this.cachePath = path.join(projectPath, defaultAdkFolder, 'assets-cache.json')\n }\n\n async load(): Promise<AssetsCache> {\n if (this.cache) {\n return this.cache\n }\n\n try {\n const content = await fs.readFile(this.cachePath, 'utf-8')\n this.cache = JSON.parse(content)\n return this.cache!\n } catch {\n // Cache doesn't exist or is invalid, create new one\n this.cache = {\n version: '1.0',\n entries: {},\n }\n return this.cache\n }\n }\n\n async save(): Promise<void> {\n if (!this.cache) {\n return\n }\n\n const cacheDir = path.dirname(this.cachePath)\n await fs.mkdir(cacheDir, { recursive: true })\n await fs.writeFile(this.cachePath, JSON.stringify(this.cache, null, 2), 'utf-8')\n }\n\n async getEntry(assetPath: string): Promise<AssetsCacheEntry | null> {\n const cache = await this.load()\n return cache.entries[assetPath] || null\n }\n\n async setEntry(assetPath: string, localHash: string, remoteHash: string, metadata: AssetFile): Promise<void> {\n const cache = await this.load()\n cache.entries[assetPath] = {\n path: assetPath,\n localHash,\n remoteHash,\n metadata,\n lastUpdated: new Date().toISOString(),\n }\n await this.save()\n }\n\n async isStale(assetPath: string): Promise<boolean> {\n const entry = await this.getEntry(assetPath)\n if (!entry) return false\n return entry.localHash !== entry.remoteHash\n }\n\n async removeEntry(assetPath: string): Promise<void> {\n const cache = await this.load()\n delete cache.entries[assetPath]\n await this.save()\n }\n\n async clear(): Promise<void> {\n this.cache = {\n version: '1.0',\n entries: {},\n }\n await this.save()\n }\n\n async getAllEntries(): Promise<AssetsCacheEntry[]> {\n const cache = await this.load()\n return Object.values(cache.entries)\n }\n}\n",
|
|
23
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport crypto from 'crypto'\nimport type { Client } from '@botpress/client'\nimport { getProjectClient } from '../auth/index.js'\nimport {\n AssetFile,\n LocalAssetFile,\n AssetSyncPlan,\n AssetSyncResult,\n AssetSyncItem,\n AssetSyncOperation,\n AssetSyncOptions,\n AssetsIndex,\n} from './types.js'\nimport { AssetsCacheManager } from './cache.js'\n\nexport interface AssetManagerOptions {\n projectPath: string\n botId?: string\n}\n\nexport class AssetsManager {\n private projectPath: string\n private assetsPath: string\n private client?: Client\n private botId?: string\n private cacheManager: AssetsCacheManager\n\n constructor(options: AssetManagerOptions) {\n this.projectPath = options.projectPath\n this.assetsPath = path.join(this.projectPath, 'assets')\n this.botId = options.botId\n this.cacheManager = new AssetsCacheManager(this.projectPath)\n }\n\n private async getClient(): Promise<Client> {\n if (!this.client) {\n if (!this.botId) {\n throw new Error(\n 'Bot ID is required for asset operations. Please deploy your agent first or create agent.json with botId and workspaceId.'\n )\n }\n\n this.client = await getProjectClient({\n project: { path: this.projectPath },\n botId: this.botId,\n headers: {\n 'x-multiple-integrations': 'true',\n },\n })\n }\n return this.client\n }\n\n private assertBotId(operation: string): void {\n if (!this.botId) {\n throw new Error(\n `Operation \"${operation}\" requires a bot ID. ` +\n 'Please deploy your agent first or create agent.json with botId and workspaceId.'\n )\n }\n }\n\n /**\n * Check if assets directory exists\n */\n async hasAssetsDirectory(): Promise<boolean> {\n try {\n const stats = await fs.stat(this.assetsPath)\n return stats.isDirectory()\n } catch {\n return false\n }\n }\n\n /**\n * Get all local asset files with their metadata\n */\n async getLocalAssets(): Promise<LocalAssetFile[]> {\n if (!(await this.hasAssetsDirectory())) {\n return []\n }\n\n const files = await this.scanDirectory(this.assetsPath)\n const assets: LocalAssetFile[] = []\n\n for (const filePath of files) {\n try {\n const stats = await fs.stat(filePath)\n if (stats.isFile()) {\n const relativePath = path.relative(this.assetsPath, filePath)\n const content = await fs.readFile(filePath)\n const hash = this.calculateHash(content)\n const mime = this.getMimeType(filePath)\n\n assets.push({\n relativePath,\n absolutePath: filePath,\n name: path.basename(filePath),\n size: stats.size,\n mime,\n hash,\n stats: {\n mtime: stats.mtime,\n size: stats.size,\n },\n })\n }\n } catch (error) {\n // Skip files that can't be read\n console.warn(`Warning: Could not read asset file ${filePath}:`, error)\n }\n }\n\n return assets\n }\n\n /**\n * Get all remote asset files from Botpress\n */\n async getRemoteAssets(): Promise<AssetFile[]> {\n this.assertBotId('get remote assets')\n\n const client = await this.getClient()\n\n try {\n // List files with ADK asset tags (botId is automatically scoped by client)\n const response = await client.listFiles({\n tags: {\n type: 'asset',\n adk: 'true',\n },\n })\n\n return response.files.map((file) => ({\n path: file.tags?.path || file.key,\n name: path.basename(file.tags?.path || file.key),\n size: file.size || 0,\n mime: file.contentType,\n hash: file.tags?.hash || '',\n createdAt: file.createdAt,\n updatedAt: file.updatedAt,\n fileId: file.id,\n url: file.url || '',\n }))\n } catch (error) {\n throw new Error(`Failed to fetch remote assets: ${error}`)\n }\n }\n\n /**\n * Create a sync plan comparing local and remote assets\n */\n async createSyncPlan(): Promise<AssetSyncPlan> {\n const [localAssets, remoteAssets] = await Promise.all([this.getLocalAssets(), this.getRemoteAssets()])\n\n const items: AssetSyncItem[] = []\n const remoteMap = new Map<string, AssetFile>()\n\n // Map remote assets by path\n for (const remote of remoteAssets) {\n remoteMap.set(remote.path, remote)\n }\n\n // Check local files against remote\n for (const local of localAssets) {\n const remote = remoteMap.get(local.relativePath)\n\n if (!remote) {\n // Local file doesn't exist remotely - needs to be created\n items.push({\n operation: AssetSyncOperation.Create,\n localFile: local,\n reason: 'New local file',\n })\n } else if (local.hash !== remote.hash) {\n // File exists but content is different - needs to be updated\n items.push({\n operation: AssetSyncOperation.Update,\n localFile: local,\n remoteFile: remote,\n reason: 'Content changed',\n })\n } else {\n // Files are identical - no operation needed\n items.push({\n operation: AssetSyncOperation.None,\n localFile: local,\n remoteFile: remote,\n reason: 'Up to date',\n })\n }\n\n // Remove from remote map so we can find orphaned remote files\n remoteMap.delete(local.relativePath)\n }\n\n // Remaining remote files don't have local counterparts - need to be deleted\n for (const [, remote] of remoteMap) {\n items.push({\n operation: AssetSyncOperation.Delete,\n remoteFile: remote,\n reason: 'Local file deleted',\n })\n }\n\n // Calculate totals\n const totalCreate = items.filter((i) => i.operation === AssetSyncOperation.Create).length\n const totalUpdate = items.filter((i) => i.operation === AssetSyncOperation.Update).length\n const totalDelete = items.filter((i) => i.operation === AssetSyncOperation.Delete).length\n const hasChanges = totalCreate > 0 || totalUpdate > 0 || totalDelete > 0\n\n return {\n items,\n totalCreate,\n totalUpdate,\n totalDelete,\n hasChanges,\n }\n }\n\n /**\n * Execute a sync plan\n */\n async executeSync(plan: AssetSyncPlan, options: AssetSyncOptions = {}): Promise<AssetSyncResult> {\n this.assertBotId('sync assets')\n\n if (options.dryRun) {\n return {\n applied: false,\n success: [],\n skipped: [],\n failed: [],\n summary: {\n created: 0,\n updated: 0,\n deleted: 0,\n skipped: 0,\n failed: 0,\n },\n }\n }\n\n const client = await this.getClient()\n const success: AssetSyncItem[] = []\n const skipped: AssetSyncItem[] = []\n const failed: Array<{ item: AssetSyncItem; error: Error }> = []\n\n for (const item of plan.items) {\n if (item.operation === AssetSyncOperation.None) {\n success.push(item)\n continue\n }\n\n try {\n switch (item.operation) {\n case AssetSyncOperation.Create:\n case AssetSyncOperation.Update:\n if (item.localFile) {\n await this.uploadAsset(client, item.localFile)\n success.push(item)\n }\n break\n\n case AssetSyncOperation.Delete:\n if (item.remoteFile?.fileId) {\n if (!options.confirmDestructive) {\n skipped.push(item)\n continue\n }\n await client.deleteFile({ id: item.remoteFile.fileId })\n success.push(item)\n }\n break\n }\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error))\n failed.push({ item, error: err })\n\n if (options.bailOnFailure) {\n break\n }\n }\n }\n\n return {\n applied: true,\n success,\n skipped,\n failed,\n summary: {\n created: success.filter((i) => i.operation === AssetSyncOperation.Create).length,\n updated: success.filter((i) => i.operation === AssetSyncOperation.Update).length,\n deleted: success.filter((i) => i.operation === AssetSyncOperation.Delete).length,\n skipped: skipped.length,\n failed: failed.length,\n },\n }\n }\n\n /**\n * Upload a local asset to Botpress\n */\n private async uploadAsset(client: Client, localFile: LocalAssetFile): Promise<void> {\n const content = await fs.readFile(localFile.absolutePath)\n\n await client.uploadFile({\n key: localFile.relativePath,\n content,\n contentType: localFile.mime,\n tags: {\n type: 'asset',\n adk: 'true',\n path: localFile.relativePath,\n hash: localFile.hash,\n name: localFile.name,\n size: localFile.size.toString(),\n },\n index: false, // Assets are static files, not knowledge — never index\n })\n }\n\n /**\n * Generate TypeScript types for assets\n */\n async generateTypes(): Promise<string> {\n const localAssets = await this.getLocalAssets()\n\n // Generate union type of all asset paths\n const pathUnion = localAssets.map((asset) => `\"${asset.relativePath}\"`).join(' | ')\n\n const paths = localAssets.map((asset) => ` \"${asset.relativePath}\": \"${asset.relativePath}\";`).join('\\n')\n\n return `// Auto-generated asset types\nimport { Asset } from '@botpress/runtime';\n\nexport type AssetPaths = ${pathUnion || 'never'};\n\nexport interface AssetPathMap {\n${paths}\n}\n\n// Runtime asset access\ndeclare global {\n const assets: {\n get<T extends AssetPaths>(path: T): Promise<Asset>;\n list(): Asset[];\n getSyncStatus(): {\n synced: boolean;\n neverSynced: string[];\n stale: string[];\n upToDate: string[];\n };\n };\n}\n`\n }\n\n /**\n * Create an assets index file\n */\n async createAssetsIndex(): Promise<AssetsIndex> {\n const remoteAssets = await this.getRemoteAssets()\n\n return {\n files: remoteAssets,\n generatedAt: new Date().toISOString(),\n totalFiles: remoteAssets.length,\n totalSize: remoteAssets.reduce((sum, asset) => sum + asset.size, 0),\n }\n }\n\n /**\n * Get enriched local assets with remote metadata when available\n * Uses cache to avoid unnecessary API calls\n */\n async getEnrichedLocalAssets(): Promise<AssetFile[]> {\n const localAssets = await this.getLocalAssets()\n const enrichedAssets: AssetFile[] = []\n\n // Try to get client if credentials are available\n let remoteAssetsMap: Map<string, AssetFile> = new Map()\n try {\n if (this.botId) {\n const remoteAssets = await this.getRemoteAssets()\n remoteAssetsMap = new Map(remoteAssets.map((asset) => [asset.path, asset]))\n }\n } catch (error) {\n // If we can't fetch remote assets, we'll use cache or placeholders\n console.debug('Could not fetch remote assets:', error)\n }\n\n for (const localAsset of localAssets) {\n const cachedEntry = await this.cacheManager.getEntry(localAsset.relativePath)\n const remoteAsset = remoteAssetsMap.get(localAsset.relativePath)\n\n if (cachedEntry) {\n // We have cached metadata - use it and update the cache with current hashes\n enrichedAssets.push(cachedEntry.metadata)\n await this.cacheManager.setEntry(\n localAsset.relativePath,\n localAsset.hash,\n cachedEntry.remoteHash,\n cachedEntry.metadata\n )\n } else if (remoteAsset) {\n // No cache but we have remote - use remote and cache it\n enrichedAssets.push(remoteAsset)\n await this.cacheManager.setEntry(localAsset.relativePath, localAsset.hash, remoteAsset.hash, remoteAsset)\n } else {\n // No cache and no remote - create placeholder\n const placeholderAsset: AssetFile = {\n url: `__PLACEHOLDER_URL_${localAsset.relativePath}__`,\n path: localAsset.relativePath,\n size: localAsset.size,\n name: localAsset.name,\n mime: localAsset.mime,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n fileId: `__PLACEHOLDER_ID_${localAsset.relativePath}__`,\n hash: localAsset.hash,\n }\n enrichedAssets.push(placeholderAsset)\n }\n }\n\n return enrichedAssets\n }\n\n // Private utility methods\n\n private async scanDirectory(dir: string, files: string[] = []): Promise<string[]> {\n const items = await fs.readdir(dir)\n\n for (const item of items) {\n const fullPath = path.join(dir, item)\n const stats = await fs.stat(fullPath)\n\n if (stats.isDirectory()) {\n await this.scanDirectory(fullPath, files)\n } else {\n files.push(fullPath)\n }\n }\n\n return files\n }\n\n private calculateHash(content: Buffer): string {\n return crypto.createHash('sha256').update(content).digest('hex')\n }\n\n private getMimeType(filePath: string): string {\n const ext = path.extname(filePath).toLowerCase()\n\n const mimeTypes: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.webp': 'image/webp',\n '.pdf': 'application/pdf',\n '.txt': 'text/plain',\n '.md': 'text/markdown',\n '.html': 'text/html',\n '.css': 'text/css',\n '.js': 'application/javascript',\n '.json': 'application/json',\n '.xml': 'application/xml',\n '.zip': 'application/zip',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n }\n\n return mimeTypes[ext] || 'application/octet-stream'\n }\n}\n",
|
|
24
|
+
"import { mkdir, writeFile } from 'fs/promises'\nimport { parse } from 'path'\n\nexport const createFile = async (path: string, content: string) => {\n const file = parse(path)\n await mkdir(file.dir, { recursive: true })\n await writeFile(path, content)\n}\n",
|
|
25
|
+
"import path from 'path'\nimport { createFile } from '../utils/fs.js'\nimport { defaultAdkFolder } from '../const.js'\nimport { AssetFile } from './types.js'\n\n/**\n * Updates the assets runtime file with actual deployed metadata\n * This is called after assets are uploaded to Botpress\n */\nexport async function updateAssetsRuntime(projectPath: string, deployedAssets: AssetFile[]): Promise<void> {\n // Create a map of deployed assets by path\n const assetsMap: Record<string, AssetFile> = {}\n for (const asset of deployedAssets) {\n assetsMap[asset.path] = asset\n }\n\n // Generate the updated runtime code with real metadata\n const runtimeCode = `\n// Auto-generated assets metadata\nimport { Asset, initAssets } from '@botpress/runtime/runtime';\n\n// Static asset metadata (populated at deploy time)\nexport const assetsMetadata: Record<string, Asset> = ${JSON.stringify(assetsMap, null, 2)};\n\n// Initialize the assets runtime with metadata\n// The global object should be passed by the agent initialization code\nexport function initializeAssets(globalObj: any = globalThis) {\n initAssets(globalObj, assetsMetadata);\n}\n\n// Auto-initialize if running in a supported environment\nif (typeof globalThis !== 'undefined') {\n initializeAssets(globalThis);\n} else if (typeof global !== 'undefined') {\n initializeAssets(global);\n}\n`\n\n const runtimePath = path.join(projectPath, defaultAdkFolder, 'assets-runtime.ts')\n await createFile(runtimePath, runtimeCode)\n}\n",
|
|
26
|
+
"export * from './types.js'\nexport * from './manager.js'\nexport * from './updater.js'\nexport * from './cache.js'\n",
|
|
27
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { IntegrationDefinition, CachedIntegration } from './types.js'\n\nexport class IntegrationCache {\n private cacheDir: string\n private integrationsDir: string\n\n constructor() {\n // Global cache in ~/.adk/cache\n this.cacheDir = path.join(os.homedir(), '.adk', 'cache')\n this.integrationsDir = path.join(this.cacheDir, 'integrations')\n }\n\n private async ensureCacheDir(): Promise<void> {\n await fs.mkdir(this.integrationsDir, { recursive: true })\n }\n\n private getCacheKey(integrationId: string, updatedAt: string): string {\n // Cache key format: integrationId@updatedAt\n // Remove any special characters that might cause filesystem issues\n const sanitizedId = integrationId.replace(/[^a-zA-Z0-9_-]/g, '_')\n const sanitizedDate = updatedAt.replace(/[^a-zA-Z0-9_-]/g, '_')\n return `${sanitizedId}@${sanitizedDate}.json`\n }\n\n async get(integrationId: string, updatedAt: string): Promise<IntegrationDefinition | null> {\n try {\n const cacheKey = this.getCacheKey(integrationId, updatedAt)\n const cachePath = path.join(this.integrationsDir, cacheKey)\n\n const data = await fs.readFile(cachePath, 'utf-8')\n const cached: CachedIntegration = JSON.parse(data)\n\n // Check if cache is expired\n if (cached.expiresAt) {\n const expiryDate = new Date(cached.expiresAt)\n if (expiryDate < new Date()) {\n // Cache expired, remove it\n await this.remove(integrationId, updatedAt)\n return null\n }\n }\n\n return cached.definition\n } catch {\n // Cache miss or error\n return null\n }\n }\n\n async set(\n integrationId: string,\n updatedAt: string,\n definition: IntegrationDefinition,\n ttlHours: number = 24 * 7 // Default 1 week\n ): Promise<void> {\n await this.ensureCacheDir()\n\n const cacheKey = this.getCacheKey(integrationId, updatedAt)\n const cachePath = path.join(this.integrationsDir, cacheKey)\n\n const expiresAt = new Date()\n expiresAt.setHours(expiresAt.getHours() + ttlHours)\n\n const cacheEntry: CachedIntegration = {\n definition,\n cachedAt: new Date().toISOString(),\n expiresAt: expiresAt.toISOString(),\n }\n\n await fs.writeFile(cachePath, JSON.stringify(cacheEntry, null, 2))\n }\n\n async remove(integrationId: string, updatedAt: string): Promise<void> {\n try {\n const cacheKey = this.getCacheKey(integrationId, updatedAt)\n const cachePath = path.join(this.integrationsDir, cacheKey)\n await fs.unlink(cachePath)\n } catch {\n // Ignore errors if file doesn't exist\n }\n }\n\n async clear(): Promise<void> {\n try {\n const files = await fs.readdir(this.integrationsDir)\n await Promise.all(files.map((file) => fs.unlink(path.join(this.integrationsDir, file))))\n } catch {\n // Ignore errors if directory doesn't exist\n }\n }\n\n async getStats(): Promise<{ count: number; sizeBytes: number }> {\n try {\n const files = await fs.readdir(this.integrationsDir)\n let totalSize = 0\n\n for (const file of files) {\n const stats = await fs.stat(path.join(this.integrationsDir, file))\n totalSize += stats.size\n }\n\n return {\n count: files.length,\n sizeBytes: totalSize,\n }\n } catch {\n return { count: 0, sizeBytes: 0 }\n }\n }\n}\n",
|
|
28
|
+
"import { Client } from '@botpress/client'\nimport * as fs from 'fs/promises'\nimport * as path from 'path'\nimport * as os from 'os'\nimport { auth } from '../auth/index.js'\n\nexport interface HubCacheEntry {\n id: string\n name: string\n version: string\n updatedAt: string\n createdAt: string\n title?: string\n description?: string\n iconUrl?: string\n public: boolean\n visibility: 'public' | 'private' | 'unlisted'\n ownerWorkspace?: {\n id: string\n name: string\n }\n verificationStatus?: 'unapproved' | 'approved' | 'pending' | 'rejected'\n}\n\nexport interface HubCacheData {\n lastUpdated: string\n integrations: HubCacheEntry[]\n}\n\nexport class HubCache {\n private static readonly CACHE_FILE = 'botpress-hub-cache.json'\n private static readonly CACHE_DIR = path.join(os.homedir(), '.adk', 'cache')\n private static readonly CACHE_PATH = path.join(HubCache.CACHE_DIR, HubCache.CACHE_FILE)\n private static readonly CACHE_DURATION = 30 * 60 * 1000 // 30 minutes in milliseconds\n\n private client?: Client\n\n constructor() {}\n\n private async getClient(): Promise<Client> {\n if (!this.client) {\n const credentials = await auth.getActiveCredentials()\n\n if (!credentials.workspaceId) {\n throw new Error('No workspace ID found in current profile. Please login again with \"adk login\"')\n }\n\n this.client = new Client({\n token: credentials.token,\n apiUrl: credentials.apiUrl,\n workspaceId: credentials.workspaceId,\n headers: {\n 'x-multiple-integrations': 'true',\n },\n })\n }\n return this.client\n }\n\n /**\n * Ensure cache directory exists\n */\n private async ensureCacheDir(): Promise<void> {\n try {\n await fs.mkdir(HubCache.CACHE_DIR, { recursive: true })\n } catch {\n // Directory might already exist, that's fine\n }\n }\n\n /**\n * Load cache from disk\n */\n private async loadCache(): Promise<HubCacheData | null> {\n try {\n const data = await fs.readFile(HubCache.CACHE_PATH, 'utf-8')\n return JSON.parse(data) as HubCacheData\n } catch {\n return null\n }\n }\n\n /**\n * Save cache to disk\n */\n private async saveCache(data: HubCacheData): Promise<void> {\n await this.ensureCacheDir()\n await fs.writeFile(HubCache.CACHE_PATH, JSON.stringify(data, null, 2))\n }\n\n /**\n * Check if cache needs refresh\n */\n private async needsRefresh(): Promise<boolean> {\n const cache = await this.loadCache()\n if (!cache) return true\n\n const lastUpdated = new Date(cache.lastUpdated)\n const now = new Date()\n const diff = now.getTime() - lastUpdated.getTime()\n\n return diff > HubCache.CACHE_DURATION\n }\n\n /**\n * Refresh the hub cache\n */\n async refresh(force: boolean = false): Promise<void> {\n // Check if refresh is needed\n if (!force && !(await this.needsRefresh())) {\n return\n }\n\n const client = await this.getClient()\n const cache = await this.loadCache()\n const latestByName = new Map<string, HubCacheEntry>()\n\n // Load existing cache into map (keyed by name for latest version tracking)\n if (cache) {\n for (const entry of cache.integrations) {\n latestByName.set(entry.name, entry)\n }\n }\n\n try {\n // Fetch integrations sorted by updatedAt descending\n for await (const integration of client.list.publicIntegrations({\n sortBy: 'updatedAt',\n direction: 'desc',\n })) {\n // Check if we have a newer version of this integration\n const existing = latestByName.get(integration.name)\n\n // If we've reached an integration with the same id and updatedAt we already have, stop\n if (existing && integration.id === existing.id && integration.updatedAt === existing.updatedAt) {\n break\n }\n\n if (\n !existing ||\n integration.version.localeCompare(existing.version, undefined, {\n numeric: true,\n }) > 0\n ) {\n // Add or update to latest version\n latestByName.set(integration.name, {\n id: integration.id,\n name: integration.name,\n version: integration.version,\n updatedAt: integration.updatedAt,\n createdAt: integration.createdAt,\n title: integration.title,\n description: integration.description,\n iconUrl: integration.iconUrl,\n public: integration.public,\n visibility: integration.visibility,\n ownerWorkspace: integration.ownerWorkspace\n ? {\n id: integration.ownerWorkspace.id,\n name: integration.ownerWorkspace.name,\n }\n : undefined,\n verificationStatus: integration.verificationStatus,\n })\n }\n }\n\n // Convert map back to array, sorted by updatedAt descending\n const integrations = Array.from(latestByName.values()).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))\n\n // If we fetched all integrations (didn't break early), we have a complete list\n // Otherwise, merge with existing cache as done above\n\n // Save the updated cache\n const newCache: HubCacheData = {\n lastUpdated: new Date().toISOString(),\n integrations,\n }\n\n await this.saveCache(newCache)\n } catch (error) {\n throw new Error(`Failed to refresh hub cache: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n\n /**\n * Get all integrations from cache\n */\n async getAllIntegrations(): Promise<HubCacheEntry[]> {\n // Ensure cache is fresh\n await this.refresh()\n\n const cache = await this.loadCache()\n return cache?.integrations || []\n }\n\n /**\n * Search integrations by name\n */\n async searchIntegrations(query: string): Promise<HubCacheEntry[]> {\n const integrations = await this.getAllIntegrations()\n const lowerQuery = query.toLowerCase()\n\n return integrations.filter(\n (integration) =>\n integration.name.toLowerCase().includes(lowerQuery) ||\n integration.title?.toLowerCase().includes(lowerQuery) ||\n integration.description?.toLowerCase().includes(lowerQuery)\n )\n }\n\n /**\n * Get integration by name (latest version)\n */\n async getIntegrationByName(name: string): Promise<HubCacheEntry | null> {\n const integrations = await this.getAllIntegrations()\n\n // Since we only keep latest versions, just find by name\n return integrations.find((i) => i.name === name) || null\n }\n\n /**\n * Get all versions of an integration\n * Note: Since we only cache latest versions, this returns only the latest\n */\n async getIntegrationVersions(name: string): Promise<string[]> {\n const integration = await this.getIntegrationByName(name)\n return integration ? [integration.version] : []\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<{\n lastUpdated: Date | null\n integrationCount: number\n cacheSize: number\n }> {\n const cache = await this.loadCache()\n\n try {\n const stats = await fs.stat(HubCache.CACHE_PATH)\n return {\n lastUpdated: cache ? new Date(cache.lastUpdated) : null,\n integrationCount: cache?.integrations.length || 0,\n cacheSize: stats.size,\n }\n } catch {\n return {\n lastUpdated: null,\n integrationCount: 0,\n cacheSize: 0,\n }\n }\n }\n\n /**\n * Clear the cache\n */\n async clear(): Promise<void> {\n try {\n await fs.unlink(HubCache.CACHE_PATH)\n } catch {\n // File might not exist, that's fine\n }\n }\n}\n",
|
|
29
|
+
"import type { Client } from '@botpress/client'\nimport { getProjectClient } from '../auth/index.js'\nimport type { AgentProject } from '../agent-project/agent-project.js'\n\n/**\n * Merges integration configuration for API calls.\n * - If no local config is defined (undefined), preserves server-side config entirely.\n * - If local config is defined, merges it on top of server-side config (local wins per-key).\n */\nexport function mergeIntegrationConfig(\n current: Record<string, unknown> | undefined,\n desired: Record<string, unknown> | undefined\n): Record<string, unknown> {\n if (desired === undefined) {\n return current || {}\n }\n return { ...(current || {}), ...desired }\n}\n\n/**\n * Checks whether the local (desired) config matches the current (server) config.\n * Only compares keys present in `desired` — server-only keys are intentionally\n * preserved and do not count as drift. Falls back to schema defaults when a value\n * is missing on either side.\n */\nexport function configsMatch(\n current: Record<string, unknown> | undefined,\n desired: Record<string, unknown>,\n schemaDefaults: Record<string, unknown> = {}\n): boolean {\n return Object.keys(desired).every((key) => {\n const currentValue = current?.[key] ?? schemaDefaults[key]\n const desiredValue = desired[key] ?? schemaDefaults[key]\n return JSON.stringify(currentValue) === JSON.stringify(desiredValue)\n })\n}\n\nexport interface FetchServerConfigsResult {\n configs: Record<string, Record<string, unknown>>\n enabledStates: Record<string, boolean>\n fetched: boolean\n skipped: boolean\n error?: string\n}\n\n/**\n * Fetches current integration configurations from the server for a given bot.\n *\n * When `targetBotId` is provided, fetches from that specific bot (used during\n * deploy/build to fetch from the production bot). Otherwise falls back to\n * devId → botId resolution (used during adk dev to fetch from the dev bot).\n */\nexport async function fetchServerIntegrationConfigs(\n project: AgentProject,\n targetBotId?: string\n): Promise<FetchServerConfigsResult> {\n const { devId, botId } = project.agentInfo ?? {}\n const targetId = targetBotId || devId || botId\n if (!targetId) {\n return { configs: {}, enabledStates: {}, fetched: false, skipped: true }\n }\n\n try {\n const client = await getProjectClient({\n project,\n headers: { 'x-multiple-integrations': 'true' },\n })\n\n try {\n return await fetchBotConfigs(client, targetId)\n } catch (err) {\n // If explicit target was given, don't fall back\n if (targetBotId) {\n throw err\n }\n // If devId fetch failed and a separate botId exists, fall back to production bot\n if (devId && botId && devId !== botId) {\n return await fetchBotConfigs(client, botId)\n }\n throw err\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return {\n configs: {},\n enabledStates: {},\n fetched: false,\n skipped: false,\n error: message,\n }\n }\n}\n\nasync function fetchBotConfigs(client: Client, botId: string): Promise<FetchServerConfigsResult> {\n const { bot } = await client.getBot({ id: botId })\n const configs: Record<string, Record<string, unknown>> = {}\n const enabledStates: Record<string, boolean> = {}\n\n for (const [alias, integration] of Object.entries(bot.integrations || {})) {\n if (integration.configuration && Object.keys(integration.configuration).length > 0) {\n configs[alias] = integration.configuration\n }\n enabledStates[alias] = integration.enabled\n }\n\n return { configs, enabledStates, fetched: true, skipped: false }\n}\n\nexport type FetchServerPluginConfigsResult = {\n configs: Record<string, Record<string, unknown>>\n fetched: boolean\n skipped: boolean\n error?: string\n}\n\nexport async function fetchServerPluginConfigs(\n project: AgentProject,\n targetBotId?: string\n): Promise<FetchServerPluginConfigsResult> {\n const { devId, botId } = project.agentInfo ?? {}\n const targetId = targetBotId || devId || botId\n if (!targetId) {\n return { configs: {}, fetched: false, skipped: true }\n }\n\n try {\n const client = await getProjectClient({\n project,\n headers: { 'x-multiple-integrations': 'true' },\n })\n\n try {\n return await fetchBotPluginConfigs(client, targetId)\n } catch (err) {\n if (targetBotId) {\n throw err\n }\n if (devId && botId && devId !== botId) {\n return await fetchBotPluginConfigs(client, botId)\n }\n throw err\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { configs: {}, fetched: false, skipped: false, error: message }\n }\n}\n\nasync function fetchBotPluginConfigs(client: Client, botId: string): Promise<FetchServerPluginConfigsResult> {\n const { bot } = await client.getBot({ id: botId })\n const configs: Record<string, Record<string, unknown>> = {}\n\n for (const [alias, plugin] of Object.entries(bot.plugins || {})) {\n if (plugin.configuration && Object.keys(plugin.configuration).length > 0) {\n configs[alias] = plugin.configuration\n }\n }\n\n return { configs, fetched: true, skipped: false }\n}\n",
|
|
30
|
+
"export { IntegrationManager } from './manager.js'\nexport type { IntegrationManagerOptions } from './manager.js'\nexport { IntegrationParser } from '../agent-project/dependencies-parser.js'\nexport { IntegrationCache } from './cache.js'\nexport { EnhancedIntegrationCache } from './enhanced-cache.js'\nexport { HubCache } from './hub-cache.js'\nexport type { HubCacheEntry, HubCacheData } from './hub-cache.js'\nexport {\n mergeIntegrationConfig,\n configsMatch,\n fetchServerIntegrationConfigs,\n fetchServerPluginConfigs,\n} from './config-utils.js'\nexport type { FetchServerConfigsResult, FetchServerPluginConfigsResult } from './config-utils.js'\nexport * from './types.js'\n",
|
|
31
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { InterfaceDefinition } from './types.js'\n\ninterface VersionResolution {\n interfaceId: string\n updatedAt: string\n cachedAt: string\n}\n\ninterface CachedDefinition {\n definition: InterfaceDefinition\n cachedAt: string\n}\n\nexport class EnhancedInterfaceCache {\n private cacheDir: string\n private resolutionsDir: string\n private definitionsDir: string\n private noCache: boolean\n\n constructor(noCache: boolean = false) {\n this.noCache = noCache\n this.cacheDir = path.join(os.homedir(), '.adk', 'cache', 'interfaces')\n this.resolutionsDir = path.join(this.cacheDir, 'resolutions')\n this.definitionsDir = path.join(this.cacheDir, 'definitions')\n }\n\n private async ensureCacheDirs(): Promise<void> {\n await fs.mkdir(this.resolutionsDir, { recursive: true })\n await fs.mkdir(this.definitionsDir, { recursive: true })\n }\n\n async getResolution(name: string, version: string, workspace?: string): Promise<VersionResolution | null> {\n if (this.noCache) return null\n try {\n const key = this.getResolutionKey(name, version, workspace)\n const cachePath = path.join(this.resolutionsDir, `${key}.json`)\n const data = await fs.readFile(cachePath, 'utf-8')\n const resolution: VersionResolution = JSON.parse(data)\n const cachedAt = new Date(resolution.cachedAt)\n const ageMinutes = (Date.now() - cachedAt.getTime()) / (1000 * 60)\n if (ageMinutes > 5) return null\n return resolution\n } catch {\n return null\n }\n }\n\n async setResolution(\n name: string,\n version: string,\n workspace: string | undefined,\n interfaceId: string,\n updatedAt: string\n ): Promise<void> {\n await this.ensureCacheDirs()\n const key = this.getResolutionKey(name, version, workspace)\n const cachePath = path.join(this.resolutionsDir, `${key}.json`)\n const resolution: VersionResolution = {\n interfaceId,\n updatedAt,\n cachedAt: new Date().toISOString(),\n }\n await fs.writeFile(cachePath, JSON.stringify(resolution, null, 2))\n }\n\n async getDefinition(interfaceId: string, updatedAt: string): Promise<InterfaceDefinition | null> {\n if (this.noCache) return null\n try {\n const key = this.getDefinitionKey(interfaceId, updatedAt)\n const cachePath = path.join(this.definitionsDir, `${key}.json`)\n const data = await fs.readFile(cachePath, 'utf-8')\n const cached: CachedDefinition = JSON.parse(data)\n return cached.definition\n } catch {\n return null\n }\n }\n\n async setDefinition(interfaceId: string, updatedAt: string, definition: InterfaceDefinition): Promise<void> {\n await this.ensureCacheDirs()\n const key = this.getDefinitionKey(interfaceId, updatedAt)\n const cachePath = path.join(this.definitionsDir, `${key}.json`)\n const cached: CachedDefinition = {\n definition,\n cachedAt: new Date().toISOString(),\n }\n await fs.writeFile(cachePath, JSON.stringify(cached, null, 2))\n }\n\n async clear(): Promise<void> {\n try {\n const resolutionFiles = await fs.readdir(this.resolutionsDir)\n await Promise.all(resolutionFiles.map((f) => fs.unlink(path.join(this.resolutionsDir, f))))\n const definitionFiles = await fs.readdir(this.definitionsDir)\n await Promise.all(definitionFiles.map((f) => fs.unlink(path.join(this.definitionsDir, f))))\n } catch {\n // ignore\n }\n }\n\n async getStats(): Promise<{\n resolutions: { count: number; sizeBytes: number }\n definitions: { count: number; sizeBytes: number }\n }> {\n const getDirectoryStats = async (dir: string) => {\n try {\n const files = await fs.readdir(dir)\n let totalSize = 0\n for (const file of files) {\n const stats = await fs.stat(path.join(dir, file))\n totalSize += stats.size\n }\n return { count: files.length, sizeBytes: totalSize }\n } catch {\n return { count: 0, sizeBytes: 0 }\n }\n }\n const [resolutions, definitions] = await Promise.all([\n getDirectoryStats(this.resolutionsDir),\n getDirectoryStats(this.definitionsDir),\n ])\n return { resolutions, definitions }\n }\n\n private getResolutionKey(name: string, version: string, workspace?: string): string {\n const prefix = workspace ? `${workspace}_` : ''\n const key = `${prefix}${name}_${version}`\n return key.replace(/[^a-zA-Z0-9_-]/g, '_')\n }\n\n private getDefinitionKey(interfaceId: string, updatedAt: string): string {\n const key = `${interfaceId}_${updatedAt}`\n return key.replace(/[^a-zA-Z0-9_-]/g, '_')\n }\n}\n",
|
|
32
|
+
"import { Dependencies, ValidationError } from '../agent-project/types.js'\nimport { ValidationErrors } from '../agent-project/validation-errors.js'\nimport { InterfaceRef, ParsedInterface } from './types.js'\nimport { BUILTIN_INTERFACES } from '../constants.js'\n\nexport class InterfaceParser {\n /**\n * Parse an interface version string into its components\n * Examples:\n * - \"translator@1.2.0\" -> { name: 'translator', version: '1.2.0', fullName: 'translator' }\n * - \"myworkspace/translator@latest\" -> { workspace: 'myworkspace', name: 'translator', version: 'latest', fullName: 'myworkspace/translator' }\n */\n static parseInterfaceRef(versionString: string): InterfaceRef {\n // Match pattern: [workspace/]name@version\n const match = versionString.match(/^(?:([^/]+)\\/)?([^@]+)@(.+)$/)\n\n if (!match) {\n throw new Error(\n `Invalid interface version format: ${versionString}. Expected format: 'name@version' or 'workspace/name@version'`\n )\n }\n\n const [, workspace, name, version] = match\n\n return {\n workspace: workspace || undefined,\n name: name!,\n version: version!,\n fullName: workspace ? `${workspace}/${name}` : name!,\n }\n }\n\n /**\n * Get built-in interfaces (hard-coded constants)\n * The dependencies parameter is kept for API compatibility but not used\n */\n static parseInterfaces(_dependencies: Dependencies): {\n interfaces: ParsedInterface[]\n errors: ValidationError[]\n } {\n const interfaces: ParsedInterface[] = []\n const errors: ValidationError[] = []\n\n for (const [alias, versionString] of Object.entries(BUILTIN_INTERFACES)) {\n try {\n // Parse the interface reference\n const ref = this.parseInterfaceRef(versionString)\n\n // Validate version format\n if (!this.isValidVersion(ref.version)) {\n errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version))\n }\n\n interfaces.push({ alias, ref, config: undefined })\n } catch (error) {\n errors.push(\n ValidationErrors.invalidDependenciesSyntax(\n `Invalid interface '${alias}': ${error instanceof Error ? error.message : String(error)}`\n )\n )\n }\n }\n\n return { interfaces, errors }\n }\n\n /**\n * Validate version format (must be exact semver or \"latest\")\n */\n private static isValidVersion(version: string): boolean {\n if (version === 'latest') return true\n const semverPattern = /^(\\d+)\\.(\\d+)\\.(\\d+)(-[\\w.]+)?(\\+[\\w.]+)?$/\n return semverPattern.test(version)\n }\n}\n",
|
|
33
|
+
"import type { Client } from '@botpress/client'\nimport { getProjectClient, type Credentials, type ProjectCredentialsContext } from '../auth/index.js'\nimport { Dependencies, ValidationError } from '../agent-project/types.js'\nimport { InterfaceDefinition, ParsedInterface, InterfaceRef, InterfaceValidationResult } from './types.js'\nimport { EnhancedInterfaceCache } from './enhanced-cache.js'\nimport { InterfaceParser } from './parser.js'\nimport { ValidationErrors } from '../agent-project/validation-errors.js'\n\nexport interface InterfaceManagerOptions {\n noCache?: boolean\n project?: ProjectCredentialsContext\n apiUrl?: string\n workspaceId?: string\n credentials?: Credentials\n}\n\nexport class InterfaceManager {\n private cache: EnhancedInterfaceCache\n private options: InterfaceManagerOptions\n private client?: Client\n\n constructor(options: InterfaceManagerOptions = {}) {\n this.options = options\n this.cache = new EnhancedInterfaceCache(options.noCache || false)\n }\n\n private async getClient(): Promise<Client> {\n if (!this.client) {\n this.client = await getProjectClient({\n project: this.options.project,\n credentials: this.options.credentials,\n apiUrl: this.options.apiUrl,\n workspaceId: this.options.workspaceId,\n headers: {\n 'x-multiple-integrations': 'true',\n },\n })\n }\n return this.client\n }\n\n async loadInterfaces(dependencies: Dependencies): Promise<{\n interfaces: ParsedInterface[]\n errors: ValidationError[]\n warnings: ValidationError[]\n }> {\n const errors: ValidationError[] = []\n const warnings: ValidationError[] = []\n\n // Parse interfaces from dependencies\n const parseResult = InterfaceParser.parseInterfaces(dependencies)\n const interfaces = parseResult.interfaces\n errors.push(...parseResult.errors)\n\n // Fetch interface definitions in parallel\n const fetchPromises = interfaces.map(async (intf) => {\n try {\n const definition = await this.fetchInterface(intf.ref)\n intf.definition = definition\n\n // Validate\n const validation = this.validateInterface(intf)\n intf.validationResult = validation\n\n if (!validation.valid) {\n validation.errors.forEach((msg) => {\n errors.push(ValidationErrors.warning(msg, 'agent.config.ts'))\n })\n }\n } catch (error) {\n if (error instanceof Error && error.message.includes('version')) {\n errors.push(ValidationErrors.unknownInterface(error.message))\n } else {\n errors.push(\n ValidationErrors.invalidDependenciesSyntax(`Unknown interface '${intf.alias}' (${intf.ref.fullName})`)\n )\n }\n }\n })\n\n await Promise.all(fetchPromises)\n\n return { interfaces, errors, warnings }\n }\n\n /**\n * Fetch interface definition from API or cache\n */\n public async fetchInterface(ref: InterfaceRef): Promise<InterfaceDefinition> {\n // Level 1: version resolution cache (name@version -> id + updatedAt)\n const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace)\n if (cachedResolution) {\n const cachedDefinition = await this.cache.getDefinition(cachedResolution.interfaceId, cachedResolution.updatedAt)\n if (cachedDefinition) {\n return cachedDefinition\n }\n }\n\n const client = await this.getClient()\n let interfaceResponse: { interface: InterfaceDefinition } | undefined\n let versionError: Error | null = null\n\n try {\n interfaceResponse = await client.getInterfaceByName({\n name: ref.name,\n version: ref.version,\n })\n } catch {\n try {\n interfaceResponse = await client.getPublicInterface({\n name: ref.name,\n version: ref.version,\n })\n } catch (publicError) {\n versionError = publicError as Error\n }\n }\n\n if (!interfaceResponse && versionError) {\n let latestVersion: string | null = null\n try {\n const latestPrivate = await client.getInterfaceByName({\n name: ref.name,\n version: 'latest',\n })\n latestVersion = latestPrivate.interface.version\n } catch {\n try {\n const latestPublic = await client.getPublicInterface({\n name: ref.name,\n version: 'latest',\n })\n latestVersion = latestPublic.interface.version\n } catch {\n const location = ref.workspace ? `workspace \"${ref.workspace}\"` : 'the official Botpress hub'\n throw new Error(`Interface \"${ref.name}\" does not exist in ${location}`)\n }\n }\n const location = ref.workspace ? `workspace \"${ref.workspace}\"` : 'Botpress'\n throw new Error(\n `Interface \"${ref.name}\" version \"${ref.version}\" not found in ${location}. Latest available version is \"${latestVersion}\"`\n )\n }\n\n const intf = interfaceResponse!.interface\n\n await this.cache.setResolution(ref.name, ref.version, ref.workspace, intf.id, intf.updatedAt)\n await this.cache.setDefinition(intf.id, intf.updatedAt, intf)\n return intf\n }\n\n /**\n * Convenience: parse and fetch from a dependency string like \"name@1.2.3\" or \"workspace/name@latest\"\n */\n public async getByDependencyString(dep: string): Promise<InterfaceDefinition> {\n // Reuse parser regex logic without duplicating\n const match = dep.match(/^(?:([^/]+)\\/)?([^@]+)@(.+)$/)\n if (!match) {\n throw new Error(\n `Invalid interface dependency string: ${dep}. Expected 'name@version' or 'workspace/name@version'`\n )\n }\n const [, workspace, name, version] = match\n return this.fetchInterface({\n workspace: workspace || undefined,\n name: name!,\n version: version!,\n fullName: workspace ? `${workspace}/${name}` : name!,\n })\n }\n\n private validateInterface(intf: ParsedInterface): InterfaceValidationResult {\n const errors: string[] = []\n const warnings: string[] = []\n\n if (!intf.definition) {\n errors.push(`Interface definition not found for ${intf.alias}`)\n return { valid: false, errors, warnings }\n }\n\n return { valid: errors.length === 0, errors, warnings }\n }\n\n async getCacheStats(): Promise<{ count: number; sizeBytes: number }> {\n const stats = await this.cache.getStats()\n return {\n count: stats.resolutions.count + stats.definitions.count,\n sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes,\n }\n }\n\n async clearCache(): Promise<void> {\n await this.cache.clear()\n }\n}\n",
|
|
34
|
+
"export { InterfaceManager } from './manager.js'\nexport type { InterfaceManagerOptions } from './manager.js'\nexport { InterfaceParser } from './parser.js'\nexport { EnhancedInterfaceCache } from './enhanced-cache.js'\nexport * from './types.js'\n",
|
|
35
|
+
"/**\n * Utility for ensuring consistent key ordering in JSON files\n */\n\n// Key ordering arrays for different file types\nexport const agentInfoKeyOrder = ['botId', 'workspaceId', 'apiUrl'] as const\nexport const agentLocalInfoKeyOrder = ['botId', 'workspaceId', 'apiUrl', 'devId'] as const\nexport const dependenciesKeyOrder = ['integrations'] as const\nexport const integrationKeyOrder = ['version', 'enabled', 'configurationType', 'config'] as const\n\n/**\n * Orders object keys according to a specified order, with unspecified keys at the end alphabetically\n */\nexport function orderKeys<T extends Record<string, unknown>>(obj: T, keyOrder?: readonly (keyof T)[]): T {\n const objKeys = Object.keys(obj)\n const orderedKeys: string[] = []\n const remainingKeys: string[] = []\n\n // Add keys in the specified order if they exist in the object\n if (keyOrder) {\n for (const key of keyOrder) {\n const keyStr = String(key)\n if (objKeys.includes(keyStr)) {\n orderedKeys.push(keyStr)\n }\n }\n }\n\n // Add remaining keys alphabetically\n for (const key of objKeys) {\n if (!orderedKeys.includes(key)) {\n remainingKeys.push(key)\n }\n }\n remainingKeys.sort()\n\n // Combine ordered keys with remaining keys\n const finalKeys = [...orderedKeys, ...remainingKeys]\n\n const result = {} as T\n for (const key of finalKeys) {\n result[key as keyof T] = obj[key] as T[keyof T]\n }\n\n return result\n}\n\n/**\n * Recursively orders keys in nested objects for integrations\n */\nexport function orderIntegrationKeys(integrations: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n\n for (const [name, config] of Object.entries(integrations)) {\n if (typeof config === 'object' && config !== null && !Array.isArray(config)) {\n result[name] = orderKeys(config as Record<string, unknown>, integrationKeyOrder)\n } else {\n result[name] = config\n }\n }\n\n return result\n}\n\n/**\n * Stringifies JSON with consistent key ordering and formatting\n */\nexport function stringifyWithOrder<T extends Record<string, unknown>>(\n obj: T,\n keyOrder?: readonly (keyof T)[],\n space: number | string = 2\n): string {\n const orderedObj = orderKeys(obj, keyOrder)\n\n // Special handling for dependencies with nested integrations\n if ('integrations' in orderedObj) {\n const integrations = (orderedObj as Record<string, unknown>).integrations\n if (integrations && typeof integrations === 'object') {\n ;(orderedObj as Record<string, unknown>).integrations = orderIntegrationKeys(\n integrations as Record<string, unknown>\n )\n }\n }\n\n return JSON.stringify(orderedObj, null, space)\n}\n",
|
|
36
|
+
"import { Primitives, Errors } from '@botpress/runtime/internal'\nimport { ValidationError, ValidationErrorCode, ValidationSeverity } from './types.js'\n\nexport interface ExpandExportsOptions {\n absolutePath: string\n relPath: string\n filename: string\n onWarning: (warning: ValidationError) => void\n}\n\n/**\n * Expands the exports of a module to include all properties,\n * including those on the default export if it is an object or array.\n * For example, exports of type `{ default: { a: 1, b: 2 } }`\n * will be expanded to `{ \"default.a\": 1, \"default.b\": 2 }`.\n *\n * @param options - Options for expanding exports\n * @returns A record of expanded exports\n */\nexport async function expandExports(options: ExpandExportsOptions): Promise<Record<string, unknown>> {\n const { absolutePath, relPath, filename, onWarning } = options\n let result: Record<string, unknown> = {}\n\n try {\n // Bust module cache by adding timestamp query parameter\n // This ensures we always get fresh imports on reload\n const importPath = `${absolutePath}?t=${Date.now()}`\n const exports = await import(importPath)\n\n if (typeof exports === 'object' && exports !== null) {\n for (const key of Object.keys(exports)) {\n try {\n result[key] = exports[key]\n } catch (error) {\n // Skip exports that throw on access\n if (Errors.isAdkError(error)) {\n onWarning({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: error.message,\n file: relPath,\n hint: `Invalid primitive instantiation in ${filename} -> ${key}`,\n })\n }\n }\n }\n\n // Handle default exports\n if (typeof exports.default === 'object' && exports.default !== null) {\n try {\n const definition = Primitives.Definitions.getDefinition(exports.default)\n if (!definition) {\n // If not a primitive, expand the default export\n for (const key of Object.keys(exports.default)) {\n try {\n result[`default.${key}`] = exports.default[key]\n } catch (error) {\n if (Errors.isAdkError(error)) {\n onWarning({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: error.message,\n file: relPath,\n hint: `Invalid primitive instantiation in ${filename} -> default.${key}`,\n })\n }\n }\n }\n }\n } catch (error) {\n // If accessing default throws, check if it's an ADK error\n if (Errors.isAdkError(error)) {\n onWarning({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: error.message,\n file: relPath,\n hint: `Invalid primitive instantiation in ${filename} -> default`,\n })\n }\n }\n }\n }\n\n return result\n } catch (importError: unknown) {\n // Check if it's an ADK error thrown during primitive instantiation\n if (Errors.isAdkError(importError)) {\n onWarning({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: importError.message,\n file: relPath,\n hint: `Invalid primitive instantiation in ${filename}`,\n })\n return {}\n }\n\n // Check error cause chain for ADK errors (handles module initialization errors)\n let currentError: unknown = importError\n while (currentError) {\n if (Errors.isAdkError(currentError)) {\n onWarning({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: currentError.message,\n file: relPath,\n hint: `Invalid primitive instantiation in ${filename}`,\n })\n return {}\n }\n currentError = currentError instanceof Error ? currentError.cause : undefined\n }\n\n // Re-throw other import errors\n throw importError\n }\n}\n",
|
|
37
|
+
"/**\n * Filename suffixes for the on-disk component contract.\n */\nexport const BP_TSX_SUFFIX = '.bp.tsx'\nexport const BP_CSS_SUFFIX = '.bp.css'\nexport const BP_TYPES_SUFFIX = '.bp.types.ts'\n\nexport const BP_BUNDLE_SUFFIXES: readonly string[] = [BP_TSX_SUFFIX, BP_CSS_SUFFIX, BP_TYPES_SUFFIX]\n\n/** Bot-relative directory containing all custom components. */\nexport const COMPONENTS_DIR = 'src/components'\n",
|
|
38
|
+
"import { Project, SyntaxKind, type SourceFile, type Node } from 'ts-morph'\nimport { readFileSync } from 'fs'\nimport * as path from 'path'\nimport { BP_TSX_SUFFIX } from './component-files.js'\n\nconst CUSTOM_COMPONENT_CLASS = 'CustomComponent'\n\n/**\n * Resolves the absolute `.bp.tsx` source path for each `CustomComponent`\n * exported from a wrapper file.\n *\n * Walks the wrapper's TS AST to:\n * 1. Map every `import <local> from '<...>.bp.tsx'` to its resolved path.\n * 2. Find every `new CustomComponent(<Ident>, ...)` and trace back through\n * const declarations and re-exports to determine which exported name\n * corresponds to which `.bp.tsx` import.\n *\n * Exports whose first argument cannot be traced back to a `.bp.tsx` import\n * are simply omitted from the returned map; the caller decides how to\n * surface the gap.\n *\n * Supported binding shapes:\n * - import Foo from './Foo.bp.tsx'\n * - import * as Foo from './Foo.bp.tsx' (uses the namespace's default)\n * - export const X = new CustomComponent(Foo, ...)\n * - export default new CustomComponent(Foo, ...)\n * - const X = new CustomComponent(Foo, ...); export { X }\n * - export { X as Y }\n *\n * Re-exports from another module (`export { X } from './foo'`) are skipped;\n * the canonical file that does `new CustomComponent` will be parsed instead.\n */\nexport function resolveComponentSources(absolutePath: string): Map<string, string> {\n const project = new Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true })\n const sourceFile = project.createSourceFile(absolutePath, readFileSync(absolutePath, 'utf-8'), { overwrite: true })\n\n const importBindings = collectBpTsxImports(sourceFile, absolutePath)\n if (importBindings.size === 0) {\n return new Map()\n }\n\n const localToSource = resolveLocalBindings(sourceFile, importBindings)\n return resolveExports(sourceFile, localToSource, importBindings)\n}\n\n/**\n * Build a map of local binding name -> absolute `.bp.tsx` path for every\n * default or namespace import of a `.bp.tsx` file in the source.\n */\nfunction collectBpTsxImports(sourceFile: SourceFile, absolutePath: string): Map<string, string> {\n const imports = new Map<string, string>()\n const dir = path.dirname(absolutePath)\n\n for (const decl of sourceFile.getImportDeclarations()) {\n const specifier = decl.getModuleSpecifierValue()\n if (!specifier.endsWith(BP_TSX_SUFFIX)) continue\n\n const resolved = path.resolve(dir, specifier)\n const defaultImport = decl.getDefaultImport()\n if (defaultImport) {\n imports.set(defaultImport.getText(), resolved)\n }\n const namespaceImport = decl.getNamespaceImport()\n if (namespaceImport) {\n imports.set(namespaceImport.getText(), resolved)\n }\n }\n\n return imports\n}\n\n/**\n * Walk every top-level const/let/var declaration assigned from\n * `new CustomComponent(<Ident>, ...)` and map the declaration's name to\n * the `.bp.tsx` source the identifier resolves to.\n */\nfunction resolveLocalBindings(sourceFile: SourceFile, importBindings: Map<string, string>): Map<string, string> {\n const result = new Map<string, string>()\n\n for (const stmt of sourceFile.getVariableStatements()) {\n for (const decl of stmt.getDeclarations()) {\n const initializer = decl.getInitializer()\n if (!initializer) continue\n const source = sourceFromCustomComponentExpr(initializer, importBindings)\n if (source) {\n result.set(decl.getName(), source)\n }\n }\n }\n\n return result\n}\n\n/**\n * Join the local-binding map with all export declarations to produce the\n * final `exportName -> source` map.\n */\nfunction resolveExports(\n sourceFile: SourceFile,\n localToSource: Map<string, string>,\n importBindings: Map<string, string>\n): Map<string, string> {\n const exportMap = new Map<string, string>()\n\n // `export const X = ...` — the local map already covers X if it was a CustomComponent.\n for (const stmt of sourceFile.getVariableStatements()) {\n if (!stmt.isExported()) continue\n for (const decl of stmt.getDeclarations()) {\n const source = localToSource.get(decl.getName())\n if (source) exportMap.set(decl.getName(), source)\n }\n }\n\n // `export default ...`\n for (const assignment of sourceFile.getExportAssignments()) {\n if (assignment.isExportEquals()) continue\n const expr = assignment.getExpression()\n\n // `export default new CustomComponent(Foo, ...)`\n const direct = sourceFromCustomComponentExpr(expr, importBindings)\n if (direct) {\n exportMap.set('default', direct)\n continue\n }\n // `export default Local` where Local was a CustomComponent constant\n if (expr.getKind() === SyntaxKind.Identifier) {\n const fromLocal = localToSource.get(expr.getText())\n if (fromLocal) exportMap.set('default', fromLocal)\n }\n }\n\n // `export { X }` and `export { X as Y }` (no module specifier — local re-export).\n for (const decl of sourceFile.getExportDeclarations()) {\n if (decl.getModuleSpecifier()) continue\n for (const named of decl.getNamedExports()) {\n const localName = named.getNameNode().getText()\n const aliasNode = named.getAliasNode()\n const exportName = aliasNode ? aliasNode.getText() : localName\n const source = localToSource.get(localName)\n if (source) exportMap.set(exportName, source)\n }\n }\n\n return exportMap\n}\n\n/**\n * If the given expression is `new CustomComponent(<Ident>, ...)` and\n * `<Ident>` resolves to a `.bp.tsx` import, return the absolute source path.\n * Returns undefined for any other shape.\n */\nfunction sourceFromCustomComponentExpr(expr: Node, importBindings: Map<string, string>): string | undefined {\n if (expr.getKind() !== SyntaxKind.NewExpression) return undefined\n const newExpr = expr.asKindOrThrow(SyntaxKind.NewExpression)\n\n if (newExpr.getExpression().getText() !== CUSTOM_COMPONENT_CLASS) return undefined\n\n const args = newExpr.getArguments()\n const firstArg = args[0]\n if (!firstArg || firstArg.getKind() !== SyntaxKind.Identifier) return undefined\n\n return importBindings.get(firstArg.getText())\n}\n",
|
|
39
|
+
"import { MAX_TABLE_COLUMNS } from '../constants.js'\n\nexport interface TableColumnViolation {\n name: string\n path: string\n columnCount: number\n}\n\nexport interface ValidatableTable {\n path: string\n definition: {\n name: string\n schema?: { properties?: Record<string, unknown> }\n }\n}\n\n/**\n * Column count is read from the JSON Schema `properties` map. `BaseTable.getDefinition()`\n * produces a `TableDefinition` whose `schema` is the JSON-schema form of the column object;\n * each top-level property in `schema.properties` is one column.\n */\nfunction getColumnCount(table: ValidatableTable): number {\n const properties = table.definition.schema?.properties\n return properties ? Object.keys(properties).length : 0\n}\n\nexport function findTableColumnViolations(\n tables: ValidatableTable[],\n max: number = MAX_TABLE_COLUMNS\n): TableColumnViolation[] {\n return tables\n .map((table) => ({\n name: table.definition.name,\n path: table.path,\n columnCount: getColumnCount(table),\n }))\n .filter((t) => t.columnCount > max)\n}\n\nexport function formatTableColumnViolationError(\n violations: TableColumnViolation[],\n max: number = MAX_TABLE_COLUMNS\n): string {\n const lines = violations.map((v) => ` - ${v.name} (${v.path}): ${v.columnCount} columns (max ${max})`)\n return [\n `Table column-count validation failed (limit: ${max} columns per table).`,\n 'The following tables exceed the limit:',\n ...lines,\n 'Reduce columns or split the table.',\n ].join('\\n')\n}\n",
|
|
40
|
+
"import type { LockFileData } from '@botpress/adk/dependencies'\nimport type { Dependencies } from './types.js'\n\n/**\n * Convert a per-env LockFileData into the `Dependencies` shape consumed by\n * IntegrationManager / InterfaceManager / PluginManager.\n *\n * The lock file is keyed by alias with `{ name, version, enabled, config }`.\n * The legacy `Dependencies` shape is keyed by alias with `{ version: \"name@version\", enabled, config }`.\n */\nexport function lockToDependencies(lock: LockFileData): Dependencies {\n const integrations: Dependencies['integrations'] = {}\n for (const [alias, entry] of Object.entries(lock.integrations)) {\n integrations[alias] = {\n version: `${entry.name}@${entry.version}`,\n enabled: entry.enabled,\n config: entry.config,\n }\n }\n\n const plugins: Dependencies['plugins'] = {}\n for (const [alias, entry] of Object.entries(lock.plugins)) {\n plugins[alias] = {\n version: `${entry.name}@${entry.version}`,\n config: entry.config,\n dependencies: entry.dependencies,\n }\n }\n\n return { integrations, plugins }\n}\n",
|
|
41
|
+
"import { BuiltInActions, BuiltInWorkflows, Errors, Primitives, setAdkCommand } from '@botpress/runtime/internal'\nimport { Autonomous } from '@botpress/runtime'\nimport createDebug from 'debug'\nimport { createRequire } from 'module'\n\nimport fs from 'fs/promises'\nimport path from 'path'\n\nimport { AssetsManager, AssetSyncOptions, AssetSyncPlan, AssetSyncResult } from '../assets/index.js'\nimport { IntegrationManager } from '../integrations/index.js'\nimport { ParsedIntegration } from '../integrations/types.js'\nimport { InterfaceManager } from '../interfaces/index.js'\nimport { ParsedInterface } from '../interfaces/types.js'\n\nimport { agentInfoKeyOrder, agentLocalInfoKeyOrder, stringifyWithOrder } from '../utils/json-ordering.js'\nimport { expandExports } from './expand-exports.js'\nimport { resolveComponentSources } from './component-source-resolver.js'\nimport { COMPONENTS_DIR } from './component-files.js'\nimport { resolveAgent } from './agent-resolver.js'\nimport {\n AgentConfig,\n AgentInfo,\n AgentToolDefinition,\n AgentLocalInfo,\n Dependencies,\n dependenciesSchema,\n Integration,\n ProjectInfo,\n ProjectState,\n ValidationError,\n ValidationErrorCode,\n ValidationResult,\n ValidationSeverity,\n ToolReference,\n} from './types.js'\nimport { ValidationErrors } from './validation-errors.js'\nimport { findTableColumnViolations } from '../bot-generator/table-validation.js'\nimport { MAX_TABLE_COLUMNS } from '../constants.js'\nimport { LockFile } from '../dependencies/lock-file.js'\nimport { lockToDependencies } from './lock-to-dependencies.js'\n\nexport interface AgentProjectOptions {\n noCache?: boolean\n adkCommand?: 'adk-dev' | 'adk-build' | 'adk-deploy'\n offline?: boolean\n}\n\nexport type AgentProjectLoader = (projectPath: string) => Promise<AgentProject>\n\nconst debug = createDebug('adk:agent-project')\ntype ConversationDefinition = Primitives.Definitions.ConversationDefinition\ntype KnowledgeDefinition = Primitives.Definitions.KnowledgeDefinition\ntype TriggerDefinition = Primitives.Definitions.TriggerDefinition\ntype WorkflowDefinition = Primitives.Definitions.WorkflowDefinition\ntype ActionDefinition = Primitives.Definitions.ActionDefinition\ntype TableDefinition = Primitives.Definitions.TableDefinition\ntype CustomComponentDefinition = Primitives.Definitions.CustomComponentDefinition\ntype PrimitiveDefinition = Primitives.Definitions.PrimitiveDefinition\n\nexport type PrimitiveReference<T extends PrimitiveDefinition = PrimitiveDefinition> = {\n path: string\n export: string\n definition: T\n}\n\nexport type CustomComponentReference = PrimitiveReference<CustomComponentDefinition> & {\n source: string\n // `BaseCustomComponent` instance, kept as `unknown` to keep ADK free of `@botpress/runtime`.\n instance: unknown\n}\n\nfunction getToolDefinition(value: unknown): AgentToolDefinition | undefined {\n if (typeof value !== 'object' || value === null) {\n return undefined\n }\n\n const maybeTool = value as Autonomous.Tool\n const isAutonomousToolInstance = value instanceof Autonomous.Tool\n // Structural duck-typing fallback: don't rely on constructor.name which gets\n // minified in compiled binaries, causing instanceof and name checks to fail\n // across module boundaries.\n const looksLikeAutonomousTool =\n typeof maybeTool.name === 'string' &&\n typeof maybeTool.execute === 'function' &&\n typeof maybeTool.toJSON === 'function'\n\n if (!isAutonomousToolInstance && !looksLikeAutonomousTool) {\n return undefined\n }\n\n return {\n name: maybeTool.name,\n description: maybeTool.description,\n }\n}\n\nexport class AgentProject {\n private static _projectCache = new Map<string, AgentProject>()\n\n private _options: AgentProjectOptions\n private _path: string\n private _config?: AgentConfig\n private _dependencies?: Dependencies\n private _agentInfo?: AgentInfo\n private _state: ProjectState = ProjectState.Unloaded\n private _errors: ValidationError[] = []\n private _warnings: ValidationError[] = []\n\n private _lastBuildTime?: Date\n private _integrations?: ParsedIntegration[]\n private _interfaces?: ParsedInterface[]\n private _integrationManager: IntegrationManager\n private _interfaceManager: InterfaceManager\n private _assetsManager: AssetsManager\n private _conversations: PrimitiveReference<ConversationDefinition>[] = []\n private _knowledge: PrimitiveReference<KnowledgeDefinition>[] = []\n private _triggers: PrimitiveReference<TriggerDefinition>[] = []\n private _workflows: PrimitiveReference<WorkflowDefinition>[] = []\n private _actions: PrimitiveReference<ActionDefinition>[] = []\n private _tables: PrimitiveReference<TableDefinition>[] = []\n private _customComponents: CustomComponentReference[] = []\n private _tools: ToolReference[] = []\n\n constructor(projectPath: string, options: AgentProjectOptions = {}) {\n this._options = options\n this._path = path.resolve(projectPath)\n this._integrationManager = new IntegrationManager({\n noCache: options.noCache,\n })\n this._interfaceManager = new InterfaceManager({\n noCache: options.noCache,\n })\n this._assetsManager = new AssetsManager({\n projectPath: this._path,\n })\n }\n\n // Static factory methods\n static async load(projectPath: string, options: AgentProjectOptions = {}): Promise<AgentProject> {\n const resolvedPath = path.resolve(projectPath)\n\n // Check cache unless explicitly disabled\n if (!options.noCache) {\n const cached = AgentProject._projectCache.get(resolvedPath)\n if (cached) {\n return cached\n }\n }\n\n // Create and load new project\n const project = new AgentProject(resolvedPath, options)\n await project.reload()\n\n // Cache the project unless caching is disabled\n if (!options.noCache) {\n AgentProject._projectCache.set(resolvedPath, project)\n }\n\n return project\n }\n\n // Static method to clear the cache\n static clearCache(): void {\n AgentProject._projectCache.clear()\n }\n\n // Static method to remove a specific project from cache\n static clearCacheForPath(projectPath: string): void {\n const resolvedPath = path.resolve(projectPath)\n AgentProject._projectCache.delete(resolvedPath)\n }\n\n // Public properties\n get path(): string {\n return this._path\n }\n\n get conversations(): PrimitiveReference<ConversationDefinition>[] {\n return this._conversations\n }\n\n get knowledge(): PrimitiveReference<KnowledgeDefinition>[] {\n return this._knowledge\n }\n\n get triggers(): PrimitiveReference<TriggerDefinition>[] {\n return this._triggers\n }\n\n get workflows(): PrimitiveReference<WorkflowDefinition>[] {\n return this._workflows\n }\n\n get actions(): PrimitiveReference<ActionDefinition>[] {\n return this._actions\n }\n\n get tables(): PrimitiveReference<TableDefinition>[] {\n return this._tables\n }\n\n get customComponents(): CustomComponentReference[] {\n return this._customComponents\n }\n\n get tools(): ToolReference[] {\n return this._tools\n }\n\n get config(): AgentConfig | undefined {\n return this._config\n }\n\n get dependencies(): Dependencies | undefined {\n return this._dependencies\n }\n\n get agentInfo(): AgentInfo | undefined {\n return this._agentInfo\n }\n\n get state(): ProjectState {\n return this._state\n }\n\n get info(): ProjectInfo {\n return {\n path: this._path,\n config: this._config!,\n dependencies: this._dependencies || {\n integrations: {},\n },\n agentInfo: this._agentInfo,\n state: this._state,\n lastBuildTime: this._lastBuildTime,\n errors: [...this._errors],\n warnings: [...this._warnings],\n errorCount: this._errors.filter((e) => e.severity === ValidationSeverity.ERROR).length,\n warningCount: this._warnings.filter((e) => e.severity === ValidationSeverity.WARNING).length,\n infoCount: [...this._errors, ...this._warnings].filter((e) => e.severity === ValidationSeverity.INFO).length,\n }\n }\n\n // Core methods\n async reload(): Promise<void> {\n this._state = ProjectState.Loading\n\n try {\n // Clear previous state\n this._conversations = []\n this._knowledge = []\n this._triggers = []\n this._workflows = []\n this._actions = []\n this._tables = []\n this._tools = []\n this._errors = []\n this._warnings = []\n this._customComponents = []\n\n // Validate project structure\n const validation = await this.validate()\n this._errors = validation.errors\n this._warnings = validation.warnings\n\n if (!validation.valid) {\n this._state = ProjectState.Error\n\n throw new Error(`Project validation failed: ${validation.errors[0]?.message}`)\n }\n\n // Load agent info FIRST so we have the workspaceId\n await this.loadAgentInfo()\n\n // Create managers with the correct workspaceId from agent.json\n this._integrationManager = new IntegrationManager({\n noCache: this._options.noCache,\n project: this,\n })\n\n this._interfaceManager = new InterfaceManager({\n noCache: this._options.noCache,\n project: this,\n })\n\n this._assetsManager = new AssetsManager({\n projectPath: this._path,\n botId: this._agentInfo?.botId,\n })\n\n // Load configuration (which will use the managers with correct workspaceId)\n await this.loadConfig()\n\n await this.loadBuiltInWorkflows()\n await this.loadBuiltInActions()\n await this.loadAgentPrimitives()\n\n if (this._errors.length > 0) {\n this._state = ProjectState.Error\n } else {\n this._state = ProjectState.Ready\n }\n } catch (error) {\n this._state = ProjectState.Error\n\n throw error\n }\n }\n\n async validate(): Promise<ValidationResult> {\n const errors: ValidationError[] = []\n const warnings: ValidationError[] = []\n const info: ValidationError[] = []\n\n try {\n // Check if directory exists\n await fs.access(this._path)\n\n // Check for required files\n const requiredFiles = ['agent.config.ts']\n for (const file of requiredFiles) {\n try {\n await fs.access(path.join(this._path, file))\n } catch {\n errors.push(ValidationErrors.requiredFileMissing(file))\n }\n }\n\n // Check for agent.json (optional, but warn if missing for deployed projects)\n try {\n await fs.access(path.join(this._path, 'agent.json'))\n } catch {\n // agent.json is optional, but we add an informational message\n info.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.MISSING_REQUIRED_FIELD,\n severity: ValidationSeverity.INFO,\n message: 'agent.json not found - this file will be required for deployment and remote operations',\n file: 'agent.json',\n hint: 'Create agent.json with botId and workspaceId after deploying your agent',\n })\n }\n\n // Check directory structure\n const expectedDirs = ['actions', 'workflows', 'conversations', 'assets']\n for (const dir of expectedDirs) {\n try {\n const stats = await fs.stat(path.join(this._path, dir))\n if (!stats.isDirectory()) {\n warnings.push(ValidationErrors.invalidStructure(dir, 'directory'))\n }\n } catch {\n // Directory doesn't exist, which is okay - they're optional\n }\n }\n } catch (error) {\n errors.push(ValidationErrors.directoryAccessError(this._path, String(error)))\n }\n\n for (const violation of findTableColumnViolations(this._tables)) {\n errors.push(\n ValidationErrors.tableTooManyColumns(violation.name, violation.path, violation.columnCount, MAX_TABLE_COLUMNS)\n )\n }\n\n // Filter by severity\n const errorsBySeverity = {\n errors: errors.filter((e) => e.severity === ValidationSeverity.ERROR),\n warnings: [...warnings, ...errors.filter((e) => e.severity === ValidationSeverity.WARNING)],\n info: [...info, ...errors.filter((e) => e.severity === ValidationSeverity.INFO)],\n }\n\n return {\n valid: errorsBySeverity.errors.length === 0,\n errors: errorsBySeverity.errors,\n warnings: errorsBySeverity.warnings,\n info: errorsBySeverity.info,\n errorCount: errorsBySeverity.errors.length,\n warningCount: errorsBySeverity.warnings.length,\n infoCount: errorsBySeverity.info.length,\n }\n }\n\n get integrations(): ParsedIntegration[] {\n if (!this._integrations) {\n throw new Error('Integrations not loaded')\n }\n\n return this._integrations!\n }\n\n get interfaces(): ParsedInterface[] {\n if (!this._interfaces) {\n throw new Error('Interfaces not loaded')\n }\n return this._interfaces!\n }\n\n // Integration management methods\n async getIntegrations(): Promise<Integration[]> {\n if (!this._dependencies || !this._integrations) {\n throw new Error('Project not loaded')\n }\n\n // Convert ParsedIntegration to Integration format\n return this._integrations.map((parsed) => ({\n name: parsed.alias,\n version: parsed.ref.version,\n workspace: parsed.ref.workspace,\n config: parsed.config,\n installed: false, // This would be determined by checking workspace\n installedVersion: undefined,\n hasChannels: parsed.definition?.channels && Object.keys(parsed.definition.channels).length > 0,\n }))\n }\n\n // Asset management methods\n async createAssetSyncPlan(): Promise<AssetSyncPlan> {\n if (this._state !== ProjectState.Ready) {\n throw new Error('Project must be in Ready state to create asset sync plan')\n }\n\n this.requiresAgentInfo('create asset sync plan')\n return await this._assetsManager.createSyncPlan()\n }\n\n async syncAssets(options?: AssetSyncOptions): Promise<AssetSyncResult> {\n if (this._state !== ProjectState.Ready) {\n throw new Error('Project must be in Ready state to sync assets')\n }\n\n this.requiresAgentInfo('sync assets')\n const plan = await this._assetsManager.createSyncPlan()\n return await this._assetsManager.executeSync(plan, options)\n }\n\n async hasAssetsDirectory(): Promise<boolean> {\n return await this._assetsManager.hasAssetsDirectory()\n }\n\n get assetsManager(): AssetsManager {\n return this._assetsManager\n }\n\n // Agent info management methods\n async createAgentInfo(info: AgentInfo): Promise<void> {\n // Extract devId — it goes to agent.local.json, not agent.json\n const { devId, ...agentJsonInfo } = info\n const agentPath = path.join(this._path, 'agent.json')\n const agentContent = stringifyWithOrder(agentJsonInfo, agentInfoKeyOrder)\n await fs.writeFile(agentPath, agentContent)\n this._agentInfo = info\n\n if (devId) {\n await this.createAgentLocalInfo({ devId })\n }\n }\n\n async updateAgentInfo(updates: Partial<AgentInfo>): Promise<void> {\n if (!this._agentInfo) {\n throw new Error('No agent.json found. Use createAgentInfo() first.')\n }\n\n // Extract devId — it goes to agent.local.json, not agent.json\n const { devId, ...agentJsonUpdates } = updates\n\n const updatedInfo = { ...this._agentInfo, ...agentJsonUpdates }\n // Strip devId from agent.json write\n const { devId: _devId, ...agentJsonData } = updatedInfo\n const agentPath = path.join(this._path, 'agent.json')\n const agentContent = stringifyWithOrder(agentJsonData, agentInfoKeyOrder)\n await fs.writeFile(agentPath, agentContent)\n this._agentInfo = updatedInfo\n\n if (devId !== undefined) {\n await this.updateAgentLocalInfo({ devId })\n }\n }\n\n async createAgentLocalInfo(info: AgentLocalInfo): Promise<void> {\n const localPath = path.join(this._path, 'agent.local.json')\n let existing: AgentLocalInfo = {}\n try {\n const content = await fs.readFile(localPath, 'utf-8')\n existing = JSON.parse(content)\n } catch {\n // File doesn't exist yet\n }\n const merged = { ...existing, ...info }\n const content = stringifyWithOrder(merged, agentLocalInfoKeyOrder)\n await fs.writeFile(localPath, content)\n // Update in-memory merged view\n if (this._agentInfo) {\n if (merged.botId) this._agentInfo.botId = merged.botId\n if (merged.workspaceId) this._agentInfo.workspaceId = merged.workspaceId\n if (merged.apiUrl) this._agentInfo.apiUrl = merged.apiUrl\n if (merged.devId) this._agentInfo.devId = merged.devId\n } else if (merged.botId && merged.workspaceId) {\n this._agentInfo = {\n botId: merged.botId,\n workspaceId: merged.workspaceId,\n apiUrl: merged.apiUrl,\n devId: merged.devId,\n }\n }\n }\n\n async updateAgentLocalInfo(updates: Partial<AgentLocalInfo>): Promise<void> {\n const localPath = path.join(this._path, 'agent.local.json')\n let existing: AgentLocalInfo = {}\n try {\n const content = await fs.readFile(localPath, 'utf-8')\n existing = JSON.parse(content)\n } catch {\n // File doesn't exist yet\n }\n const updated: Record<string, unknown> = { ...existing, ...updates }\n // Remove undefined keys\n for (const key of Object.keys(updated)) {\n if (updated[key] === undefined) {\n delete updated[key]\n }\n }\n\n if (Object.keys(updated).length === 0) {\n // No local overrides remain — delete the file so adk dev starts fresh\n try {\n await fs.unlink(localPath)\n } catch {\n // File already gone — no-op\n }\n } else {\n const content = stringifyWithOrder(updated as AgentLocalInfo, agentLocalInfoKeyOrder)\n await fs.writeFile(localPath, content)\n }\n\n // Recompute in-memory agentInfo from agent.json base + surviving local overrides\n // so cleared fields (e.g. devId) are no longer visible in memory.\n if (this._agentInfo) {\n // Re-read agent.json base — devId never lives in agent.json, so\n // both the fallback and the parsed path explicitly exclude it.\n const agentJsonPath = path.join(this._path, 'agent.json')\n let base: Omit<AgentInfo, 'devId'> = {\n botId: this._agentInfo.botId,\n workspaceId: this._agentInfo.workspaceId,\n apiUrl: this._agentInfo.apiUrl,\n }\n try {\n const agentJsonContent = await fs.readFile(agentJsonPath, 'utf-8')\n const parsed = JSON.parse(agentJsonContent) as AgentInfo\n base = {\n botId: parsed.botId ?? this._agentInfo.botId,\n workspaceId: parsed.workspaceId ?? this._agentInfo.workspaceId,\n apiUrl: parsed.apiUrl ?? this._agentInfo.apiUrl,\n }\n } catch {\n // agent.json may not exist (local-only project) — keep existing base\n }\n const local = updated as AgentLocalInfo\n this._agentInfo = {\n botId: local.botId ?? base.botId,\n workspaceId: local.workspaceId ?? base.workspaceId,\n apiUrl: local.apiUrl ?? base.apiUrl,\n devId: local.devId,\n }\n }\n }\n\n requiresAgentInfo(operation: string): void {\n if (!this._agentInfo?.botId) {\n throw new Error(\n `Operation \"${operation}\" requires a bot ID. ` +\n 'Please create agent.json with botId and workspaceId after deploying your agent.'\n )\n }\n }\n\n // Private helper methods\n private async loadConfig(): Promise<void> {\n // Default to empty collections so any early-return or thrown-error path below\n // still leaves the project in a state readable by `adk status` and the other\n // consumers of the integrations/interfaces getters. Successful paths overwrite.\n this._dependencies = { integrations: {} }\n this._integrations = []\n this._interfaces = []\n\n try {\n // Bust module cache to ensure fresh config on reload\n const configPath = path.join(this._path, 'agent.config.ts')\n debug('loading agent.config.ts from %s', configPath)\n\n // Create a require function that resolves from the user's project directory\n // This is critical for compiled binaries which otherwise resolve modules from the binary's location\n const projectRequire = createRequire(path.join(this._path, 'package.json'))\n debug('created projectRequire from %s', path.join(this._path, 'package.json'))\n\n // Clear the module from cache if it exists\n try {\n const resolvedPath = projectRequire.resolve(configPath)\n debug('resolved config path: %s', resolvedPath)\n if (projectRequire.cache[resolvedPath]) {\n debug('clearing require.cache for %s', resolvedPath)\n delete projectRequire.cache[resolvedPath]\n }\n } catch {\n // Module not in cache yet, that's fine\n debug('config not in require.cache (first load)')\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic import returns unknown module shape\n let configModule: any\n try {\n // Use ?t= query string for cache busting to ensure fresh imports on reload\n const configUrl = `${configPath}?t=${Date.now()}`\n debug('importing from: %s', configUrl)\n configModule = await import(configUrl)\n debug('successfully loaded agent.config.ts')\n } catch (importError) {\n debug('failed to load agent.config.ts: %O', importError)\n throw importError\n }\n if (!configModule || !configModule.default) {\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_CONFIG_SCHEMA,\n severity: ValidationSeverity.ERROR,\n message: 'agent.config.ts does not export a default configuration object',\n file: 'agent.config.ts',\n })\n return\n }\n\n // Check if the config was created with defineConfig\n const { isAgentConfig } = await import('@botpress/runtime/internal')\n if (!isAgentConfig(configModule.default)) {\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_CONFIG_SCHEMA,\n severity: ValidationSeverity.ERROR,\n message:\n 'agent.config.ts must export the result of defineConfig(). ' +\n \"Example: export default defineConfig({ name: 'my-agent', ... })\",\n file: 'agent.config.ts',\n hint: 'Wrap your config object with defineConfig() from @botpress/runtime',\n })\n return\n }\n\n this._config = configModule.default as AgentConfig\n\n const lockFile = new LockFile({ projectPath: this._path, env: 'dev' })\n let lockBasedDependencies: Dependencies | undefined\n try {\n const lockData = await lockFile.read()\n const hasDependencies =\n Object.keys(lockData.integrations).length > 0 || Object.keys(lockData.plugins).length > 0\n if (hasDependencies) {\n lockBasedDependencies = lockToDependencies(lockData)\n }\n } catch (err) {\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_DEPENDENCIES_SCHEMA,\n severity: ValidationSeverity.WARNING,\n message: `Could not read dependencies.dev.lock.json: ${(err as Error).message}. Falling back to agent.config.ts dependencies.`,\n file: 'dependencies.dev.lock.json',\n })\n }\n\n // Extract dependencies from config (fallback for un-migrated projects)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic import module shape\n const config = configModule.default as any\n let configBasedDependencies: Dependencies | undefined\n if (!lockBasedDependencies && config.dependencies) {\n // Validate dependencies against schema\n const validationResult = dependenciesSchema.safeParse(config.dependencies)\n if (!validationResult.success) {\n const errors = validationResult.error.errors\n for (const error of errors) {\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_DEPENDENCIES_SCHEMA,\n severity: ValidationSeverity.ERROR,\n message: `Invalid dependencies in agent.config.ts: ${error.path.join('.')} - ${error.message}`,\n file: 'agent.config.ts',\n hint: error.code === 'invalid_type' ? `Expected ${error.expected}, but got ${error.received}` : undefined,\n })\n }\n this._dependencies = { integrations: {} }\n this._integrations = []\n this._interfaces = []\n return\n }\n configBasedDependencies = validationResult.data\n }\n\n const depsToLoad = lockBasedDependencies ?? configBasedDependencies\n\n if (depsToLoad) {\n this._dependencies = depsToLoad\n\n // Validate and load integrations and interfaces\n if (!this._options.offline) {\n const [intRes, ifRes] = await Promise.all([\n this._integrationManager.loadIntegrations(this._dependencies),\n this._interfaceManager.loadInterfaces(this._dependencies),\n ])\n this._integrations = intRes.integrations\n this._interfaces = ifRes.interfaces\n\n // Add errors and warnings\n this._errors.push(...intRes.errors, ...ifRes.errors)\n this._warnings.push(...intRes.warnings, ...ifRes.warnings)\n } else {\n // In offline mode, skip API-dependent integration/interface loading\n this._integrations = []\n this._interfaces = []\n }\n } else {\n // Neither lock file nor config.dependencies present — empty deps.\n this._dependencies = { integrations: {} }\n this._integrations = []\n this._interfaces = []\n }\n } catch (error) {\n const err = error as Error\n debug('loadConfig error: %O', err)\n\n // Build a detailed error message with stack trace for debugging\n let detailedMessage = `Failed to load agent.config.ts: ${err.message}`\n if (err.stack) {\n // Include the stack trace in debug output\n debug('stack trace:\\n%s', err.stack)\n }\n\n // Check for common issues and provide helpful hints\n let hint: string | undefined\n if (err.message.includes('Cannot find module')) {\n const moduleMatch = err.message.match(/Cannot find module '([^']+)'/)\n const moduleName = moduleMatch?.[1] || 'unknown'\n hint = `Module \"${moduleName}\" is not installed. Run \"bun install\" to install dependencies.`\n detailedMessage += `\\n\\n Stack trace:\\n${err.stack?.split('\\n').slice(0, 5).join('\\n')}`\n }\n\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_CONFIG_SYNTAX,\n severity: ValidationSeverity.ERROR,\n message: detailedMessage,\n file: 'agent.config.ts',\n hint,\n })\n }\n }\n\n private async loadAgentInfo(): Promise<void> {\n try {\n // Use the agent resolver to load agent.json (not required for basic project loading)\n const agentInfo = await resolveAgent(this._path, { required: false })\n this._agentInfo = agentInfo ?? undefined\n } catch (error) {\n // Handle validation errors from resolver\n if (ValidationErrors.isValidationError(error)) {\n this._errors.push(error)\n } else if (error instanceof Error) {\n // Unexpected error - wrap it\n this._errors.push(ValidationErrors.warning(`Failed to load agent.json: ${error.message}`, 'agent.json'))\n }\n\n this._agentInfo = undefined\n }\n }\n\n private async loadBuiltInWorkflows(): Promise<void> {\n for (const wf of Object.values(BuiltInWorkflows)) {\n const definition = Primitives.Definitions.getDefinition(wf)\n if (Primitives.Definitions.isWorkflowDefinition(definition)) {\n this._workflows.push({\n definition,\n export: 'default',\n path: '<adk:builtin>',\n })\n }\n }\n }\n\n private async loadBuiltInActions(): Promise<void> {\n for (const action of Object.values(BuiltInActions)) {\n const definition = Primitives.Definitions.getDefinition(action)\n if (Primitives.Definitions.isActionDefinition(definition)) {\n this._actions.push({\n definition,\n export: 'default',\n path: '<adk:builtin>',\n })\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- knowledge base has dynamic structure\n private async registerDataSourceWorkflows(knowledgeBase: any, kbPath: string, kbExport: string): Promise<void> {\n try {\n // Each knowledge base has data sources with sync workflows\n if (!knowledgeBase.sources || !Array.isArray(knowledgeBase.sources)) {\n return\n }\n\n for (const source of knowledgeBase.sources) {\n if (!source.syncWorkflow) {\n continue\n }\n\n const workflowDefinition = source.syncWorkflow.getDefinition()\n\n // Check if workflow already exists\n const existing = this._workflows.find((p) => p.definition.name === workflowDefinition.name)\n\n if (existing) {\n // Skip if already registered\n continue\n }\n\n // Register the data source's sync workflow\n this._workflows.push({\n definition: workflowDefinition,\n export: `${kbExport}.sources[${knowledgeBase.sources.indexOf(source)}].syncWorkflow`,\n path: kbPath,\n })\n }\n } catch (error) {\n console.warn(`Failed to register data source workflows for ${kbPath}:`, error)\n }\n }\n\n /**\n * Get list of channels from a channel specification (single, array, or glob)\n * For glob '*', we need to check against all integration channels - but for validation\n * we treat it as a special marker\n */\n /**\n * Checks if a duplicate primitive is just a re-export from a barrel file (index.ts/index.js).\n * If so, prefers the non-barrel file path for the reference and returns true to signal\n * that the duplicate should be silently skipped.\n */\n private isBarrelReexport(\n existing: PrimitiveReference,\n newPath: string,\n newExport: string,\n newDefinition: PrimitiveDefinition\n ): boolean {\n const isNewBarrel = /^index\\.[tj]s$/i.test(path.basename(newPath))\n const isExistingBarrel = /^index\\.[tj]s$/i.test(path.basename(existing.path))\n\n if (!isNewBarrel && !isExistingBarrel) {\n return false\n }\n\n // Prefer the non-barrel file as the canonical source\n if (isExistingBarrel && !isNewBarrel) {\n existing.path = newPath\n existing.export = newExport\n existing.definition = newDefinition\n }\n\n return true\n }\n\n private isToolBarrelReexport(existingPath: string, newPath: string): boolean {\n const isNewBarrel = /^index\\.[tj]s$/i.test(path.basename(newPath))\n const isExistingBarrel = /^index\\.[tj]s$/i.test(path.basename(existingPath))\n\n if (!isNewBarrel && !isExistingBarrel) {\n return false\n }\n\n return true\n }\n\n private shouldPreferToolDefinition(existingPath: string, newPath: string): boolean {\n const isNewBarrel = /^index\\.[tj]s$/i.test(path.basename(newPath))\n const isExistingBarrel = /^index\\.[tj]s$/i.test(path.basename(existingPath))\n\n return isExistingBarrel && !isNewBarrel\n }\n\n private getChannelsList(channelSpec: string | string[]): string[] {\n if (channelSpec === '*') {\n return ['*'] // Glob marker - matches everything\n } else if (Array.isArray(channelSpec)) {\n return channelSpec\n } else {\n return [channelSpec]\n }\n }\n\n private async loadAgentPrimitives(): Promise<void> {\n // Set the ADK command in the runtime environment\n if (this._options.adkCommand) {\n setAdkCommand(this._options.adkCommand)\n }\n\n const src = path.join(this._path, 'src')\n\n if (!(await fs.stat(src).catch(() => false))) {\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_STRUCTURE,\n severity: ValidationSeverity.ERROR,\n message: `\\`src\\` directory not found at expected path: ${src}`,\n })\n return\n }\n\n const allFiles = await fs.readdir(src, {\n withFileTypes: true,\n recursive: true,\n })\n\n for (const file of allFiles.filter((x) => x.isFile())) {\n const filename = file.name\n const absolutePath = path.join(file.parentPath, file.name)\n const relPath = path.relative(this.path, absolutePath)\n\n if (filename.toLowerCase().endsWith('.d.ts')) {\n // Skip TypeScript declaration files\n continue\n }\n\n if (filename.toLowerCase().endsWith('.test.ts') || filename.toLowerCase().endsWith('.test.js')) {\n // Skip test files\n continue\n }\n\n if (!filename.toLowerCase().endsWith('.js') && !filename.toLowerCase().endsWith('.ts')) {\n continue // Only process .js or .ts files\n }\n\n if (file.isSymbolicLink()) {\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_FILE_TYPE,\n severity: ValidationSeverity.WARNING,\n message: `Skipping symbolic link in conversations directory: ${relPath}`,\n file: relPath,\n })\n continue\n }\n\n try {\n const expandedExports = await expandExports({\n absolutePath,\n relPath,\n filename,\n onWarning: (warning) => this._warnings.push(warning),\n })\n\n // Resolved lazily on first custom-component encounter for this file.\n let componentSources: Map<string, string> | undefined\n\n for (const key of Object.keys(expandedExports)) {\n let definition\n try {\n definition = Primitives.Definitions.getDefinition(expandedExports[key])\n } catch (error) {\n // This might catch errors from getDefinition itself\n if (Errors.isAdkError(error)) {\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: error.message,\n file: relPath,\n hint: `Check the primitive definition in ${filename} -> ${key}`,\n })\n continue\n }\n // Re-throw if it's not an ADK error\n throw error\n }\n\n if (Primitives.Definitions.isConversationDefinition(definition)) {\n // Check for overlapping channel definitions\n const overlapping = this._conversations.find((p) => {\n const existingChannels = this.getChannelsList(p.definition.channel)\n const newChannels = this.getChannelsList(definition.channel)\n\n // Check if any channel overlaps\n return existingChannels.some((ch) => newChannels.includes(ch))\n })\n\n if (overlapping) {\n if (this.isBarrelReexport(overlapping, relPath, key, definition)) {\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Overlapping conversation channels found: ${filename} -> ${key} overlaps with ${overlapping.path} -> ${overlapping.export}`,\n file: relPath,\n })\n continue\n }\n this._conversations.push({\n definition,\n export: key,\n path: relPath,\n })\n } else if (Primitives.Definitions.isKnowledgeDefinition(definition)) {\n const existing = this._knowledge.find((p) => p.definition.name === definition.name)\n\n if (existing) {\n if (this.isBarrelReexport(existing, relPath, key, definition)) {\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate knowledge definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n\n this._knowledge.push({\n definition,\n export: key,\n path: relPath,\n })\n\n // Register data source sync workflows\n await this.registerDataSourceWorkflows(expandedExports[key], relPath, key)\n } else if (Primitives.Definitions.isTriggerDefinition(definition)) {\n const existing = this._triggers.find((p) => p.definition.name === definition.name)\n if (existing) {\n if (this.isBarrelReexport(existing, relPath, key, definition)) {\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate trigger definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n this._triggers.push({\n definition,\n export: key,\n path: relPath,\n })\n } else if (Primitives.Definitions.isWorkflowDefinition(definition)) {\n const existing = this._workflows.find((p) => p.definition.name === definition.name)\n if (existing) {\n if (this.isBarrelReexport(existing, relPath, key, definition)) {\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate workflow definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n this._workflows.push({\n definition,\n export: key,\n path: relPath,\n })\n } else if (Primitives.Definitions.isActionDefinition(definition)) {\n const existing = this._actions.find((p) => p.definition.name === definition.name)\n if (existing) {\n if (this.isBarrelReexport(existing, relPath, key, definition)) {\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate action definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n this._actions.push({\n definition,\n export: key,\n path: relPath,\n })\n } else if (Primitives.Definitions.isCustomComponentDefinition(definition)) {\n const posixRelPath = relPath.split(/[\\\\/]+/).join('/')\n if (!posixRelPath.startsWith(`${COMPONENTS_DIR}/`)) {\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: `Custom components must be defined under \\`${COMPONENTS_DIR}/\\`. Found \"${definition.name}\" in ${relPath}.`,\n file: relPath,\n })\n continue\n }\n if (componentSources === undefined) {\n try {\n componentSources = resolveComponentSources(absolutePath)\n } catch (error) {\n componentSources = new Map()\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.WARNING,\n message: `Failed to parse component sources from ${relPath}: ${error instanceof Error ? error.message : String(error)}`,\n file: relPath,\n })\n }\n }\n const source = componentSources.get(key)\n\n const existing = this._customComponents.find((p) => p.definition.name === definition.name)\n if (existing) {\n if (this.isBarrelReexport(existing, relPath, key, definition)) {\n // If the swap promoted this file to the canonical, refresh source.\n if (existing.path === relPath && source) {\n existing.source = source\n }\n existing.instance = expandedExports[key]\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate custom component definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n this._customComponents.push({\n definition,\n export: key,\n path: relPath,\n source: source ?? '',\n instance: expandedExports[key],\n })\n } else if (Primitives.Definitions.isTableDefinition(definition)) {\n const existing = this._tables.find((p) => p.definition.name === definition.name)\n if (existing) {\n if (this.isBarrelReexport(existing, relPath, key, definition)) {\n continue\n }\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate table definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n this._tables.push({\n definition,\n export: key,\n path: relPath,\n })\n } else {\n const toolDefinition = getToolDefinition(expandedExports[key])\n\n if (!toolDefinition) {\n continue\n }\n\n const existing = this._tools.find((tool) => tool.definition.name === toolDefinition.name)\n if (existing) {\n if (this.isToolBarrelReexport(existing.path, relPath)) {\n if (this.shouldPreferToolDefinition(existing.path, relPath)) {\n existing.path = relPath\n existing.export = key\n existing.definition = toolDefinition\n }\n\n continue\n }\n\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.DUPLICATE_PRIMITIVE,\n severity: ValidationSeverity.WARNING,\n message: `Duplicate tool definition found: ${filename} -> ${key} (already defined in ${existing.path} -> ${existing.export})`,\n file: relPath,\n })\n continue\n }\n\n this._tools.push({\n definition: toolDefinition,\n export: key,\n path: relPath,\n })\n }\n }\n } catch (error) {\n // Check if it's an ADK error from expandExports\n if (Errors.isAdkError(error)) {\n // Error is already handled by expandExports, skip this file\n continue\n }\n\n // Log other import errors with context\n this._warnings.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.IMPORT_ERROR,\n severity: ValidationSeverity.WARNING,\n message: `Failed to import primitive from ${relPath}: ${error instanceof Error ? error.message : String(error)}`,\n file: relPath,\n hint: 'Ensure the file exports valid primitives and has no syntax errors',\n })\n }\n }\n\n // Custom components must trace back to a `.bp.tsx` import. Drop and report\n // any whose source we couldn't resolve from the AST after all files were processed.\n const unresolved = this._customComponents.filter((c) => !c.source)\n if (unresolved.length > 0) {\n this._customComponents = this._customComponents.filter((c) => c.source)\n for (const comp of unresolved) {\n this._errors.push({\n $type: 'ValidationError',\n code: ValidationErrorCode.INVALID_PRIMITIVE_DEFINITION,\n severity: ValidationSeverity.ERROR,\n message: `Cannot resolve .bp.tsx source for custom component \"${comp.definition.name}\" exported from ${comp.path} as \"${comp.export}\".`,\n file: comp.path,\n hint:\n 'Each CustomComponent must be constructed from a default-imported .bp.tsx component, e.g. ' +\n \"`import Foo from './Foo.bp.tsx'; export const FooComponent = new CustomComponent(Foo, ...)`.\",\n })\n }\n }\n }\n}\n",
|
|
42
|
+
"import path from 'path'\n\n// Lazy-load oxfmt because it has a native binding that isn't available\n// in compiled binaries. The dynamic import lets us catch the failure\n// gracefully and fall back to unformatted code.\nlet _format: ((file: string, code: string) => Promise<{ code: string }>) | null = null\nlet _formatLoaded = false\n\nasync function getFormat() {\n if (!_formatLoaded) {\n _formatLoaded = true\n try {\n const oxfmt = await import('oxfmt')\n _format = oxfmt.format\n } catch {\n // Native binding unavailable (e.g. compiled binary) — formatting disabled\n }\n }\n return _format\n}\n\nexport const formatCode = async (code: string, filepath?: string): Promise<string> => {\n try {\n // Skip formatting if code is empty or too large\n if (!code || code.length > 1_000_000) {\n return code\n }\n\n const format = await getFormat()\n if (!format) return code\n\n const fileName = filepath || 'file.ts'\n const result = await format(fileName, code)\n\n return result.code\n } catch (err) {\n console.warn('Failed to format code with oxfmt:', err)\n console.warn(\n code\n .slice(0, 1000)\n .split('\\n')\n .map((l, i) => `\\t${i.toString().padStart(2, '0')} | ${l}`)\n .join('\\n')\n )\n return code\n }\n}\n\n// This constant is injected at build time by esbuild's define\ndeclare const __RUNTIME_VERSION__: string\n\nexport const ADK_VERSION =\n typeof __RUNTIME_VERSION__ === 'undefined'\n ? ((globalThis as { __RUNTIME_VERSION__?: string }).__RUNTIME_VERSION__ ?? '0.0.0')\n : __RUNTIME_VERSION__\n\nexport const relative = (from: string, to: string): string => {\n const fromDir = path.dirname(from)\n const relative = path.relative(fromDir, to)\n return relative.startsWith('.') ? relative : `./${relative}`\n}\n\nexport function toMultilineComment(comment: string): string {\n // Handle empty or null comments\n if (!comment || comment.trim() === '') {\n return ''\n }\n\n // Escape potentially dangerous characters in the comment\n // Replace */ with *\\/ to prevent premature comment closure\n let safeComment = comment.replace(/\\*\\//g, '*\\\\/')\n\n // Split by newlines to handle multi-line comments\n // Handle all line ending types: \\r\\n (Windows), \\n (Unix), \\r (old Mac)\n const lines = safeComment.split(/\\r\\n|\\r|\\n/)\n\n // If single line and short enough, return inline comment\n if (lines.length === 1 && lines[0] && lines[0].length <= 60) {\n return `/** ${lines[0]} */`\n }\n\n // For multi-line comments, format with proper indentation\n let result = '/**\\n'\n for (const line of lines) {\n // Trim trailing whitespace but preserve leading whitespace for formatting\n const trimmedLine = line.replace(/\\s+$/, '')\n result += ` * ${trimmedLine}\\n`\n }\n result += ' */'\n\n return result\n}\n",
|
|
43
|
+
"import type { Client } from '@botpress/client'\nimport { LockFile } from './lock-file.js'\nimport { generateFriendlyAlias, isFriendlyAlias } from './alias-utils.js'\nimport { jsonEqual } from './json-utils.js'\nimport type {\n Environment,\n ResourceType,\n AddSpec,\n MutationResult,\n IntegrationLockEntry,\n PluginLockEntry,\n LockFileData,\n ConfigPatch,\n DiffResult,\n SyncResult,\n ApplyResult,\n ApplyAction,\n} from './types.js'\nimport { DependencyError } from './errors.js'\nimport { IntegrationResolver } from './resolvers/integration-resolver.js'\nimport { PluginResolver } from './resolvers/plugin-resolver.js'\nimport { IntegrationRegistry } from './registry/integration-registry.js'\nimport { PluginRegistry } from './registry/plugin-registry.js'\nimport { AgentProject } from '../agent-project/agent-project.js'\n\nexport interface ResourceEntry {\n type: ResourceType\n alias: string\n name: string\n version: string\n enabled: boolean\n}\n\nexport interface DependencyManagerOptions {\n projectPath: string\n env: Environment\n client: Client\n botId: string\n integrationRegistry?: IntegrationRegistry\n pluginRegistry?: PluginRegistry\n integrationResolver?: IntegrationResolver\n pluginResolver?: PluginResolver\n}\n\nexport class DependencyManager {\n private readonly lockFile: LockFile\n private readonly env: Environment\n private readonly client: Client\n private readonly projectPath: string\n private readonly botId: string\n private readonly integrationRegistry: IntegrationRegistry\n private readonly pluginRegistry: PluginRegistry\n private readonly integrationResolver: IntegrationResolver\n private readonly pluginResolver: PluginResolver\n private readonly envSource: Record<string, string>\n\n constructor(opts: DependencyManagerOptions) {\n this.projectPath = opts.projectPath\n this.env = opts.env\n this.client = opts.client\n this.lockFile = new LockFile({ projectPath: opts.projectPath, env: opts.env })\n this.botId = opts.botId\n this.integrationRegistry = opts.integrationRegistry ?? new IntegrationRegistry()\n this.pluginRegistry = opts.pluginRegistry ?? new PluginRegistry()\n this.integrationResolver =\n opts.integrationResolver ?? new IntegrationResolver({ registry: this.integrationRegistry, client: this.client })\n this.pluginResolver =\n opts.pluginResolver ??\n new PluginResolver({\n registry: this.pluginRegistry,\n integrationRegistry: this.integrationRegistry,\n client: this.client,\n })\n this.envSource = Object.fromEntries(Object.entries(process.env).filter(([, v]) => typeof v === 'string')) as Record<\n string,\n string\n >\n }\n\n static async fromProject(opts: {\n projectPath: string\n env: Environment\n client: Client\n integrationRegistry?: IntegrationRegistry\n pluginRegistry?: PluginRegistry\n integrationResolver?: IntegrationResolver\n pluginResolver?: PluginResolver\n }): Promise<DependencyManager> {\n const project = await AgentProject.load(opts.projectPath)\n const info = project.agentInfo\n if (!info) {\n throw new DependencyError({\n code: 'BOT_NOT_FOUND',\n message: `No agent.json found in ${opts.projectPath}. Run 'adk init' or 'adk login' to set up the project.`,\n })\n }\n const botId = opts.env === 'dev' ? (info.devId ?? info.botId) : info.botId\n return new DependencyManager({\n projectPath: project.path,\n env: opts.env,\n client: opts.client,\n botId,\n integrationRegistry: opts.integrationRegistry,\n pluginRegistry: opts.pluginRegistry,\n integrationResolver: opts.integrationResolver,\n pluginResolver: opts.pluginResolver,\n })\n }\n\n async list(type?: ResourceType): Promise<ResourceEntry[]> {\n const data = await this.lockFile.read()\n const out: ResourceEntry[] = []\n if (!type || type === 'integration') {\n for (const [alias, e] of Object.entries(data.integrations)) {\n out.push({ type: 'integration', alias, name: e.name, version: e.version, enabled: e.enabled })\n }\n }\n if (!type || type === 'plugin') {\n for (const [alias, e] of Object.entries(data.plugins)) {\n out.push({ type: 'plugin', alias, name: e.name, version: e.version, enabled: e.enabled })\n }\n }\n return out\n }\n\n async get(type: ResourceType, alias: string): Promise<ResourceEntry | undefined> {\n const all = await this.list(type)\n return all.find((e) => e.alias === alias)\n }\n\n async add(type: ResourceType, spec: AddSpec): Promise<MutationResult> {\n if (type === 'interface') {\n throw new DependencyError({\n code: 'BUILTIN_INTERFACE_IMMUTABLE',\n message: 'Interfaces are built-in platform constants and cannot be added.',\n })\n }\n const alias = spec.alias ?? spec.name\n const version = spec.version ?? 'latest'\n const lock = await this.lockFile.read()\n\n if (type === 'integration' && lock.integrations[alias]) {\n const existing = lock.integrations[alias]!\n const versionMatch = version === 'latest' || existing.version === version\n if (existing.enabled && versionMatch && jsonEqual(existing.config, spec.config ?? {})) {\n return {\n ok: true,\n noop: true,\n resource: { type, alias, name: spec.name, version: existing.version },\n }\n }\n }\n if (type === 'plugin' && lock.plugins[alias]) {\n const existing = lock.plugins[alias]!\n const versionMatch = version === 'latest' || existing.version === version\n if (existing.enabled && versionMatch && jsonEqual(existing.config, spec.config ?? {})) {\n return {\n ok: true,\n noop: true,\n resource: { type, alias, name: spec.name, version: existing.version },\n }\n }\n }\n\n if (type === 'integration') {\n const desired: IntegrationLockEntry = {\n name: spec.name,\n version,\n enabled: true,\n config: spec.config ?? {},\n }\n let installedDisabled: { missingFields: string[] } | undefined\n try {\n await this.integrationResolver.applyToCloud({ botId: this.botId, alias, entry: desired, env: this.envSource })\n } catch (err) {\n const missingFields = extractMissingRequiredFields(err)\n if (!missingFields) throw err\n await this.integrationResolver.applyToCloud({\n botId: this.botId,\n alias,\n entry: { ...desired, enabled: false },\n env: this.envSource,\n })\n installedDisabled = { missingFields }\n }\n const refreshed = await this.refreshLockFromCloud()\n const resolvedVersion = refreshed.integrations[alias]?.version ?? version\n return { ok: true, resource: { type, alias, name: spec.name, version: resolvedVersion }, installedDisabled }\n } else {\n const { dependencies: resolvedDeps, autoResolved } = await this.resolvePluginDependencies({\n pluginName: spec.name,\n pluginVersion: version,\n userDeps: spec.dependencies ?? {},\n lock,\n })\n const desired: PluginLockEntry = {\n name: spec.name,\n version,\n enabled: true,\n config: spec.config ?? {},\n dependencies: resolvedDeps,\n }\n await this.pluginResolver.applyToCloud({ botId: this.botId, alias, entry: desired, lock, env: this.envSource })\n const refreshed = await this.refreshLockFromCloud()\n const resolvedVersion = refreshed.plugins[alias]?.version ?? version\n return { ok: true, resource: { type, alias, name: spec.name, version: resolvedVersion }, autoResolved }\n }\n }\n\n async remove(type: ResourceType, alias: string): Promise<MutationResult> {\n if (type === 'interface') {\n throw new DependencyError({ code: 'BUILTIN_INTERFACE_IMMUTABLE', message: 'Interfaces cannot be removed.' })\n }\n const lock = await this.lockFile.read()\n const exists = type === 'integration' ? !!lock.integrations[alias] : !!lock.plugins[alias]\n if (!exists) return { ok: true, noop: true }\n\n if (type === 'integration') {\n await this.integrationResolver.removeFromCloud({ botId: this.botId, alias })\n } else {\n await this.pluginResolver.removeFromCloud({ botId: this.botId, alias })\n }\n await this.refreshLockFromCloud()\n return { ok: true }\n }\n\n async upgrade(type: ResourceType, alias: string, version?: string): Promise<MutationResult> {\n if (type === 'interface') {\n throw new DependencyError({ code: 'BUILTIN_INTERFACE_IMMUTABLE', message: 'Interfaces cannot be upgraded.' })\n }\n const lock = await this.lockFile.read()\n const existing = type === 'integration' ? lock.integrations[alias] : lock.plugins[alias]\n if (!existing) {\n throw new DependencyError({\n code: type === 'integration' ? 'INTEGRATION_NOT_FOUND' : 'PLUGIN_NOT_FOUND',\n message: `'${alias}' is not installed in ${this.env}`,\n })\n }\n const targetVersion = version ?? 'latest'\n if (existing.version === targetVersion) {\n return { ok: true, noop: true, resource: { type, alias, name: existing.name, version: existing.version } }\n }\n const next = { ...existing, version: targetVersion }\n await this.applyEntry(type, alias, next, lock)\n await this.refreshLockFromCloud()\n return { ok: true, resource: { type, alias, name: existing.name, version: next.version } }\n }\n\n async enable(type: ResourceType, alias: string): Promise<MutationResult> {\n return this.toggleEnabled(type, alias, true)\n }\n\n async disable(type: ResourceType, alias: string): Promise<MutationResult> {\n return this.toggleEnabled(type, alias, false)\n }\n\n private async toggleEnabled(type: ResourceType, alias: string, enabled: boolean): Promise<MutationResult> {\n if (type === 'interface') {\n throw new DependencyError({\n code: 'BUILTIN_INTERFACE_IMMUTABLE',\n message: 'Interfaces cannot be enabled/disabled.',\n })\n }\n const lock = await this.lockFile.read()\n const existing = type === 'integration' ? lock.integrations[alias] : lock.plugins[alias]\n if (!existing) {\n throw new DependencyError({\n code: type === 'integration' ? 'INTEGRATION_NOT_FOUND' : 'PLUGIN_NOT_FOUND',\n message: `'${alias}' is not installed in ${this.env}`,\n })\n }\n if (existing.enabled === enabled) return { ok: true, noop: true }\n await this.applyEntry(type, alias, { ...existing, enabled }, lock)\n const refreshedLock = await this.refreshLockFromCloud()\n const refreshedEntry = type === 'integration' ? refreshedLock.integrations[alias] : refreshedLock.plugins[alias]\n if (!refreshedEntry || refreshedEntry.enabled !== enabled) {\n throw new DependencyError({\n code: 'LOCK_DRIFT',\n message: `Cloud did not persist ${type} '${alias}' as ${enabled ? 'enabled' : 'disabled'}.`,\n details: {\n type,\n alias,\n expected: { enabled },\n actual: refreshedEntry ? { enabled: refreshedEntry.enabled } : null,\n },\n })\n }\n return { ok: true, resource: { type, alias, name: existing.name, version: existing.version } }\n }\n\n async configure(type: ResourceType, alias: string, patch: ConfigPatch): Promise<MutationResult> {\n if (type === 'interface') {\n throw new DependencyError({ code: 'BUILTIN_INTERFACE_IMMUTABLE', message: 'Interfaces cannot be configured.' })\n }\n const lock = await this.lockFile.read()\n const existing = type === 'integration' ? lock.integrations[alias] : lock.plugins[alias]\n if (!existing) {\n throw new DependencyError({\n code: type === 'integration' ? 'INTEGRATION_NOT_FOUND' : 'PLUGIN_NOT_FOUND',\n message: `'${alias}' is not installed in ${this.env}`,\n })\n }\n const nextConfig = { ...existing.config, ...(patch.set ?? {}) }\n for (const key of patch.unset ?? []) delete nextConfig[key]\n const next: typeof existing = { ...existing, config: nextConfig }\n if (type === 'plugin' && patch.map && 'dependencies' in next) {\n ;(next as PluginLockEntry).dependencies = { ...(next as PluginLockEntry).dependencies, ...patch.map }\n }\n if (jsonEqual(next, existing)) {\n return { ok: true, noop: true, resource: { type, alias, name: existing.name, version: existing.version } }\n }\n await this.applyEntry(type, alias, next, lock)\n await this.refreshLockFromCloud()\n return { ok: true, resource: { type, alias, name: existing.name, version: existing.version } }\n }\n\n private async applyEntry(\n type: ResourceType,\n alias: string,\n entry: IntegrationLockEntry | PluginLockEntry,\n lock: LockFileData\n ): Promise<void> {\n if (type === 'integration') {\n await this.integrationResolver.applyToCloud({\n botId: this.botId,\n alias,\n entry: entry as IntegrationLockEntry,\n env: this.envSource,\n })\n } else {\n await this.pluginResolver.applyToCloud({\n botId: this.botId,\n alias,\n entry: entry as PluginLockEntry,\n lock,\n env: this.envSource,\n })\n }\n }\n\n /**\n * For each interface the plugin requires that is NOT in `userDeps`, scan\n * the lock's installed integrations to find one that implements it.\n *\n * - Exactly one match → auto-resolve (no prompt needed).\n * - Multiple matches → throw AMBIGUOUS_DEPENDENCY (caller / CLI should prompt\n * the user to pass --dep <iface>=<alias> and retry).\n * - No matches → throw MISSING_DEPENDENCY.\n */\n private async resolvePluginDependencies(opts: {\n pluginName: string\n pluginVersion: string\n userDeps: Record<string, { integrationAlias: string }>\n lock: LockFileData\n }): Promise<{\n dependencies: Record<string, { integrationAlias: string }>\n autoResolved: Array<{ pluginInterfaceAlias: string; integrationAlias: string }>\n }> {\n const pluginSpec = await this.pluginRegistry.getSpec(opts.pluginName, opts.pluginVersion)\n const requiredInterfaces: Record<string, { name: string }> =\n (pluginSpec as { dependencies?: { interfaces?: Record<string, { name: string }> } }).dependencies?.interfaces ??\n {}\n\n const resolved: Record<string, { integrationAlias: string }> = { ...opts.userDeps }\n const autoResolved: Array<{ pluginInterfaceAlias: string; integrationAlias: string }> = []\n\n for (const [pluginIfaceAlias, requirement] of Object.entries(requiredInterfaces)) {\n if (resolved[pluginIfaceAlias]) {\n // User explicitly provided this dep — skip auto-resolution.\n continue\n }\n\n // Find all installed integrations that implement the required interface.\n const candidates: Array<{ alias: string; integrationName: string }> = []\n for (const [integrationAlias, integrationEntry] of Object.entries(opts.lock.integrations)) {\n let integrationSpec: { interfaces?: Record<string, { name: string }> }\n try {\n integrationSpec = await this.integrationRegistry.getSpec(integrationEntry.name, integrationEntry.version)\n } catch {\n // If we can't fetch the spec, skip this integration for auto-resolution.\n continue\n }\n const implements_ = Object.values(integrationSpec.interfaces ?? {}).some(\n (iface) => iface.name === requirement.name\n )\n if (implements_) {\n candidates.push({ alias: integrationAlias, integrationName: integrationEntry.name })\n }\n }\n\n if (candidates.length === 1) {\n const match = candidates[0]!\n resolved[pluginIfaceAlias] = { integrationAlias: match.alias }\n autoResolved.push({ pluginInterfaceAlias: pluginIfaceAlias, integrationAlias: match.alias })\n } else if (candidates.length > 1) {\n throw new DependencyError({\n code: 'AMBIGUOUS_DEPENDENCY',\n message: `Multiple installed integrations implement interface '${requirement.name}' required by plugin '${opts.pluginName}': ${candidates.map((c) => c.alias).join(', ')}. Pass --dep ${pluginIfaceAlias}=<alias> to disambiguate.`,\n details: {\n plugin: opts.pluginName,\n pluginInterfaceAlias: pluginIfaceAlias,\n interfaceName: requirement.name,\n candidates: candidates.map((c) => ({ alias: c.alias, name: c.integrationName })),\n },\n suggestion: `Pass --dep ${pluginIfaceAlias}=<alias> where <alias> is one of: ${candidates.map((c) => c.alias).join(', ')}`,\n })\n } else {\n const implementers = await this.findHubImplementersSafely(requirement.name)\n const suggestion = formatMissingDependencySuggestion({\n interfaceName: requirement.name,\n pluginInterfaceAlias: pluginIfaceAlias,\n implementers,\n })\n throw new DependencyError({\n code: 'MISSING_DEPENDENCY',\n message:\n `Plugin '${opts.pluginName}' requires interface '${requirement.name}', but no installed integration implements it.\\n` +\n suggestion,\n details: {\n plugin: opts.pluginName,\n pluginInterfaceAlias: pluginIfaceAlias,\n interfaceName: requirement.name,\n implementers: implementers.map((i) => ({ name: i.name, version: i.version, title: i.title })),\n },\n suggestion,\n })\n }\n }\n\n return { dependencies: resolved, autoResolved }\n }\n\n /**\n * Best-effort lookup of hub integrations that implement a given interface.\n * Returns [] if the Cloud call fails — never throws (we don't want to mask\n * the real MISSING_DEPENDENCY error with a network error).\n */\n private async findHubImplementersSafely(\n interfaceName: string\n ): Promise<Array<{ name: string; version: string; title?: string }>> {\n try {\n const results = (await this.integrationRegistry.findImplementersOfInterface(interfaceName, 5)) as Array<{\n name: string\n version: string\n title?: string\n }>\n return results\n } catch {\n return []\n }\n }\n\n private async refreshLockFromCloud(): Promise<LockFileData> {\n const { bot } = await this.client.getBot({ id: this.botId })\n const previous = await this.lockFile.read()\n const updated = { ...previous, ...this.cloudToLockShape(bot, previous) }\n await this.lockFile.write(updated)\n return updated\n }\n\n async diff(): Promise<DiffResult> {\n const lock = await this.lockFile.read()\n const cloud = await this.readCloudAsLockShape(lock)\n const delta: DiffResult['delta'] = { addedInLock: [], removedInLock: [], changedInLock: [] }\n for (const [alias, entry] of Object.entries(lock.integrations)) {\n const cloudEntry = cloud.integrations[alias]\n if (!cloudEntry) {\n delta.addedInLock.push({ type: 'integration', alias, name: entry.name, version: entry.version })\n } else if (!jsonEqual(entry, cloudEntry)) {\n delta.changedInLock.push({ type: 'integration', alias, field: 'unspecified' })\n }\n }\n for (const [alias, entry] of Object.entries(cloud.integrations)) {\n if (!lock.integrations[alias]) {\n delta.removedInLock.push({ type: 'integration', alias, name: entry.name, version: entry.version })\n }\n }\n for (const [alias, entry] of Object.entries(lock.plugins)) {\n const cloudEntry = cloud.plugins[alias]\n if (!cloudEntry) {\n delta.addedInLock.push({ type: 'plugin', alias, name: entry.name, version: entry.version })\n } else if (!jsonEqual(entry, cloudEntry)) {\n delta.changedInLock.push({ type: 'plugin', alias, field: 'unspecified' })\n }\n }\n for (const [alias, entry] of Object.entries(cloud.plugins)) {\n if (!lock.plugins[alias]) {\n delta.removedInLock.push({ type: 'plugin', alias, name: entry.name, version: entry.version })\n }\n }\n const lockReflectsCloud =\n delta.addedInLock.length === 0 && delta.removedInLock.length === 0 && delta.changedInLock.length === 0\n return { target: this.env, lockReflectsCloud, delta }\n }\n\n async sync(opts?: { dryRun?: boolean }): Promise<SyncResult> {\n const previous = await this.lockFile.read()\n const cloud = await this.readCloudAsLockShape(previous)\n\n const added: SyncResult['added'] = []\n const removed: SyncResult['removed'] = []\n const updated: SyncResult['updated'] = []\n\n for (const [alias, entry] of Object.entries(cloud.integrations)) {\n const prev = previous.integrations[alias]\n if (!prev) added.push({ type: 'integration', alias })\n else if (!jsonEqual(prev, entry)) updated.push({ type: 'integration', alias })\n }\n for (const alias of Object.keys(previous.integrations)) {\n if (!cloud.integrations[alias]) removed.push({ type: 'integration', alias })\n }\n for (const [alias, entry] of Object.entries(cloud.plugins)) {\n const prev = previous.plugins[alias]\n if (!prev) added.push({ type: 'plugin', alias })\n else if (!jsonEqual(prev, entry)) updated.push({ type: 'plugin', alias })\n }\n for (const alias of Object.keys(previous.plugins)) {\n if (!cloud.plugins[alias]) removed.push({ type: 'plugin', alias })\n }\n\n if (!opts?.dryRun) {\n await this.lockFile.write({ ...previous, integrations: cloud.integrations, plugins: cloud.plugins })\n }\n\n return { target: this.env, added, removed, updated, dryRun: opts?.dryRun ?? false }\n }\n\n async apply(opts?: { dryRun?: boolean; yes?: boolean }): Promise<ApplyResult> {\n const lock = await this.lockFile.read()\n const cloud = await this.readCloudAsLockShape(lock)\n\n const actions: ApplyAction[] = []\n const errors: ApplyResult['errors'] = []\n\n for (const [alias, entry] of Object.entries(lock.integrations)) {\n const c = cloud.integrations[alias]\n if (!c) {\n actions.push({ type: 'integration', alias, action: 'install' })\n } else if (c.version !== entry.version) {\n actions.push({ type: 'integration', alias, action: 'upgrade' })\n } else {\n if (c.enabled !== entry.enabled)\n actions.push({ type: 'integration', alias, action: entry.enabled ? 'enable' : 'disable' })\n if (!jsonEqual(c.config, entry.config)) actions.push({ type: 'integration', alias, action: 'reconfigure' })\n }\n }\n for (const alias of Object.keys(cloud.integrations)) {\n if (!lock.integrations[alias]) actions.push({ type: 'integration', alias, action: 'uninstall' })\n }\n for (const [alias, entry] of Object.entries(lock.plugins)) {\n const c = cloud.plugins[alias]\n if (!c) {\n actions.push({ type: 'plugin', alias, action: 'install' })\n } else if (c.version !== entry.version) {\n actions.push({ type: 'plugin', alias, action: 'upgrade' })\n } else {\n if (c.enabled !== entry.enabled)\n actions.push({ type: 'plugin', alias, action: entry.enabled ? 'enable' : 'disable' })\n if (!jsonEqual(c.config, entry.config) || !jsonEqual(c.dependencies, entry.dependencies))\n actions.push({ type: 'plugin', alias, action: 'reconfigure' })\n }\n }\n for (const alias of Object.keys(cloud.plugins)) {\n if (!lock.plugins[alias]) actions.push({ type: 'plugin', alias, action: 'uninstall' })\n }\n\n if (opts?.dryRun) {\n return { target: this.env, applied: [], skipped: actions, errors: [], dryRun: true }\n }\n\n if (actions.length === 0) {\n return { target: this.env, applied: [], skipped: [], errors, dryRun: false }\n }\n\n if (!opts?.yes && this.env === 'prod') {\n throw new DependencyError({\n code: 'PROD_CONFIRMATION_REQUIRED',\n message: 'Apply targets production. Pass yes: true to confirm.',\n details: { planned: actions },\n })\n }\n\n if (!opts?.yes && actions.some((a) => a.action === 'uninstall')) {\n throw new DependencyError({\n code: 'UNINSTALL_REQUIRES_CONFIRMATION',\n message: 'Apply would uninstall resources from cloud. Pass yes: true to confirm.',\n details: { destructive: actions.filter((a) => a.action === 'uninstall') },\n })\n }\n\n const order: ApplyAction['action'][] = ['uninstall', 'upgrade', 'install', 'reconfigure', 'enable', 'disable']\n // For installs, integrations before plugins (plugins depend on integrations).\n // For uninstalls, plugins before integrations (mirror of install order — avoid\n // removing an integration that a plugin still depends on).\n function typeWeight(action: string, type: 'integration' | 'plugin' | 'interface'): number {\n if (action === 'uninstall') return type === 'plugin' ? 0 : 1\n return type === 'integration' ? 0 : 1\n }\n const sorted = [...actions].sort((a, b) => {\n const verbDiff = order.indexOf(a.action) - order.indexOf(b.action)\n if (verbDiff !== 0) return verbDiff\n return typeWeight(a.action, a.type) - typeWeight(b.action, b.type)\n })\n\n const applied: ApplyAction[] = []\n const appliedKeys = new Set<string>()\n for (const a of sorted) {\n try {\n const key = `${a.type}:${a.alias}`\n if (a.action === 'uninstall') {\n if (a.type === 'integration')\n await this.integrationResolver.removeFromCloud({ botId: this.botId, alias: a.alias })\n else await this.pluginResolver.removeFromCloud({ botId: this.botId, alias: a.alias })\n } else if (!appliedKeys.has(key)) {\n const entry = a.type === 'integration' ? lock.integrations[a.alias]! : lock.plugins[a.alias]!\n await this.applyEntry(a.type, a.alias, entry, lock)\n appliedKeys.add(key)\n }\n applied.push(a)\n } catch (err) {\n const code = (err as DependencyError).code ?? 'INVALID_CONFIG'\n errors.push({ action: a, code, message: (err as Error).message })\n }\n }\n\n await this.refreshLockFromCloud()\n return { target: this.env, applied, skipped: [], errors, dryRun: false }\n }\n\n async copy(opts: { from: Environment; to: Environment; dryRun?: boolean; yes?: boolean }): Promise<ApplyResult> {\n if (opts.from === opts.to) {\n throw new DependencyError({ code: 'SAME_SOURCE_TARGET', message: '--from and --to must be different' })\n }\n if (this.env !== opts.to) {\n throw new DependencyError({\n code: 'INVALID_CONFIG',\n message: `DependencyManager constructed with env='${this.env}' but copy targets '${opts.to}'`,\n })\n }\n const sourceLock = new LockFile({ projectPath: this.projectPath, env: opts.from })\n if (!(await sourceLock.exists())) {\n throw new DependencyError({\n code: 'SOURCE_LOCK_MISSING',\n message: `Source lock file dependencies.${opts.from}.lock.json does not exist`,\n })\n }\n const sourceData = await sourceLock.read()\n const targetLockExists = await this.lockFile.exists()\n const targetLock = await this.lockFile.read()\n\n // Snapshot the original target lock so we can restore it on dry-run or on\n // non-recoverable apply failure. We always write the source data into the\n // target lock file so that apply() reads the correct baseline when computing\n // its diff.\n const snapshot = JSON.stringify(targetLock)\n const merged = { ...targetLock, integrations: sourceData.integrations, plugins: sourceData.plugins }\n await this.lockFile.write(merged)\n\n try {\n const result = await this.apply({ dryRun: opts.dryRun, yes: opts.yes })\n if (opts.dryRun) {\n // Restore the original target lock on dry-run to preserve the \"no disk changes\" guarantee.\n if (targetLockExists) {\n await this.lockFile.write(JSON.parse(snapshot))\n } else {\n await this.lockFile.delete()\n }\n }\n return result\n } catch (err) {\n // Restore the original target lock so the user isn't left with source data\n // in their target lock file after a failed apply.\n if (targetLockExists) {\n await this.lockFile.write(JSON.parse(snapshot)).catch(() => {})\n } else {\n await this.lockFile.delete().catch(() => {})\n }\n throw err\n }\n }\n\n private async readCloudAsLockShape(previousLock?: LockFileData): Promise<{\n integrations: Record<string, IntegrationLockEntry>\n plugins: Record<string, PluginLockEntry>\n }> {\n const { bot } = await this.client.getBot({ id: this.botId })\n const previous = previousLock ?? (await this.lockFile.read())\n return this.cloudToLockShape(bot, previous)\n }\n\n private cloudToLockShape(\n bot: Awaited<ReturnType<Client['getBot']>>['bot'],\n previous: LockFileData\n ): {\n integrations: Record<string, IntegrationLockEntry>\n plugins: Record<string, PluginLockEntry>\n } {\n const integrations: Record<string, IntegrationLockEntry> = {}\n const usedIntegrationAliases = new Set<string>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- cloud bot integrations shape is untyped\n for (const [cloudAlias, c] of Object.entries((bot.integrations ?? {}) as Record<string, any>)) {\n const cloudName = typeof c.name === 'string' ? c.name : undefined\n const alias = this.chooseCloudAlias({\n cloudAlias,\n cloudName,\n previous: previous.integrations,\n used: usedIntegrationAliases,\n })\n usedIntegrationAliases.add(alias)\n const entry = this.integrationResolver.toLockEntry(c)\n entry.config = preserveEnvRefs(previous.integrations[alias]?.config, entry.config) as Record<string, unknown>\n integrations[alias] = entry\n }\n\n const plugins: Record<string, PluginLockEntry> = {}\n const usedPluginAliases = new Set<string>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- cloud bot plugins shape is untyped\n for (const [cloudAlias, c] of Object.entries((bot.plugins ?? {}) as Record<string, any>)) {\n const cloudName = typeof c.name === 'string' ? c.name : undefined\n const alias = this.chooseCloudAlias({\n cloudAlias,\n cloudName,\n previous: previous.plugins,\n used: usedPluginAliases,\n })\n usedPluginAliases.add(alias)\n const entry = this.pluginResolver.toLockEntry(c)\n entry.config = preserveEnvRefs(previous.plugins[alias]?.config, entry.config) as Record<string, unknown>\n plugins[alias] = entry\n }\n\n return { integrations, plugins }\n }\n\n private chooseCloudAlias<T extends { name: string }>(opts: {\n cloudAlias: string\n cloudName: string | undefined\n previous: Record<string, T>\n used: Set<string>\n }): string {\n if (isFriendlyAlias(opts.cloudAlias) && opts.previous[opts.cloudAlias] && !opts.used.has(opts.cloudAlias)) {\n return opts.cloudAlias\n }\n\n if (opts.cloudName) {\n const match = Object.entries(opts.previous).find(\n ([alias, entry]) => !opts.used.has(alias) && entry.name === opts.cloudName\n )\n if (match) return match[0]\n }\n\n return generateFriendlyAlias(opts.cloudName, opts.cloudAlias, opts.used)\n }\n}\n\nfunction formatMissingDependencySuggestion(opts: {\n interfaceName: string\n pluginInterfaceAlias: string\n implementers: Array<{ name: string; version: string; title?: string }>\n}): string {\n if (opts.implementers.length === 0) {\n return (\n `Install an integration that implements '${opts.interfaceName}' first, ` +\n `then retry — or pass --dep ${opts.pluginInterfaceAlias}=<alias> if you already have one.`\n )\n }\n const lines = [`Hub integrations that implement '${opts.interfaceName}':`]\n for (const i of opts.implementers) {\n const title = i.title && i.title !== i.name ? ` — ${i.title}` : ''\n lines.push(` • ${i.name}@${i.version}${title}`)\n }\n lines.push('')\n lines.push(`Install one and retry: adk integrations add ${opts.implementers[0]!.name}`)\n lines.push(\n `Or, if you have an installed integration that implements this: --dep ${opts.pluginInterfaceAlias}=<alias>`\n )\n return lines.join('\\n')\n}\n\n/**\n * Detects AJV-shaped \"data must have required property '<name>'\" errors from Cloud\n * (e.g. InvalidDataFormatError) and returns the missing field names. Returns null\n * if the error is not a missing-required-fields validation error.\n */\nfunction extractMissingRequiredFields(err: unknown): string[] | null {\n const message = err instanceof Error ? err.message : typeof err === 'string' ? err : ''\n if (!message.includes('required property')) return null\n const fields = new Set<string>()\n const re = /required property ['\"]([^'\"]+)['\"]/g\n let match: RegExpExecArray | null\n while ((match = re.exec(message)) !== null) {\n if (match[1]) fields.add(match[1])\n }\n return fields.size > 0 ? [...fields] : null\n}\n\nfunction preserveEnvRefs(previous: unknown, next: unknown): unknown {\n if (typeof previous === 'string' && /\\$\\{env:[A-Z0-9_]+\\}/.test(previous)) {\n return previous\n }\n if (Array.isArray(next)) {\n const prevArray = Array.isArray(previous) ? previous : []\n return next.map((value, index) => preserveEnvRefs(prevArray[index], value))\n }\n if (next && typeof next === 'object') {\n const prevObject = previous && typeof previous === 'object' ? (previous as Record<string, unknown>) : {}\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(next)) {\n out[key] = preserveEnvRefs(prevObject[key], value)\n }\n return out\n }\n return next\n}\n",
|
|
44
|
+
"const FRIENDLY_ALIAS_RE = /^[a-z0-9_-]{2,100}$/\n\n/**\n * Botpress internal ID prefixes that are never user-facing friendly aliases.\n * Aliases that start with one of these are always considered unfriendly even\n * though they may otherwise satisfy the character-class regex.\n */\nconst BP_INTERNAL_ID_PREFIXES = ['intver_', 'plgver_', 'int_', 'plg_']\n\n/**\n * Returns true if the alias looks like a Botpress platform ID (e.g. `intver_01JK…`)\n * rather than a human-authored name.\n */\nfunction isBotpressInternalId(alias: string): boolean {\n return BP_INTERNAL_ID_PREFIXES.some((prefix) => alias.startsWith(prefix))\n}\n\nexport function isFriendlyAlias(alias: string): boolean {\n return FRIENDLY_ALIAS_RE.test(alias) && !isBotpressInternalId(alias)\n}\n\n/**\n * Derive a friendly alias for a cloud-side integration/plugin entry.\n *\n * Strategy:\n * 1. If the cloud's alias is already friendly (matches the regex and is not a\n * Botpress-internal ID like `intver_*`), use it as-is.\n * 2. Otherwise, sanitize cloud.name (strip namespace prefix, lowercase, replace\n * non-conforming chars with `-`).\n * 3. Disambiguate against `used` with a numeric suffix.\n */\nexport function generateFriendlyAlias(cloudName: string | undefined, cloudAlias: string, used: Set<string>): string {\n if (isFriendlyAlias(cloudAlias) && !used.has(cloudAlias)) return cloudAlias\n\n const base = cloudName?.split('/').at(-1) ?? cloudAlias\n const sanitized = base.toLowerCase().replace(/[^a-z0-9_-]/g, '-')\n let candidate = sanitized\n let n = 2\n while (used.has(candidate)) {\n candidate = `${sanitized}-${n}`\n n++\n }\n return candidate\n}\n",
|
|
45
|
+
"import type { Client } from '@botpress/client'\nimport type { IntegrationRegistry } from '../registry/integration-registry.js'\nimport type { IntegrationLockEntry } from '../types.js'\nimport { DependencyError } from '../errors.js'\nimport { substituteEnvRefs } from '../env-substitution.js'\n\ninterface CloudIntegration {\n name?: string\n version?: string\n enabled?: boolean\n configuration?: Record<string, unknown>\n}\n\nexport interface IntegrationResolverOptions {\n registry: IntegrationRegistry\n client: Client\n}\n\nexport class IntegrationResolver {\n private readonly registry: IntegrationRegistry\n private readonly client: Client\n\n constructor(opts: IntegrationResolverOptions) {\n this.registry = opts.registry\n this.client = opts.client\n }\n\n toLockEntry(cloud: CloudIntegration): IntegrationLockEntry {\n return {\n name: cloud.name ?? '',\n version: cloud.version ?? '0.0.0',\n enabled: Boolean(cloud.enabled),\n config: cloud.configuration ?? {},\n }\n }\n\n async applyToCloud(opts: {\n botId: string\n alias: string\n entry: IntegrationLockEntry\n env?: Record<string, string | undefined>\n }): Promise<void> {\n // Resolve integrationId from the registry spec. IntegrationDefinition extends Integration which has `.id`.\n const spec = await this.registry.getSpec(opts.entry.name, opts.entry.version)\n const integrationId = spec.id\n if (!integrationId) {\n throw new DependencyError({\n code: 'INTEGRATION_NOT_FOUND',\n message: `Could not resolve integrationId for ${opts.entry.name}@${opts.entry.version}`,\n })\n }\n\n const resolvedConfig = opts.env ? substituteEnvRefs(opts.entry.config, opts.env) : opts.entry.config\n\n await this.client.updateBot({\n id: opts.botId,\n integrations: {\n [opts.alias]: {\n integrationId,\n enabled: opts.entry.enabled,\n configuration: resolvedConfig as Record<string, unknown>,\n },\n },\n })\n }\n\n async removeFromCloud(opts: { botId: string; alias: string }): Promise<void> {\n await this.client.updateBot({\n id: opts.botId,\n integrations: { [opts.alias]: null },\n })\n }\n}\n",
|
|
46
|
+
"import { DependencyError } from './errors.js'\n\nconst ENV_REF_RE = /\\$\\{env:([A-Z0-9_]+)\\}/g\n\nexport function substituteEnvRefs<T>(value: T, env: Record<string, string | undefined>): T {\n if (typeof value === 'string') {\n return value.replace(ENV_REF_RE, (_match, key: string) => {\n const v = env[key]\n if (v === undefined) {\n throw new DependencyError({\n code: 'INVALID_CONFIG',\n message: `Env var ${key} referenced in config but not set`,\n details: { key },\n suggestion: `Set ${key} in your .env or environment`,\n })\n }\n return v\n }) as unknown as T\n }\n if (Array.isArray(value)) return value.map((v) => substituteEnvRefs(v, env)) as unknown as T\n if (value && typeof value === 'object') {\n const obj = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(obj)) out[k] = substituteEnvRefs(v, env)\n return out as unknown as T\n }\n return value\n}\n\nexport function collectEnvRefs(value: unknown, into: Set<string> = new Set()): Set<string> {\n if (typeof value === 'string') {\n for (const m of value.matchAll(ENV_REF_RE)) into.add(m[1]!)\n return into\n }\n if (Array.isArray(value)) {\n for (const v of value) collectEnvRefs(v, into)\n return into\n }\n if (value && typeof value === 'object') {\n for (const v of Object.values(value as Record<string, unknown>)) collectEnvRefs(v, into)\n }\n return into\n}\n",
|
|
47
|
+
"import type { Client } from '@botpress/client'\nimport type { PluginRegistry } from '../registry/plugin-registry.js'\nimport type { IntegrationRegistry } from '../registry/integration-registry.js'\nimport type { LockFileData, PluginLockEntry } from '../types.js'\nimport { DependencyError } from '../errors.js'\nimport { substituteEnvRefs } from '../env-substitution.js'\n\ninterface CloudPlugin {\n name?: string\n version?: string\n enabled?: boolean\n configuration?: Record<string, unknown>\n interfaces?: Record<string, { integrationAlias?: string; integrationInterfaceAlias?: string }>\n}\n\ninterface PluginSpec {\n name: string\n version?: string\n dependencies?: { interfaces?: Record<string, { name: string }> }\n}\n\nexport interface PluginResolverOptions {\n registry: PluginRegistry\n integrationRegistry: IntegrationRegistry\n client: Client\n}\n\nexport class PluginResolver {\n private readonly registry: PluginRegistry\n private readonly integrationRegistry: IntegrationRegistry\n private readonly client: Client\n\n constructor(opts: PluginResolverOptions) {\n this.registry = opts.registry\n this.integrationRegistry = opts.integrationRegistry\n this.client = opts.client\n }\n\n toLockEntry(cloud: CloudPlugin): PluginLockEntry {\n const dependencies: Record<string, { integrationAlias: string }> = {}\n for (const [ifaceAlias, dep] of Object.entries(cloud.interfaces ?? {})) {\n if (dep.integrationAlias) {\n dependencies[ifaceAlias] = { integrationAlias: dep.integrationAlias }\n }\n }\n return {\n name: cloud.name ?? '',\n version: cloud.version ?? '0.0.0',\n enabled: cloud.enabled ?? true,\n config: cloud.configuration ?? {},\n dependencies,\n }\n }\n\n async applyToCloud(opts: {\n botId: string\n alias: string\n entry: PluginLockEntry\n lock: LockFileData\n env?: Record<string, string | undefined>\n }): Promise<void> {\n const pluginSpec = (await this.registry.getSpec(opts.entry.name, opts.entry.version)) as PluginSpec & {\n id?: string\n }\n const requiredInterfaces = pluginSpec.dependencies?.interfaces ?? {}\n const resolvedInterfaces: Record<\n string,\n { integrationId: string; integrationAlias: string; integrationInterfaceAlias: string }\n > = {}\n\n for (const [pluginIfaceAlias, requirement] of Object.entries(requiredInterfaces)) {\n const dep = opts.entry.dependencies[pluginIfaceAlias]\n if (!dep) {\n throw new DependencyError({\n code: 'MISSING_DEPENDENCY',\n message: `Plugin '${opts.alias}' is missing dependency '${pluginIfaceAlias}' (needs an integration implementing '${requirement.name}')`,\n details: { plugin: opts.alias, pluginInterfaceAlias: pluginIfaceAlias, interfaceName: requirement.name },\n })\n }\n const integration = opts.lock.integrations[dep.integrationAlias]\n if (!integration) {\n throw new DependencyError({\n code: 'MISSING_DEPENDENCY',\n message: `Plugin '${opts.alias}' references integration alias '${dep.integrationAlias}' which is not installed`,\n details: { plugin: opts.alias, integrationAlias: dep.integrationAlias },\n suggestion: `Run: adk integrations add ${dep.integrationAlias}`,\n })\n }\n const integrationSpec = await this.integrationRegistry.getSpec(integration.name, integration.version)\n const integrationIfaceAlias = Object.entries(integrationSpec.interfaces ?? {}).find(\n ([, def]) => def.name === requirement.name\n )?.[0]\n if (!integrationIfaceAlias) {\n throw new DependencyError({\n code: 'INTERFACE_NOT_IMPLEMENTED',\n message: `Integration '${integration.name}' does not implement interface '${requirement.name}' required by plugin '${opts.alias}'`,\n details: { integration: integration.name, interfaceName: requirement.name },\n })\n }\n resolvedInterfaces[pluginIfaceAlias] = {\n integrationId: integrationSpec.id,\n integrationAlias: dep.integrationAlias,\n integrationInterfaceAlias: integrationIfaceAlias,\n }\n }\n\n const pluginId = pluginSpec.id\n if (!pluginId) {\n throw new DependencyError({\n code: 'PLUGIN_NOT_FOUND',\n message: `Could not resolve plugin id for ${opts.entry.name}@${opts.entry.version}`,\n })\n }\n\n const resolvedConfig = opts.env ? substituteEnvRefs(opts.entry.config, opts.env) : opts.entry.config\n\n await this.client.updateBot({\n id: opts.botId,\n plugins: {\n [opts.alias]: {\n id: pluginId,\n enabled: opts.entry.enabled,\n configuration: resolvedConfig as Record<string, unknown>,\n interfaces: resolvedInterfaces,\n },\n },\n })\n }\n\n async removeFromCloud(opts: { botId: string; alias: string }): Promise<void> {\n await this.client.updateBot({ id: opts.botId, plugins: { [opts.alias]: null } })\n }\n}\n",
|
|
48
|
+
"import { IntegrationManager, type IntegrationManagerOptions } from '../../integrations/manager.js'\nimport type { IntegrationDefinition, IntegrationRef } from '../../integrations/types.js'\n\nexport interface IntegrationRegistryOptions {\n /** Optional: pass a pre-built manager. If omitted, a default is constructed. */\n manager?: IntegrationManager\n /** Optional: manager options passed to constructor when manager is not provided. */\n managerOptions?: IntegrationManagerOptions\n}\n\nexport class IntegrationRegistry {\n private readonly manager: IntegrationManager\n\n constructor(opts: IntegrationRegistryOptions = {}) {\n this.manager = opts.manager ?? new IntegrationManager(opts.managerOptions)\n }\n\n async getSpec(name: string, version?: string): Promise<IntegrationDefinition> {\n const ref: IntegrationRef = {\n name,\n version: version ?? 'latest',\n fullName: name,\n }\n return this.manager.fetchIntegration(ref)\n }\n\n async search(_query: string): Promise<unknown[]> {\n return this.manager.searchIntegrations(_query)\n }\n\n async findImplementersOfInterface(interfaceName: string, limit?: number): Promise<unknown[]> {\n return this.manager.findImplementersOfInterface(interfaceName, limit)\n }\n\n async listVersions(name: string): Promise<string[]> {\n return this.manager.listIntegrationVersions(name)\n }\n}\n",
|
|
49
|
+
"import type { Client } from '@botpress/client'\nimport { getProjectClient, type Credentials, type ProjectCredentialsContext } from '../auth/index.js'\nimport { Dependencies, ValidationError } from '../agent-project/types.js'\nimport { PluginDefinition, PluginRef, ParsedPlugin } from './types.js'\nimport { EnhancedPluginCache } from './enhanced-cache.js'\nimport { PluginParser } from '../agent-project/dependencies-parser.js'\nimport { ValidationErrors } from '../agent-project/validation-errors.js'\nimport {\n collectCatalogSearchResult,\n getSortedCatalogSearchResults,\n getSortedVersions,\n type RankedCatalogEntry,\n} from '../utils/search-ranking.js'\n\nexport interface PluginSearchResult {\n id: string\n name: string\n version: string\n createdAt: string\n updatedAt: string\n title: string\n description: string\n iconUrl: string\n readmeUrl: string\n public: boolean\n visibility: 'public' | 'private' | 'unlisted'\n lifecycleStatus: 'published' | 'deprecated'\n}\n\nexport interface PluginManagerOptions {\n noCache?: boolean\n project?: ProjectCredentialsContext\n apiUrl?: string\n workspaceId?: string\n credentials?: Credentials\n}\n\nexport class PluginManager {\n private cache: EnhancedPluginCache\n private options: PluginManagerOptions\n private client?: Client\n\n constructor(options: PluginManagerOptions = {}) {\n this.options = options\n this.cache = new EnhancedPluginCache(options.noCache || false)\n }\n\n private async getClient(): Promise<Client> {\n if (!this.client) {\n this.client = await getProjectClient({\n project: this.options.project,\n credentials: this.options.credentials,\n apiUrl: this.options.apiUrl,\n workspaceId: this.options.workspaceId,\n headers: {\n 'x-multiple-integrations': 'true',\n },\n })\n }\n return this.client\n }\n\n /**\n * Load and validate all plugins from dependencies\n */\n async loadPlugins(dependencies: Dependencies): Promise<{\n plugins: ParsedPlugin[]\n errors: ValidationError[]\n warnings: ValidationError[]\n }> {\n const errors: ValidationError[] = []\n const warnings: ValidationError[] = []\n\n // Parse plugins from dependencies\n const parseResult = PluginParser.parsePlugins(dependencies)\n const plugins = parseResult.plugins\n errors.push(...parseResult.errors)\n\n // Check for duplicates\n const duplicateWarnings = PluginParser.checkDuplicates(plugins)\n warnings.push(...duplicateWarnings)\n\n // Fetch plugin definitions in parallel\n const fetchPromises = plugins.map(async (plugin) => {\n try {\n plugin.definition = await this.fetchPlugin(plugin.ref)\n } catch (error) {\n if (error instanceof Error && error.message.includes('version')) {\n errors.push(ValidationErrors.pluginVersionError(plugin.alias, error.message))\n } else {\n const errorMessage = error instanceof Error ? error.message : undefined\n errors.push(ValidationErrors.unknownPlugin(plugin.alias, plugin.ref.fullName, errorMessage))\n }\n }\n })\n\n await Promise.all(fetchPromises)\n\n return { plugins, errors, warnings }\n }\n\n /**\n * Fetch plugin definition from API or cache (public Hub only)\n */\n public async fetchPlugin(ref: PluginRef): Promise<PluginDefinition> {\n // Level 1: Check version resolution cache\n const cachedResolution = await this.cache.getResolution(ref.name, ref.version)\n\n if (cachedResolution) {\n // Level 2: Check definition cache\n const cachedDefinition = await this.cache.getDefinition(cachedResolution.pluginId, cachedResolution.updatedAt)\n\n if (cachedDefinition) {\n return cachedDefinition\n }\n }\n\n // No cache hit, fetch from API\n const client = await this.getClient()\n const plugin = await this._findPublicPlugin(client, ref)\n\n if (!plugin) {\n throw new Error(`Plugin \"${ref.name}\" not found on the Botpress Hub`)\n }\n\n // Cache Level 1: Version resolution\n await this.cache.setResolution(ref.name, ref.version, plugin.id, plugin.updatedAt)\n\n // Cache Level 2: Definition\n await this.cache.setDefinition(plugin.id, plugin.updatedAt, plugin)\n\n return plugin\n }\n\n /**\n * Search public plugins in the Botpress hub.\n *\n * The public plugin list API does not expose server-side search yet, so this\n * filters the catalog client-side. The catalog is small, and callers cap\n * results to keep CLI output compact.\n */\n public async searchPlugins(query: string, limit: number = 20): Promise<PluginSearchResult[]> {\n const client = await this.getClient()\n const results = new Map<string, RankedCatalogEntry<PluginSearchResult>>()\n\n for await (const plugin of client.list.publicPlugins({})) {\n collectCatalogSearchResult(results, plugin, query)\n }\n\n return getSortedCatalogSearchResults(results, limit)\n }\n\n /**\n * List known public versions for a plugin name.\n */\n public async listPluginVersions(name: string): Promise<string[]> {\n const client = await this.getClient()\n const versions = new Set<string>()\n\n for await (const plugin of client.list.publicPlugins({ name })) {\n versions.add(plugin.version)\n }\n\n return getSortedVersions(versions)\n }\n\n /**\n * Find public plugin on the Botpress Hub\n */\n private async _findPublicPlugin(client: Client, ref: PluginRef): Promise<PluginDefinition | undefined> {\n try {\n const response = await client.getPublicPlugin({\n name: ref.name,\n version: ref.version,\n })\n return response.plugin\n } catch (error) {\n if (this._isResourceNotFoundError(error)) {\n return undefined\n }\n throw error\n }\n }\n\n private _isResourceNotFoundError(error: unknown): boolean {\n if (error && typeof error === 'object' && 'type' in error) {\n return (error as { type: unknown }).type === 'ResourceNotFound'\n }\n return false\n }\n\n /**\n * Get cache statistics\n */\n async getCacheStats(): Promise<{ count: number; sizeBytes: number }> {\n const stats = await this.cache.getStats()\n return {\n count: stats.resolutions.count + stats.definitions.count,\n sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes,\n }\n }\n\n /**\n * Clear plugin cache\n */\n async clearCache(): Promise<void> {\n await this.cache.clear()\n }\n}\n",
|
|
50
|
+
"import fs from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { PluginDefinition } from './types.js'\n\ninterface VersionResolution {\n pluginId: string\n updatedAt: string\n cachedAt: string\n}\n\ninterface CachedDefinition {\n definition: PluginDefinition\n cachedAt: string\n}\n\nexport class EnhancedPluginCache {\n private cacheDir: string\n private resolutionsDir: string\n private definitionsDir: string\n private noCache: boolean\n\n constructor(noCache: boolean = false) {\n this.noCache = noCache\n this.cacheDir = path.join(os.homedir(), '.adk', 'cache', 'plugins')\n this.resolutionsDir = path.join(this.cacheDir, 'resolutions')\n this.definitionsDir = path.join(this.cacheDir, 'definitions')\n }\n\n private async ensureCacheDirs(): Promise<void> {\n await fs.mkdir(this.resolutionsDir, { recursive: true })\n await fs.mkdir(this.definitionsDir, { recursive: true })\n }\n\n /**\n * Get version resolution from cache (name@version → pluginId + updatedAt)\n * Returns null if cache miss or expired (5 minutes)\n */\n async getResolution(name: string, version: string): Promise<VersionResolution | null> {\n if (this.noCache) {\n return null\n }\n\n try {\n const key = this.getResolutionKey(name, version)\n const cachePath = path.join(this.resolutionsDir, `${key}.json`)\n\n const data = await fs.readFile(cachePath, 'utf-8')\n const resolution: VersionResolution = JSON.parse(data)\n\n // Check if cache is expired (5 minutes)\n const cachedAt = new Date(resolution.cachedAt)\n const now = new Date()\n const ageMinutes = (now.getTime() - cachedAt.getTime()) / (1000 * 60)\n\n if (ageMinutes > 5) {\n return null\n }\n\n return resolution\n } catch {\n return null\n }\n }\n\n /**\n * Cache version resolution (name@version → pluginId + updatedAt)\n */\n async setResolution(name: string, version: string, pluginId: string, updatedAt: string): Promise<void> {\n await this.ensureCacheDirs()\n\n const key = this.getResolutionKey(name, version)\n const cachePath = path.join(this.resolutionsDir, `${key}.json`)\n\n const resolution: VersionResolution = {\n pluginId,\n updatedAt,\n cachedAt: new Date().toISOString(),\n }\n\n await fs.writeFile(cachePath, JSON.stringify(resolution, null, 2))\n }\n\n /**\n * Get plugin definition from cache (pluginId + updatedAt → definition)\n * Never expires for same pluginId + updatedAt (immutable)\n */\n async getDefinition(pluginId: string, updatedAt: string): Promise<PluginDefinition | null> {\n if (this.noCache) {\n return null\n }\n\n try {\n const key = this.getDefinitionKey(pluginId, updatedAt)\n const cachePath = path.join(this.definitionsDir, `${key}.json`)\n\n const data = await fs.readFile(cachePath, 'utf-8')\n const cached: CachedDefinition = JSON.parse(data)\n\n return cached.definition\n } catch {\n return null\n }\n }\n\n /**\n * Cache plugin definition (pluginId + updatedAt → definition)\n */\n async setDefinition(pluginId: string, updatedAt: string, definition: PluginDefinition): Promise<void> {\n await this.ensureCacheDirs()\n\n const key = this.getDefinitionKey(pluginId, updatedAt)\n const cachePath = path.join(this.definitionsDir, `${key}.json`)\n\n const cached: CachedDefinition = {\n definition,\n cachedAt: new Date().toISOString(),\n }\n\n await fs.writeFile(cachePath, JSON.stringify(cached, null, 2))\n }\n\n /**\n * Clear all caches\n */\n async clear(): Promise<void> {\n try {\n const resolutionFiles = await fs.readdir(this.resolutionsDir)\n await Promise.all(resolutionFiles.map((file) => fs.unlink(path.join(this.resolutionsDir, file))))\n\n const definitionFiles = await fs.readdir(this.definitionsDir)\n await Promise.all(definitionFiles.map((file) => fs.unlink(path.join(this.definitionsDir, file))))\n } catch {\n // Ignore errors if directories don't exist\n }\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<{\n resolutions: { count: number; sizeBytes: number }\n definitions: { count: number; sizeBytes: number }\n }> {\n const getDirectoryStats = async (dir: string) => {\n try {\n const files = await fs.readdir(dir)\n let totalSize = 0\n\n for (const file of files) {\n const stats = await fs.stat(path.join(dir, file))\n totalSize += stats.size\n }\n\n return {\n count: files.length,\n sizeBytes: totalSize,\n }\n } catch {\n return { count: 0, sizeBytes: 0 }\n }\n }\n\n const [resolutions, definitions] = await Promise.all([\n getDirectoryStats(this.resolutionsDir),\n getDirectoryStats(this.definitionsDir),\n ])\n\n return { resolutions, definitions }\n }\n\n private getResolutionKey(name: string, version: string): string {\n const key = `${name}_${version}`\n return key.replace(/[^a-zA-Z0-9_-]/g, '_')\n }\n\n private getDefinitionKey(pluginId: string, updatedAt: string): string {\n const key = `${pluginId}_${updatedAt}`\n return key.replace(/[^a-zA-Z0-9_-]/g, '_')\n }\n}\n",
|
|
51
|
+
"import { PluginManager, type PluginManagerOptions } from '../../plugins/manager.js'\nimport type { PluginDefinition, PluginRef } from '../../plugins/types.js'\n\nexport interface PluginRegistryOptions {\n /** Optional: pass a pre-built manager. If omitted, a default is constructed. */\n manager?: PluginManager\n /** Optional: manager options passed to constructor when manager is not provided. */\n managerOptions?: PluginManagerOptions\n}\n\nexport class PluginRegistry {\n private readonly manager: PluginManager\n\n constructor(opts: PluginRegistryOptions = {}) {\n this.manager = opts.manager ?? new PluginManager(opts.managerOptions)\n }\n\n async getSpec(name: string, version?: string): Promise<PluginDefinition> {\n const ref: PluginRef = {\n name,\n version: version ?? 'latest',\n fullName: name,\n }\n return this.manager.fetchPlugin(ref)\n }\n\n async search(_query: string): Promise<unknown[]> {\n return this.manager.searchPlugins(_query)\n }\n\n async listVersions(name: string): Promise<string[]> {\n return this.manager.listPluginVersions(name)\n }\n}\n",
|
|
52
|
+
"export { DependencyManager } from './dependency-manager.js'\nexport type { DependencyManagerOptions, ResourceEntry } from './dependency-manager.js'\n\nexport { LockFile } from './lock-file.js'\nexport type { LockFileOptions } from './lock-file.js'\n\nexport {\n type Environment,\n type ResourceType,\n type IntegrationLockEntry,\n type PluginLockEntry,\n type PluginDependencyMapping,\n type LockFileData,\n type AddSpec,\n type ConfigPatch,\n type MutationResult,\n type DiffResult,\n type SyncResult,\n type ApplyAction,\n type ApplyResult,\n type MigrationResult,\n} from './types.js'\n\nexport { DependencyError, DEPENDENCY_ERROR_CODES, DEPENDENCY_WARNING_CODES } from './errors.js'\nexport type { DependencyErrorCode, DependencyWarningCode } from './errors.js'\n\nexport { sortKeysDeep, jsonEqual } from './json-utils.js'\nexport { substituteEnvRefs, collectEnvRefs } from './env-substitution.js'\nexport { rewriteSecrets } from './secrets-rewriter.js'\n\nexport { IntegrationRegistry } from './registry/integration-registry.js'\nexport { PluginRegistry } from './registry/plugin-registry.js'\nexport { InterfaceRegistry } from './registry/interface-registry.js'\nexport type { InterfaceInfo } from './registry/interface-registry.js'\n\nexport { IntegrationResolver } from './resolvers/integration-resolver.js'\nexport { PluginResolver } from './resolvers/plugin-resolver.js'\n\nexport { migrateFromConfig } from './migration.js'\nexport type { MigrateOptions } from './migration.js'\n",
|
|
53
|
+
"import type { DependencyWarningCode } from './errors.js'\n\nconst HEURISTIC_SECRET_PATTERN = /secret|token|key|password|credential/i\nconst EXISTING_REF_PATTERN = /^\\$\\{env:[A-Z0-9_]+\\}$/\n\ninterface SchemaProperty {\n 'x-zui'?: { secret?: boolean }\n}\n\ninterface SchemaLike {\n properties?: Record<string, SchemaProperty>\n}\n\nexport interface RewriteInput {\n alias: string\n config: Record<string, unknown>\n schema?: SchemaLike\n}\n\nexport interface RewriteOutput {\n config: Record<string, unknown>\n envVars: string[]\n warnings: Array<{ code: DependencyWarningCode; message: string }>\n}\n\nexport function rewriteSecrets(input: RewriteInput): RewriteOutput {\n const result: Record<string, unknown> = { ...input.config }\n const envVars: string[] = []\n const warnings: Array<{ code: DependencyWarningCode; message: string }> = []\n\n for (const [field, value] of Object.entries(result)) {\n if (typeof value !== 'string') continue\n if (EXISTING_REF_PATTERN.test(value)) {\n const match = value.match(/^\\$\\{env:([A-Z0-9_]+)\\}$/)\n if (match) envVars.push(match[1]!)\n continue\n }\n const markedSecret = input.schema?.properties?.[field]?.['x-zui']?.secret === true\n const heuristic = !markedSecret && HEURISTIC_SECRET_PATTERN.test(field)\n if (markedSecret || heuristic) {\n const envName = toEnvVar(input.alias, field)\n result[field] = `\\${env:${envName}}`\n envVars.push(envName)\n if (heuristic) {\n warnings.push({\n code: 'HEURISTIC_SECRET_MASKED',\n message: `Heuristically masked ${input.alias}.${field} as \\${env:${envName}}. Confirm and set the env var.`,\n })\n }\n }\n }\n\n return { config: result, envVars, warnings }\n}\n\nfunction toEnvVar(alias: string, field: string): string {\n const norm = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .toUpperCase()\n .replace(/^_+|_+$/g, '')\n return `${norm(alias)}_${norm(field)}`\n}\n",
|
|
54
|
+
"import { BUILTIN_INTERFACES } from '../../constants.js'\n\nexport interface InterfaceInfo {\n alias: string\n name: string\n version: string\n builtin: boolean\n}\n\nexport class InterfaceRegistry {\n async list(): Promise<InterfaceInfo[]> {\n return Object.entries(BUILTIN_INTERFACES).map(([alias, versionString]) => {\n const [name, version] = versionString.split('@')\n return { alias, name: name || alias, version: version || 'latest', builtin: true }\n })\n }\n\n async getInfo(alias: string): Promise<InterfaceInfo | undefined> {\n const all = await this.list()\n return all.find((i) => i.alias === alias)\n }\n}\n",
|
|
55
|
+
"import * as fs from 'fs/promises'\nimport * as path from 'path'\nimport { Project, SyntaxKind } from 'ts-morph'\nimport type { Client } from '@botpress/client'\nimport { LockFile } from './lock-file.js'\nimport { ConfigWriter } from '../agent-project/config-writer.js'\nimport { rewriteSecrets } from './secrets-rewriter.js'\nimport { DependencyError } from './errors.js'\nimport type { Environment, MigrationResult, LockFileData } from './types.js'\nimport type { IntegrationRegistry } from './registry/integration-registry.js'\nimport { AgentProject } from '../agent-project/agent-project.js'\nimport { generateFriendlyAlias } from './alias-utils.js'\n\nexport interface MigrateOptions {\n projectPath: string\n client: Client\n integrationRegistry: IntegrationRegistry\n}\n\nexport async function migrateFromConfig(opts: MigrateOptions): Promise<MigrationResult> {\n const result: MigrationResult = {\n migrated: [],\n envVarsToSet: [],\n warnings: [],\n skipped: [],\n }\n\n // Load agent project to get real bot IDs\n const project = await AgentProject.load(opts.projectPath)\n const info = project.agentInfo\n\n // Check whether agent.config.ts has a non-empty `dependencies` field by\n // parsing the AST. A raw substring search would match comments such as\n // \"// these are the integrations dependencies you need\" — causing a false-positive\n // MIGRATION_CONFLICT when a lock file already exists.\n const declaredAliasesForConflictCheck = await readAliasesFromConfig(opts.projectPath)\n const agentConfigHasDependencies =\n Object.keys(declaredAliasesForConflictCheck.integrations).length > 0 ||\n Object.keys(declaredAliasesForConflictCheck.plugins).length > 0\n\n const envs: Environment[] = ['dev', 'prod']\n\n // If agent info is missing, skip migration for all envs\n if (!info) {\n result.warnings.push({\n code: 'CLOUD_FETCH_PARTIAL',\n message: 'No agent.json found; cannot fetch cloud state for migration.',\n })\n for (const env of envs) {\n result.skipped.push({ env, reason: 'no agent.json' })\n }\n // Still return early but allow optional field stripping (below) to run if config has dependencies\n } else {\n for (const env of envs) {\n const lockFile = new LockFile({ projectPath: opts.projectPath, env })\n if (await lockFile.exists()) {\n if (agentConfigHasDependencies) {\n throw new DependencyError({\n code: 'MIGRATION_CONFLICT',\n message: `Cannot migrate: a lock file (dependencies.${env}.lock.json) already exists alongside the 'dependencies' field in agent.config.ts. Remove one of them before running migration.`,\n })\n }\n result.skipped.push({ env, reason: 'lock file already exists' })\n continue\n }\n\n // Compute botId based on env\n const botId = env === 'dev' ? (info.devId ?? info.botId) : info.botId\n\n // Surface a clear warning when prod has no bot configured, rather than\n // silently failing or emitting a generic CLOUD_FETCH_PARTIAL.\n if (env === 'prod' && !botId) {\n result.warnings.push({\n code: 'NO_PROD_BOT',\n message:\n 'No prod bot configured in agent.json. Only dependencies.dev.lock.json was generated. Use `adk deploy` to create a prod bot.',\n })\n result.skipped.push({ env, reason: 'no prod bot configured' })\n continue\n }\n\n let bot: Awaited<ReturnType<Client['getBot']>>['bot'] | undefined\n try {\n const r = await opts.client.getBot({ id: botId })\n bot = r.bot\n } catch (err) {\n result.warnings.push({\n code: 'CLOUD_FETCH_PARTIAL',\n message: `Could not fetch cloud state for ${env}: ${(err as Error).message}`,\n })\n result.skipped.push({ env, reason: 'cloud fetch failed' })\n continue\n }\n\n const lockData: LockFileData = {\n version: 1,\n env,\n integrations: {},\n plugins: {},\n }\n const declaredAliases = declaredAliasesForConflictCheck\n const usedIntegrationAliases = new Set<string>(Object.keys(declaredAliases.integrations))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- cloud bot.integrations shape is untyped; we access known string fields at runtime\n for (const [cloudAlias, cloud] of Object.entries((bot.integrations ?? {}) as Record<string, any>)) {\n // Prefer the user-facing alias from agent.config.ts over the cloud-side ID (e.g. intver_xyz)\n const declaredAlias = Object.entries(declaredAliases.integrations).find(\n ([, decl]) => decl.name === cloud.name\n )?.[0]\n const alias = declaredAlias ?? generateFriendlyAlias(cloud.name, cloudAlias, usedIntegrationAliases)\n usedIntegrationAliases.add(alias)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- registry spec shape is opaque; catch fallback is {}\n const spec = await opts.integrationRegistry.getSpec(cloud.name, cloud.version).catch(() => ({}) as any)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- spec may be the {} fallback which lacks typed configuration\n const schema = (spec as any)?.configuration?.schema\n const rewritten = rewriteSecrets({ alias, config: cloud.configuration ?? {}, schema })\n result.envVarsToSet.push(...rewritten.envVars)\n result.warnings.push(...rewritten.warnings)\n lockData.integrations[alias] = {\n name: cloud.name,\n version: cloud.version,\n enabled: cloud.enabled ?? false,\n config: rewritten.config,\n }\n }\n const usedPluginAliases = new Set<string>(Object.keys(declaredAliases.plugins))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- cloud bot.plugins shape is untyped\n for (const [cloudAlias, cloud] of Object.entries((bot.plugins ?? {}) as Record<string, any>)) {\n // Prefer the user-facing alias from agent.config.ts over the cloud-side ID\n const declaredAlias = Object.entries(declaredAliases.plugins).find(([, decl]) => decl.name === cloud.name)?.[0]\n const alias = declaredAlias ?? generateFriendlyAlias(cloud.name, cloudAlias, usedPluginAliases)\n usedPluginAliases.add(alias)\n lockData.plugins[alias] = {\n name: cloud.name,\n version: cloud.version,\n enabled: cloud.enabled ?? true,\n config: cloud.configuration ?? {},\n dependencies: Object.fromEntries(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- cloud plugin interface shape is not narrowed to record; v.integrationAlias is safe at runtime\n Object.entries((cloud.interfaces ?? {}) as Record<string, any>).map(([k, v]) => [\n k,\n { integrationAlias: v.integrationAlias },\n ])\n ),\n }\n }\n await lockFile.write(lockData)\n result.migrated.push(env)\n }\n }\n\n if (result.migrated.length > 0) {\n const writer = new ConfigWriter(opts.projectPath)\n await writer.removeDependenciesField()\n result.warnings.push({\n code: 'MIGRATED_DEPENDENCIES',\n message: `Migrated dependencies to ${result.migrated.map((e) => `dependencies.${e}.lock.json`).join(', ')}. Review the diff and commit.`,\n })\n }\n\n result.envVarsToSet = [...new Set(result.envVarsToSet)]\n return result\n}\n\n/**\n * Read the declared integration and plugin aliases from `agent.config.ts`.\n * Uses ts-morph to extract keys and `name@version` values from the\n * `dependencies.integrations` and `dependencies.plugins` objects inside\n * the `defineConfig(...)` call.\n *\n * Returns empty objects if the file is absent, has no `dependencies` field,\n * or cannot be parsed.\n */\nasync function readAliasesFromConfig(projectPath: string): Promise<{\n integrations: Record<string, { name: string; version: string }>\n plugins: Record<string, { name: string; version: string }>\n}> {\n const configPath = path.join(projectPath, 'agent.config.ts')\n try {\n await fs.access(configPath)\n } catch {\n return { integrations: {}, plugins: {} }\n }\n\n const integrations: Record<string, { name: string; version: string }> = {}\n const plugins: Record<string, { name: string; version: string }> = {}\n\n try {\n const project = new Project({ useInMemoryFileSystem: false })\n const sourceFile = project.addSourceFileAtPath(configPath)\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((c) => c.getExpression().getText() === 'defineConfig')\n const obj = callExpr?.getArguments()[0]?.asKind(SyntaxKind.ObjectLiteralExpression)\n if (!obj) return { integrations, plugins }\n\n const depsProp = obj.getProperty('dependencies')\n if (!depsProp || !depsProp.isKind(SyntaxKind.PropertyAssignment)) return { integrations, plugins }\n const depsObj = depsProp.getInitializer()?.asKind(SyntaxKind.ObjectLiteralExpression)\n if (!depsObj) return { integrations, plugins }\n\n for (const field of ['integrations', 'plugins'] as const) {\n const target = field === 'integrations' ? integrations : plugins\n const innerProp = depsObj.getProperty(field)\n if (!innerProp || !innerProp.isKind(SyntaxKind.PropertyAssignment)) continue\n const inner = innerProp.getInitializer()?.asKind(SyntaxKind.ObjectLiteralExpression)\n if (!inner) continue\n for (const aliasProp of inner.getProperties()) {\n if (!aliasProp.isKind(SyntaxKind.PropertyAssignment)) continue\n const alias = aliasProp.getName().replace(/['\"]/g, '')\n const initializer = aliasProp.getInitializer()\n let nameVersion = ''\n if (initializer?.isKind(SyntaxKind.StringLiteral)) {\n nameVersion = initializer.getLiteralText()\n } else if (initializer?.isKind(SyntaxKind.ObjectLiteralExpression)) {\n // Object form: { version: \"name@v\", ... }\n const versionProp = initializer.getProperty('version')\n if (versionProp?.isKind(SyntaxKind.PropertyAssignment)) {\n const v = versionProp.getInitializer()\n if (v?.isKind(SyntaxKind.StringLiteral)) nameVersion = v.getLiteralText()\n }\n }\n const at = nameVersion.indexOf('@')\n if (at < 0) continue\n const name = nameVersion.slice(0, at)\n const version = nameVersion.slice(at + 1)\n target[alias] = { name, version }\n }\n }\n } catch {\n // Parsing failed; return whatever was collected so far (likely empty)\n }\n\n return { integrations, plugins }\n}\n",
|
|
56
|
+
"import { Project, SyntaxKind, PropertyAssignment, SourceFile, ObjectLiteralExpression } from 'ts-morph'\nimport { readFileSync } from 'fs'\nimport * as path from 'path'\nimport type { Dependencies } from './types'\nimport { formatCode } from '../generators/utils'\n\nexport interface ConfigSchemaFieldUpdate {\n action: 'add' | 'update' | 'remove'\n field: string\n /** Raw TS expression for the field type, e.g. \"z.string().default('sk-...')\" */\n definition?: string\n}\n\nexport interface SecretDeclarationUpdate {\n action: 'add' | 'update' | 'remove'\n field: string\n /** Optional: include to set or overwrite the description. */\n description?: string\n /** Optional: include to set or overwrite the optional flag. */\n optional?: boolean\n}\n\nexport type DefaultModelSelection = string | string[]\n\nexport interface DefaultModelsUpdate {\n autonomous?: DefaultModelSelection\n zai?: DefaultModelSelection\n}\n\nexport interface IntegrationConfigMigrationState {\n deprecatedAliases: string[]\n migratableAliases: string[]\n}\n\n/**\n * Minimal ConfigWriter shape used by callers that only need to rewrite\n * dependencies — exposed so tests can inject stubs without constructing a\n * full ConfigWriter.\n */\nexport interface DependencyConfigWriter {\n updateDependencies(dependencies: Dependencies): Promise<void>\n}\n\nexport type DependencyConfigWriterFactory = (projectPath: string) => DependencyConfigWriter\n\n/**\n * ConfigWriter handles writing updates to agent.config.ts\n *\n * Note: For reading dependencies, use AgentProject.dependencies instead.\n * This class is only for surgical updates to specific fields.\n */\nexport class ConfigWriter {\n private configPath: string\n\n constructor(projectPath: string) {\n this.configPath = path.join(projectPath, 'agent.config.ts')\n }\n\n private loadConfig(): {\n sourceFile: SourceFile\n configObject: ObjectLiteralExpression\n } {\n const project = new Project()\n const sourceFile = project.createSourceFile(this.configPath, readFileSync(this.configPath, 'utf-8'), {\n overwrite: true,\n })\n\n const defineConfigCall = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression).find((call) => {\n return call.getExpression().getText() === 'defineConfig'\n })\n\n if (!defineConfigCall) {\n throw new Error('Could not find defineConfig() call in agent.config.ts')\n }\n\n const configArg = defineConfigCall.getArguments()[0]\n if (!configArg || !configArg.isKind(SyntaxKind.ObjectLiteralExpression)) {\n throw new Error('defineConfig() must have an object literal as its first argument')\n }\n\n return { sourceFile, configObject: configArg as ObjectLiteralExpression }\n }\n\n private async saveConfig(sourceFile: SourceFile): Promise<void> {\n sourceFile.formatText()\n const content = sourceFile.getFullText()\n const formatted = await formatCode(content, this.configPath)\n sourceFile.replaceWithText(formatted)\n await sourceFile.save()\n }\n\n private serializeDefaultModelSelection(value: DefaultModelSelection): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => `'${entry.replace(/'/g, \"\\\\'\")}'`).join(', ')}]`\n }\n\n return `'${value.replace(/'/g, \"\\\\'\")}'`\n }\n\n private getIntegrationConfigMigrationCandidates(): {\n sourceFile: SourceFile\n candidates: Array<{\n alias: string\n assignment: PropertyAssignment\n hasConfigProperty: boolean\n versionInitializerText?: string\n }>\n } {\n const { sourceFile, configObject } = this.loadConfig()\n\n const dependenciesProp = configObject.getProperty('dependencies') as PropertyAssignment | undefined\n if (!dependenciesProp) {\n return { sourceFile, candidates: [] }\n }\n\n const depsInit = dependenciesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!depsInit) {\n return { sourceFile, candidates: [] }\n }\n\n const integrationsProp = depsInit.getProperty('integrations') as PropertyAssignment | undefined\n if (!integrationsProp) {\n return { sourceFile, candidates: [] }\n }\n\n const integrationsInit = integrationsProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!integrationsInit) {\n return { sourceFile, candidates: [] }\n }\n\n const candidates = integrationsInit.getProperties().flatMap((prop) => {\n if (!prop.isKind(SyntaxKind.PropertyAssignment)) {\n return []\n }\n\n const assignment = prop as PropertyAssignment\n const initializer = assignment.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!initializer) {\n return []\n }\n\n const hasConfigProperty = initializer.getProperty('config') !== undefined\n\n const versionProp = initializer.getProperty('version') as PropertyAssignment | undefined\n const versionInitializer = versionProp?.getInitializer()\n const versionInitializerText =\n versionInitializer &&\n (versionInitializer.isKind(SyntaxKind.StringLiteral) ||\n versionInitializer.isKind(SyntaxKind.NoSubstitutionTemplateLiteral))\n ? versionInitializer.getText()\n : undefined\n\n return [{ alias: assignment.getName(), assignment, hasConfigProperty, versionInitializerText }]\n })\n\n return { sourceFile, candidates }\n }\n\n /**\n * Updates the dependencies field in agent.config.ts\n * Uses ts-morph to surgically update only the dependencies property\n * while preserving all other config fields (name, models, state, etc.)\n */\n async updateDependencies(dependencies: Dependencies): Promise<void> {\n const { sourceFile, configObject } = this.loadConfig()\n\n // Find or create the dependencies property\n let dependenciesProperty = configObject.getProperty('dependencies') as PropertyAssignment | undefined\n\n if (dependenciesProperty) {\n // Update existing property\n dependenciesProperty.setInitializer(JSON.stringify(dependencies, null, 2))\n } else {\n // Add new property at the end\n dependenciesProperty = configObject.addPropertyAssignment({\n name: 'dependencies',\n initializer: JSON.stringify(dependencies),\n })\n }\n\n await this.saveConfig(sourceFile)\n }\n\n /**\n * Updates the name field in agent.config.ts\n */\n async updateName(name: string): Promise<void> {\n const { sourceFile, configObject } = this.loadConfig()\n\n const nameProperty = configObject.getProperty('name') as PropertyAssignment | undefined\n if (nameProperty) {\n nameProperty.setInitializer(`'${name.replace(/'/g, \"\\\\'\")}'`)\n }\n\n await this.saveConfig(sourceFile)\n }\n\n /**\n * Updates the defaultModels field in agent.config.ts.\n * Creates the object when it does not exist and only mutates the requested keys.\n */\n async updateDefaultModels(updates: DefaultModelsUpdate): Promise<void> {\n const requestedEntries = Object.entries(updates).filter(([, value]) => value !== undefined) as Array<\n [keyof DefaultModelsUpdate, DefaultModelSelection]\n >\n\n if (requestedEntries.length === 0) {\n return\n }\n\n const { sourceFile, configObject } = this.loadConfig()\n\n let defaultModelsProperty = configObject.getProperty('defaultModels') as PropertyAssignment | undefined\n\n if (!defaultModelsProperty) {\n defaultModelsProperty = configObject.addPropertyAssignment({\n name: 'defaultModels',\n initializer: '{}',\n })\n }\n\n const defaultModelsObject = defaultModelsProperty.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!defaultModelsObject) {\n throw new Error('defaultModels must be an object literal in agent.config.ts')\n }\n\n for (const [key, value] of requestedEntries) {\n const existingProperty = defaultModelsObject.getProperty(key) as PropertyAssignment | undefined\n const initializer = this.serializeDefaultModelSelection(value)\n\n if (existingProperty) {\n existingProperty.setInitializer(initializer)\n } else {\n defaultModelsObject.addPropertyAssignment({\n name: key,\n initializer,\n })\n }\n }\n\n await this.saveConfig(sourceFile)\n }\n\n /**\n * Migrates object-format integrations to the string shorthand format.\n * e.g. `chat: { version: \"chat@0.7.6\", enabled: true }` → `chat: \"chat@0.7.6\"`\n *\n * Returns the list of alias names that were migrated.\n */\n async migrateIntegrationsToStringFormat(): Promise<string[]> {\n const { sourceFile, candidates } = this.getIntegrationConfigMigrationCandidates()\n const migrated: string[] = []\n\n for (const candidate of candidates) {\n if (!candidate.versionInitializerText || candidate.hasConfigProperty) {\n continue\n }\n\n candidate.assignment.setInitializer(candidate.versionInitializerText)\n migrated.push(candidate.alias)\n }\n\n if (migrated.length > 0) {\n await this.saveConfig(sourceFile)\n }\n\n return migrated\n }\n\n /**\n * Checks which integrations still use the deprecated object format and which\n * of those entries can be safely rewritten to string shorthand.\n */\n getIntegrationConfigMigrationState(): IntegrationConfigMigrationState {\n try {\n const { candidates } = this.getIntegrationConfigMigrationCandidates()\n const deprecatedAliases = candidates.map((candidate) => candidate.alias)\n const migratableAliases = candidates\n .filter((candidate) => candidate.versionInitializerText && !candidate.hasConfigProperty)\n .map((candidate) => candidate.alias)\n\n return { deprecatedAliases, migratableAliases }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n console.error(\n `Configuration update failed with error: ${message} — please verify that there are no syntax errors in your agent.config.ts`\n )\n return { deprecatedAliases: [], migratableAliases: [] }\n }\n }\n\n /**\n * Checks if any integrations use the deprecated object format.\n * Returns alias names of integrations using the deprecated format.\n */\n getObjectFormatIntegrations(): string[] {\n return this.getIntegrationConfigMigrationState().deprecatedAliases\n }\n\n /**\n * Serializes a string literal using single quotes, escaping any embedded single quotes.\n */\n private serializeStringLiteral(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n }\n\n /**\n * Builds the initializer for a new secret declaration:\n * { description: '…', optional: true }\n * Only emits fields that are provided.\n */\n private buildSecretInitializer(update: { description?: string; optional?: boolean }): string {\n const parts: string[] = []\n if (update.description !== undefined) {\n parts.push(`description: ${this.serializeStringLiteral(update.description)}`)\n }\n if (update.optional !== undefined) {\n parts.push(`optional: ${update.optional ? 'true' : 'false'}`)\n }\n return `{ ${parts.join(', ')} }`\n }\n\n /**\n * Adds, updates, or removes entries inside the top-level `secrets` object.\n *\n * Shape:\n * secrets: {\n * MY_SECRET: { description: '...', optional: true },\n * }\n *\n * For `update`, only the fields provided (`description` / `optional`) are modified;\n * other keys on the existing secret declaration are preserved.\n */\n async updateSecrets(updates: SecretDeclarationUpdate[]): Promise<void> {\n const { sourceFile, configObject } = this.loadConfig()\n\n const hasAdds = updates.some((u) => u.action === 'add')\n\n let secretsProp = configObject.getProperty('secrets') as PropertyAssignment | undefined\n if (!secretsProp) {\n if (!hasAdds) return\n secretsProp = configObject.addPropertyAssignment({\n name: 'secrets',\n initializer: '{}',\n })\n }\n\n const secretsObject = secretsProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!secretsObject) return\n\n for (const update of updates) {\n const existing = secretsObject.getProperty(update.field) as PropertyAssignment | undefined\n\n switch (update.action) {\n case 'add':\n if (!existing) {\n secretsObject.addPropertyAssignment({\n name: update.field,\n initializer: this.buildSecretInitializer(update),\n })\n }\n break\n case 'update': {\n if (!existing) break\n const existingInit = existing.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!existingInit) {\n // Replace malformed initializer with a fresh object literal\n existing.setInitializer(this.buildSecretInitializer(update))\n break\n }\n\n if (update.description !== undefined) {\n const descProp = existingInit.getProperty('description') as PropertyAssignment | undefined\n const initializer = this.serializeStringLiteral(update.description)\n if (descProp) {\n descProp.setInitializer(initializer)\n } else {\n existingInit.addPropertyAssignment({ name: 'description', initializer })\n }\n }\n\n if (update.optional !== undefined) {\n const optionalProp = existingInit.getProperty('optional') as PropertyAssignment | undefined\n const initializer = update.optional ? 'true' : 'false'\n if (optionalProp) {\n optionalProp.setInitializer(initializer)\n } else {\n existingInit.addPropertyAssignment({ name: 'optional', initializer })\n }\n }\n break\n }\n case 'remove':\n if (existing) {\n existing.remove()\n }\n break\n }\n }\n\n await this.saveConfig(sourceFile)\n }\n\n /**\n * Adds, updates, or removes fields inside configuration.schema (the z.object({...}))\n */\n async updateConfiguration(updates: ConfigSchemaFieldUpdate[]): Promise<void> {\n const { sourceFile, configObject } = this.loadConfig()\n\n const hasAdds = updates.some((u) => u.action === 'add')\n\n // Find or create configuration property\n let configProp = configObject.getProperty('configuration') as PropertyAssignment | undefined\n if (!configProp) {\n if (!hasAdds) return\n configProp = configObject.addPropertyAssignment({\n name: 'configuration',\n initializer: '{ schema: z.object({}) }',\n })\n }\n\n const configInit = configProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n if (!configInit) return\n\n // Find or create schema property\n let schemaProp = configInit.getProperty('schema') as PropertyAssignment | undefined\n if (!schemaProp) {\n if (!hasAdds) return\n schemaProp = configInit.addPropertyAssignment({\n name: 'schema',\n initializer: 'z.object({})',\n })\n }\n\n const schemaCall = schemaProp.getInitializerIfKind(SyntaxKind.CallExpression)\n if (!schemaCall) return\n\n const schemaArg = schemaCall.getArguments()[0]\n if (!schemaArg || !schemaArg.isKind(SyntaxKind.ObjectLiteralExpression)) return\n\n const schemaObject = schemaArg as ObjectLiteralExpression\n\n for (const update of updates) {\n const existing = schemaObject.getProperty(update.field) as PropertyAssignment | undefined\n\n switch (update.action) {\n case 'add':\n if (!existing && update.definition) {\n schemaObject.addPropertyAssignment({\n name: update.field,\n initializer: update.definition,\n })\n }\n break\n case 'update':\n if (existing && update.definition) {\n existing.setInitializer(update.definition)\n }\n break\n case 'remove':\n if (existing) {\n existing.remove()\n }\n break\n }\n }\n\n await this.saveConfig(sourceFile)\n }\n\n /**\n * Removes the top-level `dependencies` field from agent.config.ts.\n * Used during migration to move dependencies to the lock file.\n */\n async removeDependenciesField(): Promise<void> {\n const { sourceFile, configObject } = this.loadConfig()\n\n const dependenciesProp = configObject.getProperty('dependencies') as PropertyAssignment | undefined\n if (dependenciesProp) {\n dependenciesProp.remove()\n await this.saveConfig(sourceFile)\n }\n }\n}\n"
|
|
57
|
+
],
|
|
58
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,IAKa,4BAQA,+BAKA,uBASA;AAAA;AAAA,EAtBA,6BAA6B,EAAE,OAAO;AAAA,IACjD,MAAM,EAAE,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