@capybara-hq/kernel 0.1.0-rc.123 → 0.1.0-rc.125

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/admin.controller.d.ts +2 -2
  3. package/dist/admin/admin.controller.js +1 -1
  4. package/dist/admin/health.service.js +5 -5
  5. package/dist/admin/overview.service.d.ts +2 -2
  6. package/dist/admin/overview.service.js +1 -1
  7. package/dist/agents/agents.module.js +4 -0
  8. package/dist/agents/agents.schemas.js +1 -0
  9. package/dist/agents/models.controller.d.ts +2 -2
  10. package/dist/agents/onboarding-checklist.d.ts +31 -0
  11. package/dist/agents/onboarding-checklist.js +189 -0
  12. package/dist/agents/readiness.controller.d.ts +1 -0
  13. package/dist/agents/readiness.controller.js +12 -2
  14. package/dist/agents/readiness.service.d.ts +5 -2
  15. package/dist/agents/readiness.service.js +14 -3
  16. package/dist/automations/automations.service.js +7 -21
  17. package/dist/automations/events/acceptance.d.ts +2 -0
  18. package/dist/automations/events/acceptance.js +14 -3
  19. package/dist/automations/events/sweep.job.d.ts +3 -36
  20. package/dist/automations/events/sweep.job.js +5 -127
  21. package/dist/automations/fire.d.ts +3 -0
  22. package/dist/automations/fire.js +18 -1
  23. package/dist/automations/grant-rules.d.ts +0 -14
  24. package/dist/automations/grant-rules.js +0 -18
  25. package/dist/automations/scan.job.js +22 -16
  26. package/dist/catalog/catalog.module.d.ts +4 -7
  27. package/dist/catalog/catalog.module.js +4 -10
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/plugin-import.js +2 -1
  30. package/dist/catalog/plugin-install.d.ts +2 -2
  31. package/dist/catalog/plugin-install.js +2 -2
  32. package/dist/catalog/template-connector-ensure.d.ts +4 -7
  33. package/dist/catalog/template-connector-ensure.js +11 -15
  34. package/dist/channels/supervisor.js +34 -23
  35. package/dist/channels/webhook.d.ts +1 -0
  36. package/dist/channels/webhook.js +10 -5
  37. package/dist/conversations/job-org.d.ts +2 -0
  38. package/dist/conversations/job-org.js +12 -0
  39. package/dist/ctx/create-ctx.js +2 -1
  40. package/dist/db/kernel-schema.d.ts +1 -0
  41. package/dist/dial-in/auth.controller.js +3 -2
  42. package/dist/dial-in/auth.service.js +3 -2
  43. package/dist/dial-in/gateway.d.ts +0 -1
  44. package/dist/dial-in/gateway.js +6 -9
  45. package/dist/extensions/host.d.ts +2 -2
  46. package/dist/extensions/host.js +22 -13
  47. package/dist/extensions/installs.d.ts +1 -0
  48. package/dist/extensions/installs.js +2 -0
  49. package/dist/html/html-document.controller.js +3 -0
  50. package/dist/html/html-document.service.js +2 -0
  51. package/dist/http/plugin-route-access.js +7 -2
  52. package/dist/identity/account-avatar.controller.js +4 -2
  53. package/dist/identity/accounts.js +19 -32
  54. package/dist/identity/api-tokens.d.ts +2 -0
  55. package/dist/identity/api-tokens.js +14 -10
  56. package/dist/identity/audit.js +10 -5
  57. package/dist/identity/binding.d.ts +1 -1
  58. package/dist/identity/binding.js +19 -10
  59. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -8
  60. package/dist/lifecycle/kernel-lifecycle.js +11 -37
  61. package/dist/models/purposes.d.ts +24 -3
  62. package/dist/models/purposes.js +131 -14
  63. package/dist/orgs/directory-sync.js +6 -4
  64. package/dist/orgs/roles.d.ts +1 -1
  65. package/dist/orgs/roles.js +1 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +1 -1
  68. package/dist/platform/ops/agents.ops.js +1 -1
  69. package/dist/platform/ops/models.ops.js +3 -3
  70. package/dist/push/fanout.d.ts +1 -0
  71. package/dist/push/fanout.js +11 -4
  72. package/dist/push/recipients.d.ts +3 -1
  73. package/dist/push/recipients.js +29 -22
  74. package/dist/runtime/maintenance.d.ts +5 -1
  75. package/dist/runtime/maintenance.js +50 -11
  76. package/dist/runtime/providers.d.ts +12 -9
  77. package/dist/runtime/providers.js +2 -23
  78. package/dist/runtime/run-orphan-check.job.d.ts +1 -0
  79. package/dist/runtime/run-orphan-check.job.js +23 -21
  80. package/dist/runtime/usage-report.d.ts +2 -1
  81. package/dist/runtime/usage-report.js +26 -4
  82. package/dist/sandbox/providers.d.ts +2 -0
  83. package/dist/sandbox/providers.js +2 -0
  84. package/dist/shares/liveness.d.ts +3 -2
  85. package/dist/shares/liveness.js +26 -11
  86. package/dist/shares/share-open.service.js +2 -0
  87. package/dist/skills/usable.d.ts +2 -0
  88. package/dist/skills/usable.js +56 -0
  89. package/dist/tools/builtins/platform.js +17 -12
  90. package/dist/tools/connector-setup.d.ts +5 -1
  91. package/dist/tools/connector-setup.js +14 -0
  92. package/dist/tools/credentials.d.ts +5 -0
  93. package/dist/tools/credentials.js +10 -0
  94. package/dist/tools/oauth/flow.d.ts +1 -0
  95. package/dist/tools/oauth/flow.js +8 -3
  96. package/dist/tools/registry.d.ts +2 -0
  97. package/dist/tools/registry.js +6 -0
  98. package/package.json +3 -3
  99. package/src/migrations/0209_onboarding_checklist.sql +5 -0
  100. package/dist/catalog/template-connector-reconcile.d.ts +0 -44
  101. package/dist/catalog/template-connector-reconcile.js +0 -114
@@ -243,8 +243,8 @@ export declare class ExtensionHost {
243
243
  private readonly deps;
244
244
  /** 配置声明插件的部署配置最近一次判定是否合法(后台列表用;没判定过时按启动配置校验)。 */
245
245
  private readonly configValidity;
246
- /** 已告警过的「部署配置不合法」(插件名 → 说明;每个周期都会重新判定,同一说明只告警一次)。 */
247
- private readonly configWarned;
246
+ /** The last config diagnostic by plugin, including its level, to deduplicate reconcile logs. */
247
+ private readonly configReported;
248
248
  /** `<name>@<version>` whose invalid config UI hints were warned about (a log dedupe only). */
249
249
  private readonly configUiWarned;
250
250
  /**
@@ -15,7 +15,7 @@ import { EXTENSION_POINT_CARDINALITY, parseExtensionPoint, SDK_VERSION, } from "
15
15
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
- import { changedPaths, configFields, secretValues, unreachableSecrets } from "../config/fields.js";
18
+ import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
19
19
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
20
20
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
21
21
  import { kernelDb } from "../db/kernel-schema.js";
@@ -387,8 +387,8 @@ let ExtensionHost = class ExtensionHost {
387
387
  deps;
388
388
  /** 配置声明插件的部署配置最近一次判定是否合法(后台列表用;没判定过时按启动配置校验)。 */
389
389
  configValidity = new Map();
390
- /** 已告警过的「部署配置不合法」(插件名 → 说明;每个周期都会重新判定,同一说明只告警一次)。 */
391
- configWarned = new Map();
390
+ /** The last config diagnostic by plugin, including its level, to deduplicate reconcile logs. */
391
+ configReported = new Map();
392
392
  /** `<name>@<version>` whose invalid config UI hints were warned about (a log dedupe only). */
393
393
  configUiWarned = new Set();
394
394
  /**
@@ -958,6 +958,7 @@ let ExtensionHost = class ExtensionHost {
958
958
  const a = {
959
959
  manifest: c.manifest,
960
960
  source: "install",
961
+ optionalBootstrap: c.d.source === "bootstrap" && !c.d.required,
961
962
  sha256: c.d.sha256,
962
963
  entryUrl: c.entryUrl,
963
964
  migrationsDir: c.migrationsDir,
@@ -1379,20 +1380,28 @@ let ExtensionHost = class ExtensionHost {
1379
1380
  }
1380
1381
  if (schema && parsed) {
1381
1382
  if (!parsed.success) {
1382
- // 只列路径与按 issue 类型生成的说明(不用 zod 的 message:自定义消息可能拼入输入值)
1383
- const detail = toIssues(parsed.error)
1384
- .map((i) => `${i.path || "<root>"}: ${i.message}`)
1385
- .join("; ");
1386
- // 待配置(C10):配置声明与安装记录都一样,内核照常启动;配置改好后下一次 reconcile 加载
1387
- if (this.configWarned.get(name) !== detail) {
1388
- this.configWarned.set(name, detail);
1389
- this.log.warn("extension not loaded: its deployment config is missing or invalid (set it in the admin console or the startup config; it loads without a restart)", { plugin: name, source: a.source, detail });
1383
+ // Report schema paths and issue kinds only, since custom messages can expose input values.
1384
+ const issues = toIssues(parsed.error);
1385
+ const detail = issues.map((i) => `${i.path || "<root>"}: ${i.message}`).join("; ");
1386
+ const unconfigured = a.optionalBootstrap === true &&
1387
+ issues.every((issue) => {
1388
+ const value = issue.path === "" ? raw : getPath(raw, issue.path);
1389
+ return value === undefined || value === "";
1390
+ });
1391
+ const level = unconfigured ? "info" : "warn";
1392
+ const report = `${level}:${detail}`;
1393
+ if (this.configReported.get(name) !== report) {
1394
+ this.configReported.set(name, report);
1395
+ const next = "set it in Admin → Extensions or the startup config; it loads without a restart";
1396
+ this.log[level](unconfigured
1397
+ ? `optional preinstalled extension is waiting for deployment config (${next})`
1398
+ : `extension not loaded: its deployment config is missing or invalid (${next})`, { plugin: name, source: a.source, detail });
1390
1399
  }
1391
1400
  retryLater();
1392
1401
  await this.writeStatus({ ...base, state: "pending", reason: "config", detail });
1393
1402
  return undefined;
1394
1403
  }
1395
- this.configWarned.delete(name);
1404
+ this.configReported.delete(name);
1396
1405
  config = parsed.data;
1397
1406
  this.reportSecrets(schema, config);
1398
1407
  }
@@ -2034,7 +2043,7 @@ let ExtensionHost = class ExtensionHost {
2034
2043
  if (declared)
2035
2044
  this.pendingActivations.set(p.plugin, { ...declared, fatal: false });
2036
2045
  }
2037
- this.configWarned.set(p.plugin, detail);
2046
+ this.configReported.set(p.plugin, `warn:${detail}`);
2038
2047
  this.log.warn(message, { plugin: p.plugin, source: p.source, detail });
2039
2048
  await this.writeStatus({ ...p, state: "pending", reason: "config", detail });
2040
2049
  }
@@ -52,6 +52,7 @@ export interface DesiredExtension {
52
52
  sha256: string;
53
53
  version: string;
54
54
  source: "npm" | "file" | "catalog" | "bootstrap";
55
+ required: boolean;
55
56
  migratedSha: string | null;
56
57
  /**
57
58
  * Where the package bytes are kept. At startup the host loads the packages kept in PG first: the
@@ -332,6 +332,7 @@ let ExtensionInstalls = class ExtensionInstalls {
332
332
  "extension_installs.sha256",
333
333
  "extension_installs.version",
334
334
  "extension_installs.source",
335
+ "extension_installs.required",
335
336
  "extension_installs.migrated_sha",
336
337
  "extension_packages.section",
337
338
  "extension_packages.blob_store",
@@ -346,6 +347,7 @@ let ExtensionInstalls = class ExtensionInstalls {
346
347
  sha256: r.sha256,
347
348
  version: r.version,
348
349
  source: r.source,
350
+ required: r.required,
349
351
  migratedSha: r.migrated_sha,
350
352
  blobStore: r.blob_store,
351
353
  section: r.section,
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Controller, Get, HttpCode, Inject, Param, Post, Res } from "@nestjs/common";
11
11
  import { z } from "zod";
12
12
  import { CurrentPrincipal, Public, requireUser } from "../identity/principal.js";
13
+ import { bindRequestScope } from "../infra/database/org-scope.js";
13
14
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
15
  import { ZParam } from "../infra/validation/zod-params.js";
15
16
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
@@ -60,6 +61,8 @@ let HtmlDocumentController = class HtmlDocumentController {
60
61
  const claims = this.tokens.verify(token);
61
62
  if (claims === null)
62
63
  throw htmlNotFound();
64
+ if (claims.kind !== "share")
65
+ bindRequestScope({ kind: "org", orgId: claims.orgId });
63
66
  await this.documents.serve(claims, reply);
64
67
  }
65
68
  };
@@ -15,6 +15,7 @@ import { ApiError } from "../errors.js";
15
15
  import { BlobsService } from "../files/blobs.service.js";
16
16
  import { LibraryQuery } from "../files/library-query.js";
17
17
  import { KernelDb } from "../infra/database/kernel-db.js";
18
+ import { bindRequestScope } from "../infra/database/org-scope.js";
18
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
19
20
  import { ShareLiveness } from "../shares/liveness.js";
20
21
  import { readHtmlCdnAllowlist } from "../shares/settings.js";
@@ -130,6 +131,7 @@ let HtmlDocumentService = class HtmlDocumentService {
130
131
  if (s === null || !isHtmlType(s.name, s.contentType) || s.size > FILE_PREVIEW_MAX_BYTES) {
131
132
  return null;
132
133
  }
134
+ bindRequestScope({ kind: "org", orgId: s.orgId });
133
135
  return { orgId: s.orgId, contentType: s.contentType, blob: s.blob };
134
136
  }
135
137
  let f;
@@ -18,6 +18,7 @@ import { ApiTokenService } from "../identity/api-tokens.js";
18
18
  import { authenticatePersonalToken } from "../identity/auth.guard.js";
19
19
  import { IdentityModule } from "../identity/identity.module.js";
20
20
  import { KernelDb } from "../infra/database/kernel-db.js";
21
+ import { withOrgScope } from "../infra/database/org-scope.js";
21
22
  import { NAMED_THROTTLERS, throttlerKey } from "../infra/throttler/named-throttlers.js";
22
23
  import { roleAtLeast } from "../orgs/roles.js";
23
24
  /** Optional provider: the public write limit instead of the `plugin-public-write` throttler's (tests). */
@@ -145,7 +146,10 @@ let PluginRouteAccess = class PluginRouteAccess {
145
146
  tokens: this.tokens,
146
147
  });
147
148
  const orgId = params.orgId ?? "";
148
- const role = orgId === "" ? undefined : await orgRouteMember(this.kdb.db, route.plugin, orgId, account.id);
149
+ // The route org selects the membership to verify for the authenticated account.
150
+ const role = orgId === ""
151
+ ? undefined
152
+ : await withOrgScope(orgId, () => orgRouteMember(this.kdb.db, route.plugin, orgId, account.id));
149
153
  if (role === undefined)
150
154
  throw new ApiError("org.not_found", "Organization not found");
151
155
  const min = route.access === "admin" ? "admin" : "member";
@@ -166,7 +170,8 @@ let PluginRouteAccess = class PluginRouteAccess {
166
170
  * is not running on this replica (not a configuration problem), else 409 `extension.needs_config`.
167
171
  */
168
172
  async config(orgId, plugin) {
169
- const effective = await this.effective.get(orgId, plugin);
173
+ // Access resolution has verified the caller's org before reading its effective config.
174
+ const effective = await withOrgScope(orgId, () => this.effective.get(orgId, plugin));
170
175
  if (!effective.ok) {
171
176
  if (effective.notRunning) {
172
177
  throw new ApiError("extension.unavailable", `Extension ${plugin} is not available right now`);
@@ -11,6 +11,7 @@ import { Controller, Get, Inject, Param, Res } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { ApiError } from "../errors.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform } from "../infra/database/org-scope.js";
14
15
  import { KERNEL_LOGGER } from "../infra/tokens.js";
15
16
  import { avatarColumns, ownAvatar, safeSsoUrl } from "./account-avatar.js";
16
17
  import { AccountAvatarsService } from "./account-avatars.service.js";
@@ -54,7 +55,8 @@ let AccountAvatarController = class AccountAvatarController {
54
55
  };
55
56
  if (reader.mustChangePassword && accountId !== reader.id)
56
57
  throw refuse();
57
- const row = await this.db
58
+ // org-filter: deployment-wide check for any live org shared by the authenticated reader and target.
59
+ const row = await asPlatform("Check avatar visibility across the reader's memberships", () => this.db
58
60
  .selectFrom("accounts")
59
61
  .select((eb) => avatarColumns(eb, "accounts", "target"))
60
62
  .where("accounts.id", "=", accountId)
@@ -69,7 +71,7 @@ let AccountAvatarController = class AccountAvatarController {
69
71
  .where("reader_m.account_id", "=", reader.id)
70
72
  .where("shared_org.deleted_at", "is", null)),
71
73
  ])))
72
- .executeTakeFirst();
74
+ .executeTakeFirst());
73
75
  if (!row)
74
76
  throw refuse();
75
77
  let location = null;
@@ -13,6 +13,7 @@ import { sql } from "kysely";
13
13
  import { SetupLock, SetupLockModule } from "../admin/setup-lock.js";
14
14
  import { ApiError } from "../errors.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { asPlatform } from "../infra/database/org-scope.js";
16
17
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
17
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
19
  import { deletePushRegistrationsForSessions } from "../push/registration-cleanup.js";
@@ -20,6 +21,7 @@ import { PermissionCeilingWritesModule } from "../sandbox/permission-authority.m
20
21
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
21
22
  import { assertThemeOnForAccount } from "../themes/theme-state.js";
22
23
  import { withAvatarUrl } from "./account-avatar.js";
24
+ import { revokePersonalTokens } from "./api-tokens.js";
23
25
  import { audit } from "./audit.js";
24
26
  import { MAX_PASSWORD_LENGTH, normalizeLogin, validatePassword } from "./login.js";
25
27
  import { DUMMY_PASSWORD_HASH, hashPassword, verifyPassword } from "./passwords.js";
@@ -349,15 +351,7 @@ let AccountsService = class AccountsService {
349
351
  .execute();
350
352
  // the other devices stop receiving push; the current session's registrations stay
351
353
  await deletePushRegistrationsForSessions(this.db.db, sessions.map((r) => r.id));
352
- // org-filter: a password change revokes the account's personal tokens in every org on purpose
353
- // (accounts are platform-wide; ruling R24)
354
- await this.db
355
- .updateTable("api_tokens")
356
- .set({ revoked_at: sql `now()` })
357
- .where("kind", "=", "personal")
358
- .where("account_id", "=", accountId)
359
- .where("revoked_at", "is", null)
360
- .execute();
354
+ await revokePersonalTokens(this.db, accountId);
361
355
  return sessions.map((r) => r.id);
362
356
  }
363
357
  async update(id, patch, actorAccountId, actorTokenId) {
@@ -594,20 +588,21 @@ let AccountsService = class AccountsService {
594
588
  values.display_name = checkDisplayNameChange(before.display_name, patch.displayName);
595
589
  }
596
590
  if (patch.status !== undefined && patch.status !== before.status) {
597
- await this.ceilings.lock({}, "platform");
598
- await this.ceilings.publishLocked({}, "platform", patch.status === "disabled" ? (_scope, row) => row.account_id === id : false);
599
- // org-filter: a super-admin account status change resets Full consent on the account's
600
- // conversations in every org on purpose (accounts are platform-wide)
601
- await this.db
602
- .updateTable("conversations")
603
- .set((eb) => ({
604
- permission_profile: "approve-for-me",
605
- permission_consent: null,
606
- permission_revision: eb("permission_revision", "+", 1),
607
- }))
608
- .where("account_id", "=", id)
609
- .where("permission_profile", "=", "full-access")
610
- .execute();
591
+ // org-filter: deployment-wide status changes affect the account's permissions in every org.
592
+ await asPlatform("Apply the account's status to permissions across orgs", async () => {
593
+ await this.ceilings.lock({}, "platform");
594
+ await this.ceilings.publishLocked({}, "platform", patch.status === "disabled" ? (_scope, row) => row.account_id === id : false);
595
+ await this.db
596
+ .updateTable("conversations")
597
+ .set((eb) => ({
598
+ permission_profile: "approve-for-me",
599
+ permission_consent: null,
600
+ permission_revision: eb("permission_revision", "+", 1),
601
+ }))
602
+ .where("account_id", "=", id)
603
+ .where("permission_profile", "=", "full-access")
604
+ .execute();
605
+ });
611
606
  }
612
607
  if (patch.status !== undefined)
613
608
  values.status = patch.status;
@@ -642,15 +637,7 @@ let AccountsService = class AccountsService {
642
637
  .where("revoked_at", "is", null)
643
638
  .returning("id")
644
639
  .execute();
645
- // org-filter: disabling an account (super admin) revokes its personal tokens in every org on
646
- // purpose (accounts are platform-wide)
647
- await this.db
648
- .updateTable("api_tokens")
649
- .set({ revoked_at: sql `now()` })
650
- .where("kind", "=", "personal")
651
- .where("account_id", "=", id)
652
- .where("revoked_at", "is", null)
653
- .execute();
640
+ await revokePersonalTokens(this.db, id);
654
641
  revokedSessionIds = sessions.map((r) => r.id);
655
642
  // a registration follows its session (push plan decision 3): a disabled account loses all
656
643
  await deletePushRegistrationsForSessions(this.db.db, revokedSessionIds);
@@ -74,4 +74,6 @@ export declare class ApiTokenService {
74
74
  private scoped;
75
75
  private insertToken;
76
76
  }
77
+ /** Revokes the account-wide credentials in the caller's transaction. */
78
+ export declare function revokePersonalTokens(db: KernelDb, accountId: string): Promise<void>;
77
79
  export {};
@@ -205,16 +205,7 @@ let ApiTokenService = class ApiTokenService {
205
205
  .execute();
206
206
  }
207
207
  async revokeAllPersonal(accountId) {
208
- await asPlatform("Revoke all personal tokens for an account", async () => {
209
- // org-filter: deployment-wide account token revocation (personal tokens have a null org_id).
210
- await this.db
211
- .updateTable("api_tokens")
212
- .set({ revoked_at: sql `now()` })
213
- .where("kind", "=", "personal")
214
- .where("account_id", "=", accountId)
215
- .where("revoked_at", "is", null)
216
- .execute();
217
- });
208
+ await revokePersonalTokens(this.db, accountId);
218
209
  }
219
210
  scoped(q, scope) {
220
211
  return "accountId" in scope
@@ -244,3 +235,16 @@ ApiTokenService = __decorate([
244
235
  __param(2, Inject(OrgLock))
245
236
  ], ApiTokenService);
246
237
  export { ApiTokenService };
238
+ /** Revokes the account-wide credentials in the caller's transaction. */
239
+ export async function revokePersonalTokens(db, accountId) {
240
+ await asPlatform("Revoke all personal tokens for an account", async () => {
241
+ // org-filter: deployment-wide account token revocation (personal tokens have a null org_id).
242
+ await db
243
+ .updateTable("api_tokens")
244
+ .set({ revoked_at: sql `now()` })
245
+ .where("kind", "=", "personal")
246
+ .where("account_id", "=", accountId)
247
+ .where("revoked_at", "is", null)
248
+ .execute();
249
+ });
250
+ }
@@ -1,18 +1,23 @@
1
+ import { asPlatform } from "../infra/database/org-scope.js";
1
2
  /**
2
3
  * Writes one audit event (`action` is dotted lower-case English, e.g. `org.member.role_changed`)
3
4
  * through `db`: a service passes `this.db.db` (`KernelDb`: the context's transaction or the pool),
4
5
  * so the event commits or rolls back with the write it records.
5
6
  */
6
7
  export async function audit(db, e) {
7
- await db
8
- .insertInto("audit_events")
9
- .values({
8
+ const query = db.insertInto("audit_events").values({
10
9
  actor_account_id: e.actorAccountId ?? null,
11
10
  actor_token_id: e.actorTokenId ?? null,
12
11
  org_id: e.orgId ?? null,
13
12
  action: e.action,
14
13
  target: e.target ?? null,
15
14
  detail: JSON.stringify(e.detail ?? {}),
16
- })
17
- .execute();
15
+ });
16
+ if (e.orgId === undefined) {
17
+ // org-filter: deployment-wide audit events have no org and may originate inside an org call.
18
+ await asPlatform("Record an audit event without an org", () => query.execute());
19
+ }
20
+ else {
21
+ await query.execute();
22
+ }
18
23
  }
@@ -40,6 +40,6 @@ export declare class IdentityBinding {
40
40
  * 已绑定他人 → `identity.taken`(令牌同样作废,需在 IM 里重新获取)。
41
41
  */
42
42
  bind(token: string, accountId: string): Promise<PendingBinding>;
43
- /** 渠道连接存在、未软删除,且其插件在连接所属组织启用。 */
43
+ /** The link's connection must still exist and its plugin must be on in that connection's org. */
44
44
  private connectionUsable;
45
45
  }
@@ -10,9 +10,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { createHash, randomBytes } from "node:crypto";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { ApiError } from "../errors.js";
13
- import { enabledExtensionsByOrg } from "../extensions/enabled.js";
13
+ import { enabledExtensionsQuery } from "../extensions/enabled.js";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
16
17
  import { REDIS } from "../infra/tokens.js";
17
18
  import { ExternalIdentities } from "./external.js";
18
19
  /** 绑定令牌的有效期(秒)。 */
@@ -88,17 +89,25 @@ let IdentityBinding = class IdentityBinding {
88
89
  await this.external.link(accountId, rec.identity);
89
90
  return view(rec);
90
91
  }
91
- /** 渠道连接存在、未软删除,且其插件在连接所属组织启用。 */
92
+ /** The link's connection must still exist and its plugin must be on in that connection's org. */
92
93
  async connectionUsable(connectionId) {
93
- const row = await this.db
94
+ // org-filter: deployment-wide lookup of the connection recorded in the one-time binding link.
95
+ const owner = await asPlatform("Resolve the binding link's connection org", () => this.db
94
96
  .selectFrom("channel_connections")
95
- .innerJoin(enabledExtensionsByOrg(this.db.db).as("en"), (j) => j
96
- .onRef("en.org_id", "=", "channel_connections.org_id")
97
- .onRef("en.plugin", "=", "channel_connections.plugin"))
98
- .select("channel_connections.id")
99
- .where("channel_connections.id", "=", connectionId)
100
- .where("channel_connections.deleted_at", "is", null)
101
- .executeTakeFirst();
97
+ .select("org_id")
98
+ .where("id", "=", connectionId)
99
+ .where("deleted_at", "is", null)
100
+ .executeTakeFirst());
101
+ if (!owner)
102
+ return false;
103
+ const row = await withOrgScope(owner.org_id, () => this.db
104
+ .selectFrom("channel_connections")
105
+ .select("id")
106
+ .where("id", "=", connectionId)
107
+ .where("org_id", "=", owner.org_id)
108
+ .where("deleted_at", "is", null)
109
+ .where("plugin", "in", enabledExtensionsQuery(this.db.db, owner.org_id))
110
+ .executeTakeFirst());
102
111
  return row !== undefined;
103
112
  }
104
113
  };
@@ -6,7 +6,6 @@ import type { KernelAppOptions } from "../app.js";
6
6
  import { MarketplacesService } from "../catalog/marketplaces.service.js";
7
7
  import { PluginImport } from "../catalog/plugin-import.js";
8
8
  import { PlatformPluginUpdater } from "../catalog/plugin-upgrade.js";
9
- import { TemplateConnectorReconciler } from "../catalog/template-connector-reconcile.js";
10
9
  import { ChannelJobs } from "../channels/jobs.js";
11
10
  import { ChannelOutbound } from "../channels/outbound.js";
12
11
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
@@ -87,7 +86,6 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
87
86
  private readonly marketplaces;
88
87
  private readonly pluginImport;
89
88
  private readonly pluginUpdater;
90
- private readonly templateConnectors;
91
89
  private readonly bus;
92
90
  private readonly usageReport;
93
91
  private readonly titles;
@@ -113,7 +111,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
113
111
  private bootstrapPackages;
114
112
  /** The merged bootstrap manifest, read once per start. */
115
113
  private mergedManifest;
116
- constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, templateConnectors: TemplateConnectorReconciler, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
114
+ constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
117
115
  /** The kernel HTTP application (set up by `buildKernelApp` before `init()`). */
118
116
  get http(): KernelHttpApp;
119
117
  attachHttp(http: KernelHttpApp): void;
@@ -144,11 +142,6 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
144
142
  * them too; the final pass imports them, and one that fails is logged like an optional entry.
145
143
  */
146
144
  private runBootstrap;
147
- /**
148
- * Runs {@link TemplateConnectorReconciler}; an error is logged, except the stop's abort (the
149
- * checkpoint after it ends the start).
150
- */
151
- private reconcileTemplateConnectors;
152
145
  /** 部署尚无活跃超级管理员时提示去初始化;查询失败只记日志,不影响启动。 */
153
146
  private warnIfSetupPending;
154
147
  beforeApplicationShutdown(): Promise<void>;
@@ -13,7 +13,6 @@ import { sql } from "kysely";
13
13
  import { MarketplacesService } from "../catalog/marketplaces.service.js";
14
14
  import { PluginImport } from "../catalog/plugin-import.js";
15
15
  import { PlatformPluginUpdater } from "../catalog/plugin-upgrade.js";
16
- import { TemplateConnectorReconciler } from "../catalog/template-connector-reconcile.js";
17
16
  import { ChannelJobs } from "../channels/jobs.js";
18
17
  import { ChannelOutbound } from "../channels/outbound.js";
19
18
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
@@ -110,7 +109,6 @@ let KernelLifecycle = class KernelLifecycle {
110
109
  marketplaces;
111
110
  pluginImport;
112
111
  pluginUpdater;
113
- templateConnectors;
114
112
  bus;
115
113
  usageReport;
116
114
  titles;
@@ -138,7 +136,7 @@ let KernelLifecycle = class KernelLifecycle {
138
136
  mergedManifest;
139
137
  constructor(permissionConfig, accounts, configService, log, options,
140
138
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
141
- pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, templateConnectors, bus,
139
+ pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
142
140
  // the producers closed on every role (their consumers are the worker role's)
143
141
  usageReport, titles, suggestions, channelJobs, channelOutbound,
144
142
  // this process's presence beat, on every role (admin overview spec §5.1)
@@ -166,7 +164,6 @@ let KernelLifecycle = class KernelLifecycle {
166
164
  this.marketplaces = marketplaces;
167
165
  this.pluginImport = pluginImport;
168
166
  this.pluginUpdater = pluginUpdater;
169
- this.templateConnectors = templateConnectors;
170
167
  this.bus = bus;
171
168
  this.usageReport = usageReport;
172
169
  this.titles = titles;
@@ -341,12 +338,6 @@ let KernelLifecycle = class KernelLifecycle {
341
338
  await this.extensionLifecycle.reconcile("bootstrap");
342
339
  this.checkpoint();
343
340
  }
344
- // The one-off reconciliation of template connectors (plugin pages spec §7): once the
345
- // extensions loaded (it plans connectors against their connector extensions) and the bootstrap
346
- // step's plugins are in, under `lock:bootstrap` (a replica that does not get it skips the
347
- // pass). Never fails the start: what it could not create waits for a later ensure
348
- await this.reconcileTemplateConnectors();
349
- this.checkpoint();
350
341
  // The extra manifest's defaults (the platform default theme), at every start whether or not
351
342
  // the step ran in it (compose's `init` usually ran it): its themes exist only once the second
352
343
  // pass imported them. A no-op once applied or once a super admin chose; never fails the start
@@ -457,22 +448,6 @@ let KernelLifecycle = class KernelLifecycle {
457
448
  throw e;
458
449
  }
459
450
  }
460
- /**
461
- * Runs {@link TemplateConnectorReconciler}; an error is logged, except the stop's abort (the
462
- * checkpoint after it ends the start).
463
- */
464
- async reconcileTemplateConnectors() {
465
- try {
466
- await this.templateConnectors.run(this.shutdown.signal);
467
- }
468
- catch (e) {
469
- if (this.shutdown.isShuttingDown())
470
- return;
471
- this.log.error("template connector reconciliation failed; retried on the next start", {
472
- error: errMsg(e),
473
- });
474
- }
475
- }
476
451
  /** 部署尚无活跃超级管理员时提示去初始化;查询失败只记日志,不影响启动。 */
477
452
  async warnIfSetupPending() {
478
453
  try {
@@ -608,17 +583,16 @@ KernelLifecycle = __decorate([
608
583
  __param(17, Inject(MarketplacesService)),
609
584
  __param(18, Inject(PluginImport)),
610
585
  __param(19, Inject(PlatformPluginUpdater)),
611
- __param(20, Inject(TemplateConnectorReconciler)),
612
- __param(21, Inject(KERNEL_BUS)),
613
- __param(22, Inject(UsageReporter)),
614
- __param(23, Inject(TitleQueue)),
615
- __param(24, Inject(PromptSuggestionQueue)),
616
- __param(25, Inject(ChannelJobs)),
617
- __param(26, Inject(ChannelOutbound)),
618
- __param(27, Inject(ReplicaPresence)),
586
+ __param(20, Inject(KERNEL_BUS)),
587
+ __param(21, Inject(UsageReporter)),
588
+ __param(22, Inject(TitleQueue)),
589
+ __param(23, Inject(PromptSuggestionQueue)),
590
+ __param(24, Inject(ChannelJobs)),
591
+ __param(25, Inject(ChannelOutbound)),
592
+ __param(26, Inject(ReplicaPresence)),
593
+ __param(27, Optional()),
594
+ __param(27, Inject(WorkerRole)),
619
595
  __param(28, Optional()),
620
- __param(28, Inject(WorkerRole)),
621
- __param(29, Optional()),
622
- __param(29, Inject(GatewayRole))
596
+ __param(28, Inject(GatewayRole))
623
597
  ], KernelLifecycle);
624
598
  export { KernelLifecycle };
@@ -31,10 +31,21 @@ interface KernelPurpose {
31
31
  purpose: string;
32
32
  kind: PurposeKind;
33
33
  requires?: PurposeRequires;
34
+ /** Absent when the purpose falls back or degrades safely when unset. */
35
+ fallback?: "none";
36
+ /** Warning shown when `fallback` is `"none"`, the purpose is unset, and selectable models exist. */
37
+ unsetWarning?: {
38
+ zh: string;
39
+ en: string;
40
+ };
34
41
  label: {
35
42
  zh: string;
36
43
  en: string;
37
44
  };
45
+ description: {
46
+ zh: string;
47
+ en: string;
48
+ };
38
49
  }
39
50
  /**
40
51
  * Purposes the kernel declares: the eval judge, and the three sub-agent model tiers (phase C,
@@ -54,13 +65,22 @@ export interface PurposeView {
54
65
  zh: string;
55
66
  en: string;
56
67
  };
68
+ description: {
69
+ zh: string;
70
+ en: string;
71
+ } | null;
57
72
  /** What the target model must support beyond its kind; absent = nothing. */
58
73
  requires?: PurposeRequires;
59
- /** `kernel` 或声明它的插件名。 */
74
+ /** `kernel` or the declaring extension's name. */
60
75
  declaredBy: string;
61
76
  default: PurposeTarget | null;
62
77
  override: PurposeTarget | null;
63
78
  effective: PurposeTarget | null;
79
+ /** Warning when a no-fallback purpose is unset and selectable models exist; null otherwise. */
80
+ unsetWarning: {
81
+ zh: string;
82
+ en: string;
83
+ } | null;
64
84
  }
65
85
  /**
66
86
  * A purpose as the purpose APIs return it: the view plus the declaring extension's display name
@@ -122,13 +142,14 @@ export declare class ModelPurposesService {
122
142
  /** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
123
143
  private readonly storage;
124
144
  private readonly log;
125
- constructor(db: KernelDb, extensions: ExtensionRegistry, config: KernelConfigService, providers: Pick<ProviderRegistry, "resolve" | "platformInfo">, txHost: TransactionHost, adminLock: SuperAdminLock, orgLock: OrgLock,
145
+ constructor(db: KernelDb, extensions: ExtensionRegistry, config: KernelConfigService, providers: Pick<ProviderRegistry, "resolve" | "platformInfo" | "listWithStatus">, txHost: TransactionHost, adminLock: SuperAdminLock, orgLock: OrgLock,
126
146
  /** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
127
147
  storage: Pick<StorageService, "available">, log: Pick<Logger, "warn">);
128
- /** 全部已声明的用途:内核的在前,其后按插件加载顺序。 */
148
+ /** All declared purposes: kernel purposes first, then extensions in load order. */
129
149
  private declared;
130
150
  private find;
131
151
  private rows;
152
+ private enabledModels;
132
153
  private views;
133
154
  /** 全部用途与映射;不给 `orgId` = 部署级视图(`override` 一律为 null)。 */
134
155
  list(orgId?: string): Promise<PurposeView[]>;