@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.
- package/bootstrap.json +31 -31
- package/dist/admin/admin.controller.d.ts +2 -2
- package/dist/admin/admin.controller.js +1 -1
- package/dist/admin/health.service.js +5 -5
- package/dist/admin/overview.service.d.ts +2 -2
- package/dist/admin/overview.service.js +1 -1
- package/dist/agents/agents.module.js +4 -0
- package/dist/agents/agents.schemas.js +1 -0
- package/dist/agents/models.controller.d.ts +2 -2
- package/dist/agents/onboarding-checklist.d.ts +31 -0
- package/dist/agents/onboarding-checklist.js +189 -0
- package/dist/agents/readiness.controller.d.ts +1 -0
- package/dist/agents/readiness.controller.js +12 -2
- package/dist/agents/readiness.service.d.ts +5 -2
- package/dist/agents/readiness.service.js +14 -3
- package/dist/automations/automations.service.js +7 -21
- package/dist/automations/events/acceptance.d.ts +2 -0
- package/dist/automations/events/acceptance.js +14 -3
- package/dist/automations/events/sweep.job.d.ts +3 -36
- package/dist/automations/events/sweep.job.js +5 -127
- package/dist/automations/fire.d.ts +3 -0
- package/dist/automations/fire.js +18 -1
- package/dist/automations/grant-rules.d.ts +0 -14
- package/dist/automations/grant-rules.js +0 -18
- package/dist/automations/scan.job.js +22 -16
- package/dist/catalog/catalog.module.d.ts +4 -7
- package/dist/catalog/catalog.module.js +4 -10
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/plugin-import.js +2 -1
- package/dist/catalog/plugin-install.d.ts +2 -2
- package/dist/catalog/plugin-install.js +2 -2
- package/dist/catalog/template-connector-ensure.d.ts +4 -7
- package/dist/catalog/template-connector-ensure.js +11 -15
- package/dist/channels/supervisor.js +34 -23
- package/dist/channels/webhook.d.ts +1 -0
- package/dist/channels/webhook.js +10 -5
- package/dist/conversations/job-org.d.ts +2 -0
- package/dist/conversations/job-org.js +12 -0
- package/dist/ctx/create-ctx.js +2 -1
- package/dist/db/kernel-schema.d.ts +1 -0
- package/dist/dial-in/auth.controller.js +3 -2
- package/dist/dial-in/auth.service.js +3 -2
- package/dist/dial-in/gateway.d.ts +0 -1
- package/dist/dial-in/gateway.js +6 -9
- package/dist/extensions/host.d.ts +2 -2
- package/dist/extensions/host.js +22 -13
- package/dist/extensions/installs.d.ts +1 -0
- package/dist/extensions/installs.js +2 -0
- package/dist/html/html-document.controller.js +3 -0
- package/dist/html/html-document.service.js +2 -0
- package/dist/http/plugin-route-access.js +7 -2
- package/dist/identity/account-avatar.controller.js +4 -2
- package/dist/identity/accounts.js +19 -32
- package/dist/identity/api-tokens.d.ts +2 -0
- package/dist/identity/api-tokens.js +14 -10
- package/dist/identity/audit.js +10 -5
- package/dist/identity/binding.d.ts +1 -1
- package/dist/identity/binding.js +19 -10
- package/dist/lifecycle/kernel-lifecycle.d.ts +1 -8
- package/dist/lifecycle/kernel-lifecycle.js +11 -37
- package/dist/models/purposes.d.ts +24 -3
- package/dist/models/purposes.js +131 -14
- package/dist/orgs/directory-sync.js +6 -4
- package/dist/orgs/roles.d.ts +1 -1
- package/dist/orgs/roles.js +1 -0
- package/dist/platform/exclusions.js +5 -0
- package/dist/platform/ops/admin.ops.js +1 -1
- package/dist/platform/ops/agents.ops.js +1 -1
- package/dist/platform/ops/models.ops.js +3 -3
- package/dist/push/fanout.d.ts +1 -0
- package/dist/push/fanout.js +11 -4
- package/dist/push/recipients.d.ts +3 -1
- package/dist/push/recipients.js +29 -22
- package/dist/runtime/maintenance.d.ts +5 -1
- package/dist/runtime/maintenance.js +50 -11
- package/dist/runtime/providers.d.ts +12 -9
- package/dist/runtime/providers.js +2 -23
- package/dist/runtime/run-orphan-check.job.d.ts +1 -0
- package/dist/runtime/run-orphan-check.job.js +23 -21
- package/dist/runtime/usage-report.d.ts +2 -1
- package/dist/runtime/usage-report.js +26 -4
- package/dist/sandbox/providers.d.ts +2 -0
- package/dist/sandbox/providers.js +2 -0
- package/dist/shares/liveness.d.ts +3 -2
- package/dist/shares/liveness.js +26 -11
- package/dist/shares/share-open.service.js +2 -0
- package/dist/skills/usable.d.ts +2 -0
- package/dist/skills/usable.js +56 -0
- package/dist/tools/builtins/platform.js +17 -12
- package/dist/tools/connector-setup.d.ts +5 -1
- package/dist/tools/connector-setup.js +14 -0
- package/dist/tools/credentials.d.ts +5 -0
- package/dist/tools/credentials.js +10 -0
- package/dist/tools/oauth/flow.d.ts +1 -0
- package/dist/tools/oauth/flow.js +8 -3
- package/dist/tools/registry.d.ts +2 -0
- package/dist/tools/registry.js +6 -0
- package/package.json +3 -3
- package/src/migrations/0209_onboarding_checklist.sql +5 -0
- package/dist/catalog/template-connector-reconcile.d.ts +0 -44
- package/dist/catalog/template-connector-reconcile.js +0 -114
|
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
|
|
|
11
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
13
13
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
14
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
14
15
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
15
16
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
16
17
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
@@ -33,9 +34,11 @@ const EXPIRED = { status: "ended", pauseReason: "expired", nextRunAt: null };
|
|
|
33
34
|
*/
|
|
34
35
|
class TaskScanFailed extends Error {
|
|
35
36
|
taskId;
|
|
36
|
-
|
|
37
|
+
orgId;
|
|
38
|
+
constructor(taskId, orgId, cause) {
|
|
37
39
|
super(`automation ${taskId} cannot be advanced`, { cause });
|
|
38
40
|
this.taskId = taskId;
|
|
41
|
+
this.orgId = orgId;
|
|
39
42
|
}
|
|
40
43
|
}
|
|
41
44
|
/**
|
|
@@ -94,7 +97,7 @@ let AutomationScanJob = class AutomationScanJob {
|
|
|
94
97
|
taskId: err.taskId,
|
|
95
98
|
err: err.cause,
|
|
96
99
|
});
|
|
97
|
-
await this.quarantine(err.taskId);
|
|
100
|
+
await withOrgScope(err.orgId, () => this.quarantine(err.taskId));
|
|
98
101
|
}
|
|
99
102
|
}
|
|
100
103
|
await this.endExpiredEvents(now);
|
|
@@ -104,8 +107,9 @@ let AutomationScanJob = class AutomationScanJob {
|
|
|
104
107
|
async endExpiredEvents(now) {
|
|
105
108
|
const t = this.db;
|
|
106
109
|
const expired = await this.store.lockExpiredEvent(t, now, MAX_TASKS);
|
|
107
|
-
for (const task of expired)
|
|
108
|
-
await this.store.updateTask(t, task.id, EXPIRED);
|
|
110
|
+
for (const task of expired) {
|
|
111
|
+
await withOrgScope(task.orgId, () => this.store.updateTask(t, task.id, EXPIRED));
|
|
112
|
+
}
|
|
109
113
|
return expired.length;
|
|
110
114
|
}
|
|
111
115
|
/**
|
|
@@ -118,17 +122,19 @@ let AutomationScanJob = class AutomationScanJob {
|
|
|
118
122
|
const [task] = await this.store.lockDue(t, now, 1);
|
|
119
123
|
if (!task)
|
|
120
124
|
return false;
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
125
|
+
return withOrgScope(task.orgId, async () => {
|
|
126
|
+
let s = settings.get(task.orgId);
|
|
127
|
+
if (s === undefined) {
|
|
128
|
+
s = await readAutomationSettings(t, this.config, task.orgId);
|
|
129
|
+
settings.set(task.orgId, s);
|
|
130
|
+
}
|
|
131
|
+
const fired = await this.advance(t, task, now, s.catchUpWindowMinutes);
|
|
132
|
+
if (fired !== null) {
|
|
133
|
+
await oweAutomationFire(this.outbox, fired.id, task.orgId);
|
|
134
|
+
await oweAutomationSettleUnfired(this.outbox, fired.id, task.orgId, fired.scheduledFor, s.catchUpWindowMinutes);
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
});
|
|
132
138
|
}
|
|
133
139
|
/** A task the scan cannot advance stops being due: paused with `invalid_schedule`. */
|
|
134
140
|
async quarantine(taskId) {
|
|
@@ -147,7 +153,7 @@ let AutomationScanJob = class AutomationScanJob {
|
|
|
147
153
|
}, now, catchUpWindowMinutes);
|
|
148
154
|
}
|
|
149
155
|
catch (err) {
|
|
150
|
-
throw new TaskScanFailed(task.id, err);
|
|
156
|
+
throw new TaskScanFailed(task.id, task.orgId, err);
|
|
151
157
|
}
|
|
152
158
|
if (step.missed !== null) {
|
|
153
159
|
await this.store.insertRun(t, {
|
|
@@ -3,13 +3,10 @@ export { CatalogImportModule };
|
|
|
3
3
|
/**
|
|
4
4
|
* The plugin catalog (spec §4, §10): {@link CatalogImportModule}, catalog requests, org installs
|
|
5
5
|
* with their dependencies, the platform plugin update (`PlatformPluginUpdater`) and the update to a
|
|
6
|
-
* staged version (`PlatformImportUpdate`),
|
|
7
|
-
*
|
|
8
|
-
* (`
|
|
9
|
-
*
|
|
10
|
-
* with the queued job (`TemplateConnectorEnsurer`), and the producer of the plugin scope sync
|
|
11
|
-
* (`PluginScopeSync`; its consumer is the worker role's `PluginScopeWorkersModule`). The catalog's periodic jobs (`CatalogJobs`) are
|
|
12
|
-
* the worker role's (`WorkerModule`).
|
|
6
|
+
* staged version (`PlatformImportUpdate`), scope and disable controls (`CatalogScopeService`),
|
|
7
|
+
* org plugin uploads (`OrgPluginUploads`), org-owned plugins (`OwnedItems`), template connector
|
|
8
|
+
* convergence (`TemplateConnectorEnsurer`), and the plugin scope sync producer
|
|
9
|
+
* (`PluginScopeSync`). The scope consumer and periodic catalog jobs run in the worker role.
|
|
13
10
|
*/
|
|
14
11
|
export declare class CatalogModule {
|
|
15
12
|
}
|
|
@@ -28,7 +28,6 @@ import { CatalogRequestsService } from "./requests.service.js";
|
|
|
28
28
|
import { PLUGIN_SCOPE_QUEUE, PluginScopeSync } from "./scope-sync.js";
|
|
29
29
|
import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
|
|
30
30
|
import { TemplateConnectorsQueueModule } from "./template-connector-jobs.js";
|
|
31
|
-
import { TemplateConnectorReconciler } from "./template-connector-reconcile.js";
|
|
32
31
|
export { CatalogImportModule };
|
|
33
32
|
/** The plugin scope sync's queue registration (re-exported: the admin health reads its counts). */
|
|
34
33
|
const PLUGIN_SCOPE_QUEUE_MODULE = QueueModule.registerQueue(PLUGIN_SCOPE_QUEUE);
|
|
@@ -37,13 +36,10 @@ const MAINTENANCE_QUEUE_MODULE = QueueModule.registerQueue(MAINTENANCE_QUEUE_NAM
|
|
|
37
36
|
/**
|
|
38
37
|
* The plugin catalog (spec §4, §10): {@link CatalogImportModule}, catalog requests, org installs
|
|
39
38
|
* with their dependencies, the platform plugin update (`PlatformPluginUpdater`) and the update to a
|
|
40
|
-
* staged version (`PlatformImportUpdate`),
|
|
41
|
-
*
|
|
42
|
-
* (`
|
|
43
|
-
*
|
|
44
|
-
* with the queued job (`TemplateConnectorEnsurer`), and the producer of the plugin scope sync
|
|
45
|
-
* (`PluginScopeSync`; its consumer is the worker role's `PluginScopeWorkersModule`). The catalog's periodic jobs (`CatalogJobs`) are
|
|
46
|
-
* the worker role's (`WorkerModule`).
|
|
39
|
+
* staged version (`PlatformImportUpdate`), scope and disable controls (`CatalogScopeService`),
|
|
40
|
+
* org plugin uploads (`OrgPluginUploads`), org-owned plugins (`OwnedItems`), template connector
|
|
41
|
+
* convergence (`TemplateConnectorEnsurer`), and the plugin scope sync producer
|
|
42
|
+
* (`PluginScopeSync`). The scope consumer and periodic catalog jobs run in the worker role.
|
|
47
43
|
*/
|
|
48
44
|
let CatalogModule = class CatalogModule {
|
|
49
45
|
};
|
|
@@ -82,7 +78,6 @@ CatalogModule = __decorate([
|
|
|
82
78
|
OwnedItems,
|
|
83
79
|
PlatformImportUpdate,
|
|
84
80
|
TemplateConnectorEnsurer,
|
|
85
|
-
TemplateConnectorReconciler,
|
|
86
81
|
],
|
|
87
82
|
exports: [
|
|
88
83
|
PLUGIN_SCOPE_QUEUE_MODULE,
|
|
@@ -101,7 +96,6 @@ CatalogModule = __decorate([
|
|
|
101
96
|
OwnedItems,
|
|
102
97
|
PlatformImportUpdate,
|
|
103
98
|
TemplateConnectorEnsurer,
|
|
104
|
-
TemplateConnectorReconciler,
|
|
105
99
|
],
|
|
106
100
|
})
|
|
107
101
|
], CatalogModule);
|
|
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
|
|
|
208
208
|
/** The host versions (an entry's `minKernel` is judged against them). */
|
|
209
209
|
export declare const HOST_VERSIONS: {
|
|
210
210
|
readonly kernel: string;
|
|
211
|
-
readonly sdk: "0.1.0-rc.
|
|
211
|
+
readonly sdk: "0.1.0-rc.97";
|
|
212
212
|
};
|
|
213
213
|
/** Whether this deployment satisfies the entry's `minKernel`. */
|
|
214
214
|
export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
|
|
@@ -1190,7 +1190,8 @@ let PluginImport = class PluginImport {
|
|
|
1190
1190
|
const total = await this.cleanupStagingRows();
|
|
1191
1191
|
// display files no version or staging lists (an abandoned import's), older than a staging
|
|
1192
1192
|
try {
|
|
1193
|
-
|
|
1193
|
+
// org-filter: deployment-wide display files can be retained by staging in any org.
|
|
1194
|
+
await asPlatform("collect display files unused by any version or staging row", () => sweepDisplayFiles(this.db, PLUGIN_STAGING_TTL_MS));
|
|
1194
1195
|
}
|
|
1195
1196
|
catch (err) {
|
|
1196
1197
|
this.log.warn("cannot sweep unused catalog display files", { err });
|
|
@@ -573,8 +573,8 @@ export declare class PluginInstaller {
|
|
|
573
573
|
* connector from the template yet (one a switch-off kept is reused, left as it is). Created like
|
|
574
574
|
* an install's ({@link planConnector}, `createDeferredIn`: no outbound call, `needs_config` when
|
|
575
575
|
* it needs an org credential or OAuth client) and recorded on the install. Returns its id, or
|
|
576
|
-
* undefined when none was created. `actor` null: the kernel itself (
|
|
577
|
-
*
|
|
576
|
+
* undefined when none was created. `actor` null: the kernel itself (`TemplateConnectorEnsurer`),
|
|
577
|
+
* which checks the template is on and holds the org lock.
|
|
578
578
|
*/
|
|
579
579
|
createSwitchedOnTemplateConnectorIn(orgId: string, actor: string | null, platformTemplateId: string, opts?: {
|
|
580
580
|
actorTokenId?: string;
|
|
@@ -1736,8 +1736,8 @@ let PluginInstaller = class PluginInstaller {
|
|
|
1736
1736
|
* connector from the template yet (one a switch-off kept is reused, left as it is). Created like
|
|
1737
1737
|
* an install's ({@link planConnector}, `createDeferredIn`: no outbound call, `needs_config` when
|
|
1738
1738
|
* it needs an org credential or OAuth client) and recorded on the install. Returns its id, or
|
|
1739
|
-
* undefined when none was created. `actor` null: the kernel itself (
|
|
1740
|
-
*
|
|
1739
|
+
* undefined when none was created. `actor` null: the kernel itself (`TemplateConnectorEnsurer`),
|
|
1740
|
+
* which checks the template is on and holds the org lock.
|
|
1741
1741
|
*/
|
|
1742
1742
|
async createSwitchedOnTemplateConnectorIn(orgId, actor, platformTemplateId, opts = {}) {
|
|
1743
1743
|
const row = await this.db
|
|
@@ -29,13 +29,12 @@ export interface EnsureResult {
|
|
|
29
29
|
* `createDeferredIn`, no outbound call, `needs_config` when it needs an org credential or OAuth
|
|
30
30
|
* client, recorded on the install). The create re-checks that the connector kind is available
|
|
31
31
|
* in the org. A refusal (an `ApiError` from those checks) is logged and skipped. Any other error
|
|
32
|
-
* is thrown
|
|
33
|
-
*
|
|
34
|
-
* attempted: the queued ensure retries until it loads.
|
|
32
|
+
* is thrown so the caller can retry. A template whose connector extension is still loading is
|
|
33
|
+
* counted in `notLoaded` and skipped. The queued ensure retries it.
|
|
35
34
|
*
|
|
36
35
|
* Callers: the `template-connectors-ensure` job (owed by an install's commit and by an org
|
|
37
|
-
* switching an extension on), the plugin scope sync after it
|
|
38
|
-
* the
|
|
36
|
+
* switching an extension on), the plugin scope sync after it adds a plugin's dependencies, and
|
|
37
|
+
* the cursor-based sweep.
|
|
39
38
|
*/
|
|
40
39
|
export declare class TemplateConnectorEnsurer {
|
|
41
40
|
private readonly kdb;
|
|
@@ -53,8 +52,6 @@ export declare class TemplateConnectorEnsurer {
|
|
|
53
52
|
/** The refusals already warned about (a lease per org and template). */
|
|
54
53
|
locks: Pick<LockService, "lease">, txHost: TransactionHost);
|
|
55
54
|
private get db();
|
|
56
|
-
/** The live orgs with at least one template connector they never had (the startup pass). */
|
|
57
|
-
orgsMissing(): Promise<string[]>;
|
|
58
55
|
/**
|
|
59
56
|
* The backstop sweep (ruling R30, `CatalogJobs.sweepTemplateConnectors`): runs
|
|
60
57
|
* {@link ensureTemplateConnectorsIn} for at most `limit` orgs that have a template connector
|
|
@@ -11,6 +11,7 @@ import { Inject, Injectable } 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, withOrgScope } from "../infra/database/org-scope.js";
|
|
14
15
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
15
16
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
16
17
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
@@ -35,13 +36,12 @@ import { PluginInstaller } from "./plugin-install.js";
|
|
|
35
36
|
* `createDeferredIn`, no outbound call, `needs_config` when it needs an org credential or OAuth
|
|
36
37
|
* client, recorded on the install). The create re-checks that the connector kind is available
|
|
37
38
|
* in the org. A refusal (an `ApiError` from those checks) is logged and skipped. Any other error
|
|
38
|
-
* is thrown
|
|
39
|
-
*
|
|
40
|
-
* attempted: the queued ensure retries until it loads.
|
|
39
|
+
* is thrown so the caller can retry. A template whose connector extension is still loading is
|
|
40
|
+
* counted in `notLoaded` and skipped. The queued ensure retries it.
|
|
41
41
|
*
|
|
42
42
|
* Callers: the `template-connectors-ensure` job (owed by an install's commit and by an org
|
|
43
|
-
* switching an extension on), the plugin scope sync after it
|
|
44
|
-
* the
|
|
43
|
+
* switching an extension on), the plugin scope sync after it adds a plugin's dependencies, and
|
|
44
|
+
* the cursor-based sweep.
|
|
45
45
|
*/
|
|
46
46
|
let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
|
|
47
47
|
kdb;
|
|
@@ -67,11 +67,6 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
|
|
|
67
67
|
get db() {
|
|
68
68
|
return this.kdb.db;
|
|
69
69
|
}
|
|
70
|
-
/** The live orgs with at least one template connector they never had (the startup pass). */
|
|
71
|
-
async orgsMissing() {
|
|
72
|
-
const rows = await this.missingQuery(undefined, undefined).execute();
|
|
73
|
-
return [...new Set(rows.map((r) => r.org_id))];
|
|
74
|
-
}
|
|
75
70
|
/**
|
|
76
71
|
* The backstop sweep (ruling R30, `CatalogJobs.sweepTemplateConnectors`): runs
|
|
77
72
|
* {@link ensureTemplateConnectorsIn} for at most `limit` orgs that have a template connector
|
|
@@ -91,7 +86,8 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
|
|
|
91
86
|
const loaded = new Set(this.installer.loadedConnectors().map((c) => c.plugin));
|
|
92
87
|
if (loaded.size === 0)
|
|
93
88
|
return { orgs: 0, created: 0 };
|
|
94
|
-
|
|
89
|
+
// org-filter: deployment-wide sweep of candidate installs, before checking each org's kinds.
|
|
90
|
+
const rows = await asPlatform("find template connector sweep candidates", () => this.missingQuery(undefined, undefined)
|
|
95
91
|
.where(sql `t.file->'template'->>'plugin'`, "in", [...loaded])
|
|
96
92
|
.where("t.disabled", "=", false)
|
|
97
93
|
.where(({ not, exists, selectFrom }) => not(exists(selectFrom("component_org_switches as s")
|
|
@@ -109,7 +105,7 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
|
|
|
109
105
|
.whereRef("s.org_id", "=", "a.org_id")
|
|
110
106
|
.where("s.enabled", "=", true)),
|
|
111
107
|
]))
|
|
112
|
-
.execute();
|
|
108
|
+
.execute());
|
|
113
109
|
const kindsByOrg = new Map();
|
|
114
110
|
for (const r of rows) {
|
|
115
111
|
const t = r.file.template;
|
|
@@ -130,7 +126,7 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
|
|
|
130
126
|
if (orgs.length >= opts.limit)
|
|
131
127
|
break;
|
|
132
128
|
opts.signal?.throwIfAborted();
|
|
133
|
-
const available = await this.connectors.kinds(orgId);
|
|
129
|
+
const available = await withOrgScope(orgId, () => this.connectors.kinds(orgId));
|
|
134
130
|
if (wanted.some((w) => available.some((k) => k.kind === w.connector && k.plugin === w.plugin)))
|
|
135
131
|
orgs.push(orgId);
|
|
136
132
|
}
|
|
@@ -146,10 +142,10 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
|
|
|
146
142
|
let created = 0;
|
|
147
143
|
for (const orgId of orgs) {
|
|
148
144
|
opts.signal?.throwIfAborted();
|
|
149
|
-
const r = await this.ensureTemplateConnectorsIn(orgId, undefined, {
|
|
145
|
+
const r = await withOrgScope(orgId, () => this.ensureTemplateConnectorsIn(orgId, undefined, {
|
|
150
146
|
...(opts.signal !== undefined && { signal: opts.signal }),
|
|
151
147
|
via: "sweep",
|
|
152
|
-
});
|
|
148
|
+
}));
|
|
153
149
|
created += r.created;
|
|
154
150
|
}
|
|
155
151
|
return { orgs: orgs.length, created };
|
|
@@ -16,6 +16,7 @@ import { ExtensionRegistry } from "../extensions/registry.js";
|
|
|
16
16
|
import { ReplicaStatusStore } from "../extensions/sources.js";
|
|
17
17
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
18
18
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
19
|
+
import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
|
|
19
20
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
20
21
|
import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
|
|
21
22
|
import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
@@ -263,7 +264,7 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
263
264
|
// watchdog's to log and judge (lost at the renewal deadline)
|
|
264
265
|
const ok = await h.lease.renew().catch(() => undefined);
|
|
265
266
|
if (ok === true)
|
|
266
|
-
await this.afterRenew(id, h, ttl);
|
|
267
|
+
await withOrgScope(h.orgId, () => this.afterRenew(id, h, ttl));
|
|
267
268
|
// false: the key is gone or taken, or the lease was already lost (`drop` is idempotent)
|
|
268
269
|
else if (ok === false)
|
|
269
270
|
this.drop(id, h);
|
|
@@ -372,21 +373,31 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
372
373
|
* 可以持有的连接:active、未删除、所属组织未删除、插件在该组织启用(组织停用插件 / 删除组织时持有方据此断开),
|
|
373
374
|
* 且插件在本进程已加载——滚动升级期间还没有该插件的副本根本不考虑它(不取租约、不记失败),留给有插件的副本。
|
|
374
375
|
*/
|
|
375
|
-
runnable(plugins) {
|
|
376
|
+
runnable(plugins, ids) {
|
|
376
377
|
const db = this.db.db;
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
378
|
+
// org-filter: deployment-wide scan for active long connections served by this gateway
|
|
379
|
+
return asPlatform("list runnable channel connections across orgs", () => {
|
|
380
|
+
let query = db
|
|
381
|
+
.selectFrom("channel_connections")
|
|
382
|
+
.innerJoin("orgs", "orgs.id", "channel_connections.org_id")
|
|
383
|
+
.innerJoin(enabledExtensionsByOrg(db).as("en"), (j) => j
|
|
384
|
+
.onRef("en.plugin", "=", "channel_connections.plugin")
|
|
385
|
+
.onRef("en.org_id", "=", "channel_connections.org_id"))
|
|
386
|
+
.select([
|
|
387
|
+
"channel_connections.id",
|
|
388
|
+
"channel_connections.org_id",
|
|
389
|
+
"channel_connections.plugin",
|
|
390
|
+
])
|
|
391
|
+
.where("channel_connections.status", "=", "active")
|
|
392
|
+
// Webhook-mode connections get callbacks on the gateway route instead (F9)
|
|
393
|
+
.where("channel_connections.inbound_mode", "=", "long_connection")
|
|
394
|
+
.where("channel_connections.deleted_at", "is", null)
|
|
395
|
+
.where("orgs.deleted_at", "is", null)
|
|
396
|
+
.where("channel_connections.plugin", "in", plugins);
|
|
397
|
+
if (ids)
|
|
398
|
+
query = query.where("channel_connections.id", "in", ids);
|
|
399
|
+
return query.execute();
|
|
400
|
+
});
|
|
390
401
|
}
|
|
391
402
|
/**
|
|
392
403
|
* 持有的连接仍须可持有(bus 广播是尽力而为,这里兜底)。交还不等待:交还要等插件 `connect` 返回(至多 SETTLE_MS),
|
|
@@ -397,9 +408,7 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
397
408
|
if (ids.length === 0)
|
|
398
409
|
return;
|
|
399
410
|
const plugins = this.localPlugins();
|
|
400
|
-
const live = new Set(plugins.length === 0
|
|
401
|
-
? []
|
|
402
|
-
: (await this.runnable(plugins).where("channel_connections.id", "in", ids).execute()).map((r) => r.id));
|
|
411
|
+
const live = new Set(plugins.length === 0 ? [] : (await this.runnable(plugins, ids)).map((r) => r.id));
|
|
403
412
|
for (const id of ids) {
|
|
404
413
|
const h = this.held.get(id);
|
|
405
414
|
if (h && !live.has(id))
|
|
@@ -418,7 +427,7 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
418
427
|
const plugins = this.localPlugins();
|
|
419
428
|
if (plugins.length === 0)
|
|
420
429
|
return;
|
|
421
|
-
const rows = await this.runnable(plugins)
|
|
430
|
+
const rows = await this.runnable(plugins);
|
|
422
431
|
const runnable = new Map();
|
|
423
432
|
for (const r of rows)
|
|
424
433
|
runnable.set(r.plugin, (runnable.get(r.plugin) ?? 0) + 1);
|
|
@@ -431,7 +440,7 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
431
440
|
if (held >= target)
|
|
432
441
|
full.add(p);
|
|
433
442
|
}
|
|
434
|
-
for (const { id, plugin } of rows) {
|
|
443
|
+
for (const { id, plugin, org_id: orgId } of rows) {
|
|
435
444
|
if (this.stopped)
|
|
436
445
|
return;
|
|
437
446
|
if (full.has(plugin))
|
|
@@ -454,7 +463,7 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
454
463
|
await lease.release();
|
|
455
464
|
return;
|
|
456
465
|
}
|
|
457
|
-
await this.connect(id, lease);
|
|
466
|
+
await withOrgScope(orgId, () => this.connect(id, lease));
|
|
458
467
|
}
|
|
459
468
|
}
|
|
460
469
|
/** 已取得租约:读配置并在后台跑插件的 `connect`。 */
|
|
@@ -483,6 +492,7 @@ let ChannelSupervisor = class ChannelSupervisor {
|
|
|
483
492
|
const abort = new AbortController();
|
|
484
493
|
const now = Date.now();
|
|
485
494
|
const h = {
|
|
495
|
+
orgId: rt.row.orgId,
|
|
486
496
|
plugin: rt.row.plugin,
|
|
487
497
|
lease,
|
|
488
498
|
abort,
|
|
@@ -714,7 +724,8 @@ export async function checkGatewayPresence(deps) {
|
|
|
714
724
|
return false;
|
|
715
725
|
// Webhook-mode connections count too (Ruling R4): the webhook route is served only by gateway
|
|
716
726
|
// replicas, so without one their callbacks get no answer either
|
|
717
|
-
|
|
727
|
+
// org-filter: deployment-wide count of active connections requiring a gateway
|
|
728
|
+
const rows = await asPlatform("count connections needing a gateway across orgs", () => deps.db
|
|
718
729
|
.selectFrom("channel_connections")
|
|
719
730
|
.innerJoin("orgs", "orgs.id", "channel_connections.org_id")
|
|
720
731
|
.innerJoin(enabledExtensionsByOrg(deps.db).as("en"), (j) => j
|
|
@@ -725,7 +736,7 @@ export async function checkGatewayPresence(deps) {
|
|
|
725
736
|
.where("channel_connections.deleted_at", "is", null)
|
|
726
737
|
.where("orgs.deleted_at", "is", null)
|
|
727
738
|
.groupBy("channel_connections.plugin")
|
|
728
|
-
.execute();
|
|
739
|
+
.execute());
|
|
729
740
|
const counts = new Map(rows.map((r) => [r.plugin, Number(r.n)]));
|
|
730
741
|
const plugins = [...counts.keys()].filter((p) => (counts.get(p) ?? 0) > 0).sort();
|
|
731
742
|
if (plugins.length === 0)
|
package/dist/channels/webhook.js
CHANGED
|
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
10
10
|
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
11
11
|
import { ApiError, errorBody } from "../errors.js";
|
|
12
12
|
import { ExtensionUnloadedError } from "../extensions/inflight.js";
|
|
13
|
+
import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
|
|
13
14
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
14
15
|
import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
15
16
|
import { ChannelConnections } from "./connections.service.js";
|
|
@@ -168,11 +169,11 @@ let ChannelWebhooks = class ChannelWebhooks {
|
|
|
168
169
|
this.log.warn("cannot record the channel webhook marker", { connectionId, err });
|
|
169
170
|
}
|
|
170
171
|
}
|
|
171
|
-
async runtime(connectionId, deadline) {
|
|
172
|
+
async runtime(connectionId, orgId, deadline) {
|
|
172
173
|
const ttl = this.runtimeCacheMs;
|
|
173
174
|
const now = Date.now();
|
|
174
175
|
const hit = this.runtimes.get(connectionId);
|
|
175
|
-
if (hit && hit.expiresAt > now)
|
|
176
|
+
if (hit?.orgId === orgId && hit.expiresAt > now)
|
|
176
177
|
return hit.value;
|
|
177
178
|
const generation = this.generation;
|
|
178
179
|
const value = await raceAbort(this.connections.runtime(connectionId), deadline);
|
|
@@ -185,7 +186,7 @@ let ChannelWebhooks = class ChannelWebhooks {
|
|
|
185
186
|
break;
|
|
186
187
|
this.runtimes.delete(oldest);
|
|
187
188
|
}
|
|
188
|
-
this.runtimes.set(connectionId, { value, expiresAt: now + ttl });
|
|
189
|
+
this.runtimes.set(connectionId, { orgId, value, expiresAt: now + ttl });
|
|
189
190
|
}
|
|
190
191
|
return value;
|
|
191
192
|
}
|
|
@@ -206,7 +207,8 @@ let ChannelWebhooks = class ChannelWebhooks {
|
|
|
206
207
|
}
|
|
207
208
|
}
|
|
208
209
|
async respondBefore(connectionId, request, deadline) {
|
|
209
|
-
|
|
210
|
+
// org-filter: deployment-wide lookup of the connection addressed by an incoming webhook
|
|
211
|
+
const row = await asPlatform("identify the connection receiving a channel webhook", () => raceAbort(this.connections.row(connectionId), deadline));
|
|
210
212
|
if (row === undefined ||
|
|
211
213
|
row.inboundMode !== "webhook" ||
|
|
212
214
|
row.status !== "active" ||
|
|
@@ -214,9 +216,12 @@ let ChannelWebhooks = class ChannelWebhooks {
|
|
|
214
216
|
this.invalidate(connectionId);
|
|
215
217
|
return notFound();
|
|
216
218
|
}
|
|
219
|
+
return withOrgScope(row.orgId, () => this.handleInOrg(connectionId, row.orgId, request, deadline));
|
|
220
|
+
}
|
|
221
|
+
async handleInOrg(connectionId, orgId, request, deadline) {
|
|
217
222
|
let runtime;
|
|
218
223
|
try {
|
|
219
|
-
runtime = await this.runtime(connectionId, deadline);
|
|
224
|
+
runtime = await this.runtime(connectionId, orgId, deadline);
|
|
220
225
|
}
|
|
221
226
|
catch (err) {
|
|
222
227
|
if (err instanceof WebhookDeadline)
|
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import type { KernelSchemaDb } from "../db/kernel-schema.js";
|
|
2
2
|
/** Looks up the owning org before a worker processes a conversation job. */
|
|
3
3
|
export declare function resolveConversationOrg(db: KernelSchemaDb, conversationId: string): Promise<string | undefined>;
|
|
4
|
+
/** A run backstop may carry just its run id. When both ids are present they must agree. */
|
|
5
|
+
export declare function resolveRunOrg(db: KernelSchemaDb, runId: string, conversationId?: string): Promise<string | undefined>;
|
|
@@ -9,3 +9,15 @@ export async function resolveConversationOrg(db, conversationId) {
|
|
|
9
9
|
.executeTakeFirst());
|
|
10
10
|
return row?.org_id;
|
|
11
11
|
}
|
|
12
|
+
/** A run backstop may carry just its run id. When both ids are present they must agree. */
|
|
13
|
+
export async function resolveRunOrg(db, runId, conversationId) {
|
|
14
|
+
// org-filter: deployment-wide lookup of the conversation owner of a queued run id
|
|
15
|
+
const row = await asPlatform("resolve the org of a queued run", () => db
|
|
16
|
+
.selectFrom("runs as r")
|
|
17
|
+
.innerJoin("conversations as c", "c.id", "r.conversation_id")
|
|
18
|
+
.select("c.org_id")
|
|
19
|
+
.where("r.id", "=", runId)
|
|
20
|
+
.$if(conversationId !== undefined, (q) => q.where("c.id", "=", conversationId))
|
|
21
|
+
.executeTakeFirst());
|
|
22
|
+
return row?.org_id;
|
|
23
|
+
}
|
package/dist/ctx/create-ctx.js
CHANGED
|
@@ -619,7 +619,8 @@ identity = { sha256: null }) {
|
|
|
619
619
|
// current role still meets the slot's minRole (a demoted caller's token stops working)
|
|
620
620
|
if (slot === undefined || slot.id === "platform.page")
|
|
621
621
|
return null;
|
|
622
|
-
const
|
|
622
|
+
const { orgId, accountId } = claims;
|
|
623
|
+
const role = await withOrgScope(orgId, () => currentOrgRole(deps.db, name, orgId, accountId));
|
|
623
624
|
if (role === undefined || !canUseSlot(slot, role))
|
|
624
625
|
return null;
|
|
625
626
|
// a skill file's token: the current role must still read skills (the issuing route's check)
|
|
@@ -226,6 +226,7 @@ export interface OrgsTable {
|
|
|
226
226
|
storage_purge_claimed_at: TsNullable;
|
|
227
227
|
}
|
|
228
228
|
export interface MembershipsTable {
|
|
229
|
+
checklist_dismissed: Generated<boolean>;
|
|
229
230
|
org_id: string;
|
|
230
231
|
account_id: string;
|
|
231
232
|
role: "owner" | "admin" | "member" | "guest";
|
|
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
9
9
|
};
|
|
10
10
|
import { Controller, Get, HttpCode, Inject, Post, Req, Res } from "@nestjs/common";
|
|
11
11
|
import { CurrentPrincipal, Public, requireUser, SessionOnly, } from "../identity/principal.js";
|
|
12
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
12
13
|
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
13
14
|
import { Throttled } from "../infra/throttler/throttler.guard.js";
|
|
14
15
|
import { ZBody, ZParam, ZQuery } from "../infra/validation/zod-params.js";
|
|
@@ -57,11 +58,11 @@ let DialInAuthController = class DialInAuthController {
|
|
|
57
58
|
}
|
|
58
59
|
async providers(principal, query, req, reply) {
|
|
59
60
|
const p = requireUser(principal);
|
|
60
|
-
return this.counted(req, reply, () => this.auth.providers(p, query));
|
|
61
|
+
return this.counted(req, reply, () => withOrgScope(query.orgId, () => this.auth.providers(p, query)));
|
|
61
62
|
}
|
|
62
63
|
async confirm(principal, body, req, reply) {
|
|
63
64
|
const p = requireUser(principal);
|
|
64
|
-
return this.counted(req, reply, () => this.auth.confirm(p, body));
|
|
65
|
+
return this.counted(req, reply, () => withOrgScope(body.orgId, () => this.auth.confirm(p, body)));
|
|
65
66
|
}
|
|
66
67
|
async deny(principal, body, req, reply) {
|
|
67
68
|
requireUser(principal);
|
|
@@ -17,6 +17,7 @@ import { audit } from "../identity/audit.js";
|
|
|
17
17
|
import { sha256Hex } from "../identity/hash.js";
|
|
18
18
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
19
19
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
20
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
20
21
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
21
22
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
22
23
|
import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
@@ -188,7 +189,7 @@ let DialInAuthService = class DialInAuthService {
|
|
|
188
189
|
case "approved": {
|
|
189
190
|
const grant = JSON.parse(r[1]);
|
|
190
191
|
const dialIn = this.config.get().devices.dialIn;
|
|
191
|
-
const [deployment, settings, device, org] = await Promise.all([
|
|
192
|
+
const [deployment, settings, device, org] = await withOrgScope(grant.orgId, () => Promise.all([
|
|
192
193
|
readDeploymentDevicePolicy(this.db.db, this.config),
|
|
193
194
|
readOrgSettings(this.db.db, grant.orgId),
|
|
194
195
|
this.db.db
|
|
@@ -203,7 +204,7 @@ let DialInAuthService = class DialInAuthService {
|
|
|
203
204
|
.where("id", "=", grant.orgId)
|
|
204
205
|
// the grant's org exists: the device row it names references it
|
|
205
206
|
.executeTakeFirstOrThrow(),
|
|
206
|
-
]);
|
|
207
|
+
]));
|
|
207
208
|
return {
|
|
208
209
|
...grant,
|
|
209
210
|
connectUrl,
|
|
@@ -251,7 +251,6 @@ export declare class DialInGateway {
|
|
|
251
251
|
* before the upgrade): null for an unknown or revoked credential.
|
|
252
252
|
*/
|
|
253
253
|
admit(credential: string): Promise<DialInAdmission>;
|
|
254
|
-
private admitted;
|
|
255
254
|
/**
|
|
256
255
|
* Serves one upgraded socket of a machine until it closes, speaking `protocol` (the route
|
|
257
256
|
* admitted it). The credential and the provider are checked again here, with the socket paused,
|
package/dist/dial-in/gateway.js
CHANGED
|
@@ -283,12 +283,12 @@ class DeviceConnection {
|
|
|
283
283
|
this.schedulePing();
|
|
284
284
|
socket.on("pong", () => {
|
|
285
285
|
this.missedPongs = 0;
|
|
286
|
-
this.traffic();
|
|
286
|
+
this.inOrg(() => this.traffic());
|
|
287
287
|
});
|
|
288
288
|
socket.on("message", (data, isBinary) => {
|
|
289
289
|
if (this.state === "closed")
|
|
290
290
|
return;
|
|
291
|
-
this.traffic();
|
|
291
|
+
this.inOrg(() => this.traffic());
|
|
292
292
|
if (isBinary) {
|
|
293
293
|
void this.inOrg(() => this.onBinary(data));
|
|
294
294
|
return;
|
|
@@ -851,7 +851,7 @@ class DeviceConnection {
|
|
|
851
851
|
return;
|
|
852
852
|
this.accepted = undefined;
|
|
853
853
|
try {
|
|
854
|
-
const r = accepted.handler.onClose?.(this.deviceId, this.closeReason, this.info());
|
|
854
|
+
const r = this.inOrg(() => accepted.handler.onClose?.(this.deviceId, this.closeReason, this.info()));
|
|
855
855
|
if (r instanceof Promise)
|
|
856
856
|
r.catch((e) => this.gw.log.warn("device provider failed onClose", {
|
|
857
857
|
deviceId: this.deviceId,
|
|
@@ -974,14 +974,11 @@ let DialInGateway = class DialInGateway {
|
|
|
974
974
|
* before the upgrade): null for an unknown or revoked credential.
|
|
975
975
|
*/
|
|
976
976
|
async admit(credential) {
|
|
977
|
-
//
|
|
978
|
-
|
|
979
|
-
}
|
|
980
|
-
async admitted(credential) {
|
|
981
|
-
const identity = await this.machines.authenticate(credential);
|
|
977
|
+
// org-filter: deployment-wide lookup of a machine credential before its org is known
|
|
978
|
+
const identity = await asPlatform("dial-in credential lookup", () => this.machines.authenticate(credential));
|
|
982
979
|
if (identity === null)
|
|
983
980
|
return null;
|
|
984
|
-
const serving = await this.handlers.forDevice(identity.deviceId);
|
|
981
|
+
const serving = await withOrgScope(identity.orgId, () => this.handlers.forDevice(identity.deviceId));
|
|
985
982
|
return "unavailable" in serving
|
|
986
983
|
? { identity, unavailable: serving.unavailable }
|
|
987
984
|
: { identity, serving };
|