@capybara-hq/kernel 0.1.0-rc.42 → 0.1.0-rc.43

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 (49) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/config/schema.d.ts +3 -0
  3. package/dist/config/schema.js +30 -0
  4. package/dist/conversations/events.d.ts +3 -0
  5. package/dist/conversations/events.js +7 -3
  6. package/dist/ctx/create-ctx.d.ts +12 -5
  7. package/dist/ctx/create-ctx.js +21 -5
  8. package/dist/db/kernel-schema.d.ts +10 -0
  9. package/dist/extensions/host.d.ts +4 -1
  10. package/dist/extensions/host.js +10 -6
  11. package/dist/infra/config/kernel-config.service.js +4 -0
  12. package/dist/models/image-usable.d.ts +22 -0
  13. package/dist/models/image-usable.js +29 -0
  14. package/dist/models/images.d.ts +125 -0
  15. package/dist/models/images.js +440 -0
  16. package/dist/models/models.module.d.ts +3 -2
  17. package/dist/models/models.module.js +16 -5
  18. package/dist/models/org-models.schemas.js +1 -0
  19. package/dist/models/purposes.controller.d.ts +7 -0
  20. package/dist/models/purposes.controller.js +9 -0
  21. package/dist/models/purposes.d.ts +28 -3
  22. package/dist/models/purposes.js +40 -13
  23. package/dist/platform/ops/models.ops.js +10 -0
  24. package/dist/runtime/hook-calls.d.ts +11 -1
  25. package/dist/runtime/hook-calls.js +24 -1
  26. package/dist/runtime/providers.d.ts +9 -5
  27. package/dist/runtime/providers.js +22 -3
  28. package/dist/runtime/usage-report.d.ts +10 -6
  29. package/dist/runtime/usage-report.js +31 -11
  30. package/dist/sandbox/review/permission-candidate.js +22 -6
  31. package/dist/sandbox/review/review.service.d.ts +1 -1
  32. package/dist/sandbox/review/review.service.js +43 -12
  33. package/dist/tools/builtin-names.d.ts +3 -1
  34. package/dist/tools/builtin-names.js +5 -1
  35. package/dist/tools/builtins/artifacts.d.ts +43 -0
  36. package/dist/tools/builtins/artifacts.js +67 -0
  37. package/dist/tools/builtins/builtin-tools.d.ts +4 -0
  38. package/dist/tools/builtins/builtin-tools.js +28 -5
  39. package/dist/tools/builtins/image/generate.d.ts +59 -0
  40. package/dist/tools/builtins/image/generate.js +535 -0
  41. package/dist/tools/builtins/image/index.d.ts +2 -0
  42. package/dist/tools/builtins/image/index.js +2 -0
  43. package/dist/tools/builtins/image/paths.d.ts +12 -0
  44. package/dist/tools/builtins/image/paths.js +26 -0
  45. package/dist/tools/builtins/sandbox/deliver.js +7 -49
  46. package/dist/tools/pipeline.js +15 -7
  47. package/dist/tools/tools.module.js +3 -0
  48. package/package.json +3 -3
  49. package/src/migrations/0160_model_usage_image_kind.sql +10 -0
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.31";
191
+ readonly sdk: "0.1.0-rc.32";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -281,6 +281,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
281
281
  models: z.ZodPrefault<z.ZodObject<{
282
282
  listTimeoutMs: z.ZodDefault<z.ZodNumber>;
283
283
  embedTimeoutMs: z.ZodDefault<z.ZodNumber>;
284
+ imageTimeoutMs: z.ZodDefault<z.ZodNumber>;
285
+ imageMaxPerCall: z.ZodDefault<z.ZodNumber>;
286
+ imagePromptMaxChars: z.ZodDefault<z.ZodNumber>;
284
287
  }, z.core.$strict>>;
285
288
  hooks: z.ZodPrefault<z.ZodObject<{
286
289
  timeoutMs: z.ZodDefault<z.ZodNumber>;
@@ -1667,6 +1667,36 @@ export const KernelConfigSchema = z.strictObject({
1667
1667
  hot: true,
1668
1668
  description: "Time limit in milliseconds for one embed call to a model provider (one batch of an extension's ctx.models.embed); the call is aborted and fails with a timeout model error",
1669
1669
  })),
1670
+ imageTimeoutMs: z
1671
+ .number()
1672
+ .int()
1673
+ .positive()
1674
+ .max(600_000)
1675
+ .default(300_000)
1676
+ .meta(meta({
1677
+ hot: true,
1678
+ description: "Time limit in milliseconds for one image generation call to a model provider (polling included); the call is aborted and fails with a timeout model error",
1679
+ })),
1680
+ imageMaxPerCall: z
1681
+ .number()
1682
+ .int()
1683
+ .positive()
1684
+ .max(10)
1685
+ .default(4)
1686
+ .meta(meta({
1687
+ hot: true,
1688
+ description: "Most images one image generation call may ask for, below each model's own maxImages; more is a validation error",
1689
+ })),
1690
+ imagePromptMaxChars: z
1691
+ .number()
1692
+ .int()
1693
+ .positive()
1694
+ .max(32_000)
1695
+ .default(4_000)
1696
+ .meta(meta({
1697
+ hot: true,
1698
+ description: "Longest prompt, in characters (code points), an image generation call accepts; longer is a validation error",
1699
+ })),
1670
1700
  })
1671
1701
  .prefault({}),
1672
1702
  hooks: z
@@ -899,11 +899,13 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
899
899
  outputTokens: z.ZodNumber;
900
900
  cacheReadTokens: z.ZodNumber;
901
901
  cacheWriteTokens: z.ZodNumber;
902
+ outputImages: z.ZodExactOptional<z.ZodNumber>;
902
903
  step: z.ZodNumber;
903
904
  provider: z.ZodString;
904
905
  model: z.ZodString;
905
906
  purpose: z.ZodOptional<z.ZodEnum<{
906
907
  compaction: "compaction";
908
+ image: "image";
907
909
  review: "review";
908
910
  title: "title";
909
911
  web_fetch: "web_fetch";
@@ -1578,6 +1580,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1578
1580
  outputTokens: z.ZodNumber;
1579
1581
  cacheReadTokens: z.ZodNumber;
1580
1582
  cacheWriteTokens: z.ZodNumber;
1583
+ outputImages: z.ZodExactOptional<z.ZodNumber>;
1581
1584
  }, z.core.$strip>;
1582
1585
  }, z.core.$strip>;
1583
1586
  }, z.core.$strip>, z.ZodObject<{
@@ -441,6 +441,8 @@ const ModelUsageShape = {
441
441
  outputTokens: count,
442
442
  cacheReadTokens: count,
443
443
  cacheWriteTokens: count,
444
+ /** Images produced (an image generation call). */
445
+ outputImages: count.exactOptional(),
444
446
  };
445
447
  /**
446
448
  * How a sub-agent's run ended (`subagent_finished`, a `subagent_delivery` finish). `timed_out`:
@@ -835,14 +837,16 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
835
837
  * `web_fetch` = a `WebFetch` extraction call (web tools spec §5: the tool call's run and step,
836
838
  * `callId` = the call; not model-visible, billed and reported, counted on a sub-agent's parent);
837
839
  * `review` = the command-review classifier's call (auto mode spec §5.3: not model-visible, billed
838
- * and reported, `callId` = the reviewed tool call).
840
+ * and reported, `callId` = the reviewed tool call); `image` = a `GenerateImage` call (image
841
+ * generation spec §7: the tool call's run and step, `callId` = the call, `outputImages` = the
842
+ * images produced; not model-visible, billed and reported, counted on a sub-agent's parent).
839
843
  */
840
844
  ev("usage", z.object({
841
845
  step: count,
842
846
  provider: z.string(),
843
847
  model: z.string(),
844
848
  ...ModelUsageShape,
845
- purpose: z.enum(["compaction", "title", "web_fetch", "review"]).optional(),
849
+ purpose: z.enum(["compaction", "title", "web_fetch", "review", "image"]).optional(),
846
850
  /**
847
851
  * The chunk a chunked compaction call summarised (1-based), with the number of calls the
848
852
  * compaction attempted (the full chunk count on a completed one; on a failed or hook-denied
@@ -850,7 +854,7 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
850
854
  */
851
855
  chunk: count.optional(),
852
856
  chunks: count.optional(),
853
- /** The tool call a `web_fetch` or `review` usage belongs to. */
857
+ /** The tool call a `web_fetch`, `review` or `image` usage belongs to. */
854
858
  callId: z.string().optional(),
855
859
  })),
856
860
  ev("reminder", z.object({ step: count, text: z.string() })),
@@ -5,6 +5,7 @@ import { type RegisteredHook } from "../extensions/hooks.js";
5
5
  import { RegistrationLedger } from "../extensions/ledger.js";
6
6
  import type { LockService } from "../infra/lock/lock.service.js";
7
7
  import type { ModelEmbeddings } from "../models/embeddings.js";
8
+ import type { ModelImages } from "../models/images.js";
8
9
  import type { OrgRole } from "../orgs/roles.js";
9
10
  import type { HookRunner } from "../runtime/hook-calls.js";
10
11
  import type { EmbedTokens } from "../ui/embed-token.js";
@@ -27,17 +28,22 @@ export interface KernelDeps {
27
28
  /** Verifies embed tokens (`ctx.ui` embed requests; the one `EmbedTokens` provider). */
28
29
  embedTokens: Pick<EmbedTokens, "verify">;
29
30
  /**
30
- * The `ctx.models` broker (the one `ModelEmbeddings` provider). Absent (a ctx built alone in a
31
- * test): `ctx.models` calls reject.
31
+ * The `ctx.models` brokers: embeddings (the one `ModelEmbeddings` provider) and image generation
32
+ * (the one `ModelImages` provider). Absent (a ctx built alone in a test): `ctx.models` calls
33
+ * reject.
32
34
  */
33
- models?: Pick<ModelEmbeddings, "embed" | "describe">;
35
+ models?: {
36
+ embeddings: Pick<ModelEmbeddings, "embed" | "describe">;
37
+ images: Pick<ModelImages, "generateForExtension" | "describeForExtension">;
38
+ };
34
39
  /**
35
40
  * What `ctx.net` reads per call: the kernel config (`net.*`) and the org network allowances.
36
41
  * Absent (a ctx built alone in a test): `ctx.net.fetch` rejects every request.
37
42
  */
38
43
  net?: ExtensionNetServices;
39
44
  /**
40
- * The host's hook registry: `ctx.models.embed` fires `model.request` through it (spec B §5.4).
45
+ * The host's hook registry: `ctx.models.embed` and `generateImage` fire `model.request` through
46
+ * it (spec B §5.4, image generation spec §5.6).
41
47
  * A required key, so no builder leaves policy hooks out by omission (fail closed by
42
48
  * construction); only a ctx built alone in a test passes `undefined` (no hooks fire).
43
49
  */
@@ -166,7 +172,8 @@ export declare class LiveConfig {
166
172
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`, `net`
167
173
  * (through `deps.net`, see `ctx/net.ts`);
168
174
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
169
- * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
175
+ * only with `permissions.models` (`embed` only its `embedding` purposes, `generateImage` only its
176
+ * `image_generation` ones, through `deps.models`); `http.route`
170
177
  * only the method + path declared in `permissions.http` (the record carries the declared access and
171
178
  * its mount, see {@link Route}); `tools.register` only names declared in
172
179
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
@@ -2,6 +2,7 @@ import { EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableEr
2
2
  import { Command, ConnectionBuilder, ControlledTransactionBuilder, Kysely, TransactionBuilder, } from "kysely";
3
3
  import { conversationTopic } from "../conversations/event-log.js";
4
4
  import { kernelDb } from "../db/kernel-schema.js";
5
+ import { ApiError } from "../errors.js";
5
6
  import { enabledExtensionsQuery, isExtensionEnabled } from "../extensions/enabled.js";
6
7
  import { checkHookRegistration } from "../extensions/hooks.js";
7
8
  import { RegistrationLedger } from "../extensions/ledger.js";
@@ -184,7 +185,8 @@ export class LiveConfig {
184
185
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`, `net`
185
186
  * (through `deps.net`, see `ctx/net.ts`);
186
187
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
187
- * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
188
+ * only with `permissions.models` (`embed` only its `embedding` purposes, `generateImage` only its
189
+ * `image_generation` ones, through `deps.models`); `http.route`
188
190
  * only the method + path declared in `permissions.http` (the record carries the declared access and
189
191
  * its mount, see {@link Route}); `tools.register` only names declared in
190
192
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
@@ -241,8 +243,9 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
241
243
  plugins: async () => [name],
242
244
  }).forPlugin(name)
243
245
  : undefined;
244
- // ctx.models: only with permissions.models; the broker accepts only the purposes declared there
245
- // with kind embedding (spec B §5.4), aborted by this instance's signal
246
+ // ctx.models: only with permissions.models; each broker accepts only the purposes declared there
247
+ // with its kind (embedding: spec B §5.4; image_generation: image generation spec §5.5), aborted
248
+ // by this instance's signal
246
249
  // a frozen copy: the approved manifest, not an object the extension could change later
247
250
  const declaredModels = Object.freeze(structuredClone(perms.models ?? []).map((m) => Object.freeze(m)));
248
251
  const modelsApi = declaredModels.length > 0
@@ -250,12 +253,25 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
250
253
  embed: async (req) => {
251
254
  if (!deps.models)
252
255
  throw new Error(`plugin ${name}: ctx.models is not available`);
253
- return deps.models.embed(name, declaredModels, req, lifecycle.signal, deps.hooks);
256
+ return deps.models.embeddings.embed(name, declaredModels, req, lifecycle.signal, deps.hooks);
254
257
  },
258
+ generateImage: async (req) => {
259
+ if (!deps.models)
260
+ throw new Error(`plugin ${name}: ctx.models is not available`);
261
+ return deps.models.images.generateForExtension(name, declaredModels, req, lifecycle.signal, deps.hooks);
262
+ },
263
+ // by the declared purpose's kind; an undeclared purpose has none, so its refusal
264
+ // (model.purpose_unknown) names no kind
255
265
  describe: async (req) => {
256
266
  if (!deps.models)
257
267
  throw new Error(`plugin ${name}: ctx.models is not available`);
258
- return deps.models.describe(name, declaredModels, req);
268
+ const kind = declaredModels.find((d) => d.purpose === req?.purpose)?.kind;
269
+ if (kind === undefined && typeof req?.purpose === "string") {
270
+ throw new ApiError("model.purpose_unknown", `Extension ${name} declared no model purpose "${req.purpose}" in permissions.models`);
271
+ }
272
+ return kind === "image_generation"
273
+ ? deps.models.images.describeForExtension(name, declaredModels, req)
274
+ : deps.models.embeddings.describe(name, declaredModels, req);
259
275
  },
260
276
  }
261
277
  : undefined;
@@ -1366,6 +1366,16 @@ export interface ModelUsageTable {
1366
1366
  provider: string;
1367
1367
  model: string;
1368
1368
  input_tokens: number;
1369
+ /** 0160: the call's kind: `embedding` (default) or `image_generation`. */
1370
+ kind: Generated<"embedding" | "image_generation">;
1371
+ /** 0160: images the call produced (0 for an embedding call). */
1372
+ output_images: Generated<number>;
1373
+ /** 0160: the answer's output tokens (0 for an embedding call). */
1374
+ output_tokens: Generated<number>;
1375
+ /** 0160: the answer's cache read tokens (0 for an embedding call). */
1376
+ cache_read_tokens: Generated<number>;
1377
+ /** 0160: the answer's cache write tokens (0 for an embedding call). */
1378
+ cache_write_tokens: Generated<number>;
1369
1379
  occurred_at: Ts;
1370
1380
  reported_at: TsNullable;
1371
1381
  /** Set when the row's `usage.report` job gave up after its last attempt. */
@@ -12,6 +12,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
12
12
  import { LockService } from "../infra/lock/lock.service.js";
13
13
  import type { KernelLogger } from "../log.js";
14
14
  import { ModelEmbeddings } from "../models/embeddings.js";
15
+ import { ModelImages } from "../models/images.js";
15
16
  import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
16
17
  import { EmbedTokens } from "../ui/embed-token.js";
17
18
  import type { UiActionHandler, UiRender } from "../ui/registry.js";
@@ -266,7 +267,9 @@ export declare class ExtensionHost {
266
267
  */
267
268
  effective: Pick<EffectiveConfigs, "get">,
268
269
  /** `ctx.models`: the embeddings broker (spec B §5.4). */
269
- models: Pick<ModelEmbeddings, "embed" | "describe">,
270
+ embeddings: Pick<ModelEmbeddings, "embed" | "describe">,
271
+ /** `ctx.models.generateImage`: the image generation calls (image generation spec §5.5). */
272
+ images: Pick<ModelImages, "generateForExtension" | "describeForExtension">,
270
273
  /** `ctx.net`: the internal endpoints each org's extension requests may reach (read per call). */
271
274
  allowances: OrgNetworkAllowances,
272
275
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
@@ -26,6 +26,7 @@ import { LockService } from "../infra/lock/lock.service.js";
26
26
  import { KERNEL_LOGGER, KEYRING, REDIS, REDIS_SUBSCRIBER } from "../infra/tokens.js";
27
27
  import { KERNEL_APP_OPTIONS } from "../lifecycle/tokens.js";
28
28
  import { ModelEmbeddings } from "../models/embeddings.js";
29
+ import { ModelImages } from "../models/images.js";
29
30
  import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
30
31
  import { packagePath } from "../packages/tgz.js";
31
32
  import { EmbedTokens } from "../ui/embed-token.js";
@@ -413,7 +414,9 @@ let ExtensionHost = class ExtensionHost {
413
414
  */
414
415
  effective,
415
416
  /** `ctx.models`: the embeddings broker (spec B §5.4). */
416
- models,
417
+ embeddings,
418
+ /** `ctx.models.generateImage`: the image generation calls (image generation spec §5.5). */
419
+ images,
417
420
  /** `ctx.net`: the internal endpoints each org's extension requests may reach (read per call). */
418
421
  allowances,
419
422
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
@@ -445,8 +448,8 @@ let ExtensionHost = class ExtensionHost {
445
448
  redisUrl: c.redis.url,
446
449
  keyring,
447
450
  embedTokens,
448
- models,
449
- // ctx.models.embed fires model.request through the same registry (spec B §5.4)
451
+ models: { embeddings, images },
452
+ // ctx.models.embed and generateImage fire model.request through the same registry
450
453
  hooks: this.hooks,
451
454
  net: { config, allowances, ...(netSeams !== undefined && { seams: netSeams }) },
452
455
  locks,
@@ -2394,8 +2397,9 @@ ExtensionHost = __decorate([
2394
2397
  __param(12, Inject(KERNEL_APP_OPTIONS)),
2395
2398
  __param(13, Inject(EffectiveConfigs)),
2396
2399
  __param(14, Inject(ModelEmbeddings)),
2397
- __param(15, Inject(OrgNetworkAllowances)),
2398
- __param(16, Optional()),
2399
- __param(16, Inject(EXTENSION_NET_SEAMS))
2400
+ __param(15, Inject(ModelImages)),
2401
+ __param(16, Inject(OrgNetworkAllowances)),
2402
+ __param(17, Optional()),
2403
+ __param(17, Inject(EXTENSION_NET_SEAMS))
2400
2404
  ], ExtensionHost);
2401
2405
  export { ExtensionHost };
@@ -35,6 +35,10 @@ const HOT_APPLIERS = {
35
35
  // The provider registry reads the list time limit at every listModels call.
36
36
  "models.listTimeoutMs": () => { },
37
37
  "models.embedTimeoutMs": () => { },
38
+ // ModelImages reads the image limits at every prepare and run.
39
+ "models.imageTimeoutMs": () => { },
40
+ "models.imageMaxPerCall": () => { },
41
+ "models.imagePromptMaxChars": () => { },
38
42
  // SandboxService reads the shared-lease cap at every acquisition.
39
43
  "sandbox.maxConcurrentCommands": () => { },
40
44
  // The command-review service reads the classifier's bounds at every classifier call.
@@ -0,0 +1,22 @@
1
+ import type { Logger } from "@capybara-hq/plugin-sdk";
2
+ import { type ProviderRegistry } from "../runtime/providers.js";
3
+ import type { StorageService } from "../storage/storage.service.js";
4
+ import type { ModelPurposesService } from "./purposes.js";
5
+ /** The model purpose `GenerateImage` calls (image generation spec §5.4; no fallback). */
6
+ export declare const IMAGE_PURPOSE = "image";
7
+ /** Whether `GenerateImage` can run in an org now, and if not, why. */
8
+ export type ImageUsable = "usable" | "no-model" | "no-storage";
9
+ /**
10
+ * The one predicate of `GenerateImage`'s availability (image generation spec §5.3), shared by the
11
+ * tool's listing and the member-readable purpose availability the agent form reads, so the two
12
+ * never disagree: the org's `image` purpose resolves to an image model the org can call now (an
13
+ * unmapped, disabled or unavailable model, or a provider whose model list fails, is `no-model`),
14
+ * and an object store is there to deliver the images (`no-storage`). Any other failure is logged
15
+ * and rethrown: it is a kernel fault, not an unavailable model.
16
+ */
17
+ export declare function imagePurposeUsable(deps: {
18
+ purposes: Pick<ModelPurposesService, "resolve">;
19
+ providers: Pick<ProviderRegistry, "resolve">;
20
+ storage: Pick<StorageService, "available">;
21
+ log: Pick<Logger, "warn">;
22
+ }, orgId: string): Promise<ImageUsable>;
@@ -0,0 +1,29 @@
1
+ import { ApiError } from "../errors.js";
2
+ import { ProviderListError } from "../runtime/providers.js";
3
+ /** The model purpose `GenerateImage` calls (image generation spec §5.4; no fallback). */
4
+ export const IMAGE_PURPOSE = "image";
5
+ /**
6
+ * The one predicate of `GenerateImage`'s availability (image generation spec §5.3), shared by the
7
+ * tool's listing and the member-readable purpose availability the agent form reads, so the two
8
+ * never disagree: the org's `image` purpose resolves to an image model the org can call now (an
9
+ * unmapped, disabled or unavailable model, or a provider whose model list fails, is `no-model`),
10
+ * and an object store is there to deliver the images (`no-storage`). Any other failure is logged
11
+ * and rethrown: it is a kernel fault, not an unavailable model.
12
+ */
13
+ export async function imagePurposeUsable(deps, orgId) {
14
+ try {
15
+ const target = await deps.purposes.resolve(orgId, IMAGE_PURPOSE);
16
+ await deps.providers.resolve(orgId, target.model, { kind: "image_generation" });
17
+ }
18
+ catch (e) {
19
+ if (e instanceof ProviderListError)
20
+ return "no-model";
21
+ if (e instanceof ApiError &&
22
+ (e.code === "model.unconfigured" || e.code === "agent.model_unavailable")) {
23
+ return "no-model";
24
+ }
25
+ deps.log.warn("image purpose availability check failed", { orgId, err: e });
26
+ throw e;
27
+ }
28
+ return deps.storage.available ? "usable" : "no-storage";
29
+ }
@@ -0,0 +1,125 @@
1
+ import { type ExtensionImageGenerateRequest, type ExtensionImageGenerateResult, type ExtensionModelTarget, type HookScope, type ImageAspectRatio, type ImageGenerateRequest, type ImageGenerateResult, type ImageMediaType, type ImageSize, type Logger, type ModelImageGenerationInfo } from "@capybara-hq/plugin-sdk";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ import { type HookDenial, type HookRunner } from "../runtime/hook-calls.js";
6
+ import { ProviderRegistry } from "../runtime/providers.js";
7
+ import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
8
+ import type { DeclaredModelPurposes } from "./embeddings.js";
9
+ import { ModelPurposesService } from "./purposes.js";
10
+ /** What a caller asks for (the tool or `ctx.models.generateImage`); references are bytes already. */
11
+ export interface ImageCallInput {
12
+ prompt: string;
13
+ /** An exact size (only `ctx.models`); must be one the model declares. */
14
+ size?: ImageSize;
15
+ aspectRatio?: ImageAspectRatio;
16
+ /** Images to produce (default 1). */
17
+ n?: number;
18
+ /** Base64 reference images. */
19
+ referenceImages?: {
20
+ mediaType: ImageMediaType;
21
+ data: string;
22
+ }[];
23
+ }
24
+ /** A validated call, ready for {@link ModelImages.run}. */
25
+ export interface PreparedImageCall {
26
+ ref: {
27
+ provider: string;
28
+ model: string;
29
+ };
30
+ info: ModelImageGenerationInfo;
31
+ request: ImageGenerateRequest;
32
+ }
33
+ /** Who makes the call, as the hook payloads name it. */
34
+ export type ImageHookIdentity = {
35
+ kind: "conversation";
36
+ scope: HookScope;
37
+ step: number;
38
+ callId: string;
39
+ } | {
40
+ kind: "extension";
41
+ extension: string;
42
+ imagePurpose: string;
43
+ };
44
+ /** A `model.request` policy hook denied the call; nothing was sent. The caller records it. */
45
+ export declare class ImageCallDenied extends Error {
46
+ readonly verdict: HookDenial;
47
+ constructor(verdict: HookDenial);
48
+ }
49
+ /**
50
+ * Image generation calls (image generation spec §5.1, §5.2, §5.6, §6), shared by the
51
+ * `GenerateImage` tool and `ctx.models.generateImage`:
52
+ * - {@link prepare} resolves the org's target for a purpose of kind `image_generation` (no
53
+ * fallback: unmapped is `model.unconfigured`), checks the prompt (code points, at most
54
+ * `models.imagePromptMaxChars`), the count (at most `models.imageMaxPerCall` and the model's
55
+ * `maxImages`), the reference images (count, media type, `MEDIA_LIMITS.imageBytes`), picks the
56
+ * size ({@link pickImageSize}) and sanitizes the mapping's params against the model's
57
+ * declarations. Every refusal is `ApiError("validation_failed")` with an actionable text.
58
+ * - {@link run} fires `model.request` (placeholders for references; a denial throws
59
+ * {@link ImageCallDenied} and sends nothing), calls `generateImage` within
60
+ * `models.imageTimeoutMs`, checks the result ({@link validateImageGenerateResult}: invalid is a
61
+ * `ModelError("server")`) and fires `model.response` (observe; media types and byte sizes, never
62
+ * bytes), also when the call failed, but not when the caller's signal aborted it.
63
+ * They store nothing and record no usage: the callers do. For extensions (spec §5.5, §8, §9),
64
+ * {@link generateForExtension} is `ctx.models.generateImage`: the admission of `ctx.models.embed`
65
+ * for kind `image_generation` (a purpose the extension declared with that kind, otherwise
66
+ * `model.purpose_unknown`; an org that enabled the extension, otherwise `extension.not_enabled`),
67
+ * then {@link prepare} and {@link run}; a policy denial writes one `hook.denied` audit row and
68
+ * rejects with `ApiError("model.hook_denied")`; a successful call writes one `model_usage` row
69
+ * (`kind = 'image_generation'`, its input tokens and images) and owes its `usage.report` delivery
70
+ * in the same transaction ({@link recordExtensionUsage}). A call that fails or is denied records
71
+ * no usage. The kernel stores no image of an extension call: the extension gets the bytes.
72
+ */
73
+ export declare class ModelImages {
74
+ private readonly purposes;
75
+ private readonly providers;
76
+ private readonly log;
77
+ /** `models.imageTimeoutMs`, `imageMaxPerCall`, `imagePromptMaxChars` (hot, read per call). */
78
+ private readonly config;
79
+ private readonly kdb;
80
+ readonly txHost: TransactionHost;
81
+ /** An extension call's `usage.report` delivery, owed with its `model_usage` row. */
82
+ private readonly usage;
83
+ constructor(purposes: Pick<ModelPurposesService, "resolve">, providers: Pick<ProviderRegistry, "resolve">, log: Pick<Logger, "warn">,
84
+ /** `models.imageTimeoutMs`, `imageMaxPerCall`, `imagePromptMaxChars` (hot, read per call). */
85
+ config: Pick<KernelConfigService, "get">, kdb: KernelDb, txHost: TransactionHost,
86
+ /** An extension call's `usage.report` delivery, owed with its `model_usage` row. */
87
+ usage: Pick<UsageReportJobs, "oweModelUsage">);
88
+ /** Refuses a purpose `plugin` did not declare with kind `image_generation`, or an org it is off in. */
89
+ private admit;
90
+ /**
91
+ * `ctx.models.generateImage` for `plugin` (its declared purposes), aborted by `signal` (the
92
+ * instance's) and the request's own signal; `hooks` is the host's hook registry
93
+ * (`model.request`, `model.response`), absent only for a ctx built without a host (tests).
94
+ */
95
+ generateForExtension(plugin: string, declared: DeclaredModelPurposes, request: ExtensionImageGenerateRequest, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ExtensionImageGenerateResult>;
96
+ /**
97
+ * `ctx.models.describe` of an image generation purpose for `plugin`: the org's effective target
98
+ * with its `imageGeneration` facts, or null when the purpose maps to no model the org can use.
99
+ */
100
+ describeForExtension(plugin: string, declared: DeclaredModelPurposes, req: {
101
+ orgId: string;
102
+ purpose: string;
103
+ }): Promise<ExtensionModelTarget | null>;
104
+ /**
105
+ * One `model_usage` row of an extension call (`kind = 'image_generation'`, the result's tokens
106
+ * and images) with its owed `usage.report` delivery, in one transaction.
107
+ */
108
+ private recordExtensionUsage;
109
+ prepare(orgId: string, purpose: string, input: ImageCallInput): Promise<PreparedImageCall>;
110
+ run(orgId: string, prepared: PreparedImageCall, who: ImageHookIdentity, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ImageGenerateResult & {
111
+ latencyMs: number;
112
+ }>;
113
+ /**
114
+ * One `generateImage` call, limited by `models.imageTimeoutMs` (hot, read per call): at the limit
115
+ * the call's signal aborts and the call fails with `ModelError("timeout")`, even when the
116
+ * provider ignores the signal (its late answer is dropped).
117
+ */
118
+ private callWithTimeout;
119
+ }
120
+ /**
121
+ * The images a validated answer is billed for: the answer's own `usage.outputImages`, else the
122
+ * images it carries, never more than it carries (a vendor count above them is not trusted). The
123
+ * one rule of the tool's `usage` event and an extension call's `model_usage` row.
124
+ */
125
+ export declare function billedImages(res: Pick<ImageGenerateResult, "images" | "usage">): number;