@feltdb/feltkit 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +22 -2
- package/bin/feltkit.js +3 -0
- package/dist/app.d.ts +247 -0
- package/dist/app.js +181 -0
- package/dist/app.js.map +1 -0
- package/dist/cli/deploy.d.ts +8 -0
- package/dist/cli/deploy.js +125 -0
- package/dist/cli/deploy.js.map +1 -0
- package/dist/cli/main.d.ts +9 -0
- package/dist/cli/main.js +581 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/output.d.ts +18 -0
- package/dist/cli/output.js +87 -0
- package/dist/cli/output.js.map +1 -0
- package/dist/cli/skills.d.ts +39 -0
- package/dist/cli/skills.js +125 -0
- package/dist/cli/skills.js.map +1 -0
- package/dist/client/index.d.ts +125 -0
- package/dist/client/index.js +306 -0
- package/dist/client/index.js.map +1 -0
- package/dist/dashboard/assets/index--1Tqbv_A.css +1 -0
- package/dist/dashboard/assets/index-Bm4qCYpv.js +15 -0
- package/dist/dashboard/index.html +16 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +56 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/react/index.d.ts +40 -0
- package/dist/react/index.js +85 -0
- package/dist/react/index.js.map +1 -0
- package/dist/runtime/activity.d.ts +110 -0
- package/dist/runtime/activity.js +113 -0
- package/dist/runtime/activity.js.map +1 -0
- package/dist/runtime/agent.d.ts +353 -0
- package/dist/runtime/agent.js +1345 -0
- package/dist/runtime/agent.js.map +1 -0
- package/dist/runtime/authority.d.ts +98 -0
- package/dist/runtime/authority.js +240 -0
- package/dist/runtime/authority.js.map +1 -0
- package/dist/runtime/changes.d.ts +42 -0
- package/dist/runtime/changes.js +85 -0
- package/dist/runtime/changes.js.map +1 -0
- package/dist/runtime/content.d.ts +33 -0
- package/dist/runtime/content.js +46 -0
- package/dist/runtime/content.js.map +1 -0
- package/dist/runtime/context.d.ts +76 -0
- package/dist/runtime/context.js +2 -0
- package/dist/runtime/context.js.map +1 -0
- package/dist/runtime/credentials.d.ts +42 -0
- package/dist/runtime/credentials.js +32 -0
- package/dist/runtime/credentials.js.map +1 -0
- package/dist/runtime/data.d.ts +145 -0
- package/dist/runtime/data.js +439 -0
- package/dist/runtime/data.js.map +1 -0
- package/dist/runtime/decisions.d.ts +131 -0
- package/dist/runtime/decisions.js +301 -0
- package/dist/runtime/decisions.js.map +1 -0
- package/dist/runtime/environment.d.ts +36 -0
- package/dist/runtime/environment.js +73 -0
- package/dist/runtime/environment.js.map +1 -0
- package/dist/runtime/idempotency.d.ts +37 -0
- package/dist/runtime/idempotency.js +88 -0
- package/dist/runtime/idempotency.js.map +1 -0
- package/dist/runtime/instance.d.ts +82 -0
- package/dist/runtime/instance.js +253 -0
- package/dist/runtime/instance.js.map +1 -0
- package/dist/runtime/integrations.d.ts +120 -0
- package/dist/runtime/integrations.js +412 -0
- package/dist/runtime/integrations.js.map +1 -0
- package/dist/runtime/loader.d.ts +15 -0
- package/dist/runtime/loader.js +121 -0
- package/dist/runtime/loader.js.map +1 -0
- package/dist/runtime/projects.d.ts +52 -0
- package/dist/runtime/projects.js +141 -0
- package/dist/runtime/projects.js.map +1 -0
- package/dist/runtime/readiness.d.ts +29 -0
- package/dist/runtime/readiness.js +154 -0
- package/dist/runtime/readiness.js.map +1 -0
- package/dist/runtime/runtime.d.ts +227 -0
- package/dist/runtime/runtime.js +664 -0
- package/dist/runtime/runtime.js.map +1 -0
- package/dist/runtime/services.d.ts +327 -0
- package/dist/runtime/services.js +686 -0
- package/dist/runtime/services.js.map +1 -0
- package/dist/runtime/sessions.d.ts +44 -0
- package/dist/runtime/sessions.js +109 -0
- package/dist/runtime/sessions.js.map +1 -0
- package/dist/schema.d.ts +56 -0
- package/dist/schema.js +44 -0
- package/dist/schema.js.map +1 -0
- package/dist/server/admin.d.ts +141 -0
- package/dist/server/admin.js +828 -0
- package/dist/server/admin.js.map +1 -0
- package/dist/server/http.d.ts +19 -0
- package/dist/server/http.js +99 -0
- package/dist/server/http.js.map +1 -0
- package/dist/server/index.d.ts +54 -0
- package/dist/server/index.js +305 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/management.d.ts +12 -0
- package/dist/server/management.js +177 -0
- package/dist/server/management.js.map +1 -0
- package/dist/server/mcp.d.ts +214 -0
- package/dist/server/mcp.js +135 -0
- package/dist/server/mcp.js.map +1 -0
- package/dist/server/operators.d.ts +77 -0
- package/dist/server/operators.js +162 -0
- package/dist/server/operators.js.map +1 -0
- package/dist/server/project.d.ts +60 -0
- package/dist/server/project.js +344 -0
- package/dist/server/project.js.map +1 -0
- package/dist/server/public.d.ts +14 -0
- package/dist/server/public.js +15 -0
- package/dist/server/public.js.map +1 -0
- package/dist/testing/index.d.ts +20 -0
- package/dist/testing/index.js +65 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +91 -4
- package/skills/.claude-plugin/marketplace.json +16 -0
- package/skills/.claude-plugin/plugin.json +24 -0
- package/skills/README.md +44 -0
- package/skills/feltkit-agent/SKILL.md +84 -0
- package/skills/feltkit-build/SKILL.md +143 -0
- package/skills/feltkit-data/SKILL.md +79 -0
- package/skills/feltkit-operations/SKILL.md +72 -0
- package/skills/feltkit-services/SKILL.md +102 -0
|
@@ -0,0 +1,664 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The FeltKit runtime: one application, one environment, one FeltDB instance.
|
|
3
|
+
*
|
|
4
|
+
* Lifecycle: start() opens the environment's instance through the factory, then
|
|
5
|
+
* builds every component on handles of that instance. If any step fails, everything
|
|
6
|
+
* already opened is closed before the error is rethrown. reload() swaps the
|
|
7
|
+
* application definition (functions, capabilities, policy) without reopening state.
|
|
8
|
+
* close() is idempotent and releases the instance.
|
|
9
|
+
*/
|
|
10
|
+
import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
|
|
11
|
+
import { performance } from "node:perf_hooks";
|
|
12
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { IntegrationHost, integrationDescriptor } from "./integrations.js";
|
|
16
|
+
import { FeltKitError, isFeltKitError } from "../errors.js";
|
|
17
|
+
import { validate } from "../schema.js";
|
|
18
|
+
import { ActivityLog, errorSummary } from "./activity.js";
|
|
19
|
+
import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal } from "./authority.js";
|
|
20
|
+
import { ChangeFeed } from "./changes.js";
|
|
21
|
+
import { ModelHost } from "./decisions.js";
|
|
22
|
+
import { CollectionResolver, Reader, Writer } from "./data.js";
|
|
23
|
+
import { describeStorage } from "./environment.js";
|
|
24
|
+
import { defaultInstanceFactory } from "./instance.js";
|
|
25
|
+
import { ServicesHost } from "./services.js";
|
|
26
|
+
import { AgentHost } from "./agent.js";
|
|
27
|
+
import { FeltDbIdempotencyStore } from "./idempotency.js";
|
|
28
|
+
import { FeltDbSessionStore } from "./sessions.js";
|
|
29
|
+
const consoleLogger = {
|
|
30
|
+
info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
|
|
31
|
+
warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
|
|
32
|
+
error: (m, f) => console.error(`[feltkit] ${m}`, f ?? ""),
|
|
33
|
+
};
|
|
34
|
+
export const silentLogger = { info() { }, warn() { }, error() { } };
|
|
35
|
+
export class FeltKitRuntime {
|
|
36
|
+
environment;
|
|
37
|
+
instance;
|
|
38
|
+
sessions;
|
|
39
|
+
activity;
|
|
40
|
+
changes;
|
|
41
|
+
/** AppPort's idempotency records, in this instance. */
|
|
42
|
+
idempotency;
|
|
43
|
+
/** The environment's model decisions (runtime/decisions.ts). */
|
|
44
|
+
models;
|
|
45
|
+
/** HTTP integrations declared with app.integration() (runtime/integrations.ts). */
|
|
46
|
+
integrations;
|
|
47
|
+
logger;
|
|
48
|
+
startedAt = new Date().toISOString();
|
|
49
|
+
#project;
|
|
50
|
+
#authority;
|
|
51
|
+
#services;
|
|
52
|
+
#appport;
|
|
53
|
+
#resolver;
|
|
54
|
+
#state = "starting";
|
|
55
|
+
#inflight = new Set();
|
|
56
|
+
#dispatched = new Set();
|
|
57
|
+
#generation = 0;
|
|
58
|
+
#reloadListeners = new Set();
|
|
59
|
+
#worker;
|
|
60
|
+
#agent;
|
|
61
|
+
#ticking;
|
|
62
|
+
#apiKeyVerifierKey;
|
|
63
|
+
recentErrors = [];
|
|
64
|
+
constructor(environment, instance, logger) {
|
|
65
|
+
this.environment = environment;
|
|
66
|
+
this.instance = instance;
|
|
67
|
+
this.logger = logger;
|
|
68
|
+
this.sessions = new FeltDbSessionStore(instance.handle("feltkit.sessions"));
|
|
69
|
+
this.activity = new ActivityLog(instance.handle("feltkit.activity"), { mode: environment.production ? "writes" : "all", evidence: (runId) => this.#services.evidence(runId) });
|
|
70
|
+
this.changes = new ChangeFeed(instance.handle("feltkit.changes"));
|
|
71
|
+
this.idempotency = new FeltDbIdempotencyStore(instance.handle("appport.idempotency"));
|
|
72
|
+
this.models = new ModelHost(this);
|
|
73
|
+
this.integrations = new IntegrationHost(this);
|
|
74
|
+
}
|
|
75
|
+
static async start(options) {
|
|
76
|
+
const factory = options.factory ?? defaultInstanceFactory;
|
|
77
|
+
const logger = options.logger ?? consoleLogger;
|
|
78
|
+
const instance = factory.open(options.environment);
|
|
79
|
+
let runtime;
|
|
80
|
+
try {
|
|
81
|
+
runtime = new FeltKitRuntime(options.environment, instance, logger);
|
|
82
|
+
runtime.#install(options.project);
|
|
83
|
+
// Verify the instance answers before declaring the runtime ready.
|
|
84
|
+
await instance.handle("feltkit.runtime").collection("_feltkit_meta").get("probe");
|
|
85
|
+
await runtime.#services.check();
|
|
86
|
+
// FeltDB's agent runtime and agent state, on this instance (see runtime/agent.ts).
|
|
87
|
+
runtime.#agent = new AgentHost(runtime, instance.handle("feltdb.agent"), {
|
|
88
|
+
separateApprover: options.environment.production,
|
|
89
|
+
...(options.agentActionTimeoutMs ? { actionTimeoutMs: options.agentActionTimeoutMs } : {}),
|
|
90
|
+
...(options.agentHooks ? { hooks: options.agentHooks } : {}),
|
|
91
|
+
});
|
|
92
|
+
await runtime.#agent.open();
|
|
93
|
+
runtime.changes.start();
|
|
94
|
+
runtime.#state = "ready";
|
|
95
|
+
// Actions an earlier process left open, settled from evidence (never re-executed).
|
|
96
|
+
// After "ready": settling may run an integration's outcome hook, which is a function call.
|
|
97
|
+
await runtime.#agent.reconcile();
|
|
98
|
+
const interval = options.workerIntervalMs ?? 1000;
|
|
99
|
+
if (interval > 0) {
|
|
100
|
+
runtime.#worker = setInterval(() => void runtime.runServices().catch(() => undefined), interval);
|
|
101
|
+
runtime.#worker.unref();
|
|
102
|
+
}
|
|
103
|
+
runtime.activity.record({
|
|
104
|
+
kind: "system",
|
|
105
|
+
name: "runtime.started",
|
|
106
|
+
via: "runtime",
|
|
107
|
+
requestId: `req_${randomUUID()}`,
|
|
108
|
+
principal: null,
|
|
109
|
+
outcome: "success",
|
|
110
|
+
durationMs: 0,
|
|
111
|
+
detail: { environment: options.environment.name, location: instance.identity.location, functions: options.project.functions.size },
|
|
112
|
+
});
|
|
113
|
+
return runtime;
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (runtime)
|
|
117
|
+
runtime.#state = "failed";
|
|
118
|
+
runtime?.changes.stop();
|
|
119
|
+
await instance.close().catch(() => undefined);
|
|
120
|
+
if (isFeltKitError(error))
|
|
121
|
+
throw error;
|
|
122
|
+
throw new FeltKitError("UNAVAILABLE", `FeltKit could not start the ${options.environment.name} runtime: ${error.message}`, { cause: error });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
get state() {
|
|
126
|
+
return this.#state;
|
|
127
|
+
}
|
|
128
|
+
get app() {
|
|
129
|
+
return this.#project.app;
|
|
130
|
+
}
|
|
131
|
+
get project() {
|
|
132
|
+
return this.#project;
|
|
133
|
+
}
|
|
134
|
+
get authority() {
|
|
135
|
+
return this.#authority;
|
|
136
|
+
}
|
|
137
|
+
get services() {
|
|
138
|
+
return this.#services;
|
|
139
|
+
}
|
|
140
|
+
/** The FeltKit agent (FeltDB agent runtime + agent state, acting through AppPort). */
|
|
141
|
+
/** Whether this process drives durable service work (jobs, schedules, deliveries). */
|
|
142
|
+
get workerRunning() {
|
|
143
|
+
return this.#worker !== undefined;
|
|
144
|
+
}
|
|
145
|
+
get agent() {
|
|
146
|
+
return this.#agent;
|
|
147
|
+
}
|
|
148
|
+
/** The AppPort application for the current definition. Replaced on reload. */
|
|
149
|
+
get appport() {
|
|
150
|
+
return this.#appport;
|
|
151
|
+
}
|
|
152
|
+
get authorizer() {
|
|
153
|
+
return this.#authority.authorizer;
|
|
154
|
+
}
|
|
155
|
+
get generation() {
|
|
156
|
+
return this.#generation;
|
|
157
|
+
}
|
|
158
|
+
onReload(listener) {
|
|
159
|
+
this.#reloadListeners.add(listener);
|
|
160
|
+
return () => this.#reloadListeners.delete(listener);
|
|
161
|
+
}
|
|
162
|
+
/** Swap in a new application definition. State, sessions, and history are untouched. */
|
|
163
|
+
async reload(project) {
|
|
164
|
+
this.#assertReady();
|
|
165
|
+
if (project.app.name !== this.#project.app.name) {
|
|
166
|
+
throw new FeltKitError("CONFIGURATION", `The application name changed from "${this.#project.app.name}" to "${project.app.name}". Restart to switch applications; the name selects the FeltDB namespace.`);
|
|
167
|
+
}
|
|
168
|
+
const previous = this.#appport;
|
|
169
|
+
this.#install(project);
|
|
170
|
+
this.#agent?.define();
|
|
171
|
+
await previous.close().catch(() => undefined);
|
|
172
|
+
for (const listener of this.#reloadListeners)
|
|
173
|
+
listener();
|
|
174
|
+
}
|
|
175
|
+
#install(project) {
|
|
176
|
+
const app = project.app;
|
|
177
|
+
const authority = new Authority(app.name, app.options.roles ?? {});
|
|
178
|
+
const config = app.options.services ?? {};
|
|
179
|
+
const services = new ServicesHost({
|
|
180
|
+
servicesDb: this.instance.handle("appport-services"),
|
|
181
|
+
contentDb: this.instance.handle("feltkit.files"),
|
|
182
|
+
applicationId: app.name,
|
|
183
|
+
authority,
|
|
184
|
+
config,
|
|
185
|
+
environment: this.environment.name,
|
|
186
|
+
resolveDurable: (subjectId) => this.#resolveDurable(subjectId),
|
|
187
|
+
runJob: async (fn, payload, principal, runId) => {
|
|
188
|
+
const result = await this.call(fn, payload, { principal, via: "job", requestId: `job_${runId}` });
|
|
189
|
+
if (!result.ok)
|
|
190
|
+
throw Object.assign(new Error(`${result.error.code}: ${result.error.message}`), { code: result.error.code });
|
|
191
|
+
},
|
|
192
|
+
...(config.apiKeys ? { apiKeyVerifierKey: this.#verifierKey() } : {}),
|
|
193
|
+
allowPrivateWebhookDestinations: this.environment.development,
|
|
194
|
+
});
|
|
195
|
+
const capabilities = [...project.functions.entries()]
|
|
196
|
+
.filter(([, fn]) => fn.capability)
|
|
197
|
+
.map(([name, fn]) => this.#capabilityFor(name, fn));
|
|
198
|
+
for (const integration of app.integrations.values()) {
|
|
199
|
+
for (const op of Object.values(integration.operations))
|
|
200
|
+
capabilities.push(this.#integrationCapability(integration, op));
|
|
201
|
+
}
|
|
202
|
+
const appport = createApplication({
|
|
203
|
+
application: { id: app.name, name: app.name, version: app.options.version ?? "0.0.0", ...(app.options.description ? { description: app.options.description } : {}) },
|
|
204
|
+
capabilities,
|
|
205
|
+
authorizer: authority.authorizer,
|
|
206
|
+
db: this.instance.handle("appport"),
|
|
207
|
+
sessions: this.sessions,
|
|
208
|
+
// Durable replay protection for capabilities that declare idempotency: the claim is
|
|
209
|
+
// written before the handler runs, so a replay after a crash is "outcome unknown".
|
|
210
|
+
// An idempotencyKey sent to a capability without idempotency support is refused in
|
|
211
|
+
// development and logged in production (AppPort's default for `unsupportedIdempotencyKey`).
|
|
212
|
+
idempotency: this.idempotency,
|
|
213
|
+
mode: this.environment.production ? "production" : "development",
|
|
214
|
+
telemetry: { record: (entry) => this.#telemetry(entry) },
|
|
215
|
+
});
|
|
216
|
+
this.#project = project;
|
|
217
|
+
this.#authority = authority;
|
|
218
|
+
this.#services = services;
|
|
219
|
+
this.#appport = appport;
|
|
220
|
+
this.#resolver = new CollectionResolver(app.collections);
|
|
221
|
+
this.#generation += 1;
|
|
222
|
+
}
|
|
223
|
+
/** An integration operation as an AppPort capability: AppPort validates and authorizes; IntegrationHost calls and records. */
|
|
224
|
+
#integrationCapability(integration, op) {
|
|
225
|
+
return defineCapability({
|
|
226
|
+
name: op.capability,
|
|
227
|
+
version: 1,
|
|
228
|
+
description: op.description ?? `${integration.name}: ${op.method} ${op.path}`,
|
|
229
|
+
input: op.inputSchema,
|
|
230
|
+
output: op.output,
|
|
231
|
+
authorization: [op.access],
|
|
232
|
+
effect: op.effect,
|
|
233
|
+
idempotency: op.idempotencyHeader ? "supported" : "unsupported",
|
|
234
|
+
integration: integrationDescriptor(integration, op),
|
|
235
|
+
attributes: { feltkitIntegration: integration.name },
|
|
236
|
+
handler: async (input, context) => {
|
|
237
|
+
const principal = fromAppPortPrincipal(context.principal ?? context.session?.principal);
|
|
238
|
+
this.#dispatched.add(context.requestId);
|
|
239
|
+
try {
|
|
240
|
+
return await this.integrations.invoke(op.capability, input, {
|
|
241
|
+
principal,
|
|
242
|
+
requestId: context.requestId,
|
|
243
|
+
...(context.idempotencyKey ? { idempotencyKey: context.idempotencyKey } : {}),
|
|
244
|
+
...(context.signal ? { signal: context.signal } : {}),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
if (!isFeltKitError(error))
|
|
249
|
+
throw error;
|
|
250
|
+
const details = (error.details ?? null);
|
|
251
|
+
if (error.code === "OUTCOME_UNKNOWN")
|
|
252
|
+
throw new AppPortError("OUTCOME_UNKNOWN", error.message, { retryable: false, details });
|
|
253
|
+
if (error.code === "UNAVAILABLE")
|
|
254
|
+
throw new AppPortError("UNAVAILABLE", error.message, { retryable: true, details });
|
|
255
|
+
if (error.code === "CONFIGURATION")
|
|
256
|
+
throw new AppPortError("NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
|
|
257
|
+
if (error.code === "CONFLICT")
|
|
258
|
+
throw appportErrors.conflict(error.message, details);
|
|
259
|
+
throw toAppPortError(error.toJSON());
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
#capabilityFor(name, fn) {
|
|
265
|
+
const exposure = fn.capability;
|
|
266
|
+
return defineCapability({
|
|
267
|
+
name: exposure.name,
|
|
268
|
+
version: exposure.version,
|
|
269
|
+
...(exposure.description ? { description: exposure.description } : {}),
|
|
270
|
+
input: fn.argsSchema,
|
|
271
|
+
output: fn.returns,
|
|
272
|
+
authorization: Authority.required(fn.access),
|
|
273
|
+
effect: fn.kind === "query" ? "observation" : "consequential",
|
|
274
|
+
// AppPort replays the stored response for a repeated idempotencyKey instead of
|
|
275
|
+
// running the mutation again (FeltDB-backed store, so also across restarts).
|
|
276
|
+
...(fn.kind === "mutation" ? { idempotency: "supported" } : {}),
|
|
277
|
+
attributes: { feltkitFunction: name, kind: fn.kind, access: fn.access },
|
|
278
|
+
handler: async (input, context) => {
|
|
279
|
+
const principal = fromAppPortPrincipal(context.principal ?? context.session?.principal);
|
|
280
|
+
this.#dispatched.add(context.requestId);
|
|
281
|
+
const transport = context.metadata?.transport === "mcp" ? "mcp" : context.metadata?.transport === "agent" ? "agent" : "appport";
|
|
282
|
+
const result = await this.call(name, input, {
|
|
283
|
+
principal,
|
|
284
|
+
via: transport,
|
|
285
|
+
requestId: context.requestId,
|
|
286
|
+
capability: { name: exposure.name, version: exposure.version },
|
|
287
|
+
...(context.authorizationDecision?.decisionId ? { appportDecisionId: context.authorizationDecision.decisionId } : {}),
|
|
288
|
+
...(fn.kind === "mutation" && context.idempotencyKey ? { idempotencyReplayKey: replayKey(context, exposure, principal) } : {}),
|
|
289
|
+
});
|
|
290
|
+
if (result.ok)
|
|
291
|
+
return result.value;
|
|
292
|
+
throw toAppPortError(result.error);
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
/** AppPort refuses some calls before FeltKit's handler runs (bad input, missing permission). Record those too. */
|
|
297
|
+
#telemetry(entry) {
|
|
298
|
+
if (this.#dispatched.delete(entry.requestId))
|
|
299
|
+
return;
|
|
300
|
+
if (entry.capability.startsWith("appport."))
|
|
301
|
+
return;
|
|
302
|
+
const denied = entry.errorCode === "UNAUTHORIZED" || entry.errorCode === "FORBIDDEN";
|
|
303
|
+
this.activity.record({
|
|
304
|
+
kind: "capability",
|
|
305
|
+
name: entry.capability,
|
|
306
|
+
capability: { name: entry.capability, version: entry.version },
|
|
307
|
+
via: entry.transport === "mcp" ? "mcp" : entry.transport === "agent" ? "agent" : "appport",
|
|
308
|
+
requestId: entry.requestId,
|
|
309
|
+
principal: entry.principal ? { id: entry.principal, type: "unknown", roles: [] } : null,
|
|
310
|
+
outcome: entry.success ? "success" : denied ? "denied" : "error",
|
|
311
|
+
...(entry.errorCode ? { error: { code: entry.errorCode, message: `Refused by AppPort before execution (${entry.errorCode})` } } : {}),
|
|
312
|
+
durationMs: Math.round(entry.durationMs),
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
functions() {
|
|
316
|
+
return [...this.#project.functions.entries()]
|
|
317
|
+
.map(([name, fn]) => ({
|
|
318
|
+
name,
|
|
319
|
+
kind: fn.kind,
|
|
320
|
+
access: fn.access,
|
|
321
|
+
...(fn.description ? { description: fn.description } : {}),
|
|
322
|
+
args: fn.argsSchema.toJSONSchema(),
|
|
323
|
+
...(fn.returns ? { returns: fn.returns.toJSONSchema() } : {}),
|
|
324
|
+
...(fn.capability ? { capability: { name: fn.capability.name, version: fn.capability.version } } : {}),
|
|
325
|
+
}))
|
|
326
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Resolve a bearer token to a principal: a FeltKit session, or (when services.apiKeys
|
|
330
|
+
* is enabled) an AppPort Services API key holding services.apiKeys.roles. Unknown,
|
|
331
|
+
* expired, and revoked credentials resolve to null.
|
|
332
|
+
*/
|
|
333
|
+
async principalForToken(token) {
|
|
334
|
+
if (!token)
|
|
335
|
+
return null;
|
|
336
|
+
if (this.#services.apiKeys && /^app_live_[0-9a-f]{6}_/.test(token)) {
|
|
337
|
+
const key = await this.#services.apiKeys.authenticateApiKey(token).catch(() => null);
|
|
338
|
+
return key ? { id: key.principalId, type: "service", roles: [...this.#services.apiKeyRoles], displayName: `API key ${key.principalId.slice(0, 8)}` } : null;
|
|
339
|
+
}
|
|
340
|
+
const session = await this.sessions.get(token);
|
|
341
|
+
return fromAppPortPrincipal(session?.principal);
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The principal behind durable service work, as it is now: an API key that still
|
|
345
|
+
* exists and is not revoked holds services.apiKeys.roles; anyone else holds the roles of
|
|
346
|
+
* their most recent active session. No active session → null, and the work is refused.
|
|
347
|
+
*/
|
|
348
|
+
async #resolveDurable(subjectId) {
|
|
349
|
+
return this.resolvePrincipal(subjectId);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* A principal as it is now, by id: a live API key, else the most recent active session.
|
|
353
|
+
* With `devUsers`, development also resolves declared dev identities (the agent's
|
|
354
|
+
* Studio-created tasks act as them). Durable service work never uses that fallback.
|
|
355
|
+
*/
|
|
356
|
+
async resolvePrincipal(subjectId, options = {}) {
|
|
357
|
+
const found = await this.#resolveStrict(subjectId);
|
|
358
|
+
if (found || !options.devUsers || !this.environment.development)
|
|
359
|
+
return found;
|
|
360
|
+
const user = this.app.options.dev?.users?.find((u) => u.id === subjectId);
|
|
361
|
+
return user ? { id: user.id, type: user.type ?? "user", roles: [...user.roles], ...(user.name ? { displayName: user.name } : {}) } : null;
|
|
362
|
+
}
|
|
363
|
+
async #resolveStrict(subjectId) {
|
|
364
|
+
const keys = this.#services.apiKeys;
|
|
365
|
+
if (keys) {
|
|
366
|
+
const key = await keys.getApiKey(this.app.name, subjectId).catch(() => null);
|
|
367
|
+
if (key)
|
|
368
|
+
return key.revokedAt || (key.expiresAt && Date.parse(String(key.expiresAt)) <= Date.now()) ? null : { id: subjectId, type: "service", roles: [...this.#services.apiKeyRoles] };
|
|
369
|
+
}
|
|
370
|
+
const session = (await this.sessions.list()).find((s) => s.principal?.id === subjectId);
|
|
371
|
+
return session?.principal ?? null;
|
|
372
|
+
}
|
|
373
|
+
/** Drive durable service work once (jobs, schedules, webhook deliveries). */
|
|
374
|
+
runServices() {
|
|
375
|
+
if (this.#state !== "ready")
|
|
376
|
+
return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0 });
|
|
377
|
+
if (this.#ticking)
|
|
378
|
+
return this.#ticking;
|
|
379
|
+
const run = this.#services.tick(`${this.app.name}:${process.pid}`).catch((error) => {
|
|
380
|
+
this.logger.warn(`services worker: ${error.message}`);
|
|
381
|
+
return { jobs: 0, deliveries: 0, scheduled: 0 };
|
|
382
|
+
});
|
|
383
|
+
this.#ticking = run.finally(() => (this.#ticking = undefined));
|
|
384
|
+
this.#inflight.add(this.#ticking);
|
|
385
|
+
void this.#ticking.finally(() => this.#inflight.delete(this.#ticking));
|
|
386
|
+
return run;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* API keys are stored as HMACs under a server-held key. Production reads it from
|
|
390
|
+
* FELTKIT_API_KEY_VERIFIER_KEY; development keeps one in .feltkit/<env>/ (0600), so
|
|
391
|
+
* issued keys keep working across restarts.
|
|
392
|
+
*/
|
|
393
|
+
#verifierKey() {
|
|
394
|
+
if (this.#apiKeyVerifierKey)
|
|
395
|
+
return this.#apiKeyVerifierKey;
|
|
396
|
+
const fromEnv = process.env.FELTKIT_API_KEY_VERIFIER_KEY;
|
|
397
|
+
if (fromEnv) {
|
|
398
|
+
if (Buffer.byteLength(fromEnv) < 32)
|
|
399
|
+
throw new FeltKitError("CONFIGURATION", "FELTKIT_API_KEY_VERIFIER_KEY must be at least 32 bytes.");
|
|
400
|
+
return (this.#apiKeyVerifierKey = fromEnv);
|
|
401
|
+
}
|
|
402
|
+
if (this.environment.production) {
|
|
403
|
+
throw new FeltKitError("CONFIGURATION", "services.apiKeys needs FELTKIT_API_KEY_VERIFIER_KEY in production.", { hint: "Generate 32+ random bytes in your secret manager. Changing it invalidates every issued key." });
|
|
404
|
+
}
|
|
405
|
+
mkdirSync(this.environment.runtimeDir, { recursive: true });
|
|
406
|
+
const file = join(this.environment.runtimeDir, "api-key-verifier");
|
|
407
|
+
if (!existsSync(file))
|
|
408
|
+
writeFileSync(file, randomBytes(32).toString("base64url"), { mode: 0o600 });
|
|
409
|
+
return (this.#apiKeyVerifierKey = readFileSync(file, "utf8").trim());
|
|
410
|
+
}
|
|
411
|
+
/** Issue a session. Development sign-in, the CLI, and auth hooks all come through here. */
|
|
412
|
+
async issueSession(input, options) {
|
|
413
|
+
const principal = normalizePrincipal(input);
|
|
414
|
+
for (const role of principal.roles) {
|
|
415
|
+
if (!this.#authority.roles[role])
|
|
416
|
+
throw new FeltKitError("INVALID_ARGUMENT", `Unknown role "${role}". Declared roles: ${Object.keys(this.#authority.roles).join(", ") || "(none)"}.`);
|
|
417
|
+
}
|
|
418
|
+
const session = await this.sessions.issue(this.app.name, principal, {
|
|
419
|
+
kind: options.kind,
|
|
420
|
+
...(options.label ? { label: options.label } : {}),
|
|
421
|
+
...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : this.app.options.auth?.sessionTtlMs ? { ttlMs: this.app.options.auth.sessionTtlMs } : {}),
|
|
422
|
+
});
|
|
423
|
+
this.activity.record({
|
|
424
|
+
kind: "auth",
|
|
425
|
+
name: "session.issued",
|
|
426
|
+
via: options.via,
|
|
427
|
+
requestId: `req_${randomUUID()}`,
|
|
428
|
+
principal: options.actor ? pick(options.actor) : pick(principal),
|
|
429
|
+
outcome: "success",
|
|
430
|
+
durationMs: 0,
|
|
431
|
+
detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
|
|
432
|
+
});
|
|
433
|
+
return { token: session.id, principal, expiresAt: session.expiresAt };
|
|
434
|
+
}
|
|
435
|
+
/** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
|
|
436
|
+
call(name, rawArgs, options) {
|
|
437
|
+
const promise = this.#call(name, rawArgs, options);
|
|
438
|
+
this.#inflight.add(promise);
|
|
439
|
+
return promise.finally(() => this.#inflight.delete(promise));
|
|
440
|
+
}
|
|
441
|
+
async #call(name, rawArgs, options) {
|
|
442
|
+
const started = performance.now();
|
|
443
|
+
const requestId = options.requestId ?? `req_${randomUUID()}`;
|
|
444
|
+
const principal = options.principal;
|
|
445
|
+
const fn = this.#project?.functions.get(name);
|
|
446
|
+
const kind = options.capability ? "capability" : fn?.kind ?? "query";
|
|
447
|
+
const base = {
|
|
448
|
+
kind,
|
|
449
|
+
name,
|
|
450
|
+
via: options.via,
|
|
451
|
+
requestId,
|
|
452
|
+
principal: principal ? pick(principal) : null,
|
|
453
|
+
...(options.capability ? { capability: options.capability } : {}),
|
|
454
|
+
};
|
|
455
|
+
const finish = (entry) => {
|
|
456
|
+
this.activity.record({ ...base, durationMs: Math.round(performance.now() - started), ...entry });
|
|
457
|
+
};
|
|
458
|
+
const failure = (error, extra = {}) => {
|
|
459
|
+
const json = this.#errorJSON(error, requestId);
|
|
460
|
+
const outcome = json.code === "UNAUTHORIZED" || json.code === "FORBIDDEN" ? "denied" : "error";
|
|
461
|
+
if (outcome === "error") {
|
|
462
|
+
this.recentErrors.unshift({ at: new Date().toISOString(), name, code: json.code, message: json.message, requestId });
|
|
463
|
+
this.recentErrors.length = Math.min(this.recentErrors.length, 50);
|
|
464
|
+
}
|
|
465
|
+
finish({ outcome, error: { code: json.code, message: json.message }, ...extra });
|
|
466
|
+
return { ok: false, error: json, requestId };
|
|
467
|
+
};
|
|
468
|
+
if (this.#state !== "ready")
|
|
469
|
+
return failure(new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`));
|
|
470
|
+
if (!fn)
|
|
471
|
+
return failure(new FeltKitError("FUNCTION_NOT_FOUND", `No query or mutation named "${name}".`, { hint: "Function names are \"<module>:<export>\", e.g. \"tasks:list\"." }));
|
|
472
|
+
const parsed = validate(fn.argsSchema, rawArgs ?? {});
|
|
473
|
+
if (!parsed.ok) {
|
|
474
|
+
return failure(new FeltKitError("INVALID_ARGUMENT", `Invalid arguments for ${name}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } }), {
|
|
475
|
+
argKeys: argKeys(rawArgs),
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
const args = parsed.value;
|
|
479
|
+
let decision;
|
|
480
|
+
try {
|
|
481
|
+
decision = await this.#authority.authorize({ access: fn.access, principal, target: { name, version: 1 }, transport: options.via, requestId, input: args });
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
return failure(error);
|
|
485
|
+
}
|
|
486
|
+
const authorityRecord = {
|
|
487
|
+
required: decision.required,
|
|
488
|
+
allowed: decision.allowed,
|
|
489
|
+
decisionId: decision.decisionId,
|
|
490
|
+
policyVersion: decision.policyVersion,
|
|
491
|
+
...(decision.reason ? { reason: decision.reason } : {}),
|
|
492
|
+
...(options.appportDecisionId ? { appportDecisionId: options.appportDecisionId } : {}),
|
|
493
|
+
};
|
|
494
|
+
if (!decision.allowed) {
|
|
495
|
+
return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: Object.keys(args) });
|
|
496
|
+
}
|
|
497
|
+
const handle = this.instance.handle("app");
|
|
498
|
+
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
499
|
+
const release = this.#services.enter(requestId, principal);
|
|
500
|
+
const servicesUsed = new Set();
|
|
501
|
+
const shared = {
|
|
502
|
+
auth: authContext(this.#authority, principal),
|
|
503
|
+
services: this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", servicesUsed),
|
|
504
|
+
environment: { name: this.environment.name, production: this.environment.production },
|
|
505
|
+
requestId,
|
|
506
|
+
log: this.logger,
|
|
507
|
+
};
|
|
508
|
+
const starts = [];
|
|
509
|
+
const agent = {
|
|
510
|
+
start: (input) => {
|
|
511
|
+
if (!principal)
|
|
512
|
+
throw new FeltKitError("UNAUTHORIZED", "Starting agent work needs a signed-in caller.");
|
|
513
|
+
if (!this.#authority.permissionsFor(principal).some((g) => g === "*" || g === "feltkit.*" || g === "feltkit.agent.*" || g === "feltkit.agent.write")) {
|
|
514
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} may not start agent work (needs feltkit.agent.write).`);
|
|
515
|
+
}
|
|
516
|
+
const taskId = `task-${randomUUID()}`;
|
|
517
|
+
starts.push({ taskId, objective: String(input?.objective ?? ""), decision: input?.decision, ...(input?.subject ? { subject: input.subject } : {}) });
|
|
518
|
+
return { taskId };
|
|
519
|
+
},
|
|
520
|
+
};
|
|
521
|
+
const ctx = fn.kind === "mutation" ? { ...shared, db, agent, unsafe: { feltdb: this.instance.handle("app.unsafe") } } : { ...shared, db };
|
|
522
|
+
try {
|
|
523
|
+
const value = await fn.handler(ctx, args);
|
|
524
|
+
if (fn.returns) {
|
|
525
|
+
const output = validate(fn.returns, value);
|
|
526
|
+
if (!output.ok) {
|
|
527
|
+
throw new FeltKitError("INTERNAL", `${name} returned a value that does not match its \`returns\` schema: ${output.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
let commit;
|
|
531
|
+
if (db instanceof Writer) {
|
|
532
|
+
commit = await db.commit(options.idempotencyReplayKey ? idempotentTransactionId(options.idempotencyReplayKey) : requestId, {
|
|
533
|
+
keyed: options.idempotencyReplayKey !== undefined,
|
|
534
|
+
});
|
|
535
|
+
if (commit.writes.length)
|
|
536
|
+
void this.changes.check();
|
|
537
|
+
// Agent work starts only once the mutation's writes are durable.
|
|
538
|
+
for (const start of starts)
|
|
539
|
+
this.#agent?.startAfterCommit(start, principal);
|
|
540
|
+
}
|
|
541
|
+
finish({
|
|
542
|
+
outcome: "success",
|
|
543
|
+
authority: authorityRecord,
|
|
544
|
+
argKeys: Object.keys(args),
|
|
545
|
+
reads: [...db.reads],
|
|
546
|
+
...(servicesUsed.size ? { services: [...servicesUsed] } : {}),
|
|
547
|
+
...(commit && commit.writes.length
|
|
548
|
+
? {
|
|
549
|
+
writes: commit.writes,
|
|
550
|
+
transactionId: commit.transactionId,
|
|
551
|
+
...(commit.commitRevision !== undefined ? { commitRevision: commit.commitRevision } : {}),
|
|
552
|
+
...(commit.revisionId ? { revisionId: commit.revisionId } : {}),
|
|
553
|
+
}
|
|
554
|
+
: {}),
|
|
555
|
+
});
|
|
556
|
+
return { ok: true, value: value === undefined ? null : value, reads: [...db.reads], requestId };
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads: [...db.reads], ...(servicesUsed.size ? { services: [...servicesUsed] } : {}) });
|
|
560
|
+
}
|
|
561
|
+
finally {
|
|
562
|
+
release();
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
#errorJSON(error, requestId) {
|
|
566
|
+
if (isFeltKitError(error))
|
|
567
|
+
return error.toJSON();
|
|
568
|
+
const message = error?.message ?? String(error);
|
|
569
|
+
this.logger.error(`Unhandled error in request ${requestId}: ${message}`, { stack: error?.stack });
|
|
570
|
+
if (this.environment.production)
|
|
571
|
+
return { code: "INTERNAL", message: `Internal error (request ${requestId}).` };
|
|
572
|
+
return { code: "INTERNAL", message, hint: "This error was thrown by application code. Throw FeltKitError (or use fail()) to return a structured error." };
|
|
573
|
+
}
|
|
574
|
+
/** An MCP tool surface for one agent identity, backed by AppPort's MCP bridge. */
|
|
575
|
+
mcpBridge(principal, session) {
|
|
576
|
+
return createMcpBridge(this.#appport, {
|
|
577
|
+
...(session ? { session } : {}),
|
|
578
|
+
...(principal && !session ? { principal: toAppPort(principal) } : {}),
|
|
579
|
+
transport: "mcp",
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
#assertReady() {
|
|
583
|
+
if (this.#state !== "ready")
|
|
584
|
+
throw new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`);
|
|
585
|
+
}
|
|
586
|
+
overview() {
|
|
587
|
+
const storage = describeStorage(this.environment.storage);
|
|
588
|
+
return {
|
|
589
|
+
application: { name: this.app.name, version: this.app.options.version ?? "0.0.0", description: this.app.options.description ?? null },
|
|
590
|
+
state: this.#state,
|
|
591
|
+
startedAt: this.startedAt,
|
|
592
|
+
generation: this.#generation,
|
|
593
|
+
loadedAt: this.#project.loadedAt,
|
|
594
|
+
environment: { name: this.environment.name, production: this.environment.production, development: this.environment.development },
|
|
595
|
+
instance: { ...this.instance.identity, storage: storage.kind, location: storage.location, sequence: this.changes.position },
|
|
596
|
+
collections: [...this.app.collections.values()].map((c) => ({ name: c.name, schema: c.schema.toJSONSchema(), ...(c.description ? { description: c.description } : {}) })),
|
|
597
|
+
functions: this.functions(),
|
|
598
|
+
roles: this.#authority.roles,
|
|
599
|
+
policyVersion: this.#authority.policyVersion,
|
|
600
|
+
recentErrors: this.recentErrors.slice(0, 10),
|
|
601
|
+
activity: { mode: this.activity.mode, lastError: this.activity.lastError },
|
|
602
|
+
changeFeed: { lastError: this.changes.lastError },
|
|
603
|
+
components: Object.fromEntries([...this.instance.access.entries()].map(([k, v]) => [k, [...v].sort()])),
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
/** Stop accepting calls, wait for in-flight work, flush the activity log, release the instance. */
|
|
607
|
+
async close() {
|
|
608
|
+
if (this.#state === "closed" || this.#state === "closing")
|
|
609
|
+
return;
|
|
610
|
+
this.#state = "closing";
|
|
611
|
+
if (this.#worker)
|
|
612
|
+
clearInterval(this.#worker);
|
|
613
|
+
this.changes.stop();
|
|
614
|
+
await Promise.allSettled([...this.#inflight]);
|
|
615
|
+
await this.#appport?.close().catch(() => undefined);
|
|
616
|
+
await this.activity.flush();
|
|
617
|
+
await this.instance.close();
|
|
618
|
+
this.#state = "closed";
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
function pick(principal) {
|
|
622
|
+
return { id: principal.id, type: principal.type, roles: principal.roles };
|
|
623
|
+
}
|
|
624
|
+
function argKeys(value) {
|
|
625
|
+
return value && typeof value === "object" ? Object.keys(value) : [];
|
|
626
|
+
}
|
|
627
|
+
function toAppPort(principal) {
|
|
628
|
+
return { id: principal.id, type: principal.type === "agent" ? "application" : principal.type, attributes: { roles: principal.roles, feltkitType: principal.type } };
|
|
629
|
+
}
|
|
630
|
+
function toAppPortError(error) {
|
|
631
|
+
switch (error.code) {
|
|
632
|
+
case "UNAUTHORIZED":
|
|
633
|
+
return appportErrors.unauthorized(error.message);
|
|
634
|
+
case "FORBIDDEN":
|
|
635
|
+
return appportErrors.forbidden(error.message);
|
|
636
|
+
case "INVALID_ARGUMENT":
|
|
637
|
+
case "VALIDATION_FAILED":
|
|
638
|
+
return appportErrors.invalidInput(error.message, (error.details ?? null));
|
|
639
|
+
case "NOT_FOUND":
|
|
640
|
+
case "FUNCTION_NOT_FOUND":
|
|
641
|
+
return appportErrors.notFound(error.message);
|
|
642
|
+
case "CONFLICT":
|
|
643
|
+
return appportErrors.conflict(error.message);
|
|
644
|
+
case "PAYLOAD_TOO_LARGE":
|
|
645
|
+
return appportErrors.payloadTooLarge(error.message);
|
|
646
|
+
// Not INTERNAL: a caller must be able to tell "may have been applied" from "failed".
|
|
647
|
+
case "OUTCOME_UNKNOWN":
|
|
648
|
+
return new AppPortError("OUTCOME_UNKNOWN", error.message, { retryable: false, details: (error.details ?? null) });
|
|
649
|
+
case "UNAVAILABLE":
|
|
650
|
+
return new AppPortError("UNAVAILABLE", error.message, { retryable: true, details: (error.details ?? null) });
|
|
651
|
+
default:
|
|
652
|
+
return appportErrors.internal(error.message);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
/** AppPort's replay key, computed exactly as AppPort scopes it (session, else principal). */
|
|
656
|
+
function replayKey(context, exposure, principal) {
|
|
657
|
+
const scope = context.session?.id ?? (principal ? `principal:${principal.id}` : undefined);
|
|
658
|
+
return idempotencyStorageKey({ key: String(context.idempotencyKey), capability: exposure.name, version: exposure.version, ...(scope ? { sessionId: scope } : {}) });
|
|
659
|
+
}
|
|
660
|
+
/** A FeltDB transaction id for one idempotent mutation: stable across retries of the same replay key. */
|
|
661
|
+
function idempotentTransactionId(replayKey) {
|
|
662
|
+
return `idem_${createHash("sha256").update(replayKey).digest("hex")}`;
|
|
663
|
+
}
|
|
664
|
+
//# sourceMappingURL=runtime.js.map
|