Kairy 课本
继续阅读
第 20 讲进阶核心约 12 分钟

连接器入站事件、条件轮询 304 与零 Token Goal 唤醒数据流

外部世界变化如何不花 1 个大模型 Token,精准唤醒正在等待的长期目标?

Poll Cursor304 Not Modifiedgoal_waitsevent_inbox0077 迁移KAIRY-0105
心智模型

被动感知不是「定时让大模型去刷网页」

第 23–24 讲介绍了内部 Goals、Hooks 与 event_inbox,但在 KAIRY-0105 之前,外部鉴权系统(如 GitHub PR 审核、Issue 状态变动)仍然缺少统一的入站链路:Bash Hook 设计上是无密钥(secretless)的,不能安全拿 OAuth Token 去拉 API。0077_connector_events_and_waits.sql 与 server/src/connectors/triggers.rs 补上了这块拼图:

  1. 条件请求把空轮询压到零成本:持久化 etag 与 last_modified,上游返回 304 Not Modified 立刻记数跳过,连 JSON 都不必解析。
  2. 401 暂停游标,暂态错误才退避:遇到 Token 失效立即置为 needs_reauth 并调用 pause_connector_cursors(paused = 1)彻底停轮询;唯有网络或上游 5xx 等 TransientError 才按指数退避(上限 MAX_BACKOFF_SECS = 3600)。
  3. 确定性键提取匹配 goal_waits:用纯 Rust 把 GitHub 事件归一为 owner/repo#42,走索引 (connector_id, resource_key, status) 精准唤醒等待该资源的 Goal。

34.1 入站事件到 Goal / Feed 的完整数据流

Kairy 架构深度长课 EP04 · 分支 C:主动伴侣引擎、连接器生态与四桶预算隔舱本章定位 37:1450:16
倍速
当前 00:00 · 开场动效:Kairy 架构深度长课 · EP04
连接器入站触发:条件轮询 304、Webhook 与零 Token Goal 唤醒数据流入站汇流门对比 304 零耗与新事件唤醒
条件轮询 Worker200 新游标推进Webhook 零 LLM 提取纯规则 JSON 提取字段水位与等待匹配goal_waits 零模型唤醒串行事件箱按 scope 合批三路精准分流Chat / Goal / 提醒
connector_cursors & goal_waitskairy-core/migrations/0077_connector_events_and_waits.sql

用 STRICT 表持久化游标、ETag、错误次数以及目标注册的等待条件;外部事件到达时按 (connector_id, resource_key, status="active") 索引瞬间匹配。

  • TABLE connector_cursors (STRICT)
  • TABLE goal_waits (active/satisfied)
  • 索引: (connector_id, resource_key)
  • 指数退避上限 MAX_BACKOFF = 3600s

不变量 只有真正命中目标等待条件或订阅路由的事件才进入下一级。

图 34-1:连接器入站触发流水线——从条件轮询/Webhook 到 goal_waits 匹配与 event_inbox 作用域串行消费。
一条 GitHub PR 状态变更如何 0 Token 唤醒长期目标
  1. Step 1到期游标扫描(30s Tick)triggers.rs 每 30 秒检查 connector_cursors.next_poll_at_ms,Cell 模式最小间隔 60s、Mac 模式 180s,避免高频轰炸。不变量 paused = 1 或状态非 connected 的连接器自动跳过。
  2. Step 2条件 HTTP 拉取(ETag / Last-Modified)经由 EgressGuard 与 HostVault 注入凭据发请求;返回 304 计入 not_modified_count 直接结束;401 立刻转 needs_reauth。不变量 失败走指数退避且封顶 3600 秒。
  3. Step 3确定性提取 (resource_key, event_type, summary)extract_item_metadata 纯代码解析 JSON Pointer 或 GitHub repository.full_name + subject.url 末尾编号生成 owner/repo#123。不变量 全过程 0 次大模型调用,不受外部文本提示词注入影响。
  4. Step 4索引匹配 goal_waits 并投递 event_inbox按 (connector_id, resource_key, status="active") 查找挂起目标,生成带唯一 dedupe_key 的 connector_event 写入 event_inbox。不变量 重复拉取同一事件被 dedupe_key UNIQUE 静默去重,绝不二次唤醒。

34.2 迁移 0077 表结构与零 LLM 元数据提取源码

TABLE goal_waits & connector_cursors0077_connector_events_and_waits.sql

用 STRICT 严格类型表持久化轮询游标与目标外部等待条件,并安全重建 event_inbox 纳入 connector_event 类型。

字段类型约束职责
connector_cursors.(connector_id, trigger_id)TEXT, TEXTPRIMARY KEY · STRICT游标主键,保存 cursor_value、etag、last_modified、consecutive_errors 与 next_poll_at_ms
goal_waits.resource_keyTEXTINDEX(connector_id, resource_key, status)结构化外部资源键(如 owner/repo#42),实现 O(log N) 唤醒匹配
goal_waits.statusTEXTCHECK('active'|'satisfied'|'closed')目标等待状态机,命中后转为 satisfied 防止重复触发
event_inbox.kindTEXT新增 'connector_event'通过建新表→导数据→删旧表→改名安全扩展 SQLite CHECK 约束
查看原始 CREATE TABLE
CREATE TABLE IF NOT EXISTS goal_waits (
    wait_id TEXT PRIMARY KEY,
    goal_id TEXT NOT NULL,
    connector_id TEXT NOT NULL,
    resource_key TEXT NOT NULL,
    event_types_json TEXT NOT NULL DEFAULT '[]',
    status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'satisfied', 'closed')),
    expires_at_ms INTEGER,
    created_at_ms INTEGER NOT NULL,
    updated_at_ms INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS goal_waits_lookup_idx
    ON goal_waits(connector_id, resource_key, status);
RUSTextract_item_metadata:纯 Rust 确定性提取资源键与摘要(0 Token)kairy-core/crates/server/src/connectors/triggers.rs · L66-L112
66/// Extracts deterministic `(resource_key, event_type, summary)` from a polled item without model calls.
67pub(crate) fn extract_item_metadata(
68 item: &Value,
69 item_id: &str,
70) -> (String, Option<String>, String) {
71 let explicit_key = item["resourceKey"]
72 .as_str()
73 .or_else(|| item["resource_key"].as_str())
74 .map(str::trim)
75 .filter(|s| !s.is_empty())
76 .map(str::to_owned);
77 let github_key = item["repository"]["full_name"]1
78 .as_str()
79 .map(str::trim)
80 .filter(|s| !s.is_empty())
81 .map(|repo| {
82 let num = item["subject"]["url"]
83 .as_str()
84 .and_then(|u| u.trim_end_matches('/').rsplit('/').next())
85 .filter(|seg| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()));
86 match num {
87 Some(n) => format!("{repo}#{n}"),
88 None => format!("{repo}:{item_id}"),
89 }
90 });
91 let resource_key = explicit_key.or(github_key).unwrap_or_else(|| item_id.to_owned());
92 let event_type = item["reason"]
93 .as_str()
94 .or_else(|| item["eventType"].as_str())
95 .or_else(|| item["type"].as_str())
96 .map(str::trim)
97 .filter(|s| !s.is_empty())
98 .map(str::to_owned);
99 let summary = item["subject"]["title"]
100 .as_str().or_else(|| item["title"].as_str()).or_else(|| item["summary"].as_str())
101 .map(str::trim).filter(|s| !s.is_empty()).unwrap_or(resource_key.as_str())
102 .chars().take(200).collect::<String>();
103 (resource_key, event_type, summary)
104}
kairy-core/crates/server/src/connectors/triggers.rs
符号 PollCycleReport, extract_item_metadata, run_one_poll_trigger

后台定时条件轮询、304 零成本跳过、401 转重授权与入队调度。

kairy-core/crates/adapters/src/connectors/goal_waits.rs
符号 upsert_goal_wait, find_matching_active_goal_waits, mark_goal_wait_satisfied, close_goal_waits_for_goal, close_goal_waits_for_connector

持久化目标等待条件并在事件命中时原子转为 satisfied 或随目标/连接器关闭。

kairy-core/crates/adapters/src/connectors/poll_http.rs
符号 execute_poll_operation_with_sidecar, PollHttpOutcome

构造 If-None-Match / If-Modified-Since 条件请求并处理响应码分叉。

kairy-core/migrations/0077_connector_events_and_waits.sql
符号 connector_cursors, goal_waits, event_inbox_new

STRICT 游标/等待表与安全的 SQLite CHECK 约束在线重建。

Owner 审阅清单

  1. 给 SQLite 存量表新增 CHECK 枚举值时,始终参考 0077 的「建新表 → 全量拷列 → 删旧表 → 重命名 → 重建索引」标准范式,绝不试图在运行时绕过约束。
  2. 任何新增外部触发器都必须先回答:「上游无变化时是否 0 模型 Token?重复投递靠什么 dedupe_key 幂等?」

自测:合上书能答出来吗

进度只存在这台电脑的浏览器里。