@agent-native/core 0.130.0 → 0.130.1
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/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +6 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/integrations/a2a-continuation-processor.ts +481 -122
- package/corpus/core/src/integrations/a2a-continuations-store.ts +345 -14
- package/corpus/core/src/integrations/adapters/slack.ts +243 -53
- package/corpus/core/src/integrations/integration-campaign-recovery.ts +4 -1
- package/corpus/core/src/integrations/plugin.ts +39 -21
- package/corpus/core/src/integrations/task-queue-stats.ts +146 -0
- package/corpus/core/src/integrations/types.ts +25 -4
- package/corpus/core/src/integrations/webhook-handler.ts +18 -5
- package/corpus/templates/dispatch/changelog/2026-07-26-slack-replies-recover-after-connected-app-updates.md +6 -0
- package/corpus/templates/slides/.agents/skills/design-systems/SKILL.md +15 -0
- package/corpus/templates/slides/actions/delete-design-system.ts +145 -0
- package/corpus/templates/slides/actions/list-design-systems.ts +94 -2
- package/corpus/templates/slides/app/components/design-system/DesignSystemCard.tsx +43 -1
- package/corpus/templates/slides/app/hooks/use-design-systems.ts +2 -0
- package/corpus/templates/slides/app/i18n/en-US.ts +7 -0
- package/corpus/templates/slides/app/pages/DesignSystems.tsx +56 -1
- package/corpus/templates/slides/changelog/2026-07-28-delete-a-design-system-you-own-from-the-design-systems-page-.md +6 -0
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/integrations/a2a-continuation-processor.d.ts +5 -0
- package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -1
- package/dist/integrations/a2a-continuation-processor.js +293 -79
- package/dist/integrations/a2a-continuation-processor.js.map +1 -1
- package/dist/integrations/a2a-continuations-store.d.ts +23 -1
- package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
- package/dist/integrations/a2a-continuations-store.js +249 -15
- package/dist/integrations/a2a-continuations-store.js.map +1 -1
- package/dist/integrations/adapters/slack.d.ts.map +1 -1
- package/dist/integrations/adapters/slack.js +155 -31
- package/dist/integrations/adapters/slack.js.map +1 -1
- package/dist/integrations/integration-campaign-recovery.d.ts.map +1 -1
- package/dist/integrations/integration-campaign-recovery.js +3 -1
- package/dist/integrations/integration-campaign-recovery.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +29 -12
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/integrations/task-queue-stats.d.ts +12 -0
- package/dist/integrations/task-queue-stats.d.ts.map +1 -1
- package/dist/integrations/task-queue-stats.js +106 -0
- package/dist/integrations/task-queue-stats.js.map +1 -1
- package/dist/integrations/types.d.ts +24 -6
- package/dist/integrations/types.d.ts.map +1 -1
- package/dist/integrations/types.js.map +1 -1
- package/dist/integrations/webhook-handler.d.ts.map +1 -1
- package/dist/integrations/webhook-handler.js +12 -3
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/observability/routes.d.ts +3 -3
- package/dist/progress/routes.d.ts +1 -1
- package/dist/resources/handlers.d.ts +1 -1
- package/dist/secrets/routes.d.ts +9 -9
- package/dist/server/realtime-token.d.ts +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/package.json +1 -1
- package/src/integrations/a2a-continuation-processor.ts +481 -122
- package/src/integrations/a2a-continuations-store.ts +345 -14
- package/src/integrations/adapters/slack.ts +243 -53
- package/src/integrations/integration-campaign-recovery.ts +4 -1
- package/src/integrations/plugin.ts +39 -21
- package/src/integrations/task-queue-stats.ts +146 -0
- package/src/integrations/types.ts +25 -4
- package/src/integrations/webhook-handler.ts +18 -5
|
@@ -10,6 +10,18 @@ export interface TaskQueueStats {
|
|
|
10
10
|
completed_last_hour: number;
|
|
11
11
|
failed_last_hour: number;
|
|
12
12
|
oldest_pending_age_seconds: number;
|
|
13
|
+
waiting_campaigns: number;
|
|
14
|
+
active_a2a_continuations: number;
|
|
15
|
+
oldest_active_a2a_age_seconds: number;
|
|
16
|
+
terminal_a2a_without_delivery: number;
|
|
17
|
+
recent_a2a_orphans: Array<{
|
|
18
|
+
continuation_id: string;
|
|
19
|
+
integration_task_id: string;
|
|
20
|
+
status: string;
|
|
21
|
+
attempts: number;
|
|
22
|
+
age_seconds: number;
|
|
23
|
+
reason_class: string;
|
|
24
|
+
}>;
|
|
13
25
|
recent_failures: RecentFailure[];
|
|
14
26
|
recent_tasks: Array<{
|
|
15
27
|
id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-queue-stats.d.ts","sourceRoot":"","sources":["../../src/integrations/task-queue-stats.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"task-queue-stats.d.ts","sourceRoot":"","sources":["../../src/integrations/task-queue-stats.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,gBAAgB,EAAE,MAAM,CAAC;IACzB,0BAA0B,EAAE,MAAM,CAAC;IACnC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,wBAAwB,EAAE,MAAM,CAAC;IACjC,6BAA6B,EAAE,MAAM,CAAC;IACtC,6BAA6B,EAAE,MAAM,CAAC;IACtC,kBAAkB,EAAE,KAAK,CAAC;QACxB,eAAe,EAAE,MAAM,CAAC;QACxB,mBAAmB,EAAE,MAAM,CAAC;QAC5B,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;QACjB,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC,CAAC;IACH,eAAe,EAAE,aAAa,EAAE,CAAC;IACjC,YAAY,EAAE,KAAK,CAAC;QAClB,EAAE,EAAE,MAAM,CAAC;QACX,QAAQ,EAAE,MAAM,CAAC;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;QACjB,iBAAiB,EAAE,MAAM,CAAC;QAC1B,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAC;QACrC,WAAW,EAAE,MAAM,CAAC;KACrB,CAAC,CAAC;CACJ;AAED,MAAM,WAAW,mBAAmB;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAwBD;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,KAAK,EAAE,mBAAmB,GACzB,OAAO,CAAC,cAAc,CAAC,CAkJzB"}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* columns before the SELECTs execute.
|
|
9
9
|
*/
|
|
10
10
|
import { getDbExec } from "../db/client.js";
|
|
11
|
+
import { ensureA2AContinuationsTable } from "./a2a-continuations-store.js";
|
|
11
12
|
import { ensurePendingTasksTable } from "./pending-tasks-store.js";
|
|
12
13
|
const ZERO_STATS = {
|
|
13
14
|
pending: 0,
|
|
@@ -15,6 +16,11 @@ const ZERO_STATS = {
|
|
|
15
16
|
completed_last_hour: 0,
|
|
16
17
|
failed_last_hour: 0,
|
|
17
18
|
oldest_pending_age_seconds: 0,
|
|
19
|
+
waiting_campaigns: 0,
|
|
20
|
+
active_a2a_continuations: 0,
|
|
21
|
+
oldest_active_a2a_age_seconds: 0,
|
|
22
|
+
terminal_a2a_without_delivery: 0,
|
|
23
|
+
recent_a2a_orphans: [],
|
|
18
24
|
recent_failures: [],
|
|
19
25
|
recent_tasks: [],
|
|
20
26
|
};
|
|
@@ -29,11 +35,14 @@ function isMissingTableError(err) {
|
|
|
29
35
|
*/
|
|
30
36
|
export async function getTaskQueueStats(scope) {
|
|
31
37
|
await ensurePendingTasksTable();
|
|
38
|
+
await ensureA2AContinuationsTable();
|
|
32
39
|
const client = getDbExec();
|
|
33
40
|
const now = Date.now();
|
|
34
41
|
const oneHourAgo = now - 60 * 60 * 1000;
|
|
35
42
|
const scopeSql = `owner_email = ?
|
|
36
43
|
AND ((org_id IS NULL AND CAST(? AS TEXT) IS NULL) OR org_id = ?)`;
|
|
44
|
+
const joinedScopeSql = `t.owner_email = ?
|
|
45
|
+
AND ((t.org_id IS NULL AND CAST(? AS TEXT) IS NULL) OR t.org_id = ?)`;
|
|
37
46
|
const scopeArgs = [scope.ownerEmail, scope.orgId, scope.orgId];
|
|
38
47
|
try {
|
|
39
48
|
// Status counts (pending, processing) — only need the live ones.
|
|
@@ -127,12 +136,16 @@ export async function getTaskQueueStats(scope) {
|
|
|
127
136
|
: String(row.last_dispatch_outcome),
|
|
128
137
|
age_seconds: Math.max(0, Math.floor((now - Number(row.created_at ?? now)) / 1000)),
|
|
129
138
|
}));
|
|
139
|
+
const waitingCampaigns = await readWaitingCampaignCount(client, joinedScopeSql, scopeArgs);
|
|
140
|
+
const a2aStats = await readA2AContinuationStats(client, joinedScopeSql, scopeArgs, now);
|
|
130
141
|
return {
|
|
131
142
|
pending,
|
|
132
143
|
processing,
|
|
133
144
|
completed_last_hour: completedLastHour,
|
|
134
145
|
failed_last_hour: failedLastHour,
|
|
135
146
|
oldest_pending_age_seconds: oldestPendingAgeSeconds,
|
|
147
|
+
waiting_campaigns: waitingCampaigns,
|
|
148
|
+
...a2aStats,
|
|
136
149
|
recent_failures: recentFailures,
|
|
137
150
|
recent_tasks: recentTasks,
|
|
138
151
|
};
|
|
@@ -144,4 +157,97 @@ export async function getTaskQueueStats(scope) {
|
|
|
144
157
|
throw err;
|
|
145
158
|
}
|
|
146
159
|
}
|
|
160
|
+
async function readWaitingCampaignCount(client, scopeSql, scopeArgs) {
|
|
161
|
+
try {
|
|
162
|
+
const result = await client.execute({
|
|
163
|
+
sql: `SELECT COUNT(*) AS c
|
|
164
|
+
FROM integration_campaigns c
|
|
165
|
+
INNER JOIN integration_pending_tasks t
|
|
166
|
+
ON t.id = c.integration_task_id
|
|
167
|
+
WHERE ${scopeSql}
|
|
168
|
+
AND c.status = 'waiting'`,
|
|
169
|
+
args: scopeArgs,
|
|
170
|
+
});
|
|
171
|
+
return Number(result.rows[0]?.c ?? 0);
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
if (isMissingTableError(err))
|
|
175
|
+
return 0;
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function readA2AContinuationStats(client, scopeSql, scopeArgs, now) {
|
|
180
|
+
try {
|
|
181
|
+
const live = await client.execute({
|
|
182
|
+
sql: `SELECT
|
|
183
|
+
COUNT(CASE WHEN c.status IN ('pending', 'processing', 'delivering') THEN 1 END) AS active_count,
|
|
184
|
+
MIN(CASE WHEN c.status IN ('pending', 'processing', 'delivering') THEN c.created_at END) AS oldest_created_at,
|
|
185
|
+
COUNT(CASE WHEN c.status IN ('completed', 'failed')
|
|
186
|
+
AND c.terminal_delivery_confirmed_at IS NULL THEN 1 END) AS orphan_count
|
|
187
|
+
FROM integration_a2a_continuations c
|
|
188
|
+
INNER JOIN integration_pending_tasks t
|
|
189
|
+
ON t.id = c.integration_task_id
|
|
190
|
+
WHERE ${scopeSql}`,
|
|
191
|
+
args: scopeArgs,
|
|
192
|
+
});
|
|
193
|
+
const orphaned = await client.execute({
|
|
194
|
+
sql: `SELECT c.id, c.integration_task_id, c.status, c.attempts,
|
|
195
|
+
c.created_at, c.error_message
|
|
196
|
+
FROM integration_a2a_continuations c
|
|
197
|
+
INNER JOIN integration_pending_tasks t
|
|
198
|
+
ON t.id = c.integration_task_id
|
|
199
|
+
WHERE ${scopeSql}
|
|
200
|
+
AND c.status IN ('completed', 'failed')
|
|
201
|
+
AND c.terminal_delivery_confirmed_at IS NULL
|
|
202
|
+
ORDER BY c.updated_at DESC
|
|
203
|
+
LIMIT 5`,
|
|
204
|
+
args: scopeArgs,
|
|
205
|
+
});
|
|
206
|
+
const activeCount = Number(live.rows[0]?.active_count ?? 0);
|
|
207
|
+
const orphanCount = Number(live.rows[0]?.orphan_count ?? 0);
|
|
208
|
+
const oldestCreatedAt = Number(live.rows[0]?.oldest_created_at ?? now);
|
|
209
|
+
const recentOrphans = orphaned.rows.map((row) => ({
|
|
210
|
+
continuation_id: String(row.id ?? ""),
|
|
211
|
+
integration_task_id: String(row.integration_task_id ?? ""),
|
|
212
|
+
status: String(row.status ?? ""),
|
|
213
|
+
attempts: Number(row.attempts ?? 0),
|
|
214
|
+
age_seconds: Math.max(0, Math.floor((now - Number(row.created_at ?? now)) / 1000)),
|
|
215
|
+
reason_class: classifyA2AOrphanReason(row.error_message),
|
|
216
|
+
}));
|
|
217
|
+
return {
|
|
218
|
+
active_a2a_continuations: activeCount,
|
|
219
|
+
oldest_active_a2a_age_seconds: activeCount > 0
|
|
220
|
+
? Math.max(0, Math.floor((now - oldestCreatedAt) / 1000))
|
|
221
|
+
: 0,
|
|
222
|
+
terminal_a2a_without_delivery: orphanCount,
|
|
223
|
+
recent_a2a_orphans: recentOrphans,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
if (isMissingTableError(err)) {
|
|
228
|
+
return {
|
|
229
|
+
active_a2a_continuations: 0,
|
|
230
|
+
oldest_active_a2a_age_seconds: 0,
|
|
231
|
+
terminal_a2a_without_delivery: 0,
|
|
232
|
+
recent_a2a_orphans: [],
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
throw err;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function classifyA2AOrphanReason(value) {
|
|
239
|
+
const message = String(value ?? "");
|
|
240
|
+
if (!message)
|
|
241
|
+
return "missing_terminal_delivery";
|
|
242
|
+
if (/timeout|timed out|abort/i.test(message))
|
|
243
|
+
return "timeout";
|
|
244
|
+
if (/token|secret|auth|credential/i.test(message))
|
|
245
|
+
return "authentication";
|
|
246
|
+
if (/database|sql|store|persist/i.test(message))
|
|
247
|
+
return "persistence";
|
|
248
|
+
if (/slack|provider|deliver|stream|response/i.test(message)) {
|
|
249
|
+
return "provider_delivery";
|
|
250
|
+
}
|
|
251
|
+
return "processor_failure";
|
|
252
|
+
}
|
|
147
253
|
//# sourceMappingURL=task-queue-stats.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-queue-stats.js","sourceRoot":"","sources":["../../src/integrations/task-queue-stats.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAgCnE,MAAM,UAAU,GAAmB;IACjC,OAAO,EAAE,CAAC;IACV,UAAU,EAAE,CAAC;IACb,mBAAmB,EAAE,CAAC;IACtB,gBAAgB,EAAE,CAAC;IACnB,0BAA0B,EAAE,CAAC;IAC7B,eAAe,EAAE,EAAE;IACnB,YAAY,EAAE,EAAE;CACjB,CAAC;AAEF,SAAS,mBAAmB,CAAC,GAAY;IACvC,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;IACnE,OAAO,0EAA0E,CAAC,IAAI,CACpF,GAAG,CACJ,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,KAA0B;IAE1B,MAAM,uBAAuB,EAAE,CAAC;IAChC,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,UAAU,GAAG,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACxC,MAAM,QAAQ,GAAG;+EAC4D,CAAC;IAC9E,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,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-only observability helpers for the integration task queue.\n *\n * Lives in its own file so it stays out of `pending-tasks-store.ts`, which is\n * actively being edited by the agent that owns the queue itself. These\n * Queue reads never expose payloads or user text. The helper first runs the\n * additive schema guard so older deployments gain the dispatch diagnostic\n * columns before the SELECTs execute.\n */\nimport { getDbExec } from \"../db/client.js\";\nimport { ensurePendingTasksTable } from \"./pending-tasks-store.js\";\n\nexport interface RecentFailure {\n id: string;\n platform: string;\n error: string;\n attempts: number;\n}\n\nexport interface TaskQueueStats {\n pending: number;\n processing: number;\n completed_last_hour: number;\n failed_last_hour: number;\n oldest_pending_age_seconds: number;\n recent_failures: RecentFailure[];\n recent_tasks: Array<{\n id: string;\n platform: string;\n status: string;\n attempts: number;\n dispatch_attempts: number;\n last_dispatch_outcome: string | null;\n age_seconds: number;\n }>;\n}\n\nexport interface TaskQueueStatsScope {\n ownerEmail: string;\n orgId: string | null;\n}\n\nconst ZERO_STATS: TaskQueueStats = {\n pending: 0,\n processing: 0,\n completed_last_hour: 0,\n failed_last_hour: 0,\n oldest_pending_age_seconds: 0,\n recent_failures: [],\n recent_tasks: [],\n};\n\nfunction isMissingTableError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err ?? \"\");\n return /no such table|does not exist|relation .* does not exist|undefined_table/i.test(\n msg,\n );\n}\n\n/**\n * Get a snapshot of the integration task queue health.\n *\n * Safe to call before the pending-tasks store has initialized the schema.\n */\nexport async function getTaskQueueStats(\n scope: TaskQueueStatsScope,\n): Promise<TaskQueueStats> {\n await ensurePendingTasksTable();\n const client = getDbExec();\n const now = Date.now();\n const oneHourAgo = now - 60 * 60 * 1000;\n const scopeSql = `owner_email = ?\n AND ((org_id IS NULL AND CAST(? AS TEXT) IS NULL) OR org_id = ?)`;\n const scopeArgs = [scope.ownerEmail, scope.orgId, scope.orgId];\n\n try {\n // Status counts (pending, processing) — only need the live ones.\n const liveCounts = await client.execute({\n sql: `SELECT status, COUNT(*) AS c FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status IN ('pending', 'processing')\n GROUP BY status`,\n args: scopeArgs,\n });\n\n let pending = 0;\n let processing = 0;\n for (const row of liveCounts.rows as Array<Record<string, unknown>>) {\n const status = row.status as string;\n const count = Number(row.c ?? 0);\n if (status === \"pending\") pending = count;\n else if (status === \"processing\") processing = count;\n }\n\n // Last-hour completion + failure counts. updated_at is the most reliable\n // column — completed_at can be null on failed tasks, and created_at would\n // miss tasks queued >1h ago that just finished now.\n const lastHourCounts = await client.execute({\n sql: `SELECT status, COUNT(*) AS c FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status IN ('completed', 'failed') AND updated_at >= ?\n GROUP BY status`,\n args: [...scopeArgs, oneHourAgo],\n });\n\n let completedLastHour = 0;\n let failedLastHour = 0;\n for (const row of lastHourCounts.rows as Array<Record<string, unknown>>) {\n const status = row.status as string;\n const count = Number(row.c ?? 0);\n if (status === \"completed\") completedLastHour = count;\n else if (status === \"failed\") failedLastHour = count;\n }\n\n // Oldest pending task — used to surface stuck queues.\n let oldestPendingAgeSeconds = 0;\n if (pending > 0) {\n const oldest = await client.execute({\n sql: `SELECT created_at FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status = 'pending'\n ORDER BY created_at ASC\n LIMIT 1`,\n args: scopeArgs,\n });\n const oldestRow = oldest.rows[0] as Record<string, unknown> | undefined;\n if (oldestRow) {\n const createdAt = Number(oldestRow.created_at ?? now);\n oldestPendingAgeSeconds = Math.max(\n 0,\n Math.floor((now - createdAt) / 1000),\n );\n }\n }\n\n // Recent failures, capped at 5 — enough to spot patterns without\n // blowing up the response payload.\n const failures = await client.execute({\n sql: `SELECT id, platform, error_message, attempts FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status = 'failed' AND updated_at >= ?\n ORDER BY updated_at DESC\n LIMIT 5`,\n args: [...scopeArgs, oneHourAgo],\n });\n const recentFailures: RecentFailure[] = (\n failures.rows as Array<Record<string, unknown>>\n ).map((row) => ({\n id: String(row.id ?? \"\"),\n platform: String(row.platform ?? \"\"),\n error: String(row.error_message ?? \"\"),\n attempts: Number(row.attempts ?? 0),\n }));\n\n const recent = await client.execute({\n sql: `SELECT id, platform, status, attempts, dispatch_attempts,\n last_dispatch_outcome, created_at\n FROM integration_pending_tasks\n WHERE ${scopeSql}\n ORDER BY created_at DESC\n LIMIT 10`,\n args: scopeArgs,\n });\n const recentTasks = (recent.rows as Array<Record<string, unknown>>).map(\n (row) => ({\n id: String(row.id ?? \"\"),\n platform: String(row.platform ?? \"\"),\n status: String(row.status ?? \"\"),\n attempts: Number(row.attempts ?? 0),\n dispatch_attempts: Number(row.dispatch_attempts ?? 0),\n last_dispatch_outcome:\n row.last_dispatch_outcome == null\n ? null\n : String(row.last_dispatch_outcome),\n age_seconds: Math.max(\n 0,\n Math.floor((now - Number(row.created_at ?? now)) / 1000),\n ),\n }),\n );\n\n return {\n pending,\n processing,\n completed_last_hour: completedLastHour,\n failed_last_hour: failedLastHour,\n oldest_pending_age_seconds: oldestPendingAgeSeconds,\n recent_failures: recentFailures,\n recent_tasks: recentTasks,\n };\n } catch (err) {\n if (isMissingTableError(err)) {\n return { ...ZERO_STATS, recent_failures: [], recent_tasks: [] };\n }\n throw err;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"task-queue-stats.js","sourceRoot":"","sources":["../../src/integrations/task-queue-stats.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AA4CnE,MAAM,UAAU,GAAmB;IACjC,OAAO,EAAE,CAAC;IACV,UAAU,EAAE,CAAC;IACb,mBAAmB,EAAE,CAAC;IACtB,gBAAgB,EAAE,CAAC;IACnB,0BAA0B,EAAE,CAAC;IAC7B,iBAAiB,EAAE,CAAC;IACpB,wBAAwB,EAAE,CAAC;IAC3B,6BAA6B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,CAAC;QAAE,OAAO,gBAAgB,CAAC;IAC3E,IAAI,6BAA6B,CAAC,IAAI,CAAC,OAAO,CAAC;QAAE,OAAO,aAAa,CAAC;IACtE,IAAI,yCAAyC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5D,OAAO,mBAAmB,CAAC;IAC7B,CAAC;IACD,OAAO,mBAAmB,CAAC;AAC7B,CAAC","sourcesContent":["/**\n * Read-only observability helpers for the integration task queue.\n *\n * Lives in its own file so it stays out of `pending-tasks-store.ts`, which is\n * actively being edited by the agent that owns the queue itself. These\n * Queue reads never expose payloads or user text. The helper first runs the\n * additive schema guard so older deployments gain the dispatch diagnostic\n * columns before the SELECTs execute.\n */\nimport { getDbExec } from \"../db/client.js\";\nimport { ensureA2AContinuationsTable } from \"./a2a-continuations-store.js\";\nimport { ensurePendingTasksTable } from \"./pending-tasks-store.js\";\n\nexport interface RecentFailure {\n id: string;\n platform: string;\n error: string;\n attempts: number;\n}\n\nexport interface TaskQueueStats {\n pending: number;\n processing: number;\n completed_last_hour: number;\n failed_last_hour: number;\n oldest_pending_age_seconds: number;\n waiting_campaigns: number;\n active_a2a_continuations: number;\n oldest_active_a2a_age_seconds: number;\n terminal_a2a_without_delivery: number;\n recent_a2a_orphans: Array<{\n continuation_id: string;\n integration_task_id: string;\n status: string;\n attempts: number;\n age_seconds: number;\n reason_class: string;\n }>;\n recent_failures: RecentFailure[];\n recent_tasks: Array<{\n id: string;\n platform: string;\n status: string;\n attempts: number;\n dispatch_attempts: number;\n last_dispatch_outcome: string | null;\n age_seconds: number;\n }>;\n}\n\nexport interface TaskQueueStatsScope {\n ownerEmail: string;\n orgId: string | null;\n}\n\nconst ZERO_STATS: TaskQueueStats = {\n pending: 0,\n processing: 0,\n completed_last_hour: 0,\n failed_last_hour: 0,\n oldest_pending_age_seconds: 0,\n waiting_campaigns: 0,\n active_a2a_continuations: 0,\n oldest_active_a2a_age_seconds: 0,\n terminal_a2a_without_delivery: 0,\n recent_a2a_orphans: [],\n recent_failures: [],\n recent_tasks: [],\n};\n\nfunction isMissingTableError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err ?? \"\");\n return /no such table|does not exist|relation .* does not exist|undefined_table/i.test(\n msg,\n );\n}\n\n/**\n * Get a snapshot of the integration task queue health.\n *\n * Safe to call before the pending-tasks store has initialized the schema.\n */\nexport async function getTaskQueueStats(\n scope: TaskQueueStatsScope,\n): Promise<TaskQueueStats> {\n await ensurePendingTasksTable();\n await ensureA2AContinuationsTable();\n const client = getDbExec();\n const now = Date.now();\n const oneHourAgo = now - 60 * 60 * 1000;\n const scopeSql = `owner_email = ?\n AND ((org_id IS NULL AND CAST(? AS TEXT) IS NULL) OR org_id = ?)`;\n const joinedScopeSql = `t.owner_email = ?\n AND ((t.org_id IS NULL AND CAST(? AS TEXT) IS NULL) OR t.org_id = ?)`;\n const scopeArgs = [scope.ownerEmail, scope.orgId, scope.orgId];\n\n try {\n // Status counts (pending, processing) — only need the live ones.\n const liveCounts = await client.execute({\n sql: `SELECT status, COUNT(*) AS c FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status IN ('pending', 'processing')\n GROUP BY status`,\n args: scopeArgs,\n });\n\n let pending = 0;\n let processing = 0;\n for (const row of liveCounts.rows as Array<Record<string, unknown>>) {\n const status = row.status as string;\n const count = Number(row.c ?? 0);\n if (status === \"pending\") pending = count;\n else if (status === \"processing\") processing = count;\n }\n\n // Last-hour completion + failure counts. updated_at is the most reliable\n // column — completed_at can be null on failed tasks, and created_at would\n // miss tasks queued >1h ago that just finished now.\n const lastHourCounts = await client.execute({\n sql: `SELECT status, COUNT(*) AS c FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status IN ('completed', 'failed') AND updated_at >= ?\n GROUP BY status`,\n args: [...scopeArgs, oneHourAgo],\n });\n\n let completedLastHour = 0;\n let failedLastHour = 0;\n for (const row of lastHourCounts.rows as Array<Record<string, unknown>>) {\n const status = row.status as string;\n const count = Number(row.c ?? 0);\n if (status === \"completed\") completedLastHour = count;\n else if (status === \"failed\") failedLastHour = count;\n }\n\n // Oldest pending task — used to surface stuck queues.\n let oldestPendingAgeSeconds = 0;\n if (pending > 0) {\n const oldest = await client.execute({\n sql: `SELECT created_at FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status = 'pending'\n ORDER BY created_at ASC\n LIMIT 1`,\n args: scopeArgs,\n });\n const oldestRow = oldest.rows[0] as Record<string, unknown> | undefined;\n if (oldestRow) {\n const createdAt = Number(oldestRow.created_at ?? now);\n oldestPendingAgeSeconds = Math.max(\n 0,\n Math.floor((now - createdAt) / 1000),\n );\n }\n }\n\n // Recent failures, capped at 5 — enough to spot patterns without\n // blowing up the response payload.\n const failures = await client.execute({\n sql: `SELECT id, platform, error_message, attempts FROM integration_pending_tasks\n WHERE ${scopeSql}\n AND status = 'failed' AND updated_at >= ?\n ORDER BY updated_at DESC\n LIMIT 5`,\n args: [...scopeArgs, oneHourAgo],\n });\n const recentFailures: RecentFailure[] = (\n failures.rows as Array<Record<string, unknown>>\n ).map((row) => ({\n id: String(row.id ?? \"\"),\n platform: String(row.platform ?? \"\"),\n error: String(row.error_message ?? \"\"),\n attempts: Number(row.attempts ?? 0),\n }));\n\n const recent = await client.execute({\n sql: `SELECT id, platform, status, attempts, dispatch_attempts,\n last_dispatch_outcome, created_at\n FROM integration_pending_tasks\n WHERE ${scopeSql}\n ORDER BY created_at DESC\n LIMIT 10`,\n args: scopeArgs,\n });\n const recentTasks = (recent.rows as Array<Record<string, unknown>>).map(\n (row) => ({\n id: String(row.id ?? \"\"),\n platform: String(row.platform ?? \"\"),\n status: String(row.status ?? \"\"),\n attempts: Number(row.attempts ?? 0),\n dispatch_attempts: Number(row.dispatch_attempts ?? 0),\n last_dispatch_outcome:\n row.last_dispatch_outcome == null\n ? null\n : String(row.last_dispatch_outcome),\n age_seconds: Math.max(\n 0,\n Math.floor((now - Number(row.created_at ?? now)) / 1000),\n ),\n }),\n );\n const waitingCampaigns = await readWaitingCampaignCount(\n client,\n joinedScopeSql,\n scopeArgs,\n );\n const a2aStats = await readA2AContinuationStats(\n client,\n joinedScopeSql,\n scopeArgs,\n now,\n );\n\n return {\n pending,\n processing,\n completed_last_hour: completedLastHour,\n failed_last_hour: failedLastHour,\n oldest_pending_age_seconds: oldestPendingAgeSeconds,\n waiting_campaigns: waitingCampaigns,\n ...a2aStats,\n recent_failures: recentFailures,\n recent_tasks: recentTasks,\n };\n } catch (err) {\n if (isMissingTableError(err)) {\n return { ...ZERO_STATS, recent_failures: [], recent_tasks: [] };\n }\n throw err;\n }\n}\n\nasync function readWaitingCampaignCount(\n client: ReturnType<typeof getDbExec>,\n scopeSql: string,\n scopeArgs: Array<string | null>,\n): Promise<number> {\n try {\n const result = await client.execute({\n sql: `SELECT COUNT(*) AS c\n FROM integration_campaigns c\n INNER JOIN integration_pending_tasks t\n ON t.id = c.integration_task_id\n WHERE ${scopeSql}\n AND c.status = 'waiting'`,\n args: scopeArgs,\n });\n return Number(result.rows[0]?.c ?? 0);\n } catch (err) {\n if (isMissingTableError(err)) return 0;\n throw err;\n }\n}\n\nasync function readA2AContinuationStats(\n client: ReturnType<typeof getDbExec>,\n scopeSql: string,\n scopeArgs: Array<string | null>,\n now: number,\n): Promise<\n Pick<\n TaskQueueStats,\n | \"active_a2a_continuations\"\n | \"oldest_active_a2a_age_seconds\"\n | \"terminal_a2a_without_delivery\"\n | \"recent_a2a_orphans\"\n >\n> {\n try {\n const live = await client.execute({\n sql: `SELECT\n COUNT(CASE WHEN c.status IN ('pending', 'processing', 'delivering') THEN 1 END) AS active_count,\n MIN(CASE WHEN c.status IN ('pending', 'processing', 'delivering') THEN c.created_at END) AS oldest_created_at,\n COUNT(CASE WHEN c.status IN ('completed', 'failed')\n AND c.terminal_delivery_confirmed_at IS NULL THEN 1 END) AS orphan_count\n FROM integration_a2a_continuations c\n INNER JOIN integration_pending_tasks t\n ON t.id = c.integration_task_id\n WHERE ${scopeSql}`,\n args: scopeArgs,\n });\n const orphaned = await client.execute({\n sql: `SELECT c.id, c.integration_task_id, c.status, c.attempts,\n c.created_at, c.error_message\n FROM integration_a2a_continuations c\n INNER JOIN integration_pending_tasks t\n ON t.id = c.integration_task_id\n WHERE ${scopeSql}\n AND c.status IN ('completed', 'failed')\n AND c.terminal_delivery_confirmed_at IS NULL\n ORDER BY c.updated_at DESC\n LIMIT 5`,\n args: scopeArgs,\n });\n const activeCount = Number(live.rows[0]?.active_count ?? 0);\n const orphanCount = Number(live.rows[0]?.orphan_count ?? 0);\n const oldestCreatedAt = Number(live.rows[0]?.oldest_created_at ?? now);\n const recentOrphans = (orphaned.rows as Array<Record<string, unknown>>).map(\n (row) => ({\n continuation_id: String(row.id ?? \"\"),\n integration_task_id: String(row.integration_task_id ?? \"\"),\n status: String(row.status ?? \"\"),\n attempts: Number(row.attempts ?? 0),\n age_seconds: Math.max(\n 0,\n Math.floor((now - Number(row.created_at ?? now)) / 1000),\n ),\n reason_class: classifyA2AOrphanReason(row.error_message),\n }),\n );\n return {\n active_a2a_continuations: activeCount,\n oldest_active_a2a_age_seconds:\n activeCount > 0\n ? Math.max(0, Math.floor((now - oldestCreatedAt) / 1000))\n : 0,\n terminal_a2a_without_delivery: orphanCount,\n recent_a2a_orphans: recentOrphans,\n };\n } catch (err) {\n if (isMissingTableError(err)) {\n return {\n active_a2a_continuations: 0,\n oldest_active_a2a_age_seconds: 0,\n terminal_a2a_without_delivery: 0,\n recent_a2a_orphans: [],\n };\n }\n throw err;\n }\n}\n\nfunction classifyA2AOrphanReason(value: unknown): string {\n const message = String(value ?? \"\");\n if (!message) return \"missing_terminal_delivery\";\n if (/timeout|timed out|abort/i.test(message)) return \"timeout\";\n if (/token|secret|auth|credential/i.test(message)) return \"authentication\";\n if (/database|sql|store|persist/i.test(message)) return \"persistence\";\n if (/slack|provider|deliver|stream|response/i.test(message)) {\n return \"provider_delivery\";\n }\n return \"processor_failure\";\n}\n"]}
|
|
@@ -122,6 +122,18 @@ export interface PlatformDeliveryReceipt {
|
|
|
122
122
|
/** Opaque provider message ids/timestamps; never message content. */
|
|
123
123
|
messageRefs?: string[];
|
|
124
124
|
}
|
|
125
|
+
export interface PlatformDeliveryOptions {
|
|
126
|
+
/** Provider-owned message reference that should be updated in place. */
|
|
127
|
+
placeholderRef?: string;
|
|
128
|
+
/** Stable logical delivery key for provider-side retry reconciliation. */
|
|
129
|
+
idempotencyKey?: string;
|
|
130
|
+
/** Earliest provider timestamp (epoch ms) that can contain this delivery. */
|
|
131
|
+
reconcileAfter?: number;
|
|
132
|
+
/** Abort provider I/O before the caller releases its durable delivery claim. */
|
|
133
|
+
signal?: AbortSignal;
|
|
134
|
+
/** Do not fall back to a fresh post if the stable target cannot be updated. */
|
|
135
|
+
strictTargetRef?: boolean;
|
|
136
|
+
}
|
|
125
137
|
/**
|
|
126
138
|
* Proactive outbound message target for a platform.
|
|
127
139
|
* Used when the agent needs to send to a saved destination instead of replying
|
|
@@ -186,12 +198,20 @@ export interface PlatformRunProgress {
|
|
|
186
198
|
* credentials, or provider payload.
|
|
187
199
|
*/
|
|
188
200
|
ref?: PlatformRunProgressRef;
|
|
201
|
+
/** Stable provider message target that can receive the terminal answer. */
|
|
202
|
+
responseTargetRef?: string;
|
|
189
203
|
/** Receive normalized agent events. Implementations should throttle writes. */
|
|
190
|
-
onEvent(event: AgentChatEvent
|
|
204
|
+
onEvent(event: AgentChatEvent, opts?: {
|
|
205
|
+
signal?: AbortSignal;
|
|
206
|
+
}): Promise<void> | void;
|
|
191
207
|
/** Finalize the provider-native progress surface with the answer. */
|
|
192
|
-
complete(message: OutgoingMessage
|
|
208
|
+
complete(message: OutgoingMessage, opts?: {
|
|
209
|
+
signal?: AbortSignal;
|
|
210
|
+
}): Promise<void | PlatformDeliveryReceipt>;
|
|
193
211
|
/** Mark the provider-native surface failed and leave a retryable explanation. */
|
|
194
|
-
fail?(message: string
|
|
212
|
+
fail?(message: string, opts?: {
|
|
213
|
+
signal?: AbortSignal;
|
|
214
|
+
}): Promise<void>;
|
|
195
215
|
}
|
|
196
216
|
/**
|
|
197
217
|
* Safe, minimal reference to a provider-native run-progress surface.
|
|
@@ -284,9 +304,7 @@ export interface PlatformAdapter {
|
|
|
284
304
|
* update that placeholder message rather than posting a new one. Adapters
|
|
285
305
|
* without an "update message" API can ignore the ref and post fresh.
|
|
286
306
|
*/
|
|
287
|
-
sendResponse(message: OutgoingMessage, context: IncomingMessage, opts?:
|
|
288
|
-
placeholderRef?: string;
|
|
289
|
-
}): Promise<void | PlatformDeliveryReceipt>;
|
|
307
|
+
sendResponse(message: OutgoingMessage, context: IncomingMessage, opts?: PlatformDeliveryOptions): Promise<void | PlatformDeliveryReceipt>;
|
|
290
308
|
/**
|
|
291
309
|
* Send a short best-effort system notice to the conversation the incoming
|
|
292
310
|
* message arrived on (polite identity declines, one-time access guidance).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/integrations/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D,MAAM,MAAM,2BAA2B,GACnC,SAAS,GACT,iBAAiB,GACjB,IAAI,GACJ,UAAU,GACV,SAAS,CAAC;AAEd,MAAM,MAAM,sBAAsB,GAAG,SAAS,GAAG,IAAI,GAAG,cAAc,CAAC;AAEvE,MAAM,WAAW,qBAAqB;IACpC,UAAU,EAAE,OAAO,GAAG,OAAO,GAAG,QAAQ,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,CAAC;IAC5E,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,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G,IAAI,CAAC;IACrB,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/integrations/types.ts"],"names":[],"mappings":"AAqOA,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAIhD,QAAQ;IACR,UAAU;IAJZ,IAAI,GAAG,iCAAiC,CAAC;IAElD,YACW,QAAgB,EAChB,UAA6C;QAEtD,KAAK,CAAC,YAAY,QAAQ,qBAAqB,UAAU,EAAE,CAAC,CAAC;wBAHpD,QAAQ;0BACR,UAAU;QAGnB,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IACnD,CAAC;CACF;AAkKD,MAAM,UAAU,wBAAwB,CACtC,OAAwB,EACxB,UAA6C;IAE7C,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE,CAAC;QAChD,MAAM,IAAI,kCAAkC,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC7E,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\n\nimport type { AgentChatEvent } from \"../agent/types.js\";\nimport type { EnvKeyConfig } from \"../server/create-server.js\";\n\nexport type IntegrationConversationType =\n | \"channel\"\n | \"private_channel\"\n | \"dm\"\n | \"group_dm\"\n | \"unknown\";\n\nexport type IntegrationTriggerKind = \"mention\" | \"dm\" | \"thread_reply\";\n\nexport interface IntegrationActorTrust {\n memberType: \"owner\" | \"admin\" | \"member\" | \"guest\" | \"external\" | \"unknown\";\n verified: boolean;\n}\n\nexport interface IntegrationContextMessage {\n senderId?: string;\n senderName?: string;\n text: string;\n timestamp: number;\n sourceUrl?: string;\n reactions?: Array<{ name: string; count: number }>;\n files?: IntegrationFileReference[];\n}\n\nexport interface IntegrationFileReference {\n id: string;\n name?: string;\n mimetype?: string;\n size?: number;\n permalink?: string;\n downloadUrl?: string;\n}\n\n/**\n * Normalized incoming message from any messaging platform.\n */\nexport interface IncomingMessage {\n /** Platform identifier (e.g., \"slack\", \"telegram\", \"whatsapp\") */\n platform: string;\n /** Platform-specific thread/conversation identifier */\n externalThreadId: string;\n /** Message text content */\n text: string;\n /** Display name of the sender */\n senderName?: string;\n /** Verified sender email, when the platform can provide one */\n senderEmail?: string;\n /** Platform-specific sender ID */\n senderId?: string;\n /** How this message intentionally invoked an agent. */\n triggerKind?: IntegrationTriggerKind;\n /** Normalized provider conversation type for policy evaluation. */\n conversationType?: IntegrationConversationType;\n /** Provider tenant/workspace identifier. */\n tenantId?: string;\n /** Authorized integration scope resolved before execution. */\n integrationScopeId?: string;\n /** Normalized actor trust; unknown/unverified callers fail closed. */\n actorTrust?: IntegrationActorTrust;\n /** Bounded provider-native conversation context hydrated at run time. */\n contextMessages?: IntegrationContextMessage[];\n /** Provider file references only. Raw file bodies never belong here. */\n files?: IntegrationFileReference[];\n /** Server-verified approval grants carried by an interaction continuation. */\n approvedToolCalls?: string[];\n /**\n * Whether the platform cryptographically authenticated that the message\n * genuinely came from the claimed sender (e.g. inbound email that passed\n * DKIM, or an aligned SPF pass, for the From domain). Defaults to\n * undefined/false for platforms that don't provide sender authentication.\n *\n * Owner-resolution paths that grant a real user's identity/credentials\n * MUST treat a missing/false value as \"unverified\" and fail closed —\n * never derive a privileged acting identity from an unverified sender.\n */\n senderVerified?: boolean;\n /** Raw platform-specific context needed for routing responses */\n platformContext: Record<string, unknown>;\n /**\n * Short-lived delivery context needed only while the queued task is active.\n * Secrets such as Discord interaction tokens belong here, never in\n * `platformContext`, thread mappings, logs, or agent-visible context.\n */\n responseContext?: Record<string, unknown>;\n /** Provider-native thread/topic reference, when one exists. */\n threadRef?: string;\n /**\n * Canonical provider URL for the originating message thread, when the\n * provider can resolve one. This is safe agent-visible provenance (not a\n * credential) and should be preserved across A2A delegation so created\n * artifacts can link back to their request source.\n */\n sourceUrl?: string;\n /**\n * Trusted app-side routing guidance added after provider parsing. Adapters\n * should not copy this from user-controlled webhook payload fields.\n */\n routingHint?: {\n targetAgent?: string;\n instruction: string;\n };\n /**\n * Trusted app-side note about the caller's identity/visibility tier, set\n * after execution-context resolution (e.g. an anonymous org-scoped Slack\n * member). Surfaced to the agent as integration context. Adapters must not\n * copy this from user-controlled webhook payload fields.\n */\n identityNote?: string;\n /** Provider-native message/activity reference for contextual replies. */\n replyRef?: string;\n /** Message timestamp (epoch ms) */\n timestamp: number;\n}\n\n/**\n * Outgoing message to send back to a messaging platform.\n */\nexport interface OutgoingMessage {\n /** Text content of the response */\n text: string;\n /** Platform-specific payload (e.g., Slack blocks, Telegram parse_mode) */\n platformContext: Record<string, unknown>;\n}\n\n/** Provider-confirmed references for a successfully delivered response. */\nexport interface PlatformDeliveryReceipt {\n status: \"delivered\";\n /** Opaque provider message ids/timestamps; never message content. */\n messageRefs?: string[];\n}\n\n/**\n * Proactive outbound message target for a platform.\n * Used when the agent needs to send to a saved destination instead of replying\n * to the current inbound thread.\n */\nexport interface OutboundTarget {\n /** Canonical platform-specific destination id (channel, chat, thread, etc.) */\n destination: string;\n /** Optional thread reference when the destination supports threading */\n threadRef?: string | null;\n /** Optional fallback display label */\n label?: string;\n /** Provider tenant/workspace used to select an installation credential. */\n tenantId?: string;\n /** Managed installation id when the caller already resolved it. */\n installationId?: string;\n}\n\n/**\n * Connection status for a platform integration.\n */\nexport interface IntegrationStatus {\n platform: string;\n /** Human-readable label (e.g., \"Slack\", \"Telegram\") */\n label: string;\n /** Whether the integration is explicitly enabled */\n enabled: boolean;\n /** Whether all required credentials are configured */\n configured: boolean;\n /** Platform-specific details (workspace name, bot username, etc.) */\n details?: Record<string, unknown>;\n /** Error message if something is wrong */\n error?: string;\n /** The webhook URL that should be configured in the platform */\n webhookUrl?: string;\n /** The full list of env keys (required + optional) the adapter recognizes,\n * including UI hints. Surfaced on the integrations status endpoint so the\n * frontend can render fields without hard-coding them per platform. */\n requiredEnvKeys?: import(\"../server/create-server.js\").EnvKeyConfig[];\n}\n\nexport interface PlatformAdapterCapabilities {\n /** The adapter can deliver a response to the current inbound event. */\n replyText: boolean;\n /** The adapter can send without an active inbound event. */\n proactiveMessages: boolean;\n /** The adapter preserves a provider-native thread or topic reference. */\n nativeThreads: boolean;\n /** The adapter can quote/reply to a specific inbound message. */\n contextualReplies: boolean;\n /** The provider requires an immediate deferred webhook acknowledgement. */\n deferredWebhookResponse: boolean;\n /** The adapter only receives explicit interactions, not ordinary messages. */\n interactionOnly?: boolean;\n /** The adapter can hydrate bounded native thread/file/reaction context. */\n nativeContextHydration?: boolean;\n /** The adapter can surface live agent progress in the provider UI. */\n liveRunProgress?: boolean;\n}\n\nexport interface PlatformRunProgress {\n /**\n * Opaque, provider-owned reference for resuming this progress surface from a\n * durable continuation. It deliberately contains no user content,\n * credentials, or provider payload.\n */\n ref?: PlatformRunProgressRef;\n /** Receive normalized agent events. Implementations should throttle writes. */\n onEvent(event: AgentChatEvent): Promise<void> | void;\n /** Finalize the provider-native progress surface with the answer. */\n complete(message: OutgoingMessage): Promise<void | PlatformDeliveryReceipt>;\n /** Mark the provider-native surface failed and leave a retryable explanation. */\n fail?(message: string): Promise<void>;\n}\n\n/**\n * Safe, minimal reference to a provider-native run-progress surface.\n *\n * The field values are opaque to the framework. Adapters may use `kind` to\n * distinguish their own resume strategy and `streamTs` to identify the\n * provider-side stream. No incoming message text, platform payload, or\n * credential belongs here.\n */\nexport interface PlatformRunProgressRef {\n kind: string;\n streamTs: string;\n}\n\nexport interface ImmediateWebhookResponse {\n status: number;\n body: unknown;\n}\n\nexport class UnsupportedPlatformCapabilityError extends Error {\n readonly code = \"UNSUPPORTED_PLATFORM_CAPABILITY\";\n\n constructor(\n readonly platform: string,\n readonly capability: keyof PlatformAdapterCapabilities,\n ) {\n super(`Platform ${platform} does not support ${capability}`);\n this.name = \"UnsupportedPlatformCapabilityError\";\n }\n}\n\n/**\n * Platform adapter interface — implement this for each messaging platform.\n *\n * Each adapter handles the platform-specific concerns:\n * - Webhook verification (HMAC signatures, challenge responses)\n * - Message parsing (platform events → normalized IncomingMessage)\n * - Response formatting (agent text → platform-specific format)\n * - Response delivery (POST back to platform API)\n */\nexport interface PlatformAdapter {\n /** Unique platform identifier */\n readonly platform: string;\n /** Human-readable label */\n readonly label: string;\n /** Explicit runtime behavior. Missing fields are treated as unsupported. */\n readonly capabilities?: Partial<PlatformAdapterCapabilities>;\n\n /** Env keys this adapter needs (tokens, secrets, etc.) */\n getRequiredEnvKeys(): EnvKeyConfig[];\n\n /**\n * Handle platform-specific verification challenges.\n * For example, Slack sends a `url_verification` event when setting up.\n * Return `{ handled: true, response }` to short-circuit the webhook handler.\n */\n handleVerification(event: H3Event): Promise<{\n handled: boolean;\n response?: unknown;\n }>;\n\n /**\n * Validate the webhook request signature.\n * Returns true if the request is authentic.\n */\n verifyWebhook(event: H3Event): Promise<boolean>;\n\n /**\n * Parse the webhook payload into a normalized IncomingMessage.\n * Return null to silently ignore the event (bot messages, edits, etc.).\n */\n parseIncomingMessage(event: H3Event): Promise<IncomingMessage | null>;\n\n /**\n * Hydrate bounded provider-native context after durable enqueue, outside the\n * provider acknowledgement budget. Implementations must return references,\n * metadata, and text only — never persist file bodies or credentials.\n */\n hydrateIncomingMessage?(incoming: IncomingMessage): Promise<IncomingMessage>;\n\n /**\n * Hydrate only verified sender identity before execution-context selection.\n * This runs on the provider acknowledgement path and must avoid fetching\n * conversation history or file bodies.\n */\n hydrateIncomingIdentity?(incoming: IncomingMessage): Promise<IncomingMessage>;\n\n /**\n * Provider-specific response returned only after a message is verified and\n * durably enqueued. Discord uses this to return a type-5 deferred response\n * within its three-second interaction deadline.\n */\n getImmediateWebhookResponse?(\n incoming: IncomingMessage,\n ): ImmediateWebhookResponse | null;\n\n /**\n * Return pre-canonical thread ids used by older adapter versions. The\n * integration handler checks these only when the canonical mapping is\n * missing, then aliases a match to the canonical id without forking history.\n */\n getLegacyExternalThreadIds?(incoming: IncomingMessage): string[];\n\n /**\n * Send the agent's response back to the messaging platform.\n *\n * If `opts.placeholderRef` is provided (returned earlier by\n * `postProcessingPlaceholder`), adapters that support in-place edits should\n * update that placeholder message rather than posting a new one. Adapters\n * without an \"update message\" API can ignore the ref and post fresh.\n */\n sendResponse(\n message: OutgoingMessage,\n context: IncomingMessage,\n opts?: { placeholderRef?: string },\n ): Promise<void | PlatformDeliveryReceipt>;\n\n /**\n * Send a short best-effort system notice to the conversation the incoming\n * message arrived on (polite identity declines, one-time access guidance).\n * Bypasses agent formatting. When `dedupeKey` is provided, the adapter may\n * drop the notice if the same key was sent recently. Callers must treat\n * failures as non-fatal.\n */\n sendSystemNotice?(\n incoming: IncomingMessage,\n text: string,\n opts?: {\n dedupeKey?: string;\n /** Dedupe window for `dedupeKey`. Adapters pick a default when omitted. */\n dedupeTtlMs?: number;\n },\n ): Promise<void>;\n\n /**\n * Optionally post a \"working on it…\" placeholder message immediately when a\n * webhook arrives, before the agent loop runs. Adapters that support\n * in-place message edits (Slack via `chat.update`, etc.) return an opaque\n * `placeholderRef` that the webhook flow threads through to `sendResponse`\n * so the same message is updated with the final answer once ready.\n *\n * Adapters without edit support should leave this undefined; the webhook\n * handler will skip the placeholder step entirely.\n */\n postProcessingPlaceholder?(\n incoming: IncomingMessage,\n ): Promise<{ placeholderRef: string } | null>;\n\n /** Start a provider-native progress/streaming surface for an agent run. */\n startRunProgress?(\n incoming: IncomingMessage,\n ): Promise<PlatformRunProgress | null>;\n\n /**\n * Reattach a durable continuation to a provider-native progress surface\n * previously started by this adapter. Adapters that cannot resume a native\n * surface should omit this and the continuation will use its normal reply\n * path instead.\n */\n resumeRunProgress?(\n incoming: IncomingMessage,\n ref: PlatformRunProgressRef,\n ): Promise<PlatformRunProgress | null>;\n\n /**\n * Send a proactive outbound message to a platform destination. Adapters that\n * only support direct replies can omit this.\n */\n sendMessageToTarget?(\n message: OutgoingMessage,\n target: OutboundTarget,\n ): Promise<void>;\n\n /**\n * Format plain agent response text into a platform-appropriate message.\n * Handles markdown conversion, message splitting for length limits, etc.\n *\n * `opts.threadDeepLinkUrl`, when present, is a URL back to the originating\n * thread in the dispatch UI. Adapters that support rich blocks should\n * render this as a button (Slack); adapters that don't may inline it as a\n * link or simply omit it.\n */\n formatAgentResponse(\n text: string,\n opts?: { threadDeepLinkUrl?: string },\n ): OutgoingMessage;\n\n /** Return current connection/configuration status for the settings UI. */\n getStatus(baseUrl?: string): Promise<IntegrationStatus>;\n}\n\nexport function assertPlatformCapability(\n adapter: PlatformAdapter,\n capability: keyof PlatformAdapterCapabilities,\n): void {\n if (adapter.capabilities?.[capability] !== true) {\n throw new UnsupportedPlatformCapabilityError(adapter.platform, capability);\n }\n}\n\n/**\n * Options for the integrations plugin.\n */\nexport interface IntegrationsPluginOptions {\n /** App identifier used by call-agent to prevent self-calls (e.g. \"dispatch\"). */\n appId?: string;\n /** Full adapter set to enable. Default: all built-in adapters. */\n adapters?: PlatformAdapter[];\n /** Replace built-in adapters by platform without removing the other defaults. */\n adapterOverrides?: PlatformAdapter[];\n /** System prompt for the agent (same as agent-chat). Inherited from agent-chat plugin if not set. */\n systemPrompt?: string;\n /** Actions registry (same as agent-chat). */\n actions?: Record<string, import(\"../agent/production-agent.js\").ActionEntry>;\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the same engine resolver as web chat. */\n engine?:\n | import(\"../agent/engine/types.js\").AgentEngine\n | string\n | {\n name: string;\n config: Record<string, unknown>;\n };\n /**\n * Resolve which owner should receive personal resource context and own the\n * created chat thread for an incoming platform message.\n */\n resolveOwner?: (incoming: IncomingMessage) => string | Promise<string>;\n /**\n * Resolve the durable execution principal for an inbound provider message.\n * Shared channels should use a service principal; DMs may use a verified\n * linked user. When present this supersedes `resolveOwner`.\n */\n resolveExecutionContext?: (\n incoming: IncomingMessage,\n ) => IntegrationExecutionContext | Promise<IntegrationExecutionContext>;\n /**\n * Explicitly allow an unlinked, verified Slack workspace member to run a DM\n * with the installation organization's shared/service visibility. Disabled\n * by default: DM identity resolution fails closed unless an app deliberately\n * accepts this wider access tier.\n */\n allowAnonymousOrgScopedSlackDm?: boolean;\n /**\n * Optional preprocessor for inbound platform messages. Can intercept special\n * commands (such as `/link`) before the agent loop runs.\n */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nexport interface IntegrationExecutionContext {\n ownerEmail: string;\n orgId: string | null;\n principalType: \"user\" | \"service\";\n installationId?: string;\n scopeId?: string;\n /**\n * True when a hydrated full workspace member could not be matched to an\n * organization member and runs with the anonymous org-scoped service\n * principal (org-wide visibility only, nothing user-private).\n */\n anonymousMember?: boolean;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/integrations/types.ts"],"names":[],"mappings":"AA0PA,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAIhD,QAAQ;IACR,UAAU;IAJZ,IAAI,GAAG,iCAAiC,CAAC;IAElD,YACW,QAAgB,EAChB,UAA6C;QAEtD,KAAK,CAAC,YAAY,QAAQ,qBAAqB,UAAU,EAAE,CAAC,CAAC;wBAHpD,QAAQ;0BACR,UAAU;QAGnB,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IACnD,CAAC;CACF;AAkKD,MAAM,UAAU,wBAAwB,CACtC,OAAwB,EACxB,UAA6C;IAE7C,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE,CAAC;QAChD,MAAM,IAAI,kCAAkC,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC7E,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\n\nimport type { AgentChatEvent } from \"../agent/types.js\";\nimport type { EnvKeyConfig } from \"../server/create-server.js\";\n\nexport type IntegrationConversationType =\n | \"channel\"\n | \"private_channel\"\n | \"dm\"\n | \"group_dm\"\n | \"unknown\";\n\nexport type IntegrationTriggerKind = \"mention\" | \"dm\" | \"thread_reply\";\n\nexport interface IntegrationActorTrust {\n memberType: \"owner\" | \"admin\" | \"member\" | \"guest\" | \"external\" | \"unknown\";\n verified: boolean;\n}\n\nexport interface IntegrationContextMessage {\n senderId?: string;\n senderName?: string;\n text: string;\n timestamp: number;\n sourceUrl?: string;\n reactions?: Array<{ name: string; count: number }>;\n files?: IntegrationFileReference[];\n}\n\nexport interface IntegrationFileReference {\n id: string;\n name?: string;\n mimetype?: string;\n size?: number;\n permalink?: string;\n downloadUrl?: string;\n}\n\n/**\n * Normalized incoming message from any messaging platform.\n */\nexport interface IncomingMessage {\n /** Platform identifier (e.g., \"slack\", \"telegram\", \"whatsapp\") */\n platform: string;\n /** Platform-specific thread/conversation identifier */\n externalThreadId: string;\n /** Message text content */\n text: string;\n /** Display name of the sender */\n senderName?: string;\n /** Verified sender email, when the platform can provide one */\n senderEmail?: string;\n /** Platform-specific sender ID */\n senderId?: string;\n /** How this message intentionally invoked an agent. */\n triggerKind?: IntegrationTriggerKind;\n /** Normalized provider conversation type for policy evaluation. */\n conversationType?: IntegrationConversationType;\n /** Provider tenant/workspace identifier. */\n tenantId?: string;\n /** Authorized integration scope resolved before execution. */\n integrationScopeId?: string;\n /** Normalized actor trust; unknown/unverified callers fail closed. */\n actorTrust?: IntegrationActorTrust;\n /** Bounded provider-native conversation context hydrated at run time. */\n contextMessages?: IntegrationContextMessage[];\n /** Provider file references only. Raw file bodies never belong here. */\n files?: IntegrationFileReference[];\n /** Server-verified approval grants carried by an interaction continuation. */\n approvedToolCalls?: string[];\n /**\n * Whether the platform cryptographically authenticated that the message\n * genuinely came from the claimed sender (e.g. inbound email that passed\n * DKIM, or an aligned SPF pass, for the From domain). Defaults to\n * undefined/false for platforms that don't provide sender authentication.\n *\n * Owner-resolution paths that grant a real user's identity/credentials\n * MUST treat a missing/false value as \"unverified\" and fail closed —\n * never derive a privileged acting identity from an unverified sender.\n */\n senderVerified?: boolean;\n /** Raw platform-specific context needed for routing responses */\n platformContext: Record<string, unknown>;\n /**\n * Short-lived delivery context needed only while the queued task is active.\n * Secrets such as Discord interaction tokens belong here, never in\n * `platformContext`, thread mappings, logs, or agent-visible context.\n */\n responseContext?: Record<string, unknown>;\n /** Provider-native thread/topic reference, when one exists. */\n threadRef?: string;\n /**\n * Canonical provider URL for the originating message thread, when the\n * provider can resolve one. This is safe agent-visible provenance (not a\n * credential) and should be preserved across A2A delegation so created\n * artifacts can link back to their request source.\n */\n sourceUrl?: string;\n /**\n * Trusted app-side routing guidance added after provider parsing. Adapters\n * should not copy this from user-controlled webhook payload fields.\n */\n routingHint?: {\n targetAgent?: string;\n instruction: string;\n };\n /**\n * Trusted app-side note about the caller's identity/visibility tier, set\n * after execution-context resolution (e.g. an anonymous org-scoped Slack\n * member). Surfaced to the agent as integration context. Adapters must not\n * copy this from user-controlled webhook payload fields.\n */\n identityNote?: string;\n /** Provider-native message/activity reference for contextual replies. */\n replyRef?: string;\n /** Message timestamp (epoch ms) */\n timestamp: number;\n}\n\n/**\n * Outgoing message to send back to a messaging platform.\n */\nexport interface OutgoingMessage {\n /** Text content of the response */\n text: string;\n /** Platform-specific payload (e.g., Slack blocks, Telegram parse_mode) */\n platformContext: Record<string, unknown>;\n}\n\n/** Provider-confirmed references for a successfully delivered response. */\nexport interface PlatformDeliveryReceipt {\n status: \"delivered\";\n /** Opaque provider message ids/timestamps; never message content. */\n messageRefs?: string[];\n}\n\nexport interface PlatformDeliveryOptions {\n /** Provider-owned message reference that should be updated in place. */\n placeholderRef?: string;\n /** Stable logical delivery key for provider-side retry reconciliation. */\n idempotencyKey?: string;\n /** Earliest provider timestamp (epoch ms) that can contain this delivery. */\n reconcileAfter?: number;\n /** Abort provider I/O before the caller releases its durable delivery claim. */\n signal?: AbortSignal;\n /** Do not fall back to a fresh post if the stable target cannot be updated. */\n strictTargetRef?: boolean;\n}\n\n/**\n * Proactive outbound message target for a platform.\n * Used when the agent needs to send to a saved destination instead of replying\n * to the current inbound thread.\n */\nexport interface OutboundTarget {\n /** Canonical platform-specific destination id (channel, chat, thread, etc.) */\n destination: string;\n /** Optional thread reference when the destination supports threading */\n threadRef?: string | null;\n /** Optional fallback display label */\n label?: string;\n /** Provider tenant/workspace used to select an installation credential. */\n tenantId?: string;\n /** Managed installation id when the caller already resolved it. */\n installationId?: string;\n}\n\n/**\n * Connection status for a platform integration.\n */\nexport interface IntegrationStatus {\n platform: string;\n /** Human-readable label (e.g., \"Slack\", \"Telegram\") */\n label: string;\n /** Whether the integration is explicitly enabled */\n enabled: boolean;\n /** Whether all required credentials are configured */\n configured: boolean;\n /** Platform-specific details (workspace name, bot username, etc.) */\n details?: Record<string, unknown>;\n /** Error message if something is wrong */\n error?: string;\n /** The webhook URL that should be configured in the platform */\n webhookUrl?: string;\n /** The full list of env keys (required + optional) the adapter recognizes,\n * including UI hints. Surfaced on the integrations status endpoint so the\n * frontend can render fields without hard-coding them per platform. */\n requiredEnvKeys?: import(\"../server/create-server.js\").EnvKeyConfig[];\n}\n\nexport interface PlatformAdapterCapabilities {\n /** The adapter can deliver a response to the current inbound event. */\n replyText: boolean;\n /** The adapter can send without an active inbound event. */\n proactiveMessages: boolean;\n /** The adapter preserves a provider-native thread or topic reference. */\n nativeThreads: boolean;\n /** The adapter can quote/reply to a specific inbound message. */\n contextualReplies: boolean;\n /** The provider requires an immediate deferred webhook acknowledgement. */\n deferredWebhookResponse: boolean;\n /** The adapter only receives explicit interactions, not ordinary messages. */\n interactionOnly?: boolean;\n /** The adapter can hydrate bounded native thread/file/reaction context. */\n nativeContextHydration?: boolean;\n /** The adapter can surface live agent progress in the provider UI. */\n liveRunProgress?: boolean;\n}\n\nexport interface PlatformRunProgress {\n /**\n * Opaque, provider-owned reference for resuming this progress surface from a\n * durable continuation. It deliberately contains no user content,\n * credentials, or provider payload.\n */\n ref?: PlatformRunProgressRef;\n /** Stable provider message target that can receive the terminal answer. */\n responseTargetRef?: string;\n /** Receive normalized agent events. Implementations should throttle writes. */\n onEvent(\n event: AgentChatEvent,\n opts?: { signal?: AbortSignal },\n ): Promise<void> | void;\n /** Finalize the provider-native progress surface with the answer. */\n complete(\n message: OutgoingMessage,\n opts?: { signal?: AbortSignal },\n ): Promise<void | PlatformDeliveryReceipt>;\n /** Mark the provider-native surface failed and leave a retryable explanation. */\n fail?(message: string, opts?: { signal?: AbortSignal }): Promise<void>;\n}\n\n/**\n * Safe, minimal reference to a provider-native run-progress surface.\n *\n * The field values are opaque to the framework. Adapters may use `kind` to\n * distinguish their own resume strategy and `streamTs` to identify the\n * provider-side stream. No incoming message text, platform payload, or\n * credential belongs here.\n */\nexport interface PlatformRunProgressRef {\n kind: string;\n streamTs: string;\n}\n\nexport interface ImmediateWebhookResponse {\n status: number;\n body: unknown;\n}\n\nexport class UnsupportedPlatformCapabilityError extends Error {\n readonly code = \"UNSUPPORTED_PLATFORM_CAPABILITY\";\n\n constructor(\n readonly platform: string,\n readonly capability: keyof PlatformAdapterCapabilities,\n ) {\n super(`Platform ${platform} does not support ${capability}`);\n this.name = \"UnsupportedPlatformCapabilityError\";\n }\n}\n\n/**\n * Platform adapter interface — implement this for each messaging platform.\n *\n * Each adapter handles the platform-specific concerns:\n * - Webhook verification (HMAC signatures, challenge responses)\n * - Message parsing (platform events → normalized IncomingMessage)\n * - Response formatting (agent text → platform-specific format)\n * - Response delivery (POST back to platform API)\n */\nexport interface PlatformAdapter {\n /** Unique platform identifier */\n readonly platform: string;\n /** Human-readable label */\n readonly label: string;\n /** Explicit runtime behavior. Missing fields are treated as unsupported. */\n readonly capabilities?: Partial<PlatformAdapterCapabilities>;\n\n /** Env keys this adapter needs (tokens, secrets, etc.) */\n getRequiredEnvKeys(): EnvKeyConfig[];\n\n /**\n * Handle platform-specific verification challenges.\n * For example, Slack sends a `url_verification` event when setting up.\n * Return `{ handled: true, response }` to short-circuit the webhook handler.\n */\n handleVerification(event: H3Event): Promise<{\n handled: boolean;\n response?: unknown;\n }>;\n\n /**\n * Validate the webhook request signature.\n * Returns true if the request is authentic.\n */\n verifyWebhook(event: H3Event): Promise<boolean>;\n\n /**\n * Parse the webhook payload into a normalized IncomingMessage.\n * Return null to silently ignore the event (bot messages, edits, etc.).\n */\n parseIncomingMessage(event: H3Event): Promise<IncomingMessage | null>;\n\n /**\n * Hydrate bounded provider-native context after durable enqueue, outside the\n * provider acknowledgement budget. Implementations must return references,\n * metadata, and text only — never persist file bodies or credentials.\n */\n hydrateIncomingMessage?(incoming: IncomingMessage): Promise<IncomingMessage>;\n\n /**\n * Hydrate only verified sender identity before execution-context selection.\n * This runs on the provider acknowledgement path and must avoid fetching\n * conversation history or file bodies.\n */\n hydrateIncomingIdentity?(incoming: IncomingMessage): Promise<IncomingMessage>;\n\n /**\n * Provider-specific response returned only after a message is verified and\n * durably enqueued. Discord uses this to return a type-5 deferred response\n * within its three-second interaction deadline.\n */\n getImmediateWebhookResponse?(\n incoming: IncomingMessage,\n ): ImmediateWebhookResponse | null;\n\n /**\n * Return pre-canonical thread ids used by older adapter versions. The\n * integration handler checks these only when the canonical mapping is\n * missing, then aliases a match to the canonical id without forking history.\n */\n getLegacyExternalThreadIds?(incoming: IncomingMessage): string[];\n\n /**\n * Send the agent's response back to the messaging platform.\n *\n * If `opts.placeholderRef` is provided (returned earlier by\n * `postProcessingPlaceholder`), adapters that support in-place edits should\n * update that placeholder message rather than posting a new one. Adapters\n * without an \"update message\" API can ignore the ref and post fresh.\n */\n sendResponse(\n message: OutgoingMessage,\n context: IncomingMessage,\n opts?: PlatformDeliveryOptions,\n ): Promise<void | PlatformDeliveryReceipt>;\n\n /**\n * Send a short best-effort system notice to the conversation the incoming\n * message arrived on (polite identity declines, one-time access guidance).\n * Bypasses agent formatting. When `dedupeKey` is provided, the adapter may\n * drop the notice if the same key was sent recently. Callers must treat\n * failures as non-fatal.\n */\n sendSystemNotice?(\n incoming: IncomingMessage,\n text: string,\n opts?: {\n dedupeKey?: string;\n /** Dedupe window for `dedupeKey`. Adapters pick a default when omitted. */\n dedupeTtlMs?: number;\n },\n ): Promise<void>;\n\n /**\n * Optionally post a \"working on it…\" placeholder message immediately when a\n * webhook arrives, before the agent loop runs. Adapters that support\n * in-place message edits (Slack via `chat.update`, etc.) return an opaque\n * `placeholderRef` that the webhook flow threads through to `sendResponse`\n * so the same message is updated with the final answer once ready.\n *\n * Adapters without edit support should leave this undefined; the webhook\n * handler will skip the placeholder step entirely.\n */\n postProcessingPlaceholder?(\n incoming: IncomingMessage,\n ): Promise<{ placeholderRef: string } | null>;\n\n /** Start a provider-native progress/streaming surface for an agent run. */\n startRunProgress?(\n incoming: IncomingMessage,\n ): Promise<PlatformRunProgress | null>;\n\n /**\n * Reattach a durable continuation to a provider-native progress surface\n * previously started by this adapter. Adapters that cannot resume a native\n * surface should omit this and the continuation will use its normal reply\n * path instead.\n */\n resumeRunProgress?(\n incoming: IncomingMessage,\n ref: PlatformRunProgressRef,\n ): Promise<PlatformRunProgress | null>;\n\n /**\n * Send a proactive outbound message to a platform destination. Adapters that\n * only support direct replies can omit this.\n */\n sendMessageToTarget?(\n message: OutgoingMessage,\n target: OutboundTarget,\n ): Promise<void>;\n\n /**\n * Format plain agent response text into a platform-appropriate message.\n * Handles markdown conversion, message splitting for length limits, etc.\n *\n * `opts.threadDeepLinkUrl`, when present, is a URL back to the originating\n * thread in the dispatch UI. Adapters that support rich blocks should\n * render this as a button (Slack); adapters that don't may inline it as a\n * link or simply omit it.\n */\n formatAgentResponse(\n text: string,\n opts?: { threadDeepLinkUrl?: string },\n ): OutgoingMessage;\n\n /** Return current connection/configuration status for the settings UI. */\n getStatus(baseUrl?: string): Promise<IntegrationStatus>;\n}\n\nexport function assertPlatformCapability(\n adapter: PlatformAdapter,\n capability: keyof PlatformAdapterCapabilities,\n): void {\n if (adapter.capabilities?.[capability] !== true) {\n throw new UnsupportedPlatformCapabilityError(adapter.platform, capability);\n }\n}\n\n/**\n * Options for the integrations plugin.\n */\nexport interface IntegrationsPluginOptions {\n /** App identifier used by call-agent to prevent self-calls (e.g. \"dispatch\"). */\n appId?: string;\n /** Full adapter set to enable. Default: all built-in adapters. */\n adapters?: PlatformAdapter[];\n /** Replace built-in adapters by platform without removing the other defaults. */\n adapterOverrides?: PlatformAdapter[];\n /** System prompt for the agent (same as agent-chat). Inherited from agent-chat plugin if not set. */\n systemPrompt?: string;\n /** Actions registry (same as agent-chat). */\n actions?: Record<string, import(\"../agent/production-agent.js\").ActionEntry>;\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the same engine resolver as web chat. */\n engine?:\n | import(\"../agent/engine/types.js\").AgentEngine\n | string\n | {\n name: string;\n config: Record<string, unknown>;\n };\n /**\n * Resolve which owner should receive personal resource context and own the\n * created chat thread for an incoming platform message.\n */\n resolveOwner?: (incoming: IncomingMessage) => string | Promise<string>;\n /**\n * Resolve the durable execution principal for an inbound provider message.\n * Shared channels should use a service principal; DMs may use a verified\n * linked user. When present this supersedes `resolveOwner`.\n */\n resolveExecutionContext?: (\n incoming: IncomingMessage,\n ) => IntegrationExecutionContext | Promise<IntegrationExecutionContext>;\n /**\n * Explicitly allow an unlinked, verified Slack workspace member to run a DM\n * with the installation organization's shared/service visibility. Disabled\n * by default: DM identity resolution fails closed unless an app deliberately\n * accepts this wider access tier.\n */\n allowAnonymousOrgScopedSlackDm?: boolean;\n /**\n * Optional preprocessor for inbound platform messages. Can intercept special\n * commands (such as `/link`) before the agent loop runs.\n */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nexport interface IntegrationExecutionContext {\n ownerEmail: string;\n orgId: string | null;\n principalType: \"user\" | \"service\";\n installationId?: string;\n scopeId?: string;\n /**\n * True when a hydrated full workspace member could not be matched to an\n * organization member and runs with the anonymous org-scoped service\n * principal (org-wide visibility only, nothing user-private).\n */\n anonymousMember?: boolean;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,EAIL,KAAK,mBAAmB,EAEzB,MAAM,6BAA6B,CAAC;AAerC,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAOL,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,EAIL,KAAK,mBAAmB,EAEzB,MAAM,6BAA6B,CAAC;AAerC,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAOL,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AA2DtC,OAAO,EAIL,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAC;AAGlC,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,eAAe,EACf,uBAAuB,EAExB,MAAM,YAAY,CAAC;AA8FpB,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mBAAmB,CAAC;IAC1B,QAAQ,EAAE,eAAe,CAAC;IAC1B,OAAO,EAAE,eAAe,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB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EAAE,uBAAuB,GAC/B,OAAO,CAAC,IAAI,CAAC,CAsEf"}
|
|
@@ -20,7 +20,8 @@ import { canUseDeployCredentialFallbackForRequest, readDeployCredentialEnv, } fr
|
|
|
20
20
|
import { runWithRequestContext } from "../server/request-context.js";
|
|
21
21
|
import { normalizeReasoningEffortForRequest } from "../shared/reasoning-effort.js";
|
|
22
22
|
import { A2A_CONTINUATION_QUEUED_MARKER } from "./a2a-continuation-marker.js";
|
|
23
|
-
import {
|
|
23
|
+
import { reconcileTerminalA2AParentIfDisabled } from "./a2a-continuation-processor.js";
|
|
24
|
+
import { getA2AContinuationTaskOutcome } from "./a2a-continuations-store.js";
|
|
24
25
|
import { clearIntegrationAwaitingInput, setIntegrationAwaitingInput, } from "./awaiting-input-store.js";
|
|
25
26
|
import { claimIntegrationCampaignDeliveryForTask, claimIntegrationCampaign, completeIntegrationCampaignTask, createIntegrationCampaign, failIntegrationCampaign, heartbeatIntegrationCampaign, scheduleNextIntegrationCampaign, waitForA2AIntegrationCampaign, } from "./integration-campaigns-store.js";
|
|
26
27
|
import { dispatchPendingIntegrationTask, integrationDispatchScopeValue, } from "./integration-durable-dispatch.js";
|
|
@@ -713,8 +714,16 @@ async function processIncomingMessage(incoming, options, opts = {}) {
|
|
|
713
714
|
}
|
|
714
715
|
catch { }
|
|
715
716
|
if (waitingForA2A) {
|
|
716
|
-
const
|
|
717
|
-
if (
|
|
717
|
+
const a2aOutcome = await getA2AContinuationTaskOutcome(opts.taskId);
|
|
718
|
+
if (a2aOutcome !== "terminal-delivered") {
|
|
719
|
+
if (a2aOutcome === "terminal-without-delivery" &&
|
|
720
|
+
(await reconcileTerminalA2AParentIfDisabled(opts.taskId))) {
|
|
721
|
+
await releaseApplicableIntegrationBudgets(budgetReservations.reservations);
|
|
722
|
+
return { status: "campaign-failed" };
|
|
723
|
+
}
|
|
724
|
+
if (a2aOutcome !== "active") {
|
|
725
|
+
console.warn(`[integrations] Waiting campaign ${campaign.row.id} has A2A outcome ${a2aOutcome} without terminal delivery proof`);
|
|
726
|
+
}
|
|
718
727
|
const waiting = await waitForA2AIntegrationCampaign(campaign.row.id, {
|
|
719
728
|
runId: campaign.runId,
|
|
720
729
|
leaseToken: campaign.leaseToken,
|