@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/tool.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type ParamSchema } from "./model-params.js";
2
- /** 工具注解(与 MCP 对齐的提示,用于推导默认策略)。 */
2
+ import type { UiOpen } from "./ui.js";
3
+ /** Tool annotations (hints aligned with MCP, used to derive the default policy). */
3
4
  export interface ToolAnnotations {
4
5
  readOnlyHint?: boolean;
5
6
  destructiveHint?: boolean;
@@ -7,17 +8,47 @@ export interface ToolAnnotations {
7
8
  openWorldHint?: boolean;
8
9
  requiresUserInteraction?: boolean;
9
10
  }
11
+ /** Where a conversation comes from; a tool may limit itself to some of these. */
12
+ export declare const CONVERSATION_SOURCES: readonly ["web", "channel_dm", "channel_group", "subagent"];
13
+ /** A conversation source (see {@link CONVERSATION_SOURCES}). */
14
+ export type ConversationSource = (typeof CONVERSATION_SOURCES)[number];
15
+ /**
16
+ * How a tool's input is previewed while it streams ({@link ToolSpec.inputView}). Every name is a
17
+ * string property of the tool's `inputSchema`.
18
+ */
19
+ export type ToolInputView = {
20
+ kind: "file_write";
21
+ path: string;
22
+ content: string;
23
+ } | {
24
+ kind: "file_edit";
25
+ path: string;
26
+ old: string;
27
+ new: string;
28
+ } | {
29
+ kind: "command";
30
+ command: string;
31
+ description?: string;
32
+ } | {
33
+ kind: "text";
34
+ field: string;
35
+ };
10
36
  export interface ToolSpec {
11
37
  name: string;
12
38
  description: string;
13
39
  inputSchema: Record<string, unknown>;
14
40
  annotations?: ToolAnnotations;
15
- /** 仅插件 / 内置工具可声明;缺省按注解推导。 */
41
+ /**
42
+ * Only plugin / builtin tools may declare it; when omitted it is derived from the annotations.
43
+ */
16
44
  defaultPolicy?: "allow" | "ask";
17
45
  /**
18
- * 仅连接器工具:连接器自己的不透明数据(如 OpenAPI 的方法、路径模板、参数位置、服务器地址),可 JSON 序列化。
19
- * 内核把它与定义一起存进快照并计入指纹(变了即漂移、需复核),调用时经 `callTool` 的 `ctx.spec` 原样交回;
20
- * 绝不发给模型。
46
+ * Connector tools only: the connector's own opaque data (e.g. OpenAPI's method, path template,
47
+ * parameter locations, server address), JSON-serializable.
48
+ * The kernel stores it with the definition in the snapshot and counts it in the fingerprint (a
49
+ * change means drift and needs review), and hands it back unchanged via `ctx.spec` of `callTool`
50
+ * on a call;
51
+ * never sent to the model.
21
52
  */
22
53
  connectorData?: Record<string, unknown>;
23
54
  /**
@@ -33,7 +64,33 @@ export interface ToolSpec {
33
64
  * model and not part of the definition fingerprint.
34
65
  */
35
66
  keyArgs?: string[];
67
+ /**
68
+ * Display only: how the UI previews this tool's input while the model is still writing it. Names
69
+ * string properties of `inputSchema` that carry a file body, an edit, a command or free text.
70
+ * Never sent to the model and not part of the definition fingerprint. Nothing streamed ever
71
+ * executes: the call runs from the logged assistant message.
72
+ */
73
+ inputView?: ToolInputView;
74
+ /**
75
+ * The conversation sources this tool is offered in; absent = every source. A non-empty list of
76
+ * {@link CONVERSATION_SOURCES}.
77
+ */
78
+ sources?: ConversationSource[];
79
+ /**
80
+ * Extension tools only: the time limit of one call in milliseconds, a whole number from
81
+ * {@link TOOL_TIMEOUT_MIN_MS} to {@link TOOL_TIMEOUT_MAX_MS}. When declared, the deployment's
82
+ * `tools.timeoutMs` no longer applies to the tool; the deployment's `tools.maxTimeoutMs`
83
+ * (default {@link TOOL_TIMEOUT_MAX_MS}) cuts a longer value. Absent: `tools.timeoutMs`. Declare
84
+ * it when a call may legitimately take longer, e.g. one that first starts a device service
85
+ * (`ctx.deviceAccess.ensureService`). Never sent to the model and not part of the definition
86
+ * fingerprint.
87
+ */
88
+ timeoutMs?: number;
36
89
  }
90
+ /** Shortest {@link ToolSpec.timeoutMs}: one second. */
91
+ export declare const TOOL_TIMEOUT_MIN_MS = 1000;
92
+ /** Longest {@link ToolSpec.timeoutMs} the kernel accepts: ten minutes. */
93
+ export declare const TOOL_TIMEOUT_MAX_MS = 600000;
37
94
  /** Longest {@link ToolSpec.title}, in code points. */
38
95
  export declare const TOOL_TITLE_MAX = 80;
39
96
  /** Most {@link ToolSpec.keyArgs}. */
@@ -44,7 +101,7 @@ export declare const TOOL_KEY_ARGS_MAX = 3;
44
101
  * characters (Unicode Cc / Cf); keyArgs are at most 3 unique strings, each a property of
45
102
  * `inputSchema.properties` and free of Cc / Cf characters.
46
103
  */
47
- export declare function validateToolPresentation(spec: Pick<ToolSpec, "title" | "keyArgs" | "inputSchema">): string[];
104
+ export declare function validateToolPresentation(spec: Pick<ToolSpec, "title" | "keyArgs" | "inputView" | "inputSchema">): string[];
48
105
  export type ToolContent = {
49
106
  type: "text";
50
107
  text: string;
@@ -58,45 +115,81 @@ export type ToolContent = {
58
115
  name?: string;
59
116
  mimeType?: string;
60
117
  };
61
- /** 工具调用的一句话说明,给界面显示(中英文各 ≤ 200 字符);不进模型上下文。 */
118
+ /**
119
+ * A one-sentence description of a tool call, shown in the UI (Chinese and English each ≤ 200
120
+ * characters); does not enter the model context.
121
+ */
62
122
  export interface ToolDisplay {
63
123
  summary: {
64
124
  zh: string;
65
125
  en: string;
66
126
  };
67
127
  }
128
+ /** The most characters of `ToolResult.card.text`. */
129
+ export declare const CARD_TEXT_MAX = 2000;
130
+ /** The most characters of `ToolResult.card.badge` (as `UiView.badge`). */
131
+ export declare const CARD_BADGE_MAX = 32;
68
132
  export interface ToolResult {
69
133
  content: ToolContent[];
70
134
  isError?: boolean;
71
- /** 可选:对话流里显示这句说明,代替原样的输入 JSON。 */
135
+ /** Optional: show this description in the conversation stream in place of the raw input JSON. */
72
136
  display?: ToolDisplay;
73
137
  /**
74
138
  * Optional: an inline card under this call in the conversation: `view` is a ui contribution of
75
139
  * the same extension in the `conversation.tool-result.card` slot, rendered with
76
140
  * `card: { callId, key }`. Display only (recorded on the `tool_result` event, never in the model's
77
141
  * context); an unknown view is dropped with a warning and the result is kept.
142
+ *
143
+ * `placement` says where the card shows: `output` (default) lifted out after the run's process
144
+ * block, where the person sees it with the answer; `pinned` as the run's pinned card, kept in
145
+ * view while the run goes on (a plan or todo list; the latest pinned card per (extension, view)
146
+ * of the run wins); `process` only inside the process block, after its call.
147
+ * `text` is the card's Markdown text for surfaces that cannot draw the view (IM channels, the
148
+ * pinned card of a channel's progress card), at most {@link CARD_TEXT_MAX} characters.
149
+ * `badge` (pinned only) is the card's state in a few characters, the same as its view's
150
+ * `UiView.badge` (e.g. "3/5"), at most {@link CARD_BADGE_MAX} characters: a finished run's
151
+ * process head shows it after the view's title without reading the view again.
78
152
  */
79
153
  card?: {
80
154
  view: string;
81
155
  key?: string;
156
+ placement?: "output" | "pinned" | "process";
157
+ text?: string;
158
+ badge?: string;
82
159
  };
83
160
  }
84
- /** 校验 {@link ToolDisplay},返回问题列表(空 = 合法);长度按 Unicode 码点计。 */
161
+ /**
162
+ * Validates a {@link ToolDisplay} and returns the list of problems (empty = valid); length is
163
+ * counted in Unicode code points.
164
+ */
85
165
  export declare function validateToolDisplay(d: unknown): string[];
86
166
  /** Text shown to people: bilingual (`zh` / `en`) or a single string shown as is. */
87
167
  export type LocalizedText = {
88
168
  zh: string;
89
169
  en: string;
90
170
  } | string;
91
- /** 交互表单:字段的 schema 只用 M2 的 ParamSchema 子集;枚举字段可设 multiSelect 与 allowOther。 */
171
+ /**
172
+ * Interactive form: field schemas use only the ParamSchema subset of M2; enum fields may set
173
+ * multiSelect and allowOther.
174
+ */
92
175
  export interface InputForm {
93
- /** 插件可给双语;内核内置工具给英文(模型生成的问题原样展示)。 */
176
+ /**
177
+ * A plugin may give both languages; builtin kernel tools give English (model-generated questions
178
+ * are displayed as is).
179
+ */
94
180
  title: LocalizedText;
95
181
  /**
96
- * 可选:需要用户在浏览器里打开的外部页面(如 MCP URL 模式的 elicitation:去对方页面授权 / 付款 / 填敏感信息)。
97
- * 界面把它显示为链接(完整地址可见);只接受 http(s) 绝对地址、≤ 2000 字符。
182
+ * Optional: an external page the user must open in a browser (e.g. an MCP URL-mode elicitation:
183
+ * go to the other party's page to authorize / pay / enter sensitive information).
184
+ * The UI shows it as a link (the full address visible); only absolute http(s) addresses, ≤ 2000
185
+ * characters, are accepted.
98
186
  */
99
187
  url?: string;
188
+ /**
189
+ * Optional: longer text under the title (the reason, what to do), at most
190
+ * {@link INPUT_FORM_BODY_MAX} characters, shown as plain text. Keep the title short.
191
+ */
192
+ body?: LocalizedText;
100
193
  fields: {
101
194
  key: string;
102
195
  label: LocalizedText;
@@ -105,58 +198,179 @@ export interface InputForm {
105
198
  multiSelect?: boolean;
106
199
  allowOther?: boolean;
107
200
  required?: boolean;
201
+ /**
202
+ * Buttons in place of the field's control: one per choice, the first is the primary, and pressing one answers
203
+ * the form with its value at once (no separate Answer). Allowed only on the form's single
204
+ * field, when it is required and a single choice: a `boolean` (values `true` / `false`) or a
205
+ * string `enum` without `multiSelect` / `allowOther` (values from the enum). 1 to
206
+ * {@link INPUT_CHOICES_MAX} choices with distinct values; labels at most
207
+ * {@link INPUT_CHOICE_LABEL_MAX} characters. Example: a confirm form `{ done: boolean }` with
208
+ * `[{ value: true, label: "Done" }, { value: false, label: "Cancel" }]`, or a one-value enum
209
+ * that renders as one button ("End wait").
210
+ */
211
+ choices?: {
212
+ value: string | boolean;
213
+ label: LocalizedText;
214
+ }[];
108
215
  }[];
109
216
  }
217
+ /** The longest {@link InputForm.body}, in characters (per language). */
218
+ export declare const INPUT_FORM_BODY_MAX = 2000;
219
+ /** The most buttons a form's choices may draw. */
220
+ export declare const INPUT_CHOICES_MAX = 3;
221
+ /** The longest choice label, in characters (per language). */
222
+ export declare const INPUT_CHOICE_LABEL_MAX = 40;
110
223
  /**
111
- * 工具需要用户输入:内核暂停运行、渲染表单;用户提交后用同一 input 再次调用该工具,
112
- * 并在 ctx.resume 中带回 state 与 answer。state ≤ 16 KB,可 JSON 序列化。
224
+ * The tool needs user input: the kernel pauses the run and renders a form; after the user submits,
225
+ * the tool is called again with the same input,
226
+ * and state and answer are brought back in ctx.resume. state ≤ 16 KB, JSON-serializable.
113
227
  */
114
228
  export interface InputRequired {
115
229
  kind: "input_required";
116
230
  form: InputForm;
117
231
  state?: unknown;
232
+ /**
233
+ * Opens a `conversation.panel` of the same extension on the asking person's open conversation
234
+ * page when the form is asked (e.g. the browser panel for a handoff), as a view's `open` does
235
+ * on a click. Display only: a target that names no panel of the extension is dropped with a
236
+ * warning and the form is asked as usual.
237
+ */
238
+ open?: UiOpen;
239
+ /**
240
+ * A watched wait: besides the person's answer and the deadline, the tool's registered watcher
241
+ * ({@link ToolWatcher}, `ctx.tools.register(spec, handler, { watch })`) may settle it. The
242
+ * kernel parks the run (no model turn, no worker held) and calls the watcher every 10 s while
243
+ * the wait is pending. `deadlineMs` is a positive integer number of milliseconds (anything else
244
+ * is refused with an invalid-form result), bounded by the deployment's
245
+ * `tools.approvalTimeoutHours`; a shorter kernel deadline resumes the call with
246
+ * `outcome: "expired"`.
247
+ */
248
+ watch?: {
249
+ deadlineMs: number;
250
+ };
118
251
  }
252
+ /** How an input round ended when the handler is called again ({@link ToolCallContext.resume}). */
253
+ export type ToolResumeOutcome = "answered" | "woken" | "expired";
119
254
  export type FormAnswer = Record<string, string | number | boolean | string[]>;
255
+ /**
256
+ * What a tool handler gets with each invocation.
257
+ *
258
+ * **Side effects and idempotency.** The kernel runs a call's effect at most once: it records
259
+ * that the call started before invoking the handler, and when a run dies after that and before
260
+ * the result is recorded, the result is written as unknown (an error result the model sees:
261
+ * `Result unknown: the call was interrupted before a result was recorded. Verify the outcome
262
+ * before retrying.`) and **the handler is never called again** for that call. The model, or a
263
+ * person, may then decide to call the tool again: that is a new call with a new `callId`.
264
+ *
265
+ * One logical call may still invoke the handler more than once: each `InputRequired` round
266
+ * resumes it with `resume`, and a call whose device service reported refused hosts
267
+ * (`ctx.deviceAccess.reportBlockedHosts`) runs again, without `resume`, once the person approved
268
+ * the network ask and the hosts are in force. `callId` and `idempotencyKey` stay the same across
269
+ * those invocations. A tool with an external side effect passes `idempotencyKey` downstream (for
270
+ * example as an `Idempotency-Key` header, or stored with the record it creates) so the effect
271
+ * applies once per logical call and an unknown outcome can be checked against the external
272
+ * system before retrying.
273
+ */
120
274
  export interface ToolCallContext {
121
275
  orgId: string;
122
276
  accountId: string;
123
277
  agentId: string;
124
278
  conversationId: string;
279
+ /**
280
+ * The root of the call's conversation tree (the conversation the person looks at); equal to
281
+ * `conversationId` outside sub-agents. Set by the kernel, never from tool input.
282
+ */
283
+ rootConversationId: string;
284
+ /**
285
+ * The model's id for this call. Stable across every invocation of one logical call (the
286
+ * `InputRequired` rounds), but unique only within its run: two runs of one conversation may
287
+ * reuse an id, so `conversationId` + `callId` is not a key. Use `idempotencyKey`.
288
+ */
125
289
  callId: string;
290
+ /**
291
+ * The key of this logical call for idempotent side effects: 64 lowercase hex characters derived
292
+ * from the conversation, the run and `callId`. The same for every invocation of the call
293
+ * (each `InputRequired` round), different for every other call, including a later call the
294
+ * model makes to retry it. A re-run of the same call after its network ask was approved
295
+ * (`ctx.deviceAccess.reportBlockedHosts`) keeps the key too.
296
+ */
297
+ idempotencyKey?: string;
126
298
  signal: AbortSignal;
127
- /** null = 用户取消或超时。 */
299
+ /**
300
+ * The previous input round's state and answer. `answer` is null unless the person answered.
301
+ * `outcome`: `answered` (the person answered), `woken` (a watched wait's watcher settled it, or
302
+ * the kernel ended the watch early: the watcher failed, is gone, or the tool is no longer
303
+ * available) or `expired` (the deadline passed). A tool with its own source of truth (a watched
304
+ * condition) asks it first and uses `outcome` only for what happened otherwise.
305
+ */
128
306
  resume?: {
129
307
  state: unknown;
130
308
  answer: FormAnswer | null;
309
+ outcome: ToolResumeOutcome;
131
310
  };
132
311
  /**
133
312
  * The extension's effective deployment config for this org: the platform's deployment config
134
- * with the org's copy applied to the overridable fields (`orgAccess(…, "override")`), or the
135
- * platform's config (equal to `ctx.config`) while the org follows it. Use it, not `ctx.config`,
136
- * for work done for this org. Optional in the type so older extensions compile; the kernel
137
- * always passes it.
313
+ * with the org's copy applied to the overridable fields (every field not marked `platformOnly`),
314
+ * or the platform's config (equal to `ctx.config`) while the org follows it. Use it, not
315
+ * `ctx.config`, for work done for this org.
138
316
  */
139
317
  config?: unknown;
318
+ /** Where the conversation comes from. The kernel always passes it. */
319
+ source?: ConversationSource;
320
+ /** The conversation's owner (`conversations.account_id`). The kernel always passes it; `accountId` stays the run's trigger account. */
321
+ ownerAccountId?: string;
322
+ /** The trigger account's role in the org. The kernel always passes it. */
323
+ role?: "owner" | "admin" | "member" | "guest";
140
324
  }
141
325
  export type ToolHandler = (input: unknown, ctx: ToolCallContext) => Promise<ToolResult | InputRequired>;
142
326
  /**
143
- * 工具错误的类别:
144
- * - `error`(缺省):远端可用、但这次调用失败(参数不对、业务错误、鉴权失败等),不计入连接器熔断;
145
- * - `unavailable`:远端不可用(连接 / 传输错误、超时、HTTP 5xx),计入连接器熔断(连接器用它告诉内核)。
327
+ * What a watcher gets: the call's context as the handler got it (the same `callId`,
328
+ * `idempotencyKey`, accounts, conversations and effective config), without `resume`, plus the
329
+ * state the handler returned with its watched `InputRequired`.
330
+ */
331
+ export interface ToolWatchContext extends Omit<ToolCallContext, "resume"> {
332
+ state: unknown;
333
+ }
334
+ /**
335
+ * A watched wait's watcher (`ctx.tools.register(spec, handler, { watch })`). The kernel calls it
336
+ * every 10 s while the wait is pending, never twice at once for one wait, never after it
337
+ * settled; `settle` ends the wait (the handler is called again with `resume.outcome: "woken"`),
338
+ * `pending` keeps it. It must be cheap: the kernel aborts `ctx.signal` and stops waiting for it
339
+ * after 5 s, which counts as a failure, as a throw does; 3 consecutive failures end the wait. A
340
+ * watcher that ignores the signal keeps running after that, so a later poll may overlap it, and a
341
+ * poll already running when the wait ends (the person answered) may overlap the resumed handler:
342
+ * keep the watcher read-only and honour `ctx.signal`. Its
343
+ * `ctx.deviceAccess.request` calls run as `ifRunning` (a stopped device or service answers
344
+ * `not_running`, nothing is resumed or started), `ensureService` is refused, and
345
+ * `reportBlockedHosts` calls are dropped.
346
+ */
347
+ export type ToolWatcher = (ctx: ToolWatchContext) => Promise<"settle" | "pending">;
348
+ /**
349
+ * Tool error categories:
350
+ * - `error` (default): the remote is available but this call failed (bad parameters, business
351
+ * error, auth failure, etc.), not counted toward the connector circuit breaker;
352
+ * - `unavailable`: the remote is unavailable (connection / transport error, timeout, HTTP 5xx),
353
+ * counted toward the connector circuit breaker (connectors use it to tell the kernel).
146
354
  */
147
355
  export type ToolErrorKind = "error" | "unavailable";
148
- /** 工具执行失败:message 给模型看,须为英文且可操作。 */
356
+ /** A tool execution failure: message is for the model and must be in English and actionable. */
149
357
  export declare class ToolError extends Error {
150
358
  readonly kind: ToolErrorKind;
151
359
  constructor(message: string, opts?: {
152
360
  kind?: ToolErrorKind;
153
361
  });
154
362
  }
155
- /** 插件工具名规则。 */
363
+ /** Plugin tool name rule. */
156
364
  export declare const EXTENSION_TOOL_NAME: RegExp;
157
- /** 校验插件注册的工具声明,返回问题列表(空 = 合法)。 */
365
+ /**
366
+ * Validates the tool declarations a plugin registers and returns the list of problems (empty =
367
+ * valid).
368
+ */
158
369
  export declare function validateToolSpec(spec: ToolSpec): string[];
159
- /** 校验交互表单的声明,返回问题列表(空 = 合法)。 */
370
+ /** Validates an interactive form declaration and returns the list of problems (empty = valid). */
160
371
  export declare function validateInputForm(form: InputForm): string[];
161
- /** 校验用户提交的答案是否符合表单,返回问题列表(空 = 合法)。 */
372
+ /**
373
+ * Validates whether the answer a user submitted conforms to the form and returns the list of
374
+ * problems (empty = valid).
375
+ */
162
376
  export declare function validateAnswer(form: InputForm, answer: FormAnswer): string[];
package/dist/tool.js CHANGED
@@ -1,5 +1,25 @@
1
1
  import { checkParamValue } from "./model-params.js";
2
2
  import { isHttpUrl } from "./url.js";
3
+ /** Where a conversation comes from; a tool may limit itself to some of these. */
4
+ export const CONVERSATION_SOURCES = ["web", "channel_dm", "channel_group", "subagent"];
5
+ const INPUT_VIEW_KINDS = ["file_write", "file_edit", "command", "text"];
6
+ /** The property names a {@link ToolInputView} refers to, by kind. */
7
+ function inputViewFields(view) {
8
+ switch (view.kind) {
9
+ case "file_write":
10
+ return [view.path, view.content];
11
+ case "file_edit":
12
+ return [view.path, view.old, view.new];
13
+ case "command":
14
+ return view.description === undefined ? [view.command] : [view.command, view.description];
15
+ default:
16
+ return [view.field];
17
+ }
18
+ }
19
+ /** Shortest {@link ToolSpec.timeoutMs}: one second. */
20
+ export const TOOL_TIMEOUT_MIN_MS = 1000;
21
+ /** Longest {@link ToolSpec.timeoutMs} the kernel accepts: ten minutes. */
22
+ export const TOOL_TIMEOUT_MAX_MS = 600_000;
3
23
  /** Longest {@link ToolSpec.title}, in code points. */
4
24
  export const TOOL_TITLE_MAX = 80;
5
25
  /** Most {@link ToolSpec.keyArgs}. */
@@ -28,6 +48,11 @@ export function validateToolPresentation(spec) {
28
48
  else if (typeof title === "string" && CONTROL_OR_FORMAT.test(title)) {
29
49
  out.push("title must not contain control, bidi or invisible characters");
30
50
  }
51
+ const schema = spec.inputSchema;
52
+ const props = typeof schema?.properties === "object" && schema.properties !== null
53
+ ? schema.properties
54
+ : {};
55
+ out.push(...validateInputView(spec.inputView, props));
31
56
  const keyArgs = spec.keyArgs;
32
57
  if (keyArgs === undefined)
33
58
  return out;
@@ -41,18 +66,42 @@ export function validateToolPresentation(spec) {
41
66
  out.push("keyArgs must not repeat a name");
42
67
  if (keyArgs.some((k) => CONTROL_OR_FORMAT.test(k)))
43
68
  out.push("keyArgs names must not contain control, bidi or invisible characters");
44
- const schema = spec.inputSchema;
45
- const props = typeof schema?.properties === "object" && schema.properties !== null
46
- ? schema.properties
47
- : {};
48
69
  for (const k of keyArgs) {
49
70
  if (!Object.hasOwn(props, k))
50
71
  out.push(`keyArgs names "${k}", which is not a property of inputSchema`);
51
72
  }
52
73
  return out;
53
74
  }
75
+ function validateInputView(view, props) {
76
+ if (view === undefined)
77
+ return [];
78
+ const kinds = INPUT_VIEW_KINDS.join(", ");
79
+ const kindProblem = `inputView kind must be one of ${kinds}`;
80
+ if (typeof view !== "object" || view === null || Array.isArray(view))
81
+ return [kindProblem];
82
+ const v = view;
83
+ if (!INPUT_VIEW_KINDS.includes(v.kind))
84
+ return [kindProblem];
85
+ const out = [];
86
+ for (const name of inputViewFields(v)) {
87
+ const label = typeof name === "string" ? name : String(name);
88
+ const prop = typeof name === "string" && Object.hasOwn(props, name)
89
+ ? props[name]
90
+ : undefined;
91
+ if (typeof name !== "string" || CONTROL_OR_FORMAT.test(name) || prop?.type !== "string")
92
+ out.push(`inputView names "${label}", which is not a string property of inputSchema`);
93
+ }
94
+ return out;
95
+ }
96
+ /** The most characters of `ToolResult.card.text`. */
97
+ export const CARD_TEXT_MAX = 2000;
98
+ /** The most characters of `ToolResult.card.badge` (as `UiView.badge`). */
99
+ export const CARD_BADGE_MAX = 32;
54
100
  const DISPLAY_MAX = 200;
55
- /** 校验 {@link ToolDisplay},返回问题列表(空 = 合法);长度按 Unicode 码点计。 */
101
+ /**
102
+ * Validates a {@link ToolDisplay} and returns the list of problems (empty = valid); length is
103
+ * counted in Unicode code points.
104
+ */
56
105
  export function validateToolDisplay(d) {
57
106
  if (typeof d !== "object" || d === null || Array.isArray(d))
58
107
  return ["display must be an object"];
@@ -67,7 +116,13 @@ export function validateToolDisplay(d) {
67
116
  }
68
117
  return out;
69
118
  }
70
- /** 工具执行失败:message 给模型看,须为英文且可操作。 */
119
+ /** The longest {@link InputForm.body}, in characters (per language). */
120
+ export const INPUT_FORM_BODY_MAX = 2000;
121
+ /** The most buttons a form's choices may draw. */
122
+ export const INPUT_CHOICES_MAX = 3;
123
+ /** The longest choice label, in characters (per language). */
124
+ export const INPUT_CHOICE_LABEL_MAX = 40;
125
+ /** A tool execution failure: message is for the model and must be in English and actionable. */
71
126
  export class ToolError extends Error {
72
127
  kind;
73
128
  constructor(message, opts) {
@@ -76,9 +131,12 @@ export class ToolError extends Error {
76
131
  this.kind = opts?.kind ?? "error";
77
132
  }
78
133
  }
79
- /** 插件工具名规则。 */
134
+ /** Plugin tool name rule. */
80
135
  export const EXTENSION_TOOL_NAME = /^[a-zA-Z0-9_-]{1,40}$/;
81
- /** 校验插件注册的工具声明,返回问题列表(空 = 合法)。 */
136
+ /**
137
+ * Validates the tool declarations a plugin registers and returns the list of problems (empty =
138
+ * valid).
139
+ */
82
140
  export function validateToolSpec(spec) {
83
141
  const out = [];
84
142
  if (typeof spec?.name !== "string" || !EXTENSION_TOOL_NAME.test(spec.name))
@@ -93,6 +151,19 @@ export function validateToolSpec(spec) {
93
151
  out.push('defaultPolicy must be "allow" or "ask"');
94
152
  if (typeof spec?.inputSchema === "object" && spec.inputSchema !== null)
95
153
  out.push(...validateToolPresentation(spec));
154
+ const sources = spec?.sources;
155
+ if (sources !== undefined &&
156
+ (!Array.isArray(sources) ||
157
+ sources.length === 0 ||
158
+ sources.some((s) => !CONVERSATION_SOURCES.includes(s))))
159
+ out.push(`sources must be a non-empty list of ${CONVERSATION_SOURCES.join(", ")}`);
160
+ const timeout = spec?.timeoutMs;
161
+ if (timeout !== undefined &&
162
+ (typeof timeout !== "number" ||
163
+ !Number.isInteger(timeout) ||
164
+ timeout < TOOL_TIMEOUT_MIN_MS ||
165
+ timeout > TOOL_TIMEOUT_MAX_MS))
166
+ out.push(`timeoutMs must be a whole number of milliseconds from ${TOOL_TIMEOUT_MIN_MS} to ${TOOL_TIMEOUT_MAX_MS}`);
96
167
  return out;
97
168
  }
98
169
  const SCHEMA_KEYS = {
@@ -101,7 +172,7 @@ const SCHEMA_KEYS = {
101
172
  number: ["type", "minimum", "maximum"],
102
173
  integer: ["type", "minimum", "maximum"],
103
174
  };
104
- /** 检查 schema 是否落在 ParamSchema 子集内,返回问题列表。 */
175
+ /** Checks whether a schema falls within the ParamSchema subset and returns the list of problems. */
105
176
  function schemaProblems(schema) {
106
177
  if (typeof schema !== "object" || schema === null || Array.isArray(schema))
107
178
  return ["schema must be an object"];
@@ -130,7 +201,7 @@ function schemaProblems(schema) {
130
201
  return out;
131
202
  }
132
203
  const isEnum = (s) => s.type === "string" && "enum" in s;
133
- /** 校验交互表单的声明,返回问题列表(空 = 合法)。 */
204
+ /** Validates an interactive form declaration and returns the list of problems (empty = valid). */
134
205
  export function validateInputForm(form) {
135
206
  const out = [];
136
207
  if (!form || !Array.isArray(form.fields))
@@ -139,6 +210,8 @@ export function validateInputForm(form) {
139
210
  out.push("form must have at least one field");
140
211
  if (form.url !== undefined && !isHttpUrl(form.url))
141
212
  out.push("url must be an absolute http(s) URL of at most 2000 characters");
213
+ if (form.body !== undefined && !textWithin(form.body, INPUT_FORM_BODY_MAX))
214
+ out.push(`body must be non-empty text of at most ${INPUT_FORM_BODY_MAX} characters`);
142
215
  const seen = new Set();
143
216
  for (const f of form.fields) {
144
217
  const at = `field ${JSON.stringify(f?.key)}`;
@@ -156,10 +229,56 @@ export function validateInputForm(form) {
156
229
  continue;
157
230
  if ((f.multiSelect || f.allowOther) && !isEnum(f.schema))
158
231
  out.push(`${at}: multiSelect and allowOther require a string enum schema`);
232
+ if (f.choices !== undefined)
233
+ out.push(...choicesProblems(form, f).map((p) => `${at}: ${p}`));
234
+ }
235
+ return out;
236
+ }
237
+ /** Non-empty text (a string or both languages) of at most `max` characters per language. */
238
+ function textWithin(t, max) {
239
+ const ok = (x) => typeof x === "string" && x.trim() !== "" && x.length <= max;
240
+ if (typeof t === "string")
241
+ return ok(t);
242
+ return (typeof t === "object" &&
243
+ t !== null &&
244
+ ok(t.zh) &&
245
+ ok(t.en));
246
+ }
247
+ /** The rules of {@link InputForm} `choices` (buttons): see the field's documentation. */
248
+ function choicesProblems(form, f) {
249
+ const out = [];
250
+ const c = f.choices;
251
+ if (!Array.isArray(c) || c.length === 0 || c.length > INPUT_CHOICES_MAX)
252
+ return [`choices must be an array of 1 to ${INPUT_CHOICES_MAX} items`];
253
+ if (form.fields.length !== 1)
254
+ out.push("choices are allowed only on a form's single field");
255
+ if (f.required !== true)
256
+ out.push("choices require required: true");
257
+ const bool = f.schema.type === "boolean";
258
+ const single = isEnum(f.schema) && !f.multiSelect && !f.allowOther;
259
+ if (!bool && !single)
260
+ out.push("choices require a boolean or a single-choice string enum (no multiSelect / allowOther)");
261
+ const seen = new Set();
262
+ for (const x of c) {
263
+ const v = x?.value;
264
+ const valid = bool
265
+ ? typeof v === "boolean"
266
+ : single && typeof v === "string" && f.schema.enum.includes(v);
267
+ if (!valid)
268
+ out.push(`choice value ${JSON.stringify(v)} is not a value of the field`);
269
+ else if (seen.has(v))
270
+ out.push(`duplicate choice value ${JSON.stringify(v)}`);
271
+ else
272
+ seen.add(v);
273
+ if (!textWithin(x?.label, INPUT_CHOICE_LABEL_MAX))
274
+ out.push(`choice label must be non-empty text of at most ${INPUT_CHOICE_LABEL_MAX} characters`);
159
275
  }
160
276
  return out;
161
277
  }
162
- /** 校验用户提交的答案是否符合表单,返回问题列表(空 = 合法)。 */
278
+ /**
279
+ * Validates whether the answer a user submitted conforms to the form and returns the list of
280
+ * problems (empty = valid).
281
+ */
163
282
  export function validateAnswer(form, answer) {
164
283
  const out = [];
165
284
  const byKey = new Map(form.fields.map((f) => [f.key, f]));
@@ -168,7 +287,8 @@ export function validateAnswer(form, answer) {
168
287
  out.push(`unknown field ${JSON.stringify(k)}`);
169
288
  for (const f of form.fields) {
170
289
  const at = `field ${JSON.stringify(f.key)}`;
171
- // 只认答案自身的键:`toString` / `constructor` 等继承属性不算已回答
290
+ // Look only at the answer's own keys: inherited properties such as `toString` / `constructor`
291
+ // do not count as answered
172
292
  const v = Object.hasOwn(answer, f.key) ? answer[f.key] : undefined;
173
293
  if (v === undefined) {
174
294
  if (f.required)
@@ -209,7 +329,9 @@ export function validateAnswer(form, answer) {
209
329
  }
210
330
  return out;
211
331
  }
212
- /** allowOther 的枚举字段接受任意非空文本,其余按 schema 校验。 */
332
+ /**
333
+ * An allowOther enum field accepts any non-empty text; the rest are validated against the schema.
334
+ */
213
335
  function otherOrValue(f, v) {
214
336
  if (f.allowOther && isEnum(f.schema)) {
215
337
  return typeof v === "string" && v !== "" ? undefined : "other text must be a non-empty string";
@@ -0,0 +1,35 @@
1
+ import type { ExtensionPointRef } from "./extension-point.js";
2
+ import type { LocalizedName } from "./plugin-package.js";
3
+ import type { TriggerSubject } from "./triggers.js";
4
+ /** One fact of an event type: its value type and whether automations may filter on it. */
5
+ export interface TriggerFactDeclaration {
6
+ type: "string" | "number" | "boolean" | "string[]";
7
+ name: LocalizedName;
8
+ filterable: boolean;
9
+ }
10
+ /** One event type an extension emits, shown when an org builds an automation. */
11
+ export interface TriggerEventDeclaration {
12
+ type: string;
13
+ name: LocalizedName;
14
+ /** Directed events wake one agent (`TriggerEvent.audience`) instead of every subscriber. */
15
+ directed: boolean;
16
+ facts: Record<string, TriggerFactDeclaration>;
17
+ }
18
+ /** What a `trigger-source@1` provider implements. */
19
+ export interface TriggerSource {
20
+ events(): TriggerEventDeclaration[];
21
+ /** Of `accountIds`, the accounts that may see `subject`. */
22
+ visible(args: {
23
+ orgId: string;
24
+ accountIds: string[];
25
+ subject: TriggerSubject;
26
+ config?: unknown;
27
+ }): Promise<string[]>;
28
+ /** A link a person can open for the subject, or null. */
29
+ subjectLink?(args: {
30
+ orgId: string;
31
+ subject: TriggerSubject;
32
+ }): Promise<string | null>;
33
+ }
34
+ /** Trigger source extension point ref. */
35
+ export declare const TRIGGER_SOURCE_EXTENSION_POINT: ExtensionPointRef;
@@ -0,0 +1,2 @@
1
+ /** Trigger source extension point ref. */
2
+ export const TRIGGER_SOURCE_EXTENSION_POINT = "trigger-source@1";