@feltdb/feltkit 0.3.33 → 0.3.34

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 (67) hide show
  1. package/dist/app.d.ts +15 -0
  2. package/dist/app.js +2 -0
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +3 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/runtime.d.ts +1 -1
  7. package/dist/appboundry/runtime.js +1 -1
  8. package/dist/appboundry/runtime.js.map +1 -1
  9. package/dist/cli/deploy-appboundry-self-hosted.js +10 -4
  10. package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
  11. package/dist/cli/main.js +1 -1
  12. package/dist/cli/main.js.map +1 -1
  13. package/dist/client/index.d.ts +8 -0
  14. package/dist/client/index.js +7 -0
  15. package/dist/client/index.js.map +1 -1
  16. package/dist/component.js +1 -1
  17. package/dist/component.js.map +1 -1
  18. package/dist/docs.d.ts +1 -1
  19. package/dist/docs.js +1 -0
  20. package/dist/docs.js.map +1 -1
  21. package/dist/measure/index.js +17 -0
  22. package/dist/measure/index.js.map +1 -1
  23. package/dist/providers.d.ts +23 -0
  24. package/dist/providers.js +29 -0
  25. package/dist/providers.js.map +1 -0
  26. package/dist/runtime/access-grants.d.ts +25 -0
  27. package/dist/runtime/access-grants.js +78 -0
  28. package/dist/runtime/access-grants.js.map +1 -0
  29. package/dist/runtime/authority.d.ts +11 -1
  30. package/dist/runtime/authority.js +2 -1
  31. package/dist/runtime/authority.js.map +1 -1
  32. package/dist/runtime/backup.js +2 -1
  33. package/dist/runtime/backup.js.map +1 -1
  34. package/dist/runtime/context.d.ts +8 -0
  35. package/dist/runtime/contract.js +10 -1
  36. package/dist/runtime/contract.js.map +1 -1
  37. package/dist/runtime/loader.js +2 -1
  38. package/dist/runtime/loader.js.map +1 -1
  39. package/dist/runtime/providers.d.ts +72 -0
  40. package/dist/runtime/providers.js +252 -0
  41. package/dist/runtime/providers.js.map +1 -0
  42. package/dist/runtime/runtime.d.ts +32 -1
  43. package/dist/runtime/runtime.js +116 -6
  44. package/dist/runtime/runtime.js.map +1 -1
  45. package/dist/runtime/sessions.d.ts +41 -1
  46. package/dist/runtime/sessions.js +74 -7
  47. package/dist/runtime/sessions.js.map +1 -1
  48. package/dist/server/admin.js +6 -1
  49. package/dist/server/admin.js.map +1 -1
  50. package/dist/server/index.d.ts +1 -0
  51. package/dist/server/index.js +36 -4
  52. package/dist/server/index.js.map +1 -1
  53. package/dist/server/mcp.d.ts +5 -0
  54. package/dist/server/mcp.js +42 -1
  55. package/dist/server/mcp.js.map +1 -1
  56. package/dist/server/project.d.ts +8 -0
  57. package/dist/server/project.js +10 -1
  58. package/dist/server/project.js.map +1 -1
  59. package/dist/server/tenancy.js +1 -1
  60. package/dist/server/tenancy.js.map +1 -1
  61. package/docs/AUTH.md +40 -0
  62. package/docs/MEASURE.md +8 -1
  63. package/docs/PROVIDERS.md +103 -0
  64. package/docs/README.md +3 -2
  65. package/package.json +11 -10
  66. package/skills/.claude-plugin/marketplace.json +1 -1
  67. package/skills/.claude-plugin/plugin.json +1 -1
@@ -0,0 +1,252 @@
1
+ /**
2
+ * AppPort providers in a FeltKit application: `feltkit({ providers: { <name>: { provider, config?, credentials? } } })`.
3
+ *
4
+ * A provider is a package's `defineProvider(...)` from `@appport/core`: capabilities, a configuration schema, the
5
+ * credentials it needs, and how to start. FeltKit composes any provider the same way, knowing nothing about it:
6
+ *
7
+ * start validate the configuration against the provider's schema, then start it with credentials from
8
+ * FeltKit's custody (only the ids the application mapped; FELTKIT_CREDENTIAL_<ID> in production)
9
+ * register its capabilities join the application's AppPort registry beside the application's own functions,
10
+ * so roles authorize them on every surface (HTTP, WebSocket, MCP, agents) through the one pipeline
11
+ * execute handlers run outside any FeltDB transaction. An external effect is recorded in this environment's
12
+ * FeltDB instance before it is attempted (`started`) and after (`succeeded` / `failed` / `unknown`),
13
+ * with the same meaning as integration calls: a process that dies in between leaves `started`, which
14
+ * is unknown, and an unknown outcome is never retried automatically
15
+ * supervise stopped (close, then abort) when the runtime closes; restarted on reload only when its
16
+ * declaration changed
17
+ *
18
+ * Credentials are resolved when the provider starts and never recorded, returned, or logged by FeltKit.
19
+ */
20
+ import { resolve } from "node:path";
21
+ import { pathToFileURL } from "node:url";
22
+ import { AccessGrantRefused, AccessGrants, channelResource, EFFECT_OUTCOME_UNKNOWN, grantChannelIssuer, instantiateProvider, isProviderDefinition } from "@appport/core";
23
+ import { FeltKitError } from "../errors.js";
24
+ import { FeltDbAccessGrantStore } from "./access-grants.js";
25
+ export const PROVIDER_CALLS = "_feltkit_provider_calls";
26
+ /**
27
+ * Imports a declared provider: a path relative to the project, or a package export resolved like an import from
28
+ * FeltKit's own installation (the project's node_modules). Checks that the export is a provider definition and that
29
+ * every credential the application maps is one the provider declares.
30
+ */
31
+ export async function loadProvider(name, declaration, projectDir) {
32
+ const where = `providers.${name}`;
33
+ const specifier = declaration.module.startsWith(".") || declaration.module.startsWith("/") ? pathToFileURL(resolve(projectDir, declaration.module)).href : declaration.module;
34
+ let module;
35
+ try {
36
+ module = (await import(specifier));
37
+ }
38
+ catch (error) {
39
+ throw new FeltKitError("CONFIGURATION", `${where}.module "${declaration.module}" could not be loaded: ${error instanceof Error ? error.message : String(error)}`, { hint: "Install the package that provides it, or fix the path (relative to the project)." });
40
+ }
41
+ const exported = declaration.export ?? "default";
42
+ const provider = module[exported];
43
+ if (!isProviderDefinition(provider))
44
+ throw new FeltKitError("CONFIGURATION", `${where}: "${declaration.module}" exports no provider definition as ${exported === "default" ? "its default export" : `"${exported}"`}.`, { hint: "Name the export with providers.<name>.export." });
45
+ const declared = new Set(provider.credentials.map((c) => c.id));
46
+ for (const id of Object.keys(declaration.credentials ?? {})) {
47
+ if (!declared.has(id))
48
+ throw new FeltKitError("CONFIGURATION", `${where}.credentials: ${provider.id} declares no credential "${id}" (it declares ${[...declared].join(", ") || "none"}).`);
49
+ }
50
+ return provider;
51
+ }
52
+ /** Starts, registers, records, and stops the application's providers. */
53
+ export class ProviderHost {
54
+ #runtime;
55
+ #running = new Map();
56
+ #grants = null;
57
+ #projectDir = process.cwd();
58
+ constructor(runtime) {
59
+ this.#runtime = runtime;
60
+ }
61
+ /** Channel grants, kept in this environment's FeltDB instance (digests only). One minute by default, at most five. */
62
+ get grants() {
63
+ this.#grants ??= new AccessGrants({ store: new FeltDbAccessGrantStore(this.#runtime.instance.handle("feltkit.grants")) });
64
+ return this.#grants;
65
+ }
66
+ /** Where a provider channel is served on the application's port. Relative, so it works on any origin the app is opened at. */
67
+ static channelPath(provider, channel) {
68
+ return `/_provider/${provider}/${channel}`;
69
+ }
70
+ /**
71
+ * A connection on a provider channel (`/_provider/<name>/<channel>`): the grant it presents is redeemed atomically for
72
+ * exactly that channel and purpose, and only then is the connection handed to the provider. Returns the refusal
73
+ * reason, or null when the provider took it.
74
+ */
75
+ async accept(provider, channel, secret, transport) {
76
+ const running = this.#running.get(provider);
77
+ const declaration = running?.provider.channels?.find((c) => c.name === channel);
78
+ if (!running || !declaration || !running.instance.accept)
79
+ return "no-channel";
80
+ try {
81
+ const grant = await this.grants.redeem(secret, { purpose: declaration.purpose, resource: channelResource(provider, channel) });
82
+ await running.instance.accept({ channel, grant, transport });
83
+ return null;
84
+ }
85
+ catch (error) {
86
+ if (error instanceof AccessGrantRefused)
87
+ return error.reason;
88
+ this.#runtime.logger.error?.(`provider ${provider}: channel ${channel} failed`, { error: String(error) });
89
+ return "failed";
90
+ }
91
+ }
92
+ get #db() {
93
+ return this.#runtime.instance.handle("feltkit.providers");
94
+ }
95
+ /** Brings the running providers in line with the declarations: starts new or changed ones, stops removed ones. */
96
+ async sync(declarations, projectDir) {
97
+ this.#projectDir = projectDir;
98
+ const wanted = Object.entries(declarations ?? {});
99
+ const next = new Map();
100
+ for (const [name, declaration] of wanted) {
101
+ const signature = signatureOf(declaration);
102
+ const current = this.#running.get(name);
103
+ if (current && current.signature === signature) {
104
+ next.set(name, current);
105
+ continue;
106
+ }
107
+ if (current)
108
+ await this.#stop(current);
109
+ next.set(name, await this.#start(name, declaration, signature));
110
+ }
111
+ for (const [name, running] of this.#running)
112
+ if (!next.has(name))
113
+ await this.#stop(running);
114
+ this.#running = next;
115
+ }
116
+ /** The providers' capabilities, instantiated with this host's recorder. */
117
+ capabilities() {
118
+ const all = [];
119
+ for (const running of this.#running.values()) {
120
+ all.push(...instantiateProvider(running.provider, running.instance, {
121
+ name: running.name,
122
+ recorder: this.#recorder(),
123
+ channels: grantChannelIssuer({ grants: this.grants, url: (provider, channel) => ProviderHost.channelPath(provider, channel.name) }),
124
+ onRecordError: (error, call) => this.#runtime.logger.error?.(`provider ${running.name}: the outcome of ${call.id} could not be recorded`, { error: String(error), outcome: call.outcome }),
125
+ }));
126
+ }
127
+ return all;
128
+ }
129
+ /** The capability names the running providers publish. */
130
+ capabilityNames() {
131
+ return [...this.#running.values()].flatMap((running) => running.provider.capabilities.map((c) => c.options.name));
132
+ }
133
+ /** Whether a capability name belongs to a running provider. */
134
+ provides(capability) {
135
+ for (const running of this.#running.values())
136
+ if (running.provider.capabilities.some((c) => c.options.name === capability))
137
+ return true;
138
+ return false;
139
+ }
140
+ async health() {
141
+ const result = {};
142
+ for (const [name, running] of this.#running) {
143
+ try {
144
+ result[name] = running.instance.health ? await running.instance.health() : { state: "ready" };
145
+ }
146
+ catch (error) {
147
+ result[name] = { state: "failed", detail: error instanceof Error ? error.message : String(error) };
148
+ }
149
+ }
150
+ return result;
151
+ }
152
+ /** A provider's external call record. */
153
+ async call(id) {
154
+ return (await this.#db.collection(PROVIDER_CALLS).get(id)) ?? null;
155
+ }
156
+ async close() {
157
+ for (const running of this.#running.values())
158
+ await this.#stop(running);
159
+ this.#running.clear();
160
+ }
161
+ async #start(name, declaration, signature) {
162
+ const provider = await loadProvider(name, declaration, this.#projectDir);
163
+ let config = declaration.config ?? {};
164
+ if (provider.configuration) {
165
+ const parsed = provider.configuration.validate(config);
166
+ if (!parsed.ok)
167
+ throw new FeltKitError("CONFIGURATION", `providers.${name}.config does not match ${provider.id}'s configuration: ${parsed.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
168
+ config = parsed.value;
169
+ }
170
+ const mapped = declaration.credentials ?? {};
171
+ for (const credential of provider.credentials) {
172
+ if ((credential.required ?? true) && !mapped[credential.id]) {
173
+ throw new FeltKitError("CONFIGURATION", `providers.${name} needs the credential "${credential.id}" (${credential.description}).`, { hint: `Map it to one of this application's credentials: providers.${name}.credentials.${credential.id}.` });
174
+ }
175
+ }
176
+ const abort = new AbortController();
177
+ const log = this.#runtime.logger;
178
+ try {
179
+ const instance = await provider.start({
180
+ name,
181
+ config,
182
+ signal: abort.signal,
183
+ credential: async (id) => {
184
+ if (!provider.credentials.some((c) => c.id === id))
185
+ throw new FeltKitError("FORBIDDEN", `${provider.id} did not declare credential "${id}".`);
186
+ const target = mapped[id];
187
+ if (!target)
188
+ return null;
189
+ try {
190
+ return await this.#runtime.credentials.withSecret({ reference: { secretId: target }, context: { purpose: `provider:${name}` } }, (secret) => secret.value);
191
+ }
192
+ catch {
193
+ return null;
194
+ }
195
+ },
196
+ log: {
197
+ info: (message) => log.info?.(`provider ${name}: ${message}`),
198
+ warn: (message) => log.warn?.(`provider ${name}: ${message}`),
199
+ error: (message) => log.error?.(`provider ${name}: ${message}`),
200
+ },
201
+ });
202
+ return { name, declaration, provider, signature, instance, abort };
203
+ }
204
+ catch (error) {
205
+ abort.abort();
206
+ if (error instanceof FeltKitError)
207
+ throw error;
208
+ throw new FeltKitError("CONFIGURATION", `providers.${name} (${provider.id}) failed to start: ${error instanceof Error ? error.message : String(error)}`);
209
+ }
210
+ }
211
+ async #stop(running) {
212
+ try {
213
+ await running.instance.close?.();
214
+ }
215
+ catch (error) {
216
+ this.#runtime.logger.warn?.(`provider ${running.name} did not close cleanly`, { error: String(error) });
217
+ }
218
+ finally {
219
+ running.abort.abort();
220
+ }
221
+ }
222
+ #recorder() {
223
+ const db = () => this.#db;
224
+ const environment = this.#runtime.environment.name;
225
+ return {
226
+ async started(call) {
227
+ await db().transaction({ operations: [{ collection: PROVIDER_CALLS, id: call.id, requireAbsent: true, value: { ...call, state: "started", environment } }] });
228
+ },
229
+ async finished(call) {
230
+ const current = (await db().collection(PROVIDER_CALLS).get(call.id));
231
+ if (!current)
232
+ throw new Error(`No started record for ${call.id}`);
233
+ const { __version, ...started } = current;
234
+ await db().transaction({ operations: [{ collection: PROVIDER_CALLS, id: call.id, ifVersion: __version, value: { ...started, state: call.outcome, finishedAt: call.finishedAt, ...(call.error ? { error: call.error } : {}) } }] });
235
+ },
236
+ };
237
+ }
238
+ }
239
+ function signatureOf(declaration) {
240
+ return JSON.stringify([declaration.module, declaration.export ?? "default", declaration.config ?? null, declaration.credentials ?? {}]);
241
+ }
242
+ /**
243
+ * An AppPort error from a provider capability as the FeltKit error application code sees. An effect whose outcome is
244
+ * unknown is OUTCOME_UNKNOWN, exactly as for an integration call; other codes keep their meaning.
245
+ */
246
+ export function providerError(error) {
247
+ const details = error.details;
248
+ const code = error.code === "CONFLICT" && details?.reason === EFFECT_OUTCOME_UNKNOWN ? "OUTCOME_UNKNOWN"
249
+ : { INVALID_INPUT: "INVALID_ARGUMENT", INVALID_REQUEST: "INVALID_ARGUMENT", UNKNOWN_CAPABILITY: "NOT_FOUND", UNAUTHORIZED: "UNAUTHORIZED", FORBIDDEN: "FORBIDDEN", NOT_FOUND: "NOT_FOUND", CONFLICT: "CONFLICT", RATE_LIMITED: "RATE_LIMITED", TIMEOUT: "UNAVAILABLE", CANCELLED: "UNAVAILABLE", PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE" }[error.code] ?? "UNAVAILABLE";
250
+ return new FeltKitError(code, error.message, { ...(error.details !== undefined ? { details: { ...error.details, appportCode: error.code } } : { details: { appportCode: error.code } }) });
251
+ }
252
+ //# sourceMappingURL=providers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.js","sourceRoot":"","sources":["../../src/runtime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AAS,CAAC,CAAC,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,IAAI,SAAS,EAAE,WAAW,CAAC,MAAM,IAAI,IAAI,EAAE,WAAW,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,CAAC;AAC1I,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,KAA2D;IACvF,MAAM,OAAO,GAAG,KAAK,CAAC,OAA2C,CAAC;IAClE,MAAM,IAAI,GACR,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,EAAE,MAAM,KAAK,sBAAsB,CAAC,CAAC,CAAC,iBAAiB;QACzF,CAAC,CAAE,EAAE,aAAa,EAAE,kBAAkB,EAAE,eAAe,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,iBAAiB,EAAE,mBAAmB,EAAuC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,aAAa,CAAC;IACjZ,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,GAAI,KAAK,CAAC,OAAkB,EAAE,WAAW,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,WAAW,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;AACzM,CAAC"}
@@ -7,6 +7,7 @@ import { IntegrationHost } from "./integrations.js";
7
7
  import { type BackupHeader, type BackupSink } from "./backup.js";
8
8
  import { type FeltKitErrorJSON } from "../errors.js";
9
9
  import { ActivityLog, type ActivityVia } from "./activity.js";
10
+ import { ProviderHost } from "./providers.js";
10
11
  import { Authority, type CallerContext, type Principal } from "./authority.js";
11
12
  import { ChangeFeed } from "./changes.js";
12
13
  import type { AgentTrigger, Logger } from "./context.js";
@@ -38,6 +39,8 @@ export interface LoadedProject {
38
39
  policies: import("../policy.js").ResolvedPolicyRule[];
39
40
  modules: string[];
40
41
  loadedAt: string;
42
+ /** The project directory, when the project was loaded from its sources; relative provider modules resolve from it. */
43
+ projectDir?: string;
41
44
  }
42
45
  /** An approved agent action, as the agent lifecycle executes it (runtime.runApproved). */
43
46
  export interface ApprovedAction {
@@ -49,6 +52,10 @@ export interface ApprovedAction {
49
52
  }
50
53
  import type { ComponentWorkItem, ComponentWorkOutcome } from "../component.js";
51
54
  export type { ComponentWorkItem, ComponentWorkOutcome };
55
+ /** How often expired sessions are ended for auth.onSessionEnd: the bound on noticing an expiry. */
56
+ export declare const SESSION_EXPIRY_SWEEP_MS = 5000;
57
+ /** Attempts at running auth.onSessionEnd for one ended session before it is kept as failed. */
58
+ export declare const SESSION_END_MAX_ATTEMPTS = 10;
52
59
  export interface CallOptions {
53
60
  principal: Principal | null;
54
61
  via: ActivityVia;
@@ -82,6 +89,10 @@ export interface CallOptions {
82
89
  emit?: (event: {
83
90
  type: string;
84
91
  } & Record<string, unknown>) => void;
92
+ /** The caller's FeltKit session, by ref (`ctx.auth.session`). Set by the HTTP and AppPort surfaces. */
93
+ session?: {
94
+ ref: string;
95
+ };
85
96
  }
86
97
  export type CallResult = {
87
98
  ok: true;
@@ -180,6 +191,8 @@ export declare class FeltKitRuntime {
180
191
  readonly models: ModelHost;
181
192
  /** HTTP integrations declared with app.integration() (runtime/integrations.ts). */
182
193
  readonly integrations: IntegrationHost;
194
+ /** AppPort providers the application declared (`feltkit({ providers })`): started, registered, recorded, stopped. */
195
+ readonly providers: ProviderHost;
183
196
  /** OAuth 2.0 grants of integrations: renewed, rotated, disconnected (runtime/oauth-credentials.ts). */
184
197
  readonly oauth: OAuthCredentials;
185
198
  /** Durable invocations from registered surfaces: lifecycle, dispatch, recovery (runtime/invocations.ts). */
@@ -250,6 +263,17 @@ export declare class FeltKitRuntime {
250
263
  functionAccess(name: string): string | undefined;
251
264
  /** Whether `principal` holds `access` under this application's roles ("public" and "authenticated" as functions treat them). */
252
265
  holds(principal: Principal | null, access: string): boolean;
266
+ /**
267
+ * Any published AppPort capability (the application's own, an integration's, a provider's), called as `principal`
268
+ * through the application's AppPort pipeline: validation, roles, idempotency, and effect recording apply exactly as
269
+ * for any AppPort client. Application code reaches it through ctx.integrations.invoke; browsers through
270
+ * POST /api/capability/<name> (client.invoke).
271
+ */
272
+ invokeCapability(capability: string, input: Record<string, unknown>, principal: Principal | null, options: {
273
+ version?: number;
274
+ idempotencyKey?: string;
275
+ via: string;
276
+ }): Promise<unknown>;
253
277
  /** Run `work` as the execution of an approved action (called by the agent lifecycle only). */
254
278
  runApproved<T>(action: ApprovedAction, work: () => Promise<T>): Promise<T>;
255
279
  functions(): FunctionInfo[];
@@ -337,7 +361,14 @@ export declare class FeltKitRuntime {
337
361
  retryOutbox(id: string, by: string): Promise<OutboxRecord>;
338
362
  /** Wait for the agent runs started so far (and any they start) to finish their current attempt. */
339
363
  settleAgents(): Promise<void>;
340
- /** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
364
+ /**
365
+ * Hand ended sessions to the application's `auth.onSessionEnd` (docs/AUTH.md, "When a session ends"): end
366
+ * expired sessions (at most every SESSION_EXPIRY_SWEEP_MS), then run the hook for each recorded end, as the
367
+ * session's principal, and forget the end once it succeeds. A failed run is retried on the next pass and
368
+ * kept as failed, with its error, after SESSION_END_MAX_ATTEMPTS. Runs on every services tick and right
369
+ * after a session ends; one pass at a time.
370
+ */
371
+ runSessionEnds(): Promise<void>;
341
372
  runServices(): Promise<ServiceTick>;
342
373
  /**
343
374
  * API keys are stored as HMACs under a server-held key: FELTKIT_API_KEY_VERIFIER_KEY when
@@ -29,6 +29,7 @@ import { backupMeta, remoteBackupRefusal } from "./backup-environment.js";
29
29
  import { FeltKitError, isFeltKitError, statusFor } from "../errors.js";
30
30
  import { validate } from "../schema.js";
31
31
  import { ActivityLog, errorSummary } from "./activity.js";
32
+ import { ProviderHost, providerError } from "./providers.js";
32
33
  import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal, toAppPortPrincipal } from "./authority.js";
33
34
  import { ChangeFeed } from "./changes.js";
34
35
  import { generationDigest } from "./generation.js";
@@ -50,7 +51,7 @@ import { credentialsFor, isCustodyError } from "./credentials.js";
50
51
  import { AgentHost } from "./agent.js";
51
52
  import { FeltDbIdempotencyStore } from "./idempotency.js";
52
53
  import { capabilityDefinition } from "./capabilities.js";
53
- import { FeltDbSessionStore } from "./sessions.js";
54
+ import { FeltDbSessionStore, sessionRef } from "./sessions.js";
54
55
  import { escapeHatch } from "./escape-hatch.js";
55
56
  import { AUDIT_COLLECTION, auditRecord, readAudit } from "./audit.js";
56
57
  import { AccountStore } from "./accounts.js";
@@ -65,6 +66,10 @@ const NODE_TENANCY_CRYPTO = {
65
66
  randomBase64url: (bytes) => randomBytes(bytes).toString("base64url"),
66
67
  hmacBase64url: (key, data) => createHmac("sha256", key).update(data).digest("base64url"),
67
68
  };
69
+ /** How often expired sessions are ended for auth.onSessionEnd: the bound on noticing an expiry. */
70
+ export const SESSION_EXPIRY_SWEEP_MS = 5_000;
71
+ /** Attempts at running auth.onSessionEnd for one ended session before it is kept as failed. */
72
+ export const SESSION_END_MAX_ATTEMPTS = 10;
68
73
  const consoleLogger = {
69
74
  info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
70
75
  warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
@@ -107,6 +112,8 @@ export class FeltKitRuntime {
107
112
  models;
108
113
  /** HTTP integrations declared with app.integration() (runtime/integrations.ts). */
109
114
  integrations;
115
+ /** AppPort providers the application declared (`feltkit({ providers })`): started, registered, recorded, stopped. */
116
+ providers;
110
117
  /** OAuth 2.0 grants of integrations: renewed, rotated, disconnected (runtime/oauth-credentials.ts). */
111
118
  oauth;
112
119
  /** Durable invocations from registered surfaces: lifecycle, dispatch, recovery (runtime/invocations.ts). */
@@ -157,6 +164,7 @@ export class FeltKitRuntime {
157
164
  this.idempotency = new FeltDbIdempotencyStore(instance.handle("appport.idempotency"));
158
165
  this.models = new ModelHost(this, { env });
159
166
  this.integrations = new IntegrationHost(this);
167
+ this.providers = new ProviderHost(this);
160
168
  this.oauth = new OAuthCredentials(this);
161
169
  this.invocations = new InvocationStore(this);
162
170
  this.localAuthority = new LocalAuthorityHost(this);
@@ -183,6 +191,7 @@ export class FeltKitRuntime {
183
191
  let runtime;
184
192
  try {
185
193
  runtime = new FeltKitRuntime(options.environment, instance, logger, options.env ?? process.env);
194
+ await runtime.providers.sync(options.project.app.options.providers, options.project.projectDir ?? process.cwd());
186
195
  runtime.#install(options.project);
187
196
  // How long each startup step took: on a FeltDB server each is network round trips, and a
188
197
  // platform that waits for the port (Vercel: ~28 s) needs to know which one is slow.
@@ -387,6 +396,7 @@ export class FeltKitRuntime {
387
396
  }
388
397
  await ensureCollectionMarkers(this.instance.handle("feltkit.runtime"), project.app.collections.keys());
389
398
  const previous = this.#appport;
399
+ await this.providers.sync(project.app.options.providers, project.projectDir ?? process.cwd());
390
400
  this.#install(project);
391
401
  await this.#ensureSchema(project.app, "reload");
392
402
  await this.#orderedIndexes(project.app);
@@ -494,6 +504,12 @@ export class FeltKitRuntime {
494
504
  if ((op.expose ?? integration.expose ?? true) !== false)
495
505
  capabilities.push(this.#integrationCapability(integration, op));
496
506
  }
507
+ // AppPort providers (feltkit({ providers })): their capabilities beside the application's own, one registry.
508
+ for (const capability of this.providers.capabilities()) {
509
+ if (capabilities.some((c) => c.name === capability.name))
510
+ throw new FeltKitError("CONFIGURATION", `Capability ${capability.name} is published both by the application and by provider ${String(capability.attributes?.providerInstance)}.`, { hint: "Rename the application's capability or remove the provider." });
511
+ capabilities.push(capability);
512
+ }
497
513
  const appport = createApplication({
498
514
  application: { id: app.name, name: app.name, version: app.version, ...(app.options.description ? { description: app.options.description } : {}) },
499
515
  capabilities,
@@ -515,6 +531,15 @@ export class FeltKitRuntime {
515
531
  const original = appport[method].bind(appport);
516
532
  appport[method] = (request, options = {}) => this.#appportCaller.run(callerScope(options?.principal ?? options?.session?.principal), () => original(request, options));
517
533
  }
534
+ // auth.onSessionEnd: a mutation of this application; ends are recorded only when one is declared.
535
+ const sessionEndHook = project.app.options.auth?.onSessionEnd;
536
+ if (sessionEndHook !== undefined) {
537
+ const target = typeof sessionEndHook === "string" ? project.functions.get(sessionEndHook) : undefined;
538
+ if (!target || target.kind !== "mutation")
539
+ throw new FeltKitError("CONFIGURATION", `auth.onSessionEnd: ${JSON.stringify(sessionEndHook)} is not a mutation of this application (write "<module>:<export>").`);
540
+ }
541
+ this.sessions.recordEnds = sessionEndHook !== undefined;
542
+ this.sessions.onEnd = () => void this.runSessionEnds();
518
543
  this.#project = project;
519
544
  this.#authority = authority;
520
545
  this.#services = services;
@@ -619,6 +644,11 @@ export class FeltKitRuntime {
619
644
  },
620
645
  },
621
646
  invoke: async (capability, input, options = {}) => {
647
+ if (this.providers.provides(capability)) {
648
+ if (options.onBehalfOf !== undefined)
649
+ throw new FeltKitError("INVALID_ARGUMENT", `${capability} is a provider capability; onBehalfOf applies to a person's integration connection.`);
650
+ return this.invokeCapability(capability, input, principal, { via: "function", ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) });
651
+ }
622
652
  const found = this.integrations.operationFor(capability);
623
653
  if (!found)
624
654
  throw new FeltKitError("NOT_FOUND", `${capability} is not an integration operation.`);
@@ -639,6 +669,20 @@ export class FeltKitRuntime {
639
669
  },
640
670
  };
641
671
  }
672
+ /**
673
+ * Any published AppPort capability (the application's own, an integration's, a provider's), called as `principal`
674
+ * through the application's AppPort pipeline: validation, roles, idempotency, and effect recording apply exactly as
675
+ * for any AppPort client. Application code reaches it through ctx.integrations.invoke; browsers through
676
+ * POST /api/capability/<name> (client.invoke).
677
+ */
678
+ async invokeCapability(capability, input, principal, options) {
679
+ if (!principal)
680
+ throw new FeltKitError("UNAUTHORIZED", `${capability} needs an authenticated caller.`);
681
+ const response = (await this.appport.handleRequest({ protocol: "appport/1", type: "request", requestId: `req_${randomUUID()}`, capability: { name: capability, version: options.version ?? 1 }, input, ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), metadata: { transport: options.via } }, { principal: toAppPort(principal), transport: options.via }));
682
+ if (response.ok)
683
+ return response.output;
684
+ throw providerError(response.error);
685
+ }
642
686
  /** An integration operation as an AppPort capability: AppPort validates and authorizes; IntegrationHost calls and records. */
643
687
  #integrationCapability(integration, op) {
644
688
  return defineCapability({
@@ -803,6 +847,8 @@ export class FeltKitRuntime {
803
847
  ...(context.authorizationDecision?.decisionId ? { appportDecisionId: context.authorizationDecision.decisionId } : {}),
804
848
  ...(fn.kind === "mutation" && context.idempotencyKey ? { idempotencyReplayKey: replayKey(context, exposure, principal) } : {}),
805
849
  ...(delegation ? { delegation } : {}),
850
+ // A delegated call acts for the person under the agent's session: it binds to no session of theirs.
851
+ ...(!delegation && sessionRef(context.session?.id) ? { session: { ref: sessionRef(context.session?.id) } } : {}),
806
852
  });
807
853
  if (result.ok)
808
854
  return result.value;
@@ -1226,6 +1272,59 @@ export class FeltKitRuntime {
1226
1272
  });
1227
1273
  }
1228
1274
  /** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
1275
+ #sessionEnds;
1276
+ #sessionEndsAgain = false;
1277
+ #lastExpirySweep = 0;
1278
+ /**
1279
+ * Hand ended sessions to the application's `auth.onSessionEnd` (docs/AUTH.md, "When a session ends"): end
1280
+ * expired sessions (at most every SESSION_EXPIRY_SWEEP_MS), then run the hook for each recorded end, as the
1281
+ * session's principal, and forget the end once it succeeds. A failed run is retried on the next pass and
1282
+ * kept as failed, with its error, after SESSION_END_MAX_ATTEMPTS. Runs on every services tick and right
1283
+ * after a session ends; one pass at a time.
1284
+ */
1285
+ runSessionEnds() {
1286
+ if (this.#state !== "ready" || this.#paused || this.app.options.auth?.onSessionEnd === undefined)
1287
+ return Promise.resolve();
1288
+ if (this.#sessionEnds) {
1289
+ this.#sessionEndsAgain = true;
1290
+ return this.#sessionEnds;
1291
+ }
1292
+ const pass = async () => {
1293
+ do {
1294
+ this.#sessionEndsAgain = false;
1295
+ const hook = this.app.options.auth?.onSessionEnd;
1296
+ if (!hook)
1297
+ return;
1298
+ if (Date.now() - this.#lastExpirySweep >= SESSION_EXPIRY_SWEEP_MS) {
1299
+ this.#lastExpirySweep = Date.now();
1300
+ await this.sessions.sweepExpired();
1301
+ }
1302
+ for (const end of await this.sessions.pendingEnds()) {
1303
+ const principal = end.principal ? fromAppPortPrincipal(end.principal) : null;
1304
+ if (!principal) {
1305
+ await this.sessions.endHandled(end); // nobody's session: nothing can be bound to it
1306
+ continue;
1307
+ }
1308
+ const result = await this.call(hook, { session: end.ref, reason: end.reason }, { principal, via: "runtime", requestId: `session_end_${end.ref}_${end.attempts}` });
1309
+ if (result.ok)
1310
+ await this.sessions.endHandled(end);
1311
+ else {
1312
+ this.logger.warn(`auth.onSessionEnd (${hook}) failed for session ${end.ref}: ${result.error.code}: ${result.error.message}`);
1313
+ await this.sessions.endAttemptFailed(end, `${result.error.code}: ${result.error.message}`, SESSION_END_MAX_ATTEMPTS);
1314
+ }
1315
+ }
1316
+ } while (this.#sessionEndsAgain);
1317
+ };
1318
+ const run = pass()
1319
+ .catch((error) => this.logger.warn(`session ends: ${error.message}`))
1320
+ .finally(() => {
1321
+ this.#sessionEnds = undefined;
1322
+ this.#inflight.delete(run);
1323
+ });
1324
+ this.#sessionEnds = run;
1325
+ this.#inflight.add(run);
1326
+ return run;
1327
+ }
1229
1328
  runServices() {
1230
1329
  if (this.#state !== "ready" || this.#paused)
1231
1330
  return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } });
@@ -1233,6 +1332,7 @@ export class FeltKitRuntime {
1233
1332
  return this.#ticking;
1234
1333
  const run = Promise.all([
1235
1334
  this.#services.tick(this.workerId),
1335
+ this.runSessionEnds(),
1236
1336
  this.recoverOutbox().catch((error) => {
1237
1337
  this.logger.warn(`after-commit recovery: ${error.message}`);
1238
1338
  return 0;
@@ -1530,8 +1630,16 @@ export class FeltKitRuntime {
1530
1630
  });
1531
1631
  }
1532
1632
  const args = parsed.value;
1533
- if (fn.kind === "action")
1534
- return this.#runAction(name, fn, args, principal, options, requestId, authorityRecord, finish, failure);
1633
+ if (fn.kind === "action") {
1634
+ // An action's own service effects (ctx.services.files) are the caller's while the action runs, as for a query or mutation.
1635
+ const releaseAction = this.#services.enter(requestId, principal);
1636
+ try {
1637
+ return await this.#runAction(name, fn, args, principal, options, requestId, authorityRecord, finish, failure);
1638
+ }
1639
+ finally {
1640
+ releaseAction();
1641
+ }
1642
+ }
1535
1643
  const handle = this.instance.handle("app");
1536
1644
  const release = this.#services.enter(requestId, principal);
1537
1645
  const servicesUsed = new Set();
@@ -1542,7 +1650,7 @@ export class FeltKitRuntime {
1542
1650
  const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
1543
1651
  const used = new Set();
1544
1652
  const shared = {
1545
- auth: authContext(this.#authority, principal, options.context, options.delegation ?? null),
1653
+ auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
1546
1654
  tenancy: {
1547
1655
  members: async () => {
1548
1656
  if (!this.tenancy)
@@ -1742,7 +1850,7 @@ export class FeltKitRuntime {
1742
1850
  if (target.kind !== kind)
1743
1851
  throw new FeltKitError("INVALID_ARGUMENT", `${ref.name} is a ${target.kind}; use ctx.run${target.kind === "query" ? "Query" : target.kind === "mutation" ? "Mutation" : "…"}.`);
1744
1852
  // Cancellation stops the model (ctx.signal); it does not stop the action recording what happened.
1745
- const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}) });
1853
+ const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}), ...(options.session ? { session: options.session } : {}) });
1746
1854
  if (!result.ok)
1747
1855
  throw new FeltKitError(result.error.code, result.error.message, { ...(result.error.details ? { details: result.error.details } : {}), ...(result.error.hint ? { hint: result.error.hint } : {}) });
1748
1856
  return result.value;
@@ -1754,7 +1862,7 @@ export class FeltKitRuntime {
1754
1862
  };
1755
1863
  const agent = this.#agent;
1756
1864
  const ctx = {
1757
- auth: authContext(this.#authority, principal, options.context, options.delegation ?? null),
1865
+ auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
1758
1866
  environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
1759
1867
  requestId,
1760
1868
  log: this.logger,
@@ -1808,6 +1916,7 @@ export class FeltKitRuntime {
1808
1916
  },
1809
1917
  authority: this.#applicationAuthority(principal, requestId),
1810
1918
  integrations: this.#integrationInvoker(principal),
1919
+ services: { files: explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), name, principal, this.#authority).files },
1811
1920
  invocations: this.#invocationsApi(principal, null, { via: String(options.via ?? "function"), requestId }),
1812
1921
  agent: {
1813
1922
  catalog: async () => (await agent.tools(signedIn())).map((t) => ({
@@ -2145,6 +2254,7 @@ export class FeltKitRuntime {
2145
2254
  // rescheduled for the services worker (of this process's successor).
2146
2255
  await this.settleAgents();
2147
2256
  await this.#appport?.close().catch(() => undefined);
2257
+ await this.providers.close();
2148
2258
  await this.models.close();
2149
2259
  await this.localAuthority.close().catch(() => undefined);
2150
2260
  await this.activity.flush();