Expand description
The input engine: composition state, input schemes, dictionary queries, ranking and learning.
This crate replaces the C++ MSIME-Engine that used to be fetched from engine-lock.json and patched by overlay scripts. It owns the input algorithms; msime-input-runtime keeps orchestrating hosts and does not duplicate any of it.
The documented API is the core layer at the crate root: Session, its options and snapshot, and the functions and types beside them (they mirror the C++ metasequoia:: API the golden fixtures were recorded against), plus the public modules such as assets, diagnostics, touch and multilingual. host, ordering, backend and web are msime’s own product glue (the session facade and settings-page helpers its hosts call, its candidate ordering, its msime-cloud protocol, its browser storage): they stay pub only so msime’s crates in the same repository can reach them, are hidden from the documentation, are not part of the library API and change with msime’s hosts; other programs should not use them. msime’s product crates import everything the core layer takes or returns from the root, like a third party would; the boundary is described in docs/ARCHITECTURE.md and .agents/notes/implemented/architecture/2026-10-29-engine-host-dogfood.md. The crate’s README says which dictionary files a session reads, what to set in a downstream workspace, and the licences of the data compiled in.
引擎在运行时读写的每个文件(词库、模型、学习日志、代次目录)的格式、版本检查、产出方与数据许可证见仓库里的 docs/data-formats.md;代码注释里的 data-formats.md §N 指它的章节。
Re-exports§
pub use access::DictionaryAccess;pub use logging::set_log_sink;pub use logging::LogSink;
Modules§
- access
- 跨进程的词库访问租约:已准备的代次目录(
RuntimePaths::dictionaries)和用户数据目录(user_data,日志在这里)各放一个锁文件LOCK_FILE。用这些数据的会话持共享租约,改个人词库、重置学习这类维护持独占租约,两者互斥,只试不等。 - assets
- 运行时资源契约(契约版本 1)的文件名。每个文件的格式、谁写谁读、放在哪个根目录下,见
docs/data-formats.md。各模块都经这些常量引用文件名,改名只改一处。 - autocorrect_
type - Quanpin autocorrect type bits (
SessionOptions::autocorrect_types). Either of the first two also enables deletion and insertion, seerequest_autocorrect_mask. - cantonese
- Cantonese input in toneless Jyutping, read against
msime-cantonese.db(language_dictionary). Output is Traditional as stored, and nothing is learned. - diagnostics
- Every user-visible diagnostic and error message, verbatim from the C++ engine and bridge. Goldens record diagnostics and host tests compare error text, so modules use these constants instead of writing their own wording. Messages specific to one module’s validation (personal dictionary edits, snapshot staging) live with that module but follow the same rule: copy the C++ text.
- format
- 词库格式契约:拼音表的命名规则,以及
msime-pinyin.db、msime-wubi.db、msime-others.db的文件内版本(metadata表)。dict-builder 和运行时必须对它们取得一致,所以只在这里定义一次。完整规格见docs/data-formats.md§4、§9、§12。 - fuzzy_
rule - Fuzzy pinyin rule bits. The values are shared with platform preferences and must not change.
- language_
dictionary - The read-only dictionaries of the Cantonese, Zhuyin and Stroke schemes (
msime-cantonese.db,msime-zhuyin.db,msime-stroke.db). They ship beside the resource set rather than inside it, so the engine opens one only when its scheme is activated and treats a missing or unknown file as the scheme being unavailable. - logging
- 引擎的日志出口。引擎只在自己兜住了的异常上记一行(日志不是数据库被挪开、反查索引建不了、下载的五笔码表并不进代次、辅助码表读不到),每一行都是警告,不影响调用结果。
- multilingual
- 按原始键位置连接已确认的中英日词条。这里只选择完整路径,不查询词库或推断未知词。
- octagram
- Rime octagram(八股文)
.gram语法模型的只读查找端。 - stroke
- 笔画输入:按笔顺键入横竖撇点折,读
msime-stroke.db(language_dictionary)给出单字候选。只读,不学习,不做繁简转换。 - time
- 引擎读取的单调时钟。原生平台就是
std::time::Instant;wasm32-unknown-unknown 的 std 没有时钟,std::time::Instant::now会 panic,所以那里换成宿主经set_host_clock注入的毫秒读数(浏览器里是performance.now()和Date.now())。注入之前Instant::now()返回零点,经过的时间读作 0,不会 panic。 - touch
- 触屏按键的落点(#10018):宿主注册的字母键几何、每次按键相对被按键中心的偏移,以及按落点给双拼纠错计价。
- url
- 网址模式:在全拼、双拼、五笔的组字中键入
www.、http:、https:、ftp.、ftp:,或在由 ASCII 字母、数字组成的组字后键入@(邮箱)后,后续按键原样作为 ASCII 网址输入,不再转成中文。第一行始终是显示整段网址的兜底行,后面跟着补全:邮箱后缀(email_completions)和顶级域名(tld_completions)。组字里原文是ht、www这类开头时,候选里另有https://、www.等补全(scheme_completions),选中后以它进入网址模式。 - vietnamese
- Vietnamese input: Telex or VNI keystrokes transformed into Vietnamese letters with tone marks. The composition is the text itself; there are no candidates and nothing is learned.
- zhuyin
- 注音输入:大千(Dachen)键盘,按 libchewing 的语义;或者注音九键(
nine_key),数字键拼音节、声调键结束音节。两者都对照msime-zhuyin.db(language_dictionary)转换,输出词库里存的繁体,不学习。
Structs§
- Clock
- Command
Table Entry - One command of a host-supplied command table (
/mode). The host validates the table it read; the engine still skips a row it cannot use rather than trusting it. - Command
Translation Query - What
/fyasks the user’s translation service: the English typed after the trigger, to be translated into Chinese. UnlikeOnlineQueryit is never raised by spelling; only this command in the/mode produces one, and the answer is refused unless the session and the text are still the ones that asked. - Dictionary
Table Entry - Dictionary
Table Page - English
Input Options - First
Page Rows - 一次请求带的首页行数。
QueryRequest派生Default,裸usize会默认成 0 从而把补全词整组关掉,所以用带默认值的新类型;new把 0 归一成 1。 - Frequency
Adjustment Options - Fuzzy
Pinyin Options - Glide
Keyboard - 宿主画出来的字母键,用宿主自己的坐标。
- Glide
Point - Helpcode
Keymap - A helpcode table: the code letters (one or two, lowercase) of each character, which the session uses to filter and order candidates and to annotate them. Read one from a resource directory with
load_helpcode_keymap, from a file’s bytes withHelpcodeKeymap::from_table_bytes, or build one withHelpcodeKeymap::from_codes; a session takes it throughSessionOptions::helpcode_tableorSession::set_helpcode_table. - KeyResult
- Outcome of one key or action. A result can be handled and still carry a diagnostic, for example when learning could not be persisted.
- Local
Date Time - Local
Mode Options - Which local modes may be entered. The Shift+letter modes of the reference are on by default, symbol mode (
S) among them, as the reference’s factory configuration ships it on; expression (V) follows the reference’sv_modefactory and is on, command (/) and mention (@) are off, because entering them takes a key that used to reach the host as text. 拆字 (C) 在共享偏好层默认开(对齐参考的radical_mode出厂值),host-api 把未写偏好的文档读作开。 - Mention
Entry - One name or place of the host’s mention list (
@mode). - Mixed
Expressive Options - Nine
KeyShuangpin - 一张两键双拼表,进程里按内容只留一份,以
&'static交给九宫格;九键用户表使用数字,14 键表从已解析的字母方案派生。 - Nine
KeyShuangpin KeyHint - 一个数字键的键面提示,见
NineKeyShuangpin::key_hints。 - Nine
KeyShuangpin Table - 九键双拼的键位表(共享偏好
nine_key_shuangpin_custom_profile),形状与ShuangpinCustomTable相同,键换成数字:initials给 23 个声母(含zhchsh)各一个数字,finals给 33 个韵母各一个数字,zero_initials给 12 个零声母音节各一个两位数字编码。数字可以是0–9,ü写作v。表合不合法由 Engine 判定(见nine_key_shuangpin),顺序无关。 - Online
Query - 宿主交给云或 AI 服务的查询,回包必须原样带回;引擎在插入候选前核对当前组字的每个字段。
- Personal
Dictionary Entry - A user’s own dictionary entry. Pinyin keys are complete syllables joined by
'; wubi 1..=4 letters; quick phrases 1..=32 letters or digits; English 1..=64 letters. - Personal
Dictionary Page - Plugin
Command - 一条脚本插件指令(
/模式):插件在清单里声明的触发词和标题。宿主把会运行的插件声明的指令按执行顺序交给引擎,引擎按local::command::usable_plugin_commands决定哪些生效(用户指令表赢、插件先到先得),不照单全收。 - Plugin
Command Query - 插件指令要宿主去问的那一次:
/模式里输入以某个生效的插件触发词开头、这份预编辑串还没有缓存的行时才有。宿主把触发词和参数交给触发词的主人,再把结果连同这个值交回Session::apply_plugin_command_rows;会话或预编辑串已经变了的回答被拒绝。 - Punctuation
Marks - 已经解析好的标点样式与顿号键:宿主从偏好算出它(
corner_when_traditional在那之前就按繁体开关定成两者之一,「至少留一个」也已归一),引擎只认确定的值。缺省就是契约第 1 版的表加「只有\出顿号」。 - Quick
Phrase Entry - 宿主提供的一条 K 模式短语(来自已启用的短语表插件)。宿主已经校验过;Engine 仍然跳过它用不了的行,而不是照单全收。
- Replay
Result - Runtime
Paths - Scheme
Set - 会话允许运行的方案集合,每个方案占
SchemeType序号对应的那一位。缺省是SchemeSet::ALL,即全部方案,行为与没有这个集合时完全相同。 - Sentence
Association Options - Neural sentence association switches. The desktop-model switch is not among them: that model runs only as the input runtime’s settled reranker, which the host gates on the preference.
- Session
- Session
Options - Everything a session is built with.
learning_undois gone with the feature. - Session
Snapshot - A value copy of the composition; safe to hand to another thread.
candidate_sources,candidate_annotationsandcandidate_answers_keyare aligned withcandidates. - Shuangpin
Custom Table - 用户自定义双拼方案的键位表(共享偏好
shuangpin_custom_profile)。三张表与内置方案同构:initials只写三个多字母声母zhchsh,单字母声母仍在自己的字母键上;finals把 33 个韵母各放到一个键上;zero_initials给 12 个零声母音节各一个两键编码。键是小写字母或;,ü写作v。表合不合法由 Engine 判定(见shuangpin::custom),顺序无关。 - Shuangpin
Helpcode Modes - 双拼辅助码的触发方式开关(Windows v0.11.1
[helpcode]组的双拼专属键),随QueryRequest交给双拼引擎。默认值与 Windows 出厂配置一致;direct控制末尾直接,trigger_*控制末尾间接,mid_sentence*控制句中间接,direct_helpcode*控制逐音节直接。 - Syllable
Helpcode - 一个音节上的辅助码约束(
core/syllable_helpcode.h的SyllableHelpcode)。 - Word
Item - One candidate row. Every field the goldens record is here from the start, including the ones the overlays added.
- Wubi
Input Options
Enums§
- Bracket
Marks []出实心【】还是空心〖〗。- Candidate
Edge - Candidate
Source - Where a candidate row came from. The discriminant is the wire value; never reorder.
- Command
- Engine-level composition commands (the C++
metasequoia::Command, plusCommitRawWithoutLearning). The host facade numbers them its own way (host::Command). - Dictionary
State Record - The host’s record shape (engine-bridge
DictionaryStateRecord); positions and counts are range-checked on import. - Engine
Error - Error
Code EngineError的稳定数字码,供宿主和 C ABI 按数字分支,不必解析说明文字。编号与引擎库 C ABI 草案的返回码共用一个空间:0 是成功,4(不支持)、5(revision 不符)、7(会话已毒化)、8(空指针)留给 C ABI 自己的情形,引擎不产生它们。已发布的编号只追加、不改、不复用。- Frequency
Adjustment Mode - KeyGrid
- 九宫格会话把字母归成组码用的键盘。一个组码键上有几个字母,解码只认组码:路径搜索、锁定、切分、整句、简拼和英文混入都与「字母怎么变成码」无关,只经由这里的表。
- Korean
Layout - 韩语方案内的键位选择;宿主选项的编码保持 0 为现有两套式。
- Local
Input Mode - Nine
KeyShuangpin Error - 表为什么不能用,带出错的位置。宿主可以按种类给出自己的提示文字,
Display是给日志和代理看的英文。 - Nine
KeyShuangpin Kind - 九键双拼方案(#6572)。序号是宿主 ABI 值,名字是共享偏好
nine_key_shuangpin_profile的取值。内置方案只收录能找到完整、前后一致的公开描述的那几个,来源见.agents/notes/implemented/feature/2026-10-10-nine-key-shuangpin.md。 - Online
Input Mode - 在线请求的输入语义;缺省沿用原有的拼音及方案转换路径。
- Personal
Dictionary Kind - Which dictionary a personal entry or journal row belongs to. The ordinal is the host ABI value.
- Quote
Marks - 引号键出哪一组字。
Corner下'出「」、"出『』,按键对应,不按语义对应。 - Scheme
Type - Input scheme. The ordinal is part of the online identity (
"<scheme>:<raw>") and of the host ABI. - Shuangpin
Custom Profile Error - 表为什么不能用。宿主可以按种类给出自己的提示文字,
Display是给日志看的英文。 - Shuangpin
Custom Table Part - 表里的哪一部分。
- Shuangpin
Profile Kind - 双拼键位方案,序号是宿主 ABI 值(
EngineOptions::shuangpin_profile),新增方案只追加。 - Wubi
Profile Kind - 五笔码表版本。序号即宿主 ABI 值(
EngineOptions::wubi_profile)。
Constants§
- DEFAULT_
FIRST_ PAGE_ ROWS - 默认的首页候选行数:宿主每页候选数(
client-core的candidate_page_size)的缺省值。引擎只把它当「第一页能放几行」用。 - DEFAULT_
MAXIMUM_ RECORDS - EXTENDED_
ARGUMENT_ SYMBOLS arguments = "extended"的插件指令在触发词后面另外收的运算符号;数字另算。和 script-runtime 的abi::EXTENDED_ARGUMENT_SYMBOLS是同一份,由 host-api 的一致性测试守着(引擎不依赖解释器)。
Functions§
- close_
cached_ databases - Drop every cached journal, personal-context and local-mode connection, on every thread (a connection an operation is using closes when that operation ends). Call before deleting or replacing a data directory.
- dictionary_
state_ revision - SHA-256 hex over
text("msime-local-dictionary-state-v1")and every streamed record, wheretext(s)isinteger(len)then the bytes andintegeris a big-endian u64 (dictionary_revision.rs). Apple computes the same digest; keep the framing byte for byte. - dictionary_
table_ entries - 只读查询:ASCII 按编码前缀,含非 ASCII 字符时按词条字面包含匹配,空查询列出全部。拼音编码忽略分隔符、空格和大小写。个人行优先,再按精确匹配、权重、编码和词条排序。
- edit_
bundled_ dictionary_ entry - Re-weight (
Some) or delete (None) a row that is not user-inserted, journaled so replay repeats it;previous.weightmust be the current weight. Request ids behave as foredit_personal_dictionary. - edit_
personal_ dictionary - Add (
previous = None), remove (replacement = None) or replace, in one attached transaction with its receipt.previousmust still be user-inserted with the same weight. A request id (1..=128 of[A-Za-z0-9_-]) makes a retry of the same edit a no-op and a reuse for different content a failure. - ensure_
english_ schema - Create or migrate an
msime-english.dbto the schema the engine reads. Fixtures without one need it;prepare_runtime_pathscopies both dictionaries. - flush_
personal_ learning - Write every queued personal-context transition now. Those writes are otherwise delayed about 2 s; call this before reading the journal directly or re-preparing a generation.
- handwriting_
recognize - Recognise one character drawn as
strokesof(x, y)points on awidthbyheightcanvas, returning up to 12 candidates ordered byorder_handwriting_candidates.model_pathis a trusted packaged zinnia model such ashandwriting-zh_CN.model. - load_
helpcode_ keymap - Parse a helpcode table (helpcode_utils.cpp:54-88): BOM and
\rstripped,#lines skipped,left=rightwith the first up-to-twoa-zletters ofright, later lines overwrite. A missing custom file fails withUNKNOWN_HELPCODE_SCHEMA. - order_
handwriting_ candidates - Drop empty, oversized and duplicate entries, move the CJK ones first keeping order within each group, keep 12.
- personal_
dictionary_ entries - User-inserted entries (auto-created words included) in kind/key/value order; with
include_learned_pinyin, also learned or edited pinyin weights of shipped multi-character words. - preload_
japanese_ dictionary - Hands the engine the bytes of
msime-japanese.datforpath, the location a Japanese session reads its model from (RuntimePaths::resource(assets::JAPANESE_MODEL)orSessionOptions::japanese_dictionary), so a host without a file system (the browser) can type Japanese. False, with nothing changed, when the bytes are not a valid model; a later call for the same path replaces the earlier one. - prepare_
runtime_ paths - 校验代次 id(1 到 128 个
[0-9A-Za-z_-])和三个互不重叠的绝对路径根,建好user_data和cache,清掉被丢下的暂存目录,然后要么对已就绪的代次重新回放日志(补上它缺的 n-gram 表),要么在这次尝试独有的<id>.<随机串>.incoming里暂存、回放、写.ready再改名就位。暂存失败只删自己的目录;同一个代次被别的进程抢先发布时用那一份。 - prepare_
runtime_ paths_ for - 按会话允许的方案准备代次,资源目录只要有这些方案读的词库。
schemes读msime-pinyin.db(SchemeSet::reads_main_dictionary,即含全拼、双拼或五笔)时与prepare_runtime_paths完全相同:msime-pinyin.db和msime-english.db都必须在资源目录里,都复制进代次。不读它时(只有日文、韩语、越南语、藏文、粤语、注音、笔画这类方案)资源目录不必有它,代次里也没有它;这样的集合也不要求msime-english.db(SchemeSet::requires_english_dictionary),资源目录带了它就复制进代次、日志只回放英文行(replay_english),没带就连它也没有、日志一行也不回放(记录留在日志里,以后带英文库的代次照样回放)。粤语、注音、笔画的语言库和日文模型不经过代次,会话从SessionOptions给的路径或资源目录直接读。 - quarantine_
corrupt_ journal - 把 SQLite 无法读取为数据库的日志挪到旁边,让宿主从空日志启动,不再因为日志损坏而完全起不来。
- release_
idle_ personal_ models - 放掉进程里为下一个会话留着、没有会话在用的整句联想 n-gram store(连同它的模型和日志连接)。正在用的会话不受影响;之后第一个会话重新读日志。和
release_japanese_dictionary_cache一样由宿主的清缓存、内存告警动作调用。 - release_
japanese_ dictionary_ cache - Releases the process-level Japanese model cache while sessions that still use a model keep it
alive. Mobile hosts call this from their memory-pressure callback when there is no session
handle to pass to
Session::reset_cache. - replay_
user_ dictionary - Apply every operation in
(updated_at, rowid)order tomain_dbandenglish_db(J:1642-1735). Never panics or errors; failures are counted and described. - request_
autocorrect_ mask - The mask the quanpin dictionary runs with for a request: the two user switches, and when either is on, also missing and extra letters.
- reset_
learned_ data - The caller must have quiesced every session on these paths.
- reset_
learned_ data_ for reset_learned_data,按代次准备时的方案集合(crate::prepare_runtime_paths_for的schemes)换回词库:只换回、只要求这个集合读的那几个,与准备代次的规则相同。不读msime-pinyin.db的集合不要求也不复制它;不要求msime-english.db的集合在资源目录带了它时换回它,没带时只清空日志。还有会话开着时以Busy失败,规则同reset_learned_data。- resolve_
eighteen_ key_ shuangpin - 按当前内置或自定义双拼方案派生 18 键表,沿用 26 键方案校验。
- resolve_
fourteen_ key_ shuangpin - 按当前内置或自定义双拼方案派生 14 键表;自定义表沿用 26 键校验,不接受另一套字母用户表。
- resolve_
nine_ key_ shuangpin - 方案
kind的表:内置方案取内置的表,Custom校验custom(没有表时报缺了第一个声母)。 - shutdown
- Write every queued personal-context transition and stop the background thread that writes them, waiting for it to end. Call before unloading the engine or exiting the process; sessions still work afterwards, and the next transition they record starts the thread again.
- stage_
dictionary_ state - Build a complete replacement in an exclusively created
generation/<content_id>fromrecords, consumed lazily.Nonefrom the iterator is verified EOF; anErraborts. Duplicates and more thanmaximum_recordsrecords are rejected. Failure removes only the new directory (DS:144-231). - stream_
dictionary_ state - Operations by (dictionary, key, value), then positions, then selections, in one read transaction with
query_only(DS:93-138).emitreturning false stops. A missing journal emits nothing and is not created; a corrupt one is an error and is left untouched. - unload_
japanese_ dictionary - Forgets the model
preload_japanese_dictionaryput atpath; sessions already using it keep it until they end. - valid_
plugin_ argument - 插件指令的参数合不合规:小写字母;
extended时另外可以有数字和EXTENDED_ARGUMENT_SYMBOLS。 - validate_
nine_ key_ shuangpin_ table - 校验
table,合法时返回它对应的方案。同一张表(单位和键相同,顺序不论)总是返回同一个引用。 - validate_
personal_ dictionary_ entry - Normalise and check an entry: pinyin
"NI HAO"becomes"ni'hao"; English keys may differ from their display (dont/don't). - validate_
shuangpin_ custom_ profile - 只回答表能不能用。合法的表同样按内容留下一份,随后用它建会话(每次偏好变更都会先校验再重建)时直接复用,不再逐个编码检查一遍。
- wubi_
phrase_ code - 为两个及以上汉字取词组码;回调必须返回该字所有最长全码一致的前缀。
无法取码时返回对应字,空串或单字返回
None。
Type Aliases§
- Result
- Shared
Keymap - Loaded once per session (and per schema change) and shared by every provider.