@capybara-hq/kernel 0.1.0-rc.128 → 0.1.0-rc.129

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 (113) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +14 -0
  3. package/dist/automations/automations.service.js +15 -21
  4. package/dist/automations/effective-settings.d.ts +3 -9
  5. package/dist/automations/effective-settings.js +3 -5
  6. package/dist/automations/fire.js +0 -11
  7. package/dist/automations/grant-rules.d.ts +7 -10
  8. package/dist/automations/grant-rules.js +9 -18
  9. package/dist/automations/unattended.d.ts +1 -4
  10. package/dist/automations/unattended.js +0 -2
  11. package/dist/catalog/org-extension.controller.d.ts +1 -20
  12. package/dist/catalog/org-extension.controller.js +1 -48
  13. package/dist/catalog/org-extension.schemas.d.ts +1 -9
  14. package/dist/catalog/org-extension.schemas.js +1 -17
  15. package/dist/config/schema.d.ts +12 -0
  16. package/dist/config/schema.js +16 -0
  17. package/dist/conversations/approval-profile.d.ts +8 -1
  18. package/dist/conversations/approval-profile.js +20 -0
  19. package/dist/conversations/conversations.service.d.ts +1 -1
  20. package/dist/conversations/conversations.service.js +8 -3
  21. package/dist/conversations/events.d.ts +25 -1
  22. package/dist/conversations/events.js +7 -2
  23. package/dist/conversations/permission-profiles.controller.d.ts +4 -0
  24. package/dist/conversations/permission-profiles.schemas.d.ts +5 -0
  25. package/dist/conversations/permission-profiles.schemas.js +8 -0
  26. package/dist/conversations/permission-profiles.service.d.ts +8 -1
  27. package/dist/conversations/permission-profiles.service.js +13 -1
  28. package/dist/db/kernel-schema.d.ts +21 -0
  29. package/dist/device-access/device-access.service.d.ts +4 -1
  30. package/dist/device-access/device-access.service.js +26 -7
  31. package/dist/device-access/viewer.d.ts +3 -1
  32. package/dist/device-access/viewer.js +18 -9
  33. package/dist/errors.d.ts +6 -0
  34. package/dist/errors.js +6 -0
  35. package/dist/git/gateway.d.ts +8 -1
  36. package/dist/git/gateway.js +68 -11
  37. package/dist/git/git.module.d.ts +2 -3
  38. package/dist/git/git.module.js +4 -4
  39. package/dist/http/api.module.js +3 -3
  40. package/dist/identity/settings.d.ts +20 -5
  41. package/dist/identity/settings.js +52 -9
  42. package/dist/infra/config/kernel-config.service.js +4 -0
  43. package/dist/orgs/orgs.module.js +12 -1
  44. package/dist/orgs/orgs.schemas.js +3 -0
  45. package/dist/orgs/security-settings.service.d.ts +94 -0
  46. package/dist/orgs/security-settings.service.js +223 -0
  47. package/dist/orgs/settings.controller.d.ts +33 -0
  48. package/dist/orgs/settings.controller.js +41 -1
  49. package/dist/orgs/settings.service.d.ts +48 -63
  50. package/dist/orgs/settings.service.js +86 -103
  51. package/dist/platform/exclusions.js +1 -1
  52. package/dist/platform/operation.js +4 -0
  53. package/dist/platform/ops/admin.ops.js +18 -4
  54. package/dist/platform/ops/connectors.ops.js +2 -2
  55. package/dist/platform/ops/extensions.ops.d.ts +1 -3
  56. package/dist/platform/ops/extensions.ops.js +4 -131
  57. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  58. package/dist/platform/ops/org-settings.ops.js +76 -3
  59. package/dist/platform/ops/orgs.ops.js +2 -0
  60. package/dist/runtime/context/permission-profile.js +6 -0
  61. package/dist/runtime/subagents/dispatch.d.ts +3 -0
  62. package/dist/runtime/subagents/dispatch.js +2 -1
  63. package/dist/runtime/subagents/messages.d.ts +3 -1
  64. package/dist/runtime/subagents/messages.js +9 -6
  65. package/dist/sandbox/device-sandbox-settings.d.ts +55 -1
  66. package/dist/sandbox/device-sandbox-settings.js +64 -1
  67. package/dist/sandbox/device-sandbox.d.ts +9 -1
  68. package/dist/sandbox/device-sandbox.js +17 -2
  69. package/dist/sandbox/device-services.d.ts +26 -3
  70. package/dist/sandbox/device-services.js +95 -16
  71. package/dist/sandbox/loopback-grant-records.d.ts +3 -2
  72. package/dist/sandbox/loopback-grant-records.js +32 -5
  73. package/dist/sandbox/operation-authority.d.ts +3 -2
  74. package/dist/sandbox/operation-authority.js +21 -1
  75. package/dist/sandbox/operation-intents.js +5 -1
  76. package/dist/sandbox/permission-call-types.d.ts +2 -1
  77. package/dist/sandbox/permission-ceiling-writes.d.ts +14 -5
  78. package/dist/sandbox/permission-ceiling-writes.js +122 -13
  79. package/dist/sandbox/permission-config-publication.d.ts +10 -0
  80. package/dist/sandbox/permission-config-publication.js +27 -5
  81. package/dist/sandbox/permission-facts.d.ts +21 -2
  82. package/dist/sandbox/permission-facts.js +101 -9
  83. package/dist/sandbox/permission-transitions.d.ts +1 -1
  84. package/dist/sandbox/sandbox.service.d.ts +2 -2
  85. package/dist/sandbox/sandbox.service.js +7 -3
  86. package/dist/tools/admin-connectors.js +2 -2
  87. package/dist/tools/approvals.service.d.ts +7 -2
  88. package/dist/tools/approvals.service.js +39 -7
  89. package/dist/tools/builtin-names.d.ts +0 -6
  90. package/dist/tools/builtin-names.js +0 -11
  91. package/dist/tools/builtins/sandbox/index.d.ts +3 -5
  92. package/dist/tools/builtins/sandbox/index.js +3 -5
  93. package/dist/tools/connector-account-policies.js +7 -4
  94. package/dist/tools/connectors.controller.d.ts +0 -6
  95. package/dist/tools/connectors.schemas.d.ts +1 -8
  96. package/dist/tools/connectors.schemas.js +1 -4
  97. package/dist/tools/connectors.service.d.ts +3 -7
  98. package/dist/tools/connectors.service.js +29 -44
  99. package/dist/tools/drift.js +12 -4
  100. package/dist/tools/git-push-policy.d.ts +1 -4
  101. package/dist/tools/git-push-policy.js +4 -5
  102. package/dist/tools/org-tool-policies.d.ts +24 -0
  103. package/dist/tools/org-tool-policies.js +113 -0
  104. package/dist/tools/org-tool-switches.d.ts +5 -70
  105. package/dist/tools/org-tool-switches.js +13 -141
  106. package/dist/tools/pipeline.d.ts +11 -5
  107. package/dist/tools/pipeline.js +173 -38
  108. package/dist/tools/policy.d.ts +3 -7
  109. package/dist/tools/policy.js +29 -48
  110. package/dist/tools/registry.d.ts +5 -0
  111. package/dist/tools/registry.js +44 -13
  112. package/package.json +1 -1
  113. package/src/migrations/0212_org_security_policy.sql +234 -0
@@ -8,26 +8,27 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash } from "node:crypto";
11
- import { DEFAULT_SANDBOX_ROOTS, rootsOf, validateAllowHost, } from "@capybara-hq/plugin-sdk";
11
+ import { DEFAULT_SANDBOX_ROOTS, instanceSupported, parseProjectReachAuthority, rootsOf, validateAllowHost, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { permissionCodePointCompare } from "../conversations/events.js";
15
15
  import { DeviceAccess } from "../devices/access.js";
16
16
  import { deviceNotFound, projectsUnsupported } from "../devices/errors.js";
17
17
  import { projectNotFound, tooBroad } from "../devices/project-rules.js";
18
- import { aboveHome } from "../devices/working-root.js";
18
+ import { aboveHome, canonicalRoot } from "../devices/working-root.js";
19
19
  import { ApiError } from "../errors.js";
20
20
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
21
21
  import { KernelDb } from "../infra/database/kernel-db.js";
22
22
  import { readOrgSettings } from "../orgs/settings.service.js";
23
23
  import { storedReport, storedSupport } from "./device-reports.js";
24
24
  import { canonicalHostCeiling, deviceListAddRefusal, effectiveDeviceSandbox, hostGrantCeiling, hostGrantRefusal, orgHostsOf, providerLayerOf, reachWithin, } from "./device-sandbox.js";
25
- import { readDeviceSandboxSettings } from "./device-sandbox-settings.js";
25
+ import { DEFAULT_ALLOWED_PROFILES, effectiveAllowedProfiles, readDeviceSandboxSettings, } from "./device-sandbox-settings.js";
26
26
  import { appliedOf, appliedWider, coversHost, effectiveDevicePolicy, readDeploymentDevicePolicy, readInstanceLimits, } from "./modes.js";
27
27
  import { assertAuthorityHeld } from "./permission-authority-lock.js";
28
28
  import { deviceWorkAvailability, permissionAvailabilityFor, } from "./permission-availability.js";
29
+ import { reachNarrowed } from "./permission-ceiling-writes.js";
29
30
  import { readCurrentReport } from "./permission-runtime-reports.js";
30
- import { DeviceProviders } from "./providers.js";
31
+ import { DeviceProviders, servesDialIn } from "./providers.js";
31
32
  import { homeOf } from "./review/rules.js";
32
33
  export const permissionScopeHash = (value) => createHash("sha256").update(canonical(value)).digest("hex");
33
34
  function canonical(value) {
@@ -129,6 +130,7 @@ let PermissionFacts = class PermissionFacts {
129
130
  egress: limits.egress,
130
131
  };
131
132
  const orgLayer = {
133
+ ...(org.projectReach !== undefined && { projectReach: org.projectReach }),
132
134
  ...(org.outsideSandbox !== undefined && { outsideSandbox: org.outsideSandbox }),
133
135
  ...(org.deviceNetwork !== undefined && { deviceNetwork: org.deviceNetwork }),
134
136
  };
@@ -161,6 +163,7 @@ let PermissionFacts = class PermissionFacts {
161
163
  /** Where its provider applies new limits (`limitsApplyAt`; absent: at its instance). */
162
164
  limitsApplyAt: row ? this.providers.forDevice(row.provider)?.impl.limitsApplyAt : undefined,
163
165
  reach: {
166
+ ...(box.projectReach !== undefined && { projectReach: box.projectReach }),
164
167
  outsideSandbox: box.outsideSandbox,
165
168
  networkCeiling: box.networkCeiling,
166
169
  networkMode: box.networkMode,
@@ -187,6 +190,7 @@ let PermissionFacts = class PermissionFacts {
187
190
  egress: limits.egress,
188
191
  };
189
192
  const orgLayer = {
193
+ ...(org.projectReach !== undefined && { projectReach: org.projectReach }),
190
194
  ...(org.outsideSandbox !== undefined && { outsideSandbox: org.outsideSandbox }),
191
195
  ...(org.deviceNetwork !== undefined && { deviceNetwork: org.deviceNetwork }),
192
196
  };
@@ -197,6 +201,59 @@ let PermissionFacts = class PermissionFacts {
197
201
  });
198
202
  return hostGrantCeiling(box, platform, orgLayer);
199
203
  }
204
+ /**
205
+ * The provider's own generation binds a restricted ceiling on dial-in work. The provider
206
+ * negotiates the wire feature against its live owner report and refuses before forwarding if
207
+ * the connected program cannot enforce it. Instance-confined providers need no wire grant.
208
+ */
209
+ async projectReachAuthority(orgId, deviceId, ceiling, held) {
210
+ if (ceiling === undefined || ceiling === "machine")
211
+ return undefined;
212
+ const row = await this.db
213
+ .selectFrom("devices as d")
214
+ .leftJoin("device_instances as i", (join) => join.onRef("i.device_id", "=", "d.id").onRef("i.org_id", "=", "d.org_id"))
215
+ .select(["d.provider", "i.handle", "i.created_at"])
216
+ .where("d.org_id", "=", orgId)
217
+ .where("d.id", "=", deviceId)
218
+ .where("d.deleted_at", "is", null)
219
+ .executeTakeFirst();
220
+ if (!row)
221
+ throw deviceNotFound();
222
+ if (row.created_at && row.provider) {
223
+ const owed = await this.db
224
+ .selectFrom("sandbox_operation_intents")
225
+ .select("scope")
226
+ .where("org_id", "=", orgId)
227
+ .where("device_id", "=", deviceId)
228
+ .where("provider", "=", row.provider)
229
+ .where("instance_generation", "=", String(row.created_at.getTime()))
230
+ .where("state", "=", "revoked")
231
+ .where("outcome_unknown", "=", true)
232
+ .where("revoke_acknowledged", "=", false)
233
+ .execute();
234
+ if (owed.some(({ scope }) => reachNarrowed(scope, ceiling)))
235
+ throw new ApiError("device.unavailable", "The device is still revoking work from its previous project reach. Try again when revocation completes.");
236
+ }
237
+ const entry = this.providers.forDevice(row.provider);
238
+ if (!entry || !servesDialIn(entry)) {
239
+ const support = entry
240
+ ? (await readCurrentReport(this.db.db, deviceId, entry.plugin, entry.version)).support
241
+ : null;
242
+ if (support && instanceSupported(support))
243
+ return undefined;
244
+ throw new ApiError("device.unavailable", "The device provider cannot prove the current project reach. Choose a device that supports the ceiling.");
245
+ }
246
+ const h = held ?? row.handle;
247
+ const generation = h && "generation" in h ? h.generation : undefined;
248
+ if (generation === undefined)
249
+ throw new ApiError("device.unavailable", "The device instance must bind before it can enforce project reach.");
250
+ try {
251
+ return parseProjectReachAuthority({ ceiling, instanceGeneration: generation });
252
+ }
253
+ catch {
254
+ throw new ApiError("device.unavailable", "The device has no valid generation for project reach.");
255
+ }
256
+ }
200
257
  /** Stored binding only; projectScope supplies the live owner and deletion checks. */
201
258
  async readProject(orgId, deviceId, name) {
202
259
  return ((await this.db
@@ -360,8 +417,11 @@ let PermissionFacts = class PermissionFacts {
360
417
  .executeTakeFirst();
361
418
  if (row === undefined)
362
419
  throw deviceNotFound();
363
- const { mode } = await this.devicePolicy({ orgId, deviceId });
364
- const home = storedReport(row.report)?.home ?? null;
420
+ const [{ mode }, sandbox] = await Promise.all([
421
+ this.devicePolicy({ orgId, deviceId }),
422
+ this.deviceSandbox(orgId, deviceId),
423
+ ]);
424
+ const home = sandbox.projectReach === "workspace" ? null : (storedReport(row.report)?.home ?? null);
365
425
  const impl = this.providers.forDevice(row.provider)?.impl;
366
426
  const handle = row.handle;
367
427
  return {
@@ -369,6 +429,7 @@ let PermissionFacts = class PermissionFacts {
369
429
  workspace: handle === null ? DEFAULT_SANDBOX_ROOTS.workspace : rootsOf(handle).workspace,
370
430
  home,
371
431
  supported: typeof impl?.list === "function",
432
+ ...(sandbox.projectReach !== undefined && { projectReach: sandbox.projectReach }),
372
433
  };
373
434
  }
374
435
  async resolveProjectForBinding(orgId, deviceId, accountId, name) {
@@ -382,6 +443,11 @@ let PermissionFacts = class PermissionFacts {
382
443
  // would fall back for it, so it is not bound (the add rule, project root §4.3)
383
444
  if (aboveHome(row.path, scope.home))
384
445
  throw tooBroad(row.name);
446
+ if (scope.projectReach === "workspace") {
447
+ const path = canonicalRoot(row.path), workspace = canonicalRoot(scope.workspace);
448
+ if (path !== workspace && !path.startsWith(workspace === "/" ? "/" : `${workspace}/`))
449
+ throw new ApiError("device.project_outside_mode", "The project's path is outside the device workspace.");
450
+ }
385
451
  return { name: row.name, path: row.path };
386
452
  }
387
453
  async projectMatches(deviceId, name, path) {
@@ -396,7 +462,17 @@ let PermissionFacts = class PermissionFacts {
396
462
  }
397
463
  async scope(orgId, deviceId, projectPath, project) {
398
464
  const { sandbox } = await this.readDevice(orgId, deviceId);
399
- const availability = await this.availability(orgId, deviceId);
465
+ let availability = await this.availability(orgId, deviceId);
466
+ if (sandbox.projectReach !== undefined && availability.state === "supported") {
467
+ try {
468
+ await this.projectReachAuthority(orgId, deviceId, sandbox.projectReach);
469
+ }
470
+ catch (error) {
471
+ if (!(error instanceof ApiError) || error.code !== "device.unavailable")
472
+ throw error;
473
+ availability = { state: "unsupported", reason: error.message, cause: { kind: "runtime" } };
474
+ }
475
+ }
400
476
  // A ceiling restored to the same values is still a new authorization decision. Reads do
401
477
  // not initialize epoch rows; absent rows denote the pre-change revision zero.
402
478
  const epochRows = await this.db
@@ -451,7 +527,18 @@ let PermissionFacts = class PermissionFacts {
451
527
  ? null
452
528
  : await this.resolveProjectForBinding(orgId, deviceId, accountId, project);
453
529
  const scope = await this.scope(orgId, deviceId, binding?.path ?? null, project ?? null);
454
- return { ...scope, availability: deviceWorkAvailability(scope.availability) };
530
+ return {
531
+ ...scope,
532
+ allowedProfiles: await this.allowedProfiles(orgId),
533
+ availability: deviceWorkAvailability(scope.availability),
534
+ };
535
+ }
536
+ async allowedProfiles(orgId) {
537
+ const [platform, org] = await Promise.all([
538
+ readDeviceSandboxSettings(this.db.db, this.config),
539
+ readOrgSettings(this.db.db, orgId),
540
+ ]);
541
+ return effectiveAllowedProfiles(platform.allowedProfiles ?? DEFAULT_ALLOWED_PROFILES, org.allowedProfiles);
455
542
  }
456
543
  async view(orgId, accountId, row) {
457
544
  return (await this.viewWithAccess(orgId, accountId, row)).view;
@@ -471,6 +558,7 @@ let PermissionFacts = class PermissionFacts {
471
558
  * recorded permission context needs the distinction; the view itself stays unchanged.
472
559
  */
473
560
  async viewWithAccess(orgId, accountId, row) {
561
+ const allowedProfiles = await this.allowedProfiles(orgId);
474
562
  let preview = null;
475
563
  let unavailableReason = "Choose a device to run device operations";
476
564
  let access = "no-device";
@@ -492,17 +580,21 @@ let PermissionFacts = class PermissionFacts {
492
580
  // Auto holds whatever the device supports (device tools refuse at admission instead) and
493
581
  // without a device (no consent row, ruling R8); with a device it needs that device to be
494
582
  // reachable and its consent to still cover the device's ceilings
495
- const profile = row.permission_profile === "full-access" &&
583
+ const selected = row.permission_profile === "full-access" &&
496
584
  row.device_id !== null &&
497
585
  (!preview || !consentHolds(consent, row.device_id, preview))
498
586
  ? "approve-for-me"
499
587
  : row.permission_profile;
588
+ const profile = allowedProfiles.includes(row.permission_profile) && allowedProfiles.includes(selected)
589
+ ? selected
590
+ : "request-approval";
500
591
  return {
501
592
  access,
502
593
  /** Whether the device's scope was read (a usable device): its availability is a verdict. */
503
594
  previewed: preview !== null,
504
595
  view: {
505
596
  profile,
597
+ allowedProfiles,
506
598
  revision: row.permission_revision,
507
599
  rootConversationId: row.id,
508
600
  deviceId: row.device_id,
@@ -14,7 +14,7 @@ export type PermissionTransition = {
14
14
  revision: number;
15
15
  scopeRevision: string | null;
16
16
  actorAccountId: string | null;
17
- reason: "user" | "authority-changed";
17
+ reason: "user" | "authority-changed" | "platform-profile-ceiling" | "org-profile-ceiling";
18
18
  };
19
19
  /** Canonical lower write: never takes descendant authority or imports the tools domain. */
20
20
  export declare class PermissionTransitions {
@@ -81,8 +81,8 @@ export type DeviceServiceMethods = Pick<DeviceProvider, "ensureService" | "stopS
81
81
  /** A device held for a stream ({@link SandboxService.holdForStream}). */
82
82
  export interface StreamHold {
83
83
  h: SandboxHandle;
84
- /** The provider's `openStream`, bound. */
85
- p: Required<Pick<DeviceProvider, "openStream">>;
84
+ /** The bound stream method and the service's reach check when supported. */
85
+ p: Required<Pick<DeviceProvider, "openStream">> & Pick<DeviceProvider, "ensureService">;
86
86
  /**
87
87
  * Aborts when the caller's signal aborts or the hold ends (a lifecycle change of the device);
88
88
  * the hold is then released.
@@ -818,7 +818,10 @@ let SandboxService = class SandboxService {
818
818
  }
819
819
  return {
820
820
  h: after.handle,
821
- p: { openStream: impl.openStream.bind(impl) },
821
+ p: {
822
+ openStream: impl.openStream.bind(impl),
823
+ ...(impl.ensureService && { ensureService: impl.ensureService.bind(impl) }),
824
+ },
822
825
  signal: sig,
823
826
  release,
824
827
  };
@@ -867,6 +870,7 @@ let SandboxService = class SandboxService {
867
870
  operationId,
868
871
  deviceId: ctx.deviceId,
869
872
  purpose,
873
+ ...(authority.projectReach !== undefined && { projectReach: authority.projectReach }),
870
874
  writeRoots: [...roots],
871
875
  tag: operationId,
872
876
  }), sig);
@@ -886,7 +890,7 @@ let SandboxService = class SandboxService {
886
890
  * ceiling and never wider; none inside it is `device.project_outside_mode`.
887
891
  */
888
892
  async withBrowse(ctx, fn, signal, narrow) {
889
- await this.authority.resolveBrowse(ctx, signal, narrow);
893
+ await this.authority.resolveBrowse(ctx, signal, narrow, true);
890
894
  const row = await this.readRow(ctx);
891
895
  if (!row)
892
896
  throw deviceNotRunning();
@@ -937,7 +941,7 @@ let SandboxService = class SandboxService {
937
941
  * (`device.project_outside_mode`) never starts the device.
938
942
  */
939
943
  async ensureRunningForOwner(ctx, signal, narrow) {
940
- await this.authority.resolveBrowse(ctx, signal, narrow);
944
+ await this.authority.resolveBrowse(ctx, signal, narrow, true);
941
945
  const p = await this.require(ctx.deviceId, ctx.orgId);
942
946
  const use = {
943
947
  orgId: ctx.orgId,
@@ -90,7 +90,7 @@ let AdminConnectors = class AdminConnectors {
90
90
  throw notFound();
91
91
  const tools = await this.db
92
92
  .selectFrom("connector_tools")
93
- .select(["name", "spec", "status", "default_policy"])
93
+ .select(["name", "spec", "status", "default_policy", "declaration_policy"])
94
94
  .where("connector_id", "=", connectorId)
95
95
  .orderBy("name")
96
96
  .execute();
@@ -105,7 +105,7 @@ let AdminConnectors = class AdminConnectors {
105
105
  name: t.name,
106
106
  title: typeof title === "string" ? title : null,
107
107
  status: t.status,
108
- defaultPolicy: t.default_policy,
108
+ defaultPolicy: t.declaration_policy ?? t.default_policy,
109
109
  };
110
110
  }),
111
111
  };
@@ -23,6 +23,7 @@ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js
23
23
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
24
24
  import type { PermissionCandidate, PermissionEscalation, PermissionExpansion } from "../sandbox/permission-call-types.js";
25
25
  import { SandboxService } from "../sandbox/sandbox.service.js";
26
+ import { type OrgToolPolicyRevision as OrgAskRevision } from "./org-tool-policies.js";
26
27
  import type { ApprovalPolicySource } from "./pipeline.js";
27
28
  import { ToolRegistry } from "./registry.js";
28
29
  export { APPROVAL_DENY_REASON_MAX_CHARS } from "../conversations/events.js";
@@ -216,7 +217,7 @@ export interface CommandAskDetail {
216
217
  export declare const NETWORK_ASK_CANCELLED_NOTE = "[network] The run was stopped before the user answered; access stays blocked.";
217
218
  /** The model-visible note after a git ask's kept result when its run is stopped before the answer. */
218
219
  export declare const GIT_ASK_CANCELLED_NOTE = "[git] The run was stopped before the user answered; the push was not made.";
219
- /** 一条审批记录。 */
220
+ /** A stored approval. */
220
221
  export interface ApprovalRecord {
221
222
  id: string;
222
223
  orgId: string;
@@ -259,6 +260,7 @@ export interface ApprovalRecord {
259
260
  * approval, R3): the card says it is the person's call. Absent otherwise.
260
261
  */
261
262
  reviewUnsure?: true;
263
+ orgAskRevisions?: readonly OrgAskRevision[];
262
264
  toolKey: string;
263
265
  specHash: string;
264
266
  connectorId: string | null;
@@ -287,7 +289,7 @@ export interface ApprovalRecord {
287
289
  createdAt: string;
288
290
  }
289
291
  /** An approval as a route answers it: a network or git ask's detail without the kept command result. */
290
- export interface ApprovalPublicRecord extends Omit<ApprovalRecord, "detail" | "git"> {
292
+ export interface ApprovalPublicRecord extends Omit<ApprovalRecord, "detail" | "git" | "orgAskRevisions"> {
291
293
  detail: NetworkAskView | null;
292
294
  git: GitAskView | null;
293
295
  }
@@ -374,6 +376,8 @@ export interface ApprovalRequestInput {
374
376
  scopes?: ApprovalScope[];
375
377
  /** The file a tool ask's call takes and the review's unsure mark (stored in `detail`). */
376
378
  detail?: ToolAskDetail;
379
+ /** Previous attempt invalidated by a change to its fixed org ask binding. */
380
+ supersedesOrgAsk?: string;
377
381
  }
378
382
  /**
379
383
  * A secure input request (profiles govern every approval, R4), made by the tool pipeline once the
@@ -410,6 +414,7 @@ export interface ToolAskDetail {
410
414
  file?: FileCardDetail;
411
415
  /** The review model could not decide the ask under Approve for me (R3). */
412
416
  reviewUnsure?: true;
417
+ orgAskRevisions?: readonly OrgAskRevision[];
413
418
  }
414
419
  /** A secure input request's `detail`: the fields the person enters and their target. */
415
420
  export interface SecureInputDetail {
@@ -12,7 +12,6 @@ import { connectorToolKey, parseToolKey, validateAllowHost, } from "@capybara-hq
12
12
  import { Inject, Injectable, Optional } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { normalizeStoredDefinition } from "../agents/definition.js";
15
- import { readAutomationSettings } from "../automations/effective-settings.js";
16
15
  import { GIT_GRANT_SPEC_HASH, gitGrantRefusal, gitPushGrantKey, grantRefusalOf, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantRefusal, normalizeGitRepo, } from "../automations/grant-rules.js";
17
16
  import { AutomationStore } from "../automations/store.js";
18
17
  import { unattendedRunOf, unattendedTaskRunOf } from "../automations/unattended.js";
@@ -50,6 +49,7 @@ import { isSessionGrantableRule } from "../sandbox/review/types.js";
50
49
  import { SandboxService } from "../sandbox/sandbox.service.js";
51
50
  import { gitPushPolicyName, personalAuth } from "./connector-account-policies.js";
52
51
  import { pluginDisplayNames } from "./display-names.js";
52
+ import { readOrgGitPushDenials, readOrgToolPolicy, } from "./org-tool-policies.js";
53
53
  import { ToolRegistry } from "./registry.js";
54
54
  export { APPROVAL_DENY_REASON_MAX_CHARS } from "../conversations/events.js";
55
55
  /** `list` 一次最多返回的审批数(收件箱据此判断这个来源是否取满)。 */
@@ -80,8 +80,9 @@ export function publicRecord(r) {
80
80
  const { result: _result, ...rest } = d;
81
81
  return rest;
82
82
  };
83
+ const { orgAskRevisions: _internalBinding, ...visible } = r;
83
84
  return {
84
- ...r,
85
+ ...visible,
85
86
  // never offered, even from a row stored before the catch-all was excluded: a `command` ask
86
87
  // remembers one concrete rule class, and a classifier ask (no rule) remembers nothing
87
88
  scopes: r.command !== null && !isSessionGrantableRule(r.command.rule)
@@ -158,6 +159,21 @@ const iso = (v) => new Date(v).toISOString();
158
159
  const isRole = (v) => v !== null && ORG_ROLES.includes(v);
159
160
  /** The scopes of an approval without stored ones: a role escalation is approved only once. */
160
161
  const derivedScopes = (requestedFor) => requestedFor === null ? ["once"] : ["once", "session", "always"];
162
+ function orgAskRevisionsOf(detail) {
163
+ if (typeof detail !== "object" || detail === null || !("orgAskRevisions" in detail))
164
+ return null;
165
+ const rows = detail.orgAskRevisions;
166
+ if (!Array.isArray(rows) || rows.length === 0)
167
+ return null;
168
+ if (!rows.every((row) => typeof row === "object" &&
169
+ row !== null &&
170
+ "toolKey" in row &&
171
+ "rowRevision" in row &&
172
+ typeof row.toolKey === "string" &&
173
+ typeof row.rowRevision === "string"))
174
+ return null;
175
+ return { orgAskRevisions: rows };
176
+ }
161
177
  function toRecord(r) {
162
178
  return {
163
179
  id: r.id,
@@ -173,6 +189,7 @@ function toRecord(r) {
173
189
  ...(r.kind === "secure_input" && personFieldsOf(r.detail)),
174
190
  ...(r.kind === "tool" && fileOf(r.detail)),
175
191
  ...(r.kind === "tool" && reviewUnsureOf(r.detail)),
192
+ ...(r.kind === "tool" && orgAskRevisionsOf(r.detail)),
176
193
  toolKey: r.tool_key,
177
194
  specHash: r.spec_hash,
178
195
  connectorId: r.connector_id,
@@ -302,6 +319,18 @@ let ApprovalsService = class ApprovalsService {
302
319
  .where("org_id", "=", input.orgId)
303
320
  .forUpdate()
304
321
  .execute();
322
+ if (input.supersedesOrgAsk !== undefined) {
323
+ await t
324
+ .updateTable("approvals")
325
+ .set({ status: "superseded", superseded_reason: "The organization’s tool policy changed" })
326
+ .where("org_id", "=", input.orgId)
327
+ .where("run_id", "=", input.runId)
328
+ .where("call_id", "=", input.callId)
329
+ .where("kind", "=", "tool")
330
+ .where("id", "=", input.supersedesOrgAsk)
331
+ .where("status", "in", ["pending", "approved"])
332
+ .execute();
333
+ }
305
334
  await t
306
335
  .insertInto("approvals")
307
336
  .values({
@@ -318,7 +347,7 @@ let ApprovalsService = class ApprovalsService {
318
347
  requested_for: input.requestedFor,
319
348
  approver_role: input.approverRole,
320
349
  summary: input.summary === undefined ? null : JSON.stringify(input.summary),
321
- scopes: input.scopes ?? null,
350
+ scopes: input.detail?.orgAskRevisions ? ["once"] : (input.scopes ?? null),
322
351
  ...(input.detail !== undefined && { detail: JSON.stringify(input.detail) }),
323
352
  scope: null,
324
353
  decided_by: null,
@@ -1478,6 +1507,9 @@ let ApprovalsService = class ApprovalsService {
1478
1507
  await this.permissionGrants.assertCurrent(before.command.permissionCandidate.binding);
1479
1508
  }
1480
1509
  const approved = body.decision === "approve";
1510
+ if (approved && before.orgAskRevisions && actorTokenId !== undefined) {
1511
+ throw new ApiError("auth.session_required", "A fixed organization ask must be confirmed by a person");
1512
+ }
1481
1513
  // only a secure input request takes values
1482
1514
  const person = before.kind === "secure_input" ? before.personFields : undefined;
1483
1515
  if (body.inputs !== undefined && (person === undefined || !approved)) {
@@ -1863,10 +1895,10 @@ let ApprovalsService = class ApprovalsService {
1863
1895
  source: await conversationSourceOf(t, a.conversationId),
1864
1896
  });
1865
1897
  const tool = tools.find((x) => x.key === a.toolKey);
1866
- const { forbiddenTools } = await readAutomationSettings(t, this.config, a.orgId);
1898
+ const orgPolicy = await readOrgToolPolicy(t, a.orgId, tool?.key ?? a.toolKey, a.toolKey, true);
1867
1899
  const why = grantRefusalOf(a.toolKey, tool, {
1868
1900
  role: member.role,
1869
- forbiddenTools,
1901
+ orgPolicy: orgPolicy.policy,
1870
1902
  });
1871
1903
  if (why !== null)
1872
1904
  return;
@@ -1958,8 +1990,8 @@ let ApprovalsService = class ApprovalsService {
1958
1990
  if (task?.account_id !== decidedBy)
1959
1991
  return;
1960
1992
  const key = gitPushGrantKey(a.git.repo);
1961
- const { forbiddenTools } = await readAutomationSettings(t, this.config, a.orgId);
1962
- if (gitGrantRefusal(key, { forbiddenTools }) !== null)
1993
+ const gitDenials = await readOrgGitPushDenials(t, a.orgId);
1994
+ if (gitGrantRefusal(key, { gitDenials }) !== null)
1963
1995
  return;
1964
1996
  await this.automations.addGrant(t, served.taskId, {
1965
1997
  toolKey: key,
@@ -49,12 +49,6 @@ export declare const WEB_TOOL_NAMES: readonly BuiltinName[];
49
49
  * background task can read and stop it). `ToolRegistry` adds them; an explicit ref is harmless.
50
50
  */
51
51
  export declare const BASH_COMPANION_TOOLS: readonly BuiltinName[];
52
- /**
53
- * Sandbox tools that need approval when the org setting `sandboxToolPolicy` is `ask` (not the
54
- * read-only ones). Not `TaskOutput`, `TaskStop` or `TaskList`: they only read, list or stop tasks whose launch
55
- * already went through `Bash`'s policy (background Bash spec §4.5).
56
- */
57
- export declare const SANDBOX_ASK_TOOL_NAMES: ReadonlySet<string>;
58
52
  /**
59
53
  * The builtins that manage the person's automations (scheduled tasks spec §11): create and
60
54
  * update are fixed asks ({@link R3_FIXED_ASK_TOOL_KEYS}), list, targets and delete only read or
@@ -63,17 +63,6 @@ export const BASH_COMPANION_TOOLS = [
63
63
  BUILTIN.TaskStop,
64
64
  BUILTIN.TaskList,
65
65
  ];
66
- /**
67
- * Sandbox tools that need approval when the org setting `sandboxToolPolicy` is `ask` (not the
68
- * read-only ones). Not `TaskOutput`, `TaskStop` or `TaskList`: they only read, list or stop tasks whose launch
69
- * already went through `Bash`'s policy (background Bash spec §4.5).
70
- */
71
- export const SANDBOX_ASK_TOOL_NAMES = new Set([
72
- BUILTIN.Bash,
73
- BUILTIN.Write,
74
- BUILTIN.Edit,
75
- BUILTIN.Deliver,
76
- ]);
77
66
  /**
78
67
  * The builtins that manage the person's automations (scheduled tasks spec §11): create and
79
68
  * update are fixed asks ({@link R3_FIXED_ASK_TOOL_KEYS}), list, targets and delete only read or
@@ -1,6 +1,6 @@
1
1
  import type { BuiltinTool } from "../../registry.js";
2
2
  import type { SandboxToolDeps } from "./common.js";
3
- export { SANDBOX_ASK_TOOL_NAMES, SANDBOX_TOOL_NAMES } from "../../builtin-names.js";
3
+ export { SANDBOX_TOOL_NAMES } from "../../builtin-names.js";
4
4
  export { BASH_SPILL_CHARS, formatExec } from "./bash.js";
5
5
  export { assignAttachmentNames, RUN_DEADLINE_MARGIN_MS, runTimeLeftMs, SANDBOX_RESTARTED_NOTICE, SANDBOX_SETUP_MARGIN_MS, SANDBOX_STARTED_NOTICE, SANDBOX_UNAVAILABLE_REASON, type SandboxToolDeps, sandboxBaseTimeoutMs, sandboxStartedNotice, sandboxUsable, searchTimeoutMs, shellQuote, } from "./common.js";
6
6
  export { sandboxFetchAttachmentTool } from "./fetch-attachment.js";
@@ -10,11 +10,9 @@ export { compileGlob, GlobPatternError, MAX_GLOB_STARS } from "./glob-match.js";
10
10
  * all run in the conversation's device (`SandboxService.withOperations`). Attachments are not
11
11
  * copied into it by a sandbox call: `FetchAttachment` is the only way in, writing one file under
12
12
  * `<workspace>/attachments/<conversation>` (the instance's roots, environments spec §13.1).
13
- * Unavailable without a provider for it. Allowed by default; with the org setting
14
- * `sandboxToolPolicy` set to ask, every one but Read / Glob / Grep / FetchAttachment needs approval
15
- * (see policy.ts).
13
+ * Availability depends on the provider. Each call follows its live organization tool ceiling.
16
14
  * `TaskOutput` and `TaskStop` read and stop background `Bash` tasks through
17
15
  * `SandboxService.ifRunning` (never creating or resuming a sandbox); `TaskList` lists them and the
18
- * conversation's sub-agents from PG; all three always allowed.
16
+ * conversation's sub-agents from PG.
19
17
  */
20
18
  export declare function sandboxTools(deps: SandboxToolDeps): BuiltinTool[];
@@ -9,7 +9,7 @@ import { taskListTool } from "./task-list.js";
9
9
  import { taskOutputTool } from "./task-output.js";
10
10
  import { taskStopTool } from "./task-stop.js";
11
11
  import { sandboxWriteTool } from "./write.js";
12
- export { SANDBOX_ASK_TOOL_NAMES, SANDBOX_TOOL_NAMES } from "../../builtin-names.js";
12
+ export { SANDBOX_TOOL_NAMES } from "../../builtin-names.js";
13
13
  export { BASH_SPILL_CHARS, formatExec } from "./bash.js";
14
14
  export { assignAttachmentNames, RUN_DEADLINE_MARGIN_MS, runTimeLeftMs, SANDBOX_RESTARTED_NOTICE, SANDBOX_SETUP_MARGIN_MS, SANDBOX_STARTED_NOTICE, SANDBOX_UNAVAILABLE_REASON, sandboxBaseTimeoutMs, sandboxStartedNotice, sandboxUsable, searchTimeoutMs, shellQuote, } from "./common.js";
15
15
  export { sandboxFetchAttachmentTool } from "./fetch-attachment.js";
@@ -19,12 +19,10 @@ export { compileGlob, GlobPatternError, MAX_GLOB_STARS } from "./glob-match.js";
19
19
  * all run in the conversation's device (`SandboxService.withOperations`). Attachments are not
20
20
  * copied into it by a sandbox call: `FetchAttachment` is the only way in, writing one file under
21
21
  * `<workspace>/attachments/<conversation>` (the instance's roots, environments spec §13.1).
22
- * Unavailable without a provider for it. Allowed by default; with the org setting
23
- * `sandboxToolPolicy` set to ask, every one but Read / Glob / Grep / FetchAttachment needs approval
24
- * (see policy.ts).
22
+ * Availability depends on the provider. Each call follows its live organization tool ceiling.
25
23
  * `TaskOutput` and `TaskStop` read and stop background `Bash` tasks through
26
24
  * `SandboxService.ifRunning` (never creating or resuming a sandbox); `TaskList` lists them and the
27
- * conversation's sub-agents from PG; all three always allowed.
25
+ * conversation's sub-agents from PG.
28
26
  */
29
27
  export function sandboxTools(deps) {
30
28
  return [
@@ -16,6 +16,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
16
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
17
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
18
  import { OrgLock } from "../orgs/org-lock.js";
19
+ import { readOrgToolPolicies } from "./org-tool-policies.js";
19
20
  import { policyFromAnnotations } from "./registry.js";
20
21
  /** Whether a connector's credential is per member: its calls are made with the member's connection. */
21
22
  export const personalAuth = (auth) => {
@@ -60,7 +61,7 @@ let ConnectorAccountPolicies = class ConnectorAccountPolicies {
60
61
  const c = await this.connector(orgId, connectorId);
61
62
  const tools = await this.db
62
63
  .selectFrom("connector_tools")
63
- .select(["name", "spec", "status", "default_policy", "missing_since"])
64
+ .select(["name", "spec", "status", "default_policy", "declaration_policy", "missing_since"])
64
65
  .where("connector_id", "=", connectorId)
65
66
  .orderBy("name")
66
67
  .execute();
@@ -71,19 +72,21 @@ let ConnectorAccountPolicies = class ConnectorAccountPolicies {
71
72
  .where("connector_id", "=", connectorId)
72
73
  .where("account_id", "=", accountId)
73
74
  .execute()).map((r) => [r.tool_name, r.policy]));
75
+ const orgRules = new Map((await readOrgToolPolicies(this.db, orgId)).map((rule) => [rule.toolKey, rule.policy]));
74
76
  return tools.map((t) => {
75
77
  const spec = t.spec;
78
+ const key = connectorToolKey(c.slug, t.name);
76
79
  const locked = t.status !== "enabled" || t.missing_since !== null
77
80
  ? "disabled"
78
- : t.default_policy === "deny"
81
+ : (t.declaration_policy ?? t.default_policy) === "deny" || orgRules.get(key) === "deny"
79
82
  ? "org_deny"
80
83
  : null;
81
84
  return {
82
85
  name: t.name,
83
- key: connectorToolKey(c.slug, t.name),
86
+ key,
84
87
  title: typeof spec.title === "string" ? spec.title : null,
85
88
  description: spec.description,
86
- defaultPolicy: t.default_policy,
89
+ defaultPolicy: t.declaration_policy ?? t.default_policy,
87
90
  annotationPolicy: policyFromAnnotations(spec.annotations),
88
91
  policy: mine.get(t.name) ?? null,
89
92
  locked,
@@ -172,13 +172,7 @@ declare const UpdateBody: z.ZodObject<{
172
172
  disabled: "disabled";
173
173
  enabled: "enabled";
174
174
  }>>;
175
- defaultPolicy: z.ZodOptional<z.ZodEnum<{
176
- allow: "allow";
177
- ask: "ask";
178
- deny: "deny";
179
- }>>;
180
175
  }, z.core.$strict>>>;
181
- allowUnannotated: z.ZodOptional<z.ZodBoolean>;
182
176
  useForGit: z.ZodOptional<z.ZodBoolean>;
183
177
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
184
178
  endpoint: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
@@ -176,8 +176,7 @@ export declare const ConnectorPreviewSchema: z.ZodObject<{
176
176
  credential: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
177
177
  }, z.core.$strict>;
178
178
  /**
179
- * `PATCH …/connectors/:connectorId`: rename, switch on or off, per-tool state and default policy,
180
- * every unannotated tool to allow, and git use. No endpoint and no credential.
179
+ * `PATCH …/connectors/:connectorId`: rename, switch on or off, per-tool availability and git use. No endpoint and no credential.
181
180
  */
182
181
  export declare const ConnectorUpdateSchema: z.ZodObject<{
183
182
  name: z.ZodOptional<z.ZodString>;
@@ -190,13 +189,7 @@ export declare const ConnectorUpdateSchema: z.ZodObject<{
190
189
  disabled: "disabled";
191
190
  enabled: "enabled";
192
191
  }>>;
193
- defaultPolicy: z.ZodOptional<z.ZodEnum<{
194
- allow: "allow";
195
- ask: "ask";
196
- deny: "deny";
197
- }>>;
198
192
  }, z.core.$strict>>>;
199
- allowUnannotated: z.ZodOptional<z.ZodBoolean>;
200
193
  useForGit: z.ZodOptional<z.ZodBoolean>;
201
194
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
202
195
  endpoint: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;