@automagik/omni 2.260906.3 → 2.260906.4

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.
@@ -207,6 +207,19 @@ var init_types2 = __esm(() => {
207
207
  "flow.data_exchange"
208
208
  ];
209
209
  });
210
+ // ../core/src/events/causality.ts
211
+ import { AsyncLocalStorage } from "async_hooks";
212
+ function runWithEventCausality(context2, fn) {
213
+ return storage.run(context2, fn);
214
+ }
215
+ function currentEventCausality() {
216
+ return storage.getStore();
217
+ }
218
+ var storage;
219
+ var init_causality = __esm(() => {
220
+ storage = new AsyncLocalStorage;
221
+ });
222
+
210
223
  // ../core/src/events/envelope.ts
211
224
  function classifyEnvelope(metadata) {
212
225
  if (metadata === null || metadata === undefined)
@@ -18232,6 +18245,38 @@ var init_logger = __esm(() => {
18232
18245
  rootLogger = createLogger("system");
18233
18246
  });
18234
18247
 
18248
+ // ../core/src/events/factory.ts
18249
+ function createOmniEvent(type, payload, metadata, serviceName) {
18250
+ const eventId = crypto.randomUUID();
18251
+ const timestamp = Date.now();
18252
+ const tenantId = resolvePublishTenantId(metadata?.tenantId, metadata?.instanceId);
18253
+ const ambient = currentEventCausality();
18254
+ const causationId = metadata?.causationId ?? ambient?.causationId;
18255
+ return {
18256
+ id: eventId,
18257
+ type,
18258
+ payload,
18259
+ timestamp,
18260
+ metadata: {
18261
+ correlationId: metadata?.correlationId ?? ambient?.correlationId ?? eventId,
18262
+ ...causationId ? { causationId } : {},
18263
+ instanceId: metadata?.instanceId,
18264
+ channelType: metadata?.channelType,
18265
+ personId: metadata?.personId,
18266
+ platformIdentityId: metadata?.platformIdentityId,
18267
+ traceId: metadata?.traceId ?? eventId,
18268
+ source: metadata?.source ?? serviceName,
18269
+ ingestMode: metadata?.ingestMode,
18270
+ timings: metadata?.timings,
18271
+ ...tenantId ? { envelopeVersion: CURRENT_ENVELOPE_VERSION, tenantId } : {}
18272
+ }
18273
+ };
18274
+ }
18275
+ var init_factory = __esm(() => {
18276
+ init_causality();
18277
+ init_envelope();
18278
+ });
18279
+
18235
18280
  // ../core/src/events/nats/streams.ts
18236
18281
  function getStreamForEventType(eventType) {
18237
18282
  const prefix = eventType.split(".")[0] ?? "";
@@ -23004,27 +23049,8 @@ class NatsEventBus {
23004
23049
  }
23005
23050
  async publishInternal(type, payload, metadata) {
23006
23051
  await this.ensureConnected();
23007
- const eventId = crypto.randomUUID();
23008
- const timestamp = Date.now();
23009
- const tenantId = resolvePublishTenantId(metadata?.tenantId, metadata?.instanceId);
23010
- const event = {
23011
- id: eventId,
23012
- type,
23013
- payload,
23014
- timestamp,
23015
- metadata: {
23016
- correlationId: metadata?.correlationId ?? eventId,
23017
- instanceId: metadata?.instanceId,
23018
- channelType: metadata?.channelType,
23019
- personId: metadata?.personId,
23020
- platformIdentityId: metadata?.platformIdentityId,
23021
- traceId: metadata?.traceId ?? eventId,
23022
- source: metadata?.source ?? this.config.serviceName,
23023
- ingestMode: metadata?.ingestMode,
23024
- timings: metadata?.timings,
23025
- ...tenantId ? { envelopeVersion: CURRENT_ENVELOPE_VERSION, tenantId } : {}
23026
- }
23027
- };
23052
+ const event = createOmniEvent(type, payload, metadata, this.config.serviceName);
23053
+ const eventId = event.id;
23028
23054
  let subject;
23029
23055
  if (metadata?.channelType && metadata?.instanceId) {
23030
23056
  subject = buildSubject(type, metadata.channelType, metadata.instanceId);
@@ -23300,7 +23326,7 @@ async function connectEventBus(config2) {
23300
23326
  var import_api2, import_nats, log4, DEFAULTS, ENSURE_CONNECTED_WAIT_MS = 5000;
23301
23327
  var init_client = __esm(() => {
23302
23328
  init_logger();
23303
- init_envelope();
23329
+ init_factory();
23304
23330
  init_consumer();
23305
23331
  init_registry();
23306
23332
  init_streams();
@@ -31293,6 +31319,7 @@ function estimateCompletion(progress) {
31293
31319
  // ../core/src/events/index.ts
31294
31320
  var init_events = __esm(() => {
31295
31321
  init_types2();
31322
+ init_causality();
31296
31323
  init_envelope();
31297
31324
  init_nats();
31298
31325
  init_dead_letter();
@@ -36972,13 +36999,7 @@ function resolveFollowUpValue(trimmed, followUp) {
36972
36999
  return;
36973
37000
  }
36974
37001
  }
36975
- function resolveTemplatePath(path, context2) {
36976
- const trimmed = path.trim();
36977
- if (!trimmed)
36978
- return;
36979
- const parts = trimmed.split(".");
36980
- const root = parts[0] ?? "";
36981
- const rest = parts.slice(1).join(".");
37002
+ function resolveSpecialValue(trimmed, root, rest, context2) {
36982
37003
  if (context2.debounce) {
36983
37004
  const debounceValue = resolveDebounceValue(trimmed, rest, context2.debounce);
36984
37005
  if (debounceValue !== undefined)
@@ -36989,6 +37010,21 @@ function resolveTemplatePath(path, context2) {
36989
37010
  if (followUpValue !== undefined)
36990
37011
  return followUpValue;
36991
37012
  }
37013
+ if (root === "event" && context2.event) {
37014
+ return rest ? getNestedValue(context2.event, rest) : context2.event;
37015
+ }
37016
+ return;
37017
+ }
37018
+ function resolveTemplatePath(path, context2) {
37019
+ const trimmed = path.trim();
37020
+ if (!trimmed)
37021
+ return;
37022
+ const parts = trimmed.split(".");
37023
+ const root = parts[0] ?? "";
37024
+ const rest = parts.slice(1).join(".");
37025
+ const specialValue = resolveSpecialValue(trimmed, root, rest, context2);
37026
+ if (specialValue !== undefined)
37027
+ return specialValue;
36992
37028
  if (root === "payload")
36993
37029
  return rest ? getNestedValue(context2.payload, rest) : context2.payload;
36994
37030
  if (root === "env")
@@ -37070,7 +37106,9 @@ function createTemplateContext(payload, options = {}) {
37070
37106
  variables: options.variables ?? {},
37071
37107
  env: process.env,
37072
37108
  debounce: options.debounce,
37073
- followUp
37109
+ followUp,
37110
+ event: options.event,
37111
+ automation: options.automation
37074
37112
  };
37075
37113
  }
37076
37114
  var TEMPLATE_REGEX;
@@ -37642,8 +37680,12 @@ var init_egress = __esm(() => {
37642
37680
  });
37643
37681
 
37644
37682
  // ../core/src/automations/actions.ts
37645
- function buildWebhookHeaders(config2, context2) {
37683
+ function buildWebhookHeaders(config2, context2, actionIndex) {
37646
37684
  const headers = { "Content-Type": "application/json" };
37685
+ if (context2.event) {
37686
+ headers["X-Omni-Event-Id"] = context2.event.id;
37687
+ headers["X-Omni-Delivery-Id"] = `${context2.event.id}:${context2.automation?.id ?? "manual"}:${actionIndex}`;
37688
+ }
37647
37689
  if (config2.headers) {
37648
37690
  for (const [key, value] of Object.entries(config2.headers)) {
37649
37691
  headers[key] = substituteTemplate(value, context2);
@@ -37651,16 +37693,28 @@ function buildWebhookHeaders(config2, context2) {
37651
37693
  }
37652
37694
  return headers;
37653
37695
  }
37696
+ function buildDefaultWebhookBody(config2, context2) {
37697
+ if (context2.event && config2.includeEnvelope !== false) {
37698
+ return JSON.stringify({
37699
+ id: context2.event.id,
37700
+ type: context2.event.type,
37701
+ payload: context2.payload,
37702
+ metadata: context2.event.metadata,
37703
+ timestamp: context2.event.timestamp
37704
+ });
37705
+ }
37706
+ return JSON.stringify(context2.payload);
37707
+ }
37654
37708
  async function parseWebhookResponse(response) {
37655
37709
  const contentType = response.headers.get("content-type") ?? "";
37656
37710
  return contentType.includes("application/json") ? response.json() : response.text();
37657
37711
  }
37658
- async function executeWebhookAction(config2, context2, _deps, trustedTenantId) {
37712
+ async function executeWebhookAction(config2, context2, _deps, trustedTenantId, actionIndex = 0) {
37659
37713
  try {
37660
37714
  const url = substituteTemplate(config2.url, context2);
37661
37715
  const method = config2.method ?? "POST";
37662
- const headers = buildWebhookHeaders(config2, context2);
37663
- const body = config2.bodyTemplate ? substituteTemplate(config2.bodyTemplate, context2) : JSON.stringify(context2.payload);
37716
+ const headers = buildWebhookHeaders(config2, context2, actionIndex);
37717
+ const body = config2.bodyTemplate ? substituteTemplate(config2.bodyTemplate, context2) : buildDefaultWebhookBody(config2, context2);
37664
37718
  logger2.debug(`Webhook ${method} ${url}`, { method, url, waitForResponse: config2.waitForResponse });
37665
37719
  const response = await brokeredFetch(url, {
37666
37720
  method,
@@ -37750,8 +37804,10 @@ async function executeEmitEventAction(config2, context2, deps, trustedTenantId)
37750
37804
  }
37751
37805
  }
37752
37806
  logger2.debug("Emitting event", { eventType });
37807
+ const correlationId = context2.event?.metadata.correlationId ?? context2.payload.correlationId ?? undefined;
37753
37808
  const result = await deps.eventBus.publishGeneric(eventType, payload, {
37754
- correlationId: context2.payload.correlationId ?? undefined,
37809
+ correlationId,
37810
+ causationId: context2.event?.id,
37755
37811
  source: "automation",
37756
37812
  ...trustedTenantId ? { tenantId: trustedTenantId } : {}
37757
37813
  });
@@ -37844,7 +37900,12 @@ function extractAgentCallContext(config2, context2) {
37844
37900
  threadId,
37845
37901
  senderId,
37846
37902
  senderName,
37847
- messages: messagesResult
37903
+ messages: messagesResult,
37904
+ event: context2.event ? {
37905
+ id: context2.event.id,
37906
+ type: context2.event.type,
37907
+ correlationId: context2.event.metadata.correlationId
37908
+ } : undefined
37848
37909
  }
37849
37910
  };
37850
37911
  }
@@ -37885,12 +37946,12 @@ async function executeCallAgentAction(config2, context2, deps, trustedTenantId)
37885
37946
  return { success: false, error: errorMessage };
37886
37947
  }
37887
37948
  }
37888
- async function executeAction(action, context2, deps, trustedTenantId) {
37949
+ async function executeAction(action, context2, deps, trustedTenantId, actionIndex = 0) {
37889
37950
  const start = Date.now();
37890
37951
  let result;
37891
37952
  switch (action.type) {
37892
37953
  case "webhook":
37893
- result = await executeWebhookAction(action.config, context2, deps, trustedTenantId);
37954
+ result = await executeWebhookAction(action.config, context2, deps, trustedTenantId, actionIndex);
37894
37955
  break;
37895
37956
  case "send_message":
37896
37957
  result = await executeSendMessageAction(action.config, context2, deps, trustedTenantId);
@@ -37919,12 +37980,12 @@ async function executeAction(action, context2, deps, trustedTenantId) {
37919
37980
  async function executeActions(actions, context2, deps, trustedTenantId) {
37920
37981
  const results = [];
37921
37982
  const variables = { ...context2.variables };
37922
- for (const action of actions) {
37983
+ for (const [actionIndex, action] of actions.entries()) {
37923
37984
  const actionContext = {
37924
37985
  ...context2,
37925
37986
  variables
37926
37987
  };
37927
- const result = await executeAction(action, actionContext, deps, trustedTenantId);
37988
+ const result = await executeAction(action, actionContext, deps, trustedTenantId, actionIndex);
37928
37989
  results.push(result);
37929
37990
  if (action.type === "webhook" && action.config.responseAs && result.status === "success" && result.result) {
37930
37991
  variables[action.config.responseAs] = result.result;
@@ -38354,13 +38415,18 @@ class AutomationEngine {
38354
38415
  type: content?.type ?? "unknown",
38355
38416
  text: content?.text,
38356
38417
  timestamp: event.timestamp,
38357
- payload
38418
+ payload,
38419
+ eventId: event.id,
38420
+ correlationId: event.metadata.correlationId
38358
38421
  };
38359
38422
  manager.addMessage(key, message2, from, instanceId, stamp);
38360
38423
  }
38361
38424
  async handleImmediate(automation, event) {
38362
38425
  const instanceId = event.metadata.instanceId ?? "global";
38363
- const context2 = createTemplateContext(event.payload);
38426
+ const context2 = createTemplateContext(event.payload, {
38427
+ event: { id: event.id, type: event.type, timestamp: event.timestamp, metadata: event.metadata },
38428
+ automation: { id: automation.id }
38429
+ });
38364
38430
  await this.queueExecution(automation, event, context2, instanceId);
38365
38431
  }
38366
38432
  setupDebounceManager(automation) {
@@ -38370,28 +38436,35 @@ class AutomationEngine {
38370
38436
  logger4.warn("Debounce callback fired with empty messages array", { key });
38371
38437
  return;
38372
38438
  }
38373
- const context2 = createTemplateContext(lastMessage.payload, {
38374
- debounce: {
38375
- messages: messages.map((m2) => ({
38376
- type: m2.type,
38377
- text: m2.text,
38378
- timestamp: m2.timestamp
38379
- })),
38380
- from,
38381
- instanceId
38382
- }
38383
- });
38384
38439
  const syntheticEvent = {
38385
38440
  id: generateId(),
38386
38441
  type: automation.triggerEventType,
38387
38442
  payload: lastMessage.payload,
38388
38443
  metadata: {
38389
- correlationId: generateId(),
38444
+ correlationId: lastMessage.correlationId ?? generateId(),
38390
38445
  instanceId,
38391
38446
  ...stamp ? { envelopeVersion: stamp.envelopeVersion, tenantId: stamp.tenantId } : {}
38392
38447
  },
38393
38448
  timestamp: Date.now()
38394
38449
  };
38450
+ const context2 = createTemplateContext(lastMessage.payload, {
38451
+ debounce: {
38452
+ messages: messages.map((m2) => ({
38453
+ type: m2.type,
38454
+ text: m2.text,
38455
+ timestamp: m2.timestamp
38456
+ })),
38457
+ from,
38458
+ instanceId
38459
+ },
38460
+ event: {
38461
+ id: lastMessage.eventId ?? syntheticEvent.id,
38462
+ type: syntheticEvent.type,
38463
+ timestamp: syntheticEvent.timestamp,
38464
+ metadata: syntheticEvent.metadata
38465
+ },
38466
+ automation: { id: automation.id }
38467
+ });
38395
38468
  await this.queueExecution(automation, syntheticEvent, context2, instanceId);
38396
38469
  };
38397
38470
  const manager = new DebounceManager(automation.debounce, callback);
@@ -38479,7 +38552,10 @@ class AutomationEngine {
38479
38552
  await this.logExecution(result2, trustedTenantId);
38480
38553
  return result2;
38481
38554
  }
38482
- const actionsExecuted = await executeActions(automation.actions, context2, this.deps, trustedTenantId);
38555
+ const actionsExecuted = await runWithEventCausality({
38556
+ correlationId: context2.event?.metadata.correlationId ?? event.metadata.correlationId,
38557
+ causationId: context2.event?.id ?? event.id
38558
+ }, () => executeActions(automation.actions, context2, this.deps, trustedTenantId));
38483
38559
  const allSucceeded = actionsExecuted.every((a) => a.status === "success");
38484
38560
  const status = allSucceeded ? "success" : "failed";
38485
38561
  const result = {
@@ -38575,6 +38651,7 @@ function createAutomationEngine(config2) {
38575
38651
  }
38576
38652
  var logger4, QueueFullError;
38577
38653
  var init_engine = __esm(() => {
38654
+ init_causality();
38578
38655
  init_envelope();
38579
38656
  init_ids();
38580
38657
  init_logger();
@@ -43113,7 +43190,7 @@ function isProviderSchemaSupported(schema) {
43113
43190
  function getSupportedProviderSchemas() {
43114
43191
  return ["agno", "webhook", "openclaw", "claude-code", "ag-ui", "a2a", "nats-genie"];
43115
43192
  }
43116
- var init_factory = __esm(() => {
43193
+ var init_factory2 = __esm(() => {
43117
43194
  init_a2a_client();
43118
43195
  init_ag_ui_client();
43119
43196
  init_agno_client();
@@ -43133,7 +43210,7 @@ var init_providers = __esm(() => {
43133
43210
  init_ag_ui_provider();
43134
43211
  init_a2a_provider();
43135
43212
  init_nats_genie_provider();
43136
- init_factory();
43213
+ init_factory2();
43137
43214
  });
43138
43215
 
43139
43216
  // ../core/src/cache/types.ts
@@ -43817,6 +43894,7 @@ __export(exports_src, {
43817
43894
  scheduledJobRuns: () => scheduledJobRuns,
43818
43895
  scheduledJobNextRun: () => scheduledJobNextRun,
43819
43896
  scheduledJobDuration: () => scheduledJobDuration,
43897
+ runWithEventCausality: () => runWithEventCausality,
43820
43898
  rootLogger: () => rootLogger,
43821
43899
  resolveResetConfig: () => resolveResetConfig,
43822
43900
  resolvePublishTenantId: () => resolvePublishTenantId,
@@ -43929,6 +44007,7 @@ __export(exports_src, {
43929
44007
  dbQueries: () => dbQueries,
43930
44008
  dbPoolSize: () => dbPoolSize,
43931
44009
  dbErrors: () => dbErrors,
44010
+ currentEventCausality: () => currentEventCausality,
43932
44011
  createValidatedSubscription: () => createValidatedSubscription,
43933
44012
  createTemplateContext: () => createTemplateContext,
43934
44013
  createSubscription: () => createSubscription,
@@ -139026,9 +139105,9 @@ var require_session = __commonJS((exports) => {
139026
139105
  return options.type === "multi" ? strictMultiSession(options) : strictSingleSession(options);
139027
139106
  }
139028
139107
  function strictSingleSession(options) {
139029
- const { initial, storage, getSessionKey, custom: custom2 } = fillDefaults(options);
139108
+ const { initial, storage: storage2, getSessionKey, custom: custom2 } = fillDefaults(options);
139030
139109
  return async (ctx, next) => {
139031
- const propSession = new PropertySession(storage, ctx, "session", initial);
139110
+ const propSession = new PropertySession(storage2, ctx, "session", initial);
139032
139111
  const key = await getSessionKey(ctx);
139033
139112
  await propSession.init(key, { custom: custom2, lazy: false });
139034
139113
  await next();
@@ -139041,8 +139120,8 @@ var require_session = __commonJS((exports) => {
139041
139120
  return async (ctx, next) => {
139042
139121
  ctx.session = {};
139043
139122
  const propSessions = await Promise.all(props.map(async (prop) => {
139044
- const { initial, storage, getSessionKey, custom: custom2 } = defaults[prop];
139045
- const s = new PropertySession(storage, ctx.session, prop, initial);
139123
+ const { initial, storage: storage2, getSessionKey, custom: custom2 } = defaults[prop];
139124
+ const s = new PropertySession(storage2, ctx.session, prop, initial);
139046
139125
  const key = await getSessionKey(ctx);
139047
139126
  await s.init(key, { custom: custom2, lazy: false });
139048
139127
  return s;
@@ -139057,9 +139136,9 @@ var require_session = __commonJS((exports) => {
139057
139136
  if (options.type !== undefined && options.type !== "single") {
139058
139137
  throw new Error("Cannot use lazy multi sessions!");
139059
139138
  }
139060
- const { initial, storage, getSessionKey, custom: custom2 } = fillDefaults(options);
139139
+ const { initial, storage: storage2, getSessionKey, custom: custom2 } = fillDefaults(options);
139061
139140
  return async (ctx, next) => {
139062
- const propSession = new PropertySession(storage, ctx, "session", initial);
139141
+ const propSession = new PropertySession(storage2, ctx, "session", initial);
139063
139142
  const key = await getSessionKey(ctx);
139064
139143
  await propSession.init(key, { custom: custom2, lazy: true });
139065
139144
  await next();
@@ -139068,8 +139147,8 @@ var require_session = __commonJS((exports) => {
139068
139147
  }
139069
139148
 
139070
139149
  class PropertySession {
139071
- constructor(storage, obj, prop, initial) {
139072
- this.storage = storage;
139150
+ constructor(storage2, obj, prop, initial) {
139151
+ this.storage = storage2;
139073
139152
  this.obj = obj;
139074
139153
  this.prop = prop;
139075
139154
  this.initial = initial;
@@ -139152,15 +139231,15 @@ var require_session = __commonJS((exports) => {
139152
139231
  }
139153
139232
  }
139154
139233
  function fillDefaults(opts = {}) {
139155
- let { prefix = "", getSessionKey = defaultGetSessionKey, initial, storage } = opts;
139156
- if (storage == null) {
139234
+ let { prefix = "", getSessionKey = defaultGetSessionKey, initial, storage: storage2 } = opts;
139235
+ if (storage2 == null) {
139157
139236
  debug2("Storing session data in memory, all data will be lost when the bot restarts.");
139158
- storage = new MemorySessionStorage;
139237
+ storage2 = new MemorySessionStorage;
139159
139238
  }
139160
139239
  const custom2 = getSessionKey !== defaultGetSessionKey;
139161
139240
  return {
139162
139241
  initial,
139163
- storage,
139242
+ storage: storage2,
139164
139243
  getSessionKey: async (ctx) => {
139165
139244
  const key = await getSessionKey(ctx);
139166
139245
  return key === undefined ? undefined : prefix + key;
@@ -139181,30 +139260,30 @@ var require_session = __commonJS((exports) => {
139181
139260
  return value === undefined || typeof value === "object" && value !== null && "__d" in value;
139182
139261
  }
139183
139262
  function enhanceStorage(options) {
139184
- let { storage, millisecondsToLive, migrations } = options;
139185
- storage = compatStorage(storage);
139263
+ let { storage: storage2, millisecondsToLive, migrations } = options;
139264
+ storage2 = compatStorage(storage2);
139186
139265
  if (millisecondsToLive !== undefined) {
139187
- storage = timeoutStorage(storage, millisecondsToLive);
139266
+ storage2 = timeoutStorage(storage2, millisecondsToLive);
139188
139267
  }
139189
139268
  if (migrations !== undefined) {
139190
- storage = migrationStorage(storage, migrations);
139269
+ storage2 = migrationStorage(storage2, migrations);
139191
139270
  }
139192
- return wrapStorage(storage);
139271
+ return wrapStorage(storage2);
139193
139272
  }
139194
- function compatStorage(storage) {
139273
+ function compatStorage(storage2) {
139195
139274
  return {
139196
139275
  read: async (k2) => {
139197
- const v2 = await storage.read(k2);
139276
+ const v2 = await storage2.read(k2);
139198
139277
  return isEnhance(v2) ? v2 : { __d: v2 };
139199
139278
  },
139200
- write: (k2, v2) => storage.write(k2, v2),
139201
- delete: (k2) => storage.delete(k2)
139279
+ write: (k2, v2) => storage2.write(k2, v2),
139280
+ delete: (k2) => storage2.delete(k2)
139202
139281
  };
139203
139282
  }
139204
- function timeoutStorage(storage, millisecondsToLive) {
139283
+ function timeoutStorage(storage2, millisecondsToLive) {
139205
139284
  const ttlStorage = {
139206
139285
  read: async (k2) => {
139207
- const value = await storage.read(k2);
139286
+ const value = await storage2.read(k2);
139208
139287
  if (value === undefined)
139209
139288
  return;
139210
139289
  if (value.e === undefined) {
@@ -139219,13 +139298,13 @@ var require_session = __commonJS((exports) => {
139219
139298
  },
139220
139299
  write: async (k2, v2) => {
139221
139300
  v2.e = addExpiryDate(v2, millisecondsToLive).expires;
139222
- await storage.write(k2, v2);
139301
+ await storage2.write(k2, v2);
139223
139302
  },
139224
- delete: (k2) => storage.delete(k2)
139303
+ delete: (k2) => storage2.delete(k2)
139225
139304
  };
139226
139305
  return ttlStorage;
139227
139306
  }
139228
- function migrationStorage(storage, migrations) {
139307
+ function migrationStorage(storage2, migrations) {
139229
139308
  const versions = Object.keys(migrations).map((v2) => parseInt(v2)).sort((a, b2) => a - b2);
139230
139309
  const count = versions.length;
139231
139310
  if (count === 0)
@@ -139244,7 +139323,7 @@ var require_session = __commonJS((exports) => {
139244
139323
  return {
139245
139324
  read: async (k2) => {
139246
139325
  var _a;
139247
- const val = await storage.read(k2);
139326
+ const val = await storage2.read(k2);
139248
139327
  if (val === undefined)
139249
139328
  return val;
139250
139329
  let { __d: value, v: current = earliest - 1 } = val;
@@ -139253,15 +139332,15 @@ var require_session = __commonJS((exports) => {
139253
139332
  value = migrations[versions[i]](value);
139254
139333
  return { ...val, v: latest, __d: value };
139255
139334
  },
139256
- write: (k2, v2) => storage.write(k2, { v: latest, ...v2 }),
139257
- delete: (k2) => storage.delete(k2)
139335
+ write: (k2, v2) => storage2.write(k2, { v: latest, ...v2 }),
139336
+ delete: (k2) => storage2.delete(k2)
139258
139337
  };
139259
139338
  }
139260
- function wrapStorage(storage) {
139339
+ function wrapStorage(storage2) {
139261
139340
  return {
139262
- read: (k2) => Promise.resolve(storage.read(k2)).then((v2) => v2 === null || v2 === undefined ? undefined : v2.__d),
139263
- write: (k2, v2) => storage.write(k2, { __d: v2 }),
139264
- delete: (k2) => storage.delete(k2)
139341
+ read: (k2) => Promise.resolve(storage2.read(k2)).then((v2) => v2 === null || v2 === undefined ? undefined : v2.__d),
139342
+ write: (k2, v2) => storage2.write(k2, { __d: v2 }),
139343
+ delete: (k2) => storage2.delete(k2)
139265
139344
  };
139266
139345
  }
139267
139346
 
@@ -143391,9 +143470,9 @@ var require_session_builder = __commonJS((exports, module) => {
143391
143470
  var queueJob = require_queue_job();
143392
143471
 
143393
143472
  class SessionBuilder {
143394
- constructor(storage, protocolAddress) {
143473
+ constructor(storage2, protocolAddress) {
143395
143474
  this.addr = protocolAddress;
143396
- this.storage = storage;
143475
+ this.storage = storage2;
143397
143476
  }
143398
143477
  async initOutgoing(device) {
143399
143478
  const fqAddr = this.addr.toString();
@@ -144839,12 +144918,12 @@ var require_session_cipher = __commonJS((exports, module) => {
144839
144918
  }
144840
144919
 
144841
144920
  class SessionCipher {
144842
- constructor(storage, protocolAddress) {
144921
+ constructor(storage2, protocolAddress) {
144843
144922
  if (!(protocolAddress instanceof ProtocolAddress)) {
144844
144923
  throw new TypeError("protocolAddress must be a ProtocolAddress");
144845
144924
  }
144846
144925
  this.addr = protocolAddress;
144847
- this.storage = storage;
144926
+ this.storage = storage2;
144848
144927
  }
144849
144928
  _encodeTupleByte(number1, number2) {
144850
144929
  if (number1 > 15 || number2 > 15) {
@@ -173074,9 +173153,11 @@ var init_schema2 = __esm(() => {
173074
173153
  agentRequest: jsonb("agent_request").$type(),
173075
173154
  agentResponse: jsonb("agent_response").$type(),
173076
173155
  metadata: jsonb("metadata").$type(),
173156
+ causationId: uuid("causation_id"),
173077
173157
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
173078
173158
  tenantId: uuid("tenant_id").references(() => tenants.id, { onDelete: "restrict" })
173079
173159
  }, (table3) => ({
173160
+ causationIdx: index("omni_events_causation_idx").on(table3.causationId),
173080
173161
  tenantIdx: index("omni_events_tenant_idx").on(table3.tenantId),
173081
173162
  tenantIdUq: uniqueIndex("omni_events_tenant_id_uq").on(table3.tenantId, table3.id),
173082
173163
  externalIdIdx: index("omni_events_external_id_idx").on(table3.externalId),
@@ -179835,11 +179916,11 @@ function isTerminal(state) {
179835
179916
  class A2ATaskStore {
179836
179917
  memory = new Map;
179837
179918
  storage;
179838
- constructor(storage) {
179839
- this.storage = storage;
179919
+ constructor(storage2) {
179920
+ this.storage = storage2;
179840
179921
  }
179841
- setStorage(storage) {
179842
- this.storage = storage;
179922
+ setStorage(storage2) {
179923
+ this.storage = storage2;
179843
179924
  }
179844
179925
  async createTask(params) {
179845
179926
  const now = new Date().toISOString();
@@ -201887,12 +201968,12 @@ var init_resource_Bhpm2sLf = __esm(() => {
201887
201968
  });
201888
201969
 
201889
201970
  // ../../node_modules/.bun/@sentry+opentelemetry@10.52.0+54dbe0b6443040f8/node_modules/@sentry/opentelemetry/build/esm/index.js
201890
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
201971
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
201891
201972
  import { EventEmitter as EventEmitter4 } from "events";
201892
201973
 
201893
201974
  class SentryAsyncLocalStorageContextManager {
201894
201975
  __init() {
201895
- this._asyncLocalStorage = new AsyncLocalStorage2;
201976
+ this._asyncLocalStorage = new AsyncLocalStorage3;
201896
201977
  }
201897
201978
  __init2() {
201898
201979
  this._kOtListeners = Symbol("OtListeners");
@@ -250825,7 +250906,7 @@ var init_sentry_scrub = __esm(() => {
250825
250906
  var require_package7 = __commonJS((exports, module) => {
250826
250907
  module.exports = {
250827
250908
  name: "@omni/api",
250828
- version: "2.260906.3",
250909
+ version: "2.260906.4",
250829
250910
  private: true,
250830
250911
  type: "module",
250831
250912
  exports: {
@@ -257810,23 +257891,23 @@ var require_Meter = __commonJS((exports) => {
257810
257891
  }
257811
257892
  createGauge(name, options) {
257812
257893
  const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.GAUGE, options);
257813
- const storage = this._meterSharedState.registerMetricStorage(descriptor);
257814
- return new Instruments_1.GaugeInstrument(storage, descriptor);
257894
+ const storage2 = this._meterSharedState.registerMetricStorage(descriptor);
257895
+ return new Instruments_1.GaugeInstrument(storage2, descriptor);
257815
257896
  }
257816
257897
  createHistogram(name, options) {
257817
257898
  const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.HISTOGRAM, options);
257818
- const storage = this._meterSharedState.registerMetricStorage(descriptor);
257819
- return new Instruments_1.HistogramInstrument(storage, descriptor);
257899
+ const storage2 = this._meterSharedState.registerMetricStorage(descriptor);
257900
+ return new Instruments_1.HistogramInstrument(storage2, descriptor);
257820
257901
  }
257821
257902
  createCounter(name, options) {
257822
257903
  const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.COUNTER, options);
257823
- const storage = this._meterSharedState.registerMetricStorage(descriptor);
257824
- return new Instruments_1.CounterInstrument(storage, descriptor);
257904
+ const storage2 = this._meterSharedState.registerMetricStorage(descriptor);
257905
+ return new Instruments_1.CounterInstrument(storage2, descriptor);
257825
257906
  }
257826
257907
  createUpDownCounter(name, options) {
257827
257908
  const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.UP_DOWN_COUNTER, options);
257828
- const storage = this._meterSharedState.registerMetricStorage(descriptor);
257829
- return new Instruments_1.UpDownCounterInstrument(storage, descriptor);
257909
+ const storage2 = this._meterSharedState.registerMetricStorage(descriptor);
257910
+ return new Instruments_1.UpDownCounterInstrument(storage2, descriptor);
257830
257911
  }
257831
257912
  createObservableGauge(name, options) {
257832
257913
  const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.OBSERVABLE_GAUGE, options);
@@ -258220,16 +258301,16 @@ var require_MetricStorageRegistry = __commonJS((exports) => {
258220
258301
  }
258221
258302
  return storages;
258222
258303
  }
258223
- register(storage) {
258224
- this._registerStorage(storage, this._sharedRegistry);
258304
+ register(storage2) {
258305
+ this._registerStorage(storage2, this._sharedRegistry);
258225
258306
  }
258226
- registerForCollector(collector, storage) {
258307
+ registerForCollector(collector, storage2) {
258227
258308
  let storageMap = this._perCollectorRegistry.get(collector);
258228
258309
  if (storageMap == null) {
258229
258310
  storageMap = new Map;
258230
258311
  this._perCollectorRegistry.set(collector, storageMap);
258231
258312
  }
258232
- this._registerStorage(storage, storageMap);
258313
+ this._registerStorage(storage2, storageMap);
258233
258314
  }
258234
258315
  findOrUpdateCompatibleStorage(expectedDescriptor) {
258235
258316
  const storages = this._sharedRegistry.get(expectedDescriptor.name);
@@ -258249,14 +258330,14 @@ var require_MetricStorageRegistry = __commonJS((exports) => {
258249
258330
  }
258250
258331
  return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages);
258251
258332
  }
258252
- _registerStorage(storage, storageMap) {
258253
- const descriptor = storage.getInstrumentDescriptor();
258333
+ _registerStorage(storage2, storageMap) {
258334
+ const descriptor = storage2.getInstrumentDescriptor();
258254
258335
  const storages = storageMap.get(descriptor.name);
258255
258336
  if (storages === undefined) {
258256
- storageMap.set(descriptor.name, [storage]);
258337
+ storageMap.set(descriptor.name, [storage2]);
258257
258338
  return;
258258
258339
  }
258259
- storages.push(storage);
258340
+ storages.push(storage2);
258260
258341
  }
258261
258342
  _findOrUpdateCompatibleStorage(expectedDescriptor, existingStorages) {
258262
258343
  let compatibleStorage = null;
@@ -258604,9 +258685,9 @@ var require_MeterSharedState = __commonJS((exports) => {
258604
258685
  return compatibleStorage;
258605
258686
  }
258606
258687
  const aggregator = aggregation.createAggregator(descriptor);
258607
- const storage = new MetricStorageType(descriptor, aggregator, AttributesProcessor_1.AttributesProcessor.Noop(), [collector]);
258608
- this.metricStorageRegistry.registerForCollector(collector, storage);
258609
- return storage;
258688
+ const storage2 = new MetricStorageType(descriptor, aggregator, AttributesProcessor_1.AttributesProcessor.Noop(), [collector]);
258689
+ this.metricStorageRegistry.registerForCollector(collector, storage2);
258690
+ return storage2;
258610
258691
  });
258611
258692
  storages = storages.concat(collectorStorages);
258612
258693
  }
@@ -300168,7 +300249,7 @@ var Factory = class {
300168
300249
  return handlers2.filter((handler) => handler !== undefined);
300169
300250
  };
300170
300251
  }, createMiddleware = (middleware) => middleware;
300171
- var init_factory2 = __esm(() => {
300252
+ var init_factory3 = __esm(() => {
300172
300253
  init_hono2();
300173
300254
  });
300174
300255
 
@@ -300697,20 +300778,20 @@ var init_tenant_transaction = __esm(() => {
300697
300778
  });
300698
300779
 
300699
300780
  // ../api/src/tenancy/tenant-scope.ts
300700
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
300781
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
300701
300782
  function currentTenantScope() {
300702
- return storage.getStore() ?? null;
300783
+ return storage2.getStore() ?? null;
300703
300784
  }
300704
300785
  function scopedHandle(db2) {
300705
- const scope = storage.getStore();
300786
+ const scope = storage2.getStore();
300706
300787
  return scope ? scope.tx : db2;
300707
300788
  }
300708
300789
  async function runInTenantScope(db2, context20, fn) {
300709
- if (storage.getStore()) {
300790
+ if (storage2.getStore()) {
300710
300791
  throw new Error("tenant-scope: a tenant scope is already active for this request");
300711
300792
  }
300712
300793
  const postCommit = [];
300713
- const result = await withTenantTransaction(db2, context20, async (tx, tenantId) => storage.run({ tx, tenantId, postCommit }, fn));
300794
+ const result = await withTenantTransaction(db2, context20, async (tx, tenantId) => storage2.run({ tx, tenantId, postCommit }, fn));
300714
300795
  for (const cb of postCommit) {
300715
300796
  try {
300716
300797
  cb();
@@ -300719,7 +300800,7 @@ async function runInTenantScope(db2, context20, fn) {
300719
300800
  return result;
300720
300801
  }
300721
300802
  function runAfterTenantCommit(fn) {
300722
- const scope = storage.getStore();
300803
+ const scope = storage2.getStore();
300723
300804
  if (scope) {
300724
300805
  scope.postCommit.push(fn);
300725
300806
  } else {
@@ -300727,12 +300808,12 @@ function runAfterTenantCommit(fn) {
300727
300808
  }
300728
300809
  }
300729
300810
  function runDetachedFromTenantScope(fn) {
300730
- return storage.exit(fn);
300811
+ return storage2.exit(fn);
300731
300812
  }
300732
- var storage;
300813
+ var storage2;
300733
300814
  var init_tenant_scope = __esm(() => {
300734
300815
  init_tenant_transaction();
300735
- storage = new AsyncLocalStorage3;
300816
+ storage2 = new AsyncLocalStorage4;
300736
300817
  });
300737
300818
 
300738
300819
  // ../api/src/tenancy/auth-context.ts
@@ -300865,7 +300946,7 @@ function filterByInstanceAccess(items, getInstanceId, apiKey) {
300865
300946
  }
300866
300947
  var authMiddleware;
300867
300948
  var init_auth = __esm(() => {
300868
- init_factory2();
300949
+ init_factory3();
300869
300950
  init_api_keys();
300870
300951
  init_tenant_scope();
300871
300952
  init_worker_tenant_context();
@@ -301088,7 +301169,7 @@ function pathFromRequest(url) {
301088
301169
  var log59, REPLAY_WINDOW_MS = 60000, ED25519_SPKI_PREFIX, HEADER_HOST_ID = "x-genie-host-id", HEADER_TIMESTAMP = "x-genie-timestamp", HEADER_SIGNATURE = "x-genie-signature", genieSignatureMiddleware;
301089
301170
  var init_genie_signature = __esm(() => {
301090
301171
  init_src();
301091
- init_factory2();
301172
+ init_factory3();
301092
301173
  log59 = createLogger("api:genie-signature");
301093
301174
  ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
301094
301175
  genieSignatureMiddleware = createMiddleware(async (c, next) => {
@@ -301480,7 +301561,7 @@ async function emitRedactionEvents(c, apiKey, presetKey, hits) {
301480
301561
  var log60, SEND_ROUTE_PREFIXES, REDACTION_MARKER = "[redacted]", SECRET_REDACTED_EVENT = "secret.redacted", MAX_REDACT_BYTES, presetRegistry = null, outputRedactorMiddleware;
301481
301562
  var init_output_redactor = __esm(() => {
301482
301563
  init_src();
301483
- init_factory2();
301564
+ init_factory3();
301484
301565
  init_profiles();
301485
301566
  log60 = createLogger("api:output-redactor");
301486
301567
  SEND_ROUTE_PREFIXES = ["/messages/send"];
@@ -301644,6 +301725,7 @@ var init_scopes = __esm(() => {
301644
301725
  "GET /events/timeline/:personId": "events:read",
301645
301726
  "POST /events/search": "events:read",
301646
301727
  "GET /events/:id": "events:read",
301728
+ "GET /events/:id/trace": "events:read",
301647
301729
  "GET /events/by-sender/:senderId": "events:read",
301648
301730
  "GET /follow-up/agents/:id": "follow-up:read",
301649
301731
  "PUT /follow-up/agents/:id": "follow-up:write",
@@ -302043,7 +302125,7 @@ function invalidSignedHostScopeContextResponse(c, hostId) {
302043
302125
  var log61, OUTBOUND_SEND_PREFIXES, PATH_INSTANCE_PREFIXES, PATH_CHAT_PREFIXES, PATH_MEDIA_INSTANCE_PREFIX = "/media/", scopeEnforcerMiddleware;
302044
302126
  var init_scope_enforcer = __esm(() => {
302045
302127
  init_src();
302046
- init_factory2();
302128
+ init_factory3();
302047
302129
  init_profiles();
302048
302130
  init_scopes();
302049
302131
  init_signed_host_scope_context();
@@ -302165,7 +302247,7 @@ async function safeReadJsonBody2(c) {
302165
302247
  var log62, requireSignedInstanceMiddleware;
302166
302248
  var init_require_signed_instance = __esm(() => {
302167
302249
  init_src();
302168
- init_factory2();
302250
+ init_factory3();
302169
302251
  init_scope_enforcer();
302170
302252
  log62 = createLogger("api:require-signed-instance");
302171
302253
  requireSignedInstanceMiddleware = createMiddleware(async (c, next) => {
@@ -302462,6 +302544,7 @@ var init_route_ownership = __esm(() => {
302462
302544
  "GET /api/v2/events/:eventId/payloads",
302463
302545
  "GET /api/v2/events/:eventId/payloads/:stage",
302464
302546
  "GET /api/v2/events/:id",
302547
+ "GET /api/v2/events/:id/trace",
302465
302548
  "GET /api/v2/events/analytics",
302466
302549
  "GET /api/v2/events/by-sender/:senderId",
302467
302550
  "GET /api/v2/events/schemas",
@@ -302873,7 +302956,7 @@ function refuseUnaddressableRoute(c) {
302873
302956
  }
302874
302957
  var TENANT_HINT_HEADER = "x-omni-tenant-id", tenancyMiddleware;
302875
302958
  var init_tenancy = __esm(() => {
302876
- init_factory2();
302959
+ init_factory3();
302877
302960
  init_route();
302878
302961
  init_route_ownership();
302879
302962
  init_scope_projection();
@@ -351309,24 +351392,24 @@ class InMemoryPluginStorage {
351309
351392
  }
351310
351393
  function setStorageDatabase(db2) {
351311
351394
  globalDb = db2;
351312
- for (const [pluginId, storage2] of storageInstances.entries()) {
351313
- if (storage2 instanceof InMemoryPluginStorage) {
351395
+ for (const [pluginId, storage3] of storageInstances.entries()) {
351396
+ if (storage3 instanceof InMemoryPluginStorage) {
351314
351397
  storageInstances.set(pluginId, new DatabasePluginStorage(db2, pluginId));
351315
351398
  }
351316
351399
  }
351317
351400
  }
351318
351401
  function getPluginStorage(pluginId) {
351319
- let storage2 = storageInstances.get(pluginId);
351320
- if (!storage2) {
351402
+ let storage3 = storageInstances.get(pluginId);
351403
+ if (!storage3) {
351321
351404
  if (globalDb) {
351322
- storage2 = new DatabasePluginStorage(globalDb, pluginId);
351405
+ storage3 = new DatabasePluginStorage(globalDb, pluginId);
351323
351406
  } else {
351324
351407
  log87.warn("Database not available, using in-memory storage", { pluginId });
351325
- storage2 = new InMemoryPluginStorage(pluginId);
351408
+ storage3 = new InMemoryPluginStorage(pluginId);
351326
351409
  }
351327
- storageInstances.set(pluginId, storage2);
351410
+ storageInstances.set(pluginId, storage3);
351328
351411
  }
351329
- return storage2;
351412
+ return storage3;
351330
351413
  }
351331
351414
  var log87, INSTANCE_ID_IN_KEY, globalDb = null, storageInstances;
351332
351415
  var init_storage = __esm(() => {
@@ -355597,7 +355680,8 @@ async function setupAgentDispatcher(eventBus, services, db2) {
355597
355680
  tracker.recordCheckpoint(firstMsg.metadata.correlationId, "T5", JOURNEY_STAGES.T5);
355598
355681
  }
355599
355682
  queuedAck?.release();
355600
- await processAgentResponse(services, instance4, messages4, triggerType, db2, eventBus);
355683
+ const lastMsg = messages4[messages4.length - 1] ?? firstMsg;
355684
+ await runWithEventCausality({ correlationId: lastMsg.metadata.correlationId, causationId: lastMsg.metadata.eventId }, () => processAgentResponse(services, instance4, messages4, triggerType, db2, eventBus));
355601
355685
  };
355602
355686
  const debouncer = new MessageDebouncer(onDebouncedFlush, Date.now, {
355603
355687
  onQueuedBehindActiveRun: (info2) => void ackQueuedMessage(info2)
@@ -355634,6 +355718,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
355634
355718
  platformIdentityId: metadata.platformIdentityId,
355635
355719
  traceId,
355636
355720
  correlationId: metadata.correlationId,
355721
+ eventId: event.id,
355637
355722
  journeyTracked: metadata.timings != null,
355638
355723
  resolvedInstance: resolved,
355639
355724
  routeId,
@@ -355665,14 +355750,14 @@ async function setupAgentDispatcher(eventBus, services, db2) {
355665
355750
  if (!instance4)
355666
355751
  return;
355667
355752
  const traceId = metadata.traceId ?? generateCorrelationId("trc");
355668
- await processReactionTrigger(services, instance4, payload, {
355753
+ await runWithEventCausality({ correlationId: metadata.correlationId, causationId: event.id }, () => processReactionTrigger(services, instance4, payload, {
355669
355754
  instanceId: instance4.id,
355670
355755
  channelType: metadata.channelType,
355671
355756
  personId: metadata.personId,
355672
355757
  platformIdentityId: metadata.platformIdentityId,
355673
355758
  traceId,
355674
355759
  trustedTenantId: trustedDispatchTenant(metadata)
355675
- }, event, db2);
355760
+ }, event, db2));
355676
355761
  } catch (error3) {
355677
355762
  log91.error("Error processing reaction for dispatch", {
355678
355763
  instanceId: metadata.instanceId,
@@ -355697,14 +355782,14 @@ async function setupAgentDispatcher(eventBus, services, db2) {
355697
355782
  if (!instance4)
355698
355783
  return;
355699
355784
  const traceId = metadata.traceId ?? generateCorrelationId("trc");
355700
- await processReactionTrigger(services, instance4, payload, {
355785
+ await runWithEventCausality({ correlationId: metadata.correlationId, causationId: event.id }, () => processReactionTrigger(services, instance4, payload, {
355701
355786
  instanceId: instance4.id,
355702
355787
  channelType: metadata.channelType,
355703
355788
  personId: metadata.personId,
355704
355789
  platformIdentityId: metadata.platformIdentityId,
355705
355790
  traceId,
355706
355791
  trustedTenantId: trustedDispatchTenant(metadata)
355707
- }, event, db2);
355792
+ }, event, db2));
355708
355793
  } catch (error3) {
355709
355794
  log91.error("Error processing reaction removal for dispatch", {
355710
355795
  instanceId: metadata.instanceId,
@@ -358890,6 +358975,46 @@ class EventService {
358890
358975
  }
358891
358976
  return result;
358892
358977
  }
358978
+ async trace(id) {
358979
+ const focus = await this.getById(id);
358980
+ const seen = new Set([focus.id]);
358981
+ const ancestors = [];
358982
+ let current = focus;
358983
+ let truncated = false;
358984
+ while (current.causationId && ancestors.length < TRACE_MAX_ANCESTORS) {
358985
+ if (seen.has(current.causationId))
358986
+ break;
358987
+ const [parent] = await this.db.select().from(omniEvents).where(eq(omniEvents.id, current.causationId)).limit(1);
358988
+ if (!parent)
358989
+ break;
358990
+ seen.add(parent.id);
358991
+ ancestors.unshift(parent);
358992
+ current = parent;
358993
+ }
358994
+ if (current.causationId && ancestors.length >= TRACE_MAX_ANCESTORS)
358995
+ truncated = true;
358996
+ const descendants = [];
358997
+ let frontier = [focus.id];
358998
+ let depth = 0;
358999
+ while (frontier.length > 0 && depth < TRACE_MAX_DEPTH && descendants.length < TRACE_MAX_NODES) {
359000
+ depth++;
359001
+ const children = await this.db.select().from(omniEvents).where(inArray(omniEvents.causationId, frontier)).orderBy(omniEvents.receivedAt).limit(TRACE_MAX_NODES + 1);
359002
+ const fresh = children.filter((c) => !seen.has(c.id));
359003
+ for (const child of fresh)
359004
+ seen.add(child.id);
359005
+ for (const child of fresh)
359006
+ descendants.push({ event: child, depth });
359007
+ if (descendants.length > TRACE_MAX_NODES) {
359008
+ descendants.length = TRACE_MAX_NODES;
359009
+ truncated = true;
359010
+ break;
359011
+ }
359012
+ frontier = fresh.map((c) => c.id);
359013
+ }
359014
+ if (frontier.length > 0 && depth >= TRACE_MAX_DEPTH)
359015
+ truncated = true;
359016
+ return { event: focus, ancestors, descendants, truncated };
359017
+ }
358893
359018
  async getTimeline(personId, options = {}) {
358894
359019
  const { channels, since, until, limit: limit2 = 50, cursor } = options;
358895
359020
  const conditions3 = [eq(omniEvents.personId, personId)];
@@ -358991,6 +359116,7 @@ class EventService {
358991
359116
  };
358992
359117
  }
358993
359118
  }
359119
+ var TRACE_MAX_ANCESTORS = 50, TRACE_MAX_DEPTH = 10, TRACE_MAX_NODES = 200;
358994
359120
  var init_events2 = __esm(() => {
358995
359121
  init_src();
358996
359122
  init_src5();
@@ -363443,12 +363569,12 @@ class WebhookService {
363443
363569
  }
363444
363570
  }
363445
363571
  }
363446
- const eventId = generateId();
363447
363572
  const eventType = resolveWebhookEventType(sourceName, source.eventTypeMapping, headers);
363448
363573
  const eventPayload = {
363449
363574
  source: sourceName,
363450
363575
  ...payload
363451
363576
  };
363577
+ let eventId = generateId();
363452
363578
  await this.enforceRegisteredSchema(eventType, eventPayload, eventId, `webhook '${sourceName}'`);
363453
363579
  await this.db.update(webhookSources).set({
363454
363580
  lastReceivedAt: new Date,
@@ -363456,10 +363582,10 @@ class WebhookService {
363456
363582
  updatedAt: new Date
363457
363583
  }).where(eq(webhookSources.id, source.id));
363458
363584
  if (this.eventBus) {
363459
- await this.eventBus.publishGeneric(eventType, eventPayload, {
363460
- correlationId: eventId,
363585
+ const result = await this.eventBus.publishGeneric(eventType, eventPayload, {
363461
363586
  source: "webhook"
363462
363587
  });
363588
+ eventId = result.id;
363463
363589
  }
363464
363590
  return {
363465
363591
  received: true,
@@ -363516,17 +363642,17 @@ class WebhookService {
363516
363642
  throw new ValidationError2(`${SCHEMA_VALIDATION_FAILED}: payload for '${eventType}' violates its registered schema (${origin})`, undefined, { eventType, errors: verdict.errors });
363517
363643
  }
363518
363644
  async trigger(eventType, payload, metadata) {
363519
- const eventId = metadata?.correlationId ?? generateId();
363520
- await this.enforceRegisteredSchema(eventType, payload, eventId, "manual trigger");
363645
+ const provisionalId = metadata?.correlationId ?? generateId();
363646
+ await this.enforceRegisteredSchema(eventType, payload, provisionalId, "manual trigger");
363521
363647
  if (this.eventBus) {
363522
- await this.eventBus.publishGeneric(eventType, payload, {
363523
- correlationId: eventId,
363648
+ const result = await this.eventBus.publishGeneric(eventType, payload, {
363649
+ correlationId: metadata?.correlationId,
363524
363650
  instanceId: metadata?.instanceId,
363525
363651
  source: "manual-trigger"
363526
363652
  });
363527
- return { eventId, published: true };
363653
+ return { eventId: result.id, published: true };
363528
363654
  }
363529
- return { eventId, published: false };
363655
+ return { eventId: provisionalId, published: false };
363530
363656
  }
363531
363657
  async heartbeat(sourceName) {
363532
363658
  const source = await this.getByName(sourceName);
@@ -363789,7 +363915,7 @@ function createContextMiddleware(db2, eventBus, channelRegistry2 = null) {
363789
363915
  return { middleware, services };
363790
363916
  }
363791
363917
  var init_context4 = __esm(() => {
363792
- init_factory2();
363918
+ init_factory3();
363793
363919
  init_services();
363794
363920
  });
363795
363921
 
@@ -364164,7 +364290,7 @@ function createRateLimiter2(config4 = RATE_LIMITS.general, keyPrefix = "ratelimi
364164
364290
  var log113, warnedUnparseableProxyHop = false, rateLimitStore, cleanupTimer, RATE_LIMITS, clientIpSchema, rateLimitMiddleware, webhookIngressRateLimitMiddleware;
364165
364291
  var init_rate_limit = __esm(() => {
364166
364292
  init_src();
364167
- init_factory2();
364293
+ init_factory3();
364168
364294
  init_zod();
364169
364295
  log113 = createLogger("api:rate-limit");
364170
364296
  rateLimitStore = new Map;
@@ -364208,7 +364334,7 @@ function timeoutMiddleware(config4 = {}) {
364208
364334
  }
364209
364335
  var DEFAULT_TIMEOUT_MS8 = 30000, defaultTimeoutMiddleware;
364210
364336
  var init_timeout = __esm(() => {
364211
- init_factory2();
364337
+ init_factory3();
364212
364338
  init_http_exception();
364213
364339
  defaultTimeoutMiddleware = timeoutMiddleware();
364214
364340
  });
@@ -364262,7 +364388,7 @@ function loadServerVersionInfo() {
364262
364388
  }
364263
364389
  var import__package, EMBEDDED_VERSION, LAST_RESORT_VERSION = "2.0.0-dev.1", FALLBACK_COMMIT = "unknown", SERVER_VERSION_INFO, versionHeadersMiddleware;
364264
364390
  var init_version_headers = __esm(() => {
364265
- init_factory2();
364391
+ init_factory3();
364266
364392
  import__package = __toESM(require_package7(), 1);
364267
364393
  EMBEDDED_VERSION = import__package.default?.version;
364268
364394
  SERVER_VERSION_INFO = loadServerVersionInfo();
@@ -364301,7 +364427,7 @@ function createWebhookAuthMiddleware(config4) {
364301
364427
  var log114;
364302
364428
  var init_webhook_auth = __esm(() => {
364303
364429
  init_src();
364304
- init_factory2();
364430
+ init_factory3();
364305
364431
  log114 = createLogger("api:webhook-auth");
364306
364432
  });
364307
364433
 
@@ -366621,7 +366747,8 @@ var init_automations3 = __esm(() => {
366621
366747
  bodyTemplate: exports_external.string().optional(),
366622
366748
  waitForResponse: exports_external.boolean().default(false),
366623
366749
  timeoutMs: exports_external.number().int().default(30000),
366624
- responseAs: exports_external.string().optional()
366750
+ responseAs: exports_external.string().optional(),
366751
+ includeEnvelope: exports_external.boolean().optional().openapi({ description: "Send the full OmniEvent envelope as the default body (default true)" })
366625
366752
  })
366626
366753
  });
366627
366754
  SendMessageActionSchema = exports_external.object({
@@ -367257,6 +367384,7 @@ function registerEventSchemas(registry4) {
367257
367384
  registry4.register("EventSummary", EventSummarySchema);
367258
367385
  registry4.register("EventAnalytics", EventAnalyticsSchema);
367259
367386
  registry4.register("EventSearch", EventSearchSchema);
367387
+ registry4.register("EventTrace", EventTraceSchema);
367260
367388
  registry4.registerPath({
367261
367389
  method: "get",
367262
367390
  path: "/events",
@@ -367381,6 +367509,22 @@ function registerEventSchemas(registry4) {
367381
367509
  404: { description: "Event not found", content: { "application/json": { schema: ErrorSchema } } }
367382
367510
  }
367383
367511
  });
367512
+ registry4.registerPath({
367513
+ method: "get",
367514
+ path: "/events/{id}/trace",
367515
+ operationId: "traceEvent",
367516
+ tags: ["Events"],
367517
+ summary: "Trace the causality chain around an event",
367518
+ description: "Walks UP via causationId to the root ingress event and DOWN breadth-first through fan-out (children are events whose causationId equals this id). correlationId groups the flow; causationId gives the tree.",
367519
+ request: { params: exports_external.object({ id: exports_external.string().uuid().openapi({ description: "Event UUID" }) }) },
367520
+ responses: {
367521
+ 200: {
367522
+ description: "Causality trace",
367523
+ content: { "application/json": { schema: exports_external.object({ data: EventTraceSchema }) } }
367524
+ },
367525
+ 404: { description: "Event not found", content: { "application/json": { schema: ErrorSchema } } }
367526
+ }
367527
+ });
367384
367528
  registry4.registerPath({
367385
367529
  method: "get",
367386
367530
  path: "/events/by-sender/{senderId}",
@@ -367410,7 +367554,7 @@ function registerEventSchemas(registry4) {
367410
367554
  }
367411
367555
  });
367412
367556
  }
367413
- var EventSchema, EventSummarySchema, EventAnalyticsSchema, EventSearchSchema;
367557
+ var EventSchema, EventSummarySchema, EventAnalyticsSchema, EventTraceSchema, EventSearchSchema;
367414
367558
  var init_events3 = __esm(() => {
367415
367559
  init_zod_openapi();
367416
367560
  init_common4();
@@ -367428,7 +367572,8 @@ var init_events3 = __esm(() => {
367428
367572
  agentId: exports_external.string().uuid().nullable().openapi({ description: "Agent UUID (FK \u2192 agents.id)" }),
367429
367573
  conversationId: exports_external.string().uuid().nullable().openapi({ description: "Conversation UUID (FK \u2192 conversations.id)" }),
367430
367574
  receivedAt: exports_external.string().datetime().openapi({ description: "When event was received" }),
367431
- processedAt: exports_external.string().datetime().nullable().openapi({ description: "When event was processed" })
367575
+ processedAt: exports_external.string().datetime().nullable().openapi({ description: "When event was processed" }),
367576
+ causationId: exports_external.string().uuid().nullable().openapi({ description: "Id of the immediate parent event (null for roots and pre-#957 rows)" })
367432
367577
  });
367433
367578
  EventSummarySchema = exports_external.object({
367434
367579
  id: exports_external.string().uuid().openapi({ description: "Event UUID" }),
@@ -367457,6 +367602,15 @@ var init_events3 = __esm(() => {
367457
367602
  count: exports_external.number().int().openapi({ description: "Event count in bucket" })
367458
367603
  })).optional().openapi({ description: "Timeline data (hourly or daily buckets)" })
367459
367604
  });
367605
+ EventTraceSchema = exports_external.object({
367606
+ event: EventSchema.openapi({ description: "The event the trace was requested for" }),
367607
+ ancestors: exports_external.array(EventSchema).openapi({ description: "Chain above the event via causationId, root first, ending at the immediate parent" }),
367608
+ descendants: exports_external.array(exports_external.object({
367609
+ event: EventSchema,
367610
+ depth: exports_external.number().int().openapi({ description: "Distance below the focus event (1 = direct child)" })
367611
+ })).openapi({ description: "Fan-out below the event, breadth-first" }),
367612
+ truncated: exports_external.boolean().openapi({ description: "True when a depth/node cap cut the walk short" })
367613
+ });
367460
367614
  EventSearchSchema = exports_external.object({
367461
367615
  query: exports_external.string().optional().openapi({ description: "Full-text search query" }),
367462
367616
  filters: exports_external.object({
@@ -371856,7 +372010,8 @@ var init_automations4 = __esm(() => {
371856
372010
  bodyTemplate: exports_external.string().optional().describe("Request body template (JSON)"),
371857
372011
  waitForResponse: exports_external.boolean().default(false).describe("Wait for response before continuing"),
371858
372012
  timeoutMs: exports_external.number().int().min(1000).max(120000).default(30000).describe("Request timeout"),
371859
- responseAs: exports_external.string().optional().describe("Store response as variable name")
372013
+ responseAs: exports_external.string().optional().describe("Store response as variable name"),
372014
+ includeEnvelope: exports_external.boolean().optional().describe("Send the full OmniEvent envelope as the default body when no bodyTemplate is set (default true)")
371860
372015
  })
371861
372016
  });
371862
372017
  sendMessageActionSchema = exports_external.object({
@@ -373652,6 +373807,16 @@ var init_events4 = __esm(() => {
373652
373807
  }
373653
373808
  return c.json({ data: event });
373654
373809
  });
373810
+ eventsRoutes.get("/:id/trace", async (c) => {
373811
+ const id = c.req.param("id");
373812
+ const services = c.get("services");
373813
+ const apiKey = c.get("apiKey");
373814
+ const trace24 = await services.events.trace(id);
373815
+ if (trace24.event.instanceId && apiKey && !ApiKeyService.instanceAllowed(apiKey.instanceIds, trace24.event.instanceId)) {
373816
+ return c.json({ error: { code: "FORBIDDEN", message: "API key does not have access to this instance" } }, 403);
373817
+ }
373818
+ return c.json({ data: trace24 });
373819
+ });
373655
373820
  eventsRoutes.get("/by-sender/:senderId", async (c) => {
373656
373821
  const senderId = c.req.param("senderId");
373657
373822
  const instanceId = c.req.query("instanceId");
@@ -378905,14 +379070,14 @@ var init_media2 = __esm(() => {
378905
379070
  }
378906
379071
  const relativePath = `${instanceId}/${path3}`;
378907
379072
  const db2 = c.get("services");
378908
- const storage2 = getMediaStorage(db2);
379073
+ const storage3 = getMediaStorage(db2);
378909
379074
  try {
378910
- const stat5 = await storage2.statMedia(relativePath);
379075
+ const stat5 = await storage3.statMedia(relativePath);
378911
379076
  if (!stat5) {
378912
379077
  return c.json({ error: { code: "NOT_FOUND", message: "Media not found" } }, 404);
378913
379078
  }
378914
379079
  const fileSize = stat5.size;
378915
- const mimeType = storage2.getMimeType(path3);
379080
+ const mimeType = storage3.getMimeType(path3);
378916
379081
  const rangeHeader = c.req.header("Range");
378917
379082
  if (rangeHeader) {
378918
379083
  const matches = rangeHeader.match(/bytes=(\d+)-(\d*)/);
@@ -378926,7 +379091,7 @@ var init_media2 = __esm(() => {
378926
379091
  headers: { "Content-Range": `bytes */${fileSize}`, "Accept-Ranges": "bytes" }
378927
379092
  });
378928
379093
  }
378929
- const chunk2 = await storage2.readMediaRange(relativePath, start, end);
379094
+ const chunk2 = await storage3.readMediaRange(relativePath, start, end);
378930
379095
  return new Response(chunk2, {
378931
379096
  status: 206,
378932
379097
  headers: {
@@ -378938,7 +379103,7 @@ var init_media2 = __esm(() => {
378938
379103
  });
378939
379104
  }
378940
379105
  }
378941
- const stream2 = await storage2.readMediaStream(relativePath);
379106
+ const stream2 = await storage3.readMediaStream(relativePath);
378942
379107
  return new Response(stream2, {
378943
379108
  status: 200,
378944
379109
  headers: {
@@ -383736,7 +383901,7 @@ function platformAuthMiddleware(requiredScope, platformAction) {
383736
383901
  }
383737
383902
  var UNAUTHORIZED, FORBIDDEN;
383738
383903
  var init_platform_auth = __esm(() => {
383739
- init_factory2();
383904
+ init_factory3();
383740
383905
  init_api_keys();
383741
383906
  UNAUTHORIZED = { error: { code: "UNAUTHORIZED", message: "Platform credential required" } };
383742
383907
  FORBIDDEN = {
@@ -384528,6 +384693,7 @@ async function setupEventPersistence(eventBus, db2) {
384528
384693
  from: payload.from
384529
384694
  },
384530
384695
  agentId: metadata.agentId ?? null,
384696
+ causationId: metadata.causationId ?? null,
384531
384697
  conversationId: null,
384532
384698
  chatUuid
384533
384699
  };
@@ -384581,6 +384747,7 @@ async function setupEventPersistence(eventBus, db2) {
384581
384747
  voiceNote: payload.content.isVoiceNote
384582
384748
  },
384583
384749
  agentId: metadata.agentId ?? null,
384750
+ causationId: metadata.causationId ?? null,
384584
384751
  conversationId: null,
384585
384752
  chatUuid
384586
384753
  };
@@ -384621,6 +384788,7 @@ async function setupEventPersistence(eventBus, db2) {
384621
384788
  receivedAt: new Date(event.timestamp),
384622
384789
  deliveredAt: new Date(payload.deliveredAt),
384623
384790
  agentId: metadata.agentId ?? null,
384791
+ causationId: metadata.causationId ?? null,
384624
384792
  conversationId: null,
384625
384793
  chatUuid
384626
384794
  };
@@ -384660,6 +384828,7 @@ async function setupEventPersistence(eventBus, db2) {
384660
384828
  receivedAt: new Date(event.timestamp),
384661
384829
  readAt: new Date(payload.readAt),
384662
384830
  agentId: metadata.agentId ?? null,
384831
+ causationId: metadata.causationId ?? null,
384663
384832
  conversationId: null,
384664
384833
  chatUuid
384665
384834
  };
@@ -384714,6 +384883,7 @@ async function setupEventPersistence(eventBus, db2) {
384714
384883
  retryable: payload.retryable
384715
384884
  },
384716
384885
  agentId: metadata.agentId ?? null,
384886
+ causationId: metadata.causationId ?? null,
384717
384887
  conversationId: null,
384718
384888
  chatUuid
384719
384889
  };
@@ -384734,6 +384904,38 @@ async function setupEventPersistence(eventBus, db2) {
384734
384904
  });
384735
384905
  }
384736
384906
  }, { ...CONSUMER_OPTIONS, durable: "event-persistence-failed" });
384907
+ await eventBus.subscribePattern("custom.>", async (event) => {
384908
+ const metadata = event.metadata;
384909
+ try {
384910
+ await runConsumerInTenantContext(db2, event, async () => {
384911
+ const sdb = scopedHandle(db2);
384912
+ const newEvent = {
384913
+ ...eventIdInsert(event.id),
384914
+ channel: "internal",
384915
+ instanceId: metadata.instanceId && isValidUuid(metadata.instanceId) ? metadata.instanceId : null,
384916
+ eventType: event.type.slice(0, 50),
384917
+ direction: "internal",
384918
+ status: "completed",
384919
+ receivedAt: new Date(event.timestamp),
384920
+ rawPayload: deepSanitize(event.payload),
384921
+ metadata: {
384922
+ correlationId: metadata.correlationId,
384923
+ source: metadata.source,
384924
+ fullEventType: event.type
384925
+ },
384926
+ causationId: metadata.causationId ?? null,
384927
+ conversationId: null
384928
+ };
384929
+ await sdb.insert(omniEvents).values(newEvent).onConflictDoNothing({ target: omniEvents.id });
384930
+ });
384931
+ } catch (error3) {
384932
+ log124.error("Failed to persist custom event", {
384933
+ eventType: event.type,
384934
+ eventId: event.id,
384935
+ error: String(error3)
384936
+ });
384937
+ }
384938
+ }, { ...CONSUMER_OPTIONS, durable: "event-persistence-custom", startFrom: "new" });
384737
384939
  log124.info("Event persistence initialized - listening for message events");
384738
384940
  } catch (error3) {
384739
384941
  log124.error("Failed to set up event persistence", { error: String(error3) });
@@ -389699,27 +389901,27 @@ var import_discord5 = __toESM(require_src2(), 1);
389699
389901
  // ../channel-discord/src/auth.ts
389700
389902
  init_src();
389701
389903
  var log21 = createLogger("discord:auth");
389702
- async function loadToken(storage, instanceId) {
389904
+ async function loadToken(storage2, instanceId) {
389703
389905
  const key = `${instanceId}:token`;
389704
- const data = await storage.get(key);
389906
+ const data = await storage2.get(key);
389705
389907
  if (data?.token) {
389706
389908
  log21.debug("Loaded token from storage", { instanceId });
389707
389909
  return data.token;
389708
389910
  }
389709
389911
  return null;
389710
389912
  }
389711
- async function saveToken(storage, instanceId, token) {
389913
+ async function saveToken(storage2, instanceId, token) {
389712
389914
  const key = `${instanceId}:token`;
389713
389915
  const data = {
389714
389916
  token,
389715
389917
  storedAt: Date.now()
389716
389918
  };
389717
- await storage.set(key, data);
389919
+ await storage2.set(key, data);
389718
389920
  log21.debug("Saved token to storage", { instanceId });
389719
389921
  }
389720
- async function clearToken(storage, instanceId) {
389922
+ async function clearToken(storage2, instanceId) {
389721
389923
  const key = `${instanceId}:token`;
389722
- await storage.delete(key);
389924
+ await storage2.delete(key);
389723
389925
  log21.debug("Cleared token from storage", { instanceId });
389724
389926
  }
389725
389927
 
@@ -490270,11 +490472,11 @@ class GroupCipher {
490270
490472
  const ret2 = wasm.groupcipher_encrypt(this.__wbg_ptr, ptr0, len0);
490271
490473
  return takeObject(ret2);
490272
490474
  }
490273
- constructor(storage, group_id, sender) {
490475
+ constructor(storage2, group_id, sender) {
490274
490476
  const ptr0 = passStringToWasm0(group_id, wasm.__wbindgen_export, wasm.__wbindgen_export2);
490275
490477
  const len0 = WASM_VECTOR_LEN;
490276
490478
  _assertClass(sender, ProtocolAddress);
490277
- const ret2 = wasm.groupcipher_new(addHeapObject(storage), ptr0, len0, sender.__wbg_ptr);
490479
+ const ret2 = wasm.groupcipher_new(addHeapObject(storage2), ptr0, len0, sender.__wbg_ptr);
490278
490480
  this.__wbg_ptr = ret2 >>> 0;
490279
490481
  GroupCipherFinalization.register(this, this.__wbg_ptr, this);
490280
490482
  return this;
@@ -490299,8 +490501,8 @@ class GroupSessionBuilder {
490299
490501
  const ret2 = wasm.groupsessionbuilder_create(this.__wbg_ptr, sender_key_name.__wbg_ptr);
490300
490502
  return takeObject(ret2);
490301
490503
  }
490302
- constructor(storage) {
490303
- const ret2 = wasm.groupsessionbuilder_new(addHeapObject(storage));
490504
+ constructor(storage2) {
490505
+ const ret2 = wasm.groupsessionbuilder_new(addHeapObject(storage2));
490304
490506
  this.__wbg_ptr = ret2 >>> 0;
490305
490507
  GroupSessionBuilderFinalization.register(this, this.__wbg_ptr, this);
490306
490508
  return this;
@@ -490956,9 +491158,9 @@ class SessionBuilder {
490956
491158
  const ret2 = wasm.sessionbuilder_initOutgoing(this.__wbg_ptr, addHeapObject(bundle_input));
490957
491159
  return takeObject(ret2);
490958
491160
  }
490959
- constructor(storage, remote_address) {
491161
+ constructor(storage2, remote_address) {
490960
491162
  _assertClass(remote_address, ProtocolAddress);
490961
- const ret2 = wasm.sessionbuilder_new(addHeapObject(storage), remote_address.__wbg_ptr);
491163
+ const ret2 = wasm.sessionbuilder_new(addHeapObject(storage2), remote_address.__wbg_ptr);
490962
491164
  this.__wbg_ptr = ret2 >>> 0;
490963
491165
  SessionBuilderFinalization.register(this, this.__wbg_ptr, this);
490964
491166
  return this;
@@ -491004,9 +491206,9 @@ class SessionCipher {
491004
491206
  const ret2 = wasm.sessioncipher_hasOpenSession(this.__wbg_ptr);
491005
491207
  return takeObject(ret2);
491006
491208
  }
491007
- constructor(storage, remote_address) {
491209
+ constructor(storage2, remote_address) {
491008
491210
  _assertClass(remote_address, ProtocolAddress);
491009
- const ret2 = wasm.sessionbuilder_new(addHeapObject(storage), remote_address.__wbg_ptr);
491211
+ const ret2 = wasm.sessionbuilder_new(addHeapObject(storage2), remote_address.__wbg_ptr);
491010
491212
  this.__wbg_ptr = ret2 >>> 0;
491011
491213
  SessionCipherFinalization.register(this, this.__wbg_ptr, this);
491012
491214
  return this;
@@ -499079,8 +499281,8 @@ var CacheableSync = class extends Hookified {
499079
499281
  data
499080
499282
  });
499081
499283
  }
499082
- subscribe(storage, cacheId) {
499083
- this._storage = storage;
499284
+ subscribe(storage2, cacheId) {
499285
+ this._storage = storage2;
499084
499286
  this._cacheId = cacheId;
499085
499287
  const setEvent = this.getPrefixedEvent("cache:set");
499086
499288
  const deleteEvent = this.getPrefixedEvent("cache:delete");
@@ -499088,7 +499290,7 @@ var CacheableSync = class extends Hookified {
499088
499290
  handler: async (message2) => {
499089
499291
  const data = message2.data;
499090
499292
  if (data.cacheId !== cacheId) {
499091
- await storage.set(data.key, data.value, data.ttl);
499293
+ await storage2.set(data.key, data.value, data.ttl);
499092
499294
  }
499093
499295
  }
499094
499296
  });
@@ -499096,7 +499298,7 @@ var CacheableSync = class extends Hookified {
499096
499298
  handler: async (message2) => {
499097
499299
  const data = message2.data;
499098
499300
  if (data.cacheId !== cacheId) {
499099
- await storage.delete(data.key);
499301
+ await storage2.delete(data.key);
499100
499302
  }
499101
499303
  }
499102
499304
  });
@@ -500084,7 +500286,7 @@ var index_default = NodeCache;
500084
500286
 
500085
500287
  // ../../node_modules/.bun/baileys@vendor+baileys-v7.0.0-rc10.tgz+89588f7e3fe8b2e6/node_modules/baileys/lib/Utils/auth-utils.js
500086
500288
  var import_boom10 = __toESM(require_lib7(), 1);
500087
- import { AsyncLocalStorage } from "async_hooks";
500289
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
500088
500290
 
500089
500291
  // ../../node_modules/.bun/async-mutex@0.5.0/node_modules/async-mutex/index.mjs
500090
500292
  var E_TIMEOUT = new Error("timeout while waiting for mutex to become available");
@@ -501060,7 +501262,7 @@ class PreKeyManager {
501060
501262
 
501061
501263
  // ../../node_modules/.bun/baileys@vendor+baileys-v7.0.0-rc10.tgz+89588f7e3fe8b2e6/node_modules/baileys/lib/Utils/auth-utils.js
501062
501264
  var addTransactionCapability = (state, logger5, { maxCommitRetries, delayBetweenTriesMs }) => {
501063
- const txStorage = new AsyncLocalStorage;
501265
+ const txStorage = new AsyncLocalStorage2;
501064
501266
  const keyQueues = new Map;
501065
501267
  const txMutexes = new Map;
501066
501268
  const txMutexRefCounts = new Map;
@@ -503745,7 +503947,7 @@ function extractIdentityFromPkmsg(ciphertext) {
503745
503947
  }
503746
503948
  function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503747
503949
  const lidMapping = new LIDMappingStore(auth.keys, logger5, pnToLIDFunc);
503748
- const storage = signalStorage(auth, lidMapping);
503950
+ const storage2 = signalStorage(auth, lidMapping);
503749
503951
  const parsedKeys = auth.keys;
503750
503952
  const migratedSessionCache = new M({
503751
503953
  ttl: 3 * 24 * 60 * 60 * 1000,
@@ -503757,21 +503959,21 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503757
503959
  const senderNameStr = senderName.toString();
503758
503960
  const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
503759
503961
  if (!senderKey) {
503760
- await storage.storeSenderKey(senderName, new SenderKeyRecord2);
503962
+ await storage2.storeSenderKey(senderName, new SenderKeyRecord2);
503761
503963
  }
503762
- const skdm = await new GroupSessionBuilder2(storage).create(senderName);
503964
+ const skdm = await new GroupSessionBuilder2(storage2).create(senderName);
503763
503965
  return { senderName, skdm };
503764
503966
  };
503765
503967
  const repository = {
503766
503968
  decryptGroupMessage({ group, authorJid, msg }) {
503767
503969
  const senderName = jidToSignalSenderKeyName(group, authorJid);
503768
- const cipher = new GroupCipher2(storage, senderName);
503970
+ const cipher = new GroupCipher2(storage2, senderName);
503769
503971
  return parsedKeys.transaction(async () => {
503770
503972
  return cipher.decrypt(msg);
503771
503973
  }, group);
503772
503974
  },
503773
503975
  async processSenderKeyDistributionMessage({ item, authorJid }) {
503774
- const builder = new GroupSessionBuilder2(storage);
503976
+ const builder = new GroupSessionBuilder2(storage2);
503775
503977
  if (!item.groupId) {
503776
503978
  throw new Error("Group ID is required for sender key distribution message");
503777
503979
  }
@@ -503780,24 +503982,24 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503780
503982
  const senderNameStr = senderName.toString();
503781
503983
  const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
503782
503984
  if (!senderKey) {
503783
- await storage.storeSenderKey(senderName, new SenderKeyRecord2);
503985
+ await storage2.storeSenderKey(senderName, new SenderKeyRecord2);
503784
503986
  }
503785
503987
  return parsedKeys.transaction(async () => {
503786
503988
  const { [senderNameStr]: senderKey2 } = await auth.keys.get("sender-key", [senderNameStr]);
503787
503989
  if (!senderKey2) {
503788
- await storage.storeSenderKey(senderName, new SenderKeyRecord2);
503990
+ await storage2.storeSenderKey(senderName, new SenderKeyRecord2);
503789
503991
  }
503790
503992
  await builder.process(senderName, senderMsg);
503791
503993
  }, item.groupId);
503792
503994
  },
503793
503995
  async decryptMessage({ jid, type, ciphertext }) {
503794
503996
  const addr = jidToSignalProtocolAddress(jid);
503795
- const session = new libsignal.SessionCipher(storage, addr);
503997
+ const session = new libsignal.SessionCipher(storage2, addr);
503796
503998
  if (type === "pkmsg") {
503797
503999
  const identityKey = extractIdentityFromPkmsg(ciphertext);
503798
504000
  if (identityKey) {
503799
504001
  const addrStr = addr.toString();
503800
- const identityChanged = await storage.saveIdentity(addrStr, identityKey);
504002
+ const identityChanged = await storage2.saveIdentity(addrStr, identityKey);
503801
504003
  if (identityChanged) {
503802
504004
  logger5.info({ jid, addr: addrStr }, "identity key changed or new contact, session will be re-established");
503803
504005
  }
@@ -503821,7 +504023,7 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503821
504023
  },
503822
504024
  async encryptMessage({ jid, data }) {
503823
504025
  const addr = jidToSignalProtocolAddress(jid);
503824
- const cipher = new libsignal.SessionCipher(storage, addr);
504026
+ const cipher = new libsignal.SessionCipher(storage2, addr);
503825
504027
  return parsedKeys.transaction(async () => {
503826
504028
  const { type: sigType, body } = await cipher.encrypt(data);
503827
504029
  const type = sigType === 3 ? "pkmsg" : "msg";
@@ -503831,7 +504033,7 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503831
504033
  async encryptGroupMessage({ group, meId, data }) {
503832
504034
  return parsedKeys.transaction(async () => {
503833
504035
  const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
503834
- const ciphertext = await new GroupCipher2(storage, senderName).encrypt(data);
504036
+ const ciphertext = await new GroupCipher2(storage2, senderName).encrypt(data);
503835
504037
  return { ciphertext, senderKeyDistributionMessage: skdm.serialize() };
503836
504038
  }, group);
503837
504039
  },
@@ -503848,7 +504050,7 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503848
504050
  },
503849
504051
  async getSessionInfo(jid) {
503850
504052
  const addr = jidToSignalProtocolAddress(jid).toString();
503851
- const session = await storage.loadSession(addr);
504053
+ const session = await storage2.loadSession(addr);
503852
504054
  if (!session) {
503853
504055
  return null;
503854
504056
  }
@@ -503862,7 +504064,7 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503862
504064
  },
503863
504065
  async injectE2ESession({ jid, session }) {
503864
504066
  logger5.trace({ jid }, "injecting E2EE session");
503865
- const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
504067
+ const cipher = new libsignal.SessionBuilder(storage2, jidToSignalProtocolAddress(jid));
503866
504068
  return parsedKeys.transaction(async () => {
503867
504069
  await cipher.initOutgoing(session);
503868
504070
  }, jid);
@@ -503874,7 +504076,7 @@ function makeLibSignalRepository(auth, logger5, pnToLIDFunc) {
503874
504076
  async validateSession(jid) {
503875
504077
  try {
503876
504078
  const addr = jidToSignalProtocolAddress(jid);
503877
- const session = await storage.loadSession(addr.toString());
504079
+ const session = await storage2.loadSession(addr.toString());
503878
504080
  if (!session) {
503879
504081
  return { exists: false, reason: "no session" };
503880
504082
  }
@@ -511868,11 +512070,11 @@ function deserializeSignalData(type, data) {
511868
512070
  }
511869
512071
  return data;
511870
512072
  }
511871
- async function createStorageAuthState(storage, instanceId) {
512073
+ async function createStorageAuthState(storage2, instanceId) {
511872
512074
  const credsKey = `auth:${instanceId}:creds`;
511873
512075
  const keyPrefix = `auth:${instanceId}:keys`;
511874
512076
  let creds;
511875
- const existingCreds = await storage.get(credsKey);
512077
+ const existingCreds = await storage2.get(credsKey);
511876
512078
  if (existingCreds) {
511877
512079
  if (typeof existingCreds === "string") {
511878
512080
  creds = deserialize(existingCreds);
@@ -511942,10 +512144,10 @@ async function createStorageAuthState(storage, instanceId) {
511942
512144
  const previousPersist = persistQueues.get(key) ?? Promise.resolve();
511943
512145
  const nextPersist = previousPersist.catch(() => {}).then(async () => {
511944
512146
  if (value !== null && value !== undefined) {
511945
- await storage.set(key, serialize(value));
512147
+ await storage2.set(key, serialize(value));
511946
512148
  return;
511947
512149
  }
511948
- await storage.delete(key);
512150
+ await storage2.delete(key);
511949
512151
  }).catch((err2) => {
511950
512152
  if (value !== null && value !== undefined) {
511951
512153
  log50.error("Background key persist failed", { type, id: id.slice(-40), instanceId, err: String(err2) });
@@ -511974,7 +512176,7 @@ async function createStorageAuthState(storage, instanceId) {
511974
512176
  data[id] = deserializeSignalData(type, cached);
511975
512177
  continue;
511976
512178
  }
511977
- const value = await storage.get(key);
512179
+ const value = await storage2.get(key);
511978
512180
  if (value !== null && value !== undefined) {
511979
512181
  const parsed = parseStorageValue(value);
511980
512182
  setCachedValue(key, parsed);
@@ -511996,19 +512198,19 @@ async function createStorageAuthState(storage, instanceId) {
511996
512198
  }
511997
512199
  },
511998
512200
  saveCreds: async () => {
511999
- await storage.set(credsKey, serialize(creds));
512201
+ await storage2.set(credsKey, serialize(creds));
512000
512202
  }
512001
512203
  };
512002
512204
  }
512003
- async function clearAuthState(storage, instanceId) {
512205
+ async function clearAuthState(storage2, instanceId) {
512004
512206
  const credsKey = `auth:${instanceId}:creds`;
512005
512207
  const keyPrefix = `auth:${instanceId}:keys`;
512006
- await storage.delete(credsKey);
512007
- const keys = await storage.keys(`${keyPrefix}:*`);
512208
+ await storage2.delete(credsKey);
512209
+ const keys = await storage2.keys(`${keyPrefix}:*`);
512008
512210
  const batchSize = 50;
512009
512211
  for (let i = 0;i < keys.length; i += batchSize) {
512010
512212
  const batch = keys.slice(i, i + batchSize);
512011
- await Promise.all(batch.map((key) => storage.delete(key)));
512213
+ await Promise.all(batch.map((key) => storage2.delete(key)));
512012
512214
  }
512013
512215
  }
512014
512216