@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Non-Convex Tech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @ftai/plugin-host-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ FtAi Desktop 插件后端的接口。插件经 `@ftai/plugin-sdk/host` 使用,不用直接依赖本包。
4
+
5
+ 开发文档见 <https://ftai.chat/desktop/docs/plugins/>。
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 附件(0.12 的 `ctx.attachments`,0.12 的 `attachment` 包):把图片存进宿主的附件存储,引用可以放进工具结果与
3
+ * 模型请求。名字、引用的字段与错误码照 0.12;引用的形状由扩展点表生成(`ImageRef`、`FileRef`)。
4
+ * @module
5
+ */
6
+ import type { FileRef, FileUpload, ImageAttachmentLimits, ImageMediaType, ImageRef, ImageRequestTarget, ImageUpload, RequestImageVersion } from './generated.ts';
7
+ /** 0.12 的名字:存下的一张图片(会话日志里也是这个形状),缩小过的带 `originalDimensions`。 */
8
+ export type ImageAttachmentRef = ImageRef;
9
+ /** 0.12 的名字:存下的一个文件。 */
10
+ export type FileAttachmentRef = FileRef;
11
+ export interface SaveImageAttachment {
12
+ readonly data: Uint8Array;
13
+ readonly mediaType: ImageMediaType;
14
+ readonly name?: string;
15
+ }
16
+ /** 0.12 的名字:base64 编码的图片。只认规范的 base64,`name` 不当路径解释。 */
17
+ export type EncodedImageAttachment = ImageUpload;
18
+ /** 0.12 的名字:base64 编码的文件。只认规范的 base64,空文件可以。 */
19
+ export type EncodedFileAttachment = FileUpload;
20
+ export interface SaveFileAttachment {
21
+ readonly data: Uint8Array;
22
+ readonly name?: string;
23
+ }
24
+ export interface SaveFileStreamAttachment {
25
+ /** 文件的字节,按顺序。 */
26
+ readonly data: AsyncIterable<Uint8Array>;
27
+ /** 中止时暂存的内容删除,不留下半个附件。 */
28
+ readonly signal?: AbortSignal;
29
+ readonly name?: string;
30
+ }
31
+ /** 提示词内容的一块:文本,或待准入的 base64 图片。 */
32
+ export type PromptContentPart = {
33
+ readonly type: 'text';
34
+ readonly text: string;
35
+ } | {
36
+ readonly type: 'image';
37
+ readonly mediaType: ImageMediaType;
38
+ readonly data: string;
39
+ readonly name?: string;
40
+ };
41
+ /** 待准入的提示词内容:文本、base64 图片,或已经存下的文件。 */
42
+ export type AttachmentAdmissionPart = PromptContentPart | {
43
+ readonly type: 'file';
44
+ readonly attachment: FileAttachmentRef;
45
+ };
46
+ /** 准入之后的提示词内容:附件都换成了引用。 */
47
+ export type AdmittedPromptContentPart = {
48
+ readonly type: 'text';
49
+ readonly text: string;
50
+ } | {
51
+ readonly type: 'image';
52
+ readonly attachment: ImageAttachmentRef;
53
+ } | {
54
+ readonly type: 'file';
55
+ readonly attachment: FileAttachmentRef;
56
+ };
57
+ /** 读出的图片:字节已经与引用核对过。 */
58
+ export interface StoredImageAttachment {
59
+ readonly ref: ImageAttachmentRef;
60
+ readonly data: Uint8Array;
61
+ }
62
+ /** 图片的请求版本(0.12 的 `RequestImageAttachment`)。 */
63
+ export interface RequestImageAttachment extends Omit<RequestImageVersion, 'data'> {
64
+ readonly data: Uint8Array;
65
+ readonly depth: 'uchar';
66
+ readonly space: 'srgb';
67
+ }
68
+ export declare const IMAGE_ADMISSION_ERROR_CODES: readonly ["TOO_MANY_IMAGES", "IMAGES_TOO_LARGE", "UNSUPPORTED_IMAGE_TYPE", "INVALID_IMAGE_BASE64", "INVALID_IMAGE", "IMAGE_TYPE_MISMATCH", "IMAGE_TOO_LARGE", "IMAGE_TOO_MANY_PIXELS", "IMAGE_DIMENSION_TOO_LARGE"];
69
+ export declare const ATTACHMENT_ERROR_CODES: readonly ["TOO_MANY_IMAGES", "IMAGES_TOO_LARGE", "UNSUPPORTED_IMAGE_TYPE", "INVALID_IMAGE_BASE64", "INVALID_IMAGE", "IMAGE_TYPE_MISMATCH", "IMAGE_TOO_LARGE", "IMAGE_TOO_MANY_PIXELS", "IMAGE_DIMENSION_TOO_LARGE", "INVALID_FILE_BASE64", "INVALID_ATTACHMENT_REF", "ATTACHMENT_CORRUPT", "ATTACHMENT_WRITE_FAILED", "ATTACHMENT_NOT_FOUND", "ATTACHMENT_READ_FAILED", "ATTACHMENT_PROJECTION_UNSUPPORTED", "ATTACHMENT_FILES_UNSUPPORTED"];
70
+ /** 图片准入的错误码:图片本身不合要求(个数、大小、格式、像素、边长)。 */
71
+ export type ImageAdmissionErrorCode = typeof IMAGE_ADMISSION_ERROR_CODES[number];
72
+ export type AttachmentErrorCode = typeof ATTACHMENT_ERROR_CODES[number];
73
+ /** 附件存储的失败(同 0.12):错误码与 0.12 原文的说明。 */
74
+ export declare class AttachmentError extends Error {
75
+ readonly code: AttachmentErrorCode;
76
+ constructor(message: string, code: AttachmentErrorCode, options?: ErrorOptions);
77
+ }
78
+ export declare function isAttachmentError(error: unknown): error is AttachmentError;
79
+ /** 图片本身不合要求:调用方可以把说明交给模型,换一句替代的文字(同 0.12)。 */
80
+ export declare function isImageAdmissionError(error: unknown): error is AttachmentError & {
81
+ readonly code: ImageAdmissionErrorCode;
82
+ };
83
+ export interface AttachmentStoreService {
84
+ /** 图片准入的上限(同步):这个服务提供时从宿主读的一份快照。宿主里是常量,这个服务在的期间不变。 */
85
+ readonly imageLimits: ImageAttachmentLimits;
86
+ /**
87
+ * 只校验一张图片,不存:准入与规范化同 `saveImage`。
88
+ * @throws AttachmentError
89
+ */
90
+ validateImage(input: SaveImageAttachment): Promise<void>;
91
+ /**
92
+ * 存一批图片:先整批检查个数、总大小与格式,再逐张准入与规范化,全部通过才写入。
93
+ * @returns 与输入同序的引用。
94
+ * @throws AttachmentError
95
+ */
96
+ saveImages(inputs: readonly SaveImageAttachment[]): Promise<readonly ImageAttachmentRef[]>;
97
+ /**
98
+ * 准入一条提示词:图片按 `saveImages` 整批准入、换成引用,文本与文件引用原样。没有图片时不碰存储。
99
+ * @returns 与输入同序。
100
+ * @throws AttachmentError
101
+ */
102
+ admitPromptContent(content: readonly AttachmentAdmissionPart[]): Promise<AdmittedPromptContentPart[]>;
103
+ /**
104
+ * 存一个 base64 编码的文件(`saveFile` 的另一种写法)。
105
+ * @throws AttachmentError 不是规范的 base64 时 `INVALID_FILE_BASE64`。
106
+ */
107
+ admitEncodedFile(input: EncodedFileAttachment): Promise<FileAttachmentRef>;
108
+ /**
109
+ * 存一张图片,不做整批的检查。
110
+ * @throws AttachmentError
111
+ */
112
+ saveImage(input: SaveImageAttachment): Promise<ImageAttachmentRef>;
113
+ /**
114
+ * 读出一张图片并核对:摘要、格式、尺寸与字节数都与引用一致。
115
+ * @throws AttachmentError
116
+ */
117
+ readImage(ref: ImageAttachmentRef, signal?: AbortSignal): Promise<StoredImageAttachment>;
118
+ /**
119
+ * 图片在宿主上的绝对路径,不读对象。形状有变:0.12 是同步的。
120
+ * @throws AttachmentError 引用不对时 `INVALID_ATTACHMENT_REF`。
121
+ */
122
+ imageHostPath(ref: ImageAttachmentRef): Promise<string>;
123
+ /**
124
+ * 原样存下一个文件,不限大小。
125
+ * @throws AttachmentError
126
+ */
127
+ saveFile(input: SaveFileAttachment): Promise<FileAttachmentRef>;
128
+ /**
129
+ * 分块存下一个文件,不限大小,内容不会整份留在内存里。每块最多 64 KiB 地发给宿主(大块拆开),宿主写不过来时等着。
130
+ * 中止、失败、两块之间超过 5 分钟没有新块或插件进程退出时暂存的内容删除,不留下半个附件。
131
+ * @throws AttachmentError 超时报 `ATTACHMENT_WRITE_FAILED`;中止时抛 `signal.reason`。
132
+ */
133
+ saveFileStream(input: SaveFileStreamAttachment): Promise<FileAttachmentRef>;
134
+ /**
135
+ * 分块读存下的文件,每块最多 64 KiB,一块向宿主要一次。边读边算摘要,读到结尾与引用不符时迭代以 `ATTACHMENT_CORRUPT` 结束:之前的
136
+ * 块已经交出去了,调用方要到迭代正常结束才算读到了完整的文件。
137
+ */
138
+ readFileStream(ref: FileAttachmentRef, signal?: AbortSignal): AsyncIterable<Uint8Array>;
139
+ /**
140
+ * 文件在宿主上的绝对路径(以文件名结尾),不读对象。形状有变:0.12 是同步的。
141
+ * @throws AttachmentError 引用不对时 `INVALID_ATTACHMENT_REF`。
142
+ */
143
+ fileHostPath(ref: FileAttachmentRef): Promise<string>;
144
+ /**
145
+ * 一张图片按 `target` 的请求版本:目标比原图大时保持原图,字节目标达不到时取质量阶梯里最小的。同样的目标读缓存。
146
+ * @throws AttachmentError
147
+ */
148
+ readImageRequest(ref: ImageAttachmentRef, target: ImageRequestTarget, signal?: AbortSignal): Promise<RequestImageAttachment>;
149
+ }
@@ -0,0 +1,26 @@
1
+ export const IMAGE_ADMISSION_ERROR_CODES = [
2
+ 'TOO_MANY_IMAGES', 'IMAGES_TOO_LARGE', 'UNSUPPORTED_IMAGE_TYPE', 'INVALID_IMAGE_BASE64', 'INVALID_IMAGE', 'IMAGE_TYPE_MISMATCH',
3
+ 'IMAGE_TOO_LARGE', 'IMAGE_TOO_MANY_PIXELS', 'IMAGE_DIMENSION_TOO_LARGE',
4
+ ];
5
+ export const ATTACHMENT_ERROR_CODES = [
6
+ ...IMAGE_ADMISSION_ERROR_CODES,
7
+ 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', 'ATTACHMENT_CORRUPT', 'ATTACHMENT_WRITE_FAILED', 'ATTACHMENT_NOT_FOUND',
8
+ 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', 'ATTACHMENT_FILES_UNSUPPORTED',
9
+ ];
10
+ /** 附件存储的失败(同 0.12):错误码与 0.12 原文的说明。 */
11
+ export class AttachmentError extends Error {
12
+ code;
13
+ constructor(message, code, options) {
14
+ super(message, options);
15
+ this.code = code;
16
+ this.name = 'AttachmentError';
17
+ }
18
+ }
19
+ export function isAttachmentError(error) {
20
+ return error instanceof AttachmentError;
21
+ }
22
+ /** 图片本身不合要求:调用方可以把说明交给模型,换一句替代的文字(同 0.12)。 */
23
+ export function isImageAdmissionError(error) {
24
+ return isAttachmentError(error) && IMAGE_ADMISSION_ERROR_CODES.includes(error.code);
25
+ }
26
+ //# sourceMappingURL=attachments.js.map
@@ -0,0 +1,99 @@
1
+ /**
2
+ * 平台服务(0.12 的 `ctx.userQuestions`、`ctx.web`、`ctx.skills`、`ctx.commands`):名字与参数照 0.12,载荷由扩展点表生成。
3
+ *
4
+ * 与 0.12 不同的地方:
5
+ * - 跨进程,读取都是异步的;0.12 收 agent 句柄的参数这里收会话 id;
6
+ * - 校验错误(名字、说明的写法)当场抛,重名由宿主判定:激活期间被拒时插件加载失败,之后的注册从 `handle.ready` 报;
7
+ * - 不开放提供方(`ctx.skills.registerProvider`、`ctx.web.register*Provider`)。
8
+ * @module
9
+ */
10
+ import type { AskUserQuestionAnswer, AskUserQuestionRequestEvent, CommandDescriptor, CommandExecution, CommandInputDescriptor, CommandResult, SkillCatalogSnapshot, SkillDefinition, SkillRegistration, SkillSummary, WebFetchRequest, WebFetchResult, WebSearchRequest, WebSearchResult } from './generated.ts';
11
+ import type { AgentHandle } from './index.ts';
12
+ /** 一项注册的撤销函数:`ready` 在宿主收下时兑现,重名等被拒时拒绝。 */
13
+ export interface HostRegistrationHandle {
14
+ (): void;
15
+ readonly ready: Promise<void>;
16
+ }
17
+ /** 提问的失败(同 0.12):`EMPTY_QUESTIONS`、`BAD_INTENT`、`BAD_ANSWER`、`CALLER_NOT_LIVE`、`DELEGATED_CALLER`、`ASK_CANCELLED`、`ASK_ABORTED`、`NO_PROVIDER`。 */
18
+ export declare class UserQuestionError extends Error {
19
+ readonly code: string;
20
+ constructor(message: string, code: string, options?: ErrorOptions);
21
+ }
22
+ export interface AskUserQuestionRequest extends AskUserQuestionRequestEvent {
23
+ /** 中止时提问撤回,`ask` 以 `ASK_ABORTED` 拒绝。 */
24
+ readonly signal?: AbortSignal;
25
+ }
26
+ export interface UserQuestionsService {
27
+ /**
28
+ * 向用户提问:先过 `user-questions/request`,最后到界面的提问卡片。不在进行中的一轮里也可以问。
29
+ * `wait.callId` 不给时宿主生成一个,监听者据此经 `answer` 回答。不带 `sessionId` 时没有卡片,没有插件作答就是 `NO_PROVIDER`。
30
+ */
31
+ ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer>;
32
+ /** 回答一个正在等待的提问,界面的卡片撤回。这个提问不在等了时为 false;没有逐个回答每个问题时抛 `BAD_ANSWER`。 */
33
+ answer(sessionId: string, callId: string, answer: AskUserQuestionAnswer): Promise<boolean>;
34
+ }
35
+ /** 联网的失败(同 0.12):错误码是开放的字符串,以 `WEB_` 开头,如 `WEB_PROVIDER_CREDENTIAL_MISSING`、`WEB_FETCH_TIMEOUT`。 */
36
+ export declare class WebError extends Error {
37
+ readonly code: string;
38
+ constructor(message: string, code: string, options?: ErrorOptions);
39
+ }
40
+ export interface WebService {
41
+ /** 用当前登录的 FtAi 账号搜一次(消耗用户的额度,与 `web_search` 工具相同)。没有登录时抛 `WEB_PROVIDER_CREDENTIAL_MISSING`。 */
42
+ search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult>;
43
+ /** 抓一个地址,地址校验与上限同 `web_fetch` 工具,只是不排版。非 2xx 也是结果,不抛错。 */
44
+ fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult>;
45
+ }
46
+ export interface SkillLookupOptions {
47
+ /** 工作目录,项目里的 Skill 按它找;不给时没有项目里的。 */
48
+ readonly cwd?: string | undefined;
49
+ readonly signal?: AbortSignal | undefined;
50
+ }
51
+ export interface SkillsService {
52
+ /** 生效的 Skill(开着、没被同名的盖住),按名字排好,与模型看到的同一份,不按调用策略过滤。 */
53
+ list(options?: SkillLookupOptions): Promise<SkillSummary[]>;
54
+ /** 同 `list`,`complete` 说明这次是不是全部读到了。 */
55
+ snapshot(options?: SkillLookupOptions): Promise<SkillCatalogSnapshot>;
56
+ /** 加载生效的那个同名 Skill;没有时为 undefined。 */
57
+ get(name: string, options?: SkillLookupOptions): Promise<SkillDefinition | undefined>;
58
+ /**
59
+ * 注册一个 Skill:进模型的 Skill 目录与用户的开关,优先级在项目的之后、用户的之前,随这项注册撤销。
60
+ * 形状有变:只能全局注册,在 `agent.ctx` 上调用抛错;插件之间重名是错误(0.12 是后注册的被忽略)。
61
+ */
62
+ register(skill: SkillRegistration): HostRegistrationHandle;
63
+ }
64
+ /** 处理函数收到的一次调用(同 0.12)。 */
65
+ export interface CommandInvocation {
66
+ /** 这次调用记在 `command/run`、`command/done` 上的编号。 */
67
+ readonly commandId: string;
68
+ /** 收到命令的 agent。 */
69
+ readonly agent: AgentHandle;
70
+ /** 命令名后面的原文,含分隔的空白。 */
71
+ readonly rawInput: string;
72
+ /** 总是空的:命令不收附件。 */
73
+ readonly attachments: readonly [];
74
+ /** 调用方不再等时触发。 */
75
+ readonly signal: AbortSignal;
76
+ }
77
+ /** 一条命令(0.12 的 `CommandDefinition`)。形状有变:`input` 没有 `attachments`,写了当场抛错。 */
78
+ /** 就是字符串:0.12 的品牌类型。 */
79
+ export type CommandDefinitionId = string;
80
+ export interface CommandDefinition {
81
+ readonly definitionId?: string;
82
+ /** 小写的命令名,不带斜杠:`/^[a-z][a-z0-9_-]*$/`。 */
83
+ readonly name: string;
84
+ readonly description: string;
85
+ readonly input?: CommandInputDescriptor;
86
+ /** `command/run` 记不记用户的输入,默认记。 */
87
+ readonly recordInput?: boolean;
88
+ handler(invocation: CommandInvocation): CommandResult | Promise<CommandResult>;
89
+ }
90
+ export interface CommandsService {
91
+ /** 注册一条命令,随这项注册撤销。在 `agent.ctx` 上调用时只对这个 agent 生效,盖住同名的全局命令。同一层里重名是错误。 */
92
+ register(definition: CommandDefinition): HostRegistrationHandle;
93
+ /** 形状有变:0.12 收 agent,同步。这个会话看得到的命令,按名字排好。 */
94
+ list(sessionId: string): Promise<CommandDescriptor[]>;
95
+ /** 形状有变:0.12 收 agent,同步,给完整定义。这里只有描述,处理函数过不了进程。 */
96
+ find(sessionId: string, name: string): Promise<CommandDescriptor | undefined>;
97
+ /** 形状有变:0.12 收 agent 与附件。解析一行斜杠命令并执行,不交给模型;不是命令或没有这条命令时为 undefined。处理函数抛错时拒绝(`COMMAND_FAILED`)。 */
98
+ execute(sessionId: string, line: string, signal?: AbortSignal): Promise<CommandExecution | undefined>;
99
+ }
@@ -0,0 +1,21 @@
1
+ // ---- 向用户提问 ----
2
+ /** 提问的失败(同 0.12):`EMPTY_QUESTIONS`、`BAD_INTENT`、`BAD_ANSWER`、`CALLER_NOT_LIVE`、`DELEGATED_CALLER`、`ASK_CANCELLED`、`ASK_ABORTED`、`NO_PROVIDER`。 */
3
+ export class UserQuestionError extends Error {
4
+ code;
5
+ constructor(message, code, options) {
6
+ super(message, options);
7
+ this.code = code;
8
+ this.name = 'UserQuestionError';
9
+ }
10
+ }
11
+ // ---- 联网 ----
12
+ /** 联网的失败(同 0.12):错误码是开放的字符串,以 `WEB_` 开头,如 `WEB_PROVIDER_CREDENTIAL_MISSING`、`WEB_FETCH_TIMEOUT`。 */
13
+ export class WebError extends Error {
14
+ code;
15
+ constructor(message, code, options) {
16
+ super(message, options);
17
+ this.code = code;
18
+ this.name = 'WebError';
19
+ }
20
+ }
21
+ //# sourceMappingURL=capabilities.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * 外部应用的入口(`ftai app`)给插件的命令行、退出与启动信号(0.12 的 `@deepseek-ai/dsh-cmdline`)。入口只解析自己的参数,其余原样交给插件,
3
+ * 任意个插件都可以读同一份。应用自己启动时没有命令行:参数是空的,`ctx.appExit` 只记日志,不关用户的应用。
4
+ * @module
5
+ */
6
+ import type { Context } from 'cordis';
7
+ /** 这次启动交给插件的参数。 */
8
+ export interface CmdlineArgs {
9
+ /** 按原来的顺序;没有时是空列表。 */
10
+ get(): readonly string[];
11
+ }
12
+ /** 请求进程退出:插件树撤销之后按这个退出码结束,只有第一次算数。 */
13
+ export type AppExit = (code: number) => void;
14
+ /** 启动成功的信号。 */
15
+ export interface AppReady {
16
+ /**
17
+ * 启动成功之后跑一次(已经成功时马上跑),返回的函数取消还没跑的。经 `ftai app` 起时要全部插件都加载起来,有失败或启动中途调了 `ctx.appExit` 就不跑;
18
+ * 在用户的应用里一个第三方插件失败不影响别的插件,照样跑。
19
+ */
20
+ onReady(listener: () => void): () => void;
21
+ }
22
+ declare module 'cordis' {
23
+ interface Context {
24
+ readonly cmdlineArgs: CmdlineArgs;
25
+ readonly appExit: AppExit;
26
+ readonly appReady: AppReady;
27
+ }
28
+ }
29
+ /** commander 的 `Command` 里用到的部分:SDK 不依赖 commander,插件带自己的一份。 */
30
+ export interface CmdlineProgram {
31
+ name(): string;
32
+ readonly commands: readonly CmdlineProgram[];
33
+ exitOverride(): unknown;
34
+ configureOutput(output: {
35
+ writeOut(text: string): void;
36
+ writeErr(text: string): void;
37
+ }): unknown;
38
+ parse(args: readonly string[], options: {
39
+ from: 'user';
40
+ }): unknown;
41
+ }
42
+ /**
43
+ * 用插件自己的 commander program 解析 `ctx.cmdlineArgs`:解析成功时跑它的 action(插件在那里发布自己的服务),`--help`、`--version` 与解析错误
44
+ * 由 commander 写出文本后请求 `ctx.appExit`。
45
+ * @throws 没有命令声明 action。
46
+ */
47
+ export declare function parseCmdline(ctx: Context, program: CmdlineProgram): void;
48
+ /**
49
+ * 启动成功之后 stdin 结束就以 0 退出,给靠 stdio 通信的应用绑生命周期。不读 stdin,也不让它开始流动:输入归应用自己的传输层,它接手之前到的字节不会丢。
50
+ * 启动失败优先于同时到来的 stdin 结束;随调用它的插件撤销。
51
+ */
52
+ export declare function exitOnStdinEnd(ctx: Context, label: string): void;
package/lib/cmdline.js ADDED
@@ -0,0 +1,68 @@
1
+ /** 有没有哪个命令声明了 action:没有时解析成功也什么都不发布,依赖它的插件就只能一直等,所以当作写错了报出来。 */
2
+ function hasAction(command) {
3
+ if (typeof command._actionHandler === 'function')
4
+ return true;
5
+ return command.commands.some(hasAction);
6
+ }
7
+ /** 子命令注册时才复制这些设置:只设根命令的话,已经注册的子命令报错时会直接 `process.exit`,绕过 `ctx.appExit`。 */
8
+ function configureExitAndOutput(command) {
9
+ command.exitOverride();
10
+ command.configureOutput({
11
+ writeOut: (text) => { process.stdout.write(text); },
12
+ writeErr: (text) => { process.stderr.write(text); },
13
+ });
14
+ for (const child of command.commands)
15
+ configureExitAndOutput(child);
16
+ }
17
+ /** 按结构判断 commander 的控制流错误:第三方插件带自己的 commander,`instanceof` 认不出来。 */
18
+ function isCommanderError(error) {
19
+ if (typeof error !== 'object' || error === null)
20
+ return false;
21
+ const candidate = error;
22
+ return typeof candidate.code === 'string' && candidate.code.startsWith('commander.') && typeof candidate.exitCode === 'number';
23
+ }
24
+ /**
25
+ * 用插件自己的 commander program 解析 `ctx.cmdlineArgs`:解析成功时跑它的 action(插件在那里发布自己的服务),`--help`、`--version` 与解析错误
26
+ * 由 commander 写出文本后请求 `ctx.appExit`。
27
+ * @throws 没有命令声明 action。
28
+ */
29
+ export function parseCmdline(ctx, program) {
30
+ if (!hasAction(program))
31
+ throw new Error(`${program.name()}: no command in the program declares an action`);
32
+ configureExitAndOutput(program);
33
+ try {
34
+ program.parse(ctx.get('cmdlineArgs').get(), { from: 'user' });
35
+ }
36
+ catch (error) {
37
+ if (!isCommanderError(error))
38
+ throw error;
39
+ ctx.get('appExit')(error.exitCode);
40
+ }
41
+ }
42
+ /**
43
+ * 启动成功之后 stdin 结束就以 0 退出,给靠 stdio 通信的应用绑生命周期。不读 stdin,也不让它开始流动:输入归应用自己的传输层,它接手之前到的字节不会丢。
44
+ * 启动失败优先于同时到来的 stdin 结束;随调用它的插件撤销。
45
+ */
46
+ export function exitOnStdinEnd(ctx, label) {
47
+ const exit = ctx.get('appExit');
48
+ const ready = ctx.get('appReady');
49
+ const stdin = process.stdin;
50
+ let active = true;
51
+ let ended = false;
52
+ let cancelReady = () => { };
53
+ const onEnd = () => {
54
+ if (!active || ended)
55
+ return;
56
+ ended = true;
57
+ cancelReady = ready.onReady(() => { exit(0); });
58
+ };
59
+ ctx.effect(() => () => {
60
+ active = false;
61
+ cancelReady();
62
+ stdin.off('end', onEnd);
63
+ }, label);
64
+ stdin.once('end', onEnd);
65
+ if (stdin.readableEnded)
66
+ queueMicrotask(onEnd);
67
+ }
68
+ //# sourceMappingURL=cmdline.js.map
@@ -0,0 +1,92 @@
1
+ /**
2
+ * 凭据(0.12 的 `ctx.credentials` 与 `@deepseek-ai/dsh-credentials`):配置里只写凭据的引用(环境变量名)或记录的地址
3
+ * (`<scope>/<id>`),值由宿主保管。方法名、参数、结果与两个事件同 0.12(本来就是异步的),`credentialRef`、`credentialKey`
4
+ * 等函数同名同形。
5
+ *
6
+ * 与 0.12 不同:按插件隔离。
7
+ * - 记录与 `set`、`unset` 只在这个插件自己的空间里:照 0.12 写的地址存在这个插件名下,别的插件与 FtAi 自己的记录看不到;
8
+ * 0.12 写下的条目不迁进来。
9
+ * - `resolve`、`describe` 先查自己的空间,再查插件进程的启动环境;别人保管的引用(FtAi 里配的提供方密钥、别的插件存的、0.12
10
+ * 留下的)要用户在界面上允许才读得到,没允许时按没配置返回、不等待,界面提示用户;一方插件不要允许。
11
+ * - `credentials/*-updated` 只发给读得到这一项的插件,只有本宿主里的写入(同 0.12 不观察启动环境)。
12
+ * - 隔离只在接口这一层:插件进程里的插件之间没有隔离,挡不住直接读进程内存或存储的插件。
13
+ * @module
14
+ */
15
+ import type { CredentialInfo, CredentialRecordEntry, CredentialRecordInfo, ResolvedCredential } from './generated.ts';
16
+ /** 一项凭据的引用:POSIX 风格的环境变量名(如 `DEEPSEEK_API_KEY`)。0.12 的品牌类型,这里就是字符串。 */
17
+ export type CredentialRef = string;
18
+ /**
19
+ * 一条记录的地址 `<scope>/<id>`:`scope` 是写它的插件的名字,`id` 是插件自己的寻址单位。两段都只有小写字母、数字与 `-`,
20
+ * 与引用的文法不相交。0.12 的品牌类型,这里就是字符串。
21
+ */
22
+ export type CredentialKey = string;
23
+ /** API key、提供方的环境变量,或两者都有;两者都没有表示拥有者确认这条路由靠环境自带的鉴权。 */
24
+ export interface ApiKeyRecord {
25
+ readonly kind: 'api-key';
26
+ readonly key?: string;
27
+ readonly env?: Readonly<Record<string, string>>;
28
+ }
29
+ /** 一次授权的产物,由拥有者按自己的格式写入;宿主不解读它,只要求能往返 JSON。 */
30
+ export interface GrantRecord {
31
+ readonly kind: 'grant';
32
+ readonly payload: unknown;
33
+ }
34
+ export type CredentialRecord = ApiKeyRecord | GrantRecord;
35
+ /** 同 0.12:校验后返回引用,不合文法时抛 `TypeError`。 */
36
+ export declare function credentialRef(value: string): CredentialRef;
37
+ /** 同 0.12:这个字符串能不能作为引用名。 */
38
+ export declare function isCredentialRefName(value: string): boolean;
39
+ /** 同 0.12:这个字符串能不能作为记录地址的一段。 */
40
+ export declare function isCredentialKeySegment(value: string): boolean;
41
+ /** 同 0.12:由两段拼出记录的地址,有一段不合文法时抛 `TypeError`。 */
42
+ export declare function credentialKey(scope: string, id: string): CredentialKey;
43
+ /** 同 0.12:解析存下的 `<scope>/<id>`,不是恰好两段合法的段时抛 `TypeError`。 */
44
+ export declare function parseCredentialKey(value: string): CredentialKey;
45
+ /** 同 0.12:地址的 scope 段。 */
46
+ export declare function credentialKeyScope(key: CredentialKey): string;
47
+ /** 同 0.12:地址的 id 段。 */
48
+ export declare function credentialKeyId(key: CredentialKey): string;
49
+ /**
50
+ * `ctx.credentials` 的形状(0.12 的 `CredentialProvider`)。形状有变:这里只是类型,插件不能提供凭据服务,FtAi 的凭据由宿主保管。
51
+ * 宿主不可用(如钥匙串不可用)时服务撤销,依赖它的插件随之停用。
52
+ */
53
+ export interface CredentialProvider {
54
+ /**
55
+ * 解析一个引用;没有配置时为 undefined。每次操作现解析,不跨操作缓存。来源是 `plugin`(自己的空间,或允许读的别的插件的空间)、
56
+ * `env`(插件进程的启动环境)、`keyring` 或 `file`(FtAi 的存储)。别人保管、还没允许的按没有配置。
57
+ */
58
+ resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>;
59
+ /** 描述一个引用,不含值;分层同 `resolve`。`writable` 总是 true:自己的空间排在启动环境之前。 */
60
+ describe(ref: CredentialRef): Promise<CredentialInfo>;
61
+ /** 存进自己的空间;空值拒绝(用 `unset`)。不会被启动环境挡住:自己的空间排在前面。 */
62
+ set(ref: CredentialRef, value: string): Promise<void>;
63
+ /** 从自己的空间删掉;本来就没有时什么也不做。 */
64
+ unset(ref: CredentialRef): Promise<void>;
65
+ /** 读自己的一条记录;没有时为 undefined。 */
66
+ readRecord(key: CredentialKey): Promise<CredentialRecord | undefined>;
67
+ describeRecord(key: CredentialKey): Promise<CredentialRecordInfo>;
68
+ /** 自己的全部记录,按地址排好。 */
69
+ listRecords(): Promise<readonly CredentialRecordEntry[]>;
70
+ /**
71
+ * 串行化的读—改—写,写记录的唯一途径:`mutate` 拿到锁内读到的记录,返回替换它的记录,返回 undefined 表示不改。形状有变:`mutate`
72
+ * 跑在插件进程里,期间宿主持着存储的锁,30 秒内要给出结论,否则这次改动失败(`credentials/modify-timeout`),什么也不写;
73
+ * `mutate` 抛错时同样不写,错误原样抛给调用方。
74
+ */
75
+ modifyRecord(key: CredentialKey, mutate: (current: CredentialRecord | undefined) => Promise<CredentialRecord | undefined>): Promise<CredentialRecord | undefined>;
76
+ /** 删掉自己的一条记录;本来就没有时什么也不做。 */
77
+ deleteRecord(key: CredentialKey): Promise<void>;
78
+ }
79
+ declare module 'cordis' {
80
+ interface Context {
81
+ credentials: CredentialProvider;
82
+ }
83
+ interface Events {
84
+ /**
85
+ * 这个插件读得到的一个引用变了:自己空间里的 `set`、`unset`,FtAi 或别的插件存的、它读得到的那一项的写入,用户允许或撤销它读。
86
+ * 不发给读不到的插件;启动环境的变化观察不到。监听者抛错只记日志。
87
+ */
88
+ 'credentials/reference-updated'(ref: CredentialRef): void;
89
+ /** 这个插件自己的一条记录写下或删掉了(`modifyRecord`、`deleteRecord`)。只发给它自己。 */
90
+ 'credentials/record-updated'(key: CredentialKey): void;
91
+ }
92
+ }
@@ -0,0 +1,41 @@
1
+ const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
+ const KEY_SEGMENT_PATTERN = /^[a-z][a-z0-9-]*$/;
3
+ /** 同 0.12:校验后返回引用,不合文法时抛 `TypeError`。 */
4
+ export function credentialRef(value) {
5
+ if (!isCredentialRefName(value))
6
+ throw new TypeError(`credential ref "${value}" must match ${String(REF_PATTERN)}`);
7
+ return value;
8
+ }
9
+ /** 同 0.12:这个字符串能不能作为引用名。 */
10
+ export function isCredentialRefName(value) {
11
+ return REF_PATTERN.test(value);
12
+ }
13
+ /** 同 0.12:这个字符串能不能作为记录地址的一段。 */
14
+ export function isCredentialKeySegment(value) {
15
+ return KEY_SEGMENT_PATTERN.test(value);
16
+ }
17
+ /** 同 0.12:由两段拼出记录的地址,有一段不合文法时抛 `TypeError`。 */
18
+ export function credentialKey(scope, id) {
19
+ for (const segment of [scope, id]) {
20
+ if (!KEY_SEGMENT_PATTERN.test(segment))
21
+ throw new TypeError(`credential key segment "${segment}" must match ${String(KEY_SEGMENT_PATTERN)}`);
22
+ }
23
+ return `${scope}/${id}`;
24
+ }
25
+ /** 同 0.12:解析存下的 `<scope>/<id>`,不是恰好两段合法的段时抛 `TypeError`。 */
26
+ export function parseCredentialKey(value) {
27
+ const segments = value.split('/');
28
+ const [scope, id] = segments;
29
+ if (segments.length !== 2 || scope === undefined || id === undefined)
30
+ throw new TypeError(`credential key "${value}" must be "<scope>/<id>"`);
31
+ return credentialKey(scope, id);
32
+ }
33
+ /** 同 0.12:地址的 scope 段。 */
34
+ export function credentialKeyScope(key) {
35
+ return key.slice(0, key.indexOf('/'));
36
+ }
37
+ /** 同 0.12:地址的 id 段。 */
38
+ export function credentialKeyId(key) {
39
+ return key.slice(key.indexOf('/') + 1);
40
+ }
41
+ //# sourceMappingURL=credentials.js.map