@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.
Files changed (269) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Account.d.ts +131 -0
  4. package/dist/Account.d.ts.map +1 -0
  5. package/dist/Account.js +169 -0
  6. package/dist/Account.js.map +1 -0
  7. package/dist/Agent.d.ts +496 -0
  8. package/dist/Agent.d.ts.map +1 -0
  9. package/dist/Agent.js +228 -0
  10. package/dist/Agent.js.map +1 -0
  11. package/dist/AgentSync.d.ts +990 -0
  12. package/dist/AgentSync.d.ts.map +1 -0
  13. package/dist/AgentSync.js +46 -0
  14. package/dist/AgentSync.js.map +1 -0
  15. package/dist/AppState.d.ts +127 -0
  16. package/dist/AppState.d.ts.map +1 -0
  17. package/dist/AppState.js +145 -0
  18. package/dist/AppState.js.map +1 -0
  19. package/dist/AppStateSync.d.ts +193 -0
  20. package/dist/AppStateSync.d.ts.map +1 -0
  21. package/dist/AppStateSync.js +23 -0
  22. package/dist/AppStateSync.js.map +1 -0
  23. package/dist/Auth.d.ts +95 -0
  24. package/dist/Auth.d.ts.map +1 -0
  25. package/dist/Auth.js +139 -0
  26. package/dist/Auth.js.map +1 -0
  27. package/dist/Avatars.d.ts +53 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +121 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/BrowserAnalytics.d.ts +56 -0
  32. package/dist/BrowserAnalytics.d.ts.map +1 -0
  33. package/dist/BrowserAnalytics.js +94 -0
  34. package/dist/BrowserAnalytics.js.map +1 -0
  35. package/dist/Chat.d.ts +712 -0
  36. package/dist/Chat.d.ts.map +1 -0
  37. package/dist/Chat.js +883 -0
  38. package/dist/Chat.js.map +1 -0
  39. package/dist/ChatIntegrity.d.ts +63 -0
  40. package/dist/ChatIntegrity.d.ts.map +1 -0
  41. package/dist/ChatIntegrity.js +89 -0
  42. package/dist/ChatIntegrity.js.map +1 -0
  43. package/dist/ChatSends.d.ts +103 -0
  44. package/dist/ChatSends.d.ts.map +1 -0
  45. package/dist/ChatSends.js +157 -0
  46. package/dist/ChatSends.js.map +1 -0
  47. package/dist/Client.d.ts +113 -0
  48. package/dist/Client.d.ts.map +1 -0
  49. package/dist/Client.js +189 -0
  50. package/dist/Client.js.map +1 -0
  51. package/dist/Collab.d.ts +138 -0
  52. package/dist/Collab.d.ts.map +1 -0
  53. package/dist/Collab.js +454 -0
  54. package/dist/Collab.js.map +1 -0
  55. package/dist/CollabTools.d.ts +129 -0
  56. package/dist/CollabTools.d.ts.map +1 -0
  57. package/dist/CollabTools.js +277 -0
  58. package/dist/CollabTools.js.map +1 -0
  59. package/dist/Connections.d.ts +288 -0
  60. package/dist/Connections.d.ts.map +1 -0
  61. package/dist/Connections.js +316 -0
  62. package/dist/Connections.js.map +1 -0
  63. package/dist/Consent.d.ts +338 -0
  64. package/dist/Consent.d.ts.map +1 -0
  65. package/dist/Consent.js +142 -0
  66. package/dist/Consent.js.map +1 -0
  67. package/dist/Desktop.d.ts +61 -0
  68. package/dist/Desktop.d.ts.map +1 -0
  69. package/dist/Desktop.js +101 -0
  70. package/dist/Desktop.js.map +1 -0
  71. package/dist/Directory.d.ts +36 -0
  72. package/dist/Directory.d.ts.map +1 -0
  73. package/dist/Directory.js +42 -0
  74. package/dist/Directory.js.map +1 -0
  75. package/dist/ErrorReporter.d.ts +48 -0
  76. package/dist/ErrorReporter.d.ts.map +1 -0
  77. package/dist/ErrorReporter.js +70 -0
  78. package/dist/ErrorReporter.js.map +1 -0
  79. package/dist/ExpoSqlite.d.ts +7 -0
  80. package/dist/ExpoSqlite.d.ts.map +1 -0
  81. package/dist/ExpoSqlite.js +7 -0
  82. package/dist/ExpoSqlite.js.map +1 -0
  83. package/dist/FileSync.d.ts +265 -0
  84. package/dist/FileSync.d.ts.map +1 -0
  85. package/dist/FileSync.js +29 -0
  86. package/dist/FileSync.js.map +1 -0
  87. package/dist/FileTables.gen.d.ts +109 -0
  88. package/dist/FileTables.gen.d.ts.map +1 -0
  89. package/dist/FileTables.gen.js +23 -0
  90. package/dist/FileTables.gen.js.map +1 -0
  91. package/dist/Foldkit.d.ts +487 -0
  92. package/dist/Foldkit.d.ts.map +1 -0
  93. package/dist/Foldkit.js +617 -0
  94. package/dist/Foldkit.js.map +1 -0
  95. package/dist/History.d.ts +133 -0
  96. package/dist/History.d.ts.map +1 -0
  97. package/dist/History.js +210 -0
  98. package/dist/History.js.map +1 -0
  99. package/dist/InboxSync.d.ts +428 -0
  100. package/dist/InboxSync.d.ts.map +1 -0
  101. package/dist/InboxSync.js +37 -0
  102. package/dist/InboxSync.js.map +1 -0
  103. package/dist/KernelTables.gen.d.ts +1522 -0
  104. package/dist/KernelTables.gen.d.ts.map +1 -0
  105. package/dist/KernelTables.gen.js +307 -0
  106. package/dist/KernelTables.gen.js.map +1 -0
  107. package/dist/Make.d.ts +75 -0
  108. package/dist/Make.d.ts.map +1 -0
  109. package/dist/Make.js +70 -0
  110. package/dist/Make.js.map +1 -0
  111. package/dist/Models.d.ts +88 -0
  112. package/dist/Models.d.ts.map +1 -0
  113. package/dist/Models.js +80 -0
  114. package/dist/Models.js.map +1 -0
  115. package/dist/Optimistic.d.ts +120 -0
  116. package/dist/Optimistic.d.ts.map +1 -0
  117. package/dist/Optimistic.js +231 -0
  118. package/dist/Optimistic.js.map +1 -0
  119. package/dist/PlatformSync.d.ts +273 -0
  120. package/dist/PlatformSync.d.ts.map +1 -0
  121. package/dist/PlatformSync.js +92 -0
  122. package/dist/PlatformSync.js.map +1 -0
  123. package/dist/Poll.d.ts +113 -0
  124. package/dist/Poll.d.ts.map +1 -0
  125. package/dist/Poll.js +179 -0
  126. package/dist/Poll.js.map +1 -0
  127. package/dist/Preferences.d.ts +18 -0
  128. package/dist/Preferences.d.ts.map +1 -0
  129. package/dist/Preferences.js +22 -0
  130. package/dist/Preferences.js.map +1 -0
  131. package/dist/Proposals.d.ts +29 -0
  132. package/dist/Proposals.d.ts.map +1 -0
  133. package/dist/Proposals.js +41 -0
  134. package/dist/Proposals.js.map +1 -0
  135. package/dist/React.d.ts +17 -0
  136. package/dist/React.d.ts.map +1 -0
  137. package/dist/React.js +17 -0
  138. package/dist/React.js.map +1 -0
  139. package/dist/Reader.d.ts +35 -0
  140. package/dist/Reader.d.ts.map +1 -0
  141. package/dist/Reader.js +136 -0
  142. package/dist/Reader.js.map +1 -0
  143. package/dist/Resources.d.ts +98 -0
  144. package/dist/Resources.d.ts.map +1 -0
  145. package/dist/Resources.js +161 -0
  146. package/dist/Resources.js.map +1 -0
  147. package/dist/Rows.d.ts +4 -0
  148. package/dist/Rows.d.ts.map +1 -0
  149. package/dist/Rows.js +16 -0
  150. package/dist/Rows.js.map +1 -0
  151. package/dist/Runtime.d.ts +254 -0
  152. package/dist/Runtime.d.ts.map +1 -0
  153. package/dist/Runtime.js +1249 -0
  154. package/dist/Runtime.js.map +1 -0
  155. package/dist/RuntimeRuns.d.ts +74 -0
  156. package/dist/RuntimeRuns.d.ts.map +1 -0
  157. package/dist/RuntimeRuns.js +118 -0
  158. package/dist/RuntimeRuns.js.map +1 -0
  159. package/dist/ServicesSync.d.ts +286 -0
  160. package/dist/ServicesSync.d.ts.map +1 -0
  161. package/dist/ServicesSync.js +40 -0
  162. package/dist/ServicesSync.js.map +1 -0
  163. package/dist/Session.d.ts +226 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +763 -0
  166. package/dist/Session.js.map +1 -0
  167. package/dist/ShareGrant.d.ts +47 -0
  168. package/dist/ShareGrant.d.ts.map +1 -0
  169. package/dist/ShareGrant.js +20 -0
  170. package/dist/ShareGrant.js.map +1 -0
  171. package/dist/Sharing.d.ts +203 -0
  172. package/dist/Sharing.d.ts.map +1 -0
  173. package/dist/Sharing.js +520 -0
  174. package/dist/Sharing.js.map +1 -0
  175. package/dist/Skew.d.ts +52 -0
  176. package/dist/Skew.d.ts.map +1 -0
  177. package/dist/Skew.js +77 -0
  178. package/dist/Skew.js.map +1 -0
  179. package/dist/SpacesSync.d.ts +247 -0
  180. package/dist/SpacesSync.d.ts.map +1 -0
  181. package/dist/SpacesSync.js +30 -0
  182. package/dist/SpacesSync.js.map +1 -0
  183. package/dist/Storage.d.ts +51 -0
  184. package/dist/Storage.d.ts.map +1 -0
  185. package/dist/Storage.js +107 -0
  186. package/dist/Storage.js.map +1 -0
  187. package/dist/Sync.d.ts +48 -0
  188. package/dist/Sync.d.ts.map +1 -0
  189. package/dist/Sync.js +48 -0
  190. package/dist/Sync.js.map +1 -0
  191. package/dist/SyncTables.d.ts +13 -0
  192. package/dist/SyncTables.d.ts.map +1 -0
  193. package/dist/SyncTables.js +13 -0
  194. package/dist/SyncTables.js.map +1 -0
  195. package/dist/Tab.d.ts +36 -0
  196. package/dist/Tab.d.ts.map +1 -0
  197. package/dist/Tab.js +44 -0
  198. package/dist/Tab.js.map +1 -0
  199. package/dist/Transport.d.ts +139 -0
  200. package/dist/Transport.d.ts.map +1 -0
  201. package/dist/Transport.js +232 -0
  202. package/dist/Transport.js.map +1 -0
  203. package/dist/Upload.d.ts +41 -0
  204. package/dist/Upload.d.ts.map +1 -0
  205. package/dist/Upload.js +93 -0
  206. package/dist/Upload.js.map +1 -0
  207. package/dist/WebMcp.d.ts +78 -0
  208. package/dist/WebMcp.d.ts.map +1 -0
  209. package/dist/WebMcp.js +204 -0
  210. package/dist/WebMcp.js.map +1 -0
  211. package/dist/index.d.ts +27 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/package.json +97 -3
  216. package/src/Account.ts +249 -0
  217. package/src/Agent.ts +387 -0
  218. package/src/AgentSync.ts +59 -0
  219. package/src/AppState.ts +222 -0
  220. package/src/AppStateSync.ts +26 -0
  221. package/src/Auth.ts +225 -0
  222. package/src/Avatars.ts +144 -0
  223. package/src/BrowserAnalytics.ts +133 -0
  224. package/src/Chat.ts +1150 -0
  225. package/src/ChatIntegrity.ts +130 -0
  226. package/src/ChatSends.ts +209 -0
  227. package/src/Client.ts +319 -0
  228. package/src/Collab.ts +524 -0
  229. package/src/CollabTools.ts +381 -0
  230. package/src/Connections.ts +517 -0
  231. package/src/Consent.ts +176 -0
  232. package/src/Desktop.ts +139 -0
  233. package/src/Directory.ts +71 -0
  234. package/src/ErrorReporter.ts +112 -0
  235. package/src/ExpoSqlite.ts +6 -0
  236. package/src/FileSync.ts +34 -0
  237. package/src/FileTables.gen.ts +23 -0
  238. package/src/Foldkit.ts +960 -0
  239. package/src/History.ts +337 -0
  240. package/src/InboxSync.ts +47 -0
  241. package/src/KernelTables.gen.ts +329 -0
  242. package/src/Make.ts +120 -0
  243. package/src/Models.ts +134 -0
  244. package/src/Optimistic.ts +364 -0
  245. package/src/PlatformSync.ts +156 -0
  246. package/src/Poll.ts +227 -0
  247. package/src/Preferences.ts +42 -0
  248. package/src/Proposals.ts +57 -0
  249. package/src/React.ts +26 -0
  250. package/src/Reader.ts +180 -0
  251. package/src/Resources.ts +257 -0
  252. package/src/Rows.ts +16 -0
  253. package/src/Runtime.ts +1409 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +814 -0
  257. package/src/ShareGrant.ts +20 -0
  258. package/src/Sharing.ts +696 -0
  259. package/src/Skew.ts +97 -0
  260. package/src/SpacesSync.ts +61 -0
  261. package/src/Storage.ts +167 -0
  262. package/src/Sync.ts +125 -0
  263. package/src/SyncTables.ts +12 -0
  264. package/src/Tab.ts +59 -0
  265. package/src/Transport.ts +321 -0
  266. package/src/Upload.ts +125 -0
  267. package/src/WebMcp.ts +279 -0
  268. package/src/index.ts +26 -0
  269. package/src/web-globals.d.ts +103 -0
package/src/Account.ts ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Account security and profile, headless: password recovery, address verification and change, two-factor
3
+ * authentication (TOTP and backup codes), OAuth sign-in and the signed-in person's own profile. Each is one request to
4
+ * the kernel's Better Auth routes (`/auth/*`), which the kernel fronts (Identity): every mail goes through the
5
+ * deployment's system email, and a flow that needs mail is refused where the deployment has none.
6
+ *
7
+ * Routes that change the account may rotate the session (Better Auth issues a new one and ends the old): they resolve
8
+ * with the token to use from then on (`token`), the same one when it did not change.
9
+ */
10
+ import { AuthError, originOf, type Session } from "./Auth.ts"
11
+
12
+ export { TwoFactorRequired } from "./Auth.ts"
13
+
14
+ /** The header a client without cookies returns a two-factor challenge in (the kernel's `TWO_FACTOR_CHALLENGE_HEADER`). */
15
+ export const TWO_FACTOR_CHALLENGE_HEADER = "x-eloxiv-two-factor"
16
+
17
+ /** The signed-in person's own account, as the kernel holds it. */
18
+ export interface Account {
19
+ readonly id: string
20
+ readonly email: string
21
+ readonly emailVerified: boolean
22
+ readonly name: string
23
+ readonly image: string | null
24
+ readonly twoFactorEnabled: boolean
25
+ }
26
+
27
+ interface Request {
28
+ readonly method?: "GET" | "POST"
29
+ readonly token?: string | undefined
30
+ readonly body?: unknown
31
+ readonly headers?: Readonly<Record<string, string>>
32
+ }
33
+
34
+ /** One call of the kernel's auth routes: its JSON answer and response, or `AuthError` with Better Auth's message. */
35
+ const call = async (baseUrl: string, path: string, request: Request = {}) => {
36
+ const method = request.method ?? "POST"
37
+ const response = await fetch(`${baseUrl}/auth${path}`, {
38
+ method,
39
+ headers: {
40
+ ...(method === "POST" ? { "content-type": "application/json", origin: originOf(baseUrl) } : {}),
41
+ ...(request.token === undefined ? {} : { authorization: `Bearer ${request.token}` }),
42
+ ...request.headers,
43
+ },
44
+ ...(method === "POST" ? { body: JSON.stringify(request.body ?? {}) } : {}),
45
+ })
46
+ const text = await response.text()
47
+ let json: unknown
48
+ try {
49
+ json = text.length === 0 ? undefined : JSON.parse(text)
50
+ } catch {
51
+ json = undefined
52
+ }
53
+ if (!response.ok) {
54
+ const message = (json as { message?: unknown } | undefined)?.message
55
+ throw new AuthError(`${path} failed: ${typeof message === "string" ? message : text}`, response.status)
56
+ }
57
+ return { json, response }
58
+ }
59
+
60
+ /** The session token a route answered with (`set-auth-token`), or the one it was called with. */
61
+ const tokenAfter = (response: Awaited<ReturnType<typeof fetch>>, token: string) =>
62
+ response.headers.get("set-auth-token") ?? token
63
+
64
+ const sessionOf = (response: Awaited<ReturnType<typeof fetch>>, json: unknown): Session => {
65
+ const token = response.headers.get("set-auth-token")
66
+ if (token === null) throw new AuthError("The server did not return a bearer token", response.status)
67
+ return { token, user: (json as { user: Session["user"] }).user }
68
+ }
69
+
70
+ /**
71
+ * Ask for a password reset: the kernel mails a link to the address when it has an account (and answers the same
72
+ * either way, so it tells nobody whether it does). The link opens `redirectTo` (an origin the kernel trusts) with
73
+ * `?token=`, which `resetPassword` takes.
74
+ */
75
+ export const requestPasswordReset = async (
76
+ baseUrl: string,
77
+ input: { readonly email: string; readonly redirectTo: string },
78
+ ): Promise<void> => {
79
+ await call(baseUrl, "/request-password-reset", { body: input })
80
+ }
81
+
82
+ /** Set a new password with a reset link's token. Every session of the account ends; sign in again. */
83
+ export const resetPassword = async (
84
+ baseUrl: string,
85
+ input: { readonly token: string; readonly newPassword: string },
86
+ ): Promise<void> => {
87
+ await call(baseUrl, "/reset-password", { body: input })
88
+ }
89
+
90
+ /** Mail (again) the link that verifies the account's address; `callbackURL` is where it lands afterwards. */
91
+ export const sendVerificationEmail = async (
92
+ baseUrl: string,
93
+ input: { readonly email: string; readonly callbackURL?: string },
94
+ ): Promise<void> => {
95
+ await call(baseUrl, "/send-verification-email", { body: input })
96
+ }
97
+
98
+ /**
99
+ * Verify an address with the token of its verification link (the link itself does the same in a browser). A change
100
+ * of address's links act only with `session`, the session that asked for the change, while it lasts, each once.
101
+ */
102
+ export const verifyEmail = async (baseUrl: string, token: string, session?: string): Promise<void> => {
103
+ await call(baseUrl, `/verify-email?token=${encodeURIComponent(token)}`, { method: "GET", token: session })
104
+ }
105
+
106
+ /** The signed-in person's account. */
107
+ export const getAccount = async (baseUrl: string, token: string): Promise<Account> => {
108
+ const { json } = await call(baseUrl, "/get-session", { method: "GET", token })
109
+ const user = (json as { user?: Record<string, unknown> } | null | undefined)?.user
110
+ if (user === undefined) throw new AuthError("Not signed in", 401)
111
+ const text = (key: string) => (typeof user[key] === "string" ? user[key] : "")
112
+ return {
113
+ id: text("id"),
114
+ email: text("email"),
115
+ emailVerified: user["emailVerified"] === true,
116
+ name: text("name"),
117
+ image: typeof user["image"] === "string" ? user["image"] : null,
118
+ twoFactorEnabled: user["twoFactorEnabled"] === true,
119
+ }
120
+ }
121
+
122
+ /** Change the person's display name. */
123
+ export const updateProfile = async (
124
+ baseUrl: string,
125
+ token: string,
126
+ input: { readonly name: string },
127
+ ): Promise<void> => {
128
+ await call(baseUrl, "/update-user", { token, body: { name: input.name } })
129
+ }
130
+
131
+ /**
132
+ * Ask to change the account's address. A verified address must confirm it first (a link mailed to it), then the new
133
+ * address is verified (a link mailed there) and only then does it change; an unverified one is verified at the new
134
+ * address. The address never changes on the request alone.
135
+ */
136
+ export const changeEmail = async (
137
+ baseUrl: string,
138
+ token: string,
139
+ input: { readonly newEmail: string; readonly callbackURL?: string },
140
+ ): Promise<void> => {
141
+ await call(baseUrl, "/change-email", { token, body: input })
142
+ }
143
+
144
+ /** Change the password; with `revokeOtherSessions`, every other session ends. Resolves with the token to use. */
145
+ export const changePassword = async (
146
+ baseUrl: string,
147
+ token: string,
148
+ input: { readonly currentPassword: string; readonly newPassword: string; readonly revokeOtherSessions?: boolean },
149
+ ): Promise<{ readonly token: string }> => {
150
+ const { response } = await call(baseUrl, "/change-password", { token, body: input })
151
+ return { token: tokenAfter(response, token) }
152
+ }
153
+
154
+ /**
155
+ * Start two-factor enrollment (the password again): the authenticator app's `otpauth://` URI and ten backup codes.
156
+ * Nothing is required at sign-in until `confirmTwoFactor` proves a first code.
157
+ */
158
+ export const enableTwoFactor = async (
159
+ baseUrl: string,
160
+ token: string,
161
+ input: { readonly password: string },
162
+ ): Promise<{ readonly totpURI: string; readonly backupCodes: ReadonlyArray<string> }> => {
163
+ const { json } = await call(baseUrl, "/two-factor/enable", { token, body: input })
164
+ const body = json as { totpURI: string; backupCodes: ReadonlyArray<string> }
165
+ return { totpURI: body.totpURI, backupCodes: body.backupCodes }
166
+ }
167
+
168
+ /** Finish enrollment with a first code from the app; from then on sign-in asks for a second factor. */
169
+ export const confirmTwoFactor = async (
170
+ baseUrl: string,
171
+ token: string,
172
+ input: { readonly code: string },
173
+ ): Promise<{ readonly token: string }> => {
174
+ const { response } = await call(baseUrl, "/two-factor/verify-totp", { token, body: input })
175
+ return { token: tokenAfter(response, token) }
176
+ }
177
+
178
+ /** Turn two-factor authentication off (the password again). */
179
+ export const disableTwoFactor = async (
180
+ baseUrl: string,
181
+ token: string,
182
+ input: { readonly password: string },
183
+ ): Promise<{ readonly token: string }> => {
184
+ const { response } = await call(baseUrl, "/two-factor/disable", { token, body: input })
185
+ return { token: tokenAfter(response, token) }
186
+ }
187
+
188
+ /** New backup codes (the password again); the old ones stop working. */
189
+ export const regenerateBackupCodes = async (
190
+ baseUrl: string,
191
+ token: string,
192
+ input: { readonly password: string },
193
+ ): Promise<{ readonly backupCodes: ReadonlyArray<string> }> => {
194
+ const { json } = await call(baseUrl, "/two-factor/generate-backup-codes", { token, body: input })
195
+ return { backupCodes: (json as { backupCodes: ReadonlyArray<string> }).backupCodes }
196
+ }
197
+
198
+ /**
199
+ * Finish a sign-in `TwoFactorRequired` interrupted: the challenge and a code from the authenticator app (`totp`) or
200
+ * one of the backup codes (`backup-code`, each good once). Resolves with the session.
201
+ */
202
+ export const verifyTwoFactor = async (
203
+ baseUrl: string,
204
+ input: { readonly challenge: string; readonly code: string; readonly method?: "totp" | "backup-code" },
205
+ ): Promise<Session> => {
206
+ const path = input.method === "backup-code" ? "/two-factor/verify-backup-code" : "/two-factor/verify-totp"
207
+ const { json, response } = await call(baseUrl, path, {
208
+ body: { code: input.code },
209
+ headers: { [TWO_FACTOR_CHALLENGE_HEADER]: input.challenge },
210
+ })
211
+ return sessionOf(response, json)
212
+ }
213
+
214
+ /**
215
+ * Where to send the browser to sign in with an OAuth provider the deployment configured: the provider's page, which
216
+ * returns to the kernel and then to `callbackURL` (an origin the kernel trusts) signed in with the session cookie.
217
+ * An existing account is joined only when the provider verified the same address and the account's own address is
218
+ * verified; otherwise the sign-in is refused (`errorCallbackURL?error=account_not_linked`).
219
+ */
220
+ export const oauthSignInUrl = async (
221
+ baseUrl: string,
222
+ input: { readonly provider: string; readonly callbackURL: string; readonly errorCallbackURL?: string },
223
+ ): Promise<string> => {
224
+ const { json } = await call(baseUrl, "/sign-in/social", { body: { ...input, disableRedirect: true } })
225
+ const url = (json as { url?: unknown } | undefined)?.url
226
+ if (typeof url !== "string") throw new AuthError("The server did not return the provider's URL", 500)
227
+ return url
228
+ }
229
+
230
+ /**
231
+ * Ask for a passwordless sign-in link (where the deployment offers magic links): mailed to the address, single use,
232
+ * five minutes. Answers alike whether or not the address has an account. A link to an account with two-factor
233
+ * authentication signs nobody in (it would skip the second factor), and one that proves an unverified account's
234
+ * address removes the account's earlier password and sessions first.
235
+ */
236
+ export const requestMagicLink = async (
237
+ baseUrl: string,
238
+ input: { readonly email: string; readonly callbackURL?: string; readonly errorCallbackURL?: string },
239
+ ): Promise<void> => {
240
+ await call(baseUrl, "/sign-in/magic-link", { body: input })
241
+ }
242
+
243
+ /** Sign in with a magic link's token (the link itself does the same in a browser, with the session cookie). */
244
+ export const verifyMagicLink = async (baseUrl: string, token: string): Promise<Session> => {
245
+ const { json, response } = await call(baseUrl, `/magic-link/verify?token=${encodeURIComponent(token)}`, {
246
+ method: "GET",
247
+ })
248
+ return sessionOf(response, json)
249
+ }
package/src/Agent.ts ADDED
@@ -0,0 +1,387 @@
1
+ /**
2
+ * The agent from the client SDK (the AgentRuntime contract over HTTP): send a message to your agent, follow
3
+ * its run's events as they happen (server-sent events, resumable from the last sequence number seen), read the
4
+ * run, its context x-ray and its sub-agents, cancel it, make one-shot completions, and read your usage (per meter,
5
+ * grouped into insights, per run) and the budgets that apply to you. Web-standard `fetch` only, like the rest of
6
+ * the SDK.
7
+ */
8
+ import type {
9
+ Attachment,
10
+ Budget,
11
+ BudgetPeriod,
12
+ CompletionMessage,
13
+ ConversationPage,
14
+ ConversationQuery,
15
+ ConversationResource,
16
+ FeedbackList,
17
+ GiveFeedback,
18
+ ContextInventory,
19
+ EngineReadiness,
20
+ ModelUsage,
21
+ Run,
22
+ RunDevice,
23
+ RunMode,
24
+ RunEvent,
25
+ RunTrace,
26
+ RunUsage,
27
+ ScreenSnapshot,
28
+ SentMessage,
29
+ UsageGrouping,
30
+ UsageInsights,
31
+ } from "@eloxiv/contracts"
32
+ import { AGENT_PATHS, CLIENT_VERSION_HEADER, IDEMPOTENCY_HEADER } from "@eloxiv/contracts"
33
+
34
+ export interface AgentClientOptions {
35
+ /** Kernel base URL, e.g. `http://localhost:4100`. */
36
+ readonly baseUrl: string
37
+ /** Current bearer token; read on every call. */
38
+ readonly token?: (() => string | undefined) | undefined
39
+ /** Organisation to act in: a fixed id, or a function read on every call. */
40
+ readonly orgId?: string | (() => string | undefined) | undefined
41
+ readonly clientVersion?: string | undefined
42
+ }
43
+
44
+ /** A refused or failed agent request: the HTTP status and the kernel's error (`_tag`, `message`, fields). */
45
+ export class AgentRequestError extends Error {
46
+ override readonly name = "AgentRequestError"
47
+ readonly status: number
48
+ readonly error: { readonly _tag: string; readonly [field: string]: unknown }
49
+ constructor(status: number, error: { readonly _tag: string; readonly [field: string]: unknown }) {
50
+ super(`${error._tag}: ${typeof error["message"] === "string" ? error["message"] : ""}`)
51
+ this.status = status
52
+ this.error = error
53
+ }
54
+ }
55
+
56
+ /** Parse a server-sent event stream's blocks into their `data:` payloads. */
57
+ const dataOf = (block: string) =>
58
+ block
59
+ .split("\n")
60
+ .filter((line) => line.startsWith("data:"))
61
+ .map((line) => line.slice(5).trimStart())
62
+ .join("\n")
63
+
64
+ /**
65
+ * An abort signal, the part of it used here (typed here: not every platform's types have it). Pass an
66
+ * `AbortController`'s `signal`.
67
+ */
68
+ export interface AbortSignalLike {
69
+ readonly aborted: boolean
70
+ readonly addEventListener: (type: "abort", listener: () => void, options?: { readonly once?: boolean }) => void
71
+ readonly removeEventListener: (type: "abort", listener: () => void) => void
72
+ }
73
+
74
+ /** `init` with `signal` for fetch, whatever the platform's types call a signal. */
75
+ const withSignal = <A extends object>(init: A, signal: AbortSignalLike | undefined): A =>
76
+ signal === undefined ? init : { ...init, signal }
77
+
78
+ /** The parts of a web stream reader the event stream uses (typed here: not every platform's types have them). */
79
+ interface ByteReader {
80
+ readonly read: () => Promise<{ readonly done: boolean; readonly value?: Uint8Array | undefined }>
81
+ readonly cancel: () => Promise<void>
82
+ }
83
+ type TextDecoderConstructor = new () => {
84
+ readonly decode: (input?: Uint8Array, options?: { readonly stream?: boolean }) => string
85
+ }
86
+
87
+ /**
88
+ * The complete server-sent events in `text`, and what is left of an incomplete one. Each event of `runId`'s stream
89
+ * names its run, and a streamed `text-delta` (which the kernel writes with neither) gets that run and `seq: -1`.
90
+ */
91
+ const eventsIn = (text: string, runId: string): { readonly events: ReadonlyArray<RunEvent>; readonly rest: string } => {
92
+ const events: Array<RunEvent> = []
93
+ let buffer = text
94
+ let split = buffer.indexOf("\n\n")
95
+ while (split >= 0) {
96
+ const data = dataOf(buffer.slice(0, split))
97
+ buffer = buffer.slice(split + 2)
98
+ split = buffer.indexOf("\n\n")
99
+ if (data === "") continue
100
+ const event = JSON.parse(data) as Partial<RunEvent> & Pick<RunEvent, "type" | "data">
101
+ events.push({
102
+ ...event,
103
+ runId: typeof event.runId === "string" ? event.runId : runId,
104
+ seq: typeof event.seq === "number" ? event.seq : -1,
105
+ at: typeof event.at === "string" ? event.at : "",
106
+ })
107
+ }
108
+ // A stream read whole may end without a blank line after its last event.
109
+ return { events, rest: buffer }
110
+ }
111
+
112
+ export const agentClient = (options: AgentClientOptions) => {
113
+ const headers = (extra: Record<string, string> = {}): Record<string, string> => {
114
+ const result: Record<string, string> = { ...extra }
115
+ const token = options.token?.()
116
+ if (token !== undefined) result["authorization"] = `Bearer ${token}`
117
+ const orgId = typeof options.orgId === "function" ? options.orgId() : options.orgId
118
+ if (orgId !== undefined) result["x-eloxiv-org"] = orgId
119
+ if (options.clientVersion !== undefined) result[CLIENT_VERSION_HEADER] = options.clientVersion
120
+ return result
121
+ }
122
+ const request = async <A>(
123
+ method: string,
124
+ path: string,
125
+ body?: unknown,
126
+ extra?: Record<string, string>,
127
+ signal?: AbortSignalLike,
128
+ ): Promise<A> => {
129
+ const response = await fetch(
130
+ `${options.baseUrl}${path}`,
131
+ withSignal(
132
+ {
133
+ method,
134
+ headers: headers(body === undefined ? extra : { "content-type": "application/json", ...extra }),
135
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
136
+ },
137
+ signal,
138
+ ),
139
+ )
140
+ const parsed = (await response.json().catch(() => ({}))) as Record<string, unknown>
141
+ if (!response.ok) {
142
+ throw new AgentRequestError(response.status, {
143
+ ...parsed,
144
+ _tag: typeof parsed["_tag"] === "string" ? parsed["_tag"] : `HTTP ${response.status}`,
145
+ })
146
+ }
147
+ return parsed as A
148
+ }
149
+ const run = (runId: string, view = "") =>
150
+ `${AGENT_PATHS.runs}/${encodeURIComponent(runId)}${view === "" ? "" : `/${view}`}`
151
+
152
+ /**
153
+ * The run's events from `after` (exclusive; default from the start), as they happen, ending after
154
+ * `run-finished`. `text-delta` events carry streamed text (`data.delta`, and `data.step`, the model step it
155
+ * belongs to) and are not stored: they come with `seq: -1`. Every other event is stored, so a consumer that stops
156
+ * can resume from the last `seq` it saw. Every event names `runId`. Aborting `signal` closes the connection at
157
+ * once, even while the stream is silent (a run waiting for consent), and ends the iteration.
158
+ */
159
+ async function* events(
160
+ runId: string,
161
+ follow: { readonly after?: number | undefined; readonly signal?: AbortSignalLike | undefined } = {},
162
+ ): AsyncGenerator<RunEvent> {
163
+ const response = await fetch(
164
+ `${options.baseUrl}${run(runId, "events")}?after=${follow.after ?? -1}`,
165
+ withSignal({ method: "GET", headers: headers({ accept: "text/event-stream" }) }, follow.signal),
166
+ )
167
+ if (!response.ok) {
168
+ const parsed = (await response.json().catch(() => ({}))) as Record<string, unknown>
169
+ throw new AgentRequestError(response.status, {
170
+ ...parsed,
171
+ _tag: typeof parsed["_tag"] === "string" ? parsed["_tag"] : `HTTP ${response.status}`,
172
+ })
173
+ }
174
+ // A streaming body where the platform has one; otherwise (React Native's fetch) the whole stream, read once
175
+ // it ends (after `run-finished`).
176
+ const body = (response as unknown as { readonly body?: { readonly getReader: () => ByteReader } | null }).body
177
+ const Decoder = (globalThis as { readonly TextDecoder?: TextDecoderConstructor }).TextDecoder
178
+ if (body === undefined || body === null || Decoder === undefined) {
179
+ for (const event of eventsIn(`${await response.text()}\n\n`, runId).events) {
180
+ yield event
181
+ if (event.type === "run-finished") return
182
+ }
183
+ return
184
+ }
185
+ const reader = body.getReader()
186
+ const decoder = new Decoder()
187
+ let buffer = ""
188
+ // Where aborting the request does not end the body's pending read (not every fetch ties them), cancelling the
189
+ // reader does: the read settles as done.
190
+ const cancel = () => void reader.cancel().catch(() => undefined)
191
+ follow.signal?.addEventListener("abort", cancel, { once: true })
192
+ try {
193
+ for (;;) {
194
+ if (follow.signal?.aborted === true) break
195
+ const { done, value } = await reader.read()
196
+ if (done) break
197
+ const parsed = eventsIn(buffer + decoder.decode(value, { stream: true }), runId)
198
+ buffer = parsed.rest
199
+ for (const event of parsed.events) {
200
+ yield event
201
+ if (event.type === "run-finished") return
202
+ }
203
+ }
204
+ } finally {
205
+ follow.signal?.removeEventListener("abort", cancel)
206
+ await reader.cancel().catch(() => undefined)
207
+ }
208
+ }
209
+
210
+ return {
211
+ /**
212
+ * Send a message (`agent.send`): to a new conversation, or `conversationId`'s. Returns the run to follow. With
213
+ * `device`, the run executes on one of the person's paired devices (its local harness, on their own
214
+ * subscription) instead of the deployment's model; the person's consent to send the turn is asked first.
215
+ */
216
+ send: (
217
+ message: {
218
+ readonly text: string
219
+ readonly conversationId?: string
220
+ readonly attachments?: ReadonlyArray<Attachment>
221
+ readonly device?: RunDevice
222
+ /** What the person is looking at (a ScreenContext snapshot: references only, after privacy rules). */
223
+ readonly screen?: ScreenSnapshot
224
+ /** `plan`: the run reads and plans but changes nothing. Default `act`. */
225
+ readonly mode?: RunMode
226
+ /** For a new conversation: the record it is about (a thread on that record). */
227
+ readonly resource?: ConversationResource
228
+ /**
229
+ * Queue the message behind the conversation's active run instead of being refused: it starts when the runs
230
+ * before it end (`queued` in the answer; cancel it with `cancelQueued`), or expires after `queueTtlMs`.
231
+ */
232
+ readonly queue?: boolean
233
+ readonly queueTtlMs?: number
234
+ },
235
+ call?: {
236
+ readonly idempotencyKey?: string
237
+ /** Aborting it stops waiting for the answer (the kernel may still have run it: retry under the same key). */
238
+ readonly signal?: AbortSignalLike | undefined
239
+ },
240
+ ) =>
241
+ request<SentMessage>(
242
+ "POST",
243
+ AGENT_PATHS.messages,
244
+ message,
245
+ call?.idempotencyKey === undefined ? {} : { [IDEMPOTENCY_HEADER]: call.idempotencyKey },
246
+ call?.signal,
247
+ ),
248
+ events,
249
+ /**
250
+ * The person's send under `idempotencyKey`, if it ran: its receipt (`agent.send`'s, from the kernel's receipt
251
+ * store), or null when none has committed yet (a send still in flight commits its receipt with it).
252
+ */
253
+ sendReceipt: (idempotencyKey: string, call?: { readonly signal?: AbortSignalLike | undefined }) =>
254
+ request<{ readonly receipt: unknown }>(
255
+ "GET",
256
+ `${AGENT_PATHS.messages}/${encodeURIComponent(idempotencyKey)}`,
257
+ undefined,
258
+ undefined,
259
+ call?.signal,
260
+ ),
261
+ /** Follow a run to its end: every stored event in order (text deltas left out), and the finished run. */
262
+ follow: async (runId: string, after?: number) => {
263
+ const seen: Array<RunEvent> = []
264
+ for await (const event of events(runId, { after })) if (event.type !== "text-delta") seen.push(event)
265
+ return { events: seen, run: await request<Run>("GET", run(runId)) }
266
+ },
267
+ run: (runId: string) => request<Run>("GET", run(runId)),
268
+ /** The context x-ray of one model call of the run (default the latest). */
269
+ context: (runId: string, step?: number) =>
270
+ request<ContextInventory>("GET", `${run(runId, "context")}${step === undefined ? "" : `?step=${step}`}`),
271
+ children: (runId: string) => request<ReadonlyArray<Run>>("GET", run(runId, "children")),
272
+ /**
273
+ * A page of the person's conversations, newest first: `q` searches titles and messages; `archived`, `hidden`
274
+ * and `pinned` select; `before` is the previous page's `next`. Invalid arguments are refused (`InvalidInput`).
275
+ */
276
+ conversations: (query: ConversationQuery = {}) => {
277
+ const search = Object.entries(query)
278
+ .filter(([, value]) => value !== undefined)
279
+ .map(([name, value]) => `${name}=${encodeURIComponent(String(value))}`)
280
+ .join("&")
281
+ return request<ConversationPage>("GET", `${AGENT_PATHS.conversations}${search === "" ? "" : `?${search}`}`)
282
+ },
283
+ /** Rename, pin, archive or hide one of the person's conversations (`agent.updateConversation`). */
284
+ updateConversation: (update: {
285
+ readonly conversationId: string
286
+ readonly title?: string
287
+ readonly pinned?: boolean
288
+ readonly archived?: boolean
289
+ readonly hidden?: boolean
290
+ }) => request<unknown>("POST", "/api/actions/agent.updateConversation", update),
291
+ /** The person's active runs (queued, running, waiting), oldest first, each with its activity (`stalled`). */
292
+ active: () => request<ReadonlyArray<Run>>("GET", AGENT_PATHS.runs),
293
+ /**
294
+ * Continue a turn the agent did not finish (`agent.continue`): a new run takes up the same request where the run
295
+ * `runId` (stopped, failed or cancelled) left it. Returns the new run.
296
+ */
297
+ continueTurn: (runId: string) =>
298
+ request<{ readonly kind: string; readonly output: { readonly id: string; readonly conversationId: string } }>(
299
+ "POST",
300
+ "/api/actions/agent.continue",
301
+ { runId },
302
+ ),
303
+ /** Cancel a queued message that has not started (`agent.cancelQueued`). */
304
+ cancelQueued: (submissionId: string) =>
305
+ request<unknown>("POST", "/api/actions/agent.cancelQueued", { id: submissionId }),
306
+ /** Cancel a run (`agent.cancel`). */
307
+ cancel: (runId: string) => request<unknown>("POST", "/api/actions/agent.cancel", { runId }),
308
+ /** A one-shot completion (text, or an object matching `schema`). */
309
+ complete: (completion: {
310
+ readonly messages: ReadonlyArray<CompletionMessage>
311
+ readonly schema?: unknown
312
+ /** The most the completion may write (at most the deployment's limit). */
313
+ readonly maxOutputTokens?: number
314
+ }) =>
315
+ request<{ readonly text: string; readonly object?: unknown; readonly usage: ModelUsage }>(
316
+ "POST",
317
+ AGENT_PATHS.complete,
318
+ completion,
319
+ ),
320
+ /** Usage per meter in the period: yours, or the organisation's (`scope: "org"`, for those who manage the agent). */
321
+ usage: (query: { readonly scope?: "user" | "org"; readonly period?: BudgetPeriod } = {}) =>
322
+ request<Readonly<Record<string, number>>>(
323
+ "GET",
324
+ `${AGENT_PATHS.usage}?scope=${query.scope ?? "user"}&period=${query.period ?? "total"}`,
325
+ ),
326
+ /** Usage grouped by model, day, run or member (the organisation's only), largest cost first. */
327
+ insights: (query: {
328
+ readonly by: UsageGrouping
329
+ readonly scope?: "user" | "org"
330
+ readonly period?: BudgetPeriod
331
+ }) =>
332
+ request<UsageInsights>(
333
+ "GET",
334
+ `${AGENT_PATHS.insights}?scope=${query.scope ?? "user"}&period=${query.period ?? "total"}&by=${query.by}`,
335
+ ),
336
+ /** One of your runs' stored trace: its model and tool calls as spans, and your feedback on it. */
337
+ trace: (runId: string) => request<RunTrace>("GET", run(runId, "trace")),
338
+ /** Rate one of your runs (`agent.feedback`): up or down, with an optional comment and tags. */
339
+ feedback: (feedback: GiveFeedback) => request<unknown>("POST", "/api/actions/agent.feedback", feedback),
340
+ /** Feedback on runs: yours, or the organisation's (`scope: "org"`, for those who manage the agent). */
341
+ feedbackList: (query: { readonly scope?: "user" | "org"; readonly period?: BudgetPeriod } = {}) =>
342
+ request<FeedbackList>(
343
+ "GET",
344
+ `${AGENT_PATHS.feedback}?scope=${query.scope ?? "user"}&period=${query.period ?? "total"}`,
345
+ ),
346
+ /** One of your runs' usage per metered call. */
347
+ runUsage: (runId: string) => request<RunUsage>("GET", run(runId, "usage")),
348
+ /** The budgets that apply to you (with their alert thresholds). */
349
+ budgets: () => request<ReadonlyArray<Budget>>("GET", AGENT_PATHS.budgets),
350
+ /**
351
+ * Whether the person's agent can answer on the organisation's model (AgentRuntime `readiness`): the kernel's
352
+ * `configured`, `missing` or `unavailable`. A request that gets no answer, or an answer that is not the kernel's
353
+ * (a gateway's error, a body it does not recognise), is `unknown`: a failed probe is never taken for a missing
354
+ * setup. A refusal of the caller (401, 403) throws `AgentRequestError`, as every request does.
355
+ */
356
+ readiness: async (options: { readonly signal?: AbortSignalLike } = {}): Promise<EngineReadiness> => {
357
+ const unknown: EngineReadiness = {
358
+ state: "unknown",
359
+ provider: null,
360
+ model: null,
361
+ detail: "Could not ask the kernel whether the agent is set up",
362
+ }
363
+ try {
364
+ const answer = await request<Partial<EngineReadiness>>(
365
+ "GET",
366
+ AGENT_PATHS.readiness,
367
+ undefined,
368
+ undefined,
369
+ options.signal,
370
+ )
371
+ return answer.state === "configured" || answer.state === "missing" || answer.state === "unavailable"
372
+ ? {
373
+ state: answer.state,
374
+ provider: typeof answer.provider === "string" ? answer.provider : null,
375
+ model: typeof answer.model === "string" ? answer.model : null,
376
+ detail: typeof answer.detail === "string" ? answer.detail : "",
377
+ }
378
+ : unknown
379
+ } catch (error) {
380
+ if (error instanceof AgentRequestError && (error.status === 401 || error.status === 403)) throw error
381
+ return unknown
382
+ }
383
+ },
384
+ }
385
+ }
386
+
387
+ export type AgentClient = ReturnType<typeof agentClient>