@feltdb/feltkit 0.3.29 → 0.3.31

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 (185) hide show
  1. package/dist/app.d.ts +101 -11
  2. package/dist/app.js +131 -3
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +2 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest-tenancy.d.ts +2 -2
  7. package/dist/appboundry/guest-tenancy.js.map +1 -1
  8. package/dist/appboundry/guest.js +27 -2
  9. package/dist/appboundry/guest.js.map +1 -1
  10. package/dist/appboundry/host.js +3 -0
  11. package/dist/appboundry/host.js.map +1 -1
  12. package/dist/authorize.d.ts +47 -4
  13. package/dist/authorize.js +37 -0
  14. package/dist/authorize.js.map +1 -1
  15. package/dist/cli/deploy-appboundry.d.ts +1 -1
  16. package/dist/cli/deploy-appboundry.js.map +1 -1
  17. package/dist/cli/deploy.js.map +1 -1
  18. package/dist/cli/main.js +27 -1
  19. package/dist/cli/main.js.map +1 -1
  20. package/dist/cli/skills.js.map +1 -1
  21. package/dist/client/index.js.map +1 -1
  22. package/dist/dashboard/assets/index-9rMS3yBm.js +15 -0
  23. package/dist/dashboard/assets/index-DkiYTUMR.css +1 -0
  24. package/dist/dashboard/index.html +2 -2
  25. package/dist/docs.d.ts +1 -1
  26. package/dist/docs.js +4 -0
  27. package/dist/docs.js.map +1 -1
  28. package/dist/errors.js.map +1 -1
  29. package/dist/event-stage.js.map +1 -1
  30. package/dist/execution.d.ts +186 -0
  31. package/dist/execution.js +105 -0
  32. package/dist/execution.js.map +1 -0
  33. package/dist/index.d.ts +10 -2
  34. package/dist/index.js +5 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/measure/index.js.map +1 -1
  37. package/dist/platform/approvals.js.map +1 -1
  38. package/dist/platform/artifacts.js.map +1 -1
  39. package/dist/platform/changes.d.ts +54 -54
  40. package/dist/platform/changes.js.map +1 -1
  41. package/dist/platform/deployments.d.ts +32 -32
  42. package/dist/platform/exec.js.map +1 -1
  43. package/dist/platform/platform.js.map +1 -1
  44. package/dist/platform/releases.js.map +1 -1
  45. package/dist/platform/server.js.map +1 -1
  46. package/dist/platform/workspaces.js.map +1 -1
  47. package/dist/policy.d.ts +172 -0
  48. package/dist/policy.js +311 -0
  49. package/dist/policy.js.map +1 -0
  50. package/dist/react/auth.d.ts +10 -10
  51. package/dist/react/auth.js +1 -1
  52. package/dist/react/auth.js.map +1 -1
  53. package/dist/react/context.d.ts +1 -1
  54. package/dist/react/index.js.map +1 -1
  55. package/dist/runtime/accounts.js.map +1 -1
  56. package/dist/runtime/activity.d.ts +17 -1
  57. package/dist/runtime/activity.js.map +1 -1
  58. package/dist/runtime/agent.d.ts +3 -3
  59. package/dist/runtime/agent.js +9 -3
  60. package/dist/runtime/agent.js.map +1 -1
  61. package/dist/runtime/application-authority.d.ts +33 -3
  62. package/dist/runtime/application-authority.js +74 -14
  63. package/dist/runtime/application-authority.js.map +1 -1
  64. package/dist/runtime/assemble.d.ts +13 -0
  65. package/dist/runtime/assemble.js +29 -1
  66. package/dist/runtime/assemble.js.map +1 -1
  67. package/dist/runtime/audit.js.map +1 -1
  68. package/dist/runtime/authboundry.d.ts +17 -0
  69. package/dist/runtime/authboundry.js +8 -1
  70. package/dist/runtime/authboundry.js.map +1 -1
  71. package/dist/runtime/authority.d.ts +10 -0
  72. package/dist/runtime/authority.js +17 -0
  73. package/dist/runtime/authority.js.map +1 -1
  74. package/dist/runtime/backup-environment.js.map +1 -1
  75. package/dist/runtime/backup.js.map +1 -1
  76. package/dist/runtime/changes.js.map +1 -1
  77. package/dist/runtime/claims.js.map +1 -1
  78. package/dist/runtime/collections.js.map +1 -1
  79. package/dist/runtime/content.d.ts +77 -2
  80. package/dist/runtime/content.js +153 -6
  81. package/dist/runtime/content.js.map +1 -1
  82. package/dist/runtime/context.d.ts +207 -3
  83. package/dist/runtime/contract.js +16 -3
  84. package/dist/runtime/contract.js.map +1 -1
  85. package/dist/runtime/credentials.d.ts +31 -2
  86. package/dist/runtime/credentials.js +55 -3
  87. package/dist/runtime/credentials.js.map +1 -1
  88. package/dist/runtime/crypto-token.js.map +1 -1
  89. package/dist/runtime/data.d.ts +25 -0
  90. package/dist/runtime/data.js +92 -8
  91. package/dist/runtime/data.js.map +1 -1
  92. package/dist/runtime/decisions.js.map +1 -1
  93. package/dist/runtime/deployment.js.map +1 -1
  94. package/dist/runtime/execution-host.d.ts +54 -0
  95. package/dist/runtime/execution-host.js +54 -0
  96. package/dist/runtime/execution-host.js.map +1 -0
  97. package/dist/runtime/generation.js.map +1 -1
  98. package/dist/runtime/image-variants.d.ts +48 -0
  99. package/dist/runtime/image-variants.js +295 -0
  100. package/dist/runtime/image-variants.js.map +1 -0
  101. package/dist/runtime/instance.js.map +1 -1
  102. package/dist/runtime/integrations.d.ts +8 -6
  103. package/dist/runtime/integrations.js +46 -5
  104. package/dist/runtime/integrations.js.map +1 -1
  105. package/dist/runtime/invocations.d.ts +313 -0
  106. package/dist/runtime/invocations.js +493 -0
  107. package/dist/runtime/invocations.js.map +1 -0
  108. package/dist/runtime/live.d.ts +10 -7
  109. package/dist/runtime/live.js +24 -12
  110. package/dist/runtime/live.js.map +1 -1
  111. package/dist/runtime/loader.js.map +1 -1
  112. package/dist/runtime/local-authority.d.ts +92 -0
  113. package/dist/runtime/local-authority.js +396 -0
  114. package/dist/runtime/local-authority.js.map +1 -0
  115. package/dist/runtime/oauth-credentials.d.ts +40 -3
  116. package/dist/runtime/oauth-credentials.js +133 -25
  117. package/dist/runtime/oauth-credentials.js.map +1 -1
  118. package/dist/runtime/outbox.js +3 -0
  119. package/dist/runtime/outbox.js.map +1 -1
  120. package/dist/runtime/policies.d.ts +89 -0
  121. package/dist/runtime/policies.js +152 -0
  122. package/dist/runtime/policies.js.map +1 -0
  123. package/dist/runtime/projects.d.ts +1 -1
  124. package/dist/runtime/readiness.js +11 -0
  125. package/dist/runtime/readiness.js.map +1 -1
  126. package/dist/runtime/runtime.d.ts +66 -5
  127. package/dist/runtime/runtime.js +328 -18
  128. package/dist/runtime/runtime.js.map +1 -1
  129. package/dist/runtime/services-rules.d.ts +9 -0
  130. package/dist/runtime/services-rules.js +47 -1
  131. package/dist/runtime/services-rules.js.map +1 -1
  132. package/dist/runtime/services.d.ts +154 -9
  133. package/dist/runtime/services.js +343 -14
  134. package/dist/runtime/services.js.map +1 -1
  135. package/dist/runtime/sessions.js.map +1 -1
  136. package/dist/runtime/state-contract.js.map +1 -1
  137. package/dist/runtime/storage-check.js.map +1 -1
  138. package/dist/runtime/targets.d.ts +1 -1
  139. package/dist/runtime/tenancy.js.map +1 -1
  140. package/dist/runtime/transactions.d.ts +15 -0
  141. package/dist/runtime/transactions.js +5 -0
  142. package/dist/runtime/transactions.js.map +1 -1
  143. package/dist/schema.js.map +1 -1
  144. package/dist/server/admin.d.ts +72 -51
  145. package/dist/server/admin.js +125 -0
  146. package/dist/server/admin.js.map +1 -1
  147. package/dist/server/components.js.map +1 -1
  148. package/dist/server/index.js +72 -6
  149. package/dist/server/index.js.map +1 -1
  150. package/dist/server/management.js.map +1 -1
  151. package/dist/server/mcp.d.ts +59 -37
  152. package/dist/server/mcp.js +24 -1
  153. package/dist/server/mcp.js.map +1 -1
  154. package/dist/server/operators.d.ts +1 -0
  155. package/dist/server/operators.js +1 -1
  156. package/dist/server/operators.js.map +1 -1
  157. package/dist/server/ports.d.ts +7 -0
  158. package/dist/server/ports.js +17 -0
  159. package/dist/server/ports.js.map +1 -1
  160. package/dist/server/production.js.map +1 -1
  161. package/dist/server/project.js.map +1 -1
  162. package/dist/server/session-http.js.map +1 -1
  163. package/dist/server/tenancy.js.map +1 -1
  164. package/dist/surfaces.d.ts +153 -0
  165. package/dist/surfaces.js +228 -0
  166. package/dist/surfaces.js.map +1 -0
  167. package/dist/testing/index.d.ts +11 -0
  168. package/dist/testing/index.js +7 -0
  169. package/dist/testing/index.js.map +1 -1
  170. package/docs/AGENT-OPERATIONS.md +1 -1
  171. package/docs/ARCHITECTURE.md +2 -1
  172. package/docs/CONNECTIONS.md +151 -0
  173. package/docs/EXECUTION.md +271 -0
  174. package/docs/GUARANTEES.md +134 -8
  175. package/docs/INVOCATIONS.md +170 -0
  176. package/docs/POLICIES.md +121 -0
  177. package/docs/README.md +6 -2
  178. package/docs/SECURITY.md +30 -0
  179. package/docs/TRANSACTIONS.md +4 -0
  180. package/package.json +27 -19
  181. package/skills/.claude-plugin/marketplace.json +1 -1
  182. package/skills/.claude-plugin/plugin.json +1 -1
  183. package/skills/feltkit-services/SKILL.md +1 -1
  184. package/dist/dashboard/assets/index-BehzsQOa.css +0 -1
  185. package/dist/dashboard/assets/index-UuZ63NA6.js +0 -15
@@ -9,7 +9,9 @@
9
9
  */
10
10
  import { JOB_CONTEXTS_COLLECTION, jobIdOfRun } from "./job-context.js";
11
11
  import { checkTokenBytes } from "./crypto-token.js";
12
- import { evaluateAuthorize } from "../authorize.js";
12
+ import { evaluateAuthorize, evaluateOwnership } from "../authorize.js";
13
+ import { evaluatePolicies, viaCollections } from "../policy.js";
14
+ import { PolicyStore } from "./policies.js";
13
15
  import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
14
16
  import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
15
17
  import { grantsPermission } from "@appport/authorization";
@@ -31,7 +33,7 @@ import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal, toApp
31
33
  import { ChangeFeed } from "./changes.js";
32
34
  import { generationDigest } from "./generation.js";
33
35
  import { ModelHost } from "./decisions.js";
34
- import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
36
+ import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, ensureOrderedIndexes, feltdbRefusalJSON, readAll } from "./data.js";
35
37
  import { describeStorage } from "./environment.js";
36
38
  import { defaultInstanceFactory } from "./instance.js";
37
39
  import { explainServiceDenials, ServicesHost } from "./services.js";
@@ -39,6 +41,9 @@ import { applySchema, blockedHint, describePlan, MIGRATIONS_COLLECTION, planSche
39
41
  import { afterCommit, newOutboxId, OUTBOX_COLLECTION, performEffect } from "./outbox.js";
40
42
  import { claimed, isRecoverable, isSequenceConflict, outboxStore, performOutbox, rescheduled, retried, settled } from "./transactions.js";
41
43
  import { OAuthCredentials } from "./oauth-credentials.js";
44
+ import { INVOCATIONS_COLLECTION, InvocationStore } from "./invocations.js";
45
+ import { ExecutionHost } from "./execution-host.js";
46
+ import { LocalAuthorityHost } from "./local-authority.js";
42
47
  import { credentialsFor, isCustodyError } from "./credentials.js";
43
48
  import { AgentHost } from "./agent.js";
44
49
  import { FeltDbIdempotencyStore } from "./idempotency.js";
@@ -102,12 +107,19 @@ export class FeltKitRuntime {
102
107
  integrations;
103
108
  /** OAuth 2.0 grants of integrations: renewed, rotated, disconnected (runtime/oauth-credentials.ts). */
104
109
  oauth;
110
+ /** Durable invocations from registered surfaces: lifecycle, dispatch, recovery (runtime/invocations.ts). */
111
+ invocations;
112
+ /** Where work runs: the registered execution environments, the placement policy and resolver (runtime/execution-host.ts). Grants no authority. */
113
+ execution = new ExecutionHost();
114
+ /** A private AuthBoundry (authority.local), when this application asks for one. */
115
+ localAuthority;
105
116
  /** This environment's credential custody (runtime/credentials.ts). One per runtime; survives reload. */
106
117
  credentials;
107
118
  logger;
108
119
  startedAt = new Date().toISOString();
109
120
  #project;
110
121
  #authority;
122
+ #policyStore;
111
123
  #services;
112
124
  #appport;
113
125
  #resolver;
@@ -140,6 +152,8 @@ export class FeltKitRuntime {
140
152
  this.models = new ModelHost(this, { env });
141
153
  this.integrations = new IntegrationHost(this);
142
154
  this.oauth = new OAuthCredentials(this);
155
+ this.invocations = new InvocationStore(this);
156
+ this.localAuthority = new LocalAuthorityHost(this);
143
157
  try {
144
158
  this.credentials = credentialsFor({
145
159
  environment: environment.name,
@@ -183,6 +197,7 @@ export class FeltKitRuntime {
183
197
  await runtime.#ensureSchema(options.project.app, "start");
184
198
  step("schema");
185
199
  await ensureCollectionMarkers(instance.handle("feltkit.runtime"), options.project.app.collections.keys());
200
+ await runtime.#orderedIndexes(options.project.app);
186
201
  step("markers");
187
202
  await runtime.#services.check();
188
203
  step("services");
@@ -209,6 +224,7 @@ export class FeltKitRuntime {
209
224
  }
210
225
  await runtime.integrations.refreshConfiguration();
211
226
  await runtime.credentials.refresh();
227
+ await runtime.localAuthority.start();
212
228
  runtime.activity.record({
213
229
  kind: "system",
214
230
  name: "runtime.started",
@@ -350,6 +366,14 @@ export class FeltKitRuntime {
350
366
  this.logger.info(`Schema ${from} → v${applied.to.version} applied${what.length ? `: ${what.join(", ")}` : " (FeltDB now enforces it)"}`);
351
367
  }
352
368
  }
369
+ /** Indexes with a "desc" direction, declared to an embedded FeltDB (a FeltDB server has the contract's). */
370
+ async #orderedIndexes(app) {
371
+ if (this.environment.storage.kind === "remote")
372
+ return;
373
+ const declared = await ensureOrderedIndexes(this.instance.handle("feltkit.runtime"), app.collections.values());
374
+ if (declared.length)
375
+ this.logger.info(`Ordered indexes declared: ${declared.join(", ")}`);
376
+ }
353
377
  async reload(project) {
354
378
  this.#assertReady();
355
379
  if (project.app.name !== this.#project.app.name) {
@@ -359,6 +383,7 @@ export class FeltKitRuntime {
359
383
  const previous = this.#appport;
360
384
  this.#install(project);
361
385
  await this.#ensureSchema(project.app, "reload");
386
+ await this.#orderedIndexes(project.app);
362
387
  this.#agent?.define();
363
388
  await previous.close().catch(() => undefined);
364
389
  for (const listener of this.#reloadListeners)
@@ -420,6 +445,7 @@ export class FeltKitRuntime {
420
445
  const services = new ServicesHost({
421
446
  servicesDb: this.instance.handle("appport-services"),
422
447
  contentDb: this.instance.handle("feltkit.files"),
448
+ outboxDb: this.instance.handle("app"),
423
449
  applicationId: app.name,
424
450
  authority,
425
451
  config,
@@ -490,6 +516,10 @@ export class FeltKitRuntime {
490
516
  this.#resolver = new CollectionResolver(app.collections);
491
517
  this.#generation += 1;
492
518
  }
519
+ /** One AuthBoundry decision as the application's executor (a person's connection: runtime/integrations.ts). Recorded like ctx.authority's. */
520
+ decideAsExecutor(principal, requestId, request) {
521
+ return this.#applicationAuthority(principal, requestId).decide(request);
522
+ }
493
523
  /** `ctx.authority`: AuthBoundry through the shared adapter, as the application's executor; each decision recorded (never a credential). */
494
524
  #applicationAuthority(principal, requestId) {
495
525
  return applicationAuthority({
@@ -499,21 +529,88 @@ export class FeltKitRuntime {
499
529
  tenantId: this.services.scope.tenantId,
500
530
  appName: this.app.name,
501
531
  env: this.#env,
502
- record: ({ capability, executor, onBehalfOf, decision, durationMs }) => this.activity.record({
503
- kind: "auth",
504
- name: "authority.decide",
505
- via: "runtime",
506
- requestId,
507
- principal: principal ? { id: principal.id, type: principal.type, roles: principal.roles } : null,
508
- outcome: decision.allowed ? "success" : decision.outcome === "deny" ? "denied" : "error",
509
- durationMs,
510
- detail: { capability, executor, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, reason: decision.reason },
511
- }),
532
+ localUrl: () => this.localAuthority.url(),
533
+ grants: this.localAuthority.grantsFor(principal, requestId),
534
+ agents: this.localAuthority.agentsFor(principal, requestId),
535
+ agentFor: (requested) => this.localAuthority.agentDecision(principal, requested),
536
+ record: async ({ capability, executor, onBehalfOf, decision, durationMs }) => {
537
+ await this.invocations.noteDecision(requestId, { capability, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, executor: decision.executorProof });
538
+ this.activity.record({
539
+ kind: "auth",
540
+ name: "authority.decide",
541
+ via: "runtime",
542
+ requestId,
543
+ principal: principal ? { id: principal.id, type: principal.type, roles: principal.roles } : null,
544
+ outcome: decision.allowed ? "success" : decision.outcome === "deny" ? "denied" : "error",
545
+ durationMs,
546
+ detail: { capability, executor, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, reason: decision.reason, executorProof: decision.executorProof },
547
+ });
548
+ },
512
549
  });
513
550
  }
514
551
  /** `ctx.integrations`: a declared integration operation, as the caller, under the operation's own permission. */
552
+ /**
553
+ * `ctx.invocations`: the platform invocation store, as the caller. `accept` exists only in a mutation
554
+ * (`staging`): the record and its dispatch commit with the mutation's writes.
555
+ */
556
+ /** This process as a worker: what attempts it runs record as their worker (evidence, never authority). */
557
+ get workerId() {
558
+ return `${this.app.name}:${process.pid}`;
559
+ }
560
+ /** The access a function declares (`app.mutation({ access })`), or undefined when there is no such function. */
561
+ functionAccess(name) {
562
+ return this.#project.functions.get(name)?.access;
563
+ }
564
+ /** Whether `principal` holds `access` under this application's roles ("public" and "authenticated" as functions treat them). */
565
+ holds(principal, access) {
566
+ if (access === "public")
567
+ return true;
568
+ if (!principal)
569
+ return false;
570
+ if (access === "authenticated")
571
+ return true;
572
+ return grantsPermission(this.#authority.permissionsFor(principal), access);
573
+ }
574
+ #invocationsApi(principal, staging, origin = { via: "runtime", requestId: null }) {
575
+ const store = this.invocations;
576
+ return {
577
+ accept: (input) => {
578
+ if (!staging)
579
+ throw new FeltKitError("FAILED_PRECONDITION", "ctx.invocations.accept runs in a mutation: the record and its dispatch commit together.");
580
+ return store.accept({ principal, ...staging }, input);
581
+ },
582
+ get: (id) => store.get(principal, id),
583
+ list: (filter) => store.list(principal, filter),
584
+ start: (id, options) => store.start(principal, id, options, origin),
585
+ progress: (id, options) => store.progress(principal, id, options),
586
+ resume: (id, options) => store.resume(principal, id, options, origin),
587
+ transition: (id, to, options) => store.transition(principal, id, to, options),
588
+ cancel: (id, options) => store.cancel(principal, id, options),
589
+ };
590
+ }
591
+ /** Connections are a signed-in person's own. */
592
+ #connectionOwner(principal) {
593
+ if (!principal || principal.type !== "user")
594
+ throw new FeltKitError("FORBIDDEN", "Connections belong to a signed-in person, who manages only their own.");
595
+ return principal.id;
596
+ }
515
597
  #integrationInvoker(principal) {
516
598
  return {
599
+ connections: {
600
+ list: async () => this.oauth.connections(this.#connectionOwner(principal)),
601
+ connect: async (integration) => {
602
+ this.#connectionOwner(principal);
603
+ const i = this.app.integrations.get(integration);
604
+ if (!i || !OAuthCredentials.personal(i))
605
+ throw new FeltKitError("NOT_FOUND", `${integration} is not connected per person (credential.owner: "person").`);
606
+ const { url, expiresAt } = await this.oauth.connect(integration, principal, "function");
607
+ return { url, expiresAt };
608
+ },
609
+ disconnect: async (integration) => {
610
+ this.#connectionOwner(principal);
611
+ return this.oauth.disconnect(integration, principal);
612
+ },
613
+ },
517
614
  invoke: async (capability, input, options = {}) => {
518
615
  const found = this.integrations.operationFor(capability);
519
616
  if (!found)
@@ -529,7 +626,9 @@ export class FeltKitRuntime {
529
626
  if (!parsed.ok) {
530
627
  throw new FeltKitError("INVALID_ARGUMENT", `Invalid input for ${capability}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } });
531
628
  }
532
- return this.integrations.invoke(capability, parsed.value, { principal, via: "function", ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) });
629
+ const requestId = `req_${randomUUID()}`;
630
+ await this.#authorizeIntegration(capability, found.op, parsed.value, principal, "function", requestId);
631
+ return this.integrations.invoke(capability, parsed.value, { principal, via: "function", requestId, ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), ...(options.onBehalfOf !== undefined ? { onBehalfOf: options.onBehalfOf } : {}) });
533
632
  },
534
633
  };
535
634
  }
@@ -550,6 +649,7 @@ export class FeltKitRuntime {
550
649
  const principal = fromAppPortPrincipal(context.principal ?? context.session?.principal);
551
650
  this.#dispatched.add(context.requestId);
552
651
  try {
652
+ await this.#authorizeIntegration(op.capability, op, input, principal, String(context.transport ?? "appport"), context.requestId);
553
653
  return await this.integrations.invoke(op.capability, input, {
554
654
  principal,
555
655
  requestId: context.requestId,
@@ -776,6 +876,8 @@ export class FeltKitRuntime {
776
876
  async #performOutbox(record, services, principal, requestId) {
777
877
  if (record.effect.service === "agent")
778
878
  return this.#runAgent(record.id);
879
+ if (record.effect.service === "files")
880
+ return this.#services.releaseFile(record.id);
779
881
  return performOutbox(outboxStore(this.instance.handle("app")), record.id, (claim, complete) => {
780
882
  const effect = claim.effect;
781
883
  // A job or webhook event is created in the transaction that records it done; a notification is sent directly.
@@ -806,6 +908,13 @@ export class FeltKitRuntime {
806
908
  performed += 1;
807
909
  continue;
808
910
  }
911
+ // A byte release needs no caller: it reads as FeltKit's file-release principal, and releases only
912
+ // bytes whose file is already deleted (the caller's decision, made when the metadata was deleted).
913
+ if (record.effect.service === "files") {
914
+ if ((await this.#services.releaseFile(record.id, () => now)) === "done")
915
+ performed += 1;
916
+ continue;
917
+ }
809
918
  // In the workspace the caller worked in, through the live membership only (no membership: not performed).
810
919
  const account = await this.#resolveDurable(record.principalId);
811
920
  const inTenant = account && record.tenantId ? await this.withTenant(account, record.tenantId) : account;
@@ -910,6 +1019,23 @@ export class FeltKitRuntime {
910
1019
  .sort((a, b) => b.createdAt - a.createdAt)
911
1020
  .slice(0, filter.limit ?? 100);
912
1021
  }
1022
+ /**
1023
+ * Stored file bytes no live file record references (ServicesHost.orphanedContent). With
1024
+ * `release`, each is reclaimed as a recorded byte release (outbox effect `files.release`), kept
1025
+ * as evidence like any other: `feltkit outbox reclaim-files [--release]`.
1026
+ */
1027
+ async fileOrphans(options = {}) {
1028
+ this.#assertReady();
1029
+ if (!this.#services.files)
1030
+ return { orphans: [], released: [] };
1031
+ const orphans = await this.#services.orphanedContent();
1032
+ if (!options.release)
1033
+ return { orphans, released: [] };
1034
+ const ids = await this.#services.reclaimOrphanedContent(options.release.by);
1035
+ const outbox = this.instance.handle("app").collection(OUTBOX_COLLECTION);
1036
+ const released = await Promise.all(ids.map(async (id) => { const { __version: _v, ...r } = (await outbox.get(id)); return r; }));
1037
+ return { orphans, released };
1038
+ }
913
1039
  /**
914
1040
  * An operator's retry of a failed after-commit effect: back to pending (attempts and last error
915
1041
  * kept), then performed now as its caller, or by the worker if that caller cannot be resolved.
@@ -928,8 +1054,8 @@ export class FeltKitRuntime {
928
1054
  catch {
929
1055
  throw new FeltKitError("CONFLICT", `After-commit effect ${id} changed while it was being retried. Nothing was changed; read it again.`);
930
1056
  }
931
- if (record.effect.service === "agent") {
932
- await this.#runAgent(id);
1057
+ if (record.effect.service === "agent" || record.effect.service === "files") {
1058
+ await (record.effect.service === "agent" ? this.#runAgent(id) : this.#services.releaseFile(id));
933
1059
  const { __version: _a, ...after } = (await outbox.get(id));
934
1060
  return after;
935
1061
  }
@@ -1027,11 +1153,15 @@ export class FeltKitRuntime {
1027
1153
  if (this.#ticking)
1028
1154
  return this.#ticking;
1029
1155
  const run = Promise.all([
1030
- this.#services.tick(`${this.app.name}:${process.pid}`),
1156
+ this.#services.tick(this.workerId),
1031
1157
  this.recoverOutbox().catch((error) => {
1032
1158
  this.logger.warn(`after-commit recovery: ${error.message}`);
1033
1159
  return 0;
1034
1160
  }),
1161
+ this.invocations.recover().catch((error) => {
1162
+ this.logger.warn(`invocation recovery: ${error.message}`);
1163
+ return null;
1164
+ }),
1035
1165
  ]).then(([tick]) => tick).catch((error) => {
1036
1166
  this.logger.warn(`services worker: ${error.message}`);
1037
1167
  return { jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } };
@@ -1294,12 +1424,16 @@ export class FeltKitRuntime {
1294
1424
  ...(options.appportDecisionId ? { appportDecisionId: options.appportDecisionId } : {}),
1295
1425
  };
1296
1426
  if (!decision.allowed) {
1427
+ // Durable evidence for a signed-in caller's refusal (an anonymous caller refused before sign-in is in the activity log only).
1428
+ if (principal)
1429
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, ...(principal.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}), outcome: "denied", layer: "role", reason: decision.reason ?? `requires ${decision.required}`, argKeys: argKeys(rawArgs) ?? [] });
1297
1430
  return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
1298
1431
  }
1299
1432
  // The approval requirement, at the execution boundary every interface goes through (/api,
1300
1433
  // AppPort, MCP, jobs, decisions): permission alone is not enough for a non-person caller.
1301
1434
  const approvalRefusal = this.#approvalRefusal(name, fn, principal);
1302
1435
  if (approvalRefusal) {
1436
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null, outcome: "denied", layer: "approval", reason: approvalRefusal, argKeys: argKeys(rawArgs) ?? [] });
1303
1437
  return failure(new FeltKitError("FORBIDDEN", approvalRefusal, { details: { approval: "required" }, hint: "Ask a person to run it, or propose it and wait for their approval." }), { authority: { ...authorityRecord, allowed: false, reason: "approval required" }, argKeys: argKeys(rawArgs) });
1304
1438
  }
1305
1439
  const approvedAction = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
@@ -1397,7 +1531,8 @@ export class FeltKitRuntime {
1397
1531
  };
1398
1532
  // Tenant-scoped collections see only the caller's tenant (the session's, never the request's).
1399
1533
  const scoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(db);
1400
- const ctx = fn.kind === "mutation" ? { ...shared, db: scoped, agent, events, afterCommit: effects, unsafe: Object.freeze({ feltdb: escapeHatch(this.instance.handle("app.unsafe"), this.app.collections) }), ...(options.agentRun ? { trigger: options.agentRun.trigger } : {}) } : { ...shared, db: scoped };
1534
+ const invocations = this.#invocationsApi(principal, fn.kind === "mutation" && db instanceof Writer ? { stage: (record) => db.stageSystem(INVOCATIONS_COLLECTION, record), staged: () => db.staged.filter((r) => r.collection === INVOCATIONS_COLLECTION).map((r) => r.value.id), effects } : null, { via: String(options.via ?? "function"), requestId });
1535
+ const ctx = fn.kind === "mutation" ? { ...shared, invocations, db: scoped, agent, events, afterCommit: effects, unsafe: Object.freeze({ feltdb: escapeHatch(this.instance.handle("app.unsafe"), this.app.collections) }), ...(options.agentRun ? { trigger: options.agentRun.trigger } : {}) } : { ...shared, db: scoped, invocations: { get: invocations.get, list: invocations.list } };
1401
1536
  try {
1402
1537
  // feltkit({ authorize }): after roles and validation, with this call's own reader, so its
1403
1538
  // reads are fenced at commit (mutations) and tracked for live queries (queries).
@@ -1590,6 +1725,7 @@ export class FeltKitRuntime {
1590
1725
  },
1591
1726
  authority: this.#applicationAuthority(principal, requestId),
1592
1727
  integrations: this.#integrationInvoker(principal),
1728
+ invocations: this.#invocationsApi(principal, null, { via: String(options.via ?? "function"), requestId }),
1593
1729
  agent: {
1594
1730
  catalog: async () => (await agent.tools(signedIn())).map((t) => ({
1595
1731
  name: t.name,
@@ -1637,13 +1773,181 @@ export class FeltKitRuntime {
1637
1773
  return failure(error, { authority: authorityRecord, argKeys: Object.keys(args) });
1638
1774
  }
1639
1775
  }
1640
- async #authorizeResource(name, fn, args, principal, options, requestId, db, record) {
1776
+ /** Managed policies and decision evidence (runtime/policies.ts), in the application's FeltDB instance. */
1777
+ get policyStore() {
1778
+ this.#policyStore ??= new PolicyStore({
1779
+ db: () => this.instance.handle("feltkit.policies"),
1780
+ code: () => this.#project?.policies ?? [],
1781
+ validate: (rule) => {
1782
+ for (const fn of rule.functions) {
1783
+ // A function, or (managed policies only, by capability name) an integration operation.
1784
+ if (!this.#project?.functions.has(fn) && !(rule.source === "managed" && this.integrations.operationFor(fn))) {
1785
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names ${fn}, which this application does not define.`);
1786
+ }
1787
+ }
1788
+ for (const via of (rule.when ?? []).flatMap(viaCollections)) {
1789
+ if (typeof via !== "string" || !this.app.collections.has(via))
1790
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} reads owner.via from ${typeof via === "string" ? via : via.name}, which this application does not declare.`);
1791
+ }
1792
+ if (rule.resource && !this.app.collections.has(rule.resource.collection)) {
1793
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names collection ${rule.resource.collection}, which this application does not declare.`);
1794
+ }
1795
+ },
1796
+ });
1797
+ return this.#policyStore;
1798
+ }
1799
+ /**
1800
+ * Evaluate the policies for a call without running it (no handler, no writes, no evidence): what a
1801
+ * policy permits, for whom, and why. Reads the real records the policy would read. A delegation
1802
+ * condition asks AuthBoundry, as the call would.
1803
+ */
1804
+ async simulatePolicy(input) {
1805
+ if (!this.#project?.functions.has(input.function) && !this.integrations.operationFor(input.function))
1806
+ throw new FeltKitError("FUNCTION_NOT_FOUND", `No function or integration operation named "${input.function}".`);
1807
+ const requestId = input.requestId ?? `sim_${randomUUID()}`;
1808
+ const db = this.#readerFor(input.principal);
1809
+ return evaluatePolicies(await this.policyStore.current(), this.#policyRequest(input.function, input.principal, input.args ?? {}, db, requestId));
1810
+ }
1811
+ /** A read-only view of the application's data for a decision made outside a function's own transaction. */
1812
+ #readerFor(principal) {
1813
+ const reader = new Reader(this.instance.handle("app"), this.#resolver);
1814
+ return hasTenantCollections(this.app.collections.values()) ? scopeToTenant(reader, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(reader);
1815
+ }
1816
+ /**
1817
+ * An integration operation's authorization beyond its role `access`, on every path that reaches
1818
+ * it (its AppPort/MCP capability, `ctx.integrations.invoke`, verification probes): the managed
1819
+ * policies that name its capability, then `feltkit({ authorize })` with `kind: "integration"`.
1820
+ * Refusals are durable evidence, as for functions.
1821
+ */
1822
+ async #authorizeIntegration(capability, op, input, principal, via, requestId) {
1641
1823
  const hook = this.app.options.authorize;
1824
+ const set = await this.policyStore.current();
1825
+ const governed = set.rules.some((rule) => rule.functions.includes(capability));
1826
+ if (!hook && !governed)
1827
+ return;
1828
+ const db = this.#readerFor(principal);
1829
+ const evidence = (outcome, layer, reason, policy) => ({
1830
+ function: capability,
1831
+ via,
1832
+ requestId,
1833
+ principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null,
1834
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
1835
+ outcome,
1836
+ layer,
1837
+ reason,
1838
+ ...(policy ? { policyVersion: policy.policyVersion, matched: policy.matched, unmet: policy.unmet, delegations: policy.delegations } : {}),
1839
+ argKeys: Object.keys(input).sort(),
1840
+ });
1841
+ let policy;
1842
+ if (governed) {
1843
+ policy = await evaluatePolicies(set, this.#policyRequest(capability, principal, input, db, requestId));
1844
+ if (!policy.allowed) {
1845
+ await this.#recordDecision(evidence("denied", "policy", policy.reason, policy));
1846
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", policy.reason, { details: { policy: "denied", matched: policy.matched, unmet: policy.unmet } });
1847
+ }
1848
+ if (policy.durable)
1849
+ await this.#recordDecision(evidence("allowed", "policy", policy.reason, policy));
1850
+ }
1642
1851
  if (!hook)
1643
1852
  return;
1644
1853
  try {
1854
+ await evaluateAuthorize(hook, {
1855
+ function: capability,
1856
+ kind: "integration",
1857
+ access: op.access,
1858
+ capability: { name: capability, version: 1 },
1859
+ principal,
1860
+ args: input,
1861
+ transport: via,
1862
+ requestId,
1863
+ db,
1864
+ ...(policy?.governed ? { policy: { allowed: policy.allowed, matched: policy.matched, version: policy.policyVersion } } : {}),
1865
+ });
1866
+ }
1867
+ catch (error) {
1868
+ if (isFeltKitError(error) && (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "NOT_FOUND"))
1869
+ await this.#recordDecision(evidence("denied", "authorize", error.message));
1870
+ throw error;
1871
+ }
1872
+ }
1873
+ #policyRequest(name, principal, args, db, requestId) {
1874
+ return {
1875
+ function: name,
1876
+ principal,
1877
+ args,
1878
+ db,
1879
+ collection: (collection) => this.app.collections.get(collection),
1880
+ delegate: async ({ capability, onBehalfOf }) => {
1881
+ // A bare id in a record or argument names a person (AuthBoundry's "user:<id>").
1882
+ const person = onBehalfOf.includes(":") ? onBehalfOf : `user:${onBehalfOf}`;
1883
+ const decision = await this.#applicationAuthority(principal, requestId).decide({ capability, onBehalfOf: person });
1884
+ return { allowed: decision.allowed, decisionId: decision.decisionId, delegationId: decision.delegationId, ...(decision.reason ? { reason: decision.reason } : {}) };
1885
+ },
1886
+ };
1887
+ }
1888
+ /**
1889
+ * Durable decision evidence. A refusal is recorded before the caller sees it; if the record cannot
1890
+ * be written the refusal still stands (it is logged). An allow that requires durable evidence is
1891
+ * refused when its record cannot be written: the effect never runs without its evidence.
1892
+ */
1893
+ async #recordDecision(entry) {
1894
+ try {
1895
+ await this.policyStore.record(entry);
1896
+ }
1897
+ catch (error) {
1898
+ if (entry.outcome === "allowed")
1899
+ throw new FeltKitError("UNAVAILABLE", `The decision for ${entry.function} could not be recorded, so it does not run: ${error.message}`);
1900
+ this.logger.error(`Decision evidence for a refusal of ${entry.function} could not be recorded: ${error.message}`);
1901
+ }
1902
+ }
1903
+ async #authorizeResource(name, fn, args, principal, options, requestId, db, record) {
1904
+ const hook = this.app.options.authorize;
1905
+ const set = await this.policyStore.current();
1906
+ const governed = set.rules.some((rule) => rule.functions.includes(name));
1907
+ if (!hook && !fn.owner && !governed)
1908
+ return;
1909
+ const evidence = (outcome, layer, reason, policy) => ({
1910
+ function: name,
1911
+ via: String(options.via),
1912
+ requestId,
1913
+ principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null,
1914
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
1915
+ outcome,
1916
+ layer,
1917
+ reason,
1918
+ ...(policy ? { policyVersion: policy.policyVersion, matched: policy.matched, unmet: policy.unmet, delegations: policy.delegations } : {}),
1919
+ argKeys: Object.keys(args).sort(),
1920
+ });
1921
+ let layer = "owner";
1922
+ let recorded = false;
1923
+ try {
1924
+ // The function's declared ownership first (fails closed), then the policies, then the hook.
1925
+ const owned = await evaluateOwnership(fn, { function: name, principal, args, db });
1926
+ if (owned)
1927
+ record.resource = owned;
1928
+ let policy;
1929
+ if (governed) {
1930
+ layer = "policy";
1931
+ policy = await evaluatePolicies(set, this.#policyRequest(name, principal, args, db, requestId));
1932
+ record.policy = { version: policy.policyVersion, matched: [...policy.matched], ...(policy.unmet.length ? { unmet: [...policy.unmet] } : {}), ...(policy.delegations.length ? { delegations: [...policy.delegations] } : {}) };
1933
+ if (!policy.allowed) {
1934
+ await this.#recordDecision(evidence("denied", "policy", policy.reason, policy));
1935
+ recorded = true;
1936
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", policy.reason, { details: { policy: "denied", matched: policy.matched, unmet: policy.unmet } });
1937
+ }
1938
+ if (policy.governed)
1939
+ record.resource = { allowed: true, reason: policy.reason };
1940
+ if (policy.durable)
1941
+ await this.#recordDecision(evidence("allowed", "policy", policy.reason, policy));
1942
+ }
1943
+ if (!hook)
1944
+ return;
1945
+ layer = "authorize";
1946
+ const run = options.agentRun?.trigger;
1947
+ const approved = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
1645
1948
  const decision = await evaluateAuthorize(hook, {
1646
1949
  function: name,
1950
+ definition: fn,
1647
1951
  kind: fn.kind,
1648
1952
  access: fn.access,
1649
1953
  ...(options.capability ? { capability: { name: options.capability.name, version: options.capability.version ?? 1 } } : {}),
@@ -1652,6 +1956,9 @@ export class FeltKitRuntime {
1652
1956
  transport: options.via,
1653
1957
  requestId,
1654
1958
  db,
1959
+ ...(policy?.governed ? { policy: { allowed: policy.allowed, matched: policy.matched, version: policy.policyVersion } } : {}),
1960
+ ...(run ? { agentRun: { agent: run.agent, triggeredBy: run.by.principalId } } : {}),
1961
+ ...(approved ? { approval: { taskId: approved.taskId, actionId: approved.actionId, approvedBy: approved.approvedBy } } : {}),
1655
1962
  });
1656
1963
  if (decision)
1657
1964
  record.resource = decision;
@@ -1661,6 +1968,8 @@ export class FeltKitRuntime {
1661
1968
  if (isFeltKitError(error) && (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "NOT_FOUND")) {
1662
1969
  record.allowed = false;
1663
1970
  record.resource = { allowed: false, reason: error.message };
1971
+ if (!recorded)
1972
+ await this.#recordDecision(evidence("denied", layer, error.message));
1664
1973
  }
1665
1974
  throw error;
1666
1975
  }
@@ -1754,6 +2063,7 @@ export class FeltKitRuntime {
1754
2063
  await this.settleAgents();
1755
2064
  await this.#appport?.close().catch(() => undefined);
1756
2065
  await this.models.close();
2066
+ await this.localAuthority.close().catch(() => undefined);
1757
2067
  await this.activity.flush();
1758
2068
  await this.instance.close();
1759
2069
  this.#state = "closed";