@capybara-hq/plugin-sdk 0.1.0-rc.3 → 0.1.0-rc.31

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 (127) hide show
  1. package/agent-docs/agent-templates.md +15 -3
  2. package/agent-docs/concepts.md +5 -0
  3. package/agent-docs/connector-templates.md +2 -1
  4. package/agent-docs/extension-points/channel.md +1 -1
  5. package/agent-docs/extension-points/config-source.md +1 -1
  6. package/agent-docs/extension-points/connector.md +1 -1
  7. package/agent-docs/extension-points/context.md +15 -0
  8. package/agent-docs/extension-points/counter.md +1 -1
  9. package/agent-docs/extension-points/directory.md +1 -1
  10. package/agent-docs/extension-points/file-preview.md +1 -1
  11. package/agent-docs/extension-points/identity-source.md +1 -1
  12. package/agent-docs/extension-points/model-provider.md +4 -2
  13. package/agent-docs/extension-points/object-store.md +3 -1
  14. package/agent-docs/extension-points/sandbox.md +3 -3
  15. package/agent-docs/extension-points/secret-store.md +1 -1
  16. package/agent-docs/extension-points/web-fetch.md +1 -1
  17. package/agent-docs/extension-points/web-search.md +1 -1
  18. package/agent-docs/extensions.md +29 -4
  19. package/agent-docs/plugin-format.md +43 -3
  20. package/agent-docs/setup.md +46 -0
  21. package/agent-docs/skills.md +1 -1
  22. package/agent-docs/tool-naming.md +1 -1
  23. package/dist/agent-template.d.ts +15 -6
  24. package/dist/agent-template.js +32 -13
  25. package/dist/bootstrap.d.ts +15 -1
  26. package/dist/bootstrap.js +17 -1
  27. package/dist/cards.d.ts +56 -13
  28. package/dist/cards.js +90 -20
  29. package/dist/channel.d.ts +111 -48
  30. package/dist/channel.js +10 -5
  31. package/dist/client-css.d.ts +36 -0
  32. package/dist/client-css.js +326 -0
  33. package/dist/client-section.d.ts +35 -0
  34. package/dist/client-section.js +133 -0
  35. package/dist/config-ui.d.ts +22 -0
  36. package/dist/config-ui.js +64 -4
  37. package/dist/connector-auth.d.ts +7 -2
  38. package/dist/connector-auth.js +29 -8
  39. package/dist/connector.d.ts +74 -32
  40. package/dist/context.d.ts +40 -0
  41. package/dist/context.js +2 -0
  42. package/dist/ctx.d.ts +135 -26
  43. package/dist/define-extension.d.ts +26 -12
  44. package/dist/define-extension.js +11 -4
  45. package/dist/device-protocol-v3.d.ts +117 -0
  46. package/dist/device-protocol-v3.js +409 -0
  47. package/dist/device-protocol.d.ts +330 -0
  48. package/dist/device-protocol.js +567 -0
  49. package/dist/extension-point.d.ts +2 -0
  50. package/dist/extension-point.js +5 -2
  51. package/dist/file-preview.d.ts +1 -1
  52. package/dist/git-hosts.d.ts +44 -0
  53. package/dist/git-hosts.js +81 -0
  54. package/dist/hooks.d.ts +111 -21
  55. package/dist/hooks.js +5 -0
  56. package/dist/http-access.d.ts +52 -0
  57. package/dist/http-access.js +12 -0
  58. package/dist/identity.d.ts +22 -9
  59. package/dist/index.d.ts +23 -1
  60. package/dist/index.js +24 -1
  61. package/dist/marketplace.d.ts +26 -0
  62. package/dist/marketplace.js +43 -1
  63. package/dist/model-params.d.ts +41 -22
  64. package/dist/model-params.js +28 -15
  65. package/dist/model.d.ts +180 -71
  66. package/dist/model.js +71 -19
  67. package/dist/net.d.ts +52 -0
  68. package/dist/net.js +34 -0
  69. package/dist/permissions.d.ts +42 -20
  70. package/dist/permissions.js +97 -40
  71. package/dist/plugin-manifest.d.ts +45 -5
  72. package/dist/plugin-manifest.js +169 -6
  73. package/dist/plugin-package.d.ts +82 -38
  74. package/dist/plugin-package.js +61 -29
  75. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  76. package/dist/sandbox-linux-runtime-source.js +1886 -0
  77. package/dist/sandbox-native-runtime-source.d.ts +8 -0
  78. package/dist/sandbox-native-runtime-source.js +325 -0
  79. package/dist/sandbox-operation.d.ts +248 -0
  80. package/dist/sandbox-operation.js +245 -0
  81. package/dist/sandbox-runtime-source.d.ts +19 -0
  82. package/dist/sandbox-runtime-source.js +28 -0
  83. package/dist/sandbox-write-denies.d.ts +60 -0
  84. package/dist/sandbox-write-denies.js +630 -0
  85. package/dist/sandbox.d.ts +201 -16
  86. package/dist/sandbox.js +89 -14
  87. package/dist/secret.d.ts +4 -1
  88. package/dist/secret.js +4 -1
  89. package/dist/setup-check.d.ts +115 -0
  90. package/dist/setup-check.js +142 -0
  91. package/dist/setup-guide-parse.d.ts +121 -0
  92. package/dist/setup-guide-parse.js +350 -0
  93. package/dist/setup-guide-render.d.ts +45 -0
  94. package/dist/setup-guide-render.js +351 -0
  95. package/dist/setup-guide.d.ts +94 -0
  96. package/dist/setup-guide.js +336 -0
  97. package/dist/skill-invocation.d.ts +4 -3
  98. package/dist/skill-invocation.js +5 -4
  99. package/dist/skill.d.ts +34 -21
  100. package/dist/skill.js +48 -31
  101. package/dist/storage.d.ts +52 -25
  102. package/dist/theme-assets.d.ts +39 -0
  103. package/dist/theme-assets.js +449 -0
  104. package/dist/theme-readability.d.ts +37 -0
  105. package/dist/theme-readability.js +145 -0
  106. package/dist/theme-tokens.generated.d.ts +279 -0
  107. package/dist/theme-tokens.generated.js +174 -0
  108. package/dist/theme.d.ts +152 -0
  109. package/dist/theme.js +392 -0
  110. package/dist/tool.d.ts +69 -26
  111. package/dist/tool.js +29 -9
  112. package/dist/ui-parts.d.ts +23 -0
  113. package/dist/ui-parts.js +337 -0
  114. package/dist/ui-resolve.d.ts +35 -0
  115. package/dist/ui-resolve.js +42 -0
  116. package/dist/ui-slots.d.ts +53 -0
  117. package/dist/ui-slots.js +238 -0
  118. package/dist/ui.d.ts +191 -79
  119. package/dist/ui.js +101 -27
  120. package/dist/url.d.ts +4 -1
  121. package/dist/url.js +4 -1
  122. package/package.json +7 -1
  123. package/schemas/bootstrap.v1.schema.json +6 -0
  124. package/schemas/connector-template.v1.schema.json +35 -0
  125. package/schemas/marketplace.v1.schema.json +14 -0
  126. package/schemas/plugin.v1.schema.json +115 -3
  127. package/schemas/theme.v1.schema.json +225 -0
package/dist/model.d.ts CHANGED
@@ -1,12 +1,36 @@
1
1
  /**
2
- * 与供应商无关的模型契约;原生协议留在各供应商插件内部。
3
- * 当前契约为 `model-provider@2`(`ModelProvider` / `ModelInfo` / `ModelRequest`,参数由插件按模型声明,
4
- * 见 `model-params.ts`);旧契约 `model-provider@1`(`ModelProviderV1` 等)由内核经适配层继续支持。
2
+ * The vendor-neutral model contract; native protocols stay inside each vendor plugin.
3
+ * The contract is `model-provider@2` (`ModelProvider` / `ModelInfo` / `ModelRequest`, parameters
4
+ * declared by the plugin per model, see `model-params.ts`).
5
5
  */
6
- import type { Effort, ModelParameter, ParamValue } from "./model-params.js";
6
+ import type { ModelCallPurpose } from "./hooks.js";
7
+ import type { ModelParameter, ParamValue } from "./model-params.js";
8
+ import type { LocalizedName } from "./plugin-package.js";
9
+ /** What a model does. Absent on a `ModelInfo` means `chat`. */
10
+ export type ModelKind = "chat" | "embedding" | "rerank" | "image_generation" | "video_generation" | "speech_to_text" | "text_to_speech";
11
+ /** Embedding facts of a model whose `kind` is `embedding`. */
12
+ export interface ModelEmbeddingInfo {
13
+ /** The output dimensions the model can produce (a single entry when not adjustable). */
14
+ dimensions: number[];
15
+ defaultDimensions: number;
16
+ /** Most tokens one input may hold. */
17
+ maxInputTokens: number;
18
+ /** Most inputs one `embed` call may carry. */
19
+ maxBatch: number;
20
+ }
7
21
  export interface ModelInfo {
8
22
  id: string;
9
23
  displayName: string;
24
+ /** Defaults to `chat`. Chat-only fields below stay required for every kind. */
25
+ kind?: ModelKind;
26
+ /** Who made the model (display only). */
27
+ publisher?: string;
28
+ /** Display only. */
29
+ description?: LocalizedName | string;
30
+ /** ISO date after which the model is retired (display only). */
31
+ retiresAt?: string;
32
+ /** Set when `kind` is `embedding`. */
33
+ embedding?: ModelEmbeddingInfo;
10
34
  contextWindow: number;
11
35
  maxOutputTokens: number;
12
36
  capabilities: {
@@ -16,43 +40,46 @@ export interface ModelInfo {
16
40
  caching: boolean;
17
41
  midConversationSystem: boolean;
18
42
  /**
19
- * 是否接受 `document` 块(缺省为 false)。图片看 `vision`。模型不支持时内核把媒体块换成英文文字占位
20
- * (如 `[Attached image "<name>" — this model cannot view images.]`;`text/*` 文档改为内联截断后的文本),
21
- * 绝不把字节发给它。
43
+ * Whether `document` blocks are accepted (default false). Images are governed by `vision`. When
44
+ * the model does not support them the kernel replaces media blocks with English text
45
+ * placeholders
46
+ * (e.g. `[Attached image "<name>" — this model cannot view images.]`; `text/*` documents are
47
+ * inlined as truncated text instead),
48
+ * and never sends the bytes to it.
22
49
  */
23
50
  documents?: boolean;
24
- /**
25
- * @deprecated `model-provider@1` 用:是否支持 `ModelRequestV1.effort`。`@2` 插件不填,改在
26
- * `parameters` 中声明 `effort` 旋钮;内核的 `@1` 适配层据此推导 `parameters`。
27
- */
28
- effort?: boolean;
29
51
  };
30
- /** 流空闲看门狗阈值;推理类模型应更长。未给时内核用配置默认值。 */
52
+ /**
53
+ * Stream idle watchdog threshold; reasoning models should use a longer one. When unset the kernel
54
+ * uses the config default.
55
+ */
31
56
  streamIdleTimeoutMs?: number;
32
- /** 该模型支持的参数(`@2` 必填,可为空数组;须通过 `assertValidDeclarations`)。 */
57
+ /**
58
+ * The parameters this model supports (may be an empty array; must pass
59
+ * `assertValidDeclarations`). Effort is the standard `effort` knob declared here.
60
+ */
33
61
  parameters: ModelParameter[];
34
62
  }
35
- /** `model-provider@1` 的模型信息:没有 `parameters`,effort 支持由 `capabilities.effort` 表示。 */
36
- export type ModelInfoV1 = Omit<ModelInfo, "parameters" | "capabilities"> & {
37
- capabilities: Omit<ModelInfo["capabilities"], "effort"> & {
38
- effort: boolean;
39
- };
40
- };
41
- /** 供应商私有数据:只回放给同一供应商(如 Anthropic 思考块签名、OpenAI 加密推理项)。 */
63
+ /**
64
+ * Vendor-private data: replayed only to the same vendor (e.g. Anthropic thinking block signatures,
65
+ * OpenAI encrypted reasoning items).
66
+ */
42
67
  export interface ProviderOpaque {
43
68
  provider: string;
44
69
  model: string;
45
70
  data: unknown;
46
71
  }
47
- /** 图片块接受的类型。 */
72
+ /** Types accepted by image blocks. */
48
73
  export declare const IMAGE_MEDIA_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp"];
49
- /** 文档块接受的类型。 */
74
+ /** Types accepted by document blocks. */
50
75
  export declare const DOCUMENT_MEDIA_TYPES: readonly ["application/pdf", "text/plain", "text/markdown", "text/csv"];
51
76
  export type ImageMediaType = (typeof IMAGE_MEDIA_TYPES)[number];
52
77
  export type DocumentMediaType = (typeof DOCUMENT_MEDIA_TYPES)[number];
53
78
  /**
54
- * 媒体内容的来源:`base64` 是字节本身,`ref` 是内核附件的引用。
55
- * 事件日志里只存 `ref`(字节不进日志);内核构建请求时把 `ref` 解析成 `base64`,插件只会收到 `base64`。
79
+ * The source of media content: `base64` is the bytes themselves, `ref` is a reference to a kernel
80
+ * attachment.
81
+ * The event log stores only `ref` (bytes never enter the log); when building a request the kernel
82
+ * resolves `ref` into `base64`, so plugins only ever receive `base64`.
56
83
  */
57
84
  export type MediaSource = {
58
85
  kind: "base64";
@@ -61,13 +88,19 @@ export type MediaSource = {
61
88
  kind: "ref";
62
89
  attachmentId: string;
63
90
  };
64
- /** 单个媒体块解码后的字节上限(按主流供应商的较小值取)。 */
91
+ /**
92
+ * Upper bound on the decoded bytes of a single media block (the smaller value among mainstream
93
+ * vendors).
94
+ */
65
95
  export declare const MEDIA_LIMITS: {
66
96
  readonly imageBytes: 5242880;
67
97
  readonly documentBytes: 33554432;
68
98
  };
69
99
  export type ContentBlock =
70
- /** text 的 opaque:供应商需要随文本回放的私有数据(如 OpenAI message 输出项的 id)。 */
100
+ /**
101
+ * Opaque for text: vendor-private data that must be replayed with the text (e.g. the id of an
102
+ * OpenAI message output item).
103
+ */
71
104
  {
72
105
  type: "text";
73
106
  text: string;
@@ -89,39 +122,63 @@ export type ContentBlock =
89
122
  isError: boolean;
90
123
  }
91
124
  /**
92
- * 图片(只出现在 user 消息里)。模型不支持 `vision` 时内核换成文字占位,插件不用把关;
93
- * 不认识此块的旧插件会跳过它。
125
+ * An image (only in user messages). When the model has no `vision` the kernel sends an English
126
+ * placeholder instead; a plugin need not check. An older plugin that does not know this block
127
+ * skips it. `size` is display metadata (the UI chip, the reference line) and is never sent.
94
128
  */
95
129
  | {
96
130
  type: "image";
97
131
  mediaType: ImageMediaType;
98
132
  source: MediaSource;
99
133
  name?: string;
134
+ size?: number;
100
135
  }
101
- /** 文档(只出现在 user 消息里),由 `capabilities.documents` 把关,规则同 image。 */
136
+ /** A document (only in user messages), gated by `capabilities.documents`; same rules as image. */
102
137
  | {
103
138
  type: "document";
104
139
  mediaType: DocumentMediaType;
105
140
  source: MediaSource;
106
141
  name?: string;
142
+ size?: number;
143
+ }
144
+ /**
145
+ * An attachment whose content the model cannot read (an xlsx, say): the kernel replaces it with
146
+ * text carrying an unsigned object reference before the request, so a provider **never** receives
147
+ * this block. `mediaType` is any non-empty `type/subtype`; `size` is display metadata (the UI
148
+ * chip, the reference line) and is never sent.
149
+ */
150
+ | {
151
+ type: "file";
152
+ mediaType: string;
153
+ source: MediaSource;
154
+ name?: string;
155
+ size?: number;
107
156
  };
108
- /** 媒体块 `name` 的最大长度(字符)。 */
157
+ /** Maximum length (characters) of a media block's `name`. */
109
158
  export declare const MEDIA_NAME_MAX_CHARS = 255;
110
- /** 供应商请求里文件名 / 标题的建议上限(码点),{@link clipMediaName} 的默认值。 */
159
+ /**
160
+ * Suggested upper bound (code points) for file names / titles in vendor requests, the default of
161
+ * {@link clipMediaName}.
162
+ */
111
163
  export declare const PROVIDER_MEDIA_NAME_MAX = 200;
112
164
  /**
113
- * 把附件名截到 `max` 个码点以内(供应商映射用:有的接口对 filename / title 有长度限制,补后缀后还会更长)。
114
- * 尽量保留扩展名(不超过 16 个字符的 `.ext`),中间用 `…` 表示截掉的部分。纯函数。
165
+ * Truncates an attachment name to at most `max` code points (for vendor mapping: some APIs limit
166
+ * filename / title length, and adding a suffix makes it longer still).
167
+ * Keeps the extension where possible (a `.ext` of at most 16 characters), with `…` marking the cut
168
+ * part in the middle. A pure function.
115
169
  */
116
170
  export declare function clipMediaName(name: string, max?: number): string;
117
- /** 是否含控制字符(C0、DEL 与 C1)。 */
171
+ /** Whether it contains control characters (C0, DEL and C1). */
118
172
  export declare function hasControlChars(s: string): boolean;
119
- /** 附件 id 是否为 UUID(任意版本,大小写不限)。 */
173
+ /** Whether the attachment id is a UUID (any version, case-insensitive). */
120
174
  export declare function isAttachmentId(s: unknown): s is string;
121
175
  /**
122
- * 校验一个 image / document 块,返回错误列表(空表示合法):类型在列表里;`base64` 是标准、带填充、
123
- * 不含空白的 base64,解码后不超过 {@link MEDIA_LIMITS};`ref` 的 `attachmentId` 是 UUID;`name` 若有须是字符串、
124
- * 不超过 {@link MEDIA_NAME_MAX_CHARS} 个字符且不含控制字符。
176
+ * Validates an image / document / file block, returning a list of errors (empty means valid): the
177
+ * media type is in the block kind's list (`file` accepts any non-empty `type/subtype`); `base64` is
178
+ * standard, padded, whitespace-free base64 that decodes to at most {@link MEDIA_LIMITS}; a `ref`'s
179
+ * `attachmentId` is a UUID; `name`, when present, is a string of at most
180
+ * {@link MEDIA_NAME_MAX_CHARS} characters with no control characters; `size`, when present, is a
181
+ * non-negative integer (display metadata, never sent by a plugin).
125
182
  */
126
183
  export declare function validateMediaBlock(b: unknown): string[];
127
184
  export type ModelMessage = {
@@ -131,7 +188,10 @@ export type ModelMessage = {
131
188
  role: "assistant";
132
189
  content: ContentBlock[];
133
190
  }
134
- /** 对话中途的系统提醒;模型不支持时由插件转成 user 文本块(以 "[system] " 开头)。 */
191
+ /**
192
+ * A mid-conversation system reminder; when the model does not support it the plugin turns it into
193
+ * a user text block (starting with "[system] ").
194
+ */
135
195
  | {
136
196
  role: "system";
137
197
  content: string;
@@ -143,7 +203,10 @@ export interface ToolDefinition {
143
203
  }
144
204
  export interface ModelRequest {
145
205
  model: string;
146
- /** 稳定内容在前;cache 为 true 的块之后打缓存断点(由插件按原生协议实现)。 */
206
+ /**
207
+ * Stable content first; after a block with cache true a cache breakpoint is placed (implemented
208
+ * by the plugin per the native protocol).
209
+ */
147
210
  system: {
148
211
  text: string;
149
212
  cache: boolean;
@@ -151,32 +214,46 @@ export interface ModelRequest {
151
214
  messages: ModelMessage[];
152
215
  tools: ToolDefinition[];
153
216
  /**
154
- * `@2`:模型可否调用工具。`"none"` = 本次只能回复文本、不得调用工具(`tools` 仍照常带上:历史里有工具调用时
155
- * 部分供应商要求请求声明工具,且保持缓存前缀稳定);缺省或 `"auto"` = 由模型决定。
156
- * 插件映射到原生字段(如 Anthropic `tool_choice: {type: "none"}`);`tools` 为空时插件不发送该字段。
217
+ * `@2`: whether the model may call tools. `"none"` = this call may only reply with text and must
218
+ * not call tools (`tools` is still sent as usual: when the history has tool calls
219
+ * some vendors require the request to declare tools, and it keeps the cache prefix stable);
220
+ * omitted or `"auto"` = the model decides.
221
+ * The plugin maps it to the native field (e.g. Anthropic `tool_choice: {type: "none"}`); when
222
+ * `tools` is empty the plugin does not send the field.
157
223
  */
158
224
  toolChoice?: "auto" | "none";
159
225
  maxOutputTokens: number;
160
- /** `@2`:本次调用的参数(已按该模型的 `parameters` 处理过),由插件映射到原生请求。 */
226
+ /**
227
+ * The parameters of this call (already processed against the model's `parameters`), mapped to the
228
+ * native request by the plugin.
229
+ */
161
230
  params: Record<string, ParamValue>;
162
- /** @deprecated `model-provider@1` 用;`@2` 插件读 `params.effort`。 */
163
- effort?: Effort;
231
+ /**
232
+ * What this call is for, when the kernel says so: `"compaction"` for a conversation summary call.
233
+ * Absent on ordinary step calls. Informational (a scripted test model keys on it); real providers
234
+ * ignore it and must not forward it to a vendor API.
235
+ */
236
+ purpose?: ModelCallPurpose;
164
237
  }
165
- /** `model-provider@1` 的请求:没有 `params` 与 `toolChoice`。 */
166
- export type ModelRequestV1 = Omit<ModelRequest, "params" | "toolChoice">;
167
238
  export type StopReason = "end_turn" | "tool_use" | "max_tokens" | "refusal" | "other";
168
239
  /**
169
- * 一次调用的 token 用量。三类输入互不重叠:本次请求的输入总量 =
170
- * `inputTokens + cacheReadTokens + cacheWriteTokens`(内核据此校正上下文估算、决定何时压缩)。
171
- * 供应商 API 的输入计数若已包含缓存命中 / 写入的 token(如 OpenAI 的 `prompt_tokens`),插件必须先减掉。
240
+ * Token usage of one call. The three kinds of input do not overlap: the total input of this request
241
+ * =
242
+ * `inputTokens + cacheReadTokens + cacheWriteTokens` (the kernel uses it to correct context
243
+ * estimates and to decide when to compact).
244
+ * If the vendor API's input count already includes cache-hit / cache-write tokens (e.g. OpenAI's
245
+ * `prompt_tokens`), the plugin must subtract them first.
172
246
  */
173
247
  export interface ModelUsage {
174
- /** 未命中缓存、也未写入缓存的输入 token(只是未缓存部分,不是输入总量)。 */
248
+ /**
249
+ * Input tokens that neither hit the cache nor were written to it (only the uncached part, not the
250
+ * total input).
251
+ */
175
252
  inputTokens: number;
176
253
  outputTokens: number;
177
- /** 从提示词缓存读取的输入 token。 */
254
+ /** Input tokens read from the prompt cache. */
178
255
  cacheReadTokens: number;
179
- /** 本次写入提示词缓存的输入 token。 */
256
+ /** Input tokens written to the prompt cache in this call. */
180
257
  cacheWriteTokens: number;
181
258
  }
182
259
  export type ModelStreamEvent = {
@@ -192,9 +269,11 @@ export type ModelStreamEvent = {
192
269
  usage: ModelUsage;
193
270
  };
194
271
  export type ModelErrorKind = "rate_limited" | "overloaded" | "server" | "timeout" | "network" | "auth" | "invalid_request" | "context_overflow" | "aborted";
195
- /** rate_limited / overloaded / server / timeout / network 为 true。 */
272
+ /** True for rate_limited / overloaded / server / timeout / network. */
196
273
  export declare function isRetryableKind(kind: ModelErrorKind): boolean;
197
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
274
+ /**
275
+ * Duck-typed check (no instanceof), compatible with a plugin bundling another copy of plugin-sdk.
276
+ */
198
277
  export declare function isModelError(e: unknown): e is ModelError;
199
278
  export declare class ModelError extends Error {
200
279
  readonly kind: ModelErrorKind;
@@ -203,25 +282,55 @@ export declare class ModelError extends Error {
203
282
  retryAfterMs?: number;
204
283
  cause?: unknown;
205
284
  });
206
- /** rate_limited / overloaded / server / timeout / network 为 true。 */
285
+ /** True for rate_limited / overloaded / server / timeout / network. */
207
286
  get retryable(): boolean;
208
287
  }
209
- /** `model-provider@2` 的实现。 */
288
+ /**
289
+ * Options of a model call made for an organization.
290
+ * `config` is the extension's effective deployment config for this org: the platform's deployment
291
+ * config with the org's copy applied to the overridable fields (`orgAccess(…, "override")`), or the
292
+ * platform's config (equal to `ctx.config`) while the org follows it. Use it, not `ctx.config`, for
293
+ * work done for this org. Optional in the type so older providers compile; the kernel always passes
294
+ * both.
295
+ */
296
+ export interface ModelCallOptions {
297
+ orgId?: string;
298
+ config?: unknown;
299
+ }
300
+ export interface EmbedRequest {
301
+ model: string;
302
+ input: string[];
303
+ /** One of the model's `embedding.dimensions`; the model's default when absent. */
304
+ dimensions?: number;
305
+ inputType?: "query" | "document";
306
+ }
307
+ export interface EmbedResult {
308
+ /** One vector per input, in input order. */
309
+ vectors: number[][];
310
+ usage: {
311
+ inputTokens: number;
312
+ };
313
+ }
314
+ /**
315
+ * Checks an embedding result against its request and the model's embedding facts. Returns null when
316
+ * valid, else the reason: wrong vector count, wrong dimension, or a non-finite number.
317
+ */
318
+ export declare function validateEmbedResult(req: EmbedRequest, info: ModelEmbeddingInfo, res: EmbedResult): string | null;
319
+ /** The `model-provider@2` implementation. */
210
320
  export interface ModelProvider {
211
- /** 每个模型的 `parameters` 须通过 `assertValidDeclarations`,否则内核不使用该供应商。 */
212
- listModels(): Promise<ModelInfo[]>;
213
- /** 事件序列必须以且仅以一个 message_complete 结束;出错抛 ModelError。 */
321
+ /**
322
+ * Every model's `parameters` must pass `assertValidDeclarations`, otherwise the kernel does not
323
+ * use this vendor.
324
+ */
325
+ listModels(opts?: ModelCallOptions): Promise<ModelInfo[]>;
326
+ /** The event sequence must end with exactly one message_complete; throw ModelError on error. */
214
327
  stream(req: ModelRequest, opts: {
215
328
  signal: AbortSignal;
216
- }): AsyncIterable<ModelStreamEvent>;
217
- }
218
- /** `model-provider@1` 的实现(旧契约,内核经适配层接入:effort 由 `capabilities.effort` 推导)。 */
219
- export interface ModelProviderV1 {
220
- listModels(): Promise<ModelInfoV1[]>;
221
- /** 事件序列必须以且仅以一个 message_complete 结束;出错抛 ModelError。 */
222
- stream(req: ModelRequestV1, opts: {
329
+ } & ModelCallOptions): AsyncIterable<ModelStreamEvent>;
330
+ /** Present only on a provider that lists `embedding` models. */
331
+ embed?(req: EmbedRequest, opts: {
223
332
  signal: AbortSignal;
224
- }): AsyncIterable<ModelStreamEvent>;
333
+ } & ModelCallOptions): Promise<EmbedResult>;
225
334
  }
226
- export declare const MODEL_PROVIDER_EXTENSION_POINT = "model-provider@1";
335
+ /** The model provider extension point (the only version since `@1` was removed before 0.1.0). */
227
336
  export declare const MODEL_PROVIDER_EXTENSION_POINT_V2 = "model-provider@2";
package/dist/model.js CHANGED
@@ -1,23 +1,31 @@
1
- /** 图片块接受的类型。 */
1
+ /** Types accepted by image blocks. */
2
2
  export const IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
3
- /** 文档块接受的类型。 */
3
+ /** Types accepted by document blocks. */
4
4
  export const DOCUMENT_MEDIA_TYPES = [
5
5
  "application/pdf",
6
6
  "text/plain",
7
7
  "text/markdown",
8
8
  "text/csv",
9
9
  ];
10
- /** 单个媒体块解码后的字节上限(按主流供应商的较小值取)。 */
10
+ /**
11
+ * Upper bound on the decoded bytes of a single media block (the smaller value among mainstream
12
+ * vendors).
13
+ */
11
14
  export const MEDIA_LIMITS = { imageBytes: 5_242_880, documentBytes: 33_554_432 };
12
15
  const B64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
13
16
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
- /** 媒体块 `name` 的最大长度(字符)。 */
17
+ /** Maximum length (characters) of a media block's `name`. */
15
18
  export const MEDIA_NAME_MAX_CHARS = 255;
16
- /** 供应商请求里文件名 / 标题的建议上限(码点),{@link clipMediaName} 的默认值。 */
19
+ /**
20
+ * Suggested upper bound (code points) for file names / titles in vendor requests, the default of
21
+ * {@link clipMediaName}.
22
+ */
17
23
  export const PROVIDER_MEDIA_NAME_MAX = 200;
18
24
  /**
19
- * 把附件名截到 `max` 个码点以内(供应商映射用:有的接口对 filename / title 有长度限制,补后缀后还会更长)。
20
- * 尽量保留扩展名(不超过 16 个字符的 `.ext`),中间用 `…` 表示截掉的部分。纯函数。
25
+ * Truncates an attachment name to at most `max` code points (for vendor mapping: some APIs limit
26
+ * filename / title length, and adding a suffix makes it longer still).
27
+ * Keeps the extension where possible (a `.ext` of at most 16 characters), with `…` marking the cut
28
+ * part in the middle. A pure function.
21
29
  */
22
30
  export function clipMediaName(name, max = PROVIDER_MEDIA_NAME_MAX) {
23
31
  const cps = [...name];
@@ -29,7 +37,7 @@ export function clipMediaName(name, max = PROVIDER_MEDIA_NAME_MAX) {
29
37
  const head = cps.slice(0, max - 1 - keep.length);
30
38
  return `${head.join("")}…${keep.join("")}`;
31
39
  }
32
- /** 是否含控制字符(C0、DEL 与 C1)。 */
40
+ /** Whether it contains control characters (C0, DEL and C1). */
33
41
  export function hasControlChars(s) {
34
42
  for (let i = 0; i < s.length; i++) {
35
43
  const c = s.charCodeAt(i);
@@ -38,18 +46,26 @@ export function hasControlChars(s) {
38
46
  }
39
47
  return false;
40
48
  }
41
- /** 附件 id 是否为 UUID(任意版本,大小写不限)。 */
49
+ /** Whether the attachment id is a UUID (any version, case-insensitive). */
42
50
  export function isAttachmentId(s) {
43
51
  return typeof s === "string" && UUID_RE.test(s);
44
52
  }
53
+ /** Any non-empty `type/subtype` (a `file` block's `mediaType`). */
54
+ const MEDIA_TYPE_RE = /^[^/\s]+\/[^/\s]+$/;
45
55
  const MEDIA = {
46
56
  image: { types: IMAGE_MEDIA_TYPES, limit: MEDIA_LIMITS.imageBytes },
47
57
  document: { types: DOCUMENT_MEDIA_TYPES, limit: MEDIA_LIMITS.documentBytes },
58
+ // A file the model cannot read: the kernel resolves it to text before the request, so no media
59
+ // type list applies. The byte ceiling is the one attachments already have.
60
+ file: { types: [], limit: MEDIA_LIMITS.documentBytes, anyType: true },
48
61
  };
49
62
  /**
50
- * 校验一个 image / document 块,返回错误列表(空表示合法):类型在列表里;`base64` 是标准、带填充、
51
- * 不含空白的 base64,解码后不超过 {@link MEDIA_LIMITS};`ref` 的 `attachmentId` 是 UUID;`name` 若有须是字符串、
52
- * 不超过 {@link MEDIA_NAME_MAX_CHARS} 个字符且不含控制字符。
63
+ * Validates an image / document / file block, returning a list of errors (empty means valid): the
64
+ * media type is in the block kind's list (`file` accepts any non-empty `type/subtype`); `base64` is
65
+ * standard, padded, whitespace-free base64 that decodes to at most {@link MEDIA_LIMITS}; a `ref`'s
66
+ * `attachmentId` is a UUID; `name`, when present, is a string of at most
67
+ * {@link MEDIA_NAME_MAX_CHARS} characters with no control characters; `size`, when present, is a
68
+ * non-negative integer (display metadata, never sent by a plugin).
53
69
  */
54
70
  export function validateMediaBlock(b) {
55
71
  if (typeof b !== "object" || b === null || Array.isArray(b))
@@ -57,9 +73,16 @@ export function validateMediaBlock(b) {
57
73
  const o = b;
58
74
  const spec = typeof o.type === "string" && Object.hasOwn(MEDIA, o.type) ? MEDIA[o.type] : undefined;
59
75
  if (!spec)
60
- return ['block type must be "image" or "document"'];
76
+ return ['block type must be "image", "document" or "file"'];
61
77
  const errs = [];
62
- if (typeof o.mediaType !== "string" || !spec.types.includes(o.mediaType)) {
78
+ if (spec.anyType) {
79
+ if (typeof o.mediaType !== "string" ||
80
+ !MEDIA_TYPE_RE.test(o.mediaType) ||
81
+ hasControlChars(o.mediaType)) {
82
+ errs.push(`${o.type} mediaType must be a non-empty type/subtype string`);
83
+ }
84
+ }
85
+ else if (typeof o.mediaType !== "string" || !spec.types.includes(o.mediaType)) {
63
86
  errs.push(`${o.type} mediaType must be one of ${spec.types.join(", ")}`);
64
87
  }
65
88
  if (o.name !== undefined) {
@@ -72,6 +95,10 @@ export function validateMediaBlock(b) {
72
95
  errs.push(`${o.type} name must not contain control characters`);
73
96
  }
74
97
  }
98
+ if (o.size !== undefined &&
99
+ (typeof o.size !== "number" || !Number.isInteger(o.size) || o.size < 0)) {
100
+ errs.push(`${o.type} size must be a non-negative integer`);
101
+ }
75
102
  const src = o.source;
76
103
  if (typeof src !== "object" || src === null) {
77
104
  errs.push(`${o.type} source must be an object`);
@@ -89,7 +116,8 @@ export function validateMediaBlock(b) {
89
116
  errs.push(`${o.type} source.data must be non-empty padded base64`);
90
117
  return errs;
91
118
  }
92
- // 先按长度算解码后的大小,超限就不再逐字符校验
119
+ // Compute the decoded size from the length first; when over the limit, skip the per-character
120
+ // validation
93
121
  const pad = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
94
122
  const bytes = (data.length / 4) * 3 - pad;
95
123
  if (bytes > spec.limit) {
@@ -122,11 +150,13 @@ const RETRYABLE = new Set([
122
150
  "timeout",
123
151
  "network",
124
152
  ]);
125
- /** rate_limited / overloaded / server / timeout / network 为 true。 */
153
+ /** True for rate_limited / overloaded / server / timeout / network. */
126
154
  export function isRetryableKind(kind) {
127
155
  return RETRYABLE.has(kind);
128
156
  }
129
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
157
+ /**
158
+ * Duck-typed check (no instanceof), compatible with a plugin bundling another copy of plugin-sdk.
159
+ */
130
160
  export function isModelError(e) {
131
161
  if (!(e instanceof Error))
132
162
  return false;
@@ -143,10 +173,32 @@ export class ModelError extends Error {
143
173
  if (opts?.retryAfterMs !== undefined)
144
174
  this.retryAfterMs = opts.retryAfterMs;
145
175
  }
146
- /** rate_limited / overloaded / server / timeout / network 为 true。 */
176
+ /** True for rate_limited / overloaded / server / timeout / network. */
147
177
  get retryable() {
148
178
  return isRetryableKind(this.kind);
149
179
  }
150
180
  }
151
- export const MODEL_PROVIDER_EXTENSION_POINT = "model-provider@1";
181
+ /**
182
+ * Checks an embedding result against its request and the model's embedding facts. Returns null when
183
+ * valid, else the reason: wrong vector count, wrong dimension, or a non-finite number.
184
+ */
185
+ export function validateEmbedResult(req, info, res) {
186
+ if (res.vectors.length !== req.input.length) {
187
+ return `vector count ${res.vectors.length} does not match input count ${req.input.length}`;
188
+ }
189
+ const dims = req.dimensions ?? info.defaultDimensions;
190
+ for (let i = 0; i < res.vectors.length; i++) {
191
+ const v = res.vectors[i];
192
+ if (v.length !== dims) {
193
+ return `vector ${i} has dimension ${v.length}, expected ${dims}`;
194
+ }
195
+ for (const x of v) {
196
+ if (typeof x !== "number" || !Number.isFinite(x)) {
197
+ return `vector ${i} holds a non-finite number`;
198
+ }
199
+ }
200
+ }
201
+ return null;
202
+ }
203
+ /** The model provider extension point (the only version since `@1` was removed before 0.1.0). */
152
204
  export const MODEL_PROVIDER_EXTENSION_POINT_V2 = "model-provider@2";
package/dist/net.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Guarded outbound HTTP for URLs a person supplied (`ctx.net`).
3
+ *
4
+ * Rule: a request whose host comes from a person or from config an org admin or member can set (a
5
+ * connector endpoint, an org-overridable base URL) goes through `ctx.net.fetch`, never the global
6
+ * `fetch`; a fixed vendor host, or a URL only the super admin can set, may keep `fetch`.
7
+ */
8
+ /** Why `ctx.net.fetch` refused a request (the codes of the kernel's guarded client). */
9
+ export type NetDeniedCode = "net.insecure_url" | "net.private_address" | "net.dns_failed" | "net.redirect" | "net.proxy_refused";
10
+ /**
11
+ * The request was refused by the kernel's network rules; `message` is English and names `host`.
12
+ * Detect it with {@link isNetDeniedError} (by `name`), never `instanceof`, which fails across
13
+ * package copies. Map it to the plugin's own actionable error (a connector's `ToolError`, a
14
+ * provider's `ModelError` of kind `invalid_request`).
15
+ */
16
+ export declare class NetDeniedError extends Error {
17
+ readonly code: NetDeniedCode;
18
+ readonly host: string;
19
+ /** The HTTP status of a refused redirect (`net.redirect`); absent for the other codes. */
20
+ readonly status?: number | undefined;
21
+ readonly name: "NetDeniedError";
22
+ constructor(code: NetDeniedCode, host: string, message: string,
23
+ /** The HTTP status of a refused redirect (`net.redirect`); absent for the other codes. */
24
+ status?: number | undefined);
25
+ }
26
+ /** True for a {@link NetDeniedError} from any copy of the SDK or the kernel (checked by `name`). */
27
+ export declare function isNetDeniedError(e: unknown): e is NetDeniedError;
28
+ /**
29
+ * `ctx.net`: the kernel's guarded HTTP client, no permission needed. It needs a kernel that ships
30
+ * it: a plugin that calls it raises its manifest's minimum `sdk` to the SDK release that added it.
31
+ */
32
+ export interface ExtensionNet {
33
+ /**
34
+ * The global `fetch` signature with the kernel's network rules applied: https only, except plain
35
+ * http to an origin `http://host:port` a super admin allowed for `opts.orgId`, and to loopback
36
+ * under the kernel's tests-only `net.allowInsecureLoopback`; private, loopback and link-local
37
+ * addresses refused (link-local always), the address checked when the connection is made (no
38
+ * DNS-rebinding window); the deployment's egress proxy honoured. An http URL to a host the org
39
+ * allows only as a hostname entry (https only) is refused with a message that names the
40
+ * `http://host:port` origin entry which would allow it. Redirects
41
+ * are never followed: with `redirect: "manual"` a 3xx response is returned as is, otherwise a 3xx
42
+ * rejects with `net.redirect`. Bodies stream; no size cap. `init.signal` is combined with
43
+ * `ctx.signal`.
44
+ *
45
+ * `opts.orgId` is the org the request is made for (e.g. `ConnectorOpenArgs.orgId`): only then may
46
+ * the target be one of the internal endpoints a super admin allowed for that org. Without it only
47
+ * public addresses are reachable. A refusal rejects with {@link NetDeniedError}.
48
+ */
49
+ fetch(url: string, init?: RequestInit, opts?: {
50
+ orgId?: string;
51
+ }): Promise<Response>;
52
+ }
package/dist/net.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Guarded outbound HTTP for URLs a person supplied (`ctx.net`).
3
+ *
4
+ * Rule: a request whose host comes from a person or from config an org admin or member can set (a
5
+ * connector endpoint, an org-overridable base URL) goes through `ctx.net.fetch`, never the global
6
+ * `fetch`; a fixed vendor host, or a URL only the super admin can set, may keep `fetch`.
7
+ */
8
+ /**
9
+ * The request was refused by the kernel's network rules; `message` is English and names `host`.
10
+ * Detect it with {@link isNetDeniedError} (by `name`), never `instanceof`, which fails across
11
+ * package copies. Map it to the plugin's own actionable error (a connector's `ToolError`, a
12
+ * provider's `ModelError` of kind `invalid_request`).
13
+ */
14
+ export class NetDeniedError extends Error {
15
+ code;
16
+ host;
17
+ status;
18
+ name = "NetDeniedError";
19
+ constructor(code, host, message,
20
+ /** The HTTP status of a refused redirect (`net.redirect`); absent for the other codes. */
21
+ status) {
22
+ super(message);
23
+ this.code = code;
24
+ this.host = host;
25
+ this.status = status;
26
+ }
27
+ }
28
+ /** True for a {@link NetDeniedError} from any copy of the SDK or the kernel (checked by `name`). */
29
+ export function isNetDeniedError(e) {
30
+ if (typeof e !== "object" || e === null)
31
+ return false;
32
+ const o = e;
33
+ return o.name === "NetDeniedError" && typeof o.code === "string" && typeof o.host === "string";
34
+ }