@eloxiv/client 0.0.0-stage → 0.1.1

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 +1283 -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 +228 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +792 -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 +1442 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +844 -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/Chat.ts ADDED
@@ -0,0 +1,1150 @@
1
+ /**
2
+ * The headless chat SDK (decision 11): the state a chat screen, its approval and consent prompts and an inbox
3
+ * render, and the operations they run, with no view code. Any UI (the Foldkit shell's reference chat screen, or an
4
+ * app's own) keeps a `ChatState` in its model, feeds it what the replica and the run's event stream deliver, and
5
+ * renders what it derives; the guarantees that are hard to get right are here, once:
6
+ *
7
+ * - **One conversation at a time, its own rows only.** The transcript holds the conversation's stored messages (from
8
+ * the replica: `agent.messages`, already filtered to the person and the organisation they act in), in order, and
9
+ * the active run's streamed text; nothing of another conversation.
10
+ * - **Streamed text by model step, never twice.** A run's model steps each store one answer, in order. Streamed text
11
+ * names its step (`data.step`) and the model call of that step it comes from (`data.attempt`: a step's call is made
12
+ * again after a restart, from the start); each step's text shows until the replica holds that step's stored
13
+ * answer, which then replaces it, and a new call's text replaces the earlier call's. An earlier step's answer (a
14
+ * tool call) never hides a later step's text, and a later step's text that arrives before the earlier step's
15
+ * stored event (streamed text is pushed at once, stored events are read from the database) is kept.
16
+ * - **Events only from the run they belong to.** A run's events (consent asked and decided, the end) change the state
17
+ * only for the conversation's active run; a late event of a run since finished, or of another conversation's, is
18
+ * dropped. The stream's `run-finished` ends the run at once, whatever the replica still says.
19
+ * - **A send is one send.** The composer sends only a non-empty draft and only when nothing is in flight and no run
20
+ * is going (a run the kernel accepted counts from its answer, before the replica has it). Each send carries an
21
+ * idempotency key, its identity, kept outside any screen (`ChatSends.ts`: written ahead, per person and
22
+ * organisation, settled only by a definitive outcome for its key). A send whose answer was lost may have run: it
23
+ * is resent under its key; one the kernel could not confirm after that is kept, shown, until its receipt is found
24
+ * (`chatClient.lookup`) or the person discards it; one held for an approval or consent is kept, waiting. An answer
25
+ * counts only for the request it answers, and changes the conversation shown only if it came from it. A refusal
26
+ * is kept as its typed error, with the draft.
27
+ * - **Consent and approval are the person's.** Pending consent comes only from the run's `consent-required` events
28
+ * and leaves only on `consent-decided` (or the run's end); approvals come from the replica (`approvals.requests`).
29
+ * Deciding either is an action of the kernel's, which refuses an agent: this SDK never decides on its own. Each
30
+ * decision (and a cancel) carries a key of its own (the consent's or approval's id and the decision; the run's),
31
+ * the same on every retry, so a retry after a lost answer decides once.
32
+ * - **Nothing of the conversation outlives the session or the organisation.** The state is a value: a UI drops it
33
+ * (and its event stream, whose connection closes as soon as it is interrupted, even while silent) when the person
34
+ * signs out or switches organisation, and makes a new one. Outstanding sends are the exception, by design: they are
35
+ * the person's, kept in the outstanding store and fed back to the next state (`withOutstanding`).
36
+ */
37
+ import {
38
+ CLIENT_VERSION_HEADER,
39
+ decisionLabel,
40
+ EngineReadiness,
41
+ EntityReference,
42
+ IDEMPOTENCY_HEADER,
43
+ readableActionName,
44
+ RunDevice,
45
+ RunStatus,
46
+ type RunEvent,
47
+ } from "@eloxiv/contracts"
48
+ import { Duration, Effect, Schema, Stream } from "effect"
49
+ import { agentClient, AgentRequestError, type AbortSignalLike } from "./Agent.ts"
50
+ import { ChatError, isDefinitive, OutstandingSend, putSend, settleSend, type SendOutcome } from "./ChatSends.ts"
51
+
52
+ export * from "./ChatSends.ts"
53
+ /** What people see an action called, from its recorded title or its readable name (`@eloxiv/contracts`). */
54
+ export { actionLabel, decisionLabel, makeDecisionLabel, readableActionName } from "@eloxiv/contracts"
55
+ export * from "./ChatIntegrity.ts"
56
+
57
+ // -- State ----------------------------------------------------------------------------------------------------
58
+ //
59
+ // Sorting copies with `slice().sort()`, not `toSorted()`: Hermes (React Native) has no ES2023 array copying methods,
60
+ // and the React Native guard runs this module there (tools/react-native).
61
+
62
+ /** A stored message of a conversation, as the replica delivers it (`agent.messages`). */
63
+ export const ChatMessage = Schema.Struct({
64
+ id: Schema.String,
65
+ conversationId: Schema.String,
66
+ runId: Schema.NullOr(Schema.String),
67
+ seq: Schema.Number,
68
+ role: Schema.Literals(["user", "assistant", "tool", "summary"]),
69
+ text: Schema.String,
70
+ /** Set when the message left the conversation: compacted into a summary, or after a restored checkpoint (`restore:`). */
71
+ coveredBy: Schema.optionalKey(Schema.NullOr(Schema.String)),
72
+ })
73
+ export type ChatMessage = typeof ChatMessage.Type
74
+
75
+ /** A run of a conversation, as the replica delivers it (`agent.runs`). */
76
+ export const ChatRun = Schema.Struct({
77
+ id: Schema.String,
78
+ conversationId: Schema.String,
79
+ status: RunStatus,
80
+ error: Schema.NullOr(Schema.String),
81
+ createdAt: Schema.Number,
82
+ })
83
+ export type ChatRun = typeof ChatRun.Type
84
+
85
+ /** A tool call the run holds for the person's consent (from its `consent-required` event). */
86
+ export const PendingConsent = Schema.Struct({
87
+ consentId: Schema.String,
88
+ runId: Schema.String,
89
+ action: Schema.String,
90
+ /**
91
+ * What the person sees the action called: the event's `title` (the action's title as it was when the call was
92
+ * held), or, from a kernel that sends none, the action's readable name; a MAKE action's from its id alone
93
+ * (`decisionLabel`). Never the raw id.
94
+ */
95
+ title: Schema.String,
96
+ })
97
+ export type PendingConsent = typeof PendingConsent.Type
98
+
99
+ /** A send: its text, the conversation it was sent from (null for a new one) and its idempotency key. */
100
+ export const SendRequest = Schema.Struct({
101
+ text: Schema.String,
102
+ conversationId: Schema.NullOr(Schema.String),
103
+ key: Schema.String,
104
+ /** The paired device it runs on (none: the deployment's model). */
105
+ device: Schema.optionalKey(Schema.NullOr(RunDevice)),
106
+ })
107
+ export type SendRequest = typeof SendRequest.Type
108
+
109
+ /**
110
+ * Named context staged for the next send (a record a screen offered, a selection, a note): sent with it, below the
111
+ * text, then cleared. At most `CONTEXT_LIMIT` items and `CONTEXT_CHARS` characters in all.
112
+ */
113
+ export const StagedContext = Schema.Struct({
114
+ name: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(64)),
115
+ text: Schema.String.check(Schema.isMaxLength(4_000)),
116
+ /** The record it is about, if any (shown to the agent as a reference; the agent reads it through its tools). */
117
+ reference: Schema.optionalKey(EntityReference),
118
+ })
119
+ export type StagedContext = typeof StagedContext.Type
120
+ export const CONTEXT_LIMIT = 10
121
+ export const CONTEXT_CHARS = 16_000
122
+
123
+ export const Composer = Schema.Struct({
124
+ draft: Schema.String,
125
+ /**
126
+ * Where the next send runs: one of the person's paired devices (its harness, on their own subscription; the kernel
127
+ * asks the person's consent to send the turn there), or the deployment's model (none).
128
+ */
129
+ device: Schema.optionalKey(Schema.NullOr(RunDevice)),
130
+ /** Context staged for the next send (`stageContext`). */
131
+ context: Schema.optionalKey(Schema.Array(StagedContext)),
132
+ /** This state's send in flight (one at a time). */
133
+ sending: Schema.NullOr(SendRequest),
134
+ /**
135
+ * The person's sends in this organisation whose outcome is not settled, every conversation's: what the outstanding
136
+ * store keeps (`withOutstanding`), with this state's own changes.
137
+ */
138
+ outstanding: Schema.Array(OutstandingSend),
139
+ /** Why the shown conversation's last send failed, kept with the draft until the next send. */
140
+ error: Schema.NullOr(ChatError),
141
+ })
142
+ export type Composer = typeof Composer.Type
143
+
144
+ /** A model step's streamed text, not yet stored, and the model call it comes from (null: the stored text). */
145
+ export const StreamedStep = Schema.Struct({
146
+ step: Schema.Number,
147
+ attempt: Schema.NullOr(Schema.String),
148
+ text: Schema.String,
149
+ })
150
+ export type StreamedStep = typeof StreamedStep.Type
151
+
152
+ /** What the active run's stream delivered that the replica may not hold yet. */
153
+ export const Live = Schema.Struct({
154
+ runId: Schema.String,
155
+ /** The last stored event's sequence number seen: each stored event counts once. */
156
+ after: Schema.Number,
157
+ /** How many model steps the stream reported done (`model-step`): text that names no step is the next one's. */
158
+ steps: Schema.Number,
159
+ streamed: Schema.Array(StreamedStep),
160
+ })
161
+ export type Live = typeof Live.Type
162
+
163
+ export const ChatState = Schema.Struct({
164
+ /** The conversation shown; null for a new one (the first send starts it). */
165
+ conversationId: Schema.NullOr(Schema.String),
166
+ messages: Schema.Array(ChatMessage),
167
+ runs: Schema.Array(ChatRun),
168
+ /** The run a send started, until the replica has it. */
169
+ pendingRun: Schema.NullOr(ChatRun),
170
+ live: Schema.NullOr(Live),
171
+ /** Runs whose stream said they ended (`run-finished`), whatever the replica says yet. */
172
+ ended: Schema.Array(Schema.String),
173
+ consents: Schema.Array(PendingConsent),
174
+ composer: Composer,
175
+ /**
176
+ * Whether the agent can answer (`chatClient.readiness`, fed with `withEngine`): while the kernel says `missing` or
177
+ * `unavailable` the composer keeps its draft but does not send; `unknown` (not asked yet, or the probe failed)
178
+ * does not hold a send back, which the kernel then answers itself.
179
+ */
180
+ engine: EngineReadiness,
181
+ })
182
+ export type ChatState = typeof ChatState.Type
183
+
184
+ /** The engine before anyone asked: unknown, which holds nothing back. */
185
+ export const UNKNOWN_ENGINE: EngineReadiness = {
186
+ state: "unknown",
187
+ provider: null,
188
+ model: null,
189
+ detail: "Not asked yet",
190
+ }
191
+
192
+ /** A chat on `conversationId` (or a new conversation). */
193
+ export const initialChat = (conversationId: string | null = null): ChatState => ({
194
+ conversationId,
195
+ messages: [],
196
+ runs: [],
197
+ pendingRun: null,
198
+ live: null,
199
+ ended: [],
200
+ consents: [],
201
+ composer: { draft: "", sending: null, outstanding: [], error: null },
202
+ engine: UNKNOWN_ENGINE,
203
+ })
204
+
205
+ const ACTIVE: ReadonlySet<RunStatus> = new Set(["queued", "running", "waiting"])
206
+ /** How many runs whose stream ended are remembered (until the replica reports each ended). */
207
+ const ENDED_KEPT = 32
208
+
209
+ const known = (state: ChatState): ReadonlyArray<ChatRun> =>
210
+ state.pendingRun === null ? state.runs : [state.pendingRun, ...state.runs]
211
+
212
+ /** The conversation's run still going (queued, running or waiting for consent, and not ended by its stream). */
213
+ export const activeRun = (state: ChatState): ChatRun | undefined =>
214
+ known(state).find((run) => ACTIVE.has(run.status) && !state.ended.includes(run.id))
215
+
216
+ /** One line of the transcript: a stored message, or a model step's streamed text (`live`). */
217
+ export interface TranscriptEntry {
218
+ readonly id: string
219
+ readonly role: ChatMessage["role"]
220
+ readonly text: string
221
+ readonly runId: string | null
222
+ readonly live: boolean
223
+ /**
224
+ * The kernel's challenge of the run's answer (its final-answer check: a `user` message the person did not write,
225
+ * id `<run>:check:<step>`), to show as the kernel's, not the person's.
226
+ */
227
+ readonly check?: boolean
228
+ }
229
+
230
+ const CHECK_MESSAGE = /:check:\d+$/u
231
+
232
+ /**
233
+ * What a transcript shows: the conversation's stored messages in order (an answer with no text, a tool call, is not a
234
+ * line), then each model step's streamed text the replica does not hold the stored answer of yet.
235
+ */
236
+ export const transcript = (state: ChatState): ReadonlyArray<TranscriptEntry> => {
237
+ const stored = state.messages
238
+ // (A message after a restored checkpoint left the conversation; compacted ones stay in its history.)
239
+ .filter(
240
+ (m) => m.role !== "summary" && !(m.role === "assistant" && m.text === "") && !m.coveredBy?.startsWith("restore:"),
241
+ )
242
+ .map((m): TranscriptEntry =>
243
+ m.role === "user" && CHECK_MESSAGE.test(m.id)
244
+ ? { id: m.id, role: m.role, text: m.text, runId: m.runId, live: false, check: true }
245
+ : { id: m.id, role: m.role, text: m.text, runId: m.runId, live: false },
246
+ )
247
+ const live = state.live
248
+ if (live === null) return stored
249
+ // The run's model steps each store one answer, in order: the replica holds the first `answered` steps'.
250
+ const answered = state.messages.filter((m) => m.runId === live.runId && m.role === "assistant").length
251
+ const streaming = live.streamed
252
+ .filter((s) => s.step >= answered && s.text !== "")
253
+ .slice()
254
+ .sort((a, b) => a.step - b.step)
255
+ .map((s): TranscriptEntry => ({
256
+ id: `live:${live.runId}:${s.step}`,
257
+ role: "assistant",
258
+ text: s.text,
259
+ runId: live.runId,
260
+ live: true,
261
+ }))
262
+ return [...stored, ...streaming]
263
+ }
264
+
265
+ /**
266
+ * An outstanding send as this state sees it: as kept, but a `sending` one this state has no request in flight for
267
+ * (an earlier screen's or page's, whose answer it will never hear) is `uncertain`, and may have run (`doubtful`).
268
+ */
269
+ const seenBy = (state: ChatState, send: OutstandingSend): OutstandingSend =>
270
+ send.state === "sending" && state.composer.sending?.key !== send.key
271
+ ? { ...send, state: "uncertain", doubtful: true }
272
+ : send
273
+
274
+ /** The shown conversation's outstanding sends, as this state sees them (see `seenBy`). */
275
+ export const outstandingSends = (state: ChatState): ReadonlyArray<OutstandingSend> =>
276
+ state.composer.outstanding
277
+ .filter((send) => send.conversationId === state.conversationId)
278
+ .map((send) => seenBy(state, send))
279
+
280
+ /** The shown conversation's send whose answer was lost, which the next send resends (under its key). */
281
+ export const unresolvedSend = (state: ChatState): OutstandingSend | undefined =>
282
+ outstandingSends(state).find((send) => send.state === "uncertain")
283
+
284
+ /**
285
+ * Whether the agent is known not to be able to answer: the kernel said its model is `missing` (not set up) or
286
+ * `unavailable`. A screen shows `state.engine.detail` and keeps the composer for drafting.
287
+ */
288
+ export const engineBlocked = (state: ChatState): boolean =>
289
+ state.engine.state === "missing" || state.engine.state === "unavailable"
290
+
291
+ /**
292
+ * Whether the composer may send now: the engine not known to be blocked, nothing in flight, no run going, and a
293
+ * non-empty draft or an unresolved send to resend.
294
+ */
295
+ export const canSend = (state: ChatState): boolean =>
296
+ !engineBlocked(state) &&
297
+ state.composer.sending === null &&
298
+ activeRun(state) === undefined &&
299
+ (state.composer.draft.trim() !== "" || unresolvedSend(state) !== undefined)
300
+
301
+ // -- Transitions ----------------------------------------------------------------------------------------------
302
+
303
+ /**
304
+ * Show another conversation (or a new one): a fresh state, nothing of the previous one kept but the composer (its
305
+ * draft, the send in flight and the unresolved ones, each still its own conversation's).
306
+ */
307
+ export const openConversation = (state: ChatState, conversationId: string | null): ChatState =>
308
+ state.conversationId === conversationId
309
+ ? state
310
+ : {
311
+ ...initialChat(conversationId),
312
+ ended: state.ended,
313
+ composer: { ...state.composer, error: null },
314
+ engine: state.engine,
315
+ }
316
+
317
+ /** The replica's messages (any conversation's): the transcript keeps this conversation's, in order. */
318
+ export const withMessages = (state: ChatState, rows: ReadonlyArray<ChatMessage>): ChatState => {
319
+ if (state.conversationId === null) return state.messages.length === 0 ? state : { ...state, messages: [] }
320
+ const messages = rows
321
+ .filter((m) => m.conversationId === state.conversationId)
322
+ .slice()
323
+ .sort((a, b) => a.seq - b.seq)
324
+ return { ...state, messages }
325
+ }
326
+
327
+ /**
328
+ * The replica's runs (any conversation's): the conversation's, newest first. A run the replica reports ended takes
329
+ * its streamed text (its stored answers are in the replica by then) and its pending consents with it.
330
+ */
331
+ export const withRuns = (state: ChatState, rows: ReadonlyArray<ChatRun>): ChatState => {
332
+ const runs = state.conversationId === null ? [] : rows.filter((r) => r.conversationId === state.conversationId)
333
+ const sorted = runs.slice().sort((a, b) => b.createdAt - a.createdAt)
334
+ // The run a send started counts until the replica has it.
335
+ const pending = state.pendingRun
336
+ const pendingRun = pending !== null && !sorted.some((run) => run.id === pending.id) ? pending : null
337
+ // A run the replica reports ended needs its stream's word no longer.
338
+ const ended = state.ended.filter((id) => !rows.some((r) => r.id === id && !ACTIVE.has(r.status)))
339
+ const next = { ...state, runs: sorted, pendingRun, ended }
340
+ const active = activeRun(next)
341
+ const live = state.live
342
+ const liveRun = live === null ? undefined : known(next).find((run) => run.id === live.runId)
343
+ return {
344
+ ...next,
345
+ live: liveRun !== undefined && ACTIVE.has(liveRun.status) ? live : null,
346
+ consents: state.consents.filter((c) => c.runId === active?.id),
347
+ }
348
+ }
349
+
350
+ /** `streamed` with `text` appended to `step`'s, or in place of it when it is another model call's (`attempt`). */
351
+ const appended = (
352
+ streamed: ReadonlyArray<StreamedStep>,
353
+ step: number,
354
+ attempt: string | null,
355
+ text: string,
356
+ ): ReadonlyArray<StreamedStep> =>
357
+ streamed.some((s) => s.step === step)
358
+ ? streamed.map((s) =>
359
+ s.step !== step ? s : s.attempt === attempt ? { ...s, text: s.text + text } : { step, attempt, text },
360
+ )
361
+ : [...streamed, { step, attempt, text }]
362
+
363
+ const stepOf = (value: unknown): number | undefined =>
364
+ typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined
365
+
366
+ /**
367
+ * One event of the active run's stream (the client SDK names each event's run, streamed text included). Only the
368
+ * conversation's active run counts; stored events count once (by sequence number); streamed text is its step's.
369
+ */
370
+ export const withEvent = (state: ChatState, event: RunEvent): ChatState => {
371
+ const active = activeRun(state)
372
+ if (active === undefined || active.id !== event.runId) return state
373
+ const live: Live =
374
+ state.live?.runId === event.runId ? state.live : { runId: event.runId, after: -1, steps: 0, streamed: [] }
375
+ const data = (event.data ?? {}) as Record<string, unknown>
376
+ if (event.type === "text-delta") {
377
+ const text = typeof data["delta"] === "string" ? data["delta"] : ""
378
+ // Text that names no step (an older kernel) is the step after the last one the stream reported done.
379
+ const step = stepOf(data["step"]) ?? live.steps
380
+ // A step the stream reported done has its stored text already.
381
+ if (text === "" || step < live.steps) return state
382
+ const attempt = typeof data["attempt"] === "string" ? data["attempt"] : null
383
+ return { ...state, live: { ...live, streamed: appended(live.streamed, step, attempt, text) } }
384
+ }
385
+ if (event.seq <= live.after) return state
386
+ const seen: Live = { ...live, after: event.seq }
387
+ switch (event.type) {
388
+ case "consent-required":
389
+ return typeof data["consentId"] === "string" && !state.consents.some((c) => c.consentId === data["consentId"])
390
+ ? {
391
+ ...state,
392
+ live: seen,
393
+ consents: [
394
+ ...state.consents,
395
+ {
396
+ consentId: data["consentId"],
397
+ runId: event.runId,
398
+ action: typeof data["action"] === "string" ? data["action"] : "",
399
+ // A MAKE action's label comes from its id, whatever title the event carries (one recorded before).
400
+ title: decisionLabel(
401
+ typeof data["action"] === "string" ? data["action"] : "",
402
+ typeof data["title"] === "string" ? data["title"] : null,
403
+ ),
404
+ },
405
+ ],
406
+ }
407
+ : { ...state, live: seen }
408
+ case "consent-decided":
409
+ return { ...state, live: seen, consents: state.consents.filter((c) => c.consentId !== data["consentId"]) }
410
+ case "model-step": {
411
+ // The step is done: its text is the stored one (whatever of it streamed, or none).
412
+ const step = stepOf(data["step"]) ?? live.steps
413
+ const text = typeof data["text"] === "string" ? data["text"] : ""
414
+ const streamed = [...seen.streamed.filter((s) => s.step !== step), { step, attempt: null, text }]
415
+ return { ...state, live: { ...seen, steps: Math.max(seen.steps, step + 1), streamed } }
416
+ }
417
+ case "reply-discarded": {
418
+ // The step's reply arrived after the run was cancelled: never the run's, so its streamed text goes.
419
+ const step = stepOf(data["step"])
420
+ return step === undefined
421
+ ? { ...state, live: seen }
422
+ : { ...state, live: { ...seen, streamed: seen.streamed.filter((s) => s.step !== step) } }
423
+ }
424
+ case "run-finished":
425
+ // Ended: it no longer holds the composer, whatever the replica says yet; its text stays until the replica
426
+ // holds its answers.
427
+ return {
428
+ ...state,
429
+ live: seen,
430
+ consents: [],
431
+ ended: [...state.ended.filter((id) => id !== event.runId), event.runId].slice(-ENDED_KEPT),
432
+ }
433
+ default:
434
+ return { ...state, live: seen }
435
+ }
436
+ }
437
+
438
+ /** What the kernel (or a failed probe) said about the agent's readiness (`chatClient.readiness`). */
439
+ export const withEngine = (state: ChatState, engine: EngineReadiness): ChatState => ({ ...state, engine })
440
+
441
+ /** The person types (also while the engine is not set up: drafting never waits for it). */
442
+ export const edit = (state: ChatState, draft: string): ChatState => ({
443
+ ...state,
444
+ composer: { ...state.composer, draft },
445
+ })
446
+
447
+ /**
448
+ * The person sends. The shown conversation's unresolved send, if any, is resent under its own key (with its own
449
+ * text); otherwise the draft is sent under `key` (fresh for each new send). Nothing happens unless the composer may
450
+ * send. The returned request is what to hand `ChatClient.send`, and `send` what to record in the outstanding store
451
+ * before it leaves.
452
+ */
453
+ /** Where the next send runs: `device`, one of the person's paired devices, or the deployment's model (null). */
454
+ export const chooseDevice = (state: ChatState, device: RunDevice | null): ChatState => ({
455
+ ...state,
456
+ composer: { ...state.composer, device },
457
+ })
458
+
459
+ export const submit = (
460
+ state: ChatState,
461
+ key: string,
462
+ ): { readonly state: ChatState; readonly request?: ChatSendRequest; readonly send?: OutstandingSend } => {
463
+ if (!canSend(state)) return { state }
464
+ const retry = unresolvedSend(state)
465
+ const send: OutstandingSend =
466
+ retry === undefined
467
+ ? {
468
+ text: withContext(state.composer.draft.trim(), state.composer.context ?? []),
469
+ conversationId: state.conversationId,
470
+ key,
471
+ state: "sending",
472
+ doubtful: false,
473
+ waitingOn: null,
474
+ ...(state.composer.device == null ? {} : { device: state.composer.device }),
475
+ }
476
+ : // A retry is the same send: where it runs too.
477
+ { ...retry, state: "sending" }
478
+ return {
479
+ state: {
480
+ ...state,
481
+ composer: {
482
+ ...state.composer,
483
+ sending: {
484
+ text: send.text,
485
+ conversationId: send.conversationId,
486
+ key: send.key,
487
+ ...(send.device == null ? {} : { device: send.device }),
488
+ },
489
+ outstanding: putSend(state.composer.outstanding, send),
490
+ error: null,
491
+ },
492
+ },
493
+ request: {
494
+ text: send.text,
495
+ conversationId: send.conversationId,
496
+ idempotencyKey: send.key,
497
+ ...(send.device == null ? {} : { device: send.device }),
498
+ },
499
+ send,
500
+ }
501
+ }
502
+
503
+ /** The text a send carries: the draft, then each staged item under its name (and its record, if any). */
504
+ const withContext = (draft: string, context: ReadonlyArray<StagedContext>) =>
505
+ context.length === 0
506
+ ? draft
507
+ : `${draft}\n\n${context
508
+ .map(
509
+ (item) =>
510
+ `[Context: ${item.name}${item.reference === undefined ? "" : ` (${item.reference.module}.${item.reference.entity} "${item.reference.id}")`}]\n${item.text}`,
511
+ )
512
+ .join("\n\n")}`
513
+
514
+ /** The draft once `send` went: cleared if it is still what was sent (its text, the context aside). */
515
+ const draftAfter = (draft: string, send: { readonly text: string }) =>
516
+ draft.trim() === send.text || send.text.startsWith(`${draft.trim()}\n\n[Context: `) ? "" : draft
517
+
518
+ /** The state with `outcome` known for the send under `key`: the same state when nothing changed. */
519
+ const settledIn = (state: ChatState, key: string, outcome: SendOutcome): ChatState => {
520
+ const outstanding = settleSend(state.composer.outstanding, key, outcome)
521
+ return outstanding === state.composer.outstanding ? state : { ...state, composer: { ...state.composer, outstanding } }
522
+ }
523
+
524
+ /**
525
+ * The send under `key` was accepted: its conversation (a new one, for a first send) and its run, the draft cleared.
526
+ * It settles the send whatever made the request; it changes what is shown only for this state's request, and only if
527
+ * it was sent from the conversation shown.
528
+ */
529
+ export const sent = (
530
+ state: ChatState,
531
+ key: string,
532
+ result: { readonly conversationId: string; readonly runId: string },
533
+ ): ChatState => {
534
+ const after = settledIn(state, key, { kind: "sent" })
535
+ const send = state.composer.sending
536
+ if (send === null || send.key !== key) return after
537
+ const composer = { ...after.composer, sending: null }
538
+ if (send.conversationId !== state.conversationId) return { ...after, composer }
539
+ return {
540
+ ...after,
541
+ conversationId: result.conversationId,
542
+ // Until the replica has the run, it is known to be queued: the composer waits for it.
543
+ pendingRun: state.runs.some((r) => r.id === result.runId)
544
+ ? null
545
+ : { id: result.runId, conversationId: result.conversationId, status: "queued", error: null, createdAt: 0 },
546
+ live: { runId: result.runId, after: -1, steps: 0, streamed: [] },
547
+ // The staged context went with the send.
548
+ composer: {
549
+ ...composer,
550
+ draft: draftAfter(state.composer.draft, send),
551
+ ...(composer.context === undefined ? {} : { context: [] }),
552
+ error: null,
553
+ },
554
+ }
555
+ }
556
+
557
+ // -- Context and intents ----------------------------------------------------------------------------------------
558
+
559
+ /** Stage named context for the next send (replacing an item of the same name), within the bounds. */
560
+ export const stageContext = (
561
+ state: ChatState,
562
+ item: StagedContext,
563
+ ): { readonly state: ChatState; readonly staged: boolean; readonly reason?: string } => {
564
+ const others = (state.composer.context ?? []).filter((c) => c.name !== item.name)
565
+ if (others.length + 1 > CONTEXT_LIMIT) return { state, staged: false, reason: `At most ${CONTEXT_LIMIT} items` }
566
+ const chars = others.reduce((sum, c) => sum + c.text.length, item.text.length)
567
+ if (chars > CONTEXT_CHARS) return { state, staged: false, reason: `At most ${CONTEXT_CHARS} characters of context` }
568
+ return { state: { ...state, composer: { ...state.composer, context: [...others, item] } }, staged: true }
569
+ }
570
+
571
+ /** Take a staged item back. */
572
+ export const unstageContext = (state: ChatState, name: string): ChatState => ({
573
+ ...state,
574
+ composer: { ...state.composer, context: (state.composer.context ?? []).filter((c) => c.name !== name) },
575
+ })
576
+
577
+ /** What is staged for the next send. */
578
+ export const stagedContext = (state: ChatState): ReadonlyArray<StagedContext> => state.composer.context ?? []
579
+
580
+ /** Put a record's reference into the draft where the person is writing (at the end), as the agent reads one. */
581
+ export const insertReference = (state: ChatState, reference: EntityReference, label?: string): ChatState => {
582
+ const token = `[${label ?? reference.id}](${reference.module}.${reference.entity} "${reference.id}")`
583
+ const draft = state.composer.draft
584
+ return edit(state, draft === "" || /\s$/.test(draft) ? `${draft}${token} ` : `${draft} ${token} `)
585
+ }
586
+
587
+ /**
588
+ * What another surface asks of the chat (a screen's "ask the agent about this", a command, a deep link): fill the
589
+ * draft (`prefill`; never over what the person is typing unless `replace`), fill it and send (`submit`), open a
590
+ * conversation (`open`), or stage context (`stage`). Each has an id, so its outcome can be reported back.
591
+ */
592
+ export type ChatIntent =
593
+ | { readonly id: string; readonly kind: "prefill"; readonly text: string; readonly replace?: boolean }
594
+ | { readonly id: string; readonly kind: "submit"; readonly text: string }
595
+ | { readonly id: string; readonly kind: "open"; readonly conversationId: string | null }
596
+ | { readonly id: string; readonly kind: "stage"; readonly context: StagedContext }
597
+
598
+ /** An intent's outcome, for its sender: applied, or not and why. */
599
+ export interface IntentOutcome {
600
+ readonly id: string
601
+ readonly applied: boolean
602
+ readonly reason?: string
603
+ }
604
+
605
+ /**
606
+ * Apply an intent. `submit: true` asks the UI to send now (`submit` with a fresh key), which it does only while
607
+ * the composer may send; a `submit` intent while a send or run is going is not applied, so nothing is sent twice.
608
+ */
609
+ export const applyIntent = (
610
+ state: ChatState,
611
+ intent: ChatIntent,
612
+ ): { readonly state: ChatState; readonly outcome: IntentOutcome; readonly submit?: true } => {
613
+ switch (intent.kind) {
614
+ case "prefill": {
615
+ if (state.composer.draft.trim() !== "" && intent.replace !== true) {
616
+ return { state, outcome: { id: intent.id, applied: false, reason: "The person is writing a message" } }
617
+ }
618
+ return { state: edit(state, intent.text), outcome: { id: intent.id, applied: true } }
619
+ }
620
+ case "submit": {
621
+ const filled = edit(state, intent.text)
622
+ if (intent.text.trim() === "" || !canSend(filled)) {
623
+ return { state, outcome: { id: intent.id, applied: false, reason: "The chat cannot send now" } }
624
+ }
625
+ return { state: filled, outcome: { id: intent.id, applied: true }, submit: true }
626
+ }
627
+ case "open":
628
+ return { state: openConversation(state, intent.conversationId), outcome: { id: intent.id, applied: true } }
629
+ case "stage": {
630
+ const staged = stageContext(state, intent.context)
631
+ return {
632
+ state: staged.state,
633
+ outcome: staged.staged
634
+ ? { id: intent.id, applied: true }
635
+ : { id: intent.id, applied: false, reason: staged.reason ?? "" },
636
+ }
637
+ }
638
+ }
639
+ }
640
+
641
+ /**
642
+ * The send under `key` ran before: a replay of its receipt (an answer to a retry), or its receipt found by looking its
643
+ * key up (`ran`). Its run and conversation reach the state through the replica, as any run does.
644
+ */
645
+ const ranBefore = (state: ChatState, key: string, outcome: SendOutcome): ChatState => {
646
+ const known = state.composer.outstanding.find((s) => s.key === key)
647
+ const after = settledIn(state, key, outcome)
648
+ const send = state.composer.sending?.key === key ? state.composer.sending : known
649
+ if (send === undefined) return after
650
+ const composer = state.composer.sending?.key === key ? { ...after.composer, sending: null } : after.composer
651
+ if (send.conversationId !== state.conversationId) return { ...after, composer }
652
+ return { ...after, composer: { ...composer, draft: draftAfter(state.composer.draft, send), error: null } }
653
+ }
654
+
655
+ /** The send under `key` was a replay of one already made under that key (its first answer was lost): it ran then. */
656
+ export const replayed = (state: ChatState, key: string): ChatState => ranBefore(state, key, { kind: "replayed" })
657
+
658
+ /**
659
+ * What looking up the send under `key` found: its receipt (it ran: settled), or none (nothing is known yet: kept as it
660
+ * was, since a send still in flight commits its receipt with it).
661
+ */
662
+ export const lookedUp = (state: ChatState, key: string, ran: boolean): ChatState =>
663
+ ran ? ranBefore(state, key, { kind: "ran" }) : state
664
+
665
+ /** The person gives up on an outstanding send (one that could not be confirmed, or waits on someone). */
666
+ export const discard = (state: ChatState, key: string): ChatState => settledIn(state, key, { kind: "discarded" })
667
+
668
+ /**
669
+ * An attempt of the send under `key` failed (see `settleSend`): refused at its first and only attempt, it did not run
670
+ * and goes; its answer lost, it is resent under its key by the next send from its conversation; refused after that,
671
+ * it is kept as could not confirm; held for an approval or consent, it waits. The error shows (with the draft) only
672
+ * under the conversation it was sent from.
673
+ */
674
+ export const sendFailed = (state: ChatState, key: string, error: ChatError): ChatState => {
675
+ const after = settledIn(state, key, { kind: "failed", error })
676
+ const send = state.composer.sending
677
+ if (send === null || send.key !== key) return after
678
+ return {
679
+ ...after,
680
+ composer: {
681
+ ...after.composer,
682
+ sending: null,
683
+ error: send.conversationId === state.conversationId ? error : after.composer.error,
684
+ },
685
+ }
686
+ }
687
+
688
+ /**
689
+ * The person's outstanding sends in this organisation, as the outstanding store has them now (it outlives screens):
690
+ * they replace the state's, but for this state's own send in flight, which stays while its request is out.
691
+ */
692
+ export const withOutstanding = (state: ChatState, sends: ReadonlyArray<OutstandingSend>): ChatState => {
693
+ const sending = state.composer.sending
694
+ const own = sending === null ? undefined : state.composer.outstanding.find((s) => s.key === sending.key)
695
+ const outstanding = own !== undefined && !sends.some((s) => s.key === own.key) ? [...sends, own] : sends
696
+ return { ...state, composer: { ...state.composer, outstanding } }
697
+ }
698
+
699
+ // -- Approvals and the inbox ------------------------------------------------------------------------------------
700
+
701
+ /** An approval request as the replica delivers it (`approvals.requests`). */
702
+ export const ApprovalItem = Schema.Struct({
703
+ id: Schema.String,
704
+ requesterId: Schema.String,
705
+ action: Schema.String,
706
+ /** What people see the action called, as recorded with the request (absent from an older kernel's rows). */
707
+ title: Schema.optionalKey(Schema.NullOr(Schema.String)),
708
+ status: Schema.Literals(["pending", "approved", "rejected", "expired"]),
709
+ createdAt: Schema.Number,
710
+ })
711
+ export type ApprovalItem = typeof ApprovalItem.Type
712
+
713
+ /**
714
+ * What a prompt calls an approval request's action: its recorded title, or its readable name; a MAKE action's from its
715
+ * id alone (`decisionLabel`), never a stored title. Never the raw id.
716
+ */
717
+ export const approvalLabel = (item: Pick<ApprovalItem, "action" | "title">): string =>
718
+ decisionLabel(item.action, item.title)
719
+
720
+ /**
721
+ * What approval prompts show: pending requests someone else made that the person may decide (the replica holds
722
+ * only the ones they made or may decide), and their own still waiting.
723
+ */
724
+ export const approvals = (rows: ReadonlyArray<ApprovalItem>, userId: string) => {
725
+ const pending = rows
726
+ .filter((r) => r.status === "pending")
727
+ .slice()
728
+ .sort((a, b) => a.createdAt - b.createdAt)
729
+ return {
730
+ toDecide: pending.filter((r) => r.requesterId !== userId),
731
+ waiting: pending.filter((r) => r.requesterId === userId),
732
+ }
733
+ }
734
+
735
+ /**
736
+ * A work item as the replica delivers it (`inbox.items`): its title, state, when it was raised, and where it comes
737
+ * from (the module's `source`, the record it links to, the view that shows that record, when the source names one),
738
+ * who it is assigned to and when it is due.
739
+ */
740
+ export const InboxItem = Schema.Struct({
741
+ id: Schema.String,
742
+ title: Schema.String,
743
+ state: Schema.String,
744
+ createdAt: Schema.Number,
745
+ source: Schema.optionalKey(Schema.String),
746
+ linkId: Schema.optionalKey(Schema.String),
747
+ view: Schema.optionalKey(Schema.NullOr(Schema.String)),
748
+ assigneeUserId: Schema.optionalKey(Schema.NullOr(Schema.String)),
749
+ dueAt: Schema.optionalKey(Schema.NullOr(Schema.Number)),
750
+ })
751
+ export type InboxItem = typeof InboxItem.Type
752
+
753
+ /** The inbox: items still to act on (open, in progress, waiting), newest first. */
754
+ export const openItems = (rows: ReadonlyArray<InboxItem>): ReadonlyArray<InboxItem> =>
755
+ rows
756
+ .filter((r) => r.state !== "done" && r.state !== "dismissed")
757
+ .slice()
758
+ .sort((a, b) => b.createdAt - a.createdAt)
759
+
760
+ /** What a person does with a work item: take it, finish it, or close it without doing it (`inbox.<step>`). */
761
+ export const WorkItemStep = Schema.Literals(["claim", "complete", "dismiss"])
762
+ export type WorkItemStep = typeof WorkItemStep.Type
763
+
764
+ /**
765
+ * The steps open to the person on an item: claim one not yet claimed (or claimed by someone else of their group),
766
+ * complete or dismiss one they may act on. The kernel's policy decides; this only offers what it would allow.
767
+ */
768
+ export const stepsFor = (item: InboxItem, userId: string): ReadonlyArray<WorkItemStep> =>
769
+ item.state === "done" || item.state === "dismissed"
770
+ ? []
771
+ : item.state === "in_progress" && item.assigneeUserId === userId
772
+ ? ["complete", "dismiss"]
773
+ : ["claim", "complete", "dismiss"]
774
+
775
+ // -- Words for people -------------------------------------------------------------------------------------------
776
+
777
+ /**
778
+ * A catalogue of what to tell people, one per locale, the app's own entries over these defaults (English). `{message}`
779
+ * is the error's own message, `{action}` a tool's label, `{task}` a delegated task.
780
+ */
781
+ export type ChatCatalog = Readonly<Record<string, string>>
782
+
783
+ export const CHAT_CATALOG_EN: ChatCatalog = {
784
+ "error.NetworkError": "The app could not be reached. Check the connection and try again.",
785
+ "error.Timeout": "No answer came back in time. It may still have been sent; it is kept and will be checked.",
786
+ "error.Unauthenticated": "Your session has ended. Sign in again.",
787
+ "error.Forbidden": "You are not allowed to do that here.",
788
+ "error.InvalidInput": "That could not be sent: {message}",
789
+ "error.ClientOutdated": "This version of the app is out of date. Reload to continue.",
790
+ "error.BudgetExceeded": "The agent has used its budget for now.",
791
+ "error.ModelUnavailable": "The agent's model is not available right now.",
792
+ "error.ApprovalRequired": "This waits for an approval.",
793
+ "error.ConsentRequired": "This waits for your consent.",
794
+ "error.default": "Something went wrong: {message}",
795
+ "tool.running": "Running {action}",
796
+ "tool.done": "{action}",
797
+ "tool.failed": "{action} failed",
798
+ "tool.consent": "{action} waits for your consent",
799
+ "tool.delegated": "Working on: {task}",
800
+ }
801
+
802
+ const fill = (template: string, values: Readonly<Record<string, string>>) =>
803
+ template.replace(/\{(\w+)\}/g, (whole, name: string) => values[name] ?? whole)
804
+
805
+ /** What to tell the person about a chat error, from the catalogue (the app's locale's, over the defaults). */
806
+ export const chatErrorMessage = (error: ChatError, catalog: ChatCatalog = {}): string => {
807
+ const entry =
808
+ catalog[`error.${error._tag}`] ??
809
+ CHAT_CATALOG_EN[`error.${error._tag}`] ??
810
+ catalog["error.default"] ??
811
+ CHAT_CATALOG_EN["error.default"]!
812
+ return fill(entry, { message: error.message === "" ? error._tag : error.message })
813
+ }
814
+
815
+ /** One tool call of a run, as a UI lists it. */
816
+ export interface ToolActivity {
817
+ readonly toolCallId: string
818
+ readonly toolName: string
819
+ readonly state: "running" | "done" | "failed" | "consent" | "delegated"
820
+ /** The words to show (from the catalogue and `labels`). */
821
+ readonly label: string
822
+ readonly error?: string
823
+ /** For a delegation: the child run doing the task. */
824
+ readonly childRunId?: string
825
+ }
826
+
827
+ /**
828
+ * A run's tool calls from its events, in order, each with its state and words: `labels` names tools for people (by the
829
+ * tool's name, `notebook_write`, the agent's), falling back to the name. A delegation shows as one line with its task,
830
+ * not as a tool running (the child run's own calls are the child's).
831
+ */
832
+ export const toolActivity = (
833
+ events: ReadonlyArray<RunEvent>,
834
+ options: { readonly labels?: Readonly<Record<string, string>>; readonly catalog?: ChatCatalog } = {},
835
+ ): ReadonlyArray<ToolActivity> => {
836
+ const words = (key: string, values: Readonly<Record<string, string>>) =>
837
+ fill(options.catalog?.[key] ?? CHAT_CATALOG_EN[key]!, values)
838
+ const calls = new Map<string, ToolActivity>()
839
+ /** The title and action an earlier event of the same call carried: a later event that omits them keeps them. */
840
+ const named = new Map<string, { title?: string; action?: string }>()
841
+ for (const event of events) {
842
+ const data = (event.data ?? {}) as Record<string, unknown>
843
+ const id = typeof data["toolCallId"] === "string" ? data["toolCallId"] : undefined
844
+ if (id === undefined) continue
845
+ const known = calls.get(id)
846
+ const toolName = typeof data["toolName"] === "string" ? data["toolName"] : (known?.toolName ?? "")
847
+ const earlier = named.get(id) ?? {}
848
+ const title = typeof data["title"] === "string" && data["title"] !== "" ? data["title"] : earlier.title
849
+ const actionName = typeof data["action"] === "string" && data["action"] !== "" ? data["action"] : earlier.action
850
+ named.set(id, {
851
+ ...(title === undefined ? {} : { title }),
852
+ ...(actionName === undefined ? {} : { action: actionName }),
853
+ })
854
+ // The app's own label for the tool, else the action's title (this event's or an earlier one's of the call: the
855
+ // kernel sends it on tool results and consent requests), else the action's readable name (an older kernel's
856
+ // events), else the tool's name.
857
+ // A MAKE action's label is computed from its id: the module's own title is never shown for it.
858
+ const action =
859
+ options.labels?.[toolName] ??
860
+ (actionName?.startsWith("mk_") === true
861
+ ? decisionLabel(actionName)
862
+ : (title ?? (actionName === undefined ? toolName : readableActionName(actionName))))
863
+ switch (event.type) {
864
+ case "tool-call":
865
+ if (known === undefined) {
866
+ calls.set(id, { toolCallId: id, toolName, state: "running", label: words("tool.running", { action }) })
867
+ }
868
+ break
869
+ case "tool-result": {
870
+ if (known?.state === "delegated") break
871
+ const failed = data["ok"] === false
872
+ calls.set(id, {
873
+ toolCallId: id,
874
+ toolName,
875
+ state: failed ? "failed" : "done",
876
+ label: words(failed ? "tool.failed" : "tool.done", { action }),
877
+ ...(failed && typeof data["error"] === "string" ? { error: data["error"] } : {}),
878
+ })
879
+ break
880
+ }
881
+ case "consent-required":
882
+ calls.set(id, { toolCallId: id, toolName, state: "consent", label: words("tool.consent", { action }) })
883
+ break
884
+ case "delegated":
885
+ calls.set(id, {
886
+ toolCallId: id,
887
+ toolName,
888
+ state: "delegated",
889
+ label: words("tool.delegated", { task: typeof data["task"] === "string" ? data["task"] : action }),
890
+ ...(typeof data["childRunId"] === "string" ? { childRunId: data["childRunId"] } : {}),
891
+ })
892
+ break
893
+ }
894
+ }
895
+ return [...calls.values()]
896
+ }
897
+
898
+ // -- Operations -----------------------------------------------------------------------------------------------
899
+
900
+ /** What a send answers: the conversation and run it started, or (a retry of a send already made) a replay. */
901
+ export type ChatSendResult =
902
+ | { readonly kind: "sent"; readonly conversationId: string; readonly runId: string }
903
+ | { readonly kind: "replayed"; readonly invocationId: string }
904
+
905
+ export interface ChatSendRequest {
906
+ readonly text: string
907
+ readonly conversationId: string | null
908
+ readonly idempotencyKey: string
909
+ /** The person's paired device the run executes on (none: the deployment's model). */
910
+ readonly device?: RunDevice | null | undefined
911
+ }
912
+
913
+ export interface ChatClientOptions {
914
+ readonly baseUrl: string
915
+ /** The session's bearer token, read when a request is made. */
916
+ readonly token: () => string | undefined
917
+ /** The organisation the chat acts in. */
918
+ readonly orgId: string
919
+ readonly clientVersion?: string | undefined
920
+ /** How long a send or a decision waits for its answer before it counts as lost (`Timeout`; 30 s). */
921
+ readonly sendTimeout?: Duration.Input | undefined
922
+ /**
923
+ * How long the run's event stream waits before it reconnects after its connection dropped or failed without a
924
+ * definitive answer: `base` at first, doubling to `max` (0.5 s and 10 s). A connection that delivered events starts
925
+ * the count again.
926
+ */
927
+ readonly reconnect?: { readonly base: Duration.Input; readonly max: Duration.Input } | undefined
928
+ }
929
+
930
+ const chatError = (error: unknown): ChatError => {
931
+ if (!(error instanceof AgentRequestError))
932
+ return { _tag: "NetworkError", message: error instanceof Error ? error.message : String(error), status: 0 }
933
+ const fields = error.error
934
+ return {
935
+ _tag: fields._tag,
936
+ message: typeof fields["message"] === "string" ? fields["message"] : "",
937
+ status: error.status,
938
+ ...(typeof fields["approvalId"] === "string" ? { approvalId: fields["approvalId"] } : {}),
939
+ ...(typeof fields["consentId"] === "string" ? { consentId: fields["consentId"] } : {}),
940
+ }
941
+ }
942
+
943
+ /** The platform's `AbortController`, where it has one (typed here: not every platform's types have it). */
944
+ const Controller = (
945
+ globalThis as { readonly AbortController?: new () => { readonly signal: AbortSignalLike; abort(): void } }
946
+ ).AbortController
947
+
948
+ /** The key a decision is made under: the same for every retry of it, another for another decision. */
949
+ export const decisionKey = {
950
+ consent: (consentId: string, decision: "approve" | "reject", remember?: string) =>
951
+ `consent:${consentId}:${decision}:${remember ?? ""}`,
952
+ approval: (approvalId: string, decision: "approve" | "reject") => `approval:${approvalId}:${decision}`,
953
+ cancel: (runId: string) => `cancel:${runId}`,
954
+ /**
955
+ * One step on a work item, by the operation it is (`operation`: new for each step the person takes, kept only to
956
+ * retry that step). Never by item and step alone: an item closed and opened again (a follow-up flagged once more
957
+ * keeps its id) is a new operation, which a stale key would answer with the old receipt.
958
+ */
959
+ workItem: (itemId: string, step: WorkItemStep, operation: string) => `inbox:${itemId}:${step}:${operation}`,
960
+ }
961
+
962
+ /**
963
+ * The chat's requests, as Effects (interrupting one aborts its request): send, cancel, the active run's events, and
964
+ * the person's consent and approval decisions (the kernel's actions, which refuse an agent). A send or decision not
965
+ * answered within `sendTimeout` fails with `Timeout` (status 0: its answer was lost, not refused).
966
+ */
967
+ export const chatClient = (options: ChatClientOptions) => {
968
+ const agent = agentClient({
969
+ baseUrl: options.baseUrl,
970
+ token: options.token,
971
+ orgId: options.orgId,
972
+ clientVersion: options.clientVersion,
973
+ })
974
+ const timeout = options.sendTimeout ?? Duration.seconds(30)
975
+ const base = Duration.fromInputUnsafe(options.reconnect?.base ?? Duration.millis(500))
976
+ const max = Duration.fromInputUnsafe(options.reconnect?.max ?? Duration.seconds(10))
977
+ /** How long to wait before reconnection attempt `attempt` (from 0). */
978
+ const backoff = (attempt: number) => Duration.min(Duration.times(base, 2 ** Math.min(attempt, 16)), max)
979
+ /** One connection to the run's event stream after `after`; interrupting it aborts its request. */
980
+ const connect = (runId: string, after: number): Stream.Stream<RunEvent, ChatError> =>
981
+ Stream.unwrap(
982
+ Effect.map(
983
+ Effect.acquireRelease(
984
+ Effect.sync(() => (Controller === undefined ? undefined : new Controller())),
985
+ (controller) => Effect.sync(() => controller?.abort()),
986
+ ),
987
+ (controller) => Stream.fromAsyncIterable(agent.events(runId, { after, signal: controller?.signal }), chatError),
988
+ ),
989
+ )
990
+ /**
991
+ * The run's events after `after`, across connections: one that drops, or fails without a definitive answer (no
992
+ * answer, a gateway's or the server's error), is followed by another (after `backoff`) from the last stored event
993
+ * delivered, until `run-finished`; a definitive refusal fails the stream.
994
+ */
995
+ const follow = (runId: string, after: number, attempt: number): Stream.Stream<RunEvent, ChatError> =>
996
+ Stream.suspend(() => {
997
+ let last = after
998
+ let delivered = false
999
+ let finished = false
1000
+ const again = Stream.suspend(() =>
1001
+ finished
1002
+ ? Stream.empty
1003
+ : Stream.fromEffect(Effect.sleep(backoff(delivered ? 0 : attempt))).pipe(
1004
+ Stream.drain,
1005
+ Stream.concat(follow(runId, last, delivered ? 1 : attempt + 1)),
1006
+ ),
1007
+ )
1008
+ return connect(runId, after).pipe(
1009
+ Stream.tap((event) =>
1010
+ Effect.sync(() => {
1011
+ delivered = true
1012
+ if (event.seq > last) last = event.seq
1013
+ if (event.type === "run-finished") finished = true
1014
+ }),
1015
+ ),
1016
+ Stream.catch((error: ChatError) => (isDefinitive(error) ? Stream.fail(error) : Stream.empty)),
1017
+ Stream.concat(again),
1018
+ )
1019
+ })
1020
+ const timed = <A>(effect: Effect.Effect<A, ChatError>) =>
1021
+ effect.pipe(
1022
+ Effect.timeoutOrElse({
1023
+ duration: timeout,
1024
+ orElse: () =>
1025
+ Effect.fail<ChatError>({
1026
+ _tag: "Timeout",
1027
+ message: `No answer within ${Duration.format(Duration.fromInputUnsafe(timeout))}`,
1028
+ status: 0,
1029
+ }),
1030
+ }),
1031
+ )
1032
+ const action = (name: string, input: unknown, key: string) =>
1033
+ timed(
1034
+ Effect.tryPromise({
1035
+ try: async (signal) => {
1036
+ const headers: Record<string, string> = {
1037
+ "content-type": "application/json",
1038
+ "x-eloxiv-org": options.orgId,
1039
+ [IDEMPOTENCY_HEADER]: key,
1040
+ }
1041
+ const token = options.token()
1042
+ if (token !== undefined) headers["authorization"] = `Bearer ${token}`
1043
+ if (options.clientVersion !== undefined) headers[CLIENT_VERSION_HEADER] = options.clientVersion
1044
+ const response = await fetch(`${options.baseUrl}/api/actions/${name}`, {
1045
+ method: "POST",
1046
+ headers,
1047
+ body: JSON.stringify(input),
1048
+ signal,
1049
+ })
1050
+ const body = (await response.json().catch(() => ({}))) as Record<string, unknown>
1051
+ if (!response.ok)
1052
+ throw new AgentRequestError(response.status, {
1053
+ ...body,
1054
+ _tag: typeof body["_tag"] === "string" ? body["_tag"] : `HTTP ${response.status}`,
1055
+ })
1056
+ return body
1057
+ },
1058
+ catch: chatError,
1059
+ }),
1060
+ )
1061
+ return {
1062
+ /**
1063
+ * Send a message (`agent.send`) under its idempotency key: the conversation and the run to follow, or, for a retry
1064
+ * of a send already made, a replay (the kernel answers a replay with its receipt, never running it again).
1065
+ */
1066
+ send: (request: ChatSendRequest): Effect.Effect<ChatSendResult, ChatError> =>
1067
+ timed(
1068
+ Effect.tryPromise({
1069
+ try: async (signal): Promise<ChatSendResult> => {
1070
+ const answer = (await agent.send(
1071
+ {
1072
+ text: request.text,
1073
+ ...(request.conversationId === null ? {} : { conversationId: request.conversationId }),
1074
+ ...(request.device === undefined || request.device === null ? {} : { device: request.device }),
1075
+ },
1076
+ { idempotencyKey: request.idempotencyKey, signal: signal as unknown as AbortSignalLike },
1077
+ )) as unknown as Record<string, unknown>
1078
+ if (typeof answer["runId"] === "string" && typeof answer["conversationId"] === "string")
1079
+ return { kind: "sent", conversationId: answer["conversationId"], runId: answer["runId"] }
1080
+ if (typeof answer["invocationId"] === "string")
1081
+ return { kind: "replayed", invocationId: answer["invocationId"] }
1082
+ throw new Error(`agent.send answered neither a send nor a replay: ${JSON.stringify(answer)}`)
1083
+ },
1084
+ catch: chatError,
1085
+ }),
1086
+ ),
1087
+ /**
1088
+ * Whether the person's send under `idempotencyKey` ran: its receipt is in the kernel's receipt store. `false` means
1089
+ * none has committed yet, not that none will (a send still in flight commits its receipt with it).
1090
+ */
1091
+ lookup: (idempotencyKey: string): Effect.Effect<{ readonly ran: boolean }, ChatError> =>
1092
+ timed(
1093
+ Effect.tryPromise({
1094
+ try: async (signal) => {
1095
+ const answer = await agent.sendReceipt(idempotencyKey, { signal: signal as unknown as AbortSignalLike })
1096
+ return { ran: answer.receipt !== null && answer.receipt !== undefined }
1097
+ },
1098
+ catch: chatError,
1099
+ }),
1100
+ ),
1101
+ /**
1102
+ * Whether the person's agent can answer (AgentRuntime `readiness`), for `withEngine`: the kernel's verdict, or
1103
+ * `unknown` when it could not be asked (never `missing` for a failed probe). A refusal of the caller fails.
1104
+ */
1105
+ readiness: (): Effect.Effect<EngineReadiness, ChatError> =>
1106
+ timed(
1107
+ Effect.tryPromise({
1108
+ try: (signal) => agent.readiness({ signal: signal as unknown as AbortSignalLike }),
1109
+ catch: chatError,
1110
+ }),
1111
+ ).pipe(
1112
+ Effect.catchIf(
1113
+ (error) => error._tag === "Timeout",
1114
+ () => Effect.succeed<EngineReadiness>({ ...UNKNOWN_ENGINE, detail: "No answer in time" }),
1115
+ ),
1116
+ ),
1117
+ /** Cancel the run (`agent.cancel`), under the run's own key. */
1118
+ cancel: (runId: string) => action("agent.cancel", { runId }, decisionKey.cancel(runId)),
1119
+ /**
1120
+ * The run's events after `after` (exclusive), as they happen, ending after `run-finished`. Each names the run;
1121
+ * streamed text has `seq: -1`. A connection that drops or fails without a definitive answer is followed by
1122
+ * another (see `reconnect`) from the last stored event delivered, so a consent asked meanwhile, or the run's end,
1123
+ * is never missed; a refusal (the session ended, not the person's run) fails the stream. Interrupting the stream
1124
+ * aborts its request: the connection closes at once, even while the stream is silent.
1125
+ */
1126
+ events: (runId: string, after = -1): Stream.Stream<RunEvent, ChatError> => follow(runId, after, 0),
1127
+ /** The person's decision on a held tool call (`consent.approve` or `consent.reject`), under its own key. */
1128
+ decideConsent: (consentId: string, decision: "approve" | "reject", remember?: "once" | "session" | "always") =>
1129
+ action(
1130
+ decision === "approve" ? "consent.approve" : "consent.reject",
1131
+ decision === "approve" && remember !== undefined ? { id: consentId, remember } : { id: consentId },
1132
+ decisionKey.consent(consentId, decision, decision === "approve" ? remember : undefined),
1133
+ ),
1134
+ /**
1135
+ * A step on a work item (`inbox.claim`, `inbox.complete`, `inbox.dismiss`) under `key`, the step's own
1136
+ * (`decisionKey.workItem` with an operation id the caller makes when the person chooses the step): the same key
1137
+ * for a retry of it acts once; another step, even the same one on the item reopened, takes a new key.
1138
+ */
1139
+ workItem: (itemId: string, step: WorkItemStep, key: string) => action(`inbox.${step}`, { id: itemId }, key),
1140
+ /** The person's decision on an approval request (`approvals.approve` or `approvals.reject`), under its own key. */
1141
+ decideApproval: (approvalId: string, decision: "approve" | "reject", comment?: string) =>
1142
+ action(
1143
+ decision === "approve" ? "approvals.approve" : "approvals.reject",
1144
+ comment === undefined ? { id: approvalId } : { id: approvalId, comment },
1145
+ decisionKey.approval(approvalId, decision),
1146
+ ),
1147
+ }
1148
+ }
1149
+
1150
+ export type ChatClient = ReturnType<typeof chatClient>