@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
@@ -40,6 +40,7 @@ import { RedisModule } from "./infra/redis/redis.module.js";
40
40
  import { KernelThrottlerModule } from "./infra/throttler/throttler.module.js";
41
41
  import { KERNEL_POOL, REDIS } from "./infra/tokens.js";
42
42
  import { ValidationModule } from "./infra/validation/validation.module.js";
43
+ import { InvalidationHintsModule } from "./invalidation/invalidation-hints.module.js";
43
44
  import { KernelLifecycle } from "./lifecycle/kernel-lifecycle.js";
44
45
  import { KERNEL_APP_OPTIONS } from "./lifecycle/tokens.js";
45
46
  import { createConfiguredLogger } from "./log-config.js";
@@ -142,6 +143,9 @@ let KernelModule = KernelModule_1 = class KernelModule {
142
143
  TriggerEventsModule,
143
144
  // ctx.inbox: personal inbox items extensions post (the host finds it at the time of use)
144
145
  InboxItemsModule,
146
+ // account invalidation hints: writers on every role (api requests, worker jobs, gateway
147
+ // events) publish them; the streams that deliver them are the api role's (MeStreamModule)
148
+ InvalidationHintsModule,
145
149
  // ctx.agents / ctx.conversations / ctx.people: read-only org facts (found at the time of use)
146
150
  PluginReadsModule,
147
151
  // ctx.conversations' external methods and the external conversation calls' queue (found at
@@ -1,9 +1,11 @@
1
+ import { type ModelListing, type RequestableFields } from "../catalog/enable-requests.js";
1
2
  import { ExtensionRegistry } from "../extensions/registry.js";
2
3
  import { SuperAdminLock } from "../identity/super-admin.js";
3
4
  import { CacheService } from "../infra/cache/cache.service.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
7
  import { OrgLock } from "../orgs/org-lock.js";
8
+ import type { OrgRole } from "../orgs/roles.js";
7
9
  /** The key of a model in a disabled set: `provider\u0000model`. */
8
10
  export declare const modelKey: (provider: string, model: string) => string;
9
11
  /** An agent whose current version uses a newly disabled model as its main model or fallback. */
@@ -70,6 +72,16 @@ export declare class ModelEnablement {
70
72
  * to evict).
71
73
  */
72
74
  enabledIn(orgId: string): Promise<Set<string>>;
75
+ /**
76
+ * The picker projection of models the org disabled (org-usable spec "Members and guests"): for
77
+ * each `{ provider, model }` whose owning switch a reader of `role` may ask an org admin to turn
78
+ * on, `requestable: true` and the org's pending request for it, by {@link modelKey}. `listing`
79
+ * is what the providers list for the org (read once by the caller). Set-based.
80
+ */
81
+ requestable(orgId: string, role: OrgRole, models: readonly {
82
+ provider: string;
83
+ model: string;
84
+ }[], listing: ModelListing): Promise<Map<string, RequestableFields>>;
73
85
  /** Whether neither the platform nor `orgId` disabled the model (the lists only; see the class). */
74
86
  isEnabled(orgId: string, provider: string, model: string): Promise<boolean>;
75
87
  /**
@@ -8,6 +8,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { Inject, Injectable, Module } from "@nestjs/common";
11
+ import { cancelEnableRequestsOfPlatformModels, requestableSubjects, settleEnableRequests, } from "../catalog/enable-requests.js";
12
+ import { encodeModelId, targetKey } from "../catalog/enable-targets.js";
11
13
  import { ApiError } from "../errors.js";
12
14
  import { enabledExtensionsQuery } from "../extensions/enabled.js";
13
15
  import { ExtensionRegistry, ExtensionRegistryModule } from "../extensions/registry.js";
@@ -83,6 +85,26 @@ let ModelEnablement = class ModelEnablement {
83
85
  const rows = await enabledExtensionsQuery(this.db, orgId).execute();
84
86
  return new Set(rows.map((r) => r.plugin));
85
87
  }
88
+ /**
89
+ * The picker projection of models the org disabled (org-usable spec "Members and guests"): for
90
+ * each `{ provider, model }` whose owning switch a reader of `role` may ask an org admin to turn
91
+ * on, `requestable: true` and the org's pending request for it, by {@link modelKey}. `listing`
92
+ * is what the providers list for the org (read once by the caller). Set-based.
93
+ */
94
+ async requestable(orgId, role, models, listing) {
95
+ const subjects = models.map((m) => ({
96
+ kind: "model",
97
+ id: encodeModelId(m.provider, m.model),
98
+ }));
99
+ const fields = await requestableSubjects(this.db, orgId, role, subjects, { models: listing });
100
+ const out = new Map();
101
+ for (const m of models) {
102
+ const f = fields.get(targetKey({ kind: "model", id: encodeModelId(m.provider, m.model) }));
103
+ if (f !== undefined)
104
+ out.set(modelKey(m.provider, m.model), f);
105
+ }
106
+ return out;
107
+ }
86
108
  /** Whether neither the platform nor `orgId` disabled the model (the lists only; see the class). */
87
109
  async isEnabled(orgId, provider, model) {
88
110
  const key = modelKey(provider, model);
@@ -139,6 +161,16 @@ let ModelEnablement = class ModelEnablement {
139
161
  })))
140
162
  .execute();
141
163
  }
164
+ // models the platform disabled: every org's pending requests for them are cancelled
165
+ if (orgId === null) {
166
+ await cancelEnableRequestsOfPlatformModels(this.db, provider, added, actor.accountId);
167
+ }
168
+ // models an org admin switched back on settle the org's pending enable requests for them
169
+ if (orgId !== null) {
170
+ for (const model of removed) {
171
+ await settleEnableRequests(this.db, orgId, { kind: "model", id: encodeModelId(provider, model) }, actor.accountId, { ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }) });
172
+ }
173
+ }
142
174
  if (added.length > 0 || removed.length > 0) {
143
175
  await audit(this.db, {
144
176
  actorAccountId: actor.accountId,
@@ -799,6 +799,11 @@ export const PLATFORM_EXCLUSIONS = [
799
799
  category: "transport",
800
800
  reason: "Server-sent event stream of UI invalidations",
801
801
  },
802
+ {
803
+ route: "GET /api/v1/orgs/:orgId/me/stream",
804
+ category: "transport",
805
+ reason: "Server-sent event stream of inbox and request invalidations",
806
+ },
802
807
  {
803
808
  route: "GET /api/v1/admin/ui/contributions",
804
809
  category: "internal",
@@ -101,7 +101,7 @@ function attentionRows(a) {
101
101
  name: localized(e.displayName, e.name).en,
102
102
  state: e.status,
103
103
  reason: e.reason,
104
- next: `Fix it on the extension's page in the admin console (/admin/extensions/${e.name}).`,
104
+ next: `Fix it on the extension's tab of its plugin in the admin console's Plugins (/admin/plugins/extensions/${encodeURIComponent(e.name)} opens it).`,
105
105
  })),
106
106
  ...a.updates.map((u) => ({
107
107
  kind: "update",
@@ -118,7 +118,7 @@ function attentionRows(a) {
118
118
  state: p.problem === "list_failed" ? "error" : "ok",
119
119
  reason: p.problem,
120
120
  next: p.problem === "list_failed"
121
- ? `Check the provider's deployment config and connection on its extension page (/admin/extensions/${p.plugin}); the models page (/admin/models) shows the list.`
121
+ ? `Check the provider's deployment config and connection on its Extension tab in the admin console's Plugins (/admin/plugins/extensions/${encodeURIComponent(p.plugin)} opens it); the models page (/admin/models) shows the list.`
122
122
  : "The provider lists no chat model that is switched on: switch one on in the admin console (/admin/models) or check the provider's config.",
123
123
  })),
124
124
  ...a.outbox.map((o) => ({
@@ -695,7 +695,7 @@ let CatalogAdminOperations = class CatalogAdminOperations {
695
695
  },
696
696
  {
697
697
  code: "catalog.extension_enabled",
698
- next: "The plugin's extension (named in the message) is still enabled on the platform: disable it first with extensions.platform-disable (or in the admin console under Extensions), then delete the plugin again.",
698
+ next: "The plugin's extension (named in the message) is still enabled on the platform: disable it first with extensions.platform-disable (or with the deployment switch on the plugin's Extension tab in the admin console), then delete the plugin again.",
699
699
  },
700
700
  ],
701
701
  precheck: async (i, ctx) => {
@@ -122,7 +122,7 @@ const why = (v) => {
122
122
  const others = v.conflict.providers.map((p) => `${localized(p.displayName, p.name).en} (${p.name})`);
123
123
  return {
124
124
  ...fields,
125
- next: `Only one extension may provide ${v.conflict.extensionPoint}, and ${others.join(", ")} already does. Disable it (extensions.platform-disable, or the admin console → Extensions) and ${enName(v)} loads by itself, no restart.`,
125
+ next: `Only one extension may provide ${v.conflict.extensionPoint}, and ${others.join(", ")} already does. Disable it (extensions.platform-disable, or the deployment switch on its Extension tab in the admin console's Plugins) and ${enName(v)} loads by itself, no restart.`,
126
126
  };
127
127
  };
128
128
  /** An extension as `extensions.platform-list` shows it: a compact row. */
@@ -134,6 +134,8 @@ const row = (v) => ({
134
134
  version: v.version,
135
135
  enabledOrgs: v.enabledOrgs,
136
136
  required: v.required,
137
+ canonicalItemId: v.canonicalItemId,
138
+ sourceItemIds: v.sourceItemIds,
137
139
  });
138
140
  /**
139
141
  * One extension as `extensions.platform-get` shows it: the admin console's view (status, replicas,
@@ -155,7 +157,7 @@ const pendingExtension = (v) => ({
155
157
  kind: "extension",
156
158
  version: v.version,
157
159
  permissions: { added: v.added, removed: v.removed, sensitive: v.sensitive },
158
- next: `${CONFIRM_ON_WEB} (Extensions → ${enName(v)})`,
160
+ next: `${CONFIRM_ON_WEB} (Plugins → ${enName(v)} → Extension tab)`,
159
161
  });
160
162
  /** A catalog plugin waiting for a permission confirmation: a compact row. */
161
163
  const pendingPlugin = (i) => ({
@@ -286,7 +288,7 @@ let ExtensionsAdminOperations = class ExtensionsAdminOperations {
286
288
  const rows = r?.items;
287
289
  if (rows === undefined || rows.length === 0)
288
290
  return null;
289
- // the one extension's page only when the whole waiting set is that extension
291
+ // the one extension's tab only when the whole waiting set is that extension
290
292
  const onlyExtension = r?.total === 1 && rows.length === 1 && rows[0]?.kind === "extension";
291
293
  const id = rows[0]?.id;
292
294
  return {
@@ -298,7 +300,7 @@ let ExtensionsAdminOperations = class ExtensionsAdminOperations {
298
300
  target: {
299
301
  type: "link",
300
302
  url: onlyExtension && typeof id === "string"
301
- ? `/admin/extensions/${encodeURIComponent(id)}`
303
+ ? `/admin/plugins/extensions/${encodeURIComponent(id)}`
302
304
  : "/admin/plugins/pending",
303
305
  },
304
306
  };
@@ -455,7 +457,10 @@ let ExtensionsAdminOperations = class ExtensionsAdminOperations {
455
457
  zh: "审阅并确认扩展的权限",
456
458
  en: "Review and confirm the extension's permissions",
457
459
  },
458
- target: { type: "link", url: `/admin/extensions/${encodeURIComponent(input.name)}` },
460
+ target: {
461
+ type: "link",
462
+ url: `/admin/plugins/extensions/${encodeURIComponent(input.name)}`,
463
+ },
459
464
  };
460
465
  },
461
466
  }),
@@ -679,7 +684,7 @@ let ExtensionsAdminOperations = class ExtensionsAdminOperations {
679
684
  }),
680
685
  defineOperation({
681
686
  id: "extensions.platform-guides",
682
- description: "Read an extension's platform setup guides (super admin): the guides it ships for its deployment config (for example a push provider's credentials), rendered with the steps and the checks as check rows (run them with extensions.platform-check). Secrets are never in a guide: the person types each one into the deployment config form in the admin console (Extensions → the extension), or in the secure input request of extensions.platform-set-config. Empty when the extension ships none.",
687
+ description: "Read an extension's platform setup guides (super admin): the guides it ships for its deployment config (for example a push provider's credentials), rendered with the steps and the checks as check rows (run them with extensions.platform-check). Secrets are never in a guide: the person types each one into the deployment config form in the admin console (Plugins → the plugin's Extension tab, or the deployment extension's page), or in the secure input request of extensions.platform-set-config. Empty when the extension ships none.",
683
688
  input: DeploymentGuidesPathParams.extend(DeploymentGuidesQuery.shape).strict(),
684
689
  example: { name: "push-apns" },
685
690
  authz: { superAdmin: true },
@@ -698,10 +703,13 @@ let ExtensionsAdminOperations = class ExtensionsAdminOperations {
698
703
  handoff: (input) => ({
699
704
  kind: "handoff",
700
705
  title: {
701
- zh: "在扩展页面填写部署配置",
702
- en: "Fill in the deployment config on the extension page",
706
+ zh: "在插件的扩展标签页填写部署配置",
707
+ en: "Fill in the deployment config on the plugin's Extension tab",
708
+ },
709
+ target: {
710
+ type: "link",
711
+ url: `/admin/plugins/extensions/${encodeURIComponent(input.name)}`,
703
712
  },
704
- target: { type: "link", url: `/admin/extensions/${encodeURIComponent(input.name)}` },
705
713
  }),
706
714
  }),
707
715
  defineOperation({
@@ -35,7 +35,7 @@ const Force = OrgExtensionPut.shape.force;
35
35
  /** The next step of an extension that needs its org config. */
36
36
  const NEEDS_ORG_CONFIG = {
37
37
  orgAdmin: "Read what is missing with extensions.org-config, then fill in the org's own copy of the overridable fields with extensions.save-org-config; the person enters secrets in a secure input request.",
38
- member: "Ask an org admin to fill in its org config on the Extensions page.",
38
+ member: "Ask an org admin to fill in its org config in Plugins.",
39
39
  };
40
40
  /** What `extensions.set-enabled` adds when the extension is on but its org config is not valid. */
41
41
  const CONFIG_NEEDED = `The extension is on, but has no valid config for this org yet and gets no calls until it does: ${NEEDS_ORG_CONFIG.orgAdmin} If only platform-only fields are missing, the super admin must set them.`;
@@ -67,7 +67,7 @@ export function copyPersonFields(v) {
67
67
  const notOurs = found.fields.filter((f) => !overridable.has(top(f.path))).map((f) => f.path);
68
68
  return withUnaddressed({ fields, recordOnly: [...found.recordOnly, ...notOurs] }, secrets.map((f) => f.path));
69
69
  }
70
- /** An extension's state in the org, as the Extensions page shows it. */
70
+ /** An extension's state in the org, as the Plugins surface's Extension tab shows it. */
71
71
  function stateOf(v) {
72
72
  if (!v.available)
73
73
  return "unavailable";
@@ -139,7 +139,7 @@ let ExtensionsOperations = class ExtensionsOperations {
139
139
  this.registry.register([
140
140
  defineOperation({
141
141
  id: "extensions.list",
142
- description: "List this org's extensions, as its Extensions page does (an extension whose plugin is not installed in the org is left out until plugins.set-enabled installs it), one compact row each: the state here (on, off, needs_config: its config for this org is not valid, unavailable: it cannot run on the platform), why an unavailable one cannot be used (reason) and your next step (next), whether it is available on the platform, the extension points it provides and the plugin that brings it. State only: an org admin reads the config with extensions.org-config and sets the org's copy with extensions.save-org-config. Pages by 50: pass the returned next as params.cursor.",
142
+ description: "List this org's extensions, as the org admin's Plugins surface does (an extension whose plugin is not installed in the org is left out until plugins.set-enabled installs it), one compact row each: the state here (on, off, needs_config: its config for this org is not valid, unavailable: it cannot run on the platform), why an unavailable one cannot be used (reason) and your next step (next), whether it is available on the platform, the extension points it provides and the plugin that brings it (catalogItemId), plus canonicalItemId (the one plugin whose page manages it, null when it is declared in the startup configuration or several plugins ship it) and sourceItemIds (every plugin of the org's that ships it). State only: an org admin reads the config with extensions.org-config and sets the org's copy with extensions.save-org-config. Pages by 50: pass the returned next as params.cursor.",
143
143
  input: z.object({ cursor: Cursor.optional() }).strict(),
144
144
  example: {},
145
145
  authz: { orgAction: "org.extensions.read" },
@@ -166,6 +166,9 @@ let ExtensionsOperations = class ExtensionsOperations {
166
166
  available: v.available,
167
167
  provides: providesOf(v),
168
168
  catalogItemId: v.catalogItem?.itemId ?? null,
169
+ // the plugin whose page manages it (its one source), and every source plugin
170
+ canonicalItemId: v.canonicalItemId,
171
+ sourceItemIds: v.sourceItemIds,
169
172
  };
170
173
  }), startOf(input.cursor), 50);
171
174
  },
@@ -378,7 +378,7 @@ let OrgPluginsOperations = class OrgPluginsOperations {
378
378
  }),
379
379
  defineOperation({
380
380
  id: "plugins.apply-appearance",
381
- description: "Apply a plugin's suggested appearance in this org (org admins; the Extensions page's \"Apply this plugin's appearance\" action), for a plugin whose extension is on here: in one step, its theme becomes the org's default theme (whether members may pick their own stays as it is) and each component it suggests replaces the built-in block of its slot (shell.brand, conversation.empty, conversation.composer.frame) in the org's arrangement. The card shows exactly what changes; a theme that is not on in the org refuses the whole call, a component that is not available is skipped.",
381
+ description: "Apply a plugin's suggested appearance in this org (org admins; the \"Apply this plugin's appearance\" action on the plugin's Extension tab in Plugins), for a plugin whose extension is on here: in one step, its theme becomes the org's default theme (whether members may pick their own stays as it is) and each component it suggests replaces the built-in block of its slot (shell.brand, conversation.empty, conversation.composer.frame) in the org's arrangement. The card shows exactly what changes; a theme that is not on in the org refuses the whole call, a component that is not available is skipped.",
382
382
  input: z.object({ extension: OrgExtensionParams.shape.extension }).strict(),
383
383
  example: { extension: "theme-cyberpunk" },
384
384
  authz: { orgAction: "org.update" },
@@ -248,7 +248,7 @@ let PluginsOperations = class PluginsOperations {
248
248
  {
249
249
  code: "catalog.not_deployed",
250
250
  next: {
251
- superAdmin: "Open the admin console → Extensions → the plugin's extension to see why it is not running (deployment config, permission approval, disabled, or failed to load); fix it, then call again.",
251
+ superAdmin: "Open the plugin's Extension tab in the admin console's Plugins to see why its extension is not running (deployment config, permission approval, disabled, or failed to load); fix it, then call again.",
252
252
  orgAdmin: "Only the super admin can make the plugin's extension run; plugins.get shows the reason. There is no request operation for this (requests.create covers enabling and access only), so tell the super admin directly.",
253
253
  member: "Ask an org admin: the super admin must set up the plugin's extension on the platform first.",
254
254
  },
@@ -9,7 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { z } from "zod";
12
- import { CatalogItemPathParams, CatalogMarketplaceRequestBody, CatalogRequestBody, CatalogRequestsListQuery, } from "../../catalog/org-catalog.schemas.js";
12
+ import { CatalogItemPathParams, CatalogMarketplaceRequestBody, CatalogRequestBody, CatalogRequestsListQuery, EnableRequestBody, } from "../../catalog/org-catalog.schemas.js";
13
13
  import { CatalogRequestsService } from "../../catalog/requests.service.js";
14
14
  import { defineOperation } from "../operation.js";
15
15
  import { PlatformOperations } from "../registry.js";
@@ -25,6 +25,7 @@ const view = (r) => ({
25
25
  entry: r.entry,
26
26
  agent: r.agent,
27
27
  network: r.network,
28
+ enable: r.enable,
28
29
  note: r.note,
29
30
  reason: r.reason,
30
31
  decidedAt: r.decidedAt,
@@ -118,6 +119,59 @@ let RequestsOperations = class RequestsOperations {
118
119
  request: view(await this.requests.requestItem(ctx.orgId, ctx.actorAccountId, input.itemId, { kind: input.kind, ...(input.note !== undefined && { note: input.note }) }, { auditDetail: viaAgent("requests.create", ctx) })),
119
120
  }),
120
121
  }),
122
+ defineOperation({
123
+ id: "plugins.request-enable",
124
+ description: 'Ask the org admins to turn on what a capability needs in this org (members and up): pass the subject the person pointed at (kind plugin with the catalog item id, extension with its name, skill / agent_template / connector_template with the component id, connector with its id, or model with the id ["<provider>","<model>"]) and an optional note. The platform finds the switch to turn on (the plugin, the extension, the component, the model or the connector) and files one request for it; when the org has a pending request for that switch already, that one is returned.',
125
+ input: EnableRequestBody,
126
+ example: {
127
+ subject: { kind: "model", id: '["model-fake","fake-large"]' },
128
+ note: "For the weekly report.",
129
+ },
130
+ authz: { orgAction: "catalog.request" },
131
+ mirrors: ["POST /api/v1/orgs/:orgId/catalog-requests/enable"],
132
+ confirm: "personal",
133
+ errors: [
134
+ {
135
+ code: "catalog.request_invalid",
136
+ next: "It is already on, built in, or not offered to this org; nothing an org admin can turn on. Tell the person what you found.",
137
+ },
138
+ {
139
+ code: "catalog.item_disabled",
140
+ next: "The super admin disabled it on the platform; only the super admin can change that.",
141
+ },
142
+ {
143
+ code: "catalog.item_not_found",
144
+ next: "This org does not see that plugin. Check the id with plugins.list.",
145
+ },
146
+ {
147
+ code: "extension.not_found",
148
+ next: "This org does not see that extension. Check the name with extensions.list.",
149
+ },
150
+ {
151
+ code: "connector.not_found",
152
+ next: "No such connector in this org. Check the id with connectors.list.",
153
+ },
154
+ {
155
+ code: "component.not_found",
156
+ next: "This org does not see that component. Check the id with the component lists.",
157
+ },
158
+ {
159
+ code: "model.not_found",
160
+ next: 'This org does not see that model. Use ["<provider>","<model>"] as models.list names them.',
161
+ },
162
+ ],
163
+ summary: (i) => ({
164
+ zh: `申请在本组织启用 ${i.subject.kind} ${i.subject.id}`,
165
+ en: `Ask the org admins to turn on ${i.subject.kind} ${i.subject.id}`,
166
+ }),
167
+ run: async (input, ctx) => {
168
+ const { request, created } = await this.requests.requestEnable(ctx.orgId, ctx.actorAccountId, {
169
+ subject: input.subject,
170
+ ...(input.note !== undefined && { note: input.note }),
171
+ }, { auditDetail: viaAgent("plugins.request-enable", ctx) });
172
+ return { request: view(request), created };
173
+ },
174
+ }),
121
175
  defineOperation({
122
176
  id: "requests.create-import",
123
177
  description: "Ask the super admin to import a plugin from a marketplace into the platform catalog (org admins, when the platform lets orgs browse): the marketplaceId, name and version from marketplaces.entries, and an optional note.",
@@ -23,7 +23,7 @@ const TELL_SUPER_ADMIN = "There is no request operation for this (requests.creat
23
23
  const memberNext = (name) => `Ask an org admin: the super admin must set up ${name} on the platform before anyone in the org can use it.`;
24
24
  /** The next step for an unavailable plugin or extension, keyed by role. */
25
25
  export function unavailableNext(reason, name) {
26
- const adminPath = `Open the admin console → Extensions → ${name}`;
26
+ const adminPath = `Open the Extension tab of ${name} in the admin console's Plugins (/admin/plugins/extensions/${encodeURIComponent(name)} opens it)`;
27
27
  switch (reason) {
28
28
  case "loading":
29
29
  case "pending_migration":
@@ -72,7 +72,7 @@ export function unavailableNext(reason, name) {
72
72
  };
73
73
  case "not_deployed":
74
74
  return {
75
- superAdmin: `Install the extension of ${name}: admin console → Extensions (or update the plugin in the admin console under Plugins), then switch it on again.`,
75
+ superAdmin: `Install the extension of ${name}: import or update its plugin in the admin console under Plugins, then switch it on again.`,
76
76
  orgAdmin: `Only the super admin can install the extension of ${name}. ${TELL_SUPER_ADMIN}`,
77
77
  member: memberNext(name),
78
78
  };
@@ -136,9 +136,9 @@ export declare const ENV_FILES_LOST_TEXT = "This device's files are gone. Ask th
136
136
  * A provider call that never connected (refused, unknown host, unreachable network): the request
137
137
  * did not reach the provider, so the call did nothing in the sandbox.
138
138
  */
139
- export declare const SANDBOX_UNREACHABLE_TEXT = "The sandbox provider can't be reached (the connection failed), so this call did nothing in the sandbox; retrying won't help until a super admin checks the sandbox extension's configuration (Admin console \u2192 Extensions). Continue without the sandbox, or ask the person to have a super admin check it.";
139
+ export declare const SANDBOX_UNREACHABLE_TEXT = "The sandbox provider can't be reached (the connection failed), so this call did nothing in the sandbox; retrying won't help until a super admin checks the sandbox extension's configuration (Admin console \u2192 Plugins \u2192 its Extension tab). Continue without the sandbox, or ask the person to have a super admin check it.";
140
140
  /** A provider connection that broke during the call: the provider may have acted before it broke. */
141
- export declare const SANDBOX_CONNECTION_DROPPED_TEXT = "The connection to the sandbox provider broke during this call, so it may or may not have taken effect; check the sandbox state before retrying. If it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's configuration (Admin console \u2192 Extensions).";
141
+ export declare const SANDBOX_CONNECTION_DROPPED_TEXT = "The connection to the sandbox provider broke during this call, so it may or may not have taken effect; check the sandbox state before retrying. If it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's configuration (Admin console \u2192 Plugins \u2192 its Extension tab).";
142
142
  /** A dial-in device whose machine is not connected (`device.offline`, the SDK's offline error). */
143
143
  export declare const DEVICE_OFFLINE_TEXT = "The machine serving this device is offline. Ask the person to connect it again, or to start a new conversation on another device.";
144
144
  /**
@@ -147,7 +147,7 @@ export declare const DEVICE_OFFLINE_TEXT = "The machine serving this device is o
147
147
  */
148
148
  export declare const SANDBOX_OPEN_NETWORK_REFUSED_TEXT = "The cloud sandbox provider refused to give this device the open public network, so nothing ran in the sandbox and retrying won't help. Ask the person to switch this device to sandbox mode and have an org admin switch the organization's cloud network to an allowlist, or have a super admin use a sandbox provider that offers the open network. Continue without the sandbox meanwhile.";
149
149
  /** A cloud provider failed to create the device's sandbox otherwise (`sandbox.create_failed`). */
150
- export declare const SANDBOX_CREATE_FAILED_TEXT = "The cloud sandbox provider could not create this device's sandbox, so nothing ran in it. Retry once; if it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's settings (Admin console \u2192 Extensions).";
150
+ export declare const SANDBOX_CREATE_FAILED_TEXT = "The cloud sandbox provider could not create this device's sandbox, so nothing ran in it. Retry once; if it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's settings (Admin console \u2192 Plugins \u2192 its Extension tab).";
151
151
  export { ATTACHMENTS_ROOT, attachmentsDir, attachmentsRoot };
152
152
  /** 附件文件名的上限(UTF-8 字节,常见文件系统单个文件名上限 255 字节,留出 `-N` 后缀的余量)。 */
153
153
  export declare const ATTACHMENT_NAME_MAX_BYTES = 200;
@@ -60,9 +60,9 @@ export const ENV_FILES_LOST_TEXT = "This device's files are gone. Ask the user t
60
60
  * A provider call that never connected (refused, unknown host, unreachable network): the request
61
61
  * did not reach the provider, so the call did nothing in the sandbox.
62
62
  */
63
- export const SANDBOX_UNREACHABLE_TEXT = "The sandbox provider can't be reached (the connection failed), so this call did nothing in the sandbox; retrying won't help until a super admin checks the sandbox extension's configuration (Admin console → Extensions). Continue without the sandbox, or ask the person to have a super admin check it.";
63
+ export const SANDBOX_UNREACHABLE_TEXT = "The sandbox provider can't be reached (the connection failed), so this call did nothing in the sandbox; retrying won't help until a super admin checks the sandbox extension's configuration (Admin console → Plugins → its Extension tab). Continue without the sandbox, or ask the person to have a super admin check it.";
64
64
  /** A provider connection that broke during the call: the provider may have acted before it broke. */
65
- export const SANDBOX_CONNECTION_DROPPED_TEXT = "The connection to the sandbox provider broke during this call, so it may or may not have taken effect; check the sandbox state before retrying. If it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's configuration (Admin console → Extensions).";
65
+ export const SANDBOX_CONNECTION_DROPPED_TEXT = "The connection to the sandbox provider broke during this call, so it may or may not have taken effect; check the sandbox state before retrying. If it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's configuration (Admin console → Plugins → its Extension tab).";
66
66
  /** A dial-in device whose machine is not connected (`device.offline`, the SDK's offline error). */
67
67
  export const DEVICE_OFFLINE_TEXT = "The machine serving this device is offline. Ask the person to connect it again, or to start a new conversation on another device.";
68
68
  const DEVICE_OUTDATED_TEXT = "The machine serving this device runs an outdated device program. Ask the person to update it on that machine and connect it again.";
@@ -74,7 +74,7 @@ const deviceProtocolText = (detail) => `The machine serving this device sent an
74
74
  */
75
75
  export const SANDBOX_OPEN_NETWORK_REFUSED_TEXT = "The cloud sandbox provider refused to give this device the open public network, so nothing ran in the sandbox and retrying won't help. Ask the person to switch this device to sandbox mode and have an org admin switch the organization's cloud network to an allowlist, or have a super admin use a sandbox provider that offers the open network. Continue without the sandbox meanwhile.";
76
76
  /** A cloud provider failed to create the device's sandbox otherwise (`sandbox.create_failed`). */
77
- export const SANDBOX_CREATE_FAILED_TEXT = "The cloud sandbox provider could not create this device's sandbox, so nothing ran in it. Retry once; if it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's settings (Admin console → Extensions).";
77
+ export const SANDBOX_CREATE_FAILED_TEXT = "The cloud sandbox provider could not create this device's sandbox, so nothing ran in it. Retry once; if it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's settings (Admin console → Plugins → its Extension tab).";
78
78
  const LOCK_LOST_TEXT = "The sandbox operation was interrupted because the sandbox lock was lost; check the sandbox state and retry.";
79
79
  export { ATTACHMENTS_ROOT, attachmentsDir, attachmentsRoot };
80
80
  /** 附件文件名的上限(UTF-8 字节,常见文件系统单个文件名上限 255 字节,留出 `-N` 后缀的余量)。 */
@@ -11,6 +11,7 @@ export interface ConnectorTemplateDescription {
11
11
  /** The template's Chinese text; null: `templateDescription` serves both languages. */
12
12
  templateDescriptionZh: string | null;
13
13
  }
14
+ import type { RequestableFields } from "../catalog/enable-requests.js";
14
15
  import type { ConnectionGuideState } from "../extensions/plugin-guides.js";
15
16
  import { PluginIcons } from "../extensions/plugin-icons.js";
16
17
  import { type Principal } from "../identity/principal.js";
@@ -228,8 +229,14 @@ export declare class ConnectorsController {
228
229
  * `connector.not_found`; no icon the reader may see -> 404 `catalog.icon_not_found`.
229
230
  */
230
231
  icon(org: OrgContext, connectorId: string, reply: FastifyReply): Promise<void>;
232
+ /**
233
+ * The org's connectors. A disabled one whose owning switch the reader may ask an org admin to
234
+ * turn on (the connector itself, or its plugin while a plugin switch-off disabled it) carries
235
+ * `requestable: true` and the org's pending request (`pendingRequestId`): the connector
236
+ * picker's "Ask to turn on" (org-usable spec). Only active connectors are selectable.
237
+ */
231
238
  list(org: OrgContext): Promise<{
232
- connectors: ConnectorPage<ConnectorSummary>[];
239
+ connectors: (ConnectorPage<ConnectorSummary> & Partial<RequestableFields>)[];
233
240
  }>;
234
241
  /** Adds the icon and the setup guide fields to connector views (one lookup each for all). */
235
242
  private withGuides;
@@ -114,9 +114,22 @@ let ConnectorsController = class ConnectorsController {
114
114
  const ref = await this.connectors.iconRef(org.orgId, connectorId);
115
115
  await sendCatalogIcon(reply, await this.icons.readConnectorIcon(ref, orgIconScope(org)));
116
116
  }
117
+ /**
118
+ * The org's connectors. A disabled one whose owning switch the reader may ask an org admin to
119
+ * turn on (the connector itself, or its plugin while a plugin switch-off disabled it) carries
120
+ * `requestable: true` and the org's pending request (`pendingRequestId`): the connector
121
+ * picker's "Ask to turn on" (org-usable spec). Only active connectors are selectable.
122
+ */
117
123
  async list(org) {
118
124
  const list = (await this.connectors.list(org.orgId)).map((a) => forViewer(org, a));
119
- return { connectors: await this.withGuides(org, list) };
125
+ const fields = await this.connectors.requestable(org.orgId, org.role, list.flatMap((c) => (c.status === "disabled" ? [c.id] : [])));
126
+ const pages = await this.withGuides(org, list);
127
+ return {
128
+ connectors: pages.map((c) => {
129
+ const f = fields.get(c.id);
130
+ return f === undefined ? c : { ...c, ...f };
131
+ }),
132
+ };
120
133
  }
121
134
  /** Adds the icon and the setup guide fields to connector views (one lookup each for all). */
122
135
  async withGuides(org, views) {
@@ -1,4 +1,5 @@
1
1
  import { type AuthHint, type ConnectorOperation, type GitSource, type ToolAnnotations } from "@capybara-hq/plugin-sdk";
2
+ import { type RequestableFields } from "../catalog/enable-requests.js";
2
3
  import { type ConnectionGuideState, type GuideAck, PluginGuides } from "../extensions/plugin-guides.js";
3
4
  import type { WriteActor } from "../identity/write-actor.js";
4
5
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -445,6 +446,12 @@ export declare class ConnectorsService {
445
446
  private ackIn;
446
447
  /** The org's connectors that are not deleted (by creation time). */
447
448
  list(orgId: string): Promise<ConnectorSummary[]>;
449
+ /**
450
+ * The picker projection of disabled connectors `ids` for a reader of `role` (org-usable spec
451
+ * "Members and guests"): the ones whose owning switch the reader may ask an org admin to turn on,
452
+ * with `requestable: true` and the org's pending request, by connector id.
453
+ */
454
+ requestable(orgId: string, role: OrgRole, ids: readonly string[]): Promise<Map<string, RequestableFields>>;
448
455
  /**
449
456
  * Where a live connector of the org takes its icon from: its platform template and its plugin
450
457
  * (catalog item). Unknown -> `connector.not_found`.
@@ -13,6 +13,8 @@ import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { z } from "zod";
15
15
  import { connectorTemplateState } from "../catalog/component-state.js";
16
+ import { cancelEnableRequestsOfConnector, requestableSubjects, settleEnableRequests, } from "../catalog/enable-requests.js";
17
+ import { targetKey } from "../catalog/enable-targets.js";
16
18
  import { pluginSwitchOff } from "../catalog/plugin-connectors.js";
17
19
  import { assertItemInstallable } from "../catalog/request-rules.js";
18
20
  import { productName } from "../config/product-name.js";
@@ -1103,6 +1105,21 @@ let ConnectorsService = class ConnectorsService {
1103
1105
  const setups = await connectorSetups(this.credentials, orgId, rows.map((r) => ({ id: r.id, auth: r.auth })));
1104
1106
  return rows.map((r) => this.summary(r, setups.get(r.id) ?? "needs_config"));
1105
1107
  }
1108
+ /**
1109
+ * The picker projection of disabled connectors `ids` for a reader of `role` (org-usable spec
1110
+ * "Members and guests"): the ones whose owning switch the reader may ask an org admin to turn on,
1111
+ * with `requestable: true` and the org's pending request, by connector id.
1112
+ */
1113
+ async requestable(orgId, role, ids) {
1114
+ const fields = await requestableSubjects(this.db, orgId, role, ids.map((id) => ({ kind: "connector", id })));
1115
+ const out = new Map();
1116
+ for (const id of ids) {
1117
+ const f = fields.get(targetKey({ kind: "connector", id }));
1118
+ if (f !== undefined)
1119
+ out.set(id, f);
1120
+ }
1121
+ return out;
1122
+ }
1106
1123
  /**
1107
1124
  * Where a live connector of the org takes its icon from: its platform template and its plugin
1108
1125
  * (catalog item). Unknown -> `connector.not_found`.
@@ -1223,6 +1240,12 @@ let ConnectorsService = class ConnectorsService {
1223
1240
  .where("org_id", "=", orgId)
1224
1241
  .execute();
1225
1242
  }
1243
+ // switched back on: the org's pending enable requests for the connector are settled
1244
+ if (patch.status === "active" && app.status === "disabled") {
1245
+ await settleEnableRequests(t, orgId, { kind: "connector", id: connectorId }, actorAccountId, {
1246
+ ...(actorTokenId !== undefined && { actorTokenId }),
1247
+ });
1248
+ }
1226
1249
  for (const [name, change] of toolChanges) {
1227
1250
  if (change.status === undefined)
1228
1251
  continue;
@@ -1390,6 +1413,8 @@ let ConnectorsService = class ConnectorsService {
1390
1413
  .where("org_id", "=", orgId)
1391
1414
  .where("deleted_at", "is", null)
1392
1415
  .execute();
1416
+ // its plugin is its owning switch now: a pending request for the connector is stale
1417
+ await cancelEnableRequestsOfConnector(this.db, orgId, connectorId, null, "target_changed");
1393
1418
  }
1394
1419
  /** Owe a listing before changing the row's status and legacy last-update timestamp. */
1395
1420
  async oweStaleEndpointList(orgId, app) {
@@ -1439,6 +1464,7 @@ let ConnectorsService = class ConnectorsService {
1439
1464
  .where("id", "=", connectorId)
1440
1465
  .where("org_id", "=", orgId)
1441
1466
  .execute();
1467
+ await settleEnableRequests(this.db, orgId, { kind: "connector", id: connectorId }, null);
1442
1468
  return true;
1443
1469
  }
1444
1470
  /**
@@ -1463,6 +1489,9 @@ let ConnectorsService = class ConnectorsService {
1463
1489
  .where("id", "=", connectorId)
1464
1490
  .where("org_id", "=", orgId)
1465
1491
  .execute();
1492
+ if (status === "active" && app.status === "disabled") {
1493
+ await settleEnableRequests(t, orgId, { kind: "connector", id: connectorId }, actor.accountId, { ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }) });
1494
+ }
1466
1495
  await audit(t, {
1467
1496
  actorAccountId: actor.accountId,
1468
1497
  ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
@@ -1507,6 +1536,7 @@ let ConnectorsService = class ConnectorsService {
1507
1536
  .where("id", "=", connectorId)
1508
1537
  .where("org_id", "=", orgId)
1509
1538
  .execute();
1539
+ await cancelEnableRequestsOfConnector(t, orgId, connectorId, actorAccountId, "connector_removed");
1510
1540
  await this.credentials.clearConnector(orgId, connectorId);
1511
1541
  // 授权绑定连接器 id(软删除不触发外键级联):一并删掉,不留给任何后来的连接器
1512
1542
  await t
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.140",
3
+ "version": "0.1.0-rc.142",
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": {