@capybara-hq/plugin-sdk 0.1.0-rc.8 → 0.1.0-rc.80

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 (149) hide show
  1. package/README.md +1 -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 +3 -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/extensions.md +77 -4
  14. package/agent-docs/plugin-format.md +45 -10
  15. package/agent-docs/setup.md +54 -0
  16. package/dist/agent-template.d.ts +15 -6
  17. package/dist/agent-template.js +32 -13
  18. package/dist/avatar-presets.d.ts +8 -0
  19. package/dist/avatar-presets.js +17 -0
  20. package/dist/bootstrap.d.ts +109 -1
  21. package/dist/bootstrap.js +185 -2
  22. package/dist/cards.d.ts +60 -13
  23. package/dist/cards.js +88 -18
  24. package/dist/channel.d.ts +128 -47
  25. package/dist/channel.js +10 -5
  26. package/dist/client-css.d.ts +36 -0
  27. package/dist/client-css.js +326 -0
  28. package/dist/client-section.d.ts +35 -0
  29. package/dist/client-section.js +133 -0
  30. package/dist/config-ui.d.ts +28 -6
  31. package/dist/config-ui.js +88 -25
  32. package/dist/config-url-fetch.d.ts +19 -0
  33. package/dist/config-url-fetch.js +43 -0
  34. package/dist/connector-auth.d.ts +13 -2
  35. package/dist/connector-auth.js +82 -8
  36. package/dist/connector.d.ts +74 -32
  37. package/dist/context.d.ts +40 -0
  38. package/dist/context.js +2 -0
  39. package/dist/ctx.d.ts +224 -30
  40. package/dist/ctx.js +9 -1
  41. package/dist/define-extension.d.ts +23 -13
  42. package/dist/define-extension.js +19 -5
  43. package/dist/device-denied-paths.d.ts +20 -0
  44. package/dist/device-denied-paths.js +118 -0
  45. package/dist/device-operation.d.ts +339 -0
  46. package/dist/device-operation.js +312 -0
  47. package/dist/device-protocol.d.ts +285 -50
  48. package/dist/device-protocol.js +755 -90
  49. package/dist/device-provider.d.ts +780 -0
  50. package/dist/device-provider.js +409 -0
  51. package/dist/device-service.d.ts +126 -0
  52. package/dist/device-service.js +211 -0
  53. package/dist/dial-in.d.ts +286 -0
  54. package/dist/dial-in.js +213 -0
  55. package/dist/directory.d.ts +15 -12
  56. package/dist/extension-point.d.ts +2 -0
  57. package/dist/extension-point.js +7 -3
  58. package/dist/field-meta.d.ts +19 -0
  59. package/dist/field-meta.js +54 -0
  60. package/dist/file-preview.d.ts +43 -10
  61. package/dist/git-hosts.d.ts +53 -0
  62. package/dist/git-hosts.js +98 -0
  63. package/dist/hooks.d.ts +125 -20
  64. package/dist/hooks.js +5 -0
  65. package/dist/http-access.d.ts +71 -0
  66. package/dist/http-access.js +12 -0
  67. package/dist/identity.d.ts +70 -9
  68. package/dist/identity.js +46 -1
  69. package/dist/index.d.ts +28 -4
  70. package/dist/index.js +28 -4
  71. package/dist/model-params.d.ts +41 -22
  72. package/dist/model-params.js +28 -15
  73. package/dist/model.d.ts +210 -75
  74. package/dist/model.js +152 -19
  75. package/dist/native-failure.d.ts +13 -0
  76. package/dist/native-failure.js +31 -0
  77. package/dist/net.d.ts +52 -0
  78. package/dist/net.js +34 -0
  79. package/dist/network-classes.d.ts +98 -0
  80. package/dist/network-classes.js +291 -0
  81. package/dist/permissions.d.ts +65 -22
  82. package/dist/permissions.js +139 -43
  83. package/dist/platform-only.d.ts +27 -0
  84. package/dist/platform-only.js +35 -0
  85. package/dist/plugin-manifest.d.ts +30 -6
  86. package/dist/plugin-manifest.js +147 -55
  87. package/dist/plugin-package.d.ts +82 -39
  88. package/dist/plugin-package.js +68 -41
  89. package/dist/push.d.ts +75 -0
  90. package/dist/push.js +87 -0
  91. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  92. package/dist/sandbox-linux-runtime-source.js +2343 -0
  93. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  94. package/dist/sandbox-native-runtime-source.js +480 -0
  95. package/dist/sandbox-runtime-source.d.ts +47 -0
  96. package/dist/sandbox-runtime-source.js +73 -0
  97. package/dist/sandbox-write-denies.d.ts +139 -0
  98. package/dist/sandbox-write-denies.js +869 -0
  99. package/dist/secret.d.ts +8 -2
  100. package/dist/secret.js +11 -4
  101. package/dist/setup-check.d.ts +128 -0
  102. package/dist/setup-check.js +142 -0
  103. package/dist/setup-guide-parse.d.ts +121 -0
  104. package/dist/setup-guide-parse.js +356 -0
  105. package/dist/setup-guide-render.d.ts +45 -0
  106. package/dist/setup-guide-render.js +351 -0
  107. package/dist/setup-guide.d.ts +86 -72
  108. package/dist/setup-guide.js +340 -108
  109. package/dist/shell-capabilities.d.ts +211 -0
  110. package/dist/shell-capabilities.js +44 -0
  111. package/dist/shell-environment.d.ts +57 -0
  112. package/dist/shell-environment.js +21 -0
  113. package/dist/skill-invocation.d.ts +5 -0
  114. package/dist/skill-invocation.js +4 -3
  115. package/dist/skill.d.ts +27 -17
  116. package/dist/skill.js +40 -26
  117. package/dist/storage.d.ts +52 -25
  118. package/dist/svg-viewbox.d.ts +10 -0
  119. package/dist/svg-viewbox.js +24 -0
  120. package/dist/theme-assets.d.ts +25 -9
  121. package/dist/theme-assets.js +87 -47
  122. package/dist/theme-tokens.generated.d.ts +26 -2
  123. package/dist/theme-tokens.generated.js +17 -0
  124. package/dist/theme.d.ts +48 -10
  125. package/dist/theme.js +100 -21
  126. package/dist/tool.d.ts +156 -30
  127. package/dist/tool.js +91 -9
  128. package/dist/ui-parts.d.ts +23 -0
  129. package/dist/ui-parts.js +385 -0
  130. package/dist/ui-resolve.d.ts +35 -0
  131. package/dist/ui-resolve.js +42 -0
  132. package/dist/ui-slots.d.ts +65 -0
  133. package/dist/ui-slots.js +261 -0
  134. package/dist/ui.d.ts +245 -77
  135. package/dist/ui.js +104 -27
  136. package/dist/url.d.ts +4 -1
  137. package/dist/url.js +4 -1
  138. package/dist/web.d.ts +26 -20
  139. package/package.json +12 -1
  140. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  141. package/schemas/bootstrap.v1.schema.json +20 -0
  142. package/schemas/connector-template.v1.schema.json +62 -4
  143. package/schemas/plugin.v1.schema.json +74 -143
  144. package/schemas/theme.v1.schema.json +77 -0
  145. package/agent-docs/extension-points/sandbox.md +0 -15
  146. package/dist/org-access.d.ts +0 -27
  147. package/dist/org-access.js +0 -35
  148. package/dist/sandbox.d.ts +0 -254
  149. package/dist/sandbox.js +0 -153
package/dist/theme.js CHANGED
@@ -1,21 +1,23 @@
1
1
  import { z } from "zod";
2
+ import { BUILTIN_AVATAR_PRESET_IDS } from "./avatar-presets.js";
2
3
  import { CATALOG_ITEM_NAME_RE, isSafePackagePath } from "./plugin-package.js";
3
4
  import { checkThemeReadability } from "./theme-readability.js";
4
5
  import { THEME_OVERRIDABLE, THEME_TOKENS } from "./theme-tokens.generated.js";
5
6
  /**
6
7
  * A theme file `themes/<id>.json` (themes spec §4): a partial override of the design tokens per
7
- * scheme, optional fonts and an optional logo. The id is the file's base name
8
+ * scheme, optional fonts, an optional logo and the brand fields (theme brand coverage spec §1:
9
+ * illustration, app icons, decoration, avatar presets). The id is the file's base name
8
10
  * ({@link themeIdOf}, `CATALOG_ITEM_NAME_RE`).
9
11
  *
10
12
  * {@link parseThemeFile} is the CSS-injection boundary: every token value is parsed against the
11
13
  * grammar `tokens.json` uses (`#RRGGBB`, `rgba(r,g,b,a)`, shadows `<x> <y> <blur> [<spread>]
12
14
  * <color>`) and re-rendered from its parts in canonical form. Asset paths (`fonts[].file`,
13
- * `logo.*`) are relative to the plugin root (an optional leading `./`) and every segment is limited
14
- * to `[A-Za-z0-9._-]`, so they need no escaping inside `url(...)`. Font families are limited to
15
- * letters, digits, spaces and `-`. Free text (`name`, `description`, `logo.wordmark`) carries no
16
- * control, format, line / paragraph separator or lone surrogate characters; it is text for the UI,
17
- * never CSS. Whether the files exist and their size / signature / SVG rules are checked by
18
- * the reader of the package, with {@link THEME_LIMITS}.
15
+ * `logo.*`, `avatars[].file`) are relative to the plugin root (an optional leading `./`) and every
16
+ * segment is limited to `[A-Za-z0-9._-]`, so they need no escaping inside `url(...)`. Font
17
+ * families are limited to letters, digits, spaces and `-`. Free text (`name`, `description`,
18
+ * `logo.wordmark`, `avatars[].name`) carries no control, format, line / paragraph separator or
19
+ * lone surrogate characters; it is text for the UI, never CSS. Whether the files exist and their
20
+ * size / signature / SVG rules are checked by the reader of the package, with {@link THEME_LIMITS}.
19
21
  *
20
22
  * The committed JSON Schema (`schemas/theme.v1.schema.json`) is generated from
21
23
  * {@link ThemeFileSchema} (the shape only) by `pnpm gen:package-schemas`; token names, value
@@ -27,7 +29,7 @@ export const THEME_LIMITS = {
27
29
  fileBytes: 64 * 1024,
28
30
  /** Themes per plugin. */
29
31
  perPlugin: 10,
30
- /** Total bytes of a plugin's theme assets (fonts and logos). */
32
+ /** Total bytes of a plugin's theme assets (fonts, logos, app icons and avatars). */
31
33
  assetsBytes: 16 * 1024 * 1024,
32
34
  /** Fonts per theme. */
33
35
  fonts: 8,
@@ -39,10 +41,21 @@ export const THEME_LIMITS = {
39
41
  pngBytes: 256 * 1024,
40
42
  /** Minimum pixel height of a logo PNG. */
41
43
  pngMinHeight: 64,
42
- /** Characters of the wordmark. */
44
+ /** Characters of the wordmark (and of each avatar preset name). */
43
45
  wordmark: 24,
46
+ /** Avatar presets per theme. */
47
+ avatars: 12,
48
+ /** Bytes of an app icon PNG. */
49
+ appIconBytes: 1_048_576,
50
+ /** Minimum pixel size of an app icon PNG (square). */
51
+ appIconMinSize: 512,
44
52
  };
45
- /** `themes/night-city.json` → `night-city`. */
53
+ /** The id of a theme's avatar preset (`avatars[].id`); never a built-in preset id. */
54
+ export const THEME_AVATAR_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
55
+ /** The sign-in page background decoration (the dither columns) a theme asks for; omitted means
56
+ * `dither`. */
57
+ export const THEME_DECORATIONS = ["dither", "none"];
58
+ /** `themes/neon-grid.json` → `neon-grid`. */
46
59
  export function themeIdOf(path) {
47
60
  return (path.split("/").pop() ?? "").replace(/\.json$/, "");
48
61
  }
@@ -53,6 +66,8 @@ const FORBIDDEN_CHARS_RE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u;
53
66
  const PATH_SEGMENT_RE = /^[A-Za-z0-9._-]+$/;
54
67
  const FORBIDDEN_CHARS_MESSAGE = "must not contain control, format, line / paragraph separator or lone surrogate characters";
55
68
  const IMAGE_RE = /\.(?:svg|png)$/i;
69
+ const PNG_RE = /\.png$/i;
70
+ const BUILTIN_AVATARS = new Set(BUILTIN_AVATAR_PRESET_IDS);
56
71
  const MAX_VALUE_CHARS = 256;
57
72
  const text = (max, what) => z
58
73
  .string()
@@ -60,6 +75,14 @@ const text = (max, what) => z
60
75
  .max(max)
61
76
  .regex(/\S/, { message: `${what} must not be blank` })
62
77
  .refine((t) => !FORBIDDEN_CHARS_RE.test(t), { message: `${what} ${FORBIDDEN_CHARS_MESSAGE}` });
78
+ /** Short free text (the wordmark, avatar names): not blank, ≤ 24 characters, no forbidden ones. */
79
+ const shortText = (what) => z
80
+ .string()
81
+ .regex(/\S/, { message: `${what} must not be blank` })
82
+ .refine((w) => [...w].length <= THEME_LIMITS.wordmark, {
83
+ message: `${what} must be at most ${THEME_LIMITS.wordmark} characters`,
84
+ })
85
+ .refine((w) => !FORBIDDEN_CHARS_RE.test(w), { message: `${what} ${FORBIDDEN_CHARS_MESSAGE}` });
63
86
  /** A plugin-root relative path (optional `./`), each segment `[A-Za-z0-9._-]`, no `.` / `..`. */
64
87
  const isPlainAssetPath = (p) => {
65
88
  const rest = p.replace(/^\.\//, "");
@@ -81,7 +104,15 @@ const schemeOverride = z.strictObject({
81
104
  .strictObject({ sm: radius.optional(), md: radius.optional(), bubble: radius.optional() })
82
105
  .optional(),
83
106
  });
84
- const shape = z.strictObject({
107
+ const avatarPreset = z.strictObject({
108
+ id: z.string().regex(THEME_AVATAR_ID_RE, {
109
+ message: "id must match ^[a-z0-9][a-z0-9-]{0,31}$",
110
+ }),
111
+ name: z.strictObject({ en: shortText("name.en"), zh: shortText("name.zh").optional() }),
112
+ file: assetPath("file", IMAGE_RE, ".svg or .png"),
113
+ });
114
+ const shape = z
115
+ .strictObject({
85
116
  $schema: z.string().max(512).optional(),
86
117
  name: z.strictObject({ zh: text(100, "name.zh"), en: text(100, "name.en") }),
87
118
  description: z
@@ -110,19 +141,67 @@ const shape = z.strictObject({
110
141
  logo: z
111
142
  .strictObject({
112
143
  mark: assetPath("mark", IMAGE_RE, ".svg or .png").optional(),
113
- wordmark: z
114
- .string()
115
- .regex(/\S/, { message: "wordmark must not be blank" })
116
- .refine((w) => [...w].length <= THEME_LIMITS.wordmark, {
117
- message: `wordmark must be at most ${THEME_LIMITS.wordmark} characters`,
118
- })
119
- .refine((w) => !FORBIDDEN_CHARS_RE.test(w), {
120
- message: `wordmark ${FORBIDDEN_CHARS_MESSAGE}`,
121
- })
122
- .optional(),
144
+ wordmark: shortText("wordmark").optional(),
123
145
  favicon: assetPath("favicon", IMAGE_RE, ".svg or .png").optional(),
146
+ illustration: assetPath("illustration", IMAGE_RE, ".svg or .png").optional(),
147
+ appIcon: assetPath("appIcon", PNG_RE, ".png").optional(),
148
+ appIconMaskable: assetPath("appIconMaskable", PNG_RE, ".png").optional(),
149
+ })
150
+ .superRefine((l, ctx) => {
151
+ if (l.appIconMaskable !== undefined && l.appIcon === undefined) {
152
+ ctx.addIssue({
153
+ code: "custom",
154
+ path: ["appIconMaskable"],
155
+ message: "appIconMaskable requires appIcon",
156
+ });
157
+ }
158
+ })
159
+ .optional(),
160
+ decoration: z.enum(THEME_DECORATIONS).optional(),
161
+ avatars: z
162
+ .array(avatarPreset)
163
+ .max(THEME_LIMITS.avatars)
164
+ .superRefine((list, ctx) => {
165
+ const seen = new Set();
166
+ list.forEach((a, i) => {
167
+ if (BUILTIN_AVATARS.has(a.id)) {
168
+ ctx.addIssue({
169
+ code: "custom",
170
+ path: [i, "id"],
171
+ message: `id must not be a built-in avatar preset id (${a.id})`,
172
+ });
173
+ }
174
+ else if (seen.has(a.id)) {
175
+ ctx.addIssue({
176
+ code: "custom",
177
+ path: [i, "id"],
178
+ message: `duplicate avatar id ${a.id}`,
179
+ });
180
+ }
181
+ seen.add(a.id);
182
+ });
124
183
  })
125
184
  .optional(),
185
+ hideAvatarPresets: z
186
+ .array(z.enum(BUILTIN_AVATAR_PRESET_IDS))
187
+ .superRefine((list, ctx) => {
188
+ list.forEach((id, i) => {
189
+ if (list.indexOf(id) !== i) {
190
+ ctx.addIssue({ code: "custom", path: [i], message: `duplicate hidden preset ${id}` });
191
+ }
192
+ });
193
+ })
194
+ .optional(),
195
+ })
196
+ .superRefine((t, ctx) => {
197
+ const hidden = new Set(t.hideAvatarPresets ?? []);
198
+ if (hidden.size === BUILTIN_AVATAR_PRESET_IDS.length && (t.avatars?.length ?? 0) === 0) {
199
+ ctx.addIssue({
200
+ code: "custom",
201
+ path: ["hideAvatarPresets"],
202
+ message: "hiding every built-in avatar preset requires at least one entry in avatars",
203
+ });
204
+ }
126
205
  });
127
206
  /**
128
207
  * The zod schema of a theme file's shape (strict objects). Token names and values are only
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,26 @@ 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];
10
15
  export interface ToolSpec {
11
16
  name: string;
12
17
  description: string;
13
18
  inputSchema: Record<string, unknown>;
14
19
  annotations?: ToolAnnotations;
15
- /** 仅插件 / 内置工具可声明;缺省按注解推导。 */
20
+ /**
21
+ * Only plugin / builtin tools may declare it; when omitted it is derived from the annotations.
22
+ */
16
23
  defaultPolicy?: "allow" | "ask";
17
24
  /**
18
- * 仅连接器工具:连接器自己的不透明数据(如 OpenAPI 的方法、路径模板、参数位置、服务器地址),可 JSON 序列化。
19
- * 内核把它与定义一起存进快照并计入指纹(变了即漂移、需复核),调用时经 `callTool` 的 `ctx.spec` 原样交回;
20
- * 绝不发给模型。
25
+ * Connector tools only: the connector's own opaque data (e.g. OpenAPI's method, path template,
26
+ * parameter locations, server address), JSON-serializable.
27
+ * The kernel stores it with the definition in the snapshot and counts it in the fingerprint (a
28
+ * change means drift and needs review), and hands it back unchanged via `ctx.spec` of `callTool`
29
+ * on a call;
30
+ * never sent to the model.
21
31
  */
22
32
  connectorData?: Record<string, unknown>;
23
33
  /**
@@ -33,7 +43,26 @@ export interface ToolSpec {
33
43
  * model and not part of the definition fingerprint.
34
44
  */
35
45
  keyArgs?: string[];
46
+ /**
47
+ * The conversation sources this tool is offered in; absent = every source. A non-empty list of
48
+ * {@link CONVERSATION_SOURCES}.
49
+ */
50
+ sources?: ConversationSource[];
51
+ /**
52
+ * Extension tools only: the time limit of one call in milliseconds, a whole number from
53
+ * {@link TOOL_TIMEOUT_MIN_MS} to {@link TOOL_TIMEOUT_MAX_MS}. When declared, the deployment's
54
+ * `tools.timeoutMs` no longer applies to the tool; the deployment's `tools.maxTimeoutMs`
55
+ * (default {@link TOOL_TIMEOUT_MAX_MS}) cuts a longer value. Absent: `tools.timeoutMs`. Declare
56
+ * it when a call may legitimately take longer, e.g. one that first starts a device service
57
+ * (`ctx.deviceAccess.ensureService`). Never sent to the model and not part of the definition
58
+ * fingerprint.
59
+ */
60
+ timeoutMs?: number;
36
61
  }
62
+ /** Shortest {@link ToolSpec.timeoutMs}: one second. */
63
+ export declare const TOOL_TIMEOUT_MIN_MS = 1000;
64
+ /** Longest {@link ToolSpec.timeoutMs} the kernel accepts: ten minutes. */
65
+ export declare const TOOL_TIMEOUT_MAX_MS = 600000;
37
66
  /** Longest {@link ToolSpec.title}, in code points. */
38
67
  export declare const TOOL_TITLE_MAX = 80;
39
68
  /** Most {@link ToolSpec.keyArgs}. */
@@ -58,7 +87,10 @@ export type ToolContent = {
58
87
  name?: string;
59
88
  mimeType?: string;
60
89
  };
61
- /** 工具调用的一句话说明,给界面显示(中英文各 ≤ 200 字符);不进模型上下文。 */
90
+ /**
91
+ * A one-sentence description of a tool call, shown in the UI (Chinese and English each ≤ 200
92
+ * characters); does not enter the model context.
93
+ */
62
94
  export interface ToolDisplay {
63
95
  summary: {
64
96
  zh: string;
@@ -68,35 +100,51 @@ export interface ToolDisplay {
68
100
  export interface ToolResult {
69
101
  content: ToolContent[];
70
102
  isError?: boolean;
71
- /** 可选:对话流里显示这句说明,代替原样的输入 JSON。 */
103
+ /** Optional: show this description in the conversation stream in place of the raw input JSON. */
72
104
  display?: ToolDisplay;
73
105
  /**
74
106
  * Optional: an inline card under this call in the conversation: `view` is a ui contribution of
75
- * the same extension with `place: "inline"`, rendered with `card: { callId, key }`. Display only
76
- * (recorded on the `tool_result` event, never in the model's context); an unknown view is dropped
77
- * with a warning and the result is kept.
107
+ * the same extension in the `conversation.tool-result.card` slot, rendered with
108
+ * `card: { callId, key }`. Display only (recorded on the `tool_result` event, never in the model's
109
+ * context); an unknown view is dropped with a warning and the result is kept.
78
110
  */
79
111
  card?: {
80
112
  view: string;
81
113
  key?: string;
82
114
  };
83
115
  }
84
- /** 校验 {@link ToolDisplay},返回问题列表(空 = 合法);长度按 Unicode 码点计。 */
116
+ /**
117
+ * Validates a {@link ToolDisplay} and returns the list of problems (empty = valid); length is
118
+ * counted in Unicode code points.
119
+ */
85
120
  export declare function validateToolDisplay(d: unknown): string[];
86
121
  /** Text shown to people: bilingual (`zh` / `en`) or a single string shown as is. */
87
122
  export type LocalizedText = {
88
123
  zh: string;
89
124
  en: string;
90
125
  } | string;
91
- /** 交互表单:字段的 schema 只用 M2 的 ParamSchema 子集;枚举字段可设 multiSelect 与 allowOther。 */
126
+ /**
127
+ * Interactive form: field schemas use only the ParamSchema subset of M2; enum fields may set
128
+ * multiSelect and allowOther.
129
+ */
92
130
  export interface InputForm {
93
- /** 插件可给双语;内核内置工具给英文(模型生成的问题原样展示)。 */
131
+ /**
132
+ * A plugin may give both languages; builtin kernel tools give English (model-generated questions
133
+ * are displayed as is).
134
+ */
94
135
  title: LocalizedText;
95
136
  /**
96
- * 可选:需要用户在浏览器里打开的外部页面(如 MCP URL 模式的 elicitation:去对方页面授权 / 付款 / 填敏感信息)。
97
- * 界面把它显示为链接(完整地址可见);只接受 http(s) 绝对地址、≤ 2000 字符。
137
+ * Optional: an external page the user must open in a browser (e.g. an MCP URL-mode elicitation:
138
+ * go to the other party's page to authorize / pay / enter sensitive information).
139
+ * The UI shows it as a link (the full address visible); only absolute http(s) addresses, ≤ 2000
140
+ * characters, are accepted.
98
141
  */
99
142
  url?: string;
143
+ /**
144
+ * Optional: longer text under the title (the reason, what to do), at most
145
+ * {@link INPUT_FORM_BODY_MAX} characters, shown as plain text. Keep the title short.
146
+ */
147
+ body?: LocalizedText;
100
148
  fields: {
101
149
  key: string;
102
150
  label: LocalizedText;
@@ -105,58 +153,136 @@ export interface InputForm {
105
153
  multiSelect?: boolean;
106
154
  allowOther?: boolean;
107
155
  required?: boolean;
156
+ /**
157
+ * Buttons in place of the field's control: one per choice, the first is the primary, and pressing one answers
158
+ * the form with its value at once (no separate Answer). Allowed only on the form's single
159
+ * field, when it is required and a single choice: a `boolean` (values `true` / `false`) or a
160
+ * string `enum` without `multiSelect` / `allowOther` (values from the enum). 1 to
161
+ * {@link INPUT_CHOICES_MAX} choices with distinct values; labels at most
162
+ * {@link INPUT_CHOICE_LABEL_MAX} characters. Example: a confirm form `{ done: boolean }` with
163
+ * `[{ value: true, label: "Done" }, { value: false, label: "Cancel" }]`, or a one-value enum
164
+ * that renders as one button ("End wait").
165
+ */
166
+ choices?: {
167
+ value: string | boolean;
168
+ label: LocalizedText;
169
+ }[];
108
170
  }[];
109
171
  }
172
+ /** The longest {@link InputForm.body}, in characters (per language). */
173
+ export declare const INPUT_FORM_BODY_MAX = 2000;
174
+ /** The most buttons a form's choices may draw. */
175
+ export declare const INPUT_CHOICES_MAX = 3;
176
+ /** The longest choice label, in characters (per language). */
177
+ export declare const INPUT_CHOICE_LABEL_MAX = 40;
110
178
  /**
111
- * 工具需要用户输入:内核暂停运行、渲染表单;用户提交后用同一 input 再次调用该工具,
112
- * 并在 ctx.resume 中带回 state 与 answer。state ≤ 16 KB,可 JSON 序列化。
179
+ * The tool needs user input: the kernel pauses the run and renders a form; after the user submits,
180
+ * the tool is called again with the same input,
181
+ * and state and answer are brought back in ctx.resume. state ≤ 16 KB, JSON-serializable.
113
182
  */
114
183
  export interface InputRequired {
115
184
  kind: "input_required";
116
185
  form: InputForm;
117
186
  state?: unknown;
187
+ /**
188
+ * Opens a `conversation.panel` of the same extension on the asking person's open conversation
189
+ * page when the form is asked (e.g. the browser panel for a handoff), as a view's `open` does
190
+ * on a click. Display only: a target that names no panel of the extension is dropped with a
191
+ * warning and the form is asked as usual.
192
+ */
193
+ open?: UiOpen;
118
194
  }
119
195
  export type FormAnswer = Record<string, string | number | boolean | string[]>;
196
+ /**
197
+ * What a tool handler gets with each invocation.
198
+ *
199
+ * **Side effects and idempotency.** The kernel runs a call's effect at most once: it records
200
+ * that the call started before invoking the handler, and when a run dies after that and before
201
+ * the result is recorded, the result is written as unknown (an error result the model sees:
202
+ * `Result unknown: the call was interrupted before a result was recorded. Verify the outcome
203
+ * before retrying.`) and **the handler is never called again** for that call. The model, or a
204
+ * person, may then decide to call the tool again: that is a new call with a new `callId`.
205
+ *
206
+ * One logical call may still invoke the handler more than once: each `InputRequired` round
207
+ * resumes it with `resume`, and a call whose device service reported refused hosts
208
+ * (`ctx.deviceAccess.reportBlockedHosts`) runs again, without `resume`, once the person approved
209
+ * the network ask and the hosts are in force. `callId` and `idempotencyKey` stay the same across
210
+ * those invocations. A tool with an external side effect passes `idempotencyKey` downstream (for
211
+ * example as an `Idempotency-Key` header, or stored with the record it creates) so the effect
212
+ * applies once per logical call and an unknown outcome can be checked against the external
213
+ * system before retrying.
214
+ */
120
215
  export interface ToolCallContext {
121
216
  orgId: string;
122
217
  accountId: string;
123
218
  agentId: string;
124
219
  conversationId: string;
220
+ /**
221
+ * The root of the call's conversation tree (the conversation the person looks at); equal to
222
+ * `conversationId` outside sub-agents. Set by the kernel, never from tool input.
223
+ */
224
+ rootConversationId: string;
225
+ /**
226
+ * The model's id for this call. Stable across every invocation of one logical call (the
227
+ * `InputRequired` rounds), but unique only within its run: two runs of one conversation may
228
+ * reuse an id, so `conversationId` + `callId` is not a key. Use `idempotencyKey`.
229
+ */
125
230
  callId: string;
231
+ /**
232
+ * The key of this logical call for idempotent side effects: 64 lowercase hex characters derived
233
+ * from the conversation, the run and `callId`. The same for every invocation of the call
234
+ * (each `InputRequired` round), different for every other call, including a later call the
235
+ * model makes to retry it. A re-run of the same call after its network ask was approved
236
+ * (`ctx.deviceAccess.reportBlockedHosts`) keeps the key too.
237
+ */
238
+ idempotencyKey?: string;
126
239
  signal: AbortSignal;
127
- /** null = 用户取消或超时。 */
240
+ /** null = the user cancelled or it timed out. */
128
241
  resume?: {
129
242
  state: unknown;
130
243
  answer: FormAnswer | null;
131
244
  };
132
245
  /**
133
246
  * 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.
247
+ * with the org's copy applied to the overridable fields (every field not marked `platformOnly`),
248
+ * or the platform's config (equal to `ctx.config`) while the org follows it. Use it, not
249
+ * `ctx.config`, for work done for this org.
138
250
  */
139
251
  config?: unknown;
252
+ /** Where the conversation comes from. The kernel always passes it. */
253
+ source?: ConversationSource;
254
+ /** The conversation's owner (`conversations.account_id`). The kernel always passes it; `accountId` stays the run's trigger account. */
255
+ ownerAccountId?: string;
256
+ /** The trigger account's role in the org. The kernel always passes it. */
257
+ role?: "owner" | "admin" | "member" | "guest";
140
258
  }
141
259
  export type ToolHandler = (input: unknown, ctx: ToolCallContext) => Promise<ToolResult | InputRequired>;
142
260
  /**
143
- * 工具错误的类别:
144
- * - `error`(缺省):远端可用、但这次调用失败(参数不对、业务错误、鉴权失败等),不计入连接器熔断;
145
- * - `unavailable`:远端不可用(连接 / 传输错误、超时、HTTP 5xx),计入连接器熔断(连接器用它告诉内核)。
261
+ * Tool error categories:
262
+ * - `error` (default): the remote is available but this call failed (bad parameters, business
263
+ * error, auth failure, etc.), not counted toward the connector circuit breaker;
264
+ * - `unavailable`: the remote is unavailable (connection / transport error, timeout, HTTP 5xx),
265
+ * counted toward the connector circuit breaker (connectors use it to tell the kernel).
146
266
  */
147
267
  export type ToolErrorKind = "error" | "unavailable";
148
- /** 工具执行失败:message 给模型看,须为英文且可操作。 */
268
+ /** A tool execution failure: message is for the model and must be in English and actionable. */
149
269
  export declare class ToolError extends Error {
150
270
  readonly kind: ToolErrorKind;
151
271
  constructor(message: string, opts?: {
152
272
  kind?: ToolErrorKind;
153
273
  });
154
274
  }
155
- /** 插件工具名规则。 */
275
+ /** Plugin tool name rule. */
156
276
  export declare const EXTENSION_TOOL_NAME: RegExp;
157
- /** 校验插件注册的工具声明,返回问题列表(空 = 合法)。 */
277
+ /**
278
+ * Validates the tool declarations a plugin registers and returns the list of problems (empty =
279
+ * valid).
280
+ */
158
281
  export declare function validateToolSpec(spec: ToolSpec): string[];
159
- /** 校验交互表单的声明,返回问题列表(空 = 合法)。 */
282
+ /** Validates an interactive form declaration and returns the list of problems (empty = valid). */
160
283
  export declare function validateInputForm(form: InputForm): string[];
161
- /** 校验用户提交的答案是否符合表单,返回问题列表(空 = 合法)。 */
284
+ /**
285
+ * Validates whether the answer a user submitted conforms to the form and returns the list of
286
+ * problems (empty = valid).
287
+ */
162
288
  export declare function validateAnswer(form: InputForm, answer: FormAnswer): string[];
package/dist/tool.js CHANGED
@@ -1,5 +1,11 @@
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
+ /** Shortest {@link ToolSpec.timeoutMs}: one second. */
6
+ export const TOOL_TIMEOUT_MIN_MS = 1000;
7
+ /** Longest {@link ToolSpec.timeoutMs} the kernel accepts: ten minutes. */
8
+ export const TOOL_TIMEOUT_MAX_MS = 600_000;
3
9
  /** Longest {@link ToolSpec.title}, in code points. */
4
10
  export const TOOL_TITLE_MAX = 80;
5
11
  /** Most {@link ToolSpec.keyArgs}. */
@@ -52,7 +58,10 @@ export function validateToolPresentation(spec) {
52
58
  return out;
53
59
  }
54
60
  const DISPLAY_MAX = 200;
55
- /** 校验 {@link ToolDisplay},返回问题列表(空 = 合法);长度按 Unicode 码点计。 */
61
+ /**
62
+ * Validates a {@link ToolDisplay} and returns the list of problems (empty = valid); length is
63
+ * counted in Unicode code points.
64
+ */
56
65
  export function validateToolDisplay(d) {
57
66
  if (typeof d !== "object" || d === null || Array.isArray(d))
58
67
  return ["display must be an object"];
@@ -67,7 +76,13 @@ export function validateToolDisplay(d) {
67
76
  }
68
77
  return out;
69
78
  }
70
- /** 工具执行失败:message 给模型看,须为英文且可操作。 */
79
+ /** The longest {@link InputForm.body}, in characters (per language). */
80
+ export const INPUT_FORM_BODY_MAX = 2000;
81
+ /** The most buttons a form's choices may draw. */
82
+ export const INPUT_CHOICES_MAX = 3;
83
+ /** The longest choice label, in characters (per language). */
84
+ export const INPUT_CHOICE_LABEL_MAX = 40;
85
+ /** A tool execution failure: message is for the model and must be in English and actionable. */
71
86
  export class ToolError extends Error {
72
87
  kind;
73
88
  constructor(message, opts) {
@@ -76,9 +91,12 @@ export class ToolError extends Error {
76
91
  this.kind = opts?.kind ?? "error";
77
92
  }
78
93
  }
79
- /** 插件工具名规则。 */
94
+ /** Plugin tool name rule. */
80
95
  export const EXTENSION_TOOL_NAME = /^[a-zA-Z0-9_-]{1,40}$/;
81
- /** 校验插件注册的工具声明,返回问题列表(空 = 合法)。 */
96
+ /**
97
+ * Validates the tool declarations a plugin registers and returns the list of problems (empty =
98
+ * valid).
99
+ */
82
100
  export function validateToolSpec(spec) {
83
101
  const out = [];
84
102
  if (typeof spec?.name !== "string" || !EXTENSION_TOOL_NAME.test(spec.name))
@@ -93,6 +111,19 @@ export function validateToolSpec(spec) {
93
111
  out.push('defaultPolicy must be "allow" or "ask"');
94
112
  if (typeof spec?.inputSchema === "object" && spec.inputSchema !== null)
95
113
  out.push(...validateToolPresentation(spec));
114
+ const sources = spec?.sources;
115
+ if (sources !== undefined &&
116
+ (!Array.isArray(sources) ||
117
+ sources.length === 0 ||
118
+ sources.some((s) => !CONVERSATION_SOURCES.includes(s))))
119
+ out.push(`sources must be a non-empty list of ${CONVERSATION_SOURCES.join(", ")}`);
120
+ const timeout = spec?.timeoutMs;
121
+ if (timeout !== undefined &&
122
+ (typeof timeout !== "number" ||
123
+ !Number.isInteger(timeout) ||
124
+ timeout < TOOL_TIMEOUT_MIN_MS ||
125
+ timeout > TOOL_TIMEOUT_MAX_MS))
126
+ out.push(`timeoutMs must be a whole number of milliseconds from ${TOOL_TIMEOUT_MIN_MS} to ${TOOL_TIMEOUT_MAX_MS}`);
96
127
  return out;
97
128
  }
98
129
  const SCHEMA_KEYS = {
@@ -101,7 +132,7 @@ const SCHEMA_KEYS = {
101
132
  number: ["type", "minimum", "maximum"],
102
133
  integer: ["type", "minimum", "maximum"],
103
134
  };
104
- /** 检查 schema 是否落在 ParamSchema 子集内,返回问题列表。 */
135
+ /** Checks whether a schema falls within the ParamSchema subset and returns the list of problems. */
105
136
  function schemaProblems(schema) {
106
137
  if (typeof schema !== "object" || schema === null || Array.isArray(schema))
107
138
  return ["schema must be an object"];
@@ -130,7 +161,7 @@ function schemaProblems(schema) {
130
161
  return out;
131
162
  }
132
163
  const isEnum = (s) => s.type === "string" && "enum" in s;
133
- /** 校验交互表单的声明,返回问题列表(空 = 合法)。 */
164
+ /** Validates an interactive form declaration and returns the list of problems (empty = valid). */
134
165
  export function validateInputForm(form) {
135
166
  const out = [];
136
167
  if (!form || !Array.isArray(form.fields))
@@ -139,6 +170,8 @@ export function validateInputForm(form) {
139
170
  out.push("form must have at least one field");
140
171
  if (form.url !== undefined && !isHttpUrl(form.url))
141
172
  out.push("url must be an absolute http(s) URL of at most 2000 characters");
173
+ if (form.body !== undefined && !textWithin(form.body, INPUT_FORM_BODY_MAX))
174
+ out.push(`body must be non-empty text of at most ${INPUT_FORM_BODY_MAX} characters`);
142
175
  const seen = new Set();
143
176
  for (const f of form.fields) {
144
177
  const at = `field ${JSON.stringify(f?.key)}`;
@@ -156,10 +189,56 @@ export function validateInputForm(form) {
156
189
  continue;
157
190
  if ((f.multiSelect || f.allowOther) && !isEnum(f.schema))
158
191
  out.push(`${at}: multiSelect and allowOther require a string enum schema`);
192
+ if (f.choices !== undefined)
193
+ out.push(...choicesProblems(form, f).map((p) => `${at}: ${p}`));
194
+ }
195
+ return out;
196
+ }
197
+ /** Non-empty text (a string or both languages) of at most `max` characters per language. */
198
+ function textWithin(t, max) {
199
+ const ok = (x) => typeof x === "string" && x.trim() !== "" && x.length <= max;
200
+ if (typeof t === "string")
201
+ return ok(t);
202
+ return (typeof t === "object" &&
203
+ t !== null &&
204
+ ok(t.zh) &&
205
+ ok(t.en));
206
+ }
207
+ /** The rules of {@link InputForm} `choices` (buttons): see the field's documentation. */
208
+ function choicesProblems(form, f) {
209
+ const out = [];
210
+ const c = f.choices;
211
+ if (!Array.isArray(c) || c.length === 0 || c.length > INPUT_CHOICES_MAX)
212
+ return [`choices must be an array of 1 to ${INPUT_CHOICES_MAX} items`];
213
+ if (form.fields.length !== 1)
214
+ out.push("choices are allowed only on a form's single field");
215
+ if (f.required !== true)
216
+ out.push("choices require required: true");
217
+ const bool = f.schema.type === "boolean";
218
+ const single = isEnum(f.schema) && !f.multiSelect && !f.allowOther;
219
+ if (!bool && !single)
220
+ out.push("choices require a boolean or a single-choice string enum (no multiSelect / allowOther)");
221
+ const seen = new Set();
222
+ for (const x of c) {
223
+ const v = x?.value;
224
+ const valid = bool
225
+ ? typeof v === "boolean"
226
+ : single && typeof v === "string" && f.schema.enum.includes(v);
227
+ if (!valid)
228
+ out.push(`choice value ${JSON.stringify(v)} is not a value of the field`);
229
+ else if (seen.has(v))
230
+ out.push(`duplicate choice value ${JSON.stringify(v)}`);
231
+ else
232
+ seen.add(v);
233
+ if (!textWithin(x?.label, INPUT_CHOICE_LABEL_MAX))
234
+ out.push(`choice label must be non-empty text of at most ${INPUT_CHOICE_LABEL_MAX} characters`);
159
235
  }
160
236
  return out;
161
237
  }
162
- /** 校验用户提交的答案是否符合表单,返回问题列表(空 = 合法)。 */
238
+ /**
239
+ * Validates whether the answer a user submitted conforms to the form and returns the list of
240
+ * problems (empty = valid).
241
+ */
163
242
  export function validateAnswer(form, answer) {
164
243
  const out = [];
165
244
  const byKey = new Map(form.fields.map((f) => [f.key, f]));
@@ -168,7 +247,8 @@ export function validateAnswer(form, answer) {
168
247
  out.push(`unknown field ${JSON.stringify(k)}`);
169
248
  for (const f of form.fields) {
170
249
  const at = `field ${JSON.stringify(f.key)}`;
171
- // 只认答案自身的键:`toString` / `constructor` 等继承属性不算已回答
250
+ // Look only at the answer's own keys: inherited properties such as `toString` / `constructor`
251
+ // do not count as answered
172
252
  const v = Object.hasOwn(answer, f.key) ? answer[f.key] : undefined;
173
253
  if (v === undefined) {
174
254
  if (f.required)
@@ -209,7 +289,9 @@ export function validateAnswer(form, answer) {
209
289
  }
210
290
  return out;
211
291
  }
212
- /** allowOther 的枚举字段接受任意非空文本,其余按 schema 校验。 */
292
+ /**
293
+ * An allowOther enum field accepts any non-empty text; the rest are validated against the schema.
294
+ */
213
295
  function otherOrValue(f, v) {
214
296
  if (f.allowOther && isEnum(f.schema)) {
215
297
  return typeof v === "string" && v !== "" ? undefined : "other text must be a non-empty string";