@feltdb/feltkit 0.1.1 → 0.3.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.
Files changed (99) hide show
  1. package/dist/app.d.ts +106 -10
  2. package/dist/app.js +51 -0
  3. package/dist/app.js.map +1 -1
  4. package/dist/cli/deploy.js +9 -0
  5. package/dist/cli/deploy.js.map +1 -1
  6. package/dist/cli/main.js +339 -2
  7. package/dist/cli/main.js.map +1 -1
  8. package/dist/cli/skills.d.ts +39 -0
  9. package/dist/cli/skills.js +125 -0
  10. package/dist/cli/skills.js.map +1 -0
  11. package/dist/dashboard/assets/{index-BLnBFDJs.css → index--1Tqbv_A.css} +1 -1
  12. package/dist/dashboard/assets/index-D9529PVz.js +15 -0
  13. package/dist/dashboard/index.html +2 -2
  14. package/dist/errors.d.ts +5 -1
  15. package/dist/errors.js +3 -0
  16. package/dist/errors.js.map +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/runtime/activity.d.ts +21 -8
  19. package/dist/runtime/activity.js +17 -3
  20. package/dist/runtime/activity.js.map +1 -1
  21. package/dist/runtime/agent.d.ts +353 -0
  22. package/dist/runtime/agent.js +1345 -0
  23. package/dist/runtime/agent.js.map +1 -0
  24. package/dist/runtime/authority.d.ts +24 -3
  25. package/dist/runtime/authority.js +72 -5
  26. package/dist/runtime/authority.js.map +1 -1
  27. package/dist/runtime/changes.d.ts +16 -8
  28. package/dist/runtime/changes.js.map +1 -1
  29. package/dist/runtime/content.d.ts +33 -0
  30. package/dist/runtime/content.js +46 -0
  31. package/dist/runtime/content.js.map +1 -0
  32. package/dist/runtime/context.d.ts +26 -1
  33. package/dist/runtime/credentials.d.ts +174 -0
  34. package/dist/runtime/credentials.js +407 -0
  35. package/dist/runtime/credentials.js.map +1 -0
  36. package/dist/runtime/data.d.ts +8 -2
  37. package/dist/runtime/data.js +74 -9
  38. package/dist/runtime/data.js.map +1 -1
  39. package/dist/runtime/decisions.d.ts +141 -0
  40. package/dist/runtime/decisions.js +330 -0
  41. package/dist/runtime/decisions.js.map +1 -0
  42. package/dist/runtime/environment.js +11 -0
  43. package/dist/runtime/environment.js.map +1 -1
  44. package/dist/runtime/idempotency.d.ts +37 -0
  45. package/dist/runtime/idempotency.js +88 -0
  46. package/dist/runtime/idempotency.js.map +1 -0
  47. package/dist/runtime/instance.d.ts +8 -3
  48. package/dist/runtime/instance.js +27 -4
  49. package/dist/runtime/instance.js.map +1 -1
  50. package/dist/runtime/integrations.d.ts +125 -0
  51. package/dist/runtime/integrations.js +429 -0
  52. package/dist/runtime/integrations.js.map +1 -0
  53. package/dist/runtime/loader.d.ts +5 -1
  54. package/dist/runtime/loader.js +35 -13
  55. package/dist/runtime/loader.js.map +1 -1
  56. package/dist/runtime/projects.d.ts +1 -0
  57. package/dist/runtime/projects.js +6 -4
  58. package/dist/runtime/projects.js.map +1 -1
  59. package/dist/runtime/readiness.d.ts +29 -0
  60. package/dist/runtime/readiness.js +154 -0
  61. package/dist/runtime/readiness.js.map +1 -0
  62. package/dist/runtime/runtime.d.ts +53 -1
  63. package/dist/runtime/runtime.js +252 -9
  64. package/dist/runtime/runtime.js.map +1 -1
  65. package/dist/runtime/services.d.ts +205 -36
  66. package/dist/runtime/services.js +479 -152
  67. package/dist/runtime/services.js.map +1 -1
  68. package/dist/runtime/sessions.d.ts +7 -18
  69. package/dist/runtime/sessions.js +7 -5
  70. package/dist/runtime/sessions.js.map +1 -1
  71. package/dist/server/admin.d.ts +80 -0
  72. package/dist/server/admin.js +677 -8
  73. package/dist/server/admin.js.map +1 -1
  74. package/dist/server/index.d.ts +2 -0
  75. package/dist/server/index.js +13 -4
  76. package/dist/server/index.js.map +1 -1
  77. package/dist/server/management.d.ts +12 -0
  78. package/dist/server/management.js +177 -0
  79. package/dist/server/management.js.map +1 -0
  80. package/dist/server/mcp.d.ts +202 -0
  81. package/dist/server/mcp.js +62 -4
  82. package/dist/server/mcp.js.map +1 -1
  83. package/dist/server/operators.d.ts +77 -0
  84. package/dist/server/operators.js +162 -0
  85. package/dist/server/operators.js.map +1 -0
  86. package/dist/server/project.js +17 -4
  87. package/dist/server/project.js.map +1 -1
  88. package/dist/testing/index.js +3 -2
  89. package/dist/testing/index.js.map +1 -1
  90. package/package.json +18 -11
  91. package/skills/.claude-plugin/marketplace.json +16 -0
  92. package/skills/.claude-plugin/plugin.json +24 -0
  93. package/skills/README.md +44 -0
  94. package/skills/feltkit-agent/SKILL.md +84 -0
  95. package/skills/feltkit-build/SKILL.md +153 -0
  96. package/skills/feltkit-data/SKILL.md +79 -0
  97. package/skills/feltkit-operations/SKILL.md +72 -0
  98. package/skills/feltkit-services/SKILL.md +124 -0
  99. package/dist/dashboard/assets/index-CxJGCspE.js +0 -15
@@ -1,43 +1,11 @@
1
- import { createServices, FeltDbEffectEvidenceStore, FeltDbFileAuditSink, FeltDbFileStore, FileService, ServiceGateway, isServiceAuthorityError, } from "@appport/services";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import { readFileSync } from "node:fs";
4
- import { join } from "node:path";
5
- import { fileURLToPath } from "node:url";
1
+ import { createServices, isServiceAuthorityError, parseConfigurationExport, MAX_EVIDENCE_LOOKUP_LIMIT, VERSION, } from "@appport/services";
2
+ import { randomUUID } from "node:crypto";
6
3
  import { FeltKitError } from "../errors.js";
7
- export const FILE_CONTENT_COLLECTION = "_feltkit_file_content";
4
+ import { FileContent, FILE_CONTENT_COLLECTION } from "./content.js";
5
+ import { EnvironmentCredentials, credentialId, isCustodyError, redactSecret } from "./credentials.js";
6
+ import { systemPrincipal } from "./authority.js";
7
+ export { FILE_CONTENT_COLLECTION };
8
8
  export const DEFAULT_MAX_FILE_BYTES = 1024 * 1024;
9
- let servicesVersion;
10
- function packageVersion() {
11
- if (servicesVersion)
12
- return servicesVersion;
13
- try {
14
- // The package is ESM-only and does not export package.json; resolve it from the entry.
15
- const entry = fileURLToPath(import.meta.resolve("@appport/services"));
16
- const pkg = join(entry, "..", "..", "..", "package.json");
17
- servicesVersion = JSON.parse(readFileSync(pkg, "utf8")).version;
18
- }
19
- catch {
20
- servicesVersion = "unknown";
21
- }
22
- return servicesVersion;
23
- }
24
- /** The first @appport/services release whose createServices() accepts the host's instance. */
25
- export const SHARED_INSTANCE_SERVICES = "0.5.0";
26
- export function supportsSharedInstance(version) {
27
- const [major = 0, minor = 0] = version.split(".").map((n) => Number.parseInt(n, 10));
28
- return Number.isFinite(major) && (major > 0 || minor >= 5);
29
- }
30
- /**
31
- * Services that are not offered to application code, with the concrete reason.
32
- * The first reason applies when the installed package cannot share the instance.
33
- */
34
- const UNAVAILABLE = [
35
- ["apikeys", "API keys", "Tenant-scoped machine credentials", "FeltKit authenticates callers with sessions; it does not yet accept API keys as an identity, so issued keys would authenticate nothing."],
36
- ["webhooks", "Webhooks", "Durable signed outbound delivery", "Delivery signs payloads with a credential resolved by a credential provider (AuthBoundry custody). FeltKit has no credential provider, so deliveries could not be signed."],
37
- ["jobs", "Jobs", "Durable background execution with leases", "Application jobs re-authorize every run as their enqueuing principal; FeltKit cannot yet resolve that principal's roles outside a live request."],
38
- ["schedules", "Schedules", "Recurring jobs", "Built on application jobs (see Jobs)."],
39
- ["intelligence", "Intelligence", "Model provider configuration", "Provider credentials need a credential provider, which FeltKit does not have."],
40
- ];
41
9
  export const CONFIGURATION_ENVIRONMENT = {
42
10
  development: "development",
43
11
  test: "development",
@@ -57,6 +25,12 @@ function toInfo(file) {
57
25
  };
58
26
  }
59
27
  function translate(error) {
28
+ const code = String(error?.code ?? "");
29
+ if (code === "CUSTODY_READ_ONLY")
30
+ throw new FeltKitError("CUSTODY_READ_ONLY", error.message, { cause: error, hint: "Set the FELTKIT_CREDENTIAL_<ID> variable on the host, or (production) opt in to a vault with FELTKIT_CREDENTIAL_VAULT=1 and FELTKIT_CREDENTIAL_VAULT_KEY." });
31
+ if (isCustodyError(error)) {
32
+ throw new FeltKitError(code === "INVALID_REQUEST" ? "INVALID_ARGUMENT" : code === "CREDENTIAL_UNAVAILABLE" ? "CONFIGURATION" : "UNAVAILABLE", error.message, { cause: error });
33
+ }
60
34
  if (isServiceAuthorityError(error)) {
61
35
  const code = error.code;
62
36
  if (code === "DENIED")
@@ -78,12 +52,21 @@ function translate(error) {
78
52
  throw error;
79
53
  }
80
54
  export class ServicesHost {
81
- mode;
82
55
  gateway;
83
56
  files;
84
57
  notifications;
85
58
  configuration;
86
- /** The instance handle every service store uses. Tests check it belongs to the shared instance. */
59
+ apiKeys;
60
+ webhooks;
61
+ jobs;
62
+ schedules;
63
+ intelligence;
64
+ credentials;
65
+ /** Roles a request authenticated by an API key holds. */
66
+ apiKeyRoles;
67
+ /** Job type → FeltKit function. */
68
+ jobHandlers;
69
+ /** The instance handle every service store uses (`services.db`, checked with `usesInstance`). */
87
70
  db;
88
71
  #official;
89
72
  #content;
@@ -98,44 +81,250 @@ export class ServicesHost {
98
81
  constructor(options) {
99
82
  this.#applicationId = options.applicationId;
100
83
  this.#tenantId = options.applicationId;
101
- this.#content = options.contentDb;
84
+ this.#content = new FileContent(options.contentDb);
102
85
  this.#environment = CONFIGURATION_ENVIRONMENT[options.environment] ?? "staging";
103
- this.db = options.servicesDb;
86
+ this.credentials = options.credentials ?? new EnvironmentCredentials();
104
87
  const config = options.config;
105
88
  this.#maxBytes = typeof config.files === "object" ? config.files.maxBytes ?? DEFAULT_MAX_FILE_BYTES : DEFAULT_MAX_FILE_BYTES;
106
- const authorizer = options.authority.serviceAuthorizer((runId) => (runId ? this.#bound.get(runId) ?? null : null));
107
- const version = packageVersion();
108
- if (supportsSharedInstance(version)) {
109
- // The package's own construction, on the shared instance.
110
- const official = createServices({ db: options.servicesDb, application: options.applicationId, authorizer });
111
- if (official._getDb !== options.servicesDb) {
112
- throw new FeltKitError("CONFIGURATION", `@appport/services ${version} did not use the application's FeltDB instance. Refusing to start with a second database.`);
113
- }
114
- this.mode = "shared-instance";
115
- this.#official = official;
116
- this.gateway = official.gateway;
117
- this.files = config.files ? official.files : null;
118
- this.notifications = config.notifications ? official.notifications : null;
119
- this.configuration = config.configuration ? official.configuration : null;
120
- return;
89
+ this.apiKeyRoles = Object.freeze([...(typeof config.apiKeys === "object" ? config.apiKeys.roles ?? [] : [])]);
90
+ this.jobHandlers = Object.freeze({ ...(typeof config.jobs === "object" ? config.jobs.handlers ?? {} : {}) });
91
+ const resolveDurable = options.resolveDurable;
92
+ const authorizer = options.authority.serviceAuthorizer(async (request) => {
93
+ if (request.durable)
94
+ return resolveDurable ? resolveDurable(request.subjectId, request.subjectKind) : null;
95
+ return request.runId ? this.#bound.get(request.runId) ?? null : null;
96
+ });
97
+ // The package's own construction, on the shared instance.
98
+ const official = createServices({
99
+ db: options.servicesDb,
100
+ application: options.applicationId,
101
+ authorizer,
102
+ credentials: this.credentials,
103
+ ...(options.allowPrivateWebhookDestinations ? { webhookDestinationPolicy: { allowPrivateNetworks: true } } : {}),
104
+ ...(options.apiKeyVerifierKey ? { apiKeyVerifierKey: options.apiKeyVerifierKey } : {}),
105
+ });
106
+ if (!official.usesInstance(options.servicesDb) || official.ownsDb) {
107
+ throw new FeltKitError("CONFIGURATION", `@appport/services ${VERSION} did not use the application's FeltDB instance. Refusing to start with a second database.`);
121
108
  }
122
- for (const service of ["notifications", "configuration"]) {
123
- if (config[service]) {
124
- throw new FeltKitError("CONFIGURATION", `services.${service} needs @appport/services ${SHARED_INSTANCE_SERVICES} or newer (installed: ${version}).`, {
125
- hint: `Older releases can only run ${service} on a FeltDB instance of their own, and FeltKit does not run a second database.`,
109
+ if (config.schedules && !config.jobs) {
110
+ throw new FeltKitError("CONFIGURATION", "services.schedules needs services.jobs: a schedule creates jobs.");
111
+ }
112
+ this.#official = official;
113
+ this.db = official.db;
114
+ this.gateway = official.gateway;
115
+ this.files = config.files ? official.files : null;
116
+ this.notifications = config.notifications ? official.notifications : null;
117
+ this.configuration = config.configuration ? official.configuration : null;
118
+ this.apiKeys = config.apiKeys ? official.apiKeys : null;
119
+ this.webhooks = config.webhooks ? official.webhooks : null;
120
+ this.jobs = config.jobs ? official.jobs : null;
121
+ this.schedules = config.schedules ? official.schedules : null;
122
+ this.intelligence = config.intelligence ? official.intelligence : null;
123
+ if (this.jobs) {
124
+ for (const [type, fn] of Object.entries(this.jobHandlers)) {
125
+ // Upstream calls this inside gateway.execute('jobs.execute', principal, …): the job is
126
+ // already authorized as its principal; the function is authorized again as itself.
127
+ this.jobs.register(type, async (job, execution) => {
128
+ const principal = await resolveDurable?.(execution.principal.principalId, execution.principal.principalType);
129
+ if (!principal)
130
+ throw new FeltKitError("FORBIDDEN", `The principal behind job ${job.id} can no longer be resolved.`);
131
+ if (!options.runJob)
132
+ throw new FeltKitError("UNAVAILABLE", "No job runner is attached.");
133
+ await options.runJob(fn, job.payload ?? {}, principal, execution.runId);
126
134
  });
127
135
  }
128
136
  }
129
- this.mode = "composed";
130
- this.#official = null;
131
- this.gateway = new ServiceGateway({ application: options.applicationId, authorizer, evidence: new FeltDbEffectEvidenceStore(options.servicesDb) });
132
- this.files = config.files ? new FileService({ store: new FeltDbFileStore(options.servicesDb), auditSink: new FeltDbFileAuditSink(options.servicesDb), authority: this.gateway }) : null;
133
- this.notifications = null;
134
- this.configuration = null;
137
+ }
138
+ /**
139
+ * The services the packaged management pages and routes are mounted for: exactly
140
+ * the enabled ones, as the same objects application code uses.
141
+ */
142
+ management() {
143
+ const out = {};
144
+ for (const key of ["apiKeys", "configuration", "intelligence", "webhooks", "jobs", "notifications", "files", "schedules"]) {
145
+ if (this[key])
146
+ out[key] = this[key];
147
+ }
148
+ return out;
149
+ }
150
+ /**
151
+ * Run `work` with `principal` bound as a live invocation: any service effect inside is
152
+ * authorized by the gateway as that principal, exactly as from a function.
153
+ */
154
+ async asPrincipal(principal, work, requestId = `req_${randomUUID()}`) {
155
+ // The request id is the run id of every service effect inside, and so the `runId`
156
+ // of AppPort Services' effect evidence for it.
157
+ const release = this.enter(requestId, principal);
158
+ try {
159
+ return await this.#record(work(this.#verified(principal, requestId)));
160
+ }
161
+ finally {
162
+ release();
163
+ }
164
+ }
165
+ /** AppPort Services' capability manifest (name, service, effect, invocable). */
166
+ capabilities() {
167
+ return this.#official.capabilities;
168
+ }
169
+ /**
170
+ * AppPort Services' own invoke(), as `principal`, for an enabled service only. The
171
+ * gateway authorizes it exactly as it would a function's or the console's request.
172
+ */
173
+ async invoke(capability, input, principal, signal, requestId) {
174
+ const declared = this.capabilities().find((c) => c.name === capability);
175
+ if (!declared || !declared.invocable)
176
+ throw new FeltKitError("NOT_FOUND", `"${capability}" is not an invocable AppPort Services capability.`);
177
+ if (!(SERVICE_KEY[declared.service] && this[SERVICE_KEY[declared.service]])) {
178
+ throw new FeltKitError("CONFIGURATION", `The ${declared.service} service is not enabled.`);
179
+ }
180
+ return this.asPrincipal(principal, (verified) => abortable(this.#official.invoke(capability, input, { principal: verified }), signal), requestId);
181
+ }
182
+ /**
183
+ * AppPort Services' effect evidence for one run id (a FeltKit request id, a job attempt
184
+ * `<jobId>:<attempt>`, or a delivery attempt `<deliveryId>:<attempt>`), this application
185
+ * and tenant only. `state: "started"` means a completion was never recorded: the
186
+ * outcome is unknown, not failed.
187
+ */
188
+ evidence(runId) {
189
+ return this.#official.evidence.findByRunId(runId, { tenantId: this.#tenantId, limit: MAX_EVIDENCE_LOOKUP_LIMIT });
190
+ }
191
+ /** AppPort Services' own health for this application's tenant. Trusted host read: counts only, authorizes nothing. */
192
+ health(options = {}) {
193
+ return this.#official.health({ tenantId: this.#tenantId, ...options });
194
+ }
195
+ /** Identity claims for the management router: verified against this gateway, bound to a request. */
196
+ identify(principal, requestId) {
197
+ return this.#verified(principal, requestId);
198
+ }
199
+ /**
200
+ * Drive durable work once: recurring schedules, due jobs, due webhook deliveries.
201
+ * Every attempt is authorized by AppPort Services as its own principal.
202
+ */
203
+ async tick(workerId) {
204
+ let jobs = 0;
205
+ let deliveries = 0;
206
+ let scheduled = 0;
207
+ if (this.jobs) {
208
+ if (this.schedules)
209
+ scheduled = await this.jobs.processRecurringSchedules(this.#tenantId);
210
+ for (const job of await this.jobs.listDueJobs(this.#tenantId)) {
211
+ await this.jobs.executeJob(this.#tenantId, job.id, workerId);
212
+ jobs += 1;
213
+ }
214
+ }
215
+ if (this.webhooks) {
216
+ const now = Date.now();
217
+ for (const delivery of await this.webhooks.listWebhookDeliveries(this.#tenantId)) {
218
+ const due = delivery.status === "pending" || (delivery.status === "retrying" && (!delivery.nextAttemptAt || Date.parse(delivery.nextAttemptAt) <= now));
219
+ if (!due)
220
+ continue;
221
+ await this.webhooks.deliverWebhook(this.#tenantId, delivery.id);
222
+ deliveries += 1;
223
+ }
224
+ }
225
+ return { jobs, deliveries, scheduled };
135
226
  }
136
227
  get tenantId() {
137
228
  return this.#tenantId;
138
229
  }
230
+ /** Every credential reference the services hold, what uses it, and whether it resolves. Never a value. */
231
+ async credentialReferences() {
232
+ const refs = new Map();
233
+ const add = (ref, usedBy) => {
234
+ if (!ref)
235
+ return;
236
+ refs.set(ref, [...(refs.get(ref) ?? []), usedBy]);
237
+ };
238
+ if (this.configuration) {
239
+ // Retained private read (docs/UPSTREAM-GAPS.md, S3): health() counts bindings but does not
240
+ // name their references, and configuration.list()/export() are authorized effects that
241
+ // write evidence, which Studio's change-driven refresh would turn into a loop. This is
242
+ // the one AppPort Services collection FeltKit still reads.
243
+ for (const secret of (await this.db.collection("ConfigurationSecrets").find({ tenantId: this.#tenantId }, { limit: 500 })))
244
+ add(secret.credentialRef, `configuration secret ${secret.name}`);
245
+ }
246
+ if (this.webhooks) {
247
+ for (const endpoint of await this.webhooks.listWebhookEndpoints(this.#tenantId))
248
+ if (!endpoint.disabledAt)
249
+ add(endpoint.signingCredentialRef, `webhook ${new URL(endpoint.url).origin}`);
250
+ }
251
+ return [...refs].map(([ref, usedBy]) => ({ ...this.credentials.describe(ref), usedBy }));
252
+ }
253
+ /**
254
+ * Store a credential value through AppPort Services' `credential.store`, as `principal`:
255
+ * authorized by the gateway (permission `credential.store`), audited and versioned by
256
+ * the service without the value, kept by FeltKit's custody (runtime/credentials.ts).
257
+ * The result carries the reference and version only. Any error is scrubbed of the value
258
+ * before it is recorded or rethrown.
259
+ */
260
+ async storeCredential(input, principal, requestId) {
261
+ if (typeof input.value !== "string" || !input.value.trim())
262
+ throw new FeltKitError("INVALID_ARGUMENT", "Enter a value to store.");
263
+ if (!credentialId(input.ref) || !input.ref.startsWith("credential-ref:"))
264
+ throw new FeltKitError("INVALID_ARGUMENT", "A credential reference is credential-ref:<id>.");
265
+ const value = input.value.trim();
266
+ this.#requireCapability("credential.store");
267
+ const result = await this.asPrincipal(principal, (verified) => this.#official
268
+ .invoke("credential.store", { ref: input.ref, value, ...(input.provider ? { provider: input.provider } : {}), ...(input.kind ? { kind: input.kind } : {}), ...(input.name ? { name: input.name } : {}) }, { principal: verified })
269
+ .catch((error) => {
270
+ // AppPort Services refuses a read-only custody; say exactly what to set on this host instead.
271
+ const readOnly = error?.code === "CUSTODY_READ_ONLY" ? this.credentials.readOnlyReason(input.ref) : null;
272
+ if (readOnly)
273
+ throw Object.assign(new Error(readOnly), { code: "CUSTODY_READ_ONLY" });
274
+ throw scrubError(error, value);
275
+ }), requestId);
276
+ const out = result;
277
+ if (JSON.stringify(out ?? {}).includes(value))
278
+ throw new FeltKitError("INTERNAL", "credential.store returned material; refusing to pass it on.");
279
+ return { ref: out.ref ?? input.ref, version: Number(out.version ?? 0), storedAt: String(out.storedAt ?? new Date().toISOString()), ...(out.binding ? { binding: out.binding } : {}) };
280
+ }
281
+ #requireCapability(name) {
282
+ if (!this.capabilities().some((c) => c.name === name)) {
283
+ throw new FeltKitError("UNAVAILABLE", `@appport/services ${VERSION} has no ${name} capability; FeltKit needs @appport/services 0.8.0 or later to store credentials.`);
284
+ }
285
+ }
286
+ /** The tenant, application, and configuration environment this runtime's services use. */
287
+ get scope() {
288
+ return { tenantId: this.#tenantId, applicationId: this.#applicationId, environment: this.#environment };
289
+ }
290
+ /**
291
+ * This environment's non-secret configuration as AppPort Services' versioned export
292
+ * document (`appport.configuration-export`): variables, credential binding names and
293
+ * references, active webhook endpoints (signing reference only), enabled schedules.
294
+ * Read as FeltKit's host-only transfer principal. Secret values never appear.
295
+ */
296
+ async exportConfiguration() {
297
+ const service = this.#require(this.configuration, "configuration");
298
+ return this.asPrincipal(TRANSFER_READ, (principal) => service.export({ principal, environment: this.#environment }));
299
+ }
300
+ /**
301
+ * Plan (dryRun) or apply an export document to this environment through AppPort
302
+ * Services' own import: each write goes through its capability, credential bindings
303
+ * are never created (they are reported in `missingSecrets` for a person to attach),
304
+ * and a document carrying a secret value is refused. Schedules are reported as
305
+ * skipped, not imported: a schedule's jobs run as its creator, and the transfer
306
+ * principal is not a person FeltKit can resolve when they run.
307
+ */
308
+ async importConfiguration(input, options = {}) {
309
+ const service = this.#require(this.configuration, "configuration");
310
+ let document;
311
+ try {
312
+ document = parseConfigurationExport(input);
313
+ }
314
+ catch (error) {
315
+ throw new FeltKitError("INVALID_ARGUMENT", `Not an importable configuration document: ${error.message}`, { cause: error });
316
+ }
317
+ const dryRun = options.dryRun === true;
318
+ const report = await this.asPrincipal(dryRun ? TRANSFER_READ : TRANSFER_WRITE, (principal) => service.import({ ...document, schedules: [] }, { principal, environment: this.#environment, dryRun, overwrite: options.overwrite === true }));
319
+ const skipped = document.schedules.map((schedule) => ({
320
+ kind: "schedule",
321
+ key: `${schedule.type}@${schedule.interval}`,
322
+ action: "skip",
323
+ applied: false,
324
+ reason: "Not imported by FeltKit: a schedule's jobs run as its creator. Create it in this environment as the person whose authority it should run with.",
325
+ }));
326
+ return { ...report, items: [...report.items, ...skipped], summary: { ...report.summary, skip: report.summary.skip + skipped.length } };
327
+ }
139
328
  /** Allow `principal` to cause service effects while request `requestId` runs. */
140
329
  enter(requestId, principal) {
141
330
  if (!principal)
@@ -202,16 +391,10 @@ export class ServicesHost {
202
391
  },
203
392
  read: async (id) => {
204
393
  const file = await reader.get(id);
205
- reads.add(FILE_CONTENT_COLLECTION);
206
- const contentId = String((await this.#record(this.#requireFiles().get(this.#tenantId, id, this.#verified(principal, requestId)))).storageKey).replace(/^feltkit-content:/, "");
207
- const record = (await this.#content.collection(FILE_CONTENT_COLLECTION).get(contentId)) ?? null;
208
- if (!record)
209
- throw new FeltKitError("NOT_FOUND", `The content for file ${id} is missing.`);
210
- const bytes = new Uint8Array(Buffer.from(record.data, "base64"));
211
- const checksum = createHash("sha256").update(bytes).digest("hex");
212
- if (checksum !== record.checksum || (file.checksum && checksum !== file.checksum)) {
213
- throw new FeltKitError("INTERNAL", `File ${id} failed its checksum; the stored bytes do not match the recorded digest.`);
214
- }
394
+ const storageKey = String((await this.#record(this.#requireFiles().get(this.#tenantId, id, this.#verified(principal, requestId)))).storageKey);
395
+ const { bytes, collection } = await this.#content.read(id, storageKey, file.checksum);
396
+ if (collection)
397
+ reads.add(collection);
215
398
  return { file, bytes, text: () => new TextDecoder().decode(bytes) };
216
399
  },
217
400
  };
@@ -230,34 +413,24 @@ export class ServicesHost {
230
413
  if (bytes.byteLength > this.#maxBytes) {
231
414
  throw new FeltKitError("PAYLOAD_TOO_LARGE", `Files are limited to ${this.#maxBytes} bytes on this runtime (got ${bytes.byteLength}).`);
232
415
  }
233
- const checksum = createHash("sha256").update(bytes).digest("hex");
234
- const contentId = randomUUID();
416
+ const { storageKey, checksum } = await this.#content.store(bytes);
235
417
  const verified = this.#verified(principal, requestId);
236
- const created = await this.#record(service.create({
237
- name: input.name.trim(),
238
- ...(input.contentType ? { contentType: input.contentType } : {}),
239
- size: bytes.byteLength,
240
- checksum,
241
- storageKey: `feltkit-content:${contentId}`,
242
- ...(input.metadata ? { metadata: input.metadata } : {}),
243
- }, verified));
244
418
  try {
245
- await this.#content.transaction({
246
- operations: [
247
- {
248
- collection: FILE_CONTENT_COLLECTION,
249
- id: contentId,
250
- requireAbsent: true,
251
- value: { id: contentId, fileId: created.id, data: Buffer.from(bytes).toString("base64"), size: bytes.byteLength, checksum },
252
- },
253
- ],
254
- });
419
+ const created = await this.#record(service.create({
420
+ name: input.name.trim(),
421
+ ...(input.contentType ? { contentType: input.contentType } : {}),
422
+ size: bytes.byteLength,
423
+ checksum,
424
+ storageKey,
425
+ ...(input.metadata ? { metadata: input.metadata } : {}),
426
+ }, verified));
427
+ return toInfo(created);
255
428
  }
256
429
  catch (error) {
257
- await service.delete(this.#tenantId, created.id, verified).catch(() => undefined);
258
- throw new FeltKitError("UNAVAILABLE", `Storing file content failed; the file record was removed: ${error.message}`, { cause: error });
430
+ // No file record points at these bytes; do not leave them behind.
431
+ await this.#content.release(storageKey).catch(() => undefined);
432
+ throw error;
259
433
  }
260
- return toInfo(created);
261
434
  },
262
435
  remove: async (id) => {
263
436
  use();
@@ -265,13 +438,35 @@ export class ServicesHost {
265
438
  const verified = this.#verified(principal, requestId);
266
439
  const current = await this.#record(service.get(this.#tenantId, id, verified));
267
440
  await this.#record(service.delete(this.#tenantId, id, verified));
268
- const contentId = String(current.storageKey).replace(/^feltkit-content:/, "");
269
- const content = await this.#content.collection(FILE_CONTENT_COLLECTION).get(contentId);
270
- if (content)
271
- await this.#content.transaction({ operations: [{ collection: FILE_CONTENT_COLLECTION, id: contentId, ifVersion: content.__version }] });
441
+ await this.#content.release(String(current.storageKey));
442
+ },
443
+ };
444
+ return { files: writer, notifications, configuration, jobs: this.#bindJobs(principal, requestId, used), webhooks: this.#bindWebhooks(principal, requestId, used) };
445
+ }
446
+ #bindJobs(principal, requestId, used) {
447
+ return {
448
+ enqueue: async (type, payload = {}, options = {}) => {
449
+ used.add("jobs");
450
+ const service = this.#require(this.jobs, "jobs");
451
+ if (typeof type !== "string" || !type)
452
+ throw new FeltKitError("INVALID_ARGUMENT", "enqueue() needs a job type.");
453
+ if (!this.jobHandlers[type]) {
454
+ throw new FeltKitError("INVALID_ARGUMENT", `No handler for job type "${type}". Declare it in feltkit({ services: { jobs: { handlers: { "${type}": "<module>:<function>" } } } }).`);
455
+ }
456
+ const job = await this.#record(service.enqueue({ type, payload, ...(options.runAt ? { runAt: options.runAt } : {}), ...(options.maxAttempts ? { maxAttempts: options.maxAttempts } : {}) }, this.#verified(principal, requestId)));
457
+ return { id: job.id, status: job.status };
458
+ },
459
+ };
460
+ }
461
+ #bindWebhooks(principal, requestId, used) {
462
+ return {
463
+ emit: async (type, payload) => {
464
+ used.add("webhooks");
465
+ const service = this.#require(this.webhooks, "webhooks");
466
+ const deliveries = await this.#record(service.emitWebhookEvent({ type, payload }, this.#verified(principal, requestId)));
467
+ return { deliveries: deliveries.length };
272
468
  },
273
469
  };
274
- return { files: writer, notifications, configuration };
275
470
  }
276
471
  #bindNotifications(principal, requestId, reads, writable, used) {
277
472
  const service = () => (used.add("notifications"), reads.add("notifications"), this.#require(this.notifications, "notifications"));
@@ -339,67 +534,199 @@ export class ServicesHost {
339
534
  },
340
535
  };
341
536
  }
342
- /** A live check: the store answers through the shared instance. Never authorizes anything. */
537
+ /** A live check: AppPort Services' health() answers through the shared instance. Authorizes nothing. */
343
538
  async check() {
344
539
  const at = new Date().toISOString();
345
540
  try {
346
- // Reads the services' own collections through the shared handle. Authorizes nothing.
347
- for (const collection of ["files", "notifications", "ConfigurationVariables", "service_effect_evidence"])
348
- await this.db.collection(collection).find({}, { limit: 1 });
349
- this.#lastChecked = { at, ok: true, detail: `Stores reachable through the shared FeltDB instance (${this.mode === "shared-instance" ? "createServices({ db })" : "composed from public classes"}).` };
541
+ await this.health({ countLimit: 1 });
542
+ this.#lastChecked = { at, ok: true, detail: "AppPort Services answered health() through the shared FeltDB instance." };
350
543
  }
351
544
  catch (error) {
352
- this.#lastChecked = { at, ok: false, detail: `Stores unreachable: ${error.message}` };
545
+ this.#lastChecked = { at, ok: false, detail: `AppPort Services health() failed: ${error.message}` };
353
546
  }
354
547
  }
355
- status(connected) {
356
- const version = packageVersion();
357
- const installed = version !== "unknown";
358
- const shared = this.mode === "shared-instance";
359
- const healthy = this.#lastChecked?.ok ?? null;
360
- const mounted = (id, name, description, service, collections, capabilities, supported) => ({
361
- id,
362
- name,
363
- description,
364
- package: "@appport/services",
365
- version,
366
- installed,
367
- configured: service !== null,
368
- connected: connected && service !== null,
369
- healthy: service === null ? null : healthy,
370
- available: supported && service !== null && connected,
371
- detail: !supported
372
- ? `Needs @appport/services ${SHARED_INSTANCE_SERVICES} or newer (installed: ${version}); older releases run it only on a second database.`
373
- : service === null
374
- ? `Not enabled. Add services: { ${id}: true } to feltkit({ ... }).`
375
- : this.#lastChecked?.detail ?? "Not checked yet.",
376
- collections,
377
- capabilities,
378
- ...(this.#lastChecked && service !== null ? { lastCheckedAt: this.#lastChecked.at } : {}),
379
- ...(this.#lastError && service !== null ? { lastError: this.#lastError } : {}),
380
- });
381
- return [
382
- mounted("files", "Files", "File records with ownership, audit, and authorization. Bytes are stored in the same FeltDB instance.", this.files, ["files", "file_audit_events", "service_effect_evidence", FILE_CONTENT_COLLECTION], ["files.read", "files.write", "files.delete"], true),
383
- mounted("notifications", "Notifications", "Durable in-app notifications. Each principal reads only its own.", this.notifications, ["notifications", "notification_deliveries", "notification_audit_events"], ["notifications.send", "notifications.read", "notifications.update", "notifications.delete"], shared),
384
- mounted("configuration", "Configuration", `Variables for this environment (stored as "${this.#environment}").`, this.configuration, ["ConfigurationVariables", "ConfigurationAuditEvents"], ["configuration.read", "configuration.write", "configuration.delete"], shared),
385
- ...UNAVAILABLE.map(([id, name, description, reason]) => ({
548
+ /**
549
+ * Every service, with an honest state, from AppPort Services' own `health()` for this
550
+ * application's tenant. FeltKit adds only what it alone knows: whether the credential
551
+ * references endpoints sign with resolve in its custody, and which job types have a
552
+ * handler. No value, payload, secret, or credential is read into the result.
553
+ */
554
+ async status(connected) {
555
+ const at = new Date().toISOString();
556
+ let health = null;
557
+ try {
558
+ health = await this.health();
559
+ this.#lastChecked = { at, ok: true, detail: "AppPort Services answered health() through the shared FeltDB instance." };
560
+ }
561
+ catch (error) {
562
+ this.#lastChecked = { at, ok: false, detail: `AppPort Services health() failed: ${error.message}` };
563
+ }
564
+ // FeltKit's custody: an active endpoint whose signing reference does not resolve cannot sign.
565
+ const unsigned = this.webhooks && health
566
+ ? (await this.webhooks.listWebhookEndpoints(this.#tenantId)).filter((e) => !e.disabledAt && (!e.signingCredentialRef || !this.credentials.describe(e.signingCredentialRef).present))
567
+ : [];
568
+ const handlers = Object.keys(this.jobHandlers).length;
569
+ const entry = (id, name, description, collections, capabilities, page) => {
570
+ const enabled = this[id] !== null;
571
+ const own = health?.services[id];
572
+ let state;
573
+ let detail;
574
+ let summary;
575
+ if (!enabled) {
576
+ state = "available";
577
+ detail = `Not enabled. Add services: { ${id}: true } to feltkit({ ... }).`;
578
+ }
579
+ else if (!health || !own) {
580
+ state = "unhealthy";
581
+ detail = this.#lastChecked.detail;
582
+ }
583
+ else {
584
+ summary = { ...own.counts, ...(id === "jobs" ? { handlers } : {}) };
585
+ const capped = health.cappedCounts.filter((c) => c.startsWith(`${id}.`));
586
+ const reasons = own.reasons.map((r) => describeReason(id, r, own.counts)).join(" ");
587
+ if (id === "webhooks" && unsigned.length) {
588
+ state = "unhealthy";
589
+ detail = `${unsigned.length} endpoint(s) cannot sign deliveries: ${unsigned.map((e) => this.credentials.describe(e.signingCredentialRef ?? "").variable ?? "(no reference)").join(", ")} not set.${reasons ? ` ${reasons}` : ""}`;
590
+ }
591
+ else if (own.state === "degraded") {
592
+ state = "unhealthy";
593
+ detail = reasons;
594
+ }
595
+ else if (own.state === "unconfigured" || own.state === "disabled" || (id === "jobs" && handlers === 0)) {
596
+ state = "unconfigured";
597
+ detail = reasons || UNCONFIGURED[id] || "Enabled; nothing set up yet.";
598
+ }
599
+ else {
600
+ state = "configured";
601
+ detail = "Enabled; AppPort Services reports nothing needing attention.";
602
+ }
603
+ if (id === "webhooks")
604
+ detail += " Delivery counts cover every application in this namespace that uses this tenant id.";
605
+ if (capped.length)
606
+ detail += ` At least ${health.countLimit} for: ${capped.join(", ")}.`;
607
+ }
608
+ return {
386
609
  id,
387
610
  name,
388
611
  description,
389
612
  package: "@appport/services",
390
- version,
391
- installed,
392
- configured: false,
393
- connected: false,
394
- healthy: null,
395
- available: false,
396
- detail: `Not available in FeltKit: ${reason}`,
397
- collections: [],
398
- capabilities: [],
399
- })),
613
+ version: VERSION,
614
+ installed: true,
615
+ configured: state === "configured" || state === "unhealthy",
616
+ connected: connected && enabled,
617
+ healthy: enabled ? state !== "unhealthy" : null,
618
+ available: enabled && connected,
619
+ state,
620
+ detail,
621
+ collections,
622
+ capabilities,
623
+ ...(summary && Object.keys(summary).length ? { summary } : {}),
624
+ ...(enabled ? { page } : {}),
625
+ ...(this.#lastChecked && enabled ? { lastCheckedAt: this.#lastChecked.at } : {}),
626
+ ...(this.#lastError && enabled ? { lastError: this.#lastError } : {}),
627
+ };
628
+ };
629
+ return [
630
+ entry("files", "Files", "File records with ownership, audit, and authorization. Bytes are stored in the same FeltDB instance.", ["files", "file_audit_events", "service_effect_evidence", FILE_CONTENT_COLLECTION], ["files.read", "files.write", "files.delete"], "/files"),
631
+ entry("notifications", "Notifications", "Durable in-app notifications. Each principal reads only its own.", ["notifications", "notification_deliveries", "notification_audit_events"], ["notifications.send", "notifications.read", "notifications.update", "notifications.delete"], "/notifications"),
632
+ entry("configuration", "Configuration", `Variables and credential references for this environment (stored as "${this.#environment}").`, ["ConfigurationVariables", "ConfigurationSecrets", "ConfigurationAuditEvents"], ["configuration.read", "configuration.write", "configuration.delete", "credential.attach", "credential.rotate", "credential.detach"], "/configuration"),
633
+ entry("apiKeys", "API keys", "Machine credentials. FeltKit accepts them as an identity holding services.apiKeys.roles.", ["api_keys", "api_key_audit_events"], ["apikeys.read", "apikeys.create", "apikeys.update", "apikeys.rotate", "apikeys.revoke", "apikeys.audit"], "/api-keys"),
634
+ entry("webhooks", "Webhooks", "Signed outbound delivery to registered endpoints, with retries and history.", ["webhook_endpoints", "webhook_deliveries", "webhook_audit_events"], ["webhooks.read", "webhooks.deliveries.read", "webhooks.register", "webhooks.remove", "webhooks.emit", "webhooks.deliver", "webhooks.replay"], "/webhooks"),
635
+ entry("jobs", "Jobs", "Durable background work with leases and retries; each type runs a FeltKit function as its enqueuer.", ["jobs", "job_audit_events"], ["jobs.read", "jobs.create", "jobs.retry", "jobs.execute"], "/jobs"),
636
+ entry("schedules", "Schedules", "Recurring jobs.", ["job_schedules"], ["schedules.read", "schedules.create", "schedules.cancel"], "/schedules"),
637
+ entry("intelligence", "Intelligence", "Model provider configuration. Configuration only: AppPort Services never runs a model.", [], ["intelligence.catalog", "intelligence.read", "intelligence.write", "intelligence.credential.set", "intelligence.credential.remove"], "/intelligence"),
400
638
  ];
401
639
  }
402
640
  }
641
+ /** AppPort Services' health reason codes (docs/health.md), as sentences. */
642
+ function describeReason(service, reason, counts) {
643
+ switch (reason) {
644
+ case "failed_deliveries":
645
+ return `${counts.failedDeliveries ?? 0} delivery(ies) failed. Open ${service === "notifications" ? "Notifications" : "Webhooks"} for the error on each.`;
646
+ case "failed_jobs":
647
+ return `${counts.failed ?? 0} job(s) failed. Open Jobs for the error on each, or ask the agent to diagnose one.`;
648
+ case "failed_notifications":
649
+ return `${counts.failedNotifications ?? 0} notification(s) failed.`;
650
+ case "missing_required":
651
+ return `${counts.missingRequired ?? 0} required configuration value(s) have no binding.`;
652
+ case "missing_material":
653
+ return `${counts.missingMaterial ?? 0} credential binding(s) have no stored value. Set each in Studio → Services → Credentials (or its FELTKIT_CREDENTIAL_<ID>).`;
654
+ case "legacy_secret_values":
655
+ return `${counts.legacySecretValues ?? 0} credential binding(s) still hold a raw value; rotate each to a credential-ref.`;
656
+ case "missing_credential":
657
+ return "The selected provider needs a credential and none is attached.";
658
+ case "not_configured":
659
+ return "Enabled; no provider selected.";
660
+ case "no_endpoints":
661
+ return UNCONFIGURED.webhooks;
662
+ case "all_endpoints_disabled":
663
+ return "Enabled; every endpoint is disabled.";
664
+ case "no_keys":
665
+ return UNCONFIGURED.apiKeys;
666
+ case "no_schedules":
667
+ return UNCONFIGURED.schedules;
668
+ case "all_schedules_disabled":
669
+ return "Enabled; every schedule is disabled.";
670
+ case "no_configuration":
671
+ return UNCONFIGURED.configuration;
672
+ case "authorizer_unconfigured":
673
+ return "No authorizer: AppPort Services refuses every effect.";
674
+ case "credentials_unconfigured":
675
+ return "No credential custody: effects that need a credential fail.";
676
+ default:
677
+ return `AppPort Services reports ${reason}.`;
678
+ }
679
+ }
680
+ /** An error with every occurrence of `secret` removed from its message, stack, and details. */
681
+ function scrubError(error, secret) {
682
+ if (!error || typeof error !== "object")
683
+ return new Error(redactSecret(String(error), secret));
684
+ const e = error;
685
+ try {
686
+ if (typeof e.message === "string")
687
+ e.message = redactSecret(e.message, secret);
688
+ if (typeof e.stack === "string")
689
+ e.stack = redactSecret(e.stack, secret);
690
+ if (e.details !== undefined && JSON.stringify(e.details).includes(secret))
691
+ e.details = undefined;
692
+ }
693
+ catch {
694
+ return new Error("credential.store failed (details withheld: they may have contained the value).");
695
+ }
696
+ return e;
697
+ }
698
+ /** FeltKit's host-only principals for `feltkit config export|import` (see Authority's system principals). */
699
+ const TRANSFER_READ = systemPrincipal("configuration-transfer", "transfer-read");
700
+ const TRANSFER_WRITE = systemPrincipal("configuration-transfer", "transfer-write");
701
+ /** AppPort Services' service names → this host's fields. */
702
+ const SERVICE_KEY = {
703
+ "api-keys": "apiKeys",
704
+ webhooks: "webhooks",
705
+ jobs: "jobs",
706
+ schedules: "schedules",
707
+ notifications: "notifications",
708
+ files: "files",
709
+ configuration: "configuration",
710
+ intelligence: "intelligence",
711
+ };
712
+ function abortable(promise, signal) {
713
+ if (!signal)
714
+ return promise;
715
+ if (signal.aborted)
716
+ return Promise.reject(Object.assign(new Error(String(signal.reason?.message ?? "cancelled")), { code: "CANCELLED" }));
717
+ return new Promise((resolve, reject) => {
718
+ const onAbort = () => reject(Object.assign(new Error(String(signal.reason?.message ?? "cancelled")), { code: "CANCELLED" }));
719
+ signal.addEventListener("abort", onAbort, { once: true });
720
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
721
+ });
722
+ }
723
+ const UNCONFIGURED = {
724
+ configuration: "Enabled; no variables or secrets yet.",
725
+ apiKeys: "Enabled; no active keys. Create one on the API keys page.",
726
+ webhooks: "Enabled; no endpoints registered.",
727
+ jobs: "Enabled; no job handlers declared (services.jobs.handlers).",
728
+ schedules: "Enabled; no active schedules.",
729
+ };
403
730
  function toNotification(item) {
404
731
  return {
405
732
  id: item.id,