Skip to content

Commit 64f5e64

Browse files
author
hzq
committed
Capture outbound webhooks with their source checkpoints
Bind recipients and their permitted payload before commit. Recover delayed fanout and retry local storage writes without replaying the agent or spending the receiver's retry budget.
1 parent e5a6eb9 commit 64f5e64

21 files changed

Lines changed: 1240 additions & 289 deletions

‎docs/stability.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ What grows with use, and what bounds it:
192192
| Runs, events, steps, approvals, output baselines, run summaries, per-run key usage rows, webhook approval announcements | `state.sqlite` | `retention.runsDays` / `oaa prune` |
193193
| Artifacts (files produced by runs) | `files` table + `<dataDir>/files/` | deleted with their run |
194194
| Uploaded files, including stored image inputs | `files` table + `<dataDir>/files/` | `oaa prune` when older than the cutoff and not listed by a kept run (image inputs are listed in their run's `fileIds`); the per-caller stored-bytes quota counts these rows, so it drops after a prune |
195-
| Webhook deliveries | `webhook_deliveries` | the last 200 finished per endpoint; at most 10,000 waiting per endpoint |
195+
| Webhook deliveries and recoverable notifications | `webhook_deliveries`, `webhook_outbox` | at most 200 finished deliveries per endpoint; at most 10,000 waiting across both tables per endpoint |
196196
| Session workspaces of the local worker | `<worker dataDir>/sessions/` | `oaa prune` when no run of the session remains and the folder is older than the cutoff |
197197
| Audit events | `audit_events` | kept per owner up to a fixed count (existing) |
198198
| Portal sessions | `platform_sessions` | expire after `platform.sessionTtlHours` (existing) |

‎docs/webhooks.md‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,15 +95,14 @@ The request body is JSON:
9595
- `data.key_id` and `data.subject` identify the key that started the run and its caller partition
9696
(`key:<id>`, or `acct:<id>` for a developer-platform account).
9797
- `pending_actions` appears only on `run.requires_action`. `type` is `tool`, `native`, `reconcile` or
98-
`client_tool` (a tool result the caller has to send back). `status` is the item's state when the
99-
body was built (normally `pending`).
98+
`client_tool` (a tool result the caller has to send back). `status` is its state at the source checkpoint.
10099
- **The task input and the output text are not included** (privacy and size). An endpoint created with
101100
`include_output: true` gets `data.output = {text, truncated, bytes}` on run events: the final output
102101
text, cut to at most 32 KiB of UTF-8 (`truncated: true` and the full size in `bytes` when cut).
103102
- For anything else, read the run with its ID: `GET /v1/runs/{id}`, `GET /v1/runs/{id}/output`,
104103
`GET /v1/runs/{id}/actions`.
105104

106-
The body is built at the first delivery attempt and then fixed: retries send the same bytes.
105+
New events capture their recipients and bounded run data at the source checkpoint. Pruning the run before the first POST does not destroy that snapshot. The first attempt fixes the exact body bytes for retries. Later opt-in never adds output to a past event. Withdrawing output before the first attempt redacts it; a retry whose fixed bytes contain withdrawn output fails as `subscription_changed` instead of sending them. Changing the URL or removing the matching event/agent also prevents delivery to the changed subscription. Secret rotation uses the current key.
107106

108107
## Signature and headers
109108

@@ -162,7 +161,7 @@ def verify(secret: str, header: str, raw_body: bytes, tolerance: int = 300) -> b
162161
- **At least once.** Events are queued in the gateway's SQLite database (`webhook_deliveries`) and
163162
survive a restart; whatever was not delivered when the gateway stopped is sent after it starts
164163
again. A receiver may see a delivery more than once; de-duplicate on `X-OAA-Delivery`.
165-
- The approval announcement and the queued deliveries for its matching endpoints commit together. A failed queue write leaves no partial announcement, so observing the notification again can enqueue it. The delivery guarantee starts **after enqueue**; a gateway exit between the source commit and the outbound observer is not covered for every event type.
164+
- For all six subscribed run events, the source transaction commits the fanout or durable recovery rows. A crash before the sender wakes does not lose a committed event. If the delivery-table write fails, the gateway retries the recorded fanout automatically, including after restart. If neither local write can commit, the source checkpoint fails rather than claiming success. If even the failure outcome cannot be recorded, the active execution retries only that final write, not the agent or its tools. Restart recovery uses the last committed run state.
166165
- **Success** is any `2xx` answer within **10 seconds** (connect, send and answer together).
167166
Redirects are not followed; a `3xx` counts as a failure. Answer fast and do the work afterwards.
168167
- **Retries.** A failed attempt is retried after about 5 s, 30 s, 2 min, 10 min and 30 min (each ±20 %
@@ -172,15 +171,13 @@ def verify(secret: str, header: str, raw_body: bytes, tolerance: int = 300) -> b
172171
- **Order.** Deliveries to one endpoint go out one at a time, oldest first, so a receiver sees the
173172
events of an endpoint in order; a delivery waiting for its retry holds back the later ones of the
174173
same endpoint. Different endpoints do not wait for each other.
175-
- **Never in the way of a run.** Queuing an event is one small insert after the run's status is
176-
committed, and happens only when a matching endpoint exists. Sending happens in the background; a
177-
slow or dead receiver does not delay or block any run.
174+
- **No network I/O in a checkpoint.** Only SQLite work is on the source commit path. Sending happens in the background; the run does not wait for the receiver.
178175
- **Failing endpoints** are not deleted or disabled automatically. The endpoint's `status` shows
179176
`state: "failing"`, `consecutive_failures`, the last error and how many deliveries are queued.
180177
- A disabled endpoint (`enabled: false`) gets no new events; deliveries already queued for it wait until
181178
it is enabled again. Deleting an endpoint deletes its queued deliveries.
182179
- The last 200 finished deliveries per endpoint are kept.
183-
- At most 10,000 deliveries wait per endpoint. Above that (an endpoint that keeps failing while events keep coming) the oldest waiting deliveries after the one in progress are marked `failed` with `queue_overflow` and dropped, so a broken receiver cannot grow the database without bound.
180+
- At most 10,000 pending items per endpoint, including recovery rows. Overflow preserves the queue head; discarded items count toward `overflow_total`. Materialized overflow deliveries are marked `failed` with `queue_overflow`. A recovery row discarded before materialization has no delivery ID.
184181
185182
## Outbound safety
186183
@@ -218,12 +215,12 @@ All endpoints need an owner-wide admin key; other keys get 403 `scope_denied`.
218215
| `POST /v1/webhooks/{id}/rotate-secret` | `{id, secret}`; the old secret stops working at once |
219216
| `POST /v1/webhooks/{id}/test` | 202 delivery; queues a `webhook.test` event |
220217
| `GET /v1/webhooks/{id}/deliveries?limit=20` | `{data: [delivery]}`, newest first (at most 200) |
221-
| `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` | 202 delivery; 409 `webhook_delivery_pending` while it is still queued |
218+
| `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` | 202 delivery; 409 `webhook_delivery_pending` while it is still queued; 429 `queue_full` when no queue capacity remains |
222219
223220
An **endpoint** is `{object: "webhook_endpoint", id, url, events, agents, include_output, enabled,
224221
description, allow_insecure_http, allow_private_network, created_at, updated_at, status}` with
225222
`status = {state: "ok" | "failing" | "disabled", consecutive_failures, last_success_at, last_failure_at,
226-
last_error, pending, latest_delivery}`. Times are Unix milliseconds, as elsewhere in the management API.
223+
last_error, pending, capture_pending, oldest_pending_at, overflow_total, latest_delivery}`. `pending` includes `capture_pending` (recorded but not yet materialized). `oldest_pending_at` is null when empty; `overflow_total` counts evictions since the upgrade. Times are Unix milliseconds, as elsewhere in the management API.
227224
228225
A **delivery** is `{object: "webhook_delivery", id, endpoint_id, event_id, event_type, run_id, status:
229226
"pending" | "succeeded" | "failed", attempts, next_attempt_at, http_status, duration_ms, last_error,
@@ -317,8 +314,6 @@ handles.
317314
- HTTPS endpoints are verified against the certificate authorities trusted by Node.js. The automated
318315
tests only use local plain-http receivers; delivery to a real public HTTPS endpoint goes through the
319316
same code but is not covered by them.
320-
- `run.interrupted` for runs interrupted while the gateway shuts down or restarts is queued either at
321-
shutdown or when the gateway starts again (runs interrupted since the process started), and sent
322-
once.
317+
- Capture is installed before startup recovery and remains attached through shutdown checkpoints. Earlier pending deliveries continue using their stored body or original seed. Upgrading does not reconstruct events that an older version never recorded or replay history to new endpoints.
323318
- Several gateway processes sharing one data directory are not supported (as for the rest of the
324319
gateway); each would send the queue.

‎docs/zh-CN/stability.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
104104
| 运行、事件、步骤、审批、输出基线、运行摘要、每运行的密钥用量行、事件回调的审批通告 | `state.sqlite` | `retention.runsDays` / `oaa prune` |
105105
| 产物(运行生成的文件) | `files` 表 + `<dataDir>/files/` | 随运行一起删除 |
106106
| 上传文件,含存下的图片输入 | `files` 表 + `<dataDir>/files/` | 早于截止时间且没有被保留的运行列出时由 `oaa prune` 删除(图片输入列在所属运行的 `fileIds` 里);每调用方的存储字节配额按这些行计算,所以清理后会相应下降 |
107-
| 事件回调投递记录 | `webhook_deliveries` | 每个端点保留最近 200 条已结束的;每个端点最多 10,000 条排队 |
107+
| 事件回调投递和待恢复的通知 | `webhook_deliveries`、`webhook_outbox` | 每个端点最多保留 200 条已结束的投递;两张表合计最多 10,000 条排队 |
108108
| 本机执行节点的会话工作区 | `<worker dataDir>/sessions/` | 会话已没有任何运行且目录早于截止时间时由 `oaa prune` 删除 |
109109
| 审计记录 | `audit_events` | 按所有者保留固定条数(原有机制) |
110110
| 门户会话 | `platform_sessions` | 按 `platform.sessionTtlHours` 过期(原有机制) |

‎docs/zh-CN/webhooks.md‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,11 @@
8080
- `created_at`、`data.created_at`、`data.updated_at`、`expires_at` 都是 Unix 秒。
8181
- `data.error` 是 `{code, message}` 或 `null`;`data.usage` 是 `{input_tokens, output_tokens, total_tokens}` 或 `null`(未知)。
8282
- `data.key_id` 与 `data.subject` 标明发起运行的密钥与调用方分区(`key:<编号>`,开发者平台账号是 `acct:<编号>`)。
83-
- `pending_actions` 只出现在 `run.requires_action` 里。`type` 为 `tool`、`native`、`reconcile` 或 `client_tool`(需要调用方回传的工具结果)。`status` 是构造请求体时该项的状态(通常是 `pending`)。
83+
- `pending_actions` 只出现在 `run.requires_action` 里。`type` 为 `tool`、`native`、`reconcile` 或 `client_tool`(需要调用方回传的工具结果)。`status` 是源任务提交检查点时该项的状态。
8484
- **默认不带任务输入与输出正文**(隐私与体积)。端点设了 `include_output: true` 时,运行事件里多一个 `data.output = {text, truncated, bytes}`:最终输出文本,最多 32 KiB(UTF-8);被截断时 `truncated: true`,`bytes` 是完整大小。
8585
- 需要更多信息时用运行编号去查:`GET /v1/runs/{id}`、`GET /v1/runs/{id}/output`、`GET /v1/runs/{id}/actions`。
8686

87-
请求体在第一次投递时构造,之后固定不变:重试发送的是同样的字节。
87+
新事件在源任务提交时固定接收端和有界的运行摘要。首次 POST 前清理源任务不影响投递。第一次发送时固定正文,重试沿用相同字节。后来启用输出不会给旧事件增加输出;首次发送前撤回输出权限会去掉正文中的输出,已经固定的正文若包含撤回的输出,则不再发送,记为 `subscription_changed`。更改地址、移除匹配的事件或智能体也不会把旧内容发给新订阅。轮换密钥后用当前密钥签名。
8888

8989
## 签名与请求头
9090

@@ -137,15 +137,15 @@ def verify(secret: str, header: str, raw_body: bytes, tolerance: int = 300) -> b
137137
## 投递
138138
139139
- **至少一次。** 事件排在网关 SQLite 数据库的队列里(`webhook_deliveries`),重启后仍在;网关停下时没发完的,再启动后继续发。接收方可能收到同一投递不止一次,请按 `X-OAA-Delivery` 去重。
140-
- 审批通知标记与各匹配端点的投递记录一起提交。写队列失败不会留下部分标记,再次收到同一通知时仍可入队。投递保证从**成功入队后**算起;源任务提交后、出站通知监听器运行前发生进程退出,并非所有事件都能自动补发。
140+
- 六类已订阅运行事件都在源事务中同时写入投递记录或待恢复记录。即使进程在唤醒发送器前退出,重启也不会漏掉已提交事件。如果投递表暂时写不进去,网关会自动补建投递记录。如果两处均无法落盘,源检查点报错,不宣称成功。若连失败状态也写不进去,执行中的任务只重试最后这笔写入,不重跑智能体或工具;重启后从上次已提交的状态恢复。
141141
- **成功**是 **10 秒**内(连接、发送与应答合计)返回任意 `2xx`。不跟随重定向,`3xx` 算失败。请先应答,再处理。
142142
- **重试。** 失败后分别约在 5 秒、30 秒、2 分钟、10 分钟、30 分钟后重试(各带 ±20% 随机抖动),共 6 次。最后一次仍失败就记为 `failed` 并保留记录。已结束的投递可以用 `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` 手动重新排队(投递编号不变,重试次数重新计)。
143143
- **顺序。** 同一端点的投递一次一条、从旧到新,接收方按顺序收到该端点的事件;等待重试的投递会挡住同一端点后面的投递。不同端点互不等待。
144-
- **不妨碍运行。** 入队是在运行状态落库之后的一次小插入,而且只在有匹配端点时才发生。发送在后台进行;接收方慢或不可达,不会拖慢或阻塞任何运行。
144+
- **检查点不等待网络。** 只有 SQLite 写入在源事务内;网络发送在后台进行,不会让任务等待接收端应答。
145145
- **连续失败的端点**不会被自动删除或停用。端点的 `status` 会显示 `state: "failing"`、`consecutive_failures`、最近的错误与排队数。
146146
- 停用的端点(`enabled: false`)不再收到新事件;已排队的投递等它重新启用后再发。删除端点会一并删除它排队中的投递。
147147
- 每个端点保留最近 200 条已结束的投递。
148-
- 每个端点最多排队 10,000 条投递。超过时(端点持续失败而事件还在不断产生),正在投递的那条之后最早排队的投递会被标为 `failed`(`queue_overflow`)并丢弃,坏掉的接收端不会让数据库无限增长。
148+
- 每个端点最多积压 10,000 项,含待恢复记录。超限时保留队首,淘汰数计入 `overflow_total`。已建单的淘汰项会标记为 `failed`(`queue_overflow`),建单前被淘汰的记录没有投递编号。
149149
150150
## 出站安全
151151
@@ -169,9 +169,9 @@ def verify(secret: str, header: str, raw_body: bytes, tolerance: int = 300) -> b
169169
| `POST /v1/webhooks/{id}/rotate-secret` | `{id, secret}`;旧密钥立即失效 |
170170
| `POST /v1/webhooks/{id}/test` | 202 delivery;排入一条 `webhook.test` 事件 |
171171
| `GET /v1/webhooks/{id}/deliveries?limit=20` | `{data: [delivery]}`,新的在前(最多 200) |
172-
| `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` | 202 delivery;还在排队时 409 `webhook_delivery_pending` |
172+
| `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` | 202 delivery;还在排队时 409 `webhook_delivery_pending`;队列已满时 429 `queue_full` |
173173
174-
**endpoint** 为 `{object: "webhook_endpoint", id, url, events, agents, include_output, enabled, description, allow_insecure_http, allow_private_network, created_at, updated_at, status}`,其中 `status = {state: "ok" | "failing" | "disabled", consecutive_failures, last_success_at, last_failure_at, last_error, pending, latest_delivery}`。时间是 Unix 毫秒,与其它管理接口一致。
174+
**endpoint** 为 `{object: "webhook_endpoint", id, url, events, agents, include_output, enabled, description, allow_insecure_http, allow_private_network, created_at, updated_at, status}`,其中 `status = {state: "ok" | "failing" | "disabled", consecutive_failures, last_success_at, last_failure_at, last_error, pending, capture_pending, oldest_pending_at, overflow_total, latest_delivery}`。`pending` 包含已记录但尚未建单的 `capture_pending`;队列为空时 `oldest_pending_at` 为 null;`overflow_total` 从升级后累计。时间是 Unix 毫秒,与其它管理接口一致。
175175
176176
**delivery** 为 `{object: "webhook_delivery", id, endpoint_id, event_id, event_type, run_id, status: "pending" | "succeeded" | "failed", attempts, next_attempt_at, http_status, duration_ms, last_error, created_at, updated_at}`。
177177
@@ -243,5 +243,5 @@ run.completed resp_c61d… agent/sample completed
243243
- 每个 owner 的端点数:20。每个端点保留的已结束投递:200。`include_output` 携带的输出:32 KiB。每次尝试的超时:10 秒。尝试次数:6。
244244
- 只有 owner 级管理员密钥能配置回调;没有按账号或按请求的回调。
245245
- HTTPS 端点按 Node.js 信任的证书颁发机构校验证书。自动化测试只用本机明文 http 接收端;投递到真实公网 HTTPS 端点走同一段代码,但不在测试覆盖之内。
246-
- 网关关机或重启时被中断的运行,其 `run.interrupted` 在关机时或下次启动时(本进程启动以来被中断的运行)入队,只发一次。
246+
- 捕获在启动恢复前安装,一直保留到关机检查点结束。旧版已排队的投递继续按原正文或原记录处理;升级不会重建旧版从未记录的事件,也不会向新端点补发历史。
247247
- 不支持多个网关进程共用一个数据目录(网关的其它部分同样不支持);那样每个进程都会发送队列。

‎src/gateway/key-routes.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import type { NodeHub } from '../fabric/network.js';
99
import { executionLevels, isOwnerWide, keyQuotaSchema } from '../core/contracts.js';
1010
import { Fault } from '../core/util.js';
1111
import { assertMayManageKey, assertQuotaWithin } from './key-guard.js';
12-
import { registerWebhookRoutes } from './webhook-routes.js';
1312

1413
/** 审计记录、API 密钥与运行事件回调的管理接口(`/v1/audit`、`/v1/keys`、`/v1/webhooks`)。 */
1514
export function registerKeyRoutes(
@@ -22,7 +21,6 @@ export function registerKeyRoutes(
2221
hub,
2322
}: { auth: Auth; audit: AuditLog; config: GatewayConfig; store: Store; hub: NodeHub },
2423
): void {
25-
registerWebhookRoutes(app, { store, config });
2624
app.get('/v1/audit', async (req) => {
2725
if (!isOwnerWide(req.principal))
2826
throw new Fault('scope_denied', 'The audit trail requires an owner-wide admin key.', 403);

0 commit comments

Comments
 (0)