@capybara-hq/plugin-sdk 0.1.0-rc.9 → 0.1.0-rc.90

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 (159) hide show
  1. package/README.md +3 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +3 -1
  9. package/agent-docs/extension-points/identity-source.md +2 -0
  10. package/agent-docs/extension-points/model-provider.md +5 -1
  11. package/agent-docs/extension-points/object-store.md +2 -0
  12. package/agent-docs/extension-points/push-provider.md +17 -0
  13. package/agent-docs/extension-points/trigger-source.md +19 -0
  14. package/agent-docs/extensions.md +98 -4
  15. package/agent-docs/plugin-format.md +45 -10
  16. package/agent-docs/setup.md +54 -0
  17. package/api/plugin-sdk.api.md +5983 -0
  18. package/dist/agent-template.d.ts +15 -6
  19. package/dist/agent-template.js +32 -13
  20. package/dist/agents-ctx.d.ts +116 -0
  21. package/dist/agents-ctx.js +22 -0
  22. package/dist/avatar-presets.d.ts +8 -0
  23. package/dist/avatar-presets.js +17 -0
  24. package/dist/bootstrap.d.ts +109 -1
  25. package/dist/bootstrap.js +185 -2
  26. package/dist/cards.d.ts +121 -13
  27. package/dist/cards.js +161 -19
  28. package/dist/channel.d.ts +133 -47
  29. package/dist/channel.js +10 -5
  30. package/dist/client-css.d.ts +36 -0
  31. package/dist/client-css.js +326 -0
  32. package/dist/client-section.d.ts +35 -0
  33. package/dist/client-section.js +133 -0
  34. package/dist/config-ui.d.ts +28 -6
  35. package/dist/config-ui.js +88 -25
  36. package/dist/config-url-fetch.d.ts +19 -0
  37. package/dist/config-url-fetch.js +43 -0
  38. package/dist/connector-auth.d.ts +13 -2
  39. package/dist/connector-auth.js +82 -8
  40. package/dist/connector.d.ts +74 -32
  41. package/dist/context.d.ts +40 -0
  42. package/dist/context.js +2 -0
  43. package/dist/ctx.d.ts +344 -31
  44. package/dist/ctx.js +9 -1
  45. package/dist/define-extension.d.ts +18 -12
  46. package/dist/define-extension.js +18 -5
  47. package/dist/device-denied-paths.d.ts +20 -0
  48. package/dist/device-denied-paths.js +118 -0
  49. package/dist/device-operation.d.ts +348 -0
  50. package/dist/device-operation.js +312 -0
  51. package/dist/device-protocol.d.ts +286 -49
  52. package/dist/device-protocol.js +766 -89
  53. package/dist/device-provider.d.ts +820 -0
  54. package/dist/device-provider.js +432 -0
  55. package/dist/device-service.d.ts +204 -0
  56. package/dist/device-service.js +291 -0
  57. package/dist/dial-in.d.ts +286 -0
  58. package/dist/dial-in.js +213 -0
  59. package/dist/directory.d.ts +15 -12
  60. package/dist/extension-point.d.ts +2 -0
  61. package/dist/extension-point.js +8 -3
  62. package/dist/field-meta.d.ts +19 -0
  63. package/dist/field-meta.js +54 -0
  64. package/dist/file-preview.d.ts +46 -9
  65. package/dist/git-hosts.d.ts +53 -0
  66. package/dist/git-hosts.js +98 -0
  67. package/dist/hooks.d.ts +185 -22
  68. package/dist/hooks.js +6 -0
  69. package/dist/http-access.d.ts +71 -0
  70. package/dist/http-access.js +12 -0
  71. package/dist/identity.d.ts +70 -9
  72. package/dist/identity.js +46 -1
  73. package/dist/inbox.d.ts +103 -0
  74. package/dist/inbox.js +173 -0
  75. package/dist/index.d.ts +30 -4
  76. package/dist/index.js +30 -4
  77. package/dist/model-params.d.ts +41 -22
  78. package/dist/model-params.js +28 -15
  79. package/dist/model.d.ts +295 -77
  80. package/dist/model.js +249 -21
  81. package/dist/native-failure.d.ts +13 -0
  82. package/dist/native-failure.js +31 -0
  83. package/dist/net.d.ts +52 -0
  84. package/dist/net.js +34 -0
  85. package/dist/network-classes.d.ts +98 -0
  86. package/dist/network-classes.js +291 -0
  87. package/dist/permissions.d.ts +95 -25
  88. package/dist/permissions.js +175 -54
  89. package/dist/platform-only.d.ts +27 -0
  90. package/dist/platform-only.js +35 -0
  91. package/dist/plugin-manifest.d.ts +30 -6
  92. package/dist/plugin-manifest.js +147 -55
  93. package/dist/plugin-package.d.ts +82 -39
  94. package/dist/plugin-package.js +68 -41
  95. package/dist/push.d.ts +75 -0
  96. package/dist/push.js +87 -0
  97. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  98. package/dist/sandbox-linux-runtime-source.js +2343 -0
  99. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  100. package/dist/sandbox-native-runtime-source.js +480 -0
  101. package/dist/sandbox-runtime-source.d.ts +47 -0
  102. package/dist/sandbox-runtime-source.js +73 -0
  103. package/dist/sandbox-write-denies.d.ts +139 -0
  104. package/dist/sandbox-write-denies.js +869 -0
  105. package/dist/secret.d.ts +8 -2
  106. package/dist/secret.js +11 -4
  107. package/dist/setup-check.d.ts +128 -0
  108. package/dist/setup-check.js +142 -0
  109. package/dist/setup-guide-parse.d.ts +121 -0
  110. package/dist/setup-guide-parse.js +356 -0
  111. package/dist/setup-guide-render.d.ts +45 -0
  112. package/dist/setup-guide-render.js +351 -0
  113. package/dist/setup-guide.d.ts +86 -72
  114. package/dist/setup-guide.js +340 -108
  115. package/dist/shell-capabilities.d.ts +216 -0
  116. package/dist/shell-capabilities.js +44 -0
  117. package/dist/shell-environment.d.ts +57 -0
  118. package/dist/shell-environment.js +21 -0
  119. package/dist/skill-invocation.d.ts +5 -0
  120. package/dist/skill-invocation.js +4 -3
  121. package/dist/skill.d.ts +27 -17
  122. package/dist/skill.js +40 -26
  123. package/dist/storage.d.ts +52 -25
  124. package/dist/svg-viewbox.d.ts +10 -0
  125. package/dist/svg-viewbox.js +24 -0
  126. package/dist/theme-assets.d.ts +25 -9
  127. package/dist/theme-assets.js +87 -47
  128. package/dist/theme-tokens.generated.d.ts +40 -12
  129. package/dist/theme-tokens.generated.js +36 -8
  130. package/dist/theme.d.ts +56 -10
  131. package/dist/theme.js +117 -23
  132. package/dist/tool.d.ts +242 -28
  133. package/dist/tool.js +135 -13
  134. package/dist/trigger-source.d.ts +35 -0
  135. package/dist/trigger-source.js +2 -0
  136. package/dist/triggers.d.ts +88 -0
  137. package/dist/triggers.js +71 -0
  138. package/dist/ui-parts.d.ts +23 -0
  139. package/dist/ui-parts.js +374 -0
  140. package/dist/ui-resolve.d.ts +2 -7
  141. package/dist/ui-resolve.js +7 -19
  142. package/dist/ui-slots.d.ts +27 -5
  143. package/dist/ui-slots.js +112 -19
  144. package/dist/ui.d.ts +203 -64
  145. package/dist/ui.js +117 -23
  146. package/dist/url.d.ts +4 -1
  147. package/dist/url.js +4 -1
  148. package/dist/web.d.ts +26 -20
  149. package/package.json +13 -1
  150. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  151. package/schemas/bootstrap.v1.schema.json +20 -0
  152. package/schemas/connector-template.v1.schema.json +62 -4
  153. package/schemas/plugin.v1.schema.json +74 -143
  154. package/schemas/theme.v1.schema.json +77 -0
  155. package/agent-docs/extension-points/sandbox.md +0 -15
  156. package/dist/org-access.d.ts +0 -27
  157. package/dist/org-access.js +0 -35
  158. package/dist/sandbox.d.ts +0 -254
  159. package/dist/sandbox.js +0 -153
package/dist/ctx.d.ts CHANGED
@@ -1,25 +1,36 @@
1
1
  import type { Kysely } from "kysely";
2
+ import type { AgentsCtx, ConversationsCtx, PeopleCtx } from "./agents-ctx.js";
3
+ import type { DeviceServiceSpec, DeviceServiceStatus, ServiceBlockedHost } from "./device-provider.js";
4
+ import type { DevicesCtx, DialInChannel } from "./dial-in.js";
2
5
  import type { ExtensionPointRef } from "./extension-point.js";
3
6
  import type { AvailableHook, HookHandler, HookOptions } from "./hooks.js";
4
- import type { ModelEmbeddingInfo, ModelKind } from "./model.js";
7
+ import type { RouteCaller } from "./http-access.js";
8
+ import type { InboxCtx } from "./inbox.js";
9
+ import type { ImageAspectRatio, ImageMediaType, ImageSize, ModelEmbeddingInfo, ModelImageGenerationInfo, ModelKind } from "./model.js";
10
+ import type { ExtensionNet } from "./net.js";
11
+ import type { SetupCheckDefinition } from "./setup-check.js";
5
12
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
6
- import type { ToolHandler, ToolSpec } from "./tool.js";
7
- import type { EmbedClaims, UiActionArgs, UiActionResult, UiRenderArgs, UiView } from "./ui.js";
8
- /** 日志接口。 */
13
+ import type { ToolCallContext, ToolHandler, ToolSpec, ToolWatcher } from "./tool.js";
14
+ import type { TriggersCtx } from "./triggers.js";
15
+ import type { EmbedClaims, JsonValue, UiActionArgs, UiActionResult, UiQueryArgs, UiRenderArgs, UiView } from "./ui.js";
16
+ /** Logger interface. */
9
17
  export interface Logger {
10
18
  info(msg: string, fields?: Record<string, unknown>): void;
11
19
  warn(msg: string, fields?: Record<string, unknown>): void;
12
20
  error(msg: string, fields?: Record<string, unknown>): void;
13
21
  }
14
- /** 分布式锁租约。 */
22
+ /** Distributed lock lease. */
15
23
  export interface Lease {
16
24
  renew(): Promise<boolean>;
17
25
  release(): Promise<void>;
18
26
  }
19
27
  /**
20
- * 插件的对象存储(`ctx.storage`,需 `permissions.storage`):与 `ObjectStore` 同形,但每个方法的第一个参数是
21
- * `orgId`,键与前缀由内核自动加上 `plugins/<插件名>/<orgId>/`——插件只能看到自己在该组织下的对象。
22
- * 底层是部署配置的 `object-store@1` 提供方;没有提供方时各方法抛错。
28
+ * The plugin's object storage (`ctx.storage`, needs `permissions.storage`): the same shape as
29
+ * `ObjectStore`, but the first parameter of every method is
30
+ * `orgId`, and the kernel adds `plugins/<plugin name>/<orgId>/` to keys and prefixes automatically:
31
+ * a plugin sees only its own objects under that org.
32
+ * The backing store is the deployment-configured `object-store@1` provider; every method throws
33
+ * when there is no provider.
23
34
  */
24
35
  export interface ExtensionStorage {
25
36
  put(orgId: string, key: string, body: Uint8Array | ReadableStream<Uint8Array>, opts: {
@@ -28,8 +39,10 @@ export interface ExtensionStorage {
28
39
  signal?: AbortSignal;
29
40
  }): Promise<ObjectHead>;
30
41
  /**
31
- * 不存在返回 null。`range` 为闭区间字节范围,缺省 `end` 表示读到末尾。
32
- * 带 `range` 时 `head.size` 仍是整个对象的大小;存储忽略 Range 时 body 可能是整个对象。
42
+ * Returns null when missing. `range` is a closed byte range; an omitted `end` means read to the
43
+ * end.
44
+ * With `range`, `head.size` is still the size of the whole object; when the store ignores Range,
45
+ * body may be the whole object.
33
46
  */
34
47
  get(orgId: string, key: string, opts?: {
35
48
  signal?: AbortSignal;
@@ -42,7 +55,7 @@ export interface ExtensionStorage {
42
55
  body: ReadableStream<Uint8Array>;
43
56
  } | null>;
44
57
  head(orgId: string, key: string): Promise<ObjectHead | null>;
45
- /** 不存在也算成功。 */
58
+ /** A missing key also counts as success. */
46
59
  delete(orgId: string, key: string): Promise<void>;
47
60
  deletePrefix(orgId: string, prefix: string): Promise<number>;
48
61
  list(orgId: string, prefix: string, opts?: {
@@ -86,6 +99,39 @@ export interface ExtensionEmbedResult {
86
99
  };
87
100
  dimensions: number;
88
101
  }
102
+ /** A `ctx.models.generateImage` request: images generated for one org with the model of a purpose. */
103
+ export interface ExtensionImageGenerateRequest {
104
+ orgId: string;
105
+ /** A purpose this extension declared in `permissions.models` with `kind: "image_generation"`. */
106
+ purpose: string;
107
+ prompt: string;
108
+ /** An exact size the model offers; rejected otherwise. Wins over `aspectRatio`. */
109
+ size?: ImageSize;
110
+ /** The closest size the model offers; the model's default size when neither is given. */
111
+ aspectRatio?: ImageAspectRatio;
112
+ /** Images to produce (default 1, at most the model's `maxImages`). */
113
+ n?: number;
114
+ /** Base64 reference images, at most the model's `maxReferenceImages`. */
115
+ referenceImages?: {
116
+ mediaType: ImageMediaType;
117
+ data: string;
118
+ }[];
119
+ /** Aborts this call; combined with `ctx.signal`. */
120
+ signal?: AbortSignal;
121
+ }
122
+ /** A `ctx.models.generateImage` result. */
123
+ export interface ExtensionImageGenerateResult {
124
+ images: {
125
+ mediaType: ImageMediaType;
126
+ data: string;
127
+ }[];
128
+ revisedPrompt?: string;
129
+ model: {
130
+ provider: string;
131
+ id: string;
132
+ };
133
+ size: ImageSize;
134
+ }
89
135
  /** The model a purpose maps to in an org (`ctx.models.describe`). */
90
136
  export interface ExtensionModelTarget {
91
137
  provider: string;
@@ -93,13 +139,16 @@ export interface ExtensionModelTarget {
93
139
  kind: ModelKind;
94
140
  /** Present for an embedding model. */
95
141
  embedding?: ModelEmbeddingInfo;
142
+ /** Present for an image generation model. */
143
+ imageGeneration?: ModelImageGenerationInfo;
96
144
  }
97
145
  /**
98
146
  * Models by purpose (`permissions.models`): the purpose → model mapping is chosen by org admins
99
147
  * (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
148
+ * extension declared with a matching `kind` (`embedding` for `embed`, `image_generation` for
149
+ * `generateImage`) are accepted (`model.purpose_unknown` otherwise), and
101
150
  * 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`).
151
+ * kernel and reported through `usage.report` (purpose `embedding`, or `image` for `generateImage`).
103
152
  */
104
153
  export interface ExtensionModels {
105
154
  /**
@@ -112,13 +161,194 @@ export interface ExtensionModels {
112
161
  * extension route), and nothing is sent or billed.
113
162
  */
114
163
  embed(req: ExtensionEmbedRequest): Promise<ExtensionEmbedResult>;
164
+ /**
165
+ * Generates images with the org's effective model for `purpose`. Rejects with
166
+ * `model.unconfigured` when the purpose maps to no usable model, `validation_failed` for a size,
167
+ * count or reference count the model does not offer, and a `ModelError` when the provider fails
168
+ * (kind `refusal` when it declines the prompt). Not retried. Fires `model.request` first
169
+ * (`purpose: "image"`); a policy denial rejects with `model.hook_denied`.
170
+ */
171
+ generateImage(req: ExtensionImageGenerateRequest): Promise<ExtensionImageGenerateResult>;
115
172
  /** The org's effective model for `purpose`, or null when it maps to no model the org can use. */
116
173
  describe(req: {
117
174
  orgId: string;
118
175
  purpose: string;
119
176
  }): Promise<ExtensionModelTarget | null>;
120
177
  }
121
- /** 传给插件 `setup` 的上下文。不提供定时器与进程内共享状态;kv 写入必须带 TTL。 */
178
+ /**
179
+ * The org, conversation and account a {@link DeviceAccessCtx} call from outside a tool call is for
180
+ * (`orgId` must be the conversation's org).
181
+ */
182
+ export type DeviceAccessScope = {
183
+ orgId: string;
184
+ conversationId: string;
185
+ accountId: string;
186
+ };
187
+ /**
188
+ * `ctx.deviceAccess` (requires `permissions.deviceAccess`): the extension's services in the
189
+ * conversation's device. Every call works on the device of the conversation it names (a tool
190
+ * call's, or `scope.conversationId`), only for a service listed in
191
+ * `permissions.deviceAccess.services`, and only when the account (the tool call's trigger account,
192
+ * or `scope.accountId`) is the conversation's owner. A refusal throws {@link DeviceAccessError}.
193
+ */
194
+ export interface DeviceAccessCtx {
195
+ /**
196
+ * Starts the service in the call's device, or finds it running: the kernel writes the spec's
197
+ * files into the service's state directory, passes the launch through the command review (fail
198
+ * closed) and starts it through the device's provider.
199
+ */
200
+ ensureService(call: ToolCallContext, spec: DeviceServiceSpec): Promise<DeviceServiceStatus>;
201
+ /**
202
+ * One request to the service's socket; resolves its answer. `ifRunning`: only a running
203
+ * instance with the service running answers, otherwise {@link DeviceAccessError}
204
+ * `not_running`; nothing is resumed or started (a running instance's last use is refreshed). A
205
+ * watcher's requests ({@link ToolWatcher}) always run so.
206
+ */
207
+ request(call: ToolCallContext, req: {
208
+ service: string;
209
+ body: Uint8Array;
210
+ timeoutMs: number;
211
+ ifRunning?: boolean;
212
+ }): Promise<Uint8Array>;
213
+ /**
214
+ * The service saw requests to `hosts` refused by the device's network during this call, each
215
+ * with the layer that refused it (`sandboxProxyRefusalLayer` reads it from the device's
216
+ * proxy): once the handler returns, the kernel raises the network ask in the call's
217
+ * conversation for `device` hosts it can offer (and runs the call again once the person
218
+ * approves), and writes a note for the others (an `address` host: a private or local address,
219
+ * which no host grant reaches). Only an ask: a layer never widens access, and the kernel's own
220
+ * planning still applies (a host the device list cannot take is never asked about; an IP
221
+ * literal is always `address`). A host reported twice keeps its most restrictive layer.
222
+ * `opts.url` is the page the refusals came from, shown with the ask.
223
+ *
224
+ * A loopback refusal (`layer: "address"`, a loopback grant host with its `port`) of an extension
225
+ * that declares `permissions.deviceAccess.loopbackPorts` raises a loopback port ask instead,
226
+ * where the device's outside-sandbox ceilings allow one (a note otherwise). `opts.service` is the
227
+ * declared service the refusals came from; it is required for a loopback ask when the
228
+ * extension declares more than one service.
229
+ */
230
+ reportBlockedHosts(call: ToolCallContext, hosts: ServiceBlockedHost[], opts?: {
231
+ url?: string;
232
+ service?: string;
233
+ }): void;
234
+ /**
235
+ * A short-lived, single-use ticket for one viewer stream to the service (the person's panel
236
+ * opens `url` as a WebSocket). The account must be the conversation's owner.
237
+ */
238
+ streamTicket(scope: DeviceAccessScope & {
239
+ service: string;
240
+ }): Promise<{
241
+ url: string;
242
+ expiresAt: string;
243
+ }>;
244
+ /**
245
+ * Adds hosts to the device's network allowlist (owner only, platform and org ceilings apply);
246
+ * the extension's running services get the device's new limits applied. Exact host names
247
+ * only, as an approved network ask grants: a `*.` wildcard is refused.
248
+ */
249
+ addNetworkHosts(scope: DeviceAccessScope & {
250
+ hosts: string[];
251
+ }): Promise<void>;
252
+ /**
253
+ * Grants the service one loopback port of the device (`LOOPBACK_GRANT_HOSTS` on `port`) for the
254
+ * scope conversation's tree: the grant is held by the conversation's root, so its sub-agents
255
+ * share it. For the person's own click in the extension's panel (needs
256
+ * `permissions.deviceAccess.loopbackPorts`, else `loopback_not_declared`; a port outside
257
+ * 1–65535 is `invalid_request`).
258
+ *
259
+ * What the kernel checks: `scope.accountId` owns the conversation, its root and the root's
260
+ * personal device; the call is not made inside a run's tool step; the tree is not unattended by
261
+ * the kernel's records (an automation's conversation, or an automation run active in it now);
262
+ * the device's runtime can run outside its sandbox now, and the outside-sandbox ceilings
263
+ * (platform, org, device and owner settings) and the provider's loopback support allow it. Any
264
+ * of these refuses with `loopback_unavailable`; more than `LOOPBACK_MAX_PORTS_PER_SERVICE` live
265
+ * ports refuse with `loopback_limit`. The kernel cannot verify that a person clicked: beyond
266
+ * these checks, the owner-panel path rests on the extension, governed by the blocking approval
267
+ * of `permissions.deviceAccess.loopbackPorts`.
268
+ *
269
+ * Recorded with source `owner-panel`; the grant lives 24 hours (or until revoked, the
270
+ * conversation is deleted or the outside-sandbox setting is switched off), and the running
271
+ * service is refreshed with it. Granting a live port again answers the existing grant.
272
+ */
273
+ grantLoopbackPort(scope: DeviceAccessScope & {
274
+ service: string;
275
+ port: number;
276
+ }): Promise<LoopbackGrantView>;
277
+ /**
278
+ * Revokes the scope conversation root's grant of `port` to the service (owner only, needs
279
+ * `permissions.deviceAccess.loopbackPorts`); succeeds when there is none. The running service is
280
+ * refreshed without the port.
281
+ */
282
+ revokeLoopbackPort(scope: DeviceAccessScope & {
283
+ service: string;
284
+ port: number;
285
+ }): Promise<void>;
286
+ /**
287
+ * The live loopback port grants of the service held by the scope conversation's root, sorted by
288
+ * port (owner only, needs `permissions.deviceAccess.loopbackPorts`). Grants live 24 hours from
289
+ * issue and follow the same outside-sandbox ceilings as {@link grantLoopbackPort}. Empty while
290
+ * the tree is unattended (an automation's conversation, or an automation's run with no person
291
+ * joined): a grant is never an unattended run's, so a per-tab check refuses that tab.
292
+ */
293
+ loopbackPorts(scope: DeviceAccessScope & {
294
+ service: string;
295
+ }): Promise<LoopbackGrantView[]>;
296
+ /**
297
+ * Answers the handoff question of this extension's tool call `callId` from the panel.
298
+ * `handoffConversationId` is the conversation whose tool call raised the handoff (the extension
299
+ * learns it from `ToolCallContext.conversationId`; the panel may echo it back, so it is
300
+ * untrusted input): the kernel answers only when it is the scope conversation or one of its
301
+ * sub-agent descendants (a call id is unique only within a run, so two sub-agents of one tree
302
+ * can wait under the same one). Any other conversation, like a question that is not pending or
303
+ * not this extension's, refuses with `question.not_found`.
304
+ */
305
+ answerHandoff(scope: DeviceAccessScope & {
306
+ callId: string;
307
+ handoffConversationId: string;
308
+ done: boolean;
309
+ }): Promise<void>;
310
+ }
311
+ /**
312
+ * Who granted a loopback port: the person deciding an ask (`human`), the review model
313
+ * (`review-model`), a Full access profile within its ceilings (`full-access`), or the owner's own
314
+ * click in the panel (`owner-panel`, {@link DeviceAccessCtx.grantLoopbackPort}).
315
+ */
316
+ export type LoopbackGrantSource = "human" | "review-model" | "full-access" | "owner-panel";
317
+ /** One live loopback port grant of a device service ({@link DeviceAccessCtx.loopbackPorts}). */
318
+ export interface LoopbackGrantView {
319
+ port: number;
320
+ source: LoopbackGrantSource;
321
+ /** ISO 8601 time the grant ends (24 hours after issue). */
322
+ expiresAt: string;
323
+ /** The port is a well-known database port (`LOOPBACK_DATABASE_PORTS`). */
324
+ database: boolean;
325
+ }
326
+ /** Why a {@link DeviceAccessCtx} call was refused. */
327
+ export type DeviceAccessErrorCode = "no_device" | "provider_unavailable" | "capability_missing" | "not_owner" | "service_not_declared"
328
+ /** An `ifRunning` request found the device's instance or the service not running. */
329
+ | "not_running"
330
+ /** A loopback port call from an extension without `permissions.deviceAccess.loopbackPorts`. */
331
+ | "loopback_not_declared"
332
+ /**
333
+ * A loopback port cannot be granted here: running outside the sandbox is off (platform, org,
334
+ * device or owner setting), the run is unattended, or the provider has no loopback support.
335
+ */
336
+ | "loopback_unavailable"
337
+ /** The service already holds `LOOPBACK_MAX_PORTS_PER_SERVICE` live loopback port grants. */
338
+ | "loopback_limit"
339
+ /** A malformed argument (a loopback port that is not an integer from 1 to 65535). */
340
+ | "invalid_request";
341
+ /** A {@link DeviceAccessCtx} call was refused; the message is actionable English for the model. */
342
+ export declare class DeviceAccessError extends Error {
343
+ readonly code: DeviceAccessErrorCode;
344
+ constructor(code: DeviceAccessErrorCode, message: string, opts?: {
345
+ cause?: unknown;
346
+ });
347
+ }
348
+ /**
349
+ * The context passed to a plugin's `setup`. It provides no timers or in-process shared state; kv
350
+ * writes must carry a TTL.
351
+ */
122
352
  export interface ExtensionContext {
123
353
  kv: {
124
354
  get(key: string): Promise<string | null>;
@@ -152,19 +382,33 @@ export interface ExtensionContext {
152
382
  get(orgId: string, key: string): Promise<string | null>;
153
383
  set(orgId: string, key: string, value: string): Promise<void>;
154
384
  };
155
- /** 对象存储(需 `permissions.storage`,见 {@link ExtensionStorage})。 */
385
+ /** Object storage (needs `permissions.storage`, see {@link ExtensionStorage}). */
156
386
  storage: ExtensionStorage;
157
387
  /** Models by purpose (requires `permissions.models`, see {@link ExtensionModels}). */
158
388
  models: ExtensionModels;
159
- /** 已切到本插件 schema(withSchema)的 Kysely 实例。 */
389
+ /**
390
+ * Guarded HTTP for URLs a person supplied (see {@link ExtensionNet}): a connector endpoint or an
391
+ * org-overridable base URL goes through `ctx.net.fetch`, never the global `fetch`.
392
+ */
393
+ net: ExtensionNet;
394
+ /** A Kysely instance already switched to this plugin's schema (withSchema). */
160
395
  db: Kysely<any>;
161
396
  http: {
162
- /** 实际挂载到 `/plugins/<name><path>`。 */
163
- route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request) => Promise<Response>): void;
397
+ /**
398
+ * Mounted at `/plugins/<name><path>` (`public`, `embed`) or `/plugins/<name>/orgs/:orgId<path>`
399
+ * (`member`, `admin`), as `permissions.http` declares. The kernel enforces the access before
400
+ * the handler runs and passes the resolved caller; trust only `caller`.
401
+ */
402
+ route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request, caller: RouteCaller) => Promise<Response>): void;
164
403
  };
165
404
  tools: {
166
- /** 注册一个工具;只能在 `setup` 期间调用,名称不可重复。 */
167
- register(spec: ToolSpec, handler: ToolHandler): void;
405
+ /**
406
+ * Registers a tool; callable only during `setup`, names must not repeat. `opts.watch`: the
407
+ * tool's watcher for watched waits (`InputRequired.watch`, see {@link ToolWatcher}).
408
+ */
409
+ register(spec: ToolSpec, handler: ToolHandler, opts?: {
410
+ watch?: ToolWatcher;
411
+ }): void;
168
412
  };
169
413
  /**
170
414
  * Consume extension points provided by other extensions: only non-brokered refs declared in the
@@ -195,20 +439,37 @@ export interface ExtensionContext {
195
439
  }[]>;
196
440
  };
197
441
  /**
198
- * 界面贡献的运行时(清单 `ui` + `permissions.ui`):
199
- * - `view` / `action`:只能在 `setup` 期间注册,id 是清单里 kind view 的贡献 id;
200
- * `action` 收到视图里按钮或表单提交(`args.actionId` 区分是哪一个);
201
- * - `invalidate`:告诉内核「这个贡献变了」,打开着它的网页会重新取视图(经 bus,跨副本);a
442
+ * Runtime of UI contributions (manifest `ui` + `permissions.ui`):
443
+ * - `view` / `action`: can be registered only during `setup`; the id is the contribution id of
444
+ * the kind-view entry in the manifest;
445
+ * `action` receives a button click or form submission from the view (`args.actionId` tells
446
+ * which one);
447
+ * - `invalidate`: tells the kernel "this contribution changed", and the web pages that have it
448
+ * open fetch the view again (via the bus, across replicas); a
202
449
  * `platform.page` contribution takes no `orgId` (it refreshes the admin console), every other
203
450
  * contribution requires one;
204
- * - `verifyEmbedToken`:校验 embed 页面拿到的嵌入令牌,只认签给本插件、未过期的,且此刻插件仍在该组织启用、
205
- * 调用者仍是 active 成员,角色仍满足位置的 minRole,否则返回 null;返回的 `role` 是此刻的角色。A
451
+ * - `verifyEmbedToken`: validates the embed token an embed page received; it accepts only
452
+ * tokens signed for this plugin and not expired, while the plugin is still enabled in that org,
453
+ * the caller is still an active member and the role still satisfies the slot's minRole,
454
+ * otherwise it returns null; the returned `role` is the role at this moment. A
206
455
  * platform-scope token (`scope: "platform"`, no `orgId`) verifies only for a `platform.page`
207
456
  * contribution while the account is still an active super admin.
208
457
  */
209
458
  ui: {
210
459
  view(id: string, render: (args: UiRenderArgs) => Promise<UiView>): void;
211
460
  action(id: string, handler: (args: UiActionArgs) => Promise<UiActionResult>): void;
461
+ /**
462
+ * Registers the data source of `usePluginQuery` for a component (only during `setup`). `id`
463
+ * must be a component id declared in `permissions.ui.components`; the kernel refuses any other
464
+ * id. Queries work in any org-scoped component slot (`org.page`, conversation and agent slots
465
+ * alike). The result is JSON of at most `UI_LIMITS.componentQueryBytes` bytes and the call's
466
+ * params at most `UI_LIMITS.componentQueryParamsBytes`. Push refresh reaches queries only
467
+ * through org-stream invalidations (`invalidate({ orgId, contribution })` without a
468
+ * `conversationId`): a conversation-scoped invalidation does not refetch them, so a component
469
+ * in a conversation slot refetches through an action result's `invalidate` query names (or
470
+ * its own `refetch`).
471
+ */
472
+ query(id: string, handler: (args: UiQueryArgs) => Promise<JsonValue>): void;
212
473
  invalidate(target: {
213
474
  /** Required, except for a `platform.page` contribution, where it must be omitted. */
214
475
  orgId?: string;
@@ -217,6 +478,18 @@ export interface ExtensionContext {
217
478
  }): Promise<void>;
218
479
  verifyEmbedToken(token: string): Promise<EmbedClaims | null>;
219
480
  };
481
+ /**
482
+ * Setup checks (`permissions.setupChecks`): the live rows of the plugin's setup guides.
483
+ * `check` is only allowed during `setup`; `id` must be listed in `permissions.setupChecks`
484
+ * (else `ExtensionPermissionError`); registering an id twice throws. The kernel runs a check only
485
+ * when a person or an agent asks, only for targets of this plugin and of `def.place`, aborts
486
+ * `signal` after `SETUP_CHECK_LIMITS.timeoutMs`, and redacts and bounds the result. A check never
487
+ * writes, passes `signal` to every request, does not retry and never puts a secret in `reason`
488
+ * or `fix`. It never receives an OAuth client secret or a member's token.
489
+ */
490
+ setup: {
491
+ check(id: string, def: SetupCheckDefinition): void;
492
+ };
220
493
  /**
221
494
  * Hooks (`permissions.hooks`): observe model and tool calls, or deny them with a policy hook.
222
495
  * `on` is only allowed during `setup`; the mount point must be declared in `permissions.hooks` and be
@@ -229,16 +502,56 @@ export interface ExtensionContext {
229
502
  hooks: {
230
503
  on<K extends AvailableHook>(mount: K, handler: HookHandler<K>, opts: HookOptions): void;
231
504
  };
505
+ /**
506
+ * The dial-in channel to the machines serving this extension's devices (requires
507
+ * `permissions.dialIn`, see {@link DialInChannel}): every call is refused for a device another
508
+ * extension serves.
509
+ */
510
+ dialIn: DialInChannel;
511
+ /**
512
+ * Tells the kernel about this extension's devices (requires `provides` to include
513
+ * `device-provider@1`, see {@link DevicesCtx}).
514
+ */
515
+ devices: DevicesCtx;
516
+ /**
517
+ * The extension's services in the conversation's device (requires `permissions.deviceAccess`,
518
+ * see {@link DeviceAccessCtx}).
519
+ */
520
+ deviceAccess: DeviceAccessCtx;
521
+ /**
522
+ * Emits events automations can react to (requires `permissions.triggers`, see
523
+ * {@link TriggersCtx}).
524
+ */
525
+ triggers: TriggersCtx;
526
+ /**
527
+ * Posts personal inbox items and resolves them (requires `permissions.inbox`, see
528
+ * {@link InboxCtx}).
529
+ */
530
+ inbox: InboxCtx;
531
+ /** The agents a member may use (requires `permissions.agents`, see {@link AgentsCtx}). */
532
+ agents: AgentsCtx;
533
+ /**
534
+ * The conversations serving the extension's own subjects (requires `permissions.conversations`,
535
+ * see {@link ConversationsCtx}).
536
+ */
537
+ conversations: ConversationsCtx;
538
+ /** Names and avatars of an org's members (requires `permissions.people`, see {@link PeopleCtx}). */
539
+ people: PeopleCtx;
232
540
  provide(extensionPoint: ExtensionPointRef, impl: unknown): void;
233
541
  /**
234
- * 本插件实例的生命周期信号:实例被撤销(停用、卸载、升级)时、在途调用排空之后中止。
235
- * 插件自己起的长任务(轮询循环、长连接等)据此收尾。
542
+ * The lifecycle signal of this plugin instance: aborted when the instance is revoked (disabled,
543
+ * uninstalled, upgraded), after in-flight calls have drained.
544
+ * Long-running tasks the plugin started itself (polling loops, long connections, etc.) wind down
545
+ * on it.
236
546
  */
237
547
  signal: AbortSignal;
238
548
  /**
239
- * 部署级配置,已按插件 schema 校验(启动配置与企业管理员在后台保存的值合并后)。这是一个 getter:
240
- * 标了 `hot`(`.meta({ hot: true })`)的字段改动时内核就地替换,插件**在用时读** `ctx.config` 才能拿到新值,
241
- * 不要在 setup 里把 hot 字段拷进闭包;改了非 hot 字段时内核重新加载插件实例(新的 setup)。
549
+ * Deployment-level config, validated against the plugin schema (the startup config merged with
550
+ * values the super admin saved in the console). This is a getter:
551
+ * when a field marked `hot` (`.meta({ hot: true })`) changes, the kernel replaces it in place, so
552
+ * the plugin must read `ctx.config` **at the time of use** to get the new value;
553
+ * do not copy hot fields into a closure in setup; when a non-hot field changes the kernel reloads
554
+ * the plugin instance (a new setup).
242
555
  */
243
556
  readonly config: unknown;
244
557
  log: Logger;
package/dist/ctx.js CHANGED
@@ -1 +1,9 @@
1
- export {};
1
+ /** A {@link DeviceAccessCtx} call was refused; the message is actionable English for the model. */
2
+ export class DeviceAccessError extends Error {
3
+ code;
4
+ constructor(code, message, opts) {
5
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
6
+ this.name = "DeviceAccessError";
7
+ this.code = code;
8
+ }
9
+ }
@@ -3,16 +3,19 @@ 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
20
  /**
18
21
  * UI contributions, each in a slot of `UI_SLOTS`; every id is also listed in `permissions.ui`.
@@ -22,24 +25,27 @@ export interface ExtensionManifest {
22
25
  ui?: UiContribution[];
23
26
  config?: {
24
27
  deployment?: z.ZodTypeAny;
25
- org?: z.ZodTypeAny;
26
28
  };
27
29
  migrations?: string;
28
30
  setup(ctx: ExtensionContext): void | Promise<void>;
29
31
  /**
30
- * 可选:插件实例被撤销(停用、卸载、升级换新实例、依赖方随提供方重新加载)时调用。
31
- * 调用时内核已经:停止接新的调用、等在途调用结束(最多 `extensionHost.drainSeconds`)、中止 `ctx.signal`、
32
- * 撤销本实例经 ctx 做过的全部登记(工具、路由、队列 worker、bus 订阅、锁租约、界面、provide)。
33
- * 这里只收拾插件自己在 ctx 之外开的东西(如自建的连接);不要再经 ctx 登记任何东西。
34
- * setup 抛错时不调用(已登记的由内核撤销)。
32
+ * Optional: called when the plugin instance is revoked (disabled, uninstalled, replaced by a new
33
+ * instance on upgrade, a dependent reloaded together with its provider).
34
+ * By then the kernel has already: stopped accepting new calls, waited for in-flight calls to
35
+ * finish (at most `extensionHost.drainSeconds`), aborted `ctx.signal`,
36
+ * and revoked every registration this instance made through ctx (tools, routes, queue workers,
37
+ * bus subscriptions, lock leases, UI, provide).
38
+ * Clean up here only what the plugin opened outside ctx (e.g. its own connections); do not
39
+ * register anything through ctx again.
40
+ * Not called when setup throws (the kernel revokes what was already registered).
35
41
  */
36
42
  dispose?(ctx: ExtensionContext): void | Promise<void>;
37
43
  }
38
- /** 插件清单不合法。 */
44
+ /** The plugin manifest is invalid. */
39
45
  export declare class ExtensionManifestError extends Error {
40
46
  constructor(plugin: string, message: string);
41
47
  }
42
- /** 插件名规则(清单 `name`;连接器模板的 `plugin` 也按它校验)。 */
48
+ /** Plugin name rule (manifest `name`; a connector template's `plugin` is validated by it too). */
43
49
  export declare const EXTENSION_NAME_RE: RegExp;
44
- /** 校验并原样返回插件清单;不合法抛 ExtensionManifestError。 */
50
+ /** Validates the plugin manifest and returns it unchanged; throws ExtensionManifestError when invalid. */
45
51
  export declare function defineExtension(m: ExtensionManifest): ExtensionManifest;
@@ -1,17 +1,20 @@
1
1
  import semver from "semver";
2
2
  import { EXTENSION_POINTS, parseExtensionPoint, } from "./extension-point.js";
3
3
  import { validatePermissions, validateUiContributions, } from "./permissions.js";
4
- /** 插件清单不合法。 */
4
+ /** The plugin manifest is invalid. */
5
5
  export class ExtensionManifestError extends Error {
6
6
  constructor(plugin, message) {
7
7
  super(`extension ${plugin}: ${message}`);
8
8
  this.name = "ExtensionManifestError";
9
9
  }
10
10
  }
11
- /** 插件名规则(清单 `name`;连接器模板的 `plugin` 也按它校验)。 */
11
+ /** Plugin name rule (manifest `name`; a connector template's `plugin` is validated by it too). */
12
12
  export const EXTENSION_NAME_RE = /^[a-z][a-z0-9-]{1,40}$/;
13
13
  const NAME_RE = EXTENSION_NAME_RE;
14
- /** 保留的插件名:内核用 `kernel` 作为自己的 secrets 命名空间,插件不能与之相同。 */
14
+ /**
15
+ * Reserved plugin name: the kernel uses `kernel` as its own secrets namespace, so a plugin cannot
16
+ * take it.
17
+ */
15
18
  const RESERVED_NAMES = new Set(["kernel"]);
16
19
  function checkRefs(label, refs, fail, forbidBrokered = false) {
17
20
  for (const ref of refs) {
@@ -30,7 +33,7 @@ function checkRefs(label, refs, fail, forbidBrokered = false) {
30
33
  }
31
34
  }
32
35
  }
33
- /** 校验并原样返回插件清单;不合法抛 ExtensionManifestError。 */
36
+ /** Validates the plugin manifest and returns it unchanged; throws ExtensionManifestError when invalid. */
34
37
  export function defineExtension(m) {
35
38
  const plugin = typeof m?.name === "string" && m.name !== "" ? m.name : "<unnamed>";
36
39
  const fail = (msg) => {
@@ -73,8 +76,18 @@ export function defineExtension(m) {
73
76
  fail(`field "optional" entry "${r}" overlaps with "provides" or "requires"`);
74
77
  }
75
78
  }
79
+ if (m.config !== undefined) {
80
+ if (typeof m.config !== "object" || m.config === null || Array.isArray(m.config)) {
81
+ fail(`field "config" must be an object`);
82
+ }
83
+ for (const key of Object.keys(m.config)) {
84
+ if (key === "deployment")
85
+ continue;
86
+ fail(`config.${key} is not a config level: the only one is config.deployment`);
87
+ }
88
+ }
76
89
  if (m.permissions !== undefined) {
77
- const errs = validatePermissions(plugin, m.permissions);
90
+ const errs = validatePermissions(plugin, m.permissions, m.provides);
78
91
  if (errs.length > 0)
79
92
  fail(`invalid permissions: ${errs.join("; ")}`);
80
93
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Paths a local device never opens to restricted work (Request approval, Approve for me), relative
3
+ * to `~` (spec §13.6, extended by ruling R19): SSH keys, cloud CLI credentials, container and
4
+ * Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the macOS keychains, the
5
+ * browser profile directories, other tool credential stores (cargo, 1Password, Vault, Terraform,
6
+ * Claude, Codex, keyrings, pass, rclone, s3cmd), mise's config directory and the config files it
7
+ * loads from the home (an `[env]` section may hold tokens; globbed names like `~/mise.<env>.toml`
8
+ * are not listed), Maven and Gradle credential files, database and X11 credential files, and
9
+ * shell and REPL histories. Secrets a shell start file exports (`export TOKEN=…` in `~/.bashrc`)
10
+ * are not covered: start files stay readable so sandboxed shells behave as the owner's. One source for
11
+ * the device, which denies them (and its own state directory), and the kernel, which never proposes
12
+ * an approval for a path under one. Full access and auto mode run as the owner and do not apply
13
+ * them: the command review does.
14
+ */
15
+ export declare const DEVICE_DENIED_SECRET_PATHS: readonly string[];
16
+ /**
17
+ * The device program's default state directory (`$XDG_CONFIG_HOME/capybara-device` when that is
18
+ * set), relative to `~`: denied to restricted work like the secret paths.
19
+ */
20
+ export declare const DEVICE_DEFAULT_STATE_PATH = "~/.config/capybara-device";