@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
package/dist/app.js CHANGED
@@ -2,12 +2,15 @@ import { checkPolicyRule, viaCollections } from "./policy.js";
2
2
  import { servicesDependencyProblem } from "./runtime/services-rules.js";
3
3
  import { validateName } from "@appport/protocol";
4
4
  import { FeltKitError } from "./errors.js";
5
+ import { modelEngine } from "./agent-engine.js";
5
6
  import { validateProviders } from "./providers.js";
6
7
  import { validateComponents } from "./component.js";
7
8
  import { defineSurface } from "./surfaces.js";
8
9
  import { REFERENCE_KEYWORD, RESERVED_FIELDS, s, shapeToObjectSchema } from "./schema.js";
9
10
  import { checkRetryPolicy } from "./runtime/transactions.js";
10
11
  import { claimSpecProblem } from "./runtime/claims.js";
12
+ import { checkQuota } from "./quota.js";
13
+ import { LEASE_FIELDS, MAX_LEASE_TTL_MS, MIN_LEASE_TTL_MS, PRESENCE } from "./presence.js";
11
14
  const APP = Symbol.for("feltkit.app");
12
15
  const COLLECTION = Symbol.for("feltkit.collection");
13
16
  const FUNCTION = Symbol.for("feltkit.function");
@@ -21,6 +24,12 @@ export const RESERVED_COLLECTIONS = new Set([
21
24
  // AppPort Services (every service it can construct on the shared instance)
22
25
  "files",
23
26
  "file_audit_events",
27
+ // AppPort Services 0.21: content-addressed file objects, resumable uploads and usage metering.
28
+ "file_objects",
29
+ "file_object_chunks",
30
+ "file_uploads",
31
+ "file_usage",
32
+ "intelligence_usage",
24
33
  "service_effect_evidence",
25
34
  "notifications",
26
35
  "notification_deliveries",
@@ -84,6 +93,12 @@ export function checkAccess(access, what) {
84
93
  throw new TypeError(`${what}: access "${access}" is not a permission (segments of letters, digits, "_" or "-" joined by ".", like "notes.read"), "authenticated" or "public".`);
85
94
  return access;
86
95
  }
96
+ /** The outbox claim of one reasoning attempt. Short: the run's own lease (renewed while it works) keeps a live attempt's run from being taken over. */
97
+ export const AGENT_REASONING_LEASE_MS = 120_000;
98
+ export const AGENT_MAX_TURNS = 100;
99
+ export const AGENT_MAX_TOOL_CALLS = 500;
100
+ /** The internal hook a reasoning agent's action calls: the runtime puts its run driver here on the action's ctx. */
101
+ export const AGENT_RUN = Symbol.for("feltkit.agentRun");
87
102
  export const AGENT_DEFAULT_ATTEMPTS = 5;
88
103
  export const AGENT_DEFAULT_BACKOFF_MS = 1_000;
89
104
  export const AGENT_MAX_BACKOFF_MS = 600_000;
@@ -101,6 +116,8 @@ export class FeltKitApp {
101
116
  migrations = [];
102
117
  /** Application agents (see `agent`), by name. */
103
118
  agents = new Map();
119
+ /** Agents that run on the agent runtime from their own project (`app.agent(name, { project })`), by name. */
120
+ projectAgents = new Map();
104
121
  /** Declared policies (`app.policy`), in declaration order. Resolved to function names at assembly. */
105
122
  policies = [];
106
123
  constructor(options) {
@@ -160,7 +177,23 @@ export class FeltKitApp {
160
177
  if (accounts.password === false && !accounts.magicLink && !options.auth?.providers)
161
178
  throw new TypeError("auth.accounts.password: false leaves no way to sign in: enable magicLink or a provider.");
162
179
  }
180
+ if (options.quotas !== undefined) {
181
+ const quotas = checkQuota(options.quotas, "feltkit({ quotas })");
182
+ if (quotas.some((q) => q.per.includes("arg:")))
183
+ throw new TypeError('feltkit({ quotas }): an application-wide quota is per "principal" or "function"; per-argument quotas belong on a function.');
184
+ }
185
+ const guests = options.auth?.guests;
186
+ if (guests !== undefined) {
187
+ if (!guests || !Array.isArray(guests.roles) || guests.roles.length === 0)
188
+ throw new TypeError('auth.guests needs the roles a guest may hold: { roles: ["guest"] }.');
189
+ for (const role of guests.roles)
190
+ if (!options.roles?.[role])
191
+ throw new TypeError(`auth.guests names role "${role}", which is not declared in roles.`);
192
+ if (guests.ttlMs !== undefined && (!Number.isInteger(guests.ttlMs) || guests.ttlMs < 60_000 || guests.ttlMs > 30 * 24 * 3_600_000))
193
+ throw new TypeError("auth.guests.ttlMs is from one minute to 30 days.");
194
+ }
163
195
  validateComponents(options.components, options.roles);
196
+ validateEve(options.eve, options.roles, options.auth?.tenant?.roles);
164
197
  validateProviders(options.providers);
165
198
  const tenant = options.auth?.tenant;
166
199
  if (tenant !== undefined) {
@@ -270,31 +303,73 @@ export class FeltKitApp {
270
303
  return definition;
271
304
  }
272
305
  /**
273
- * An application agent: a handler that runs after a mutation commits, **as the agent** (principal
274
- * type "agent", `roles`, never the triggering caller's authority), through the same authority as
275
- * any call (roles → `access` → `feltkit({ authorize })`). A mutation triggers it with
276
- * `ctx.afterCommit.agent(name, input)`, or by publishing an event named in `on`. The run is
277
- * recorded in the mutation's transaction (the after-commit outbox), so it happens for every
278
- * committed mutation and never for one that did not commit; it runs at least once, with a lease,
279
- * retries with backoff, and its writes commit at most once per trigger (`ctx.trigger.idempotencyKey`).
306
+ * A channel of transient messages (K2): WebRTC signaling, typing, a raised hand, reactions. A message is
307
+ * sent to one scope (a recipient: a connection id, a call) with `ctx.channels.send(channel, scope,
308
+ * message)` from a mutation, delivered after it commits, at most once, to whoever is subscribed to that
309
+ * scope now (`client.subscribe(channel, { scope }, listener)` / `useEvent`), and **never written to
310
+ * FeltDB**: no record, no journal entry, no backup; the activity log records the sending call's
311
+ * metadata only (never a payload).
280
312
  *
281
- * export const assistant = app.agent("assistant", {
282
- * principal: { id: "assistant", displayName: "Assistant" },
283
- * roles: ["assistant"],
284
- * access: "messages.write",
285
- * handler: async (ctx, { roomId }) => { ... ctx.db.insert(messages, { roomId, text }) ... },
286
- * });
287
- * // in messages:send — if (text.includes("@assistant")) ctx.afterCommit.agent("assistant", { roomId });
313
+ * Authority is the channel's, declared here: the sender needs `access.send` (and `authorize.send` when
314
+ * declared); each recipient needs `access.receive` and `authorize.receive` for the scope, asked when it
315
+ * subscribes and again before every delivery, so a revoked recipient gets nothing more, and a wildcard
316
+ * subscription never carries a message its holder may not receive. `quota` limits each sender.
288
317
  *
289
- * See docs/TRANSACTIONS.md ("Application agents"). Not available in an AppBoundry artifact.
318
+ * export const signaling = app.channel("call.signal", {
319
+ * message: s.object({ kind: s.enum(["offer", "answer", "ice"]), sdp: s.string({ maxLength: 65_536 }) }),
320
+ * access: { send: "calls.signal", receive: "calls.signal" },
321
+ * authorize: { receive: async ({ principal, scope, db }) => (await db.get(connections, scope))?.holder === principal?.id },
322
+ * quota: { per: "principal", limit: 60, windowMs: 60_000 },
323
+ * });
290
324
  */
325
+ channel(name, config) {
326
+ const where = `app.channel("${name}")`;
327
+ if (!config || typeof config !== "object")
328
+ throw new TypeError(`${where} needs { message, access, authorize }.`);
329
+ const unknownKeys = Object.keys(config).filter((k) => !["message", "access", "authorize", "maxBytes", "quota", "description"].includes(k));
330
+ if (unknownKeys.length)
331
+ throw new TypeError(`${where}: unknown option ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
332
+ const send = checkAccess(config.access?.send, `${where}: access.send`);
333
+ const receive = checkAccess(config.access?.receive, `${where}: access.receive`);
334
+ if (typeof config.authorize?.receive !== "function")
335
+ throw new TypeError(`${where}: authorize.receive is required: who may receive on a scope is the channel's decision, asked at subscribe and before every delivery.`);
336
+ if (config.authorize.send !== undefined && typeof config.authorize.send !== "function")
337
+ throw new TypeError(`${where}: authorize.send is a function.`);
338
+ const maxBytes = config.maxBytes ?? 65_536;
339
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1_048_576)
340
+ throw new TypeError(`${where}: maxBytes is an integer from 1 to 1048576.`);
341
+ const quota = config.quota === undefined ? undefined : checkQuota(config.quota, where);
342
+ if (quota?.some((q) => q.per.includes("arg:")))
343
+ throw new TypeError(`${where}: a channel's quota is per "principal" or "function".`);
344
+ const definition = this.event(name, { payload: config.message, access: receive, ...(config.description ? { description: config.description } : {}) });
345
+ const channel = Object.freeze({ send, receive, authorize: Object.freeze({ ...config.authorize }), maxBytes, ...(quota ? { quota } : {}) });
346
+ const frozen = Object.freeze({ ...definition, channel });
347
+ this.events.set(name, frozen);
348
+ return frozen;
349
+ }
291
350
  agent(name, config) {
351
+ if (config && typeof config.project === "string")
352
+ return this.projectAgent(name, config);
353
+ return this.inProcessAgent(name, config);
354
+ }
355
+ projectAgent(name, config) {
356
+ if (this.agents.has(name) || this.projectAgents.has(name) || Object.hasOwn(this.options.eve ?? {}, name))
357
+ throw new TypeError(`app.agent("${name}") is declared twice.`);
358
+ if (config.handler !== undefined || config.instructions !== undefined)
359
+ throw new TypeError(`app.agent("${name}") needs exactly one of handler (a deterministic agent), instructions (in-process reasoning) and project (an agent project on the agent runtime).`);
360
+ const { project, displayName, roles, tenantRole, capabilities, grantTtlMs } = config;
361
+ const declaration = { root: project, roles, capabilities, ...(tenantRole ? { tenantRole } : {}), ...(displayName ? { displayName } : {}), ...(grantTtlMs !== undefined ? { grantTtlMs } : {}) };
362
+ validateEve({ [name]: declaration }, this.options.roles, this.options.auth?.tenant?.roles, `app.agent("${name}")`);
363
+ this.projectAgents.set(name, Object.freeze(declaration));
364
+ return Object.freeze({ name, project });
365
+ }
366
+ inProcessAgent(name, config) {
292
367
  if (typeof name !== "string" || !/^[a-z][a-zA-Z0-9_-]{0,62}$/.test(name))
293
368
  throw new TypeError(`app.agent("${name}"): the name is a lowercase letter, then letters, digits, "_" or "-" (at most 63).`);
294
- if (this.agents.has(name))
369
+ if (this.agents.has(name) || this.projectAgents.has(name))
295
370
  throw new TypeError(`app.agent("${name}") is declared twice.`);
296
- if (!config || typeof config.handler !== "function")
297
- throw new TypeError(`app.agent("${name}") needs a handler function.`);
371
+ if (!config || (typeof config.handler !== "function") === (config.instructions === undefined))
372
+ throw new TypeError(`app.agent("${name}") needs exactly one of handler (a deterministic agent) and instructions (a reasoning agent).`);
298
373
  const id = config.principal?.id;
299
374
  if (typeof id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(id))
300
375
  throw new TypeError(`app.agent("${name}"): principal.id must be 1-128 letters, digits, ".", "_", ":", "@" or "-".`);
@@ -312,7 +387,8 @@ export class FeltKitApp {
312
387
  }
313
388
  const maxAttempts = config.retry?.maxAttempts ?? AGENT_DEFAULT_ATTEMPTS;
314
389
  const backoffMs = config.retry?.backoffMs ?? AGENT_DEFAULT_BACKOFF_MS;
315
- const leaseMs = config.leaseMs ?? AGENT_DEFAULT_LEASE_MS;
390
+ const reasoning = config.instructions !== undefined ? this.checkReasoning(name, config) : undefined;
391
+ const leaseMs = config.leaseMs ?? (reasoning ? AGENT_REASONING_LEASE_MS : AGENT_DEFAULT_LEASE_MS);
316
392
  if (!Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 100)
317
393
  throw new TypeError(`app.agent("${name}"): retry.maxAttempts must be an integer from 1 to 100.`);
318
394
  if (!Number.isFinite(backoffMs) || backoffMs < 0 || backoffMs > AGENT_MAX_BACKOFF_MS)
@@ -320,7 +396,9 @@ export class FeltKitApp {
320
396
  if (!Number.isFinite(leaseMs) || leaseMs < 1_000)
321
397
  throw new TypeError(`app.agent("${name}"): leaseMs must be at least 1000.`);
322
398
  const handler = config.handler;
323
- const fn = this.define("mutation", { access: checkAccess(config.access, `app.agent("${name}")`), ...(config.description ? { description: config.description } : {}), handler: (ctx, input) => handler(ctx, input) });
399
+ const fn = reasoning
400
+ ? this.define("action", { access: checkAccess(config.access, `app.agent("${name}")`), ...(config.description ? { description: config.description } : {}), handler: (ctx, input) => ctx[AGENT_RUN](input) })
401
+ : this.define("mutation", { access: checkAccess(config.access, `app.agent("${name}")`), ...(config.description ? { description: config.description } : {}), handler: (ctx, input) => handler(ctx, input) });
324
402
  // Any input object: the trigger's input is the app's own (validated where it is staged, if at all).
325
403
  const definition = Object.freeze({
326
404
  name,
@@ -329,11 +407,57 @@ export class FeltKitApp {
329
407
  on: Object.freeze(events.map((e) => e.name)),
330
408
  retry: Object.freeze({ maxAttempts, backoffMs }),
331
409
  leaseMs,
332
- function: Object.freeze({ ...fn, argsSchema: shapeToObjectSchema({}, { additionalProperties: true }) }),
410
+ function: Object.freeze({ ...fn, argsSchema: config.input ? shapeToObjectSchema(config.input) : shapeToObjectSchema({}, { additionalProperties: true }) }),
411
+ ...(reasoning ? { reasoning } : {}),
333
412
  });
334
413
  this.agents.set(name, definition);
335
414
  return definition;
336
415
  }
416
+ checkReasoning(name, config) {
417
+ const where = `app.agent("${name}")`;
418
+ if (typeof config.instructions !== "string" || !config.instructions.trim() || config.instructions.length > 100_000)
419
+ throw new TypeError(`${where}: instructions is a non-empty string (at most 100 000 characters).`);
420
+ const capabilityOf = (fn, list) => {
421
+ if (!isFunctionDefinition(fn) || fn.app !== this)
422
+ throw new TypeError(`${where}: ${list} takes this application's query, mutation or action definitions (import them).`);
423
+ if (!fn.capability)
424
+ throw new TypeError(`${where}: ${list} names a function that is not published as a capability; add capability: "<name>" to it, so the agent uses it through AppPort like any caller.`);
425
+ return fn.capability.name;
426
+ };
427
+ if (!Array.isArray(config.tools) || config.tools.length === 0)
428
+ throw new TypeError(`${where}: a reasoning agent declares the tools it may use (tools: [...]).`);
429
+ const tools = [...new Set(config.tools.map((fn) => capabilityOf(fn, "tools")))];
430
+ const autonomous = [...new Set((config.autonomous ?? []).map((fn) => capabilityOf(fn, "autonomous")))];
431
+ for (const a of autonomous)
432
+ if (!tools.includes(a))
433
+ throw new TypeError(`${where}: autonomous names ${a}, which is not in tools.`);
434
+ const maxTurns = config.limits?.maxTurns ?? 8;
435
+ const maxToolCalls = config.limits?.maxToolCalls ?? 20;
436
+ if (!Number.isInteger(maxTurns) || maxTurns < 1 || maxTurns > AGENT_MAX_TURNS)
437
+ throw new TypeError(`${where}: limits.maxTurns is an integer from 1 to ${AGENT_MAX_TURNS}.`);
438
+ if (!Number.isInteger(maxToolCalls) || maxToolCalls < 1 || maxToolCalls > AGENT_MAX_TOOL_CALLS)
439
+ throw new TypeError(`${where}: limits.maxToolCalls is an integer from 1 to ${AGENT_MAX_TOOL_CALLS}.`);
440
+ const engine = config.engine ?? modelEngine();
441
+ if (!engine || typeof engine.id !== "string" || typeof engine.next !== "function")
442
+ throw new TypeError(`${where}: engine is an AgentEngine ({ id, usesModel, next }), e.g. modelEngine() or rulesEngine(id, decide).`);
443
+ const int = (key, fallback, min, max) => {
444
+ const value = config.limits?.[key] ?? fallback;
445
+ if (value !== undefined && (!Number.isInteger(value) || value < min || value > max))
446
+ throw new TypeError(`${where}: limits.${key} is an integer from ${min} to ${max}.`);
447
+ return value;
448
+ };
449
+ const maxGenerations = int("maxGenerations", maxTurns * 2, 1, 1_000);
450
+ const maxActiveMs = int("maxActiveMs", 600_000, 1_000, 86_400_000);
451
+ const maxTokens = int("maxTokens", undefined, 1, 100_000_000);
452
+ const concurrency = int("concurrency", 4, 1, 1_000);
453
+ const limits = Object.freeze({ maxTurns, maxToolCalls, maxGenerations, maxActiveMs, concurrency, ...(maxTokens !== undefined ? { maxTokens } : {}) });
454
+ let output;
455
+ if (config.output !== undefined) {
456
+ const candidate = config.output;
457
+ output = typeof candidate?.toJSONSchema === "function" ? config.output : shapeToObjectSchema(config.output);
458
+ }
459
+ return Object.freeze({ instructions: config.instructions, tools: Object.freeze(tools), autonomous: Object.freeze(autonomous), limits, engine, ...(output ? { output } : {}) });
460
+ }
337
461
  /**
338
462
  * Declare a policy: who may call which functions, on which resource, under which conditions
339
463
  * (see PolicyRule and src/policy.ts for the semantics). Deterministic, enforced at the execution
@@ -354,6 +478,10 @@ export class FeltKitApp {
354
478
  if (collection !== undefined && (typeof collection === "string" || this.collections.get(collection.name) !== collection)) {
355
479
  throw new TypeError(`app.policy(${rule.id}): resource.collection must be a collection of this application.`);
356
480
  }
481
+ const by = rule.resource?.by;
482
+ if (by !== undefined && collection !== undefined && typeof collection !== "string" && !uniqueField(collection, by)) {
483
+ throw new TypeError(`app.policy(${rule.id}): resource.by "${by}" must be a field of ${collection.name} with its own unique constraint (unique: [["${by}"]]), so it names one record.`);
484
+ }
357
485
  for (const via of (rule.when ?? []).flatMap(viaCollections)) {
358
486
  if (typeof via === "string" || this.collections.get(via.name) !== via)
359
487
  throw new TypeError(`app.policy(${rule.id}): owner.via.collection must be a collection of this application.`);
@@ -361,6 +489,43 @@ export class FeltKitApp {
361
489
  this.policies.push(rule);
362
490
  return rule;
363
491
  }
492
+ /**
493
+ * Presence (K1): a collection whose records are leases, bound to their holder and ending exactly once
494
+ * (left, removed, expired, session-ended, replaced). Hold one with `ctx.presence.join(peers, fields)`,
495
+ * renew it with `ctx.presence.renew`, end it with `ctx.presence.end`; read live leases with `ctx.db`
496
+ * as usual (expired and ended ones are left out). A lease not renewed within `ttlMs` ends at that time
497
+ * without anyone asking, and live queries over the collection re-run. `onEnd` names an `app.agent` run
498
+ * after each end. See src/presence.ts and docs/PRESENCE-AND-SIGNALING-PROPOSAL.md.
499
+ *
500
+ * export const peers = app.presence("peers", { callId: s.string(), name: s.string() }, { ttlMs: 45_000 });
501
+ */
502
+ presence(name, shape, options) {
503
+ const where = `app.presence("${name}")`;
504
+ if (!options || !Number.isInteger(options.ttlMs) || options.ttlMs < MIN_LEASE_TTL_MS || options.ttlMs > MAX_LEASE_TTL_MS)
505
+ throw new TypeError(`${where}: ttlMs is an integer from ${MIN_LEASE_TTL_MS} to ${MAX_LEASE_TTL_MS} (milliseconds).`);
506
+ for (const field of Object.keys(LEASE_FIELDS))
507
+ if (field in shape)
508
+ throw new TypeError(`${where}: "${field}" is a lease field FeltKit keeps; name yours differently.`);
509
+ let onEnd;
510
+ if (options.onEnd !== undefined) {
511
+ onEnd = typeof options.onEnd === "string" ? options.onEnd : options.onEnd?.name;
512
+ if (typeof onEnd !== "string" || (typeof options.onEnd !== "string" && this.agents.get(onEnd) !== options.onEnd))
513
+ throw new TypeError(`${where}: onEnd names an app.agent of this application.`);
514
+ }
515
+ if (options.history !== undefined && typeof options.history !== "boolean")
516
+ throw new TypeError(`${where}: history is true or false.`);
517
+ const known = new Set(Object.keys(options).filter((k) => !["ttlMs", "onEnd", "history", "tenant", "indexes", "description"].includes(k)));
518
+ if (known.size)
519
+ throw new TypeError(`${where}: unknown option ${[...known].map((k) => `"${k}"`).join(", ")}.`);
520
+ const definition = this.collection(name, { ...shape, ...LEASE_FIELDS }, {
521
+ ...(options.tenant ? { tenant: options.tenant } : {}),
522
+ indexes: [{ fields: ["live"] }, { fields: ["session"] }, { fields: ["holder"] }, ...(options.indexes ?? [])],
523
+ description: options.description ?? `Presence leases (app.presence, ttl ${options.ttlMs} ms).`,
524
+ });
525
+ const config = Object.freeze({ ttlMs: options.ttlMs, history: options.history ?? true, ...(onEnd ? { onEnd } : {}) });
526
+ Object.defineProperty(definition, PRESENCE, { value: config });
527
+ return definition;
528
+ }
364
529
  collection(name, shape, options = {}) {
365
530
  if (!/^[a-z][a-zA-Z0-9_]{0,62}$/.test(name)) {
366
531
  throw new TypeError(`Collection name "${name}" must start with a lowercase letter and contain only letters, digits, and "_".`);
@@ -655,16 +820,37 @@ export class FeltKitApp {
655
820
  }
656
821
  action(input) {
657
822
  const config = input;
658
- if (config?.capability)
659
- throw new TypeError("An action cannot be an AppPort capability: it is not a transaction and makes no single, verifiable change. Expose a mutation as the capability, and call it from the action.");
660
- if (config?.approval)
661
- throw new TypeError("approval applies to mutations. An action changes state only through mutations and proposals, which carry their own approval rules.");
662
823
  if (config?.retry)
663
824
  throw new TypeError("retry applies to mutations.");
664
825
  if (config?.owner !== undefined)
665
826
  throw new TypeError("owner applies to queries and mutations: an action reads and writes only through them, which carry their own ownership rules.");
666
827
  return this.define("action", input);
667
828
  }
829
+ /** A resource binding (FunctionConfig.resource), checked when the function is declared, and frozen. */
830
+ checkResource(input, kind, args) {
831
+ const where = `app.${kind}({ resource })`;
832
+ if (kind === "action")
833
+ throw new TypeError(`${where}: resource applies to queries and mutations (an action reaches records only through them).`);
834
+ const r = input;
835
+ if (!r || typeof r !== "object" || Array.isArray(r))
836
+ throw new TypeError(`${where} is { collection, id, by?, guests?, agents? }.`);
837
+ const unknownKeys = Object.keys(r).filter((k) => !["collection", "id", "by", "guests", "agents"].includes(k));
838
+ if (unknownKeys.length)
839
+ throw new TypeError(`${where}: unknown member ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
840
+ if (!isCollectionDefinition(r.collection) || this.collections.get(r.collection.name) !== r.collection)
841
+ throw new TypeError(`${where}: collection must be a collection of this application.`);
842
+ if (typeof r.id !== "string" || !Object.prototype.hasOwnProperty.call(args, r.id))
843
+ throw new TypeError(`${where}: id names the argument holding the record's id or key (${Object.keys(args).join(", ") || "none declared"}).`);
844
+ if (r.by !== undefined && (typeof r.by !== "string" || !uniqueField(r.collection, r.by)))
845
+ throw new TypeError(`${where}: by "${String(r.by)}" must be a field of ${r.collection.name} with its own unique constraint (unique: [["${String(r.by)}"]]).`);
846
+ if (r.guests !== undefined && typeof r.guests !== "boolean")
847
+ throw new TypeError(`${where}: guests is true or false.`);
848
+ if (r.guests === true && !this.options.auth?.guests)
849
+ throw new TypeError(`${where}: guests: true needs auth.guests (the roles a guest may hold).`);
850
+ if (r.agents !== undefined && r.agents !== "grant")
851
+ throw new TypeError(`${where}: agents is "grant" (or omitted).`);
852
+ return Object.freeze({ collection: r.collection, id: r.id, ...(r.by !== undefined ? { by: r.by } : {}), ...(r.guests ? { guests: true } : {}), ...(r.agents ? { agents: "grant" } : {}) });
853
+ }
668
854
  /** An owner declaration, checked when the function is declared (never at a call), and frozen. */
669
855
  checkOwner(input, kind, access, args) {
670
856
  const where = `app.${kind}({ owner })`;
@@ -743,13 +929,25 @@ export class FeltKitApp {
743
929
  if (config.approval !== undefined) {
744
930
  if (config.approval !== "required")
745
931
  throw new TypeError(`approval must be "required" (or omitted); got ${JSON.stringify(config.approval)}.`);
746
- if (kind !== "mutation")
747
- throw new TypeError("approval: \"required\" applies to mutations: a query changes nothing, so there is nothing to approve.");
932
+ if (kind === "query")
933
+ throw new TypeError("approval: \"required\" applies to mutations and actions: a query changes nothing, so there is nothing to approve.");
748
934
  if (config.access === "public")
749
935
  throw new TypeError("approval: \"required\" needs an access permission: an approval never grants one, and a public function has none to check.");
750
936
  }
751
937
  const owner = config.owner === undefined ? undefined : this.checkOwner(config.owner, kind, config.access, args);
938
+ const quota = config.quota === undefined ? undefined : checkQuota(config.quota, `app.${kind}()`, args);
939
+ const resource = config.resource === undefined ? undefined : this.checkResource(config.resource, kind, args);
940
+ if (config.visibility !== undefined && !VISIBILITIES.includes(config.visibility))
941
+ throw new TypeError(`app.${kind}(): visibility is ${VISIBILITIES.map((v) => `"${v}"`).join(", ")} (or omitted); got ${JSON.stringify(config.visibility)}.`);
942
+ if (config.visibility === "internal" && capability)
943
+ throw new TypeError(`app.${kind}(): an internal function is reached only by the application's own code, so it cannot be published as capability "${capability.name}".`);
944
+ if (config.visibility === "internal" && config.approval)
945
+ throw new TypeError(`app.${kind}(): approval: "required" governs callers on a surface; an internal function has none.`);
946
+ const visibility = config.visibility && config.visibility !== "public" ? config.visibility : undefined;
752
947
  return Object.freeze({
948
+ ...(resource ? { resource } : {}),
949
+ ...(visibility ? { visibility } : {}),
950
+ ...(quota ? { quota } : {}),
753
951
  [FUNCTION]: true,
754
952
  kind,
755
953
  ...(retry ? { retry: Object.freeze(retry) } : {}),
@@ -766,8 +964,18 @@ export class FeltKitApp {
766
964
  });
767
965
  }
768
966
  }
967
+ /** Whether `field` has a single-field unique constraint on `collection` (it then names at most one record). */
968
+ export function uniqueField(collection, field) {
969
+ if (!Object.prototype.hasOwnProperty.call(collection.shape, field))
970
+ return false;
971
+ return (collection.unique ?? []).some((u) => {
972
+ const fields = Array.isArray(u) ? u : u.fields;
973
+ return fields.length === 1 && fields[0] === field;
974
+ });
975
+ }
769
976
  /** Every member a function declaration may have (FunctionConfig). */
770
- const FUNCTION_CONFIG_KEYS = new Set(["args", "returns", "access", "description", "capability", "retry", "approval", "owner", "handler"]);
977
+ const FUNCTION_CONFIG_KEYS = new Set(["args", "returns", "access", "description", "capability", "retry", "approval", "owner", "quota", "resource", "visibility", "handler"]);
978
+ const VISIBILITIES = ["public", "worker", "service", "internal"];
771
979
  /** A reference field's target collection (`s.ref(...)`, optional or not), if it is one. */
772
980
  function referenceTarget(schema) {
773
981
  const json = schema?.toJSONSchema?.();
@@ -784,6 +992,18 @@ export function isFeltKitApp(value) {
784
992
  export function isFunctionDefinition(value) {
785
993
  return typeof value === "object" && value !== null && value[FUNCTION] === true;
786
994
  }
995
+ /**
996
+ * A function group: one export whose function members are named `<module>:<member>`, as if each
997
+ * were exported on its own (a capability built from the public API, such as Boards, ships its
998
+ * functions this way). Members that are not functions (collections, helpers) are ignored.
999
+ */
1000
+ export const FUNCTION_GROUP = Symbol.for("feltkit.functionGroup");
1001
+ export function functionGroup(members) {
1002
+ return Object.freeze(Object.assign(Object.create(null), members, { $functionGroup: true, [FUNCTION_GROUP]: true }));
1003
+ }
1004
+ export function isFunctionGroup(value) {
1005
+ return typeof value === "object" && value !== null && value[FUNCTION_GROUP] === true;
1006
+ }
787
1007
  export function isEventDefinition(value) {
788
1008
  return typeof value === "object" && value !== null && value[EVENT] === true;
789
1009
  }
@@ -815,4 +1035,45 @@ export function capabilityNameSuggestion(name) {
815
1035
  const example = options.length ? `Use ${options.join(" or ")}.` : 'For example "tasks.complete".';
816
1036
  return `Names are lowercase <namespace>.<operation>, ASCII letters and digits only (no hyphens, underscores, or capitals). ${example}`;
817
1037
  }
1038
+ function validateEve(eve, roles, tenantRoles, label) {
1039
+ if (eve === undefined)
1040
+ return;
1041
+ if (!eve || typeof eve !== "object" || Array.isArray(eve))
1042
+ throw new TypeError("feltkit({ eve }) is { <name>: { roles, capabilities, tenantRole?, root? } }.");
1043
+ for (const [name, agent] of Object.entries(eve)) {
1044
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(name))
1045
+ throw new TypeError(`${label ?? `agent "${name}"`}: a name is 1–32 lowercase letters, digits or '-', starting with a letter.`);
1046
+ if (!agent || typeof agent !== "object")
1047
+ throw new TypeError(`${label ?? `agent "${name}"`} is { roles, capabilities, tenantRole?, root? }.`);
1048
+ if (!Array.isArray(agent.roles) || agent.roles.length === 0)
1049
+ throw new TypeError(`${label ?? `agent "${name}"`} needs the roles its worker holds: roles: ["agent"].`);
1050
+ for (const role of agent.roles)
1051
+ if (!roles?.[role])
1052
+ throw new TypeError(`${label ?? `agent "${name}"`} names role "${role}", which is not declared in roles.`);
1053
+ const grants = agent.roles.flatMap((role) => roles?.[role] ?? []);
1054
+ if (!grants.some((g) => g === "*" || g === "feltkit.*" || g === "feltkit.agent.*" || g === "feltkit.agent.write"))
1055
+ throw new TypeError(`${label ?? `agent "${name}"`}: its roles must grant "feltkit.agent.write": each session is an agent task the agent reports on (checkpoints, acknowledged updates). Add it to the "${agent.roles[0]}" role.`);
1056
+ if (!Array.isArray(agent.capabilities) || agent.capabilities.length === 0)
1057
+ throw new TypeError(`${label ?? `agent "${name}"`} needs the capabilities it may be granted: capabilities: ["tasks.*"].`);
1058
+ for (const c of agent.capabilities)
1059
+ if (typeof c !== "string" || !/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*(\.\*)?$/.test(c))
1060
+ throw new TypeError(`${label ?? `agent "${name}"`}: ${JSON.stringify(c)} is not a capability name or "namespace.*".`);
1061
+ if (tenantRoles) {
1062
+ if (!agent.tenantRole)
1063
+ throw new TypeError(`${label ?? `agent "${name}"`}: this application has workspaces, so name the workspace role the agent joins with (tenantRole).`);
1064
+ if (!tenantRoles.includes(agent.tenantRole))
1065
+ throw new TypeError(`${label ?? `agent "${name}"`}: tenantRole "${agent.tenantRole}" is not one of auth.tenant.roles.`);
1066
+ }
1067
+ else if (agent.tenantRole !== undefined)
1068
+ throw new TypeError(`${label ?? `agent "${name}"`}: tenantRole needs auth.tenant.`);
1069
+ if (agent.root !== undefined && (typeof agent.root !== "string" || agent.root.startsWith("/") || agent.root.split(/[\\/]/).includes("..")))
1070
+ throw new TypeError(`${label ?? `agent "${name}"`}: root is a directory inside the application.`);
1071
+ if (agent.grantTtlMs !== undefined && (!Number.isInteger(agent.grantTtlMs) || agent.grantTtlMs < 3_600_000 || agent.grantTtlMs > 30 * 24 * 3_600_000))
1072
+ throw new TypeError(`${label ?? `agent "${name}"`}: grantTtlMs is from one hour to 30 days.`);
1073
+ }
1074
+ }
1075
+ /** Every agent of the application that runs on the agent runtime: `app.agent(name, { project })` and `feltkit({ eve })`. */
1076
+ export function projectAgentsOf(app) {
1077
+ return { ...(app.options.eve ?? {}), ...Object.fromEntries(app.projectAgents) };
1078
+ }
818
1079
  //# sourceMappingURL=app.js.map