@ftai/plugin-host-api 0.0.0-stage → 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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/lib/attachments.d.ts +149 -0
  4. package/lib/attachments.js +26 -0
  5. package/lib/capabilities.d.ts +99 -0
  6. package/lib/capabilities.js +21 -0
  7. package/lib/cmdline.d.ts +52 -0
  8. package/lib/cmdline.js +68 -0
  9. package/lib/credentials.d.ts +92 -0
  10. package/lib/credentials.js +41 -0
  11. package/lib/fs.d.ts +117 -0
  12. package/lib/fs.js +14 -0
  13. package/lib/generated.d.ts +4198 -0
  14. package/lib/generated.js +80 -0
  15. package/lib/index.d.ts +665 -0
  16. package/lib/index.js +151 -0
  17. package/lib/jobs.d.ts +88 -0
  18. package/lib/jobs.js +2 -0
  19. package/lib/llm.d.ts +255 -0
  20. package/lib/llm.js +144 -0
  21. package/lib/local-install.d.ts +38 -0
  22. package/lib/local-install.js +9 -0
  23. package/lib/permissions.d.ts +97 -0
  24. package/lib/permissions.js +11 -0
  25. package/lib/platform.d.ts +167 -0
  26. package/lib/platform.js +74 -0
  27. package/lib/porting.d.ts +51 -0
  28. package/lib/porting.js +752 -0
  29. package/lib/prompt.d.ts +117 -0
  30. package/lib/prompt.js +43 -0
  31. package/lib/runtime-context.d.ts +29 -0
  32. package/lib/runtime-context.js +6 -0
  33. package/lib/schedule-types.d.ts +333 -0
  34. package/lib/schedule-types.js +4 -0
  35. package/lib/session-events.d.ts +194 -0
  36. package/lib/session-events.js +2 -0
  37. package/lib/sessions.d.ts +246 -0
  38. package/lib/sessions.js +2 -0
  39. package/lib/settings.d.ts +86 -0
  40. package/lib/settings.js +13 -0
  41. package/lib/storage.d.ts +144 -0
  42. package/lib/storage.js +62 -0
  43. package/lib/subagents.d.ts +57 -0
  44. package/lib/subagents.js +17 -0
  45. package/lib/subprocess.d.ts +97 -0
  46. package/lib/subprocess.js +8 -0
  47. package/lib/tools.d.ts +212 -0
  48. package/lib/tools.js +2 -0
  49. package/lib/web.d.ts +192 -0
  50. package/lib/web.js +53 -0
  51. package/package.json +40 -3
package/lib/index.js ADDED
@@ -0,0 +1,151 @@
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,工作区登记、Goal、已安排的任务与压缩在 platform.ts,凭据在 credentials.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 "./jobs.js";
25
+ export * from "./llm.js";
26
+ export * from "./platform.js";
27
+ export * from "./capabilities.js";
28
+ export * from "./credentials.js";
29
+ export * from "./permissions.js";
30
+ export * from "./prompt.js";
31
+ export * from "./session-events.js";
32
+ export * from "./sessions.js";
33
+ export * from "./subagents.js";
34
+ export * from "./tools.js";
35
+ export * from "./storage.js";
36
+ export * from "./settings.js";
37
+ export * from "./subprocess.js";
38
+ export * from "./local-install.js";
39
+ export * from "./runtime-context.js";
40
+ export * from "./cmdline.js";
41
+ export * from "./web.js";
42
+ /** cordis 的 `FiberState`:上游是 `const enum`,`verbatimModuleSyntax` 下不能直接用,取这份。 */
43
+ export const FiberState = { PENDING: 0, LOADING: 1, ACTIVE: 2, FAILED: 3, DISPOSED: 4, UNLOADING: 5 };
44
+ /** 同 0.12 的 `createUserMessage`:给一条用户消息分配 id,并冻结。`source.kind` 写消息的来源,`user` 在界面上显示成用户发的。 */
45
+ export function createUserMessage(input) {
46
+ return Object.freeze({ content: [...input.content], source: input.source, role: 'user', id: crypto.randomUUID() });
47
+ }
48
+ /** 同 0.12 `tools` 的 `defineTool`:参数与结果的类型由 `parameters` 与 `output.schema` 推出。 */
49
+ export function defineTool(options) {
50
+ return options;
51
+ }
52
+ const RECORD_TYPE = /^plugin:[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)*$/;
53
+ /** 这个事件类型是插件记录的写法(`plugin:` 后面是斜杠分隔的段,同 0.12)。 */
54
+ export function isPluginRecordType(type) {
55
+ return RECORD_TYPE.test(type);
56
+ }
57
+ /** 同 0.12 的 `session`:插件记录事件的内容;不是插件记录时为 undefined。 */
58
+ export function pluginRecordOf(event) {
59
+ if (!RECORD_TYPE.test(event.type) || event.ignorable !== true)
60
+ return undefined;
61
+ return { type: event.type, seq: event.seq, time: event.time, data: event.data };
62
+ }
63
+ let bridge;
64
+ /** 由插件运行时调用一次,插件不要调用。 */
65
+ export function installRuntime(runtime) {
66
+ bridge = runtime;
67
+ }
68
+ /**
69
+ * 形状有变:0.12 里是同步的。追加一条插件记录(可忽略的会话事件,模型看不到),返回它的 seq;
70
+ * 兑现时本进程的会话投影已经折叠了它(读到自己的写入)。
71
+ */
72
+ export function appendPluginRecord(session, type, data) {
73
+ if (!RECORD_TYPE.test(type))
74
+ return Promise.reject(new Error(`invalid plugin record type ${type}`));
75
+ if (bridge === undefined)
76
+ return Promise.reject(new Error('appendPluginRecord is only available inside the plugin process'));
77
+ return bridge.appendPluginRecord(session, type, data);
78
+ }
79
+ /** remote 调用的失败:插件后端在失败处抛出,宿主把错误码、说明与 `details` 原样交给插件前端。 */
80
+ export class RemoteError extends Error {
81
+ /** 结构上的标记:跨模块副本识别时不用 instanceof。 */
82
+ isRemoteError = true;
83
+ code;
84
+ details;
85
+ constructor(code, message, details, options) {
86
+ super(message, options);
87
+ this.name = 'RemoteError';
88
+ this.code = code;
89
+ this.details = details;
90
+ }
91
+ }
92
+ /** 方法上 `@Remote` 的标记(按方法函数本身记,与类、实例无关)。 */
93
+ const MARKS = new WeakMap();
94
+ export function Remote(first, _context) {
95
+ if (typeof first === 'function') {
96
+ MARKS.set(first, { name: undefined, stream: false });
97
+ return;
98
+ }
99
+ const option = first;
100
+ if (typeof option !== 'string')
101
+ checkRemoteOptions(option);
102
+ return (method) => {
103
+ MARKS.set(method, { name: typeof option === 'string' ? option : option.name, stream: typeof option === 'object' && option.mode === 'stream' });
104
+ };
105
+ }
106
+ function checkRemoteOptions(option) {
107
+ if (typeof option !== 'object' || option === null)
108
+ throw new TypeError('@Remote expects a call name or { name?, mode? }');
109
+ const { name, mode, ...rest } = option;
110
+ const unsupported = Object.keys(rest);
111
+ if (unsupported.length > 0)
112
+ throw new TypeError(`@Remote does not support option(s) ${unsupported.join(', ')}`);
113
+ if (name !== undefined && typeof name !== 'string')
114
+ throw new TypeError('@Remote option name must be a string');
115
+ if (mode !== undefined && mode !== 'stream')
116
+ throw new TypeError("@Remote option mode must be 'stream'");
117
+ }
118
+ /** 服务上标了 `@Remote` 的方法,按原型链从子类往上找,子类的同名方法优先。 */
119
+ function remoteMethodsOf(service) {
120
+ const methods = new Map();
121
+ for (let proto = Object.getPrototypeOf(service); proto !== null && proto !== Service.prototype; proto = Object.getPrototypeOf(proto)) {
122
+ for (const member of Object.getOwnPropertyNames(proto)) {
123
+ const value = Object.getOwnPropertyDescriptor(proto, member)?.value;
124
+ const mark = typeof value === 'function' ? MARKS.get(value) : undefined;
125
+ const name = mark?.name ?? member;
126
+ if (mark !== undefined && !methods.has(name))
127
+ methods.set(name, { member, name, stream: mark.stream });
128
+ }
129
+ }
130
+ return [...methods.values()];
131
+ }
132
+ /**
133
+ * 同 0.12 的 `typert-protocol`:给插件前端提供 remote 服务的服务基类。服务名就是 remote 命名空间(可另给 `namespace`),
134
+ * 由插件 id 派生,所有插件里唯一;服务在时命名空间挂着,服务撤销(插件停用、卸载)时随之撤销。
135
+ * 插件进程之外(如插件自己的单测)不挂载,服务照常可用。
136
+ */
137
+ export class TypertRemoteService extends Service {
138
+ constructor(ctx, serviceKey, options) {
139
+ super(ctx, serviceKey);
140
+ const namespace = options?.namespace ?? serviceKey;
141
+ const methods = remoteMethodsOf(this);
142
+ const invoke = (name, args, signal) => {
143
+ const entry = methods.find((method) => method.name === name);
144
+ if (entry === undefined)
145
+ throw new RemoteError('remote/bad-request', `unknown remote method ${name}`, {});
146
+ return this[entry.member](...args, signal);
147
+ };
148
+ ctx.effect(() => bridge?.mountRemote(ctx, serviceKey, namespace, methods, invoke) ?? (() => { }), `remote ${namespace}`);
149
+ }
150
+ }
151
+ //# sourceMappingURL=index.js.map
package/lib/jobs.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 后台任务的接口(0.12 的 `ctx.jobs`)。注册表在宿主上,工作跑在插件进程里:`run` 拿到的写入是同步的,发出去不等答复;读取要跨进程,
3
+ * 都变成 Promise。快照与事件的类型由扩展点表生成(generated.ts)。
4
+ * @module @ftai/plugin-host-api/jobs
5
+ */
6
+ import type { JobAppendOptions, JobChannel, JobEvent, JobOutcome, JobOutputRead, JobRead, JobView, KillOutcome } from './generated.ts';
7
+ /** 同 0.12:任务 id(`<kind>-N`)是字符串,不是品牌类型。 */
8
+ export type JobId = string;
9
+ /** 同 0.12:生产方种类的表,插件以模块扩充声明自己的;注册表只把它当 id 的前缀。 */
10
+ export interface JobKindMap {
11
+ bash: 'bash';
12
+ }
13
+ export type JobKind = JobKindMap[keyof JobKindMap];
14
+ /** 从 {@link JobOutputSource} 读一次。 */
15
+ export interface JobSourceRead {
16
+ /** 这次的文本(`lossy` 时是留着的整个尾部)。 */
17
+ readonly text: string;
18
+ /** 下次从哪里接着读。 */
19
+ readonly nextOffset: number;
20
+ /** 请求的位置已滑出来源留着的窗口。 */
21
+ readonly lossy: boolean;
22
+ /** 存着完整输出的文件。每次都报,后面一次不带即撤回。 */
23
+ readonly spillPath?: string;
24
+ }
25
+ /** 定时拉取的输出来源(同 0.12),在插件进程里每 150 毫秒读一次;生产方结束后再读最后一次。读抛错时这个来源到此为止。 */
26
+ export interface JobOutputSource {
27
+ readonly channel?: JobChannel;
28
+ read(fromByte: number): JobSourceRead;
29
+ }
30
+ /** 生产方的一面,交给 {@link JobSpec.run}。都是同步的:发给宿主不等答复,按调用的顺序生效,结束之后的写入丢掉。 */
31
+ export interface JobHandle {
32
+ readonly id: JobId;
33
+ /** 追加一段输出;空的丢掉。 */
34
+ append(text: string, options?: JobAppendOptions): void;
35
+ /** 换掉进度行;结束时清掉。 */
36
+ updateProgress(line: string): void;
37
+ }
38
+ /** 宿主控制与观察工作的钩子。 */
39
+ export interface JobHooks {
40
+ /** 请求停下:可以重复调用,最终让 {@link done} 兑现。 */
41
+ cancel(reason?: string): void;
42
+ /** 释放完资源后给出结局。拒绝算作 `failed`。 */
43
+ done: Promise<JobOutcome>;
44
+ }
45
+ /** `ctx.jobs.start` 的参数(同 0.12 的 `JobSpec`)。 */
46
+ export interface JobSpec {
47
+ /** 种类,也是 id 的前缀。 */
48
+ kind: JobKind;
49
+ /** 给模型看的一行。 */
50
+ label: string;
51
+ /** 归属的会话 id:只有这个会话读得到、停得了,结束时通知它的模型,归档它时停下。不给时任何调用方都看得到。 */
52
+ owner?: string;
53
+ /** 交给模型的一次读取与结束通知的字节上限;观察者不受限。 */
54
+ outputLimitBytes?: number;
55
+ output?: readonly JobOutputSource[];
56
+ /** 在插件进程里起工作,同步交回钩子。抛错时什么也不留。 */
57
+ run(job: JobHandle): JobHooks;
58
+ }
59
+ /** 订阅谁的事件(同 0.12):`{ owner }` 是这个会话的与不归属会话的;`{ owners: 'scope' }` 在 `agent.ctx` 上是这个 agent 的,否则同 `all`。 */
60
+ export type JobEventFilter = {
61
+ readonly owner: string;
62
+ } | {
63
+ readonly owners: 'all' | 'scope';
64
+ };
65
+ export type JobEventListener = (event: JobEvent) => void;
66
+ export interface JobEvents {
67
+ /** 订阅,随调用者撤销。监听者抛错只记日志。 */
68
+ subscribe(filter: JobEventFilter, listener: JobEventListener): () => void;
69
+ }
70
+ /**
71
+ * 同 0.12 的 `ctx.jobs`(`JobRegistry`)。`caller` 是读取方的会话 id:归属会话的任务只有那个会话读得到,不给 `caller` 时只看得到不归属会话的。
72
+ * 形状有变:跨进程后都返回 Promise。
73
+ */
74
+ export interface JobRegistry {
75
+ readonly events: JobEvents;
76
+ /** 形状有变:返回 Promise,`run` 在宿主留下 id 之后才调用,不在这次调用里同步跑。每个插件同时最多 10 个。 */
77
+ start(spec: JobSpec): Promise<JobId>;
78
+ list(caller?: string): Promise<JobView[]>;
79
+ get(id: JobId, caller?: string): Promise<JobView>;
80
+ /** 消费式读取:给上次读到之后的,结束后第一次读取带上结果。 */
81
+ read(id: JobId, caller?: string): Promise<JobRead>;
82
+ /** 从字节偏移 `from` 读留着的输出,不影响消费式读取的位置。 */
83
+ readAt(id: JobId, from: number, caller?: string): Promise<JobOutputRead>;
84
+ kill(id: JobId, caller?: string, reason?: string): Promise<KillOutcome>;
85
+ /** 等到结束或过了 `timeoutMs`(到时任务照常在跑),返回那时的快照。`signal` 只取消这次等待。 */
86
+ wait(id: JobId, timeoutMs: number, caller?: string, signal?: AbortSignal): Promise<JobView>;
87
+ remove(id: JobId, caller?: string): Promise<void>;
88
+ }
package/lib/jobs.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=jobs.js.map
package/lib/llm.d.ts ADDED
@@ -0,0 +1,255 @@
1
+ /**
2
+ * 模型(0.12 的 `ctx.llm`,0.12 的 `llm` 包):注册模型路由与自带流式实现的适配器、查模型目录、准备与发起模型调用、改写流式输出。
3
+ * 类型名与形状照 0.12,跨进程做不到同形的地方:
4
+ * - 同步读取(`listProviders`、`providerRetryPolicy` 等)变成 Promise;同步的重试策略与图片定价注册时以数据给出,不收函数;
5
+ * - 适配器只有流式实现,路由清单在注册时给出;
6
+ * - `GenerateOptions` 没有 `toolHistory`:路由都按完整声明发工具,同 0.12 省略它的情形;
7
+ * - 内容块只有文本、推理、图片、文件与工具调用。
8
+ *
9
+ * 与 0.12 一样不重试:失败作为最后一个 `finish` 块给出(`reason.kind` 为 `error` 或 `aborted`,带 `failure.code`),
10
+ * 要重试由调用方决定。请求消息与模型信息的形状由扩展点表生成(`RequestMessage`、`LlmModelInfo`)。路由的 key 与请求头不经过这里的
11
+ * 任何接口。
12
+ * @module
13
+ */
14
+ import type { FileAttachmentRef, ImageAttachmentRef } from './attachments.ts';
15
+ import type { FileRef, GenerateRequest, InputModality, LlmCallAdapterDefaults, LlmCallConfig, LlmConfigurableProvider, LlmDiscoveredModel, LlmImageRequestPricing, LlmModelContext, LlmModelDiscoveryRequest, LlmModelInfo, LlmProviderInfo, LlmStreamRequest, RequestMessage, ResolvedRetryPolicy, RouteCredentials, RouteDeclaration } from './generated.ts';
16
+ /** 一次失败的事实:稳定的错误码(如 `AUTH`、`RATE_LIMIT`)与说明。 */
17
+ export interface LlmFailure {
18
+ readonly message: string;
19
+ readonly code: string;
20
+ readonly status?: number;
21
+ readonly providerRetryAfterMs?: number;
22
+ readonly requestId?: string;
23
+ readonly offloadImages?: number;
24
+ }
25
+ export type FinishReason = {
26
+ readonly kind: 'stop';
27
+ } | {
28
+ readonly kind: 'tool-calls';
29
+ } | {
30
+ readonly kind: 'max-tokens';
31
+ } | {
32
+ readonly kind: 'aborted';
33
+ readonly failure: LlmFailure;
34
+ } | {
35
+ readonly kind: 'error';
36
+ readonly failure: LlmFailure;
37
+ };
38
+ /** 用量:`inputTokens` 不含缓存命中,缓存另计。 */
39
+ export interface TokenUsage {
40
+ inputTokens: number;
41
+ outputTokens: number;
42
+ totalTokens?: number;
43
+ cacheReadTokens?: number;
44
+ cacheWriteTokens?: number;
45
+ reasoningTokens?: number;
46
+ }
47
+ export interface TextBlock {
48
+ readonly type: 'text';
49
+ readonly text: string;
50
+ }
51
+ export interface ReasoningBlock {
52
+ readonly type: 'reasoning';
53
+ readonly text: string;
54
+ }
55
+ export interface ImageBlock {
56
+ readonly type: 'image';
57
+ readonly attachment: ImageAttachmentRef;
58
+ }
59
+ export interface FileBlock {
60
+ readonly type: 'file';
61
+ readonly attachment: FileAttachmentRef;
62
+ }
63
+ export interface ToolCallBlock {
64
+ readonly type: 'tool-call';
65
+ readonly id: string;
66
+ readonly name: string;
67
+ /** 模型给的参数原文。 */
68
+ readonly arguments: string;
69
+ }
70
+ export type ContentBlock = TextBlock | ReasoningBlock | ImageBlock | FileBlock | ToolCallBlock;
71
+ export type ContentBlockType = ContentBlock['type'];
72
+ /** 流式输出的一块(会话格式 v4 的 `StreamChunk`)。 */
73
+ export type StreamChunk = {
74
+ readonly type: 'block-start';
75
+ readonly index: number;
76
+ readonly blockType: ContentBlockType;
77
+ } | {
78
+ readonly type: 'text-delta';
79
+ readonly index: number;
80
+ readonly text: string;
81
+ } | {
82
+ readonly type: 'reasoning-delta';
83
+ readonly index: number;
84
+ readonly text: string;
85
+ } | {
86
+ readonly type: 'tool-call-delta';
87
+ readonly index: number;
88
+ readonly id: string;
89
+ readonly name?: string;
90
+ readonly argumentsDelta: string;
91
+ } | {
92
+ readonly type: 'block-end';
93
+ readonly index: number;
94
+ readonly block: ContentBlock;
95
+ } | {
96
+ readonly type: 'usage';
97
+ readonly usage: TokenUsage;
98
+ }
99
+ /** `replayState` 是成功的回复续聊时要原样写回的状态;放回 assistant 消息的 `source.replayState`(`BlockAssembler.message()` 替你放好)。 */
100
+ | {
101
+ readonly type: 'finish';
102
+ readonly reason: FinishReason;
103
+ readonly replayState?: ReplayEnvelope;
104
+ };
105
+ /** 适配器私有的重放状态(0.12 的 `ReplayEnvelope`),内容不透明:`blocks` 给出时一项对应一个发出的块,项数对不上时整个不要。 */
106
+ export interface ReplayEnvelope {
107
+ readonly response: unknown;
108
+ readonly blocks?: readonly unknown[];
109
+ }
110
+ export interface GenerateOptions extends Omit<GenerateRequest, 'messages'> {
111
+ /**
112
+ * 会话格式 v4 的消息,多给的字段不看。图片发的是请求版本(按像素预算缩小),模型不收图时换成「只收文本」的占位文本、请求照发;文件转成
113
+ * 带路径的文本。
114
+ */
115
+ readonly messages: readonly RequestMessage[];
116
+ /** 中止时断开模型请求,流以 `signal.reason` 结束。 */
117
+ readonly signal?: AbortSignal;
118
+ }
119
+ /**
120
+ * `llm/stream` 的监听者与适配器看到的请求(已冻结,改不了)。监听者看到的文件与图片还是引用;适配器看到的已经按路由投影:文件与不发字节的图片
121
+ * 换成文本,其余图片的字节用 `ctx.attachments` 读。`agentLoop` 标明是 Agent 回路组装的(`isAgentLoopRequest`)。
122
+ */
123
+ export type LlmStreamOptions = Readonly<LlmStreamRequest> & {
124
+ readonly signal: AbortSignal;
125
+ };
126
+ /** 同 0.12:这个请求是不是 Agent 回路组装的。 */
127
+ export declare function isAgentLoopRequest(options: {
128
+ readonly agentLoop?: boolean;
129
+ }): boolean;
130
+ /** 同 0.12:两份调用配置逐项相同(`stop` 按元素比)。 */
131
+ export declare function callConfigEquals(a: LlmCallConfig, b: LlmCallConfig): boolean;
132
+ /** 模型信息(0.12 的名字),`defaultMaxTokens` 只在路由给模型配了输出上限时有。FtAi 的路由都按完整声明发系统提示与工具,`systemPromptUpdate`、`toolUpdate` 总是没有。 */
133
+ export type LlmResolvedModelInfo = LlmModelInfo & {
134
+ readonly systemPromptUpdate?: 'in-history';
135
+ readonly toolUpdate?: 'in-history' | 'addition-only';
136
+ };
137
+ /** 模型路由(0.12 没有这个类型):`registerRoute` 收的 {@link RouteDeclaration} 去掉另外声明的部分。 */
138
+ export type ModelRoute = Omit<RouteDeclaration, 'retryPolicy' | 'modelOptions'>;
139
+ /** 具体的请求控制(0.12 的 `LlmCallControls`);不给的用路由的默认值。 */
140
+ export type LlmCallControls = Omit<LlmCallConfig, 'provider' | 'model'>;
141
+ /** 准备调用时选控制(0.12 的 `ConfigureCall`):在插件进程里同步调用,收到冻结的副本,路由改不了;结果再经宿主校验、补默认值。 */
142
+ export type ConfigureCall = (controls: Readonly<LlmCallControls>, model: Readonly<LlmResolvedModelInfo>) => LlmCallControls;
143
+ /** 钉住路由注册快照的一次调用(0.12 的 `PreparedLlmCall`)。句柄在宿主里,凭据在派发时才向注册方取。 */
144
+ export interface PreparedLlmCall {
145
+ readonly config: Readonly<LlmCallConfig>;
146
+ readonly retryPolicy: ResolvedRetryPolicy;
147
+ readonly context: LlmModelContext;
148
+ readonly inputModalities: readonly InputModality[];
149
+ /** 配置里由路由补上、不是调用方给的项。 */
150
+ readonly adapterDefaults: LlmCallAdapterDefaults;
151
+ /** 经钉住的快照派发一次(含 `llm/stream`)。第二次调用或配置对不上报 `INVALID_PREPARED_CALL`。 */
152
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
153
+ }
154
+ /** 自带流式实现的适配器(0.12 的 `LlmAdapter`,路由清单与同步查询的答案在注册时以数据给出)。插件自己发 HTTP。 */
155
+ export interface LlmAdapter {
156
+ /** 逐块给出 v4 的 StreamChunk,以 `finish` 结束;形状不对或抛错时这次请求以 `error` 的 `finish` 结束,抛 `LlmError` 时带着它的错误码与事实,别的错误记 `LLM_ADAPTER_FAILED`。`options.signal` 中止时要尽快停下。 */
157
+ stream(options: LlmStreamOptions): AsyncIterable<StreamChunk>;
158
+ }
159
+ /** `registerAdapter` 的结果(0.12 的 `AdapterRegistrationHandle`):调用它撤销。 */
160
+ export interface AdapterRegistrationHandle {
161
+ (): void;
162
+ /** 宿主收下了这项注册;形状有变:校验错误(`DUPLICATE_ADAPTER`、`INVALID_ADAPTER`)从这里报,0.12 是同步抛出。 */
163
+ readonly ready: Promise<void>;
164
+ /** 整体替换路由,适配器不变。形状有变:返回 Promise。校验不过时原样不动并拒绝,已撤销时报 `REGISTRATION_DISPOSED`。 */
165
+ replace(routes: readonly RouteDeclaration[]): Promise<void>;
166
+ }
167
+ /** `registerConfigurableProviders` 的结果(0.12 的 `DirectoryRegistrationHandle`):调用它撤销。 */
168
+ export interface DirectoryRegistrationHandle {
169
+ (): void;
170
+ /** 宿主收下了这项声明;形状有变:`DUPLICATE_DIRECTORY` 从这里报,0.12 是同步抛出。 */
171
+ readonly ready: Promise<void>;
172
+ /** 整体替换,可以换成空的。形状有变:返回 Promise。校验不过时原样不动并拒绝,已撤销时报 `REGISTRATION_DISPOSED`。 */
173
+ replace(entries: readonly LlmConfigurableProvider[]): Promise<void>;
174
+ }
175
+ /** 模型层的失败(同 0.12):没有这条路由是 `NO_ADAPTER`,路由里没有这个模型是 `UNKNOWN_MODEL`。 */
176
+ export declare class LlmError extends Error {
177
+ readonly code: string;
178
+ readonly failure: LlmFailure;
179
+ /** @param options 除了 `cause`,还可以带失败的事实:`status`、`providerRetryAfterMs`(服务端要求的重试延迟)、`requestId`、`offloadImages`。 */
180
+ constructor(message: string, code: string, options?: ErrorOptions & Omit<LlmFailure, 'message' | 'code'>);
181
+ }
182
+ export interface LlmService {
183
+ /**
184
+ * 注册一条模型路由(0.12 的 `registerAdapter`):一个 provider 与它的模型清单,每次请求经回调向插件取地址与凭据,协议层由宿主负责。
185
+ * 清单变了就撤销旧的注册、再注册一次。
186
+ */
187
+ registerRoute(route: RouteDeclaration, credentials: (provider: string) => RouteCredentials | Promise<RouteCredentials>): () => void;
188
+ /**
189
+ * 注册自带流式实现的路由(0.12 的 `registerAdapter`):插件自己发 HTTP、逐块给出 v4 的 StreamChunk,宿主核对形状。模型清单里的 `api` 不影响它。
190
+ * @throws LlmError `INVALID_ADAPTER`:一条路由都没有。
191
+ */
192
+ registerAdapter(routes: readonly RouteDeclaration[], adapter: LlmAdapter): AdapterRegistrationHandle;
193
+ /** 注册了的路由。后台服务刚启动、账号的模型清单还在第一次加载时先等它,最多 10 秒。形状有变:0.12 是同步的。 */
194
+ listProviders(): Promise<LlmProviderInfo[]>;
195
+ /** 一条路由的模型,藏起来的不列;路由还没有、第一次加载还没完时先等,同 `listProviders`。@throws LlmError `NO_ADAPTER` */
196
+ listModels(provider: string): Promise<LlmModelInfo[]>;
197
+ /** 声明可以经配置启用的 provider,随调用方撤销。@throws LlmError `INVALID_DIRECTORY`:空的或字段不对。 */
198
+ registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;
199
+ /** 声明了的 provider,按声明的顺序。形状有变:0.12 是同步的。 */
200
+ listConfigurableProviders(): Promise<LlmConfigurableProvider[]>;
201
+ /** 按设置命名空间注册模型发现,随调用方撤销。 */
202
+ registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal: AbortSignal) => readonly LlmDiscoveredModel[] | Promise<readonly LlmDiscoveredModel[]>): () => void;
203
+ /** 问一个草稿端点有哪些模型,按 id 去重,`request.apiKey` 只交给这个命名空间的发现实现。@throws LlmError `NO_DISCOVERY`、`INVALID_DISCOVERY`、`DISCOVERY_FAILED`、`TIMEOUT` */
204
+ discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise<LlmDiscoveredModel[]>;
205
+ /** 同 `discoverModels`,失败时报 `RemoteError`(`llm/model-discovery-rejected`):写给插件自己的 `@Remote` 方法转给界面用。 */
206
+ remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise<LlmDiscoveredModel[]>;
207
+ /** 路由的重试策略,只有 `normal` 一种。形状有变:0.12 是同步的。@throws LlmError `NO_ADAPTER` */
208
+ providerRetryPolicy(provider: string): Promise<ResolvedRetryPolicy>;
209
+ /** 路由给这个模型声明的图片定价(数据);没有这条路由或没有声明时为 undefined。形状有变:0.12 同步给出带 `priceImages` 函数的对象。 */
210
+ imageRequestPricing(provider: string, model: string): Promise<LlmImageRequestPricing | undefined>;
211
+ /** 文件附件进请求时的文本,与派发时用的相同。形状有变:0.12 是同步的。 */
212
+ fileRequestText(ref: FileRef): Promise<string>;
213
+ /** 按模型校验配置、补上路由的默认值,与 `stream` 共用同一份规则。@throws LlmError `NO_ADAPTER`、`UNKNOWN_MODEL`、`UNSUPPORTED_REASONING_EFFORT` */
214
+ resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise<LlmCallConfig>;
215
+ /** 钉住路由的注册快照,校验与派发都按它。@throws LlmError 同 `resolveCallConfig` */
216
+ prepareCall(config: LlmCallConfig, signal?: AbortSignal, configure?: ConfigureCall): Promise<PreparedLlmCall>;
217
+ /** @throws LlmError */
218
+ resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<LlmResolvedModelInfo>;
219
+ /**
220
+ * 直接调用模型,逐块给出流式输出。路由、推理档位(模型不支持这个档位时失败,`off` 也不例外)或凭据在请求之前就失败时,
221
+ * 只有一个 `finish` 块。
222
+ */
223
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
224
+ }
225
+ /**
226
+ * 把流式输出拼成完整的内容块(同 0.12 的 `BlockAssembler`)。也接受只有增量、没有 `block-start` / `block-end` 的流;
227
+ * 一块已经由 `block-end` 结束后,同一个序号再来的增量忽略。
228
+ */
229
+ export declare class BlockAssembler {
230
+ private readonly partials;
231
+ private readonly order;
232
+ private finishReason;
233
+ private reportedUsage;
234
+ private reportedReplay;
235
+ /** 按流的顺序送进一块。 */
236
+ push(chunk: StreamChunk): void;
237
+ /** 到目前为止的全部块,按流的顺序;因输出上限截断时去掉工具调用(执行不了)。还没结束的块按已到的增量拼出。 */
238
+ blocks(): ContentBlock[];
239
+ private kept;
240
+ /** `finish` 块给的重放状态,每块一项的部分随 `blocks()` 去掉对应的项;项数与块数对不上时为 undefined。 */
241
+ get replayState(): ReplayEnvelope | undefined;
242
+ /** 拼好的回复,可以放回下一次请求的 `messages`(同 0.12):带着重放状态,续聊时原样写回推理与签名。 */
243
+ message(source: {
244
+ readonly provider: string;
245
+ readonly model: string;
246
+ }): Readonly<RequestMessage>;
247
+ /** 流被中断时能保留的部分:有非空白内容的文本与推理块,按流的顺序;工具调用不保留。 */
248
+ interruptedBlocks(): ContentBlock[];
249
+ /** `usage` 块给出的用量;还没到时为 undefined。 */
250
+ get usage(): TokenUsage | undefined;
251
+ /** `finish` 块给出的结束原因;流没有 `finish` 块就结束时是 `{ kind: 'stop' }`。 */
252
+ get finish(): FinishReason;
253
+ private ensure;
254
+ private assemble;
255
+ }
package/lib/llm.js ADDED
@@ -0,0 +1,144 @@
1
+ /** 同 0.12:这个请求是不是 Agent 回路组装的。 */
2
+ export function isAgentLoopRequest(options) {
3
+ return options.agentLoop === true;
4
+ }
5
+ /** 同 0.12:两份调用配置逐项相同(`stop` 按元素比)。 */
6
+ export function callConfigEquals(a, b) {
7
+ const stop = (config) => config.stop ?? undefined;
8
+ const [left, right] = [stop(a), stop(b)];
9
+ return a.provider === b.provider
10
+ && a.model === b.model
11
+ && (a.reasoningEffort ?? undefined) === (b.reasoningEffort ?? undefined)
12
+ && (a.maxTokens ?? undefined) === (b.maxTokens ?? undefined)
13
+ && (a.temperature ?? undefined) === (b.temperature ?? undefined)
14
+ && left?.length === right?.length
15
+ && (left ?? []).every((value, index) => value === right?.[index]);
16
+ }
17
+ /** 模型层的失败(同 0.12):没有这条路由是 `NO_ADAPTER`,路由里没有这个模型是 `UNKNOWN_MODEL`。 */
18
+ export class LlmError extends Error {
19
+ code;
20
+ failure;
21
+ /** @param options 除了 `cause`,还可以带失败的事实:`status`、`providerRetryAfterMs`(服务端要求的重试延迟)、`requestId`、`offloadImages`。 */
22
+ constructor(message, code, options) {
23
+ super(message, options);
24
+ this.code = code;
25
+ this.name = 'LlmError';
26
+ const { cause: _cause, ...facts } = options ?? {};
27
+ this.failure = { ...facts, message, code };
28
+ }
29
+ }
30
+ /**
31
+ * 把流式输出拼成完整的内容块(同 0.12 的 `BlockAssembler`)。也接受只有增量、没有 `block-start` / `block-end` 的流;
32
+ * 一块已经由 `block-end` 结束后,同一个序号再来的增量忽略。
33
+ */
34
+ export class BlockAssembler {
35
+ partials = new Map();
36
+ order = [];
37
+ finishReason;
38
+ reportedUsage;
39
+ reportedReplay;
40
+ /** 按流的顺序送进一块。 */
41
+ push(chunk) {
42
+ switch (chunk.type) {
43
+ case 'block-start':
44
+ this.ensure(chunk.index, chunk.blockType);
45
+ return;
46
+ case 'text-delta':
47
+ case 'reasoning-delta': {
48
+ const partial = this.ensure(chunk.index, chunk.type === 'text-delta' ? 'text' : 'reasoning');
49
+ if (partial.block === undefined)
50
+ partial.text += chunk.text;
51
+ return;
52
+ }
53
+ case 'tool-call-delta': {
54
+ const partial = this.ensure(chunk.index, 'tool-call');
55
+ if (partial.block !== undefined)
56
+ return;
57
+ partial.toolCallId = chunk.id;
58
+ if (chunk.name)
59
+ partial.toolCallName = chunk.name;
60
+ partial.toolCallArguments += chunk.argumentsDelta;
61
+ return;
62
+ }
63
+ case 'block-end': {
64
+ const partial = this.ensure(chunk.index, chunk.block.type);
65
+ partial.block ??= chunk.block;
66
+ return;
67
+ }
68
+ case 'usage':
69
+ this.reportedUsage = chunk.usage;
70
+ return;
71
+ case 'finish':
72
+ this.finishReason = chunk.reason;
73
+ this.reportedReplay = chunk.replayState;
74
+ return;
75
+ }
76
+ }
77
+ /** 到目前为止的全部块,按流的顺序;因输出上限截断时去掉工具调用(执行不了)。还没结束的块按已到的增量拼出。 */
78
+ blocks() {
79
+ return this.order.map(index => this.assemble(index)).filter(block => this.kept(block));
80
+ }
81
+ kept(block) {
82
+ return this.finish.kind !== 'max-tokens' || block.type !== 'tool-call';
83
+ }
84
+ /** `finish` 块给的重放状态,每块一项的部分随 `blocks()` 去掉对应的项;项数与块数对不上时为 undefined。 */
85
+ get replayState() {
86
+ const envelope = this.reportedReplay;
87
+ if (envelope?.blocks === undefined)
88
+ return envelope;
89
+ if (envelope.blocks.length !== this.order.length)
90
+ return undefined;
91
+ const all = this.order.map(index => this.assemble(index));
92
+ return { response: envelope.response, blocks: envelope.blocks.filter((_, position) => this.kept(all[position])) };
93
+ }
94
+ /** 拼好的回复,可以放回下一次请求的 `messages`(同 0.12):带着重放状态,续聊时原样写回推理与签名。 */
95
+ message(source) {
96
+ const replayState = this.replayState;
97
+ const content = this.blocks().filter((block) => block.type === 'text' || block.type === 'reasoning' || block.type === 'tool-call');
98
+ return Object.freeze({
99
+ role: 'assistant',
100
+ content,
101
+ source: { kind: 'model', provider: source.provider, model: source.model, ...replayState === undefined ? {} : { replayState } },
102
+ });
103
+ }
104
+ /** 流被中断时能保留的部分:有非空白内容的文本与推理块,按流的顺序;工具调用不保留。 */
105
+ interruptedBlocks() {
106
+ return this.order.flatMap((index) => {
107
+ const partial = this.partials.get(index);
108
+ const type = partial.block?.type ?? partial.blockType;
109
+ if (type !== 'text' && type !== 'reasoning')
110
+ return [];
111
+ const block = this.assemble(index);
112
+ return (block.type === 'text' || block.type === 'reasoning') && block.text.trim() !== '' ? [block] : [];
113
+ });
114
+ }
115
+ /** `usage` 块给出的用量;还没到时为 undefined。 */
116
+ get usage() {
117
+ return this.reportedUsage;
118
+ }
119
+ /** `finish` 块给出的结束原因;流没有 `finish` 块就结束时是 `{ kind: 'stop' }`。 */
120
+ get finish() {
121
+ return this.finishReason ?? { kind: 'stop' };
122
+ }
123
+ ensure(index, blockType) {
124
+ let partial = this.partials.get(index);
125
+ if (partial === undefined) {
126
+ partial = { blockType, text: '', toolCallArguments: '' };
127
+ this.partials.set(index, partial);
128
+ this.order.push(index);
129
+ }
130
+ return partial;
131
+ }
132
+ assemble(index) {
133
+ const partial = this.partials.get(index);
134
+ if (partial.block !== undefined)
135
+ return partial.block;
136
+ switch (partial.blockType) {
137
+ case 'text': return { type: 'text', text: partial.text };
138
+ case 'reasoning': return { type: 'reasoning', text: partial.text };
139
+ case 'tool-call': return { type: 'tool-call', id: partial.toolCallId ?? `call-${String(index)}`, name: partial.toolCallName ?? '', arguments: partial.toolCallArguments };
140
+ default: throw new Error(`cannot assemble incomplete block of type "${partial.blockType}"`);
141
+ }
142
+ }
143
+ }
144
+ //# sourceMappingURL=llm.js.map