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

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 (134) 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 +4 -1
  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 +2 -0
  9. package/agent-docs/extension-points/model-provider.md +3 -1
  10. package/agent-docs/extension-points/object-store.md +2 -0
  11. package/agent-docs/extension-points/push-provider.md +17 -0
  12. package/agent-docs/extensions.md +29 -3
  13. package/agent-docs/plugin-format.md +53 -2
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +86 -1
  20. package/dist/bootstrap.js +161 -2
  21. package/dist/cards.d.ts +67 -13
  22. package/dist/cards.js +91 -21
  23. package/dist/channel.d.ts +148 -48
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +22 -0
  30. package/dist/config-ui.js +64 -4
  31. package/dist/connector-auth.d.ts +7 -2
  32. package/dist/connector-auth.js +29 -8
  33. package/dist/connector.d.ts +74 -32
  34. package/dist/context.d.ts +40 -0
  35. package/dist/context.js +2 -0
  36. package/dist/ctx.d.ts +120 -29
  37. package/dist/define-extension.d.ts +26 -12
  38. package/dist/define-extension.js +11 -4
  39. package/dist/device-denied-paths.d.ts +14 -0
  40. package/dist/device-denied-paths.js +41 -0
  41. package/dist/device-operation.d.ts +302 -0
  42. package/dist/device-operation.js +292 -0
  43. package/dist/device-protocol.d.ts +490 -0
  44. package/dist/device-protocol.js +1117 -0
  45. package/dist/device-provider.d.ts +472 -0
  46. package/dist/device-provider.js +283 -0
  47. package/dist/extension-point.d.ts +2 -0
  48. package/dist/extension-point.js +6 -2
  49. package/dist/file-preview.d.ts +23 -6
  50. package/dist/git-hosts.d.ts +53 -0
  51. package/dist/git-hosts.js +98 -0
  52. package/dist/hooks.d.ts +125 -20
  53. package/dist/hooks.js +5 -0
  54. package/dist/http-access.d.ts +62 -0
  55. package/dist/http-access.js +12 -0
  56. package/dist/identity.d.ts +38 -9
  57. package/dist/identity.js +21 -1
  58. package/dist/index.d.ts +29 -2
  59. package/dist/index.js +29 -2
  60. package/dist/marketplace.d.ts +26 -0
  61. package/dist/marketplace.js +43 -1
  62. package/dist/model-params.d.ts +41 -22
  63. package/dist/model-params.js +28 -15
  64. package/dist/model.d.ts +206 -71
  65. package/dist/model.js +152 -19
  66. package/dist/net.d.ts +52 -0
  67. package/dist/net.js +34 -0
  68. package/dist/network-classes.d.ts +98 -0
  69. package/dist/network-classes.js +291 -0
  70. package/dist/permissions.d.ts +41 -21
  71. package/dist/permissions.js +101 -42
  72. package/dist/plugin-manifest.d.ts +45 -5
  73. package/dist/plugin-manifest.js +169 -6
  74. package/dist/plugin-package.d.ts +82 -38
  75. package/dist/plugin-package.js +61 -29
  76. package/dist/push.d.ts +75 -0
  77. package/dist/push.js +87 -0
  78. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  79. package/dist/sandbox-linux-runtime-source.js +2318 -0
  80. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  81. package/dist/sandbox-native-runtime-source.js +476 -0
  82. package/dist/sandbox-runtime-source.d.ts +19 -0
  83. package/dist/sandbox-runtime-source.js +28 -0
  84. package/dist/sandbox-write-denies.d.ts +139 -0
  85. package/dist/sandbox-write-denies.js +869 -0
  86. package/dist/secret.d.ts +4 -1
  87. package/dist/secret.js +4 -1
  88. package/dist/setup-check.d.ts +128 -0
  89. package/dist/setup-check.js +142 -0
  90. package/dist/setup-guide-parse.d.ts +135 -0
  91. package/dist/setup-guide-parse.js +413 -0
  92. package/dist/setup-guide-render.d.ts +50 -0
  93. package/dist/setup-guide-render.js +367 -0
  94. package/dist/setup-guide.d.ts +109 -0
  95. package/dist/setup-guide.js +377 -0
  96. package/dist/shell-capabilities.d.ts +231 -0
  97. package/dist/shell-capabilities.js +37 -0
  98. package/dist/shell-environment.d.ts +57 -0
  99. package/dist/shell-environment.js +22 -0
  100. package/dist/skill-invocation.d.ts +4 -3
  101. package/dist/skill-invocation.js +5 -4
  102. package/dist/skill.d.ts +34 -21
  103. package/dist/skill.js +49 -32
  104. package/dist/storage.d.ts +52 -25
  105. package/dist/theme-assets.d.ts +55 -0
  106. package/dist/theme-assets.js +507 -0
  107. package/dist/theme-readability.d.ts +37 -0
  108. package/dist/theme-readability.js +145 -0
  109. package/dist/theme-tokens.generated.d.ts +299 -0
  110. package/dist/theme-tokens.generated.js +184 -0
  111. package/dist/theme.d.ts +190 -0
  112. package/dist/theme.js +471 -0
  113. package/dist/tool.d.ts +69 -26
  114. package/dist/tool.js +29 -9
  115. package/dist/ui-parts.d.ts +23 -0
  116. package/dist/ui-parts.js +348 -0
  117. package/dist/ui-resolve.d.ts +35 -0
  118. package/dist/ui-resolve.js +42 -0
  119. package/dist/ui-slots.d.ts +65 -0
  120. package/dist/ui-slots.js +261 -0
  121. package/dist/ui.d.ts +212 -76
  122. package/dist/ui.js +101 -27
  123. package/dist/url.d.ts +4 -1
  124. package/dist/url.js +4 -1
  125. package/package.json +8 -1
  126. package/schemas/bootstrap-extra.v1.schema.json +172 -0
  127. package/schemas/bootstrap.v1.schema.json +6 -0
  128. package/schemas/connector-template.v1.schema.json +35 -0
  129. package/schemas/marketplace.v1.schema.json +14 -0
  130. package/schemas/plugin.v1.schema.json +117 -3
  131. package/schemas/theme.v1.schema.json +302 -0
  132. package/agent-docs/extension-points/sandbox.md +0 -15
  133. package/dist/sandbox.d.ts +0 -232
  134. package/dist/sandbox.js +0 -120
package/dist/theme.js ADDED
@@ -0,0 +1,471 @@
1
+ import { z } from "zod";
2
+ import { BUILTIN_AVATAR_PRESET_IDS } from "./avatar-presets.js";
3
+ import { CATALOG_ITEM_NAME_RE, isSafePackagePath } from "./plugin-package.js";
4
+ import { checkThemeReadability } from "./theme-readability.js";
5
+ import { THEME_OVERRIDABLE, THEME_TOKENS } from "./theme-tokens.generated.js";
6
+ /**
7
+ * A theme file `themes/<id>.json` (themes spec §4): a partial override of the design tokens per
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
10
+ * ({@link themeIdOf}, `CATALOG_ITEM_NAME_RE`).
11
+ *
12
+ * {@link parseThemeFile} is the CSS-injection boundary: every token value is parsed against the
13
+ * grammar `tokens.json` uses (`#RRGGBB`, `rgba(r,g,b,a)`, shadows `<x> <y> <blur> [<spread>]
14
+ * <color>`) and re-rendered from its parts in canonical form. Asset paths (`fonts[].file`,
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}.
21
+ *
22
+ * The committed JSON Schema (`schemas/theme.v1.schema.json`) is generated from
23
+ * {@link ThemeFileSchema} (the shape only) by `pnpm gen:package-schemas`; token names, value
24
+ * grammar, path safety and readability are decided only by {@link parseThemeFile}.
25
+ */
26
+ /** Limits of theme files and their assets. */
27
+ export const THEME_LIMITS = {
28
+ /** UTF-8 bytes of one theme file. */
29
+ fileBytes: 64 * 1024,
30
+ /** Themes per plugin. */
31
+ perPlugin: 10,
32
+ /** Total bytes of a plugin's theme assets (fonts, logos, app icons and avatars). */
33
+ assetsBytes: 16 * 1024 * 1024,
34
+ /** Fonts per theme. */
35
+ fonts: 8,
36
+ /** Bytes of one woff2 font. */
37
+ fontBytes: 2 * 1024 * 1024,
38
+ /** Bytes of a logo SVG. */
39
+ svgBytes: 128 * 1024,
40
+ /** Bytes of a logo PNG. */
41
+ pngBytes: 256 * 1024,
42
+ /** Minimum pixel height of a logo PNG. */
43
+ pngMinHeight: 64,
44
+ /** Characters of the wordmark (and of each avatar preset name). */
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,
52
+ };
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`. */
59
+ export function themeIdOf(path) {
60
+ return (path.split("/").pop() ?? "").replace(/\.json$/, "");
61
+ }
62
+ const MAX_ERRORS = 50;
63
+ const FAMILY_RE = /^[A-Za-z0-9 -]{1,64}$/;
64
+ /** Control, format, line / paragraph separator and lone surrogate characters. */
65
+ const FORBIDDEN_CHARS_RE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u;
66
+ const PATH_SEGMENT_RE = /^[A-Za-z0-9._-]+$/;
67
+ const FORBIDDEN_CHARS_MESSAGE = "must not contain control, format, line / paragraph separator or lone surrogate characters";
68
+ const IMAGE_RE = /\.(?:svg|png)$/i;
69
+ const PNG_RE = /\.png$/i;
70
+ const BUILTIN_AVATARS = new Set(BUILTIN_AVATAR_PRESET_IDS);
71
+ const MAX_VALUE_CHARS = 256;
72
+ const text = (max, what) => z
73
+ .string()
74
+ .min(1)
75
+ .max(max)
76
+ .regex(/\S/, { message: `${what} must not be blank` })
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}` });
86
+ /** A plugin-root relative path (optional `./`), each segment `[A-Za-z0-9._-]`, no `.` / `..`. */
87
+ const isPlainAssetPath = (p) => {
88
+ const rest = p.replace(/^\.\//, "");
89
+ return (isSafePackagePath(rest) &&
90
+ rest.split("/").every((seg) => PATH_SEGMENT_RE.test(seg) && seg !== "." && seg !== ".."));
91
+ };
92
+ const assetPath = (what, ext, kind) => z
93
+ .string()
94
+ .max(512)
95
+ .refine((p) => isPlainAssetPath(p) && ext.test(p), {
96
+ message: `${what} must be a relative ${kind} path inside the plugin, each segment of letters, digits, ".", "_" or "-"`,
97
+ });
98
+ const tokenValues = z.record(z.string().max(64), z.string().max(MAX_VALUE_CHARS));
99
+ const radius = z.number().int().min(0).max(16);
100
+ const schemeOverride = z.strictObject({
101
+ color: tokenValues.optional(),
102
+ shadow: tokenValues.optional(),
103
+ radius: z
104
+ .strictObject({ sm: radius.optional(), md: radius.optional(), bubble: radius.optional() })
105
+ .optional(),
106
+ });
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({
116
+ $schema: z.string().max(512).optional(),
117
+ name: z.strictObject({ zh: text(100, "name.zh"), en: text(100, "name.en") }),
118
+ description: z
119
+ .strictObject({
120
+ en: text(1024, "description.en"),
121
+ zh: text(1024, "description.zh").optional(),
122
+ })
123
+ .optional(),
124
+ schemes: z
125
+ .strictObject({ dark: schemeOverride.optional(), light: schemeOverride.optional() })
126
+ .refine((s) => s.dark !== undefined || s.light !== undefined, {
127
+ message: "schemes must define dark, light or both",
128
+ }),
129
+ fonts: z
130
+ .array(z.strictObject({
131
+ family: z.string().regex(FAMILY_RE, {
132
+ message: "family must be 1-64 letters, digits, spaces or '-'",
133
+ }),
134
+ file: assetPath("file", /\.woff2$/i, ".woff2"),
135
+ weight: z.number().int().min(100).max(900),
136
+ style: z.enum(["normal", "italic"]).optional(),
137
+ role: z.enum(["prose", "mono"]),
138
+ }))
139
+ .max(THEME_LIMITS.fonts)
140
+ .optional(),
141
+ logo: z
142
+ .strictObject({
143
+ mark: assetPath("mark", IMAGE_RE, ".svg or .png").optional(),
144
+ wordmark: shortText("wordmark").optional(),
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
+ });
183
+ })
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
+ }
205
+ });
206
+ /**
207
+ * The zod schema of a theme file's shape (strict objects). Token names and values are only
208
+ * strings here; see {@link parseThemeFile}. The JSON Schema is generated with
209
+ * `z.toJSONSchema(ThemeFileSchema, { io: "input" })`.
210
+ */
211
+ export const ThemeFileSchema = shape;
212
+ const HEX_RE = /^#([0-9A-Fa-f]{6})$/;
213
+ const RGBA_RE = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d{1,4})\s*\)$/;
214
+ const LENGTH_RE = /^(-?)(\d{1,3})(px)?$/;
215
+ /** `#RRGGBB` uppercase or `rgba(r,g,b,a)` rendered from its parts; undefined outside the grammar. */
216
+ function parseColor(v) {
217
+ const hex = HEX_RE.exec(v);
218
+ if (hex)
219
+ return `#${hex[1].toUpperCase()}`;
220
+ const m = RGBA_RE.exec(v);
221
+ if (!m)
222
+ return undefined;
223
+ const ch = [m[1], m[2], m[3]].map(Number);
224
+ if (ch.some((c) => c > 255))
225
+ return undefined;
226
+ return `rgba(${ch.join(",")},${String(Number(m[4]))})`;
227
+ }
228
+ /** A shadow length: `0` or `<n>px` (unitless only for 0), rendered as `0` / `<n>px`. */
229
+ function parseLength(v, allowNegative) {
230
+ const m = LENGTH_RE.exec(v);
231
+ if (!m)
232
+ return undefined;
233
+ const n = Number(m[2]);
234
+ if (n !== 0 && m[3] === undefined)
235
+ return undefined;
236
+ if (n === 0)
237
+ return "0";
238
+ if (m[1] === "-" && !allowNegative)
239
+ return undefined;
240
+ return `${m[1]}${n}px`;
241
+ }
242
+ /** `<x> <y> <blur> [<spread>] <color>`, rendered canonically; undefined outside the grammar. */
243
+ function parseShadow(v) {
244
+ const s = v.trim();
245
+ const at = s.endsWith(")") ? s.lastIndexOf("rgba(") : s.lastIndexOf(" ") + 1;
246
+ if (at <= 0 || !/\s/.test(s.charAt(at - 1)))
247
+ return undefined;
248
+ const color = parseColor(s.slice(at));
249
+ const lengths = s.slice(0, at).trim().split(/\s+/);
250
+ if (color === undefined || lengths.length < 3 || lengths.length > 4)
251
+ return undefined;
252
+ // x, y and spread may be negative; blur may not.
253
+ const parts = lengths.map((l, i) => parseLength(l, i !== 2));
254
+ if (parts.some((p) => p === undefined))
255
+ return undefined;
256
+ return `${parts.join(" ")} ${color}`;
257
+ }
258
+ const SCHEMES = ["dark", "light"];
259
+ const OVERRIDABLE = {
260
+ color: new Set(THEME_OVERRIDABLE.color),
261
+ shadow: new Set(THEME_OVERRIDABLE.shadow),
262
+ };
263
+ const GRAMMAR = {
264
+ color: { parse: parseColor, form: "#RRGGBB or rgba(r,g,b,a)" },
265
+ shadow: {
266
+ parse: parseShadow,
267
+ form: "<x> <y> <blur> [<spread>] <color> with px lengths and a #RRGGBB or rgba(r,g,b,a) color",
268
+ },
269
+ };
270
+ /**
271
+ * The canonical form of a token value under the grammar of `group` (the one {@link parseThemeFile}
272
+ * applies), or undefined when `value` is not a string within it. For readers of stored themes that
273
+ * emit values again (the kernel's stylesheet, themes spec §8): a stored value is re-validated
274
+ * before it reaches CSS, so a changed database row cannot inject CSS.
275
+ */
276
+ export function canonicalThemeValue(group, value) {
277
+ if (typeof value !== "string" || value.length > MAX_VALUE_CHARS)
278
+ return undefined;
279
+ return GRAMMAR[group].parse(value);
280
+ }
281
+ /** Whether `v` is a font family a theme may name: 1-64 letters, digits, spaces or `-`. */
282
+ export function isThemeFontFamily(v) {
283
+ return typeof v === "string" && FAMILY_RE.test(v);
284
+ }
285
+ /**
286
+ * Whether `v` is an asset path a theme may name: plugin-root relative (an optional leading `./`),
287
+ * every segment of `[A-Za-z0-9._-]`, no `.` / `..` segments (the extension is not checked).
288
+ */
289
+ export function isThemeAssetPath(v) {
290
+ return typeof v === "string" && v.length <= 512 && isPlainAssetPath(v);
291
+ }
292
+ /**
293
+ * Each scheme the theme defines, merged onto the current built-in values (for swatches, the
294
+ * readability check and anything else that needs full values). A stored theme is read leniently:
295
+ * an override whose token name the built-in tokens no longer know (renamed in core), that is not
296
+ * overridable, or whose value falls outside the grammar is skipped, as the stylesheet skips it.
297
+ */
298
+ export function mergeThemeSchemes(theme) {
299
+ const out = {};
300
+ const schemes = theme?.schemes;
301
+ if (schemes === null || typeof schemes !== "object")
302
+ return out;
303
+ for (const scheme of SCHEMES) {
304
+ const over = schemes[scheme];
305
+ if (over === null || typeof over !== "object")
306
+ continue;
307
+ const m = builtIn(scheme);
308
+ for (const group of ["color", "shadow"]) {
309
+ const values = over[group];
310
+ if (values === null || typeof values !== "object")
311
+ continue;
312
+ for (const [name, raw] of Object.entries(values)) {
313
+ if (!OVERRIDABLE[group].has(name))
314
+ continue;
315
+ const v = canonicalThemeValue(group, raw);
316
+ if (v !== undefined)
317
+ m[group][name] = v;
318
+ }
319
+ }
320
+ const radii = over.radius;
321
+ if (radii !== null && typeof radii === "object") {
322
+ for (const key of ["sm", "md", "bubble"]) {
323
+ const v = radii[key];
324
+ if (Number.isInteger(v) && v >= 0 && v <= 16) {
325
+ m.radius[key] = v;
326
+ }
327
+ }
328
+ }
329
+ out[scheme] = m;
330
+ }
331
+ return out;
332
+ }
333
+ /** The built-in values of one scheme. */
334
+ function builtIn(scheme) {
335
+ const pick = (group) => Object.fromEntries(Object.entries(group).map(([n, v]) => [n, v[scheme]]));
336
+ return {
337
+ color: pick(THEME_TOKENS.color),
338
+ shadow: pick(THEME_TOKENS.shadow),
339
+ radius: { ...THEME_TOKENS.radius },
340
+ };
341
+ }
342
+ function readJson(json) {
343
+ let text;
344
+ if (typeof json === "string") {
345
+ text = json;
346
+ }
347
+ else {
348
+ // An already parsed value is measured by its JSON serialization.
349
+ try {
350
+ text = JSON.stringify(json) ?? "";
351
+ }
352
+ catch {
353
+ return { errors: ["theme file must be a JSON object"] };
354
+ }
355
+ }
356
+ if (new TextEncoder().encode(text).length > THEME_LIMITS.fileBytes) {
357
+ return { errors: [`theme file is larger than ${THEME_LIMITS.fileBytes} bytes`] };
358
+ }
359
+ if (typeof json !== "string")
360
+ return { value: json };
361
+ try {
362
+ return { value: JSON.parse(json.startsWith("\uFEFF") ? json.slice(1) : json) };
363
+ }
364
+ catch (e) {
365
+ const first = (e instanceof Error ? e.message : String(e)).split("\n")[0];
366
+ return { errors: [`theme file is not valid JSON: ${first}`] };
367
+ }
368
+ }
369
+ /**
370
+ * Parses and validates a theme file: the parsed JSON value or the file text (larger than
371
+ * {@link THEME_LIMITS}`.fileBytes`, measured as text or as the value's JSON, is refused). Checks the id, the shape, token names against
372
+ * the generated allowlist (an unknown or non-overridable name is an error), the value grammar,
373
+ * fonts and logo; then (unless `options.readability` is false) merges every defined scheme onto
374
+ * the built-in tokens ({@link mergeThemeSchemes}) and reports each readability issue as an error
375
+ * starting `unreadable:`. Returned values are canonical (uppercase
376
+ * hex, rgba and shadows re-rendered from their parts). Invalid input returns `{ errors }`
377
+ * (`<path>: <reason>`, English, at most 50); never throws.
378
+ */
379
+ export function parseThemeFile(id, json, options = {}) {
380
+ if (!CATALOG_ITEM_NAME_RE.test(id)) {
381
+ return { errors: [`theme id "${id}" must match ^[a-z0-9][a-z0-9-]{0,63}$`] };
382
+ }
383
+ const read = readJson(json);
384
+ if ("errors" in read)
385
+ return read;
386
+ const data = read.value;
387
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
388
+ return { errors: ["theme file must be a JSON object"] };
389
+ }
390
+ const r = shape.safeParse(data);
391
+ if (!r.success) {
392
+ return {
393
+ errors: r.error.issues.slice(0, MAX_ERRORS).map((i) => {
394
+ const path = i.path.map(String).join(".");
395
+ return path ? `${path}: ${i.message}` : i.message;
396
+ }),
397
+ };
398
+ }
399
+ const file = r.data;
400
+ const errors = [];
401
+ const seenFonts = new Set();
402
+ file.fonts?.forEach((f, i) => {
403
+ const key = `${f.family.toLowerCase()}|${f.weight}|${f.style ?? "normal"}|${f.role}`;
404
+ if (seenFonts.has(key)) {
405
+ errors.push(`fonts.${i}: duplicate font ${f.family} ${f.weight} ${f.style ?? "normal"} (${f.role})`);
406
+ }
407
+ seenFonts.add(key);
408
+ });
409
+ const schemes = {};
410
+ for (const scheme of SCHEMES) {
411
+ const over = file.schemes[scheme];
412
+ if (over === undefined)
413
+ continue;
414
+ const out = {};
415
+ // Token names come from the raw object's own keys: the zod record drops `__proto__`.
416
+ const rawScheme = data.schemes[scheme];
417
+ for (const group of ["color", "shadow"]) {
418
+ const values = over[group];
419
+ if (values === undefined)
420
+ continue;
421
+ const rawGroup = rawScheme?.[group];
422
+ const names = rawGroup !== null && typeof rawGroup === "object" ? Object.keys(rawGroup) : [];
423
+ const canonical = {};
424
+ for (const name of names) {
425
+ const path = `schemes.${scheme}.${group}.${name}`;
426
+ if (!OVERRIDABLE[group].has(name)) {
427
+ errors.push(Object.hasOwn(THEME_TOKENS[group], name)
428
+ ? `${path}: token ${group}.${name} is not overridable`
429
+ : `${path}: unknown token ${group}.${name}`);
430
+ continue;
431
+ }
432
+ const raw = values[name];
433
+ const v = raw === undefined ? undefined : GRAMMAR[group].parse(raw);
434
+ if (v === undefined) {
435
+ errors.push(`${path}: must be ${GRAMMAR[group].form}`);
436
+ continue;
437
+ }
438
+ canonical[name] = v;
439
+ }
440
+ out[group] = canonical;
441
+ }
442
+ if (over.radius !== undefined)
443
+ out.radius = { ...over.radius };
444
+ schemes[scheme] = out;
445
+ }
446
+ if (errors.length > 0)
447
+ return { errors: errors.slice(0, MAX_ERRORS) };
448
+ const merged = options.readability === false ? {} : mergeThemeSchemes({ schemes });
449
+ for (const scheme of SCHEMES) {
450
+ const m = merged[scheme];
451
+ if (m === undefined)
452
+ continue;
453
+ for (const issue of checkThemeReadability(scheme, m)) {
454
+ errors.push(issue.kind === "unevaluable"
455
+ ? `unreadable: schemes.${scheme}: ${issue.pair} has a value the check cannot evaluate`
456
+ : issue.kind === "separation-order"
457
+ ? `unreadable: schemes.${scheme}: ${issue.pair} must stand further from the surface than hover (${issue.ratio.toFixed(1)} ≤ ${issue.floor.toFixed(1)})`
458
+ : `unreadable: schemes.${scheme}: ${issue.pair} ${issue.kind} ${issue.ratio.toFixed(2)} is below ${issue.floor}${issue.detail === undefined ? "" : ` (${issue.detail})`}`);
459
+ }
460
+ }
461
+ if (errors.length > 0)
462
+ return { errors: errors.slice(0, MAX_ERRORS) };
463
+ const defined = SCHEMES.filter((s) => schemes[s] !== undefined);
464
+ const { $schema: _schema, ...rest } = file;
465
+ return {
466
+ ...rest,
467
+ schemes,
468
+ id,
469
+ singleScheme: defined.length === 1 ? defined[0] : null,
470
+ };
471
+ }
package/dist/tool.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ParamSchema } from "./model-params.js";
2
- /** 工具注解(与 MCP 对齐的提示,用于推导默认策略)。 */
2
+ /** Tool annotations (hints aligned with MCP, used to derive the default policy). */
3
3
  export interface ToolAnnotations {
4
4
  readOnlyHint?: boolean;
5
5
  destructiveHint?: boolean;
@@ -7,17 +7,26 @@ export interface ToolAnnotations {
7
7
  openWorldHint?: boolean;
8
8
  requiresUserInteraction?: boolean;
9
9
  }
10
+ /** Where a conversation comes from; a tool may limit itself to some of these. */
11
+ export declare const CONVERSATION_SOURCES: readonly ["web", "channel_dm", "channel_group", "subagent"];
12
+ /** A conversation source (see {@link CONVERSATION_SOURCES}). */
13
+ export type ConversationSource = (typeof CONVERSATION_SOURCES)[number];
10
14
  export interface ToolSpec {
11
15
  name: string;
12
16
  description: string;
13
17
  inputSchema: Record<string, unknown>;
14
18
  annotations?: ToolAnnotations;
15
- /** 仅插件 / 内置工具可声明;缺省按注解推导。 */
19
+ /**
20
+ * Only plugin / builtin tools may declare it; when omitted it is derived from the annotations.
21
+ */
16
22
  defaultPolicy?: "allow" | "ask";
17
23
  /**
18
- * 仅连接器工具:连接器自己的不透明数据(如 OpenAPI 的方法、路径模板、参数位置、服务器地址),可 JSON 序列化。
19
- * 内核把它与定义一起存进快照并计入指纹(变了即漂移、需复核),调用时经 `callTool` 的 `ctx.spec` 原样交回;
20
- * 绝不发给模型。
24
+ * Connector tools only: the connector's own opaque data (e.g. OpenAPI's method, path template,
25
+ * parameter locations, server address), JSON-serializable.
26
+ * The kernel stores it with the definition in the snapshot and counts it in the fingerprint (a
27
+ * change means drift and needs review), and hands it back unchanged via `ctx.spec` of `callTool`
28
+ * on a call;
29
+ * never sent to the model.
21
30
  */
22
31
  connectorData?: Record<string, unknown>;
23
32
  /**
@@ -33,6 +42,11 @@ export interface ToolSpec {
33
42
  * model and not part of the definition fingerprint.
34
43
  */
35
44
  keyArgs?: string[];
45
+ /**
46
+ * The conversation sources this tool is offered in; absent = every source. A non-empty list of
47
+ * {@link CONVERSATION_SOURCES}.
48
+ */
49
+ sources?: ConversationSource[];
36
50
  }
37
51
  /** Longest {@link ToolSpec.title}, in code points. */
38
52
  export declare const TOOL_TITLE_MAX = 80;
@@ -58,7 +72,10 @@ export type ToolContent = {
58
72
  name?: string;
59
73
  mimeType?: string;
60
74
  };
61
- /** 工具调用的一句话说明,给界面显示(中英文各 ≤ 200 字符);不进模型上下文。 */
75
+ /**
76
+ * A one-sentence description of a tool call, shown in the UI (Chinese and English each ≤ 200
77
+ * characters); does not enter the model context.
78
+ */
62
79
  export interface ToolDisplay {
63
80
  summary: {
64
81
  zh: string;
@@ -68,33 +85,44 @@ export interface ToolDisplay {
68
85
  export interface ToolResult {
69
86
  content: ToolContent[];
70
87
  isError?: boolean;
71
- /** 可选:对话流里显示这句说明,代替原样的输入 JSON。 */
88
+ /** Optional: show this description in the conversation stream in place of the raw input JSON. */
72
89
  display?: ToolDisplay;
73
90
  /**
74
91
  * 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.
92
+ * the same extension in the `conversation.tool-result.card` slot, rendered with
93
+ * `card: { callId, key }`. Display only (recorded on the `tool_result` event, never in the model's
94
+ * context); an unknown view is dropped with a warning and the result is kept.
78
95
  */
79
96
  card?: {
80
97
  view: string;
81
98
  key?: string;
82
99
  };
83
100
  }
84
- /** 校验 {@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
+ */
85
105
  export declare function validateToolDisplay(d: unknown): string[];
86
106
  /** Text shown to people: bilingual (`zh` / `en`) or a single string shown as is. */
87
107
  export type LocalizedText = {
88
108
  zh: string;
89
109
  en: string;
90
110
  } | string;
91
- /** 交互表单:字段的 schema 只用 M2 的 ParamSchema 子集;枚举字段可设 multiSelect 与 allowOther。 */
111
+ /**
112
+ * Interactive form: field schemas use only the ParamSchema subset of M2; enum fields may set
113
+ * multiSelect and allowOther.
114
+ */
92
115
  export interface InputForm {
93
- /** 插件可给双语;内核内置工具给英文(模型生成的问题原样展示)。 */
116
+ /**
117
+ * A plugin may give both languages; builtin kernel tools give English (model-generated questions
118
+ * are displayed as is).
119
+ */
94
120
  title: LocalizedText;
95
121
  /**
96
- * 可选:需要用户在浏览器里打开的外部页面(如 MCP URL 模式的 elicitation:去对方页面授权 / 付款 / 填敏感信息)。
97
- * 界面把它显示为链接(完整地址可见);只接受 http(s) 绝对地址、≤ 2000 字符。
122
+ * Optional: an external page the user must open in a browser (e.g. an MCP URL-mode elicitation:
123
+ * go to the other party's page to authorize / pay / enter sensitive information).
124
+ * The UI shows it as a link (the full address visible); only absolute http(s) addresses, ≤ 2000
125
+ * characters, are accepted.
98
126
  */
99
127
  url?: string;
100
128
  fields: {
@@ -108,8 +136,9 @@ export interface InputForm {
108
136
  }[];
109
137
  }
110
138
  /**
111
- * 工具需要用户输入:内核暂停运行、渲染表单;用户提交后用同一 input 再次调用该工具,
112
- * 并在 ctx.resume 中带回 state 与 answer。state ≤ 16 KB,可 JSON 序列化。
139
+ * The tool needs user input: the kernel pauses the run and renders a form; after the user submits,
140
+ * the tool is called again with the same input,
141
+ * and state and answer are brought back in ctx.resume. state ≤ 16 KB, JSON-serializable.
113
142
  */
114
143
  export interface InputRequired {
115
144
  kind: "input_required";
@@ -124,7 +153,7 @@ export interface ToolCallContext {
124
153
  conversationId: string;
125
154
  callId: string;
126
155
  signal: AbortSignal;
127
- /** null = 用户取消或超时。 */
156
+ /** null = the user cancelled or it timed out. */
128
157
  resume?: {
129
158
  state: unknown;
130
159
  answer: FormAnswer | null;
@@ -137,26 +166,40 @@ export interface ToolCallContext {
137
166
  * always passes it.
138
167
  */
139
168
  config?: unknown;
169
+ /** Where the conversation comes from. The kernel always passes it. */
170
+ source?: ConversationSource;
171
+ /** The conversation's owner (`conversations.account_id`). The kernel always passes it; `accountId` stays the run's trigger account. */
172
+ ownerAccountId?: string;
173
+ /** The trigger account's role in the org. The kernel always passes it. */
174
+ role?: "owner" | "admin" | "member" | "guest";
140
175
  }
141
176
  export type ToolHandler = (input: unknown, ctx: ToolCallContext) => Promise<ToolResult | InputRequired>;
142
177
  /**
143
- * 工具错误的类别:
144
- * - `error`(缺省):远端可用、但这次调用失败(参数不对、业务错误、鉴权失败等),不计入连接器熔断;
145
- * - `unavailable`:远端不可用(连接 / 传输错误、超时、HTTP 5xx),计入连接器熔断(连接器用它告诉内核)。
178
+ * Tool error categories:
179
+ * - `error` (default): the remote is available but this call failed (bad parameters, business
180
+ * error, auth failure, etc.), not counted toward the connector circuit breaker;
181
+ * - `unavailable`: the remote is unavailable (connection / transport error, timeout, HTTP 5xx),
182
+ * counted toward the connector circuit breaker (connectors use it to tell the kernel).
146
183
  */
147
184
  export type ToolErrorKind = "error" | "unavailable";
148
- /** 工具执行失败:message 给模型看,须为英文且可操作。 */
185
+ /** A tool execution failure: message is for the model and must be in English and actionable. */
149
186
  export declare class ToolError extends Error {
150
187
  readonly kind: ToolErrorKind;
151
188
  constructor(message: string, opts?: {
152
189
  kind?: ToolErrorKind;
153
190
  });
154
191
  }
155
- /** 插件工具名规则。 */
192
+ /** Plugin tool name rule. */
156
193
  export declare const EXTENSION_TOOL_NAME: RegExp;
157
- /** 校验插件注册的工具声明,返回问题列表(空 = 合法)。 */
194
+ /**
195
+ * Validates the tool declarations a plugin registers and returns the list of problems (empty =
196
+ * valid).
197
+ */
158
198
  export declare function validateToolSpec(spec: ToolSpec): string[];
159
- /** 校验交互表单的声明,返回问题列表(空 = 合法)。 */
199
+ /** Validates an interactive form declaration and returns the list of problems (empty = valid). */
160
200
  export declare function validateInputForm(form: InputForm): string[];
161
- /** 校验用户提交的答案是否符合表单,返回问题列表(空 = 合法)。 */
201
+ /**
202
+ * Validates whether the answer a user submitted conforms to the form and returns the list of
203
+ * problems (empty = valid).
204
+ */
162
205
  export declare function validateAnswer(form: InputForm, answer: FormAnswer): string[];