@ftai/plugin-host-api 0.0.0-stage → 2.0.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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/lib/attachments.d.ts +38 -0
- package/lib/attachments.js +26 -0
- package/lib/fs.d.ts +53 -0
- package/lib/fs.js +14 -0
- package/lib/generated.d.ts +579 -0
- package/lib/generated.js +20 -0
- package/lib/index.d.ts +369 -0
- package/lib/index.js +110 -0
- package/lib/llm.d.ts +152 -0
- package/lib/llm.js +102 -0
- package/lib/porting.d.ts +35 -0
- package/lib/porting.js +127 -0
- package/package.json +40 -3
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件后端(宿主一半)的 SDK(docs/rust-host/architecture.md「与 0.12 写法的关系」),插件经 `@ftai/plugin-sdk/host` 使用。
|
|
3
|
+
* 插件后端运行在 FtAi 的 TS 插件进程里,写法与 0.12 插件相似:插件仍是 `apply(ctx, config)` 或继承服务类,`ctx.on`、
|
|
4
|
+
* `ctx.effect`、`inject` 照旧(上游 `cordis`),服务名、扩展点名与参数形状沿用 0.12;只在跨进程做不到时改,改动集中在三类,
|
|
5
|
+
* 对照表逐项写明:
|
|
6
|
+
*
|
|
7
|
+
* 1. 同步读取改为异步:如 `sessionProjections.stateOf()`、`appendPluginRecord()` 返回 Promise;
|
|
8
|
+
* 2. 活对象改为句柄:事件里的 agent、会话、工具调用是按 id 驻留的句柄(同一个 id 总是同一个对象),保留 `agent.ctx`;
|
|
9
|
+
* 3. 0.12 内部类型改为 SDK 类型:载荷类型由宿主的扩展点表生成(generated.ts),字段与会话格式 v4 一致。
|
|
10
|
+
*
|
|
11
|
+
* 宿主服务与扩展点的类型都由扩展点表生成,核心新增的服务与扩展点自动出现在这里;本文件是 SDK 以 0.12 写法另包一层的部分
|
|
12
|
+
* (工具、提示词段、会话投影、agent 与它们的扩展点、给插件前端的 remote)以及 0.12 的包里常用的函数。文件、附件与模型
|
|
13
|
+
* 另包的那一层在 fs.ts、attachments.ts、llm.ts。
|
|
14
|
+
*
|
|
15
|
+
* 单独成包是为了插件运行时只带这一层、不带 SDK 的构建工具。插件进程里本模块只有一份:插件运行时把对
|
|
16
|
+
* `@ftai/plugin-sdk/host`、本包与 `cordis` 的引用都解析到运行时自己的那一份,插件把 `@ftai/plugin-sdk` 与 `cordis`
|
|
17
|
+
* 写进 devDependencies 即可。
|
|
18
|
+
* @module @ftai/plugin-host-api
|
|
19
|
+
*/
|
|
20
|
+
import { Service, type Context } from 'cordis';
|
|
21
|
+
import type { AgentSource, JsonValue, ModelRef, PreToolDecision, PromptSection, StreamFrame, ToolContent, ToolFilter } from './generated.ts';
|
|
22
|
+
import type { AttachmentStoreService } from './attachments.ts';
|
|
23
|
+
import type { FileSystemService } from './fs.ts';
|
|
24
|
+
import type { LlmService } from './llm.ts';
|
|
25
|
+
export * from './generated.ts';
|
|
26
|
+
export * from './attachments.ts';
|
|
27
|
+
export * from './fs.ts';
|
|
28
|
+
export * from './llm.ts';
|
|
29
|
+
/** 会话头里插件可读的部分。 */
|
|
30
|
+
export interface SessionHeader {
|
|
31
|
+
/**
|
|
32
|
+
* 会话的工作目录。工具执行时是宿主这一步确认过的当前目录,换目录之后跟着换(相对路径按它解析);这个会话还没执行过
|
|
33
|
+
* 插件的工具时是会话头记的目录,没记时没有。
|
|
34
|
+
*/
|
|
35
|
+
readonly cwd?: string;
|
|
36
|
+
}
|
|
37
|
+
/** 会话的句柄:同一个 id 总是同一个对象。 */
|
|
38
|
+
export interface SessionHandle {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly header: SessionHeader;
|
|
41
|
+
}
|
|
42
|
+
/** 按 agent 生效的注册(0.12 的 `agent.ctx`):随 agent 结束撤销。 */
|
|
43
|
+
export interface AgentScope {
|
|
44
|
+
readonly tools: {
|
|
45
|
+
register(definition: ToolDefinition): () => void;
|
|
46
|
+
restrict(filter: ToolFilter): () => void;
|
|
47
|
+
};
|
|
48
|
+
readonly systemPrompt: {
|
|
49
|
+
section(section: PromptSection): () => void;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** agent 的句柄。agent 与会话一一对应。 */
|
|
53
|
+
export interface AgentHandle {
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly session: SessionHandle;
|
|
56
|
+
readonly ctx: AgentScope;
|
|
57
|
+
}
|
|
58
|
+
/** 一次工具调用的句柄(0.12 的 `ToolExecution`):同一次调用总是同一个对象,可以作 WeakMap 的键。 */
|
|
59
|
+
export interface ToolExecution {
|
|
60
|
+
readonly token: string;
|
|
61
|
+
readonly callId: string;
|
|
62
|
+
readonly name: string;
|
|
63
|
+
/** 模型给的参数(解析后的 JSON,同 0.12;解析不了时是原文)。 */
|
|
64
|
+
readonly arguments: unknown;
|
|
65
|
+
readonly agent: AgentHandle;
|
|
66
|
+
/**
|
|
67
|
+
* 发起这次调用的那一步实际用的模型(代替 0.12 读的 `agent.session.requestHeader().config`),子 agent 里是它自己的;
|
|
68
|
+
* 不是模型发起的调用没有。
|
|
69
|
+
*/
|
|
70
|
+
readonly model?: ModelRef;
|
|
71
|
+
/** 同 0.12:这次调用被取消(如轮次取消)时触发;只在工具执行期间可能触发。 */
|
|
72
|
+
readonly signal: AbortSignal;
|
|
73
|
+
}
|
|
74
|
+
/** 会话事件:会话文件里的 v4 行。 */
|
|
75
|
+
export interface SessionEvent {
|
|
76
|
+
readonly type: string;
|
|
77
|
+
readonly seq: number;
|
|
78
|
+
readonly time: number;
|
|
79
|
+
readonly data: unknown;
|
|
80
|
+
readonly ignorable?: true;
|
|
81
|
+
}
|
|
82
|
+
/** 插件记录:插件写进会话的可忽略事件。 */
|
|
83
|
+
export interface PluginRecord {
|
|
84
|
+
readonly type: string;
|
|
85
|
+
readonly seq: number;
|
|
86
|
+
readonly time: number;
|
|
87
|
+
readonly data: unknown;
|
|
88
|
+
}
|
|
89
|
+
/** 各种值都可以带的说明。 */
|
|
90
|
+
export interface ValueSchemaAnnotations {
|
|
91
|
+
description?: string;
|
|
92
|
+
title?: string;
|
|
93
|
+
default?: JsonValue;
|
|
94
|
+
examples?: JsonValue;
|
|
95
|
+
}
|
|
96
|
+
export interface StringValueSchemaSpec extends ValueSchemaAnnotations {
|
|
97
|
+
type: 'string';
|
|
98
|
+
enum?: readonly string[];
|
|
99
|
+
const?: string;
|
|
100
|
+
}
|
|
101
|
+
export interface NumberValueSchemaSpec extends ValueSchemaAnnotations {
|
|
102
|
+
type: 'number';
|
|
103
|
+
enum?: readonly number[];
|
|
104
|
+
const?: number;
|
|
105
|
+
}
|
|
106
|
+
export interface IntegerValueSchemaSpec extends ValueSchemaAnnotations {
|
|
107
|
+
type: 'integer';
|
|
108
|
+
enum?: readonly number[];
|
|
109
|
+
const?: number;
|
|
110
|
+
}
|
|
111
|
+
export interface BooleanValueSchemaSpec extends ValueSchemaAnnotations {
|
|
112
|
+
type: 'boolean';
|
|
113
|
+
enum?: readonly boolean[];
|
|
114
|
+
const?: boolean;
|
|
115
|
+
}
|
|
116
|
+
export interface NullValueSchemaSpec extends ValueSchemaAnnotations {
|
|
117
|
+
type: 'null';
|
|
118
|
+
enum?: readonly null[];
|
|
119
|
+
const?: null;
|
|
120
|
+
}
|
|
121
|
+
export interface ArrayValueSchemaSpec extends ValueSchemaAnnotations {
|
|
122
|
+
type: 'array';
|
|
123
|
+
items?: ValueSchemaSpec;
|
|
124
|
+
}
|
|
125
|
+
export interface ObjectValueSchemaSpec extends ValueSchemaAnnotations {
|
|
126
|
+
type: 'object';
|
|
127
|
+
properties?: ParameterSchemaSpec;
|
|
128
|
+
additionalProperties: boolean;
|
|
129
|
+
}
|
|
130
|
+
/** 任意 JSON 值,发给模型时只带说明。 */
|
|
131
|
+
export interface JsonValueSchemaSpec extends ValueSchemaAnnotations {
|
|
132
|
+
type: 'json';
|
|
133
|
+
}
|
|
134
|
+
export interface OneOfValueSchemaSpec extends ValueSchemaAnnotations {
|
|
135
|
+
oneOf: readonly [ValueSchemaSpec, ValueSchemaSpec, ...ValueSchemaSpec[]];
|
|
136
|
+
}
|
|
137
|
+
export type ValueSchemaSpec = StringValueSchemaSpec | NumberValueSchemaSpec | IntegerValueSchemaSpec | BooleanValueSchemaSpec | NullValueSchemaSpec | ArrayValueSchemaSpec | ObjectValueSchemaSpec | JsonValueSchemaSpec | OneOfValueSchemaSpec;
|
|
138
|
+
/** 一个参数:值的写法,必填的另标 `required: true`。 */
|
|
139
|
+
export type ParameterPropertySpec = ValueSchemaSpec & {
|
|
140
|
+
required?: true;
|
|
141
|
+
};
|
|
142
|
+
/** 参数表:参数名 → 写法。 */
|
|
143
|
+
export type ParameterSchemaSpec = {
|
|
144
|
+
[key: string]: ParameterPropertySpec;
|
|
145
|
+
[key: symbol]: never;
|
|
146
|
+
};
|
|
147
|
+
type Simplify<T> = {
|
|
148
|
+
[K in keyof T]: T[K];
|
|
149
|
+
} & {};
|
|
150
|
+
type StringKeyOf<S> = Extract<keyof S, string>;
|
|
151
|
+
type RequiredKeys<S> = {
|
|
152
|
+
[K in StringKeyOf<S>]: S[K] extends {
|
|
153
|
+
required: true;
|
|
154
|
+
} ? K : never;
|
|
155
|
+
}[StringKeyOf<S>];
|
|
156
|
+
type InferProperties<S, Depth extends unknown[]> = Simplify<{
|
|
157
|
+
[K in RequiredKeys<S>]: InferValueAt<S[K], Depth>;
|
|
158
|
+
} & {
|
|
159
|
+
[K in Exclude<StringKeyOf<S>, RequiredKeys<S>>]?: InferValueAt<S[K], Depth>;
|
|
160
|
+
}>;
|
|
161
|
+
type InferObject<S extends {
|
|
162
|
+
additionalProperties: boolean;
|
|
163
|
+
}, Depth extends unknown[]> = S extends {
|
|
164
|
+
properties: infer P;
|
|
165
|
+
} ? S['additionalProperties'] extends true ? InferProperties<P, Depth> & Record<string, JsonValue> : InferProperties<P, Depth> : S['additionalProperties'] extends true ? Record<string, JsonValue> : Record<string, never>;
|
|
166
|
+
type InferScalar<S, Fallback> = S extends {
|
|
167
|
+
const: infer C;
|
|
168
|
+
} ? C : S extends {
|
|
169
|
+
enum: readonly (infer E)[];
|
|
170
|
+
} ? E : Fallback;
|
|
171
|
+
type Deeper<Depth extends unknown[]> = [unknown, ...Depth];
|
|
172
|
+
type InferValueAt<S, Depth extends unknown[]> = Depth['length'] extends 16 ? JsonValue : S extends {
|
|
173
|
+
type: 'string';
|
|
174
|
+
} ? InferScalar<S, string> : S extends {
|
|
175
|
+
type: 'number' | 'integer';
|
|
176
|
+
} ? InferScalar<S, number> : S extends {
|
|
177
|
+
type: 'boolean';
|
|
178
|
+
} ? InferScalar<S, boolean> : S extends {
|
|
179
|
+
type: 'null';
|
|
180
|
+
} ? null : S extends {
|
|
181
|
+
type: 'array';
|
|
182
|
+
} ? S extends {
|
|
183
|
+
items: infer I;
|
|
184
|
+
} ? InferValueAt<I, Deeper<Depth>>[] : JsonValue[] : S extends {
|
|
185
|
+
type: 'object';
|
|
186
|
+
additionalProperties: boolean;
|
|
187
|
+
} ? InferObject<S, Deeper<Depth>> : S extends {
|
|
188
|
+
type: 'json';
|
|
189
|
+
} ? JsonValue : S extends {
|
|
190
|
+
oneOf: readonly unknown[];
|
|
191
|
+
} ? InferValueAt<S['oneOf'][number], Deeper<Depth>> : never;
|
|
192
|
+
/** 同 0.12 的 `tools`:值的写法对应的 TS 类型。 */
|
|
193
|
+
export type InferValue<S> = InferValueAt<S, []>;
|
|
194
|
+
/** 同 0.12 的 `tools`:参数表对应的参数对象类型。 */
|
|
195
|
+
export type InferArgs<S> = InferProperties<S, []>;
|
|
196
|
+
/**
|
|
197
|
+
* 申请提权的两个参数(`sandboxEscalation: true` 时由宿主加进参数表,写法与说明同核心的文件工具):为这一次调用申请更宽的
|
|
198
|
+
* 沙箱模式,两个一起给。宿主在执行之前已经按它们审批并定下了这一次的模式,插件只是读得到。
|
|
199
|
+
*/
|
|
200
|
+
export interface SandboxEscalationArgs {
|
|
201
|
+
sandbox_permissions?: 'workspace-write' | 'danger-full-access';
|
|
202
|
+
justification?: string;
|
|
203
|
+
}
|
|
204
|
+
/** 工具收到的参数:声明了 `sandboxEscalation` 时多出申请提权的两个参数。 */
|
|
205
|
+
export type ToolArgs<S, E extends boolean> = E extends true ? Simplify<InferArgs<S> & SandboxEscalationArgs> : InferArgs<S>;
|
|
206
|
+
/** 同 0.12 `tools` 的 `DefineToolOptions`:参数与结果的类型由写法推出。 */
|
|
207
|
+
export interface DefineToolOptions<S extends ParameterSchemaSpec, O extends ValueSchemaSpec, E extends boolean = false> {
|
|
208
|
+
readonly name: string;
|
|
209
|
+
readonly description: string;
|
|
210
|
+
readonly parameters: S;
|
|
211
|
+
readonly output: {
|
|
212
|
+
readonly schema: O;
|
|
213
|
+
/**
|
|
214
|
+
* 把执行结果变成给模型看的内容:文本块与图片块(图片先经 `ctx.attachments.saveImages` 存下,块里放它的引用)。
|
|
215
|
+
* 在插件进程里、执行之后调用。
|
|
216
|
+
*/
|
|
217
|
+
render(args: ToolArgs<S, E>, value: InferValue<NoInfer<O>>): readonly ToolContent[];
|
|
218
|
+
};
|
|
219
|
+
/** 形状有变:0.12 里是函数,跨进程只接受常量(见对照表)。 */
|
|
220
|
+
readonly isConcurrencySafe?: boolean;
|
|
221
|
+
/** 默认要用户审批(`tools/pre-execute` 的默认结论为 ask)。 */
|
|
222
|
+
readonly needsApproval?: boolean;
|
|
223
|
+
/**
|
|
224
|
+
* 可以为一次调用申请更宽的沙箱模式,同核心的文件工具(0.12 插件自己带的 `sandbox_permissions` 与 `justification`):
|
|
225
|
+
* 宿主给参数表加上这两个参数(`parameters` 里不能自带),执行之前按申请经审批定下这一次的模式,没批准时工具不执行、
|
|
226
|
+
* 模型收到说明;`ctx.fs.writeBytes` 带着这次调用(`execution: exec`)写入时按这个模式围住,越界被拒时错误的说明带被拒
|
|
227
|
+
* 标记与提权提示,抛给模型即可。批准只管这一次调用。
|
|
228
|
+
*/
|
|
229
|
+
readonly sandboxEscalation?: E;
|
|
230
|
+
execute(args: ToolArgs<S, E>, exec: ToolExecution): Promise<InferValue<NoInfer<O>>>;
|
|
231
|
+
}
|
|
232
|
+
/** 一个可以注册的工具(`defineTool` 的结果)。 */
|
|
233
|
+
export interface ToolDefinition {
|
|
234
|
+
readonly name: string;
|
|
235
|
+
readonly description: string;
|
|
236
|
+
readonly parameters: ParameterSchemaSpec;
|
|
237
|
+
readonly output: {
|
|
238
|
+
readonly schema: ValueSchemaSpec;
|
|
239
|
+
render(args: never, value: never): readonly ToolContent[];
|
|
240
|
+
};
|
|
241
|
+
readonly isConcurrencySafe?: boolean;
|
|
242
|
+
readonly needsApproval?: boolean;
|
|
243
|
+
readonly sandboxEscalation?: boolean;
|
|
244
|
+
execute(args: never, exec: ToolExecution): Promise<unknown>;
|
|
245
|
+
}
|
|
246
|
+
/** 同 0.12 `tools` 的 `defineTool`:参数与结果的类型由 `parameters` 与 `output.schema` 推出。 */
|
|
247
|
+
export declare function defineTool<const S extends ParameterSchemaSpec, const O extends ValueSchemaSpec, const E extends boolean = false>(options: DefineToolOptions<S, O, E>): ToolDefinition;
|
|
248
|
+
/** 插件记录的类型表:插件以模块扩充声明自己的记录(同 0.12 `session` 的 PluginRecordMap)。 */
|
|
249
|
+
export interface PluginRecordMap {
|
|
250
|
+
}
|
|
251
|
+
/** 会话投影的状态表:插件以模块扩充声明自己的投影(同 0.12 `session-projection` 的 SessionProjectionStateMap)。 */
|
|
252
|
+
export interface SessionProjectionStateMap {
|
|
253
|
+
}
|
|
254
|
+
/** 会话投影:从会话事件折叠出的状态,reducer 在插件进程里运行。 */
|
|
255
|
+
export interface ProjectionDefinition<Key extends string = string, State = unknown> {
|
|
256
|
+
readonly key: Key;
|
|
257
|
+
readonly stateVersion: number;
|
|
258
|
+
/** 状态的 schema(standard schema,如 zod)。 */
|
|
259
|
+
readonly stateSchema?: unknown;
|
|
260
|
+
init(header: SessionHeader): State;
|
|
261
|
+
apply(state: State, event: SessionEvent): State;
|
|
262
|
+
}
|
|
263
|
+
export interface ToolsService {
|
|
264
|
+
register(definition: ToolDefinition): () => void;
|
|
265
|
+
}
|
|
266
|
+
export interface SystemPromptService {
|
|
267
|
+
section(section: PromptSection): () => void;
|
|
268
|
+
}
|
|
269
|
+
export interface SessionProjectionsService {
|
|
270
|
+
register<Key extends keyof SessionProjectionStateMap & string>(definition: ProjectionDefinition<Key, SessionProjectionStateMap[Key]>): () => void;
|
|
271
|
+
/** 形状有变:0.12 里是同步的。读之前等本进程的折叠追上宿主已落盘的事件。 */
|
|
272
|
+
stateOf<Key extends keyof SessionProjectionStateMap & string>(session: SessionHandle, key: Key): Promise<SessionProjectionStateMap[Key] | undefined>;
|
|
273
|
+
}
|
|
274
|
+
export interface AgentsService {
|
|
275
|
+
get(id: string): AgentHandle | undefined;
|
|
276
|
+
list(): AgentHandle[];
|
|
277
|
+
}
|
|
278
|
+
declare module 'cordis' {
|
|
279
|
+
interface Context {
|
|
280
|
+
tools: ToolsService;
|
|
281
|
+
systemPrompt: SystemPromptService;
|
|
282
|
+
sessionProjections: SessionProjectionsService;
|
|
283
|
+
agents: AgentsService;
|
|
284
|
+
fs: FileSystemService;
|
|
285
|
+
attachments: AttachmentStoreService;
|
|
286
|
+
llm: LlmService;
|
|
287
|
+
}
|
|
288
|
+
interface Events {
|
|
289
|
+
'tools/pre-execute'(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> | PreToolDecision;
|
|
290
|
+
'agent/created'(payload: {
|
|
291
|
+
agent: AgentHandle;
|
|
292
|
+
source: AgentSource;
|
|
293
|
+
}): void | Promise<void>;
|
|
294
|
+
'agent/assistant-stream'(payload: {
|
|
295
|
+
agent: AgentHandle;
|
|
296
|
+
frame: StreamFrame;
|
|
297
|
+
}): void;
|
|
298
|
+
'session/event'(session: SessionHandle, event: SessionEvent): void;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** 同 0.12 的 `session`:插件记录事件的内容;不是插件记录时为 undefined。 */
|
|
302
|
+
export declare function pluginRecordOf(event: SessionEvent): PluginRecord | undefined;
|
|
303
|
+
/** 插件运行时装上的宿主连接;插件进程之外调用 SDK 的写入函数时报错。 */
|
|
304
|
+
export interface RuntimeBridge {
|
|
305
|
+
appendPluginRecord(session: SessionHandle, type: string, data: unknown): Promise<number>;
|
|
306
|
+
/**
|
|
307
|
+
* 挂载一个 remote 命名空间,返回撤销函数。`invoke` 调用服务上对应的方法,最后一个参数是这次调用的取消信号;
|
|
308
|
+
* 流式方法返回(异步)可迭代对象。
|
|
309
|
+
*/
|
|
310
|
+
mountRemote(ctx: Context, namespace: string, methods: readonly RemoteMethodEntry[], invoke: (method: string, args: unknown[], signal: AbortSignal) => unknown): () => void;
|
|
311
|
+
}
|
|
312
|
+
/** 由插件运行时调用一次,插件不要调用。 */
|
|
313
|
+
export declare function installRuntime(runtime: RuntimeBridge): void;
|
|
314
|
+
/**
|
|
315
|
+
* 形状有变:0.12 里是同步的。追加一条插件记录(可忽略的会话事件,模型看不到),返回它的 seq;
|
|
316
|
+
* 兑现时本进程的会话投影已经折叠了它(读到自己的写入)。
|
|
317
|
+
*/
|
|
318
|
+
export declare function appendPluginRecord<Type extends keyof PluginRecordMap & string>(session: SessionHandle, type: Type, data: PluginRecordMap[Type]): Promise<number>;
|
|
319
|
+
/**
|
|
320
|
+
* remote 失败的错误码 → `details` 的类型。插件以模块扩充登记自己的错误码,写成 `<插件 id>/<原因>`;
|
|
321
|
+
* 插件前端按 `error.code` 分支时 `error.details` 带上对应的类型。
|
|
322
|
+
*/
|
|
323
|
+
export interface RemoteErrorDetailsMap {
|
|
324
|
+
/** 请求不对(参数缺失或形状不对)。 */
|
|
325
|
+
'remote/bad-request': {
|
|
326
|
+
readonly issues?: readonly object[];
|
|
327
|
+
};
|
|
328
|
+
/** 调用被取消。 */
|
|
329
|
+
'remote/cancelled': {};
|
|
330
|
+
/** 插件后端出了没有预料到的错误;说明只给日志看。 */
|
|
331
|
+
'remote/internal': {};
|
|
332
|
+
}
|
|
333
|
+
export type RemoteErrorCode = keyof RemoteErrorDetailsMap & string;
|
|
334
|
+
/** remote 调用的失败:插件后端在失败处抛出,宿主把错误码、说明与 `details` 原样交给插件前端。 */
|
|
335
|
+
export declare class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends Error {
|
|
336
|
+
/** 结构上的标记:跨模块副本识别时不用 instanceof。 */
|
|
337
|
+
readonly isRemoteError = true;
|
|
338
|
+
readonly code: Code;
|
|
339
|
+
readonly details: RemoteErrorDetailsMap[Code];
|
|
340
|
+
constructor(code: Code, message: string, details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);
|
|
341
|
+
}
|
|
342
|
+
/** `@Remote` 的选项:流式方法逐条给出结果。 */
|
|
343
|
+
export interface RemoteMethodOptions {
|
|
344
|
+
readonly mode: 'stream';
|
|
345
|
+
}
|
|
346
|
+
/** 一个 remote 方法:服务上的方法名、界面调用的名字与是否流式。 */
|
|
347
|
+
export interface RemoteMethodEntry {
|
|
348
|
+
readonly member: string;
|
|
349
|
+
readonly name: string;
|
|
350
|
+
readonly stream: boolean;
|
|
351
|
+
}
|
|
352
|
+
type MethodDecorator = <This extends object, Args extends unknown[], Result>(method: (this: This, ...args: Args) => Result, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Result>) => void;
|
|
353
|
+
/**
|
|
354
|
+
* 同 0.12 的 `typert-protocol`:把一个公开的实例方法标为插件前端可调用。`@Remote` 是请求/应答,`@Remote('名字')` 换一个
|
|
355
|
+
* 调用名,`@Remote({ mode: 'stream' })` 是流式方法(返回可迭代对象,逐条交给界面)。参数与返回值只能是 JSON;
|
|
356
|
+
* 宿主在调用时另传最后一个参数 `signal: AbortSignal`,界面取消时触发。
|
|
357
|
+
*/
|
|
358
|
+
export declare function Remote<This extends object, Args extends unknown[], Result>(method: (this: This, ...args: Args) => Result, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Result>): void;
|
|
359
|
+
export declare function Remote(option: string | RemoteMethodOptions): MethodDecorator;
|
|
360
|
+
/**
|
|
361
|
+
* 同 0.12 的 `typert-protocol`:给插件前端提供 remote 服务的服务基类。服务名就是 remote 命名空间(可另给 `namespace`),
|
|
362
|
+
* 由插件 id 派生,所有插件里唯一;服务在时命名空间挂着,服务撤销(插件停用、卸载)时随之撤销。
|
|
363
|
+
* 插件进程之外(如插件自己的单测)不挂载,服务照常可用。
|
|
364
|
+
*/
|
|
365
|
+
export declare abstract class TypertRemoteService<T = never> extends Service<T> {
|
|
366
|
+
protected constructor(ctx: Context, serviceKey: string, options?: {
|
|
367
|
+
readonly namespace?: string;
|
|
368
|
+
});
|
|
369
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件后端(宿主一半)的 SDK(docs/rust-host/architecture.md「与 0.12 写法的关系」),插件经 `@ftai/plugin-sdk/host` 使用。
|
|
3
|
+
* 插件后端运行在 FtAi 的 TS 插件进程里,写法与 0.12 插件相似:插件仍是 `apply(ctx, config)` 或继承服务类,`ctx.on`、
|
|
4
|
+
* `ctx.effect`、`inject` 照旧(上游 `cordis`),服务名、扩展点名与参数形状沿用 0.12;只在跨进程做不到时改,改动集中在三类,
|
|
5
|
+
* 对照表逐项写明:
|
|
6
|
+
*
|
|
7
|
+
* 1. 同步读取改为异步:如 `sessionProjections.stateOf()`、`appendPluginRecord()` 返回 Promise;
|
|
8
|
+
* 2. 活对象改为句柄:事件里的 agent、会话、工具调用是按 id 驻留的句柄(同一个 id 总是同一个对象),保留 `agent.ctx`;
|
|
9
|
+
* 3. 0.12 内部类型改为 SDK 类型:载荷类型由宿主的扩展点表生成(generated.ts),字段与会话格式 v4 一致。
|
|
10
|
+
*
|
|
11
|
+
* 宿主服务与扩展点的类型都由扩展点表生成,核心新增的服务与扩展点自动出现在这里;本文件是 SDK 以 0.12 写法另包一层的部分
|
|
12
|
+
* (工具、提示词段、会话投影、agent 与它们的扩展点、给插件前端的 remote)以及 0.12 的包里常用的函数。文件、附件与模型
|
|
13
|
+
* 另包的那一层在 fs.ts、attachments.ts、llm.ts。
|
|
14
|
+
*
|
|
15
|
+
* 单独成包是为了插件运行时只带这一层、不带 SDK 的构建工具。插件进程里本模块只有一份:插件运行时把对
|
|
16
|
+
* `@ftai/plugin-sdk/host`、本包与 `cordis` 的引用都解析到运行时自己的那一份,插件把 `@ftai/plugin-sdk` 与 `cordis`
|
|
17
|
+
* 写进 devDependencies 即可。
|
|
18
|
+
* @module @ftai/plugin-host-api
|
|
19
|
+
*/
|
|
20
|
+
import { Service } from 'cordis';
|
|
21
|
+
export * from "./generated.js";
|
|
22
|
+
export * from "./attachments.js";
|
|
23
|
+
export * from "./fs.js";
|
|
24
|
+
export * from "./llm.js";
|
|
25
|
+
/** 同 0.12 `tools` 的 `defineTool`:参数与结果的类型由 `parameters` 与 `output.schema` 推出。 */
|
|
26
|
+
export function defineTool(options) {
|
|
27
|
+
return options;
|
|
28
|
+
}
|
|
29
|
+
const RECORD_TYPE = /^plugin:[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)*$/;
|
|
30
|
+
/** 同 0.12 的 `session`:插件记录事件的内容;不是插件记录时为 undefined。 */
|
|
31
|
+
export function pluginRecordOf(event) {
|
|
32
|
+
if (!RECORD_TYPE.test(event.type) || event.ignorable !== true)
|
|
33
|
+
return undefined;
|
|
34
|
+
return { type: event.type, seq: event.seq, time: event.time, data: event.data };
|
|
35
|
+
}
|
|
36
|
+
let bridge;
|
|
37
|
+
/** 由插件运行时调用一次,插件不要调用。 */
|
|
38
|
+
export function installRuntime(runtime) {
|
|
39
|
+
bridge = runtime;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* 形状有变:0.12 里是同步的。追加一条插件记录(可忽略的会话事件,模型看不到),返回它的 seq;
|
|
43
|
+
* 兑现时本进程的会话投影已经折叠了它(读到自己的写入)。
|
|
44
|
+
*/
|
|
45
|
+
export function appendPluginRecord(session, type, data) {
|
|
46
|
+
if (!RECORD_TYPE.test(type))
|
|
47
|
+
return Promise.reject(new Error(`invalid plugin record type ${type}`));
|
|
48
|
+
if (bridge === undefined)
|
|
49
|
+
return Promise.reject(new Error('appendPluginRecord is only available inside the plugin process'));
|
|
50
|
+
return bridge.appendPluginRecord(session, type, data);
|
|
51
|
+
}
|
|
52
|
+
/** remote 调用的失败:插件后端在失败处抛出,宿主把错误码、说明与 `details` 原样交给插件前端。 */
|
|
53
|
+
export class RemoteError extends Error {
|
|
54
|
+
/** 结构上的标记:跨模块副本识别时不用 instanceof。 */
|
|
55
|
+
isRemoteError = true;
|
|
56
|
+
code;
|
|
57
|
+
details;
|
|
58
|
+
constructor(code, message, details, options) {
|
|
59
|
+
super(message, options);
|
|
60
|
+
this.name = 'RemoteError';
|
|
61
|
+
this.code = code;
|
|
62
|
+
this.details = details;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** 方法上 `@Remote` 的标记(按方法函数本身记,与类、实例无关)。 */
|
|
66
|
+
const MARKS = new WeakMap();
|
|
67
|
+
export function Remote(first, _context) {
|
|
68
|
+
if (typeof first === 'function') {
|
|
69
|
+
MARKS.set(first, { name: undefined, stream: false });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const option = first;
|
|
73
|
+
return (method) => {
|
|
74
|
+
MARKS.set(method, { name: typeof option === 'string' ? option : undefined, stream: typeof option === 'object' && option.mode === 'stream' });
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/** 服务上标了 `@Remote` 的方法,按原型链从子类往上找,子类的同名方法优先。 */
|
|
78
|
+
function remoteMethodsOf(service) {
|
|
79
|
+
const methods = new Map();
|
|
80
|
+
for (let proto = Object.getPrototypeOf(service); proto !== null && proto !== Service.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
81
|
+
for (const member of Object.getOwnPropertyNames(proto)) {
|
|
82
|
+
const value = Object.getOwnPropertyDescriptor(proto, member)?.value;
|
|
83
|
+
const mark = typeof value === 'function' ? MARKS.get(value) : undefined;
|
|
84
|
+
const name = mark?.name ?? member;
|
|
85
|
+
if (mark !== undefined && !methods.has(name))
|
|
86
|
+
methods.set(name, { member, name, stream: mark.stream });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return [...methods.values()];
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* 同 0.12 的 `typert-protocol`:给插件前端提供 remote 服务的服务基类。服务名就是 remote 命名空间(可另给 `namespace`),
|
|
93
|
+
* 由插件 id 派生,所有插件里唯一;服务在时命名空间挂着,服务撤销(插件停用、卸载)时随之撤销。
|
|
94
|
+
* 插件进程之外(如插件自己的单测)不挂载,服务照常可用。
|
|
95
|
+
*/
|
|
96
|
+
export class TypertRemoteService extends Service {
|
|
97
|
+
constructor(ctx, serviceKey, options) {
|
|
98
|
+
super(ctx, serviceKey);
|
|
99
|
+
const namespace = options?.namespace ?? serviceKey;
|
|
100
|
+
const methods = remoteMethodsOf(this);
|
|
101
|
+
const invoke = (name, args, signal) => {
|
|
102
|
+
const entry = methods.find((method) => method.name === name);
|
|
103
|
+
if (entry === undefined)
|
|
104
|
+
throw new RemoteError('remote/bad-request', `unknown remote method ${name}`, {});
|
|
105
|
+
return this[entry.member](...args, signal);
|
|
106
|
+
};
|
|
107
|
+
ctx.effect(() => bridge?.mountRemote(ctx, namespace, methods, invoke) ?? (() => { }), `remote ${namespace}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=index.js.map
|
package/lib/llm.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模型(0.12 的 `ctx.llm`,0.12 的 `llm` 包):注册模型路由、按 id 取模型信息、插件直接调用模型。类型名与形状照 0.12,
|
|
3
|
+
* 只收插件直接调用模型用得到的部分:
|
|
4
|
+
* - `GenerateOptions` 没有 `tools`、`toolHistory`、`temperature`、`stop` 与 `purpose`;
|
|
5
|
+
* - 内容块只有文本、推理、图片、文件与工具调用;`finish` 块不带 `replayState`;
|
|
6
|
+
* - `BlockAssembler` 没有 `replayState` 与 `message()`(那是 Agent 回路落盘用的)。
|
|
7
|
+
*
|
|
8
|
+
* 与 0.12 一样不重试:失败作为最后一个 `finish` 块给出(`reason.kind` 为 `error` 或 `aborted`,带 `failure.code`),
|
|
9
|
+
* 要重试由调用方决定。请求消息与模型信息的形状由扩展点表生成(`RequestMessage`、`LlmModelInfo`)。
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import type { FileAttachmentRef, ImageAttachmentRef } from './attachments.ts';
|
|
13
|
+
import type { GenerateRequest, LlmModelInfo, ModelRoute, RequestMessage, RouteCredentials } from './generated.ts';
|
|
14
|
+
/** 一次失败的事实:稳定的错误码(如 `AUTH`、`RATE_LIMIT`)与说明。 */
|
|
15
|
+
export interface LlmFailure {
|
|
16
|
+
readonly message: string;
|
|
17
|
+
readonly code: string;
|
|
18
|
+
readonly status?: number;
|
|
19
|
+
readonly providerRetryAfterMs?: number;
|
|
20
|
+
readonly requestId?: string;
|
|
21
|
+
readonly offloadImages?: number;
|
|
22
|
+
}
|
|
23
|
+
export type FinishReason = {
|
|
24
|
+
readonly kind: 'stop';
|
|
25
|
+
} | {
|
|
26
|
+
readonly kind: 'tool-calls';
|
|
27
|
+
} | {
|
|
28
|
+
readonly kind: 'max-tokens';
|
|
29
|
+
} | {
|
|
30
|
+
readonly kind: 'aborted';
|
|
31
|
+
readonly failure: LlmFailure;
|
|
32
|
+
} | {
|
|
33
|
+
readonly kind: 'error';
|
|
34
|
+
readonly failure: LlmFailure;
|
|
35
|
+
};
|
|
36
|
+
/** 用量:`inputTokens` 不含缓存命中,缓存另计。 */
|
|
37
|
+
export interface TokenUsage {
|
|
38
|
+
readonly inputTokens: number;
|
|
39
|
+
readonly outputTokens: number;
|
|
40
|
+
readonly totalTokens?: number;
|
|
41
|
+
readonly cacheReadTokens?: number;
|
|
42
|
+
readonly cacheWriteTokens?: number;
|
|
43
|
+
readonly reasoningTokens?: number;
|
|
44
|
+
}
|
|
45
|
+
export interface TextBlock {
|
|
46
|
+
readonly type: 'text';
|
|
47
|
+
readonly text: string;
|
|
48
|
+
}
|
|
49
|
+
export interface ReasoningBlock {
|
|
50
|
+
readonly type: 'reasoning';
|
|
51
|
+
readonly text: string;
|
|
52
|
+
}
|
|
53
|
+
export interface ImageBlock {
|
|
54
|
+
readonly type: 'image';
|
|
55
|
+
readonly attachment: ImageAttachmentRef;
|
|
56
|
+
}
|
|
57
|
+
export interface FileBlock {
|
|
58
|
+
readonly type: 'file';
|
|
59
|
+
readonly attachment: FileAttachmentRef;
|
|
60
|
+
}
|
|
61
|
+
export interface ToolCallBlock {
|
|
62
|
+
readonly type: 'tool-call';
|
|
63
|
+
readonly id: string;
|
|
64
|
+
readonly name: string;
|
|
65
|
+
/** 模型给的参数原文。 */
|
|
66
|
+
readonly arguments: string;
|
|
67
|
+
}
|
|
68
|
+
export type ContentBlock = TextBlock | ReasoningBlock | ImageBlock | FileBlock | ToolCallBlock;
|
|
69
|
+
export type ContentBlockType = ContentBlock['type'];
|
|
70
|
+
/** 流式输出的一块(会话格式 v4 的 `StreamChunk`)。 */
|
|
71
|
+
export type StreamChunk = {
|
|
72
|
+
readonly type: 'block-start';
|
|
73
|
+
readonly index: number;
|
|
74
|
+
readonly blockType: ContentBlockType;
|
|
75
|
+
} | {
|
|
76
|
+
readonly type: 'text-delta';
|
|
77
|
+
readonly index: number;
|
|
78
|
+
readonly text: string;
|
|
79
|
+
} | {
|
|
80
|
+
readonly type: 'reasoning-delta';
|
|
81
|
+
readonly index: number;
|
|
82
|
+
readonly text: string;
|
|
83
|
+
} | {
|
|
84
|
+
readonly type: 'tool-call-delta';
|
|
85
|
+
readonly index: number;
|
|
86
|
+
readonly id: string;
|
|
87
|
+
readonly name?: string;
|
|
88
|
+
readonly argumentsDelta: string;
|
|
89
|
+
} | {
|
|
90
|
+
readonly type: 'block-end';
|
|
91
|
+
readonly index: number;
|
|
92
|
+
readonly block: ContentBlock;
|
|
93
|
+
} | {
|
|
94
|
+
readonly type: 'usage';
|
|
95
|
+
readonly usage: TokenUsage;
|
|
96
|
+
} | {
|
|
97
|
+
readonly type: 'finish';
|
|
98
|
+
readonly reason: FinishReason;
|
|
99
|
+
};
|
|
100
|
+
export interface GenerateOptions extends Omit<GenerateRequest, 'messages'> {
|
|
101
|
+
/**
|
|
102
|
+
* 只有 user 与 assistant 两种消息(同 0.12 的 `RequestMessage` 里插件用得到的部分)。图片发的是请求版本(按像素预算缩小),
|
|
103
|
+
* 模型不收图时换成「只收文本」的占位文本、请求照发;文件转成带路径的文本。
|
|
104
|
+
*/
|
|
105
|
+
readonly messages: readonly RequestMessage[];
|
|
106
|
+
/** 中止时断开模型请求,流以 `signal.reason` 结束。 */
|
|
107
|
+
readonly signal?: AbortSignal;
|
|
108
|
+
}
|
|
109
|
+
/** 0.12 的名字:模型信息,`defaultMaxTokens` 只在路由给模型配了输出上限时有。 */
|
|
110
|
+
export type LlmResolvedModelInfo = LlmModelInfo;
|
|
111
|
+
/** 模型层的失败(同 0.12):没有这条路由是 `NO_ADAPTER`,路由里没有这个模型是 `UNKNOWN_MODEL`。 */
|
|
112
|
+
export declare class LlmError extends Error {
|
|
113
|
+
readonly code: string;
|
|
114
|
+
readonly failure: LlmFailure;
|
|
115
|
+
constructor(message: string, code: string, options?: ErrorOptions);
|
|
116
|
+
}
|
|
117
|
+
export interface LlmService {
|
|
118
|
+
/**
|
|
119
|
+
* 注册一条模型路由(0.12 的 `registerAdapter`):一个 provider 与它的模型清单,每次请求经回调向插件取地址与凭据。
|
|
120
|
+
* 清单变了就撤销旧的注册、再注册一次。
|
|
121
|
+
*/
|
|
122
|
+
registerRoute(route: ModelRoute, credentials: (provider: string) => RouteCredentials | Promise<RouteCredentials>): () => void;
|
|
123
|
+
/** @throws LlmError */
|
|
124
|
+
resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<LlmResolvedModelInfo>;
|
|
125
|
+
/**
|
|
126
|
+
* 直接调用模型,逐块给出流式输出。路由、推理档位(模型不支持这个档位时失败,`off` 也不例外)或凭据在请求之前就失败时,
|
|
127
|
+
* 只有一个 `finish` 块。
|
|
128
|
+
*/
|
|
129
|
+
stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* 把流式输出拼成完整的内容块(同 0.12 的 `BlockAssembler`)。也接受只有增量、没有 `block-start` / `block-end` 的流;
|
|
133
|
+
* 一块已经由 `block-end` 结束后,同一个序号再来的增量忽略。
|
|
134
|
+
*/
|
|
135
|
+
export declare class BlockAssembler {
|
|
136
|
+
private readonly partials;
|
|
137
|
+
private readonly order;
|
|
138
|
+
private finishReason;
|
|
139
|
+
private reportedUsage;
|
|
140
|
+
/** 按流的顺序送进一块。 */
|
|
141
|
+
push(chunk: StreamChunk): void;
|
|
142
|
+
/** 到目前为止的全部块,按流的顺序;因输出上限截断时去掉工具调用(执行不了)。还没结束的块按已到的增量拼出。 */
|
|
143
|
+
blocks(): ContentBlock[];
|
|
144
|
+
/** 流被中断时能保留的部分:有非空白内容的文本与推理块,按流的顺序;工具调用不保留。 */
|
|
145
|
+
interruptedBlocks(): ContentBlock[];
|
|
146
|
+
/** `usage` 块给出的用量;还没到时为 undefined。 */
|
|
147
|
+
get usage(): TokenUsage | undefined;
|
|
148
|
+
/** `finish` 块给出的结束原因;流没有 `finish` 块就结束时是 `{ kind: 'stop' }`。 */
|
|
149
|
+
get finish(): FinishReason;
|
|
150
|
+
private ensure;
|
|
151
|
+
private assemble;
|
|
152
|
+
}
|