@capybara-hq/kernel 0.1.0-rc.42 → 0.1.0-rc.44
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/catalog/scope-sync.d.ts +3 -2
- package/dist/catalog/scope-sync.js +3 -2
- package/dist/client/client-access.service.js +4 -4
- 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 +13 -6
- package/dist/ctx/create-ctx.js +21 -5
- package/dist/db/kernel-schema.d.ts +10 -0
- package/dist/extensions/enabled.d.ts +24 -4
- package/dist/extensions/enabled.js +47 -10
- package/dist/extensions/host.d.ts +7 -3
- package/dist/extensions/host.js +13 -8
- package/dist/extensions/org-config.d.ts +5 -2
- package/dist/extensions/org-config.js +32 -22
- package/dist/infra/config/kernel-config.service.js +4 -0
- package/dist/models/enablement.d.ts +1 -1
- package/dist/models/enablement.js +1 -1
- 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 +10 -6
- package/dist/runtime/providers.js +23 -4
- 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/registry.d.ts +2 -2
- package/dist/tools/registry.js +2 -2
- package/dist/tools/tools.module.js +3 -0
- package/package.json +4 -4
- package/src/migrations/0160_model_usage_image_kind.sql +10 -0
package/dist/models/purposes.js
CHANGED
|
@@ -19,21 +19,14 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
|
19
19
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
20
20
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
21
21
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
22
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
22
23
|
import { createZodDto } from "../infra/validation/create-zod-dto.js";
|
|
23
24
|
import { OrgLock } from "../orgs/org-lock.js";
|
|
24
25
|
import { estimateTokens } from "../runtime/context/tokens.js";
|
|
25
26
|
import { consumeModelStream } from "../runtime/model-call.js";
|
|
26
27
|
import { ProviderListError, ProviderRegistry } from "../runtime/providers.js";
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
* - 用途 = 内核用途 {@link KERNEL_PURPOSES}(目前只有评委 `eval`),或已加载插件 `permissions.models` 声明的;
|
|
30
|
-
* - 映射 = 部署默认(`org_id` 为 null,超级管理员设)+ 组织覆盖(组织管理员设,`org.models.manage`);
|
|
31
|
-
* 生效的映射先取组织覆盖、再取部署默认,都没有 → `model.unconfigured`;
|
|
32
|
-
* - a target's kind must equal the purpose's kind; an org's override must be enabled in the org on
|
|
33
|
-
* save (a deployment default: not disabled on the platform), and an effective target disabled in
|
|
34
|
-
* the org (by either layer) counts as unconfigured there (spec B §5.3);参数按目标模型自己的声明严格校验;
|
|
35
|
-
* - 每次都查 PG,不在进程内缓存(多副本下改映射立即生效)。`ctx.models` 仍预留,插件暂不能调用。
|
|
36
|
-
*/
|
|
28
|
+
import { StorageService } from "../storage/storage.service.js";
|
|
29
|
+
import { IMAGE_PURPOSE, imagePurposeUsable } from "./image-usable.js";
|
|
37
30
|
/**
|
|
38
31
|
* Purposes the kernel declares: the eval judge, and the three sub-agent model tiers (phase C,
|
|
39
32
|
* spec §5.4: `fast` / `standard` / `capable` → `subagent_<tier>`; an unmapped tier runs on the
|
|
@@ -68,6 +61,8 @@ export const KERNEL_PURPOSES = [
|
|
|
68
61
|
kind: "chat",
|
|
69
62
|
label: { zh: "子智能体:最强", en: "Sub-agent: capable" },
|
|
70
63
|
},
|
|
64
|
+
/** The `GenerateImage` tool's model; no fallback: unmapped → `model.unconfigured`. */
|
|
65
|
+
{ purpose: "image", kind: "image_generation", label: { zh: "图片生成", en: "Image generation" } },
|
|
71
66
|
];
|
|
72
67
|
/** {@link PurposeListing}s of `views`, the display names read in one call. */
|
|
73
68
|
export async function withDeclaredByNames(views, names) {
|
|
@@ -131,7 +126,11 @@ let ModelPurposesService = class ModelPurposesService {
|
|
|
131
126
|
txHost;
|
|
132
127
|
adminLock;
|
|
133
128
|
orgLock;
|
|
134
|
-
|
|
129
|
+
storage;
|
|
130
|
+
log;
|
|
131
|
+
constructor(db, extensions, config, providers, txHost, adminLock, orgLock,
|
|
132
|
+
/** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
|
|
133
|
+
storage, log) {
|
|
135
134
|
this.db = db;
|
|
136
135
|
this.extensions = extensions;
|
|
137
136
|
this.config = config;
|
|
@@ -139,6 +138,8 @@ let ModelPurposesService = class ModelPurposesService {
|
|
|
139
138
|
this.txHost = txHost;
|
|
140
139
|
this.adminLock = adminLock;
|
|
141
140
|
this.orgLock = orgLock;
|
|
141
|
+
this.storage = storage;
|
|
142
|
+
this.log = log;
|
|
142
143
|
}
|
|
143
144
|
/** 全部已声明的用途:内核的在前,其后按插件加载顺序。 */
|
|
144
145
|
declared() {
|
|
@@ -196,6 +197,30 @@ let ModelPurposesService = class ModelPurposesService {
|
|
|
196
197
|
async list(orgId) {
|
|
197
198
|
return this.views(this.declared(), orgId);
|
|
198
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Whether each purpose (kernel and extension-declared) resolves to a usable model for the org
|
|
202
|
+
* now, as {@link resolve} decides, without naming the model (the agent form's gate for
|
|
203
|
+
* `GenerateImage`, readable by every member). The `image` purpose reads `GenerateImage`'s own
|
|
204
|
+
* predicate ({@link imagePurposeUsable}: an image model callable now and an object store).
|
|
205
|
+
*/
|
|
206
|
+
async availability(orgId) {
|
|
207
|
+
const out = [];
|
|
208
|
+
for (const d of this.declared()) {
|
|
209
|
+
if (d.purpose === IMAGE_PURPOSE) {
|
|
210
|
+
// `GenerateImage`'s own predicate: the form offers the tool exactly when it is listed
|
|
211
|
+
const usable = await imagePurposeUsable({ purposes: this, providers: this.providers, storage: this.storage, log: this.log }, orgId);
|
|
212
|
+
out.push({ purpose: d.purpose, available: usable === "usable" });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const available = await this.resolve(orgId, d.purpose).then(() => true, (e) => {
|
|
216
|
+
if (e instanceof ApiError && e.code === "model.unconfigured")
|
|
217
|
+
return false;
|
|
218
|
+
throw e;
|
|
219
|
+
});
|
|
220
|
+
out.push({ purpose: d.purpose, available });
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
199
224
|
/**
|
|
200
225
|
* 校验目标:模型可解析且启用(an org's override for the org, a deployment default in the
|
|
201
226
|
* platform view)、its kind is the purpose's `kind`、参数按它的声明严格通过。
|
|
@@ -220,7 +245,7 @@ let ModelPurposesService = class ModelPurposesService {
|
|
|
220
245
|
throw invalid([
|
|
221
246
|
{
|
|
222
247
|
path: "target.model",
|
|
223
|
-
message: `this purpose needs ${kind
|
|
248
|
+
message: `this purpose needs ${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} model, not ${info.kind}`,
|
|
224
249
|
},
|
|
225
250
|
]);
|
|
226
251
|
}
|
|
@@ -398,6 +423,8 @@ ModelPurposesService = __decorate([
|
|
|
398
423
|
__param(3, Inject(ProviderRegistry)),
|
|
399
424
|
__param(4, Inject(TransactionHost)),
|
|
400
425
|
__param(5, Inject(SuperAdminLock)),
|
|
401
|
-
__param(6, Inject(OrgLock))
|
|
426
|
+
__param(6, Inject(OrgLock)),
|
|
427
|
+
__param(7, Inject(StorageService)),
|
|
428
|
+
__param(8, Inject(KERNEL_LOGGER))
|
|
402
429
|
], ModelPurposesService);
|
|
403
430
|
export { ModelPurposesService };
|
|
@@ -86,6 +86,16 @@ let ModelsOperations = class ModelsOperations {
|
|
|
86
86
|
purposes: await withDeclaredByNames(await this.purposes.list(ctx.orgId), this.displayNames),
|
|
87
87
|
}),
|
|
88
88
|
}),
|
|
89
|
+
defineOperation({
|
|
90
|
+
id: "models.purpose-availability",
|
|
91
|
+
description: "Whether each model purpose (such as image generation) has a usable model in this org now, without naming models.",
|
|
92
|
+
input: z.object({}).strict(),
|
|
93
|
+
example: {},
|
|
94
|
+
authz: { orgAction: "agents.use" },
|
|
95
|
+
mirrors: ["GET /api/v1/orgs/:orgId/model-purposes/available"],
|
|
96
|
+
confirm: "read",
|
|
97
|
+
run: async (_input, ctx) => ({ purposes: await this.purposes.availability(ctx.orgId) }),
|
|
98
|
+
}),
|
|
89
99
|
defineOperation({
|
|
90
100
|
id: "models.set-purpose",
|
|
91
101
|
description: "Set the org's model for one purpose (org admins): target.model is { provider, model } with optional params, or target null to clear the override and fall back to the platform default. The model must be usable in the org and of the purpose's kind.",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AvailableHook, EmbeddingRequestHookPayload, HookModelRequest, HookParentScope, HookPayloads, HookScope, Logger, ModelRequest } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import type { AvailableHook, EmbeddingRequestHookPayload, HookModelRequest, HookParentScope, HookPayloads, HookScope, ImageRequestHookPayload, Logger, ModelRequest } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { AppendEvent, EventLog } from "../conversations/event-log.js";
|
|
3
3
|
import type { EventPayload } from "../conversations/events.js";
|
|
4
4
|
import type { HookOutcome, HookRegistry } from "../extensions/hooks.js";
|
|
@@ -35,6 +35,8 @@ export declare function hookScope(hooks: HookRunner | undefined, s: {
|
|
|
35
35
|
* run-scoped (not a per-call controller aborted when the call ends), or the hooks would be cut off.
|
|
36
36
|
*/
|
|
37
37
|
export declare function fireObserve<K extends "model.response" | "tool.postExecute">(hooks: HookRunner, mount: K, payload: HookPayloads[K], signal: AbortSignal, log: Pick<Logger, "warn">): void;
|
|
38
|
+
/** Decoded size of standard padded base64, in bytes. */
|
|
39
|
+
export declare const base64Bytes: (data: string) => number;
|
|
38
40
|
/**
|
|
39
41
|
* The `model.request` payload's request (F10, I-3): the request sent to the provider with every image,
|
|
40
42
|
* document and file block replaced by a {@link HookMediaPlaceholder} (`kind`, `mediaType`, decoded
|
|
@@ -74,6 +76,14 @@ export declare function hookDeniedAudit(at: DenialSite, payload: EventPayload<"h
|
|
|
74
76
|
* call's purpose, extension, embedding purpose and model.
|
|
75
77
|
*/
|
|
76
78
|
export declare function embeddingDeniedAudit(call: Pick<EmbeddingRequestHookPayload, "orgId" | "extension" | "embeddingPurpose" | "provider" | "model">, denial: HookDenial): AuditEntry;
|
|
79
|
+
/**
|
|
80
|
+
* The `hook.denied` audit entry of a denied image generation call (`ctx.models.generateImage`,
|
|
81
|
+
* image generation spec §5.6): as {@link embeddingDeniedAudit}, with the call's image purpose.
|
|
82
|
+
*/
|
|
83
|
+
export declare function imageDeniedAudit(call: Pick<ImageRequestHookPayload, "orgId" | "provider" | "model"> & {
|
|
84
|
+
extension: string;
|
|
85
|
+
imagePurpose: string;
|
|
86
|
+
}, denial: HookDenial): AuditEntry;
|
|
77
87
|
/** Audit entry shape (the argument of `audit()`). */
|
|
78
88
|
export type AuditEntry = Parameters<typeof audit>[1];
|
|
79
89
|
/**
|
|
@@ -38,7 +38,7 @@ export function fireObserve(hooks, mount, payload, signal, log) {
|
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
40
|
/** Decoded size of standard padded base64, in bytes. */
|
|
41
|
-
const base64Bytes = (data) => {
|
|
41
|
+
export const base64Bytes = (data) => {
|
|
42
42
|
const pad = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
|
|
43
43
|
return Math.max(0, Math.floor(data.length / 4) * 3 - pad);
|
|
44
44
|
};
|
|
@@ -148,6 +148,29 @@ export function embeddingDeniedAudit(call, denial) {
|
|
|
148
148
|
},
|
|
149
149
|
};
|
|
150
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* The `hook.denied` audit entry of a denied image generation call (`ctx.models.generateImage`,
|
|
153
|
+
* image generation spec §5.6): as {@link embeddingDeniedAudit}, with the call's image purpose.
|
|
154
|
+
*/
|
|
155
|
+
export function imageDeniedAudit(call, denial) {
|
|
156
|
+
return {
|
|
157
|
+
orgId: call.orgId,
|
|
158
|
+
action: "hook.denied",
|
|
159
|
+
target: call.extension,
|
|
160
|
+
detail: {
|
|
161
|
+
mount: "model.request",
|
|
162
|
+
plugin: denial.plugin,
|
|
163
|
+
reason: denial.reason,
|
|
164
|
+
cause: denial.cause,
|
|
165
|
+
purpose: "image",
|
|
166
|
+
extension: call.extension,
|
|
167
|
+
imagePurpose: call.imagePurpose,
|
|
168
|
+
provider: call.provider,
|
|
169
|
+
model: call.model,
|
|
170
|
+
...denialAuditDetail(denial),
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
|
151
174
|
/**
|
|
152
175
|
* Writes a model request's `hook_denied` event and its audit entry in one transaction (the tool path
|
|
153
176
|
* writes them with the `tool_result` instead). Idempotent by idem key: a resumed run that finds the
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type Logger, type ModelInfo, type ModelKind, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type ImageGenerateRequest, type ImageGenerateResult, type Logger, type ModelInfo, type ModelKind, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { Redis } from "ioredis";
|
|
3
3
|
import type { ModelRef } from "../agents/definition.js";
|
|
4
4
|
import { ApiError } from "../errors.js";
|
|
@@ -46,15 +46,15 @@ export type KernelModelInfo = Omit<ModelInfo, "kind"> & {
|
|
|
46
46
|
export type ListedModelInfo = KernelModelInfo & {
|
|
47
47
|
disabled?: boolean;
|
|
48
48
|
};
|
|
49
|
-
/** A model `resolve` returns: only `chat` and `
|
|
49
|
+
/** A model `resolve` returns: only `chat`, `embedding` and `image_generation` models are callable. */
|
|
50
50
|
export type ResolvedModelInfo = Omit<ModelInfo, "kind"> & {
|
|
51
|
-
kind: "chat" | "embedding";
|
|
51
|
+
kind: "chat" | "embedding" | "image_generation";
|
|
52
52
|
};
|
|
53
53
|
/**
|
|
54
54
|
* The kind a `resolve` caller needs (default `chat`: every streaming caller); `callable` accepts
|
|
55
|
-
*
|
|
55
|
+
* any callable kind (a purpose target checked against the purpose's own kind).
|
|
56
56
|
*/
|
|
57
|
-
export type ExpectedKind = "chat" | "embedding" | "callable";
|
|
57
|
+
export type ExpectedKind = "chat" | "embedding" | "image_generation" | "callable";
|
|
58
58
|
/**
|
|
59
59
|
* A provider bound to one org's call options (`orgId` and the effective config, spec B §5.5): the
|
|
60
60
|
* kernel's callers pass only the signal. Built per `resolve`, never cached; the config stays in
|
|
@@ -68,6 +68,10 @@ export interface BoundProvider {
|
|
|
68
68
|
embed?(req: EmbedRequest, opts: {
|
|
69
69
|
signal: AbortSignal;
|
|
70
70
|
}): Promise<EmbedResult>;
|
|
71
|
+
/** Present when the provider implements `generateImage`. */
|
|
72
|
+
generateImage?(req: ImageGenerateRequest, opts: {
|
|
73
|
+
signal: AbortSignal;
|
|
74
|
+
}): Promise<ImageGenerateResult>;
|
|
71
75
|
}
|
|
72
76
|
/**
|
|
73
77
|
* 一个供应商在后台的视图:供应商名即插件名;`status: "error"` 时 `models` 为空、`error` 为内核的说明。
|
|
@@ -97,7 +101,7 @@ export declare class ProviderListError extends ApiError {
|
|
|
97
101
|
* Org-bound (spec B §5.5, A §6): every list and call is made for an org with the provider's
|
|
98
102
|
* effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`. A provider is on
|
|
99
103
|
* in an org only when the org enabled it, like every other extension (`enabledExtensionsQuery`: the
|
|
100
|
-
* org's switch on, or
|
|
104
|
+
* org's switch on, or always on: required or builtin); one not enabled there, or whose effective
|
|
101
105
|
* config is not valid there, offers no models there. The admin view (no org) lists with the
|
|
102
106
|
* platform config.
|
|
103
107
|
*
|
|
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { createHash } from "node:crypto";
|
|
11
|
-
import { assertValidDeclarations, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { assertValidDeclarations, isValidImageGenerationInfo, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
|
|
12
12
|
import { Inject, Injectable, Module, Optional } from "@nestjs/common";
|
|
13
13
|
import { ApiError } from "../errors.js";
|
|
14
14
|
import { deploymentConfigHash } from "../extensions/config-hash.js";
|
|
@@ -84,6 +84,12 @@ function bindProvider(impl, call) {
|
|
|
84
84
|
if (typeof impl.embed === "function") {
|
|
85
85
|
bound.embed = (req, opts) => impl.embed(req, { signal: opts.signal, ...call });
|
|
86
86
|
}
|
|
87
|
+
if (typeof impl.generateImage === "function") {
|
|
88
|
+
bound.generateImage = (req, opts) => impl.generateImage(req, {
|
|
89
|
+
signal: opts.signal,
|
|
90
|
+
...call,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
87
93
|
return bound;
|
|
88
94
|
}
|
|
89
95
|
const positiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
|
|
@@ -122,7 +128,7 @@ export class ProviderListError extends ApiError {
|
|
|
122
128
|
* Org-bound (spec B §5.5, A §6): every list and call is made for an org with the provider's
|
|
123
129
|
* effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`. A provider is on
|
|
124
130
|
* in an org only when the org enabled it, like every other extension (`enabledExtensionsQuery`: the
|
|
125
|
-
* org's switch on, or
|
|
131
|
+
* org's switch on, or always on: required or builtin); one not enabled there, or whose effective
|
|
126
132
|
* config is not valid there, offers no models there. The admin view (no org) lists with the
|
|
127
133
|
* platform config.
|
|
128
134
|
*
|
|
@@ -278,6 +284,12 @@ let ProviderRegistry = class ProviderRegistry {
|
|
|
278
284
|
problem = "an embedding model from a provider without embed";
|
|
279
285
|
}
|
|
280
286
|
}
|
|
287
|
+
else if (kind === "image_generation") {
|
|
288
|
+
// absent info (or a provider without generateImage) stays listed, list-only
|
|
289
|
+
if (m.imageGeneration !== undefined && !isValidImageGenerationInfo(m.imageGeneration)) {
|
|
290
|
+
problem = "malformed image generation info";
|
|
291
|
+
}
|
|
292
|
+
}
|
|
281
293
|
if (problem !== undefined) {
|
|
282
294
|
await this.warnDropped(provider, m.id, hash, problem, cause);
|
|
283
295
|
continue;
|
|
@@ -444,10 +456,17 @@ let ProviderRegistry = class ProviderRegistry {
|
|
|
444
456
|
: `Model provider ${ref.provider} needs configuration in this organization`);
|
|
445
457
|
}
|
|
446
458
|
const info = (await this.models(p, t)).find((m) => m.id === ref.model);
|
|
447
|
-
if (!info
|
|
459
|
+
if (!info)
|
|
460
|
+
throw unavailable();
|
|
461
|
+
if (info.kind === "image_generation") {
|
|
462
|
+
// callable only with valid info and a provider that implements generateImage
|
|
463
|
+
if (!info.imageGeneration || typeof p.impl.generateImage !== "function")
|
|
464
|
+
throw unavailable();
|
|
465
|
+
}
|
|
466
|
+
else if (info.kind !== "chat" && info.kind !== "embedding")
|
|
448
467
|
throw unavailable();
|
|
449
468
|
if (kind !== "callable" && info.kind !== kind) {
|
|
450
|
-
throw new ApiError("agent.model_unavailable", `Model ${ref.provider}/${ref.model} is not ${kind
|
|
469
|
+
throw new ApiError("agent.model_unavailable", `Model ${ref.provider}/${ref.model} is not ${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} model`);
|
|
451
470
|
}
|
|
452
471
|
const key = modelKey(ref.provider, ref.model);
|
|
453
472
|
const [platform, org] = await Promise.all([
|
|
@@ -53,11 +53,13 @@ export declare function narrowPending(stored: readonly string[] | undefined, fai
|
|
|
53
53
|
* Nothing is written to the event log (never model-visible). Compaction calls log usage too (`purpose: "compaction"`) and are reported,
|
|
54
54
|
* as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
|
|
55
55
|
* extraction calls (`purpose: "web_fetch"`). Command-review classifier calls log usage with
|
|
56
|
-
* `purpose: "review"` and the reviewed tool call's `callId
|
|
56
|
+
* `purpose: "review"` and the reviewed tool call's `callId`; `GenerateImage` calls with
|
|
57
|
+
* `purpose: "image"` and their `outputImages`, passed through in `usage`.
|
|
57
58
|
* Single-step eval replays and judge requests log no usage: not reported (M7).
|
|
58
|
-
* - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed`
|
|
59
|
-
* `model_usage` row and owes job `usage-model-<rowId>`
|
|
60
|
-
* (`purpose: "embedding"`, `
|
|
59
|
+
* - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` and
|
|
60
|
+
* `ctx.models.generateImage` call writes a `model_usage` row and owes job `usage-model-<rowId>`
|
|
61
|
+
* with it; the payload (`purpose: "embedding"`, or `"image"` with `usage.outputImages` for an
|
|
62
|
+
* image generation row; `eventId` = the row id, the calling `extension`, no conversation fields)
|
|
61
63
|
* is read from the row when the job runs, and the row's `reported_at` is set once nothing is left
|
|
62
64
|
* to deliver; a job that gives up after its last attempt sets `report_failed_at`. A row with
|
|
63
65
|
* `reported_at IS NULL` is not necessarily pending: no job is owed when no enabled extension
|
|
@@ -122,8 +124,10 @@ export declare class UsageReporter {
|
|
|
122
124
|
/** The payload of a job: a `usage` event's or a `model_usage` row's; null when it is gone. */
|
|
123
125
|
private payloadOfJob;
|
|
124
126
|
/**
|
|
125
|
-
* The payload of one `model_usage` row (spec B §5.4): purpose `
|
|
126
|
-
*
|
|
127
|
+
* The payload of one `model_usage` row (spec B §5.4, image generation spec §9): purpose `image`
|
|
128
|
+
* for an image generation call (`kind = 'image_generation'`, with its output and cache tokens
|
|
129
|
+
* and `usage.outputImages` when it produced any), else `embedding`; the calling extension, no
|
|
130
|
+
* conversation fields; `eventId` is the row id. Null when the row no longer exists.
|
|
127
131
|
*/
|
|
128
132
|
private payloadOfUsage;
|
|
129
133
|
/** A `model_usage` job is done (delivered, or nothing left to deliver to): marks the row. */
|
|
@@ -108,11 +108,13 @@ export function narrowPending(stored, failed) {
|
|
|
108
108
|
* Nothing is written to the event log (never model-visible). Compaction calls log usage too (`purpose: "compaction"`) and are reported,
|
|
109
109
|
* as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
|
|
110
110
|
* extraction calls (`purpose: "web_fetch"`). Command-review classifier calls log usage with
|
|
111
|
-
* `purpose: "review"` and the reviewed tool call's `callId
|
|
111
|
+
* `purpose: "review"` and the reviewed tool call's `callId`; `GenerateImage` calls with
|
|
112
|
+
* `purpose: "image"` and their `outputImages`, passed through in `usage`.
|
|
112
113
|
* Single-step eval replays and judge requests log no usage: not reported (M7).
|
|
113
|
-
* - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed`
|
|
114
|
-
* `model_usage` row and owes job `usage-model-<rowId>`
|
|
115
|
-
* (`purpose: "embedding"`, `
|
|
114
|
+
* - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` and
|
|
115
|
+
* `ctx.models.generateImage` call writes a `model_usage` row and owes job `usage-model-<rowId>`
|
|
116
|
+
* with it; the payload (`purpose: "embedding"`, or `"image"` with `usage.outputImages` for an
|
|
117
|
+
* image generation row; `eventId` = the row id, the calling `extension`, no conversation fields)
|
|
116
118
|
* is read from the row when the job runs, and the row's `reported_at` is set once nothing is left
|
|
117
119
|
* to deliver; a job that gives up after its last attempt sets `report_failed_at`. A row with
|
|
118
120
|
* `reported_at IS NULL` is not necessarily pending: no job is owed when no enabled extension
|
|
@@ -229,29 +231,46 @@ let UsageReporter = class UsageReporter {
|
|
|
229
231
|
: this.payloadOf(data.conversationId, data.seq);
|
|
230
232
|
}
|
|
231
233
|
/**
|
|
232
|
-
* The payload of one `model_usage` row (spec B §5.4): purpose `
|
|
233
|
-
*
|
|
234
|
+
* The payload of one `model_usage` row (spec B §5.4, image generation spec §9): purpose `image`
|
|
235
|
+
* for an image generation call (`kind = 'image_generation'`, with its output and cache tokens
|
|
236
|
+
* and `usage.outputImages` when it produced any), else `embedding`; the calling extension, no
|
|
237
|
+
* conversation fields; `eventId` is the row id. Null when the row no longer exists.
|
|
234
238
|
*/
|
|
235
239
|
async payloadOfUsage(id) {
|
|
236
240
|
const row = await this.db
|
|
237
241
|
.selectFrom("model_usage")
|
|
238
|
-
.select([
|
|
242
|
+
.select([
|
|
243
|
+
"id",
|
|
244
|
+
"org_id",
|
|
245
|
+
"extension",
|
|
246
|
+
"kind",
|
|
247
|
+
"provider",
|
|
248
|
+
"model",
|
|
249
|
+
"input_tokens",
|
|
250
|
+
"output_tokens",
|
|
251
|
+
"cache_read_tokens",
|
|
252
|
+
"cache_write_tokens",
|
|
253
|
+
"output_images",
|
|
254
|
+
"occurred_at",
|
|
255
|
+
])
|
|
239
256
|
.where("id", "=", id)
|
|
240
257
|
.executeTakeFirst();
|
|
241
258
|
if (!row)
|
|
242
259
|
return null;
|
|
243
260
|
return {
|
|
244
261
|
eventId: row.id,
|
|
245
|
-
purpose: "embedding",
|
|
262
|
+
purpose: row.kind === "image_generation" ? "image" : "embedding",
|
|
246
263
|
orgId: row.org_id,
|
|
247
264
|
extension: row.extension,
|
|
248
265
|
provider: row.provider,
|
|
249
266
|
model: row.model,
|
|
250
267
|
usage: {
|
|
251
268
|
inputTokens: row.input_tokens,
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
269
|
+
// an embedding row's are 0: only an image answer carries output and cache tokens
|
|
270
|
+
outputTokens: row.output_tokens,
|
|
271
|
+
cacheReadTokens: row.cache_read_tokens,
|
|
272
|
+
cacheWriteTokens: row.cache_write_tokens,
|
|
273
|
+
...(row.output_images > 0 && { outputImages: row.output_images }),
|
|
255
274
|
},
|
|
256
275
|
occurredAt: new Date(row.occurred_at).toISOString(),
|
|
257
276
|
};
|
|
@@ -335,6 +354,7 @@ let UsageReporter = class UsageReporter {
|
|
|
335
354
|
outputTokens: p.outputTokens,
|
|
336
355
|
cacheReadTokens: p.cacheReadTokens,
|
|
337
356
|
cacheWriteTokens: p.cacheWriteTokens,
|
|
357
|
+
...(typeof p.outputImages === "number" && { outputImages: p.outputImages }),
|
|
338
358
|
},
|
|
339
359
|
occurredAt: new Date(row.created_at).toISOString(),
|
|
340
360
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { validateAllowHost } from "@capybara-hq/plugin-sdk";
|
|
3
3
|
import { ApiError } from "../../errors.js";
|
|
4
|
+
import { generateImagePaths } from "../../tools/builtins/image/paths.js";
|
|
4
5
|
import { coversHost } from "../modes.js";
|
|
5
6
|
import { hostsWithinOuter, permissionScopeHash } from "../permission-facts.js";
|
|
6
7
|
import { parseCommand } from "./rules.js";
|
|
@@ -49,15 +50,30 @@ export function buildPermissionCandidate(call, facts) {
|
|
|
49
50
|
if (!base.some((root) => withinDirectory(normalized, root)))
|
|
50
51
|
(write ? writes : reads).push(normalized);
|
|
51
52
|
};
|
|
53
|
+
// the paths a file call names: `file_path`, or every path a `GenerateImage` call writes into the
|
|
54
|
+
// device (none without `file_path`; the suffixed paths of several images), each judged
|
|
55
|
+
const targets = call.toolKey === "GenerateImage"
|
|
56
|
+
? generateImagePaths(call.validatedInput)
|
|
57
|
+
: ["Read", "Write", "Edit"].includes(call.toolKey) && typeof input?.file_path === "string"
|
|
58
|
+
? [input.file_path]
|
|
59
|
+
: [];
|
|
52
60
|
try {
|
|
53
|
-
if (
|
|
54
|
-
if (input.file_path.length > 4096 || /[\0*?[\]{}]/.test(input.file_path))
|
|
55
|
-
throw new Error("Invalid target path");
|
|
56
|
-
targetPath = path.posix.resolve(facts.workingRoot, input.file_path);
|
|
61
|
+
if (targets.length > 0) {
|
|
57
62
|
const write = call.toolKey !== "Read", base = write ? facts.baseWriteDirectories : facts.baseReadDirectories;
|
|
58
|
-
|
|
59
|
-
|
|
63
|
+
const resolved = targets.map((target) => {
|
|
64
|
+
if (target.length > 4096 || /[\0*?[\]{}]/.test(target))
|
|
65
|
+
throw new Error("Invalid target path");
|
|
66
|
+
return path.posix.resolve(facts.workingRoot, target);
|
|
67
|
+
});
|
|
68
|
+
for (const target of resolved) {
|
|
69
|
+
if (!base.some((root) => withinDirectory(target, root))) {
|
|
70
|
+
proposeDirectory(path.posix.dirname(target), write);
|
|
71
|
+
}
|
|
60
72
|
}
|
|
73
|
+
// what the person approves: every path the call writes
|
|
74
|
+
targetPath = resolved.join(", ");
|
|
75
|
+
if (targetPath.length > 4096)
|
|
76
|
+
throw new Error("Invalid target path");
|
|
61
77
|
}
|
|
62
78
|
else if (call.toolKey === "Bash" && typeof input?.command === "string") {
|
|
63
79
|
const parsed = parseCommand(input.command);
|
|
@@ -39,7 +39,7 @@ export interface ReviewInput {
|
|
|
39
39
|
conversationId: string;
|
|
40
40
|
runId: string;
|
|
41
41
|
accountId: string;
|
|
42
|
-
/** `Bash` / `Write` / `Edit
|
|
42
|
+
/** `Bash` / `Write` / `Edit` / `GenerateImage` with `file_path`; others are not reviewed. */
|
|
43
43
|
toolKey: string;
|
|
44
44
|
/** The validated tool input (the command for `Bash`, the path for a file write). */
|
|
45
45
|
input: unknown;
|
|
@@ -15,6 +15,7 @@ import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
|
15
15
|
import { KERNEL_LOGGER } from "../../infra/tokens.js";
|
|
16
16
|
import { ModelPurposesService } from "../../models/purposes.js";
|
|
17
17
|
import { StepLog } from "../../runtime/step-log.js";
|
|
18
|
+
import { generateImagePaths } from "../../tools/builtins/image/paths.js";
|
|
18
19
|
import { boundMessages, newReviewTag, REVIEW_ASK_REASON, REVIEW_PURPOSE, runClassifier, } from "./classifier.js";
|
|
19
20
|
import { reviewRules, reviewWrite, writtenPaths } from "./rules.js";
|
|
20
21
|
import { applySessionGrants, isSessionGrantableRule, } from "./types.js";
|
|
@@ -29,8 +30,14 @@ export const REVIEW_REASONS = {
|
|
|
29
30
|
/** The person allowed this rule class for the conversation. */
|
|
30
31
|
sessionGrant: "Allowed for the rest of this conversation by an earlier approval.",
|
|
31
32
|
};
|
|
32
|
-
/**
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* The tools the review covers: the shell, and the file tools whose writes may leave the workspace
|
|
35
|
+
* (`GenerateImage` writes its images into the device at `file_path`, reviewed as a `Write`; a call
|
|
36
|
+
* without `file_path` writes nothing there and is not reviewed).
|
|
37
|
+
*/
|
|
38
|
+
const REVIEWED_TOOLS = new Set(["Bash", "Write", "Edit", "GenerateImage"]);
|
|
39
|
+
/** The reviewed tools that write a file at `file_path` (the rest run a shell command). */
|
|
40
|
+
const WRITE_TOOLS = new Set(["Write", "Edit", "GenerateImage"]);
|
|
34
41
|
/** How many of a conversation tree's latest assistant messages the review reads for its writes. */
|
|
35
42
|
const WRITTEN_EVENTS_READ = 200;
|
|
36
43
|
/** How many of the root conversation's latest person messages are read before bounding the text. */
|
|
@@ -97,16 +104,21 @@ let CommandReviewService = class CommandReviewService {
|
|
|
97
104
|
if (!REVIEWED_TOOLS.has(input.toolKey) && !input.permissionProfile) {
|
|
98
105
|
return allow(REVIEW_REASONS.notReviewed, null);
|
|
99
106
|
}
|
|
100
|
-
|
|
101
|
-
|
|
107
|
+
// a path call: the file writes, and a `Read` under a permission profile (its path is judged)
|
|
108
|
+
const isWrite = WRITE_TOOLS.has(input.toolKey) ||
|
|
102
109
|
(input.toolKey === "Read" && input.permissionProfile !== undefined);
|
|
110
|
+
// every path the call names (a GenerateImage call without file_path writes none)
|
|
111
|
+
const paths = isWrite ? writePathsOf(input.toolKey, input.input) : [];
|
|
112
|
+
if (isWrite && paths.length === 0)
|
|
113
|
+
return allow(REVIEW_REASONS.notReviewed, null);
|
|
103
114
|
if (input.mode === "sandbox" && isWrite && !input.permissionProfile) {
|
|
104
115
|
return allow(REVIEW_REASONS.sandboxWrite, null);
|
|
105
116
|
}
|
|
106
117
|
const workspace = input.workspace;
|
|
107
118
|
if (workspace === undefined)
|
|
108
119
|
return allow(REVIEW_REASONS.noDevice, null);
|
|
109
|
-
|
|
120
|
+
// the classifier reads every path a write call writes, one per line
|
|
121
|
+
const target = isWrite ? paths.join("\n") : commandOf(input.input);
|
|
110
122
|
if (target === null) {
|
|
111
123
|
// argument validation runs before this stage; a shape the tool itself will refuse
|
|
112
124
|
return allow(REVIEW_REASONS.notReviewed, null);
|
|
@@ -125,7 +137,7 @@ let CommandReviewService = class CommandReviewService {
|
|
|
125
137
|
};
|
|
126
138
|
// running a file this conversation wrote is not a development command (hardening spec R1)
|
|
127
139
|
const result = isWrite
|
|
128
|
-
?
|
|
140
|
+
? reviewWrites(paths, facts)
|
|
129
141
|
: reviewRules(target, {
|
|
130
142
|
...facts,
|
|
131
143
|
written: await this.writtenInTree(await rootOf(), facts),
|
|
@@ -305,8 +317,10 @@ let CommandReviewService = class CommandReviewService {
|
|
|
305
317
|
const written = new Set();
|
|
306
318
|
for (const row of rows) {
|
|
307
319
|
for (const call of toolCallsOf(row.payload)) {
|
|
308
|
-
if ((call.name
|
|
309
|
-
|
|
320
|
+
if (WRITE_TOOLS.has(call.name)) {
|
|
321
|
+
for (const path of writePathsOf(call.name, call.input)) {
|
|
322
|
+
written.add(path.startsWith("/") ? path : `${facts.workspace}/${path}`);
|
|
323
|
+
}
|
|
310
324
|
}
|
|
311
325
|
else if (call.name === "Bash" && typeof call.command === "string") {
|
|
312
326
|
for (const path of writtenPaths(call.command, facts))
|
|
@@ -356,7 +370,7 @@ function toolCallsOf(payload) {
|
|
|
356
370
|
if (block.type !== "tool_call" || typeof block.name !== "string")
|
|
357
371
|
return [];
|
|
358
372
|
const input = (block.input ?? {});
|
|
359
|
-
return [{ name: block.name,
|
|
373
|
+
return [{ name: block.name, input: block.input, command: input.command }];
|
|
360
374
|
});
|
|
361
375
|
}
|
|
362
376
|
/** The text blocks of a `user_message` payload (its images, documents and attachments are skipped). */
|
|
@@ -379,8 +393,25 @@ function commandOf(input) {
|
|
|
379
393
|
const command = input?.command;
|
|
380
394
|
return typeof command === "string" ? command : null;
|
|
381
395
|
}
|
|
382
|
-
/**
|
|
383
|
-
|
|
396
|
+
/**
|
|
397
|
+
* The paths a validated write call writes: `Write` / `Edit`'s `file_path`, every path of a
|
|
398
|
+
* `GenerateImage` call ({@link generateImagePaths}: none without `file_path`, the suffixed paths
|
|
399
|
+
* of several images). Empty when there is none (the file tools refuse such an input).
|
|
400
|
+
*/
|
|
401
|
+
function writePathsOf(toolKey, input) {
|
|
402
|
+
if (toolKey === "GenerateImage")
|
|
403
|
+
return generateImagePaths(input);
|
|
384
404
|
const path = input?.file_path;
|
|
385
|
-
return typeof path === "string" ? path :
|
|
405
|
+
return typeof path === "string" ? [path] : [];
|
|
406
|
+
}
|
|
407
|
+
const OUTCOME_RANK = { allow: 0, unsure: 1, ask: 2, deny: 3 };
|
|
408
|
+
/**
|
|
409
|
+
* The review of a call that writes several paths: each path reviewed as a `Write`, the worst
|
|
410
|
+
* outcome deciding (deny, then ask, then unsure) over all their hits, so the call is allowed only
|
|
411
|
+
* when every path is and a session grant settles it only when it covers every path's asks.
|
|
412
|
+
*/
|
|
413
|
+
function reviewWrites(paths, facts) {
|
|
414
|
+
const results = paths.map((p) => reviewWrite(p, facts));
|
|
415
|
+
const outcome = results.reduce((worst, r) => (OUTCOME_RANK[r.outcome] > OUTCOME_RANK[worst] ? r.outcome : worst), "allow");
|
|
416
|
+
return { outcome, hits: results.flatMap((r) => r.hits) };
|
|
386
417
|
}
|
|
@@ -26,6 +26,7 @@ export declare const BUILTIN: {
|
|
|
26
26
|
readonly TaskList: "TaskList";
|
|
27
27
|
readonly WebSearch: "WebSearch";
|
|
28
28
|
readonly WebFetch: "WebFetch";
|
|
29
|
+
readonly GenerateImage: "GenerateImage";
|
|
29
30
|
readonly Platform: "Platform";
|
|
30
31
|
readonly CurrentTime: "CurrentTime";
|
|
31
32
|
readonly ScheduleCreate: "ScheduleCreate";
|
|
@@ -67,7 +68,8 @@ export declare const SCHEDULE_TOOL_NAMES: readonly BuiltinName[];
|
|
|
67
68
|
* by the registry; `Agent` dispatches sub-agents and its description is built per agent;
|
|
68
69
|
* `SendMessage` and `SubagentHandback` are added by the registry ({@link SUBAGENT_MESSAGE_TOOLS}).
|
|
69
70
|
* `Platform` calls the platform's own operations as the run's person (Platform tool spec).
|
|
70
|
-
* `CurrentTime` reads the clock (the run context carries only the date).
|
|
71
|
+
* `CurrentTime` reads the clock (the run context carries only the date). `GenerateImage` makes
|
|
72
|
+
* images with the org's `image` purpose model (image generation spec §5.3). The schedule tools
|
|
71
73
|
* manage the person's scheduled tasks ({@link SCHEDULE_TOOL_NAMES}).
|
|
72
74
|
*/
|
|
73
75
|
export declare const BUILTIN_TOOL_NAMES: readonly BuiltinName[];
|
|
@@ -25,6 +25,7 @@ export const BUILTIN = {
|
|
|
25
25
|
TaskList: "TaskList",
|
|
26
26
|
WebSearch: "WebSearch",
|
|
27
27
|
WebFetch: "WebFetch",
|
|
28
|
+
GenerateImage: "GenerateImage",
|
|
28
29
|
Platform: "Platform",
|
|
29
30
|
CurrentTime: "CurrentTime",
|
|
30
31
|
ScheduleCreate: "ScheduleCreate",
|
|
@@ -92,7 +93,8 @@ export const SCHEDULE_TOOL_NAMES = [
|
|
|
92
93
|
* by the registry; `Agent` dispatches sub-agents and its description is built per agent;
|
|
93
94
|
* `SendMessage` and `SubagentHandback` are added by the registry ({@link SUBAGENT_MESSAGE_TOOLS}).
|
|
94
95
|
* `Platform` calls the platform's own operations as the run's person (Platform tool spec).
|
|
95
|
-
* `CurrentTime` reads the clock (the run context carries only the date).
|
|
96
|
+
* `CurrentTime` reads the clock (the run context carries only the date). `GenerateImage` makes
|
|
97
|
+
* images with the org's `image` purpose model (image generation spec §5.3). The schedule tools
|
|
96
98
|
* manage the person's scheduled tasks ({@link SCHEDULE_TOOL_NAMES}).
|
|
97
99
|
*/
|
|
98
100
|
export const BUILTIN_TOOL_NAMES = [
|
|
@@ -105,6 +107,7 @@ export const BUILTIN_TOOL_NAMES = [
|
|
|
105
107
|
BUILTIN.SendMessage,
|
|
106
108
|
BUILTIN.SubagentHandback,
|
|
107
109
|
...WEB_TOOL_NAMES,
|
|
110
|
+
BUILTIN.GenerateImage,
|
|
108
111
|
BUILTIN.Platform,
|
|
109
112
|
BUILTIN.CurrentTime,
|
|
110
113
|
...SCHEDULE_TOOL_NAMES,
|
|
@@ -188,6 +191,7 @@ export const BUILTIN_TOOL_KINDS = {
|
|
|
188
191
|
[BUILTIN.SubagentHandback]: "meta",
|
|
189
192
|
[BUILTIN.WebSearch]: "search",
|
|
190
193
|
[BUILTIN.WebFetch]: "read",
|
|
194
|
+
[BUILTIN.GenerateImage]: "tool",
|
|
191
195
|
[BUILTIN.Platform]: "tool",
|
|
192
196
|
[BUILTIN.CurrentTime]: "tool",
|
|
193
197
|
[BUILTIN.ScheduleCreate]: "tool",
|