@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
@@ -0,0 +1,517 @@
1
+ /**
2
+ * Connections in the headless client SDK (docs/contracts/client-sdk.md, "Connections"): the kernel's Connection
3
+ * lifecycle and its endpoint Connections (remote MCP servers, HTTP APIs) as plain functions and small state holders an
4
+ * app's screens bind to, with no UI:
5
+ *
6
+ * connectionsOf(client) the `connections.*` actions, the Secrets routes (put, inventory, removal preview, delete)
7
+ * and `servers`: remote MCP servers listed, added, removed, reconnected and tested, each
8
+ * outcome told apart (active, consent needed, address refused, refused, failed to load),
9
+ * and `apps`: headless MCP App sessions (a tool's `ui://` view opened, called through,
10
+ * closed), which the app renders in a sandbox of its own
11
+ * consentInPopup(...) OAuth consent in a popup window opened synchronously from the person's gesture (a waiting
12
+ * page first, the authorization URL once the kernel answers), completed only when the popup
13
+ * comes back to the app's own origin carrying this attempt's nonce and a Connection id;
14
+ * cancelled when closed, failed on timeout
15
+ * authorizationResume(...) a request blocked on a Connection's authorisation (a chat tool call), recorded before
16
+ * consent and consumed once after it, so the blocked work continues exactly once
17
+ *
18
+ * Web-standard only: the popup is whatever the host's `open` returns, described structurally.
19
+ */
20
+ import type { ConsentStart } from "@eloxiv/contracts"
21
+
22
+ /** What the SDK needs of a client: an untyped action call and the headers it sends (the typed client has both). */
23
+ export interface ConnectionsCaller {
24
+ readonly call: (action: never, input: never) => Promise<unknown>
25
+ readonly headers: () => Record<string, string>
26
+ }
27
+
28
+ /** How the agent behaves in one channel of a channel Connection (`connections.channels`, `connections.setChannel`). */
29
+ export interface ChannelSettingRecord {
30
+ readonly connectionId: string
31
+ readonly channelId: string
32
+ readonly enabled: boolean
33
+ readonly scope: "act" | "plan"
34
+ readonly dailyTokens: number | null
35
+ readonly memory: "thread" | "channel" | "none"
36
+ readonly usedToday: number
37
+ }
38
+
39
+ /** A change to one channel's settings: only the fields given change. */
40
+ export interface ChannelSettingChange {
41
+ readonly enabled?: boolean
42
+ readonly scope?: "act" | "plan"
43
+ readonly dailyTokens?: number | null
44
+ readonly memory?: "thread" | "channel" | "none"
45
+ }
46
+
47
+ /** A Connection as the kernel lists it (the Connections contract's record). */
48
+ export interface ConnectionRecord {
49
+ readonly id: string
50
+ readonly provider: string
51
+ readonly accountLabel: string
52
+ readonly status: "active" | "needs-reauth" | "disconnected"
53
+ readonly statusReason: string | null
54
+ readonly shared: boolean
55
+ readonly endpoint: string | null
56
+ readonly auth: "oauth" | "secret" | "none"
57
+ readonly tools: ReadonlyArray<string> | null
58
+ }
59
+
60
+ export interface RemoteToolRecord {
61
+ readonly name: string
62
+ readonly title: string | null
63
+ readonly description: string
64
+ readonly inputSchema: Readonly<Record<string, unknown>>
65
+ readonly readOnly: boolean
66
+ readonly destructive: boolean
67
+ /** The MCP Apps declaration: the tool's `ui://` view (or null) and who may call it (`model`, `app`). */
68
+ readonly ui?: { readonly resourceUri: string | null; readonly visibility: ReadonlyArray<"model" | "app"> }
69
+ }
70
+
71
+ /** An open MCP App session (`connections.openApp`): the view's calls name its `id`. */
72
+ export interface McpAppSessionRecord {
73
+ readonly id: string
74
+ readonly connectionId: string
75
+ readonly tool: string
76
+ readonly resourceUri: string
77
+ /** The tools the view may call. */
78
+ readonly tools: ReadonlyArray<string>
79
+ readonly openedAt: string
80
+ readonly expiresAt: string
81
+ }
82
+
83
+ /** A resource as the server sent it: text or base64 `blob`, and its `_meta` (an MCP App's CSP and permissions). */
84
+ export interface ResourceContentRecord {
85
+ readonly uri: string
86
+ readonly mimeType: string | null
87
+ readonly text: string | null
88
+ readonly blob: string | null
89
+ readonly meta: Readonly<Record<string, unknown>> | null
90
+ }
91
+
92
+ export interface ToolResultRecord {
93
+ readonly content: ReadonlyArray<unknown>
94
+ readonly structuredContent: unknown
95
+ readonly isError: boolean
96
+ }
97
+
98
+ export type SecretScopeInput =
99
+ | { readonly kind: "user"; readonly orgId: string; readonly userId: string }
100
+ | { readonly kind: "org"; readonly orgId: string }
101
+
102
+ /** How adding a server came out. */
103
+ export type AddOutcome =
104
+ | { readonly kind: "active"; readonly connection: ConnectionRecord }
105
+ /** OAuth: open `consent` (consentInPopup) to finish; the Connection waits ("consent pending"). */
106
+ | { readonly kind: "consent"; readonly connection: ConnectionRecord; readonly consent: ConsentStart }
107
+ /** The kernel refused the address (not https, not public, does not resolve) or the input (a missing secret). */
108
+ | { readonly kind: "rejected"; readonly reason: "address" | "input"; readonly message: string }
109
+ /** Not allowed (a shared server without eloxiv.connections.manage, an organisation secret without eloxiv.secrets.manage). */
110
+ | { readonly kind: "forbidden"; readonly message: string }
111
+
112
+ /** What testing a server found. */
113
+ export type TestOutcome =
114
+ | { readonly kind: "ok"; readonly tools: ReadonlyArray<RemoteToolRecord> }
115
+ /** Consent was started but not finished. */
116
+ | { readonly kind: "pending" }
117
+ /** It needs reauthorisation (its credential was refused). */
118
+ | { readonly kind: "needs-reauth"; readonly reason: string | null }
119
+ /** The server could not be reached or answered badly. */
120
+ | { readonly kind: "load-failed"; readonly message: string }
121
+
122
+ /** The state a servers screen renders. */
123
+ export interface ServersState {
124
+ readonly status: "idle" | "loading" | "ready" | "error"
125
+ readonly servers: ReadonlyArray<ConnectionRecord>
126
+ readonly error: string | null
127
+ }
128
+
129
+ const tagOf = (error: unknown) => (error as { readonly _tag?: unknown } | null)?._tag
130
+ const messageOf = (error: unknown) => {
131
+ const message = (error as { readonly message?: unknown } | null)?.message
132
+ return typeof message === "string" ? message : String(error)
133
+ }
134
+
135
+ /** An address the destination policy refused, by the kernel's wording (a reason a person can act on). */
136
+ const ADDRESS = /destination|https|public address|does not resolve|query or a fragment|absolute URL/iu
137
+
138
+ export const connectionsOf = (client: ConnectionsCaller, options: { readonly baseUrl: string }) => {
139
+ const call = <A>(action: string, input: unknown) =>
140
+ (client.call as unknown as (a: string, i: unknown) => Promise<unknown>)(action, input).then((envelope) => {
141
+ const output = (envelope as { readonly output?: unknown } | null)?.output
142
+ return (output === undefined ? envelope : output) as A
143
+ })
144
+
145
+ const kernel = async <A>(path: string, body: unknown): Promise<A> => {
146
+ const response = await fetch(`${options.baseUrl}${path}`, {
147
+ method: "POST",
148
+ headers: { ...client.headers(), "content-type": "application/json" },
149
+ body: JSON.stringify(body),
150
+ })
151
+ const json = (await response.json()) as A & { readonly _tag?: string; readonly message?: string }
152
+ if (!response.ok) throw json
153
+ return json
154
+ }
155
+
156
+ const list = () =>
157
+ call<{ connections: ReadonlyArray<ConnectionRecord> }>("connections.list", {}).then((r) => r.connections)
158
+
159
+ const add = async (input: Record<string, unknown>): Promise<AddOutcome> => {
160
+ try {
161
+ const { connection, consent } = await call<{ connection: ConnectionRecord; consent: ConsentStart | null }>(
162
+ "connections.add",
163
+ input,
164
+ )
165
+ return consent === null ? { kind: "active", connection } : { kind: "consent", connection, consent }
166
+ } catch (error) {
167
+ const tag = tagOf(error)
168
+ if (tag === "Forbidden") return { kind: "forbidden", message: messageOf(error) }
169
+ if (tag === "InvalidInput") {
170
+ return {
171
+ kind: "rejected",
172
+ reason: ADDRESS.test(messageOf(error)) ? "address" : "input",
173
+ message: messageOf(error),
174
+ }
175
+ }
176
+ throw error
177
+ }
178
+ }
179
+
180
+ const test = async (connection: ConnectionRecord): Promise<TestOutcome> => {
181
+ if (connection.status === "needs-reauth") {
182
+ return connection.statusReason === "consent pending"
183
+ ? { kind: "pending" }
184
+ : { kind: "needs-reauth", reason: connection.statusReason }
185
+ }
186
+ try {
187
+ const { tools } = await call<{ tools: ReadonlyArray<RemoteToolRecord> }>("connections.tools", {
188
+ connectionId: connection.id,
189
+ })
190
+ return { kind: "ok", tools }
191
+ } catch (error) {
192
+ // A refusal that marked the Connection (a 401 the refresh could not cure) is reauthorisation, not a load failure.
193
+ const now = (await list()).find((c) => c.id === connection.id)
194
+ if (now?.status === "needs-reauth") return { kind: "needs-reauth", reason: now.statusReason }
195
+ return { kind: "load-failed", message: messageOf(error) }
196
+ }
197
+ }
198
+
199
+ /** Remote MCP servers (provider `mcp`), as a state a screen renders and the operations on them. */
200
+ const servers = (provider = "mcp") => {
201
+ let state: ServersState = { status: "idle", servers: [], error: null }
202
+ const listeners = new Set<(state: ServersState) => void>()
203
+ const set = (next: ServersState) => {
204
+ state = next
205
+ for (const listener of listeners) listener(state)
206
+ }
207
+ const refresh = async () => {
208
+ set({ ...state, status: "loading", error: null })
209
+ try {
210
+ set({ status: "ready", servers: (await list()).filter((c) => c.provider === provider), error: null })
211
+ } catch (error) {
212
+ set({ ...state, status: "error", error: messageOf(error) })
213
+ }
214
+ }
215
+ return {
216
+ get state() {
217
+ return state
218
+ },
219
+ subscribe: (listener: (state: ServersState) => void) => {
220
+ listeners.add(listener)
221
+ return () => void listeners.delete(listener)
222
+ },
223
+ refresh,
224
+ create: async (
225
+ input: { readonly endpoint: string; readonly auth: Record<string, unknown> } & Record<string, unknown>,
226
+ ) => {
227
+ const outcome = await add({ ...input, provider })
228
+ if (outcome.kind === "active" || outcome.kind === "consent") await refresh()
229
+ return outcome
230
+ },
231
+ remove: async (connectionId: string) => {
232
+ await call("connections.disconnect", { connectionId })
233
+ await refresh()
234
+ },
235
+ /** Consent again (OAuth): open the answer with consentInPopup. */
236
+ reconnect: (connectionId: string, returnTo?: string) =>
237
+ call<ConsentStart>("connections.reconnect", { connectionId, ...(returnTo === undefined ? {} : { returnTo }) }),
238
+ test,
239
+ }
240
+ }
241
+
242
+ return {
243
+ list,
244
+ add,
245
+ test,
246
+ servers,
247
+ disconnect: (connectionId: string) => call("connections.disconnect", { connectionId }),
248
+ /**
249
+ * A channel Connection's channels (Slack's): the settings set for each (a channel not listed takes the defaults:
250
+ * answered, `act`, no budget, `thread` memory), with the tokens used today; and a change to one channel's.
251
+ * The Connection's owner's, or any with `eloxiv.connections.manage` (others are refused `Forbidden`).
252
+ */
253
+ channels: {
254
+ list: (connectionId: string) =>
255
+ call<{ channels: ReadonlyArray<ChannelSettingRecord> }>("connections.channels", { connectionId }).then(
256
+ (r) => r.channels,
257
+ ),
258
+ set: (connectionId: string, channelId: string, change: ChannelSettingChange) =>
259
+ call<ChannelSettingRecord>("connections.setChannel", { connectionId, channelId, ...change }),
260
+ },
261
+ reconnect: (connectionId: string, returnTo?: string) =>
262
+ call<ConsentStart>("connections.reconnect", { connectionId, ...(returnTo === undefined ? {} : { returnTo }) }),
263
+ tools: (connectionId: string) =>
264
+ call<{ tools: ReadonlyArray<RemoteToolRecord> }>("connections.tools", { connectionId }).then((r) => r.tools),
265
+ callTool: (connectionId: string, name: string, args: Record<string, unknown> = {}) =>
266
+ call<ToolResultRecord>("connections.callTool", {
267
+ connectionId,
268
+ name,
269
+ arguments: args,
270
+ }),
271
+ /**
272
+ * MCP App sessions, headless: `open` a tool's `ui://` view (the resource to render, in a sandbox of the app's own,
273
+ * and the tools it may call), `call` a tool for the view (only one the session lists; an agent's call waits for the
274
+ * person's consent), `close` it. A session is the caller's alone.
275
+ */
276
+ apps: {
277
+ open: (connectionId: string, tool: string) =>
278
+ call<{
279
+ session: McpAppSessionRecord
280
+ resource: ResourceContentRecord
281
+ tools: ReadonlyArray<RemoteToolRecord>
282
+ }>("connections.openApp", { connectionId, tool }),
283
+ call: (sessionId: string, name: string, args: Record<string, unknown> = {}) =>
284
+ call<ToolResultRecord>("connections.appCall", { sessionId, name, arguments: args }),
285
+ close: (sessionId: string) => call<{ sessionId: string }>("connections.closeApp", { sessionId }),
286
+ },
287
+ /** The Secrets routes: secrets are put here, never through an action, and only ever named afterwards. */
288
+ secrets: {
289
+ put: (scope: SecretScopeInput, name: string, value: string, allowedOrigins?: ReadonlyArray<string>) =>
290
+ kernel("/kernel/secrets/put", {
291
+ scope,
292
+ name,
293
+ value,
294
+ ...(allowedOrigins === undefined ? {} : { allowedOrigins }),
295
+ }),
296
+ inventory: () =>
297
+ kernel<{ secrets: ReadonlyArray<unknown> }>("/kernel/secrets/inventory", {}).then((r) => r.secrets),
298
+ previewRemoval: (scope: SecretScopeInput, name: string) =>
299
+ kernel<{ metadata: unknown; usages: ReadonlyArray<unknown>; deletable: boolean }>(
300
+ "/kernel/secrets/preview-removal",
301
+ {
302
+ scope,
303
+ name,
304
+ },
305
+ ),
306
+ delete: (scope: SecretScopeInput, name: string) =>
307
+ kernel<{ deleted: number }>("/kernel/secrets/delete", { scope, name }),
308
+ },
309
+ }
310
+ }
311
+
312
+ // ---------------------------------------------------------------------------------------------------------- popup
313
+
314
+ /** The popup window the host opens (a browser's `window.open` result), as the SDK uses it. */
315
+ export interface PopupWindow {
316
+ readonly closed: boolean
317
+ /** Reading `href` throws while the popup shows another origin (the provider's pages). */
318
+ readonly location: { readonly href: string; replace(url: string): void }
319
+ close(): void
320
+ }
321
+
322
+ export class ConsentCancelled extends Error {
323
+ readonly _tag = "ConsentCancelled"
324
+ }
325
+ export class ConsentTimedOut extends Error {
326
+ readonly _tag = "ConsentTimedOut"
327
+ }
328
+ export class PopupBlocked extends Error {
329
+ readonly _tag = "PopupBlocked"
330
+ }
331
+
332
+ const NONCE = "eloxiv_consent"
333
+
334
+ const nonce = () => {
335
+ const bytes = new Uint8Array(16)
336
+ // Read from globalThis: a runtime without Web Crypto (React Native without its polyfill) has no `crypto` global at
337
+ // all, and naming one would throw a ReferenceError instead of this error.
338
+ const webCrypto = (globalThis as { readonly crypto?: { getRandomValues(array: Uint8Array): Uint8Array } }).crypto
339
+ if (webCrypto === undefined) throw new Error("No crypto.getRandomValues on this runtime")
340
+ webCrypto.getRandomValues(bytes)
341
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")
342
+ }
343
+
344
+ const originOf = (href: string) => {
345
+ const match = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]*)/iu.exec(href)
346
+ return match?.[1]?.toLowerCase()
347
+ }
348
+
349
+ const paramOf = (href: string, name: string) => {
350
+ const query = href.split("#", 1)[0]!.split("?", 2)[1] ?? ""
351
+ for (const pair of query.split("&")) {
352
+ const [key, value] = pair.split("=", 2)
353
+ if (key !== undefined && decodeURIComponent(key) === name)
354
+ return value === undefined ? "" : decodeURIComponent(value.replaceAll("+", " "))
355
+ }
356
+ return undefined
357
+ }
358
+
359
+ /**
360
+ * Consent in a popup. Call it from the person's gesture (a click handler) without awaiting anything first: it opens the
361
+ * popup at once on `waitingUrl` (a page of the app's own, `about:blank` by default), so browsers do not block it, then
362
+ * asks `start` for the consent (with a `returnTo` on `appOrigin` carrying this attempt's nonce) and sends the popup to
363
+ * its authorization URL. It resolves with the Connection's id only when the popup returns to `appOrigin` (`appOrigin`
364
+ * must be one of the kernel's trusted origins) with this nonce and a `connection`; a page that lands elsewhere or
365
+ * without them resolves nothing. Closing the popup cancels (`ConsentCancelled`); `timeoutMs` (default 10 minutes, the
366
+ * kernel's consent lifetime) fails with `ConsentTimedOut`. The popup is closed whatever the outcome.
367
+ */
368
+ export const consentInPopup = (options: {
369
+ readonly open: (url: string) => PopupWindow | null
370
+ readonly start: (returnTo: string) => Promise<ConsentStart>
371
+ readonly appOrigin: string
372
+ /** Where the popup comes back on the app's origin (default `/`). */
373
+ readonly returnPath?: string | undefined
374
+ readonly waitingUrl?: string | undefined
375
+ readonly timeoutMs?: number | undefined
376
+ readonly pollMs?: number | undefined
377
+ }): Promise<{ readonly connectionId: string }> => {
378
+ const popup = options.open(options.waitingUrl ?? "about:blank")
379
+ if (popup === null) return Promise.reject(new PopupBlocked("The browser blocked the consent window"))
380
+ const expected = originOf(options.appOrigin)
381
+ const attempt = nonce()
382
+ const path = options.returnPath ?? "/"
383
+ const returnTo = `${options.appOrigin.replace(/\/$/u, "")}${path}${path.includes("?") ? "&" : "?"}${NONCE}=${attempt}`
384
+ return new Promise((resolve, reject) => {
385
+ let timer: ReturnType<typeof setTimeout> | undefined
386
+ let poll: ReturnType<typeof setInterval> | undefined
387
+ let done = false
388
+ const finish = (outcome: () => void) => {
389
+ if (done) return
390
+ done = true
391
+ clearTimeout(timer)
392
+ clearInterval(poll)
393
+ try {
394
+ popup.close()
395
+ } catch {
396
+ // Already closed.
397
+ }
398
+ outcome()
399
+ }
400
+ timer = setTimeout(
401
+ () => finish(() => reject(new ConsentTimedOut("Consent took too long"))),
402
+ options.timeoutMs ?? 600_000,
403
+ )
404
+ void (async () => {
405
+ let consent: ConsentStart
406
+ try {
407
+ consent = await options.start(returnTo)
408
+ } catch (error) {
409
+ finish(() => reject(error))
410
+ return
411
+ }
412
+ if (done) return
413
+ popup.location.replace(consent.authorizeUrl)
414
+ poll = setInterval(() => {
415
+ if (popup.closed) return finish(() => reject(new ConsentCancelled("The consent window was closed")))
416
+ let href: string
417
+ try {
418
+ href = popup.location.href
419
+ } catch {
420
+ return // The provider's pages: another origin.
421
+ }
422
+ if (originOf(href) !== expected || paramOf(href, NONCE) !== attempt) return
423
+ const connectionId = paramOf(href, "connection")
424
+ if (connectionId === undefined || connectionId === "") return
425
+ finish(() => resolve({ connectionId }))
426
+ }, options.pollMs ?? 250)
427
+ })()
428
+ })
429
+ }
430
+
431
+ // --------------------------------------------------------------------------------------------------------- resume
432
+
433
+ /** Where pending authorisations are kept between page loads (the host's `localStorage`, or memory). */
434
+ export interface ResumeStorage {
435
+ getItem(key: string): string | null
436
+ setItem(key: string, value: string): void
437
+ removeItem(key: string): void
438
+ }
439
+
440
+ export interface PendingAuthorization<R> {
441
+ readonly id: string
442
+ readonly connectionId: string
443
+ readonly request: R
444
+ readonly createdAt: number
445
+ }
446
+
447
+ const memoryStorage = (): ResumeStorage => {
448
+ const map = new Map<string, string>()
449
+ return {
450
+ getItem: (key) => map.get(key) ?? null,
451
+ setItem: (key, value) => void map.set(key, value),
452
+ removeItem: (key) => void map.delete(key),
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Requests blocked on a Connection's authorisation (an agent's tool call refused because the server needs consent):
458
+ * `record` keeps one before consent starts (in `storage`, so a reload does not lose it), `consume` hands it back once
459
+ * (a second consume, from another tab or a repeated completion, gets nothing), and `resume` does the whole round:
460
+ * record, consent (any function that resolves once the Connection is authorised, `consentInPopup` say), consume, then
461
+ * run the request again exactly once. Pending entries older than `maxAgeMs` (default 15 minutes) are dropped.
462
+ */
463
+ export const authorizationResume = <R>(
464
+ options: {
465
+ readonly storage?: ResumeStorage | undefined
466
+ readonly key?: string | undefined
467
+ readonly maxAgeMs?: number | undefined
468
+ } = {},
469
+ ) => {
470
+ const storage = options.storage ?? memoryStorage()
471
+ const key = options.key ?? "eloxiv.pending-authorizations"
472
+ const maxAge = options.maxAgeMs ?? 15 * 60_000
473
+ const read = (): Array<PendingAuthorization<R>> => {
474
+ try {
475
+ const parsed = JSON.parse(storage.getItem(key) ?? "[]") as Array<PendingAuthorization<R>>
476
+ return Array.isArray(parsed) ? parsed.filter((p) => Date.now() - p.createdAt < maxAge) : []
477
+ } catch {
478
+ return []
479
+ }
480
+ }
481
+ const write = (entries: ReadonlyArray<PendingAuthorization<R>>) =>
482
+ entries.length === 0 ? storage.removeItem(key) : storage.setItem(key, JSON.stringify(entries))
483
+ const record = (connectionId: string, request: R): PendingAuthorization<R> => {
484
+ const entry = { id: nonce(), connectionId, request, createdAt: Date.now() }
485
+ write([...read(), entry])
486
+ return entry
487
+ }
488
+ const consume = (id: string): R | undefined => {
489
+ const entries = read()
490
+ const found = entries.find((e) => e.id === id)
491
+ if (found === undefined) return undefined
492
+ write(entries.filter((e) => e.id !== id))
493
+ return found.request
494
+ }
495
+ return {
496
+ record,
497
+ consume,
498
+ pending: (connectionId?: string) =>
499
+ read().filter((e) => connectionId === undefined || e.connectionId === connectionId),
500
+ resume: async <A>(
501
+ connectionId: string,
502
+ request: R,
503
+ authorize: () => Promise<unknown>,
504
+ run: (request: R) => Promise<A>,
505
+ ): Promise<A | undefined> => {
506
+ const entry = record(connectionId, request)
507
+ try {
508
+ await authorize()
509
+ } catch (error) {
510
+ consume(entry.id)
511
+ throw error
512
+ }
513
+ const again = consume(entry.id)
514
+ return again === undefined ? undefined : run(again)
515
+ },
516
+ }
517
+ }