@capybara-hq/kernel 0.1.0-rc.125 → 0.1.0-rc.127

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 (41) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/catalog.module.js +0 -3
  3. package/dist/catalog/org-catalog.service.d.ts +0 -2
  4. package/dist/catalog/org-catalog.service.js +0 -4
  5. package/dist/catalog/org-extension.controller.d.ts +5 -9
  6. package/dist/catalog/org-extension.controller.js +22 -22
  7. package/dist/catalog/org-extension.schemas.d.ts +0 -1
  8. package/dist/catalog/org-extension.schemas.js +0 -2
  9. package/dist/catalog/plugin-install.d.ts +4 -1
  10. package/dist/catalog/plugin-install.js +4 -1
  11. package/dist/conversations/events.d.ts +10 -154
  12. package/dist/conversations/events.js +8 -83
  13. package/dist/db/kernel-schema.d.ts +7 -107
  14. package/dist/devices/conversation-devices.d.ts +1 -2
  15. package/dist/devices/devices.service.d.ts +8 -1
  16. package/dist/devices/devices.service.js +1 -1
  17. package/dist/errors.d.ts +5 -0
  18. package/dist/errors.js +5 -0
  19. package/dist/evals/recorded-permission-context.js +1 -3
  20. package/dist/evals/recorded-tools.d.ts +3 -4
  21. package/dist/evals/recorded-tools.js +6 -7
  22. package/dist/extensions/org-config.d.ts +35 -8
  23. package/dist/extensions/org-config.js +61 -14
  24. package/dist/extensions/plugin-items.d.ts +16 -0
  25. package/dist/extensions/plugin-items.js +35 -0
  26. package/dist/platform/operation.d.ts +0 -2
  27. package/dist/platform/ops/extensions.ops.d.ts +4 -6
  28. package/dist/platform/ops/extensions.ops.js +17 -34
  29. package/dist/runtime/context/build.d.ts +1 -1
  30. package/dist/runtime/context/build.js +1 -10
  31. package/dist/runtime/context/device-paths.d.ts +5 -82
  32. package/dist/runtime/context/device-paths.js +3 -174
  33. package/dist/runtime/context/permission-profile.d.ts +3 -13
  34. package/dist/runtime/context/permission-profile.js +9 -26
  35. package/dist/runtime/permission-context.service.js +3 -4
  36. package/dist/runtime/run-worker.js +6 -5
  37. package/package.json +1 -1
  38. package/src/migrations/0210_normalize_conversation_history.sql +1012 -0
  39. package/src/migrations/0211_pre_release_cleanup.sql +154 -0
  40. package/dist/catalog/org-extension-switch.d.ts +0 -41
  41. package/dist/catalog/org-extension-switch.js +0 -123
@@ -86,8 +86,6 @@ export interface OperationError {
86
86
  * `marketplaces.add` duplicate check is tool policy; the web accepts a duplicate source),
87
87
  * `agent.visibility_web_only`,
88
88
  * `catalog.org_owned` (`plugins.set-shown` leaves an org's own plugin to that org),
89
- * `extension.switch_via_plugin` (`extensions.set-enabled` leaves a catalog plugin's extension to
90
- * `plugins.set-enabled`),
91
89
  * `account.self` / `account.no_change` (disabling your own account, a status that is set already),
92
90
  * and `platform.secret_record_web_only` (a secret record the card cannot ask for; ruling R1).
93
91
  */
@@ -1,5 +1,4 @@
1
1
  import { type OnModuleInit } from "@nestjs/common";
2
- import { OrgExtensionSwitch } from "../../catalog/org-extension-switch.js";
3
2
  import { ExtensionDisplayNames } from "../../extensions/display-name.js";
4
3
  import { OrgExtensionConfigs } from "../../extensions/org-config.js";
5
4
  import { OrgOverrides, type OrgOverrideView } from "../../extensions/org-overrides.js";
@@ -29,12 +28,11 @@ export declare class ExtensionsOperations implements OnModuleInit {
29
28
  private readonly switches;
30
29
  private readonly pointDefaults;
31
30
  private readonly overrides;
32
- private readonly extSwitch;
33
- constructor(registry: PlatformOperations, configs: OrgExtensionConfigs, displayNames: ExtensionDisplayNames, kdb: KernelDb, switches: OrgToolSwitches, pointDefaults: ExtensionPointDefaults, overrides: OrgOverrides, extSwitch: OrgExtensionSwitch);
31
+ constructor(registry: PlatformOperations, configs: OrgExtensionConfigs, displayNames: ExtensionDisplayNames, kdb: KernelDb, switches: OrgToolSwitches, pointDefaults: ExtensionPointDefaults, overrides: OrgOverrides);
34
32
  /**
35
- * Why `extensions.set-enabled` refuses the switch before writing, or null: an extension of one
36
- * catalog plugin is switched through its plugin; a required or builtin one cannot go off. The
37
- * write itself repeats every rule ({@link OrgExtensionSwitch.put}).
33
+ * Why `extensions.set-enabled` refuses the switch before writing, or null: switching on needs the
34
+ * extension's plugin installed in the org; a required or builtin one cannot go off. The write
35
+ * itself repeats every rule ({@link OrgExtensionConfigs.put}).
38
36
  */
39
37
  private switchRefusal;
40
38
  /** The org view of one extension, or `extension.not_found` (not installed or not offered). */
@@ -7,14 +7,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { EXTENSION_POINTS, parseExtensionPoint, ToolError } from "@capybara-hq/plugin-sdk";
10
+ import { EXTENSION_POINTS, parseExtensionPoint } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { OrgExtensionParams, OrgExtensionPut, OrgExtensionToolParams, OrgOverridesPut, OrgOverridesTake, OrgToolSwitchPut, } from "../../catalog/org-extension.schemas.js";
14
- import { OrgExtensionSwitch } from "../../catalog/org-extension-switch.js";
15
14
  import { ApiError } from "../../errors.js";
16
15
  import { ExtensionDisplayNames } from "../../extensions/display-name.js";
17
- import { OrgExtensionConfigs, providesOf, } from "../../extensions/org-config.js";
16
+ import { listedInOrg, OrgExtensionConfigs, pluginNotInstalledError, providesOf, } from "../../extensions/org-config.js";
18
17
  import { OrgOverrides } from "../../extensions/org-overrides.js";
19
18
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
20
19
  import { ExtensionPointDefaultBody, ExtensionPointParams, } from "../../extensions/point-defaults.schemas.js";
@@ -36,11 +35,6 @@ const Extension = OrgExtensionParams.shape.extension;
36
35
  const Tool = OrgExtensionToolParams.shape.tool;
37
36
  const SwitchConfirm = OrgToolSwitchPut.shape.confirm.unwrap();
38
37
  const Force = OrgExtensionPut.shape.force;
39
- /**
40
- * Why `extensions.set-enabled` does not switch an extension that ships in one catalog plugin: that
41
- * switch is the plugin's (with its uninstall preview), `plugins.set-enabled`.
42
- */
43
- const viaPlugin = (extension, itemId) => `Extension ${extension} ships in a catalog plugin, whose switch it is: switch the plugin with plugins.set-enabled (itemId ${itemId}; switching off takes the confirm value of plugins.disable-preview).`;
44
38
  /** The next step of an extension that needs its org config. */
45
39
  const NEEDS_ORG_CONFIG = {
46
40
  orgAdmin: "Read what is missing with extensions.org-config, then fill in the org's own copy of the overridable fields with extensions.save-org-config; the person enters secrets in a secure input request.",
@@ -99,8 +93,7 @@ let ExtensionsOperations = class ExtensionsOperations {
99
93
  switches;
100
94
  pointDefaults;
101
95
  overrides;
102
- extSwitch;
103
- constructor(registry, configs, displayNames, kdb, switches, pointDefaults, overrides, extSwitch) {
96
+ constructor(registry, configs, displayNames, kdb, switches, pointDefaults, overrides) {
104
97
  this.registry = registry;
105
98
  this.configs = configs;
106
99
  this.displayNames = displayNames;
@@ -108,18 +101,18 @@ let ExtensionsOperations = class ExtensionsOperations {
108
101
  this.switches = switches;
109
102
  this.pointDefaults = pointDefaults;
110
103
  this.overrides = overrides;
111
- this.extSwitch = extSwitch;
112
104
  }
113
105
  /**
114
- * Why `extensions.set-enabled` refuses the switch before writing, or null: an extension of one
115
- * catalog plugin is switched through its plugin; a required or builtin one cannot go off. The
116
- * write itself repeats every rule ({@link OrgExtensionSwitch.put}).
106
+ * Why `extensions.set-enabled` refuses the switch before writing, or null: switching on needs the
107
+ * extension's plugin installed in the org; a required or builtin one cannot go off. The write
108
+ * itself repeats every rule ({@link OrgExtensionConfigs.put}).
117
109
  */
118
110
  async switchRefusal(orgId, extension, enabled) {
119
111
  const v = await this.viewOf(orgId, extension);
120
- const plan = await this.configs.switchPlan(extension, enabled);
121
- if (plan.kind === "item") {
122
- return { code: "extension.switch_via_plugin", message: viaPlugin(extension, plan.itemId) };
112
+ const plan = await this.configs.switchPlan(orgId, extension, enabled);
113
+ if (plan.kind === "not_installed") {
114
+ const e = await pluginNotInstalledError(this.kdb.db, extension, plan.itemId);
115
+ return { code: e.code, message: `${e.message} (plugins.set-enabled, itemId ${plan.itemId})` };
123
116
  }
124
117
  if (!enabled && v.required) {
125
118
  return {
@@ -151,7 +144,7 @@ let ExtensionsOperations = class ExtensionsOperations {
151
144
  this.registry.register([
152
145
  defineOperation({
153
146
  id: "extensions.list",
154
- description: "List the extensions installed on the platform as this org sees them, one compact row each: the state here (on, off, needs_config: its config for this org is not valid, unavailable: it cannot run on the platform), why an unavailable one cannot be used (reason) and your next step (next), whether it is available on the platform, the extension points it provides and the plugin that brings it. State only: an org admin reads the config with extensions.org-config and sets the org's copy with extensions.save-org-config. Pages by 50: pass the returned next as params.cursor.",
147
+ description: "List this org's extensions, as its Extensions page does (an extension whose plugin is not installed in the org is left out until plugins.set-enabled installs it), one compact row each: the state here (on, off, needs_config: its config for this org is not valid, unavailable: it cannot run on the platform), why an unavailable one cannot be used (reason) and your next step (next), whether it is available on the platform, the extension points it provides and the plugin that brings it. State only: an org admin reads the config with extensions.org-config and sets the org's copy with extensions.save-org-config. Pages by 50: pass the returned next as params.cursor.",
155
148
  input: z.object({ cursor: Cursor.optional() }).strict(),
156
149
  example: {},
157
150
  authz: { orgAction: "org.extensions.read" },
@@ -164,7 +157,7 @@ let ExtensionsOperations = class ExtensionsOperations {
164
157
  roleFor(this.kdb.db, ctx),
165
158
  ]);
166
159
  const names = await this.displayNames.many(views.map((v) => v.plugin));
167
- return pageOf(views.map((v) => {
160
+ return pageOf(views.filter(listedInOrg).map((v) => {
168
161
  const name = localized(names.get(v.plugin), v.plugin).en;
169
162
  return {
170
163
  id: v.plugin,
@@ -184,13 +177,11 @@ let ExtensionsOperations = class ExtensionsOperations {
184
177
  }),
185
178
  defineOperation({
186
179
  id: "extensions.set-enabled",
187
- description: "Switch an extension that is not a catalog plugin's on or off in this org (org admins): one declared in the deployment config, or one several catalog plugins bring. An extension shipped in one catalog plugin is switched with plugins.set-enabled; extensions.list shows its catalogItemId. Switching on never waits for config: an extension with no valid config for the org is switched on anyway and the result's configNeeded says how to fill in the org's copy (extensions.save-org-config). Switching off is refused while other enabled extensions depend on it, unless force is true (they lose what they depend on).",
180
+ description: "Start or stop one extension in this org (org admins). It switches the extension only: its plugin stays installed and its config is kept, and switching it on again needs no install. The extension's plugin must be installed in the org (plugins.set-enabled installs and uninstalls plugins; extensions.list shows the catalogItemId). Switching on never waits for config: an extension with no valid config for the org is switched on anyway and the result's configNeeded says how to fill in the org's copy (extensions.save-org-config). Switching off is refused while other enabled extensions depend on it, unless force is true (they lose what they depend on).",
188
181
  input: z.object({ extension: Extension, enabled: z.boolean(), force: Force }).strict(),
189
182
  example: { extension: "web-search-tavily", enabled: true },
190
183
  authz: { orgAction: "org.extensions.manage" },
191
184
  mirrors: ["PUT /api/v1/orgs/:orgId/extensions/:extension"],
192
- // the confirm of a catalog plugin's switch-off: that switch is plugins.set-enabled's
193
- omits: ["confirm"],
194
185
  confirm: "org",
195
186
  errors: [
196
187
  {
@@ -198,8 +189,8 @@ let ExtensionsOperations = class ExtensionsOperations {
198
189
  next: "The extension is not running or not visible to this org; check the name with extensions.list.",
199
190
  },
200
191
  {
201
- code: "extension.switch_via_plugin",
202
- next: "Switch its plugin with plugins.set-enabled (the itemId is extensions.list's catalogItemId).",
192
+ code: "extension.plugin_not_installed",
193
+ next: "Its plugin is not installed in this org: install it with plugins.set-enabled (the itemId is in the message and extensions.list's catalogItemId), which starts the extension too.",
203
194
  },
204
195
  {
205
196
  code: "extension.required",
@@ -255,14 +246,7 @@ let ExtensionsOperations = class ExtensionsOperations {
255
246
  : { zh: `在本组织停用扩展「${x.zh}」`, en: `Disable extension "${x.en}" in the org` };
256
247
  },
257
248
  run: async (input, ctx) => {
258
- const refusal = await this.switchRefusal(ctx.orgId, input.extension, input.enabled);
259
- if (refusal?.code === "extension.switch_via_plugin")
260
- throw new ToolError(refusal.message);
261
- const r = await this.extSwitch.put(ctx.orgId, ctx.actorAccountId, input.extension, { enabled: input.enabled, ...(input.force === true && { force: true }) }, undefined, viaAgent("extensions.set-enabled", ctx));
262
- // unreachable: only a catalog plugin's switch-off answers a preview, refused above
263
- if (r.kind === "preview")
264
- throw new Error("extensions.set-enabled: unexpected preview");
265
- const v = r.view;
249
+ const v = await this.configs.put(ctx.orgId, input.extension, { enabled: input.enabled, ...(input.force === true && { force: true }) }, ctx.actorAccountId, undefined, { auditDetail: { reason: "org_switch", ...viaAgent("extensions.set-enabled", ctx) } });
266
250
  return {
267
251
  extension: v.plugin,
268
252
  state: stateOf(v),
@@ -664,7 +648,6 @@ ExtensionsOperations = __decorate([
664
648
  __param(3, Inject(KernelDb)),
665
649
  __param(4, Inject(OrgToolSwitches)),
666
650
  __param(5, Inject(ExtensionPointDefaults)),
667
- __param(6, Inject(OrgOverrides)),
668
- __param(7, Inject(OrgExtensionSwitch))
651
+ __param(6, Inject(OrgOverrides))
669
652
  ], ExtensionsOperations);
670
653
  export { ExtensionsOperations };
@@ -382,7 +382,7 @@ export declare function summaryText(summary: string, framing: {
382
382
  * `user_message` / `assistant_message`(content 原样,含 opaque;aborted 的也回放;媒体引用按
383
383
  * {@link resolveMedia} 换成 base64 或文字占位)/ `reminder`
384
384
  * (`role: "system"`,放在它所在的位置)/ `tools_changed` (`role: "system"`, the text of {@link toolsChangedText}, at its position) /
385
- * `device_paths` (`role: "system"` at its position, `devicePathsText`; covered by the
385
+ * `device_paths` (`role: "system"` at its position, `managedDevicePathsText`; covered by the
386
386
  * summary: the latest one follows the summary) /
387
387
  * `run_context` (`role: "system"` at its position, `runContextText`; covered by the summary: the
388
388
  * current context follows the summary whole; a user message's sender line by `senderLines`) /
@@ -4,7 +4,6 @@ import { renderBackgroundFinished } from "../../background/render.js";
4
4
  import { isAbsorbable, refFileId, } from "../../conversations/events.js";
5
5
  import { catalogText, isAlwaysLoaded } from "../../tools/builtins/tool-search.js";
6
6
  import { renderSubagentDelivery } from "../subagents/render.js";
7
- import { devicePathsAt, devicePathsText } from "./device-paths.js";
8
7
  import { OUTPUT_TRUNCATED_TEXT } from "./output-truncated.js";
9
8
  import { permissionContextHistory } from "./permission-profile.js";
10
9
  import { pluginContextsAfterSummary, pluginContextText } from "./plugin-context.js";
@@ -607,7 +606,7 @@ export function summaryText(summary, framing) {
607
606
  * `user_message` / `assistant_message`(content 原样,含 opaque;aborted 的也回放;媒体引用按
608
607
  * {@link resolveMedia} 换成 base64 或文字占位)/ `reminder`
609
608
  * (`role: "system"`,放在它所在的位置)/ `tools_changed` (`role: "system"`, the text of {@link toolsChangedText}, at its position) /
610
- * `device_paths` (`role: "system"` at its position, `devicePathsText`; covered by the
609
+ * `device_paths` (`role: "system"` at its position, `managedDevicePathsText`; covered by the
611
610
  * summary: the latest one follows the summary) /
612
611
  * `run_context` (`role: "system"` at its position, `runContextText`; covered by the summary: the
613
612
  * current context follows the summary whole; a user message's sender line by `senderLines`) /
@@ -895,12 +894,6 @@ export function buildModelRequest(input) {
895
894
  content: runContextFullText(currentRunContext(events, after)),
896
895
  });
897
896
  }
898
- // environments spec §13.1: the instance's directories told before the boundary follow the
899
- // summary again (the model keeps using the real paths)
900
- const paths = devicePathsAt(events, after);
901
- if (paths && paths.payload.permissionContextVersion !== 1) {
902
- messages.push({ role: "system", content: devicePathsText(paths.payload) });
903
- }
904
897
  for (const contribution of permissionHistory.restored) {
905
898
  messages.push({ role: "system", content: contribution.text });
906
899
  }
@@ -1006,8 +999,6 @@ export function buildModelRequest(input) {
1006
999
  const contribution = permissionHistory.ordered.get(e.seq);
1007
1000
  if (contribution)
1008
1001
  messages.push({ role: "system", content: contribution.text });
1009
- else if (e.type === "device_paths")
1010
- messages.push({ role: "system", content: devicePathsText(e.payload) });
1011
1002
  break;
1012
1003
  }
1013
1004
  // a context@1 provider's text (memory spec §6.1); empty text (nothing any more) renders nothing
@@ -1,92 +1,15 @@
1
1
  import type { SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import type { ConversationEvent, ManagedDevicePathsV1 } from "../../conversations/events.js";
3
- import type { DeviceNetwork, SandboxMode } from "../../sandbox/modes.js";
4
- /**
5
- * The `device_paths` event (environments spec §13.1, ruling R22; auto mode spec §4.2): the first
6
- * sandbox tool call of every conversation records the instance's roots (the defaults included) and
7
- * the device's mode and network, and a later call records them again whenever they differ from the
8
- * conversation's latest recorded ones (a connected machine's real paths, a mode switch back to the
9
- * defaults, a network change). Model-visible: rendered at its position as a system message; in the
10
- * log, so it needs no `DriftReason`. Events recorded before auto mode carry the old `tier` /
11
- * `isolation` fields and render exactly as they always did.
12
- */
13
- /** The mode and network a device's commands run at, as the model is told them. */
14
- export interface DeviceModeLevel {
15
- mode: SandboxMode;
16
- allowedMode: SandboxMode;
17
- network: DeviceNetwork;
18
- /**
19
- * Its provider runs each operation on its host machine (an operation boundary, `true`) rather
20
- * than in an instance of its own (a container).
21
- */
22
- local: boolean;
23
- }
24
- /** The payload of a `device_paths` event; the mode fields are absent on events before auto mode. */
25
- export type DevicePathsPayload = LegacyDevicePathsPayload | ManagedDevicePathsV1;
26
- export interface LegacyDevicePathsPayload {
27
- permissionContextVersion?: undefined;
28
- roots: SandboxRoots;
29
- mode?: SandboxMode | undefined;
30
- allowedMode?: SandboxMode | undefined;
31
- /** A device network; `"none"` only on events recorded before auto mode. */
32
- network?: DeviceNetwork | "none" | undefined;
33
- local?: boolean | undefined;
34
- /** Before auto mode: the tier and isolation the device ran at. */
35
- tier?: LegacyTier | undefined;
36
- isolation?: "sandbox" | "none" | undefined;
37
- localhost?: "on" | "off-proxy-detected" | "off" | undefined;
38
- unixSockets?: "roots" | "all-masked" | "off" | undefined;
39
- unattended?: true | undefined;
40
- }
41
- /** The tier names of events recorded before auto mode (read only by their old rendering). */
42
- type LegacyTier = "strict" | "dev" | "open";
43
- /** The old level of a payload (before auto mode), for its unchanged rendering. */
44
- export interface LegacyLevel {
45
- tier: LegacyTier;
46
- isolation: "sandbox" | "none";
47
- network?: "none" | undefined;
48
- localhost?: "on" | "off-proxy-detected" | "off" | undefined;
49
- unixSockets?: "roots" | "all-masked" | "off" | undefined;
50
- unattended?: true | undefined;
51
- }
52
- /** The mode and network line of a `device_paths` event (model-visible, English). */
53
- export declare function modeLevelText(level: DeviceModeLevel): string;
54
- /** A payload's level: the current mode/network shape or the pre-auto-mode one. */
55
- export type DevicePathsLevel = DeviceModeLevel | LegacyLevel;
56
- /** The level a payload records, in either shape; undefined without one. */
57
- export declare function devicePathsLevel(p: DevicePathsPayload): DevicePathsLevel | undefined;
58
- /** The system message of a `device_paths` event (model-visible, English). */
59
- export declare function devicePathsText(p: DevicePathsPayload): string;
2
+ import type { ManagedDevicePathsV1 } from "../../conversations/events.js";
3
+ export type DevicePathsPayload = ManagedDevicePathsV1;
60
4
  /** Whether two sets of roots are the same paths. */
61
5
  export declare const sameRoots: (a: SandboxRoots, b: SandboxRoots) => boolean;
62
- /**
63
- * The idempotency key of a `device_paths` event for `p` that follows the conversation's event at
64
- * `prevSeq` (0: none). Unique per change (A → B → A gets three events), while parallel calls that
65
- * saw the same latest event write it once.
66
- */
67
- export declare const devicePathsIdemKey: (p: DevicePathsPayload, prevSeq: number) => string;
68
- /**
69
- * The `device_paths` event to append when a sandbox call holds an instance with `roots` in a
70
- * device at `level`, and the conversation's latest such event is `latest`; null when nothing
71
- * changed. Without a `level` (not known: test stubs, a replay of a call recorded before auto mode)
72
- * only the roots are compared and recorded.
73
- */
74
- export declare function devicePathsChange(latest: {
6
+ /** Append the managed paths only when their recorded facts change. */
7
+ export declare function devicePathsChangeFromPayload(latest: {
75
8
  seq: number;
76
9
  payload: DevicePathsPayload;
77
- } | undefined, roots: SandboxRoots, runId: string | undefined, level?: DevicePathsLevel): {
10
+ } | undefined, payload: DevicePathsPayload, runId?: string): {
78
11
  type: "device_paths";
79
12
  runId?: string;
80
13
  idemKey: string;
81
14
  payload: DevicePathsPayload;
82
15
  } | null;
83
- /** The latest `device_paths` event at or before `seq`; undefined without one. */
84
- export declare function devicePathsAt(events: readonly ConversationEvent[], seq: number): Extract<ConversationEvent, {
85
- type: "device_paths";
86
- }> | undefined;
87
- /** Full managed payload equality; historical payloads retain their existing comparisons and keys. */
88
- export declare function devicePathsChangeFromPayload(latest: {
89
- seq: number;
90
- payload: DevicePathsPayload;
91
- } | undefined, payload: DevicePathsPayload, runId?: string): ReturnType<typeof devicePathsChange>;
92
- export {};
@@ -1,180 +1,9 @@
1
- import { createHash } from "node:crypto";
2
- import { managedDevicePathsHash, managedDevicePathsIdemKey, managedDevicePathsText, } from "./permission-profile.js";
3
- /** The roots line of a `device_paths` event (model-visible, English). */
4
- const rootsText = (r) => `This device's directories: workspace ${r.workspace}, skills ${r.skills} (read only), temporary files ${r.tmp}. Use these paths in commands and tool calls.`;
5
- const TIER_NAMES = {
6
- strict: "strict",
7
- dev: "development",
8
- open: "open",
9
- };
10
- /** What a domain outside the reachable ones needs: the user's approval, unless nobody is there. */
11
- const otherDomains = (unattended) => unattended
12
- ? "approvals are not available in a scheduled run, so other domains stay blocked."
13
- : "other domains need the user's approval.";
14
- /** Local servers and unix sockets in `dev` / `open` (a cloud instance has both). */
15
- function localText(level) {
16
- const { localhost, unixSockets } = level;
17
- if (localhost === undefined || unixSockets === undefined) {
18
- return "Local servers and unix sockets work.";
19
- }
20
- const servers = localhost === "on"
21
- ? "Local servers work"
22
- : localhost === "off-proxy-detected"
23
- ? "Local servers are blocked on this machine because a local proxy was detected (the user can allow them on the device)"
24
- : "Local servers are blocked";
25
- const sockets = unixSockets === "roots"
26
- ? "unix sockets work under the device's directories only"
27
- : unixSockets === "all-masked"
28
- ? "unix sockets work inside the device's container only"
29
- : "unix sockets are blocked";
30
- return `${servers}; ${sockets}.`;
31
- }
32
- /** The old level line of a `device_paths` event (before auto mode; kept byte for byte). */
33
- function sandboxLevelText(level) {
34
- if (level.isolation === "none") {
35
- return "Sandbox level: open, without a sandbox. Commands run directly on the user's computer as the user, with their files, credentials and network; be careful with anything that deletes files or sends data out.";
36
- }
37
- const head = `Sandbox level: ${TIER_NAMES[level.tier]}.`;
38
- if (level.network === "none") {
39
- return `${head} The network is switched off for this organization: no domain is reachable and approval requests cannot change that.`;
40
- }
41
- const unattended = level.unattended === true;
42
- switch (level.tier) {
43
- case "strict":
44
- return `${head} Only the organization's allowed domains are reachable; ${otherDomains(unattended)}`;
45
- case "dev":
46
- return `${head} Package registries and common developer hosts are reachable; ${otherDomains(unattended)} ${localText(level)}`;
47
- case "open":
48
- return `${head} Any public address is reachable. ${localText(level)}`;
49
- }
50
- }
51
- /** The mode and network line of a `device_paths` event (model-visible, English). */
52
- export function modeLevelText(level) {
53
- if (!level.local) {
54
- const head = `Mode: ${level.mode}. Commands run in the device's container; outside it `;
55
- return level.network.kind === "open-public"
56
- ? `${head}only public addresses are reachable (loopback, private and cloud metadata addresses are blocked).`
57
- : `${head}the network reaches the organization's allowlisted hosts.`;
58
- }
59
- if (level.mode === "auto") {
60
- return "Mode: auto. Commands run as the user on this machine, with their files, credentials and network; every command is reviewed and dangerous ones are blocked or need approval.";
61
- }
62
- return "Mode: sandbox. Only the workspace, skills and temporary files are writable; the network reaches the allowed hosts.";
63
- }
64
- /** The old level a payload records; undefined for an event recorded after auto mode. */
65
- function legacyLevel(p) {
66
- if (p.tier === undefined)
67
- return undefined;
68
- return {
69
- tier: p.tier,
70
- isolation: p.isolation ?? "sandbox",
71
- ...(p.network === "none" && { network: "none" }),
72
- ...(p.localhost !== undefined && { localhost: p.localhost }),
73
- ...(p.unixSockets !== undefined && { unixSockets: p.unixSockets }),
74
- ...(p.unattended === true && { unattended: true }),
75
- };
76
- }
77
- /** The level a payload records, in either shape; undefined without one. */
78
- export function devicePathsLevel(p) {
79
- if (p.permissionContextVersion === 1)
80
- return undefined;
81
- if (p.mode !== undefined &&
82
- p.allowedMode !== undefined &&
83
- typeof p.network === "object" &&
84
- p.network !== null) {
85
- return {
86
- mode: p.mode,
87
- allowedMode: p.allowedMode,
88
- network: { kind: p.network.kind, hosts: [...p.network.hosts] },
89
- local: p.local === true,
90
- };
91
- }
92
- return legacyLevel(p);
93
- }
94
- /** The system message of a `device_paths` event (model-visible, English). */
95
- export function devicePathsText(p) {
96
- if (p.permissionContextVersion === 1)
97
- return managedDevicePathsText(p);
98
- const roots = rootsText(p.roots);
99
- const level = devicePathsLevel(p);
100
- if (level === undefined)
101
- return roots;
102
- return `${roots}\n${"mode" in level ? modeLevelText(level) : sandboxLevelText(level)}`;
103
- }
104
- /** The fields of a level, in a fixed order (absent ones left out). */
105
- const levelKey = (l) => {
106
- if (l === undefined)
107
- return [];
108
- if ("mode" in l)
109
- return [l.mode, l.network.kind];
110
- return [
111
- l.tier,
112
- l.isolation,
113
- ...(l.network !== undefined ? [`network:${l.network}`] : []),
114
- ...(l.localhost !== undefined ? [`localhost:${l.localhost}`] : []),
115
- ...(l.unixSockets !== undefined ? [`unixSockets:${l.unixSockets}`] : []),
116
- ...(l.unattended === true ? ["unattended"] : []),
117
- ];
118
- };
1
+ import { managedDevicePathsHash, managedDevicePathsIdemKey } from "./permission-profile.js";
119
2
  /** Whether two sets of roots are the same paths. */
120
3
  export const sameRoots = (a, b) => a.workspace === b.workspace && a.skills === b.skills && a.tmp === b.tmp;
121
- /**
122
- * The idempotency key of a `device_paths` event for `p` that follows the conversation's event at
123
- * `prevSeq` (0: none). Unique per change (A → B → A gets three events), while parallel calls that
124
- * saw the same latest event write it once.
125
- */
126
- export const devicePathsIdemKey = (p, prevSeq) => `device_paths:${createHash("sha256")
127
- .update(JSON.stringify([
128
- p.roots.workspace,
129
- p.roots.skills,
130
- p.roots.tmp,
131
- ...levelKey(devicePathsLevel(p)),
132
- ]))
133
- .digest("hex")
134
- .slice(0, 16)}:${prevSeq}`;
135
- /**
136
- * The `device_paths` event to append when a sandbox call holds an instance with `roots` in a
137
- * device at `level`, and the conversation's latest such event is `latest`; null when nothing
138
- * changed. Without a `level` (not known: test stubs, a replay of a call recorded before auto mode)
139
- * only the roots are compared and recorded.
140
- */
141
- export function devicePathsChange(latest, roots, runId, level) {
142
- if (latest) {
143
- const sameLevel = level === undefined ||
144
- JSON.stringify(levelKey(devicePathsLevel(latest.payload))) ===
145
- JSON.stringify(levelKey(level));
146
- if (sameRoots(latest.payload.roots, roots) && sameLevel)
147
- return null;
148
- }
149
- const payload = {
150
- roots: { workspace: roots.workspace, skills: roots.skills, tmp: roots.tmp },
151
- ...(level !== undefined && level),
152
- };
153
- return {
154
- type: "device_paths",
155
- ...(runId !== undefined && { runId }),
156
- idemKey: devicePathsIdemKey(payload, latest?.seq ?? 0),
157
- payload,
158
- };
159
- }
160
- /** The latest `device_paths` event at or before `seq`; undefined without one. */
161
- export function devicePathsAt(events, seq) {
162
- let found;
163
- for (const e of events) {
164
- if (e.seq > seq)
165
- break;
166
- if (e.type === "device_paths")
167
- found = e;
168
- }
169
- return found;
170
- }
171
- /** Full managed payload equality; historical payloads retain their existing comparisons and keys. */
4
+ /** Append the managed paths only when their recorded facts change. */
172
5
  export function devicePathsChangeFromPayload(latest, payload, runId) {
173
- if (payload.permissionContextVersion !== 1)
174
- return devicePathsChange(latest, payload.roots, runId, devicePathsLevel(payload));
175
- const currentHash = managedDevicePathsHash(payload);
176
- if (latest?.payload.permissionContextVersion === 1 &&
177
- managedDevicePathsHash(latest.payload) === currentHash)
6
+ if (latest && managedDevicePathsHash(latest.payload) === managedDevicePathsHash(payload))
178
7
  return null;
179
8
  return {
180
9
  type: "device_paths",
@@ -17,7 +17,7 @@ export declare const permissionQuote: (value: string) => string;
17
17
  */
18
18
  export declare function permissionContextText(payload: PermissionContextV2): string;
19
19
  export declare function managedDevicePathsText(payload: ManagedDevicePathsV1): string;
20
- /** A recorded payload read as v2 (a stored v1 one up-converted with `sandbox: null`); throws. */
20
+ /** Parse a recorded payload with the current schema. */
21
21
  export declare function readRecordedPermissionContext(payload: unknown): PermissionContextV2;
22
22
  /** The canonical hash of a recorded device sandbox block (request metadata `sandbox`). */
23
23
  export declare const permissionSandboxHash: (sandbox: PermissionContextSandbox) => string;
@@ -28,24 +28,14 @@ export declare const managedDevicePathsIdemKey: (payload: ManagedDevicePathsV1,
28
28
  export declare function permissionContextAt(events: readonly ConversationEvent[], seq: number): Extract<ConversationEvent, {
29
29
  type: "permission_context";
30
30
  }> | undefined;
31
- /**
32
- * Snapshot validation for raw (cast) events: every `permission_context` and every `device_paths`
33
- * carrying a marker must satisfy its strict schema, covered or not, before any rendering; an
34
- * unsupported version must never fall back to historical text. Unmarked paths keep their parser.
35
- */
31
+ /** Validate recorded permissions, including events that a summary covers. */
36
32
  export declare function assertRecordedPermissionEvents(events: readonly ConversationEvent[]): void;
37
33
  export interface PermissionContribution {
38
34
  type: "permission_context" | "device_paths";
39
35
  text: string;
40
36
  }
41
37
  export declare function permissionContextMeta(events: readonly ConversationEvent[], contributions: readonly PermissionContribution[]): PermissionContextMetaV1 | undefined;
42
- /**
43
- * One traversal for request rendering and original-coordinate replay diagnostics. Both callers get
44
- * the same marker rule: a present marker or version that fails its strict schema (covered by a
45
- * summary or not) throws {@link RecordedPermissionContextError} before anything renders, so it is
46
- * never shown as historical device-mode text nor surfaces as a raw schema error. Unmarked events
47
- * are left to their historical rendering.
48
- */
38
+ /** Shared traversal for request rendering and original-coordinate replay diagnostics. */
49
39
  export declare function permissionContextHistory(events: readonly ConversationEvent[], coversUpToSeq?: number): {
50
40
  restored: (PermissionContribution & {
51
41
  seq: number;
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { ManagedDevicePathsV1Schema, PermissionContextV2Schema, permissionCodePointCompare, RecordedPermissionContextSchema, } from "../../conversations/events.js";
2
+ import { ManagedDevicePathsV1Schema, PermissionContextV2Schema, permissionCodePointCompare, } from "../../conversations/events.js";
3
3
  /** A recorded log carries a present marker or version that its strict schema rejects. */
4
4
  export class RecordedPermissionContextError extends Error {
5
5
  seq;
@@ -173,9 +173,9 @@ export function managedDevicePathsText(payload) {
173
173
  const p = ManagedDevicePathsV1Schema.parse(payload);
174
174
  return `Device directories: workspace ${permissionQuote(p.roots.workspace)}, skills ${permissionQuote(p.roots.skills)}, temporary files ${permissionQuote(p.roots.tmp)}.\nSelected working directory: ${permissionQuote(p.workingRoot)}. These paths do not grant access; the current permission context governs new operations.`;
175
175
  }
176
- /** A recorded payload read as v2 (a stored v1 one up-converted with `sandbox: null`); throws. */
176
+ /** Parse a recorded payload with the current schema. */
177
177
  export function readRecordedPermissionContext(payload) {
178
- return RecordedPermissionContextSchema.parse(payload);
178
+ return PermissionContextV2Schema.parse(payload);
179
179
  }
180
180
  /** The canonical hash of a recorded device sandbox block (request metadata `sandbox`). */
181
181
  export const permissionSandboxHash = (sandbox) => hash(["permission_sandbox", 2, sandbox]);
@@ -197,23 +197,12 @@ export function permissionContextAt(events, seq) {
197
197
  latest = e;
198
198
  return latest;
199
199
  }
200
- /**
201
- * Snapshot validation for raw (cast) events: every `permission_context` and every `device_paths`
202
- * carrying a marker must satisfy its strict schema, covered or not, before any rendering; an
203
- * unsupported version must never fall back to historical text. Unmarked paths keep their parser.
204
- */
200
+ /** Validate recorded permissions, including events that a summary covers. */
205
201
  export function assertRecordedPermissionEvents(events) {
206
202
  for (const e of events) {
207
- if (e.type === "permission_context") {
208
- if (!RecordedPermissionContextSchema.safeParse(e.payload).success)
209
- throw new RecordedPermissionContextError(e.seq, e.type);
210
- }
211
- else if (e.type === "device_paths" &&
212
- typeof e.payload === "object" &&
213
- e.payload !== null &&
214
- e.payload.permissionContextVersion !==
215
- undefined &&
216
- !ManagedDevicePathsV1Schema.safeParse(e.payload).success)
203
+ if ((e.type === "permission_context" &&
204
+ !PermissionContextV2Schema.safeParse(e.payload).success) ||
205
+ (e.type === "device_paths" && !ManagedDevicePathsV1Schema.safeParse(e.payload).success))
217
206
  throw new RecordedPermissionContextError(e.seq, e.type);
218
207
  }
219
208
  }
@@ -229,13 +218,7 @@ export function permissionContextMeta(events, contributions) {
229
218
  ...(sandbox !== null && { sandbox: permissionSandboxHash(sandbox) }),
230
219
  };
231
220
  }
232
- /**
233
- * One traversal for request rendering and original-coordinate replay diagnostics. Both callers get
234
- * the same marker rule: a present marker or version that fails its strict schema (covered by a
235
- * summary or not) throws {@link RecordedPermissionContextError} before anything renders, so it is
236
- * never shown as historical device-mode text nor surfaces as a raw schema error. Unmarked events
237
- * are left to their historical rendering.
238
- */
221
+ /** Shared traversal for request rendering and original-coordinate replay diagnostics. */
239
222
  export function permissionContextHistory(events, coversUpToSeq) {
240
223
  assertRecordedPermissionEvents(events);
241
224
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
@@ -244,7 +227,7 @@ export function permissionContextHistory(events, coversUpToSeq) {
244
227
  const contribution = (e) => {
245
228
  if (e.type === "permission_context")
246
229
  return { type: e.type, text: permissionContextText(e.payload) };
247
- if (e.type === "device_paths" && e.payload.permissionContextVersion === 1)
230
+ if (e.type === "device_paths")
248
231
  return { type: e.type, text: managedDevicePathsText(e.payload) };
249
232
  return undefined;
250
233
  };
@@ -10,7 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { SandboxScopeDeniedError } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { EventLog } from "../conversations/event-log.js";
13
- import { RecordedPermissionContextSchema } from "../conversations/events.js";
13
+ import { PermissionContextV2Schema } from "../conversations/events.js";
14
14
  import { PermissionProfileStore } from "../conversations/permission-profile-store.js";
15
15
  import { ApiError } from "../errors.js";
16
16
  import { afterCommit } from "../infra/database/after-commit.js";
@@ -243,11 +243,10 @@ let PermissionContextRecorder = class PermissionContextRecorder {
243
243
  .executeTakeFirst();
244
244
  const previousSeq = latest ? Number(latest.seq) : 0;
245
245
  if (latest) {
246
- const prior = RecordedPermissionContextSchema.safeParse(latest.payload);
246
+ const prior = PermissionContextV2Schema.safeParse(latest.payload);
247
247
  if (!prior.success)
248
248
  throw new RecordedPermissionContextError(previousSeq, "permission_context");
249
- // a stored v1 prior compares as its up-converted form (v2, sandbox null): identical
250
- // content appends nothing, whatever version the row was written in
249
+ // Identical recorded facts append nothing.
251
250
  if (permissionContextHash(prior.data) === permissionContextHash(payload))
252
251
  return null;
253
252
  }