@feltdb/feltkit 0.4.0 → 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 (126) 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 +153 -4
  5. package/dist/app.js +134 -25
  6. package/dist/app.js.map +1 -1
  7. package/dist/appboundry/build.d.ts +7 -0
  8. package/dist/appboundry/build.js +4 -1
  9. package/dist/appboundry/build.js.map +1 -1
  10. package/dist/appboundry/guest.js +4 -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 +265 -4
  32. package/dist/client/index.js +170 -3
  33. package/dist/client/index.js.map +1 -1
  34. package/dist/cron.d.ts +18 -0
  35. package/dist/cron.js +67 -0
  36. package/dist/cron.js.map +1 -0
  37. package/dist/dashboard/assets/index-iIj7SL77.js +15 -0
  38. package/dist/dashboard/index.html +1 -1
  39. package/dist/docs.d.ts +1 -1
  40. package/dist/docs.js +3 -0
  41. package/dist/docs.js.map +1 -1
  42. package/dist/eve/index.d.ts +77 -0
  43. package/dist/eve/index.js +128 -0
  44. package/dist/eve/index.js.map +1 -0
  45. package/dist/index.d.ts +7 -2
  46. package/dist/index.js +2 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/native/build.d.ts +112 -0
  49. package/dist/native/build.js +472 -0
  50. package/dist/native/build.js.map +1 -0
  51. package/dist/native/index.d.ts +67 -0
  52. package/dist/native/index.js +113 -0
  53. package/dist/native/index.js.map +1 -0
  54. package/dist/native/instance.d.ts +3 -0
  55. package/dist/native/instance.js +18 -0
  56. package/dist/native/instance.js.map +1 -0
  57. package/dist/react/agent-control.d.ts +2 -0
  58. package/dist/react/agent-control.js +1 -1
  59. package/dist/react/agent-control.js.map +1 -1
  60. package/dist/react/auth.d.ts +15 -1
  61. package/dist/react/auth.js +28 -5
  62. package/dist/react/auth.js.map +1 -1
  63. package/dist/react/hooks.d.ts +88 -0
  64. package/dist/react/hooks.js +188 -0
  65. package/dist/react/hooks.js.map +1 -0
  66. package/dist/react/index.d.ts +5 -88
  67. package/dist/react/index.js +3 -185
  68. package/dist/react/index.js.map +1 -1
  69. package/dist/runtime/agent-control.d.ts +10 -0
  70. package/dist/runtime/agent-control.js +9 -1
  71. package/dist/runtime/agent-control.js.map +1 -1
  72. package/dist/runtime/agent-run.d.ts +166 -0
  73. package/dist/runtime/agent-run.js +431 -0
  74. package/dist/runtime/agent-run.js.map +1 -0
  75. package/dist/runtime/agent.d.ts +158 -1
  76. package/dist/runtime/agent.js +329 -8
  77. package/dist/runtime/agent.js.map +1 -1
  78. package/dist/runtime/assemble.js +14 -1
  79. package/dist/runtime/assemble.js.map +1 -1
  80. package/dist/runtime/authority.d.ts +9 -0
  81. package/dist/runtime/authority.js.map +1 -1
  82. package/dist/runtime/context.d.ts +9 -0
  83. package/dist/runtime/required-capabilities.d.ts +73 -0
  84. package/dist/runtime/required-capabilities.js +69 -0
  85. package/dist/runtime/required-capabilities.js.map +1 -0
  86. package/dist/runtime/runtime.d.ts +70 -1
  87. package/dist/runtime/runtime.js +261 -9
  88. package/dist/runtime/runtime.js.map +1 -1
  89. package/dist/runtime/sessions.d.ts +1 -0
  90. package/dist/runtime/sessions.js +1 -1
  91. package/dist/runtime/sessions.js.map +1 -1
  92. package/dist/runtime/tenancy.d.ts +9 -1
  93. package/dist/runtime/tenancy.js +22 -0
  94. package/dist/runtime/tenancy.js.map +1 -1
  95. package/dist/runtime/transactions.d.ts +3 -1
  96. package/dist/runtime/transactions.js.map +1 -1
  97. package/dist/server/eve.d.ts +287 -0
  98. package/dist/server/eve.js +1071 -0
  99. package/dist/server/eve.js.map +1 -0
  100. package/dist/server/index.d.ts +2 -0
  101. package/dist/server/index.js +58 -1
  102. package/dist/server/index.js.map +1 -1
  103. package/dist/server/mcp.d.ts +7 -7
  104. package/dist/server/project.js +20 -3
  105. package/dist/server/project.js.map +1 -1
  106. package/dist/server/tenancy.d.ts +2 -0
  107. package/dist/server/tenancy.js +31 -1
  108. package/dist/server/tenancy.js.map +1 -1
  109. package/dist/testing/index.d.ts +1 -4
  110. package/dist/testing/index.js.map +1 -1
  111. package/docs/AGENT-CONTROL.md +36 -0
  112. package/docs/APPBOUNDRY.md +36 -0
  113. package/docs/AUTH.md +2 -0
  114. package/docs/EVE-COMPOSITION.md +75 -0
  115. package/docs/NATIVE-AGENTS.md +353 -0
  116. package/docs/NATIVE.md +137 -0
  117. package/docs/README.md +5 -2
  118. package/package.json +33 -7
  119. package/skills/.claude-plugin/marketplace.json +1 -1
  120. package/skills/.claude-plugin/plugin.json +1 -1
  121. package/skills/feltkit-agent/SKILL.md +1 -1
  122. package/skills/feltkit-build/SKILL.md +1 -1
  123. package/skills/feltkit-data/SKILL.md +1 -1
  124. package/skills/feltkit-operations/SKILL.md +1 -1
  125. package/skills/feltkit-services/SKILL.md +1 -1
  126. package/dist/dashboard/assets/index-BhxrvY37.js +0 -15
@@ -8,6 +8,7 @@
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";
@@ -27,7 +28,7 @@ import { performance } from "node:perf_hooks";
27
28
  import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
28
29
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
29
30
  import { dirname, join } from "node:path";
30
- import { AGENT_MAX_BACKOFF_MS, uniqueField } from "../app.js";
31
+ import { AGENT_MAX_BACKOFF_MS, AGENT_RUN, uniqueField } from "../app.js";
31
32
  import { IntegrationHost, integrationDescriptor } from "./integrations.js";
32
33
  import { applicationAuthority } from "./application-authority.js";
33
34
  import { verifyStorage } from "./storage-check.js";
@@ -56,6 +57,7 @@ import { authorityPrincipalOf } from "./application-authority.js";
56
57
  import { verifyDelegation } from "./delegation.js";
57
58
  import { credentialsFor, isCustodyError } from "./credentials.js";
58
59
  import { AgentHost, AGENT_PERMISSIONS } from "./agent.js";
60
+ import { runReasoningAgent, runBusy, RUN_KIND, LEASE_KIND } from "./agent-run.js";
59
61
  import { AGENT_CONTROL_EVENT, agentTaskScope, defineEvent, taskIdOfAgentScope } from "@appport/sdk";
60
62
  import { toSchema } from "@appport/schema";
61
63
  import { SEQUENCES_COLLECTION } from "./transactions.js";
@@ -80,6 +82,10 @@ const NODE_TENANCY_CRYPTO = {
80
82
  export const SESSION_EXPIRY_SWEEP_MS = 5_000;
81
83
  /** Attempts at running auth.onSessionEnd for one ended session before it is kept as failed. */
82
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;
83
89
  const consoleLogger = {
84
90
  info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
85
91
  warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
@@ -260,12 +266,25 @@ export class FeltKitRuntime {
260
266
  step("markers");
261
267
  await runtime.#services.check();
262
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
+ }
263
278
  // FeltDB's agent runtime and agent state, on this instance (see runtime/agent.ts).
264
279
  runtime.#agent = new AgentHost(runtime, instance.handle("feltdb.agent"), {
265
280
  separateApprover: options.environment.production,
266
281
  ...(options.agentActionTimeoutMs ? { actionTimeoutMs: options.agentActionTimeoutMs } : {}),
267
282
  ...(options.agentHooks ? { hooks: options.agentHooks } : {}),
283
+ onSettled: (taskId, actionId) => runtime.resumeAgentRun(taskId, `settled:${actionId}`),
268
284
  });
285
+ if (options.agentRunLeaseMs)
286
+ runtime.#runLeaseMs = options.agentRunLeaseMs;
287
+ runtime.#agentHooks = options.agentHooks;
269
288
  await runtime.#agent.open();
270
289
  step("agent");
271
290
  runtime.changes.start();
@@ -479,7 +498,7 @@ export class FeltKitRuntime {
479
498
  if (!live)
480
499
  return null;
481
500
  const input = {
482
- app: app.options.description ?? app.name,
501
+ app: appTitle(app.name),
483
502
  link: this.invitationLink(live.token),
484
503
  tenant: live.tenantName,
485
504
  role: live.invitation.role,
@@ -497,7 +516,7 @@ export class FeltKitRuntime {
497
516
  if (!live)
498
517
  return null; // used, superseded or expired before delivery: send nothing
499
518
  const link = `${this.publicUrl()}/#feltkit-${live.purpose}=${live.token}`;
500
- 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)) };
501
520
  const template = accounts.email.templates?.[live.purpose];
502
521
  return template ? template(input) : accountMessage(live.purpose, input);
503
522
  },
@@ -715,6 +734,9 @@ export class FeltKitRuntime {
715
734
  * state as that change left it, scoped to the task. Emissions for one task are serialized in this process.
716
735
  */
717
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}`);
718
740
  const previous = this.#agentEvents.get(taskId) ?? Promise.resolve();
719
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}`));
720
742
  this.#agentEvents.set(taskId, next);
@@ -1087,7 +1109,31 @@ export class FeltKitRuntime {
1087
1109
  return null;
1088
1110
  principal = { ...principal, roles: [...account.roles], displayName: account.name ?? account.email };
1089
1111
  }
1090
- 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);
1091
1137
  }
1092
1138
  /**
1093
1139
  * The principal working in a tenant: the live membership's role joins its roles, and its claims
@@ -1391,6 +1437,144 @@ export class FeltKitRuntime {
1391
1437
  const tenantId = principal?.tenant?.id ?? tenant;
1392
1438
  return { service: "agent", method: "run", agent: name, input, ...(tenantId ? { tenantId } : {}), ...(event ? { event } : {}) };
1393
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
+ }
1394
1578
  /** Start an agent run now, without making the triggering call wait for it. */
1395
1579
  #dispatchAgent(id) {
1396
1580
  const run = this.#runAgent(id).catch((error) => this.logger.warn(`agent run ${id}: ${error.message}`));
@@ -1417,7 +1601,9 @@ export class FeltKitRuntime {
1417
1601
  const definition = this.app.agents.get(effect.agent);
1418
1602
  if (!definition)
1419
1603
  throw new FeltKitError("FUNCTION_NOT_FOUND", `Application agent "${effect.agent}" is no longer declared.`);
1420
- 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)
1421
1607
  throw new FeltKitError("FAILED_PRECONDITION", `Agent run abandoned: its claim expired ${claim.attempts - 1} times (lease ${definition.leaseMs} ms).`);
1422
1608
  // The agent's own identity and roles; a tenant only through its own active membership.
1423
1609
  const principal = await this.withTenant({ id: definition.principal.id, type: "agent", roles: [...definition.roles], ...(definition.principal.displayName ? { displayName: definition.principal.displayName } : {}) }, effect.tenantId);
@@ -1425,14 +1611,33 @@ export class FeltKitRuntime {
1425
1611
  agent: definition.name,
1426
1612
  idempotencyKey: claim.id,
1427
1613
  attempt: claim.attempts,
1614
+ runId: effect.run ?? claim.id,
1428
1615
  by: Object.freeze({ principalId: claim.principalId, function: claim.function, requestId: claim.requestId }),
1429
1616
  ...(effect.event ? { event: effect.event } : {}),
1430
1617
  ...(effect.tenantId ? { requestedTenantId: effect.tenantId } : {}),
1431
1618
  });
1432
1619
  const requestId = `agent_${claim.id}_${claim.attempts}`;
1433
- 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);
1434
1639
  if (result.ok)
1435
- return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}) };
1640
+ return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}), ...(definition.reasoning ? { run: result.value } : {}) };
1436
1641
  // An earlier attempt committed (its done mark was lost): the run happened, once.
1437
1642
  if (result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true)
1438
1643
  return { requestId, committedEarlier: true };
@@ -1441,8 +1646,21 @@ export class FeltKitRuntime {
1441
1646
  warn: (message) => this.logger.warn(message, { outboxId: id }),
1442
1647
  retryAt: (claim, error) => {
1443
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;
1444
1659
  if (!definition || terminal.has(error.code) || claim.attempts >= definition.retry.maxAttempts)
1445
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;
1446
1664
  return Date.now() + Math.min(definition.retry.backoffMs * 2 ** Math.max(0, claim.attempts - 1), AGENT_MAX_BACKOFF_MS);
1447
1665
  },
1448
1666
  });
@@ -1523,6 +1741,10 @@ export class FeltKitRuntime {
1523
1741
  this.logger.warn(`invocation recovery: ${error.message}`);
1524
1742
  return null;
1525
1743
  }),
1744
+ this.reconcileAgentRuns().catch((error) => {
1745
+ this.logger.warn(`agent run reconciliation: ${error.message}`);
1746
+ return null;
1747
+ }),
1526
1748
  ]).then(([tick]) => tick).catch((error) => {
1527
1749
  this.logger.warn(`services worker: ${error.message}`);
1528
1750
  return { jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } };
@@ -1681,6 +1903,7 @@ export class FeltKitRuntime {
1681
1903
  kind: options.kind,
1682
1904
  ...(options.label ? { label: options.label } : {}),
1683
1905
  ...(tenantId ? { tenantId } : {}),
1906
+ ...(tenantId && options.previewRole ? { previewRole: options.previewRole } : {}),
1684
1907
  ...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : this.app.options.auth?.sessionTtlMs ? { ttlMs: this.app.options.auth.sessionTtlMs } : {}),
1685
1908
  });
1686
1909
  this.activity.record({
@@ -1693,7 +1916,7 @@ export class FeltKitRuntime {
1693
1916
  durationMs: 0,
1694
1917
  detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(tenantId ? { tenantId } : {}), ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
1695
1918
  });
1696
- 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 };
1697
1920
  }
1698
1921
  /**
1699
1922
  * An agent or service identity this app knows: one holding an active session (operator-issued:
@@ -1736,6 +1959,10 @@ export class FeltKitRuntime {
1736
1959
  return { token: session.id, principal: resolved, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) };
1737
1960
  }
1738
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
+ }
1739
1966
  #grantsApi(principal, db) {
1740
1967
  const person = () => {
1741
1968
  if (!principal || principal.type !== "user" || principal.guest)
@@ -1972,6 +2199,9 @@ export class FeltKitRuntime {
1972
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) ?? [] });
1973
2200
  return failure(new FeltKitError(visibilityRefusal.code, visibilityRefusal.message, { details: { visibility: fn.visibility } }));
1974
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
+ }
1975
2205
  // Never hand stored records to code that declares a different schema for them.
1976
2206
  if (this.schema?.status === "blocked") {
1977
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) }));
@@ -2085,6 +2315,7 @@ export class FeltKitRuntime {
2085
2315
  requestId,
2086
2316
  log: this.logger,
2087
2317
  crypto: { token: async (bytes) => randomBytes(checkTokenBytes(bytes)).toString("base64url") },
2318
+ capabilities: unavailableCapabilities(),
2088
2319
  authority: this.#applicationAuthority(principal, requestId),
2089
2320
  // An external call from a mutation is an effect outside its transaction: the attempt is never re-run on a
2090
2321
  // sequence conflict (as for ctx.services), so the call is not repeated. Prefer ctx.afterCommit.jobs → an action.
@@ -2472,7 +2703,17 @@ export class FeltKitRuntime {
2472
2703
  },
2473
2704
  },
2474
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 }),
2475
- }, (effect) => fn.handler({ ...ctx, effect }, args)).catch((error) => {
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) => {
2476
2717
  throw error instanceof AppPortError ? providerError(error) : error;
2477
2718
  });
2478
2719
  if (fn.returns) {
@@ -2735,6 +2976,12 @@ export class FeltKitRuntime {
2735
2976
  ...(session ? { session } : {}),
2736
2977
  ...(principal && !session ? { principal: toAppPort(principal) } : {}),
2737
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),
2738
2985
  });
2739
2986
  }
2740
2987
  #assertReady() {
@@ -2951,4 +3198,9 @@ function trackedIntegrations(invoker, used) {
2951
3198
  },
2952
3199
  };
2953
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
+ }
2954
3206
  //# sourceMappingURL=runtime.js.map