@feltdb/feltkit 0.3.17 → 0.3.19

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 (188) hide show
  1. package/dist/app.d.ts +246 -13
  2. package/dist/app.js +215 -6
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.d.ts +70 -0
  5. package/dist/appboundry/build.js +62 -2
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/guest.js +57 -3
  8. package/dist/appboundry/guest.js.map +1 -1
  9. package/dist/appboundry/host.js +7 -0
  10. package/dist/appboundry/host.js.map +1 -1
  11. package/dist/authorize.js +1 -0
  12. package/dist/authorize.js.map +1 -1
  13. package/dist/cli/compose.d.ts +31 -0
  14. package/dist/cli/compose.js +274 -0
  15. package/dist/cli/compose.js.map +1 -0
  16. package/dist/cli/create.d.ts +201 -0
  17. package/dist/cli/create.js +1139 -0
  18. package/dist/cli/create.js.map +1 -0
  19. package/dist/cli/deploy-appboundry-self-hosted.d.ts +2 -0
  20. package/dist/cli/deploy-appboundry-self-hosted.js +1 -1
  21. package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
  22. package/dist/cli/deploy-appboundry.js +3 -0
  23. package/dist/cli/deploy-appboundry.js.map +1 -1
  24. package/dist/cli/deploy.d.ts +1 -0
  25. package/dist/cli/deploy.js +66 -6
  26. package/dist/cli/deploy.js.map +1 -1
  27. package/dist/cli/domain.d.ts +174 -0
  28. package/dist/cli/domain.js +1119 -0
  29. package/dist/cli/domain.js.map +1 -0
  30. package/dist/cli/main.d.ts +2 -0
  31. package/dist/cli/main.js +141 -7
  32. package/dist/cli/main.js.map +1 -1
  33. package/dist/cli/shell.d.ts +7 -0
  34. package/dist/cli/shell.js +59 -0
  35. package/dist/cli/shell.js.map +1 -0
  36. package/dist/client/index.d.ts +192 -5
  37. package/dist/client/index.js +301 -28
  38. package/dist/client/index.js.map +1 -1
  39. package/dist/component.d.ts +174 -0
  40. package/dist/component.js +77 -0
  41. package/dist/component.js.map +1 -0
  42. package/dist/composition/catalog.d.ts +3 -0
  43. package/dist/composition/catalog.js +217 -0
  44. package/dist/composition/catalog.js.map +1 -0
  45. package/dist/composition/contract.d.ts +165 -0
  46. package/dist/composition/contract.js +12 -0
  47. package/dist/composition/contract.js.map +1 -0
  48. package/dist/composition/execute.d.ts +110 -0
  49. package/dist/composition/execute.js +350 -0
  50. package/dist/composition/execute.js.map +1 -0
  51. package/dist/composition/generate.d.ts +105 -0
  52. package/dist/composition/generate.js +274 -0
  53. package/dist/composition/generate.js.map +1 -0
  54. package/dist/composition/plan.d.ts +131 -0
  55. package/dist/composition/plan.js +558 -0
  56. package/dist/composition/plan.js.map +1 -0
  57. package/dist/composition/profiles.d.ts +20 -0
  58. package/dist/composition/profiles.js +81 -0
  59. package/dist/composition/profiles.js.map +1 -0
  60. package/dist/composition/reconcile.d.ts +153 -0
  61. package/dist/composition/reconcile.js +282 -0
  62. package/dist/composition/reconcile.js.map +1 -0
  63. package/dist/composition/recover.d.ts +89 -0
  64. package/dist/composition/recover.js +407 -0
  65. package/dist/composition/recover.js.map +1 -0
  66. package/dist/composition/resolve.d.ts +2 -0
  67. package/dist/composition/resolve.js +208 -0
  68. package/dist/composition/resolve.js.map +1 -0
  69. package/dist/dashboard/assets/{index-DnIOVGF-.js → index-BrC1AtZ1.js} +5 -5
  70. package/dist/dashboard/index.html +1 -1
  71. package/dist/docs.d.ts +1 -1
  72. package/dist/docs.js +2 -0
  73. package/dist/docs.js.map +1 -1
  74. package/dist/index.d.ts +7 -3
  75. package/dist/index.js +2 -0
  76. package/dist/index.js.map +1 -1
  77. package/dist/react/auth.d.ts +131 -0
  78. package/dist/react/auth.js +830 -0
  79. package/dist/react/auth.js.map +1 -0
  80. package/dist/react/context.d.ts +8 -0
  81. package/dist/react/context.js +14 -0
  82. package/dist/react/context.js.map +1 -0
  83. package/dist/react/index.d.ts +3 -18
  84. package/dist/react/index.js +5 -13
  85. package/dist/react/index.js.map +1 -1
  86. package/dist/runtime/accounts.d.ts +33 -2
  87. package/dist/runtime/accounts.js +167 -27
  88. package/dist/runtime/accounts.js.map +1 -1
  89. package/dist/runtime/activity.d.ts +8 -1
  90. package/dist/runtime/activity.js.map +1 -1
  91. package/dist/runtime/audit.d.ts +43 -0
  92. package/dist/runtime/audit.js +52 -0
  93. package/dist/runtime/audit.js.map +1 -0
  94. package/dist/runtime/authority.d.ts +8 -1
  95. package/dist/runtime/authority.js +11 -2
  96. package/dist/runtime/authority.js.map +1 -1
  97. package/dist/runtime/challenges.d.ts +51 -0
  98. package/dist/runtime/challenges.js +121 -0
  99. package/dist/runtime/challenges.js.map +1 -0
  100. package/dist/runtime/changes.d.ts +22 -0
  101. package/dist/runtime/changes.js +51 -3
  102. package/dist/runtime/changes.js.map +1 -1
  103. package/dist/runtime/claims.d.ts +76 -0
  104. package/dist/runtime/claims.js +100 -0
  105. package/dist/runtime/claims.js.map +1 -0
  106. package/dist/runtime/context.d.ts +47 -5
  107. package/dist/runtime/contract.js +17 -3
  108. package/dist/runtime/contract.js.map +1 -1
  109. package/dist/runtime/data.d.ts +50 -4
  110. package/dist/runtime/data.js +113 -35
  111. package/dist/runtime/data.js.map +1 -1
  112. package/dist/runtime/escape-hatch.d.ts +37 -0
  113. package/dist/runtime/escape-hatch.js +76 -0
  114. package/dist/runtime/escape-hatch.js.map +1 -0
  115. package/dist/runtime/instance.js +2 -1
  116. package/dist/runtime/instance.js.map +1 -1
  117. package/dist/runtime/live.d.ts +48 -0
  118. package/dist/runtime/live.js +154 -0
  119. package/dist/runtime/live.js.map +1 -0
  120. package/dist/runtime/outbox.js +6 -0
  121. package/dist/runtime/outbox.js.map +1 -1
  122. package/dist/runtime/runtime.d.ts +103 -5
  123. package/dist/runtime/runtime.js +411 -41
  124. package/dist/runtime/runtime.js.map +1 -1
  125. package/dist/runtime/search.d.ts +54 -0
  126. package/dist/runtime/search.js +66 -0
  127. package/dist/runtime/search.js.map +1 -0
  128. package/dist/runtime/services-rules.d.ts +12 -0
  129. package/dist/runtime/services-rules.js +8 -0
  130. package/dist/runtime/services-rules.js.map +1 -0
  131. package/dist/runtime/services.js +5 -3
  132. package/dist/runtime/services.js.map +1 -1
  133. package/dist/runtime/sessions.d.ts +16 -2
  134. package/dist/runtime/sessions.js +40 -4
  135. package/dist/runtime/sessions.js.map +1 -1
  136. package/dist/runtime/tenancy.d.ts +198 -0
  137. package/dist/runtime/tenancy.js +397 -0
  138. package/dist/runtime/tenancy.js.map +1 -0
  139. package/dist/runtime/tenant-scope.d.ts +9 -0
  140. package/dist/runtime/tenant-scope.js +127 -0
  141. package/dist/runtime/tenant-scope.js.map +1 -0
  142. package/dist/runtime/transactions.d.ts +83 -3
  143. package/dist/runtime/transactions.js +53 -11
  144. package/dist/runtime/transactions.js.map +1 -1
  145. package/dist/server/admin.js +52 -0
  146. package/dist/server/admin.js.map +1 -1
  147. package/dist/server/components.d.ts +44 -0
  148. package/dist/server/components.js +212 -0
  149. package/dist/server/components.js.map +1 -0
  150. package/dist/server/index.d.ts +4 -1
  151. package/dist/server/index.js +324 -63
  152. package/dist/server/index.js.map +1 -1
  153. package/dist/server/mcp.js +6 -3
  154. package/dist/server/mcp.js.map +1 -1
  155. package/dist/server/project.d.ts +27 -0
  156. package/dist/server/project.js +63 -0
  157. package/dist/server/project.js.map +1 -1
  158. package/dist/server/public.d.ts +2 -0
  159. package/dist/server/public.js +2 -0
  160. package/dist/server/public.js.map +1 -1
  161. package/dist/server/session-http.d.ts +48 -0
  162. package/dist/server/session-http.js +116 -0
  163. package/dist/server/session-http.js.map +1 -0
  164. package/dist/server/tenancy.d.ts +40 -0
  165. package/dist/server/tenancy.js +191 -0
  166. package/dist/server/tenancy.js.map +1 -0
  167. package/dist/testing/index.d.ts +19 -0
  168. package/dist/testing/index.js +22 -2
  169. package/dist/testing/index.js.map +1 -1
  170. package/docs/AGENT-OPERATIONS.md +1 -0
  171. package/docs/APPBOUNDRY.md +11 -1
  172. package/docs/ARCHITECTURE.md +5 -3
  173. package/docs/AUTH.md +267 -0
  174. package/docs/COMPONENTS.md +91 -0
  175. package/docs/GUARANTEES.md +74 -7
  176. package/docs/README.md +4 -2
  177. package/docs/RESOLVER.md +4 -2
  178. package/docs/SECURITY.md +5 -4
  179. package/docs/TRANSACTIONS.md +98 -1
  180. package/docs/UPSTREAM-GAPS.md +2 -0
  181. package/package.json +15 -12
  182. package/skills/.claude-plugin/marketplace.json +1 -1
  183. package/skills/.claude-plugin/plugin.json +1 -1
  184. package/skills/feltkit-data/SKILL.md +6 -0
  185. package/skills/feltkit-services/SKILL.md +1 -1
  186. package/dist/runtime/account-links.d.ts +0 -19
  187. package/dist/runtime/account-links.js +0 -45
  188. package/dist/runtime/account-links.js.map +0 -1
@@ -17,6 +17,7 @@ import { performance } from "node:perf_hooks";
17
17
  import { createHash, randomBytes, randomUUID } from "node:crypto";
18
18
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
19
19
  import { dirname, join } from "node:path";
20
+ import { AGENT_MAX_BACKOFF_MS } from "../app.js";
20
21
  import { IntegrationHost, integrationDescriptor } from "./integrations.js";
21
22
  import { verifyStorage } from "./storage-check.js";
22
23
  import { assertNotPartiallyRestored, writeBackup } from "./backup.js";
@@ -27,22 +28,26 @@ import { ActivityLog, errorSummary } from "./activity.js";
27
28
  import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal } from "./authority.js";
28
29
  import { ChangeFeed } from "./changes.js";
29
30
  import { ModelHost } from "./decisions.js";
30
- import { CollectionResolver, Reader, Writer, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
31
+ import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
31
32
  import { describeStorage } from "./environment.js";
32
33
  import { defaultInstanceFactory } from "./instance.js";
33
34
  import { explainServiceDenials, ServicesHost } from "./services.js";
34
35
  import { applySchema, blockedHint, describePlan, MIGRATIONS_COLLECTION, planSchema, publicPlan } from "./state-contract.js";
35
36
  import { afterCommit, newOutboxId, OUTBOX_COLLECTION, performEffect } from "./outbox.js";
36
- import { isRecoverable, isSequenceConflict, outboxStore, performOutbox, retried, settled } from "./transactions.js";
37
+ import { claimed, isRecoverable, isSequenceConflict, outboxStore, performOutbox, rescheduled, retried, settled } from "./transactions.js";
37
38
  import { credentialsFor, isCustodyError } from "./credentials.js";
38
39
  import { AgentHost } from "./agent.js";
39
40
  import { FeltDbIdempotencyStore } from "./idempotency.js";
40
41
  import { capabilityDefinition } from "./capabilities.js";
41
42
  import { FeltDbSessionStore } from "./sessions.js";
43
+ import { escapeHatch } from "./escape-hatch.js";
44
+ import { AUDIT_COLLECTION, auditRecord, readAudit } from "./audit.js";
42
45
  import { AccountStore } from "./accounts.js";
43
46
  import * as appportServices from "@appport/services";
44
47
  import { accountMail } from "./mail.js";
45
- import { signLink } from "./account-links.js";
48
+ import { ChallengeStore } from "./challenges.js";
49
+ import { MEMBERSHIPS_COLLECTION, TenancyStore } from "./tenancy.js";
50
+ import { hasTenantCollections, scopeToTenant } from "./tenant-scope.js";
46
51
  const consoleLogger = {
47
52
  info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
48
53
  warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
@@ -65,6 +70,10 @@ export class FeltKitRuntime {
65
70
  sessions;
66
71
  /** Built-in accounts (`auth.accounts`), or null when the app does not use them. */
67
72
  accounts = null;
73
+ /** Account e-mail challenges (verify, reset, magic link, address change). Null without accounts. */
74
+ challenges = null;
75
+ /** Tenants, memberships and invitations (`auth.tenant`). Null without tenancy. */
76
+ tenancy = null;
68
77
  /** Account e-mail (auth.accounts.email) through Mailerport, or null (none declared, or production without MAILPORT_URL). */
69
78
  mail = null;
70
79
  /** This server's own URL, set by the HTTP server: development's fallback for links. */
@@ -88,6 +97,8 @@ export class FeltKitRuntime {
88
97
  #resolver;
89
98
  #state = "starting";
90
99
  #inflight = new Set();
100
+ /** Application agent runs started after a commit (app.agent), awaited by close() and settleAgents(). */
101
+ #agentRuns = new Set();
91
102
  /** Set while backup() reads the state: calls and the services worker wait for it. */
92
103
  #paused = null;
93
104
  #dispatched = new Set();
@@ -338,6 +349,9 @@ export class FeltKitRuntime {
338
349
  const authority = new Authority(app.name, app.options.roles ?? {});
339
350
  const accounts = app.options.auth?.accounts;
340
351
  this.accounts = accounts ? new AccountStore(this.instance.handle("feltkit.accounts"), accounts) : null;
352
+ this.challenges = accounts ? new ChallengeStore(this.instance.handle("feltkit.accounts"), () => this.authSecret()) : null;
353
+ const tenant = app.options.auth?.tenant;
354
+ this.tenancy = tenant ? new TenancyStore(this.instance.handle("feltkit.tenancy"), tenant, () => this.authSecret()) : null;
341
355
  this.mail = accounts?.email ? accountMail({ env: this.#env, development: !this.environment.production, from: accounts.email.from, identity: accounts.email.identity ?? "auth", logger: this.logger }) : null;
342
356
  const config = app.options.services ?? {};
343
357
  const store = this.accounts;
@@ -347,15 +361,38 @@ export class FeltKitRuntime {
347
361
  new (emailChannelClass())({
348
362
  transport: mail.transport,
349
363
  identity: accounts.email.identity ?? "auth",
350
- address: async (n) => (await store.get(n.recipient))?.email ?? null,
364
+ // An account's address, or (magic link for a new address, address change) the address itself.
365
+ address: async (n) => (n.recipient.startsWith("email:") ? n.recipient.slice(6) : (await store.get(n.recipient))?.email ?? null),
366
+ // Rendered when delivered, from the live challenge: the link and code are never stored.
351
367
  render: async (n) => {
352
- const purpose = n.data?.purpose;
353
- if (purpose !== "verify" && purpose !== "reset")
354
- return null;
355
- const bind = await store.linkBinding(n.recipient, purpose);
356
- if (bind === null)
368
+ // A workspace invitation (auth.tenant): rendered from the live invitation, so a
369
+ // withdrawn or accepted one sends nothing, and its token is never stored.
370
+ if (typeof n.data?.invitation === "string") {
371
+ const live = this.tenancy ? await this.tenancy.tokenFor(n.data.invitation) : null;
372
+ if (!live)
373
+ return null;
374
+ const input = {
375
+ app: app.options.description ?? app.name,
376
+ link: this.invitationLink(live.token),
377
+ tenant: live.tenantName,
378
+ role: live.invitation.role,
379
+ inviter: live.invitation.inviterName ?? "",
380
+ word: app.options.auth?.tenant?.name ?? "workspace",
381
+ expiresInDays: Math.max(1, Math.round((Date.parse(live.invitation.expiresAt) - Date.now()) / 86_400_000)),
382
+ };
383
+ const template = accounts.email.templates?.invitation;
384
+ return template ? template(input) : invitationMessage(input);
385
+ }
386
+ const id = n.data?.challenge;
387
+ if (typeof id !== "string" || !this.challenges)
357
388
  return null;
358
- return accountMessage(app.options.description ?? app.name, purpose, this.accountLink(purpose, n.recipient, bind));
389
+ const live = await this.challenges.secretsFor(id);
390
+ if (!live)
391
+ return null; // used, superseded or expired before delivery: send nothing
392
+ const link = `${this.publicUrl()}/#feltkit-${live.purpose}=${live.token}`;
393
+ const input = { app: app.options.description ?? app.name, link, code: live.code, email: live.data.email ?? "", expiresInMinutes: Math.max(1, Math.round((live.expiresAt - Date.now()) / 60_000)) };
394
+ const template = accounts.email.templates?.[live.purpose];
395
+ return template ? template(input) : accountMessage(live.purpose, input);
359
396
  },
360
397
  }),
361
398
  ]
@@ -369,7 +406,15 @@ export class FeltKitRuntime {
369
406
  environment: this.environment.name,
370
407
  resolveDurable: (subjectId) => this.#resolveDurable(subjectId),
371
408
  runJob: async (fn, payload, principal, runId) => {
372
- const result = await this.call(fn, payload, { principal, via: "job", requestId: `job_${runId}` });
409
+ // The job, not the attempt, is the unit of effect: a re-run (lease expired after the commit) replays the
410
+ // first commit by its transaction id instead of committing again.
411
+ const jobId = runId.slice(0, runId.lastIndexOf(":") > 0 ? runId.lastIndexOf(":") : runId.length);
412
+ const result = await this.call(fn, payload, { principal, via: "job", requestId: `job_${runId}`, idempotencyReplayKey: `job:${jobId}` });
413
+ // An earlier attempt of this job committed (its completion was lost): the job happened, once. A job's value is not kept.
414
+ if (!result.ok && result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true) {
415
+ this.logger.info?.(`job ${jobId}: an earlier attempt committed; not performed again`, { requestId: `job_${runId}` });
416
+ return;
417
+ }
373
418
  if (!result.ok)
374
419
  throw Object.assign(new Error(`${result.error.code}: ${result.error.message}`), { code: result.error.code });
375
420
  },
@@ -565,7 +610,32 @@ export class FeltKitRuntime {
565
610
  return key ? { id: key.principalId, type: "service", roles: [...this.#services.apiKeyRoles], displayName: `API key ${key.principalId.slice(0, 8)}` } : null;
566
611
  }
567
612
  const session = await this.sessions.get(token);
568
- return fromAppPortPrincipal(session?.principal);
613
+ let principal = fromAppPortPrincipal(session?.principal);
614
+ if (!principal)
615
+ return null;
616
+ const attributes = (session?.attributes ?? {});
617
+ // An account session is resolved again on every request: the account as it is now (a
618
+ // disabled or deleted account has no session; changed roles apply at once), never the copy
619
+ // taken at sign-in. Dev, CLI and agent sessions carry the roles their issuer gave them.
620
+ if (attributes.kind === "account") {
621
+ const account = this.accounts ? await this.accounts.get(principal.id) : null;
622
+ if (!account || account.disabled)
623
+ return null;
624
+ principal = { ...principal, roles: [...account.roles], displayName: account.name ?? account.email };
625
+ }
626
+ return this.withTenant(principal, typeof attributes.tenantId === "string" ? attributes.tenantId : undefined);
627
+ }
628
+ /**
629
+ * The principal working in a tenant: the live membership's role joins its roles, and its claims
630
+ * come along. No active membership (removed, or never a member) means no tenant and no tenant role.
631
+ */
632
+ async withTenant(principal, tenantId) {
633
+ if (!this.tenancy || !tenantId)
634
+ return principal;
635
+ const tenant = await this.tenancy.context(tenantId, principal.id);
636
+ if (!tenant)
637
+ return principal;
638
+ return { ...principal, roles: [...new Set([...principal.roles, tenant.role])], tenant };
569
639
  }
570
640
  /**
571
641
  * The principal behind durable service work, as it is now: an API key that still
@@ -587,7 +657,26 @@ export class FeltKitRuntime {
587
657
  const user = this.app.options.dev?.users?.find((u) => u.id === subjectId);
588
658
  return user ? { id: user.id, type: user.type ?? "user", roles: [...user.roles], ...(user.name ? { displayName: user.name } : {}) } : null;
589
659
  }
660
+ /**
661
+ * Identities the application itself declares — its app agents and its runtime components — are what the
662
+ * declaration says, with no session: their durable work resolves the same after a restart or a session's
663
+ * expiry. Their tenant authority is still their live membership (withTenant), so revoking it is immediate.
664
+ */
665
+ declaredPrincipal(subjectId) {
666
+ for (const agent of this.app.agents.values()) {
667
+ if (agent.principal.id === subjectId)
668
+ return { id: subjectId, type: "agent", roles: [...agent.roles], ...(agent.principal.displayName ? { displayName: agent.principal.displayName } : {}) };
669
+ }
670
+ for (const [name, c] of Object.entries(this.app.options.components ?? {})) {
671
+ if (c.principal.id === subjectId && c.principal.id === `component:${name}`)
672
+ return { id: subjectId, type: "service", roles: [...c.principal.roles], displayName: c.principal.displayName ?? `component ${name}` };
673
+ }
674
+ return null;
675
+ }
590
676
  async #resolveStrict(subjectId) {
677
+ const declared = this.declaredPrincipal(subjectId);
678
+ if (declared)
679
+ return declared;
591
680
  const keys = this.#services.apiKeys;
592
681
  if (keys) {
593
682
  const key = await keys.getApiKey(this.app.name, subjectId).catch(() => null);
@@ -607,6 +696,8 @@ export class FeltKitRuntime {
607
696
  * the log.
608
697
  */
609
698
  async #performOutbox(record, services, principal, requestId) {
699
+ if (record.effect.service === "agent")
700
+ return this.#runAgent(record.id);
610
701
  return performOutbox(outboxStore(this.instance.handle("app")), record.id, (claim, complete) => {
611
702
  const effect = claim.effect;
612
703
  // A job or webhook event is created in the transaction that records it done; a notification is sent directly.
@@ -626,9 +717,17 @@ export class FeltKitRuntime {
626
717
  const store = this.instance.handle("app");
627
718
  const outbox = store.collection(OUTBOX_COLLECTION);
628
719
  const read = async (state) => (await readAll(store, { collection: OUTBOX_COLLECTION, where: [{ field: "state", eq: state }] }));
629
- const stale = [...(await read("pending")), ...(await read("performing"))].filter((r) => isRecoverable(r, now));
720
+ const lease = (r) => (r.effect.service === "agent" ? this.app.agents.get(r.effect.agent)?.leaseMs : undefined);
721
+ // Component work is claimed by its component (its lease is on the record), never performed here.
722
+ const stale = [...(await read("pending")), ...(await read("performing"))].filter((r) => r.effect.service !== "component" && isRecoverable(r, now, lease(r)));
630
723
  let performed = 0;
631
724
  for (const record of stale) {
725
+ // An application agent runs as itself: the caller is not resolved (nor needed).
726
+ if (record.effect.service === "agent") {
727
+ if ((await this.#runAgent(record.id)) === "done")
728
+ performed += 1;
729
+ continue;
730
+ }
632
731
  const principal = await this.#resolveDurable(record.principalId);
633
732
  if (!principal) {
634
733
  await store
@@ -649,7 +748,79 @@ export class FeltKitRuntime {
649
748
  }
650
749
  return performed;
651
750
  }
751
+ /**
752
+ * Claim due work for runtime component `component`: pending work that is due, and work whose
753
+ * previous claim's lease expired (`resumed`: an earlier attempt may have partly happened). Each claim
754
+ * is a version-checked write, so two performers never hold the same item.
755
+ */
756
+ async claimComponentWork(component, options = {}, now = Date.now()) {
757
+ const leaseMs = Math.min(Math.max(options.leaseMs ?? 60_000, 1000), 3_600_000);
758
+ const limit = Math.min(Math.max(options.limit ?? 10, 1), 100);
759
+ const store = this.instance.handle("app");
760
+ const read = async (state) => (await readAll(store, { collection: OUTBOX_COLLECTION, where: [{ field: "state", eq: state }] }));
761
+ const mine = (r) => r.effect.service === "component" && r.effect.component === component && (!options.kinds || options.kinds.includes(r.effect.kind));
762
+ const due = [
763
+ ...(await read("pending")).filter((r) => mine(r) && (r.notBefore === undefined || r.notBefore <= now)),
764
+ ...(await read("performing")).filter((r) => mine(r) && (r.leaseUntil ?? 0) < now),
765
+ ].sort((a, b) => a.createdAt - b.createdAt).slice(0, limit);
766
+ const items = [];
767
+ for (const record of due) {
768
+ const next = { ...claimed(record, now), leaseUntil: now + leaseMs };
769
+ try {
770
+ await store.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: record.__version, value: next }] });
771
+ }
772
+ catch {
773
+ continue; // another performer claimed it first
774
+ }
775
+ const held = (await store.collection(OUTBOX_COLLECTION).get(record.id));
776
+ const effect = held.effect;
777
+ items.push({
778
+ id: held.id, version: held.__version, kind: effect.kind, input: effect.input, attempt: held.attempts, resumed: record.state === "performing",
779
+ leaseUntil: held.leaseUntil, ...(effect.tenantId ? { tenantId: effect.tenantId } : {}),
780
+ provenance: { requestId: held.requestId, function: held.function, principalId: held.principalId, recordedAt: held.createdAt },
781
+ });
782
+ }
783
+ return items;
784
+ }
785
+ /**
786
+ * Settle a claimed work item, fenced on the claim: a performer whose lease was taken over cannot settle
787
+ * it (CONFLICT). done → `result` is the receipt; retry → pending again after a backoff, until maxAttempts
788
+ * (then failed); failed; unknown → terminal, for a person to resolve (`feltkit outbox retry`).
789
+ */
790
+ async finishComponentWork(component, item, outcome, now = Date.now()) {
791
+ const store = this.instance.handle("app");
792
+ const record = await store.collection(OUTBOX_COLLECTION).get(item.id);
793
+ if (!record || record.effect.service !== "component" || record.effect.component !== component)
794
+ throw new FeltKitError("NOT_FOUND", `No work ${item.id} for component ${component}.`);
795
+ if (record.state !== "performing" || record.__version !== item.version)
796
+ throw new FeltKitError("CONFLICT", `Work ${item.id} is no longer held by this claim (it is ${record.state}).`, { hint: "Its lease expired and it was claimed again, or it was settled." });
797
+ const error = "error" in outcome && outcome.error ? { code: outcome.error.code ?? "FAILED", message: String(outcome.error.message ?? outcome.error).slice(0, 1000) } : { code: "FAILED", message: "No error given." };
798
+ const { leaseUntil: _l, ...base } = record;
799
+ let next;
800
+ if (outcome.outcome === "done")
801
+ next = settled(base, { ok: true, ...(outcome.receipt && Object.keys(outcome.receipt).length ? { result: outcome.receipt } : {}) }, now);
802
+ else if (outcome.outcome === "failed")
803
+ next = settled(base, { ok: false, error }, now);
804
+ else if (outcome.outcome === "unknown") {
805
+ const { __version: _v, notBefore: _n, ...rest } = base;
806
+ next = { ...rest, state: "unknown", updatedAt: now, error, ...(outcome.receipt ? { result: outcome.receipt } : {}) };
807
+ }
808
+ else {
809
+ const max = record.effect.maxAttempts ?? 5;
810
+ next = record.attempts >= max
811
+ ? settled(base, { ok: false, error: { ...error, message: `${error.message} (gave up after ${record.attempts} attempts)` } }, now)
812
+ : rescheduled(base, error, now + (outcome.retryInMs ?? Math.min(1000 * 2 ** Math.max(record.attempts - 1, 0), 600_000)), now);
813
+ }
814
+ await store.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: record.__version, value: next }] }).catch(() => {
815
+ throw new FeltKitError("CONFLICT", `Work ${item.id} changed while it was being settled.`);
816
+ });
817
+ return next.state;
818
+ }
652
819
  /** After-commit effects, newest first (optionally only those in `state`). */
820
+ /** The audit trail: one record per committed mutation, oldest first (runtime/audit.ts). */
821
+ async auditTrail(filter = {}) {
822
+ return readAudit(this.instance.handle("feltkit.audit"), filter);
823
+ }
653
824
  async listOutbox(filter = {}) {
654
825
  const rows = (await this.instance.handle("app").collection(OUTBOX_COLLECTION).find((filter.state ? { state: filter.state } : {})));
655
826
  return rows
@@ -675,6 +846,11 @@ export class FeltKitRuntime {
675
846
  catch {
676
847
  throw new FeltKitError("CONFLICT", `After-commit effect ${id} changed while it was being retried. Nothing was changed; read it again.`);
677
848
  }
849
+ if (record.effect.service === "agent") {
850
+ await this.#runAgent(id);
851
+ const { __version: _a, ...after } = (await outbox.get(id));
852
+ return after;
853
+ }
678
854
  const principal = await this.#resolveDurable(record.principalId);
679
855
  if (principal) {
680
856
  const requestId = `outbox_${id}_retry`;
@@ -690,6 +866,72 @@ export class FeltKitRuntime {
690
866
  const { __version: _v, ...after } = (await outbox.get(id));
691
867
  return after;
692
868
  }
869
+ /**
870
+ * The outbox effect that runs application agent `name` (`ctx.afterCommit.agent`, or an event in
871
+ * its `on`). It records the tenant the caller worked in; whether the agent may work there is
872
+ * decided when it runs, from the agent's own membership.
873
+ */
874
+ #agentEffect(name, input, principal, event) {
875
+ if (!this.app.agents.has(name))
876
+ throw new FeltKitError("INVALID_ARGUMENT", `No application agent named "${name}".`, { hint: `Declare it with app.agent("${name}", { principal, roles, handler }).` });
877
+ return { service: "agent", method: "run", agent: name, input, ...(principal?.tenant ? { tenantId: principal.tenant.id } : {}), ...(event ? { event } : {}) };
878
+ }
879
+ /** Start an agent run now, without making the triggering call wait for it. */
880
+ #dispatchAgent(id) {
881
+ const run = this.#runAgent(id).catch((error) => this.logger.warn(`agent run ${id}: ${error.message}`));
882
+ this.#agentRuns.add(run);
883
+ void run.finally(() => this.#agentRuns.delete(run));
884
+ }
885
+ /** Wait for the agent runs started so far (and any they start) to finish their current attempt. */
886
+ async settleAgents() {
887
+ while (this.#agentRuns.size)
888
+ await Promise.allSettled([...this.#agentRuns]);
889
+ }
890
+ /**
891
+ * One attempt of an application agent's run (an outbox record, `effect.service === "agent"`),
892
+ * through the shared performer: claim (version-checked: one performer at a time; a claim older
893
+ * than the agent's lease is taken over), run the handler as the agent through call() (roles,
894
+ * access, authorize hook, activity), then done, rescheduled with backoff, or failed. The run's
895
+ * writes commit under a transaction id derived from the record, so a run repeated after an
896
+ * unrecorded success writes nothing again.
897
+ */
898
+ #runAgent(id) {
899
+ const terminal = new Set(["UNAUTHORIZED", "FORBIDDEN", "INVALID_ARGUMENT", "NOT_FOUND", "FUNCTION_NOT_FOUND"]);
900
+ return performOutbox(outboxStore(this.instance.handle("app")), id, async (claim) => {
901
+ const effect = claim.effect;
902
+ const definition = this.app.agents.get(effect.agent);
903
+ if (!definition)
904
+ throw new FeltKitError("FUNCTION_NOT_FOUND", `Application agent "${effect.agent}" is no longer declared.`);
905
+ if (claim.attempts > definition.retry.maxAttempts && !claim.retriedBy)
906
+ throw new FeltKitError("FAILED_PRECONDITION", `Agent run abandoned: its claim expired ${claim.attempts - 1} times (lease ${definition.leaseMs} ms).`);
907
+ // The agent's own identity and roles; a tenant only through its own active membership.
908
+ const principal = await this.withTenant({ id: definition.principal.id, type: "agent", roles: [...definition.roles], ...(definition.principal.displayName ? { displayName: definition.principal.displayName } : {}) }, effect.tenantId);
909
+ const trigger = Object.freeze({
910
+ agent: definition.name,
911
+ idempotencyKey: claim.id,
912
+ attempt: claim.attempts,
913
+ by: Object.freeze({ principalId: claim.principalId, function: claim.function, requestId: claim.requestId }),
914
+ ...(effect.event ? { event: effect.event } : {}),
915
+ ...(effect.tenantId ? { requestedTenantId: effect.tenantId } : {}),
916
+ });
917
+ const requestId = `agent_${claim.id}_${claim.attempts}`;
918
+ const result = await this.call(`agent/${definition.name}`, effect.input ?? {}, { principal, via: "agent", requestId, idempotencyReplayKey: `agent:${claim.id}`, agentRun: { definition, trigger } });
919
+ if (result.ok)
920
+ return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}) };
921
+ // An earlier attempt committed (its done mark was lost): the run happened, once.
922
+ if (result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true)
923
+ return { requestId, committedEarlier: true };
924
+ throw Object.assign(new FeltKitError(result.error.code, result.error.message), { requestId });
925
+ }, {
926
+ warn: (message) => this.logger.warn(message, { outboxId: id }),
927
+ retryAt: (claim, error) => {
928
+ const definition = claim.effect.service === "agent" ? this.app.agents.get(claim.effect.agent) : undefined;
929
+ if (!definition || terminal.has(error.code) || claim.attempts >= definition.retry.maxAttempts)
930
+ return null;
931
+ return Date.now() + Math.min(definition.retry.backoffMs * 2 ** Math.max(0, claim.attempts - 1), AGENT_MAX_BACKOFF_MS);
932
+ },
933
+ });
934
+ }
693
935
  /** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
694
936
  runServices() {
695
937
  if (this.#state !== "ready" || this.#paused)
@@ -781,9 +1023,41 @@ export class FeltKitRuntime {
781
1023
  hint: "`npx feltkit vercel env` sets it from the recorded deployment.",
782
1024
  });
783
1025
  }
784
- /** A signed account link (verify an address, reset a password) for this app. */
785
- accountLink(purpose, accountId, bind) {
786
- return `${this.publicUrl()}/#feltkit-${purpose}=${signLink(this.authSecret(), { purpose, accountId, bind })}`;
1026
+ /**
1027
+ * Issue an account e-mail challenge and send it through AppPort Services' notifications (and
1028
+ * Mailerport). Returns false when nothing was sent (no account e-mail, or the subject's hourly
1029
+ * limit was reached); callers answer the same either way.
1030
+ */
1031
+ /** The link that accepts an invitation: on the app's public URL (relative when that is not configured). */
1032
+ invitationLink(token) {
1033
+ let origin = "";
1034
+ try {
1035
+ origin = this.publicUrl();
1036
+ }
1037
+ catch {
1038
+ origin = "";
1039
+ }
1040
+ return `${origin}/#feltkit-invitation=${token}`;
1041
+ }
1042
+ /** E-mail a workspace invitation (when the app sends account e-mail). False when nothing was sent. */
1043
+ async sendInvitation(invitationId, email) {
1044
+ if (!this.mail || !this.tenancy)
1045
+ return false;
1046
+ const live = await this.tenancy.tokenFor(invitationId);
1047
+ if (!live)
1048
+ return false;
1049
+ await this.services.sendAccountMail({ recipient: `email:${email}`, type: "account.invitation", title: `Join ${live.tenantName}`, data: { invitation: invitationId }, expiresAt: live.invitation.expiresAt });
1050
+ return true;
1051
+ }
1052
+ async sendChallenge(input) {
1053
+ if (!this.challenges || !this.mail)
1054
+ return false;
1055
+ const challenge = await this.challenges.issue({ purpose: input.purpose, subject: input.subject, ...(input.data ? { data: input.data } : {}) });
1056
+ if (!challenge)
1057
+ return false;
1058
+ const titles = { verify: "Verify your e-mail address", reset: "Reset your password", "magic-link": "Your sign-in link", "email-change": "Confirm your new e-mail address" };
1059
+ await this.services.sendAccountMail({ recipient: input.recipient, type: `account.${input.purpose}`, title: titles[input.purpose], data: { purpose: input.purpose, challenge: challenge.id }, expiresAt: new Date(challenge.expiresAt).toISOString() });
1060
+ return true;
787
1061
  }
788
1062
  /**
789
1063
  * The key that signs account links and sign-in provider state: FELTKIT_AUTH_SECRET, else
@@ -815,6 +1089,11 @@ export class FeltKitRuntime {
815
1089
  /** Issue a session. Development sign-in, the CLI, and auth hooks all come through here. */
816
1090
  async issueSession(input, options) {
817
1091
  const principal = normalizePrincipal(input);
1092
+ // A person's session starts in the tenant they used last (an explicit tenantId, or null for none, wins).
1093
+ let tenantId = options.tenantId === undefined ? undefined : options.tenantId ?? undefined;
1094
+ if (options.tenantId === undefined && this.tenancy && (options.kind === "account" || options.kind === "dev")) {
1095
+ tenantId = (await this.tenancy.tenantsFor(principal.id))[0]?.id;
1096
+ }
818
1097
  for (const role of principal.roles) {
819
1098
  if (!this.#authority.roles[role])
820
1099
  throw new FeltKitError("INVALID_ARGUMENT", `Unknown role "${role}". Declared roles: ${Object.keys(this.#authority.roles).join(", ") || "(none)"}.`);
@@ -822,6 +1101,7 @@ export class FeltKitRuntime {
822
1101
  const session = await this.sessions.issue(this.app.name, principal, {
823
1102
  kind: options.kind,
824
1103
  ...(options.label ? { label: options.label } : {}),
1104
+ ...(tenantId ? { tenantId } : {}),
825
1105
  ...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : this.app.options.auth?.sessionTtlMs ? { ttlMs: this.app.options.auth.sessionTtlMs } : {}),
826
1106
  });
827
1107
  this.activity.record({
@@ -832,9 +1112,32 @@ export class FeltKitRuntime {
832
1112
  principal: options.actor ? pick(options.actor) : pick(principal),
833
1113
  outcome: "success",
834
1114
  durationMs: 0,
835
- detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
1115
+ detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(tenantId ? { tenantId } : {}), ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
836
1116
  });
837
- return { token: session.id, principal, expiresAt: session.expiresAt };
1117
+ return { token: session.id, principal: await this.withTenant(principal, tenantId), expiresAt: session.expiresAt };
1118
+ }
1119
+ /**
1120
+ * An agent or service identity this app knows: one holding an active session (operator-issued:
1121
+ * `feltkit session create --type agent`), an application agent the app declares (`app.agent`), or a
1122
+ * declared development agent in development. Null for people (they join tenants by invitation) and
1123
+ * for unknown ids.
1124
+ */
1125
+ async knownNonPersonPrincipal(id) {
1126
+ if (!id || id.startsWith("acct_"))
1127
+ return null;
1128
+ // The application's own declared identities (app agents, runtime components) can be granted membership by a tenant manager.
1129
+ const declared = this.declaredPrincipal(id);
1130
+ if (declared)
1131
+ return { id, type: declared.type, ...(declared.displayName ? { displayName: declared.displayName } : {}) };
1132
+ const dev = this.environment.development ? this.app.options.dev?.users?.find((u) => u.id === id && (u.type === "agent" || u.type === "service")) : undefined;
1133
+ if (dev)
1134
+ return { id: dev.id, type: dev.type, ...(dev.name ? { displayName: dev.name } : {}) };
1135
+ const active = (await this.sessions.list()).find((s) => s.principal?.id === id && (s.principal.type === "agent" || s.principal.type === "service"));
1136
+ return active?.principal ? { id, type: active.principal.type, ...(active.principal.displayName ? { displayName: active.principal.displayName } : {}) } : null;
1137
+ }
1138
+ /** Record an authentication event (sign-in failures, revocations, membership changes) in the activity log. */
1139
+ recordAuth(name, principal, detail, outcome = "success", via = "http") {
1140
+ this.activity.record({ kind: "auth", name, via, requestId: `req_${randomUUID()}`, principal: principal ? pick(principal) : null, outcome, durationMs: 0, detail });
838
1141
  }
839
1142
  /** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
840
1143
  call(name, rawArgs, options) {
@@ -847,7 +1150,8 @@ export class FeltKitRuntime {
847
1150
  const started = performance.now();
848
1151
  const requestId = options.requestId ?? `req_${randomUUID()}`;
849
1152
  const principal = options.principal;
850
- const fn = this.#project?.functions.get(name);
1153
+ // An application agent's handler is reachable only from its run, never by name from outside.
1154
+ const fn = options.agentRun ? options.agentRun.definition.function : this.#project?.functions.get(name);
851
1155
  const kind = options.capability ? "capability" : fn?.kind ?? "query";
852
1156
  const base = {
853
1157
  kind,
@@ -855,10 +1159,14 @@ export class FeltKitRuntime {
855
1159
  via: options.via,
856
1160
  requestId,
857
1161
  principal: principal ? pick(principal) : null,
1162
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
858
1163
  ...(options.capability ? { capability: options.capability } : {}),
859
1164
  };
1165
+ const run = options.agentRun?.trigger;
1166
+ const agentDetail = run ? { agentRun: { agent: run.agent, idempotencyKey: run.idempotencyKey, attempt: run.attempt, triggeredBy: run.by.principalId, triggeredFrom: run.by.function, ...(run.event ? { event: run.event } : {}) } } : undefined;
860
1167
  const finish = (entry) => {
861
- this.activity.record({ ...base, durationMs: Math.round(performance.now() - started), ...entry });
1168
+ const detail = agentDetail || entry.detail ? { ...agentDetail, ...entry.detail } : undefined;
1169
+ this.activity.record({ ...base, durationMs: Math.round(performance.now() - started), ...entry, ...(detail ? { detail } : {}) });
862
1170
  };
863
1171
  const failure = (error, extra = {}) => {
864
1172
  const json = this.#errorJSON(error, requestId);
@@ -928,6 +1236,17 @@ export class FeltKitRuntime {
928
1236
  const used = new Set();
929
1237
  const shared = {
930
1238
  auth: authContext(this.#authority, principal),
1239
+ tenancy: {
1240
+ members: async () => {
1241
+ if (!this.tenancy)
1242
+ throw new FeltKitError("CONFIGURATION", "This app has no tenants (auth.tenant).");
1243
+ db.reads.add(MEMBERSHIPS_COLLECTION); // re-run live queries when memberships change
1244
+ const tenantId = principal?.tenant?.id;
1245
+ if (!tenantId)
1246
+ return [];
1247
+ return (await this.tenancy.members(tenantId)).map((m) => ({ principalId: m.principalId, type: m.principalType, role: m.role, claims: m.claims, ...(m.displayName ? { displayName: m.displayName } : {}), ...(m.email ? { email: m.email } : {}) }));
1248
+ },
1249
+ },
931
1250
  services: explainServiceDenials(this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", used), name, principal, this.#authority),
932
1251
  environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
933
1252
  requestId,
@@ -955,16 +1274,42 @@ export class FeltKitRuntime {
955
1274
  enabled: { notifications: Boolean(enabled.notifications), webhooks: Boolean(enabled.webhooks), jobs: Boolean(enabled.jobs) },
956
1275
  stage: (record) => db.stageSystem(OUTBOX_COLLECTION, record),
957
1276
  newId: newOutboxId,
1277
+ agent: (agentName, input) => this.#agentEffect(agentName, input, principal, triggeringEvent),
1278
+ work: (component, kind, input, opts) => {
1279
+ if (!this.app.options.components?.[component])
1280
+ throw new FeltKitError("INVALID_ARGUMENT", `afterCommit.work: "${component}" is not a component of this application.`, { hint: "Declare it in feltkit({ components })." });
1281
+ return { service: "component", method: "work", component, kind, input, ...(principal?.tenant ? { tenantId: principal.tenant.id } : {}), ...(opts.maxAttempts ? { maxAttempts: opts.maxAttempts } : {}) };
1282
+ },
958
1283
  })
959
1284
  : null;
960
- // ctx.events: validated now, published only after the commit (below); never stored.
1285
+ // ctx.events: validated now, published only after the commit (below); never stored. An
1286
+ // application agent whose `on` names the event is recorded now, in this transaction.
961
1287
  const published = [];
962
- const events = { publish: (event, payload, options = {}) => published.push(stageEvent(this.app, event, payload, options)) };
963
- const ctx = fn.kind === "mutation" ? { ...shared, db, agent, events, afterCommit: effects, unsafe: { feltdb: this.instance.handle("app.unsafe") } } : { ...shared, db };
1288
+ let triggeringEvent;
1289
+ const events = {
1290
+ publish: (event, payload, options = {}) => {
1291
+ const staged = stageEvent(this.app, event, payload, options);
1292
+ published.push(staged);
1293
+ for (const definition of this.app.agents.values()) {
1294
+ if (!definition.on.includes(staged.name))
1295
+ continue;
1296
+ triggeringEvent = staged.name;
1297
+ try {
1298
+ effects.agent(definition.name, { event: staged.name, payload: staged.payload, ...(staged.scope !== undefined ? { scope: staged.scope } : {}) });
1299
+ }
1300
+ finally {
1301
+ triggeringEvent = undefined;
1302
+ }
1303
+ }
1304
+ },
1305
+ };
1306
+ // Tenant-scoped collections see only the caller's tenant (the session's, never the request's).
1307
+ const scoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(db);
1308
+ 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 };
964
1309
  try {
965
1310
  // feltkit({ authorize }): after roles and validation, with this call's own reader, so its
966
1311
  // reads are fenced at commit (mutations) and tracked for live queries (queries).
967
- await this.#authorizeResource(name, fn, args, principal, options, requestId, db, authorityRecord);
1312
+ await this.#authorizeResource(name, fn, args, principal, options, requestId, scoped, authorityRecord);
968
1313
  const value = await fn.handler(ctx, args);
969
1314
  if (fn.returns) {
970
1315
  const output = validate(fn.returns, value);
@@ -974,9 +1319,14 @@ export class FeltKitRuntime {
974
1319
  }
975
1320
  let commit;
976
1321
  if (db instanceof Writer) {
977
- commit = await db.commit(options.idempotencyReplayKey ? idempotentTransactionId(options.idempotencyReplayKey) : requestId, {
978
- keyed: options.idempotencyReplayKey !== undefined,
979
- });
1322
+ const transactionId = options.idempotencyReplayKey ? idempotentTransactionId(options.idempotencyReplayKey) : requestId;
1323
+ // The audit record commits with the writes it describes (runtime/audit.ts).
1324
+ const writes = db.pendingWrites();
1325
+ const effects = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value.id);
1326
+ if (writes.length || effects.length) {
1327
+ db.stageSystem(AUDIT_COLLECTION, auditRecord({ transactionId, function: name, via: options.via, requestId, principal: principal ?? null, authority: authorityRecord, writes, effects }));
1328
+ }
1329
+ commit = await db.commit(transactionId, { keyed: options.idempotencyReplayKey !== undefined });
980
1330
  }
981
1331
  return { value, db, commit, starts, used, published };
982
1332
  }
@@ -1009,16 +1359,24 @@ export class FeltKitRuntime {
1009
1359
  const { value, db, commit, starts, published } = outcome;
1010
1360
  reads = [...db.reads];
1011
1361
  if (db instanceof Writer && commit) {
1012
- if (commit.writes.length)
1362
+ if (commit.writes.length) {
1363
+ this.changes.describe(commit.described);
1013
1364
  void this.changes.check();
1365
+ }
1014
1366
  // Agent work starts only once the mutation's writes are durable.
1015
1367
  for (const start of starts)
1016
1368
  this.#agent?.startAfterCommit(start, principal);
1017
1369
  // So do after-commit effects: performed now, as the caller, while its binding is live.
1018
1370
  const outbox = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value);
1019
- if (outbox.length) {
1371
+ // Application agents run as themselves, without holding up this call (or its services binding).
1372
+ for (const record of outbox)
1373
+ if (record.effect.service === "agent")
1374
+ this.#dispatchAgent(record.id);
1375
+ // Component work waits for its component to claim it (ctx.work.claim).
1376
+ const effects = outbox.filter((record) => record.effect.service !== "agent" && record.effect.service !== "component");
1377
+ if (effects.length) {
1020
1378
  const bound = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true, servicesUsed), name, principal, this.#authority);
1021
- for (const record of outbox)
1379
+ for (const record of effects)
1022
1380
  await this.#performOutbox(record, bound, principal, requestId);
1023
1381
  }
1024
1382
  // Ephemeral events: at most once, to whoever is subscribed now (AppPort's event bus).
@@ -1041,7 +1399,8 @@ export class FeltKitRuntime {
1041
1399
  }
1042
1400
  : {}),
1043
1401
  });
1044
- return { ok: true, value: value === undefined ? null : value, reads, requestId };
1402
+ // `reads` for the caller: collection names, then `collection#key` per equality predicate (runtime/live.ts).
1403
+ return { ok: true, value: value === undefined ? null : value, reads: db.reads.report(), requestId };
1045
1404
  }
1046
1405
  }
1047
1406
  catch (error) {
@@ -1163,6 +1522,9 @@ export class FeltKitRuntime {
1163
1522
  clearInterval(this.#worker);
1164
1523
  this.changes.stop();
1165
1524
  await Promise.allSettled([...this.#inflight]);
1525
+ // Agent runs started before the close: their calls now answer UNAVAILABLE, so each is
1526
+ // rescheduled for the services worker (of this process's successor).
1527
+ await this.settleAgents();
1166
1528
  await this.#appport?.close().catch(() => undefined);
1167
1529
  await this.models.close();
1168
1530
  await this.activity.flush();
@@ -1234,19 +1596,27 @@ function replayKey(context, exposure, principal) {
1234
1596
  function idempotentTransactionId(replayKey) {
1235
1597
  return `idem_${createHash("sha256").update(replayKey).digest("hex")}`;
1236
1598
  }
1237
- /** The text of an account e-mail. */
1238
- function accountMessage(appName, purpose, link) {
1239
- if (purpose === "reset") {
1240
- return {
1241
- subject: `Reset your ${appName} password`,
1242
- text: `Someone asked to reset the password for your ${appName} account.\n\nSet a new password (the link works once, for an hour):\n${link}\n\nIf it was not you, ignore this e-mail; your password has not changed.`,
1243
- };
1244
- }
1599
+ function invitationMessage(input) {
1600
+ const who = input.inviter ? `${input.inviter} invited you` : "You are invited";
1245
1601
  return {
1246
- subject: `Verify your e-mail address for ${appName}`,
1247
- text: `Confirm that this is your address (the link works for 7 days):\n${link}\n\nIf you did not create a ${appName} account, ignore this e-mail.`,
1602
+ subject: `${who} to join ${input.tenant} on ${input.app}`,
1603
+ text: `${who} to join the ${input.word} "${input.tenant}" on ${input.app} as ${input.role}.\n\nAccept the invitation (it works once, for ${input.expiresInDays} day${input.expiresInDays === 1 ? "" : "s"}):\n${input.link}\n\nIf you did not expect this, ignore this e-mail.`,
1248
1604
  };
1249
1605
  }
1606
+ /** The default text of an account e-mail. */
1607
+ function accountMessage(purpose, input) {
1608
+ const { app, link, code, expiresInMinutes: minutes } = input;
1609
+ switch (purpose) {
1610
+ case "reset":
1611
+ return { subject: `Reset your ${app} password`, text: `Someone asked to reset the password for your ${app} account.\n\nSet a new password (the link works once, for ${minutes} minutes):\n${link}\n\nIf it was not you, ignore this e-mail; your password has not changed.` };
1612
+ case "magic-link":
1613
+ return { subject: `Sign in to ${app}`, text: `Sign in to ${app} (the link works once, for ${minutes} minutes):\n${link}\n\nOr enter this code: ${code.slice(0, 4)} ${code.slice(4)}\n\nIf you did not ask to sign in, ignore this e-mail.` };
1614
+ case "email-change":
1615
+ return { subject: `Confirm your new e-mail address for ${app}`, text: `Confirm that ${input.email} is your new address for ${app} (the link works once, for ${minutes} minutes):\n${link}\n\nIf you did not ask for this, ignore this e-mail; nothing changes.` };
1616
+ default:
1617
+ return { subject: `Verify your e-mail address for ${app}`, text: `Confirm that this is your address (the link works once, for ${minutes} minutes):\n${link}\n\nIf you did not create a ${app} account, ignore this e-mail.` };
1618
+ }
1619
+ }
1250
1620
  /**
1251
1621
  * AppPort Services' e-mail channel (0.13.0+). Looked up when an app sends account e-mail, so an
1252
1622
  * older AppPort Services still runs every other app, and this one says what it needs.