@ftai/plugin-host-api 2.0.0 → 2.3.0

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.
Files changed (47) hide show
  1. package/lib/attachments.d.ts +112 -1
  2. package/lib/capabilities.d.ts +99 -0
  3. package/lib/capabilities.js +21 -0
  4. package/lib/cmdline.d.ts +52 -0
  5. package/lib/cmdline.js +68 -0
  6. package/lib/credentials.d.ts +92 -0
  7. package/lib/credentials.js +41 -0
  8. package/lib/fs.d.ts +69 -5
  9. package/lib/generated.d.ts +3935 -316
  10. package/lib/generated.js +66 -6
  11. package/lib/index.d.ts +365 -69
  12. package/lib/index.js +44 -3
  13. package/lib/jobs.d.ts +88 -0
  14. package/lib/jobs.js +2 -0
  15. package/lib/llm.d.ts +124 -21
  16. package/lib/llm.js +45 -3
  17. package/lib/local-install.d.ts +38 -0
  18. package/lib/local-install.js +9 -0
  19. package/lib/permissions.d.ts +97 -0
  20. package/lib/permissions.js +11 -0
  21. package/lib/platform.d.ts +167 -0
  22. package/lib/platform.js +74 -0
  23. package/lib/porting.d.ts +23 -7
  24. package/lib/porting.js +692 -67
  25. package/lib/prompt.d.ts +117 -0
  26. package/lib/prompt.js +43 -0
  27. package/lib/runtime-context.d.ts +29 -0
  28. package/lib/runtime-context.js +6 -0
  29. package/lib/schedule-types.d.ts +333 -0
  30. package/lib/schedule-types.js +4 -0
  31. package/lib/session-events.d.ts +194 -0
  32. package/lib/session-events.js +2 -0
  33. package/lib/sessions.d.ts +246 -0
  34. package/lib/sessions.js +2 -0
  35. package/lib/settings.d.ts +86 -0
  36. package/lib/settings.js +13 -0
  37. package/lib/storage.d.ts +144 -0
  38. package/lib/storage.js +62 -0
  39. package/lib/subagents.d.ts +57 -0
  40. package/lib/subagents.js +17 -0
  41. package/lib/subprocess.d.ts +97 -0
  42. package/lib/subprocess.js +8 -0
  43. package/lib/tools.d.ts +212 -0
  44. package/lib/tools.js +2 -0
  45. package/lib/web.d.ts +192 -0
  46. package/lib/web.js +53 -0
  47. package/package.json +1 -1
@@ -0,0 +1,194 @@
1
+ /**
2
+ * 会话事件的类型:会话文件里的 v4 行(格式冻结,同 0.12 `dsh-session` 的 `SessionEventMap`)。`SessionEvent` 是按 `type` 区分的联合,
3
+ * `switch (event.type)` 或 `event.type === …` 收窄之后 `event.data` 就是对应的形状。没有列形状的事件(宿主自己的记录)`data` 是
4
+ * `unknown`,读的时候断言。插件记录同样:`plugin:*` 收窄不出形状,要类型时以模块扩充登记进 `SessionEventMap`,写 `SessionEvent<'plugin:x'>`。
5
+ * @module @ftai/plugin-host-api/session-events
6
+ */
7
+ import type { AgentCancelCause, JsonValue, LlmCallConfig, UserMessage } from './generated.ts';
8
+ import type { ContentBlock, LlmFailure, StreamChunk, TokenUsage } from './llm.ts';
9
+ /** 一轮为什么结束(同 0.12)。 */
10
+ export interface TurnEndReasonMap {
11
+ completed: {
12
+ readonly kind: 'completed';
13
+ };
14
+ /** 这一轮被取消。 */
15
+ aborted: {
16
+ readonly kind: 'aborted';
17
+ readonly reason: AgentCancelCause;
18
+ };
19
+ /** 被 `agent/pre-step` 否决。 */
20
+ blocked: {
21
+ readonly kind: 'blocked';
22
+ };
23
+ error: {
24
+ readonly kind: 'error';
25
+ readonly error: LlmFailure;
26
+ };
27
+ 'max-tokens': {
28
+ readonly kind: 'max-tokens';
29
+ };
30
+ /** 进程崩溃时没有结束的一轮,事后补上的结尾。 */
31
+ interrupted: {
32
+ readonly kind: 'interrupted';
33
+ };
34
+ /** 分叉时源会话还没结束的一轮,只出现在分叉出来的会话里。 */
35
+ forked: {
36
+ readonly kind: 'forked';
37
+ };
38
+ }
39
+ export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];
40
+ interface MessageBase {
41
+ readonly id: string;
42
+ readonly content: readonly ContentBlock[];
43
+ readonly source: {
44
+ readonly kind: string;
45
+ };
46
+ }
47
+ export interface SystemMessage extends MessageBase {
48
+ readonly role: 'system';
49
+ }
50
+ export interface AssistantMessage extends MessageBase {
51
+ readonly role: 'assistant';
52
+ }
53
+ export interface ToolResultMessage extends MessageBase {
54
+ readonly role: 'tool';
55
+ readonly toolCallId: string;
56
+ readonly isError?: boolean;
57
+ }
58
+ /** `assistant/message` 里压缩存放的流式输出(同 0.12 的 `AssistantStreamRecord`)。 */
59
+ export type AssistantStreamRecord = {
60
+ readonly type: 'text-chunks' | 'reasoning-chunks';
61
+ readonly time0: number;
62
+ readonly index: number;
63
+ readonly dt: readonly number[];
64
+ readonly texts: readonly string[];
65
+ } | {
66
+ readonly type: 'tool-call-chunks';
67
+ readonly time0: number;
68
+ readonly index: number;
69
+ readonly dt: readonly number[];
70
+ readonly id: string;
71
+ readonly name?: string;
72
+ readonly args: readonly string[];
73
+ } | {
74
+ readonly type: 'chunk';
75
+ readonly time: number;
76
+ readonly chunk: StreamChunk;
77
+ };
78
+ /** 事件类型 → `data` 的形状。 */
79
+ export interface SessionEventMap {
80
+ 'turn/start': {
81
+ readonly turn: number;
82
+ };
83
+ 'turn/end': {
84
+ readonly turn: number;
85
+ readonly reason: TurnEndReason;
86
+ };
87
+ 'step/start': {
88
+ readonly turn: number;
89
+ readonly step: number;
90
+ };
91
+ 'step/end': {
92
+ readonly turn: number;
93
+ readonly step: number;
94
+ };
95
+ 'user/message': UserMessage;
96
+ 'system/message': {
97
+ readonly turn: number;
98
+ readonly step: number;
99
+ readonly message: SystemMessage;
100
+ };
101
+ /** 这一步的模型输出,落盘时才有;要边生成边读用 `agent/assistant-stream`。`stream` 宿主总是写空(内容在 `message`,0.12 用它算首字延迟)。`interrupted` 是取消时已经生成的部分。 */
102
+ 'assistant/message': {
103
+ readonly turn: number;
104
+ readonly step: number;
105
+ readonly message: AssistantMessage;
106
+ readonly stream: readonly AssistantStreamRecord[];
107
+ readonly usage?: TokenUsage;
108
+ readonly interrupted?: true;
109
+ };
110
+ /** 一次没有留下消息的模型调用(失败、重试、取消)。 */
111
+ 'assistant/attempt': {
112
+ readonly turn: number;
113
+ readonly step: number;
114
+ readonly stream: readonly AssistantStreamRecord[];
115
+ };
116
+ /** `arguments` 是模型给的参数原文。 */
117
+ 'tool/call': {
118
+ readonly turn: number;
119
+ readonly step: number;
120
+ readonly callId: string;
121
+ readonly name: string;
122
+ readonly arguments: string;
123
+ };
124
+ 'tool/result': {
125
+ readonly turn: number;
126
+ readonly step: number;
127
+ readonly message: ToolResultMessage;
128
+ readonly error?: {
129
+ readonly name: string;
130
+ readonly code: string;
131
+ readonly reason?: string;
132
+ };
133
+ readonly meta?: JsonValue;
134
+ };
135
+ 'request/header': {
136
+ readonly header: {
137
+ readonly config: LlmCallConfig;
138
+ readonly tools?: readonly unknown[];
139
+ };
140
+ readonly reason: 'initial' | 'resume' | 'change' | 'series';
141
+ readonly startsSeries?: true;
142
+ };
143
+ 'request/context': {
144
+ readonly provider: string;
145
+ readonly model: string;
146
+ readonly contextWindow?: number;
147
+ };
148
+ 'session/end-seed': {
149
+ readonly inherited?: true;
150
+ };
151
+ 'developer/message': unknown;
152
+ 'agent/inbox/spliced': unknown;
153
+ 'approval/asked': unknown;
154
+ 'approval/decided': unknown;
155
+ 'approval/policy': unknown;
156
+ 'command/run': unknown;
157
+ 'command/done': unknown;
158
+ 'compaction/start': unknown;
159
+ 'compaction/summary': unknown;
160
+ 'compaction/end': unknown;
161
+ 'deliverables/presented': unknown;
162
+ 'goal/change': unknown;
163
+ 'llm/retry': unknown;
164
+ 'llm/retry-started': unknown;
165
+ 'model/selection': unknown;
166
+ 'permission/preset': unknown;
167
+ 'sandbox/mode': unknown;
168
+ 'session/title': unknown;
169
+ 'session/title-llm-request': unknown;
170
+ 'subagent/catalog': unknown;
171
+ 'subagent/descriptor': unknown;
172
+ 'todo/write': unknown;
173
+ 'working-directory/change': unknown;
174
+ }
175
+ /** 插件记录的事件类型(`appendPluginRecord` 写的)。 */
176
+ export type PluginRecordType = `plugin:${string}`;
177
+ export type SessionEventType = keyof SessionEventMap | PluginRecordType;
178
+ interface SessionEventLine<Type extends SessionEventType, Data> {
179
+ readonly type: Type;
180
+ readonly seq: number;
181
+ readonly time: number;
182
+ readonly data: Data;
183
+ readonly ignorable?: true;
184
+ /** 这条事件怎么进模型看得到的上下文;只有产生消息的事件有。 */
185
+ readonly surfaceOp?: 'append' | {
186
+ readonly op: 'replace';
187
+ readonly startSeq: number;
188
+ readonly endSeq: number;
189
+ };
190
+ readonly sourceEventSeqs?: readonly number[];
191
+ }
192
+ /** 会话事件:会话文件里的 v4 行。`SessionEvent<'turn/end'>` 是其中一种。 */
193
+ export type SessionEvent<Type extends SessionEventType = SessionEventType> = Type extends keyof SessionEventMap ? SessionEventLine<Type, SessionEventMap[Type]> : SessionEventLine<Type, unknown>;
194
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=session-events.js.map
@@ -0,0 +1,246 @@
1
+ /**
2
+ * 会话与会话投影的接口(0.12 的 `ctx.sessions`、`Session`、`ctx.sessionProjections`)。会话在宿主上,插件进程里只有按 id 驻留的句柄:
3
+ * 读日志都要跨进程,同步读取变成 Promise(对照表标 `awaited`);投影的 reducer 在插件进程里运行。
4
+ * @module @ftai/plugin-host-api/sessions
5
+ */
6
+ import type { LlmCallConfig, ToolSchema, UserMessage } from './generated.ts';
7
+ import type { AssistantMessage, PluginRecordType, SessionEvent, SessionEventType, SystemMessage, ToolResultMessage } from './session-events.ts';
8
+ /** 会话头里插件可读的部分。 */
9
+ export interface SessionHeader {
10
+ /**
11
+ * 会话的工作目录。工具执行时是宿主这一步确认过的当前目录,换目录之后跟着换(相对路径按它解析);这个会话还没执行过
12
+ * 插件的工具时是会话头记的目录,没记时没有。
13
+ */
14
+ readonly cwd?: string;
15
+ }
16
+ /** 完整的会话头(会话文件的首行,v4)。 */
17
+ export interface SessionLogHeader {
18
+ readonly type: 'session';
19
+ readonly version: number;
20
+ readonly id: string;
21
+ readonly createdAt: number;
22
+ readonly cwd?: string;
23
+ readonly parentSession?: string;
24
+ readonly isSeeded: boolean;
25
+ readonly origin?: string;
26
+ readonly delegationDepth: number;
27
+ readonly agentPreset?: string;
28
+ }
29
+ /** 模型历史里的 developer 消息。 */
30
+ export interface DeveloperMessage {
31
+ readonly role: 'developer';
32
+ readonly id: string;
33
+ readonly content: readonly unknown[];
34
+ readonly source: {
35
+ readonly kind: string;
36
+ };
37
+ }
38
+ /** 模型可见的一条消息(0.12 `llm` 的 `Message`)。 */
39
+ export type SessionMessage = UserMessage | SystemMessage | DeveloperMessage | AssistantMessage | ToolResultMessage;
40
+ /** 一段请求的头(0.12 的 `EpochHeader`):配置与工具清单。系统提示是模型可见的第一个节点,不在这里。 */
41
+ export interface EpochHeader {
42
+ readonly config: LlmCallConfig;
43
+ readonly adapterDefaults?: {
44
+ readonly reasoningEffort?: true;
45
+ readonly maxTokens?: true;
46
+ };
47
+ readonly tools?: readonly ToolSchema[];
48
+ }
49
+ /** 最近一次解析出的路由(0.12 的 `RequestContext`)。 */
50
+ export interface RequestContext {
51
+ readonly provider: string;
52
+ readonly model: string;
53
+ readonly contextWindow?: number;
54
+ }
55
+ /** 工具增减的折叠结果(0.12 `llm` 的 `ToolHistory`):这一段请求开头的工具与之后的增量。 */
56
+ export interface ToolHistory {
57
+ readonly tools: readonly ToolSchema[];
58
+ readonly updates: readonly {
59
+ readonly messageId: string;
60
+ readonly additions: readonly ToolSchema[];
61
+ }[];
62
+ }
63
+ /** 会话的句柄:同一个 id 总是同一个对象,直到会话从宿主内存卸下。 */
64
+ export interface SessionHandle {
65
+ readonly id: string;
66
+ readonly header: SessionHeader;
67
+ /** 形状有变:0.12 的 `session.header` 是同步的。没有这个会话时为 undefined。 */
68
+ readHeader(): Promise<SessionLogHeader | undefined>;
69
+ /** 形状有变:0.12 按区间同步读。按 seq 取 `fromSeq` 到 `toSeq`,两端都含,不给时不限。 */
70
+ readEvents(range?: {
71
+ readonly fromSeq?: number;
72
+ readonly toSeq?: number;
73
+ }): Promise<readonly SessionEvent[]>;
74
+ /** 形状有变:0.12 的 `session.surface` 是同步的。模型此刻看得到的事件,按顺序。 */
75
+ readSurface(): Promise<readonly SessionEvent[]>;
76
+ /** 形状有变:0.12 的 `session.seq` 是同步的。下一个事件的 seq,即日志长度;没有这个会话时为 0。 */
77
+ readSeq(): Promise<number>;
78
+ /** 读属性得到 Promise。分叉继承来的事件数,没有继承时为 0。 */
79
+ readonly inheritedEventCount: Promise<number>;
80
+ /** 读属性得到 Promise。这次进内存时带来的事件数:之后的事件都是这个宿主进程写的;不写进日志,卸下再读进来时会变。 */
81
+ readonly firstLiveSeq: Promise<number>;
82
+ /** 读属性得到 Promise。这次进内存之后产生的第一个事件:新分叉的从它自己的继承标记算,读进来的同 `firstLiveSeq`。 */
83
+ readonly firstLifecycleSeq: Promise<number>;
84
+ /** 形状有变:返回 Promise。这个会话自己写下的事件,不含继承的。 */
85
+ ownEvents(): Promise<readonly SessionEvent[]>;
86
+ /** 形状有变:返回 Promise。这个 seq 存在且不是继承来的。 */
87
+ isOwnSeq(seq: number): Promise<boolean>;
88
+ /**
89
+ * 形状有变:返回 Promise,只收插件记录的类型(`plugin:...`),一律可忽略,模型看不到;其余类型报错。`data` 要能无损地写成 JSON。
90
+ * 兑现时本进程的会话投影已经折叠了它。结果是记下的事件。
91
+ */
92
+ append<Type extends PluginRecordType>(type: Type, data: unknown): Promise<SessionEvent<Type>>;
93
+ /** 形状有变:返回 Promise。最近一段请求的头;还没请求过时为 undefined。只要这一步的模型时读 `exec.model`。 */
94
+ requestHeader(): Promise<EpochHeader | undefined>;
95
+ /** 形状有变:返回 Promise。最新的 provider、model 与上下文窗口;还没有时为 undefined。 */
96
+ requestContext(): Promise<RequestContext | undefined>;
97
+ /** 形状有变:返回 Promise,每次从日志整份折叠。 */
98
+ toolHistory(): Promise<ToolHistory>;
99
+ /** 形状有变:返回 Promise。模型此刻看到的消息,消息投影已生效,日志不变;投影失败(超时、插件进程不在)时拒绝。 */
100
+ deriveMessages(): Promise<readonly SessionMessage[]>;
101
+ /** 形状有变:返回 Promise。一条事件对应的模型可见消息,不产生消息时为 null;失败同 `deriveMessages`。 */
102
+ deriveEventMessage(event: SessionEvent): Promise<SessionMessage | null>;
103
+ }
104
+ /** 消息投影看到的这个事件之前的历史(0.12 的 `SessionMessageProjectionContext`)。入参是 JSON 副本,不是宿主里的对象。 */
105
+ export interface SessionMessageProjectionContext {
106
+ /** 模型可见节点(事件的 seq),按顺序。 */
107
+ readonly nodes: readonly number[];
108
+ /** 这个事件之前的日志原文。 */
109
+ readonly events: readonly SessionEvent[];
110
+ /** `events` 第一个事件的 seq。 */
111
+ readonly baseSeq: number;
112
+ /** 之前的投影改写过的消息,键是节点的 seq。 */
113
+ readonly messages: ReadonlyMap<number, SessionMessage>;
114
+ }
115
+ /**
116
+ * 插件拥有的事件怎么改写既有消息的内容(0.12 的 `SessionMessageProjection`)。在插件进程里运行,派生时宿主等它,所以要快、要是纯函数,
117
+ * 不要调用宿主。只能改 user、assistant、tool 消息的内容,id、角色、来源与工具调用不能动。
118
+ */
119
+ export interface SessionMessageProjection<Type extends SessionEventType = SessionEventType> {
120
+ /** 要解释的事件类型:插件记录(`plugin:...`),`plugin:ftai/` 留给 FtAi 自己。 */
121
+ readonly type: Type;
122
+ /**
123
+ * @returns 改写了的消息,键是节点的 seq。抛错、超时(30 秒)或插件进程不在时这一步失败,不会按原文发给模型:
124
+ * 插件进程正在起时宿主先等它激活(最长 60 秒),崩溃后在等待重启时不等,直接失败。
125
+ */
126
+ project(event: SessionEvent<Type>, context: SessionMessageProjectionContext): ReadonlyMap<number, SessionMessage> | Promise<ReadonlyMap<number, SessionMessage>>;
127
+ }
128
+ /** `ctx.sessions.create`、`prepare` 的选项:只收工作目录。种子与血缘由宿主拥有,给了报错;种子只经 `fork` 带入。 */
129
+ export interface CreateSessionOptions {
130
+ readonly meta?: {
131
+ readonly cwd?: string;
132
+ };
133
+ }
134
+ /** 同 0.12 的 `ctx.sessions`。插件记录用 `appendPluginRecord()`,读日志用会话的句柄。 */
135
+ export interface SessionsService {
136
+ /** 本进程登记的消息投影(同一个进程里全部 TS 插件的)。 */
137
+ readonly messageProjections: readonly SessionMessageProjection[];
138
+ /** 登记一个事件类型的投影,随调用者撤销。同一个类型已有登记时抛错。撤销之后这种记录被忽略,模型看到的回到原文。 */
139
+ registerMessageProjection(projection: SessionMessageProjection): () => void;
140
+ /**
141
+ * 形状有变:返回 Promise。建会话并拿着它,随调用者撤销。写进磁盘后是普通会话(进会话目录);要驱动它用 `ctx.agents.resume`。
142
+ * id 已有时报 `session/exists`。
143
+ */
144
+ create(id?: string, options?: CreateSessionOptions): Promise<SessionHandle>;
145
+ /** 形状有变:返回 Promise。校验 id 与工作目录,不进内存;`enter` 之前句柄读不到、写不了这个会话。 */
146
+ prepare(id?: string, options?: CreateSessionOptions): Promise<SessionHandle>;
147
+ /** 形状有变:返回 Promise。把 `prepare` 的会话放进内存,宿主此时发 `session/created`。结果是放开它的函数:调用后下一次核对时(最长约 1 分钟)卸下。 */
148
+ enter(session: SessionHandle): Promise<() => Promise<void>>;
149
+ /** 形状有变:`session/created` 由宿主在 `enter` 时发,不能否决;这里只等它发到监听者手里。再调一次报错。 */
150
+ announce(session: SessionHandle): Promise<void>;
151
+ /** 等已发出的 `session/event` 到了监听者手里,再按顺序等 `session/flush` 的监听者,第一个失败的错误交回。宿主记事件时同步落盘,结果总是 true。 */
152
+ flush(session: SessionHandle): Promise<boolean>;
153
+ /** 形状有变:返回 Promise。宿主内存里的会话;不在内存里(没用到或已卸下)时为 undefined。 */
154
+ get(id: string): Promise<SessionHandle | undefined>;
155
+ /** 形状有变:返回 Promise。宿主内存里全部的会话,按建立的先后。 */
156
+ list(): Promise<SessionHandle[]>;
157
+ /**
158
+ * 形状有变:返回 Promise。从来源的 `boundary`(含,不给时是最后一个事件)分叉,种子只经这里带入。新会话落盘、发 `agent/created`、
159
+ * 挂到来源所在的工作区,并由调用者拿着。空的来源没有可分叉的事件,报 `session/fork-unavailable`。
160
+ */
161
+ fork(source: SessionHandle | string, boundary?: number, childSessionId?: string): Promise<SessionHandle>;
162
+ }
163
+ /** 这个会话的轮次与步骤边界(同 0.12 Agent 回路提供的单元)。 */
164
+ export interface TurnBoundaryProjection {
165
+ /** 开着的一轮的 `turn/start`,两轮之间为 null。 */
166
+ readonly openTurnStartSeq: number | null;
167
+ /** 最后一个 `step/start`,第一步之前为 null。 */
168
+ readonly lastStepStartSeq: number | null;
169
+ /** 最后一个步骤边界,第一步之前为 null。 */
170
+ readonly lastStepBoundary: {
171
+ readonly kind: 'start' | 'end';
172
+ readonly seq: number;
173
+ } | null;
174
+ /** 最后一个 `turn/start` 的轮次,第一轮之前是 0。 */
175
+ readonly lastTurn: number;
176
+ }
177
+ /** 会话投影的状态表:插件以模块扩充声明自己的投影(同 0.12 `session-projection` 的 SessionProjectionStateMap)。`turnBoundary` 一直有。 */
178
+ export interface SessionProjectionStateMap {
179
+ turnBoundary: TurnBoundaryProjection;
180
+ }
181
+ /** 投影给界面的视图表:插件以模块扩充声明(同 0.12 `session-projection` 的 SessionProjectionMap)。视图经插件自己的 remote 交给界面。 */
182
+ export interface SessionProjectionMap {
183
+ }
184
+ /** 会话投影:从会话事件折叠出的状态,reducer 在插件进程里运行。 */
185
+ export interface ProjectionDefinition<Key extends string = string, State = unknown, View = unknown> {
186
+ readonly key: Key;
187
+ readonly stateVersion: number;
188
+ /** 状态的 schema(standard schema,如 zod):恢复检查点时校验。 */
189
+ readonly stateSchema?: unknown;
190
+ /** @param inheritedEventCount 分叉继承来的事件数。 */
191
+ init(header: SessionHeader, inheritedEventCount: number): State;
192
+ /** 不关心的事件返回同一个引用(`Object.is`),之后什么都不用算。 */
193
+ apply(state: State, event: SessionEvent): State;
194
+ /** 给界面的视图;只给插件自己用的单元不写。 */
195
+ readonly wire?: {
196
+ /** 视图的 schema,交出去之前校验。 */
197
+ readonly viewSchema: unknown;
198
+ /** 状态 → 视图。对象形式的视图没变时要复用引用,否则每次状态变化都会通知。 */
199
+ view(state: State): View;
200
+ };
201
+ }
202
+ /** 视图变了的通知:`seq` 是引起变化的事件(只有实时事件通知,整批回放不通知)。 */
203
+ export type ProjectionChangeListener = (session: SessionHandle, key: string, value: unknown, seq: number) => void;
204
+ /** 同一个游标上全部视图的读数(0.12 的 `ProjectionSnapshot`)。 */
205
+ export interface ProjectionSnapshot {
206
+ /** 这些值反映到的最后一个事件;空日志是 -1。 */
207
+ readonly asOfSeq: number;
208
+ readonly values: Readonly<Record<string, unknown>>;
209
+ }
210
+ /** 一个单元的检查点:状态、折叠到的 seq、产生它的 `stateVersion`。只是折叠的捷径,不是事实来源。 */
211
+ export interface ProjectionCheckpointRow {
212
+ readonly ver: number;
213
+ readonly seq: number;
214
+ readonly val: unknown;
215
+ }
216
+ /** 一个会话的检查点,键是投影的 key。宿主不托管,要跨重启由插件自己存(值要能写成 JSON)。 */
217
+ export type ProjectionCheckpoint = Readonly<Record<string, ProjectionCheckpointRow>>;
218
+ export interface SessionProjectionsService {
219
+ register<Key extends keyof SessionProjectionStateMap & string>(definition: ProjectionDefinition<Key, SessionProjectionStateMap[Key], Key extends keyof SessionProjectionMap ? SessionProjectionMap[Key] : unknown>): () => void;
220
+ /** 同 0.12,直接写明状态类型(`register<'todos', Todo[] | null>`):这样注册的单元不在状态表里,`stateOf` 读不到类型。 */
221
+ register<Key extends string, State, View = unknown>(definition: ProjectionDefinition<Key, State, View>): () => void;
222
+ /** 形状有变:0.12 里是同步的。读之前等本进程的折叠追上宿主已落盘的事件。 */
223
+ stateOf<Key extends keyof SessionProjectionStateMap & string>(session: SessionHandle, key: Key): Promise<SessionProjectionStateMap[Key] | undefined>;
224
+ /** 订阅带 `wire` 的单元的视图变化,随调用者撤销。有订阅时每个有新事件的会话都会折叠一次。 */
225
+ onChanged(listener: ProjectionChangeListener): () => void;
226
+ /** 形状有变:返回 Promise。各单元来自同一个游标;第一次用到这个会话时要向宿主取事件。 */
227
+ snapshot(session: SessionHandle, keys?: readonly string[]): Promise<ProjectionSnapshot>;
228
+ /** 只读已经折叠的视图,同步;这个会话还没折叠时为 undefined。可能落后于日志。 */
229
+ cachedSnapshot(session: SessionHandle, keys?: readonly string[]): ProjectionSnapshot | undefined;
230
+ /** 形状有变:返回 Promise。全部单元的检查点,`val` 是脱离内部引用的拷贝。 */
231
+ checkpoint(session: SessionHandle): Promise<ProjectionCheckpoint>;
232
+ /** `restore` 要读的尾部从哪个 seq 开始。 */
233
+ restoreFloor(checkpoint: ProjectionCheckpoint): number | undefined;
234
+ /** 不读日志,从检查点算出视图;版本不对或校验不过的单元不给。 */
235
+ viewCheckpoint(checkpoint: ProjectionCheckpoint, keys?: readonly string[]): Readonly<Record<string, unknown>>;
236
+ /**
237
+ * 从检查点与日志的尾部(`await session.readEvents({ fromSeq: baseSeq })`)恢复,不碰已折叠的状态。行不可用且 `baseSeq` 大于 0 时抛错,
238
+ * 从 0 重读。结果是读数与刷新后的检查点。
239
+ */
240
+ restore(checkpoint: ProjectionCheckpoint, events: readonly SessionEvent[], baseSeq: number, header: SessionHeader, inheritedEventCount: number): {
241
+ readonly snapshot: ProjectionSnapshot;
242
+ readonly checkpoint: ProjectionCheckpoint;
243
+ };
244
+ /** 形状有变:返回 Promise。同 `restore`,并把结果装进这个会话的折叠,之后跟着 `session/event` 继续。 */
245
+ hydrate(session: SessionHandle, checkpoint: ProjectionCheckpoint, events: readonly SessionEvent[], baseSeq: number): Promise<ProjectionSnapshot>;
246
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=sessions.js.map
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 插件自己的配置文档(同 0.12 的 `ctx.settings`)。每个插件一份,存在它的数据目录里;加载时读出来,按插件的 `Config` 校验后作为
3
+ * `apply` 的第二个参数。`ns` 就是插件的包名,只能是插件自己:`describe()` 只给自己,写别的 `ns` 报错。
4
+ *
5
+ * 改了配置时默认重新加载这个插件(撤销再激活,拿到新配置);`configure({ auto: false })` 之后不重新加载,由插件听
6
+ * `settings/document-updated` 自己处理。
7
+ * @module
8
+ */
9
+ import type { Fiber } from 'cordis';
10
+ /** 一个密钥字段的位置:`Config` 的 JSON Schema 里写了 `writeOnly: true` 的字段(zod 写 `.meta({ writeOnly: true })`)。 */
11
+ export interface RedactedSecret {
12
+ readonly path: readonly string[];
13
+ /** 这个字段现在有没有值。 */
14
+ readonly set: boolean;
15
+ }
16
+ /** 插件配置的一份视图(同 0.12)。 */
17
+ export interface SettingsDescriptor {
18
+ /** 插件的包名。 */
19
+ readonly ns: string;
20
+ /** 同 `configure` 的 `auto`:改了配置时是否重新加载。 */
21
+ readonly autoGenerate: boolean;
22
+ /** `Config` 的 JSON Schema;它给不出时没有。 */
23
+ readonly schema?: unknown;
24
+ /** 文档与宿主给的配置合起来、按 `Config` 校验后的值。`redactSecrets` 时去掉密钥字段;`Config` 给不出 JSON Schema 时不知道哪些是密钥,一律不给。 */
25
+ readonly value?: unknown;
26
+ /** 这份配置的版本:写的时候带上,配置变过就报 `SETTINGS_CONFLICT`。进程重启后从 0 算起。 */
27
+ readonly revision: number;
28
+ /** 宿主给的配置(第三方插件没有),带默认值。 */
29
+ readonly base?: unknown;
30
+ /** 文档的内容,没有文档时没有。 */
31
+ readonly user?: unknown;
32
+ readonly applies: 'live';
33
+ /** `redactSecrets` 时有:每个密钥字段的位置与有没有值。 */
34
+ readonly secrets?: readonly RedactedSecret[];
35
+ }
36
+ export interface SettingsDescribeOptions {
37
+ /** 去掉密钥字段:视图要离开插件进程(交给界面)时用。 */
38
+ readonly redactSecrets?: boolean;
39
+ }
40
+ /** 按路径改一处:`set` 写值,缺的对象补上;`unset` 去掉,数组里的元素连位置一起去掉。空路径是文档的根。 */
41
+ export type SettingsPathOp = {
42
+ readonly op: 'set';
43
+ readonly path: readonly string[];
44
+ readonly value: unknown;
45
+ } | {
46
+ readonly op: 'unset';
47
+ readonly path: readonly string[];
48
+ };
49
+ /** 写的时候带的版本过期了(同 0.12)。 */
50
+ export declare class SettingsConflictError extends Error {
51
+ readonly expected: number;
52
+ readonly actual: number;
53
+ readonly code = "SETTINGS_CONFLICT";
54
+ constructor(ns: string, expected: number, actual: number);
55
+ }
56
+ /** 同 0.12 的 `ctx.settings`。`ns` 只能是调用方插件自己。 */
57
+ export interface SettingsService {
58
+ /** 文档内容不合法时抛错。声明了 `Config` 的插件是一项,没声明的是空的。 */
59
+ describe(options?: SettingsDescribeOptions): SettingsDescriptor[];
60
+ /** 按 `Config` 校验后写进文档,不合法时不写。下面三个写法相同:`patch` 合并进去;`section` 换掉整份;`ops` 按路径改。 */
61
+ update(ns: string, patch: object, expectedRevision?: number): Promise<void>;
62
+ replace(ns: string, section: object, expectedRevision?: number): Promise<void>;
63
+ mutate(ns: string, ops: readonly SettingsPathOp[], expectedRevision?: number): Promise<void>;
64
+ /**
65
+ * 改了配置时怎么办:`auto`(默认 true)重新加载这个插件;false 时不重新加载,插件听 `settings/document-updated`,读 `describe()` 自己处理。
66
+ * 随 `owner`(默认调用方的 fiber,要属于这个插件)撤销;一个插件只能有一份,重复时抛错。
67
+ */
68
+ configure(presentation: {
69
+ readonly auto?: boolean;
70
+ }, owner?: Fiber): () => void;
71
+ /** 总是 true:文档在插件自己的数据目录里。 */
72
+ readonly writable: boolean;
73
+ /** 文档的路径,可能还不存在。 */
74
+ readonly documentPath: string;
75
+ /** 文档不存在时建一份空的,给出路径。 */
76
+ prepareDocument(): Promise<string>;
77
+ }
78
+ declare module 'cordis' {
79
+ interface Context {
80
+ settings: SettingsService;
81
+ }
82
+ interface Events {
83
+ /** 这个插件的配置变了(经 `ctx.settings` 写的,或 `describe()` 发现文档被改过)。只发给这个插件自己。 */
84
+ 'settings/document-updated'(ns: string, revision: number): void;
85
+ }
86
+ }
@@ -0,0 +1,13 @@
1
+ /** 写的时候带的版本过期了(同 0.12)。 */
2
+ export class SettingsConflictError extends Error {
3
+ expected;
4
+ actual;
5
+ code = 'SETTINGS_CONFLICT';
6
+ constructor(ns, expected, actual) {
7
+ super(`settings namespace "${ns}" changed since it was read (expected revision ${String(expected)}, now ${String(actual)})`);
8
+ this.expected = expected;
9
+ this.actual = actual;
10
+ this.name = 'SettingsConflictError';
11
+ }
12
+ }
13
+ //# sourceMappingURL=settings.js.map