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

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 (123) 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.d.ts +319 -0
  46. package/dist/device-protocol.js +559 -0
  47. package/dist/extension-point.d.ts +2 -0
  48. package/dist/extension-point.js +5 -2
  49. package/dist/file-preview.d.ts +1 -1
  50. package/dist/git-hosts.d.ts +44 -0
  51. package/dist/git-hosts.js +81 -0
  52. package/dist/hooks.d.ts +111 -21
  53. package/dist/hooks.js +5 -0
  54. package/dist/http-access.d.ts +52 -0
  55. package/dist/http-access.js +12 -0
  56. package/dist/identity.d.ts +22 -9
  57. package/dist/index.d.ts +21 -1
  58. package/dist/index.js +21 -1
  59. package/dist/marketplace.d.ts +26 -0
  60. package/dist/marketplace.js +43 -1
  61. package/dist/model-params.d.ts +41 -22
  62. package/dist/model-params.js +28 -15
  63. package/dist/model.d.ts +180 -71
  64. package/dist/model.js +71 -19
  65. package/dist/net.d.ts +52 -0
  66. package/dist/net.js +34 -0
  67. package/dist/permissions.d.ts +42 -20
  68. package/dist/permissions.js +97 -40
  69. package/dist/plugin-manifest.d.ts +45 -5
  70. package/dist/plugin-manifest.js +169 -6
  71. package/dist/plugin-package.d.ts +82 -38
  72. package/dist/plugin-package.js +61 -29
  73. package/dist/sandbox-linux-runtime-source.d.ts +15 -0
  74. package/dist/sandbox-linux-runtime-source.js +1421 -0
  75. package/dist/sandbox-native-runtime-source.d.ts +8 -0
  76. package/dist/sandbox-native-runtime-source.js +307 -0
  77. package/dist/sandbox-operation.d.ts +248 -0
  78. package/dist/sandbox-operation.js +245 -0
  79. package/dist/sandbox-runtime-source.d.ts +19 -0
  80. package/dist/sandbox-runtime-source.js +28 -0
  81. package/dist/sandbox.d.ts +201 -16
  82. package/dist/sandbox.js +89 -14
  83. package/dist/secret.d.ts +4 -1
  84. package/dist/secret.js +4 -1
  85. package/dist/setup-check.d.ts +115 -0
  86. package/dist/setup-check.js +142 -0
  87. package/dist/setup-guide-parse.d.ts +121 -0
  88. package/dist/setup-guide-parse.js +350 -0
  89. package/dist/setup-guide-render.d.ts +45 -0
  90. package/dist/setup-guide-render.js +351 -0
  91. package/dist/setup-guide.d.ts +94 -0
  92. package/dist/setup-guide.js +336 -0
  93. package/dist/skill-invocation.d.ts +4 -3
  94. package/dist/skill-invocation.js +5 -4
  95. package/dist/skill.d.ts +34 -21
  96. package/dist/skill.js +48 -31
  97. package/dist/storage.d.ts +52 -25
  98. package/dist/theme-assets.d.ts +39 -0
  99. package/dist/theme-assets.js +449 -0
  100. package/dist/theme-readability.d.ts +37 -0
  101. package/dist/theme-readability.js +145 -0
  102. package/dist/theme-tokens.generated.d.ts +279 -0
  103. package/dist/theme-tokens.generated.js +174 -0
  104. package/dist/theme.d.ts +152 -0
  105. package/dist/theme.js +392 -0
  106. package/dist/tool.d.ts +69 -26
  107. package/dist/tool.js +29 -9
  108. package/dist/ui-parts.d.ts +23 -0
  109. package/dist/ui-parts.js +337 -0
  110. package/dist/ui-resolve.d.ts +35 -0
  111. package/dist/ui-resolve.js +42 -0
  112. package/dist/ui-slots.d.ts +53 -0
  113. package/dist/ui-slots.js +238 -0
  114. package/dist/ui.d.ts +191 -79
  115. package/dist/ui.js +101 -27
  116. package/dist/url.d.ts +4 -1
  117. package/dist/url.js +4 -1
  118. package/package.json +7 -1
  119. package/schemas/bootstrap.v1.schema.json +6 -0
  120. package/schemas/connector-template.v1.schema.json +35 -0
  121. package/schemas/marketplace.v1.schema.json +14 -0
  122. package/schemas/plugin.v1.schema.json +115 -3
  123. package/schemas/theme.v1.schema.json +225 -0
package/dist/ctx.d.ts CHANGED
@@ -1,24 +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 { RouteCaller } from "./http-access.js";
5
+ import type { ModelEmbeddingInfo, ModelKind } from "./model.js";
6
+ import type { ExtensionNet } from "./net.js";
7
+ import type { SetupCheckDefinition } from "./setup-check.js";
4
8
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
5
9
  import type { ToolHandler, ToolSpec } from "./tool.js";
6
10
  import type { EmbedClaims, UiActionArgs, UiActionResult, UiRenderArgs, UiView } from "./ui.js";
7
- /** 日志接口。 */
11
+ /** Logger interface. */
8
12
  export interface Logger {
9
13
  info(msg: string, fields?: Record<string, unknown>): void;
10
14
  warn(msg: string, fields?: Record<string, unknown>): void;
11
15
  error(msg: string, fields?: Record<string, unknown>): void;
12
16
  }
13
- /** 分布式锁租约。 */
17
+ /** Distributed lock lease. */
14
18
  export interface Lease {
15
19
  renew(): Promise<boolean>;
16
20
  release(): Promise<void>;
17
21
  }
18
22
  /**
19
- * 插件的对象存储(`ctx.storage`,需 `permissions.storage`):与 `ObjectStore` 同形,但每个方法的第一个参数是
20
- * `orgId`,键与前缀由内核自动加上 `plugins/<插件名>/<orgId>/`——插件只能看到自己在该组织下的对象。
21
- * 底层是部署配置的 `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.
22
29
  */
23
30
  export interface ExtensionStorage {
24
31
  put(orgId: string, key: string, body: Uint8Array | ReadableStream<Uint8Array>, opts: {
@@ -27,8 +34,10 @@ export interface ExtensionStorage {
27
34
  signal?: AbortSignal;
28
35
  }): Promise<ObjectHead>;
29
36
  /**
30
- * 不存在返回 null。`range` 为闭区间字节范围,缺省 `end` 表示读到末尾。
31
- * 带 `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.
32
41
  */
33
42
  get(orgId: string, key: string, opts?: {
34
43
  signal?: AbortSignal;
@@ -41,7 +50,7 @@ export interface ExtensionStorage {
41
50
  body: ReadableStream<Uint8Array>;
42
51
  } | null>;
43
52
  head(orgId: string, key: string): Promise<ObjectHead | null>;
44
- /** 不存在也算成功。 */
53
+ /** A missing key also counts as success. */
45
54
  delete(orgId: string, key: string): Promise<void>;
46
55
  deletePrefix(orgId: string, prefix: string): Promise<number>;
47
56
  list(orgId: string, prefix: string, opts?: {
@@ -58,7 +67,69 @@ export interface ExtensionStorage {
58
67
  ttlSeconds: number;
59
68
  }): Promise<PresignedUpload>;
60
69
  }
61
- /** 传给插件 `setup` 的上下文。不提供定时器与进程内共享状态;kv 写入必须带 TTL。 */
70
+ /** A `ctx.models.embed` request: texts embedded for one org with the model mapped to a purpose. */
71
+ export interface ExtensionEmbedRequest {
72
+ orgId: string;
73
+ /** A purpose this extension declared in `permissions.models` with `kind: "embedding"`. */
74
+ purpose: string;
75
+ /** The texts, one vector each; split into batches by the model's `maxBatch` by the kernel. */
76
+ input: string[];
77
+ /** One of the model's `embedding.dimensions`; the model's default when absent. */
78
+ dimensions?: number;
79
+ inputType?: "query" | "document";
80
+ /**
81
+ * Aborts this call (e.g. the tool call's `signal`); combined with `ctx.signal`. Batches not yet
82
+ * sent are not sent; batches already answered are still recorded as usage.
83
+ */
84
+ signal?: AbortSignal;
85
+ }
86
+ /** A `ctx.models.embed` result. */
87
+ export interface ExtensionEmbedResult {
88
+ /** One vector per input, in input order. */
89
+ vectors: number[][];
90
+ /** The model that made them (a changed model invalidates stored vectors). */
91
+ model: {
92
+ provider: string;
93
+ id: string;
94
+ };
95
+ dimensions: number;
96
+ }
97
+ /** The model a purpose maps to in an org (`ctx.models.describe`). */
98
+ export interface ExtensionModelTarget {
99
+ provider: string;
100
+ id: string;
101
+ kind: ModelKind;
102
+ /** Present for an embedding model. */
103
+ embedding?: ModelEmbeddingInfo;
104
+ }
105
+ /**
106
+ * Models by purpose (`permissions.models`): the purpose → model mapping is chosen by org admins
107
+ * (and the deployment default by the super admin), never by the extension. Only purposes this
108
+ * extension declared with `kind: "embedding"` are accepted (`model.purpose_unknown` otherwise), and
109
+ * only for an org that enabled the extension (`extension.not_enabled`). Usage is recorded by the
110
+ * kernel and reported through `usage.report` (purpose `embedding`).
111
+ */
112
+ export interface ExtensionModels {
113
+ /**
114
+ * Embeds `input` with the org's effective model for `purpose`. Rejects with `model.unconfigured`
115
+ * when the purpose maps to no model the org can use, `validation_failed` for dimensions the model
116
+ * lacks, and a `ModelError` when the provider fails (a result of the wrong count or dimension is a
117
+ * `ModelError` of kind `server`). Not retried by the kernel. Each call fires the `model.request`
118
+ * hook first (`purpose: "embedding"`, every text of the call): when a policy hook denies it, the
119
+ * call rejects with an error whose `code` is `model.hook_denied` (HTTP 403 if it escapes an
120
+ * extension route), and nothing is sent or billed.
121
+ */
122
+ embed(req: ExtensionEmbedRequest): Promise<ExtensionEmbedResult>;
123
+ /** The org's effective model for `purpose`, or null when it maps to no model the org can use. */
124
+ describe(req: {
125
+ orgId: string;
126
+ purpose: string;
127
+ }): Promise<ExtensionModelTarget | null>;
128
+ }
129
+ /**
130
+ * The context passed to a plugin's `setup`. It provides no timers or in-process shared state; kv
131
+ * writes must carry a TTL.
132
+ */
62
133
  export interface ExtensionContext {
63
134
  kv: {
64
135
  get(key: string): Promise<string | null>;
@@ -92,16 +163,27 @@ export interface ExtensionContext {
92
163
  get(orgId: string, key: string): Promise<string | null>;
93
164
  set(orgId: string, key: string, value: string): Promise<void>;
94
165
  };
95
- /** 对象存储(需 `permissions.storage`,见 {@link ExtensionStorage})。 */
166
+ /** Object storage (needs `permissions.storage`, see {@link ExtensionStorage}). */
96
167
  storage: ExtensionStorage;
97
- /** 已切到本插件 schema(withSchema)的 Kysely 实例。 */
168
+ /** Models by purpose (requires `permissions.models`, see {@link ExtensionModels}). */
169
+ models: ExtensionModels;
170
+ /**
171
+ * Guarded HTTP for URLs a person supplied (see {@link ExtensionNet}): a connector endpoint or an
172
+ * org-overridable base URL goes through `ctx.net.fetch`, never the global `fetch`.
173
+ */
174
+ net: ExtensionNet;
175
+ /** A Kysely instance already switched to this plugin's schema (withSchema). */
98
176
  db: Kysely<any>;
99
177
  http: {
100
- /** 实际挂载到 `/plugins/<name><path>`。 */
101
- route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request) => Promise<Response>): void;
178
+ /**
179
+ * Mounted at `/plugins/<name><path>` (`public`, `embed`) or `/plugins/<name>/orgs/:orgId<path>`
180
+ * (`member`, `admin`), as `permissions.http` declares. The kernel enforces the access before
181
+ * the handler runs and passes the resolved caller; trust only `caller`.
182
+ */
183
+ route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request, caller: RouteCaller) => Promise<Response>): void;
102
184
  };
103
185
  tools: {
104
- /** 注册一个工具;只能在 `setup` 期间调用,名称不可重复。 */
186
+ /** Registers a tool; callable only during `setup`, names must not repeat. */
105
187
  register(spec: ToolSpec, handler: ToolHandler): void;
106
188
  };
107
189
  /**
@@ -133,23 +215,45 @@ export interface ExtensionContext {
133
215
  }[]>;
134
216
  };
135
217
  /**
136
- * 界面贡献的运行时(清单 `ui` + `permissions.ui`):
137
- * - `view` / `action`:只能在 `setup` 期间注册,id 是清单里 kind view 的贡献 id;
138
- * `action` 收到视图里按钮或表单提交(`args.actionId` 区分是哪一个);
139
- * - `invalidate`:告诉内核「这个贡献变了」,打开着它的网页会重新取视图(经 bus,跨副本);
140
- * - `verifyEmbedToken`:校验 embed 页面拿到的嵌入令牌,只认签给本插件、未过期的,且此刻插件仍在该组织启用、
141
- * 调用者仍是 active 成员(组织页面还要求 member 以上),否则返回 null;返回的 `role` 是此刻的角色。
218
+ * Runtime of UI contributions (manifest `ui` + `permissions.ui`):
219
+ * - `view` / `action`: can be registered only during `setup`; the id is the contribution id of
220
+ * the kind-view entry in the manifest;
221
+ * `action` receives a button click or form submission from the view (`args.actionId` tells
222
+ * which one);
223
+ * - `invalidate`: tells the kernel "this contribution changed", and the web pages that have it
224
+ * open fetch the view again (via the bus, across replicas); a
225
+ * `platform.page` contribution takes no `orgId` (it refreshes the admin console), every other
226
+ * contribution requires one;
227
+ * - `verifyEmbedToken`: validates the embed token an embed page received; it accepts only
228
+ * tokens signed for this plugin and not expired, while the plugin is still enabled in that org,
229
+ * the caller is still an active member and the role still satisfies the slot's minRole,
230
+ * otherwise it returns null; the returned `role` is the role at this moment. A
231
+ * platform-scope token (`scope: "platform"`, no `orgId`) verifies only for a `platform.page`
232
+ * contribution while the account is still an active super admin.
142
233
  */
143
234
  ui: {
144
235
  view(id: string, render: (args: UiRenderArgs) => Promise<UiView>): void;
145
236
  action(id: string, handler: (args: UiActionArgs) => Promise<UiActionResult>): void;
146
237
  invalidate(target: {
147
- orgId: string;
238
+ /** Required, except for a `platform.page` contribution, where it must be omitted. */
239
+ orgId?: string;
148
240
  conversationId?: string;
149
241
  contribution: string;
150
242
  }): Promise<void>;
151
243
  verifyEmbedToken(token: string): Promise<EmbedClaims | null>;
152
244
  };
245
+ /**
246
+ * Setup checks (`permissions.setupChecks`): the live rows of the plugin's setup guides.
247
+ * `check` is only allowed during `setup`; `id` must be listed in `permissions.setupChecks`
248
+ * (else `ExtensionPermissionError`); registering an id twice throws. The kernel runs a check only
249
+ * when a person or an agent asks, only for targets of this plugin and of `def.place`, aborts
250
+ * `signal` after `SETUP_CHECK_LIMITS.timeoutMs`, and redacts and bounds the result. A check never
251
+ * writes, passes `signal` to every request, does not retry and never puts a secret in `reason`
252
+ * or `fix`. It never receives an OAuth client secret or a member's token.
253
+ */
254
+ setup: {
255
+ check(id: string, def: SetupCheckDefinition): void;
256
+ };
153
257
  /**
154
258
  * Hooks (`permissions.hooks`): observe model and tool calls, or deny them with a policy hook.
155
259
  * `on` is only allowed during `setup`; the mount point must be declared in `permissions.hooks` and be
@@ -164,14 +268,19 @@ export interface ExtensionContext {
164
268
  };
165
269
  provide(extensionPoint: ExtensionPointRef, impl: unknown): void;
166
270
  /**
167
- * 本插件实例的生命周期信号:实例被撤销(停用、卸载、升级)时、在途调用排空之后中止。
168
- * 插件自己起的长任务(轮询循环、长连接等)据此收尾。
271
+ * The lifecycle signal of this plugin instance: aborted when the instance is revoked (disabled,
272
+ * uninstalled, upgraded), after in-flight calls have drained.
273
+ * Long-running tasks the plugin started itself (polling loops, long connections, etc.) wind down
274
+ * on it.
169
275
  */
170
276
  signal: AbortSignal;
171
277
  /**
172
- * 部署级配置,已按插件 schema 校验(启动配置与企业管理员在后台保存的值合并后)。这是一个 getter:
173
- * 标了 `hot`(`.meta({ hot: true })`)的字段改动时内核就地替换,插件**在用时读** `ctx.config` 才能拿到新值,
174
- * 不要在 setup 里把 hot 字段拷进闭包;改了非 hot 字段时内核重新加载插件实例(新的 setup)。
278
+ * Deployment-level config, validated against the plugin schema (the startup config merged with
279
+ * values the super admin saved in the console). This is a getter:
280
+ * when a field marked `hot` (`.meta({ hot: true })`) changes, the kernel replaces it in place, so
281
+ * the plugin must read `ctx.config` **at the time of use** to get the new value;
282
+ * do not copy hot fields into a closure in setup; when a non-hot field changes the kernel reloads
283
+ * the plugin instance (a new setup).
175
284
  */
176
285
  readonly config: unknown;
177
286
  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;
@@ -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,10 @@ function checkRefs(label, refs, fail, forbidBrokered = false) {
30
33
  }
31
34
  }
32
35
  }
33
- /** 校验并原样返回插件清单;不合法抛 ExtensionManifestError。 */
36
+ /**
37
+ * Validates the plugin manifest and returns it unchanged; throws ExtensionManifestError when
38
+ * invalid.
39
+ */
34
40
  export function defineExtension(m) {
35
41
  const plugin = typeof m?.name === "string" && m.name !== "" ? m.name : "<unnamed>";
36
42
  const fail = (msg) => {
@@ -78,6 +84,7 @@ export function defineExtension(m) {
78
84
  if (errs.length > 0)
79
85
  fail(`invalid permissions: ${errs.join("; ")}`);
80
86
  }
87
+ // structural ui problems only; slot resolution never fails the extension (UI slots spec §3.2)
81
88
  const uiErrs = validateUiContributions(m.ui, m.permissions);
82
89
  if (uiErrs.length > 0)
83
90
  fail(`invalid ui: ${uiErrs.join("; ")}`);
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Device protocol v2: the WebSocket frames between the kernel and a `capybara-device` program
3
+ * (a connected machine that serves as a device). Pure types and hand-written guards.
4
+ */
5
+ import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./sandbox.js";
6
+ /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
7
+ export declare const DEVICE_PROTOCOL_VERSION = 2;
8
+ /** The operations the kernel asks a device to run. */
9
+ export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "policy" | "policyStatus" | "list" | "scan";
10
+ /**
11
+ * Optional capabilities a device announces in its hello. `policyOp`: the device takes the `policy`
12
+ * op; `policyOpId`: it also logs each `policy` op's outcome by its `opId`, answers `policyStatus`
13
+ * and reports recent outcomes in its hello (`recentOps`); `networkReport` means exec results may
14
+ * carry `network`; `mode` means the device applies `limits.mode` / `limits.network` (without it
15
+ * the device behaves as an allowlisted sandbox); `projects` means the device serves `list` and
16
+ * `scan` (the kernel keeps a device's projects itself and asks the device only what it can read).
17
+ * The kernel gates each op on its feature, as it gates `policy` on `policyOp` / `policyOpId`: it
18
+ * never sends `list` or `scan` to a device that did not announce `projects`.
19
+ */
20
+ export type DeviceFeature = "networkReport" | "policyOp" | "policyOpId" | "mode" | "projects";
21
+ /** The most entries a `list` op may ask for and its result may carry. */
22
+ export declare const MAX_DEVICE_LIST_ENTRIES = 1000;
23
+ /** What a device knows of its local policy and reports (in the hello or a `policy` op). */
24
+ export interface DeviceLocalPolicySummary {
25
+ /** `auto` = no OS sandbox (the owner's machine); `sandbox` = the OS sandbox. */
26
+ mode: "auto" | "sandbox";
27
+ /** The device's sandbox-mode allowlist; meaningful in sandbox mode only. */
28
+ allowedDomains: string[];
29
+ }
30
+ /**
31
+ * A directory a `scan` found that looks like a project (it holds `.git` or `AGENTS.md`): a
32
+ * suggestion, not a project. `path` is absolute ({@link validateSandboxPathShape});
33
+ * `suggestedName` is a guess from its basename ({@link isDeviceProjectName}) the owner may change.
34
+ */
35
+ export interface DeviceProjectCandidate {
36
+ path: string;
37
+ suggestedName: string;
38
+ }
39
+ /**
40
+ * The kernel's current ceiling on a request that reads the device's file system outside a command
41
+ * (`readFile`, `stat`, `list`, `scan`): the device answers in the mode it would run this request in, the owner's
42
+ * choice cut to `mode`, never by a ceiling it saw on an earlier command.
43
+ */
44
+ export type DeviceRequestCeiling = Pick<SandboxLimits, "mode">;
45
+ /**
46
+ * The first line of the kernel's background task launch command (`Bash` `run_in_background`), a
47
+ * shell comment. A device kills what a foreground exec leaves running once the exec ends; an exec
48
+ * whose command starts with this line detaches a task on purpose, and its processes are left alone.
49
+ */
50
+ export declare const BACKGROUND_LAUNCH_LINE = "# capybara: background task launch";
51
+ /** Whether an exec's command is a background task launch ({@link BACKGROUND_LAUNCH_LINE}). */
52
+ export declare function isBackgroundLaunch(command: string): boolean;
53
+ /** The most blocked hosts an exec result reports; the parser cuts longer lists. */
54
+ export declare const MAX_NETWORK_BLOCKED_HOSTS = 20;
55
+ /** The longest `opId` a `policy` / `policyStatus` op may carry. */
56
+ export declare const MAX_POLICY_OP_ID_LENGTH = 128;
57
+ /** The most entries a hello's `recentOps` carries; the parser keeps the newest. */
58
+ export declare const MAX_RECENT_POLICY_OPS = 100;
59
+ /**
60
+ * What a device recorded of a `policy` op: `started` (written before the change, so an op the
61
+ * device was stopped in the middle of stays `started`), then `applied` or `refused`.
62
+ */
63
+ export type DevicePolicyOpOutcome = "applied" | "refused" | "started";
64
+ /** One entry of a hello's `recentOps`. */
65
+ export interface DevicePolicyOpReport {
66
+ opId: string;
67
+ outcome: DevicePolicyOpOutcome;
68
+ }
69
+ /** First frame from the device after the WebSocket opens. */
70
+ export interface DeviceHello {
71
+ type: "hello";
72
+ protocol: number;
73
+ programVersion: string;
74
+ os: "darwin" | "linux";
75
+ arch: string;
76
+ mode: "os" | "docker";
77
+ roots: SandboxRoots;
78
+ sessionIsolation: boolean;
79
+ /** Optional capabilities (absent on older devices; unknown entries are dropped by the parser). */
80
+ features?: DeviceFeature[];
81
+ /** The device's local policy at connect time (absent on older devices). */
82
+ policy?: DeviceLocalPolicySummary;
83
+ /**
84
+ * The outcomes of the latest `policy` ops by op id, oldest first, at most
85
+ * {@link MAX_RECENT_POLICY_OPS} (devices with `policyOpId`; malformed entries are dropped by
86
+ * the parser).
87
+ */
88
+ recentOps?: DevicePolicyOpReport[];
89
+ /**
90
+ * The owner's home directory, an absolute path (a local device; the base of an auto-mode
91
+ * project's relative path). A malformed value is dropped by the parser.
92
+ */
93
+ home?: string;
94
+ }
95
+ /** Error kinds a device reports for a failed request. */
96
+ export type DeviceErrorKind = "gone" | "fs_gone" | "policy" | "error";
97
+ /** The device's answer to a {@link KernelReq}. */
98
+ export type DeviceRes = {
99
+ type: "res";
100
+ id: string;
101
+ ok: true;
102
+ result: unknown;
103
+ } | {
104
+ type: "res";
105
+ id: string;
106
+ ok: false;
107
+ error: {
108
+ kind: DeviceErrorKind;
109
+ message: string;
110
+ };
111
+ };
112
+ /** A request from the kernel. */
113
+ export interface KernelReq {
114
+ type: "req";
115
+ id: string;
116
+ op: DeviceOp;
117
+ args: unknown;
118
+ deadlineMs: number;
119
+ }
120
+ /** The kernel gives up on a request (abort or deadline). */
121
+ export interface KernelCancel {
122
+ type: "cancel";
123
+ id: string;
124
+ }
125
+ /**
126
+ * The device's local policy changed while connected (its file was edited on the machine, the owner
127
+ * switched mode): the summary as it is now, sent only when it differs from the last one sent on
128
+ * this connection. `policy` is absent when the frame's summary was unreadable; the kernel then
129
+ * learns the policy later, as for the hello.
130
+ */
131
+ export interface DevicePolicyChanged {
132
+ type: "policy";
133
+ policy?: DeviceLocalPolicySummary;
134
+ }
135
+ export type DeviceFrame = DeviceHello | DeviceRes | DevicePolicyChanged | KernelReq | KernelCancel;
136
+ export interface DeviceExecArgs {
137
+ command: string;
138
+ cwd?: string;
139
+ env?: Record<string, string>;
140
+ timeoutMs: number;
141
+ maxOutputBytes: number;
142
+ tag: string;
143
+ actor: SandboxActor;
144
+ limits: SandboxLimits;
145
+ /**
146
+ * Hosts the kernel allows for this command beyond the local policy (a run's "Allow this time" or
147
+ * a
148
+ * scheduled task's grants). A device applies them only in sandbox mode, within `limits`; a
149
+ * device without the feature ignores the field.
150
+ */
151
+ grants?: DeviceExecGrants;
152
+ }
153
+ /** Extra hosts for one exec and where they come from (logged by the device with the command). */
154
+ export interface DeviceExecGrants {
155
+ hosts: string[];
156
+ source: {
157
+ kind: "run" | "task";
158
+ id: string;
159
+ accountId: string;
160
+ };
161
+ }
162
+ export type DeviceExecResult = ExecResult;
163
+ export interface DeviceReadFileArgs {
164
+ path: string;
165
+ limits: DeviceRequestCeiling;
166
+ maxBytes: number;
167
+ }
168
+ export type DeviceReadFileResult = {
169
+ dataB64: string;
170
+ truncated: boolean;
171
+ } | null;
172
+ export interface DeviceWriteFileArgs {
173
+ path: string;
174
+ dataB64: string;
175
+ }
176
+ export type DeviceWriteFileResult = null;
177
+ export interface DeviceStatArgs {
178
+ path: string;
179
+ limits: DeviceRequestCeiling;
180
+ }
181
+ export type DeviceStatResult = {
182
+ size: number;
183
+ isDir: boolean;
184
+ } | null;
185
+ export interface DeviceKillTaggedArgs {
186
+ tags: string[];
187
+ }
188
+ export type DeviceKillAllArgs = Record<string, never>;
189
+ export interface DeviceCreateArgs {
190
+ limits: SandboxLimits;
191
+ }
192
+ export interface DeviceCreateResult {
193
+ roots: SandboxRoots;
194
+ }
195
+ export interface DeviceStopArgs {
196
+ reason: "revoked" | "deleted";
197
+ }
198
+ /**
199
+ * Edits the device's local policy. The kernel may only narrow: `mode` may turn the sandbox back on
200
+ * (`"sandbox"`), never off (turning auto mode on is decided on the machine), and `add` extends the
201
+ * sandbox-mode allowlist only. Narrowing is always accepted.
202
+ */
203
+ export interface DevicePolicyArgs {
204
+ /**
205
+ * The kernel's id of this change (non-empty, no `:`, at most {@link MAX_POLICY_OP_ID_LENGTH}
206
+ * characters): the device logs the op's outcome under it, for `policyStatus` and the hello's
207
+ * `recentOps`.
208
+ */
209
+ opId: string;
210
+ /** Hosts to add to `allowedDomains`. */
211
+ add?: string[];
212
+ /** Hosts to remove from `allowedDomains`. */
213
+ remove?: string[];
214
+ /** Only `"sandbox"`: the kernel may narrow, never turn auto mode on. */
215
+ mode?: "sandbox";
216
+ /** Who decided, for the device's local audit line. */
217
+ source: {
218
+ approvalId?: string;
219
+ accountId: string;
220
+ accountName: string;
221
+ via: "web" | "im";
222
+ };
223
+ }
224
+ /** The policy as the device wrote it. */
225
+ export interface DevicePolicyResult {
226
+ policy: DeviceLocalPolicySummary;
227
+ }
228
+ /** Asks what became of the `policy` op with this id. Read-only on the device. */
229
+ export interface DevicePolicyStatusArgs {
230
+ opId: string;
231
+ }
232
+ /**
233
+ * What the device logged of a `policy` op: its {@link DevicePolicyOpOutcome}, or `unknown` when
234
+ * the id is not in its log (never received, or dropped from the log since). `policy` is the
235
+ * device's summary now; `message` the refusal's.
236
+ */
237
+ export interface DevicePolicyStatus {
238
+ outcome: DevicePolicyOpOutcome | "unknown";
239
+ policy?: DeviceLocalPolicySummary;
240
+ message?: string;
241
+ }
242
+ /**
243
+ * Lists one directory (absolute `path`, {@link validateSandboxPathShape}): at most `limit` entries
244
+ * (at most {@link MAX_DEVICE_LIST_ENTRIES}), read in the mode `limits` gives. See
245
+ * `SandboxProvider.list` for the semantics.
246
+ */
247
+ export interface DeviceListArgs {
248
+ path: string;
249
+ limit: number;
250
+ limits: DeviceRequestCeiling;
251
+ }
252
+ /**
253
+ * One entry of a listed directory: `name` is never empty, `.` or `..` and holds no `/`. `isDir`
254
+ * follows symbolic links (stat semantics): a link to a directory is `true`, a dangling link `false`,
255
+ * and so is a link whose target the request's mode cannot reach.
256
+ */
257
+ export interface DeviceListEntry {
258
+ name: string;
259
+ isDir: boolean;
260
+ }
261
+ /**
262
+ * The directory's entries sorted by code unit, `truncated` when more than `limit` exist; null only
263
+ * when the path does not exist and the request's mode could reach it (like `stat` / `readFile`).
264
+ * A file, an unreadable directory, or a path the request's mode cannot reach is an error (the
265
+ * latter a `policy` refusal), never null.
266
+ */
267
+ export type DeviceListResult = {
268
+ entries: DeviceListEntry[];
269
+ truncated: boolean;
270
+ } | null;
271
+ /**
272
+ * Looks for project-like directories under `base` (absolute, {@link validateSandboxPathShape}),
273
+ * read in the mode `limits` gives. A `base` that does not exist answers `[]`; a `base` that is a
274
+ * file, unreadable, or outside the request's mode is an error. See `SandboxProvider.scan` for the
275
+ * traversal.
276
+ */
277
+ export interface DeviceScanArgs {
278
+ base: string;
279
+ limits: DeviceRequestCeiling;
280
+ }
281
+ /**
282
+ * `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH} levels below it that
283
+ * hold a `.git` entry or an `AGENTS.md` file, sorted by `path` in code-unit order and cut to the
284
+ * first {@link MAX_DEVICE_SCAN_RESULTS}. Never file contents. See `SandboxProvider.scan`.
285
+ */
286
+ export type DeviceScanResult = DeviceProjectCandidate[];
287
+ /** A frame that is not valid device protocol (or came from the wrong side). */
288
+ export declare class DeviceProtocolError extends Error {
289
+ constructor(message: string);
290
+ }
291
+ /**
292
+ * Whether `v` is a valid policy op id: non-empty, no `:`, at most
293
+ * {@link MAX_POLICY_OP_ID_LENGTH} characters.
294
+ */
295
+ export declare function isPolicyOpId(v: unknown): v is string;
296
+ /** Result type per op. */
297
+ export interface DeviceOpResults {
298
+ create: DeviceCreateResult;
299
+ exec: DeviceExecResult;
300
+ readFile: DeviceReadFileResult;
301
+ writeFile: DeviceWriteFileResult;
302
+ stat: DeviceStatResult;
303
+ killTagged: null;
304
+ killAll: null;
305
+ stop: null;
306
+ policy: DevicePolicyResult;
307
+ policyStatus: DevicePolicyStatus;
308
+ list: DeviceListResult;
309
+ scan: DeviceScanResult;
310
+ }
311
+ /** Validates the `result` of a successful `res` for `op`; throws {@link DeviceProtocolError}. */
312
+ export declare function parseOpResult<Op extends DeviceOp>(op: Op, result: unknown): DeviceOpResults[Op];
313
+ /**
314
+ * Parses one WebSocket text frame. `from` is the sender: a device may send `hello`, `res` and
315
+ * `policy`, the
316
+ * kernel `req` and `cancel`. Throws {@link DeviceProtocolError} on bad JSON, an unknown `type`,
317
+ * missing fields or a frame of the wrong direction.
318
+ */
319
+ export declare function parseDeviceFrame(raw: string, from: "device" | "kernel"): DeviceFrame;