@botpress/adk 1.19.0-beta.12 → 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 (109) 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 +41 -19
  8. package/dist/agent0/index.js.map +7 -7
  9. package/dist/agent0/runtime/client.d.ts +2 -0
  10. package/dist/agent0/runtime/client.d.ts.map +1 -1
  11. package/dist/agent0/runtime/engine.d.ts +2 -1
  12. package/dist/agent0/runtime/engine.d.ts.map +1 -1
  13. package/dist/agent0/runtime/process.d.ts +1 -0
  14. package/dist/agent0/runtime/process.d.ts.map +1 -1
  15. package/dist/assets/manager.d.ts +3 -0
  16. package/dist/assets/manager.d.ts.map +1 -1
  17. package/dist/auth/credentials.d.ts +1 -1
  18. package/dist/bot-generator/generator.d.ts +22 -0
  19. package/dist/bot-generator/generator.d.ts.map +1 -1
  20. package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
  21. package/dist/commands/bp-dev-stderr.d.ts +9 -0
  22. package/dist/commands/bp-dev-stderr.d.ts.map +1 -1
  23. package/dist/commands/index.d.ts +1 -0
  24. package/dist/commands/index.d.ts.map +1 -1
  25. package/dist/dependencies/catalog/catalog-service.d.ts +53 -0
  26. package/dist/dependencies/catalog/catalog-service.d.ts.map +1 -0
  27. package/dist/dependencies/catalog/client-factory.d.ts +33 -0
  28. package/dist/dependencies/catalog/client-factory.d.ts.map +1 -0
  29. package/dist/dependencies/catalog/integration-source.d.ts +34 -0
  30. package/dist/dependencies/catalog/integration-source.d.ts.map +1 -0
  31. package/dist/dependencies/catalog/interface-source.d.ts +23 -0
  32. package/dist/dependencies/catalog/interface-source.d.ts.map +1 -0
  33. package/dist/dependencies/catalog/plugin-source.d.ts +49 -0
  34. package/dist/dependencies/catalog/plugin-source.d.ts.map +1 -0
  35. package/dist/dependencies/catalog/resolution-cache.d.ts +76 -0
  36. package/dist/dependencies/catalog/resolution-cache.d.ts.map +1 -0
  37. package/dist/dependencies/dependency-manager.d.ts +31 -16
  38. package/dist/dependencies/dependency-manager.d.ts.map +1 -1
  39. package/dist/dependencies/errors.d.ts +2 -2
  40. package/dist/dependencies/errors.d.ts.map +1 -1
  41. package/dist/dependencies/index.d.ts +5 -4
  42. package/dist/dependencies/index.d.ts.map +1 -1
  43. package/dist/dependencies/index.js +2052 -1655
  44. package/dist/dependencies/index.js.map +36 -29
  45. package/dist/dependencies/legacy-lock-file.d.ts +15 -0
  46. package/dist/dependencies/legacy-lock-file.d.ts.map +1 -0
  47. package/dist/dependencies/migration.d.ts +19 -0
  48. package/dist/dependencies/migration.d.ts.map +1 -1
  49. package/dist/dependencies/resolvers/integration-resolver.d.ts +4 -3
  50. package/dist/dependencies/resolvers/integration-resolver.d.ts.map +1 -1
  51. package/dist/dependencies/resolvers/plugin-resolver.d.ts +4 -4
  52. package/dist/dependencies/resolvers/plugin-resolver.d.ts.map +1 -1
  53. package/dist/dependencies/snapshot-store.d.ts +59 -0
  54. package/dist/dependencies/snapshot-store.d.ts.map +1 -0
  55. package/dist/dependencies/status-resolver.d.ts +36 -0
  56. package/dist/dependencies/status-resolver.d.ts.map +1 -0
  57. package/dist/dependencies/status.d.ts +214 -0
  58. package/dist/dependencies/status.d.ts.map +1 -0
  59. package/dist/dependencies/types.d.ts +379 -29
  60. package/dist/dependencies/types.d.ts.map +1 -1
  61. package/dist/file-watcher/watcher.d.ts.map +1 -1
  62. package/dist/index.d.ts +3 -3
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +2730 -2050
  65. package/dist/index.js.map +49 -42
  66. package/dist/integrations/config-utils.d.ts +11 -7
  67. package/dist/integrations/config-utils.d.ts.map +1 -1
  68. package/dist/integrations/hub-cache.d.ts +0 -58
  69. package/dist/integrations/hub-cache.d.ts.map +1 -1
  70. package/dist/integrations/index.d.ts +1 -3
  71. package/dist/integrations/index.d.ts.map +1 -1
  72. package/dist/integrations/manager.d.ts +19 -53
  73. package/dist/integrations/manager.d.ts.map +1 -1
  74. package/dist/interfaces/enhanced-cache.d.ts +7 -7
  75. package/dist/interfaces/enhanced-cache.d.ts.map +1 -1
  76. package/dist/interfaces/manager.d.ts +11 -17
  77. package/dist/interfaces/manager.d.ts.map +1 -1
  78. package/dist/knowledge/manager.d.ts +3 -0
  79. package/dist/knowledge/manager.d.ts.map +1 -1
  80. package/dist/plugins/index.d.ts +0 -1
  81. package/dist/plugins/index.d.ts.map +1 -1
  82. package/dist/plugins/manager.d.ts +16 -53
  83. package/dist/plugins/manager.d.ts.map +1 -1
  84. package/dist/preflight/checker.d.ts +6 -1
  85. package/dist/preflight/checker.d.ts.map +1 -1
  86. package/dist/preflight/dependency-gate.d.ts +36 -0
  87. package/dist/preflight/dependency-gate.d.ts.map +1 -0
  88. package/dist/preflight/index.d.ts +1 -0
  89. package/dist/preflight/index.d.ts.map +1 -1
  90. package/dist/preflight/types.d.ts +10 -0
  91. package/dist/preflight/types.d.ts.map +1 -1
  92. package/dist/runner/script-runner.d.ts.map +1 -1
  93. package/dist/tables/table-manager.d.ts +3 -0
  94. package/dist/tables/table-manager.d.ts.map +1 -1
  95. package/dist/templates/botpress-desk/evals/index.eval.ts +1 -1
  96. package/dist/templates/template.config.json +3 -3
  97. package/dist/utils/ids.d.ts +10 -0
  98. package/dist/utils/ids.d.ts.map +1 -1
  99. package/dist/workspace/workspace-cache.d.ts +2 -1
  100. package/dist/workspace/workspace-cache.d.ts.map +1 -1
  101. package/package.json +2 -2
  102. package/dist/agent-project/lock-to-dependencies.d.ts +0 -11
  103. package/dist/agent-project/lock-to-dependencies.d.ts.map +0 -1
  104. package/dist/dependencies/lock-file.d.ts +0 -15
  105. package/dist/dependencies/lock-file.d.ts.map +0 -1
  106. package/dist/integrations/enhanced-cache.d.ts +0 -53
  107. package/dist/integrations/enhanced-cache.d.ts.map +0 -1
  108. package/dist/plugins/enhanced-cache.d.ts +0 -53
  109. 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();
@@ -944,7 +1309,7 @@ class CredentialsManager {
944
1309
  await this.writeCredentials(store);
945
1310
  }
946
1311
  async getActiveCredentials() {
947
- const profileName = this.profileOverride || process.env.ADK_PROFILE;
1312
+ const profileName = this.profileOverride;
948
1313
  const credentials = await this.getCredentials(profileName);
949
1314
  if (!credentials) {
950
1315
  const displayName = profileName || "default";
@@ -976,7 +1341,7 @@ class CredentialsManager {
976
1341
  });
977
1342
  const agentApiUrl = agentInfo.apiUrl;
978
1343
  let baseCredentials;
979
- const hasExplicitProfile = !!(this.profileOverride || process.env.ADK_PROFILE);
1344
+ const hasExplicitProfile = !!this.profileOverride;
980
1345
  if (hasExplicitProfile) {
981
1346
  baseCredentials = await this.getActiveCredentials();
982
1347
  } else {
@@ -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,89 +2003,23 @@ function normalize(value) {
1765
2003
  }
1766
2004
  var init_search_ranking = () => {};
1767
2005
 
1768
- // src/integrations/manager.ts
1769
- class IntegrationManager {
1770
- cache;
1771
- options;
1772
- client;
1773
- constructor(options = {}) {
1774
- this.options = options;
1775
- this.cache = new EnhancedIntegrationCache(options.noCache || false);
1776
- }
1777
- async getClient() {
1778
- if (!this.client) {
1779
- this.client = await getProjectClient({
1780
- project: this.options.project,
1781
- credentials: this.options.credentials,
1782
- apiUrl: this.options.apiUrl,
1783
- workspaceId: this.options.workspaceId,
1784
- headers: {
1785
- "x-multiple-integrations": "true"
1786
- }
1787
- });
1788
- }
1789
- return this.client;
1790
- }
1791
- async loadIntegrations(dependencies) {
1792
- const errors = [];
1793
- const warnings = [];
1794
- const parseResult = IntegrationParser.parseIntegrations(dependencies);
1795
- const integrations = parseResult.integrations;
1796
- errors.push(...parseResult.errors);
1797
- const duplicateWarnings = IntegrationParser.checkDuplicates(integrations);
1798
- warnings.push(...duplicateWarnings);
1799
- const fetchPromises = integrations.map(async (integration) => {
1800
- try {
1801
- const definition = await this.fetchIntegration(integration.ref);
1802
- integration.definition = definition;
1803
- const validation = this.validateIntegration(integration);
1804
- integration.validationResult = validation;
1805
- if (!validation.valid) {
1806
- validation.errors.forEach(() => {
1807
- errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName));
1808
- });
1809
- }
1810
- if (validation.warnings.length > 0) {
1811
- validation.warnings.forEach((warn) => {
1812
- warnings.push(ValidationErrors.warning(warn, "agent.config.ts"));
1813
- });
1814
- }
1815
- } catch (error) {
1816
- if (error instanceof Error && error.message.includes("version")) {
1817
- errors.push(ValidationErrors.integrationVersionError(integration.alias, error.message));
1818
- } else {
1819
- const errorMessage = error instanceof Error ? error.message : undefined;
1820
- errors.push(ValidationErrors.unknownIntegration(integration.alias, integration.ref.fullName, errorMessage));
1821
- }
1822
- }
1823
- });
1824
- await Promise.all(fetchPromises);
1825
- const hasChannels = integrations.some((i) => i.definition?.channels && Object.keys(i.definition.channels).length > 0);
1826
- if (!hasChannels && integrations.length > 0) {
1827
- 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"));
1828
- }
1829
- return { integrations, errors, warnings };
1830
- }
1831
- async fetchIntegration(ref) {
1832
- const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace);
1833
- if (cachedResolution) {
1834
- const cachedDefinition = await this.cache.getDefinition(cachedResolution.integrationId, cachedResolution.updatedAt);
1835
- if (cachedDefinition) {
1836
- return cachedDefinition;
1837
- }
1838
- }
1839
- 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();
1840
2015
  const integration = await this._findPrivateOrPublicIntegration(client, ref);
1841
2016
  if (!integration) {
1842
2017
  throw await this._buildIntegrationNotFoundError(client, ref);
1843
2018
  }
1844
- await this.cache.setResolution(ref.name, ref.version, ref.workspace, integration.id, integration.updatedAt);
1845
- const definition = integration;
1846
- await this.cache.setDefinition(integration.id, integration.updatedAt, definition);
1847
- return definition;
2019
+ return { id: integration.id, updatedAt: integration.updatedAt, definition: integration };
1848
2020
  }
1849
- async searchIntegrations(query, limit = 20) {
1850
- const client = await this.getClient();
2021
+ async search(query, limit = 20) {
2022
+ const client = await this.clientFactory.getClient();
1851
2023
  const results = new Map;
1852
2024
  const scanLimit = Math.max(limit * 5, 50);
1853
2025
  for await (const integration of client.list.publicIntegrations({
@@ -1872,7 +2044,7 @@ class IntegrationManager {
1872
2044
  return getSortedCatalogSearchResults(results, limit);
1873
2045
  }
1874
2046
  async findImplementersOfInterface(interfaceName, limit = 10) {
1875
- const client = await this.getClient();
2047
+ const client = await this.clientFactory.getClient();
1876
2048
  const seen = new Map;
1877
2049
  for await (const integration of client.list.publicIntegrations({
1878
2050
  interfaceName,
@@ -1888,8 +2060,8 @@ class IntegrationManager {
1888
2060
  }
1889
2061
  return [...seen.values()];
1890
2062
  }
1891
- async listIntegrationVersions(name) {
1892
- const client = await this.getClient();
2063
+ async listVersions(name) {
2064
+ const client = await this.clientFactory.getClient();
1893
2065
  const versions = new Set;
1894
2066
  for await (const integration of client.list.publicIntegrations({
1895
2067
  name,
@@ -1953,7 +2125,7 @@ class IntegrationManager {
1953
2125
  const scope = ref.workspace ? `workspace "${ref.workspace}"` : "the official Botpress hub";
1954
2126
  return new AdkError({
1955
2127
  code: "INTEGRATION_NOT_FOUND",
1956
- 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.`,
1957
2129
  expected: true
1958
2130
  });
1959
2131
  }
@@ -1969,10 +2141,10 @@ class IntegrationManager {
1969
2141
  let workspaceId;
1970
2142
  try {
1971
2143
  const credentials = await resolveWorkspaceCredentials({
1972
- project: this.options.project,
1973
- credentials: this.options.credentials,
1974
- apiUrl: this.options.apiUrl,
1975
- 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
1976
2148
  });
1977
2149
  workspaceId = credentials.workspaceId;
1978
2150
  if (workspaceId) {
@@ -2000,6 +2172,96 @@ class IntegrationManager {
2000
2172
  expected: true
2001
2173
  });
2002
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
+ }
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();
2264
+ }
2003
2265
  validateIntegration(integration) {
2004
2266
  const errors = [];
2005
2267
  const warnings = [];
@@ -2029,40 +2291,13 @@ class IntegrationManager {
2029
2291
  missingChannels: !hasChannels
2030
2292
  };
2031
2293
  }
2032
- async getCacheStats() {
2033
- const stats = await this.cache.getStats();
2034
- return {
2035
- count: stats.resolutions.count + stats.definitions.count,
2036
- sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
2037
- };
2038
- }
2039
- async clearCache() {
2040
- await this.cache.clear();
2041
- }
2042
- }
2043
- function toHubCacheEntry(integration) {
2044
- return {
2045
- id: integration.id,
2046
- name: integration.name,
2047
- version: integration.version,
2048
- updatedAt: integration.updatedAt,
2049
- createdAt: integration.createdAt,
2050
- title: integration.title,
2051
- description: integration.description,
2052
- iconUrl: integration.iconUrl,
2053
- public: integration.public,
2054
- visibility: integration.visibility,
2055
- ownerWorkspace: integration.ownerWorkspace ? { id: integration.ownerWorkspace.id, name: integration.ownerWorkspace.name } : undefined,
2056
- verificationStatus: integration.verificationStatus
2057
- };
2058
2294
  }
2059
2295
  var init_manager = __esm(() => {
2060
- init_src();
2061
- init_auth();
2062
- init_enhanced_cache();
2063
2296
  init_dependencies_parser();
2064
2297
  init_validation_errors();
2065
- init_search_ranking();
2298
+ init_client_factory();
2299
+ init_catalog_service();
2300
+ init_integration_source();
2066
2301
  });
2067
2302
 
2068
2303
  // src/assets/types.ts
@@ -2072,8 +2307,8 @@ var init_types3 = () => {};
2072
2307
  var defaultAdkFolder = ".adk";
2073
2308
 
2074
2309
  // src/assets/cache.ts
2075
- import fs7 from "fs/promises";
2076
- import path7 from "path";
2310
+ import fs5 from "fs/promises";
2311
+ import path5 from "path";
2077
2312
 
2078
2313
  class AssetsCacheManager {
2079
2314
  projectPath;
@@ -2081,14 +2316,14 @@ class AssetsCacheManager {
2081
2316
  cache = null;
2082
2317
  constructor(projectPath) {
2083
2318
  this.projectPath = projectPath;
2084
- this.cachePath = path7.join(projectPath, defaultAdkFolder, "assets-cache.json");
2319
+ this.cachePath = path5.join(projectPath, defaultAdkFolder, "assets-cache.json");
2085
2320
  }
2086
2321
  async load() {
2087
2322
  if (this.cache) {
2088
2323
  return this.cache;
2089
2324
  }
2090
2325
  try {
2091
- const content = await fs7.readFile(this.cachePath, "utf-8");
2326
+ const content = await fs5.readFile(this.cachePath, "utf-8");
2092
2327
  this.cache = JSON.parse(content);
2093
2328
  return this.cache;
2094
2329
  } catch {
@@ -2103,9 +2338,9 @@ class AssetsCacheManager {
2103
2338
  if (!this.cache) {
2104
2339
  return;
2105
2340
  }
2106
- const cacheDir = path7.dirname(this.cachePath);
2107
- await fs7.mkdir(cacheDir, { recursive: true });
2108
- 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");
2109
2344
  }
2110
2345
  async getEntry(assetPath) {
2111
2346
  const cache = await this.load();
@@ -2148,8 +2383,8 @@ class AssetsCacheManager {
2148
2383
  var init_cache = () => {};
2149
2384
 
2150
2385
  // src/assets/manager.ts
2151
- import fs8 from "fs/promises";
2152
- import path8 from "path";
2386
+ import fs6 from "fs/promises";
2387
+ import path6 from "path";
2153
2388
  import crypto from "crypto";
2154
2389
 
2155
2390
  class AssetsManager {
@@ -2157,11 +2392,13 @@ class AssetsManager {
2157
2392
  assetsPath;
2158
2393
  client;
2159
2394
  botId;
2395
+ credentials;
2160
2396
  cacheManager;
2161
2397
  constructor(options) {
2162
2398
  this.projectPath = options.projectPath;
2163
- this.assetsPath = path8.join(this.projectPath, "assets");
2399
+ this.assetsPath = path6.join(this.projectPath, "assets");
2164
2400
  this.botId = options.botId;
2401
+ this.credentials = options.credentials;
2165
2402
  this.cacheManager = new AssetsCacheManager(this.projectPath);
2166
2403
  }
2167
2404
  async getClient() {
@@ -2176,6 +2413,7 @@ class AssetsManager {
2176
2413
  }
2177
2414
  this.client = await getProjectClient({
2178
2415
  project: { path: this.projectPath },
2416
+ credentials: this.credentials,
2179
2417
  botId: this.botId,
2180
2418
  headers: {
2181
2419
  "x-multiple-integrations": "true"
@@ -2196,7 +2434,7 @@ class AssetsManager {
2196
2434
  }
2197
2435
  async hasAssetsDirectory() {
2198
2436
  try {
2199
- const stats = await fs8.stat(this.assetsPath);
2437
+ const stats = await fs6.stat(this.assetsPath);
2200
2438
  return stats.isDirectory();
2201
2439
  } catch {
2202
2440
  return false;
@@ -2210,16 +2448,16 @@ class AssetsManager {
2210
2448
  const assets = [];
2211
2449
  for (const filePath of files) {
2212
2450
  try {
2213
- const stats = await fs8.stat(filePath);
2451
+ const stats = await fs6.stat(filePath);
2214
2452
  if (stats.isFile()) {
2215
- const relativePath = path8.relative(this.assetsPath, filePath);
2216
- const content = await fs8.readFile(filePath);
2453
+ const relativePath = path6.relative(this.assetsPath, filePath);
2454
+ const content = await fs6.readFile(filePath);
2217
2455
  const hash = this.calculateHash(content);
2218
2456
  const mime = this.getMimeType(filePath);
2219
2457
  assets.push({
2220
2458
  relativePath,
2221
2459
  absolutePath: filePath,
2222
- name: path8.basename(filePath),
2460
+ name: path6.basename(filePath),
2223
2461
  size: stats.size,
2224
2462
  mime,
2225
2463
  hash,
@@ -2247,7 +2485,7 @@ class AssetsManager {
2247
2485
  });
2248
2486
  return response.files.map((file) => ({
2249
2487
  path: file.tags?.path || file.key,
2250
- name: path8.basename(file.tags?.path || file.key),
2488
+ name: path6.basename(file.tags?.path || file.key),
2251
2489
  size: file.size || 0,
2252
2490
  mime: file.contentType,
2253
2491
  hash: file.tags?.hash || "",
@@ -2385,7 +2623,7 @@ class AssetsManager {
2385
2623
  };
2386
2624
  }
2387
2625
  async uploadAsset(client, localFile) {
2388
- const content = await fs8.readFile(localFile.absolutePath);
2626
+ const content = await fs6.readFile(localFile.absolutePath);
2389
2627
  await client.uploadFile({
2390
2628
  key: localFile.relativePath,
2391
2629
  content,
@@ -2478,10 +2716,10 @@ declare global {
2478
2716
  return enrichedAssets;
2479
2717
  }
2480
2718
  async scanDirectory(dir, files = []) {
2481
- const items = await fs8.readdir(dir);
2719
+ const items = await fs6.readdir(dir);
2482
2720
  for (const item of items) {
2483
- const fullPath = path8.join(dir, item);
2484
- const stats = await fs8.stat(fullPath);
2721
+ const fullPath = path6.join(dir, item);
2722
+ const stats = await fs6.stat(fullPath);
2485
2723
  if (stats.isDirectory()) {
2486
2724
  await this.scanDirectory(fullPath, files);
2487
2725
  } else {
@@ -2494,7 +2732,7 @@ declare global {
2494
2732
  return crypto.createHash("sha256").update(content).digest("hex");
2495
2733
  }
2496
2734
  getMimeType(filePath) {
2497
- const ext = path8.extname(filePath).toLowerCase();
2735
+ const ext = path6.extname(filePath).toLowerCase();
2498
2736
  const mimeTypes = {
2499
2737
  ".png": "image/png",
2500
2738
  ".jpg": "image/jpeg",
@@ -2528,12 +2766,12 @@ var init_manager2 = __esm(() => {
2528
2766
  });
2529
2767
 
2530
2768
  // src/utils/fs.ts
2531
- import { mkdir, writeFile as writeFile2 } from "fs/promises";
2769
+ import { mkdir, writeFile } from "fs/promises";
2532
2770
  import { parse } from "path";
2533
- var createFile = async (path9, content) => {
2534
- const file = parse(path9);
2771
+ var createFile = async (path7, content) => {
2772
+ const file = parse(path7);
2535
2773
  await mkdir(file.dir, { recursive: true });
2536
- await writeFile2(path9, content);
2774
+ await writeFile(path7, content);
2537
2775
  };
2538
2776
  var init_fs = () => {};
2539
2777
 
@@ -2551,19 +2789,19 @@ var init_assets = __esm(() => {
2551
2789
  });
2552
2790
 
2553
2791
  // src/integrations/cache.ts
2554
- import fs9 from "fs/promises";
2555
- import path9 from "path";
2556
- import os5 from "os";
2792
+ import fs7 from "fs/promises";
2793
+ import path7 from "path";
2794
+ import os4 from "os";
2557
2795
 
2558
2796
  class IntegrationCache {
2559
2797
  cacheDir;
2560
2798
  integrationsDir;
2561
2799
  constructor() {
2562
- this.cacheDir = path9.join(os5.homedir(), ".adk", "cache");
2563
- this.integrationsDir = path9.join(this.cacheDir, "integrations");
2800
+ this.cacheDir = path7.join(os4.homedir(), ".adk", "cache");
2801
+ this.integrationsDir = path7.join(this.cacheDir, "integrations");
2564
2802
  }
2565
2803
  async ensureCacheDir() {
2566
- await fs9.mkdir(this.integrationsDir, { recursive: true });
2804
+ await fs7.mkdir(this.integrationsDir, { recursive: true });
2567
2805
  }
2568
2806
  getCacheKey(integrationId, updatedAt) {
2569
2807
  const sanitizedId = integrationId.replace(/[^a-zA-Z0-9_-]/g, "_");
@@ -2573,8 +2811,8 @@ class IntegrationCache {
2573
2811
  async get(integrationId, updatedAt) {
2574
2812
  try {
2575
2813
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2576
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2577
- 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");
2578
2816
  const cached = JSON.parse(data);
2579
2817
  if (cached.expiresAt) {
2580
2818
  const expiryDate = new Date(cached.expiresAt);
@@ -2591,7 +2829,7 @@ class IntegrationCache {
2591
2829
  async set(integrationId, updatedAt, definition, ttlHours = 24 * 7) {
2592
2830
  await this.ensureCacheDir();
2593
2831
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2594
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2832
+ const cachePath = path7.join(this.integrationsDir, cacheKey);
2595
2833
  const expiresAt = new Date;
2596
2834
  expiresAt.setHours(expiresAt.getHours() + ttlHours);
2597
2835
  const cacheEntry = {
@@ -2599,27 +2837,27 @@ class IntegrationCache {
2599
2837
  cachedAt: new Date().toISOString(),
2600
2838
  expiresAt: expiresAt.toISOString()
2601
2839
  };
2602
- await fs9.writeFile(cachePath, JSON.stringify(cacheEntry, null, 2));
2840
+ await fs7.writeFile(cachePath, JSON.stringify(cacheEntry, null, 2));
2603
2841
  }
2604
2842
  async remove(integrationId, updatedAt) {
2605
2843
  try {
2606
2844
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2607
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2608
- await fs9.unlink(cachePath);
2845
+ const cachePath = path7.join(this.integrationsDir, cacheKey);
2846
+ await fs7.unlink(cachePath);
2609
2847
  } catch {}
2610
2848
  }
2611
2849
  async clear() {
2612
2850
  try {
2613
- const files = await fs9.readdir(this.integrationsDir);
2614
- 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))));
2615
2853
  } catch {}
2616
2854
  }
2617
2855
  async getStats() {
2618
2856
  try {
2619
- const files = await fs9.readdir(this.integrationsDir);
2857
+ const files = await fs7.readdir(this.integrationsDir);
2620
2858
  let totalSize = 0;
2621
2859
  for (const file of files) {
2622
- const stats = await fs9.stat(path9.join(this.integrationsDir, file));
2860
+ const stats = await fs7.stat(path7.join(this.integrationsDir, file));
2623
2861
  totalSize += stats.size;
2624
2862
  }
2625
2863
  return {
@@ -2633,171 +2871,6 @@ class IntegrationCache {
2633
2871
  }
2634
2872
  var init_cache2 = () => {};
2635
2873
 
2636
- // src/integrations/hub-cache.ts
2637
- import { Client as Client3 } from "@botpress/client";
2638
- import * as fs10 from "fs/promises";
2639
- import * as path10 from "path";
2640
- import * as os6 from "os";
2641
- var HubCache;
2642
- var init_hub_cache = __esm(() => {
2643
- init_src();
2644
- init_auth();
2645
- HubCache = class HubCache {
2646
- static CACHE_FILE = "botpress-hub-cache.json";
2647
- static CACHE_DIR = path10.join(os6.homedir(), ".adk", "cache");
2648
- static CACHE_PATH = path10.join(HubCache.CACHE_DIR, HubCache.CACHE_FILE);
2649
- static CACHE_DURATION = 30 * 60 * 1000;
2650
- client;
2651
- constructor() {}
2652
- async getClient() {
2653
- if (!this.client) {
2654
- const credentials = await auth.getActiveCredentials();
2655
- if (!credentials.workspaceId) {
2656
- throw new AdkError({
2657
- code: "WORKSPACE_ID_MISSING",
2658
- message: 'No workspace ID found in current profile. Please login again with "adk login"',
2659
- expected: true,
2660
- suggestion: 'Please login again with "adk login".'
2661
- });
2662
- }
2663
- this.client = new Client3({
2664
- token: credentials.token,
2665
- apiUrl: credentials.apiUrl,
2666
- workspaceId: credentials.workspaceId,
2667
- headers: {
2668
- "x-multiple-integrations": "true"
2669
- }
2670
- });
2671
- }
2672
- return this.client;
2673
- }
2674
- async ensureCacheDir() {
2675
- try {
2676
- await fs10.mkdir(HubCache.CACHE_DIR, { recursive: true });
2677
- } catch {}
2678
- }
2679
- async loadCache() {
2680
- try {
2681
- const data = await fs10.readFile(HubCache.CACHE_PATH, "utf-8");
2682
- return JSON.parse(data);
2683
- } catch {
2684
- return null;
2685
- }
2686
- }
2687
- async saveCache(data) {
2688
- await this.ensureCacheDir();
2689
- await fs10.writeFile(HubCache.CACHE_PATH, JSON.stringify(data, null, 2));
2690
- }
2691
- async needsRefresh() {
2692
- const cache2 = await this.loadCache();
2693
- if (!cache2)
2694
- return true;
2695
- const lastUpdated = new Date(cache2.lastUpdated);
2696
- const now = new Date;
2697
- const diff = now.getTime() - lastUpdated.getTime();
2698
- return diff > HubCache.CACHE_DURATION;
2699
- }
2700
- async refresh(force = false) {
2701
- if (!force && !await this.needsRefresh()) {
2702
- return;
2703
- }
2704
- const client = await this.getClient();
2705
- const cache2 = await this.loadCache();
2706
- const latestByName = new Map;
2707
- if (cache2) {
2708
- for (const entry of cache2.integrations) {
2709
- latestByName.set(entry.name, entry);
2710
- }
2711
- }
2712
- try {
2713
- for await (const integration of client.list.publicIntegrations({
2714
- sortBy: "updatedAt",
2715
- direction: "desc"
2716
- })) {
2717
- const existing = latestByName.get(integration.name);
2718
- if (existing && integration.id === existing.id && integration.updatedAt === existing.updatedAt) {
2719
- break;
2720
- }
2721
- if (!existing || integration.version.localeCompare(existing.version, undefined, {
2722
- numeric: true
2723
- }) > 0) {
2724
- latestByName.set(integration.name, {
2725
- id: integration.id,
2726
- name: integration.name,
2727
- version: integration.version,
2728
- updatedAt: integration.updatedAt,
2729
- createdAt: integration.createdAt,
2730
- title: integration.title,
2731
- description: integration.description,
2732
- iconUrl: integration.iconUrl,
2733
- public: integration.public,
2734
- visibility: integration.visibility,
2735
- ownerWorkspace: integration.ownerWorkspace ? {
2736
- id: integration.ownerWorkspace.id,
2737
- name: integration.ownerWorkspace.name
2738
- } : undefined,
2739
- verificationStatus: integration.verificationStatus
2740
- });
2741
- }
2742
- }
2743
- const integrations = Array.from(latestByName.values()).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
2744
- const newCache = {
2745
- lastUpdated: new Date().toISOString(),
2746
- integrations
2747
- };
2748
- await this.saveCache(newCache);
2749
- } catch (error) {
2750
- throw new AdkError({
2751
- code: "HUB_CACHE_REFRESH_FAILED",
2752
- message: `Failed to refresh hub cache: ${error instanceof Error ? error.message : String(error)}`,
2753
- expected: true,
2754
- cause: error
2755
- });
2756
- }
2757
- }
2758
- async getAllIntegrations() {
2759
- await this.refresh();
2760
- const cache2 = await this.loadCache();
2761
- return cache2?.integrations || [];
2762
- }
2763
- async searchIntegrations(query) {
2764
- const integrations = await this.getAllIntegrations();
2765
- const lowerQuery = query.toLowerCase();
2766
- return integrations.filter((integration) => integration.name.toLowerCase().includes(lowerQuery) || integration.title?.toLowerCase().includes(lowerQuery) || integration.description?.toLowerCase().includes(lowerQuery));
2767
- }
2768
- async getIntegrationByName(name) {
2769
- const integrations = await this.getAllIntegrations();
2770
- return integrations.find((i) => i.name === name) || null;
2771
- }
2772
- async getIntegrationVersions(name) {
2773
- const integration = await this.getIntegrationByName(name);
2774
- return integration ? [integration.version] : [];
2775
- }
2776
- async getStats() {
2777
- const cache2 = await this.loadCache();
2778
- try {
2779
- const stats = await fs10.stat(HubCache.CACHE_PATH);
2780
- return {
2781
- lastUpdated: cache2 ? new Date(cache2.lastUpdated) : null,
2782
- integrationCount: cache2?.integrations.length || 0,
2783
- cacheSize: stats.size
2784
- };
2785
- } catch {
2786
- return {
2787
- lastUpdated: null,
2788
- integrationCount: 0,
2789
- cacheSize: 0
2790
- };
2791
- }
2792
- }
2793
- async clear() {
2794
- try {
2795
- await fs10.unlink(HubCache.CACHE_PATH);
2796
- } catch {}
2797
- }
2798
- };
2799
- });
2800
-
2801
2874
  // src/integrations/config-utils.ts
2802
2875
  function mergeIntegrationConfig(current, desired) {
2803
2876
  if (desired === undefined) {
@@ -2809,7 +2882,7 @@ async function fetchServerIntegrationConfigs(project, targetBotId) {
2809
2882
  const { devId, botId } = project.agentInfo ?? {};
2810
2883
  const targetId = targetBotId || devId || botId;
2811
2884
  if (!targetId) {
2812
- return { configs: {}, enabledStates: {}, fetched: false, skipped: true };
2885
+ return { configs: {}, enabledStates: {}, authorizedStates: {}, fetched: false, skipped: true };
2813
2886
  }
2814
2887
  try {
2815
2888
  const client = await getProjectClient({
@@ -2832,6 +2905,7 @@ async function fetchServerIntegrationConfigs(project, targetBotId) {
2832
2905
  return {
2833
2906
  configs: {},
2834
2907
  enabledStates: {},
2908
+ authorizedStates: {},
2835
2909
  fetched: false,
2836
2910
  skipped: false,
2837
2911
  error: message
@@ -2842,13 +2916,15 @@ async function fetchBotConfigs(client, botId) {
2842
2916
  const { bot } = await client.getBot({ id: botId });
2843
2917
  const configs = {};
2844
2918
  const enabledStates = {};
2919
+ const authorizedStates = {};
2845
2920
  for (const [alias, integration] of Object.entries(bot.integrations || {})) {
2846
2921
  if (integration.configuration && Object.keys(integration.configuration).length > 0) {
2847
2922
  configs[alias] = integration.configuration;
2848
2923
  }
2849
2924
  enabledStates[alias] = integration.enabled;
2925
+ authorizedStates[alias] = !!integration.identifier;
2850
2926
  }
2851
- return { configs, enabledStates, fetched: true, skipped: false };
2927
+ return { configs, enabledStates, authorizedStates, fetched: true, skipped: false };
2852
2928
  }
2853
2929
  async function fetchServerPluginConfigs(project, targetBotId) {
2854
2930
  const { devId, botId } = project.agentInfo ?? {};
@@ -2895,122 +2971,9 @@ var init_integrations = __esm(() => {
2895
2971
  init_manager();
2896
2972
  init_dependencies_parser();
2897
2973
  init_cache2();
2898
- init_enhanced_cache();
2899
- init_hub_cache();
2900
2974
  init_config_utils();
2901
2975
  });
2902
2976
 
2903
- // src/interfaces/enhanced-cache.ts
2904
- import fs11 from "fs/promises";
2905
- import path11 from "path";
2906
- import os7 from "os";
2907
-
2908
- class EnhancedInterfaceCache {
2909
- cacheDir;
2910
- resolutionsDir;
2911
- definitionsDir;
2912
- noCache;
2913
- constructor(noCache = false) {
2914
- this.noCache = noCache;
2915
- this.cacheDir = path11.join(os7.homedir(), ".adk", "cache", "interfaces");
2916
- this.resolutionsDir = path11.join(this.cacheDir, "resolutions");
2917
- this.definitionsDir = path11.join(this.cacheDir, "definitions");
2918
- }
2919
- async ensureCacheDirs() {
2920
- await fs11.mkdir(this.resolutionsDir, { recursive: true });
2921
- await fs11.mkdir(this.definitionsDir, { recursive: true });
2922
- }
2923
- async getResolution(name, version, workspace) {
2924
- if (this.noCache)
2925
- return null;
2926
- try {
2927
- const key = this.getResolutionKey(name, version, workspace);
2928
- const cachePath = path11.join(this.resolutionsDir, `${key}.json`);
2929
- const data = await fs11.readFile(cachePath, "utf-8");
2930
- const resolution = JSON.parse(data);
2931
- const cachedAt = new Date(resolution.cachedAt);
2932
- const ageMinutes = (Date.now() - cachedAt.getTime()) / (1000 * 60);
2933
- if (ageMinutes > 5)
2934
- return null;
2935
- return resolution;
2936
- } catch {
2937
- return null;
2938
- }
2939
- }
2940
- async setResolution(name, version, workspace, interfaceId, updatedAt) {
2941
- await this.ensureCacheDirs();
2942
- const key = this.getResolutionKey(name, version, workspace);
2943
- const cachePath = path11.join(this.resolutionsDir, `${key}.json`);
2944
- const resolution = {
2945
- interfaceId,
2946
- updatedAt,
2947
- cachedAt: new Date().toISOString()
2948
- };
2949
- await fs11.writeFile(cachePath, JSON.stringify(resolution));
2950
- }
2951
- async getDefinition(interfaceId, updatedAt) {
2952
- if (this.noCache)
2953
- return null;
2954
- try {
2955
- const key = this.getDefinitionKey(interfaceId, updatedAt);
2956
- const cachePath = path11.join(this.definitionsDir, `${key}.json`);
2957
- const data = await fs11.readFile(cachePath, "utf-8");
2958
- const cached = JSON.parse(data);
2959
- return cached.definition;
2960
- } catch {
2961
- return null;
2962
- }
2963
- }
2964
- async setDefinition(interfaceId, updatedAt, definition) {
2965
- await this.ensureCacheDirs();
2966
- const key = this.getDefinitionKey(interfaceId, updatedAt);
2967
- const cachePath = path11.join(this.definitionsDir, `${key}.json`);
2968
- const cached = {
2969
- definition,
2970
- cachedAt: new Date().toISOString()
2971
- };
2972
- await fs11.writeFile(cachePath, JSON.stringify(cached));
2973
- }
2974
- async clear() {
2975
- try {
2976
- const resolutionFiles = await fs11.readdir(this.resolutionsDir);
2977
- await Promise.all(resolutionFiles.map((f) => fs11.unlink(path11.join(this.resolutionsDir, f))));
2978
- const definitionFiles = await fs11.readdir(this.definitionsDir);
2979
- await Promise.all(definitionFiles.map((f) => fs11.unlink(path11.join(this.definitionsDir, f))));
2980
- } catch {}
2981
- }
2982
- async getStats() {
2983
- const getDirectoryStats = async (dir) => {
2984
- try {
2985
- const files = await fs11.readdir(dir);
2986
- let totalSize = 0;
2987
- for (const file of files) {
2988
- const stats = await fs11.stat(path11.join(dir, file));
2989
- totalSize += stats.size;
2990
- }
2991
- return { count: files.length, sizeBytes: totalSize };
2992
- } catch {
2993
- return { count: 0, sizeBytes: 0 };
2994
- }
2995
- };
2996
- const [resolutions, definitions] = await Promise.all([
2997
- getDirectoryStats(this.resolutionsDir),
2998
- getDirectoryStats(this.definitionsDir)
2999
- ]);
3000
- return { resolutions, definitions };
3001
- }
3002
- getResolutionKey(name, version, workspace) {
3003
- const prefix = workspace ? `${workspace}_` : "";
3004
- const key = `${prefix}${name}_${version}`;
3005
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
3006
- }
3007
- getDefinitionKey(interfaceId, updatedAt) {
3008
- const key = `${interfaceId}_${updatedAt}`;
3009
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
3010
- }
3011
- }
3012
- var init_enhanced_cache2 = () => {};
3013
-
3014
2977
  // src/interfaces/parser.ts
3015
2978
  class InterfaceParser {
3016
2979
  static parseInterfaceRef(versionString) {
@@ -3035,90 +2998,39 @@ class InterfaceParser {
3035
2998
  const errors = [];
3036
2999
  for (const [alias, versionString] of Object.entries(BUILTIN_INTERFACES)) {
3037
3000
  try {
3038
- const ref = this.parseInterfaceRef(versionString);
3039
- if (!this.isValidVersion(ref.version)) {
3040
- errors.push(ValidationErrors.invalidVersionFormat(alias, ref.version));
3041
- }
3042
- interfaces.push({ alias, ref, config: undefined });
3043
- } catch (error) {
3044
- errors.push(ValidationErrors.invalidDependenciesSyntax(`Invalid interface '${alias}': ${error instanceof Error ? error.message : String(error)}`));
3045
- }
3046
- }
3047
- return { interfaces, errors };
3048
- }
3049
- static isValidVersion(version) {
3050
- if (version === "latest")
3051
- return true;
3052
- const semverPattern = /^(\d+)\.(\d+)\.(\d+)(-[\w.]+)?(\+[\w.]+)?$/;
3053
- return semverPattern.test(version);
3054
- }
3055
- }
3056
- var init_parser = __esm(() => {
3057
- init_src();
3058
- init_validation_errors();
3059
- init_constants();
3060
- });
3061
-
3062
- // src/interfaces/manager.ts
3063
- class InterfaceManager {
3064
- cache;
3065
- options;
3066
- client;
3067
- constructor(options = {}) {
3068
- this.options = options;
3069
- this.cache = new EnhancedInterfaceCache(options.noCache || false);
3070
- }
3071
- async getClient() {
3072
- if (!this.client) {
3073
- this.client = await getProjectClient({
3074
- project: this.options.project,
3075
- credentials: this.options.credentials,
3076
- apiUrl: this.options.apiUrl,
3077
- workspaceId: this.options.workspaceId,
3078
- headers: {
3079
- "x-multiple-integrations": "true"
3080
- }
3081
- });
3082
- }
3083
- return this.client;
3084
- }
3085
- async loadInterfaces(dependencies) {
3086
- const errors = [];
3087
- const warnings = [];
3088
- const parseResult = InterfaceParser.parseInterfaces(dependencies);
3089
- const interfaces = parseResult.interfaces;
3090
- errors.push(...parseResult.errors);
3091
- const fetchPromises = interfaces.map(async (intf) => {
3092
- try {
3093
- const definition = await this.fetchInterface(intf.ref);
3094
- intf.definition = definition;
3095
- const validation = this.validateInterface(intf);
3096
- intf.validationResult = validation;
3097
- if (!validation.valid) {
3098
- validation.errors.forEach((msg) => {
3099
- errors.push(ValidationErrors.warning(msg, "agent.config.ts"));
3100
- });
3101
- }
3102
- } catch (error) {
3103
- if (error instanceof Error && error.message.includes("version")) {
3104
- errors.push(ValidationErrors.unknownInterface(error.message));
3105
- } else {
3106
- errors.push(ValidationErrors.invalidDependenciesSyntax(`Unknown interface '${intf.alias}' (${intf.ref.fullName})`));
3107
- }
3108
- }
3109
- });
3110
- await Promise.all(fetchPromises);
3111
- return { interfaces, errors, warnings };
3112
- }
3113
- async fetchInterface(ref) {
3114
- const cachedResolution = await this.cache.getResolution(ref.name, ref.version, ref.workspace);
3115
- if (cachedResolution) {
3116
- const cachedDefinition = await this.cache.getDefinition(cachedResolution.interfaceId, cachedResolution.updatedAt);
3117
- if (cachedDefinition) {
3118
- return cachedDefinition;
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)}`));
3119
3008
  }
3120
3009
  }
3121
- 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();
3122
3034
  let interfaceResponse;
3123
3035
  let versionError = null;
3124
3036
  try {
@@ -3162,32 +3074,56 @@ class InterfaceManager {
3162
3074
  }
3163
3075
  const location = ref.workspace ? `workspace "${ref.workspace}"` : "Botpress";
3164
3076
  throw new AdkError({
3165
- code: "INTERFACE_VERSION_NOT_FOUND",
3077
+ code: "VERSION_NOT_FOUND",
3166
3078
  message: `Interface "${ref.name}" version "${ref.version}" not found in ${location}. Latest available version is "${latestVersion}"`,
3167
3079
  expected: true
3168
3080
  });
3169
3081
  }
3170
3082
  const intf = interfaceResponse.interface;
3171
- await this.cache.setResolution(ref.name, ref.version, ref.workspace, intf.id, intf.updatedAt);
3172
- await this.cache.setDefinition(intf.id, intf.updatedAt, intf);
3173
- return intf;
3083
+ return { id: intf.id, updatedAt: intf.updatedAt, definition: intf };
3174
3084
  }
3175
- async getByDependencyString(dep) {
3176
- const match = dep.match(/^(?:([^/]+)\/)?([^@]+)@(.+)$/);
3177
- if (!match) {
3178
- throw new AdkError({
3179
- code: "INVALID_VERSION_FORMAT",
3180
- message: `Invalid interface dependency string: ${dep}. Expected 'name@version' or 'workspace/name@version'`,
3181
- expected: true
3182
- });
3183
- }
3184
- const [, workspace, name, version] = match;
3185
- return this.fetchInterface({
3186
- workspace: workspace || undefined,
3187
- name,
3188
- version,
3189
- 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
+ }
3190
3121
  });
3122
+ await Promise.all(fetchPromises);
3123
+ return { interfaces, errors, warnings };
3124
+ }
3125
+ async fetchInterface(ref) {
3126
+ return this.service.getDefinition(ref);
3191
3127
  }
3192
3128
  validateInterface(intf) {
3193
3129
  const errors = [];
@@ -3199,28 +3135,56 @@ class InterfaceManager {
3199
3135
  return { valid: errors.length === 0, errors, warnings };
3200
3136
  }
3201
3137
  async getCacheStats() {
3202
- const stats = await this.cache.getStats();
3203
- return {
3204
- count: stats.resolutions.count + stats.definitions.count,
3205
- sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
3206
- };
3138
+ return this.service.getCacheStats();
3207
3139
  }
3208
3140
  async clearCache() {
3209
- await this.cache.clear();
3141
+ await this.service.clearCache();
3210
3142
  }
3211
3143
  }
3212
3144
  var init_manager3 = __esm(() => {
3213
- init_src();
3214
- init_auth();
3215
- init_enhanced_cache2();
3216
3145
  init_parser();
3217
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();
3218
3182
  });
3219
3183
  // src/interfaces/index.ts
3220
3184
  var init_interfaces = __esm(() => {
3221
3185
  init_manager3();
3222
3186
  init_parser();
3223
- init_enhanced_cache2();
3187
+ init_enhanced_cache();
3224
3188
  });
3225
3189
 
3226
3190
  // src/utils/json-ordering.ts
@@ -3382,7 +3346,7 @@ var init_component_files = __esm(() => {
3382
3346
  // src/agent-project/component-source-resolver.ts
3383
3347
  import { Project, SyntaxKind } from "ts-morph";
3384
3348
  import { readFileSync } from "fs";
3385
- import * as path12 from "path";
3349
+ import * as path8 from "path";
3386
3350
  function resolveComponentSources(absolutePath) {
3387
3351
  const project = new Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true });
3388
3352
  const sourceFile = project.createSourceFile(absolutePath, readFileSync(absolutePath, "utf-8"), { overwrite: true });
@@ -3395,12 +3359,12 @@ function resolveComponentSources(absolutePath) {
3395
3359
  }
3396
3360
  function collectBpTsxImports(sourceFile, absolutePath) {
3397
3361
  const imports = new Map;
3398
- const dir = path12.dirname(absolutePath);
3362
+ const dir = path8.dirname(absolutePath);
3399
3363
  for (const decl of sourceFile.getImportDeclarations()) {
3400
3364
  const specifier = decl.getModuleSpecifierValue();
3401
3365
  if (!specifier.endsWith(BP_TSX_SUFFIX))
3402
3366
  continue;
3403
- const resolved = path12.resolve(dir, specifier);
3367
+ const resolved = path8.resolve(dir, specifier);
3404
3368
  const defaultImport = decl.getDefaultImport();
3405
3369
  if (defaultImport) {
3406
3370
  imports.set(defaultImport.getText(), resolved);
@@ -3453,69 +3417,370 @@ function resolveExports(sourceFile, localToSource, importBindings) {
3453
3417
  exportMap.set("default", fromLocal);
3454
3418
  }
3455
3419
  }
3456
- for (const decl of sourceFile.getExportDeclarations()) {
3457
- if (decl.getModuleSpecifier())
3458
- continue;
3459
- for (const named of decl.getNamedExports()) {
3460
- const localName = named.getNameNode().getText();
3461
- const aliasNode = named.getAliasNode();
3462
- const exportName = aliasNode ? aliasNode.getText() : localName;
3463
- const source = localToSource.get(localName);
3464
- if (source)
3465
- 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
+ }
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
+ };
3733
+ }
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
+ };
3743
+ }
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];
3466
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];
3467
3757
  }
3468
- return exportMap;
3469
- }
3470
- function sourceFromCustomComponentExpr(expr, importBindings) {
3471
- if (expr.getKind() !== SyntaxKind.NewExpression)
3472
- return;
3473
- const newExpr = expr.asKindOrThrow(SyntaxKind.NewExpression);
3474
- if (newExpr.getExpression().getText() !== CUSTOM_COMPONENT_CLASS)
3475
- return;
3476
- const args = newExpr.getArguments();
3477
- const firstArg = args[0];
3478
- if (!firstArg || firstArg.getKind() !== SyntaxKind.Identifier)
3479
- return;
3480
- return importBindings.get(firstArg.getText());
3481
- }
3482
- var CUSTOM_COMPONENT_CLASS = "CustomComponent";
3483
- var init_component_source_resolver = __esm(() => {
3484
- init_component_files();
3485
- });
3486
-
3487
- // src/bot-generator/table-validation.ts
3488
- function getColumnCount(table) {
3489
- const properties = table.definition.schema?.properties;
3490
- return properties ? Object.keys(properties).length : 0;
3491
- }
3492
- function findTableColumnViolations(tables, max = MAX_TABLE_COLUMNS) {
3493
- return tables.map((table) => ({
3494
- name: table.definition.name,
3495
- path: table.path,
3496
- columnCount: getColumnCount(table)
3497
- })).filter((t) => t.columnCount > max);
3758
+ return generateFriendlyAlias(opts.cloudName, opts.cloudAlias, opts.used);
3498
3759
  }
3499
- var init_table_validation = __esm(() => {
3500
- init_constants();
3760
+ var init_snapshot_store = __esm(() => {
3761
+ init_alias_utils();
3762
+ init_errors2();
3763
+ init_types();
3501
3764
  });
3502
3765
 
3503
- // src/agent-project/lock-to-dependencies.ts
3504
- function lockToDependencies(lock) {
3766
+ // src/agent-project/dependency-state-to-dependencies.ts
3767
+ function dependencyStateToDependencies(state) {
3505
3768
  const integrations = {};
3506
- for (const [alias, entry] of Object.entries(lock.integrations)) {
3769
+ for (const [alias, entry] of Object.entries(state.integrations)) {
3507
3770
  integrations[alias] = {
3508
3771
  version: `${entry.name}@${entry.version}`,
3509
3772
  enabled: entry.enabled,
3510
- config: entry.config
3773
+ config: entry.config,
3774
+ ...entry.configurationType ? { configurationType: entry.configurationType } : {}
3511
3775
  };
3512
3776
  }
3513
3777
  const plugins = {};
3514
- for (const [alias, entry] of Object.entries(lock.plugins)) {
3778
+ for (const [alias, entry] of Object.entries(state.plugins)) {
3515
3779
  plugins[alias] = {
3516
3780
  version: `${entry.name}@${entry.version}`,
3517
3781
  config: entry.config,
3518
- dependencies: entry.dependencies
3782
+ dependencies: entry.dependencies,
3783
+ ...entry.missingFields !== undefined ? { missingFields: entry.missingFields } : {}
3519
3784
  };
3520
3785
  }
3521
3786
  return { integrations, plugins };
@@ -3526,8 +3791,8 @@ import { BuiltInActions, BuiltInWorkflows, Errors as Errors2, Primitives as Prim
3526
3791
  import { Autonomous } from "@botpress/runtime";
3527
3792
  import createDebug from "debug";
3528
3793
  import { createRequire as createRequire2 } from "module";
3529
- import fs12 from "fs/promises";
3530
- import path13 from "path";
3794
+ import fs9 from "fs/promises";
3795
+ import path10 from "path";
3531
3796
  function getToolDefinition(value) {
3532
3797
  if (typeof value !== "object" || value === null) {
3533
3798
  return;
@@ -3558,7 +3823,7 @@ var init_agent_project = __esm(() => {
3558
3823
  init_validation_errors();
3559
3824
  init_table_validation();
3560
3825
  init_constants();
3561
- init_lock_file();
3826
+ init_snapshot_store();
3562
3827
  debug = createDebug("adk:agent-project");
3563
3828
  AgentProject = class AgentProject {
3564
3829
  static _projectCache = new Map;
@@ -3586,7 +3851,7 @@ var init_agent_project = __esm(() => {
3586
3851
  _tools = [];
3587
3852
  constructor(projectPath, options = {}) {
3588
3853
  this._options = options;
3589
- this._path = path13.resolve(projectPath);
3854
+ this._path = path10.resolve(projectPath);
3590
3855
  this._integrationManager = new IntegrationManager({
3591
3856
  noCache: options.noCache
3592
3857
  });
@@ -3598,7 +3863,7 @@ var init_agent_project = __esm(() => {
3598
3863
  });
3599
3864
  }
3600
3865
  static async load(projectPath, options = {}) {
3601
- const resolvedPath = path13.resolve(projectPath);
3866
+ const resolvedPath = path10.resolve(projectPath);
3602
3867
  if (!options.noCache) {
3603
3868
  const cached = AgentProject._projectCache.get(resolvedPath);
3604
3869
  if (cached) {
@@ -3616,7 +3881,7 @@ var init_agent_project = __esm(() => {
3616
3881
  AgentProject._projectCache.clear();
3617
3882
  }
3618
3883
  static clearCacheForPath(projectPath) {
3619
- const resolvedPath = path13.resolve(projectPath);
3884
+ const resolvedPath = path10.resolve(projectPath);
3620
3885
  AgentProject._projectCache.delete(resolvedPath);
3621
3886
  }
3622
3887
  get path() {
@@ -3732,17 +3997,17 @@ var init_agent_project = __esm(() => {
3732
3997
  const warnings = [];
3733
3998
  const info = [];
3734
3999
  try {
3735
- await fs12.access(this._path);
4000
+ await fs9.access(this._path);
3736
4001
  const requiredFiles = ["agent.config.ts"];
3737
4002
  for (const file of requiredFiles) {
3738
4003
  try {
3739
- await fs12.access(path13.join(this._path, file));
4004
+ await fs9.access(path10.join(this._path, file));
3740
4005
  } catch {
3741
4006
  errors.push(ValidationErrors.requiredFileMissing(file));
3742
4007
  }
3743
4008
  }
3744
4009
  try {
3745
- await fs12.access(path13.join(this._path, "agent.json"));
4010
+ await fs9.access(path10.join(this._path, "agent.json"));
3746
4011
  } catch {
3747
4012
  info.push({
3748
4013
  $type: "ValidationError",
@@ -3756,7 +4021,7 @@ var init_agent_project = __esm(() => {
3756
4021
  const expectedDirs = ["actions", "workflows", "conversations", "assets"];
3757
4022
  for (const dir of expectedDirs) {
3758
4023
  try {
3759
- const stats = await fs12.stat(path13.join(this._path, dir));
4024
+ const stats = await fs9.stat(path10.join(this._path, dir));
3760
4025
  if (!stats.isDirectory()) {
3761
4026
  warnings.push(ValidationErrors.invalidStructure(dir, "directory"));
3762
4027
  }
@@ -3840,9 +4105,9 @@ var init_agent_project = __esm(() => {
3840
4105
  }
3841
4106
  async createAgentInfo(info) {
3842
4107
  const { devId, ...agentJsonInfo } = info;
3843
- const agentPath = path13.join(this._path, "agent.json");
4108
+ const agentPath = path10.join(this._path, "agent.json");
3844
4109
  const agentContent = stringifyWithOrder(agentJsonInfo, agentInfoKeyOrder);
3845
- await fs12.writeFile(agentPath, agentContent);
4110
+ await fs9.writeFile(agentPath, agentContent);
3846
4111
  this._agentInfo = info;
3847
4112
  if (devId) {
3848
4113
  await this.createAgentLocalInfo({ devId });
@@ -3859,24 +4124,24 @@ var init_agent_project = __esm(() => {
3859
4124
  const { devId, ...agentJsonUpdates } = updates;
3860
4125
  const updatedInfo = { ...this._agentInfo, ...agentJsonUpdates };
3861
4126
  const { devId: _devId, ...agentJsonData } = updatedInfo;
3862
- const agentPath = path13.join(this._path, "agent.json");
4127
+ const agentPath = path10.join(this._path, "agent.json");
3863
4128
  const agentContent = stringifyWithOrder(agentJsonData, agentInfoKeyOrder);
3864
- await fs12.writeFile(agentPath, agentContent);
4129
+ await fs9.writeFile(agentPath, agentContent);
3865
4130
  this._agentInfo = updatedInfo;
3866
4131
  if (devId !== undefined) {
3867
4132
  await this.updateAgentLocalInfo({ devId });
3868
4133
  }
3869
4134
  }
3870
4135
  async createAgentLocalInfo(info) {
3871
- const localPath = path13.join(this._path, "agent.local.json");
4136
+ const localPath = path10.join(this._path, "agent.local.json");
3872
4137
  let existing = {};
3873
4138
  try {
3874
- const content2 = await fs12.readFile(localPath, "utf-8");
4139
+ const content2 = await fs9.readFile(localPath, "utf-8");
3875
4140
  existing = JSON.parse(content2);
3876
4141
  } catch {}
3877
4142
  const merged = { ...existing, ...info };
3878
4143
  const content = stringifyWithOrder(merged, agentLocalInfoKeyOrder);
3879
- await fs12.writeFile(localPath, content);
4144
+ await fs9.writeFile(localPath, content);
3880
4145
  if (this._agentInfo) {
3881
4146
  if (merged.botId)
3882
4147
  this._agentInfo.botId = merged.botId;
@@ -3896,10 +4161,10 @@ var init_agent_project = __esm(() => {
3896
4161
  }
3897
4162
  }
3898
4163
  async updateAgentLocalInfo(updates) {
3899
- const localPath = path13.join(this._path, "agent.local.json");
4164
+ const localPath = path10.join(this._path, "agent.local.json");
3900
4165
  let existing = {};
3901
4166
  try {
3902
- const content = await fs12.readFile(localPath, "utf-8");
4167
+ const content = await fs9.readFile(localPath, "utf-8");
3903
4168
  existing = JSON.parse(content);
3904
4169
  } catch {}
3905
4170
  const updated = { ...existing, ...updates };
@@ -3910,21 +4175,21 @@ var init_agent_project = __esm(() => {
3910
4175
  }
3911
4176
  if (Object.keys(updated).length === 0) {
3912
4177
  try {
3913
- await fs12.unlink(localPath);
4178
+ await fs9.unlink(localPath);
3914
4179
  } catch {}
3915
4180
  } else {
3916
4181
  const content = stringifyWithOrder(updated, agentLocalInfoKeyOrder);
3917
- await fs12.writeFile(localPath, content);
4182
+ await fs9.writeFile(localPath, content);
3918
4183
  }
3919
4184
  if (this._agentInfo) {
3920
- const agentJsonPath = path13.join(this._path, "agent.json");
4185
+ const agentJsonPath = path10.join(this._path, "agent.json");
3921
4186
  let base = {
3922
4187
  botId: this._agentInfo.botId,
3923
4188
  workspaceId: this._agentInfo.workspaceId,
3924
4189
  apiUrl: this._agentInfo.apiUrl
3925
4190
  };
3926
4191
  try {
3927
- const agentJsonContent = await fs12.readFile(agentJsonPath, "utf-8");
4192
+ const agentJsonContent = await fs9.readFile(agentJsonPath, "utf-8");
3928
4193
  const parsed = JSON.parse(agentJsonContent);
3929
4194
  base = {
3930
4195
  botId: parsed.botId ?? this._agentInfo.botId,
@@ -3956,10 +4221,10 @@ var init_agent_project = __esm(() => {
3956
4221
  this._integrations = [];
3957
4222
  this._interfaces = [];
3958
4223
  try {
3959
- const configPath = path13.join(this._path, "agent.config.ts");
4224
+ const configPath = path10.join(this._path, "agent.config.ts");
3960
4225
  debug("loading agent.config.ts from %s", configPath);
3961
- const projectRequire = createRequire2(path13.join(this._path, "package.json"));
3962
- debug("created projectRequire from %s", path13.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"));
3963
4228
  try {
3964
4229
  const resolvedPath = projectRequire.resolve(configPath);
3965
4230
  debug("resolved config path: %s", resolvedPath);
@@ -4003,49 +4268,29 @@ var init_agent_project = __esm(() => {
4003
4268
  return;
4004
4269
  }
4005
4270
  this._config = configModule.default;
4006
- const lockFile = new LockFile({ projectPath: this._path, env: "dev" });
4007
- 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;
4008
4275
  try {
4009
- const lockData = await lockFile.read();
4010
- 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;
4011
4279
  if (hasDependencies) {
4012
- lockBasedDependencies = lockToDependencies(lockData);
4280
+ snapshotBasedDependencies = dependencyStateToDependencies(state);
4013
4281
  }
4014
4282
  } catch (err) {
4015
4283
  this._warnings.push({
4016
4284
  $type: "ValidationError",
4017
4285
  code: "INVALID_DEPENDENCIES_SCHEMA" /* INVALID_DEPENDENCIES_SCHEMA */,
4018
4286
  severity: "warning" /* WARNING */,
4019
- message: `Could not read dependencies.dev.lock.json: ${err.message}. Falling back to agent.config.ts dependencies.`,
4020
- 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`
4021
4289
  });
4290
+ dependencySnapshotReadFailed = true;
4022
4291
  }
4023
- const config = configModule.default;
4024
- let configBasedDependencies;
4025
- if (!lockBasedDependencies && config.dependencies) {
4026
- const validationResult = dependenciesSchema.safeParse(config.dependencies);
4027
- if (!validationResult.success) {
4028
- const errors = validationResult.error.errors;
4029
- for (const error of errors) {
4030
- this._errors.push({
4031
- $type: "ValidationError",
4032
- code: "INVALID_DEPENDENCIES_SCHEMA" /* INVALID_DEPENDENCIES_SCHEMA */,
4033
- severity: "error" /* ERROR */,
4034
- message: `Invalid dependencies in agent.config.ts: ${error.path.join(".")} - ${error.message}`,
4035
- file: "agent.config.ts",
4036
- hint: error.code === "invalid_type" ? `Expected ${error.expected}, but got ${error.received}` : undefined
4037
- });
4038
- }
4039
- this._dependencies = { integrations: {} };
4040
- this._integrations = [];
4041
- this._interfaces = [];
4042
- return;
4043
- }
4044
- configBasedDependencies = validationResult.data;
4045
- }
4046
- const depsToLoad = lockBasedDependencies ?? configBasedDependencies;
4047
- if (depsToLoad) {
4048
- this._dependencies = depsToLoad;
4292
+ if (snapshotBasedDependencies) {
4293
+ this._dependencies = snapshotBasedDependencies;
4049
4294
  if (!this._options.offline) {
4050
4295
  const [intRes, ifRes] = await Promise.all([
4051
4296
  this._integrationManager.loadIntegrations(this._dependencies),
@@ -4156,8 +4401,8 @@ ${err.stack?.split(`
4156
4401
  }
4157
4402
  }
4158
4403
  isBarrelReexport(existing, newPath, newExport, newDefinition) {
4159
- const isNewBarrel = /^index\.[tj]s$/i.test(path13.basename(newPath));
4160
- const isExistingBarrel = /^index\.[tj]s$/i.test(path13.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));
4161
4406
  if (!isNewBarrel && !isExistingBarrel) {
4162
4407
  return false;
4163
4408
  }
@@ -4169,16 +4414,16 @@ ${err.stack?.split(`
4169
4414
  return true;
4170
4415
  }
4171
4416
  isToolBarrelReexport(existingPath, newPath) {
4172
- const isNewBarrel = /^index\.[tj]s$/i.test(path13.basename(newPath));
4173
- const isExistingBarrel = /^index\.[tj]s$/i.test(path13.basename(existingPath));
4417
+ const isNewBarrel = /^index\.[tj]s$/i.test(path10.basename(newPath));
4418
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path10.basename(existingPath));
4174
4419
  if (!isNewBarrel && !isExistingBarrel) {
4175
4420
  return false;
4176
4421
  }
4177
4422
  return true;
4178
4423
  }
4179
4424
  shouldPreferToolDefinition(existingPath, newPath) {
4180
- const isNewBarrel = /^index\.[tj]s$/i.test(path13.basename(newPath));
4181
- const isExistingBarrel = /^index\.[tj]s$/i.test(path13.basename(existingPath));
4425
+ const isNewBarrel = /^index\.[tj]s$/i.test(path10.basename(newPath));
4426
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path10.basename(existingPath));
4182
4427
  return isExistingBarrel && !isNewBarrel;
4183
4428
  }
4184
4429
  getChannelsList(channelSpec) {
@@ -4194,8 +4439,8 @@ ${err.stack?.split(`
4194
4439
  if (this._options.adkCommand) {
4195
4440
  setAdkCommand(this._options.adkCommand);
4196
4441
  }
4197
- const src = path13.join(this._path, "src");
4198
- if (!await fs12.stat(src).catch(() => false)) {
4442
+ const src = path10.join(this._path, "src");
4443
+ if (!await fs9.stat(src).catch(() => false)) {
4199
4444
  this._errors.push({
4200
4445
  $type: "ValidationError",
4201
4446
  code: "INVALID_STRUCTURE" /* INVALID_STRUCTURE */,
@@ -4204,14 +4449,14 @@ ${err.stack?.split(`
4204
4449
  });
4205
4450
  return;
4206
4451
  }
4207
- const allFiles = await fs12.readdir(src, {
4452
+ const allFiles = await fs9.readdir(src, {
4208
4453
  withFileTypes: true,
4209
4454
  recursive: true
4210
4455
  });
4211
4456
  for (const file of allFiles.filter((x) => x.isFile())) {
4212
4457
  const filename = file.name;
4213
- const absolutePath = path13.join(file.parentPath, file.name);
4214
- const relPath = path13.relative(this.path, absolutePath);
4458
+ const absolutePath = path10.join(file.parentPath, file.name);
4459
+ const relPath = path10.relative(this.path, absolutePath);
4215
4460
  if (filename.toLowerCase().endsWith(".d.ts")) {
4216
4461
  continue;
4217
4462
  }
@@ -4498,7 +4743,7 @@ ${err.stack?.split(`
4498
4743
  });
4499
4744
 
4500
4745
  // src/generators/utils.ts
4501
- import path14 from "path";
4746
+ import path13 from "path";
4502
4747
  async function getFormat() {
4503
4748
  if (!_formatLoaded) {
4504
4749
  _formatLoaded = true;
@@ -4546,9 +4791,9 @@ var _format = null, _formatLoaded = false, formatCode = async (code, filepath) =
4546
4791
  `));
4547
4792
  return code;
4548
4793
  }
4549
- }, ADK_VERSION = "1.19.0-beta.12", relative = (from, to) => {
4550
- const fromDir = path14.dirname(from);
4551
- const relative2 = path14.relative(fromDir, to);
4794
+ }, ADK_VERSION = "1.19.0-beta.14", relative = (from, to) => {
4795
+ const fromDir = path13.dirname(from);
4796
+ const relative2 = path13.relative(fromDir, to);
4552
4797
  return relative2.startsWith(".") ? relative2 : `./${relative2}`;
4553
4798
  };
4554
4799
  var init_utils = () => {};
@@ -4557,14 +4802,22 @@ var init_utils = () => {};
4557
4802
  var exports_dependencies = {};
4558
4803
  __export(exports_dependencies, {
4559
4804
  sortKeysDeep: () => sortKeysDeep,
4805
+ resolveDependencyStatuses: () => resolveDependencyStatuses,
4560
4806
  migrateFromConfig: () => migrateFromConfig,
4561
4807
  jsonEqual: () => jsonEqual,
4808
+ isCallable: () => isCallable,
4809
+ emptyDependencySnapshot: () => emptyDependencySnapshot,
4810
+ dependencyStateSchema: () => dependencyStateSchema,
4811
+ dependencySnapshotFromBot: () => dependencySnapshotFromBot,
4812
+ computePluginStatus: () => computePluginStatus,
4813
+ computeIntegrationStatus: () => computeIntegrationStatus,
4562
4814
  PluginResolver: () => PluginResolver,
4563
4815
  PluginRegistry: () => PluginRegistry,
4564
- LockFile: () => LockFile,
4565
4816
  InterfaceRegistry: () => InterfaceRegistry,
4566
4817
  IntegrationResolver: () => IntegrationResolver,
4567
4818
  IntegrationRegistry: () => IntegrationRegistry,
4819
+ DependencySnapshotStore: () => DependencySnapshotStore,
4820
+ DependencyMigrationManager: () => DependencyMigrationManager,
4568
4821
  DependencyManager: () => DependencyManager,
4569
4822
  DependencyError: () => DependencyError,
4570
4823
  DEPENDENCY_WARNING_CODES: () => DEPENDENCY_WARNING_CODES,
@@ -4572,34 +4825,10 @@ __export(exports_dependencies, {
4572
4825
  });
4573
4826
 
4574
4827
  // src/dependencies/dependency-manager.ts
4575
- init_lock_file();
4576
- import * as semver2 from "semver";
4577
-
4578
- // src/dependencies/alias-utils.ts
4579
- var FRIENDLY_ALIAS_RE = /^[a-z0-9_-]{2,100}$/;
4580
- var BP_INTERNAL_ID_PREFIXES = ["intver_", "plgver_", "int_", "plg_"];
4581
- function isBotpressInternalId(alias) {
4582
- return BP_INTERNAL_ID_PREFIXES.some((prefix) => alias.startsWith(prefix));
4583
- }
4584
- function isFriendlyAlias(alias) {
4585
- return FRIENDLY_ALIAS_RE.test(alias) && !isBotpressInternalId(alias);
4586
- }
4587
- function generateFriendlyAlias(cloudName, cloudAlias, used) {
4588
- if (isFriendlyAlias(cloudAlias) && !used.has(cloudAlias))
4589
- return cloudAlias;
4590
- const base = cloudName?.split("/").at(-1) ?? cloudAlias;
4591
- const sanitized = base.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
4592
- let candidate = sanitized;
4593
- let n = 2;
4594
- while (used.has(candidate)) {
4595
- candidate = `${sanitized}-${n}`;
4596
- n++;
4597
- }
4598
- return candidate;
4599
- }
4600
-
4601
- // src/dependencies/dependency-manager.ts
4828
+ init_types();
4602
4829
  init_errors2();
4830
+ import * as semver2 from "semver";
4831
+ import { extractMissingRequiredFields } from "@botpress/runtime";
4603
4832
 
4604
4833
  // src/dependencies/resolvers/integration-resolver.ts
4605
4834
  init_errors2();
@@ -4611,13 +4840,17 @@ class IntegrationResolver {
4611
4840
  this.registry = opts.registry;
4612
4841
  this.client = opts.client;
4613
4842
  }
4614
- toLockEntry(cloud) {
4615
- return {
4843
+ toDependencyEntry(cloud) {
4844
+ const entry = {
4616
4845
  name: cloud.name ?? "",
4617
4846
  version: cloud.version ?? "0.0.0",
4618
4847
  enabled: Boolean(cloud.enabled),
4619
4848
  config: cloud.configuration ?? {}
4620
4849
  };
4850
+ if (typeof cloud.configurationType === "string" && cloud.configurationType && cloud.configurationType !== "default") {
4851
+ entry.configurationType = cloud.configurationType;
4852
+ }
4853
+ return entry;
4621
4854
  }
4622
4855
  async applyToCloud(opts) {
4623
4856
  const spec = await this.registry.getSpec(opts.entry.name, opts.entry.version);
@@ -4659,7 +4892,7 @@ class PluginResolver {
4659
4892
  this.integrationRegistry = opts.integrationRegistry;
4660
4893
  this.client = opts.client;
4661
4894
  }
4662
- toLockEntry(cloud) {
4895
+ toDependencyEntry(cloud) {
4663
4896
  const dependencies = {};
4664
4897
  for (const [ifaceAlias, dep] of Object.entries(cloud.interfaces ?? {})) {
4665
4898
  if (dep.integrationAlias) {
@@ -4687,7 +4920,7 @@ class PluginResolver {
4687
4920
  details: { plugin: opts.alias, pluginInterfaceAlias: pluginIfaceAlias, interfaceName: requirement.name }
4688
4921
  });
4689
4922
  }
4690
- const integration = opts.lock.integrations[dep.integrationAlias];
4923
+ const integration = opts.state.integrations[dep.integrationAlias];
4691
4924
  if (!integration) {
4692
4925
  throw new DependencyError({
4693
4926
  code: "MISSING_DEPENDENCY",
@@ -4762,180 +4995,24 @@ class IntegrationRegistry {
4762
4995
  }
4763
4996
  }
4764
4997
 
4765
- // src/plugins/manager.ts
4766
- init_src();
4767
- init_auth();
4768
-
4769
- // src/plugins/enhanced-cache.ts
4770
- import fs6 from "fs/promises";
4771
- import path6 from "path";
4772
- import os4 from "os";
4773
-
4774
- class EnhancedPluginCache {
4775
- cacheDir;
4776
- resolutionsDir;
4777
- definitionsDir;
4778
- noCache;
4779
- constructor(noCache = false) {
4780
- this.noCache = noCache;
4781
- this.cacheDir = path6.join(os4.homedir(), ".adk", "cache", "plugins");
4782
- this.resolutionsDir = path6.join(this.cacheDir, "resolutions");
4783
- this.definitionsDir = path6.join(this.cacheDir, "definitions");
4784
- }
4785
- async ensureCacheDirs() {
4786
- await fs6.mkdir(this.resolutionsDir, { recursive: true });
4787
- await fs6.mkdir(this.definitionsDir, { recursive: true });
4788
- }
4789
- async getResolution(name, version) {
4790
- if (this.noCache) {
4791
- return null;
4792
- }
4793
- try {
4794
- const key = this.getResolutionKey(name, version);
4795
- const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
4796
- const data = await fs6.readFile(cachePath, "utf-8");
4797
- const resolution = JSON.parse(data);
4798
- const cachedAt = new Date(resolution.cachedAt);
4799
- const now = new Date;
4800
- const ageMinutes = (now.getTime() - cachedAt.getTime()) / (1000 * 60);
4801
- if (ageMinutes > 5) {
4802
- return null;
4803
- }
4804
- return resolution;
4805
- } catch {
4806
- return null;
4807
- }
4808
- }
4809
- async setResolution(name, version, pluginId, updatedAt) {
4810
- await this.ensureCacheDirs();
4811
- const key = this.getResolutionKey(name, version);
4812
- const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
4813
- const resolution = {
4814
- pluginId,
4815
- updatedAt,
4816
- cachedAt: new Date().toISOString()
4817
- };
4818
- await fs6.writeFile(cachePath, JSON.stringify(resolution));
4819
- }
4820
- async getDefinition(pluginId, updatedAt) {
4821
- if (this.noCache) {
4822
- return null;
4823
- }
4824
- try {
4825
- const key = this.getDefinitionKey(pluginId, updatedAt);
4826
- const cachePath = path6.join(this.definitionsDir, `${key}.json`);
4827
- const data = await fs6.readFile(cachePath, "utf-8");
4828
- const cached = JSON.parse(data);
4829
- return cached.definition;
4830
- } catch {
4831
- return null;
4832
- }
4833
- }
4834
- async setDefinition(pluginId, updatedAt, definition) {
4835
- await this.ensureCacheDirs();
4836
- const key = this.getDefinitionKey(pluginId, updatedAt);
4837
- const cachePath = path6.join(this.definitionsDir, `${key}.json`);
4838
- const cached = {
4839
- definition,
4840
- cachedAt: new Date().toISOString()
4841
- };
4842
- await fs6.writeFile(cachePath, JSON.stringify(cached));
4843
- }
4844
- async clear() {
4845
- try {
4846
- const resolutionFiles = await fs6.readdir(this.resolutionsDir);
4847
- await Promise.all(resolutionFiles.map((file) => fs6.unlink(path6.join(this.resolutionsDir, file))));
4848
- const definitionFiles = await fs6.readdir(this.definitionsDir);
4849
- await Promise.all(definitionFiles.map((file) => fs6.unlink(path6.join(this.definitionsDir, file))));
4850
- } catch {}
4851
- }
4852
- async getStats() {
4853
- const getDirectoryStats = async (dir) => {
4854
- try {
4855
- const files = await fs6.readdir(dir);
4856
- let totalSize = 0;
4857
- for (const file of files) {
4858
- const stats = await fs6.stat(path6.join(dir, file));
4859
- totalSize += stats.size;
4860
- }
4861
- return {
4862
- count: files.length,
4863
- sizeBytes: totalSize
4864
- };
4865
- } catch {
4866
- return { count: 0, sizeBytes: 0 };
4867
- }
4868
- };
4869
- const [resolutions, definitions] = await Promise.all([
4870
- getDirectoryStats(this.resolutionsDir),
4871
- getDirectoryStats(this.definitionsDir)
4872
- ]);
4873
- return { resolutions, definitions };
4874
- }
4875
- getResolutionKey(name, version) {
4876
- const key = `${name}_${version}`;
4877
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
4878
- }
4879
- getDefinitionKey(pluginId, updatedAt) {
4880
- const key = `${pluginId}_${updatedAt}`;
4881
- return key.replace(/[^a-zA-Z0-9_-]/g, "_");
4882
- }
4883
- }
4884
-
4885
4998
  // src/plugins/manager.ts
4886
4999
  init_dependencies_parser();
4887
5000
  init_validation_errors();
5001
+ init_client_factory();
5002
+ init_catalog_service();
5003
+
5004
+ // src/dependencies/catalog/plugin-source.ts
5005
+ init_src();
4888
5006
  init_search_ranking();
4889
5007
 
4890
- class PluginManager {
4891
- cache;
4892
- options;
4893
- client;
4894
- constructor(options = {}) {
4895
- this.options = options;
4896
- this.cache = new EnhancedPluginCache(options.noCache || false);
4897
- }
4898
- async getClient() {
4899
- if (!this.client) {
4900
- this.client = await getProjectClient({
4901
- project: this.options.project,
4902
- credentials: this.options.credentials,
4903
- apiUrl: this.options.apiUrl,
4904
- workspaceId: this.options.workspaceId,
4905
- headers: {
4906
- "x-multiple-integrations": "true"
4907
- }
4908
- });
4909
- }
4910
- return this.client;
4911
- }
4912
- async loadPlugins(dependencies) {
4913
- const errors = [];
4914
- const warnings = [];
4915
- const parseResult = PluginParser.parsePlugins(dependencies);
4916
- const plugins = parseResult.plugins;
4917
- errors.push(...parseResult.errors);
4918
- const duplicateWarnings = PluginParser.checkDuplicates(plugins);
4919
- warnings.push(...duplicateWarnings);
4920
- const fetchPromises = plugins.map(async (plugin) => {
4921
- try {
4922
- plugin.definition = await this.fetchPlugin(plugin.ref);
4923
- } catch {
4924
- errors.push(ValidationErrors.unknownPlugin(plugin.alias, plugin.ref.fullName));
4925
- }
4926
- });
4927
- await Promise.all(fetchPromises);
4928
- return { plugins, errors, warnings };
4929
- }
4930
- async fetchPlugin(ref) {
4931
- const cachedResolution = await this.cache.getResolution(ref.name, ref.version);
4932
- if (cachedResolution) {
4933
- const cachedDefinition = await this.cache.getDefinition(cachedResolution.pluginId, cachedResolution.updatedAt);
4934
- if (cachedDefinition) {
4935
- return cachedDefinition;
4936
- }
4937
- }
4938
- 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();
4939
5016
  const plugin = await this._findPublicPlugin(client, ref);
4940
5017
  if (!plugin) {
4941
5018
  throw new AdkError({
@@ -4944,20 +5021,18 @@ class PluginManager {
4944
5021
  message: await this._buildPluginNotFoundMessage(client, ref)
4945
5022
  });
4946
5023
  }
4947
- await this.cache.setResolution(ref.name, ref.version, plugin.id, plugin.updatedAt);
4948
- await this.cache.setDefinition(plugin.id, plugin.updatedAt, plugin);
4949
- return plugin;
5024
+ return { id: plugin.id, updatedAt: plugin.updatedAt, definition: plugin };
4950
5025
  }
4951
- async searchPlugins(query, limit = 20) {
4952
- const client = await this.getClient();
5026
+ async search(query, limit = 20) {
5027
+ const client = await this.clientFactory.getClient();
4953
5028
  const results = new Map;
4954
5029
  for await (const plugin of client.list.publicPlugins({})) {
4955
5030
  collectCatalogSearchResult(results, plugin, query);
4956
5031
  }
4957
5032
  return getSortedCatalogSearchResults(results, limit);
4958
5033
  }
4959
- async listPluginVersions(name) {
4960
- const client = await this.getClient();
5034
+ async listVersions(name) {
5035
+ const client = await this.clientFactory.getClient();
4961
5036
  const versions = new Set;
4962
5037
  for await (const plugin of client.list.publicPlugins({ name })) {
4963
5038
  versions.add(plugin.version);
@@ -4993,15 +5068,49 @@ class PluginManager {
4993
5068
  }
4994
5069
  return false;
4995
5070
  }
4996
- async getCacheStats() {
4997
- const stats = await this.cache.getStats();
4998
- return {
4999
- count: stats.resolutions.count + stats.definitions.count,
5000
- sizeBytes: stats.resolutions.sizeBytes + stats.definitions.sizeBytes
5001
- };
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
+ }
5109
+ async getCacheStats() {
5110
+ return this.service.getCacheStats();
5002
5111
  }
5003
5112
  async clearCache() {
5004
- await this.cache.clear();
5113
+ await this.service.clearCache();
5005
5114
  }
5006
5115
  }
5007
5116
 
@@ -5029,9 +5138,10 @@ class PluginRegistry {
5029
5138
 
5030
5139
  // src/dependencies/dependency-manager.ts
5031
5140
  init_agent_project();
5141
+ init_snapshot_store();
5032
5142
 
5033
5143
  class DependencyManager {
5034
- lockFile;
5144
+ snapshotStore;
5035
5145
  env;
5036
5146
  client;
5037
5147
  projectPath;
@@ -5044,8 +5154,8 @@ class DependencyManager {
5044
5154
  this.projectPath = opts.projectPath;
5045
5155
  this.env = opts.env;
5046
5156
  this.client = opts.client;
5047
- this.lockFile = new LockFile({ projectPath: opts.projectPath, env: opts.env });
5048
5157
  this.botId = opts.botId;
5158
+ this.snapshotStore = new DependencySnapshotStore({ projectPath: opts.projectPath });
5049
5159
  this.integrationRegistry = opts.integrationRegistry ?? new IntegrationRegistry;
5050
5160
  this.pluginRegistry = opts.pluginRegistry ?? new PluginRegistry;
5051
5161
  this.integrationResolver = opts.integrationResolver ?? new IntegrationResolver({ registry: this.integrationRegistry, client: this.client });
@@ -5057,14 +5167,13 @@ class DependencyManager {
5057
5167
  }
5058
5168
  static async fromProject(opts) {
5059
5169
  const project = await AgentProject.load(opts.projectPath);
5060
- const info = project.agentInfo;
5061
- if (!info) {
5170
+ const botId = opts.botId ?? DependencyManager.getProjectBotId(project, opts.env);
5171
+ if (!botId) {
5062
5172
  throw new DependencyError({
5063
5173
  code: "BOT_NOT_FOUND",
5064
- 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.`
5065
5175
  });
5066
5176
  }
5067
- const botId = opts.env === "dev" ? info.devId ?? info.botId : info.botId;
5068
5177
  return new DependencyManager({
5069
5178
  projectPath: project.path,
5070
5179
  env: opts.env,
@@ -5076,8 +5185,68 @@ class DependencyManager {
5076
5185
  pluginResolver: opts.pluginResolver
5077
5186
  });
5078
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
+ }
5079
5248
  async list(type) {
5080
- const data = await this.lockFile.read();
5249
+ const data = await this.readSnapshot({ tolerant: true });
5081
5250
  const out = [];
5082
5251
  if (!type || type === "integration") {
5083
5252
  for (const [alias, e] of Object.entries(data.integrations)) {
@@ -5104,9 +5273,9 @@ class DependencyManager {
5104
5273
  }
5105
5274
  const alias = spec.alias ?? spec.name;
5106
5275
  const version = spec.version ?? "latest";
5107
- const lock = await this.lockFile.read();
5108
- if (type === "integration" && lock.integrations[alias]) {
5109
- const existing = lock.integrations[alias];
5276
+ const snapshot = await this.readSnapshot();
5277
+ if (type === "integration" && snapshot.integrations[alias]) {
5278
+ const existing = snapshot.integrations[alias];
5110
5279
  const versionMatch = version === "latest" || existing.version === version;
5111
5280
  if (existing.enabled && versionMatch && jsonEqual(existing.config, spec.config ?? {})) {
5112
5281
  return {
@@ -5116,8 +5285,8 @@ class DependencyManager {
5116
5285
  };
5117
5286
  }
5118
5287
  }
5119
- if (type === "plugin" && lock.plugins[alias]) {
5120
- const existing = lock.plugins[alias];
5288
+ if (type === "plugin" && snapshot.plugins[alias]) {
5289
+ const existing = snapshot.plugins[alias];
5121
5290
  const versionMatch = version === "latest" || existing.version === version;
5122
5291
  if (existing.enabled && versionMatch && jsonEqual(existing.config, spec.config ?? {})) {
5123
5292
  return {
@@ -5135,28 +5304,54 @@ class DependencyManager {
5135
5304
  config: spec.config ?? {}
5136
5305
  };
5137
5306
  let installedDisabled;
5307
+ let authorizationPending = false;
5138
5308
  try {
5139
5309
  await this.integrationResolver.applyToCloud({ botId: this.botId, alias, entry: desired });
5140
5310
  } catch (err) {
5141
5311
  const missingFields = extractMissingRequiredFields(err);
5142
- 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 {
5143
5327
  throw err;
5144
- await this.integrationResolver.applyToCloud({
5145
- botId: this.botId,
5146
- alias,
5147
- entry: { ...desired, enabled: false }
5148
- });
5149
- 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
+ }
5150
5341
  }
5151
- const refreshed = await this.refreshLockFromCloud();
5152
5342
  const resolvedVersion = refreshed.integrations[alias]?.version ?? version;
5153
- 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
+ };
5154
5349
  } else {
5155
5350
  const { dependencies: resolvedDeps, autoResolved } = await this.resolvePluginDependencies({
5156
5351
  pluginName: spec.name,
5157
5352
  pluginVersion: version,
5158
5353
  userDeps: spec.dependencies ?? {},
5159
- lock
5354
+ state: snapshot
5160
5355
  });
5161
5356
  const desired = {
5162
5357
  name: spec.name,
@@ -5165,18 +5360,47 @@ class DependencyManager {
5165
5360
  config: spec.config ?? {},
5166
5361
  dependencies: resolvedDeps
5167
5362
  };
5168
- await this.pluginResolver.applyToCloud({ botId: this.botId, alias, entry: desired, lock });
5169
- 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
+ }
5170
5389
  const resolvedVersion = refreshed.plugins[alias]?.version ?? version;
5171
- 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
+ };
5172
5396
  }
5173
5397
  }
5174
5398
  async remove(type, alias) {
5175
5399
  if (type === "interface") {
5176
5400
  throw new DependencyError({ code: "BUILTIN_INTERFACE_IMMUTABLE", message: "Interfaces cannot be removed." });
5177
5401
  }
5178
- const lock = await this.lockFile.read();
5179
- 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];
5180
5404
  if (!exists)
5181
5405
  return { ok: true, noop: true };
5182
5406
  if (type === "integration") {
@@ -5184,15 +5408,15 @@ class DependencyManager {
5184
5408
  } else {
5185
5409
  await this.pluginResolver.removeFromCloud({ botId: this.botId, alias });
5186
5410
  }
5187
- await this.refreshLockFromCloud();
5411
+ await this.refreshSnapshotFromCloud();
5188
5412
  return { ok: true };
5189
5413
  }
5190
5414
  async upgrade(type, alias, version) {
5191
5415
  if (type === "interface") {
5192
5416
  throw new DependencyError({ code: "BUILTIN_INTERFACE_IMMUTABLE", message: "Interfaces cannot be upgraded." });
5193
5417
  }
5194
- const lock = await this.lockFile.read();
5195
- 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];
5196
5420
  if (!existing) {
5197
5421
  throw new DependencyError({
5198
5422
  code: type === "integration" ? "INTEGRATION_NOT_FOUND" : "PLUGIN_NOT_FOUND",
@@ -5204,8 +5428,8 @@ class DependencyManager {
5204
5428
  return { ok: true, noop: true, resource: { type, alias, name: existing.name, version: existing.version } };
5205
5429
  }
5206
5430
  const next = { ...existing, version: targetVersion };
5207
- await this.applyEntry(type, alias, next, lock);
5208
- await this.refreshLockFromCloud();
5431
+ await this.applyEntry(type, alias, next, snapshot);
5432
+ await this.refreshSnapshotFromCloud();
5209
5433
  return { ok: true, resource: { type, alias, name: existing.name, version: next.version } };
5210
5434
  }
5211
5435
  async enable(type, alias) {
@@ -5221,8 +5445,8 @@ class DependencyManager {
5221
5445
  message: "Interfaces cannot be enabled/disabled."
5222
5446
  });
5223
5447
  }
5224
- const lock = await this.lockFile.read();
5225
- 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];
5226
5450
  if (!existing) {
5227
5451
  throw new DependencyError({
5228
5452
  code: type === "integration" ? "INTEGRATION_NOT_FOUND" : "PLUGIN_NOT_FOUND",
@@ -5231,12 +5455,12 @@ class DependencyManager {
5231
5455
  }
5232
5456
  if (existing.enabled === enabled)
5233
5457
  return { ok: true, noop: true };
5234
- await this.applyEntry(type, alias, { ...existing, enabled }, lock);
5235
- const refreshedLock = await this.refreshLockFromCloud();
5236
- 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];
5237
5461
  if (!refreshedEntry || refreshedEntry.enabled !== enabled) {
5238
5462
  throw new DependencyError({
5239
- code: "LOCK_DRIFT",
5463
+ code: "SNAPSHOT_DRIFT",
5240
5464
  message: `Cloud did not persist ${type} '${alias}' as ${enabled ? "enabled" : "disabled"}.`,
5241
5465
  details: {
5242
5466
  type,
@@ -5252,8 +5476,8 @@ class DependencyManager {
5252
5476
  if (type === "interface") {
5253
5477
  throw new DependencyError({ code: "BUILTIN_INTERFACE_IMMUTABLE", message: "Interfaces cannot be configured." });
5254
5478
  }
5255
- const lock = await this.lockFile.read();
5256
- 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];
5257
5481
  if (!existing) {
5258
5482
  throw new DependencyError({
5259
5483
  code: type === "integration" ? "INTEGRATION_NOT_FOUND" : "PLUGIN_NOT_FOUND",
@@ -5270,11 +5494,11 @@ class DependencyManager {
5270
5494
  if (jsonEqual(next, existing)) {
5271
5495
  return { ok: true, noop: true, resource: { type, alias, name: existing.name, version: existing.version } };
5272
5496
  }
5273
- await this.applyEntry(type, alias, next, lock);
5274
- await this.refreshLockFromCloud();
5497
+ await this.applyEntry(type, alias, next, snapshot);
5498
+ await this.refreshSnapshotFromCloud();
5275
5499
  return { ok: true, resource: { type, alias, name: existing.name, version: existing.version } };
5276
5500
  }
5277
- async applyEntry(type, alias, entry, lock) {
5501
+ async applyEntry(type, alias, entry, state) {
5278
5502
  if (type === "integration") {
5279
5503
  await this.integrationResolver.applyToCloud({
5280
5504
  botId: this.botId,
@@ -5286,7 +5510,7 @@ class DependencyManager {
5286
5510
  botId: this.botId,
5287
5511
  alias,
5288
5512
  entry,
5289
- lock
5513
+ state
5290
5514
  });
5291
5515
  }
5292
5516
  }
@@ -5300,7 +5524,7 @@ class DependencyManager {
5300
5524
  continue;
5301
5525
  }
5302
5526
  const candidates = [];
5303
- for (const [integrationAlias, integrationEntry] of Object.entries(opts.lock.integrations)) {
5527
+ for (const [integrationAlias, integrationEntry] of Object.entries(opts.state.integrations)) {
5304
5528
  let integrationSpec;
5305
5529
  try {
5306
5530
  integrationSpec = await this.integrationRegistry.getSpec(integrationEntry.name, integrationEntry.version);
@@ -5359,85 +5583,67 @@ class DependencyManager {
5359
5583
  return [];
5360
5584
  }
5361
5585
  }
5362
- async refreshLockFromCloud() {
5363
- const { bot } = await this.client.getBot({ id: this.botId });
5364
- const previous = await this.lockFile.read();
5365
- const updated = { ...previous, ...this.cloudToLockShape(bot, previous) };
5366
- await this.lockFile.write(updated);
5367
- 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));
5368
5607
  }
5369
5608
  async diff() {
5370
- const lock = await this.lockFile.read();
5371
- const cloud = await this.readCloudAsLockShape(lock);
5372
- const delta = { addedInLock: [], removedInLock: [], changedInLock: [] };
5373
- 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)) {
5374
5613
  const cloudEntry = cloud.integrations[alias];
5375
5614
  if (!cloudEntry) {
5376
- delta.addedInLock.push({ type: "integration", alias, name: entry.name, version: entry.version });
5377
- } else if (!jsonEqual(entry, cloudEntry)) {
5378
- 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" });
5379
5618
  }
5380
5619
  }
5381
5620
  for (const [alias, entry] of Object.entries(cloud.integrations)) {
5382
- if (!lock.integrations[alias]) {
5383
- 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 });
5384
5623
  }
5385
5624
  }
5386
- for (const [alias, entry] of Object.entries(lock.plugins)) {
5625
+ for (const [alias, entry] of Object.entries(snapshot.plugins)) {
5387
5626
  const cloudEntry = cloud.plugins[alias];
5388
5627
  if (!cloudEntry) {
5389
- delta.addedInLock.push({ type: "plugin", alias, name: entry.name, version: entry.version });
5390
- } else if (!jsonEqual(entry, cloudEntry)) {
5391
- 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" });
5392
5631
  }
5393
5632
  }
5394
5633
  for (const [alias, entry] of Object.entries(cloud.plugins)) {
5395
- if (!lock.plugins[alias]) {
5396
- 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 });
5397
5636
  }
5398
5637
  }
5399
- const lockReflectsCloud = delta.addedInLock.length === 0 && delta.removedInLock.length === 0 && delta.changedInLock.length === 0;
5400
- return { target: this.env, lockReflectsCloud, delta };
5401
- }
5402
- async sync(opts) {
5403
- const previous = await this.lockFile.read();
5404
- const cloud = await this.readCloudAsLockShape(previous);
5405
- const added = [];
5406
- const removed = [];
5407
- const updated = [];
5408
- for (const [alias, entry] of Object.entries(cloud.integrations)) {
5409
- const prev = previous.integrations[alias];
5410
- if (!prev)
5411
- added.push({ type: "integration", alias });
5412
- else if (!jsonEqual(prev, entry))
5413
- updated.push({ type: "integration", alias });
5414
- }
5415
- for (const alias of Object.keys(previous.integrations)) {
5416
- if (!cloud.integrations[alias])
5417
- removed.push({ type: "integration", alias });
5418
- }
5419
- for (const [alias, entry] of Object.entries(cloud.plugins)) {
5420
- const prev = previous.plugins[alias];
5421
- if (!prev)
5422
- added.push({ type: "plugin", alias });
5423
- else if (!jsonEqual(prev, entry))
5424
- updated.push({ type: "plugin", alias });
5425
- }
5426
- for (const alias of Object.keys(previous.plugins)) {
5427
- if (!cloud.plugins[alias])
5428
- removed.push({ type: "plugin", alias });
5429
- }
5430
- if (!opts?.dryRun) {
5431
- await this.lockFile.write({ ...previous, integrations: cloud.integrations, plugins: cloud.plugins });
5432
- }
5433
- 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 };
5434
5640
  }
5435
5641
  async apply(opts) {
5436
- const lock = await this.lockFile.read();
5437
- const cloud = await this.readCloudAsLockShape(lock);
5642
+ const snapshot = await this.readSnapshot();
5643
+ const cloud = await this.readCloudSnapshot(snapshot);
5438
5644
  const actions = [];
5439
5645
  const errors = [];
5440
- for (const [alias, entry] of Object.entries(lock.integrations)) {
5646
+ for (const [alias, entry] of Object.entries(snapshot.integrations)) {
5441
5647
  const c = cloud.integrations[alias];
5442
5648
  if (!c) {
5443
5649
  actions.push({
@@ -5472,7 +5678,7 @@ class DependencyManager {
5472
5678
  }
5473
5679
  }
5474
5680
  for (const alias of Object.keys(cloud.integrations)) {
5475
- if (!lock.integrations[alias]) {
5681
+ if (!snapshot.integrations[alias]) {
5476
5682
  const c = cloud.integrations[alias];
5477
5683
  actions.push({
5478
5684
  type: "integration",
@@ -5482,7 +5688,7 @@ class DependencyManager {
5482
5688
  });
5483
5689
  }
5484
5690
  }
5485
- for (const [alias, entry] of Object.entries(lock.plugins)) {
5691
+ for (const [alias, entry] of Object.entries(snapshot.plugins)) {
5486
5692
  const c = cloud.plugins[alias];
5487
5693
  if (!c) {
5488
5694
  actions.push({
@@ -5525,7 +5731,7 @@ class DependencyManager {
5525
5731
  }
5526
5732
  }
5527
5733
  for (const alias of Object.keys(cloud.plugins)) {
5528
- if (!lock.plugins[alias]) {
5734
+ if (!snapshot.plugins[alias]) {
5529
5735
  const c = cloud.plugins[alias];
5530
5736
  actions.push({
5531
5737
  type: "plugin",
@@ -5578,8 +5784,8 @@ class DependencyManager {
5578
5784
  else
5579
5785
  await this.pluginResolver.removeFromCloud({ botId: this.botId, alias: a.alias });
5580
5786
  } else if (!appliedKeys.has(key)) {
5581
- const entry = a.type === "integration" ? lock.integrations[a.alias] : lock.plugins[a.alias];
5582
- 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);
5583
5789
  appliedKeys.add(key);
5584
5790
  }
5585
5791
  applied.push(a);
@@ -5592,7 +5798,7 @@ class DependencyManager {
5592
5798
  });
5593
5799
  }
5594
5800
  }
5595
- await this.refreshLockFromCloud();
5801
+ await this.refreshSnapshotFromCloud();
5596
5802
  return { target: this.env, applied, skipped: [], errors, dryRun: false };
5597
5803
  }
5598
5804
  async copy(opts) {
@@ -5605,85 +5811,44 @@ class DependencyManager {
5605
5811
  message: `DependencyManager constructed with env='${this.env}' but copy targets '${opts.to}'`
5606
5812
  });
5607
5813
  }
5608
- const sourceLock = new LockFile({ projectPath: this.projectPath, env: opts.from });
5609
- if (!await sourceLock.exists()) {
5814
+ const sourceBotId = opts.sourceBotId?.trim() || await this.getProjectBotId(opts.from);
5815
+ if (sourceBotId === this.botId) {
5610
5816
  throw new DependencyError({
5611
- code: "SOURCE_LOCK_MISSING",
5612
- 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}).`
5613
5819
  });
5614
5820
  }
5615
- const sourceData = await sourceLock.read();
5616
- const targetLockExists = await this.lockFile.exists();
5617
- const targetLock = await this.lockFile.read();
5618
- const snapshot = JSON.stringify(targetLock);
5619
- const merged = { ...targetLock, integrations: sourceData.integrations, plugins: sourceData.plugins };
5620
- 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);
5621
5833
  try {
5622
5834
  const result = await this.apply({ dryRun: opts.dryRun, yes: opts.yes });
5623
5835
  if (opts.dryRun) {
5624
- if (targetLockExists) {
5625
- await this.lockFile.write(JSON.parse(snapshot));
5836
+ if (targetSnapshotExists) {
5837
+ await this.writeSnapshot(JSON.parse(originalSnapshot));
5626
5838
  } else {
5627
- await this.lockFile.delete();
5839
+ await this.snapshotStore.delete(this.env);
5628
5840
  }
5629
5841
  }
5630
5842
  return result;
5631
5843
  } catch (err) {
5632
- if (targetLockExists) {
5633
- await this.lockFile.write(JSON.parse(snapshot)).catch(() => {});
5844
+ if (targetSnapshotExists) {
5845
+ await this.writeSnapshot(JSON.parse(originalSnapshot)).catch(() => {});
5634
5846
  } else {
5635
- await this.lockFile.delete().catch(() => {});
5847
+ await this.snapshotStore.delete(this.env).catch(() => {});
5636
5848
  }
5637
5849
  throw err;
5638
5850
  }
5639
5851
  }
5640
- async readCloudAsLockShape(previousLock) {
5641
- const { bot } = await this.client.getBot({ id: this.botId });
5642
- const previous = previousLock ?? await this.lockFile.read();
5643
- return this.cloudToLockShape(bot, previous);
5644
- }
5645
- cloudToLockShape(bot, previous) {
5646
- const integrations = {};
5647
- const usedIntegrationAliases = new Set;
5648
- for (const [cloudAlias, c] of Object.entries(bot.integrations ?? {})) {
5649
- const cloudName = typeof c.name === "string" ? c.name : undefined;
5650
- const alias = this.chooseCloudAlias({
5651
- cloudAlias,
5652
- cloudName,
5653
- previous: previous.integrations,
5654
- used: usedIntegrationAliases
5655
- });
5656
- usedIntegrationAliases.add(alias);
5657
- const entry = this.integrationResolver.toLockEntry(c);
5658
- integrations[alias] = entry;
5659
- }
5660
- const plugins = {};
5661
- const usedPluginAliases = new Set;
5662
- for (const [cloudAlias, c] of Object.entries(bot.plugins ?? {})) {
5663
- const cloudName = typeof c.name === "string" ? c.name : undefined;
5664
- const alias = this.chooseCloudAlias({
5665
- cloudAlias,
5666
- cloudName,
5667
- previous: previous.plugins,
5668
- used: usedPluginAliases
5669
- });
5670
- usedPluginAliases.add(alias);
5671
- const entry = this.pluginResolver.toLockEntry(c);
5672
- plugins[alias] = entry;
5673
- }
5674
- return { integrations, plugins };
5675
- }
5676
- chooseCloudAlias(opts) {
5677
- if (isFriendlyAlias(opts.cloudAlias) && opts.previous[opts.cloudAlias] && !opts.used.has(opts.cloudAlias)) {
5678
- return opts.cloudAlias;
5679
- }
5680
- if (opts.cloudName) {
5681
- const match = Object.entries(opts.previous).find(([alias, entry]) => !opts.used.has(alias) && entry.name === opts.cloudName);
5682
- if (match)
5683
- return match[0];
5684
- }
5685
- return generateFriendlyAlias(opts.cloudName, opts.cloudAlias, opts.used);
5686
- }
5687
5852
  }
5688
5853
  function formatMissingDependencySuggestion(opts) {
5689
5854
  if (opts.implementers.length === 0) {
@@ -5700,22 +5865,119 @@ function formatMissingDependencySuggestion(opts) {
5700
5865
  return lines.join(`
5701
5866
  `);
5702
5867
  }
5703
- function extractMissingRequiredFields(err) {
5704
- const message = err instanceof Error ? err.message : typeof err === "string" ? err : "";
5705
- 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 {
5706
5976
  return null;
5707
- const fields = new Set;
5708
- const re = /required property ['"]([^'"]+)['"]/g;
5709
- let match;
5710
- while ((match = re.exec(message)) !== null) {
5711
- if (match[1])
5712
- fields.add(match[1]);
5713
- }
5714
- return fields.size > 0 ? [...fields] : null;
5977
+ }
5715
5978
  }
5716
5979
 
5717
5980
  // src/dependencies/index.ts
5718
- init_lock_file();
5719
5981
  init_errors2();
5720
5982
 
5721
5983
  // src/dependencies/registry/interface-registry.ts
@@ -5733,23 +5995,80 @@ class InterfaceRegistry {
5733
5995
  return all.find((i) => i.alias === alias);
5734
5996
  }
5735
5997
  }
5998
+
5999
+ // src/dependencies/index.ts
6000
+ init_snapshot_store();
6001
+
5736
6002
  // src/dependencies/migration.ts
5737
- init_lock_file();
5738
- import * as fs13 from "fs/promises";
5739
- import * as path16 from "path";
6003
+ import * as fs11 from "fs/promises";
6004
+ import * as path15 from "path";
5740
6005
  import { Project as Project3, SyntaxKind as SyntaxKind3 } from "ts-morph";
5741
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
+
5742
6061
  // src/agent-project/config-writer.ts
5743
6062
  init_utils();
5744
6063
  init_src();
5745
6064
  import { Project as Project2, SyntaxKind as SyntaxKind2 } from "ts-morph";
5746
6065
  import { readFileSync as readFileSync2 } from "fs";
5747
- import * as path15 from "path";
6066
+ import * as path14 from "path";
5748
6067
 
5749
6068
  class ConfigWriter {
5750
6069
  configPath;
5751
6070
  constructor(projectPath) {
5752
- this.configPath = path15.join(projectPath, "agent.config.ts");
6071
+ this.configPath = path14.join(projectPath, "agent.config.ts");
5753
6072
  }
5754
6073
  loadConfig() {
5755
6074
  const project = new Project2;
@@ -6053,181 +6372,259 @@ class ConfigWriter {
6053
6372
  }
6054
6373
 
6055
6374
  // src/dependencies/migration.ts
6056
- init_errors2();
6057
6375
  init_agent_project();
6058
- async function migrateFromConfig(opts) {
6059
- const result = {
6060
- migrated: [],
6061
- warnings: [],
6062
- skipped: []
6063
- };
6064
- const project = await AgentProject.load(opts.projectPath);
6065
- const info = project.agentInfo;
6066
- const declaredAliasesForConflictCheck = await readAliasesFromConfig(opts.projectPath);
6067
- const agentConfigHasDependencies = Object.keys(declaredAliasesForConflictCheck.integrations).length > 0 || Object.keys(declaredAliasesForConflictCheck.plugins).length > 0;
6068
- const envs = ["dev", "prod"];
6069
- if (!info) {
6070
- result.warnings.push({
6071
- code: "CLOUD_FETCH_PARTIAL",
6072
- 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
6073
6396
  });
6074
- for (const env of envs) {
6075
- 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;
6076
6413
  }
6077
- } else {
6078
- for (const env of envs) {
6079
- const lockFile = new LockFile({ projectPath: opts.projectPath, env });
6080
- if (await lockFile.exists()) {
6081
- if (agentConfigHasDependencies) {
6082
- throw new DependencyError({
6083
- code: "MIGRATION_CONFLICT",
6084
- 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.`
6085
- });
6086
- }
6087
- result.skipped.push({ env, reason: "lock file already exists" });
6088
- 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" });
6089
6428
  }
6429
+ return result;
6430
+ }
6431
+ const markerSources = new Set;
6432
+ for (const env of ["dev", "prod"]) {
6090
6433
  const botId = env === "dev" ? info.devId ?? info.botId : info.botId;
6091
- if (env === "prod" && !botId) {
6434
+ if (!botId) {
6092
6435
  result.warnings.push({
6093
6436
  code: "NO_PROD_BOT",
6094
- 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."
6095
6438
  });
6096
6439
  result.skipped.push({ env, reason: "no prod bot configured" });
6097
6440
  continue;
6098
6441
  }
6099
- let bot;
6100
- try {
6101
- const r = await opts.client.getBot({ id: botId });
6102
- bot = r.bot;
6103
- } catch (err) {
6104
- result.warnings.push({
6105
- code: "CLOUD_FETCH_PARTIAL",
6106
- message: `Could not fetch cloud state for ${env}: ${err.message}`
6107
- });
6108
- 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)
6109
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");
6110
6458
  }
6111
- const lockData = {
6112
- version: 1,
6459
+ await this.snapshotStore.write(dependencySnapshotFromBot({
6460
+ bot,
6461
+ botId,
6113
6462
  env,
6114
- integrations: {},
6115
- plugins: {}
6116
- };
6117
- const declaredAliases = declaredAliasesForConflictCheck;
6118
- const usedIntegrationAliases = new Set(Object.keys(declaredAliases.integrations));
6119
- for (const [cloudAlias, cloud] of Object.entries(bot.integrations ?? {})) {
6120
- const declaredAlias = Object.entries(declaredAliases.integrations).find(([, decl]) => decl.name === cloud.name)?.[0];
6121
- const alias = declaredAlias ?? generateFriendlyAlias(cloud.name, cloudAlias, usedIntegrationAliases);
6122
- usedIntegrationAliases.add(alias);
6123
- lockData.integrations[alias] = {
6124
- name: cloud.name,
6125
- version: cloud.version,
6126
- enabled: cloud.enabled ?? false,
6127
- config: cloud.configuration ?? {}
6128
- };
6129
- }
6130
- const usedPluginAliases = new Set(Object.keys(declaredAliases.plugins));
6131
- for (const [cloudAlias, cloud] of Object.entries(bot.plugins ?? {})) {
6132
- const declaredAlias = Object.entries(declaredAliases.plugins).find(([, decl]) => decl.name === cloud.name)?.[0];
6133
- const alias = declaredAlias ?? generateFriendlyAlias(cloud.name, cloudAlias, usedPluginAliases);
6134
- usedPluginAliases.add(alias);
6135
- lockData.plugins[alias] = {
6136
- name: cloud.name,
6137
- version: cloud.version,
6138
- enabled: cloud.enabled ?? true,
6139
- config: cloud.configuration ?? {},
6140
- dependencies: Object.fromEntries(Object.entries(cloud.interfaces ?? {}).map(([k, v]) => [
6141
- k,
6142
- { integrationAlias: v.integrationAlias }
6143
- ]))
6144
- };
6145
- }
6146
- await lockFile.write(lockData);
6463
+ fetchedAt: new Date,
6464
+ previous: await this.snapshotStore.read(env, { tolerant: true })
6465
+ }));
6466
+ result.snapshotWrites?.push(env);
6147
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
+ });
6148
6484
  }
6485
+ return result;
6149
6486
  }
6150
- if (result.migrated.length > 0) {
6151
- const writer = new ConfigWriter(opts.projectPath);
6152
- await writer.removeDependenciesField();
6153
- result.warnings.push({
6154
- code: "MIGRATED_DEPENDENCIES",
6155
- message: `Migrated dependencies to ${result.migrated.map((e) => `dependencies.${e}.lock.json`).join(", ")}. Review the diff and commit.`
6156
- });
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
+ }
6157
6527
  }
6158
- return result;
6159
6528
  }
6160
- async function readAliasesFromConfig(projectPath) {
6161
- const configPath = path16.join(projectPath, "agent.config.ts");
6529
+ async function migrateFromConfig(opts) {
6530
+ return new DependencyMigrationManager(opts).run();
6531
+ }
6532
+ async function readDependenciesFromConfig(projectPath) {
6533
+ const configPath = path15.join(projectPath, "agent.config.ts");
6534
+ const empty = { version: 1, env: "dev", integrations: {}, plugins: {} };
6162
6535
  try {
6163
- await fs13.access(configPath);
6536
+ await fs11.access(configPath);
6164
6537
  } catch {
6165
- return { integrations: {}, plugins: {} };
6538
+ return empty;
6166
6539
  }
6167
- const integrations = {};
6168
- const plugins = {};
6169
6540
  try {
6170
6541
  const project = new Project3({ useInMemoryFileSystem: false });
6171
6542
  const sourceFile = project.addSourceFileAtPath(configPath);
6172
6543
  const callExpr = sourceFile.getDescendantsOfKind(SyntaxKind3.CallExpression).find((c) => c.getExpression().getText() === "defineConfig");
6173
6544
  const obj = callExpr?.getArguments()[0]?.asKind(SyntaxKind3.ObjectLiteralExpression);
6174
6545
  if (!obj)
6175
- return { integrations, plugins };
6546
+ return empty;
6176
6547
  const depsProp = obj.getProperty("dependencies");
6177
- if (!depsProp || !depsProp.isKind(SyntaxKind3.PropertyAssignment))
6178
- return { integrations, plugins };
6548
+ if (!depsProp?.isKind(SyntaxKind3.PropertyAssignment))
6549
+ return empty;
6179
6550
  const depsObj = depsProp.getInitializer()?.asKind(SyntaxKind3.ObjectLiteralExpression);
6180
6551
  if (!depsObj)
6181
- return { integrations, plugins };
6182
- for (const field of ["integrations", "plugins"]) {
6183
- const target = field === "integrations" ? integrations : plugins;
6184
- const innerProp = depsObj.getProperty(field);
6185
- if (!innerProp || !innerProp.isKind(SyntaxKind3.PropertyAssignment))
6186
- continue;
6187
- const inner = innerProp.getInitializer()?.asKind(SyntaxKind3.ObjectLiteralExpression);
6188
- if (!inner)
6189
- continue;
6190
- for (const aliasProp of inner.getProperties()) {
6191
- if (!aliasProp.isKind(SyntaxKind3.PropertyAssignment))
6192
- continue;
6193
- const alias = aliasProp.getName().replace(/['"]/g, "");
6194
- const initializer = aliasProp.getInitializer();
6195
- let nameVersion = "";
6196
- if (initializer?.isKind(SyntaxKind3.StringLiteral)) {
6197
- nameVersion = initializer.getLiteralText();
6198
- } else if (initializer?.isKind(SyntaxKind3.ObjectLiteralExpression)) {
6199
- const versionProp = initializer.getProperty("version");
6200
- if (versionProp?.isKind(SyntaxKind3.PropertyAssignment)) {
6201
- const v = versionProp.getInitializer();
6202
- if (v?.isKind(SyntaxKind3.StringLiteral))
6203
- nameVersion = v.getLiteralText();
6204
- }
6205
- }
6206
- const at = nameVersion.indexOf("@");
6207
- if (at < 0)
6208
- continue;
6209
- const name = nameVersion.slice(0, at);
6210
- const version = nameVersion.slice(at + 1);
6211
- target[alias] = { name, version };
6212
- }
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: {} };
6213
6583
  }
6214
- } catch {}
6215
- 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;
6216
6605
  }
6217
6606
  export {
6218
6607
  sortKeysDeep,
6608
+ resolveDependencyStatuses,
6219
6609
  migrateFromConfig,
6220
6610
  jsonEqual,
6611
+ isCallable,
6612
+ emptyDependencySnapshot,
6613
+ dependencyStateSchema,
6614
+ dependencySnapshotFromBot,
6615
+ computePluginStatus,
6616
+ computeIntegrationStatus,
6221
6617
  PluginResolver,
6222
6618
  PluginRegistry,
6223
- LockFile,
6224
6619
  InterfaceRegistry,
6225
6620
  IntegrationResolver,
6226
6621
  IntegrationRegistry,
6622
+ DependencySnapshotStore,
6623
+ DependencyMigrationManager,
6227
6624
  DependencyManager,
6228
6625
  DependencyError,
6229
6626
  DEPENDENCY_WARNING_CODES,
6230
6627
  DEPENDENCY_ERROR_CODES
6231
6628
  };
6232
6629
 
6233
- //# debugId=BD3DB13E662439CA64756E2164756E21
6630
+ //# debugId=63074253A1710FE164756E2164756E21