@eloxiv/client 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +6 -2
- package/dist/Account.d.ts +131 -0
- package/dist/Account.d.ts.map +1 -0
- package/dist/Account.js +169 -0
- package/dist/Account.js.map +1 -0
- package/dist/Agent.d.ts +496 -0
- package/dist/Agent.d.ts.map +1 -0
- package/dist/Agent.js +228 -0
- package/dist/Agent.js.map +1 -0
- package/dist/AgentSync.d.ts +990 -0
- package/dist/AgentSync.d.ts.map +1 -0
- package/dist/AgentSync.js +46 -0
- package/dist/AgentSync.js.map +1 -0
- package/dist/AppState.d.ts +127 -0
- package/dist/AppState.d.ts.map +1 -0
- package/dist/AppState.js +145 -0
- package/dist/AppState.js.map +1 -0
- package/dist/AppStateSync.d.ts +193 -0
- package/dist/AppStateSync.d.ts.map +1 -0
- package/dist/AppStateSync.js +23 -0
- package/dist/AppStateSync.js.map +1 -0
- package/dist/Auth.d.ts +95 -0
- package/dist/Auth.d.ts.map +1 -0
- package/dist/Auth.js +139 -0
- package/dist/Auth.js.map +1 -0
- package/dist/Avatars.d.ts +53 -0
- package/dist/Avatars.d.ts.map +1 -0
- package/dist/Avatars.js +121 -0
- package/dist/Avatars.js.map +1 -0
- package/dist/BrowserAnalytics.d.ts +56 -0
- package/dist/BrowserAnalytics.d.ts.map +1 -0
- package/dist/BrowserAnalytics.js +94 -0
- package/dist/BrowserAnalytics.js.map +1 -0
- package/dist/Chat.d.ts +712 -0
- package/dist/Chat.d.ts.map +1 -0
- package/dist/Chat.js +883 -0
- package/dist/Chat.js.map +1 -0
- package/dist/ChatIntegrity.d.ts +63 -0
- package/dist/ChatIntegrity.d.ts.map +1 -0
- package/dist/ChatIntegrity.js +89 -0
- package/dist/ChatIntegrity.js.map +1 -0
- package/dist/ChatSends.d.ts +103 -0
- package/dist/ChatSends.d.ts.map +1 -0
- package/dist/ChatSends.js +157 -0
- package/dist/ChatSends.js.map +1 -0
- package/dist/Client.d.ts +113 -0
- package/dist/Client.d.ts.map +1 -0
- package/dist/Client.js +189 -0
- package/dist/Client.js.map +1 -0
- package/dist/Collab.d.ts +138 -0
- package/dist/Collab.d.ts.map +1 -0
- package/dist/Collab.js +454 -0
- package/dist/Collab.js.map +1 -0
- package/dist/CollabTools.d.ts +129 -0
- package/dist/CollabTools.d.ts.map +1 -0
- package/dist/CollabTools.js +277 -0
- package/dist/CollabTools.js.map +1 -0
- package/dist/Connections.d.ts +288 -0
- package/dist/Connections.d.ts.map +1 -0
- package/dist/Connections.js +316 -0
- package/dist/Connections.js.map +1 -0
- package/dist/Consent.d.ts +338 -0
- package/dist/Consent.d.ts.map +1 -0
- package/dist/Consent.js +142 -0
- package/dist/Consent.js.map +1 -0
- package/dist/Desktop.d.ts +61 -0
- package/dist/Desktop.d.ts.map +1 -0
- package/dist/Desktop.js +101 -0
- package/dist/Desktop.js.map +1 -0
- package/dist/Directory.d.ts +36 -0
- package/dist/Directory.d.ts.map +1 -0
- package/dist/Directory.js +42 -0
- package/dist/Directory.js.map +1 -0
- package/dist/ErrorReporter.d.ts +48 -0
- package/dist/ErrorReporter.d.ts.map +1 -0
- package/dist/ErrorReporter.js +70 -0
- package/dist/ErrorReporter.js.map +1 -0
- package/dist/ExpoSqlite.d.ts +7 -0
- package/dist/ExpoSqlite.d.ts.map +1 -0
- package/dist/ExpoSqlite.js +7 -0
- package/dist/ExpoSqlite.js.map +1 -0
- package/dist/FileSync.d.ts +265 -0
- package/dist/FileSync.d.ts.map +1 -0
- package/dist/FileSync.js +29 -0
- package/dist/FileSync.js.map +1 -0
- package/dist/FileTables.gen.d.ts +109 -0
- package/dist/FileTables.gen.d.ts.map +1 -0
- package/dist/FileTables.gen.js +23 -0
- package/dist/FileTables.gen.js.map +1 -0
- package/dist/Foldkit.d.ts +487 -0
- package/dist/Foldkit.d.ts.map +1 -0
- package/dist/Foldkit.js +617 -0
- package/dist/Foldkit.js.map +1 -0
- package/dist/History.d.ts +133 -0
- package/dist/History.d.ts.map +1 -0
- package/dist/History.js +210 -0
- package/dist/History.js.map +1 -0
- package/dist/InboxSync.d.ts +428 -0
- package/dist/InboxSync.d.ts.map +1 -0
- package/dist/InboxSync.js +37 -0
- package/dist/InboxSync.js.map +1 -0
- package/dist/KernelTables.gen.d.ts +1522 -0
- package/dist/KernelTables.gen.d.ts.map +1 -0
- package/dist/KernelTables.gen.js +307 -0
- package/dist/KernelTables.gen.js.map +1 -0
- package/dist/Make.d.ts +75 -0
- package/dist/Make.d.ts.map +1 -0
- package/dist/Make.js +70 -0
- package/dist/Make.js.map +1 -0
- package/dist/Models.d.ts +88 -0
- package/dist/Models.d.ts.map +1 -0
- package/dist/Models.js +80 -0
- package/dist/Models.js.map +1 -0
- package/dist/Optimistic.d.ts +120 -0
- package/dist/Optimistic.d.ts.map +1 -0
- package/dist/Optimistic.js +231 -0
- package/dist/Optimistic.js.map +1 -0
- package/dist/PlatformSync.d.ts +273 -0
- package/dist/PlatformSync.d.ts.map +1 -0
- package/dist/PlatformSync.js +92 -0
- package/dist/PlatformSync.js.map +1 -0
- package/dist/Poll.d.ts +113 -0
- package/dist/Poll.d.ts.map +1 -0
- package/dist/Poll.js +179 -0
- package/dist/Poll.js.map +1 -0
- package/dist/Preferences.d.ts +18 -0
- package/dist/Preferences.d.ts.map +1 -0
- package/dist/Preferences.js +22 -0
- package/dist/Preferences.js.map +1 -0
- package/dist/Proposals.d.ts +29 -0
- package/dist/Proposals.d.ts.map +1 -0
- package/dist/Proposals.js +41 -0
- package/dist/Proposals.js.map +1 -0
- package/dist/React.d.ts +17 -0
- package/dist/React.d.ts.map +1 -0
- package/dist/React.js +17 -0
- package/dist/React.js.map +1 -0
- package/dist/Reader.d.ts +35 -0
- package/dist/Reader.d.ts.map +1 -0
- package/dist/Reader.js +136 -0
- package/dist/Reader.js.map +1 -0
- package/dist/Resources.d.ts +98 -0
- package/dist/Resources.d.ts.map +1 -0
- package/dist/Resources.js +161 -0
- package/dist/Resources.js.map +1 -0
- package/dist/Rows.d.ts +4 -0
- package/dist/Rows.d.ts.map +1 -0
- package/dist/Rows.js +16 -0
- package/dist/Rows.js.map +1 -0
- package/dist/Runtime.d.ts +254 -0
- package/dist/Runtime.d.ts.map +1 -0
- package/dist/Runtime.js +1249 -0
- package/dist/Runtime.js.map +1 -0
- package/dist/RuntimeRuns.d.ts +74 -0
- package/dist/RuntimeRuns.d.ts.map +1 -0
- package/dist/RuntimeRuns.js +118 -0
- package/dist/RuntimeRuns.js.map +1 -0
- package/dist/ServicesSync.d.ts +286 -0
- package/dist/ServicesSync.d.ts.map +1 -0
- package/dist/ServicesSync.js +40 -0
- package/dist/ServicesSync.js.map +1 -0
- package/dist/Session.d.ts +226 -0
- package/dist/Session.d.ts.map +1 -0
- package/dist/Session.js +763 -0
- package/dist/Session.js.map +1 -0
- package/dist/ShareGrant.d.ts +47 -0
- package/dist/ShareGrant.d.ts.map +1 -0
- package/dist/ShareGrant.js +20 -0
- package/dist/ShareGrant.js.map +1 -0
- package/dist/Sharing.d.ts +203 -0
- package/dist/Sharing.d.ts.map +1 -0
- package/dist/Sharing.js +520 -0
- package/dist/Sharing.js.map +1 -0
- package/dist/Skew.d.ts +52 -0
- package/dist/Skew.d.ts.map +1 -0
- package/dist/Skew.js +77 -0
- package/dist/Skew.js.map +1 -0
- package/dist/SpacesSync.d.ts +247 -0
- package/dist/SpacesSync.d.ts.map +1 -0
- package/dist/SpacesSync.js +30 -0
- package/dist/SpacesSync.js.map +1 -0
- package/dist/Storage.d.ts +51 -0
- package/dist/Storage.d.ts.map +1 -0
- package/dist/Storage.js +107 -0
- package/dist/Storage.js.map +1 -0
- package/dist/Sync.d.ts +48 -0
- package/dist/Sync.d.ts.map +1 -0
- package/dist/Sync.js +48 -0
- package/dist/Sync.js.map +1 -0
- package/dist/SyncTables.d.ts +13 -0
- package/dist/SyncTables.d.ts.map +1 -0
- package/dist/SyncTables.js +13 -0
- package/dist/SyncTables.js.map +1 -0
- package/dist/Tab.d.ts +36 -0
- package/dist/Tab.d.ts.map +1 -0
- package/dist/Tab.js +44 -0
- package/dist/Tab.js.map +1 -0
- package/dist/Transport.d.ts +139 -0
- package/dist/Transport.d.ts.map +1 -0
- package/dist/Transport.js +232 -0
- package/dist/Transport.js.map +1 -0
- package/dist/Upload.d.ts +41 -0
- package/dist/Upload.d.ts.map +1 -0
- package/dist/Upload.js +93 -0
- package/dist/Upload.js.map +1 -0
- package/dist/WebMcp.d.ts +78 -0
- package/dist/WebMcp.d.ts.map +1 -0
- package/dist/WebMcp.js +204 -0
- package/dist/WebMcp.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/package.json +97 -3
- package/src/Account.ts +249 -0
- package/src/Agent.ts +387 -0
- package/src/AgentSync.ts +59 -0
- package/src/AppState.ts +222 -0
- package/src/AppStateSync.ts +26 -0
- package/src/Auth.ts +225 -0
- package/src/Avatars.ts +144 -0
- package/src/BrowserAnalytics.ts +133 -0
- package/src/Chat.ts +1150 -0
- package/src/ChatIntegrity.ts +130 -0
- package/src/ChatSends.ts +209 -0
- package/src/Client.ts +319 -0
- package/src/Collab.ts +524 -0
- package/src/CollabTools.ts +381 -0
- package/src/Connections.ts +517 -0
- package/src/Consent.ts +176 -0
- package/src/Desktop.ts +139 -0
- package/src/Directory.ts +71 -0
- package/src/ErrorReporter.ts +112 -0
- package/src/ExpoSqlite.ts +6 -0
- package/src/FileSync.ts +34 -0
- package/src/FileTables.gen.ts +23 -0
- package/src/Foldkit.ts +960 -0
- package/src/History.ts +337 -0
- package/src/InboxSync.ts +47 -0
- package/src/KernelTables.gen.ts +329 -0
- package/src/Make.ts +120 -0
- package/src/Models.ts +134 -0
- package/src/Optimistic.ts +364 -0
- package/src/PlatformSync.ts +156 -0
- package/src/Poll.ts +227 -0
- package/src/Preferences.ts +42 -0
- package/src/Proposals.ts +57 -0
- package/src/React.ts +26 -0
- package/src/Reader.ts +180 -0
- package/src/Resources.ts +257 -0
- package/src/Rows.ts +16 -0
- package/src/Runtime.ts +1409 -0
- package/src/RuntimeRuns.ts +180 -0
- package/src/ServicesSync.ts +58 -0
- package/src/Session.ts +814 -0
- package/src/ShareGrant.ts +20 -0
- package/src/Sharing.ts +696 -0
- package/src/Skew.ts +97 -0
- package/src/SpacesSync.ts +61 -0
- package/src/Storage.ts +167 -0
- package/src/Sync.ts +125 -0
- package/src/SyncTables.ts +12 -0
- package/src/Tab.ts +59 -0
- package/src/Transport.ts +321 -0
- package/src/Upload.ts +125 -0
- package/src/WebMcp.ts +279 -0
- package/src/index.ts +26 -0
- package/src/web-globals.d.ts +103 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An opt-in integrity reporter for the chat SDK (`@eloxiv/client/chat`): it watches what a chat screen feeds its
|
|
3
|
+
* state, and reports what should never happen, so a deployment learns of it instead of a person seeing a garbled
|
|
4
|
+
* transcript:
|
|
5
|
+
*
|
|
6
|
+
* - **ordering gaps**: a run's stored event arrives after a sequence number was skipped (`gap`);
|
|
7
|
+
* - **duplicates and reordering**: a stored event arrives again (`duplicate`) or after a later one (`out-of-order`);
|
|
8
|
+
* - **missing terminals**: a run's stream closes, or the replica says the run ended, without its `run-finished`;
|
|
9
|
+
* - **dropped sends**: a send recorded in the outstanding store leaves it without a definitive outcome (an answer, a
|
|
10
|
+
* replay, a receipt found, a refusal of its only attempt, or the person discarding it).
|
|
11
|
+
*
|
|
12
|
+
* Each report names the surface it happened on (the app's label: `web-chat`, `desktop-chat`) and is **redacted**:
|
|
13
|
+
* run ids, sequence numbers and the event's type, never an event's data, a message's text or a send's key or draft.
|
|
14
|
+
* The SDK's own reducers never depend on it; the app routes reports where it likes (the error reporter's breadcrumbs,
|
|
15
|
+
* a declared analytics event).
|
|
16
|
+
*/
|
|
17
|
+
import type { RunEvent } from "@eloxiv/contracts"
|
|
18
|
+
import type { OutstandingSend } from "./ChatSends.ts"
|
|
19
|
+
|
|
20
|
+
/** The run event types a report may name; anything else is `other`. */
|
|
21
|
+
const KNOWN_TYPES = new Set([
|
|
22
|
+
"run-started",
|
|
23
|
+
"model-step",
|
|
24
|
+
"tool-call",
|
|
25
|
+
"tool-result",
|
|
26
|
+
"consent-required",
|
|
27
|
+
"consent-decided",
|
|
28
|
+
"compacted",
|
|
29
|
+
"delegated",
|
|
30
|
+
"seat-spawned",
|
|
31
|
+
"team-message",
|
|
32
|
+
"reply-discarded",
|
|
33
|
+
"answer-checked",
|
|
34
|
+
"processor-tripped",
|
|
35
|
+
"run-finished",
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
export type IntegrityIssue =
|
|
39
|
+
| {
|
|
40
|
+
readonly kind: "gap"
|
|
41
|
+
readonly surface: string
|
|
42
|
+
readonly runId: string
|
|
43
|
+
readonly expected: number
|
|
44
|
+
readonly got: number
|
|
45
|
+
readonly eventType: string
|
|
46
|
+
}
|
|
47
|
+
| {
|
|
48
|
+
readonly kind: "duplicate" | "out-of-order"
|
|
49
|
+
readonly surface: string
|
|
50
|
+
readonly runId: string
|
|
51
|
+
readonly seq: number
|
|
52
|
+
readonly eventType: string
|
|
53
|
+
}
|
|
54
|
+
| { readonly kind: "missing-terminal"; readonly surface: string; readonly runId: string; readonly lastSeq: number }
|
|
55
|
+
| { readonly kind: "dropped-send"; readonly surface: string; readonly sends: number }
|
|
56
|
+
|
|
57
|
+
export interface ChatIntegrityOptions {
|
|
58
|
+
/** Where the issue happened, as the app names its surface (a short label). */
|
|
59
|
+
readonly surface: string
|
|
60
|
+
readonly report: (issue: IntegrityIssue) => void
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** At most this many sequence numbers are remembered per run (to tell a duplicate from a reordering). */
|
|
64
|
+
const SEEN_KEPT = 512
|
|
65
|
+
|
|
66
|
+
export const chatIntegrity = (options: ChatIntegrityOptions) => {
|
|
67
|
+
const surface = options.surface.replaceAll(/[^A-Za-z0-9_.:-]/gu, "_").slice(0, 64) || "chat"
|
|
68
|
+
const runs = new Map<string, { last: number; seen: Set<number>; finished: boolean }>()
|
|
69
|
+
/** The keys of sends recorded and not yet settled definitively (kept here only, never reported). */
|
|
70
|
+
const open = new Set<string>()
|
|
71
|
+
const report = (issue: IntegrityIssue) => {
|
|
72
|
+
try {
|
|
73
|
+
options.report(issue)
|
|
74
|
+
} catch {
|
|
75
|
+
// The app's reporting never breaks the chat.
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const runOf = (runId: string) => {
|
|
79
|
+
const known = runs.get(runId) ?? { last: -1, seen: new Set<number>(), finished: false }
|
|
80
|
+
runs.set(runId, known)
|
|
81
|
+
return known
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
/** A run event, as the screen feeds it to `withEvent` (streamed text, without a sequence number, is not checked). */
|
|
86
|
+
observe: (event: RunEvent) => {
|
|
87
|
+
if (event.type === "text-delta" || event.seq < 0) return
|
|
88
|
+
const run = runOf(event.runId)
|
|
89
|
+
const eventType = KNOWN_TYPES.has(event.type) ? event.type : "other"
|
|
90
|
+
if (run.seen.has(event.seq)) {
|
|
91
|
+
report({ kind: "duplicate", surface, runId: event.runId, seq: event.seq, eventType })
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
if (event.seq < run.last) {
|
|
95
|
+
report({ kind: "out-of-order", surface, runId: event.runId, seq: event.seq, eventType })
|
|
96
|
+
} else if (event.seq > run.last + 1) {
|
|
97
|
+
report({ kind: "gap", surface, runId: event.runId, expected: run.last + 1, got: event.seq, eventType })
|
|
98
|
+
}
|
|
99
|
+
run.seen.add(event.seq)
|
|
100
|
+
if (run.seen.size > SEEN_KEPT) run.seen.delete(Math.min(...run.seen))
|
|
101
|
+
run.last = Math.max(run.last, event.seq)
|
|
102
|
+
if (event.type === "run-finished") run.finished = true
|
|
103
|
+
},
|
|
104
|
+
/** The run's stream closed for good, or the replica says the run ended: it must have said `run-finished`. */
|
|
105
|
+
ended: (runId: string) => {
|
|
106
|
+
const run = runs.get(runId)
|
|
107
|
+
// A run never seen (its stream ended before its first stored event, or carried only streamed text) is unfinished.
|
|
108
|
+
if (run === undefined || !run.finished) {
|
|
109
|
+
report({ kind: "missing-terminal", surface, runId, lastSeq: run?.last ?? -1 })
|
|
110
|
+
}
|
|
111
|
+
runs.delete(runId)
|
|
112
|
+
},
|
|
113
|
+
/** A send recorded in the outstanding store (its key, before its request leaves). */
|
|
114
|
+
recorded: (key: string) => void open.add(key),
|
|
115
|
+
/** A send settled by a definitive outcome (an answer, a replay, a receipt found, a refusal, a discard). */
|
|
116
|
+
settled: (key: string) => void open.delete(key),
|
|
117
|
+
/**
|
|
118
|
+
* Compare with the outstanding sends a state holds now: a recorded send neither settled nor still outstanding was
|
|
119
|
+
* dropped. Reported by count only.
|
|
120
|
+
*/
|
|
121
|
+
audit: (outstanding: ReadonlyArray<OutstandingSend>) => {
|
|
122
|
+
const kept = new Set(outstanding.map((send) => send.key))
|
|
123
|
+
const dropped = [...open].filter((key) => !kept.has(key))
|
|
124
|
+
for (const key of dropped) open.delete(key)
|
|
125
|
+
if (dropped.length > 0) report({ kind: "dropped-send", surface, sends: dropped.length })
|
|
126
|
+
},
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type ChatIntegrity = ReturnType<typeof chatIntegrity>
|
package/src/ChatSends.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A person's sends whose outcome is not settled (part of the headless chat SDK, `@eloxiv/client/chat`). A send's
|
|
3
|
+
* identity is its idempotency key; it must outlive any screen that made it, so it is kept here, outside UI state:
|
|
4
|
+
*
|
|
5
|
+
* - **Written ahead.** A send is recorded (`OutstandingStore.put`) before its request leaves, and its outcome is
|
|
6
|
+
* recorded when it comes, by whoever made the request, whether or not the screen that asked for it still exists.
|
|
7
|
+
* - **Settled only by a definitive outcome for its key.** The kernel ran it (an answer, a replay of its receipt, or
|
|
8
|
+
* its receipt found by looking the key up), or refused it before anything could commit: a refusal of a send's first
|
|
9
|
+
* and only attempt. After an answer was lost (no answer, a timeout, a 408, a gateway's or the server's 5xx) the send
|
|
10
|
+
* may have run, and a later refusal (the retry refused before the kernel looked at the key: a policy or credential
|
|
11
|
+
* change) proves nothing: it is kept as "could not confirm" until its receipt is found or the person discards it.
|
|
12
|
+
* `ApprovalRequired` and `ConsentRequired` mean work was stored under the key, not a refusal: it is kept, waiting.
|
|
13
|
+
* - **Scoped to the person and the organisation**, for as long as they are kept: across screens, an organisation
|
|
14
|
+
* switch and back, a reload (with a web `Storage`), and a sign-out (shown again at the person's next sign-in in that
|
|
15
|
+
* organisation). Only what identifies a send is kept (its text, conversation and key), never a credential.
|
|
16
|
+
*/
|
|
17
|
+
import { RunDevice } from "@eloxiv/contracts"
|
|
18
|
+
import { Effect, Option, Queue, Schema, Stream } from "effect"
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Why the kernel refused or failed a request: its error's tag and message, the HTTP status (0 for no answer), and the
|
|
22
|
+
* approval request or consent it waits on (`ApprovalRequired`, `ConsentRequired`).
|
|
23
|
+
*/
|
|
24
|
+
export const ChatError = Schema.Struct({
|
|
25
|
+
_tag: Schema.String,
|
|
26
|
+
message: Schema.String,
|
|
27
|
+
status: Schema.Number,
|
|
28
|
+
approvalId: Schema.optionalKey(Schema.String),
|
|
29
|
+
consentId: Schema.optionalKey(Schema.String),
|
|
30
|
+
})
|
|
31
|
+
export type ChatError = typeof ChatError.Type
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Whether a failed request's answer was definitive: the kernel answered, and the answer was a refusal (a 4xx but 408;
|
|
35
|
+
* `ApprovalRequired` and `ConsentRequired` are not refusals but work stored). No answer, a timeout, a 408, a
|
|
36
|
+
* gateway's or the server's error (5xx) may hide a request that ran.
|
|
37
|
+
*/
|
|
38
|
+
export const isDefinitive = (error: ChatError): boolean =>
|
|
39
|
+
error.status >= 400 && error.status < 500 && error.status !== 408 && !isHeld(error)
|
|
40
|
+
|
|
41
|
+
/** Work stored under the call's key, waiting on a person: a business approval, or their consent. */
|
|
42
|
+
const isHeld = (error: ChatError) => error._tag === "ApprovalRequired" || error._tag === "ConsentRequired"
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Where an outstanding send stands: `sending` (an attempt in flight, its outcome unknown until it answers),
|
|
46
|
+
* `uncertain` (an answer was lost: send again, under its key), `unconfirmed` (it may have run, and the kernel could
|
|
47
|
+
* not confirm it: kept until its receipt is found or the person discards it), `awaiting-approval` and
|
|
48
|
+
* `awaiting-consent` (stored under its key, waiting on a person).
|
|
49
|
+
*/
|
|
50
|
+
export const SendState = Schema.Literals([
|
|
51
|
+
"sending",
|
|
52
|
+
"uncertain",
|
|
53
|
+
"unconfirmed",
|
|
54
|
+
"awaiting-approval",
|
|
55
|
+
"awaiting-consent",
|
|
56
|
+
])
|
|
57
|
+
export type SendState = typeof SendState.Type
|
|
58
|
+
|
|
59
|
+
export const OutstandingSend = Schema.Struct({
|
|
60
|
+
text: Schema.String,
|
|
61
|
+
/** The conversation it was sent from (null for a new one). */
|
|
62
|
+
conversationId: Schema.NullOr(Schema.String),
|
|
63
|
+
/** Its idempotency key: its identity, the same on every attempt. */
|
|
64
|
+
key: Schema.String,
|
|
65
|
+
state: SendState,
|
|
66
|
+
/** Whether it may have run, or work is stored under its key: then only its receipt or the person settles it. */
|
|
67
|
+
doubtful: Schema.Boolean,
|
|
68
|
+
/** The approval request or consent it waits on. */
|
|
69
|
+
waitingOn: Schema.NullOr(Schema.String),
|
|
70
|
+
/** The person's paired device it runs on (its harness, on their own subscription); none: the deployment's model. */
|
|
71
|
+
device: Schema.optionalKey(Schema.NullOr(RunDevice)),
|
|
72
|
+
})
|
|
73
|
+
export type OutstandingSend = typeof OutstandingSend.Type
|
|
74
|
+
|
|
75
|
+
/** What became of an attempt of a send, or what was learnt about it. */
|
|
76
|
+
export type SendOutcome =
|
|
77
|
+
| { readonly kind: "sent" }
|
|
78
|
+
| { readonly kind: "replayed" }
|
|
79
|
+
/** Its receipt was found by looking its key up: it ran. */
|
|
80
|
+
| { readonly kind: "ran" }
|
|
81
|
+
| { readonly kind: "failed"; readonly error: ChatError }
|
|
82
|
+
/** The person gave up on it. */
|
|
83
|
+
| { readonly kind: "discarded" }
|
|
84
|
+
|
|
85
|
+
/** The send after a failed attempt, or none when the failure settled it (a refusal of its first and only attempt). */
|
|
86
|
+
const afterFailure = (send: OutstandingSend, error: ChatError): OutstandingSend | undefined => {
|
|
87
|
+
if (error._tag === "ApprovalRequired")
|
|
88
|
+
return { ...send, state: "awaiting-approval", doubtful: true, waitingOn: error.approvalId ?? send.waitingOn }
|
|
89
|
+
if (error._tag === "ConsentRequired")
|
|
90
|
+
return { ...send, state: "awaiting-consent", doubtful: true, waitingOn: error.consentId ?? send.waitingOn }
|
|
91
|
+
// The answer was lost: it may have run. Sending again, under its key, runs it at most once.
|
|
92
|
+
if (!isDefinitive(error)) return { ...send, state: "uncertain", doubtful: true }
|
|
93
|
+
// A refusal, and nothing else was ever sent under the key: it did not run.
|
|
94
|
+
if (!send.doubtful) return undefined
|
|
95
|
+
// After a lost answer or stored work, a refusal now proves nothing about what was sent before.
|
|
96
|
+
return { ...send, state: send.state === "sending" || send.state === "uncertain" ? "unconfirmed" : send.state }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The outstanding sends once `outcome` is known for the send under `key` (the same array when no send has that key,
|
|
101
|
+
* or nothing changed).
|
|
102
|
+
*/
|
|
103
|
+
export const settleSend = (
|
|
104
|
+
sends: ReadonlyArray<OutstandingSend>,
|
|
105
|
+
key: string,
|
|
106
|
+
outcome: SendOutcome,
|
|
107
|
+
): ReadonlyArray<OutstandingSend> => {
|
|
108
|
+
const index = sends.findIndex((send) => send.key === key)
|
|
109
|
+
if (index < 0) return sends
|
|
110
|
+
const next = outcome.kind === "failed" ? afterFailure(sends[index]!, outcome.error) : undefined
|
|
111
|
+
return next === undefined ? sends.filter((_, i) => i !== index) : sends.map((send, i) => (i === index ? next : send))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** `sends` with `send` in place of the one under its key (or added). */
|
|
115
|
+
export const putSend = (sends: ReadonlyArray<OutstandingSend>, send: OutstandingSend): ReadonlyArray<OutstandingSend> =>
|
|
116
|
+
sends.some((s) => s.key === send.key) ? sends.map((s) => (s.key === send.key ? send : s)) : [...sends, send]
|
|
117
|
+
|
|
118
|
+
// -- The store ------------------------------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
/** Whose sends: a person, in an organisation. */
|
|
121
|
+
export interface SendScope {
|
|
122
|
+
readonly userId: string
|
|
123
|
+
readonly orgId: string
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A web `Storage` (`localStorage`), or anything with its three methods. */
|
|
127
|
+
export interface StorageLike {
|
|
128
|
+
readonly getItem: (key: string) => string | null
|
|
129
|
+
readonly setItem: (key: string, value: string) => void
|
|
130
|
+
readonly removeItem: (key: string) => void
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface OutstandingStore {
|
|
134
|
+
/** The person's outstanding sends in the organisation, in the order they were made. */
|
|
135
|
+
readonly list: (scope: SendScope) => ReadonlyArray<OutstandingSend>
|
|
136
|
+
/** Record a send (before its request leaves), or its new state. */
|
|
137
|
+
readonly put: (scope: SendScope, send: OutstandingSend) => void
|
|
138
|
+
/** Record what became of the send under `key`. */
|
|
139
|
+
readonly settle: (scope: SendScope, key: string, outcome: SendOutcome) => void
|
|
140
|
+
/** The scope's sends now, then after every change, until the stream is interrupted. */
|
|
141
|
+
readonly changes: (scope: SendScope) => Stream.Stream<ReadonlyArray<OutstandingSend>>
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const decodeSends = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(OutstandingSend)))
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The outstanding sends, kept per person and organisation: in `storage` when given (a web `Storage`, `localStorage`,
|
|
148
|
+
* for them to survive a reload and a sign-out, and to be one list for every tab: each change reads it afresh), and in
|
|
149
|
+
* this page's memory, which still outlives every screen when storage fails (full, denied, a private mode).
|
|
150
|
+
*/
|
|
151
|
+
export const outstandingStore = (storage?: StorageLike): OutstandingStore => {
|
|
152
|
+
const memory = new Map<string, ReadonlyArray<OutstandingSend>>()
|
|
153
|
+
/** Scopes whose last write storage refused: until it takes one, this page's memory is the newer. */
|
|
154
|
+
const unwritten = new Set<string>()
|
|
155
|
+
const listeners = new Map<string, Set<(sends: ReadonlyArray<OutstandingSend>) => void>>()
|
|
156
|
+
const keyOf = (scope: SendScope) =>
|
|
157
|
+
`eloxiv.chat.outstanding:${encodeURIComponent(scope.userId)}:${encodeURIComponent(scope.orgId)}`
|
|
158
|
+
const list = (scope: SendScope): ReadonlyArray<OutstandingSend> => {
|
|
159
|
+
const key = keyOf(scope)
|
|
160
|
+
if (storage !== undefined && !unwritten.has(key)) {
|
|
161
|
+
try {
|
|
162
|
+
const raw = storage.getItem(key)
|
|
163
|
+
const stored = raw === null ? [] : Option.getOrElse(decodeSends(raw), () => [])
|
|
164
|
+
memory.set(key, stored)
|
|
165
|
+
return stored
|
|
166
|
+
} catch {
|
|
167
|
+
// Storage unavailable: this page's memory.
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return memory.get(key) ?? []
|
|
171
|
+
}
|
|
172
|
+
const write = (scope: SendScope, sends: ReadonlyArray<OutstandingSend>) => {
|
|
173
|
+
const key = keyOf(scope)
|
|
174
|
+
memory.set(key, sends)
|
|
175
|
+
try {
|
|
176
|
+
if (sends.length === 0) storage?.removeItem(key)
|
|
177
|
+
else storage?.setItem(key, JSON.stringify(sends))
|
|
178
|
+
unwritten.delete(key)
|
|
179
|
+
} catch {
|
|
180
|
+
// Storage refused the write: this page's memory has it.
|
|
181
|
+
unwritten.add(key)
|
|
182
|
+
}
|
|
183
|
+
for (const listener of listeners.get(key) ?? []) listener(sends)
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
list,
|
|
187
|
+
put: (scope, send) => write(scope, putSend(list(scope), send)),
|
|
188
|
+
settle: (scope, key, outcome) => {
|
|
189
|
+
const before = list(scope)
|
|
190
|
+
const after = settleSend(before, key, outcome)
|
|
191
|
+
if (after !== before) write(scope, after)
|
|
192
|
+
},
|
|
193
|
+
changes: (scope) =>
|
|
194
|
+
Stream.callback<ReadonlyArray<OutstandingSend>>((queue) =>
|
|
195
|
+
Effect.acquireRelease(
|
|
196
|
+
Effect.sync(() => {
|
|
197
|
+
const key = keyOf(scope)
|
|
198
|
+
const listener = (sends: ReadonlyArray<OutstandingSend>) => Queue.offerUnsafe(queue, sends)
|
|
199
|
+
const set = listeners.get(key) ?? new Set()
|
|
200
|
+
set.add(listener)
|
|
201
|
+
listeners.set(key, set)
|
|
202
|
+
Queue.offerUnsafe(queue, list(scope))
|
|
203
|
+
return () => set.delete(listener)
|
|
204
|
+
}),
|
|
205
|
+
(remove) => Effect.sync(remove),
|
|
206
|
+
).pipe(Effect.andThen(Effect.never)),
|
|
207
|
+
),
|
|
208
|
+
}
|
|
209
|
+
}
|
package/src/Client.ts
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The headless client SDK. The typed client is the action registry projected
|
|
3
|
+
* through `toRpcGroup` (no hand-written glue): every action is a method whose
|
|
4
|
+
* input and output types come from its contract.
|
|
5
|
+
*
|
|
6
|
+
* Uses only web-standard APIs (fetch, WebSocket via Zero), so it runs in
|
|
7
|
+
* browsers, Tauri, Bun, Node and React Native.
|
|
8
|
+
*/
|
|
9
|
+
import type {
|
|
10
|
+
AnyModuleContract,
|
|
11
|
+
MakeActionListing,
|
|
12
|
+
McpServerIdentity,
|
|
13
|
+
RegistryRpcs,
|
|
14
|
+
ReleaseInfo,
|
|
15
|
+
} from "@eloxiv/contracts"
|
|
16
|
+
import {
|
|
17
|
+
actionRegistry,
|
|
18
|
+
actionResult,
|
|
19
|
+
CLIENT_VERSION_HEADER,
|
|
20
|
+
IDEMPOTENCY_HEADER,
|
|
21
|
+
MAKE_RPC_ACTIONS,
|
|
22
|
+
MAKE_RPC_CALL,
|
|
23
|
+
MakeRpcGroup,
|
|
24
|
+
MCP_IDENTITY_PATH,
|
|
25
|
+
RELEASE_PATH,
|
|
26
|
+
toRpcGroup,
|
|
27
|
+
} from "@eloxiv/contracts"
|
|
28
|
+
import { Context, Effect, Exit, Layer, ManagedRuntime, Schema, Scope } from "effect"
|
|
29
|
+
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"
|
|
30
|
+
import { type Rpc, RpcClient, type RpcClientError, RpcSerialization } from "effect/rpc"
|
|
31
|
+
import { makeReader, type ReaderOptions } from "./Reader.ts"
|
|
32
|
+
import {
|
|
33
|
+
backendStatus,
|
|
34
|
+
type BackendStatus,
|
|
35
|
+
type Circuit,
|
|
36
|
+
httpAction,
|
|
37
|
+
makeCircuit,
|
|
38
|
+
RequestError,
|
|
39
|
+
type RequestOptions,
|
|
40
|
+
type SignalLike,
|
|
41
|
+
} from "./Transport.ts"
|
|
42
|
+
|
|
43
|
+
export interface ClientOptions<Modules extends ReadonlyArray<AnyModuleContract>> {
|
|
44
|
+
/** Kernel base URL, e.g. `http://localhost:4100`. */
|
|
45
|
+
readonly baseUrl: string
|
|
46
|
+
/** Module contracts the app installed (generated `eloxiv.modules.ts`). */
|
|
47
|
+
readonly modules: Modules
|
|
48
|
+
/** Current bearer token; read on every call. */
|
|
49
|
+
readonly token?: (() => string | undefined) | undefined
|
|
50
|
+
/**
|
|
51
|
+
* Organisation to act in, when the user belongs to several: a fixed id, or a function read on every call
|
|
52
|
+
* (an app that lets the user switch organisations).
|
|
53
|
+
*/
|
|
54
|
+
readonly orgId?: string | (() => string | undefined) | undefined
|
|
55
|
+
/**
|
|
56
|
+
* This client's version (the app build), sent as `x-eloxiv-client-version` on every call. The kernel
|
|
57
|
+
* refuses writes from versions older than its minimum (`ClientOutdated`); reads keep working.
|
|
58
|
+
*/
|
|
59
|
+
readonly clientVersion?: string | undefined
|
|
60
|
+
/**
|
|
61
|
+
* A host that supplies no backend says so, with why (a standalone or static build): every call and read is
|
|
62
|
+
* refused before it is made (`BackendDisabled`), and `status()` reports it.
|
|
63
|
+
*/
|
|
64
|
+
readonly backend?: { readonly disabled: string } | undefined
|
|
65
|
+
/** The backend's failure circuit (`makeCircuit`), shared by every request this client makes (default: its own). */
|
|
66
|
+
readonly circuit?: Circuit | undefined
|
|
67
|
+
/** How `read` batches (`makeReader`'s window, size, retries and timeout). */
|
|
68
|
+
readonly batch?: Pick<ReaderOptions, "windowMs" | "maxItems" | "retries" | "retryBaseMs" | "timeoutMs"> | undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface CallOptions {
|
|
72
|
+
readonly idempotencyKey?: string | undefined
|
|
73
|
+
/** Give up after this long (ms): the call rejects with `RequestError` `Timeout` (it may still have run). */
|
|
74
|
+
readonly timeoutMs?: number | undefined
|
|
75
|
+
/** Abort the call (its request is aborted; a write the kernel already received may still run). */
|
|
76
|
+
readonly signal?: SignalLike | undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type ActionName<Modules extends ReadonlyArray<AnyModuleContract>> = RegistryRpcs<Modules>["_tag"]
|
|
80
|
+
export type ActionInput<Modules extends ReadonlyArray<AnyModuleContract>, Tag extends string> = Rpc.PayloadConstructor<
|
|
81
|
+
Rpc.ExtractTag<RegistryRpcs<Modules>, Tag>
|
|
82
|
+
>
|
|
83
|
+
export type ActionOutput<Modules extends ReadonlyArray<AnyModuleContract>, Tag extends string> = Rpc.Success<
|
|
84
|
+
Rpc.ExtractTag<RegistryRpcs<Modules>, Tag>
|
|
85
|
+
>
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The `authorization` header a call is made with, sent on its HTTP request as well as inside the RPC message. The
|
|
89
|
+
* kernel's cookie guard reads the request's headers, not the message's: a runtime that keeps a cookie jar (React
|
|
90
|
+
* Native on Android attaches the session cookie Better Auth set at sign-in to every later request) would otherwise
|
|
91
|
+
* send a cookie POST with no `Authorization` header, which the guard refuses as a forgery (`403`). With it, the guard
|
|
92
|
+
* drops the cookie and the call authenticates by its bearer token only. (Provided to the call's fiber; Effect RPC
|
|
93
|
+
* runs the HTTP send with that fiber's services.)
|
|
94
|
+
*/
|
|
95
|
+
const CallAuthorization = Context.Reference<string | undefined>("@eloxiv/client/CallAuthorization", {
|
|
96
|
+
defaultValue: () => undefined,
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
export const makeClient = <const Modules extends ReadonlyArray<AnyModuleContract>>(options: ClientOptions<Modules>) => {
|
|
100
|
+
const group = toRpcGroup(options.modules).merge(MakeRpcGroup)
|
|
101
|
+
const protocol = RpcClient.layerProtocolHttp({
|
|
102
|
+
url: `${options.baseUrl}/rpc`,
|
|
103
|
+
transformClient: HttpClient.mapRequestEffect((request) =>
|
|
104
|
+
Effect.map(Effect.service(CallAuthorization), (authorization) =>
|
|
105
|
+
authorization === undefined ? request : HttpClientRequest.setHeader(request, "authorization", authorization),
|
|
106
|
+
),
|
|
107
|
+
),
|
|
108
|
+
}).pipe(Layer.provide(FetchHttpClient.layer), Layer.provide(RpcSerialization.layerJson))
|
|
109
|
+
const runtime = ManagedRuntime.make(protocol)
|
|
110
|
+
const scope = Effect.runSync(Scope.make())
|
|
111
|
+
const rpc = runtime.runPromise(Scope.provide(RpcClient.make(group), scope))
|
|
112
|
+
const circuit = options.circuit ?? makeCircuit()
|
|
113
|
+
const reader = makeReader({ ...options, ...options.batch }, circuit)
|
|
114
|
+
const registry = actionRegistry(options.modules)
|
|
115
|
+
const decoders = new Map<string, (value: unknown) => unknown>()
|
|
116
|
+
/** The envelope of `action` as the RPC client would give it (its output decoded by the action's schema). */
|
|
117
|
+
const decodeResult = (action: string, encoded: unknown) => {
|
|
118
|
+
let decode = decoders.get(action)
|
|
119
|
+
if (decode === undefined) {
|
|
120
|
+
const contract = registry.get(action)
|
|
121
|
+
if (contract === undefined)
|
|
122
|
+
throw new RequestError(404, { _tag: "UnknownAction", action, message: `No action ${action}` })
|
|
123
|
+
decode = Schema.decodeUnknownSync(actionResult(contract) as unknown as Schema.Codec<unknown, unknown>)
|
|
124
|
+
decoders.set(action, decode)
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
return decode(encoded)
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw new RequestError(0, { _tag: "InvalidOutput", message: String(error) })
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Refuses a call before it is made while the host supplies no backend or the circuit is open. */
|
|
133
|
+
const admit = () => {
|
|
134
|
+
const status = backendStatus(options, circuit)
|
|
135
|
+
if (status.state === "disabled") throw new RequestError(0, { _tag: "BackendDisabled", message: status.reason })
|
|
136
|
+
if (circuit.isOpen() && status.state === "unavailable") {
|
|
137
|
+
throw new RequestError(0, { _tag: "BackendUnavailable", message: status.reason, retryAt: status.retryAt })
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** A typed error is the kernel's answer; a protocol error (nothing definitive came back) counts against the circuit. */
|
|
141
|
+
const told = <A>(effect: Effect.Effect<A, unknown>) =>
|
|
142
|
+
effect.pipe(
|
|
143
|
+
Effect.tap(() => Effect.sync(() => circuit.succeeded())),
|
|
144
|
+
Effect.tapError((error) =>
|
|
145
|
+
Effect.sync(() =>
|
|
146
|
+
(error as { _tag?: unknown })._tag === "RpcClientError" ? circuit.failed("retry") : circuit.succeeded(),
|
|
147
|
+
),
|
|
148
|
+
),
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
const headers = (call?: CallOptions): Record<string, string> => {
|
|
152
|
+
const result: Record<string, string> = {}
|
|
153
|
+
const token = options.token?.()
|
|
154
|
+
if (token !== undefined) result["authorization"] = `Bearer ${token}`
|
|
155
|
+
const orgId = typeof options.orgId === "function" ? options.orgId() : options.orgId
|
|
156
|
+
if (orgId !== undefined) result["x-eloxiv-org"] = orgId
|
|
157
|
+
if (options.clientVersion !== undefined) result[CLIENT_VERSION_HEADER] = options.clientVersion
|
|
158
|
+
if (call?.idempotencyKey !== undefined) result[IDEMPOTENCY_HEADER] = call.idempotencyKey
|
|
159
|
+
return result
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
type Methods = Record<
|
|
163
|
+
string,
|
|
164
|
+
(input: unknown, options: { headers: Record<string, string> }) => Effect.Effect<unknown, unknown>
|
|
165
|
+
>
|
|
166
|
+
const methodOf = async (action: string) => {
|
|
167
|
+
const method = ((await rpc) as unknown as Methods)[action]
|
|
168
|
+
if (method === undefined) throw new Error(`Unknown action ${action}`)
|
|
169
|
+
return method
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
/** Call an action. Rejects with the action's typed error (`Forbidden`, `ApprovalRequired`, ...). */
|
|
174
|
+
call: async <const Tag extends ActionName<Modules>>(
|
|
175
|
+
action: Tag,
|
|
176
|
+
input: ActionInput<Modules, Tag>,
|
|
177
|
+
call?: CallOptions,
|
|
178
|
+
): Promise<ActionOutput<Modules, Tag>> => {
|
|
179
|
+
admit()
|
|
180
|
+
const method = await methodOf(action)
|
|
181
|
+
const sent = headers(call)
|
|
182
|
+
let effect = told(
|
|
183
|
+
method(input, { headers: sent }).pipe(Effect.provideService(CallAuthorization, sent["authorization"])),
|
|
184
|
+
)
|
|
185
|
+
if (call?.timeoutMs !== undefined) {
|
|
186
|
+
const ms = call.timeoutMs
|
|
187
|
+
effect = effect.pipe(
|
|
188
|
+
Effect.timeoutOrElse({
|
|
189
|
+
duration: ms,
|
|
190
|
+
orElse: () => Effect.fail(new RequestError(0, { _tag: "Timeout", message: `No answer within ${ms} ms` })),
|
|
191
|
+
}),
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
return (await runtime.runPromise(
|
|
195
|
+
effect,
|
|
196
|
+
call?.signal === undefined ? undefined : { signal: call.signal as never },
|
|
197
|
+
)) as ActionOutput<Modules, Tag>
|
|
198
|
+
},
|
|
199
|
+
/**
|
|
200
|
+
* A read-only action's result, read in a batch with the other reads made in the same window (`makeReader`):
|
|
201
|
+
* typed like `call`, rejecting with `RequestError` (the item's own refusal, or the transport's).
|
|
202
|
+
*/
|
|
203
|
+
read: async <const Tag extends ActionName<Modules>>(
|
|
204
|
+
action: Tag,
|
|
205
|
+
input: ActionInput<Modules, Tag>,
|
|
206
|
+
request?: { readonly signal?: SignalLike | undefined },
|
|
207
|
+
): Promise<ActionOutput<Modules, Tag>> => {
|
|
208
|
+
const contract = registry.get(action)
|
|
209
|
+
if (contract === undefined)
|
|
210
|
+
throw new RequestError(404, { _tag: "UnknownAction", action, message: `No action ${action}` })
|
|
211
|
+
const encoded = Schema.encodeUnknownSync(contract.input as Schema.Codec<unknown, unknown>)(input)
|
|
212
|
+
return decodeResult(action, await reader.read(action, encoded, request)) as ActionOutput<Modules, Tag>
|
|
213
|
+
},
|
|
214
|
+
/**
|
|
215
|
+
* An action over plain HTTP (`POST /api/actions/<action>`), for what the RPC call does not give: `keepalive`
|
|
216
|
+
* (state published while the page goes away) and retries under an idempotency key, with a timeout and an abort
|
|
217
|
+
* signal. Typed like `call`; rejects with `RequestError`.
|
|
218
|
+
*/
|
|
219
|
+
send: async <const Tag extends ActionName<Modules>>(
|
|
220
|
+
action: Tag,
|
|
221
|
+
input: ActionInput<Modules, Tag>,
|
|
222
|
+
request?: RequestOptions,
|
|
223
|
+
): Promise<ActionOutput<Modules, Tag>> => {
|
|
224
|
+
const contract = registry.get(action)
|
|
225
|
+
if (contract === undefined)
|
|
226
|
+
throw new RequestError(404, { _tag: "UnknownAction", action, message: `No action ${action}` })
|
|
227
|
+
const encoded = Schema.encodeUnknownSync(contract.input as Schema.Codec<unknown, unknown>)(input)
|
|
228
|
+
return decodeResult(action, await httpAction(options, circuit, action, encoded, request)) as ActionOutput<
|
|
229
|
+
Modules,
|
|
230
|
+
Tag
|
|
231
|
+
>
|
|
232
|
+
},
|
|
233
|
+
/** Whether there is a backend to talk to: disabled by the host, or the failure circuit's state. */
|
|
234
|
+
status: (): BackendStatus => backendStatus(options, circuit),
|
|
235
|
+
/** Told when the backend becomes unavailable or available again; returns the unsubscribe. */
|
|
236
|
+
onStatus: (listener: (status: BackendStatus) => void) => circuit.subscribe(listener),
|
|
237
|
+
/**
|
|
238
|
+
* Call an action as an Effect that runs in the caller's fiber, acting with the session and organisation given
|
|
239
|
+
* here (not the client's `token` and `orgId`): interrupting it aborts the request. Fails with the action's
|
|
240
|
+
* typed error, or the protocol's (`RpcClientError`).
|
|
241
|
+
*/
|
|
242
|
+
callEffect: <const Tag extends ActionName<Modules>>(
|
|
243
|
+
action: Tag,
|
|
244
|
+
input: ActionInput<Modules, Tag>,
|
|
245
|
+
acting: { readonly token: string; readonly orgId: string; readonly idempotencyKey?: string | undefined },
|
|
246
|
+
): Effect.Effect<ActionOutput<Modules, Tag>, unknown> =>
|
|
247
|
+
Effect.promise(() => methodOf(action)).pipe(
|
|
248
|
+
Effect.flatMap((method) => {
|
|
249
|
+
const sent: Record<string, string> = {
|
|
250
|
+
authorization: `Bearer ${acting.token}`,
|
|
251
|
+
"x-eloxiv-org": acting.orgId,
|
|
252
|
+
}
|
|
253
|
+
if (options.clientVersion !== undefined) sent[CLIENT_VERSION_HEADER] = options.clientVersion
|
|
254
|
+
if (acting.idempotencyKey !== undefined) sent[IDEMPOTENCY_HEADER] = acting.idempotencyKey
|
|
255
|
+
return method(input, { headers: sent }).pipe(Effect.provideService(CallAuthorization, sent["authorization"]))
|
|
256
|
+
}),
|
|
257
|
+
) as Effect.Effect<ActionOutput<Modules, Tag>, unknown>,
|
|
258
|
+
/**
|
|
259
|
+
* MAKE modules' actions, installed at run time (so not among the typed methods): the ones the caller reaches,
|
|
260
|
+
* and a call of one through the invocation path (its envelope, or its typed error).
|
|
261
|
+
*/
|
|
262
|
+
make: {
|
|
263
|
+
actions: async (): Promise<ReadonlyArray<MakeActionListing>> => {
|
|
264
|
+
const method = await methodOf(MAKE_RPC_ACTIONS)
|
|
265
|
+
const sent = headers()
|
|
266
|
+
return (await runtime.runPromise(
|
|
267
|
+
method({}, { headers: sent }).pipe(Effect.provideService(CallAuthorization, sent["authorization"])),
|
|
268
|
+
)) as ReadonlyArray<MakeActionListing>
|
|
269
|
+
},
|
|
270
|
+
call: async (action: string, input: unknown, call?: CallOptions): Promise<unknown> => {
|
|
271
|
+
const method = await methodOf(MAKE_RPC_CALL)
|
|
272
|
+
const sent = headers(call)
|
|
273
|
+
return await runtime.runPromise(
|
|
274
|
+
method({ action, input }, { headers: sent }).pipe(
|
|
275
|
+
Effect.provideService(CallAuthorization, sent["authorization"]),
|
|
276
|
+
),
|
|
277
|
+
)
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
/** The installed modules this client was projected from. */
|
|
281
|
+
modules: options.modules,
|
|
282
|
+
/** The underlying Effect RPC client, for Effect programs. */
|
|
283
|
+
rpc: rpc as Promise<RpcClient.RpcClient<RegistryRpcs<Modules>, RpcClientError.RpcClientError>>,
|
|
284
|
+
headers,
|
|
285
|
+
dispose: async () => {
|
|
286
|
+
await Effect.runPromise(Scope.close(scope, Exit.void))
|
|
287
|
+
await runtime.dispose()
|
|
288
|
+
},
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export type EloxivClient<Modules extends ReadonlyArray<AnyModuleContract>> = ReturnType<typeof makeClient<Modules>>
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* A call's result is an envelope: `{ kind: "output", output }` on first execution, or, when an idempotent call
|
|
296
|
+
* is replayed, `{ kind: "replay", receipt }` (facts about what the original call did, never its output).
|
|
297
|
+
*/
|
|
298
|
+
export { isReplay, type InvocationReceipt, type ReplayEnvelope } from "@eloxiv/contracts"
|
|
299
|
+
|
|
300
|
+
/** The release a kernel advertises (`GET /release`): its versions and the oldest client it accepts writes from. */
|
|
301
|
+
export const fetchRelease = async (baseUrl: string): Promise<ReleaseInfo> => {
|
|
302
|
+
const response = await fetch(`${baseUrl}${RELEASE_PATH}`)
|
|
303
|
+
if (!response.ok) throw new Error(`${RELEASE_PATH} answered ${response.status}`)
|
|
304
|
+
return (await response.json()) as ReleaseInfo
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The kernel's MCP server identity (`GET /.well-known/mcp.json`): the canonical name to list it under, its endpoint
|
|
309
|
+
* and OAuth resource. A settings page or connect flow shows and uses these, never a name of its own.
|
|
310
|
+
*/
|
|
311
|
+
export const mcpServerIdentity = async (baseUrl: string): Promise<McpServerIdentity> => {
|
|
312
|
+
const response = await fetch(`${baseUrl}${MCP_IDENTITY_PATH}`)
|
|
313
|
+
if (!response.ok) throw new Error(`${MCP_IDENTITY_PATH} answered ${response.status}`)
|
|
314
|
+
return (await response.json()) as McpServerIdentity
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Whether a call failed because this client is older than the kernel's minimum (reload or upgrade, then retry). */
|
|
318
|
+
export const isClientOutdated = (error: unknown): boolean =>
|
|
319
|
+
typeof error === "object" && error !== null && (error as { _tag?: unknown })._tag === "ClientOutdated"
|