@capybara-hq/kernel 0.1.0-rc.140 → 0.1.0-rc.142

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 (82) hide show
  1. package/dist/agents/models.controller.d.ts +9 -2
  2. package/dist/agents/models.controller.js +35 -4
  3. package/dist/catalog/catalog-scope.service.js +3 -0
  4. package/dist/catalog/catalog.module.js +8 -0
  5. package/dist/catalog/catalog.service.d.ts +2 -2
  6. package/dist/catalog/catalog.service.js +3 -3
  7. package/dist/catalog/component-scope.controller.d.ts +2 -1
  8. package/dist/catalog/component-scope.controller.js +5 -2
  9. package/dist/catalog/component-scope.service.d.ts +16 -0
  10. package/dist/catalog/component-scope.service.js +21 -1
  11. package/dist/catalog/enable-decision.d.ts +34 -0
  12. package/dist/catalog/enable-decision.js +17 -0
  13. package/dist/catalog/enable-requests.d.ts +186 -0
  14. package/dist/catalog/enable-requests.js +767 -0
  15. package/dist/catalog/enable-targets.d.ts +63 -0
  16. package/dist/catalog/enable-targets.js +94 -0
  17. package/dist/catalog/org-catalog.controller.d.ts +11 -3
  18. package/dist/catalog/org-catalog.controller.js +28 -5
  19. package/dist/catalog/org-catalog.schemas.d.ts +38 -0
  20. package/dist/catalog/org-catalog.schemas.js +31 -0
  21. package/dist/catalog/org-catalog.service.js +1 -1
  22. package/dist/catalog/org-extension.controller.d.ts +1 -1
  23. package/dist/catalog/owned-items.js +6 -1
  24. package/dist/catalog/plugin-install.js +7 -2
  25. package/dist/catalog/plugin-upgrade.js +3 -0
  26. package/dist/catalog/request-rules.d.ts +7 -5
  27. package/dist/catalog/request-rules.js +53 -14
  28. package/dist/catalog/requests.service.d.ts +137 -4
  29. package/dist/catalog/requests.service.js +574 -28
  30. package/dist/catalog/scope-writer.d.ts +20 -3
  31. package/dist/catalog/scope-writer.js +32 -3
  32. package/dist/config/schema.d.ts +1 -0
  33. package/dist/config/schema.js +10 -0
  34. package/dist/ctx/bus.js +3 -2
  35. package/dist/db/kernel-schema.d.ts +3 -2
  36. package/dist/errors.d.ts +7 -0
  37. package/dist/errors.js +7 -0
  38. package/dist/extensions/admin-ops.js +2 -0
  39. package/dist/extensions/admin-view.js +2 -1
  40. package/dist/extensions/host.js +1 -1
  41. package/dist/extensions/org-config.d.ts +8 -0
  42. package/dist/extensions/org-config.js +20 -5
  43. package/dist/extensions/permission-view.d.ts +7 -0
  44. package/dist/extensions/plugin-guides.d.ts +1 -1
  45. package/dist/extensions/plugin-guides.js +1 -1
  46. package/dist/extensions/plugin-items.d.ts +8 -0
  47. package/dist/extensions/plugin-items.js +8 -0
  48. package/dist/http/api.module.js +6 -0
  49. package/dist/infra/config/kernel-config.service.js +2 -0
  50. package/dist/infra/queue/run-job.js +3 -1
  51. package/dist/invalidation/hints.d.ts +56 -0
  52. package/dist/invalidation/hints.js +67 -0
  53. package/dist/invalidation/invalidation-hints.d.ts +24 -0
  54. package/dist/invalidation/invalidation-hints.js +59 -0
  55. package/dist/invalidation/invalidation-hints.module.d.ts +8 -0
  56. package/dist/invalidation/invalidation-hints.module.js +23 -0
  57. package/dist/invalidation/me-stream.controller.d.ts +30 -0
  58. package/dist/invalidation/me-stream.controller.js +100 -0
  59. package/dist/invalidation/me-stream.d.ts +67 -0
  60. package/dist/invalidation/me-stream.js +351 -0
  61. package/dist/invalidation/me-stream.module.d.ts +7 -0
  62. package/dist/invalidation/me-stream.module.js +22 -0
  63. package/dist/kernel.module.js +4 -0
  64. package/dist/models/enablement.d.ts +12 -0
  65. package/dist/models/enablement.js +32 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +2 -2
  68. package/dist/platform/ops/catalog-admin.ops.js +1 -1
  69. package/dist/platform/ops/extensions-admin.ops.js +17 -9
  70. package/dist/platform/ops/extensions.ops.js +6 -3
  71. package/dist/platform/ops/org-plugins.ops.js +1 -1
  72. package/dist/platform/ops/plugins.ops.js +1 -1
  73. package/dist/platform/ops/requests.ops.js +55 -1
  74. package/dist/platform/ops/unavailable.js +2 -2
  75. package/dist/tools/builtins/sandbox/common.d.ts +3 -3
  76. package/dist/tools/builtins/sandbox/common.js +3 -3
  77. package/dist/tools/connectors.controller.d.ts +8 -1
  78. package/dist/tools/connectors.controller.js +14 -1
  79. package/dist/tools/connectors.service.d.ts +7 -0
  80. package/dist/tools/connectors.service.js +30 -0
  81. package/package.json +1 -1
  82. package/src/migrations/0233_enable_request_targets.sql +64 -0
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The switch a point-of-use enable request asks the org admins to turn on, and the picker subject
3
+ * it was resolved from (org-usable spec 2026-12-02, `catalog_requests.detail.target`). Pure types
4
+ * and functions: the route schemas import this file.
5
+ */
6
+ /** What a member points at in a picker, and what an enable request targets. */
7
+ export declare const ENABLE_TARGET_KINDS: readonly ["plugin", "extension", "skill", "agent_template", "connector_template", "connector", "model"];
8
+ export type EnableTargetKind = (typeof ENABLE_TARGET_KINDS)[number];
9
+ /**
10
+ * A subject or a target: a plugin's catalog item id, an extension's name, a platform component's
11
+ * id, an org connector's id, or a model's canonical id ({@link encodeModelId}).
12
+ */
13
+ export interface EnableTarget {
14
+ kind: EnableTargetKind;
15
+ id: string;
16
+ }
17
+ /** The longest provider or model name a model id carries (the disabled-list routes' bound). */
18
+ export declare const MODEL_NAME_MAX = 200;
19
+ /** The longest subject id (a model id is the longest: two names in a JSON array). */
20
+ export declare const ENABLE_SUBJECT_ID_MAX = 512;
21
+ /**
22
+ * A model's id in a request: the canonical JSON tuple `["<provider>","<model>"]` (no spaces), so a
23
+ * provider and model name containing any separator can never collide with another pair.
24
+ */
25
+ export declare function encodeModelId(provider: string, model: string): string;
26
+ /**
27
+ * The provider and model of a canonical model id, or null when `id` is not one: not JSON, not an
28
+ * array of exactly two non-empty strings of at most {@link MODEL_NAME_MAX} characters, or not in
29
+ * the canonical form {@link encodeModelId} writes.
30
+ */
31
+ export declare function decodeModelId(id: string): {
32
+ provider: string;
33
+ model: string;
34
+ } | null;
35
+ /** A map key for a subject or target. */
36
+ export declare const targetKey: (t: EnableTarget) => string;
37
+ export declare const sameTarget: (a: EnableTarget, b: EnableTarget) => boolean;
38
+ /**
39
+ * An `enable` request's `detail` (0233): `target`, the switch an approval turns on; `subject`, what
40
+ * the member pointed at (equal to `target` when the subject is its own switch; legacy rows have
41
+ * none and count as their target); `bundle`, the plugin an extension or component target needs
42
+ * on (switching that plugin off makes the request stale); `cancelReason`, set when a switch change
43
+ * cancelled the pending request; `followers`, other members who asked for the same switch, each
44
+ * with their own subject and, once settled, their own outcome (they get their own notice);
45
+ * `dismissedBy`, the followers who dismissed that notice.
46
+ */
47
+ export interface EnableRequestDetail {
48
+ target: EnableTarget;
49
+ subject?: EnableTarget;
50
+ bundle?: string | null;
51
+ cancelReason?: "target_changed";
52
+ followers?: EnableFollower[];
53
+ dismissedBy?: string[];
54
+ }
55
+ /** Another member who asked for the same switch, with what they pointed at. */
56
+ export interface EnableFollower {
57
+ accountId: string;
58
+ subject: EnableTarget;
59
+ /** Set when the request is settled: whether their own subject is usable now. */
60
+ outcome?: "approved" | "target_changed";
61
+ }
62
+ /** Reads an `enable` request's detail; null when it carries no valid target. */
63
+ export declare function readEnableDetail(detail: unknown): EnableRequestDetail | null;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The switch a point-of-use enable request asks the org admins to turn on, and the picker subject
3
+ * it was resolved from (org-usable spec 2026-12-02, `catalog_requests.detail.target`). Pure types
4
+ * and functions: the route schemas import this file.
5
+ */
6
+ /** What a member points at in a picker, and what an enable request targets. */
7
+ export const ENABLE_TARGET_KINDS = [
8
+ "plugin",
9
+ "extension",
10
+ "skill",
11
+ "agent_template",
12
+ "connector_template",
13
+ "connector",
14
+ "model",
15
+ ];
16
+ /** The longest provider or model name a model id carries (the disabled-list routes' bound). */
17
+ export const MODEL_NAME_MAX = 200;
18
+ /** The longest subject id (a model id is the longest: two names in a JSON array). */
19
+ export const ENABLE_SUBJECT_ID_MAX = 512;
20
+ /**
21
+ * A model's id in a request: the canonical JSON tuple `["<provider>","<model>"]` (no spaces), so a
22
+ * provider and model name containing any separator can never collide with another pair.
23
+ */
24
+ export function encodeModelId(provider, model) {
25
+ return JSON.stringify([provider, model]);
26
+ }
27
+ /**
28
+ * The provider and model of a canonical model id, or null when `id` is not one: not JSON, not an
29
+ * array of exactly two non-empty strings of at most {@link MODEL_NAME_MAX} characters, or not in
30
+ * the canonical form {@link encodeModelId} writes.
31
+ */
32
+ export function decodeModelId(id) {
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(id);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ if (!Array.isArray(parsed) || parsed.length !== 2)
41
+ return null;
42
+ const [provider, model] = parsed;
43
+ if (typeof provider !== "string" || typeof model !== "string")
44
+ return null;
45
+ if (provider.length === 0 || model.length === 0)
46
+ return null;
47
+ if (provider.length > MODEL_NAME_MAX || model.length > MODEL_NAME_MAX)
48
+ return null;
49
+ if (encodeModelId(provider, model) !== id)
50
+ return null;
51
+ return { provider, model };
52
+ }
53
+ /** A map key for a subject or target. */
54
+ export const targetKey = (t) => `${t.kind}\u0000${t.id}`;
55
+ export const sameTarget = (a, b) => a.kind === b.kind && a.id === b.id;
56
+ const asTarget = (t) => {
57
+ const x = t;
58
+ return x && typeof x.id === "string" && ENABLE_TARGET_KINDS.includes(x.kind)
59
+ ? { kind: x.kind, id: x.id }
60
+ : undefined;
61
+ };
62
+ /** Reads an `enable` request's detail; null when it carries no valid target. */
63
+ export function readEnableDetail(detail) {
64
+ const d = detail;
65
+ const t = d?.target;
66
+ if (!t || typeof t.id !== "string" || !ENABLE_TARGET_KINDS.includes(t.kind))
67
+ return null;
68
+ const s = d.subject;
69
+ return {
70
+ target: { kind: t.kind, id: t.id },
71
+ ...(s && typeof s.id === "string" && ENABLE_TARGET_KINDS.includes(s.kind)
72
+ ? { subject: { kind: s.kind, id: s.id } }
73
+ : {}),
74
+ bundle: typeof d.bundle === "string" ? d.bundle : null,
75
+ ...(d.cancelReason === "target_changed" && { cancelReason: "target_changed" }),
76
+ followers: (Array.isArray(d.followers) ? d.followers : []).flatMap((f) => {
77
+ const subject = asTarget(f?.subject);
78
+ if (typeof f?.accountId !== "string" || subject === undefined)
79
+ return [];
80
+ return [
81
+ {
82
+ accountId: f.accountId,
83
+ subject,
84
+ ...((f.outcome === "approved" || f.outcome === "target_changed") && {
85
+ outcome: f.outcome,
86
+ }),
87
+ },
88
+ ];
89
+ }),
90
+ dismissedBy: Array.isArray(d.dismissedBy)
91
+ ? d.dismissedBy.filter((a) => typeof a === "string")
92
+ : [],
93
+ };
94
+ }
@@ -7,10 +7,10 @@ import { type OrgContext } from "../orgs/org.guard.js";
7
7
  import type { ConnectorDetail, ToolIssue } from "../tools/connectors.service.js";
8
8
  import type { MarketplaceImportResult } from "./catalog.service.js";
9
9
  import type { CatalogIcon, OrgCatalogDetail, OrgCatalogItem, OrgInstallResult } from "./catalog-content.js";
10
- import { CatalogGuideQuery, CatalogMarketplaceRequestBody, CatalogRequestBody, CatalogRequestsListQuery, NetworkRequestBody, OrgPluginInstallBody, OrgPluginSwitchBody } from "./org-catalog.schemas.js";
10
+ import { CatalogGuideQuery, CatalogMarketplaceRequestBody, CatalogRequestBody, CatalogRequestsListQuery, EnableRequestBody, NetworkRequestBody, OrgPluginInstallBody, OrgPluginSwitchBody } from "./org-catalog.schemas.js";
11
11
  import { OrgCatalogService } from "./org-catalog.service.js";
12
12
  import { PluginInstaller, type PluginInstallView, type UninstallPreview, type UninstallReport } from "./plugin-install.js";
13
- import { CatalogRequestsService, type CatalogRequestView } from "./requests.service.js";
13
+ import { CatalogRequestsService, type CatalogRequestView, type OrgDecisionResult } from "./requests.service.js";
14
14
  declare const TemplateConnectorBody: z.ZodObject<{
15
15
  name: z.ZodOptional<z.ZodString>;
16
16
  config: z.ZodObject<{
@@ -38,6 +38,8 @@ declare const DecideBody: z.ZodObject<{
38
38
  * - `POST catalog/:itemId/requests` (`catalog.request`; `access` needs an org admin): requests
39
39
  * under plugin scope (spec §5.1), `enable` into the org admins' inbox, `access` to the super
40
40
  * admin; `POST marketplace-requests` (org admins): an `import` request for a marketplace entry;
41
+ * - `POST catalog-requests/enable` (`catalog.request`): a member asks the org admins to turn on
42
+ * what a picker subject needs (the kernel resolves the owning switch; org-usable spec);
41
43
  * - `POST catalog-requests/network` (`catalog.request`, web sessions only): a member asks the org
42
44
  * admins to allow hosts in the org's sandbox network (network ask-to-allow spec §5.3);
43
45
  * - `PUT catalog/:itemId/switch` (scope phase 1): `{ enabled: true, inputs? }` installs -> 200 `{ item }`;
@@ -142,9 +144,15 @@ export declare class OrgCatalogController {
142
144
  networkRequest(principal: Principal, org: OrgContext, body: z.infer<typeof NetworkRequestBody>): Promise<{
143
145
  request: CatalogRequestView;
144
146
  }>;
145
- decide(principal: Principal, org: OrgContext, id: string, body: z.infer<typeof DecideBody>): Promise<{
147
+ /**
148
+ * A member asks the org admins to turn on what a picker subject needs ("Ask to turn on") ->
149
+ * 201 `{ request }`; the org's pending request for the same switch comes back as 200.
150
+ * Registered before `catalog-requests/:id/...`: `enable` is a literal segment.
151
+ */
152
+ enableRequest(principal: Principal, org: OrgContext, body: z.infer<typeof EnableRequestBody>, reply: FastifyReply): Promise<{
146
153
  request: CatalogRequestView;
147
154
  }>;
155
+ decide(principal: Principal, org: OrgContext, id: string, body: z.infer<typeof DecideBody>): Promise<OrgDecisionResult>;
148
156
  /** The requester dismisses a decided request from the inbox -> 204. */
149
157
  dismiss(principal: Principal, org: OrgContext, id: string): Promise<void>;
150
158
  }
@@ -16,10 +16,10 @@ import { createZodDto } from "../infra/validation/create-zod-dto.js";
16
16
  import { ZBody, ZQuery } from "../infra/validation/zod-params.js";
17
17
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
18
18
  import { roleAtLeast } from "../orgs/roles.js";
19
- import { CatalogGuideQuery, CatalogMarketplaceRequestBody, CatalogRequestBody, CatalogRequestsListQuery, NetworkRequestBody, OrgPluginInstallBody, OrgPluginSwitchBody, OrgTemplateConnectorSchema, } from "./org-catalog.schemas.js";
19
+ import { CatalogGuideQuery, CatalogMarketplaceRequestBody, CatalogRequestBody, CatalogRequestsListQuery, EnableRequestBody, NetworkRequestBody, OrgPluginInstallBody, OrgPluginSwitchBody, OrgTemplateConnectorSchema, } from "./org-catalog.schemas.js";
20
20
  import { OrgCatalogService } from "./org-catalog.service.js";
21
21
  import { PluginInstaller, } from "./plugin-install.js";
22
- import { CatalogRequestsService } from "./requests.service.js";
22
+ import { CatalogRequestsService, } from "./requests.service.js";
23
23
  const TemplateConnectorBody = OrgTemplateConnectorSchema;
24
24
  /**
25
25
  * 条目图标的响应头:图标可能是 SVG(可含脚本),只许网页以 `<img>` 显示;直接打开时 CSP sandbox 禁止脚本与一切外部
@@ -52,6 +52,8 @@ class CatalogRequestBodyDto extends createZodDto(CatalogRequestBody, "CatalogReq
52
52
  }
53
53
  class NetworkRequestBodyDto extends createZodDto(NetworkRequestBody, "NetworkRequestBody") {
54
54
  }
55
+ class EnableRequestBodyDto extends createZodDto(EnableRequestBody, "EnableRequestBody") {
56
+ }
55
57
  class CatalogMarketplaceRequestBodyDto extends createZodDto(CatalogMarketplaceRequestBody, "CatalogMarketplaceRequestBody") {
56
58
  }
57
59
  /**
@@ -60,6 +62,8 @@ class CatalogMarketplaceRequestBodyDto extends createZodDto(CatalogMarketplaceRe
60
62
  * - `POST catalog/:itemId/requests` (`catalog.request`; `access` needs an org admin): requests
61
63
  * under plugin scope (spec §5.1), `enable` into the org admins' inbox, `access` to the super
62
64
  * admin; `POST marketplace-requests` (org admins): an `import` request for a marketplace entry;
65
+ * - `POST catalog-requests/enable` (`catalog.request`): a member asks the org admins to turn on
66
+ * what a picker subject needs (the kernel resolves the owning switch; org-usable spec);
63
67
  * - `POST catalog-requests/network` (`catalog.request`, web sessions only): a member asks the org
64
68
  * admins to allow hosts in the org's sandbox network (network ask-to-allow spec §5.3);
65
69
  * - `PUT catalog/:itemId/switch` (scope phase 1): `{ enabled: true, inputs? }` installs -> 200 `{ item }`;
@@ -208,12 +212,23 @@ let OrgCatalogController = class OrgCatalogController {
208
212
  const p = requireUser(principal);
209
213
  return { request: await this.requests.requestNetwork(org.orgId, p.account.id, body) };
210
214
  }
215
+ /**
216
+ * A member asks the org admins to turn on what a picker subject needs ("Ask to turn on") ->
217
+ * 201 `{ request }`; the org's pending request for the same switch comes back as 200.
218
+ * Registered before `catalog-requests/:id/...`: `enable` is a literal segment.
219
+ */
220
+ async enableRequest(principal, org, body, reply) {
221
+ const p = requireUser(principal);
222
+ const tokenId = patTokenId(p);
223
+ const { request, created } = await this.requests.requestEnable(org.orgId, p.account.id, { subject: body.subject, ...(body.note !== undefined && { note: body.note }) }, tokenId !== undefined ? { actorTokenId: tokenId } : {});
224
+ reply.status(created ? 201 : 200);
225
+ return { request };
226
+ }
211
227
  async decide(principal, org, id, body) {
212
228
  const p = requireUser(principal);
213
229
  const tokenId = patTokenId(p);
214
- return {
215
- request: await this.requests.decideOrg(org.orgId, p.account.id, id, body, tokenId !== undefined ? { actorTokenId: tokenId } : {}),
216
- };
230
+ // `notice: "needs_another_switch"`: the switch is on, the member's item needs another one
231
+ return this.requests.decideOrg(org.orgId, p.account.id, id, body, tokenId !== undefined ? { actorTokenId: tokenId } : {});
217
232
  }
218
233
  /** The requester dismisses a decided request from the inbox -> 204. */
219
234
  async dismiss(principal, org, id) {
@@ -319,6 +334,14 @@ __decorate([
319
334
  __param(1, CurrentOrg()),
320
335
  __param(2, ZBody(NetworkRequestBodyDto))
321
336
  ], OrgCatalogController.prototype, "networkRequest", null);
337
+ __decorate([
338
+ Post("catalog-requests/enable"),
339
+ OrgAction("catalog.request"),
340
+ __param(0, CurrentPrincipal()),
341
+ __param(1, CurrentOrg()),
342
+ __param(2, ZBody(EnableRequestBodyDto)),
343
+ __param(3, Res({ passthrough: true }))
344
+ ], OrgCatalogController.prototype, "enableRequest", null);
322
345
  __decorate([
323
346
  Post("catalog-requests/:id/decide"),
324
347
  HttpCode(200),
@@ -7,6 +7,44 @@ export declare const CatalogRequestBody: z.ZodObject<{
7
7
  }>;
8
8
  note: z.ZodOptional<z.ZodString>;
9
9
  }, z.core.$strict>;
10
+ /**
11
+ * What a member points at in a picker (org-usable spec "Members and guests"): a plugin (its
12
+ * catalog item id), an extension (its name), a platform skill, agent template or connector
13
+ * template (its component id), an org connector (its id) or a model (the canonical JSON tuple
14
+ * `["<provider>","<model>"]`, `encodeModelId` in enable-targets.ts).
15
+ */
16
+ export declare const EnableRequestSubject: z.ZodObject<{
17
+ kind: z.ZodEnum<{
18
+ agent_template: "agent_template";
19
+ connector: "connector";
20
+ connector_template: "connector_template";
21
+ extension: "extension";
22
+ model: "model";
23
+ plugin: "plugin";
24
+ skill: "skill";
25
+ }>;
26
+ id: z.ZodString;
27
+ }, z.core.$strict>;
28
+ /**
29
+ * A member asks the org admins to turn on what a picker subject needs
30
+ * (`POST /api/v1/orgs/:orgId/catalog-requests/enable`, Platform `plugins.request-enable`): the
31
+ * kernel resolves the owning switch; an optional note says why.
32
+ */
33
+ export declare const EnableRequestBody: z.ZodObject<{
34
+ subject: z.ZodObject<{
35
+ kind: z.ZodEnum<{
36
+ agent_template: "agent_template";
37
+ connector: "connector";
38
+ connector_template: "connector_template";
39
+ extension: "extension";
40
+ model: "model";
41
+ plugin: "plugin";
42
+ skill: "skill";
43
+ }>;
44
+ id: z.ZodString;
45
+ }, z.core.$strict>;
46
+ note: z.ZodOptional<z.ZodString>;
47
+ }, z.core.$strict>;
10
48
  /** The most hosts one network request asks for. */
11
49
  export declare const NETWORK_REQUEST_HOSTS_MAX = 20;
12
50
  /**
@@ -1,12 +1,42 @@
1
1
  import { secret, validateAllowHost } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import { CredentialValue } from "../tools/connectors.schemas.js";
4
+ import { decodeModelId, ENABLE_SUBJECT_ID_MAX, ENABLE_TARGET_KINDS } from "./enable-targets.js";
4
5
  export const CatalogRequestBody = z
5
6
  .object({
6
7
  kind: z.enum(["access", "enable"]),
7
8
  note: z.string().max(1000).optional(),
8
9
  })
9
10
  .strict();
11
+ /**
12
+ * What a member points at in a picker (org-usable spec "Members and guests"): a plugin (its
13
+ * catalog item id), an extension (its name), a platform skill, agent template or connector
14
+ * template (its component id), an org connector (its id) or a model (the canonical JSON tuple
15
+ * `["<provider>","<model>"]`, `encodeModelId` in enable-targets.ts).
16
+ */
17
+ export const EnableRequestSubject = z
18
+ .object({
19
+ kind: z.enum(ENABLE_TARGET_KINDS),
20
+ id: z.string().min(1).max(ENABLE_SUBJECT_ID_MAX),
21
+ })
22
+ .strict()
23
+ .superRefine((s, ctx) => {
24
+ if (s.kind === "model" && decodeModelId(s.id) === null) {
25
+ ctx.addIssue({
26
+ code: "custom",
27
+ path: ["id"],
28
+ message: 'A model id is the JSON array ["<provider>","<model>"] with no spaces',
29
+ });
30
+ }
31
+ });
32
+ /**
33
+ * A member asks the org admins to turn on what a picker subject needs
34
+ * (`POST /api/v1/orgs/:orgId/catalog-requests/enable`, Platform `plugins.request-enable`): the
35
+ * kernel resolves the owning switch; an optional note says why.
36
+ */
37
+ export const EnableRequestBody = z
38
+ .object({ subject: EnableRequestSubject, note: z.string().max(1000).optional() })
39
+ .strict();
10
40
  /** The most hosts one network request asks for. */
11
41
  export const NETWORK_REQUEST_HOSTS_MAX = 20;
12
42
  /**
@@ -149,6 +179,7 @@ export const ORG_CATALOG_ROUTES = [
149
179
  body: CatalogRequestBody,
150
180
  },
151
181
  { route: "POST /api/v1/orgs/:orgId/marketplace-requests", body: CatalogMarketplaceRequestBody },
182
+ { route: "POST /api/v1/orgs/:orgId/catalog-requests/enable", body: EnableRequestBody },
152
183
  {
153
184
  route: "POST /api/v1/orgs/:orgId/catalog/:itemId/install",
154
185
  params: CatalogItemPathParams,
@@ -588,7 +588,7 @@ let OrgCatalogService = class OrgCatalogService {
588
588
  throw new ApiError("plugin.switch_stale", "The switch preview changed; review it and confirm again");
589
589
  }
590
590
  }
591
- await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, enabled, actor);
591
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, enabled, actor, opts);
592
592
  await audit(this.db, {
593
593
  actorAccountId: actor,
594
594
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
@@ -28,7 +28,7 @@ export type OrgExtensionItem = OrgExtensionView & {
28
28
  };
29
29
  /**
30
30
  * What a member sees of an extension: its state and the points it provides (names only, what the
31
- * Extensions page sorts by), never the permission list, the suggested appearance (members cannot
31
+ * Plugins surface sorts by), never the permission list, the suggested appearance (members cannot
32
32
  * apply it) or the client build (part of the permission review).
33
33
  */
34
34
  export type OrgExtensionMemberItem = Omit<OrgExtensionItem, "permissions" | "suggestedAppearance" | "client">;
@@ -36,6 +36,7 @@ import { CatalogScopeService } from "./catalog-scope.service.js";
36
36
  import { notOwnedError } from "./component-promotion.js";
37
37
  import { agentsUsing, COMPONENT_KINDS, componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "./component-state.js";
38
38
  import { EFFECT_CANDIDATES_LOCK } from "./effect-work.js";
39
+ import { reconcileEnableRequestsOf } from "./enable-requests.js";
39
40
  import { orgsUsing } from "./ownership.js";
40
41
  import { PluginInstaller } from "./plugin-install.js";
41
42
  import { ScopeStillWanted } from "./scope-state.js";
@@ -162,8 +163,10 @@ let OwnedItems = class OwnedItems {
162
163
  .set({ shareable, updated_at: sql `now()` })
163
164
  .where("id", "=", c.id)
164
165
  .execute();
165
- if (!shareable)
166
+ if (!shareable) {
166
167
  await narrowComponentOnUnshare(this.db, actor, c);
168
+ await reconcileEnableRequestsOf(this.db, { kind, id: c.id }, actor);
169
+ }
167
170
  }
168
171
  }
169
172
  await audit(this.db, {
@@ -454,6 +457,8 @@ let OwnedItems = class OwnedItems {
454
457
  .where("item_id", "=", item.id)
455
458
  .where("org_id", "=", owner)
456
459
  .execute();
460
+ // the former owner's named entry went: its pending enable requests are checked again
461
+ await reconcileEnableRequestsOf(t, { kind: "plugin", id: item.id }, actor);
457
462
  }
458
463
  await t
459
464
  .deleteFrom("catalog_item_org_switches")
@@ -375,7 +375,12 @@ let PluginInstaller = class PluginInstaller {
375
375
  if (existing?.version != null)
376
376
  return;
377
377
  if (switchOn) {
378
- await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: plan.itemId }, orgId, true, actor);
378
+ // the setup failed: pending enable requests stay pending (never "approved" for a failed
379
+ // setup); the failure shows in the org's setup diagnostics
380
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: plan.itemId }, orgId, true, actor, {
381
+ ...opts,
382
+ settle: false,
383
+ });
379
384
  }
380
385
  const work = await this.db
381
386
  .updateTable("plugin_effect_work")
@@ -863,7 +868,7 @@ let PluginInstaller = class PluginInstaller {
863
868
  }
864
869
  await assertItemInstallable(t, orgId, itemId, ctx.approvedBy ?? itemId);
865
870
  if (ctx.switchOn === true && ctx.parent === undefined) {
866
- await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, true, actor);
871
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, true, actor, opts);
867
872
  }
868
873
  if (!appliesOrgEffects(plan)) {
869
874
  if (ctx.parent === undefined) {
@@ -50,6 +50,7 @@ import { agentsUsing, clashingOrgSkills, clashingPlatformSkills, componentOn, co
50
50
  import { credentialKey } from "./credential-key.js";
51
51
  import { refreshCatalogDependencyEdges } from "./dependency-edges.js";
52
52
  import { EFFECT_CANDIDATES_LOCK } from "./effect-work.js";
53
+ import { reconcileEnableRequestsOf } from "./enable-requests.js";
53
54
  import { CatalogItemLock } from "./locks.js";
54
55
  import { requireMarketplacePublisher } from "./marketplace-fetch.js";
55
56
  import { orgPluginEffectIntent, orgUsable } from "./org-intent.js";
@@ -610,6 +611,8 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
610
611
  .set({ deleted_at: now, updated_at: now })
611
612
  .where("id", "=", c.id)
612
613
  .execute();
614
+ // every org's pending enable requests that name it (target, subject or a follower's)
615
+ await reconcileEnableRequestsOf(t, { kind: c.kind, id: c.id }, null);
613
616
  }
614
617
  // Pins of linked copies: moved to the plugin's version (spec §7.1)
615
618
  for (const c of diff.components) {
@@ -35,8 +35,10 @@ export interface RequestActorOpts {
35
35
  }
36
36
  /**
37
37
  * Cancels catalog requests still pending in the caller's transaction (`db` is its handle; when the
38
- * item or the org is deleted), status `cancelled` (the decider is the actor). Each one audits
39
- * `catalog.request_cancelled` (with the reason). Returns how many were cancelled.
38
+ * item or the org is deleted), status `cancelled` (the decider is the actor). For an item, that is
39
+ * its own requests and the enable requests that target it or need it on (`detail.bundle`: an
40
+ * extension, component, connector or model of it). Each one audits `catalog.request_cancelled`
41
+ * (with the reason). Returns how many were cancelled.
40
42
  */
41
43
  export declare function cancelPendingRequests(db: KernelSchemaDb, where: {
42
44
  itemId: string;
@@ -45,9 +47,9 @@ export declare function cancelPendingRequests(db: KernelSchemaDb, where: {
45
47
  }, actor: string | null, reason: "item_removed" | "org_deleted", opts?: RequestActorOpts): Promise<number>;
46
48
  /**
47
49
  * After an install (or an upgrade) of the item in the org, in the caller's transaction: the org's
48
- * pending requests for the item (a member's `enable`, an `access` the scope has since granted) are
49
- * approved with the installer as the decider (null for the scope sync). Audits
50
- * `catalog.request_decided` with `installed: true`.
50
+ * pending `access` request the scope has since granted is approved with the installer as the
51
+ * decider (null for the scope sync), audited `catalog.request_decided` with `installed: true`;
52
+ * the pending enable requests that target the plugin are settled ({@link settleEnableRequests}).
51
53
  */
52
54
  export declare function resolveRequestsByInstall(db: KernelSchemaDb, orgId: string, itemId: string, actor: string | null, opts?: RequestActorOpts): Promise<void>;
53
55
  /** The pending `import` request linked to a staged import (its approval prepared it), if any. */
@@ -2,6 +2,8 @@ import { sql } from "kysely";
2
2
  import { ApiError } from "../errors.js";
3
3
  import { extensionSourcesQuery } from "../extensions/plugin-items.js";
4
4
  import { audit } from "../identity/audit.js";
5
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
6
+ import { settleEnableRequests } from "./enable-requests.js";
5
7
  import { isUsable } from "./ownership.js";
6
8
  import { visibleTo } from "./scope.js";
7
9
  /**
@@ -123,34 +125,69 @@ export async function assertPluginSourcesInstallable(t, orgId, plugin) {
123
125
  }
124
126
  /**
125
127
  * Cancels catalog requests still pending in the caller's transaction (`db` is its handle; when the
126
- * item or the org is deleted), status `cancelled` (the decider is the actor). Each one audits
127
- * `catalog.request_cancelled` (with the reason). Returns how many were cancelled.
128
+ * item or the org is deleted), status `cancelled` (the decider is the actor). For an item, that is
129
+ * its own requests and the enable requests that target it or need it on (`detail.bundle`: an
130
+ * extension, component, connector or model of it). Each one audits `catalog.request_cancelled`
131
+ * (with the reason). Returns how many were cancelled.
128
132
  */
129
133
  export async function cancelPendingRequests(db, where, actor, reason, opts = {}) {
130
- let q = db
131
- .updateTable("catalog_requests")
132
- .set({ status: "cancelled", decided_by: actor, decided_at: sql `now()` })
133
- .where("status", "=", "pending");
134
- q =
135
- "itemId" in where ? q.where("item_id", "=", where.itemId) : q.where("org_id", "=", where.orgId);
136
- const rows = await q.returning(["id", "org_id", "item_id", "kind"]).execute();
134
+ // Rows are locked in id order first, as settlement and reconciliation lock them (no deadlock),
135
+ // then cancelled by id
136
+ const cancel = async (ids) => {
137
+ if (ids.length === 0)
138
+ return [];
139
+ // org-filter: by the ids locked just before (of every org for a removed item)
140
+ const done = await db
141
+ .updateTable("catalog_requests")
142
+ .set({ status: "cancelled", decided_by: actor, decided_at: sql `now()` })
143
+ .where("id", "in", [...ids])
144
+ .returning(["id", "org_id", "item_id", "kind"])
145
+ .execute();
146
+ return done;
147
+ };
148
+ const rows = "itemId" in where
149
+ ? // An item's requests come from every org (another org's request for a shared item, an
150
+ // owner's delete running under the owner's scope): deployment-wide
151
+ await asPlatform("cancel every org's pending requests for a removed item", async () => {
152
+ // org-filter: deployment-wide: requests of every org for the removed item
153
+ const locked = await db
154
+ .selectFrom("catalog_requests")
155
+ .select("id")
156
+ .where("status", "=", "pending")
157
+ .where((eb) => eb.or([
158
+ eb("item_id", "=", where.itemId),
159
+ sql `(kind = 'enable' AND (detail ->> 'bundle' = ${where.itemId} OR detail -> 'target' ->> 'id' = ${where.itemId}))`,
160
+ ]))
161
+ .orderBy("id")
162
+ .forUpdate()
163
+ .execute();
164
+ return cancel(locked.map((r) => r.id));
165
+ })
166
+ : await cancel((await db
167
+ .selectFrom("catalog_requests")
168
+ .select("id")
169
+ .where("status", "=", "pending")
170
+ .where("org_id", "=", where.orgId)
171
+ .orderBy("id")
172
+ .forUpdate()
173
+ .execute()).map((r) => r.id));
137
174
  for (const r of rows) {
138
- await audit(db, {
175
+ await withOrgScope(r.org_id, () => audit(db, {
139
176
  actorAccountId: actor,
140
177
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
141
178
  orgId: r.org_id,
142
179
  action: "catalog.request_cancelled",
143
180
  target: r.id,
144
181
  detail: { itemId: r.item_id, kind: r.kind, reason },
145
- });
182
+ }));
146
183
  }
147
184
  return rows.length;
148
185
  }
149
186
  /**
150
187
  * After an install (or an upgrade) of the item in the org, in the caller's transaction: the org's
151
- * pending requests for the item (a member's `enable`, an `access` the scope has since granted) are
152
- * approved with the installer as the decider (null for the scope sync). Audits
153
- * `catalog.request_decided` with `installed: true`.
188
+ * pending `access` request the scope has since granted is approved with the installer as the
189
+ * decider (null for the scope sync), audited `catalog.request_decided` with `installed: true`;
190
+ * the pending enable requests that target the plugin are settled ({@link settleEnableRequests}).
154
191
  */
155
192
  export async function resolveRequestsByInstall(db, orgId, itemId, actor, opts = {}) {
156
193
  const rows = await db
@@ -158,6 +195,7 @@ export async function resolveRequestsByInstall(db, orgId, itemId, actor, opts =
158
195
  .set({ status: "approved", decided_by: actor, decided_at: sql `now()` })
159
196
  .where("org_id", "=", orgId)
160
197
  .where("item_id", "=", itemId)
198
+ .where("kind", "<>", "enable")
161
199
  .where("status", "=", "pending")
162
200
  .returning(["id", "kind"])
163
201
  .execute();
@@ -171,6 +209,7 @@ export async function resolveRequestsByInstall(db, orgId, itemId, actor, opts =
171
209
  detail: { itemId, kind: r.kind, decision: "approve", installed: true },
172
210
  });
173
211
  }
212
+ await settleEnableRequests(db, orgId, { kind: "plugin", id: itemId }, actor, opts);
174
213
  }
175
214
  /** The pending `import` request linked to a staged import (its approval prepared it), if any. */
176
215
  // org-filter: by the staging id of the confirm's own staging row (ownStaging checked it); a platform