@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.d.ts ADDED
@@ -0,0 +1,665 @@
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, type Context } from 'cordis';
21
+ import type { AgentCancelCause, AgentErrorInfo, AgentOptions, AgentSource, AgentStatus, ApprovalOutcome, AskUserQuestionAnswer, AskUserQuestionRequestEvent, CancelOptions, FsObservation, FsTarget, FsWriteIntent, InboxTarget, JsonValue, LlmCallConfig, ModelRef, PreStepDecision, PreToolDecision, RequestErrorAction, RequestFailure, StreamFrame, ToolContent, ToolExecutionMode, ToolFilter, ToolSchema, UserContent, UserMessage } from './generated.ts';
22
+ import type { AttachmentStoreService } from './attachments.ts';
23
+ import type { FileSystemService } from './fs.ts';
24
+ import type { JobRegistry } from './jobs.ts';
25
+ import type { LlmService, LlmStreamOptions, StreamChunk } from './llm.ts';
26
+ import type { CommandsService, SkillsService, UserQuestionsService, WebService } from './capabilities.ts';
27
+ import type { ApprovalRequest, ApprovalService, SandboxPolicyService, SandboxProvider, ShellExecutor } from './permissions.ts';
28
+ import type { SystemPromptService } from './prompt.ts';
29
+ import type { SessionEvent } from './session-events.ts';
30
+ import type { SessionHandle, SessionProjectionsService, SessionsService } from './sessions.ts';
31
+ import type { SubagentRuntime } from './subagents.ts';
32
+ import type { PostToolDecision, ToolCallView, ToolExecutionInput, ToolExecutionModeInput, ToolExecutionResult, ToolGuard, ToolGuardOptions, ToolPresentedResult, ToolResultView } from './tools.ts';
33
+ export * from './generated.ts';
34
+ export * from './attachments.ts';
35
+ export * from './fs.ts';
36
+ export * from './jobs.ts';
37
+ export * from './llm.ts';
38
+ export * from './platform.ts';
39
+ export * from './capabilities.ts';
40
+ export * from './credentials.ts';
41
+ export * from './permissions.ts';
42
+ export * from './prompt.ts';
43
+ export * from './session-events.ts';
44
+ export * from './sessions.ts';
45
+ export * from './subagents.ts';
46
+ export * from './tools.ts';
47
+ export * from './storage.ts';
48
+ export * from './settings.ts';
49
+ export * from './subprocess.ts';
50
+ export * from './local-install.ts';
51
+ export * from './runtime-context.ts';
52
+ export * from './cmdline.ts';
53
+ export * from './web.ts';
54
+ /** 收件箱(0.12 的 `Inbox`):agent 待处理的输入。形状有变:读与改都要跨进程,都是异步的。 */
55
+ export interface Inbox {
56
+ /** 排队的消息,每条单独成一轮。 */
57
+ readonly nextTurn: Promise<readonly UserMessage[]>;
58
+ /** 插话,下一步开始时全部认领。 */
59
+ readonly nextStep: Promise<readonly UserMessage[]>;
60
+ /** 丢弃全部待处理的输入,先插话后排队。 */
61
+ clear(): Promise<void>;
62
+ append(target: InboxTarget, message: UserMessage): Promise<void>;
63
+ prepend(target: InboxTarget, message: UserMessage): Promise<void>;
64
+ /** 原地换掉一条,返回它是否还在。 */
65
+ replace(messageId: string, message: UserMessage): Promise<boolean>;
66
+ /** 撤下一条(记作丢弃),返回它是否还在。 */
67
+ remove(messageId: string): Promise<boolean>;
68
+ /** 同数组的 splice,负的 `start` 从末尾算;删掉的记作丢弃。 */
69
+ splice(target: InboxTarget, start: number, deleteCount: number, inserted: readonly UserMessage[]): Promise<readonly UserMessage[]>;
70
+ }
71
+ /**
72
+ * agent 的句柄。agent 与会话一一对应,同一个 id 总是同一个对象,直到会话从宿主内存卸下(`agent/disposed`)。
73
+ * 形状有变:0.12 的同步方法与属性要跨进程,都是异步的,加 `await`。写入失败(如会话被 0.12 开着、子 agent 的会话)时 Promise 拒绝。
74
+ */
75
+ export interface AgentHandle {
76
+ readonly id: string;
77
+ readonly session: SessionHandle;
78
+ /** 这个 agent 的上下文:`on`、`effect`、`tools`、`systemPrompt`、`agents` 都只对它生效,随 agent 卸下或放手撤销。 */
79
+ readonly ctx: Context;
80
+ /** 这个 agent 此刻的请求配置。 */
81
+ readonly options: Promise<AgentOptions>;
82
+ readonly status: Promise<AgentStatus>;
83
+ readonly inbox: Inbox;
84
+ /** 把消息放进收件箱的一张清单,`wakeup` 时唤醒驱动。这一轮已经取消时插话改排队。 */
85
+ send(message: UserMessage, target: InboxTarget, wakeup: boolean): Promise<void>;
86
+ /** 排队单独成一轮,唤醒驱动。 */
87
+ followup(message: UserMessage): Promise<void>;
88
+ /** 插话:在跑时下一步认领,空闲时开始一轮。 */
89
+ steer(message: UserMessage): Promise<void>;
90
+ /** 放进下一步的输入,不唤醒。 */
91
+ inject(message: UserMessage): Promise<void>;
92
+ /** 取消在跑的这一轮或维护任务;不给 `keepInbox` 时一并丢掉待处理的输入。 */
93
+ cancel(cause: AgentCancelCause, options?: CancelOptions): Promise<void>;
94
+ /** 等到没有驱动与维护任务在跑。 */
95
+ whenIdle(): Promise<void>;
96
+ /** 占住空闲的 agent 做维护,期间的发送排进队列;不空闲时报错。`signal` 随 `cancel` 触发。 */
97
+ runMaintenance<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
98
+ }
99
+ /** 同 0.12 的 `Agent`:agent 的句柄。 */
100
+ export type Agent = AgentHandle;
101
+ /** 同 0.12 的 `ToolRunContext`:工具执行时拿到的调用句柄。 */
102
+ export interface ToolRunContext extends ToolExecution {
103
+ /**
104
+ * 给这次调用的结果带一条上下文,记下结果之后排进插话、下一步交给模型;复合工具用它把嵌套调用的上下文带回来。形状有变:`source.kind`
105
+ * 不能是 `user`(抛错),其余的来源写进会话时统一成工具的通知,原来的 `kind` 留在摘要里;图片与文件要在附件存储里。
106
+ */
107
+ deferContext(context: UserMessage): void;
108
+ /** 这次调用成功时,这一批结果记下之后结束这一轮(同一条回复里的其他调用照常跑完)。失败的结果不看它。 */
109
+ concludeTurn(): void;
110
+ }
111
+ /** `tools/execute` 的监听者拿到的句柄(0.12 的 `ToolDispatchExecution`):可以换 `signal`,只在监听者运行期间;去不掉调用方的取消。 */
112
+ export interface ToolDispatchExecution extends Omit<ToolExecution, 'signal'> {
113
+ signal: AbortSignal;
114
+ }
115
+ /** 同 0.12:会话 id、工具调用 id、消息 id 与推理档位都是字符串,不是品牌类型。 */
116
+ export type SessionId = string;
117
+ export type ToolCallId = string;
118
+ /** cordis 的 `FiberState`:上游是 `const enum`,`verbatimModuleSyntax` 下不能直接用,取这份。 */
119
+ export declare const FiberState: {
120
+ readonly PENDING: 0;
121
+ readonly LOADING: 1;
122
+ readonly ACTIVE: 2;
123
+ readonly FAILED: 3;
124
+ readonly DISPOSED: 4;
125
+ readonly UNLOADING: 5;
126
+ };
127
+ /** 事件在会话日志里的序号(0.12 是品牌类型,这里就是数字)。 */
128
+ export type SessionSeq = number;
129
+ export type OptionalSessionSeq = number | null;
130
+ export type MessageId = string;
131
+ export type ReasoningEffortId = string;
132
+ /** 消息来源(0.12 的 `MessageSource`):`kind` 是字符串,插件用自己的不用登记。 */
133
+ export type MessageSource = UserMessage['source'];
134
+ /** 0.12 里登记消息来源的表。这里 `kind` 不查表,留着只为 0.12 的模块扩充照常编译。 */
135
+ export interface MessageSourceMap {
136
+ }
137
+ /** 给模型看的上下文的形式(同 0.12):`snapshot` 只留最新一份,`notice` 是一次性的提醒。 */
138
+ export type ContextFormed = {
139
+ readonly form?: never;
140
+ } | {
141
+ readonly form: 'instructions';
142
+ } | {
143
+ readonly form: 'catalog';
144
+ } | {
145
+ readonly form: 'snapshot';
146
+ readonly sections: readonly {
147
+ readonly name: string;
148
+ readonly text: string;
149
+ }[];
150
+ } | {
151
+ readonly form: 'notice';
152
+ readonly summary: string;
153
+ };
154
+ /** 同 0.12 的 `createUserMessage`:给一条用户消息分配 id,并冻结。`source.kind` 写消息的来源,`user` 在界面上显示成用户发的。 */
155
+ export declare function createUserMessage(input: {
156
+ readonly content: readonly UserContent[];
157
+ readonly source: UserMessage['source'];
158
+ }): Readonly<UserMessage>;
159
+ /** 同 0.12 的 `AgentSetup`:agent 发布之前往它的上下文里注册(工具、提示词段、收起工具、监听者)。只做组合,不驱动它。 */
160
+ export type AgentSetup = (agentCtx: Context, agent: Agent) => {
161
+ commit(): void;
162
+ } | Promise<{
163
+ commit(): void;
164
+ } | void> | void;
165
+ /** `ctx.agents.create` 的参数(0.12 的 `CreateAgentOptions`)。 */
166
+ export interface CreateAgentOptions {
167
+ /** 不给时生成一个。已有的会话 id 报错。 */
168
+ readonly sessionId?: string;
169
+ /** 持有它的 agent:持有者放手或卸下时它也放手。经 `agent.ctx.agents.create` 建时默认是那个 agent。 */
170
+ readonly parentAgent?: Agent;
171
+ /** 只收 `cwd`(绝对路径,不给时用宿主的默认目录)。插件不能写血缘。 */
172
+ readonly meta?: {
173
+ readonly cwd?: string;
174
+ };
175
+ /** 模型配置;不给时用新对话的默认模型。 */
176
+ readonly agentOptions?: AgentOptions;
177
+ /**
178
+ * 模型在这个会话(及它的子 agent 的会话)里跑的命令额外加的环境变量,如外部应用经 `ftai app` 交给插件的运行参数。放手
179
+ * (`dispose`)或插件进程退出时撤掉;只在内存里,不记进会话日志。宿主自己设的 `FTAI_*` 以宿主的为准;插件给的不按名字过滤。
180
+ * 名字不能为空、不能含 `=`,名字与值都不能含 NUL,否则报 `invalid_params`。
181
+ */
182
+ readonly env?: Readonly<Record<string, string>>;
183
+ /**
184
+ * 列不列在用户的会话列表里(桌面端的侧栏、搜索与项目,手机上的列表),不给时列出。只有外部应用(`ftai app` 起的进程)能给
185
+ * `false`:会话里有应用自己的内容、只该在应用里看时用,桌面端打开这样的会话时只读,并提示到应用里查看。用户的插件进程里给
186
+ * `false` 报 `invalid_params`。宿主把它连同应用一起记进会话,从这个会话分叉出的会话沿用。
187
+ */
188
+ readonly listed?: boolean;
189
+ /** 取消这次建立。 */
190
+ readonly signal?: AbortSignal;
191
+ readonly setup?: AgentSetup;
192
+ }
193
+ /** `ctx.agents.resume` 的参数(0.12 的 `ResumeAgentOptions`)。 */
194
+ export interface ResumeAgentOptions {
195
+ /**
196
+ * 已有的会话 id,不存在时报错。可以是用户正开着的会话,也可以是本插件已经持有的(每次续都多一个持有者)。续失败时这次 `setup`
197
+ * 在 agent 上做的注册不撤销(setup 拿到的就是 `agent.ctx`),随 agent 卸下一起撤;不想留着就自己撤。
198
+ */
199
+ readonly resumeSessionId: string;
200
+ readonly parentAgent?: Agent;
201
+ readonly agentOptions?: AgentOptions;
202
+ /** 同 `CreateAgentOptions.env`:给了就换掉之前给的,不给时沿用还没撤掉的。 */
203
+ readonly env?: Readonly<Record<string, string>>;
204
+ readonly signal?: AbortSignal;
205
+ readonly setup?: AgentSetup;
206
+ }
207
+ /** `ctx.agents.create`、`resume` 的结果(0.12 的 `AgentHandle`):agent 与放手它的方法。 */
208
+ export interface OwnedAgent {
209
+ readonly agent: Agent;
210
+ /**
211
+ * 放手:停下在跑的一轮(待处理的输入留着,取消原因记 `{ kind: 'hook', reason: 'plugin-disposed' }`),撤销 `agent.ctx` 上的注册,
212
+ * 放手它持有的 agent;之后没人跟随时会话在下一次核对时(最长约 1 分钟)卸下。持有它的插件停用时自动调用。
213
+ */
214
+ dispose(): Promise<void>;
215
+ }
216
+ /** 一次工具调用的句柄(0.12 的 `ToolExecution`):同一次调用总是同一个对象,可以作 WeakMap 的键。 */
217
+ export interface ToolExecution {
218
+ readonly token: string;
219
+ readonly callId: string;
220
+ /** 所在调用树的根调用:模型发起的调用等于 `callId`,嵌套调用是调用方传的值。 */
221
+ readonly rootCallId: string;
222
+ readonly name: string;
223
+ /** 模型给的参数(解析后的 JSON,同 0.12;解析不了时是原文)。 */
224
+ readonly arguments: unknown;
225
+ readonly agent: AgentHandle;
226
+ /**
227
+ * 发起这次调用的那一步实际用的模型(代替 0.12 读的 `agent.session.requestHeader().config`),子 agent 里是它自己的;
228
+ * 不是模型发起的调用没有。
229
+ */
230
+ readonly model?: ModelRef;
231
+ /** 同 0.12:这次调用被取消(如轮次取消)时触发;只在工具执行期间可能触发。 */
232
+ readonly signal: AbortSignal;
233
+ }
234
+ /** 插件记录:插件写进会话的可忽略事件。 */
235
+ export interface PluginRecord {
236
+ readonly type: string;
237
+ readonly seq: number;
238
+ readonly time: number;
239
+ readonly data: unknown;
240
+ }
241
+ /** 各种值都可以带的说明。 */
242
+ export interface ValueSchemaAnnotations {
243
+ description?: string;
244
+ title?: string;
245
+ default?: JsonValue;
246
+ examples?: JsonValue;
247
+ }
248
+ export interface StringValueSchemaSpec extends ValueSchemaAnnotations {
249
+ type: 'string';
250
+ enum?: readonly string[];
251
+ const?: string;
252
+ }
253
+ export interface NumberValueSchemaSpec extends ValueSchemaAnnotations {
254
+ type: 'number';
255
+ enum?: readonly number[];
256
+ const?: number;
257
+ }
258
+ export interface IntegerValueSchemaSpec extends ValueSchemaAnnotations {
259
+ type: 'integer';
260
+ enum?: readonly number[];
261
+ const?: number;
262
+ }
263
+ export interface BooleanValueSchemaSpec extends ValueSchemaAnnotations {
264
+ type: 'boolean';
265
+ enum?: readonly boolean[];
266
+ const?: boolean;
267
+ }
268
+ export interface NullValueSchemaSpec extends ValueSchemaAnnotations {
269
+ type: 'null';
270
+ enum?: readonly null[];
271
+ const?: null;
272
+ }
273
+ export interface ArrayValueSchemaSpec extends ValueSchemaAnnotations {
274
+ type: 'array';
275
+ items?: ValueSchemaSpec;
276
+ }
277
+ export interface ObjectValueSchemaSpec extends ValueSchemaAnnotations {
278
+ type: 'object';
279
+ properties?: ParameterSchemaSpec;
280
+ additionalProperties: boolean;
281
+ }
282
+ /** 任意 JSON 值,发给模型时只带说明。 */
283
+ export interface JsonValueSchemaSpec extends ValueSchemaAnnotations {
284
+ type: 'json';
285
+ }
286
+ export interface OneOfValueSchemaSpec extends ValueSchemaAnnotations {
287
+ oneOf: readonly [ValueSchemaSpec, ValueSchemaSpec, ...ValueSchemaSpec[]];
288
+ }
289
+ export type ValueSchemaSpec = StringValueSchemaSpec | NumberValueSchemaSpec | IntegerValueSchemaSpec | BooleanValueSchemaSpec | NullValueSchemaSpec | ArrayValueSchemaSpec | ObjectValueSchemaSpec | JsonValueSchemaSpec | OneOfValueSchemaSpec;
290
+ /** 一个参数:值的写法,必填的另标 `required: true`。 */
291
+ export type ParameterPropertySpec = ValueSchemaSpec & {
292
+ required?: true;
293
+ };
294
+ /** 参数表:参数名 → 写法。 */
295
+ export type ParameterSchemaSpec = {
296
+ [key: string]: ParameterPropertySpec;
297
+ [key: symbol]: never;
298
+ };
299
+ type Simplify<T> = {
300
+ [K in keyof T]: T[K];
301
+ } & {};
302
+ type StringKeyOf<S> = Extract<keyof S, string>;
303
+ type RequiredKeys<S> = {
304
+ [K in StringKeyOf<S>]: S[K] extends {
305
+ required: true;
306
+ } ? K : never;
307
+ }[StringKeyOf<S>];
308
+ type InferProperties<S, Depth extends unknown[]> = Simplify<{
309
+ [K in RequiredKeys<S>]: InferValueAt<S[K], Depth>;
310
+ } & {
311
+ [K in Exclude<StringKeyOf<S>, RequiredKeys<S>>]?: InferValueAt<S[K], Depth>;
312
+ }>;
313
+ type InferObject<S extends {
314
+ additionalProperties: boolean;
315
+ }, Depth extends unknown[]> = S extends {
316
+ properties: infer P;
317
+ } ? S['additionalProperties'] extends true ? InferProperties<P, Depth> & Record<string, JsonValue> : InferProperties<P, Depth> : S['additionalProperties'] extends true ? Record<string, JsonValue> : Record<string, never>;
318
+ type InferScalar<S, Fallback> = S extends {
319
+ const: infer C;
320
+ } ? C : S extends {
321
+ enum: readonly (infer E)[];
322
+ } ? E : Fallback;
323
+ type Deeper<Depth extends unknown[]> = [unknown, ...Depth];
324
+ type InferValueAt<S, Depth extends unknown[]> = Depth['length'] extends 16 ? JsonValue : S extends {
325
+ type: 'string';
326
+ } ? InferScalar<S, string> : S extends {
327
+ type: 'number' | 'integer';
328
+ } ? InferScalar<S, number> : S extends {
329
+ type: 'boolean';
330
+ } ? InferScalar<S, boolean> : S extends {
331
+ type: 'null';
332
+ } ? null : S extends {
333
+ type: 'array';
334
+ } ? S extends {
335
+ items: infer I;
336
+ } ? InferValueAt<I, Deeper<Depth>>[] : JsonValue[] : S extends {
337
+ type: 'object';
338
+ additionalProperties: boolean;
339
+ } ? InferObject<S, Deeper<Depth>> : S extends {
340
+ type: 'json';
341
+ } ? JsonValue : S extends {
342
+ oneOf: readonly unknown[];
343
+ } ? InferValueAt<S['oneOf'][number], Deeper<Depth>> : never;
344
+ /** 同 0.12 的 `tools`:值的写法对应的 TS 类型。 */
345
+ export type InferValue<S> = InferValueAt<S, []>;
346
+ /** 同 0.12 的 `tools`:参数表对应的参数对象类型。 */
347
+ export type InferArgs<S> = InferProperties<S, []>;
348
+ /**
349
+ * 申请提权的两个参数(`sandboxEscalation: true` 时由宿主加进参数表,写法与说明同核心的文件工具):为这一次调用申请更宽的
350
+ * 沙箱模式,两个一起给。宿主在执行之前已经按它们审批并定下了这一次的模式,插件只是读得到。
351
+ */
352
+ export interface SandboxEscalationArgs {
353
+ sandbox_permissions?: 'workspace-write' | 'danger-full-access';
354
+ justification?: string;
355
+ }
356
+ /** 工具收到的参数:声明了 `sandboxEscalation` 时多出申请提权的两个参数。 */
357
+ export type ToolArgs<S, E extends boolean> = E extends true ? Simplify<InferArgs<S> & SandboxEscalationArgs> : InferArgs<S>;
358
+ /** 同 0.12 `tools` 的 `DefineToolOptions`:参数与结果的类型由写法推出。 */
359
+ export interface DefineToolOptions<S extends ParameterSchemaSpec, O extends ValueSchemaSpec, E extends boolean = false> {
360
+ readonly name: string;
361
+ readonly description: string;
362
+ readonly parameters: S;
363
+ readonly output: {
364
+ readonly schema: O;
365
+ /**
366
+ * 把执行结果变成给模型看的内容:文本块与图片块(图片先经 `ctx.attachments.saveImages` 存下,块里放它的引用)。
367
+ * 在插件进程里、执行之后调用。
368
+ */
369
+ render(args: ToolArgs<S, E>, value: InferValue<NoInfer<O>>): readonly ToolContent[];
370
+ };
371
+ /**
372
+ * 能不能与同一条回复里相邻的调用一起跑。函数形式每次按参数问一次(形状有变:宿主等它的答复,超时 5 秒;抛错、超时、崩溃或不是 `true`
373
+ * 都按独占)。要快、不要有副作用。
374
+ */
375
+ readonly isConcurrencySafe?: boolean | ((args: ToolArgs<S, E>) => boolean | Promise<boolean>);
376
+ /** 单个工具的超时(毫秒):到时这次调用记作 `TOOL_TIMEOUT`,`exec.signal` 随之触发。`tools/execute` 的监听者也算在内。不给时不限时。 */
377
+ readonly timeoutMs?: number;
378
+ /**
379
+ * 结果写进会话之前的最后一次改写,只换给模型看的内容,拒绝、超时、取消的结果也经过这里。返回 `undefined` 不换。形状有变:可以是异步的,
380
+ * 拿到的是快照(`exec` 没有活的 agent 以外的东西);抛错或超时(30 秒,这一轮已取消时 2 秒)时结果换成固定的失败文本,不回退到原文。
381
+ */
382
+ finalizeContent?(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): readonly ToolContent[] | undefined | Promise<readonly ToolContent[] | undefined>;
383
+ /** 工具卡片按参数的待定视图。只影响显示,要快(宿主最多等 2 秒),抛错或等不到时按默认卡片。结论随会话记下,回放时不再调用。 */
384
+ presentCall?(args: ToolArgs<S, E>): ToolCallView | undefined | Promise<ToolCallView | undefined>;
385
+ /** 工具卡片按结果的完成视图。同 `presentCall`。 */
386
+ presentResult?(args: ToolArgs<S, E>, result: ToolPresentedResult): ToolResultView | undefined | Promise<ToolResultView | undefined>;
387
+ /** 默认要用户审批(`tools/pre-execute` 的默认结论为 ask)。 */
388
+ readonly needsApproval?: boolean;
389
+ /**
390
+ * 可以为一次调用申请更宽的沙箱模式,同核心的文件工具(0.12 插件自己带的 `sandbox_permissions` 与 `justification`):
391
+ * 宿主给参数表加上这两个参数(`parameters` 里不能自带),执行之前按申请经审批定下这一次的模式,没批准时工具不执行、
392
+ * 模型收到说明;`ctx.fs.writeBytes` 带着这次调用(`execution: exec`)写入时按这个模式围住,越界被拒时错误的说明带被拒
393
+ * 标记与提权提示,抛给模型即可。批准只管这一次调用。
394
+ */
395
+ readonly sandboxEscalation?: E;
396
+ execute(args: ToolArgs<S, E>, exec: ToolRunContext): Promise<InferValue<NoInfer<O>>>;
397
+ }
398
+ /** 一个可以注册的工具(`defineTool` 的结果)。 */
399
+ export interface ToolDefinition {
400
+ readonly name: string;
401
+ readonly description: string;
402
+ /** `defineTool` 的参数表,或根上 `type: 'object'` 的 JSON Schema(同 0.12 直接调 `ctx.tools.register`,schema 来自外面时用)。 */
403
+ readonly parameters: ParameterSchemaSpec | Readonly<Record<string, unknown>>;
404
+ readonly output: {
405
+ /** 值的写法,或 JSON Schema 子集(`required` 数组)。 */
406
+ readonly schema: ValueSchemaSpec | Readonly<Record<string, unknown>>;
407
+ render(args: never, value: never): readonly ToolContent[];
408
+ };
409
+ readonly isConcurrencySafe?: boolean | ((args: never) => boolean | Promise<boolean>);
410
+ readonly timeoutMs?: number;
411
+ finalizeContent?(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): readonly ToolContent[] | undefined | Promise<readonly ToolContent[] | undefined>;
412
+ presentCall?(args: never): ToolCallView | undefined | Promise<ToolCallView | undefined>;
413
+ presentResult?(args: never, result: ToolPresentedResult): ToolResultView | undefined | Promise<ToolResultView | undefined>;
414
+ readonly needsApproval?: boolean;
415
+ readonly sandboxEscalation?: boolean;
416
+ execute(args: never, exec: ToolRunContext): Promise<unknown>;
417
+ }
418
+ /** 同 0.12 `tools` 的 `defineTool`:参数与结果的类型由 `parameters` 与 `output.schema` 推出。 */
419
+ export declare function defineTool<const S extends ParameterSchemaSpec, const O extends ValueSchemaSpec, const E extends boolean = false>(options: DefineToolOptions<S, O, E>): ToolDefinition;
420
+ /** 插件记录的类型表:插件以模块扩充声明自己的记录(同 0.12 `session` 的 PluginRecordMap)。 */
421
+ export interface PluginRecordMap {
422
+ }
423
+ export interface ToolsService {
424
+ register(definition: ToolDefinition): () => void;
425
+ /** 收起工具,多个限制取交集。只能在 `agent.ctx.tools` 上调用(同 0.12)。 */
426
+ restrict(filter: ToolFilter): () => void;
427
+ /**
428
+ * 只能拒绝的关口,排在全部 `tools/pre-execute` 与审批之后、工具体之前。在 `agent.ctx.tools` 上调用时只管那个 agent 的调用。
429
+ * 关口失败当它没表态,`options.failClosed` 为 true 时按拒绝。
430
+ */
431
+ guard(guard: ToolGuard, options?: ToolGuardOptions): () => void;
432
+ /** 形状有变:0.12 里是同步的,给完整定义。这里只有 schema,不含执行体。`scope` 给出时按它看到的,不给时按全局的。 */
433
+ get(name: string, scope?: AgentHandle): Promise<ToolSchema | undefined>;
434
+ /** 形状有变:0.12 里是同步的。看得到的工具的 schema,按名字排好,含还没加载的延迟工具。`scope` 同 {@link get}。 */
435
+ schemas(scope?: AgentHandle): Promise<ToolSchema[]>;
436
+ /** 形状有变:0.12 里是同步的。不认识的工具、判定失败或不是 `true` 都是 `exclusive`。 */
437
+ executionMode(exec: ToolExecutionModeInput): Promise<ToolExecutionMode>;
438
+ /**
439
+ * 执行一次工具调用,与模型发起的调用走同一条路:`tools/pre-execute`、审批、`guard`、沙箱、`tools/execute`、`tools/post-execute`。不写 tool/call
440
+ * 与 tool/result,上下文与 `concludesTurn` 在结果里,由调用方带进自己的结果(`exec.deferContext`)。要审批的调用只能在进行中的一轮里。
441
+ * 失败与取消都是失败的结果;没有这个 agent、会话已归档时 Promise 拒绝。
442
+ */
443
+ execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>;
444
+ }
445
+ export interface AgentsService {
446
+ /** 本进程见过的 agent(同一个 id 总是同一个对象);要全部活着的用 `list`。 */
447
+ get(id: string): AgentHandle | undefined;
448
+ /** 形状有变:0.12 里是同步的。宿主内存里全部的 agent,按建立的先后。 */
449
+ list(): Promise<AgentHandle[]>;
450
+ /** 形状有变:0.12 里是同步的。没有持有者的 agent。 */
451
+ roots(): Promise<AgentHandle[]>;
452
+ /** 形状有变:0.12 里是同步的。`owner` 是这个 agent 的直接持有者。 */
453
+ isOwnedBy(id: string, owner: Agent): Promise<boolean>;
454
+ create(options?: CreateAgentOptions): Promise<OwnedAgent>;
455
+ resume(options: ResumeAgentOptions): Promise<OwnedAgent>;
456
+ /** 这条异步链路的发起者:工具执行与带 agent 的扩展点监听者里是那个 agent。只在插件进程内有效,不是权限依据。 */
457
+ currentInitiator(): AgentHandle | undefined;
458
+ /** 同 `currentInitiator`,没有发起者时抛错。 */
459
+ requireInitiator(): AgentHandle;
460
+ withInitiator<T>(agent: Agent, operation: () => T): T;
461
+ withoutInitiator<T>(operation: () => T): T;
462
+ }
463
+ declare module 'cordis' {
464
+ interface Context {
465
+ tools: ToolsService;
466
+ systemPrompt: SystemPromptService;
467
+ sessionProjections: SessionProjectionsService;
468
+ sessions: SessionsService;
469
+ agents: AgentsService;
470
+ fs: FileSystemService;
471
+ attachments: AttachmentStoreService;
472
+ llm: LlmService;
473
+ jobs: JobRegistry;
474
+ subagents: SubagentRuntime;
475
+ userQuestions: UserQuestionsService;
476
+ web: WebService;
477
+ skills: SkillsService;
478
+ commands: CommandsService;
479
+ approval: ApprovalService;
480
+ sandboxPolicy: SandboxPolicyService;
481
+ sandbox: SandboxProvider;
482
+ shell: ShellExecutor;
483
+ }
484
+ interface Events {
485
+ 'tools/pre-execute'(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> | PreToolDecision;
486
+ 'tools/execute'(exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> | ToolExecutionResult;
487
+ 'tools/post-execute'(exec: ToolExecution, result: Readonly<ToolExecutionResult>, next: () => Promise<PostToolDecision>): Promise<PostToolDecision> | PostToolDecision;
488
+ 'tools/result'(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): void;
489
+ 'agent/created'(payload: {
490
+ agent: AgentHandle;
491
+ source: AgentSource;
492
+ signal: AbortSignal;
493
+ }): void | Promise<void>;
494
+ 'agent/assistant-stream'(payload: {
495
+ agent: AgentHandle;
496
+ frame: StreamFrame;
497
+ }): void;
498
+ 'session/event'(session: SessionHandle, event: SessionEvent): void;
499
+ 'session/created'(session: SessionHandle): void;
500
+ 'session/disposed'(session: SessionHandle): void;
501
+ 'session/flush'(session: SessionHandle): void | Promise<void>;
502
+ 'agent/disposed'(payload: {
503
+ agent: AgentHandle;
504
+ }): void;
505
+ 'agent/status'(payload: {
506
+ agent: AgentHandle;
507
+ status: AgentStatus;
508
+ }): void;
509
+ 'agent/error'(payload: {
510
+ agent: AgentHandle;
511
+ turn: number;
512
+ step: number;
513
+ error: AgentErrorInfo;
514
+ }): void;
515
+ 'agent/inbox/inserted'(payload: {
516
+ agent: AgentHandle;
517
+ message: UserMessage;
518
+ }): void;
519
+ 'agent/inbox/claimed'(payload: {
520
+ agent: AgentHandle;
521
+ message: UserMessage;
522
+ turn: number;
523
+ }): void;
524
+ 'agent/inbox/discarded'(payload: {
525
+ agent: AgentHandle;
526
+ message: UserMessage;
527
+ }): void;
528
+ 'agent/pre-step'(payload: {
529
+ agent: AgentHandle;
530
+ messages: UserMessage[];
531
+ turn: number;
532
+ step: number;
533
+ signal: AbortSignal;
534
+ }, next: () => Promise<PreStepDecision>): Promise<PreStepDecision> | PreStepDecision;
535
+ 'agent/request'(payload: {
536
+ agent: AgentHandle;
537
+ turn: number;
538
+ step: number;
539
+ signal: AbortSignal;
540
+ }, next: () => Promise<LlmCallConfig>): Promise<LlmCallConfig> | LlmCallConfig;
541
+ 'agent/request-error'(payload: {
542
+ agent: AgentHandle;
543
+ turn: number;
544
+ step: number;
545
+ provider: string;
546
+ failure: RequestFailure;
547
+ signal: AbortSignal;
548
+ }, next: () => Promise<RequestErrorAction | undefined>): Promise<RequestErrorAction | undefined> | RequestErrorAction | undefined;
549
+ 'agent/turn-stopping'(payload: {
550
+ agent: AgentHandle;
551
+ turn: number;
552
+ signal: AbortSignal;
553
+ }): void | Promise<void>;
554
+ /**
555
+ * 整份写入之前:只能收紧。返回的条件与宿主的先读后改都要满足,不调用 `next` 时宿主照样跑下游;抛 `FsError` 时这次写入以它结束;
556
+ * 其他错误、超时或插件进程不在时这次写入以 `FS_IO_ERROR` 结束。监听者总是排在观察策略之前。插件不能发起。
557
+ */
558
+ 'fs/write-intent'(target: FsTarget, actor: ToolExecution | undefined, next: () => Promise<FsWriteIntent | undefined>): Promise<FsWriteIntent | undefined> | FsWriteIntent | undefined;
559
+ /** 编辑之前,同 `fs/write-intent`:结论是这次编辑要核对的版本。插件不能发起。 */
560
+ 'fs/edit-intent'(target: FsTarget, actor: ToolExecution | undefined, next: () => Promise<{
561
+ version: string;
562
+ } | undefined>): Promise<{
563
+ version: string;
564
+ } | undefined> | {
565
+ version: string;
566
+ } | undefined;
567
+ /** 文件工具确定地看到了一个目标在或不在。只能监听:发起不算观察,放宽不了先读后改。 */
568
+ 'fs/observed'(target: FsTarget, observation: FsObservation, actor: ToolExecution | undefined): void;
569
+ 'llm/stream'(options: LlmStreamOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> | Promise<AsyncIterable<StreamChunk>>;
570
+ /**
571
+ * 向用户提问之前:调用 `next()` 交给后面的监听者,最后到界面的提问卡片,等用户的时间不计入这个监听者的上限(60 秒);用户关掉提问或没有界面时
572
+ * `next()` 以 `UserQuestionError` 拒绝。不调用 `next` 就是替用户作答。抛错、超时或插件进程不在时不算作答,交给下一个。
573
+ */
574
+ 'user-questions/request'(request: AskUserQuestionRequestEvent & {
575
+ readonly signal: AbortSignal;
576
+ }, next: () => Promise<AskUserQuestionAnswer>): Promise<AskUserQuestionAnswer> | AskUserQuestionAnswer;
577
+ /**
578
+ * 工具调用要批准时:返回结论作答,或调用 `next()` 交给下一个,最里层是界面卡片。监听要声明 `approval.observe`(契约 2.3.0 起)。
579
+ * `allowed-once` 等于用户批准这一次,包括提权;要声明 `approval.answer` 并经用户授权,否则当它没表态、交给下一个,卡上写明插件的建议。
580
+ * 「替我审批」与审批策略 never 的会话不派发。抛错、崩溃、自身用时超过 60 秒(等 `next()` 的时间不算)、返回值不是四种之一时当它没表态、
581
+ * 交给下一个;监听时写了 `failClosed: true` 的是 `unavailable`。
582
+ */
583
+ 'approval/request'(request: ApprovalRequest, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome> | ApprovalOutcome;
584
+ }
585
+ }
586
+ /** 这个事件类型是插件记录的写法(`plugin:` 后面是斜杠分隔的段,同 0.12)。 */
587
+ export declare function isPluginRecordType(type: string): boolean;
588
+ /** 同 0.12 的 `session`:插件记录事件的内容;不是插件记录时为 undefined。 */
589
+ export declare function pluginRecordOf(event: SessionEvent): PluginRecord | undefined;
590
+ /** 插件运行时装上的宿主连接;插件进程之外调用 SDK 的写入函数时报错。 */
591
+ export interface RuntimeBridge {
592
+ appendPluginRecord(session: SessionHandle, type: string, data: unknown): Promise<number>;
593
+ /**
594
+ * 挂载一个 remote 命名空间,返回撤销函数。`invoke` 调用服务上对应的方法,最后一个参数是这次调用的取消信号;
595
+ * 流式方法返回(异步)可迭代对象。`service` 是服务名,方法里经 `ctx.invocation` 读到。
596
+ */
597
+ mountRemote(ctx: Context, service: string, namespace: string, methods: readonly RemoteMethodEntry[], invoke: (method: string, args: unknown[], signal: AbortSignal) => unknown): () => void;
598
+ }
599
+ /** 由插件运行时调用一次,插件不要调用。 */
600
+ export declare function installRuntime(runtime: RuntimeBridge): void;
601
+ /**
602
+ * 形状有变:0.12 里是同步的。追加一条插件记录(可忽略的会话事件,模型看不到),返回它的 seq;
603
+ * 兑现时本进程的会话投影已经折叠了它(读到自己的写入)。
604
+ */
605
+ export declare function appendPluginRecord<Type extends keyof PluginRecordMap & string>(session: SessionHandle, type: Type, data: PluginRecordMap[Type]): Promise<number>;
606
+ /**
607
+ * remote 失败的错误码 → `details` 的类型。插件以模块扩充登记自己的错误码,写成 `<插件 id>/<原因>`;
608
+ * 插件前端按 `error.code` 分支时 `error.details` 带上对应的类型。
609
+ */
610
+ export interface RemoteErrorDetailsMap {
611
+ /** 请求不对(参数缺失或形状不对)。 */
612
+ 'remote/bad-request': {
613
+ readonly issues?: readonly object[];
614
+ };
615
+ /** 调用被取消。 */
616
+ 'remote/cancelled': {};
617
+ /** 插件后端出了没有预料到的错误;说明只给日志看。 */
618
+ 'remote/internal': {};
619
+ /** 问一个草稿端点的模型失败(`ctx.llm.remoteDiscoverModels`)。 */
620
+ 'llm/model-discovery-rejected': {
621
+ readonly settingsNs: string;
622
+ readonly baseURL?: string;
623
+ };
624
+ }
625
+ export type RemoteErrorCode = keyof RemoteErrorDetailsMap & string;
626
+ /** remote 调用的失败:插件后端在失败处抛出,宿主把错误码、说明与 `details` 原样交给插件前端。 */
627
+ export declare class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends Error {
628
+ /** 结构上的标记:跨模块副本识别时不用 instanceof。 */
629
+ readonly isRemoteError = true;
630
+ readonly code: Code;
631
+ readonly details: RemoteErrorDetailsMap[Code];
632
+ constructor(code: Code, message: string, details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);
633
+ }
634
+ /** `@Remote` 的选项(同 0.12 之后 dsh 的 `@Remote({ name, mode })`;dsh 的 `resources` 不支持)。 */
635
+ export interface RemoteMethodOptions {
636
+ /** 界面调用的名字,不给时是方法名(同 `@Remote('名字')`)。 */
637
+ readonly name?: string;
638
+ /** 流式方法:逐条给出结果。 */
639
+ readonly mode?: 'stream';
640
+ }
641
+ /** 一个 remote 方法:服务上的方法名、界面调用的名字与是否流式。 */
642
+ export interface RemoteMethodEntry {
643
+ readonly member: string;
644
+ readonly name: string;
645
+ readonly stream: boolean;
646
+ }
647
+ type MethodDecorator = <This extends object, Args extends unknown[], Result>(method: (this: This, ...args: Args) => Result, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Result>) => void;
648
+ /**
649
+ * 同 0.12 的 `typert-protocol`:把一个公开的实例方法标为插件前端可调用。`@Remote` 是请求/应答,`@Remote('名字')` 换一个
650
+ * 调用名,`@Remote({ mode: 'stream' })` 是流式方法(返回可迭代对象,逐条交给界面),两者可以合写成 `@Remote({ name, mode })`。
651
+ * 参数与返回值只能是 JSON;宿主在调用时另传最后一个参数 `signal: AbortSignal`,界面取消时触发。
652
+ * 选项里有别的键(如 dsh 的 `resources`)时抛错:静默忽略会让方法以意料之外的名字或方式挂上。
653
+ */
654
+ 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;
655
+ export declare function Remote(option: string | RemoteMethodOptions): MethodDecorator;
656
+ /**
657
+ * 同 0.12 的 `typert-protocol`:给插件前端提供 remote 服务的服务基类。服务名就是 remote 命名空间(可另给 `namespace`),
658
+ * 由插件 id 派生,所有插件里唯一;服务在时命名空间挂着,服务撤销(插件停用、卸载)时随之撤销。
659
+ * 插件进程之外(如插件自己的单测)不挂载,服务照常可用。
660
+ */
661
+ export declare abstract class TypertRemoteService<T = never> extends Service<T> {
662
+ protected constructor(ctx: Context, serviceKey: string, options?: {
663
+ readonly namespace?: string;
664
+ });
665
+ }