@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.
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +30 -0
- package/dist/conversations/events.d.ts +3 -0
- package/dist/conversations/events.js +7 -3
- package/dist/ctx/create-ctx.d.ts +12 -5
- package/dist/ctx/create-ctx.js +21 -5
- package/dist/db/kernel-schema.d.ts +10 -0
- package/dist/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +10 -6
- package/dist/infra/config/kernel-config.service.js +4 -0
- package/dist/models/image-usable.d.ts +22 -0
- package/dist/models/image-usable.js +29 -0
- package/dist/models/images.d.ts +125 -0
- package/dist/models/images.js +440 -0
- package/dist/models/models.module.d.ts +3 -2
- package/dist/models/models.module.js +16 -5
- package/dist/models/org-models.schemas.js +1 -0
- package/dist/models/purposes.controller.d.ts +7 -0
- package/dist/models/purposes.controller.js +9 -0
- package/dist/models/purposes.d.ts +28 -3
- package/dist/models/purposes.js +40 -13
- package/dist/platform/ops/models.ops.js +10 -0
- package/dist/runtime/hook-calls.d.ts +11 -1
- package/dist/runtime/hook-calls.js +24 -1
- package/dist/runtime/providers.d.ts +9 -5
- package/dist/runtime/providers.js +22 -3
- package/dist/runtime/usage-report.d.ts +10 -6
- package/dist/runtime/usage-report.js +31 -11
- package/dist/sandbox/review/permission-candidate.js +22 -6
- package/dist/sandbox/review/review.service.d.ts +1 -1
- package/dist/sandbox/review/review.service.js +43 -12
- package/dist/tools/builtin-names.d.ts +3 -1
- package/dist/tools/builtin-names.js +5 -1
- package/dist/tools/builtins/artifacts.d.ts +43 -0
- package/dist/tools/builtins/artifacts.js +67 -0
- package/dist/tools/builtins/builtin-tools.d.ts +4 -0
- package/dist/tools/builtins/builtin-tools.js +28 -5
- package/dist/tools/builtins/image/generate.d.ts +59 -0
- package/dist/tools/builtins/image/generate.js +535 -0
- package/dist/tools/builtins/image/index.d.ts +2 -0
- package/dist/tools/builtins/image/index.js +2 -0
- package/dist/tools/builtins/image/paths.d.ts +12 -0
- package/dist/tools/builtins/image/paths.js +26 -0
- package/dist/tools/builtins/sandbox/deliver.js +7 -49
- package/dist/tools/pipeline.js +15 -7
- package/dist/tools/tools.module.js +3 -0
- package/package.json +3 -3
- package/src/migrations/0160_model_usage_image_kind.sql +10 -0
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { IMAGE_ASPECT_RATIOS, IMAGE_MEDIA_TYPES, isModelError, MEDIA_LIMITS, ModelError, pickImageSize, sanitizeParams, validateImageGenerateResult, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { ApiError } from "../errors.js";
|
|
13
|
+
import { isExtensionEnabled } from "../extensions/enabled.js";
|
|
14
|
+
import { audit } from "../identity/audit.js";
|
|
15
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
16
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
17
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
18
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
19
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
20
|
+
import { base64Bytes, fireObserve, imageDeniedAudit, } from "../runtime/hook-calls.js";
|
|
21
|
+
import { modelDeniedText } from "../runtime/model-call.js";
|
|
22
|
+
import { ProviderRegistry } from "../runtime/providers.js";
|
|
23
|
+
import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
|
|
24
|
+
import { ModelPurposesService } from "./purposes.js";
|
|
25
|
+
/** Standard padded base64 (the check `validateImageGenerateResult` applies to results). */
|
|
26
|
+
const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
27
|
+
/** `MEDIA_LIMITS.imageBytes` in MB, for the reference-image error text. */
|
|
28
|
+
const IMAGE_LIMIT_MB = MEDIA_LIMITS.imageBytes / 1_048_576;
|
|
29
|
+
/** A `model.request` policy hook denied the call; nothing was sent. The caller records it. */
|
|
30
|
+
export class ImageCallDenied extends Error {
|
|
31
|
+
verdict;
|
|
32
|
+
constructor(verdict) {
|
|
33
|
+
super(modelDeniedText(verdict.plugin, verdict.reason));
|
|
34
|
+
this.verdict = verdict;
|
|
35
|
+
this.name = "ImageCallDenied";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Image generation calls (image generation spec §5.1, §5.2, §5.6, §6), shared by the
|
|
40
|
+
* `GenerateImage` tool and `ctx.models.generateImage`:
|
|
41
|
+
* - {@link prepare} resolves the org's target for a purpose of kind `image_generation` (no
|
|
42
|
+
* fallback: unmapped is `model.unconfigured`), checks the prompt (code points, at most
|
|
43
|
+
* `models.imagePromptMaxChars`), the count (at most `models.imageMaxPerCall` and the model's
|
|
44
|
+
* `maxImages`), the reference images (count, media type, `MEDIA_LIMITS.imageBytes`), picks the
|
|
45
|
+
* size ({@link pickImageSize}) and sanitizes the mapping's params against the model's
|
|
46
|
+
* declarations. Every refusal is `ApiError("validation_failed")` with an actionable text.
|
|
47
|
+
* - {@link run} fires `model.request` (placeholders for references; a denial throws
|
|
48
|
+
* {@link ImageCallDenied} and sends nothing), calls `generateImage` within
|
|
49
|
+
* `models.imageTimeoutMs`, checks the result ({@link validateImageGenerateResult}: invalid is a
|
|
50
|
+
* `ModelError("server")`) and fires `model.response` (observe; media types and byte sizes, never
|
|
51
|
+
* bytes), also when the call failed, but not when the caller's signal aborted it.
|
|
52
|
+
* They store nothing and record no usage: the callers do. For extensions (spec §5.5, §8, §9),
|
|
53
|
+
* {@link generateForExtension} is `ctx.models.generateImage`: the admission of `ctx.models.embed`
|
|
54
|
+
* for kind `image_generation` (a purpose the extension declared with that kind, otherwise
|
|
55
|
+
* `model.purpose_unknown`; an org that enabled the extension, otherwise `extension.not_enabled`),
|
|
56
|
+
* then {@link prepare} and {@link run}; a policy denial writes one `hook.denied` audit row and
|
|
57
|
+
* rejects with `ApiError("model.hook_denied")`; a successful call writes one `model_usage` row
|
|
58
|
+
* (`kind = 'image_generation'`, its input tokens and images) and owes its `usage.report` delivery
|
|
59
|
+
* in the same transaction ({@link recordExtensionUsage}). A call that fails or is denied records
|
|
60
|
+
* no usage. The kernel stores no image of an extension call: the extension gets the bytes.
|
|
61
|
+
*/
|
|
62
|
+
let ModelImages = class ModelImages {
|
|
63
|
+
purposes;
|
|
64
|
+
providers;
|
|
65
|
+
log;
|
|
66
|
+
config;
|
|
67
|
+
kdb;
|
|
68
|
+
txHost;
|
|
69
|
+
usage;
|
|
70
|
+
constructor(purposes, providers, log,
|
|
71
|
+
/** `models.imageTimeoutMs`, `imageMaxPerCall`, `imagePromptMaxChars` (hot, read per call). */
|
|
72
|
+
config, kdb, txHost,
|
|
73
|
+
/** An extension call's `usage.report` delivery, owed with its `model_usage` row. */
|
|
74
|
+
usage) {
|
|
75
|
+
this.purposes = purposes;
|
|
76
|
+
this.providers = providers;
|
|
77
|
+
this.log = log;
|
|
78
|
+
this.config = config;
|
|
79
|
+
this.kdb = kdb;
|
|
80
|
+
this.txHost = txHost;
|
|
81
|
+
this.usage = usage;
|
|
82
|
+
}
|
|
83
|
+
/** Refuses a purpose `plugin` did not declare with kind `image_generation`, or an org it is off in. */
|
|
84
|
+
async admit(plugin, declared, orgId, purpose) {
|
|
85
|
+
if (!declared.some((d) => d.purpose === purpose && d.kind === "image_generation")) {
|
|
86
|
+
throw new ApiError("model.purpose_unknown", `Extension ${plugin} declared no image generation purpose "${purpose}" in permissions.models`);
|
|
87
|
+
}
|
|
88
|
+
if (!(await isExtensionEnabled(this.kdb.db, orgId, plugin))) {
|
|
89
|
+
throw new ApiError("extension.not_enabled", `Extension ${plugin} is not enabled in organization ${orgId}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* `ctx.models.generateImage` for `plugin` (its declared purposes), aborted by `signal` (the
|
|
94
|
+
* instance's) and the request's own signal; `hooks` is the host's hook registry
|
|
95
|
+
* (`model.request`, `model.response`), absent only for a ctx built without a host (tests).
|
|
96
|
+
*/
|
|
97
|
+
async generateForExtension(plugin, declared, request, signal, hooks) {
|
|
98
|
+
checkExtensionRequest(request);
|
|
99
|
+
// a copy, read once: what the hooks see is what is sent, whatever the extension does with its
|
|
100
|
+
// own request object meanwhile
|
|
101
|
+
const { orgId, purpose } = request;
|
|
102
|
+
const input = {
|
|
103
|
+
prompt: request.prompt,
|
|
104
|
+
...(request.size !== undefined && {
|
|
105
|
+
size: { width: request.size.width, height: request.size.height },
|
|
106
|
+
}),
|
|
107
|
+
...(request.aspectRatio !== undefined && { aspectRatio: request.aspectRatio }),
|
|
108
|
+
...(request.n !== undefined && { n: request.n }),
|
|
109
|
+
...(request.referenceImages !== undefined && {
|
|
110
|
+
referenceImages: request.referenceImages.map((r) => ({
|
|
111
|
+
mediaType: r?.mediaType,
|
|
112
|
+
data: r?.data,
|
|
113
|
+
})),
|
|
114
|
+
}),
|
|
115
|
+
};
|
|
116
|
+
await this.admit(plugin, declared, orgId, purpose);
|
|
117
|
+
const prepared = await this.prepare(orgId, purpose, input);
|
|
118
|
+
const callSignal = request.signal ? AbortSignal.any([signal, request.signal]) : signal;
|
|
119
|
+
const who = { kind: "extension", extension: plugin, imagePurpose: purpose };
|
|
120
|
+
let res;
|
|
121
|
+
try {
|
|
122
|
+
res = await this.run(orgId, prepared, who, callSignal, hooks);
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
if (!(err instanceof ImageCallDenied))
|
|
126
|
+
throw err;
|
|
127
|
+
const call = {
|
|
128
|
+
orgId,
|
|
129
|
+
extension: plugin,
|
|
130
|
+
imagePurpose: purpose,
|
|
131
|
+
provider: prepared.ref.provider,
|
|
132
|
+
model: prepared.ref.model,
|
|
133
|
+
};
|
|
134
|
+
await audit(this.kdb.db, imageDeniedAudit(call, err.verdict));
|
|
135
|
+
this.log.warn("image generation call blocked by a policy hook", {
|
|
136
|
+
plugin,
|
|
137
|
+
orgId,
|
|
138
|
+
hookPlugin: err.verdict.plugin,
|
|
139
|
+
cause: err.verdict.cause,
|
|
140
|
+
});
|
|
141
|
+
throw new ApiError("model.hook_denied", err.message);
|
|
142
|
+
}
|
|
143
|
+
await this.recordExtensionUsage(plugin, orgId, purpose, prepared.ref, res);
|
|
144
|
+
return {
|
|
145
|
+
images: res.images.map((i) => ({ mediaType: i.mediaType, data: i.data })),
|
|
146
|
+
...(typeof res.revisedPrompt === "string" && { revisedPrompt: res.revisedPrompt }),
|
|
147
|
+
model: { provider: prepared.ref.provider, id: prepared.ref.model },
|
|
148
|
+
size: { width: prepared.request.size.width, height: prepared.request.size.height },
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* `ctx.models.describe` of an image generation purpose for `plugin`: the org's effective target
|
|
153
|
+
* with its `imageGeneration` facts, or null when the purpose maps to no model the org can use.
|
|
154
|
+
*/
|
|
155
|
+
async describeForExtension(plugin, declared, req) {
|
|
156
|
+
if (typeof req?.orgId !== "string" || typeof req.purpose !== "string") {
|
|
157
|
+
throw new ApiError("validation_failed", "describe needs orgId and purpose strings");
|
|
158
|
+
}
|
|
159
|
+
await this.admit(plugin, declared, req.orgId, req.purpose);
|
|
160
|
+
try {
|
|
161
|
+
const target = await this.purposes.resolve(req.orgId, req.purpose);
|
|
162
|
+
const { info } = await this.providers.resolve(req.orgId, target.model, {
|
|
163
|
+
kind: "image_generation",
|
|
164
|
+
});
|
|
165
|
+
if (info.imageGeneration === undefined)
|
|
166
|
+
return null;
|
|
167
|
+
return {
|
|
168
|
+
provider: target.model.provider,
|
|
169
|
+
id: target.model.model,
|
|
170
|
+
kind: "image_generation",
|
|
171
|
+
imageGeneration: structuredClone(info.imageGeneration),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
if (e instanceof ApiError && e.code === "model.unconfigured")
|
|
176
|
+
return null;
|
|
177
|
+
throw e;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* One `model_usage` row of an extension call (`kind = 'image_generation'`, the result's tokens
|
|
182
|
+
* and images) with its owed `usage.report` delivery, in one transaction.
|
|
183
|
+
*/
|
|
184
|
+
async recordExtensionUsage(plugin, orgId, purpose, ref, res) {
|
|
185
|
+
const row = await this.kdb.db
|
|
186
|
+
.insertInto("model_usage")
|
|
187
|
+
.values({
|
|
188
|
+
org_id: orgId,
|
|
189
|
+
extension: plugin,
|
|
190
|
+
purpose,
|
|
191
|
+
kind: "image_generation",
|
|
192
|
+
provider: ref.provider,
|
|
193
|
+
model: ref.model,
|
|
194
|
+
// `run` validated the answer's usage (validateImageGenerateResult): whole counts
|
|
195
|
+
input_tokens: res.usage.inputTokens,
|
|
196
|
+
output_tokens: res.usage.outputTokens,
|
|
197
|
+
cache_read_tokens: res.usage.cacheReadTokens,
|
|
198
|
+
cache_write_tokens: res.usage.cacheWriteTokens,
|
|
199
|
+
output_images: billedImages(res),
|
|
200
|
+
})
|
|
201
|
+
.returning("id")
|
|
202
|
+
.executeTakeFirstOrThrow();
|
|
203
|
+
await this.usage.oweModelUsage(row.id, orgId);
|
|
204
|
+
}
|
|
205
|
+
async prepare(orgId, purpose, input) {
|
|
206
|
+
const limits = this.config.get().models;
|
|
207
|
+
const bad = (text) => {
|
|
208
|
+
throw new ApiError("validation_failed", text);
|
|
209
|
+
};
|
|
210
|
+
const prompt = typeof input.prompt === "string" ? input.prompt : "";
|
|
211
|
+
if (prompt.trim() === "")
|
|
212
|
+
bad("prompt must not be empty");
|
|
213
|
+
const chars = [...prompt].length;
|
|
214
|
+
if (chars > limits.imagePromptMaxChars) {
|
|
215
|
+
bad(`prompt has ${chars} characters; the limit is ${limits.imagePromptMaxChars}`);
|
|
216
|
+
}
|
|
217
|
+
const target = await this.purposes.resolve(orgId, purpose);
|
|
218
|
+
const { info } = await this.providers.resolve(orgId, target.model, {
|
|
219
|
+
kind: "image_generation",
|
|
220
|
+
});
|
|
221
|
+
const gen = info.imageGeneration;
|
|
222
|
+
if (gen === undefined) {
|
|
223
|
+
// the registry refuses such models; kept as a guard
|
|
224
|
+
throw new ApiError("model.unconfigured", `The model configured for the "${purpose}" purpose cannot generate images`);
|
|
225
|
+
}
|
|
226
|
+
const cap = Math.min(limits.imageMaxPerCall, gen.maxImages);
|
|
227
|
+
const n = input.n ?? 1;
|
|
228
|
+
if (!Number.isInteger(n) || n < 1)
|
|
229
|
+
bad(`n must be a whole number from 1 to ${cap}`);
|
|
230
|
+
if (n > cap)
|
|
231
|
+
bad(`n must be at most ${cap} for this model`);
|
|
232
|
+
const refs = input.referenceImages ?? [];
|
|
233
|
+
if (refs.length > gen.maxReferenceImages) {
|
|
234
|
+
bad(gen.maxReferenceImages === 0
|
|
235
|
+
? "this model takes no reference images"
|
|
236
|
+
: `this model takes at most ${gen.maxReferenceImages} reference images`);
|
|
237
|
+
}
|
|
238
|
+
refs.forEach((r, i) => {
|
|
239
|
+
const okType = IMAGE_MEDIA_TYPES.includes(r?.mediaType);
|
|
240
|
+
const okData = typeof r?.data === "string" && BASE64.test(r.data);
|
|
241
|
+
if (!okType || !okData || base64Bytes(r.data) > MEDIA_LIMITS.imageBytes) {
|
|
242
|
+
bad(`reference image ${i} must be PNG, JPEG, GIF or WebP up to ${IMAGE_LIMIT_MB} MB`);
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
const size = pickImageSize(gen, {
|
|
246
|
+
...(input.size !== undefined && { size: input.size }),
|
|
247
|
+
...(input.aspectRatio !== undefined && { aspectRatio: input.aspectRatio }),
|
|
248
|
+
});
|
|
249
|
+
if (!size.ok)
|
|
250
|
+
return bad(size.error);
|
|
251
|
+
const params = sanitizeParams(info.parameters ?? [], target.params).value;
|
|
252
|
+
return {
|
|
253
|
+
ref: { provider: target.model.provider, model: target.model.model },
|
|
254
|
+
info: structuredClone(gen),
|
|
255
|
+
request: {
|
|
256
|
+
model: target.model.model,
|
|
257
|
+
prompt,
|
|
258
|
+
size: size.size,
|
|
259
|
+
n,
|
|
260
|
+
...(refs.length > 0 && {
|
|
261
|
+
referenceImages: refs.map((r) => ({ mediaType: r.mediaType, data: r.data })),
|
|
262
|
+
}),
|
|
263
|
+
params,
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
async run(orgId, prepared, who, signal, hooks) {
|
|
268
|
+
const { ref, info, request } = prepared;
|
|
269
|
+
const { provider } = await this.providers.resolve(orgId, ref, { kind: "image_generation" });
|
|
270
|
+
if (provider.generateImage === undefined) {
|
|
271
|
+
throw new ApiError("model.unconfigured", `Model ${ref.provider}/${ref.model} cannot generate images`);
|
|
272
|
+
}
|
|
273
|
+
const generate = provider.generateImage.bind(provider);
|
|
274
|
+
const identity = identityFields(who);
|
|
275
|
+
const base = { purpose: "image", orgId, provider: ref.provider, model: ref.model };
|
|
276
|
+
if (hooks?.has("model.request")) {
|
|
277
|
+
const payload = {
|
|
278
|
+
...base,
|
|
279
|
+
prompt: request.prompt,
|
|
280
|
+
size: { ...request.size },
|
|
281
|
+
n: request.n,
|
|
282
|
+
referenceImages: (request.referenceImages ?? []).map((r) => ({
|
|
283
|
+
type: "media_omitted",
|
|
284
|
+
kind: "image",
|
|
285
|
+
mediaType: r.mediaType,
|
|
286
|
+
size: base64Bytes(r.data),
|
|
287
|
+
})),
|
|
288
|
+
...identity,
|
|
289
|
+
};
|
|
290
|
+
// an abort while the hooks run rejects with the caller's reason (never a deny)
|
|
291
|
+
const verdict = await hooks.run("model.request", payload, signal);
|
|
292
|
+
if (!verdict.allowed)
|
|
293
|
+
throw new ImageCallDenied(verdict);
|
|
294
|
+
}
|
|
295
|
+
signal.throwIfAborted();
|
|
296
|
+
const sentAt = Date.now();
|
|
297
|
+
const respond = (r) => {
|
|
298
|
+
if (!hooks)
|
|
299
|
+
return;
|
|
300
|
+
fireObserve(hooks, "model.response", { ...base, ...identity, ...r, latencyMs: Date.now() - sentAt }, signal, this.log);
|
|
301
|
+
};
|
|
302
|
+
let res;
|
|
303
|
+
try {
|
|
304
|
+
res = await this.callWithTimeout(generate, request, signal, ref);
|
|
305
|
+
const problem = validateImageGenerateResult(request, info, res);
|
|
306
|
+
if (problem !== null) {
|
|
307
|
+
throw new ModelError("server", `Model ${ref.provider}/${ref.model} returned an invalid image result: ${problem}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
// a call the caller aborted gets no model.response (as a chat call the user stopped)
|
|
312
|
+
if (!signal.aborted) {
|
|
313
|
+
respond({
|
|
314
|
+
outcome: "failed",
|
|
315
|
+
images: [],
|
|
316
|
+
usage: null,
|
|
317
|
+
errorCode: isModelError(err) ? `model.${err.kind}` : "model.unknown",
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
throw err;
|
|
321
|
+
}
|
|
322
|
+
const latencyMs = Date.now() - sentAt;
|
|
323
|
+
respond({
|
|
324
|
+
outcome: "ok",
|
|
325
|
+
images: res.images.map((i) => ({ mediaType: i.mediaType, size: base64Bytes(i.data) })),
|
|
326
|
+
...(typeof res.revisedPrompt === "string" && { revisedPrompt: res.revisedPrompt }),
|
|
327
|
+
usage: res.usage ?? null,
|
|
328
|
+
});
|
|
329
|
+
return { ...res, latencyMs };
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* One `generateImage` call, limited by `models.imageTimeoutMs` (hot, read per call): at the limit
|
|
333
|
+
* the call's signal aborts and the call fails with `ModelError("timeout")`, even when the
|
|
334
|
+
* provider ignores the signal (its late answer is dropped).
|
|
335
|
+
*/
|
|
336
|
+
async callWithTimeout(generate, request, signal, ref) {
|
|
337
|
+
const ms = this.config.get().models.imageTimeoutMs;
|
|
338
|
+
const timer = new AbortController();
|
|
339
|
+
const both = AbortSignal.any([signal, timer.signal]);
|
|
340
|
+
let handle;
|
|
341
|
+
let onAbort;
|
|
342
|
+
const call = Promise.resolve().then(() => generate(request, { signal: both }));
|
|
343
|
+
call.catch(() => { });
|
|
344
|
+
try {
|
|
345
|
+
return await Promise.race([
|
|
346
|
+
call,
|
|
347
|
+
new Promise((_, reject) => {
|
|
348
|
+
handle = setTimeout(() => {
|
|
349
|
+
const err = new ModelError("timeout", `Model ${ref.provider}/${ref.model} did not finish generating images within ${ms} ms`);
|
|
350
|
+
timer.abort(err);
|
|
351
|
+
reject(err);
|
|
352
|
+
}, ms);
|
|
353
|
+
onAbort = () => reject(signal.reason);
|
|
354
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
355
|
+
}),
|
|
356
|
+
]);
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
clearTimeout(handle);
|
|
360
|
+
// the caller's signal may outlive the call (an extension's ctx.signal): drop the listener
|
|
361
|
+
if (onAbort)
|
|
362
|
+
signal.removeEventListener("abort", onAbort);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
__decorate([
|
|
367
|
+
Transactional()
|
|
368
|
+
], ModelImages.prototype, "recordExtensionUsage", null);
|
|
369
|
+
ModelImages = __decorate([
|
|
370
|
+
Injectable(),
|
|
371
|
+
__param(0, Inject(ModelPurposesService)),
|
|
372
|
+
__param(1, Inject(ProviderRegistry)),
|
|
373
|
+
__param(2, Inject(KERNEL_LOGGER)),
|
|
374
|
+
__param(3, Inject(KernelConfigService)),
|
|
375
|
+
__param(4, Inject(KernelDb)),
|
|
376
|
+
__param(5, Inject(TransactionHost)),
|
|
377
|
+
__param(6, Inject(UsageReportJobs))
|
|
378
|
+
], ModelImages);
|
|
379
|
+
export { ModelImages };
|
|
380
|
+
/** The identity fields of the hook payloads: conversation fields or the extension's. */
|
|
381
|
+
function identityFields(who) {
|
|
382
|
+
if (who.kind === "extension") {
|
|
383
|
+
return { extension: who.extension, imagePurpose: who.imagePurpose };
|
|
384
|
+
}
|
|
385
|
+
const s = who.scope;
|
|
386
|
+
return {
|
|
387
|
+
accountId: s.accountId,
|
|
388
|
+
agentId: s.agentId,
|
|
389
|
+
agentVersion: s.agentVersion,
|
|
390
|
+
conversationId: s.conversationId,
|
|
391
|
+
runId: s.runId,
|
|
392
|
+
...(s.parent !== undefined && { parent: { ...s.parent } }),
|
|
393
|
+
step: who.step,
|
|
394
|
+
callId: who.callId,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* The images a validated answer is billed for: the answer's own `usage.outputImages`, else the
|
|
399
|
+
* images it carries, never more than it carries (a vendor count above them is not trusted). The
|
|
400
|
+
* one rule of the tool's `usage` event and an extension call's `model_usage` row.
|
|
401
|
+
*/
|
|
402
|
+
export function billedImages(res) {
|
|
403
|
+
return Math.min(res.usage.outputImages ?? res.images.length, res.images.length);
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* The shape of a `ctx.models.generateImage` request (an extension is untyped JavaScript at run
|
|
407
|
+
* time); the values themselves (prompt, size, count, references) are checked by `prepare`.
|
|
408
|
+
*/
|
|
409
|
+
function checkExtensionRequest(req) {
|
|
410
|
+
const bad = (why) => {
|
|
411
|
+
throw new ApiError("validation_failed", `Invalid generateImage request: ${why}`);
|
|
412
|
+
};
|
|
413
|
+
if (typeof req !== "object" || req === null)
|
|
414
|
+
bad("expected an object");
|
|
415
|
+
if (typeof req.orgId !== "string" || req.orgId === "")
|
|
416
|
+
bad("orgId must be a string");
|
|
417
|
+
if (typeof req.purpose !== "string" || req.purpose === "")
|
|
418
|
+
bad("purpose must be a string");
|
|
419
|
+
if (typeof req.prompt !== "string")
|
|
420
|
+
bad("prompt must be a string");
|
|
421
|
+
if (req.size !== undefined &&
|
|
422
|
+
(typeof req.size !== "object" ||
|
|
423
|
+
req.size === null ||
|
|
424
|
+
!Number.isInteger(req.size.width) ||
|
|
425
|
+
!Number.isInteger(req.size.height))) {
|
|
426
|
+
bad("size must be { width, height } in whole pixels");
|
|
427
|
+
}
|
|
428
|
+
if (req.aspectRatio !== undefined &&
|
|
429
|
+
!IMAGE_ASPECT_RATIOS.includes(req.aspectRatio)) {
|
|
430
|
+
bad(`aspectRatio must be one of ${IMAGE_ASPECT_RATIOS.join(", ")}`);
|
|
431
|
+
}
|
|
432
|
+
if (req.n !== undefined && typeof req.n !== "number")
|
|
433
|
+
bad("n must be a number");
|
|
434
|
+
if (req.referenceImages !== undefined && !Array.isArray(req.referenceImages)) {
|
|
435
|
+
bad("referenceImages must be an array");
|
|
436
|
+
}
|
|
437
|
+
if (req.signal !== undefined && !(req.signal instanceof AbortSignal)) {
|
|
438
|
+
bad("signal must be an AbortSignal");
|
|
439
|
+
}
|
|
440
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Model prices, model purposes, the model disabled lists
|
|
3
|
-
*
|
|
2
|
+
* Model prices, model purposes, the model disabled lists, the `ctx.models` embeddings broker and
|
|
3
|
+
* the image generation calls ({@link ModelImages}).
|
|
4
|
+
* Below the extension host (the host injects both brokers for `ctx.models`): it must not
|
|
4
5
|
* import `ExtensionsModule`.
|
|
5
6
|
*/
|
|
6
7
|
export declare class ModelsModule {
|
|
@@ -10,13 +10,16 @@ import { IdentityModule } from "../identity/identity.module.js";
|
|
|
10
10
|
import { OrgLockModule } from "../orgs/org-lock.js";
|
|
11
11
|
import { ProvidersModule } from "../runtime/providers.js";
|
|
12
12
|
import { UsageReportJobsModule } from "../runtime/usage-report-jobs.js";
|
|
13
|
+
import { StorageModule } from "../storage/storage.module.js";
|
|
13
14
|
import { ModelEmbeddings } from "./embeddings.js";
|
|
14
15
|
import { ModelEnablementModule } from "./enablement.js";
|
|
16
|
+
import { ModelImages } from "./images.js";
|
|
15
17
|
import { PricesService } from "./prices.js";
|
|
16
18
|
import { ModelPurposesService } from "./purposes.js";
|
|
17
19
|
/**
|
|
18
|
-
* Model prices, model purposes, the model disabled lists
|
|
19
|
-
*
|
|
20
|
+
* Model prices, model purposes, the model disabled lists, the `ctx.models` embeddings broker and
|
|
21
|
+
* the image generation calls ({@link ModelImages}).
|
|
22
|
+
* Below the extension host (the host injects both brokers for `ctx.models`): it must not
|
|
20
23
|
* import `ExtensionsModule`.
|
|
21
24
|
*/
|
|
22
25
|
let ModelsModule = class ModelsModule {
|
|
@@ -29,11 +32,19 @@ ModelsModule = __decorate([
|
|
|
29
32
|
OrgLockModule,
|
|
30
33
|
ProvidersModule,
|
|
31
34
|
ModelEnablementModule,
|
|
32
|
-
// an
|
|
35
|
+
// an extension model call's `usage.report` delivery, owed with its `model_usage` row (no queue)
|
|
33
36
|
UsageReportJobsModule,
|
|
37
|
+
// the `image` purpose's availability needs an object store (GenerateImage delivers there)
|
|
38
|
+
StorageModule,
|
|
39
|
+
],
|
|
40
|
+
providers: [PricesService, ModelPurposesService, ModelEmbeddings, ModelImages],
|
|
41
|
+
exports: [
|
|
42
|
+
PricesService,
|
|
43
|
+
ModelPurposesService,
|
|
44
|
+
ModelEnablementModule,
|
|
45
|
+
ModelEmbeddings,
|
|
46
|
+
ModelImages,
|
|
34
47
|
],
|
|
35
|
-
providers: [PricesService, ModelPurposesService, ModelEmbeddings],
|
|
36
|
-
exports: [PricesService, ModelPurposesService, ModelEnablementModule, ModelEmbeddings],
|
|
37
48
|
})
|
|
38
49
|
], ModelsModule);
|
|
39
50
|
export { ModelsModule };
|
|
@@ -9,6 +9,7 @@ export const ORG_MODEL_ROUTES = [
|
|
|
9
9
|
{ route: "GET /api/v1/orgs/:orgId/models", query: ModelsQuery },
|
|
10
10
|
{ route: "GET /api/v1/orgs/:orgId/models/catalog" },
|
|
11
11
|
{ route: "GET /api/v1/orgs/:orgId/model-purposes" },
|
|
12
|
+
{ route: "GET /api/v1/orgs/:orgId/model-purposes/available" },
|
|
12
13
|
{
|
|
13
14
|
route: "PUT /api/v1/orgs/:orgId/model-purposes/:purpose",
|
|
14
15
|
params: ModelPurposePathParams,
|
|
@@ -15,6 +15,13 @@ export declare class ModelPurposesController {
|
|
|
15
15
|
list(principal: Principal, org: OrgContext): Promise<{
|
|
16
16
|
purposes: PurposeListing[];
|
|
17
17
|
}>;
|
|
18
|
+
/** Whether each purpose has a usable model in the org now, no model names (any member). */
|
|
19
|
+
available(org: OrgContext): Promise<{
|
|
20
|
+
purposes: {
|
|
21
|
+
purpose: string;
|
|
22
|
+
available: boolean;
|
|
23
|
+
}[];
|
|
24
|
+
}>;
|
|
18
25
|
put(principal: Principal, org: OrgContext, purpose: string, body: PurposePut): Promise<{
|
|
19
26
|
purpose: PurposeListing;
|
|
20
27
|
}>;
|
|
@@ -32,6 +32,10 @@ let ModelPurposesController = class ModelPurposesController {
|
|
|
32
32
|
purposes: await withDeclaredByNames(await this.purposes.list(org.orgId), this.displayNames),
|
|
33
33
|
};
|
|
34
34
|
}
|
|
35
|
+
/** Whether each purpose has a usable model in the org now, no model names (any member). */
|
|
36
|
+
async available(org) {
|
|
37
|
+
return { purposes: await this.purposes.availability(org.orgId) };
|
|
38
|
+
}
|
|
35
39
|
async put(principal, org, purpose, body) {
|
|
36
40
|
const p = requireUser(principal);
|
|
37
41
|
const view = await this.purposes.setOrg(org.orgId, purpose, purposeTargetOf(body), p.account.id, patTokenId(p));
|
|
@@ -45,6 +49,11 @@ __decorate([
|
|
|
45
49
|
__param(0, CurrentPrincipal()),
|
|
46
50
|
__param(1, CurrentOrg())
|
|
47
51
|
], ModelPurposesController.prototype, "list", null);
|
|
52
|
+
__decorate([
|
|
53
|
+
Get("available"),
|
|
54
|
+
OrgAction("agents.use"),
|
|
55
|
+
__param(0, CurrentOrg())
|
|
56
|
+
], ModelPurposesController.prototype, "available", null);
|
|
48
57
|
__decorate([
|
|
49
58
|
Put(":purpose"),
|
|
50
59
|
OrgAction("org.models.manage"),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ContentBlock, type LocalizedName, type ModelRequest, type ModelUsage, type ParamValue, type StopReason } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { type ContentBlock, type LocalizedName, type Logger, type ModelRequest, type ModelUsage, type ParamValue, type StopReason } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { ModelRef } from "../agents/definition.js";
|
|
4
4
|
import { ExtensionRegistry } from "../extensions/registry.js";
|
|
@@ -8,6 +8,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
|
|
|
8
8
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
9
9
|
import { OrgLock } from "../orgs/org-lock.js";
|
|
10
10
|
import { ProviderRegistry } from "../runtime/providers.js";
|
|
11
|
+
import { StorageService } from "../storage/storage.service.js";
|
|
11
12
|
/**
|
|
12
13
|
* 模型用途映射(C9):内核与插件按「用途」取模型,不在代码里写死模型。
|
|
13
14
|
* - 用途 = 内核用途 {@link KERNEL_PURPOSES}(目前只有评委 `eval`),或已加载插件 `permissions.models` 声明的;
|
|
@@ -18,6 +19,8 @@ import { ProviderRegistry } from "../runtime/providers.js";
|
|
|
18
19
|
* the org (by either layer) counts as unconfigured there (spec B §5.3);参数按目标模型自己的声明严格校验;
|
|
19
20
|
* - 每次都查 PG,不在进程内缓存(多副本下改映射立即生效)。`ctx.models` 仍预留,插件暂不能调用。
|
|
20
21
|
*/
|
|
22
|
+
/** The kinds a purpose can need: the callable model kinds. */
|
|
23
|
+
export type PurposeKind = "chat" | "embedding" | "image_generation";
|
|
21
24
|
/**
|
|
22
25
|
* Purposes the kernel declares: the eval judge, and the three sub-agent model tiers (phase C,
|
|
23
26
|
* spec §5.4: `fast` / `standard` / `capable` → `subagent_<tier>`; an unmapped tier runs on the
|
|
@@ -72,6 +75,13 @@ export declare const KERNEL_PURPOSES: readonly [{
|
|
|
72
75
|
readonly zh: "子智能体:最强";
|
|
73
76
|
readonly en: "Sub-agent: capable";
|
|
74
77
|
};
|
|
78
|
+
}, {
|
|
79
|
+
readonly purpose: "image";
|
|
80
|
+
readonly kind: "image_generation";
|
|
81
|
+
readonly label: {
|
|
82
|
+
readonly zh: "图片生成";
|
|
83
|
+
readonly en: "Image generation";
|
|
84
|
+
};
|
|
75
85
|
}];
|
|
76
86
|
/** 一个用途映射到的模型与参数。 */
|
|
77
87
|
export interface PurposeTarget {
|
|
@@ -80,7 +90,7 @@ export interface PurposeTarget {
|
|
|
80
90
|
}
|
|
81
91
|
export interface PurposeView {
|
|
82
92
|
purpose: string;
|
|
83
|
-
kind:
|
|
93
|
+
kind: PurposeKind;
|
|
84
94
|
label: {
|
|
85
95
|
zh: string;
|
|
86
96
|
en: string;
|
|
@@ -148,7 +158,12 @@ export declare class ModelPurposesService {
|
|
|
148
158
|
readonly txHost: TransactionHost;
|
|
149
159
|
private readonly adminLock;
|
|
150
160
|
private readonly orgLock;
|
|
151
|
-
|
|
161
|
+
/** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
|
|
162
|
+
private readonly storage;
|
|
163
|
+
private readonly log;
|
|
164
|
+
constructor(db: KernelDb, extensions: ExtensionRegistry, config: KernelConfigService, providers: Pick<ProviderRegistry, "resolve" | "platformInfo">, txHost: TransactionHost, adminLock: SuperAdminLock, orgLock: OrgLock,
|
|
165
|
+
/** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
|
|
166
|
+
storage: Pick<StorageService, "available">, log: Pick<Logger, "warn">);
|
|
152
167
|
/** 全部已声明的用途:内核的在前,其后按插件加载顺序。 */
|
|
153
168
|
private declared;
|
|
154
169
|
private find;
|
|
@@ -156,6 +171,16 @@ export declare class ModelPurposesService {
|
|
|
156
171
|
private views;
|
|
157
172
|
/** 全部用途与映射;不给 `orgId` = 部署级视图(`override` 一律为 null)。 */
|
|
158
173
|
list(orgId?: string): Promise<PurposeView[]>;
|
|
174
|
+
/**
|
|
175
|
+
* Whether each purpose (kernel and extension-declared) resolves to a usable model for the org
|
|
176
|
+
* now, as {@link resolve} decides, without naming the model (the agent form's gate for
|
|
177
|
+
* `GenerateImage`, readable by every member). The `image` purpose reads `GenerateImage`'s own
|
|
178
|
+
* predicate ({@link imagePurposeUsable}: an image model callable now and an object store).
|
|
179
|
+
*/
|
|
180
|
+
availability(orgId: string): Promise<{
|
|
181
|
+
purpose: string;
|
|
182
|
+
available: boolean;
|
|
183
|
+
}[]>;
|
|
159
184
|
/**
|
|
160
185
|
* 校验目标:模型可解析且启用(an org's override for the org, a deployment default in the
|
|
161
186
|
* platform view)、its kind is the purpose's `kind`、参数按它的声明严格通过。
|