@botpress/adk 1.19.0-beta.13 → 1.19.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/agent-project/agent-project.d.ts.map +1 -1
  2. package/dist/agent-project/config-writer.d.ts +1 -1
  3. package/dist/agent-project/dependency-state-to-dependencies.d.ts +11 -0
  4. package/dist/agent-project/dependency-state-to-dependencies.d.ts.map +1 -0
  5. package/dist/agent-project/types.d.ts +5 -0
  6. package/dist/agent-project/types.d.ts.map +1 -1
  7. package/dist/agent0/index.js +26 -13
  8. package/dist/agent0/index.js.map +5 -5
  9. package/dist/agent0/runtime/client.d.ts.map +1 -1
  10. package/dist/bot-generator/generator.d.ts +22 -0
  11. package/dist/bot-generator/generator.d.ts.map +1 -1
  12. package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
  13. package/dist/commands/bp-dev-stderr.d.ts +9 -0
  14. package/dist/commands/bp-dev-stderr.d.ts.map +1 -1
  15. package/dist/commands/index.d.ts +1 -0
  16. package/dist/commands/index.d.ts.map +1 -1
  17. package/dist/dependencies/catalog/catalog-service.d.ts +53 -0
  18. package/dist/dependencies/catalog/catalog-service.d.ts.map +1 -0
  19. package/dist/dependencies/catalog/client-factory.d.ts +33 -0
  20. package/dist/dependencies/catalog/client-factory.d.ts.map +1 -0
  21. package/dist/dependencies/catalog/integration-source.d.ts +34 -0
  22. package/dist/dependencies/catalog/integration-source.d.ts.map +1 -0
  23. package/dist/dependencies/catalog/interface-source.d.ts +23 -0
  24. package/dist/dependencies/catalog/interface-source.d.ts.map +1 -0
  25. package/dist/dependencies/catalog/plugin-source.d.ts +49 -0
  26. package/dist/dependencies/catalog/plugin-source.d.ts.map +1 -0
  27. package/dist/dependencies/catalog/resolution-cache.d.ts +76 -0
  28. package/dist/dependencies/catalog/resolution-cache.d.ts.map +1 -0
  29. package/dist/dependencies/dependency-manager.d.ts +31 -16
  30. package/dist/dependencies/dependency-manager.d.ts.map +1 -1
  31. package/dist/dependencies/errors.d.ts +2 -2
  32. package/dist/dependencies/errors.d.ts.map +1 -1
  33. package/dist/dependencies/index.d.ts +5 -4
  34. package/dist/dependencies/index.d.ts.map +1 -1
  35. package/dist/dependencies/index.js +2062 -1541
  36. package/dist/dependencies/index.js.map +34 -26
  37. package/dist/dependencies/legacy-lock-file.d.ts +15 -0
  38. package/dist/dependencies/legacy-lock-file.d.ts.map +1 -0
  39. package/dist/dependencies/migration.d.ts +19 -0
  40. package/dist/dependencies/migration.d.ts.map +1 -1
  41. package/dist/dependencies/resolvers/integration-resolver.d.ts +4 -3
  42. package/dist/dependencies/resolvers/integration-resolver.d.ts.map +1 -1
  43. package/dist/dependencies/resolvers/plugin-resolver.d.ts +4 -4
  44. package/dist/dependencies/resolvers/plugin-resolver.d.ts.map +1 -1
  45. package/dist/dependencies/snapshot-store.d.ts +59 -0
  46. package/dist/dependencies/snapshot-store.d.ts.map +1 -0
  47. package/dist/dependencies/status-resolver.d.ts +36 -0
  48. package/dist/dependencies/status-resolver.d.ts.map +1 -0
  49. package/dist/dependencies/status.d.ts +214 -0
  50. package/dist/dependencies/status.d.ts.map +1 -0
  51. package/dist/dependencies/types.d.ts +379 -29
  52. package/dist/dependencies/types.d.ts.map +1 -1
  53. package/dist/file-watcher/watcher.d.ts.map +1 -1
  54. package/dist/index.d.ts +2 -2
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +2540 -1746
  57. package/dist/index.js.map +44 -36
  58. package/dist/integrations/config-utils.d.ts +11 -7
  59. package/dist/integrations/config-utils.d.ts.map +1 -1
  60. package/dist/integrations/index.d.ts +1 -2
  61. package/dist/integrations/index.d.ts.map +1 -1
  62. package/dist/integrations/manager.d.ts +19 -53
  63. package/dist/integrations/manager.d.ts.map +1 -1
  64. package/dist/interfaces/enhanced-cache.d.ts +7 -7
  65. package/dist/interfaces/enhanced-cache.d.ts.map +1 -1
  66. package/dist/interfaces/manager.d.ts +11 -17
  67. package/dist/interfaces/manager.d.ts.map +1 -1
  68. package/dist/plugins/index.d.ts +0 -1
  69. package/dist/plugins/index.d.ts.map +1 -1
  70. package/dist/plugins/manager.d.ts +16 -53
  71. package/dist/plugins/manager.d.ts.map +1 -1
  72. package/dist/preflight/checker.d.ts.map +1 -1
  73. package/dist/preflight/dependency-gate.d.ts +36 -0
  74. package/dist/preflight/dependency-gate.d.ts.map +1 -0
  75. package/dist/preflight/index.d.ts +1 -0
  76. package/dist/preflight/index.d.ts.map +1 -1
  77. package/dist/preflight/types.d.ts +10 -0
  78. package/dist/preflight/types.d.ts.map +1 -1
  79. package/dist/runner/script-runner.d.ts.map +1 -1
  80. package/dist/templates/botpress-desk/evals/index.eval.ts +1 -1
  81. package/dist/templates/template.config.json +3 -3
  82. package/dist/utils/ids.d.ts +10 -0
  83. package/dist/utils/ids.d.ts.map +1 -1
  84. package/package.json +2 -2
  85. package/dist/agent-project/lock-to-dependencies.d.ts +0 -11
  86. package/dist/agent-project/lock-to-dependencies.d.ts.map +0 -1
  87. package/dist/dependencies/lock-file.d.ts +0 -15
  88. package/dist/dependencies/lock-file.d.ts.map +0 -1
  89. package/dist/integrations/enhanced-cache.d.ts +0 -53
  90. package/dist/integrations/enhanced-cache.d.ts.map +0 -1
  91. package/dist/plugins/enhanced-cache.d.ts +0 -53
  92. package/dist/plugins/enhanced-cache.d.ts.map +0 -1
@@ -46,32 +46,80 @@ var __export = (target, all) => {
46
46
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
47
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
48
48
 
49
+ // src/dependencies/json-utils.ts
50
+ function sortKeysDeep(value) {
51
+ if (Array.isArray(value))
52
+ return value.map(sortKeysDeep);
53
+ if (value && typeof value === "object") {
54
+ const obj = value;
55
+ const sorted = {};
56
+ for (const key of Object.keys(obj).sort()) {
57
+ sorted[key] = sortKeysDeep(obj[key]);
58
+ }
59
+ return sorted;
60
+ }
61
+ return value;
62
+ }
63
+ function jsonEqual(a, b) {
64
+ return JSON.stringify(sortKeysDeep(a)) === JSON.stringify(sortKeysDeep(b));
65
+ }
66
+
49
67
  // src/dependencies/types.ts
50
68
  import { z } from "@botpress/sdk";
51
- var integrationLockEntrySchema, pluginDependencyMappingSchema, pluginLockEntrySchema, lockFileSchema;
69
+ var integrationDependencyEntrySchema, pluginDependencyMappingSchema, pluginDependencyEntrySchema, integrationSnapshotEntrySchema, pluginSnapshotEntrySchema, dependencyStateSchema, dependencySnapshotSchema, dependencyMigrationMarkerSchema;
52
70
  var init_types = __esm(() => {
53
- integrationLockEntrySchema = z.object({
71
+ integrationDependencyEntrySchema = z.object({
54
72
  name: z.string(),
55
73
  version: z.string(),
56
74
  enabled: z.boolean(),
57
- config: z.record(z.any()).default({})
75
+ config: z.record(z.any()).default({}),
76
+ configurationType: z.string().optional(),
77
+ missingFields: z.array(z.string()).optional(),
78
+ authorizationPending: z.boolean().optional()
58
79
  });
59
80
  pluginDependencyMappingSchema = z.object({
60
81
  integrationAlias: z.string()
61
82
  });
62
- pluginLockEntrySchema = z.object({
83
+ pluginDependencyEntrySchema = z.object({
63
84
  name: z.string(),
64
85
  version: z.string(),
65
86
  enabled: z.boolean().default(true),
66
87
  config: z.record(z.any()).default({}),
67
- dependencies: z.record(pluginDependencyMappingSchema).default({})
88
+ dependencies: z.record(pluginDependencyMappingSchema).default({}),
89
+ missingFields: z.array(z.string()).optional()
90
+ });
91
+ integrationSnapshotEntrySchema = integrationDependencyEntrySchema.extend({
92
+ cloudAlias: z.string().optional(),
93
+ cloudId: z.string().optional(),
94
+ updatedAt: z.string().optional()
95
+ });
96
+ pluginSnapshotEntrySchema = pluginDependencyEntrySchema.extend({
97
+ cloudAlias: z.string().optional(),
98
+ cloudId: z.string().optional(),
99
+ updatedAt: z.string().optional()
100
+ });
101
+ dependencyStateSchema = z.object({
102
+ $schema: z.string().optional(),
103
+ version: z.literal(1),
104
+ env: z.enum(["dev", "prod"]),
105
+ integrations: z.record(integrationDependencyEntrySchema).default({}),
106
+ plugins: z.record(pluginDependencyEntrySchema).default({})
68
107
  });
69
- lockFileSchema = z.object({
108
+ dependencySnapshotSchema = z.object({
70
109
  $schema: z.string().optional(),
71
110
  version: z.literal(1),
72
111
  env: z.enum(["dev", "prod"]),
73
- integrations: z.record(integrationLockEntrySchema).default({}),
74
- plugins: z.record(pluginLockEntrySchema).default({})
112
+ botId: z.string(),
113
+ fetchedAt: z.string(),
114
+ botUpdatedAt: z.string().optional(),
115
+ stale: z.boolean().optional(),
116
+ integrations: z.record(integrationSnapshotEntrySchema).default({}),
117
+ plugins: z.record(pluginSnapshotEntrySchema).default({})
118
+ });
119
+ dependencyMigrationMarkerSchema = z.object({
120
+ version: z.literal(1),
121
+ migratedAt: z.string(),
122
+ sources: z.array(z.enum(["lock", "agentConfig", "cloud"]))
75
123
  });
76
124
  });
77
125
 
@@ -125,109 +173,198 @@ var init_errors2 = __esm(() => {
125
173
  "MISSING_DEPENDENCY",
126
174
  "AMBIGUOUS_DEPENDENCY",
127
175
  "INTERFACE_NOT_IMPLEMENTED",
128
- "LOCK_DRIFT",
176
+ "SNAPSHOT_DRIFT",
129
177
  "UNINSTALL_REQUIRES_CONFIRMATION",
130
178
  "SAME_SOURCE_TARGET",
131
- "SOURCE_LOCK_MISSING",
179
+ "SOURCE_SNAPSHOT_MISSING",
132
180
  "MIGRATION_CONFLICT",
133
181
  "INVALID_CONFIG",
134
182
  "BOT_NOT_FOUND",
135
183
  "BUILTIN_INTERFACE_IMMUTABLE",
136
- "PROD_CONFIRMATION_REQUIRED"
184
+ "PROD_CONFIRMATION_REQUIRED",
185
+ "UNCONFIGURED_DEPENDENCIES"
137
186
  ];
138
187
  DependencyError = class DependencyError extends AdkError {
139
188
  constructor(opts) {
140
189
  super({ ...opts, expected: true });
141
190
  }
142
191
  };
143
- DEPENDENCY_WARNING_CODES = [
144
- "DEPRECATED_COMMAND",
145
- "MIGRATED_DEPENDENCIES",
146
- "CLOUD_FETCH_PARTIAL",
147
- "NO_PROD_BOT"
148
- ];
192
+ DEPENDENCY_WARNING_CODES = ["MIGRATED_DEPENDENCIES", "CLOUD_FETCH_PARTIAL", "NO_PROD_BOT"];
149
193
  });
150
194
 
151
- // src/dependencies/json-utils.ts
152
- function sortKeysDeep(value) {
153
- if (Array.isArray(value))
154
- return value.map(sortKeysDeep);
155
- if (value && typeof value === "object") {
156
- const obj = value;
157
- const sorted = {};
158
- for (const key of Object.keys(obj).sort()) {
159
- sorted[key] = sortKeysDeep(obj[key]);
160
- }
161
- return sorted;
162
- }
163
- return value;
195
+ // src/dependencies/status.ts
196
+ function schemaRequiredFields(config) {
197
+ const required = config?.schema?.required;
198
+ if (!Array.isArray(required))
199
+ return [];
200
+ return required.filter((field) => typeof field === "string");
164
201
  }
165
- function jsonEqual(a, b) {
166
- return JSON.stringify(sortKeysDeep(a)) === JSON.stringify(sortKeysDeep(b));
202
+ function configurationRequiresInput(config) {
203
+ if (!config)
204
+ return false;
205
+ if (configGatesOnAuthorization(config))
206
+ return true;
207
+ return schemaRequiredFields(config).length > 0;
167
208
  }
168
-
169
- // src/dependencies/lock-file.ts
170
- import * as path from "path";
171
- import * as fs from "fs/promises";
172
-
173
- class LockFile {
174
- filePath;
175
- env;
176
- constructor(opts) {
177
- this.env = opts.env;
178
- this.filePath = path.join(opts.projectPath, `dependencies.${opts.env}.lock.json`);
179
- }
180
- async read() {
181
- let raw;
182
- try {
183
- raw = await fs.readFile(this.filePath, "utf8");
184
- } catch (err) {
185
- if (err.code === "ENOENT") {
186
- return lockFileSchema.parse({ version: 1, env: this.env });
187
- }
188
- throw err;
189
- }
190
- const parsed = JSON.parse(raw);
191
- try {
192
- return lockFileSchema.parse(parsed);
193
- } catch (err) {
194
- throw new DependencyError({
195
- code: "INVALID_CONFIG",
196
- message: `Lock file at ${this.filePath} failed schema validation`,
197
- details: { issues: err.issues ?? String(err) }
198
- });
199
- }
200
- }
201
- async write(data) {
202
- const validated = lockFileSchema.parse(data);
203
- const serialized = JSON.stringify(sortKeysDeep(validated), null, 2) + `
204
- `;
205
- const tmp = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
206
- await fs.writeFile(tmp, serialized, "utf8");
207
- await fs.rename(tmp, this.filePath);
208
- }
209
- async exists() {
210
- try {
211
- await fs.access(this.filePath);
212
- return true;
213
- } catch {
214
- return false;
215
- }
216
- }
217
- async delete() {
218
- try {
219
- await fs.unlink(this.filePath);
220
- } catch (err) {
221
- if (err.code === "ENOENT")
222
- return;
223
- throw err;
224
- }
225
- }
209
+ function configGatesOnAuthorization(config) {
210
+ return !!(config?.identifier?.required || config?.identifier?.linkTemplateScript);
211
+ }
212
+ function missingRequiredFields(config, values) {
213
+ return schemaRequiredFields(config).filter((field) => values[field] === undefined);
214
+ }
215
+ function unconfigured(missingFields) {
216
+ if (missingFields.length > 0)
217
+ return { state: "unconfigured", missingFields };
218
+ return {
219
+ state: "unconfigured",
220
+ missingFields: [],
221
+ reason: "requires authorization or credentials (configure it in the Control Panel)"
222
+ };
223
+ }
224
+ function authorizationPendingVerdict() {
225
+ return {
226
+ state: "unconfigured",
227
+ missingFields: [],
228
+ reason: "requires authorization — connect it in the Control Panel, then re-deploy"
229
+ };
230
+ }
231
+ function snapshotOnlyVerdict(enabled, persistedMissingFields) {
232
+ if (persistedMissingFields.length > 0)
233
+ return unconfigured(persistedMissingFields);
234
+ if (!enabled)
235
+ return { state: "disabled" };
236
+ return { state: "available" };
237
+ }
238
+ function integrationRequiresConfiguration(definition) {
239
+ const config = definition.configuration;
240
+ if (!config)
241
+ return true;
242
+ return configurationRequiresInput(config);
243
+ }
244
+ function pluginRequiresConfiguration(definition) {
245
+ return schemaRequiredFields(definition.configuration).length > 0;
246
+ }
247
+ function integrationRequiresAuthorization(definition, configurationType) {
248
+ const { config } = resolveActiveConfiguration(definition, configurationType);
249
+ return configGatesOnAuthorization(config);
250
+ }
251
+ function resolveActiveConfiguration(spec, configurationType) {
252
+ if (configurationType && configurationType !== "default") {
253
+ const variant = spec.configurations?.[configurationType];
254
+ if (variant)
255
+ return { config: variant, isDefault: false, variantMissing: false };
256
+ return { config: undefined, isDefault: false, variantMissing: true };
257
+ }
258
+ return { config: spec.configuration, isDefault: true, variantMissing: false };
259
+ }
260
+ function computeIntegrationStatus(input) {
261
+ if (!input.installed)
262
+ return { state: "not_installed" };
263
+ if (!input.spec)
264
+ return { state: "unresolved", reason: "integration definition could not be resolved" };
265
+ const {
266
+ config: activeConfig,
267
+ isDefault,
268
+ variantMissing
269
+ } = resolveActiveConfiguration(input.spec, input.configurationType);
270
+ if (variantMissing) {
271
+ return { state: "unresolved", reason: `configuration variant '${input.configurationType}' not found in spec` };
272
+ }
273
+ const requiresConfig = isDefault ? integrationRequiresConfiguration(input.spec) : configurationRequiresInput(activeConfig);
274
+ const values = input.config ?? {};
275
+ const schemaMissing = requiresConfig ? missingRequiredFields(activeConfig, values) : [];
276
+ let configIncomplete = false;
277
+ if (input.persistedMissingFields !== undefined) {
278
+ configIncomplete = input.persistedMissingFields.length > 0;
279
+ } else if (requiresConfig) {
280
+ if (schemaMissing.length > 0) {
281
+ configIncomplete = true;
282
+ } else if (input.cloudEnabled === false && configGatesOnAuthorization(activeConfig)) {
283
+ configIncomplete = true;
284
+ }
285
+ }
286
+ if (configIncomplete) {
287
+ const missingFields = input.persistedMissingFields && input.persistedMissingFields.length > 0 ? input.persistedMissingFields : schemaMissing;
288
+ return unconfigured(missingFields);
289
+ }
290
+ if (input.authorizationPending)
291
+ return authorizationPendingVerdict();
292
+ if (!input.enabled || input.cloudEnabled === false)
293
+ return { state: "disabled" };
294
+ return { state: "available" };
295
+ }
296
+ function isAuthorizationPending(input) {
297
+ if (input.cloudFetchErrored)
298
+ return false;
299
+ if (!input.requiresAuthorization)
300
+ return false;
301
+ return !input.cloudAuthorized;
302
+ }
303
+ function transitiveDependencyVerdict(dependencyStatuses) {
304
+ const broken = (dependencyStatuses ?? []).find((dep) => dep.verdict.state !== "available");
305
+ if (!broken)
306
+ return null;
307
+ const state = broken.verdict.state === "disabled" ? "disabled" : "unresolved";
308
+ return { state, reason: `dependency '${broken.alias}' is ${broken.verdict.state}` };
309
+ }
310
+ function mapPluginDependencyStatuses(dependencies, verdictFor) {
311
+ return Object.values(dependencies ?? {}).map((dep) => dep.integrationAlias).filter((alias) => !!alias).map((alias) => ({
312
+ alias,
313
+ verdict: verdictFor(alias) ?? {
314
+ state: "unresolved",
315
+ reason: `backing integration '${alias}' is not declared in the project`
316
+ }
317
+ }));
318
+ }
319
+ function computePluginStatus(input) {
320
+ if (!input.installed)
321
+ return { state: "not_installed" };
322
+ if (!input.spec)
323
+ return { state: "unresolved", reason: "plugin definition could not be resolved" };
324
+ const transitive = transitiveDependencyVerdict(input.dependencyStatuses);
325
+ if (transitive)
326
+ return transitive;
327
+ const requiresConfig = pluginRequiresConfiguration(input.spec);
328
+ const values = input.config ?? {};
329
+ const schemaMissing = requiresConfig ? missingRequiredFields(input.spec.configuration, values) : [];
330
+ let configIncomplete = false;
331
+ if (input.persistedMissingFields !== undefined) {
332
+ configIncomplete = input.persistedMissingFields.length > 0;
333
+ } else if (requiresConfig) {
334
+ configIncomplete = schemaMissing.length > 0;
335
+ }
336
+ if (configIncomplete) {
337
+ const missingFields = input.persistedMissingFields && input.persistedMissingFields.length > 0 ? input.persistedMissingFields : schemaMissing;
338
+ return unconfigured(missingFields);
339
+ }
340
+ if (!input.enabled)
341
+ return { state: "disabled" };
342
+ return { state: "available" };
343
+ }
344
+ function computePluginCarrierStatus(input) {
345
+ if (!input.installed)
346
+ return { state: "not_installed" };
347
+ const transitive = transitiveDependencyVerdict(input.dependencyStatuses);
348
+ if (transitive)
349
+ return transitive;
350
+ if (input.persistedMissingFields && input.persistedMissingFields.length > 0) {
351
+ return unconfigured(input.persistedMissingFields);
352
+ }
353
+ return { state: "available" };
354
+ }
355
+ function computeSnapshotOnlyStatus(input) {
356
+ if (!input.installed)
357
+ return { state: "not_installed" };
358
+ const verdict = snapshotOnlyVerdict(input.enabled, input.missingFields ?? []);
359
+ if (verdict.state === "available" || verdict.state === "disabled") {
360
+ if (input.authorizationPending)
361
+ return authorizationPendingVerdict();
362
+ }
363
+ return verdict;
364
+ }
365
+ function isCallable(state) {
366
+ return state === "available";
226
367
  }
227
- var init_lock_file = __esm(() => {
228
- init_types();
229
- init_errors2();
230
- });
231
368
 
232
369
  // src/agent-project/types.ts
233
370
  import { z as z2 } from "@botpress/sdk";
@@ -250,7 +387,8 @@ var init_types2 = __esm(() => {
250
387
  plugins: z2.record(z2.object({
251
388
  version: z2.string(),
252
389
  config: z2.record(z2.any()).optional(),
253
- dependencies: z2.record(pluginDependencyMappingSchema2).optional()
390
+ dependencies: z2.record(pluginDependencyMappingSchema2).optional(),
391
+ missingFields: z2.array(z2.string()).optional()
254
392
  })).optional()
255
393
  });
256
394
  agentInfoSchema = z2.object({
@@ -316,24 +454,24 @@ class ValidationErrors {
316
454
  static isValidationError(error) {
317
455
  return error !== null && typeof error === "object" && "$type" in error && error.$type === "ValidationError";
318
456
  }
319
- static directoryNotFound(path2) {
457
+ static directoryNotFound(path) {
320
458
  return {
321
459
  $type: ValidationErrors.$type,
322
460
  code: "DIRECTORY_NOT_FOUND" /* DIRECTORY_NOT_FOUND */,
323
461
  severity: "error" /* ERROR */,
324
- message: `Project directory not found: ${path2}`,
462
+ message: `Project directory not found: ${path}`,
325
463
  hint: "Ensure the directory exists and you have permission to access it",
326
- context: { path: path2 }
464
+ context: { path }
327
465
  };
328
466
  }
329
- static directoryAccessError(path2, error) {
467
+ static directoryAccessError(path, error) {
330
468
  return {
331
469
  $type: ValidationErrors.$type,
332
470
  code: "DIRECTORY_ACCESS_ERROR" /* DIRECTORY_ACCESS_ERROR */,
333
471
  severity: "error" /* ERROR */,
334
472
  message: `Cannot access project directory: ${error}`,
335
473
  hint: "Check file system permissions",
336
- context: { path: path2, error }
474
+ context: { path, error }
337
475
  };
338
476
  }
339
477
  static requiredFileMissing(file) {
@@ -691,89 +829,316 @@ var init_validation_errors = __esm(() => {
691
829
  init_types2();
692
830
  });
693
831
 
694
- // src/constants.ts
695
- var DEFAULT_API_URL = "https://api.botpress.cloud", BUILTIN_INTERFACES, MAX_TABLE_COLUMNS = 20;
696
- var init_constants = __esm(() => {
697
- BUILTIN_INTERFACES = {
698
- "typing-indicator": "typing-indicator@0.0.3",
699
- llm: "llm@9.0.0",
700
- listable: "listable@0.0.2"
701
- };
702
- });
832
+ // src/agent-project/dependencies-parser.ts
833
+ import { z as z3 } from "@botpress/sdk";
834
+ function isIntegrationAliasValid(alias) {
835
+ return alias.length >= INTEGRATION_ALIAS_MIN_LENGTH && alias.length <= INTEGRATION_ALIAS_MAX_LENGTH && INTEGRATION_ALIAS_REGEX.test(alias);
836
+ }
703
837
 
704
- // src/agent-project/agent-resolver.ts
705
- import fs2 from "fs/promises";
706
- import path2 from "path";
707
- async function readLocalInfo(agentPath) {
708
- const localPath = path2.join(agentPath, "agent.local.json");
709
- try {
710
- const localContent = await fs2.readFile(localPath, "utf-8");
711
- const localData = JSON.parse(localContent);
712
- const localResult = agentLocalInfoSchema.safeParse(localData);
713
- if (!localResult.success) {
714
- const issue = localResult.error.errors[0];
715
- throw ValidationErrors.warning(`agent.local.json has an invalid field: ${issue?.path.join(".")} — ${issue?.message}`, "agent.local.json");
838
+ class IntegrationParser {
839
+ static parseIntegrationRef(versionString) {
840
+ const result = integrationRefSchema.safeParse(versionString);
841
+ if (!result.success) {
842
+ throw new AdkError({
843
+ code: "INVALID_VERSION_FORMAT",
844
+ expected: true,
845
+ message: result.error.errors[0]?.message || "Invalid integration version format"
846
+ });
716
847
  }
717
- return localResult.data;
718
- } catch (error) {
719
- if (error.code === "ENOENT") {
720
- return null;
848
+ return result.data;
849
+ }
850
+ static parseIntegrations(dependencies) {
851
+ const integrations = [];
852
+ const errors = [];
853
+ if (!dependencies.integrations) {
854
+ return { integrations, errors };
721
855
  }
722
- if (ValidationErrors.isValidationError(error)) {
723
- throw error;
856
+ for (const [alias, value] of Object.entries(dependencies.integrations)) {
857
+ try {
858
+ if (!isIntegrationAliasValid(alias)) {
859
+ errors.push(ValidationErrors.invalidIntegrationAlias(alias));
860
+ continue;
861
+ }
862
+ const normalized = typeof value === "string" ? { version: value } : value;
863
+ const ref = this.parseIntegrationRef(normalized.version);
864
+ const versionResult = versionSchema.safeParse(ref.version);
865
+ if (!versionResult.success) {
866
+ errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version));
867
+ }
868
+ integrations.push({
869
+ alias,
870
+ ref,
871
+ enabled: "enabled" in normalized ? normalized.enabled : undefined,
872
+ configurationType: "configurationType" in normalized ? normalized.configurationType : undefined,
873
+ config: "config" in normalized ? normalized.config : undefined
874
+ });
875
+ } catch (error) {
876
+ errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid integration '${alias}': ${error instanceof Error ? error.message : String(error)}`));
877
+ }
724
878
  }
725
- throw ValidationErrors.warning(`Failed to read agent.local.json: ${error.message}`, "agent.local.json");
726
- }
727
- }
728
- function applyLocalOverrides(agentInfo, localInfo) {
729
- if (localInfo.botId) {
730
- agentInfo.botId = localInfo.botId;
731
- }
732
- if (localInfo.workspaceId) {
733
- agentInfo.workspaceId = localInfo.workspaceId;
734
- }
735
- if (localInfo.apiUrl) {
736
- agentInfo.apiUrl = localInfo.apiUrl;
737
- }
738
- if (localInfo.devId) {
739
- agentInfo.devId = localInfo.devId;
879
+ return { integrations, errors };
740
880
  }
741
- }
742
- async function resolveAgent(agentPath, options = {}) {
743
- const { required = false, requireWorkspace = false, requireBot = false } = options;
744
- const agentJsonPath = path2.join(agentPath, "agent.json");
745
- const localInfo = await readLocalInfo(agentPath);
746
- let agentInfo = null;
747
- try {
748
- const agentJsonContent = await fs2.readFile(agentJsonPath, "utf-8");
749
- let agentData;
750
- try {
751
- agentData = JSON.parse(agentJsonContent);
752
- } catch (parseError) {
753
- throw ValidationErrors.invalidConfigSyntax("agent.json", parseError.message);
754
- }
755
- const validationResult = agentInfoSchema.safeParse(agentData);
756
- if (!validationResult.success) {
757
- const zodError = validationResult.error.errors[0];
758
- throw ValidationErrors.invalidConfigSchema("agent.json", zodError?.path.join(".") || "unknown", zodError?.message || "Invalid schema");
881
+ static checkDuplicates(integrations) {
882
+ const errors = [];
883
+ const seen = new Map;
884
+ for (const integration of integrations) {
885
+ const key = integration.ref.fullName;
886
+ const group = seen.get(key) || [];
887
+ group.push(integration);
888
+ seen.set(key, group);
759
889
  }
760
- agentInfo = validationResult.data;
761
- } catch (error) {
762
- if (error.code === "ENOENT") {} else if (ValidationErrors.isValidationError(error)) {
763
- throw error;
764
- } else {
765
- throw ValidationErrors.warning(`Failed to read agent.json: ${error.message}`, "agent.json");
890
+ for (const [integrationName, group] of seen.entries()) {
891
+ if (group.length > 1) {
892
+ const duplicateConfigs = [];
893
+ for (let i = 0;i < group.length; i++) {
894
+ for (let j = i + 1;j < group.length; j++) {
895
+ const configA = JSON.stringify(group[i].config ?? {});
896
+ const configB = JSON.stringify(group[j].config ?? {});
897
+ if (configA === configB) {
898
+ if (!duplicateConfigs.includes(group[i].alias)) {
899
+ duplicateConfigs.push(group[i].alias);
900
+ }
901
+ if (!duplicateConfigs.includes(group[j].alias)) {
902
+ duplicateConfigs.push(group[j].alias);
903
+ }
904
+ }
905
+ }
906
+ }
907
+ if (duplicateConfigs.length > 0) {
908
+ errors.push(ValidationErrors.warning(`Integration '${integrationName}' has aliases with identical configurations: ${duplicateConfigs.join(", ")}. Consider using different configs or removing duplicates.`, "agent.config.ts"));
909
+ }
910
+ }
766
911
  }
912
+ return errors;
767
913
  }
768
- if (!agentInfo) {
769
- if (localInfo?.botId && localInfo?.workspaceId) {
770
- agentInfo = {
771
- botId: localInfo.botId,
772
- workspaceId: localInfo.workspaceId,
773
- apiUrl: localInfo.apiUrl,
774
- devId: localInfo.devId
775
- };
776
- } else if (required || requireWorkspace || requireBot) {
914
+ }
915
+ function isPluginAliasValid(alias) {
916
+ return alias.length >= PLUGIN_ALIAS_MIN_LENGTH && alias.length <= PLUGIN_ALIAS_MAX_LENGTH && PLUGIN_ALIAS_REGEX.test(alias);
917
+ }
918
+
919
+ class PluginParser {
920
+ static parsePluginRef(versionString) {
921
+ const result = pluginRefSchema.safeParse(versionString);
922
+ if (!result.success) {
923
+ throw new AdkError({
924
+ code: "INVALID_VERSION_FORMAT",
925
+ expected: true,
926
+ message: result.error.errors[0]?.message || "Invalid plugin version format"
927
+ });
928
+ }
929
+ return result.data;
930
+ }
931
+ static parsePlugins(dependencies) {
932
+ const plugins = [];
933
+ const errors = [];
934
+ if (!dependencies.plugins) {
935
+ return { plugins, errors };
936
+ }
937
+ for (const [alias, value] of Object.entries(dependencies.plugins)) {
938
+ try {
939
+ if (!isPluginAliasValid(alias)) {
940
+ errors.push(ValidationErrors.invalidPluginAlias(alias));
941
+ continue;
942
+ }
943
+ const ref = this.parsePluginRef(value.version);
944
+ const versionResult = versionSchema.safeParse(ref.version);
945
+ if (!versionResult.success) {
946
+ errors.push(ValidationErrors.invalidPluginVersionFormat(alias, ref.version));
947
+ }
948
+ plugins.push({
949
+ alias,
950
+ ref,
951
+ config: value.config,
952
+ dependencies: value.dependencies
953
+ });
954
+ } catch (error) {
955
+ errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid plugin '${alias}': ${error instanceof Error ? error.message : String(error)}`));
956
+ }
957
+ }
958
+ return { plugins, errors };
959
+ }
960
+ static validateDependencyReferences(dependencies) {
961
+ const errors = [];
962
+ if (!dependencies.plugins) {
963
+ return errors;
964
+ }
965
+ const integrationAliases = Object.keys(dependencies.integrations || {});
966
+ for (const [alias, pluginConfig] of Object.entries(dependencies.plugins)) {
967
+ if (!pluginConfig.dependencies) {
968
+ continue;
969
+ }
970
+ for (const [_depAlias, depMapping] of Object.entries(pluginConfig.dependencies)) {
971
+ if (!integrationAliases.includes(depMapping.integrationAlias)) {
972
+ errors.push(ValidationErrors.invalidPluginDependency(alias, depMapping.integrationAlias, integrationAliases));
973
+ }
974
+ }
975
+ }
976
+ return errors;
977
+ }
978
+ static checkDuplicates(plugins) {
979
+ const errors = [];
980
+ const seen = new Map;
981
+ for (const plugin of plugins) {
982
+ const key = plugin.ref.fullName;
983
+ const group = seen.get(key) || [];
984
+ group.push(plugin);
985
+ seen.set(key, group);
986
+ }
987
+ for (const [pluginName, group] of seen.entries()) {
988
+ if (group.length > 1) {
989
+ const duplicateConfigs = [];
990
+ for (let i = 0;i < group.length; i++) {
991
+ for (let j = i + 1;j < group.length; j++) {
992
+ const configA = JSON.stringify(group[i].config ?? {});
993
+ const configB = JSON.stringify(group[j].config ?? {});
994
+ if (configA === configB) {
995
+ if (!duplicateConfigs.includes(group[i].alias)) {
996
+ duplicateConfigs.push(group[i].alias);
997
+ }
998
+ if (!duplicateConfigs.includes(group[j].alias)) {
999
+ duplicateConfigs.push(group[j].alias);
1000
+ }
1001
+ }
1002
+ }
1003
+ }
1004
+ if (duplicateConfigs.length > 0) {
1005
+ errors.push(ValidationErrors.warning(`Plugin '${pluginName}' has aliases with identical configurations: ${duplicateConfigs.join(", ")}. Consider using different configs or removing duplicates.`, "agent.config.ts"));
1006
+ }
1007
+ }
1008
+ }
1009
+ return errors;
1010
+ }
1011
+ }
1012
+ var INTEGRATION_ALIAS_MIN_LENGTH = 2, INTEGRATION_ALIAS_MAX_LENGTH = 100, INTEGRATION_ALIAS_REGEX, integrationRefSchema, versionSchema, PLUGIN_ALIAS_MIN_LENGTH = 2, PLUGIN_ALIAS_MAX_LENGTH = 100, PLUGIN_ALIAS_REGEX, pluginRefSchema;
1013
+ var init_dependencies_parser = __esm(() => {
1014
+ init_src();
1015
+ init_validation_errors();
1016
+ INTEGRATION_ALIAS_REGEX = /^(?:[a-z][a-z0-9_-]*\/)?[a-z][a-z0-9_-]*$/;
1017
+ integrationRefSchema = z3.string().transform((val, ctx) => {
1018
+ const match = val.match(/^(?:([^/]+)\/)?([^@]+)@(.+)$/);
1019
+ if (!match) {
1020
+ ctx.addIssue({
1021
+ code: "custom",
1022
+ message: `Invalid integration version format: ${val}. Expected format: 'name@version' or 'workspace/name@version'`
1023
+ });
1024
+ return;
1025
+ }
1026
+ const [, workspace, name, version] = match;
1027
+ return {
1028
+ workspace: workspace || undefined,
1029
+ name,
1030
+ version,
1031
+ fullName: workspace ? `${workspace}/${name}` : name
1032
+ };
1033
+ });
1034
+ versionSchema = z3.string().refine((version) => {
1035
+ if (version === "latest")
1036
+ return true;
1037
+ const semverPattern = /^(\d+)\.(\d+)\.(\d+)(-[\w.]+)?(\+[\w.]+)?$/;
1038
+ return semverPattern.test(version);
1039
+ }, { message: "Version must be exact semver (e.g., 1.2.3) or 'latest'" });
1040
+ PLUGIN_ALIAS_REGEX = /^[a-z][a-z0-9_-]*$/;
1041
+ pluginRefSchema = z3.string().transform((val, ctx) => {
1042
+ const match = val.match(/^([^/@]+)@(.+)$/);
1043
+ if (!match) {
1044
+ ctx.addIssue({
1045
+ code: "custom",
1046
+ message: `Invalid plugin version format: ${val}. Expected format: 'name@version' (no workspace prefix)`
1047
+ });
1048
+ return;
1049
+ }
1050
+ const [, name, version] = match;
1051
+ return {
1052
+ name,
1053
+ version,
1054
+ fullName: name
1055
+ };
1056
+ });
1057
+ });
1058
+
1059
+ // src/constants.ts
1060
+ var DEFAULT_API_URL = "https://api.botpress.cloud", BUILTIN_INTERFACES, MAX_TABLE_COLUMNS = 20;
1061
+ var init_constants = __esm(() => {
1062
+ BUILTIN_INTERFACES = {
1063
+ "typing-indicator": "typing-indicator@0.0.3",
1064
+ llm: "llm@9.0.0",
1065
+ listable: "listable@0.0.2"
1066
+ };
1067
+ });
1068
+
1069
+ // src/agent-project/agent-resolver.ts
1070
+ import fs from "fs/promises";
1071
+ import path from "path";
1072
+ async function readLocalInfo(agentPath) {
1073
+ const localPath = path.join(agentPath, "agent.local.json");
1074
+ try {
1075
+ const localContent = await fs.readFile(localPath, "utf-8");
1076
+ const localData = JSON.parse(localContent);
1077
+ const localResult = agentLocalInfoSchema.safeParse(localData);
1078
+ if (!localResult.success) {
1079
+ const issue = localResult.error.errors[0];
1080
+ throw ValidationErrors.warning(`agent.local.json has an invalid field: ${issue?.path.join(".")} — ${issue?.message}`, "agent.local.json");
1081
+ }
1082
+ return localResult.data;
1083
+ } catch (error) {
1084
+ if (error.code === "ENOENT") {
1085
+ return null;
1086
+ }
1087
+ if (ValidationErrors.isValidationError(error)) {
1088
+ throw error;
1089
+ }
1090
+ throw ValidationErrors.warning(`Failed to read agent.local.json: ${error.message}`, "agent.local.json");
1091
+ }
1092
+ }
1093
+ function applyLocalOverrides(agentInfo, localInfo) {
1094
+ if (localInfo.botId) {
1095
+ agentInfo.botId = localInfo.botId;
1096
+ }
1097
+ if (localInfo.workspaceId) {
1098
+ agentInfo.workspaceId = localInfo.workspaceId;
1099
+ }
1100
+ if (localInfo.apiUrl) {
1101
+ agentInfo.apiUrl = localInfo.apiUrl;
1102
+ }
1103
+ if (localInfo.devId) {
1104
+ agentInfo.devId = localInfo.devId;
1105
+ }
1106
+ }
1107
+ async function resolveAgent(agentPath, options = {}) {
1108
+ const { required = false, requireWorkspace = false, requireBot = false } = options;
1109
+ const agentJsonPath = path.join(agentPath, "agent.json");
1110
+ const localInfo = await readLocalInfo(agentPath);
1111
+ let agentInfo = null;
1112
+ try {
1113
+ const agentJsonContent = await fs.readFile(agentJsonPath, "utf-8");
1114
+ let agentData;
1115
+ try {
1116
+ agentData = JSON.parse(agentJsonContent);
1117
+ } catch (parseError) {
1118
+ throw ValidationErrors.invalidConfigSyntax("agent.json", parseError.message);
1119
+ }
1120
+ const validationResult = agentInfoSchema.safeParse(agentData);
1121
+ if (!validationResult.success) {
1122
+ const zodError = validationResult.error.errors[0];
1123
+ throw ValidationErrors.invalidConfigSchema("agent.json", zodError?.path.join(".") || "unknown", zodError?.message || "Invalid schema");
1124
+ }
1125
+ agentInfo = validationResult.data;
1126
+ } catch (error) {
1127
+ if (error.code === "ENOENT") {} else if (ValidationErrors.isValidationError(error)) {
1128
+ throw error;
1129
+ } else {
1130
+ throw ValidationErrors.warning(`Failed to read agent.json: ${error.message}`, "agent.json");
1131
+ }
1132
+ }
1133
+ if (!agentInfo) {
1134
+ if (localInfo?.botId && localInfo?.workspaceId) {
1135
+ agentInfo = {
1136
+ botId: localInfo.botId,
1137
+ workspaceId: localInfo.workspaceId,
1138
+ apiUrl: localInfo.apiUrl,
1139
+ devId: localInfo.devId
1140
+ };
1141
+ } else if (required || requireWorkspace || requireBot) {
777
1142
  throw ValidationErrors.requiredFileMissing("agent.json or agent.local.json");
778
1143
  } else {
779
1144
  return null;
@@ -805,8 +1170,8 @@ var exports_credentials = {};
805
1170
  __export(exports_credentials, {
806
1171
  CredentialsManager: () => CredentialsManager
807
1172
  });
808
- import fs3 from "fs/promises";
809
- import path3 from "path";
1173
+ import fs2 from "fs/promises";
1174
+ import path2 from "path";
810
1175
  import os from "os";
811
1176
 
812
1177
  class CredentialsManager {
@@ -814,20 +1179,20 @@ class CredentialsManager {
814
1179
  configDir;
815
1180
  profileOverride;
816
1181
  constructor() {
817
- this.configDir = path3.join(os.homedir(), ".adk");
818
- this.credentialsPath = path3.join(this.configDir, "credentials");
1182
+ this.configDir = path2.join(os.homedir(), ".adk");
1183
+ this.credentialsPath = path2.join(this.configDir, "credentials");
819
1184
  }
820
1185
  setProfileOverride(profile) {
821
1186
  this.profileOverride = profile;
822
1187
  }
823
1188
  async ensureConfigDir() {
824
1189
  try {
825
- await fs3.mkdir(this.configDir, { recursive: true });
1190
+ await fs2.mkdir(this.configDir, { recursive: true });
826
1191
  } catch {}
827
1192
  }
828
1193
  async readCredentials() {
829
1194
  try {
830
- const data = await fs3.readFile(this.credentialsPath, "utf-8");
1195
+ const data = await fs2.readFile(this.credentialsPath, "utf-8");
831
1196
  return JSON.parse(data);
832
1197
  } catch {
833
1198
  return {
@@ -839,8 +1204,8 @@ class CredentialsManager {
839
1204
  }
840
1205
  async writeCredentials(store) {
841
1206
  await this.ensureConfigDir();
842
- await fs3.writeFile(this.credentialsPath, JSON.stringify(store, null, 2));
843
- await fs3.chmod(this.credentialsPath, 384);
1207
+ await fs2.writeFile(this.credentialsPath, JSON.stringify(store, null, 2));
1208
+ await fs2.chmod(this.credentialsPath, 384);
844
1209
  }
845
1210
  async saveCredentials(profileName, credentials, userInfo) {
846
1211
  const store = await this.readCredentials();
@@ -1082,18 +1447,18 @@ var init_service = __esm(() => {
1082
1447
  });
1083
1448
 
1084
1449
  // src/auth/bp-cli-import.ts
1085
- import fs4 from "fs/promises";
1086
- import path4 from "path";
1450
+ import fs3 from "fs/promises";
1451
+ import path3 from "path";
1087
1452
  import os2 from "os";
1088
1453
 
1089
1454
  class BpCliImporter {
1090
1455
  bpCachePath;
1091
1456
  constructor() {
1092
- this.bpCachePath = path4.join(os2.homedir(), ".botpress", "global.cache.json");
1457
+ this.bpCachePath = path3.join(os2.homedir(), ".botpress", "global.cache.json");
1093
1458
  }
1094
1459
  async hasBpCliCredentials() {
1095
1460
  try {
1096
- await fs4.access(this.bpCachePath);
1461
+ await fs3.access(this.bpCachePath);
1097
1462
  return true;
1098
1463
  } catch {
1099
1464
  return false;
@@ -1101,7 +1466,7 @@ class BpCliImporter {
1101
1466
  }
1102
1467
  async getBpCliCredentials() {
1103
1468
  try {
1104
- const data = await fs4.readFile(this.bpCachePath, "utf-8");
1469
+ const data = await fs3.readFile(this.bpCachePath, "utf-8");
1105
1470
  const credentials = JSON.parse(data);
1106
1471
  if (!credentials.token || !credentials.workspaceId || !credentials.apiUrl) {
1107
1472
  return null;
@@ -1354,102 +1719,148 @@ var init_auth = __esm(() => {
1354
1719
  projectClientCache = new Map;
1355
1720
  });
1356
1721
 
1357
- // src/integrations/enhanced-cache.ts
1358
- import fs5 from "fs/promises";
1359
- import path5 from "path";
1722
+ // src/dependencies/catalog/client-factory.ts
1723
+ import { Client as Client3 } from "@botpress/client";
1724
+
1725
+ class CatalogClientFactory {
1726
+ options;
1727
+ client;
1728
+ constructor(options = {}) {
1729
+ this.options = options;
1730
+ }
1731
+ async getClient() {
1732
+ if (this.client)
1733
+ return this.client;
1734
+ const { project, workspaceId, credentials, apiUrl } = this.options;
1735
+ const hasProjectScope = !!(project || workspaceId);
1736
+ if (hasProjectScope) {
1737
+ this.client = await getProjectClient({
1738
+ project,
1739
+ credentials,
1740
+ apiUrl,
1741
+ workspaceId,
1742
+ headers: { ...CATALOG_HEADERS }
1743
+ });
1744
+ } else if (credentials) {
1745
+ this.client = new Client3({
1746
+ token: credentials.token,
1747
+ apiUrl: apiUrl || credentials.apiUrl,
1748
+ ...credentials.workspaceId ? { workspaceId: credentials.workspaceId } : {},
1749
+ headers: { ...CATALOG_HEADERS }
1750
+ });
1751
+ } else {
1752
+ this.client = await getProjectClient({ headers: { ...CATALOG_HEADERS } });
1753
+ }
1754
+ return this.client;
1755
+ }
1756
+ }
1757
+ var CATALOG_HEADERS;
1758
+ var init_client_factory = __esm(() => {
1759
+ init_auth();
1760
+ CATALOG_HEADERS = { "x-multiple-integrations": "true" };
1761
+ });
1762
+
1763
+ // src/dependencies/catalog/resolution-cache.ts
1764
+ import fs4 from "fs/promises";
1765
+ import path4 from "path";
1360
1766
  import os3 from "os";
1361
1767
 
1362
- class EnhancedIntegrationCache {
1768
+ class ResolutionCache {
1363
1769
  cacheDir;
1364
1770
  resolutionsDir;
1365
1771
  definitionsDir;
1772
+ idField;
1366
1773
  noCache;
1367
- constructor(noCache = false) {
1774
+ constructor(config, noCache = false) {
1775
+ this.idField = config.idField;
1368
1776
  this.noCache = noCache;
1369
- this.cacheDir = path5.join(os3.homedir(), ".adk", "cache", "integrations");
1370
- this.resolutionsDir = path5.join(this.cacheDir, "resolutions");
1371
- this.definitionsDir = path5.join(this.cacheDir, "definitions");
1777
+ const cacheRoot = config.cacheRoot ?? path4.join(os3.homedir(), ".adk", "cache");
1778
+ this.cacheDir = path4.join(cacheRoot, config.cacheType);
1779
+ this.resolutionsDir = path4.join(this.cacheDir, "resolutions");
1780
+ this.definitionsDir = path4.join(this.cacheDir, "definitions");
1372
1781
  }
1373
1782
  async ensureCacheDirs() {
1374
- await fs5.mkdir(this.resolutionsDir, { recursive: true });
1375
- await fs5.mkdir(this.definitionsDir, { recursive: true });
1783
+ await fs4.mkdir(this.resolutionsDir, { recursive: true });
1784
+ await fs4.mkdir(this.definitionsDir, { recursive: true });
1376
1785
  }
1377
- async getResolution(name, version, workspace) {
1786
+ async getResolution(name, version, workspace, options) {
1378
1787
  if (this.noCache) {
1379
1788
  return null;
1380
1789
  }
1381
1790
  try {
1382
1791
  const key = this.getResolutionKey(name, version, workspace);
1383
- const cachePath = path5.join(this.resolutionsDir, `${key}.json`);
1384
- const data = await fs5.readFile(cachePath, "utf-8");
1385
- const resolution = JSON.parse(data);
1386
- const cachedAt = new Date(resolution.cachedAt);
1387
- const now = new Date;
1388
- const ageMinutes = (now.getTime() - cachedAt.getTime()) / (1000 * 60);
1389
- if (ageMinutes > 5) {
1792
+ const cachePath = path4.join(this.resolutionsDir, `${key}.json`);
1793
+ const data = await fs4.readFile(cachePath, "utf-8");
1794
+ const raw = JSON.parse(data);
1795
+ if (!options?.allowStale) {
1796
+ const cachedAt = new Date(raw.cachedAt);
1797
+ const ageMinutes = (Date.now() - cachedAt.getTime()) / (1000 * 60);
1798
+ if (ageMinutes > RESOLUTION_TTL_MINUTES) {
1799
+ return null;
1800
+ }
1801
+ }
1802
+ const id = raw[this.idField];
1803
+ if (!id) {
1390
1804
  return null;
1391
1805
  }
1392
- return resolution;
1806
+ return { id, updatedAt: raw.updatedAt, cachedAt: raw.cachedAt };
1393
1807
  } catch {
1394
1808
  return null;
1395
1809
  }
1396
1810
  }
1397
- async setResolution(name, version, workspace, integrationId, updatedAt) {
1811
+ async setResolution(name, version, workspace, id, updatedAt) {
1398
1812
  await this.ensureCacheDirs();
1399
1813
  const key = this.getResolutionKey(name, version, workspace);
1400
- const cachePath = path5.join(this.resolutionsDir, `${key}.json`);
1814
+ const cachePath = path4.join(this.resolutionsDir, `${key}.json`);
1401
1815
  const resolution = {
1402
- integrationId,
1816
+ [this.idField]: id,
1403
1817
  updatedAt,
1404
1818
  cachedAt: new Date().toISOString()
1405
1819
  };
1406
- await fs5.writeFile(cachePath, JSON.stringify(resolution));
1820
+ await fs4.writeFile(cachePath, JSON.stringify(resolution));
1407
1821
  }
1408
- async getDefinition(integrationId, updatedAt) {
1822
+ async getDefinition(id, updatedAt) {
1409
1823
  if (this.noCache) {
1410
1824
  return null;
1411
1825
  }
1412
1826
  try {
1413
- const key = this.getDefinitionKey(integrationId, updatedAt);
1414
- const cachePath = path5.join(this.definitionsDir, `${key}.json`);
1415
- const data = await fs5.readFile(cachePath, "utf-8");
1827
+ const key = this.getDefinitionKey(id, updatedAt);
1828
+ const cachePath = path4.join(this.definitionsDir, `${key}.json`);
1829
+ const data = await fs4.readFile(cachePath, "utf-8");
1416
1830
  const cached = JSON.parse(data);
1417
1831
  return cached.definition;
1418
1832
  } catch {
1419
1833
  return null;
1420
1834
  }
1421
1835
  }
1422
- async setDefinition(integrationId, updatedAt, definition) {
1836
+ async setDefinition(id, updatedAt, definition) {
1423
1837
  await this.ensureCacheDirs();
1424
- const key = this.getDefinitionKey(integrationId, updatedAt);
1425
- const cachePath = path5.join(this.definitionsDir, `${key}.json`);
1838
+ const key = this.getDefinitionKey(id, updatedAt);
1839
+ const cachePath = path4.join(this.definitionsDir, `${key}.json`);
1426
1840
  const cached = {
1427
1841
  definition,
1428
1842
  cachedAt: new Date().toISOString()
1429
1843
  };
1430
- await fs5.writeFile(cachePath, JSON.stringify(cached));
1844
+ await fs4.writeFile(cachePath, JSON.stringify(cached));
1431
1845
  }
1432
1846
  async clear() {
1433
1847
  try {
1434
- const resolutionFiles = await fs5.readdir(this.resolutionsDir);
1435
- await Promise.all(resolutionFiles.map((file) => fs5.unlink(path5.join(this.resolutionsDir, file))));
1436
- const definitionFiles = await fs5.readdir(this.definitionsDir);
1437
- await Promise.all(definitionFiles.map((file) => fs5.unlink(path5.join(this.definitionsDir, file))));
1848
+ const resolutionFiles = await fs4.readdir(this.resolutionsDir);
1849
+ await Promise.all(resolutionFiles.map((file) => fs4.unlink(path4.join(this.resolutionsDir, file))));
1850
+ const definitionFiles = await fs4.readdir(this.definitionsDir);
1851
+ await Promise.all(definitionFiles.map((file) => fs4.unlink(path4.join(this.definitionsDir, file))));
1438
1852
  } catch {}
1439
1853
  }
1440
1854
  async getStats() {
1441
1855
  const getDirectoryStats = async (dir) => {
1442
1856
  try {
1443
- const files = await fs5.readdir(dir);
1857
+ const files = await fs4.readdir(dir);
1444
1858
  let totalSize = 0;
1445
1859
  for (const file of files) {
1446
- const stats = await fs5.stat(path5.join(dir, file));
1860
+ const stats = await fs4.stat(path4.join(dir, file));
1447
1861
  totalSize += stats.size;
1448
1862
  }
1449
- return {
1450
- count: files.length,
1451
- sizeBytes: totalSize
1452
- };
1863
+ return { count: files.length, sizeBytes: totalSize };
1453
1864
  } catch {
1454
1865
  return { count: 0, sizeBytes: 0 };
1455
1866
  }
@@ -1465,238 +1876,65 @@ class EnhancedIntegrationCache {
1465
1876
  const key = `${prefix}${name}_${version}`;
1466
1877
  return key.replace(/[^a-zA-Z0-9_-]/g, "_");
1467
1878
  }
1468
- getDefinitionKey(integrationId, updatedAt) {
1469
- const key = `${integrationId}_${updatedAt}`;
1879
+ getDefinitionKey(id, updatedAt) {
1880
+ const key = `${id}_${updatedAt}`;
1470
1881
  return key.replace(/[^a-zA-Z0-9_-]/g, "_");
1471
1882
  }
1472
1883
  }
1473
- var init_enhanced_cache = () => {};
1474
-
1475
- // src/agent-project/dependencies-parser.ts
1476
- import { z as z3 } from "@botpress/sdk";
1477
- function isIntegrationAliasValid(alias) {
1478
- return alias.length >= INTEGRATION_ALIAS_MIN_LENGTH && alias.length <= INTEGRATION_ALIAS_MAX_LENGTH && INTEGRATION_ALIAS_REGEX.test(alias);
1479
- }
1884
+ var RESOLUTION_TTL_MINUTES = 5;
1885
+ var init_resolution_cache = () => {};
1480
1886
 
1481
- class IntegrationParser {
1482
- static parseIntegrationRef(versionString) {
1483
- const result = integrationRefSchema.safeParse(versionString);
1484
- if (!result.success) {
1485
- throw new AdkError({
1486
- code: "INVALID_VERSION_FORMAT",
1487
- expected: true,
1488
- message: result.error.errors[0]?.message || "Invalid integration version format"
1489
- });
1490
- }
1491
- return result.data;
1887
+ // src/dependencies/catalog/catalog-service.ts
1888
+ class CatalogService {
1889
+ source;
1890
+ cache;
1891
+ constructor(source, noCache = false) {
1892
+ this.source = source;
1893
+ this.cache = new ResolutionCache(source.cacheConfig, noCache);
1492
1894
  }
1493
- static parseIntegrations(dependencies) {
1494
- const integrations = [];
1495
- const errors = [];
1496
- if (!dependencies.integrations) {
1497
- return { integrations, errors };
1498
- }
1499
- for (const [alias, value] of Object.entries(dependencies.integrations)) {
1500
- try {
1501
- if (!isIntegrationAliasValid(alias)) {
1502
- errors.push(ValidationErrors.invalidIntegrationAlias(alias));
1503
- continue;
1504
- }
1505
- const normalized = typeof value === "string" ? { version: value } : value;
1506
- const ref = this.parseIntegrationRef(normalized.version);
1507
- const versionResult = versionSchema.safeParse(ref.version);
1508
- if (!versionResult.success) {
1509
- errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version));
1510
- }
1511
- integrations.push({
1512
- alias,
1513
- ref,
1514
- enabled: "enabled" in normalized ? normalized.enabled : undefined,
1515
- configurationType: "configurationType" in normalized ? normalized.configurationType : undefined,
1516
- config: "config" in normalized ? normalized.config : undefined
1517
- });
1518
- } catch (error) {
1519
- errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid integration '${alias}': ${error instanceof Error ? error.message : String(error)}`));
1895
+ async getDefinition(ref) {
1896
+ const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace);
1897
+ if (cachedResolution) {
1898
+ const cachedDefinition = await this.cache.getDefinition(cachedResolution.id, cachedResolution.updatedAt);
1899
+ if (cachedDefinition) {
1900
+ return cachedDefinition;
1520
1901
  }
1521
1902
  }
1522
- return { integrations, errors };
1523
- }
1524
- static checkDuplicates(integrations) {
1525
- const errors = [];
1526
- const seen = new Map;
1527
- for (const integration of integrations) {
1528
- const key = integration.ref.fullName;
1529
- const group = seen.get(key) || [];
1530
- group.push(integration);
1531
- seen.set(key, group);
1532
- }
1533
- for (const [integrationName, group] of seen.entries()) {
1534
- if (group.length > 1) {
1535
- const duplicateConfigs = [];
1536
- for (let i = 0;i < group.length; i++) {
1537
- for (let j = i + 1;j < group.length; j++) {
1538
- const configA = JSON.stringify(group[i].config ?? {});
1539
- const configB = JSON.stringify(group[j].config ?? {});
1540
- if (configA === configB) {
1541
- if (!duplicateConfigs.includes(group[i].alias)) {
1542
- duplicateConfigs.push(group[i].alias);
1543
- }
1544
- if (!duplicateConfigs.includes(group[j].alias)) {
1545
- duplicateConfigs.push(group[j].alias);
1546
- }
1547
- }
1548
- }
1549
- }
1550
- if (duplicateConfigs.length > 0) {
1551
- errors.push(ValidationErrors.warning(`Integration '${integrationName}' has aliases with identical configurations: ${duplicateConfigs.join(", ")}. Consider using different configs or removing duplicates.`, "agent.config.ts"));
1903
+ try {
1904
+ const { id, updatedAt, definition } = await this.source.fetchByRef(ref);
1905
+ await this.cache.setResolution(ref.name, ref.version, ref.workspace, id, updatedAt);
1906
+ await this.cache.setDefinition(id, updatedAt, definition);
1907
+ return definition;
1908
+ } catch (err) {
1909
+ if (!(err instanceof AdkError && err.expected)) {
1910
+ const stale = await this.getStaleDefinition(ref);
1911
+ if (stale !== null) {
1912
+ return stale;
1552
1913
  }
1553
1914
  }
1915
+ throw err;
1554
1916
  }
1555
- return errors;
1556
- }
1557
- }
1558
- function isPluginAliasValid(alias) {
1559
- return alias.length >= PLUGIN_ALIAS_MIN_LENGTH && alias.length <= PLUGIN_ALIAS_MAX_LENGTH && PLUGIN_ALIAS_REGEX.test(alias);
1560
- }
1561
-
1562
- class PluginParser {
1563
- static parsePluginRef(versionString) {
1564
- const result = pluginRefSchema.safeParse(versionString);
1565
- if (!result.success) {
1566
- throw new AdkError({
1567
- code: "INVALID_VERSION_FORMAT",
1568
- expected: true,
1569
- message: result.error.errors[0]?.message || "Invalid plugin version format"
1570
- });
1571
- }
1572
- return result.data;
1573
1917
  }
1574
- static parsePlugins(dependencies) {
1575
- const plugins = [];
1576
- const errors = [];
1577
- if (!dependencies.plugins) {
1578
- return { plugins, errors };
1579
- }
1580
- for (const [alias, value] of Object.entries(dependencies.plugins)) {
1581
- try {
1582
- if (!isPluginAliasValid(alias)) {
1583
- errors.push(ValidationErrors.invalidPluginAlias(alias));
1584
- continue;
1585
- }
1586
- const ref = this.parsePluginRef(value.version);
1587
- const versionResult = versionSchema.safeParse(ref.version);
1588
- if (!versionResult.success) {
1589
- errors.push(ValidationErrors.invalidPluginVersionFormat(alias, ref.version));
1590
- }
1591
- plugins.push({
1592
- alias,
1593
- ref,
1594
- config: value.config,
1595
- dependencies: value.dependencies
1596
- });
1597
- } catch (error) {
1598
- errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid plugin '${alias}': ${error instanceof Error ? error.message : String(error)}`));
1599
- }
1600
- }
1601
- return { plugins, errors };
1918
+ async getStaleDefinition(ref) {
1919
+ const stale = await this.cache.getResolution(ref.name, ref.version, ref.workspace, { allowStale: true });
1920
+ if (!stale)
1921
+ return null;
1922
+ return this.cache.getDefinition(stale.id, stale.updatedAt);
1602
1923
  }
1603
- static validateDependencyReferences(dependencies) {
1604
- const errors = [];
1605
- if (!dependencies.plugins) {
1606
- return errors;
1607
- }
1608
- const integrationAliases = Object.keys(dependencies.integrations || {});
1609
- for (const [alias, pluginConfig] of Object.entries(dependencies.plugins)) {
1610
- if (!pluginConfig.dependencies) {
1611
- continue;
1612
- }
1613
- for (const [_depAlias, depMapping] of Object.entries(pluginConfig.dependencies)) {
1614
- if (!integrationAliases.includes(depMapping.integrationAlias)) {
1615
- errors.push(ValidationErrors.invalidPluginDependency(alias, depMapping.integrationAlias, integrationAliases));
1616
- }
1617
- }
1618
- }
1619
- return errors;
1924
+ async getCacheStats() {
1925
+ const stats = await this.cache.getStats();
1926
+ return {
1927
+ count: stats.resolutions.count + stats.definitions.count,
1928
+ sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
1929
+ };
1620
1930
  }
1621
- static checkDuplicates(plugins) {
1622
- const errors = [];
1623
- const seen = new Map;
1624
- for (const plugin of plugins) {
1625
- const key = plugin.ref.fullName;
1626
- const group = seen.get(key) || [];
1627
- group.push(plugin);
1628
- seen.set(key, group);
1629
- }
1630
- for (const [pluginName, group] of seen.entries()) {
1631
- if (group.length > 1) {
1632
- const duplicateConfigs = [];
1633
- for (let i = 0;i < group.length; i++) {
1634
- for (let j = i + 1;j < group.length; j++) {
1635
- const configA = JSON.stringify(group[i].config ?? {});
1636
- const configB = JSON.stringify(group[j].config ?? {});
1637
- if (configA === configB) {
1638
- if (!duplicateConfigs.includes(group[i].alias)) {
1639
- duplicateConfigs.push(group[i].alias);
1640
- }
1641
- if (!duplicateConfigs.includes(group[j].alias)) {
1642
- duplicateConfigs.push(group[j].alias);
1643
- }
1644
- }
1645
- }
1646
- }
1647
- if (duplicateConfigs.length > 0) {
1648
- errors.push(ValidationErrors.warning(`Plugin '${pluginName}' has aliases with identical configurations: ${duplicateConfigs.join(", ")}. Consider using different configs or removing duplicates.`, "agent.config.ts"));
1649
- }
1650
- }
1651
- }
1652
- return errors;
1931
+ async clearCache() {
1932
+ await this.cache.clear();
1653
1933
  }
1654
1934
  }
1655
- var INTEGRATION_ALIAS_MIN_LENGTH = 2, INTEGRATION_ALIAS_MAX_LENGTH = 100, INTEGRATION_ALIAS_REGEX, integrationRefSchema, versionSchema, PLUGIN_ALIAS_MIN_LENGTH = 2, PLUGIN_ALIAS_MAX_LENGTH = 100, PLUGIN_ALIAS_REGEX, pluginRefSchema;
1656
- var init_dependencies_parser = __esm(() => {
1935
+ var init_catalog_service = __esm(() => {
1657
1936
  init_src();
1658
- init_validation_errors();
1659
- INTEGRATION_ALIAS_REGEX = /^(?:[a-z][a-z0-9_-]*\/)?[a-z][a-z0-9_-]*$/;
1660
- integrationRefSchema = z3.string().transform((val, ctx) => {
1661
- const match = val.match(/^(?:([^/]+)\/)?([^@]+)@(.+)$/);
1662
- if (!match) {
1663
- ctx.addIssue({
1664
- code: "custom",
1665
- message: `Invalid integration version format: ${val}. Expected format: 'name@version' or 'workspace/name@version'`
1666
- });
1667
- return;
1668
- }
1669
- const [, workspace, name, version] = match;
1670
- return {
1671
- workspace: workspace || undefined,
1672
- name,
1673
- version,
1674
- fullName: workspace ? `${workspace}/${name}` : name
1675
- };
1676
- });
1677
- versionSchema = z3.string().refine((version) => {
1678
- if (version === "latest")
1679
- return true;
1680
- const semverPattern = /^(\d+)\.(\d+)\.(\d+)(-[\w.]+)?(\+[\w.]+)?$/;
1681
- return semverPattern.test(version);
1682
- }, { message: "Version must be exact semver (e.g., 1.2.3) or 'latest'" });
1683
- PLUGIN_ALIAS_REGEX = /^[a-z][a-z0-9_-]*$/;
1684
- pluginRefSchema = z3.string().transform((val, ctx) => {
1685
- const match = val.match(/^([^/@]+)@(.+)$/);
1686
- if (!match) {
1687
- ctx.addIssue({
1688
- code: "custom",
1689
- message: `Invalid plugin version format: ${val}. Expected format: 'name@version' (no workspace prefix)`
1690
- });
1691
- return;
1692
- }
1693
- const [, name, version] = match;
1694
- return {
1695
- name,
1696
- version,
1697
- fullName: name
1698
- };
1699
- });
1937
+ init_resolution_cache();
1700
1938
  });
1701
1939
 
1702
1940
  // src/utils/search-ranking.ts
@@ -1765,109 +2003,23 @@ function normalize(value) {
1765
2003
  }
1766
2004
  var init_search_ranking = () => {};
1767
2005
 
1768
- // src/integrations/manager.ts
1769
- import { Client as Client3 } from "@botpress/client";
1770
-
1771
- class IntegrationManager {
1772
- cache;
1773
- options;
1774
- client;
1775
- constructor(options = {}) {
1776
- this.options = options;
1777
- this.cache = new EnhancedIntegrationCache(options.noCache || false);
1778
- }
1779
- async getClient() {
1780
- if (!this.client) {
1781
- const hasProjectScope = !!(this.options.project || this.options.workspaceId);
1782
- if (hasProjectScope) {
1783
- this.client = await getProjectClient({
1784
- project: this.options.project,
1785
- credentials: this.options.credentials,
1786
- apiUrl: this.options.apiUrl,
1787
- workspaceId: this.options.workspaceId,
1788
- headers: {
1789
- "x-multiple-integrations": "true"
1790
- }
1791
- });
1792
- } else if (this.options.credentials) {
1793
- this.client = new Client3({
1794
- token: this.options.credentials.token,
1795
- apiUrl: this.options.apiUrl || this.options.credentials.apiUrl,
1796
- ...this.options.credentials.workspaceId ? { workspaceId: this.options.credentials.workspaceId } : {},
1797
- headers: {
1798
- "x-multiple-integrations": "true"
1799
- }
1800
- });
1801
- } else {
1802
- this.client = await getProjectClient({
1803
- headers: {
1804
- "x-multiple-integrations": "true"
1805
- }
1806
- });
1807
- }
1808
- }
1809
- return this.client;
1810
- }
1811
- async loadIntegrations(dependencies) {
1812
- const errors = [];
1813
- const warnings = [];
1814
- const parseResult = IntegrationParser.parseIntegrations(dependencies);
1815
- const integrations = parseResult.integrations;
1816
- errors.push(...parseResult.errors);
1817
- const duplicateWarnings = IntegrationParser.checkDuplicates(integrations);
1818
- warnings.push(...duplicateWarnings);
1819
- const fetchPromises = integrations.map(async (integration) => {
1820
- try {
1821
- const definition = await this.fetchIntegration(integration.ref);
1822
- integration.definition = definition;
1823
- const validation = this.validateIntegration(integration);
1824
- integration.validationResult = validation;
1825
- if (!validation.valid) {
1826
- validation.errors.forEach(() => {
1827
- errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName));
1828
- });
1829
- }
1830
- if (validation.warnings.length > 0) {
1831
- validation.warnings.forEach((warn) => {
1832
- warnings.push(ValidationErrors.warning(warn, "agent.config.ts"));
1833
- });
1834
- }
1835
- } catch (error) {
1836
- if (error instanceof Error && error.message.includes("version")) {
1837
- errors.push(ValidationErrors.integrationVersionError(integration.alias, error.message));
1838
- } else {
1839
- const errorMessage = error instanceof Error ? error.message : undefined;
1840
- errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName, errorMessage));
1841
- }
1842
- }
1843
- });
1844
- await Promise.all(fetchPromises);
1845
- const hasChannels = integrations.some((i) => i.definition?.channels && Object.keys(i.definition.channels).length > 0);
1846
- if (!hasChannels && integrations.length > 0) {
1847
- warnings.push(ValidationErrors.warning("No integrations with channels found. Your agent may not be able to receive messages.", "agent.config.ts", "Add an integration with channels (e.g., slack, webchat) to enable conversations"));
1848
- }
1849
- return { integrations, errors, warnings };
1850
- }
1851
- async fetchIntegration(ref) {
1852
- const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace);
1853
- if (cachedResolution) {
1854
- const cachedDefinition = await this.cache.getDefinition(cachedResolution.integrationId, cachedResolution.updatedAt);
1855
- if (cachedDefinition) {
1856
- return cachedDefinition;
1857
- }
1858
- }
1859
- const client = await this.getClient();
2006
+ // src/dependencies/catalog/integration-source.ts
2007
+ class IntegrationCatalogSource {
2008
+ clientFactory;
2009
+ cacheConfig = { cacheType: "integrations", idField: "integrationId" };
2010
+ constructor(clientFactory) {
2011
+ this.clientFactory = clientFactory;
2012
+ }
2013
+ async fetchByRef(ref) {
2014
+ const client = await this.clientFactory.getClient();
1860
2015
  const integration = await this._findPrivateOrPublicIntegration(client, ref);
1861
2016
  if (!integration) {
1862
2017
  throw await this._buildIntegrationNotFoundError(client, ref);
1863
2018
  }
1864
- await this.cache.setResolution(ref.name, ref.version, ref.workspace, integration.id, integration.updatedAt);
1865
- const definition = integration;
1866
- await this.cache.setDefinition(integration.id, integration.updatedAt, definition);
1867
- return definition;
2019
+ return { id: integration.id, updatedAt: integration.updatedAt, definition: integration };
1868
2020
  }
1869
- async searchIntegrations(query, limit = 20) {
1870
- const client = await this.getClient();
2021
+ async search(query, limit = 20) {
2022
+ const client = await this.clientFactory.getClient();
1871
2023
  const results = new Map;
1872
2024
  const scanLimit = Math.max(limit * 5, 50);
1873
2025
  for await (const integration of client.list.publicIntegrations({
@@ -1892,7 +2044,7 @@ class IntegrationManager {
1892
2044
  return getSortedCatalogSearchResults(results, limit);
1893
2045
  }
1894
2046
  async findImplementersOfInterface(interfaceName, limit = 10) {
1895
- const client = await this.getClient();
2047
+ const client = await this.clientFactory.getClient();
1896
2048
  const seen = new Map;
1897
2049
  for await (const integration of client.list.publicIntegrations({
1898
2050
  interfaceName,
@@ -1908,8 +2060,8 @@ class IntegrationManager {
1908
2060
  }
1909
2061
  return [...seen.values()];
1910
2062
  }
1911
- async listIntegrationVersions(name) {
1912
- const client = await this.getClient();
2063
+ async listVersions(name) {
2064
+ const client = await this.clientFactory.getClient();
1913
2065
  const versions = new Set;
1914
2066
  for await (const integration of client.list.publicIntegrations({
1915
2067
  name,
@@ -1973,7 +2125,7 @@ class IntegrationManager {
1973
2125
  const scope = ref.workspace ? `workspace "${ref.workspace}"` : "the official Botpress hub";
1974
2126
  return new AdkError({
1975
2127
  code: "INTEGRATION_NOT_FOUND",
1976
- message: `Integration "${ref.name}" version "${ref.version}" not found in ${scope} ` + `(latest is ${latestExists.version}). Run 'adk info ${ref.fullName}' to see available versions.`,
2128
+ message: `Integration "${ref.name}" version "${ref.version}" not found in ${scope} ` + `(latest is ${latestExists.version}). Run 'adk integrations info ${ref.fullName}' to see available versions.`,
1977
2129
  expected: true
1978
2130
  });
1979
2131
  }
@@ -1989,36 +2141,126 @@ class IntegrationManager {
1989
2141
  let workspaceId;
1990
2142
  try {
1991
2143
  const credentials = await resolveWorkspaceCredentials({
1992
- project: this.options.project,
1993
- credentials: this.options.credentials,
1994
- apiUrl: this.options.apiUrl,
1995
- workspaceId: this.options.workspaceId
2144
+ project: this.clientFactory.options.project,
2145
+ credentials: this.clientFactory.options.credentials,
2146
+ apiUrl: this.clientFactory.options.apiUrl,
2147
+ workspaceId: this.clientFactory.options.workspaceId
1996
2148
  });
1997
2149
  workspaceId = credentials.workspaceId;
1998
2150
  if (workspaceId) {
1999
2151
  const currentWorkspace = await client.getWorkspace({ id: workspaceId });
2000
2152
  currentWorkspaceHandle = currentWorkspace?.handle;
2001
2153
  }
2002
- } catch {
2003
- return new AdkError({
2004
- code: "INTEGRATION_NOT_FOUND",
2005
- message: `Integration "${ref.name}" not found in workspace "${ref.workspace}"`,
2006
- expected: true
2007
- });
2008
- }
2009
- if (currentWorkspaceHandle === ref.workspace) {
2010
- return new AdkError({
2011
- code: "INTEGRATION_NOT_FOUND",
2012
- message: `Integration "${ref.name}" not found in workspace "${ref.workspace}" (workspaceId: ${workspaceId}). ` + `Are you sure you published the integration? ` + `Run 'adk deploy' to publish it to your workspace.`,
2013
- expected: true,
2014
- suggestion: "Are you sure you published the integration? Run 'adk deploy' to publish it to your workspace."
2015
- });
2016
- }
2017
- return new AdkError({
2018
- code: "INTEGRATION_NOT_FOUND",
2019
- message: `Integration "${ref.name}" not found in workspace "${ref.workspace}" (current workspaceId: ${workspaceId}). ` + `This integration may be private. Private integrations can only be installed in the same workspace. ` + `If you want to share this integration with other workspaces, deploy it with --visibility="unlisted" or --visibility="public".`,
2020
- expected: true
2154
+ } catch {
2155
+ return new AdkError({
2156
+ code: "INTEGRATION_NOT_FOUND",
2157
+ message: `Integration "${ref.name}" not found in workspace "${ref.workspace}"`,
2158
+ expected: true
2159
+ });
2160
+ }
2161
+ if (currentWorkspaceHandle === ref.workspace) {
2162
+ return new AdkError({
2163
+ code: "INTEGRATION_NOT_FOUND",
2164
+ message: `Integration "${ref.name}" not found in workspace "${ref.workspace}" (workspaceId: ${workspaceId}). ` + `Are you sure you published the integration? ` + `Run 'adk deploy' to publish it to your workspace.`,
2165
+ expected: true,
2166
+ suggestion: "Are you sure you published the integration? Run 'adk deploy' to publish it to your workspace."
2167
+ });
2168
+ }
2169
+ return new AdkError({
2170
+ code: "INTEGRATION_NOT_FOUND",
2171
+ message: `Integration "${ref.name}" not found in workspace "${ref.workspace}" (current workspaceId: ${workspaceId}). ` + `This integration may be private. Private integrations can only be installed in the same workspace. ` + `If you want to share this integration with other workspaces, deploy it with --visibility="unlisted" or --visibility="public".`,
2172
+ expected: true
2173
+ });
2174
+ }
2175
+ }
2176
+ function toHubCacheEntry(integration) {
2177
+ return {
2178
+ id: integration.id,
2179
+ name: integration.name,
2180
+ version: integration.version,
2181
+ updatedAt: integration.updatedAt,
2182
+ createdAt: integration.createdAt,
2183
+ title: integration.title,
2184
+ description: integration.description,
2185
+ iconUrl: integration.iconUrl,
2186
+ public: integration.public,
2187
+ visibility: integration.visibility,
2188
+ ownerWorkspace: integration.ownerWorkspace ? { id: integration.ownerWorkspace.id, name: integration.ownerWorkspace.name } : undefined,
2189
+ verificationStatus: integration.verificationStatus
2190
+ };
2191
+ }
2192
+ var init_integration_source = __esm(() => {
2193
+ init_src();
2194
+ init_auth();
2195
+ init_search_ranking();
2196
+ });
2197
+
2198
+ // src/integrations/manager.ts
2199
+ class IntegrationManager {
2200
+ source;
2201
+ service;
2202
+ constructor(options = {}) {
2203
+ const { noCache, ...clientOptions } = options;
2204
+ this.source = new IntegrationCatalogSource(new CatalogClientFactory(clientOptions));
2205
+ this.service = new CatalogService(this.source, noCache || false);
2206
+ }
2207
+ async loadIntegrations(dependencies) {
2208
+ const errors = [];
2209
+ const warnings = [];
2210
+ const parseResult = IntegrationParser.parseIntegrations(dependencies);
2211
+ const integrations = parseResult.integrations;
2212
+ errors.push(...parseResult.errors);
2213
+ const duplicateWarnings = IntegrationParser.checkDuplicates(integrations);
2214
+ warnings.push(...duplicateWarnings);
2215
+ const fetchPromises = integrations.map(async (integration) => {
2216
+ try {
2217
+ const definition = await this.fetchIntegration(integration.ref);
2218
+ integration.definition = definition;
2219
+ const validation = this.validateIntegration(integration);
2220
+ integration.validationResult = validation;
2221
+ if (!validation.valid) {
2222
+ validation.errors.forEach(() => {
2223
+ errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName));
2224
+ });
2225
+ }
2226
+ if (validation.warnings.length > 0) {
2227
+ validation.warnings.forEach((warn) => {
2228
+ warnings.push(ValidationErrors.warning(warn, "agent.config.ts"));
2229
+ });
2230
+ }
2231
+ } catch (error) {
2232
+ if (error instanceof Error && error.message.includes("version")) {
2233
+ errors.push(ValidationErrors.integrationVersionError(integration.alias, error.message));
2234
+ } else {
2235
+ const errorMessage = error instanceof Error ? error.message : undefined;
2236
+ errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName, errorMessage));
2237
+ }
2238
+ }
2021
2239
  });
2240
+ await Promise.all(fetchPromises);
2241
+ const hasChannels = integrations.some((i) => i.definition?.channels && Object.keys(i.definition.channels).length > 0);
2242
+ if (!hasChannels && integrations.length > 0) {
2243
+ warnings.push(ValidationErrors.warning("No integrations with channels found. Your agent may not be able to receive messages.", "agent.config.ts", "Add an integration with channels (e.g., slack, webchat) to enable conversations"));
2244
+ }
2245
+ return { integrations, errors, warnings };
2246
+ }
2247
+ async fetchIntegration(ref) {
2248
+ return this.service.getDefinition(ref);
2249
+ }
2250
+ async searchIntegrations(query, limit = 20) {
2251
+ return this.source.search(query, limit);
2252
+ }
2253
+ async findImplementersOfInterface(interfaceName, limit = 10) {
2254
+ return this.source.findImplementersOfInterface(interfaceName, limit);
2255
+ }
2256
+ async listIntegrationVersions(name) {
2257
+ return this.source.listVersions(name);
2258
+ }
2259
+ async getCacheStats() {
2260
+ return this.service.getCacheStats();
2261
+ }
2262
+ async clearCache() {
2263
+ await this.service.clearCache();
2022
2264
  }
2023
2265
  validateIntegration(integration) {
2024
2266
  const errors = [];
@@ -2049,40 +2291,13 @@ class IntegrationManager {
2049
2291
  missingChannels: !hasChannels
2050
2292
  };
2051
2293
  }
2052
- async getCacheStats() {
2053
- const stats = await this.cache.getStats();
2054
- return {
2055
- count: stats.resolutions.count + stats.definitions.count,
2056
- sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
2057
- };
2058
- }
2059
- async clearCache() {
2060
- await this.cache.clear();
2061
- }
2062
- }
2063
- function toHubCacheEntry(integration) {
2064
- return {
2065
- id: integration.id,
2066
- name: integration.name,
2067
- version: integration.version,
2068
- updatedAt: integration.updatedAt,
2069
- createdAt: integration.createdAt,
2070
- title: integration.title,
2071
- description: integration.description,
2072
- iconUrl: integration.iconUrl,
2073
- public: integration.public,
2074
- visibility: integration.visibility,
2075
- ownerWorkspace: integration.ownerWorkspace ? { id: integration.ownerWorkspace.id, name: integration.ownerWorkspace.name } : undefined,
2076
- verificationStatus: integration.verificationStatus
2077
- };
2078
2294
  }
2079
2295
  var init_manager = __esm(() => {
2080
- init_src();
2081
- init_auth();
2082
- init_enhanced_cache();
2083
2296
  init_dependencies_parser();
2084
2297
  init_validation_errors();
2085
- init_search_ranking();
2298
+ init_client_factory();
2299
+ init_catalog_service();
2300
+ init_integration_source();
2086
2301
  });
2087
2302
 
2088
2303
  // src/assets/types.ts
@@ -2092,8 +2307,8 @@ var init_types3 = () => {};
2092
2307
  var defaultAdkFolder = ".adk";
2093
2308
 
2094
2309
  // src/assets/cache.ts
2095
- import fs7 from "fs/promises";
2096
- import path7 from "path";
2310
+ import fs5 from "fs/promises";
2311
+ import path5 from "path";
2097
2312
 
2098
2313
  class AssetsCacheManager {
2099
2314
  projectPath;
@@ -2101,14 +2316,14 @@ class AssetsCacheManager {
2101
2316
  cache = null;
2102
2317
  constructor(projectPath) {
2103
2318
  this.projectPath = projectPath;
2104
- this.cachePath = path7.join(projectPath, defaultAdkFolder, "assets-cache.json");
2319
+ this.cachePath = path5.join(projectPath, defaultAdkFolder, "assets-cache.json");
2105
2320
  }
2106
2321
  async load() {
2107
2322
  if (this.cache) {
2108
2323
  return this.cache;
2109
2324
  }
2110
2325
  try {
2111
- const content = await fs7.readFile(this.cachePath, "utf-8");
2326
+ const content = await fs5.readFile(this.cachePath, "utf-8");
2112
2327
  this.cache = JSON.parse(content);
2113
2328
  return this.cache;
2114
2329
  } catch {
@@ -2123,9 +2338,9 @@ class AssetsCacheManager {
2123
2338
  if (!this.cache) {
2124
2339
  return;
2125
2340
  }
2126
- const cacheDir = path7.dirname(this.cachePath);
2127
- await fs7.mkdir(cacheDir, { recursive: true });
2128
- await fs7.writeFile(this.cachePath, JSON.stringify(this.cache, null, 2), "utf-8");
2341
+ const cacheDir = path5.dirname(this.cachePath);
2342
+ await fs5.mkdir(cacheDir, { recursive: true });
2343
+ await fs5.writeFile(this.cachePath, JSON.stringify(this.cache, null, 2), "utf-8");
2129
2344
  }
2130
2345
  async getEntry(assetPath) {
2131
2346
  const cache = await this.load();
@@ -2168,8 +2383,8 @@ class AssetsCacheManager {
2168
2383
  var init_cache = () => {};
2169
2384
 
2170
2385
  // src/assets/manager.ts
2171
- import fs8 from "fs/promises";
2172
- import path8 from "path";
2386
+ import fs6 from "fs/promises";
2387
+ import path6 from "path";
2173
2388
  import crypto from "crypto";
2174
2389
 
2175
2390
  class AssetsManager {
@@ -2181,7 +2396,7 @@ class AssetsManager {
2181
2396
  cacheManager;
2182
2397
  constructor(options) {
2183
2398
  this.projectPath = options.projectPath;
2184
- this.assetsPath = path8.join(this.projectPath, "assets");
2399
+ this.assetsPath = path6.join(this.projectPath, "assets");
2185
2400
  this.botId = options.botId;
2186
2401
  this.credentials = options.credentials;
2187
2402
  this.cacheManager = new AssetsCacheManager(this.projectPath);
@@ -2219,7 +2434,7 @@ class AssetsManager {
2219
2434
  }
2220
2435
  async hasAssetsDirectory() {
2221
2436
  try {
2222
- const stats = await fs8.stat(this.assetsPath);
2437
+ const stats = await fs6.stat(this.assetsPath);
2223
2438
  return stats.isDirectory();
2224
2439
  } catch {
2225
2440
  return false;
@@ -2233,16 +2448,16 @@ class AssetsManager {
2233
2448
  const assets = [];
2234
2449
  for (const filePath of files) {
2235
2450
  try {
2236
- const stats = await fs8.stat(filePath);
2451
+ const stats = await fs6.stat(filePath);
2237
2452
  if (stats.isFile()) {
2238
- const relativePath = path8.relative(this.assetsPath, filePath);
2239
- const content = await fs8.readFile(filePath);
2453
+ const relativePath = path6.relative(this.assetsPath, filePath);
2454
+ const content = await fs6.readFile(filePath);
2240
2455
  const hash = this.calculateHash(content);
2241
2456
  const mime = this.getMimeType(filePath);
2242
2457
  assets.push({
2243
2458
  relativePath,
2244
2459
  absolutePath: filePath,
2245
- name: path8.basename(filePath),
2460
+ name: path6.basename(filePath),
2246
2461
  size: stats.size,
2247
2462
  mime,
2248
2463
  hash,
@@ -2270,7 +2485,7 @@ class AssetsManager {
2270
2485
  });
2271
2486
  return response.files.map((file) => ({
2272
2487
  path: file.tags?.path || file.key,
2273
- name: path8.basename(file.tags?.path || file.key),
2488
+ name: path6.basename(file.tags?.path || file.key),
2274
2489
  size: file.size || 0,
2275
2490
  mime: file.contentType,
2276
2491
  hash: file.tags?.hash || "",
@@ -2408,7 +2623,7 @@ class AssetsManager {
2408
2623
  };
2409
2624
  }
2410
2625
  async uploadAsset(client, localFile) {
2411
- const content = await fs8.readFile(localFile.absolutePath);
2626
+ const content = await fs6.readFile(localFile.absolutePath);
2412
2627
  await client.uploadFile({
2413
2628
  key: localFile.relativePath,
2414
2629
  content,
@@ -2501,10 +2716,10 @@ declare global {
2501
2716
  return enrichedAssets;
2502
2717
  }
2503
2718
  async scanDirectory(dir, files = []) {
2504
- const items = await fs8.readdir(dir);
2719
+ const items = await fs6.readdir(dir);
2505
2720
  for (const item of items) {
2506
- const fullPath = path8.join(dir, item);
2507
- const stats = await fs8.stat(fullPath);
2721
+ const fullPath = path6.join(dir, item);
2722
+ const stats = await fs6.stat(fullPath);
2508
2723
  if (stats.isDirectory()) {
2509
2724
  await this.scanDirectory(fullPath, files);
2510
2725
  } else {
@@ -2517,7 +2732,7 @@ declare global {
2517
2732
  return crypto.createHash("sha256").update(content).digest("hex");
2518
2733
  }
2519
2734
  getMimeType(filePath) {
2520
- const ext = path8.extname(filePath).toLowerCase();
2735
+ const ext = path6.extname(filePath).toLowerCase();
2521
2736
  const mimeTypes = {
2522
2737
  ".png": "image/png",
2523
2738
  ".jpg": "image/jpeg",
@@ -2551,12 +2766,12 @@ var init_manager2 = __esm(() => {
2551
2766
  });
2552
2767
 
2553
2768
  // src/utils/fs.ts
2554
- import { mkdir, writeFile as writeFile2 } from "fs/promises";
2769
+ import { mkdir, writeFile } from "fs/promises";
2555
2770
  import { parse } from "path";
2556
- var createFile = async (path9, content) => {
2557
- const file = parse(path9);
2771
+ var createFile = async (path7, content) => {
2772
+ const file = parse(path7);
2558
2773
  await mkdir(file.dir, { recursive: true });
2559
- await writeFile2(path9, content);
2774
+ await writeFile(path7, content);
2560
2775
  };
2561
2776
  var init_fs = () => {};
2562
2777
 
@@ -2574,19 +2789,19 @@ var init_assets = __esm(() => {
2574
2789
  });
2575
2790
 
2576
2791
  // src/integrations/cache.ts
2577
- import fs9 from "fs/promises";
2578
- import path9 from "path";
2579
- import os5 from "os";
2792
+ import fs7 from "fs/promises";
2793
+ import path7 from "path";
2794
+ import os4 from "os";
2580
2795
 
2581
2796
  class IntegrationCache {
2582
2797
  cacheDir;
2583
2798
  integrationsDir;
2584
2799
  constructor() {
2585
- this.cacheDir = path9.join(os5.homedir(), ".adk", "cache");
2586
- this.integrationsDir = path9.join(this.cacheDir, "integrations");
2800
+ this.cacheDir = path7.join(os4.homedir(), ".adk", "cache");
2801
+ this.integrationsDir = path7.join(this.cacheDir, "integrations");
2587
2802
  }
2588
2803
  async ensureCacheDir() {
2589
- await fs9.mkdir(this.integrationsDir, { recursive: true });
2804
+ await fs7.mkdir(this.integrationsDir, { recursive: true });
2590
2805
  }
2591
2806
  getCacheKey(integrationId, updatedAt) {
2592
2807
  const sanitizedId = integrationId.replace(/[^a-zA-Z0-9_-]/g, "_");
@@ -2596,8 +2811,8 @@ class IntegrationCache {
2596
2811
  async get(integrationId, updatedAt) {
2597
2812
  try {
2598
2813
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2599
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2600
- const data = await fs9.readFile(cachePath, "utf-8");
2814
+ const cachePath = path7.join(this.integrationsDir, cacheKey);
2815
+ const data = await fs7.readFile(cachePath, "utf-8");
2601
2816
  const cached = JSON.parse(data);
2602
2817
  if (cached.expiresAt) {
2603
2818
  const expiryDate = new Date(cached.expiresAt);
@@ -2614,7 +2829,7 @@ class IntegrationCache {
2614
2829
  async set(integrationId, updatedAt, definition, ttlHours = 24 * 7) {
2615
2830
  await this.ensureCacheDir();
2616
2831
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2617
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2832
+ const cachePath = path7.join(this.integrationsDir, cacheKey);
2618
2833
  const expiresAt = new Date;
2619
2834
  expiresAt.setHours(expiresAt.getHours() + ttlHours);
2620
2835
  const cacheEntry = {
@@ -2622,27 +2837,27 @@ class IntegrationCache {
2622
2837
  cachedAt: new Date().toISOString(),
2623
2838
  expiresAt: expiresAt.toISOString()
2624
2839
  };
2625
- await fs9.writeFile(cachePath, JSON.stringify(cacheEntry, null, 2));
2840
+ await fs7.writeFile(cachePath, JSON.stringify(cacheEntry, null, 2));
2626
2841
  }
2627
2842
  async remove(integrationId, updatedAt) {
2628
2843
  try {
2629
2844
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2630
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2631
- await fs9.unlink(cachePath);
2845
+ const cachePath = path7.join(this.integrationsDir, cacheKey);
2846
+ await fs7.unlink(cachePath);
2632
2847
  } catch {}
2633
2848
  }
2634
2849
  async clear() {
2635
2850
  try {
2636
- const files = await fs9.readdir(this.integrationsDir);
2637
- await Promise.all(files.map((file) => fs9.unlink(path9.join(this.integrationsDir, file))));
2851
+ const files = await fs7.readdir(this.integrationsDir);
2852
+ await Promise.all(files.map((file) => fs7.unlink(path7.join(this.integrationsDir, file))));
2638
2853
  } catch {}
2639
2854
  }
2640
2855
  async getStats() {
2641
2856
  try {
2642
- const files = await fs9.readdir(this.integrationsDir);
2857
+ const files = await fs7.readdir(this.integrationsDir);
2643
2858
  let totalSize = 0;
2644
2859
  for (const file of files) {
2645
- const stats = await fs9.stat(path9.join(this.integrationsDir, file));
2860
+ const stats = await fs7.stat(path7.join(this.integrationsDir, file));
2646
2861
  totalSize += stats.size;
2647
2862
  }
2648
2863
  return {
@@ -2667,7 +2882,7 @@ async function fetchServerIntegrationConfigs(project, targetBotId) {
2667
2882
  const { devId, botId } = project.agentInfo ?? {};
2668
2883
  const targetId = targetBotId || devId || botId;
2669
2884
  if (!targetId) {
2670
- return { configs: {}, enabledStates: {}, fetched: false, skipped: true };
2885
+ return { configs: {}, enabledStates: {}, authorizedStates: {}, fetched: false, skipped: true };
2671
2886
  }
2672
2887
  try {
2673
2888
  const client = await getProjectClient({
@@ -2690,6 +2905,7 @@ async function fetchServerIntegrationConfigs(project, targetBotId) {
2690
2905
  return {
2691
2906
  configs: {},
2692
2907
  enabledStates: {},
2908
+ authorizedStates: {},
2693
2909
  fetched: false,
2694
2910
  skipped: false,
2695
2911
  error: message
@@ -2700,13 +2916,15 @@ async function fetchBotConfigs(client, botId) {
2700
2916
  const { bot } = await client.getBot({ id: botId });
2701
2917
  const configs = {};
2702
2918
  const enabledStates = {};
2919
+ const authorizedStates = {};
2703
2920
  for (const [alias, integration] of Object.entries(bot.integrations || {})) {
2704
2921
  if (integration.configuration && Object.keys(integration.configuration).length > 0) {
2705
2922
  configs[alias] = integration.configuration;
2706
2923
  }
2707
2924
  enabledStates[alias] = integration.enabled;
2925
+ authorizedStates[alias] = !!integration.identifier;
2708
2926
  }
2709
- return { configs, enabledStates, fetched: true, skipped: false };
2927
+ return { configs, enabledStates, authorizedStates, fetched: true, skipped: false };
2710
2928
  }
2711
2929
  async function fetchServerPluginConfigs(project, targetBotId) {
2712
2930
  const { devId, botId } = project.agentInfo ?? {};
@@ -2753,121 +2971,9 @@ var init_integrations = __esm(() => {
2753
2971
  init_manager();
2754
2972
  init_dependencies_parser();
2755
2973
  init_cache2();
2756
- init_enhanced_cache();
2757
2974
  init_config_utils();
2758
2975
  });
2759
2976
 
2760
- // src/interfaces/enhanced-cache.ts
2761
- import fs10 from "fs/promises";
2762
- import path10 from "path";
2763
- import os6 from "os";
2764
-
2765
- class EnhancedInterfaceCache {
2766
- cacheDir;
2767
- resolutionsDir;
2768
- definitionsDir;
2769
- noCache;
2770
- constructor(noCache = false) {
2771
- this.noCache = noCache;
2772
- this.cacheDir = path10.join(os6.homedir(), ".adk", "cache", "interfaces");
2773
- this.resolutionsDir = path10.join(this.cacheDir, "resolutions");
2774
- this.definitionsDir = path10.join(this.cacheDir, "definitions");
2775
- }
2776
- async ensureCacheDirs() {
2777
- await fs10.mkdir(this.resolutionsDir, { recursive: true });
2778
- await fs10.mkdir(this.definitionsDir, { recursive: true });
2779
- }
2780
- async getResolution(name, version, workspace) {
2781
- if (this.noCache)
2782
- return null;
2783
- try {
2784
- const key = this.getResolutionKey(name, version, workspace);
2785
- const cachePath = path10.join(this.resolutionsDir, `${key}.json`);
2786
- const data = await fs10.readFile(cachePath, "utf-8");
2787
- const resolution = JSON.parse(data);
2788
- const cachedAt = new Date(resolution.cachedAt);
2789
- const ageMinutes = (Date.now() - cachedAt.getTime()) / (1000 * 60);
2790
- if (ageMinutes > 5)
2791
- return null;
2792
- return resolution;
2793
- } catch {
2794
- return null;
2795
- }
2796
- }
2797
- async setResolution(name, version, workspace, interfaceId, updatedAt) {
2798
- await this.ensureCacheDirs();
2799
- const key = this.getResolutionKey(name, version, workspace);
2800
- const cachePath = path10.join(this.resolutionsDir, `${key}.json`);
2801
- const resolution = {
2802
- interfaceId,
2803
- updatedAt,
2804
- cachedAt: new Date().toISOString()
2805
- };
2806
- await fs10.writeFile(cachePath, JSON.stringify(resolution));
2807
- }
2808
- async getDefinition(interfaceId, updatedAt) {
2809
- if (this.noCache)
2810
- return null;
2811
- try {
2812
- const key = this.getDefinitionKey(interfaceId, updatedAt);
2813
- const cachePath = path10.join(this.definitionsDir, `${key}.json`);
2814
- const data = await fs10.readFile(cachePath, "utf-8");
2815
- const cached = JSON.parse(data);
2816
- return cached.definition;
2817
- } catch {
2818
- return null;
2819
- }
2820
- }
2821
- async setDefinition(interfaceId, updatedAt, definition) {
2822
- await this.ensureCacheDirs();
2823
- const key = this.getDefinitionKey(interfaceId, updatedAt);
2824
- const cachePath = path10.join(this.definitionsDir, `${key}.json`);
2825
- const cached = {
2826
- definition,
2827
- cachedAt: new Date().toISOString()
2828
- };
2829
- await fs10.writeFile(cachePath, JSON.stringify(cached));
2830
- }
2831
- async clear() {
2832
- try {
2833
- const resolutionFiles = await fs10.readdir(this.resolutionsDir);
2834
- await Promise.all(resolutionFiles.map((f) => fs10.unlink(path10.join(this.resolutionsDir, f))));
2835
- const definitionFiles = await fs10.readdir(this.definitionsDir);
2836
- await Promise.all(definitionFiles.map((f) => fs10.unlink(path10.join(this.definitionsDir, f))));
2837
- } catch {}
2838
- }
2839
- async getStats() {
2840
- const getDirectoryStats = async (dir) => {
2841
- try {
2842
- const files = await fs10.readdir(dir);
2843
- let totalSize = 0;
2844
- for (const file of files) {
2845
- const stats = await fs10.stat(path10.join(dir, file));
2846
- totalSize += stats.size;
2847
- }
2848
- return { count: files.length, sizeBytes: totalSize };
2849
- } catch {
2850
- return { count: 0, sizeBytes: 0 };
2851
- }
2852
- };
2853
- const [resolutions, definitions] = await Promise.all([
2854
- getDirectoryStats(this.resolutionsDir),
2855
- getDirectoryStats(this.definitionsDir)
2856
- ]);
2857
- return { resolutions, definitions };
2858
- }
2859
- getResolutionKey(name, version, workspace) {
2860
- const prefix = workspace ? `${workspace}_` : "";
2861
- const key = `${prefix}${name}_${version}`;
2862
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
2863
- }
2864
- getDefinitionKey(interfaceId, updatedAt) {
2865
- const key = `${interfaceId}_${updatedAt}`;
2866
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
2867
- }
2868
- }
2869
- var init_enhanced_cache2 = () => {};
2870
-
2871
2977
  // src/interfaces/parser.ts
2872
2978
  class InterfaceParser {
2873
2979
  static parseInterfaceRef(versionString) {
@@ -2887,95 +2993,44 @@ class InterfaceParser {
2887
2993
  fullName: workspace ? `${workspace}/${name}` : name
2888
2994
  };
2889
2995
  }
2890
- static parseInterfaces(_dependencies) {
2891
- const interfaces = [];
2892
- const errors = [];
2893
- for (const [alias, versionString] of Object.entries(BUILTIN_INTERFACES)) {
2894
- try {
2895
- const ref = this.parseInterfaceRef(versionString);
2896
- if (!this.isValidVersion(ref.version)) {
2897
- errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version));
2898
- }
2899
- interfaces.push({ alias, ref, config: undefined });
2900
- } catch (error) {
2901
- errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid interface '${alias}': ${error instanceof Error ? error.message : String(error)}`));
2902
- }
2903
- }
2904
- return { interfaces, errors };
2905
- }
2906
- static isValidVersion(version) {
2907
- if (version === "latest")
2908
- return true;
2909
- const semverPattern = /^(\d+)\.(\d+)\.(\d+)(-[\w.]+)?(\+[\w.]+)?$/;
2910
- return semverPattern.test(version);
2911
- }
2912
- }
2913
- var init_parser = __esm(() => {
2914
- init_src();
2915
- init_validation_errors();
2916
- init_constants();
2917
- });
2918
-
2919
- // src/interfaces/manager.ts
2920
- class InterfaceManager {
2921
- cache;
2922
- options;
2923
- client;
2924
- constructor(options = {}) {
2925
- this.options = options;
2926
- this.cache = new EnhancedInterfaceCache(options.noCache || false);
2927
- }
2928
- async getClient() {
2929
- if (!this.client) {
2930
- this.client = await getProjectClient({
2931
- project: this.options.project,
2932
- credentials: this.options.credentials,
2933
- apiUrl: this.options.apiUrl,
2934
- workspaceId: this.options.workspaceId,
2935
- headers: {
2936
- "x-multiple-integrations": "true"
2937
- }
2938
- });
2939
- }
2940
- return this.client;
2941
- }
2942
- async loadInterfaces(dependencies) {
2943
- const errors = [];
2944
- const warnings = [];
2945
- const parseResult = InterfaceParser.parseInterfaces(dependencies);
2946
- const interfaces = parseResult.interfaces;
2947
- errors.push(...parseResult.errors);
2948
- const fetchPromises = interfaces.map(async (intf) => {
2949
- try {
2950
- const definition = await this.fetchInterface(intf.ref);
2951
- intf.definition = definition;
2952
- const validation = this.validateInterface(intf);
2953
- intf.validationResult = validation;
2954
- if (!validation.valid) {
2955
- validation.errors.forEach((msg) => {
2956
- errors.push(ValidationErrors.warning(msg, "agent.config.ts"));
2957
- });
2958
- }
2959
- } catch (error) {
2960
- if (error instanceof Error && error.message.includes("version")) {
2961
- errors.push(ValidationErrors.unknownInterface(error.message));
2962
- } else {
2963
- errors.push(ValidationErrors.invalidDependenciesSyntax(`Unknown interface '${intf.alias}' (${intf.ref.fullName})`));
2964
- }
2965
- }
2966
- });
2967
- await Promise.all(fetchPromises);
2968
- return { interfaces, errors, warnings };
2969
- }
2970
- async fetchInterface(ref) {
2971
- const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace);
2972
- if (cachedResolution) {
2973
- const cachedDefinition = await this.cache.getDefinition(cachedResolution.interfaceId, cachedResolution.updatedAt);
2974
- if (cachedDefinition) {
2975
- return cachedDefinition;
2996
+ static parseInterfaces(_dependencies) {
2997
+ const interfaces = [];
2998
+ const errors = [];
2999
+ for (const [alias, versionString] of Object.entries(BUILTIN_INTERFACES)) {
3000
+ try {
3001
+ const ref = this.parseInterfaceRef(versionString);
3002
+ if (!this.isValidVersion(ref.version)) {
3003
+ errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version));
3004
+ }
3005
+ interfaces.push({ alias, ref, config: undefined });
3006
+ } catch (error) {
3007
+ errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid interface '${alias}': ${error instanceof Error ? error.message : String(error)}`));
2976
3008
  }
2977
3009
  }
2978
- const client = await this.getClient();
3010
+ return { interfaces, errors };
3011
+ }
3012
+ static isValidVersion(version) {
3013
+ if (version === "latest")
3014
+ return true;
3015
+ const semverPattern = /^(\d+)\.(\d+)\.(\d+)(-[\w.]+)?(\+[\w.]+)?$/;
3016
+ return semverPattern.test(version);
3017
+ }
3018
+ }
3019
+ var init_parser = __esm(() => {
3020
+ init_src();
3021
+ init_validation_errors();
3022
+ init_constants();
3023
+ });
3024
+
3025
+ // src/dependencies/catalog/interface-source.ts
3026
+ class InterfaceCatalogSource {
3027
+ clientFactory;
3028
+ cacheConfig = { cacheType: "interfaces", idField: "interfaceId" };
3029
+ constructor(clientFactory) {
3030
+ this.clientFactory = clientFactory;
3031
+ }
3032
+ async fetchByRef(ref) {
3033
+ const client = await this.clientFactory.getClient();
2979
3034
  let interfaceResponse;
2980
3035
  let versionError = null;
2981
3036
  try {
@@ -3019,32 +3074,56 @@ class InterfaceManager {
3019
3074
  }
3020
3075
  const location = ref.workspace ? `workspace "${ref.workspace}"` : "Botpress";
3021
3076
  throw new AdkError({
3022
- code: "INTERFACE_VERSION_NOT_FOUND",
3077
+ code: "VERSION_NOT_FOUND",
3023
3078
  message: `Interface "${ref.name}" version "${ref.version}" not found in ${location}. Latest available version is "${latestVersion}"`,
3024
3079
  expected: true
3025
3080
  });
3026
3081
  }
3027
3082
  const intf = interfaceResponse.interface;
3028
- await this.cache.setResolution(ref.name, ref.version, ref.workspace, intf.id, intf.updatedAt);
3029
- await this.cache.setDefinition(intf.id, intf.updatedAt, intf);
3030
- return intf;
3083
+ return { id: intf.id, updatedAt: intf.updatedAt, definition: intf };
3031
3084
  }
3032
- async getByDependencyString(dep) {
3033
- const match = dep.match(/^(?:([^/]+)\/)?([^@]+)@(.+)$/);
3034
- if (!match) {
3035
- throw new AdkError({
3036
- code: "INVALID_VERSION_FORMAT",
3037
- message: `Invalid interface dependency string: ${dep}. Expected 'name@version' or 'workspace/name@version'`,
3038
- expected: true
3039
- });
3040
- }
3041
- const [, workspace, name, version] = match;
3042
- return this.fetchInterface({
3043
- workspace: workspace || undefined,
3044
- name,
3045
- version,
3046
- fullName: workspace ? `${workspace}/${name}` : name
3085
+ }
3086
+ var init_interface_source = __esm(() => {
3087
+ init_src();
3088
+ });
3089
+
3090
+ // src/interfaces/manager.ts
3091
+ class InterfaceManager {
3092
+ service;
3093
+ constructor(options = {}) {
3094
+ const { noCache, ...clientOptions } = options;
3095
+ this.service = new CatalogService(new InterfaceCatalogSource(new CatalogClientFactory(clientOptions)), noCache || false);
3096
+ }
3097
+ async loadInterfaces(dependencies) {
3098
+ const errors = [];
3099
+ const warnings = [];
3100
+ const parseResult = InterfaceParser.parseInterfaces(dependencies);
3101
+ const interfaces = parseResult.interfaces;
3102
+ errors.push(...parseResult.errors);
3103
+ const fetchPromises = interfaces.map(async (intf) => {
3104
+ try {
3105
+ const definition = await this.fetchInterface(intf.ref);
3106
+ intf.definition = definition;
3107
+ const validation = this.validateInterface(intf);
3108
+ intf.validationResult = validation;
3109
+ if (!validation.valid) {
3110
+ validation.errors.forEach((msg) => {
3111
+ errors.push(ValidationErrors.warning(msg, "agent.config.ts"));
3112
+ });
3113
+ }
3114
+ } catch (error) {
3115
+ if (error instanceof Error && error.message.includes("version")) {
3116
+ errors.push(ValidationErrors.unknownInterface(error.message));
3117
+ } else {
3118
+ errors.push(ValidationErrors.invalidDependenciesSyntax(`Unknown interface '${intf.alias}' (${intf.ref.fullName})`));
3119
+ }
3120
+ }
3047
3121
  });
3122
+ await Promise.all(fetchPromises);
3123
+ return { interfaces, errors, warnings };
3124
+ }
3125
+ async fetchInterface(ref) {
3126
+ return this.service.getDefinition(ref);
3048
3127
  }
3049
3128
  validateInterface(intf) {
3050
3129
  const errors = [];
@@ -3056,28 +3135,56 @@ class InterfaceManager {
3056
3135
  return { valid: errors.length === 0, errors, warnings };
3057
3136
  }
3058
3137
  async getCacheStats() {
3059
- const stats = await this.cache.getStats();
3060
- return {
3061
- count: stats.resolutions.count + stats.definitions.count,
3062
- sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
3063
- };
3138
+ return this.service.getCacheStats();
3064
3139
  }
3065
3140
  async clearCache() {
3066
- await this.cache.clear();
3141
+ await this.service.clearCache();
3067
3142
  }
3068
3143
  }
3069
3144
  var init_manager3 = __esm(() => {
3070
- init_src();
3071
- init_auth();
3072
- init_enhanced_cache2();
3073
3145
  init_parser();
3074
3146
  init_validation_errors();
3147
+ init_client_factory();
3148
+ init_catalog_service();
3149
+ init_interface_source();
3150
+ });
3151
+
3152
+ // src/interfaces/enhanced-cache.ts
3153
+ class EnhancedInterfaceCache {
3154
+ cache;
3155
+ constructor(noCache = false) {
3156
+ this.cache = new ResolutionCache({ cacheType: "interfaces", idField: "interfaceId" }, noCache);
3157
+ }
3158
+ async getResolution(name, version, workspace) {
3159
+ const resolution = await this.cache.getResolution(name, version, workspace);
3160
+ if (!resolution)
3161
+ return null;
3162
+ return { interfaceId: resolution.id, updatedAt: resolution.updatedAt, cachedAt: resolution.cachedAt };
3163
+ }
3164
+ async setResolution(name, version, workspace, interfaceId, updatedAt) {
3165
+ await this.cache.setResolution(name, version, workspace, interfaceId, updatedAt);
3166
+ }
3167
+ async getDefinition(interfaceId, updatedAt) {
3168
+ return this.cache.getDefinition(interfaceId, updatedAt);
3169
+ }
3170
+ async setDefinition(interfaceId, updatedAt, definition) {
3171
+ await this.cache.setDefinition(interfaceId, updatedAt, definition);
3172
+ }
3173
+ async clear() {
3174
+ await this.cache.clear();
3175
+ }
3176
+ async getStats() {
3177
+ return this.cache.getStats();
3178
+ }
3179
+ }
3180
+ var init_enhanced_cache = __esm(() => {
3181
+ init_resolution_cache();
3075
3182
  });
3076
3183
  // src/interfaces/index.ts
3077
3184
  var init_interfaces = __esm(() => {
3078
3185
  init_manager3();
3079
3186
  init_parser();
3080
- init_enhanced_cache2();
3187
+ init_enhanced_cache();
3081
3188
  });
3082
3189
 
3083
3190
  // src/utils/json-ordering.ts
@@ -3239,7 +3346,7 @@ var init_component_files = __esm(() => {
3239
3346
  // src/agent-project/component-source-resolver.ts
3240
3347
  import { Project, SyntaxKind } from "ts-morph";
3241
3348
  import { readFileSync } from "fs";
3242
- import * as path11 from "path";
3349
+ import * as path8 from "path";
3243
3350
  function resolveComponentSources(absolutePath) {
3244
3351
  const project = new Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true });
3245
3352
  const sourceFile = project.createSourceFile(absolutePath, readFileSync(absolutePath, "utf-8"), { overwrite: true });
@@ -3252,12 +3359,12 @@ function resolveComponentSources(absolutePath) {
3252
3359
  }
3253
3360
  function collectBpTsxImports(sourceFile, absolutePath) {
3254
3361
  const imports = new Map;
3255
- const dir = path11.dirname(absolutePath);
3362
+ const dir = path8.dirname(absolutePath);
3256
3363
  for (const decl of sourceFile.getImportDeclarations()) {
3257
3364
  const specifier = decl.getModuleSpecifierValue();
3258
3365
  if (!specifier.endsWith(BP_TSX_SUFFIX))
3259
3366
  continue;
3260
- const resolved = path11.resolve(dir, specifier);
3367
+ const resolved = path8.resolve(dir, specifier);
3261
3368
  const defaultImport = decl.getDefaultImport();
3262
3369
  if (defaultImport) {
3263
3370
  imports.set(defaultImport.getText(), resolved);
@@ -3310,69 +3417,370 @@ function resolveExports(sourceFile, localToSource, importBindings) {
3310
3417
  exportMap.set("default", fromLocal);
3311
3418
  }
3312
3419
  }
3313
- for (const decl of sourceFile.getExportDeclarations()) {
3314
- if (decl.getModuleSpecifier())
3315
- continue;
3316
- for (const named of decl.getNamedExports()) {
3317
- const localName = named.getNameNode().getText();
3318
- const aliasNode = named.getAliasNode();
3319
- const exportName = aliasNode ? aliasNode.getText() : localName;
3320
- const source = localToSource.get(localName);
3321
- if (source)
3322
- exportMap.set(exportName, source);
3420
+ for (const decl of sourceFile.getExportDeclarations()) {
3421
+ if (decl.getModuleSpecifier())
3422
+ continue;
3423
+ for (const named of decl.getNamedExports()) {
3424
+ const localName = named.getNameNode().getText();
3425
+ const aliasNode = named.getAliasNode();
3426
+ const exportName = aliasNode ? aliasNode.getText() : localName;
3427
+ const source = localToSource.get(localName);
3428
+ if (source)
3429
+ exportMap.set(exportName, source);
3430
+ }
3431
+ }
3432
+ return exportMap;
3433
+ }
3434
+ function sourceFromCustomComponentExpr(expr, importBindings) {
3435
+ if (expr.getKind() !== SyntaxKind.NewExpression)
3436
+ return;
3437
+ const newExpr = expr.asKindOrThrow(SyntaxKind.NewExpression);
3438
+ if (newExpr.getExpression().getText() !== CUSTOM_COMPONENT_CLASS)
3439
+ return;
3440
+ const args = newExpr.getArguments();
3441
+ const firstArg = args[0];
3442
+ if (!firstArg || firstArg.getKind() !== SyntaxKind.Identifier)
3443
+ return;
3444
+ return importBindings.get(firstArg.getText());
3445
+ }
3446
+ var CUSTOM_COMPONENT_CLASS = "CustomComponent";
3447
+ var init_component_source_resolver = __esm(() => {
3448
+ init_component_files();
3449
+ });
3450
+
3451
+ // src/bot-generator/table-validation.ts
3452
+ function getColumnCount(table) {
3453
+ const properties = table.definition.schema?.properties;
3454
+ return properties ? Object.keys(properties).length : 0;
3455
+ }
3456
+ function findTableColumnViolations(tables, max = MAX_TABLE_COLUMNS) {
3457
+ return tables.map((table) => ({
3458
+ name: table.definition.name,
3459
+ path: table.path,
3460
+ columnCount: getColumnCount(table)
3461
+ })).filter((t) => t.columnCount > max);
3462
+ }
3463
+ var init_table_validation = __esm(() => {
3464
+ init_constants();
3465
+ });
3466
+
3467
+ // src/dependencies/alias-utils.ts
3468
+ function isBotpressInternalId(alias) {
3469
+ return BP_INTERNAL_ID_PREFIXES.some((prefix) => alias.startsWith(prefix));
3470
+ }
3471
+ function isFriendlyAlias(alias) {
3472
+ return FRIENDLY_ALIAS_RE.test(alias) && !isBotpressInternalId(alias);
3473
+ }
3474
+ function generateFriendlyAlias(cloudName, cloudAlias, used) {
3475
+ if (isFriendlyAlias(cloudAlias) && !used.has(cloudAlias))
3476
+ return cloudAlias;
3477
+ const base = cloudName?.split("/").at(-1) ?? cloudAlias;
3478
+ const sanitized = base.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
3479
+ let candidate = sanitized;
3480
+ let n = 2;
3481
+ while (used.has(candidate)) {
3482
+ candidate = `${sanitized}-${n}`;
3483
+ n++;
3484
+ }
3485
+ return candidate;
3486
+ }
3487
+ var FRIENDLY_ALIAS_RE, BP_INTERNAL_ID_PREFIXES;
3488
+ var init_alias_utils = __esm(() => {
3489
+ FRIENDLY_ALIAS_RE = /^[a-z0-9_-]{2,100}$/;
3490
+ BP_INTERNAL_ID_PREFIXES = ["intver_", "plgver_", "int_", "plg_"];
3491
+ });
3492
+
3493
+ // src/dependencies/snapshot-store.ts
3494
+ import * as fs8 from "fs/promises";
3495
+ import * as path9 from "path";
3496
+
3497
+ class DependencySnapshotStore {
3498
+ projectPath;
3499
+ dirPath;
3500
+ constructor(opts) {
3501
+ this.projectPath = opts.projectPath;
3502
+ this.dirPath = path9.join(opts.projectPath, ".adk", "dependencies");
3503
+ }
3504
+ getSnapshotPath(env) {
3505
+ return path9.join(this.dirPath, `${env}.json`);
3506
+ }
3507
+ getMigrationMarkerPath() {
3508
+ return path9.join(this.dirPath, "migration.json");
3509
+ }
3510
+ async exists(env) {
3511
+ try {
3512
+ await fs8.access(this.getSnapshotPath(env));
3513
+ return true;
3514
+ } catch {
3515
+ return false;
3516
+ }
3517
+ }
3518
+ async read(env, options) {
3519
+ const filePath = this.getSnapshotPath(env);
3520
+ let raw;
3521
+ try {
3522
+ raw = await fs8.readFile(filePath, "utf8");
3523
+ } catch (err) {
3524
+ if (err.code === "ENOENT")
3525
+ return null;
3526
+ throw err;
3527
+ }
3528
+ try {
3529
+ return dependencySnapshotSchema.parse(JSON.parse(raw));
3530
+ } catch (err) {
3531
+ if (options?.tolerant)
3532
+ return null;
3533
+ throw new DependencyError({
3534
+ code: "INVALID_CONFIG",
3535
+ message: `Dependency snapshot at ${filePath} failed schema validation`,
3536
+ details: { issues: err.issues ?? String(err) }
3537
+ });
3538
+ }
3539
+ }
3540
+ async readOrEmpty(env, options) {
3541
+ const snapshot = await this.read(env, options);
3542
+ return snapshot ?? emptyDependencySnapshot(env, options?.botId, options?.fetchedAt);
3543
+ }
3544
+ async write(snapshot) {
3545
+ const validated = dependencySnapshotSchema.parse(snapshot);
3546
+ await fs8.mkdir(this.dirPath, { recursive: true });
3547
+ const filePath = this.getSnapshotPath(validated.env);
3548
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
3549
+ await fs8.writeFile(tmp, JSON.stringify(sortKeysDeep(validated), null, 2) + `
3550
+ `, "utf8");
3551
+ await fs8.rename(tmp, filePath);
3552
+ }
3553
+ async delete(env) {
3554
+ try {
3555
+ await fs8.unlink(this.getSnapshotPath(env));
3556
+ } catch (err) {
3557
+ if (err.code !== "ENOENT")
3558
+ throw err;
3559
+ }
3560
+ }
3561
+ async hasMigrationMarker() {
3562
+ try {
3563
+ await fs8.access(this.getMigrationMarkerPath());
3564
+ return true;
3565
+ } catch {
3566
+ return false;
3567
+ }
3568
+ }
3569
+ async writeMigrationMarker(marker) {
3570
+ const validated = dependencyMigrationMarkerSchema.parse(marker);
3571
+ await fs8.mkdir(this.dirPath, { recursive: true });
3572
+ const filePath = this.getMigrationMarkerPath();
3573
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
3574
+ await fs8.writeFile(tmp, JSON.stringify(sortKeysDeep(validated), null, 2) + `
3575
+ `, "utf8");
3576
+ await fs8.rename(tmp, filePath);
3577
+ }
3578
+ async refreshFromCloud(opts) {
3579
+ const previous = await this.readForRefresh(opts.env, opts.onWarning);
3580
+ const { bot } = await opts.client.getBot({ id: opts.botId });
3581
+ const snapshot = dependencySnapshotFromBot({
3582
+ bot,
3583
+ botId: opts.botId,
3584
+ env: opts.env,
3585
+ fetchedAt: opts.fetchedAt ?? new Date,
3586
+ previous
3587
+ });
3588
+ await annotateAuthorizationPending({
3589
+ snapshot,
3590
+ bot,
3591
+ integrationRegistry: opts.integrationRegistry
3592
+ });
3593
+ if (previous && cloudSnapshotUnchanged(previous, snapshot)) {
3594
+ return previous;
3595
+ }
3596
+ await this.write(snapshot);
3597
+ return snapshot;
3598
+ }
3599
+ async readForRefresh(env, onWarning) {
3600
+ try {
3601
+ return await this.read(env);
3602
+ } catch (err) {
3603
+ if (!(err instanceof DependencyError) || err.code !== "INVALID_CONFIG")
3604
+ throw err;
3605
+ const filePath = this.getSnapshotPath(env);
3606
+ await this.delete(env);
3607
+ onWarning?.({
3608
+ code: "SNAPSHOT_CORRUPT",
3609
+ message: `Removed corrupt dependency snapshot at ${filePath}; refreshing from Cloud.`,
3610
+ env,
3611
+ path: filePath
3612
+ });
3613
+ return null;
3614
+ }
3615
+ }
3616
+ }
3617
+ function emptyDependencySnapshot(env, botId = "local", fetchedAt = new Date(0)) {
3618
+ return {
3619
+ version: 1,
3620
+ env,
3621
+ botId,
3622
+ fetchedAt: fetchedAt.toISOString(),
3623
+ integrations: {},
3624
+ plugins: {}
3625
+ };
3626
+ }
3627
+ function cloudSnapshotUnchanged(previous, next) {
3628
+ if (previous.botId !== next.botId || previous.env !== next.env)
3629
+ return false;
3630
+ if (previous.botUpdatedAt !== next.botUpdatedAt)
3631
+ return false;
3632
+ return jsonEqual({ integrations: previous.integrations, plugins: previous.plugins }, { integrations: next.integrations, plugins: next.plugins });
3633
+ }
3634
+ async function annotateAuthorizationPending(opts) {
3635
+ const registry = opts.integrationRegistry;
3636
+ if (!registry)
3637
+ return;
3638
+ const cloudIntegrations = opts.bot.integrations ?? {};
3639
+ const specCache = new Map;
3640
+ const getSpec = (name, version) => {
3641
+ const key = `${name}@${version}`;
3642
+ const cached = specCache.get(key);
3643
+ if (cached)
3644
+ return cached;
3645
+ const promise = registry.getSpec(name, version).catch(() => null);
3646
+ specCache.set(key, promise);
3647
+ return promise;
3648
+ };
3649
+ await Promise.all(Object.entries(opts.snapshot.integrations).map(async ([alias, entry]) => {
3650
+ const cloudAlias = entry.cloudAlias ?? alias;
3651
+ const cloud = cloudIntegrations[cloudAlias];
3652
+ if (!cloud)
3653
+ return;
3654
+ if (cloud.identifier) {
3655
+ delete entry.authorizationPending;
3656
+ return;
3657
+ }
3658
+ const spec = await getSpec(entry.name, entry.version);
3659
+ if (!spec)
3660
+ return;
3661
+ const requiresAuthorization = integrationRequiresAuthorization(spec, entry.configurationType);
3662
+ if (requiresAuthorization) {
3663
+ entry.authorizationPending = true;
3664
+ } else {
3665
+ delete entry.authorizationPending;
3666
+ }
3667
+ }));
3668
+ }
3669
+ function dependencySnapshotFromBot(opts) {
3670
+ const integrations = {};
3671
+ const usedIntegrationAliases = new Set;
3672
+ for (const [cloudAlias, cloud] of Object.entries(opts.bot.integrations ?? {})) {
3673
+ const cloudName = typeof cloud.name === "string" ? cloud.name : undefined;
3674
+ const config = cloud.configuration ?? {};
3675
+ const version = cloud.version ?? "0.0.0";
3676
+ const configurationType = typeof cloud.configurationType === "string" && cloud.configurationType && cloud.configurationType !== "default" ? cloud.configurationType : undefined;
3677
+ const alias = chooseCloudAlias({
3678
+ cloudAlias,
3679
+ cloudName,
3680
+ previous: opts.previous?.integrations ?? {},
3681
+ used: usedIntegrationAliases,
3682
+ matches: (entry) => entry.version === version && entry.configurationType === configurationType && jsonEqual(entry.config, config)
3683
+ });
3684
+ usedIntegrationAliases.add(alias);
3685
+ const previousEntry = opts.previous?.integrations[alias];
3686
+ const previousMissingFields = previousEntry?.missingFields?.length && !cloud.enabled && previousEntry.version === version && previousEntry.configurationType === configurationType && jsonEqual(previousEntry.config, config) ? previousEntry.missingFields : undefined;
3687
+ integrations[alias] = {
3688
+ name: cloud.name ?? "",
3689
+ version,
3690
+ enabled: Boolean(cloud.enabled),
3691
+ config,
3692
+ ...configurationType ? { configurationType } : {},
3693
+ ...previousMissingFields ? { missingFields: previousMissingFields } : {},
3694
+ ...!cloud.identifier && previousEntry?.authorizationPending ? { authorizationPending: true } : {},
3695
+ ...typeof cloud.id === "string" ? { cloudId: cloud.id } : {},
3696
+ cloudAlias,
3697
+ ...typeof cloud.updatedAt === "string" ? { updatedAt: cloud.updatedAt } : {}
3698
+ };
3699
+ }
3700
+ const plugins = {};
3701
+ const usedPluginAliases = new Set;
3702
+ for (const [cloudAlias, cloud] of Object.entries(opts.bot.plugins ?? {})) {
3703
+ const cloudName = typeof cloud.name === "string" ? cloud.name : undefined;
3704
+ const config = cloud.configuration ?? {};
3705
+ const version = cloud.version ?? "0.0.0";
3706
+ const dependencies = {};
3707
+ for (const [ifaceAlias, dep] of Object.entries(cloud.interfaces ?? {})) {
3708
+ if (typeof dep.integrationAlias === "string") {
3709
+ dependencies[ifaceAlias] = { integrationAlias: dep.integrationAlias };
3710
+ }
3323
3711
  }
3712
+ const alias = chooseCloudAlias({
3713
+ cloudAlias,
3714
+ cloudName,
3715
+ previous: opts.previous?.plugins ?? {},
3716
+ used: usedPluginAliases,
3717
+ matches: (entry) => entry.version === version && jsonEqual(entry.config, config)
3718
+ });
3719
+ usedPluginAliases.add(alias);
3720
+ const previousEntry = opts.previous?.plugins[alias];
3721
+ const previousMissingFields = previousEntry?.missingFields?.length && !(cloud.enabled ?? true) && previousEntry.version === version && jsonEqual(previousEntry.config, config) ? previousEntry.missingFields : undefined;
3722
+ plugins[alias] = {
3723
+ name: cloud.name ?? "",
3724
+ version,
3725
+ enabled: cloud.enabled ?? true,
3726
+ config,
3727
+ dependencies,
3728
+ ...previousMissingFields ? { missingFields: previousMissingFields } : {},
3729
+ ...typeof cloud.id === "string" ? { cloudId: cloud.id } : {},
3730
+ cloudAlias,
3731
+ ...typeof cloud.updatedAt === "string" ? { updatedAt: cloud.updatedAt } : {}
3732
+ };
3324
3733
  }
3325
- return exportMap;
3326
- }
3327
- function sourceFromCustomComponentExpr(expr, importBindings) {
3328
- if (expr.getKind() !== SyntaxKind.NewExpression)
3329
- return;
3330
- const newExpr = expr.asKindOrThrow(SyntaxKind.NewExpression);
3331
- if (newExpr.getExpression().getText() !== CUSTOM_COMPONENT_CLASS)
3332
- return;
3333
- const args = newExpr.getArguments();
3334
- const firstArg = args[0];
3335
- if (!firstArg || firstArg.getKind() !== SyntaxKind.Identifier)
3336
- return;
3337
- return importBindings.get(firstArg.getText());
3338
- }
3339
- var CUSTOM_COMPONENT_CLASS = "CustomComponent";
3340
- var init_component_source_resolver = __esm(() => {
3341
- init_component_files();
3342
- });
3343
-
3344
- // src/bot-generator/table-validation.ts
3345
- function getColumnCount(table) {
3346
- const properties = table.definition.schema?.properties;
3347
- return properties ? Object.keys(properties).length : 0;
3734
+ return {
3735
+ version: 1,
3736
+ env: opts.env,
3737
+ botId: opts.botId,
3738
+ fetchedAt: opts.fetchedAt.toISOString(),
3739
+ ...typeof opts.bot.updatedAt === "string" ? { botUpdatedAt: opts.bot.updatedAt } : {},
3740
+ integrations,
3741
+ plugins
3742
+ };
3348
3743
  }
3349
- function findTableColumnViolations(tables, max = MAX_TABLE_COLUMNS) {
3350
- return tables.map((table) => ({
3351
- name: table.definition.name,
3352
- path: table.path,
3353
- columnCount: getColumnCount(table)
3354
- })).filter((t) => t.columnCount > max);
3744
+ function chooseCloudAlias(opts) {
3745
+ if (isFriendlyAlias(opts.cloudAlias) && opts.previous[opts.cloudAlias] && !opts.used.has(opts.cloudAlias)) {
3746
+ return opts.cloudAlias;
3747
+ }
3748
+ if (opts.cloudName) {
3749
+ if (opts.matches) {
3750
+ const exactMatch = Object.entries(opts.previous).find(([alias, entry]) => !opts.used.has(alias) && entry.name === opts.cloudName && opts.matches(entry));
3751
+ if (exactMatch)
3752
+ return exactMatch[0];
3753
+ }
3754
+ const match = Object.entries(opts.previous).find(([alias, entry]) => !opts.used.has(alias) && entry.name === opts.cloudName);
3755
+ if (match)
3756
+ return match[0];
3757
+ }
3758
+ return generateFriendlyAlias(opts.cloudName, opts.cloudAlias, opts.used);
3355
3759
  }
3356
- var init_table_validation = __esm(() => {
3357
- init_constants();
3760
+ var init_snapshot_store = __esm(() => {
3761
+ init_alias_utils();
3762
+ init_errors2();
3763
+ init_types();
3358
3764
  });
3359
3765
 
3360
- // src/agent-project/lock-to-dependencies.ts
3361
- function lockToDependencies(lock) {
3766
+ // src/agent-project/dependency-state-to-dependencies.ts
3767
+ function dependencyStateToDependencies(state) {
3362
3768
  const integrations = {};
3363
- for (const [alias, entry] of Object.entries(lock.integrations)) {
3769
+ for (const [alias, entry] of Object.entries(state.integrations)) {
3364
3770
  integrations[alias] = {
3365
3771
  version: `${entry.name}@${entry.version}`,
3366
3772
  enabled: entry.enabled,
3367
- config: entry.config
3773
+ config: entry.config,
3774
+ ...entry.configurationType ? { configurationType: entry.configurationType } : {}
3368
3775
  };
3369
3776
  }
3370
3777
  const plugins = {};
3371
- for (const [alias, entry] of Object.entries(lock.plugins)) {
3778
+ for (const [alias, entry] of Object.entries(state.plugins)) {
3372
3779
  plugins[alias] = {
3373
3780
  version: `${entry.name}@${entry.version}`,
3374
3781
  config: entry.config,
3375
- dependencies: entry.dependencies
3782
+ dependencies: entry.dependencies,
3783
+ ...entry.missingFields !== undefined ? { missingFields: entry.missingFields } : {}
3376
3784
  };
3377
3785
  }
3378
3786
  return { integrations, plugins };
@@ -3383,8 +3791,8 @@ import { BuiltInActions, BuiltInWorkflows, Errors as Errors2, Primitives as Prim
3383
3791
  import { Autonomous } from "@botpress/runtime";
3384
3792
  import createDebug from "debug";
3385
3793
  import { createRequire as createRequire2 } from "module";
3386
- import fs11 from "fs/promises";
3387
- import path12 from "path";
3794
+ import fs9 from "fs/promises";
3795
+ import path10 from "path";
3388
3796
  function getToolDefinition(value) {
3389
3797
  if (typeof value !== "object" || value === null) {
3390
3798
  return;
@@ -3415,7 +3823,7 @@ var init_agent_project = __esm(() => {
3415
3823
  init_validation_errors();
3416
3824
  init_table_validation();
3417
3825
  init_constants();
3418
- init_lock_file();
3826
+ init_snapshot_store();
3419
3827
  debug = createDebug("adk:agent-project");
3420
3828
  AgentProject = class AgentProject {
3421
3829
  static _projectCache = new Map;
@@ -3443,7 +3851,7 @@ var init_agent_project = __esm(() => {
3443
3851
  _tools = [];
3444
3852
  constructor(projectPath, options = {}) {
3445
3853
  this._options = options;
3446
- this._path = path12.resolve(projectPath);
3854
+ this._path = path10.resolve(projectPath);
3447
3855
  this._integrationManager = new IntegrationManager({
3448
3856
  noCache: options.noCache
3449
3857
  });
@@ -3455,7 +3863,7 @@ var init_agent_project = __esm(() => {
3455
3863
  });
3456
3864
  }
3457
3865
  static async load(projectPath, options = {}) {
3458
- const resolvedPath = path12.resolve(projectPath);
3866
+ const resolvedPath = path10.resolve(projectPath);
3459
3867
  if (!options.noCache) {
3460
3868
  const cached = AgentProject._projectCache.get(resolvedPath);
3461
3869
  if (cached) {
@@ -3473,7 +3881,7 @@ var init_agent_project = __esm(() => {
3473
3881
  AgentProject._projectCache.clear();
3474
3882
  }
3475
3883
  static clearCacheForPath(projectPath) {
3476
- const resolvedPath = path12.resolve(projectPath);
3884
+ const resolvedPath = path10.resolve(projectPath);
3477
3885
  AgentProject._projectCache.delete(resolvedPath);
3478
3886
  }
3479
3887
  get path() {
@@ -3589,17 +3997,17 @@ var init_agent_project = __esm(() => {
3589
3997
  const warnings = [];
3590
3998
  const info = [];
3591
3999
  try {
3592
- await fs11.access(this._path);
4000
+ await fs9.access(this._path);
3593
4001
  const requiredFiles = ["agent.config.ts"];
3594
4002
  for (const file of requiredFiles) {
3595
4003
  try {
3596
- await fs11.access(path12.join(this._path, file));
4004
+ await fs9.access(path10.join(this._path, file));
3597
4005
  } catch {
3598
4006
  errors.push(ValidationErrors.requiredFileMissing(file));
3599
4007
  }
3600
4008
  }
3601
4009
  try {
3602
- await fs11.access(path12.join(this._path, "agent.json"));
4010
+ await fs9.access(path10.join(this._path, "agent.json"));
3603
4011
  } catch {
3604
4012
  info.push({
3605
4013
  $type: "ValidationError",
@@ -3613,7 +4021,7 @@ var init_agent_project = __esm(() => {
3613
4021
  const expectedDirs = ["actions", "workflows", "conversations", "assets"];
3614
4022
  for (const dir of expectedDirs) {
3615
4023
  try {
3616
- const stats = await fs11.stat(path12.join(this._path, dir));
4024
+ const stats = await fs9.stat(path10.join(this._path, dir));
3617
4025
  if (!stats.isDirectory()) {
3618
4026
  warnings.push(ValidationErrors.invalidStructure(dir, "directory"));
3619
4027
  }
@@ -3697,9 +4105,9 @@ var init_agent_project = __esm(() => {
3697
4105
  }
3698
4106
  async createAgentInfo(info) {
3699
4107
  const { devId, ...agentJsonInfo } = info;
3700
- const agentPath = path12.join(this._path, "agent.json");
4108
+ const agentPath = path10.join(this._path, "agent.json");
3701
4109
  const agentContent = stringifyWithOrder(agentJsonInfo, agentInfoKeyOrder);
3702
- await fs11.writeFile(agentPath, agentContent);
4110
+ await fs9.writeFile(agentPath, agentContent);
3703
4111
  this._agentInfo = info;
3704
4112
  if (devId) {
3705
4113
  await this.createAgentLocalInfo({ devId });
@@ -3716,24 +4124,24 @@ var init_agent_project = __esm(() => {
3716
4124
  const { devId, ...agentJsonUpdates } = updates;
3717
4125
  const updatedInfo = { ...this._agentInfo, ...agentJsonUpdates };
3718
4126
  const { devId: _devId, ...agentJsonData } = updatedInfo;
3719
- const agentPath = path12.join(this._path, "agent.json");
4127
+ const agentPath = path10.join(this._path, "agent.json");
3720
4128
  const agentContent = stringifyWithOrder(agentJsonData, agentInfoKeyOrder);
3721
- await fs11.writeFile(agentPath, agentContent);
4129
+ await fs9.writeFile(agentPath, agentContent);
3722
4130
  this._agentInfo = updatedInfo;
3723
4131
  if (devId !== undefined) {
3724
4132
  await this.updateAgentLocalInfo({ devId });
3725
4133
  }
3726
4134
  }
3727
4135
  async createAgentLocalInfo(info) {
3728
- const localPath = path12.join(this._path, "agent.local.json");
4136
+ const localPath = path10.join(this._path, "agent.local.json");
3729
4137
  let existing = {};
3730
4138
  try {
3731
- const content2 = await fs11.readFile(localPath, "utf-8");
4139
+ const content2 = await fs9.readFile(localPath, "utf-8");
3732
4140
  existing = JSON.parse(content2);
3733
4141
  } catch {}
3734
4142
  const merged = { ...existing, ...info };
3735
4143
  const content = stringifyWithOrder(merged, agentLocalInfoKeyOrder);
3736
- await fs11.writeFile(localPath, content);
4144
+ await fs9.writeFile(localPath, content);
3737
4145
  if (this._agentInfo) {
3738
4146
  if (merged.botId)
3739
4147
  this._agentInfo.botId = merged.botId;
@@ -3753,10 +4161,10 @@ var init_agent_project = __esm(() => {
3753
4161
  }
3754
4162
  }
3755
4163
  async updateAgentLocalInfo(updates) {
3756
- const localPath = path12.join(this._path, "agent.local.json");
4164
+ const localPath = path10.join(this._path, "agent.local.json");
3757
4165
  let existing = {};
3758
4166
  try {
3759
- const content = await fs11.readFile(localPath, "utf-8");
4167
+ const content = await fs9.readFile(localPath, "utf-8");
3760
4168
  existing = JSON.parse(content);
3761
4169
  } catch {}
3762
4170
  const updated = { ...existing, ...updates };
@@ -3767,21 +4175,21 @@ var init_agent_project = __esm(() => {
3767
4175
  }
3768
4176
  if (Object.keys(updated).length === 0) {
3769
4177
  try {
3770
- await fs11.unlink(localPath);
4178
+ await fs9.unlink(localPath);
3771
4179
  } catch {}
3772
4180
  } else {
3773
4181
  const content = stringifyWithOrder(updated, agentLocalInfoKeyOrder);
3774
- await fs11.writeFile(localPath, content);
4182
+ await fs9.writeFile(localPath, content);
3775
4183
  }
3776
4184
  if (this._agentInfo) {
3777
- const agentJsonPath = path12.join(this._path, "agent.json");
4185
+ const agentJsonPath = path10.join(this._path, "agent.json");
3778
4186
  let base = {
3779
4187
  botId: this._agentInfo.botId,
3780
4188
  workspaceId: this._agentInfo.workspaceId,
3781
4189
  apiUrl: this._agentInfo.apiUrl
3782
4190
  };
3783
4191
  try {
3784
- const agentJsonContent = await fs11.readFile(agentJsonPath, "utf-8");
4192
+ const agentJsonContent = await fs9.readFile(agentJsonPath, "utf-8");
3785
4193
  const parsed = JSON.parse(agentJsonContent);
3786
4194
  base = {
3787
4195
  botId: parsed.botId ?? this._agentInfo.botId,
@@ -3813,10 +4221,10 @@ var init_agent_project = __esm(() => {
3813
4221
  this._integrations = [];
3814
4222
  this._interfaces = [];
3815
4223
  try {
3816
- const configPath = path12.join(this._path, "agent.config.ts");
4224
+ const configPath = path10.join(this._path, "agent.config.ts");
3817
4225
  debug("loading agent.config.ts from %s", configPath);
3818
- const projectRequire = createRequire2(path12.join(this._path, "package.json"));
3819
- debug("created projectRequire from %s", path12.join(this._path, "package.json"));
4226
+ const projectRequire = createRequire2(path10.join(this._path, "package.json"));
4227
+ debug("created projectRequire from %s", path10.join(this._path, "package.json"));
3820
4228
  try {
3821
4229
  const resolvedPath = projectRequire.resolve(configPath);
3822
4230
  debug("resolved config path: %s", resolvedPath);
@@ -3860,49 +4268,29 @@ var init_agent_project = __esm(() => {
3860
4268
  return;
3861
4269
  }
3862
4270
  this._config = configModule.default;
3863
- const lockFile = new LockFile({ projectPath: this._path, env: "dev" });
3864
- let lockBasedDependencies;
4271
+ const dependencyEnv = this._options.adkCommand === "adk-deploy" ? "prod" : "dev";
4272
+ const snapshotStore = new DependencySnapshotStore({ projectPath: this._path });
4273
+ let snapshotBasedDependencies;
4274
+ let dependencySnapshotReadFailed = false;
3865
4275
  try {
3866
- const lockData = await lockFile.read();
3867
- const hasDependencies = Object.keys(lockData.integrations).length > 0 || Object.keys(lockData.plugins).length > 0;
4276
+ const snapshot = await snapshotStore.read(dependencyEnv);
4277
+ const state = snapshot ?? { version: 1, env: dependencyEnv, integrations: {}, plugins: {} };
4278
+ const hasDependencies = Object.keys(state.integrations).length > 0 || Object.keys(state.plugins).length > 0;
3868
4279
  if (hasDependencies) {
3869
- lockBasedDependencies = lockToDependencies(lockData);
4280
+ snapshotBasedDependencies = dependencyStateToDependencies(state);
3870
4281
  }
3871
4282
  } catch (err) {
3872
4283
  this._warnings.push({
3873
4284
  $type: "ValidationError",
3874
4285
  code: "INVALID_DEPENDENCIES_SCHEMA" /* INVALID_DEPENDENCIES_SCHEMA */,
3875
4286
  severity: "warning" /* WARNING */,
3876
- message: `Could not read dependencies.dev.lock.json: ${err.message}. Falling back to agent.config.ts dependencies.`,
3877
- file: "dependencies.dev.lock.json"
4287
+ message: `Could not read .adk/dependencies/${dependencyEnv}.json: ${err.message}. Refresh dependencies from Cloud; agent.config.ts dependencies is not used when a snapshot exists but is invalid.`,
4288
+ file: `.adk/dependencies/${dependencyEnv}.json`
3878
4289
  });
4290
+ dependencySnapshotReadFailed = true;
3879
4291
  }
3880
- const config = configModule.default;
3881
- let configBasedDependencies;
3882
- if (!lockBasedDependencies && config.dependencies) {
3883
- const validationResult = dependenciesSchema.safeParse(config.dependencies);
3884
- if (!validationResult.success) {
3885
- const errors = validationResult.error.errors;
3886
- for (const error of errors) {
3887
- this._errors.push({
3888
- $type: "ValidationError",
3889
- code: "INVALID_DEPENDENCIES_SCHEMA" /* INVALID_DEPENDENCIES_SCHEMA */,
3890
- severity: "error" /* ERROR */,
3891
- message: `Invalid dependencies in agent.config.ts: ${error.path.join(".")} - ${error.message}`,
3892
- file: "agent.config.ts",
3893
- hint: error.code === "invalid_type" ? `Expected ${error.expected}, but got ${error.received}` : undefined
3894
- });
3895
- }
3896
- this._dependencies = { integrations: {} };
3897
- this._integrations = [];
3898
- this._interfaces = [];
3899
- return;
3900
- }
3901
- configBasedDependencies = validationResult.data;
3902
- }
3903
- const depsToLoad = lockBasedDependencies ?? configBasedDependencies;
3904
- if (depsToLoad) {
3905
- this._dependencies = depsToLoad;
4292
+ if (snapshotBasedDependencies) {
4293
+ this._dependencies = snapshotBasedDependencies;
3906
4294
  if (!this._options.offline) {
3907
4295
  const [intRes, ifRes] = await Promise.all([
3908
4296
  this._integrationManager.loadIntegrations(this._dependencies),
@@ -4013,8 +4401,8 @@ ${err.stack?.split(`
4013
4401
  }
4014
4402
  }
4015
4403
  isBarrelReexport(existing, newPath, newExport, newDefinition) {
4016
- const isNewBarrel = /^index\.[tj]s$/i.test(path12.basename(newPath));
4017
- const isExistingBarrel = /^index\.[tj]s$/i.test(path12.basename(existing.path));
4404
+ const isNewBarrel = /^index\.[tj]s$/i.test(path10.basename(newPath));
4405
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path10.basename(existing.path));
4018
4406
  if (!isNewBarrel && !isExistingBarrel) {
4019
4407
  return false;
4020
4408
  }
@@ -4026,16 +4414,16 @@ ${err.stack?.split(`
4026
4414
  return true;
4027
4415
  }
4028
4416
  isToolBarrelReexport(existingPath, newPath) {
4029
- const isNewBarrel = /^index\.[tj]s$/i.test(path12.basename(newPath));
4030
- const isExistingBarrel = /^index\.[tj]s$/i.test(path12.basename(existingPath));
4417
+ const isNewBarrel = /^index\.[tj]s$/i.test(path10.basename(newPath));
4418
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path10.basename(existingPath));
4031
4419
  if (!isNewBarrel && !isExistingBarrel) {
4032
4420
  return false;
4033
4421
  }
4034
4422
  return true;
4035
4423
  }
4036
4424
  shouldPreferToolDefinition(existingPath, newPath) {
4037
- const isNewBarrel = /^index\.[tj]s$/i.test(path12.basename(newPath));
4038
- const isExistingBarrel = /^index\.[tj]s$/i.test(path12.basename(existingPath));
4425
+ const isNewBarrel = /^index\.[tj]s$/i.test(path10.basename(newPath));
4426
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path10.basename(existingPath));
4039
4427
  return isExistingBarrel && !isNewBarrel;
4040
4428
  }
4041
4429
  getChannelsList(channelSpec) {
@@ -4051,8 +4439,8 @@ ${err.stack?.split(`
4051
4439
  if (this._options.adkCommand) {
4052
4440
  setAdkCommand(this._options.adkCommand);
4053
4441
  }
4054
- const src = path12.join(this._path, "src");
4055
- if (!await fs11.stat(src).catch(() => false)) {
4442
+ const src = path10.join(this._path, "src");
4443
+ if (!await fs9.stat(src).catch(() => false)) {
4056
4444
  this._errors.push({
4057
4445
  $type: "ValidationError",
4058
4446
  code: "INVALID_STRUCTURE" /* INVALID_STRUCTURE */,
@@ -4061,14 +4449,14 @@ ${err.stack?.split(`
4061
4449
  });
4062
4450
  return;
4063
4451
  }
4064
- const allFiles = await fs11.readdir(src, {
4452
+ const allFiles = await fs9.readdir(src, {
4065
4453
  withFileTypes: true,
4066
4454
  recursive: true
4067
4455
  });
4068
4456
  for (const file of allFiles.filter((x) => x.isFile())) {
4069
4457
  const filename = file.name;
4070
- const absolutePath = path12.join(file.parentPath, file.name);
4071
- const relPath = path12.relative(this.path, absolutePath);
4458
+ const absolutePath = path10.join(file.parentPath, file.name);
4459
+ const relPath = path10.relative(this.path, absolutePath);
4072
4460
  if (filename.toLowerCase().endsWith(".d.ts")) {
4073
4461
  continue;
4074
4462
  }
@@ -4403,7 +4791,7 @@ var _format = null, _formatLoaded = false, formatCode = async (code, filepath) =
4403
4791
  `));
4404
4792
  return code;
4405
4793
  }
4406
- }, ADK_VERSION = "1.19.0-beta.13", relative = (from, to) => {
4794
+ }, ADK_VERSION = "1.19.0-beta.14", relative = (from, to) => {
4407
4795
  const fromDir = path13.dirname(from);
4408
4796
  const relative2 = path13.relative(fromDir, to);
4409
4797
  return relative2.startsWith(".") ? relative2 : `./${relative2}`;
@@ -4414,14 +4802,22 @@ var init_utils = () => {};
4414
4802
  var exports_dependencies = {};
4415
4803
  __export(exports_dependencies, {
4416
4804
  sortKeysDeep: () => sortKeysDeep,
4805
+ resolveDependencyStatuses: () => resolveDependencyStatuses,
4417
4806
  migrateFromConfig: () => migrateFromConfig,
4418
4807
  jsonEqual: () => jsonEqual,
4808
+ isCallable: () => isCallable,
4809
+ emptyDependencySnapshot: () => emptyDependencySnapshot,
4810
+ dependencyStateSchema: () => dependencyStateSchema,
4811
+ dependencySnapshotFromBot: () => dependencySnapshotFromBot,
4812
+ computePluginStatus: () => computePluginStatus,
4813
+ computeIntegrationStatus: () => computeIntegrationStatus,
4419
4814
  PluginResolver: () => PluginResolver,
4420
4815
  PluginRegistry: () => PluginRegistry,
4421
- LockFile: () => LockFile,
4422
4816
  InterfaceRegistry: () => InterfaceRegistry,
4423
4817
  IntegrationResolver: () => IntegrationResolver,
4424
4818
  IntegrationRegistry: () => IntegrationRegistry,
4819
+ DependencySnapshotStore: () => DependencySnapshotStore,
4820
+ DependencyMigrationManager: () => DependencyMigrationManager,
4425
4821
  DependencyManager: () => DependencyManager,
4426
4822
  DependencyError: () => DependencyError,
4427
4823
  DEPENDENCY_WARNING_CODES: () => DEPENDENCY_WARNING_CODES,
@@ -4429,34 +4825,10 @@ __export(exports_dependencies, {
4429
4825
  });
4430
4826
 
4431
4827
  // src/dependencies/dependency-manager.ts
4432
- init_lock_file();
4433
- import * as semver2 from "semver";
4434
-
4435
- // src/dependencies/alias-utils.ts
4436
- var FRIENDLY_ALIAS_RE = /^[a-z0-9_-]{2,100}$/;
4437
- var BP_INTERNAL_ID_PREFIXES = ["intver_", "plgver_", "int_", "plg_"];
4438
- function isBotpressInternalId(alias) {
4439
- return BP_INTERNAL_ID_PREFIXES.some((prefix) => alias.startsWith(prefix));
4440
- }
4441
- function isFriendlyAlias(alias) {
4442
- return FRIENDLY_ALIAS_RE.test(alias) && !isBotpressInternalId(alias);
4443
- }
4444
- function generateFriendlyAlias(cloudName, cloudAlias, used) {
4445
- if (isFriendlyAlias(cloudAlias) && !used.has(cloudAlias))
4446
- return cloudAlias;
4447
- const base = cloudName?.split("/").at(-1) ?? cloudAlias;
4448
- const sanitized = base.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
4449
- let candidate = sanitized;
4450
- let n = 2;
4451
- while (used.has(candidate)) {
4452
- candidate = `${sanitized}-${n}`;
4453
- n++;
4454
- }
4455
- return candidate;
4456
- }
4457
-
4458
- // src/dependencies/dependency-manager.ts
4828
+ init_types();
4459
4829
  init_errors2();
4830
+ import * as semver2 from "semver";
4831
+ import { extractMissingRequiredFields } from "@botpress/runtime";
4460
4832
 
4461
4833
  // src/dependencies/resolvers/integration-resolver.ts
4462
4834
  init_errors2();
@@ -4468,13 +4840,17 @@ class IntegrationResolver {
4468
4840
  this.registry = opts.registry;
4469
4841
  this.client = opts.client;
4470
4842
  }
4471
- toLockEntry(cloud) {
4472
- return {
4843
+ toDependencyEntry(cloud) {
4844
+ const entry = {
4473
4845
  name: cloud.name ?? "",
4474
4846
  version: cloud.version ?? "0.0.0",
4475
4847
  enabled: Boolean(cloud.enabled),
4476
4848
  config: cloud.configuration ?? {}
4477
4849
  };
4850
+ if (typeof cloud.configurationType === "string" && cloud.configurationType && cloud.configurationType !== "default") {
4851
+ entry.configurationType = cloud.configurationType;
4852
+ }
4853
+ return entry;
4478
4854
  }
4479
4855
  async applyToCloud(opts) {
4480
4856
  const spec = await this.registry.getSpec(opts.entry.name, opts.entry.version);
@@ -4516,7 +4892,7 @@ class PluginResolver {
4516
4892
  this.integrationRegistry = opts.integrationRegistry;
4517
4893
  this.client = opts.client;
4518
4894
  }
4519
- toLockEntry(cloud) {
4895
+ toDependencyEntry(cloud) {
4520
4896
  const dependencies = {};
4521
4897
  for (const [ifaceAlias, dep] of Object.entries(cloud.interfaces ?? {})) {
4522
4898
  if (dep.integrationAlias) {
@@ -4544,7 +4920,7 @@ class PluginResolver {
4544
4920
  details: { plugin: opts.alias, pluginInterfaceAlias: pluginIfaceAlias, interfaceName: requirement.name }
4545
4921
  });
4546
4922
  }
4547
- const integration = opts.lock.integrations[dep.integrationAlias];
4923
+ const integration = opts.state.integrations[dep.integrationAlias];
4548
4924
  if (!integration) {
4549
4925
  throw new DependencyError({
4550
4926
  code: "MISSING_DEPENDENCY",
@@ -4619,199 +4995,24 @@ class IntegrationRegistry {
4619
4995
  }
4620
4996
  }
4621
4997
 
4622
- // src/plugins/manager.ts
4623
- init_src();
4624
- init_auth();
4625
- import { Client as Client4 } from "@botpress/client";
4626
-
4627
- // src/plugins/enhanced-cache.ts
4628
- import fs6 from "fs/promises";
4629
- import path6 from "path";
4630
- import os4 from "os";
4631
-
4632
- class EnhancedPluginCache {
4633
- cacheDir;
4634
- resolutionsDir;
4635
- definitionsDir;
4636
- noCache;
4637
- constructor(noCache = false) {
4638
- this.noCache = noCache;
4639
- this.cacheDir = path6.join(os4.homedir(), ".adk", "cache", "plugins");
4640
- this.resolutionsDir = path6.join(this.cacheDir, "resolutions");
4641
- this.definitionsDir = path6.join(this.cacheDir, "definitions");
4642
- }
4643
- async ensureCacheDirs() {
4644
- await fs6.mkdir(this.resolutionsDir, { recursive: true });
4645
- await fs6.mkdir(this.definitionsDir, { recursive: true });
4646
- }
4647
- async getResolution(name, version) {
4648
- if (this.noCache) {
4649
- return null;
4650
- }
4651
- try {
4652
- const key = this.getResolutionKey(name, version);
4653
- const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
4654
- const data = await fs6.readFile(cachePath, "utf-8");
4655
- const resolution = JSON.parse(data);
4656
- const cachedAt = new Date(resolution.cachedAt);
4657
- const now = new Date;
4658
- const ageMinutes = (now.getTime() - cachedAt.getTime()) / (1000 * 60);
4659
- if (ageMinutes > 5) {
4660
- return null;
4661
- }
4662
- return resolution;
4663
- } catch {
4664
- return null;
4665
- }
4666
- }
4667
- async setResolution(name, version, pluginId, updatedAt) {
4668
- await this.ensureCacheDirs();
4669
- const key = this.getResolutionKey(name, version);
4670
- const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
4671
- const resolution = {
4672
- pluginId,
4673
- updatedAt,
4674
- cachedAt: new Date().toISOString()
4675
- };
4676
- await fs6.writeFile(cachePath, JSON.stringify(resolution));
4677
- }
4678
- async getDefinition(pluginId, updatedAt) {
4679
- if (this.noCache) {
4680
- return null;
4681
- }
4682
- try {
4683
- const key = this.getDefinitionKey(pluginId, updatedAt);
4684
- const cachePath = path6.join(this.definitionsDir, `${key}.json`);
4685
- const data = await fs6.readFile(cachePath, "utf-8");
4686
- const cached = JSON.parse(data);
4687
- return cached.definition;
4688
- } catch {
4689
- return null;
4690
- }
4691
- }
4692
- async setDefinition(pluginId, updatedAt, definition) {
4693
- await this.ensureCacheDirs();
4694
- const key = this.getDefinitionKey(pluginId, updatedAt);
4695
- const cachePath = path6.join(this.definitionsDir, `${key}.json`);
4696
- const cached = {
4697
- definition,
4698
- cachedAt: new Date().toISOString()
4699
- };
4700
- await fs6.writeFile(cachePath, JSON.stringify(cached));
4701
- }
4702
- async clear() {
4703
- try {
4704
- const resolutionFiles = await fs6.readdir(this.resolutionsDir);
4705
- await Promise.all(resolutionFiles.map((file) => fs6.unlink(path6.join(this.resolutionsDir, file))));
4706
- const definitionFiles = await fs6.readdir(this.definitionsDir);
4707
- await Promise.all(definitionFiles.map((file) => fs6.unlink(path6.join(this.definitionsDir, file))));
4708
- } catch {}
4709
- }
4710
- async getStats() {
4711
- const getDirectoryStats = async (dir) => {
4712
- try {
4713
- const files = await fs6.readdir(dir);
4714
- let totalSize = 0;
4715
- for (const file of files) {
4716
- const stats = await fs6.stat(path6.join(dir, file));
4717
- totalSize += stats.size;
4718
- }
4719
- return {
4720
- count: files.length,
4721
- sizeBytes: totalSize
4722
- };
4723
- } catch {
4724
- return { count: 0, sizeBytes: 0 };
4725
- }
4726
- };
4727
- const [resolutions, definitions] = await Promise.all([
4728
- getDirectoryStats(this.resolutionsDir),
4729
- getDirectoryStats(this.definitionsDir)
4730
- ]);
4731
- return { resolutions, definitions };
4732
- }
4733
- getResolutionKey(name, version) {
4734
- const key = `${name}_${version}`;
4735
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
4736
- }
4737
- getDefinitionKey(pluginId, updatedAt) {
4738
- const key = `${pluginId}_${updatedAt}`;
4739
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
4740
- }
4741
- }
4742
-
4743
4998
  // src/plugins/manager.ts
4744
4999
  init_dependencies_parser();
4745
5000
  init_validation_errors();
5001
+ init_client_factory();
5002
+ init_catalog_service();
5003
+
5004
+ // src/dependencies/catalog/plugin-source.ts
5005
+ init_src();
4746
5006
  init_search_ranking();
4747
5007
 
4748
- class PluginManager {
4749
- cache;
4750
- options;
4751
- client;
4752
- constructor(options = {}) {
4753
- this.options = options;
4754
- this.cache = new EnhancedPluginCache(options.noCache || false);
4755
- }
4756
- async getClient() {
4757
- if (!this.client) {
4758
- const hasProjectScope = !!(this.options.project || this.options.workspaceId);
4759
- if (hasProjectScope) {
4760
- this.client = await getProjectClient({
4761
- project: this.options.project,
4762
- credentials: this.options.credentials,
4763
- apiUrl: this.options.apiUrl,
4764
- workspaceId: this.options.workspaceId,
4765
- headers: {
4766
- "x-multiple-integrations": "true"
4767
- }
4768
- });
4769
- } else if (this.options.credentials) {
4770
- this.client = new Client4({
4771
- token: this.options.credentials.token,
4772
- apiUrl: this.options.apiUrl || this.options.credentials.apiUrl,
4773
- ...this.options.credentials.workspaceId ? { workspaceId: this.options.credentials.workspaceId } : {},
4774
- headers: {
4775
- "x-multiple-integrations": "true"
4776
- }
4777
- });
4778
- } else {
4779
- this.client = await getProjectClient({
4780
- headers: {
4781
- "x-multiple-integrations": "true"
4782
- }
4783
- });
4784
- }
4785
- }
4786
- return this.client;
4787
- }
4788
- async loadPlugins(dependencies) {
4789
- const errors = [];
4790
- const warnings = [];
4791
- const parseResult = PluginParser.parsePlugins(dependencies);
4792
- const plugins = parseResult.plugins;
4793
- errors.push(...parseResult.errors);
4794
- const duplicateWarnings = PluginParser.checkDuplicates(plugins);
4795
- warnings.push(...duplicateWarnings);
4796
- const fetchPromises = plugins.map(async (plugin) => {
4797
- try {
4798
- plugin.definition = await this.fetchPlugin(plugin.ref);
4799
- } catch {
4800
- errors.push(ValidationErrors.unknownPlugin(plugin.alias, plugin.ref.fullName));
4801
- }
4802
- });
4803
- await Promise.all(fetchPromises);
4804
- return { plugins, errors, warnings };
4805
- }
4806
- async fetchPlugin(ref) {
4807
- const cachedResolution = await this.cache.getResolution(ref.name, ref.version);
4808
- if (cachedResolution) {
4809
- const cachedDefinition = await this.cache.getDefinition(cachedResolution.pluginId, cachedResolution.updatedAt);
4810
- if (cachedDefinition) {
4811
- return cachedDefinition;
4812
- }
4813
- }
4814
- const client = await this.getClient();
5008
+ class PluginCatalogSource {
5009
+ clientFactory;
5010
+ cacheConfig = { cacheType: "plugins", idField: "pluginId" };
5011
+ constructor(clientFactory) {
5012
+ this.clientFactory = clientFactory;
5013
+ }
5014
+ async fetchByRef(ref) {
5015
+ const client = await this.clientFactory.getClient();
4815
5016
  const plugin = await this._findPublicPlugin(client, ref);
4816
5017
  if (!plugin) {
4817
5018
  throw new AdkError({
@@ -4820,20 +5021,18 @@ class PluginManager {
4820
5021
  message: await this._buildPluginNotFoundMessage(client, ref)
4821
5022
  });
4822
5023
  }
4823
- await this.cache.setResolution(ref.name, ref.version, plugin.id, plugin.updatedAt);
4824
- await this.cache.setDefinition(plugin.id, plugin.updatedAt, plugin);
4825
- return plugin;
5024
+ return { id: plugin.id, updatedAt: plugin.updatedAt, definition: plugin };
4826
5025
  }
4827
- async searchPlugins(query, limit = 20) {
4828
- const client = await this.getClient();
5026
+ async search(query, limit = 20) {
5027
+ const client = await this.clientFactory.getClient();
4829
5028
  const results = new Map;
4830
5029
  for await (const plugin of client.list.publicPlugins({})) {
4831
5030
  collectCatalogSearchResult(results, plugin, query);
4832
5031
  }
4833
5032
  return getSortedCatalogSearchResults(results, limit);
4834
5033
  }
4835
- async listPluginVersions(name) {
4836
- const client = await this.getClient();
5034
+ async listVersions(name) {
5035
+ const client = await this.clientFactory.getClient();
4837
5036
  const versions = new Set;
4838
5037
  for await (const plugin of client.list.publicPlugins({ name })) {
4839
5038
  versions.add(plugin.version);
@@ -4869,15 +5068,49 @@ class PluginManager {
4869
5068
  }
4870
5069
  return false;
4871
5070
  }
5071
+ }
5072
+
5073
+ // src/plugins/manager.ts
5074
+ class PluginManager {
5075
+ source;
5076
+ service;
5077
+ constructor(options = {}) {
5078
+ const { noCache, ...clientOptions } = options;
5079
+ this.source = new PluginCatalogSource(new CatalogClientFactory(clientOptions));
5080
+ this.service = new CatalogService(this.source, noCache || false);
5081
+ }
5082
+ async loadPlugins(dependencies) {
5083
+ const errors = [];
5084
+ const warnings = [];
5085
+ const parseResult = PluginParser.parsePlugins(dependencies);
5086
+ const plugins = parseResult.plugins;
5087
+ errors.push(...parseResult.errors);
5088
+ const duplicateWarnings = PluginParser.checkDuplicates(plugins);
5089
+ warnings.push(...duplicateWarnings);
5090
+ const fetchPromises = plugins.map(async (plugin) => {
5091
+ try {
5092
+ plugin.definition = await this.fetchPlugin(plugin.ref);
5093
+ } catch {
5094
+ errors.push(ValidationErrors.unknownPlugin(plugin.alias, plugin.ref.fullName));
5095
+ }
5096
+ });
5097
+ await Promise.all(fetchPromises);
5098
+ return { plugins, errors, warnings };
5099
+ }
5100
+ async fetchPlugin(ref) {
5101
+ return this.service.getDefinition(ref);
5102
+ }
5103
+ async searchPlugins(query, limit = 20) {
5104
+ return this.source.search(query, limit);
5105
+ }
5106
+ async listPluginVersions(name) {
5107
+ return this.source.listVersions(name);
5108
+ }
4872
5109
  async getCacheStats() {
4873
- const stats = await this.cache.getStats();
4874
- return {
4875
- count: stats.resolutions.count + stats.definitions.count,
4876
- sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
4877
- };
5110
+ return this.service.getCacheStats();
4878
5111
  }
4879
5112
  async clearCache() {
4880
- await this.cache.clear();
5113
+ await this.service.clearCache();
4881
5114
  }
4882
5115
  }
4883
5116
 
@@ -4905,9 +5138,10 @@ class PluginRegistry {
4905
5138
 
4906
5139
  // src/dependencies/dependency-manager.ts
4907
5140
  init_agent_project();
5141
+ init_snapshot_store();
4908
5142
 
4909
5143
  class DependencyManager {
4910
- lockFile;
5144
+ snapshotStore;
4911
5145
  env;
4912
5146
  client;
4913
5147
  projectPath;
@@ -4920,8 +5154,8 @@ class DependencyManager {
4920
5154
  this.projectPath = opts.projectPath;
4921
5155
  this.env = opts.env;
4922
5156
  this.client = opts.client;
4923
- this.lockFile = new LockFile({ projectPath: opts.projectPath, env: opts.env });
4924
5157
  this.botId = opts.botId;
5158
+ this.snapshotStore = new DependencySnapshotStore({ projectPath: opts.projectPath });
4925
5159
  this.integrationRegistry = opts.integrationRegistry ?? new IntegrationRegistry;
4926
5160
  this.pluginRegistry = opts.pluginRegistry ?? new PluginRegistry;
4927
5161
  this.integrationResolver = opts.integrationResolver ?? new IntegrationResolver({ registry: this.integrationRegistry, client: this.client });
@@ -4933,14 +5167,13 @@ class DependencyManager {
4933
5167
  }
4934
5168
  static async fromProject(opts) {
4935
5169
  const project = await AgentProject.load(opts.projectPath);
4936
- const info = project.agentInfo;
4937
- if (!info) {
5170
+ const botId = opts.botId ?? DependencyManager.getProjectBotId(project, opts.env);
5171
+ if (!botId) {
4938
5172
  throw new DependencyError({
4939
5173
  code: "BOT_NOT_FOUND",
4940
- message: `No agent.json found in ${opts.projectPath}. Run 'adk init' or 'adk login' to set up the project.`
5174
+ message: `No ${opts.env} bot ID found in ${opts.projectPath}. Run 'adk link' to link the project to a bot.`
4941
5175
  });
4942
5176
  }
4943
- const botId = opts.env === "dev" ? info.devId ?? info.botId : info.botId;
4944
5177
  return new DependencyManager({
4945
5178
  projectPath: project.path,
4946
5179
  env: opts.env,
@@ -4952,8 +5185,68 @@ class DependencyManager {
4952
5185
  pluginResolver: opts.pluginResolver
4953
5186
  });
4954
5187
  }
5188
+ static getProjectBotId(project, env) {
5189
+ const info = project.agentInfo;
5190
+ if (!info)
5191
+ return;
5192
+ return env === "dev" ? info.devId ?? info.botId : info.botId;
5193
+ }
5194
+ async getProjectBotId(env) {
5195
+ const project = await AgentProject.load(this.projectPath);
5196
+ const botId = DependencyManager.getProjectBotId(project, env);
5197
+ if (!botId) {
5198
+ throw new DependencyError({
5199
+ code: "BOT_NOT_FOUND",
5200
+ message: `No ${env} bot ID found in ${this.projectPath}. Run 'adk link' to link the project to a bot.`
5201
+ });
5202
+ }
5203
+ return botId;
5204
+ }
5205
+ async readSnapshot(options) {
5206
+ return this.snapshotStore.readOrEmpty(this.env, {
5207
+ tolerant: options?.tolerant,
5208
+ botId: this.botId
5209
+ });
5210
+ }
5211
+ async writeSnapshot(snapshot) {
5212
+ await this.snapshotStore.write({
5213
+ ...snapshot,
5214
+ botId: snapshot.botId || this.botId,
5215
+ fetchedAt: new Date().toISOString()
5216
+ });
5217
+ }
5218
+ async readCloudSnapshot(previous) {
5219
+ const { bot } = await this.client.getBot({ id: this.botId });
5220
+ return dependencySnapshotFromBot({
5221
+ bot,
5222
+ botId: this.botId,
5223
+ env: this.env,
5224
+ fetchedAt: new Date,
5225
+ previous
5226
+ });
5227
+ }
5228
+ async snapshotStateFromCloud() {
5229
+ const previous = await this.readSnapshot({ tolerant: true });
5230
+ const cloud = await this.readCloudSnapshot(previous);
5231
+ return dependencySnapshotToState(cloud);
5232
+ }
5233
+ async applyState(state, opts) {
5234
+ const parsed = dependencyStateSchema.parse({
5235
+ ...state,
5236
+ env: this.env
5237
+ });
5238
+ await this.writeSnapshot({
5239
+ version: 1,
5240
+ env: this.env,
5241
+ botId: this.botId,
5242
+ fetchedAt: new Date().toISOString(),
5243
+ integrations: parsed.integrations,
5244
+ plugins: parsed.plugins
5245
+ });
5246
+ return await this.apply(opts);
5247
+ }
4955
5248
  async list(type) {
4956
- const data = await this.lockFile.read();
5249
+ const data = await this.readSnapshot({ tolerant: true });
4957
5250
  const out = [];
4958
5251
  if (!type || type === "integration") {
4959
5252
  for (const [alias, e] of Object.entries(data.integrations)) {
@@ -4980,9 +5273,9 @@ class DependencyManager {
4980
5273
  }
4981
5274
  const alias = spec.alias ?? spec.name;
4982
5275
  const version = spec.version ?? "latest";
4983
- const lock = await this.lockFile.read();
4984
- if (type === "integration" && lock.integrations[alias]) {
4985
- const existing = lock.integrations[alias];
5276
+ const snapshot = await this.readSnapshot();
5277
+ if (type === "integration" && snapshot.integrations[alias]) {
5278
+ const existing = snapshot.integrations[alias];
4986
5279
  const versionMatch = version === "latest" || existing.version === version;
4987
5280
  if (existing.enabled && versionMatch && jsonEqual(existing.config, spec.config ?? {})) {
4988
5281
  return {
@@ -4992,8 +5285,8 @@ class DependencyManager {
4992
5285
  };
4993
5286
  }
4994
5287
  }
4995
- if (type === "plugin" && lock.plugins[alias]) {
4996
- const existing = lock.plugins[alias];
5288
+ if (type === "plugin" && snapshot.plugins[alias]) {
5289
+ const existing = snapshot.plugins[alias];
4997
5290
  const versionMatch = version === "latest" || existing.version === version;
4998
5291
  if (existing.enabled && versionMatch && jsonEqual(existing.config, spec.config ?? {})) {
4999
5292
  return {
@@ -5011,28 +5304,54 @@ class DependencyManager {
5011
5304
  config: spec.config ?? {}
5012
5305
  };
5013
5306
  let installedDisabled;
5307
+ let authorizationPending = false;
5014
5308
  try {
5015
5309
  await this.integrationResolver.applyToCloud({ botId: this.botId, alias, entry: desired });
5016
5310
  } catch (err) {
5017
5311
  const missingFields = extractMissingRequiredFields(err);
5018
- if (!missingFields)
5312
+ if (missingFields) {
5313
+ await this.integrationResolver.applyToCloud({
5314
+ botId: this.botId,
5315
+ alias,
5316
+ entry: { ...desired, enabled: false }
5317
+ });
5318
+ installedDisabled = { missingFields };
5319
+ } else if (await this.specRequiresAuthorization(spec.name, spec.version)) {
5320
+ await this.integrationResolver.applyToCloud({
5321
+ botId: this.botId,
5322
+ alias,
5323
+ entry: { ...desired, enabled: false }
5324
+ });
5325
+ authorizationPending = true;
5326
+ } else {
5019
5327
  throw err;
5020
- await this.integrationResolver.applyToCloud({
5021
- botId: this.botId,
5022
- alias,
5023
- entry: { ...desired, enabled: false }
5024
- });
5025
- installedDisabled = { missingFields };
5328
+ }
5329
+ }
5330
+ const refreshed = await this.refreshSnapshotFromCloud();
5331
+ if (installedDisabled || authorizationPending) {
5332
+ const snapshotAlias = refreshed.integrations[alias] ? alias : Object.keys(refreshed.integrations).find((k) => !snapshot.integrations[k] && !refreshed.integrations[k].enabled && refreshed.integrations[k].name === spec.name);
5333
+ if (snapshotAlias && refreshed.integrations[snapshotAlias]) {
5334
+ refreshed.integrations[snapshotAlias] = {
5335
+ ...refreshed.integrations[snapshotAlias],
5336
+ ...installedDisabled ? { missingFields: installedDisabled.missingFields } : {},
5337
+ ...authorizationPending ? { authorizationPending: true } : {}
5338
+ };
5339
+ await this.writeSnapshot(refreshed);
5340
+ }
5026
5341
  }
5027
- const refreshed = await this.refreshLockFromCloud();
5028
5342
  const resolvedVersion = refreshed.integrations[alias]?.version ?? version;
5029
- return { ok: true, resource: { type, alias, name: spec.name, version: resolvedVersion }, installedDisabled };
5343
+ return {
5344
+ ok: true,
5345
+ resource: { type, alias, name: spec.name, version: resolvedVersion },
5346
+ installedDisabled,
5347
+ ...authorizationPending ? { installedAwaitingAuthorization: true } : {}
5348
+ };
5030
5349
  } else {
5031
5350
  const { dependencies: resolvedDeps, autoResolved } = await this.resolvePluginDependencies({
5032
5351
  pluginName: spec.name,
5033
5352
  pluginVersion: version,
5034
5353
  userDeps: spec.dependencies ?? {},
5035
- lock
5354
+ state: snapshot
5036
5355
  });
5037
5356
  const desired = {
5038
5357
  name: spec.name,
@@ -5041,18 +5360,47 @@ class DependencyManager {
5041
5360
  config: spec.config ?? {},
5042
5361
  dependencies: resolvedDeps
5043
5362
  };
5044
- await this.pluginResolver.applyToCloud({ botId: this.botId, alias, entry: desired, lock });
5045
- const refreshed = await this.refreshLockFromCloud();
5363
+ let installedDisabled;
5364
+ try {
5365
+ await this.pluginResolver.applyToCloud({ botId: this.botId, alias, entry: desired, state: snapshot });
5366
+ } catch (err) {
5367
+ const missingFields = extractMissingRequiredFields(err);
5368
+ if (!missingFields)
5369
+ throw err;
5370
+ await this.pluginResolver.applyToCloud({
5371
+ botId: this.botId,
5372
+ alias,
5373
+ entry: { ...desired, enabled: false },
5374
+ state: snapshot
5375
+ });
5376
+ installedDisabled = { missingFields };
5377
+ }
5378
+ const refreshed = await this.refreshSnapshotFromCloud();
5379
+ if (installedDisabled) {
5380
+ const snapshotAlias = refreshed.plugins[alias] ? alias : Object.keys(refreshed.plugins).find((k) => !snapshot.plugins[k] && !refreshed.plugins[k].enabled && refreshed.plugins[k].name === spec.name);
5381
+ if (snapshotAlias && refreshed.plugins[snapshotAlias]) {
5382
+ refreshed.plugins[snapshotAlias] = {
5383
+ ...refreshed.plugins[snapshotAlias],
5384
+ missingFields: installedDisabled.missingFields
5385
+ };
5386
+ await this.writeSnapshot(refreshed);
5387
+ }
5388
+ }
5046
5389
  const resolvedVersion = refreshed.plugins[alias]?.version ?? version;
5047
- return { ok: true, resource: { type, alias, name: spec.name, version: resolvedVersion }, autoResolved };
5390
+ return {
5391
+ ok: true,
5392
+ resource: { type, alias, name: spec.name, version: resolvedVersion },
5393
+ autoResolved,
5394
+ installedDisabled
5395
+ };
5048
5396
  }
5049
5397
  }
5050
5398
  async remove(type, alias) {
5051
5399
  if (type === "interface") {
5052
5400
  throw new DependencyError({ code: "BUILTIN_INTERFACE_IMMUTABLE", message: "Interfaces cannot be removed." });
5053
5401
  }
5054
- const lock = await this.lockFile.read();
5055
- const exists = type === "integration" ? !!lock.integrations[alias] : !!lock.plugins[alias];
5402
+ const snapshot = await this.readSnapshot();
5403
+ const exists = type === "integration" ? !!snapshot.integrations[alias] : !!snapshot.plugins[alias];
5056
5404
  if (!exists)
5057
5405
  return { ok: true, noop: true };
5058
5406
  if (type === "integration") {
@@ -5060,15 +5408,15 @@ class DependencyManager {
5060
5408
  } else {
5061
5409
  await this.pluginResolver.removeFromCloud({ botId: this.botId, alias });
5062
5410
  }
5063
- await this.refreshLockFromCloud();
5411
+ await this.refreshSnapshotFromCloud();
5064
5412
  return { ok: true };
5065
5413
  }
5066
5414
  async upgrade(type, alias, version) {
5067
5415
  if (type === "interface") {
5068
5416
  throw new DependencyError({ code: "BUILTIN_INTERFACE_IMMUTABLE", message: "Interfaces cannot be upgraded." });
5069
5417
  }
5070
- const lock = await this.lockFile.read();
5071
- const existing = type === "integration" ? lock.integrations[alias] : lock.plugins[alias];
5418
+ const snapshot = await this.readSnapshot();
5419
+ const existing = type === "integration" ? snapshot.integrations[alias] : snapshot.plugins[alias];
5072
5420
  if (!existing) {
5073
5421
  throw new DependencyError({
5074
5422
  code: type === "integration" ? "INTEGRATION_NOT_FOUND" : "PLUGIN_NOT_FOUND",
@@ -5080,8 +5428,8 @@ class DependencyManager {
5080
5428
  return { ok: true, noop: true, resource: { type, alias, name: existing.name, version: existing.version } };
5081
5429
  }
5082
5430
  const next = { ...existing, version: targetVersion };
5083
- await this.applyEntry(type, alias, next, lock);
5084
- await this.refreshLockFromCloud();
5431
+ await this.applyEntry(type, alias, next, snapshot);
5432
+ await this.refreshSnapshotFromCloud();
5085
5433
  return { ok: true, resource: { type, alias, name: existing.name, version: next.version } };
5086
5434
  }
5087
5435
  async enable(type, alias) {
@@ -5097,8 +5445,8 @@ class DependencyManager {
5097
5445
  message: "Interfaces cannot be enabled/disabled."
5098
5446
  });
5099
5447
  }
5100
- const lock = await this.lockFile.read();
5101
- const existing = type === "integration" ? lock.integrations[alias] : lock.plugins[alias];
5448
+ const snapshot = await this.readSnapshot();
5449
+ const existing = type === "integration" ? snapshot.integrations[alias] : snapshot.plugins[alias];
5102
5450
  if (!existing) {
5103
5451
  throw new DependencyError({
5104
5452
  code: type === "integration" ? "INTEGRATION_NOT_FOUND" : "PLUGIN_NOT_FOUND",
@@ -5107,12 +5455,12 @@ class DependencyManager {
5107
5455
  }
5108
5456
  if (existing.enabled === enabled)
5109
5457
  return { ok: true, noop: true };
5110
- await this.applyEntry(type, alias, { ...existing, enabled }, lock);
5111
- const refreshedLock = await this.refreshLockFromCloud();
5112
- const refreshedEntry = type === "integration" ? refreshedLock.integrations[alias] : refreshedLock.plugins[alias];
5458
+ await this.applyEntry(type, alias, { ...existing, enabled }, snapshot);
5459
+ const refreshedSnapshot = await this.refreshSnapshotFromCloud();
5460
+ const refreshedEntry = type === "integration" ? refreshedSnapshot.integrations[alias] : refreshedSnapshot.plugins[alias];
5113
5461
  if (!refreshedEntry || refreshedEntry.enabled !== enabled) {
5114
5462
  throw new DependencyError({
5115
- code: "LOCK_DRIFT",
5463
+ code: "SNAPSHOT_DRIFT",
5116
5464
  message: `Cloud did not persist ${type} '${alias}' as ${enabled ? "enabled" : "disabled"}.`,
5117
5465
  details: {
5118
5466
  type,
@@ -5128,8 +5476,8 @@ class DependencyManager {
5128
5476
  if (type === "interface") {
5129
5477
  throw new DependencyError({ code: "BUILTIN_INTERFACE_IMMUTABLE", message: "Interfaces cannot be configured." });
5130
5478
  }
5131
- const lock = await this.lockFile.read();
5132
- const existing = type === "integration" ? lock.integrations[alias] : lock.plugins[alias];
5479
+ const snapshot = await this.readSnapshot();
5480
+ const existing = type === "integration" ? snapshot.integrations[alias] : snapshot.plugins[alias];
5133
5481
  if (!existing) {
5134
5482
  throw new DependencyError({
5135
5483
  code: type === "integration" ? "INTEGRATION_NOT_FOUND" : "PLUGIN_NOT_FOUND",
@@ -5146,11 +5494,11 @@ class DependencyManager {
5146
5494
  if (jsonEqual(next, existing)) {
5147
5495
  return { ok: true, noop: true, resource: { type, alias, name: existing.name, version: existing.version } };
5148
5496
  }
5149
- await this.applyEntry(type, alias, next, lock);
5150
- await this.refreshLockFromCloud();
5497
+ await this.applyEntry(type, alias, next, snapshot);
5498
+ await this.refreshSnapshotFromCloud();
5151
5499
  return { ok: true, resource: { type, alias, name: existing.name, version: existing.version } };
5152
5500
  }
5153
- async applyEntry(type, alias, entry, lock) {
5501
+ async applyEntry(type, alias, entry, state) {
5154
5502
  if (type === "integration") {
5155
5503
  await this.integrationResolver.applyToCloud({
5156
5504
  botId: this.botId,
@@ -5162,7 +5510,7 @@ class DependencyManager {
5162
5510
  botId: this.botId,
5163
5511
  alias,
5164
5512
  entry,
5165
- lock
5513
+ state
5166
5514
  });
5167
5515
  }
5168
5516
  }
@@ -5176,7 +5524,7 @@ class DependencyManager {
5176
5524
  continue;
5177
5525
  }
5178
5526
  const candidates = [];
5179
- for (const [integrationAlias, integrationEntry] of Object.entries(opts.lock.integrations)) {
5527
+ for (const [integrationAlias, integrationEntry] of Object.entries(opts.state.integrations)) {
5180
5528
  let integrationSpec;
5181
5529
  try {
5182
5530
  integrationSpec = await this.integrationRegistry.getSpec(integrationEntry.name, integrationEntry.version);
@@ -5235,85 +5583,67 @@ class DependencyManager {
5235
5583
  return [];
5236
5584
  }
5237
5585
  }
5238
- async refreshLockFromCloud() {
5239
- const { bot } = await this.client.getBot({ id: this.botId });
5240
- const previous = await this.lockFile.read();
5241
- const updated = { ...previous, ...this.cloudToLockShape(bot, previous) };
5242
- await this.lockFile.write(updated);
5243
- return updated;
5586
+ async specRequiresAuthorization(name, version) {
5587
+ try {
5588
+ const spec = await this.integrationRegistry.getSpec(name, version);
5589
+ return integrationRequiresAuthorization(spec);
5590
+ } catch {
5591
+ return false;
5592
+ }
5593
+ }
5594
+ async refreshSnapshotFromCloud() {
5595
+ return this.snapshotStore.refreshFromCloud({
5596
+ client: this.client,
5597
+ botId: this.botId,
5598
+ env: this.env,
5599
+ integrationRegistry: this.integrationRegistry
5600
+ });
5601
+ }
5602
+ integrationEntriesMatch(a, b) {
5603
+ return jsonEqual(stripSnapshotMetadata(a), stripSnapshotMetadata(b));
5604
+ }
5605
+ pluginEntriesMatch(a, b) {
5606
+ return jsonEqual(stripSnapshotMetadata(a), stripSnapshotMetadata(b));
5244
5607
  }
5245
5608
  async diff() {
5246
- const lock = await this.lockFile.read();
5247
- const cloud = await this.readCloudAsLockShape(lock);
5248
- const delta = { addedInLock: [], removedInLock: [], changedInLock: [] };
5249
- for (const [alias, entry] of Object.entries(lock.integrations)) {
5609
+ const snapshot = await this.readSnapshot();
5610
+ const cloud = await this.readCloudSnapshot(snapshot);
5611
+ const delta = { addedInSnapshot: [], removedInSnapshot: [], changedInSnapshot: [] };
5612
+ for (const [alias, entry] of Object.entries(snapshot.integrations)) {
5250
5613
  const cloudEntry = cloud.integrations[alias];
5251
5614
  if (!cloudEntry) {
5252
- delta.addedInLock.push({ type: "integration", alias, name: entry.name, version: entry.version });
5253
- } else if (!jsonEqual(entry, cloudEntry)) {
5254
- delta.changedInLock.push({ type: "integration", alias, field: "unspecified" });
5615
+ delta.addedInSnapshot.push({ type: "integration", alias, name: entry.name, version: entry.version });
5616
+ } else if (!this.integrationEntriesMatch(entry, cloudEntry)) {
5617
+ delta.changedInSnapshot.push({ type: "integration", alias, field: "unspecified" });
5255
5618
  }
5256
5619
  }
5257
5620
  for (const [alias, entry] of Object.entries(cloud.integrations)) {
5258
- if (!lock.integrations[alias]) {
5259
- delta.removedInLock.push({ type: "integration", alias, name: entry.name, version: entry.version });
5621
+ if (!snapshot.integrations[alias]) {
5622
+ delta.removedInSnapshot.push({ type: "integration", alias, name: entry.name, version: entry.version });
5260
5623
  }
5261
5624
  }
5262
- for (const [alias, entry] of Object.entries(lock.plugins)) {
5625
+ for (const [alias, entry] of Object.entries(snapshot.plugins)) {
5263
5626
  const cloudEntry = cloud.plugins[alias];
5264
5627
  if (!cloudEntry) {
5265
- delta.addedInLock.push({ type: "plugin", alias, name: entry.name, version: entry.version });
5266
- } else if (!jsonEqual(entry, cloudEntry)) {
5267
- delta.changedInLock.push({ type: "plugin", alias, field: "unspecified" });
5628
+ delta.addedInSnapshot.push({ type: "plugin", alias, name: entry.name, version: entry.version });
5629
+ } else if (!this.pluginEntriesMatch(entry, cloudEntry)) {
5630
+ delta.changedInSnapshot.push({ type: "plugin", alias, field: "unspecified" });
5268
5631
  }
5269
5632
  }
5270
5633
  for (const [alias, entry] of Object.entries(cloud.plugins)) {
5271
- if (!lock.plugins[alias]) {
5272
- delta.removedInLock.push({ type: "plugin", alias, name: entry.name, version: entry.version });
5634
+ if (!snapshot.plugins[alias]) {
5635
+ delta.removedInSnapshot.push({ type: "plugin", alias, name: entry.name, version: entry.version });
5273
5636
  }
5274
5637
  }
5275
- const lockReflectsCloud = delta.addedInLock.length === 0 && delta.removedInLock.length === 0 && delta.changedInLock.length === 0;
5276
- return { target: this.env, lockReflectsCloud, delta };
5277
- }
5278
- async sync(opts) {
5279
- const previous = await this.lockFile.read();
5280
- const cloud = await this.readCloudAsLockShape(previous);
5281
- const added = [];
5282
- const removed = [];
5283
- const updated = [];
5284
- for (const [alias, entry] of Object.entries(cloud.integrations)) {
5285
- const prev = previous.integrations[alias];
5286
- if (!prev)
5287
- added.push({ type: "integration", alias });
5288
- else if (!jsonEqual(prev, entry))
5289
- updated.push({ type: "integration", alias });
5290
- }
5291
- for (const alias of Object.keys(previous.integrations)) {
5292
- if (!cloud.integrations[alias])
5293
- removed.push({ type: "integration", alias });
5294
- }
5295
- for (const [alias, entry] of Object.entries(cloud.plugins)) {
5296
- const prev = previous.plugins[alias];
5297
- if (!prev)
5298
- added.push({ type: "plugin", alias });
5299
- else if (!jsonEqual(prev, entry))
5300
- updated.push({ type: "plugin", alias });
5301
- }
5302
- for (const alias of Object.keys(previous.plugins)) {
5303
- if (!cloud.plugins[alias])
5304
- removed.push({ type: "plugin", alias });
5305
- }
5306
- if (!opts?.dryRun) {
5307
- await this.lockFile.write({ ...previous, integrations: cloud.integrations, plugins: cloud.plugins });
5308
- }
5309
- return { target: this.env, added, removed, updated, dryRun: opts?.dryRun ?? false };
5638
+ const snapshotReflectsCloud = delta.addedInSnapshot.length === 0 && delta.removedInSnapshot.length === 0 && delta.changedInSnapshot.length === 0;
5639
+ return { target: this.env, snapshotReflectsCloud, delta };
5310
5640
  }
5311
5641
  async apply(opts) {
5312
- const lock = await this.lockFile.read();
5313
- const cloud = await this.readCloudAsLockShape(lock);
5642
+ const snapshot = await this.readSnapshot();
5643
+ const cloud = await this.readCloudSnapshot(snapshot);
5314
5644
  const actions = [];
5315
5645
  const errors = [];
5316
- for (const [alias, entry] of Object.entries(lock.integrations)) {
5646
+ for (const [alias, entry] of Object.entries(snapshot.integrations)) {
5317
5647
  const c = cloud.integrations[alias];
5318
5648
  if (!c) {
5319
5649
  actions.push({
@@ -5348,7 +5678,7 @@ class DependencyManager {
5348
5678
  }
5349
5679
  }
5350
5680
  for (const alias of Object.keys(cloud.integrations)) {
5351
- if (!lock.integrations[alias]) {
5681
+ if (!snapshot.integrations[alias]) {
5352
5682
  const c = cloud.integrations[alias];
5353
5683
  actions.push({
5354
5684
  type: "integration",
@@ -5358,7 +5688,7 @@ class DependencyManager {
5358
5688
  });
5359
5689
  }
5360
5690
  }
5361
- for (const [alias, entry] of Object.entries(lock.plugins)) {
5691
+ for (const [alias, entry] of Object.entries(snapshot.plugins)) {
5362
5692
  const c = cloud.plugins[alias];
5363
5693
  if (!c) {
5364
5694
  actions.push({
@@ -5401,7 +5731,7 @@ class DependencyManager {
5401
5731
  }
5402
5732
  }
5403
5733
  for (const alias of Object.keys(cloud.plugins)) {
5404
- if (!lock.plugins[alias]) {
5734
+ if (!snapshot.plugins[alias]) {
5405
5735
  const c = cloud.plugins[alias];
5406
5736
  actions.push({
5407
5737
  type: "plugin",
@@ -5454,8 +5784,8 @@ class DependencyManager {
5454
5784
  else
5455
5785
  await this.pluginResolver.removeFromCloud({ botId: this.botId, alias: a.alias });
5456
5786
  } else if (!appliedKeys.has(key)) {
5457
- const entry = a.type === "integration" ? lock.integrations[a.alias] : lock.plugins[a.alias];
5458
- await this.applyEntry(a.type, a.alias, entry, lock);
5787
+ const entry = a.type === "integration" ? snapshot.integrations[a.alias] : snapshot.plugins[a.alias];
5788
+ await this.applyEntry(a.type, a.alias, entry, snapshot);
5459
5789
  appliedKeys.add(key);
5460
5790
  }
5461
5791
  applied.push(a);
@@ -5468,7 +5798,7 @@ class DependencyManager {
5468
5798
  });
5469
5799
  }
5470
5800
  }
5471
- await this.refreshLockFromCloud();
5801
+ await this.refreshSnapshotFromCloud();
5472
5802
  return { target: this.env, applied, skipped: [], errors, dryRun: false };
5473
5803
  }
5474
5804
  async copy(opts) {
@@ -5481,85 +5811,44 @@ class DependencyManager {
5481
5811
  message: `DependencyManager constructed with env='${this.env}' but copy targets '${opts.to}'`
5482
5812
  });
5483
5813
  }
5484
- const sourceLock = new LockFile({ projectPath: this.projectPath, env: opts.from });
5485
- if (!await sourceLock.exists()) {
5814
+ const sourceBotId = opts.sourceBotId?.trim() || await this.getProjectBotId(opts.from);
5815
+ if (sourceBotId === this.botId) {
5486
5816
  throw new DependencyError({
5487
- code: "SOURCE_LOCK_MISSING",
5488
- message: `Source lock file dependencies.${opts.from}.lock.json does not exist`
5817
+ code: "SAME_SOURCE_TARGET",
5818
+ message: `${opts.from} and ${opts.to} resolve to the same Cloud bot (${sourceBotId}).`
5489
5819
  });
5490
5820
  }
5491
- const sourceData = await sourceLock.read();
5492
- const targetLockExists = await this.lockFile.exists();
5493
- const targetLock = await this.lockFile.read();
5494
- const snapshot = JSON.stringify(targetLock);
5495
- const merged = { ...targetLock, integrations: sourceData.integrations, plugins: sourceData.plugins };
5496
- await this.lockFile.write(merged);
5821
+ const sourceStore = new DependencySnapshotStore({ projectPath: this.projectPath });
5822
+ const sourceData = await sourceStore.refreshFromCloud({
5823
+ client: this.client,
5824
+ botId: sourceBotId,
5825
+ env: opts.from,
5826
+ integrationRegistry: this.integrationRegistry
5827
+ });
5828
+ const targetSnapshotExists = await this.snapshotStore.exists(this.env);
5829
+ const targetSnapshot = await this.readSnapshot();
5830
+ const originalSnapshot = JSON.stringify(targetSnapshot);
5831
+ const merged = { ...targetSnapshot, integrations: sourceData.integrations, plugins: sourceData.plugins };
5832
+ await this.writeSnapshot(merged);
5497
5833
  try {
5498
5834
  const result = await this.apply({ dryRun: opts.dryRun, yes: opts.yes });
5499
5835
  if (opts.dryRun) {
5500
- if (targetLockExists) {
5501
- await this.lockFile.write(JSON.parse(snapshot));
5836
+ if (targetSnapshotExists) {
5837
+ await this.writeSnapshot(JSON.parse(originalSnapshot));
5502
5838
  } else {
5503
- await this.lockFile.delete();
5839
+ await this.snapshotStore.delete(this.env);
5504
5840
  }
5505
5841
  }
5506
5842
  return result;
5507
5843
  } catch (err) {
5508
- if (targetLockExists) {
5509
- await this.lockFile.write(JSON.parse(snapshot)).catch(() => {});
5844
+ if (targetSnapshotExists) {
5845
+ await this.writeSnapshot(JSON.parse(originalSnapshot)).catch(() => {});
5510
5846
  } else {
5511
- await this.lockFile.delete().catch(() => {});
5847
+ await this.snapshotStore.delete(this.env).catch(() => {});
5512
5848
  }
5513
5849
  throw err;
5514
5850
  }
5515
5851
  }
5516
- async readCloudAsLockShape(previousLock) {
5517
- const { bot } = await this.client.getBot({ id: this.botId });
5518
- const previous = previousLock ?? await this.lockFile.read();
5519
- return this.cloudToLockShape(bot, previous);
5520
- }
5521
- cloudToLockShape(bot, previous) {
5522
- const integrations = {};
5523
- const usedIntegrationAliases = new Set;
5524
- for (const [cloudAlias, c] of Object.entries(bot.integrations ?? {})) {
5525
- const cloudName = typeof c.name === "string" ? c.name : undefined;
5526
- const alias = this.chooseCloudAlias({
5527
- cloudAlias,
5528
- cloudName,
5529
- previous: previous.integrations,
5530
- used: usedIntegrationAliases
5531
- });
5532
- usedIntegrationAliases.add(alias);
5533
- const entry = this.integrationResolver.toLockEntry(c);
5534
- integrations[alias] = entry;
5535
- }
5536
- const plugins = {};
5537
- const usedPluginAliases = new Set;
5538
- for (const [cloudAlias, c] of Object.entries(bot.plugins ?? {})) {
5539
- const cloudName = typeof c.name === "string" ? c.name : undefined;
5540
- const alias = this.chooseCloudAlias({
5541
- cloudAlias,
5542
- cloudName,
5543
- previous: previous.plugins,
5544
- used: usedPluginAliases
5545
- });
5546
- usedPluginAliases.add(alias);
5547
- const entry = this.pluginResolver.toLockEntry(c);
5548
- plugins[alias] = entry;
5549
- }
5550
- return { integrations, plugins };
5551
- }
5552
- chooseCloudAlias(opts) {
5553
- if (isFriendlyAlias(opts.cloudAlias) && opts.previous[opts.cloudAlias] && !opts.used.has(opts.cloudAlias)) {
5554
- return opts.cloudAlias;
5555
- }
5556
- if (opts.cloudName) {
5557
- const match = Object.entries(opts.previous).find(([alias, entry]) => !opts.used.has(alias) && entry.name === opts.cloudName);
5558
- if (match)
5559
- return match[0];
5560
- }
5561
- return generateFriendlyAlias(opts.cloudName, opts.cloudAlias, opts.used);
5562
- }
5563
5852
  }
5564
5853
  function formatMissingDependencySuggestion(opts) {
5565
5854
  if (opts.implementers.length === 0) {
@@ -5576,22 +5865,119 @@ function formatMissingDependencySuggestion(opts) {
5576
5865
  return lines.join(`
5577
5866
  `);
5578
5867
  }
5579
- function extractMissingRequiredFields(err) {
5580
- const message = err instanceof Error ? err.message : typeof err === "string" ? err : "";
5581
- if (!message.includes("required property"))
5868
+ function stripSnapshotMetadata(entry) {
5869
+ const {
5870
+ cloudAlias: _cloudAlias,
5871
+ cloudId: _cloudId,
5872
+ updatedAt: _updatedAt,
5873
+ ...semantic
5874
+ } = entry;
5875
+ return semantic;
5876
+ }
5877
+ function dependencySnapshotToState(snapshot) {
5878
+ const integrations = {};
5879
+ for (const [alias, entry] of Object.entries(snapshot.integrations)) {
5880
+ integrations[alias] = stripSnapshotMetadata(entry);
5881
+ }
5882
+ const plugins = {};
5883
+ for (const [alias, entry] of Object.entries(snapshot.plugins)) {
5884
+ plugins[alias] = stripSnapshotMetadata(entry);
5885
+ }
5886
+ return dependencyStateSchema.parse({
5887
+ version: 1,
5888
+ env: snapshot.env,
5889
+ integrations,
5890
+ plugins
5891
+ });
5892
+ }
5893
+
5894
+ // src/dependencies/index.ts
5895
+ init_types();
5896
+
5897
+ // src/dependencies/status-resolver.ts
5898
+ import { existsSync } from "fs";
5899
+ import * as path11 from "path";
5900
+
5901
+ // src/utils/ids.ts
5902
+ function getIntegrationAlias(integrationName) {
5903
+ return integrationName.replace(/\//g, "__").replace(/-/g, "_").toLowerCase();
5904
+ }
5905
+ function getPluginAlias(pluginName) {
5906
+ return pluginName.replace(/-/g, "_").toLowerCase();
5907
+ }
5908
+ function bpModuleDirName(kind, alias) {
5909
+ return kind === "integration" ? `integration_${getIntegrationAlias(alias)}` : `plugin_${alias}`;
5910
+ }
5911
+
5912
+ // src/dependencies/status-resolver.ts
5913
+ async function resolveDependencyStatuses(input) {
5914
+ const out = [];
5915
+ const integrationVerdicts = new Map;
5916
+ for (const [alias, entry] of Object.entries(input.snapshot.integrations)) {
5917
+ const installed = input.bpModulesDir ? existsSync(path11.join(input.bpModulesDir, bpModuleDirName("integration", alias))) : true;
5918
+ const spec = await tryGetSpec(input.integrationRegistry, entry.name, entry.version);
5919
+ const verdict = spec ? computeIntegrationStatus({
5920
+ installed,
5921
+ spec,
5922
+ enabled: entry.enabled,
5923
+ config: entry.config,
5924
+ ...entry.configurationType ? { configurationType: entry.configurationType } : {},
5925
+ ...entry.missingFields !== undefined ? { persistedMissingFields: entry.missingFields } : {},
5926
+ ...entry.authorizationPending !== undefined ? { authorizationPending: entry.authorizationPending } : {}
5927
+ }) : computeSnapshotOnlyStatus({
5928
+ installed,
5929
+ enabled: entry.enabled,
5930
+ ...entry.missingFields !== undefined ? { missingFields: entry.missingFields } : {},
5931
+ ...entry.authorizationPending !== undefined ? { authorizationPending: entry.authorizationPending } : {}
5932
+ });
5933
+ integrationVerdicts.set(alias, verdict);
5934
+ out.push({
5935
+ type: "integration",
5936
+ alias,
5937
+ name: entry.name,
5938
+ version: entry.version,
5939
+ enabled: entry.enabled,
5940
+ ...verdict
5941
+ });
5942
+ }
5943
+ for (const [alias, entry] of Object.entries(input.snapshot.plugins)) {
5944
+ const installed = input.bpModulesDir ? existsSync(path11.join(input.bpModulesDir, bpModuleDirName("plugin", alias))) : true;
5945
+ const spec = await tryGetSpec(input.pluginRegistry, entry.name, entry.version);
5946
+ const dependencyStatuses = mapPluginDependencyStatuses(entry.dependencies, (intAlias) => integrationVerdicts.get(intAlias));
5947
+ let verdict;
5948
+ if (spec) {
5949
+ verdict = computePluginStatus({
5950
+ installed,
5951
+ spec,
5952
+ enabled: entry.enabled,
5953
+ config: entry.config,
5954
+ dependencyStatuses,
5955
+ ...entry.missingFields !== undefined ? { persistedMissingFields: entry.missingFields } : {}
5956
+ });
5957
+ } else if (!installed) {
5958
+ verdict = { state: "not_installed" };
5959
+ } else {
5960
+ verdict = transitiveDependencyVerdict(dependencyStatuses) ?? computeSnapshotOnlyStatus({
5961
+ installed: true,
5962
+ enabled: entry.enabled,
5963
+ ...entry.missingFields !== undefined ? { missingFields: entry.missingFields } : {}
5964
+ });
5965
+ }
5966
+ out.push({ type: "plugin", alias, name: entry.name, version: entry.version, enabled: entry.enabled, ...verdict });
5967
+ }
5968
+ return out;
5969
+ }
5970
+ async function tryGetSpec(source, name, version) {
5971
+ if (!source)
5972
+ return null;
5973
+ try {
5974
+ return await source.getSpec(name, version);
5975
+ } catch {
5582
5976
  return null;
5583
- const fields = new Set;
5584
- const re = /required property ['"]([^'"]+)['"]/g;
5585
- let match;
5586
- while ((match = re.exec(message)) !== null) {
5587
- if (match[1])
5588
- fields.add(match[1]);
5589
- }
5590
- return fields.size > 0 ? [...fields] : null;
5977
+ }
5591
5978
  }
5592
5979
 
5593
5980
  // src/dependencies/index.ts
5594
- init_lock_file();
5595
5981
  init_errors2();
5596
5982
 
5597
5983
  // src/dependencies/registry/interface-registry.ts
@@ -5609,12 +5995,69 @@ class InterfaceRegistry {
5609
5995
  return all.find((i) => i.alias === alias);
5610
5996
  }
5611
5997
  }
5998
+
5999
+ // src/dependencies/index.ts
6000
+ init_snapshot_store();
6001
+
5612
6002
  // src/dependencies/migration.ts
5613
- init_lock_file();
5614
- import * as fs12 from "fs/promises";
6003
+ import * as fs11 from "fs/promises";
5615
6004
  import * as path15 from "path";
5616
6005
  import { Project as Project3, SyntaxKind as SyntaxKind3 } from "ts-morph";
5617
6006
 
6007
+ // src/dependencies/legacy-lock-file.ts
6008
+ init_types();
6009
+ init_errors2();
6010
+ import * as fs10 from "fs/promises";
6011
+ import * as path12 from "path";
6012
+
6013
+ class LegacyDependencyLockFile {
6014
+ filePath;
6015
+ env;
6016
+ constructor(opts) {
6017
+ this.env = opts.env;
6018
+ this.filePath = path12.join(opts.projectPath, `dependencies.${opts.env}.lock.json`);
6019
+ }
6020
+ async exists() {
6021
+ try {
6022
+ await fs10.access(this.filePath);
6023
+ return true;
6024
+ } catch {
6025
+ return false;
6026
+ }
6027
+ }
6028
+ async read(options) {
6029
+ let raw;
6030
+ try {
6031
+ raw = await fs10.readFile(this.filePath, "utf8");
6032
+ } catch (err) {
6033
+ if (err.code === "ENOENT") {
6034
+ return dependencyStateSchema.parse({ version: 1, env: this.env });
6035
+ }
6036
+ throw err;
6037
+ }
6038
+ try {
6039
+ return dependencyStateSchema.parse(JSON.parse(raw));
6040
+ } catch (err) {
6041
+ if (options?.tolerant) {
6042
+ return dependencyStateSchema.parse({ version: 1, env: this.env });
6043
+ }
6044
+ throw new DependencyError({
6045
+ code: "INVALID_CONFIG",
6046
+ message: `Legacy dependency lock at ${this.filePath} failed schema validation`,
6047
+ details: { issues: err.issues ?? String(err) }
6048
+ });
6049
+ }
6050
+ }
6051
+ async delete() {
6052
+ try {
6053
+ await fs10.unlink(this.filePath);
6054
+ } catch (err) {
6055
+ if (err.code !== "ENOENT")
6056
+ throw err;
6057
+ }
6058
+ }
6059
+ }
6060
+
5618
6061
  // src/agent-project/config-writer.ts
5619
6062
  init_utils();
5620
6063
  init_src();
@@ -5929,181 +6372,259 @@ class ConfigWriter {
5929
6372
  }
5930
6373
 
5931
6374
  // src/dependencies/migration.ts
5932
- init_errors2();
5933
6375
  init_agent_project();
5934
- async function migrateFromConfig(opts) {
5935
- const result = {
5936
- migrated: [],
5937
- warnings: [],
5938
- skipped: []
5939
- };
5940
- const project = await AgentProject.load(opts.projectPath);
5941
- const info = project.agentInfo;
5942
- const declaredAliasesForConflictCheck = await readAliasesFromConfig(opts.projectPath);
5943
- const agentConfigHasDependencies = Object.keys(declaredAliasesForConflictCheck.integrations).length > 0 || Object.keys(declaredAliasesForConflictCheck.plugins).length > 0;
5944
- const envs = ["dev", "prod"];
5945
- if (!info) {
5946
- result.warnings.push({
5947
- code: "CLOUD_FETCH_PARTIAL",
5948
- message: "No agent.json found; cannot fetch cloud state for migration."
6376
+ init_snapshot_store();
6377
+ class DependencyMigrationManager {
6378
+ projectPath;
6379
+ client;
6380
+ snapshotStore;
6381
+ integrationRegistry;
6382
+ pluginRegistry;
6383
+ integrationResolver;
6384
+ pluginResolver;
6385
+ constructor(opts) {
6386
+ this.projectPath = opts.projectPath;
6387
+ this.client = opts.client;
6388
+ this.snapshotStore = new DependencySnapshotStore({ projectPath: opts.projectPath });
6389
+ this.integrationRegistry = new IntegrationRegistry;
6390
+ this.pluginRegistry = new PluginRegistry;
6391
+ this.integrationResolver = opts.integrationResolver ?? new IntegrationResolver({ registry: this.integrationRegistry, client: this.client });
6392
+ this.pluginResolver = opts.pluginResolver ?? new PluginResolver({
6393
+ registry: this.pluginRegistry,
6394
+ integrationRegistry: this.integrationRegistry,
6395
+ client: this.client
5949
6396
  });
5950
- for (const env of envs) {
5951
- result.skipped.push({ env, reason: "no agent.json" });
6397
+ }
6398
+ async run() {
6399
+ const result = {
6400
+ migrated: [],
6401
+ warnings: [],
6402
+ skipped: [],
6403
+ legacySources: [],
6404
+ snapshotWrites: [],
6405
+ cloudWrites: []
6406
+ };
6407
+ if (await this.snapshotStore.hasMigrationMarker()) {
6408
+ for (const env of ["dev", "prod"]) {
6409
+ await this.deleteLegacyLock(env, result);
6410
+ result.skipped.push({ env, reason: "migration already completed" });
6411
+ }
6412
+ return result;
5952
6413
  }
5953
- } else {
5954
- for (const env of envs) {
5955
- const lockFile = new LockFile({ projectPath: opts.projectPath, env });
5956
- if (await lockFile.exists()) {
5957
- if (agentConfigHasDependencies) {
5958
- throw new DependencyError({
5959
- code: "MIGRATION_CONFLICT",
5960
- 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.`
5961
- });
5962
- }
5963
- result.skipped.push({ env, reason: "lock file already exists" });
5964
- continue;
6414
+ const project = await AgentProject.load(this.projectPath);
6415
+ const info = project.agentInfo;
6416
+ const agentConfigDependencies = await readDependenciesFromConfig(this.projectPath);
6417
+ const hasAgentConfigDependencies = hasDependencies(agentConfigDependencies);
6418
+ if (hasAgentConfigDependencies) {
6419
+ result.legacySources?.push("agentConfig");
6420
+ }
6421
+ if (!info) {
6422
+ result.warnings.push({
6423
+ code: "CLOUD_FETCH_PARTIAL",
6424
+ message: "No agent.json found; cannot migrate dependencies to Cloud-backed snapshots."
6425
+ });
6426
+ for (const env of ["dev", "prod"]) {
6427
+ result.skipped.push({ env, reason: "no agent.json" });
5965
6428
  }
6429
+ return result;
6430
+ }
6431
+ const markerSources = new Set;
6432
+ for (const env of ["dev", "prod"]) {
5966
6433
  const botId = env === "dev" ? info.devId ?? info.botId : info.botId;
5967
- if (env === "prod" && !botId) {
6434
+ if (!botId) {
5968
6435
  result.warnings.push({
5969
6436
  code: "NO_PROD_BOT",
5970
- message: "No prod bot configured in agent.json. Only dependencies.dev.lock.json was generated. Use `adk deploy` to create a prod bot."
6437
+ message: "No prod bot configured in agent.json. Prod dependency snapshot was not written."
5971
6438
  });
5972
6439
  result.skipped.push({ env, reason: "no prod bot configured" });
5973
6440
  continue;
5974
6441
  }
5975
- let bot;
5976
- try {
5977
- const r = await opts.client.getBot({ id: botId });
5978
- bot = r.bot;
5979
- } catch (err) {
5980
- result.warnings.push({
5981
- code: "CLOUD_FETCH_PARTIAL",
5982
- message: `Could not fetch cloud state for ${env}: ${err.message}`
5983
- });
5984
- result.skipped.push({ env, reason: "cloud fetch failed" });
6442
+ const legacy = await this.readLegacyState(env, agentConfigDependencies);
6443
+ if (legacy?.source === "lock" && !result.legacySources?.includes("lock")) {
6444
+ result.legacySources?.push("lock");
6445
+ }
6446
+ let bot = await this.fetchBot(botId, env, result);
6447
+ if (!bot)
5985
6448
  continue;
6449
+ if (!cloudHasDependencies(bot) && legacy) {
6450
+ await this.importLegacyToCloud({ botId, legacy: legacy.data });
6451
+ result.cloudWrites?.push(env);
6452
+ markerSources.add(legacy.source);
6453
+ bot = await this.fetchBot(botId, env, result);
6454
+ if (!bot)
6455
+ continue;
6456
+ } else {
6457
+ markerSources.add("cloud");
5986
6458
  }
5987
- const lockData = {
5988
- version: 1,
6459
+ await this.snapshotStore.write(dependencySnapshotFromBot({
6460
+ bot,
6461
+ botId,
5989
6462
  env,
5990
- integrations: {},
5991
- plugins: {}
5992
- };
5993
- const declaredAliases = declaredAliasesForConflictCheck;
5994
- const usedIntegrationAliases = new Set(Object.keys(declaredAliases.integrations));
5995
- for (const [cloudAlias, cloud] of Object.entries(bot.integrations ?? {})) {
5996
- const declaredAlias = Object.entries(declaredAliases.integrations).find(([, decl]) => decl.name === cloud.name)?.[0];
5997
- const alias = declaredAlias ?? generateFriendlyAlias(cloud.name, cloudAlias, usedIntegrationAliases);
5998
- usedIntegrationAliases.add(alias);
5999
- lockData.integrations[alias] = {
6000
- name: cloud.name,
6001
- version: cloud.version,
6002
- enabled: cloud.enabled ?? false,
6003
- config: cloud.configuration ?? {}
6004
- };
6005
- }
6006
- const usedPluginAliases = new Set(Object.keys(declaredAliases.plugins));
6007
- for (const [cloudAlias, cloud] of Object.entries(bot.plugins ?? {})) {
6008
- const declaredAlias = Object.entries(declaredAliases.plugins).find(([, decl]) => decl.name === cloud.name)?.[0];
6009
- const alias = declaredAlias ?? generateFriendlyAlias(cloud.name, cloudAlias, usedPluginAliases);
6010
- usedPluginAliases.add(alias);
6011
- lockData.plugins[alias] = {
6012
- name: cloud.name,
6013
- version: cloud.version,
6014
- enabled: cloud.enabled ?? true,
6015
- config: cloud.configuration ?? {},
6016
- dependencies: Object.fromEntries(Object.entries(cloud.interfaces ?? {}).map(([k, v]) => [
6017
- k,
6018
- { integrationAlias: v.integrationAlias }
6019
- ]))
6020
- };
6021
- }
6022
- await lockFile.write(lockData);
6463
+ fetchedAt: new Date,
6464
+ previous: await this.snapshotStore.read(env, { tolerant: true })
6465
+ }));
6466
+ result.snapshotWrites?.push(env);
6023
6467
  result.migrated.push(env);
6468
+ await this.deleteLegacyLock(env, result);
6469
+ }
6470
+ if (hasAgentConfigDependencies && result.migrated.length > 0) {
6471
+ const writer = new ConfigWriter(this.projectPath);
6472
+ await writer.removeDependenciesField();
6473
+ }
6474
+ if (result.migrated.length > 0) {
6475
+ await this.snapshotStore.writeMigrationMarker({
6476
+ version: 1,
6477
+ migratedAt: new Date().toISOString(),
6478
+ sources: [...markerSources]
6479
+ });
6480
+ result.warnings.push({
6481
+ code: "MIGRATED_DEPENDENCIES",
6482
+ message: `Migrated dependencies to .adk snapshots for ${result.migrated.join(", ")}. Cloud is now the source of truth.`
6483
+ });
6024
6484
  }
6485
+ return result;
6025
6486
  }
6026
- if (result.migrated.length > 0) {
6027
- const writer = new ConfigWriter(opts.projectPath);
6028
- await writer.removeDependenciesField();
6029
- result.warnings.push({
6030
- code: "MIGRATED_DEPENDENCIES",
6031
- message: `Migrated dependencies to ${result.migrated.map((e) => `dependencies.${e}.lock.json`).join(", ")}. Review the diff and commit.`
6032
- });
6487
+ async deleteLegacyLock(env, result) {
6488
+ try {
6489
+ await new LegacyDependencyLockFile({ projectPath: this.projectPath, env }).delete();
6490
+ } catch (err) {
6491
+ result.warnings.push({
6492
+ code: "LEGACY_LOCK_DELETE_FAILED",
6493
+ message: `Migrated ${env} dependencies, but could not delete dependencies.${env}.lock.json: ${err.message}`
6494
+ });
6495
+ }
6496
+ }
6497
+ async readLegacyState(env, agentConfigDependencies) {
6498
+ const legacyLock = new LegacyDependencyLockFile({ projectPath: this.projectPath, env });
6499
+ if (await legacyLock.exists()) {
6500
+ return { source: "lock", data: await legacyLock.read() };
6501
+ }
6502
+ if (hasDependencies(agentConfigDependencies)) {
6503
+ return { source: "agentConfig", data: { ...agentConfigDependencies, env } };
6504
+ }
6505
+ return null;
6506
+ }
6507
+ async fetchBot(botId, env, result) {
6508
+ try {
6509
+ const { bot } = await this.client.getBot({ id: botId });
6510
+ return bot;
6511
+ } catch (err) {
6512
+ result.warnings.push({
6513
+ code: "CLOUD_FETCH_PARTIAL",
6514
+ message: `Could not fetch cloud state for ${env}: ${err.message}`
6515
+ });
6516
+ result.skipped.push({ env, reason: "cloud fetch failed" });
6517
+ return null;
6518
+ }
6519
+ }
6520
+ async importLegacyToCloud(opts) {
6521
+ for (const [alias, entry] of Object.entries(opts.legacy.integrations)) {
6522
+ await this.integrationResolver.applyToCloud({ botId: opts.botId, alias, entry });
6523
+ }
6524
+ for (const [alias, entry] of Object.entries(opts.legacy.plugins)) {
6525
+ await this.pluginResolver.applyToCloud({ botId: opts.botId, alias, entry, state: opts.legacy });
6526
+ }
6033
6527
  }
6034
- return result;
6035
6528
  }
6036
- async function readAliasesFromConfig(projectPath) {
6529
+ async function migrateFromConfig(opts) {
6530
+ return new DependencyMigrationManager(opts).run();
6531
+ }
6532
+ async function readDependenciesFromConfig(projectPath) {
6037
6533
  const configPath = path15.join(projectPath, "agent.config.ts");
6534
+ const empty = { version: 1, env: "dev", integrations: {}, plugins: {} };
6038
6535
  try {
6039
- await fs12.access(configPath);
6536
+ await fs11.access(configPath);
6040
6537
  } catch {
6041
- return { integrations: {}, plugins: {} };
6538
+ return empty;
6042
6539
  }
6043
- const integrations = {};
6044
- const plugins = {};
6045
6540
  try {
6046
6541
  const project = new Project3({ useInMemoryFileSystem: false });
6047
6542
  const sourceFile = project.addSourceFileAtPath(configPath);
6048
6543
  const callExpr = sourceFile.getDescendantsOfKind(SyntaxKind3.CallExpression).find((c) => c.getExpression().getText() === "defineConfig");
6049
6544
  const obj = callExpr?.getArguments()[0]?.asKind(SyntaxKind3.ObjectLiteralExpression);
6050
6545
  if (!obj)
6051
- return { integrations, plugins };
6546
+ return empty;
6052
6547
  const depsProp = obj.getProperty("dependencies");
6053
- if (!depsProp || !depsProp.isKind(SyntaxKind3.PropertyAssignment))
6054
- return { integrations, plugins };
6548
+ if (!depsProp?.isKind(SyntaxKind3.PropertyAssignment))
6549
+ return empty;
6055
6550
  const depsObj = depsProp.getInitializer()?.asKind(SyntaxKind3.ObjectLiteralExpression);
6056
6551
  if (!depsObj)
6057
- return { integrations, plugins };
6058
- for (const field of ["integrations", "plugins"]) {
6059
- const target = field === "integrations" ? integrations : plugins;
6060
- const innerProp = depsObj.getProperty(field);
6061
- if (!innerProp || !innerProp.isKind(SyntaxKind3.PropertyAssignment))
6062
- continue;
6063
- const inner = innerProp.getInitializer()?.asKind(SyntaxKind3.ObjectLiteralExpression);
6064
- if (!inner)
6065
- continue;
6066
- for (const aliasProp of inner.getProperties()) {
6067
- if (!aliasProp.isKind(SyntaxKind3.PropertyAssignment))
6068
- continue;
6069
- const alias = aliasProp.getName().replace(/['"]/g, "");
6070
- const initializer = aliasProp.getInitializer();
6071
- let nameVersion = "";
6072
- if (initializer?.isKind(SyntaxKind3.StringLiteral)) {
6073
- nameVersion = initializer.getLiteralText();
6074
- } else if (initializer?.isKind(SyntaxKind3.ObjectLiteralExpression)) {
6075
- const versionProp = initializer.getProperty("version");
6076
- if (versionProp?.isKind(SyntaxKind3.PropertyAssignment)) {
6077
- const v = versionProp.getInitializer();
6078
- if (v?.isKind(SyntaxKind3.StringLiteral))
6079
- nameVersion = v.getLiteralText();
6080
- }
6081
- }
6082
- const at = nameVersion.indexOf("@");
6083
- if (at < 0)
6084
- continue;
6085
- const name = nameVersion.slice(0, at);
6086
- const version = nameVersion.slice(at + 1);
6087
- target[alias] = { name, version };
6088
- }
6552
+ return empty;
6553
+ readDependencyField(depsObj, "integrations", empty);
6554
+ readDependencyField(depsObj, "plugins", empty);
6555
+ } catch {
6556
+ return empty;
6557
+ }
6558
+ return empty;
6559
+ }
6560
+ function readDependencyField(depsObj, field, data) {
6561
+ const innerProp = depsObj.getProperty(field);
6562
+ if (!innerProp?.isKind(SyntaxKind3.PropertyAssignment))
6563
+ return;
6564
+ const inner = innerProp.getInitializer()?.asKind(SyntaxKind3.ObjectLiteralExpression);
6565
+ if (!inner)
6566
+ return;
6567
+ for (const aliasProp of inner.getProperties()) {
6568
+ if (!aliasProp.isKind(SyntaxKind3.PropertyAssignment))
6569
+ continue;
6570
+ const alias = aliasProp.getName().replace(/['"]/g, "");
6571
+ const version = readVersionLiteral(aliasProp.getInitializer());
6572
+ if (!version)
6573
+ continue;
6574
+ const at = version.indexOf("@");
6575
+ if (at < 0)
6576
+ continue;
6577
+ const name = version.slice(0, at);
6578
+ const semver3 = version.slice(at + 1);
6579
+ if (field === "integrations") {
6580
+ data.integrations[alias] = { name, version: semver3, enabled: true, config: {} };
6581
+ } else {
6582
+ data.plugins[alias] = { name, version: semver3, enabled: true, config: {}, dependencies: {} };
6089
6583
  }
6090
- } catch {}
6091
- return { integrations, plugins };
6584
+ }
6585
+ }
6586
+ function readVersionLiteral(node) {
6587
+ if (node?.isKind(SyntaxKind3.StringLiteral)) {
6588
+ return node.getLiteralText();
6589
+ }
6590
+ if (node?.isKind(SyntaxKind3.ObjectLiteralExpression)) {
6591
+ const versionProp = node.getProperty("version");
6592
+ if (versionProp?.isKind(SyntaxKind3.PropertyAssignment)) {
6593
+ const value = versionProp.getInitializer();
6594
+ if (value?.isKind(SyntaxKind3.StringLiteral))
6595
+ return value.getLiteralText();
6596
+ }
6597
+ }
6598
+ return null;
6599
+ }
6600
+ function hasDependencies(data) {
6601
+ return Object.keys(data.integrations).length > 0 || Object.keys(data.plugins).length > 0;
6602
+ }
6603
+ function cloudHasDependencies(bot) {
6604
+ return Object.keys(bot.integrations ?? {}).length > 0 || Object.keys(bot.plugins ?? {}).length > 0;
6092
6605
  }
6093
6606
  export {
6094
6607
  sortKeysDeep,
6608
+ resolveDependencyStatuses,
6095
6609
  migrateFromConfig,
6096
6610
  jsonEqual,
6611
+ isCallable,
6612
+ emptyDependencySnapshot,
6613
+ dependencyStateSchema,
6614
+ dependencySnapshotFromBot,
6615
+ computePluginStatus,
6616
+ computeIntegrationStatus,
6097
6617
  PluginResolver,
6098
6618
  PluginRegistry,
6099
- LockFile,
6100
6619
  InterfaceRegistry,
6101
6620
  IntegrationResolver,
6102
6621
  IntegrationRegistry,
6622
+ DependencySnapshotStore,
6623
+ DependencyMigrationManager,
6103
6624
  DependencyManager,
6104
6625
  DependencyError,
6105
6626
  DEPENDENCY_WARNING_CODES,
6106
6627
  DEPENDENCY_ERROR_CODES
6107
6628
  };
6108
6629
 
6109
- //# debugId=955ACBEC7AB99F3F64756E2164756E21
6630
+ //# debugId=63074253A1710FE164756E2164756E21