@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
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 CHANGED
@@ -1,16 +1,18 @@
1
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 回路落盘用的)。
2
+ * 模型(0.12 的 `ctx.llm`,0.12 的 `llm` 包):注册模型路由与自带流式实现的适配器、查模型目录、准备与发起模型调用、改写流式输出。
3
+ * 类型名与形状照 0.12,跨进程做不到同形的地方:
4
+ * - 同步读取(`listProviders`、`providerRetryPolicy` 等)变成 Promise;同步的重试策略与图片定价注册时以数据给出,不收函数;
5
+ * - 适配器只有流式实现,路由清单在注册时给出;
6
+ * - `GenerateOptions` 没有 `toolHistory`:路由都按完整声明发工具,同 0.12 省略它的情形;
7
+ * - 内容块只有文本、推理、图片、文件与工具调用。
7
8
  *
8
9
  * 与 0.12 一样不重试:失败作为最后一个 `finish` 块给出(`reason.kind` 为 `error` 或 `aborted`,带 `failure.code`),
9
- * 要重试由调用方决定。请求消息与模型信息的形状由扩展点表生成(`RequestMessage`、`LlmModelInfo`)。
10
+ * 要重试由调用方决定。请求消息与模型信息的形状由扩展点表生成(`RequestMessage`、`LlmModelInfo`)。路由的 key 与请求头不经过这里的
11
+ * 任何接口。
10
12
  * @module
11
13
  */
12
14
  import type { FileAttachmentRef, ImageAttachmentRef } from './attachments.ts';
13
- import type { GenerateRequest, LlmModelInfo, ModelRoute, RequestMessage, RouteCredentials } from './generated.ts';
15
+ import type { FileRef, GenerateRequest, InputModality, LlmCallAdapterDefaults, LlmCallConfig, LlmConfigurableProvider, LlmDiscoveredModel, LlmImageRequestPricing, LlmModelContext, LlmModelDiscoveryRequest, LlmModelInfo, LlmProviderInfo, LlmStreamRequest, RequestMessage, ResolvedRetryPolicy, RouteCredentials, RouteDeclaration } from './generated.ts';
14
16
  /** 一次失败的事实:稳定的错误码(如 `AUTH`、`RATE_LIMIT`)与说明。 */
15
17
  export interface LlmFailure {
16
18
  readonly message: string;
@@ -35,12 +37,12 @@ export type FinishReason = {
35
37
  };
36
38
  /** 用量:`inputTokens` 不含缓存命中,缓存另计。 */
37
39
  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;
40
+ inputTokens: number;
41
+ outputTokens: number;
42
+ totalTokens?: number;
43
+ cacheReadTokens?: number;
44
+ cacheWriteTokens?: number;
45
+ reasoningTokens?: number;
44
46
  }
45
47
  export interface TextBlock {
46
48
  readonly type: 'text';
@@ -93,33 +95,125 @@ export type StreamChunk = {
93
95
  } | {
94
96
  readonly type: 'usage';
95
97
  readonly usage: TokenUsage;
96
- } | {
98
+ }
99
+ /** `replayState` 是成功的回复续聊时要原样写回的状态;放回 assistant 消息的 `source.replayState`(`BlockAssembler.message()` 替你放好)。 */
100
+ | {
97
101
  readonly type: 'finish';
98
102
  readonly reason: FinishReason;
103
+ readonly replayState?: ReplayEnvelope;
99
104
  };
105
+ /** 适配器私有的重放状态(0.12 的 `ReplayEnvelope`),内容不透明:`blocks` 给出时一项对应一个发出的块,项数对不上时整个不要。 */
106
+ export interface ReplayEnvelope {
107
+ readonly response: unknown;
108
+ readonly blocks?: readonly unknown[];
109
+ }
100
110
  export interface GenerateOptions extends Omit<GenerateRequest, 'messages'> {
101
111
  /**
102
- * 只有 user 与 assistant 两种消息(同 0.12 的 `RequestMessage` 里插件用得到的部分)。图片发的是请求版本(按像素预算缩小),
103
- * 模型不收图时换成「只收文本」的占位文本、请求照发;文件转成带路径的文本。
112
+ * 会话格式 v4 的消息,多给的字段不看。图片发的是请求版本(按像素预算缩小),模型不收图时换成「只收文本」的占位文本、请求照发;文件转成
113
+ * 带路径的文本。
104
114
  */
105
115
  readonly messages: readonly RequestMessage[];
106
116
  /** 中止时断开模型请求,流以 `signal.reason` 结束。 */
107
117
  readonly signal?: AbortSignal;
108
118
  }
109
- /** 0.12 的名字:模型信息,`defaultMaxTokens` 只在路由给模型配了输出上限时有。 */
110
- export type LlmResolvedModelInfo = LlmModelInfo;
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
+ }
111
175
  /** 模型层的失败(同 0.12):没有这条路由是 `NO_ADAPTER`,路由里没有这个模型是 `UNKNOWN_MODEL`。 */
112
176
  export declare class LlmError extends Error {
113
177
  readonly code: string;
114
178
  readonly failure: LlmFailure;
115
- constructor(message: string, code: string, options?: ErrorOptions);
179
+ /** @param options 除了 `cause`,还可以带失败的事实:`status`、`providerRetryAfterMs`(服务端要求的重试延迟)、`requestId`、`offloadImages`。 */
180
+ constructor(message: string, code: string, options?: ErrorOptions & Omit<LlmFailure, 'message' | 'code'>);
116
181
  }
117
182
  export interface LlmService {
118
183
  /**
119
- * 注册一条模型路由(0.12 的 `registerAdapter`):一个 provider 与它的模型清单,每次请求经回调向插件取地址与凭据。
184
+ * 注册一条模型路由(0.12 的 `registerAdapter`):一个 provider 与它的模型清单,每次请求经回调向插件取地址与凭据,协议层由宿主负责。
120
185
  * 清单变了就撤销旧的注册、再注册一次。
121
186
  */
122
- registerRoute(route: ModelRoute, credentials: (provider: string) => RouteCredentials | Promise<RouteCredentials>): () => void;
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>;
123
217
  /** @throws LlmError */
124
218
  resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<LlmResolvedModelInfo>;
125
219
  /**
@@ -137,10 +231,19 @@ export declare class BlockAssembler {
137
231
  private readonly order;
138
232
  private finishReason;
139
233
  private reportedUsage;
234
+ private reportedReplay;
140
235
  /** 按流的顺序送进一块。 */
141
236
  push(chunk: StreamChunk): void;
142
237
  /** 到目前为止的全部块,按流的顺序;因输出上限截断时去掉工具调用(执行不了)。还没结束的块按已到的增量拼出。 */
143
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>;
144
247
  /** 流被中断时能保留的部分:有非空白内容的文本与推理块,按流的顺序;工具调用不保留。 */
145
248
  interruptedBlocks(): ContentBlock[];
146
249
  /** `usage` 块给出的用量;还没到时为 undefined。 */
package/lib/llm.js CHANGED
@@ -1,12 +1,30 @@
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
+ }
1
17
  /** 模型层的失败(同 0.12):没有这条路由是 `NO_ADAPTER`,路由里没有这个模型是 `UNKNOWN_MODEL`。 */
2
18
  export class LlmError extends Error {
3
19
  code;
4
20
  failure;
21
+ /** @param options 除了 `cause`,还可以带失败的事实:`status`、`providerRetryAfterMs`(服务端要求的重试延迟)、`requestId`、`offloadImages`。 */
5
22
  constructor(message, code, options) {
6
23
  super(message, options);
7
24
  this.code = code;
8
25
  this.name = 'LlmError';
9
- this.failure = { message, code };
26
+ const { cause: _cause, ...facts } = options ?? {};
27
+ this.failure = { ...facts, message, code };
10
28
  }
11
29
  }
12
30
  /**
@@ -18,6 +36,7 @@ export class BlockAssembler {
18
36
  order = [];
19
37
  finishReason;
20
38
  reportedUsage;
39
+ reportedReplay;
21
40
  /** 按流的顺序送进一块。 */
22
41
  push(chunk) {
23
42
  switch (chunk.type) {
@@ -51,13 +70,36 @@ export class BlockAssembler {
51
70
  return;
52
71
  case 'finish':
53
72
  this.finishReason = chunk.reason;
73
+ this.reportedReplay = chunk.replayState;
54
74
  return;
55
75
  }
56
76
  }
57
77
  /** 到目前为止的全部块,按流的顺序;因输出上限截断时去掉工具调用(执行不了)。还没结束的块按已到的增量拼出。 */
58
78
  blocks() {
59
- const blocks = this.order.map(index => this.assemble(index));
60
- return this.finish.kind === 'max-tokens' ? blocks.filter(block => block.type !== 'tool-call') : 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
+ });
61
103
  }
62
104
  /** 流被中断时能保留的部分:有非空白内容的文本与推理块,按流的顺序;工具调用不保留。 */
63
105
  interruptedBlocks() {
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 插件进程所在的本机安装(SDK 2.2):插件自己的数据目录与缓存目录,与连上同一个后台服务的命令行 `ftai`。实现在插件进程里。
3
+ *
4
+ * 给要在本机落大文件、或要拉起外部应用的插件用:例如插件下载一个运行包放进自己的缓存目录,再由那个应用经 `ftai app` 连回
5
+ * FtAi(docs/rust-host/cli.md「外部应用」)。
6
+ * @module
7
+ */
8
+ /** 本机的 `ftai`。 */
9
+ export interface LocalCli {
10
+ /** 可执行文件的绝对路径。 */
11
+ readonly path: string;
12
+ /**
13
+ * 运行它时要带上的环境变量:后台服务启动时的全部 `FTAI_*`,不多不少。`ftai` 环境里的 `FTAI_*` 与在跑的后台服务不同时,
14
+ * 它会按「构建不同」替换掉那个后台服务,所以原样带上这一份,别的 `FTAI_*` 不要加。`ctx.subprocess` 会去掉 `FTAI_*`,
15
+ * 要经它的 `env` 显式交回去;交给外部应用时,也要让它把这一份原样交给它起的 `ftai`。
16
+ */
17
+ readonly env: Readonly<Record<string, string>>;
18
+ }
19
+ export interface LocalInstall {
20
+ /**
21
+ * 这个插件自己的数据目录(绝对路径),放用户的数据,可能还不存在,用时自己建。`ctx.storageDomain` 与 `ctx.settings` 的文件
22
+ * 也在这里(`storages/` 与 `settings.json`),插件自己的文件放在别的子目录里。卸载插件时默认留下,重装后接着用;用户在卸载
23
+ * 确认里勾选删除时连同整个目录删掉。
24
+ */
25
+ readonly dataDir: string;
26
+ /**
27
+ * 这个插件自己的缓存目录(绝对路径),放能重新得到的内容,如下载的运行包,可能还不存在,用时自己建。插件没在运行时宿主可能
28
+ * 清空它,插件要能自己重新下载;卸载插件时一定删掉。用户的数据不要放在这里。
29
+ */
30
+ readonly cacheDir: string;
31
+ /** 本机的 `ftai`;宿主旁边没有时为 undefined(如测试)。 */
32
+ readonly cli: LocalCli | undefined;
33
+ }
34
+ declare module 'cordis' {
35
+ interface Context {
36
+ readonly localInstall: LocalInstall;
37
+ }
38
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 插件进程所在的本机安装(SDK 2.2):插件自己的数据目录与缓存目录,与连上同一个后台服务的命令行 `ftai`。实现在插件进程里。
3
+ *
4
+ * 给要在本机落大文件、或要拉起外部应用的插件用:例如插件下载一个运行包放进自己的缓存目录,再由那个应用经 `ftai app` 连回
5
+ * FtAi(docs/rust-host/cli.md「外部应用」)。
6
+ * @module
7
+ */
8
+ export {};
9
+ //# sourceMappingURL=local-install.js.map
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 审批、沙箱与 shell 另包的一层(`ctx.approval`、`ctx.sandboxPolicy`、`ctx.sandbox`、`ctx.shell`):接口同 0.12,跨进程后都是异步的,
3
+ * 0.12 收 agent 句柄的参数这里收会话 id。放开给第三方,但失败时的结论不放宽:出错、超时、崩溃一律不放行。逐项的差别见移植指南的对照表,
4
+ * 产品约束见 docs/rust-host/plugin-parity.md。
5
+ * @module
6
+ */
7
+ import type { ApprovalConfig, ApprovalOutcome, ApprovalPolicy, ApprovalRequestEvent, ConfinedArgv, SandboxExecutionPolicy, SandboxMode, SandboxPolicy, ShellCollectedOutput, ShellCommandRequest, ShellCommandSpec, ShellProcessRead, ShellProcessStatus, ShellSandboxInfo } from './generated.ts';
8
+ import type { ToolExecution } from './index.ts';
9
+ /** 审批(0.12 的 `ApprovalService`)。 */
10
+ export interface ApprovalService {
11
+ /** 部署默认的审批策略。 */
12
+ config(): Promise<ApprovalConfig>;
13
+ /** 会话记下的审批策略,不套默认;没有记录时是 undefined。 */
14
+ overrideOf(sessionId: string): Promise<ApprovalPolicy | undefined>;
15
+ /** 切换会话的审批策略。与生效的策略相同时不写;子 agent 的会话拒绝。模型会收到一条通知,不说是谁改的。 */
16
+ setPolicy(sessionId: string, policy: ApprovalPolicy): Promise<void>;
17
+ /** 为进行中的工具调用申请一次批准。只有 `allowed-once` 算批准。 */
18
+ request(execution: ToolExecution, reason?: string, displayReason?: {
19
+ readonly en: string;
20
+ readonly [locale: string]: string;
21
+ }): Promise<ApprovalOutcome>;
22
+ }
23
+ /** `approval/request` 的监听者拿到的请求。`signal` 在这一轮取消或宿主不再等时触发。 */
24
+ export interface ApprovalRequest extends ApprovalRequestEvent {
25
+ readonly signal: AbortSignal;
26
+ }
27
+ /** `ctx.sandboxPolicy.resolve` 的入参。`execution` 同 `ctx.fs`:进行中工具调用的句柄。 */
28
+ export interface SandboxPolicyQuery {
29
+ readonly sessionId?: string;
30
+ readonly execution?: ToolExecution;
31
+ }
32
+ /** 沙箱策略(0.12 的 `SandboxPolicyService`):只读,不收调用方传的模式。 */
33
+ export interface SandboxPolicyService {
34
+ /** 带 `execution` 时是这次工具调用定下的模式,带 `sessionId` 时是会话的,都不带时是部署默认。 */
35
+ resolve(request?: SandboxPolicyQuery): Promise<SandboxExecutionPolicy>;
36
+ /** 会话记下的沙箱模式,不套默认;没有记录时是 undefined。 */
37
+ overrideOf(sessionId: string): Promise<SandboxMode | undefined>;
38
+ defaultMode(): Promise<SandboxMode>;
39
+ workspaceRoot(): Promise<string>;
40
+ }
41
+ /** 同 0.12:没有可用的运行器时的错误码。 */
42
+ export declare const SANDBOX_UNAVAILABLE = "SANDBOX_UNAVAILABLE";
43
+ /** 同 0.12:要求受限执行而这个平台没有可用的运行器。绝不回退成不围。 */
44
+ export declare class SandboxUnavailableError extends Error {
45
+ readonly code = "SANDBOX_UNAVAILABLE";
46
+ constructor(message: string, options?: ErrorOptions);
47
+ }
48
+ /** 把命令围进沙箱(0.12 的 `SandboxProvider`):只包启动参数,进程由调用方起。 */
49
+ export interface SandboxProvider {
50
+ /** 模式只收 `read-only`、`workspace-write`。没有可用的运行器时抛 {@link SandboxUnavailableError}。 */
51
+ confine(argv: readonly string[], policy: SandboxPolicy, signal?: AbortSignal): Promise<ConfinedArgv>;
52
+ }
53
+ /** `ctx.shell.resolve` 的入参(0.12 的 `ShellExecRequest`)。没有 `sandboxPolicy`、`dshEnv`、`stdoutMaxBytes`,写了报 `invalid_params`。 */
54
+ export interface ShellExecRequest extends Omit<ShellCommandRequest, 'execution'> {
55
+ /** 同 `ctx.fs`:进行中工具调用的句柄,按这次调用定下的模式围。不给时是插件自己的命令,按部署默认的模式,断网。 */
56
+ readonly execution?: ToolExecution;
57
+ /** 触发时停下命令。 */
58
+ signal?: AbortSignal;
59
+ }
60
+ /** `ctx.shell.resolve` 的结果(0.12 的 `ShellExecSpec`)。 */
61
+ export interface ShellExecSpec extends ShellCommandSpec {
62
+ signal?: AbortSignal;
63
+ }
64
+ /** 跑完的结果(0.12 的 `ShellRunResult`)。非零退出、超时与中止都不算失败。 */
65
+ export interface ShellRunResult {
66
+ exitCode: number | null;
67
+ signal: string | null;
68
+ /** 到时限被停下。与 `aborted` 只有一个成立。 */
69
+ timedOut: boolean;
70
+ /** 调用方的 `signal` 或插件撤销先停下了它。 */
71
+ aborted: boolean;
72
+ timeoutMs: number;
73
+ stdout: ShellCollectedOutput;
74
+ stderr: ShellCollectedOutput;
75
+ sandbox?: ShellSandboxInfo;
76
+ }
77
+ /** 一条在跑的命令(0.12 的 `ShellExecution`)。`status`、`exitCode`、`signal`、`sandbox` 在结束时更新。 */
78
+ export interface ShellExecution {
79
+ readonly status: ShellProcessStatus;
80
+ readonly exitCode: number | null;
81
+ readonly signal: string | null;
82
+ readonly sandbox?: ShellSandboxInfo;
83
+ /** 命令结束时兑现,不会拒绝。 */
84
+ readonly done: Promise<void>;
85
+ /** 等它结束给出结果;命令没有跑成(起不来、运行器失败)时拒绝。 */
86
+ result(): Promise<ShellRunResult>;
87
+ /** 上一次读取之后的输出,消费式,stderr 在 `[stderr]` 一节里。 */
88
+ readOutput(): Promise<ShellProcessRead>;
89
+ /** 停下命令,返回是否这次停下的;已经结束时为否。 */
90
+ kill(): Promise<boolean>;
91
+ }
92
+ /** 在沙箱里跑命令(0.12 的 `ShellExecutor`)。带 `execution` 时按这次工具调用定下的模式,不带时按部署默认的模式(插件自己的命令),都断网。命令随调用方插件撤销停下。 */
93
+ export interface ShellExecutor {
94
+ resolve(request: ShellExecRequest): Promise<ShellExecSpec>;
95
+ /** 命令规则禁止(`COMMAND_FORBIDDEN`)、没有可用的运行器({@link SandboxUnavailableError})时拒绝,不起进程。 */
96
+ execute(spec: ShellExecSpec): Promise<ShellExecution>;
97
+ }
@@ -0,0 +1,11 @@
1
+ /** 同 0.12:没有可用的运行器时的错误码。 */
2
+ export const SANDBOX_UNAVAILABLE = 'SANDBOX_UNAVAILABLE';
3
+ /** 同 0.12:要求受限执行而这个平台没有可用的运行器。绝不回退成不围。 */
4
+ export class SandboxUnavailableError extends Error {
5
+ code = SANDBOX_UNAVAILABLE;
6
+ constructor(message, options) {
7
+ super(message, options);
8
+ this.name = 'SandboxUnavailableError';
9
+ }
10
+ }
11
+ //# sourceMappingURL=permissions.js.map