@capybara-hq/kernel 0.1.0-rc.63 → 0.1.0-rc.65
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/org-catalog.schemas.d.ts +1 -1
- package/dist/catalog/org-catalog.schemas.js +1 -1
- package/dist/channels/actions.d.ts +2 -5
- package/dist/channels/actions.js +20 -8
- package/dist/channels/cards.d.ts +4 -3
- package/dist/channels/cards.js +6 -4
- package/dist/channels/outbound.js +3 -2
- package/dist/config/schema.js +1 -1
- package/dist/conversations/approval-profile.d.ts +30 -0
- package/dist/conversations/approval-profile.js +62 -0
- package/dist/conversations/conversations.service.js +0 -2
- package/dist/conversations/events.d.ts +46 -2
- package/dist/conversations/events.js +55 -2
- package/dist/conversations/permission-profiles.controller.d.ts +3 -2
- package/dist/conversations/permission-profiles.service.d.ts +3 -2
- package/dist/conversations/permission-profiles.service.js +12 -8
- package/dist/db/kernel-schema.d.ts +4 -2
- package/dist/identity/initial-passwords.controller.d.ts +8 -6
- package/dist/identity/initial-passwords.controller.js +13 -7
- package/dist/identity/initial-passwords.d.ts +22 -13
- package/dist/identity/initial-passwords.js +25 -29
- package/dist/local-devices/relay.js +3 -1
- package/dist/models/images.js +5 -4
- package/dist/platform/connector-person-fields.js +2 -2
- package/dist/platform/exclusions.js +4 -4
- package/dist/platform/method.js +1 -1
- package/dist/platform/operation.d.ts +9 -7
- package/dist/platform/operation.js +1 -1
- package/dist/platform/ops/accounts.ops.d.ts +1 -1
- package/dist/platform/ops/accounts.ops.js +3 -3
- package/dist/platform/ops/channels.ops.d.ts +1 -1
- package/dist/platform/ops/channels.ops.js +2 -2
- package/dist/platform/ops/connectors.ops.d.ts +2 -2
- package/dist/platform/ops/connectors.ops.js +8 -8
- package/dist/platform/ops/extensions-admin.ops.d.ts +1 -1
- package/dist/platform/ops/extensions-admin.ops.js +3 -3
- package/dist/platform/ops/extensions.ops.d.ts +1 -1
- package/dist/platform/ops/extensions.ops.js +4 -4
- package/dist/platform/ops/org-plugins.ops.js +2 -2
- package/dist/platform/ops/orgs.ops.d.ts +1 -1
- package/dist/platform/ops/orgs.ops.js +3 -3
- package/dist/platform/ops/plugins.ops.d.ts +1 -1
- package/dist/platform/ops/plugins.ops.js +2 -2
- package/dist/platform/person-fields.d.ts +4 -3
- package/dist/platform/person-fields.js +6 -5
- package/dist/platform/sealed-inputs.d.ts +2 -2
- package/dist/platform/sealed-inputs.js +2 -2
- package/dist/platform/sealed-reveals.controller.d.ts +5 -8
- package/dist/platform/sealed-reveals.controller.js +8 -8
- package/dist/platform/sealed-reveals.d.ts +19 -17
- package/dist/platform/sealed-reveals.js +30 -33
- package/dist/runtime/context/build.js +3 -0
- package/dist/runtime/context/compaction.js +2 -0
- package/dist/runtime/waits.js +3 -2
- package/dist/sandbox/operation-authority.js +16 -15
- package/dist/sandbox/operation-intents.js +2 -2
- package/dist/sandbox/permission-availability.d.ts +49 -3
- package/dist/sandbox/permission-availability.js +61 -6
- package/dist/sandbox/permission-call-types.d.ts +3 -0
- package/dist/sandbox/permission-facts.d.ts +29 -1
- package/dist/sandbox/permission-facts.js +30 -6
- package/dist/sandbox/permission-runtime-reports.js +1 -0
- package/dist/sandbox/review/classifier.d.ts +72 -2
- package/dist/sandbox/review/classifier.js +113 -38
- package/dist/sandbox/review/index.d.ts +2 -2
- package/dist/sandbox/review/index.js +1 -1
- package/dist/sandbox/review/review.service.d.ts +1 -4
- package/dist/sandbox/review/review.service.js +4 -33
- package/dist/setup/setup-guides.service.js +1 -1
- package/dist/tools/approvals.service.d.ts +71 -16
- package/dist/tools/approvals.service.js +139 -13
- package/dist/tools/builtins/builtin-tools.d.ts +1 -1
- package/dist/tools/builtins/builtin-tools.js +12 -6
- package/dist/tools/builtins/platform.d.ts +15 -11
- package/dist/tools/builtins/platform.js +49 -39
- package/dist/tools/builtins/sandbox/bash.d.ts +1 -1
- package/dist/tools/builtins/sandbox/bash.js +32 -14
- package/dist/tools/builtins/sandbox/common.d.ts +12 -3
- package/dist/tools/builtins/sandbox/common.js +29 -5
- package/dist/tools/connectors.schemas.d.ts +1 -1
- package/dist/tools/connectors.schemas.js +1 -1
- package/dist/tools/pipeline.d.ts +70 -10
- package/dist/tools/pipeline.js +359 -49
- package/dist/tools/policy.d.ts +4 -3
- package/dist/tools/policy.js +6 -6
- package/dist/tools/registry.d.ts +25 -9
- package/dist/tools/tool-review.d.ts +113 -0
- package/dist/tools/tool-review.js +303 -0
- package/dist/tools/tools.module.js +6 -0
- package/package.json +3 -3
- package/src/migrations/0175_secure_input_kind.sql +8 -0
|
@@ -1,19 +1,74 @@
|
|
|
1
|
+
import { instanceSupported, SandboxPermissionUnsupportedError, } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
/**
|
|
3
|
+
* Admission's refusal of device work on a device that cannot run permission-scoped operations:
|
|
4
|
+
* nothing was sent. It extends {@link SandboxPermissionUnsupportedError} (and keeps its name), so
|
|
5
|
+
* every check that treats that error as a definite refusal treats this one the same way; the
|
|
6
|
+
* model's text is rendered from `cause` (`admissionUnavailableText`), never from the message,
|
|
7
|
+
* which is the availability reason (a provider may write it). Exported to tools from
|
|
8
|
+
* `tools/builtins/sandbox/common.ts`.
|
|
9
|
+
*/
|
|
10
|
+
export class PermissionAdmissionUnavailable extends SandboxPermissionUnsupportedError {
|
|
11
|
+
cause;
|
|
12
|
+
constructor(cause, reason) {
|
|
13
|
+
super(reason);
|
|
14
|
+
this.cause = cause;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
1
17
|
export const unprobedPermissionAvailability = () => ({
|
|
2
18
|
state: "unprobed",
|
|
3
19
|
reason: "Checked when this device starts",
|
|
4
20
|
});
|
|
5
21
|
/** Method presence is only an unknown runtime candidate, never evidence of enforcement support.
|
|
6
22
|
* No capability probe or lifecycle operation runs here, even for an empty or suspended device.
|
|
7
|
-
* Task 6 records provenance-bound runtime reports before user execution can be admitted.
|
|
23
|
+
* Task 6 records provenance-bound runtime reports before user execution can be admitted. A
|
|
24
|
+
* provider without the permission-scoped methods is an outdated plugin, named with its version
|
|
25
|
+
* (ruling R9).
|
|
8
26
|
*/
|
|
9
27
|
export function permissionAvailabilityFor(provider) {
|
|
10
|
-
if (!provider
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
28
|
+
if (!provider)
|
|
29
|
+
return {
|
|
30
|
+
state: "unsupported",
|
|
31
|
+
reason: "This device's sandbox provider is not available",
|
|
32
|
+
cause: { kind: "runtime" },
|
|
33
|
+
};
|
|
34
|
+
const { impl, plugin } = provider;
|
|
35
|
+
if (typeof impl.operation !== "function" ||
|
|
36
|
+
typeof impl.permissionSupport !== "function" ||
|
|
37
|
+
typeof impl.revokeOperation !== "function") {
|
|
38
|
+
const version = provider.version ?? "unknown version";
|
|
14
39
|
return {
|
|
15
40
|
state: "unsupported",
|
|
16
|
-
reason:
|
|
41
|
+
reason: `This device's sandbox plugin (${plugin} ${version}) does not implement permission-scoped operations; a super admin updates it`,
|
|
42
|
+
cause: { kind: "provider-outdated", plugin, version },
|
|
17
43
|
};
|
|
44
|
+
}
|
|
18
45
|
return unprobedPermissionAvailability();
|
|
19
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Why a recorded runtime report cannot run permission-scoped work on a device at `location`, or
|
|
49
|
+
* null when it can: the one rule admission's withheld scope and the people's view both apply
|
|
50
|
+
* (the "one verdict" rule, B-16). A local machine's sandbox is per operation (only a cloud
|
|
51
|
+
* provider's instance is the sandbox); a runtime without a restricted mode and without an instance
|
|
52
|
+
* boundary only runs outside its sandbox.
|
|
53
|
+
*/
|
|
54
|
+
export function runtimeReportVerdict(report, location) {
|
|
55
|
+
if (report.boundary === "instance" && location === "local")
|
|
56
|
+
return "A local device cannot report an instance boundary";
|
|
57
|
+
if (report.restricted === null && !instanceSupported(report))
|
|
58
|
+
return report.unavailableReason ?? "This device's runtime cannot enforce its sandbox";
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The availability of device work as people see it (the HTTP views): a supported report that
|
|
63
|
+
* {@link runtimeReportVerdict} refuses reads `unsupported` with the runtime cause, as admission
|
|
64
|
+
* refuses it. Kernel readers keep the raw availability (its report decides the provider layer and
|
|
65
|
+
* the kernel read route).
|
|
66
|
+
*/
|
|
67
|
+
export function deviceWorkAvailability(availability, location) {
|
|
68
|
+
if (availability.state !== "supported")
|
|
69
|
+
return availability;
|
|
70
|
+
const reason = runtimeReportVerdict(availability.report, location);
|
|
71
|
+
return reason === null
|
|
72
|
+
? availability
|
|
73
|
+
: { state: "unsupported", reason, cause: { kind: "runtime" } };
|
|
74
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { PermissionProfile } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { HostGrantCeiling } from "./device-sandbox.js";
|
|
3
3
|
import type { EffectiveDevicePolicy } from "./modes.js";
|
|
4
|
+
import type { PermissionAvailabilityCause } from "./permission-availability.js";
|
|
4
5
|
import type { AppliedOuterNetwork } from "./permission-context-types.js";
|
|
5
6
|
export type PermissionCallRef = {
|
|
6
7
|
runId: string;
|
|
@@ -109,9 +110,11 @@ export type PermissionReviewSnapshot = Readonly<Omit<PermissionCallBinding, "too
|
|
|
109
110
|
broadProjectReach: boolean;
|
|
110
111
|
unattended: boolean;
|
|
111
112
|
fullConsent: boolean;
|
|
113
|
+
/** An `unsupported` state carries its cause (R9), from which admission renders the text. */
|
|
112
114
|
availability: {
|
|
113
115
|
state: string;
|
|
114
116
|
reason?: string;
|
|
117
|
+
cause?: PermissionAvailabilityCause;
|
|
115
118
|
};
|
|
116
119
|
/**
|
|
117
120
|
* The reason admission refuses this device (B-16): the recorded permission context withholds
|
|
@@ -185,10 +185,15 @@ export declare class PermissionFacts {
|
|
|
185
185
|
hostCeiling: HostGrantCeiling;
|
|
186
186
|
};
|
|
187
187
|
availability: PermissionAvailability;
|
|
188
|
+
location: "cloud" | "local";
|
|
188
189
|
sandbox: DeviceSandbox;
|
|
189
190
|
outsideSandboxCeiling: boolean;
|
|
190
191
|
broadProjectReach: boolean;
|
|
191
192
|
}>;
|
|
193
|
+
/**
|
|
194
|
+
* The preview people see before choosing a profile: availability is the device-work verdict
|
|
195
|
+
* ({@link deviceWorkAvailability}). Kernel callers only use it as a check.
|
|
196
|
+
*/
|
|
192
197
|
preview(orgId: string, accountId: string, deviceId: string, project?: string): Promise<{
|
|
193
198
|
deviceId: string;
|
|
194
199
|
project: string | null;
|
|
@@ -201,10 +206,11 @@ export declare class PermissionFacts {
|
|
|
201
206
|
restrictedProjectReach: "os-user" | "workspace";
|
|
202
207
|
hostCeiling: HostGrantCeiling;
|
|
203
208
|
};
|
|
204
|
-
|
|
209
|
+
location: "cloud" | "local";
|
|
205
210
|
sandbox: DeviceSandbox;
|
|
206
211
|
outsideSandboxCeiling: boolean;
|
|
207
212
|
broadProjectReach: boolean;
|
|
213
|
+
availability: PermissionAvailability;
|
|
208
214
|
}>;
|
|
209
215
|
view(orgId: string, accountId: string, row: PermissionRoot): Promise<{
|
|
210
216
|
profile: PermissionProfile;
|
|
@@ -222,6 +228,27 @@ export declare class PermissionFacts {
|
|
|
222
228
|
sandbox: DeviceSandbox | null;
|
|
223
229
|
startingWorkNotice: string;
|
|
224
230
|
}>;
|
|
231
|
+
/**
|
|
232
|
+
* {@link view} as people see it (`GET …/permissions`): availability is the device-work verdict
|
|
233
|
+
* admission applies ({@link deviceWorkAvailability}), so a device whose runtime cannot enforce
|
|
234
|
+
* its sandbox reads `unsupported` with the runtime cause. Kernel readers use {@link view}.
|
|
235
|
+
*/
|
|
236
|
+
peopleView(orgId: string, accountId: string, row: PermissionRoot): Promise<{
|
|
237
|
+
availability: PermissionAvailability;
|
|
238
|
+
profile: PermissionProfile;
|
|
239
|
+
revision: number;
|
|
240
|
+
rootConversationId: string;
|
|
241
|
+
deviceId: string | null;
|
|
242
|
+
consentScope: {
|
|
243
|
+
deviceId: string;
|
|
244
|
+
scopeRevision: string;
|
|
245
|
+
} | null;
|
|
246
|
+
scopeRevision: string | null;
|
|
247
|
+
outsideSandboxCeiling: boolean;
|
|
248
|
+
broadProjectReach: boolean;
|
|
249
|
+
sandbox: DeviceSandbox | null;
|
|
250
|
+
startingWorkNotice: string;
|
|
251
|
+
}>;
|
|
225
252
|
/**
|
|
226
253
|
* {@link view} plus how the actor reached the root's device: none selected, usable, refused for
|
|
227
254
|
* this actor (`device.not_found`: not its device), or its provider is not the current one. The
|
|
@@ -229,6 +256,7 @@ export declare class PermissionFacts {
|
|
|
229
256
|
*/
|
|
230
257
|
viewWithAccess(orgId: string, accountId: string, row: PermissionRoot): Promise<{
|
|
231
258
|
access: "actor-device-access" | "device" | "no-device" | "provider-unavailable";
|
|
259
|
+
location: "cloud" | "local" | null;
|
|
232
260
|
view: {
|
|
233
261
|
profile: PermissionProfile;
|
|
234
262
|
revision: number;
|
|
@@ -26,7 +26,7 @@ import { canonicalHostCeiling, effectiveDeviceSandbox, hostGrantCeiling, hostGra
|
|
|
26
26
|
import { readDeviceSandboxSettings } from "./device-sandbox-settings.js";
|
|
27
27
|
import { appliedOf, appliedWider, cloudChosenMode, coversHost, effectiveDevicePolicy, readDeploymentDevicePolicy, readInstanceLimits, } from "./modes.js";
|
|
28
28
|
import { assertAuthorityHeld } from "./permission-authority-lock.js";
|
|
29
|
-
import { permissionAvailabilityFor, } from "./permission-availability.js";
|
|
29
|
+
import { deviceWorkAvailability, permissionAvailabilityFor, } from "./permission-availability.js";
|
|
30
30
|
import { readCurrentReport, readRuntimeReport, sameRuntimeIdentity, } from "./permission-runtime-reports.js";
|
|
31
31
|
import { providerForDevice, SandboxProviders } from "./providers.js";
|
|
32
32
|
import { homeOf } from "./review/rules.js";
|
|
@@ -303,7 +303,7 @@ let PermissionFacts = class PermissionFacts {
|
|
|
303
303
|
.where("org_id", "=", orgId)
|
|
304
304
|
.executeTakeFirst();
|
|
305
305
|
const provider = device ? providerForDevice(this.providers, device.provider) : undefined;
|
|
306
|
-
let availability = permissionAvailabilityFor(provider
|
|
306
|
+
let availability = permissionAvailabilityFor(provider);
|
|
307
307
|
if (availability.state === "unprobed" && provider) {
|
|
308
308
|
const machine = provider.plugin === "@local"
|
|
309
309
|
? await this.db
|
|
@@ -314,6 +314,9 @@ let PermissionFacts = class PermissionFacts {
|
|
|
314
314
|
.executeTakeFirst()
|
|
315
315
|
: undefined;
|
|
316
316
|
availability = await readRuntimeReport(this.db.db, deviceId, provider.plugin, machine?.program_version ?? provider.version);
|
|
317
|
+
// a recorded runtime report that cannot enforce the sandbox is the runtime's cause
|
|
318
|
+
if (availability.state === "unsupported")
|
|
319
|
+
availability = { ...availability, cause: { kind: "runtime" } };
|
|
317
320
|
}
|
|
318
321
|
return availability;
|
|
319
322
|
}
|
|
@@ -535,6 +538,7 @@ let PermissionFacts = class PermissionFacts {
|
|
|
535
538
|
consentIdentity,
|
|
536
539
|
consentReach,
|
|
537
540
|
availability,
|
|
541
|
+
location: source === "local" ? "local" : "cloud",
|
|
538
542
|
sandbox,
|
|
539
543
|
outsideSandboxCeiling: sandbox.outsideSandbox,
|
|
540
544
|
// B2: broad restricted reach (directories outside the working root) is the owner's reach
|
|
@@ -546,16 +550,32 @@ let PermissionFacts = class PermissionFacts {
|
|
|
546
550
|
: policy.mode === "auto" && policy.allowedMode === "auto"),
|
|
547
551
|
};
|
|
548
552
|
}
|
|
553
|
+
/**
|
|
554
|
+
* The preview people see before choosing a profile: availability is the device-work verdict
|
|
555
|
+
* ({@link deviceWorkAvailability}). Kernel callers only use it as a check.
|
|
556
|
+
*/
|
|
549
557
|
async preview(orgId, accountId, deviceId, project) {
|
|
550
558
|
await this.devices.usable(orgId, accountId, deviceId);
|
|
551
559
|
const binding = project === undefined
|
|
552
560
|
? null
|
|
553
561
|
: await this.resolveProjectForBinding(orgId, deviceId, accountId, project);
|
|
554
|
-
|
|
562
|
+
const scope = await this.scope(orgId, deviceId, binding?.path ?? null, project ?? null);
|
|
563
|
+
return { ...scope, availability: deviceWorkAvailability(scope.availability, scope.location) };
|
|
555
564
|
}
|
|
556
565
|
async view(orgId, accountId, row) {
|
|
557
566
|
return (await this.viewWithAccess(orgId, accountId, row)).view;
|
|
558
567
|
}
|
|
568
|
+
/**
|
|
569
|
+
* {@link view} as people see it (`GET …/permissions`): availability is the device-work verdict
|
|
570
|
+
* admission applies ({@link deviceWorkAvailability}), so a device whose runtime cannot enforce
|
|
571
|
+
* its sandbox reads `unsupported` with the runtime cause. Kernel readers use {@link view}.
|
|
572
|
+
*/
|
|
573
|
+
async peopleView(orgId, accountId, row) {
|
|
574
|
+
const { view, location } = await this.viewWithAccess(orgId, accountId, row);
|
|
575
|
+
return location === null
|
|
576
|
+
? view
|
|
577
|
+
: { ...view, availability: deviceWorkAvailability(view.availability, location) };
|
|
578
|
+
}
|
|
559
579
|
/**
|
|
560
580
|
* {@link view} plus how the actor reached the root's device: none selected, usable, refused for
|
|
561
581
|
* this actor (`device.not_found`: not its device), or its provider is not the current one. The
|
|
@@ -580,14 +600,17 @@ let PermissionFacts = class PermissionFacts {
|
|
|
580
600
|
}
|
|
581
601
|
}
|
|
582
602
|
const consent = row.permission_consent;
|
|
603
|
+
// Auto holds whatever the device supports (device tools refuse at admission instead) and
|
|
604
|
+
// without a device (no consent row, ruling R8); with a device it needs that device to be
|
|
605
|
+
// reachable and its consent to still cover the device's ceilings
|
|
583
606
|
const profile = row.permission_profile === "full-access" &&
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
!consentHolds(consent, row.device_id, preview))
|
|
607
|
+
row.device_id !== null &&
|
|
608
|
+
(!preview || !consentHolds(consent, row.device_id, preview))
|
|
587
609
|
? "approve-for-me"
|
|
588
610
|
: row.permission_profile;
|
|
589
611
|
return {
|
|
590
612
|
access,
|
|
613
|
+
location: preview?.location ?? null,
|
|
591
614
|
view: {
|
|
592
615
|
profile,
|
|
593
616
|
revision: row.permission_revision,
|
|
@@ -600,6 +623,7 @@ let PermissionFacts = class PermissionFacts {
|
|
|
600
623
|
availability: preview?.availability ?? {
|
|
601
624
|
state: "unsupported",
|
|
602
625
|
reason: unavailableReason,
|
|
626
|
+
cause: { kind: "runtime" },
|
|
603
627
|
},
|
|
604
628
|
outsideSandboxCeiling: preview?.outsideSandboxCeiling ?? false,
|
|
605
629
|
broadProjectReach: preview?.broadProjectReach ?? false,
|
|
@@ -198,6 +198,7 @@ export async function readCurrentReport(db, deviceId, provider, version) {
|
|
|
198
198
|
availability: {
|
|
199
199
|
state: "unsupported",
|
|
200
200
|
reason: report.unavailableReason ?? "This runtime cannot enforce permission operations",
|
|
201
|
+
cause: { kind: "runtime" },
|
|
201
202
|
},
|
|
202
203
|
identityHash: row.identity_hash,
|
|
203
204
|
instanceGeneration: row.instance_generation,
|
|
@@ -3,6 +3,7 @@ import { z } from "zod";
|
|
|
3
3
|
import type { ModelRef } from "../../agents/definition.js";
|
|
4
4
|
import type { EventLog } from "../../conversations/event-log.js";
|
|
5
5
|
import type { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
6
|
+
import type { KernelDb } from "../../infra/database/kernel-db.js";
|
|
6
7
|
import { type ModelPurposesService } from "../../models/purposes.js";
|
|
7
8
|
import type { ConversationKindForHooks, HookRunner } from "../../runtime/hook-calls.js";
|
|
8
9
|
import type { StepLog } from "../../runtime/step-log.js";
|
|
@@ -103,6 +104,32 @@ export declare function fitReviewInput(input: ReviewClassifierInput, system: str
|
|
|
103
104
|
contextWindow: number;
|
|
104
105
|
maxOutputTokens: number;
|
|
105
106
|
}): ReviewClassifierInput;
|
|
107
|
+
/**
|
|
108
|
+
* Fits one review message to the review model's context: `build` renders the message from its one
|
|
109
|
+
* unbounded part (`text`) and the person's messages; everything else in it is always kept. When
|
|
110
|
+
* the whole does not fit, `text` keeps its beginning and ends with `marker`; the person's messages
|
|
111
|
+
* are cut (newest end kept) only if they alone overflow the model. Shared by the command review
|
|
112
|
+
* and the tool review.
|
|
113
|
+
*/
|
|
114
|
+
export declare function fitReviewText(build: (text: string, personMessages: string) => string, parts: {
|
|
115
|
+
text: string;
|
|
116
|
+
personMessages: string;
|
|
117
|
+
}, system: string, limits: {
|
|
118
|
+
contextWindow: number;
|
|
119
|
+
maxOutputTokens: number;
|
|
120
|
+
}, marker: string): {
|
|
121
|
+
text: string;
|
|
122
|
+
personMessages: string;
|
|
123
|
+
};
|
|
124
|
+
/** How many of the root conversation's latest person messages are read before bounding the text. */
|
|
125
|
+
export declare const PERSON_MESSAGES_READ = 20;
|
|
126
|
+
/**
|
|
127
|
+
* The bounded text of the root conversation's last person messages: the `user_message` text blocks
|
|
128
|
+
* only, never an assistant message or a tool result, newest {@link PERSON_MESSAGES_READ} read and
|
|
129
|
+
* bounded to `budget` estimated tokens (`sandbox.review.messageTokens`). The command review and the
|
|
130
|
+
* tool review read the same messages.
|
|
131
|
+
*/
|
|
132
|
+
export declare function readPersonMessages(db: KernelDb["db"], rootConversationId: string, budget: number): Promise<string>;
|
|
106
133
|
/** The identity facts the hook payloads need (all of them: without one, no hooks fire). */
|
|
107
134
|
export interface ReviewHookFacts {
|
|
108
135
|
accountId: string;
|
|
@@ -120,7 +147,8 @@ export interface ReviewClassifierDeps {
|
|
|
120
147
|
/** Extension hooks (absent: none fire). */
|
|
121
148
|
hooks?: HookRunner | undefined;
|
|
122
149
|
}
|
|
123
|
-
|
|
150
|
+
/** Who, where and how one review model call runs (the command review's and the tool review's). */
|
|
151
|
+
export interface ReviewModelCallArgs {
|
|
124
152
|
orgId: string;
|
|
125
153
|
/** The root conversation: where the person's messages are read and the usage event is written. */
|
|
126
154
|
conversationId: string;
|
|
@@ -133,13 +161,55 @@ export interface RunClassifierArgs {
|
|
|
133
161
|
/** The budget window of the run tree (agent map spec §6), when known. */
|
|
134
162
|
budgetRunId?: string | undefined;
|
|
135
163
|
hookFacts: ReviewHookFacts;
|
|
136
|
-
input: ReviewClassifierInput;
|
|
137
164
|
/** Called with the resolved target and final request just before it is sent (a test seam). */
|
|
138
165
|
beforeSend?: ((target: ModelRef, request: ModelRequest) => Promise<void>) | undefined;
|
|
139
166
|
}
|
|
167
|
+
export interface RunClassifierArgs extends ReviewModelCallArgs {
|
|
168
|
+
input: ReviewClassifierInput;
|
|
169
|
+
}
|
|
170
|
+
/** The texts of the outcomes one review subject (command, tool) reports when it cannot decide. */
|
|
171
|
+
export interface ReviewOutcomeTexts {
|
|
172
|
+
/** Names the review in log lines. */
|
|
173
|
+
label: string;
|
|
174
|
+
/** The reason of an ask after a timeout, an error or an unparseable answer. */
|
|
175
|
+
ask: string;
|
|
176
|
+
/** The reason of an allow turned into an ask because the model read a cut input. */
|
|
177
|
+
truncatedAsk: string;
|
|
178
|
+
/** Prefixes a `model.request` policy hook's reason. */
|
|
179
|
+
unavailablePrefix: string;
|
|
180
|
+
}
|
|
181
|
+
/** One prepared review model call: its prompt and message, already fitted to the model. */
|
|
182
|
+
export interface ReviewModelCall {
|
|
183
|
+
system: string;
|
|
184
|
+
message: string;
|
|
185
|
+
/** The message carries a cut input: an `allow` cannot cover what the model never read. */
|
|
186
|
+
truncated: boolean;
|
|
187
|
+
/** The idempotency key of the call's `usage` event. */
|
|
188
|
+
usageIdemKey: string;
|
|
189
|
+
/** The idempotency key of a `hook_denied` event (default `hook_denied_review:<run>:<call>`). */
|
|
190
|
+
hookDeniedIdemKey?: string | undefined;
|
|
191
|
+
/** The outcome texts (default the command review's). */
|
|
192
|
+
outcomes?: ReviewOutcomeTexts | undefined;
|
|
193
|
+
}
|
|
140
194
|
/**
|
|
141
195
|
* Runs the classifier call (see the module comment). Never throws: every failure is `ask`, and
|
|
142
196
|
* `ask` is also what an answer other than an explicit `allow` / `deny` becomes.
|
|
143
197
|
*/
|
|
144
198
|
export declare function runClassifier(deps: ReviewClassifierDeps, args: RunClassifierArgs): Promise<ClassifierAnswer>;
|
|
199
|
+
/**
|
|
200
|
+
* The limits of the model the `review` purpose resolves to in the org, or null when it has no
|
|
201
|
+
* usable model (logged; the caller asks without sending anything).
|
|
202
|
+
*/
|
|
203
|
+
export declare function reviewModelLimits(deps: Pick<ReviewClassifierDeps, "purposes" | "log">, args: Pick<ReviewModelCallArgs, "orgId" | "conversationId" | "callId">, label: string): Promise<{
|
|
204
|
+
contextWindow: number;
|
|
205
|
+
maxOutputTokens: number;
|
|
206
|
+
} | null>;
|
|
207
|
+
/**
|
|
208
|
+
* Sends one prepared review call on the `review` purpose: the `model.request` policy hook, the
|
|
209
|
+
* call bounded by `sandbox.review.timeoutMs` and the run's signal, `model.response`, the `usage`
|
|
210
|
+
* event (a sent call that failed billed at its estimate), and the strict parse of the answer.
|
|
211
|
+
* Never throws: a hook denial, a timeout, an error or an unparseable answer is `ask`, and so is an
|
|
212
|
+
* `allow` on a truncated message.
|
|
213
|
+
*/
|
|
214
|
+
export declare function callReviewModel(deps: ReviewClassifierDeps, args: ReviewModelCallArgs, call: ReviewModelCall): Promise<ClassifierAnswer>;
|
|
145
215
|
export {};
|
|
@@ -224,31 +224,75 @@ const headroomTokens = (contextWindow) => Math.max(1024, Math.ceil(contextWindow
|
|
|
224
224
|
* bounded by `sandbox.review.messageTokens`; they are cut only if that alone overflows the model.
|
|
225
225
|
*/
|
|
226
226
|
export function fitReviewInput(input, system, limits) {
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
227
|
+
const fitted = fitReviewText((text, personMessages) => classifierMessage({ ...input, text, personMessages }), { text: input.text, personMessages: input.personMessages }, system, limits, REVIEW_TRUNCATED_MARKER);
|
|
228
|
+
if (fitted.text === input.text && fitted.personMessages === input.personMessages)
|
|
229
|
+
return input;
|
|
230
|
+
return { ...input, ...fitted };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Fits one review message to the review model's context: `build` renders the message from its one
|
|
234
|
+
* unbounded part (`text`) and the person's messages; everything else in it is always kept. When
|
|
235
|
+
* the whole does not fit, `text` keeps its beginning and ends with `marker`; the person's messages
|
|
236
|
+
* are cut (newest end kept) only if they alone overflow the model. Shared by the command review
|
|
237
|
+
* and the tool review.
|
|
238
|
+
*/
|
|
239
|
+
export function fitReviewText(build, parts, system, limits, marker) {
|
|
240
|
+
const estimate = (text, personMessages) => estimateTokens([{ role: "user", content: [{ type: "text", text: build(text, personMessages) }] }], [{ text: system, cache: false }], []);
|
|
233
241
|
const budget = limits.contextWindow -
|
|
234
242
|
Math.min(REVIEW_MAX_OUTPUT_TOKENS, limits.maxOutputTokens) -
|
|
235
243
|
headroomTokens(limits.contextWindow);
|
|
236
|
-
if (estimate(
|
|
237
|
-
return
|
|
238
|
-
// the fixed part of the message and the person's messages; the
|
|
239
|
-
let personMessages =
|
|
244
|
+
if (estimate(parts.text, parts.personMessages) <= budget)
|
|
245
|
+
return parts;
|
|
246
|
+
// the fixed part of the message and the person's messages; the unbounded text gets the rest
|
|
247
|
+
let personMessages = parts.personMessages;
|
|
240
248
|
let available = budget - estimate("", personMessages);
|
|
241
249
|
if (available < 0) {
|
|
242
250
|
// a misconfigured message budget alone overflows the model: keep the newest end, half the room
|
|
243
251
|
const fixed = estimate("", "");
|
|
244
|
-
personMessages = tailToTokens(
|
|
252
|
+
personMessages = tailToTokens(parts.personMessages, Math.max(0, Math.floor((budget - fixed) / 2)));
|
|
245
253
|
available = budget - estimate("", personMessages);
|
|
246
254
|
}
|
|
247
|
-
const
|
|
248
|
-
const text = cost(
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
255
|
+
const room = Math.max(0, available - cost(marker));
|
|
256
|
+
const text = cost(parts.text) > room ? `${headToTokens(parts.text, room)}${marker}` : parts.text;
|
|
257
|
+
return { text, personMessages };
|
|
258
|
+
}
|
|
259
|
+
/* ---------------------------------------------------------------------------------------------- *
|
|
260
|
+
* Reading the person's messages
|
|
261
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
262
|
+
/** How many of the root conversation's latest person messages are read before bounding the text. */
|
|
263
|
+
export const PERSON_MESSAGES_READ = 20;
|
|
264
|
+
/** The text blocks of a `user_message` payload (its images, documents and attachments are skipped). */
|
|
265
|
+
function textOfUserMessage(payload) {
|
|
266
|
+
const content = payload?.content;
|
|
267
|
+
if (!Array.isArray(content))
|
|
268
|
+
return "";
|
|
269
|
+
return content
|
|
270
|
+
.flatMap((b) => {
|
|
271
|
+
if (b === null || typeof b !== "object")
|
|
272
|
+
return [];
|
|
273
|
+
const block = b;
|
|
274
|
+
return block.type === "text" && typeof block.text === "string" ? [block.text] : [];
|
|
275
|
+
})
|
|
276
|
+
.join("\n")
|
|
277
|
+
.trim();
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The bounded text of the root conversation's last person messages: the `user_message` text blocks
|
|
281
|
+
* only, never an assistant message or a tool result, newest {@link PERSON_MESSAGES_READ} read and
|
|
282
|
+
* bounded to `budget` estimated tokens (`sandbox.review.messageTokens`). The command review and the
|
|
283
|
+
* tool review read the same messages.
|
|
284
|
+
*/
|
|
285
|
+
export async function readPersonMessages(db, rootConversationId, budget) {
|
|
286
|
+
const rows = await db
|
|
287
|
+
.selectFrom("conversation_events")
|
|
288
|
+
.select("payload")
|
|
289
|
+
.where("conversation_id", "=", rootConversationId)
|
|
290
|
+
.where("type", "=", "user_message")
|
|
291
|
+
.orderBy("seq", "desc")
|
|
292
|
+
.limit(PERSON_MESSAGES_READ)
|
|
293
|
+
.execute();
|
|
294
|
+
const texts = rows.map((r) => textOfUserMessage(r.payload)).filter((t) => t !== "");
|
|
295
|
+
return boundMessages(texts, budget);
|
|
252
296
|
}
|
|
253
297
|
/* ---------------------------------------------------------------------------------------------- *
|
|
254
298
|
* The call
|
|
@@ -261,6 +305,13 @@ class ReviewDenied extends Error {
|
|
|
261
305
|
this.reason = reason;
|
|
262
306
|
}
|
|
263
307
|
}
|
|
308
|
+
/** The command review's outcome texts. */
|
|
309
|
+
const COMMAND_REVIEW_OUTCOMES = {
|
|
310
|
+
label: "command review classifier",
|
|
311
|
+
ask: REVIEW_ASK_REASON,
|
|
312
|
+
truncatedAsk: REVIEW_TRUNCATED_ASK_REASON,
|
|
313
|
+
unavailablePrefix: REVIEW_UNAVAILABLE_PREFIX,
|
|
314
|
+
};
|
|
264
315
|
const textOf = (content) => content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
|
|
265
316
|
const errorCodeOf = (err) => {
|
|
266
317
|
const cause = err instanceof PurposeAttemptError ? err.cause : err;
|
|
@@ -271,23 +322,47 @@ const errorCodeOf = (err) => {
|
|
|
271
322
|
* `ask` is also what an answer other than an explicit `allow` / `deny` becomes.
|
|
272
323
|
*/
|
|
273
324
|
export async function runClassifier(deps, args) {
|
|
274
|
-
const { input } = args;
|
|
325
|
+
const { input, ...callArgs } = args;
|
|
275
326
|
const system = reviewSystemPrompt(input.tag);
|
|
276
327
|
// fit the command and messages to the model the call will use (as `chat` resolves it)
|
|
277
|
-
|
|
328
|
+
const limits = await reviewModelLimits(deps, args, COMMAND_REVIEW_OUTCOMES.label);
|
|
329
|
+
if (limits === null)
|
|
330
|
+
return { decision: "ask", reason: REVIEW_ASK_REASON };
|
|
331
|
+
const fitted = fitReviewInput(input, system, limits);
|
|
332
|
+
return callReviewModel(deps, callArgs, {
|
|
333
|
+
system,
|
|
334
|
+
message: classifierMessage(fitted),
|
|
335
|
+
truncated: fitted.text !== input.text,
|
|
336
|
+
usageIdemKey: `usage_review:${args.runId}:${args.callId}`,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The limits of the model the `review` purpose resolves to in the org, or null when it has no
|
|
341
|
+
* usable model (logged; the caller asks without sending anything).
|
|
342
|
+
*/
|
|
343
|
+
export async function reviewModelLimits(deps, args, label) {
|
|
278
344
|
try {
|
|
279
|
-
|
|
345
|
+
return await deps.purposes.chatLimits(args.orgId, REVIEW_PURPOSE);
|
|
280
346
|
}
|
|
281
347
|
catch (err) {
|
|
282
348
|
// no usable purpose model: fail closed without sending anything
|
|
283
|
-
deps.log.warn(
|
|
349
|
+
deps.log.warn(`${label} has no usable model`, {
|
|
284
350
|
conversationId: args.conversationId,
|
|
285
351
|
callId: args.callId,
|
|
286
352
|
err,
|
|
287
353
|
});
|
|
288
|
-
return
|
|
354
|
+
return null;
|
|
289
355
|
}
|
|
290
|
-
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Sends one prepared review call on the `review` purpose: the `model.request` policy hook, the
|
|
359
|
+
* call bounded by `sandbox.review.timeoutMs` and the run's signal, `model.response`, the `usage`
|
|
360
|
+
* event (a sent call that failed billed at its estimate), and the strict parse of the answer.
|
|
361
|
+
* Never throws: a hook denial, a timeout, an error or an unparseable answer is `ask`, and so is an
|
|
362
|
+
* `allow` on a truncated message.
|
|
363
|
+
*/
|
|
364
|
+
export async function callReviewModel(deps, args, call) {
|
|
365
|
+
const outcomes = call.outcomes ?? COMMAND_REVIEW_OUTCOMES;
|
|
291
366
|
const scope = hookScope(deps.hooks, {
|
|
292
367
|
...(args.hookFacts.conversationKind !== undefined && {
|
|
293
368
|
conversationKind: args.hookFacts.conversationKind,
|
|
@@ -317,8 +392,8 @@ export async function runClassifier(deps, args) {
|
|
|
317
392
|
let out;
|
|
318
393
|
try {
|
|
319
394
|
out = await deps.purposes.chat(args.orgId, REVIEW_PURPOSE, {
|
|
320
|
-
system: [{ text: system, cache: false }],
|
|
321
|
-
messages: [{ role: "user", content: [{ type: "text", text:
|
|
395
|
+
system: [{ text: call.system, cache: false }],
|
|
396
|
+
messages: [{ role: "user", content: [{ type: "text", text: call.message }] }],
|
|
322
397
|
tools: [],
|
|
323
398
|
toolChoice: "none",
|
|
324
399
|
maxOutputTokens: REVIEW_MAX_OUTPUT_TOKENS,
|
|
@@ -328,7 +403,7 @@ export async function runClassifier(deps, args) {
|
|
|
328
403
|
if (base && deps.hooks?.has("model.request")) {
|
|
329
404
|
const verdict = await deps.hooks.run("model.request", { ...base, request: hookRequestOf(request, deps.log) }, signal);
|
|
330
405
|
if (!verdict.allowed) {
|
|
331
|
-
await recordDenial(deps, args, verdict);
|
|
406
|
+
await recordDenial(deps, args, call, outcomes, verdict);
|
|
332
407
|
throw new ReviewDenied(verdict.reason);
|
|
333
408
|
}
|
|
334
409
|
}
|
|
@@ -339,14 +414,14 @@ export async function runClassifier(deps, args) {
|
|
|
339
414
|
}
|
|
340
415
|
catch (err) {
|
|
341
416
|
observe(deps, hookBase, sent, null, err, args.signal);
|
|
342
|
-
deps.log.warn(
|
|
417
|
+
deps.log.warn(`${outcomes.label} call failed`, {
|
|
343
418
|
conversationId: args.conversationId,
|
|
344
419
|
callId: args.callId,
|
|
345
420
|
err,
|
|
346
421
|
});
|
|
347
422
|
// a sent call is billed: its estimated usage is logged like a successful one's
|
|
348
423
|
if (err instanceof PurposeAttemptError) {
|
|
349
|
-
await logUsage(deps, args, {
|
|
424
|
+
await logUsage(deps, args, call.usageIdemKey, {
|
|
350
425
|
provider: err.provider,
|
|
351
426
|
model: err.model,
|
|
352
427
|
usage: {
|
|
@@ -357,19 +432,19 @@ export async function runClassifier(deps, args) {
|
|
|
357
432
|
},
|
|
358
433
|
});
|
|
359
434
|
}
|
|
360
|
-
const reason = err instanceof ReviewDenied ? `${
|
|
435
|
+
const reason = err instanceof ReviewDenied ? `${outcomes.unavailablePrefix}${err.reason}` : outcomes.ask;
|
|
361
436
|
return { decision: "ask", reason };
|
|
362
437
|
}
|
|
363
438
|
observe(deps, hookBase, sent, out, null, args.signal);
|
|
364
|
-
await logUsage(deps, args, out);
|
|
439
|
+
await logUsage(deps, args, call.usageIdemKey, out);
|
|
365
440
|
const answer = parseReviewAnswer(textOf(out.content)) ?? {
|
|
366
441
|
decision: "ask",
|
|
367
|
-
reason:
|
|
442
|
+
reason: outcomes.ask,
|
|
368
443
|
};
|
|
369
|
-
// the model saw only the beginning of the
|
|
444
|
+
// the model saw only the beginning of the input: its allow cannot cover the part it never read
|
|
370
445
|
// (hardening spec R8); its deny or ask stands
|
|
371
|
-
if (answer.decision === "allow" &&
|
|
372
|
-
return { decision: "ask", reason:
|
|
446
|
+
if (answer.decision === "allow" && call.truncated) {
|
|
447
|
+
return { decision: "ask", reason: outcomes.truncatedAsk };
|
|
373
448
|
}
|
|
374
449
|
return answer;
|
|
375
450
|
}
|
|
@@ -379,11 +454,11 @@ export async function runClassifier(deps, args) {
|
|
|
379
454
|
* counts on its parent run's `subagent_tokens_used`, in the same transaction
|
|
380
455
|
* ({@link appendCounted}, as the `WebFetch` extraction does).
|
|
381
456
|
*/
|
|
382
|
-
async function logUsage(deps, args, u) {
|
|
457
|
+
async function logUsage(deps, args, idemKey, u) {
|
|
383
458
|
const event = {
|
|
384
459
|
type: "usage",
|
|
385
460
|
...(args.runId !== "" && { runId: args.runId }),
|
|
386
|
-
idemKey
|
|
461
|
+
idemKey,
|
|
387
462
|
payload: {
|
|
388
463
|
step: args.step,
|
|
389
464
|
provider: u.provider,
|
|
@@ -406,14 +481,14 @@ async function logUsage(deps, args, u) {
|
|
|
406
481
|
* Records a `model.request` denial of the classifier call: the `hook_denied` event (the call's step
|
|
407
482
|
* and `callId`) with its `hook.denied` audit row (`detail.purpose: "review"`), in one transaction.
|
|
408
483
|
*/
|
|
409
|
-
async function recordDenial(deps, args, verdict) {
|
|
484
|
+
async function recordDenial(deps, args, call, outcomes, verdict) {
|
|
410
485
|
const site = {
|
|
411
486
|
orgId: args.orgId,
|
|
412
487
|
conversationId: args.conversationId,
|
|
413
488
|
runId: args.runId,
|
|
414
489
|
accountId: args.hookFacts.accountId,
|
|
415
490
|
...(args.hookFacts.agentId !== undefined && { agentId: args.hookFacts.agentId }),
|
|
416
|
-
idemKey: `hook_denied_review:${args.runId}:${args.callId}`,
|
|
491
|
+
idemKey: call.hookDeniedIdemKey ?? `hook_denied_review:${args.runId}:${args.callId}`,
|
|
417
492
|
};
|
|
418
493
|
const event = hookDeniedEvent(site, "model.request", verdict, {
|
|
419
494
|
step: args.step,
|
|
@@ -422,7 +497,7 @@ async function recordDenial(deps, args, verdict) {
|
|
|
422
497
|
});
|
|
423
498
|
const entry = hookDeniedAudit(site, event.payload, verdict);
|
|
424
499
|
entry.detail = { ...entry.detail, purpose: REVIEW_PURPOSE };
|
|
425
|
-
deps.log.warn(
|
|
500
|
+
deps.log.warn(`${outcomes.label} blocked by a policy hook`, {
|
|
426
501
|
conversationId: args.conversationId,
|
|
427
502
|
callId: args.callId,
|
|
428
503
|
plugin: verdict.plugin,
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* auto mode (and for the file writes outside the workspace). Only the service touches the database,
|
|
5
5
|
* a model or a lock; the parser and the table are pure.
|
|
6
6
|
*/
|
|
7
|
-
export type { ClassifierAnswer, ReviewClassifierDeps, ReviewClassifierInput, ReviewHookFacts, RunClassifierArgs, } from "./classifier.js";
|
|
8
|
-
export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
|
|
7
|
+
export type { ClassifierAnswer, ReviewClassifierDeps, ReviewClassifierInput, ReviewHookFacts, ReviewModelCall, ReviewModelCallArgs, ReviewOutcomeTexts, RunClassifierArgs, } from "./classifier.js";
|
|
8
|
+
export { boundMessages, callReviewModel, classifierMessage, fitReviewInput, fitReviewText, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, readPersonMessages, reviewModelLimits, reviewSystemPrompt, runClassifier, } from "./classifier.js";
|
|
9
9
|
export type { CommandReview, ReviewCall, ReviewInput, ReviewVerdict } from "./review.service.js";
|
|
10
10
|
export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
|
|
11
11
|
export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
|