@automagik/omni 2.260407.1 → 2.260409.3
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.
- package/dist/__tests__/mock-api.d.ts.map +1 -1
- package/dist/commands/agents.d.ts +1 -0
- package/dist/commands/agents.d.ts.map +1 -1
- package/dist/commands/events.d.ts.map +1 -1
- package/dist/commands/logs.d.ts.map +1 -1
- package/dist/index.js +105 -2
- package/dist/server/index.js +902 -578
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -222829,7 +222829,7 @@ var init_sentry_scrub = __esm(() => {
|
|
|
222829
222829
|
var require_package8 = __commonJS((exports, module) => {
|
|
222830
222830
|
module.exports = {
|
|
222831
222831
|
name: "@omni/api",
|
|
222832
|
-
version: "2.
|
|
222832
|
+
version: "2.260409.3",
|
|
222833
222833
|
type: "module",
|
|
222834
222834
|
exports: {
|
|
222835
222835
|
".": {
|
|
@@ -237804,28 +237804,6 @@ var init_api_keys = __esm(() => {
|
|
|
237804
237804
|
});
|
|
237805
237805
|
|
|
237806
237806
|
// ../api/src/middleware/auth.ts
|
|
237807
|
-
function requireScope(scope) {
|
|
237808
|
-
return createMiddleware(async (c, next) => {
|
|
237809
|
-
const apiKey = c.get("apiKey");
|
|
237810
|
-
if (!apiKey) {
|
|
237811
|
-
return c.json({
|
|
237812
|
-
error: {
|
|
237813
|
-
code: "UNAUTHORIZED",
|
|
237814
|
-
message: "Authentication required"
|
|
237815
|
-
}
|
|
237816
|
-
}, 401);
|
|
237817
|
-
}
|
|
237818
|
-
if (!ApiKeyService.scopeAllows(apiKey.scopes, scope)) {
|
|
237819
|
-
return c.json({
|
|
237820
|
-
error: {
|
|
237821
|
-
code: "FORBIDDEN",
|
|
237822
|
-
message: `Insufficient permissions. Required scope: ${scope}`
|
|
237823
|
-
}
|
|
237824
|
-
}, 403);
|
|
237825
|
-
}
|
|
237826
|
-
return next();
|
|
237827
|
-
});
|
|
237828
|
-
}
|
|
237829
237807
|
function requireInstanceAccess(instanceIdGetter) {
|
|
237830
237808
|
return createMiddleware(async (c, next) => {
|
|
237831
237809
|
const apiKey = c.get("apiKey");
|
|
@@ -238003,6 +237981,341 @@ var init_body_limit2 = __esm(() => {
|
|
|
238003
237981
|
defaultBodyLimitMiddleware = bodyLimitMiddleware();
|
|
238004
237982
|
});
|
|
238005
237983
|
|
|
237984
|
+
// ../api/src/constants/scopes.ts
|
|
237985
|
+
var DEFAULT_TURN_SCOPES, SCOPE_MAP;
|
|
237986
|
+
var init_scopes = __esm(() => {
|
|
237987
|
+
DEFAULT_TURN_SCOPES = ["messages:send", "turns:close", "tts:synthesize", "context:read"];
|
|
237988
|
+
SCOPE_MAP = {
|
|
237989
|
+
"GET /access/rules": "access:read",
|
|
237990
|
+
"GET /access/rules/:id": "access:read",
|
|
237991
|
+
"POST /access/rules": "access:write",
|
|
237992
|
+
"PATCH /access/rules/:id": "access:write",
|
|
237993
|
+
"DELETE /access/rules/:id": "access:write",
|
|
237994
|
+
"POST /access/check": "access:read",
|
|
237995
|
+
"GET /instances/:instanceId/routes": "routes:read",
|
|
237996
|
+
"GET /instances/:instanceId/routes/:id": "routes:read",
|
|
237997
|
+
"POST /instances/:instanceId/routes": "routes:write",
|
|
237998
|
+
"PATCH /instances/:instanceId/routes/:id": "routes:write",
|
|
237999
|
+
"DELETE /instances/:instanceId/routes/:id": "routes:write",
|
|
238000
|
+
"GET /routes/metrics": "routes:read",
|
|
238001
|
+
"GET /agent-state/stream": "agent-state:read",
|
|
238002
|
+
"GET /agent-state/:agentId/:chatId": "agent-state:read",
|
|
238003
|
+
"PUT /agent-state/:agentId/:chatId": "agent-state:write",
|
|
238004
|
+
"GET /agent-tasks": "agent-tasks:read",
|
|
238005
|
+
"POST /agent-tasks": "agent-tasks:write",
|
|
238006
|
+
"GET /agent-tasks/:id": "agent-tasks:read",
|
|
238007
|
+
"PATCH /agent-tasks/:id": "agent-tasks:write",
|
|
238008
|
+
"DELETE /agent-tasks/:id": "agent-tasks:write",
|
|
238009
|
+
"GET /agents": "agents:read",
|
|
238010
|
+
"GET /agents/:id": "agents:read",
|
|
238011
|
+
"POST /agents": "agents:write",
|
|
238012
|
+
"PATCH /agents/:id": "agents:write",
|
|
238013
|
+
"DELETE /agents/:id": "agents:write",
|
|
238014
|
+
"GET /agents/:id/identities": "agents:read",
|
|
238015
|
+
"POST /agents/:id/identities": "agents:write",
|
|
238016
|
+
"GET /agents/:id/tasks": "agents:read",
|
|
238017
|
+
"POST /auth/validate": "auth:validate",
|
|
238018
|
+
"GET /automations": "automations:read",
|
|
238019
|
+
"GET /automations/:id": "automations:read",
|
|
238020
|
+
"POST /automations": "automations:write",
|
|
238021
|
+
"PATCH /automations/:id": "automations:write",
|
|
238022
|
+
"DELETE /automations/:id": "automations:write",
|
|
238023
|
+
"POST /automations/:id/enable": "automations:write",
|
|
238024
|
+
"POST /automations/:id/disable": "automations:write",
|
|
238025
|
+
"POST /automations/:id/test": "automations:write",
|
|
238026
|
+
"POST /automations/:id/execute": "automations:write",
|
|
238027
|
+
"GET /automations/:id/logs": "automations:read",
|
|
238028
|
+
"GET /automation-logs": "automations:read",
|
|
238029
|
+
"GET /automation-metrics": "automations:read",
|
|
238030
|
+
"POST /batch-jobs": "batch-jobs:write",
|
|
238031
|
+
"GET /batch-jobs": "batch-jobs:read",
|
|
238032
|
+
"POST /batch-jobs/estimate": "batch-jobs:read",
|
|
238033
|
+
"GET /batch-jobs/:id": "batch-jobs:read",
|
|
238034
|
+
"GET /batch-jobs/:id/status": "batch-jobs:read",
|
|
238035
|
+
"POST /batch-jobs/:id/cancel": "batch-jobs:write",
|
|
238036
|
+
"GET /chats": "chats:read",
|
|
238037
|
+
"POST /chats": "chats:write",
|
|
238038
|
+
"GET /chats/:id": "chats:read",
|
|
238039
|
+
"PATCH /chats/:id": "chats:write",
|
|
238040
|
+
"DELETE /chats/:id": "chats:write",
|
|
238041
|
+
"POST /chats/:id/archive": "chats:write",
|
|
238042
|
+
"POST /chats/:id/unarchive": "chats:write",
|
|
238043
|
+
"POST /chats/:id/hide": "chats:write",
|
|
238044
|
+
"POST /chats/:id/unhide": "chats:write",
|
|
238045
|
+
"POST /chats/:id/label": "chats:write",
|
|
238046
|
+
"DELETE /chats/:id/label": "chats:write",
|
|
238047
|
+
"POST /chats/:id/pin": "chats:write",
|
|
238048
|
+
"POST /chats/:id/unpin": "chats:write",
|
|
238049
|
+
"POST /chats/:id/mute": "chats:write",
|
|
238050
|
+
"POST /chats/:id/unmute": "chats:write",
|
|
238051
|
+
"GET /chats/:id/participants": "chats:read",
|
|
238052
|
+
"POST /chats/:id/participants": "chats:write",
|
|
238053
|
+
"DELETE /chats/:id/participants/:platformUserId": "chats:write",
|
|
238054
|
+
"PATCH /chats/:id/participants/:platformUserId": "chats:write",
|
|
238055
|
+
"GET /chats/:id/messages": "chats:read",
|
|
238056
|
+
"GET /chats/by-external": "chats:read",
|
|
238057
|
+
"POST /chats/:id/read": "chats:write",
|
|
238058
|
+
"POST /chats/:id/disappearing": "chats:write",
|
|
238059
|
+
"POST /chats/sync-names": "chats:write",
|
|
238060
|
+
"GET /context": "context:read",
|
|
238061
|
+
"POST /context": "context:write",
|
|
238062
|
+
"POST /context/use": "context:read",
|
|
238063
|
+
"DELETE /context": "context:write",
|
|
238064
|
+
"GET /conversations": "conversations:read",
|
|
238065
|
+
"POST /conversations": "conversations:write",
|
|
238066
|
+
"GET /conversations/:id": "conversations:read",
|
|
238067
|
+
"PATCH /conversations/:id": "conversations:write",
|
|
238068
|
+
"DELETE /conversations/:id": "conversations:write",
|
|
238069
|
+
"GET /conversations/:id/chats": "conversations:read",
|
|
238070
|
+
"GET /dead-letters": "dead-letters:read",
|
|
238071
|
+
"GET /dead-letters/stats": "dead-letters:read",
|
|
238072
|
+
"GET /dead-letters/:id": "dead-letters:read",
|
|
238073
|
+
"POST /dead-letters/:id/retry": "dead-letters:write",
|
|
238074
|
+
"POST /dead-letters/:id/resolve": "dead-letters:write",
|
|
238075
|
+
"POST /dead-letters/:id/abandon": "dead-letters:write",
|
|
238076
|
+
"GET /event-ops/metrics": "event-ops:read",
|
|
238077
|
+
"POST /event-ops/replay": "event-ops:write",
|
|
238078
|
+
"GET /event-ops/replay": "event-ops:read",
|
|
238079
|
+
"GET /event-ops/replay/:id": "event-ops:read",
|
|
238080
|
+
"DELETE /event-ops/replay/:id": "event-ops:write",
|
|
238081
|
+
"POST /event-ops/scheduled": "event-ops:write",
|
|
238082
|
+
"GET /events": "events:read",
|
|
238083
|
+
"GET /events/analytics": "events:read",
|
|
238084
|
+
"GET /events/timeline/:personId": "events:read",
|
|
238085
|
+
"POST /events/search": "events:read",
|
|
238086
|
+
"GET /events/:id": "events:read",
|
|
238087
|
+
"GET /events/by-sender/:senderId": "events:read",
|
|
238088
|
+
"GET /instances": "instances:read",
|
|
238089
|
+
"GET /instances/supported-channels": "instances:read",
|
|
238090
|
+
"GET /instances/:id": "instances:read",
|
|
238091
|
+
"POST /instances": "instances:write",
|
|
238092
|
+
"PATCH /instances/:id": "instances:write",
|
|
238093
|
+
"DELETE /instances/:id": "instances:write",
|
|
238094
|
+
"GET /instances/:id/status": "instances:read",
|
|
238095
|
+
"GET /instances/:id/qr": "instances:read",
|
|
238096
|
+
"POST /instances/:id/pair": "instances:write",
|
|
238097
|
+
"POST /instances/:id/connect": "instances:write",
|
|
238098
|
+
"POST /instances/:id/disconnect": "instances:write",
|
|
238099
|
+
"POST /instances/:id/restart": "instances:write",
|
|
238100
|
+
"POST /instances/:id/logout": "instances:write",
|
|
238101
|
+
"POST /instances/:id/sync/profile": "instances:write",
|
|
238102
|
+
"PUT /instances/:id/profile/name": "instances:write",
|
|
238103
|
+
"POST /instances/:id/sync": "instances:write",
|
|
238104
|
+
"GET /instances/:id/sync/:jobId": "instances:read",
|
|
238105
|
+
"GET /instances/:id/sync": "instances:read",
|
|
238106
|
+
"GET /instances/:id/users/:userId/profile": "instances:read",
|
|
238107
|
+
"GET /instances/:id/contacts": "instances:read",
|
|
238108
|
+
"GET /instances/:id/groups": "instances:read",
|
|
238109
|
+
"GET /instances/:id/groups/:jid/members": "instances:read",
|
|
238110
|
+
"POST /instances/:id/check-number": "instances:read",
|
|
238111
|
+
"PUT /instances/:id/profile/status": "instances:write",
|
|
238112
|
+
"POST /instances/:id/block": "instances:write",
|
|
238113
|
+
"DELETE /instances/:id/block": "instances:write",
|
|
238114
|
+
"GET /instances/:id/blocklist": "instances:read",
|
|
238115
|
+
"PUT /instances/:id/profile/picture": "instances:write",
|
|
238116
|
+
"DELETE /instances/:id/profile/picture": "instances:write",
|
|
238117
|
+
"POST /instances/:id/groups": "instances:write",
|
|
238118
|
+
"GET /instances/:id/chats/:chatId/invite": "instances:read",
|
|
238119
|
+
"GET /instances/:id/groups/:groupJid/invite": "instances:read",
|
|
238120
|
+
"POST /instances/:id/groups/:groupJid/invite/revoke": "instances:write",
|
|
238121
|
+
"POST /instances/:id/groups/join": "instances:write",
|
|
238122
|
+
"PUT /instances/:id/groups/:groupJid/picture": "instances:write",
|
|
238123
|
+
"GET /instances/:id/privacy": "instances:read",
|
|
238124
|
+
"POST /instances/:id/calls/reject": "instances:write",
|
|
238125
|
+
"POST /instances/:id/resync": "instances:write",
|
|
238126
|
+
"POST /instances/:id/replay": "instances:write",
|
|
238127
|
+
"GET /instances/:id/pairing-requests": "instances:read",
|
|
238128
|
+
"POST /instances/:id/pairing-requests/:requestId/action": "instances:write",
|
|
238129
|
+
"GET /instances/:id/guilds": "instances:read",
|
|
238130
|
+
"GET /instances/:id/guilds/:guildId/config": "instances:read",
|
|
238131
|
+
"PUT /instances/:id/guilds/:guildId/config": "instances:write",
|
|
238132
|
+
"DELETE /instances/:id/guilds/:guildId/config": "instances:write",
|
|
238133
|
+
"GET /instances/:id/guilds/:guildId/audit": "instances:read",
|
|
238134
|
+
"PUT /instances/:id/presence": "instances:write",
|
|
238135
|
+
"GET /journeys/summary": "journeys:read",
|
|
238136
|
+
"GET /journeys/:correlationId": "journeys:read",
|
|
238137
|
+
"POST /keys": "keys:write",
|
|
238138
|
+
"GET /keys": "keys:read",
|
|
238139
|
+
"GET /keys/:id": "keys:read",
|
|
238140
|
+
"PATCH /keys/:id": "keys:write",
|
|
238141
|
+
"POST /keys/:id/revoke": "keys:write",
|
|
238142
|
+
"DELETE /keys/:id": "keys:write",
|
|
238143
|
+
"GET /keys/:id/audit": "keys:read",
|
|
238144
|
+
"GET /logs/stream": "logs:read",
|
|
238145
|
+
"GET /logs/recent": "logs:read",
|
|
238146
|
+
"POST /media/tts": "tts:synthesize",
|
|
238147
|
+
"POST /media/stt": "media:write",
|
|
238148
|
+
"POST /media/imagine": "media:write",
|
|
238149
|
+
"POST /media/vision": "media:read",
|
|
238150
|
+
"POST /media/film": "media:write",
|
|
238151
|
+
"GET /media/:instanceId/*": "media:read",
|
|
238152
|
+
"GET /messages": "messages:read",
|
|
238153
|
+
"GET /messages/by-external": "messages:read",
|
|
238154
|
+
"POST /messages/media/download": "messages:read",
|
|
238155
|
+
"POST /messages": "messages:write",
|
|
238156
|
+
"GET /messages/:id": "messages:read",
|
|
238157
|
+
"PATCH /messages/:id": "messages:write",
|
|
238158
|
+
"DELETE /messages/:id": "messages:write",
|
|
238159
|
+
"POST /messages/:id/edit": "messages:write",
|
|
238160
|
+
"POST /messages/:id/reactions": "messages:write",
|
|
238161
|
+
"DELETE /messages/:id/reactions": "messages:write",
|
|
238162
|
+
"PATCH /messages/:id/delivery-status": "messages:write",
|
|
238163
|
+
"PATCH /messages/:id/transcription": "messages:write",
|
|
238164
|
+
"PATCH /messages/:id/image-description": "messages:write",
|
|
238165
|
+
"PATCH /messages/:id/video-description": "messages:write",
|
|
238166
|
+
"PATCH /messages/:id/document-extraction": "messages:write",
|
|
238167
|
+
"POST /messages/send": "messages:send",
|
|
238168
|
+
"POST /messages/send/media": "messages:send",
|
|
238169
|
+
"POST /messages/send/reaction": "messages:send",
|
|
238170
|
+
"POST /messages/send/sticker": "messages:send",
|
|
238171
|
+
"POST /messages/send/contact": "messages:send",
|
|
238172
|
+
"POST /messages/send/location": "messages:send",
|
|
238173
|
+
"GET /messages/tts/voices": "messages:read",
|
|
238174
|
+
"POST /messages/send/tts": "messages:send",
|
|
238175
|
+
"POST /messages/send/forward": "messages:send",
|
|
238176
|
+
"POST /messages/send/presence": "messages:send",
|
|
238177
|
+
"POST /messages/:id/read": "messages:write",
|
|
238178
|
+
"POST /messages/read": "messages:write",
|
|
238179
|
+
"POST /messages/send/poll": "messages:send",
|
|
238180
|
+
"POST /messages/send/embed": "messages:send",
|
|
238181
|
+
"POST /messages/edit-channel": "messages:send",
|
|
238182
|
+
"POST /messages/delete-channel": "messages:send",
|
|
238183
|
+
"POST /messages/:id/star": "messages:write",
|
|
238184
|
+
"DELETE /messages/:id/star": "messages:write",
|
|
238185
|
+
"GET /metrics": "metrics:read",
|
|
238186
|
+
"GET /events/:eventId/payloads": "payloads:read",
|
|
238187
|
+
"GET /events/:eventId/payloads/:stage": "payloads:read",
|
|
238188
|
+
"DELETE /events/:eventId/payloads": "payloads:write",
|
|
238189
|
+
"GET /payload-config": "payloads:read",
|
|
238190
|
+
"PUT /payload-config/:eventType": "payloads:write",
|
|
238191
|
+
"GET /payload-stats": "payloads:read",
|
|
238192
|
+
"GET /persons": "persons:read",
|
|
238193
|
+
"GET /persons/:id": "persons:read",
|
|
238194
|
+
"PATCH /persons/:id": "persons:write",
|
|
238195
|
+
"GET /persons/:id/presence": "persons:read",
|
|
238196
|
+
"GET /persons/:id/timeline": "persons:read",
|
|
238197
|
+
"POST /persons/link": "persons:write",
|
|
238198
|
+
"POST /persons/unlink": "persons:write",
|
|
238199
|
+
"POST /persons/merge": "persons:write",
|
|
238200
|
+
"GET /providers": "providers:read",
|
|
238201
|
+
"GET /providers/:id": "providers:read",
|
|
238202
|
+
"POST /providers": "providers:write",
|
|
238203
|
+
"PATCH /providers/:id": "providers:write",
|
|
238204
|
+
"DELETE /providers/:id": "providers:write",
|
|
238205
|
+
"POST /providers/:id/health": "providers:read",
|
|
238206
|
+
"GET /providers/:id/agents": "providers:read",
|
|
238207
|
+
"GET /providers/:id/teams": "providers:read",
|
|
238208
|
+
"GET /providers/:id/workflows": "providers:read",
|
|
238209
|
+
"GET /settings": "settings:read",
|
|
238210
|
+
"GET /settings/:key": "settings:read",
|
|
238211
|
+
"PUT /settings/:key": "settings:write",
|
|
238212
|
+
"PATCH /settings": "settings:write",
|
|
238213
|
+
"DELETE /settings/:key": "settings:write",
|
|
238214
|
+
"GET /settings/:key/history": "settings:read",
|
|
238215
|
+
"POST /turns/close": "turns:close",
|
|
238216
|
+
"GET /webhook-sources": "webhooks:read",
|
|
238217
|
+
"GET /webhook-sources/:id": "webhooks:read",
|
|
238218
|
+
"POST /webhook-sources": "webhooks:write",
|
|
238219
|
+
"PATCH /webhook-sources/:id": "webhooks:write",
|
|
238220
|
+
"DELETE /webhook-sources/:id": "webhooks:write",
|
|
238221
|
+
"POST /webhooks/:source": "webhooks:write",
|
|
238222
|
+
"POST /events/trigger": "events:write"
|
|
238223
|
+
};
|
|
238224
|
+
});
|
|
238225
|
+
|
|
238226
|
+
// ../api/src/middleware/scope-enforcer.ts
|
|
238227
|
+
function buildSegmentRegex(patternPath) {
|
|
238228
|
+
const escaped = patternPath.split("/").map((seg) => seg.startsWith(":") ? "[^/]+" : seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/");
|
|
238229
|
+
return new RegExp(`^${escaped}$`);
|
|
238230
|
+
}
|
|
238231
|
+
function matchesWildcard(patternPath, cleanPath) {
|
|
238232
|
+
const prefix = patternPath.slice(0, -2);
|
|
238233
|
+
const prefixRegex = buildSegmentRegex(prefix);
|
|
238234
|
+
return prefixRegex.test(cleanPath) || new RegExp(`^${prefixRegex.source.slice(0, -1)}/.+$`).test(cleanPath);
|
|
238235
|
+
}
|
|
238236
|
+
function matchesSegments(patternPath, cleanPath) {
|
|
238237
|
+
const patternSegments = patternPath.split("/");
|
|
238238
|
+
const pathSegments = cleanPath.split("/");
|
|
238239
|
+
if (patternSegments.length !== pathSegments.length)
|
|
238240
|
+
return false;
|
|
238241
|
+
for (let i = 0;i < patternSegments.length; i++) {
|
|
238242
|
+
if (patternSegments[i]?.startsWith(":"))
|
|
238243
|
+
continue;
|
|
238244
|
+
if (patternSegments[i] !== pathSegments[i])
|
|
238245
|
+
return false;
|
|
238246
|
+
}
|
|
238247
|
+
return true;
|
|
238248
|
+
}
|
|
238249
|
+
function normalizePath2(path3) {
|
|
238250
|
+
const stripped = path3.replace(/^\/api\/v2/, "");
|
|
238251
|
+
return stripped.endsWith("/") && stripped.length > 1 ? stripped.slice(0, -1) : stripped;
|
|
238252
|
+
}
|
|
238253
|
+
function findRequiredScope(method, path3) {
|
|
238254
|
+
const cleanPath = normalizePath2(path3);
|
|
238255
|
+
const exactKey = `${method} ${cleanPath}`;
|
|
238256
|
+
if (SCOPE_MAP[exactKey])
|
|
238257
|
+
return SCOPE_MAP[exactKey];
|
|
238258
|
+
for (const [pattern, scope] of Object.entries(SCOPE_MAP)) {
|
|
238259
|
+
const spaceIdx = pattern.indexOf(" ");
|
|
238260
|
+
const patternMethod = pattern.slice(0, spaceIdx);
|
|
238261
|
+
if (patternMethod !== method)
|
|
238262
|
+
continue;
|
|
238263
|
+
const patternPath = pattern.slice(spaceIdx + 1);
|
|
238264
|
+
if (patternPath.endsWith("/*")) {
|
|
238265
|
+
if (matchesWildcard(patternPath, cleanPath))
|
|
238266
|
+
return scope;
|
|
238267
|
+
continue;
|
|
238268
|
+
}
|
|
238269
|
+
if (matchesSegments(patternPath, cleanPath))
|
|
238270
|
+
return scope;
|
|
238271
|
+
}
|
|
238272
|
+
return;
|
|
238273
|
+
}
|
|
238274
|
+
var log56, scopeEnforcerMiddleware;
|
|
238275
|
+
var init_scope_enforcer = __esm(() => {
|
|
238276
|
+
init_src();
|
|
238277
|
+
init_factory2();
|
|
238278
|
+
init_scopes();
|
|
238279
|
+
init_api_keys();
|
|
238280
|
+
log56 = createLogger("api:scope-enforcer");
|
|
238281
|
+
scopeEnforcerMiddleware = createMiddleware(async (c, next) => {
|
|
238282
|
+
const apiKey = c.get("apiKey");
|
|
238283
|
+
if (!apiKey) {
|
|
238284
|
+
return c.json({
|
|
238285
|
+
error: {
|
|
238286
|
+
code: "UNAUTHORIZED",
|
|
238287
|
+
message: "Authentication required"
|
|
238288
|
+
}
|
|
238289
|
+
}, 401);
|
|
238290
|
+
}
|
|
238291
|
+
if (ApiKeyService.scopeAllows(apiKey.scopes, "*")) {
|
|
238292
|
+
return next();
|
|
238293
|
+
}
|
|
238294
|
+
const method = c.req.method.toUpperCase();
|
|
238295
|
+
const path3 = c.req.path;
|
|
238296
|
+
const requiredScope = findRequiredScope(method, path3);
|
|
238297
|
+
if (!requiredScope) {
|
|
238298
|
+
log56.warn(`DENIED: key=${apiKey.id} route=${method} ${path3} required=UNMAPPED`);
|
|
238299
|
+
return c.json({
|
|
238300
|
+
error: {
|
|
238301
|
+
code: "FORBIDDEN",
|
|
238302
|
+
message: "Insufficient permissions. Route not mapped in scope policy."
|
|
238303
|
+
}
|
|
238304
|
+
}, 403);
|
|
238305
|
+
}
|
|
238306
|
+
if (!ApiKeyService.scopeAllows(apiKey.scopes, requiredScope)) {
|
|
238307
|
+
log56.warn(`DENIED: key=${apiKey.id} route=${method} ${path3} required=${requiredScope}`);
|
|
238308
|
+
return c.json({
|
|
238309
|
+
error: {
|
|
238310
|
+
code: "FORBIDDEN",
|
|
238311
|
+
message: `Insufficient permissions. Required scope: ${requiredScope}`
|
|
238312
|
+
}
|
|
238313
|
+
}, 403);
|
|
238314
|
+
}
|
|
238315
|
+
return next();
|
|
238316
|
+
});
|
|
238317
|
+
});
|
|
238318
|
+
|
|
238006
238319
|
// ../api/src/providers/elevenlabs/tts.ts
|
|
238007
238320
|
class ElevenLabsTtsProvider {
|
|
238008
238321
|
service;
|
|
@@ -241397,7 +241710,7 @@ var require_logging_utils = __commonJS((exports) => {
|
|
|
241397
241710
|
exports.getDebugBackend = getDebugBackend;
|
|
241398
241711
|
exports.getStructuredBackend = getStructuredBackend;
|
|
241399
241712
|
exports.setBackend = setBackend;
|
|
241400
|
-
exports.log =
|
|
241713
|
+
exports.log = log57;
|
|
241401
241714
|
var events_1 = __require("events");
|
|
241402
241715
|
var process3 = __importStar(__require("process"));
|
|
241403
241716
|
var util4 = __importStar(__require("util"));
|
|
@@ -241424,7 +241737,7 @@ var require_logging_utils = __commonJS((exports) => {
|
|
|
241424
241737
|
this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args);
|
|
241425
241738
|
this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args);
|
|
241426
241739
|
this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args);
|
|
241427
|
-
this.func.sublog = (namespace2) =>
|
|
241740
|
+
this.func.sublog = (namespace2) => log57(namespace2, this.func);
|
|
241428
241741
|
}
|
|
241429
241742
|
invoke(fields, ...args) {
|
|
241430
241743
|
if (this.upstream) {
|
|
@@ -241585,7 +241898,7 @@ var require_logging_utils = __commonJS((exports) => {
|
|
|
241585
241898
|
cachedBackend = backend;
|
|
241586
241899
|
loggerCache.clear();
|
|
241587
241900
|
}
|
|
241588
|
-
function
|
|
241901
|
+
function log57(namespace, parent) {
|
|
241589
241902
|
if (!cachedBackend) {
|
|
241590
241903
|
const enablesFlag = process3.env[exports.env.nodeEnables];
|
|
241591
241904
|
if (!enablesFlag) {
|
|
@@ -241725,7 +242038,7 @@ var require_src43 = __commonJS((exports) => {
|
|
|
241725
242038
|
exports.HEADER_NAME = "Metadata-Flavor";
|
|
241726
242039
|
exports.HEADER_VALUE = "Google";
|
|
241727
242040
|
exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });
|
|
241728
|
-
var
|
|
242041
|
+
var log57 = logger6.log("gcp-metadata");
|
|
241729
242042
|
exports.METADATA_SERVER_DETECTION = Object.freeze({
|
|
241730
242043
|
"assume-present": "don't try to ping the metadata server, but assume it's present",
|
|
241731
242044
|
none: "don't try to ping the metadata server, but don't try to use it either",
|
|
@@ -241788,9 +242101,9 @@ var require_src43 = __commonJS((exports) => {
|
|
|
241788
242101
|
responseType: "text",
|
|
241789
242102
|
timeout: requestTimeout()
|
|
241790
242103
|
};
|
|
241791
|
-
|
|
242104
|
+
log57.info("instance request %j", req);
|
|
241792
242105
|
const res = await requestMethod(req);
|
|
241793
|
-
|
|
242106
|
+
log57.info("instance metadata is %s", res.data);
|
|
241794
242107
|
const metadataFlavor = res.headers.get(exports.HEADER_NAME);
|
|
241795
242108
|
if (metadataFlavor !== exports.HEADER_VALUE) {
|
|
241796
242109
|
throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : "no header"}`);
|
|
@@ -263278,7 +263591,7 @@ function getGeminiClient(apiKey) {
|
|
|
263278
263591
|
if (clientInstance && clientApiKey === apiKey) {
|
|
263279
263592
|
return clientInstance;
|
|
263280
263593
|
}
|
|
263281
|
-
|
|
263594
|
+
log57.info("Initializing Gemini client");
|
|
263282
263595
|
clientInstance = new GoogleGenAI({ apiKey });
|
|
263283
263596
|
clientApiKey = apiKey;
|
|
263284
263597
|
return clientInstance;
|
|
@@ -263290,11 +263603,11 @@ async function resolveGeminiApiKey(settings) {
|
|
|
263290
263603
|
}
|
|
263291
263604
|
return apiKey;
|
|
263292
263605
|
}
|
|
263293
|
-
var
|
|
263606
|
+
var log57, GEMINI_MODELS, clientInstance = null, clientApiKey = null;
|
|
263294
263607
|
var init_client6 = __esm(() => {
|
|
263295
263608
|
init_node3();
|
|
263296
263609
|
init_src();
|
|
263297
|
-
|
|
263610
|
+
log57 = createLogger("gemini");
|
|
263298
263611
|
GEMINI_MODELS = {
|
|
263299
263612
|
FLASH: "gemini-2.0-flash",
|
|
263300
263613
|
PRO: "gemini-2.5-pro-preview-06-05",
|
|
@@ -263315,7 +263628,7 @@ function resolveModel(alias3) {
|
|
|
263315
263628
|
return resolved;
|
|
263316
263629
|
if (alias3.startsWith("gemini-"))
|
|
263317
263630
|
return alias3;
|
|
263318
|
-
|
|
263631
|
+
log58.warn("Unknown image model alias, falling back to default", {
|
|
263319
263632
|
alias: alias3,
|
|
263320
263633
|
fallback: DEFAULT_MODEL_ALIAS
|
|
263321
263634
|
});
|
|
@@ -263383,7 +263696,7 @@ class GeminiImageGenProvider {
|
|
|
263383
263696
|
const modelSetting = await this.settings.getString("imagegen.model", "GEMINI_IMAGE_MODEL", DEFAULT_MODEL_ALIAS);
|
|
263384
263697
|
const model = resolveModel(options?.model || modelSetting);
|
|
263385
263698
|
const count3 = Math.max(1, Math.min(options?.count ?? 1, 4));
|
|
263386
|
-
|
|
263699
|
+
log58.info("Generating image(s)", {
|
|
263387
263700
|
model,
|
|
263388
263701
|
promptLength: prompt.length,
|
|
263389
263702
|
count: count3,
|
|
@@ -263400,7 +263713,7 @@ class GeminiImageGenProvider {
|
|
|
263400
263713
|
});
|
|
263401
263714
|
} catch (err) {
|
|
263402
263715
|
const message2 = err instanceof Error ? err.message : String(err);
|
|
263403
|
-
|
|
263716
|
+
log58.error("Gemini image generation failed", { model, error: message2 });
|
|
263404
263717
|
throw new Error(`Gemini image generation failed: ${message2}`);
|
|
263405
263718
|
}
|
|
263406
263719
|
const images = collectImages(response.candidates ?? []);
|
|
@@ -263409,7 +263722,7 @@ class GeminiImageGenProvider {
|
|
|
263409
263722
|
throw new Error(text3 ? `Gemini returned no image (model responded with text: "${text3.slice(0, 200)}")` : "Gemini returned no image in response");
|
|
263410
263723
|
}
|
|
263411
263724
|
const processingMs = Date.now() - started;
|
|
263412
|
-
|
|
263725
|
+
log58.info("Image generation complete", {
|
|
263413
263726
|
model,
|
|
263414
263727
|
imageCount: images.length,
|
|
263415
263728
|
processingMs,
|
|
@@ -263418,11 +263731,11 @@ class GeminiImageGenProvider {
|
|
|
263418
263731
|
return { images, processingMs };
|
|
263419
263732
|
}
|
|
263420
263733
|
}
|
|
263421
|
-
var
|
|
263734
|
+
var log58, MODEL_ALIASES, DEFAULT_MODEL_ALIAS = "nano-banana-2";
|
|
263422
263735
|
var init_imagegen = __esm(() => {
|
|
263423
263736
|
init_src();
|
|
263424
263737
|
init_client6();
|
|
263425
|
-
|
|
263738
|
+
log58 = createLogger("gemini-imagegen");
|
|
263426
263739
|
MODEL_ALIASES = {
|
|
263427
263740
|
"nano-banana-2": "gemini-3.1-flash-image-preview",
|
|
263428
263741
|
"nano-banana-pro": "gemini-3.1-pro-image-preview",
|
|
@@ -263455,7 +263768,7 @@ class GeminiSttProvider {
|
|
|
263455
263768
|
if (wantTimestamps) {
|
|
263456
263769
|
promptParts.push('Return a JSON object with this exact shape: {"text": "full transcript", "segments": [{"text": "...", "startMs": 0, "endMs": 1000}]}', "Do not wrap the JSON in markdown code fences.");
|
|
263457
263770
|
}
|
|
263458
|
-
|
|
263771
|
+
log59.debug("Calling Gemini STT", { model, mimeType, sizeBytes: audio.length, wantTimestamps, language });
|
|
263459
263772
|
const response = await client.models.generateContent({
|
|
263460
263773
|
model,
|
|
263461
263774
|
contents: [
|
|
@@ -263494,7 +263807,7 @@ class GeminiSttProvider {
|
|
|
263494
263807
|
processingMs
|
|
263495
263808
|
};
|
|
263496
263809
|
} catch (err) {
|
|
263497
|
-
|
|
263810
|
+
log59.warn("Failed to parse Gemini STT JSON response, falling back to raw text", {
|
|
263498
263811
|
error: err instanceof Error ? err.message : String(err)
|
|
263499
263812
|
});
|
|
263500
263813
|
return {
|
|
@@ -263515,11 +263828,11 @@ function normalizeAudioMimeType(mimeType) {
|
|
|
263515
263828
|
return "audio/ogg";
|
|
263516
263829
|
return lower;
|
|
263517
263830
|
}
|
|
263518
|
-
var
|
|
263831
|
+
var log59;
|
|
263519
263832
|
var init_stt = __esm(() => {
|
|
263520
263833
|
init_src();
|
|
263521
263834
|
init_client6();
|
|
263522
|
-
|
|
263835
|
+
log59 = createLogger("provider:gemini:stt");
|
|
263523
263836
|
});
|
|
263524
263837
|
|
|
263525
263838
|
// ../api/src/providers/gemini/tts.ts
|
|
@@ -263542,7 +263855,7 @@ class GeminiTtsProvider {
|
|
|
263542
263855
|
const client = getGeminiClient(apiKey);
|
|
263543
263856
|
const voice = options?.voice || DEFAULT_VOICE;
|
|
263544
263857
|
const prompt = options?.style ? `${options.style}: ${text3}` : text3;
|
|
263545
|
-
|
|
263858
|
+
log60.debug("Generating speech", { voice, textLen: text3.length, hasStyle: !!options?.style });
|
|
263546
263859
|
const response = await client.models.generateContent({
|
|
263547
263860
|
model: GEMINI_MODELS.TTS,
|
|
263548
263861
|
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
@@ -263717,11 +264030,11 @@ async function getAudioDurationMs(audioBuffer) {
|
|
|
263717
264030
|
await fs11.unlink(tempPath).catch(() => {});
|
|
263718
264031
|
}
|
|
263719
264032
|
}
|
|
263720
|
-
var
|
|
264033
|
+
var log60, GEMINI_VOICES, DEFAULT_VOICE = "Kore";
|
|
263721
264034
|
var init_tts = __esm(() => {
|
|
263722
264035
|
init_src();
|
|
263723
264036
|
init_client6();
|
|
263724
|
-
|
|
264037
|
+
log60 = createLogger("gemini-tts");
|
|
263725
264038
|
GEMINI_VOICES = [
|
|
263726
264039
|
{ id: "Zephyr", name: "Zephyr", provider: "gemini", gender: "female" },
|
|
263727
264040
|
{ id: "Puck", name: "Puck", provider: "gemini", gender: "male" },
|
|
@@ -263770,7 +264083,7 @@ class GeminiVideoGenProvider {
|
|
|
263770
264083
|
const apiKey = await resolveGeminiApiKey(this.settings);
|
|
263771
264084
|
const client = getGeminiClient(apiKey);
|
|
263772
264085
|
const aspectRatio = options?.aspectRatio === "9:16" || options?.aspectRatio === "16:9" ? options.aspectRatio : "16:9";
|
|
263773
|
-
|
|
264086
|
+
log61.info("Submitting Veo 3.1 video generation", {
|
|
263774
264087
|
promptLen: prompt.length,
|
|
263775
264088
|
aspectRatio,
|
|
263776
264089
|
durationSec: options?.durationSec
|
|
@@ -263814,7 +264127,7 @@ class GeminiVideoGenProvider {
|
|
|
263814
264127
|
if (operation.error) {
|
|
263815
264128
|
activeOperations.delete(operationId);
|
|
263816
264129
|
const message2 = operation.error.message ?? JSON.stringify(operation.error) ?? "Unknown error";
|
|
263817
|
-
|
|
264130
|
+
log61.warn("Veo operation failed", { operationId, message: message2 });
|
|
263818
264131
|
return { operationId, state: "failed", error: message2 };
|
|
263819
264132
|
}
|
|
263820
264133
|
if (!operation.done) {
|
|
@@ -263835,11 +264148,11 @@ class GeminiVideoGenProvider {
|
|
|
263835
264148
|
} catch (err) {
|
|
263836
264149
|
activeOperations.delete(operationId);
|
|
263837
264150
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
263838
|
-
|
|
264151
|
+
log61.error("Failed to download Veo video", { operationId, error: message2 });
|
|
263839
264152
|
return { operationId, state: "failed", error: `Failed to download video: ${message2}` };
|
|
263840
264153
|
}
|
|
263841
264154
|
activeOperations.delete(operationId);
|
|
263842
|
-
|
|
264155
|
+
log61.info("Veo operation complete", {
|
|
263843
264156
|
operationId,
|
|
263844
264157
|
sizeBytes: video.data.length,
|
|
263845
264158
|
mimeType: video.mimeType
|
|
@@ -263867,11 +264180,11 @@ class GeminiVideoGenProvider {
|
|
|
263867
264180
|
return { data, mimeType, durationMs: 0 };
|
|
263868
264181
|
}
|
|
263869
264182
|
}
|
|
263870
|
-
var
|
|
264183
|
+
var log61, activeOperations;
|
|
263871
264184
|
var init_videogen = __esm(() => {
|
|
263872
264185
|
init_src();
|
|
263873
264186
|
init_client6();
|
|
263874
|
-
|
|
264187
|
+
log61 = createLogger("gemini-videogen");
|
|
263875
264188
|
activeOperations = new Map;
|
|
263876
264189
|
});
|
|
263877
264190
|
|
|
@@ -263889,7 +264202,7 @@ class GeminiVisionProvider {
|
|
|
263889
264202
|
const model = await this.settings.getString("vision.model", "GEMINI_VISION_MODEL", DEFAULT_VISION_MODEL);
|
|
263890
264203
|
const prompt = this.buildPrompt(options);
|
|
263891
264204
|
const base64 = media.toString("base64");
|
|
263892
|
-
|
|
264205
|
+
log62.info("Describing media", {
|
|
263893
264206
|
model,
|
|
263894
264207
|
mimeType,
|
|
263895
264208
|
sizeBytes: media.length,
|
|
@@ -263919,10 +264232,10 @@ class GeminiVisionProvider {
|
|
|
263919
264232
|
throw new Error("Gemini returned empty vision response");
|
|
263920
264233
|
}
|
|
263921
264234
|
const processingMs = Date.now() - started;
|
|
263922
|
-
|
|
264235
|
+
log62.info("Vision description complete", { processingMs, textLength: text3.length });
|
|
263923
264236
|
return { text: text3, processingMs };
|
|
263924
264237
|
} catch (err) {
|
|
263925
|
-
|
|
264238
|
+
log62.error("Vision description failed", {
|
|
263926
264239
|
error: err instanceof Error ? err.message : String(err)
|
|
263927
264240
|
});
|
|
263928
264241
|
throw err;
|
|
@@ -263938,11 +264251,11 @@ ${base2}`;
|
|
|
263938
264251
|
return base2;
|
|
263939
264252
|
}
|
|
263940
264253
|
}
|
|
263941
|
-
var
|
|
264254
|
+
var log62, DEFAULT_VISION_MODEL = "gemini-3.1-flash-lite-preview", DEFAULT_PROMPT = "Describe this image in clear, concise detail. Mention key subjects, actions, colors, setting, and any legible text.";
|
|
263942
264255
|
var init_vision = __esm(() => {
|
|
263943
264256
|
init_src();
|
|
263944
264257
|
init_client6();
|
|
263945
|
-
|
|
264258
|
+
log62 = createLogger("gemini-vision");
|
|
263946
264259
|
});
|
|
263947
264260
|
|
|
263948
264261
|
// ../api/src/providers/groq/stt.ts
|
|
@@ -263971,7 +264284,7 @@ class GroqSttProvider {
|
|
|
263971
264284
|
if (wantTimestamps) {
|
|
263972
264285
|
form.append("timestamp_granularities[]", "segment");
|
|
263973
264286
|
}
|
|
263974
|
-
|
|
264287
|
+
log63.debug("Calling Groq Whisper", {
|
|
263975
264288
|
model,
|
|
263976
264289
|
mimeType,
|
|
263977
264290
|
sizeBytes: audio.length,
|
|
@@ -264017,18 +264330,18 @@ function guessFilename(mimeType) {
|
|
|
264017
264330
|
const ext = subtype.replace("mpeg", "mp3").replace("x-m4a", "m4a").replace("mp4", "m4a").replace("quicktime", "mov");
|
|
264018
264331
|
return `audio.${ext}`;
|
|
264019
264332
|
}
|
|
264020
|
-
var
|
|
264333
|
+
var log63, GROQ_MAX_BYTES, GROQ_STT_MODEL = "whisper-large-v3-turbo", GROQ_TRANSCRIPTION_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
|
|
264021
264334
|
var init_stt2 = __esm(() => {
|
|
264022
264335
|
init_src();
|
|
264023
|
-
|
|
264336
|
+
log63 = createLogger("provider:groq:stt");
|
|
264024
264337
|
GROQ_MAX_BYTES = 19.5 * 1024 * 1024;
|
|
264025
264338
|
});
|
|
264026
264339
|
|
|
264027
264340
|
// ../api/src/providers/registry.ts
|
|
264028
|
-
var
|
|
264341
|
+
var log64, ProviderRegistry, providerRegistry;
|
|
264029
264342
|
var init_registry3 = __esm(() => {
|
|
264030
264343
|
init_src();
|
|
264031
|
-
|
|
264344
|
+
log64 = createLogger("provider-registry");
|
|
264032
264345
|
ProviderRegistry = class ProviderRegistry {
|
|
264033
264346
|
providers = new Map;
|
|
264034
264347
|
settings = null;
|
|
@@ -264049,10 +264362,10 @@ var init_registry3 = __esm(() => {
|
|
|
264049
264362
|
this.providers.set(capability, map);
|
|
264050
264363
|
}
|
|
264051
264364
|
if (map.has(name)) {
|
|
264052
|
-
|
|
264365
|
+
log64.warn("Overwriting existing provider", { capability, name });
|
|
264053
264366
|
}
|
|
264054
264367
|
map.set(name, provider);
|
|
264055
|
-
|
|
264368
|
+
log64.info("Provider registered", { capability, name });
|
|
264056
264369
|
}
|
|
264057
264370
|
async resolve(capability, name) {
|
|
264058
264371
|
const map = this.providers.get(capability);
|
|
@@ -264101,7 +264414,7 @@ var init_registry3 = __esm(() => {
|
|
|
264101
264414
|
return false;
|
|
264102
264415
|
const removed = map.delete(name);
|
|
264103
264416
|
if (removed) {
|
|
264104
|
-
|
|
264417
|
+
log64.info("Provider unregistered", { capability, name });
|
|
264105
264418
|
}
|
|
264106
264419
|
return removed;
|
|
264107
264420
|
}
|
|
@@ -264468,19 +264781,19 @@ function shouldAgentReply(filter, context15) {
|
|
|
264468
264781
|
return true;
|
|
264469
264782
|
const { conditions: conditions3 } = filter;
|
|
264470
264783
|
if (conditions3.onDm && context15.isDirectMessage) {
|
|
264471
|
-
|
|
264784
|
+
log65.debug("Agent reply triggered: onDm");
|
|
264472
264785
|
return true;
|
|
264473
264786
|
}
|
|
264474
264787
|
if (conditions3.onMention && context15.mentionsBot) {
|
|
264475
|
-
|
|
264788
|
+
log65.debug("Agent reply triggered: onMention");
|
|
264476
264789
|
return true;
|
|
264477
264790
|
}
|
|
264478
264791
|
if (conditions3.onReply && context15.isReplyToBot) {
|
|
264479
|
-
|
|
264792
|
+
log65.debug("Agent reply triggered: onReply");
|
|
264480
264793
|
return true;
|
|
264481
264794
|
}
|
|
264482
264795
|
if (conditions3.onNameMatch && matchesNamePattern(context15.text, conditions3.namePatterns)) {
|
|
264483
|
-
|
|
264796
|
+
log65.debug("Agent reply triggered: onNameMatch");
|
|
264484
264797
|
return true;
|
|
264485
264798
|
}
|
|
264486
264799
|
return false;
|
|
@@ -264641,7 +264954,7 @@ class AgentRunnerService {
|
|
|
264641
264954
|
`);
|
|
264642
264955
|
const sessionStrategy = instance4.agentSessionStrategy ?? "per_chat";
|
|
264643
264956
|
const sessionId = computeSessionId(sessionStrategy, senderId, chatId);
|
|
264644
|
-
|
|
264957
|
+
log65.info("Running agent", {
|
|
264645
264958
|
instanceId: instance4.id,
|
|
264646
264959
|
agentInternalId: instance4.agentInternalId,
|
|
264647
264960
|
agentType: instance4.agentType,
|
|
@@ -264679,7 +264992,7 @@ class AgentRunnerService {
|
|
|
264679
264992
|
};
|
|
264680
264993
|
const response = await client.run(request2);
|
|
264681
264994
|
const parts = splitResponse(response.content, instance4.enableAutoSplit ?? true);
|
|
264682
|
-
|
|
264995
|
+
log65.info("Agent run complete", {
|
|
264683
264996
|
instanceId: instance4.id,
|
|
264684
264997
|
runId: response.runId,
|
|
264685
264998
|
status: response.status,
|
|
@@ -264760,13 +265073,13 @@ class AgentRunnerService {
|
|
|
264760
265073
|
}
|
|
264761
265074
|
}
|
|
264762
265075
|
}
|
|
264763
|
-
var
|
|
265076
|
+
var log65;
|
|
264764
265077
|
var init_agent_runner = __esm(() => {
|
|
264765
265078
|
init_src();
|
|
264766
265079
|
init_src();
|
|
264767
265080
|
init_src4();
|
|
264768
265081
|
init_drizzle_orm();
|
|
264769
|
-
|
|
265082
|
+
log65 = createLogger("agent-runner");
|
|
264770
265083
|
});
|
|
264771
265084
|
|
|
264772
265085
|
// ../api/src/services/agent-state.ts
|
|
@@ -264791,22 +265104,22 @@ class AgentStateService {
|
|
|
264791
265104
|
}
|
|
264792
265105
|
async initKv() {
|
|
264793
265106
|
if (!(this.eventBus instanceof NatsEventBus)) {
|
|
264794
|
-
|
|
265107
|
+
log66.warn("AgentStateService: eventBus is not a NatsEventBus \u2014 state will not be persisted");
|
|
264795
265108
|
return;
|
|
264796
265109
|
}
|
|
264797
265110
|
const js = this.eventBus.getJetStreamClient();
|
|
264798
265111
|
if (!js) {
|
|
264799
|
-
|
|
265112
|
+
log66.warn("AgentStateService: JetStream client not available");
|
|
264800
265113
|
return;
|
|
264801
265114
|
}
|
|
264802
265115
|
try {
|
|
264803
265116
|
this.kv = await js.views.kv(AGENT_STATE_KV_BUCKET, {
|
|
264804
265117
|
ttl: KV_TTL_MS
|
|
264805
265118
|
});
|
|
264806
|
-
|
|
265119
|
+
log66.info("AgentStateService: KV bucket ready", { bucket: AGENT_STATE_KV_BUCKET });
|
|
264807
265120
|
} catch (err) {
|
|
264808
265121
|
this.initPromise = null;
|
|
264809
|
-
|
|
265122
|
+
log66.error("AgentStateService: failed to open KV bucket", { error: String(err) });
|
|
264810
265123
|
}
|
|
264811
265124
|
}
|
|
264812
265125
|
async setState(agentId, chatId, status, statusMeta, conversationId = null) {
|
|
@@ -264823,7 +265136,7 @@ class AgentStateService {
|
|
|
264823
265136
|
const key = agentStateKey(agentId, chatId);
|
|
264824
265137
|
await kv.put(key, sc.encode(JSON.stringify(state)));
|
|
264825
265138
|
} catch (err) {
|
|
264826
|
-
|
|
265139
|
+
log66.warn("AgentStateService: failed to write state to KV", {
|
|
264827
265140
|
agentId,
|
|
264828
265141
|
chatId,
|
|
264829
265142
|
status,
|
|
@@ -264842,7 +265155,7 @@ class AgentStateService {
|
|
|
264842
265155
|
updatedAt: state.updatedAt
|
|
264843
265156
|
});
|
|
264844
265157
|
} catch (err) {
|
|
264845
|
-
|
|
265158
|
+
log66.warn("AgentStateService: failed to publish agent.state.changed", {
|
|
264846
265159
|
agentId,
|
|
264847
265160
|
chatId,
|
|
264848
265161
|
error: String(err)
|
|
@@ -264863,7 +265176,7 @@ class AgentStateService {
|
|
|
264863
265176
|
return null;
|
|
264864
265177
|
return state;
|
|
264865
265178
|
} catch (err) {
|
|
264866
|
-
|
|
265179
|
+
log66.warn("AgentStateService: failed to read state from KV", {
|
|
264867
265180
|
agentId,
|
|
264868
265181
|
chatId,
|
|
264869
265182
|
error: String(err)
|
|
@@ -264884,7 +265197,7 @@ class AgentStateService {
|
|
|
264884
265197
|
status: "idle",
|
|
264885
265198
|
updatedAt: Date.now()
|
|
264886
265199
|
}).catch((err) => {
|
|
264887
|
-
|
|
265200
|
+
log66.warn("AgentStateService: failed to publish clearState event", {
|
|
264888
265201
|
agentId,
|
|
264889
265202
|
chatId,
|
|
264890
265203
|
error: String(err)
|
|
@@ -264892,7 +265205,7 @@ class AgentStateService {
|
|
|
264892
265205
|
});
|
|
264893
265206
|
}
|
|
264894
265207
|
} catch (err) {
|
|
264895
|
-
|
|
265208
|
+
log66.warn("AgentStateService: failed to clear state from KV", {
|
|
264896
265209
|
agentId,
|
|
264897
265210
|
chatId,
|
|
264898
265211
|
error: String(err)
|
|
@@ -264930,7 +265243,7 @@ class AgentStateService {
|
|
|
264930
265243
|
}));
|
|
264931
265244
|
}
|
|
264932
265245
|
} catch (err) {
|
|
264933
|
-
|
|
265246
|
+
log66.warn("AgentStateService: failed to list active agents", {
|
|
264934
265247
|
chatId,
|
|
264935
265248
|
error: String(err)
|
|
264936
265249
|
});
|
|
@@ -264973,18 +265286,18 @@ class AgentStateService {
|
|
|
264973
265286
|
try {
|
|
264974
265287
|
raw2 = JSON.parse(sc.decode(entry.value));
|
|
264975
265288
|
} catch {
|
|
264976
|
-
|
|
265289
|
+
log66.warn("AgentStateService: failed to parse KV entry", { operation: entry.operation });
|
|
264977
265290
|
return null;
|
|
264978
265291
|
}
|
|
264979
265292
|
const parsed = AgentChatStateSchema.safeParse(raw2);
|
|
264980
265293
|
return parsed.success ? parsed.data : null;
|
|
264981
265294
|
}
|
|
264982
265295
|
}
|
|
264983
|
-
var import_nats6,
|
|
265296
|
+
var import_nats6, log66, sc, KV_TTL_MS;
|
|
264984
265297
|
var init_agent_state2 = __esm(() => {
|
|
264985
265298
|
init_src();
|
|
264986
265299
|
import_nats6 = __toESM(require_mod4(), 1);
|
|
264987
|
-
|
|
265300
|
+
log66 = createLogger("services:agent-state");
|
|
264988
265301
|
sc = import_nats6.StringCodec();
|
|
264989
265302
|
KV_TTL_MS = 24 * 60 * 60 * 1000;
|
|
264990
265303
|
});
|
|
@@ -265011,7 +265324,7 @@ class AgentTaskService {
|
|
|
265011
265324
|
type: created.type,
|
|
265012
265325
|
title: created.title,
|
|
265013
265326
|
status: created.status
|
|
265014
|
-
}, { instanceId: undefined }).catch((err) =>
|
|
265327
|
+
}, { instanceId: undefined }).catch((err) => log67.warn("Failed to publish agent.task.created", { error: String(err) }));
|
|
265015
265328
|
}
|
|
265016
265329
|
return created;
|
|
265017
265330
|
}
|
|
@@ -265097,7 +265410,7 @@ class AgentTaskService {
|
|
|
265097
265410
|
chatId: updated.chatId,
|
|
265098
265411
|
status: updated.status,
|
|
265099
265412
|
progress: updated.progress
|
|
265100
|
-
}, { instanceId: undefined }).catch((err) =>
|
|
265413
|
+
}, { instanceId: undefined }).catch((err) => log67.warn("Failed to publish agent.task.updated", { error: String(err) }));
|
|
265101
265414
|
}
|
|
265102
265415
|
return updated;
|
|
265103
265416
|
}
|
|
@@ -265132,7 +265445,7 @@ class AgentTaskService {
|
|
|
265132
265445
|
agentId: updated.agentId,
|
|
265133
265446
|
chatId: updated.chatId,
|
|
265134
265447
|
result: updated.result ?? null
|
|
265135
|
-
}, { instanceId: undefined }).catch((err) =>
|
|
265448
|
+
}, { instanceId: undefined }).catch((err) => log67.warn("Failed to publish agent.task.completed", { error: String(err) }));
|
|
265136
265449
|
}
|
|
265137
265450
|
return updated;
|
|
265138
265451
|
}
|
|
@@ -265151,7 +265464,7 @@ class AgentTaskService {
|
|
|
265151
265464
|
agentId: updated.agentId,
|
|
265152
265465
|
chatId: updated.chatId,
|
|
265153
265466
|
error: error2
|
|
265154
|
-
}, { instanceId: undefined }).catch((err) =>
|
|
265467
|
+
}, { instanceId: undefined }).catch((err) => log67.warn("Failed to publish agent.task.failed", { error: String(err) }));
|
|
265155
265468
|
}
|
|
265156
265469
|
return updated;
|
|
265157
265470
|
}
|
|
@@ -265168,17 +265481,17 @@ class AgentTaskService {
|
|
|
265168
265481
|
taskId: updated.id,
|
|
265169
265482
|
agentId: updated.agentId,
|
|
265170
265483
|
chatId: updated.chatId
|
|
265171
|
-
}, { instanceId: undefined }).catch((err) =>
|
|
265484
|
+
}, { instanceId: undefined }).catch((err) => log67.warn("Failed to publish agent.task.cancelled", { error: String(err) }));
|
|
265172
265485
|
}
|
|
265173
265486
|
return updated;
|
|
265174
265487
|
}
|
|
265175
265488
|
}
|
|
265176
|
-
var
|
|
265489
|
+
var log67;
|
|
265177
265490
|
var init_agent_tasks = __esm(() => {
|
|
265178
265491
|
init_src();
|
|
265179
265492
|
init_src4();
|
|
265180
265493
|
init_drizzle_orm();
|
|
265181
|
-
|
|
265494
|
+
log67 = createLogger("services:agent-tasks");
|
|
265182
265495
|
});
|
|
265183
265496
|
|
|
265184
265497
|
// ../api/src/services/agents.ts
|
|
@@ -265267,7 +265580,7 @@ class AuditService {
|
|
|
265267
265580
|
userAgent: entry.userAgent ?? null,
|
|
265268
265581
|
responseTimeMs: entry.responseTimeMs ?? null
|
|
265269
265582
|
};
|
|
265270
|
-
this.db.insert(apiKeyAuditLogs).values(data).then(() => {}).catch((err) =>
|
|
265583
|
+
this.db.insert(apiKeyAuditLogs).values(data).then(() => {}).catch((err) => log68.error("Failed to write audit log", { error: String(err) }));
|
|
265271
265584
|
}
|
|
265272
265585
|
async listByKeyId(keyId, options = {}) {
|
|
265273
265586
|
const { since, until, path: path4, statusCode, limit = 50, cursor } = options;
|
|
@@ -265305,12 +265618,12 @@ class AuditService {
|
|
|
265305
265618
|
};
|
|
265306
265619
|
}
|
|
265307
265620
|
}
|
|
265308
|
-
var
|
|
265621
|
+
var log68;
|
|
265309
265622
|
var init_audit = __esm(() => {
|
|
265310
265623
|
init_src();
|
|
265311
265624
|
init_src4();
|
|
265312
265625
|
init_drizzle_orm();
|
|
265313
|
-
|
|
265626
|
+
log68 = createLogger("audit");
|
|
265314
265627
|
});
|
|
265315
265628
|
|
|
265316
265629
|
// ../api/src/services/automations.ts
|
|
@@ -265330,8 +265643,8 @@ class AutomationService {
|
|
|
265330
265643
|
this.engine = createAutomationEngine({
|
|
265331
265644
|
defaultConcurrency: 5
|
|
265332
265645
|
});
|
|
265333
|
-
this.engine.setLogger(async (
|
|
265334
|
-
await this.logExecution(
|
|
265646
|
+
this.engine.setLogger(async (log69) => {
|
|
265647
|
+
await this.logExecution(log69);
|
|
265335
265648
|
});
|
|
265336
265649
|
await this.engine.start(this.eventBus, enabledAutomations, deps ?? {});
|
|
265337
265650
|
}
|
|
@@ -265439,8 +265752,8 @@ class AutomationService {
|
|
|
265439
265752
|
results
|
|
265440
265753
|
};
|
|
265441
265754
|
}
|
|
265442
|
-
async logExecution(
|
|
265443
|
-
const [created] = await this.db.insert(automationLogs).values(
|
|
265755
|
+
async logExecution(log69) {
|
|
265756
|
+
const [created] = await this.db.insert(automationLogs).values(log69).returning();
|
|
265444
265757
|
if (!created) {
|
|
265445
265758
|
throw new Error("Failed to log automation execution");
|
|
265446
265759
|
}
|
|
@@ -265581,7 +265894,7 @@ class CircuitBreaker {
|
|
|
265581
265894
|
this.successCount = 0;
|
|
265582
265895
|
this.lastFailureTime = 0;
|
|
265583
265896
|
this.halfOpenInFlight = false;
|
|
265584
|
-
|
|
265897
|
+
log69.info("Circuit breaker manually reset", { name: this.name });
|
|
265585
265898
|
}
|
|
265586
265899
|
evaluateState() {
|
|
265587
265900
|
if (this.state === "open") {
|
|
@@ -265590,7 +265903,7 @@ class CircuitBreaker {
|
|
|
265590
265903
|
const from = this.state;
|
|
265591
265904
|
this.state = "half-open";
|
|
265592
265905
|
this.halfOpenInFlight = false;
|
|
265593
|
-
|
|
265906
|
+
log69.info("Circuit breaker transitioning to half-open", { name: this.name });
|
|
265594
265907
|
this.emitStateChange(from, "half-open");
|
|
265595
265908
|
}
|
|
265596
265909
|
}
|
|
@@ -265602,7 +265915,7 @@ class CircuitBreaker {
|
|
|
265602
265915
|
if (stateAtExecution === "half-open") {
|
|
265603
265916
|
this.state = "closed";
|
|
265604
265917
|
this.failureTimestamps = [];
|
|
265605
|
-
|
|
265918
|
+
log69.info("Circuit breaker closed after successful probe", { name: this.name });
|
|
265606
265919
|
this.emitStateChange("half-open", "closed");
|
|
265607
265920
|
}
|
|
265608
265921
|
}
|
|
@@ -265612,7 +265925,7 @@ class CircuitBreaker {
|
|
|
265612
265925
|
this.lastFailureTime = now;
|
|
265613
265926
|
if (stateAtExecution === "half-open") {
|
|
265614
265927
|
this.state = "open";
|
|
265615
|
-
|
|
265928
|
+
log69.warn("Circuit breaker re-opened after failed probe", { name: this.name });
|
|
265616
265929
|
this.emitStateChange("half-open", "open");
|
|
265617
265930
|
return;
|
|
265618
265931
|
}
|
|
@@ -265621,7 +265934,7 @@ class CircuitBreaker {
|
|
|
265621
265934
|
if (this.failureTimestamps.length >= this.failureThreshold) {
|
|
265622
265935
|
const from = stateAtExecution;
|
|
265623
265936
|
this.state = "open";
|
|
265624
|
-
|
|
265937
|
+
log69.warn("Circuit breaker opened", {
|
|
265625
265938
|
name: this.name,
|
|
265626
265939
|
failures: this.failureTimestamps.length,
|
|
265627
265940
|
threshold: this.failureThreshold
|
|
@@ -265634,7 +265947,7 @@ class CircuitBreaker {
|
|
|
265634
265947
|
try {
|
|
265635
265948
|
this.onStateChangeCallback(this.name, from, to);
|
|
265636
265949
|
} catch (err) {
|
|
265637
|
-
|
|
265950
|
+
log69.warn("onStateChange callback error", { name: this.name, error: String(err) });
|
|
265638
265951
|
}
|
|
265639
265952
|
}
|
|
265640
265953
|
}
|
|
@@ -265654,14 +265967,14 @@ function getCircuitBreaker(name, options) {
|
|
|
265654
265967
|
if (!breaker) {
|
|
265655
265968
|
breaker = new CircuitBreaker({ name, onStateChange: globalStateChangeCallback, ...options });
|
|
265656
265969
|
circuitBreakerRegistry.set(name, breaker);
|
|
265657
|
-
|
|
265970
|
+
log69.debug("Circuit breaker created", { name });
|
|
265658
265971
|
}
|
|
265659
265972
|
return breaker;
|
|
265660
265973
|
}
|
|
265661
|
-
var
|
|
265974
|
+
var log69, DEFAULT_CIRCUIT_BREAKER_OPTIONS, CircuitOpenError, circuitBreakerRegistry, globalStateChangeCallback;
|
|
265662
265975
|
var init_circuit_breaker = __esm(() => {
|
|
265663
265976
|
init_src();
|
|
265664
|
-
|
|
265977
|
+
log69 = createLogger("media-processing:circuit-breaker");
|
|
265665
265978
|
DEFAULT_CIRCUIT_BREAKER_OPTIONS = {
|
|
265666
265979
|
failureThreshold: 5,
|
|
265667
265980
|
resetTimeoutMs: 300000,
|
|
@@ -265738,7 +266051,7 @@ class MediaHealthTracker {
|
|
|
265738
266051
|
}
|
|
265739
266052
|
reset() {
|
|
265740
266053
|
this.metrics.clear();
|
|
265741
|
-
|
|
266054
|
+
log70.info("Health metrics reset");
|
|
265742
266055
|
}
|
|
265743
266056
|
getOrCreate(processor, provider) {
|
|
265744
266057
|
const key = metricsKey(processor, provider);
|
|
@@ -265762,11 +266075,11 @@ function getMediaHealthTracker() {
|
|
|
265762
266075
|
}
|
|
265763
266076
|
return globalTracker;
|
|
265764
266077
|
}
|
|
265765
|
-
var
|
|
266078
|
+
var log70, globalTracker = null;
|
|
265766
266079
|
var init_health = __esm(() => {
|
|
265767
266080
|
init_src();
|
|
265768
266081
|
init_circuit_breaker();
|
|
265769
|
-
|
|
266082
|
+
log70 = createLogger("media-processing:health");
|
|
265770
266083
|
});
|
|
265771
266084
|
|
|
265772
266085
|
// ../media-processing/src/retry.ts
|
|
@@ -265837,7 +266150,7 @@ async function withRetry(fn, options) {
|
|
|
265837
266150
|
break;
|
|
265838
266151
|
}
|
|
265839
266152
|
const delay2 = calculateBackoffDelay2(attempt, opts.baseDelayMs, opts.maxDelayMs);
|
|
265840
|
-
|
|
266153
|
+
log71.debug("Retrying after transient error", {
|
|
265841
266154
|
attempt: attempt + 1,
|
|
265842
266155
|
maxRetries: opts.maxRetries,
|
|
265843
266156
|
delayMs: delay2,
|
|
@@ -265849,10 +266162,10 @@ async function withRetry(fn, options) {
|
|
|
265849
266162
|
}
|
|
265850
266163
|
throw lastError ?? new Error("withRetry failed with no error captured");
|
|
265851
266164
|
}
|
|
265852
|
-
var
|
|
266165
|
+
var log71, DEFAULT_RETRY_OPTIONS, TRANSIENT_MESSAGE_PATTERNS, TRANSIENT_ERROR_NAMES;
|
|
265853
266166
|
var init_retry = __esm(() => {
|
|
265854
266167
|
init_src();
|
|
265855
|
-
|
|
266168
|
+
log71 = createLogger("media-processing:retry");
|
|
265856
266169
|
DEFAULT_RETRY_OPTIONS = {
|
|
265857
266170
|
maxRetries: 3,
|
|
265858
266171
|
baseDelayMs: 1000,
|
|
@@ -328154,7 +328467,7 @@ Source:
|
|
|
328154
328467
|
function groupBySeries(coll, iteratee, callback) {
|
|
328155
328468
|
return groupByLimit$1(coll, 1, iteratee, callback);
|
|
328156
328469
|
}
|
|
328157
|
-
var
|
|
328470
|
+
var log72 = consoleFunc("log");
|
|
328158
328471
|
function mapValuesLimit(obj2, limit2, iteratee, callback) {
|
|
328159
328472
|
callback = once2(callback);
|
|
328160
328473
|
var newObj = {};
|
|
@@ -328697,7 +329010,7 @@ Source:
|
|
|
328697
329010
|
groupBy,
|
|
328698
329011
|
groupByLimit: groupByLimit$1,
|
|
328699
329012
|
groupBySeries,
|
|
328700
|
-
log:
|
|
329013
|
+
log: log72,
|
|
328701
329014
|
map: map$1,
|
|
328702
329015
|
mapLimit: mapLimit$1,
|
|
328703
329016
|
mapSeries: mapSeries$1,
|
|
@@ -328825,7 +329138,7 @@ Source:
|
|
|
328825
329138
|
exports2.groupByLimit = groupByLimit$1;
|
|
328826
329139
|
exports2.groupBySeries = groupBySeries;
|
|
328827
329140
|
exports2.inject = reduce$1;
|
|
328828
|
-
exports2.log =
|
|
329141
|
+
exports2.log = log72;
|
|
328829
329142
|
exports2.map = map$1;
|
|
328830
329143
|
exports2.mapLimit = mapLimit$1;
|
|
328831
329144
|
exports2.mapSeries = mapSeries$1;
|
|
@@ -333089,7 +333402,7 @@ var require_archiver_utils = __commonJS((exports, module) => {
|
|
|
333089
333402
|
var path4 = __require("path");
|
|
333090
333403
|
var nutil = __require("util");
|
|
333091
333404
|
var lazystream = require_lazystream();
|
|
333092
|
-
var
|
|
333405
|
+
var normalizePath3 = require_normalize_path();
|
|
333093
333406
|
var defaults2 = require_lodash16();
|
|
333094
333407
|
var Stream6 = __require("stream").Stream;
|
|
333095
333408
|
var PassThrough = require_readable().PassThrough;
|
|
@@ -333150,13 +333463,13 @@ var require_archiver_utils = __commonJS((exports, module) => {
|
|
|
333150
333463
|
return source;
|
|
333151
333464
|
};
|
|
333152
333465
|
utils4.sanitizePath = function(filepath) {
|
|
333153
|
-
return
|
|
333466
|
+
return normalizePath3(filepath, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
|
|
333154
333467
|
};
|
|
333155
333468
|
utils4.trailingSlashIt = function(str2) {
|
|
333156
333469
|
return str2.slice(-1) !== "/" ? str2 + "/" : str2;
|
|
333157
333470
|
};
|
|
333158
333471
|
utils4.unixifyPath = function(filepath) {
|
|
333159
|
-
return
|
|
333472
|
+
return normalizePath3(filepath, false).replace(/^\w+:/, "");
|
|
333160
333473
|
};
|
|
333161
333474
|
utils4.walkdir = function(dirpath, base2, callback) {
|
|
333162
333475
|
var results = [];
|
|
@@ -333971,7 +334284,7 @@ var require_constants21 = __commonJS((exports, module) => {
|
|
|
333971
334284
|
// ../../node_modules/.bun/compress-commons@4.1.2/node_modules/compress-commons/lib/archivers/zip/zip-archive-entry.js
|
|
333972
334285
|
var require_zip_archive_entry = __commonJS((exports, module) => {
|
|
333973
334286
|
var inherits = __require("util").inherits;
|
|
333974
|
-
var
|
|
334287
|
+
var normalizePath3 = require_normalize_path();
|
|
333975
334288
|
var ArchiveEntry = require_archive_entry();
|
|
333976
334289
|
var GeneralPurposeBit = require_general_purpose_bit();
|
|
333977
334290
|
var UnixStat = require_unix_stat();
|
|
@@ -334095,7 +334408,7 @@ var require_zip_archive_entry = __commonJS((exports, module) => {
|
|
|
334095
334408
|
this.method = method;
|
|
334096
334409
|
};
|
|
334097
334410
|
ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) {
|
|
334098
|
-
name =
|
|
334411
|
+
name = normalizePath3(name, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
|
|
334099
334412
|
if (prependSlash) {
|
|
334100
334413
|
name = `/${name}`;
|
|
334101
334414
|
}
|
|
@@ -335191,7 +335504,7 @@ var require_archiver_utils2 = __commonJS((exports, module) => {
|
|
|
335191
335504
|
var fs12 = require_graceful_fs();
|
|
335192
335505
|
var path4 = __require("path");
|
|
335193
335506
|
var lazystream = require_lazystream();
|
|
335194
|
-
var
|
|
335507
|
+
var normalizePath3 = require_normalize_path();
|
|
335195
335508
|
var defaults2 = require_lodash16();
|
|
335196
335509
|
var Stream6 = __require("stream").Stream;
|
|
335197
335510
|
var PassThrough = require_readable2().PassThrough;
|
|
@@ -335250,13 +335563,13 @@ var require_archiver_utils2 = __commonJS((exports, module) => {
|
|
|
335250
335563
|
return source;
|
|
335251
335564
|
};
|
|
335252
335565
|
utils4.sanitizePath = function(filepath) {
|
|
335253
|
-
return
|
|
335566
|
+
return normalizePath3(filepath, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
|
|
335254
335567
|
};
|
|
335255
335568
|
utils4.trailingSlashIt = function(str2) {
|
|
335256
335569
|
return str2.slice(-1) !== "/" ? str2 + "/" : str2;
|
|
335257
335570
|
};
|
|
335258
335571
|
utils4.unixifyPath = function(filepath) {
|
|
335259
|
-
return
|
|
335572
|
+
return normalizePath3(filepath, false).replace(/^\w+:/, "");
|
|
335260
335573
|
};
|
|
335261
335574
|
utils4.walkdir = function(dirpath, base2, callback) {
|
|
335262
335575
|
var results = [];
|
|
@@ -344827,20 +345140,20 @@ class MediaProcessingService {
|
|
|
344827
345140
|
new VideoProcessor(config4),
|
|
344828
345141
|
new DocumentProcessor(config4)
|
|
344829
345142
|
];
|
|
344830
|
-
|
|
345143
|
+
log72.info("MediaProcessingService initialized", {
|
|
344831
345144
|
processorCount: this.processors.length,
|
|
344832
345145
|
hasGroq: !!config4.groqApiKey,
|
|
344833
345146
|
hasOpenAI: !!config4.openaiApiKey,
|
|
344834
345147
|
hasGemini: !!config4.geminiApiKey
|
|
344835
345148
|
});
|
|
344836
345149
|
if (!config4.geminiApiKey && !config4.openaiApiKey) {
|
|
344837
|
-
|
|
345150
|
+
log72.warn("No vision API configured \u2014 set GEMINI_API_KEY or OPENAI_API_KEY in .env for image/video/document processing");
|
|
344838
345151
|
}
|
|
344839
345152
|
}
|
|
344840
345153
|
async process(filePath, mimeType, options) {
|
|
344841
345154
|
const processor = this.findProcessor(mimeType);
|
|
344842
345155
|
if (!processor) {
|
|
344843
|
-
|
|
345156
|
+
log72.warn("No processor found for MIME type", { mimeType, filePath });
|
|
344844
345157
|
return {
|
|
344845
345158
|
success: false,
|
|
344846
345159
|
contentFormat: "text",
|
|
@@ -344852,7 +345165,7 @@ class MediaProcessingService {
|
|
|
344852
345165
|
errorMessage: `No processor available for MIME type: ${mimeType}`
|
|
344853
345166
|
};
|
|
344854
345167
|
}
|
|
344855
|
-
|
|
345168
|
+
log72.debug("Processing media", {
|
|
344856
345169
|
processor: processor.name,
|
|
344857
345170
|
mimeType,
|
|
344858
345171
|
filePath
|
|
@@ -344860,7 +345173,7 @@ class MediaProcessingService {
|
|
|
344860
345173
|
try {
|
|
344861
345174
|
const result = await processor.process(filePath, mimeType, options);
|
|
344862
345175
|
if (result.success) {
|
|
344863
|
-
|
|
345176
|
+
log72.info("Media processing complete", {
|
|
344864
345177
|
processor: processor.name,
|
|
344865
345178
|
provider: result.provider,
|
|
344866
345179
|
model: result.model,
|
|
@@ -344869,7 +345182,7 @@ class MediaProcessingService {
|
|
|
344869
345182
|
contentLength: result.content?.length ?? 0
|
|
344870
345183
|
});
|
|
344871
345184
|
} else {
|
|
344872
|
-
|
|
345185
|
+
log72.warn("Media processing failed", {
|
|
344873
345186
|
processor: processor.name,
|
|
344874
345187
|
error: result.errorMessage
|
|
344875
345188
|
});
|
|
@@ -344877,7 +345190,7 @@ class MediaProcessingService {
|
|
|
344877
345190
|
return result;
|
|
344878
345191
|
} catch (error2) {
|
|
344879
345192
|
const errorMsg = error2 instanceof Error ? error2.message : String(error2);
|
|
344880
|
-
|
|
345193
|
+
log72.error("Media processing error", {
|
|
344881
345194
|
processor: processor.name,
|
|
344882
345195
|
error: errorMsg
|
|
344883
345196
|
});
|
|
@@ -344922,11 +345235,11 @@ function createMediaProcessingService(config4) {
|
|
|
344922
345235
|
};
|
|
344923
345236
|
return new MediaProcessingService(fullConfig);
|
|
344924
345237
|
}
|
|
344925
|
-
var
|
|
345238
|
+
var log72;
|
|
344926
345239
|
var init_service = __esm(() => {
|
|
344927
345240
|
init_src();
|
|
344928
345241
|
init_processors();
|
|
344929
|
-
|
|
345242
|
+
log72 = createLogger("media-processing:service");
|
|
344930
345243
|
});
|
|
344931
345244
|
|
|
344932
345245
|
// ../media-processing/src/index.ts
|
|
@@ -344993,7 +345306,7 @@ class MediaStorageService {
|
|
|
344993
345306
|
this.basePath = basePath ?? process.env.MEDIA_STORAGE_PATH ?? DEFAULT_MEDIA_PATH;
|
|
344994
345307
|
if (!existsSync5(this.basePath)) {
|
|
344995
345308
|
mkdirSync3(this.basePath, { recursive: true });
|
|
344996
|
-
|
|
345309
|
+
log73.info("Created media storage directory", { path: this.basePath });
|
|
344997
345310
|
}
|
|
344998
345311
|
}
|
|
344999
345312
|
buildPath(instanceId, messageId, mimeType, timestamp3) {
|
|
@@ -345010,7 +345323,7 @@ class MediaStorageService {
|
|
|
345010
345323
|
}
|
|
345011
345324
|
const buffer3 = Buffer.from(base64Data, "base64");
|
|
345012
345325
|
writeFileSync3(localPath, buffer3);
|
|
345013
|
-
|
|
345326
|
+
log73.debug("Stored media from base64", { messageId, localPath, size: buffer3.length });
|
|
345014
345327
|
return {
|
|
345015
345328
|
localPath: relative2(this.basePath, localPath),
|
|
345016
345329
|
size: buffer3.length,
|
|
@@ -345024,7 +345337,7 @@ class MediaStorageService {
|
|
|
345024
345337
|
mkdirSync3(dir, { recursive: true });
|
|
345025
345338
|
}
|
|
345026
345339
|
writeFileSync3(localPath, buffer3);
|
|
345027
|
-
|
|
345340
|
+
log73.debug("Stored media from buffer", { messageId, localPath, size: buffer3.length });
|
|
345028
345341
|
return {
|
|
345029
345342
|
localPath: relative2(this.basePath, localPath),
|
|
345030
345343
|
size: buffer3.length,
|
|
@@ -345105,12 +345418,12 @@ class MediaStorageService {
|
|
|
345105
345418
|
return this.basePath;
|
|
345106
345419
|
}
|
|
345107
345420
|
}
|
|
345108
|
-
var
|
|
345421
|
+
var log73, DEFAULT_MEDIA_PATH = "./data/media";
|
|
345109
345422
|
var init_media_storage = __esm(() => {
|
|
345110
345423
|
init_src();
|
|
345111
345424
|
init_src4();
|
|
345112
345425
|
init_drizzle_orm();
|
|
345113
|
-
|
|
345426
|
+
log73 = createLogger("services:media-storage");
|
|
345114
345427
|
});
|
|
345115
345428
|
|
|
345116
345429
|
// ../api/src/services/batch-jobs.ts
|
|
@@ -345176,7 +345489,7 @@ class BatchJobService {
|
|
|
345176
345489
|
if (!created) {
|
|
345177
345490
|
throw new Error("Failed to create batch job");
|
|
345178
345491
|
}
|
|
345179
|
-
|
|
345492
|
+
log74.info("Batch job created", { jobId: created.id, jobType, instanceId });
|
|
345180
345493
|
if (this.eventBus) {
|
|
345181
345494
|
await this.eventBus.publish("batch-job.created", {
|
|
345182
345495
|
jobId: created.id,
|
|
@@ -345186,7 +345499,7 @@ class BatchJobService {
|
|
|
345186
345499
|
}, { instanceId });
|
|
345187
345500
|
}
|
|
345188
345501
|
this.executeJob(created.id).catch((error2) => {
|
|
345189
|
-
|
|
345502
|
+
log74.error("Job execution failed", { jobId: created.id, error: String(error2) });
|
|
345190
345503
|
});
|
|
345191
345504
|
return created;
|
|
345192
345505
|
}
|
|
@@ -345251,7 +345564,7 @@ class BatchJobService {
|
|
|
345251
345564
|
if (!updated) {
|
|
345252
345565
|
throw new NotFoundError("BatchJob", id);
|
|
345253
345566
|
}
|
|
345254
|
-
|
|
345567
|
+
log74.info("Batch job cancelled", { jobId: id });
|
|
345255
345568
|
if (this.eventBus) {
|
|
345256
345569
|
await this.eventBus.publish("batch-job.cancelled", {
|
|
345257
345570
|
jobId: id,
|
|
@@ -345294,13 +345607,13 @@ class BatchJobService {
|
|
|
345294
345607
|
async resumeJobs() {
|
|
345295
345608
|
const runningJobs = await this.db.select().from(batchJobs).where(eq(batchJobs.status, "running"));
|
|
345296
345609
|
if (runningJobs.length === 0) {
|
|
345297
|
-
|
|
345610
|
+
log74.debug("No jobs to resume");
|
|
345298
345611
|
return;
|
|
345299
345612
|
}
|
|
345300
|
-
|
|
345613
|
+
log74.info("Resuming batch jobs", { count: runningJobs.length });
|
|
345301
345614
|
for (const job of runningJobs) {
|
|
345302
345615
|
this.executeJob(job.id).catch((error2) => {
|
|
345303
|
-
|
|
345616
|
+
log74.error("Failed to resume job", { jobId: job.id, error: String(error2) });
|
|
345304
345617
|
});
|
|
345305
345618
|
}
|
|
345306
345619
|
}
|
|
@@ -345340,7 +345653,7 @@ class BatchJobService {
|
|
|
345340
345653
|
}
|
|
345341
345654
|
async markJobRunning(jobId, instanceId, jobType, totalItems) {
|
|
345342
345655
|
await this.db.update(batchJobs).set({ status: "running", startedAt: new Date, totalItems }).where(eq(batchJobs.id, jobId));
|
|
345343
|
-
|
|
345656
|
+
log74.info("Job started", { jobId, totalItems });
|
|
345344
345657
|
if (this.eventBus) {
|
|
345345
345658
|
await this.eventBus.publish("batch-job.started", { jobId, instanceId, jobType, totalItems }, { instanceId });
|
|
345346
345659
|
}
|
|
@@ -345371,12 +345684,12 @@ class BatchJobService {
|
|
|
345371
345684
|
async isJobCancelled(jobId) {
|
|
345372
345685
|
const activeJob = this.activeJobs.get(jobId);
|
|
345373
345686
|
if (activeJob?.cancelled) {
|
|
345374
|
-
|
|
345687
|
+
log74.info("Job cancelled by user", { jobId });
|
|
345375
345688
|
return true;
|
|
345376
345689
|
}
|
|
345377
345690
|
const [current] = await this.db.select({ status: batchJobs.status }).from(batchJobs).where(eq(batchJobs.id, jobId)).limit(1);
|
|
345378
345691
|
if (current?.status === "cancelled") {
|
|
345379
|
-
|
|
345692
|
+
log74.info("Job cancelled (DB check)", { jobId });
|
|
345380
345693
|
return true;
|
|
345381
345694
|
}
|
|
345382
345695
|
return false;
|
|
@@ -345395,7 +345708,7 @@ class BatchJobService {
|
|
|
345395
345708
|
} catch (error2) {
|
|
345396
345709
|
state.failedItems++;
|
|
345397
345710
|
state.errors.push({ itemId: item.id, error: String(error2) });
|
|
345398
|
-
|
|
345711
|
+
log74.warn("Item processing error", { jobId, itemId: item.id, error: String(error2) });
|
|
345399
345712
|
}
|
|
345400
345713
|
}
|
|
345401
345714
|
async updateProgressIfNeeded(jobId, instanceId, index2, total, totalItems, skippedItems, currentItemId, state) {
|
|
@@ -345445,7 +345758,7 @@ class BatchJobService {
|
|
|
345445
345758
|
errors: state.errors,
|
|
345446
345759
|
currentItem: null
|
|
345447
345760
|
}).where(eq(batchJobs.id, jobId));
|
|
345448
|
-
|
|
345761
|
+
log74.info("Job completed", {
|
|
345449
345762
|
jobId,
|
|
345450
345763
|
processedItems: state.processedItems,
|
|
345451
345764
|
failedItems: state.failedItems,
|
|
@@ -345470,7 +345783,7 @@ class BatchJobService {
|
|
|
345470
345783
|
}
|
|
345471
345784
|
}
|
|
345472
345785
|
async handleJobError(jobId, instanceId, error2) {
|
|
345473
|
-
|
|
345786
|
+
log74.error("Job execution failed", { jobId, error: String(error2) });
|
|
345474
345787
|
await this.db.update(batchJobs).set({ status: "failed", completedAt: new Date, errorMessage: String(error2) }).where(eq(batchJobs.id, jobId));
|
|
345475
345788
|
if (this.eventBus) {
|
|
345476
345789
|
await this.eventBus.publish("batch-job.failed", { jobId, instanceId, error: String(error2) }, { instanceId });
|
|
@@ -345631,14 +345944,14 @@ class BatchJobService {
|
|
|
345631
345944
|
};
|
|
345632
345945
|
}
|
|
345633
345946
|
}
|
|
345634
|
-
var
|
|
345947
|
+
var log74, PROCESSABLE_CONTENT_TYPES;
|
|
345635
345948
|
var init_batch_jobs = __esm(() => {
|
|
345636
345949
|
init_src();
|
|
345637
345950
|
init_src4();
|
|
345638
345951
|
init_src6();
|
|
345639
345952
|
init_drizzle_orm();
|
|
345640
345953
|
init_media_storage();
|
|
345641
|
-
|
|
345954
|
+
log74 = createLogger("services:batch-jobs");
|
|
345642
345955
|
PROCESSABLE_CONTENT_TYPES = new Set(["audio", "image", "video", "document"]);
|
|
345643
345956
|
});
|
|
345644
345957
|
|
|
@@ -345871,12 +346184,12 @@ class ChatService {
|
|
|
345871
346184
|
async findByExternalIdSmart(instanceId, externalId) {
|
|
345872
346185
|
const existing = await this.getByExternalId(instanceId, externalId);
|
|
345873
346186
|
if (existing) {
|
|
345874
|
-
|
|
346187
|
+
log75.debug("chat_resolution", { externalId, resolvedVia: "direct", instanceId });
|
|
345875
346188
|
return existing;
|
|
345876
346189
|
}
|
|
345877
346190
|
const [byCanonical] = await this.db.select().from(chats).where(and2(eq(chats.instanceId, instanceId), eq(chats.canonicalId, externalId))).limit(1);
|
|
345878
346191
|
if (byCanonical) {
|
|
345879
|
-
|
|
346192
|
+
log75.debug("chat_resolution", { externalId, resolvedVia: "canonicalId", instanceId });
|
|
345880
346193
|
return byCanonical;
|
|
345881
346194
|
}
|
|
345882
346195
|
if (externalId.endsWith("@s.whatsapp.net")) {
|
|
@@ -345884,7 +346197,7 @@ class ChatService {
|
|
|
345884
346197
|
if (mapping) {
|
|
345885
346198
|
const lidChat = await this.getByExternalId(instanceId, mapping.lidId);
|
|
345886
346199
|
if (lidChat) {
|
|
345887
|
-
|
|
346200
|
+
log75.debug("chat_resolution", { externalId, resolvedVia: "phoneMapping", instanceId });
|
|
345888
346201
|
return lidChat;
|
|
345889
346202
|
}
|
|
345890
346203
|
}
|
|
@@ -345893,7 +346206,7 @@ class ChatService {
|
|
|
345893
346206
|
if (mapping) {
|
|
345894
346207
|
const phoneChat = await this.getByExternalId(instanceId, mapping.phoneId);
|
|
345895
346208
|
if (phoneChat) {
|
|
345896
|
-
|
|
346209
|
+
log75.debug("chat_resolution", { externalId, resolvedVia: "lidMapping", instanceId });
|
|
345897
346210
|
return phoneChat;
|
|
345898
346211
|
}
|
|
345899
346212
|
}
|
|
@@ -346131,12 +346444,12 @@ class ChatService {
|
|
|
346131
346444
|
return updated;
|
|
346132
346445
|
}
|
|
346133
346446
|
}
|
|
346134
|
-
var
|
|
346447
|
+
var log75, ATTENTION_LABEL = "follow-up";
|
|
346135
346448
|
var init_chats = __esm(() => {
|
|
346136
346449
|
init_src();
|
|
346137
346450
|
init_src4();
|
|
346138
346451
|
init_drizzle_orm();
|
|
346139
|
-
|
|
346452
|
+
log75 = createLogger("chats");
|
|
346140
346453
|
});
|
|
346141
346454
|
|
|
346142
346455
|
// ../api/src/services/consumer-offsets.ts
|
|
@@ -346183,7 +346496,7 @@ class ConsumerOffsetService {
|
|
|
346183
346496
|
streamTotal: info.messages,
|
|
346184
346497
|
gap
|
|
346185
346498
|
});
|
|
346186
|
-
|
|
346499
|
+
log76.warn("Consumer gap detected", {
|
|
346187
346500
|
consumer: offset.consumerName,
|
|
346188
346501
|
stream: offset.streamName,
|
|
346189
346502
|
lastOffset: offset.lastSequence,
|
|
@@ -346195,12 +346508,12 @@ class ConsumerOffsetService {
|
|
|
346195
346508
|
return gaps;
|
|
346196
346509
|
}
|
|
346197
346510
|
}
|
|
346198
|
-
var
|
|
346511
|
+
var log76;
|
|
346199
346512
|
var init_consumer_offsets = __esm(() => {
|
|
346200
346513
|
init_src();
|
|
346201
346514
|
init_src4();
|
|
346202
346515
|
init_drizzle_orm();
|
|
346203
|
-
|
|
346516
|
+
log76 = createLogger("consumer-offsets");
|
|
346204
346517
|
});
|
|
346205
346518
|
|
|
346206
346519
|
// ../api/src/services/conversations.ts
|
|
@@ -346228,7 +346541,7 @@ class ConversationService {
|
|
|
346228
346541
|
throw new Error("Failed to create conversation");
|
|
346229
346542
|
}
|
|
346230
346543
|
if (this.eventBus) {
|
|
346231
|
-
this.eventBus.publish("conversation.created", { conversationId: created.id, title: created.title }, { instanceId: undefined }).catch((err) =>
|
|
346544
|
+
this.eventBus.publish("conversation.created", { conversationId: created.id, title: created.title }, { instanceId: undefined }).catch((err) => log77.warn("Failed to publish conversation.created", { error: String(err) }));
|
|
346232
346545
|
}
|
|
346233
346546
|
return created;
|
|
346234
346547
|
}
|
|
@@ -346238,7 +346551,7 @@ class ConversationService {
|
|
|
346238
346551
|
throw new NotFoundError("Conversation", id);
|
|
346239
346552
|
}
|
|
346240
346553
|
if (this.eventBus) {
|
|
346241
|
-
this.eventBus.publish("conversation.updated", { conversationId: updated.id, title: updated.title }, { instanceId: undefined }).catch((err) =>
|
|
346554
|
+
this.eventBus.publish("conversation.updated", { conversationId: updated.id, title: updated.title }, { instanceId: undefined }).catch((err) => log77.warn("Failed to publish conversation.updated", { error: String(err) }));
|
|
346242
346555
|
}
|
|
346243
346556
|
return updated;
|
|
346244
346557
|
}
|
|
@@ -346248,19 +346561,19 @@ class ConversationService {
|
|
|
346248
346561
|
throw new NotFoundError("Conversation", id);
|
|
346249
346562
|
}
|
|
346250
346563
|
if (this.eventBus) {
|
|
346251
|
-
this.eventBus.publish("conversation.deleted", { conversationId: deleted.id }, { instanceId: undefined }).catch((err) =>
|
|
346564
|
+
this.eventBus.publish("conversation.deleted", { conversationId: deleted.id }, { instanceId: undefined }).catch((err) => log77.warn("Failed to publish conversation.deleted", { error: String(err) }));
|
|
346252
346565
|
}
|
|
346253
346566
|
}
|
|
346254
346567
|
async getChats(conversationId) {
|
|
346255
346568
|
return this.db.select().from(chats).where(eq(chats.conversationId, conversationId));
|
|
346256
346569
|
}
|
|
346257
346570
|
}
|
|
346258
|
-
var
|
|
346571
|
+
var log77;
|
|
346259
346572
|
var init_conversations = __esm(() => {
|
|
346260
346573
|
init_src();
|
|
346261
346574
|
init_src4();
|
|
346262
346575
|
init_drizzle_orm();
|
|
346263
|
-
|
|
346576
|
+
log77 = createLogger("services:conversations");
|
|
346264
346577
|
});
|
|
346265
346578
|
|
|
346266
346579
|
// ../api/src/services/dead-letters.ts
|
|
@@ -346315,7 +346628,7 @@ class DeadLetterService {
|
|
|
346315
346628
|
if (!result) {
|
|
346316
346629
|
throw new Error("Failed to create dead letter entry");
|
|
346317
346630
|
}
|
|
346318
|
-
|
|
346631
|
+
log78.info("Dead letter created", {
|
|
346319
346632
|
deadLetterId: result.id,
|
|
346320
346633
|
eventId: result.eventId,
|
|
346321
346634
|
eventType: result.eventType,
|
|
@@ -346328,7 +346641,7 @@ class DeadLetterService {
|
|
|
346328
346641
|
source: "dead-letter-service"
|
|
346329
346642
|
});
|
|
346330
346643
|
} catch (err) {
|
|
346331
|
-
|
|
346644
|
+
log78.error("Failed to publish dead letter system event", { error: String(err) });
|
|
346332
346645
|
}
|
|
346333
346646
|
}
|
|
346334
346647
|
return result;
|
|
@@ -346357,7 +346670,7 @@ class DeadLetterService {
|
|
|
346357
346670
|
resolvedBy: "manual-retry",
|
|
346358
346671
|
manualRetryCount: deadLetter.manualRetryCount + 1
|
|
346359
346672
|
}).where(eq(deadLetterEvents.id, id));
|
|
346360
|
-
|
|
346673
|
+
log78.info("Dead letter manually retried successfully", { deadLetterId: id });
|
|
346361
346674
|
return { success: true, deadLetterId: id };
|
|
346362
346675
|
} catch (err) {
|
|
346363
346676
|
const newAutoRetryCount = deadLetter.autoRetryCount;
|
|
@@ -346366,7 +346679,7 @@ class DeadLetterService {
|
|
|
346366
346679
|
manualRetryCount: deadLetter.manualRetryCount + 1,
|
|
346367
346680
|
nextAutoRetryAt: calculateNextAutoRetryAt(newAutoRetryCount)
|
|
346368
346681
|
}).where(eq(deadLetterEvents.id, id));
|
|
346369
|
-
|
|
346682
|
+
log78.error("Dead letter manual retry failed", { deadLetterId: id, error: String(err) });
|
|
346370
346683
|
return { success: false, deadLetterId: id, error: String(err) };
|
|
346371
346684
|
}
|
|
346372
346685
|
}
|
|
@@ -346383,7 +346696,7 @@ class DeadLetterService {
|
|
|
346383
346696
|
resolvedBy: note,
|
|
346384
346697
|
nextAutoRetryAt: null
|
|
346385
346698
|
}).where(eq(deadLetterEvents.id, id)).returning();
|
|
346386
|
-
|
|
346699
|
+
log78.info("Dead letter resolved", { deadLetterId: id, note });
|
|
346387
346700
|
return updated;
|
|
346388
346701
|
}
|
|
346389
346702
|
async abandon(id) {
|
|
@@ -346398,7 +346711,7 @@ class DeadLetterService {
|
|
|
346398
346711
|
status: "abandoned",
|
|
346399
346712
|
nextAutoRetryAt: null
|
|
346400
346713
|
}).where(eq(deadLetterEvents.id, id)).returning();
|
|
346401
|
-
|
|
346714
|
+
log78.info("Dead letter abandoned", { deadLetterId: id });
|
|
346402
346715
|
return updated;
|
|
346403
346716
|
}
|
|
346404
346717
|
async processAutoRetries() {
|
|
@@ -346422,7 +346735,7 @@ class DeadLetterService {
|
|
|
346422
346735
|
resolvedBy: `auto-retry-${deadLetter.autoRetryCount + 1}`
|
|
346423
346736
|
}).where(eq(deadLetterEvents.id, deadLetter.id));
|
|
346424
346737
|
succeeded++;
|
|
346425
|
-
|
|
346738
|
+
log78.info("Auto-retry succeeded", { deadLetterId: deadLetter.id });
|
|
346426
346739
|
} catch (err) {
|
|
346427
346740
|
const newRetryCount = deadLetter.autoRetryCount + 1;
|
|
346428
346741
|
const nextRetry = calculateNextAutoRetryAt(newRetryCount, now);
|
|
@@ -346434,7 +346747,7 @@ class DeadLetterService {
|
|
|
346434
346747
|
[Auto-retry ${newRetryCount}]: ${String(err)}`
|
|
346435
346748
|
}).where(eq(deadLetterEvents.id, deadLetter.id));
|
|
346436
346749
|
failed++;
|
|
346437
|
-
|
|
346750
|
+
log78.warn("Auto-retry failed", {
|
|
346438
346751
|
deadLetterId: deadLetter.id,
|
|
346439
346752
|
retryCount: newRetryCount,
|
|
346440
346753
|
nextRetryAt: nextRetry?.toISOString() ?? "manual-only"
|
|
@@ -346443,7 +346756,7 @@ class DeadLetterService {
|
|
|
346443
346756
|
}
|
|
346444
346757
|
}
|
|
346445
346758
|
if (processed > 0) {
|
|
346446
|
-
|
|
346759
|
+
log78.info("Auto-retry batch completed", { processed, succeeded, failed });
|
|
346447
346760
|
}
|
|
346448
346761
|
return { processed, succeeded, failed };
|
|
346449
346762
|
}
|
|
@@ -346474,17 +346787,17 @@ class DeadLetterService {
|
|
|
346474
346787
|
const cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
|
346475
346788
|
const result = await this.db.delete(deadLetterEvents).where(and2(lte(deadLetterEvents.createdAt, cutoff), or2(eq(deadLetterEvents.status, "resolved"), eq(deadLetterEvents.status, "abandoned")))).returning({ id: deadLetterEvents.id });
|
|
346476
346789
|
if (result.length > 0) {
|
|
346477
|
-
|
|
346790
|
+
log78.info("Cleaned up expired dead letters", { count: result.length });
|
|
346478
346791
|
}
|
|
346479
346792
|
return result.length;
|
|
346480
346793
|
}
|
|
346481
346794
|
}
|
|
346482
|
-
var
|
|
346795
|
+
var log78;
|
|
346483
346796
|
var init_dead_letters = __esm(() => {
|
|
346484
346797
|
init_src();
|
|
346485
346798
|
init_src4();
|
|
346486
346799
|
init_drizzle_orm();
|
|
346487
|
-
|
|
346800
|
+
log78 = createLogger("dead-letters");
|
|
346488
346801
|
});
|
|
346489
346802
|
|
|
346490
346803
|
// ../api/src/services/event-ops.ts
|
|
@@ -346536,13 +346849,13 @@ class EventOpsService {
|
|
|
346536
346849
|
source: "event-ops"
|
|
346537
346850
|
});
|
|
346538
346851
|
} catch (err) {
|
|
346539
|
-
|
|
346852
|
+
log79.error("Failed to publish replay started event", { error: String(err) });
|
|
346540
346853
|
}
|
|
346541
346854
|
}
|
|
346542
346855
|
this.executeReplay(sessionId, options).catch((err) => {
|
|
346543
|
-
|
|
346856
|
+
log79.error("Replay failed", { sessionId, error: String(err) });
|
|
346544
346857
|
});
|
|
346545
|
-
|
|
346858
|
+
log79.info("Replay started", { sessionId, total, options });
|
|
346546
346859
|
return session3;
|
|
346547
346860
|
}
|
|
346548
346861
|
getReplaySession(sessionId) {
|
|
@@ -346560,7 +346873,7 @@ class EventOpsService {
|
|
|
346560
346873
|
if (this.activeReplayId === sessionId) {
|
|
346561
346874
|
this.activeReplayId = null;
|
|
346562
346875
|
}
|
|
346563
|
-
|
|
346876
|
+
log79.info("Replay cancelled", { sessionId });
|
|
346564
346877
|
return true;
|
|
346565
346878
|
}
|
|
346566
346879
|
async getMetrics() {
|
|
@@ -346612,13 +346925,13 @@ class EventOpsService {
|
|
|
346612
346925
|
};
|
|
346613
346926
|
}
|
|
346614
346927
|
async runScheduledOps() {
|
|
346615
|
-
|
|
346928
|
+
log79.info("Running scheduled event ops");
|
|
346616
346929
|
const [autoRetry, payloadCleanup, deadLetterCleanup] = await Promise.all([
|
|
346617
346930
|
this.deadLetterService.processAutoRetries(),
|
|
346618
346931
|
this.payloadStoreService.cleanupExpired(),
|
|
346619
346932
|
this.deadLetterService.cleanupExpired()
|
|
346620
346933
|
]);
|
|
346621
|
-
|
|
346934
|
+
log79.info("Scheduled event ops completed", {
|
|
346622
346935
|
autoRetry,
|
|
346623
346936
|
payloadCleanup,
|
|
346624
346937
|
deadLetterCleanup
|
|
@@ -346702,7 +347015,7 @@ class EventOpsService {
|
|
|
346702
347015
|
} catch (err) {
|
|
346703
347016
|
session3.status = "failed";
|
|
346704
347017
|
session3.error = String(err);
|
|
346705
|
-
|
|
347018
|
+
log79.error("Replay execution failed", { sessionId, error: String(err) });
|
|
346706
347019
|
} finally {
|
|
346707
347020
|
session3.completedAt = new Date;
|
|
346708
347021
|
this.activeReplayId = null;
|
|
@@ -346722,10 +347035,10 @@ class EventOpsService {
|
|
|
346722
347035
|
source: "event-ops"
|
|
346723
347036
|
});
|
|
346724
347037
|
} catch (err) {
|
|
346725
|
-
|
|
347038
|
+
log79.error("Failed to publish replay completed event", { error: String(err) });
|
|
346726
347039
|
}
|
|
346727
347040
|
}
|
|
346728
|
-
|
|
347041
|
+
log79.info("Replay completed", {
|
|
346729
347042
|
sessionId,
|
|
346730
347043
|
status: session3.status,
|
|
346731
347044
|
processed: session3.progress.processed,
|
|
@@ -346736,12 +347049,12 @@ class EventOpsService {
|
|
|
346736
347049
|
}
|
|
346737
347050
|
}
|
|
346738
347051
|
}
|
|
346739
|
-
var
|
|
347052
|
+
var log79;
|
|
346740
347053
|
var init_event_ops = __esm(() => {
|
|
346741
347054
|
init_src();
|
|
346742
347055
|
init_src4();
|
|
346743
347056
|
init_drizzle_orm();
|
|
346744
|
-
|
|
347057
|
+
log79 = createLogger("event-ops");
|
|
346745
347058
|
});
|
|
346746
347059
|
|
|
346747
347060
|
// ../api/src/services/events.ts
|
|
@@ -347478,12 +347791,12 @@ class PayloadStoreService {
|
|
|
347478
347791
|
const { eventId, eventType, stage, payload } = options;
|
|
347479
347792
|
const config4 = await this.getConfig(eventType);
|
|
347480
347793
|
if (!shouldStoreStage(stage, config4)) {
|
|
347481
|
-
|
|
347794
|
+
log80.debug("Skipping payload storage", { eventId, eventType, stage, reason: "config-disabled" });
|
|
347482
347795
|
return null;
|
|
347483
347796
|
}
|
|
347484
347797
|
const insertData = preparePayloadInsert({ eventId, eventType, stage, payload });
|
|
347485
347798
|
const [result] = await this.db.insert(eventPayloads).values(insertData).returning();
|
|
347486
|
-
|
|
347799
|
+
log80.debug("Payload stored", {
|
|
347487
347800
|
eventId,
|
|
347488
347801
|
stage,
|
|
347489
347802
|
originalSize: result?.payloadSizeOriginal,
|
|
@@ -347515,7 +347828,7 @@ class PayloadStoreService {
|
|
|
347515
347828
|
deleteReason: reason,
|
|
347516
347829
|
payloadCompressed: ""
|
|
347517
347830
|
}).where(and2(eq(eventPayloads.eventId, eventId), isNull2(eventPayloads.deletedAt))).returning({ id: eventPayloads.id });
|
|
347518
|
-
|
|
347831
|
+
log80.info("Payloads soft-deleted", { eventId, count: result.length, deletedBy, reason });
|
|
347519
347832
|
return result.length;
|
|
347520
347833
|
}
|
|
347521
347834
|
async listConfigs() {
|
|
@@ -347537,7 +347850,7 @@ class PayloadStoreService {
|
|
|
347537
347850
|
}
|
|
347538
347851
|
}).returning();
|
|
347539
347852
|
this.configCache.delete(eventType);
|
|
347540
|
-
|
|
347853
|
+
log80.info("Payload storage config updated", { eventType });
|
|
347541
347854
|
if (!result) {
|
|
347542
347855
|
throw new Error("Failed to create/update payload storage config");
|
|
347543
347856
|
}
|
|
@@ -347589,17 +347902,17 @@ class PayloadStoreService {
|
|
|
347589
347902
|
totalDeleted += deleted.length;
|
|
347590
347903
|
}
|
|
347591
347904
|
if (totalDeleted > 0) {
|
|
347592
|
-
|
|
347905
|
+
log80.info("Cleaned up expired payloads", { count: totalDeleted });
|
|
347593
347906
|
}
|
|
347594
347907
|
return totalDeleted;
|
|
347595
347908
|
}
|
|
347596
347909
|
}
|
|
347597
|
-
var
|
|
347910
|
+
var log80;
|
|
347598
347911
|
var init_payload_store2 = __esm(() => {
|
|
347599
347912
|
init_src();
|
|
347600
347913
|
init_src4();
|
|
347601
347914
|
init_drizzle_orm();
|
|
347602
|
-
|
|
347915
|
+
log80 = createLogger("payload-store");
|
|
347603
347916
|
});
|
|
347604
347917
|
|
|
347605
347918
|
// ../api/src/services/persons.ts
|
|
@@ -348109,7 +348422,7 @@ class RouteResolver {
|
|
|
348109
348422
|
}
|
|
348110
348423
|
async resolve(instanceId, chatId, personId) {
|
|
348111
348424
|
if (!UUID_RE2.test(chatId)) {
|
|
348112
|
-
|
|
348425
|
+
log81.debug("Skipping chat route resolution \u2014 chatId is not a valid UUID", {
|
|
348113
348426
|
instanceId,
|
|
348114
348427
|
chatId,
|
|
348115
348428
|
personId
|
|
@@ -348121,7 +348434,7 @@ class RouteResolver {
|
|
|
348121
348434
|
if (cached !== undefined) {
|
|
348122
348435
|
this.metrics.hits++;
|
|
348123
348436
|
const result = cached === NO_ROUTE ? null : cached;
|
|
348124
|
-
|
|
348437
|
+
log81.debug("Route cache hit", { instanceId, chatId, personId, hit: true, hasRoute: result !== null });
|
|
348125
348438
|
return result;
|
|
348126
348439
|
}
|
|
348127
348440
|
this.metrics.misses++;
|
|
@@ -348135,7 +348448,7 @@ class RouteResolver {
|
|
|
348135
348448
|
if (!dbRoute) {
|
|
348136
348449
|
this.metrics.sets++;
|
|
348137
348450
|
this.cache.set(cacheKey, NO_ROUTE);
|
|
348138
|
-
|
|
348451
|
+
log81.debug("No route found (using instance default, cached negative result)", {
|
|
348139
348452
|
instanceId,
|
|
348140
348453
|
chatId,
|
|
348141
348454
|
personId,
|
|
@@ -348149,7 +348462,7 @@ class RouteResolver {
|
|
|
348149
348462
|
};
|
|
348150
348463
|
this.metrics.sets++;
|
|
348151
348464
|
this.cache.set(cacheKey, route);
|
|
348152
|
-
|
|
348465
|
+
log81.debug("Route resolved from DB", {
|
|
348153
348466
|
instanceId,
|
|
348154
348467
|
chatId,
|
|
348155
348468
|
personId,
|
|
@@ -348162,12 +348475,12 @@ class RouteResolver {
|
|
|
348162
348475
|
invalidateRoute(routeId) {
|
|
348163
348476
|
this.cache.clear();
|
|
348164
348477
|
this.metrics.invalidations++;
|
|
348165
|
-
|
|
348478
|
+
log81.debug("Route cache invalidated", { routeId });
|
|
348166
348479
|
}
|
|
348167
348480
|
invalidateInstance(instanceId) {
|
|
348168
348481
|
this.cache.clear();
|
|
348169
348482
|
this.metrics.invalidations++;
|
|
348170
|
-
|
|
348483
|
+
log81.debug("Instance cache invalidated", { instanceId });
|
|
348171
348484
|
}
|
|
348172
348485
|
getMetrics() {
|
|
348173
348486
|
const total = this.metrics.hits + this.metrics.misses;
|
|
@@ -348182,13 +348495,13 @@ class RouteResolver {
|
|
|
348182
348495
|
return `${instanceId}:${chatId ?? "null"}:${personId ?? "null"}`;
|
|
348183
348496
|
}
|
|
348184
348497
|
}
|
|
348185
|
-
var
|
|
348498
|
+
var log81, UUID_RE2, NO_ROUTE;
|
|
348186
348499
|
var init_route_resolver = __esm(() => {
|
|
348187
348500
|
init_src();
|
|
348188
348501
|
init_src4();
|
|
348189
348502
|
init_drizzle_orm();
|
|
348190
348503
|
init_index_min();
|
|
348191
|
-
|
|
348504
|
+
log81 = createLogger("route-resolver");
|
|
348192
348505
|
UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
348193
348506
|
NO_ROUTE = Symbol("NO_ROUTE");
|
|
348194
348507
|
});
|
|
@@ -348423,7 +348736,7 @@ class SettingsService {
|
|
|
348423
348736
|
}
|
|
348424
348737
|
}
|
|
348425
348738
|
if (seeded > 0) {
|
|
348426
|
-
|
|
348739
|
+
log82.info("Seeded default settings", { count: seeded });
|
|
348427
348740
|
}
|
|
348428
348741
|
return seeded;
|
|
348429
348742
|
}
|
|
@@ -348484,12 +348797,12 @@ class SettingsService {
|
|
|
348484
348797
|
return "string";
|
|
348485
348798
|
}
|
|
348486
348799
|
}
|
|
348487
|
-
var
|
|
348800
|
+
var log82, DEFAULT_SETTINGS;
|
|
348488
348801
|
var init_settings = __esm(() => {
|
|
348489
348802
|
init_src();
|
|
348490
348803
|
init_src4();
|
|
348491
348804
|
init_drizzle_orm();
|
|
348492
|
-
|
|
348805
|
+
log82 = createLogger("settings");
|
|
348493
348806
|
DEFAULT_SETTINGS = [
|
|
348494
348807
|
{
|
|
348495
348808
|
key: "elevenlabs.api_key",
|
|
@@ -349011,7 +349324,7 @@ class TurnService {
|
|
|
349011
349324
|
if (!turn) {
|
|
349012
349325
|
throw new Error("Failed to create turn");
|
|
349013
349326
|
}
|
|
349014
|
-
|
|
349327
|
+
log83.info("Turn opened", {
|
|
349015
349328
|
turnId: turn.id,
|
|
349016
349329
|
instanceId: options.instanceId,
|
|
349017
349330
|
chatId: options.chatId,
|
|
@@ -349032,7 +349345,7 @@ class TurnService {
|
|
|
349032
349345
|
}).where(and2(eq(turns.id, turnId), eq(turns.status, "open"))).returning();
|
|
349033
349346
|
if (closed) {
|
|
349034
349347
|
const durationMs = now.getTime() - closed.startedAt.getTime();
|
|
349035
|
-
|
|
349348
|
+
log83.info("Turn closed", {
|
|
349036
349349
|
turnId,
|
|
349037
349350
|
action: options.action,
|
|
349038
349351
|
durationMs,
|
|
@@ -349065,12 +349378,12 @@ class TurnService {
|
|
|
349065
349378
|
await this.db.update(turns).set({ messagesSent: sql`${turns.messagesSent} + 1` }).where(eq(turns.id, turnId));
|
|
349066
349379
|
}
|
|
349067
349380
|
}
|
|
349068
|
-
var
|
|
349381
|
+
var log83;
|
|
349069
349382
|
var init_turns = __esm(() => {
|
|
349070
349383
|
init_src();
|
|
349071
349384
|
init_src4();
|
|
349072
349385
|
init_drizzle_orm();
|
|
349073
|
-
|
|
349386
|
+
log83 = createLogger("turns");
|
|
349074
349387
|
});
|
|
349075
349388
|
|
|
349076
349389
|
// ../api/src/services/webhooks.ts
|
|
@@ -349486,15 +349799,15 @@ function isClientError(error2) {
|
|
|
349486
349799
|
}
|
|
349487
349800
|
return false;
|
|
349488
349801
|
}
|
|
349489
|
-
var
|
|
349802
|
+
var log84, SENSITIVE_KEYS, ERROR_STATUS_MAP, CHANNEL_ERROR_MAP, PG_CLIENT_ERROR_CODES, errorHandler2 = (error2, c) => {
|
|
349490
349803
|
const requestId = c.get("requestId") ?? "unknown";
|
|
349491
349804
|
if (isClientError(error2)) {
|
|
349492
|
-
|
|
349805
|
+
log84.debug("Client error", {
|
|
349493
349806
|
requestId,
|
|
349494
349807
|
error: error2 instanceof Error ? error2.message : String(error2)
|
|
349495
349808
|
});
|
|
349496
349809
|
} else {
|
|
349497
|
-
|
|
349810
|
+
log84.error("Server error", {
|
|
349498
349811
|
requestId,
|
|
349499
349812
|
error: error2 instanceof Error ? error2.message : String(error2),
|
|
349500
349813
|
stack: error2 instanceof Error ? error2.stack : undefined
|
|
@@ -349522,7 +349835,7 @@ var init_error3 = __esm(() => {
|
|
|
349522
349835
|
init_esm5();
|
|
349523
349836
|
init_http_exception();
|
|
349524
349837
|
init_zod();
|
|
349525
|
-
|
|
349838
|
+
log84 = createLogger("api:error");
|
|
349526
349839
|
SENSITIVE_KEYS = new Set([
|
|
349527
349840
|
"password",
|
|
349528
349841
|
"token",
|
|
@@ -349768,22 +350081,22 @@ function createWebhookAuthMiddleware(config4) {
|
|
|
349768
350081
|
const token = c.req.header("x-telegram-bot-api-secret-token");
|
|
349769
350082
|
if (!token) {
|
|
349770
350083
|
const ip = c.req.header("x-forwarded-for") || c.req.header("x-real-ip") || "unknown";
|
|
349771
|
-
|
|
350084
|
+
log85.warn("Webhook request missing secret token", { ip });
|
|
349772
350085
|
return c.json({ error: { code: "UNAUTHORIZED", message: "Missing webhook secret token" } }, 401);
|
|
349773
350086
|
}
|
|
349774
350087
|
if (token !== webhookSecret) {
|
|
349775
350088
|
const ip = c.req.header("x-forwarded-for") || c.req.header("x-real-ip") || "unknown";
|
|
349776
|
-
|
|
350089
|
+
log85.warn("Webhook request with invalid secret token", { ip });
|
|
349777
350090
|
return c.json({ error: { code: "UNAUTHORIZED", message: "Invalid webhook secret token" } }, 401);
|
|
349778
350091
|
}
|
|
349779
350092
|
return next();
|
|
349780
350093
|
});
|
|
349781
350094
|
}
|
|
349782
|
-
var
|
|
350095
|
+
var log85;
|
|
349783
350096
|
var init_webhook_auth = __esm(() => {
|
|
349784
350097
|
init_src();
|
|
349785
350098
|
init_factory2();
|
|
349786
|
-
|
|
350099
|
+
log85 = createLogger("api:webhook-auth");
|
|
349787
350100
|
});
|
|
349788
350101
|
|
|
349789
350102
|
// ../api/src/routes/health.ts
|
|
@@ -353782,7 +354095,8 @@ var init_logs = __esm(() => {
|
|
|
353782
354095
|
time: exports_external.number().openapi({ description: "Timestamp (ms)" }),
|
|
353783
354096
|
level: exports_external.enum(["debug", "info", "warn", "error"]).openapi({ description: "Log level" }),
|
|
353784
354097
|
module: exports_external.string().openapi({ description: "Module name" }),
|
|
353785
|
-
msg: exports_external.string().openapi({ description: "Log message" })
|
|
354098
|
+
msg: exports_external.string().openapi({ description: "Log message" }),
|
|
354099
|
+
data: exports_external.record(exports_external.string(), exports_external.unknown()).optional().openapi({ description: "Additional contextual data (stack traces, agent/chat IDs, error details)" })
|
|
353786
354100
|
});
|
|
353787
354101
|
});
|
|
353788
354102
|
|
|
@@ -358295,12 +358609,12 @@ async function printQrCodeToTerminal(qrCode, instanceId) {
|
|
|
358295
358609
|
try {
|
|
358296
358610
|
const qrTerminalModule = await Promise.resolve().then(() => __toESM(require_main(), 1));
|
|
358297
358611
|
const qrTerminal = qrTerminalModule.default || qrTerminalModule;
|
|
358298
|
-
|
|
358612
|
+
log86.info("QR Code generated for WhatsApp", { instanceId });
|
|
358299
358613
|
qrTerminal.generate(qrCode, { small: true });
|
|
358300
358614
|
} catch (error2) {
|
|
358301
|
-
|
|
358615
|
+
log86.info("QR Code generated", { instanceId, qrCode: `${qrCode.substring(0, 50)}...` });
|
|
358302
358616
|
if (error2 instanceof Error && process.env.DEBUG) {
|
|
358303
|
-
|
|
358617
|
+
log86.debug("QR Terminal unavailable", { error: error2.message });
|
|
358304
358618
|
}
|
|
358305
358619
|
}
|
|
358306
358620
|
}
|
|
@@ -358312,13 +358626,13 @@ async function setupQrCodeListener(eventBus) {
|
|
|
358312
358626
|
await printQrCodeToTerminal(qrCode, instanceId);
|
|
358313
358627
|
});
|
|
358314
358628
|
} catch (error2) {
|
|
358315
|
-
|
|
358629
|
+
log86.warn("Failed to set up QR code listener", { error: String(error2) });
|
|
358316
358630
|
}
|
|
358317
358631
|
}
|
|
358318
|
-
var
|
|
358632
|
+
var log86, qrCodes;
|
|
358319
358633
|
var init_qr_store = __esm(() => {
|
|
358320
358634
|
init_src();
|
|
358321
|
-
|
|
358635
|
+
log86 = createLogger("api:qr-store");
|
|
358322
358636
|
qrCodes = new Map;
|
|
358323
358637
|
});
|
|
358324
358638
|
|
|
@@ -358339,29 +358653,29 @@ class AgentReplayService {
|
|
|
358339
358653
|
agentId: instances.agentId
|
|
358340
358654
|
}).from(instances).where(eq(instances.id, instanceId)).limit(1);
|
|
358341
358655
|
if (!instance4) {
|
|
358342
|
-
|
|
358656
|
+
log87.warn("Instance not found for replay", { instanceId });
|
|
358343
358657
|
return;
|
|
358344
358658
|
}
|
|
358345
358659
|
if (!instance4.agentId) {
|
|
358346
|
-
|
|
358660
|
+
log87.debug("Instance has no agent, skipping replay", { instanceId });
|
|
358347
358661
|
await this.updateLastSeenAt(instanceId);
|
|
358348
358662
|
return;
|
|
358349
358663
|
}
|
|
358350
358664
|
if (!instance4.replayEnabled) {
|
|
358351
|
-
|
|
358665
|
+
log87.debug("Replay disabled for instance", { instanceId });
|
|
358352
358666
|
await this.updateLastSeenAt(instanceId);
|
|
358353
358667
|
return;
|
|
358354
358668
|
}
|
|
358355
358669
|
const since = instance4.lastSeenAt ?? null;
|
|
358356
358670
|
if (!since) {
|
|
358357
|
-
|
|
358671
|
+
log87.debug("No lastSeenAt recorded, skipping replay (first connect)", { instanceId });
|
|
358358
358672
|
await this.updateLastSeenAt(instanceId);
|
|
358359
358673
|
return;
|
|
358360
358674
|
}
|
|
358361
|
-
|
|
358675
|
+
log87.info("Starting replay on reconnect", { instanceId, since: since.toISOString() });
|
|
358362
358676
|
try {
|
|
358363
358677
|
const result = await this.replayMissedMessages({ instanceId, since });
|
|
358364
|
-
|
|
358678
|
+
log87.info("Replay complete", {
|
|
358365
358679
|
instanceId,
|
|
358366
358680
|
replayed: result.replayed,
|
|
358367
358681
|
skipped: result.skipped,
|
|
@@ -358369,7 +358683,7 @@ class AgentReplayService {
|
|
|
358369
358683
|
});
|
|
358370
358684
|
await this.updateLastSeenAt(instanceId, result.until);
|
|
358371
358685
|
} catch (error2) {
|
|
358372
|
-
|
|
358686
|
+
log87.error("Replay failed", { instanceId, error: String(error2) });
|
|
358373
358687
|
}
|
|
358374
358688
|
}
|
|
358375
358689
|
async replayMissedMessages(options) {
|
|
@@ -358377,7 +358691,7 @@ class AgentReplayService {
|
|
|
358377
358691
|
const now = new Date;
|
|
358378
358692
|
const cutoff = new Date(now.getTime() - MAX_REPLAY_WINDOW_MS);
|
|
358379
358693
|
const since = options.since && options.since > cutoff ? options.since : cutoff;
|
|
358380
|
-
|
|
358694
|
+
log87.debug("Fetching missed messages", { instanceId, since: since.toISOString(), until: now.toISOString() });
|
|
358381
358695
|
let cursorTimestamp = since;
|
|
358382
358696
|
let cursorId = null;
|
|
358383
358697
|
let totalReplayed = 0;
|
|
@@ -358405,7 +358719,7 @@ class AgentReplayService {
|
|
|
358405
358719
|
if (rows.length === 0)
|
|
358406
358720
|
break;
|
|
358407
358721
|
if (rows.length === PAGE_SIZE) {
|
|
358408
|
-
|
|
358722
|
+
log87.warn("Replay page cap hit, fetching next page", {
|
|
358409
358723
|
instanceId,
|
|
358410
358724
|
limit: PAGE_SIZE,
|
|
358411
358725
|
cursor: cursorTimestamp.toISOString()
|
|
@@ -358433,7 +358747,7 @@ class AgentReplayService {
|
|
|
358433
358747
|
await this.redispatchMessage(instanceId, row);
|
|
358434
358748
|
replayed++;
|
|
358435
358749
|
} catch (error2) {
|
|
358436
|
-
|
|
358750
|
+
log87.warn("Failed to redispatch message during replay", {
|
|
358437
358751
|
instanceId,
|
|
358438
358752
|
messageId: row.id,
|
|
358439
358753
|
error: String(error2)
|
|
@@ -358490,12 +358804,12 @@ function mapMessageTypeToContentType(messageType) {
|
|
|
358490
358804
|
return "text";
|
|
358491
358805
|
}
|
|
358492
358806
|
}
|
|
358493
|
-
var
|
|
358807
|
+
var log87, MAX_REPLAY_WINDOW_MS;
|
|
358494
358808
|
var init_agent_replay = __esm(() => {
|
|
358495
358809
|
init_src();
|
|
358496
358810
|
init_src4();
|
|
358497
358811
|
init_drizzle_orm();
|
|
358498
|
-
|
|
358812
|
+
log87 = createLogger("agent-replay");
|
|
358499
358813
|
MAX_REPLAY_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
358500
358814
|
});
|
|
358501
358815
|
|
|
@@ -358619,15 +358933,15 @@ async function connectInstanceWithPlugin(plugin6, instanceId, options) {
|
|
|
358619
358933
|
async function triggerCreateConnection(channelRegistry2, channel4, instanceId, options) {
|
|
358620
358934
|
const plugin6 = getPluginFromRegistry(channelRegistry2, channel4);
|
|
358621
358935
|
if (!plugin6) {
|
|
358622
|
-
|
|
358936
|
+
log88.warn("No plugin found for channel", { channel: channel4 });
|
|
358623
358937
|
return;
|
|
358624
358938
|
}
|
|
358625
358939
|
const errorMessage = await connectInstanceWithPlugin(plugin6, instanceId, options);
|
|
358626
358940
|
if (errorMessage) {
|
|
358627
|
-
|
|
358941
|
+
log88.error("Failed to connect instance", { instanceId, error: errorMessage });
|
|
358628
358942
|
return;
|
|
358629
358943
|
}
|
|
358630
|
-
|
|
358944
|
+
log88.info("Triggered connection", { instanceId, channel: channel4 });
|
|
358631
358945
|
}
|
|
358632
358946
|
function buildTokenPersistUpdates(channel4, body) {
|
|
358633
358947
|
const updates = {};
|
|
@@ -358655,10 +358969,10 @@ async function handleAgentKeyProvisioning(services, instanceId, newAgentId, oldA
|
|
|
358655
358969
|
await services.apiKeys.update(existingKey.id, {
|
|
358656
358970
|
instanceIds: updated.length > 0 ? updated : null
|
|
358657
358971
|
});
|
|
358658
|
-
|
|
358972
|
+
log88.info("Removed instance from agent key", { keyName, instanceId });
|
|
358659
358973
|
}
|
|
358660
358974
|
} catch (err) {
|
|
358661
|
-
|
|
358975
|
+
log88.error("Failed to remove instance from old agent key", { oldAgentId, instanceId, error: String(err) });
|
|
358662
358976
|
}
|
|
358663
358977
|
}
|
|
358664
358978
|
if (newAgentId) {
|
|
@@ -358672,20 +358986,21 @@ async function handleAgentKeyProvisioning(services, instanceId, newAgentId, oldA
|
|
|
358672
358986
|
await services.apiKeys.update(existingKey.id, {
|
|
358673
358987
|
instanceIds: [...currentIds, instanceId]
|
|
358674
358988
|
});
|
|
358675
|
-
|
|
358989
|
+
log88.info("Added instance to existing agent key", { keyName, instanceId });
|
|
358676
358990
|
}
|
|
358677
358991
|
} else {
|
|
358992
|
+
const agentScopes = Array.isArray(agent3.metadata?.omniScopes) ? agent3.metadata.omniScopes : [...DEFAULT_TURN_SCOPES];
|
|
358678
358993
|
const result = await services.apiKeys.create({
|
|
358679
358994
|
name: keyName,
|
|
358680
358995
|
description: `Auto-provisioned scoped key for agent ${agent3.name}`,
|
|
358681
|
-
scopes:
|
|
358996
|
+
scopes: agentScopes,
|
|
358682
358997
|
instanceIds: [instanceId],
|
|
358683
358998
|
createdBy: "system:auto-provision"
|
|
358684
358999
|
});
|
|
358685
|
-
|
|
359000
|
+
log88.info("Created scoped agent key", { keyName, instanceId, keyId: result.key.id });
|
|
358686
359001
|
}
|
|
358687
359002
|
} catch (err) {
|
|
358688
|
-
|
|
359003
|
+
log88.error("Failed to provision agent key", { newAgentId, instanceId, error: String(err) });
|
|
358689
359004
|
}
|
|
358690
359005
|
}
|
|
358691
359006
|
}
|
|
@@ -358764,18 +359079,19 @@ function getCacheKey(instanceId, guildId) {
|
|
|
358764
359079
|
function invalidateGuildCache(instanceId, guildId) {
|
|
358765
359080
|
guildConfigCache.delete(getCacheKey(instanceId, guildId));
|
|
358766
359081
|
}
|
|
358767
|
-
var
|
|
359082
|
+
var log88, instancesRoutes, instanceAccess2, listQuerySchema10, agentReplyFilterSchema, createInstanceSchema, updateInstanceSchema, SENSITIVE_INSTANCE_FIELDS, pairingCodeSchema, connectInstanceSchema, syncRequestSchema, listContactsQuerySchema, listGroupsQuerySchema, checkNumberSchema, updateBioSchema, blockContactSchema, resyncSchema, replaySchema, pairingActionSchema, guildConfigOverrideSchema, guildConfigCache, GUILD_CONFIG_TTL, presenceSchema;
|
|
358768
359083
|
var init_instances3 = __esm(() => {
|
|
358769
359084
|
init_dist6();
|
|
358770
359085
|
init_src();
|
|
358771
359086
|
init_dist2();
|
|
358772
359087
|
init_zod();
|
|
358773
359088
|
init_cache_keys();
|
|
359089
|
+
init_scopes();
|
|
358774
359090
|
init_auth();
|
|
358775
359091
|
init_qr_store();
|
|
358776
359092
|
init_access();
|
|
358777
359093
|
init_agent_replay();
|
|
358778
|
-
|
|
359094
|
+
log88 = createLogger("api:instances");
|
|
358779
359095
|
instancesRoutes = new Hono2;
|
|
358780
359096
|
instanceAccess2 = requireInstanceAccess((c) => c.req.param("id"));
|
|
358781
359097
|
listQuerySchema10 = exports_external.object({
|
|
@@ -358968,7 +359284,7 @@ var init_instances3 = __esm(() => {
|
|
|
358968
359284
|
try {
|
|
358969
359285
|
await plugin6.disconnect(id);
|
|
358970
359286
|
} catch (error2) {
|
|
358971
|
-
|
|
359287
|
+
log88.error("Failed to disconnect instance before delete", { instanceId: id, error: String(error2) });
|
|
358972
359288
|
}
|
|
358973
359289
|
}
|
|
358974
359290
|
await services.instances.delete(id);
|
|
@@ -358976,7 +359292,7 @@ var init_instances3 = __esm(() => {
|
|
|
358976
359292
|
try {
|
|
358977
359293
|
await plugin6.logout(id);
|
|
358978
359294
|
} catch (error2) {
|
|
358979
|
-
|
|
359295
|
+
log88.error("Failed to clear channel auth after delete", { instanceId: id, error: String(error2) });
|
|
358980
359296
|
}
|
|
358981
359297
|
}
|
|
358982
359298
|
return c.json({ success: true });
|
|
@@ -359159,7 +359475,7 @@ var init_instances3 = __esm(() => {
|
|
|
359159
359475
|
try {
|
|
359160
359476
|
await plugin6.disconnect(id);
|
|
359161
359477
|
} catch (error2) {
|
|
359162
|
-
|
|
359478
|
+
log88.error("Failed to disconnect instance", { instanceId: id, error: String(error2) });
|
|
359163
359479
|
}
|
|
359164
359480
|
}
|
|
359165
359481
|
}
|
|
@@ -359230,13 +359546,13 @@ var init_instances3 = __esm(() => {
|
|
|
359230
359546
|
try {
|
|
359231
359547
|
await plugin6.logout(id);
|
|
359232
359548
|
} catch (error2) {
|
|
359233
|
-
|
|
359549
|
+
log88.error("Failed to logout instance", { instanceId: id, error: String(error2) });
|
|
359234
359550
|
}
|
|
359235
359551
|
} else if (plugin6) {
|
|
359236
359552
|
try {
|
|
359237
359553
|
await plugin6.disconnect(id);
|
|
359238
359554
|
} catch (error2) {
|
|
359239
|
-
|
|
359555
|
+
log88.error("Failed to disconnect instance during logout", { instanceId: id, error: String(error2) });
|
|
359240
359556
|
}
|
|
359241
359557
|
}
|
|
359242
359558
|
}
|
|
@@ -360026,7 +360342,7 @@ var init_instances3 = __esm(() => {
|
|
|
360026
360342
|
...chatJids?.length ? { chatJids } : {}
|
|
360027
360343
|
}
|
|
360028
360344
|
});
|
|
360029
|
-
|
|
360345
|
+
log88.info("Resync triggered", {
|
|
360030
360346
|
instanceId: id,
|
|
360031
360347
|
jobId: job.id,
|
|
360032
360348
|
since: sinceDate.toISOString(),
|
|
@@ -360044,7 +360360,7 @@ var init_instances3 = __esm(() => {
|
|
|
360044
360360
|
});
|
|
360045
360361
|
} catch (error2) {
|
|
360046
360362
|
const message2 = error2 instanceof Error ? error2.message : "Unknown error";
|
|
360047
|
-
|
|
360363
|
+
log88.error("Failed to trigger resync", { instanceId: id, error: message2 });
|
|
360048
360364
|
return c.json({ error: { code: "RESYNC_FAILED", message: message2 } }, 500);
|
|
360049
360365
|
}
|
|
360050
360366
|
});
|
|
@@ -360073,7 +360389,7 @@ var init_instances3 = __esm(() => {
|
|
|
360073
360389
|
const sinceDate = since ? new Date(since) : undefined;
|
|
360074
360390
|
try {
|
|
360075
360391
|
const result = await replayService.replayMissedMessages({ instanceId: instance4.id, since: sinceDate });
|
|
360076
|
-
|
|
360392
|
+
log88.info("Manual replay triggered", {
|
|
360077
360393
|
instanceId: instance4.id,
|
|
360078
360394
|
replayed: result.replayed,
|
|
360079
360395
|
since: result.since.toISOString()
|
|
@@ -360089,7 +360405,7 @@ var init_instances3 = __esm(() => {
|
|
|
360089
360405
|
});
|
|
360090
360406
|
} catch (error2) {
|
|
360091
360407
|
const message2 = error2 instanceof Error ? error2.message : "Unknown error";
|
|
360092
|
-
|
|
360408
|
+
log88.error("Manual replay failed", { instanceId: id, error: message2 });
|
|
360093
360409
|
return c.json({ error: { code: "REPLAY_FAILED", message: message2 } }, 500);
|
|
360094
360410
|
}
|
|
360095
360411
|
});
|
|
@@ -360222,7 +360538,7 @@ var init_instances3 = __esm(() => {
|
|
|
360222
360538
|
plugin6.setGuildConfig(id, guildId, newConfig);
|
|
360223
360539
|
}
|
|
360224
360540
|
}
|
|
360225
|
-
|
|
360541
|
+
log88.info("Guild config updated", {
|
|
360226
360542
|
instanceId: id,
|
|
360227
360543
|
guildId,
|
|
360228
360544
|
apiKeyId: apiKey?.id,
|
|
@@ -360251,7 +360567,7 @@ var init_instances3 = __esm(() => {
|
|
|
360251
360567
|
plugin6.removeGuildConfig(id, guildId);
|
|
360252
360568
|
}
|
|
360253
360569
|
}
|
|
360254
|
-
|
|
360570
|
+
log88.info("Guild config deleted", {
|
|
360255
360571
|
instanceId: id,
|
|
360256
360572
|
guildId,
|
|
360257
360573
|
apiKeyId: apiKey?.id,
|
|
@@ -360352,7 +360668,6 @@ var init_keys = __esm(() => {
|
|
|
360352
360668
|
init_dist6();
|
|
360353
360669
|
init_dist2();
|
|
360354
360670
|
init_zod();
|
|
360355
|
-
init_auth();
|
|
360356
360671
|
keysRoutes = new Hono2;
|
|
360357
360672
|
createKeySchema = exports_external.object({
|
|
360358
360673
|
name: exports_external.string().min(1).max(255).describe("Human-readable key name"),
|
|
@@ -360386,7 +360701,7 @@ var init_keys = __esm(() => {
|
|
|
360386
360701
|
limit: exports_external.coerce.number().int().min(1).max(100).default(50).describe("Max results"),
|
|
360387
360702
|
cursor: exports_external.string().optional().describe("Pagination cursor")
|
|
360388
360703
|
});
|
|
360389
|
-
keysRoutes.post("/",
|
|
360704
|
+
keysRoutes.post("/", zValidator("json", createKeySchema), async (c) => {
|
|
360390
360705
|
const data = c.req.valid("json");
|
|
360391
360706
|
const services = c.get("services");
|
|
360392
360707
|
const result = await services.apiKeys.create({
|
|
@@ -360405,7 +360720,7 @@ var init_keys = __esm(() => {
|
|
|
360405
360720
|
}
|
|
360406
360721
|
}, 201);
|
|
360407
360722
|
});
|
|
360408
|
-
keysRoutes.get("/",
|
|
360723
|
+
keysRoutes.get("/", zValidator("query", listQuerySchema11), async (c) => {
|
|
360409
360724
|
const { status, limit: limit2 } = c.req.valid("query");
|
|
360410
360725
|
const services = c.get("services");
|
|
360411
360726
|
let items = await services.apiKeys.list();
|
|
@@ -360420,7 +360735,7 @@ var init_keys = __esm(() => {
|
|
|
360420
360735
|
}
|
|
360421
360736
|
});
|
|
360422
360737
|
});
|
|
360423
|
-
keysRoutes.get("/:id",
|
|
360738
|
+
keysRoutes.get("/:id", async (c) => {
|
|
360424
360739
|
const id = c.req.param("id");
|
|
360425
360740
|
const services = c.get("services");
|
|
360426
360741
|
const key = await services.apiKeys.getById(id);
|
|
@@ -360429,7 +360744,7 @@ var init_keys = __esm(() => {
|
|
|
360429
360744
|
}
|
|
360430
360745
|
return c.json({ data: key });
|
|
360431
360746
|
});
|
|
360432
|
-
keysRoutes.patch("/:id",
|
|
360747
|
+
keysRoutes.patch("/:id", zValidator("json", updateKeySchema), async (c) => {
|
|
360433
360748
|
const id = c.req.param("id");
|
|
360434
360749
|
const data = c.req.valid("json");
|
|
360435
360750
|
const services = c.get("services");
|
|
@@ -360450,7 +360765,7 @@ var init_keys = __esm(() => {
|
|
|
360450
360765
|
throw error2;
|
|
360451
360766
|
}
|
|
360452
360767
|
});
|
|
360453
|
-
keysRoutes.post("/:id/revoke",
|
|
360768
|
+
keysRoutes.post("/:id/revoke", zValidator("json", revokeKeySchema), async (c) => {
|
|
360454
360769
|
const id = c.req.param("id");
|
|
360455
360770
|
const data = c.req.valid("json");
|
|
360456
360771
|
const services = c.get("services");
|
|
@@ -360460,7 +360775,7 @@ var init_keys = __esm(() => {
|
|
|
360460
360775
|
}
|
|
360461
360776
|
return c.json({ data: revoked });
|
|
360462
360777
|
});
|
|
360463
|
-
keysRoutes.delete("/:id",
|
|
360778
|
+
keysRoutes.delete("/:id", async (c) => {
|
|
360464
360779
|
const id = c.req.param("id");
|
|
360465
360780
|
const services = c.get("services");
|
|
360466
360781
|
try {
|
|
@@ -360477,7 +360792,7 @@ var init_keys = __esm(() => {
|
|
|
360477
360792
|
throw error2;
|
|
360478
360793
|
}
|
|
360479
360794
|
});
|
|
360480
|
-
keysRoutes.get("/:id/audit",
|
|
360795
|
+
keysRoutes.get("/:id/audit", zValidator("query", auditQuerySchema), async (c) => {
|
|
360481
360796
|
const id = c.req.param("id");
|
|
360482
360797
|
const { since, until, path: path4, statusCode, limit: limit2, cursor } = c.req.valid("query");
|
|
360483
360798
|
const services = c.get("services");
|
|
@@ -360571,10 +360886,15 @@ var init_logs2 = __esm(() => {
|
|
|
360571
360886
|
modules,
|
|
360572
360887
|
limit: limit2
|
|
360573
360888
|
});
|
|
360889
|
+
const items = entries.map((entry) => {
|
|
360890
|
+
const { time: time3, level: entryLevel, module, msg, ...rest } = entry;
|
|
360891
|
+
const hasData = Object.keys(rest).length > 0;
|
|
360892
|
+
return hasData ? { time: time3, level: entryLevel, module, msg, data: rest } : { time: time3, level: entryLevel, module, msg };
|
|
360893
|
+
});
|
|
360574
360894
|
return c.json({
|
|
360575
|
-
items
|
|
360895
|
+
items,
|
|
360576
360896
|
meta: {
|
|
360577
|
-
total:
|
|
360897
|
+
total: items.length,
|
|
360578
360898
|
bufferSize: buffer3.maxSize,
|
|
360579
360899
|
limit: limit2
|
|
360580
360900
|
}
|
|
@@ -360601,7 +360921,7 @@ function isValidPathComponent(component) {
|
|
|
360601
360921
|
function isValidUUID(str2) {
|
|
360602
360922
|
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(str2);
|
|
360603
360923
|
}
|
|
360604
|
-
var
|
|
360924
|
+
var log89, mediaRoutes, mediaStorage = null, ttsAudioFormatSchema, ttsRequestSchema, sttRequestSchema, imagineAspectRatioSchema, imagineRequestSchema, visionRequestSchema, filmAspectRatioSchema, filmRequestSchema, FILM_TIMEOUT_MS, FILM_POLL_INTERVAL_MS = 5000;
|
|
360605
360925
|
var init_media = __esm(() => {
|
|
360606
360926
|
init_dist6();
|
|
360607
360927
|
init_src();
|
|
@@ -360609,7 +360929,7 @@ var init_media = __esm(() => {
|
|
|
360609
360929
|
init_zod();
|
|
360610
360930
|
init_registry3();
|
|
360611
360931
|
init_media_storage();
|
|
360612
|
-
|
|
360932
|
+
log89 = createLogger("routes:media");
|
|
360613
360933
|
mediaRoutes = new Hono2;
|
|
360614
360934
|
ttsAudioFormatSchema = exports_external.enum(["mp3", "ogg", "opus", "wav", "pcm", "flac", "aac"]);
|
|
360615
360935
|
ttsRequestSchema = exports_external.object({
|
|
@@ -360628,7 +360948,7 @@ var init_media = __esm(() => {
|
|
|
360628
360948
|
provider = await providerRegistry.resolve("tts", body.provider);
|
|
360629
360949
|
} catch (err) {
|
|
360630
360950
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360631
|
-
|
|
360951
|
+
log89.warn("TTS provider resolution failed", { provider: body.provider, error: message2 });
|
|
360632
360952
|
return c.json({
|
|
360633
360953
|
error: {
|
|
360634
360954
|
code: "PROVIDER_NOT_AVAILABLE",
|
|
@@ -360656,7 +360976,7 @@ var init_media = __esm(() => {
|
|
|
360656
360976
|
});
|
|
360657
360977
|
} catch (err) {
|
|
360658
360978
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360659
|
-
|
|
360979
|
+
log89.error("TTS synthesis failed", { provider: provider.name, error: message2 });
|
|
360660
360980
|
return c.json({
|
|
360661
360981
|
error: {
|
|
360662
360982
|
code: "TTS_SYNTHESIS_FAILED",
|
|
@@ -360681,7 +361001,7 @@ var init_media = __esm(() => {
|
|
|
360681
361001
|
provider = await providerRegistry.resolve("stt", body.provider);
|
|
360682
361002
|
} catch (err) {
|
|
360683
361003
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360684
|
-
|
|
361004
|
+
log89.warn("STT provider resolution failed", { provider: body.provider, error: message2 });
|
|
360685
361005
|
return c.json({
|
|
360686
361006
|
error: {
|
|
360687
361007
|
code: "PROVIDER_NOT_AVAILABLE",
|
|
@@ -360722,7 +361042,7 @@ var init_media = __esm(() => {
|
|
|
360722
361042
|
});
|
|
360723
361043
|
} catch (err) {
|
|
360724
361044
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360725
|
-
|
|
361045
|
+
log89.error("STT transcription failed", { provider: provider.name, error: message2 });
|
|
360726
361046
|
return c.json({
|
|
360727
361047
|
error: {
|
|
360728
361048
|
code: "STT_TRANSCRIPTION_FAILED",
|
|
@@ -360750,7 +361070,7 @@ var init_media = __esm(() => {
|
|
|
360750
361070
|
provider = await providerRegistry.resolve("imagegen", body.provider);
|
|
360751
361071
|
} catch (err) {
|
|
360752
361072
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360753
|
-
|
|
361073
|
+
log89.warn("Imagegen provider resolution failed", { provider: body.provider, error: message2 });
|
|
360754
361074
|
return c.json({
|
|
360755
361075
|
error: {
|
|
360756
361076
|
code: "PROVIDER_NOT_AVAILABLE",
|
|
@@ -360784,7 +361104,7 @@ var init_media = __esm(() => {
|
|
|
360784
361104
|
});
|
|
360785
361105
|
} catch (err) {
|
|
360786
361106
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360787
|
-
|
|
361107
|
+
log89.error("Image generation failed", { provider: provider.name, error: message2 });
|
|
360788
361108
|
return c.json({
|
|
360789
361109
|
error: {
|
|
360790
361110
|
code: "IMAGE_GEN_FAILED",
|
|
@@ -360809,7 +361129,7 @@ var init_media = __esm(() => {
|
|
|
360809
361129
|
provider = await providerRegistry.resolve("vision", body.provider);
|
|
360810
361130
|
} catch (err) {
|
|
360811
361131
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360812
|
-
|
|
361132
|
+
log89.warn("Vision provider resolution failed", { provider: body.provider, error: message2 });
|
|
360813
361133
|
return c.json({
|
|
360814
361134
|
error: {
|
|
360815
361135
|
code: "PROVIDER_NOT_AVAILABLE",
|
|
@@ -360848,7 +361168,7 @@ var init_media = __esm(() => {
|
|
|
360848
361168
|
});
|
|
360849
361169
|
} catch (err) {
|
|
360850
361170
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360851
|
-
|
|
361171
|
+
log89.error("Vision description failed", { provider: provider.name, error: message2 });
|
|
360852
361172
|
return c.json({
|
|
360853
361173
|
error: {
|
|
360854
361174
|
code: "VISION_DESCRIBE_FAILED",
|
|
@@ -360876,7 +361196,7 @@ var init_media = __esm(() => {
|
|
|
360876
361196
|
provider = await providerRegistry.resolve("videogen", body.provider);
|
|
360877
361197
|
} catch (err) {
|
|
360878
361198
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360879
|
-
|
|
361199
|
+
log89.warn("Videogen provider resolution failed", { provider: body.provider, error: message2 });
|
|
360880
361200
|
return c.json({
|
|
360881
361201
|
error: {
|
|
360882
361202
|
code: "PROVIDER_NOT_AVAILABLE",
|
|
@@ -360910,7 +361230,7 @@ var init_media = __esm(() => {
|
|
|
360910
361230
|
}
|
|
360911
361231
|
if (operation.state === "failed" || !operation.video) {
|
|
360912
361232
|
const message2 = operation.error ?? "Video generation failed without error";
|
|
360913
|
-
|
|
361233
|
+
log89.error("Videogen operation failed", { provider: provider.name, error: message2 });
|
|
360914
361234
|
return c.json({
|
|
360915
361235
|
error: {
|
|
360916
361236
|
code: "VIDEO_GEN_FAILED",
|
|
@@ -360921,7 +361241,7 @@ var init_media = __esm(() => {
|
|
|
360921
361241
|
}, 500);
|
|
360922
361242
|
}
|
|
360923
361243
|
const video = operation.video;
|
|
360924
|
-
|
|
361244
|
+
log89.info("Videogen operation complete", {
|
|
360925
361245
|
provider: provider.name,
|
|
360926
361246
|
operationId: operation.operationId,
|
|
360927
361247
|
sizeBytes: video.data.length,
|
|
@@ -360940,7 +361260,7 @@ var init_media = __esm(() => {
|
|
|
360940
361260
|
});
|
|
360941
361261
|
} catch (err) {
|
|
360942
361262
|
const message2 = err instanceof Error ? err.message : "Unknown error";
|
|
360943
|
-
|
|
361263
|
+
log89.error("Videogen request failed", { provider: provider.name, error: message2 });
|
|
360944
361264
|
return c.json({
|
|
360945
361265
|
error: {
|
|
360946
361266
|
code: "VIDEO_GEN_FAILED",
|
|
@@ -361142,7 +361462,7 @@ async function verifyMessageInstanceOwnership(services, message2, instanceId) {
|
|
|
361142
361462
|
});
|
|
361143
361463
|
}
|
|
361144
361464
|
}
|
|
361145
|
-
var
|
|
361465
|
+
var log90, mediaDownloadLog, messagesRoutes, UUID_REGEX, MessageSourceSchema, MessageTypeSchema, MessageStatusSchema, DeliveryStatusSchema, listQuerySchema12, createMessageSchema, updateMessageSchema, recordEditSchema, addReactionSchema, removeReactionSchema, updateDeliveryStatusSchema, MentionSchema, sendTextSchema, sendMediaSchema, sendReactionSchema, sendStickerSchema, sendContactSchema, sendLocationSchema, messageRefSchema, _mediaStorageForDownload = null, sendTtsSchema, forwardMessageSchema, sendPresenceSchema, markMessageReadSchema, markBatchReadSchema, sendPollSchema, sendEmbedSchema, editMessageChannelSchema, deleteMessageChannelSchema, starMessageSchema;
|
|
361146
361466
|
var init_messages5 = __esm(() => {
|
|
361147
361467
|
init_dist6();
|
|
361148
361468
|
init_src2();
|
|
@@ -361153,7 +361473,7 @@ var init_messages5 = __esm(() => {
|
|
|
361153
361473
|
init_sentry_scrub();
|
|
361154
361474
|
init_api_keys();
|
|
361155
361475
|
init_media_storage();
|
|
361156
|
-
|
|
361476
|
+
log90 = createLogger("routes:messages");
|
|
361157
361477
|
mediaDownloadLog = createLogger("routes:messages:media-download");
|
|
361158
361478
|
messagesRoutes = new Hono2;
|
|
361159
361479
|
UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
@@ -361697,7 +362017,7 @@ var init_messages5 = __esm(() => {
|
|
|
361697
362017
|
if (chat2) {
|
|
361698
362018
|
const target = await services.messages.getByExternalId(chat2.id, messageId);
|
|
361699
362019
|
if (!target) {
|
|
361700
|
-
|
|
362020
|
+
log90.warn("Target message not found in DB, sending reaction anyway", { messageId, chatId: chat2.id });
|
|
361701
362021
|
}
|
|
361702
362022
|
}
|
|
361703
362023
|
const outgoingMessage = {
|
|
@@ -362431,7 +362751,7 @@ var init_messages5 = __esm(() => {
|
|
|
362431
362751
|
const message2 = await services.messages.getById(messageId);
|
|
362432
362752
|
await verifyMessageInstanceOwnership(services, message2, instanceId);
|
|
362433
362753
|
resolvedMessageId = message2.externalId;
|
|
362434
|
-
|
|
362754
|
+
log90.debug("Resolved internal UUID to external ID", { messageId, externalId: resolvedMessageId });
|
|
362435
362755
|
}
|
|
362436
362756
|
try {
|
|
362437
362757
|
await plugin6.editMessage(instanceId, channelId, resolvedMessageId, text3);
|
|
@@ -363123,9 +363443,9 @@ async function initTurnEvents(natsUrl) {
|
|
|
363123
363443
|
maxReconnectAttempts: -1,
|
|
363124
363444
|
reconnectTimeWait: 2000
|
|
363125
363445
|
});
|
|
363126
|
-
|
|
363446
|
+
log91.info("Turn events NATS connected", { url: natsUrl });
|
|
363127
363447
|
} catch (error2) {
|
|
363128
|
-
|
|
363448
|
+
log91.warn("Failed to connect NATS for turn events", { error: String(error2) });
|
|
363129
363449
|
}
|
|
363130
363450
|
}
|
|
363131
363451
|
async function closeTurnEvents() {
|
|
@@ -363136,7 +363456,7 @@ async function closeTurnEvents() {
|
|
|
363136
363456
|
}
|
|
363137
363457
|
function publish(topic, payload) {
|
|
363138
363458
|
if (!nc || nc.isClosed()) {
|
|
363139
|
-
|
|
363459
|
+
log91.warn("Cannot publish turn event: NATS not connected", { topic });
|
|
363140
363460
|
return;
|
|
363141
363461
|
}
|
|
363142
363462
|
nc.publish(topic, sc2.encode(JSON.stringify(payload)));
|
|
@@ -363144,28 +363464,28 @@ function publish(topic, payload) {
|
|
|
363144
363464
|
function publishTurnOpen(instanceId, chatId, event) {
|
|
363145
363465
|
const topic = `omni.turn.open.${instanceId}.${chatId}`;
|
|
363146
363466
|
publish(topic, event);
|
|
363147
|
-
|
|
363467
|
+
log91.debug("Published turn.open", { turnId: event.turnId, instanceId, chatId });
|
|
363148
363468
|
}
|
|
363149
363469
|
function publishTurnDone(instanceId, chatId, event) {
|
|
363150
363470
|
const topic = `omni.turn.done.${instanceId}.${chatId}`;
|
|
363151
363471
|
publish(topic, event);
|
|
363152
|
-
|
|
363472
|
+
log91.debug("Published turn.done", { turnId: event.turnId, action: event.action, instanceId });
|
|
363153
363473
|
}
|
|
363154
363474
|
function publishTurnNudge(instanceId, chatId, event) {
|
|
363155
363475
|
const topic = `omni.turn.nudge.${instanceId}.${chatId}`;
|
|
363156
363476
|
publish(topic, event);
|
|
363157
|
-
|
|
363477
|
+
log91.debug("Published turn.nudge", { turnId: event.turnId, nudgeCount: event.nudgeCount, instanceId });
|
|
363158
363478
|
}
|
|
363159
363479
|
function publishTurnTimeout(instanceId, chatId, event) {
|
|
363160
363480
|
const topic = `omni.turn.timeout.${instanceId}.${chatId}`;
|
|
363161
363481
|
publish(topic, event);
|
|
363162
|
-
|
|
363482
|
+
log91.debug("Published turn.timeout", { turnId: event.turnId, instanceId });
|
|
363163
363483
|
}
|
|
363164
|
-
var import_nats7,
|
|
363484
|
+
var import_nats7, log91, sc2, nc = null;
|
|
363165
363485
|
var init_turn_events = __esm(() => {
|
|
363166
363486
|
init_src();
|
|
363167
363487
|
import_nats7 = __toESM(require_mod4(), 1);
|
|
363168
|
-
|
|
363488
|
+
log91 = createLogger("turn-events");
|
|
363169
363489
|
sc2 = import_nats7.StringCodec();
|
|
363170
363490
|
});
|
|
363171
363491
|
|
|
@@ -363490,6 +363810,7 @@ function createApp(db2, eventBus = null, channelRegistry2 = null) {
|
|
|
363490
363810
|
});
|
|
363491
363811
|
const protectedApp = new Hono2;
|
|
363492
363812
|
protectedApp.use("*", authMiddleware);
|
|
363813
|
+
protectedApp.use("*", scopeEnforcerMiddleware);
|
|
363493
363814
|
protectedApp.use("*", rateLimitMiddleware);
|
|
363494
363815
|
protectedApp.route("/", v2Routes);
|
|
363495
363816
|
app.route("/api/v2", protectedApp);
|
|
@@ -363541,6 +363862,7 @@ var init_app = __esm(() => {
|
|
|
363541
363862
|
init_timing2();
|
|
363542
363863
|
init_auth();
|
|
363543
363864
|
init_body_limit2();
|
|
363865
|
+
init_scope_enforcer();
|
|
363544
363866
|
init_context3();
|
|
363545
363867
|
init_error3();
|
|
363546
363868
|
init_rate_limit();
|
|
@@ -363586,7 +363908,7 @@ class DatabasePluginStorage {
|
|
|
363586
363908
|
const result = await this.db.select().from(pluginStorage).where(and2(eq(pluginStorage.pluginId, this.pluginId), eq(pluginStorage.key, fullKey), or2(isNull2(pluginStorage.expiresAt), gt(pluginStorage.expiresAt, new Date)))).limit(1);
|
|
363587
363909
|
const elapsed = Date.now() - t0;
|
|
363588
363910
|
if (elapsed > 500) {
|
|
363589
|
-
|
|
363911
|
+
log92.warn("Slow storage.get", {
|
|
363590
363912
|
pluginId: this.pluginId,
|
|
363591
363913
|
key: fullKey.slice(-80),
|
|
363592
363914
|
elapsedMs: elapsed
|
|
@@ -363720,19 +364042,19 @@ function getPluginStorage(pluginId) {
|
|
|
363720
364042
|
if (globalDb) {
|
|
363721
364043
|
storage = new DatabasePluginStorage(globalDb, pluginId);
|
|
363722
364044
|
} else {
|
|
363723
|
-
|
|
364045
|
+
log92.warn("Database not available, using in-memory storage", { pluginId });
|
|
363724
364046
|
storage = new InMemoryPluginStorage(pluginId);
|
|
363725
364047
|
}
|
|
363726
364048
|
storageInstances.set(pluginId, storage);
|
|
363727
364049
|
}
|
|
363728
364050
|
return storage;
|
|
363729
364051
|
}
|
|
363730
|
-
var
|
|
364052
|
+
var log92, globalDb = null, storageInstances;
|
|
363731
364053
|
var init_storage = __esm(() => {
|
|
363732
364054
|
init_src();
|
|
363733
364055
|
init_src4();
|
|
363734
364056
|
init_drizzle_orm();
|
|
363735
|
-
|
|
364057
|
+
log92 = createLogger("api:storage");
|
|
363736
364058
|
storageInstances = new Map;
|
|
363737
364059
|
});
|
|
363738
364060
|
|
|
@@ -363740,7 +364062,7 @@ var init_storage = __esm(() => {
|
|
|
363740
364062
|
function createPluginDatabase(db2) {
|
|
363741
364063
|
return {
|
|
363742
364064
|
async execute(_sql, _params) {
|
|
363743
|
-
|
|
364065
|
+
log93.warn("PluginDatabase execute() is not implemented. Use getDrizzle() for queries.");
|
|
363744
364066
|
return [];
|
|
363745
364067
|
},
|
|
363746
364068
|
getDrizzle() {
|
|
@@ -363769,12 +364091,12 @@ function createPluginContext(options) {
|
|
|
363769
364091
|
db: createPluginDatabase(db2)
|
|
363770
364092
|
};
|
|
363771
364093
|
}
|
|
363772
|
-
var
|
|
364094
|
+
var log93;
|
|
363773
364095
|
var init_context5 = __esm(() => {
|
|
363774
364096
|
init_src();
|
|
363775
364097
|
init_logger5();
|
|
363776
364098
|
init_storage();
|
|
363777
|
-
|
|
364099
|
+
log93 = createLogger("api:plugin-context");
|
|
363778
364100
|
});
|
|
363779
364101
|
|
|
363780
364102
|
// ../api/src/plugins/loader.ts
|
|
@@ -364136,12 +364458,12 @@ async function setupEventPersistence(eventBus, db2) {
|
|
|
364136
364458
|
const tracker = getJourneyTracker();
|
|
364137
364459
|
tracker.recordCheckpoint(metadata.correlationId, "T4", JOURNEY_STAGES.T4);
|
|
364138
364460
|
}
|
|
364139
|
-
|
|
364461
|
+
log94.debug("Persisted message.received", {
|
|
364140
364462
|
externalId: payload.externalId,
|
|
364141
364463
|
instanceId: metadata.instanceId
|
|
364142
364464
|
});
|
|
364143
364465
|
} catch (error2) {
|
|
364144
|
-
|
|
364466
|
+
log94.error("Failed to persist message.received", {
|
|
364145
364467
|
externalId: payload.externalId,
|
|
364146
364468
|
error: String(error2)
|
|
364147
364469
|
});
|
|
@@ -364177,12 +364499,12 @@ async function setupEventPersistence(eventBus, db2) {
|
|
|
364177
364499
|
chatUuid
|
|
364178
364500
|
};
|
|
364179
364501
|
await db2.insert(omniEvents).values(newEvent);
|
|
364180
|
-
|
|
364502
|
+
log94.debug("Persisted message.sent", {
|
|
364181
364503
|
externalId: payload.externalId,
|
|
364182
364504
|
instanceId: metadata.instanceId
|
|
364183
364505
|
});
|
|
364184
364506
|
} catch (error2) {
|
|
364185
|
-
|
|
364507
|
+
log94.error("Failed to persist message.sent", {
|
|
364186
364508
|
externalId: payload.externalId,
|
|
364187
364509
|
error: String(error2)
|
|
364188
364510
|
});
|
|
@@ -364214,11 +364536,11 @@ async function setupEventPersistence(eventBus, db2) {
|
|
|
364214
364536
|
};
|
|
364215
364537
|
await db2.insert(omniEvents).values(newEvent);
|
|
364216
364538
|
}
|
|
364217
|
-
|
|
364539
|
+
log94.debug("Persisted message.delivered", {
|
|
364218
364540
|
externalId: payload.externalId
|
|
364219
364541
|
});
|
|
364220
364542
|
} catch (error2) {
|
|
364221
|
-
|
|
364543
|
+
log94.error("Failed to persist message.delivered", {
|
|
364222
364544
|
externalId: payload.externalId,
|
|
364223
364545
|
error: String(error2)
|
|
364224
364546
|
});
|
|
@@ -364249,11 +364571,11 @@ async function setupEventPersistence(eventBus, db2) {
|
|
|
364249
364571
|
};
|
|
364250
364572
|
await db2.insert(omniEvents).values(newEvent);
|
|
364251
364573
|
}
|
|
364252
|
-
|
|
364574
|
+
log94.debug("Persisted message.read", {
|
|
364253
364575
|
externalId: payload.externalId
|
|
364254
364576
|
});
|
|
364255
364577
|
} catch (error2) {
|
|
364256
|
-
|
|
364578
|
+
log94.error("Failed to persist message.read", {
|
|
364257
364579
|
externalId: payload.externalId,
|
|
364258
364580
|
error: String(error2)
|
|
364259
364581
|
});
|
|
@@ -364285,29 +364607,29 @@ async function setupEventPersistence(eventBus, db2) {
|
|
|
364285
364607
|
chatUuid
|
|
364286
364608
|
};
|
|
364287
364609
|
await db2.insert(omniEvents).values(newEvent);
|
|
364288
|
-
|
|
364610
|
+
log94.debug("Persisted message.failed", {
|
|
364289
364611
|
chatId: payload.chatId,
|
|
364290
364612
|
error: payload.error
|
|
364291
364613
|
});
|
|
364292
364614
|
} catch (error2) {
|
|
364293
|
-
|
|
364615
|
+
log94.error("Failed to persist message.failed", {
|
|
364294
364616
|
chatId: payload.chatId,
|
|
364295
364617
|
error: String(error2)
|
|
364296
364618
|
});
|
|
364297
364619
|
}
|
|
364298
364620
|
}, { ...CONSUMER_OPTIONS, durable: "event-persistence-failed" });
|
|
364299
|
-
|
|
364621
|
+
log94.info("Event persistence initialized - listening for message events");
|
|
364300
364622
|
} catch (error2) {
|
|
364301
|
-
|
|
364623
|
+
log94.error("Failed to set up event persistence", { error: String(error2) });
|
|
364302
364624
|
throw error2;
|
|
364303
364625
|
}
|
|
364304
364626
|
}
|
|
364305
|
-
var
|
|
364627
|
+
var log94, CONSUMER_OPTIONS;
|
|
364306
364628
|
var init_event_persistence = __esm(() => {
|
|
364307
364629
|
init_src();
|
|
364308
364630
|
init_src4();
|
|
364309
364631
|
init_drizzle_orm();
|
|
364310
|
-
|
|
364632
|
+
log94 = createLogger("event-persistence");
|
|
364311
364633
|
CONSUMER_OPTIONS = {
|
|
364312
364634
|
queue: "event-persistence",
|
|
364313
364635
|
maxRetries: 3,
|
|
@@ -364422,7 +364744,7 @@ async function processSenderIdentity(services, payload, metadata, channel4) {
|
|
|
364422
364744
|
matchByChannel: channel4
|
|
364423
364745
|
});
|
|
364424
364746
|
if (isNew) {
|
|
364425
|
-
|
|
364747
|
+
log95.debug("Auto-created identity for sender", {
|
|
364426
364748
|
platformUserId: payload.from,
|
|
364427
364749
|
identityId: identity.id,
|
|
364428
364750
|
personId: person2?.id
|
|
@@ -364440,14 +364762,14 @@ async function fetchAndUpdateProfile(services, channel4, instanceId, userId, ide
|
|
|
364440
364762
|
const profile = await fetchProfile.call(plugin6, instanceId, userId);
|
|
364441
364763
|
if (profile.avatarUrl || profile.bio || profile.platformData) {
|
|
364442
364764
|
await services.persons.updateIdentityProfile(identityId, profile);
|
|
364443
|
-
|
|
364765
|
+
log95.debug("Updated identity with profile data", {
|
|
364444
364766
|
identityId,
|
|
364445
364767
|
hasAvatar: !!profile.avatarUrl,
|
|
364446
364768
|
hasBio: !!profile.bio
|
|
364447
364769
|
});
|
|
364448
364770
|
}
|
|
364449
364771
|
} catch (error2) {
|
|
364450
|
-
|
|
364772
|
+
log95.warn("Failed to fetch profile for new identity", { identityId, error: String(error2) });
|
|
364451
364773
|
}
|
|
364452
364774
|
}
|
|
364453
364775
|
function shouldUpdateChatName(current, incoming) {
|
|
@@ -364461,7 +364783,7 @@ async function persistLidMappings(services, chat2, chatExternalId, instanceId, r
|
|
|
364461
364783
|
const originalLidJid = rawPayload?.originalLidJid;
|
|
364462
364784
|
if (originalLidJid && chatExternalId.endsWith("@s.whatsapp.net")) {
|
|
364463
364785
|
services.chats.upsertLidMapping(instanceId, originalLidJid, chatExternalId).catch((err) => {
|
|
364464
|
-
|
|
364786
|
+
log95.debug("Failed to persist LID mapping (non-critical)", { error: String(err) });
|
|
364465
364787
|
});
|
|
364466
364788
|
if (!chat2.canonicalId) {
|
|
364467
364789
|
await services.chats.update(chat2.id, { canonicalId: chatExternalId });
|
|
@@ -364471,14 +364793,14 @@ async function persistLidMappings(services, chat2, chatExternalId, instanceId, r
|
|
|
364471
364793
|
const resolvedPhoneJid = rawPayload?.resolvedPhoneJid;
|
|
364472
364794
|
if (chatExternalId.endsWith("@lid") && resolvedPhoneJid) {
|
|
364473
364795
|
services.chats.upsertLidMapping(instanceId, chatExternalId, resolvedPhoneJid).catch((err) => {
|
|
364474
|
-
|
|
364796
|
+
log95.debug("Failed to persist LID\u2194phone mapping for LID-canonical chat (non-critical)", { error: String(err) });
|
|
364475
364797
|
});
|
|
364476
364798
|
if (!chat2.canonicalId) {
|
|
364477
364799
|
try {
|
|
364478
364800
|
await services.chats.update(chat2.id, { canonicalId: resolvedPhoneJid });
|
|
364479
364801
|
chat2.canonicalId = resolvedPhoneJid;
|
|
364480
364802
|
} catch (err) {
|
|
364481
|
-
|
|
364803
|
+
log95.debug("canonicalId backfill skipped \u2014 already claimed by another chat", {
|
|
364482
364804
|
chatId: chat2.id,
|
|
364483
364805
|
resolvedPhoneJid,
|
|
364484
364806
|
error: String(err)
|
|
@@ -364542,10 +364864,10 @@ function maybeUpdateRecency(services, instanceId, chatId, rawPayload, payload, p
|
|
|
364542
364864
|
const preview = sanitizeText(buildChatPreview(payload, rawPayload)) ?? "";
|
|
364543
364865
|
const isFromMe2 = rawPayload?.isFromMe === true;
|
|
364544
364866
|
services.chats.updateLastMessage(chatId, preview, platformTimestamp, isFromMe2).catch((error2) => {
|
|
364545
|
-
|
|
364867
|
+
log95.debug("Failed to update chat lastMessage (non-critical)", { error: String(error2) });
|
|
364546
364868
|
});
|
|
364547
364869
|
services.instances.updateLastMessageAt(instanceId, platformTimestamp).catch((error2) => {
|
|
364548
|
-
|
|
364870
|
+
log95.debug("Failed to update instance lastMessageAt (non-critical)", { error: String(error2) });
|
|
364549
364871
|
});
|
|
364550
364872
|
}
|
|
364551
364873
|
async function resolveOrCreateChat(services, instanceId, chatExternalId, chatType, channel4, effectiveName, canonicalId, rawPayload) {
|
|
@@ -364554,7 +364876,7 @@ async function resolveOrCreateChat(services, instanceId, chatExternalId, chatTyp
|
|
|
364554
364876
|
return services.chats.findByExternalIdSmart(instanceId, resolvedPhoneJid).then((phoneChat) => {
|
|
364555
364877
|
if (phoneChat) {
|
|
364556
364878
|
services.chats.upsertLidMapping(instanceId, chatExternalId, resolvedPhoneJid).catch((err) => {
|
|
364557
|
-
|
|
364879
|
+
log95.debug("Failed to persist LID mapping during chat pre-check (non-critical)", { error: String(err) });
|
|
364558
364880
|
});
|
|
364559
364881
|
return { chat: phoneChat, created: false };
|
|
364560
364882
|
}
|
|
@@ -364613,7 +364935,7 @@ async function handleMessageReceived(services, payload, metadata, eventTimestamp
|
|
|
364613
364935
|
});
|
|
364614
364936
|
await maybeRecordMessageEdit(services, created, rawPayload, message2.id, sanitizeText(payload.content.text) ?? undefined, platformTimestamp, payload.from);
|
|
364615
364937
|
if (created) {
|
|
364616
|
-
|
|
364938
|
+
log95.debug("Created message", { externalId: payload.externalId, chatId: chat2.id });
|
|
364617
364939
|
}
|
|
364618
364940
|
await maybeRecordParticipantActivity(services, chat2.id, payload.from);
|
|
364619
364941
|
maybeUpdateRecency(services, metadata.instanceId, chat2.id, rawPayload, payload, platformTimestamp);
|
|
@@ -364622,7 +364944,7 @@ function logMessageReceivedError(payload, error2) {
|
|
|
364622
364944
|
const rawPayload = payload.rawPayload;
|
|
364623
364945
|
const quotedMsg = rawPayload?.quotedMessage;
|
|
364624
364946
|
const longFields = findLongStrings(rawPayload, "raw.");
|
|
364625
|
-
|
|
364947
|
+
log95.error("Failed to persist message.received to unified model", {
|
|
364626
364948
|
externalId: payload.externalId,
|
|
364627
364949
|
error: String(error2),
|
|
364628
364950
|
fieldLengths: {
|
|
@@ -364644,7 +364966,7 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364644
364966
|
const payload = event.payload;
|
|
364645
364967
|
const metadata = event.metadata;
|
|
364646
364968
|
if (!metadata.instanceId) {
|
|
364647
|
-
|
|
364969
|
+
log95.debug("Skipping message without instanceId", { externalId: payload.externalId });
|
|
364648
364970
|
return;
|
|
364649
364971
|
}
|
|
364650
364972
|
try {
|
|
@@ -364674,7 +364996,7 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364674
364996
|
const metadata = event.metadata;
|
|
364675
364997
|
try {
|
|
364676
364998
|
if (!metadata.instanceId) {
|
|
364677
|
-
|
|
364999
|
+
log95.debug("Skipping sent message without instanceId", { externalId: payload.externalId });
|
|
364678
365000
|
return;
|
|
364679
365001
|
}
|
|
364680
365002
|
const chatExternalId = truncate3(payload.chatId, 255) ?? payload.chatId;
|
|
@@ -364697,18 +365019,18 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364697
365019
|
replyToExternalId: truncate3(payload.replyToId, 255)
|
|
364698
365020
|
});
|
|
364699
365021
|
if (created) {
|
|
364700
|
-
|
|
365022
|
+
log95.debug("Created sent message", {
|
|
364701
365023
|
messageId: message2.id,
|
|
364702
365024
|
externalId: payload.externalId,
|
|
364703
365025
|
chatId: chat2.id
|
|
364704
365026
|
});
|
|
364705
365027
|
}
|
|
364706
|
-
services.chats.updateLastMessage(chat2.id, sanitizeText(payload.content.text ?? "") ?? "", new Date(event.timestamp), true).catch((err) =>
|
|
365028
|
+
services.chats.updateLastMessage(chat2.id, sanitizeText(payload.content.text ?? "") ?? "", new Date(event.timestamp), true).catch((err) => log95.debug("Failed to update chat recency (sent)", { error: String(err) }));
|
|
364707
365029
|
if (metadata.streamSequence) {
|
|
364708
365030
|
await services.consumerOffsets.updateOffset("message-persistence-sent", "MESSAGE", metadata.streamSequence, event.id);
|
|
364709
365031
|
}
|
|
364710
365032
|
} catch (error2) {
|
|
364711
|
-
|
|
365033
|
+
log95.error("Failed to persist message.sent to unified model", {
|
|
364712
365034
|
externalId: payload.externalId,
|
|
364713
365035
|
error: String(error2)
|
|
364714
365036
|
});
|
|
@@ -364732,18 +365054,18 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364732
365054
|
return;
|
|
364733
365055
|
const chat2 = await services.chats.findByExternalIdSmart(metadata.instanceId, payload.chatId);
|
|
364734
365056
|
if (!chat2) {
|
|
364735
|
-
|
|
365057
|
+
log95.debug("Chat not found for message.delivered", { chatId: payload.chatId });
|
|
364736
365058
|
return;
|
|
364737
365059
|
}
|
|
364738
365060
|
const message2 = await services.messages.getByExternalId(chat2.id, payload.externalId);
|
|
364739
365061
|
if (!message2) {
|
|
364740
|
-
|
|
365062
|
+
log95.debug("Message not found for message.delivered", { externalId: payload.externalId });
|
|
364741
365063
|
return;
|
|
364742
365064
|
}
|
|
364743
365065
|
await services.messages.updateDeliveryStatus(message2.id, "delivered");
|
|
364744
|
-
|
|
365066
|
+
log95.debug("Updated message delivery status", { messageId: message2.id, status: "delivered" });
|
|
364745
365067
|
} catch (error2) {
|
|
364746
|
-
|
|
365068
|
+
log95.error("Failed to update delivery status", {
|
|
364747
365069
|
externalId: payload.externalId,
|
|
364748
365070
|
error: String(error2)
|
|
364749
365071
|
});
|
|
@@ -364766,18 +365088,18 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364766
365088
|
return;
|
|
364767
365089
|
const chat2 = await services.chats.findByExternalIdSmart(metadata.instanceId, payload.chatId);
|
|
364768
365090
|
if (!chat2) {
|
|
364769
|
-
|
|
365091
|
+
log95.debug("Chat not found for message.read", { chatId: payload.chatId });
|
|
364770
365092
|
return;
|
|
364771
365093
|
}
|
|
364772
365094
|
const message2 = await services.messages.getByExternalId(chat2.id, payload.externalId);
|
|
364773
365095
|
if (!message2) {
|
|
364774
|
-
|
|
365096
|
+
log95.debug("Message not found for message.read", { externalId: payload.externalId });
|
|
364775
365097
|
return;
|
|
364776
365098
|
}
|
|
364777
365099
|
await services.messages.updateDeliveryStatus(message2.id, "read");
|
|
364778
|
-
|
|
365100
|
+
log95.debug("Updated message delivery status", { messageId: message2.id, status: "read" });
|
|
364779
365101
|
} catch (error2) {
|
|
364780
|
-
|
|
365102
|
+
log95.error("Failed to update read status", {
|
|
364781
365103
|
externalId: payload.externalId,
|
|
364782
365104
|
error: String(error2)
|
|
364783
365105
|
});
|
|
@@ -364806,12 +365128,12 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364806
365128
|
if (gapMs > gapThresholdMs) {
|
|
364807
365129
|
const channelType = event.metadata.channelType ?? "whatsapp-baileys";
|
|
364808
365130
|
if (channelType === "discord") {
|
|
364809
|
-
|
|
365131
|
+
log95.info("Instance reconnected with message gap (Discord \u2014 skipping auto-backfill, use manual sync)", {
|
|
364810
365132
|
instanceId,
|
|
364811
365133
|
gapMinutes
|
|
364812
365134
|
});
|
|
364813
365135
|
} else {
|
|
364814
|
-
|
|
365136
|
+
log95.warn("Instance reconnected with message gap", {
|
|
364815
365137
|
instanceId,
|
|
364816
365138
|
lastMessageAt: lastMessageAt.toISOString(),
|
|
364817
365139
|
gapMinutes
|
|
@@ -364825,7 +365147,7 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364825
365147
|
until: new Date().toISOString()
|
|
364826
365148
|
}
|
|
364827
365149
|
});
|
|
364828
|
-
|
|
365150
|
+
log95.info("Post-reconnect backfill triggered", {
|
|
364829
365151
|
instanceId,
|
|
364830
365152
|
jobId: job.id,
|
|
364831
365153
|
since: lastMessageAt.toISOString(),
|
|
@@ -364833,10 +365155,10 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364833
365155
|
});
|
|
364834
365156
|
}
|
|
364835
365157
|
} else {
|
|
364836
|
-
|
|
365158
|
+
log95.debug("Instance reconnected, gap within threshold", { instanceId, gapMinutes });
|
|
364837
365159
|
}
|
|
364838
365160
|
} catch (error2) {
|
|
364839
|
-
|
|
365161
|
+
log95.warn("Post-reconnect gap check failed (non-critical)", {
|
|
364840
365162
|
instanceId,
|
|
364841
365163
|
error: String(error2)
|
|
364842
365164
|
});
|
|
@@ -364849,12 +365171,12 @@ async function setupMessagePersistence(eventBus, services) {
|
|
|
364849
365171
|
startFrom: "first",
|
|
364850
365172
|
concurrency: 5
|
|
364851
365173
|
});
|
|
364852
|
-
|
|
365174
|
+
log95.info("Message persistence initialized - populating unified chats/messages");
|
|
364853
365175
|
detectStartupGaps(services).catch((error2) => {
|
|
364854
|
-
|
|
365176
|
+
log95.warn("Startup gap detection failed (non-critical)", { error: String(error2) });
|
|
364855
365177
|
});
|
|
364856
365178
|
} catch (error2) {
|
|
364857
|
-
|
|
365179
|
+
log95.error("Failed to set up message persistence", { error: String(error2) });
|
|
364858
365180
|
throw error2;
|
|
364859
365181
|
}
|
|
364860
365182
|
}
|
|
@@ -364868,17 +365190,17 @@ async function detectStartupGaps(services) {
|
|
|
364868
365190
|
for (const consumerName of consumers) {
|
|
364869
365191
|
const offset = await services.consumerOffsets.getOffset(consumerName);
|
|
364870
365192
|
if (offset > 0) {
|
|
364871
|
-
|
|
365193
|
+
log95.info("Consumer startup offset", { consumer: consumerName, lastSequence: offset });
|
|
364872
365194
|
}
|
|
364873
365195
|
}
|
|
364874
365196
|
}
|
|
364875
|
-
var
|
|
365197
|
+
var log95, CONTENT_TYPE_MAP, INTERNAL_JID_SUFFIXES, MEDIA_BADGES2;
|
|
364876
365198
|
var init_message_persistence = __esm(() => {
|
|
364877
365199
|
init_src();
|
|
364878
365200
|
init_esm5();
|
|
364879
365201
|
init_sentry_scrub();
|
|
364880
365202
|
init_loader2();
|
|
364881
|
-
|
|
365203
|
+
log95 = createLogger("message-persistence");
|
|
364882
365204
|
CONTENT_TYPE_MAP = {
|
|
364883
365205
|
audio: "audio",
|
|
364884
365206
|
image: "image",
|
|
@@ -364969,10 +365291,10 @@ async function downloadMediaFromUrl(ctx, instanceId, messageId, mediaUrl, mimeTy
|
|
|
364969
365291
|
try {
|
|
364970
365292
|
const result = await ctx.mediaStorage.storeFromUrl(instanceId, messageId, mediaUrl, mimeType, platformTimestamp, fetchOptions);
|
|
364971
365293
|
await ctx.mediaStorage.updateMessageLocalPath(messageId, result.localPath);
|
|
364972
|
-
|
|
365294
|
+
log96.debug("Downloaded media from URL", { messageId, filePath: result.localPath });
|
|
364973
365295
|
return result.localPath;
|
|
364974
365296
|
} catch (error2) {
|
|
364975
|
-
|
|
365297
|
+
log96.error("Failed to download media", { error: String(error2), mediaUrl });
|
|
364976
365298
|
return null;
|
|
364977
365299
|
}
|
|
364978
365300
|
}
|
|
@@ -364986,7 +365308,7 @@ async function resolveMediaPath(ctx, instanceId, chatId, externalId, content, mi
|
|
|
364986
365308
|
chat2 = await ctx.services.chats.findByExternalIdSmart(instanceId, chatId);
|
|
364987
365309
|
}
|
|
364988
365310
|
if (!chat2) {
|
|
364989
|
-
|
|
365311
|
+
log96.debug("Chat not found, cannot process media", { chatId, externalId });
|
|
364990
365312
|
return null;
|
|
364991
365313
|
}
|
|
364992
365314
|
let message2 = await ctx.services.messages.getByExternalId(chat2.id, externalId);
|
|
@@ -364995,7 +365317,7 @@ async function resolveMediaPath(ctx, instanceId, chatId, externalId, content, mi
|
|
|
364995
365317
|
message2 = await ctx.services.messages.getByExternalId(chat2.id, externalId);
|
|
364996
365318
|
}
|
|
364997
365319
|
if (!message2) {
|
|
364998
|
-
|
|
365320
|
+
log96.debug("Message not found after waiting, cannot process media", { externalId });
|
|
364999
365321
|
return null;
|
|
365000
365322
|
}
|
|
365001
365323
|
let filePath = message2.mediaLocalPath;
|
|
@@ -365005,7 +365327,7 @@ async function resolveMediaPath(ctx, instanceId, chatId, externalId, content, mi
|
|
|
365005
365327
|
return null;
|
|
365006
365328
|
}
|
|
365007
365329
|
if (!filePath) {
|
|
365008
|
-
|
|
365330
|
+
log96.debug("No media file path available", { externalId });
|
|
365009
365331
|
return null;
|
|
365010
365332
|
}
|
|
365011
365333
|
return {
|
|
@@ -365036,7 +365358,7 @@ async function persistProcessingResult(ctx, messageId, eventId, result, contentT
|
|
|
365036
365358
|
processingTimeMs: result.processingTimeMs
|
|
365037
365359
|
});
|
|
365038
365360
|
} catch (error2) {
|
|
365039
|
-
|
|
365361
|
+
log96.warn("Failed to insert media_content record (non-critical)", {
|
|
365040
365362
|
messageId,
|
|
365041
365363
|
error: String(error2)
|
|
365042
365364
|
});
|
|
@@ -365056,13 +365378,13 @@ async function processMessageMedia(ctx, payload, metadata) {
|
|
|
365056
365378
|
const { content, externalId } = payload;
|
|
365057
365379
|
const mimeType = getMimeType2(content);
|
|
365058
365380
|
if (!mimeType || !ctx.mediaService.canProcess(mimeType)) {
|
|
365059
|
-
|
|
365381
|
+
log96.debug("MIME type not processable or missing", { mimeType, externalId });
|
|
365060
365382
|
return;
|
|
365061
365383
|
}
|
|
365062
365384
|
const media = await resolveMediaPath(ctx, instanceId, payload.chatId, externalId, content, mimeType, metadata.channelType);
|
|
365063
365385
|
if (!media)
|
|
365064
365386
|
return;
|
|
365065
|
-
|
|
365387
|
+
log96.info("Processing media", { messageId: media.messageId, mimeType, filePath: media.fullPath });
|
|
365066
365388
|
const result = await ctx.mediaService.process(media.fullPath, mimeType, {
|
|
365067
365389
|
language: "pt",
|
|
365068
365390
|
caption: content.text,
|
|
@@ -365070,7 +365392,7 @@ async function processMessageMedia(ctx, payload, metadata) {
|
|
|
365070
365392
|
});
|
|
365071
365393
|
if (!result.success) {
|
|
365072
365394
|
const reason = result.errorMessage ?? "unknown";
|
|
365073
|
-
|
|
365395
|
+
log96.warn("Media processing failed", { messageId: media.messageId, error: reason });
|
|
365074
365396
|
const processingType = result.processingType ?? inferProcessingType(content.type);
|
|
365075
365397
|
const errorColumn = getContentFieldForType(processingType, content.type);
|
|
365076
365398
|
if (errorColumn) {
|
|
@@ -365095,7 +365417,7 @@ async function processMessageMedia(ctx, payload, metadata) {
|
|
|
365095
365417
|
return;
|
|
365096
365418
|
}
|
|
365097
365419
|
await persistProcessingResult(ctx, media.messageId, eventId, result, content.type);
|
|
365098
|
-
|
|
365420
|
+
log96.info("Media processing complete", {
|
|
365099
365421
|
messageId: media.messageId,
|
|
365100
365422
|
processingType: result.processingType,
|
|
365101
365423
|
provider: result.provider,
|
|
@@ -365135,7 +365457,7 @@ async function publishMediaCrashEvents(ctx, eventId, payload, metadata, error2)
|
|
|
365135
365457
|
error: reason
|
|
365136
365458
|
}, meta);
|
|
365137
365459
|
} catch (publishError) {
|
|
365138
|
-
|
|
365460
|
+
log96.error("Failed to publish media failure event", { error: String(publishError) });
|
|
365139
365461
|
}
|
|
365140
365462
|
}
|
|
365141
365463
|
async function resolveMediaIdForCrash(ctx, instanceId, payload) {
|
|
@@ -365147,7 +365469,7 @@ async function resolveMediaIdForCrash(ctx, instanceId, payload) {
|
|
|
365147
365469
|
return msg.id;
|
|
365148
365470
|
}
|
|
365149
365471
|
} catch (lookupError) {
|
|
365150
|
-
|
|
365472
|
+
log96.debug("Failed to resolve DB message UUID for crash handler, falling back to externalId", {
|
|
365151
365473
|
error: String(lookupError),
|
|
365152
365474
|
instanceId,
|
|
365153
365475
|
chatId: payload.chatId
|
|
@@ -365198,7 +365520,7 @@ async function setupMediaProcessor(eventBus, db2, services) {
|
|
|
365198
365520
|
channelType: metadata.channelType
|
|
365199
365521
|
});
|
|
365200
365522
|
} catch (error2) {
|
|
365201
|
-
|
|
365523
|
+
log96.error("Failed to process media", {
|
|
365202
365524
|
externalId: payload.externalId,
|
|
365203
365525
|
error: String(error2)
|
|
365204
365526
|
});
|
|
@@ -365213,14 +365535,14 @@ async function setupMediaProcessor(eventBus, db2, services) {
|
|
|
365213
365535
|
concurrency: 5
|
|
365214
365536
|
});
|
|
365215
365537
|
setGlobalCircuitBreakerStateChangeCallback((name, from, to) => {
|
|
365216
|
-
|
|
365538
|
+
log96.warn("Circuit breaker state change", { provider: name, from, to });
|
|
365217
365539
|
});
|
|
365218
365540
|
await eventBus.subscribePattern("media.health.request", async (event) => {
|
|
365219
365541
|
const tracker = getMediaHealthTracker();
|
|
365220
365542
|
const report = tracker.getReport();
|
|
365221
365543
|
const correlationId = event.metadata?.correlationId ?? event.id;
|
|
365222
365544
|
await eventBus.publishGeneric("system.media.health.response", { correlationId, report }, { source: "media-processor" });
|
|
365223
|
-
|
|
365545
|
+
log96.debug("Published media health report", {
|
|
365224
365546
|
correlationId,
|
|
365225
365547
|
totalRequests: report.overall.totalRequests,
|
|
365226
365548
|
successRate: report.overall.successRate
|
|
@@ -365229,16 +365551,16 @@ async function setupMediaProcessor(eventBus, db2, services) {
|
|
|
365229
365551
|
durable: "media-health-responder",
|
|
365230
365552
|
queue: "media-health-responder"
|
|
365231
365553
|
});
|
|
365232
|
-
|
|
365554
|
+
log96.info("Media processor initialized");
|
|
365233
365555
|
}
|
|
365234
|
-
var
|
|
365556
|
+
var log96, PROCESSABLE_MEDIA_TYPES;
|
|
365235
365557
|
var init_media_processor = __esm(() => {
|
|
365236
365558
|
init_src();
|
|
365237
365559
|
init_src4();
|
|
365238
365560
|
init_src6();
|
|
365239
365561
|
init_drizzle_orm();
|
|
365240
365562
|
init_media_storage();
|
|
365241
|
-
|
|
365563
|
+
log96 = createLogger("media-processor");
|
|
365242
365564
|
PROCESSABLE_MEDIA_TYPES = new Set(["audio", "image", "document", "video"]);
|
|
365243
365565
|
});
|
|
365244
365566
|
|
|
@@ -365287,7 +365609,7 @@ class MessageDebouncer {
|
|
|
365287
365609
|
if (this.inFlight.has(chatKey))
|
|
365288
365610
|
return;
|
|
365289
365611
|
if (config4.restartOnTyping && this.buffers.has(chatKey)) {
|
|
365290
|
-
|
|
365612
|
+
log97.debug("Restarting debounce timer on user typing", { chatKey });
|
|
365291
365613
|
this.restartTimer(chatKey, config4);
|
|
365292
365614
|
}
|
|
365293
365615
|
}
|
|
@@ -365327,7 +365649,7 @@ class MessageDebouncer {
|
|
|
365327
365649
|
try {
|
|
365328
365650
|
await this.onFlush(chatKey, messages4);
|
|
365329
365651
|
} catch (error2) {
|
|
365330
|
-
|
|
365652
|
+
log97.error("Error flushing debounced messages", { chatKey, error: String(error2) });
|
|
365331
365653
|
} finally {
|
|
365332
365654
|
this.inFlight.delete(chatKey);
|
|
365333
365655
|
const pending = this.buffers.get(chatKey);
|
|
@@ -365344,10 +365666,10 @@ class MessageDebouncer {
|
|
|
365344
365666
|
this.inFlight.clear();
|
|
365345
365667
|
}
|
|
365346
365668
|
}
|
|
365347
|
-
var
|
|
365669
|
+
var log97;
|
|
365348
365670
|
var init_message_debouncer = __esm(() => {
|
|
365349
365671
|
init_src();
|
|
365350
|
-
|
|
365672
|
+
log97 = createLogger("message-debouncer");
|
|
365351
365673
|
});
|
|
365352
365674
|
|
|
365353
365675
|
// ../api/src/plugins/session-storage.ts
|
|
@@ -365438,7 +365760,7 @@ class RateLimiter {
|
|
|
365438
365760
|
let timestamps = this.counters.get(key) ?? [];
|
|
365439
365761
|
timestamps = timestamps.filter((ts) => now - ts < this.windowMs);
|
|
365440
365762
|
if (timestamps.length >= maxPerMinute) {
|
|
365441
|
-
|
|
365763
|
+
log98.debug("Rate limit exceeded", { key, count: timestamps.length, limit: maxPerMinute });
|
|
365442
365764
|
return false;
|
|
365443
365765
|
}
|
|
365444
365766
|
timestamps.push(now);
|
|
@@ -365470,7 +365792,7 @@ class ReactionDedup {
|
|
|
365470
365792
|
}
|
|
365471
365793
|
const msgCount = this.messageCounters.get(messageId) ?? 0;
|
|
365472
365794
|
if (msgCount >= this.maxPerMessage) {
|
|
365473
|
-
|
|
365795
|
+
log98.debug("Reaction per-message limit reached", { messageId, count: msgCount });
|
|
365474
365796
|
return true;
|
|
365475
365797
|
}
|
|
365476
365798
|
this.seen.set(key, Date.now());
|
|
@@ -365578,7 +365900,7 @@ async function sendTypingPresence(channel4, instanceId, chatId, state) {
|
|
|
365578
365900
|
await plugin6.sendTyping(instanceId, chatId, duration);
|
|
365579
365901
|
}
|
|
365580
365902
|
} catch (error2) {
|
|
365581
|
-
|
|
365903
|
+
log98.debug("Failed to send typing presence", { error: String(error2) });
|
|
365582
365904
|
}
|
|
365583
365905
|
}
|
|
365584
365906
|
async function sendTextMessage5(channel4, instanceId, chatId, text3, messageFormatMode = "convert", replyTo, correlationId, senderAgentId) {
|
|
@@ -365597,7 +365919,7 @@ async function sendTextMessage5(channel4, instanceId, chatId, text3, messageForm
|
|
|
365597
365919
|
}
|
|
365598
365920
|
async function sendErrorFeedback(channel4, instanceId, chatId, error2) {
|
|
365599
365921
|
const errorMsg = error2 instanceof Error ? error2.message : String(error2);
|
|
365600
|
-
|
|
365922
|
+
log98.error("agent_dispatch_error", { channel: channel4, instanceId, chatId, error: errorMsg });
|
|
365601
365923
|
const text3 = "\u26A0\uFE0F Sorry, I ran into an issue processing your message. Please try again.";
|
|
365602
365924
|
await sendTextMessage5(channel4, instanceId, chatId, text3);
|
|
365603
365925
|
}
|
|
@@ -365647,7 +365969,7 @@ function resolveMediaPath2(mediaUrl) {
|
|
|
365647
365969
|
const fullPath = resolve2(MEDIA_BASE_PATH3, relativePath);
|
|
365648
365970
|
const basePath = resolve2(MEDIA_BASE_PATH3);
|
|
365649
365971
|
if (!fullPath.startsWith(`${basePath}/`) && fullPath !== basePath) {
|
|
365650
|
-
|
|
365972
|
+
log98.warn("Path traversal attempt blocked", { mediaUrl, resolved: fullPath, basePath });
|
|
365651
365973
|
return null;
|
|
365652
365974
|
}
|
|
365653
365975
|
return fullPath;
|
|
@@ -365717,17 +366039,17 @@ async function awaitMediaProcessing(services, instanceId, chatId, externalId, co
|
|
|
365717
366039
|
return MEDIA_WAIT_NULL;
|
|
365718
366040
|
const chat2 = await waitForRecord(() => services.chats.findByExternalIdSmart(instanceId, chatId));
|
|
365719
366041
|
if (!chat2) {
|
|
365720
|
-
|
|
366042
|
+
log98.warn("Chat not found for media wait", { instanceId, chatId });
|
|
365721
366043
|
return MEDIA_WAIT_NULL;
|
|
365722
366044
|
}
|
|
365723
366045
|
const msg = await waitForRecord(() => services.messages.getByExternalId(chat2.id, externalId));
|
|
365724
366046
|
if (!msg) {
|
|
365725
|
-
|
|
366047
|
+
log98.warn("Message not found for media wait after retries", { instanceId, chatId, externalId });
|
|
365726
366048
|
return MEDIA_WAIT_NULL;
|
|
365727
366049
|
}
|
|
365728
366050
|
const existing = checkProcessedColumn(msg, column2);
|
|
365729
366051
|
if (existing === "error") {
|
|
365730
|
-
|
|
366052
|
+
log98.warn("Media processing failed (DB)", { instanceId, chatId, externalId });
|
|
365731
366053
|
return MEDIA_WAIT_NULL;
|
|
365732
366054
|
}
|
|
365733
366055
|
if (existing !== "pending")
|
|
@@ -365788,7 +366110,7 @@ async function resolveQuotedMessage(services, instanceId, chatId, replyToId) {
|
|
|
365788
366110
|
const timeStr = time3 ? ` at ${time3}` : "";
|
|
365789
366111
|
return `[Quoting ${sender}${timeStr}: ${truncated}]`;
|
|
365790
366112
|
} catch (error2) {
|
|
365791
|
-
|
|
366113
|
+
log98.debug("Failed to resolve quoted message", { replyToId, error: String(error2) });
|
|
365792
366114
|
return null;
|
|
365793
366115
|
}
|
|
365794
366116
|
}
|
|
@@ -365829,7 +366151,7 @@ async function collectProcessedMedia(services, instance4, messages4) {
|
|
|
365829
366151
|
try {
|
|
365830
366152
|
result = await awaitMediaProcessing(services, instance4.id, m2.payload.chatId, m2.payload.externalId, contentType);
|
|
365831
366153
|
} catch (error2) {
|
|
365832
|
-
|
|
366154
|
+
log98.warn("Media await failed", { externalId: m2.payload.externalId, error: String(error2) });
|
|
365833
366155
|
result = MEDIA_WAIT_NULL;
|
|
365834
366156
|
}
|
|
365835
366157
|
if (result.content) {
|
|
@@ -365867,11 +366189,11 @@ async function resolveContactName2(services, instanceId, jid, cacheMap) {
|
|
|
365867
366189
|
try {
|
|
365868
366190
|
const chat2 = await services.chats.findByExternalIdSmart(instanceId, jid);
|
|
365869
366191
|
if (chat2?.name) {
|
|
365870
|
-
|
|
366192
|
+
log98.debug("Contact name from DB fallback", { jid, name: chat2.name });
|
|
365871
366193
|
return chat2.name;
|
|
365872
366194
|
}
|
|
365873
366195
|
} catch (error2) {
|
|
365874
|
-
|
|
366196
|
+
log98.warn("Failed to query DB for contact", { jid, error: String(error2) });
|
|
365875
366197
|
}
|
|
365876
366198
|
return null;
|
|
365877
366199
|
}
|
|
@@ -365903,14 +366225,14 @@ async function applyJidMentionReplacement(services, instanceId, jid, jidToName,
|
|
|
365903
366225
|
async function replaceMentionsWithContactNames(services, instanceId, text3, mentionedJids, mentionedContacts) {
|
|
365904
366226
|
if (!mentionedJids?.length)
|
|
365905
366227
|
return text3;
|
|
365906
|
-
|
|
366228
|
+
log98.debug("Starting mention replacement", { mentionCount: mentionedJids.length });
|
|
365907
366229
|
const jidToName = buildJidNameMap(mentionedContacts);
|
|
365908
366230
|
const stats = { resolved: 0, replaced: 0, unresolved: 0, skipped: 0 };
|
|
365909
366231
|
let replacedText = text3;
|
|
365910
366232
|
for (const jid of mentionedJids) {
|
|
365911
366233
|
replacedText = await applyJidMentionReplacement(services, instanceId, jid, jidToName, replacedText, stats);
|
|
365912
366234
|
}
|
|
365913
|
-
|
|
366235
|
+
log98.debug("Mention replacement complete", {
|
|
365914
366236
|
original: text3,
|
|
365915
366237
|
replaced: replacedText,
|
|
365916
366238
|
mentionCount: mentionedJids.length,
|
|
@@ -365979,7 +366301,7 @@ async function fetchSenderMetadata(services, channel4, instanceId, senderId) {
|
|
|
365979
366301
|
platformUsername: identity?.platformUsername ?? undefined
|
|
365980
366302
|
};
|
|
365981
366303
|
} catch (error2) {
|
|
365982
|
-
|
|
366304
|
+
log98.debug("Failed to fetch sender identity metadata", { error: String(error2) });
|
|
365983
366305
|
return {};
|
|
365984
366306
|
}
|
|
365985
366307
|
}
|
|
@@ -365993,7 +366315,7 @@ async function fetchChatMetadata(services, instanceId, chatId, chatType) {
|
|
|
365993
366315
|
participantCount: chat2?.participantCount ?? undefined
|
|
365994
366316
|
};
|
|
365995
366317
|
} catch (error2) {
|
|
365996
|
-
|
|
366318
|
+
log98.debug("Failed to fetch chat metadata", { error: String(error2) });
|
|
365997
366319
|
return {};
|
|
365998
366320
|
}
|
|
365999
366321
|
}
|
|
@@ -366015,7 +366337,7 @@ async function routeStreamDelta(sender, delta) {
|
|
|
366015
366337
|
}
|
|
366016
366338
|
async function resolveStreamingCapabilities(services, instance4, channel4, chatId, traceId, db2) {
|
|
366017
366339
|
if (!instance4.agentStreamMode) {
|
|
366018
|
-
|
|
366340
|
+
log98.debug("Stream guard: agentStreamMode is falsy", {
|
|
366019
366341
|
instanceId: instance4.id,
|
|
366020
366342
|
agentStreamMode: instance4.agentStreamMode,
|
|
366021
366343
|
chatId
|
|
@@ -366024,7 +366346,7 @@ async function resolveStreamingCapabilities(services, instance4, channel4, chatI
|
|
|
366024
366346
|
}
|
|
366025
366347
|
const provider = await getAgentProvider(services, instance4, db2);
|
|
366026
366348
|
if (!provider?.triggerStream) {
|
|
366027
|
-
|
|
366349
|
+
log98.debug("Stream guard: provider has no triggerStream", {
|
|
366028
366350
|
instanceId: instance4.id,
|
|
366029
366351
|
hasProvider: !!provider,
|
|
366030
366352
|
chatId
|
|
@@ -366033,7 +366355,7 @@ async function resolveStreamingCapabilities(services, instance4, channel4, chatI
|
|
|
366033
366355
|
}
|
|
366034
366356
|
const plugin6 = await getPlugin(channel4);
|
|
366035
366357
|
if (!plugin6?.capabilities?.canStreamResponse || !plugin6.createStreamSender) {
|
|
366036
|
-
|
|
366358
|
+
log98.debug("Stream guard: channel does not support streaming", {
|
|
366037
366359
|
channel: channel4,
|
|
366038
366360
|
canStream: plugin6?.capabilities?.canStreamResponse,
|
|
366039
366361
|
chatId
|
|
@@ -366042,7 +366364,7 @@ async function resolveStreamingCapabilities(services, instance4, channel4, chatI
|
|
|
366042
366364
|
}
|
|
366043
366365
|
const streamKey = `${instance4.id}:${chatId}`;
|
|
366044
366366
|
if (activeStreams.has(streamKey)) {
|
|
366045
|
-
|
|
366367
|
+
log98.info("Stream guard: parallel stream blocked, falling back to accumulate", {
|
|
366046
366368
|
instanceId: instance4.id,
|
|
366047
366369
|
chatId,
|
|
366048
366370
|
traceId
|
|
@@ -366065,7 +366387,7 @@ async function consumeStream(generator, sender, instanceId, chatId, traceId) {
|
|
|
366065
366387
|
hadContent = true;
|
|
366066
366388
|
await routeStreamDelta(sender, delta);
|
|
366067
366389
|
}
|
|
366068
|
-
|
|
366390
|
+
log98.info("Streaming response complete", {
|
|
366069
366391
|
instanceId,
|
|
366070
366392
|
chatId,
|
|
366071
366393
|
durationMs: Date.now() - startTime3,
|
|
@@ -366193,7 +366515,7 @@ async function dispatchViaStreamingProvider(services, instance4, messages4, trig
|
|
|
366193
366515
|
}
|
|
366194
366516
|
return streamResult;
|
|
366195
366517
|
} catch (err) {
|
|
366196
|
-
|
|
366518
|
+
log98.error("Streaming dispatch failed, falling back", {
|
|
366197
366519
|
instanceId: instance4.id,
|
|
366198
366520
|
chatId,
|
|
366199
366521
|
error: String(err),
|
|
@@ -366277,7 +366599,7 @@ async function buildContextMessages(services, instance4, chatId, currentMessageI
|
|
|
366277
366599
|
return `[${name}${time3 ? ` - ${time3}` : ""}] ${text3}`;
|
|
366278
366600
|
});
|
|
366279
366601
|
} catch (error2) {
|
|
366280
|
-
|
|
366602
|
+
log98.warn("Failed to build context messages", { error: error2, chatId, instanceId: instance4.id });
|
|
366281
366603
|
return [];
|
|
366282
366604
|
}
|
|
366283
366605
|
}
|
|
@@ -366314,13 +366636,13 @@ async function dispatchViaTurnBasedProvider(services, instance4, provider, trigg
|
|
|
366314
366636
|
agentRecord = row;
|
|
366315
366637
|
}
|
|
366316
366638
|
if (!agentRecord) {
|
|
366317
|
-
|
|
366639
|
+
log98.error("Turn-based dispatch: agent not found", { instanceId: instance4.id, agentId: instance4.agentId });
|
|
366318
366640
|
return false;
|
|
366319
366641
|
}
|
|
366320
366642
|
const keyName = `agent:${agentRecord.name}`;
|
|
366321
366643
|
const scopedKey = await services.apiKeys.findByName(keyName);
|
|
366322
366644
|
if (!scopedKey) {
|
|
366323
|
-
|
|
366645
|
+
log98.error("Turn-based dispatch: scoped API key not found", { keyName, instanceId: instance4.id });
|
|
366324
366646
|
return false;
|
|
366325
366647
|
}
|
|
366326
366648
|
const turn = await services.turns.open({
|
|
@@ -366357,7 +366679,7 @@ async function dispatchViaTurnBasedProvider(services, instance4, provider, trigg
|
|
|
366357
366679
|
attributes: { provider_type: provider.schema, mode: "turn-based" }
|
|
366358
366680
|
});
|
|
366359
366681
|
}
|
|
366360
|
-
|
|
366682
|
+
log98.info("Turn-based dispatch: turn opened", {
|
|
366361
366683
|
turnId: turn.id,
|
|
366362
366684
|
instanceId: instance4.id,
|
|
366363
366685
|
chatId,
|
|
@@ -366373,7 +366695,7 @@ async function dispatchViaProvider(services, instance4, messages4, triggerType,
|
|
|
366373
366695
|
return false;
|
|
366374
366696
|
const { messageTexts, mediaFiles } = await prepareAgentContent(services, instance4, messages4);
|
|
366375
366697
|
if (!messageTexts.length && !mediaFiles.length) {
|
|
366376
|
-
|
|
366698
|
+
log98.debug("No text or media content for provider trigger, skipping");
|
|
366377
366699
|
return false;
|
|
366378
366700
|
}
|
|
366379
366701
|
if (!messageTexts.length && mediaFiles.length) {
|
|
@@ -366412,7 +366734,7 @@ async function dispatchViaProvider(services, instance4, messages4, triggerType,
|
|
|
366412
366734
|
recordJourneyCheckpoint(correlationId, "T9", JOURNEY_STAGES.T9);
|
|
366413
366735
|
await forwardToChainedInstance(instance4, parts, correlationId, messages4);
|
|
366414
366736
|
}
|
|
366415
|
-
|
|
366737
|
+
log98.info("Agent response via IAgentProvider", {
|
|
366416
366738
|
instanceId: instance4.id,
|
|
366417
366739
|
chatId,
|
|
366418
366740
|
parts: result?.parts.length ?? 0,
|
|
@@ -366426,14 +366748,14 @@ async function dispatchViaProvider(services, instance4, messages4, triggerType,
|
|
|
366426
366748
|
async function dispatchViaLegacy(services, instance4, messages4, triggerType, channel4, chatId, senderId, personId, senderName, traceId, perThreadExtraContext, senderAgentId) {
|
|
366427
366749
|
const { messageTexts, mediaFiles } = await prepareAgentContent(services, instance4, messages4);
|
|
366428
366750
|
if (perThreadExtraContext?.length) {
|
|
366429
|
-
|
|
366751
|
+
log98.warn("per_thread context available but legacy dispatch path has limited support \u2014 prepending as text", {
|
|
366430
366752
|
instanceId: instance4.id,
|
|
366431
366753
|
contextCount: perThreadExtraContext.length
|
|
366432
366754
|
});
|
|
366433
366755
|
messageTexts.unshift(...perThreadExtraContext);
|
|
366434
366756
|
}
|
|
366435
366757
|
if (!messageTexts.length && !mediaFiles.length) {
|
|
366436
|
-
|
|
366758
|
+
log98.debug("No text or media content in messages, skipping agent call");
|
|
366437
366759
|
return;
|
|
366438
366760
|
}
|
|
366439
366761
|
if (!messageTexts.length && mediaFiles.length) {
|
|
@@ -366467,7 +366789,7 @@ async function dispatchViaLegacy(services, instance4, messages4, triggerType, ch
|
|
|
366467
366789
|
recordJourneyCheckpoint(correlationId, "T8", JOURNEY_STAGES.T8);
|
|
366468
366790
|
await sendResponseParts(channel4, instance4.id, chatId, parts, getSplitDelayConfig(instance4), _fmtMode, replyTo, correlationId, senderAgentId);
|
|
366469
366791
|
recordJourneyCheckpoint(correlationId, "T9", JOURNEY_STAGES.T9);
|
|
366470
|
-
|
|
366792
|
+
log98.info("Agent response via legacy runner", {
|
|
366471
366793
|
instanceId: instance4.id,
|
|
366472
366794
|
chatId,
|
|
366473
366795
|
parts: result.parts.length,
|
|
@@ -366487,14 +366809,14 @@ async function performSessionReset(instance4, sessionId, chatId, services, db2,
|
|
|
366487
366809
|
sessionActuallyReset = true;
|
|
366488
366810
|
}
|
|
366489
366811
|
} catch (err) {
|
|
366490
|
-
|
|
366812
|
+
log98.warn("Failed to reset provider session", { error: String(err), instanceId: instance4.id, sessionId });
|
|
366491
366813
|
}
|
|
366492
366814
|
if (sessionActuallyReset) {
|
|
366493
366815
|
sessionActivityStore.recordReset(instance4.id, sessionId, Date.now());
|
|
366494
366816
|
eventBus.publish("session.reset", { instanceId: instance4.id, sessionId, timestamp: Date.now() }, { instanceId: instance4.id, channelType: channel4 }).catch((err) => {
|
|
366495
|
-
|
|
366817
|
+
log98.warn("Failed to publish session.reset event", { error: String(err), instanceId: instance4.id, sessionId });
|
|
366496
366818
|
});
|
|
366497
|
-
|
|
366819
|
+
log98.info("Session reset triggered", {
|
|
366498
366820
|
instanceId: instance4.id,
|
|
366499
366821
|
sessionId,
|
|
366500
366822
|
strategy: resetStrategy,
|
|
@@ -366537,7 +366859,7 @@ async function markPerThreadSessionInitialized(db2, instanceId, sessionId) {
|
|
|
366537
366859
|
target: [agentSessions.instanceId, agentSessions.sessionKey],
|
|
366538
366860
|
set: { lastUsedAt: now, updatedAt: now }
|
|
366539
366861
|
});
|
|
366540
|
-
|
|
366862
|
+
log98.info("per_thread session initialized", { instanceId, sessionId });
|
|
366541
366863
|
}
|
|
366542
366864
|
function mimeToContentType(mimeType) {
|
|
366543
366865
|
if (mimeType.startsWith("audio/"))
|
|
@@ -366576,7 +366898,7 @@ async function processMediaFile(msg, mimeType, mediaService) {
|
|
|
366576
366898
|
const result = await mediaService.process(localPath, mimeType, { caption: msg.content.caption });
|
|
366577
366899
|
return result.success && result.content ? result.content : null;
|
|
366578
366900
|
} catch (err) {
|
|
366579
|
-
|
|
366901
|
+
log98.debug("Media processing failed for history message", { error: String(err), messageId: msg.externalId });
|
|
366580
366902
|
return null;
|
|
366581
366903
|
} finally {
|
|
366582
366904
|
if (ownedTempFile) {
|
|
@@ -366613,7 +366935,7 @@ async function processHistoryMessage2(msg, mediaService, reactFn, unreactFn) {
|
|
|
366613
366935
|
async function fetchAndProcessThreadHistory(services, instance4, channel4, chatId, threadId2) {
|
|
366614
366936
|
const plugin6 = await getPlugin(channel4);
|
|
366615
366937
|
if (!plugin6?.fetchHistory) {
|
|
366616
|
-
|
|
366938
|
+
log98.debug("Channel plugin does not support fetchHistory", { instanceId: instance4.id, channel: channel4 });
|
|
366617
366939
|
return [];
|
|
366618
366940
|
}
|
|
366619
366941
|
let historyResult;
|
|
@@ -366624,7 +366946,7 @@ async function fetchAndProcessThreadHistory(services, instance4, channel4, chatI
|
|
|
366624
366946
|
limit: 200
|
|
366625
366947
|
});
|
|
366626
366948
|
} catch (err) {
|
|
366627
|
-
|
|
366949
|
+
log98.warn("fetchHistory failed, proceeding without thread context", {
|
|
366628
366950
|
error: String(err),
|
|
366629
366951
|
instanceId: instance4.id,
|
|
366630
366952
|
channel: channel4
|
|
@@ -366654,7 +366976,7 @@ async function fetchAndProcessThreadHistory(services, instance4, channel4, chatI
|
|
|
366654
366976
|
const results = await Promise.all(batch.map((msg) => processHistoryMessage2(msg, mediaService, reactFn, unreactFn)));
|
|
366655
366977
|
contextMessages.push(...results);
|
|
366656
366978
|
}
|
|
366657
|
-
|
|
366979
|
+
log98.info("Thread history fetched", {
|
|
366658
366980
|
instanceId: instance4.id,
|
|
366659
366981
|
channel: channel4,
|
|
366660
366982
|
chatId,
|
|
@@ -366665,7 +366987,7 @@ async function fetchAndProcessThreadHistory(services, instance4, channel4, chatI
|
|
|
366665
366987
|
return contextMessages;
|
|
366666
366988
|
}
|
|
366667
366989
|
async function handlePerThreadLazyInit(services, instance4, channel4, chatId, threadId2, sessionId, db2) {
|
|
366668
|
-
|
|
366990
|
+
log98.info("per_thread lazy init", {
|
|
366669
366991
|
instanceId: instance4.id,
|
|
366670
366992
|
channel: channel4,
|
|
366671
366993
|
chatId,
|
|
@@ -366676,7 +366998,7 @@ async function handlePerThreadLazyInit(services, instance4, channel4, chatId, th
|
|
|
366676
366998
|
try {
|
|
366677
366999
|
await markPerThreadSessionInitialized(db2, instance4.id, sessionId);
|
|
366678
367000
|
} catch (err) {
|
|
366679
|
-
|
|
367001
|
+
log98.warn("Failed to mark per_thread session initialized", {
|
|
366680
367002
|
error: String(err),
|
|
366681
367003
|
instanceId: instance4.id,
|
|
366682
367004
|
sessionId
|
|
@@ -366718,7 +367040,7 @@ async function dispatchToAgent(services, instance4, msgs, triggerType, channel4,
|
|
|
366718
367040
|
handled = await dispatchViaProvider(services, instance4, msgs, triggerType, channel4, chatId, senderId, personId, senderName, traceId, rawEvent, db2, perThreadExtraContext, senderAgentId);
|
|
366719
367041
|
}
|
|
366720
367042
|
} catch (providerError) {
|
|
366721
|
-
|
|
367043
|
+
log98.error("Provider dispatch failed, falling back to legacy", {
|
|
366722
367044
|
instanceId: instance4.id,
|
|
366723
367045
|
chatId,
|
|
366724
367046
|
error: String(providerError),
|
|
@@ -366727,7 +367049,7 @@ async function dispatchToAgent(services, instance4, msgs, triggerType, channel4,
|
|
|
366727
367049
|
}
|
|
366728
367050
|
if (handled)
|
|
366729
367051
|
return;
|
|
366730
|
-
|
|
367052
|
+
log98.debug("No IAgentProvider resolved or provider failed, using legacy agentRunner path", {
|
|
366731
367053
|
instanceId: instance4.id
|
|
366732
367054
|
});
|
|
366733
367055
|
await dispatchViaLegacy(services, instance4, msgs, triggerType, channel4, chatId, senderId, personId, senderName, traceId, perThreadExtraContext, senderAgentId);
|
|
@@ -366746,7 +367068,7 @@ async function processAgentResponse(services, instance4, messages4, triggerType,
|
|
|
366746
367068
|
const ackHandle = startAck(plugin6, ackProvider, instance4.id, chatId, messageId, channel4, buildAckConfig(instance4));
|
|
366747
367069
|
const personId = await resolvePersonId(services, channel4, instance4.id, senderId, firstMessage.metadata.personId);
|
|
366748
367070
|
if (!personId) {
|
|
366749
|
-
|
|
367071
|
+
log98.warn("Could not resolve person ID, skipping agent", { instanceId: instance4.id, chatId, senderId });
|
|
366750
367072
|
ackHandle.remove();
|
|
366751
367073
|
return;
|
|
366752
367074
|
}
|
|
@@ -366755,7 +367077,7 @@ async function processAgentResponse(services, instance4, messages4, triggerType,
|
|
|
366755
367077
|
const pushName = rawPayload.pushName ?? rawPayload.displayName;
|
|
366756
367078
|
const senderName = await services.agentRunner.getSenderName(personId, pushName);
|
|
366757
367079
|
const senderAgentId = await resolveDispatchSenderAgentId(db2, instance4);
|
|
366758
|
-
|
|
367080
|
+
log98.info("Dispatching to agent", {
|
|
366759
367081
|
instanceId: instance4.id,
|
|
366760
367082
|
chatId,
|
|
366761
367083
|
messageCount: messages4.length,
|
|
@@ -366769,14 +367091,14 @@ async function processAgentResponse(services, instance4, messages4, triggerType,
|
|
|
366769
367091
|
const agentAckMessage = inst.agentAckMessage ?? null;
|
|
366770
367092
|
if (agentAckMessage) {
|
|
366771
367093
|
sendTextMessage5(channel4, instance4.id, chatId, agentAckMessage).catch((err) => {
|
|
366772
|
-
|
|
367094
|
+
log98.warn("Failed to send agent ack message", { instanceId: instance4.id, chatId, error: String(err) });
|
|
366773
367095
|
});
|
|
366774
367096
|
}
|
|
366775
367097
|
const perThreadExtraContext = await resolvePerThreadExtraContext(db2, services, instance4, channel4, chatId, senderId, firstMessage);
|
|
366776
367098
|
try {
|
|
366777
367099
|
await dispatchToAgent(services, instance4, messages4, triggerType, channel4, chatId, senderId, personId, senderName, traceId, senderAgentId, perThreadExtraContext, db2);
|
|
366778
367100
|
} catch (error2) {
|
|
366779
|
-
|
|
367101
|
+
log98.error("Failed to process agent response", {
|
|
366780
367102
|
instanceId: instance4.id,
|
|
366781
367103
|
chatId,
|
|
366782
367104
|
error: String(error2),
|
|
@@ -366820,7 +367142,7 @@ function createOpenClawProviderInstance(provider, instance4) {
|
|
|
366820
367142
|
}
|
|
366821
367143
|
function createAgnoProvider(provider, instance4) {
|
|
366822
367144
|
if (!provider.apiKey) {
|
|
366823
|
-
|
|
367145
|
+
log98.warn("Provider has no API key, falling back to legacy path", { providerId: provider.id });
|
|
366824
367146
|
return null;
|
|
366825
367147
|
}
|
|
366826
367148
|
const client = createProviderClient({
|
|
@@ -366842,7 +367164,7 @@ function createClaudeCodeProviderInstance(provider, instance4, db2) {
|
|
|
366842
367164
|
const schemaConfig = provider.schemaConfig ?? {};
|
|
366843
367165
|
const projectPath = schemaConfig.projectPath;
|
|
366844
367166
|
if (!projectPath) {
|
|
366845
|
-
|
|
367167
|
+
log98.error("Claude Code provider missing projectPath", { providerId: provider.id });
|
|
366846
367168
|
throw new Error("Claude Code provider requires schemaConfig.projectPath");
|
|
366847
367169
|
}
|
|
366848
367170
|
return new ClaudeCodeAgentProvider(provider.id, provider.name, {
|
|
@@ -366873,7 +367195,7 @@ function createWebhookProvider(provider) {
|
|
|
366873
367195
|
}
|
|
366874
367196
|
function createAgUiProviderInstance(provider, instance4) {
|
|
366875
367197
|
if (!provider.apiKey) {
|
|
366876
|
-
|
|
367198
|
+
log98.warn("AG-UI provider has no API key, falling back to legacy path", { providerId: provider.id });
|
|
366877
367199
|
return null;
|
|
366878
367200
|
}
|
|
366879
367201
|
const schemaConfig = provider.schemaConfig ?? {};
|
|
@@ -366892,7 +367214,7 @@ function createAgUiProviderInstance(provider, instance4) {
|
|
|
366892
367214
|
}
|
|
366893
367215
|
function createA2AProviderInstance(provider, instance4) {
|
|
366894
367216
|
if (!provider.apiKey) {
|
|
366895
|
-
|
|
367217
|
+
log98.warn("A2A provider has no API key, falling back to legacy path", { providerId: provider.id });
|
|
366896
367218
|
return null;
|
|
366897
367219
|
}
|
|
366898
367220
|
const schemaConfig = provider.schemaConfig ?? {};
|
|
@@ -366913,13 +367235,14 @@ function createNatsGenieProviderInstance(provider, instance4) {
|
|
|
366913
367235
|
const schemaConfig = typeof provider.schemaConfig === "object" && provider.schemaConfig !== null ? provider.schemaConfig : {};
|
|
366914
367236
|
const agentName = typeof schemaConfig.agentName === "string" ? schemaConfig.agentName : "";
|
|
366915
367237
|
if (!agentName) {
|
|
366916
|
-
|
|
367238
|
+
log98.error("NATS Genie provider missing agentName in schemaConfig", { providerId: provider.id });
|
|
366917
367239
|
return null;
|
|
366918
367240
|
}
|
|
366919
367241
|
const natsUrl = typeof schemaConfig.natsUrl === "string" ? schemaConfig.natsUrl : "localhost:4222";
|
|
366920
367242
|
const providerMode = schemaConfig.mode === "turn-based" ? "turn-based" : "fire-and-forget";
|
|
366921
367243
|
const channel4 = instance4.channel;
|
|
366922
|
-
const
|
|
367244
|
+
const Ctor = _natsGenieProviderCtor;
|
|
367245
|
+
const natsProvider = new Ctor(provider.id, provider.name, {
|
|
366923
367246
|
agentName,
|
|
366924
367247
|
natsUrl,
|
|
366925
367248
|
instanceId: instance4.id,
|
|
@@ -366929,7 +367252,7 @@ function createNatsGenieProviderInstance(provider, instance4) {
|
|
|
366929
367252
|
try {
|
|
366930
367253
|
await sendTextMessage5(channel4, instance4.id, chatId, content);
|
|
366931
367254
|
} catch (error2) {
|
|
366932
|
-
|
|
367255
|
+
log98.error("Failed to deliver agent reply", {
|
|
366933
367256
|
chatId,
|
|
366934
367257
|
instanceId: instance4.id,
|
|
366935
367258
|
providerId: provider.id,
|
|
@@ -366942,11 +367265,11 @@ function createNatsGenieProviderInstance(provider, instance4) {
|
|
|
366942
367265
|
const startWithRetry = async (attempt = 1) => {
|
|
366943
367266
|
try {
|
|
366944
367267
|
await natsProvider.startReplySubscription();
|
|
366945
|
-
|
|
367268
|
+
log98.info("NATS reply subscription started", { instanceId: instance4.id, attempt });
|
|
366946
367269
|
} catch (err) {
|
|
366947
367270
|
const delay2 = Math.min(2000 * 2 ** (attempt - 1), 60000);
|
|
366948
367271
|
if (attempt < 10) {
|
|
366949
|
-
|
|
367272
|
+
log98.warn("NATS reply subscription failed, retrying", {
|
|
366950
367273
|
instanceId: instance4.id,
|
|
366951
367274
|
providerId: provider.id,
|
|
366952
367275
|
attempt,
|
|
@@ -366955,7 +367278,7 @@ function createNatsGenieProviderInstance(provider, instance4) {
|
|
|
366955
367278
|
});
|
|
366956
367279
|
setTimeout(() => startWithRetry(attempt + 1), delay2);
|
|
366957
367280
|
} else {
|
|
366958
|
-
|
|
367281
|
+
log98.error("NATS reply subscription permanently failed", {
|
|
366959
367282
|
instanceId: instance4.id,
|
|
366960
367283
|
providerId: provider.id,
|
|
366961
367284
|
error: err instanceof Error ? err.message : String(err)
|
|
@@ -366995,7 +367318,7 @@ function resolveProvider(provider, instance4, db2) {
|
|
|
366995
367318
|
agentProvider = createNatsGenieProviderInstance(provider, instance4);
|
|
366996
367319
|
break;
|
|
366997
367320
|
default:
|
|
366998
|
-
|
|
367321
|
+
log98.debug("Provider schema not supported for IAgentProvider dispatch", {
|
|
366999
367322
|
schema: provider.schema,
|
|
367000
367323
|
providerId: provider.id
|
|
367001
367324
|
});
|
|
@@ -367015,7 +367338,7 @@ async function getAgentProvider(services, instance4, db2) {
|
|
|
367015
367338
|
return null;
|
|
367016
367339
|
return resolveProvider(provider, instance4, db2);
|
|
367017
367340
|
} catch (error2) {
|
|
367018
|
-
|
|
367341
|
+
log98.warn("Failed to resolve agent provider, falling back to legacy", {
|
|
367019
367342
|
instanceId: instance4.id,
|
|
367020
367343
|
providerId: instance4.agentProviderId,
|
|
367021
367344
|
error: String(error2)
|
|
@@ -367078,7 +367401,7 @@ async function applyInstanceFkAndReturn(db2, instance4) {
|
|
|
367078
367401
|
}
|
|
367079
367402
|
async function resolveEffectiveInstance(services, db2, instance4, chatId, personId) {
|
|
367080
367403
|
if (!chatId) {
|
|
367081
|
-
|
|
367404
|
+
log98.debug("No internal chatId \u2014 using instance default agent", { instanceId: instance4.id, personId });
|
|
367082
367405
|
return applyInstanceFkAndReturn(db2, instance4);
|
|
367083
367406
|
}
|
|
367084
367407
|
const route = await services.routeResolver.resolve(instance4.id, chatId, personId);
|
|
@@ -367090,7 +367413,7 @@ async function resolveEffectiveInstance(services, db2, instance4, chatId, person
|
|
|
367090
367413
|
if (effectiveAgentFkId) {
|
|
367091
367414
|
await applyAgentFkOverrides(db2, effectiveAgentFkId, effectiveInstance);
|
|
367092
367415
|
}
|
|
367093
|
-
|
|
367416
|
+
log98.debug("Route resolved and merged", {
|
|
367094
367417
|
instanceId: instance4.id,
|
|
367095
367418
|
chatId,
|
|
367096
367419
|
personId,
|
|
@@ -367110,7 +367433,7 @@ async function processReactionTrigger(services, baseInstance, payload, metadata,
|
|
|
367110
367433
|
const chat2 = await services.chats.findByExternalIdSmart(baseInstance.id, externalChatId);
|
|
367111
367434
|
const internalChatId = chat2?.id;
|
|
367112
367435
|
const { instance: instance4, routeId: _routeId } = await resolveEffectiveInstance(services, db2, baseInstance, internalChatId, metadata.personId);
|
|
367113
|
-
|
|
367436
|
+
log98.info("Dispatching reaction trigger", {
|
|
367114
367437
|
instanceId: instance4.id,
|
|
367115
367438
|
chatId: externalChatId,
|
|
367116
367439
|
routeChatId: internalChatId ?? "none",
|
|
@@ -367150,7 +367473,7 @@ async function processReactionTrigger(services, baseInstance, payload, metadata,
|
|
|
367150
367473
|
const _fmtMode = instance4.messageFormatMode ?? "convert";
|
|
367151
367474
|
await sendResponseParts(channel4, instance4.id, externalChatId, result2.parts, getSplitDelayConfig(instance4), _fmtMode, payload.messageId);
|
|
367152
367475
|
}
|
|
367153
|
-
|
|
367476
|
+
log98.info("Reaction trigger response via provider", {
|
|
367154
367477
|
instanceId: instance4.id,
|
|
367155
367478
|
chatId: externalChatId,
|
|
367156
367479
|
routeChatId: internalChatId,
|
|
@@ -367162,7 +367485,7 @@ async function processReactionTrigger(services, baseInstance, payload, metadata,
|
|
|
367162
367485
|
});
|
|
367163
367486
|
return;
|
|
367164
367487
|
}
|
|
367165
|
-
|
|
367488
|
+
log98.debug("No IAgentProvider resolved, using legacy agentRunner path", {
|
|
367166
367489
|
instanceId: instance4.id
|
|
367167
367490
|
});
|
|
367168
367491
|
const personId = await resolvePersonId(services, channel4, instance4.id, payload.from, metadata.personId);
|
|
@@ -367188,7 +367511,7 @@ async function processReactionTrigger(services, baseInstance, payload, metadata,
|
|
|
367188
367511
|
const _fmtMode = instance4.messageFormatMode ?? "convert";
|
|
367189
367512
|
await sendResponseParts(channel4, instance4.id, externalChatId, result.parts, getSplitDelayConfig(instance4), _fmtMode, payload.messageId);
|
|
367190
367513
|
}
|
|
367191
|
-
|
|
367514
|
+
log98.info("Reaction trigger response via legacy runner", {
|
|
367192
367515
|
instanceId: instance4.id,
|
|
367193
367516
|
chatId: externalChatId,
|
|
367194
367517
|
routeChatId: internalChatId,
|
|
@@ -367197,7 +367520,7 @@ async function processReactionTrigger(services, baseInstance, payload, metadata,
|
|
|
367197
367520
|
traceId: metadata.traceId
|
|
367198
367521
|
});
|
|
367199
367522
|
} catch (error2) {
|
|
367200
|
-
|
|
367523
|
+
log98.error("Failed to process reaction trigger", {
|
|
367201
367524
|
instanceId: instance4.id,
|
|
367202
367525
|
chatId: externalChatId,
|
|
367203
367526
|
routeChatId: internalChatId,
|
|
@@ -367232,7 +367555,7 @@ function isTrashEmojiOnly(text3) {
|
|
|
367232
367555
|
}
|
|
367233
367556
|
async function isLidMatchingOwner(chatsService, instanceId, ownerIdentifier, ownerPhone, ownerIsLid, lidJid) {
|
|
367234
367557
|
if (ownerIsLid && extractPhoneFromJid(lidJid) === ownerPhone) {
|
|
367235
|
-
|
|
367558
|
+
log98.debug("LID mention matches owner LID directly", { lidJid, ownerIdentifier });
|
|
367236
367559
|
return true;
|
|
367237
367560
|
}
|
|
367238
367561
|
try {
|
|
@@ -367241,13 +367564,13 @@ async function isLidMatchingOwner(chatsService, instanceId, ownerIdentifier, own
|
|
|
367241
367564
|
return false;
|
|
367242
367565
|
const resolvedPhone = extractPhoneFromJid(mapping);
|
|
367243
367566
|
if (resolvedPhone === ownerPhone) {
|
|
367244
|
-
|
|
367567
|
+
log98.debug("LID resolved to instance owner via DB", { lidJid, resolvedPhone, ownerPhone });
|
|
367245
367568
|
return true;
|
|
367246
367569
|
}
|
|
367247
367570
|
if (ownerIsLid) {
|
|
367248
367571
|
const ownerMapping = await chatsService.findLidMapping(instanceId, ownerIdentifier);
|
|
367249
367572
|
if (ownerMapping && extractPhoneFromJid(ownerMapping) === resolvedPhone) {
|
|
367250
|
-
|
|
367573
|
+
log98.debug("LID resolved to owner via reverse mapping", { lidJid, resolvedPhone, ownerIdentifier });
|
|
367251
367574
|
return true;
|
|
367252
367575
|
}
|
|
367253
367576
|
}
|
|
@@ -367293,15 +367616,15 @@ function needsLidMentionCheck(messageContext, instance4) {
|
|
|
367293
367616
|
}
|
|
367294
367617
|
async function shouldProcessMessage3(agentRunner, accessService, chatsService, messagesService, routeResolver, rateLimiter, payload, metadata) {
|
|
367295
367618
|
if (!metadata.instanceId) {
|
|
367296
|
-
|
|
367619
|
+
log98.debug("No instanceId in metadata", { from: payload.from, chatId: payload.chatId });
|
|
367297
367620
|
return null;
|
|
367298
367621
|
}
|
|
367299
367622
|
if (payload.from === metadata.platformIdentityId) {
|
|
367300
|
-
|
|
367623
|
+
log98.debug("Message from self, skipping", { instanceId: metadata.instanceId, from: payload.from });
|
|
367301
367624
|
return null;
|
|
367302
367625
|
}
|
|
367303
367626
|
if (isTrashEmojiOnly(payload.content?.text)) {
|
|
367304
|
-
|
|
367627
|
+
log98.debug("Skipping trash emoji message (session-cleaner handles this)", {
|
|
367305
367628
|
instanceId: metadata.instanceId,
|
|
367306
367629
|
chatId: payload.chatId
|
|
367307
367630
|
});
|
|
@@ -367309,16 +367632,16 @@ async function shouldProcessMessage3(agentRunner, accessService, chatsService, m
|
|
|
367309
367632
|
}
|
|
367310
367633
|
const chatId = payload.chatId ?? "";
|
|
367311
367634
|
if (isBroadcastOrNewsletter(chatId)) {
|
|
367312
|
-
|
|
367635
|
+
log98.debug("Skipping newsletter/broadcast message", { instanceId: metadata.instanceId, chatId });
|
|
367313
367636
|
return null;
|
|
367314
367637
|
}
|
|
367315
367638
|
const instance4 = await agentRunner.getInstanceWithProvider(metadata.instanceId);
|
|
367316
367639
|
if (!instance4?.agentId) {
|
|
367317
|
-
|
|
367640
|
+
log98.debug("Instance has no agentId", { instanceId: metadata.instanceId });
|
|
367318
367641
|
return null;
|
|
367319
367642
|
}
|
|
367320
367643
|
if (!instanceTriggersOnEvent(instance4, "message.received")) {
|
|
367321
|
-
|
|
367644
|
+
log98.debug("Instance does not trigger on message.received", { instanceId: instance4.id });
|
|
367322
367645
|
return null;
|
|
367323
367646
|
}
|
|
367324
367647
|
const messageContext = buildMessageContext(payload, instance4);
|
|
@@ -367328,7 +367651,7 @@ async function shouldProcessMessage3(agentRunner, accessService, chatsService, m
|
|
|
367328
367651
|
await resolveLidMentionBot(chatsService, metadata.instanceId, instance4.ownerIdentifier, mentionedJids, messageContext);
|
|
367329
367652
|
}
|
|
367330
367653
|
await resolveSlackThreadReply(chatsService, messagesService, instance4, payload, messageContext);
|
|
367331
|
-
|
|
367654
|
+
log98.debug("Message context built", {
|
|
367332
367655
|
instanceId: instance4.id,
|
|
367333
367656
|
chatId: payload.chatId,
|
|
367334
367657
|
isDirectMessage: messageContext.isDirectMessage,
|
|
@@ -367338,7 +367661,7 @@ async function shouldProcessMessage3(agentRunner, accessService, chatsService, m
|
|
|
367338
367661
|
});
|
|
367339
367662
|
const effectiveReplyFilter = await resolveEffectiveReplyFilter(chatsService, routeResolver, instance4.id, payload.chatId, instance4.agentReplyFilter);
|
|
367340
367663
|
if (!shouldAgentReply(effectiveReplyFilter, messageContext)) {
|
|
367341
|
-
|
|
367664
|
+
log98.debug("Message did not pass reply filter", {
|
|
367342
367665
|
instanceId: instance4.id,
|
|
367343
367666
|
chatId: payload.chatId,
|
|
367344
367667
|
messageContext,
|
|
@@ -367349,7 +367672,7 @@ async function shouldProcessMessage3(agentRunner, accessService, chatsService, m
|
|
|
367349
367672
|
const channel4 = metadata.channelType ?? "whatsapp";
|
|
367350
367673
|
const rateLimit = instance4.triggerRateLimit;
|
|
367351
367674
|
if (!rateLimiter.isAllowed(payload.from, channel4, instance4.id, rateLimit ?? DEFAULT_RATE_LIMIT)) {
|
|
367352
|
-
|
|
367675
|
+
log98.info("Rate limited", { instanceId: instance4.id, from: payload.from, channel: channel4 });
|
|
367353
367676
|
return null;
|
|
367354
367677
|
}
|
|
367355
367678
|
const accessDenied = await checkAccessWithFallback(accessService, instance4, payload, channel4);
|
|
@@ -367367,7 +367690,7 @@ async function checkAccessWithFallback(accessService, instance4, payload, channe
|
|
|
367367
367690
|
const primaryId = payload.from ?? "";
|
|
367368
367691
|
let accessResult = await accessService.checkAccess(instance4, primaryId, channel4);
|
|
367369
367692
|
if (!accessResult.allowed && participantAlt && participantAlt !== primaryId) {
|
|
367370
|
-
|
|
367693
|
+
log98.warn("Access fallback to participantAlt", {
|
|
367371
367694
|
instanceId: instance4.id,
|
|
367372
367695
|
primaryId,
|
|
367373
367696
|
participantAlt,
|
|
@@ -367376,7 +367699,7 @@ async function checkAccessWithFallback(accessService, instance4, payload, channe
|
|
|
367376
367699
|
accessResult = await accessService.checkAccess(instance4, participantAlt, channel4);
|
|
367377
367700
|
}
|
|
367378
367701
|
if (!accessResult.allowed && resolvedSenderPhone && resolvedSenderPhone !== primaryId && resolvedSenderPhone !== participantAlt) {
|
|
367379
|
-
|
|
367702
|
+
log98.debug("Access fallback to resolvedSenderPhone (LID\u2192phone)", {
|
|
367380
367703
|
instanceId: instance4.id,
|
|
367381
367704
|
primaryId,
|
|
367382
367705
|
resolvedSenderPhone,
|
|
@@ -367386,7 +367709,7 @@ async function checkAccessWithFallback(accessService, instance4, payload, channe
|
|
|
367386
367709
|
}
|
|
367387
367710
|
if (accessResult.allowed)
|
|
367388
367711
|
return false;
|
|
367389
|
-
|
|
367712
|
+
log98.info("Access denied", {
|
|
367390
367713
|
instanceId: instance4.id,
|
|
367391
367714
|
chatId: payload.chatId,
|
|
367392
367715
|
from: payload.from,
|
|
@@ -367395,7 +367718,7 @@ async function checkAccessWithFallback(accessService, instance4, payload, channe
|
|
|
367395
367718
|
});
|
|
367396
367719
|
if (accessResult.mode === "allowlist" && !accessResult.rule && primaryId) {
|
|
367397
367720
|
accessService.requestPairing(instance4.id, primaryId, { channelType: instance4.channel }).catch((err) => {
|
|
367398
|
-
|
|
367721
|
+
log98.warn("Failed to create pairing request", { instanceId: instance4.id, from: primaryId, error: String(err) });
|
|
367399
367722
|
});
|
|
367400
367723
|
}
|
|
367401
367724
|
if (accessResult.rule?.action !== "silent_block" && accessResult.rule?.blockMessage) {
|
|
@@ -367412,20 +367735,20 @@ async function shouldProcessReaction(agentRunner, accessService, rateLimiter, re
|
|
|
367412
367735
|
if (!instanceTriggersOnEvent(instance4, eventType))
|
|
367413
367736
|
return null;
|
|
367414
367737
|
if (!isReactionTrigger(instance4, payload.emoji)) {
|
|
367415
|
-
|
|
367738
|
+
log98.debug("Reaction emoji not in trigger list", { instanceId: instance4.id, emoji: payload.emoji });
|
|
367416
367739
|
return null;
|
|
367417
367740
|
}
|
|
367418
367741
|
const channel4 = metadata.channelType ?? "whatsapp";
|
|
367419
367742
|
const rateLimit = instance4.triggerRateLimit;
|
|
367420
367743
|
if (!rateLimiter.isAllowed(payload.from, channel4, instance4.id, rateLimit ?? DEFAULT_RATE_LIMIT)) {
|
|
367421
|
-
|
|
367744
|
+
log98.info("Rate limited reaction trigger", { instanceId: instance4.id, from: payload.from });
|
|
367422
367745
|
return null;
|
|
367423
367746
|
}
|
|
367424
367747
|
const accessDenied = await checkAccessWithFallback(accessService, instance4, payload, channel4);
|
|
367425
367748
|
if (accessDenied)
|
|
367426
367749
|
return null;
|
|
367427
367750
|
if (reactionDedup.isDuplicate(payload.messageId, payload.emoji, payload.from)) {
|
|
367428
|
-
|
|
367751
|
+
log98.debug("Duplicate reaction, skipping", {
|
|
367429
367752
|
instanceId: instance4.id,
|
|
367430
367753
|
messageId: payload.messageId,
|
|
367431
367754
|
emoji: payload.emoji
|
|
@@ -367458,7 +367781,7 @@ async function shouldRespondViaGate(instance4, messages4, chatType, settings) {
|
|
|
367458
367781
|
try {
|
|
367459
367782
|
const apiKey = await settings.getSecret("gemini.api_key", "GEMINI_API_KEY");
|
|
367460
367783
|
if (!apiKey) {
|
|
367461
|
-
|
|
367784
|
+
log98.warn("Gate: no Gemini API key, fail-open", { traceId });
|
|
367462
367785
|
return true;
|
|
367463
367786
|
}
|
|
367464
367787
|
const controller = new AbortController;
|
|
@@ -367476,13 +367799,13 @@ async function shouldRespondViaGate(instance4, messages4, chatType, settings) {
|
|
|
367476
367799
|
});
|
|
367477
367800
|
clearTimeout(timeout);
|
|
367478
367801
|
if (!res.ok) {
|
|
367479
|
-
|
|
367802
|
+
log98.warn("Gate: API error, fail-open", { traceId, status: res.status, durationMs: Date.now() - startMs });
|
|
367480
367803
|
return true;
|
|
367481
367804
|
}
|
|
367482
367805
|
const data = await res.json();
|
|
367483
367806
|
const answer = data.candidates?.[0]?.content?.parts?.[0]?.text?.trim().toLowerCase() ?? "";
|
|
367484
367807
|
const shouldRespond = !answer.startsWith("skip");
|
|
367485
|
-
|
|
367808
|
+
log98.info("Gate decision", {
|
|
367486
367809
|
traceId,
|
|
367487
367810
|
decision: shouldRespond ? "respond" : "skip",
|
|
367488
367811
|
rawAnswer: answer,
|
|
@@ -367496,14 +367819,14 @@ async function shouldRespondViaGate(instance4, messages4, chatType, settings) {
|
|
|
367496
367819
|
clearTimeout(timeout);
|
|
367497
367820
|
const errName = fetchError.name;
|
|
367498
367821
|
if (errName === "AbortError") {
|
|
367499
|
-
|
|
367822
|
+
log98.warn("Gate: timeout, fail-open", { traceId, durationMs: Date.now() - startMs });
|
|
367500
367823
|
} else {
|
|
367501
|
-
|
|
367824
|
+
log98.warn("Gate: fetch error, fail-open", { traceId, error: String(fetchError) });
|
|
367502
367825
|
}
|
|
367503
367826
|
return true;
|
|
367504
367827
|
}
|
|
367505
367828
|
} catch (error2) {
|
|
367506
|
-
|
|
367829
|
+
log98.warn("Gate: unexpected error, fail-open", { traceId, error: String(error2) });
|
|
367507
367830
|
return true;
|
|
367508
367831
|
}
|
|
367509
367832
|
}
|
|
@@ -367513,7 +367836,7 @@ async function shouldSkipViaGate(triggerType, firstMsg, instance4, messages4, se
|
|
|
367513
367836
|
const chatType = determineChatType(firstMsg.payload.chatId, firstMsg.metadata.channelType ?? "whatsapp", firstMsg.payload.rawPayload ?? {});
|
|
367514
367837
|
const shouldRespond = await shouldRespondViaGate(instance4, messages4, chatType, services.settings);
|
|
367515
367838
|
if (!shouldRespond) {
|
|
367516
|
-
|
|
367839
|
+
log98.info("Gate skipped response", {
|
|
367517
367840
|
instanceId: instance4.id,
|
|
367518
367841
|
chatId: firstMsg.payload.chatId,
|
|
367519
367842
|
triggerType,
|
|
@@ -367534,7 +367857,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367534
367857
|
const leakThreshold = 10 * 60000;
|
|
367535
367858
|
for (const [mediaId, pending] of mediaCompletions.entries()) {
|
|
367536
367859
|
if (now - pending.createdAt > leakThreshold) {
|
|
367537
|
-
|
|
367860
|
+
log98.warn("media_promise_leaked", { mediaId, ageMs: now - pending.createdAt });
|
|
367538
367861
|
pending.reject(new Error("media processing promise leaked (10min circuit breaker)"));
|
|
367539
367862
|
mediaCompletions.delete(mediaId);
|
|
367540
367863
|
}
|
|
@@ -367551,7 +367874,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367551
367874
|
} else {
|
|
367552
367875
|
const baseInstance = await agentRunner.getInstanceWithProvider(instanceId);
|
|
367553
367876
|
if (!baseInstance) {
|
|
367554
|
-
|
|
367877
|
+
log98.warn("Instance not found for debounced messages", { instanceId });
|
|
367555
367878
|
return;
|
|
367556
367879
|
}
|
|
367557
367880
|
const externalChatId = firstMsg.payload.chatId;
|
|
@@ -367603,7 +367926,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367603
367926
|
timestamp: event.timestamp
|
|
367604
367927
|
}, effectiveDebounceConfig);
|
|
367605
367928
|
} catch (error2) {
|
|
367606
|
-
|
|
367929
|
+
log98.error("Error processing message for dispatch", {
|
|
367607
367930
|
instanceId: metadata.instanceId,
|
|
367608
367931
|
error: String(error2)
|
|
367609
367932
|
});
|
|
@@ -367632,7 +367955,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367632
367955
|
traceId
|
|
367633
367956
|
}, event, db2);
|
|
367634
367957
|
} catch (error2) {
|
|
367635
|
-
|
|
367958
|
+
log98.error("Error processing reaction for dispatch", {
|
|
367636
367959
|
instanceId: metadata.instanceId,
|
|
367637
367960
|
error: String(error2)
|
|
367638
367961
|
});
|
|
@@ -367661,7 +367984,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367661
367984
|
traceId
|
|
367662
367985
|
}, event, db2);
|
|
367663
367986
|
} catch (error2) {
|
|
367664
|
-
|
|
367987
|
+
log98.error("Error processing reaction removal for dispatch", {
|
|
367665
367988
|
instanceId: metadata.instanceId,
|
|
367666
367989
|
error: String(error2)
|
|
367667
367990
|
});
|
|
@@ -367690,7 +368013,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367690
368013
|
debouncer.onUserTyping(metadata.instanceId, payload.chatId, debounceConfig);
|
|
367691
368014
|
}
|
|
367692
368015
|
} catch (error2) {
|
|
367693
|
-
|
|
368016
|
+
log98.debug("Error handling typing event", { error: String(error2) });
|
|
367694
368017
|
}
|
|
367695
368018
|
}, {
|
|
367696
368019
|
durable: "agent-dispatcher-typing",
|
|
@@ -367715,16 +368038,16 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367715
368038
|
queue: "agent-dispatcher-media",
|
|
367716
368039
|
startFrom: "new"
|
|
367717
368040
|
});
|
|
367718
|
-
|
|
368041
|
+
log98.info("Agent dispatcher initialized (message + reaction + reaction-removed + media triggers)");
|
|
367719
368042
|
} catch (error2) {
|
|
367720
|
-
|
|
368043
|
+
log98.error("Failed to set up agent dispatcher", { error: String(error2) });
|
|
367721
368044
|
clearInterval(cleanupInterval2);
|
|
367722
368045
|
clearInterval(mediaCleanupInterval);
|
|
367723
368046
|
debouncer.clear();
|
|
367724
368047
|
throw error2;
|
|
367725
368048
|
}
|
|
367726
368049
|
return async () => {
|
|
367727
|
-
|
|
368050
|
+
log98.info("Shutting down agent dispatcher");
|
|
367728
368051
|
clearInterval(cleanupInterval2);
|
|
367729
368052
|
clearInterval(mediaCleanupInterval);
|
|
367730
368053
|
debouncer.clear();
|
|
@@ -367737,7 +368060,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367737
368060
|
for (const [key, provider] of providerCache.entries()) {
|
|
367738
368061
|
if (provider.dispose) {
|
|
367739
368062
|
disposePromises.push(provider.dispose().catch((err) => {
|
|
367740
|
-
|
|
368063
|
+
log98.warn("Error disposing provider", { key, error: String(err) });
|
|
367741
368064
|
}));
|
|
367742
368065
|
}
|
|
367743
368066
|
}
|
|
@@ -367747,7 +368070,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367747
368070
|
try {
|
|
367748
368071
|
client.stop();
|
|
367749
368072
|
} catch (err) {
|
|
367750
|
-
|
|
368073
|
+
log98.warn("Error stopping OpenClaw client", { providerId: id, error: String(err) });
|
|
367751
368074
|
}
|
|
367752
368075
|
}));
|
|
367753
368076
|
}
|
|
@@ -367755,7 +368078,7 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367755
368078
|
let timeoutId;
|
|
367756
368079
|
const timeoutGuard = new Promise((resolve3) => {
|
|
367757
368080
|
timeoutId = setTimeout(() => {
|
|
367758
|
-
|
|
368081
|
+
log98.warn("Dispatcher shutdown timed out after 5s, proceeding");
|
|
367759
368082
|
resolve3([]);
|
|
367760
368083
|
}, 5000);
|
|
367761
368084
|
});
|
|
@@ -367768,10 +368091,10 @@ async function setupAgentDispatcher(eventBus, services, db2) {
|
|
|
367768
368091
|
}
|
|
367769
368092
|
providerCache.clear();
|
|
367770
368093
|
openclawClientPool.clear();
|
|
367771
|
-
|
|
368094
|
+
log98.info("Agent dispatcher shutdown complete");
|
|
367772
368095
|
};
|
|
367773
368096
|
}
|
|
367774
|
-
var
|
|
368097
|
+
var log98, _natsGenieProviderCtor, QUOTED_MESSAGE_MAX_CHARS = 4000, DM_HISTORY_LIMIT = 20, DEFAULT_RATE_LIMIT = 5, DEFAULT_RATE_WINDOW_MS = 60000, CHANNEL_MESSAGE_LIMITS, DEFAULT_MESSAGE_LIMIT = 4000, MEDIA_BASE_PATH3, MEDIA_ICONS, MEDIA_WAIT_NULL, mediaCompletions, mediaResultCache, DEFAULT_SEND_MEDIA_PATH_TYPES, BOT_PREFIX = "\uD83E\uDD16 ", activeStreams, sessionActivityStore, PROC_REACT_START, PROC_REACT_DONE = "\u2705", providerCache, openclawClientPool, DEFAULT_GATE_MODEL = "gemini-3-flash-preview", GATE_TIMEOUT_MS = 3000, setupAgentResponder;
|
|
367775
368098
|
var init_agent_dispatcher = __esm(() => {
|
|
367776
368099
|
init_src2();
|
|
367777
368100
|
init_src();
|
|
@@ -367786,7 +368109,8 @@ var init_agent_dispatcher = __esm(() => {
|
|
|
367786
368109
|
init_message_debouncer();
|
|
367787
368110
|
init_session_storage();
|
|
367788
368111
|
init_src6();
|
|
367789
|
-
|
|
368112
|
+
log98 = createLogger("agent-dispatcher");
|
|
368113
|
+
_natsGenieProviderCtor = NatsGenieProvider;
|
|
367790
368114
|
CHANNEL_MESSAGE_LIMITS = {
|
|
367791
368115
|
discord: 2000,
|
|
367792
368116
|
"whatsapp-baileys": 65536,
|
|
@@ -367881,7 +368205,7 @@ async function setupSyncWorker(eventBus, services, channelRegistry2, database) {
|
|
|
367881
368205
|
await eventBus.subscribe("sync.started", async (event) => {
|
|
367882
368206
|
const payload = event.payload;
|
|
367883
368207
|
const { jobId, instanceId, type, config: config4 } = payload;
|
|
367884
|
-
|
|
368208
|
+
log99.info("Processing sync job", { jobId, instanceId, type });
|
|
367885
368209
|
try {
|
|
367886
368210
|
await services.syncJobs.start(jobId);
|
|
367887
368211
|
const instance4 = await services.instances.getById(instanceId);
|
|
@@ -367908,12 +368232,12 @@ async function setupSyncWorker(eventBus, services, channelRegistry2, database) {
|
|
|
367908
368232
|
case "history-push":
|
|
367909
368233
|
break;
|
|
367910
368234
|
default:
|
|
367911
|
-
|
|
368235
|
+
log99.warn("Unknown sync type", { jobId, type });
|
|
367912
368236
|
await services.syncJobs.fail(jobId, `Unknown sync type: ${type}`);
|
|
367913
368237
|
}
|
|
367914
368238
|
} catch (error2) {
|
|
367915
368239
|
const errorMessage = error2 instanceof Error ? error2.message : String(error2);
|
|
367916
|
-
|
|
368240
|
+
log99.error("Sync job failed", { jobId, error: errorMessage });
|
|
367917
368241
|
await services.syncJobs.fail(jobId, errorMessage);
|
|
367918
368242
|
}
|
|
367919
368243
|
}, {
|
|
@@ -367921,15 +368245,15 @@ async function setupSyncWorker(eventBus, services, channelRegistry2, database) {
|
|
|
367921
368245
|
queue: "sync-workers",
|
|
367922
368246
|
startFrom: "new"
|
|
367923
368247
|
});
|
|
367924
|
-
|
|
368248
|
+
log99.info("Sync worker initialized - listening for sync.started events");
|
|
367925
368249
|
} catch (error2) {
|
|
367926
|
-
|
|
368250
|
+
log99.error("Failed to set up sync worker", { error: String(error2) });
|
|
367927
368251
|
throw error2;
|
|
367928
368252
|
}
|
|
367929
368253
|
}
|
|
367930
368254
|
async function buildWhatsAppAnchors(instanceId, _services) {
|
|
367931
368255
|
if (!db2) {
|
|
367932
|
-
|
|
368256
|
+
log99.warn("Database not available for building anchors");
|
|
367933
368257
|
return [];
|
|
367934
368258
|
}
|
|
367935
368259
|
const result = await db2.execute(sql`
|
|
@@ -367965,20 +368289,20 @@ async function buildWhatsAppAnchors(instanceId, _services) {
|
|
|
367965
368289
|
});
|
|
367966
368290
|
}
|
|
367967
368291
|
}
|
|
367968
|
-
|
|
368292
|
+
log99.info("Built WhatsApp anchors", { instanceId, anchorCount: anchors.length });
|
|
367969
368293
|
return anchors;
|
|
367970
368294
|
}
|
|
367971
368295
|
function buildAnchorsForExplicitChatJids(jobId, chatJids, dbAnchors) {
|
|
367972
|
-
|
|
368296
|
+
log99.info("Using explicit chatJids for sync", { jobId, chatJids });
|
|
367973
368297
|
const anchors = [];
|
|
367974
368298
|
for (const jid of chatJids) {
|
|
367975
368299
|
const dbAnchor = dbAnchors.find((a3) => a3.chatJid === jid);
|
|
367976
368300
|
if (dbAnchor) {
|
|
367977
|
-
|
|
368301
|
+
log99.debug("Found DB anchor for chatJid", { jobId, chatJid: jid, anchorId: dbAnchor.messageKey.id });
|
|
367978
368302
|
anchors.push(dbAnchor);
|
|
367979
368303
|
continue;
|
|
367980
368304
|
}
|
|
367981
|
-
|
|
368305
|
+
log99.debug("No DB anchor for chatJid, will fetch recent", { jobId, chatJid: jid });
|
|
367982
368306
|
anchors.push({
|
|
367983
368307
|
chatJid: jid,
|
|
367984
368308
|
messageKey: { remoteJid: jid, id: "", fromMe: false },
|
|
@@ -368004,7 +368328,7 @@ async function discoverAnchorsFromPlugin(jobId, instanceId, plugin6, dbAnchors,
|
|
|
368004
368328
|
discovered.push({ chatJid: jid, messageKey: { remoteJid: jid, id: "", fromMe: false }, timestamp: Date.now() });
|
|
368005
368329
|
}
|
|
368006
368330
|
if (discovered.length > 0) {
|
|
368007
|
-
|
|
368331
|
+
log99.info("Discovered chats from DB + Baileys not in anchors", {
|
|
368008
368332
|
jobId,
|
|
368009
368333
|
discoveredCount: discovered.length,
|
|
368010
368334
|
fromDb: dbExternalIds.length,
|
|
@@ -368025,7 +368349,7 @@ async function processMessageSync(jobId, instanceId, channelType, config4, servi
|
|
|
368025
368349
|
throw new Error(`No plugin found for channel type: ${channelType}`);
|
|
368026
368350
|
}
|
|
368027
368351
|
if (!("fetchHistory" in plugin6) || typeof plugin6.fetchHistory !== "function") {
|
|
368028
|
-
|
|
368352
|
+
log99.warn("Plugin does not support fetchHistory", { channelType });
|
|
368029
368353
|
await services.syncJobs.complete(jobId);
|
|
368030
368354
|
return;
|
|
368031
368355
|
}
|
|
@@ -368034,7 +368358,7 @@ async function processMessageSync(jobId, instanceId, channelType, config4, servi
|
|
|
368034
368358
|
let fetched = 0;
|
|
368035
368359
|
let stored = 0;
|
|
368036
368360
|
let duplicates = 0;
|
|
368037
|
-
|
|
368361
|
+
log99.info("Starting message sync", {
|
|
368038
368362
|
jobId,
|
|
368039
368363
|
instanceId,
|
|
368040
368364
|
channelType,
|
|
@@ -368044,13 +368368,13 @@ async function processMessageSync(jobId, instanceId, channelType, config4, servi
|
|
|
368044
368368
|
if (channelType === "whatsapp-baileys" && config4.chatJids?.length) {
|
|
368045
368369
|
const dbAnchors = await buildWhatsAppAnchors(instanceId, services);
|
|
368046
368370
|
anchors = await resolveWhatsAppAnchors(jobId, instanceId, config4, plugin6, dbAnchors, services);
|
|
368047
|
-
|
|
368371
|
+
log99.info("WhatsApp per-chat active sync", { jobId, anchorCount: anchors.length, chatJids: config4.chatJids });
|
|
368048
368372
|
} else if (channelType === "whatsapp-baileys") {
|
|
368049
368373
|
const dbAnchors = await buildWhatsAppAnchors(instanceId, services);
|
|
368050
368374
|
const discoveredAnchors = await discoverAnchorsFromPlugin(jobId, instanceId, plugin6, dbAnchors, services);
|
|
368051
368375
|
anchors = [...dbAnchors, ...discoveredAnchors];
|
|
368052
368376
|
if (anchors.length > 0) {
|
|
368053
|
-
|
|
368377
|
+
log99.info("WhatsApp default sync with DB+cache discovery", {
|
|
368054
368378
|
jobId,
|
|
368055
368379
|
instanceId,
|
|
368056
368380
|
dbAnchorCount: dbAnchors.length,
|
|
@@ -368058,7 +368382,7 @@ async function processMessageSync(jobId, instanceId, channelType, config4, servi
|
|
|
368058
368382
|
totalAnchors: anchors.length
|
|
368059
368383
|
});
|
|
368060
368384
|
} else {
|
|
368061
|
-
|
|
368385
|
+
log99.info("WhatsApp passive sync (no prior data)", { jobId, instanceId });
|
|
368062
368386
|
}
|
|
368063
368387
|
}
|
|
368064
368388
|
const fetchOptions = {
|
|
@@ -368100,7 +368424,7 @@ async function processMessageSync(jobId, instanceId, channelType, config4, servi
|
|
|
368100
368424
|
});
|
|
368101
368425
|
stored++;
|
|
368102
368426
|
} catch (error2) {
|
|
368103
|
-
|
|
368427
|
+
log99.warn("Failed to store synced message", {
|
|
368104
368428
|
externalId: msg.externalId,
|
|
368105
368429
|
error: String(error2)
|
|
368106
368430
|
});
|
|
@@ -368117,7 +368441,7 @@ async function processMessageSync(jobId, instanceId, channelType, config4, servi
|
|
|
368117
368441
|
duplicates
|
|
368118
368442
|
});
|
|
368119
368443
|
await services.syncJobs.complete(jobId);
|
|
368120
|
-
|
|
368444
|
+
log99.info("Message sync completed", {
|
|
368121
368445
|
jobId,
|
|
368122
368446
|
fetched,
|
|
368123
368447
|
stored,
|
|
@@ -368164,14 +368488,14 @@ async function processContactsSync(jobId, instanceId, channelType, config4, serv
|
|
|
368164
368488
|
throw new Error(`No plugin found for channel type: ${channelType}`);
|
|
368165
368489
|
}
|
|
368166
368490
|
if (!("fetchContacts" in plugin6) || typeof plugin6.fetchContacts !== "function") {
|
|
368167
|
-
|
|
368491
|
+
log99.warn("Plugin does not support fetchContacts", { channelType });
|
|
368168
368492
|
await services.syncJobs.complete(jobId);
|
|
368169
368493
|
return;
|
|
368170
368494
|
}
|
|
368171
368495
|
let fetched = 0;
|
|
368172
368496
|
let stored = 0;
|
|
368173
368497
|
let linked = 0;
|
|
368174
|
-
|
|
368498
|
+
log99.info("Starting contacts sync", {
|
|
368175
368499
|
jobId,
|
|
368176
368500
|
instanceId,
|
|
368177
368501
|
channelType
|
|
@@ -368210,7 +368534,7 @@ async function processContactsSync(jobId, instanceId, channelType, config4, serv
|
|
|
368210
368534
|
await updateDmChatName(services, instanceId, c.platformUserId, c.name);
|
|
368211
368535
|
}
|
|
368212
368536
|
} catch (error2) {
|
|
368213
|
-
|
|
368537
|
+
log99.warn("Failed to store synced contact", {
|
|
368214
368538
|
platformUserId: c.platformUserId,
|
|
368215
368539
|
error: String(error2)
|
|
368216
368540
|
});
|
|
@@ -368227,7 +368551,7 @@ async function processContactsSync(jobId, instanceId, channelType, config4, serv
|
|
|
368227
368551
|
duplicates: 0
|
|
368228
368552
|
});
|
|
368229
368553
|
await services.syncJobs.complete(jobId);
|
|
368230
|
-
|
|
368554
|
+
log99.info("Contacts sync completed", {
|
|
368231
368555
|
jobId,
|
|
368232
368556
|
fetched,
|
|
368233
368557
|
stored,
|
|
@@ -368241,7 +368565,7 @@ async function processGroupsSync(jobId, instanceId, channelType, _config, servic
|
|
|
368241
368565
|
}
|
|
368242
368566
|
const fetchMethod = channelType === "discord" ? "fetchGuilds" : "fetchGroups";
|
|
368243
368567
|
if (!(fetchMethod in plugin6) || typeof plugin6[fetchMethod] !== "function") {
|
|
368244
|
-
|
|
368568
|
+
log99.warn(`Plugin does not support ${fetchMethod}`, { channelType });
|
|
368245
368569
|
await services.syncJobs.complete(jobId);
|
|
368246
368570
|
return;
|
|
368247
368571
|
}
|
|
@@ -368252,7 +368576,7 @@ async function processGroupsSync(jobId, instanceId, channelType, _config, servic
|
|
|
368252
368576
|
let fetched = 0;
|
|
368253
368577
|
let stored = 0;
|
|
368254
368578
|
let updated = 0;
|
|
368255
|
-
|
|
368579
|
+
log99.info("Starting groups sync", {
|
|
368256
368580
|
jobId,
|
|
368257
368581
|
instanceId,
|
|
368258
368582
|
channelType
|
|
@@ -368302,7 +368626,7 @@ async function processGroupsSync(jobId, instanceId, channelType, _config, servic
|
|
|
368302
368626
|
stored++;
|
|
368303
368627
|
}
|
|
368304
368628
|
} catch (error2) {
|
|
368305
|
-
|
|
368629
|
+
log99.warn("Failed to store synced group", {
|
|
368306
368630
|
externalId: g2.externalId,
|
|
368307
368631
|
error: String(error2)
|
|
368308
368632
|
});
|
|
@@ -368343,7 +368667,7 @@ async function processGroupsSync(jobId, instanceId, channelType, _config, servic
|
|
|
368343
368667
|
stored++;
|
|
368344
368668
|
}
|
|
368345
368669
|
} catch (error2) {
|
|
368346
|
-
|
|
368670
|
+
log99.warn("Failed to store synced guild", {
|
|
368347
368671
|
externalId: g2.externalId,
|
|
368348
368672
|
error: String(error2)
|
|
368349
368673
|
});
|
|
@@ -368358,7 +368682,7 @@ async function processGroupsSync(jobId, instanceId, channelType, _config, servic
|
|
|
368358
368682
|
duplicates: updated
|
|
368359
368683
|
});
|
|
368360
368684
|
await services.syncJobs.complete(jobId);
|
|
368361
|
-
|
|
368685
|
+
log99.info("Groups sync completed", {
|
|
368362
368686
|
jobId,
|
|
368363
368687
|
fetched,
|
|
368364
368688
|
stored,
|
|
@@ -368468,12 +368792,12 @@ async function setupHistoryPushTracker(eventBus, services) {
|
|
|
368468
368792
|
throw error2;
|
|
368469
368793
|
}
|
|
368470
368794
|
}
|
|
368471
|
-
var
|
|
368795
|
+
var log99, RATE_LIMITS2, db2 = null, historyPushLog;
|
|
368472
368796
|
var init_sync_worker = __esm(() => {
|
|
368473
368797
|
init_src();
|
|
368474
368798
|
init_src4();
|
|
368475
368799
|
init_drizzle_orm();
|
|
368476
|
-
|
|
368800
|
+
log99 = createLogger("sync-worker");
|
|
368477
368801
|
RATE_LIMITS2 = {
|
|
368478
368802
|
"whatsapp-baileys": 30,
|
|
368479
368803
|
discord: 50,
|
|
@@ -368537,15 +368861,15 @@ async function handleTrashEmojiMessage(services, db3, event) {
|
|
|
368537
368861
|
return;
|
|
368538
368862
|
if (!isTrashEmojiOnly2(content.text))
|
|
368539
368863
|
return;
|
|
368540
|
-
|
|
368864
|
+
log100.info("Trash emoji detected, clearing session", { instanceId, chatId, from });
|
|
368541
368865
|
try {
|
|
368542
368866
|
const { sessionId, sessionStrategy } = await clearAgentSession(services, db3, instanceId, from, chatId);
|
|
368543
|
-
|
|
368867
|
+
log100.info("Session cleared successfully", { instanceId, sessionId, sessionStrategy });
|
|
368544
368868
|
try {
|
|
368545
368869
|
await sendMessage(services, instanceId, chatId, "\u2705 Conversa limpa! Sua sess\xE3o com o assistente foi resetada.");
|
|
368546
|
-
|
|
368870
|
+
log100.info("Sent session cleared confirmation", { instanceId, chatId });
|
|
368547
368871
|
} catch (sendError) {
|
|
368548
|
-
|
|
368872
|
+
log100.error("Failed to send confirmation message", { instanceId, chatId, error: String(sendError) });
|
|
368549
368873
|
}
|
|
368550
368874
|
} catch (error2) {
|
|
368551
368875
|
const errorMessage = error2 instanceof Error ? error2.message : String(error2);
|
|
@@ -368556,14 +368880,14 @@ async function handleTrashEmojiMessage(services, db3, event) {
|
|
|
368556
368880
|
"Session clearing not supported for"
|
|
368557
368881
|
];
|
|
368558
368882
|
if (skippableErrors.some((e) => errorMessage.includes(e))) {
|
|
368559
|
-
|
|
368883
|
+
log100.debug("Session clearing skipped", { instanceId, reason: errorMessage });
|
|
368560
368884
|
return;
|
|
368561
368885
|
}
|
|
368562
|
-
|
|
368886
|
+
log100.error("Failed to clear session", { instanceId, chatId, error: errorMessage });
|
|
368563
368887
|
try {
|
|
368564
368888
|
await sendMessage(services, instanceId, chatId, "\u274C Erro ao limpar sess\xE3o. Tente novamente.");
|
|
368565
368889
|
} catch (sendError) {
|
|
368566
|
-
|
|
368890
|
+
log100.error("Failed to send error message", { instanceId, chatId, error: String(sendError) });
|
|
368567
368891
|
}
|
|
368568
368892
|
}
|
|
368569
368893
|
}
|
|
@@ -368577,13 +368901,13 @@ async function setupSessionCleaner(eventBus, services, db3) {
|
|
|
368577
368901
|
startFrom: "last",
|
|
368578
368902
|
concurrency: 5
|
|
368579
368903
|
});
|
|
368580
|
-
|
|
368904
|
+
log100.info("Session cleaner initialized");
|
|
368581
368905
|
} catch (error2) {
|
|
368582
|
-
|
|
368906
|
+
log100.error("Failed to set up session cleaner", { error: String(error2) });
|
|
368583
368907
|
throw error2;
|
|
368584
368908
|
}
|
|
368585
368909
|
}
|
|
368586
|
-
var
|
|
368910
|
+
var log100;
|
|
368587
368911
|
var init_session_cleaner = __esm(() => {
|
|
368588
368912
|
init_src();
|
|
368589
368913
|
init_src4();
|
|
@@ -368591,7 +368915,7 @@ var init_session_cleaner = __esm(() => {
|
|
|
368591
368915
|
init_agent_runner();
|
|
368592
368916
|
init_agent_dispatcher();
|
|
368593
368917
|
init_loader2();
|
|
368594
|
-
|
|
368918
|
+
log100 = createLogger("session-cleaner");
|
|
368595
368919
|
});
|
|
368596
368920
|
|
|
368597
368921
|
// ../api/src/plugins/instance-monitor.ts
|
|
@@ -368991,7 +369315,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
368991
369315
|
recordScheduledJob("dead-letter-auto-retry", "success", durationSec);
|
|
368992
369316
|
const pendingCount = await services.deadLetters.getPendingCount();
|
|
368993
369317
|
deadLettersPending.set(pendingCount);
|
|
368994
|
-
|
|
369318
|
+
log101.info("Dead letter auto-retry completed", result);
|
|
368995
369319
|
} catch (err) {
|
|
368996
369320
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
368997
369321
|
recordScheduledJob("dead-letter-auto-retry", "failure", durationSec);
|
|
@@ -369013,7 +369337,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369013
369337
|
recordScheduledJob("payload-cleanup", "success", durationSec);
|
|
369014
369338
|
const stats = await services.payloadStore.getStats();
|
|
369015
369339
|
payloadStorageSize.set(stats.totalSizeCompressed);
|
|
369016
|
-
|
|
369340
|
+
log101.info("Payload cleanup completed", { deleted });
|
|
369017
369341
|
} catch (err) {
|
|
369018
369342
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369019
369343
|
recordScheduledJob("payload-cleanup", "failure", durationSec);
|
|
@@ -369033,7 +369357,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369033
369357
|
const deleted = await services.deadLetters.cleanupExpired();
|
|
369034
369358
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369035
369359
|
recordScheduledJob("dead-letter-cleanup", "success", durationSec);
|
|
369036
|
-
|
|
369360
|
+
log101.info("Dead letter cleanup completed", { deleted });
|
|
369037
369361
|
} catch (err) {
|
|
369038
369362
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369039
369363
|
recordScheduledJob("dead-letter-cleanup", "failure", durationSec);
|
|
@@ -369062,7 +369386,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369062
369386
|
});
|
|
369063
369387
|
jobsCreated++;
|
|
369064
369388
|
} catch (err) {
|
|
369065
|
-
|
|
369389
|
+
log101.warn("Failed to create contacts sync job for instance", {
|
|
369066
369390
|
instanceId: instance4.id,
|
|
369067
369391
|
error: String(err)
|
|
369068
369392
|
});
|
|
@@ -369070,7 +369394,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369070
369394
|
}
|
|
369071
369395
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369072
369396
|
recordScheduledJob("contacts-sync-daily", "success", durationSec);
|
|
369073
|
-
|
|
369397
|
+
log101.info("Daily contacts sync jobs created", { jobsCreated, instanceCount: instances2.length });
|
|
369074
369398
|
} catch (err) {
|
|
369075
369399
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369076
369400
|
recordScheduledJob("contacts-sync-daily", "failure", durationSec);
|
|
@@ -369099,7 +369423,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369099
369423
|
});
|
|
369100
369424
|
jobsCreated++;
|
|
369101
369425
|
} catch (err) {
|
|
369102
|
-
|
|
369426
|
+
log101.warn("Failed to create groups sync job for instance", {
|
|
369103
369427
|
instanceId: instance4.id,
|
|
369104
369428
|
error: String(err)
|
|
369105
369429
|
});
|
|
@@ -369107,7 +369431,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369107
369431
|
}
|
|
369108
369432
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369109
369433
|
recordScheduledJob("groups-sync-daily", "success", durationSec);
|
|
369110
|
-
|
|
369434
|
+
log101.info("Daily groups sync jobs created", { jobsCreated, instanceCount: instances2.length });
|
|
369111
369435
|
} catch (err) {
|
|
369112
369436
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369113
369437
|
recordScheduledJob("groups-sync-daily", "failure", durationSec);
|
|
@@ -369136,7 +369460,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369136
369460
|
}
|
|
369137
369461
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369138
369462
|
recordScheduledJob("unread-count-refresh", "success", durationSec);
|
|
369139
|
-
|
|
369463
|
+
log101.debug("Refreshed unread counts", { instanceCount: waInstances.length });
|
|
369140
369464
|
} catch (err) {
|
|
369141
369465
|
const durationSec = (Date.now() - startTime3) / 1000;
|
|
369142
369466
|
recordScheduledJob("unread-count-refresh", "failure", durationSec);
|
|
@@ -369147,7 +369471,7 @@ function setupScheduler(services, channelRegistry2) {
|
|
|
369147
369471
|
});
|
|
369148
369472
|
updateSchedulerMetrics();
|
|
369149
369473
|
scheduler.start();
|
|
369150
|
-
|
|
369474
|
+
log101.info("Scheduler started", {
|
|
369151
369475
|
jobs: scheduler.listJobs().map((j) => ({
|
|
369152
369476
|
name: j.name,
|
|
369153
369477
|
cron: j.cron,
|
|
@@ -369167,14 +369491,14 @@ function updateSchedulerMetrics() {
|
|
|
369167
369491
|
function stopScheduler() {
|
|
369168
369492
|
const scheduler = getScheduler();
|
|
369169
369493
|
scheduler.stop();
|
|
369170
|
-
|
|
369494
|
+
log101.info("Scheduler stopped");
|
|
369171
369495
|
}
|
|
369172
|
-
var
|
|
369496
|
+
var log101;
|
|
369173
369497
|
var init_scheduler2 = __esm(() => {
|
|
369174
369498
|
init_src();
|
|
369175
369499
|
init_esm5();
|
|
369176
369500
|
init_sentry_scrub();
|
|
369177
|
-
|
|
369501
|
+
log101 = createLogger("scheduler:setup");
|
|
369178
369502
|
});
|
|
369179
369503
|
|
|
369180
369504
|
// ../api/src/services/turn-monitor.ts
|
|
@@ -369188,7 +369512,7 @@ class TurnMonitor {
|
|
|
369188
369512
|
start() {
|
|
369189
369513
|
if (this.intervalId)
|
|
369190
369514
|
return;
|
|
369191
|
-
|
|
369515
|
+
log102.info("Turn monitor started", {
|
|
369192
369516
|
pollIntervalMs: POLL_INTERVAL_MS2,
|
|
369193
369517
|
nudgeMs: NUDGE_THRESHOLD_MS,
|
|
369194
369518
|
fallbackMs: FALLBACK_THRESHOLD_MS,
|
|
@@ -369200,7 +369524,7 @@ class TurnMonitor {
|
|
|
369200
369524
|
if (this.intervalId) {
|
|
369201
369525
|
clearInterval(this.intervalId);
|
|
369202
369526
|
this.intervalId = null;
|
|
369203
|
-
|
|
369527
|
+
log102.info("Turn monitor stopped");
|
|
369204
369528
|
}
|
|
369205
369529
|
}
|
|
369206
369530
|
async tick() {
|
|
@@ -369226,7 +369550,7 @@ class TurnMonitor {
|
|
|
369226
369550
|
}
|
|
369227
369551
|
}
|
|
369228
369552
|
} catch (error2) {
|
|
369229
|
-
|
|
369553
|
+
log102.error("Turn monitor tick failed", { error: String(error2) });
|
|
369230
369554
|
} finally {
|
|
369231
369555
|
this.running = false;
|
|
369232
369556
|
}
|
|
@@ -369239,16 +369563,16 @@ class TurnMonitor {
|
|
|
369239
369563
|
idleSec,
|
|
369240
369564
|
message: `Turn idle for ${idleSec}s. Are you still working?`
|
|
369241
369565
|
});
|
|
369242
|
-
|
|
369566
|
+
log102.info("Turn nudge emitted", { turnId, nudgeCount, idleSec });
|
|
369243
369567
|
}
|
|
369244
369568
|
async handleFallback(turnId, instanceId, chatId, idleSec) {
|
|
369245
369569
|
await this.deps.turnService.incrementNudge(turnId);
|
|
369246
369570
|
if (this.deps.sendFallback) {
|
|
369247
369571
|
try {
|
|
369248
369572
|
await this.deps.sendFallback(instanceId, chatId, "\u23F1 Still processing your request...");
|
|
369249
|
-
|
|
369573
|
+
log102.info("Fallback message sent", { turnId, idleSec });
|
|
369250
369574
|
} catch (error2) {
|
|
369251
|
-
|
|
369575
|
+
log102.error("Failed to send fallback message", { turnId, error: String(error2) });
|
|
369252
369576
|
}
|
|
369253
369577
|
}
|
|
369254
369578
|
}
|
|
@@ -369265,7 +369589,7 @@ class TurnMonitor {
|
|
|
369265
369589
|
try {
|
|
369266
369590
|
await this.deps.sendFallback(instanceId, chatId, "\u23F1 Request timed out. Please try again.");
|
|
369267
369591
|
} catch (error2) {
|
|
369268
|
-
|
|
369592
|
+
log102.error("Failed to send timeout fallback", { turnId, error: String(error2) });
|
|
369269
369593
|
}
|
|
369270
369594
|
}
|
|
369271
369595
|
publishTurnTimeout(instanceId, chatId, {
|
|
@@ -369282,14 +369606,14 @@ class TurnMonitor {
|
|
|
369282
369606
|
nudgeCount,
|
|
369283
369607
|
messagesSent: closed.messagesSent
|
|
369284
369608
|
});
|
|
369285
|
-
|
|
369609
|
+
log102.info("Turn force-closed (timeout)", { turnId, duration, nudgeCount });
|
|
369286
369610
|
}
|
|
369287
369611
|
}
|
|
369288
|
-
var
|
|
369612
|
+
var log102, NUDGE_THRESHOLD_MS = 60000, FALLBACK_THRESHOLD_MS = 300000, TIMEOUT_THRESHOLD_MS = 900000, POLL_INTERVAL_MS2 = 1e4;
|
|
369289
369613
|
var init_turn_monitor = __esm(() => {
|
|
369290
369614
|
init_src();
|
|
369291
369615
|
init_turn_events();
|
|
369292
|
-
|
|
369616
|
+
log102 = createLogger("turn-monitor");
|
|
369293
369617
|
});
|
|
369294
369618
|
|
|
369295
369619
|
// ../api/src/utils/startup-banner.ts
|
|
@@ -369363,12 +369687,12 @@ function printStartupBanner(options) {
|
|
|
369363
369687
|
process.stdout.write(`${line3}
|
|
369364
369688
|
`);
|
|
369365
369689
|
}
|
|
369366
|
-
|
|
369690
|
+
log103.info("Server ready", { host, port, version: version4 });
|
|
369367
369691
|
}
|
|
369368
|
-
var
|
|
369692
|
+
var log103, COLORS3, BOX, ANSI_ESCAPE_PATTERN;
|
|
369369
369693
|
var init_startup_banner = __esm(() => {
|
|
369370
369694
|
init_src();
|
|
369371
|
-
|
|
369695
|
+
log103 = createLogger("api:startup");
|
|
369372
369696
|
COLORS3 = {
|
|
369373
369697
|
reset: "\x1B[0m",
|
|
369374
369698
|
dim: "\x1B[2m",
|
|
@@ -369530,23 +369854,23 @@ function setupShutdownHandlers(server, earlyShutdown) {
|
|
|
369530
369854
|
}
|
|
369531
369855
|
async function setupEventBusServices(eventBus, services, db3) {
|
|
369532
369856
|
if (!eventBus) {
|
|
369533
|
-
|
|
369857
|
+
log104.warn("Skipping event bus services (no event bus)");
|
|
369534
369858
|
return;
|
|
369535
369859
|
}
|
|
369536
369860
|
try {
|
|
369537
369861
|
await setupMessagePersistence(eventBus, services);
|
|
369538
369862
|
} catch (error2) {
|
|
369539
|
-
|
|
369863
|
+
log104.error("Failed to set up message persistence", { error: String(error2) });
|
|
369540
369864
|
}
|
|
369541
369865
|
try {
|
|
369542
369866
|
await setupMediaProcessor(eventBus, db3, services);
|
|
369543
369867
|
} catch (error2) {
|
|
369544
|
-
|
|
369868
|
+
log104.error("Failed to set up media processor", { error: String(error2) });
|
|
369545
369869
|
}
|
|
369546
369870
|
try {
|
|
369547
369871
|
globalDispatcherCleanup = await setupAgentResponder(eventBus, services, db3);
|
|
369548
369872
|
} catch (error2) {
|
|
369549
|
-
|
|
369873
|
+
log104.error("Failed to set up agent dispatcher", { error: String(error2) });
|
|
369550
369874
|
}
|
|
369551
369875
|
try {
|
|
369552
369876
|
await services.automations.startEngine({
|
|
@@ -369561,29 +369885,29 @@ async function setupEventBusServices(eventBus, services, db3) {
|
|
|
369561
369885
|
}
|
|
369562
369886
|
});
|
|
369563
369887
|
} catch (error2) {
|
|
369564
|
-
|
|
369888
|
+
log104.error("Failed to start automation engine", { error: String(error2) });
|
|
369565
369889
|
}
|
|
369566
369890
|
try {
|
|
369567
369891
|
await setupSessionCleaner(eventBus, services, db3);
|
|
369568
369892
|
} catch (error2) {
|
|
369569
|
-
|
|
369893
|
+
log104.error("Failed to set up session cleaner", { error: String(error2) });
|
|
369570
369894
|
}
|
|
369571
369895
|
if (globalChannelRegistry) {
|
|
369572
369896
|
try {
|
|
369573
369897
|
await setupSyncWorker(eventBus, services, globalChannelRegistry, db3);
|
|
369574
369898
|
} catch (error2) {
|
|
369575
|
-
|
|
369899
|
+
log104.error("Failed to set up sync worker", { error: String(error2) });
|
|
369576
369900
|
}
|
|
369577
369901
|
}
|
|
369578
369902
|
try {
|
|
369579
369903
|
await setupHistoryPushTracker(eventBus, services);
|
|
369580
369904
|
} catch (error2) {
|
|
369581
|
-
|
|
369905
|
+
log104.error("Failed to set up history-push tracker", { error: String(error2) });
|
|
369582
369906
|
}
|
|
369583
369907
|
try {
|
|
369584
369908
|
await initTurnEvents(NATS_URL);
|
|
369585
369909
|
} catch (error2) {
|
|
369586
|
-
|
|
369910
|
+
log104.error("Failed to initialize turn events", { error: String(error2) });
|
|
369587
369911
|
}
|
|
369588
369912
|
try {
|
|
369589
369913
|
globalTurnMonitor = new TurnMonitor({
|
|
@@ -369599,41 +369923,41 @@ async function setupEventBusServices(eventBus, services, db3) {
|
|
|
369599
369923
|
}
|
|
369600
369924
|
});
|
|
369601
369925
|
globalTurnMonitor.start();
|
|
369602
|
-
|
|
369926
|
+
log104.info("Turn monitor started");
|
|
369603
369927
|
} catch (error2) {
|
|
369604
|
-
|
|
369928
|
+
log104.error("Failed to start turn monitor", { error: String(error2) });
|
|
369605
369929
|
}
|
|
369606
369930
|
}
|
|
369607
369931
|
async function waitForDatabaseReady(db3, maxAttempts = 30) {
|
|
369608
|
-
|
|
369932
|
+
log104.info("Waiting for database readiness");
|
|
369609
369933
|
for (let attempt = 1;attempt <= maxAttempts; attempt++) {
|
|
369610
369934
|
try {
|
|
369611
369935
|
await db3.execute(sql`SELECT 1`);
|
|
369612
|
-
|
|
369936
|
+
log104.info("Database ready", { attempt });
|
|
369613
369937
|
return;
|
|
369614
369938
|
} catch {
|
|
369615
369939
|
if (attempt === maxAttempts) {
|
|
369616
369940
|
throw new Error(`Database not ready after ${maxAttempts} attempts`);
|
|
369617
369941
|
}
|
|
369618
|
-
|
|
369942
|
+
log104.warn("Database not ready, retrying...", { attempt });
|
|
369619
369943
|
await new Promise((resolve3) => setTimeout(resolve3, 1000));
|
|
369620
369944
|
}
|
|
369621
369945
|
}
|
|
369622
369946
|
}
|
|
369623
369947
|
async function main() {
|
|
369624
|
-
|
|
369948
|
+
log104.info("Starting Omni API v2");
|
|
369625
369949
|
enableDefaultMetrics();
|
|
369626
369950
|
const pgserveConfig = resolvePgserveConfig();
|
|
369627
369951
|
const databaseUrl = await startEmbeddedPgserve(pgserveConfig);
|
|
369628
|
-
|
|
369952
|
+
log104.info("Connecting to database");
|
|
369629
369953
|
const db3 = createDb({ url: databaseUrl });
|
|
369630
369954
|
const earlyShutdown = async () => {
|
|
369631
|
-
|
|
369955
|
+
log104.info("Shutdown during startup \u2014 cleaning up");
|
|
369632
369956
|
try {
|
|
369633
369957
|
await closeDb();
|
|
369634
369958
|
await stopEmbeddedPgserve();
|
|
369635
369959
|
} catch (err) {
|
|
369636
|
-
|
|
369960
|
+
log104.error("Cleanup failed during early shutdown", { error: String(err) });
|
|
369637
369961
|
} finally {
|
|
369638
369962
|
process.exit(1);
|
|
369639
369963
|
}
|
|
@@ -369647,7 +369971,7 @@ async function main() {
|
|
|
369647
369971
|
await stopEmbeddedPgserve();
|
|
369648
369972
|
throw error2;
|
|
369649
369973
|
}
|
|
369650
|
-
|
|
369974
|
+
log104.info("Running database migrations");
|
|
369651
369975
|
const migrationStart = Date.now();
|
|
369652
369976
|
const MIGRATION_TIMEOUT_MS = 60000;
|
|
369653
369977
|
try {
|
|
@@ -369660,7 +369984,7 @@ async function main() {
|
|
|
369660
369984
|
await stopEmbeddedPgserve();
|
|
369661
369985
|
throw error2;
|
|
369662
369986
|
}
|
|
369663
|
-
|
|
369987
|
+
log104.info("Database migrations complete", { durationMs: Date.now() - migrationStart });
|
|
369664
369988
|
const eventBus = await connectToNats(db3);
|
|
369665
369989
|
if (eventBus) {
|
|
369666
369990
|
try {
|
|
@@ -369675,9 +369999,9 @@ async function main() {
|
|
|
369675
369999
|
try {
|
|
369676
370000
|
await services.settings.seedDefaults();
|
|
369677
370001
|
} catch (error2) {
|
|
369678
|
-
|
|
370002
|
+
log104.error("Failed to seed default settings", { error: String(error2) });
|
|
369679
370003
|
}
|
|
369680
|
-
|
|
370004
|
+
log104.info("Initializing API key");
|
|
369681
370005
|
let apiKeyInfo;
|
|
369682
370006
|
try {
|
|
369683
370007
|
const keyResult = await services.apiKeys.initializePrimaryKey();
|
|
@@ -369687,17 +370011,17 @@ async function main() {
|
|
|
369687
370011
|
isFromEnv: keyResult.isFromEnv
|
|
369688
370012
|
};
|
|
369689
370013
|
if (keyResult.isNew) {
|
|
369690
|
-
|
|
370014
|
+
log104.info("Generated new primary API key");
|
|
369691
370015
|
} else if (keyResult.isFromEnv) {
|
|
369692
|
-
|
|
370016
|
+
log104.info("Using primary API key from environment");
|
|
369693
370017
|
} else {
|
|
369694
|
-
|
|
370018
|
+
log104.info("Using existing primary API key");
|
|
369695
370019
|
}
|
|
369696
370020
|
} catch (error2) {
|
|
369697
|
-
|
|
370021
|
+
log104.error("Failed to initialize primary API key", { error: String(error2) });
|
|
369698
370022
|
}
|
|
369699
370023
|
await setupEventBusServices(eventBus, services, db3);
|
|
369700
|
-
|
|
370024
|
+
log104.info("Starting scheduler");
|
|
369701
370025
|
setupScheduler(services, globalChannelRegistry);
|
|
369702
370026
|
const server = startBunServer(app);
|
|
369703
370027
|
printStartupBanner({
|
|
@@ -369711,7 +370035,7 @@ async function main() {
|
|
|
369711
370035
|
});
|
|
369712
370036
|
setupShutdownHandlers(server, earlyShutdown);
|
|
369713
370037
|
}
|
|
369714
|
-
var import__package3,
|
|
370038
|
+
var import__package3, log104, natsLog, pluginLog, shutdownLog, PORT, HOST, NATS_URL, globalEventBus = null, globalChannelRegistry = null, globalInstanceMonitor = null, globalDispatcherCleanup = null, globalTurnMonitor = null;
|
|
369715
370039
|
var init_src7 = __esm(() => {
|
|
369716
370040
|
init_instrument2();
|
|
369717
370041
|
init_src();
|
|
@@ -369733,7 +370057,7 @@ var init_src7 = __esm(() => {
|
|
|
369733
370057
|
level: process.env.LOG_LEVEL ?? "info",
|
|
369734
370058
|
format: process.env.LOG_FORMAT ?? "auto"
|
|
369735
370059
|
});
|
|
369736
|
-
|
|
370060
|
+
log104 = createLogger("api:startup");
|
|
369737
370061
|
natsLog = createLogger("api:nats");
|
|
369738
370062
|
pluginLog = createLogger("api:plugins");
|
|
369739
370063
|
shutdownLog = createLogger("api:shutdown");
|
|
@@ -369741,7 +370065,7 @@ var init_src7 = __esm(() => {
|
|
|
369741
370065
|
HOST = process.env.API_HOST ?? "0.0.0.0";
|
|
369742
370066
|
NATS_URL = process.env.NATS_URL ?? "nats://localhost:4222";
|
|
369743
370067
|
main().catch((error2) => {
|
|
369744
|
-
|
|
370068
|
+
log104.error("Failed to start API server", { error: String(error2) });
|
|
369745
370069
|
process.exit(1);
|
|
369746
370070
|
});
|
|
369747
370071
|
});
|