@botpress/adk 1.19.0-beta.7 → 1.19.0-beta.9

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 (67) hide show
  1. package/dist/agent-init/agent-project-generator.d.ts.map +1 -1
  2. package/dist/agent-project/agent-project.d.ts.map +1 -1
  3. package/dist/agent-project/config-writer.d.ts.map +1 -1
  4. package/dist/agent-project/dependencies-parser.d.ts.map +1 -1
  5. package/dist/agent-project/file-watcher.d.ts.map +1 -1
  6. package/dist/agent0/config/schema.d.ts.map +1 -1
  7. package/dist/agent0/config/store.d.ts +8 -3
  8. package/dist/agent0/config/store.d.ts.map +1 -1
  9. package/dist/agent0/index.js +174 -41
  10. package/dist/agent0/index.js.map +15 -13
  11. package/dist/agent0/providers/catalog.d.ts.map +1 -1
  12. package/dist/agent0/providers/registry.d.ts.map +1 -1
  13. package/dist/agent0/providers/source.d.ts +8 -3
  14. package/dist/agent0/providers/source.d.ts.map +1 -1
  15. package/dist/agent0/runtime/client.d.ts +2 -3
  16. package/dist/agent0/runtime/client.d.ts.map +1 -1
  17. package/dist/agent0/runtime/engine.d.ts +5 -0
  18. package/dist/agent0/runtime/engine.d.ts.map +1 -1
  19. package/dist/agent0/runtime/manager.d.ts +2 -3
  20. package/dist/agent0/runtime/manager.d.ts.map +1 -1
  21. package/dist/agent0/runtime/process.d.ts +9 -0
  22. package/dist/agent0/runtime/process.d.ts.map +1 -1
  23. package/dist/assets/manager.d.ts.map +1 -1
  24. package/dist/auth/credentials.d.ts.map +1 -1
  25. package/dist/auth/index.d.ts.map +1 -1
  26. package/dist/auth/service.d.ts.map +1 -1
  27. package/dist/bot-generator/generator.d.ts.map +1 -1
  28. package/dist/bot-generator/integration-sync.d.ts +2 -0
  29. package/dist/bot-generator/integration-sync.d.ts.map +1 -1
  30. package/dist/bot-generator/interface-sync.d.ts +2 -0
  31. package/dist/bot-generator/interface-sync.d.ts.map +1 -1
  32. package/dist/bot-generator/plugin-sync.d.ts +2 -0
  33. package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
  34. package/dist/cognitive/models.d.ts.map +1 -1
  35. package/dist/commands/bp-cli.d.ts.map +1 -1
  36. package/dist/commands/bp-cli.js +147 -0
  37. package/dist/commands/bp-cli.js.map +12 -0
  38. package/dist/commands/bp-dev-command.d.ts +2 -0
  39. package/dist/commands/bp-dev-command.d.ts.map +1 -1
  40. package/dist/commands/bp-dev-worker-env.d.ts +7 -0
  41. package/dist/commands/bp-dev-worker-env.d.ts.map +1 -0
  42. package/dist/config/manager.d.ts.map +1 -1
  43. package/dist/dependencies/dependency-manager.d.ts.map +1 -1
  44. package/dist/dependencies/errors.d.ts +7 -4
  45. package/dist/dependencies/errors.d.ts.map +1 -1
  46. package/dist/dependencies/index.js +255 -62
  47. package/dist/dependencies/index.js.map +23 -21
  48. package/dist/dependencies/types.d.ts +12 -12
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +807 -417
  52. package/dist/index.js.map +40 -37
  53. package/dist/integrations/hub-cache.d.ts.map +1 -1
  54. package/dist/integrations/manager.d.ts.map +1 -1
  55. package/dist/interfaces/manager.d.ts.map +1 -1
  56. package/dist/interfaces/parser.d.ts.map +1 -1
  57. package/dist/knowledge/manager.d.ts.map +1 -1
  58. package/dist/plugins/manager.d.ts.map +1 -1
  59. package/dist/runner/script-runner.d.ts.map +1 -1
  60. package/dist/secrets/manager.d.ts.map +1 -1
  61. package/dist/tables/table-manager.d.ts.map +1 -1
  62. package/dist/test-utils/mock-module.d.ts +29 -0
  63. package/dist/test-utils/mock-module.d.ts.map +1 -0
  64. package/dist/utils/require-chat.d.ts.map +1 -1
  65. package/dist/utils/source-map-optimizer.d.ts +10 -11
  66. package/dist/utils/source-map-optimizer.d.ts.map +1 -1
  67. package/package.json +7 -3
package/dist/index.js CHANGED
@@ -46,6 +46,42 @@ 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
+ // ../analytics/src/errors.ts
50
+ function isAdkError(error) {
51
+ if (error instanceof AdkError)
52
+ return true;
53
+ if (!(error instanceof Error))
54
+ return false;
55
+ return error.constructor?.__IS_ADK_BASE_ERROR === true;
56
+ }
57
+ var AdkError;
58
+ var init_errors = __esm(() => {
59
+ AdkError = class AdkError extends Error {
60
+ static __IS_ADK_BASE_ERROR = true;
61
+ code;
62
+ expected;
63
+ details;
64
+ suggestion;
65
+ constructor(opts) {
66
+ super(opts.message, opts.cause !== undefined ? { cause: opts.cause } : undefined);
67
+ this.name = this.constructor.name;
68
+ this.code = opts.code;
69
+ this.expected = opts.expected ?? false;
70
+ if (opts.details !== undefined) {
71
+ this.details = opts.details;
72
+ }
73
+ if (opts.suggestion !== undefined) {
74
+ this.suggestion = opts.suggestion;
75
+ }
76
+ }
77
+ };
78
+ });
79
+
80
+ // ../analytics/src/index.ts
81
+ var init_src = __esm(() => {
82
+ init_errors();
83
+ });
84
+
49
85
  // src/dependencies/types.ts
50
86
  import { z } from "@botpress/sdk";
51
87
  var integrationLockEntrySchema, pluginDependencyMappingSchema, pluginLockEntrySchema, lockFileSchema;
@@ -77,7 +113,8 @@ var init_types = __esm(() => {
77
113
 
78
114
  // src/dependencies/errors.ts
79
115
  var DEPENDENCY_ERROR_CODES, DependencyError, DEPENDENCY_WARNING_CODES;
80
- var init_errors = __esm(() => {
116
+ var init_errors2 = __esm(() => {
117
+ init_src();
81
118
  DEPENDENCY_ERROR_CODES = [
82
119
  "AUTH_REQUIRED",
83
120
  "INTEGRATION_NOT_FOUND",
@@ -98,16 +135,9 @@ var init_errors = __esm(() => {
98
135
  "BUILTIN_INTERFACE_IMMUTABLE",
99
136
  "PROD_CONFIRMATION_REQUIRED"
100
137
  ];
101
- DependencyError = class DependencyError extends Error {
102
- code;
103
- details;
104
- suggestion;
138
+ DependencyError = class DependencyError extends AdkError {
105
139
  constructor(opts) {
106
- super(opts.message);
107
- this.name = "DependencyError";
108
- this.code = opts.code;
109
- this.details = opts.details;
110
- this.suggestion = opts.suggestion;
140
+ super({ ...opts, expected: true });
111
141
  }
112
142
  };
113
143
  DEPENDENCY_WARNING_CODES = [
@@ -137,7 +167,7 @@ function jsonEqual(a, b) {
137
167
  }
138
168
 
139
169
  // src/dependencies/lock-file.ts
140
- import * as path from "path";
170
+ import * as path2 from "path";
141
171
  import * as fs from "fs/promises";
142
172
 
143
173
  class LockFile {
@@ -145,7 +175,7 @@ class LockFile {
145
175
  env;
146
176
  constructor(opts) {
147
177
  this.env = opts.env;
148
- this.filePath = path.join(opts.projectPath, `dependencies.${opts.env}.lock.json`);
178
+ this.filePath = path2.join(opts.projectPath, `dependencies.${opts.env}.lock.json`);
149
179
  }
150
180
  async read() {
151
181
  let raw;
@@ -196,7 +226,7 @@ class LockFile {
196
226
  }
197
227
  var init_lock_file = __esm(() => {
198
228
  init_types();
199
- init_errors();
229
+ init_errors2();
200
230
  });
201
231
 
202
232
  // src/agent-project/types.ts
@@ -286,24 +316,24 @@ class ValidationErrors {
286
316
  static isValidationError(error) {
287
317
  return error !== null && typeof error === "object" && "$type" in error && error.$type === "ValidationError";
288
318
  }
289
- static directoryNotFound(path2) {
319
+ static directoryNotFound(path3) {
290
320
  return {
291
321
  $type: ValidationErrors.$type,
292
322
  code: "DIRECTORY_NOT_FOUND" /* DIRECTORY_NOT_FOUND */,
293
323
  severity: "error" /* ERROR */,
294
- message: `Project directory not found: ${path2}`,
324
+ message: `Project directory not found: ${path3}`,
295
325
  hint: "Ensure the directory exists and you have permission to access it",
296
- context: { path: path2 }
326
+ context: { path: path3 }
297
327
  };
298
328
  }
299
- static directoryAccessError(path2, error) {
329
+ static directoryAccessError(path3, error) {
300
330
  return {
301
331
  $type: ValidationErrors.$type,
302
332
  code: "DIRECTORY_ACCESS_ERROR" /* DIRECTORY_ACCESS_ERROR */,
303
333
  severity: "error" /* ERROR */,
304
334
  message: `Cannot access project directory: ${error}`,
305
335
  hint: "Check file system permissions",
306
- context: { path: path2, error }
336
+ context: { path: path3, error }
307
337
  };
308
338
  }
309
339
  static requiredFileMissing(file) {
@@ -673,9 +703,9 @@ var init_constants = __esm(() => {
673
703
 
674
704
  // src/agent-project/agent-resolver.ts
675
705
  import fs2 from "fs/promises";
676
- import path2 from "path";
706
+ import path3 from "path";
677
707
  async function readLocalInfo(agentPath) {
678
- const localPath = path2.join(agentPath, "agent.local.json");
708
+ const localPath = path3.join(agentPath, "agent.local.json");
679
709
  try {
680
710
  const localContent = await fs2.readFile(localPath, "utf-8");
681
711
  const localData = JSON.parse(localContent);
@@ -711,7 +741,7 @@ function applyLocalOverrides(agentInfo, localInfo) {
711
741
  }
712
742
  async function resolveAgent(agentPath, options = {}) {
713
743
  const { required = false, requireWorkspace = false, requireBot = false } = options;
714
- const agentJsonPath = path2.join(agentPath, "agent.json");
744
+ const agentJsonPath = path3.join(agentPath, "agent.json");
715
745
  const localInfo = await readLocalInfo(agentPath);
716
746
  let agentInfo = null;
717
747
  try {
@@ -776,16 +806,16 @@ __export(exports_credentials, {
776
806
  CredentialsManager: () => CredentialsManager
777
807
  });
778
808
  import fs3 from "fs/promises";
779
- import path3 from "path";
780
- import os from "os";
809
+ import path4 from "path";
810
+ import os2 from "os";
781
811
 
782
812
  class CredentialsManager {
783
813
  credentialsPath;
784
814
  configDir;
785
815
  profileOverride;
786
816
  constructor() {
787
- this.configDir = path3.join(os.homedir(), ".adk");
788
- this.credentialsPath = path3.join(this.configDir, "credentials");
817
+ this.configDir = path4.join(os2.homedir(), ".adk");
818
+ this.credentialsPath = path4.join(this.configDir, "credentials");
789
819
  }
790
820
  setProfileOverride(profile) {
791
821
  this.profileOverride = profile;
@@ -880,7 +910,11 @@ class CredentialsManager {
880
910
  async setCurrentProfile(profileName) {
881
911
  const store = await this.readCredentials();
882
912
  if (!store.profiles[profileName]) {
883
- throw new Error(`Profile '${profileName}' not found`);
913
+ throw new AdkError({
914
+ code: "PROFILE_NOT_FOUND",
915
+ message: `Profile '${profileName}' not found`,
916
+ expected: true
917
+ });
884
918
  }
885
919
  if (!store.profileMetadata) {
886
920
  store.profileMetadata = {};
@@ -895,7 +929,11 @@ class CredentialsManager {
895
929
  async deleteProfile(profileName) {
896
930
  const store = await this.readCredentials();
897
931
  if (!store.profiles[profileName]) {
898
- throw new Error(`Profile '${profileName}' not found`);
932
+ throw new AdkError({
933
+ code: "PROFILE_NOT_FOUND",
934
+ message: `Profile '${profileName}' not found`,
935
+ expected: true
936
+ });
899
937
  }
900
938
  delete store.profiles[profileName];
901
939
  delete store.profileMetadata?.[profileName];
@@ -910,7 +948,12 @@ class CredentialsManager {
910
948
  const credentials = await this.getCredentials(profileName);
911
949
  if (!credentials) {
912
950
  const displayName = profileName || "default";
913
- throw new Error(`No credentials found for profile '${displayName}'. ` + `Please run 'adk login' to authenticate.`);
951
+ throw new AdkError({
952
+ code: "NOT_AUTHENTICATED",
953
+ message: `No credentials found for profile '${displayName}'. ` + `Please run 'adk login' to authenticate.`,
954
+ expected: true,
955
+ suggestion: "Run 'adk login' to authenticate."
956
+ });
914
957
  }
915
958
  return credentials;
916
959
  }
@@ -945,7 +988,12 @@ class CredentialsManager {
945
988
  const profileName = store.currentProfile || "default";
946
989
  const activeCredentials = store.profiles[profileName];
947
990
  if (!activeCredentials) {
948
- throw new Error(`No credentials found for profile '${profileName}'. ` + `Please run 'adk login' to authenticate.`);
991
+ throw new AdkError({
992
+ code: "NOT_AUTHENTICATED",
993
+ message: `No credentials found for profile '${profileName}'. ` + `Please run 'adk login' to authenticate.`,
994
+ expected: true,
995
+ suggestion: "Run 'adk login' to authenticate."
996
+ });
949
997
  }
950
998
  baseCredentials = activeCredentials;
951
999
  }
@@ -959,6 +1007,7 @@ class CredentialsManager {
959
1007
  }
960
1008
  }
961
1009
  var init_credentials = __esm(() => {
1010
+ init_src();
962
1011
  init_agent_resolver();
963
1012
  });
964
1013
 
@@ -972,7 +1021,11 @@ class AuthService {
972
1021
  }
973
1022
  async validateToken(token) {
974
1023
  if (!token || !token.startsWith("bp_")) {
975
- throw new Error('Invalid token format. Token should start with "bp_"');
1024
+ throw new AdkError({
1025
+ code: "INVALID_TOKEN_FORMAT",
1026
+ message: 'Invalid token format. Token should start with "bp_"',
1027
+ expected: true
1028
+ });
976
1029
  }
977
1030
  try {
978
1031
  const client = new Client({
@@ -996,10 +1049,20 @@ class AuthService {
996
1049
  } catch (error) {
997
1050
  if (error instanceof Error) {
998
1051
  if (error.message.includes("401") || error.message.includes("Unauthorized")) {
999
- throw new Error("Invalid token. Please check your API token and try again.");
1052
+ throw new AdkError({
1053
+ code: "AUTH_FAILED",
1054
+ message: "Invalid token. Please check your API token and try again.",
1055
+ expected: true,
1056
+ cause: error
1057
+ });
1000
1058
  }
1001
1059
  if (error.message.includes("Network") || error.message.includes("ENOTFOUND")) {
1002
- throw new Error(`Unable to connect to ${this.apiUrl}. Please check your internet connection and API URL.`);
1060
+ throw new AdkError({
1061
+ code: "NETWORK_ERROR",
1062
+ message: `Unable to connect to ${this.apiUrl}. Please check your internet connection and API URL.`,
1063
+ expected: true,
1064
+ cause: error
1065
+ });
1003
1066
  }
1004
1067
  }
1005
1068
  throw error;
@@ -1014,17 +1077,19 @@ class AuthService {
1014
1077
  }
1015
1078
  }
1016
1079
  }
1017
- var init_service = () => {};
1080
+ var init_service = __esm(() => {
1081
+ init_src();
1082
+ });
1018
1083
 
1019
1084
  // src/auth/bp-cli-import.ts
1020
1085
  import fs4 from "fs/promises";
1021
- import path4 from "path";
1022
- import os2 from "os";
1086
+ import path5 from "path";
1087
+ import os3 from "os";
1023
1088
 
1024
1089
  class BpCliImporter {
1025
1090
  bpCachePath;
1026
1091
  constructor() {
1027
- this.bpCachePath = path4.join(os2.homedir(), ".botpress", "global.cache.json");
1092
+ this.bpCachePath = path5.join(os3.homedir(), ".botpress", "global.cache.json");
1028
1093
  }
1029
1094
  async hasBpCliCredentials() {
1030
1095
  try {
@@ -1195,7 +1260,12 @@ async function resolveProjectCredentials(options = {}) {
1195
1260
  async function resolveWorkspaceCredentials(options = {}) {
1196
1261
  const credentials = await resolveProjectCredentials(options);
1197
1262
  if (!credentials.workspaceId) {
1198
- throw new Error('No workspace ID found. Please login again with "adk login" or link your agent first.');
1263
+ throw new AdkError({
1264
+ code: "WORKSPACE_ID_MISSING",
1265
+ message: 'No workspace ID found. Please login again with "adk login" or link your agent first.',
1266
+ expected: true,
1267
+ suggestion: 'Login again with "adk login" or link your agent first.'
1268
+ });
1199
1269
  }
1200
1270
  return {
1201
1271
  ...credentials,
@@ -1205,7 +1275,12 @@ async function resolveWorkspaceCredentials(options = {}) {
1205
1275
  async function resolveBotCredentials(options = {}) {
1206
1276
  const credentials = await resolveWorkspaceCredentials(options);
1207
1277
  if (!credentials.botId) {
1208
- throw new Error("No bot ID found. Please link your agent first.");
1278
+ throw new AdkError({
1279
+ code: "BOT_ID_MISSING",
1280
+ message: "No bot ID found. Please link your agent first.",
1281
+ expected: true,
1282
+ suggestion: "Link your agent first."
1283
+ });
1209
1284
  }
1210
1285
  return {
1211
1286
  ...credentials,
@@ -1269,6 +1344,7 @@ var auth, projectClientCache, MAX_PROJECT_CLIENT_CACHE_ENTRIES = 32, stableStrin
1269
1344
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
1270
1345
  };
1271
1346
  var init_auth = __esm(() => {
1347
+ init_src();
1272
1348
  init_credentials();
1273
1349
  init_service();
1274
1350
  init_agent_resolver();
@@ -1280,8 +1356,8 @@ var init_auth = __esm(() => {
1280
1356
 
1281
1357
  // src/integrations/enhanced-cache.ts
1282
1358
  import fs5 from "fs/promises";
1283
- import path5 from "path";
1284
- import os3 from "os";
1359
+ import path6 from "path";
1360
+ import os4 from "os";
1285
1361
 
1286
1362
  class EnhancedIntegrationCache {
1287
1363
  cacheDir;
@@ -1290,9 +1366,9 @@ class EnhancedIntegrationCache {
1290
1366
  noCache;
1291
1367
  constructor(noCache = false) {
1292
1368
  this.noCache = noCache;
1293
- this.cacheDir = path5.join(os3.homedir(), ".adk", "cache", "integrations");
1294
- this.resolutionsDir = path5.join(this.cacheDir, "resolutions");
1295
- this.definitionsDir = path5.join(this.cacheDir, "definitions");
1369
+ this.cacheDir = path6.join(os4.homedir(), ".adk", "cache", "integrations");
1370
+ this.resolutionsDir = path6.join(this.cacheDir, "resolutions");
1371
+ this.definitionsDir = path6.join(this.cacheDir, "definitions");
1296
1372
  }
1297
1373
  async ensureCacheDirs() {
1298
1374
  await fs5.mkdir(this.resolutionsDir, { recursive: true });
@@ -1304,7 +1380,7 @@ class EnhancedIntegrationCache {
1304
1380
  }
1305
1381
  try {
1306
1382
  const key = this.getResolutionKey(name, version, workspace);
1307
- const cachePath = path5.join(this.resolutionsDir, `${key}.json`);
1383
+ const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
1308
1384
  const data = await fs5.readFile(cachePath, "utf-8");
1309
1385
  const resolution = JSON.parse(data);
1310
1386
  const cachedAt = new Date(resolution.cachedAt);
@@ -1321,13 +1397,13 @@ class EnhancedIntegrationCache {
1321
1397
  async setResolution(name, version, workspace, integrationId, updatedAt) {
1322
1398
  await this.ensureCacheDirs();
1323
1399
  const key = this.getResolutionKey(name, version, workspace);
1324
- const cachePath = path5.join(this.resolutionsDir, `${key}.json`);
1400
+ const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
1325
1401
  const resolution = {
1326
1402
  integrationId,
1327
1403
  updatedAt,
1328
1404
  cachedAt: new Date().toISOString()
1329
1405
  };
1330
- await fs5.writeFile(cachePath, JSON.stringify(resolution, null, 2));
1406
+ await fs5.writeFile(cachePath, JSON.stringify(resolution));
1331
1407
  }
1332
1408
  async getDefinition(integrationId, updatedAt) {
1333
1409
  if (this.noCache) {
@@ -1335,7 +1411,7 @@ class EnhancedIntegrationCache {
1335
1411
  }
1336
1412
  try {
1337
1413
  const key = this.getDefinitionKey(integrationId, updatedAt);
1338
- const cachePath = path5.join(this.definitionsDir, `${key}.json`);
1414
+ const cachePath = path6.join(this.definitionsDir, `${key}.json`);
1339
1415
  const data = await fs5.readFile(cachePath, "utf-8");
1340
1416
  const cached = JSON.parse(data);
1341
1417
  return cached.definition;
@@ -1346,19 +1422,19 @@ class EnhancedIntegrationCache {
1346
1422
  async setDefinition(integrationId, updatedAt, definition) {
1347
1423
  await this.ensureCacheDirs();
1348
1424
  const key = this.getDefinitionKey(integrationId, updatedAt);
1349
- const cachePath = path5.join(this.definitionsDir, `${key}.json`);
1425
+ const cachePath = path6.join(this.definitionsDir, `${key}.json`);
1350
1426
  const cached = {
1351
1427
  definition,
1352
1428
  cachedAt: new Date().toISOString()
1353
1429
  };
1354
- await fs5.writeFile(cachePath, JSON.stringify(cached, null, 2));
1430
+ await fs5.writeFile(cachePath, JSON.stringify(cached));
1355
1431
  }
1356
1432
  async clear() {
1357
1433
  try {
1358
1434
  const resolutionFiles = await fs5.readdir(this.resolutionsDir);
1359
- await Promise.all(resolutionFiles.map((file) => fs5.unlink(path5.join(this.resolutionsDir, file))));
1435
+ await Promise.all(resolutionFiles.map((file) => fs5.unlink(path6.join(this.resolutionsDir, file))));
1360
1436
  const definitionFiles = await fs5.readdir(this.definitionsDir);
1361
- await Promise.all(definitionFiles.map((file) => fs5.unlink(path5.join(this.definitionsDir, file))));
1437
+ await Promise.all(definitionFiles.map((file) => fs5.unlink(path6.join(this.definitionsDir, file))));
1362
1438
  } catch {}
1363
1439
  }
1364
1440
  async getStats() {
@@ -1367,7 +1443,7 @@ class EnhancedIntegrationCache {
1367
1443
  const files = await fs5.readdir(dir);
1368
1444
  let totalSize = 0;
1369
1445
  for (const file of files) {
1370
- const stats = await fs5.stat(path5.join(dir, file));
1446
+ const stats = await fs5.stat(path6.join(dir, file));
1371
1447
  totalSize += stats.size;
1372
1448
  }
1373
1449
  return {
@@ -1406,7 +1482,11 @@ class IntegrationParser {
1406
1482
  static parseIntegrationRef(versionString) {
1407
1483
  const result = integrationRefSchema.safeParse(versionString);
1408
1484
  if (!result.success) {
1409
- throw new Error(result.error.errors[0]?.message || "Invalid integration version format");
1485
+ throw new AdkError({
1486
+ code: "INVALID_VERSION_FORMAT",
1487
+ expected: true,
1488
+ message: result.error.errors[0]?.message || "Invalid integration version format"
1489
+ });
1410
1490
  }
1411
1491
  return result.data;
1412
1492
  }
@@ -1483,7 +1563,11 @@ class PluginParser {
1483
1563
  static parsePluginRef(versionString) {
1484
1564
  const result = pluginRefSchema.safeParse(versionString);
1485
1565
  if (!result.success) {
1486
- throw new Error(result.error.errors[0]?.message || "Invalid plugin version format");
1566
+ throw new AdkError({
1567
+ code: "INVALID_VERSION_FORMAT",
1568
+ expected: true,
1569
+ message: result.error.errors[0]?.message || "Invalid plugin version format"
1570
+ });
1487
1571
  }
1488
1572
  return result.data;
1489
1573
  }
@@ -1570,6 +1654,7 @@ class PluginParser {
1570
1654
  }
1571
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;
1572
1656
  var init_dependencies_parser = __esm(() => {
1657
+ init_src();
1573
1658
  init_validation_errors();
1574
1659
  INTEGRATION_ALIAS_REGEX = /^(?:[a-z][a-z0-9_-]*\/)?[a-z][a-z0-9_-]*$/;
1575
1660
  integrationRefSchema = z3.string().transform((val, ctx) => {
@@ -1866,11 +1951,19 @@ class IntegrationManager {
1866
1951
  const latestExists = await this._findPrivateOrPublicIntegration(client, { ...ref, version: "latest" });
1867
1952
  if (latestExists) {
1868
1953
  const scope = ref.workspace ? `workspace "${ref.workspace}"` : "the official Botpress hub";
1869
- return new Error(`Integration "${ref.name}" version "${ref.version}" not found in ${scope} ` + `(latest is ${latestExists.version}). Run 'adk info ${ref.fullName}' to see available versions.`);
1954
+ return new AdkError({
1955
+ 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.`,
1957
+ expected: true
1958
+ });
1870
1959
  }
1871
1960
  }
1872
1961
  if (!ref.workspace) {
1873
- return new Error(`Integration "${ref.name}" not found in the official Botpress hub`);
1962
+ return new AdkError({
1963
+ code: "INTEGRATION_NOT_FOUND",
1964
+ message: `Integration "${ref.name}" not found in the official Botpress hub`,
1965
+ expected: true
1966
+ });
1874
1967
  }
1875
1968
  let currentWorkspaceHandle;
1876
1969
  let workspaceId;
@@ -1887,12 +1980,25 @@ class IntegrationManager {
1887
1980
  currentWorkspaceHandle = currentWorkspace?.handle;
1888
1981
  }
1889
1982
  } catch {
1890
- return new Error(`Integration "${ref.name}" not found in workspace "${ref.workspace}"`);
1983
+ return new AdkError({
1984
+ code: "INTEGRATION_NOT_FOUND",
1985
+ message: `Integration "${ref.name}" not found in workspace "${ref.workspace}"`,
1986
+ expected: true
1987
+ });
1891
1988
  }
1892
1989
  if (currentWorkspaceHandle === ref.workspace) {
1893
- return new Error(`Integration "${ref.name}" not found in workspace "${ref.workspace}" (workspaceId: ${workspaceId}). ` + `Are you sure you published the integration? ` + `Run 'adk deploy' to publish it to your workspace.`);
1990
+ return new AdkError({
1991
+ code: "INTEGRATION_NOT_FOUND",
1992
+ message: `Integration "${ref.name}" not found in workspace "${ref.workspace}" (workspaceId: ${workspaceId}). ` + `Are you sure you published the integration? ` + `Run 'adk deploy' to publish it to your workspace.`,
1993
+ expected: true,
1994
+ suggestion: "Are you sure you published the integration? Run 'adk deploy' to publish it to your workspace."
1995
+ });
1894
1996
  }
1895
- return new Error(`Integration "${ref.name}" not found in workspace "${ref.workspace}" (current workspaceId: ${workspaceId}). ` + `This integration may be private. Private integrations can only be installed in the same workspace. ` + `If you want to share this integration with other workspaces, deploy it with --visibility="unlisted" or --visibility="public".`);
1997
+ return new AdkError({
1998
+ code: "INTEGRATION_NOT_FOUND",
1999
+ message: `Integration "${ref.name}" not found in workspace "${ref.workspace}" (current workspaceId: ${workspaceId}). ` + `This integration may be private. Private integrations can only be installed in the same workspace. ` + `If you want to share this integration with other workspaces, deploy it with --visibility="unlisted" or --visibility="public".`,
2000
+ expected: true
2001
+ });
1896
2002
  }
1897
2003
  validateIntegration(integration) {
1898
2004
  const errors = [];
@@ -1951,6 +2057,7 @@ function toHubCacheEntry(integration) {
1951
2057
  };
1952
2058
  }
1953
2059
  var init_manager = __esm(() => {
2060
+ init_src();
1954
2061
  init_auth();
1955
2062
  init_enhanced_cache();
1956
2063
  init_dependencies_parser();
@@ -1966,7 +2073,7 @@ var defaultAdkFolder = ".adk";
1966
2073
 
1967
2074
  // src/assets/cache.ts
1968
2075
  import fs7 from "fs/promises";
1969
- import path7 from "path";
2076
+ import path8 from "path";
1970
2077
 
1971
2078
  class AssetsCacheManager {
1972
2079
  projectPath;
@@ -1974,7 +2081,7 @@ class AssetsCacheManager {
1974
2081
  cache = null;
1975
2082
  constructor(projectPath) {
1976
2083
  this.projectPath = projectPath;
1977
- this.cachePath = path7.join(projectPath, defaultAdkFolder, "assets-cache.json");
2084
+ this.cachePath = path8.join(projectPath, defaultAdkFolder, "assets-cache.json");
1978
2085
  }
1979
2086
  async load() {
1980
2087
  if (this.cache) {
@@ -1996,7 +2103,7 @@ class AssetsCacheManager {
1996
2103
  if (!this.cache) {
1997
2104
  return;
1998
2105
  }
1999
- const cacheDir = path7.dirname(this.cachePath);
2106
+ const cacheDir = path8.dirname(this.cachePath);
2000
2107
  await fs7.mkdir(cacheDir, { recursive: true });
2001
2108
  await fs7.writeFile(this.cachePath, JSON.stringify(this.cache, null, 2), "utf-8");
2002
2109
  }
@@ -2042,7 +2149,7 @@ var init_cache = () => {};
2042
2149
 
2043
2150
  // src/assets/manager.ts
2044
2151
  import fs8 from "fs/promises";
2045
- import path8 from "path";
2152
+ import path9 from "path";
2046
2153
  import crypto from "crypto";
2047
2154
 
2048
2155
  class AssetsManager {
@@ -2053,14 +2160,19 @@ class AssetsManager {
2053
2160
  cacheManager;
2054
2161
  constructor(options) {
2055
2162
  this.projectPath = options.projectPath;
2056
- this.assetsPath = path8.join(this.projectPath, "assets");
2163
+ this.assetsPath = path9.join(this.projectPath, "assets");
2057
2164
  this.botId = options.botId;
2058
2165
  this.cacheManager = new AssetsCacheManager(this.projectPath);
2059
2166
  }
2060
2167
  async getClient() {
2061
2168
  if (!this.client) {
2062
2169
  if (!this.botId) {
2063
- throw new Error("Bot ID is required for asset operations. Please deploy your agent first or create agent.json with botId and workspaceId.");
2170
+ throw new AdkError({
2171
+ code: "BOT_ID_REQUIRED",
2172
+ message: "Bot ID is required for asset operations. Please deploy your agent first or create agent.json with botId and workspaceId.",
2173
+ expected: true,
2174
+ suggestion: "Deploy your agent first or create agent.json with botId and workspaceId."
2175
+ });
2064
2176
  }
2065
2177
  this.client = await getProjectClient({
2066
2178
  project: { path: this.projectPath },
@@ -2074,7 +2186,12 @@ class AssetsManager {
2074
2186
  }
2075
2187
  assertBotId(operation) {
2076
2188
  if (!this.botId) {
2077
- throw new Error(`Operation "${operation}" requires a bot ID. ` + "Please deploy your agent first or create agent.json with botId and workspaceId.");
2189
+ throw new AdkError({
2190
+ code: "BOT_ID_REQUIRED",
2191
+ message: `Operation "${operation}" requires a bot ID. ` + "Please deploy your agent first or create agent.json with botId and workspaceId.",
2192
+ expected: true,
2193
+ suggestion: "Deploy your agent first or create agent.json with botId and workspaceId."
2194
+ });
2078
2195
  }
2079
2196
  }
2080
2197
  async hasAssetsDirectory() {
@@ -2095,14 +2212,14 @@ class AssetsManager {
2095
2212
  try {
2096
2213
  const stats = await fs8.stat(filePath);
2097
2214
  if (stats.isFile()) {
2098
- const relativePath = path8.relative(this.assetsPath, filePath);
2215
+ const relativePath = path9.relative(this.assetsPath, filePath);
2099
2216
  const content = await fs8.readFile(filePath);
2100
2217
  const hash = this.calculateHash(content);
2101
2218
  const mime = this.getMimeType(filePath);
2102
2219
  assets.push({
2103
2220
  relativePath,
2104
2221
  absolutePath: filePath,
2105
- name: path8.basename(filePath),
2222
+ name: path9.basename(filePath),
2106
2223
  size: stats.size,
2107
2224
  mime,
2108
2225
  hash,
@@ -2130,7 +2247,7 @@ class AssetsManager {
2130
2247
  });
2131
2248
  return response.files.map((file) => ({
2132
2249
  path: file.tags?.path || file.key,
2133
- name: path8.basename(file.tags?.path || file.key),
2250
+ name: path9.basename(file.tags?.path || file.key),
2134
2251
  size: file.size || 0,
2135
2252
  mime: file.contentType,
2136
2253
  hash: file.tags?.hash || "",
@@ -2140,7 +2257,12 @@ class AssetsManager {
2140
2257
  url: file.url || ""
2141
2258
  }));
2142
2259
  } catch (error) {
2143
- throw new Error(`Failed to fetch remote assets: ${error}`);
2260
+ throw new AdkError({
2261
+ code: "ASSET_FETCH_FAILED",
2262
+ message: `Failed to fetch remote assets: ${error}`,
2263
+ expected: true,
2264
+ cause: error
2265
+ });
2144
2266
  }
2145
2267
  }
2146
2268
  async createSyncPlan() {
@@ -2358,7 +2480,7 @@ declare global {
2358
2480
  async scanDirectory(dir, files = []) {
2359
2481
  const items = await fs8.readdir(dir);
2360
2482
  for (const item of items) {
2361
- const fullPath = path8.join(dir, item);
2483
+ const fullPath = path9.join(dir, item);
2362
2484
  const stats = await fs8.stat(fullPath);
2363
2485
  if (stats.isDirectory()) {
2364
2486
  await this.scanDirectory(fullPath, files);
@@ -2372,7 +2494,7 @@ declare global {
2372
2494
  return crypto.createHash("sha256").update(content).digest("hex");
2373
2495
  }
2374
2496
  getMimeType(filePath) {
2375
- const ext = path8.extname(filePath).toLowerCase();
2497
+ const ext = path9.extname(filePath).toLowerCase();
2376
2498
  const mimeTypes = {
2377
2499
  ".png": "image/png",
2378
2500
  ".jpg": "image/jpeg",
@@ -2399,6 +2521,7 @@ declare global {
2399
2521
  }
2400
2522
  }
2401
2523
  var init_manager2 = __esm(() => {
2524
+ init_src();
2402
2525
  init_auth();
2403
2526
  init_types3();
2404
2527
  init_cache();
@@ -2407,10 +2530,10 @@ var init_manager2 = __esm(() => {
2407
2530
  // src/utils/fs.ts
2408
2531
  import { mkdir, writeFile as writeFile2 } from "fs/promises";
2409
2532
  import { parse } from "path";
2410
- var createFile = async (path9, content) => {
2411
- const file = parse(path9);
2533
+ var createFile = async (path10, content) => {
2534
+ const file = parse(path10);
2412
2535
  await mkdir(file.dir, { recursive: true });
2413
- await writeFile2(path9, content);
2536
+ await writeFile2(path10, content);
2414
2537
  };
2415
2538
  var init_fs = () => {};
2416
2539
 
@@ -2429,15 +2552,15 @@ var init_assets = __esm(() => {
2429
2552
 
2430
2553
  // src/integrations/cache.ts
2431
2554
  import fs9 from "fs/promises";
2432
- import path9 from "path";
2433
- import os5 from "os";
2555
+ import path10 from "path";
2556
+ import os6 from "os";
2434
2557
 
2435
2558
  class IntegrationCache {
2436
2559
  cacheDir;
2437
2560
  integrationsDir;
2438
2561
  constructor() {
2439
- this.cacheDir = path9.join(os5.homedir(), ".adk", "cache");
2440
- this.integrationsDir = path9.join(this.cacheDir, "integrations");
2562
+ this.cacheDir = path10.join(os6.homedir(), ".adk", "cache");
2563
+ this.integrationsDir = path10.join(this.cacheDir, "integrations");
2441
2564
  }
2442
2565
  async ensureCacheDir() {
2443
2566
  await fs9.mkdir(this.integrationsDir, { recursive: true });
@@ -2450,7 +2573,7 @@ class IntegrationCache {
2450
2573
  async get(integrationId, updatedAt) {
2451
2574
  try {
2452
2575
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2453
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2576
+ const cachePath = path10.join(this.integrationsDir, cacheKey);
2454
2577
  const data = await fs9.readFile(cachePath, "utf-8");
2455
2578
  const cached = JSON.parse(data);
2456
2579
  if (cached.expiresAt) {
@@ -2468,7 +2591,7 @@ class IntegrationCache {
2468
2591
  async set(integrationId, updatedAt, definition, ttlHours = 24 * 7) {
2469
2592
  await this.ensureCacheDir();
2470
2593
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2471
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2594
+ const cachePath = path10.join(this.integrationsDir, cacheKey);
2472
2595
  const expiresAt = new Date;
2473
2596
  expiresAt.setHours(expiresAt.getHours() + ttlHours);
2474
2597
  const cacheEntry = {
@@ -2481,14 +2604,14 @@ class IntegrationCache {
2481
2604
  async remove(integrationId, updatedAt) {
2482
2605
  try {
2483
2606
  const cacheKey = this.getCacheKey(integrationId, updatedAt);
2484
- const cachePath = path9.join(this.integrationsDir, cacheKey);
2607
+ const cachePath = path10.join(this.integrationsDir, cacheKey);
2485
2608
  await fs9.unlink(cachePath);
2486
2609
  } catch {}
2487
2610
  }
2488
2611
  async clear() {
2489
2612
  try {
2490
2613
  const files = await fs9.readdir(this.integrationsDir);
2491
- await Promise.all(files.map((file) => fs9.unlink(path9.join(this.integrationsDir, file))));
2614
+ await Promise.all(files.map((file) => fs9.unlink(path10.join(this.integrationsDir, file))));
2492
2615
  } catch {}
2493
2616
  }
2494
2617
  async getStats() {
@@ -2496,7 +2619,7 @@ class IntegrationCache {
2496
2619
  const files = await fs9.readdir(this.integrationsDir);
2497
2620
  let totalSize = 0;
2498
2621
  for (const file of files) {
2499
- const stats = await fs9.stat(path9.join(this.integrationsDir, file));
2622
+ const stats = await fs9.stat(path10.join(this.integrationsDir, file));
2500
2623
  totalSize += stats.size;
2501
2624
  }
2502
2625
  return {
@@ -2513,15 +2636,16 @@ var init_cache2 = () => {};
2513
2636
  // src/integrations/hub-cache.ts
2514
2637
  import { Client as Client3 } from "@botpress/client";
2515
2638
  import * as fs10 from "fs/promises";
2516
- import * as path10 from "path";
2517
- import * as os6 from "os";
2639
+ import * as path11 from "path";
2640
+ import * as os7 from "os";
2518
2641
  var HubCache;
2519
2642
  var init_hub_cache = __esm(() => {
2643
+ init_src();
2520
2644
  init_auth();
2521
2645
  HubCache = class HubCache {
2522
2646
  static CACHE_FILE = "botpress-hub-cache.json";
2523
- static CACHE_DIR = path10.join(os6.homedir(), ".adk", "cache");
2524
- static CACHE_PATH = path10.join(HubCache.CACHE_DIR, HubCache.CACHE_FILE);
2647
+ static CACHE_DIR = path11.join(os7.homedir(), ".adk", "cache");
2648
+ static CACHE_PATH = path11.join(HubCache.CACHE_DIR, HubCache.CACHE_FILE);
2525
2649
  static CACHE_DURATION = 30 * 60 * 1000;
2526
2650
  client;
2527
2651
  constructor() {}
@@ -2529,7 +2653,12 @@ var init_hub_cache = __esm(() => {
2529
2653
  if (!this.client) {
2530
2654
  const credentials = await auth.getActiveCredentials();
2531
2655
  if (!credentials.workspaceId) {
2532
- throw new Error('No workspace ID found in current profile. Please login again with "adk login"');
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
+ });
2533
2662
  }
2534
2663
  this.client = new Client3({
2535
2664
  token: credentials.token,
@@ -2618,7 +2747,12 @@ var init_hub_cache = __esm(() => {
2618
2747
  };
2619
2748
  await this.saveCache(newCache);
2620
2749
  } catch (error) {
2621
- throw new Error(`Failed to refresh hub cache: ${error instanceof Error ? error.message : String(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
+ });
2622
2756
  }
2623
2757
  }
2624
2758
  async getAllIntegrations() {
@@ -2768,8 +2902,8 @@ var init_integrations = __esm(() => {
2768
2902
 
2769
2903
  // src/interfaces/enhanced-cache.ts
2770
2904
  import fs11 from "fs/promises";
2771
- import path11 from "path";
2772
- import os7 from "os";
2905
+ import path12 from "path";
2906
+ import os8 from "os";
2773
2907
 
2774
2908
  class EnhancedInterfaceCache {
2775
2909
  cacheDir;
@@ -2778,9 +2912,9 @@ class EnhancedInterfaceCache {
2778
2912
  noCache;
2779
2913
  constructor(noCache = false) {
2780
2914
  this.noCache = noCache;
2781
- this.cacheDir = path11.join(os7.homedir(), ".adk", "cache", "interfaces");
2782
- this.resolutionsDir = path11.join(this.cacheDir, "resolutions");
2783
- this.definitionsDir = path11.join(this.cacheDir, "definitions");
2915
+ this.cacheDir = path12.join(os8.homedir(), ".adk", "cache", "interfaces");
2916
+ this.resolutionsDir = path12.join(this.cacheDir, "resolutions");
2917
+ this.definitionsDir = path12.join(this.cacheDir, "definitions");
2784
2918
  }
2785
2919
  async ensureCacheDirs() {
2786
2920
  await fs11.mkdir(this.resolutionsDir, { recursive: true });
@@ -2791,7 +2925,7 @@ class EnhancedInterfaceCache {
2791
2925
  return null;
2792
2926
  try {
2793
2927
  const key = this.getResolutionKey(name, version, workspace);
2794
- const cachePath = path11.join(this.resolutionsDir, `${key}.json`);
2928
+ const cachePath = path12.join(this.resolutionsDir, `${key}.json`);
2795
2929
  const data = await fs11.readFile(cachePath, "utf-8");
2796
2930
  const resolution = JSON.parse(data);
2797
2931
  const cachedAt = new Date(resolution.cachedAt);
@@ -2806,20 +2940,20 @@ class EnhancedInterfaceCache {
2806
2940
  async setResolution(name, version, workspace, interfaceId, updatedAt) {
2807
2941
  await this.ensureCacheDirs();
2808
2942
  const key = this.getResolutionKey(name, version, workspace);
2809
- const cachePath = path11.join(this.resolutionsDir, `${key}.json`);
2943
+ const cachePath = path12.join(this.resolutionsDir, `${key}.json`);
2810
2944
  const resolution = {
2811
2945
  interfaceId,
2812
2946
  updatedAt,
2813
2947
  cachedAt: new Date().toISOString()
2814
2948
  };
2815
- await fs11.writeFile(cachePath, JSON.stringify(resolution, null, 2));
2949
+ await fs11.writeFile(cachePath, JSON.stringify(resolution));
2816
2950
  }
2817
2951
  async getDefinition(interfaceId, updatedAt) {
2818
2952
  if (this.noCache)
2819
2953
  return null;
2820
2954
  try {
2821
2955
  const key = this.getDefinitionKey(interfaceId, updatedAt);
2822
- const cachePath = path11.join(this.definitionsDir, `${key}.json`);
2956
+ const cachePath = path12.join(this.definitionsDir, `${key}.json`);
2823
2957
  const data = await fs11.readFile(cachePath, "utf-8");
2824
2958
  const cached = JSON.parse(data);
2825
2959
  return cached.definition;
@@ -2830,19 +2964,19 @@ class EnhancedInterfaceCache {
2830
2964
  async setDefinition(interfaceId, updatedAt, definition) {
2831
2965
  await this.ensureCacheDirs();
2832
2966
  const key = this.getDefinitionKey(interfaceId, updatedAt);
2833
- const cachePath = path11.join(this.definitionsDir, `${key}.json`);
2967
+ const cachePath = path12.join(this.definitionsDir, `${key}.json`);
2834
2968
  const cached = {
2835
2969
  definition,
2836
2970
  cachedAt: new Date().toISOString()
2837
2971
  };
2838
- await fs11.writeFile(cachePath, JSON.stringify(cached, null, 2));
2972
+ await fs11.writeFile(cachePath, JSON.stringify(cached));
2839
2973
  }
2840
2974
  async clear() {
2841
2975
  try {
2842
2976
  const resolutionFiles = await fs11.readdir(this.resolutionsDir);
2843
- await Promise.all(resolutionFiles.map((f) => fs11.unlink(path11.join(this.resolutionsDir, f))));
2977
+ await Promise.all(resolutionFiles.map((f) => fs11.unlink(path12.join(this.resolutionsDir, f))));
2844
2978
  const definitionFiles = await fs11.readdir(this.definitionsDir);
2845
- await Promise.all(definitionFiles.map((f) => fs11.unlink(path11.join(this.definitionsDir, f))));
2979
+ await Promise.all(definitionFiles.map((f) => fs11.unlink(path12.join(this.definitionsDir, f))));
2846
2980
  } catch {}
2847
2981
  }
2848
2982
  async getStats() {
@@ -2851,7 +2985,7 @@ class EnhancedInterfaceCache {
2851
2985
  const files = await fs11.readdir(dir);
2852
2986
  let totalSize = 0;
2853
2987
  for (const file of files) {
2854
- const stats = await fs11.stat(path11.join(dir, file));
2988
+ const stats = await fs11.stat(path12.join(dir, file));
2855
2989
  totalSize += stats.size;
2856
2990
  }
2857
2991
  return { count: files.length, sizeBytes: totalSize };
@@ -2882,7 +3016,11 @@ class InterfaceParser {
2882
3016
  static parseInterfaceRef(versionString) {
2883
3017
  const match = versionString.match(/^(?:([^/]+)\/)?([^@]+)@(.+)$/);
2884
3018
  if (!match) {
2885
- throw new Error(`Invalid interface version format: ${versionString}. Expected format: 'name@version' or 'workspace/name@version'`);
3019
+ throw new AdkError({
3020
+ code: "INVALID_VERSION_FORMAT",
3021
+ message: `Invalid interface version format: ${versionString}. Expected format: 'name@version' or 'workspace/name@version'`,
3022
+ expected: true
3023
+ });
2886
3024
  }
2887
3025
  const [, workspace, name, version] = match;
2888
3026
  return {
@@ -2916,6 +3054,7 @@ class InterfaceParser {
2916
3054
  }
2917
3055
  }
2918
3056
  var init_parser = __esm(() => {
3057
+ init_src();
2919
3058
  init_validation_errors();
2920
3059
  init_constants();
2921
3060
  });
@@ -3014,11 +3153,19 @@ class InterfaceManager {
3014
3153
  latestVersion = latestPublic.interface.version;
3015
3154
  } catch {
3016
3155
  const location2 = ref.workspace ? `workspace "${ref.workspace}"` : "the official Botpress hub";
3017
- throw new Error(`Interface "${ref.name}" does not exist in ${location2}`);
3156
+ throw new AdkError({
3157
+ code: "INTERFACE_NOT_FOUND",
3158
+ message: `Interface "${ref.name}" does not exist in ${location2}`,
3159
+ expected: true
3160
+ });
3018
3161
  }
3019
3162
  }
3020
3163
  const location = ref.workspace ? `workspace "${ref.workspace}"` : "Botpress";
3021
- throw new Error(`Interface "${ref.name}" version "${ref.version}" not found in ${location}. Latest available version is "${latestVersion}"`);
3164
+ throw new AdkError({
3165
+ code: "INTERFACE_VERSION_NOT_FOUND",
3166
+ message: `Interface "${ref.name}" version "${ref.version}" not found in ${location}. Latest available version is "${latestVersion}"`,
3167
+ expected: true
3168
+ });
3022
3169
  }
3023
3170
  const intf = interfaceResponse.interface;
3024
3171
  await this.cache.setResolution(ref.name, ref.version, ref.workspace, intf.id, intf.updatedAt);
@@ -3028,7 +3175,11 @@ class InterfaceManager {
3028
3175
  async getByDependencyString(dep) {
3029
3176
  const match = dep.match(/^(?:([^/]+)\/)?([^@]+)@(.+)$/);
3030
3177
  if (!match) {
3031
- throw new Error(`Invalid interface dependency string: ${dep}. Expected 'name@version' or 'workspace/name@version'`);
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
+ });
3032
3183
  }
3033
3184
  const [, workspace, name, version] = match;
3034
3185
  return this.fetchInterface({
@@ -3059,6 +3210,7 @@ class InterfaceManager {
3059
3210
  }
3060
3211
  }
3061
3212
  var init_manager3 = __esm(() => {
3213
+ init_src();
3062
3214
  init_auth();
3063
3215
  init_enhanced_cache2();
3064
3216
  init_parser();
@@ -3230,7 +3382,7 @@ var init_component_files = __esm(() => {
3230
3382
  // src/agent-project/component-source-resolver.ts
3231
3383
  import { Project, SyntaxKind } from "ts-morph";
3232
3384
  import { readFileSync } from "fs";
3233
- import * as path12 from "path";
3385
+ import * as path13 from "path";
3234
3386
  function resolveComponentSources(absolutePath) {
3235
3387
  const project = new Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true });
3236
3388
  const sourceFile = project.createSourceFile(absolutePath, readFileSync(absolutePath, "utf-8"), { overwrite: true });
@@ -3243,12 +3395,12 @@ function resolveComponentSources(absolutePath) {
3243
3395
  }
3244
3396
  function collectBpTsxImports(sourceFile, absolutePath) {
3245
3397
  const imports = new Map;
3246
- const dir = path12.dirname(absolutePath);
3398
+ const dir = path13.dirname(absolutePath);
3247
3399
  for (const decl of sourceFile.getImportDeclarations()) {
3248
3400
  const specifier = decl.getModuleSpecifierValue();
3249
3401
  if (!specifier.endsWith(BP_TSX_SUFFIX))
3250
3402
  continue;
3251
- const resolved = path12.resolve(dir, specifier);
3403
+ const resolved = path13.resolve(dir, specifier);
3252
3404
  const defaultImport = decl.getDefaultImport();
3253
3405
  if (defaultImport) {
3254
3406
  imports.set(defaultImport.getText(), resolved);
@@ -3372,10 +3524,10 @@ function lockToDependencies(lock) {
3372
3524
  // src/agent-project/agent-project.ts
3373
3525
  import { BuiltInActions, BuiltInWorkflows, Errors as Errors2, Primitives as Primitives2, setAdkCommand } from "@botpress/runtime/internal";
3374
3526
  import { Autonomous } from "@botpress/runtime";
3375
- import createDebug from "debug";
3527
+ import createDebug2 from "debug";
3376
3528
  import { createRequire as createRequire2 } from "module";
3377
3529
  import fs12 from "fs/promises";
3378
- import path13 from "path";
3530
+ import path14 from "path";
3379
3531
  function getToolDefinition(value) {
3380
3532
  if (typeof value !== "object" || value === null) {
3381
3533
  return;
@@ -3391,8 +3543,9 @@ function getToolDefinition(value) {
3391
3543
  description: maybeTool.description
3392
3544
  };
3393
3545
  }
3394
- var debug, AgentProject;
3546
+ var debug2, AgentProject;
3395
3547
  var init_agent_project = __esm(() => {
3548
+ init_src();
3396
3549
  init_assets();
3397
3550
  init_integrations();
3398
3551
  init_interfaces();
@@ -3406,7 +3559,7 @@ var init_agent_project = __esm(() => {
3406
3559
  init_table_validation();
3407
3560
  init_constants();
3408
3561
  init_lock_file();
3409
- debug = createDebug("adk:agent-project");
3562
+ debug2 = createDebug2("adk:agent-project");
3410
3563
  AgentProject = class AgentProject {
3411
3564
  static _projectCache = new Map;
3412
3565
  _options;
@@ -3433,7 +3586,7 @@ var init_agent_project = __esm(() => {
3433
3586
  _tools = [];
3434
3587
  constructor(projectPath, options = {}) {
3435
3588
  this._options = options;
3436
- this._path = path13.resolve(projectPath);
3589
+ this._path = path14.resolve(projectPath);
3437
3590
  this._integrationManager = new IntegrationManager({
3438
3591
  noCache: options.noCache
3439
3592
  });
@@ -3445,7 +3598,7 @@ var init_agent_project = __esm(() => {
3445
3598
  });
3446
3599
  }
3447
3600
  static async load(projectPath, options = {}) {
3448
- const resolvedPath = path13.resolve(projectPath);
3601
+ const resolvedPath = path14.resolve(projectPath);
3449
3602
  if (!options.noCache) {
3450
3603
  const cached = AgentProject._projectCache.get(resolvedPath);
3451
3604
  if (cached) {
@@ -3463,7 +3616,7 @@ var init_agent_project = __esm(() => {
3463
3616
  AgentProject._projectCache.clear();
3464
3617
  }
3465
3618
  static clearCacheForPath(projectPath) {
3466
- const resolvedPath = path13.resolve(projectPath);
3619
+ const resolvedPath = path14.resolve(projectPath);
3467
3620
  AgentProject._projectCache.delete(resolvedPath);
3468
3621
  }
3469
3622
  get path() {
@@ -3540,7 +3693,12 @@ var init_agent_project = __esm(() => {
3540
3693
  this._warnings = validation.warnings;
3541
3694
  if (!validation.valid) {
3542
3695
  this._state = "error" /* Error */;
3543
- throw new Error(`Project validation failed: ${validation.errors[0]?.message}`);
3696
+ throw new AdkError({
3697
+ code: "PROJECT_VALIDATION_FAILED",
3698
+ expected: true,
3699
+ message: `Project validation failed: ${validation.errors[0]?.message}`,
3700
+ details: { errors: validation.errors }
3701
+ });
3544
3702
  }
3545
3703
  await this.loadAgentInfo();
3546
3704
  this._integrationManager = new IntegrationManager({
@@ -3578,13 +3736,13 @@ var init_agent_project = __esm(() => {
3578
3736
  const requiredFiles = ["agent.config.ts"];
3579
3737
  for (const file of requiredFiles) {
3580
3738
  try {
3581
- await fs12.access(path13.join(this._path, file));
3739
+ await fs12.access(path14.join(this._path, file));
3582
3740
  } catch {
3583
3741
  errors.push(ValidationErrors.requiredFileMissing(file));
3584
3742
  }
3585
3743
  }
3586
3744
  try {
3587
- await fs12.access(path13.join(this._path, "agent.json"));
3745
+ await fs12.access(path14.join(this._path, "agent.json"));
3588
3746
  } catch {
3589
3747
  info.push({
3590
3748
  $type: "ValidationError",
@@ -3598,7 +3756,7 @@ var init_agent_project = __esm(() => {
3598
3756
  const expectedDirs = ["actions", "workflows", "conversations", "assets"];
3599
3757
  for (const dir of expectedDirs) {
3600
3758
  try {
3601
- const stats = await fs12.stat(path13.join(this._path, dir));
3759
+ const stats = await fs12.stat(path14.join(this._path, dir));
3602
3760
  if (!stats.isDirectory()) {
3603
3761
  warnings.push(ValidationErrors.invalidStructure(dir, "directory"));
3604
3762
  }
@@ -3627,19 +3785,19 @@ var init_agent_project = __esm(() => {
3627
3785
  }
3628
3786
  get integrations() {
3629
3787
  if (!this._integrations) {
3630
- throw new Error("Integrations not loaded");
3788
+ throw new AdkError({ code: "PROJECT_NOT_LOADED", expected: false, message: "Integrations not loaded" });
3631
3789
  }
3632
3790
  return this._integrations;
3633
3791
  }
3634
3792
  get interfaces() {
3635
3793
  if (!this._interfaces) {
3636
- throw new Error("Interfaces not loaded");
3794
+ throw new AdkError({ code: "PROJECT_NOT_LOADED", expected: false, message: "Interfaces not loaded" });
3637
3795
  }
3638
3796
  return this._interfaces;
3639
3797
  }
3640
3798
  async getIntegrations() {
3641
3799
  if (!this._dependencies || !this._integrations) {
3642
- throw new Error("Project not loaded");
3800
+ throw new AdkError({ code: "PROJECT_NOT_LOADED", expected: false, message: "Project not loaded" });
3643
3801
  }
3644
3802
  return this._integrations.map((parsed) => ({
3645
3803
  name: parsed.alias,
@@ -3653,14 +3811,22 @@ var init_agent_project = __esm(() => {
3653
3811
  }
3654
3812
  async createAssetSyncPlan() {
3655
3813
  if (this._state !== "ready" /* Ready */) {
3656
- throw new Error("Project must be in Ready state to create asset sync plan");
3814
+ throw new AdkError({
3815
+ code: "PROJECT_NOT_READY",
3816
+ expected: false,
3817
+ message: "Project must be in Ready state to create asset sync plan"
3818
+ });
3657
3819
  }
3658
3820
  this.requiresAgentInfo("create asset sync plan");
3659
3821
  return await this._assetsManager.createSyncPlan();
3660
3822
  }
3661
3823
  async syncAssets(options) {
3662
3824
  if (this._state !== "ready" /* Ready */) {
3663
- throw new Error("Project must be in Ready state to sync assets");
3825
+ throw new AdkError({
3826
+ code: "PROJECT_NOT_READY",
3827
+ expected: false,
3828
+ message: "Project must be in Ready state to sync assets"
3829
+ });
3664
3830
  }
3665
3831
  this.requiresAgentInfo("sync assets");
3666
3832
  const plan = await this._assetsManager.createSyncPlan();
@@ -3674,7 +3840,7 @@ var init_agent_project = __esm(() => {
3674
3840
  }
3675
3841
  async createAgentInfo(info) {
3676
3842
  const { devId, ...agentJsonInfo } = info;
3677
- const agentPath = path13.join(this._path, "agent.json");
3843
+ const agentPath = path14.join(this._path, "agent.json");
3678
3844
  const agentContent = stringifyWithOrder(agentJsonInfo, agentInfoKeyOrder);
3679
3845
  await fs12.writeFile(agentPath, agentContent);
3680
3846
  this._agentInfo = info;
@@ -3684,12 +3850,16 @@ var init_agent_project = __esm(() => {
3684
3850
  }
3685
3851
  async updateAgentInfo(updates) {
3686
3852
  if (!this._agentInfo) {
3687
- throw new Error("No agent.json found. Use createAgentInfo() first.");
3853
+ throw new AdkError({
3854
+ code: "AGENT_INFO_MISSING",
3855
+ expected: false,
3856
+ message: "No agent.json found. Use createAgentInfo() first."
3857
+ });
3688
3858
  }
3689
3859
  const { devId, ...agentJsonUpdates } = updates;
3690
3860
  const updatedInfo = { ...this._agentInfo, ...agentJsonUpdates };
3691
3861
  const { devId: _devId, ...agentJsonData } = updatedInfo;
3692
- const agentPath = path13.join(this._path, "agent.json");
3862
+ const agentPath = path14.join(this._path, "agent.json");
3693
3863
  const agentContent = stringifyWithOrder(agentJsonData, agentInfoKeyOrder);
3694
3864
  await fs12.writeFile(agentPath, agentContent);
3695
3865
  this._agentInfo = updatedInfo;
@@ -3698,7 +3868,7 @@ var init_agent_project = __esm(() => {
3698
3868
  }
3699
3869
  }
3700
3870
  async createAgentLocalInfo(info) {
3701
- const localPath = path13.join(this._path, "agent.local.json");
3871
+ const localPath = path14.join(this._path, "agent.local.json");
3702
3872
  let existing = {};
3703
3873
  try {
3704
3874
  const content2 = await fs12.readFile(localPath, "utf-8");
@@ -3726,7 +3896,7 @@ var init_agent_project = __esm(() => {
3726
3896
  }
3727
3897
  }
3728
3898
  async updateAgentLocalInfo(updates) {
3729
- const localPath = path13.join(this._path, "agent.local.json");
3899
+ const localPath = path14.join(this._path, "agent.local.json");
3730
3900
  let existing = {};
3731
3901
  try {
3732
3902
  const content = await fs12.readFile(localPath, "utf-8");
@@ -3747,7 +3917,7 @@ var init_agent_project = __esm(() => {
3747
3917
  await fs12.writeFile(localPath, content);
3748
3918
  }
3749
3919
  if (this._agentInfo) {
3750
- const agentJsonPath = path13.join(this._path, "agent.json");
3920
+ const agentJsonPath = path14.join(this._path, "agent.json");
3751
3921
  let base = {
3752
3922
  botId: this._agentInfo.botId,
3753
3923
  workspaceId: this._agentInfo.workspaceId,
@@ -3773,7 +3943,12 @@ var init_agent_project = __esm(() => {
3773
3943
  }
3774
3944
  requiresAgentInfo(operation) {
3775
3945
  if (!this._agentInfo?.botId) {
3776
- throw new Error(`Operation "${operation}" requires a bot ID. ` + "Please create agent.json with botId and workspaceId after deploying your agent.");
3946
+ throw new AdkError({
3947
+ code: "BOT_ID_REQUIRED",
3948
+ expected: true,
3949
+ message: `Operation "${operation}" requires a bot ID. ` + "Please create agent.json with botId and workspaceId after deploying your agent.",
3950
+ suggestion: "Create agent.json with botId and workspaceId after deploying your agent."
3951
+ });
3777
3952
  }
3778
3953
  }
3779
3954
  async loadConfig() {
@@ -3781,28 +3956,28 @@ var init_agent_project = __esm(() => {
3781
3956
  this._integrations = [];
3782
3957
  this._interfaces = [];
3783
3958
  try {
3784
- const configPath = path13.join(this._path, "agent.config.ts");
3785
- debug("loading agent.config.ts from %s", configPath);
3786
- const projectRequire = createRequire2(path13.join(this._path, "package.json"));
3787
- debug("created projectRequire from %s", path13.join(this._path, "package.json"));
3959
+ const configPath = path14.join(this._path, "agent.config.ts");
3960
+ debug2("loading agent.config.ts from %s", configPath);
3961
+ const projectRequire = createRequire2(path14.join(this._path, "package.json"));
3962
+ debug2("created projectRequire from %s", path14.join(this._path, "package.json"));
3788
3963
  try {
3789
3964
  const resolvedPath = projectRequire.resolve(configPath);
3790
- debug("resolved config path: %s", resolvedPath);
3965
+ debug2("resolved config path: %s", resolvedPath);
3791
3966
  if (projectRequire.cache[resolvedPath]) {
3792
- debug("clearing require.cache for %s", resolvedPath);
3967
+ debug2("clearing require.cache for %s", resolvedPath);
3793
3968
  delete projectRequire.cache[resolvedPath];
3794
3969
  }
3795
3970
  } catch {
3796
- debug("config not in require.cache (first load)");
3971
+ debug2("config not in require.cache (first load)");
3797
3972
  }
3798
3973
  let configModule;
3799
3974
  try {
3800
3975
  const configUrl = `${configPath}?t=${Date.now()}`;
3801
- debug("importing from: %s", configUrl);
3976
+ debug2("importing from: %s", configUrl);
3802
3977
  configModule = await import(configUrl);
3803
- debug("successfully loaded agent.config.ts");
3978
+ debug2("successfully loaded agent.config.ts");
3804
3979
  } catch (importError) {
3805
- debug("failed to load agent.config.ts: %O", importError);
3980
+ debug2("failed to load agent.config.ts: %O", importError);
3806
3981
  throw importError;
3807
3982
  }
3808
3983
  if (!configModule || !configModule.default) {
@@ -3891,10 +4066,10 @@ var init_agent_project = __esm(() => {
3891
4066
  }
3892
4067
  } catch (error) {
3893
4068
  const err = error;
3894
- debug("loadConfig error: %O", err);
4069
+ debug2("loadConfig error: %O", err);
3895
4070
  let detailedMessage = `Failed to load agent.config.ts: ${err.message}`;
3896
4071
  if (err.stack) {
3897
- debug(`stack trace:
4072
+ debug2(`stack trace:
3898
4073
  %s`, err.stack);
3899
4074
  }
3900
4075
  let hint;
@@ -3981,8 +4156,8 @@ ${err.stack?.split(`
3981
4156
  }
3982
4157
  }
3983
4158
  isBarrelReexport(existing, newPath, newExport, newDefinition) {
3984
- const isNewBarrel = /^index\.[tj]s$/i.test(path13.basename(newPath));
3985
- const isExistingBarrel = /^index\.[tj]s$/i.test(path13.basename(existing.path));
4159
+ const isNewBarrel = /^index\.[tj]s$/i.test(path14.basename(newPath));
4160
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path14.basename(existing.path));
3986
4161
  if (!isNewBarrel && !isExistingBarrel) {
3987
4162
  return false;
3988
4163
  }
@@ -3994,16 +4169,16 @@ ${err.stack?.split(`
3994
4169
  return true;
3995
4170
  }
3996
4171
  isToolBarrelReexport(existingPath, newPath) {
3997
- const isNewBarrel = /^index\.[tj]s$/i.test(path13.basename(newPath));
3998
- const isExistingBarrel = /^index\.[tj]s$/i.test(path13.basename(existingPath));
4172
+ const isNewBarrel = /^index\.[tj]s$/i.test(path14.basename(newPath));
4173
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path14.basename(existingPath));
3999
4174
  if (!isNewBarrel && !isExistingBarrel) {
4000
4175
  return false;
4001
4176
  }
4002
4177
  return true;
4003
4178
  }
4004
4179
  shouldPreferToolDefinition(existingPath, newPath) {
4005
- const isNewBarrel = /^index\.[tj]s$/i.test(path13.basename(newPath));
4006
- const isExistingBarrel = /^index\.[tj]s$/i.test(path13.basename(existingPath));
4180
+ const isNewBarrel = /^index\.[tj]s$/i.test(path14.basename(newPath));
4181
+ const isExistingBarrel = /^index\.[tj]s$/i.test(path14.basename(existingPath));
4007
4182
  return isExistingBarrel && !isNewBarrel;
4008
4183
  }
4009
4184
  getChannelsList(channelSpec) {
@@ -4019,7 +4194,7 @@ ${err.stack?.split(`
4019
4194
  if (this._options.adkCommand) {
4020
4195
  setAdkCommand(this._options.adkCommand);
4021
4196
  }
4022
- const src = path13.join(this._path, "src");
4197
+ const src = path14.join(this._path, "src");
4023
4198
  if (!await fs12.stat(src).catch(() => false)) {
4024
4199
  this._errors.push({
4025
4200
  $type: "ValidationError",
@@ -4035,8 +4210,8 @@ ${err.stack?.split(`
4035
4210
  });
4036
4211
  for (const file of allFiles.filter((x) => x.isFile())) {
4037
4212
  const filename = file.name;
4038
- const absolutePath = path13.join(file.parentPath, file.name);
4039
- const relPath = path13.relative(this.path, absolutePath);
4213
+ const absolutePath = path14.join(file.parentPath, file.name);
4214
+ const relPath = path14.relative(this.path, absolutePath);
4040
4215
  if (filename.toLowerCase().endsWith(".d.ts")) {
4041
4216
  continue;
4042
4217
  }
@@ -4323,7 +4498,7 @@ ${err.stack?.split(`
4323
4498
  });
4324
4499
 
4325
4500
  // src/generators/utils.ts
4326
- import path14 from "path";
4501
+ import path15 from "path";
4327
4502
  async function getFormat() {
4328
4503
  if (!_formatLoaded) {
4329
4504
  _formatLoaded = true;
@@ -4371,9 +4546,9 @@ var _format = null, _formatLoaded = false, formatCode = async (code, filepath) =
4371
4546
  `));
4372
4547
  return code;
4373
4548
  }
4374
- }, ADK_VERSION = "1.19.0-beta.7", relative = (from, to) => {
4375
- const fromDir = path14.dirname(from);
4376
- const relative2 = path14.relative(fromDir, to);
4549
+ }, ADK_VERSION = "1.19.0-beta.9", relative = (from, to) => {
4550
+ const fromDir = path15.dirname(from);
4551
+ const relative2 = path15.relative(fromDir, to);
4377
4552
  return relative2.startsWith(".") ? relative2 : `./${relative2}`;
4378
4553
  };
4379
4554
  var init_utils = () => {};
@@ -15448,7 +15623,7 @@ var init_integration_action_types = __esm(() => {
15448
15623
  var require_package = __commonJS((exports, module) => {
15449
15624
  module.exports = {
15450
15625
  name: "@botpress/adk",
15451
- version: "1.19.0-beta.7",
15626
+ version: "1.19.0-beta.9",
15452
15627
  description: "Core ADK library for building AI agents on Botpress",
15453
15628
  keywords: [
15454
15629
  "adk",
@@ -15486,6 +15661,10 @@ var require_package = __commonJS((exports, module) => {
15486
15661
  types: "./dist/agent0/index.d.ts",
15487
15662
  import: "./dist/agent0/index.js"
15488
15663
  },
15664
+ "./internal/bp-cli": {
15665
+ types: "./dist/commands/bp-cli.d.ts",
15666
+ import: "./dist/commands/bp-cli.js"
15667
+ },
15489
15668
  "./package.json": "./package.json",
15490
15669
  "./schemas/*": "./schemas/*"
15491
15670
  },
@@ -15502,10 +15681,10 @@ var require_package = __commonJS((exports, module) => {
15502
15681
  },
15503
15682
  dependencies: {
15504
15683
  "@botpress/chat": "~0.5.5",
15505
- "@botpress/cli": "~6.8.1",
15684
+ "@botpress/cli": "~6.8.6",
15506
15685
  "@botpress/client": "~1.46.0",
15507
15686
  "@botpress/cognitive": "~0.5.5",
15508
- "@botpress/runtime": "^1.19.0-beta.7",
15687
+ "@botpress/runtime": "^1.19.0-beta.9",
15509
15688
  "@botpress/sdk": "~6.11.1",
15510
15689
  "@bpinternal/jex": "^1.2.4",
15511
15690
  "@bpinternal/yargs-extra": "^0.0.21",
@@ -15532,6 +15711,60 @@ var require_package = __commonJS((exports, module) => {
15532
15711
  };
15533
15712
  });
15534
15713
 
15714
+ // src/commands/bp-cli.ts
15715
+ init_src();
15716
+ import { existsSync } from "fs";
15717
+ import os from "os";
15718
+ import path from "path";
15719
+ import createDebug from "debug";
15720
+ var debug = createDebug("adk:bp-cli");
15721
+ var BP_CLI_VERSION = "6.8.6";
15722
+ var BP_CLI_INSTALL_ALL = path.join(os.homedir(), ".adk", `bp-cli`);
15723
+ var BP_CLI_INSTALL_DIR = path.join(BP_CLI_INSTALL_ALL, BP_CLI_VERSION);
15724
+ var BP_CLI_BIN_PATH = path.join(BP_CLI_INSTALL_DIR, "node_modules", "@botpress", "cli", "bin.js");
15725
+ var BP_CLIENT_ENV_KEYS = [
15726
+ "BP_API_URL",
15727
+ "BP_TOKEN",
15728
+ "BP_WORKSPACE_ID",
15729
+ "BP_BOT_ID",
15730
+ "BP_INTEGRATION_ID",
15731
+ "BP_INTEGRATION_ALIAS"
15732
+ ];
15733
+ debug("BP_CLI_VERSION=%s (injected at build time)", BP_CLI_VERSION);
15734
+ debug("BP_CLI_INSTALL_ALL=%s", BP_CLI_INSTALL_ALL);
15735
+ debug("BP_CLI_INSTALL_DIR=%s", BP_CLI_INSTALL_DIR);
15736
+ debug("BP_CLI_BIN_PATH=%s", BP_CLI_BIN_PATH);
15737
+ function getBpCli() {
15738
+ debug("getBpCli() called");
15739
+ debug("checking if BP_CLI_BIN_PATH exists: %s", BP_CLI_BIN_PATH);
15740
+ const exists = existsSync(BP_CLI_BIN_PATH);
15741
+ debug("BP_CLI_BIN_PATH exists=%s", exists);
15742
+ if (!exists) {
15743
+ debug("ERROR: bp CLI not found at expected path");
15744
+ throw new AdkError({
15745
+ code: "INTERNAL_BP_CLI_MISSING",
15746
+ message: `@botpress/cli version ${BP_CLI_VERSION} is not installed in the ADK directory "${BP_CLI_INSTALL_DIR}". This is a bug, please report it to the Botpress team.`,
15747
+ expected: false
15748
+ });
15749
+ }
15750
+ const info = {
15751
+ path: BP_CLI_BIN_PATH,
15752
+ version: BP_CLI_VERSION
15753
+ };
15754
+ debug("returning BpCliInfo: %O", info);
15755
+ return info;
15756
+ }
15757
+ function getBpCliEnvironment(overrides = {}) {
15758
+ const env = { ...process.env };
15759
+ for (const key of BP_CLIENT_ENV_KEYS) {
15760
+ delete env[key];
15761
+ }
15762
+ return {
15763
+ ...env,
15764
+ ...overrides
15765
+ };
15766
+ }
15767
+
15535
15768
  // src/dependencies/index.ts
15536
15769
  var exports_dependencies = {};
15537
15770
  __export(exports_dependencies, {
@@ -15578,10 +15811,10 @@ function generateFriendlyAlias(cloudName, cloudAlias, used) {
15578
15811
  }
15579
15812
 
15580
15813
  // src/dependencies/dependency-manager.ts
15581
- init_errors();
15814
+ init_errors2();
15582
15815
 
15583
15816
  // src/dependencies/resolvers/integration-resolver.ts
15584
- init_errors();
15817
+ init_errors2();
15585
15818
 
15586
15819
  class IntegrationResolver {
15587
15820
  registry;
@@ -15627,7 +15860,7 @@ class IntegrationResolver {
15627
15860
  }
15628
15861
 
15629
15862
  // src/dependencies/resolvers/plugin-resolver.ts
15630
- init_errors();
15863
+ init_errors2();
15631
15864
 
15632
15865
  class PluginResolver {
15633
15866
  registry;
@@ -15742,12 +15975,13 @@ class IntegrationRegistry {
15742
15975
  }
15743
15976
 
15744
15977
  // src/plugins/manager.ts
15978
+ init_src();
15745
15979
  init_auth();
15746
15980
 
15747
15981
  // src/plugins/enhanced-cache.ts
15748
15982
  import fs6 from "fs/promises";
15749
- import path6 from "path";
15750
- import os4 from "os";
15983
+ import path7 from "path";
15984
+ import os5 from "os";
15751
15985
 
15752
15986
  class EnhancedPluginCache {
15753
15987
  cacheDir;
@@ -15756,9 +15990,9 @@ class EnhancedPluginCache {
15756
15990
  noCache;
15757
15991
  constructor(noCache = false) {
15758
15992
  this.noCache = noCache;
15759
- this.cacheDir = path6.join(os4.homedir(), ".adk", "cache", "plugins");
15760
- this.resolutionsDir = path6.join(this.cacheDir, "resolutions");
15761
- this.definitionsDir = path6.join(this.cacheDir, "definitions");
15993
+ this.cacheDir = path7.join(os5.homedir(), ".adk", "cache", "plugins");
15994
+ this.resolutionsDir = path7.join(this.cacheDir, "resolutions");
15995
+ this.definitionsDir = path7.join(this.cacheDir, "definitions");
15762
15996
  }
15763
15997
  async ensureCacheDirs() {
15764
15998
  await fs6.mkdir(this.resolutionsDir, { recursive: true });
@@ -15770,7 +16004,7 @@ class EnhancedPluginCache {
15770
16004
  }
15771
16005
  try {
15772
16006
  const key = this.getResolutionKey(name, version);
15773
- const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
16007
+ const cachePath = path7.join(this.resolutionsDir, `${key}.json`);
15774
16008
  const data = await fs6.readFile(cachePath, "utf-8");
15775
16009
  const resolution = JSON.parse(data);
15776
16010
  const cachedAt = new Date(resolution.cachedAt);
@@ -15787,13 +16021,13 @@ class EnhancedPluginCache {
15787
16021
  async setResolution(name, version, pluginId, updatedAt) {
15788
16022
  await this.ensureCacheDirs();
15789
16023
  const key = this.getResolutionKey(name, version);
15790
- const cachePath = path6.join(this.resolutionsDir, `${key}.json`);
16024
+ const cachePath = path7.join(this.resolutionsDir, `${key}.json`);
15791
16025
  const resolution = {
15792
16026
  pluginId,
15793
16027
  updatedAt,
15794
16028
  cachedAt: new Date().toISOString()
15795
16029
  };
15796
- await fs6.writeFile(cachePath, JSON.stringify(resolution, null, 2));
16030
+ await fs6.writeFile(cachePath, JSON.stringify(resolution));
15797
16031
  }
15798
16032
  async getDefinition(pluginId, updatedAt) {
15799
16033
  if (this.noCache) {
@@ -15801,7 +16035,7 @@ class EnhancedPluginCache {
15801
16035
  }
15802
16036
  try {
15803
16037
  const key = this.getDefinitionKey(pluginId, updatedAt);
15804
- const cachePath = path6.join(this.definitionsDir, `${key}.json`);
16038
+ const cachePath = path7.join(this.definitionsDir, `${key}.json`);
15805
16039
  const data = await fs6.readFile(cachePath, "utf-8");
15806
16040
  const cached = JSON.parse(data);
15807
16041
  return cached.definition;
@@ -15812,19 +16046,19 @@ class EnhancedPluginCache {
15812
16046
  async setDefinition(pluginId, updatedAt, definition) {
15813
16047
  await this.ensureCacheDirs();
15814
16048
  const key = this.getDefinitionKey(pluginId, updatedAt);
15815
- const cachePath = path6.join(this.definitionsDir, `${key}.json`);
16049
+ const cachePath = path7.join(this.definitionsDir, `${key}.json`);
15816
16050
  const cached = {
15817
16051
  definition,
15818
16052
  cachedAt: new Date().toISOString()
15819
16053
  };
15820
- await fs6.writeFile(cachePath, JSON.stringify(cached, null, 2));
16054
+ await fs6.writeFile(cachePath, JSON.stringify(cached));
15821
16055
  }
15822
16056
  async clear() {
15823
16057
  try {
15824
16058
  const resolutionFiles = await fs6.readdir(this.resolutionsDir);
15825
- await Promise.all(resolutionFiles.map((file) => fs6.unlink(path6.join(this.resolutionsDir, file))));
16059
+ await Promise.all(resolutionFiles.map((file) => fs6.unlink(path7.join(this.resolutionsDir, file))));
15826
16060
  const definitionFiles = await fs6.readdir(this.definitionsDir);
15827
- await Promise.all(definitionFiles.map((file) => fs6.unlink(path6.join(this.definitionsDir, file))));
16061
+ await Promise.all(definitionFiles.map((file) => fs6.unlink(path7.join(this.definitionsDir, file))));
15828
16062
  } catch {}
15829
16063
  }
15830
16064
  async getStats() {
@@ -15833,7 +16067,7 @@ class EnhancedPluginCache {
15833
16067
  const files = await fs6.readdir(dir);
15834
16068
  let totalSize = 0;
15835
16069
  for (const file of files) {
15836
- const stats = await fs6.stat(path6.join(dir, file));
16070
+ const stats = await fs6.stat(path7.join(dir, file));
15837
16071
  totalSize += stats.size;
15838
16072
  }
15839
16073
  return {
@@ -15921,7 +16155,11 @@ class PluginManager {
15921
16155
  const client = await this.getClient();
15922
16156
  const plugin = await this._findPublicPlugin(client, ref);
15923
16157
  if (!plugin) {
15924
- throw new Error(`Plugin "${ref.name}" not found on the Botpress Hub`);
16158
+ throw new AdkError({
16159
+ code: "PLUGIN_NOT_FOUND",
16160
+ expected: true,
16161
+ message: `Plugin "${ref.name}" not found on the Botpress Hub`
16162
+ });
15925
16163
  }
15926
16164
  await this.cache.setResolution(ref.name, ref.version, plugin.id, plugin.updatedAt);
15927
16165
  await this.cache.setDefinition(plugin.id, plugin.updatedAt, plugin);
@@ -16682,7 +16920,7 @@ function extractMissingRequiredFields(err) {
16682
16920
 
16683
16921
  // src/dependencies/index.ts
16684
16922
  init_lock_file();
16685
- init_errors();
16923
+ init_errors2();
16686
16924
 
16687
16925
  // src/dependencies/registry/interface-registry.ts
16688
16926
  init_constants();
@@ -16702,19 +16940,20 @@ class InterfaceRegistry {
16702
16940
  // src/dependencies/migration.ts
16703
16941
  init_lock_file();
16704
16942
  import * as fs13 from "fs/promises";
16705
- import * as path16 from "path";
16943
+ import * as path17 from "path";
16706
16944
  import { Project as Project3, SyntaxKind as SyntaxKind3 } from "ts-morph";
16707
16945
 
16708
16946
  // src/agent-project/config-writer.ts
16709
16947
  init_utils();
16948
+ init_src();
16710
16949
  import { Project as Project2, SyntaxKind as SyntaxKind2 } from "ts-morph";
16711
16950
  import { readFileSync as readFileSync2 } from "fs";
16712
- import * as path15 from "path";
16951
+ import * as path16 from "path";
16713
16952
 
16714
16953
  class ConfigWriter {
16715
16954
  configPath;
16716
16955
  constructor(projectPath) {
16717
- this.configPath = path15.join(projectPath, "agent.config.ts");
16956
+ this.configPath = path16.join(projectPath, "agent.config.ts");
16718
16957
  }
16719
16958
  loadConfig() {
16720
16959
  const project = new Project2;
@@ -16725,11 +16964,19 @@ class ConfigWriter {
16725
16964
  return call.getExpression().getText() === "defineConfig";
16726
16965
  });
16727
16966
  if (!defineConfigCall) {
16728
- throw new Error("Could not find defineConfig() call in agent.config.ts");
16967
+ throw new AdkError({
16968
+ code: "CONFIG_AST_INVALID",
16969
+ expected: true,
16970
+ message: "Could not find defineConfig() call in agent.config.ts"
16971
+ });
16729
16972
  }
16730
16973
  const configArg = defineConfigCall.getArguments()[0];
16731
16974
  if (!configArg || !configArg.isKind(SyntaxKind2.ObjectLiteralExpression)) {
16732
- throw new Error("defineConfig() must have an object literal as its first argument");
16975
+ throw new AdkError({
16976
+ code: "CONFIG_AST_INVALID",
16977
+ expected: true,
16978
+ message: "defineConfig() must have an object literal as its first argument"
16979
+ });
16733
16980
  }
16734
16981
  return { sourceFile, configObject: configArg };
16735
16982
  }
@@ -16817,7 +17064,11 @@ class ConfigWriter {
16817
17064
  }
16818
17065
  const defaultModelsObject = defaultModelsProperty.getInitializerIfKind(SyntaxKind2.ObjectLiteralExpression);
16819
17066
  if (!defaultModelsObject) {
16820
- throw new Error("defaultModels must be an object literal in agent.config.ts");
17067
+ throw new AdkError({
17068
+ code: "CONFIG_AST_INVALID",
17069
+ expected: true,
17070
+ message: "defaultModels must be an object literal in agent.config.ts"
17071
+ });
16821
17072
  }
16822
17073
  for (const [key, value] of requestedEntries) {
16823
17074
  const existingProperty = defaultModelsObject.getProperty(key);
@@ -17006,7 +17257,7 @@ class ConfigWriter {
17006
17257
  }
17007
17258
 
17008
17259
  // src/dependencies/migration.ts
17009
- init_errors();
17260
+ init_errors2();
17010
17261
  init_agent_project();
17011
17262
  async function migrateFromConfig(opts) {
17012
17263
  const result = {
@@ -17111,7 +17362,7 @@ async function migrateFromConfig(opts) {
17111
17362
  return result;
17112
17363
  }
17113
17364
  async function readAliasesFromConfig(projectPath) {
17114
- const configPath = path16.join(projectPath, "agent.config.ts");
17365
+ const configPath = path17.join(projectPath, "agent.config.ts");
17115
17366
  try {
17116
17367
  await fs13.access(configPath);
17117
17368
  } catch {
@@ -17202,57 +17453,6 @@ class BaseCommand {
17202
17453
  }
17203
17454
  // src/commands/bp-add-command.ts
17204
17455
  import { execa } from "execa";
17205
-
17206
- // src/commands/bp-cli.ts
17207
- import { existsSync } from "fs";
17208
- import os8 from "os";
17209
- import path17 from "path";
17210
- import createDebug2 from "debug";
17211
- var debug2 = createDebug2("adk:bp-cli");
17212
- var BP_CLI_VERSION = "6.8.1";
17213
- var BP_CLI_INSTALL_ALL = path17.join(os8.homedir(), ".adk", `bp-cli`);
17214
- var BP_CLI_INSTALL_DIR = path17.join(BP_CLI_INSTALL_ALL, BP_CLI_VERSION);
17215
- var BP_CLI_BIN_PATH = path17.join(BP_CLI_INSTALL_DIR, "node_modules", "@botpress", "cli", "bin.js");
17216
- var BP_CLIENT_ENV_KEYS = [
17217
- "BP_API_URL",
17218
- "BP_TOKEN",
17219
- "BP_WORKSPACE_ID",
17220
- "BP_BOT_ID",
17221
- "BP_INTEGRATION_ID",
17222
- "BP_INTEGRATION_ALIAS"
17223
- ];
17224
- debug2("BP_CLI_VERSION=%s (injected at build time)", BP_CLI_VERSION);
17225
- debug2("BP_CLI_INSTALL_ALL=%s", BP_CLI_INSTALL_ALL);
17226
- debug2("BP_CLI_INSTALL_DIR=%s", BP_CLI_INSTALL_DIR);
17227
- debug2("BP_CLI_BIN_PATH=%s", BP_CLI_BIN_PATH);
17228
- function getBpCli() {
17229
- debug2("getBpCli() called");
17230
- debug2("checking if BP_CLI_BIN_PATH exists: %s", BP_CLI_BIN_PATH);
17231
- const exists = existsSync(BP_CLI_BIN_PATH);
17232
- debug2("BP_CLI_BIN_PATH exists=%s", exists);
17233
- if (!exists) {
17234
- debug2("ERROR: bp CLI not found at expected path");
17235
- throw new Error(`@botpress/cli version ${BP_CLI_VERSION} is not installed in the ADK directory "${BP_CLI_INSTALL_DIR}". This is a bug, please report it to the Botpress team.`);
17236
- }
17237
- const info = {
17238
- path: BP_CLI_BIN_PATH,
17239
- version: BP_CLI_VERSION
17240
- };
17241
- debug2("returning BpCliInfo: %O", info);
17242
- return info;
17243
- }
17244
- function getBpCliEnvironment(overrides = {}) {
17245
- const env = { ...process.env };
17246
- for (const key of BP_CLIENT_ENV_KEYS) {
17247
- delete env[key];
17248
- }
17249
- return {
17250
- ...env,
17251
- ...overrides
17252
- };
17253
- }
17254
-
17255
- // src/commands/bp-add-command.ts
17256
17456
  class BpAddCommand extends BaseCommand {
17257
17457
  options;
17258
17458
  childProcess = null;
@@ -17322,39 +17522,9 @@ import { join as join5 } from "path";
17322
17522
  import { access as access3 } from "fs/promises";
17323
17523
 
17324
17524
  // src/utils/source-map-optimizer.ts
17525
+ init_src();
17325
17526
  import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
17326
17527
  import { resolve as resolve2, isAbsolute, relative as relative2, dirname as dirname2 } from "path";
17327
- function decodeVLQ(input, pos) {
17328
- let result = 0;
17329
- let shift = 0;
17330
- let continuation = true;
17331
- let digit;
17332
- while (continuation) {
17333
- if (pos >= input.length) {
17334
- throw new Error("Unexpected end of VLQ data");
17335
- }
17336
- const char = input.charCodeAt(pos++);
17337
- if (char >= 65 && char <= 90)
17338
- digit = char - 65;
17339
- else if (char >= 97 && char <= 122)
17340
- digit = char - 97 + 26;
17341
- else if (char >= 48 && char <= 57)
17342
- digit = char - 48 + 52;
17343
- else if (char === 43)
17344
- digit = 62;
17345
- else if (char === 47)
17346
- digit = 63;
17347
- else
17348
- throw new Error("Invalid VLQ character");
17349
- continuation = (digit & 32) !== 0;
17350
- digit &= 31;
17351
- result += digit << shift;
17352
- shift += 5;
17353
- }
17354
- const negate = (result & 1) === 1;
17355
- result >>= 1;
17356
- return [negate ? -result : result, pos];
17357
- }
17358
17528
  function encodeVLQ(value) {
17359
17529
  const base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
17360
17530
  let encoded = "";
@@ -17369,120 +17539,152 @@ function encodeVLQ(value) {
17369
17539
  } while (num > 0);
17370
17540
  return encoded;
17371
17541
  }
17372
- function parseMappings(mappings) {
17373
- const lines = [];
17374
- const lineStrings = mappings.split(";");
17542
+ function collectKeptSegments(mappings, indicesToKeep) {
17543
+ const keptByLine = new Map;
17544
+ const usedNameIndices = new Set;
17545
+ const len = mappings.length;
17546
+ let pos = 0;
17547
+ let line = 0;
17548
+ let genColumn = 0;
17375
17549
  let sourceIndex = 0;
17376
17550
  let sourceLine = 0;
17377
17551
  let sourceColumn = 0;
17378
17552
  let nameIndex = 0;
17379
- for (let lineNum = 0;lineNum < lineStrings.length; lineNum++) {
17380
- const line = lineStrings[lineNum];
17381
- if (!line) {
17382
- lines.push({ line: lineNum, segments: [] });
17553
+ const readVLQ = () => {
17554
+ let result = 0;
17555
+ let shift = 0;
17556
+ let continuation = true;
17557
+ while (continuation) {
17558
+ if (pos >= len) {
17559
+ throw new AdkError({
17560
+ code: "SOURCEMAP_DECODE_ERROR",
17561
+ message: "Unexpected end of VLQ data"
17562
+ });
17563
+ }
17564
+ const char = mappings.charCodeAt(pos++);
17565
+ let digit;
17566
+ if (char >= 65 && char <= 90)
17567
+ digit = char - 65;
17568
+ else if (char >= 97 && char <= 122)
17569
+ digit = char - 97 + 26;
17570
+ else if (char >= 48 && char <= 57)
17571
+ digit = char - 48 + 52;
17572
+ else if (char === 43)
17573
+ digit = 62;
17574
+ else if (char === 47)
17575
+ digit = 63;
17576
+ else
17577
+ throw new AdkError({ code: "SOURCEMAP_DECODE_ERROR", message: "Invalid VLQ character" });
17578
+ continuation = (digit & 32) !== 0;
17579
+ digit &= 31;
17580
+ result += digit << shift;
17581
+ shift += 5;
17582
+ }
17583
+ const negate = (result & 1) === 1;
17584
+ result >>= 1;
17585
+ return negate ? -result : result;
17586
+ };
17587
+ const hasMoreFields = () => {
17588
+ if (pos >= len)
17589
+ return false;
17590
+ const c = mappings.charCodeAt(pos);
17591
+ return c !== 44 && c !== 59;
17592
+ };
17593
+ while (pos < len) {
17594
+ const char = mappings.charCodeAt(pos);
17595
+ if (char === 59) {
17596
+ line++;
17597
+ genColumn = 0;
17598
+ pos++;
17383
17599
  continue;
17384
17600
  }
17385
- const segments = [];
17386
- let column = 0;
17387
- const segmentStrings = line.split(",");
17388
- for (const segmentString of segmentStrings) {
17389
- if (!segmentString)
17390
- continue;
17391
- let pos = 0;
17392
- const segment = {
17393
- column: 0,
17394
- encoded: segmentString
17395
- };
17396
- const [colDelta, newPos1] = decodeVLQ(segmentString, pos);
17397
- column += colDelta;
17398
- segment.column = column;
17399
- pos = newPos1;
17400
- if (pos < segmentString.length) {
17401
- const [srcDelta, newPos2] = decodeVLQ(segmentString, pos);
17402
- sourceIndex += srcDelta;
17403
- segment.sourceIndex = sourceIndex;
17404
- pos = newPos2;
17405
- if (pos < segmentString.length) {
17406
- const [lineDelta, newPos3] = decodeVLQ(segmentString, pos);
17407
- sourceLine += lineDelta;
17408
- segment.sourceLine = sourceLine;
17409
- pos = newPos3;
17410
- if (pos < segmentString.length) {
17411
- const [colDelta2, newPos4] = decodeVLQ(segmentString, pos);
17412
- sourceColumn += colDelta2;
17413
- segment.sourceColumn = sourceColumn;
17414
- pos = newPos4;
17415
- if (pos < segmentString.length) {
17416
- const [nameDelta, newPos5] = decodeVLQ(segmentString, pos);
17417
- nameIndex += nameDelta;
17418
- segment.nameIndex = nameIndex;
17419
- pos = newPos5;
17420
- }
17601
+ if (char === 44) {
17602
+ pos++;
17603
+ continue;
17604
+ }
17605
+ genColumn += readVLQ();
17606
+ let segSourceIndex;
17607
+ let segSourceLine;
17608
+ let segSourceColumn;
17609
+ let segNameIndex;
17610
+ if (hasMoreFields()) {
17611
+ sourceIndex += readVLQ();
17612
+ segSourceIndex = sourceIndex;
17613
+ if (hasMoreFields()) {
17614
+ sourceLine += readVLQ();
17615
+ segSourceLine = sourceLine;
17616
+ if (hasMoreFields()) {
17617
+ sourceColumn += readVLQ();
17618
+ segSourceColumn = sourceColumn;
17619
+ if (hasMoreFields()) {
17620
+ nameIndex += readVLQ();
17621
+ segNameIndex = nameIndex;
17421
17622
  }
17422
17623
  }
17423
17624
  }
17424
- segments.push(segment);
17425
17625
  }
17426
- lines.push({ line: lineNum, segments });
17626
+ if (segSourceIndex === undefined || indicesToKeep.has(segSourceIndex)) {
17627
+ let segs = keptByLine.get(line);
17628
+ if (!segs) {
17629
+ segs = [];
17630
+ keptByLine.set(line, segs);
17631
+ }
17632
+ segs.push({
17633
+ column: genColumn,
17634
+ sourceIndex: segSourceIndex,
17635
+ sourceLine: segSourceLine,
17636
+ sourceColumn: segSourceColumn,
17637
+ nameIndex: segNameIndex
17638
+ });
17639
+ if (segNameIndex !== undefined) {
17640
+ usedNameIndices.add(segNameIndex);
17641
+ }
17642
+ }
17427
17643
  }
17428
- return lines;
17644
+ return { keptByLine, totalLines: line + 1, usedNameIndices };
17429
17645
  }
17430
- function rebuildMappings(lines, sourceIndexMap, nameIndexMap) {
17431
- const result = [];
17432
- let prevColumn = 0;
17646
+ function encodeKeptSegments(keptByLine, totalLines, sourceIndexMap, nameIndexMap) {
17647
+ const lines = [];
17433
17648
  let prevSourceIndex = 0;
17434
17649
  let prevSourceLine = 0;
17435
17650
  let prevSourceColumn = 0;
17436
17651
  let prevNameIndex = 0;
17437
- for (let lineNum = 0;lineNum < lines.length; lineNum++) {
17438
- const line = lines[lineNum];
17439
- if (!line)
17652
+ for (let line = 0;line < totalLines; line++) {
17653
+ const segs = keptByLine.get(line);
17654
+ if (!segs) {
17655
+ lines.push("");
17440
17656
  continue;
17441
- if (lineNum > 0) {
17442
- result.push(";");
17443
- prevColumn = 0;
17444
- }
17445
- const segments = [];
17446
- for (const segment of line.segments) {
17447
- if (segment.sourceIndex !== undefined) {
17448
- const newSourceIndex = sourceIndexMap.get(segment.sourceIndex);
17449
- if (newSourceIndex === undefined) {
17450
- continue;
17451
- }
17452
- }
17453
- const parts = [];
17454
- const colDelta = segment.column - prevColumn;
17455
- parts.push(encodeVLQ(colDelta));
17456
- prevColumn = segment.column;
17457
- if (segment.sourceIndex !== undefined) {
17458
- const newSourceIndex = sourceIndexMap.get(segment.sourceIndex);
17459
- const srcDelta = newSourceIndex - prevSourceIndex;
17460
- parts.push(encodeVLQ(srcDelta));
17657
+ }
17658
+ let prevColumn = 0;
17659
+ const parts = [];
17660
+ for (const seg of segs) {
17661
+ let encoded = encodeVLQ(seg.column - prevColumn);
17662
+ prevColumn = seg.column;
17663
+ if (seg.sourceIndex !== undefined) {
17664
+ const newSourceIndex = sourceIndexMap.get(seg.sourceIndex);
17665
+ encoded += encodeVLQ(newSourceIndex - prevSourceIndex);
17461
17666
  prevSourceIndex = newSourceIndex;
17462
- if (segment.sourceLine !== undefined) {
17463
- const lineDelta = segment.sourceLine - prevSourceLine;
17464
- parts.push(encodeVLQ(lineDelta));
17465
- prevSourceLine = segment.sourceLine;
17466
- if (segment.sourceColumn !== undefined) {
17467
- const colDelta2 = segment.sourceColumn - prevSourceColumn;
17468
- parts.push(encodeVLQ(colDelta2));
17469
- prevSourceColumn = segment.sourceColumn;
17470
- if (segment.nameIndex !== undefined) {
17471
- const newNameIndex = nameIndexMap.get(segment.nameIndex);
17667
+ if (seg.sourceLine !== undefined) {
17668
+ encoded += encodeVLQ(seg.sourceLine - prevSourceLine);
17669
+ prevSourceLine = seg.sourceLine;
17670
+ if (seg.sourceColumn !== undefined) {
17671
+ encoded += encodeVLQ(seg.sourceColumn - prevSourceColumn);
17672
+ prevSourceColumn = seg.sourceColumn;
17673
+ if (seg.nameIndex !== undefined) {
17674
+ const newNameIndex = nameIndexMap.get(seg.nameIndex);
17472
17675
  if (newNameIndex !== undefined) {
17473
- const nameDelta = newNameIndex - prevNameIndex;
17474
- parts.push(encodeVLQ(nameDelta));
17676
+ encoded += encodeVLQ(newNameIndex - prevNameIndex);
17475
17677
  prevNameIndex = newNameIndex;
17476
17678
  }
17477
17679
  }
17478
17680
  }
17479
17681
  }
17480
17682
  }
17481
- segments.push(parts.join(""));
17683
+ parts.push(encoded);
17482
17684
  }
17483
- result.push(segments.join(","));
17685
+ lines.push(parts.join(","));
17484
17686
  }
17485
- return result.join("");
17687
+ return lines.join(";");
17486
17688
  }
17487
17689
  async function optimizeSourceMap(options) {
17488
17690
  const { sourceMapPath, agentSrcPath } = options;
@@ -17503,7 +17705,7 @@ async function optimizeSourceMap(options) {
17503
17705
  indicesToKeep.add(i);
17504
17706
  }
17505
17707
  }
17506
- const parsedLines = parseMappings(sourceMap.mappings);
17708
+ const { keptByLine, totalLines, usedNameIndices } = collectKeptSegments(sourceMap.mappings, indicesToKeep);
17507
17709
  const newSources = [];
17508
17710
  const newSourcesContent = [];
17509
17711
  const sourceIndexMap = new Map;
@@ -17519,14 +17721,6 @@ async function optimizeSourceMap(options) {
17519
17721
  newSourcesContent.push(sourceMap.sourcesContent[oldIndex] || null);
17520
17722
  }
17521
17723
  }
17522
- const usedNameIndices = new Set;
17523
- for (const line of parsedLines) {
17524
- for (const segment of line.segments) {
17525
- if (segment.sourceIndex !== undefined && indicesToKeep.has(segment.sourceIndex) && segment.nameIndex !== undefined) {
17526
- usedNameIndices.add(segment.nameIndex);
17527
- }
17528
- }
17529
- }
17530
17724
  const newNames = [];
17531
17725
  const nameIndexMap = new Map;
17532
17726
  if (sourceMap.names) {
@@ -17541,7 +17735,7 @@ async function optimizeSourceMap(options) {
17541
17735
  }
17542
17736
  }
17543
17737
  }
17544
- const newMappings = rebuildMappings(parsedLines, sourceIndexMap, nameIndexMap);
17738
+ const newMappings = encodeKeptSegments(keptByLine, totalLines, sourceIndexMap, nameIndexMap);
17545
17739
  const optimizedSourceMap = {
17546
17740
  version: sourceMap.version,
17547
17741
  file: sourceMap.file,
@@ -17727,6 +17921,37 @@ function classifyFatalStderr(text, port) {
17727
17921
  return null;
17728
17922
  }
17729
17923
 
17924
+ // src/commands/bp-dev-worker-env.ts
17925
+ function isEnabled(value) {
17926
+ const normalized = value?.trim().toLowerCase();
17927
+ return normalized === "1" || normalized === "true";
17928
+ }
17929
+ function shouldDisableSourceMaps(env) {
17930
+ return isEnabled(env.ADK_DEV_WORKER_DISABLE_SOURCE_MAPS);
17931
+ }
17932
+ function compactNodeOptions(options) {
17933
+ return options.map((option) => option?.trim()).filter((option) => !!option).join(" ");
17934
+ }
17935
+ function stripEnableSourceMapsOption(nodeOptions) {
17936
+ return (nodeOptions ?? "").replace(/(^|\s)--enable-source-maps(?=\s|$)/g, " ").trim().replace(/\s+/g, " ");
17937
+ }
17938
+ function shouldEnableWorkerSourceMaps(env = process.env) {
17939
+ if (shouldDisableSourceMaps(env)) {
17940
+ return false;
17941
+ }
17942
+ return isEnabled(env.ADK_DEV_WORKER_SOURCE_MAPS);
17943
+ }
17944
+ function shouldPassSourceMapFlag(sourceMap, env = process.env) {
17945
+ return sourceMap && !shouldDisableSourceMaps(env);
17946
+ }
17947
+ function getWorkerNodeOptions(env = process.env) {
17948
+ return compactNodeOptions([
17949
+ stripEnableSourceMapsOption(env.NODE_OPTIONS),
17950
+ shouldEnableWorkerSourceMaps(env) ? "--enable-source-maps" : undefined,
17951
+ stripEnableSourceMapsOption(env.ADK_DEV_WORKER_NODE_OPTIONS_EXTRA)
17952
+ ]);
17953
+ }
17954
+
17730
17955
  // src/commands/bp-dev-command.ts
17731
17956
  class BpDevCommand extends BaseCommand {
17732
17957
  options;
@@ -17753,9 +17978,12 @@ class BpDevCommand extends BaseCommand {
17753
17978
  "--apiUrl",
17754
17979
  credentials.apiUrl
17755
17980
  ];
17756
- if (sourceMap) {
17981
+ if (shouldPassSourceMapFlag(sourceMap)) {
17757
17982
  bpArgs.push("--sourceMap");
17758
17983
  }
17984
+ if (this.options.watch === false) {
17985
+ bpArgs.push("--no-watch");
17986
+ }
17759
17987
  if (this.options.secrets) {
17760
17988
  for (const [key, value] of Object.entries(this.options.secrets)) {
17761
17989
  bpArgs.push("--secrets", `${key}=${value}`);
@@ -17774,8 +18002,8 @@ class BpDevCommand extends BaseCommand {
17774
18002
  cwd: botPath,
17775
18003
  env: getBpCliEnvironment({
17776
18004
  TRACE_DIR: join6(botPath, "traces"),
17777
- NODE_ENV: "development",
17778
- VM_DRIVER: "node",
18005
+ NODE_ENV: process.env.ADK_DEV_WORKER_NODE_ENV || "development",
18006
+ VM_DRIVER: process.env.ADK_DEV_WORKER_VM_DRIVER || "node",
17779
18007
  ADK_LOCAL_PAT: credentials.token,
17780
18008
  ADK_TOKEN: credentials.token,
17781
18009
  ADK_API_URL: credentials.apiUrl,
@@ -17792,7 +18020,7 @@ class BpDevCommand extends BaseCommand {
17792
18020
  ...this.options.botName && { ADK_BOT_NAME: this.options.botName },
17793
18021
  ADK_DIRECTORY: join6(botPath, ".."),
17794
18022
  AGENT_DIRECTORY: this.options.agentPath,
17795
- NODE_OPTIONS: `${process.env.NODE_OPTIONS || ""} --enable-source-maps`.trim()
18023
+ NODE_OPTIONS: getWorkerNodeOptions()
17796
18024
  }),
17797
18025
  extendEnv: false,
17798
18026
  stdio: ["ignore", "pipe", "pipe"]
@@ -18048,6 +18276,9 @@ class BpChatCommand extends BaseCommand {
18048
18276
  }
18049
18277
  }
18050
18278
  }
18279
+ // src/index.ts
18280
+ init_src();
18281
+
18051
18282
  // src/workspace/workspace-cache.ts
18052
18283
  init_auth();
18053
18284
  import { Client as Client4 } from "@botpress/client";
@@ -18110,12 +18341,16 @@ function getRelativeTime(date) {
18110
18341
  }
18111
18342
  }
18112
18343
  // src/utils/require-chat.ts
18344
+ init_src();
18113
18345
  var chatBundle = __toESM(require_chat_bundle(), 1);
18114
18346
  function getChatClient() {
18115
18347
  const mod = chatBundle;
18116
18348
  const Client5 = mod.default?.Client ?? mod.Client;
18117
18349
  if (!Client5) {
18118
- throw new Error("@botpress/chat bundle did not expose a Client export — build artifact may be stale.");
18350
+ throw new AdkError({
18351
+ code: "CHAT_BUNDLE_STALE",
18352
+ message: "@botpress/chat bundle did not expose a Client export — build artifact may be stale."
18353
+ });
18119
18354
  }
18120
18355
  return Client5;
18121
18356
  }
@@ -18197,6 +18432,7 @@ function buildExportLine(exportName, llm) {
18197
18432
  }
18198
18433
  // src/agent-project/file-watcher.ts
18199
18434
  init_types2();
18435
+ init_src();
18200
18436
  import { watch } from "fs";
18201
18437
  import { EventEmitter as EventEmitter2 } from "events";
18202
18438
  import path18 from "path";
@@ -18218,7 +18454,7 @@ class FileWatcher extends EventEmitter2 {
18218
18454
  }
18219
18455
  start() {
18220
18456
  if (this.watcher) {
18221
- throw new Error("Watcher already started");
18457
+ throw new AdkError({ code: "WATCHER_ALREADY_STARTED", expected: false, message: "Watcher already started" });
18222
18458
  }
18223
18459
  this.watcher = watch(this.basePath, { recursive: true }, (eventType, filename) => {
18224
18460
  if (!filename)
@@ -18276,6 +18512,7 @@ init_validation_errors();
18276
18512
  init_agent_resolver();
18277
18513
  init_types2();
18278
18514
  // src/config/manager.ts
18515
+ init_src();
18279
18516
  init_auth();
18280
18517
  import { sync as jex } from "@bpinternal/jex";
18281
18518
 
@@ -18369,7 +18606,12 @@ class ConfigManager {
18369
18606
  }
18370
18607
  await client.updateBot(updates);
18371
18608
  } catch (error) {
18372
- throw new Error(`Failed to save configuration to bot ${this.botId}: ${error}`);
18609
+ throw new AdkError({
18610
+ code: "BOT_CONFIG_SAVE_FAILED",
18611
+ message: `Failed to save configuration to bot ${this.botId}: ${error}`,
18612
+ expected: true,
18613
+ cause: error
18614
+ });
18373
18615
  }
18374
18616
  }
18375
18617
  async get(key) {
@@ -18460,6 +18702,7 @@ class ConfigManager {
18460
18702
  }
18461
18703
  }
18462
18704
  // src/secrets/manager.ts
18705
+ init_src();
18463
18706
  import fs14 from "fs/promises";
18464
18707
  import path19 from "path";
18465
18708
 
@@ -18469,12 +18712,42 @@ class SecretsManager {
18469
18712
  this.storePath = path19.join(projectPath, ".adk", "secrets.json");
18470
18713
  }
18471
18714
  async readStore() {
18715
+ let content;
18472
18716
  try {
18473
- const content = await fs14.readFile(this.storePath, "utf-8");
18474
- return JSON.parse(content);
18475
- } catch {
18476
- return { dev: {}, prod: {} };
18717
+ content = await fs14.readFile(this.storePath, "utf-8");
18718
+ } catch (err) {
18719
+ if (err.code === "ENOENT") {
18720
+ return { dev: {}, prod: {} };
18721
+ }
18722
+ throw new AdkError({
18723
+ code: "SECRETS_STORE_UNREADABLE",
18724
+ message: `Could not read the local secrets store at ${this.storePath}.`,
18725
+ expected: true,
18726
+ suggestion: "Check the file permissions, or delete the file to start over (local secret values will be lost).",
18727
+ cause: err
18728
+ });
18729
+ }
18730
+ let parsed;
18731
+ try {
18732
+ parsed = JSON.parse(content);
18733
+ } catch (err) {
18734
+ throw new AdkError({
18735
+ code: "SECRETS_STORE_CORRUPT",
18736
+ message: `The local secrets store at ${this.storePath} is not valid JSON.`,
18737
+ expected: true,
18738
+ suggestion: "Fix the JSON by hand, or delete the file and re-enter your secrets with `adk secrets set` (local secret values will be lost).",
18739
+ cause: err
18740
+ });
18741
+ }
18742
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.dev !== "object" || typeof parsed.prod !== "object") {
18743
+ throw new AdkError({
18744
+ code: "SECRETS_STORE_CORRUPT",
18745
+ message: `The local secrets store at ${this.storePath} has an unexpected shape (expected { dev, prod }).`,
18746
+ expected: true,
18747
+ suggestion: "Fix the JSON by hand, or delete the file and re-enter your secrets with `adk secrets set` (local secret values will be lost)."
18748
+ });
18477
18749
  }
18750
+ return parsed;
18478
18751
  }
18479
18752
  async writeStore(store) {
18480
18753
  await fs14.mkdir(path19.dirname(this.storePath), { recursive: true });
@@ -18522,6 +18795,7 @@ class SecretsManager {
18522
18795
  import { validateSecretName } from "@botpress/runtime/definition";
18523
18796
 
18524
18797
  // src/agent-init/agent-project-generator.ts
18798
+ init_src();
18525
18799
  init_utils();
18526
18800
  import * as fs15 from "fs";
18527
18801
  import * as path20 from "path";
@@ -18624,12 +18898,16 @@ class AgentProjectGenerator {
18624
18898
  }
18625
18899
  const tried = candidates.map((c) => ` - ${c}`).join(`
18626
18900
  `);
18627
- throw new Error(`Could not find templates directory.
18901
+ throw new AdkError({
18902
+ code: "TEMPLATES_DIR_NOT_FOUND",
18903
+ expected: false,
18904
+ message: `Could not find templates directory.
18628
18905
 
18629
18906
  Searched:
18630
18907
  ${tried}
18631
18908
 
18632
- Ensure the ADK package is properly installed or run the CLI build.`);
18909
+ Ensure the ADK package is properly installed or run the CLI build.`
18910
+ });
18633
18911
  }
18634
18912
  resolveTemplateDir() {
18635
18913
  const templatesRoot = AgentProjectGenerator.getTemplatesRoot();
@@ -18638,21 +18916,31 @@ Ensure the ADK package is properly installed or run the CLI build.`);
18638
18916
  const available = AgentProjectGenerator.getAvailableTemplates();
18639
18917
  const names = available.map((t) => ` - ${t.name}: ${t.description}`).join(`
18640
18918
  `);
18641
- throw new Error(`Unknown template: "${this.template}"
18919
+ const validNames = available.map((t) => t.name).join(", ");
18920
+ throw new AdkError({
18921
+ code: "UNKNOWN_TEMPLATE",
18922
+ expected: true,
18923
+ message: `Unknown template: "${this.template}"
18642
18924
 
18643
18925
  Available templates:
18644
- ${names || " (none found)"}`);
18926
+ ${names || " (none found)"}`,
18927
+ suggestion: validNames ? `Re-run with a valid template name (one of: ${validNames}).` : "Re-run with a valid template name."
18928
+ });
18645
18929
  }
18646
18930
  const configFile = path20.join(templateDir, "agent.config.ts");
18647
18931
  if (!fs15.existsSync(configFile)) {
18648
- throw new Error(`Template "${this.template}" is missing agent.config.ts`);
18932
+ throw new AdkError({
18933
+ code: "TEMPLATE_INVALID",
18934
+ expected: false,
18935
+ message: `Template "${this.template}" is missing agent.config.ts`
18936
+ });
18649
18937
  }
18650
18938
  return templateDir;
18651
18939
  }
18652
18940
  async copyTemplateFiles(templateDir) {
18653
18941
  const substitutions = {
18654
18942
  "{{projectName}}": this.projectName,
18655
- "{{runtimeVersion}}": "1.19.0-beta.7",
18943
+ "{{runtimeVersion}}": "1.19.0-beta.9",
18656
18944
  "{{packageManager}}": this.packageManager
18657
18945
  };
18658
18946
  await this.copyDirRecursive(templateDir, this.projectPath, substitutions);
@@ -18693,7 +18981,12 @@ ${names || " (none found)"}`);
18693
18981
  }
18694
18982
  const files = fs15.readdirSync(this.projectPath);
18695
18983
  if (files.length > 0) {
18696
- throw new Error(`Directory ${this.projectPath} is not empty. Please use an empty directory.`);
18984
+ throw new AdkError({
18985
+ code: "TARGET_DIR_NOT_EMPTY",
18986
+ expected: true,
18987
+ message: `Directory ${this.projectPath} is not empty. Please use an empty directory.`,
18988
+ suggestion: "Use an empty directory or pass the overwrite option to replace the existing contents."
18989
+ });
18697
18990
  }
18698
18991
  }
18699
18992
  createAgentJson() {
@@ -19719,6 +20012,7 @@ export function createAdkClient(client: Client): AdkClient {
19719
20012
  await createFile(clientWrapperPath, formattedContent);
19720
20013
  }
19721
20014
  // src/bot-generator/generator.ts
20015
+ init_src();
19722
20016
  import dedent from "dedent";
19723
20017
  import { existsSync as existsSync7 } from "fs";
19724
20018
  import fs21 from "fs/promises";
@@ -20843,6 +21137,7 @@ function isProjectCache(value) {
20843
21137
  }
20844
21138
 
20845
21139
  // src/bot-generator/integration-sync.ts
21140
+ init_src();
20846
21141
  init_agent_project();
20847
21142
  init_auth();
20848
21143
  import path39 from "path";
@@ -20852,11 +21147,21 @@ class IntegrationSync {
20852
21147
  projectPath;
20853
21148
  botProjectPath;
20854
21149
  bpModulesPath;
21150
+ credentialsPromise = null;
20855
21151
  constructor(projectPath, botProjectPath) {
20856
21152
  this.projectPath = projectPath;
20857
21153
  this.botProjectPath = botProjectPath;
20858
21154
  this.bpModulesPath = path39.join(botProjectPath, "bp_modules");
20859
21155
  }
21156
+ getCredentials() {
21157
+ if (!this.credentialsPromise) {
21158
+ this.credentialsPromise = (async () => {
21159
+ const project = await AgentProject.load(this.projectPath);
21160
+ return resolveWorkspaceCredentials({ project });
21161
+ })();
21162
+ }
21163
+ return this.credentialsPromise;
21164
+ }
20860
21165
  async parseIntegrations() {
20861
21166
  const project = await AgentProject.load(this.projectPath);
20862
21167
  const dependencies = project.dependencies;
@@ -20907,8 +21212,7 @@ class IntegrationSync {
20907
21212
  }
20908
21213
  }
20909
21214
  async installIntegration(integration) {
20910
- const project = await AgentProject.load(this.projectPath);
20911
- const credentials = await resolveWorkspaceCredentials({ project });
21215
+ const credentials = await this.getCredentials();
20912
21216
  const command = new BpAddCommand({
20913
21217
  resource: `integration:${integration.fullVersion}`,
20914
21218
  botPath: this.botProjectPath,
@@ -20925,7 +21229,11 @@ class IntegrationSync {
20925
21229
  const sourceFolder = path39.join(this.bpModulesPath, integration.name.replace(/[/_]/g, "-"));
20926
21230
  const targetFolder = path39.join(this.bpModulesPath, `integration_${integration.alias}`);
20927
21231
  if (!existsSync4(sourceFolder)) {
20928
- throw new Error(`Integration folder not found: ${sourceFolder}`);
21232
+ throw new AdkError({
21233
+ code: "GENERATED_FOLDER_MISSING",
21234
+ message: `Integration folder not found: ${sourceFolder}`,
21235
+ expected: false
21236
+ });
20929
21237
  }
20930
21238
  if (existsSync4(targetFolder)) {
20931
21239
  await fs18.rm(targetFolder, { recursive: true, force: true });
@@ -20967,6 +21275,7 @@ class IntegrationSync {
20967
21275
  }
20968
21276
 
20969
21277
  // src/bot-generator/interface-sync.ts
21278
+ init_src();
20970
21279
  init_agent_project();
20971
21280
  init_auth();
20972
21281
  import path40 from "path";
@@ -20977,11 +21286,21 @@ class InterfaceSync {
20977
21286
  projectPath;
20978
21287
  botProjectPath;
20979
21288
  bpModulesPath;
21289
+ credentialsPromise = null;
20980
21290
  constructor(projectPath, botProjectPath) {
20981
21291
  this.projectPath = projectPath;
20982
21292
  this.botProjectPath = botProjectPath;
20983
21293
  this.bpModulesPath = path40.join(botProjectPath, "bp_modules");
20984
21294
  }
21295
+ getCredentials() {
21296
+ if (!this.credentialsPromise) {
21297
+ this.credentialsPromise = (async () => {
21298
+ const project = await AgentProject.load(this.projectPath);
21299
+ return resolveWorkspaceCredentials({ project });
21300
+ })();
21301
+ }
21302
+ return this.credentialsPromise;
21303
+ }
20985
21304
  async parseInterfaces() {
20986
21305
  const interfaces = [];
20987
21306
  for (const [alias, fullVersion] of Object.entries(BUILTIN_INTERFACES)) {
@@ -21019,8 +21338,7 @@ class InterfaceSync {
21019
21338
  }
21020
21339
  }
21021
21340
  async installInterface(interfaceInfo) {
21022
- const project = await AgentProject.load(this.projectPath);
21023
- const credentials = await resolveWorkspaceCredentials({ project });
21341
+ const credentials = await this.getCredentials();
21024
21342
  return new Promise((resolve4, reject) => {
21025
21343
  const command = new BpAddCommand({
21026
21344
  resource: `interface:${interfaceInfo.fullVersion}`,
@@ -21048,7 +21366,11 @@ class InterfaceSync {
21048
21366
  const sourceFolder = path40.join(this.bpModulesPath, interfaceInfo.name);
21049
21367
  const targetFolder = path40.join(this.bpModulesPath, `interface_${pascalCase(interfaceInfo.alias)}`);
21050
21368
  if (!existsSync5(sourceFolder)) {
21051
- throw new Error(`Interface folder not found: ${sourceFolder}`);
21369
+ throw new AdkError({
21370
+ code: "GENERATED_FOLDER_MISSING",
21371
+ message: `Interface folder not found: ${sourceFolder}`,
21372
+ expected: false
21373
+ });
21052
21374
  }
21053
21375
  if (existsSync5(targetFolder)) {
21054
21376
  await fs19.rm(targetFolder, { recursive: true, force: true });
@@ -21090,6 +21412,7 @@ class InterfaceSync {
21090
21412
  }
21091
21413
 
21092
21414
  // src/bot-generator/plugin-sync.ts
21415
+ init_src();
21093
21416
  init_agent_project();
21094
21417
  init_auth();
21095
21418
  import path41 from "path";
@@ -21099,11 +21422,21 @@ class PluginSync {
21099
21422
  projectPath;
21100
21423
  botProjectPath;
21101
21424
  bpModulesPath;
21425
+ credentialsPromise = null;
21102
21426
  constructor(projectPath, botProjectPath) {
21103
21427
  this.projectPath = projectPath;
21104
21428
  this.botProjectPath = botProjectPath;
21105
21429
  this.bpModulesPath = path41.join(botProjectPath, "bp_modules");
21106
21430
  }
21431
+ getCredentials() {
21432
+ if (!this.credentialsPromise) {
21433
+ this.credentialsPromise = (async () => {
21434
+ const project = await AgentProject.load(this.projectPath);
21435
+ return resolveWorkspaceCredentials({ project });
21436
+ })();
21437
+ }
21438
+ return this.credentialsPromise;
21439
+ }
21107
21440
  async parsePlugins() {
21108
21441
  const project = await AgentProject.load(this.projectPath);
21109
21442
  const dependencies = project.dependencies;
@@ -21146,8 +21479,7 @@ class PluginSync {
21146
21479
  }
21147
21480
  }
21148
21481
  async installPlugin(plugin) {
21149
- const project = await AgentProject.load(this.projectPath);
21150
- const credentials = await resolveWorkspaceCredentials({ project });
21482
+ const credentials = await this.getCredentials();
21151
21483
  const command = new BpAddCommand({
21152
21484
  resource: `plugin:${plugin.fullVersion}`,
21153
21485
  botPath: this.botProjectPath,
@@ -21164,7 +21496,11 @@ class PluginSync {
21164
21496
  const sourceFolder = path41.join(this.bpModulesPath, plugin.name.replace("/", "-"));
21165
21497
  const targetFolder = path41.join(this.bpModulesPath, `plugin_${plugin.alias}`);
21166
21498
  if (!existsSync6(sourceFolder)) {
21167
- throw new Error(`Plugin folder not found: ${sourceFolder}`);
21499
+ throw new AdkError({
21500
+ code: "GENERATED_FOLDER_MISSING",
21501
+ message: `Plugin folder not found: ${sourceFolder}`,
21502
+ expected: false
21503
+ });
21168
21504
  }
21169
21505
  if (existsSync6(targetFolder)) {
21170
21506
  await fs20.rm(targetFolder, { recursive: true, force: true });
@@ -21748,8 +22084,13 @@ declare module "@botpress/runtime/_types/state" {
21748
22084
  if (depRefErrors.length > 0) {
21749
22085
  const messages = depRefErrors.map((e) => e.message).join(`
21750
22086
  `);
21751
- throw new Error(`Plugin dependency validation failed:
21752
- ${messages}`);
22087
+ throw new AdkError({
22088
+ code: "PLUGIN_DEP_VALIDATION_FAILED",
22089
+ message: `Plugin dependency validation failed:
22090
+ ${messages}`,
22091
+ expected: true,
22092
+ details: { errors: depRefErrors }
22093
+ });
21753
22094
  }
21754
22095
  const plugins = project.dependencies?.plugins || {};
21755
22096
  const addPlugins = [];
@@ -22635,14 +22976,16 @@ export default bot;`;
22635
22976
  }
22636
22977
  async function generateBotProject(options) {
22637
22978
  const generator = new BotGenerator(options);
22638
- await generator.generate();
22639
- await generator.generateAdkRuntime();
22640
- await generator.copyAssetsRuntime();
22641
22979
  const botPath = options.outputPath || path44.join(options.projectPath, ".adk", "bot");
22642
- await linkSdk(options.projectPath, botPath);
22643
- const devIdManager = new DevIdManager(options.projectPath, options.outputPath || path44.join(options.projectPath, ".adk", "bot"));
22644
- await devIdManager.restoreDevId();
22645
- const integrationSync = new IntegrationSync(options.projectPath, options.outputPath || path44.join(options.projectPath, ".adk", "bot"));
22980
+ await generator.generate();
22981
+ const devIdManager = new DevIdManager(options.projectPath, botPath);
22982
+ await Promise.all([
22983
+ generator.generateAdkRuntime(),
22984
+ generator.copyAssetsRuntime(),
22985
+ linkSdk(options.projectPath, botPath),
22986
+ devIdManager.restoreDevId()
22987
+ ]);
22988
+ const integrationSync = new IntegrationSync(options.projectPath, botPath);
22646
22989
  const integrationSyncResult = await integrationSync.syncIntegrations();
22647
22990
  if (integrationSyncResult.errors.length > 0) {
22648
22991
  console.warn(`⚠️ Some integrations failed to sync:`);
@@ -22650,7 +22993,7 @@ async function generateBotProject(options) {
22650
22993
  console.warn(` - ${alias}: ${error}`);
22651
22994
  });
22652
22995
  }
22653
- const interfaceSync = new InterfaceSync(options.projectPath, options.outputPath || path44.join(options.projectPath, ".adk", "bot"));
22996
+ const interfaceSync = new InterfaceSync(options.projectPath, botPath);
22654
22997
  const interfaceSyncResult = await interfaceSync.syncInterfaces();
22655
22998
  if (interfaceSyncResult.errors.length > 0) {
22656
22999
  console.warn(`⚠️ Some interfaces failed to sync:`);
@@ -22658,7 +23001,7 @@ async function generateBotProject(options) {
22658
23001
  console.warn(` - ${alias}: ${error}`);
22659
23002
  });
22660
23003
  }
22661
- const pluginSync = new PluginSync(options.projectPath, options.outputPath || path44.join(options.projectPath, ".adk", "bot"));
23004
+ const pluginSync = new PluginSync(options.projectPath, botPath);
22662
23005
  const pluginSyncResult = await pluginSync.syncPlugins();
22663
23006
  if (pluginSyncResult.errors.length > 0) {
22664
23007
  console.warn(`⚠️ Some plugins failed to sync:`);
@@ -22668,6 +23011,7 @@ async function generateBotProject(options) {
22668
23011
  }
22669
23012
  }
22670
23013
  // src/tables/table-manager.ts
23014
+ init_src();
22671
23015
  init_auth();
22672
23016
  import { z as z9 } from "@botpress/sdk";
22673
23017
  var { transforms: transforms5 } = z9;
@@ -22695,7 +23039,12 @@ class TableManager {
22695
23039
  }
22696
23040
  assertBotId(operation) {
22697
23041
  if (!this.botId) {
22698
- throw new Error(`Operation "${operation}" requires a bot ID. ` + "Please deploy your agent first or create agent.json with botId and workspaceId.");
23042
+ throw new AdkError({
23043
+ code: "BOT_ID_REQUIRED",
23044
+ expected: true,
23045
+ message: `Operation "${operation}" requires a bot ID. ` + "Please deploy your agent first or create agent.json with botId and workspaceId.",
23046
+ suggestion: "Deploy your agent first or create agent.json with botId and workspaceId."
23047
+ });
22699
23048
  }
22700
23049
  }
22701
23050
  getSchemaType(schema) {
@@ -23163,6 +23512,7 @@ class TableManager {
23163
23512
  }
23164
23513
  }
23165
23514
  // src/knowledge/manager.ts
23515
+ init_src();
23166
23516
  init_auth();
23167
23517
  import crypto6 from "crypto";
23168
23518
  import path45 from "path";
@@ -23224,7 +23574,12 @@ class KnowledgeManager {
23224
23574
  }
23225
23575
  assertBotId(operation) {
23226
23576
  if (!this.botId) {
23227
- throw new Error(`Operation "${operation}" requires a bot ID. ` + "Please deploy your agent first or create agent.json with botId and workspaceId.");
23577
+ throw new AdkError({
23578
+ code: "BOT_ID_REQUIRED",
23579
+ expected: true,
23580
+ message: `Operation "${operation}" requires a bot ID. ` + "Please deploy your agent first or create agent.json with botId and workspaceId.",
23581
+ suggestion: "Deploy your agent first or create agent.json with botId and workspaceId."
23582
+ });
23228
23583
  }
23229
23584
  }
23230
23585
  formatError(error) {
@@ -23287,7 +23642,10 @@ class KnowledgeManager {
23287
23642
  this.invalidateRemoteKbsCache();
23288
23643
  const created = await this.findRemoteKB(name);
23289
23644
  if (!created) {
23290
- throw new Error(`Failed to find KB "${name}" after creation`);
23645
+ throw new AdkError({
23646
+ code: "KB_CREATE_VERIFY_FAILED",
23647
+ message: `Failed to find KB "${name}" after creation`
23648
+ });
23291
23649
  }
23292
23650
  return created;
23293
23651
  }
@@ -23660,7 +24018,11 @@ class KnowledgeManager {
23660
24018
  console.log(`Syncing KB "${item.kb.name}"...`);
23661
24019
  const kbRef = this.project.knowledge.find((k) => k.definition.name === item.kb.name);
23662
24020
  if (!kbRef) {
23663
- throw new Error(`KB "${item.kb.name}" not found in project`);
24021
+ throw new AdkError({
24022
+ code: "KB_NOT_FOUND",
24023
+ expected: true,
24024
+ message: `KB "${item.kb.name}" not found in project`
24025
+ });
23664
24026
  }
23665
24027
  let remoteKb = await this.findRemoteKB(item.kb.name);
23666
24028
  if (!remoteKb) {
@@ -23765,7 +24127,11 @@ class KnowledgeManager {
23765
24127
  const projectDir = this.project.path;
23766
24128
  const directory = path45.resolve(projectDir, directoryPath);
23767
24129
  if (!directory.startsWith(projectDir)) {
23768
- throw new Error("Directory path must be within the agent's directory");
24130
+ throw new AdkError({
24131
+ code: "PATH_OUTSIDE_PROJECT",
24132
+ expected: true,
24133
+ message: "Directory path must be within the agent's directory"
24134
+ });
23769
24135
  }
23770
24136
  const tags = {
23771
24137
  [WellKnownTags.KNOWLEDGE]: "knowledge-base",
@@ -24441,6 +24807,7 @@ function superviseChild(child, options = {}) {
24441
24807
  }
24442
24808
 
24443
24809
  // src/runner/script-runner.ts
24810
+ init_src();
24444
24811
  async function findAgentRoot(startPath) {
24445
24812
  let currentPath = path47.resolve(startPath);
24446
24813
  const root = path47.parse(currentPath).root;
@@ -24599,7 +24966,13 @@ class ScriptRunner {
24599
24966
  const workspaceId = project.agentInfo?.workspaceId || this.credentials.workspaceId || "";
24600
24967
  if (!botId) {
24601
24968
  const idType = this.prod ? "botId" : "devId";
24602
- throw new Error(`No ${idType} found in agent.json. ` + (this.prod ? 'Please deploy your agent first with "adk deploy".' : 'Please run "adk dev" first to create a development bot, or use --prod to use the production bot.'));
24969
+ const suggestion = this.prod ? 'Please deploy your agent first with "adk deploy".' : 'Please run "adk dev" first to create a development bot, or use --prod to use the production bot.';
24970
+ throw new AdkError({
24971
+ code: "BOT_ID_REQUIRED",
24972
+ expected: true,
24973
+ message: `No ${idType} found in agent.json. ` + suggestion,
24974
+ suggestion
24975
+ });
24603
24976
  }
24604
24977
  let configuration;
24605
24978
  try {
@@ -24676,13 +25049,23 @@ class ScriptRunner {
24676
25049
  const { botPath, runnerPath, project } = await this.prepare();
24677
25050
  const absoluteScriptPath = path47.isAbsolute(scriptPath) ? scriptPath : path47.resolve(this.projectPath, scriptPath);
24678
25051
  if (!existsSync9(absoluteScriptPath)) {
24679
- throw new Error(`Script not found: ${absoluteScriptPath}`);
25052
+ throw new AdkError({
25053
+ code: "SCRIPT_NOT_FOUND",
25054
+ expected: true,
25055
+ message: `Script not found: ${absoluteScriptPath}`
25056
+ });
24680
25057
  }
24681
25058
  const botId = this.prod ? project.agentInfo?.botId : project.agentInfo?.devId || project.agentInfo?.botId;
24682
25059
  const workspaceId = project.agentInfo?.workspaceId || this.credentials.workspaceId;
24683
25060
  if (!botId) {
24684
25061
  const idType = this.prod ? "botId" : "devId";
24685
- throw new Error(`No ${idType} found in agent.json. ` + (this.prod ? 'Please deploy your agent first with "adk deploy".' : 'Please run "adk dev" first to create a development bot, or use --prod to use the production bot.'));
25062
+ const suggestion = this.prod ? 'Please deploy your agent first with "adk deploy".' : 'Please run "adk dev" first to create a development bot, or use --prod to use the production bot.';
25063
+ throw new AdkError({
25064
+ code: "BOT_ID_REQUIRED",
25065
+ expected: true,
25066
+ message: `No ${idType} found in agent.json. ` + suggestion,
25067
+ suggestion
25068
+ });
24686
25069
  }
24687
25070
  const args = ["run", runnerPath, absoluteScriptPath, ...options.args || []];
24688
25071
  let configuration;
@@ -24734,8 +25117,13 @@ async function setupTestRuntime(options = {}) {
24734
25117
  if (!projectPath) {
24735
25118
  const detected = await findAgentRoot(process.cwd());
24736
25119
  if (!detected) {
24737
- throw new Error(`Could not find ADK agent project. No agent.config.ts found in current directory or parents.
24738
- Either run from within an agent project directory, or provide projectPath explicitly.`);
25120
+ throw new AdkError({
25121
+ code: "PROJECT_NOT_FOUND",
25122
+ expected: true,
25123
+ message: `Could not find ADK agent project. No agent.config.ts found in current directory or parents.
25124
+ Either run from within an agent project directory, or provide projectPath explicitly.`,
25125
+ suggestion: "Either run from within an agent project directory, or provide projectPath explicitly."
25126
+ });
24739
25127
  }
24740
25128
  projectPath = detected;
24741
25129
  }
@@ -24772,6 +25160,7 @@ export {
24772
25160
  resolveBotCredentials,
24773
25161
  pluralize2 as pluralize,
24774
25162
  orderKeys,
25163
+ isAdkError,
24775
25164
  integrationKeyOrder,
24776
25165
  initAssets,
24777
25166
  getRelativeTime,
@@ -24842,7 +25231,8 @@ export {
24842
25231
  AssetsManager,
24843
25232
  AgentProjectGenerator,
24844
25233
  AgentProject,
25234
+ AdkError,
24845
25235
  ADK_MANIFEST_BOT_TAGS
24846
25236
  };
24847
25237
 
24848
- //# debugId=375110FEE55C43C964756E2164756E21
25238
+ //# debugId=0592B7F499E9D09F64756E2164756E21