@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/model.js CHANGED
@@ -1,23 +1,91 @@
1
- /** 图片块接受的类型。 */
1
+ /** The aspect ratios a caller may ask for instead of an exact size. */
2
+ export const IMAGE_ASPECT_RATIOS = ["1:1", "4:3", "3:4", "3:2", "2:3", "16:9", "9:16"];
3
+ const isPositiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
4
+ /**
5
+ * Checks a model's cache declaration: positive integer TTLs, `ttlOptions` ascending and unique,
6
+ * `defaultTtl` present and among the options when options exist, `none` with no options and no
7
+ * guarantee, a guarantee only with a known lifetime, `minTokens` a positive integer. Returns the
8
+ * first problem (naming the field), or `null` when valid.
9
+ */
10
+ export function validateModelCache(cache) {
11
+ if (cache === undefined)
12
+ return null;
13
+ if (typeof cache !== "object" || cache === null || Array.isArray(cache)) {
14
+ return "cache must be an object";
15
+ }
16
+ if (!["explicit", "implicit", "none"].includes(cache.mechanism)) {
17
+ return `cache.mechanism must be "explicit", "implicit" or "none"`;
18
+ }
19
+ if (!Array.isArray(cache.ttlOptions))
20
+ return "cache.ttlOptions must be an array";
21
+ for (const [i, ttl] of cache.ttlOptions.entries()) {
22
+ if (!isPositiveInt(ttl))
23
+ return `cache.ttlOptions[${i}] must be a positive integer (seconds)`;
24
+ const prev = cache.ttlOptions[i - 1];
25
+ if (i > 0 && prev !== undefined && ttl <= prev) {
26
+ return "cache.ttlOptions must be ascending and unique";
27
+ }
28
+ }
29
+ if (cache.defaultTtl !== undefined) {
30
+ if (!isPositiveInt(cache.defaultTtl)) {
31
+ return "cache.defaultTtl must be a positive integer (seconds)";
32
+ }
33
+ if (cache.ttlOptions.length > 0 && !cache.ttlOptions.includes(cache.defaultTtl)) {
34
+ return "cache.defaultTtl must be one of cache.ttlOptions";
35
+ }
36
+ }
37
+ if (!["request_start", "unknown"].includes(cache.ttlClock)) {
38
+ return `cache.ttlClock must be "request_start" or "unknown"`;
39
+ }
40
+ for (const field of ["ttlIsMinimum", "refreshOnHit", "guaranteed"]) {
41
+ if (typeof cache[field] !== "boolean")
42
+ return `cache.${field} must be a boolean`;
43
+ }
44
+ if (cache.minTokens !== undefined && !isPositiveInt(cache.minTokens)) {
45
+ return "cache.minTokens must be a positive integer";
46
+ }
47
+ if (cache.mechanism === "none") {
48
+ if (cache.ttlOptions.length > 0)
49
+ return 'cache.mechanism "none" takes no ttlOptions';
50
+ if (cache.guaranteed)
51
+ return 'cache.guaranteed must be false with mechanism "none"';
52
+ }
53
+ if (cache.ttlOptions.length > 0 && cache.defaultTtl === undefined) {
54
+ return "cache.defaultTtl is required when cache.ttlOptions is non-empty";
55
+ }
56
+ if (cache.guaranteed && cache.ttlOptions.length === 0 && cache.defaultTtl === undefined) {
57
+ return "cache.guaranteed needs a known lifetime (ttlOptions or defaultTtl)";
58
+ }
59
+ return null;
60
+ }
61
+ /** Types accepted by image blocks. */
2
62
  export const IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
3
- /** 文档块接受的类型。 */
63
+ /** Types accepted by document blocks. */
4
64
  export const DOCUMENT_MEDIA_TYPES = [
5
65
  "application/pdf",
6
66
  "text/plain",
7
67
  "text/markdown",
8
68
  "text/csv",
9
69
  ];
10
- /** 单个媒体块解码后的字节上限(按主流供应商的较小值取)。 */
70
+ /**
71
+ * Upper bound on the decoded bytes of a single media block (the smaller value among mainstream
72
+ * vendors).
73
+ */
11
74
  export const MEDIA_LIMITS = { imageBytes: 5_242_880, documentBytes: 33_554_432 };
12
75
  const B64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
13
76
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
- /** 媒体块 `name` 的最大长度(字符)。 */
77
+ /** Maximum length (characters) of a media block's `name`. */
15
78
  export const MEDIA_NAME_MAX_CHARS = 255;
16
- /** 供应商请求里文件名 / 标题的建议上限(码点),{@link clipMediaName} 的默认值。 */
79
+ /**
80
+ * Suggested upper bound (code points) for file names / titles in vendor requests, the default of
81
+ * {@link clipMediaName}.
82
+ */
17
83
  export const PROVIDER_MEDIA_NAME_MAX = 200;
18
84
  /**
19
- * 把附件名截到 `max` 个码点以内(供应商映射用:有的接口对 filename / title 有长度限制,补后缀后还会更长)。
20
- * 尽量保留扩展名(不超过 16 个字符的 `.ext`),中间用 `…` 表示截掉的部分。纯函数。
85
+ * Truncates an attachment name to at most `max` code points (for vendor mapping: some APIs limit
86
+ * filename / title length, and adding a suffix makes it longer still).
87
+ * Keeps the extension where possible (a `.ext` of at most 16 characters), with `…` marking the cut
88
+ * part in the middle. A pure function.
21
89
  */
22
90
  export function clipMediaName(name, max = PROVIDER_MEDIA_NAME_MAX) {
23
91
  const cps = [...name];
@@ -29,7 +97,7 @@ export function clipMediaName(name, max = PROVIDER_MEDIA_NAME_MAX) {
29
97
  const head = cps.slice(0, max - 1 - keep.length);
30
98
  return `${head.join("")}…${keep.join("")}`;
31
99
  }
32
- /** 是否含控制字符(C0、DEL 与 C1)。 */
100
+ /** Whether it contains control characters (C0, DEL and C1). */
33
101
  export function hasControlChars(s) {
34
102
  for (let i = 0; i < s.length; i++) {
35
103
  const c = s.charCodeAt(i);
@@ -38,18 +106,30 @@ export function hasControlChars(s) {
38
106
  }
39
107
  return false;
40
108
  }
41
- /** 附件 id 是否为 UUID(任意版本,大小写不限)。 */
109
+ /** Whether the attachment id is a UUID (any version, case-insensitive). */
42
110
  export function isAttachmentId(s) {
43
111
  return typeof s === "string" && UUID_RE.test(s);
44
112
  }
113
+ /** Whether the file id (a media `ref`'s `fileId`) is a UUID (any version, case-insensitive). */
114
+ export function isFileId(s) {
115
+ return typeof s === "string" && UUID_RE.test(s);
116
+ }
117
+ /** Any non-empty `type/subtype` (a `file` block's `mediaType`). */
118
+ const MEDIA_TYPE_RE = /^[^/\s]+\/[^/\s]+$/;
45
119
  const MEDIA = {
46
120
  image: { types: IMAGE_MEDIA_TYPES, limit: MEDIA_LIMITS.imageBytes },
47
121
  document: { types: DOCUMENT_MEDIA_TYPES, limit: MEDIA_LIMITS.documentBytes },
122
+ // A file the model cannot read: the kernel resolves it to text before the request, so no media
123
+ // type list applies. The byte ceiling is the one attachments already have.
124
+ file: { types: [], limit: MEDIA_LIMITS.documentBytes, anyType: true },
48
125
  };
49
126
  /**
50
- * 校验一个 image / document 块,返回错误列表(空表示合法):类型在列表里;`base64` 是标准、带填充、
51
- * 不含空白的 base64,解码后不超过 {@link MEDIA_LIMITS};`ref` 的 `attachmentId` 是 UUID;`name` 若有须是字符串、
52
- * 不超过 {@link MEDIA_NAME_MAX_CHARS} 个字符且不含控制字符。
127
+ * Validates an image / document / file block, returning a list of errors (empty means valid): the
128
+ * media type is in the block kind's list (`file` accepts any non-empty `type/subtype`); `base64` is
129
+ * standard, padded, whitespace-free base64 that decodes to at most {@link MEDIA_LIMITS}; a `ref`'s
130
+ * `fileId` is a UUID; `name`, when present, is a string of at most
131
+ * {@link MEDIA_NAME_MAX_CHARS} characters with no control characters; `size`, when present, is a
132
+ * non-negative integer (display metadata, never sent by a plugin).
53
133
  */
54
134
  export function validateMediaBlock(b) {
55
135
  if (typeof b !== "object" || b === null || Array.isArray(b))
@@ -57,9 +137,16 @@ export function validateMediaBlock(b) {
57
137
  const o = b;
58
138
  const spec = typeof o.type === "string" && Object.hasOwn(MEDIA, o.type) ? MEDIA[o.type] : undefined;
59
139
  if (!spec)
60
- return ['block type must be "image" or "document"'];
140
+ return ['block type must be "image", "document" or "file"'];
61
141
  const errs = [];
62
- if (typeof o.mediaType !== "string" || !spec.types.includes(o.mediaType)) {
142
+ if (spec.anyType) {
143
+ if (typeof o.mediaType !== "string" ||
144
+ !MEDIA_TYPE_RE.test(o.mediaType) ||
145
+ hasControlChars(o.mediaType)) {
146
+ errs.push(`${o.type} mediaType must be a non-empty type/subtype string`);
147
+ }
148
+ }
149
+ else if (typeof o.mediaType !== "string" || !spec.types.includes(o.mediaType)) {
63
150
  errs.push(`${o.type} mediaType must be one of ${spec.types.join(", ")}`);
64
151
  }
65
152
  if (o.name !== undefined) {
@@ -72,6 +159,10 @@ export function validateMediaBlock(b) {
72
159
  errs.push(`${o.type} name must not contain control characters`);
73
160
  }
74
161
  }
162
+ if (o.size !== undefined &&
163
+ (typeof o.size !== "number" || !Number.isInteger(o.size) || o.size < 0)) {
164
+ errs.push(`${o.type} size must be a non-negative integer`);
165
+ }
75
166
  const src = o.source;
76
167
  if (typeof src !== "object" || src === null) {
77
168
  errs.push(`${o.type} source must be an object`);
@@ -79,8 +170,8 @@ export function validateMediaBlock(b) {
79
170
  }
80
171
  const source = src;
81
172
  if (source.kind === "ref") {
82
- if (!isAttachmentId(source.attachmentId)) {
83
- errs.push(`${o.type} source.attachmentId must be a UUID`);
173
+ if (!isFileId(source.fileId)) {
174
+ errs.push(`${o.type} source.fileId must be a UUID file id`);
84
175
  }
85
176
  }
86
177
  else if (source.kind === "base64") {
@@ -89,7 +180,8 @@ export function validateMediaBlock(b) {
89
180
  errs.push(`${o.type} source.data must be non-empty padded base64`);
90
181
  return errs;
91
182
  }
92
- // 先按长度算解码后的大小,超限就不再逐字符校验
183
+ // Compute the decoded size from the length first; when over the limit, skip the per-character
184
+ // validation
93
185
  const pad = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
94
186
  const bytes = (data.length / 4) * 3 - pad;
95
187
  if (bytes > spec.limit) {
@@ -104,6 +196,39 @@ export function validateMediaBlock(b) {
104
196
  }
105
197
  return errs;
106
198
  }
199
+ /**
200
+ * Checks `usage.cacheWriteByTtl` when present: positive integer `ttl`s, each once; non-negative
201
+ * integer `tokens`; the tokens sum to `cacheWriteTokens`. Returns the first problem, or `null`.
202
+ */
203
+ export function validateCacheWriteByTtl(usage) {
204
+ if (typeof usage !== "object" || usage === null)
205
+ return "usage must be an object";
206
+ const tiers = usage.cacheWriteByTtl;
207
+ if (tiers === undefined)
208
+ return null;
209
+ if (!Array.isArray(tiers))
210
+ return "cacheWriteByTtl must be an array";
211
+ const seen = new Set();
212
+ let sum = 0;
213
+ for (const [i, tier] of tiers.entries()) {
214
+ if (typeof tier !== "object" || tier === null)
215
+ return `cacheWriteByTtl[${i}] must be an object`;
216
+ if (!isPositiveInt(tier.ttl)) {
217
+ return `cacheWriteByTtl[${i}].ttl must be a positive integer (seconds)`;
218
+ }
219
+ if (seen.has(tier.ttl))
220
+ return `cacheWriteByTtl has ttl ${tier.ttl} twice`;
221
+ seen.add(tier.ttl);
222
+ if (typeof tier.tokens !== "number" || !Number.isInteger(tier.tokens) || tier.tokens < 0) {
223
+ return `cacheWriteByTtl[${i}].tokens must be a non-negative integer`;
224
+ }
225
+ sum += tier.tokens;
226
+ }
227
+ if (sum !== usage.cacheWriteTokens) {
228
+ return `cacheWriteByTtl sums to ${sum}, not cacheWriteTokens ${usage.cacheWriteTokens}`;
229
+ }
230
+ return null;
231
+ }
107
232
  const ALL_KINDS = new Set([
108
233
  "rate_limited",
109
234
  "overloaded",
@@ -113,6 +238,7 @@ const ALL_KINDS = new Set([
113
238
  "auth",
114
239
  "invalid_request",
115
240
  "context_overflow",
241
+ "refusal",
116
242
  "aborted",
117
243
  ]);
118
244
  const RETRYABLE = new Set([
@@ -122,11 +248,13 @@ const RETRYABLE = new Set([
122
248
  "timeout",
123
249
  "network",
124
250
  ]);
125
- /** rate_limited / overloaded / server / timeout / network 为 true。 */
251
+ /** True for rate_limited / overloaded / server / timeout / network. */
126
252
  export function isRetryableKind(kind) {
127
253
  return RETRYABLE.has(kind);
128
254
  }
129
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
255
+ /**
256
+ * Duck-typed check (no instanceof), compatible with a plugin bundling another copy of plugin-sdk.
257
+ */
130
258
  export function isModelError(e) {
131
259
  if (!(e instanceof Error))
132
260
  return false;
@@ -143,7 +271,7 @@ export class ModelError extends Error {
143
271
  if (opts?.retryAfterMs !== undefined)
144
272
  this.retryAfterMs = opts.retryAfterMs;
145
273
  }
146
- /** rate_limited / overloaded / server / timeout / network 为 true。 */
274
+ /** True for rate_limited / overloaded / server / timeout / network. */
147
275
  get retryable() {
148
276
  return isRetryableKind(this.kind);
149
277
  }
@@ -170,5 +298,105 @@ export function validateEmbedResult(req, info, res) {
170
298
  }
171
299
  return null;
172
300
  }
173
- export const MODEL_PROVIDER_EXTENSION_POINT = "model-provider@1";
301
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
302
+ /** True when `x` is a well-formed {@link ModelImageGenerationInfo}. */
303
+ export function isValidImageGenerationInfo(x) {
304
+ if (typeof x !== "object" || x === null)
305
+ return false;
306
+ const o = x;
307
+ const isSize = (s) => typeof s === "object" &&
308
+ s !== null &&
309
+ Number.isInteger(s.width) &&
310
+ Number.isInteger(s.height) &&
311
+ s.width > 0 &&
312
+ s.height > 0;
313
+ if (!Array.isArray(o.sizes) || o.sizes.length === 0 || !o.sizes.every(isSize))
314
+ return false;
315
+ if (!isSize(o.defaultSize))
316
+ return false;
317
+ const d = o.defaultSize;
318
+ if (!o.sizes.some((s) => s.width === d.width && s.height === d.height))
319
+ return false;
320
+ if (!Number.isInteger(o.maxImages) || o.maxImages < 1)
321
+ return false;
322
+ if (!Number.isInteger(o.maxReferenceImages) || o.maxReferenceImages < 0) {
323
+ return false;
324
+ }
325
+ return (Array.isArray(o.outputMediaTypes) &&
326
+ o.outputMediaTypes.length > 0 &&
327
+ o.outputMediaTypes.every((t) => IMAGE_MEDIA_TYPES.includes(t)));
328
+ }
329
+ /**
330
+ * Checks an image generation result against its request and the model's facts. Returns null when
331
+ * valid, else the reason: wrong image count, an undeclared media type, data that is not base64,
332
+ * or a `usage` that is not an object whose token counts (and `outputImages`, when present) are
333
+ * non-negative integers (a caller records usage from it, so it is checked before anything is).
334
+ */
335
+ export function validateImageGenerateResult(req, info, res) {
336
+ const images = res?.images;
337
+ if (!Array.isArray(images))
338
+ return "result has no images array";
339
+ if (images.length !== req.n)
340
+ return `expected ${req.n} images, got ${images.length}`;
341
+ for (let i = 0; i < images.length; i++) {
342
+ const img = images[i];
343
+ const type = img?.mediaType;
344
+ if (typeof type !== "string" || !info.outputMediaTypes.includes(type)) {
345
+ return `image ${i} has media type ${String(type)}, not one of ${info.outputMediaTypes.join(", ")}`;
346
+ }
347
+ if (typeof img?.data !== "string" || !BASE64.test(img.data)) {
348
+ return `image ${i} data is not base64`;
349
+ }
350
+ }
351
+ const usage = res.usage;
352
+ if (typeof usage !== "object" || usage === null)
353
+ return "result has no usage object";
354
+ const u = usage;
355
+ const count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
356
+ for (const field of ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"]) {
357
+ if (!count(u[field]))
358
+ return `usage.${field} is ${String(u[field])}, not a non-negative integer`;
359
+ }
360
+ if (u.outputImages !== undefined && !count(u.outputImages)) {
361
+ return `usage.outputImages is ${String(u.outputImages)}, not a non-negative integer`;
362
+ }
363
+ return null;
364
+ }
365
+ /**
366
+ * Chooses an output size: an exact `size` must be one the model offers; an `aspectRatio` picks the
367
+ * closest declared ratio (ties by area closest to the default's, then declaration order); neither
368
+ * gives the default size.
369
+ */
370
+ export function pickImageSize(info, opts) {
371
+ const fmt = (s) => `${s.width}x${s.height}`;
372
+ const { size, aspectRatio } = opts;
373
+ if (size) {
374
+ const hit = info.sizes.find((s) => s.width === size.width && s.height === size.height);
375
+ if (hit)
376
+ return { ok: true, size: hit };
377
+ return {
378
+ ok: false,
379
+ error: `Size ${fmt(size)} is not offered by this model; use one of ${info.sizes.map(fmt).join(", ")}.`,
380
+ };
381
+ }
382
+ if (!aspectRatio)
383
+ return { ok: true, size: info.defaultSize };
384
+ const [rw, rh] = aspectRatio.split(":").map(Number);
385
+ const target = Math.log(rw / rh);
386
+ const area = info.defaultSize.width * info.defaultSize.height;
387
+ let best = info.defaultSize;
388
+ let bestDiff = Number.POSITIVE_INFINITY;
389
+ let bestArea = Number.POSITIVE_INFINITY;
390
+ for (const s of info.sizes) {
391
+ const diff = Math.abs(Math.log(s.width / s.height) - target);
392
+ const areaDiff = Math.abs(s.width * s.height - area);
393
+ if (diff < bestDiff - 1e-9 || (Math.abs(diff - bestDiff) <= 1e-9 && areaDiff < bestArea)) {
394
+ best = s;
395
+ bestDiff = diff;
396
+ bestArea = areaDiff;
397
+ }
398
+ }
399
+ return { ok: true, size: best };
400
+ }
401
+ /** The model provider extension point (the only version since `@1` was removed before 0.1.0). */
174
402
  export const MODEL_PROVIDER_EXTENSION_POINT_V2 = "model-provider@2";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The model-facing text of a failed native file operation (#907), one mapping for every native
3
+ * helper and provider (capybara-device, device-docker, device-e2b). A native helper answers
4
+ * `{ error: { code } }` with an errno name (`ENOENT`, …), `SCOPE_DENIED`, `NOT_REGULAR_FILE` or
5
+ * `INVALID_NATIVE_REQUEST`; its own exception text never reaches the model (it may carry paths or
6
+ * other details), only the kernel-defined text for the code.
7
+ */
8
+ /** The code a native helper answers when a read or write names something other than a regular file. */
9
+ export declare const NATIVE_NOT_REGULAR_FILE = "NOT_REGULAR_FILE";
10
+ /** The text for a code this mapping does not know. */
11
+ export declare const NATIVE_FAILURE_GENERIC = "Native operation failed; check the path, scope and filesystem access";
12
+ /** The model-facing text for a native helper's error code. */
13
+ export declare function nativeFailureText(code: string | undefined): string;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The model-facing text of a failed native file operation (#907), one mapping for every native
3
+ * helper and provider (capybara-device, device-docker, device-e2b). A native helper answers
4
+ * `{ error: { code } }` with an errno name (`ENOENT`, …), `SCOPE_DENIED`, `NOT_REGULAR_FILE` or
5
+ * `INVALID_NATIVE_REQUEST`; its own exception text never reaches the model (it may carry paths or
6
+ * other details), only the kernel-defined text for the code.
7
+ */
8
+ /** The code a native helper answers when a read or write names something other than a regular file. */
9
+ export const NATIVE_NOT_REGULAR_FILE = "NOT_REGULAR_FILE";
10
+ /** The text for a code this mapping does not know. */
11
+ export const NATIVE_FAILURE_GENERIC = "Native operation failed; check the path, scope and filesystem access";
12
+ const TEXTS = {
13
+ [NATIVE_NOT_REGULAR_FILE]: "The path is not a regular file (it is a directory, a device or another special file); only regular files can be read or written",
14
+ ENOENT: "The path, or one of its parent directories, does not exist; check the path",
15
+ ENOTDIR: "A component of the path is not a directory; check the path",
16
+ EISDIR: "The path is a directory, not a file",
17
+ EEXIST: "The path already exists",
18
+ ENAMETOOLONG: "The path is too long",
19
+ ENOSPC: "The device's disk is full; free some space, then retry",
20
+ EDQUOT: "The device's disk quota is exhausted; free some space, then retry",
21
+ EROFS: "The path is on a read-only file system",
22
+ EFBIG: "The file is too large for the device's file system",
23
+ EBUSY: "The file is busy; retry the call",
24
+ ESTALE: "The file changed while it was being used; retry the call",
25
+ EIO: "The device's disk reported an input/output error",
26
+ };
27
+ /** The model-facing text for a native helper's error code. */
28
+ export function nativeFailureText(code) {
29
+ return ((code !== undefined && Object.hasOwn(TEXTS, code) ? TEXTS[code] : undefined) ??
30
+ NATIVE_FAILURE_GENERIC);
31
+ }
package/dist/net.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Guarded outbound HTTP for URLs a person supplied (`ctx.net`).
3
+ *
4
+ * Rule: a request whose host comes from a person or from config an org admin or member can set (a
5
+ * connector endpoint, an org-overridable base URL) goes through `ctx.net.fetch`, never the global
6
+ * `fetch`; a fixed vendor host, or a URL only the super admin can set, may keep `fetch`.
7
+ */
8
+ /** Why `ctx.net.fetch` refused a request (the codes of the kernel's guarded client). */
9
+ export type NetDeniedCode = "net.insecure_url" | "net.private_address" | "net.dns_failed" | "net.redirect" | "net.proxy_refused";
10
+ /**
11
+ * The request was refused by the kernel's network rules; `message` is English and names `host`.
12
+ * Detect it with {@link isNetDeniedError} (by `name`), never `instanceof`, which fails across
13
+ * package copies. Map it to the plugin's own actionable error (a connector's `ToolError`, a
14
+ * provider's `ModelError` of kind `invalid_request`).
15
+ */
16
+ export declare class NetDeniedError extends Error {
17
+ readonly code: NetDeniedCode;
18
+ readonly host: string;
19
+ /** The HTTP status of a refused redirect (`net.redirect`); absent for the other codes. */
20
+ readonly status?: number | undefined;
21
+ readonly name: "NetDeniedError";
22
+ constructor(code: NetDeniedCode, host: string, message: string,
23
+ /** The HTTP status of a refused redirect (`net.redirect`); absent for the other codes. */
24
+ status?: number | undefined);
25
+ }
26
+ /** True for a {@link NetDeniedError} from any copy of the SDK or the kernel (checked by `name`). */
27
+ export declare function isNetDeniedError(e: unknown): e is NetDeniedError;
28
+ /**
29
+ * `ctx.net`: the kernel's guarded HTTP client, no permission needed. It needs a kernel that ships
30
+ * it: a plugin that calls it raises its manifest's minimum `sdk` to the SDK release that added it.
31
+ */
32
+ export interface ExtensionNet {
33
+ /**
34
+ * The global `fetch` signature with the kernel's network rules applied: https only, except plain
35
+ * http to an origin `http://host:port` a super admin allowed for `opts.orgId`, and to loopback
36
+ * under the kernel's tests-only `net.allowInsecureLoopback`; private, loopback and link-local
37
+ * addresses refused (link-local always), the address checked when the connection is made (no
38
+ * DNS-rebinding window); the deployment's egress proxy honoured. An http URL to a host the org
39
+ * allows only as a hostname entry (https only) is refused with a message that names the
40
+ * `http://host:port` origin entry which would allow it. Redirects
41
+ * are never followed: with `redirect: "manual"` a 3xx response is returned as is, otherwise a 3xx
42
+ * rejects with `net.redirect`. Bodies stream; no size cap. `init.signal` is combined with
43
+ * `ctx.signal`.
44
+ *
45
+ * `opts.orgId` is the org the request is made for (e.g. `ConnectorOpenArgs.orgId`): only then may
46
+ * the target be one of the internal endpoints a super admin allowed for that org. Without it only
47
+ * public addresses are reachable. A refusal rejects with {@link NetDeniedError}.
48
+ */
49
+ fetch(url: string, init?: RequestInit, opts?: {
50
+ orgId?: string;
51
+ }): Promise<Response>;
52
+ }
package/dist/net.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Guarded outbound HTTP for URLs a person supplied (`ctx.net`).
3
+ *
4
+ * Rule: a request whose host comes from a person or from config an org admin or member can set (a
5
+ * connector endpoint, an org-overridable base URL) goes through `ctx.net.fetch`, never the global
6
+ * `fetch`; a fixed vendor host, or a URL only the super admin can set, may keep `fetch`.
7
+ */
8
+ /**
9
+ * The request was refused by the kernel's network rules; `message` is English and names `host`.
10
+ * Detect it with {@link isNetDeniedError} (by `name`), never `instanceof`, which fails across
11
+ * package copies. Map it to the plugin's own actionable error (a connector's `ToolError`, a
12
+ * provider's `ModelError` of kind `invalid_request`).
13
+ */
14
+ export class NetDeniedError extends Error {
15
+ code;
16
+ host;
17
+ status;
18
+ name = "NetDeniedError";
19
+ constructor(code, host, message,
20
+ /** The HTTP status of a refused redirect (`net.redirect`); absent for the other codes. */
21
+ status) {
22
+ super(message);
23
+ this.code = code;
24
+ this.host = host;
25
+ this.status = status;
26
+ }
27
+ }
28
+ /** True for a {@link NetDeniedError} from any copy of the SDK or the kernel (checked by `name`). */
29
+ export function isNetDeniedError(e) {
30
+ if (typeof e !== "object" || e === null)
31
+ return false;
32
+ const o = e;
33
+ return o.name === "NetDeniedError" && typeof o.code === "string" && typeof o.host === "string";
34
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The address classes of the sandbox network (approval-only profiles design, "Open network"): pure
3
+ * data plus {@link classifyAddress}. The device workers (macOS SRT, the Linux forwarder) and the
4
+ * cloud providers' egress proxies decide every sandboxed connection on the resolved address with
5
+ * this one table, so the classes cannot drift between them.
6
+ *
7
+ * The table ({@link ADDRESS_CLASS_RANGES}) is data a copy in another language can mirror (the Linux
8
+ * forwarder's Python): the class of an address is that of the longest-prefix range containing it.
9
+ * Every family ends with a catch-all, so the table is total.
10
+ */
11
+ /**
12
+ * The class of one IP address.
13
+ *
14
+ * - `public`: globally routable; the only class open in `open-public` mode.
15
+ * - `private`: `10/8`, `172.16/12`, `192.168/16`.
16
+ * - `cgnat`: `100.64/10`.
17
+ * - `ula`: IPv6 unique local `fc00::/7` (except the metadata address).
18
+ * - `link-local`: `169.254/16` and `fe80::/10` (except the metadata addresses).
19
+ * - `metadata`: cloud metadata endpoints (`169.254.169.254`, `fd00:ec2::254`).
20
+ * - `loopback`: `127/8`, `::1`.
21
+ * - `multicast`, `broadcast`, `unspecified` (`0/8`, `::`), `nat64` (the NAT64 prefixes),
22
+ * `reserved` (every other special-purpose range).
23
+ *
24
+ * The host's own interface addresses are not a class of the table: the worker that knows them
25
+ * closes them in addition (a placeholder in the table test).
26
+ */
27
+ export type AddressClass = "public" | "private" | "cgnat" | "ula" | "link-local" | "metadata" | "loopback" | "multicast" | "broadcast" | "unspecified" | "nat64" | "reserved";
28
+ /** Every class closed in `open-public` mode: reachable only by running outside the sandbox. */
29
+ export declare const OPEN_PUBLIC_DENIED_CLASSES: readonly AddressClass[];
30
+ /**
31
+ * One range of the address-class table. A range with `embeddedIpv4At` is an IPv6 form that carries
32
+ * an IPv4 address (v4-mapped, SIIT, v4-compatible, 6to4): the address classifies as the 32-bit IPv4
33
+ * address starting at that bit offset (from the most significant bit). The NAT64 prefixes are not
34
+ * such ranges: the design closes them whatever they embed.
35
+ */
36
+ export type AddressClassRange = {
37
+ readonly family: "ipv4" | "ipv6";
38
+ /** `address/prefix`, the address in its canonical lower-case form. */
39
+ readonly cidr: string;
40
+ readonly class: AddressClass;
41
+ } | {
42
+ readonly family: "ipv6";
43
+ readonly cidr: string;
44
+ readonly embeddedIpv4At: number;
45
+ };
46
+ /**
47
+ * The address-class table, most specific range first within each family (longest prefix wins).
48
+ * IPv4 follows the kernel's `net/public-address.ts` (and the sandbox-docker egress proxy); IPv6
49
+ * does too, plus closures the design adds: the well-known NAT64 prefixes (`64:ff9b::/96`,
50
+ * `64:ff9b:1::/48`) whatever they embed, `2001::/23` (Teredo, ORCHID and the other IETF
51
+ * assignments), `3fff::/20`, and everything outside global unicast `2000::/3`.
52
+ *
53
+ * Not covered: an operator-specific NAT64 prefix (a network-specific prefix, RFC 6052, announced
54
+ * by the local DNS64) is ordinary global unicast here, so a private IPv4 address reached through
55
+ * it classifies as public. A worker on such a network resolves through a resolver it trusts or adds
56
+ * the prefix to its own deny list.
57
+ */
58
+ export declare const ADDRESS_CLASS_RANGES: readonly AddressClassRange[];
59
+ /**
60
+ * Classifies one IPv4 or IPv6 address literal by {@link ADDRESS_CLASS_RANGES}. IPv6 may carry a
61
+ * zone (`fe80::1%en0`) and a trailing dotted IPv4 address; an IPv6 form that embeds an IPv4 address
62
+ * (v4-mapped and the others in the table) classifies as that IPv4 address, except NAT64. Throws on a
63
+ * string that is not an IP address: brackets, ports, short, octal or hex IPv4 forms, and an IPv4
64
+ * address with a zone.
65
+ */
66
+ export declare function classifyAddress(ip: string): AddressClass;
67
+ /**
68
+ * Every address closed in `open-public` mode as one CIDR list (IPv4, then IPv6), computed from
69
+ * {@link ADDRESS_CLASS_RANGES}: for a consumer that can only deny ranges (the macOS runtime's
70
+ * resolved-address deny list). Embedded forms are expanded (the v4-mapped, SIIT, v4-compatible and
71
+ * 6to4 sub-ranges of every closed IPv4 range), and adjacent closed blocks are merged. An address
72
+ * is in a listed CIDR exactly when {@link classifyAddress} gives it a closed class.
73
+ */
74
+ export declare const OPEN_PUBLIC_DENIED_CIDRS: readonly string[];
75
+ /**
76
+ * Encrypted DNS for a network whose resolver answers with fake IPs (maintainer decision
77
+ * 2026-11-19): a router running a fake-IP proxy (OpenClash and the like) intercepts every port-53
78
+ * query and answers each name with an address in {@link fakeIpCidr} (`198.18.0.0/15`, a reserved
79
+ * class), so in open mode every name would resolve to a closed address. When the system
80
+ * resolver's answer for a name contains such an address, a sandbox egress proxy re-resolves the
81
+ * name (A and AAAA) through DNS-over-HTTPS (RFC 8484, GET, wire format) at these IP-literal
82
+ * endpoints, in order (Cloudflare, then Google as the fallback), verifying TLS against the
83
+ * endpoint's IP SAN so no DNS is needed to reach them. {@link timeoutMs} is one overall deadline
84
+ * per name, covering A and AAAA and every endpoint; each endpoint gets its share of the time left.
85
+ * An answer is cached only when both queries succeeded, for its TTL, at most
86
+ * {@link cacheTtlCapSeconds}, and for at most {@link cacheMaxNames} names. The real address is
87
+ * classified like any resolved address and dialled as checked. When encrypted DNS fails the
88
+ * connection is refused, naming the fake-IP resolver; the fake address is never dialled. The same
89
+ * rule applies to an allowlisted name. Shared by the macOS worker and the Linux forwarder, so both
90
+ * keep identical endpoints and limits.
91
+ */
92
+ export declare const SANDBOX_FAKE_IP_DNS: {
93
+ readonly fakeIpCidr: string;
94
+ readonly endpoints: readonly string[];
95
+ readonly timeoutMs: number;
96
+ readonly cacheTtlCapSeconds: number;
97
+ readonly cacheMaxNames: number;
98
+ };