Skip to main content

base/interface/
catalog.rs

1//! The extension points, as data.
2//!
3//! They accumulated one at a time, each documented where it lives, which is
4//! the right place for the detail and the wrong place for the overview. There
5//! was no answer to "what can I hook, when does it fire, how often, and am I
6//! allowed to" that did not involve reading nine modules — and no way to check
7//! that the answer written in a document still matched the code.
8//!
9//! So the overview is a value. [`all`] is the list; the reference table in the
10//! extension-point index is [rendered from it](render_markdown) rather than
11//! typed out, which is what keeps the two from drifting.
12//!
13//! # Frequency is a design constraint, not a footnote
14//!
15//! A point that fires once per session can afford a subprocess. One that fires
16//! per streamed chunk cannot afford anything — at ten thousand calls a turn,
17//! even a cheap in-process call is the difference between streaming and
18//! stuttering. That is why [`Frequency::PerStreamChunk`] points are closed to
19//! scripts by default: not because a script would do something dangerous
20//! there, but because the cost is not one an author can see when they write
21//! it.
22
23/// What kind of seam this is.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum Kind {
27    /// Replace a whole subsystem by implementing a trait.
28    Contract,
29    /// Contribute something to a collection the engine assembles.
30    Registration,
31    /// Sit in the path of something the engine is doing, with the option to
32    /// change it.
33    Interception,
34}
35
36/// How often it fires, to an order of magnitude.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum Frequency {
40    /// Once per process.
41    PerProcess,
42    /// Once per session.
43    PerSession,
44    /// Once or twice a turn.
45    PerTurn,
46    /// Once per tool call — tens per turn.
47    PerToolCall,
48    /// Once per model request — a few per turn.
49    PerModelCall,
50    /// Per streamed chunk — thousands per turn.
51    PerStreamChunk,
52}
53
54impl Frequency {
55    pub fn label(self) -> &'static str {
56        match self {
57            Self::PerProcess => "每进程",
58            Self::PerSession => "每会话",
59            Self::PerTurn => "每轮",
60            Self::PerToolCall => "每次工具调用",
61            Self::PerModelCall => "每次模型调用",
62            Self::PerStreamChunk => "每个流式分片",
63        }
64    }
65
66    /// Roughly how many times a busy turn hits it.
67    pub fn magnitude(self) -> &'static str {
68        match self {
69            Self::PerProcess | Self::PerSession => "10⁰ 量级",
70            Self::PerTurn | Self::PerModelCall => "10⁰–10¹ 量级",
71            Self::PerToolCall => "10¹ 量级",
72            Self::PerStreamChunk => "10³–10⁴ 量级",
73        }
74    }
75}
76
77/// What one kind of author may do at a point.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79#[non_exhaustive]
80pub enum Access {
81    /// Everything the point offers.
82    Full,
83    /// May contribute, may not change or remove what is already there.
84    AddOnly,
85    /// The full point, but only with a capability declared at install and
86    /// shown to whoever installed it.
87    Declared,
88    /// Not available.
89    Denied,
90}
91
92impl Access {
93    pub fn label(self) -> &'static str {
94        match self {
95            Self::Full => "完全",
96            Self::AddOnly => "只能新增",
97            Self::Declared => "需声明能力",
98            Self::Denied => "不开放",
99        }
100    }
101}
102
103/// Who may do what, by where the extension came from.
104///
105/// The axis is *provenance*, not privilege level: the question a host is
106/// really answering is "did the operator write this, or download it".
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub struct Trust {
109    /// The engine's own registrations.
110    pub kernel: Access,
111    /// Written in settings by whoever runs this deployment.
112    pub config: Access,
113    /// A script in the operator's own project.
114    pub script: Access,
115    /// An installed plugin.
116    pub plugin: Access,
117}
118
119impl Trust {
120    /// Everything the operator wrote is unrestricted; a plugin may add.
121    pub const fn operator_full_plugin_adds() -> Self {
122        Self {
123            kernel: Access::Full,
124            config: Access::Full,
125            script: Access::Full,
126            plugin: Access::AddOnly,
127        }
128    }
129
130    /// Everything the operator wrote is unrestricted; a plugin needs to have
131    /// declared the capability.
132    pub const fn operator_full_plugin_declares() -> Self {
133        Self {
134            kernel: Access::Full,
135            config: Access::Full,
136            script: Access::Full,
137            plugin: Access::Declared,
138        }
139    }
140
141    /// A seam only the embedding program can reach — it is a Rust trait
142    /// wired at build time, so there is nothing for a script or a plugin to
143    /// register through.
144    pub const fn host_only() -> Self {
145        Self {
146            kernel: Access::Full,
147            config: Access::Denied,
148            script: Access::Denied,
149            plugin: Access::Denied,
150        }
151    }
152}
153
154/// One place something can be plugged in.
155#[derive(Debug, Clone, Copy)]
156pub struct ExtensionPoint {
157    /// Stable id. What documentation, configuration and error messages call
158    /// this point.
159    pub id: &'static str,
160    pub kind: Kind,
161    /// One line: what it is for.
162    pub summary: &'static str,
163    /// When in a turn it happens.
164    pub timing: &'static str,
165    /// What an implementation may change. "nothing" for a pure observer.
166    pub rewrites: &'static str,
167    pub frequency: Frequency,
168    pub trust: Trust,
169    /// Where the contract is defined, as a Rust path.
170    pub defined_in: &'static str,
171    /// Every way a host or extension author gets an implementation in.
172    pub wired_by: &'static [Wiring],
173}
174
175/// How an implementation of a point reaches the engine.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177#[non_exhaustive]
178pub enum Wiring {
179    /// `runtime::agent::Builder::<method>`.
180    Builder(&'static str),
181    /// `runtime::plugin::Registrar::<method>`; a host reaches it through `Builder::plugin`.
182    Registrar(&'static str),
183    /// One of the points `script_host::bindings::BINDABLE_POINTS` binds.
184    Script,
185    /// Set on the object another point wires.
186    Carried { by: &'static str, via: &'static str },
187    /// Once per process, by whoever assembles models or settings.
188    Process(&'static str),
189    /// A module's own builder.
190    Module(&'static str),
191    /// A settings key.
192    Settings(&'static str),
193}
194
195impl Wiring {
196    pub fn label(&self) -> String {
197        match self {
198            Self::Builder(m) => format!("`Builder::{m}`"),
199            Self::Registrar(m) => format!("`Registrar::{m}`"),
200            Self::Script => "脚本绑定".to_string(),
201            Self::Carried { by, via } => format!("随 `{by}`:`{via}`"),
202            Self::Process(p) => format!("进程级:`{p}`"),
203            Self::Module(p) => format!("模块:`{p}`"),
204            Self::Settings(k) => format!("设置项 `{k}`"),
205        }
206    }
207}
208
209/// Every extension point the engine has.
210pub fn all() -> &'static [ExtensionPoint] {
211    &POINTS
212}
213
214static POINTS: [ExtensionPoint; 47] = [
215    ExtensionPoint {
216        id: "tool.registry",
217        kind: Kind::Contract,
218        summary: "整套工具,或者其中一个工具",
219        timing: "会话构建时,以及之后任何时候",
220        rewrites: "有哪些工具、它们各是什么",
221        frequency: Frequency::PerSession,
222        trust: Trust::host_only(),
223        defined_in: "base::interface::tool::ToolRegistry",
224        wired_by: &[Wiring::Builder("tools"), Wiring::Registrar("tool")],
225    },
226    ExtensionPoint {
227        id: "tool.around",
228        kind: Kind::Interception,
229        summary: "套在每次工具调用外面的一圈:超时、重试、缓存、埋点",
230        timing: "分发前后,在权限和 hooks 的外侧",
231        rewrites: "取消信号和结果;改不了输入",
232        frequency: Frequency::PerToolCall,
233        trust: Trust::operator_full_plugin_declares(),
234        defined_in: "base::interface::tool_middleware::ToolMiddleware",
235        wired_by: &[
236            Wiring::Builder("tool_middleware"),
237            Wiring::Registrar("tool_middleware"),
238            Wiring::Script,
239        ],
240    },
241    ExtensionPoint {
242        id: "tool.result",
243        kind: Kind::Interception,
244        summary: "工具结果长什么样:截断、脱敏、大块内容",
245        timing: "所有 hook 之后,模型看到它之前的最后一步",
246        rewrites: "结果文本和其中的图片",
247        frequency: Frequency::PerToolCall,
248        trust: Trust::operator_full_plugin_declares(),
249        defined_in: "base::interface::tool_result::ToolResultTransformer",
250        wired_by: &[
251            Wiring::Builder("tool_result_transformer"),
252            Wiring::Registrar("tool_result"),
253            Wiring::Script,
254        ],
255    },
256    ExtensionPoint {
257        id: "prompt.block",
258        kind: Kind::Registration,
259        summary: "系统提示里一个具名、有序、可撤销的块",
260        timing: "提示组装时,每轮一次",
261        rewrites: "只能新增",
262        frequency: Frequency::PerTurn,
263        trust: Trust::operator_full_plugin_adds(),
264        defined_in: "base::interface::prompt_registry::PromptRegistry::register_block",
265        wired_by: &[
266            Wiring::Builder("prompt_registry"),
267            Wiring::Registrar("prompt_block"),
268            Wiring::Script,
269        ],
270    },
271    ExtensionPoint {
272        id: "prompt.context",
273        kind: Kind::Registration,
274        summary: "文本在提示组装时才算出来的块",
275        timing: "提示组装时,每轮一次",
276        rewrites: "只能新增",
277        frequency: Frequency::PerTurn,
278        trust: Trust::operator_full_plugin_adds(),
279        defined_in: "base::interface::prompt_registry::PromptRegistry::register_context",
280        wired_by: &[
281            Wiring::Builder("prompt_registry"),
282            Wiring::Registrar("prompt_context"),
283            Wiring::Script,
284        ],
285    },
286    ExtensionPoint {
287        id: "prompt.variable",
288        kind: Kind::Registration,
289        summary: "`{{name}}` 在每个块里展开成什么",
290        timing: "提示组装时,块合并之后",
291        rewrites: "只有自己那个占位符,别的都不行",
292        frequency: Frequency::PerTurn,
293        trust: Trust::operator_full_plugin_adds(),
294        defined_in: "base::interface::prompt_registry::PromptRegistry::register_variable",
295        wired_by: &[
296            Wiring::Builder("prompt_registry"),
297            Wiring::Registrar("prompt_variable"),
298            Wiring::Script,
299        ],
300    },
301    ExtensionPoint {
302        id: "prompt.assembler",
303        kind: Kind::Contract,
304        summary: "所有贡献怎么变成请求携带的那些块",
305        timing: "提示组装时,取代引擎自己那套",
306        rewrites: "顺序、缓存边界、合并策略——整个结果",
307        frequency: Frequency::PerModelCall,
308        trust: Trust::host_only(),
309        defined_in: "base::interface::prompt_assembler::PromptAssembler",
310        wired_by: &[Wiring::Builder("prompt_assembler")],
311    },
312    ExtensionPoint {
313        id: "prompt.assemble",
314        kind: Kind::Interception,
315        summary: "在组装好的整份提示上再过一遍",
316        timing: "提示组装的最后一步",
317        rewrites: "块的内容、顺序和取舍",
318        frequency: Frequency::PerTurn,
319        trust: Trust::operator_full_plugin_declares(),
320        defined_in: "base::interface::prompt_assembly::AssemblyHook",
321        wired_by: &[
322            Wiring::Builder("prompt_registry"),
323            Wiring::Registrar("assembly_hook"),
324            Wiring::Registrar("async_assembly_hook"),
325            Wiring::Script,
326        ],
327    },
328    ExtensionPoint {
329        id: "prompt.submit",
330        kind: Kind::Interception,
331        summary: "用户消息进对话之前的最后一道:放行、改写或拒收",
332        timing: "每条用户消息进转录之前,开一轮的与 steer 进来的都算;在 UserPromptSubmit hook 之后",
333        rewrites: "消息文本;或者拒收这条",
334        frequency: Frequency::PerTurn,
335        trust: Trust::host_only(),
336        defined_in: "base::interface::prompt_middleware::PromptMiddleware",
337        wired_by: &[
338            Wiring::Builder("prompt_middleware"),
339            Wiring::Registrar("prompt_middleware"),
340        ],
341    },
342    ExtensionPoint {
343        id: "event.sink",
344        kind: Kind::Contract,
345        summary: "除了引擎返回的那个 channel,事件还往哪里去",
346        timing: "每次发射,在 sink 自己的 task 上",
347        rewrites: "什么都改不了——只能观察",
348        frequency: Frequency::PerStreamChunk,
349        trust: Trust::host_only(),
350        defined_in: "base::interface::event_sink::EventSink",
351        wired_by: &[Wiring::Builder("event_sink")],
352    },
353    ExtensionPoint {
354        id: "health.check",
355        kind: Kind::Registration,
356        summary: "某个子系统是否正常,和引擎自己的答案并列",
357        timing: "每当有人要一份健康报告",
358        rewrites: "什么都改不了——检查只汇报,不修复",
359        frequency: Frequency::PerProcess,
360        trust: Trust::host_only(),
361        defined_in: "base::interface::health::HealthCheck",
362        wired_by: &[
363            Wiring::Builder("health_check"),
364            Wiring::Registrar("health_check"),
365        ],
366    },
367    ExtensionPoint {
368        id: "elicitation.ask",
369        kind: Kind::Contract,
370        summary: "引擎怎么问人:授权、澄清、导入",
371        timing: "每当一个决定需要人来做",
372        rewrites: "答案",
373        frequency: Frequency::PerTurn,
374        trust: Trust::host_only(),
375        defined_in: "base::interface::elicitation::Elicitation",
376        wired_by: &[Wiring::Builder("elicitation")],
377    },
378    ExtensionPoint {
379        id: "host_calls.call",
380        kind: Kind::Contract,
381        summary: "宿主声明的工具怎么交给宿主去跑、等它答;含连接经 daemon.setHostTools 提供的工具",
382        timing: "模型调用一个宿主声明的工具时",
383        rewrites: "这次调用的结果",
384        frequency: Frequency::PerToolCall,
385        trust: Trust::host_only(),
386        defined_in: "base::interface::host_call::HostCalls",
387        wired_by: &[Wiring::Builder("host_calls")],
388    },
389    ExtensionPoint {
390        id: "permission.check",
391        kind: Kind::Contract,
392        summary: "一次工具调用允不允许",
393        timing: "每次工具调用之前",
394        rewrites: "放行、拒绝,或者问人",
395        frequency: Frequency::PerToolCall,
396        trust: Trust::host_only(),
397        defined_in: "base::interface::permission::PermissionPolicy",
398        wired_by: &[Wiring::Builder("permission")],
399    },
400    ExtensionPoint {
401        id: "permission.grants",
402        kind: Kind::Contract,
403        summary: "会话里给出的放行记在哪、记多久",
404        timing: "skill 的 allowed-tools 生效、人答\"总是允许\"时",
405        rewrites: "本轮、本会话、本项目的放行",
406        frequency: Frequency::PerTurn,
407        trust: Trust::host_only(),
408        defined_in: "base::interface::permission::PermissionGrants",
409        wired_by: &[Wiring::Builder("permission")],
410    },
411    ExtensionPoint {
412        id: "scene",
413        kind: Kind::Contract,
414        summary: "系统提示骨架、工具面和预算",
415        timing: "会话构建时",
416        rewrites: "一个 agent 怎么呈现自己,全部",
417        frequency: Frequency::PerSession,
418        trust: Trust::host_only(),
419        defined_in: "base::interface::scene::SceneSpec",
420        wired_by: &[Wiring::Builder("scene")],
421    },
422    ExtensionPoint {
423        id: "model",
424        kind: Kind::Contract,
425        summary: "LLM 后端与它的传输协议",
426        timing: "每次模型请求",
427        rewrites: "整场交互",
428        frequency: Frequency::PerModelCall,
429        trust: Trust::host_only(),
430        defined_in: "base::interface::model::Model",
431        wired_by: &[Wiring::Builder("model")],
432    },
433    ExtensionPoint {
434        id: "model.factory",
435        kind: Kind::Registration,
436        summary: "settings 里的 `api_type` 怎么变成一个跑得起来的模型",
437        timing: "启动时,读 provider 配置的那一刻",
438        rewrites: "哪些协议可以被配置出来",
439        frequency: Frequency::PerProcess,
440        trust: Trust::host_only(),
441        defined_in: "base::interface::model_factory::ModelFactory",
442        wired_by: &[Wiring::Process(
443            "base::interface::model_factory::ModelFactoryRegistry::register",
444        )],
445    },
446    ExtensionPoint {
447        id: "model.request",
448        kind: Kind::Interception,
449        summary: "组装好、还没发出去的请求:消息、工具、参数",
450        timing: "每次模型调用之前的最后一刻",
451        rewrites: "请求里的一切",
452        frequency: Frequency::PerModelCall,
453        trust: Trust::operator_full_plugin_declares(),
454        defined_in: "base::interface::model_interceptor::ModelInterceptor::on_request",
455        wired_by: &[
456            Wiring::Builder("model_interceptor"),
457            Wiring::Registrar("model_interceptor"),
458            Wiring::Script,
459        ],
460    },
461    ExtensionPoint {
462        id: "model.message",
463        kind: Kind::Interception,
464        summary: "模型产出的一条完整消息,在它被记下来之前",
465        timing: "承载它的那段流结束之后",
466        rewrites: "消息内容",
467        frequency: Frequency::PerModelCall,
468        trust: Trust::operator_full_plugin_declares(),
469        defined_in: "base::interface::model_interceptor::ModelInterceptor::on_message",
470        wired_by: &[
471            Wiring::Builder("model_interceptor"),
472            Wiring::Registrar("model_interceptor"),
473            Wiring::Script,
474        ],
475    },
476    ExtensionPoint {
477        id: "credentials",
478        kind: Kind::Contract,
479        summary: "provider 的 API key 从哪来",
480        timing: "启动时,读 provider 配置的那一刻",
481        rewrites: "凭据本身",
482        frequency: Frequency::PerProcess,
483        trust: Trust::host_only(),
484        defined_in: "base::interface::credentials::CredentialSource",
485        wired_by: &[Wiring::Process(
486            "base::interface::model_factory::ModelFactoryRegistry::with_credentials",
487        )],
488    },
489    ExtensionPoint {
490        id: "config.source",
491        kind: Kind::Contract,
492        summary: "配置层在合并之前从哪来",
493        timing: "进程启动,任何东西被构建之前",
494        rewrites: "有哪些层、每层里是什么 JSON;合并本身动不了",
495        frequency: Frequency::PerProcess,
496        trust: Trust::host_only(),
497        defined_in: "base::interface::config_source::ConfigSource",
498        wired_by: &[Wiring::Process("settings::LoadedSettings::load_from")],
499    },
500    ExtensionPoint {
501        id: "token.count",
502        kind: Kind::Contract,
503        summary: "上下文被判定为多大",
504        timing: "每次预算检查",
505        rewrites: "压缩据以触发的那个数字",
506        frequency: Frequency::PerTurn,
507        trust: Trust::host_only(),
508        defined_in: "base::interface::token_counter::TokenCounter",
509        wired_by: &[Wiring::Builder("token_counter")],
510    },
511    ExtensionPoint {
512        id: "history.store",
513        kind: Kind::Contract,
514        summary: "会话日志在两次运行之间存在哪",
515        timing: "每次追加,以及恢复时",
516        rewrites: "日志怎么持久化、存到哪",
517        frequency: Frequency::PerTurn,
518        trust: Trust::host_only(),
519        defined_in: "history::store::HistoryStore",
520        wired_by: &[Wiring::Builder("history_store")],
521    },
522    ExtensionPoint {
523        id: "history.query",
524        kind: Kind::Contract,
525        summary: "怎么找会话:按时间列表、按文本搜索,以及按内容找到每个会话里第一次说到的地方",
526        timing: "每当有人要的是若干会话而不是某一个会话",
527        rewrites: "返回哪些会话、按什么顺序、怎么算匹配",
528        frequency: Frequency::PerSession,
529        trust: Trust::host_only(),
530        defined_in: "history::store::HistoryStore::find_sessions",
531        wired_by: &[Wiring::Carried {
532            by: "history.store",
533            via: "HistoryStore::find_sessions / search_text",
534        }],
535    },
536    ExtensionPoint {
537        id: "history.blob",
538        kind: Kind::Contract,
539        summary: "大到不适合留在日志里的内容存在哪",
540        timing: "每次追加带图片或大负载时,以及加载时",
541        rewrites: "大块内容存在哪、怎么寻址",
542        frequency: Frequency::PerTurn,
543        trust: Trust::host_only(),
544        defined_in: "history::blob::BlobStore",
545        wired_by: &[Wiring::Carried {
546            by: "history.store",
547            via: "JsonlHistoryStore::with_blob_store",
548        }],
549    },
550    ExtensionPoint {
551        id: "history.projection",
552        kind: Kind::Contract,
553        summary: "一份日志对模型意味着什么,包括扩展自己写的条目",
554        timing: "每次读取转录:恢复、分叉、搜索、翻页",
555        rewrites: "哪些条目变成消息、它们说了什么",
556        frequency: Frequency::PerSession,
557        trust: Trust::host_only(),
558        defined_in: "history::transcript::TranscriptProjection",
559        wired_by: &[Wiring::Carried {
560            by: "history.store",
561            via: "JsonlHistoryStore::with_projection",
562        }],
563    },
564    ExtensionPoint {
565        id: "history.extension_entry",
566        kind: Kind::Registration,
567        summary: "在会话日志里写自己的状态,挂在自己的命名空间下",
568        timing: "任何时候;和其余条目同序",
569        rewrites: "只能新增;内核从不解析 payload",
570        frequency: Frequency::PerTurn,
571        trust: Trust::operator_full_plugin_adds(),
572        defined_in: "history::entry::LogEntry::Extension",
573        wired_by: &[Wiring::Carried {
574            by: "history.store",
575            via: "HistoryStore::append",
576        }],
577    },
578    ExtensionPoint {
579        id: "memory.retriever",
580        kind: Kind::Contract,
581        summary: "一轮能召回哪些记忆",
582        timing: "每条用户消息一次,在后台",
583        rewrites: "召回的集合",
584        frequency: Frequency::PerTurn,
585        trust: Trust::host_only(),
586        defined_in: "base::interface::memory_contracts::MemoryRetriever",
587        wired_by: &[Wiring::Builder("memory_retriever")],
588    },
589    ExtensionPoint {
590        id: "memory.retrieval_hook",
591        kind: Kind::Interception,
592        summary: "召回的问题在提出之前,召回的答案在被用之前",
593        timing: "召回前后",
594        rewrites: "查询,以及召回的记忆名",
595        frequency: Frequency::PerTurn,
596        trust: Trust::operator_full_plugin_declares(),
597        defined_in: "base::interface::memory_contracts::RetrievalHook",
598        wired_by: &[
599            Wiring::Builder("retrieval_hook"),
600            Wiring::Registrar("retrieval_hook"),
601            Wiring::Script,
602        ],
603    },
604    ExtensionPoint {
605        id: "history.append_observer",
606        kind: Kind::Interception,
607        summary: "看着条目进入会话日志",
608        timing: "每次追加成功之后",
609        rewrites: "什么都改不了——只读是类型定死的,不是约定的",
610        frequency: Frequency::PerTurn,
611        trust: Trust {
612            kernel: Access::Full,
613            config: Access::Full,
614            script: Access::Full,
615            plugin: Access::AddOnly,
616        },
617        defined_in: "history::store::AppendObserver",
618        wired_by: &[Wiring::Carried {
619            by: "history.store",
620            via: "ObservedHistoryStore::new",
621        }],
622    },
623    ExtensionPoint {
624        id: "skill.source",
625        kind: Kind::Contract,
626        summary: "一次会话的 skill 从哪来",
627        timing: "会话构建时,以及每当有 MCP server 接入",
628        rewrites: "有哪些 skill、每个展开成什么文本",
629        frequency: Frequency::PerSession,
630        trust: Trust::host_only(),
631        defined_in: "base::interface::skill_provider::SkillProvider",
632        wired_by: &[Wiring::Module("skills::SkillsModule::provider")],
633    },
634    ExtensionPoint {
635        id: "instruction.source",
636        kind: Kind::Contract,
637        summary: "常驻指令从哪来",
638        timing: "会话构建时",
639        rewrites: "每会话注入一次的 AGENTS.md 文本",
640        frequency: Frequency::PerSession,
641        trust: Trust::host_only(),
642        defined_in: "base::interface::instruction_provider::InstructionProvider",
643        wired_by: &[Wiring::Builder("instruction_provider")],
644    },
645    ExtensionPoint {
646        id: "rules.source",
647        kind: Kind::Contract,
648        summary: "规则索引从哪来",
649        timing: "系统提示组装期间",
650        rewrites: "告诉模型存在哪些规则文档",
651        frequency: Frequency::PerModelCall,
652        trust: Trust::host_only(),
653        defined_in: "base::interface::instruction_provider::RuleProvider",
654        wired_by: &[Wiring::Builder("rule_provider")],
655    },
656    ExtensionPoint {
657        id: "turn.policy",
658        kind: Kind::Contract,
659        summary: "一轮什么时候算走得够久了",
660        timing: "每次模型调用之前,以及每次返回之后",
661        rewrites: "循环还走不走下一步,以及上报的停止原因",
662        frequency: Frequency::PerModelCall,
663        trust: Trust::host_only(),
664        defined_in: "base::interface::turn_policy::TurnPolicy",
665        wired_by: &[Wiring::Builder("turn_policy")],
666    },
667    ExtensionPoint {
668        id: "model.recovery",
669        kind: Kind::Contract,
670        summary: "模型调用失败或者半途截断时怎么办",
671        timing: "出错时,以及响应撞上输出上限被截断、被厂商暂停时",
672        rewrites: "换模型、压缩后重试、等一会儿原样重发、抬高上限、续上暂停的回复,还是直接失败",
673        frequency: Frequency::PerModelCall,
674        trust: Trust::host_only(),
675        defined_in: "base::interface::recovery_policy::RecoveryPolicy",
676        wired_by: &[Wiring::Builder("recovery_policy")],
677    },
678    ExtensionPoint {
679        id: "model.backoff",
680        kind: Kind::Contract,
681        summary: "首字节前失败的请求还发不发,发之前先等多久",
682        timing: "在 client 内部、模型契约之下,每次在首字节前失败的尝试",
683        rewrites: "重试前等多久,以及到底有没有重试",
684        frequency: Frequency::PerModelCall,
685        trust: Trust::host_only(),
686        defined_in: "base::interface::backoff::BackoffPolicy",
687        wired_by: &[Wiring::Carried {
688            by: "model",
689            via: "AnthropicClient::with_backoff_policy",
690        }],
691    },
692    ExtensionPoint {
693        id: "budget",
694        kind: Kind::Contract,
695        summary: "一轮能花多少,一个请求能长到多大",
696        timing: "每次模型调用之后,以及每个请求组装之前",
697        rewrites: "这轮还继不继续、被告知了什么、压缩的上限",
698        frequency: Frequency::PerModelCall,
699        trust: Trust::host_only(),
700        defined_in: "base::interface::budget_policy::BudgetPolicy",
701        wired_by: &[Wiring::Builder("budget_policy")],
702    },
703    ExtensionPoint {
704        id: "environment",
705        kind: Kind::Contract,
706        summary: "被记下来的时间和标识符——让重放对不上的那些输入",
707        timing: "每当一个答案是被写下来而不是被测量出来的",
708        rewrites: "日志时间戳、条目 id、提示里带的日期",
709        frequency: Frequency::PerTurn,
710        trust: Trust::host_only(),
711        defined_in: "base::interface::environment::Environment",
712        wired_by: &[Wiring::Builder("environment")],
713    },
714    ExtensionPoint {
715        id: "exec.process",
716        kind: Kind::Contract,
717        summary: "程序在哪跑",
718        timing: "工具启动的每一条命令,以及引擎替会话跑的 git 和辅助程序",
719        rewrites: "活儿在哪台机器上干",
720        frequency: Frequency::PerToolCall,
721        trust: Trust::host_only(),
722        defined_in: "base::interface::exec::process::Process",
723        wired_by: &[Wiring::Builder("exec")],
724    },
725    ExtensionPoint {
726        id: "exec.filesystem",
727        kind: Kind::Contract,
728        summary: "工具的文件在哪",
729        timing: "工具的每一次读、写、stat",
730        rewrites: "工具看到的是哪个文件系统",
731        frequency: Frequency::PerToolCall,
732        trust: Trust::host_only(),
733        defined_in: "base::interface::exec::filesystem::FileSystem",
734        wired_by: &[Wiring::Builder("exec")],
735    },
736    ExtensionPoint {
737        id: "exec.network",
738        kind: Kind::Contract,
739        summary: "工具发出的请求,以及它们能不能出去",
740        timing: "每个出站请求;出网策略约束的是模型选的那些",
741        rewrites: "请求去哪、去不去、谁来应答",
742        frequency: Frequency::PerToolCall,
743        trust: Trust::host_only(),
744        defined_in: "base::interface::exec::network::Network",
745        wired_by: &[Wiring::Builder("exec")],
746    },
747    ExtensionPoint {
748        id: "exec.sandbox",
749        kind: Kind::Contract,
750        summary: "一个进程怎么被约束——而不是要不要约束",
751        timing: "命令启动之前",
752        rewrites: "真正跑起来的那条命令,以及它能碰什么",
753        frequency: Frequency::PerToolCall,
754        trust: Trust::host_only(),
755        defined_in: "base::interface::exec::sandbox::Sandbox",
756        wired_by: &[Wiring::Builder("exec")],
757    },
758    ExtensionPoint {
759        id: "compaction",
760        kind: Kind::Contract,
761        summary: "对话什么时候被缩短、怎么缩",
762        timing: "每轮一次:两趟老化、一趟预测,最后是阈值",
763        rewrites: "消息历史,以及到底要不要重写",
764        frequency: Frequency::PerTurn,
765        trust: Trust::host_only(),
766        defined_in: "compaction::compact::Compactor",
767        wired_by: &[Wiring::Builder("compactor")],
768    },
769    ExtensionPoint {
770        id: "script.carrier",
771        kind: Kind::Contract,
772        summary: "在九个挂载点上跑运维者自己的代码,就在本进程里(QuickJS)",
773        timing: "载体被绑到哪就在哪;受每轮配额约束",
774        rewrites: "所绑那个点允许的一切,按脚本自己的来源定级",
775        frequency: Frequency::PerTurn,
776        trust: Trust::operator_full_plugin_declares(),
777        defined_in: "base::interface::script::ScriptEngine",
778        wired_by: &[
779            Wiring::Module("script_host::bindings::bind"),
780            Wiring::Builder("plugin"),
781        ],
782    },
783    ExtensionPoint {
784        id: "hooks",
785        kind: Kind::Interception,
786        summary: "生命周期回调——command、prompt、HTTP 或 agent",
787        timing: "二十九个具名时刻;见 docs/hooks.md",
788        rewrites: "按事件而异:拦截、改写输入、结束这一轮",
789        frequency: Frequency::PerToolCall,
790        trust: Trust {
791            kernel: Access::Full,
792            config: Access::Full,
793            script: Access::Full,
794            plugin: Access::Declared,
795        },
796        defined_in: "hooks::runner::HookRunner",
797        wired_by: &[Wiring::Builder("hooks"), Wiring::Settings("hooks")],
798    },
799    ExtensionPoint {
800        id: "hooks.host",
801        kind: Kind::Interception,
802        summary: "宿主连接登记的 hook(daemon.setHooks):每次触发时现读,叠加在设置的 hook 之后,只能拦下或补一段上下文",
803        timing: "PreToolUse、PostToolUse、PostToolUseFailure、UserPromptSubmit、Stop;设置里的 hook 先跑",
804        rewrites: "拦下这次调用,或补一段上下文;不批准、不改入参",
805        frequency: Frequency::PerToolCall,
806        trust: Trust::host_only(),
807        defined_in: "hooks::runner::hosts::HostHookSource",
808        wired_by: &[Wiring::Builder("host_hooks")],
809    },
810];
811
812/// Look one up by id.
813pub fn find(id: &str) -> Option<&'static ExtensionPoint> {
814    all().iter().find(|p| p.id == id)
815}
816
817/// The reference table, generated.
818///
819/// The extension-point index embeds this rather than restating it, so a point
820/// added to [`all`] appears in the documentation without anybody remembering
821/// to write it down, and a point whose trust rules change cannot leave a
822/// stale row behind.
823pub fn render_markdown() -> String {
824    let mut out = String::new();
825    out.push_str("| 扩展点 | 类型 | 接线 | 时机 | 可改什么 | 频率 | 配置 | 脚本 | 插件 |\n");
826    out.push_str("|---|---|---|---|---|---|---|---|---|\n");
827    for p in all() {
828        let kind = match p.kind {
829            Kind::Contract => "契约",
830            Kind::Registration => "注册",
831            Kind::Interception => "拦截",
832        };
833        out.push_str(&format!(
834            "| `{}` | {} | {} | {} | {} | {}({}) | {} | {} | {} |\n",
835            p.id,
836            kind,
837            p.wired_by
838                .iter()
839                .map(Wiring::label)
840                .collect::<Vec<_>>()
841                .join("、"),
842            p.timing,
843            p.rewrites,
844            p.frequency.label(),
845            p.frequency.magnitude(),
846            p.trust.config.label(),
847            p.trust.script.label(),
848            p.trust.plugin.label(),
849        ));
850    }
851    out
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857    use std::collections::HashSet;
858
859    #[test]
860    fn every_point_says_all_the_things_a_reader_needs() {
861        for p in all() {
862            for (field, value) in [
863                ("id", p.id),
864                ("summary", p.summary),
865                ("timing", p.timing),
866                ("rewrites", p.rewrites),
867                ("defined_in", p.defined_in),
868            ] {
869                assert!(
870                    !value.trim().is_empty(),
871                    "extension point '{}' has an empty {field}",
872                    p.id
873                );
874            }
875        }
876    }
877
878    #[test]
879    fn ids_are_unique() {
880        let mut seen = HashSet::new();
881        for p in all() {
882            assert!(seen.insert(p.id), "duplicate extension point id '{}'", p.id);
883        }
884    }
885
886    /// The rule the frequency column exists to enforce: a point that fires
887    /// thousands of times a turn is not open to a script, because the cost is
888    /// invisible to whoever writes one.
889    #[test]
890    fn the_highest_frequency_points_are_closed_to_scripts() {
891        for p in all() {
892            if p.frequency == Frequency::PerStreamChunk {
893                assert_eq!(
894                    p.trust.script,
895                    Access::Denied,
896                    "'{}' fires {} and must not be open to scripts",
897                    p.id,
898                    p.frequency.magnitude()
899                );
900                assert_eq!(p.trust.plugin, Access::Denied, "same for '{}'", p.id);
901            }
902        }
903    }
904
905    /// A plugin may only ever *add* without declaring something. Anything a
906    /// point lets it rewrite has to be behind a declaration, or the
907    /// install-time disclosure is not telling the truth.
908    #[test]
909    fn a_plugin_never_gets_more_than_add_only_by_default() {
910        for p in all() {
911            assert!(
912                matches!(
913                    p.trust.plugin,
914                    Access::AddOnly | Access::Declared | Access::Denied
915                ),
916                "'{}' would give an installed plugin unrestricted access",
917                p.id
918            );
919        }
920    }
921
922    #[test]
923    fn the_table_has_a_row_for_every_point() {
924        let table = render_markdown();
925        for p in all() {
926            assert!(
927                table.contains(&format!("`{}`", p.id)),
928                "'{}' is missing from the generated table",
929                p.id
930            );
931        }
932        assert_eq!(
933            table.lines().count(),
934            all().len() + 2,
935            "header, separator, and one row each"
936        );
937    }
938
939    #[test]
940    fn every_contract_can_be_wired_somehow() {
941        for p in all() {
942            if p.kind == Kind::Contract {
943                assert!(
944                    !p.wired_by.is_empty(),
945                    "contract '{}' says nothing about how an implementation gets in",
946                    p.id
947                );
948            }
949        }
950    }
951
952    #[test]
953    fn a_carried_point_names_a_point_that_exists() {
954        for p in all() {
955            for w in p.wired_by {
956                if let Wiring::Carried { by, .. } = w {
957                    assert!(
958                        find(by).is_some(),
959                        "'{}' is carried by '{by}', which is not a point",
960                        p.id
961                    );
962                    assert_ne!(*by, p.id, "'{}' cannot carry itself", p.id);
963                }
964            }
965        }
966    }
967
968    #[test]
969    fn find_is_the_id_lookup_it_claims_to_be() {
970        assert_eq!(
971            find("tool.around").map(|p| p.kind),
972            Some(Kind::Interception)
973        );
974        assert!(find("nothing.like.this").is_none());
975    }
976}