@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
@@ -0,0 +1,43 @@
1
+ import type { EventLog } from "../../conversations/event-log.js";
2
+ import type { StorageService } from "../../storage/storage.service.js";
3
+ import type { BuiltinCallContext } from "../registry.js";
4
+ /**
5
+ * The tool error when the deployment has no object store (or it went away): files cannot be
6
+ * delivered. `Deliver` and `GenerateImage` share it.
7
+ */
8
+ export declare const NO_STORAGE = "File storage is not configured in this deployment, so files cannot be delivered; ask an administrator, or provide the result in your reply instead.";
9
+ /** The same as the "tool unavailable" reason (the kernel adds the final period). */
10
+ export declare const NO_STORAGE_REASON: string;
11
+ /** What {@link storeArtifacts} needs. */
12
+ export interface ArtifactStoreDeps {
13
+ storage: Pick<StorageService, "kernel">;
14
+ eventLog: Pick<EventLog, "append"> & Partial<Pick<EventLog, "publishChanged">>;
15
+ }
16
+ /** One file to deliver as an artifact. */
17
+ export interface ArtifactFile {
18
+ /** The name shown to the user (already checked with `isValidArtifactName`). */
19
+ name: string;
20
+ contentType: string;
21
+ data: Uint8Array;
22
+ /**
23
+ * Where the file came from, which groups deliveries into versions in the conversation's files:
24
+ * the device path for `Deliver`, `generated/<callId>/<name>` for a generated file.
25
+ */
26
+ sourcePath: string;
27
+ }
28
+ /** A stored artifact as the tool result names it. */
29
+ export interface StoredArtifact {
30
+ artifactId: string;
31
+ name: string;
32
+ size: number;
33
+ }
34
+ /**
35
+ * Stores `files` as artifacts of the call's conversation, all or none: every object is uploaded
36
+ * under the kernel prefix (`artifacts/<conversationId>/<artifactId>`), then all their
37
+ * `artifact_created` events (the call's run and `callId`) go into the log in one append. Any
38
+ * failure, an abort of the call before the append included, deletes every object uploaded so far
39
+ * (best effort; one left behind is unreferenced and goes with the conversation's purge) and
40
+ * rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The conversation's
41
+ * files are announced changed once.
42
+ */
43
+ export declare function storeArtifacts(deps: ArtifactStoreDeps, ctx: BuiltinCallContext, files: readonly ArtifactFile[]): Promise<StoredArtifact[]>;
@@ -0,0 +1,67 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ExtensionPointUnavailableError, ToolError } from "@capybara-hq/plugin-sdk";
3
+ import { ApiError } from "../../errors.js";
4
+ /**
5
+ * The tool error when the deployment has no object store (or it went away): files cannot be
6
+ * delivered. `Deliver` and `GenerateImage` share it.
7
+ */
8
+ export const NO_STORAGE = "File storage is not configured in this deployment, so files cannot be delivered; ask an administrator, or provide the result in your reply instead.";
9
+ /** The same as the "tool unavailable" reason (the kernel adds the final period). */
10
+ export const NO_STORAGE_REASON = NO_STORAGE.slice(0, -1);
11
+ const isStorageGone = (e) => (e instanceof ApiError && e.code === "storage.unavailable") ||
12
+ e instanceof ExtensionPointUnavailableError;
13
+ /**
14
+ * Stores `files` as artifacts of the call's conversation, all or none: every object is uploaded
15
+ * under the kernel prefix (`artifacts/<conversationId>/<artifactId>`), then all their
16
+ * `artifact_created` events (the call's run and `callId`) go into the log in one append. Any
17
+ * failure, an abort of the call before the append included, deletes every object uploaded so far
18
+ * (best effort; one left behind is unreferenced and goes with the conversation's purge) and
19
+ * rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The conversation's
20
+ * files are announced changed once.
21
+ */
22
+ export async function storeArtifacts(deps, ctx, files) {
23
+ const uploaded = [];
24
+ const events = [];
25
+ const out = [];
26
+ try {
27
+ const store = deps.storage.kernel(ctx.orgId);
28
+ for (const f of files) {
29
+ const artifactId = randomUUID();
30
+ const objectKey = `artifacts/${ctx.conversationId}/${artifactId}`;
31
+ await store.put(objectKey, f.data, {
32
+ contentType: f.contentType,
33
+ size: f.data.byteLength,
34
+ signal: ctx.signal,
35
+ });
36
+ uploaded.push(objectKey);
37
+ events.push({
38
+ type: "artifact_created",
39
+ ...(ctx.runId !== undefined && { runId: ctx.runId }),
40
+ payload: {
41
+ artifactId,
42
+ name: f.name,
43
+ contentType: f.contentType,
44
+ size: f.data.byteLength,
45
+ objectKey,
46
+ sourcePath: f.sourcePath,
47
+ callId: ctx.callId,
48
+ },
49
+ });
50
+ out.push({ artifactId, name: f.name, size: f.data.byteLength });
51
+ }
52
+ // a call stopped while uploading writes no event: its objects are removed below
53
+ ctx.signal.throwIfAborted();
54
+ await deps.eventLog.append(ctx.conversationId, events);
55
+ }
56
+ catch (e) {
57
+ // no event references them: remove what was uploaded (best effort)
58
+ await Promise.all(uploaded.map((key) => Promise.resolve()
59
+ .then(() => deps.storage.kernel(ctx.orgId).delete(key))
60
+ .catch(() => { })));
61
+ if (isStorageGone(e))
62
+ throw new ToolError(NO_STORAGE);
63
+ throw e;
64
+ }
65
+ await deps.eventLog.publishChanged?.(ctx.conversationId, "files");
66
+ return out;
67
+ }
@@ -8,11 +8,13 @@ import { ConversationDevices } from "../../devices/conversation-devices.js";
8
8
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
9
9
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
10
10
  import { KernelDb } from "../../infra/database/kernel-db.js";
11
+ import { ModelImages } from "../../models/images.js";
11
12
  import { ModelPurposesService } from "../../models/purposes.js";
12
13
  import { PlatformActor } from "../../platform/actor.js";
13
14
  import { AgentDocs } from "../../platform/agent-docs.js";
14
15
  import { PlatformOperations } from "../../platform/registry.js";
15
16
  import type { HookRunner } from "../../runtime/hook-calls.js";
17
+ import { ProviderRegistry } from "../../runtime/providers.js";
16
18
  import { StepLog } from "../../runtime/step-log.js";
17
19
  import { LegacyRetirementStore } from "../../sandbox/legacy-retirement.js";
18
20
  import { type ManagedDeviceContextPort, ManagedDeviceContextRecorder } from "../../sandbox/managed-device-context.js";
@@ -45,6 +47,8 @@ export declare class BuiltinTools {
45
47
  scheduleUpdates: ScheduleUpdates,
46
48
  /** The task service, bound by `SchedulesModule` at start (a registration port: no cycle). */
47
49
  schedulePort: ScheduleToolsPort,
50
+ /** `GenerateImage`: the image calls, and the image model's availability per listing. */
51
+ images: ModelImages, providers: ProviderRegistry,
48
52
  /** The clock `CurrentTime` reads (the run context's clock seam; `Date.now` by default). */
49
53
  /** The managed sandbox route's device context writer (permission context replay spec B3). */
50
54
  managedDeviceContext: ManagedDeviceContextRecorder, now?: () => number,
@@ -21,11 +21,13 @@ import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
21
21
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
22
22
  import { KernelDb } from "../../infra/database/kernel-db.js";
23
23
  import { KERNEL_LOGGER } from "../../infra/tokens.js";
24
+ import { ModelImages } from "../../models/images.js";
24
25
  import { ModelPurposesService } from "../../models/purposes.js";
25
26
  import { readOrgSettings } from "../../orgs/settings.service.js";
26
27
  import { PlatformActor } from "../../platform/actor.js";
27
28
  import { AgentDocs } from "../../platform/agent-docs.js";
28
29
  import { PlatformOperations } from "../../platform/registry.js";
30
+ import { ProviderRegistry } from "../../runtime/providers.js";
29
31
  import { conversationTimeZone, RUN_CONTEXT_CLOCK } from "../../runtime/run-context.service.js";
30
32
  import { StepLog } from "../../runtime/step-log.js";
31
33
  import { LegacyRetirementStore } from "../../sandbox/legacy-retirement.js";
@@ -39,6 +41,7 @@ import { agentTool } from "./agent.js";
39
41
  import { askUserTool } from "./ask-user.js";
40
42
  import { currentTimeTool } from "./current-time.js";
41
43
  import { handbackTool } from "./handback.js";
44
+ import { generateImageTool } from "./image/index.js";
42
45
  import { platformTool } from "./platform.js";
43
46
  import { readToolOutputTool } from "./read-tool-output.js";
44
47
  import { sandboxTools } from "./sandbox/index.js";
@@ -66,6 +69,8 @@ let BuiltinTools = class BuiltinTools {
66
69
  scheduleUpdates,
67
70
  /** The task service, bound by `SchedulesModule` at start (a registration port: no cycle). */
68
71
  schedulePort,
72
+ /** `GenerateImage`: the image calls, and the image model's availability per listing. */
73
+ images, providers,
69
74
  /** The clock `CurrentTime` reads (the run context's clock seam; `Date.now` by default). */
70
75
  /** The managed sandbox route's device context writer (permission context replay spec B3). */
71
76
  managedDeviceContext, now,
@@ -124,6 +129,22 @@ let BuiltinTools = class BuiltinTools {
124
129
  cache: webPages,
125
130
  extract: (ctx, page, prompt) => extractAnswer({ purposes, eventLog, stepLog, config, log, hooks: host?.hooks }, ctx, page, prompt),
126
131
  }),
132
+ // images from the org's `image` purpose model, delivered as artifacts (image generation
133
+ // spec §5.3); written into the device too with `file_path`
134
+ generateImageTool({
135
+ images,
136
+ purposes,
137
+ providers,
138
+ storage,
139
+ eventLog,
140
+ stepLog,
141
+ config,
142
+ log,
143
+ hooks: host?.hooks,
144
+ db: () => db.db,
145
+ attachments,
146
+ sandbox: sandboxDeps,
147
+ }),
127
148
  // the platform's own operations and docs, as the run's person (Platform tool spec)
128
149
  platformTool({
129
150
  ops: platformOps,
@@ -180,11 +201,13 @@ BuiltinTools = __decorate([
180
201
  __param(21, Inject(ScheduledTaskStore)),
181
202
  __param(22, Inject(ScheduleUpdates)),
182
203
  __param(23, Inject(ScheduleToolsPort)),
183
- __param(24, Inject(ManagedDeviceContextRecorder)),
184
- __param(25, Optional()),
185
- __param(25, Inject(RUN_CONTEXT_CLOCK)),
186
- __param(26, Optional()),
187
- __param(26, Inject(PERMISSION_CONTEXT_ACTIVATION))
204
+ __param(24, Inject(ModelImages)),
205
+ __param(25, Inject(ProviderRegistry)),
206
+ __param(26, Inject(ManagedDeviceContextRecorder)),
207
+ __param(27, Optional()),
208
+ __param(27, Inject(RUN_CONTEXT_CLOCK)),
209
+ __param(28, Optional()),
210
+ __param(28, Inject(PERMISSION_CONTEXT_ACTIVATION))
188
211
  ], BuiltinTools);
189
212
  export { BuiltinTools };
190
213
  /**
@@ -0,0 +1,59 @@
1
+ import { type ImageMediaType, type Logger, type ToolSpec } from "@capybara-hq/plugin-sdk";
2
+ import type { AttachmentsService } from "../../../conversations/attachments.service.js";
3
+ import type { EventLog } from "../../../conversations/event-log.js";
4
+ import type { KernelSchemaDb } from "../../../db/kernel-schema.js";
5
+ import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
6
+ import { type ModelImages } from "../../../models/images.js";
7
+ import type { ModelPurposesService } from "../../../models/purposes.js";
8
+ import { type HookRunner } from "../../../runtime/hook-calls.js";
9
+ import { type ProviderRegistry } from "../../../runtime/providers.js";
10
+ import type { StepLog } from "../../../runtime/step-log.js";
11
+ import type { StorageService } from "../../../storage/storage.service.js";
12
+ import type { BuiltinTool } from "../../registry.js";
13
+ import { type SandboxToolDeps } from "../sandbox/common.js";
14
+ export declare const GENERATE_IMAGE_SPEC: ToolSpec;
15
+ /** Why the tool is not listed: the org's `image` purpose has no usable model (spec §5.3). */
16
+ export declare const NO_IMAGE_MODEL_REASON = "No image model is configured for this organization";
17
+ /** The tool error when the purpose's model went away after the listing. */
18
+ export declare const NO_IMAGE_MODEL_TEXT = "No image model is configured for this organization; ask an org admin to set a model for the image purpose, or continue without the image.";
19
+ /** The tool error when a `model.request` policy hook denies the call. */
20
+ export declare const GENERATE_IMAGE_DENIED_TEXT = "An org policy blocked this image request; continue without it or ask the user.";
21
+ /** The device line of a call whose conversation has no device to write to. */
22
+ export declare const NO_DEVICE_LINE = "Not written to the device: this conversation has no device.";
23
+ /** What the `GenerateImage` builtin needs (everything read per call: no process state). */
24
+ export interface GenerateImageDeps {
25
+ images: Pick<ModelImages, "prepare" | "run">;
26
+ /** Availability: the org's `image` purpose target, and its model resolved as an image model. */
27
+ purposes: Pick<ModelPurposesService, "resolve">;
28
+ providers: Pick<ProviderRegistry, "resolve">;
29
+ storage: Pick<StorageService, "kernel" | "available">;
30
+ eventLog: Pick<EventLog, "append" | "notify"> & Partial<Pick<EventLog, "publishChanged">>;
31
+ stepLog: Pick<StepLog, "appendCounted" | "appendReported" | "appendAudited">;
32
+ config: Pick<KernelConfigService, "get">;
33
+ log: Pick<Logger, "warn">;
34
+ /** Extension hooks (absent: none fire). */
35
+ hooks?: HookRunner | undefined;
36
+ /** The artifact lookup of `reference_images`. */
37
+ db: () => KernelSchemaDb;
38
+ attachments: Pick<AttachmentsService, "openForConversation">;
39
+ /** The device copy of `file_path` (the sandbox tools' own dependencies). */
40
+ sandbox: SandboxToolDeps;
41
+ }
42
+ /**
43
+ * The builtin `GenerateImage` (image generation spec §5.3): generates images with the org's
44
+ * `image` purpose model ({@link ModelImages}), stores them as artifacts of the conversation as
45
+ * `Deliver` stores a file (all or none, {@link storeArtifacts}), records the call's `usage` event
46
+ * (purpose `image`, the call id, `outputImages`) and, with `file_path`, also writes the images
47
+ * into the device through `Write`'s path checks (the command review covers such a call as a
48
+ * write). Listed only while the purpose resolves to a callable image model and an object store
49
+ * is there. A `model.request` policy denial is logged as any hook denial and sends nothing; a
50
+ * refusal or a failure is an actionable tool error, never retried. The model sees only the result
51
+ * text, so replays never call an image model.
52
+ */
53
+ export declare function generateImageTool(deps: GenerateImageDeps): BuiltinTool;
54
+ /**
55
+ * A written path as the device line names it: the path, followed by the image's media type when
56
+ * the path's extension is not one of that type's (`out/a.jpg (image/png)`), so the model knows
57
+ * what the file holds whatever it was called.
58
+ */
59
+ export declare function deviceEntry(path: string, mediaType: ImageMediaType): string;