@agentshouse/mdruntime 0.1.0-cebcd51f70ed1 → 0.1.0-cedb03eaa48b6

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 (204) hide show
  1. package/AGENTS.md +283 -222
  2. package/README.md +20 -10
  3. package/dist/adapter.d.ts +95 -20
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/attached-model.d.ts.map +1 -1
  6. package/dist/attached-model.js +15 -2
  7. package/dist/attempt.d.ts +16 -0
  8. package/dist/attempt.d.ts.map +1 -0
  9. package/dist/attempt.js +70 -0
  10. package/dist/binary.d.ts +23 -0
  11. package/dist/binary.d.ts.map +1 -0
  12. package/dist/binary.js +8 -0
  13. package/dist/bootstrap.d.ts +18 -5
  14. package/dist/bootstrap.d.ts.map +1 -1
  15. package/dist/bootstrap.js +113 -37
  16. package/dist/change-set.d.ts +2 -0
  17. package/dist/change-set.d.ts.map +1 -1
  18. package/dist/change-set.js +49 -16
  19. package/dist/change.d.ts +15 -0
  20. package/dist/change.d.ts.map +1 -1
  21. package/dist/change.js +26 -1
  22. package/dist/chat/acts.d.ts +33 -0
  23. package/dist/chat/acts.d.ts.map +1 -0
  24. package/dist/chat/acts.js +36 -0
  25. package/dist/chat/context.d.ts +3 -0
  26. package/dist/chat/context.d.ts.map +1 -0
  27. package/dist/chat/context.js +10 -0
  28. package/dist/chat/earlier.d.ts +10 -0
  29. package/dist/chat/earlier.d.ts.map +1 -0
  30. package/dist/chat/earlier.js +54 -0
  31. package/dist/chat/input.d.ts +9 -0
  32. package/dist/chat/input.d.ts.map +1 -0
  33. package/dist/chat/input.js +99 -0
  34. package/dist/chat/kit.d.ts +61 -0
  35. package/dist/chat/kit.d.ts.map +1 -0
  36. package/dist/chat/kit.js +123 -0
  37. package/dist/chat/lasting.d.ts +6 -0
  38. package/dist/chat/lasting.d.ts.map +1 -0
  39. package/dist/chat/lasting.js +19 -0
  40. package/dist/chat/list.d.ts +27 -0
  41. package/dist/chat/list.d.ts.map +1 -0
  42. package/dist/chat/list.js +99 -0
  43. package/dist/chat/markdown.d.ts +20 -0
  44. package/dist/chat/markdown.d.ts.map +1 -0
  45. package/dist/chat/markdown.js +188 -0
  46. package/dist/chat/message.d.ts +6 -0
  47. package/dist/chat/message.d.ts.map +1 -0
  48. package/dist/chat/message.js +192 -0
  49. package/dist/chat/messages.d.ts +22 -0
  50. package/dist/chat/messages.d.ts.map +1 -0
  51. package/dist/chat/messages.js +155 -0
  52. package/dist/chat/name.d.ts +6 -0
  53. package/dist/chat/name.d.ts.map +1 -0
  54. package/dist/chat/name.js +37 -0
  55. package/dist/chat/opened.d.ts +11 -0
  56. package/dist/chat/opened.d.ts.map +1 -0
  57. package/dist/chat/opened.js +17 -0
  58. package/dist/chat/overlay.d.ts +31 -0
  59. package/dist/chat/overlay.d.ts.map +1 -0
  60. package/dist/chat/overlay.js +97 -0
  61. package/dist/chat/parts.d.ts +57 -0
  62. package/dist/chat/parts.d.ts.map +1 -0
  63. package/dist/chat/parts.js +119 -0
  64. package/dist/chat/process.d.ts +20 -0
  65. package/dist/chat/process.d.ts.map +1 -0
  66. package/dist/chat/process.js +32 -0
  67. package/dist/chat/provider.d.ts +63 -0
  68. package/dist/chat/provider.d.ts.map +1 -0
  69. package/dist/chat/provider.js +628 -0
  70. package/dist/chat/question.d.ts +9 -0
  71. package/dist/chat/question.d.ts.map +1 -0
  72. package/dist/chat/question.js +69 -0
  73. package/dist/chat/questions.d.ts +31 -0
  74. package/dist/chat/questions.d.ts.map +1 -0
  75. package/dist/chat/questions.js +111 -0
  76. package/dist/chat/read.d.ts +5 -0
  77. package/dist/chat/read.d.ts.map +1 -0
  78. package/dist/chat/read.js +13 -0
  79. package/dist/chat/ready.d.ts +34 -0
  80. package/dist/chat/ready.d.ts.map +1 -0
  81. package/dist/chat/ready.js +91 -0
  82. package/dist/chat/style.d.ts +4 -0
  83. package/dist/chat/style.d.ts.map +1 -0
  84. package/dist/chat/style.js +302 -0
  85. package/dist/chat.d.ts +14 -0
  86. package/dist/chat.d.ts.map +1 -0
  87. package/dist/chat.js +8 -0
  88. package/dist/client.d.ts +30 -13
  89. package/dist/client.d.ts.map +1 -1
  90. package/dist/client.js +79 -16
  91. package/dist/collection.d.ts +21 -12
  92. package/dist/collection.d.ts.map +1 -1
  93. package/dist/collection.js +301 -23
  94. package/dist/connection.d.ts +50 -16
  95. package/dist/connection.d.ts.map +1 -1
  96. package/dist/connection.js +1936 -415
  97. package/dist/conversation.d.ts +31 -10
  98. package/dist/conversation.d.ts.map +1 -1
  99. package/dist/conversation.js +521 -170
  100. package/dist/durability.d.ts +7 -1
  101. package/dist/durability.d.ts.map +1 -1
  102. package/dist/entry.d.ts +17 -0
  103. package/dist/entry.d.ts.map +1 -0
  104. package/dist/entry.js +157 -0
  105. package/dist/expectation.d.ts +21 -0
  106. package/dist/expectation.d.ts.map +1 -0
  107. package/dist/expectation.js +70 -0
  108. package/dist/failure.d.ts +13 -0
  109. package/dist/failure.d.ts.map +1 -0
  110. package/dist/failure.js +19 -0
  111. package/dist/fence.d.ts +6 -0
  112. package/dist/fence.d.ts.map +1 -0
  113. package/dist/fence.js +10 -0
  114. package/dist/host.d.ts +15 -2
  115. package/dist/host.d.ts.map +1 -1
  116. package/dist/host.js +102 -19
  117. package/dist/identity.d.ts +5 -0
  118. package/dist/identity.d.ts.map +1 -1
  119. package/dist/identity.js +19 -1
  120. package/dist/index.d.ts +16 -8
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +5 -0
  123. package/dist/memory.d.ts +11 -4
  124. package/dist/memory.d.ts.map +1 -1
  125. package/dist/memory.js +91 -24
  126. package/dist/model.d.ts +14 -4
  127. package/dist/model.d.ts.map +1 -1
  128. package/dist/model.js +12 -1
  129. package/dist/observation.d.ts +7 -2
  130. package/dist/observation.d.ts.map +1 -1
  131. package/dist/observation.js +29 -12
  132. package/dist/open.d.ts +2 -0
  133. package/dist/open.d.ts.map +1 -0
  134. package/dist/open.js +1 -0
  135. package/dist/outcome.d.ts +38 -3
  136. package/dist/outcome.d.ts.map +1 -1
  137. package/dist/outcome.js +45 -1
  138. package/dist/overlay.d.ts +16 -3
  139. package/dist/overlay.d.ts.map +1 -1
  140. package/dist/overlay.js +118 -77
  141. package/dist/query.d.ts +60 -4
  142. package/dist/query.d.ts.map +1 -1
  143. package/dist/query.js +41 -38
  144. package/dist/reach.d.ts +8 -3
  145. package/dist/reach.d.ts.map +1 -1
  146. package/dist/reach.js +73 -24
  147. package/dist/react.d.ts +31 -20
  148. package/dist/react.d.ts.map +1 -1
  149. package/dist/react.js +13 -21
  150. package/dist/read-side.d.ts +16 -7
  151. package/dist/read-side.d.ts.map +1 -1
  152. package/dist/read-side.js +493 -102
  153. package/dist/readiness.d.ts +53 -0
  154. package/dist/readiness.d.ts.map +1 -0
  155. package/dist/readiness.js +33 -0
  156. package/dist/reads.d.ts +11 -0
  157. package/dist/reads.d.ts.map +1 -0
  158. package/dist/reads.js +98 -0
  159. package/dist/recovery.d.ts +25 -0
  160. package/dist/recovery.d.ts.map +1 -0
  161. package/dist/recovery.js +197 -0
  162. package/dist/refresh.d.ts +13 -3
  163. package/dist/refresh.d.ts.map +1 -1
  164. package/dist/refresh.js +49 -38
  165. package/dist/replica.d.ts +13 -6
  166. package/dist/replica.d.ts.map +1 -1
  167. package/dist/replica.js +143 -70
  168. package/dist/room-draft.d.ts +38 -9
  169. package/dist/room-draft.d.ts.map +1 -1
  170. package/dist/room-draft.js +134 -25
  171. package/dist/rows.d.ts +10 -13
  172. package/dist/rows.d.ts.map +1 -1
  173. package/dist/rows.js +19 -14
  174. package/dist/save.d.ts +32 -1
  175. package/dist/save.d.ts.map +1 -1
  176. package/dist/save.js +390 -45
  177. package/dist/search.d.ts +52 -8
  178. package/dist/search.d.ts.map +1 -1
  179. package/dist/search.js +192 -47
  180. package/dist/seed.d.ts +16 -0
  181. package/dist/seed.d.ts.map +1 -0
  182. package/dist/seed.js +75 -0
  183. package/dist/shared.d.ts +11 -0
  184. package/dist/shared.d.ts.map +1 -0
  185. package/dist/shared.js +368 -0
  186. package/dist/status.d.ts +6 -2
  187. package/dist/status.d.ts.map +1 -1
  188. package/dist/status.js +0 -8
  189. package/dist/store.d.ts +89 -18
  190. package/dist/store.d.ts.map +1 -1
  191. package/dist/store.js +573 -200
  192. package/dist/turn.d.ts +7 -0
  193. package/dist/turn.d.ts.map +1 -0
  194. package/dist/turn.js +51 -0
  195. package/dist/windows.d.ts +26 -0
  196. package/dist/windows.d.ts.map +1 -0
  197. package/dist/windows.js +93 -0
  198. package/dist/wire.d.ts +157 -33
  199. package/dist/wire.d.ts.map +1 -1
  200. package/dist/wire.js +65 -31
  201. package/package.json +26 -14
  202. package/dist/attachment.d.ts +0 -3
  203. package/dist/attachment.d.ts.map +0 -1
  204. package/dist/attachment.js +0 -8
@@ -0,0 +1,628 @@
1
+ import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from 'react';
2
+ import { AssistantRuntimeProvider, createMessageQueue, generateId, useExternalStoreRuntime, } from '@assistant-ui/react';
3
+ import { attempts } from '../attempt.js';
4
+ import { newChat, } from '../conversation.js';
5
+ import { expectedList } from '../expectation.js';
6
+ import { chatDraftRevision } from '../identity.js';
7
+ import { useObserve } from '../react.js';
8
+ import { accepted, answeredOf, outcomeOf, sender, unanswered, } from './acts.js';
9
+ import { CHAT_WINDOW, useEarlier } from './earlier.js';
10
+ import { askedBefore, chatMessages, contextOf } from './messages.js';
11
+ import { conversationChanged, conversationGone, conversationListed, optionChosen, overlay, questionAnswered, sentMessage, } from './overlay.js';
12
+ import { commandIn, commandsOf, optionsOf } from './process.js';
13
+ import { loneOf, questionsOf } from './questions.js';
14
+ import { record, text } from './read.js';
15
+ const SHARED = new WeakMap();
16
+ const LATEST = { limit: CHAT_WINDOW };
17
+ function sharedOf(client) {
18
+ const held = SHARED.get(client);
19
+ if (held !== undefined)
20
+ return held;
21
+ const fresh = { overlay: overlay(), created: new Map(), sends: 0 };
22
+ SHARED.set(client, fresh);
23
+ return fresh;
24
+ }
25
+ function ready(observed) {
26
+ return observed.state === 'ready' ? observed.value : null;
27
+ }
28
+ function turnOf(result) {
29
+ return accepted(result) ? text(record(result.result), 'turn') : null;
30
+ }
31
+ async function deliver(client, send, conversation, said, key, idle) {
32
+ const result = await send.numbered('conversation.send', { conversation, key }, (operation) => client.conversation.send(conversation, operation, said));
33
+ if (accepted(result))
34
+ send.expect(sentMessage(key, [conversation], said, turnOf(result)));
35
+ else if (!unanswered(result))
36
+ idle();
37
+ return result;
38
+ }
39
+ const IDLE = { busy: false, outcome: null };
40
+ const SENDING = { state: 'sending' };
41
+ function useActs(overlay, online) {
42
+ const [running, setRunning] = useState(IDLE);
43
+ const [tried] = useState(() => attempts());
44
+ const latest = useRef(0);
45
+ const mounted = useRef(true);
46
+ useEffect(() => {
47
+ mounted.current = true;
48
+ return () => {
49
+ mounted.current = false;
50
+ };
51
+ }, []);
52
+ const clear = useCallback(() => {
53
+ latest.current += 1;
54
+ setRunning(IDLE);
55
+ }, []);
56
+ const call = useCallback((steps, expected = null, then) => {
57
+ latest.current += 1;
58
+ const mine = latest.current;
59
+ const act = overlay.begin();
60
+ const drawn = typeof expected === 'function' ? null : expected;
61
+ overlay.expect(act, drawn);
62
+ setRunning({ busy: true, outcome: expectedList(drawn).length > 0 ? null : SENDING });
63
+ const attempt = tried.begin(act);
64
+ const send = sender({
65
+ online,
66
+ identity: attempt.identity,
67
+ expect: (expecting) => overlay.expect(overlay.begin(), expecting),
68
+ draw: (expecting) => overlay.expect(act, expecting),
69
+ });
70
+ return steps(send)
71
+ .catch(() => ({
72
+ kind: 'transport-uncertainty',
73
+ code: 'transport-uncertainty',
74
+ fields: {},
75
+ retryable: true,
76
+ }))
77
+ .then((result) => {
78
+ if (accepted(result) && typeof expected === 'function') {
79
+ overlay.expect(act, expected(result.result));
80
+ }
81
+ attempt.settle(answeredOf(result), (one) => overlay.drop(one));
82
+ if (!mounted.current || latest.current !== mine)
83
+ return accepted(result);
84
+ if (accepted(result))
85
+ then?.(result.result);
86
+ if (latest.current === mine)
87
+ setRunning({ busy: false, outcome: outcomeOf(result) });
88
+ return accepted(result);
89
+ });
90
+ }, [overlay, online, tried]);
91
+ return { ...running, call, clear };
92
+ }
93
+ const ATTACHMENTS = {
94
+ accept: '*',
95
+ add: ({ file }) => Promise.resolve({
96
+ id: generateId(),
97
+ type: 'file',
98
+ name: file.name,
99
+ contentType: file.type,
100
+ file,
101
+ status: { type: 'requires-action', reason: 'composer-send' },
102
+ }),
103
+ send: (attachment) => Promise.resolve({ ...attachment, status: { type: 'complete' }, content: [] }),
104
+ remove: () => Promise.resolve(),
105
+ };
106
+ function filesOf(attachments) {
107
+ return attachments.flatMap((one) => one.file === undefined ? [] : [{ name: one.name, blob: one.file }]);
108
+ }
109
+ function fileOf(file) {
110
+ return file.blob instanceof File && file.blob.name === file.name
111
+ ? file.blob
112
+ : new File([file.blob], file.name, { type: file.blob.type });
113
+ }
114
+ function textOf(parts) {
115
+ return parts.map((part) => (part.type === 'text' ? (part.text ?? '') : '')).join('');
116
+ }
117
+ function draftOf(message) {
118
+ return { text: textOf(message.content), files: filesOf(message.attachments ?? []) };
119
+ }
120
+ function appended(draft) {
121
+ return {
122
+ role: 'user',
123
+ content: [{ type: 'text', text: draft.text }],
124
+ attachments: draft.files.map((file) => ({
125
+ id: generateId(),
126
+ type: 'file',
127
+ name: file.name,
128
+ contentType: file.blob.type,
129
+ file: fileOf(file),
130
+ status: { type: 'complete' },
131
+ content: [],
132
+ })),
133
+ metadata: { custom: {} },
134
+ createdAt: new Date(),
135
+ parentId: null,
136
+ sourceId: null,
137
+ runConfig: undefined,
138
+ };
139
+ }
140
+ function composed(state) {
141
+ return JSON.stringify([state.text, state.attachments.map((one) => one.id)]);
142
+ }
143
+ const ChatContext = createContext(null);
144
+ const ScopeContext = createContext(null);
145
+ export function useChatScope() {
146
+ const scope = useContext(ScopeContext);
147
+ if (scope === null)
148
+ throw new Error('useChat is called outside a ChatProvider');
149
+ return scope;
150
+ }
151
+ export function useChat() {
152
+ const chat = useContext(ChatContext);
153
+ if (chat === null)
154
+ throw new Error('useChat is called outside a ChatProvider');
155
+ return chat;
156
+ }
157
+ export function ChatProvider({ client, conversation = null, agent = null, onOpen, children, }) {
158
+ const shared = sharedOf(client);
159
+ const asked = JSON.stringify([conversation, agent]);
160
+ const [followed, setFollowed] = useState(asked);
161
+ const [open, setOpen] = useState({ conversation, agent });
162
+ if (followed !== asked) {
163
+ setFollowed(asked);
164
+ setOpen({ conversation, agent });
165
+ }
166
+ const opened = useRef(open);
167
+ opened.current = open;
168
+ const told = useRef(onOpen);
169
+ told.current = onOpen;
170
+ const go = useCallback((next) => {
171
+ opened.current = next;
172
+ setOpen(next);
173
+ told.current?.(next);
174
+ }, []);
175
+ const listedHeld = ready(useObserve(client, 'conversations'));
176
+ const agentsHeld = ready(useObserve(client, 'agents'));
177
+ const readiness = ready(useObserve(client, 'readiness'));
178
+ const refusal = ready(useObserve(client, 'connection-refusal'));
179
+ const online = readiness?.connection !== 'unreachable' && refusal === null;
180
+ const thread = open.conversation ??
181
+ (open.agent === null ? null : (shared.created.get(open.agent) ?? newChat(open.agent)));
182
+ const observed = ready(useObserve(thread === null ? null : client, 'conversation', thread ?? '', LATEST));
183
+ const held = observed !== null && observed.conversation === thread ? observed : null;
184
+ const paged = useEarlier(client, thread, held);
185
+ const version = useSyncExternalStore(shared.overlay.subscribe, shared.overlay.version);
186
+ useEffect(() => {
187
+ if (listedHeld !== null)
188
+ shared.overlay.heardList(listedHeld);
189
+ }, [shared, listedHeld, version]);
190
+ useEffect(() => {
191
+ if (held !== null)
192
+ shared.overlay.heard(held);
193
+ }, [shared, held, version]);
194
+ const conversations = useMemo(() => shared.overlay.conversations(listedHeld ?? []), [shared, listedHeld, version]);
195
+ const view = useMemo(() => (paged.view === null ? null : shared.overlay.conversation(paged.view)), [shared, paged.view, version]);
196
+ const agents = agentsHeld ?? [];
197
+ const known = useRef(agents);
198
+ known.current = agents;
199
+ const entry = conversations.find((one) => one.conversation === open.conversation);
200
+ const running = entry?.state === 'working' || view?.turn != null;
201
+ const questions = useMemo(() => questionsOf(view), [view]);
202
+ const lone = loneOf(questions);
203
+ const commands = useMemo(() => commandsOf(view), [view]);
204
+ const messages = useMemo(() => chatMessages(view), [view]);
205
+ const sending = useActs(shared.overlay, online);
206
+ const behind = useActs(shared.overlay, online);
207
+ const acting = useActs(shared.overlay, online);
208
+ const [again, setAgain] = useState(null);
209
+ const current = useRef(thread);
210
+ current.current = thread;
211
+ const seeding = useRef(false);
212
+ const mounted = useRef(true);
213
+ useEffect(() => {
214
+ mounted.current = true;
215
+ return () => {
216
+ mounted.current = false;
217
+ };
218
+ }, []);
219
+ const was = useRef(null);
220
+ const heard = useRef('');
221
+ const shown = useRef('');
222
+ const own = useRef([]);
223
+ const noted = useCallback((to, revision) => {
224
+ own.current = [...own.current, `${to}\u0000${revision ?? ''}`];
225
+ }, []);
226
+ const keep = useCallback((to, draft) => {
227
+ const revision = draft.text === '' && draft.files.length === 0 ? null : chatDraftRevision();
228
+ noted(to, revision);
229
+ void (revision === null
230
+ ? client.chatDraft.discard(to)
231
+ : client.chatDraft.write(to, draft, revision));
232
+ }, [client, noted]);
233
+ useEffect(() => {
234
+ heard.current = '';
235
+ shown.current = '';
236
+ own.current = own.current.filter((one) => one.startsWith(`${thread}\u0000`));
237
+ const created = was.current === open;
238
+ was.current = open;
239
+ if (created)
240
+ return;
241
+ sending.clear();
242
+ acting.clear();
243
+ setAgain(null);
244
+ }, [thread, sending.clear, acting.clear]);
245
+ const sendTo = (to, said, key, idle, acts = sending) => acts.call((send) => deliver(client, send, to, said, key, idle), sentMessage(key, [to], said, null));
246
+ const first = (to, said, key, returning, idle) => {
247
+ const drafted = [newChat(to)];
248
+ return sending.call(async (send) => {
249
+ let conversation = shared.created.get(to);
250
+ if (conversation === undefined) {
251
+ const answer = await send.carried('conversation.create', { agent: to }, (operation) => client.conversation.create({ agent_id: to, operation_id: operation }));
252
+ if (!accepted(answer)) {
253
+ if (!unanswered(answer)) {
254
+ returning();
255
+ idle();
256
+ }
257
+ return answer;
258
+ }
259
+ const named = text(record(answer.result), 'conversation');
260
+ if (named === null)
261
+ return answer;
262
+ conversation = named;
263
+ shared.created.set(to, conversation);
264
+ const name = known.current.find((one) => one.identity === to)?.name ?? null;
265
+ send.expect(conversationListed({
266
+ conversation,
267
+ agent: { identity: to, name },
268
+ name: name ?? '',
269
+ created: new Date().toISOString(),
270
+ finished: null,
271
+ outcome: null,
272
+ state: 'idle',
273
+ started: null,
274
+ }));
275
+ }
276
+ send.draw(sentMessage(key, [...drafted, conversation], said, null));
277
+ const result = await deliver(client, send, conversation, said, key, idle);
278
+ if (!accepted(result))
279
+ return result;
280
+ shared.created.delete(to);
281
+ const now = opened.current;
282
+ if (mounted.current && now.conversation === null && now.agent === to) {
283
+ go({ conversation, agent: to });
284
+ }
285
+ return result;
286
+ }, sentMessage(key, drafted, said, null));
287
+ };
288
+ const sent = () => {
289
+ shared.sends += 1;
290
+ return `sent ${shared.sends}`;
291
+ };
292
+ const deliverDraft = (said, returning, idle) => {
293
+ const key = sent();
294
+ const { conversation: to, agent: by } = opened.current;
295
+ const attempt = to !== null
296
+ ? () => void sendTo(to, said, key, idle)
297
+ : by !== null
298
+ ? () => void first(by, said, key, returning, idle)
299
+ : null;
300
+ if (attempt === null)
301
+ return;
302
+ setAgain(() => attempt);
303
+ attempt();
304
+ };
305
+ const control = (name, input, expected) => acting.call((send) => send.carried(name, input, (operation) => client.call(name, { ...input, operation_id: operation })), expected);
306
+ const carried = (name, act) => {
307
+ const to = opened.current.conversation;
308
+ if (to === null)
309
+ return Promise.resolve(false);
310
+ return acting.call((send) => send.carried(name, { conversation: to }, () => act(to)));
311
+ };
312
+ const stop = () => carried('conversation.interrupt', (to) => client.conversation.interrupt(to));
313
+ const kill = () => carried('conversation.kill', (to) => client.conversation.kill(to));
314
+ const answer = (question, response) => {
315
+ const to = opened.current.conversation;
316
+ if (to === null || question.secret)
317
+ return Promise.resolve(false);
318
+ return acting.call((send) => send.carried('conversation.answer', { conversation: to, question: question.interaction }, () => client.conversation.answer(to, { interaction_id: question.interaction, response })), () => questionAnswered(to, question.interaction));
319
+ };
320
+ const choose = (option, value) => {
321
+ const to = opened.current.conversation;
322
+ if (to === null)
323
+ return Promise.resolve(false);
324
+ return control('conversation.setOption', { conversation_id: to, option, value }, optionChosen(to, option, value));
325
+ };
326
+ const done = (to = opened.current.conversation) => to === null
327
+ ? Promise.resolve(false)
328
+ : control('conversation.markDone', { conversation_id: to }, conversationChanged(to, { finished: new Date().toISOString() }, (one) => one.finished !== null));
329
+ const rename = (name, to = opened.current.conversation) => to === null
330
+ ? Promise.resolve(false)
331
+ : control('conversation.rename', { conversation_id: to, name }, conversationChanged(to, { name }, (one) => one.name === name));
332
+ const remove = (to = opened.current.conversation) => to === null
333
+ ? Promise.resolve(false)
334
+ : acting.call((send) => send.carried('conversation.delete', { conversation: to }, () => client.conversation.delete(to)), conversationGone(to), () => {
335
+ const now = opened.current;
336
+ if (now.conversation === to)
337
+ go({ conversation: null, agent: now.agent });
338
+ });
339
+ const openConversation = (id) => go({
340
+ conversation: id,
341
+ agent: conversations.find((one) => one.conversation === id)?.agent.identity ?? null,
342
+ });
343
+ const start = (by) => go({ conversation: null, agent: by });
344
+ const dispatch = useRef(() => undefined);
345
+ const queues = useRef(new Map());
346
+ const into = thread ?? '';
347
+ const laneOf = (key) => {
348
+ const held = queues.current.get(key);
349
+ if (held !== undefined)
350
+ return held;
351
+ const fresh = {
352
+ queue: createMessageQueue({ run: (message) => dispatch.current(message, key) }),
353
+ running: false,
354
+ };
355
+ queues.current.set(key, fresh);
356
+ return fresh;
357
+ };
358
+ const lane = laneOf(into);
359
+ const queue = lane.queue;
360
+ const [, moved] = useReducer((count) => count + 1, 0);
361
+ useEffect(() => queue.subscribe(moved), [queue]);
362
+ useEffect(() => {
363
+ for (const [key, one] of queues.current) {
364
+ const now = key === into
365
+ ? running
366
+ : conversations.some((entry) => entry.conversation === key && entry.state !== 'idle');
367
+ const empty = one.queue.adapter.items.length + one.queue.adapter.steerItems.length === 0;
368
+ if (key !== into && !now && empty) {
369
+ queues.current.delete(key);
370
+ continue;
371
+ }
372
+ if (now === one.running)
373
+ continue;
374
+ one.running = now;
375
+ if (now)
376
+ one.queue.notifyBusy();
377
+ else
378
+ one.queue.notifyIdle();
379
+ }
380
+ }, [into, running, conversations]);
381
+ const waiting = useRef(new Map());
382
+ const lanes = () => [...queue.adapter.steerItems, ...queue.adapter.items];
383
+ const threads = useMemo(() => {
384
+ const item = (one) => ({
385
+ id: one.conversation,
386
+ title: one.name,
387
+ custom: { agent: one.agent.identity, state: one.state, finished: one.finished },
388
+ });
389
+ return {
390
+ regular: conversations
391
+ .filter((one) => one.finished === null)
392
+ .map((one) => ({ ...item(one), status: 'regular' })),
393
+ archived: conversations
394
+ .filter((one) => one.finished !== null)
395
+ .map((one) => ({ ...item(one), status: 'archived' })),
396
+ };
397
+ }, [conversations]);
398
+ const aui = useExternalStoreRuntime({
399
+ messages,
400
+ isRunning: running,
401
+ hasEarlier: paged.hasEarlier,
402
+ onLoadEarlier: paged.loadEarlier,
403
+ convertMessage: (message) => message,
404
+ queue: lined(),
405
+ onNew: async (message) => lined().enqueue(message),
406
+ onCancel: async () => {
407
+ void stop();
408
+ },
409
+ onReload: thread === null
410
+ ? undefined
411
+ : async (parent) => {
412
+ const said = askedBefore(view, parent);
413
+ if (said === null)
414
+ return;
415
+ const draft = { text: said, files: [] };
416
+ const into = thread;
417
+ deliverDraft(draft, () => back(draft, into), () => undefined);
418
+ },
419
+ adapters: {
420
+ attachments: ATTACHMENTS,
421
+ threadList: {
422
+ ...(thread === null ? {} : { threadId: thread }),
423
+ threads: threads.regular,
424
+ archivedThreads: threads.archived,
425
+ onSwitchToThread: (id) => openConversation(id),
426
+ onSwitchToNewThread: () => {
427
+ const by = open.agent ?? known.current[0]?.identity;
428
+ if (by !== undefined)
429
+ start(by);
430
+ },
431
+ onRename: (id, name) => {
432
+ void rename(name, id);
433
+ },
434
+ onArchive: (id) => {
435
+ void done(id);
436
+ },
437
+ onDelete: (id) => {
438
+ void remove(id);
439
+ },
440
+ },
441
+ },
442
+ });
443
+ function back(one, into) {
444
+ if (current.current !== into) {
445
+ void client.chatDraft.prepend(into, one);
446
+ return;
447
+ }
448
+ const composer = aui.thread.composer;
449
+ const now = composer.getState().text;
450
+ composer.setText(now === '' ? one.text : `${one.text}\n${now}`);
451
+ for (const file of one.files)
452
+ void composer.addAttachment(fileOf(file));
453
+ }
454
+ function taken(message) {
455
+ const said = textOf(message.content);
456
+ if (lone === null || commandIn(said, commands))
457
+ return false;
458
+ void answer(lone.question, lone.question.accept({ [lone.field.name]: said }));
459
+ return true;
460
+ }
461
+ function lined() {
462
+ const holding = (put) => (message) => {
463
+ if (taken(message))
464
+ return;
465
+ if (!online) {
466
+ const draft = draftOf(message);
467
+ const at = current.current;
468
+ deliverDraft(draft, () => {
469
+ if (at !== null)
470
+ back(draft, at);
471
+ }, () => undefined);
472
+ return;
473
+ }
474
+ const known = new Set(lanes().map((one) => one.id));
475
+ if (!lane.running)
476
+ queue.notifyIdle();
477
+ put(message);
478
+ const added = lanes().find((one) => !known.has(one.id));
479
+ if (added !== undefined)
480
+ waiting.current.set(added.id, message);
481
+ };
482
+ return {
483
+ get items() {
484
+ return queue.adapter.items;
485
+ },
486
+ get steerItems() {
487
+ return queue.adapter.steerItems;
488
+ },
489
+ enqueue: holding(queue.adapter.enqueue),
490
+ steer: holding(queue.adapter.steer),
491
+ move: queue.adapter.move,
492
+ edit: queue.adapter.edit,
493
+ remove: queue.adapter.remove,
494
+ __internal_setDispatchTransform: queue.adapter.__internal_setDispatchTransform,
495
+ };
496
+ }
497
+ dispatch.current = (message, key) => {
498
+ const draft = draftOf(message);
499
+ const idle = () => queues.current.get(key)?.queue.notifyIdle();
500
+ if (key !== (current.current ?? '')) {
501
+ void sendTo(key, draft, sent(), idle, behind);
502
+ return;
503
+ }
504
+ const into = current.current;
505
+ deliverDraft(draft, () => {
506
+ if (into !== null)
507
+ back(draft, into);
508
+ }, idle);
509
+ };
510
+ const unqueue = (id) => {
511
+ const message = waiting.current.get(id);
512
+ waiting.current.delete(id);
513
+ queue.adapter.remove(id);
514
+ return message;
515
+ };
516
+ const edit = (id) => {
517
+ const item = lanes().find((one) => one.id === id);
518
+ const message = unqueue(id);
519
+ if (thread === null || item === undefined)
520
+ return;
521
+ back(message === undefined ? { text: textOf(item.parts), files: [] } : draftOf(message), thread);
522
+ };
523
+ const reconcile = useRef(() => undefined);
524
+ reconcile.current = () => {
525
+ if (thread === null || view === null || seeding.current)
526
+ return;
527
+ const at = `${thread}\u0000`;
528
+ const now = `${at}${view.chatDraft?.revision ?? ''}`;
529
+ if (now === heard.current)
530
+ return;
531
+ const echo = own.current.indexOf(now);
532
+ const known = heard.current.startsWith(at);
533
+ heard.current = now;
534
+ if (known && echo >= 0) {
535
+ own.current = own.current.slice(echo);
536
+ return;
537
+ }
538
+ own.current = own.current.filter((one) => !one.startsWith(at));
539
+ const composer = aui.thread.composer;
540
+ const state = composer.getState();
541
+ const stored = view.chatDraft;
542
+ const typed = { text: state.text, files: filesOf(state.attachments) };
543
+ const kept = !known && (typed.text !== '' || typed.files.length > 0);
544
+ if (kept && stored === null) {
545
+ shown.current = `${at}${composed(state)}`;
546
+ keep(thread, typed);
547
+ return;
548
+ }
549
+ const draft = kept
550
+ ? {
551
+ text: [stored?.text ?? '', typed.text].filter((one) => one !== '').join('\n'),
552
+ files: [...(stored?.files ?? []), ...typed.files],
553
+ }
554
+ : stored;
555
+ if (state.text === (draft?.text ?? '') &&
556
+ state.attachments.length === 0 &&
557
+ (draft?.files.length ?? 0) === 0) {
558
+ shown.current = `${at}${composed(state)}`;
559
+ return;
560
+ }
561
+ seeding.current = true;
562
+ composer.setText(draft?.text ?? '');
563
+ void composer
564
+ .clearAttachments()
565
+ .then(() => Promise.all((draft?.files ?? []).map((file) => composer.addAttachment(fileOf(file)))))
566
+ .finally(() => {
567
+ seeding.current = false;
568
+ if (current.current !== thread) {
569
+ reconcile.current();
570
+ return;
571
+ }
572
+ const seeded = composer.getState();
573
+ shown.current = `${at}${composed(seeded)}`;
574
+ if (kept)
575
+ keep(thread, { text: seeded.text, files: filesOf(seeded.attachments) });
576
+ reconcile.current();
577
+ });
578
+ };
579
+ useEffect(() => reconcile.current(), [aui, thread, view]);
580
+ useEffect(() => {
581
+ if (thread === null)
582
+ return;
583
+ const at = `${thread}\u0000`;
584
+ const composer = aui.thread.composer;
585
+ return composer.subscribe(() => {
586
+ if (seeding.current || !heard.current.startsWith(at))
587
+ return;
588
+ const state = composer.getState();
589
+ const next = `${at}${composed(state)}`;
590
+ if (next === shown.current)
591
+ return;
592
+ shown.current = next;
593
+ keep(thread, { text: state.text, files: filesOf(state.attachments) });
594
+ });
595
+ }, [aui, thread, keep]);
596
+ const queued = lanes().map((item) => ({ id: item.id, text: textOf(item.parts) }));
597
+ const chat = {
598
+ ...open,
599
+ conversations,
600
+ agents,
601
+ view,
602
+ running,
603
+ questions,
604
+ lone,
605
+ options: optionsOf(view),
606
+ commands,
607
+ context: contextOf(view),
608
+ queued,
609
+ sending: { busy: sending.busy, outcome: sending.outcome, again },
610
+ acting: { busy: acting.busy, outcome: acting.outcome },
611
+ open: openConversation,
612
+ start,
613
+ send: (draft) => lined().enqueue(appended(draft)),
614
+ answer,
615
+ choose,
616
+ stop,
617
+ kill,
618
+ done: () => done(),
619
+ rename: (name) => rename(name),
620
+ remove: () => remove(),
621
+ edit,
622
+ unqueue: (id) => {
623
+ unqueue(id);
624
+ },
625
+ };
626
+ const scope = useMemo(() => ({ client, known: agentsHeld !== null }), [client, agentsHeld]);
627
+ return createElement(AssistantRuntimeProvider, { runtime: aui }, createElement(ScopeContext.Provider, { value: scope }, createElement(ChatContext.Provider, { value: chat }, children)));
628
+ }
@@ -0,0 +1,9 @@
1
+ import { type ReactElement } from 'react';
2
+ import type { MdRuntimeClient } from '../client.js';
3
+ import type { ChatQuestion } from './questions.js';
4
+ export declare function forgetAnswers(client: MdRuntimeClient, conversation: string, interaction?: string): Promise<void>;
5
+ export type ChatQuestionCardProps = {
6
+ readonly question: ChatQuestion;
7
+ };
8
+ export declare function ChatQuestionCard({ question }: ChatQuestionCardProps): ReactElement;
9
+ //# sourceMappingURL=question.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"question.d.ts","sourceRoot":"","sources":["../../src/chat/question.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,YAAY,EAAE,MAAM,OAAO,CAAC;AAGhE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAMpD,OAAO,KAAK,EAAa,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAO9D,wBAAsB,aAAa,CACjC,MAAM,EAAE,eAAe,EACvB,YAAY,EAAE,MAAM,EACpB,WAAW,SAAK,GACf,OAAO,CAAC,IAAI,CAAC,CAOf;AAeD,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;CACjC,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,EAAE,QAAQ,EAAE,EAAE,qBAAqB,GAAG,YAAY,CAmHlF"}