@capybara-hq/plugin-sdk 0.1.0-rc.5 → 0.1.0-rc.50

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 (130) hide show
  1. package/agent-docs/agent-templates.md +14 -2
  2. package/agent-docs/concepts.md +14 -5
  3. package/agent-docs/connector-templates.md +4 -1
  4. package/agent-docs/extension-points/channel.md +1 -1
  5. package/agent-docs/extension-points/context.md +15 -0
  6. package/agent-docs/extension-points/file-preview.md +2 -0
  7. package/agent-docs/extension-points/model-provider.md +3 -1
  8. package/agent-docs/extension-points/object-store.md +2 -0
  9. package/agent-docs/extension-points/push-provider.md +17 -0
  10. package/agent-docs/extension-points/sandbox.md +2 -2
  11. package/agent-docs/extensions.md +29 -3
  12. package/agent-docs/plugin-format.md +48 -2
  13. package/agent-docs/setup.md +54 -0
  14. package/dist/agent-template.d.ts +15 -6
  15. package/dist/agent-template.js +32 -13
  16. package/dist/avatar-presets.d.ts +8 -0
  17. package/dist/avatar-presets.js +17 -0
  18. package/dist/bootstrap.d.ts +86 -1
  19. package/dist/bootstrap.js +161 -2
  20. package/dist/cards.d.ts +67 -13
  21. package/dist/cards.js +91 -21
  22. package/dist/channel.d.ts +148 -48
  23. package/dist/channel.js +10 -5
  24. package/dist/client-css.d.ts +36 -0
  25. package/dist/client-css.js +326 -0
  26. package/dist/client-section.d.ts +35 -0
  27. package/dist/client-section.js +133 -0
  28. package/dist/config-ui.d.ts +22 -0
  29. package/dist/config-ui.js +64 -4
  30. package/dist/connector-auth.d.ts +7 -2
  31. package/dist/connector-auth.js +29 -8
  32. package/dist/connector.d.ts +74 -32
  33. package/dist/context.d.ts +40 -0
  34. package/dist/context.js +2 -0
  35. package/dist/ctx.d.ts +120 -29
  36. package/dist/define-extension.d.ts +26 -12
  37. package/dist/define-extension.js +11 -4
  38. package/dist/device-denied-paths.d.ts +14 -0
  39. package/dist/device-denied-paths.js +41 -0
  40. package/dist/device-protocol.d.ts +489 -0
  41. package/dist/device-protocol.js +1116 -0
  42. package/dist/extension-point.d.ts +2 -0
  43. package/dist/extension-point.js +6 -2
  44. package/dist/file-preview.d.ts +23 -6
  45. package/dist/git-hosts.d.ts +53 -0
  46. package/dist/git-hosts.js +98 -0
  47. package/dist/hooks.d.ts +125 -20
  48. package/dist/hooks.js +5 -0
  49. package/dist/http-access.d.ts +62 -0
  50. package/dist/http-access.js +12 -0
  51. package/dist/identity.d.ts +38 -9
  52. package/dist/identity.js +21 -1
  53. package/dist/index.d.ts +28 -1
  54. package/dist/index.js +28 -1
  55. package/dist/marketplace.d.ts +26 -0
  56. package/dist/marketplace.js +43 -1
  57. package/dist/model-params.d.ts +41 -22
  58. package/dist/model-params.js +28 -15
  59. package/dist/model.d.ts +206 -71
  60. package/dist/model.js +152 -19
  61. package/dist/net.d.ts +52 -0
  62. package/dist/net.js +34 -0
  63. package/dist/network-classes.d.ts +98 -0
  64. package/dist/network-classes.js +291 -0
  65. package/dist/permissions.d.ts +41 -21
  66. package/dist/permissions.js +101 -42
  67. package/dist/plugin-manifest.d.ts +45 -5
  68. package/dist/plugin-manifest.js +169 -6
  69. package/dist/plugin-package.d.ts +82 -38
  70. package/dist/plugin-package.js +61 -29
  71. package/dist/push.d.ts +75 -0
  72. package/dist/push.js +87 -0
  73. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  74. package/dist/sandbox-linux-runtime-source.js +2318 -0
  75. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  76. package/dist/sandbox-native-runtime-source.js +476 -0
  77. package/dist/sandbox-operation.d.ts +298 -0
  78. package/dist/sandbox-operation.js +282 -0
  79. package/dist/sandbox-runtime-source.d.ts +19 -0
  80. package/dist/sandbox-runtime-source.js +28 -0
  81. package/dist/sandbox-write-denies.d.ts +139 -0
  82. package/dist/sandbox-write-denies.js +869 -0
  83. package/dist/sandbox.d.ts +190 -16
  84. package/dist/sandbox.js +89 -14
  85. package/dist/secret.d.ts +4 -1
  86. package/dist/secret.js +4 -1
  87. package/dist/setup-check.d.ts +128 -0
  88. package/dist/setup-check.js +142 -0
  89. package/dist/setup-guide-parse.d.ts +121 -0
  90. package/dist/setup-guide-parse.js +350 -0
  91. package/dist/setup-guide-render.d.ts +45 -0
  92. package/dist/setup-guide-render.js +351 -0
  93. package/dist/setup-guide.d.ts +96 -0
  94. package/dist/setup-guide.js +348 -0
  95. package/dist/shell-capabilities.d.ts +231 -0
  96. package/dist/shell-capabilities.js +37 -0
  97. package/dist/shell-environment.d.ts +57 -0
  98. package/dist/shell-environment.js +22 -0
  99. package/dist/skill-invocation.d.ts +4 -3
  100. package/dist/skill-invocation.js +5 -4
  101. package/dist/skill.d.ts +34 -21
  102. package/dist/skill.js +48 -31
  103. package/dist/storage.d.ts +52 -25
  104. package/dist/theme-assets.d.ts +55 -0
  105. package/dist/theme-assets.js +507 -0
  106. package/dist/theme-readability.d.ts +37 -0
  107. package/dist/theme-readability.js +145 -0
  108. package/dist/theme-tokens.generated.d.ts +299 -0
  109. package/dist/theme-tokens.generated.js +184 -0
  110. package/dist/theme.d.ts +190 -0
  111. package/dist/theme.js +471 -0
  112. package/dist/tool.d.ts +69 -26
  113. package/dist/tool.js +29 -9
  114. package/dist/ui-parts.d.ts +23 -0
  115. package/dist/ui-parts.js +348 -0
  116. package/dist/ui-resolve.d.ts +35 -0
  117. package/dist/ui-resolve.js +42 -0
  118. package/dist/ui-slots.d.ts +65 -0
  119. package/dist/ui-slots.js +261 -0
  120. package/dist/ui.d.ts +212 -76
  121. package/dist/ui.js +101 -27
  122. package/dist/url.d.ts +4 -1
  123. package/dist/url.js +4 -1
  124. package/package.json +8 -1
  125. package/schemas/bootstrap-extra.v1.schema.json +172 -0
  126. package/schemas/bootstrap.v1.schema.json +6 -0
  127. package/schemas/connector-template.v1.schema.json +35 -0
  128. package/schemas/marketplace.v1.schema.json +14 -0
  129. package/schemas/plugin.v1.schema.json +116 -3
  130. package/schemas/theme.v1.schema.json +302 -0
@@ -1,21 +1,24 @@
1
1
  import { z } from "zod";
2
2
  /*
3
- * 连接器的认证方式(只有类型与非密钥字段,凭据值不在这里):内核的连接器安装接口与企业目录里的连接器模板
4
- * (`ConnectorTemplateSpec.auth`)共用这一个 schema。各分支都是 strict:多出的字段(如 `token`)一律拒绝,
5
- * 所以合法的认证预设里不可能夹带凭据。OAuth 端点是否必须 https 由内核按部署配置再校验。
3
+ * A connector's authentication method (only the type and non-secret fields; credential values are
4
+ * not here): the kernel's connector install API and the connector templates in the catalog
5
+ * (`ConnectorTemplateSpec.auth`) share this one schema. Every branch is strict: extra fields (such
6
+ * as `token`) are always rejected,
7
+ * so a valid auth preset cannot smuggle in a credential. Whether OAuth endpoints must be https is
8
+ * checked again by the kernel per deployment config.
6
9
  */
7
- /** HTTP 头名(RFC 9110 token)。 */
10
+ /** HTTP header name (RFC 9110 token). */
8
11
  const HeaderName = z
9
12
  .string()
10
13
  .min(1)
11
14
  .max(100)
12
15
  .regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/, "Invalid header name");
13
16
  const Ownership = z.enum(["org", "personal"]);
14
- /** OAuth 端点(https 等由内核按部署配置再校验)。 */
17
+ /** OAuth endpoint (https etc. is checked again by the kernel per deployment config). */
15
18
  const OAuthUrl = z.url().max(2000);
16
- /** 令牌端点的客户端认证方式(有客户端密钥时)。 */
19
+ /** Client authentication method at the token endpoint (when there is a client secret). */
17
20
  const TokenAuthMethod = z.enum(["client_secret_basic", "client_secret_post"]);
18
- /** OAuth scope(RFC 6749 §3.3 scope-token)。 */
21
+ /** OAuth scope (RFC 6749 §3.3 scope-token). */
19
22
  const Scopes = z
20
23
  .array(z
21
24
  .string()
@@ -23,7 +26,23 @@ const Scopes = z
23
26
  .max(200)
24
27
  .regex(/^[\x21\x23-\x5B\x5D-\x7E]+$/, "Invalid scope"))
25
28
  .max(50);
26
- /** 认证方式:只有类型与非密钥字段;凭据值走内核的 `credential` / 凭据接口。 */
29
+ /**
30
+ * More `token_type` values the token endpoint may return for a bearer token (case-insensitive;
31
+ * `Bearer` and Slack's `user` are always accepted). The token is still sent as
32
+ * `Authorization: Bearer`. Never `DPoP`: such a token is bound to a key the kernel does not hold.
33
+ */
34
+ const TokenTypes = z
35
+ .array(z
36
+ .string()
37
+ .min(1)
38
+ .max(32)
39
+ .regex(/^[A-Za-z][A-Za-z0-9_.-]*$/, "Invalid token type")
40
+ .refine((t) => t.toLowerCase() !== "dpop", "DPoP tokens are not bearer tokens"))
41
+ .max(5);
42
+ /**
43
+ * Authentication method: only the type and non-secret fields; credential values go through the
44
+ * kernel's `credential` / credentials API.
45
+ */
27
46
  export const ConnectorAuthSchema = z.discriminatedUnion("type", [
28
47
  z.object({ type: z.literal("none") }).strict(),
29
48
  z.object({ type: z.literal("bearer"), ownership: Ownership }).strict(),
@@ -57,6 +76,7 @@ export const ConnectorAuthSchema = z.discriminatedUnion("type", [
57
76
  scopes: Scopes.optional(),
58
77
  client: z.enum(["dcr", "manual"]),
59
78
  tokenAuthMethod: TokenAuthMethod.optional(),
79
+ tokenTypes: TokenTypes.optional(),
60
80
  })
61
81
  .strict()
62
82
  .superRefine((a, ctx) => {
@@ -91,6 +111,7 @@ export const ConnectorAuthSchema = z.discriminatedUnion("type", [
91
111
  tokenUrl: OAuthUrl,
92
112
  scopes: Scopes.optional(),
93
113
  tokenAuthMethod: TokenAuthMethod.optional(),
114
+ tokenTypes: TokenTypes.optional(),
94
115
  })
95
116
  .strict(),
96
117
  ]);
@@ -1,16 +1,19 @@
1
1
  import type { ZodTypeAny } from "zod";
2
2
  import type { FormAnswer, ToolContent, ToolResult, ToolSpec } from "./tool.js";
3
- /** 注入到出站请求的鉴权信息。 */
3
+ /** Authentication information injected into outbound requests. */
4
4
  export interface AuthInjection {
5
5
  headers: Record<string, string>;
6
6
  query?: Record<string, string>;
7
7
  }
8
- /** 连接器与远端服务的一次会话。 */
8
+ /** One session between the connector and the remote service. */
9
9
  export interface ConnectorSession {
10
10
  listTools(): Promise<ToolSpec[]>;
11
11
  /**
12
- * `ctx.spec`:内核快照里该工具已复核的定义(`connector_tools.spec`,绝不是待复核的新定义),含 listTools 时给出的
13
- * `connectorData`。连接器应按它路由调用,而不是重新读取远端描述(远端变化须先经漂移复核)。旧内核不传,须判空。
12
+ * `ctx.spec`: the already-reviewed definition of this tool in the kernel snapshot
13
+ * (`connector_tools.spec`, never a new definition awaiting review), including the `connectorData`
14
+ * given at listTools.
15
+ * The connector should route the call by it rather than re-reading the remote description (remote
16
+ * changes must pass drift review first). Old kernels do not pass it; check for absence.
14
17
  */
15
18
  callTool(name: string, input: unknown, signal: AbortSignal, ctx?: {
16
19
  spec: ToolSpec;
@@ -22,13 +25,19 @@ export interface ConnectorSession {
22
25
  mimeType?: string;
23
26
  }[]>;
24
27
  readResource?(uri: string): Promise<ToolResult>;
25
- /** 可选:远端提供的提示模板(如 MCP prompts)。不支持时不实现,内核须判空。 */
28
+ /**
29
+ * Optional: prompt templates the remote provides (e.g. MCP prompts). Do not implement when
30
+ * unsupported; the kernel must check for absence.
31
+ */
26
32
  listPrompts?(): Promise<PromptInfo[]>;
27
- /** 可选:按参数渲染一个提示模板,返回消息(如 MCP `prompts/get`)。失败抛 ToolError(英文、不含凭据)。 */
33
+ /**
34
+ * Optional: renders a prompt template with arguments and returns messages (e.g. MCP
35
+ * `prompts/get`). On failure throw ToolError (English, no credentials).
36
+ */
28
37
  getPrompt?(name: string, args: Record<string, string>): Promise<RenderedPrompt>;
29
38
  close(): Promise<void>;
30
39
  }
31
- /** 远端提示模板(`/连接器:提示名` 斜杠命令)。 */
40
+ /** A remote prompt template (the `/connector:promptName` slash command). */
32
41
  export interface PromptInfo {
33
42
  name: string;
34
43
  title?: string;
@@ -39,7 +48,10 @@ export interface PromptInfo {
39
48
  required?: boolean;
40
49
  }[];
41
50
  }
42
- /** 渲染后的提示:按顺序的消息,内容块同工具结果(非文本给类型说明)。 */
51
+ /**
52
+ * A rendered prompt: messages in order, content blocks the same as tool results (non-text gets a
53
+ * type description).
54
+ */
43
55
  export interface RenderedPrompt {
44
56
  description?: string;
45
57
  messages: {
@@ -48,9 +60,11 @@ export interface RenderedPrompt {
48
60
  }[];
49
61
  }
50
62
  /**
51
- * 远端在一次调用中途向用户要输入(MCP `elicitation/create`):
52
- * - `form`:`requestedSchema` 是远端给的扁平 JSON Schema(object + 原始类型属性),由内核映射成交互表单;
53
- * - `url`:请用户在浏览器里打开 `url` 完成某步(授权、付款、填敏感信息),完成与否由用户确认。
63
+ * The remote asks the user for input in the middle of a call (MCP `elicitation/create`):
64
+ * - `form`: `requestedSchema` is the flat JSON Schema the remote gives (object + primitive-typed
65
+ * properties), which the kernel maps to an interactive form;
66
+ * - `url`: asks the user to open `url` in a browser to complete a step (authorization, payment,
67
+ * entering sensitive information); the user confirms whether it was completed.
54
68
  */
55
69
  export type ElicitationRequest = {
56
70
  mode: "form";
@@ -62,7 +76,10 @@ export type ElicitationRequest = {
62
76
  url: string;
63
77
  elicitationId: string;
64
78
  };
65
- /** 对 elicitation 的答复(与 MCP `ElicitResult` 对应):接受(带表单内容)/ 拒绝 / 取消。 */
79
+ /**
80
+ * The reply to an elicitation (corresponds to MCP `ElicitResult`): accept (with form content) /
81
+ * decline / cancel.
82
+ */
66
83
  export type ElicitationResponse = {
67
84
  action: "accept";
68
85
  content?: FormAnswer;
@@ -71,18 +88,26 @@ export type ElicitationResponse = {
71
88
  } | {
72
89
  action: "cancel";
73
90
  };
74
- /** 内核打开会话时传给连接器的参数。 */
91
+ /** Parameters the kernel passes to the connector when it opens a session. */
75
92
  export interface ConnectorOpenArgs {
76
- /** 已按 endpointSchema 校验。 */
93
+ /** Already validated against endpointSchema. */
77
94
  endpoint: unknown;
78
- /** 每次请求前调用,凭据的刷新由内核负责。 */
95
+ /** Called before every request; refreshing credentials is the kernel's job. */
79
96
  auth: () => Promise<AuthInjection>;
80
- /** 收到 401 时调用一次;内核刷新凭据后,插件重试一次。 */
97
+ /** Called once on a 401; after the kernel refreshes credentials the plugin retries once. */
81
98
  onUnauthorized: () => Promise<void>;
82
99
  signal: AbortSignal;
83
100
  /**
84
- * 会话期间远端报告工具清单变了(如 MCP `notifications/tools/list_changed`)时调用,可能多次;内核据此安排一次
85
- * 漂移检查(新的 / 变了的工具在管理员复核前不可用)。可选:旧内核不提供,连接器须判空。不要等待它、不要因它抛错。
101
+ * The org this session serves. Pass it to `ctx.net.fetch` as `opts.orgId` for every request to
102
+ * the endpoint, so the org's allowed internal endpoints apply (and no other org's).
103
+ */
104
+ orgId: string;
105
+ /**
106
+ * Called when the remote reports during the session that its tool list changed (e.g. MCP
107
+ * `notifications/tools/list_changed`), possibly several times; the kernel schedules one
108
+ * drift check from it (new / changed tools are unavailable until an admin reviews them).
109
+ * Optional: old kernels do not provide it, so the connector must check for absence. Do not wait
110
+ * for it and do not throw because of it.
86
111
  */
87
112
  onToolsChanged?: () => void;
88
113
  /**
@@ -91,17 +116,26 @@ export interface ConnectorOpenArgs {
91
116
  * when the kernel does not provide it, the connector does not declare the MCP elicitation
92
117
  * capability (so the remote never starts one).
93
118
  *
94
- * 内核不能在等用户回答期间保持远端调用(运行会暂停、worker 释放、会话关闭):需要问用户时,内核**中止本次调用**
95
- * (经 `callTool` 的 signal)并让运行进入等待;用户回答后内核重新发起同一调用,远端再次发起同样的 elicitation 时
96
- * 由本回调立即用用户的答案答复。所以连接器只需「收到就调用、拿到就回」,不要自己缓存或重试;需要问用户时本回调
97
- * 以错误拒绝(调用已被中止),连接器让该错误原样结束本次调用即可。
119
+ * The kernel cannot hold a remote call while waiting for the user to answer (the run pauses, the
120
+ * worker is released, the session closes): when the user must be asked, the kernel **aborts this
121
+ * call**
122
+ * (via the `callTool` signal) and puts the run into waiting; after the user answers the kernel
123
+ * issues the same call again, and when the remote raises the same elicitation again
124
+ * this callback replies at once with the user's answer. So the connector only needs "call it when
125
+ * received, return what it gets"; do not cache or retry yourself; when the user must be asked
126
+ * this callback
127
+ * rejects with an error (the call has already been aborted), and the connector simply lets that
128
+ * error end this call unchanged.
98
129
  */
99
130
  onElicit?: (request: ElicitationRequest) => Promise<ElicitationResponse>;
100
131
  }
101
132
  /**
102
- * 远端描述里声明的一种认证方式,映射到内核连接器认证(ConnectorAuth)的形状,供安装向导预填。
103
- * `scheme` 是远端描述里的名字(如 OpenAPI `securitySchemes` 的键),`description` 原样给出(可能缺省)。
104
- * 只列内核支持的方式;其余(cookie 里的 API key、OpenID Connect、implicit / password 流等)不出现。
133
+ * An authentication method declared in the remote description, mapped to the shape of the kernel's
134
+ * connector auth (ConnectorAuth), to prefill the install wizard.
135
+ * `scheme` is the name in the remote description (e.g. the key of OpenAPI `securitySchemes`),
136
+ * `description` is given as is (may be absent).
137
+ * Only methods the kernel supports are listed; the rest (API keys in cookies, OpenID Connect,
138
+ * implicit / password flows, etc.) do not appear.
105
139
  */
106
140
  export type AuthHint = {
107
141
  scheme: string;
@@ -124,31 +158,39 @@ export type AuthHint = {
124
158
  tokenUrl: string;
125
159
  scopes: string[];
126
160
  });
127
- /** 远端描述里的一个操作(如 OpenAPI operation),供安装向导勾选。 */
161
+ /**
162
+ * An operation in the remote description (e.g. an OpenAPI operation), for the install wizard to
163
+ * tick.
164
+ */
128
165
  export interface ConnectorOperation {
129
- /** 端点配置里勾选用的 id(如 OpenAPI 的 operationId)。 */
166
+ /** The id used for ticking in the endpoint config (e.g. OpenAPI's operationId). */
130
167
  id: string;
131
- /** 大写 HTTP 方法。 */
168
+ /** Uppercase HTTP method. */
132
169
  method: string;
133
170
  path: string;
134
171
  summary?: string;
135
172
  }
136
- /** `Connector.inspect` 的结果。 */
173
+ /** The result of `Connector.inspect`. */
137
174
  export interface ConnectorInspection {
138
175
  authHints: AuthHint[];
139
176
  operations?: ConnectorOperation[];
140
177
  }
141
- /** `connector@1`:插件实现、内核调用。 */
178
+ /** `connector@1`: implemented by the plugin, called by the kernel. */
142
179
  export interface Connector {
143
180
  kind: string;
144
181
  endpointSchema: ZodTypeAny;
145
182
  open(args: ConnectorOpenArgs): Promise<ConnectorSession>;
146
183
  /**
147
- * 可选:不带凭据读取端点的描述(安装向导的预览用),返回声明的认证方式与可选的操作清单。
148
- * `endpoint` 已按 endpointSchema 校验。失败抛 ToolError(消息英文、不含凭据)。旧连接器不实现,内核须判空。
184
+ * Optional: reads the endpoint's description without credentials (for the install wizard
185
+ * preview), returning the declared auth methods and an optional operation list.
186
+ * `endpoint` is already validated against endpointSchema. On failure throw ToolError (message in
187
+ * English, no credentials). Old connectors do not implement it; the kernel must check for
188
+ * absence. `orgId` is the org the preview runs for: pass it to `ctx.net.fetch` as `opts.orgId`
189
+ * for every request to the endpoint, as with `ConnectorOpenArgs.orgId`.
149
190
  */
150
191
  inspect?(args: {
151
192
  endpoint: unknown;
152
193
  signal: AbortSignal;
194
+ orgId: string;
153
195
  }): Promise<ConnectorInspection>;
154
196
  }
@@ -0,0 +1,40 @@
1
+ import type { ConversationSource } from "./tool.js";
2
+ /**
3
+ * What the kernel passes to a `context@1` provider at the start of a run. The provider returns the
4
+ * text it wants the model to see, or null.
5
+ */
6
+ export interface ContextRequest {
7
+ orgId: string;
8
+ /** The run's trigger account (the person whose message started the run). */
9
+ accountId: string;
10
+ agentId: string;
11
+ agentName: string;
12
+ conversationId: string;
13
+ runId: string;
14
+ /** Where the conversation comes from. */
15
+ source: ConversationSource;
16
+ /** The trigger account's role in the org. */
17
+ role: "owner" | "admin" | "member" | "guest";
18
+ /** The conversation's owner (`conversations.account_id`); `accountId` is the run's trigger account. */
19
+ ownerAccountId: string;
20
+ ownerName: string;
21
+ /** Keys of the tools the agent has in this run. */
22
+ tools: string[];
23
+ /** The provider's effective config for the org. */
24
+ config: unknown;
25
+ /** Aborts when the call runs past {@link CONTEXT_LIMITS}.timeoutMs or the run is aborted. */
26
+ signal: AbortSignal;
27
+ }
28
+ /** The text a provider adds to the model's context, or null for nothing. */
29
+ export type ContextResult = {
30
+ text: string;
31
+ } | null;
32
+ /** The `context@1` contract: an extension that adds text to the model's context at run start. */
33
+ export interface ContextProvider {
34
+ provide(req: ContextRequest): Promise<ContextResult>;
35
+ }
36
+ /** Limits on one `provide` call: the time it may take and the bytes of text the kernel keeps. */
37
+ export declare const CONTEXT_LIMITS: {
38
+ readonly timeoutMs: 2000;
39
+ readonly maxBytes: 32768;
40
+ };
@@ -0,0 +1,2 @@
1
+ /** Limits on one `provide` call: the time it may take and the bytes of text the kernel keeps. */
2
+ export const CONTEXT_LIMITS = { timeoutMs: 2000, maxBytes: 32768 };
package/dist/ctx.d.ts CHANGED
@@ -1,25 +1,31 @@
1
1
  import type { Kysely } from "kysely";
2
2
  import type { ExtensionPointRef } from "./extension-point.js";
3
3
  import type { AvailableHook, HookHandler, HookOptions } from "./hooks.js";
4
- import type { ModelEmbeddingInfo, ModelKind } from "./model.js";
4
+ import type { RouteCaller } from "./http-access.js";
5
+ import type { ImageAspectRatio, ImageMediaType, ImageSize, ModelEmbeddingInfo, ModelImageGenerationInfo, ModelKind } from "./model.js";
6
+ import type { ExtensionNet } from "./net.js";
7
+ import type { SetupCheckDefinition } from "./setup-check.js";
5
8
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
6
9
  import type { ToolHandler, ToolSpec } from "./tool.js";
7
10
  import type { EmbedClaims, UiActionArgs, UiActionResult, UiRenderArgs, UiView } from "./ui.js";
8
- /** 日志接口。 */
11
+ /** Logger interface. */
9
12
  export interface Logger {
10
13
  info(msg: string, fields?: Record<string, unknown>): void;
11
14
  warn(msg: string, fields?: Record<string, unknown>): void;
12
15
  error(msg: string, fields?: Record<string, unknown>): void;
13
16
  }
14
- /** 分布式锁租约。 */
17
+ /** Distributed lock lease. */
15
18
  export interface Lease {
16
19
  renew(): Promise<boolean>;
17
20
  release(): Promise<void>;
18
21
  }
19
22
  /**
20
- * 插件的对象存储(`ctx.storage`,需 `permissions.storage`):与 `ObjectStore` 同形,但每个方法的第一个参数是
21
- * `orgId`,键与前缀由内核自动加上 `plugins/<插件名>/<orgId>/`——插件只能看到自己在该组织下的对象。
22
- * 底层是部署配置的 `object-store@1` 提供方;没有提供方时各方法抛错。
23
+ * The plugin's object storage (`ctx.storage`, needs `permissions.storage`): the same shape as
24
+ * `ObjectStore`, but the first parameter of every method is
25
+ * `orgId`, and the kernel adds `plugins/<plugin name>/<orgId>/` to keys and prefixes automatically:
26
+ * a plugin sees only its own objects under that org.
27
+ * The backing store is the deployment-configured `object-store@1` provider; every method throws
28
+ * when there is no provider.
23
29
  */
24
30
  export interface ExtensionStorage {
25
31
  put(orgId: string, key: string, body: Uint8Array | ReadableStream<Uint8Array>, opts: {
@@ -28,8 +34,10 @@ export interface ExtensionStorage {
28
34
  signal?: AbortSignal;
29
35
  }): Promise<ObjectHead>;
30
36
  /**
31
- * 不存在返回 null。`range` 为闭区间字节范围,缺省 `end` 表示读到末尾。
32
- * 带 `range` 时 `head.size` 仍是整个对象的大小;存储忽略 Range 时 body 可能是整个对象。
37
+ * Returns null when missing. `range` is a closed byte range; an omitted `end` means read to the
38
+ * end.
39
+ * With `range`, `head.size` is still the size of the whole object; when the store ignores Range,
40
+ * body may be the whole object.
33
41
  */
34
42
  get(orgId: string, key: string, opts?: {
35
43
  signal?: AbortSignal;
@@ -42,7 +50,7 @@ export interface ExtensionStorage {
42
50
  body: ReadableStream<Uint8Array>;
43
51
  } | null>;
44
52
  head(orgId: string, key: string): Promise<ObjectHead | null>;
45
- /** 不存在也算成功。 */
53
+ /** A missing key also counts as success. */
46
54
  delete(orgId: string, key: string): Promise<void>;
47
55
  deletePrefix(orgId: string, prefix: string): Promise<number>;
48
56
  list(orgId: string, prefix: string, opts?: {
@@ -86,6 +94,39 @@ export interface ExtensionEmbedResult {
86
94
  };
87
95
  dimensions: number;
88
96
  }
97
+ /** A `ctx.models.generateImage` request: images generated for one org with the model of a purpose. */
98
+ export interface ExtensionImageGenerateRequest {
99
+ orgId: string;
100
+ /** A purpose this extension declared in `permissions.models` with `kind: "image_generation"`. */
101
+ purpose: string;
102
+ prompt: string;
103
+ /** An exact size the model offers; rejected otherwise. Wins over `aspectRatio`. */
104
+ size?: ImageSize;
105
+ /** The closest size the model offers; the model's default size when neither is given. */
106
+ aspectRatio?: ImageAspectRatio;
107
+ /** Images to produce (default 1, at most the model's `maxImages`). */
108
+ n?: number;
109
+ /** Base64 reference images, at most the model's `maxReferenceImages`. */
110
+ referenceImages?: {
111
+ mediaType: ImageMediaType;
112
+ data: string;
113
+ }[];
114
+ /** Aborts this call; combined with `ctx.signal`. */
115
+ signal?: AbortSignal;
116
+ }
117
+ /** A `ctx.models.generateImage` result. */
118
+ export interface ExtensionImageGenerateResult {
119
+ images: {
120
+ mediaType: ImageMediaType;
121
+ data: string;
122
+ }[];
123
+ revisedPrompt?: string;
124
+ model: {
125
+ provider: string;
126
+ id: string;
127
+ };
128
+ size: ImageSize;
129
+ }
89
130
  /** The model a purpose maps to in an org (`ctx.models.describe`). */
90
131
  export interface ExtensionModelTarget {
91
132
  provider: string;
@@ -93,13 +134,16 @@ export interface ExtensionModelTarget {
93
134
  kind: ModelKind;
94
135
  /** Present for an embedding model. */
95
136
  embedding?: ModelEmbeddingInfo;
137
+ /** Present for an image generation model. */
138
+ imageGeneration?: ModelImageGenerationInfo;
96
139
  }
97
140
  /**
98
141
  * Models by purpose (`permissions.models`): the purpose → model mapping is chosen by org admins
99
142
  * (and the deployment default by the super admin), never by the extension. Only purposes this
100
- * extension declared with `kind: "embedding"` are accepted (`model.purpose_unknown` otherwise), and
143
+ * extension declared with a matching `kind` (`embedding` for `embed`, `image_generation` for
144
+ * `generateImage`) are accepted (`model.purpose_unknown` otherwise), and
101
145
  * only for an org that enabled the extension (`extension.not_enabled`). Usage is recorded by the
102
- * kernel and reported through `usage.report` (purpose `embedding`).
146
+ * kernel and reported through `usage.report` (purpose `embedding`, or `image` for `generateImage`).
103
147
  */
104
148
  export interface ExtensionModels {
105
149
  /**
@@ -112,13 +156,24 @@ export interface ExtensionModels {
112
156
  * extension route), and nothing is sent or billed.
113
157
  */
114
158
  embed(req: ExtensionEmbedRequest): Promise<ExtensionEmbedResult>;
159
+ /**
160
+ * Generates images with the org's effective model for `purpose`. Rejects with
161
+ * `model.unconfigured` when the purpose maps to no usable model, `validation_failed` for a size,
162
+ * count or reference count the model does not offer, and a `ModelError` when the provider fails
163
+ * (kind `refusal` when it declines the prompt). Not retried. Fires `model.request` first
164
+ * (`purpose: "image"`); a policy denial rejects with `model.hook_denied`.
165
+ */
166
+ generateImage(req: ExtensionImageGenerateRequest): Promise<ExtensionImageGenerateResult>;
115
167
  /** The org's effective model for `purpose`, or null when it maps to no model the org can use. */
116
168
  describe(req: {
117
169
  orgId: string;
118
170
  purpose: string;
119
171
  }): Promise<ExtensionModelTarget | null>;
120
172
  }
121
- /** 传给插件 `setup` 的上下文。不提供定时器与进程内共享状态;kv 写入必须带 TTL。 */
173
+ /**
174
+ * The context passed to a plugin's `setup`. It provides no timers or in-process shared state; kv
175
+ * writes must carry a TTL.
176
+ */
122
177
  export interface ExtensionContext {
123
178
  kv: {
124
179
  get(key: string): Promise<string | null>;
@@ -152,18 +207,27 @@ export interface ExtensionContext {
152
207
  get(orgId: string, key: string): Promise<string | null>;
153
208
  set(orgId: string, key: string, value: string): Promise<void>;
154
209
  };
155
- /** 对象存储(需 `permissions.storage`,见 {@link ExtensionStorage})。 */
210
+ /** Object storage (needs `permissions.storage`, see {@link ExtensionStorage}). */
156
211
  storage: ExtensionStorage;
157
212
  /** Models by purpose (requires `permissions.models`, see {@link ExtensionModels}). */
158
213
  models: ExtensionModels;
159
- /** 已切到本插件 schema(withSchema)的 Kysely 实例。 */
214
+ /**
215
+ * Guarded HTTP for URLs a person supplied (see {@link ExtensionNet}): a connector endpoint or an
216
+ * org-overridable base URL goes through `ctx.net.fetch`, never the global `fetch`.
217
+ */
218
+ net: ExtensionNet;
219
+ /** A Kysely instance already switched to this plugin's schema (withSchema). */
160
220
  db: Kysely<any>;
161
221
  http: {
162
- /** 实际挂载到 `/plugins/<name><path>`。 */
163
- route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request) => Promise<Response>): void;
222
+ /**
223
+ * Mounted at `/plugins/<name><path>` (`public`, `embed`) or `/plugins/<name>/orgs/:orgId<path>`
224
+ * (`member`, `admin`), as `permissions.http` declares. The kernel enforces the access before
225
+ * the handler runs and passes the resolved caller; trust only `caller`.
226
+ */
227
+ route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request, caller: RouteCaller) => Promise<Response>): void;
164
228
  };
165
229
  tools: {
166
- /** 注册一个工具;只能在 `setup` 期间调用,名称不可重复。 */
230
+ /** Registers a tool; callable only during `setup`, names must not repeat. */
167
231
  register(spec: ToolSpec, handler: ToolHandler): void;
168
232
  };
169
233
  /**
@@ -195,23 +259,45 @@ export interface ExtensionContext {
195
259
  }[]>;
196
260
  };
197
261
  /**
198
- * 界面贡献的运行时(清单 `ui` + `permissions.ui`):
199
- * - `view` / `action`:只能在 `setup` 期间注册,id 是清单里 kind view 的贡献 id;
200
- * `action` 收到视图里按钮或表单提交(`args.actionId` 区分是哪一个);
201
- * - `invalidate`:告诉内核「这个贡献变了」,打开着它的网页会重新取视图(经 bus,跨副本);
202
- * - `verifyEmbedToken`:校验 embed 页面拿到的嵌入令牌,只认签给本插件、未过期的,且此刻插件仍在该组织启用、
203
- * 调用者仍是 active 成员(组织页面还要求 member 以上),否则返回 null;返回的 `role` 是此刻的角色。
262
+ * Runtime of UI contributions (manifest `ui` + `permissions.ui`):
263
+ * - `view` / `action`: can be registered only during `setup`; the id is the contribution id of
264
+ * the kind-view entry in the manifest;
265
+ * `action` receives a button click or form submission from the view (`args.actionId` tells
266
+ * which one);
267
+ * - `invalidate`: tells the kernel "this contribution changed", and the web pages that have it
268
+ * open fetch the view again (via the bus, across replicas); a
269
+ * `platform.page` contribution takes no `orgId` (it refreshes the admin console), every other
270
+ * contribution requires one;
271
+ * - `verifyEmbedToken`: validates the embed token an embed page received; it accepts only
272
+ * tokens signed for this plugin and not expired, while the plugin is still enabled in that org,
273
+ * the caller is still an active member and the role still satisfies the slot's minRole,
274
+ * otherwise it returns null; the returned `role` is the role at this moment. A
275
+ * platform-scope token (`scope: "platform"`, no `orgId`) verifies only for a `platform.page`
276
+ * contribution while the account is still an active super admin.
204
277
  */
205
278
  ui: {
206
279
  view(id: string, render: (args: UiRenderArgs) => Promise<UiView>): void;
207
280
  action(id: string, handler: (args: UiActionArgs) => Promise<UiActionResult>): void;
208
281
  invalidate(target: {
209
- orgId: string;
282
+ /** Required, except for a `platform.page` contribution, where it must be omitted. */
283
+ orgId?: string;
210
284
  conversationId?: string;
211
285
  contribution: string;
212
286
  }): Promise<void>;
213
287
  verifyEmbedToken(token: string): Promise<EmbedClaims | null>;
214
288
  };
289
+ /**
290
+ * Setup checks (`permissions.setupChecks`): the live rows of the plugin's setup guides.
291
+ * `check` is only allowed during `setup`; `id` must be listed in `permissions.setupChecks`
292
+ * (else `ExtensionPermissionError`); registering an id twice throws. The kernel runs a check only
293
+ * when a person or an agent asks, only for targets of this plugin and of `def.place`, aborts
294
+ * `signal` after `SETUP_CHECK_LIMITS.timeoutMs`, and redacts and bounds the result. A check never
295
+ * writes, passes `signal` to every request, does not retry and never puts a secret in `reason`
296
+ * or `fix`. It never receives an OAuth client secret or a member's token.
297
+ */
298
+ setup: {
299
+ check(id: string, def: SetupCheckDefinition): void;
300
+ };
215
301
  /**
216
302
  * Hooks (`permissions.hooks`): observe model and tool calls, or deny them with a policy hook.
217
303
  * `on` is only allowed during `setup`; the mount point must be declared in `permissions.hooks` and be
@@ -226,14 +312,19 @@ export interface ExtensionContext {
226
312
  };
227
313
  provide(extensionPoint: ExtensionPointRef, impl: unknown): void;
228
314
  /**
229
- * 本插件实例的生命周期信号:实例被撤销(停用、卸载、升级)时、在途调用排空之后中止。
230
- * 插件自己起的长任务(轮询循环、长连接等)据此收尾。
315
+ * The lifecycle signal of this plugin instance: aborted when the instance is revoked (disabled,
316
+ * uninstalled, upgraded), after in-flight calls have drained.
317
+ * Long-running tasks the plugin started itself (polling loops, long connections, etc.) wind down
318
+ * on it.
231
319
  */
232
320
  signal: AbortSignal;
233
321
  /**
234
- * 部署级配置,已按插件 schema 校验(启动配置与企业管理员在后台保存的值合并后)。这是一个 getter:
235
- * 标了 `hot`(`.meta({ hot: true })`)的字段改动时内核就地替换,插件**在用时读** `ctx.config` 才能拿到新值,
236
- * 不要在 setup 里把 hot 字段拷进闭包;改了非 hot 字段时内核重新加载插件实例(新的 setup)。
322
+ * Deployment-level config, validated against the plugin schema (the startup config merged with
323
+ * values the super admin saved in the console). This is a getter:
324
+ * when a field marked `hot` (`.meta({ hot: true })`) changes, the kernel replaces it in place, so
325
+ * the plugin must read `ctx.config` **at the time of use** to get the new value;
326
+ * do not copy hot fields into a closure in setup; when a non-hot field changes the kernel reloads
327
+ * the plugin instance (a new setup).
237
328
  */
238
329
  readonly config: unknown;
239
330
  log: Logger;
@@ -3,18 +3,25 @@ import type { ExtensionContext } from "./ctx.js";
3
3
  import { type ExtensionPointRef } from "./extension-point.js";
4
4
  import { type ExtensionPermissions } from "./permissions.js";
5
5
  import type { UiContribution } from "./ui.js";
6
- /** 插件清单。 */
6
+ /** The plugin manifest. */
7
7
  export interface ExtensionManifest {
8
8
  name: string;
9
9
  version: string;
10
10
  sdk: string;
11
11
  provides: ExtensionPointRef[];
12
12
  requires?: ExtensionPointRef[];
13
- /** 可选依赖:缺失时插件照常加载,运行时经 ctx.extensionPoints 判断。 */
13
+ /**
14
+ * Optional dependencies: when missing the plugin still loads, and decides at runtime through
15
+ * ctx.extensionPoints.
16
+ */
14
17
  optional?: ExtensionPointRef[];
15
- /** 权限清单(治理而非沙箱)。 */
18
+ /** Permission manifest (governance, not a sandbox). */
16
19
  permissions?: ExtensionPermissions;
17
- /** 界面贡献:对话页标签与组织页面;id 须同时列在 `permissions.ui` 里。 */
20
+ /**
21
+ * UI contributions, each in a slot of `UI_SLOTS`; every id is also listed in `permissions.ui`.
22
+ * Kept exactly as written: structural problems fail the extension, while a contribution to an
23
+ * unknown slot or version is only dropped when the host resolves the slots (`resolveUiSlots`).
24
+ */
18
25
  ui?: UiContribution[];
19
26
  config?: {
20
27
  deployment?: z.ZodTypeAny;
@@ -23,19 +30,26 @@ export interface ExtensionManifest {
23
30
  migrations?: string;
24
31
  setup(ctx: ExtensionContext): void | Promise<void>;
25
32
  /**
26
- * 可选:插件实例被撤销(停用、卸载、升级换新实例、依赖方随提供方重新加载)时调用。
27
- * 调用时内核已经:停止接新的调用、等在途调用结束(最多 `extensionHost.drainSeconds`)、中止 `ctx.signal`、
28
- * 撤销本实例经 ctx 做过的全部登记(工具、路由、队列 worker、bus 订阅、锁租约、界面、provide)。
29
- * 这里只收拾插件自己在 ctx 之外开的东西(如自建的连接);不要再经 ctx 登记任何东西。
30
- * setup 抛错时不调用(已登记的由内核撤销)。
33
+ * Optional: called when the plugin instance is revoked (disabled, uninstalled, replaced by a new
34
+ * instance on upgrade, a dependent reloaded together with its provider).
35
+ * By then the kernel has already: stopped accepting new calls, waited for in-flight calls to
36
+ * finish (at most `extensionHost.drainSeconds`), aborted `ctx.signal`,
37
+ * and revoked every registration this instance made through ctx (tools, routes, queue workers,
38
+ * bus subscriptions, lock leases, UI, provide).
39
+ * Clean up here only what the plugin opened outside ctx (e.g. its own connections); do not
40
+ * register anything through ctx again.
41
+ * Not called when setup throws (the kernel revokes what was already registered).
31
42
  */
32
43
  dispose?(ctx: ExtensionContext): void | Promise<void>;
33
44
  }
34
- /** 插件清单不合法。 */
45
+ /** The plugin manifest is invalid. */
35
46
  export declare class ExtensionManifestError extends Error {
36
47
  constructor(plugin: string, message: string);
37
48
  }
38
- /** 插件名规则(清单 `name`;连接器模板的 `plugin` 也按它校验)。 */
49
+ /** Plugin name rule (manifest `name`; a connector template's `plugin` is validated by it too). */
39
50
  export declare const EXTENSION_NAME_RE: RegExp;
40
- /** 校验并原样返回插件清单;不合法抛 ExtensionManifestError。 */
51
+ /**
52
+ * Validates the plugin manifest and returns it unchanged; throws ExtensionManifestError when
53
+ * invalid.
54
+ */
41
55
  export declare function defineExtension(m: ExtensionManifest): ExtensionManifest;