@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
@@ -60,12 +60,10 @@ export const ConnectorPreviewSchema = z
60
60
  const ToolPatch = z
61
61
  .object({
62
62
  status: z.enum(["enabled", "disabled"]).optional(),
63
- defaultPolicy: z.enum(["allow", "ask", "deny"]).optional(),
64
63
  })
65
64
  .strict();
66
65
  /**
67
- * `PATCH …/connectors/:connectorId`: rename, switch on or off, per-tool state and default policy,
68
- * every unannotated tool to allow, and git use. No endpoint and no credential.
66
+ * `PATCH …/connectors/:connectorId`: rename, switch on or off, per-tool availability and git use. No endpoint and no credential.
69
67
  */
70
68
  export const ConnectorUpdateSchema = z
71
69
  .object({
@@ -75,7 +73,6 @@ export const ConnectorUpdateSchema = z
75
73
  .record(z.string().max(200), ToolPatch)
76
74
  .refine((v) => Object.keys(v).length <= 1000, { message: "Too many tools" })
77
75
  .optional(),
78
- allowUnannotated: z.boolean().optional(),
79
76
  /** Use an org-credential connector for git in sandboxes (spec 2026-11-12 §6.2). */
80
77
  useForGit: z.boolean().optional(),
81
78
  /** The connector's own description; null or blank removes it. */
@@ -41,7 +41,7 @@ export interface ConnectorToolView {
41
41
  * 默认策略的来历:`derived` 按注解推导(定义变化复核通过后重新推导),`admin` 管理员设定(保留),
42
42
  * `template` 来自目录模板的 `defaultToolPolicies`(与 admin 一样保留)。
43
43
  */
44
- policySource: "derived" | "admin" | "template";
44
+ policySource: "derived" | "template";
45
45
  /** 远端已不再提供该工具(随之停用;又出现时待复核)。 */
46
46
  missing: boolean;
47
47
  reviewedAt: Date | null;
@@ -229,10 +229,7 @@ export interface UpdateConnectorInput {
229
229
  status?: "active" | "disabled" | undefined;
230
230
  tools?: Record<string, {
231
231
  status?: "enabled" | "disabled" | undefined;
232
- defaultPolicy?: ToolPolicy | undefined;
233
232
  }> | undefined;
234
- /** 把「没有 readOnlyHint / destructiveHint 注解」的工具默认策略批量改为 allow。 */
235
- allowUnannotated?: boolean | undefined;
236
233
  /**
237
234
  * Use this connector's credential for git in sandboxes (sandbox git credentials spec §6.2): only
238
235
  * an org-ownership connector that declares git hosts; pushes are then the bot's.
@@ -458,8 +455,7 @@ export declare class ConnectorsService {
458
455
  }>;
459
456
  get(orgId: string, connectorId: string, viewerAccountId: string): Promise<ConnectorDetail>;
460
457
  /**
461
- * Renames, switches on or off, sets tool status and default policies, allows unannotated tools
462
- * in bulk (`connectors.manage`), and changes the editable endpoint fields of a template connector
458
+ * Renames, switches on or off, sets tool availability (`connectors.manage`), and changes the editable endpoint fields of a template connector
463
459
  * ({@link endpointChange}).
464
460
  */
465
461
  update(orgId: string, connectorId: string, actorAccountId: string, patch: UpdateConnectorInput, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<ConnectorDetail>;
@@ -572,7 +568,7 @@ export declare class ConnectorsService {
572
568
  /**
573
569
  * Reviews a tool pending review (`connectors.manage`, spec 7.3). `approve`: adopts the pending
574
570
  * definition (if any) and enables it, `reviewed_at` set to now; the default policy is derived
575
- * again from the new definition's annotations unless an admin set it (`policy_source = admin`)
571
+ * again from the new definition and connector template
576
572
  * and the source did not change. `reject`: disables it, drops the pending definition and keeps
577
573
  * the old one; a never-reviewed tool keeps `reviewed_at` empty after a rejection (it can still
578
574
  * be approved). A missing tool -> 404 `connector.tool_not_found`; not reviewable (reviewed with
@@ -108,8 +108,6 @@ function parseOAuthClient(credential, requireSecret, prefix = "credential") {
108
108
  }
109
109
  return r.data;
110
110
  }
111
- /** 无注解 = 既没有 readOnlyHint 也没有 destructiveHint。 */
112
- const unannotated = (a) => a?.readOnlyHint === undefined && a?.destructiveHint === undefined;
113
111
  /**
114
112
  * 连接器(远端服务实例)与其工具快照、凭据。写操作都在组织行锁内复核发起人权限并写审计
115
113
  * (detail 只有凭据类型与归属,没有值)。连接器会话按操作打开、用完即关,不在进程内缓存。
@@ -680,9 +678,8 @@ let ConnectorsService = class ConnectorsService {
680
678
  // unnamed derived ones and the org's own (`admin`) stay
681
679
  const atDefault = await t
682
680
  .selectFrom("connector_tools")
683
- .select(["name", "spec", "default_policy", "policy_source"])
681
+ .select(["name", "spec", "default_policy", "declaration_policy", "policy_source"])
684
682
  .where("connector_id", "=", connectorId)
685
- .where("policy_source", "in", ["template", "derived"])
686
683
  .forUpdate()
687
684
  .execute();
688
685
  const policyChanges = {};
@@ -695,12 +692,15 @@ let ConnectorsService = class ConnectorsService {
695
692
  : policyFromAnnotations(tool.spec.annotations);
696
693
  await t
697
694
  .updateTable("connector_tools")
698
- .set({ default_policy: next, policy_source: named ? "template" : "derived" })
695
+ .set(tool.policy_source === "admin"
696
+ ? { declaration_policy: next }
697
+ : { default_policy: next, policy_source: named ? "template" : "derived" })
699
698
  .where("connector_id", "=", connectorId)
700
699
  .where("name", "=", tool.name)
701
700
  .execute();
702
- if (next !== tool.default_policy) {
703
- policyChanges[tool.name] = { from: tool.default_policy, to: next };
701
+ const previous = tool.declaration_policy ?? tool.default_policy;
702
+ if (next !== previous) {
703
+ policyChanges[tool.name] = { from: previous, to: next };
704
704
  }
705
705
  }
706
706
  if (input.resetCredentials) {
@@ -956,6 +956,7 @@ let ConnectorsService = class ConnectorsService {
956
956
  "spec_hash",
957
957
  "status",
958
958
  "default_policy",
959
+ "declaration_policy",
959
960
  "source",
960
961
  "policy_source",
961
962
  "missing_since",
@@ -984,11 +985,15 @@ let ConnectorsService = class ConnectorsService {
984
985
  annotations: spec.annotations ?? null,
985
986
  connectorData: spec.connectorData ?? null,
986
987
  status: t.status,
987
- defaultPolicy: t.default_policy,
988
+ defaultPolicy: t.declaration_policy ?? t.default_policy,
988
989
  specHash: t.spec_hash,
989
990
  issue: toolIssue(r.slug, next ?? spec),
990
991
  source: t.source,
991
- policySource: t.policy_source,
992
+ policySource: t.policy_source === "admin"
993
+ ? Object.hasOwn(r.template_tool_policies ?? {}, t.name)
994
+ ? "template"
995
+ : "derived"
996
+ : t.policy_source,
992
997
  missing: t.missing_since !== null,
993
998
  reviewedAt: t.reviewed_at,
994
999
  pending: next && t.pending_spec_hash !== null
@@ -1120,8 +1125,7 @@ let ConnectorsService = class ConnectorsService {
1120
1125
  return this.detail(this.db, orgId, connectorId, viewerAccountId);
1121
1126
  }
1122
1127
  /**
1123
- * Renames, switches on or off, sets tool status and default policies, allows unannotated tools
1124
- * in bulk (`connectors.manage`), and changes the editable endpoint fields of a template connector
1128
+ * Renames, switches on or off, sets tool availability (`connectors.manage`), and changes the editable endpoint fields of a template connector
1125
1129
  * ({@link endpointChange}).
1126
1130
  */
1127
1131
  async update(orgId, connectorId, actorAccountId, patch, actorTokenId, auditDetail) {
@@ -1227,37 +1231,12 @@ let ConnectorsService = class ConnectorsService {
1227
1231
  .where("org_id", "=", orgId)
1228
1232
  .execute();
1229
1233
  }
1230
- const allowed = [];
1231
- if (patch.allowUnannotated) {
1232
- for (const c of current) {
1233
- const explicit = patch.tools?.[c.name]?.defaultPolicy !== undefined;
1234
- if (!explicit &&
1235
- c.default_policy === "ask" &&
1236
- unannotated(c.spec.annotations)) {
1237
- allowed.push(c.name);
1238
- }
1239
- }
1240
- if (allowed.length > 0) {
1241
- await t
1242
- .updateTable("connector_tools")
1243
- .set({ default_policy: "allow", policy_source: "admin" })
1244
- .where("connector_id", "=", connectorId)
1245
- .where("name", "in", allowed)
1246
- .execute();
1247
- }
1248
- }
1249
1234
  for (const [name, change] of toolChanges) {
1250
- if (change.status === undefined && change.defaultPolicy === undefined)
1235
+ if (change.status === undefined)
1251
1236
  continue;
1252
1237
  await t
1253
1238
  .updateTable("connector_tools")
1254
- .set({
1255
- ...(change.status !== undefined && { status: change.status }),
1256
- ...(change.defaultPolicy !== undefined && {
1257
- default_policy: change.defaultPolicy,
1258
- policy_source: "admin",
1259
- }),
1260
- })
1239
+ .set({ status: change.status })
1261
1240
  .where("connector_id", "=", connectorId)
1262
1241
  .where("name", "=", name)
1263
1242
  .execute();
@@ -1296,7 +1275,6 @@ let ConnectorsService = class ConnectorsService {
1296
1275
  ...(gitChanged && { useForGit: { from: app.use_for_git, to: patch.useForGit } }),
1297
1276
  ...(descriptionChanged && { description: { from: app.description, to: description } }),
1298
1277
  ...(toolChanges.length > 0 && { tools: Object.fromEntries(toolChanges) }),
1299
- ...(allowed.length > 0 && { allowedUnannotated: allowed }),
1300
1278
  // the changed paths, never their values (a header may carry a tenant key)
1301
1279
  ...(ep !== undefined && { endpoint: ep.changed }),
1302
1280
  // which credentials a destination change cleared, by name
@@ -1675,7 +1653,7 @@ let ConnectorsService = class ConnectorsService {
1675
1653
  /**
1676
1654
  * Reviews a tool pending review (`connectors.manage`, spec 7.3). `approve`: adopts the pending
1677
1655
  * definition (if any) and enables it, `reviewed_at` set to now; the default policy is derived
1678
- * again from the new definition's annotations unless an admin set it (`policy_source = admin`)
1656
+ * again from the new definition and connector template
1679
1657
  * and the source did not change. `reject`: disables it, drops the pending definition and keeps
1680
1658
  * the old one; a never-reviewed tool keeps `reviewed_at` empty after a rejection (it can still
1681
1659
  * be approved). A missing tool -> 404 `connector.tool_not_found`; not reviewable (reviewed with
@@ -1722,6 +1700,7 @@ let ConnectorsService = class ConnectorsService {
1722
1700
  throw fail("action", issue);
1723
1701
  }
1724
1702
  const rederive = tool.policy_source === "derived" || nextSource !== tool.source;
1703
+ const declaration = app.template_tool_policies?.[name] ?? policyFromAnnotations(next.annotations);
1725
1704
  await t
1726
1705
  .updateTable("connector_tools")
1727
1706
  .set({
@@ -1733,10 +1712,16 @@ let ConnectorsService = class ConnectorsService {
1733
1712
  spec_hash: tool.pending_spec_hash,
1734
1713
  source: nextSource,
1735
1714
  }),
1736
- ...(rederive && {
1737
- default_policy: policyFromAnnotations(next.annotations),
1738
- policy_source: "derived",
1739
- }),
1715
+ ...(tool.policy_source === "admin"
1716
+ ? { declaration_policy: declaration }
1717
+ : rederive
1718
+ ? {
1719
+ default_policy: declaration,
1720
+ policy_source: app.template_tool_policies?.[name] === undefined
1721
+ ? "derived"
1722
+ : "template",
1723
+ }
1724
+ : {}),
1740
1725
  }
1741
1726
  : { status: "disabled" }),
1742
1727
  pending_spec: null,
@@ -328,10 +328,18 @@ let ToolDrift = class ToolDrift {
328
328
  pending_spec: null,
329
329
  pending_spec_hash: null,
330
330
  pending_source: null,
331
- ...((c.policy_source === "derived" || c.source !== r.source) && {
332
- default_policy: policyFromAnnotations(r.spec.annotations),
333
- policy_source: "derived",
334
- }),
331
+ ...(c.policy_source === "admin"
332
+ ? {
333
+ declaration_policy: app.template_tool_policies?.[r.name] ?? policyFromAnnotations(r.spec.annotations),
334
+ }
335
+ : c.policy_source === "derived" || c.source !== r.source
336
+ ? {
337
+ default_policy: app.template_tool_policies?.[r.name] ?? policyFromAnnotations(r.spec.annotations),
338
+ policy_source: app.template_tool_policies?.[r.name] === undefined
339
+ ? "derived"
340
+ : "template",
341
+ }
342
+ : {}),
335
343
  };
336
344
  // 复核过的工具:新定义(含不合规的)只进 pending,`spec` 始终是上次复核通过的定义(复核对比的基准);
337
345
  // 不合规的新定义只能停用(approve 会因不合规被拒,reject 清掉)
@@ -19,10 +19,7 @@ export type GitPushReason =
19
19
  | "org_deny"
20
20
  /** The member denied pushes to the repository for themselves. */
21
21
  | "member_deny"
22
- /**
23
- * The org forbids `git:push` (or the repository's key) in scheduled runs, or its forbidden list
24
- * cannot be read (fails closed).
25
- */
22
+ /** The organization denies this repository or all pushes in unattended runs. */
26
23
  | "forbidden"
27
24
  /** An unattended run in `fail` mode without a task grant: no one can be asked. */
28
25
  | "unattended"
@@ -1,16 +1,17 @@
1
1
  import { sql } from "kysely";
2
- import { GIT_PUSH_GRANT, gitPushForbidden, gitPushGrantKey, normalizeGitRepo, } from "../automations/grant-rules.js";
2
+ import { GIT_PUSH_GRANT, gitPushGrantKey, normalizeGitRepo } from "../automations/grant-rules.js";
3
3
  import { unattendedRules, unattendedRunOf } from "../automations/unattended.js";
4
4
  import { budgetRunOf } from "../runtime/subagents/limits.js";
5
5
  import { gitPushPolicyName, personalAuth } from "./connector-account-policies.js";
6
6
  import { gitRepoKey } from "./git-asks.js";
7
+ import { isOrgGitPushDenied } from "./org-tool-policies.js";
7
8
  import { connectorPolicy } from "./policy.js";
8
9
  /**
9
10
  * The push policy of the git gateway (sandbox git credentials spec §7): fetches run, a push
10
11
  * follows the connector's virtual tool `git_push`. Read from PG on every push (no in-process
11
12
  * state), so a decision on one replica holds on every other.
12
13
  *
13
- * Storage (no new table): the org's default is `connectors.git_push_policy` (default `ask`); a
14
+ * The connector declaration is `connectors.git_push_policy` (default `ask`); a
14
15
  * member's standing allow (or deny) for one repository is their `connector_tool_account_policies`
15
16
  * row `git_push:<host>/<owner>/<repo>` (a personal connector only: an org connector's push acts as the
16
17
  * org); a run grant is an approved `once` git ask of the run tree; an automation's grants are
@@ -80,9 +81,7 @@ export async function decideGitPush(db, config, input) {
80
81
  ? input.unattended
81
82
  : await unattendedRunOf(db, config, input.orgId, input.runId);
82
83
  const rules = unattendedRules(unattended) ? unattended : null;
83
- // fail closed: an unreadable list forbids every push of an unattended run
84
- if (rules !== null &&
85
- (rules.forbiddenToolsUnreadable === true || gitPushForbidden(rules.forbiddenTools, key))) {
84
+ if (rules !== null && (await isOrgGitPushDenied(db, input.orgId, repo))) {
86
85
  return { decision: "deny", reason: "forbidden", repo };
87
86
  }
88
87
  if (base.policy === "allow")
@@ -0,0 +1,24 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ export type OrgToolPolicy = "allow" | "ask" | "deny";
3
+ export interface OrgToolPolicyEdit {
4
+ toolKey: string;
5
+ policy: OrgToolPolicy;
6
+ unattendedPolicy: OrgToolPolicy;
7
+ }
8
+ export interface OrgToolPolicyRevision {
9
+ toolKey: string;
10
+ rowRevision: string;
11
+ }
12
+ export declare function strongerOrgToolPolicy(left: OrgToolPolicy, right: OrgToolPolicy): OrgToolPolicy;
13
+ export declare function readOrgToolPolicy(db: KernelSchemaDb, orgId: string, toolKey: string, perCallKey?: string, unattended?: boolean): Promise<{
14
+ policy: OrgToolPolicy;
15
+ revisions: readonly OrgToolPolicyRevision[];
16
+ }>;
17
+ export declare function readOrgToolPolicies(db: KernelSchemaDb, orgId: string): Promise<(OrgToolPolicyEdit & OrgToolPolicyRevision)[]>;
18
+ export declare function readOrgGitPushDenials(db: KernelSchemaDb, orgId: string): Promise<string[]>;
19
+ /** A final Git push needs only the repositories that can cover it. */
20
+ export declare function isOrgGitPushDenied(db: KernelSchemaDb, orgId: string, repo: string): Promise<boolean>;
21
+ /** The caller owns the org scope, writer transaction, authority lock and audit. */
22
+ export declare function writeOrgToolPolicy(db: KernelSchemaDb, orgId: string, edit: OrgToolPolicyEdit, actorId: string): Promise<boolean>;
23
+ /** The caller owns the org scope, writer transaction, authority lock and audit. */
24
+ export declare function writeOrgGitPushDenial(db: KernelSchemaDb, orgId: string, target: string, denied: boolean, actorId: string): Promise<boolean>;
@@ -0,0 +1,113 @@
1
+ import { sql } from "kysely";
2
+ const rank = { allow: 0, ask: 1, deny: 2 };
3
+ export function strongerOrgToolPolicy(left, right) {
4
+ return rank[left] >= rank[right] ? left : right;
5
+ }
6
+ export async function readOrgToolPolicy(db, orgId, toolKey, perCallKey, unattended = false) {
7
+ const rows = await db
8
+ .selectFrom("org_tool_policies")
9
+ .select(["tool_key", "policy", "unattended_policy", "row_revision"])
10
+ .where("org_id", "=", orgId)
11
+ .where("tool_key", "in", perCallKey && perCallKey !== toolKey ? [toolKey, perCallKey] : [toolKey])
12
+ .orderBy("tool_key")
13
+ .execute();
14
+ let policy = "allow";
15
+ const revisions = [];
16
+ for (const row of rows) {
17
+ const effective = unattended
18
+ ? strongerOrgToolPolicy(row.policy, row.unattended_policy)
19
+ : row.policy;
20
+ policy = strongerOrgToolPolicy(policy, effective);
21
+ if (effective === "ask")
22
+ revisions.push({ toolKey: row.tool_key, rowRevision: row.row_revision });
23
+ }
24
+ return { policy, revisions: policy === "ask" ? revisions : [] };
25
+ }
26
+ export function readOrgToolPolicies(db, orgId) {
27
+ return db
28
+ .selectFrom("org_tool_policies")
29
+ .select([
30
+ "tool_key as toolKey",
31
+ "policy",
32
+ "unattended_policy as unattendedPolicy",
33
+ "row_revision as rowRevision",
34
+ ])
35
+ .where("org_id", "=", orgId)
36
+ .orderBy("tool_key")
37
+ .execute();
38
+ }
39
+ export async function readOrgGitPushDenials(db, orgId) {
40
+ const rows = await db
41
+ .selectFrom("org_git_push_denials")
42
+ .select("target")
43
+ .where("org_id", "=", orgId)
44
+ .orderBy("target")
45
+ .execute();
46
+ return rows.map(({ target }) => target);
47
+ }
48
+ /** A final Git push needs only the repositories that can cover it. */
49
+ export async function isOrgGitPushDenied(db, orgId, repo) {
50
+ const row = await db
51
+ .selectFrom("org_git_push_denials")
52
+ .select("target")
53
+ .where("org_id", "=", orgId)
54
+ .where("target", "in", ["*", repo])
55
+ .executeTakeFirst();
56
+ return row !== undefined;
57
+ }
58
+ /** The caller owns the org scope, writer transaction, authority lock and audit. */
59
+ export async function writeOrgToolPolicy(db, orgId, edit, actorId) {
60
+ if (edit.policy === "allow" && edit.unattendedPolicy === "allow") {
61
+ const deleted = await db
62
+ .deleteFrom("org_tool_policies")
63
+ .where("org_id", "=", orgId)
64
+ .where("tool_key", "=", edit.toolKey)
65
+ .returning("tool_key")
66
+ .executeTakeFirst();
67
+ return deleted !== undefined;
68
+ }
69
+ const row = await db
70
+ .insertInto("org_tool_policies")
71
+ .values({
72
+ org_id: orgId,
73
+ tool_key: edit.toolKey,
74
+ policy: edit.policy,
75
+ unattended_policy: edit.unattendedPolicy,
76
+ updated_by: actorId,
77
+ })
78
+ .onConflict((oc) => oc
79
+ .columns(["org_id", "tool_key"])
80
+ .doUpdateSet((eb) => ({
81
+ policy: eb.ref("excluded.policy"),
82
+ unattended_policy: eb.ref("excluded.unattended_policy"),
83
+ row_revision: eb.ref("excluded.row_revision"),
84
+ updated_by: eb.ref("excluded.updated_by"),
85
+ updated_at: sql `now()`,
86
+ }))
87
+ .where((eb) => eb.or([
88
+ eb("org_tool_policies.policy", "!=", edit.policy),
89
+ eb("org_tool_policies.unattended_policy", "!=", edit.unattendedPolicy),
90
+ ])))
91
+ .returning("tool_key")
92
+ .executeTakeFirst();
93
+ return row !== undefined;
94
+ }
95
+ /** The caller owns the org scope, writer transaction, authority lock and audit. */
96
+ export async function writeOrgGitPushDenial(db, orgId, target, denied, actorId) {
97
+ if (!denied) {
98
+ const deleted = await db
99
+ .deleteFrom("org_git_push_denials")
100
+ .where("org_id", "=", orgId)
101
+ .where("target", "=", target)
102
+ .returning("target")
103
+ .executeTakeFirst();
104
+ return deleted !== undefined;
105
+ }
106
+ const inserted = await db
107
+ .insertInto("org_git_push_denials")
108
+ .values({ org_id: orgId, target, updated_by: actorId })
109
+ .onConflict((oc) => oc.columns(["org_id", "target"]).doNothing())
110
+ .returning("target")
111
+ .executeTakeFirst();
112
+ return inserted !== undefined;
113
+ }
@@ -1,86 +1,21 @@
1
1
  import { ExtensionHost } from "../extensions/host.js";
2
2
  import { KernelDb } from "../infra/database/kernel-db.js";
3
- import { TransactionHost } from "../infra/database/transaction-host.js";
4
- import { OrgLock } from "../orgs/org-lock.js";
5
- /** One tool of an extension with its switch in the org. */
6
- export interface OrgToolSwitch {
7
- tool: string;
8
- enabled: boolean;
9
- }
10
- /** An org agent whose current version selects the tool being switched off. */
3
+ /** A live org agent whose current version can use an extension tool. */
11
4
  export interface AffectedAgent {
12
5
  id: string;
13
6
  name: string;
14
7
  }
15
- /**
16
- * The result of {@link OrgToolSwitches.set}: the PCM §5 rule 8 preview of a switch-off (the org's
17
- * agents that selected the tool and the hash to confirm it with), or the switch applied.
18
- */
19
- export type OrgToolSwitchResult = {
20
- applied: false;
21
- affectedAgents: AffectedAgent[];
22
- confirm: string;
23
- } | {
24
- applied: true;
25
- };
26
- /** Model-visible (English): why a turned-off extension tool is not offered. */
8
+ /** Model-visible reason for a tool denied by the organization. */
27
9
  export declare const toolTurnedOffReason: (key: string) => string;
28
- /**
29
- * Per-org switches of single extension tools (layering spec A §7, table `org_tool_switches`): an
30
- * org admin turns off one tool an extension registers (`ctx.tools.register`); it is then not
31
- * offered to any agent of the org (`ToolRegistry.forAgent`) and refused if called
32
- * (`ToolPipeline`). No row means on. A row of a tool the extension stops registering is kept and
33
- * applies again if the tool comes back. Builtin and connector tools are out of scope. Read from PG
34
- * on every use, no in-process state.
35
- */
10
+ /** Broad-deny visibility and the affected-agent preview for an extension tool. */
36
11
  export declare class OrgToolSwitches {
37
12
  private readonly kdb;
38
- readonly txHost: TransactionHost;
39
13
  private readonly host;
40
- /** The org row lock: re-checks `org.extensions.manage` under the lock. */
41
- private readonly orgLock;
42
- constructor(kdb: KernelDb, txHost: TransactionHost, host: Pick<ExtensionHost, "tools" | "current">,
43
- /** The org row lock: re-checks `org.extensions.manage` under the lock. */
44
- orgLock: Pick<OrgLock, "lockAndAuthorize">);
14
+ constructor(kdb: KernelDb, host: Pick<ExtensionHost, "tools">);
45
15
  private get db();
46
- /** The tool names `plugin` registers on this replica, in registration order. */
47
- private registered;
48
- /**
49
- * The tools of an extension the org sees: running here and visible under plugin scope, else 404
50
- * `extension.not_found` (an invisible one is answered like an unknown one). An extension that
51
- * runs but registers no tools (a channel, a model provider) answers an empty list, not 404.
52
- */
53
- private toolsFor;
54
- /** The stored switches of the org (all extensions, or one), `false` ones only matter. */
55
- private offRows;
56
- /** Every tool the extension registers on this replica with its switch (default on). */
57
- list(orgId: string, plugin: string): Promise<OrgToolSwitch[]>;
58
- /**
59
- * What turning one tool off would affect (nothing written): the agents selecting it and the
60
- * confirm hash {@link set} takes, or null when it is off already. Unknown tool -> 404
61
- * `extension.tool_not_found`.
62
- */
63
- previewOff(orgId: string, plugin: string, tool: string): Promise<{
64
- affectedAgents: AffectedAgent[];
65
- confirm: string;
66
- } | null>;
67
- /** The model-visible keys (`plugin__<extension>__<tool>`) of the tools turned off in the org. */
68
16
  offKeys(orgId: string): Promise<Set<string>>;
69
- /** Whether the org turned off this tool. */
70
17
  isToolOff(orgId: string, plugin: string, tool: string): Promise<boolean>;
71
- /**
72
- * Switches one tool in the org. On applies at once. Off, while the tool is on: without
73
- * `confirm` the preview (the org's agents whose current version does not turn it off) and its hash,
74
- * with the current hash the switch is written (a changed preview -> 409 `plugin.switch_stale`).
75
- * A tool the extension does not register -> 404 `extension.tool_not_found`. A change writes the
76
- * audit row `extension.tool_switched`.
77
- */
78
- set(orgId: string, plugin: string, tool: string, enabled: boolean, actor: {
79
- accountId: string;
80
- tokenId?: string | undefined;
81
- /** Merged into the audit detail (a write made through the Platform tool). */
82
- auditDetail?: Record<string, unknown>;
83
- }, confirm?: string): Promise<OrgToolSwitchResult>;
18
+ affectedAgents(orgId: string, toolKey: string): Promise<AffectedAgent[]>;
84
19
  /**
85
20
  * The org's live agents whose current version has extension tool `tool` of `plugin` on: tools
86
21
  * are on by default (tools default-on spec §4), so every agent that does not turn it off.