@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
@@ -87,6 +87,19 @@ function extensionIdentityApi() {
87
87
  const identity = globalThis.chrome?.identity;
88
88
  return identity && typeof identity.launchWebAuthFlow === "function" && typeof identity.getRedirectURL === "function" ? identity : null;
89
89
  }
90
+ /**
91
+ * Whether an error says the call may or may not have taken effect (an external effect with no definite answer):
92
+ * never repeat it blindly; ask `client.invocationStatus` and settle it.
93
+ */
94
+ export function isOutcomeUnknown(error) {
95
+ const e = error;
96
+ return !!e && (e.code === "OUTCOME_UNKNOWN" || e.details?.reason === "EFFECT_OUTCOME_UNKNOWN" || e.details?.reason === "IDEMPOTENCY_OUTCOME_UNKNOWN");
97
+ }
98
+ /** The call an unknown outcome is about (its request id), when the error names it. */
99
+ export function unknownCallId(error) {
100
+ const id = error?.details?.callId;
101
+ return typeof id === "string" ? id : undefined;
102
+ }
90
103
  /** A token store that holds nothing: in cookie mode the browser keeps the session, not the page. */
91
104
  function noTokens() {
92
105
  return { get: () => null, set: () => undefined };
@@ -183,6 +196,16 @@ export class FeltKitClient {
183
196
  if (notify)
184
197
  this.#notifySession();
185
198
  }
199
+ #wakers = new Set();
200
+ /**
201
+ * Reconnect the live streams now instead of after their back-off. A browser tells the client itself (`online`,
202
+ * `visibilitychange`); a host with no such events (React Native: the app returning to the foreground, the network
203
+ * coming back) calls this. Harmless when nothing is waiting.
204
+ */
205
+ wake() {
206
+ for (const wake of [...this.#wakers])
207
+ wake();
208
+ }
186
209
  get connected() {
187
210
  return this.#connected;
188
211
  }
@@ -284,6 +307,26 @@ export class FeltKitClient {
284
307
  async invoke(capability, input = {}, options = {}) {
285
308
  return (await this.#post(`/api/capability/${encodeURIComponent(capability)}`, { input, ...(options.version ? { version: options.version } : {}), ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) })).value;
286
309
  }
310
+ /**
311
+ * What happened to one of your calls (`appport.invocation.status@1`): by the request id an unknown outcome named
312
+ * (`unknownCallId(error)`, or the `requestId` a call returned), or by the idempotency key you sent. Only your own
313
+ * calls are answered; anyone else's reads `unrecorded`. It never runs anything.
314
+ */
315
+ async invocationStatus(query) {
316
+ const input = "requestId" in query ? { requestId: query.requestId } : { idempotencyKey: query.idempotencyKey, capability: { name: query.capability.name, version: query.capability.version ?? 1 } };
317
+ return this.invoke("appport.invocation.status", input);
318
+ }
319
+ /** Ask the external system what happened to an unknown call (its capability's `verify`); a definite answer settles it. */
320
+ async verifyCall(callId) {
321
+ return this.#post(`/api/provider-calls/${encodeURIComponent(callId)}/verify`, {});
322
+ }
323
+ /**
324
+ * Settle an unknown call, saying what you checked. Only a person who may make the call settles it, once; the external
325
+ * system's answer comes first (a contradicting decision is refused). Nothing runs.
326
+ */
327
+ async settleCall(callId, input) {
328
+ await this.#post(`/api/provider-calls/${encodeURIComponent(callId)}/settle`, input);
329
+ }
287
330
  /** Run a mutation. Resolves after its writes have committed. */
288
331
  async mutation(fn, args) {
289
332
  return (await this.#post(`/api/mutation/${encodeURIComponent(fn.name)}`, { args: args ?? {} })).value;
@@ -423,6 +466,38 @@ export class FeltKitClient {
423
466
  void run();
424
467
  return () => controller.abort();
425
468
  }
469
+ /**
470
+ * Proposals by the application's agents that you may decide: in your workspace, for capabilities you may perform
471
+ * yourself. Default: those waiting (`state: "proposed"`); `"all"` includes decided ones.
472
+ */
473
+ async agentApprovals(filter = {}) {
474
+ await this.#upgrade;
475
+ const query = new URLSearchParams({ ...(filter.state ? { state: filter.state } : {}), ...(filter.limit ? { limit: String(filter.limit) } : {}) });
476
+ const response = await this.#fetch(`${this.url}/api/agent/approvals${query.size ? `?${query}` : ""}`, { credentials: "same-origin", headers: this.#headers() });
477
+ const payload = (await response.json());
478
+ if (!payload.ok)
479
+ throw new FeltKitClientError(payload.error ?? { code: "INTERNAL", message: "Could not list approvals." });
480
+ return payload.approvals;
481
+ }
482
+ /** One agent proposal, with the agent's explanation, the run's input and the proposal's history. NOT_FOUND unless you may decide it. */
483
+ async agentApproval(taskId, actionId) {
484
+ await this.#upgrade;
485
+ const response = await this.#fetch(`${this.url}/api/agent/approvals/${encodeURIComponent(taskId)}/${encodeURIComponent(actionId)}`, { credentials: "same-origin", headers: this.#headers() });
486
+ const payload = (await response.json());
487
+ if (!payload.ok)
488
+ throw new FeltKitClientError(payload.error ?? { code: "INTERNAL", message: "Could not read the approval." });
489
+ return payload.approval;
490
+ }
491
+ /**
492
+ * Approve or reject an agent's proposal, as you, bound to what you reviewed (`attempt`, and `inputDigest` to
493
+ * approve). Approving runs it (as the agent, through AppPort) before this resolves; the agent's run then resumes.
494
+ * Deciding what is already decided answers its current state. A different attempt or input is refused
495
+ * (FAILED_PRECONDITION): review it again.
496
+ */
497
+ async decideAgentApproval(approval, decision, reason) {
498
+ const payload = await this.#post("/api/agent/approvals/decide", { taskId: approval.taskId, actionId: approval.actionId, attempt: approval.attempt, decision, ...(approval.inputDigest ? { inputDigest: approval.inputDigest } : {}), ...(reason ? { reason } : {}) });
499
+ return payload.approval;
500
+ }
426
501
  /** Approve one of your own proposed actions. It runs (as you, through AppPort) before this resolves. */
427
502
  async approveAction(taskId, actionId, reviewed) {
428
503
  const payload = await this.#post("/api/agent/actions/approve", { taskId, actionId, ...(reviewed?.inputDigest ? { inputDigest: reviewed.inputDigest } : {}) });
@@ -433,6 +508,108 @@ export class FeltKitClient {
433
508
  const payload = await this.#post("/api/agent/actions/reject", { taskId, actionId, ...(reason ? { reason } : {}) });
434
509
  return payload.action ? { taskId, ...payload.action } : null;
435
510
  }
511
+ // ---- Agent control: steer a running agent task (docs/AGENT-CONTROL.md) ----------------
512
+ /** The task's control state now. */
513
+ async agentControl(taskId) {
514
+ await this.#upgrade;
515
+ const sent = this.tokens.get();
516
+ const response = await this.#fetch(`${this.url}/api/agent/tasks/${encodeURIComponent(taskId)}/control`, { credentials: "same-origin", headers: this.#headers() });
517
+ const payload = (await response.json().catch(() => null));
518
+ if (!payload?.ok) {
519
+ this.#sessionEnded(payload?.error, sent);
520
+ throw new FeltKitClientError(payload?.error ?? { code: "INTERNAL", message: `The control state answered ${response.status}.` });
521
+ }
522
+ return payload.control;
523
+ }
524
+ /** Say an update is coming. The agent keeps working. Returns the signaled update (fill it with `submitAgentUpdate({ instructionId })`). */
525
+ async signalAgentUpdate(taskId, options = {}) {
526
+ const payload = await this.#post(`/api/agent/tasks/${encodeURIComponent(taskId)}/control/signal`, { ...(options.note ? { note: options.note } : {}), ...(options.idempotencyKey ? { key: options.idempotencyKey } : {}) });
527
+ return payload.instruction;
528
+ }
529
+ /**
530
+ * Send an update. It is *received* (stored) when this resolves, not yet incorporated. `instructionId` fills your own
531
+ * signal; `idempotencyKey` makes a retry (or a double click) the same update: the same key with other text is refused
532
+ * (IDEMPOTENCY_KEY_REUSED).
533
+ */
534
+ async submitAgentUpdate(taskId, text, options = {}) {
535
+ const payload = await this.#post(`/api/agent/tasks/${encodeURIComponent(taskId)}/control/submit`, { text, ...(options.instructionId ? { instructionId: options.instructionId } : {}), ...(options.idempotencyKey ? { key: options.idempotencyKey } : {}) });
536
+ return payload.instruction;
537
+ }
538
+ /** Take back a signaled or received update (its sender or the task owner). */
539
+ async withdrawAgentUpdate(taskId, instructionId, reason) {
540
+ const payload = await this.#post(`/api/agent/tasks/${encodeURIComponent(taskId)}/control/withdraw`, { instructionId, ...(reason ? { reason } : {}) });
541
+ return payload.instruction;
542
+ }
543
+ /** pause, resume, interrupt or stop the task. Answers the state after the change, as the server reads it back. */
544
+ async controlAgent(taskId, op, reason) {
545
+ const payload = await this.#post(`/api/agent/tasks/${encodeURIComponent(taskId)}/control/${op}`, reason ? { reason } : {});
546
+ return payload.control;
547
+ }
548
+ /**
549
+ * Follow a task's control state live (`GET …/control/events`). Level-triggered: `listener` gets the whole state on
550
+ * connect and after every change; a frame whose revision is one already shown, or that arrives out of order after a
551
+ * newer one, is dropped. Reconnects after a dropped stream; stops on a refusal (signed out, no access). Returns stop().
552
+ */
553
+ watchAgentControl(taskId, listener, onError) {
554
+ const controller = new AbortController();
555
+ let attempt = 0;
556
+ let sent = null;
557
+ const tracker = controlRevisions();
558
+ const run = async () => {
559
+ while (!controller.signal.aborted) {
560
+ try {
561
+ await this.#upgrade;
562
+ sent = this.tokens.get();
563
+ const response = await this.#fetch(`${this.url}/api/agent/tasks/${encodeURIComponent(taskId)}/control/events`, { credentials: "same-origin", headers: { ...this.#headers(), Accept: "text/event-stream" }, signal: controller.signal });
564
+ if (!response.ok || !response.body) {
565
+ const payload = await response.json().catch(() => null);
566
+ this.#sessionEnded(payload?.error, sent);
567
+ throw new FeltKitClientError(payload?.error ?? { code: "UNAVAILABLE", message: `The control stream answered ${response.status}.` });
568
+ }
569
+ attempt = 0;
570
+ const reader = response.body.getReader();
571
+ const decoder = new TextDecoder();
572
+ let buffer = "";
573
+ for (;;) {
574
+ const { value, done } = await reader.read();
575
+ if (done)
576
+ break;
577
+ buffer += decoder.decode(value, { stream: true });
578
+ let index;
579
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
580
+ const raw = buffer.slice(0, index);
581
+ buffer = buffer.slice(index + 2);
582
+ const event = /^event: (.+)$/m.exec(raw)?.[1];
583
+ const data = /^data: (.+)$/m.exec(raw)?.[1];
584
+ if (event === "control" && data) {
585
+ const state = JSON.parse(data).control;
586
+ if (tracker.accept(state))
587
+ listener(state);
588
+ }
589
+ if (event === "error" && data) {
590
+ const error = JSON.parse(data).error;
591
+ if (this.#sessionEnded(error, sent))
592
+ throw new FeltKitClientError(error);
593
+ onError?.(new FeltKitClientError(error));
594
+ }
595
+ }
596
+ }
597
+ }
598
+ catch (error) {
599
+ if (controller.signal.aborted)
600
+ return;
601
+ if (error instanceof FeltKitClientError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN" || error.code === "NOT_FOUND")) {
602
+ onError?.(error);
603
+ return;
604
+ }
605
+ }
606
+ attempt += 1;
607
+ await new Promise((r) => setTimeout(r, Math.min(500 * 2 ** attempt, 15_000)));
608
+ }
609
+ };
610
+ void run();
611
+ return () => controller.abort();
612
+ }
436
613
  async session() {
437
614
  await this.#upgrade;
438
615
  const response = await this.#fetch(`${this.url}/api/session`, { credentials: "same-origin", headers: this.#headers() });
@@ -537,6 +714,116 @@ export class FeltKitClient {
537
714
  this.#notifySession();
538
715
  }
539
716
  // ── Tenancy (auth.tenant) ────────────────────────────────────────────────────
717
+ /**
718
+ * An agent this application runs on the agent runtime (`app.agent(name, { project })`), as the signed-in person in
719
+ * their workspace: its state, activating it, the workspace's sessions with it, sending messages, reading and
720
+ * following a session's history (messages, calls, approvals, turns), and answering an approval (recorded as an
721
+ * AppPort approval of exactly the call waiting).
722
+ */
723
+ agent(name) {
724
+ return this.eve(name);
725
+ }
726
+ /**
727
+ * The same as `agent(name)`, under the runtime's internal name.
728
+ * @deprecated Use `agent(name)`.
729
+ * An eve agent this application runs (`feltkit({ eve })`), as the signed-in person in their workspace: its state,
730
+ * activating it, the workspace's sessions with it, sending messages, reading and following a session's history
731
+ * (eve's facts: messages, calls, approvals, turns), and answering an approval (recorded as an AppPort approval of
732
+ * exactly the call waiting).
733
+ */
734
+ eve(agent) {
735
+ const root = `/api/eve/${encodeURIComponent(agent)}`;
736
+ const forward = `/eve/${encodeURIComponent(agent)}/eve/v1/session`;
737
+ const readFacts = async (sessionId, follow, signal, onLine) => {
738
+ await this.#upgrade;
739
+ const response = await this.#fetch(`${this.url}${forward}/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=${follow}`, { credentials: "same-origin", headers: this.#headers(), ...(signal ? { signal } : {}) });
740
+ if (!response.ok) {
741
+ const payload = (await response.json().catch(() => null));
742
+ throw new FeltKitClientError(payload?.error ?? { code: "UNAVAILABLE", message: `The agent answered ${response.status}.` });
743
+ }
744
+ const facts = [];
745
+ const take = (line) => {
746
+ const text = line.trim();
747
+ if (!text.startsWith("{"))
748
+ return;
749
+ try {
750
+ const parsed = JSON.parse(text);
751
+ if (Array.isArray(parsed.facts) && parsed.facts.length) {
752
+ facts.push(...parsed.facts);
753
+ onLine?.(facts.slice());
754
+ }
755
+ }
756
+ catch {
757
+ /* a partial or foreign line */
758
+ }
759
+ };
760
+ if (!response.body || !follow) {
761
+ for (const line of (await response.text()).split("\n"))
762
+ take(line);
763
+ return facts;
764
+ }
765
+ const reader = response.body.getReader();
766
+ const decoder = new TextDecoder();
767
+ let buffered = "";
768
+ for (;;) {
769
+ const { done, value } = await reader.read();
770
+ if (done)
771
+ break;
772
+ buffered += decoder.decode(value, { stream: true });
773
+ const lines = buffered.split("\n");
774
+ buffered = lines.pop() ?? "";
775
+ for (const line of lines)
776
+ take(line);
777
+ }
778
+ take(buffered);
779
+ return facts;
780
+ };
781
+ return {
782
+ status: async () => {
783
+ const { ok: _ok, ...status } = await this.#get(root);
784
+ return status;
785
+ },
786
+ activate: async () => {
787
+ const { worker, activated } = await this.#post(`${root}/activate`, {});
788
+ return { worker, activated };
789
+ },
790
+ sessions: async () => (await this.#get(`${root}/sessions`)).sessions,
791
+ start: async (message) => {
792
+ const payload = await this.#post(forward, { message });
793
+ return { sessionId: String(payload.sessionId), deliveryId: String(payload.deliveryId ?? "") };
794
+ },
795
+ send: async (sessionId, message) => {
796
+ const payload = await this.#post(`${forward}/${encodeURIComponent(sessionId)}`, { message });
797
+ return { deliveryId: String(payload.deliveryId ?? "") };
798
+ },
799
+ history: (sessionId) => readFacts(sessionId, false, undefined),
800
+ follow: (sessionId, onFacts, onError) => {
801
+ const controller = new AbortController();
802
+ void (async () => {
803
+ let delay = 500;
804
+ while (!controller.signal.aborted) {
805
+ try {
806
+ await readFacts(sessionId, true, controller.signal, onFacts);
807
+ delay = 500;
808
+ }
809
+ catch (error) {
810
+ if (controller.signal.aborted)
811
+ return;
812
+ onError?.(error);
813
+ delay = Math.min(delay * 2, 10_000);
814
+ }
815
+ await new Promise((r) => setTimeout(r, delay));
816
+ }
817
+ })();
818
+ return () => controller.abort();
819
+ },
820
+ evidence: async (sessionId) => (await this.#get(`${root}/sessions/${encodeURIComponent(sessionId)}/evidence`)).evidence,
821
+ answer: async (sessionId, interactionId, decision) => {
822
+ const { approval } = await this.#post(`${root}/answer`, { sessionId, interactionId, decision });
823
+ return { ...(approval ? { approval: String(approval) } : {}) };
824
+ },
825
+ };
826
+ }
540
827
  async #get(path) {
541
828
  await this.#upgrade;
542
829
  const response = await this.#fetch(`${this.url}${path}`, { credentials: "same-origin", headers: this.#headers() });
@@ -562,6 +849,15 @@ export class FeltKitClient {
562
849
  this.#accept(payload);
563
850
  return payload.tenant;
564
851
  }
852
+ /**
853
+ * See the application as a lower role of yours in this tenant (`role`), read-only: the server answers every call as
854
+ * that role, and refuses every change until the preview ends (`null`). Owners use it to check what each role sees.
855
+ */
856
+ async previewRole(role) {
857
+ const payload = await this.#post("/api/tenants/current/preview", { role });
858
+ this.#accept(payload);
859
+ return payload.tenant;
860
+ }
565
861
  async members() {
566
862
  return (await this.#get("/api/tenants/current/members")).members;
567
863
  }
@@ -590,6 +886,34 @@ export class FeltKitClient {
590
886
  await this.#post("/api/tenants/current/rename", { name });
591
887
  this.#notifySession();
592
888
  }
889
+ /**
890
+ * Which tenant a slug or custom domain names, as its public branding (K5). No sign-in needed: for a join or
891
+ * sign-in page that must be branded first. With neither, the page's own host. Null when nothing matches.
892
+ */
893
+ async resolveTenant(by = {}) {
894
+ const query = new URLSearchParams({ ...(by.slug ? { slug: by.slug } : {}), ...(by.domain ? { domain: by.domain } : {}) });
895
+ const response = await this.#fetch(`${this.url}/api/tenants/resolve${query.size ? `?${query}` : ""}`, { credentials: "omit" });
896
+ if (response.status === 404)
897
+ return null;
898
+ const payload = (await response.json().catch(() => null));
899
+ if (!payload?.ok)
900
+ throw new FeltKitClientError(payload?.error ?? { code: "INTERNAL", message: `Tenant resolution answered ${response.status}.` });
901
+ return payload.tenant;
902
+ }
903
+ /** The current tenant's slug, custom domains and branding (members). */
904
+ async tenantPublic() {
905
+ await this.#upgrade;
906
+ const response = await this.#fetch(`${this.url}/api/tenants/current/public`, { credentials: "same-origin", headers: this.#headers() });
907
+ const payload = (await response.json());
908
+ if (!payload.ok)
909
+ throw new FeltKitClientError(payload.error ?? { code: "INTERNAL", message: "Could not read the tenant's public settings." });
910
+ return payload.public;
911
+ }
912
+ /** Set the current tenant's slug, domains and branding (tenant.update); null clears one. */
913
+ async setTenantPublic(input) {
914
+ const payload = await this.#post("/api/tenants/current/public", input);
915
+ return payload.public;
916
+ }
593
917
  async invitations() {
594
918
  return (await this.#get("/api/tenants/current/invitations")).invitations;
595
919
  }
@@ -605,6 +929,10 @@ export class FeltKitClient {
605
929
  async previewInvitation(token) {
606
930
  return (await this.#post("/api/invitations/preview", { token })).invitation;
607
931
  }
932
+ /** Decline an invitation (its holder; no sign-in needed). A declined invitation cannot be accepted. */
933
+ async declineInvitation(token) {
934
+ await this.#post("/api/invitations/decline", { token });
935
+ }
608
936
  /** Accept an invitation (signed in with the invited address) and switch to its tenant. */
609
937
  async acceptInvitation(token) {
610
938
  const payload = await this.#post("/api/invitations/accept", { token });
@@ -882,7 +1210,7 @@ export class FeltKitClient {
882
1210
  break;
883
1211
  // Back off, but reconnect at once when the browser says the network is back or the page is
884
1212
  // visible again: a client that comes back online catches up in ~one round trip, not ~10 s.
885
- const woken = await waitOrWake(delay, controller.signal);
1213
+ const woken = await waitOrWake(delay, controller.signal, undefined, undefined, this.#wakers);
886
1214
  delay = woken ? 500 : Math.min(delay * 2, 10_000);
887
1215
  this.#emit(["*"]);
888
1216
  }
@@ -955,7 +1283,7 @@ export class FeltKitClient {
955
1283
  }
956
1284
  if (controller.signal.aborted)
957
1285
  break;
958
- const woken = await waitOrWake(delay, controller.signal);
1286
+ const woken = await waitOrWake(delay, controller.signal, undefined, undefined, this.#wakers);
959
1287
  delay = woken ? 500 : Math.min(delay * 2, 10_000);
960
1288
  }
961
1289
  })();
@@ -1007,7 +1335,7 @@ export class FeltKitClient {
1007
1335
  * Wait `ms`, or less: resolves true early on `online`, or on `visibilitychange` to visible, where the
1008
1336
  * environment has them (browsers); false after the full wait or on abort. No-op listeners elsewhere.
1009
1337
  */
1010
- export function waitOrWake(ms, signal, target = globalThis, doc = globalThis.document) {
1338
+ export function waitOrWake(ms, signal, target = globalThis, doc = globalThis.document, wakers) {
1011
1339
  return new Promise((resolve) => {
1012
1340
  let done = false;
1013
1341
  const finish = (woken) => {
@@ -1017,6 +1345,7 @@ export function waitOrWake(ms, signal, target = globalThis, doc = globalThis.doc
1017
1345
  clearTimeout(timer);
1018
1346
  target?.removeEventListener?.("online", online);
1019
1347
  doc?.removeEventListener?.("visibilitychange", visible);
1348
+ wakers?.delete(online);
1020
1349
  signal.removeEventListener("abort", aborted);
1021
1350
  resolve(woken);
1022
1351
  };
@@ -1027,10 +1356,49 @@ export function waitOrWake(ms, signal, target = globalThis, doc = globalThis.doc
1027
1356
  const timer = setTimeout(() => finish(false), ms);
1028
1357
  target?.addEventListener?.("online", online);
1029
1358
  doc?.addEventListener?.("visibilitychange", visible);
1359
+ wakers?.add(online);
1030
1360
  signal.addEventListener("abort", aborted, { once: true });
1031
1361
  });
1032
1362
  }
1033
1363
  export function createClient(options) {
1034
1364
  return new FeltKitClient(options);
1035
1365
  }
1366
+ /**
1367
+ * Which control frames to show. A revision is a digest, not a counter, so order comes from the state itself: the
1368
+ * checkpoint count and every record's sequence only grow. A frame is stale when it shows nothing newer than the
1369
+ * last one shown and something older; a frame that repeats the last revision changes nothing.
1370
+ */
1371
+ export function controlRevisions() {
1372
+ let last = null;
1373
+ const marks = (state) => {
1374
+ const updates = new Map(state.instructions.map((i) => [i.instructionId, i.seq]));
1375
+ return { checkpoint: state.checkpoint, updates, terminal: state.phase === "completed" || state.phase === "stopped" };
1376
+ };
1377
+ return {
1378
+ accept(state) {
1379
+ if (last && last.revision === state.revision)
1380
+ return false;
1381
+ if (last) {
1382
+ const a = marks(last);
1383
+ const b = marks(state);
1384
+ let older = b.checkpoint < a.checkpoint || (a.terminal && !b.terminal);
1385
+ let newer = b.checkpoint > a.checkpoint || (b.terminal && !a.terminal);
1386
+ for (const [id, seq] of a.updates) {
1387
+ const next = b.updates.get(id);
1388
+ if (next === undefined || next < seq)
1389
+ older = true;
1390
+ else if (next > seq)
1391
+ newer = true;
1392
+ }
1393
+ for (const id of b.updates.keys())
1394
+ if (!a.updates.has(id))
1395
+ newer = true;
1396
+ if (older && !newer)
1397
+ return false;
1398
+ }
1399
+ last = state;
1400
+ return true;
1401
+ },
1402
+ };
1403
+ }
1036
1404
  //# sourceMappingURL=index.js.map