@botpress/runtime 1.13.13 → 1.13.15

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.
@@ -48,7 +48,7 @@ var init_define_BUILD = __esm({
48
48
  var define_PACKAGE_VERSIONS_default;
49
49
  var init_define_PACKAGE_VERSIONS = __esm({
50
50
  "<define:__PACKAGE_VERSIONS__>"() {
51
- define_PACKAGE_VERSIONS_default = { runtime: "1.13.13", adk: "1.13.13", sdk: "5.0.2", llmz: "0.0.37", zai: "2.5.6", cognitive: "0.3.3" };
51
+ define_PACKAGE_VERSIONS_default = { runtime: "1.13.15", adk: "1.13.15", sdk: "5.0.2", llmz: "0.0.37", zai: "2.5.6", cognitive: "0.3.3" };
52
52
  }
53
53
  });
54
54
 
@@ -10657,7 +10657,7 @@ var require_form_data = __commonJS({
10657
10657
  var parseUrl = __require("url").parse;
10658
10658
  var fs3 = __require("fs");
10659
10659
  var Stream2 = __require("stream").Stream;
10660
- var crypto2 = __require("crypto");
10660
+ var crypto3 = __require("crypto");
10661
10661
  var mime = require_mime_types();
10662
10662
  var asynckit = require_asynckit();
10663
10663
  var setToStringTag = require_es_set_tostringtag();
@@ -10863,7 +10863,7 @@ var require_form_data = __commonJS({
10863
10863
  return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
10864
10864
  };
10865
10865
  FormData3.prototype._generateBoundary = function() {
10866
- this._boundary = "--------------------------" + crypto2.randomBytes(12).toString("hex");
10866
+ this._boundary = "--------------------------" + crypto3.randomBytes(12).toString("hex");
10867
10867
  };
10868
10868
  FormData3.prototype.getLengthSync = function() {
10869
10869
  var knownLength = this._overheadLength + this._valueLength;
@@ -11284,7 +11284,7 @@ var init_URLSearchParams = __esm({
11284
11284
  });
11285
11285
 
11286
11286
  // ../../node_modules/axios/lib/platform/node/index.js
11287
- import crypto from "crypto";
11287
+ import crypto2 from "crypto";
11288
11288
  var ALPHA, DIGIT, ALPHABET, generateString, node_default;
11289
11289
  var init_node = __esm({
11290
11290
  "../../node_modules/axios/lib/platform/node/index.js"() {
@@ -11303,7 +11303,7 @@ var init_node = __esm({
11303
11303
  let str = "";
11304
11304
  const { length } = alphabet;
11305
11305
  const randomValues = new Uint32Array(size);
11306
- crypto.randomFillSync(randomValues);
11306
+ crypto2.randomFillSync(randomValues);
11307
11307
  for (let i = 0; i < size; i++) {
11308
11308
  str += alphabet[randomValues[i] % length];
11309
11309
  }
@@ -32973,908 +32973,165 @@ var init_agent_registry = __esm({
32973
32973
  }
32974
32974
  });
32975
32975
 
32976
- // src/runtime/tracked-tags.ts
32977
- function isSystemTag(key) {
32978
- return key.includes(":");
32976
+ // src/utilities/abort-signal.ts
32977
+ function createJoinedAbortController(signals) {
32978
+ const controller = new AbortController();
32979
+ const validSignals = signals.filter((signal) => signal != null);
32980
+ if (validSignals.length === 0) {
32981
+ return controller;
32982
+ }
32983
+ for (const signal of validSignals) {
32984
+ if (signal.aborted) {
32985
+ controller.abort(signal.reason);
32986
+ return controller;
32987
+ }
32988
+ }
32989
+ const abortListeners = [];
32990
+ for (const signal of validSignals) {
32991
+ const listener = () => {
32992
+ controller.abort(signal.reason);
32993
+ cleanup();
32994
+ };
32995
+ signal.addEventListener("abort", listener);
32996
+ abortListeners.push(() => signal.removeEventListener("abort", listener));
32997
+ }
32998
+ const cleanup = () => {
32999
+ abortListeners.forEach((removeListener) => removeListener());
33000
+ };
33001
+ controller.signal.addEventListener("abort", cleanup, { once: true });
33002
+ return controller;
32979
33003
  }
32980
- var TrackedTags;
32981
- var init_tracked_tags = __esm({
32982
- "src/runtime/tracked-tags.ts"() {
33004
+ function createJoinedAbortSignal(signals) {
33005
+ return createJoinedAbortController(signals).signal;
33006
+ }
33007
+ var init_abort_signal = __esm({
33008
+ "src/utilities/abort-signal.ts"() {
32983
33009
  "use strict";
32984
33010
  init_define_BUILD();
32985
33011
  init_define_PACKAGE_VERSIONS();
32986
- init_context3();
32987
- init_tracing();
32988
- TrackedTags = class _TrackedTags {
32989
- type;
32990
- id;
32991
- client;
32992
- _tags = {};
32993
- _initialTags = {};
32994
- _loaded = false;
32995
- _saving = false;
32996
- _saveAgain = false;
32997
- _saveAgainCount = 0;
32998
- static _savingAll = false;
32999
- static _saveAllAgain = false;
33000
- static _saveAllCount = 0;
33001
- constructor(props) {
33002
- this.type = props.type;
33003
- this.id = props.id;
33004
- this.client = props.client;
33005
- }
33006
- static create(props) {
33007
- const tags = context2.get("tags", { optional: true });
33008
- const executionFinished = context2.get("executionFinished", { optional: true });
33009
- if (executionFinished) {
33010
- throw new Error(`Cannot create new TrackedTags "${props.type}/${props.id}" after execution has finished.`);
33011
- }
33012
- const match2 = tags?.find((x) => x.id === props.id && x.type === props.type);
33013
- if (match2) {
33014
- return match2;
33015
- }
33016
- const instance = new _TrackedTags(props);
33017
- if (props.initialTags) {
33018
- instance._tags = { ...props.initialTags };
33019
- instance._initialTags = { ...props.initialTags };
33020
- instance._loaded = true;
33021
- }
33022
- tags?.push(instance);
33023
- return instance;
33024
- }
33025
- static async saveAllDirty() {
33026
- if (this._savingAll) {
33027
- this._saveAllAgain = true;
33028
- return;
33029
- }
33030
- try {
33031
- this._savingAll = true;
33032
- const tags = context2.get("tags", { optional: true });
33033
- const dirtyTags = tags?.filter((t) => t.isDirty()) || [];
33034
- if (!dirtyTags.length) {
33035
- return;
33036
- }
33037
- await span(
33038
- "tags.saveAllDirty",
33039
- {
33040
- tags_count: tags?.length || 0,
33041
- tags: tags.map((t) => `${t.type}/${t.id}`)
33042
- },
33043
- () => Promise.allSettled(dirtyTags.map((t) => t.save()))
33044
- );
33045
- } finally {
33046
- this._savingAll = false;
33047
- if (this._saveAllAgain && this._saveAllCount++ <= 5) {
33048
- this._saveAllAgain = false;
33049
- await this.saveAllDirty();
33050
- } else {
33051
- this._saveAllCount = 0;
33052
- }
33053
- }
33054
- }
33055
- static async loadAll() {
33056
- await span("tags.loadAll", {}, async () => {
33057
- const client2 = context2.get("client")._inner;
33058
- const bot2 = context2.get("bot", { optional: true });
33059
- const user2 = context2.get("user", { optional: true });
33060
- const conversation = context2.get("conversation", { optional: true });
33061
- const workflow = context2.get("workflow", { optional: true });
33062
- if (bot2) {
33063
- const botTags = bot2.tags;
33064
- _TrackedTags.create({
33065
- client: client2,
33066
- type: "bot",
33067
- id: bot2.id,
33068
- ...botTags && { initialTags: botTags }
33069
- });
33070
- }
33071
- if (user2) {
33072
- const userTags = user2.tags;
33073
- _TrackedTags.create({
33074
- client: client2,
33075
- type: "user",
33076
- id: user2.id,
33077
- ...userTags && { initialTags: userTags }
33078
- });
33079
- }
33080
- if (conversation) {
33081
- const conversationTags = conversation.tags;
33082
- _TrackedTags.create({
33083
- client: client2,
33084
- type: "conversation",
33085
- id: conversation.id,
33086
- ...conversationTags && { initialTags: conversationTags }
33087
- });
33088
- }
33089
- if (workflow) {
33090
- const workflowTags = workflow.tags;
33091
- _TrackedTags.create({
33092
- client: client2,
33093
- type: "workflow",
33094
- id: workflow.id,
33095
- ...workflowTags && { initialTags: workflowTags }
33096
- });
33097
- }
33098
- const tags = context2.get("tags", { optional: true });
33099
- const unloadedTags = tags?.filter((tag) => !tag._loaded) ?? [];
33100
- if (unloadedTags.length > 0) {
33101
- await Promise.allSettled(unloadedTags.map((tag) => tag.load()));
33102
- }
33103
- });
33104
- }
33105
- static unloadAll() {
33106
- context2.get("tags", { optional: true })?.splice(0);
33107
- }
33108
- async load(force = false) {
33109
- if (this._loaded && !force) {
33110
- return;
33111
- }
33112
- await span(
33113
- "tags.load",
33114
- {
33115
- type: this.type,
33116
- id: this.id
33117
- },
33118
- async () => {
33119
- const tags = await this.fetchTags();
33120
- this._tags = { ...tags };
33121
- this._initialTags = { ...tags };
33122
- this._loaded = true;
33123
- }
33124
- );
33125
- }
33126
- async save() {
33127
- if (this._saving) {
33128
- this._saveAgain = true;
33129
- return;
33130
- }
33131
- const executionFinished = context2.get("executionFinished", { optional: true });
33132
- if (executionFinished) {
33133
- throw new Error(`Cannot save TrackedTags "${this.type}/${this.id}" after execution has finished.`);
33134
- }
33135
- try {
33136
- this._saving = true;
33137
- await span(
33138
- "tags.save",
33139
- {
33140
- type: this.type,
33141
- id: this.id
33142
- },
33143
- async () => {
33144
- await this.persistTags(this._tags);
33145
- this._initialTags = { ...this._tags };
33146
- }
33147
- );
33148
- } finally {
33149
- this._saving = false;
33150
- if (this._saveAgain && this._saveAgainCount++ <= 5) {
33151
- this._saveAgain = false;
33152
- await this.save();
33153
- } else {
33154
- this._saveAgainCount = 0;
33155
- }
33156
- }
33157
- }
33158
- isDirty() {
33159
- const currentKeys = Object.keys(this._tags).filter((k) => !isSystemTag(k)).sort();
33160
- const initialKeys = Object.keys(this._initialTags).filter((k) => !isSystemTag(k)).sort();
33161
- if (currentKeys.length !== initialKeys.length) {
33162
- return true;
33163
- }
33164
- for (const key of currentKeys) {
33165
- if (this._tags[key] !== this._initialTags[key]) {
33166
- return true;
33167
- }
33168
- }
33169
- return false;
33170
- }
33171
- get tags() {
33172
- return new Proxy(this._tags, {
33173
- set: (target, prop, value) => {
33174
- if (isSystemTag(prop)) {
33175
- return true;
33176
- }
33177
- target[prop] = value;
33178
- return true;
33179
- },
33180
- deleteProperty: (target, prop) => {
33181
- if (isSystemTag(prop)) {
33182
- return true;
33183
- }
33184
- target[prop] = void 0;
33185
- return true;
33186
- }
33187
- });
33188
- }
33189
- set tags(value) {
33190
- this._tags = { ...value };
33191
- }
33192
- async fetchTags() {
33193
- try {
33194
- if (this.type === "bot") {
33195
- const { bot: bot2 } = await this.client.getBot({ id: this.id });
33196
- return bot2.tags || {};
33197
- } else if (this.type === "user") {
33198
- const { user: user2 } = await this.client.getUser({ id: this.id });
33199
- return user2.tags || {};
33200
- } else if (this.type === "conversation") {
33201
- const { conversation } = await this.client.getConversation({ id: this.id });
33202
- return conversation.tags || {};
33203
- } else if (this.type === "workflow") {
33204
- const { workflow } = await this.client.getWorkflow({ id: this.id });
33205
- return workflow.tags || {};
33206
- }
33207
- } catch (err) {
33208
- console.error(`Failed to fetch tags for ${this.type}/${this.id}:`, err);
33209
- }
33210
- return {};
33211
- }
33212
- async persistTags(tags) {
33213
- const tagsForApi = {};
33214
- for (const [key, value] of Object.entries(tags)) {
33215
- if (value !== void 0 && !isSystemTag(key)) {
33216
- tagsForApi[key] = value;
33217
- }
33218
- }
33219
- try {
33220
- if (this.type === "bot") {
33221
- await this.client.updateBot({ id: this.id, tags: tagsForApi });
33222
- } else if (this.type === "user") {
33223
- await this.client.updateUser({ id: this.id, tags: tagsForApi });
33224
- } else if (this.type === "conversation") {
33225
- await this.client.updateConversation({ id: this.id, tags: tagsForApi });
33226
- } else if (this.type === "workflow") {
33227
- await this.client.updateWorkflow({ id: this.id, tags: tagsForApi });
33228
- }
33229
- } catch (err) {
33230
- console.error(`Failed to persist tags for ${this.type}/${this.id}:`, err);
33231
- throw err;
33232
- }
33233
- }
33234
- };
33235
33012
  }
33236
33013
  });
33237
33014
 
33238
- // src/runtime/heavy-imports.ts
33239
- var HEAVY_IMPORTS, clearScheduledHeavyImports, importScheduledHeavyImports;
33240
- var init_heavy_imports = __esm({
33241
- "src/runtime/heavy-imports.ts"() {
33015
+ // src/constants.ts
33016
+ var WellKnownTags, WellKnownMetadata;
33017
+ var init_constants = __esm({
33018
+ "src/constants.ts"() {
33242
33019
  "use strict";
33243
33020
  init_define_BUILD();
33244
33021
  init_define_PACKAGE_VERSIONS();
33245
- init_context3();
33246
- HEAVY_IMPORTS = {
33247
- sdk: () => import("@botpress/sdk"),
33248
- client: () => import("@botpress/client"),
33249
- llmz: async () => {
33250
- const llmz = await import("llmz");
33251
- await llmz.init();
33022
+ WellKnownTags = {
33023
+ knowledge: {
33024
+ /**
33025
+ * All knowledge base have this tag (with value "knowledge-base") to identify them as knowledge-related records.
33026
+ * @example "source": "knowledge-base"
33027
+ */
33028
+ KNOWLEDGE: "source",
33029
+ /**
33030
+ * The ID of the knowledge base the record belongs to.
33031
+ * This is the ID of the Knowledge Base primitive from Botpress.
33032
+ * @example "kbId": "kb_01K6RT9T39KF7K0A7R7D71TDZ1"
33033
+ */
33034
+ KNOWLEDGE_BASE_ID: "kbId",
33035
+ /**
33036
+ * The name of the knowledge base as defined in the Knowledge Base primitive by the user.
33037
+ * @example "kbName": "My Files"
33038
+ */
33039
+ KNOWLEDGE_BASE_NAME: "kbName",
33040
+ /**
33041
+ * The ID of the Data Source the record was ingested from.
33042
+ * @example "dsId": "docs"
33043
+ */
33044
+ KNOWLEDGE_SOURCE_ID: "dsId",
33045
+ /**
33046
+ * The type of the Data Source the record was ingested from.
33047
+ * Possible values are: "document", "rich-text", "web-page", etc.
33048
+ * @example "dsType": "document"
33049
+ */
33050
+ KNOWLEDGE_SOURCE_TYPE: "dsType"
33252
33051
  }
33253
33052
  };
33254
- clearScheduledHeavyImports = () => {
33255
- context2.get("scheduledHeavyImports").clear();
33256
- };
33257
- importScheduledHeavyImports = async () => {
33258
- const imports = Array.from(context2.get("scheduledHeavyImports"));
33259
- clearScheduledHeavyImports();
33260
- for (const key of imports) {
33261
- try {
33262
- void HEAVY_IMPORTS[key]?.().catch(() => {
33263
- });
33264
- } catch {
33265
- }
33053
+ WellKnownMetadata = {
33054
+ knowledge: {
33055
+ /**
33056
+ * The title of the document or page.
33057
+ * @example "title": "Getting Started Guide"
33058
+ */
33059
+ TITLE: "title",
33060
+ /**
33061
+ * The URL of the document or page.
33062
+ * @example "url": "https://example.com/docs/getting-started"
33063
+ */
33064
+ URL: "url",
33065
+ /**
33066
+ * The favicon URL of the website.
33067
+ * @example "favicon": "https://example.com/favicon.ico"
33068
+ */
33069
+ FAVICON: "favicon",
33070
+ /**
33071
+ * A brief description of the document or page.
33072
+ * @example "description": "Learn how to get started with our platform"
33073
+ */
33074
+ DESCRIPTION: "description"
33266
33075
  }
33267
33076
  };
33268
33077
  }
33269
33078
  });
33270
33079
 
33271
- // src/runtime/context/inspector-handler.ts
33272
- var init_inspector_handler = __esm({
33273
- "src/runtime/context/inspector-handler.ts"() {
33274
- "use strict";
33275
- init_define_BUILD();
33276
- init_define_PACKAGE_VERSIONS();
33277
- }
33278
- });
33279
-
33280
- // src/runtime/events.ts
33080
+ // src/runtime/autonomous.ts
33081
+ import { getValue } from "llmz";
33082
+ import {
33083
+ Tool as LlmzTool,
33084
+ ThinkSignal as _ThinkSignal,
33085
+ SnapshotSignal as _SnapshotSignal,
33086
+ CitationsManager as _CitationsManager,
33087
+ ListenExit as _ListenExit,
33088
+ ThinkExit as _ThinkExit,
33089
+ DefaultExit as _DefaultExit,
33090
+ Component as LlmzComponent
33091
+ } from "llmz";
33092
+ import { Exit as LlmzExit } from "llmz";
33093
+ import { ObjectInstance as LlmzObject } from "llmz";
33281
33094
  import { z as z3 } from "@botpress/sdk";
33282
- var WorkflowCallbackEvent, WorkflowScheduleEvent, WorkflowContinueEvent, SubworkflowFinished, WorkflowDataRequestEvent;
33283
- var init_events = __esm({
33284
- "src/runtime/events.ts"() {
33285
- "use strict";
33286
- init_define_BUILD();
33287
- init_define_PACKAGE_VERSIONS();
33288
- WorkflowCallbackEvent = {
33289
- name: "workflowCallback",
33290
- schema: z3.object({
33291
- workflow: z3.string(),
33292
- workflowId: z3.string(),
33293
- target: z3.union([
33294
- z3.object({
33295
- conversationId: z3.string()
33296
- }),
33297
- z3.object({
33298
- workflowId: z3.string()
33299
- })
33300
- ]),
33301
- status: z3.enum(["completed", "failed", "canceled", "timed_out"]),
33302
- output: z3.any().optional(),
33303
- error: z3.string().optional()
33304
- })
33305
- };
33306
- WorkflowScheduleEvent = {
33307
- name: "workflowSchedule",
33308
- schema: z3.object({
33309
- workflow: z3.string()
33310
- })
33311
- };
33312
- WorkflowContinueEvent = {
33313
- name: "workflowContinue",
33314
- schema: z3.object({})
33315
- };
33316
- SubworkflowFinished = {
33317
- name: "subworkflowFinished",
33318
- schema: z3.object({})
33319
- };
33320
- WorkflowDataRequestEvent = {
33321
- name: "workflowDataRequest",
33322
- schema: z3.object({
33323
- workflowId: z3.string(),
33324
- workflowName: z3.string(),
33325
- stepName: z3.string(),
33326
- request: z3.string(),
33327
- message: z3.string(),
33328
- schema: z3.any()
33329
- // JSON Schema
33330
- })
33331
- };
33332
- }
33333
- });
33334
-
33335
- // src/runtime/context/handlers.ts
33336
- import * as sdk from "@botpress/sdk";
33337
- import { CitationsManager } from "llmz";
33338
- import { Client } from "@botpress/client";
33339
- import { ulid } from "ulid";
33340
- var init_handlers = __esm({
33341
- "src/runtime/context/handlers.ts"() {
33095
+ import { AsyncResource } from "node:async_hooks";
33096
+ var import_lodash2, Autonomous;
33097
+ var init_autonomous = __esm({
33098
+ "src/runtime/autonomous.ts"() {
33342
33099
  "use strict";
33343
33100
  init_define_BUILD();
33344
33101
  init_define_PACKAGE_VERSIONS();
33345
- init_cognitive();
33346
- init_promises();
33347
- init_context3();
33348
- init_interfaces();
33349
- init_http2();
33350
- init_agent_registry();
33351
- init_tracked_state();
33352
- init_tracked_tags();
33102
+ init_esm();
33103
+ init_abort_signal();
33353
33104
  init_tracing();
33354
- init_heavy_imports();
33355
- init_environment();
33356
- init_inspector_handler();
33357
- init_events();
33358
- }
33359
- });
33360
-
33361
- // src/runtime/chat/truncate-object.ts
33362
- var init_truncate_object = __esm({
33363
- "src/runtime/chat/truncate-object.ts"() {
33364
- "use strict";
33365
- init_define_BUILD();
33366
- init_define_PACKAGE_VERSIONS();
33367
- }
33368
- });
33369
-
33370
- // src/runtime/chat/truncate-transcript.ts
33371
- var init_truncate_transcript = __esm({
33372
- "src/runtime/chat/truncate-transcript.ts"() {
33373
- "use strict";
33374
- init_define_BUILD();
33375
- init_define_PACKAGE_VERSIONS();
33376
- init_truncate_object();
33377
- }
33378
- });
33379
-
33380
- // src/runtime/chat/html.ts
33381
- var HTML_TAGS;
33382
- var init_html = __esm({
33383
- "src/runtime/chat/html.ts"() {
33384
- "use strict";
33385
- init_define_BUILD();
33386
- init_define_PACKAGE_VERSIONS();
33387
- HTML_TAGS = [
33388
- "html",
33389
- "head",
33390
- "body",
33391
- "div",
33392
- "span",
33393
- "a",
33394
- "img",
33395
- "video",
33396
- "audio",
33397
- "source",
33398
- "button",
33399
- "input",
33400
- "form",
33401
- "label",
33402
- "select",
33403
- "option",
33404
- "textarea",
33405
- "table",
33406
- "tr",
33407
- "td",
33408
- "th",
33409
- "thead",
33410
- "tbody",
33411
- "tfoot",
33412
- "ul",
33413
- "ol",
33414
- "li",
33415
- "h1",
33416
- "h2",
33417
- "h3",
33418
- "h4",
33419
- "h5",
33420
- "h6",
33421
- "p",
33422
- "br",
33423
- "hr",
33424
- "b",
33425
- "strong",
33426
- "i",
33427
- "em",
33428
- "u",
33429
- "s",
33430
- "strike",
33431
- "pre",
33432
- "code",
33433
- "blockquote",
33434
- "cite",
33435
- "q",
33436
- "abbr",
33437
- "acronym",
33438
- "address",
33439
- "del",
33440
- "ins",
33441
- "sub",
33442
- "sup",
33443
- "small",
33444
- "big",
33445
- "tt",
33446
- "dfn",
33447
- "kbd",
33448
- "samp",
33449
- "var",
33450
- "mark",
33451
- "ruby",
33452
- "rt",
33453
- "rp",
33454
- "bdi",
33455
- "bdo",
33456
- "wbr",
33457
- "details",
33458
- "summary",
33459
- "menu",
33460
- "menuitem",
33461
- "menuitem",
33462
- "figure",
33463
- "figcaption",
33464
- "main",
33465
- "article",
33466
- "section",
33467
- "aside",
33468
- "header",
33469
- "footer",
33470
- "nav",
33471
- "dialog",
33472
- "meter",
33473
- "progress",
33474
- "canvas",
33475
- "svg",
33476
- "math",
33477
- "iframe",
33478
- "embed",
33479
- "object",
33480
- "param",
33481
- "source",
33482
- "track",
33483
- "area",
33484
- "map",
33485
- "iframe",
33486
- "frame",
33487
- "frameset",
33488
- "noframes",
33489
- "noscript",
33490
- "style",
33491
- "link",
33492
- "meta",
33493
- "title",
33494
- "base",
33495
- "script",
33496
- "noscript",
33497
- "template"
33498
- ];
33499
- }
33500
- });
33501
-
33502
- // src/runtime/chat/messages.ts
33503
- import { z as z4 } from "@bpinternal/zui";
33504
- import { isAnyComponent } from "llmz";
33505
- function joinMarkdownChildren(children, stringify3 = (el) => JSON.stringify(el, null, 2)) {
33506
- return children.reduce((acc, child, idx) => {
33507
- const isPrimitive = typeof child === "string" || typeof child === "number" || typeof child === "boolean";
33508
- const str = isPrimitive ? child?.toString() ?? "" : stringify3(child) ?? "";
33509
- if (str.trim().length === 0) {
33510
- return acc;
33511
- }
33512
- const leftSymbols = '*_~`"[({-'.split("");
33513
- const rightSymbols = '*_~`"])}-!'.split("");
33514
- const last = idx > 0 && acc.at(-1) && typeof acc.at(-1) === "string" ? acc.at(-1) : "";
33515
- const endsWithSpace = last && last.trimEnd() !== last;
33516
- let prev = idx === 0 || endsWithSpace || last.length && leftSymbols.includes(last.at(-1)) ? "" : " ";
33517
- if (str.trimStart() !== str || str.length && rightSymbols.includes(str.at(0))) {
33518
- prev = "";
33519
- }
33520
- return [...acc, prev, str];
33521
- }, []).join("").trim();
33522
- }
33523
- function rebuildTSXCode(node, hasParent = false) {
33524
- if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
33525
- return node?.toString() ?? "";
33526
- }
33527
- if (typeof node === "undefined" || node === null || typeof node === "function" || typeof node === "symbol" || typeof node === "boolean") {
33528
- return "";
33529
- }
33530
- let { type = "", props = {}, children = [] } = node;
33531
- if (HTML_TAGS.includes(type.toLowerCase())) {
33532
- type = type.toLowerCase();
33533
- }
33534
- let openTag = `<${type}`;
33535
- Object.entries(props).forEach(([k, v]) => {
33536
- openTag += ` ${k}={${JSON.stringify(v)}}`;
33537
- });
33538
- openTag += ">";
33539
- const inner = children.map((child) => rebuildTSXCode(child, true)).join("");
33540
- const closeTag = `</${type}>`;
33541
- if (hasParent) {
33542
- return `${openTag}${inner}${closeTag}`;
33543
- }
33544
- return `
33545
- \`\`\`
33546
- ${openTag}${inner}${closeTag}
33547
- \`\`\``;
33548
- }
33549
- var Message;
33550
- var init_messages = __esm({
33551
- "src/runtime/chat/messages.ts"() {
33552
- "use strict";
33553
- init_define_BUILD();
33554
- init_define_PACKAGE_VERSIONS();
33555
- init_html();
33556
- Message = z4.object({
33557
- __jsx: z4.literal(true),
33558
- type: z4.literal("MESSAGE"),
33559
- props: z4.object({
33560
- type: z4.enum(["error", "info", "success", "prompt"]).default("info").catch(() => "info")
33561
- }).passthrough(),
33562
- children: z4.array(z4.any()).default([]).transform((children) => {
33563
- children = children.map((child) => Array.isArray(child) ? child : [child]).flat();
33564
- const text = joinMarkdownChildren(
33565
- children.filter((x) => !isAnyComponent(x)).map((x) => rebuildTSXCode(x, false))
33566
- ).trim();
33567
- const components = children.filter((child) => isAnyComponent(child));
33568
- return [text, ...components];
33569
- })
33570
- });
33571
- }
33572
- });
33573
-
33574
- // ../../node_modules/dedent/dist/dedent.mjs
33575
- function ownKeys(object, enumerableOnly) {
33576
- var keys = Object.keys(object);
33577
- if (Object.getOwnPropertySymbols) {
33578
- var symbols = Object.getOwnPropertySymbols(object);
33579
- enumerableOnly && (symbols = symbols.filter(function(sym) {
33580
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
33581
- })), keys.push.apply(keys, symbols);
33582
- }
33583
- return keys;
33584
- }
33585
- function _objectSpread(target) {
33586
- for (var i = 1; i < arguments.length; i++) {
33587
- var source = null != arguments[i] ? arguments[i] : {};
33588
- i % 2 ? ownKeys(Object(source), true).forEach(function(key) {
33589
- _defineProperty(target, key, source[key]);
33590
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
33591
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
33592
- });
33593
- }
33594
- return target;
33595
- }
33596
- function _defineProperty(obj, key, value) {
33597
- key = _toPropertyKey(key);
33598
- if (key in obj) {
33599
- Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
33600
- } else {
33601
- obj[key] = value;
33602
- }
33603
- return obj;
33604
- }
33605
- function _toPropertyKey(arg) {
33606
- var key = _toPrimitive(arg, "string");
33607
- return typeof key === "symbol" ? key : String(key);
33608
- }
33609
- function _toPrimitive(input, hint) {
33610
- if (typeof input !== "object" || input === null) return input;
33611
- var prim = input[Symbol.toPrimitive];
33612
- if (prim !== void 0) {
33613
- var res = prim.call(input, hint || "default");
33614
- if (typeof res !== "object") return res;
33615
- throw new TypeError("@@toPrimitive must return a primitive value.");
33616
- }
33617
- return (hint === "string" ? String : Number)(input);
33618
- }
33619
- function createDedent(options) {
33620
- dedent2.withOptions = (newOptions) => createDedent(_objectSpread(_objectSpread({}, options), newOptions));
33621
- return dedent2;
33622
- function dedent2(strings, ...values) {
33623
- const raw = typeof strings === "string" ? [strings] : strings.raw;
33624
- const {
33625
- alignValues = false,
33626
- escapeSpecialCharacters = Array.isArray(strings),
33627
- trimWhitespace = true
33628
- } = options;
33629
- let result = "";
33630
- for (let i = 0; i < raw.length; i++) {
33631
- let next = raw[i];
33632
- if (escapeSpecialCharacters) {
33633
- next = next.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{");
33634
- }
33635
- result += next;
33636
- if (i < values.length) {
33637
- const value = alignValues ? alignValue(values[i], result) : values[i];
33638
- result += value;
33639
- }
33640
- }
33641
- const lines = result.split("\n");
33642
- let mindent = null;
33643
- for (const l of lines) {
33644
- const m = l.match(/^(\s+)\S+/);
33645
- if (m) {
33646
- const indent = m[1].length;
33647
- if (!mindent) {
33648
- mindent = indent;
33649
- } else {
33650
- mindent = Math.min(mindent, indent);
33651
- }
33652
- }
33653
- }
33654
- if (mindent !== null) {
33655
- const m = mindent;
33656
- result = lines.map((l) => l[0] === " " || l[0] === " " ? l.slice(m) : l).join("\n");
33657
- }
33658
- if (trimWhitespace) {
33659
- result = result.trim();
33660
- }
33661
- if (escapeSpecialCharacters) {
33662
- result = result.replace(/\\n/g, "\n");
33663
- }
33664
- if (typeof Bun !== "undefined") {
33665
- result = result.replace(
33666
- // Matches e.g. \\u{1f60a} or \\u5F1F
33667
- /\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,
33668
- (_2, braced, unbraced) => {
33669
- var _ref;
33670
- const hex = (_ref = braced !== null && braced !== void 0 ? braced : unbraced) !== null && _ref !== void 0 ? _ref : "";
33671
- return String.fromCodePoint(parseInt(hex, 16));
33672
- }
33673
- );
33674
- }
33675
- return result;
33676
- }
33677
- }
33678
- function alignValue(value, precedingText) {
33679
- if (typeof value !== "string" || !value.includes("\n")) {
33680
- return value;
33681
- }
33682
- const currentLine = precedingText.slice(precedingText.lastIndexOf("\n") + 1);
33683
- const indentMatch = currentLine.match(/^(\s+)/);
33684
- if (indentMatch) {
33685
- const indent = indentMatch[1];
33686
- return value.replace(/\n/g, `
33687
- ${indent}`);
33688
- }
33689
- return value;
33690
- }
33691
- var dedent;
33692
- var init_dedent = __esm({
33693
- "../../node_modules/dedent/dist/dedent.mjs"() {
33694
- init_define_BUILD();
33695
- init_define_PACKAGE_VERSIONS();
33696
- dedent = createDedent({});
33697
- }
33698
- });
33699
-
33700
- // src/utilities/events.ts
33701
- function isEvent(event) {
33702
- return event !== null && typeof event === "object" && "type" in event && "payload" in event && "id" in event;
33703
- }
33704
- function isEventMessage(event) {
33705
- const type = event?.type || null;
33706
- if (type === "message_created" && event.payload && typeof event.payload.message === "object") {
33707
- return true;
33708
- }
33709
- return false;
33710
- }
33711
- var init_events2 = __esm({
33712
- "src/utilities/events.ts"() {
33713
- "use strict";
33714
- init_define_BUILD();
33715
- init_define_PACKAGE_VERSIONS();
33716
- }
33717
- });
33718
-
33719
- // src/utilities/abort-signal.ts
33720
- function createJoinedAbortController(signals) {
33721
- const controller = new AbortController();
33722
- const validSignals = signals.filter((signal) => signal != null);
33723
- if (validSignals.length === 0) {
33724
- return controller;
33725
- }
33726
- for (const signal of validSignals) {
33727
- if (signal.aborted) {
33728
- controller.abort(signal.reason);
33729
- return controller;
33730
- }
33731
- }
33732
- const abortListeners = [];
33733
- for (const signal of validSignals) {
33734
- const listener = () => {
33735
- controller.abort(signal.reason);
33736
- cleanup();
33737
- };
33738
- signal.addEventListener("abort", listener);
33739
- abortListeners.push(() => signal.removeEventListener("abort", listener));
33740
- }
33741
- const cleanup = () => {
33742
- abortListeners.forEach((removeListener) => removeListener());
33743
- };
33744
- controller.signal.addEventListener("abort", cleanup, { once: true });
33745
- return controller;
33746
- }
33747
- function createJoinedAbortSignal(signals) {
33748
- return createJoinedAbortController(signals).signal;
33749
- }
33750
- var init_abort_signal = __esm({
33751
- "src/utilities/abort-signal.ts"() {
33752
- "use strict";
33753
- init_define_BUILD();
33754
- init_define_PACKAGE_VERSIONS();
33755
- }
33756
- });
33757
-
33758
- // src/constants.ts
33759
- var WellKnownTags, WellKnownMetadata;
33760
- var init_constants = __esm({
33761
- "src/constants.ts"() {
33762
- "use strict";
33763
- init_define_BUILD();
33764
- init_define_PACKAGE_VERSIONS();
33765
- WellKnownTags = {
33766
- knowledge: {
33767
- /**
33768
- * All knowledge base have this tag (with value "knowledge-base") to identify them as knowledge-related records.
33769
- * @example "source": "knowledge-base"
33770
- */
33771
- KNOWLEDGE: "source",
33772
- /**
33773
- * The ID of the knowledge base the record belongs to.
33774
- * This is the ID of the Knowledge Base primitive from Botpress.
33775
- * @example "kbId": "kb_01K6RT9T39KF7K0A7R7D71TDZ1"
33776
- */
33777
- KNOWLEDGE_BASE_ID: "kbId",
33778
- /**
33779
- * The name of the knowledge base as defined in the Knowledge Base primitive by the user.
33780
- * @example "kbName": "My Files"
33781
- */
33782
- KNOWLEDGE_BASE_NAME: "kbName",
33783
- /**
33784
- * The ID of the Data Source the record was ingested from.
33785
- * @example "dsId": "docs"
33786
- */
33787
- KNOWLEDGE_SOURCE_ID: "dsId",
33788
- /**
33789
- * The type of the Data Source the record was ingested from.
33790
- * Possible values are: "document", "rich-text", "web-page", etc.
33791
- * @example "dsType": "document"
33792
- */
33793
- KNOWLEDGE_SOURCE_TYPE: "dsType"
33794
- }
33795
- };
33796
- WellKnownMetadata = {
33797
- knowledge: {
33798
- /**
33799
- * The title of the document or page.
33800
- * @example "title": "Getting Started Guide"
33801
- */
33802
- TITLE: "title",
33803
- /**
33804
- * The URL of the document or page.
33805
- * @example "url": "https://example.com/docs/getting-started"
33806
- */
33807
- URL: "url",
33808
- /**
33809
- * The favicon URL of the website.
33810
- * @example "favicon": "https://example.com/favicon.ico"
33811
- */
33812
- FAVICON: "favicon",
33813
- /**
33814
- * A brief description of the document or page.
33815
- * @example "description": "Learn how to get started with our platform"
33816
- */
33817
- DESCRIPTION: "description"
33818
- }
33819
- };
33820
- }
33821
- });
33822
-
33823
- // src/runtime/autonomous.ts
33824
- import { getValue } from "llmz";
33825
- import {
33826
- Tool as LlmzTool,
33827
- ThinkSignal as _ThinkSignal,
33828
- SnapshotSignal as _SnapshotSignal,
33829
- CitationsManager as _CitationsManager,
33830
- ListenExit as _ListenExit,
33831
- ThinkExit as _ThinkExit,
33832
- DefaultExit as _DefaultExit,
33833
- Component as LlmzComponent
33834
- } from "llmz";
33835
- import { Exit as LlmzExit } from "llmz";
33836
- import { ObjectInstance as LlmzObject } from "llmz";
33837
- import { z as z5 } from "@botpress/sdk";
33838
- import { AsyncResource } from "node:async_hooks";
33839
- var import_lodash2, Autonomous;
33840
- var init_autonomous = __esm({
33841
- "src/runtime/autonomous.ts"() {
33842
- "use strict";
33843
- init_define_BUILD();
33844
- init_define_PACKAGE_VERSIONS();
33845
- init_esm();
33846
- init_abort_signal();
33847
- init_tracing();
33848
- init_context3();
33849
- init_constants();
33850
- import_lodash2 = __toESM(require_lodash(), 1);
33851
- init_span_helpers();
33852
- ((Autonomous2) => {
33853
- Autonomous2.Tool = LlmzTool;
33854
- Autonomous2.Component = LlmzComponent;
33855
- Autonomous2.Exit = LlmzExit;
33856
- Autonomous2.Object = LlmzObject;
33857
- Autonomous2.ThinkSignal = _ThinkSignal;
33858
- Autonomous2.SnapshotSignal = _SnapshotSignal;
33859
- Autonomous2.CitationsManager = _CitationsManager;
33860
- Autonomous2.ListenExit = _ListenExit;
33861
- Autonomous2.ThinkExit = _ThinkExit;
33862
- Autonomous2.DefaultExit = _DefaultExit;
33863
- function createKnowledgeSearchTool(knowledgeBases) {
33864
- const kbNames = knowledgeBases.map((kb) => kb.name);
33865
- const description = knowledgeBases.map((kb) => `- "${kb.name}": ${kb.description || "No description"}`).join("\n");
33866
- return new LlmzTool({
33867
- name: "search_knowledge",
33868
- description: `
33869
- Search the knowledge base for relevant information.
33870
- Here are the available knowledge bases and their descriptions:
33871
- ${description}
33105
+ init_context3();
33106
+ init_constants();
33107
+ import_lodash2 = __toESM(require_lodash(), 1);
33108
+ init_span_helpers();
33109
+ ((Autonomous2) => {
33110
+ Autonomous2.Tool = LlmzTool;
33111
+ Autonomous2.Component = LlmzComponent;
33112
+ Autonomous2.Exit = LlmzExit;
33113
+ Autonomous2.Object = LlmzObject;
33114
+ Autonomous2.ThinkSignal = _ThinkSignal;
33115
+ Autonomous2.SnapshotSignal = _SnapshotSignal;
33116
+ Autonomous2.CitationsManager = _CitationsManager;
33117
+ Autonomous2.ListenExit = _ListenExit;
33118
+ Autonomous2.ThinkExit = _ThinkExit;
33119
+ Autonomous2.DefaultExit = _DefaultExit;
33120
+ function createKnowledgeSearchTool(knowledgeBases) {
33121
+ const kbNames = knowledgeBases.map((kb) => kb.name);
33122
+ const description = knowledgeBases.map((kb) => `- "${kb.name}": ${kb.description || "No description"}`).join("\n");
33123
+ return new LlmzTool({
33124
+ name: "search_knowledge",
33125
+ description: `
33126
+ Search the knowledge base for relevant information.
33127
+ Here are the available knowledge bases and their descriptions:
33128
+ ${description}
33872
33129
 
33873
33130
  Use this tool to find specific information from the knowledge bases.
33874
33131
  Always prefer information from the knowledge bases over general knowledge when available.
33875
33132
  If the question is not related to the knowledge bases, do NOT use this tool.`.trim(),
33876
- input: z5.string().describe("The query to search for.").min(1).max(1024),
33877
- output: z5.string().describe("The search results."),
33133
+ input: z3.string().describe("The query to search for.").min(1).max(1024),
33134
+ output: z3.string().describe("The search results."),
33878
33135
  handler: async (query) => {
33879
33136
  const client2 = context2.get("client");
33880
33137
  const citations = context2.get("citations");
@@ -34250,10 +33507,15 @@ var init_actions = __esm({
34250
33507
  if (typeof propertyName !== "string") {
34251
33508
  return void 0;
34252
33509
  }
33510
+ let client2;
33511
+ client2 ??= context2.get("client", { optional: true });
34253
33512
  const botAction = adk.project.actions.find((a) => a.name === propertyName);
34254
33513
  if (botAction) {
34255
33514
  const handler = async (input) => {
34256
- return await botAction.handler(input);
33515
+ return await botAction.handler({
33516
+ input,
33517
+ client: client2
33518
+ });
34257
33519
  };
34258
33520
  handler.asTool = () => new Autonomous.Tool({
34259
33521
  name: botAction.name,
@@ -34265,9 +33527,7 @@ var init_actions = __esm({
34265
33527
  return handler;
34266
33528
  }
34267
33529
  let integrations;
34268
- let client2;
34269
33530
  integrations ??= context2.get("integrations", { optional: true });
34270
- client2 ??= context2.get("client", { optional: true });
34271
33531
  const integrationName = propertyName.replace("__", "/");
34272
33532
  return new Proxy(
34273
33533
  {},
@@ -34386,7 +33646,7 @@ var init_actions = __esm({
34386
33646
  });
34387
33647
 
34388
33648
  // src/errors.ts
34389
- import { z as z6 } from "@botpress/sdk";
33649
+ import { z as z4 } from "@botpress/sdk";
34390
33650
  var Errors;
34391
33651
  var init_errors = __esm({
34392
33652
  "src/errors.ts"() {
@@ -34470,7 +33730,7 @@ ${e.stack}` : "";
34470
33730
  if (zodError) {
34471
33731
  message += "\n" + formatZodError(zodError);
34472
33732
  }
34473
- } else if (messageOrError instanceof z6.ZodError) {
33733
+ } else if (messageOrError instanceof z4.ZodError) {
34474
33734
  message = formatZodError(messageOrError);
34475
33735
  } else {
34476
33736
  message = "";
@@ -34560,7 +33820,7 @@ ${issues.join("\n")}`;
34560
33820
  });
34561
33821
 
34562
33822
  // src/runtime/client.ts
34563
- import { Client as Client2 } from "@botpress/client";
33823
+ import { Client } from "@botpress/client";
34564
33824
  function getStandaloneClient() {
34565
33825
  return getSingleton("__ADK_GLOBAL_STANDALONE_CLIENT", () => {
34566
33826
  const token = process.env.BP_TOKEN || process.env.ADK_TOKEN;
@@ -34576,7 +33836,7 @@ function getStandaloneClient() {
34576
33836
  );
34577
33837
  }
34578
33838
  const apiUrl = process.env.ADK_API_URL || "https://api.botpress.cloud";
34579
- return new Client2({
33839
+ return new Client({
34580
33840
  token,
34581
33841
  apiUrl,
34582
33842
  botId
@@ -34743,7 +34003,7 @@ var init_state_reference_symbol = __esm({
34743
34003
  });
34744
34004
 
34745
34005
  // src/primitives/reference.ts
34746
- import { z as z7 } from "@botpress/sdk";
34006
+ import { z as z5 } from "@botpress/sdk";
34747
34007
  var Reference;
34748
34008
  var init_reference = __esm({
34749
34009
  "src/primitives/reference.ts"() {
@@ -34753,7 +34013,7 @@ var init_reference = __esm({
34753
34013
  init_state_reference_symbol();
34754
34014
  ((Reference2) => {
34755
34015
  function Workflow(name) {
34756
- const schema = z7.custom(
34016
+ const schema = z5.custom(
34757
34017
  (val) => {
34758
34018
  if (val && typeof val === "object") {
34759
34019
  if ("__ref__" in val && val.__ref__ === "workflow" && "id" in val) {
@@ -34779,7 +34039,7 @@ var init_reference = __esm({
34779
34039
  });
34780
34040
 
34781
34041
  // src/primitives/definition.ts
34782
- import { z as z8 } from "@botpress/sdk";
34042
+ import { z as z6 } from "@botpress/sdk";
34783
34043
  var Definitions;
34784
34044
  var init_definition = __esm({
34785
34045
  "src/primitives/definition.ts"() {
@@ -34787,42 +34047,42 @@ var init_definition = __esm({
34787
34047
  init_define_BUILD();
34788
34048
  init_define_PACKAGE_VERSIONS();
34789
34049
  ((Definitions2) => {
34790
- const conversationDefinitionSchema = z8.object({
34791
- type: z8.literal("conversation"),
34792
- channel: z8.union([
34793
- z8.string().min(1, "Channel must be a non-empty string").max(255, "Channel must be less than 255 characters").regex(/^(\*|[a-zA-Z0-9._-]+)$/, "Channel must be a valid identifier or glob '*'"),
34794
- z8.array(
34795
- z8.string().min(1, "Channel must be a non-empty string").max(255, "Channel must be less than 255 characters").regex(/^[a-zA-Z0-9._-]+$/, "Channel must be a valid identifier")
34050
+ const conversationDefinitionSchema = z6.object({
34051
+ type: z6.literal("conversation"),
34052
+ channel: z6.union([
34053
+ z6.string().min(1, "Channel must be a non-empty string").max(255, "Channel must be less than 255 characters").regex(/^(\*|[a-zA-Z0-9._-]+)$/, "Channel must be a valid identifier or glob '*'"),
34054
+ z6.array(
34055
+ z6.string().min(1, "Channel must be a non-empty string").max(255, "Channel must be less than 255 characters").regex(/^[a-zA-Z0-9._-]+$/, "Channel must be a valid identifier")
34796
34056
  )
34797
34057
  ])
34798
34058
  });
34799
- const workflowDefinitionSchema = z8.object({
34800
- type: z8.literal("workflow"),
34801
- name: z8.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34059
+ const workflowDefinitionSchema = z6.object({
34060
+ type: z6.literal("workflow"),
34061
+ name: z6.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34802
34062
  });
34803
- const knowledgeDefinitionSchema = z8.object({
34804
- type: z8.literal("knowledge"),
34805
- name: z8.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34063
+ const knowledgeDefinitionSchema = z6.object({
34064
+ type: z6.literal("knowledge"),
34065
+ name: z6.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34806
34066
  });
34807
- const triggerDefinitionSchema = z8.object({
34808
- type: z8.literal("trigger"),
34809
- name: z8.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34067
+ const triggerDefinitionSchema = z6.object({
34068
+ type: z6.literal("trigger"),
34069
+ name: z6.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34810
34070
  });
34811
- const actionDefinitionSchema = z8.object({
34812
- type: z8.literal("action"),
34813
- name: z8.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z][a-zA-Z0-9]*$/, "Name must be alphanumeric with no special characters"),
34814
- title: z8.string().optional(),
34815
- description: z8.string().optional(),
34816
- attributes: z8.record(z8.string()).optional(),
34817
- input: z8.any().optional(),
34071
+ const actionDefinitionSchema = z6.object({
34072
+ type: z6.literal("action"),
34073
+ name: z6.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z][a-zA-Z0-9]*$/, "Name must be alphanumeric with no special characters"),
34074
+ title: z6.string().optional(),
34075
+ description: z6.string().optional(),
34076
+ attributes: z6.record(z6.string()).optional(),
34077
+ input: z6.any().optional(),
34818
34078
  // JSONSchema7
34819
- output: z8.any().optional(),
34079
+ output: z6.any().optional(),
34820
34080
  // JSONSchema7
34821
- cached: z8.boolean().optional()
34081
+ cached: z6.boolean().optional()
34822
34082
  });
34823
- const tableDefinitionSchema = z8.object({
34824
- type: z8.literal("table"),
34825
- name: z8.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34083
+ const tableDefinitionSchema = z6.object({
34084
+ type: z6.literal("table"),
34085
+ name: z6.string().min(1, "Name must be a non-empty string").max(255, "Name must be less than 255 characters").regex(/^[a-zA-Z0-9_-]+$/, "Name must be a valid identifier")
34826
34086
  });
34827
34087
  function isConversationDefinition(value) {
34828
34088
  return conversationDefinitionSchema.safeParse(value).success;
@@ -34874,7 +34134,7 @@ var init_definition = __esm({
34874
34134
  });
34875
34135
 
34876
34136
  // src/primitives/data-sources/source-base.ts
34877
- import { z as z9 } from "@botpress/sdk";
34137
+ import { z as z7 } from "@botpress/sdk";
34878
34138
  var Item, SyncInput, SyncOutput, createSyncWorkflow, DataSource;
34879
34139
  var init_source_base = __esm({
34880
34140
  "src/primitives/data-sources/source-base.ts"() {
@@ -34883,24 +34143,24 @@ var init_source_base = __esm({
34883
34143
  init_define_PACKAGE_VERSIONS();
34884
34144
  init_workflow();
34885
34145
  init_library();
34886
- Item = z9.object({
34887
- file: z9.string(),
34888
- name: z9.string(),
34889
- hash: z9.string(),
34890
- size: z9.number()
34146
+ Item = z7.object({
34147
+ file: z7.string(),
34148
+ name: z7.string(),
34149
+ hash: z7.string(),
34150
+ size: z7.number()
34891
34151
  });
34892
- SyncInput = z9.object({
34893
- dsId: z9.string(),
34894
- kbName: z9.string(),
34895
- kbId: z9.string(),
34896
- force: z9.boolean().optional().describe("Force re-indexing even if files haven't changed").default(false)
34152
+ SyncInput = z7.object({
34153
+ dsId: z7.string(),
34154
+ kbName: z7.string(),
34155
+ kbId: z7.string(),
34156
+ force: z7.boolean().optional().describe("Force re-indexing even if files haven't changed").default(false)
34897
34157
  });
34898
- SyncOutput = z9.object({
34899
- processed: z9.number().default(0),
34900
- added: z9.array(Item).default([]),
34901
- updated: z9.array(Item).default([]),
34902
- deleted: z9.array(Item).default([]),
34903
- errors: z9.array(z9.string()).default([])
34158
+ SyncOutput = z7.object({
34159
+ processed: z7.number().default(0),
34160
+ added: z7.array(Item).default([]),
34161
+ updated: z7.array(Item).default([]),
34162
+ deleted: z7.array(Item).default([]),
34163
+ errors: z7.array(z7.string()).default([])
34904
34164
  });
34905
34165
  createSyncWorkflow = (props) => new BaseWorkflow({
34906
34166
  name: `data_source_sync_${props.type}`,
@@ -34934,7 +34194,7 @@ var init_source_base = __esm({
34934
34194
  });
34935
34195
 
34936
34196
  // src/primitives/data-sources/source-table.ts
34937
- import { z as z10 } from "@botpress/sdk";
34197
+ import { z as z8 } from "@botpress/sdk";
34938
34198
  var TableSource;
34939
34199
  var init_source_table = __esm({
34940
34200
  "src/primitives/data-sources/source-table.ts"() {
@@ -34962,7 +34222,7 @@ var init_source_table = __esm({
34962
34222
  get syncWorkflow() {
34963
34223
  return createSyncWorkflow({
34964
34224
  type: "table",
34965
- state: z10.object({ offset: z10.number().default(0) }),
34225
+ state: z8.object({ offset: z8.number().default(0) }),
34966
34226
  handler: async () => {
34967
34227
  throw new Error("TableSource synchronization not implemented");
34968
34228
  }
@@ -36619,7 +35879,7 @@ var init_html_fetch = __esm({
36619
35879
  });
36620
35880
 
36621
35881
  // src/primitives/data-sources/source-website.ts
36622
- import { z as z11 } from "@botpress/sdk";
35882
+ import { z as z9 } from "@botpress/sdk";
36623
35883
  var State, WebsiteSource;
36624
35884
  var init_source_website = __esm({
36625
35885
  "src/primitives/data-sources/source-website.ts"() {
@@ -36632,16 +35892,16 @@ var init_source_website = __esm({
36632
35892
  init_library();
36633
35893
  init_context3();
36634
35894
  init_html_fetch();
36635
- State = z11.object({
36636
- urls: z11.array(
36637
- z11.object({
36638
- loc: z11.string(),
36639
- lastmod: z11.string().optional(),
36640
- changefreq: z11.string().optional(),
36641
- priority: z11.string().optional()
35895
+ State = z9.object({
35896
+ urls: z9.array(
35897
+ z9.object({
35898
+ loc: z9.string(),
35899
+ lastmod: z9.string().optional(),
35900
+ changefreq: z9.string().optional(),
35901
+ priority: z9.string().optional()
36642
35902
  })
36643
35903
  ).default([]),
36644
- queue: z11.array(z11.object({ url: z11.string(), depth: z11.number() })).default([])
35904
+ queue: z9.array(z9.object({ url: z9.string(), depth: z9.number() })).default([])
36645
35905
  });
36646
35906
  WebsiteSource = class _WebsiteSource extends DataSource {
36647
35907
  mode;
@@ -37033,7 +36293,7 @@ var init_source_website = __esm({
37033
36293
  type: "website",
37034
36294
  state: State,
37035
36295
  async handler({ input, step: step2, state, client: client2 }) {
37036
- const crypto2 = await import("crypto");
36296
+ const crypto3 = await import("crypto");
37037
36297
  console.log(
37038
36298
  `Starting sync for WebsiteSource [${this.id}] in mode [${this.mode}, maxPages=${this.maxPages}, maxDepth=${this.maxDepth}, baseUrl=${this.baseUrl}, sitemapUrl=${this.sitemapUrl}]`
37039
36299
  );
@@ -37116,7 +36376,7 @@ var init_source_website = __esm({
37116
36376
  content,
37117
36377
  metadata: fetchMetadata
37118
36378
  } = await this.fetchUrl(sitemapUrl.loc);
37119
- const hash = crypto2.createHash("sha256").update(content).digest("hex");
36379
+ const hash = crypto3.createHash("sha256").update(content).digest("hex");
37120
36380
  let contentType = fetchedContentType;
37121
36381
  if (!contentType) {
37122
36382
  contentType = content.includes("<html") ? "text/html" : "text/markdown";
@@ -44063,7 +43323,7 @@ var init_esm9 = __esm({
44063
43323
  });
44064
43324
 
44065
43325
  // src/primitives/data-sources/source-directory.ts
44066
- import { z as z12 } from "@botpress/sdk";
43326
+ import { z as z10 } from "@botpress/sdk";
44067
43327
  var DirectorySource;
44068
43328
  var init_source_directory = __esm({
44069
43329
  "src/primitives/data-sources/source-directory.ts"() {
@@ -44101,7 +43361,7 @@ var init_source_directory = __esm({
44101
43361
  get syncWorkflow() {
44102
43362
  return createSyncWorkflow({
44103
43363
  type: "directory",
44104
- state: z12.object({}),
43364
+ state: z10.object({}),
44105
43365
  handler: async ({ input, step: step2, client: client2 }) => {
44106
43366
  if (!adk.environment.isDevelopment()) {
44107
43367
  console.log("Directory ingestion is only supported in development environment");
@@ -44119,7 +43379,7 @@ var init_source_directory = __esm({
44119
43379
  const glob2 = await Promise.resolve().then(() => (init_esm9(), esm_exports3));
44120
43380
  const path4 = await import("path");
44121
43381
  const fs3 = await import("fs/promises");
44122
- const crypto2 = await import("crypto");
43382
+ const crypto3 = await import("crypto");
44123
43383
  const directory = path4.resolve(adk.environment.agent.directory, this.directoryPath);
44124
43384
  const tags = {
44125
43385
  [WellKnownTags.knowledge.KNOWLEDGE]: "knowledge-base",
@@ -44181,7 +43441,7 @@ var init_source_directory = __esm({
44181
43441
  const upsertFile = async (local) => {
44182
43442
  const key = `data_source://${this.type}/${this.id}/${local.rel}`;
44183
43443
  const content = await fs3.readFile(local.abs);
44184
- const hash = crypto2.createHash("sha256").update(content).digest("hex");
43444
+ const hash = crypto3.createHash("sha256").update(content).digest("hex");
44185
43445
  const { file } = await client2.getFile({ id: key }).catch(() => ({ file: null }));
44186
43446
  const isFailed = file?.status === "indexing_failed" || file?.status === "upload_failed" || file?.status === "upload_pending";
44187
43447
  if (!input.force && !isFailed && file?.metadata?.hash === hash) {
@@ -44271,8 +43531,27 @@ var init_data_sources = __esm({
44271
43531
  }
44272
43532
  });
44273
43533
 
43534
+ // src/utilities/events.ts
43535
+ function isEvent(event) {
43536
+ return event !== null && typeof event === "object" && "type" in event && "payload" in event && "id" in event;
43537
+ }
43538
+ function isEventMessage(event) {
43539
+ const type = event?.type || null;
43540
+ if (type === "message_created" && event.payload && typeof event.payload.message === "object") {
43541
+ return true;
43542
+ }
43543
+ return false;
43544
+ }
43545
+ var init_events = __esm({
43546
+ "src/utilities/events.ts"() {
43547
+ "use strict";
43548
+ init_define_BUILD();
43549
+ init_define_PACKAGE_VERSIONS();
43550
+ }
43551
+ });
43552
+
44274
43553
  // src/primitives/conversation.ts
44275
- import { z as z13 } from "@botpress/sdk";
43554
+ import { z as z11 } from "@botpress/sdk";
44276
43555
  import { setTimeout as setTimeout2 } from "node:timers/promises";
44277
43556
  var ConversationHandler, Typings2, BaseConversation;
44278
43557
  var init_conversation = __esm({
@@ -44284,7 +43563,7 @@ var init_conversation = __esm({
44284
43563
  init_autonomous();
44285
43564
  init_context3();
44286
43565
  init_tracing();
44287
- init_events2();
43566
+ init_events();
44288
43567
  init_conversation_instance();
44289
43568
  init_workflow_instance();
44290
43569
  ConversationHandler = Symbol.for("conversation.handler");
@@ -44305,7 +43584,7 @@ var init_conversation = __esm({
44305
43584
  constructor(props) {
44306
43585
  this.channel = props.channel;
44307
43586
  this.events = props.events ?? [];
44308
- this.schema = props.state ?? z13.object({}).passthrough();
43587
+ this.schema = props.state ?? z11.object({}).passthrough();
44309
43588
  this.#handler = props.handler;
44310
43589
  }
44311
43590
  /** @internal */
@@ -44426,9 +43705,13 @@ var init_conversation = __esm({
44426
43705
  }
44427
43706
  const stateProxy = new Proxy(conversationInstance.TrackedState.value, {
44428
43707
  set(target, prop, value) {
44429
- const result = Reflect.set(target, prop, value);
44430
- conversationInstance.TrackedState.markDirty();
44431
- return result;
43708
+ const oldValue = target[prop];
43709
+ if (oldValue !== value) {
43710
+ const result = Reflect.set(target, prop, value);
43711
+ conversationInstance.TrackedState.markDirty();
43712
+ return result;
43713
+ }
43714
+ return true;
44432
43715
  }
44433
43716
  });
44434
43717
  await this.#handler({
@@ -44668,7 +43951,7 @@ var init_validate_event_name = __esm({
44668
43951
  });
44669
43952
 
44670
43953
  // src/define-config.ts
44671
- import { z as z14 } from "@botpress/sdk";
43954
+ import { z as z12 } from "@botpress/sdk";
44672
43955
  var zuiSchema, modelSchema, tagDefinitionSchema, eventDefinitionSchema, configSchema, AGENT_CONFIG_BRAND;
44673
43956
  var init_define_config = __esm({
44674
43957
  "src/define-config.ts"() {
@@ -44677,7 +43960,7 @@ var init_define_config = __esm({
44677
43960
  init_define_PACKAGE_VERSIONS();
44678
43961
  init_validate_tag_name();
44679
43962
  init_validate_event_name();
44680
- zuiSchema = z14.custom(
43963
+ zuiSchema = z12.custom(
44681
43964
  (val) => {
44682
43965
  if (typeof val === "object" && val !== null && "parse" in val) {
44683
43966
  return true;
@@ -44688,48 +43971,48 @@ var init_define_config = __esm({
44688
43971
  message: "Invalid ZUI Schema, must be an instance of z.object()"
44689
43972
  }
44690
43973
  );
44691
- modelSchema = z14.custom(
43974
+ modelSchema = z12.custom(
44692
43975
  (val) => typeof val === "string" && val.length > 0 || Array.isArray(val) && val.every((m) => typeof m === "string" && m.length > 0),
44693
43976
  {
44694
43977
  message: "Model must be a non-empty string, or an array of non-empty strings"
44695
43978
  }
44696
43979
  );
44697
- tagDefinitionSchema = z14.record(
44698
- z14.string(),
44699
- z14.object({
44700
- title: z14.string(),
44701
- description: z14.string().optional()
43980
+ tagDefinitionSchema = z12.record(
43981
+ z12.string(),
43982
+ z12.object({
43983
+ title: z12.string(),
43984
+ description: z12.string().optional()
44702
43985
  })
44703
43986
  );
44704
- eventDefinitionSchema = z14.record(
44705
- z14.string(),
44706
- z14.object({
43987
+ eventDefinitionSchema = z12.record(
43988
+ z12.string(),
43989
+ z12.object({
44707
43990
  schema: zuiSchema.optional(),
44708
- description: z14.string().optional()
43991
+ description: z12.string().optional()
44709
43992
  })
44710
43993
  );
44711
- configSchema = z14.object({
44712
- name: z14.string().optional(),
44713
- description: z14.string().optional(),
44714
- user: z14.object({
43994
+ configSchema = z12.object({
43995
+ name: z12.string().optional(),
43996
+ description: z12.string().optional(),
43997
+ user: z12.object({
44715
43998
  state: zuiSchema.optional(),
44716
43999
  tags: tagDefinitionSchema.optional()
44717
44000
  }).optional(),
44718
- bot: z14.object({
44001
+ bot: z12.object({
44719
44002
  state: zuiSchema.optional(),
44720
44003
  tags: tagDefinitionSchema.optional()
44721
44004
  }).optional(),
44722
- conversation: z14.object({
44005
+ conversation: z12.object({
44723
44006
  tags: tagDefinitionSchema.optional()
44724
44007
  }).optional(),
44725
- message: z14.object({
44008
+ message: z12.object({
44726
44009
  tags: tagDefinitionSchema.optional()
44727
44010
  }).optional(),
44728
- workflow: z14.object({
44011
+ workflow: z12.object({
44729
44012
  tags: tagDefinitionSchema.optional()
44730
44013
  }).optional(),
44731
- configuration: z14.object({
44732
- schema: z14.custom(
44014
+ configuration: z12.object({
44015
+ schema: z12.custom(
44733
44016
  (val) => {
44734
44017
  if (typeof val === "object" && val !== null && "parse" in val && "_def" in val) {
44735
44018
  return val._def?.typeName === "ZodObject";
@@ -44741,14 +44024,14 @@ var init_define_config = __esm({
44741
44024
  }
44742
44025
  )
44743
44026
  }).optional(),
44744
- defaultModels: z14.object({
44027
+ defaultModels: z12.object({
44745
44028
  zai: modelSchema,
44746
44029
  autonomous: modelSchema
44747
44030
  }).optional().transform((val) => ({
44748
44031
  zai: val?.zai ?? "openai:gpt-4.1-2025-04-14",
44749
44032
  autonomous: val?.autonomous ?? "openai:gpt-4.1-mini-2025-04-14"
44750
44033
  })),
44751
- dependencies: z14.custom(),
44034
+ dependencies: z12.custom(),
44752
44035
  events: eventDefinitionSchema.optional()
44753
44036
  });
44754
44037
  AGENT_CONFIG_BRAND = Symbol.for("@botpress/runtime/AgentConfig");
@@ -44756,7 +44039,7 @@ var init_define_config = __esm({
44756
44039
  });
44757
44040
 
44758
44041
  // src/runtime.ts
44759
- import { z as z15 } from "@botpress/sdk";
44042
+ import { z as z13 } from "@botpress/sdk";
44760
44043
  var init_runtime = __esm({
44761
44044
  "src/runtime.ts"() {
44762
44045
  "use strict";
@@ -44872,7 +44155,7 @@ var init_action = __esm({
44872
44155
  });
44873
44156
 
44874
44157
  // src/primitives/table.ts
44875
- import { transforms as transforms2, z as z17 } from "@bpinternal/zui";
44158
+ import { transforms as transforms2, z as z15 } from "@bpinternal/zui";
44876
44159
  var Typings5;
44877
44160
  var init_table = __esm({
44878
44161
  "src/primitives/table.ts"() {
@@ -44888,7 +44171,7 @@ var init_table = __esm({
44888
44171
  });
44889
44172
 
44890
44173
  // src/primitives/trigger.ts
44891
- import { z as z18 } from "@botpress/sdk";
44174
+ import { z as z16 } from "@botpress/sdk";
44892
44175
  var Typings6, TriggerSchema;
44893
44176
  var init_trigger = __esm({
44894
44177
  "src/primitives/trigger.ts"() {
@@ -44899,11 +44182,11 @@ var init_trigger = __esm({
44899
44182
  ((Typings8) => {
44900
44183
  Typings8.Primitive = "trigger";
44901
44184
  })(Typings6 || (Typings6 = {}));
44902
- TriggerSchema = z18.object({
44903
- name: z18.string().min(3, "Trigger name must be at least 3 characters").max(255, "Trigger name must be less than 255 characters").regex(/^[a-zA-Z0-9_]+$/, "Trigger name must contain only alphanumeric characters and underscores"),
44904
- description: z18.string().max(1024, "Description must be less than 1024 characters").optional(),
44905
- events: z18.array(z18.string()),
44906
- handler: z18.function().describe("Handler function for the trigger")
44185
+ TriggerSchema = z16.object({
44186
+ name: z16.string().min(3, "Trigger name must be at least 3 characters").max(255, "Trigger name must be less than 255 characters").regex(/^[a-zA-Z0-9_]+$/, "Trigger name must contain only alphanumeric characters and underscores"),
44187
+ description: z16.string().max(1024, "Description must be less than 1024 characters").optional(),
44188
+ events: z16.array(z16.string()),
44189
+ handler: z16.function().describe("Handler function for the trigger")
44907
44190
  });
44908
44191
  }
44909
44192
  });
@@ -44962,7 +44245,7 @@ var init_workflow_utils = __esm({
44962
44245
  init_define_PACKAGE_VERSIONS();
44963
44246
  init_library();
44964
44247
  init_runtime();
44965
- init_events2();
44248
+ init_events();
44966
44249
  updateWorkflow = async (props) => {
44967
44250
  const client2 = context2.get("client");
44968
44251
  const workflowId = props.id;
@@ -44993,7 +44276,7 @@ var init_workflow_utils = __esm({
44993
44276
  });
44994
44277
 
44995
44278
  // src/library.ts
44996
- import { z as z20 } from "@botpress/sdk";
44279
+ import { z as z18 } from "@botpress/sdk";
44997
44280
  import { Cognitive as Cognitive2 } from "@botpress/cognitive";
44998
44281
  import { Zai } from "@botpress/zai";
44999
44282
  var init_library = __esm({
@@ -45005,7 +44288,7 @@ var init_library = __esm({
45005
44288
  init_client();
45006
44289
  init_primitives();
45007
44290
  init_workflow_utils();
45008
- init_events2();
44291
+ init_events();
45009
44292
  init_autonomous();
45010
44293
  init_types2();
45011
44294
  init_errors();
@@ -45018,7 +44301,7 @@ var init_library = __esm({
45018
44301
  });
45019
44302
 
45020
44303
  // src/primitives/workflow-step.ts
45021
- import { ulid as ulid2 } from "ulid";
44304
+ import { ulid } from "ulid";
45022
44305
  import assert from "assert";
45023
44306
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
45024
44307
  import { transforms as transforms3 } from "@botpress/sdk";
@@ -45310,7 +44593,7 @@ var init_workflow_step = __esm({
45310
44593
  step.executeWorkflow = async (name, workflow, input) => _step(
45311
44594
  name,
45312
44595
  async () => {
45313
- const key = await _step(`${name}-key`, () => ulid2());
44596
+ const key = await _step(`${name}-key`, () => ulid());
45314
44597
  const wfId = await _step(
45315
44598
  `${name}-start`,
45316
44599
  async () => (await workflow.getOrCreate({
@@ -45450,1036 +44733,1801 @@ function startWorkflowCancellationMonitor(props) {
45450
44733
  }
45451
44734
  clearInterval(interval);
45452
44735
  }
45453
- } catch (error) {
45454
- console.warn(`Failed to check workflow status for ${workflowId}:`, error);
45455
- }
45456
- }, pollIntervalMs);
45457
- return () => {
45458
- clearInterval(interval);
45459
- };
45460
- }
45461
- var init_workflow_cancellation_monitor = __esm({
45462
- "src/primitives/workflow-cancellation-monitor.ts"() {
45463
- "use strict";
45464
- init_define_BUILD();
45465
- init_define_PACKAGE_VERSIONS();
44736
+ } catch (error) {
44737
+ console.warn(`Failed to check workflow status for ${workflowId}:`, error);
44738
+ }
44739
+ }, pollIntervalMs);
44740
+ return () => {
44741
+ clearInterval(interval);
44742
+ };
44743
+ }
44744
+ var init_workflow_cancellation_monitor = __esm({
44745
+ "src/primitives/workflow-cancellation-monitor.ts"() {
44746
+ "use strict";
44747
+ init_define_BUILD();
44748
+ init_define_PACKAGE_VERSIONS();
44749
+ }
44750
+ });
44751
+
44752
+ // src/primitives/workflow-instance.ts
44753
+ var workflow_instance_exports = {};
44754
+ __export(workflow_instance_exports, {
44755
+ BaseWorkflowInstance: () => BaseWorkflowInstance,
44756
+ createStepSignal: () => createStepSignal,
44757
+ createWorkflowExecutionState: () => createWorkflowExecutionState,
44758
+ isStepSignal: () => isStepSignal
44759
+ });
44760
+ import { z as z20 } from "@botpress/sdk";
44761
+ import assert2 from "assert";
44762
+ function isStepSignal(e) {
44763
+ return typeof e === "object" && e !== null && StepSymbol in e;
44764
+ }
44765
+ function createStepSignal() {
44766
+ return {
44767
+ [StepSymbol]: true
44768
+ };
44769
+ }
44770
+ function createWorkflowExecutionState(client2, workflowId) {
44771
+ return TrackedState2.create({
44772
+ type: "workflow",
44773
+ client: client2,
44774
+ id: workflowId,
44775
+ schema: workflowExecutionContextSchema,
44776
+ name: BUILT_IN_STATES.workflowSteps
44777
+ });
44778
+ }
44779
+ var import_ms, workflowStepContextSchema, workflowExecutionContextSchema, StepSymbol, BaseWorkflowInstance;
44780
+ var init_workflow_instance = __esm({
44781
+ "src/primitives/workflow-instance.ts"() {
44782
+ "use strict";
44783
+ init_define_BUILD();
44784
+ init_define_PACKAGE_VERSIONS();
44785
+ import_ms = __toESM(require_ms(), 1);
44786
+ init_errors();
44787
+ init_library();
44788
+ init_autonomous();
44789
+ init_runtime2();
44790
+ init_state_reference_symbol();
44791
+ init_workflow_step();
44792
+ init_workflow_utils();
44793
+ init_workflow_cancellation_monitor();
44794
+ workflowStepContextSchema = z20.lazy(
44795
+ () => z20.object({
44796
+ output: z20.unknown().optional(),
44797
+ attempts: z20.number(),
44798
+ i: z20.number().optional(),
44799
+ startedAt: z20.string(),
44800
+ finishedAt: z20.string().optional(),
44801
+ steps: z20.record(z20.string(), workflowStepContextSchema).optional(),
44802
+ error: z20.object({
44803
+ message: z20.string(),
44804
+ failedAt: z20.string(),
44805
+ maxAttemptsReached: z20.boolean()
44806
+ }).optional()
44807
+ })
44808
+ );
44809
+ workflowExecutionContextSchema = z20.object({
44810
+ executionCount: z20.number().default(0),
44811
+ revision: z20.number().default(0),
44812
+ steps: z20.record(z20.string(), workflowStepContextSchema)
44813
+ }).default({
44814
+ executionCount: 0,
44815
+ steps: {}
44816
+ });
44817
+ StepSymbol = Symbol.for("StepSignal");
44818
+ BaseWorkflowInstance = class _BaseWorkflowInstance {
44819
+ id;
44820
+ name;
44821
+ key;
44822
+ input;
44823
+ createdAt;
44824
+ updatedAt;
44825
+ client;
44826
+ // Can be Client or BotClient
44827
+ workflow;
44828
+ // @internal
44829
+ TrackedState;
44830
+ // @internal
44831
+ TrackedTags;
44832
+ constructor(workflow, client2) {
44833
+ const definition = adk.project.workflows.find((w) => w.name === workflow.name);
44834
+ this.TrackedState = TrackedState2.create({
44835
+ type: "workflow",
44836
+ client: client2._inner,
44837
+ id: workflow.id,
44838
+ schema: definition?.stateSchema,
44839
+ name: BUILT_IN_STATES.workflowState
44840
+ });
44841
+ this.TrackedTags = TrackedTags.create({
44842
+ type: "workflow",
44843
+ client: client2._inner,
44844
+ id: workflow.id,
44845
+ initialTags: workflow.tags
44846
+ });
44847
+ this.id = workflow.id;
44848
+ this.name = workflow.name;
44849
+ this.key = workflow.tags.key;
44850
+ this.input = workflow.input;
44851
+ this.createdAt = new Date(workflow.createdAt);
44852
+ this.updatedAt = new Date(workflow.updatedAt);
44853
+ this.client = client2;
44854
+ this.workflow = workflow;
44855
+ }
44856
+ get tags() {
44857
+ return this.TrackedTags.tags;
44858
+ }
44859
+ set tags(value) {
44860
+ this.TrackedTags.tags = value;
44861
+ }
44862
+ /**
44863
+ * Symbol method for automatic serialization to reference in state
44864
+ * @internal
44865
+ */
44866
+ [StateReference]() {
44867
+ return {
44868
+ __ref__: "workflow",
44869
+ id: this.id
44870
+ };
44871
+ }
44872
+ static Primitive = "workflow_instance";
44873
+ static async load(props) {
44874
+ const client2 = context2.get("client");
44875
+ const workflow = props.workflow ? props.workflow : await client2.getWorkflow({ id: props.id }).then((x) => x.workflow);
44876
+ if (!adk.project.workflows.find((w) => w.name === workflow.name)) {
44877
+ throw new Error(`No ADK Workflow definition found for "${workflow.name}"`);
44878
+ }
44879
+ TrackedTags.create({
44880
+ type: "workflow",
44881
+ client: client2._inner,
44882
+ id: workflow.id,
44883
+ initialTags: workflow.tags
44884
+ });
44885
+ await TrackedTags.loadAll();
44886
+ return new _BaseWorkflowInstance(workflow, client2);
44887
+ }
44888
+ /**
44889
+ * Executes the workflow with the provided autonomous engine configuration.
44890
+ * Workflows always run in "worker" mode (no chat capabilities).
44891
+ */
44892
+ async execute(props) {
44893
+ const executeFunc = Autonomous.createExecute({
44894
+ mode: "worker",
44895
+ defaultModel: adk.project.config.defaultModels.autonomous
44896
+ });
44897
+ return executeFunc(props);
44898
+ }
44899
+ /**
44900
+ * Cancel the workflow execution.
44901
+ * Note: This should be called from within a proper bot handler context.
44902
+ * If calling from a conversation handler, ensure TrackedTags.loadAll() has been called.
44903
+ */
44904
+ async cancel() {
44905
+ await TrackedTags.loadAll();
44906
+ const { workflow } = await updateWorkflow({
44907
+ id: this.id,
44908
+ status: "cancelled"
44909
+ });
44910
+ Object.assign(this.workflow, workflow);
44911
+ }
44912
+ /**
44913
+ * Extend the workflow timeout by setting a new timeout.
44914
+ * This is useful for long-running workflows that need more time to complete.
44915
+ *
44916
+ * @param options - Either `{ in: string }` for relative duration or `{ at: string }` for absolute ISO timestamp
44917
+ * @returns A promise that resolves when the timeout is updated (can be awaited or not)
44918
+ * @example
44919
+ * // Relative timeout (duration from now):
44920
+ * workflow.setTimeout({ in: '30m' }) // Timeout in 30 minutes
44921
+ * workflow.setTimeout({ in: '6 hours' }) // Timeout in 6 hours
44922
+ *
44923
+ * // Absolute timeout (ISO timestamp):
44924
+ * workflow.setTimeout({ at: '2024-12-25T00:00:00Z' })
44925
+ *
44926
+ * // Optionally await if you need to ensure the update completes:
44927
+ * await workflow.setTimeout({ in: '1h' })
44928
+ */
44929
+ setTimeout(options) {
44930
+ let newTimeoutAt;
44931
+ if ("in" in options) {
44932
+ const durationMs = (0, import_ms.default)(options.in);
44933
+ if (!durationMs) {
44934
+ throw new Error(`Invalid duration format: "${options.in}". Use formats like "30m", "1h", "6 hours".`);
44935
+ }
44936
+ newTimeoutAt = new Date(Date.now() + durationMs).toISOString();
44937
+ } else {
44938
+ const date = new Date(options.at);
44939
+ if (isNaN(date.getTime())) {
44940
+ throw new Error(`Invalid ISO date format: "${options.at}".`);
44941
+ }
44942
+ newTimeoutAt = date.toISOString();
44943
+ }
44944
+ return updateWorkflow({
44945
+ id: this.id,
44946
+ timeoutAt: newTimeoutAt
44947
+ }).then(({ workflow }) => {
44948
+ Object.assign(this.workflow, workflow);
44949
+ });
44950
+ }
44951
+ /**
44952
+ * Fail the workflow with an error reason.
44953
+ * This immediately interrupts the workflow handler and marks the workflow as failed.
44954
+ * Can only be called from within a workflow handler.
44955
+ *
44956
+ * @param reason - The error reason for the failure
44957
+ * @throws Never returns - always throws to interrupt the handler
44958
+ * @example
44959
+ * workflow.fail('Invalid input data')
44960
+ */
44961
+ fail(reason) {
44962
+ const controlContext = context2.get("workflowControlContext", { optional: true });
44963
+ if (!controlContext || controlContext.workflow.id !== this.id) {
44964
+ throw new Error("workflow.fail() can only be called from within the workflow handler");
44965
+ }
44966
+ controlContext.fail(reason);
44967
+ throw createStepSignal();
44968
+ }
44969
+ /**
44970
+ * Complete the workflow early with the given output.
44971
+ * This immediately interrupts the workflow handler and marks the workflow as completed.
44972
+ * Can only be called from within a workflow handler.
44973
+ *
44974
+ * @param output - The workflow output (typed according to workflow definition)
44975
+ * @throws Never returns - always throws to interrupt the handler
44976
+ * @example
44977
+ * workflow.complete({ result: 'success', data: processedData })
44978
+ */
44979
+ complete(output2) {
44980
+ const controlContext = context2.get("workflowControlContext", { optional: true });
44981
+ if (!controlContext || controlContext.workflow.id !== this.id) {
44982
+ throw new Error("workflow.complete() can only be called from within the workflow handler");
44983
+ }
44984
+ controlContext.complete(output2);
44985
+ throw createStepSignal();
44986
+ }
44987
+ /**
44988
+ * Provide data in response to a workflow data request (instance method).
44989
+ * Call this method from a conversation handler when you receive a WorkflowDataRequestEvent.
44990
+ * @param request - The name of the request being responded to
44991
+ * @param data - The data to provide to the workflow
44992
+ * @example
44993
+ * if (type === 'workflow_request') {
44994
+ * await workflow.provide('topic', { topic: "Hello" });
44995
+ * }
44996
+ */
44997
+ async provide(request, data) {
44998
+ const client2 = context2.get("client");
44999
+ const state = createWorkflowExecutionState(client2._inner, this.id);
45000
+ await state.load();
45001
+ if (!state.value) {
45002
+ throw new Error(`Workflow execution state not found for workflow ${this.id}`);
45003
+ }
45004
+ const stepName = request;
45005
+ if (!state.value.steps[stepName]) {
45006
+ state.value.steps[stepName] = {
45007
+ output: data,
45008
+ attempts: 0,
45009
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45010
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString()
45011
+ };
45012
+ } else {
45013
+ state.value.steps[stepName].output = data;
45014
+ state.value.steps[stepName].finishedAt = (/* @__PURE__ */ new Date()).toISOString();
45015
+ }
45016
+ state.value.revision++;
45017
+ await state.save();
45018
+ await client2.createEvent({
45019
+ type: WorkflowContinueEvent.name,
45020
+ workflowId: this.id,
45021
+ payload: {}
45022
+ });
45023
+ }
45024
+ // @internal
45025
+ async handle(abortSignal) {
45026
+ abortSignal.throwIfAborted();
45027
+ const handler = adk.project.workflows.find((w) => w.name === this.name)._handler;
45028
+ if (!handler) {
45029
+ throw new Error(`No ADK Workflow handler found for "${this.name}"`);
45030
+ }
45031
+ await TrackedState2.loadAll();
45032
+ abortSignal.throwIfAborted();
45033
+ const workflowControlContext = {
45034
+ workflow: this.workflow,
45035
+ aborted: false,
45036
+ failed: false,
45037
+ completed: false,
45038
+ acked: false,
45039
+ restarted: false,
45040
+ signal: abortSignal,
45041
+ restart: () => {
45042
+ workflowControlContext.restarted = true;
45043
+ },
45044
+ abort: () => {
45045
+ workflowControlContext.aborted = true;
45046
+ workflowControlContext.acked = true;
45047
+ },
45048
+ fail: (reason) => {
45049
+ workflowControlContext.failed = true;
45050
+ workflowControlContext.failedReason = reason;
45051
+ },
45052
+ complete: (result) => {
45053
+ workflowControlContext.completed = true;
45054
+ workflowControlContext.completedResult = result;
45055
+ },
45056
+ ack: async () => {
45057
+ if (workflowControlContext.acked) {
45058
+ return;
45059
+ }
45060
+ const eventId = context2.get("event")?.id;
45061
+ if (!eventId) {
45062
+ throw new Error(`Event ID not found in context. Cannot ack workflow ${this.id}`);
45063
+ }
45064
+ workflowControlContext.acked = true;
45065
+ await updateWorkflow({
45066
+ id: this.id,
45067
+ status: "in_progress",
45068
+ eventId
45069
+ });
45070
+ this.workflow.status = "in_progress";
45071
+ }
45072
+ };
45073
+ try {
45074
+ const client2 = context2.get("client");
45075
+ const workflowExecutionState = createWorkflowExecutionState(client2._inner, this.id);
45076
+ await workflowExecutionState.load();
45077
+ await this.TrackedState.load();
45078
+ abortSignal.throwIfAborted();
45079
+ assert2(workflowExecutionState.value, "Workflow execution state is not loaded");
45080
+ workflowExecutionState.value.executionCount++;
45081
+ if (!this.TrackedState.value) {
45082
+ this.TrackedState.value = {};
45083
+ }
45084
+ const trackedState = this.TrackedState;
45085
+ const stateProxy = new Proxy(this.TrackedState.value, {
45086
+ set(target, prop, value) {
45087
+ const oldValue = target[prop];
45088
+ if (oldValue !== value) {
45089
+ const result = Reflect.set(target, prop, value);
45090
+ trackedState.markDirty();
45091
+ return result;
45092
+ }
45093
+ return true;
45094
+ }
45095
+ });
45096
+ if (this.workflow.status === "pending") {
45097
+ await workflowControlContext.ack();
45098
+ }
45099
+ context2.set("workflowControlContext", workflowControlContext);
45100
+ const stopCancellationMonitor = startWorkflowCancellationMonitor({
45101
+ client: client2._inner,
45102
+ workflowId: this.id,
45103
+ workflowControlContext,
45104
+ abortSignal
45105
+ });
45106
+ try {
45107
+ const result = await handler({
45108
+ input: this.input,
45109
+ state: stateProxy,
45110
+ step,
45111
+ client: this.client,
45112
+ execute: this.execute.bind(this),
45113
+ signal: abortSignal,
45114
+ workflow: this
45115
+ });
45116
+ return {
45117
+ status: "done",
45118
+ result
45119
+ };
45120
+ } finally {
45121
+ stopCancellationMonitor();
45122
+ }
45123
+ } catch (err) {
45124
+ if (isStepSignal(err)) {
45125
+ if (workflowControlContext.completed) {
45126
+ return {
45127
+ status: "done",
45128
+ result: workflowControlContext.completedResult
45129
+ };
45130
+ }
45131
+ if (workflowControlContext.failed) {
45132
+ return {
45133
+ status: "error",
45134
+ error: workflowControlContext.failedReason || Errors.toErrorString(err)
45135
+ };
45136
+ }
45137
+ return {
45138
+ status: "continue"
45139
+ };
45140
+ } else {
45141
+ const str = Errors.toErrorString(err);
45142
+ return {
45143
+ status: "error",
45144
+ error: str
45145
+ };
45146
+ }
45147
+ } finally {
45148
+ await TrackedState2.saveAllDirty();
45149
+ context2.set("workflowControlContext", void 0);
45150
+ }
45151
+ }
45152
+ /**
45153
+ * Returns a string representation for console.log
45154
+ */
45155
+ toString() {
45156
+ const keyPart = this.key ? ` [${this.key}]` : "";
45157
+ return `WorkflowInstance<${String(this.name)}>${keyPart} { id: "${this.id}", status: "${this.workflow.status}" }`;
45158
+ }
45159
+ /**
45160
+ * Returns a JSON representation for serialization
45161
+ */
45162
+ toJSON() {
45163
+ return {
45164
+ id: this.id,
45165
+ name: this.name,
45166
+ key: this.key,
45167
+ status: this.workflow.status,
45168
+ input: this.input,
45169
+ createdAt: this.createdAt.toISOString(),
45170
+ updatedAt: this.updatedAt.toISOString()
45171
+ };
45172
+ }
45173
+ /**
45174
+ * Custom inspect for Node.js console.log
45175
+ */
45176
+ [Symbol.for("nodejs.util.inspect.custom")]() {
45177
+ return this.toString();
45178
+ }
45179
+ };
45180
+ }
45181
+ });
45182
+
45183
+ // src/primitives/workflow.ts
45184
+ import { z as z21 } from "@botpress/sdk";
45185
+ var import_ms2, WorkflowHandler, Typings7, BaseWorkflow;
45186
+ var init_workflow = __esm({
45187
+ "src/primitives/workflow.ts"() {
45188
+ "use strict";
45189
+ init_define_BUILD();
45190
+ init_define_PACKAGE_VERSIONS();
45191
+ init_workflow_instance();
45192
+ init_context3();
45193
+ import_ms2 = __toESM(require_ms(), 1);
45194
+ init_autonomous();
45195
+ init_runtime();
45196
+ WorkflowHandler = Symbol.for("workflow.handler");
45197
+ ((Typings8) => {
45198
+ Typings8.Primitive = "workflow";
45199
+ })(Typings7 || (Typings7 = {}));
45200
+ BaseWorkflow = class {
45201
+ name;
45202
+ description;
45203
+ /** @internal */
45204
+ _inputSchema;
45205
+ /** @internal */
45206
+ _outputSchema;
45207
+ /** @internal */
45208
+ _stateSchema;
45209
+ /** @internal */
45210
+ _requestsSchemas;
45211
+ /** @internal */
45212
+ _handler;
45213
+ /** @internal */
45214
+ schedule;
45215
+ timeout = (0, import_ms2.default)("5m");
45216
+ constructor(props) {
45217
+ this.name = props.name;
45218
+ if (props.description !== void 0) {
45219
+ this.description = props.description;
45220
+ }
45221
+ this._inputSchema = props.input || z21.object({});
45222
+ this._outputSchema = props.output || z21.object({});
45223
+ this._stateSchema = props.state || z21.object({});
45224
+ this._requestsSchemas = props.requests || {};
45225
+ this._handler = props.handler;
45226
+ this.schedule = props.schedule;
45227
+ if (props.timeout) {
45228
+ this.timeout = (0, import_ms2.default)(props.timeout);
45229
+ }
45230
+ }
45231
+ // @internal
45232
+ get inputSchema() {
45233
+ const schema = this._inputSchema ?? z21.object({}).passthrough();
45234
+ return this.schedule ? schema.optional() : schema;
45235
+ }
45236
+ // @internal
45237
+ get outputSchema() {
45238
+ return this._outputSchema ?? z21.object({}).passthrough();
45239
+ }
45240
+ // @internal
45241
+ get stateSchema() {
45242
+ return this._stateSchema ?? z21.object({}).passthrough();
45243
+ }
45244
+ /**
45245
+ * Get the workflow definition for code generation
45246
+ * @internal
45247
+ */
45248
+ getDefinition() {
45249
+ return {
45250
+ name: this.name,
45251
+ type: Typings7.Primitive,
45252
+ description: this.description,
45253
+ input: this.inputSchema.toJSONSchema(),
45254
+ output: this.outputSchema.toJSONSchema(),
45255
+ state: this.stateSchema.toJSONSchema(),
45256
+ schedule: this.schedule,
45257
+ timeout: this.timeout
45258
+ };
45259
+ }
45260
+ /**
45261
+ * Get or create a workflow instance with the given key and input
45262
+ *
45263
+ * @param props.key - Optional unique key for workflow deduplication
45264
+ * @param props.start - Whether to start the workflow immediately (default: true)
45265
+ * @param props.input - The input data for the workflow
45266
+ * @returns The workflow instance
45267
+ */
45268
+ async getOrCreate(props) {
45269
+ const client2 = context2.get("client");
45270
+ const statuses = props.statuses || ["pending", "in_progress", "listening", "paused"];
45271
+ const validatedInput = this._inputSchema.parse(props.input);
45272
+ const tags = {};
45273
+ if (props.key) {
45274
+ tags["key"] = props.key;
45275
+ }
45276
+ const discriminator = props.key ? ["key"] : void 0;
45277
+ const createArgs = {
45278
+ status: "pending",
45279
+ name: this.name,
45280
+ input: validatedInput,
45281
+ tags,
45282
+ conversationId: context2.get("conversation", { optional: true })?.id,
45283
+ parentWorkflowId: context2.get("workflow", { optional: true })?.id,
45284
+ timeoutAt: new Date(Date.now() + (this.timeout ?? (0, import_ms2.default)("5m"))).toISOString(),
45285
+ ...discriminator && { discriminateBy: { tags: discriminator } }
45286
+ };
45287
+ let { workflow } = await client2._inner.getOrCreateWorkflow(createArgs);
45288
+ if (props.key && !statuses.includes(workflow.status)) {
45289
+ await client2._inner.deleteWorkflow({ id: workflow.id });
45290
+ ({ workflow } = await client2._inner.getOrCreateWorkflow(createArgs));
45291
+ }
45292
+ return await BaseWorkflowInstance.load({
45293
+ id: workflow.id,
45294
+ workflow
45295
+ });
45296
+ }
45297
+ /**
45298
+ * Provide data in response to a workflow data request.
45299
+ * Call this method from a conversation handler when you receive a WorkflowDataRequestEvent.
45300
+ * @param event - The event object from the conversation handler
45301
+ * @param data - The data to provide to the workflow
45302
+ * @example
45303
+ * if (isWorkflowDataRequest(event)) {
45304
+ * await SomeWorkflow.provide(event, { orderId: "12345" });
45305
+ * }
45306
+ */
45307
+ async provide(event, data) {
45308
+ const client2 = context2.get("client");
45309
+ const { workflowId, stepName } = event.payload;
45310
+ const state = createWorkflowExecutionState(client2._inner, workflowId);
45311
+ await state.load();
45312
+ if (!state.value) {
45313
+ throw new Error(`Workflow execution state not found for workflow ${workflowId}`);
45314
+ }
45315
+ console.log(`Providing data to workflow ${workflowId} step ${stepName}`, data, stepName);
45316
+ if (!state.value.steps[stepName]) {
45317
+ state.value.steps[stepName] = {
45318
+ output: data,
45319
+ attempts: 0,
45320
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45321
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString()
45322
+ };
45323
+ } else {
45324
+ state.value.steps[stepName].output = data;
45325
+ state.value.steps[stepName].finishedAt = (/* @__PURE__ */ new Date()).toISOString();
45326
+ }
45327
+ state.value.revision++;
45328
+ await state.save();
45329
+ await client2.createEvent({
45330
+ type: WorkflowContinueEvent.name,
45331
+ workflowId,
45332
+ payload: {}
45333
+ });
45334
+ }
45335
+ async start(input) {
45336
+ const validatedInput = this._inputSchema.parse(input);
45337
+ const client2 = context2.get("client");
45338
+ const event = context2.get("event", { optional: true });
45339
+ const workflow = context2.get("workflow", { optional: true });
45340
+ const res = await client2._inner.createWorkflow({
45341
+ name: this.name,
45342
+ status: event ? "in_progress" : "pending",
45343
+ eventId: event?.id,
45344
+ input: validatedInput,
45345
+ parentWorkflowId: workflow?.id,
45346
+ conversationId: context2.get("conversation", { optional: true })?.id,
45347
+ timeoutAt: new Date(Date.now() + (this.timeout ?? (0, import_ms2.default)("5m"))).toISOString()
45348
+ });
45349
+ return await BaseWorkflowInstance.load({
45350
+ id: res.workflow.id,
45351
+ workflow: res.workflow
45352
+ });
45353
+ }
45354
+ /**
45355
+ * Convert this workflow into an Autonomous.Tool that can be used with execute().
45356
+ * Starts the workflow and returns basic information about the workflow instance.
45357
+ *
45358
+ * @param options.description - Optional description override for the tool
45359
+ * @returns An Autonomous.Tool instance
45360
+ *
45361
+ * @example
45362
+ * const tool = MyWorkflow.asTool()
45363
+ *
45364
+ * await execute({
45365
+ * tools: [tool],
45366
+ * instructions: 'Use the workflow when needed'
45367
+ * })
45368
+ */
45369
+ asTool(options) {
45370
+ const description = options?.description || this.description || `Starts the ${this.name} workflow`;
45371
+ return new Autonomous.Tool({
45372
+ name: this.name,
45373
+ description,
45374
+ input: this._inputSchema,
45375
+ output: z21.object({
45376
+ workflowId: z21.string().describe("The ID of the started workflow"),
45377
+ status: z21.string().describe("The initial status of the workflow")
45378
+ }),
45379
+ handler: async (input) => {
45380
+ const instance = await this.start(input);
45381
+ return {
45382
+ workflowId: instance.id,
45383
+ status: instance.workflow.status
45384
+ };
45385
+ }
45386
+ });
45387
+ }
45388
+ };
45389
+ }
45390
+ });
45391
+
45392
+ // src/runtime/workflows/knowledge-indexing.ts
45393
+ import { z as z22 } from "@botpress/sdk";
45394
+ var KnowledgeIndexingWorkflow;
45395
+ var init_knowledge_indexing = __esm({
45396
+ "src/runtime/workflows/knowledge-indexing.ts"() {
45397
+ "use strict";
45398
+ init_define_BUILD();
45399
+ init_define_PACKAGE_VERSIONS();
45400
+ init_workflow();
45401
+ init_adk();
45402
+ init_source_base();
45403
+ KnowledgeIndexingWorkflow = new BaseWorkflow({
45404
+ name: "builtin_knowledge_indexing",
45405
+ description: "Built-in workflow to re-index all data sources in a knowledge base",
45406
+ input: z22.object({
45407
+ kbName: z22.string(),
45408
+ kbId: z22.string(),
45409
+ force: z22.boolean().optional().describe("Force re-indexing even if files haven't changed").default(false)
45410
+ }),
45411
+ timeout: "180m",
45412
+ output: SyncOutput,
45413
+ handler: async ({ input, step: step2 }) => {
45414
+ const { kbName, kbId } = input;
45415
+ const kb = adk.project.knowledge.find((x) => x.name === kbName);
45416
+ if (!kb) {
45417
+ throw new Error(`Knowledge base '${kbName}' not found`);
45418
+ }
45419
+ const workflows = await step2.map(
45420
+ "index-sources",
45421
+ kb.sources,
45422
+ async (source) => {
45423
+ const workflowId = await step2(
45424
+ "create-sync-workflow",
45425
+ async () => await source.syncWorkflow.getOrCreate({
45426
+ key: `${kbName}:${source.id}`,
45427
+ statuses: ["in_progress", "listening", "pending", "paused"],
45428
+ input: {
45429
+ kbName,
45430
+ kbId,
45431
+ dsId: source.id,
45432
+ force: input.force || false
45433
+ }
45434
+ }).then((x) => x.id)
45435
+ );
45436
+ return await step2.waitForWorkflow(source.id, workflowId).then((x) => x.output);
45437
+ },
45438
+ { concurrency: 10, maxAttempts: 1 }
45439
+ );
45440
+ return {
45441
+ errors: workflows.flatMap((w) => w.errors || []),
45442
+ processed: workflows.reduce((a, w) => a + (w.processed || 0), 0),
45443
+ added: workflows.flatMap((w) => w.added || []),
45444
+ updated: workflows.flatMap((w) => w.updated || []),
45445
+ deleted: workflows.flatMap((w) => w.deleted || [])
45446
+ };
45447
+ }
45448
+ });
45449
+ }
45450
+ });
45451
+
45452
+ // src/runtime/workflows/index.ts
45453
+ var BuiltInWorkflows;
45454
+ var init_workflows = __esm({
45455
+ "src/runtime/workflows/index.ts"() {
45456
+ "use strict";
45457
+ init_define_BUILD();
45458
+ init_define_PACKAGE_VERSIONS();
45459
+ init_knowledge_indexing();
45460
+ BuiltInWorkflows = {
45461
+ KnowledgeIndexingWorkflow
45462
+ };
45463
+ }
45464
+ });
45465
+
45466
+ // src/runtime/actions/order-recompute-columns.ts
45467
+ function orderRecomputeColumns(toRecompute, staleColumns, columns) {
45468
+ const ordered = [];
45469
+ const visited = /* @__PURE__ */ new Set();
45470
+ function visit(colName) {
45471
+ if (visited.has(colName)) return;
45472
+ visited.add(colName);
45473
+ const deps = columns[colName]?.dependencies || [];
45474
+ for (const dep of deps) {
45475
+ if (staleColumns.has(dep)) {
45476
+ visit(dep);
45477
+ }
45478
+ }
45479
+ if (staleColumns.has(colName) || toRecompute.includes(colName)) {
45480
+ ordered.push(colName);
45481
+ }
45482
+ }
45483
+ for (const col of toRecompute) {
45484
+ visit(col);
45485
+ }
45486
+ return ordered;
45487
+ }
45488
+ var init_order_recompute_columns = __esm({
45489
+ "src/runtime/actions/order-recompute-columns.ts"() {
45490
+ "use strict";
45491
+ init_define_BUILD();
45492
+ init_define_PACKAGE_VERSIONS();
45493
+ }
45494
+ });
45495
+
45496
+ // src/runtime/actions/computed-columns.ts
45497
+ import { z as z23 } from "@botpress/sdk";
45498
+ var tablesRecomputeRows;
45499
+ var init_computed_columns = __esm({
45500
+ "src/runtime/actions/computed-columns.ts"() {
45501
+ "use strict";
45502
+ init_define_BUILD();
45503
+ init_define_PACKAGE_VERSIONS();
45504
+ init_action();
45505
+ init_adk();
45506
+ init_order_recompute_columns();
45507
+ init_runtime();
45508
+ tablesRecomputeRows = new BaseAction({
45509
+ name: "tablesRecomputeRows",
45510
+ // skynet/packages/tables-api/src/services/computed/compute-stale-rows.ts
45511
+ input: z23.object({
45512
+ tableId: z23.string(),
45513
+ botId: z23.string(),
45514
+ schema: z23.any(),
45515
+ requests: z23.array(
45516
+ z23.object({
45517
+ row: z23.record(z23.any()),
45518
+ columnsToRecompute: z23.array(z23.string())
45519
+ })
45520
+ )
45521
+ }),
45522
+ output: z23.object({
45523
+ isFinished: z23.boolean(),
45524
+ rows: z23.array(z23.any())
45525
+ }),
45526
+ handler: async ({ input, client: client2 }) => {
45527
+ const { tableId, requests } = input;
45528
+ const { table: remoteTable } = await client2._inner.getTable({ table: tableId });
45529
+ const table = adk.project.tables.find((x) => x.name === remoteTable.name);
45530
+ async function computeRow(row, columnsToRecompute) {
45531
+ const newRow = { id: row.id };
45532
+ const recompute = orderRecomputeColumns(
45533
+ columnsToRecompute,
45534
+ new Set(row.stale ?? []),
45535
+ table?.columns || {}
45536
+ );
45537
+ for (const colName of recompute) {
45538
+ const col = table?.columns[colName];
45539
+ if (!col || !col.computed) {
45540
+ newRow[colName] = { status: "error", error: "Column not found or not computed" };
45541
+ continue;
45542
+ }
45543
+ const value = await col.value(row);
45544
+ row[colName] = value;
45545
+ newRow[colName] = {
45546
+ status: "computed",
45547
+ value
45548
+ };
45549
+ }
45550
+ return newRow;
45551
+ }
45552
+ const MIN_REMAINING_TIME_MS = 5e3;
45553
+ const BUFFER_TIME_MS = 5e3;
45554
+ let recomputed = [];
45555
+ let isFinished = true;
45556
+ const remainingTime = context2.get("runtime").getRemainingExecutionTimeInMs();
45557
+ if (remainingTime && remainingTime < MIN_REMAINING_TIME_MS) {
45558
+ return { isFinished: false, rows: [] };
45559
+ }
45560
+ const timeoutPromise = new Promise((resolve) => {
45561
+ setTimeout(() => {
45562
+ isFinished = false;
45563
+ resolve();
45564
+ }, remainingTime - BUFFER_TIME_MS);
45565
+ });
45566
+ const allRowsPromise = Promise.all(
45567
+ requests.map(async (r) => {
45568
+ const computedRow = await computeRow(r.row, r.columnsToRecompute);
45569
+ recomputed.push(computedRow);
45570
+ })
45571
+ );
45572
+ await Promise.race([timeoutPromise, allRowsPromise]);
45573
+ return { isFinished, rows: recomputed };
45574
+ }
45575
+ });
45576
+ }
45577
+ });
45578
+
45579
+ // src/runtime/actions/index.ts
45580
+ var BuiltInActions;
45581
+ var init_actions2 = __esm({
45582
+ "src/runtime/actions/index.ts"() {
45583
+ "use strict";
45584
+ init_define_BUILD();
45585
+ init_define_PACKAGE_VERSIONS();
45586
+ init_computed_columns();
45587
+ BuiltInActions = {
45588
+ tablesRecomputeRows
45589
+ };
45590
+ }
45591
+ });
45592
+
45593
+ // src/runtime/adk.ts
45594
+ var adk_exports = {};
45595
+ __export(adk_exports, {
45596
+ adk: () => adk,
45597
+ initialize: () => initialize,
45598
+ register: () => register,
45599
+ registerIntegration: () => registerIntegration
45600
+ });
45601
+ import { BotSpecificClient } from "@botpress/sdk";
45602
+ import { Zai as Zai2 } from "@botpress/zai";
45603
+ import { Cognitive as Cognitive3 } from "@botpress/cognitive";
45604
+ import { Client as Client2 } from "@botpress/client";
45605
+ function getStandaloneCognitive() {
45606
+ return getSingleton("__ADK_GLOBAL_STANDALONE_COGNITIVE", () => {
45607
+ const token = process.env.BP_TOKEN || process.env.ADK_TOKEN;
45608
+ if (!token) {
45609
+ throw new Error(
45610
+ 'No token found. Set BP_TOKEN or ADK_TOKEN environment variable, or run this script using "adk run".'
45611
+ );
45612
+ }
45613
+ const botId = process.env.ADK_BOT_ID;
45614
+ if (!botId) {
45615
+ throw new Error('No bot ID found. Set ADK_BOT_ID environment variable, or run this script using "adk run".');
45616
+ }
45617
+ const apiUrl = process.env.ADK_API_URL || "https://api.botpress.cloud";
45618
+ const vanillaClient = new Client2({
45619
+ token,
45620
+ apiUrl,
45621
+ botId
45622
+ });
45623
+ const botClient = new BotSpecificClient(vanillaClient);
45624
+ return new Cognitive3({
45625
+ client: botClient,
45626
+ __experimental_beta: true
45627
+ });
45628
+ });
45629
+ }
45630
+ function initialize(options) {
45631
+ const state = getState();
45632
+ if (state.initialized) {
45633
+ throw new Error("ADK API already initialized");
45634
+ }
45635
+ state.projectConfig = options.config;
45636
+ state.initialized = true;
45637
+ state.primitives.workflows.push(...Object.values(BuiltInWorkflows));
45638
+ state.primitives.actions.push(...Object.values(BuiltInActions));
45639
+ }
45640
+ function register(...primitives) {
45641
+ const state = getState();
45642
+ if (!state.initialized) {
45643
+ throw new Error("ADK API not initialized. Call initialize() first.");
45644
+ }
45645
+ for (const primitive of primitives) {
45646
+ const definition = primitive.getDefinition();
45647
+ switch (definition.type) {
45648
+ case "action":
45649
+ state.primitives.actions.push(primitive);
45650
+ break;
45651
+ case "conversation":
45652
+ state.primitives.conversations.push(primitive);
45653
+ break;
45654
+ case "knowledge":
45655
+ state.primitives.knowledge.push(primitive);
45656
+ for (const source of definition.sources) {
45657
+ state.primitives.workflows.push(source.syncWorkflow);
45658
+ }
45659
+ break;
45660
+ case "table":
45661
+ state.primitives.tables.push(primitive);
45662
+ break;
45663
+ case "trigger":
45664
+ state.primitives.triggers.push(primitive);
45665
+ break;
45666
+ case "workflow":
45667
+ state.primitives.workflows.push(primitive);
45668
+ break;
45669
+ }
45670
+ }
45671
+ }
45672
+ function registerIntegration(props) {
45673
+ const state = getState();
45674
+ if (!state.initialized) {
45675
+ throw new Error("ADK API not initialized. Call initialize() first.");
45676
+ }
45677
+ state.primitives.integrations.push({
45678
+ alias: props.alias,
45679
+ definition: props.definition,
45680
+ get actions() {
45681
+ return actions[props.alias];
45682
+ }
45683
+ });
45684
+ }
45685
+ var getState, adk;
45686
+ var init_adk = __esm({
45687
+ "src/runtime/adk.ts"() {
45688
+ "use strict";
45689
+ init_define_BUILD();
45690
+ init_define_PACKAGE_VERSIONS();
45691
+ init_singletons();
45692
+ init_environment();
45693
+ init_actions();
45694
+ init_workflows();
45695
+ init_library();
45696
+ init_actions2();
45697
+ getState = () => getSingleton("__ADK_GLOBAL_PROJECT", () => {
45698
+ const state = {
45699
+ initialized: false,
45700
+ primitives: {
45701
+ integrations: [],
45702
+ actions: [],
45703
+ knowledge: [],
45704
+ tables: [],
45705
+ workflows: [],
45706
+ conversations: [],
45707
+ triggers: []
45708
+ }
45709
+ };
45710
+ return state;
45711
+ });
45712
+ adk = {
45713
+ get environment() {
45714
+ return Environment;
45715
+ },
45716
+ get zai() {
45717
+ const contextCognitive = context2.get("cognitive", { optional: true });
45718
+ const cognitive = contextCognitive ?? getStandaloneCognitive();
45719
+ return new Zai2({
45720
+ client: cognitive,
45721
+ modelId: Array.isArray(adk.project.config.defaultModels.zai) ? adk.project.config.defaultModels.zai[0] ?? "auto" : adk.project.config.defaultModels.zai
45722
+ });
45723
+ },
45724
+ get project() {
45725
+ const state = getState();
45726
+ if (!state.initialized || !state.projectConfig) {
45727
+ throw new Error("ADK API not initialized");
45728
+ }
45729
+ return {
45730
+ config: state.projectConfig,
45731
+ integrations: Object.assign(state.primitives.integrations, {
45732
+ get(name) {
45733
+ const byAlias = state.primitives.integrations.find((int) => int.alias === name);
45734
+ const byName = state.primitives.integrations.find((int) => int.definition.name === name);
45735
+ return byAlias || byName;
45736
+ }
45737
+ }),
45738
+ actions: state.primitives.actions,
45739
+ knowledge: state.primitives.knowledge,
45740
+ tables: state.primitives.tables,
45741
+ workflows: state.primitives.workflows,
45742
+ conversations: state.primitives.conversations,
45743
+ triggers: state.primitives.triggers
45744
+ };
45745
+ },
45746
+ async execute(props) {
45747
+ const contextCognitive = context2.get("cognitive", { optional: true });
45748
+ const cognitive = contextCognitive ?? getStandaloneCognitive();
45749
+ const defaultModel = adk.project.config.defaultModels.autonomous;
45750
+ const { execute: llmz_execute, getValue: getValue2 } = await import("llmz");
45751
+ return llmz_execute({
45752
+ client: cognitive,
45753
+ instructions: props.instructions,
45754
+ ...props.tools && { tools: props.tools },
45755
+ ...props.objects && { objects: props.objects },
45756
+ ...props.exits && { exits: props.exits },
45757
+ ...props.signal && { signal: props.signal },
45758
+ temperature: async (ctx) => props.temperature ? await getValue2(props.temperature, ctx) : 0.7,
45759
+ model: async (ctx) => props.model ? await getValue2(props.model, ctx) : defaultModel,
45760
+ options: { loop: props.iterations ?? 10 },
45761
+ ...props.hooks?.onTrace && { onTrace: props.hooks.onTrace },
45762
+ ...props.hooks?.onIterationEnd && { onIterationEnd: props.hooks.onIterationEnd },
45763
+ ...props.hooks?.onBeforeTool && { onBeforeTool: props.hooks.onBeforeTool },
45764
+ ...props.hooks?.onAfterTool && { onAfterTool: props.hooks.onAfterTool },
45765
+ ...props.hooks?.onBeforeExecution && { onBeforeExecution: props.hooks.onBeforeExecution },
45766
+ ...props.hooks?.onExit && { onExit: props.hooks.onExit }
45767
+ });
45768
+ }
45769
+ };
45466
45770
  }
45467
45771
  });
45468
45772
 
45469
- // src/primitives/workflow-instance.ts
45470
- var workflow_instance_exports = {};
45471
- __export(workflow_instance_exports, {
45472
- BaseWorkflowInstance: () => BaseWorkflowInstance,
45473
- createStepSignal: () => createStepSignal,
45474
- createWorkflowExecutionState: () => createWorkflowExecutionState,
45475
- isStepSignal: () => isStepSignal
45476
- });
45477
- import { z as z22 } from "@botpress/sdk";
45478
- import assert2 from "assert";
45479
- function isStepSignal(e) {
45480
- return typeof e === "object" && e !== null && StepSymbol in e;
45481
- }
45482
- function createStepSignal() {
45483
- return {
45484
- [StepSymbol]: true
45485
- };
45486
- }
45487
- function createWorkflowExecutionState(client2, workflowId) {
45488
- return TrackedState.create({
45489
- type: "workflow",
45490
- client: client2,
45491
- id: workflowId,
45492
- schema: workflowExecutionContextSchema,
45493
- name: BUILT_IN_STATES.workflowSteps
45494
- });
45773
+ // src/runtime/tracked-tags.ts
45774
+ function isSystemTag(key) {
45775
+ return key.includes(":");
45495
45776
  }
45496
- var import_ms, workflowStepContextSchema, workflowExecutionContextSchema, StepSymbol, BaseWorkflowInstance;
45497
- var init_workflow_instance = __esm({
45498
- "src/primitives/workflow-instance.ts"() {
45777
+ var TrackedTags;
45778
+ var init_tracked_tags = __esm({
45779
+ "src/runtime/tracked-tags.ts"() {
45499
45780
  "use strict";
45500
45781
  init_define_BUILD();
45501
45782
  init_define_PACKAGE_VERSIONS();
45502
- import_ms = __toESM(require_ms(), 1);
45503
- init_errors();
45504
- init_library();
45505
- init_autonomous();
45506
- init_runtime2();
45507
- init_state_reference_symbol();
45508
- init_workflow_step();
45509
- init_workflow_utils();
45510
- init_workflow_cancellation_monitor();
45511
- workflowStepContextSchema = z22.lazy(
45512
- () => z22.object({
45513
- output: z22.unknown().optional(),
45514
- attempts: z22.number(),
45515
- i: z22.number().optional(),
45516
- startedAt: z22.string(),
45517
- finishedAt: z22.string().optional(),
45518
- steps: z22.record(z22.string(), workflowStepContextSchema).optional(),
45519
- error: z22.object({
45520
- message: z22.string(),
45521
- failedAt: z22.string(),
45522
- maxAttemptsReached: z22.boolean()
45523
- }).optional()
45524
- })
45525
- );
45526
- workflowExecutionContextSchema = z22.object({
45527
- executionCount: z22.number().default(0),
45528
- revision: z22.number().default(0),
45529
- steps: z22.record(z22.string(), workflowStepContextSchema)
45530
- }).default({
45531
- executionCount: 0,
45532
- steps: {}
45533
- });
45534
- StepSymbol = Symbol.for("StepSignal");
45535
- BaseWorkflowInstance = class _BaseWorkflowInstance {
45783
+ init_context3();
45784
+ init_tracing();
45785
+ init_adk();
45786
+ TrackedTags = class _TrackedTags {
45787
+ type;
45536
45788
  id;
45537
- name;
45538
- key;
45539
- input;
45540
- createdAt;
45541
- updatedAt;
45542
45789
  client;
45543
- // Can be Client or BotClient
45544
- workflow;
45545
- // @internal
45546
- TrackedState;
45547
- // @internal
45548
- TrackedTags;
45549
- constructor(workflow, client2) {
45550
- const definition = adk.project.workflows.find((w) => w.name === workflow.name);
45551
- this.TrackedState = TrackedState.create({
45552
- type: "workflow",
45553
- client: client2._inner,
45554
- id: workflow.id,
45555
- schema: definition?.stateSchema,
45556
- name: BUILT_IN_STATES.workflowState
45557
- });
45558
- this.TrackedTags = TrackedTags.create({
45559
- type: "workflow",
45560
- client: client2._inner,
45561
- id: workflow.id,
45562
- initialTags: workflow.tags
45563
- });
45564
- this.id = workflow.id;
45565
- this.name = workflow.name;
45566
- this.key = workflow.tags.key;
45567
- this.input = workflow.input;
45568
- this.createdAt = new Date(workflow.createdAt);
45569
- this.updatedAt = new Date(workflow.updatedAt);
45570
- this.client = client2;
45571
- this.workflow = workflow;
45572
- }
45573
- get tags() {
45574
- return this.TrackedTags.tags;
45575
- }
45576
- set tags(value) {
45577
- this.TrackedTags.tags = value;
45578
- }
45579
- /**
45580
- * Symbol method for automatic serialization to reference in state
45581
- * @internal
45582
- */
45583
- [StateReference]() {
45584
- return {
45585
- __ref__: "workflow",
45586
- id: this.id
45587
- };
45588
- }
45589
- static Primitive = "workflow_instance";
45590
- static async load(props) {
45591
- const client2 = context2.get("client");
45592
- const workflow = props.workflow ? props.workflow : await client2.getWorkflow({ id: props.id }).then((x) => x.workflow);
45593
- if (!adk.project.workflows.find((w) => w.name === workflow.name)) {
45594
- throw new Error(`No ADK Workflow definition found for "${workflow.name}"`);
45595
- }
45596
- TrackedTags.create({
45597
- type: "workflow",
45598
- client: client2._inner,
45599
- id: workflow.id,
45600
- initialTags: workflow.tags
45601
- });
45602
- await TrackedTags.loadAll();
45603
- return new _BaseWorkflowInstance(workflow, client2);
45604
- }
45605
- /**
45606
- * Executes the workflow with the provided autonomous engine configuration.
45607
- * Workflows always run in "worker" mode (no chat capabilities).
45608
- */
45609
- async execute(props) {
45610
- const executeFunc = Autonomous.createExecute({
45611
- mode: "worker",
45612
- defaultModel: adk.project.config.defaultModels.autonomous
45613
- });
45614
- return executeFunc(props);
45615
- }
45616
- /**
45617
- * Cancel the workflow execution.
45618
- * Note: This should be called from within a proper bot handler context.
45619
- * If calling from a conversation handler, ensure TrackedTags.loadAll() has been called.
45620
- */
45621
- async cancel() {
45622
- await TrackedTags.loadAll();
45623
- const { workflow } = await updateWorkflow({
45624
- id: this.id,
45625
- status: "cancelled"
45626
- });
45627
- Object.assign(this.workflow, workflow);
45790
+ _tags = {};
45791
+ _initialTags = {};
45792
+ _loaded = false;
45793
+ _saving = false;
45794
+ _saveAgain = false;
45795
+ _saveAgainCount = 0;
45796
+ static _savingAll = false;
45797
+ static _saveAllAgain = false;
45798
+ static _saveAllCount = 0;
45799
+ constructor(props) {
45800
+ this.type = props.type;
45801
+ this.id = props.id;
45802
+ this.client = props.client;
45628
45803
  }
45629
- /**
45630
- * Extend the workflow timeout by setting a new timeout.
45631
- * This is useful for long-running workflows that need more time to complete.
45632
- *
45633
- * @param options - Either `{ in: string }` for relative duration or `{ at: string }` for absolute ISO timestamp
45634
- * @returns A promise that resolves when the timeout is updated (can be awaited or not)
45635
- * @example
45636
- * // Relative timeout (duration from now):
45637
- * workflow.setTimeout({ in: '30m' }) // Timeout in 30 minutes
45638
- * workflow.setTimeout({ in: '6 hours' }) // Timeout in 6 hours
45639
- *
45640
- * // Absolute timeout (ISO timestamp):
45641
- * workflow.setTimeout({ at: '2024-12-25T00:00:00Z' })
45642
- *
45643
- * // Optionally await if you need to ensure the update completes:
45644
- * await workflow.setTimeout({ in: '1h' })
45645
- */
45646
- setTimeout(options) {
45647
- let newTimeoutAt;
45648
- if ("in" in options) {
45649
- const durationMs = (0, import_ms.default)(options.in);
45650
- if (!durationMs) {
45651
- throw new Error(`Invalid duration format: "${options.in}". Use formats like "30m", "1h", "6 hours".`);
45652
- }
45653
- newTimeoutAt = new Date(Date.now() + durationMs).toISOString();
45654
- } else {
45655
- const date = new Date(options.at);
45656
- if (isNaN(date.getTime())) {
45657
- throw new Error(`Invalid ISO date format: "${options.at}".`);
45658
- }
45659
- newTimeoutAt = date.toISOString();
45804
+ static create(props) {
45805
+ const tags = context2.get("tags", { optional: true });
45806
+ const executionFinished = context2.get("executionFinished", { optional: true });
45807
+ if (executionFinished) {
45808
+ throw new Error(`Cannot create new TrackedTags "${props.type}/${props.id}" after execution has finished.`);
45660
45809
  }
45661
- return updateWorkflow({
45662
- id: this.id,
45663
- timeoutAt: newTimeoutAt
45664
- }).then(({ workflow }) => {
45665
- Object.assign(this.workflow, workflow);
45666
- });
45667
- }
45668
- /**
45669
- * Fail the workflow with an error reason.
45670
- * This immediately interrupts the workflow handler and marks the workflow as failed.
45671
- * Can only be called from within a workflow handler.
45672
- *
45673
- * @param reason - The error reason for the failure
45674
- * @throws Never returns - always throws to interrupt the handler
45675
- * @example
45676
- * workflow.fail('Invalid input data')
45677
- */
45678
- fail(reason) {
45679
- const controlContext = context2.get("workflowControlContext", { optional: true });
45680
- if (!controlContext || controlContext.workflow.id !== this.id) {
45681
- throw new Error("workflow.fail() can only be called from within the workflow handler");
45810
+ const match2 = tags?.find((x) => x.id === props.id && x.type === props.type);
45811
+ if (match2) {
45812
+ return match2;
45682
45813
  }
45683
- controlContext.fail(reason);
45684
- throw createStepSignal();
45685
- }
45686
- /**
45687
- * Complete the workflow early with the given output.
45688
- * This immediately interrupts the workflow handler and marks the workflow as completed.
45689
- * Can only be called from within a workflow handler.
45690
- *
45691
- * @param output - The workflow output (typed according to workflow definition)
45692
- * @throws Never returns - always throws to interrupt the handler
45693
- * @example
45694
- * workflow.complete({ result: 'success', data: processedData })
45695
- */
45696
- complete(output2) {
45697
- const controlContext = context2.get("workflowControlContext", { optional: true });
45698
- if (!controlContext || controlContext.workflow.id !== this.id) {
45699
- throw new Error("workflow.complete() can only be called from within the workflow handler");
45814
+ const instance = new _TrackedTags(props);
45815
+ if (props.initialTags) {
45816
+ instance._tags = { ...props.initialTags };
45817
+ instance._initialTags = { ...props.initialTags };
45818
+ instance._loaded = true;
45700
45819
  }
45701
- controlContext.complete(output2);
45702
- throw createStepSignal();
45820
+ tags?.push(instance);
45821
+ return instance;
45703
45822
  }
45704
- /**
45705
- * Provide data in response to a workflow data request (instance method).
45706
- * Call this method from a conversation handler when you receive a WorkflowDataRequestEvent.
45707
- * @param request - The name of the request being responded to
45708
- * @param data - The data to provide to the workflow
45709
- * @example
45710
- * if (type === 'workflow_request') {
45711
- * await workflow.provide('topic', { topic: "Hello" });
45712
- * }
45713
- */
45714
- async provide(request, data) {
45715
- const client2 = context2.get("client");
45716
- const state = createWorkflowExecutionState(client2._inner, this.id);
45717
- await state.load();
45718
- if (!state.value) {
45719
- throw new Error(`Workflow execution state not found for workflow ${this.id}`);
45823
+ static async saveAllDirty() {
45824
+ if (this._savingAll) {
45825
+ this._saveAllAgain = true;
45826
+ return;
45720
45827
  }
45721
- const stepName = request;
45722
- if (!state.value.steps[stepName]) {
45723
- state.value.steps[stepName] = {
45724
- output: data,
45725
- attempts: 0,
45726
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45727
- finishedAt: (/* @__PURE__ */ new Date()).toISOString()
45728
- };
45729
- } else {
45730
- state.value.steps[stepName].output = data;
45731
- state.value.steps[stepName].finishedAt = (/* @__PURE__ */ new Date()).toISOString();
45828
+ try {
45829
+ this._savingAll = true;
45830
+ const tags = context2.get("tags", { optional: true });
45831
+ const dirtyTags = tags?.filter((t) => t.isDirty()) || [];
45832
+ if (!dirtyTags.length) {
45833
+ return;
45834
+ }
45835
+ await span(
45836
+ "tags.saveAllDirty",
45837
+ {
45838
+ tags_count: tags?.length || 0,
45839
+ tags: tags.map((t) => `${t.type}/${t.id}`)
45840
+ },
45841
+ () => Promise.allSettled(dirtyTags.map((t) => t.save()))
45842
+ );
45843
+ } finally {
45844
+ this._savingAll = false;
45845
+ if (this._saveAllAgain && this._saveAllCount++ <= 5) {
45846
+ this._saveAllAgain = false;
45847
+ await this.saveAllDirty();
45848
+ } else {
45849
+ this._saveAllCount = 0;
45850
+ }
45732
45851
  }
45733
- state.value.revision++;
45734
- await state.save();
45735
- await client2.createEvent({
45736
- type: WorkflowContinueEvent.name,
45737
- workflowId: this.id,
45738
- payload: {}
45739
- });
45740
45852
  }
45741
- // @internal
45742
- async handle(abortSignal) {
45743
- abortSignal.throwIfAborted();
45744
- const handler = adk.project.workflows.find((w) => w.name === this.name)._handler;
45745
- if (!handler) {
45746
- throw new Error(`No ADK Workflow handler found for "${this.name}"`);
45747
- }
45748
- await TrackedState.loadAll();
45749
- abortSignal.throwIfAborted();
45750
- const workflowControlContext = {
45751
- workflow: this.workflow,
45752
- aborted: false,
45753
- failed: false,
45754
- completed: false,
45755
- acked: false,
45756
- restarted: false,
45757
- signal: abortSignal,
45758
- restart: () => {
45759
- workflowControlContext.restarted = true;
45760
- },
45761
- abort: () => {
45762
- workflowControlContext.aborted = true;
45763
- workflowControlContext.acked = true;
45764
- },
45765
- fail: (reason) => {
45766
- workflowControlContext.failed = true;
45767
- workflowControlContext.failedReason = reason;
45768
- },
45769
- complete: (result) => {
45770
- workflowControlContext.completed = true;
45771
- workflowControlContext.completedResult = result;
45772
- },
45773
- ack: async () => {
45774
- if (workflowControlContext.acked) {
45775
- return;
45776
- }
45777
- const eventId = context2.get("event")?.id;
45778
- if (!eventId) {
45779
- throw new Error(`Event ID not found in context. Cannot ack workflow ${this.id}`);
45780
- }
45781
- workflowControlContext.acked = true;
45782
- await updateWorkflow({
45783
- id: this.id,
45784
- status: "in_progress",
45785
- eventId
45853
+ static async loadAll() {
45854
+ await span("tags.loadAll", {}, async () => {
45855
+ const client2 = context2.get("client")._inner;
45856
+ const bot2 = context2.get("bot", { optional: true });
45857
+ const user2 = context2.get("user", { optional: true });
45858
+ const conversation = context2.get("conversation", { optional: true });
45859
+ const workflow = context2.get("workflow", { optional: true });
45860
+ if (bot2) {
45861
+ const botTags = bot2.tags;
45862
+ _TrackedTags.create({
45863
+ client: client2,
45864
+ type: "bot",
45865
+ id: bot2.id,
45866
+ ...botTags && { initialTags: botTags }
45786
45867
  });
45787
- this.workflow.status = "in_progress";
45788
45868
  }
45789
- };
45790
- try {
45791
- const client2 = context2.get("client");
45792
- const workflowExecutionState = createWorkflowExecutionState(client2._inner, this.id);
45793
- await workflowExecutionState.load();
45794
- await this.TrackedState.load();
45795
- abortSignal.throwIfAborted();
45796
- assert2(workflowExecutionState.value, "Workflow execution state is not loaded");
45797
- workflowExecutionState.value.executionCount++;
45798
- if (!this.TrackedState.value) {
45799
- this.TrackedState.value = {};
45869
+ if (user2) {
45870
+ const userTags = user2.tags;
45871
+ _TrackedTags.create({
45872
+ client: client2,
45873
+ type: "user",
45874
+ id: user2.id,
45875
+ ...userTags && { initialTags: userTags }
45876
+ });
45800
45877
  }
45801
- const trackedState = this.TrackedState;
45802
- const stateProxy = new Proxy(this.TrackedState.value, {
45803
- set(target, prop, value) {
45804
- const result = Reflect.set(target, prop, value);
45805
- trackedState.markDirty();
45806
- return result;
45807
- }
45808
- });
45809
- if (this.workflow.status === "pending") {
45810
- await workflowControlContext.ack();
45878
+ if (conversation) {
45879
+ const conversationTags = conversation.tags;
45880
+ _TrackedTags.create({
45881
+ client: client2,
45882
+ type: "conversation",
45883
+ id: conversation.id,
45884
+ ...conversationTags && { initialTags: conversationTags }
45885
+ });
45811
45886
  }
45812
- context2.set("workflowControlContext", workflowControlContext);
45813
- const stopCancellationMonitor = startWorkflowCancellationMonitor({
45814
- client: client2._inner,
45815
- workflowId: this.id,
45816
- workflowControlContext,
45817
- abortSignal
45818
- });
45819
- try {
45820
- const result = await handler({
45821
- input: this.input,
45822
- state: stateProxy,
45823
- step,
45824
- client: this.client,
45825
- execute: this.execute.bind(this),
45826
- signal: abortSignal,
45827
- workflow: this
45887
+ if (workflow) {
45888
+ const workflowTags = workflow.tags;
45889
+ _TrackedTags.create({
45890
+ client: client2,
45891
+ type: "workflow",
45892
+ id: workflow.id,
45893
+ ...workflowTags && { initialTags: workflowTags }
45828
45894
  });
45829
- return {
45830
- status: "done",
45831
- result
45832
- };
45833
- } finally {
45834
- stopCancellationMonitor();
45835
45895
  }
45836
- } catch (err) {
45837
- if (isStepSignal(err)) {
45838
- if (workflowControlContext.completed) {
45839
- return {
45840
- status: "done",
45841
- result: workflowControlContext.completedResult
45842
- };
45843
- }
45844
- if (workflowControlContext.failed) {
45845
- return {
45846
- status: "error",
45847
- error: workflowControlContext.failedReason || Errors.toErrorString(err)
45848
- };
45896
+ const tags = context2.get("tags", { optional: true });
45897
+ const unloadedTags = tags?.filter((tag) => !tag._loaded) ?? [];
45898
+ if (unloadedTags.length > 0) {
45899
+ await Promise.allSettled(unloadedTags.map((tag) => tag.load()));
45900
+ }
45901
+ });
45902
+ }
45903
+ static unloadAll() {
45904
+ context2.get("tags", { optional: true })?.splice(0);
45905
+ }
45906
+ async load(force = false) {
45907
+ if (this._loaded && !force) {
45908
+ return;
45909
+ }
45910
+ await span(
45911
+ "tags.load",
45912
+ {
45913
+ type: this.type,
45914
+ id: this.id
45915
+ },
45916
+ async () => {
45917
+ const tags = await this.fetchTags();
45918
+ this._tags = { ...tags };
45919
+ this._initialTags = { ...tags };
45920
+ this._loaded = true;
45921
+ }
45922
+ );
45923
+ }
45924
+ async save() {
45925
+ if (this._saving) {
45926
+ this._saveAgain = true;
45927
+ return;
45928
+ }
45929
+ const executionFinished = context2.get("executionFinished", { optional: true });
45930
+ if (executionFinished) {
45931
+ throw new Error(`Cannot save TrackedTags "${this.type}/${this.id}" after execution has finished.`);
45932
+ }
45933
+ try {
45934
+ this._saving = true;
45935
+ await span(
45936
+ "tags.save",
45937
+ {
45938
+ type: this.type,
45939
+ id: this.id
45940
+ },
45941
+ async () => {
45942
+ await this.persistTags(this._tags);
45943
+ this._initialTags = { ...this._tags };
45849
45944
  }
45850
- return {
45851
- status: "continue"
45852
- };
45945
+ );
45946
+ } finally {
45947
+ this._saving = false;
45948
+ if (this._saveAgain && this._saveAgainCount++ <= 5) {
45949
+ this._saveAgain = false;
45950
+ await this.save();
45853
45951
  } else {
45854
- const str = Errors.toErrorString(err);
45855
- return {
45856
- status: "error",
45857
- error: str
45858
- };
45952
+ this._saveAgainCount = 0;
45859
45953
  }
45860
- } finally {
45861
- await TrackedState.saveAllDirty();
45862
- context2.set("workflowControlContext", void 0);
45863
45954
  }
45864
45955
  }
45865
- /**
45866
- * Returns a string representation for console.log
45867
- */
45868
- toString() {
45869
- const keyPart = this.key ? ` [${this.key}]` : "";
45870
- return `WorkflowInstance<${String(this.name)}>${keyPart} { id: "${this.id}", status: "${this.workflow.status}" }`;
45871
- }
45872
- /**
45873
- * Returns a JSON representation for serialization
45874
- */
45875
- toJSON() {
45876
- return {
45877
- id: this.id,
45878
- name: this.name,
45879
- key: this.key,
45880
- status: this.workflow.status,
45881
- input: this.input,
45882
- createdAt: this.createdAt.toISOString(),
45883
- updatedAt: this.updatedAt.toISOString()
45884
- };
45885
- }
45886
- /**
45887
- * Custom inspect for Node.js console.log
45888
- */
45889
- [Symbol.for("nodejs.util.inspect.custom")]() {
45890
- return this.toString();
45891
- }
45892
- };
45893
- }
45894
- });
45895
-
45896
- // src/primitives/workflow.ts
45897
- import { z as z23 } from "@botpress/sdk";
45898
- var import_ms2, WorkflowHandler, Typings7, BaseWorkflow;
45899
- var init_workflow = __esm({
45900
- "src/primitives/workflow.ts"() {
45901
- "use strict";
45902
- init_define_BUILD();
45903
- init_define_PACKAGE_VERSIONS();
45904
- init_workflow_instance();
45905
- init_context3();
45906
- import_ms2 = __toESM(require_ms(), 1);
45907
- init_autonomous();
45908
- init_runtime();
45909
- WorkflowHandler = Symbol.for("workflow.handler");
45910
- ((Typings8) => {
45911
- Typings8.Primitive = "workflow";
45912
- })(Typings7 || (Typings7 = {}));
45913
- BaseWorkflow = class {
45914
- name;
45915
- description;
45916
- /** @internal */
45917
- _inputSchema;
45918
- /** @internal */
45919
- _outputSchema;
45920
- /** @internal */
45921
- _stateSchema;
45922
- /** @internal */
45923
- _requestsSchemas;
45924
- /** @internal */
45925
- _handler;
45926
- /** @internal */
45927
- schedule;
45928
- timeout = (0, import_ms2.default)("5m");
45929
- constructor(props) {
45930
- this.name = props.name;
45931
- if (props.description !== void 0) {
45932
- this.description = props.description;
45956
+ isDirty() {
45957
+ const currentKeys = Object.keys(this._tags).filter((k) => !isSystemTag(k)).sort();
45958
+ const initialKeys = Object.keys(this._initialTags).filter((k) => !isSystemTag(k)).sort();
45959
+ if (currentKeys.length !== initialKeys.length) {
45960
+ return true;
45933
45961
  }
45934
- this._inputSchema = props.input || z23.object({});
45935
- this._outputSchema = props.output || z23.object({});
45936
- this._stateSchema = props.state || z23.object({});
45937
- this._requestsSchemas = props.requests || {};
45938
- this._handler = props.handler;
45939
- this.schedule = props.schedule;
45940
- if (props.timeout) {
45941
- this.timeout = (0, import_ms2.default)(props.timeout);
45962
+ for (const key of currentKeys) {
45963
+ if (this._tags[key] !== this._initialTags[key]) {
45964
+ return true;
45965
+ }
45942
45966
  }
45967
+ return false;
45943
45968
  }
45944
- // @internal
45945
- get inputSchema() {
45946
- const schema = this._inputSchema ?? z23.object({}).passthrough();
45947
- return this.schedule ? schema.optional() : schema;
45948
- }
45949
- // @internal
45950
- get outputSchema() {
45951
- return this._outputSchema ?? z23.object({}).passthrough();
45969
+ get tags() {
45970
+ return new Proxy(this._tags, {
45971
+ set: (target, prop, value) => {
45972
+ if (isSystemTag(prop)) {
45973
+ return true;
45974
+ }
45975
+ target[prop] = value;
45976
+ return true;
45977
+ },
45978
+ deleteProperty: (target, prop) => {
45979
+ if (isSystemTag(prop)) {
45980
+ return true;
45981
+ }
45982
+ target[prop] = void 0;
45983
+ return true;
45984
+ }
45985
+ });
45952
45986
  }
45953
- // @internal
45954
- get stateSchema() {
45955
- return this._stateSchema ?? z23.object({}).passthrough();
45987
+ set tags(value) {
45988
+ this._tags = { ...value };
45956
45989
  }
45957
- /**
45958
- * Get the workflow definition for code generation
45959
- * @internal
45960
- */
45961
- getDefinition() {
45962
- return {
45963
- name: this.name,
45964
- type: Typings7.Primitive,
45965
- description: this.description,
45966
- input: this.inputSchema.toJSONSchema(),
45967
- output: this.outputSchema.toJSONSchema(),
45968
- state: this.stateSchema.toJSONSchema(),
45969
- schedule: this.schedule,
45970
- timeout: this.timeout
45971
- };
45990
+ async fetchTags() {
45991
+ try {
45992
+ if (this.type === "bot") {
45993
+ const { bot: bot2 } = await this.client.getBot({ id: this.id });
45994
+ return bot2.tags || {};
45995
+ } else if (this.type === "user") {
45996
+ const { user: user2 } = await this.client.getUser({ id: this.id });
45997
+ return user2.tags || {};
45998
+ } else if (this.type === "conversation") {
45999
+ const { conversation } = await this.client.getConversation({ id: this.id });
46000
+ return conversation.tags || {};
46001
+ } else if (this.type === "workflow") {
46002
+ const { workflow } = await this.client.getWorkflow({ id: this.id });
46003
+ return workflow.tags || {};
46004
+ }
46005
+ } catch (err) {
46006
+ console.error(`Failed to fetch tags for ${this.type}/${this.id}:`, err);
46007
+ }
46008
+ return {};
45972
46009
  }
45973
46010
  /**
45974
- * Get or create a workflow instance with the given key and input
45975
- *
45976
- * @param props.key - Optional unique key for workflow deduplication
45977
- * @param props.start - Whether to start the workflow immediately (default: true)
45978
- * @param props.input - The input data for the workflow
45979
- * @returns The workflow instance
46011
+ * Get the list of valid tag keys from the agent configuration.
46012
+ * Only tags defined in agent.config.ts can be persisted.
45980
46013
  */
45981
- async getOrCreate(props) {
45982
- const client2 = context2.get("client");
45983
- const statuses = props.statuses || ["pending", "in_progress", "listening", "paused"];
45984
- const validatedInput = this._inputSchema.parse(props.input);
45985
- const tags = {};
45986
- if (props.key) {
45987
- tags["key"] = props.key;
45988
- }
45989
- const discriminator = props.key ? ["key"] : void 0;
45990
- const createArgs = {
45991
- status: "pending",
45992
- name: this.name,
45993
- input: validatedInput,
45994
- tags,
45995
- conversationId: context2.get("conversation", { optional: true })?.id,
45996
- parentWorkflowId: context2.get("workflow", { optional: true })?.id,
45997
- timeoutAt: new Date(Date.now() + (this.timeout ?? (0, import_ms2.default)("5m"))).toISOString(),
45998
- ...discriminator && { discriminateBy: { tags: discriminator } }
45999
- };
46000
- let { workflow } = await client2._inner.getOrCreateWorkflow(createArgs);
46001
- if (props.key && !statuses.includes(workflow.status)) {
46002
- await client2._inner.deleteWorkflow({ id: workflow.id });
46003
- ({ workflow } = await client2._inner.getOrCreateWorkflow(createArgs));
46014
+ getValidTagKeys() {
46015
+ const validKeys = /* @__PURE__ */ new Set();
46016
+ try {
46017
+ const config = adk.project.config;
46018
+ if (this.type === "bot" && config.bot?.tags) {
46019
+ Object.keys(config.bot.tags).forEach((key) => validKeys.add(key));
46020
+ } else if (this.type === "user" && config.user?.tags) {
46021
+ Object.keys(config.user.tags).forEach((key) => validKeys.add(key));
46022
+ } else if (this.type === "conversation" && config.conversation?.tags) {
46023
+ Object.keys(config.conversation.tags).forEach((key) => validKeys.add(key));
46024
+ } else if (this.type === "workflow" && config.workflow?.tags) {
46025
+ Object.keys(config.workflow.tags).forEach((key) => validKeys.add(key));
46026
+ }
46027
+ } catch (err) {
46028
+ console.warn(`[TrackedTags] Could not load tag definitions from config: ${err}`);
46004
46029
  }
46005
- return await BaseWorkflowInstance.load({
46006
- id: workflow.id,
46007
- workflow
46008
- });
46030
+ return validKeys;
46009
46031
  }
46010
- /**
46011
- * Provide data in response to a workflow data request.
46012
- * Call this method from a conversation handler when you receive a WorkflowDataRequestEvent.
46013
- * @param event - The event object from the conversation handler
46014
- * @param data - The data to provide to the workflow
46015
- * @example
46016
- * if (isWorkflowDataRequest(event)) {
46017
- * await SomeWorkflow.provide(event, { orderId: "12345" });
46018
- * }
46019
- */
46020
- async provide(event, data) {
46021
- const client2 = context2.get("client");
46022
- const { workflowId, stepName } = event.payload;
46023
- const state = createWorkflowExecutionState(client2._inner, workflowId);
46024
- await state.load();
46025
- if (!state.value) {
46026
- throw new Error(`Workflow execution state not found for workflow ${workflowId}`);
46032
+ async persistTags(tags) {
46033
+ const validKeys = this.getValidTagKeys();
46034
+ const tagsForApi = {};
46035
+ const skippedTags = [];
46036
+ for (const [key, value] of Object.entries(tags)) {
46037
+ if (value === void 0 || isSystemTag(key)) {
46038
+ continue;
46039
+ }
46040
+ if (validKeys.size === 0 || validKeys.has(key)) {
46041
+ tagsForApi[key] = value;
46042
+ } else {
46043
+ skippedTags.push(key);
46044
+ delete this._tags[key];
46045
+ delete this._initialTags[key];
46046
+ }
46027
46047
  }
46028
- console.log(`Providing data to workflow ${workflowId} step ${stepName}`, data, stepName);
46029
- if (!state.value.steps[stepName]) {
46030
- state.value.steps[stepName] = {
46031
- output: data,
46032
- attempts: 0,
46033
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
46034
- finishedAt: (/* @__PURE__ */ new Date()).toISOString()
46035
- };
46036
- } else {
46037
- state.value.steps[stepName].output = data;
46038
- state.value.steps[stepName].finishedAt = (/* @__PURE__ */ new Date()).toISOString();
46048
+ if (skippedTags.length > 0) {
46049
+ console.warn(
46050
+ `[TrackedTags] Skipping tags not defined in agent.config.ts for ${this.type}/${this.id}: ${skippedTags.join(", ")}`
46051
+ );
46039
46052
  }
46040
- state.value.revision++;
46041
- await state.save();
46042
- await client2.createEvent({
46043
- type: WorkflowContinueEvent.name,
46044
- workflowId,
46045
- payload: {}
46046
- });
46047
- }
46048
- async start(input) {
46049
- const validatedInput = this._inputSchema.parse(input);
46050
- const client2 = context2.get("client");
46051
- const event = context2.get("event", { optional: true });
46052
- const workflow = context2.get("workflow", { optional: true });
46053
- const res = await client2._inner.createWorkflow({
46054
- name: this.name,
46055
- status: event ? "in_progress" : "pending",
46056
- eventId: event?.id,
46057
- input: validatedInput,
46058
- parentWorkflowId: workflow?.id,
46059
- conversationId: context2.get("conversation", { optional: true })?.id,
46060
- timeoutAt: new Date(Date.now() + (this.timeout ?? (0, import_ms2.default)("5m"))).toISOString()
46061
- });
46062
- return await BaseWorkflowInstance.load({
46063
- id: res.workflow.id,
46064
- workflow: res.workflow
46065
- });
46066
- }
46067
- /**
46068
- * Convert this workflow into an Autonomous.Tool that can be used with execute().
46069
- * Starts the workflow and returns basic information about the workflow instance.
46070
- *
46071
- * @param options.description - Optional description override for the tool
46072
- * @returns An Autonomous.Tool instance
46073
- *
46074
- * @example
46075
- * const tool = MyWorkflow.asTool()
46076
- *
46077
- * await execute({
46078
- * tools: [tool],
46079
- * instructions: 'Use the workflow when needed'
46080
- * })
46081
- */
46082
- asTool(options) {
46083
- const description = options?.description || this.description || `Starts the ${this.name} workflow`;
46084
- return new Autonomous.Tool({
46085
- name: this.name,
46086
- description,
46087
- input: this._inputSchema,
46088
- output: z23.object({
46089
- workflowId: z23.string().describe("The ID of the started workflow"),
46090
- status: z23.string().describe("The initial status of the workflow")
46091
- }),
46092
- handler: async (input) => {
46093
- const instance = await this.start(input);
46094
- return {
46095
- workflowId: instance.id,
46096
- status: instance.workflow.status
46097
- };
46053
+ try {
46054
+ if (this.type === "bot") {
46055
+ await this.client.updateBot({ id: this.id, tags: tagsForApi });
46056
+ } else if (this.type === "user") {
46057
+ await this.client.updateUser({ id: this.id, tags: tagsForApi });
46058
+ } else if (this.type === "conversation") {
46059
+ await this.client.updateConversation({ id: this.id, tags: tagsForApi });
46060
+ } else if (this.type === "workflow") {
46061
+ await this.client.updateWorkflow({ id: this.id, tags: tagsForApi });
46098
46062
  }
46099
- });
46063
+ } catch (err) {
46064
+ console.error(`Failed to persist tags for ${this.type}/${this.id}:`, err);
46065
+ throw err;
46066
+ }
46100
46067
  }
46101
46068
  };
46102
46069
  }
46103
46070
  });
46104
46071
 
46105
- // src/runtime/workflows/knowledge-indexing.ts
46106
- import { z as z24 } from "@botpress/sdk";
46107
- var KnowledgeIndexingWorkflow;
46108
- var init_knowledge_indexing = __esm({
46109
- "src/runtime/workflows/knowledge-indexing.ts"() {
46072
+ // src/runtime/heavy-imports.ts
46073
+ var HEAVY_IMPORTS, clearScheduledHeavyImports, importScheduledHeavyImports;
46074
+ var init_heavy_imports = __esm({
46075
+ "src/runtime/heavy-imports.ts"() {
46110
46076
  "use strict";
46111
46077
  init_define_BUILD();
46112
46078
  init_define_PACKAGE_VERSIONS();
46113
- init_workflow();
46114
- init_adk();
46115
- init_source_base();
46116
- KnowledgeIndexingWorkflow = new BaseWorkflow({
46117
- name: "builtin_knowledge_indexing",
46118
- description: "Built-in workflow to re-index all data sources in a knowledge base",
46119
- input: z24.object({
46120
- kbName: z24.string(),
46121
- kbId: z24.string(),
46122
- force: z24.boolean().optional().describe("Force re-indexing even if files haven't changed").default(false)
46123
- }),
46124
- timeout: "180m",
46125
- output: SyncOutput,
46126
- handler: async ({ input, step: step2 }) => {
46127
- const { kbName, kbId } = input;
46128
- const kb = adk.project.knowledge.find((x) => x.name === kbName);
46129
- if (!kb) {
46130
- throw new Error(`Knowledge base '${kbName}' not found`);
46079
+ init_context3();
46080
+ HEAVY_IMPORTS = {
46081
+ sdk: () => import("@botpress/sdk"),
46082
+ client: () => import("@botpress/client"),
46083
+ llmz: async () => {
46084
+ const llmz = await import("llmz");
46085
+ await llmz.init();
46086
+ }
46087
+ };
46088
+ clearScheduledHeavyImports = () => {
46089
+ context2.get("scheduledHeavyImports").clear();
46090
+ };
46091
+ importScheduledHeavyImports = async () => {
46092
+ const imports = Array.from(context2.get("scheduledHeavyImports"));
46093
+ clearScheduledHeavyImports();
46094
+ for (const key of imports) {
46095
+ try {
46096
+ void HEAVY_IMPORTS[key]?.().catch(() => {
46097
+ });
46098
+ } catch {
46131
46099
  }
46132
- const workflows = await step2.map(
46133
- "index-sources",
46134
- kb.sources,
46135
- async (source) => {
46136
- const workflowId = await step2(
46137
- "create-sync-workflow",
46138
- async () => await source.syncWorkflow.getOrCreate({
46139
- key: `${kbName}:${source.id}`,
46140
- statuses: ["in_progress", "listening", "pending", "paused"],
46141
- input: {
46142
- kbName,
46143
- kbId,
46144
- dsId: source.id,
46145
- force: input.force || false
46146
- }
46147
- }).then((x) => x.id)
46148
- );
46149
- return await step2.waitForWorkflow(source.id, workflowId).then((x) => x.output);
46150
- },
46151
- { concurrency: 10, maxAttempts: 1 }
46152
- );
46153
- return {
46154
- errors: workflows.flatMap((w) => w.errors || []),
46155
- processed: workflows.reduce((a, w) => a + (w.processed || 0), 0),
46156
- added: workflows.flatMap((w) => w.added || []),
46157
- updated: workflows.flatMap((w) => w.updated || []),
46158
- deleted: workflows.flatMap((w) => w.deleted || [])
46159
- };
46160
46100
  }
46161
- });
46101
+ };
46162
46102
  }
46163
46103
  });
46164
46104
 
46165
- // src/runtime/workflows/index.ts
46166
- var BuiltInWorkflows;
46167
- var init_workflows = __esm({
46168
- "src/runtime/workflows/index.ts"() {
46105
+ // src/runtime/context/inspector-handler.ts
46106
+ var init_inspector_handler = __esm({
46107
+ "src/runtime/context/inspector-handler.ts"() {
46169
46108
  "use strict";
46170
46109
  init_define_BUILD();
46171
46110
  init_define_PACKAGE_VERSIONS();
46172
- init_knowledge_indexing();
46173
- BuiltInWorkflows = {
46174
- KnowledgeIndexingWorkflow
46111
+ }
46112
+ });
46113
+
46114
+ // src/runtime/events.ts
46115
+ import { z as z24 } from "@botpress/sdk";
46116
+ var WorkflowCallbackEvent, WorkflowScheduleEvent, WorkflowContinueEvent, SubworkflowFinished, WorkflowDataRequestEvent;
46117
+ var init_events2 = __esm({
46118
+ "src/runtime/events.ts"() {
46119
+ "use strict";
46120
+ init_define_BUILD();
46121
+ init_define_PACKAGE_VERSIONS();
46122
+ WorkflowCallbackEvent = {
46123
+ name: "workflowCallback",
46124
+ schema: z24.object({
46125
+ workflow: z24.string(),
46126
+ workflowId: z24.string(),
46127
+ target: z24.union([
46128
+ z24.object({
46129
+ conversationId: z24.string()
46130
+ }),
46131
+ z24.object({
46132
+ workflowId: z24.string()
46133
+ })
46134
+ ]),
46135
+ status: z24.enum(["completed", "failed", "canceled", "timed_out"]),
46136
+ output: z24.any().optional(),
46137
+ error: z24.string().optional()
46138
+ })
46139
+ };
46140
+ WorkflowScheduleEvent = {
46141
+ name: "workflowSchedule",
46142
+ schema: z24.object({
46143
+ workflow: z24.string()
46144
+ })
46145
+ };
46146
+ WorkflowContinueEvent = {
46147
+ name: "workflowContinue",
46148
+ schema: z24.object({})
46149
+ };
46150
+ SubworkflowFinished = {
46151
+ name: "subworkflowFinished",
46152
+ schema: z24.object({})
46153
+ };
46154
+ WorkflowDataRequestEvent = {
46155
+ name: "workflowDataRequest",
46156
+ schema: z24.object({
46157
+ workflowId: z24.string(),
46158
+ workflowName: z24.string(),
46159
+ stepName: z24.string(),
46160
+ request: z24.string(),
46161
+ message: z24.string(),
46162
+ schema: z24.any()
46163
+ // JSON Schema
46164
+ })
46175
46165
  };
46176
46166
  }
46177
46167
  });
46178
46168
 
46179
- // src/runtime/actions/order-recompute-columns.ts
46180
- function orderRecomputeColumns(toRecompute, staleColumns, columns) {
46181
- const ordered = [];
46182
- const visited = /* @__PURE__ */ new Set();
46183
- function visit(colName) {
46184
- if (visited.has(colName)) return;
46185
- visited.add(colName);
46186
- const deps = columns[colName]?.dependencies || [];
46187
- for (const dep of deps) {
46188
- if (staleColumns.has(dep)) {
46189
- visit(dep);
46190
- }
46169
+ // src/runtime/context/handlers.ts
46170
+ import * as sdk from "@botpress/sdk";
46171
+ import { CitationsManager } from "llmz";
46172
+ import { Client as Client3 } from "@botpress/client";
46173
+ import { ulid as ulid2 } from "ulid";
46174
+ var init_handlers = __esm({
46175
+ "src/runtime/context/handlers.ts"() {
46176
+ "use strict";
46177
+ init_define_BUILD();
46178
+ init_define_PACKAGE_VERSIONS();
46179
+ init_cognitive();
46180
+ init_promises();
46181
+ init_context3();
46182
+ init_interfaces();
46183
+ init_http2();
46184
+ init_agent_registry();
46185
+ init_tracked_state();
46186
+ init_tracked_tags();
46187
+ init_tracing();
46188
+ init_heavy_imports();
46189
+ init_environment();
46190
+ init_inspector_handler();
46191
+ init_events2();
46192
+ }
46193
+ });
46194
+
46195
+ // src/runtime/chat/truncate-object.ts
46196
+ var init_truncate_object = __esm({
46197
+ "src/runtime/chat/truncate-object.ts"() {
46198
+ "use strict";
46199
+ init_define_BUILD();
46200
+ init_define_PACKAGE_VERSIONS();
46201
+ }
46202
+ });
46203
+
46204
+ // src/runtime/chat/truncate-transcript.ts
46205
+ var init_truncate_transcript = __esm({
46206
+ "src/runtime/chat/truncate-transcript.ts"() {
46207
+ "use strict";
46208
+ init_define_BUILD();
46209
+ init_define_PACKAGE_VERSIONS();
46210
+ init_truncate_object();
46211
+ }
46212
+ });
46213
+
46214
+ // src/runtime/chat/html.ts
46215
+ var HTML_TAGS;
46216
+ var init_html = __esm({
46217
+ "src/runtime/chat/html.ts"() {
46218
+ "use strict";
46219
+ init_define_BUILD();
46220
+ init_define_PACKAGE_VERSIONS();
46221
+ HTML_TAGS = [
46222
+ "html",
46223
+ "head",
46224
+ "body",
46225
+ "div",
46226
+ "span",
46227
+ "a",
46228
+ "img",
46229
+ "video",
46230
+ "audio",
46231
+ "source",
46232
+ "button",
46233
+ "input",
46234
+ "form",
46235
+ "label",
46236
+ "select",
46237
+ "option",
46238
+ "textarea",
46239
+ "table",
46240
+ "tr",
46241
+ "td",
46242
+ "th",
46243
+ "thead",
46244
+ "tbody",
46245
+ "tfoot",
46246
+ "ul",
46247
+ "ol",
46248
+ "li",
46249
+ "h1",
46250
+ "h2",
46251
+ "h3",
46252
+ "h4",
46253
+ "h5",
46254
+ "h6",
46255
+ "p",
46256
+ "br",
46257
+ "hr",
46258
+ "b",
46259
+ "strong",
46260
+ "i",
46261
+ "em",
46262
+ "u",
46263
+ "s",
46264
+ "strike",
46265
+ "pre",
46266
+ "code",
46267
+ "blockquote",
46268
+ "cite",
46269
+ "q",
46270
+ "abbr",
46271
+ "acronym",
46272
+ "address",
46273
+ "del",
46274
+ "ins",
46275
+ "sub",
46276
+ "sup",
46277
+ "small",
46278
+ "big",
46279
+ "tt",
46280
+ "dfn",
46281
+ "kbd",
46282
+ "samp",
46283
+ "var",
46284
+ "mark",
46285
+ "ruby",
46286
+ "rt",
46287
+ "rp",
46288
+ "bdi",
46289
+ "bdo",
46290
+ "wbr",
46291
+ "details",
46292
+ "summary",
46293
+ "menu",
46294
+ "menuitem",
46295
+ "menuitem",
46296
+ "figure",
46297
+ "figcaption",
46298
+ "main",
46299
+ "article",
46300
+ "section",
46301
+ "aside",
46302
+ "header",
46303
+ "footer",
46304
+ "nav",
46305
+ "dialog",
46306
+ "meter",
46307
+ "progress",
46308
+ "canvas",
46309
+ "svg",
46310
+ "math",
46311
+ "iframe",
46312
+ "embed",
46313
+ "object",
46314
+ "param",
46315
+ "source",
46316
+ "track",
46317
+ "area",
46318
+ "map",
46319
+ "iframe",
46320
+ "frame",
46321
+ "frameset",
46322
+ "noframes",
46323
+ "noscript",
46324
+ "style",
46325
+ "link",
46326
+ "meta",
46327
+ "title",
46328
+ "base",
46329
+ "script",
46330
+ "noscript",
46331
+ "template"
46332
+ ];
46333
+ }
46334
+ });
46335
+
46336
+ // src/runtime/chat/messages.ts
46337
+ import { z as z25 } from "@bpinternal/zui";
46338
+ import { isAnyComponent } from "llmz";
46339
+ function joinMarkdownChildren(children, stringify3 = (el) => JSON.stringify(el, null, 2)) {
46340
+ return children.reduce((acc, child, idx) => {
46341
+ const isPrimitive = typeof child === "string" || typeof child === "number" || typeof child === "boolean";
46342
+ const str = isPrimitive ? child?.toString() ?? "" : stringify3(child) ?? "";
46343
+ if (str.trim().length === 0) {
46344
+ return acc;
46191
46345
  }
46192
- if (staleColumns.has(colName) || toRecompute.includes(colName)) {
46193
- ordered.push(colName);
46346
+ const leftSymbols = '*_~`"[({-'.split("");
46347
+ const rightSymbols = '*_~`"])}-!'.split("");
46348
+ const last = idx > 0 && acc.at(-1) && typeof acc.at(-1) === "string" ? acc.at(-1) : "";
46349
+ const endsWithSpace = last && last.trimEnd() !== last;
46350
+ let prev = idx === 0 || endsWithSpace || last.length && leftSymbols.includes(last.at(-1)) ? "" : " ";
46351
+ if (str.trimStart() !== str || str.length && rightSymbols.includes(str.at(0))) {
46352
+ prev = "";
46194
46353
  }
46354
+ return [...acc, prev, str];
46355
+ }, []).join("").trim();
46356
+ }
46357
+ function rebuildTSXCode(node, hasParent = false) {
46358
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
46359
+ return node?.toString() ?? "";
46195
46360
  }
46196
- for (const col of toRecompute) {
46197
- visit(col);
46361
+ if (typeof node === "undefined" || node === null || typeof node === "function" || typeof node === "symbol" || typeof node === "boolean") {
46362
+ return "";
46198
46363
  }
46199
- return ordered;
46200
- }
46201
- var init_order_recompute_columns = __esm({
46202
- "src/runtime/actions/order-recompute-columns.ts"() {
46203
- "use strict";
46204
- init_define_BUILD();
46205
- init_define_PACKAGE_VERSIONS();
46364
+ let { type = "", props = {}, children = [] } = node;
46365
+ if (HTML_TAGS.includes(type.toLowerCase())) {
46366
+ type = type.toLowerCase();
46206
46367
  }
46207
- });
46208
-
46209
- // src/runtime/actions/computed-columns.ts
46210
- import { z as z25 } from "@botpress/sdk";
46211
- var tablesRecomputeRows;
46212
- var init_computed_columns = __esm({
46213
- "src/runtime/actions/computed-columns.ts"() {
46368
+ let openTag = `<${type}`;
46369
+ Object.entries(props).forEach(([k, v]) => {
46370
+ openTag += ` ${k}={${JSON.stringify(v)}}`;
46371
+ });
46372
+ openTag += ">";
46373
+ const inner = children.map((child) => rebuildTSXCode(child, true)).join("");
46374
+ const closeTag = `</${type}>`;
46375
+ if (hasParent) {
46376
+ return `${openTag}${inner}${closeTag}`;
46377
+ }
46378
+ return `
46379
+ \`\`\`
46380
+ ${openTag}${inner}${closeTag}
46381
+ \`\`\``;
46382
+ }
46383
+ var Message;
46384
+ var init_messages = __esm({
46385
+ "src/runtime/chat/messages.ts"() {
46214
46386
  "use strict";
46215
46387
  init_define_BUILD();
46216
46388
  init_define_PACKAGE_VERSIONS();
46217
- init_action();
46218
- init_adk();
46219
- init_order_recompute_columns();
46220
- init_runtime();
46221
- tablesRecomputeRows = new BaseAction({
46222
- name: "tablesRecomputeRows",
46223
- // skynet/packages/tables-api/src/services/computed/compute-stale-rows.ts
46224
- input: z25.object({
46225
- tableId: z25.string(),
46226
- botId: z25.string(),
46227
- schema: z25.any(),
46228
- requests: z25.array(
46229
- z25.object({
46230
- row: z25.record(z25.any()),
46231
- columnsToRecompute: z25.array(z25.string())
46232
- })
46233
- )
46234
- }),
46235
- output: z25.object({
46236
- isFinished: z25.boolean(),
46237
- rows: z25.array(z25.any())
46238
- }),
46239
- handler: async ({ input, client: client2 }) => {
46240
- const { tableId, requests } = input;
46241
- const { table: remoteTable } = await client2._inner.getTable({ table: tableId });
46242
- const table = adk.project.tables.find((x) => x.name === remoteTable.name);
46243
- async function computeRow(row, columnsToRecompute) {
46244
- const newRow = { id: row.id };
46245
- const recompute = orderRecomputeColumns(
46246
- columnsToRecompute,
46247
- new Set(row.stale ?? []),
46248
- table?.columns || {}
46249
- );
46250
- for (const colName of recompute) {
46251
- const col = table?.columns[colName];
46252
- if (!col || !col.computed) {
46253
- newRow[colName] = { status: "error", error: "Column not found or not computed" };
46254
- continue;
46255
- }
46256
- const value = await col.value(row);
46257
- row[colName] = value;
46258
- newRow[colName] = {
46259
- status: "computed",
46260
- value
46261
- };
46262
- }
46263
- return newRow;
46264
- }
46265
- const MIN_REMAINING_TIME_MS = 5e3;
46266
- const BUFFER_TIME_MS = 5e3;
46267
- let recomputed = [];
46268
- let isFinished = true;
46269
- const remainingTime = context2.get("runtime").getRemainingExecutionTimeInMs();
46270
- if (remainingTime && remainingTime < MIN_REMAINING_TIME_MS) {
46271
- return { isFinished: false, rows: [] };
46272
- }
46273
- const timeoutPromise = new Promise((resolve) => {
46274
- setTimeout(() => {
46275
- isFinished = false;
46276
- resolve();
46277
- }, remainingTime - BUFFER_TIME_MS);
46278
- });
46279
- const allRowsPromise = Promise.all(
46280
- requests.map(async (r) => {
46281
- const computedRow = await computeRow(r.row, r.columnsToRecompute);
46282
- recomputed.push(computedRow);
46283
- })
46284
- );
46285
- await Promise.race([timeoutPromise, allRowsPromise]);
46286
- return { isFinished, rows: recomputed };
46287
- }
46389
+ init_html();
46390
+ Message = z25.object({
46391
+ __jsx: z25.literal(true),
46392
+ type: z25.literal("MESSAGE"),
46393
+ props: z25.object({
46394
+ type: z25.enum(["error", "info", "success", "prompt"]).default("info").catch(() => "info")
46395
+ }).passthrough(),
46396
+ children: z25.array(z25.any()).default([]).transform((children) => {
46397
+ children = children.map((child) => Array.isArray(child) ? child : [child]).flat();
46398
+ const text = joinMarkdownChildren(
46399
+ children.filter((x) => !isAnyComponent(x)).map((x) => rebuildTSXCode(x, false))
46400
+ ).trim();
46401
+ const components = children.filter((child) => isAnyComponent(child));
46402
+ return [text, ...components];
46403
+ })
46288
46404
  });
46289
46405
  }
46290
46406
  });
46291
46407
 
46292
- // src/runtime/actions/index.ts
46293
- var BuiltInActions;
46294
- var init_actions2 = __esm({
46295
- "src/runtime/actions/index.ts"() {
46296
- "use strict";
46297
- init_define_BUILD();
46298
- init_define_PACKAGE_VERSIONS();
46299
- init_computed_columns();
46300
- BuiltInActions = {
46301
- tablesRecomputeRows
46302
- };
46408
+ // ../../node_modules/dedent/dist/dedent.mjs
46409
+ function ownKeys(object, enumerableOnly) {
46410
+ var keys = Object.keys(object);
46411
+ if (Object.getOwnPropertySymbols) {
46412
+ var symbols = Object.getOwnPropertySymbols(object);
46413
+ enumerableOnly && (symbols = symbols.filter(function(sym) {
46414
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
46415
+ })), keys.push.apply(keys, symbols);
46303
46416
  }
46304
- });
46305
-
46306
- // src/runtime/adk.ts
46307
- var adk_exports = {};
46308
- __export(adk_exports, {
46309
- adk: () => adk,
46310
- initialize: () => initialize,
46311
- register: () => register,
46312
- registerIntegration: () => registerIntegration
46313
- });
46314
- import { BotSpecificClient as BotSpecificClient2 } from "@botpress/sdk";
46315
- import { Zai as Zai2 } from "@botpress/zai";
46316
- import { Cognitive as Cognitive3 } from "@botpress/cognitive";
46317
- import { Client as Client3 } from "@botpress/client";
46318
- function getStandaloneCognitive() {
46319
- return getSingleton("__ADK_GLOBAL_STANDALONE_COGNITIVE", () => {
46320
- const token = process.env.BP_TOKEN || process.env.ADK_TOKEN;
46321
- if (!token) {
46322
- throw new Error(
46323
- 'No token found. Set BP_TOKEN or ADK_TOKEN environment variable, or run this script using "adk run".'
46324
- );
46325
- }
46326
- const botId = process.env.ADK_BOT_ID;
46327
- if (!botId) {
46328
- throw new Error('No bot ID found. Set ADK_BOT_ID environment variable, or run this script using "adk run".');
46329
- }
46330
- const apiUrl = process.env.ADK_API_URL || "https://api.botpress.cloud";
46331
- const vanillaClient = new Client3({
46332
- token,
46333
- apiUrl,
46334
- botId
46335
- });
46336
- const botClient = new BotSpecificClient2(vanillaClient);
46337
- return new Cognitive3({
46338
- client: botClient,
46339
- __experimental_beta: true
46417
+ return keys;
46418
+ }
46419
+ function _objectSpread(target) {
46420
+ for (var i = 1; i < arguments.length; i++) {
46421
+ var source = null != arguments[i] ? arguments[i] : {};
46422
+ i % 2 ? ownKeys(Object(source), true).forEach(function(key) {
46423
+ _defineProperty(target, key, source[key]);
46424
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
46425
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
46340
46426
  });
46341
- });
46427
+ }
46428
+ return target;
46342
46429
  }
46343
- function initialize(options) {
46344
- const state = getState();
46345
- if (state.initialized) {
46346
- throw new Error("ADK API already initialized");
46430
+ function _defineProperty(obj, key, value) {
46431
+ key = _toPropertyKey(key);
46432
+ if (key in obj) {
46433
+ Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
46434
+ } else {
46435
+ obj[key] = value;
46347
46436
  }
46348
- state.projectConfig = options.config;
46349
- state.initialized = true;
46350
- state.primitives.workflows.push(...Object.values(BuiltInWorkflows));
46351
- state.primitives.actions.push(...Object.values(BuiltInActions));
46437
+ return obj;
46352
46438
  }
46353
- function register(...primitives) {
46354
- const state = getState();
46355
- if (!state.initialized) {
46356
- throw new Error("ADK API not initialized. Call initialize() first.");
46439
+ function _toPropertyKey(arg) {
46440
+ var key = _toPrimitive(arg, "string");
46441
+ return typeof key === "symbol" ? key : String(key);
46442
+ }
46443
+ function _toPrimitive(input, hint) {
46444
+ if (typeof input !== "object" || input === null) return input;
46445
+ var prim = input[Symbol.toPrimitive];
46446
+ if (prim !== void 0) {
46447
+ var res = prim.call(input, hint || "default");
46448
+ if (typeof res !== "object") return res;
46449
+ throw new TypeError("@@toPrimitive must return a primitive value.");
46357
46450
  }
46358
- for (const primitive of primitives) {
46359
- const definition = primitive.getDefinition();
46360
- switch (definition.type) {
46361
- case "action":
46362
- state.primitives.actions.push(primitive);
46363
- break;
46364
- case "conversation":
46365
- state.primitives.conversations.push(primitive);
46366
- break;
46367
- case "knowledge":
46368
- state.primitives.knowledge.push(primitive);
46369
- for (const source of definition.sources) {
46370
- state.primitives.workflows.push(source.syncWorkflow);
46451
+ return (hint === "string" ? String : Number)(input);
46452
+ }
46453
+ function createDedent(options) {
46454
+ dedent2.withOptions = (newOptions) => createDedent(_objectSpread(_objectSpread({}, options), newOptions));
46455
+ return dedent2;
46456
+ function dedent2(strings, ...values) {
46457
+ const raw = typeof strings === "string" ? [strings] : strings.raw;
46458
+ const {
46459
+ alignValues = false,
46460
+ escapeSpecialCharacters = Array.isArray(strings),
46461
+ trimWhitespace = true
46462
+ } = options;
46463
+ let result = "";
46464
+ for (let i = 0; i < raw.length; i++) {
46465
+ let next = raw[i];
46466
+ if (escapeSpecialCharacters) {
46467
+ next = next.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{");
46468
+ }
46469
+ result += next;
46470
+ if (i < values.length) {
46471
+ const value = alignValues ? alignValue(values[i], result) : values[i];
46472
+ result += value;
46473
+ }
46474
+ }
46475
+ const lines = result.split("\n");
46476
+ let mindent = null;
46477
+ for (const l of lines) {
46478
+ const m = l.match(/^(\s+)\S+/);
46479
+ if (m) {
46480
+ const indent = m[1].length;
46481
+ if (!mindent) {
46482
+ mindent = indent;
46483
+ } else {
46484
+ mindent = Math.min(mindent, indent);
46371
46485
  }
46372
- break;
46373
- case "table":
46374
- state.primitives.tables.push(primitive);
46375
- break;
46376
- case "trigger":
46377
- state.primitives.triggers.push(primitive);
46378
- break;
46379
- case "workflow":
46380
- state.primitives.workflows.push(primitive);
46381
- break;
46486
+ }
46487
+ }
46488
+ if (mindent !== null) {
46489
+ const m = mindent;
46490
+ result = lines.map((l) => l[0] === " " || l[0] === " " ? l.slice(m) : l).join("\n");
46491
+ }
46492
+ if (trimWhitespace) {
46493
+ result = result.trim();
46382
46494
  }
46495
+ if (escapeSpecialCharacters) {
46496
+ result = result.replace(/\\n/g, "\n");
46497
+ }
46498
+ if (typeof Bun !== "undefined") {
46499
+ result = result.replace(
46500
+ // Matches e.g. \\u{1f60a} or \\u5F1F
46501
+ /\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,
46502
+ (_2, braced, unbraced) => {
46503
+ var _ref;
46504
+ const hex = (_ref = braced !== null && braced !== void 0 ? braced : unbraced) !== null && _ref !== void 0 ? _ref : "";
46505
+ return String.fromCodePoint(parseInt(hex, 16));
46506
+ }
46507
+ );
46508
+ }
46509
+ return result;
46383
46510
  }
46384
46511
  }
46385
- function registerIntegration(props) {
46386
- const state = getState();
46387
- if (!state.initialized) {
46388
- throw new Error("ADK API not initialized. Call initialize() first.");
46512
+ function alignValue(value, precedingText) {
46513
+ if (typeof value !== "string" || !value.includes("\n")) {
46514
+ return value;
46389
46515
  }
46390
- state.primitives.integrations.push({
46391
- alias: props.alias,
46392
- definition: props.definition,
46393
- get actions() {
46394
- return actions[props.alias];
46395
- }
46396
- });
46516
+ const currentLine = precedingText.slice(precedingText.lastIndexOf("\n") + 1);
46517
+ const indentMatch = currentLine.match(/^(\s+)/);
46518
+ if (indentMatch) {
46519
+ const indent = indentMatch[1];
46520
+ return value.replace(/\n/g, `
46521
+ ${indent}`);
46522
+ }
46523
+ return value;
46397
46524
  }
46398
- var getState, adk;
46399
- var init_adk = __esm({
46400
- "src/runtime/adk.ts"() {
46401
- "use strict";
46525
+ var dedent;
46526
+ var init_dedent = __esm({
46527
+ "../../node_modules/dedent/dist/dedent.mjs"() {
46402
46528
  init_define_BUILD();
46403
46529
  init_define_PACKAGE_VERSIONS();
46404
- init_singletons();
46405
- init_environment();
46406
- init_actions();
46407
- init_workflows();
46408
- init_library();
46409
- init_actions2();
46410
- getState = () => getSingleton("__ADK_GLOBAL_PROJECT", () => {
46411
- const state = {
46412
- initialized: false,
46413
- primitives: {
46414
- integrations: [],
46415
- actions: [],
46416
- knowledge: [],
46417
- tables: [],
46418
- workflows: [],
46419
- conversations: [],
46420
- triggers: []
46421
- }
46422
- };
46423
- return state;
46424
- });
46425
- adk = {
46426
- get environment() {
46427
- return Environment;
46428
- },
46429
- get zai() {
46430
- const contextCognitive = context2.get("cognitive", { optional: true });
46431
- const cognitive = contextCognitive ?? getStandaloneCognitive();
46432
- return new Zai2({
46433
- client: cognitive,
46434
- modelId: Array.isArray(adk.project.config.defaultModels.zai) ? adk.project.config.defaultModels.zai[0] ?? "auto" : adk.project.config.defaultModels.zai
46435
- });
46436
- },
46437
- get project() {
46438
- const state = getState();
46439
- if (!state.initialized || !state.projectConfig) {
46440
- throw new Error("ADK API not initialized");
46441
- }
46442
- return {
46443
- config: state.projectConfig,
46444
- integrations: Object.assign(state.primitives.integrations, {
46445
- get(name) {
46446
- const byAlias = state.primitives.integrations.find((int) => int.alias === name);
46447
- const byName = state.primitives.integrations.find((int) => int.definition.name === name);
46448
- return byAlias || byName;
46449
- }
46450
- }),
46451
- actions: state.primitives.actions,
46452
- knowledge: state.primitives.knowledge,
46453
- tables: state.primitives.tables,
46454
- workflows: state.primitives.workflows,
46455
- conversations: state.primitives.conversations,
46456
- triggers: state.primitives.triggers
46457
- };
46458
- },
46459
- async execute(props) {
46460
- const contextCognitive = context2.get("cognitive", { optional: true });
46461
- const cognitive = contextCognitive ?? getStandaloneCognitive();
46462
- const defaultModel = adk.project.config.defaultModels.autonomous;
46463
- const { execute: llmz_execute, getValue: getValue2 } = await import("llmz");
46464
- return llmz_execute({
46465
- client: cognitive,
46466
- instructions: props.instructions,
46467
- ...props.tools && { tools: props.tools },
46468
- ...props.objects && { objects: props.objects },
46469
- ...props.exits && { exits: props.exits },
46470
- ...props.signal && { signal: props.signal },
46471
- temperature: async (ctx) => props.temperature ? await getValue2(props.temperature, ctx) : 0.7,
46472
- model: async (ctx) => props.model ? await getValue2(props.model, ctx) : defaultModel,
46473
- options: { loop: props.iterations ?? 10 },
46474
- ...props.hooks?.onTrace && { onTrace: props.hooks.onTrace },
46475
- ...props.hooks?.onIterationEnd && { onIterationEnd: props.hooks.onIterationEnd },
46476
- ...props.hooks?.onBeforeTool && { onBeforeTool: props.hooks.onBeforeTool },
46477
- ...props.hooks?.onAfterTool && { onAfterTool: props.hooks.onAfterTool },
46478
- ...props.hooks?.onBeforeExecution && { onBeforeExecution: props.hooks.onBeforeExecution },
46479
- ...props.hooks?.onExit && { onExit: props.hooks.onExit }
46480
- });
46481
- }
46482
- };
46530
+ dedent = createDedent({});
46483
46531
  }
46484
46532
  });
46485
46533
 
@@ -46806,7 +46854,7 @@ var init_chat = __esm({
46806
46854
  init_messages();
46807
46855
  init_dedent();
46808
46856
  init_tracing();
46809
- init_events2();
46857
+ init_events();
46810
46858
  init_adk();
46811
46859
  init_config();
46812
46860
  init_components();
@@ -46946,7 +46994,7 @@ var init_runtime2 = __esm({
46946
46994
  init_tracked_state_schema();
46947
46995
  init_tracked_tags();
46948
46996
  init_actions();
46949
- init_events();
46997
+ init_events2();
46950
46998
  init_client();
46951
46999
  }
46952
47000
  });
@@ -48044,7 +48092,7 @@ var init_state_references = __esm({
48044
48092
  // src/runtime/tracked-state.ts
48045
48093
  import { z as z27 } from "@botpress/sdk";
48046
48094
  import { createHash } from "crypto";
48047
- var import_bytes2, import_object_sizeof2, EMPTY_STATE, MAX_SWAP_FILE_SIZE, BUILT_IN_STATES, TrackedState, parseState;
48095
+ var import_bytes2, import_object_sizeof2, EMPTY_STATE, MAX_SWAP_FILE_SIZE, BUILT_IN_STATES, TrackedState2, parseState;
48048
48096
  var init_tracked_state = __esm({
48049
48097
  "src/runtime/tracked-state.ts"() {
48050
48098
  "use strict";
@@ -48079,7 +48127,7 @@ var init_tracked_state = __esm({
48079
48127
  /** Data source metadata for dashboard visibility */
48080
48128
  dsData: "dsData"
48081
48129
  };
48082
- TrackedState = class _TrackedState {
48130
+ TrackedState2 = class _TrackedState {
48083
48131
  type;
48084
48132
  id;
48085
48133
  name;
@@ -48232,7 +48280,8 @@ var init_tracked_state = __esm({
48232
48280
  } else {
48233
48281
  this.value = value;
48234
48282
  }
48235
- if (this.value == null || this.value === void 0) {
48283
+ const needsDefaults = this.value == null || this.value === void 0;
48284
+ if (needsDefaults) {
48236
48285
  if (this.state && "parse" in this.state) {
48237
48286
  try {
48238
48287
  this.value = this.state.parse({});
@@ -48429,7 +48478,7 @@ init_define_PACKAGE_VERSIONS();
48429
48478
  init_transcript();
48430
48479
  init_tracked_state_schema();
48431
48480
  init_tracked_state();
48432
- init_events();
48481
+ init_events2();
48433
48482
  export {
48434
48483
  BUILT_IN_STATES,
48435
48484
  SubworkflowFinished,