@feltdb/feltkit 0.3.37 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/dist/agent-engine.d.ts +93 -0
  2. package/dist/agent-engine.js +40 -0
  3. package/dist/agent-engine.js.map +1 -0
  4. package/dist/app.d.ts +306 -7
  5. package/dist/app.js +289 -28
  6. package/dist/app.js.map +1 -1
  7. package/dist/appboundry/build.d.ts +7 -0
  8. package/dist/appboundry/build.js +25 -1
  9. package/dist/appboundry/build.js.map +1 -1
  10. package/dist/appboundry/guest.js +8 -0
  11. package/dist/appboundry/guest.js.map +1 -1
  12. package/dist/appboundry/host.d.ts +21 -0
  13. package/dist/appboundry/host.js +25 -0
  14. package/dist/appboundry/host.js.map +1 -1
  15. package/dist/appboundry/runtime.js +1 -0
  16. package/dist/appboundry/runtime.js.map +1 -1
  17. package/dist/boards/index.d.ts +1258 -0
  18. package/dist/boards/index.js +1410 -0
  19. package/dist/boards/index.js.map +1 -0
  20. package/dist/boards/model.d.ts +177 -0
  21. package/dist/boards/model.js +177 -0
  22. package/dist/boards/model.js.map +1 -0
  23. package/dist/boards/react.d.ts +18 -0
  24. package/dist/boards/react.js +339 -0
  25. package/dist/boards/react.js.map +1 -0
  26. package/dist/cli/deploy-appboundry-self-hosted.js +2 -2
  27. package/dist/cli/deploy.js +19 -6
  28. package/dist/cli/deploy.js.map +1 -1
  29. package/dist/cli/main.js +70 -5
  30. package/dist/cli/main.js.map +1 -1
  31. package/dist/client/index.d.ts +454 -4
  32. package/dist/client/index.js +371 -3
  33. package/dist/client/index.js.map +1 -1
  34. package/dist/clock.d.ts +24 -0
  35. package/dist/clock.js +49 -0
  36. package/dist/clock.js.map +1 -0
  37. package/dist/cron.d.ts +18 -0
  38. package/dist/cron.js +67 -0
  39. package/dist/cron.js.map +1 -0
  40. package/dist/dashboard/assets/index-iIj7SL77.js +15 -0
  41. package/dist/dashboard/index.html +1 -1
  42. package/dist/docs.d.ts +1 -1
  43. package/dist/docs.js +4 -0
  44. package/dist/docs.js.map +1 -1
  45. package/dist/eve/index.d.ts +77 -0
  46. package/dist/eve/index.js +128 -0
  47. package/dist/eve/index.js.map +1 -0
  48. package/dist/event-stage.js +2 -0
  49. package/dist/event-stage.js.map +1 -1
  50. package/dist/index.d.ts +17 -2
  51. package/dist/index.js +3 -1
  52. package/dist/index.js.map +1 -1
  53. package/dist/native/build.d.ts +112 -0
  54. package/dist/native/build.js +472 -0
  55. package/dist/native/build.js.map +1 -0
  56. package/dist/native/index.d.ts +67 -0
  57. package/dist/native/index.js +113 -0
  58. package/dist/native/index.js.map +1 -0
  59. package/dist/native/instance.d.ts +3 -0
  60. package/dist/native/instance.js +18 -0
  61. package/dist/native/instance.js.map +1 -0
  62. package/dist/policy.d.ts +9 -1
  63. package/dist/policy.js +16 -3
  64. package/dist/policy.js.map +1 -1
  65. package/dist/presence.d.ts +85 -0
  66. package/dist/presence.js +37 -0
  67. package/dist/presence.js.map +1 -0
  68. package/dist/quota.d.ts +72 -0
  69. package/dist/quota.js +143 -0
  70. package/dist/quota.js.map +1 -0
  71. package/dist/react/agent-control.d.ts +191 -0
  72. package/dist/react/agent-control.js +366 -0
  73. package/dist/react/agent-control.js.map +1 -0
  74. package/dist/react/auth.d.ts +15 -1
  75. package/dist/react/auth.js +28 -5
  76. package/dist/react/auth.js.map +1 -1
  77. package/dist/react/hooks.d.ts +88 -0
  78. package/dist/react/hooks.js +188 -0
  79. package/dist/react/hooks.js.map +1 -0
  80. package/dist/react/index.d.ts +5 -75
  81. package/dist/react/index.js +4 -145
  82. package/dist/react/index.js.map +1 -1
  83. package/dist/runtime/activity.d.ts +8 -0
  84. package/dist/runtime/activity.js.map +1 -1
  85. package/dist/runtime/agent-control.d.ts +28 -0
  86. package/dist/runtime/agent-control.js +43 -2
  87. package/dist/runtime/agent-control.js.map +1 -1
  88. package/dist/runtime/agent-run.d.ts +166 -0
  89. package/dist/runtime/agent-run.js +431 -0
  90. package/dist/runtime/agent-run.js.map +1 -0
  91. package/dist/runtime/agent.d.ts +158 -1
  92. package/dist/runtime/agent.js +345 -12
  93. package/dist/runtime/agent.js.map +1 -1
  94. package/dist/runtime/assemble.js +15 -2
  95. package/dist/runtime/assemble.js.map +1 -1
  96. package/dist/runtime/authority.d.ts +47 -0
  97. package/dist/runtime/authority.js +13 -2
  98. package/dist/runtime/authority.js.map +1 -1
  99. package/dist/runtime/capabilities.js +2 -1
  100. package/dist/runtime/capabilities.js.map +1 -1
  101. package/dist/runtime/changes.d.ts +17 -0
  102. package/dist/runtime/changes.js +65 -2
  103. package/dist/runtime/changes.js.map +1 -1
  104. package/dist/runtime/context.d.ts +123 -0
  105. package/dist/runtime/contract.js +9 -3
  106. package/dist/runtime/contract.js.map +1 -1
  107. package/dist/runtime/events.js +17 -1
  108. package/dist/runtime/events.js.map +1 -1
  109. package/dist/runtime/integrations.js +7 -7
  110. package/dist/runtime/integrations.js.map +1 -1
  111. package/dist/runtime/invocations.d.ts +19 -2
  112. package/dist/runtime/invocations.js +16 -3
  113. package/dist/runtime/invocations.js.map +1 -1
  114. package/dist/runtime/policies.d.ts +5 -2
  115. package/dist/runtime/policies.js.map +1 -1
  116. package/dist/runtime/presence-host.d.ts +84 -0
  117. package/dist/runtime/presence-host.js +303 -0
  118. package/dist/runtime/presence-host.js.map +1 -0
  119. package/dist/runtime/providers.d.ts +5 -1
  120. package/dist/runtime/providers.js +11 -5
  121. package/dist/runtime/providers.js.map +1 -1
  122. package/dist/runtime/required-capabilities.d.ts +73 -0
  123. package/dist/runtime/required-capabilities.js +69 -0
  124. package/dist/runtime/required-capabilities.js.map +1 -0
  125. package/dist/runtime/resource-access.d.ts +137 -0
  126. package/dist/runtime/resource-access.js +177 -0
  127. package/dist/runtime/resource-access.js.map +1 -0
  128. package/dist/runtime/runtime.d.ts +143 -1
  129. package/dist/runtime/runtime.js +853 -44
  130. package/dist/runtime/runtime.js.map +1 -1
  131. package/dist/runtime/sessions.d.ts +12 -0
  132. package/dist/runtime/sessions.js +16 -1
  133. package/dist/runtime/sessions.js.map +1 -1
  134. package/dist/runtime/tenancy.d.ts +68 -1
  135. package/dist/runtime/tenancy.js +150 -0
  136. package/dist/runtime/tenancy.js.map +1 -1
  137. package/dist/runtime/transactions.d.ts +3 -1
  138. package/dist/runtime/transactions.js.map +1 -1
  139. package/dist/runtime/workers.d.ts +123 -0
  140. package/dist/runtime/workers.js +291 -0
  141. package/dist/runtime/workers.js.map +1 -0
  142. package/dist/server/eve.d.ts +287 -0
  143. package/dist/server/eve.js +1071 -0
  144. package/dist/server/eve.js.map +1 -0
  145. package/dist/server/index.d.ts +2 -19
  146. package/dist/server/index.js +102 -5
  147. package/dist/server/index.js.map +1 -1
  148. package/dist/server/mcp.d.ts +15 -22
  149. package/dist/server/mcp.js +40 -3
  150. package/dist/server/mcp.js.map +1 -1
  151. package/dist/server/project.js +26 -8
  152. package/dist/server/project.js.map +1 -1
  153. package/dist/server/tenancy.d.ts +9 -0
  154. package/dist/server/tenancy.js +62 -1
  155. package/dist/server/tenancy.js.map +1 -1
  156. package/dist/server/watch.d.ts +10 -0
  157. package/dist/server/watch.js +88 -0
  158. package/dist/server/watch.js.map +1 -0
  159. package/dist/testing/index.d.ts +4 -5
  160. package/dist/testing/index.js +3 -2
  161. package/dist/testing/index.js.map +1 -1
  162. package/docs/AGENT-CONTROL.md +166 -4
  163. package/docs/APPBOUNDRY.md +73 -0
  164. package/docs/ARCHITECTURE.md +6 -2
  165. package/docs/AUTH.md +37 -0
  166. package/docs/COMPONENTS.md +71 -0
  167. package/docs/EVE-COMPOSITION.md +75 -0
  168. package/docs/GUARANTEES.md +4 -4
  169. package/docs/NATIVE-AGENTS.md +353 -0
  170. package/docs/NATIVE.md +137 -0
  171. package/docs/PRESENCE-AND-SIGNALING-PROPOSAL.md +152 -0
  172. package/docs/README.md +6 -2
  173. package/docs/SECURITY.md +71 -3
  174. package/docs/TRANSACTIONS.md +48 -0
  175. package/docs/UPSTREAM-GAPS.md +16 -2
  176. package/package.json +42 -16
  177. package/skills/.claude-plugin/marketplace.json +1 -1
  178. package/skills/.claude-plugin/plugin.json +1 -1
  179. package/skills/feltkit-agent/SKILL.md +1 -1
  180. package/skills/feltkit-build/SKILL.md +11 -1
  181. package/skills/feltkit-data/SKILL.md +1 -1
  182. package/skills/feltkit-operations/SKILL.md +1 -1
  183. package/skills/feltkit-services/SKILL.md +1 -1
  184. package/dist/dashboard/assets/index-BhxrvY37.js +0 -15
@@ -8,12 +8,19 @@
8
8
  * close() is idempotent and releases the instance.
9
9
  */
10
10
  import { JOB_CONTEXTS_COLLECTION, jobIdOfRun } from "./job-context.js";
11
+ import { unavailableCapabilities } from "./required-capabilities.js";
11
12
  import { checkTokenBytes } from "./crypto-token.js";
12
13
  import { evaluateAuthorize, evaluateOwnership } from "../authorize.js";
13
14
  import { evaluatePolicies, viaCollections } from "../policy.js";
14
15
  import { PolicyStore } from "./policies.js";
15
16
  import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
16
- import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
17
+ import { systemClock } from "../clock.js";
18
+ import { PresenceHost } from "./presence-host.js";
19
+ import { GUEST_SESSION_MAX_MS, MAX_ACCESS_TTL_MS, resourceRefusal, ResourceAccessStore, loadBoundResource } from "./resource-access.js";
20
+ import { presenceOf } from "../presence.js";
21
+ import { QuotaLimiter, rateLimited } from "../quota.js";
22
+ import { AppPortError, combineAuthorizers, outcomeUnknown, runEffectful, createApplication, defineCapability, createMcpBridge, delegatedAuthorityAuthorizer, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
23
+ import { WorkerAuthority, WORKER_PREFIX } from "./workers.js";
17
24
  import { grantsPermission } from "@appport/authorization";
18
25
  import { AsyncLocalStorage } from "node:async_hooks";
19
26
  import { AGENT_CONTROL_EXTENSION, agentControlCapabilities } from "./agent-control-capabilities.js";
@@ -21,7 +28,7 @@ import { performance } from "node:perf_hooks";
21
28
  import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
22
29
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
23
30
  import { dirname, join } from "node:path";
24
- import { AGENT_MAX_BACKOFF_MS } from "../app.js";
31
+ import { AGENT_MAX_BACKOFF_MS, AGENT_RUN, uniqueField } from "../app.js";
25
32
  import { IntegrationHost, integrationDescriptor } from "./integrations.js";
26
33
  import { applicationAuthority } from "./application-authority.js";
27
34
  import { verifyStorage } from "./storage-check.js";
@@ -43,13 +50,17 @@ import { applySchema, blockedHint, describePlan, MIGRATIONS_COLLECTION, planSche
43
50
  import { afterCommit, newOutboxId, OUTBOX_COLLECTION, performEffect } from "./outbox.js";
44
51
  import { claimed, isRecoverable, isSequenceConflict, outboxStore, performOutbox, rescheduled, retried, settled } from "./transactions.js";
45
52
  import { OAuthCredentials } from "./oauth-credentials.js";
46
- import { INVOCATIONS_COLLECTION, InvocationStore } from "./invocations.js";
53
+ import { INVOCATIONS_COLLECTION, InvocationStore, workItemScoped } from "./invocations.js";
47
54
  import { ExecutionHost } from "./execution-host.js";
48
55
  import { LocalAuthorityHost, applicationCapabilities, authorityAgentId } from "./local-authority.js";
49
56
  import { authorityPrincipalOf } from "./application-authority.js";
50
57
  import { verifyDelegation } from "./delegation.js";
51
58
  import { credentialsFor, isCustodyError } from "./credentials.js";
52
- import { AgentHost } from "./agent.js";
59
+ import { AgentHost, AGENT_PERMISSIONS } from "./agent.js";
60
+ import { runReasoningAgent, runBusy, RUN_KIND, LEASE_KIND } from "./agent-run.js";
61
+ import { AGENT_CONTROL_EVENT, agentTaskScope, defineEvent, taskIdOfAgentScope } from "@appport/sdk";
62
+ import { toSchema } from "@appport/schema";
63
+ import { SEQUENCES_COLLECTION } from "./transactions.js";
53
64
  import { FeltDbIdempotencyStore } from "./idempotency.js";
54
65
  import { capabilityDefinition } from "./capabilities.js";
55
66
  import { FeltDbSessionStore, sessionRef } from "./sessions.js";
@@ -71,6 +82,10 @@ const NODE_TENANCY_CRYPTO = {
71
82
  export const SESSION_EXPIRY_SWEEP_MS = 5_000;
72
83
  /** Attempts at running auth.onSessionEnd for one ended session before it is kept as failed. */
73
84
  export const SESSION_END_MAX_ATTEMPTS = 10;
85
+ /** The appport.agent-control/1 operations a person uses, offered as MCP tools. */
86
+ const MCP_AGENT_CONTROL = new Set(["state", "signal", "submit", "withdraw", "pause", "resume", "interrupt", "stop"].map((op) => `appport.agent.${op}`));
87
+ /** How often the services tick reconciles agent runs. */
88
+ export const AGENT_RECONCILE_MS = 15_000;
74
89
  const consoleLogger = {
75
90
  info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
76
91
  warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
@@ -154,14 +169,48 @@ export class FeltKitRuntime {
154
169
  get settings() {
155
170
  return this.#env;
156
171
  }
157
- constructor(environment, instance, logger, env = process.env) {
172
+ /** The clock leases and quotas read (RuntimeStartOptions.clock). */
173
+ clock;
174
+ /** Call quotas (src/quota.ts): in-process sliding windows. */
175
+ quotas;
176
+ /** Presence leases (app.presence): ctx.presence, the live view, expiry and session ends (runtime/presence-host.ts). */
177
+ presence;
178
+ /** Guest links and agent grants: access to one resource (runtime/resource-access.ts). */
179
+ access;
180
+ /** Workers, their work grants, and people's approvals of exact calls (runtime/workers.ts). */
181
+ workers;
182
+ constructor(environment, instance, logger, env = process.env, clock = systemClock) {
158
183
  this.#env = env;
184
+ this.clock = clock;
185
+ this.quotas = new QuotaLimiter(clock);
186
+ this.access = new ResourceAccessStore(() => instance.handle("feltkit.access"), clock);
187
+ this.workers = new WorkerAuthority(() => instance.handle("feltkit.access"), clock);
188
+ this.presence = new PresenceHost({
189
+ app: () => this.app,
190
+ handle: () => this.instance.handle("app"),
191
+ resolver: () => this.#resolver,
192
+ clock,
193
+ agentEffect: (name, input, tenantId) => this.#agentEffect(name, input, null, undefined, tenantId),
194
+ committed: (commit, outbox) => {
195
+ if (commit.writes.length) {
196
+ this.changes.describe(commit.described);
197
+ void this.changes.check();
198
+ }
199
+ for (const record of outbox)
200
+ if (record.effect.service === "agent")
201
+ this.#dispatchAgent(record.id);
202
+ },
203
+ warn: (message) => this.logger.warn(message),
204
+ });
159
205
  this.environment = environment;
160
206
  this.instance = instance;
161
207
  this.logger = logger;
162
208
  this.sessions = new FeltDbSessionStore(instance.handle("feltkit.sessions"));
163
209
  this.activity = new ActivityLog(instance.handle("feltkit.activity"), { mode: environment.production ? "writes" : "all", evidence: (runId) => this.#services.evidence(runId) });
164
- this.changes = new ChangeFeed(instance.handle("feltkit.changes"), { remote: environment.storage.kind === "remote" });
210
+ // FELTKIT_CHANGE_POLL_MS: the fallback poll of the change feed (default 1 s embedded and 5 s on a server with commit
211
+ // notices; 150 ms and 1 s without them).
212
+ const pollMs = Number(env.FELTKIT_CHANGE_POLL_MS);
213
+ this.changes = new ChangeFeed(instance.handle("feltkit.changes"), { remote: environment.storage.kind === "remote", ...(Number.isFinite(pollMs) && pollMs >= 50 ? { intervalMs: Math.floor(pollMs) } : {}) });
165
214
  this.idempotency = new FeltDbIdempotencyStore(instance.handle("appport.idempotency"));
166
215
  this.models = new ModelHost(this, { env });
167
216
  this.integrations = new IntegrationHost(this);
@@ -191,7 +240,7 @@ export class FeltKitRuntime {
191
240
  const instance = factory.open(options.environment);
192
241
  let runtime;
193
242
  try {
194
- runtime = new FeltKitRuntime(options.environment, instance, logger, options.env ?? process.env);
243
+ runtime = new FeltKitRuntime(options.environment, instance, logger, options.env ?? process.env, options.clock ?? systemClock);
195
244
  await runtime.providers.sync(options.project.app.options.providers, options.project.projectDir ?? process.cwd());
196
245
  runtime.#install(options.project);
197
246
  // How long each startup step took: on a FeltDB server each is network round trips, and a
@@ -217,16 +266,31 @@ export class FeltKitRuntime {
217
266
  step("markers");
218
267
  await runtime.#services.check();
219
268
  step("services");
269
+ // A reasoning agent records its own work as agent tasks: its roles must say so, explicitly.
270
+ for (const agent of options.project.app.agents.values()) {
271
+ if (!agent.reasoning)
272
+ continue;
273
+ const permissions = runtime.#authority.permissionsFor({ id: agent.principal.id, type: "agent", roles: [...agent.roles] });
274
+ if (!grantsPermission(permissions, AGENT_PERMISSIONS.write)) {
275
+ throw new FeltKitError("CONFIGURATION", `app.agent("${agent.name}") is a reasoning agent: it records its work as agent tasks, so its roles (${agent.roles.join(", ") || "none"}) must grant ${AGENT_PERMISSIONS.write}.`, { hint: `Add "${AGENT_PERMISSIONS.write}" to one of its roles in feltkit({ roles }).` });
276
+ }
277
+ }
220
278
  // FeltDB's agent runtime and agent state, on this instance (see runtime/agent.ts).
221
279
  runtime.#agent = new AgentHost(runtime, instance.handle("feltdb.agent"), {
222
280
  separateApprover: options.environment.production,
223
281
  ...(options.agentActionTimeoutMs ? { actionTimeoutMs: options.agentActionTimeoutMs } : {}),
224
282
  ...(options.agentHooks ? { hooks: options.agentHooks } : {}),
283
+ onSettled: (taskId, actionId) => runtime.resumeAgentRun(taskId, `settled:${actionId}`),
225
284
  });
285
+ if (options.agentRunLeaseMs)
286
+ runtime.#runLeaseMs = options.agentRunLeaseMs;
287
+ runtime.#agentHooks = options.agentHooks;
226
288
  await runtime.#agent.open();
227
289
  step("agent");
228
290
  runtime.changes.start();
229
291
  runtime.#state = "ready";
292
+ // Leases that expired while no process ran end now; the timer is armed for the next expiry.
293
+ await runtime.presence.sweep();
230
294
  // Actions an earlier process left open, settled from evidence (never re-executed).
231
295
  // After "ready": settling may run an integration's outcome hook, which is a function call.
232
296
  await runtime.#agent.reconcile();
@@ -434,7 +498,7 @@ export class FeltKitRuntime {
434
498
  if (!live)
435
499
  return null;
436
500
  const input = {
437
- app: app.options.description ?? app.name,
501
+ app: appTitle(app.name),
438
502
  link: this.invitationLink(live.token),
439
503
  tenant: live.tenantName,
440
504
  role: live.invitation.role,
@@ -452,7 +516,7 @@ export class FeltKitRuntime {
452
516
  if (!live)
453
517
  return null; // used, superseded or expired before delivery: send nothing
454
518
  const link = `${this.publicUrl()}/#feltkit-${live.purpose}=${live.token}`;
455
- 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)) };
519
+ const input = { app: appTitle(app.name), link, code: live.code, email: live.data.email ?? "", expiresInMinutes: Math.max(1, Math.round((live.expiresAt - Date.now()) / 60_000)) };
456
520
  const template = accounts.email.templates?.[live.purpose];
457
521
  return template ? template(input) : accountMessage(live.purpose, input);
458
522
  },
@@ -473,7 +537,7 @@ export class FeltKitRuntime {
473
537
  // The job, not the attempt, is the unit of effect: a re-run (lease expired after the commit) replays the
474
538
  // first commit by its transaction id instead of committing again.
475
539
  const jobId = runId.slice(0, runId.lastIndexOf(":") > 0 ? runId.lastIndexOf(":") : runId.length);
476
- const result = await this.call(fn, payload, { principal, via: "job", requestId: `job_${runId}`, idempotencyReplayKey: `job:${jobId}` });
540
+ const result = await this.call(fn, payload, { principal, via: "job", internal: true, requestId: `job_${runId}`, idempotencyReplayKey: `job:${jobId}` });
477
541
  // An earlier attempt of this job committed (its completion was lost): the job happened, once. A job's value is not kept.
478
542
  if (!result.ok && result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true) {
479
543
  this.logger.info?.(`job ${jobId}: an earlier attempt committed; not performed again`, { requestId: `job_${runId}` });
@@ -484,7 +548,7 @@ export class FeltKitRuntime {
484
548
  },
485
549
  // An inbound webhook's handler: the declared mutation, as `integration:<provider>` (no tenant).
486
550
  runInbound: async (fn, principal, event) => {
487
- const result = await this.call(fn, { event }, { principal, via: "integration", requestId: `inbound_${String(event.integrationId)}_${String(event.eventId)}`.slice(0, 200) });
551
+ const result = await this.call(fn, { event }, { principal, via: "integration", internal: true, requestId: `inbound_${String(event.integrationId)}_${String(event.eventId)}`.slice(0, 200) });
488
552
  if (!result.ok)
489
553
  throw Object.assign(new Error(`${result.error.code}: ${result.error.message}`), { code: result.error.code });
490
554
  return result.value;
@@ -529,8 +593,42 @@ export class FeltKitRuntime {
529
593
  extensions: [AGENT_CONTROL_EXTENSION],
530
594
  capabilities,
531
595
  // app.event(): AppPort events; observation is authorized by roles, then feltkit({ authorize }).
532
- events: eventDefinitions(app),
533
- authorizer: this.#delegatedAuthorizer(observationAuthorizer(app, authority.authorizer, () => new Reader(this.instance.handle("app"), new CollectionResolver(app.collections)))),
596
+ // app.event()s, and agent control's change event (appport.agent.changed@1, spec/agent-control-1.md §7).
597
+ events: [...eventDefinitions(app), defineEvent({ name: AGENT_CONTROL_EVENT.name, version: 1, description: "A task's control state changed (durably): its revision, phase, mode, what changed, and a per-task sequence.", payload: toSchema(AGENT_CONTROL_EVENT.payloadSchema), authorization: [AGENT_PERMISSIONS.read] })],
598
+ // Workers act under work grants, and approvals bind to exact calls (runtime/workers.ts): AppPort's own delegated
599
+ // authority rules over FeltKit's durable records. #call checks the same records again on every surface.
600
+ authorizer: combineAuthorizers([
601
+ this.#delegatedAuthorizer(observationAuthorizer(app, authority.authorizer, () => new Reader(this.instance.handle("app"), new CollectionResolver(app.collections)))),
602
+ // appport.agent.changed: observed only by someone who may read the task, subscribed to that task's scope.
603
+ {
604
+ name: "agent-changed",
605
+ authorize: async (request) => {
606
+ if (request.capability?.name !== AGENT_CONTROL_EVENT.name)
607
+ return { allowed: true };
608
+ const scope = request.input?.scope;
609
+ const taskId = typeof scope === "string" ? taskIdOfAgentScope(scope) : undefined;
610
+ if (!taskId)
611
+ return { allowed: false, code: "FORBIDDEN", reason: `Subscribe to one task's changes: scope ${agentTaskScope("<taskId>")}.` };
612
+ const principal = fromAppPortPrincipal((request.principal ?? request.session?.principal));
613
+ if (!principal)
614
+ return { allowed: false, code: "UNAUTHORIZED", reason: "Sign in to observe agent tasks." };
615
+ try {
616
+ await this.agent.control.view(taskId, principal);
617
+ return { allowed: true };
618
+ }
619
+ catch {
620
+ return { allowed: false, code: "FORBIDDEN", reason: "Not a reader of this task." };
621
+ }
622
+ },
623
+ },
624
+ // A worker needs a grant for everything but the protocol's own description and its own calls' status.
625
+ delegatedAuthorityAuthorizer({ grants: this.workers, approvals: this.workers, require: (request) => typeof (request.principal ?? request.session?.principal)?.attributes?.feltkitWorker === "string" && !WORKER_UNGRANTED.includes(request.capability.name), now: () => this.clock.now() }),
626
+ ]),
627
+ // A capability that publishes `integration.approval.required` runs only with an approval the authorizer verified.
628
+ enforceApprovals: true,
629
+ // `appport.invocation.status@1`: "what happened to my call?", the caller's own calls only, answered from the
630
+ // idempotency records and the external effect records (actions' ctx.effect and providers' calls, one recorder).
631
+ reconciliation: { calls: this.providers.effectRecorder() },
534
632
  db: this.instance.handle("appport"),
535
633
  sessions: this.sessions,
536
634
  // Durable replay protection for capabilities that declare idempotency: the claim is
@@ -544,7 +642,7 @@ export class FeltKitRuntime {
544
642
  // Every transport (HTTP, WebSocket, MCP) dispatches through these two methods.
545
643
  for (const method of ["handleRequest", "handleStreamRequest"]) {
546
644
  const original = appport[method].bind(appport);
547
- appport[method] = (request, options = {}) => this.#appportCaller.run(callerScope(options?.principal ?? options?.session?.principal), () => original(request, options));
645
+ appport[method] = (request, options = {}) => this.#appportCaller.run({ ...callerScope(options?.principal ?? options?.session?.principal), ...(request?.invocation ? { invocation: request.invocation } : {}) }, () => original(request, options));
548
646
  }
549
647
  // auth.onSessionEnd: a mutation of this application; ends are recorded only when one is declared.
550
648
  const sessionEndHook = project.app.options.auth?.onSessionEnd;
@@ -553,13 +651,16 @@ export class FeltKitRuntime {
553
651
  if (!target || target.kind !== "mutation")
554
652
  throw new FeltKitError("CONFIGURATION", `auth.onSessionEnd: ${JSON.stringify(sessionEndHook)} is not a mutation of this application (write "<module>:<export>").`);
555
653
  }
556
- this.sessions.recordEnds = sessionEndHook !== undefined;
654
+ // Presence leases end with their holder's session, so ends are recorded for them too.
655
+ const hasPresence = [...project.app.collections.values()].some((c) => presenceOf(c));
656
+ this.sessions.recordEnds = sessionEndHook !== undefined || hasPresence;
557
657
  this.sessions.onEnd = () => void this.runSessionEnds();
558
658
  this.#project = project;
559
659
  this.#authority = authority;
560
660
  this.#services = services;
561
661
  this.#appport = appport;
562
662
  this.#resolver = new CollectionResolver(app.collections);
663
+ this.presence.check();
563
664
  this.#generation += 1;
564
665
  }
565
666
  /** One AuthBoundry decision as the application's executor (a person's connection: runtime/integrations.ts). Recorded like ctx.authority's. */
@@ -608,6 +709,62 @@ export class FeltKitRuntime {
608
709
  functionAccess(name) {
609
710
  return this.#project.functions.get(name)?.access;
610
711
  }
712
+ /**
713
+ * The permissions a function requires (`access`), by the capability it publishes or, for one that publishes none (an
714
+ * internal job handler recording an effect), by its name; null when there is no such function.
715
+ */
716
+ capabilityAccess(capability) {
717
+ const fn = [...(this.#project?.functions.values() ?? [])].find((f) => f.capability?.name === capability) ?? this.#project?.functions.get(capability);
718
+ return fn ? Authority.required(fn.access) : null;
719
+ }
720
+ /** Per task: the emission of appport.agent.changed events, in order, in this process. */
721
+ #agentEvents = new Map();
722
+ #agentEventId(taskId) {
723
+ const id = `agent-changed.${taskId}`;
724
+ return /^[A-Za-z0-9._-]{1,128}$/.test(id) ? id : `_agent-changed.${createHash("sha256").update(taskId).digest("hex")}`;
725
+ }
726
+ /** The `sequence` of the last appport.agent.changed event for a task (0 before any), from its durable counter. */
727
+ async agentChangeSequence(taskId) {
728
+ const record = (await this.instance.handle("feltkit.agent-events").collection(SEQUENCES_COLLECTION).get(this.#agentEventId(taskId)));
729
+ return typeof record?.value === "number" ? record.value : 0;
730
+ }
731
+ /**
732
+ * A task's control state changed durably (runtime/agent-control.ts): allocate the next per-task sequence (a durable
733
+ * counter, compare-and-set, so it survives restarts and never repeats) and publish appport.agent.changed@1 with the
734
+ * state as that change left it, scoped to the task. Emissions for one task are serialized in this process.
735
+ */
736
+ agentChanged(taskId, changes, instructionId, state) {
737
+ // A person resumed a held task: a reasoning run that stopped at its boundary continues.
738
+ if (changes.includes("mode") && state.mode === "running")
739
+ this.resumeAgentRun(taskId, `control:${state.revision}`);
740
+ const previous = this.#agentEvents.get(taskId) ?? Promise.resolve();
741
+ const next = previous.then(() => this.#emitAgentChanged(taskId, changes, instructionId, state)).catch((error) => this.logger.warn(`appport.agent.changed for ${taskId} was not published: ${error.message}`));
742
+ this.#agentEvents.set(taskId, next);
743
+ void next.finally(() => {
744
+ if (this.#agentEvents.get(taskId) === next)
745
+ this.#agentEvents.delete(taskId);
746
+ });
747
+ return next;
748
+ }
749
+ async #emitAgentChanged(taskId, changes, instructionId, state) {
750
+ const db = this.instance.handle("feltkit.agent-events");
751
+ const id = this.#agentEventId(taskId);
752
+ let sequence = 0;
753
+ for (let attempt = 0; attempt < 8 && !sequence; attempt++) {
754
+ const current = (await db.collection(SEQUENCES_COLLECTION).get(id));
755
+ const value = (current?.value ?? 0) + 1;
756
+ try {
757
+ await db.transaction({ operations: [{ collection: SEQUENCES_COLLECTION, id, ...(current ? { ifVersion: current.__version } : { requireAbsent: true }), value: { name: id, value, transactionId: `agent-changed-${randomUUID()}` } }] });
758
+ sequence = value;
759
+ }
760
+ catch {
761
+ /* another process advanced it: read again */
762
+ }
763
+ }
764
+ if (!sequence)
765
+ throw new Error("the event sequence kept changing");
766
+ await this.#appport.emit({ name: AGENT_CONTROL_EVENT.name, version: 1, payload: { taskId, revision: state.revision, sequence, phase: state.phase, mode: state.mode, changes: [...new Set(changes)], ...(instructionId ? { instructionId } : {}) }, scope: agentTaskScope(taskId) });
767
+ }
611
768
  /** Whether `principal` holds `access` under this application's roles ("public" and "authenticated" as functions treat them). */
612
769
  holds(principal, access) {
613
770
  if (access === "public")
@@ -836,11 +993,16 @@ export class FeltKitRuntime {
836
993
  return;
837
994
  if (!scope.principal)
838
995
  throw appportErrors.unauthorized("Authentication is required");
996
+ const name0 = [...this.#project.functions.entries()].find(([, f]) => f === fn)?.[0] ?? fn.capability?.name ?? "";
997
+ const hidden = fn.visibility ? visibilityRefusalFor(name0, fn.visibility, scope.principal) : null;
998
+ if (hidden)
999
+ throw hidden.code === "FORBIDDEN" ? appportErrors.forbidden(hidden.message, { visibility: fn.visibility }) : appportErrors.unauthorized(hidden.message);
839
1000
  const required = Authority.required(fn.access);
840
1001
  if (required.length && !grantsPermission(this.#authority.permissionsFor(scope.principal), required[0]))
841
1002
  throw appportErrors.forbidden(`Missing permission: ${required[0]}`);
842
1003
  const name = [...this.#project.functions.entries()].find(([, f]) => f === fn)?.[0] ?? fn.capability?.name ?? "";
843
- const refusal = this.#approvalRefusal(name, fn, scope.principal);
1004
+ // A named approval is verified by the authorizer and again at execution, against this exact input.
1005
+ const refusal = scope.invocation?.approvalRef ? null : this.#approvalRefusal(name, fn, scope.principal);
844
1006
  if (refusal)
845
1007
  throw appportErrors.forbidden(refusal, { approval: "required" });
846
1008
  }
@@ -861,7 +1023,9 @@ export class FeltKitRuntime {
861
1023
  capability: { name: exposure.name, version: exposure.version },
862
1024
  ...(context.authorizationDecision?.decisionId ? { appportDecisionId: context.authorizationDecision.decisionId } : {}),
863
1025
  ...(fn.kind === "mutation" && context.idempotencyKey ? { idempotencyReplayKey: replayKey(context, exposure, principal) } : {}),
1026
+ ...(context.idempotencyKey ? { idempotencyKey: String(context.idempotencyKey) } : {}),
864
1027
  ...(delegation ? { delegation } : {}),
1028
+ ...(context.invocation ? { invocation: { claimed: { ...(context.invocation.claimed ?? {}) } } } : {}),
865
1029
  // A delegated call acts for the person under the agent's session: it binds to no session of theirs.
866
1030
  ...(!delegation && sessionRef(context.session?.id) ? { session: { ref: sessionRef(context.session?.id) } } : {}),
867
1031
  });
@@ -923,13 +1087,53 @@ export class FeltKitRuntime {
923
1087
  // An account session is resolved again on every request: the account as it is now (a
924
1088
  // disabled or deleted account has no session; changed roles apply at once), never the copy
925
1089
  // taken at sign-in. Dev, CLI and agent sessions carry the roles their issuer gave them.
1090
+ // A guest session (K4): resolved from its link on every request; a revoked or expired link ends it at once.
1091
+ if (attributes.kind === "guest") {
1092
+ const linkId = session?.attributes?.guestLink;
1093
+ const link = typeof linkId === "string" ? await this.access.liveGuestLink(linkId) : null;
1094
+ if (!link || !this.app.options.auth?.guests?.roles.includes(link.role))
1095
+ return null;
1096
+ return { id: principal.id, type: "user", roles: [link.role], ...(principal.displayName ? { displayName: principal.displayName } : {}), guest: { link: link.id, resource: { ...link.resource }, expiresAt: new Date(link.expiresAt).toISOString() } };
1097
+ }
1098
+ // A worker session: resolved from its registration on every request; a revoked or expired worker is refused at once.
1099
+ if (attributes.kind === "worker") {
1100
+ const registrationId = session?.attributes?.worker;
1101
+ const registration = typeof registrationId === "string" ? await this.workers.liveWorker(registrationId) : null;
1102
+ if (!registration || registration.principalId !== principal.id)
1103
+ return null;
1104
+ return this.withTenant({ id: principal.id, type: "agent", roles: [...(registration.roles ?? [])], ...(registration.label ? { displayName: registration.label } : {}), worker: { id: registration.id } }, registration.tenantId);
1105
+ }
926
1106
  if (attributes.kind === "account") {
927
1107
  const account = this.accounts ? await this.accounts.get(principal.id) : null;
928
1108
  if (!account || account.disabled)
929
1109
  return null;
930
1110
  principal = { ...principal, roles: [...account.roles], displayName: account.name ?? account.email };
931
1111
  }
932
- return this.withTenant(principal, typeof attributes.tenantId === "string" ? attributes.tenantId : undefined);
1112
+ const previewRole = session?.attributes?.previewRole;
1113
+ return this.previewAs(await this.withTenant(principal, typeof attributes.tenantId === "string" ? attributes.tenantId : undefined), typeof previewRole === "string" ? previewRole : undefined);
1114
+ }
1115
+ /**
1116
+ * A member previewing the application as a lower role of their tenant: only the accounts' base roles and that
1117
+ * role, marked `preview` (every write is then refused). A role that is not below theirs, or no tenant, previews
1118
+ * nothing: the principal is returned as it is.
1119
+ */
1120
+ previewAs(principal, role) {
1121
+ const tenant = principal.tenant;
1122
+ if (!role || !tenant || !this.tenancy || this.tenancy.rank(role) < 0 || this.tenancy.rank(role) > this.tenancy.rank(tenant.role) || role === tenant.role)
1123
+ return principal;
1124
+ const base = this.app.options.auth?.accounts?.roles ?? [];
1125
+ return { ...principal, roles: [...new Set([...base, role])], tenant: { ...tenant, role, claims: { ...tenant.claims, role } }, preview: { role, actualRole: tenant.role } };
1126
+ }
1127
+ /**
1128
+ * A worker as it is now, from its active registration (the same resolution as a worker session's): its
1129
+ * registered roles, in the tenant it was registered in, through its live membership there. Null when no
1130
+ * registration of that principal is active.
1131
+ */
1132
+ async workerPrincipal(principalId) {
1133
+ const registration = await this.workers.activeWorker(principalId);
1134
+ if (!registration)
1135
+ return null;
1136
+ return this.withTenant({ id: principalId, type: "agent", roles: [...(registration.roles ?? [])], ...(registration.label ? { displayName: registration.label } : {}), worker: { id: registration.id } }, registration.tenantId);
933
1137
  }
934
1138
  /**
935
1139
  * The principal working in a tenant: the live membership's role joins its roles, and its claims
@@ -992,6 +1196,9 @@ export class FeltKitRuntime {
992
1196
  return null;
993
1197
  }
994
1198
  async #resolveStrict(subjectId) {
1199
+ // A guest has no durable authority: work it queued does not run as it later.
1200
+ if (subjectId.startsWith("guest:"))
1201
+ return null;
995
1202
  const declared = this.declaredPrincipal(subjectId);
996
1203
  if (declared)
997
1204
  return declared;
@@ -1230,6 +1437,144 @@ export class FeltKitRuntime {
1230
1437
  const tenantId = principal?.tenant?.id ?? tenant;
1231
1438
  return { service: "agent", method: "run", agent: name, input, ...(tenantId ? { tenantId } : {}), ...(event ? { event } : {}) };
1232
1439
  }
1440
+ /** Reasoning attempts executing in this process now, per agent (limits.concurrency). */
1441
+ #reasoningActive = new Map();
1442
+ /** An attempt refused because the run (or the agent's concurrency) was busy: when to try it again. */
1443
+ #busyUntil = new Map();
1444
+ #lastReconcile = 0;
1445
+ #runLeaseMs;
1446
+ #agentHooks;
1447
+ #reconciling;
1448
+ /**
1449
+ * A new attempt of the reasoning run on `taskId`, when it is open and owned by one of this application's
1450
+ * reasoning agents: an outbox record keyed by the task and `cause` (written once, `requireAbsent`: a repeated
1451
+ * cause, from this process or another, adds nothing), run now and recovered by the services worker like any
1452
+ * agent run. Nothing is decided here: the attempt takes the run's lease, reads its state and continues only
1453
+ * where something changed. Returns the record's id when this call created it.
1454
+ */
1455
+ resumeAgentRun(taskId, cause) {
1456
+ if (this.#agentHooks?.dropResumes)
1457
+ return Promise.resolve(null);
1458
+ const work = this.#writeResume(taskId, cause).catch((error) => {
1459
+ this.logger.warn(`agent run on ${taskId}: resuming after ${cause}: ${error.message}`);
1460
+ return null;
1461
+ });
1462
+ this.#agentRuns.add(work);
1463
+ void work.finally(() => this.#agentRuns.delete(work));
1464
+ return work;
1465
+ }
1466
+ async #writeResume(taskId, cause) {
1467
+ const task = await this.#agent.taskStatus(taskId);
1468
+ if (!task || task.status === "completed" || task.status === "cancelled" || !task.owner.startsWith("agent:"))
1469
+ return null;
1470
+ const definition = [...this.app.agents.values()].find((a) => a.reasoning && `agent:${a.principal.id}` === task.owner);
1471
+ if (!definition)
1472
+ return null;
1473
+ const run = (await this.#agent.memoriesOf(taskId, "admin", RUN_KIND))[0]?.content;
1474
+ if (!run || run.agent !== definition.name)
1475
+ return null;
1476
+ const id = `outbox_resume_${createHash("sha256").update(`${taskId}\u0000${cause}`).digest("hex").slice(0, 32)}`;
1477
+ const now = Date.now();
1478
+ const record = { id, requestId: `resume_${id}`, function: `agent/${definition.name}`, principalId: definition.principal.id, ...(run.tenantId ? { tenantId: run.tenantId } : {}), effect: { service: "agent", method: "run", agent: definition.name, input: run.input, run: run.runId, ...(run.tenantId ? { tenantId: run.tenantId } : {}) }, state: "pending", createdAt: now, updatedAt: now, attempts: 0 };
1479
+ try {
1480
+ await this.instance.handle("app").transaction({ operations: [{ collection: OUTBOX_COLLECTION, id, requireAbsent: true, value: record }] });
1481
+ }
1482
+ catch {
1483
+ return null; // this cause already resumed the run
1484
+ }
1485
+ this.#agentHooks?.afterResumeRecorded?.({ taskId, resumeId: id });
1486
+ this.#dispatchAgent(id);
1487
+ return id;
1488
+ }
1489
+ /**
1490
+ * Agent run reconciliation: find reasoning runs that should be executing and are not, from durable state only,
1491
+ * and resume each through the outbox. Part of the services tick (at most every 15 s), and safe to call at any
1492
+ * time, from any number of processes:
1493
+ *
1494
+ * proposal past its approval window expired (cancelled), as approve() would; the run then resumes
1495
+ * released "waiting", every waited-on resume: a person decided (approve, reject, settle) or it expired, and
1496
+ * action now decided the resume record was never written or never ran
1497
+ * released "held", task running again resume: a person resumed it
1498
+ * lease expired, never released resume, unless the outbox record of the attempt that held it is still
1499
+ * pending or performing (outbox recovery takes that one over)
1500
+ * no lease at all, task older than 30 s resume: the first attempt stopped before taking the run
1501
+ * released "completed"/"stopped", resume: the attempt released before its task's end was recorded
1502
+ * task still open
1503
+ *
1504
+ * Never resumed: a live lease (an attempt is executing), "error" (the outbox retries it or it failed; an operator
1505
+ * decides), a proposal still waiting for a person, an outcome a person must settle, a paused task. Each resume is
1506
+ * keyed by the lease link it reads and the states of what it waited on, so the same state resumes once however
1507
+ * often or concurrently this runs; each is recorded on the task (`<task>.recovery-…`) and in the activity log.
1508
+ */
1509
+ reconcileAgentRuns(options = {}) {
1510
+ const reasoning = [...this.app.agents.values()].filter((a) => a.reasoning);
1511
+ if (!reasoning.length || this.#state !== "ready")
1512
+ return Promise.resolve({ examined: 0, expired: [], resumed: [] });
1513
+ const now = options.now ?? Date.now();
1514
+ if (!options.force && now - this.#lastReconcile < AGENT_RECONCILE_MS)
1515
+ return Promise.resolve({ examined: 0, expired: [], resumed: [] });
1516
+ if (this.#reconciling)
1517
+ return this.#reconciling;
1518
+ this.#lastReconcile = now;
1519
+ const pass = (async () => {
1520
+ const owners = new Map(reasoning.map((a) => [`agent:${a.principal.id}`, a]));
1521
+ const tasks = await this.#agent.openTasksOwnedBy(new Set(owners.keys()));
1522
+ const result = { examined: tasks.length, expired: [], resumed: [] };
1523
+ const outbox = this.instance.handle("app").collection(OUTBOX_COLLECTION);
1524
+ for (const task of tasks) {
1525
+ const taskId = task.task_id;
1526
+ try {
1527
+ for (const actionId of await this.#agent.expireDue(taskId, now))
1528
+ result.expired.push({ taskId, actionId });
1529
+ const head = (await this.#agent.activeMemories(taskId, "admin", LEASE_KIND))[0];
1530
+ const lease = head?.content;
1531
+ let cause = null;
1532
+ let why = "";
1533
+ if (!lease) {
1534
+ if (now - Date.parse(task.updated_at) > 30_000)
1535
+ [cause, why] = [`no-lease:${task.revision}`, "the run's first attempt stopped before it took the run"];
1536
+ }
1537
+ else if (!lease.released) {
1538
+ if (lease.until <= now) {
1539
+ const holder = await outbox.get(lease.holder.outboxId).catch(() => null);
1540
+ if (!holder || (holder.state !== "pending" && holder.state !== "performing"))
1541
+ [cause, why] = [`expired:${head.key}`, `the attempt holding the run (${lease.holder.outboxId}#${lease.holder.attempt}) stopped without releasing it`];
1542
+ }
1543
+ }
1544
+ else if (lease.released.status === "waiting") {
1545
+ const states = await this.#agent.actionStates(taskId);
1546
+ const waited = lease.released.actions.map((id) => `${id}=${states.get(id)?.state ?? "missing"}`);
1547
+ const open = lease.released.actions.some((id) => ["proposed", "approved", "executing", "interrupted"].includes(states.get(id)?.state ?? ""));
1548
+ if (!open)
1549
+ [cause, why] = [`decided:${head.key}:${waited.join(",")}`, `what it waited on is decided (${waited.join(", ")})`];
1550
+ }
1551
+ else if (lease.released.status === "held") {
1552
+ if ((await this.#agent.control.mode(taskId)).mode === "running")
1553
+ [cause, why] = [`unheld:${head.key}`, "a person resumed the task"];
1554
+ }
1555
+ else if (lease.released.status === "completed" || lease.released.status === "stopped") {
1556
+ [cause, why] = [`unfinished:${head.key}`, `its attempt released the run as ${lease.released.status} but the task is still open`];
1557
+ }
1558
+ if (!cause)
1559
+ continue;
1560
+ const resumeId = await this.#writeResume(taskId, `reconcile:${cause}`);
1561
+ if (!resumeId)
1562
+ continue;
1563
+ result.resumed.push({ taskId, cause, resumeId });
1564
+ const definition = owners.get(task.owner);
1565
+ const principal = await this.withTenant({ id: definition.principal.id, type: "agent", roles: [...definition.roles] }, task.scope?.workspace);
1566
+ await this.#agent.rememberOnce(taskId, principal, `recovery-${resumeId.slice(-16)}`, "agent-recovery", { cause, why, resumeId, at: new Date(now).toISOString(), lease: head ? head.key : null }).catch(() => undefined);
1567
+ this.activity.record({ kind: "agent", name: "agent.run.recovered", via: "runtime", requestId: resumeId, principal: { id: definition.principal.id, type: "agent", roles: [...definition.roles] }, outcome: "success", durationMs: 0, detail: { taskId, agent: definition.name, cause, why, resumeId } });
1568
+ }
1569
+ catch (error) {
1570
+ this.logger.warn(`agent run reconciliation of ${taskId}: ${error.message}`);
1571
+ }
1572
+ }
1573
+ return result;
1574
+ })();
1575
+ this.#reconciling = pass.finally(() => (this.#reconciling = undefined));
1576
+ return this.#reconciling;
1577
+ }
1233
1578
  /** Start an agent run now, without making the triggering call wait for it. */
1234
1579
  #dispatchAgent(id) {
1235
1580
  const run = this.#runAgent(id).catch((error) => this.logger.warn(`agent run ${id}: ${error.message}`));
@@ -1256,7 +1601,9 @@ export class FeltKitRuntime {
1256
1601
  const definition = this.app.agents.get(effect.agent);
1257
1602
  if (!definition)
1258
1603
  throw new FeltKitError("FUNCTION_NOT_FOUND", `Application agent "${effect.agent}" is no longer declared.`);
1259
- if (claim.attempts > definition.retry.maxAttempts && !claim.retriedBy)
1604
+ // A reasoning run is bounded by its own budgets (execution time, generations), which survive restarts; its
1605
+ // attempts also count waits for a busy run, so the claim count says nothing about abandonment there.
1606
+ if (!definition.reasoning && claim.attempts > definition.retry.maxAttempts && !claim.retriedBy)
1260
1607
  throw new FeltKitError("FAILED_PRECONDITION", `Agent run abandoned: its claim expired ${claim.attempts - 1} times (lease ${definition.leaseMs} ms).`);
1261
1608
  // The agent's own identity and roles; a tenant only through its own active membership.
1262
1609
  const principal = await this.withTenant({ id: definition.principal.id, type: "agent", roles: [...definition.roles], ...(definition.principal.displayName ? { displayName: definition.principal.displayName } : {}) }, effect.tenantId);
@@ -1264,14 +1611,33 @@ export class FeltKitRuntime {
1264
1611
  agent: definition.name,
1265
1612
  idempotencyKey: claim.id,
1266
1613
  attempt: claim.attempts,
1614
+ runId: effect.run ?? claim.id,
1267
1615
  by: Object.freeze({ principalId: claim.principalId, function: claim.function, requestId: claim.requestId }),
1268
1616
  ...(effect.event ? { event: effect.event } : {}),
1269
1617
  ...(effect.tenantId ? { requestedTenantId: effect.tenantId } : {}),
1270
1618
  });
1271
1619
  const requestId = `agent_${claim.id}_${claim.attempts}`;
1272
- const result = await this.call(`agent/${definition.name}`, effect.input ?? {}, { principal, via: "agent", requestId, idempotencyReplayKey: `agent:${claim.id}`, agentRun: { definition, trigger } });
1620
+ const reasoning = definition.reasoning;
1621
+ const active = this.#reasoningActive.get(definition.name) ?? 0;
1622
+ if (reasoning && active >= reasoning.limits.concurrency) {
1623
+ this.#busyUntil.set(claim.id, Date.now() + 2_000);
1624
+ throw runBusy(Date.now() + 2_000, `${active} run(s) of ${definition.name} in this process (limits.concurrency ${reasoning.limits.concurrency})`);
1625
+ }
1626
+ const abort = new AbortController();
1627
+ if (reasoning)
1628
+ this.#reasoningActive.set(definition.name, active + 1);
1629
+ let result;
1630
+ try {
1631
+ result = await this.call(`agent/${definition.name}`, effect.input ?? {}, { principal, via: "agent", requestId, idempotencyReplayKey: `agent:${claim.id}`, agentRun: { definition, trigger, outboxId: claim.id, abort }, ...(reasoning ? { signal: abort.signal } : {}) });
1632
+ }
1633
+ finally {
1634
+ if (reasoning)
1635
+ this.#reasoningActive.set(definition.name, (this.#reasoningActive.get(definition.name) ?? 1) - 1);
1636
+ }
1637
+ if (!result.ok && result.error.details?.reason === "RUN_BUSY")
1638
+ this.#busyUntil.set(claim.id, Number(result.error.details.until) || Date.now() + 2_000);
1273
1639
  if (result.ok)
1274
- return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}) };
1640
+ return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}), ...(definition.reasoning ? { run: result.value } : {}) };
1275
1641
  // An earlier attempt committed (its done mark was lost): the run happened, once.
1276
1642
  if (result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true)
1277
1643
  return { requestId, committedEarlier: true };
@@ -1280,8 +1646,21 @@ export class FeltKitRuntime {
1280
1646
  warn: (message) => this.logger.warn(message, { outboxId: id }),
1281
1647
  retryAt: (claim, error) => {
1282
1648
  const definition = claim.effect.service === "agent" ? this.app.agents.get(claim.effect.agent) : undefined;
1649
+ // Busy (another attempt holds the run, or the agent's concurrency is full): try again when it may be free. Not a failure.
1650
+ const busy = this.#busyUntil.get(claim.id);
1651
+ if (busy !== undefined) {
1652
+ this.#busyUntil.delete(claim.id);
1653
+ // Backoff, not the holder's whole lease: a holder that finishes early frees the run long before its lease ends.
1654
+ return Math.min(Math.max(busy, Date.now() + 250), Date.now() + Math.min(15_000, 500 * 2 ** Math.min(claim.attempts, 5)));
1655
+ }
1656
+ // Fenced: this attempt lost the run to a newer one, which carries it on; this record is finished.
1657
+ if (definition?.reasoning && /no longer owns the run/.test(error.message))
1658
+ return null;
1283
1659
  if (!definition || terminal.has(error.code) || claim.attempts >= definition.retry.maxAttempts)
1284
1660
  return null;
1661
+ // A reasoning run that cannot start for want of configuration (no model) waits for an operator's retry.
1662
+ if (definition.reasoning && error.code === "CONFIGURATION")
1663
+ return null;
1285
1664
  return Date.now() + Math.min(definition.retry.backoffMs * 2 ** Math.max(0, claim.attempts - 1), AGENT_MAX_BACKOFF_MS);
1286
1665
  },
1287
1666
  });
@@ -1298,7 +1677,7 @@ export class FeltKitRuntime {
1298
1677
  * after a session ends; one pass at a time.
1299
1678
  */
1300
1679
  runSessionEnds() {
1301
- if (this.#state !== "ready" || this.#paused || this.app.options.auth?.onSessionEnd === undefined)
1680
+ if (this.#state !== "ready" || this.#paused || !this.sessions.recordEnds)
1302
1681
  return Promise.resolve();
1303
1682
  if (this.#sessionEnds) {
1304
1683
  this.#sessionEndsAgain = true;
@@ -1308,19 +1687,25 @@ export class FeltKitRuntime {
1308
1687
  do {
1309
1688
  this.#sessionEndsAgain = false;
1310
1689
  const hook = this.app.options.auth?.onSessionEnd;
1311
- if (!hook)
1690
+ if (!this.sessions.recordEnds)
1312
1691
  return;
1313
1692
  if (Date.now() - this.#lastExpirySweep >= SESSION_EXPIRY_SWEEP_MS) {
1314
1693
  this.#lastExpirySweep = Date.now();
1315
1694
  await this.sessions.sweepExpired();
1316
1695
  }
1317
1696
  for (const end of await this.sessions.pendingEnds()) {
1697
+ // Presence leases held under the session end with it, before the application hears of the end.
1698
+ await this.presence.endForSession(end.ref).catch((error) => this.logger.warn(`presence: ending leases of session ${end.ref}: ${error.message}`));
1699
+ if (!hook) {
1700
+ await this.sessions.endHandled(end);
1701
+ continue;
1702
+ }
1318
1703
  const principal = end.principal ? fromAppPortPrincipal(end.principal) : null;
1319
1704
  if (!principal) {
1320
1705
  await this.sessions.endHandled(end); // nobody's session: nothing can be bound to it
1321
1706
  continue;
1322
1707
  }
1323
- const result = await this.call(hook, { session: end.ref, reason: end.reason }, { principal, via: "runtime", requestId: `session_end_${end.ref}_${end.attempts}` });
1708
+ const result = await this.call(hook, { session: end.ref, reason: end.reason }, { principal, via: "runtime", internal: true, requestId: `session_end_${end.ref}_${end.attempts}` });
1324
1709
  if (result.ok)
1325
1710
  await this.sessions.endHandled(end);
1326
1711
  else {
@@ -1356,6 +1741,10 @@ export class FeltKitRuntime {
1356
1741
  this.logger.warn(`invocation recovery: ${error.message}`);
1357
1742
  return null;
1358
1743
  }),
1744
+ this.reconcileAgentRuns().catch((error) => {
1745
+ this.logger.warn(`agent run reconciliation: ${error.message}`);
1746
+ return null;
1747
+ }),
1359
1748
  ]).then(([tick]) => tick).catch((error) => {
1360
1749
  this.logger.warn(`services worker: ${error.message}`);
1361
1750
  return { jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } };
@@ -1514,6 +1903,7 @@ export class FeltKitRuntime {
1514
1903
  kind: options.kind,
1515
1904
  ...(options.label ? { label: options.label } : {}),
1516
1905
  ...(tenantId ? { tenantId } : {}),
1906
+ ...(tenantId && options.previewRole ? { previewRole: options.previewRole } : {}),
1517
1907
  ...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : this.app.options.auth?.sessionTtlMs ? { ttlMs: this.app.options.auth.sessionTtlMs } : {}),
1518
1908
  });
1519
1909
  this.activity.record({
@@ -1526,7 +1916,7 @@ export class FeltKitRuntime {
1526
1916
  durationMs: 0,
1527
1917
  detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(tenantId ? { tenantId } : {}), ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
1528
1918
  });
1529
- return { token: session.id, principal: await this.withTenant(principal, tenantId), expiresAt: session.expiresAt };
1919
+ return { token: session.id, principal: this.previewAs(await this.withTenant(principal, tenantId), options.previewRole), expiresAt: session.expiresAt };
1530
1920
  }
1531
1921
  /**
1532
1922
  * An agent or service identity this app knows: one holding an active session (operator-issued:
@@ -1547,6 +1937,214 @@ export class FeltKitRuntime {
1547
1937
  const active = (await this.sessions.list()).find((s) => s.principal?.id === id && (s.principal.type === "agent" || s.principal.type === "service"));
1548
1938
  return active?.principal ? { id, type: active.principal.type, ...(active.principal.displayName ? { displayName: active.principal.displayName } : {}) } : null;
1549
1939
  }
1940
+ /**
1941
+ * Redeem a guest link (K4): a session for a guest with no account, holding the link's role, admitted to the
1942
+ * link's one resource, lasting until the link expires (at most GUEST_SESSION_MAX_MS). The display name is the
1943
+ * guest's own words, shown to others as such.
1944
+ */
1945
+ async redeemGuestLink(token, displayName) {
1946
+ if (!this.app.options.auth?.guests)
1947
+ throw new FeltKitError("NOT_FOUND", "This application has no guests (auth.guests).");
1948
+ const link = await this.access.guestLinkFor(token);
1949
+ if (!link)
1950
+ throw new FeltKitError("UNAUTHORIZED", "This guest link is not valid: it was withdrawn, it expired, or it never existed.", { hint: "GUEST_LINK" });
1951
+ const name = typeof displayName === "string" ? displayName.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 80) : "";
1952
+ if (!name)
1953
+ throw new FeltKitError("INVALID_ARGUMENT", "A guest gives a display name.");
1954
+ const ttlMs = Math.min(GUEST_SESSION_MAX_MS, link.expiresAt - this.clock.now());
1955
+ const principal = { id: `guest:${randomUUID().replace(/-/g, "").slice(0, 20)}`, type: "user", roles: [link.role], displayName: name };
1956
+ const session = await this.sessions.create({ applicationId: this.app.name, principal: toAppPortPrincipal(principal), ttlMs, attributes: { kind: "guest", label: `guest of ${link.resource.collection} ${link.resource.id}`, guestLink: link.id } });
1957
+ const resolved = (await this.principalForToken(session.id));
1958
+ this.recordAuth("guest.admitted", resolved, { link: link.id, resource: link.resource });
1959
+ return { token: session.id, principal: resolved, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) };
1960
+ }
1961
+ /** ctx.grants for one call: guest links and agent grants for records the caller can see, issued as a person. */
1962
+ /** `ctx.grants` as this principal, outside a function: the same rules (FeltKit's own surfaces, e.g. eve agents). */
1963
+ grantsFor(principal) {
1964
+ return this.#grantsApi(principal, applicationView(new Reader(this.instance.handle("app"), this.#resolver)));
1965
+ }
1966
+ #grantsApi(principal, db) {
1967
+ const person = () => {
1968
+ if (!principal || principal.type !== "user" || principal.guest)
1969
+ throw new FeltKitError("FORBIDDEN", "Only a signed-in person (not a guest, agent or service) issues guest links and agent grants.");
1970
+ return principal;
1971
+ };
1972
+ const target = async (collection, id) => {
1973
+ const definition = collection && this.app.collections.get(collection.name);
1974
+ if (!definition || definition !== collection)
1975
+ throw new FeltKitError("INVALID_ARGUMENT", "ctx.grants: name the resource by a collection of this application and a record id.");
1976
+ // Through the call's own reader: another tenant's record does not exist for the caller.
1977
+ if (typeof id !== "string" || !(await db.get(definition, id)))
1978
+ throw new FeltKitError("NOT_FOUND", `No ${definition.name} ${String(id)}.`);
1979
+ return { collection: definition.name, id };
1980
+ };
1981
+ const ttl = (ttlMs, fallback) => {
1982
+ const value = ttlMs ?? fallback;
1983
+ if (!Number.isInteger(value) || value < 60_000 || value > MAX_ACCESS_TTL_MS)
1984
+ throw new FeltKitError("INVALID_ARGUMENT", "ctx.grants: ttlMs is from one minute to 30 days.");
1985
+ return value;
1986
+ };
1987
+ return {
1988
+ guestLink: async (collection, id, options = {}) => {
1989
+ const by = person();
1990
+ const guests = this.app.options.auth?.guests;
1991
+ if (!guests)
1992
+ throw new FeltKitError("CONFIGURATION", "Guest links need auth.guests (the roles a guest may hold).");
1993
+ const role = options.role ?? guests.roles[0];
1994
+ if (!guests.roles.includes(role))
1995
+ throw new FeltKitError("INVALID_ARGUMENT", `A guest may hold only ${guests.roles.join(", ")} (auth.guests.roles), not "${role}".`);
1996
+ const resource = await target(collection, id);
1997
+ const issued = await this.access.issueGuestLink({ resource, role, ttlMs: ttl(options.ttlMs, guests.ttlMs ?? 24 * 3_600_000), ...(options.label ? { label: options.label } : {}), by });
1998
+ this.recordAuth("guest.link-issued", by, { link: issued.link.id, resource, role }, "success", "runtime");
1999
+ return { ...issued.link, token: issued.token, url: `${this.publicUrl()}/?guest=${issued.token}` };
2000
+ },
2001
+ admitAgent: async (collection, id, agent, options = {}) => {
2002
+ const by = person();
2003
+ const resource = await target(collection, id);
2004
+ const known = typeof agent === "string" ? await this.knownNonPersonPrincipal(agent) : null;
2005
+ if (!known)
2006
+ throw new FeltKitError("NOT_FOUND", `No agent or service "${String(agent)}" is known here (an app.agent, or one with an operator-issued session).`);
2007
+ const grant = await this.access.grantAgent({ resource, agent, ttlMs: ttl(options.ttlMs, 24 * 3_600_000), ...(options.label ? { label: options.label } : {}), by });
2008
+ this.recordAuth("agent.admitted", by, { grant: grant.id, resource, agent }, "success", "runtime");
2009
+ return grant;
2010
+ },
2011
+ revoke: async (collection, id, accessId) => {
2012
+ const by = person();
2013
+ const resource = await target(collection, id);
2014
+ const revoked = await this.access.revoke(accessId, resource, by);
2015
+ if (revoked)
2016
+ this.recordAuth("access.revoked", by, { access: accessId, resource }, "success", "runtime");
2017
+ return revoked;
2018
+ },
2019
+ list: async (collection, id) => {
2020
+ person();
2021
+ return this.access.list(await target(collection, id));
2022
+ },
2023
+ ...this.#workersApi(principal),
2024
+ };
2025
+ }
2026
+ /**
2027
+ * ctx.grants for workers (runtime/workers.ts): registering and revoking workers and their work grants needs
2028
+ * `feltkit.workers.write` (a person or a service, never a guest or a worker); approving an exact call is a person's.
2029
+ */
2030
+ #workersApi(principal) {
2031
+ const manager = () => {
2032
+ if (!principal || principal.guest || principal.worker || principal.type === "agent")
2033
+ throw new FeltKitError("FORBIDDEN", "Workers and work grants are managed by a signed-in person or a service, not by a guest, an agent or a worker.");
2034
+ if (!grantsPermission(this.#authority.permissionsFor(principal), "feltkit.workers.write"))
2035
+ throw new FeltKitError("FORBIDDEN", `${principal.id} may not manage workers (needs feltkit.workers.write).`);
2036
+ return principal;
2037
+ };
2038
+ const workerId = (worker) => {
2039
+ if (typeof worker !== "string" || !worker)
2040
+ throw new FeltKitError("INVALID_ARGUMENT", "Name the worker by its principal id (worker:<name>) or its name.");
2041
+ return worker.startsWith(WORKER_PREFIX) ? worker : `${WORKER_PREFIX}${worker}`;
2042
+ };
2043
+ const capabilityAccess = (capability) => {
2044
+ const fn = [...this.#project.functions.values()].find((f) => f.capability?.name === capability);
2045
+ if (fn)
2046
+ return fn.access;
2047
+ return this.integrations.operationFor(capability)?.op.access ?? null;
2048
+ };
2049
+ return {
2050
+ registerWorker: async (input) => {
2051
+ const by = manager();
2052
+ const roles = Array.isArray(input?.roles) ? input.roles : [];
2053
+ for (const role of roles)
2054
+ if (typeof role !== "string" || !this.#authority.roles[role])
2055
+ throw new FeltKitError("INVALID_ARGUMENT", `Unknown role "${String(role)}". Declared roles: ${Object.keys(this.#authority.roles).join(", ") || "(none)"}.`);
2056
+ // No escalation: a worker holds nothing its registrar does not.
2057
+ const mine = this.#authority.permissionsFor(by);
2058
+ const beyond = this.#authority.permissionsFor({ id: "worker", type: "agent", roles: [...roles] }).filter((p) => !grantsPermission(mine, p));
2059
+ if (beyond.length)
2060
+ throw new FeltKitError("FORBIDDEN", `${by.id} cannot give a worker ${beyond.join(", ")}: a worker holds only what its registrar holds.`);
2061
+ const ttlMs = WorkerAuthority.ttl(input?.ttlMs, 30 * 24 * 3_600_000, "registerWorker");
2062
+ const record = await this.workers.register({ name: String(input?.name ?? ""), roles, ...(input?.displayName ? { displayName: input.displayName } : {}), ttlMs, by });
2063
+ const session = await this.sessions.create({ applicationId: this.app.name, principal: toAppPortPrincipal({ id: record.principalId, type: "agent", roles: [...roles], ...(record.label ? { displayName: record.label } : {}) }), ttlMs, attributes: { kind: "worker", label: `worker ${record.principalId}`, worker: record.id, ...(record.tenantId ? { tenantId: record.tenantId } : {}) } });
2064
+ this.recordAuth("worker.registered", by, { worker: record.principalId, registration: record.id, roles }, "success", "runtime");
2065
+ return { ...this.workers.workerView(record), token: session.id };
2066
+ },
2067
+ revokeWorker: async (worker) => {
2068
+ const by = manager();
2069
+ const id = workerId(worker);
2070
+ const changed = await this.workers.revokeWorker(id, by);
2071
+ await this.sessions.revokePrincipal(id);
2072
+ this.recordAuth("worker.revoked", by, { worker: id }, "success", "runtime");
2073
+ return changed;
2074
+ },
2075
+ workers: async () => {
2076
+ manager();
2077
+ return this.workers.workers();
2078
+ },
2079
+ workGrant: async (input) => {
2080
+ const by = manager();
2081
+ let actor = input?.actor;
2082
+ if (by.type === "user") {
2083
+ if (actor && actor.id !== by.id)
2084
+ throw new FeltKitError("FORBIDDEN", `${by.id} can grant a worker authority to act only for themselves, not for ${actor.id}.`);
2085
+ actor = { id: by.id, type: "user" };
2086
+ }
2087
+ else if (!actor || typeof actor.id !== "string" || !actor.id) {
2088
+ throw new FeltKitError("INVALID_ARGUMENT", "A service names whom the worker acts for: actor: { id, type? }.");
2089
+ }
2090
+ // A person grants only what they could call themselves.
2091
+ if (by.type === "user") {
2092
+ for (const capability of input?.capabilities ?? []) {
2093
+ const access = typeof capability === "string" ? capabilityAccess(capability) : null;
2094
+ if (access && !this.holds(by, access))
2095
+ throw new FeltKitError("FORBIDDEN", `${by.id} may not call ${capability} (requires ${access}), so cannot grant it to a worker.`);
2096
+ }
2097
+ }
2098
+ const grant = await this.workers.issueGrant({ worker: workerId(input?.worker), actor: { id: actor.id, ...(actor.type ? { type: actor.type } : {}) }, capabilities: input?.capabilities, ...(input?.workItemId !== undefined ? { workItemId: input.workItemId } : {}), ...(input?.delegationId !== undefined ? { delegationId: input.delegationId } : {}), ttlMs: WorkerAuthority.ttl(input?.ttlMs, 24 * 3_600_000, "workGrant"), by });
2099
+ this.recordAuth("work-grant.issued", by, { grant: grant.ref, worker: grant.worker, actor: grant.actor.id, capabilities: grant.capabilities, ...(grant.workItemId ? { workItemId: grant.workItemId } : {}) }, "success", "runtime");
2100
+ return grant;
2101
+ },
2102
+ revokeWorkGrant: async (ref) => {
2103
+ const by = manager();
2104
+ const changed = await this.workers.revokeGrant(ref, by);
2105
+ if (changed)
2106
+ this.recordAuth("work-grant.revoked", by, { grant: ref }, "success", "runtime");
2107
+ return changed;
2108
+ },
2109
+ approve: async (input) => {
2110
+ const by = principal;
2111
+ if (!by || by.type !== "user" || by.guest)
2112
+ throw new FeltKitError("FORBIDDEN", "Only a signed-in person approves a call; agents, services, workers and guests cannot.");
2113
+ const access = typeof input?.capability === "string" ? capabilityAccess(input.capability) : null;
2114
+ if (!access)
2115
+ throw new FeltKitError("NOT_FOUND", `${String(input?.capability)} is not a capability of this application.`);
2116
+ if (!this.holds(by, access))
2117
+ throw new FeltKitError("FORBIDDEN", `${by.id} may not call ${input.capability} (requires ${access}), so cannot approve it.`);
2118
+ const resource = input.resource ? { collection: input.resource.collection?.name, id: input.resource.id } : undefined;
2119
+ if (resource && (!this.app.collections.has(String(resource.collection)) || typeof resource.id !== "string"))
2120
+ throw new FeltKitError("INVALID_ARGUMENT", "approve: resource is { collection, id } of this application.");
2121
+ const approval = await this.workers.issueApproval({ capability: input.capability, input: input.input, ...(input.worker !== undefined ? { worker: workerId(input.worker) } : {}), ...(input.workItemId !== undefined ? { workItemId: input.workItemId } : {}), ...(resource ? { resource: resource } : {}), ttlMs: WorkerAuthority.ttl(input.ttlMs, 24 * 3_600_000, "approve"), by });
2122
+ this.recordAuth("approval.issued", by, { approval: approval.ref, capability: approval.capability, digest: approval.digest, ...(approval.worker ? { worker: approval.worker } : {}) }, "success", "runtime");
2123
+ return approval;
2124
+ },
2125
+ revokeApproval: async (ref) => {
2126
+ if (!principal || principal.guest || principal.worker)
2127
+ throw new FeltKitError("FORBIDDEN", "Only the person who approved, or a holder of feltkit.workers.write, withdraws an approval.");
2128
+ const record = await this.workers.approval(ref);
2129
+ if (!record)
2130
+ throw new FeltKitError("NOT_FOUND", `No approval ${String(ref)}.`);
2131
+ if (record.createdBy !== `${principal.type}:${principal.id}` && !grantsPermission(this.#authority.permissionsFor(principal), "feltkit.workers.write"))
2132
+ throw new FeltKitError("FORBIDDEN", `${principal.id} did not give approval ${ref}.`);
2133
+ const changed = await this.workers.revokeApproval(ref, principal);
2134
+ if (changed)
2135
+ this.recordAuth("approval.revoked", principal, { approval: ref }, "success", "runtime");
2136
+ return changed;
2137
+ },
2138
+ approval: async (ref) => {
2139
+ if (!principal)
2140
+ throw new FeltKitError("UNAUTHORIZED", "Sign in to read an approval.");
2141
+ const record = await this.workers.approval(ref);
2142
+ if (!record)
2143
+ throw new FeltKitError("NOT_FOUND", `No approval ${String(ref)}.`);
2144
+ return this.workers.approvalView(record);
2145
+ },
2146
+ };
2147
+ }
1550
2148
  /** Record an authentication event (sign-in failures, revocations, membership changes) in the activity log. */
1551
2149
  recordAuth(name, principal, detail, outcome = "success", via = "http") {
1552
2150
  this.activity.record({ kind: "auth", name, via, requestId: `req_${randomUUID()}`, principal: principal ? pick(principal) : null, outcome, durationMs: 0, detail });
@@ -1582,7 +2180,7 @@ export class FeltKitRuntime {
1582
2180
  };
1583
2181
  const failure = (error, extra = {}) => {
1584
2182
  const json = this.#errorJSON(error, requestId);
1585
- const outcome = json.code === "UNAUTHORIZED" || json.code === "FORBIDDEN" || extra.authority?.resource?.allowed === false ? "denied" : "error";
2183
+ const outcome = json.code === "UNAUTHORIZED" || json.code === "FORBIDDEN" || json.code === "RATE_LIMITED" || extra.authority?.resource?.allowed === false ? "denied" : "error";
1586
2184
  if (outcome === "error") {
1587
2185
  this.recentErrors.unshift({ at: new Date().toISOString(), name, code: json.code, message: json.message, requestId });
1588
2186
  this.recentErrors.length = Math.min(this.recentErrors.length, 50);
@@ -1594,6 +2192,16 @@ export class FeltKitRuntime {
1594
2192
  return failure(new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`));
1595
2193
  if (!fn)
1596
2194
  return failure(new FeltKitError("FUNCTION_NOT_FOUND", `No query or mutation named "${name}".`, { hint: "Function names are \"<module>:<export>\", e.g. \"tasks:list\"." }));
2195
+ // Visibility, before anything else: an internal function does not exist for any surface.
2196
+ const visibilityRefusal = fn.visibility && !options.internal && !options.agentRun ? visibilityRefusalFor(name, fn.visibility, principal) : null;
2197
+ if (visibilityRefusal) {
2198
+ if (principal && visibilityRefusal.code !== "FUNCTION_NOT_FOUND")
2199
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, outcome: "denied", layer: "visibility", reason: visibilityRefusal.message, argKeys: argKeys(rawArgs) ?? [] });
2200
+ return failure(new FeltKitError(visibilityRefusal.code, visibilityRefusal.message, { details: { visibility: fn.visibility } }));
2201
+ }
2202
+ if (principal?.preview && fn.kind !== "query") {
2203
+ return failure(new FeltKitError("FORBIDDEN", `You are previewing as ${principal.preview.role}: nothing can be changed while you preview. Stop previewing to make changes.`, { hint: "PREVIEW" }));
2204
+ }
1597
2205
  // Never hand stored records to code that declares a different schema for them.
1598
2206
  if (this.schema?.status === "blocked") {
1599
2207
  return failure(new FeltKitError("CONFIGURATION", `The application's schema changed and the stored data has not been migrated: ${this.schema.plan.reason ?? "run `feltkit migrate`"}. No function runs until it is.`, { hint: blockedHint(this.schema.plan) }));
@@ -1627,14 +2235,32 @@ export class FeltKitRuntime {
1627
2235
  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) ?? [] });
1628
2236
  return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
1629
2237
  }
2238
+ // The invocation context (runtime/workers.ts): a worker acts only under a work grant naming this function's
2239
+ // capability; a named grant or approval must verify. Internal calls carry their caller's verified context.
2240
+ let invocation = null;
2241
+ const claimedInvocation = options.invocation?.claimed ?? {};
2242
+ if (options.internal && options.invocation?.verified) {
2243
+ invocation = { claimed: claimedInvocation, verified: options.invocation.verified };
2244
+ }
2245
+ else if (principal?.worker || Object.keys(claimedInvocation).length) {
2246
+ const checked = await this.workers.check({ principal, capability: fn.capability?.name ?? name, input: (rawArgs ?? {}), invocation: claimedInvocation, requireGrant: Boolean(principal?.worker) && !options.internal });
2247
+ if (!checked.ok) {
2248
+ if (principal)
2249
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, outcome: "denied", layer: "grant", reason: `${checked.reason}: ${checked.message}`, argKeys: argKeys(rawArgs) ?? [] });
2250
+ return failure(new FeltKitError("FORBIDDEN", checked.message, { details: { reason: checked.reason } }), { authority: { ...authorityRecord, allowed: false, reason: checked.reason, invocation: { claimed: claimedInvocation, verified: {} } }, argKeys: argKeys(rawArgs) });
2251
+ }
2252
+ invocation = { claimed: claimedInvocation, verified: checked.verified };
2253
+ }
2254
+ if (invocation)
2255
+ authorityRecord.invocation = invocation;
1630
2256
  // The approval requirement, at the execution boundary every interface goes through (/api,
1631
2257
  // AppPort, MCP, jobs, decisions): permission alone is not enough for a non-person caller.
1632
- const approvalRefusal = this.#approvalRefusal(name, fn, principal);
2258
+ const approvalRefusal = invocation?.verified.approvalRef ? null : this.#approvalRefusal(name, fn, principal);
1633
2259
  if (approvalRefusal) {
1634
2260
  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) ?? [] });
1635
2261
  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) });
1636
2262
  }
1637
- const approvedAction = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
2263
+ const approvedAction = fn.approval === "required" && principal?.type !== "user" && !invocation?.verified.approvalRef ? this.#approvedAction.getStore() : undefined;
1638
2264
  if (approvedAction)
1639
2265
  Object.assign(authorityRecord, { approval: { taskId: approvedAction.taskId, actionId: approvedAction.actionId, approvedBy: approvedAction.approvedBy } });
1640
2266
  const parsed = validate(fn.argsSchema, rawArgs ?? {});
@@ -1645,6 +2271,12 @@ export class FeltKitRuntime {
1645
2271
  });
1646
2272
  }
1647
2273
  const args = parsed.value;
2274
+ // Quotas (K3): before the policies, the authorize hook and the handler; a refusal writes nothing.
2275
+ const quotaRefusal = this.#admit(name, fn, args, principal, options);
2276
+ if (quotaRefusal)
2277
+ return failure(quotaRefusal, { authority: authorityRecord, argKeys: Object.keys(args), detail: { quota: quotaRefusal.details.quota } });
2278
+ if (fn.kind === "action" && principal?.guest)
2279
+ return failure(new FeltKitError("FORBIDDEN", `${name} is not open to guests: a guest calls only queries and mutations bound to its resource.`, { hint: "GUEST" }), { authority: { ...authorityRecord, allowed: false } });
1648
2280
  if (fn.kind === "action") {
1649
2281
  // An action's own service effects (ctx.services.files) are the caller's while the action runs, as for a query or mutation.
1650
2282
  const releaseAction = this.#services.enter(requestId, principal);
@@ -1656,6 +2288,7 @@ export class FeltKitRuntime {
1656
2288
  }
1657
2289
  }
1658
2290
  const handle = this.instance.handle("app");
2291
+ const releaseFeed = fn.kind === "mutation" ? this.changes.hold() : null;
1659
2292
  const release = this.#services.enter(requestId, principal);
1660
2293
  const servicesUsed = new Set();
1661
2294
  const enabled = this.app.options.services ?? {};
@@ -1665,7 +2298,7 @@ export class FeltKitRuntime {
1665
2298
  const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
1666
2299
  const used = new Set();
1667
2300
  const shared = {
1668
- auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
2301
+ auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null, invocation),
1669
2302
  tenancy: {
1670
2303
  members: async () => {
1671
2304
  if (!this.tenancy)
@@ -1682,8 +2315,11 @@ export class FeltKitRuntime {
1682
2315
  requestId,
1683
2316
  log: this.logger,
1684
2317
  crypto: { token: async (bytes) => randomBytes(checkTokenBytes(bytes)).toString("base64url") },
2318
+ capabilities: unavailableCapabilities(),
1685
2319
  authority: this.#applicationAuthority(principal, requestId),
1686
- integrations: this.#integrationInvoker(principal),
2320
+ // An external call from a mutation is an effect outside its transaction: the attempt is never re-run on a
2321
+ // sequence conflict (as for ctx.services), so the call is not repeated. Prefer ctx.afterCommit.jobs → an action.
2322
+ integrations: trackedIntegrations(this.#integrationInvoker(principal), used),
1687
2323
  };
1688
2324
  const starts = [];
1689
2325
  const agent = {
@@ -1735,10 +2371,55 @@ export class FeltKitRuntime {
1735
2371
  }
1736
2372
  },
1737
2373
  };
2374
+ // ctx.channels (app.channel): authorized for the sender now, delivered after the commit, never stored.
2375
+ const channels = {
2376
+ send: async (channel, scope, message) => {
2377
+ const declared = channel && this.app.events.get(channel.name);
2378
+ if (!declared?.channel || declared !== channel)
2379
+ throw new FeltKitError("INVALID_ARGUMENT", `ctx.channels.send: ${String(channel?.name ?? channel)} is not a channel declared with app.channel().`);
2380
+ const config = declared.channel;
2381
+ if (typeof scope !== "string" || !/^[^\u0000-\u001f\u007f]{1,256}$/.test(scope))
2382
+ throw new FeltKitError("INVALID_ARGUMENT", `ctx.channels.send(${declared.name}): scope (the recipient) is a non-empty string of at most 256 characters.`);
2383
+ const checked = declared.payload.validate(message);
2384
+ if (!checked.ok)
2385
+ throw new FeltKitError("INVALID_ARGUMENT", `ctx.channels.send(${declared.name}): the message does not match its schema: ${(checked.issues ?? []).map((i) => i.message).join("; ")}`);
2386
+ const bytes = new TextEncoder().encode(JSON.stringify(checked.value ?? message)).length;
2387
+ if (bytes > config.maxBytes)
2388
+ throw new FeltKitError("PAYLOAD_TOO_LARGE", `ctx.channels.send(${declared.name}): the message is ${bytes} bytes; at most ${config.maxBytes}.`);
2389
+ const refuse = async (reason) => {
2390
+ 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: "channel", reason, argKeys: [] });
2391
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", reason, { details: { channel: declared.name } });
2392
+ };
2393
+ if (!this.holds(principal, config.send))
2394
+ await refuse(`${principal?.id ?? "An anonymous caller"} may not send on ${declared.name} (needs ${config.send}).`);
2395
+ if (config.authorize.send) {
2396
+ let allowed = false;
2397
+ try {
2398
+ allowed = (await config.authorize.send({ principal, scope, message: checked.value ?? message, db: scoped })) === true;
2399
+ }
2400
+ catch {
2401
+ allowed = false;
2402
+ }
2403
+ if (!allowed)
2404
+ await refuse(`${declared.name}: the channel's send rule refused this scope.`);
2405
+ }
2406
+ if (config.quota) {
2407
+ const admitted = this.quotas.admit(`channel:${declared.name}`, config.quota, { principalId: principal?.id ?? null, ...(options.client ? { client: options.client } : {}) });
2408
+ if (!admitted.ok)
2409
+ throw rateLimited(admitted.refusal, `${declared.name} (channel)`);
2410
+ }
2411
+ published.push({ name: declared.name, payload: checked.value ?? message, scope });
2412
+ },
2413
+ };
1738
2414
  // Tenant-scoped collections see only the caller's tenant (the session's, never the request's).
1739
- const scoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(db);
1740
- 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 });
1741
- 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 } };
2415
+ const tenantScoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(db);
2416
+ // Presence collections show only leases that hold now, and change only through ctx.presence.
2417
+ const presenceNames = this.presence.names();
2418
+ const scoped = presenceNames.size ? this.presence.view(tenantScoped) : tenantScoped;
2419
+ const presence = this.presence.api(tenantScoped, principal, options.session ?? null, fn.kind === "mutation" && db instanceof Writer ? (record) => db.stageSystem(OUTBOX_COLLECTION, record) : null, { function: name, requestId });
2420
+ const invocations = this.#invocationsApi(workItemScoped(principal, invocation?.verified), 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 });
2421
+ const grants = this.#grantsApi(principal, scoped);
2422
+ const ctx = fn.kind === "mutation" ? { ...shared, presence, channels, grants, 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, presence, db: scoped, invocations: { get: invocations.get, list: invocations.list } };
1742
2423
  try {
1743
2424
  // feltkit({ authorize }): after roles and validation, with this call's own reader, so its
1744
2425
  // reads are fenced at commit (mutations) and tracked for live queries (queries).
@@ -1795,6 +2476,10 @@ export class FeltKitRuntime {
1795
2476
  if (commit.writes.length) {
1796
2477
  this.changes.describe(commit.described);
1797
2478
  void this.changes.check();
2479
+ releaseFeed?.();
2480
+ // A lease joined, renewed or ended: the expiry timer follows the earliest live lease.
2481
+ if (this.presence.names().size && commit.writes.some((w) => this.presence.names().has(w.collection)))
2482
+ void this.presence.arm().catch((error) => this.logger.warn(`presence: ${error.message}`));
1798
2483
  }
1799
2484
  // Agent work starts only once the mutation's writes are durable.
1800
2485
  for (const start of starts)
@@ -1840,9 +2525,33 @@ export class FeltKitRuntime {
1840
2525
  return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads, ...(servicesUsed.size ? { services: [...servicesUsed] } : {}), ...(retries ? { detail: { sequenceRetries: retries } } : {}) });
1841
2526
  }
1842
2527
  finally {
2528
+ releaseFeed?.();
1843
2529
  release();
1844
2530
  }
1845
2531
  }
2532
+ /**
2533
+ * Count a call against the function's quotas and the application's (K3), or refuse it. Application
2534
+ * agents' runs and the runtime's own calls (session ends, presence ends) are not counted: they are
2535
+ * the platform's, not a caller's.
2536
+ */
2537
+ #admit(name, fn, args, principal, options) {
2538
+ if (options.agentRun || options.via === "runtime")
2539
+ return null;
2540
+ const caller = { principalId: principal?.id ?? null, ...(options.client ? { client: options.client } : {}) };
2541
+ if (fn.quota) {
2542
+ const admitted = this.quotas.admit(`function:${name}`, fn.quota, caller, args);
2543
+ if (!admitted.ok)
2544
+ return rateLimited(admitted.refusal, name);
2545
+ }
2546
+ const app = this.app.options.quotas;
2547
+ if (app) {
2548
+ const specs = Array.isArray(app) ? app : [app];
2549
+ const admitted = this.quotas.admit("application", specs, caller, args);
2550
+ if (!admitted.ok)
2551
+ return rateLimited(admitted.refusal, `${this.app.name} (every function)`);
2552
+ }
2553
+ return null;
2554
+ }
1846
2555
  /**
1847
2556
  * Run an action: no transaction and no database handle. It reads and writes only through calls
1848
2557
  * (each authorized as the caller, each in its own transaction) and the agent's proposals, so
@@ -1865,7 +2574,7 @@ export class FeltKitRuntime {
1865
2574
  if (target.kind !== kind)
1866
2575
  throw new FeltKitError("INVALID_ARGUMENT", `${ref.name} is a ${target.kind}; use ctx.run${target.kind === "query" ? "Query" : target.kind === "mutation" ? "Mutation" : "…"}.`);
1867
2576
  // Cancellation stops the model (ctx.signal); it does not stop the action recording what happened.
1868
- const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}), ...(options.session ? { session: options.session } : {}) });
2577
+ const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, internal: true, ...(authorityRecord.invocation ? { invocation: authorityRecord.invocation } : {}), ...(options.context ? { context: options.context } : {}), ...(options.session ? { session: options.session } : {}) });
1869
2578
  if (!result.ok)
1870
2579
  throw new FeltKitError(result.error.code, result.error.message, { ...(result.error.details ? { details: result.error.details } : {}), ...(result.error.hint ? { hint: result.error.hint } : {}) });
1871
2580
  return result.value;
@@ -1877,7 +2586,7 @@ export class FeltKitRuntime {
1877
2586
  };
1878
2587
  const agent = this.#agent;
1879
2588
  const ctx = {
1880
- auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
2589
+ auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null, authorityRecord.invocation ?? null),
1881
2590
  environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
1882
2591
  requestId,
1883
2592
  log: this.logger,
@@ -1932,8 +2641,9 @@ export class FeltKitRuntime {
1932
2641
  },
1933
2642
  authority: this.#applicationAuthority(principal, requestId),
1934
2643
  integrations: this.#integrationInvoker(principal),
2644
+ grants: this.#grantsApi(principal, applicationView(new Reader(this.instance.handle("app"), this.#resolver))),
1935
2645
  services: { files: explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), name, principal, this.#authority).files },
1936
- invocations: this.#invocationsApi(principal, null, { via: String(options.via ?? "function"), requestId }),
2646
+ invocations: this.#invocationsApi(workItemScoped(principal, authorityRecord.invocation?.verified), null, { via: String(options.via ?? "function"), requestId }),
1937
2647
  agent: {
1938
2648
  catalog: async () => (await agent.tools(signedIn())).map((t) => ({
1939
2649
  name: t.name,
@@ -1970,7 +2680,42 @@ export class FeltKitRuntime {
1970
2680
  try {
1971
2681
  const reader = new Reader(this.instance.handle("app"), this.#resolver);
1972
2682
  await this.#authorizeResource(name, fn, args, principal, options, requestId, applicationView(reader), authorityRecord);
1973
- const value = await fn.handler(ctx, args);
2683
+ // ctx.effect (AppPort's external effect lifecycle, spec §13.5): `begin()` records the effect in
2684
+ // _feltkit_provider_calls before it is attempted; returning is succeeded, effectFailed(...) is failed, any other
2685
+ // throw after begin() is unknown and never repeated. A job's attempts share one record, so a retried job never
2686
+ // begins its effect twice.
2687
+ const effectId = options.idempotencyReplayKey ? `fx_${createHash("sha256").update(options.idempotencyReplayKey).digest("hex").slice(0, 40)}` : requestId;
2688
+ const recorder = this.providers.effectRecorder();
2689
+ const value = await runEffectful({ requestId: effectId, capability: { name: fn.capability?.name ?? name, version: fn.capability?.version ?? 1 }, ...(principal ? { principal: toAppPort(principal) } : {}), ...(authorityRecord.invocation ? { invocation: authorityRecord.invocation } : {}), ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) }, {
2690
+ provider: this.app.name,
2691
+ providerId: this.app.name,
2692
+ recorder: {
2693
+ ...recorder,
2694
+ started: async (call) => {
2695
+ try {
2696
+ await recorder.started(call);
2697
+ }
2698
+ catch (error) {
2699
+ if (await recorder.get(call.id).catch(() => null))
2700
+ throw outcomeUnknown(`${name} already began this external effect in an earlier attempt (${call.id}); it is not attempted again. Ask what happened (appport.invocation.status) or settle it.`, { callId: call.id });
2701
+ throw error;
2702
+ }
2703
+ },
2704
+ },
2705
+ onRecordError: (error, call) => this.logger.error(`${name}: the outcome of external effect ${call.id} could not be recorded`, { error: String(error), outcome: call.outcome }),
2706
+ }, (effect) => {
2707
+ const full = { ...ctx, effect };
2708
+ const run = options.agentRun;
2709
+ if (run?.definition.reasoning && principal) {
2710
+ Object.assign(full, {
2711
+ trigger: run.trigger,
2712
+ [AGENT_RUN]: (input) => runReasoningAgent({ host: this.#agent, ctx: full, definition: run.definition, trigger: run.trigger, principal, runInput: input, leaseMs: this.#runLeaseMs ?? Math.floor(run.definition.leaseMs / 2), ...(this.#agentHooks?.holdLeaseRenewal ? { holdLeaseRenewal: this.#agentHooks.holdLeaseRenewal } : {}), abort: run.abort ?? new AbortController(), outboxId: run.outboxId ?? run.trigger.idempotencyKey, onResumeNeeded: (taskId, cause) => this.resumeAgentRun(taskId, cause) }),
2713
+ });
2714
+ }
2715
+ return fn.handler(full, args);
2716
+ }).catch((error) => {
2717
+ throw error instanceof AppPortError ? providerError(error) : error;
2718
+ });
1974
2719
  if (fn.returns) {
1975
2720
  const output = validate(fn.returns, value);
1976
2721
  if (!output.ok)
@@ -2002,6 +2747,9 @@ export class FeltKitRuntime {
2002
2747
  if (rule.resource && !this.app.collections.has(rule.resource.collection)) {
2003
2748
  throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names collection ${rule.resource.collection}, which this application does not declare.`);
2004
2749
  }
2750
+ if (rule.resource?.by !== undefined && !uniqueField(this.app.collections.get(rule.resource.collection), rule.resource.by)) {
2751
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} addresses ${rule.resource.collection} by "${rule.resource.by}", which is not a unique field of it.`);
2752
+ }
2005
2753
  },
2006
2754
  });
2007
2755
  return this.#policyStore;
@@ -2114,6 +2862,30 @@ export class FeltKitRuntime {
2114
2862
  const hook = this.app.options.authorize;
2115
2863
  const set = await this.policyStore.current();
2116
2864
  const governed = set.rules.some((rule) => rule.functions.includes(name));
2865
+ // The resource gate (K4, K6): guests only on functions bound to their resource, agents only with a grant.
2866
+ if (principal?.guest || fn.resource?.agents === "grant") {
2867
+ const refusal = await resourceRefusal(fn, name, args, principal, db, this.access);
2868
+ if (refusal) {
2869
+ record.allowed = false;
2870
+ record.resource = { allowed: false, reason: refusal.reason };
2871
+ 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: "resource", reason: refusal.reason, argKeys: Object.keys(args).sort() });
2872
+ throw new FeltKitError(refusal.code, refusal.reason, { details: { resource: refusal.resource ?? null }, hint: principal?.guest ? "GUEST" : "AGENT_GRANT" });
2873
+ }
2874
+ if (fn.resource)
2875
+ record.resource = { allowed: true, reason: principal?.guest ? `guest of ${principal.guest.resource.collection} ${principal.guest.resource.id}` : "agent granted" };
2876
+ }
2877
+ // A worker's grant scoped to a work item reaches only that record, on a function bound to one (runtime/workers.ts).
2878
+ const workItem = principal?.worker ? record.invocation?.verified.workItemId : undefined;
2879
+ if (workItem !== undefined && fn.resource) {
2880
+ const bound = await loadBoundResource(fn, args, db);
2881
+ if (!bound || String(bound.id) !== workItem) {
2882
+ const reason = `${name}: ${principal.id}'s grant covers ${fn.resource.collection.name} ${workItem} only.`;
2883
+ record.allowed = false;
2884
+ record.resource = { allowed: false, reason };
2885
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, outcome: "denied", layer: "grant", reason: `GRANT_WORK_ITEM_MISMATCH: ${reason}`, argKeys: Object.keys(args).sort() });
2886
+ throw new FeltKitError("FORBIDDEN", reason, { details: { reason: "GRANT_WORK_ITEM_MISMATCH" } });
2887
+ }
2888
+ }
2117
2889
  if (!hook && !fn.owner && !governed)
2118
2890
  return;
2119
2891
  const evidence = (outcome, layer, reason, policy) => ({
@@ -2204,6 +2976,12 @@ export class FeltKitRuntime {
2204
2976
  ...(session ? { session } : {}),
2205
2977
  ...(principal && !session ? { principal: toAppPort(principal) } : {}),
2206
2978
  transport: "mcp",
2979
+ }, {
2980
+ // Reserved appport.* capabilities are left out of MCP by default; people steer agents (appport.agent-control/1)
2981
+ // over MCP exactly as over HTTP and AppPort, so those are projected too. The reasoner's checkpoint and acknowledge
2982
+ // are FeltKit's own agent tools.
2983
+ includeBuiltins: true,
2984
+ include: (entry) => !entry.name.startsWith("appport.") || MCP_AGENT_CONTROL.has(entry.name),
2207
2985
  });
2208
2986
  }
2209
2987
  #assertReady() {
@@ -2264,6 +3042,7 @@ export class FeltKitRuntime {
2264
3042
  if (this.#state === "closed" || this.#state === "closing")
2265
3043
  return;
2266
3044
  this.#state = "closing";
3045
+ this.presence.close();
2267
3046
  if (this.#worker)
2268
3047
  clearInterval(this.#worker);
2269
3048
  this.changes.stop();
@@ -2297,10 +3076,9 @@ function toAppPort(principal) {
2297
3076
  */
2298
3077
  export const FELTKIT_APPPORT_STATUS = {
2299
3078
  "feltkit.FAILED_PRECONDITION": statusFor("FAILED_PRECONDITION"),
2300
- UPSTREAM_REJECTED: statusFor("UPSTREAM_REJECTED"),
2301
- OUTCOME_UNKNOWN: statusFor("OUTCOME_UNKNOWN"),
2302
- UNAVAILABLE: statusFor("UNAVAILABLE"),
2303
- NOT_CONFIGURED: statusFor("CONFIGURATION"),
3079
+ "feltkit.UPSTREAM_REJECTED": statusFor("UPSTREAM_REJECTED"),
3080
+ "feltkit.UNAVAILABLE": statusFor("UNAVAILABLE"),
3081
+ "feltkit.NOT_CONFIGURED": statusFor("CONFIGURATION"),
2304
3082
  };
2305
3083
  function toAppPortError(error) {
2306
3084
  switch (error.code) {
@@ -2327,19 +3105,23 @@ function toAppPortError(error) {
2327
3105
  return appportErrors.rateLimited(error.message, (error.details ?? undefined));
2328
3106
  // Not INTERNAL: a caller must be able to tell "may have been applied" from "failed".
2329
3107
  case "OUTCOME_UNKNOWN":
2330
- return new AppPortError("OUTCOME_UNKNOWN", error.message, { retryable: false, details: (error.details ?? null) });
3108
+ // AppPort's own shape (CONFLICT, details.reason EFFECT_OUTCOME_UNKNOWN): never retried, recorded under the idempotency key.
3109
+ return outcomeUnknown(error.message, (error.details && typeof error.details === "object" && !Array.isArray(error.details) ? error.details : {}));
3110
+ // FeltKit's own codes, namespaced as AppPort requires of codes outside its standard set (`feltkit.*`).
2331
3111
  case "UNAVAILABLE":
2332
- return new AppPortError("UNAVAILABLE", error.message, { retryable: true, details: (error.details ?? null) });
3112
+ return new AppPortError("feltkit.UNAVAILABLE", error.message, { retryable: true, details: (error.details ?? null) });
2333
3113
  // An external API refused the request: its identity and status survive, never retryable.
2334
3114
  case "UPSTREAM_REJECTED":
2335
- return new AppPortError("UPSTREAM_REJECTED", error.message, { retryable: false, details: (error.details ?? null) });
3115
+ return new AppPortError("feltkit.UPSTREAM_REJECTED", error.message, { retryable: false, details: (error.details ?? null) });
2336
3116
  // The server lacks something an operator must provide (a credential, a URL): not retryable.
2337
3117
  case "CONFIGURATION":
2338
- return new AppPortError("NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
3118
+ return new AppPortError("feltkit.NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
2339
3119
  default:
2340
3120
  return appportErrors.internal(error.message);
2341
3121
  }
2342
3122
  }
3123
+ /** AppPort's own capabilities a worker reaches without a work grant: describing the application, and its own calls. */
3124
+ const WORKER_UNGRANTED = ["appport.manifest", "appport.ping", "appport.invocation.status"];
2343
3125
  /** AppPort's replay key, computed exactly as AppPort scopes it (session, else principal). */
2344
3126
  const BUILTIN_CAPABILITY_NAMES = ["appport.manifest", "appport.ping"];
2345
3127
  function callerScope(appportPrincipal) {
@@ -2394,4 +3176,31 @@ class AttemptFailed {
2394
3176
  this.error = error;
2395
3177
  }
2396
3178
  }
3179
+ /** Why `principal` may not call a function of this visibility from a surface, or null (runtime/workers.ts). */
3180
+ export function visibilityRefusalFor(name, visibility, principal) {
3181
+ if (visibility === "internal")
3182
+ return { code: "FUNCTION_NOT_FOUND", message: `No query or mutation named "${name}".` };
3183
+ if (!principal)
3184
+ return { code: "UNAUTHORIZED", message: `${name} is for ${visibility === "worker" ? "registered workers" : "services"} only.` };
3185
+ if (visibility === "worker" && !principal.worker)
3186
+ return { code: "FORBIDDEN", message: `${name} is called only by a registered worker under a work grant, not by a ${principal.type}.` };
3187
+ if (visibility === "service" && principal.type !== "service")
3188
+ return { code: "FORBIDDEN", message: `${name} is called only by a service (an API key, a component), not by a ${principal.type}.` };
3189
+ return null;
3190
+ }
3191
+ /** ctx.integrations, noting into `used` that the attempt reached outside its transaction (no sequence-conflict re-run). */
3192
+ function trackedIntegrations(invoker, used) {
3193
+ return {
3194
+ ...invoker,
3195
+ invoke: (...args) => {
3196
+ used.add("integrations");
3197
+ return invoker.invoke(...args);
3198
+ },
3199
+ };
3200
+ }
3201
+ /** How messages name the application: its name as a title ("team-board" → "Team board"). A description is not a name. */
3202
+ export function appTitle(name) {
3203
+ const words = name.replace(/[-_]+/g, " ").trim();
3204
+ return words.charAt(0).toUpperCase() + words.slice(1);
3205
+ }
2397
3206
  //# sourceMappingURL=runtime.js.map