@capybara-hq/kernel 0.1.0-rc.127 → 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 (122) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +14 -0
  3. package/dist/agents/readiness.service.d.ts +6 -0
  4. package/dist/agents/readiness.service.js +1 -1
  5. package/dist/automations/automations.service.js +15 -21
  6. package/dist/automations/effective-settings.d.ts +3 -9
  7. package/dist/automations/effective-settings.js +3 -5
  8. package/dist/automations/fire.js +0 -11
  9. package/dist/automations/grant-rules.d.ts +7 -10
  10. package/dist/automations/grant-rules.js +9 -18
  11. package/dist/automations/unattended.d.ts +1 -4
  12. package/dist/automations/unattended.js +0 -2
  13. package/dist/catalog/catalog-items.d.ts +7 -4
  14. package/dist/catalog/catalog-items.js +8 -7
  15. package/dist/catalog/catalog-scope.service.d.ts +3 -2
  16. package/dist/catalog/catalog-scope.service.js +5 -4
  17. package/dist/catalog/org-extension.controller.d.ts +1 -20
  18. package/dist/catalog/org-extension.controller.js +1 -48
  19. package/dist/catalog/org-extension.schemas.d.ts +1 -9
  20. package/dist/catalog/org-extension.schemas.js +1 -17
  21. package/dist/config/schema.d.ts +12 -0
  22. package/dist/config/schema.js +16 -0
  23. package/dist/conversations/approval-profile.d.ts +8 -1
  24. package/dist/conversations/approval-profile.js +20 -0
  25. package/dist/conversations/conversations.service.d.ts +1 -1
  26. package/dist/conversations/conversations.service.js +8 -3
  27. package/dist/conversations/events.d.ts +25 -1
  28. package/dist/conversations/events.js +7 -2
  29. package/dist/conversations/permission-profiles.controller.d.ts +4 -0
  30. package/dist/conversations/permission-profiles.schemas.d.ts +5 -0
  31. package/dist/conversations/permission-profiles.schemas.js +8 -0
  32. package/dist/conversations/permission-profiles.service.d.ts +8 -1
  33. package/dist/conversations/permission-profiles.service.js +13 -1
  34. package/dist/db/kernel-schema.d.ts +21 -0
  35. package/dist/device-access/device-access.service.d.ts +4 -1
  36. package/dist/device-access/device-access.service.js +26 -7
  37. package/dist/device-access/viewer.d.ts +3 -1
  38. package/dist/device-access/viewer.js +18 -9
  39. package/dist/errors.d.ts +6 -0
  40. package/dist/errors.js +6 -0
  41. package/dist/extensions/admin-view.d.ts +1 -3
  42. package/dist/extensions/admin-view.js +5 -8
  43. package/dist/git/gateway.d.ts +8 -1
  44. package/dist/git/gateway.js +68 -11
  45. package/dist/git/git.module.d.ts +2 -3
  46. package/dist/git/git.module.js +4 -4
  47. package/dist/http/api.module.js +3 -3
  48. package/dist/identity/settings.d.ts +20 -5
  49. package/dist/identity/settings.js +52 -9
  50. package/dist/infra/config/kernel-config.service.js +4 -0
  51. package/dist/orgs/orgs.module.js +12 -1
  52. package/dist/orgs/orgs.schemas.js +3 -0
  53. package/dist/orgs/security-settings.service.d.ts +94 -0
  54. package/dist/orgs/security-settings.service.js +223 -0
  55. package/dist/orgs/settings.controller.d.ts +33 -0
  56. package/dist/orgs/settings.controller.js +41 -1
  57. package/dist/orgs/settings.service.d.ts +48 -63
  58. package/dist/orgs/settings.service.js +86 -103
  59. package/dist/platform/exclusions.js +1 -1
  60. package/dist/platform/operation.js +4 -0
  61. package/dist/platform/ops/admin.ops.js +18 -4
  62. package/dist/platform/ops/agents.ops.js +1 -1
  63. package/dist/platform/ops/connectors.ops.js +2 -2
  64. package/dist/platform/ops/extensions.ops.d.ts +1 -3
  65. package/dist/platform/ops/extensions.ops.js +4 -131
  66. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  67. package/dist/platform/ops/org-settings.ops.js +76 -3
  68. package/dist/platform/ops/orgs.ops.js +2 -0
  69. package/dist/runtime/context/permission-profile.js +6 -0
  70. package/dist/runtime/subagents/dispatch.d.ts +3 -0
  71. package/dist/runtime/subagents/dispatch.js +2 -1
  72. package/dist/runtime/subagents/messages.d.ts +3 -1
  73. package/dist/runtime/subagents/messages.js +9 -6
  74. package/dist/sandbox/device-sandbox-settings.d.ts +55 -1
  75. package/dist/sandbox/device-sandbox-settings.js +64 -1
  76. package/dist/sandbox/device-sandbox.d.ts +9 -1
  77. package/dist/sandbox/device-sandbox.js +17 -2
  78. package/dist/sandbox/device-services.d.ts +26 -3
  79. package/dist/sandbox/device-services.js +95 -16
  80. package/dist/sandbox/loopback-grant-records.d.ts +3 -2
  81. package/dist/sandbox/loopback-grant-records.js +32 -5
  82. package/dist/sandbox/operation-authority.d.ts +3 -2
  83. package/dist/sandbox/operation-authority.js +21 -1
  84. package/dist/sandbox/operation-intents.js +5 -1
  85. package/dist/sandbox/permission-call-types.d.ts +2 -1
  86. package/dist/sandbox/permission-ceiling-writes.d.ts +14 -5
  87. package/dist/sandbox/permission-ceiling-writes.js +122 -13
  88. package/dist/sandbox/permission-config-publication.d.ts +10 -0
  89. package/dist/sandbox/permission-config-publication.js +27 -5
  90. package/dist/sandbox/permission-facts.d.ts +21 -2
  91. package/dist/sandbox/permission-facts.js +101 -9
  92. package/dist/sandbox/permission-transitions.d.ts +1 -1
  93. package/dist/sandbox/sandbox.service.d.ts +2 -2
  94. package/dist/sandbox/sandbox.service.js +7 -3
  95. package/dist/tools/admin-connectors.js +2 -2
  96. package/dist/tools/approvals.service.d.ts +7 -2
  97. package/dist/tools/approvals.service.js +39 -7
  98. package/dist/tools/builtin-names.d.ts +0 -6
  99. package/dist/tools/builtin-names.js +0 -11
  100. package/dist/tools/builtins/sandbox/index.d.ts +3 -5
  101. package/dist/tools/builtins/sandbox/index.js +3 -5
  102. package/dist/tools/connector-account-policies.js +7 -4
  103. package/dist/tools/connectors.controller.d.ts +0 -6
  104. package/dist/tools/connectors.schemas.d.ts +1 -8
  105. package/dist/tools/connectors.schemas.js +1 -4
  106. package/dist/tools/connectors.service.d.ts +3 -7
  107. package/dist/tools/connectors.service.js +29 -44
  108. package/dist/tools/drift.js +12 -4
  109. package/dist/tools/git-push-policy.d.ts +1 -4
  110. package/dist/tools/git-push-policy.js +4 -5
  111. package/dist/tools/org-tool-policies.d.ts +24 -0
  112. package/dist/tools/org-tool-policies.js +113 -0
  113. package/dist/tools/org-tool-switches.d.ts +5 -70
  114. package/dist/tools/org-tool-switches.js +13 -141
  115. package/dist/tools/pipeline.d.ts +11 -5
  116. package/dist/tools/pipeline.js +173 -38
  117. package/dist/tools/policy.d.ts +3 -7
  118. package/dist/tools/policy.js +29 -48
  119. package/dist/tools/registry.d.ts +5 -0
  120. package/dist/tools/registry.js +44 -13
  121. package/package.json +1 -1
  122. package/src/migrations/0212_org_security_policy.sql +234 -0
@@ -4,10 +4,10 @@ import { grantRefusalOf } from "../automations/grant-rules.js";
4
4
  import { findTaskGrant } from "../automations/store.js";
5
5
  import { changesAgentSkills, UNATTENDED_ASK_ERROR, UNATTENDED_FIXED_ASK_ERROR, UNATTENDED_QUESTION_ERROR, unattendedRules, } from "../automations/unattended.js";
6
6
  import { roleAtLeast } from "../orgs/roles.js";
7
- import { FORBIDDEN_TOOLS_UNREADABLE_ERROR, readOrgSettings } from "../orgs/settings.service.js";
8
- import { BUILTIN, SANDBOX_ASK_TOOL_NAMES } from "./builtin-names.js";
7
+ import { BUILTIN } from "./builtin-names.js";
9
8
  import { personalAuth } from "./connector-account-policies.js";
10
9
  import { isFixedAsk } from "./fixed-ask.js";
10
+ import { readOrgToolPolicy } from "./org-tool-policies.js";
11
11
  export { R3_FIXED_ASK_TOOL_KEYS } from "./builtin-names.js";
12
12
  export { isFixedAsk } from "./fixed-ask.js";
13
13
  const RANK = { allow: 0, ask: 1, deny: 2 };
@@ -75,7 +75,7 @@ export function connectorPolicy(input) {
75
75
  }
76
76
  /**
77
77
  * 执行时的策略判定(spec 3.6 R5:在动作执行那一刻判定)。每次调用都实时读取:
78
- * - 沙箱工具(bash / write / edit / deliver)的组织设置 `sandboxToolPolicy`(为 ask 时组织默认至少 ask);
78
+ * - The organization’s live tool and per-call ceilings; a fixed organization ask needs a human.
79
79
  * - 连接器工具的 `connector_tools.default_policy` / 状态 / 指纹(连接器或工具已不存在、停用、删除、待审核 →
80
80
  * `{ unavailable: 原因 }`,管线写「工具不可用」的事实说明,而非策略拒绝);
81
81
  * - agent 当前版本的 `toolPolicies`,与运行所用版本取更严者(负责人运行中收紧立即生效;放宽不影响已在跑的运行);
@@ -93,8 +93,7 @@ export function connectorPolicy(input) {
93
93
  * 结果为 `ask` 时返回审批请求,默认指向发起人本人;记住的授权把 `ask` 放行时返回 `{ grant }`(按 allow 执行)。
94
94
  *
95
95
  * An unattended run (`ctx.unattended`, not a trial run; scheduled tasks spec §7):
96
- * - a tool in the org's `forbiddenTools` (by tool key or per-call key) is denied; when the stored
97
- * list cannot be read every call is refused (`FORBIDDEN_TOOLS_UNREADABLE_ERROR`);
96
+ * - the unattended column further narrows the organization’s general tool ceiling;
98
97
  * - a Platform call that changes the agent's skills (`agents.register-skill`, ...) is an ask no
99
98
  * grant covers, even on a private agent where it would run without asking;
100
99
  * - an ask is also allowed by a task grant of the current definition (`{ grant: "task" }`), never
@@ -107,14 +106,13 @@ export function connectorPolicy(input) {
107
106
  * the ask (profiles govern every approval, R5): the pipeline asks for their values in a secure
108
107
  * input request after the consent. The pipeline refuses both before this in an unattended run.
109
108
  */
110
- export function createDecidePolicy(db,
111
- /** Logs (debug: once per call) when an org's stored security setting is unreadable. */
112
- log) {
109
+ export function createDecidePolicy(db) {
113
110
  return async (tool, agentDef, ctx) => {
114
111
  // a per-call policy (Platform tool spec §6.2): its key replaces the tool key for policies,
115
112
  // grants and approvals, and its policy replaces the tool's default
116
113
  const call = ctx.callPolicy ?? null;
117
114
  const policyKey = call?.key ?? tool.key;
115
+ const unattended = unattendedRules(ctx.unattended) ? ctx.unattended : undefined;
118
116
  let connectorDefault = call?.policy ?? tool.defaultPolicy;
119
117
  let connectorId = null;
120
118
  let hashCurrent = true;
@@ -139,7 +137,7 @@ log) {
139
137
  return { unavailable: `App ${app.slug} is disabled` };
140
138
  const row = await db
141
139
  .selectFrom("connector_tools")
142
- .select(["default_policy", "spec_hash", "status", "missing_since"])
140
+ .select(["default_policy", "declaration_policy", "spec_hash", "status", "missing_since"])
143
141
  .where("connector_id", "=", tool.source.connectorId)
144
142
  .where("name", "=", tool.source.name)
145
143
  .executeTakeFirst();
@@ -150,7 +148,7 @@ log) {
150
148
  return { unavailable: "Tool is disabled" };
151
149
  if (row.status !== "enabled")
152
150
  return { unavailable: "Tool is pending review" };
153
- connectorDefault = row.default_policy;
151
+ connectorDefault = row.declaration_policy ?? row.default_policy;
154
152
  hashCurrent = row.spec_hash === tool.specHash;
155
153
  // The call is made with the acting account's own connection (the credential the pipeline
156
154
  // injects for `ctx.accountId`): that account's settings apply, never another's
@@ -167,30 +165,12 @@ log) {
167
165
  memberSetting = mine?.policy;
168
166
  }
169
167
  }
170
- // scheduled tasks spec §7: what an unattended run may not do at all
171
- const unattended = unattendedRules(ctx.unattended) ? ctx.unattended : undefined;
172
- if (unattended !== undefined) {
173
- // fail closed: an unreadable list never runs as "nothing forbidden"
174
- if (unattended.forbiddenToolsUnreadable === true) {
175
- return { refused: FORBIDDEN_TOOLS_UNREADABLE_ERROR };
176
- }
177
- const forbidden = unattended.forbiddenTools;
178
- if (forbidden.includes(tool.key) || forbidden.includes(policyKey))
179
- return "deny";
180
- if (unattended.unattendedAsk === "fail" &&
181
- tool.source.kind === "builtin" &&
182
- tool.key === BUILTIN.AskUserQuestion) {
183
- return { refused: UNATTENDED_QUESTION_ERROR };
184
- }
185
- }
186
- // 沙箱工具的组织默认(M5 T8):组织设置 sandboxToolPolicy 为 ask 时,有副作用的沙箱工具至少 ask
187
- // `orgAsk`: the org setting, not the tool's own default, is what makes it ask
188
- let orgAsk = false;
189
- if (tool.source.kind === "builtin" && SANDBOX_ASK_TOOL_NAMES.has(tool.source.name)) {
190
- if ((await readOrgSettings(db, ctx.orgId, log)).sandboxToolPolicy === "ask") {
191
- orgAsk = connectorDefault === "allow";
192
- connectorDefault = stricter(connectorDefault, "ask");
193
- }
168
+ const orgPolicy = await readOrgToolPolicy(db, ctx.orgId, tool.key, policyKey, unattended !== undefined);
169
+ if (orgPolicy.policy === "deny")
170
+ return "deny";
171
+ const orgAsk = orgPolicy.policy === "ask";
172
+ if (unattended?.unattendedAsk === "fail" && tool.key === BUILTIN.AskUserQuestion) {
173
+ return { refused: UNATTENDED_QUESTION_ERROR };
194
174
  }
195
175
  // 运行所用版本可能是加 toolPolicies 字段之前保存的:缺省为空
196
176
  const runSetting = settingOf(agentDef.toolPolicies, tool.key, policyKey);
@@ -258,7 +238,8 @@ log) {
258
238
  changesAgentSkills(policyKey);
259
239
  // a call only the person may confirm (its result is shown to them once, R6) asks every time,
260
240
  // outside every grant, and no agent `allow` lifts it
261
- const fixedAsk = unattendedSkillChange ||
241
+ const fixedAsk = orgAsk ||
242
+ unattendedSkillChange ||
262
243
  call?.personOnly === true ||
263
244
  isFixedAsk(tool) ||
264
245
  (call !== null && !call.remember && (call.policy !== "allow" || agentOverride !== undefined));
@@ -296,7 +277,7 @@ log) {
296
277
  : grantRefusalOf(policyKey, tool, {
297
278
  // only `requiredRole` reads the role, and then it was read above
298
279
  role: memberRole ?? "guest",
299
- forbiddenTools: unattended.forbiddenTools,
280
+ orgPolicy: orgPolicy.policy,
300
281
  });
301
282
  if (why !== null && why.code !== "needs_role") {
302
283
  return { refused: UNATTENDED_FIXED_ASK_ERROR(policyKey) };
@@ -310,21 +291,21 @@ log) {
310
291
  requestedFor: escalateTo === null ? ctx.accountId : null,
311
292
  approverRole: escalateTo,
312
293
  // the most specific rule that asked: role escalation, the agent's tightening, the connector,
313
- // a fixed ask (requiresUserInteraction), the org's sandboxToolPolicy, else the tool's own
314
- // default
294
+ // an organization ceiling, a fixed ask, or the declaration default
315
295
  policy: escalateTo !== null
316
296
  ? "role"
317
- : agentOverride === "ask" || (decidedBy === "agent" && connectorDefault === "ask")
318
- ? "agent"
319
- : decidedBy === "member" && connectorDefault === "ask"
320
- ? "member"
321
- : tool.source.kind === "connector" && connectorDefault === "ask"
322
- ? "connector"
323
- : fixedAsk
324
- ? "fixed"
325
- : orgAsk
326
- ? "org"
297
+ : orgAsk
298
+ ? "org"
299
+ : agentOverride === "ask" || (decidedBy === "agent" && connectorDefault === "ask")
300
+ ? "agent"
301
+ : decidedBy === "member" && connectorDefault === "ask"
302
+ ? "member"
303
+ : tool.source.kind === "connector" && connectorDefault === "ask"
304
+ ? "connector"
305
+ : fixedAsk
306
+ ? "fixed"
327
307
  : "default",
308
+ ...(orgAsk && { orgAskRevisions: orgPolicy.revisions }),
328
309
  };
329
310
  return { ask };
330
311
  };
@@ -469,6 +469,11 @@ export declare class ToolRegistry {
469
469
  keys: Set<string>;
470
470
  issues: ToolRefIssue[];
471
471
  }>;
472
+ /** Canonical keys for security settings, including tools that are currently unavailable. */
473
+ securityCatalog(orgId: string): Promise<{
474
+ toolKey: string;
475
+ source: "builtin" | "connector" | "extension";
476
+ }[]>;
472
477
  /**
473
478
  * Resolves what the agent has (see the class comment), then decides on `ToolSearch`: the org
474
479
  * setting `toolSearch === "on"` and more than `tools.searchThresholdTools` tools or more than
@@ -13,6 +13,7 @@ import { Inject, Injectable } from "@nestjs/common";
13
13
  import { builtinDisabled, connectorToolDisabled, extensionToolDisabled, } from "../agents/definition.js";
14
14
  import { EffectiveConfigs, NEEDS_CONFIG_REASON } from "../extensions/effective-config.js";
15
15
  import { ExtensionHost } from "../extensions/host.js";
16
+ import { extensionVisibleTo } from "../extensions/org-config.js";
16
17
  import { ExtensionRegistry } from "../extensions/registry.js";
17
18
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
18
19
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -329,6 +330,29 @@ let ToolRegistry = class ToolRegistry {
329
330
  });
330
331
  return { keys, issues };
331
332
  }
333
+ /** Canonical keys for security settings, including tools that are currently unavailable. */
334
+ async securityCatalog(orgId) {
335
+ const tools = this.host.tools();
336
+ const candidates = [...new Set(tools.map(({ plugin }) => plugin))];
337
+ const [apps, eligibility] = await Promise.all([
338
+ this.loadOrgConnectors(orgId, { includeDeleted: false }),
339
+ Promise.all(candidates.map((plugin) => extensionVisibleTo(this.db.db, orgId, plugin))),
340
+ ]);
341
+ const plugins = new Set(candidates.filter((_plugin, index) => eligibility[index]));
342
+ return [
343
+ ...this.builtins.map((b) => ({ toolKey: b.spec.name, source: "builtin" })),
344
+ ...apps.flatMap((app) => app.tools.map((t) => ({
345
+ toolKey: connectorToolKey(app.slug, t.name),
346
+ source: "connector",
347
+ }))),
348
+ ...tools
349
+ .filter((t) => plugins.has(t.plugin))
350
+ .map((t) => ({
351
+ toolKey: extensionToolKey(t.plugin, t.spec.name),
352
+ source: "extension",
353
+ })),
354
+ ];
355
+ }
332
356
  /**
333
357
  * Resolves what the agent has (see the class comment), then decides on `ToolSearch`: the org
334
358
  * setting `toolSearch === "on"` and more than `tools.searchThresholdTools` tools or more than
@@ -337,9 +361,18 @@ let ToolRegistry = class ToolRegistry {
337
361
  * the builtin `Skill` is added (always fully loaded).
338
362
  */
339
363
  async forAgent(orgId, def) {
340
- const resolved = await this.resolve(orgId, def);
364
+ const [resolved, denied] = await Promise.all([
365
+ this.resolve(orgId, def),
366
+ def.replay === true ? new Set() : this.switches.offKeys(orgId),
367
+ ]);
341
368
  const { unavailable, hidden } = resolved;
342
- const tools = filterSubagentTools(resolved.tools, def.subagentTools);
369
+ const visible = (tool) => {
370
+ if (!denied.has(tool.key))
371
+ return true;
372
+ hidden.push({ ref: tool.key, reason: toolTurnedOffReason(tool.key) });
373
+ return false;
374
+ };
375
+ const tools = filterSubagentTools(resolved.tools, def.subagentTools).filter(visible);
343
376
  // `SendMessage` to an agent that has `Agent` (to reach its sub-agents) or a parent;
344
377
  // `SubagentHandback` to a sub-agent only; a fork invocation's child reports by its reply
345
378
  const toParent = def.child === true && def.forkChild !== true;
@@ -363,7 +396,12 @@ let ToolRegistry = class ToolRegistry {
363
396
  ...(sl.timeoutMs !== undefined && { timeoutMs: sl.timeoutMs }),
364
397
  });
365
398
  }
366
- const toolSearch = await this.searchActive(orgId, tools);
399
+ for (let i = tools.length - 1; i >= 0; i--) {
400
+ const tool = tools[i];
401
+ if (tool !== undefined && !visible(tool))
402
+ tools.splice(i, 1);
403
+ }
404
+ const toolSearch = !denied.has(TOOL_SEARCH) && (await this.searchActive(orgId, tools));
367
405
  if (toolSearch) {
368
406
  const b = this.builtins.find((x) => x.spec.name === TOOL_SEARCH);
369
407
  tools.push({
@@ -452,10 +490,7 @@ let ToolRegistry = class ToolRegistry {
452
490
  // extension tools: the extensions enabled in the org
453
491
  const pluginTools = this.host.tools();
454
492
  if (pluginTools.length > 0) {
455
- const [enabledPlugins, offKeys] = await Promise.all([
456
- this.enabledPlugins(orgId),
457
- this.switches.offKeys(orgId),
458
- ]);
493
+ const enabledPlugins = await this.enabledPlugins(orgId);
459
494
  // one effective config read per extension and resolution, however many tools it has
460
495
  const configured = new Map();
461
496
  const configuredIn = (plugin) => {
@@ -472,11 +507,6 @@ let ToolRegistry = class ToolRegistry {
472
507
  if (extensionToolDisabled(disabled, t.plugin, t.spec.name))
473
508
  continue;
474
509
  const key = extensionToolKey(t.plugin, t.spec.name);
475
- // the pipeline refuses such calls too (a resumed step), this keeps them from the model
476
- if (offKeys.has(key)) {
477
- hidden.push({ ref: key, reason: toolTurnedOffReason(key) });
478
- continue;
479
- }
480
510
  // offered only in some conversation sources; the source never changes, so this also
481
511
  // refuses a resumed call (the pipeline resolves the step's tools with the same source)
482
512
  if (t.spec.sources !== undefined && !t.spec.sources.includes(source)) {
@@ -606,6 +636,7 @@ let ToolRegistry = class ToolRegistry {
606
636
  "spec_hash",
607
637
  "status",
608
638
  "default_policy",
639
+ "declaration_policy",
609
640
  "source",
610
641
  "missing_since",
611
642
  ])
@@ -625,7 +656,7 @@ let ToolRegistry = class ToolRegistry {
625
656
  spec: t.spec,
626
657
  specHash: t.spec_hash,
627
658
  status: t.status,
628
- defaultPolicy: t.default_policy,
659
+ defaultPolicy: t.declaration_policy ?? t.default_policy,
629
660
  source: t.source,
630
661
  gone: t.missing_since !== null,
631
662
  })),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.127",
3
+ "version": "0.1.0-rc.129",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,234 @@
1
+ -- Copy policy under write-conflicting locks, then fence the old representation before committing.
2
+ LOCK TABLE orgs, org_tool_switches, connectors, connector_tools IN SHARE ROW EXCLUSIVE MODE;
3
+
4
+ -- capybara:allow-destructive The expansion must abort before copying any rules when an old deny list cannot be read.
5
+ DO $$
6
+ DECLARE
7
+ bad_orgs text;
8
+ BEGIN
9
+ SELECT string_agg(id, ', ' ORDER BY id COLLATE "C") INTO bad_orgs
10
+ FROM orgs
11
+ WHERE (settings ? 'automations' AND jsonb_typeof(settings -> 'automations') <> 'object')
12
+ OR (settings -> 'automations' ? 'forbiddenTools'
13
+ AND jsonb_typeof(settings #> '{automations,forbiddenTools}') <> 'array');
14
+
15
+ IF bad_orgs IS NOT NULL THEN
16
+ RAISE EXCEPTION 'Cannot migrate unreadable organization tool policy for org IDs: %', bad_orgs;
17
+ END IF;
18
+ END
19
+ $$;
20
+
21
+ CREATE SEQUENCE IF NOT EXISTS org_tool_policy_row_revision_seq AS bigint;
22
+
23
+ CREATE TABLE IF NOT EXISTS org_tool_policies (
24
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
25
+ tool_key text COLLATE "C" NOT NULL CHECK (char_length(tool_key) BETWEEN 1 AND 200),
26
+ policy text NOT NULL CHECK (policy IN ('allow', 'ask', 'deny')),
27
+ unattended_policy text NOT NULL CHECK (unattended_policy IN ('allow', 'ask', 'deny')),
28
+ row_revision bigint NOT NULL DEFAULT nextval('org_tool_policy_row_revision_seq'),
29
+ updated_by text REFERENCES accounts(id) ON DELETE SET NULL,
30
+ updated_at timestamptz NOT NULL DEFAULT now(),
31
+ PRIMARY KEY (org_id, tool_key)
32
+ );
33
+
34
+ CREATE TABLE IF NOT EXISTS org_git_push_denials (
35
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
36
+ target text COLLATE "C" NOT NULL CHECK (target = '*' OR (
37
+ char_length(target) <= 191 AND target ~ '^[a-z0-9_.-]+/[a-z0-9_.-]+$'
38
+ AND split_part(target, '/', 1) NOT IN ('.', '..')
39
+ AND split_part(target, '/', 2) NOT IN ('.', '..')
40
+ )),
41
+ updated_by text REFERENCES accounts(id) ON DELETE SET NULL,
42
+ updated_at timestamptz NOT NULL DEFAULT now(),
43
+ PRIMARY KEY (org_id, target)
44
+ );
45
+
46
+ DROP POLICY IF EXISTS org_scope ON org_tool_policies;
47
+ CREATE POLICY org_scope ON org_tool_policies USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
48
+ DROP POLICY IF EXISTS org_scope ON org_git_push_denials;
49
+ CREATE POLICY org_scope ON org_git_push_denials USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
50
+
51
+ ALTER TABLE connector_tools ADD COLUMN IF NOT EXISTS declaration_policy text
52
+ CHECK (declaration_policy IN ('allow', 'ask', 'deny'));
53
+
54
+ -- Keep the old admin columns for old readers. The separately stored baseline comes from the
55
+ -- retained template or annotations. An admin allow cannot erase a template or annotation ask.
56
+ UPDATE connector_tools t
57
+ SET declaration_policy = CASE
58
+ WHEN c.template_tool_policies ->> t.name IN ('allow', 'ask', 'deny')
59
+ THEN c.template_tool_policies ->> t.name
60
+ WHEN t.spec #> '{annotations,readOnlyHint}' = 'true'::jsonb THEN 'allow'
61
+ ELSE 'ask'
62
+ END
63
+ FROM connectors c
64
+ WHERE c.id = t.connector_id AND t.policy_source = 'admin' AND t.declaration_policy IS NULL;
65
+
66
+ CREATE OR REPLACE FUNCTION pg_temp.security_legacy_trim(v text) RETURNS text
67
+ LANGUAGE sql IMMUTABLE STRICT AS $$
68
+ SELECT btrim(v, U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF')
69
+ $$;
70
+
71
+ -- Keep exact ordinary keys, including dormant keys. Recognized Git crossings have their own
72
+ -- target keys; this namespace does not name any ordinary tools or per-call tools.
73
+ CREATE TEMP TABLE IF NOT EXISTS legacy_security_deny_keys ON COMMIT DROP AS
74
+ SELECT o.id AS org_id, v.key #>> '{}' AS tool_key,
75
+ CASE
76
+ WHEN normalized.key = 'git:push' THEN '*'
77
+ WHEN starts_with(normalized.key, 'git:push:') AND char_length(repo.target) <= 191
78
+ AND repo.target COLLATE "C" ~ '^[a-z0-9_.-]+/[a-z0-9_.-]+$'
79
+ AND split_part(repo.target, '/', 1) NOT IN ('.', '..')
80
+ AND split_part(repo.target, '/', 2) NOT IN ('.', '..')
81
+ THEN repo.target
82
+ END AS git_target
83
+ FROM orgs o
84
+ CROSS JOIN LATERAL jsonb_array_elements(o.settings #> '{automations,forbiddenTools}') AS v(key)
85
+ -- Use locale-independent ASCII folding. Kelvin sign is the one non-ASCII character that
86
+ -- JavaScript lowercases to ASCII, so it too can participate in an old Git repository key.
87
+ CROSS JOIN LATERAL (
88
+ SELECT lower(translate(pg_temp.security_legacy_trim(v.key #>> '{}'), U&'\212A', 'k') COLLATE "C") AS key
89
+ ) AS normalized
90
+ CROSS JOIN LATERAL (SELECT regexp_replace(pg_temp.security_legacy_trim(substr(normalized.key, 10)), '[.]git$', '') AS target) AS repo
91
+ WHERE jsonb_typeof(v.key) = 'string'
92
+ -- Match JavaScript's stored list limit, which counts astral characters as two code units.
93
+ AND char_length(v.key #>> '{}') + char_length(regexp_replace(v.key #>> '{}', U&'[^\+010000-\+10FFFF]', '', 'g')) BETWEEN 1 AND 200;
94
+
95
+ WITH copied AS (
96
+ SELECT id AS org_id, tool_key, 1 AS attended, 0 AS unattended, NULL::text AS actor
97
+ FROM orgs CROSS JOIN (VALUES ('Bash'), ('Write'), ('Edit'), ('Deliver')) AS builtins(tool_key)
98
+ WHERE settings ? 'sandboxToolPolicy' AND settings -> 'sandboxToolPolicy' <> '"allow"'::jsonb
99
+ UNION ALL
100
+ SELECT org_id, 'plugin__' || plugin || '__' || tool, 2, 0, updated_by
101
+ FROM org_tool_switches WHERE NOT enabled
102
+ UNION ALL
103
+ SELECT c.org_id, 'mcp__' || c.slug || '__' || t.name,
104
+ CASE t.default_policy WHEN 'deny' THEN 2 ELSE 1 END, 0, NULL
105
+ FROM connectors c JOIN connector_tools t ON t.connector_id = c.id
106
+ WHERE t.policy_source = 'admin' AND t.default_policy IN ('ask', 'deny')
107
+ UNION ALL
108
+ SELECT org_id, tool_key, 0, 2, NULL
109
+ FROM legacy_security_deny_keys WHERE git_target IS NULL
110
+ )
111
+ INSERT INTO org_tool_policies (org_id, tool_key, policy, unattended_policy, updated_by)
112
+ SELECT org_id, tool_key, (ARRAY['allow', 'ask', 'deny'])[max(attended) + 1],
113
+ (ARRAY['allow', 'ask', 'deny'])[max(unattended) + 1], max(actor)
114
+ FROM copied
115
+ -- A reapplication must not restore a rule the new representation removed.
116
+ WHERE NOT EXISTS (
117
+ SELECT FROM pg_trigger
118
+ WHERE tgrelid = 'orgs'::regclass AND tgname = 'org_security_legacy_settings_fence'
119
+ )
120
+ GROUP BY org_id, tool_key
121
+ ON CONFLICT (org_id, tool_key) DO NOTHING;
122
+
123
+ INSERT INTO org_git_push_denials (org_id, target)
124
+ SELECT DISTINCT org_id, git_target
125
+ FROM legacy_security_deny_keys
126
+ WHERE git_target IS NOT NULL AND NOT EXISTS (
127
+ SELECT FROM pg_trigger
128
+ WHERE tgrelid = 'orgs'::regclass AND tgname = 'org_security_legacy_settings_fence'
129
+ )
130
+ ON CONFLICT (org_id, target) DO NOTHING;
131
+
132
+ CREATE OR REPLACE FUNCTION fence_legacy_org_security_settings() RETURNS trigger
133
+ LANGUAGE plpgsql AS $$
134
+ DECLARE
135
+ old_settings jsonb;
136
+ old_sandbox_policy jsonb;
137
+ old_forbidden_tools jsonb;
138
+ new_forbidden_tools jsonb;
139
+ projected_forbidden_tools jsonb;
140
+ BEGIN
141
+ old_settings := CASE WHEN TG_OP = 'INSERT' THEN '{}'::jsonb ELSE OLD.settings END;
142
+ old_sandbox_policy := old_settings -> 'sandboxToolPolicy';
143
+ old_forbidden_tools := old_settings #> '{automations,forbiddenTools}';
144
+ new_forbidden_tools := NEW.settings #> '{automations,forbiddenTools}';
145
+ -- Old replicas materialize defaults when writing unrelated settings. Keep an absent old key
146
+ -- absent while accepting that harmless serialization. Every actual old policy change fails.
147
+ IF old_settings -> 'sandboxToolPolicy' IS NULL AND NEW.settings -> 'sandboxToolPolicy' = '"allow"'::jsonb
148
+ THEN NEW.settings := NEW.settings - 'sandboxToolPolicy'; END IF;
149
+ IF old_settings #> '{automations,forbiddenTools}' IS NULL AND NEW.settings #> '{automations,forbiddenTools}' = '[]'::jsonb
150
+ THEN NEW.settings := NEW.settings #- '{automations,forbiddenTools}'; END IF;
151
+
152
+ -- The old settings writer serializes its read projection while changing unrelated settings.
153
+ -- Accept that exact projection only by restoring the legacy values before checking the fence.
154
+ IF TG_OP = 'UPDATE' AND
155
+ ((old_settings - 'sandboxToolPolicy') #- '{automations,forbiddenTools}')
156
+ IS DISTINCT FROM
157
+ ((NEW.settings - 'sandboxToolPolicy') #- '{automations,forbiddenTools}')
158
+ THEN
159
+ IF old_sandbox_policy NOT IN ('"allow"'::jsonb, '"ask"'::jsonb)
160
+ AND NEW.settings -> 'sandboxToolPolicy' = '"ask"'::jsonb
161
+ THEN
162
+ NEW.settings := jsonb_set(NEW.settings, '{sandboxToolPolicy}', old_sandbox_policy);
163
+ END IF;
164
+ IF jsonb_typeof(old_forbidden_tools) = 'array'
165
+ AND jsonb_typeof(new_forbidden_tools) = 'array'
166
+ AND old_forbidden_tools IS DISTINCT FROM new_forbidden_tools
167
+ THEN
168
+ SELECT coalesce(jsonb_agg(key ORDER BY position), '[]'::jsonb) INTO projected_forbidden_tools
169
+ FROM (
170
+ SELECT key, position
171
+ FROM jsonb_array_elements(old_forbidden_tools) WITH ORDINALITY AS entry(key, position)
172
+ WHERE jsonb_typeof(key) = 'string'
173
+ AND char_length(key #>> '{}') + char_length(regexp_replace(key #>> '{}', U&'[^\+010000-\+10FFFF]', '', 'g')) BETWEEN 1 AND 200
174
+ ORDER BY position
175
+ LIMIT 500
176
+ ) AS accepted;
177
+ IF new_forbidden_tools = projected_forbidden_tools THEN
178
+ NEW.settings := jsonb_set(NEW.settings, '{automations,forbiddenTools}', old_forbidden_tools);
179
+ END IF;
180
+ END IF;
181
+ END IF;
182
+
183
+ IF old_settings -> 'sandboxToolPolicy' IS DISTINCT FROM NEW.settings -> 'sandboxToolPolicy'
184
+ OR old_settings #> '{automations,forbiddenTools}' IS DISTINCT FROM NEW.settings #> '{automations,forbiddenTools}'
185
+ THEN
186
+ RAISE EXCEPTION 'security policy moved; retry after the upgrade';
187
+ END IF;
188
+ RETURN NEW;
189
+ END
190
+ $$;
191
+
192
+ CREATE OR REPLACE FUNCTION fence_legacy_org_tool_switches() RETURNS trigger
193
+ LANGUAGE plpgsql AS $$
194
+ BEGIN
195
+ IF TG_OP = 'DELETE' THEN
196
+ -- A removed organization no longer has a policy. Let its foreign key cascade finish.
197
+ IF NOT EXISTS (SELECT FROM capybara.orgs WHERE id = OLD.org_id)
198
+ THEN RETURN OLD; END IF;
199
+ ELSIF TG_OP = 'UPDATE' THEN
200
+ -- The account foreign key may clear its audit reference without changing the policy.
201
+ IF NEW.updated_by IS NULL AND OLD.updated_by IS NOT NULL
202
+ AND (OLD.org_id, OLD.plugin, OLD.tool, OLD.enabled, OLD.updated_at)
203
+ IS NOT DISTINCT FROM (NEW.org_id, NEW.plugin, NEW.tool, NEW.enabled, NEW.updated_at)
204
+ AND NOT EXISTS (SELECT FROM capybara.accounts WHERE id = OLD.updated_by)
205
+ THEN RETURN NEW; END IF;
206
+ END IF;
207
+ RAISE EXCEPTION 'security policy moved; retry after the upgrade';
208
+ END
209
+ $$;
210
+
211
+ CREATE OR REPLACE FUNCTION fence_legacy_connector_tool_policy() RETURNS trigger
212
+ LANGUAGE plpgsql AS $$
213
+ BEGIN
214
+ IF (TG_OP = 'INSERT' AND NEW.policy_source = 'admin') OR
215
+ (TG_OP = 'UPDATE' AND (OLD.policy_source = 'admin' OR NEW.policy_source = 'admin')
216
+ AND (OLD.policy_source, OLD.default_policy) IS DISTINCT FROM (NEW.policy_source, NEW.default_policy))
217
+ THEN
218
+ RAISE EXCEPTION 'security policy moved; retry after the upgrade';
219
+ END IF;
220
+ RETURN NEW;
221
+ END
222
+ $$;
223
+
224
+ CREATE OR REPLACE TRIGGER org_security_legacy_settings_fence
225
+ BEFORE INSERT OR UPDATE OF settings ON orgs
226
+ FOR EACH ROW EXECUTE FUNCTION fence_legacy_org_security_settings();
227
+
228
+ CREATE OR REPLACE TRIGGER org_security_legacy_switches_fence
229
+ BEFORE INSERT OR UPDATE OR DELETE ON org_tool_switches
230
+ FOR EACH ROW EXECUTE FUNCTION fence_legacy_org_tool_switches();
231
+
232
+ CREATE OR REPLACE TRIGGER org_security_legacy_connector_policy_fence
233
+ BEFORE INSERT OR UPDATE OF policy_source, default_policy ON connector_tools
234
+ FOR EACH ROW EXECUTE FUNCTION fence_legacy_connector_tool_policy();