@agentshouse/mdruntime 0.1.0-cacb4c3f6734e → 0.1.0-caee7332d2235

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