@feltdb/feltkit 0.3.36 → 0.4.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 (130) hide show
  1. package/dist/app.d.ts +153 -3
  2. package/dist/app.js +159 -7
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +21 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest.js +4 -0
  7. package/dist/appboundry/guest.js.map +1 -1
  8. package/dist/client/index.d.ts +189 -0
  9. package/dist/client/index.js +201 -0
  10. package/dist/client/index.js.map +1 -1
  11. package/dist/clock.d.ts +24 -0
  12. package/dist/clock.js +49 -0
  13. package/dist/clock.js.map +1 -0
  14. package/dist/dashboard/assets/index-BhxrvY37.js +15 -0
  15. package/dist/dashboard/assets/index-CSzYeCo_.css +1 -0
  16. package/dist/dashboard/index.html +2 -2
  17. package/dist/docs.d.ts +1 -1
  18. package/dist/docs.js +1 -0
  19. package/dist/docs.js.map +1 -1
  20. package/dist/event-stage.js +2 -0
  21. package/dist/event-stage.js.map +1 -1
  22. package/dist/index.d.ts +11 -1
  23. package/dist/index.js +1 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/policy.d.ts +9 -1
  26. package/dist/policy.js +16 -3
  27. package/dist/policy.js.map +1 -1
  28. package/dist/presence.d.ts +85 -0
  29. package/dist/presence.js +37 -0
  30. package/dist/presence.js.map +1 -0
  31. package/dist/quota.d.ts +72 -0
  32. package/dist/quota.js +143 -0
  33. package/dist/quota.js.map +1 -0
  34. package/dist/react/agent-control.d.ts +189 -0
  35. package/dist/react/agent-control.js +366 -0
  36. package/dist/react/agent-control.js.map +1 -0
  37. package/dist/react/index.d.ts +14 -1
  38. package/dist/react/index.js +41 -0
  39. package/dist/react/index.js.map +1 -1
  40. package/dist/runtime/activity.d.ts +8 -0
  41. package/dist/runtime/activity.js.map +1 -1
  42. package/dist/runtime/agent-control.d.ts +18 -0
  43. package/dist/runtime/agent-control.js +34 -1
  44. package/dist/runtime/agent-control.js.map +1 -1
  45. package/dist/runtime/agent.js +16 -4
  46. package/dist/runtime/agent.js.map +1 -1
  47. package/dist/runtime/assemble.js +1 -1
  48. package/dist/runtime/assemble.js.map +1 -1
  49. package/dist/runtime/authority.d.ts +38 -0
  50. package/dist/runtime/authority.js +13 -2
  51. package/dist/runtime/authority.js.map +1 -1
  52. package/dist/runtime/capabilities.js +2 -1
  53. package/dist/runtime/capabilities.js.map +1 -1
  54. package/dist/runtime/changes.d.ts +17 -0
  55. package/dist/runtime/changes.js +65 -2
  56. package/dist/runtime/changes.js.map +1 -1
  57. package/dist/runtime/context.d.ts +114 -0
  58. package/dist/runtime/contract.js +9 -3
  59. package/dist/runtime/contract.js.map +1 -1
  60. package/dist/runtime/events.js +17 -1
  61. package/dist/runtime/events.js.map +1 -1
  62. package/dist/runtime/integrations.js +7 -7
  63. package/dist/runtime/integrations.js.map +1 -1
  64. package/dist/runtime/invocations.d.ts +19 -2
  65. package/dist/runtime/invocations.js +16 -3
  66. package/dist/runtime/invocations.js.map +1 -1
  67. package/dist/runtime/policies.d.ts +5 -2
  68. package/dist/runtime/policies.js.map +1 -1
  69. package/dist/runtime/presence-host.d.ts +84 -0
  70. package/dist/runtime/presence-host.js +303 -0
  71. package/dist/runtime/presence-host.js.map +1 -0
  72. package/dist/runtime/providers.d.ts +130 -1
  73. package/dist/runtime/providers.js +251 -9
  74. package/dist/runtime/providers.js.map +1 -1
  75. package/dist/runtime/resource-access.d.ts +137 -0
  76. package/dist/runtime/resource-access.js +177 -0
  77. package/dist/runtime/resource-access.js.map +1 -0
  78. package/dist/runtime/runtime.d.ts +73 -0
  79. package/dist/runtime/runtime.js +594 -37
  80. package/dist/runtime/runtime.js.map +1 -1
  81. package/dist/runtime/sessions.d.ts +11 -0
  82. package/dist/runtime/sessions.js +15 -0
  83. package/dist/runtime/sessions.js.map +1 -1
  84. package/dist/runtime/tenancy.d.ts +59 -0
  85. package/dist/runtime/tenancy.js +128 -0
  86. package/dist/runtime/tenancy.js.map +1 -1
  87. package/dist/runtime/workers.d.ts +123 -0
  88. package/dist/runtime/workers.js +291 -0
  89. package/dist/runtime/workers.js.map +1 -0
  90. package/dist/server/admin.js +48 -1
  91. package/dist/server/admin.js.map +1 -1
  92. package/dist/server/index.d.ts +0 -19
  93. package/dist/server/index.js +61 -4
  94. package/dist/server/index.js.map +1 -1
  95. package/dist/server/mcp.d.ts +8 -15
  96. package/dist/server/mcp.js +40 -3
  97. package/dist/server/mcp.js.map +1 -1
  98. package/dist/server/project.js +6 -5
  99. package/dist/server/project.js.map +1 -1
  100. package/dist/server/tenancy.d.ts +7 -0
  101. package/dist/server/tenancy.js +31 -0
  102. package/dist/server/tenancy.js.map +1 -1
  103. package/dist/server/watch.d.ts +10 -0
  104. package/dist/server/watch.js +88 -0
  105. package/dist/server/watch.js.map +1 -0
  106. package/dist/testing/index.d.ts +3 -1
  107. package/dist/testing/index.js +3 -2
  108. package/dist/testing/index.js.map +1 -1
  109. package/docs/AGENT-CONTROL.md +130 -4
  110. package/docs/APPBOUNDRY.md +37 -0
  111. package/docs/ARCHITECTURE.md +6 -2
  112. package/docs/AUTH.md +35 -0
  113. package/docs/COMPONENTS.md +71 -0
  114. package/docs/GUARANTEES.md +4 -4
  115. package/docs/PRESENCE-AND-SIGNALING-PROPOSAL.md +152 -0
  116. package/docs/PROVIDERS.md +58 -1
  117. package/docs/README.md +3 -2
  118. package/docs/SECURITY.md +71 -3
  119. package/docs/TRANSACTIONS.md +48 -0
  120. package/docs/UPSTREAM-GAPS.md +16 -2
  121. package/package.json +16 -16
  122. package/skills/.claude-plugin/marketplace.json +1 -1
  123. package/skills/.claude-plugin/plugin.json +1 -1
  124. package/skills/feltkit-agent/SKILL.md +1 -1
  125. package/skills/feltkit-build/SKILL.md +11 -1
  126. package/skills/feltkit-data/SKILL.md +1 -1
  127. package/skills/feltkit-operations/SKILL.md +1 -1
  128. package/skills/feltkit-services/SKILL.md +1 -1
  129. package/dist/dashboard/assets/index-9rMS3yBm.js +0 -15
  130. package/dist/dashboard/assets/index-DkiYTUMR.css +0 -1
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The runtime's half of presence (src/presence.ts): `ctx.presence`, the read view that shows only leases
3
+ * that hold now, and the ends nobody asks for (expiry, by a timer on the runtime's clock; a session that
4
+ * ended). Every end is one FeltDB transaction that conditions on the lease's version, so a lease ends
5
+ * once whatever races it (a renew, another end, another sweep), and the onEnd agent run is recorded in
6
+ * that same transaction.
7
+ */
8
+ import type { CollectionDefinition, FeltKitApp } from "../app.js";
9
+ import type { Clock } from "../clock.js";
10
+ import { type Lease, type LeaseEndReason } from "../presence.js";
11
+ import type { DatabaseReader, DatabaseWriter } from "./data.js";
12
+ import { Writer } from "./data.js";
13
+ import type { CollectionResolver } from "./collections.js";
14
+ import { type OutboxEffect, type OutboxRecord } from "./outbox.js";
15
+ import type { Principal } from "./authority.js";
16
+ import type { StateFirstDB } from "@feltdb/core";
17
+ export interface PresenceDeps {
18
+ app(): FeltKitApp;
19
+ handle(): StateFirstDB;
20
+ resolver(): CollectionResolver;
21
+ clock: Clock;
22
+ /** The outbox effect that runs agent `name` (the runtime's #agentEffect). */
23
+ agentEffect(name: string, input: Record<string, unknown>, tenantId: string | undefined): OutboxEffect;
24
+ /** After a commit made outside a call: describe it to the change feed, check it, start agent runs. */
25
+ committed(commit: Awaited<ReturnType<Writer["commit"]>>, outbox: OutboxRecord[]): void;
26
+ warn(message: string): void;
27
+ }
28
+ /** What `ctx.presence` offers. Join, renew and end exist in mutations only. */
29
+ export interface PresenceWriter {
30
+ /**
31
+ * Hold a lease in `collection` as the caller, bound to the caller's session when the call has one.
32
+ * `key`: one live lease per holder and key (joining again ends the earlier one as "replaced").
33
+ * `bind: "session"`: no expiry; the lease lives until the holder's session ends (a resident agent),
34
+ * or until it is ended. Needs a session.
35
+ */
36
+ join<C extends CollectionDefinition>(collection: C, fields: Record<string, unknown>, options?: {
37
+ key?: string;
38
+ bind?: "ttl" | "session";
39
+ }): Promise<{
40
+ id: string;
41
+ expiresAt: number | null;
42
+ }>;
43
+ /** Extend a lease (and optionally change its fields). Only its holder; an ended or expired lease is NOT_FOUND. */
44
+ renew<C extends CollectionDefinition>(collection: C, id: string, fields?: Record<string, unknown>): Promise<{
45
+ id: string;
46
+ expiresAt: number | null;
47
+ }>;
48
+ /** End a lease: "left" when its holder ends it, "removed" otherwise (the function's access decided who may). */
49
+ end<C extends CollectionDefinition>(collection: C, id: string): Promise<{
50
+ id: string;
51
+ reason: LeaseEndReason;
52
+ }>;
53
+ /** Every lease, ended ones included (attendance), matching an equality filter. */
54
+ history<C extends CollectionDefinition>(collection: C, filter?: Record<string, unknown>): Promise<Lease[]>;
55
+ }
56
+ export type PresenceReader = Pick<PresenceWriter, "history">;
57
+ export declare class PresenceHost {
58
+ #private;
59
+ constructor(deps: PresenceDeps);
60
+ /** The application's presence collections. */
61
+ collections(): CollectionDefinition[];
62
+ names(): Set<string>;
63
+ /** A reader (or writer) whose presence collections show only leases that hold now, and refuse direct writes. */
64
+ view<D extends DatabaseReader>(inner: D): D;
65
+ /**
66
+ * `ctx.presence` for one call. `db` is the call's own (tenant-scoped) writer, so a lease commits with
67
+ * the mutation's other writes; `stage` records an outbox entry in the same transaction.
68
+ */
69
+ api(db: DatabaseWriter | DatabaseReader, principal: Principal | null, session: {
70
+ ref: string;
71
+ } | null, stage: ((record: OutboxRecord) => void) | null, call: {
72
+ function: string;
73
+ requestId: string;
74
+ }): PresenceWriter | PresenceReader;
75
+ /** Check every onEnd names an application agent (at start and reload). */
76
+ check(): void;
77
+ /** End every ttl lease past its expiry (reason "expired"). Returns how many ended. One sweep at a time. */
78
+ sweep(): Promise<number>;
79
+ /** End every lease held under a session that ended (reason "session-ended"). */
80
+ endForSession(ref: string): Promise<number>;
81
+ /** Arm the timer for the earliest expiry of a live ttl lease (or none). Called at start and after presence writes. */
82
+ arm(): Promise<void>;
83
+ close(): void;
84
+ }
@@ -0,0 +1,303 @@
1
+ import { FeltKitError } from "../errors.js";
2
+ import { leaseHolds, presenceOf, LEASE_FIELDS } from "../presence.js";
3
+ import { readAll, Writer } from "./data.js";
4
+ import { newOutboxId, OUTBOX_COLLECTION } from "./outbox.js";
5
+ const PLATFORM = new Set(Object.keys(LEASE_FIELDS));
6
+ const actorOf = (p) => `${p.type}:${p.id}`;
7
+ export class PresenceHost {
8
+ #deps;
9
+ #cancel;
10
+ #armedFor = null;
11
+ #sweeping = null;
12
+ #closed = false;
13
+ constructor(deps) {
14
+ this.#deps = deps;
15
+ }
16
+ /** The application's presence collections. */
17
+ collections() {
18
+ return [...this.#deps.app().collections.values()].filter((c) => presenceOf(c));
19
+ }
20
+ names() {
21
+ return new Set(this.collections().map((c) => c.name));
22
+ }
23
+ #definition(ref) {
24
+ const definition = this.#deps.resolver().resolve(ref);
25
+ const config = presenceOf(definition);
26
+ if (!config)
27
+ throw new FeltKitError("INVALID_ARGUMENT", `ctx.presence: ${definition.name} is not a presence collection (declare it with app.presence).`);
28
+ return Object.assign(Object.create(definition), definition, { config });
29
+ }
30
+ // ---- ctx.db over presence collections --------------------------------------------------
31
+ /** A reader (or writer) whose presence collections show only leases that hold now, and refuse direct writes. */
32
+ view(inner) {
33
+ const resolve = (ref) => this.#deps.resolver().resolve(ref);
34
+ const isPresence = (ref) => presenceOf(resolve(ref)) !== null;
35
+ const now = () => this.#deps.clock.now();
36
+ const reader = {
37
+ async get(ref, id) {
38
+ const record = await inner.get(ref, id);
39
+ return !isPresence(ref) || leaseHolds(record, now()) ? record : null;
40
+ },
41
+ async find(ref, filter, options) {
42
+ if (!isPresence(ref))
43
+ return inner.find(ref, filter, options);
44
+ const all = await inner.find(ref, { ...(filter ?? {}), live: true }, options?.orderBy ? { orderBy: options.orderBy } : {});
45
+ const live = all.filter((r) => leaseHolds(r, now()));
46
+ return options?.limit !== undefined ? live.slice(0, options.limit) : live;
47
+ },
48
+ async count(ref, filter) {
49
+ if (!isPresence(ref))
50
+ return inner.count(ref, filter);
51
+ return (await reader.find(ref, filter)).length;
52
+ },
53
+ async query(ref, request) {
54
+ if (!isPresence(ref))
55
+ return inner.query(ref, request);
56
+ // A page may hold fewer records than its limit: leases past their expiry are left out of it.
57
+ const page = await inner.query(ref, { ...request, where: [...(request?.where ?? []).filter((c) => c.field !== "live"), { field: "live", eq: true }] });
58
+ return { ...page, records: page.records.filter((r) => leaseHolds(r, now())) };
59
+ },
60
+ async search(ref, request) {
61
+ if (!isPresence(ref))
62
+ return inner.search(ref, request);
63
+ const found = await inner.search(ref, { ...request, where: { ...(request?.where ?? {}), live: true } });
64
+ return found.filter((r) => leaseHolds(r, now()));
65
+ },
66
+ };
67
+ if (!("insert" in inner))
68
+ return reader;
69
+ const writer = inner;
70
+ const refuse = (ref) => {
71
+ if (isPresence(ref))
72
+ throw new FeltKitError("FORBIDDEN", `${resolve(ref).name} holds presence leases: change them with ctx.presence.join, renew and end, not ctx.db.`, { hint: "PRESENCE" });
73
+ };
74
+ const guarded = {
75
+ ...reader,
76
+ insert: async (ref, value) => (refuse(ref), writer.insert(ref, value)),
77
+ patch: async (ref, id, fields) => (refuse(ref), writer.patch(ref, id, fields)),
78
+ replace: async (ref, id, value) => (refuse(ref), writer.replace(ref, id, value)),
79
+ delete: async (ref, id) => (refuse(ref), writer.delete(ref, id)),
80
+ sequence: (name) => writer.sequence(name),
81
+ };
82
+ return guarded;
83
+ }
84
+ // ---- ctx.presence ------------------------------------------------------------------------
85
+ /**
86
+ * `ctx.presence` for one call. `db` is the call's own (tenant-scoped) writer, so a lease commits with
87
+ * the mutation's other writes; `stage` records an outbox entry in the same transaction.
88
+ */
89
+ api(db, principal, session, stage, call) {
90
+ const history = async (collection, filter = {}) => {
91
+ const definition = this.#definition(collection);
92
+ return (await db.find(definition, filter));
93
+ };
94
+ if (!stage || !("insert" in db))
95
+ return { history };
96
+ const writer = db;
97
+ const clock = this.#deps.clock;
98
+ const who = () => {
99
+ if (!principal)
100
+ throw new FeltKitError("UNAUTHORIZED", "A lease has a holder: sign in to hold one.");
101
+ return principal;
102
+ };
103
+ const fieldsOnly = (fields) => {
104
+ for (const key of Object.keys(fields ?? {}))
105
+ if (PLATFORM.has(key))
106
+ throw new FeltKitError("INVALID_ARGUMENT", `ctx.presence: "${key}" is kept by FeltKit.`);
107
+ return fields ?? {};
108
+ };
109
+ const live = async (definition, id) => {
110
+ const record = (await writer.get(definition, id));
111
+ if (!record || !leaseHolds(record, clock.now()))
112
+ throw new FeltKitError("NOT_FOUND", `No live lease ${id} in ${definition.name} (it ended or expired).`);
113
+ return record;
114
+ };
115
+ const endWith = async (definition, record, reason, by) => {
116
+ const at = clock.now();
117
+ if (definition.config.history)
118
+ await writer.patch(definition, record.id, { live: false, endedAt: at, endReason: reason, endedBy: by });
119
+ else
120
+ await writer.delete(definition, record.id);
121
+ const effect = this.#onEnd(definition, { ...record, live: false, endedAt: at, endReason: reason, endedBy: by });
122
+ if (effect)
123
+ stage(this.#outbox(effect, call.function, call.requestId, principal?.id ?? "platform", at));
124
+ };
125
+ return {
126
+ history,
127
+ join: async (collection, fields, options = {}) => {
128
+ const p = who();
129
+ const definition = this.#definition(collection);
130
+ const bind = options.bind ?? "ttl";
131
+ if (bind !== "ttl" && bind !== "session")
132
+ throw new FeltKitError("INVALID_ARGUMENT", 'ctx.presence.join: bind is "ttl" or "session".');
133
+ if (bind === "session" && !session)
134
+ throw new FeltKitError("FAILED_PRECONDITION", "A session-bound lease needs a session: this call has none (an API key, a job, a test caller without one).");
135
+ if (options.key !== undefined && (typeof options.key !== "string" || !options.key || options.key.length > 200))
136
+ throw new FeltKitError("INVALID_ARGUMENT", "ctx.presence.join: key is a string of 1 to 200 characters.");
137
+ if (options.key !== undefined) {
138
+ for (const earlier of (await writer.find(definition, { holder: p.id, key: options.key, live: true })))
139
+ await endWith(definition, earlier, "replaced", actorOf(p));
140
+ }
141
+ const now = clock.now();
142
+ const expiresAt = bind === "ttl" ? now + definition.config.ttlMs : null;
143
+ const id = await writer.insert(definition, {
144
+ ...fieldsOnly(fields),
145
+ holder: p.id,
146
+ holderType: p.type,
147
+ ...(session ? { session: session.ref } : {}),
148
+ ...(options.key !== undefined ? { key: options.key } : {}),
149
+ binding: bind,
150
+ startedAt: now,
151
+ renewedAt: now,
152
+ ...(expiresAt !== null ? { expiresAt } : {}),
153
+ live: true,
154
+ });
155
+ return { id, expiresAt };
156
+ },
157
+ renew: async (collection, id, fields) => {
158
+ const p = who();
159
+ const definition = this.#definition(collection);
160
+ const record = await live(definition, id);
161
+ if (record.holder !== p.id)
162
+ throw new FeltKitError("FORBIDDEN", "Only a lease's holder renews it.");
163
+ const now = clock.now();
164
+ const expiresAt = record.binding === "session" ? null : now + definition.config.ttlMs;
165
+ await writer.patch(definition, id, { ...fieldsOnly(fields), renewedAt: now, ...(expiresAt !== null ? { expiresAt } : {}) });
166
+ return { id, expiresAt };
167
+ },
168
+ end: async (collection, id) => {
169
+ const p = who();
170
+ const definition = this.#definition(collection);
171
+ const record = await live(definition, id);
172
+ const reason = record.holder === p.id ? "left" : "removed";
173
+ await endWith(definition, record, reason, actorOf(p));
174
+ return { id, reason };
175
+ },
176
+ };
177
+ }
178
+ #onEnd(definition, lease) {
179
+ const agent = definition.config.onEnd;
180
+ if (!agent)
181
+ return null;
182
+ const { __version: _v, ...plain } = lease;
183
+ const tenantField = definition.tenant?.field;
184
+ const tenantId = tenantField && typeof plain[tenantField] === "string" ? plain[tenantField] : undefined;
185
+ return this.#deps.agentEffect(agent, { presence: definition.name, lease: plain, reason: plain.endReason }, tenantId);
186
+ }
187
+ #outbox(effect, fn, requestId, principalId, at) {
188
+ const tenantId = effect.tenantId;
189
+ return { id: newOutboxId(), requestId, function: fn, principalId, ...(tenantId ? { tenantId } : {}), effect, state: "pending", createdAt: at, updatedAt: at, attempts: 0 };
190
+ }
191
+ /** Check every onEnd names an application agent (at start and reload). */
192
+ check() {
193
+ for (const definition of this.collections()) {
194
+ const agent = presenceOf(definition).onEnd;
195
+ if (agent && !this.#deps.app().agents.has(agent))
196
+ throw new FeltKitError("CONFIGURATION", `app.presence("${definition.name}"): onEnd names "${agent}", which is not an app.agent of this application.`);
197
+ }
198
+ }
199
+ // ---- Ends nobody asks for ----------------------------------------------------------------
200
+ /** End one lease outside a call (expiry, session end): its own transaction, conditioned on its version. */
201
+ async #endNow(definition, id, reason, holds) {
202
+ const config = presenceOf(definition);
203
+ const writer = new Writer(this.#deps.handle(), this.#deps.resolver());
204
+ const record = (await writer.get(definition, id));
205
+ if (!record || record.live !== true || !holds(record))
206
+ return false;
207
+ const at = this.#deps.clock.now();
208
+ if (config.history)
209
+ await writer.patch(definition, id, { live: false, endedAt: at, endReason: reason, endedBy: "platform" });
210
+ else
211
+ await writer.delete(definition, id);
212
+ const effect = this.#onEnd(Object.assign(Object.create(definition), definition, { config }), { ...record, live: false, endedAt: at, endReason: reason, endedBy: "platform" });
213
+ const outbox = effect ? [this.#outbox(effect, `presence:${definition.name}`, `presence_${reason}_${id}`, "platform", at)] : [];
214
+ for (const entry of outbox)
215
+ writer.stageSystem(OUTBOX_COLLECTION, entry);
216
+ try {
217
+ const commit = await writer.commit(`presence_end_${id}_${record.__version}`);
218
+ this.#deps.committed(commit, outbox);
219
+ return true;
220
+ }
221
+ catch (error) {
222
+ // Renewed or ended concurrently: whoever committed first decided; this end did not happen.
223
+ if (error.code === "CONFLICT" || error.code === "OUTCOME_UNKNOWN")
224
+ return false;
225
+ throw error;
226
+ }
227
+ }
228
+ /** End every ttl lease past its expiry (reason "expired"). Returns how many ended. One sweep at a time. */
229
+ sweep() {
230
+ if (this.#sweeping)
231
+ return this.#sweeping.then(() => this.sweep());
232
+ const run = (async () => {
233
+ let ended = 0;
234
+ const now = this.#deps.clock.now();
235
+ for (const definition of this.collections()) {
236
+ const live = (await readAll(this.#deps.handle(), { collection: definition.name, where: [{ field: "live", eq: true }] }));
237
+ for (const lease of live) {
238
+ if (typeof lease.expiresAt !== "number" || lease.expiresAt > now)
239
+ continue;
240
+ try {
241
+ if (await this.#endNow(definition, lease.id, "expired", (l) => typeof l.expiresAt === "number" && l.expiresAt <= this.#deps.clock.now()))
242
+ ended += 1;
243
+ }
244
+ catch (error) {
245
+ this.#deps.warn(`presence: ending expired lease ${definition.name}/${lease.id} failed: ${error.message}`);
246
+ }
247
+ }
248
+ }
249
+ return ended;
250
+ })();
251
+ this.#sweeping = run.finally(() => {
252
+ this.#sweeping = null;
253
+ });
254
+ return this.#sweeping.then(async (n) => {
255
+ await this.arm();
256
+ return n;
257
+ });
258
+ }
259
+ /** End every lease held under a session that ended (reason "session-ended"). */
260
+ async endForSession(ref) {
261
+ let ended = 0;
262
+ for (const definition of this.collections()) {
263
+ const held = (await readAll(this.#deps.handle(), { collection: definition.name, where: [{ field: "session", eq: ref }] }));
264
+ for (const lease of held)
265
+ if (lease.live === true && (await this.#endNow(definition, lease.id, "session-ended", () => true)))
266
+ ended += 1;
267
+ }
268
+ if (ended)
269
+ await this.arm();
270
+ return ended;
271
+ }
272
+ /** Arm the timer for the earliest expiry of a live ttl lease (or none). Called at start and after presence writes. */
273
+ async arm() {
274
+ if (this.#closed)
275
+ return;
276
+ let earliest = null;
277
+ for (const definition of this.collections()) {
278
+ const live = (await readAll(this.#deps.handle(), { collection: definition.name, where: [{ field: "live", eq: true }] }));
279
+ for (const lease of live)
280
+ if (typeof lease.expiresAt === "number" && (earliest === null || lease.expiresAt < earliest))
281
+ earliest = lease.expiresAt;
282
+ }
283
+ if (earliest === this.#armedFor && this.#cancel)
284
+ return;
285
+ this.#cancel?.();
286
+ this.#cancel = undefined;
287
+ this.#armedFor = earliest;
288
+ if (earliest === null || this.#closed)
289
+ return;
290
+ const delay = Math.max(0, earliest - this.#deps.clock.now());
291
+ this.#cancel = this.#deps.clock.setTimer(() => {
292
+ this.#cancel = undefined;
293
+ this.#armedFor = null;
294
+ void this.sweep().catch((error) => this.#deps.warn(`presence sweep: ${error.message}`));
295
+ }, delay);
296
+ }
297
+ close() {
298
+ this.#closed = true;
299
+ this.#cancel?.();
300
+ this.#cancel = undefined;
301
+ }
302
+ }
303
+ //# sourceMappingURL=presence-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence-host.js","sourceRoot":"","sources":["../../src/runtime/presence-host.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAmC,MAAM,gBAAgB,CAAC;AAEvG,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAwC,MAAM,aAAa,CAAC;AAqCnG,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;AACpD,MAAM,OAAO,GAAG,CAAC,CAAY,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC;AAEtD,MAAM,OAAO,YAAY;IACd,KAAK,CAAe;IAC7B,OAAO,CAA2B;IAClC,SAAS,GAAkB,IAAI,CAAC;IAChC,SAAS,GAA2B,IAAI,CAAC;IACzC,OAAO,GAAG,KAAK,CAAC;IAEhB,YAAY,IAAkB;QAC5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED,8CAA8C;IAC9C,WAAW;QACT,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IACjF,CAAC;IAED,KAAK;QACH,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACxD,CAAC;IAED,WAAW,CAAC,GAA+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AAC;YACzB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;YACtB,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAoB,KAAe,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QACrG,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,KAAK;QACH,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC3B,CAAC;CACF"}
@@ -1,4 +1,4 @@
1
- import { AccessGrants, type CapabilityDefinition, type ProviderDefinition, type ProviderHealth } from "@appport/core";
1
+ import { AccessGrants, type CapabilityDefinition, type EffectVerification, type ExternalCallRecord, type ExternalCallRecorder, type ExternalCallSettlement, type ProviderDefinition, type ProviderHealth } from "@appport/core";
2
2
  import { FeltKitError } from "../errors.js";
3
3
  import type { ProviderDeclaration } from "../providers.js";
4
4
  export type { ProviderDeclaration } from "../providers.js";
@@ -10,6 +10,16 @@ export declare const PROVIDER_CALLS = "_feltkit_provider_calls";
10
10
  */
11
11
  export declare function loadProvider(name: string, declaration: ProviderDeclaration, projectDir: string): Promise<ProviderDefinition<any, any>>;
12
12
  export interface ProviderHostRuntime {
13
+ /** Whether `principal` holds `permission` under the application's roles (settling a call needs its capability's). */
14
+ holds?(principal: {
15
+ id: string;
16
+ type: string;
17
+ } | null, permission: string): boolean;
18
+ /** The permissions an application capability requires (an action recording effects), or null when there is none. */
19
+ capabilityAccess?(capability: string): readonly string[] | null;
20
+ readonly activity?: {
21
+ record(event: Record<string, unknown>): unknown;
22
+ };
13
23
  readonly logger: {
14
24
  info?(message: string, meta?: object): void;
15
25
  warn?(message: string, meta?: object): void;
@@ -59,7 +69,126 @@ export declare class ProviderHost {
59
69
  health(): Promise<Record<string, ProviderHealth>>;
60
70
  /** A provider's external call record. */
61
71
  call(id: string): Promise<Record<string, unknown> | null>;
72
+ /**
73
+ * Calls whose outcome is unknown and not yet settled, newest first: `unknown`, and `started` with no outcome for
74
+ * longer than STRANDED_AFTER_MS (the process that ran it died) and not running here. For a person, only the calls of
75
+ * capabilities they may perform.
76
+ */
77
+ unsettled(principal: {
78
+ id: string;
79
+ type: string;
80
+ } | null, options?: {
81
+ limit?: number;
82
+ now?: number;
83
+ }): Promise<ExternalCallRecord[]>;
84
+ /** Recent provider calls, newest first, each as the operator sees it (any state; `status` filters). */
85
+ calls(principal: {
86
+ id: string;
87
+ type: string;
88
+ } | null, options?: {
89
+ status?: ProviderCallView["status"][];
90
+ limit?: number;
91
+ now?: number;
92
+ }): Promise<ProviderCallView[]>;
93
+ /** One provider call as the operator sees it. */
94
+ callView(id: string, principal: {
95
+ id: string;
96
+ type: string;
97
+ } | null, options?: {
98
+ now?: number;
99
+ }): Promise<ProviderCallView>;
100
+ /**
101
+ * Asks the provider what happened to an unsettled call; a definite answer is recorded as its settlement, by
102
+ * verification, with `principal` as who asked. Returns the call as recorded and what the provider answered.
103
+ */
104
+ verify(id: string, principal: {
105
+ id: string;
106
+ type: string;
107
+ } | null, options?: {
108
+ now?: number;
109
+ }): Promise<{
110
+ call: ExternalCallRecord;
111
+ verification: EffectVerification;
112
+ }>;
113
+ /**
114
+ * A person settles an unsettled call, saying what they checked. Evidence first: the provider is asked; an answer
115
+ * that contradicts the person is refused (CONFLICT), one that agrees is recorded as verification confirmed by them,
116
+ * and only when it cannot tell is their decision recorded as theirs (determinedBy "person").
117
+ */
118
+ settle(id: string, input: {
119
+ outcome: "succeeded" | "failed";
120
+ note: string;
121
+ }, principal: {
122
+ id: string;
123
+ type: string;
124
+ } | null, options?: {
125
+ now?: number;
126
+ }): Promise<ExternalCallRecord>;
62
127
  close(): Promise<void>;
128
+ /** The recorder for application actions' external effects (`ctx.effect`): the same records, lifecycle and settlement. */
129
+ effectRecorder(): ExternalCallRecorder;
130
+ }
131
+ /**
132
+ * How long a call may stay `started` with no outcome before it counts as stranded (its process died) and is settleable.
133
+ * Ten minutes; an operator may set FELTKIT_PROVIDER_STRANDED_AFTER_SECONDS (at least 1) to match how long their
134
+ * provider calls can run. Too short a value lets a person settle a call that is still running elsewhere.
135
+ */
136
+ export declare const STRANDED_AFTER_MS: number;
137
+ export declare function strandedAfterMs(env?: NodeJS.ProcessEnv): number;
138
+ /** One time the external system was asked about a call: who asked, when, and what it answered. */
139
+ export interface VerificationAttempt {
140
+ at: string;
141
+ by: {
142
+ id: string;
143
+ type?: string;
144
+ };
145
+ outcome: "succeeded" | "failed" | "unknown";
146
+ conclusive: boolean;
147
+ evidence?: unknown;
148
+ reason?: string;
149
+ }
150
+ /**
151
+ * A call as an operator sees it. `recorded` is what the host recorded when the call ran, never rewritten; the
152
+ * verification attempts and the settlement are what was established afterwards, kept separately.
153
+ *
154
+ * status succeeded / failed the recorded outcome is known (a known failure is not an uncertain effect)
155
+ * running started, no outcome yet, and may still be running
156
+ * unknown the outcome is unknown and not settled
157
+ * stranded started, no outcome, older than the stranded threshold, not running here
158
+ * verified / decided settled: by the external system's answer, or by a person's decision
159
+ */
160
+ export interface ProviderCallView {
161
+ id: string;
162
+ provider: string;
163
+ capability: string;
164
+ principal: {
165
+ id: string;
166
+ type?: string;
167
+ } | null;
168
+ detail: unknown;
169
+ environment: string | null;
170
+ startedAt: string;
171
+ recorded: {
172
+ outcome: "succeeded" | "failed" | "unknown" | null;
173
+ finishedAt: string | null;
174
+ error: {
175
+ code: string;
176
+ message: string;
177
+ } | null;
178
+ };
179
+ status: "succeeded" | "failed" | "running" | "unknown" | "stranded" | "verified" | "decided";
180
+ /** When the outcome became uncertain: the recorded finish of an unknown call, or the start of a stranded one. */
181
+ uncertainSince: string | null;
182
+ verifications: VerificationAttempt[];
183
+ settlement: ExternalCallSettlement | null;
184
+ /** Whether the capability can ask the external system (declares verify, and its provider is running here). */
185
+ verifiable: boolean;
186
+ /** What this person may do now, and why not. */
187
+ may: {
188
+ verify: boolean;
189
+ decide: boolean;
190
+ why: string | null;
191
+ };
63
192
  }
64
193
  /**
65
194
  * An AppPort error from a provider capability as the FeltKit error application code sees. An effect whose outcome is