@capybara-hq/plugin-sdk 0.1.0-rc.31 → 0.1.0-rc.33

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.
@@ -12,4 +12,6 @@ Contract: FilePreviewProvider (`file-preview.ts`)
12
12
 
13
13
  Declare which file types you can preview and render them through schema views or an approved embed. Enabled per org.
14
14
 
15
+ `render` args are a union on `source`: `"conversation"` (org, account, conversation) or `"share"` (org and share id; `file.id` is the share id; no account or conversation). A previewer that needs the conversation declines `source: "share"` by throwing; the kernel reports the failure and the share page falls to the next previewer. A share token is valid only for the `file.preview` slot, never for `/api`.
16
+
15
17
  See `extensions` for the rules every extension follows.
package/dist/ctx.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { Kysely } from "kysely";
2
2
  import type { ExtensionPointRef } from "./extension-point.js";
3
3
  import type { AvailableHook, HookHandler, HookOptions } from "./hooks.js";
4
4
  import type { RouteCaller } from "./http-access.js";
5
- import type { ModelEmbeddingInfo, ModelKind } from "./model.js";
5
+ import type { ImageAspectRatio, ImageMediaType, ImageSize, ModelEmbeddingInfo, ModelImageGenerationInfo, ModelKind } from "./model.js";
6
6
  import type { ExtensionNet } from "./net.js";
7
7
  import type { SetupCheckDefinition } from "./setup-check.js";
8
8
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
@@ -94,6 +94,39 @@ export interface ExtensionEmbedResult {
94
94
  };
95
95
  dimensions: number;
96
96
  }
97
+ /** A `ctx.models.generateImage` request: images generated for one org with the model of a purpose. */
98
+ export interface ExtensionImageGenerateRequest {
99
+ orgId: string;
100
+ /** A purpose this extension declared in `permissions.models` with `kind: "image_generation"`. */
101
+ purpose: string;
102
+ prompt: string;
103
+ /** An exact size the model offers; rejected otherwise. Wins over `aspectRatio`. */
104
+ size?: ImageSize;
105
+ /** The closest size the model offers; the model's default size when neither is given. */
106
+ aspectRatio?: ImageAspectRatio;
107
+ /** Images to produce (default 1, at most the model's `maxImages`). */
108
+ n?: number;
109
+ /** Base64 reference images, at most the model's `maxReferenceImages`. */
110
+ referenceImages?: {
111
+ mediaType: ImageMediaType;
112
+ data: string;
113
+ }[];
114
+ /** Aborts this call; combined with `ctx.signal`. */
115
+ signal?: AbortSignal;
116
+ }
117
+ /** A `ctx.models.generateImage` result. */
118
+ export interface ExtensionImageGenerateResult {
119
+ images: {
120
+ mediaType: ImageMediaType;
121
+ data: string;
122
+ }[];
123
+ revisedPrompt?: string;
124
+ model: {
125
+ provider: string;
126
+ id: string;
127
+ };
128
+ size: ImageSize;
129
+ }
97
130
  /** The model a purpose maps to in an org (`ctx.models.describe`). */
98
131
  export interface ExtensionModelTarget {
99
132
  provider: string;
@@ -101,13 +134,16 @@ export interface ExtensionModelTarget {
101
134
  kind: ModelKind;
102
135
  /** Present for an embedding model. */
103
136
  embedding?: ModelEmbeddingInfo;
137
+ /** Present for an image generation model. */
138
+ imageGeneration?: ModelImageGenerationInfo;
104
139
  }
105
140
  /**
106
141
  * Models by purpose (`permissions.models`): the purpose → model mapping is chosen by org admins
107
142
  * (and the deployment default by the super admin), never by the extension. Only purposes this
108
- * extension declared with `kind: "embedding"` are accepted (`model.purpose_unknown` otherwise), and
143
+ * extension declared with a matching `kind` (`embedding` for `embed`, `image_generation` for
144
+ * `generateImage`) are accepted (`model.purpose_unknown` otherwise), and
109
145
  * only for an org that enabled the extension (`extension.not_enabled`). Usage is recorded by the
110
- * kernel and reported through `usage.report` (purpose `embedding`).
146
+ * kernel and reported through `usage.report` (purpose `embedding`, or `image` for `generateImage`).
111
147
  */
112
148
  export interface ExtensionModels {
113
149
  /**
@@ -120,6 +156,14 @@ export interface ExtensionModels {
120
156
  * extension route), and nothing is sent or billed.
121
157
  */
122
158
  embed(req: ExtensionEmbedRequest): Promise<ExtensionEmbedResult>;
159
+ /**
160
+ * Generates images with the org's effective model for `purpose`. Rejects with
161
+ * `model.unconfigured` when the purpose maps to no usable model, `validation_failed` for a size,
162
+ * count or reference count the model does not offer, and a `ModelError` when the provider fails
163
+ * (kind `refusal` when it declines the prompt). Not retried. Fires `model.request` first
164
+ * (`purpose: "image"`); a policy denial rejects with `model.hook_denied`.
165
+ */
166
+ generateImage(req: ExtensionImageGenerateRequest): Promise<ExtensionImageGenerateResult>;
123
167
  /** The org's effective model for `purpose`, or null when it maps to no model the org can use. */
124
168
  describe(req: {
125
169
  orgId: string;
@@ -34,14 +34,12 @@ export interface FilePreviewer {
34
34
  export interface FilePreviewProvider {
35
35
  previewers: FilePreviewer[];
36
36
  }
37
- /** Arguments of {@link FilePreviewer.render}; identities come from the kernel after authentication. */
38
- export interface FilePreviewArgs {
39
- orgId: string;
40
- accountId: string;
41
- conversationId: string;
37
+ /** What every {@link FilePreviewArgs} variant carries. */
38
+ export interface FilePreviewArgsBase {
42
39
  locale: Locale;
43
40
  /** Aborted at the kernel's time limit: stop reading and rendering. */
44
41
  signal: AbortSignal;
42
+ /** In the share variant `file.id` is the share id. */
45
43
  file: {
46
44
  id: string;
47
45
  name: string;
@@ -62,6 +60,25 @@ export interface FilePreviewArgs {
62
60
  */
63
61
  config?: unknown;
64
62
  }
63
+ /** A preview inside a conversation; identities come from the kernel after authentication. */
64
+ export interface FilePreviewConversationArgs extends FilePreviewArgsBase {
65
+ source: "conversation";
66
+ orgId: string;
67
+ accountId: string;
68
+ conversationId: string;
69
+ }
70
+ /**
71
+ * A preview on a share page: there is no account and no conversation. A previewer that needs the
72
+ * conversation declines this variant by throwing; the kernel reports the failure and the page falls
73
+ * to the next previewer.
74
+ */
75
+ export interface FilePreviewShareArgs extends FilePreviewArgsBase {
76
+ source: "share";
77
+ orgId: string;
78
+ shareId: string;
79
+ }
80
+ /** Arguments of {@link FilePreviewer.render}: narrow on `source`. */
81
+ export type FilePreviewArgs = FilePreviewConversationArgs | FilePreviewShareArgs;
65
82
  /** Checks a `file-preview@1` provider; returns the problems (empty = valid). */
66
83
  export declare function validateFilePreviewProvider(p: unknown): string[];
67
84
  /** Whether a previewer takes this file: its type or extension is accepted and it is within `maxBytes`. */
package/dist/hooks.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ContentBlock, ModelRequest, ModelUsage } from "./model.js";
1
+ import type { ContentBlock, ImageSize, ModelRequest, ModelUsage } from "./model.js";
2
2
  /**
3
3
  * Hook mount points a plugin can register on through `ctx.hooks.on` (from M7). The other names in
4
4
  * `HOOK_MOUNT_POINTS` (`session.*`, `agent.preStep`) stay reserved: they validate in a manifest but
@@ -41,7 +41,7 @@ export interface HookScope {
41
41
  * `WebFetch` tool, `review` is the command-review classifier's call (`review` purpose, no run
42
42
  * step; absent = no classifier).
43
43
  */
44
- export type ModelCallPurpose = "step" | "compaction" | "title" | "web_fetch" | "review";
44
+ export type ModelCallPurpose = "step" | "compaction" | "title" | "web_fetch" | "review" | "image";
45
45
  /**
46
46
  * What a reported or requested model call was for: the {@link ModelCallPurpose} values, or
47
47
  * `embedding` for an embedding call an extension made through `ctx.models` (`usage.report`, and
@@ -92,7 +92,7 @@ export type HookModelRequest = Omit<ModelRequest, "messages"> & {
92
92
  * ({@link HookMediaPlaceholder}): no media bytes, no attachment ids.
93
93
  */
94
94
  export interface ModelCallRequestHookPayload extends HookScope {
95
- purpose: ModelCallPurpose;
95
+ purpose: Exclude<ModelCallPurpose, "image">;
96
96
  step: number;
97
97
  attempt: number;
98
98
  provider: string;
@@ -130,22 +130,81 @@ export interface EmbeddingRequestHookPayload {
130
130
  runId?: undefined;
131
131
  parent?: undefined;
132
132
  }
133
+ /**
134
+ * `model.request` of an image generation call (`purpose: "image"`): once per `GenerateImage` tool
135
+ * call (conversation fields set) or `ctx.models.generateImage` call (`extension` and `imagePurpose`
136
+ * set, conversation fields absent). Reference images are placeholders: no bytes. A policy denial
137
+ * sends nothing and records no usage.
138
+ */
139
+ export interface ImageRequestHookPayload {
140
+ purpose: "image";
141
+ orgId: string;
142
+ provider: string;
143
+ model: string;
144
+ prompt: string;
145
+ size: ImageSize;
146
+ n: number;
147
+ referenceImages: HookMediaPlaceholder[];
148
+ /** Conversation call: */
149
+ accountId?: string;
150
+ agentId?: string;
151
+ agentVersion?: number;
152
+ conversationId?: string;
153
+ runId?: string;
154
+ parent?: HookParentScope;
155
+ step?: number;
156
+ callId?: string;
157
+ /** Extension call: */
158
+ extension?: string;
159
+ imagePurpose?: string;
160
+ }
161
+ /**
162
+ * `model.response` of an image generation call: after it finished or failed. Same identity fields
163
+ * as {@link ImageRequestHookPayload}; images carry only their media type and byte size.
164
+ */
165
+ export interface ImageResponseHookPayload {
166
+ purpose: "image";
167
+ orgId: string;
168
+ provider: string;
169
+ model: string;
170
+ accountId?: string;
171
+ agentId?: string;
172
+ agentVersion?: number;
173
+ conversationId?: string;
174
+ runId?: string;
175
+ parent?: HookParentScope;
176
+ step?: number;
177
+ callId?: string;
178
+ extension?: string;
179
+ imagePurpose?: string;
180
+ outcome: "ok" | "failed";
181
+ images: {
182
+ mediaType: string;
183
+ size: number;
184
+ }[];
185
+ revisedPrompt?: string;
186
+ usage: ModelUsage | null;
187
+ latencyMs: number;
188
+ errorCode?: string;
189
+ }
133
190
  /**
134
191
  * `model.request`: before a model call is sent. A policy hook may deny it. Either a chat model call
135
192
  * ({@link ModelCallRequestHookPayload}: steps, compaction, titles, `WebFetch`) or an extension's
136
- * embedding call ({@link EmbeddingRequestHookPayload}, `purpose: "embedding"`); tell them apart by
193
+ * embedding call ({@link EmbeddingRequestHookPayload}, `purpose: "embedding"`) or an image generation
194
+ * call ({@link ImageRequestHookPayload}, `purpose: "image"`); tell them apart by
137
195
  * `purpose`. Handlers must accept the absent conversation fields of an embedding call (a policy
138
196
  * hook that throws on one denies the call). Payloads carry no media bytes.
139
197
  */
140
- export type ModelRequestHookPayload = ModelCallRequestHookPayload | EmbeddingRequestHookPayload;
198
+ export type ModelRequestHookPayload = ModelCallRequestHookPayload | EmbeddingRequestHookPayload | ImageRequestHookPayload;
141
199
  /**
142
200
  * `model.response`: after a sent model call finished or failed, with its usage when known (step
143
201
  * attempts, compaction and title calls, see `purpose`). Not fired for a call the user aborted (the run was
144
202
  * stopped while the call was in flight), nor for a call that was never sent (denied, or failed
145
- * before sending), so a `model.request` can have no matching `model.response`.
203
+ * before sending), so a `model.request` can have no matching `model.response`. The mount's payload
204
+ * is this or, for an image generation call, an {@link ImageResponseHookPayload}.
146
205
  */
147
206
  export interface ModelResponseHookPayload extends HookScope {
148
- purpose: ModelCallPurpose;
207
+ purpose: Exclude<ModelCallPurpose, "image">;
149
208
  step: number;
150
209
  attempt: number;
151
210
  provider: string;
@@ -237,7 +296,7 @@ export interface OrgDeletedPayload {
237
296
  /** Payload type of each mount point. */
238
297
  export interface HookPayloads {
239
298
  "model.request": ModelRequestHookPayload;
240
- "model.response": ModelResponseHookPayload;
299
+ "model.response": ModelResponseHookPayload | ImageResponseHookPayload;
241
300
  "tool.preExecute": ToolPreHookPayload;
242
301
  "tool.postExecute": ToolPostHookPayload;
243
302
  "usage.report": UsageReportPayload;
@@ -43,6 +43,16 @@ export type RouteCaller = {
43
43
  contribution: string;
44
44
  /** The token's expiry (Unix seconds): a long-lived response (SSE) ends by then. */
45
45
  exp: number;
46
+ } | {
47
+ /** A share page's `file.preview` embed: no account, no role. */
48
+ access: "embed";
49
+ scope: "share";
50
+ orgId: string;
51
+ shareId: string;
52
+ contribution: string;
53
+ /** The token's expiry (Unix seconds): a long-lived response (SSE) ends by then. */
54
+ exp: number;
55
+ config: unknown;
46
56
  } | {
47
57
  access: "member" | "admin";
48
58
  orgId: string;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.31";
1
+ export declare const SDK_VERSION = "0.1.0-rc.33";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./bootstrap.js";
4
4
  export * from "./cards.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.31";
1
+ export const SDK_VERSION = "0.1.0-rc.33";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./bootstrap.js";
4
4
  export * from "./cards.js";
package/dist/model.d.ts CHANGED
@@ -6,7 +6,10 @@
6
6
  import type { ModelCallPurpose } from "./hooks.js";
7
7
  import type { ModelParameter, ParamValue } from "./model-params.js";
8
8
  import type { LocalizedName } from "./plugin-package.js";
9
- /** What a model does. Absent on a `ModelInfo` means `chat`. */
9
+ /**
10
+ * What a model does. Absent on a `ModelInfo` means `chat`. Callable kinds: `chat` (`stream`),
11
+ * `embedding` (`embed`) and `image_generation` (`generateImage`); the others are list-only.
12
+ */
10
13
  export type ModelKind = "chat" | "embedding" | "rerank" | "image_generation" | "video_generation" | "speech_to_text" | "text_to_speech";
11
14
  /** Embedding facts of a model whose `kind` is `embedding`. */
12
15
  export interface ModelEmbeddingInfo {
@@ -18,6 +21,27 @@ export interface ModelEmbeddingInfo {
18
21
  /** Most inputs one `embed` call may carry. */
19
22
  maxBatch: number;
20
23
  }
24
+ /** An output size of an image generation model, in pixels. */
25
+ export interface ImageSize {
26
+ width: number;
27
+ height: number;
28
+ }
29
+ /** The aspect ratios a caller may ask for instead of an exact size. */
30
+ export declare const IMAGE_ASPECT_RATIOS: readonly ["1:1", "4:3", "3:4", "3:2", "2:3", "16:9", "9:16"];
31
+ export type ImageAspectRatio = (typeof IMAGE_ASPECT_RATIOS)[number];
32
+ /** Image generation facts of a model whose `kind` is `image_generation`. */
33
+ export interface ModelImageGenerationInfo {
34
+ /** The output sizes the model offers. */
35
+ sizes: ImageSize[];
36
+ /** One of `sizes`, used when the caller asks for none. */
37
+ defaultSize: ImageSize;
38
+ /** Most images one `generateImage` call may produce. */
39
+ maxImages: number;
40
+ /** Most reference images one call may carry (0 = text to image only). */
41
+ maxReferenceImages: number;
42
+ /** The media types the model returns. */
43
+ outputMediaTypes: ImageMediaType[];
44
+ }
21
45
  export interface ModelInfo {
22
46
  id: string;
23
47
  displayName: string;
@@ -31,6 +55,8 @@ export interface ModelInfo {
31
55
  retiresAt?: string;
32
56
  /** Set when `kind` is `embedding`. */
33
57
  embedding?: ModelEmbeddingInfo;
58
+ /** Set when `kind` is `image_generation`. */
59
+ imageGeneration?: ModelImageGenerationInfo;
34
60
  contextWindow: number;
35
61
  maxOutputTokens: number;
36
62
  capabilities: {
@@ -255,6 +281,8 @@ export interface ModelUsage {
255
281
  cacheReadTokens: number;
256
282
  /** Input tokens written to the prompt cache in this call. */
257
283
  cacheWriteTokens: number;
284
+ /** Images produced (image generation calls). */
285
+ outputImages?: number;
258
286
  }
259
287
  export type ModelStreamEvent = {
260
288
  type: "text_delta";
@@ -268,7 +296,7 @@ export type ModelStreamEvent = {
268
296
  stopReason: StopReason;
269
297
  usage: ModelUsage;
270
298
  };
271
- export type ModelErrorKind = "rate_limited" | "overloaded" | "server" | "timeout" | "network" | "auth" | "invalid_request" | "context_overflow" | "aborted";
299
+ export type ModelErrorKind = "rate_limited" | "overloaded" | "server" | "timeout" | "network" | "auth" | "invalid_request" | "context_overflow" | "refusal" | "aborted";
272
300
  /** True for rate_limited / overloaded / server / timeout / network. */
273
301
  export declare function isRetryableKind(kind: ModelErrorKind): boolean;
274
302
  /**
@@ -316,6 +344,54 @@ export interface EmbedResult {
316
344
  * valid, else the reason: wrong vector count, wrong dimension, or a non-finite number.
317
345
  */
318
346
  export declare function validateEmbedResult(req: EmbedRequest, info: ModelEmbeddingInfo, res: EmbedResult): string | null;
347
+ export interface ImageGenerateRequest {
348
+ model: string;
349
+ prompt: string;
350
+ /** One of the model's `imageGeneration.sizes`. */
351
+ size: ImageSize;
352
+ /** Images to produce, 1 to `imageGeneration.maxImages`. */
353
+ n: number;
354
+ /** Base64 reference images, at most `imageGeneration.maxReferenceImages`. */
355
+ referenceImages?: {
356
+ mediaType: ImageMediaType;
357
+ data: string;
358
+ }[];
359
+ params: Record<string, ParamValue>;
360
+ }
361
+ export interface ImageGenerateResult {
362
+ /** Exactly `req.n` images, base64 encoded. */
363
+ images: {
364
+ mediaType: ImageMediaType;
365
+ data: string;
366
+ }[];
367
+ /** The prompt as the vendor rewrote it, when it did. */
368
+ revisedPrompt?: string;
369
+ usage: ModelUsage;
370
+ }
371
+ /** True when `x` is a well-formed {@link ModelImageGenerationInfo}. */
372
+ export declare function isValidImageGenerationInfo(x: unknown): x is ModelImageGenerationInfo;
373
+ /**
374
+ * Checks an image generation result against its request and the model's facts. Returns null when
375
+ * valid, else the reason: wrong image count, an undeclared media type, data that is not base64,
376
+ * or a `usage` that is not an object whose token counts (and `outputImages`, when present) are
377
+ * non-negative integers (a caller records usage from it, so it is checked before anything is).
378
+ */
379
+ export declare function validateImageGenerateResult(req: ImageGenerateRequest, info: ModelImageGenerationInfo, res: unknown): string | null;
380
+ /**
381
+ * Chooses an output size: an exact `size` must be one the model offers; an `aspectRatio` picks the
382
+ * closest declared ratio (ties by area closest to the default's, then declaration order); neither
383
+ * gives the default size.
384
+ */
385
+ export declare function pickImageSize(info: ModelImageGenerationInfo, opts: {
386
+ size?: ImageSize;
387
+ aspectRatio?: ImageAspectRatio;
388
+ }): {
389
+ ok: true;
390
+ size: ImageSize;
391
+ } | {
392
+ ok: false;
393
+ error: string;
394
+ };
319
395
  /** The `model-provider@2` implementation. */
320
396
  export interface ModelProvider {
321
397
  /**
@@ -331,6 +407,13 @@ export interface ModelProvider {
331
407
  embed?(req: EmbedRequest, opts: {
332
408
  signal: AbortSignal;
333
409
  } & ModelCallOptions): Promise<EmbedResult>;
410
+ /**
411
+ * Present only on a provider that lists `image_generation` models. Throws `ModelError` of kind
412
+ * `refusal` when the vendor declines the prompt.
413
+ */
414
+ generateImage?(req: ImageGenerateRequest, opts: {
415
+ signal: AbortSignal;
416
+ } & ModelCallOptions): Promise<ImageGenerateResult>;
334
417
  }
335
418
  /** The model provider extension point (the only version since `@1` was removed before 0.1.0). */
336
419
  export declare const MODEL_PROVIDER_EXTENSION_POINT_V2 = "model-provider@2";
package/dist/model.js CHANGED
@@ -1,3 +1,5 @@
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"];
1
3
  /** Types accepted by image blocks. */
2
4
  export const IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
3
5
  /** Types accepted by document blocks. */
@@ -141,6 +143,7 @@ const ALL_KINDS = new Set([
141
143
  "auth",
142
144
  "invalid_request",
143
145
  "context_overflow",
146
+ "refusal",
144
147
  "aborted",
145
148
  ]);
146
149
  const RETRYABLE = new Set([
@@ -200,5 +203,105 @@ export function validateEmbedResult(req, info, res) {
200
203
  }
201
204
  return null;
202
205
  }
206
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
207
+ /** True when `x` is a well-formed {@link ModelImageGenerationInfo}. */
208
+ export function isValidImageGenerationInfo(x) {
209
+ if (typeof x !== "object" || x === null)
210
+ return false;
211
+ const o = x;
212
+ const isSize = (s) => typeof s === "object" &&
213
+ s !== null &&
214
+ Number.isInteger(s.width) &&
215
+ Number.isInteger(s.height) &&
216
+ s.width > 0 &&
217
+ s.height > 0;
218
+ if (!Array.isArray(o.sizes) || o.sizes.length === 0 || !o.sizes.every(isSize))
219
+ return false;
220
+ if (!isSize(o.defaultSize))
221
+ return false;
222
+ const d = o.defaultSize;
223
+ if (!o.sizes.some((s) => s.width === d.width && s.height === d.height))
224
+ return false;
225
+ if (!Number.isInteger(o.maxImages) || o.maxImages < 1)
226
+ return false;
227
+ if (!Number.isInteger(o.maxReferenceImages) || o.maxReferenceImages < 0) {
228
+ return false;
229
+ }
230
+ return (Array.isArray(o.outputMediaTypes) &&
231
+ o.outputMediaTypes.length > 0 &&
232
+ o.outputMediaTypes.every((t) => IMAGE_MEDIA_TYPES.includes(t)));
233
+ }
234
+ /**
235
+ * Checks an image generation result against its request and the model's facts. Returns null when
236
+ * valid, else the reason: wrong image count, an undeclared media type, data that is not base64,
237
+ * or a `usage` that is not an object whose token counts (and `outputImages`, when present) are
238
+ * non-negative integers (a caller records usage from it, so it is checked before anything is).
239
+ */
240
+ export function validateImageGenerateResult(req, info, res) {
241
+ const images = res?.images;
242
+ if (!Array.isArray(images))
243
+ return "result has no images array";
244
+ if (images.length !== req.n)
245
+ return `expected ${req.n} images, got ${images.length}`;
246
+ for (let i = 0; i < images.length; i++) {
247
+ const img = images[i];
248
+ const type = img?.mediaType;
249
+ if (typeof type !== "string" || !info.outputMediaTypes.includes(type)) {
250
+ return `image ${i} has media type ${String(type)}, not one of ${info.outputMediaTypes.join(", ")}`;
251
+ }
252
+ if (typeof img?.data !== "string" || !BASE64.test(img.data)) {
253
+ return `image ${i} data is not base64`;
254
+ }
255
+ }
256
+ const usage = res.usage;
257
+ if (typeof usage !== "object" || usage === null)
258
+ return "result has no usage object";
259
+ const u = usage;
260
+ const count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
261
+ for (const field of ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"]) {
262
+ if (!count(u[field]))
263
+ return `usage.${field} is ${String(u[field])}, not a non-negative integer`;
264
+ }
265
+ if (u.outputImages !== undefined && !count(u.outputImages)) {
266
+ return `usage.outputImages is ${String(u.outputImages)}, not a non-negative integer`;
267
+ }
268
+ return null;
269
+ }
270
+ /**
271
+ * Chooses an output size: an exact `size` must be one the model offers; an `aspectRatio` picks the
272
+ * closest declared ratio (ties by area closest to the default's, then declaration order); neither
273
+ * gives the default size.
274
+ */
275
+ export function pickImageSize(info, opts) {
276
+ const fmt = (s) => `${s.width}x${s.height}`;
277
+ const { size, aspectRatio } = opts;
278
+ if (size) {
279
+ const hit = info.sizes.find((s) => s.width === size.width && s.height === size.height);
280
+ if (hit)
281
+ return { ok: true, size: hit };
282
+ return {
283
+ ok: false,
284
+ error: `Size ${fmt(size)} is not offered by this model; use one of ${info.sizes.map(fmt).join(", ")}.`,
285
+ };
286
+ }
287
+ if (!aspectRatio)
288
+ return { ok: true, size: info.defaultSize };
289
+ const [rw, rh] = aspectRatio.split(":").map(Number);
290
+ const target = Math.log(rw / rh);
291
+ const area = info.defaultSize.width * info.defaultSize.height;
292
+ let best = info.defaultSize;
293
+ let bestDiff = Number.POSITIVE_INFINITY;
294
+ let bestArea = Number.POSITIVE_INFINITY;
295
+ for (const s of info.sizes) {
296
+ const diff = Math.abs(Math.log(s.width / s.height) - target);
297
+ const areaDiff = Math.abs(s.width * s.height - area);
298
+ if (diff < bestDiff - 1e-9 || (Math.abs(diff - bestDiff) <= 1e-9 && areaDiff < bestArea)) {
299
+ best = s;
300
+ bestDiff = diff;
301
+ bestArea = areaDiff;
302
+ }
303
+ }
304
+ return { ok: true, size: best };
305
+ }
203
306
  /** The model provider extension point (the only version since `@1` was removed before 0.1.0). */
204
307
  export const MODEL_PROVIDER_EXTENSION_POINT_V2 = "model-provider@2";
@@ -21,11 +21,12 @@ export interface ExtensionPermissions {
21
21
  policyHooks?: PolicyHook[];
22
22
  /**
23
23
  * Model purposes (`ctx.models`): each key must be `<extension name>.<name>`; an org admin maps
24
- * each to a model of its `kind`. `ctx.models.embed` / `describe` accept the `embedding` ones.
24
+ * each to a model of its `kind`. `ctx.models.embed` accepts the `embedding` ones, `generateImage`
25
+ * the `image_generation` ones.
25
26
  */
26
27
  models?: {
27
28
  purpose: string;
28
- kind: "chat" | "embedding";
29
+ kind: "chat" | "embedding" | "image_generation";
29
30
  label: {
30
31
  zh: string;
31
32
  en: string;
@@ -180,13 +180,13 @@ export function validatePermissions(plugin, p) {
180
180
  const label = isObj(m) && isObj(m.label) ? m.label : undefined;
181
181
  if (!isObj(m) ||
182
182
  typeof m.purpose !== "string" ||
183
- (m.kind !== "chat" && m.kind !== "embedding") ||
183
+ (m.kind !== "chat" && m.kind !== "embedding" && m.kind !== "image_generation") ||
184
184
  !label ||
185
185
  typeof label.zh !== "string" ||
186
186
  label.zh === "" ||
187
187
  typeof label.en !== "string" ||
188
188
  label.en === "") {
189
- errs.push("permissions.models entries need purpose, kind chat/embedding and label zh/en");
189
+ errs.push("permissions.models entries need purpose, kind chat/embedding/image_generation, label zh/en");
190
190
  continue;
191
191
  }
192
192
  if (!m.purpose.startsWith(`${plugin}.`) || m.purpose.length === plugin.length + 1) {
package/dist/ui.d.ts CHANGED
@@ -270,10 +270,9 @@ export type UiActionResult = {
270
270
  } | {
271
271
  view: UiView;
272
272
  };
273
- /** The embed claims both scopes share. `exp` is Unix seconds. */
273
+ /** The embed claims every scope shares. `exp` is Unix seconds. */
274
274
  export interface EmbedClaimsBase {
275
275
  plugin: string;
276
- accountId: string;
277
276
  contribution: string;
278
277
  exp: number;
279
278
  }
@@ -281,6 +280,7 @@ export interface EmbedClaimsBase {
281
280
  export interface OrgEmbedClaims extends EmbedClaimsBase {
282
281
  scope: "org";
283
282
  orgId: string;
283
+ accountId: string;
284
284
  /**
285
285
  * The caller's role: written at issuance; `ctx.ui.verifyEmbedToken` returns the current role at
286
286
  * validation time.
@@ -295,18 +295,33 @@ export interface OrgEmbedClaims extends EmbedClaimsBase {
295
295
  /** A `platform.page` embed token's claims: a super admin's, with no org, conversation, agent or file. */
296
296
  export interface PlatformEmbedClaims extends EmbedClaimsBase {
297
297
  scope: "platform";
298
+ accountId: string;
298
299
  orgId?: undefined;
299
300
  role: "superAdmin";
300
301
  conversationId?: undefined;
301
302
  agentId?: undefined;
302
303
  fileId?: undefined;
303
304
  }
305
+ /**
306
+ * A share page's `file.preview` embed token's claims: no account and no role, only the org, the
307
+ * share and the share's generation. Valid only for the `file.preview` slot, never for `/api`.
308
+ */
309
+ export interface ShareEmbedClaims extends EmbedClaimsBase {
310
+ scope: "share";
311
+ orgId: string;
312
+ shareId: string;
313
+ generation: number;
314
+ accountId?: undefined;
315
+ role?: undefined;
316
+ conversationId?: undefined;
317
+ agentId?: undefined;
318
+ fileId?: undefined;
319
+ }
304
320
  /**
305
321
  * Claims in an embed token (trustworthy after validation by `ctx.ui.verifyEmbedToken`): narrow on
306
- * `scope` (`"platform"` has no
307
- * `orgId` and `role` `"superAdmin"`).
322
+ * `scope` (`"platform"` has no `orgId` and `role` `"superAdmin"`; `"share"` has no account or role).
308
323
  */
309
- export type EmbedClaims = OrgEmbedClaims | PlatformEmbedClaims;
324
+ export type EmbedClaims = OrgEmbedClaims | PlatformEmbedClaims | ShareEmbedClaims;
310
325
  /**
311
326
  * The version marker of the `postMessage` protocol between the outer page and the embedded iframe.
312
327
  */
@@ -314,7 +329,7 @@ export declare const EMBED_PROTOCOL = "capybara-embed/1";
314
329
  /**
315
330
  * What an embed's `init` says about where it is shown, narrowed on `scope` like {@link EmbedClaims}:
316
331
  * an org's page, panel, section or previewer (`orgId`, and the conversation when there is one), or
317
- * a platform page of the admin console (no org).
332
+ * a platform page of the admin console (no org), or a share page (no org or conversation).
318
333
  */
319
334
  export type EmbedInitContext = {
320
335
  scope: "org";
@@ -324,6 +339,10 @@ export type EmbedInitContext = {
324
339
  scope: "platform";
325
340
  orgId?: undefined;
326
341
  conversationId?: undefined;
342
+ } | {
343
+ scope: "share";
344
+ orgId?: undefined;
345
+ conversationId?: undefined;
327
346
  };
328
347
  /** Messages the outer page sends to the iframe. */
329
348
  export type EmbedParentMessage = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.31",
3
+ "version": "0.1.0-rc.33",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {