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