@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
@@ -7,7 +7,7 @@ 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 { UI_CONTRIBUTION_KEY_RE } from "@capybara-hq/plugin-sdk";
10
+ import { narrowerProjectReach, UI_CONTRIBUTION_KEY_RE, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Module, Optional } from "@nestjs/common";
12
12
  import { ModuleRef } from "@nestjs/core";
13
13
  import { z } from "zod";
@@ -23,10 +23,10 @@ import { TransactionHost, withOrderedLocks } from "../infra/database/transaction
23
23
  import { Transactional } from "../infra/database/transactional.decorator.js";
24
24
  import { KERNEL_LOGGER } from "../infra/tokens.js";
25
25
  import { hostGrantable, hostGrantCeiling, } from "../sandbox/device-sandbox.js";
26
- import { OrgDeviceSandboxStoredSchema, readDeviceSandboxSettingsView, } from "../sandbox/device-sandbox-settings.js";
26
+ import { AllowedProfilesSchema, effectiveAllowedProfiles, effectiveProjectReach, OrgDeviceSandboxStoredSchema, ProjectReachSchema, readDeviceSandboxSettingsView, } from "../sandbox/device-sandbox-settings.js";
27
27
  import { coversHost, orgCloudMode, orgEffectiveHosts, orgHostOutsideCeiling, } from "../sandbox/modes.js";
28
28
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
29
- import { devicesFollowingDefault, hostsNarrowed, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
29
+ import { devicesFollowingDefault, hostsNarrowed, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "../sandbox/permission-ceiling-writes.js";
30
30
  import { readExternalSharing, readShareMaxExpiry, } from "../shares/settings.js";
31
31
  import { assertThemeOnIn } from "../themes/theme-state.js";
32
32
  import { IanaTimeZone } from "../time-zone.js";
@@ -42,9 +42,6 @@ import { can } from "./roles.js";
42
42
  * (D11, default on).
43
43
  * - `locale`: the org's default language (`zh` / `en`, default en); the bot's fixed phrases in IM
44
44
  * follow it.
45
- * - `sandboxToolPolicy`: the default policy of the sandbox tools (M5 T8, default allow). With
46
- * `ask`, every tool but the read-only `Read` / `Glob` / `Grep` needs approval (read live at
47
- * execution). An invalid stored value reads as `ask` (narrower, never wider) and is logged.
48
45
  * - `wakeOnBackgroundTask`: the org's override of `runtime.wakeOnBackgroundTask` (absent follows
49
46
  * the deployment), see {@link effectiveWakeOnBackgroundTask}.
50
47
  * - `outsideSandbox`: whether devices of the org may be granted running a call outside their
@@ -94,16 +91,9 @@ export const OrgThemeSettingSchema = z
94
91
  /** The theme setting of an org that has none: follow the platform, personal picks allowed. */
95
92
  export const DEFAULT_ORG_THEME = { id: null, personal: "allowed" };
96
93
  const posInt = (max, def) => z.number().int().min(1).max(max).default(def).catch(def);
97
- /** A stored `forbiddenTools` entry worth keeping: a tool key of the length the PATCH accepts. */
98
- const isForbiddenToolEntry = (v) => typeof v === "string" && v.length >= 1 && v.length <= 200;
99
94
  /** A stored `eventSourcesOff` entry worth keeping: an extension name of the length the PATCH accepts. */
100
95
  const isEventSourceEntry = (v) => typeof v === "string" && v.length >= 1 && v.length <= 214;
101
- /**
102
- * Org settings of automations (spec §9); every field reads leniently (invalid = default,
103
- * except `forbiddenTools`, which keeps its valid entries). A stored `forbiddenTools` that is not a
104
- * list (or a group that is not an object) reads as `[]` here, for display; enforcement checks
105
- * {@link invalidStoredForbiddenTools} and fails unattended runs instead (never wider).
106
- */
96
+ /** Organization automation settings with per-field defaults. */
107
97
  export const AutomationsSettingsSchema = z.object({
108
98
  enabled: z.boolean().default(true).catch(true),
109
99
  minIntervalMinutes: posInt(1_000_000, 60),
@@ -129,15 +119,10 @@ export const AutomationsSettingsSchema = z.object({
129
119
  eventSourcesOff: z
130
120
  .preprocess((v) => (Array.isArray(v) ? v.filter(isEventSourceEntry).slice(0, 200) : v), z.array(z.string()).max(200).default([]))
131
121
  .catch([]),
132
- // fail-safe: an invalid entry is dropped, the valid ones stay forbidden (never reset to []);
133
- // past the PATCH's 500 the list is truncated
134
- forbiddenTools: z
135
- .preprocess((v) => (Array.isArray(v) ? v.filter(isForbiddenToolEntry).slice(0, 500) : v), z.array(z.string()).max(500).default([]))
136
- .catch([]),
137
122
  });
138
123
  /**
139
124
  * The PATCH form: a partial merge into the group (fields left out keep their stored value; see
140
- * `OrgSettingsService.update`). A field given replaces that field whole, `forbiddenTools` too.
125
+ * `OrgSettingsService.update`). A supplied field replaces that field.
141
126
  */
142
127
  export const AutomationsPatchSchema = z
143
128
  .object({
@@ -155,7 +140,6 @@ export const AutomationsPatchSchema = z
155
140
  maxEventRunsPerSubjectPerHour: z.number().int().min(1).max(1_000_000),
156
141
  directedDefault: z.enum(["auto", "confirm", "off"]),
157
142
  eventSourcesOff: z.array(z.string().min(1).max(214)).max(200),
158
- forbiddenTools: z.array(z.string().min(1).max(200)).max(500),
159
143
  })
160
144
  .partial()
161
145
  .strict();
@@ -206,9 +190,10 @@ export const OrgSettingsSchema = z.object({
206
190
  toolSearch: z.enum(["on", "off"]).default("on").catch("on"),
207
191
  locale: z.enum(["zh", "en"]).default("en").catch("en"),
208
192
  /** Absent = `allow`; an invalid stored value reads as `ask` (narrower, never wider). */
209
- sandboxToolPolicy: z.enum(["allow", "ask"]).default("allow").catch("ask"),
210
193
  platformTool: z.enum(["on", "read-only", "off"]).default("on").catch("on"),
211
194
  /** The org's outside-sandbox ceiling; absent follows the platform. */
195
+ allowedProfiles: OrgDeviceSandboxStoredSchema.shape.allowedProfiles,
196
+ projectReach: OrgDeviceSandboxStoredSchema.shape.projectReach,
212
197
  outsideSandbox: OrgDeviceSandboxStoredSchema.shape.outsideSandbox,
213
198
  /** The org's device sandbox network; absent follows the platform. */
214
199
  deviceNetwork: OrgDeviceSandboxStoredSchema.shape.deviceNetwork,
@@ -246,19 +231,15 @@ export const OrgSettingsSchema = z.object({
246
231
  */
247
232
  promptSuggestions: PromptSuggestionsSetting.optional().catch("off"),
248
233
  });
249
- /** {@link OrgSettingsView} of `settings`, flagged from the stored value `raw`. */
250
- const viewOf = (settings, raw) => invalidStoredForbiddenTools(raw)
251
- ? {
252
- ...settings,
253
- automations: { ...settings.automations, forbiddenToolsUnreadable: true },
254
- }
255
- : settings;
234
+ export const OrgSecurityCeilingsPatchSchema = z.object({
235
+ allowedProfiles: AllowedProfilesSchema.nullable().optional(),
236
+ projectReach: ProjectReachSchema.nullable().optional(),
237
+ });
256
238
  /** PATCH 体:只改给出的字段;未知字段 → 400。 */
257
239
  export const OrgSettingsPatchSchema = z
258
240
  .object({
259
241
  toolSearch: z.enum(["on", "off"]).optional(),
260
242
  locale: z.enum(["zh", "en"]).optional(),
261
- sandboxToolPolicy: z.enum(["allow", "ask"]).optional(),
262
243
  platformTool: z.enum(["on", "read-only", "off"]).optional(),
263
244
  /**
264
245
  * The org's default device provider; null clears it (follow the platform). A provider that is
@@ -349,55 +330,9 @@ export async function readStoredOrgSettings(db, orgId) {
349
330
  .executeTakeFirst();
350
331
  return row?.settings;
351
332
  }
352
- /**
353
- * Reads the org settings (live from PG every time, so a change applies at once across replicas);
354
- * a missing or deleted org reads as the defaults. With `log`, an
355
- * unreadable security setting ({@link logUnreadableSecuritySettings}) is logged.
356
- */
357
- export async function readOrgSettings(db, orgId,
358
- /** Per-call paths (the tool policy) log at debug; the settings reads and the fire warn. */
359
- log) {
360
- const raw = await readStoredOrgSettings(db, orgId);
361
- if (log !== undefined) {
362
- logUnreadableSecuritySettings((msg, f) => log.debug(msg, f), orgId, raw);
363
- }
364
- return parseOrgSettings(raw);
365
- }
366
- /** Whether a stored settings object holds a `sandboxToolPolicy` this version reads as `ask`. */
367
- export function invalidStoredSandboxToolPolicy(raw) {
368
- const v = asObject(raw).sandboxToolPolicy;
369
- return v !== undefined && !OrgSettingsPatchSchema.shape.sandboxToolPolicy.safeParse(v).success;
370
- }
371
- /**
372
- * Whether the stored automation `forbiddenTools` cannot be read: the group or the field is
373
- * present but not an object / a list. Unattended runs of such an org fail
374
- * ({@link FORBIDDEN_TOOLS_UNREADABLE_ERROR}) rather than run with nothing forbidden. Invalid
375
- * entries inside a list are dropped instead (the valid ones stay forbidden).
376
- */
377
- export function invalidStoredForbiddenTools(raw) {
378
- const group = asObject(raw).automations;
379
- if (group === undefined)
380
- return false;
381
- if (group === null || typeof group !== "object" || Array.isArray(group))
382
- return true;
383
- const v = group.forbiddenTools;
384
- return v !== undefined && !Array.isArray(v);
385
- }
386
- /** The refusal of an unattended run of an org whose `forbiddenTools` cannot be read. */
387
- export const FORBIDDEN_TOOLS_UNREADABLE_ERROR = "The organization's forbidden tool list for automations is unreadable, so this scheduled run cannot continue; an org admin must save the list again in the organization's automation settings.";
388
- /** The refusal of a new task grant while the org's `forbiddenTools` cannot be read. */
389
- export const FORBIDDEN_TOOLS_UNREADABLE_GRANT_ERROR = "The organization's forbidden tool list for automations is unreadable, so no tool can be approved for a task now; an org admin must save the list again in the organization's automation settings.";
390
- /**
391
- * Logs (through `log`, at the caller's level) the security settings a stored value reads narrower
392
- * than written, with the org id.
393
- */
394
- export function logUnreadableSecuritySettings(log, orgId, raw) {
395
- if (invalidStoredSandboxToolPolicy(raw)) {
396
- log("org settings: stored sandboxToolPolicy is invalid; it reads as ask", { orgId });
397
- }
398
- if (invalidStoredForbiddenTools(raw)) {
399
- log("org settings: stored automations.forbiddenTools is unreadable; unattended runs fail until an org admin saves it again", { orgId });
400
- }
333
+ /** Reads the org settings live; a missing or deleted org reads as the defaults. */
334
+ export async function readOrgSettings(db, orgId) {
335
+ return parseOrgSettings(await readStoredOrgSettings(db, orgId));
401
336
  }
402
337
  const outsideSandboxNotAllowed = (message) => new ApiError("org.outside_sandbox_not_allowed", message);
403
338
  const networkNotAllowed = (message, field) => new ApiError("org.network_not_allowed", message, [{ path: `deviceNetwork.${field}` }]);
@@ -496,9 +431,7 @@ let OrgSettingsService = class OrgSettingsService {
496
431
  this.log = log;
497
432
  this.modules = modules;
498
433
  }
499
- /** Parses stored settings, warning when an invalid `outsideSandbox` narrows to `off`, an
500
- * invalid `deviceNetwork` to an empty allowlist, or a security setting reads narrower
501
- * ({@link logUnreadableSecuritySettings}, warn). */
434
+ /** Parses stored settings and warns when malformed network or capability fields narrow. */
502
435
  parseStored(orgId, raw) {
503
436
  if (invalidStoredOutsideSandbox(raw)) {
504
437
  this.log?.warn("org settings: stored outsideSandbox is invalid; it reads as off", { orgId });
@@ -516,9 +449,6 @@ let OrgSettingsService = class OrgSettingsService {
516
449
  orgId,
517
450
  });
518
451
  }
519
- const log = this.log;
520
- if (log !== undefined)
521
- logUnreadableSecuritySettings((m, f) => log.warn(m, f), orgId, raw);
522
452
  return parseOrgSettings(raw);
523
453
  }
524
454
  /** The deployment defaults (what "follow the platform" means on the settings page). */
@@ -535,6 +465,8 @@ let OrgSettingsService = class OrgSettingsService {
535
465
  ]);
536
466
  return {
537
467
  outsideSandbox: deviceSandbox.outsideSandbox,
468
+ allowedProfiles: deviceSandbox.allowedProfiles,
469
+ projectReach: deviceSandbox.projectReach,
538
470
  deviceNetwork: {
539
471
  ...deviceSandbox.network,
540
472
  allowHosts: [...lim.allowHosts],
@@ -550,6 +482,58 @@ let OrgSettingsService = class OrgSettingsService {
550
482
  promptSuggestions,
551
483
  };
552
484
  }
485
+ async securityCeilings(orgId) {
486
+ const [settings, platform] = await Promise.all([
487
+ this.get(orgId),
488
+ readDeviceSandboxSettingsView(this.db.db, this.config, this.log),
489
+ ]);
490
+ return {
491
+ allowedProfiles: {
492
+ configured: settings.allowedProfiles ?? null,
493
+ platform: platform.allowedProfiles.value,
494
+ effective: effectiveAllowedProfiles(platform.allowedProfiles.value, settings.allowedProfiles),
495
+ source: platform.allowedProfiles.source,
496
+ },
497
+ projectReach: {
498
+ configured: settings.projectReach ?? null,
499
+ platform: platform.projectReach.ceiling,
500
+ effective: effectiveProjectReach(platform.projectReach.ceiling, settings.projectReach),
501
+ source: platform.projectReach.source.ceiling,
502
+ limitingLayer: settings.projectReach !== undefined &&
503
+ narrowerProjectReach(platform.projectReach.ceiling, settings.projectReach) !==
504
+ platform.projectReach.ceiling
505
+ ? "org"
506
+ : "platform",
507
+ },
508
+ };
509
+ }
510
+ async updateSecurityCeilingsLocked(orgId, patch, actor, token, onlyNarrows, auditDetail) {
511
+ if (patch.allowedProfiles === undefined && patch.projectReach === undefined)
512
+ return;
513
+ const before = await this.securityCeilings(orgId);
514
+ const nextProfiles = patch.allowedProfiles ?? before.allowedProfiles.platform;
515
+ const nextReach = patch.projectReach ?? before.projectReach.platform;
516
+ if (patch.allowedProfiles?.some((profile) => !before.allowedProfiles.platform.includes(profile)) ||
517
+ (patch.projectReach != null &&
518
+ narrowerProjectReach(patch.projectReach, before.projectReach.platform) !==
519
+ patch.projectReach))
520
+ throw new ApiError("org.security_ceiling_not_allowed", "The organization security settings exceed the platform ceiling");
521
+ if (onlyNarrows &&
522
+ ((patch.allowedProfiles !== undefined &&
523
+ nextProfiles.some((profile) => !before.allowedProfiles.effective.includes(profile))) ||
524
+ (patch.projectReach !== undefined &&
525
+ narrowerProjectReach(nextReach, before.projectReach.effective) !== nextReach)))
526
+ throw new ApiError("org.security_widening_not_allowed", "Open /settings/security on the web to widen the organization security settings");
527
+ await this.updateIn(orgId, patch, actor, token, auditDetail, undefined);
528
+ if (patch.allowedProfiles !== undefined)
529
+ await this.ceilings.reconcileAllowedProfilesLocked({ orgId }, "org", before.allowedProfiles.effective, nextProfiles);
530
+ const previousReach = before.projectReach.effective;
531
+ const reachChanged = patch.projectReach !== undefined && nextReach !== previousReach;
532
+ const reachTightened = narrowerProjectReach(previousReach, nextReach) !== previousReach;
533
+ if (reachChanged) {
534
+ await this.ceilings.publishLocked({ orgId }, "org", (scope) => reachTightened && reachNarrowed(scope, nextReach), !reachTightened, reachTightened);
535
+ }
536
+ }
553
537
  /** Whether prompt suggestions run for the org now: one read of the platform and of the org. */
554
538
  async promptSuggestionsEnabled(orgId) {
555
539
  const [platform, row] = await Promise.all([
@@ -617,7 +601,7 @@ let OrgSettingsService = class OrgSettingsService {
617
601
  .executeTakeFirst();
618
602
  if (!row)
619
603
  throw new ApiError("org.not_found", "Organization not found");
620
- return viewOf(this.parseStored(orgId, row.settings), row.settings);
604
+ return this.parseStored(orgId, row.settings);
621
605
  }
622
606
  /**
623
607
  * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
@@ -796,6 +780,10 @@ let OrgSettingsService = class OrgSettingsService {
796
780
  if (Object.keys(after.uiArrangement).length === 0)
797
781
  delete after.uiArrangement;
798
782
  }
783
+ if (after.allowedProfiles === undefined)
784
+ delete after.allowedProfiles;
785
+ if (after.projectReach === undefined)
786
+ delete after.projectReach;
799
787
  if (after.outsideSandbox === undefined)
800
788
  delete after.outsideSandbox;
801
789
  if (after.deviceNetwork === undefined)
@@ -829,28 +817,20 @@ let OrgSettingsService = class OrgSettingsService {
829
817
  delete after.externalSharing;
830
818
  if (after.promptSuggestions === undefined)
831
819
  delete after.promptSuggestions;
832
- // saving an unreadable security setting writes it even when it equals what it read as
833
- const repairs = (invalidStoredForbiddenTools(stored) && patch.automations?.forbiddenTools !== undefined) ||
834
- (invalidStoredSandboxToolPolicy(stored) && patch.sandboxToolPolicy !== undefined);
835
- if (!repairs && sameSettings(before, after))
836
- return viewOf(before, stored);
820
+ if (sameSettings(before, after))
821
+ return before;
837
822
  // Lock order: the org row (orgLock above), then the theme's catalog item and its row FOR
838
823
  // SHARE (assertThemeOnIn), then the check, so no scope writer changes what it read first
839
824
  if (patch.theme?.id != null && patch.theme.id !== before.theme?.id) {
840
825
  await assertThemeOnIn(this.db.db, orgId, patch.theme.id);
841
826
  }
842
827
  // Preserve unknown settings and apply cleared optional fields.
843
- const { outsideSandbox: _oldOutside, deviceNetwork: _oldNetwork, deviceDefaultProvider: _oldDeviceProvider, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, navigation: _oldNavigation, automations: _oldAutomations, compaction: _oldCompaction, promptCache: _oldPromptCache, externalSharing: _oldExternalSharing, promptSuggestions: _oldPromptSuggestions, ...rest } = stored;
828
+ const { allowedProfiles: _oldProfiles, projectReach: _oldReach, outsideSandbox: _oldOutside, deviceNetwork: _oldNetwork, deviceDefaultProvider: _oldDeviceProvider, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, navigation: _oldNavigation, automations: _oldAutomations, compaction: _oldCompaction, promptCache: _oldPromptCache, externalSharing: _oldExternalSharing, promptSuggestions: _oldPromptSuggestions, ...rest } = stored;
844
829
  const written = { ...rest, ...after };
845
- // An unreadable forbiddenTools reads as [] for display only: a write that does not replace the
846
- // list keeps it unreadable (never healed to "nothing forbidden"); saving the list fixes it
847
- if (invalidStoredForbiddenTools(stored) && patch.automations?.forbiddenTools === undefined) {
848
- const group = asObject(stored.automations);
849
- written.automations = {
850
- ...after.automations,
851
- forbiddenTools: group.forbiddenTools ?? null,
852
- };
853
- }
830
+ written.automations =
831
+ patch.automations === undefined && Object.hasOwn(stored, "automations")
832
+ ? stored.automations
833
+ : { ...asObject(stored.automations), ...after.automations };
854
834
  await this.db
855
835
  .updateTable("orgs")
856
836
  .set({ settings: JSON.stringify(written) })
@@ -862,7 +842,7 @@ let OrgSettingsService = class OrgSettingsService {
862
842
  orgId,
863
843
  action: "org.settings_updated",
864
844
  target: orgId,
865
- detail: { before, after, ...(repairs && { repaired: true }), ...auditDetail },
845
+ detail: { before, after, ...auditDetail },
866
846
  });
867
847
  if (patch.outsideSandbox !== undefined || patch.deviceNetwork !== undefined) {
868
848
  // the consent reset follows the effective values as every reader sees them (re-read from
@@ -898,9 +878,12 @@ let OrgSettingsService = class OrgSettingsService {
898
878
  return hostsNarrowed(scope, row, orgHosts, (host) => hostGrantable(grantCeiling, host));
899
879
  }, resetConsent);
900
880
  }
901
- return viewOf(after, written);
881
+ return after;
902
882
  }
903
883
  };
884
+ __decorate([
885
+ Transactional({ propagation: "mandatory" })
886
+ ], OrgSettingsService.prototype, "updateSecurityCeilingsLocked", null);
904
887
  __decorate([
905
888
  Transactional({ propagation: "mandatory" })
906
889
  ], OrgSettingsService.prototype, "lockFor", null);
@@ -702,7 +702,7 @@ export const PLATFORM_EXCLUSIONS = [
702
702
  {
703
703
  route: "GET /api/v1/orgs/:orgId/tools/extensions",
704
704
  category: "internal",
705
- reason: "Display list of the agent form's tools picker; extensions.tools gives an agent the same facts",
705
+ reason: "Display list for the agent form's extension tool picker; org-security.get provides the policy catalog",
706
706
  },
707
707
  {
708
708
  route: "GET /api/v1/oauth/callback",
@@ -87,6 +87,10 @@ export const PLATFORM_DOMAINS = [
87
87
  id: "channels",
88
88
  description: "The org's channel connections (IM bots): list, read without credentials, change the binding, remove.",
89
89
  },
90
+ {
91
+ id: "org-security",
92
+ description: "Review and narrow organization tool rules and device security ceilings.",
93
+ },
90
94
  {
91
95
  id: "org-settings",
92
96
  description: "The org's settings (tool search, language, sandbox policy, the Platform tool switch, the default theme): read and change.",
@@ -47,6 +47,8 @@ const SettingsInput = DEPLOYMENT_SETTINGS_PATCH.pick({
47
47
  clientExtensions: true,
48
48
  devicesOutsideSandbox: true,
49
49
  devicesNetwork: true,
50
+ devicesAllowedProfiles: true,
51
+ devicesProjectReach: true,
50
52
  devicesDefaultProvider: true,
51
53
  attribution: true,
52
54
  externalSharing: true,
@@ -242,7 +244,7 @@ let AdminOperations = class AdminOperations {
242
244
  }),
243
245
  defineOperation({
244
246
  id: "admin.settings",
245
- description: "Read the deployment settings (super admin): who may create orgs (orgCreation), the price currency, whether orgs may create their own connectors and skills, whether org admins may browse the marketplaces, the per-org limit overrides keyed by org id (orgs.get reads one org's), the platform's device sandbox settings in effect (devicesOutsideSandbox: permission allowed or off, whether a device may be granted running a call outside its sandbox; devicesNetwork: default and ceiling, open for the public internet with private addresses closed or allowlist, the network a device gets and the widest an org or device may choose), devicesDefaultProvider (provider: the device provider extension that makes a person's default device, null for none), the platform's attribution defaults for agent-created git commits and pull requests (attribution: commit, pr, sessionUrl), file sharing (externalSharing: value allow or deny, whether orgs may turn on public links to conversation files; shareMaxExpiryDays: value, the longest expiry a share may take in days), htmlRenderCdnAllowlist (the https origins a rendered HTML file may load libraries, styles, fonts and images from) and promptSuggestions (on or off, absent meaning on: whether the composer suggests the person's next message after a completed run; an org's own promptSuggestions must be on too); the switches each with sources: env, file or nacos are set in the startup config and read-only, db chosen in the admin console, default.",
247
+ description: "Read the deployment settings (super admin): who may create orgs (orgCreation), the price currency, whether orgs may create their own connectors and skills, whether org admins may browse the marketplaces, the per-org limit overrides keyed by org id (orgs.get reads one org's), the platform's device sandbox settings in effect (devicesOutsideSandbox: permission allowed or off, whether a device may be granted running a call outside its sandbox; devicesNetwork: default and ceiling, open for the public internet with private addresses closed or allowlist, the network a device gets and the widest an org or device may choose), devicesAllowedProfiles ({ value }: profiles members may choose), devicesProjectReach ({ ceiling }: workspace, paths or machine), devicesDefaultProvider (provider: the device provider extension that makes a person's default device, null for none), the platform's attribution defaults for agent-created git commits and pull requests (attribution: commit, pr, sessionUrl), file sharing (externalSharing: value allow or deny, whether orgs may turn on public links to conversation files; shareMaxExpiryDays: value, the longest expiry a share may take in days), htmlRenderCdnAllowlist (the https origins a rendered HTML file may load libraries, styles, fonts and images from) and promptSuggestions (on or off, absent meaning on: whether the composer suggests the person's next message after a completed run; an org's own promptSuggestions must be on too); the switches each with sources: env, file or nacos are set in the startup config and read-only, db chosen in the admin console, default.",
246
248
  input: z.object({}).strict(),
247
249
  example: {},
248
250
  authz: { superAdmin: true },
@@ -252,7 +254,7 @@ let AdminOperations = class AdminOperations {
252
254
  }),
253
255
  defineOperation({
254
256
  id: "admin.update-settings",
255
- description: "Change deployment settings (super admin); give only the keys to change: orgCreation (anyone or super_admin), priceCurrency (ISO 4217 code), customConnectors / customSkills (allow or deny: whether orgs may create their own instead of installing from the catalog), orgMarketplaceBrowse (true or false), uiTheme ({ id }: the platform default theme, a platform theme whose scope is all, or null for the built-in theme; it is what every org falls back to and what the sign-in pages show), uiArrangement ({ <slot>: { hidden, order } } for a list slot, { <slot>: { use } } for a single slot: the platform default arrangement of UI slots, with contribution keys <extension>/<contribution>; hidden ones are not listed but still open by URL; use names the contribution that replaces the built-in, null for the built-in; null for a slot removes its entry), clientExtensions ({ enabled?, disabled? }: the kill switch of plugin client code; enabled false stops every plugin's interface code in every browser, disabled is the whole list of plugins whose interface code alone is stopped while their tools keep working; read the current list from admin.settings first), devicesOutsideSandbox ({ permission }: whether a device may be granted running a call outside its sandbox, allowed or off; null clears it back to the default, allowed; through this tool it may only be turned off, never allowed, and a value set in the startup config is read-only), devicesNetwork ({ default?, ceiling? }: the device sandbox network, open or allowlist; null clears a field back to the default, open; the default may not be above the ceiling; through this tool either may only be narrowed to allowlist, never opened, and a field set in the startup config is read-only), devicesDefaultProvider ({ provider }: the device provider extension that makes a person's default device; null clears it back to none; read-only when set in the startup config), attribution ({ commit?, pr?, sessionUrl? }: the platform's defaults for agent-created git commits and pull requests; null clears a field back to its default, an empty string turns that line off, and fields set in the startup config are read-only), externalSharing (allow or deny: whether orgs may turn on public links to conversation files; null clears it back to the default, deny; externalSharing may only be turned off through this tool, and a value set in the startup config is read-only), shareMaxExpiryDays (1 to 365: the longest expiry a share may take, in days; null clears it back to 30; through this tool it may only be lowered, never raised, and it is read-only when set in the startup config), htmlRenderCdnAllowlist (the whole list of https origins, scheme and host with an optional port and nothing else, that a rendered HTML file may load from; at most 50; through this tool origins may only be removed, never added, so read the current list from admin.settings first and send it without the ones to drop). promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; an org's own promptSuggestions must be on too) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; an org may override it) may be set either way. Per-org limits are orgs.set-limits.",
257
+ description: "Change deployment settings (super admin); give only the keys to change: orgCreation (anyone or super_admin), priceCurrency (ISO 4217 code), customConnectors / customSkills (allow or deny: whether orgs may create their own instead of installing from the catalog), orgMarketplaceBrowse (true or false), uiTheme ({ id }: the platform default theme, a platform theme whose scope is all, or null for the built-in theme; it is what every org falls back to and what the sign-in pages show), uiArrangement ({ <slot>: { hidden, order } } for a list slot, { <slot>: { use } } for a single slot: the platform default arrangement of UI slots, with contribution keys <extension>/<contribution>; hidden ones are not listed but still open by URL; use names the contribution that replaces the built-in, null for the built-in; null for a slot removes its entry), clientExtensions ({ enabled?, disabled? }: the kill switch of plugin client code; enabled false stops every plugin's interface code in every browser, disabled is the whole list of plugins whose interface code alone is stopped while their tools keep working; read the current list from admin.settings first), devicesOutsideSandbox ({ permission }: whether a device may be granted running a call outside its sandbox, allowed or off; null clears it back to the default, allowed; through this tool it may only be turned off, never allowed, and a value set in the startup config is read-only), devicesNetwork ({ default?, ceiling? }: the device sandbox network, open or allowlist; null clears a field back to the default, open; the default may not be above the ceiling; through this tool either may only be narrowed to allowlist, never opened, and a field set in the startup config is read-only), devicesAllowedProfiles ({ value }: choose a subset including request-approval), devicesProjectReach ({ ceiling }: workspace, paths or machine); these two may only narrow through this tool, null follows the default, and startup config is read-only. A super admin decides on wider profile or project reach ceilings in the web admin settings at /admin/settings. The other settings are devicesDefaultProvider ({ provider }: the device provider extension that makes a person's default device; null clears it back to none; read-only when set in the startup config), attribution ({ commit?, pr?, sessionUrl? }: the platform's defaults for agent-created git commits and pull requests; null clears a field back to its default, an empty string turns that line off, and fields set in the startup config are read-only), externalSharing (allow or deny: whether orgs may turn on public links to conversation files; null clears it back to the default, deny; externalSharing may only be turned off through this tool, and a value set in the startup config is read-only), shareMaxExpiryDays (1 to 365: the longest expiry a share may take, in days; null clears it back to 30; through this tool it may only be lowered, never raised, and it is read-only when set in the startup config), htmlRenderCdnAllowlist (the whole list of https origins, scheme and host with an optional port and nothing else, that a rendered HTML file may load from; at most 50; through this tool origins may only be removed, never added, so read the current list from admin.settings first and send it without the ones to drop). promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; an org's own promptSuggestions must be on too) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; an org may override it) may be set either way. Per-org limits are orgs.set-limits.",
256
258
  input: SettingsInput.refine((b) => Object.keys(b).length > 0, {
257
259
  message: "at least one setting is required",
258
260
  }),
@@ -268,6 +270,7 @@ let AdminOperations = class AdminOperations {
268
270
  "compaction",
269
271
  ],
270
272
  confirm: "platform",
273
+ noHandoff: "Widenings are refused before confirmation. A super admin makes a separate edit in web settings, where there is no pending operation to review.",
271
274
  errors: [
272
275
  {
273
276
  code: "validation_failed",
@@ -285,6 +288,10 @@ let AdminOperations = class AdminOperations {
285
288
  code: "deployment.external_sharing_not_allowed",
286
289
  next: "Through this tool external sharing may only be turned off (deny); to allow it, ask a super admin to change it in the admin console settings on the web.",
287
290
  },
291
+ {
292
+ code: "deployment.security_widen_not_allowed",
293
+ next: "Profile and project reach ceilings may only be narrowed through this tool. A super admin can widen them on the web at /admin/settings.",
294
+ },
288
295
  {
289
296
  code: "deployment.sharing_widen_not_allowed",
290
297
  next: "Through this tool shareMaxExpiryDays may only be lowered and htmlRenderCdnAllowlist may only lose origins (send the current list from admin.settings minus the ones to drop); to raise the maximum or add an origin, ask a super admin to change it in the admin console settings on the web.",
@@ -308,7 +315,10 @@ let AdminOperations = class AdminOperations {
308
315
  };
309
316
  }
310
317
  return precheckBy(async () => {
311
- if (i.devicesOutsideSandbox !== undefined || i.devicesNetwork !== undefined)
318
+ if (i.devicesOutsideSandbox !== undefined ||
319
+ i.devicesNetwork !== undefined ||
320
+ i.devicesAllowedProfiles !== undefined ||
321
+ i.devicesProjectReach !== undefined)
312
322
  await this.settings.checkDeviceSandbox(i, { onlyNarrows: true });
313
323
  if (i.devicesDefaultProvider !== undefined)
314
324
  this.settings.checkDefaultProvider(i.devicesDefaultProvider);
@@ -316,7 +326,7 @@ let AdminOperations = class AdminOperations {
316
326
  });
317
327
  },
318
328
  summary: async (i) => {
319
- const { uiTheme, uiArrangement, clientExtensions, devicesOutsideSandbox, devicesNetwork, devicesDefaultProvider, attribution, htmlRenderCdnAllowlist, promptCache, ...rest } = i;
329
+ const { uiTheme, uiArrangement, clientExtensions, devicesOutsideSandbox, devicesNetwork, devicesAllowedProfiles, devicesProjectReach, devicesDefaultProvider, attribution, htmlRenderCdnAllowlist, promptCache, ...rest } = i;
320
330
  const parts = Object.entries(rest).map(([k, v]) => `${k}=${String(v)}`);
321
331
  if (htmlRenderCdnAllowlist !== undefined) {
322
332
  parts.push(`htmlRenderCdnAllowlist=[${htmlRenderCdnAllowlist.join(", ")}]`);
@@ -329,6 +339,10 @@ let AdminOperations = class AdminOperations {
329
339
  if (devicesNetwork[field] !== undefined)
330
340
  parts.push(`devicesNetwork.${field}=${String(devicesNetwork[field])}`);
331
341
  }
342
+ if (devicesAllowedProfiles !== undefined)
343
+ parts.push(`devicesAllowedProfiles=${devicesAllowedProfiles.value?.join(", ") ?? "default"}`);
344
+ if (devicesProjectReach !== undefined)
345
+ parts.push(`devicesProjectReach=${devicesProjectReach.ceiling ?? "default"}`);
332
346
  if (devicesDefaultProvider !== undefined)
333
347
  parts.push(`devicesDefaultProvider=${String(devicesDefaultProvider.provider)}`);
334
348
  if (promptCache?.longTtl !== undefined)
@@ -44,7 +44,7 @@ const CreateInput = ConnectorCreateSchema.omit({ credential: true })
44
44
  /** `connectors.update`: the PATCH body without per-tool policies (ruling R4). */
45
45
  const UpdateInput = z
46
46
  .object({ connectorId: ConnectorId })
47
- .extend(ConnectorUpdateSchema.omit({ tools: true, allowUnannotated: true }).shape)
47
+ .extend(ConnectorUpdateSchema.omit({ tools: true }).shape)
48
48
  .strict();
49
49
  /** `connectors.add-from-template`: the route's name and its `config` flattened, no secrets. */
50
50
  const FromTemplateInput = z
@@ -492,7 +492,7 @@ let ConnectorsOperations = class ConnectorsOperations {
492
492
  authz: { orgAction: "connectors.manage" },
493
493
  mirrors: ["PATCH /api/v1/orgs/:orgId/connectors/:connectorId"],
494
494
  // per-tool policies decide what agents may call without asking (ruling R4)
495
- omits: ["tools", "allowUnannotated"],
495
+ omits: ["tools"],
496
496
  confirm: "org",
497
497
  errors: [
498
498
  { code: "connector.not_found", next: "Check the connector id with connectors.list." },
@@ -4,7 +4,6 @@ import { OrgExtensionConfigs } from "../../extensions/org-config.js";
4
4
  import { OrgOverrides, type OrgOverrideView } from "../../extensions/org-overrides.js";
5
5
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
6
6
  import { KernelDb } from "../../infra/database/kernel-db.js";
7
- import { OrgToolSwitches } from "../../tools/org-tool-switches.js";
8
7
  import { type PersonFieldTarget } from "../person-fields.js";
9
8
  import { PlatformOperations } from "../registry.js";
10
9
  /**
@@ -25,10 +24,9 @@ export declare class ExtensionsOperations implements OnModuleInit {
25
24
  private readonly configs;
26
25
  private readonly displayNames;
27
26
  private readonly kdb;
28
- private readonly switches;
29
27
  private readonly pointDefaults;
30
28
  private readonly overrides;
31
- constructor(registry: PlatformOperations, configs: OrgExtensionConfigs, displayNames: ExtensionDisplayNames, kdb: KernelDb, switches: OrgToolSwitches, pointDefaults: ExtensionPointDefaults, overrides: OrgOverrides);
29
+ constructor(registry: PlatformOperations, configs: OrgExtensionConfigs, displayNames: ExtensionDisplayNames, kdb: KernelDb, pointDefaults: ExtensionPointDefaults, overrides: OrgOverrides);
32
30
  /**
33
31
  * Why `extensions.set-enabled` refuses the switch before writing, or null: switching on needs the
34
32
  * extension's plugin installed in the org; a required or builtin one cannot go off. The write