@feltdb/feltkit 0.1.1 → 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.
Files changed (97) 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/main.js +218 -2
  5. package/dist/cli/main.js.map +1 -1
  6. package/dist/cli/skills.d.ts +39 -0
  7. package/dist/cli/skills.js +125 -0
  8. package/dist/cli/skills.js.map +1 -0
  9. package/dist/dashboard/assets/{index-BLnBFDJs.css → index--1Tqbv_A.css} +1 -1
  10. package/dist/dashboard/assets/index-Bm4qCYpv.js +15 -0
  11. package/dist/dashboard/index.html +2 -2
  12. package/dist/errors.d.ts +3 -1
  13. package/dist/errors.js +2 -0
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/runtime/activity.d.ts +21 -8
  17. package/dist/runtime/activity.js +17 -3
  18. package/dist/runtime/activity.js.map +1 -1
  19. package/dist/runtime/agent.d.ts +353 -0
  20. package/dist/runtime/agent.js +1345 -0
  21. package/dist/runtime/agent.js.map +1 -0
  22. package/dist/runtime/authority.d.ts +23 -3
  23. package/dist/runtime/authority.js +69 -5
  24. package/dist/runtime/authority.js.map +1 -1
  25. package/dist/runtime/changes.d.ts +16 -8
  26. package/dist/runtime/changes.js.map +1 -1
  27. package/dist/runtime/content.d.ts +33 -0
  28. package/dist/runtime/content.js +46 -0
  29. package/dist/runtime/content.js.map +1 -0
  30. package/dist/runtime/context.d.ts +26 -1
  31. package/dist/runtime/credentials.d.ts +42 -0
  32. package/dist/runtime/credentials.js +32 -0
  33. package/dist/runtime/credentials.js.map +1 -0
  34. package/dist/runtime/data.d.ts +8 -2
  35. package/dist/runtime/data.js +74 -9
  36. package/dist/runtime/data.js.map +1 -1
  37. package/dist/runtime/decisions.d.ts +131 -0
  38. package/dist/runtime/decisions.js +301 -0
  39. package/dist/runtime/decisions.js.map +1 -0
  40. package/dist/runtime/environment.js +11 -0
  41. package/dist/runtime/environment.js.map +1 -1
  42. package/dist/runtime/idempotency.d.ts +37 -0
  43. package/dist/runtime/idempotency.js +88 -0
  44. package/dist/runtime/idempotency.js.map +1 -0
  45. package/dist/runtime/instance.d.ts +8 -3
  46. package/dist/runtime/instance.js +27 -4
  47. package/dist/runtime/instance.js.map +1 -1
  48. package/dist/runtime/integrations.d.ts +120 -0
  49. package/dist/runtime/integrations.js +412 -0
  50. package/dist/runtime/integrations.js.map +1 -0
  51. package/dist/runtime/loader.d.ts +5 -1
  52. package/dist/runtime/loader.js +35 -13
  53. package/dist/runtime/loader.js.map +1 -1
  54. package/dist/runtime/projects.d.ts +1 -0
  55. package/dist/runtime/projects.js +6 -4
  56. package/dist/runtime/projects.js.map +1 -1
  57. package/dist/runtime/readiness.d.ts +29 -0
  58. package/dist/runtime/readiness.js +154 -0
  59. package/dist/runtime/readiness.js.map +1 -0
  60. package/dist/runtime/runtime.d.ts +50 -1
  61. package/dist/runtime/runtime.js +225 -9
  62. package/dist/runtime/runtime.js.map +1 -1
  63. package/dist/runtime/services.d.ts +186 -36
  64. package/dist/runtime/services.js +420 -152
  65. package/dist/runtime/services.js.map +1 -1
  66. package/dist/runtime/sessions.d.ts +7 -18
  67. package/dist/runtime/sessions.js +7 -5
  68. package/dist/runtime/sessions.js.map +1 -1
  69. package/dist/server/admin.d.ts +26 -0
  70. package/dist/server/admin.js +510 -8
  71. package/dist/server/admin.js.map +1 -1
  72. package/dist/server/index.d.ts +2 -0
  73. package/dist/server/index.js +13 -4
  74. package/dist/server/index.js.map +1 -1
  75. package/dist/server/management.d.ts +12 -0
  76. package/dist/server/management.js +177 -0
  77. package/dist/server/management.js.map +1 -0
  78. package/dist/server/mcp.d.ts +202 -0
  79. package/dist/server/mcp.js +62 -4
  80. package/dist/server/mcp.js.map +1 -1
  81. package/dist/server/operators.d.ts +77 -0
  82. package/dist/server/operators.js +162 -0
  83. package/dist/server/operators.js.map +1 -0
  84. package/dist/server/project.js +17 -4
  85. package/dist/server/project.js.map +1 -1
  86. package/dist/testing/index.js +3 -2
  87. package/dist/testing/index.js.map +1 -1
  88. package/package.json +18 -11
  89. package/skills/.claude-plugin/marketplace.json +16 -0
  90. package/skills/.claude-plugin/plugin.json +24 -0
  91. package/skills/README.md +44 -0
  92. package/skills/feltkit-agent/SKILL.md +84 -0
  93. package/skills/feltkit-build/SKILL.md +143 -0
  94. package/skills/feltkit-data/SKILL.md +79 -0
  95. package/skills/feltkit-operations/SKILL.md +72 -0
  96. package/skills/feltkit-services/SKILL.md +102 -0
  97. 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 } 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",
@@ -78,12 +46,21 @@ function translate(error) {
78
46
  throw error;
79
47
  }
80
48
  export class ServicesHost {
81
- mode;
82
49
  gateway;
83
50
  files;
84
51
  notifications;
85
52
  configuration;
86
- /** The instance handle every service store uses. Tests check it belongs to the shared instance. */
53
+ apiKeys;
54
+ webhooks;
55
+ jobs;
56
+ schedules;
57
+ intelligence;
58
+ credentials;
59
+ /** Roles a request authenticated by an API key holds. */
60
+ apiKeyRoles;
61
+ /** Job type → FeltKit function. */
62
+ jobHandlers;
63
+ /** The instance handle every service store uses (`services.db`, checked with `usesInstance`). */
87
64
  db;
88
65
  #official;
89
66
  #content;
@@ -98,44 +75,217 @@ export class ServicesHost {
98
75
  constructor(options) {
99
76
  this.#applicationId = options.applicationId;
100
77
  this.#tenantId = options.applicationId;
101
- this.#content = options.contentDb;
78
+ this.#content = new FileContent(options.contentDb);
102
79
  this.#environment = CONFIGURATION_ENVIRONMENT[options.environment] ?? "staging";
103
- this.db = options.servicesDb;
80
+ this.credentials = options.credentials ?? new EnvironmentCredentials();
104
81
  const config = options.config;
105
82
  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;
83
+ this.apiKeyRoles = Object.freeze([...(typeof config.apiKeys === "object" ? config.apiKeys.roles ?? [] : [])]);
84
+ this.jobHandlers = Object.freeze({ ...(typeof config.jobs === "object" ? config.jobs.handlers ?? {} : {}) });
85
+ const resolveDurable = options.resolveDurable;
86
+ const authorizer = options.authority.serviceAuthorizer(async (request) => {
87
+ if (request.durable)
88
+ return resolveDurable ? resolveDurable(request.subjectId, request.subjectKind) : null;
89
+ return request.runId ? this.#bound.get(request.runId) ?? null : null;
90
+ });
91
+ // The package's own construction, on the shared instance.
92
+ const official = createServices({
93
+ db: options.servicesDb,
94
+ application: options.applicationId,
95
+ authorizer,
96
+ credentials: this.credentials,
97
+ ...(options.allowPrivateWebhookDestinations ? { webhookDestinationPolicy: { allowPrivateNetworks: true } } : {}),
98
+ ...(options.apiKeyVerifierKey ? { apiKeyVerifierKey: options.apiKeyVerifierKey } : {}),
99
+ });
100
+ if (!official.usesInstance(options.servicesDb) || official.ownsDb) {
101
+ throw new FeltKitError("CONFIGURATION", `@appport/services ${VERSION} did not use the application's FeltDB instance. Refusing to start with a second database.`);
121
102
  }
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.`,
103
+ if (config.schedules && !config.jobs) {
104
+ throw new FeltKitError("CONFIGURATION", "services.schedules needs services.jobs: a schedule creates jobs.");
105
+ }
106
+ this.#official = official;
107
+ this.db = official.db;
108
+ this.gateway = official.gateway;
109
+ this.files = config.files ? official.files : null;
110
+ this.notifications = config.notifications ? official.notifications : null;
111
+ this.configuration = config.configuration ? official.configuration : null;
112
+ this.apiKeys = config.apiKeys ? official.apiKeys : null;
113
+ this.webhooks = config.webhooks ? official.webhooks : null;
114
+ this.jobs = config.jobs ? official.jobs : null;
115
+ this.schedules = config.schedules ? official.schedules : null;
116
+ this.intelligence = config.intelligence ? official.intelligence : null;
117
+ if (this.jobs) {
118
+ for (const [type, fn] of Object.entries(this.jobHandlers)) {
119
+ // Upstream calls this inside gateway.execute('jobs.execute', principal, …): the job is
120
+ // already authorized as its principal; the function is authorized again as itself.
121
+ this.jobs.register(type, async (job, execution) => {
122
+ const principal = await resolveDurable?.(execution.principal.principalId, execution.principal.principalType);
123
+ if (!principal)
124
+ throw new FeltKitError("FORBIDDEN", `The principal behind job ${job.id} can no longer be resolved.`);
125
+ if (!options.runJob)
126
+ throw new FeltKitError("UNAVAILABLE", "No job runner is attached.");
127
+ await options.runJob(fn, job.payload ?? {}, principal, execution.runId);
126
128
  });
127
129
  }
128
130
  }
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;
131
+ }
132
+ /**
133
+ * The services the packaged management pages and routes are mounted for: exactly
134
+ * the enabled ones, as the same objects application code uses.
135
+ */
136
+ management() {
137
+ const out = {};
138
+ for (const key of ["apiKeys", "configuration", "intelligence", "webhooks", "jobs", "notifications", "files", "schedules"]) {
139
+ if (this[key])
140
+ out[key] = this[key];
141
+ }
142
+ return out;
143
+ }
144
+ /**
145
+ * Run `work` with `principal` bound as a live invocation: any service effect inside is
146
+ * authorized by the gateway as that principal, exactly as from a function.
147
+ */
148
+ async asPrincipal(principal, work, requestId = `req_${randomUUID()}`) {
149
+ // The request id is the run id of every service effect inside, and so the `runId`
150
+ // of AppPort Services' effect evidence for it.
151
+ const release = this.enter(requestId, principal);
152
+ try {
153
+ return await this.#record(work(this.#verified(principal, requestId)));
154
+ }
155
+ finally {
156
+ release();
157
+ }
158
+ }
159
+ /** AppPort Services' capability manifest (name, service, effect, invocable). */
160
+ capabilities() {
161
+ return this.#official.capabilities;
162
+ }
163
+ /**
164
+ * AppPort Services' own invoke(), as `principal`, for an enabled service only. The
165
+ * gateway authorizes it exactly as it would a function's or the console's request.
166
+ */
167
+ async invoke(capability, input, principal, signal, requestId) {
168
+ const declared = this.capabilities().find((c) => c.name === capability);
169
+ if (!declared || !declared.invocable)
170
+ throw new FeltKitError("NOT_FOUND", `"${capability}" is not an invocable AppPort Services capability.`);
171
+ if (!(SERVICE_KEY[declared.service] && this[SERVICE_KEY[declared.service]])) {
172
+ throw new FeltKitError("CONFIGURATION", `The ${declared.service} service is not enabled.`);
173
+ }
174
+ return this.asPrincipal(principal, (verified) => abortable(this.#official.invoke(capability, input, { principal: verified }), signal), requestId);
175
+ }
176
+ /**
177
+ * AppPort Services' effect evidence for one run id (a FeltKit request id, a job attempt
178
+ * `<jobId>:<attempt>`, or a delivery attempt `<deliveryId>:<attempt>`), this application
179
+ * and tenant only. `state: "started"` means a completion was never recorded: the
180
+ * outcome is unknown, not failed.
181
+ */
182
+ evidence(runId) {
183
+ return this.#official.evidence.findByRunId(runId, { tenantId: this.#tenantId, limit: MAX_EVIDENCE_LOOKUP_LIMIT });
184
+ }
185
+ /** AppPort Services' own health for this application's tenant. Trusted host read: counts only, authorizes nothing. */
186
+ health(options = {}) {
187
+ return this.#official.health({ tenantId: this.#tenantId, ...options });
188
+ }
189
+ /** Identity claims for the management router: verified against this gateway, bound to a request. */
190
+ identify(principal, requestId) {
191
+ return this.#verified(principal, requestId);
192
+ }
193
+ /**
194
+ * Drive durable work once: recurring schedules, due jobs, due webhook deliveries.
195
+ * Every attempt is authorized by AppPort Services as its own principal.
196
+ */
197
+ async tick(workerId) {
198
+ let jobs = 0;
199
+ let deliveries = 0;
200
+ let scheduled = 0;
201
+ if (this.jobs) {
202
+ if (this.schedules)
203
+ scheduled = await this.jobs.processRecurringSchedules(this.#tenantId);
204
+ for (const job of await this.jobs.listDueJobs(this.#tenantId)) {
205
+ await this.jobs.executeJob(this.#tenantId, job.id, workerId);
206
+ jobs += 1;
207
+ }
208
+ }
209
+ if (this.webhooks) {
210
+ const now = Date.now();
211
+ for (const delivery of await this.webhooks.listWebhookDeliveries(this.#tenantId)) {
212
+ const due = delivery.status === "pending" || (delivery.status === "retrying" && (!delivery.nextAttemptAt || Date.parse(delivery.nextAttemptAt) <= now));
213
+ if (!due)
214
+ continue;
215
+ await this.webhooks.deliverWebhook(this.#tenantId, delivery.id);
216
+ deliveries += 1;
217
+ }
218
+ }
219
+ return { jobs, deliveries, scheduled };
135
220
  }
136
221
  get tenantId() {
137
222
  return this.#tenantId;
138
223
  }
224
+ /** Every credential reference the services hold, what uses it, and whether it resolves. Never a value. */
225
+ async credentialReferences() {
226
+ const refs = new Map();
227
+ const add = (ref, usedBy) => {
228
+ if (!ref)
229
+ return;
230
+ refs.set(ref, [...(refs.get(ref) ?? []), usedBy]);
231
+ };
232
+ if (this.configuration) {
233
+ // Retained private read (docs/UPSTREAM-GAPS.md, S3): health() counts bindings but does not
234
+ // name their references, and configuration.list()/export() are authorized effects that
235
+ // write evidence, which Studio's change-driven refresh would turn into a loop. This is
236
+ // the one AppPort Services collection FeltKit still reads.
237
+ for (const secret of (await this.db.collection("ConfigurationSecrets").find({ tenantId: this.#tenantId }, { limit: 500 })))
238
+ add(secret.credentialRef, `configuration secret ${secret.name}`);
239
+ }
240
+ if (this.webhooks) {
241
+ for (const endpoint of await this.webhooks.listWebhookEndpoints(this.#tenantId))
242
+ if (!endpoint.disabledAt)
243
+ add(endpoint.signingCredentialRef, `webhook ${new URL(endpoint.url).origin}`);
244
+ }
245
+ return [...refs].map(([ref, usedBy]) => ({ ...this.credentials.describe(ref), usedBy }));
246
+ }
247
+ /** The tenant, application, and configuration environment this runtime's services use. */
248
+ get scope() {
249
+ return { tenantId: this.#tenantId, applicationId: this.#applicationId, environment: this.#environment };
250
+ }
251
+ /**
252
+ * This environment's non-secret configuration as AppPort Services' versioned export
253
+ * document (`appport.configuration-export`): variables, credential binding names and
254
+ * references, active webhook endpoints (signing reference only), enabled schedules.
255
+ * Read as FeltKit's host-only transfer principal. Secret values never appear.
256
+ */
257
+ async exportConfiguration() {
258
+ const service = this.#require(this.configuration, "configuration");
259
+ return this.asPrincipal(TRANSFER_READ, (principal) => service.export({ principal, environment: this.#environment }));
260
+ }
261
+ /**
262
+ * Plan (dryRun) or apply an export document to this environment through AppPort
263
+ * Services' own import: each write goes through its capability, credential bindings
264
+ * are never created (they are reported in `missingSecrets` for a person to attach),
265
+ * and a document carrying a secret value is refused. Schedules are reported as
266
+ * skipped, not imported: a schedule's jobs run as its creator, and the transfer
267
+ * principal is not a person FeltKit can resolve when they run.
268
+ */
269
+ async importConfiguration(input, options = {}) {
270
+ const service = this.#require(this.configuration, "configuration");
271
+ let document;
272
+ try {
273
+ document = parseConfigurationExport(input);
274
+ }
275
+ catch (error) {
276
+ throw new FeltKitError("INVALID_ARGUMENT", `Not an importable configuration document: ${error.message}`, { cause: error });
277
+ }
278
+ const dryRun = options.dryRun === true;
279
+ const report = await this.asPrincipal(dryRun ? TRANSFER_READ : TRANSFER_WRITE, (principal) => service.import({ ...document, schedules: [] }, { principal, environment: this.#environment, dryRun, overwrite: options.overwrite === true }));
280
+ const skipped = document.schedules.map((schedule) => ({
281
+ kind: "schedule",
282
+ key: `${schedule.type}@${schedule.interval}`,
283
+ action: "skip",
284
+ applied: false,
285
+ 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.",
286
+ }));
287
+ return { ...report, items: [...report.items, ...skipped], summary: { ...report.summary, skip: report.summary.skip + skipped.length } };
288
+ }
139
289
  /** Allow `principal` to cause service effects while request `requestId` runs. */
140
290
  enter(requestId, principal) {
141
291
  if (!principal)
@@ -202,16 +352,10 @@ export class ServicesHost {
202
352
  },
203
353
  read: async (id) => {
204
354
  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
- }
355
+ const storageKey = String((await this.#record(this.#requireFiles().get(this.#tenantId, id, this.#verified(principal, requestId)))).storageKey);
356
+ const { bytes, collection } = await this.#content.read(id, storageKey, file.checksum);
357
+ if (collection)
358
+ reads.add(collection);
215
359
  return { file, bytes, text: () => new TextDecoder().decode(bytes) };
216
360
  },
217
361
  };
@@ -230,34 +374,24 @@ export class ServicesHost {
230
374
  if (bytes.byteLength > this.#maxBytes) {
231
375
  throw new FeltKitError("PAYLOAD_TOO_LARGE", `Files are limited to ${this.#maxBytes} bytes on this runtime (got ${bytes.byteLength}).`);
232
376
  }
233
- const checksum = createHash("sha256").update(bytes).digest("hex");
234
- const contentId = randomUUID();
377
+ const { storageKey, checksum } = await this.#content.store(bytes);
235
378
  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
379
  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
- });
380
+ const created = await this.#record(service.create({
381
+ name: input.name.trim(),
382
+ ...(input.contentType ? { contentType: input.contentType } : {}),
383
+ size: bytes.byteLength,
384
+ checksum,
385
+ storageKey,
386
+ ...(input.metadata ? { metadata: input.metadata } : {}),
387
+ }, verified));
388
+ return toInfo(created);
255
389
  }
256
390
  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 });
391
+ // No file record points at these bytes; do not leave them behind.
392
+ await this.#content.release(storageKey).catch(() => undefined);
393
+ throw error;
259
394
  }
260
- return toInfo(created);
261
395
  },
262
396
  remove: async (id) => {
263
397
  use();
@@ -265,13 +399,35 @@ export class ServicesHost {
265
399
  const verified = this.#verified(principal, requestId);
266
400
  const current = await this.#record(service.get(this.#tenantId, id, verified));
267
401
  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 }] });
402
+ await this.#content.release(String(current.storageKey));
403
+ },
404
+ };
405
+ return { files: writer, notifications, configuration, jobs: this.#bindJobs(principal, requestId, used), webhooks: this.#bindWebhooks(principal, requestId, used) };
406
+ }
407
+ #bindJobs(principal, requestId, used) {
408
+ return {
409
+ enqueue: async (type, payload = {}, options = {}) => {
410
+ used.add("jobs");
411
+ const service = this.#require(this.jobs, "jobs");
412
+ if (typeof type !== "string" || !type)
413
+ throw new FeltKitError("INVALID_ARGUMENT", "enqueue() needs a job type.");
414
+ if (!this.jobHandlers[type]) {
415
+ throw new FeltKitError("INVALID_ARGUMENT", `No handler for job type "${type}". Declare it in feltkit({ services: { jobs: { handlers: { "${type}": "<module>:<function>" } } } }).`);
416
+ }
417
+ const job = await this.#record(service.enqueue({ type, payload, ...(options.runAt ? { runAt: options.runAt } : {}), ...(options.maxAttempts ? { maxAttempts: options.maxAttempts } : {}) }, this.#verified(principal, requestId)));
418
+ return { id: job.id, status: job.status };
419
+ },
420
+ };
421
+ }
422
+ #bindWebhooks(principal, requestId, used) {
423
+ return {
424
+ emit: async (type, payload) => {
425
+ used.add("webhooks");
426
+ const service = this.#require(this.webhooks, "webhooks");
427
+ const deliveries = await this.#record(service.emitWebhookEvent({ type, payload }, this.#verified(principal, requestId)));
428
+ return { deliveries: deliveries.length };
272
429
  },
273
430
  };
274
- return { files: writer, notifications, configuration };
275
431
  }
276
432
  #bindNotifications(principal, requestId, reads, writable, used) {
277
433
  const service = () => (used.add("notifications"), reads.add("notifications"), this.#require(this.notifications, "notifications"));
@@ -339,67 +495,179 @@ export class ServicesHost {
339
495
  },
340
496
  };
341
497
  }
342
- /** A live check: the store answers through the shared instance. Never authorizes anything. */
498
+ /** A live check: AppPort Services' health() answers through the shared instance. Authorizes nothing. */
343
499
  async check() {
344
500
  const at = new Date().toISOString();
345
501
  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"}).` };
502
+ await this.health({ countLimit: 1 });
503
+ this.#lastChecked = { at, ok: true, detail: "AppPort Services answered health() through the shared FeltDB instance." };
350
504
  }
351
505
  catch (error) {
352
- this.#lastChecked = { at, ok: false, detail: `Stores unreachable: ${error.message}` };
506
+ this.#lastChecked = { at, ok: false, detail: `AppPort Services health() failed: ${error.message}` };
353
507
  }
354
508
  }
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]) => ({
509
+ /**
510
+ * Every service, with an honest state, from AppPort Services' own `health()` for this
511
+ * application's tenant. FeltKit adds only what it alone knows: whether the credential
512
+ * references endpoints sign with resolve in its custody, and which job types have a
513
+ * handler. No value, payload, secret, or credential is read into the result.
514
+ */
515
+ async status(connected) {
516
+ const at = new Date().toISOString();
517
+ let health = null;
518
+ try {
519
+ health = await this.health();
520
+ this.#lastChecked = { at, ok: true, detail: "AppPort Services answered health() through the shared FeltDB instance." };
521
+ }
522
+ catch (error) {
523
+ this.#lastChecked = { at, ok: false, detail: `AppPort Services health() failed: ${error.message}` };
524
+ }
525
+ // FeltKit's custody: an active endpoint whose signing reference does not resolve cannot sign.
526
+ const unsigned = this.webhooks && health
527
+ ? (await this.webhooks.listWebhookEndpoints(this.#tenantId)).filter((e) => !e.disabledAt && (!e.signingCredentialRef || !this.credentials.describe(e.signingCredentialRef).present))
528
+ : [];
529
+ const handlers = Object.keys(this.jobHandlers).length;
530
+ const entry = (id, name, description, collections, capabilities, page) => {
531
+ const enabled = this[id] !== null;
532
+ const own = health?.services[id];
533
+ let state;
534
+ let detail;
535
+ let summary;
536
+ if (!enabled) {
537
+ state = "available";
538
+ detail = `Not enabled. Add services: { ${id}: true } to feltkit({ ... }).`;
539
+ }
540
+ else if (!health || !own) {
541
+ state = "unhealthy";
542
+ detail = this.#lastChecked.detail;
543
+ }
544
+ else {
545
+ summary = { ...own.counts, ...(id === "jobs" ? { handlers } : {}) };
546
+ const capped = health.cappedCounts.filter((c) => c.startsWith(`${id}.`));
547
+ const reasons = own.reasons.map((r) => describeReason(id, r, own.counts)).join(" ");
548
+ if (id === "webhooks" && unsigned.length) {
549
+ state = "unhealthy";
550
+ detail = `${unsigned.length} endpoint(s) cannot sign deliveries: ${unsigned.map((e) => this.credentials.describe(e.signingCredentialRef ?? "").variable ?? "(no reference)").join(", ")} not set.${reasons ? ` ${reasons}` : ""}`;
551
+ }
552
+ else if (own.state === "degraded") {
553
+ state = "unhealthy";
554
+ detail = reasons;
555
+ }
556
+ else if (own.state === "unconfigured" || own.state === "disabled" || (id === "jobs" && handlers === 0)) {
557
+ state = "unconfigured";
558
+ detail = reasons || UNCONFIGURED[id] || "Enabled; nothing set up yet.";
559
+ }
560
+ else {
561
+ state = "configured";
562
+ detail = "Enabled; AppPort Services reports nothing needing attention.";
563
+ }
564
+ if (id === "webhooks")
565
+ detail += " Delivery counts cover every application in this namespace that uses this tenant id.";
566
+ if (capped.length)
567
+ detail += ` At least ${health.countLimit} for: ${capped.join(", ")}.`;
568
+ }
569
+ return {
386
570
  id,
387
571
  name,
388
572
  description,
389
573
  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
- })),
574
+ version: VERSION,
575
+ installed: true,
576
+ configured: state === "configured" || state === "unhealthy",
577
+ connected: connected && enabled,
578
+ healthy: enabled ? state !== "unhealthy" : null,
579
+ available: enabled && connected,
580
+ state,
581
+ detail,
582
+ collections,
583
+ capabilities,
584
+ ...(summary && Object.keys(summary).length ? { summary } : {}),
585
+ ...(enabled ? { page } : {}),
586
+ ...(this.#lastChecked && enabled ? { lastCheckedAt: this.#lastChecked.at } : {}),
587
+ ...(this.#lastError && enabled ? { lastError: this.#lastError } : {}),
588
+ };
589
+ };
590
+ return [
591
+ 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"),
592
+ 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"),
593
+ 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"),
594
+ 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"),
595
+ 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"),
596
+ 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"),
597
+ entry("schedules", "Schedules", "Recurring jobs.", ["job_schedules"], ["schedules.read", "schedules.create", "schedules.cancel"], "/schedules"),
598
+ 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
599
  ];
401
600
  }
402
601
  }
602
+ /** AppPort Services' health reason codes (docs/health.md), as sentences. */
603
+ function describeReason(service, reason, counts) {
604
+ switch (reason) {
605
+ case "failed_deliveries":
606
+ return `${counts.failedDeliveries ?? 0} delivery(ies) failed. Open ${service === "notifications" ? "Notifications" : "Webhooks"} for the error on each.`;
607
+ case "failed_jobs":
608
+ return `${counts.failed ?? 0} job(s) failed. Open Jobs for the error on each, or ask the agent to diagnose one.`;
609
+ case "failed_notifications":
610
+ return `${counts.failedNotifications ?? 0} notification(s) failed.`;
611
+ case "missing_required":
612
+ return `${counts.missingRequired ?? 0} required configuration value(s) have no binding.`;
613
+ case "legacy_secret_values":
614
+ return `${counts.legacySecretValues ?? 0} credential binding(s) still hold a raw value; rotate each to a credential-ref.`;
615
+ case "missing_credential":
616
+ return "The selected provider needs a credential and none is attached.";
617
+ case "not_configured":
618
+ return "Enabled; no provider selected.";
619
+ case "no_endpoints":
620
+ return UNCONFIGURED.webhooks;
621
+ case "all_endpoints_disabled":
622
+ return "Enabled; every endpoint is disabled.";
623
+ case "no_keys":
624
+ return UNCONFIGURED.apiKeys;
625
+ case "no_schedules":
626
+ return UNCONFIGURED.schedules;
627
+ case "all_schedules_disabled":
628
+ return "Enabled; every schedule is disabled.";
629
+ case "no_configuration":
630
+ return UNCONFIGURED.configuration;
631
+ case "authorizer_unconfigured":
632
+ return "No authorizer: AppPort Services refuses every effect.";
633
+ case "credentials_unconfigured":
634
+ return "No credential custody: effects that need a credential fail.";
635
+ default:
636
+ return `AppPort Services reports ${reason}.`;
637
+ }
638
+ }
639
+ /** FeltKit's host-only principals for `feltkit config export|import` (see Authority's system principals). */
640
+ const TRANSFER_READ = systemPrincipal("configuration-transfer", "transfer-read");
641
+ const TRANSFER_WRITE = systemPrincipal("configuration-transfer", "transfer-write");
642
+ /** AppPort Services' service names → this host's fields. */
643
+ const SERVICE_KEY = {
644
+ "api-keys": "apiKeys",
645
+ webhooks: "webhooks",
646
+ jobs: "jobs",
647
+ schedules: "schedules",
648
+ notifications: "notifications",
649
+ files: "files",
650
+ configuration: "configuration",
651
+ intelligence: "intelligence",
652
+ };
653
+ function abortable(promise, signal) {
654
+ if (!signal)
655
+ return promise;
656
+ if (signal.aborted)
657
+ return Promise.reject(Object.assign(new Error(String(signal.reason?.message ?? "cancelled")), { code: "CANCELLED" }));
658
+ return new Promise((resolve, reject) => {
659
+ const onAbort = () => reject(Object.assign(new Error(String(signal.reason?.message ?? "cancelled")), { code: "CANCELLED" }));
660
+ signal.addEventListener("abort", onAbort, { once: true });
661
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
662
+ });
663
+ }
664
+ const UNCONFIGURED = {
665
+ configuration: "Enabled; no variables or secrets yet.",
666
+ apiKeys: "Enabled; no active keys. Create one on the API keys page.",
667
+ webhooks: "Enabled; no endpoints registered.",
668
+ jobs: "Enabled; no job handlers declared (services.jobs.handlers).",
669
+ schedules: "Enabled; no active schedules.",
670
+ };
403
671
  function toNotification(item) {
404
672
  return {
405
673
  id: item.id,