@feltdb/feltkit 0.3.17 → 0.3.18

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 (107) hide show
  1. package/dist/app.d.ts +195 -5
  2. package/dist/app.js +150 -3
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.d.ts +45 -0
  5. package/dist/appboundry/build.js +52 -1
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/guest.js +39 -1
  8. package/dist/appboundry/guest.js.map +1 -1
  9. package/dist/appboundry/host.js +4 -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/deploy-appboundry-self-hosted.d.ts +2 -0
  14. package/dist/cli/deploy-appboundry-self-hosted.js +1 -1
  15. package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
  16. package/dist/cli/deploy-appboundry.js +3 -0
  17. package/dist/cli/deploy-appboundry.js.map +1 -1
  18. package/dist/cli/main.js +6 -1
  19. package/dist/cli/main.js.map +1 -1
  20. package/dist/client/index.d.ts +192 -5
  21. package/dist/client/index.js +301 -28
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/docs.d.ts +1 -1
  24. package/dist/docs.js +1 -0
  25. package/dist/docs.js.map +1 -1
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js.map +1 -1
  28. package/dist/react/auth.d.ts +131 -0
  29. package/dist/react/auth.js +830 -0
  30. package/dist/react/auth.js.map +1 -0
  31. package/dist/react/context.d.ts +8 -0
  32. package/dist/react/context.js +14 -0
  33. package/dist/react/context.js.map +1 -0
  34. package/dist/react/index.d.ts +3 -18
  35. package/dist/react/index.js +5 -13
  36. package/dist/react/index.js.map +1 -1
  37. package/dist/runtime/accounts.d.ts +33 -2
  38. package/dist/runtime/accounts.js +167 -27
  39. package/dist/runtime/accounts.js.map +1 -1
  40. package/dist/runtime/authority.d.ts +8 -1
  41. package/dist/runtime/authority.js +11 -2
  42. package/dist/runtime/authority.js.map +1 -1
  43. package/dist/runtime/challenges.d.ts +51 -0
  44. package/dist/runtime/challenges.js +121 -0
  45. package/dist/runtime/challenges.js.map +1 -0
  46. package/dist/runtime/changes.d.ts +22 -0
  47. package/dist/runtime/changes.js +51 -3
  48. package/dist/runtime/changes.js.map +1 -1
  49. package/dist/runtime/context.d.ts +41 -0
  50. package/dist/runtime/contract.js +14 -3
  51. package/dist/runtime/contract.js.map +1 -1
  52. package/dist/runtime/data.d.ts +36 -2
  53. package/dist/runtime/data.js +56 -17
  54. package/dist/runtime/data.js.map +1 -1
  55. package/dist/runtime/live.d.ts +48 -0
  56. package/dist/runtime/live.js +154 -0
  57. package/dist/runtime/live.js.map +1 -0
  58. package/dist/runtime/outbox.js +3 -0
  59. package/dist/runtime/outbox.js.map +1 -1
  60. package/dist/runtime/runtime.d.ts +70 -5
  61. package/dist/runtime/runtime.js +290 -35
  62. package/dist/runtime/runtime.js.map +1 -1
  63. package/dist/runtime/search.d.ts +54 -0
  64. package/dist/runtime/search.js +66 -0
  65. package/dist/runtime/search.js.map +1 -0
  66. package/dist/runtime/sessions.d.ts +16 -2
  67. package/dist/runtime/sessions.js +40 -4
  68. package/dist/runtime/sessions.js.map +1 -1
  69. package/dist/runtime/tenancy.d.ts +189 -0
  70. package/dist/runtime/tenancy.js +376 -0
  71. package/dist/runtime/tenancy.js.map +1 -0
  72. package/dist/runtime/tenant-scope.d.ts +9 -0
  73. package/dist/runtime/tenant-scope.js +127 -0
  74. package/dist/runtime/tenant-scope.js.map +1 -0
  75. package/dist/runtime/transactions.d.ts +45 -2
  76. package/dist/runtime/transactions.js +36 -9
  77. package/dist/runtime/transactions.js.map +1 -1
  78. package/dist/server/index.d.ts +2 -1
  79. package/dist/server/index.js +300 -58
  80. package/dist/server/index.js.map +1 -1
  81. package/dist/server/mcp.js +6 -3
  82. package/dist/server/mcp.js.map +1 -1
  83. package/dist/server/session-http.d.ts +48 -0
  84. package/dist/server/session-http.js +116 -0
  85. package/dist/server/session-http.js.map +1 -0
  86. package/dist/server/tenancy.d.ts +40 -0
  87. package/dist/server/tenancy.js +191 -0
  88. package/dist/server/tenancy.js.map +1 -0
  89. package/dist/testing/index.d.ts +7 -0
  90. package/dist/testing/index.js +7 -2
  91. package/dist/testing/index.js.map +1 -1
  92. package/docs/AGENT-OPERATIONS.md +1 -0
  93. package/docs/APPBOUNDRY.md +11 -1
  94. package/docs/ARCHITECTURE.md +4 -2
  95. package/docs/AUTH.md +262 -0
  96. package/docs/GUARANTEES.md +50 -3
  97. package/docs/README.md +3 -2
  98. package/docs/SECURITY.md +3 -2
  99. package/docs/TRANSACTIONS.md +98 -1
  100. package/docs/UPSTREAM-GAPS.md +2 -0
  101. package/package.json +11 -10
  102. package/skills/.claude-plugin/marketplace.json +1 -1
  103. package/skills/.claude-plugin/plugin.json +1 -1
  104. package/skills/feltkit-data/SKILL.md +6 -0
  105. package/dist/runtime/account-links.d.ts +0 -19
  106. package/dist/runtime/account-links.js +0 -45
  107. 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";
@@ -42,7 +43,9 @@ import { FeltDbSessionStore } from "./sessions.js";
42
43
  import { AccountStore } from "./accounts.js";
43
44
  import * as appportServices from "@appport/services";
44
45
  import { accountMail } from "./mail.js";
45
- import { signLink } from "./account-links.js";
46
+ import { ChallengeStore } from "./challenges.js";
47
+ import { MEMBERSHIPS_COLLECTION, TenancyStore } from "./tenancy.js";
48
+ import { hasTenantCollections, scopeToTenant } from "./tenant-scope.js";
46
49
  const consoleLogger = {
47
50
  info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
48
51
  warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
@@ -65,6 +68,10 @@ export class FeltKitRuntime {
65
68
  sessions;
66
69
  /** Built-in accounts (`auth.accounts`), or null when the app does not use them. */
67
70
  accounts = null;
71
+ /** Account e-mail challenges (verify, reset, magic link, address change). Null without accounts. */
72
+ challenges = null;
73
+ /** Tenants, memberships and invitations (`auth.tenant`). Null without tenancy. */
74
+ tenancy = null;
68
75
  /** Account e-mail (auth.accounts.email) through Mailerport, or null (none declared, or production without MAILPORT_URL). */
69
76
  mail = null;
70
77
  /** This server's own URL, set by the HTTP server: development's fallback for links. */
@@ -88,6 +95,8 @@ export class FeltKitRuntime {
88
95
  #resolver;
89
96
  #state = "starting";
90
97
  #inflight = new Set();
98
+ /** Application agent runs started after a commit (app.agent), awaited by close() and settleAgents(). */
99
+ #agentRuns = new Set();
91
100
  /** Set while backup() reads the state: calls and the services worker wait for it. */
92
101
  #paused = null;
93
102
  #dispatched = new Set();
@@ -338,6 +347,9 @@ export class FeltKitRuntime {
338
347
  const authority = new Authority(app.name, app.options.roles ?? {});
339
348
  const accounts = app.options.auth?.accounts;
340
349
  this.accounts = accounts ? new AccountStore(this.instance.handle("feltkit.accounts"), accounts) : null;
350
+ this.challenges = accounts ? new ChallengeStore(this.instance.handle("feltkit.accounts"), () => this.authSecret()) : null;
351
+ const tenant = app.options.auth?.tenant;
352
+ this.tenancy = tenant ? new TenancyStore(this.instance.handle("feltkit.tenancy"), tenant, () => this.authSecret()) : null;
341
353
  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
354
  const config = app.options.services ?? {};
343
355
  const store = this.accounts;
@@ -347,15 +359,38 @@ export class FeltKitRuntime {
347
359
  new (emailChannelClass())({
348
360
  transport: mail.transport,
349
361
  identity: accounts.email.identity ?? "auth",
350
- address: async (n) => (await store.get(n.recipient))?.email ?? null,
362
+ // An account's address, or (magic link for a new address, address change) the address itself.
363
+ address: async (n) => (n.recipient.startsWith("email:") ? n.recipient.slice(6) : (await store.get(n.recipient))?.email ?? null),
364
+ // Rendered when delivered, from the live challenge: the link and code are never stored.
351
365
  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)
366
+ // A workspace invitation (auth.tenant): rendered from the live invitation, so a
367
+ // withdrawn or accepted one sends nothing, and its token is never stored.
368
+ if (typeof n.data?.invitation === "string") {
369
+ const live = this.tenancy ? await this.tenancy.tokenFor(n.data.invitation) : null;
370
+ if (!live)
371
+ return null;
372
+ const input = {
373
+ app: app.options.description ?? app.name,
374
+ link: this.invitationLink(live.token),
375
+ tenant: live.tenantName,
376
+ role: live.invitation.role,
377
+ inviter: live.invitation.inviterName ?? "",
378
+ word: app.options.auth?.tenant?.name ?? "workspace",
379
+ expiresInDays: Math.max(1, Math.round((Date.parse(live.invitation.expiresAt) - Date.now()) / 86_400_000)),
380
+ };
381
+ const template = accounts.email.templates?.invitation;
382
+ return template ? template(input) : invitationMessage(input);
383
+ }
384
+ const id = n.data?.challenge;
385
+ if (typeof id !== "string" || !this.challenges)
357
386
  return null;
358
- return accountMessage(app.options.description ?? app.name, purpose, this.accountLink(purpose, n.recipient, bind));
387
+ const live = await this.challenges.secretsFor(id);
388
+ if (!live)
389
+ return null; // used, superseded or expired before delivery: send nothing
390
+ const link = `${this.publicUrl()}/#feltkit-${live.purpose}=${live.token}`;
391
+ 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)) };
392
+ const template = accounts.email.templates?.[live.purpose];
393
+ return template ? template(input) : accountMessage(live.purpose, input);
359
394
  },
360
395
  }),
361
396
  ]
@@ -565,7 +600,32 @@ export class FeltKitRuntime {
565
600
  return key ? { id: key.principalId, type: "service", roles: [...this.#services.apiKeyRoles], displayName: `API key ${key.principalId.slice(0, 8)}` } : null;
566
601
  }
567
602
  const session = await this.sessions.get(token);
568
- return fromAppPortPrincipal(session?.principal);
603
+ let principal = fromAppPortPrincipal(session?.principal);
604
+ if (!principal)
605
+ return null;
606
+ const attributes = (session?.attributes ?? {});
607
+ // An account session is resolved again on every request: the account as it is now (a
608
+ // disabled or deleted account has no session; changed roles apply at once), never the copy
609
+ // taken at sign-in. Dev, CLI and agent sessions carry the roles their issuer gave them.
610
+ if (attributes.kind === "account") {
611
+ const account = this.accounts ? await this.accounts.get(principal.id) : null;
612
+ if (!account || account.disabled)
613
+ return null;
614
+ principal = { ...principal, roles: [...account.roles], displayName: account.name ?? account.email };
615
+ }
616
+ return this.withTenant(principal, typeof attributes.tenantId === "string" ? attributes.tenantId : undefined);
617
+ }
618
+ /**
619
+ * The principal working in a tenant: the live membership's role joins its roles, and its claims
620
+ * come along. No active membership (removed, or never a member) means no tenant and no tenant role.
621
+ */
622
+ async withTenant(principal, tenantId) {
623
+ if (!this.tenancy || !tenantId)
624
+ return principal;
625
+ const tenant = await this.tenancy.context(tenantId, principal.id);
626
+ if (!tenant)
627
+ return principal;
628
+ return { ...principal, roles: [...new Set([...principal.roles, tenant.role])], tenant };
569
629
  }
570
630
  /**
571
631
  * The principal behind durable service work, as it is now: an API key that still
@@ -607,6 +667,8 @@ export class FeltKitRuntime {
607
667
  * the log.
608
668
  */
609
669
  async #performOutbox(record, services, principal, requestId) {
670
+ if (record.effect.service === "agent")
671
+ return this.#runAgent(record.id);
610
672
  return performOutbox(outboxStore(this.instance.handle("app")), record.id, (claim, complete) => {
611
673
  const effect = claim.effect;
612
674
  // A job or webhook event is created in the transaction that records it done; a notification is sent directly.
@@ -626,9 +688,16 @@ export class FeltKitRuntime {
626
688
  const store = this.instance.handle("app");
627
689
  const outbox = store.collection(OUTBOX_COLLECTION);
628
690
  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));
691
+ const lease = (r) => (r.effect.service === "agent" ? this.app.agents.get(r.effect.agent)?.leaseMs : undefined);
692
+ const stale = [...(await read("pending")), ...(await read("performing"))].filter((r) => isRecoverable(r, now, lease(r)));
630
693
  let performed = 0;
631
694
  for (const record of stale) {
695
+ // An application agent runs as itself: the caller is not resolved (nor needed).
696
+ if (record.effect.service === "agent") {
697
+ if ((await this.#runAgent(record.id)) === "done")
698
+ performed += 1;
699
+ continue;
700
+ }
632
701
  const principal = await this.#resolveDurable(record.principalId);
633
702
  if (!principal) {
634
703
  await store
@@ -675,6 +744,11 @@ export class FeltKitRuntime {
675
744
  catch {
676
745
  throw new FeltKitError("CONFLICT", `After-commit effect ${id} changed while it was being retried. Nothing was changed; read it again.`);
677
746
  }
747
+ if (record.effect.service === "agent") {
748
+ await this.#runAgent(id);
749
+ const { __version: _a, ...after } = (await outbox.get(id));
750
+ return after;
751
+ }
678
752
  const principal = await this.#resolveDurable(record.principalId);
679
753
  if (principal) {
680
754
  const requestId = `outbox_${id}_retry`;
@@ -690,6 +764,72 @@ export class FeltKitRuntime {
690
764
  const { __version: _v, ...after } = (await outbox.get(id));
691
765
  return after;
692
766
  }
767
+ /**
768
+ * The outbox effect that runs application agent `name` (`ctx.afterCommit.agent`, or an event in
769
+ * its `on`). It records the tenant the caller worked in; whether the agent may work there is
770
+ * decided when it runs, from the agent's own membership.
771
+ */
772
+ #agentEffect(name, input, principal, event) {
773
+ if (!this.app.agents.has(name))
774
+ throw new FeltKitError("INVALID_ARGUMENT", `No application agent named "${name}".`, { hint: `Declare it with app.agent("${name}", { principal, roles, handler }).` });
775
+ return { service: "agent", method: "run", agent: name, input, ...(principal?.tenant ? { tenantId: principal.tenant.id } : {}), ...(event ? { event } : {}) };
776
+ }
777
+ /** Start an agent run now, without making the triggering call wait for it. */
778
+ #dispatchAgent(id) {
779
+ const run = this.#runAgent(id).catch((error) => this.logger.warn(`agent run ${id}: ${error.message}`));
780
+ this.#agentRuns.add(run);
781
+ void run.finally(() => this.#agentRuns.delete(run));
782
+ }
783
+ /** Wait for the agent runs started so far (and any they start) to finish their current attempt. */
784
+ async settleAgents() {
785
+ while (this.#agentRuns.size)
786
+ await Promise.allSettled([...this.#agentRuns]);
787
+ }
788
+ /**
789
+ * One attempt of an application agent's run (an outbox record, `effect.service === "agent"`),
790
+ * through the shared performer: claim (version-checked: one performer at a time; a claim older
791
+ * than the agent's lease is taken over), run the handler as the agent through call() (roles,
792
+ * access, authorize hook, activity), then done, rescheduled with backoff, or failed. The run's
793
+ * writes commit under a transaction id derived from the record, so a run repeated after an
794
+ * unrecorded success writes nothing again.
795
+ */
796
+ #runAgent(id) {
797
+ const terminal = new Set(["UNAUTHORIZED", "FORBIDDEN", "INVALID_ARGUMENT", "NOT_FOUND", "FUNCTION_NOT_FOUND"]);
798
+ return performOutbox(outboxStore(this.instance.handle("app")), id, async (claim) => {
799
+ const effect = claim.effect;
800
+ const definition = this.app.agents.get(effect.agent);
801
+ if (!definition)
802
+ throw new FeltKitError("FUNCTION_NOT_FOUND", `Application agent "${effect.agent}" is no longer declared.`);
803
+ if (claim.attempts > definition.retry.maxAttempts && !claim.retriedBy)
804
+ throw new FeltKitError("FAILED_PRECONDITION", `Agent run abandoned: its claim expired ${claim.attempts - 1} times (lease ${definition.leaseMs} ms).`);
805
+ // The agent's own identity and roles; a tenant only through its own active membership.
806
+ const principal = await this.withTenant({ id: definition.principal.id, type: "agent", roles: [...definition.roles], ...(definition.principal.displayName ? { displayName: definition.principal.displayName } : {}) }, effect.tenantId);
807
+ const trigger = Object.freeze({
808
+ agent: definition.name,
809
+ idempotencyKey: claim.id,
810
+ attempt: claim.attempts,
811
+ by: Object.freeze({ principalId: claim.principalId, function: claim.function, requestId: claim.requestId }),
812
+ ...(effect.event ? { event: effect.event } : {}),
813
+ ...(effect.tenantId ? { requestedTenantId: effect.tenantId } : {}),
814
+ });
815
+ const requestId = `agent_${claim.id}_${claim.attempts}`;
816
+ const result = await this.call(`agent/${definition.name}`, effect.input ?? {}, { principal, via: "agent", requestId, idempotencyReplayKey: `agent:${claim.id}`, agentRun: { definition, trigger } });
817
+ if (result.ok)
818
+ return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}) };
819
+ // An earlier attempt committed (its done mark was lost): the run happened, once.
820
+ if (result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true)
821
+ return { requestId, committedEarlier: true };
822
+ throw Object.assign(new FeltKitError(result.error.code, result.error.message), { requestId });
823
+ }, {
824
+ warn: (message) => this.logger.warn(message, { outboxId: id }),
825
+ retryAt: (claim, error) => {
826
+ const definition = claim.effect.service === "agent" ? this.app.agents.get(claim.effect.agent) : undefined;
827
+ if (!definition || terminal.has(error.code) || claim.attempts >= definition.retry.maxAttempts)
828
+ return null;
829
+ return Date.now() + Math.min(definition.retry.backoffMs * 2 ** Math.max(0, claim.attempts - 1), AGENT_MAX_BACKOFF_MS);
830
+ },
831
+ });
832
+ }
693
833
  /** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
694
834
  runServices() {
695
835
  if (this.#state !== "ready" || this.#paused)
@@ -781,9 +921,41 @@ export class FeltKitRuntime {
781
921
  hint: "`npx feltkit vercel env` sets it from the recorded deployment.",
782
922
  });
783
923
  }
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 })}`;
924
+ /**
925
+ * Issue an account e-mail challenge and send it through AppPort Services' notifications (and
926
+ * Mailerport). Returns false when nothing was sent (no account e-mail, or the subject's hourly
927
+ * limit was reached); callers answer the same either way.
928
+ */
929
+ /** The link that accepts an invitation: on the app's public URL (relative when that is not configured). */
930
+ invitationLink(token) {
931
+ let origin = "";
932
+ try {
933
+ origin = this.publicUrl();
934
+ }
935
+ catch {
936
+ origin = "";
937
+ }
938
+ return `${origin}/#feltkit-invitation=${token}`;
939
+ }
940
+ /** E-mail a workspace invitation (when the app sends account e-mail). False when nothing was sent. */
941
+ async sendInvitation(invitationId, email) {
942
+ if (!this.mail || !this.tenancy)
943
+ return false;
944
+ const live = await this.tenancy.tokenFor(invitationId);
945
+ if (!live)
946
+ return false;
947
+ await this.services.sendAccountMail({ recipient: `email:${email}`, type: "account.invitation", title: `Join ${live.tenantName}`, data: { invitation: invitationId }, expiresAt: live.invitation.expiresAt });
948
+ return true;
949
+ }
950
+ async sendChallenge(input) {
951
+ if (!this.challenges || !this.mail)
952
+ return false;
953
+ const challenge = await this.challenges.issue({ purpose: input.purpose, subject: input.subject, ...(input.data ? { data: input.data } : {}) });
954
+ if (!challenge)
955
+ return false;
956
+ 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" };
957
+ 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() });
958
+ return true;
787
959
  }
788
960
  /**
789
961
  * The key that signs account links and sign-in provider state: FELTKIT_AUTH_SECRET, else
@@ -815,6 +987,11 @@ export class FeltKitRuntime {
815
987
  /** Issue a session. Development sign-in, the CLI, and auth hooks all come through here. */
816
988
  async issueSession(input, options) {
817
989
  const principal = normalizePrincipal(input);
990
+ // A person's session starts in the tenant they used last (an explicit tenantId, or null for none, wins).
991
+ let tenantId = options.tenantId === undefined ? undefined : options.tenantId ?? undefined;
992
+ if (options.tenantId === undefined && this.tenancy && (options.kind === "account" || options.kind === "dev")) {
993
+ tenantId = (await this.tenancy.tenantsFor(principal.id))[0]?.id;
994
+ }
818
995
  for (const role of principal.roles) {
819
996
  if (!this.#authority.roles[role])
820
997
  throw new FeltKitError("INVALID_ARGUMENT", `Unknown role "${role}". Declared roles: ${Object.keys(this.#authority.roles).join(", ") || "(none)"}.`);
@@ -822,6 +999,7 @@ export class FeltKitRuntime {
822
999
  const session = await this.sessions.issue(this.app.name, principal, {
823
1000
  kind: options.kind,
824
1001
  ...(options.label ? { label: options.label } : {}),
1002
+ ...(tenantId ? { tenantId } : {}),
825
1003
  ...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : this.app.options.auth?.sessionTtlMs ? { ttlMs: this.app.options.auth.sessionTtlMs } : {}),
826
1004
  });
827
1005
  this.activity.record({
@@ -832,9 +1010,31 @@ export class FeltKitRuntime {
832
1010
  principal: options.actor ? pick(options.actor) : pick(principal),
833
1011
  outcome: "success",
834
1012
  durationMs: 0,
835
- detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
1013
+ detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(tenantId ? { tenantId } : {}), ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
836
1014
  });
837
- return { token: session.id, principal, expiresAt: session.expiresAt };
1015
+ return { token: session.id, principal: await this.withTenant(principal, tenantId), expiresAt: session.expiresAt };
1016
+ }
1017
+ /**
1018
+ * An agent or service identity this app knows: one holding an active session (operator-issued:
1019
+ * `feltkit session create --type agent`), an application agent the app declares (`app.agent`), or a
1020
+ * declared development agent in development. Null for people (they join tenants by invitation) and
1021
+ * for unknown ids.
1022
+ */
1023
+ async knownNonPersonPrincipal(id) {
1024
+ if (!id || id.startsWith("acct_"))
1025
+ return null;
1026
+ const declared = [...this.app.agents.values()].find((a) => a.principal.id === id);
1027
+ if (declared)
1028
+ return { id, type: "agent", ...(declared.principal.displayName ? { displayName: declared.principal.displayName } : {}) };
1029
+ const dev = this.environment.development ? this.app.options.dev?.users?.find((u) => u.id === id && (u.type === "agent" || u.type === "service")) : undefined;
1030
+ if (dev)
1031
+ return { id: dev.id, type: dev.type, ...(dev.name ? { displayName: dev.name } : {}) };
1032
+ const active = (await this.sessions.list()).find((s) => s.principal?.id === id && (s.principal.type === "agent" || s.principal.type === "service"));
1033
+ return active?.principal ? { id, type: active.principal.type, ...(active.principal.displayName ? { displayName: active.principal.displayName } : {}) } : null;
1034
+ }
1035
+ /** Record an authentication event (sign-in failures, revocations, membership changes) in the activity log. */
1036
+ recordAuth(name, principal, detail, outcome = "success", via = "http") {
1037
+ this.activity.record({ kind: "auth", name, via, requestId: `req_${randomUUID()}`, principal: principal ? pick(principal) : null, outcome, durationMs: 0, detail });
838
1038
  }
839
1039
  /** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
840
1040
  call(name, rawArgs, options) {
@@ -847,7 +1047,8 @@ export class FeltKitRuntime {
847
1047
  const started = performance.now();
848
1048
  const requestId = options.requestId ?? `req_${randomUUID()}`;
849
1049
  const principal = options.principal;
850
- const fn = this.#project?.functions.get(name);
1050
+ // An application agent's handler is reachable only from its run, never by name from outside.
1051
+ const fn = options.agentRun ? options.agentRun.definition.function : this.#project?.functions.get(name);
851
1052
  const kind = options.capability ? "capability" : fn?.kind ?? "query";
852
1053
  const base = {
853
1054
  kind,
@@ -857,8 +1058,11 @@ export class FeltKitRuntime {
857
1058
  principal: principal ? pick(principal) : null,
858
1059
  ...(options.capability ? { capability: options.capability } : {}),
859
1060
  };
1061
+ const run = options.agentRun?.trigger;
1062
+ 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
1063
  const finish = (entry) => {
861
- this.activity.record({ ...base, durationMs: Math.round(performance.now() - started), ...entry });
1064
+ const detail = agentDetail || entry.detail ? { ...agentDetail, ...entry.detail } : undefined;
1065
+ this.activity.record({ ...base, durationMs: Math.round(performance.now() - started), ...entry, ...(detail ? { detail } : {}) });
862
1066
  };
863
1067
  const failure = (error, extra = {}) => {
864
1068
  const json = this.#errorJSON(error, requestId);
@@ -928,6 +1132,17 @@ export class FeltKitRuntime {
928
1132
  const used = new Set();
929
1133
  const shared = {
930
1134
  auth: authContext(this.#authority, principal),
1135
+ tenancy: {
1136
+ members: async () => {
1137
+ if (!this.tenancy)
1138
+ throw new FeltKitError("CONFIGURATION", "This app has no tenants (auth.tenant).");
1139
+ db.reads.add(MEMBERSHIPS_COLLECTION); // re-run live queries when memberships change
1140
+ const tenantId = principal?.tenant?.id;
1141
+ if (!tenantId)
1142
+ return [];
1143
+ 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 } : {}) }));
1144
+ },
1145
+ },
931
1146
  services: explainServiceDenials(this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", used), name, principal, this.#authority),
932
1147
  environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
933
1148
  requestId,
@@ -955,16 +1170,37 @@ export class FeltKitRuntime {
955
1170
  enabled: { notifications: Boolean(enabled.notifications), webhooks: Boolean(enabled.webhooks), jobs: Boolean(enabled.jobs) },
956
1171
  stage: (record) => db.stageSystem(OUTBOX_COLLECTION, record),
957
1172
  newId: newOutboxId,
1173
+ agent: (agentName, input) => this.#agentEffect(agentName, input, principal, triggeringEvent),
958
1174
  })
959
1175
  : null;
960
- // ctx.events: validated now, published only after the commit (below); never stored.
1176
+ // ctx.events: validated now, published only after the commit (below); never stored. An
1177
+ // application agent whose `on` names the event is recorded now, in this transaction.
961
1178
  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 };
1179
+ let triggeringEvent;
1180
+ const events = {
1181
+ publish: (event, payload, options = {}) => {
1182
+ const staged = stageEvent(this.app, event, payload, options);
1183
+ published.push(staged);
1184
+ for (const definition of this.app.agents.values()) {
1185
+ if (!definition.on.includes(staged.name))
1186
+ continue;
1187
+ triggeringEvent = staged.name;
1188
+ try {
1189
+ effects.agent(definition.name, { event: staged.name, payload: staged.payload, ...(staged.scope !== undefined ? { scope: staged.scope } : {}) });
1190
+ }
1191
+ finally {
1192
+ triggeringEvent = undefined;
1193
+ }
1194
+ }
1195
+ },
1196
+ };
1197
+ // Tenant-scoped collections see only the caller's tenant (the session's, never the request's).
1198
+ const scoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : db;
1199
+ const ctx = fn.kind === "mutation" ? { ...shared, db: scoped, agent, events, afterCommit: effects, unsafe: { feltdb: this.instance.handle("app.unsafe") }, ...(options.agentRun ? { trigger: options.agentRun.trigger } : {}) } : { ...shared, db: scoped };
964
1200
  try {
965
1201
  // feltkit({ authorize }): after roles and validation, with this call's own reader, so its
966
1202
  // reads are fenced at commit (mutations) and tracked for live queries (queries).
967
- await this.#authorizeResource(name, fn, args, principal, options, requestId, db, authorityRecord);
1203
+ await this.#authorizeResource(name, fn, args, principal, options, requestId, scoped, authorityRecord);
968
1204
  const value = await fn.handler(ctx, args);
969
1205
  if (fn.returns) {
970
1206
  const output = validate(fn.returns, value);
@@ -1009,16 +1245,23 @@ export class FeltKitRuntime {
1009
1245
  const { value, db, commit, starts, published } = outcome;
1010
1246
  reads = [...db.reads];
1011
1247
  if (db instanceof Writer && commit) {
1012
- if (commit.writes.length)
1248
+ if (commit.writes.length) {
1249
+ this.changes.describe(commit.described);
1013
1250
  void this.changes.check();
1251
+ }
1014
1252
  // Agent work starts only once the mutation's writes are durable.
1015
1253
  for (const start of starts)
1016
1254
  this.#agent?.startAfterCommit(start, principal);
1017
1255
  // So do after-commit effects: performed now, as the caller, while its binding is live.
1018
1256
  const outbox = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value);
1019
- if (outbox.length) {
1257
+ // Application agents run as themselves, without holding up this call (or its services binding).
1258
+ for (const record of outbox)
1259
+ if (record.effect.service === "agent")
1260
+ this.#dispatchAgent(record.id);
1261
+ const effects = outbox.filter((record) => record.effect.service !== "agent");
1262
+ if (effects.length) {
1020
1263
  const bound = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true, servicesUsed), name, principal, this.#authority);
1021
- for (const record of outbox)
1264
+ for (const record of effects)
1022
1265
  await this.#performOutbox(record, bound, principal, requestId);
1023
1266
  }
1024
1267
  // Ephemeral events: at most once, to whoever is subscribed now (AppPort's event bus).
@@ -1041,7 +1284,8 @@ export class FeltKitRuntime {
1041
1284
  }
1042
1285
  : {}),
1043
1286
  });
1044
- return { ok: true, value: value === undefined ? null : value, reads, requestId };
1287
+ // `reads` for the caller: collection names, then `collection#key` per equality predicate (runtime/live.ts).
1288
+ return { ok: true, value: value === undefined ? null : value, reads: db.reads.report(), requestId };
1045
1289
  }
1046
1290
  }
1047
1291
  catch (error) {
@@ -1163,6 +1407,9 @@ export class FeltKitRuntime {
1163
1407
  clearInterval(this.#worker);
1164
1408
  this.changes.stop();
1165
1409
  await Promise.allSettled([...this.#inflight]);
1410
+ // Agent runs started before the close: their calls now answer UNAVAILABLE, so each is
1411
+ // rescheduled for the services worker (of this process's successor).
1412
+ await this.settleAgents();
1166
1413
  await this.#appport?.close().catch(() => undefined);
1167
1414
  await this.models.close();
1168
1415
  await this.activity.flush();
@@ -1234,19 +1481,27 @@ function replayKey(context, exposure, principal) {
1234
1481
  function idempotentTransactionId(replayKey) {
1235
1482
  return `idem_${createHash("sha256").update(replayKey).digest("hex")}`;
1236
1483
  }
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
- }
1484
+ function invitationMessage(input) {
1485
+ const who = input.inviter ? `${input.inviter} invited you` : "You are invited";
1245
1486
  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.`,
1487
+ subject: `${who} to join ${input.tenant} on ${input.app}`,
1488
+ 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
1489
  };
1249
1490
  }
1491
+ /** The default text of an account e-mail. */
1492
+ function accountMessage(purpose, input) {
1493
+ const { app, link, code, expiresInMinutes: minutes } = input;
1494
+ switch (purpose) {
1495
+ case "reset":
1496
+ 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.` };
1497
+ case "magic-link":
1498
+ 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.` };
1499
+ case "email-change":
1500
+ 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.` };
1501
+ default:
1502
+ 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.` };
1503
+ }
1504
+ }
1250
1505
  /**
1251
1506
  * AppPort Services' e-mail channel (0.13.0+). Looked up when an app sends account e-mail, so an
1252
1507
  * older AppPort Services still runs every other app, and this one says what it needs.