@agentshouse/mdruntime 0.1.0-cf6d5f0a5c9c8 → 0.1.0-cf96c797c5fa8

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