@contractspec/module.ai-chat 4.0.3 → 4.1.0

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 (51) hide show
  1. package/README.md +130 -10
  2. package/dist/adapters/ai-sdk-bundle-adapter.d.ts +18 -0
  3. package/dist/adapters/index.d.ts +4 -0
  4. package/dist/browser/core/index.js +1138 -21
  5. package/dist/browser/index.js +2816 -651
  6. package/dist/browser/presentation/components/index.js +3143 -358
  7. package/dist/browser/presentation/hooks/index.js +961 -43
  8. package/dist/browser/presentation/index.js +2784 -666
  9. package/dist/core/agent-adapter.d.ts +53 -0
  10. package/dist/core/agent-tools-adapter.d.ts +12 -0
  11. package/dist/core/chat-service.d.ts +49 -1
  12. package/dist/core/contracts-context.d.ts +46 -0
  13. package/dist/core/contracts-context.test.d.ts +1 -0
  14. package/dist/core/conversation-store.d.ts +16 -2
  15. package/dist/core/create-chat-route.d.ts +3 -0
  16. package/dist/core/export-formatters.d.ts +29 -0
  17. package/dist/core/export-formatters.test.d.ts +1 -0
  18. package/dist/core/index.d.ts +8 -0
  19. package/dist/core/index.js +1138 -21
  20. package/dist/core/local-storage-conversation-store.d.ts +33 -0
  21. package/dist/core/message-types.d.ts +6 -0
  22. package/dist/core/surface-planner-tools.d.ts +23 -0
  23. package/dist/core/surface-planner-tools.test.d.ts +1 -0
  24. package/dist/core/thinking-levels.d.ts +38 -0
  25. package/dist/core/thinking-levels.test.d.ts +1 -0
  26. package/dist/core/workflow-tools.d.ts +18 -0
  27. package/dist/core/workflow-tools.test.d.ts +1 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.js +2816 -651
  30. package/dist/node/core/index.js +1138 -21
  31. package/dist/node/index.js +2816 -651
  32. package/dist/node/presentation/components/index.js +3143 -358
  33. package/dist/node/presentation/hooks/index.js +961 -43
  34. package/dist/node/presentation/index.js +2787 -669
  35. package/dist/presentation/components/ChatContainer.d.ts +3 -1
  36. package/dist/presentation/components/ChatExportToolbar.d.ts +25 -0
  37. package/dist/presentation/components/ChatMessage.d.ts +16 -1
  38. package/dist/presentation/components/ChatSidebar.d.ts +26 -0
  39. package/dist/presentation/components/ChatWithExport.d.ts +34 -0
  40. package/dist/presentation/components/ChatWithSidebar.d.ts +19 -0
  41. package/dist/presentation/components/ThinkingLevelPicker.d.ts +16 -0
  42. package/dist/presentation/components/ToolResultRenderer.d.ts +33 -0
  43. package/dist/presentation/components/index.d.ts +6 -0
  44. package/dist/presentation/components/index.js +3143 -358
  45. package/dist/presentation/hooks/index.d.ts +2 -0
  46. package/dist/presentation/hooks/index.js +961 -43
  47. package/dist/presentation/hooks/useChat.d.ts +44 -2
  48. package/dist/presentation/hooks/useConversations.d.ts +18 -0
  49. package/dist/presentation/hooks/useMessageSelection.d.ts +13 -0
  50. package/dist/presentation/index.js +2787 -669
  51. package/package.json +14 -18
@@ -10,12 +10,13 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
10
10
  import * as React from "react";
11
11
  import { ScrollArea } from "@contractspec/lib.ui-kit-web/ui/scroll-area";
12
12
  import { cn } from "@contractspec/lib.ui-kit-web/ui/utils";
13
- import { jsxDEV } from "react/jsx-dev-runtime";
13
+ import { jsx, jsxs } from "react/jsx-runtime";
14
14
  "use client";
15
15
  function ChatContainer({
16
16
  children,
17
17
  className,
18
- showScrollButton = true
18
+ showScrollButton = true,
19
+ headerContent
19
20
  }) {
20
21
  const scrollRef = React.useRef(null);
21
22
  const [showScrollDown, setShowScrollDown] = React.useState(false);
@@ -42,24 +43,28 @@ function ChatContainer({
42
43
  });
43
44
  }
44
45
  }, []);
45
- return /* @__PURE__ */ jsxDEV("div", {
46
+ return /* @__PURE__ */ jsxs("div", {
46
47
  className: cn("relative flex flex-1 flex-col", className),
47
48
  children: [
48
- /* @__PURE__ */ jsxDEV(ScrollArea, {
49
+ headerContent && /* @__PURE__ */ jsx("div", {
50
+ className: "border-border flex shrink-0 items-center justify-end gap-2 border-b px-4 py-2",
51
+ children: headerContent
52
+ }),
53
+ /* @__PURE__ */ jsx(ScrollArea, {
49
54
  ref: scrollRef,
50
55
  className: "flex-1",
51
56
  onScroll: handleScroll,
52
- children: /* @__PURE__ */ jsxDEV("div", {
57
+ children: /* @__PURE__ */ jsx("div", {
53
58
  className: "flex flex-col gap-4 p-4",
54
59
  children
55
- }, undefined, false, undefined, this)
56
- }, undefined, false, undefined, this),
57
- showScrollButton && showScrollDown && /* @__PURE__ */ jsxDEV("button", {
60
+ })
61
+ }),
62
+ showScrollButton && showScrollDown && /* @__PURE__ */ jsxs("button", {
58
63
  onClick: scrollToBottom,
59
64
  className: cn("absolute bottom-4 left-1/2 -translate-x-1/2", "bg-primary text-primary-foreground", "rounded-full px-3 py-1.5 text-sm font-medium shadow-lg", "hover:bg-primary/90 transition-colors", "flex items-center gap-1.5"),
60
65
  "aria-label": "Scroll to bottom",
61
66
  children: [
62
- /* @__PURE__ */ jsxDEV("svg", {
67
+ /* @__PURE__ */ jsx("svg", {
63
68
  xmlns: "http://www.w3.org/2000/svg",
64
69
  width: "16",
65
70
  height: "16",
@@ -69,15 +74,15 @@ function ChatContainer({
69
74
  strokeWidth: "2",
70
75
  strokeLinecap: "round",
71
76
  strokeLinejoin: "round",
72
- children: /* @__PURE__ */ jsxDEV("path", {
77
+ children: /* @__PURE__ */ jsx("path", {
73
78
  d: "m6 9 6 6 6-6"
74
- }, undefined, false, undefined, this)
75
- }, undefined, false, undefined, this),
79
+ })
80
+ }),
76
81
  "New messages"
77
82
  ]
78
- }, undefined, true, undefined, this)
83
+ })
79
84
  ]
80
- }, undefined, true, undefined, this);
85
+ });
81
86
  }
82
87
  // src/presentation/components/ChatMessage.tsx
83
88
  import * as React3 from "react";
@@ -91,16 +96,19 @@ import {
91
96
  Copy as Copy2,
92
97
  Check as Check2,
93
98
  ExternalLink,
94
- Wrench
99
+ Wrench,
100
+ Pencil,
101
+ X
95
102
  } from "lucide-react";
96
103
  import { Button as Button2 } from "@contractspec/lib.design-system";
104
+ import { Checkbox } from "@contractspec/lib.ui-kit-web/ui/checkbox";
97
105
 
98
106
  // src/presentation/components/CodePreview.tsx
99
107
  import * as React2 from "react";
100
108
  import { cn as cn2 } from "@contractspec/lib.ui-kit-web/ui/utils";
101
109
  import { Button } from "@contractspec/lib.design-system";
102
110
  import { Copy, Check, Play, Download } from "lucide-react";
103
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
111
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
104
112
  "use client";
105
113
  var LANGUAGE_NAMES = {
106
114
  ts: "TypeScript",
@@ -153,93 +161,147 @@ function CodePreview({
153
161
  document.body.removeChild(a);
154
162
  URL.revokeObjectURL(url);
155
163
  }, [code, filename, language]);
156
- return /* @__PURE__ */ jsxDEV2("div", {
164
+ return /* @__PURE__ */ jsxs2("div", {
157
165
  className: cn2("overflow-hidden rounded-lg border", "bg-muted/50", className),
158
166
  children: [
159
- /* @__PURE__ */ jsxDEV2("div", {
167
+ /* @__PURE__ */ jsxs2("div", {
160
168
  className: cn2("flex items-center justify-between px-3 py-1.5", "bg-muted/80 border-b"),
161
169
  children: [
162
- /* @__PURE__ */ jsxDEV2("div", {
170
+ /* @__PURE__ */ jsxs2("div", {
163
171
  className: "flex items-center gap-2 text-sm",
164
172
  children: [
165
- filename && /* @__PURE__ */ jsxDEV2("span", {
173
+ filename && /* @__PURE__ */ jsx2("span", {
166
174
  className: "text-foreground font-mono",
167
175
  children: filename
168
- }, undefined, false, undefined, this),
169
- /* @__PURE__ */ jsxDEV2("span", {
176
+ }),
177
+ /* @__PURE__ */ jsx2("span", {
170
178
  className: "text-muted-foreground",
171
179
  children: displayLanguage
172
- }, undefined, false, undefined, this)
180
+ })
173
181
  ]
174
- }, undefined, true, undefined, this),
175
- /* @__PURE__ */ jsxDEV2("div", {
182
+ }),
183
+ /* @__PURE__ */ jsxs2("div", {
176
184
  className: "flex items-center gap-1",
177
185
  children: [
178
- showExecute && onExecute && /* @__PURE__ */ jsxDEV2(Button, {
186
+ showExecute && onExecute && /* @__PURE__ */ jsx2(Button, {
179
187
  variant: "ghost",
180
188
  size: "sm",
181
189
  onPress: () => onExecute(code),
182
190
  className: "h-7 w-7 p-0",
183
191
  "aria-label": "Execute code",
184
- children: /* @__PURE__ */ jsxDEV2(Play, {
192
+ children: /* @__PURE__ */ jsx2(Play, {
185
193
  className: "h-3.5 w-3.5"
186
- }, undefined, false, undefined, this)
187
- }, undefined, false, undefined, this),
188
- showDownload && /* @__PURE__ */ jsxDEV2(Button, {
194
+ })
195
+ }),
196
+ showDownload && /* @__PURE__ */ jsx2(Button, {
189
197
  variant: "ghost",
190
198
  size: "sm",
191
199
  onPress: handleDownload,
192
200
  className: "h-7 w-7 p-0",
193
201
  "aria-label": "Download code",
194
- children: /* @__PURE__ */ jsxDEV2(Download, {
202
+ children: /* @__PURE__ */ jsx2(Download, {
195
203
  className: "h-3.5 w-3.5"
196
- }, undefined, false, undefined, this)
197
- }, undefined, false, undefined, this),
198
- showCopy && /* @__PURE__ */ jsxDEV2(Button, {
204
+ })
205
+ }),
206
+ showCopy && /* @__PURE__ */ jsx2(Button, {
199
207
  variant: "ghost",
200
208
  size: "sm",
201
209
  onPress: handleCopy,
202
210
  className: "h-7 w-7 p-0",
203
211
  "aria-label": copied ? "Copied" : "Copy code",
204
- children: copied ? /* @__PURE__ */ jsxDEV2(Check, {
212
+ children: copied ? /* @__PURE__ */ jsx2(Check, {
205
213
  className: "h-3.5 w-3.5 text-green-500"
206
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV2(Copy, {
214
+ }) : /* @__PURE__ */ jsx2(Copy, {
207
215
  className: "h-3.5 w-3.5"
208
- }, undefined, false, undefined, this)
209
- }, undefined, false, undefined, this)
216
+ })
217
+ })
210
218
  ]
211
- }, undefined, true, undefined, this)
219
+ })
212
220
  ]
213
- }, undefined, true, undefined, this),
214
- /* @__PURE__ */ jsxDEV2("div", {
221
+ }),
222
+ /* @__PURE__ */ jsx2("div", {
215
223
  className: "overflow-auto",
216
224
  style: { maxHeight },
217
- children: /* @__PURE__ */ jsxDEV2("pre", {
225
+ children: /* @__PURE__ */ jsx2("pre", {
218
226
  className: "p-3",
219
- children: /* @__PURE__ */ jsxDEV2("code", {
227
+ children: /* @__PURE__ */ jsx2("code", {
220
228
  className: "text-sm",
221
- children: lines.map((line, i) => /* @__PURE__ */ jsxDEV2("div", {
229
+ children: lines.map((line, i) => /* @__PURE__ */ jsxs2("div", {
222
230
  className: "flex",
223
231
  children: [
224
- /* @__PURE__ */ jsxDEV2("span", {
232
+ /* @__PURE__ */ jsx2("span", {
225
233
  className: "text-muted-foreground mr-4 w-8 text-right select-none",
226
234
  children: i + 1
227
- }, undefined, false, undefined, this),
228
- /* @__PURE__ */ jsxDEV2("span", {
235
+ }),
236
+ /* @__PURE__ */ jsx2("span", {
229
237
  className: "flex-1",
230
238
  children: line || " "
231
- }, undefined, false, undefined, this)
239
+ })
232
240
  ]
233
- }, i, true, undefined, this))
234
- }, undefined, false, undefined, this)
235
- }, undefined, false, undefined, this)
236
- }, undefined, false, undefined, this)
241
+ }, i))
242
+ })
243
+ })
244
+ })
245
+ ]
246
+ });
247
+ }
248
+
249
+ // src/presentation/components/ToolResultRenderer.tsx
250
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
251
+ "use client";
252
+ function isPresentationToolResult(result) {
253
+ return typeof result === "object" && result !== null && "presentationKey" in result && typeof result.presentationKey === "string";
254
+ }
255
+ function isFormToolResult(result) {
256
+ return typeof result === "object" && result !== null && "formKey" in result && typeof result.formKey === "string";
257
+ }
258
+ function ToolResultRenderer({
259
+ toolName,
260
+ result,
261
+ presentationRenderer,
262
+ formRenderer,
263
+ showRawFallback = true
264
+ }) {
265
+ if (result === undefined || result === null) {
266
+ return null;
267
+ }
268
+ if (isPresentationToolResult(result) && presentationRenderer) {
269
+ const rendered = presentationRenderer(result.presentationKey, result.data);
270
+ if (rendered != null) {
271
+ return /* @__PURE__ */ jsx3("div", {
272
+ className: "mt-2 rounded-md border border-border bg-background/50 p-3",
273
+ children: rendered
274
+ });
275
+ }
276
+ }
277
+ if (isFormToolResult(result) && formRenderer) {
278
+ const rendered = formRenderer(result.formKey, result.defaultValues);
279
+ if (rendered != null) {
280
+ return /* @__PURE__ */ jsx3("div", {
281
+ className: "mt-2 rounded-md border border-border bg-background/50 p-3",
282
+ children: rendered
283
+ });
284
+ }
285
+ }
286
+ if (!showRawFallback) {
287
+ return null;
288
+ }
289
+ return /* @__PURE__ */ jsxs3("div", {
290
+ children: [
291
+ /* @__PURE__ */ jsx3("span", {
292
+ className: "text-muted-foreground font-medium",
293
+ children: "Output:"
294
+ }),
295
+ /* @__PURE__ */ jsx3("pre", {
296
+ className: "bg-background mt-1 overflow-x-auto rounded p-2 text-xs",
297
+ children: typeof result === "object" ? JSON.stringify(result, null, 2) : String(result)
298
+ })
237
299
  ]
238
- }, undefined, true, undefined, this);
300
+ });
239
301
  }
240
302
 
241
303
  // src/presentation/components/ChatMessage.tsx
242
- import { jsxDEV as jsxDEV3, Fragment } from "react/jsx-dev-runtime";
304
+ import { jsx as jsx4, jsxs as jsxs4, Fragment } from "react/jsx-runtime";
243
305
  "use client";
244
306
  function extractCodeBlocks(content) {
245
307
  const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
@@ -262,33 +324,33 @@ function renderInlineMarkdown(text) {
262
324
  let key = 0;
263
325
  while ((match = linkRegex.exec(text)) !== null) {
264
326
  if (match.index > lastIndex) {
265
- parts.push(/* @__PURE__ */ jsxDEV3("span", {
327
+ parts.push(/* @__PURE__ */ jsx4("span", {
266
328
  children: text.slice(lastIndex, match.index)
267
- }, key++, false, undefined, this));
329
+ }, key++));
268
330
  }
269
- parts.push(/* @__PURE__ */ jsxDEV3("a", {
331
+ parts.push(/* @__PURE__ */ jsx4("a", {
270
332
  href: match[2],
271
333
  target: "_blank",
272
334
  rel: "noopener noreferrer",
273
335
  className: "text-primary underline hover:no-underline",
274
336
  children: match[1]
275
- }, key++, false, undefined, this));
337
+ }, key++));
276
338
  lastIndex = match.index + match[0].length;
277
339
  }
278
340
  if (lastIndex < text.length) {
279
- parts.push(/* @__PURE__ */ jsxDEV3("span", {
341
+ parts.push(/* @__PURE__ */ jsx4("span", {
280
342
  children: text.slice(lastIndex)
281
- }, key++, false, undefined, this));
343
+ }, key++));
282
344
  }
283
345
  return parts.length > 0 ? parts : [text];
284
346
  }
285
347
  function MessageContent({ content }) {
286
348
  const codeBlocks = extractCodeBlocks(content);
287
349
  if (codeBlocks.length === 0) {
288
- return /* @__PURE__ */ jsxDEV3("p", {
350
+ return /* @__PURE__ */ jsx4("p", {
289
351
  className: "whitespace-pre-wrap",
290
352
  children: renderInlineMarkdown(content)
291
- }, undefined, false, undefined, this);
353
+ });
292
354
  }
293
355
  let remaining = content;
294
356
  const parts = [];
@@ -296,33 +358,40 @@ function MessageContent({ content }) {
296
358
  for (const block of codeBlocks) {
297
359
  const [before, after] = remaining.split(block.raw);
298
360
  if (before) {
299
- parts.push(/* @__PURE__ */ jsxDEV3("p", {
361
+ parts.push(/* @__PURE__ */ jsx4("p", {
300
362
  className: "whitespace-pre-wrap",
301
363
  children: renderInlineMarkdown(before.trim())
302
- }, key++, false, undefined, this));
364
+ }, key++));
303
365
  }
304
- parts.push(/* @__PURE__ */ jsxDEV3(CodePreview, {
366
+ parts.push(/* @__PURE__ */ jsx4(CodePreview, {
305
367
  code: block.code,
306
368
  language: block.language,
307
369
  className: "my-2"
308
- }, key++, false, undefined, this));
370
+ }, key++));
309
371
  remaining = after ?? "";
310
372
  }
311
373
  if (remaining.trim()) {
312
- parts.push(/* @__PURE__ */ jsxDEV3("p", {
374
+ parts.push(/* @__PURE__ */ jsx4("p", {
313
375
  className: "whitespace-pre-wrap",
314
376
  children: renderInlineMarkdown(remaining.trim())
315
- }, key++, false, undefined, this));
377
+ }, key++));
316
378
  }
317
- return /* @__PURE__ */ jsxDEV3(Fragment, {
379
+ return /* @__PURE__ */ jsx4(Fragment, {
318
380
  children: parts
319
- }, undefined, false, undefined, this);
381
+ });
320
382
  }
321
383
  function ChatMessage({
322
384
  message,
323
385
  className,
324
386
  showCopy = true,
325
- showAvatar = true
387
+ showAvatar = true,
388
+ selectable = false,
389
+ selected = false,
390
+ onSelect,
391
+ editable = false,
392
+ onEdit,
393
+ presentationRenderer,
394
+ formRenderer
326
395
  }) {
327
396
  const [copied, setCopied] = React3.useState(false);
328
397
  const isUser = message.role === "user";
@@ -333,185 +402,262 @@ function ChatMessage({
333
402
  setCopied(true);
334
403
  setTimeout(() => setCopied(false), 2000);
335
404
  }, [message.content]);
336
- return /* @__PURE__ */ jsxDEV3("div", {
405
+ const handleSelectChange = React3.useCallback((checked) => {
406
+ if (checked !== "indeterminate")
407
+ onSelect?.(message.id);
408
+ }, [message.id, onSelect]);
409
+ const [isEditing, setIsEditing] = React3.useState(false);
410
+ const [editContent, setEditContent] = React3.useState(message.content);
411
+ React3.useEffect(() => {
412
+ setEditContent(message.content);
413
+ }, [message.content]);
414
+ const handleStartEdit = React3.useCallback(() => {
415
+ setEditContent(message.content);
416
+ setIsEditing(true);
417
+ }, [message.content]);
418
+ const handleSaveEdit = React3.useCallback(async () => {
419
+ const trimmed = editContent.trim();
420
+ if (trimmed !== message.content) {
421
+ await onEdit?.(message.id, trimmed);
422
+ }
423
+ setIsEditing(false);
424
+ }, [editContent, message.id, message.content, onEdit]);
425
+ const handleCancelEdit = React3.useCallback(() => {
426
+ setEditContent(message.content);
427
+ setIsEditing(false);
428
+ }, [message.content]);
429
+ return /* @__PURE__ */ jsxs4("div", {
337
430
  className: cn3("group flex gap-3", isUser && "flex-row-reverse", className),
338
431
  children: [
339
- showAvatar && /* @__PURE__ */ jsxDEV3(Avatar, {
432
+ selectable && /* @__PURE__ */ jsx4("div", {
433
+ className: cn3("flex shrink-0 items-start pt-1", "opacity-0 transition-opacity group-hover:opacity-100"),
434
+ children: /* @__PURE__ */ jsx4(Checkbox, {
435
+ checked: selected,
436
+ onCheckedChange: handleSelectChange,
437
+ "aria-label": selected ? "Deselect message" : "Select message"
438
+ })
439
+ }),
440
+ showAvatar && /* @__PURE__ */ jsx4(Avatar, {
340
441
  className: "h-8 w-8 shrink-0",
341
- children: /* @__PURE__ */ jsxDEV3(AvatarFallback, {
442
+ children: /* @__PURE__ */ jsx4(AvatarFallback, {
342
443
  className: cn3(isUser ? "bg-primary text-primary-foreground" : "bg-muted"),
343
- children: isUser ? /* @__PURE__ */ jsxDEV3(User, {
444
+ children: isUser ? /* @__PURE__ */ jsx4(User, {
344
445
  className: "h-4 w-4"
345
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV3(Bot, {
446
+ }) : /* @__PURE__ */ jsx4(Bot, {
346
447
  className: "h-4 w-4"
347
- }, undefined, false, undefined, this)
348
- }, undefined, false, undefined, this)
349
- }, undefined, false, undefined, this),
350
- /* @__PURE__ */ jsxDEV3("div", {
448
+ })
449
+ })
450
+ }),
451
+ /* @__PURE__ */ jsxs4("div", {
351
452
  className: cn3("flex max-w-[80%] flex-col gap-1", isUser && "items-end"),
352
453
  children: [
353
- /* @__PURE__ */ jsxDEV3("div", {
454
+ /* @__PURE__ */ jsx4("div", {
354
455
  className: cn3("rounded-2xl px-4 py-2", isUser ? "bg-primary text-primary-foreground" : "bg-muted text-foreground", isError && "border-destructive bg-destructive/10 border"),
355
- children: isError && message.error ? /* @__PURE__ */ jsxDEV3("div", {
456
+ children: isError && message.error ? /* @__PURE__ */ jsxs4("div", {
356
457
  className: "flex items-start gap-2",
357
458
  children: [
358
- /* @__PURE__ */ jsxDEV3(AlertCircle, {
459
+ /* @__PURE__ */ jsx4(AlertCircle, {
359
460
  className: "text-destructive mt-0.5 h-4 w-4 shrink-0"
360
- }, undefined, false, undefined, this),
361
- /* @__PURE__ */ jsxDEV3("div", {
461
+ }),
462
+ /* @__PURE__ */ jsxs4("div", {
362
463
  children: [
363
- /* @__PURE__ */ jsxDEV3("p", {
464
+ /* @__PURE__ */ jsx4("p", {
364
465
  className: "text-destructive font-medium",
365
466
  children: message.error.code
366
- }, undefined, false, undefined, this),
367
- /* @__PURE__ */ jsxDEV3("p", {
467
+ }),
468
+ /* @__PURE__ */ jsx4("p", {
368
469
  className: "text-muted-foreground text-sm",
369
470
  children: message.error.message
370
- }, undefined, false, undefined, this)
471
+ })
472
+ ]
473
+ })
474
+ ]
475
+ }) : isEditing ? /* @__PURE__ */ jsxs4("div", {
476
+ className: "flex flex-col gap-2",
477
+ children: [
478
+ /* @__PURE__ */ jsx4("textarea", {
479
+ value: editContent,
480
+ onChange: (e) => setEditContent(e.target.value),
481
+ className: "bg-background/50 min-h-[80px] w-full resize-y rounded-md border px-3 py-2 text-sm",
482
+ rows: 4,
483
+ autoFocus: true
484
+ }),
485
+ /* @__PURE__ */ jsxs4("div", {
486
+ className: "flex gap-2",
487
+ children: [
488
+ /* @__PURE__ */ jsxs4(Button2, {
489
+ variant: "default",
490
+ size: "sm",
491
+ onPress: handleSaveEdit,
492
+ "aria-label": "Save edit",
493
+ children: [
494
+ /* @__PURE__ */ jsx4(Check2, {
495
+ className: "h-3 w-3"
496
+ }),
497
+ "Save"
498
+ ]
499
+ }),
500
+ /* @__PURE__ */ jsxs4(Button2, {
501
+ variant: "ghost",
502
+ size: "sm",
503
+ onPress: handleCancelEdit,
504
+ "aria-label": "Cancel edit",
505
+ children: [
506
+ /* @__PURE__ */ jsx4(X, {
507
+ className: "h-3 w-3"
508
+ }),
509
+ "Cancel"
510
+ ]
511
+ })
371
512
  ]
372
- }, undefined, true, undefined, this)
513
+ })
373
514
  ]
374
- }, undefined, true, undefined, this) : isStreaming && !message.content ? /* @__PURE__ */ jsxDEV3("div", {
515
+ }) : isStreaming && !message.content ? /* @__PURE__ */ jsxs4("div", {
375
516
  className: "flex flex-col gap-2",
376
517
  children: [
377
- /* @__PURE__ */ jsxDEV3(Skeleton, {
518
+ /* @__PURE__ */ jsx4(Skeleton, {
378
519
  className: "h-4 w-48"
379
- }, undefined, false, undefined, this),
380
- /* @__PURE__ */ jsxDEV3(Skeleton, {
520
+ }),
521
+ /* @__PURE__ */ jsx4(Skeleton, {
381
522
  className: "h-4 w-32"
382
- }, undefined, false, undefined, this)
523
+ })
383
524
  ]
384
- }, undefined, true, undefined, this) : /* @__PURE__ */ jsxDEV3(MessageContent, {
525
+ }) : /* @__PURE__ */ jsx4(MessageContent, {
385
526
  content: message.content
386
- }, undefined, false, undefined, this)
387
- }, undefined, false, undefined, this),
388
- /* @__PURE__ */ jsxDEV3("div", {
527
+ })
528
+ }),
529
+ /* @__PURE__ */ jsxs4("div", {
389
530
  className: cn3("flex items-center gap-2 text-xs", "text-muted-foreground opacity-0 transition-opacity", "group-hover:opacity-100"),
390
531
  children: [
391
- /* @__PURE__ */ jsxDEV3("span", {
532
+ /* @__PURE__ */ jsx4("span", {
392
533
  children: new Date(message.createdAt).toLocaleTimeString([], {
393
534
  hour: "2-digit",
394
535
  minute: "2-digit"
395
536
  })
396
- }, undefined, false, undefined, this),
397
- message.usage && /* @__PURE__ */ jsxDEV3("span", {
537
+ }),
538
+ message.usage && /* @__PURE__ */ jsxs4("span", {
398
539
  children: [
399
540
  message.usage.inputTokens + message.usage.outputTokens,
400
541
  " tokens"
401
542
  ]
402
- }, undefined, true, undefined, this),
403
- showCopy && !isUser && message.content && /* @__PURE__ */ jsxDEV3(Button2, {
543
+ }),
544
+ showCopy && !isUser && message.content && /* @__PURE__ */ jsx4(Button2, {
404
545
  variant: "ghost",
405
546
  size: "sm",
406
547
  className: "h-6 w-6 p-0",
407
548
  onPress: handleCopy,
408
549
  "aria-label": copied ? "Copied" : "Copy message",
409
- children: copied ? /* @__PURE__ */ jsxDEV3(Check2, {
550
+ children: copied ? /* @__PURE__ */ jsx4(Check2, {
551
+ className: "h-3 w-3"
552
+ }) : /* @__PURE__ */ jsx4(Copy2, {
410
553
  className: "h-3 w-3"
411
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV3(Copy2, {
554
+ })
555
+ }),
556
+ editable && isUser && !isEditing && /* @__PURE__ */ jsx4(Button2, {
557
+ variant: "ghost",
558
+ size: "sm",
559
+ className: "h-6 w-6 p-0",
560
+ onPress: handleStartEdit,
561
+ "aria-label": "Edit message",
562
+ children: /* @__PURE__ */ jsx4(Pencil, {
412
563
  className: "h-3 w-3"
413
- }, undefined, false, undefined, this)
414
- }, undefined, false, undefined, this)
564
+ })
565
+ })
415
566
  ]
416
- }, undefined, true, undefined, this),
417
- message.reasoning && /* @__PURE__ */ jsxDEV3("details", {
567
+ }),
568
+ message.reasoning && /* @__PURE__ */ jsxs4("details", {
418
569
  className: "text-muted-foreground mt-2 text-sm",
419
570
  children: [
420
- /* @__PURE__ */ jsxDEV3("summary", {
571
+ /* @__PURE__ */ jsx4("summary", {
421
572
  className: "cursor-pointer hover:underline",
422
573
  children: "View reasoning"
423
- }, undefined, false, undefined, this),
424
- /* @__PURE__ */ jsxDEV3("div", {
574
+ }),
575
+ /* @__PURE__ */ jsx4("div", {
425
576
  className: "bg-muted mt-1 rounded-md p-2",
426
- children: /* @__PURE__ */ jsxDEV3("p", {
577
+ children: /* @__PURE__ */ jsx4("p", {
427
578
  className: "whitespace-pre-wrap",
428
579
  children: message.reasoning
429
- }, undefined, false, undefined, this)
430
- }, undefined, false, undefined, this)
580
+ })
581
+ })
431
582
  ]
432
- }, undefined, true, undefined, this),
433
- message.sources && message.sources.length > 0 && /* @__PURE__ */ jsxDEV3("div", {
583
+ }),
584
+ message.sources && message.sources.length > 0 && /* @__PURE__ */ jsx4("div", {
434
585
  className: "mt-2 flex flex-wrap gap-2",
435
- children: message.sources.map((source) => /* @__PURE__ */ jsxDEV3("a", {
586
+ children: message.sources.map((source) => /* @__PURE__ */ jsxs4("a", {
436
587
  href: source.url ?? "#",
437
588
  target: "_blank",
438
589
  rel: "noopener noreferrer",
439
590
  className: "text-muted-foreground hover:text-foreground bg-muted inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors",
440
591
  children: [
441
- /* @__PURE__ */ jsxDEV3(ExternalLink, {
592
+ /* @__PURE__ */ jsx4(ExternalLink, {
442
593
  className: "h-3 w-3"
443
- }, undefined, false, undefined, this),
594
+ }),
444
595
  source.title || source.url || source.id
445
596
  ]
446
- }, source.id, true, undefined, this))
447
- }, undefined, false, undefined, this),
448
- message.toolCalls && message.toolCalls.length > 0 && /* @__PURE__ */ jsxDEV3("div", {
597
+ }, source.id))
598
+ }),
599
+ message.toolCalls && message.toolCalls.length > 0 && /* @__PURE__ */ jsx4("div", {
449
600
  className: "mt-2 space-y-2",
450
- children: message.toolCalls.map((tc) => /* @__PURE__ */ jsxDEV3("details", {
601
+ children: message.toolCalls.map((tc) => /* @__PURE__ */ jsxs4("details", {
451
602
  className: "bg-muted border-border rounded-md border",
452
603
  children: [
453
- /* @__PURE__ */ jsxDEV3("summary", {
604
+ /* @__PURE__ */ jsxs4("summary", {
454
605
  className: "flex cursor-pointer items-center gap-2 px-3 py-2 text-sm font-medium",
455
606
  children: [
456
- /* @__PURE__ */ jsxDEV3(Wrench, {
607
+ /* @__PURE__ */ jsx4(Wrench, {
457
608
  className: "text-muted-foreground h-4 w-4"
458
- }, undefined, false, undefined, this),
609
+ }),
459
610
  tc.name,
460
- /* @__PURE__ */ jsxDEV3("span", {
611
+ /* @__PURE__ */ jsx4("span", {
461
612
  className: cn3("ml-auto rounded px-1.5 py-0.5 text-xs", tc.status === "completed" && "bg-green-500/20 text-green-700 dark:text-green-400", tc.status === "error" && "bg-destructive/20 text-destructive", tc.status === "running" && "bg-blue-500/20 text-blue-700 dark:text-blue-400"),
462
613
  children: tc.status
463
- }, undefined, false, undefined, this)
614
+ })
464
615
  ]
465
- }, undefined, true, undefined, this),
466
- /* @__PURE__ */ jsxDEV3("div", {
616
+ }),
617
+ /* @__PURE__ */ jsxs4("div", {
467
618
  className: "border-border border-t px-3 py-2 text-xs",
468
619
  children: [
469
- Object.keys(tc.args).length > 0 && /* @__PURE__ */ jsxDEV3("div", {
620
+ Object.keys(tc.args).length > 0 && /* @__PURE__ */ jsxs4("div", {
470
621
  className: "mb-2",
471
622
  children: [
472
- /* @__PURE__ */ jsxDEV3("span", {
623
+ /* @__PURE__ */ jsx4("span", {
473
624
  className: "text-muted-foreground font-medium",
474
625
  children: "Input:"
475
- }, undefined, false, undefined, this),
476
- /* @__PURE__ */ jsxDEV3("pre", {
626
+ }),
627
+ /* @__PURE__ */ jsx4("pre", {
477
628
  className: "bg-background mt-1 overflow-x-auto rounded p-2",
478
629
  children: JSON.stringify(tc.args, null, 2)
479
- }, undefined, false, undefined, this)
480
- ]
481
- }, undefined, true, undefined, this),
482
- tc.result !== undefined && /* @__PURE__ */ jsxDEV3("div", {
483
- children: [
484
- /* @__PURE__ */ jsxDEV3("span", {
485
- className: "text-muted-foreground font-medium",
486
- children: "Output:"
487
- }, undefined, false, undefined, this),
488
- /* @__PURE__ */ jsxDEV3("pre", {
489
- className: "bg-background mt-1 overflow-x-auto rounded p-2",
490
- children: typeof tc.result === "object" ? JSON.stringify(tc.result, null, 2) : String(tc.result)
491
- }, undefined, false, undefined, this)
630
+ })
492
631
  ]
493
- }, undefined, true, undefined, this),
494
- tc.error && /* @__PURE__ */ jsxDEV3("p", {
632
+ }),
633
+ tc.result !== undefined && /* @__PURE__ */ jsx4(ToolResultRenderer, {
634
+ toolName: tc.name,
635
+ result: tc.result,
636
+ presentationRenderer,
637
+ formRenderer,
638
+ showRawFallback: true
639
+ }),
640
+ tc.error && /* @__PURE__ */ jsx4("p", {
495
641
  className: "text-destructive mt-1",
496
642
  children: tc.error
497
- }, undefined, false, undefined, this)
643
+ })
498
644
  ]
499
- }, undefined, true, undefined, this)
645
+ })
500
646
  ]
501
- }, tc.id, true, undefined, this))
502
- }, undefined, false, undefined, this)
647
+ }, tc.id))
648
+ })
503
649
  ]
504
- }, undefined, true, undefined, this)
650
+ })
505
651
  ]
506
- }, undefined, true, undefined, this);
652
+ });
507
653
  }
508
654
  // src/presentation/components/ChatInput.tsx
509
655
  import * as React4 from "react";
510
656
  import { cn as cn4 } from "@contractspec/lib.ui-kit-web/ui/utils";
511
657
  import { Textarea } from "@contractspec/lib.design-system";
512
658
  import { Button as Button3 } from "@contractspec/lib.design-system";
513
- import { Send, Paperclip, X, Loader2, FileText, Code } from "lucide-react";
514
- import { jsxDEV as jsxDEV4, Fragment as Fragment2 } from "react/jsx-dev-runtime";
659
+ import { Send, Paperclip, X as X2, Loader2, FileText, Code } from "lucide-react";
660
+ import { jsx as jsx5, jsxs as jsxs5, Fragment as Fragment2 } from "react/jsx-runtime";
515
661
  "use client";
516
662
  function ChatInput({
517
663
  onSend,
@@ -577,42 +723,42 @@ function ChatInput({
577
723
  const removeAttachment = React4.useCallback((id) => {
578
724
  setAttachments((prev) => prev.filter((a) => a.id !== id));
579
725
  }, []);
580
- return /* @__PURE__ */ jsxDEV4("div", {
726
+ return /* @__PURE__ */ jsxs5("div", {
581
727
  className: cn4("flex flex-col gap-2", className),
582
728
  children: [
583
- attachments.length > 0 && /* @__PURE__ */ jsxDEV4("div", {
729
+ attachments.length > 0 && /* @__PURE__ */ jsx5("div", {
584
730
  className: "flex flex-wrap gap-2",
585
- children: attachments.map((attachment) => /* @__PURE__ */ jsxDEV4("div", {
731
+ children: attachments.map((attachment) => /* @__PURE__ */ jsxs5("div", {
586
732
  className: cn4("flex items-center gap-1.5 rounded-md px-2 py-1", "bg-muted text-muted-foreground text-sm"),
587
733
  children: [
588
- attachment.type === "code" ? /* @__PURE__ */ jsxDEV4(Code, {
734
+ attachment.type === "code" ? /* @__PURE__ */ jsx5(Code, {
589
735
  className: "h-3.5 w-3.5"
590
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV4(FileText, {
736
+ }) : /* @__PURE__ */ jsx5(FileText, {
591
737
  className: "h-3.5 w-3.5"
592
- }, undefined, false, undefined, this),
593
- /* @__PURE__ */ jsxDEV4("span", {
738
+ }),
739
+ /* @__PURE__ */ jsx5("span", {
594
740
  className: "max-w-[150px] truncate",
595
741
  children: attachment.name
596
- }, undefined, false, undefined, this),
597
- /* @__PURE__ */ jsxDEV4("button", {
742
+ }),
743
+ /* @__PURE__ */ jsx5("button", {
598
744
  type: "button",
599
745
  onClick: () => removeAttachment(attachment.id),
600
746
  className: "hover:text-foreground",
601
747
  "aria-label": `Remove ${attachment.name}`,
602
- children: /* @__PURE__ */ jsxDEV4(X, {
748
+ children: /* @__PURE__ */ jsx5(X2, {
603
749
  className: "h-3.5 w-3.5"
604
- }, undefined, false, undefined, this)
605
- }, undefined, false, undefined, this)
750
+ })
751
+ })
606
752
  ]
607
- }, attachment.id, true, undefined, this))
608
- }, undefined, false, undefined, this),
609
- /* @__PURE__ */ jsxDEV4("form", {
753
+ }, attachment.id))
754
+ }),
755
+ /* @__PURE__ */ jsxs5("form", {
610
756
  onSubmit: handleSubmit,
611
757
  className: "flex items-end gap-2",
612
758
  children: [
613
- showAttachments && /* @__PURE__ */ jsxDEV4(Fragment2, {
759
+ showAttachments && /* @__PURE__ */ jsxs5(Fragment2, {
614
760
  children: [
615
- /* @__PURE__ */ jsxDEV4("input", {
761
+ /* @__PURE__ */ jsx5("input", {
616
762
  ref: fileInputRef,
617
763
  type: "file",
618
764
  multiple: true,
@@ -620,23 +766,23 @@ function ChatInput({
620
766
  onChange: handleFileSelect,
621
767
  className: "hidden",
622
768
  "aria-label": "Attach files"
623
- }, undefined, false, undefined, this),
624
- /* @__PURE__ */ jsxDEV4(Button3, {
769
+ }),
770
+ /* @__PURE__ */ jsx5(Button3, {
625
771
  type: "button",
626
772
  variant: "ghost",
627
773
  size: "sm",
628
774
  onPress: () => fileInputRef.current?.click(),
629
775
  disabled: disabled || attachments.length >= maxAttachments,
630
776
  "aria-label": "Attach files",
631
- children: /* @__PURE__ */ jsxDEV4(Paperclip, {
777
+ children: /* @__PURE__ */ jsx5(Paperclip, {
632
778
  className: "h-4 w-4"
633
- }, undefined, false, undefined, this)
634
- }, undefined, false, undefined, this)
779
+ })
780
+ })
635
781
  ]
636
- }, undefined, true, undefined, this),
637
- /* @__PURE__ */ jsxDEV4("div", {
782
+ }),
783
+ /* @__PURE__ */ jsx5("div", {
638
784
  className: "relative flex-1",
639
- children: /* @__PURE__ */ jsxDEV4(Textarea, {
785
+ children: /* @__PURE__ */ jsx5(Textarea, {
640
786
  value: content,
641
787
  onChange: (e) => setContent(e.target.value),
642
788
  onKeyDown: handleKeyDown,
@@ -645,32 +791,418 @@ function ChatInput({
645
791
  className: cn4("max-h-[200px] min-h-[44px] resize-none pr-12", "focus-visible:ring-1"),
646
792
  rows: 1,
647
793
  "aria-label": "Chat message"
648
- }, undefined, false, undefined, this)
649
- }, undefined, false, undefined, this),
650
- /* @__PURE__ */ jsxDEV4(Button3, {
794
+ })
795
+ }),
796
+ /* @__PURE__ */ jsx5(Button3, {
651
797
  type: "submit",
652
798
  disabled: !canSend || disabled || isLoading,
653
799
  size: "sm",
654
800
  "aria-label": isLoading ? "Sending..." : "Send message",
655
- children: isLoading ? /* @__PURE__ */ jsxDEV4(Loader2, {
801
+ children: isLoading ? /* @__PURE__ */ jsx5(Loader2, {
656
802
  className: "h-4 w-4 animate-spin"
657
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV4(Send, {
803
+ }) : /* @__PURE__ */ jsx5(Send, {
658
804
  className: "h-4 w-4"
659
- }, undefined, false, undefined, this)
660
- }, undefined, false, undefined, this)
805
+ })
806
+ })
661
807
  ]
662
- }, undefined, true, undefined, this),
663
- /* @__PURE__ */ jsxDEV4("p", {
808
+ }),
809
+ /* @__PURE__ */ jsx5("p", {
664
810
  className: "text-muted-foreground text-xs",
665
811
  children: "Press Enter to send, Shift+Enter for new line"
666
- }, undefined, false, undefined, this)
812
+ })
667
813
  ]
668
- }, undefined, true, undefined, this);
814
+ });
669
815
  }
670
- // src/presentation/components/ModelPicker.tsx
816
+ // src/presentation/components/ChatExportToolbar.tsx
671
817
  import * as React5 from "react";
672
- import { cn as cn5 } from "@contractspec/lib.ui-kit-web/ui/utils";
818
+ import { Download as Download2, FileText as FileText2, Copy as Copy3, Check as Check3, Plus, GitFork } from "lucide-react";
673
819
  import { Button as Button4 } from "@contractspec/lib.design-system";
820
+ import {
821
+ DropdownMenu,
822
+ DropdownMenuContent,
823
+ DropdownMenuItem,
824
+ DropdownMenuSeparator,
825
+ DropdownMenuTrigger
826
+ } from "@contractspec/lib.ui-kit-web/ui/dropdown-menu";
827
+
828
+ // src/core/export-formatters.ts
829
+ function formatTimestamp(date) {
830
+ return date.toLocaleTimeString([], {
831
+ hour: "2-digit",
832
+ minute: "2-digit"
833
+ });
834
+ }
835
+ function toIsoString(date) {
836
+ return date.toISOString();
837
+ }
838
+ function messageToJsonSerializable(msg) {
839
+ return {
840
+ id: msg.id,
841
+ conversationId: msg.conversationId,
842
+ role: msg.role,
843
+ content: msg.content,
844
+ status: msg.status,
845
+ createdAt: toIsoString(msg.createdAt),
846
+ updatedAt: toIsoString(msg.updatedAt),
847
+ ...msg.attachments && { attachments: msg.attachments },
848
+ ...msg.codeBlocks && { codeBlocks: msg.codeBlocks },
849
+ ...msg.toolCalls && { toolCalls: msg.toolCalls },
850
+ ...msg.sources && { sources: msg.sources },
851
+ ...msg.reasoning && { reasoning: msg.reasoning },
852
+ ...msg.usage && { usage: msg.usage },
853
+ ...msg.error && { error: msg.error },
854
+ ...msg.metadata && { metadata: msg.metadata }
855
+ };
856
+ }
857
+ function formatSourcesMarkdown(sources) {
858
+ if (sources.length === 0)
859
+ return "";
860
+ return `
861
+
862
+ **Sources:**
863
+ ` + sources.map((s) => `- [${s.title}](${s.url ?? "#"})`).join(`
864
+ `);
865
+ }
866
+ function formatSourcesTxt(sources) {
867
+ if (sources.length === 0)
868
+ return "";
869
+ return `
870
+
871
+ Sources:
872
+ ` + sources.map((s) => `- ${s.title}${s.url ? ` - ${s.url}` : ""}`).join(`
873
+ `);
874
+ }
875
+ function formatToolCallsMarkdown(toolCalls) {
876
+ if (toolCalls.length === 0)
877
+ return "";
878
+ return `
879
+
880
+ **Tool calls:**
881
+ ` + toolCalls.map((tc) => `**${tc.name}** (${tc.status})
882
+ \`\`\`json
883
+ ${JSON.stringify(tc.args, null, 2)}
884
+ \`\`\`` + (tc.result !== undefined ? `
885
+ Output:
886
+ \`\`\`json
887
+ ${typeof tc.result === "object" ? JSON.stringify(tc.result, null, 2) : String(tc.result)}
888
+ \`\`\`` : "") + (tc.error ? `
889
+ Error: ${tc.error}` : "")).join(`
890
+
891
+ `);
892
+ }
893
+ function formatToolCallsTxt(toolCalls) {
894
+ if (toolCalls.length === 0)
895
+ return "";
896
+ return `
897
+
898
+ Tool calls:
899
+ ` + toolCalls.map((tc) => `- ${tc.name} (${tc.status}): ${JSON.stringify(tc.args)}` + (tc.result !== undefined ? ` -> ${typeof tc.result === "object" ? JSON.stringify(tc.result) : String(tc.result)}` : "") + (tc.error ? ` [Error: ${tc.error}]` : "")).join(`
900
+ `);
901
+ }
902
+ function formatUsage(usage) {
903
+ const total = usage.inputTokens + usage.outputTokens;
904
+ return ` (${total} tokens)`;
905
+ }
906
+ function formatMessagesAsMarkdown(messages) {
907
+ const parts = [];
908
+ for (const msg of messages) {
909
+ const roleLabel = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
910
+ const header = `## ${roleLabel}`;
911
+ const timestamp = `*${formatTimestamp(msg.createdAt)}*`;
912
+ const usageSuffix = msg.usage ? formatUsage(msg.usage) : "";
913
+ const meta = `${timestamp}${usageSuffix}
914
+
915
+ `;
916
+ let body = msg.content;
917
+ if (msg.error) {
918
+ body += `
919
+
920
+ **Error:** ${msg.error.code} - ${msg.error.message}`;
921
+ }
922
+ if (msg.reasoning) {
923
+ body += `
924
+
925
+ > **Reasoning:**
926
+ > ${msg.reasoning.replace(/\n/g, `
927
+ > `)}`;
928
+ }
929
+ body += formatSourcesMarkdown(msg.sources ?? []);
930
+ body += formatToolCallsMarkdown(msg.toolCalls ?? []);
931
+ parts.push(`${header}
932
+
933
+ ${meta}${body}`);
934
+ }
935
+ return parts.join(`
936
+
937
+ ---
938
+
939
+ `);
940
+ }
941
+ function formatMessagesAsTxt(messages) {
942
+ const parts = [];
943
+ for (const msg of messages) {
944
+ const roleLabel = msg.role === "user" ? "User" : msg.role === "assistant" ? "Assistant" : "System";
945
+ const timestamp = `(${formatTimestamp(msg.createdAt)})`;
946
+ const usageSuffix = msg.usage ? formatUsage(msg.usage) : "";
947
+ const header = `[${roleLabel}] ${timestamp}${usageSuffix}
948
+
949
+ `;
950
+ let body = msg.content;
951
+ if (msg.error) {
952
+ body += `
953
+
954
+ Error: ${msg.error.code} - ${msg.error.message}`;
955
+ }
956
+ if (msg.reasoning) {
957
+ body += `
958
+
959
+ Reasoning: ${msg.reasoning}`;
960
+ }
961
+ body += formatSourcesTxt(msg.sources ?? []);
962
+ body += formatToolCallsTxt(msg.toolCalls ?? []);
963
+ parts.push(`${header}${body}`);
964
+ }
965
+ return parts.join(`
966
+
967
+ ---
968
+
969
+ `);
970
+ }
971
+ function formatMessagesAsJson(messages, conversation) {
972
+ const payload = {
973
+ messages: messages.map(messageToJsonSerializable)
974
+ };
975
+ if (conversation) {
976
+ payload.conversation = {
977
+ id: conversation.id,
978
+ title: conversation.title,
979
+ status: conversation.status,
980
+ createdAt: toIsoString(conversation.createdAt),
981
+ updatedAt: toIsoString(conversation.updatedAt),
982
+ provider: conversation.provider,
983
+ model: conversation.model,
984
+ workspacePath: conversation.workspacePath,
985
+ contextFiles: conversation.contextFiles,
986
+ summary: conversation.summary,
987
+ metadata: conversation.metadata
988
+ };
989
+ }
990
+ return JSON.stringify(payload, null, 2);
991
+ }
992
+ function getExportFilename(format, conversation) {
993
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
994
+ const base = conversation?.title ? conversation.title.replace(/[^a-zA-Z0-9-_]/g, "_").slice(0, 40) : "chat-export";
995
+ const ext = format === "markdown" ? "md" : format === "txt" ? "txt" : "json";
996
+ return `${base}-${timestamp}.${ext}`;
997
+ }
998
+ var MIME_TYPES = {
999
+ markdown: "text/markdown",
1000
+ txt: "text/plain",
1001
+ json: "application/json"
1002
+ };
1003
+ function downloadAsFile(content, filename, mimeType) {
1004
+ const blob = new Blob([content], { type: mimeType });
1005
+ const url = URL.createObjectURL(blob);
1006
+ const a = document.createElement("a");
1007
+ a.href = url;
1008
+ a.download = filename;
1009
+ document.body.appendChild(a);
1010
+ a.click();
1011
+ document.body.removeChild(a);
1012
+ URL.revokeObjectURL(url);
1013
+ }
1014
+ function exportToFile(messages, format, conversation) {
1015
+ let content;
1016
+ if (format === "markdown") {
1017
+ content = formatMessagesAsMarkdown(messages);
1018
+ } else if (format === "txt") {
1019
+ content = formatMessagesAsTxt(messages);
1020
+ } else {
1021
+ content = formatMessagesAsJson(messages, conversation);
1022
+ }
1023
+ const filename = getExportFilename(format, conversation);
1024
+ const mimeType = MIME_TYPES[format];
1025
+ downloadAsFile(content, filename, mimeType);
1026
+ }
1027
+
1028
+ // src/presentation/components/ChatExportToolbar.tsx
1029
+ import { jsx as jsx6, jsxs as jsxs6, Fragment as Fragment3 } from "react/jsx-runtime";
1030
+ "use client";
1031
+ function ChatExportToolbar({
1032
+ messages,
1033
+ conversation,
1034
+ selectedIds,
1035
+ onExported,
1036
+ showSelectionSummary = true,
1037
+ onSelectAll,
1038
+ onClearSelection,
1039
+ selectedCount = selectedIds.size,
1040
+ totalCount = messages.length,
1041
+ onCreateNew,
1042
+ onFork
1043
+ }) {
1044
+ const [copied, setCopied] = React5.useState(false);
1045
+ const toExport = React5.useMemo(() => {
1046
+ if (selectedIds.size > 0) {
1047
+ const idSet = selectedIds;
1048
+ return messages.filter((m) => idSet.has(m.id));
1049
+ }
1050
+ return messages;
1051
+ }, [messages, selectedIds]);
1052
+ const handleExport = React5.useCallback((format) => {
1053
+ exportToFile(toExport, format, conversation);
1054
+ onExported?.(format, toExport.length);
1055
+ }, [toExport, conversation, onExported]);
1056
+ const handleCopy = React5.useCallback(async () => {
1057
+ const content = formatMessagesAsMarkdown(toExport);
1058
+ await navigator.clipboard.writeText(content);
1059
+ setCopied(true);
1060
+ setTimeout(() => setCopied(false), 2000);
1061
+ onExported?.("markdown", toExport.length);
1062
+ }, [toExport, onExported]);
1063
+ const disabled = messages.length === 0;
1064
+ const [forking, setForking] = React5.useState(false);
1065
+ const handleFork = React5.useCallback(async (upToMessageId) => {
1066
+ if (!onFork)
1067
+ return;
1068
+ setForking(true);
1069
+ try {
1070
+ await onFork(upToMessageId);
1071
+ } finally {
1072
+ setForking(false);
1073
+ }
1074
+ }, [onFork]);
1075
+ return /* @__PURE__ */ jsxs6("div", {
1076
+ className: "flex items-center gap-2",
1077
+ children: [
1078
+ onCreateNew && /* @__PURE__ */ jsxs6(Button4, {
1079
+ variant: "outline",
1080
+ size: "sm",
1081
+ onPress: onCreateNew,
1082
+ "aria-label": "New conversation",
1083
+ children: [
1084
+ /* @__PURE__ */ jsx6(Plus, {
1085
+ className: "h-4 w-4"
1086
+ }),
1087
+ "New"
1088
+ ]
1089
+ }),
1090
+ onFork && messages.length > 0 && /* @__PURE__ */ jsxs6(Button4, {
1091
+ variant: "outline",
1092
+ size: "sm",
1093
+ disabled: forking,
1094
+ onPress: () => handleFork(),
1095
+ "aria-label": "Fork conversation",
1096
+ children: [
1097
+ /* @__PURE__ */ jsx6(GitFork, {
1098
+ className: "h-4 w-4"
1099
+ }),
1100
+ "Fork"
1101
+ ]
1102
+ }),
1103
+ showSelectionSummary && selectedCount > 0 && /* @__PURE__ */ jsxs6("span", {
1104
+ className: "text-muted-foreground text-sm",
1105
+ children: [
1106
+ selectedCount,
1107
+ " message",
1108
+ selectedCount !== 1 ? "s" : "",
1109
+ " selected"
1110
+ ]
1111
+ }),
1112
+ onSelectAll && onClearSelection && totalCount > 0 && /* @__PURE__ */ jsxs6(Fragment3, {
1113
+ children: [
1114
+ /* @__PURE__ */ jsx6(Button4, {
1115
+ variant: "ghost",
1116
+ size: "sm",
1117
+ onPress: onSelectAll,
1118
+ className: "text-xs",
1119
+ children: "Select all"
1120
+ }),
1121
+ selectedCount > 0 && /* @__PURE__ */ jsx6(Button4, {
1122
+ variant: "ghost",
1123
+ size: "sm",
1124
+ onPress: onClearSelection,
1125
+ className: "text-xs",
1126
+ children: "Clear"
1127
+ })
1128
+ ]
1129
+ }),
1130
+ /* @__PURE__ */ jsxs6(DropdownMenu, {
1131
+ children: [
1132
+ /* @__PURE__ */ jsx6(DropdownMenuTrigger, {
1133
+ asChild: true,
1134
+ children: /* @__PURE__ */ jsxs6(Button4, {
1135
+ variant: "outline",
1136
+ size: "sm",
1137
+ disabled,
1138
+ "aria-label": selectedCount > 0 ? "Export selected messages" : "Export conversation",
1139
+ children: [
1140
+ /* @__PURE__ */ jsx6(Download2, {
1141
+ className: "h-4 w-4"
1142
+ }),
1143
+ "Export"
1144
+ ]
1145
+ })
1146
+ }),
1147
+ /* @__PURE__ */ jsxs6(DropdownMenuContent, {
1148
+ align: "end",
1149
+ children: [
1150
+ /* @__PURE__ */ jsxs6(DropdownMenuItem, {
1151
+ onSelect: () => handleExport("markdown"),
1152
+ disabled,
1153
+ children: [
1154
+ /* @__PURE__ */ jsx6(FileText2, {
1155
+ className: "h-4 w-4"
1156
+ }),
1157
+ "Export as Markdown (.md)"
1158
+ ]
1159
+ }),
1160
+ /* @__PURE__ */ jsxs6(DropdownMenuItem, {
1161
+ onSelect: () => handleExport("txt"),
1162
+ disabled,
1163
+ children: [
1164
+ /* @__PURE__ */ jsx6(FileText2, {
1165
+ className: "h-4 w-4"
1166
+ }),
1167
+ "Export as Plain Text (.txt)"
1168
+ ]
1169
+ }),
1170
+ /* @__PURE__ */ jsxs6(DropdownMenuItem, {
1171
+ onSelect: () => handleExport("json"),
1172
+ disabled,
1173
+ children: [
1174
+ /* @__PURE__ */ jsx6(FileText2, {
1175
+ className: "h-4 w-4"
1176
+ }),
1177
+ "Export as JSON (.json)"
1178
+ ]
1179
+ }),
1180
+ /* @__PURE__ */ jsx6(DropdownMenuSeparator, {}),
1181
+ /* @__PURE__ */ jsxs6(DropdownMenuItem, {
1182
+ onSelect: () => handleCopy(),
1183
+ disabled,
1184
+ children: [
1185
+ copied ? /* @__PURE__ */ jsx6(Check3, {
1186
+ className: "h-4 w-4 text-green-500"
1187
+ }) : /* @__PURE__ */ jsx6(Copy3, {
1188
+ className: "h-4 w-4"
1189
+ }),
1190
+ copied ? "Copied to clipboard" : "Copy to clipboard"
1191
+ ]
1192
+ })
1193
+ ]
1194
+ })
1195
+ ]
1196
+ })
1197
+ ]
1198
+ });
1199
+ }
1200
+ // src/presentation/components/ChatWithExport.tsx
1201
+ import * as React8 from "react";
1202
+
1203
+ // src/presentation/components/ThinkingLevelPicker.tsx
1204
+ import * as React6 from "react";
1205
+ import { cn as cn5 } from "@contractspec/lib.ui-kit-web/ui/utils";
674
1206
  import {
675
1207
  Select,
676
1208
  SelectContent,
@@ -678,402 +1210,487 @@ import {
678
1210
  SelectTrigger,
679
1211
  SelectValue
680
1212
  } from "@contractspec/lib.ui-kit-web/ui/select";
681
- import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
682
1213
  import { Label } from "@contractspec/lib.ui-kit-web/ui/label";
683
- import { Bot as Bot2, Cloud, Cpu, Sparkles } from "lucide-react";
684
- import {
685
- getModelsForProvider
686
- } from "@contractspec/lib.ai-providers";
687
- import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
688
- "use client";
689
- var PROVIDER_ICONS = {
690
- ollama: /* @__PURE__ */ jsxDEV5(Cpu, {
691
- className: "h-4 w-4"
692
- }, undefined, false, undefined, this),
693
- openai: /* @__PURE__ */ jsxDEV5(Bot2, {
694
- className: "h-4 w-4"
695
- }, undefined, false, undefined, this),
696
- anthropic: /* @__PURE__ */ jsxDEV5(Sparkles, {
697
- className: "h-4 w-4"
698
- }, undefined, false, undefined, this),
699
- mistral: /* @__PURE__ */ jsxDEV5(Cloud, {
700
- className: "h-4 w-4"
701
- }, undefined, false, undefined, this),
702
- gemini: /* @__PURE__ */ jsxDEV5(Sparkles, {
703
- className: "h-4 w-4"
704
- }, undefined, false, undefined, this)
705
- };
706
- var PROVIDER_NAMES = {
707
- ollama: "Ollama (Local)",
708
- openai: "OpenAI",
709
- anthropic: "Anthropic",
710
- mistral: "Mistral",
711
- gemini: "Google Gemini"
1214
+
1215
+ // src/core/thinking-levels.ts
1216
+ var THINKING_LEVEL_LABELS = {
1217
+ instant: "Instant",
1218
+ thinking: "Thinking",
1219
+ extra_thinking: "Extra Thinking",
1220
+ max: "Max"
712
1221
  };
713
- var MODE_BADGES = {
714
- local: { label: "Local", variant: "secondary" },
715
- byok: { label: "BYOK", variant: "outline" },
716
- managed: { label: "Managed", variant: "default" }
1222
+ var THINKING_LEVEL_DESCRIPTIONS = {
1223
+ instant: "Fast responses, minimal reasoning",
1224
+ thinking: "Standard reasoning depth",
1225
+ extra_thinking: "More thorough reasoning",
1226
+ max: "Maximum reasoning depth"
717
1227
  };
718
- function ModelPicker({
1228
+ function getProviderOptions(level, providerName) {
1229
+ if (!level || level === "instant") {
1230
+ return {};
1231
+ }
1232
+ switch (providerName) {
1233
+ case "anthropic": {
1234
+ const budgetMap = {
1235
+ thinking: 8000,
1236
+ extra_thinking: 16000,
1237
+ max: 32000
1238
+ };
1239
+ return {
1240
+ anthropic: {
1241
+ thinking: { type: "enabled", budgetTokens: budgetMap[level] }
1242
+ }
1243
+ };
1244
+ }
1245
+ case "openai": {
1246
+ const effortMap = {
1247
+ thinking: "low",
1248
+ extra_thinking: "medium",
1249
+ max: "high"
1250
+ };
1251
+ return {
1252
+ openai: {
1253
+ reasoningEffort: effortMap[level]
1254
+ }
1255
+ };
1256
+ }
1257
+ case "ollama":
1258
+ case "mistral":
1259
+ case "gemini":
1260
+ return {};
1261
+ default:
1262
+ return {};
1263
+ }
1264
+ }
1265
+
1266
+ // src/presentation/components/ThinkingLevelPicker.tsx
1267
+ import { jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
1268
+ "use client";
1269
+ var THINKING_LEVELS = [
1270
+ "instant",
1271
+ "thinking",
1272
+ "extra_thinking",
1273
+ "max"
1274
+ ];
1275
+ function ThinkingLevelPicker({
719
1276
  value,
720
1277
  onChange,
721
- availableProviders,
722
1278
  className,
723
1279
  compact = false
724
1280
  }) {
725
- const providers = availableProviders ?? [
726
- { provider: "ollama", available: true, mode: "local" },
727
- { provider: "openai", available: true, mode: "byok" },
728
- { provider: "anthropic", available: true, mode: "byok" },
729
- { provider: "mistral", available: true, mode: "byok" },
730
- { provider: "gemini", available: true, mode: "byok" }
731
- ];
732
- const models = getModelsForProvider(value.provider);
733
- const selectedModel = models.find((m) => m.id === value.model);
734
- const handleProviderChange = React5.useCallback((providerName) => {
735
- const provider = providerName;
736
- const providerInfo = providers.find((p) => p.provider === provider);
737
- const providerModels = getModelsForProvider(provider);
738
- const defaultModel = providerModels[0]?.id ?? "";
739
- onChange({
740
- provider,
741
- model: defaultModel,
742
- mode: providerInfo?.mode ?? "byok"
743
- });
744
- }, [onChange, providers]);
745
- const handleModelChange = React5.useCallback((modelId) => {
746
- onChange({
747
- ...value,
748
- model: modelId
749
- });
750
- }, [onChange, value]);
1281
+ const handleChange = React6.useCallback((v) => {
1282
+ onChange(v);
1283
+ }, [onChange]);
751
1284
  if (compact) {
752
- return /* @__PURE__ */ jsxDEV5("div", {
753
- className: cn5("flex items-center gap-2", className),
1285
+ return /* @__PURE__ */ jsxs7(Select, {
1286
+ value,
1287
+ onValueChange: handleChange,
754
1288
  children: [
755
- /* @__PURE__ */ jsxDEV5(Select, {
756
- value: value.provider,
757
- onValueChange: handleProviderChange,
758
- children: [
759
- /* @__PURE__ */ jsxDEV5(SelectTrigger, {
760
- className: "w-[140px]",
761
- children: /* @__PURE__ */ jsxDEV5(SelectValue, {}, undefined, false, undefined, this)
762
- }, undefined, false, undefined, this),
763
- /* @__PURE__ */ jsxDEV5(SelectContent, {
764
- children: providers.map((p) => /* @__PURE__ */ jsxDEV5(SelectItem, {
765
- value: p.provider,
766
- disabled: !p.available,
767
- children: /* @__PURE__ */ jsxDEV5("div", {
768
- className: "flex items-center gap-2",
769
- children: [
770
- PROVIDER_ICONS[p.provider],
771
- /* @__PURE__ */ jsxDEV5("span", {
772
- children: PROVIDER_NAMES[p.provider]
773
- }, undefined, false, undefined, this)
774
- ]
775
- }, undefined, true, undefined, this)
776
- }, p.provider, false, undefined, this))
777
- }, undefined, false, undefined, this)
778
- ]
779
- }, undefined, true, undefined, this),
780
- /* @__PURE__ */ jsxDEV5(Select, {
781
- value: value.model,
782
- onValueChange: handleModelChange,
783
- children: [
784
- /* @__PURE__ */ jsxDEV5(SelectTrigger, {
785
- className: "w-[160px]",
786
- children: /* @__PURE__ */ jsxDEV5(SelectValue, {}, undefined, false, undefined, this)
787
- }, undefined, false, undefined, this),
788
- /* @__PURE__ */ jsxDEV5(SelectContent, {
789
- children: models.map((m) => /* @__PURE__ */ jsxDEV5(SelectItem, {
790
- value: m.id,
791
- children: m.name
792
- }, m.id, false, undefined, this))
793
- }, undefined, false, undefined, this)
794
- ]
795
- }, undefined, true, undefined, this)
1289
+ /* @__PURE__ */ jsx7(SelectTrigger, {
1290
+ className: cn5("w-[140px]", className),
1291
+ children: /* @__PURE__ */ jsx7(SelectValue, {})
1292
+ }),
1293
+ /* @__PURE__ */ jsx7(SelectContent, {
1294
+ children: THINKING_LEVELS.map((level) => /* @__PURE__ */ jsx7(SelectItem, {
1295
+ value: level,
1296
+ children: THINKING_LEVEL_LABELS[level]
1297
+ }, level))
1298
+ })
796
1299
  ]
797
- }, undefined, true, undefined, this);
1300
+ });
798
1301
  }
799
- return /* @__PURE__ */ jsxDEV5("div", {
800
- className: cn5("flex flex-col gap-3", className),
1302
+ return /* @__PURE__ */ jsxs7("div", {
1303
+ className: cn5("flex flex-col gap-1.5", className),
801
1304
  children: [
802
- /* @__PURE__ */ jsxDEV5("div", {
803
- className: "flex flex-col gap-1.5",
1305
+ /* @__PURE__ */ jsx7(Label, {
1306
+ htmlFor: "thinking-level-picker",
1307
+ className: "text-sm font-medium",
1308
+ children: "Thinking Level"
1309
+ }),
1310
+ /* @__PURE__ */ jsxs7(Select, {
1311
+ name: "thinking-level-picker",
1312
+ value,
1313
+ onValueChange: handleChange,
804
1314
  children: [
805
- /* @__PURE__ */ jsxDEV5(Label, {
806
- htmlFor: "provider-selection",
807
- className: "text-sm font-medium",
808
- children: "Provider"
809
- }, undefined, false, undefined, this),
810
- /* @__PURE__ */ jsxDEV5("div", {
811
- className: "flex flex-wrap gap-2",
812
- id: "provider-selection",
813
- children: providers.map((p) => /* @__PURE__ */ jsxDEV5(Button4, {
814
- variant: value.provider === p.provider ? "default" : "outline",
815
- size: "sm",
816
- onPress: () => p.available && handleProviderChange(p.provider),
817
- disabled: !p.available,
818
- className: cn5(!p.available && "opacity-50"),
819
- children: [
820
- PROVIDER_ICONS[p.provider],
821
- /* @__PURE__ */ jsxDEV5("span", {
822
- children: PROVIDER_NAMES[p.provider]
823
- }, undefined, false, undefined, this),
824
- /* @__PURE__ */ jsxDEV5(Badge, {
825
- variant: MODE_BADGES[p.mode].variant,
826
- className: "ml-1",
827
- children: MODE_BADGES[p.mode].label
828
- }, undefined, false, undefined, this)
829
- ]
830
- }, p.provider, true, undefined, this))
831
- }, undefined, false, undefined, this)
1315
+ /* @__PURE__ */ jsx7(SelectTrigger, {
1316
+ children: /* @__PURE__ */ jsx7(SelectValue, {
1317
+ placeholder: "Select thinking level"
1318
+ })
1319
+ }),
1320
+ /* @__PURE__ */ jsx7(SelectContent, {
1321
+ children: THINKING_LEVELS.map((level) => /* @__PURE__ */ jsx7(SelectItem, {
1322
+ value: level,
1323
+ title: THINKING_LEVEL_DESCRIPTIONS[level],
1324
+ children: THINKING_LEVEL_LABELS[level]
1325
+ }, level))
1326
+ })
832
1327
  ]
833
- }, undefined, true, undefined, this),
834
- /* @__PURE__ */ jsxDEV5("div", {
835
- className: "flex flex-col gap-1.5",
836
- children: [
837
- /* @__PURE__ */ jsxDEV5(Label, {
838
- htmlFor: "model-picker",
839
- className: "text-sm font-medium",
840
- children: "Model"
841
- }, undefined, false, undefined, this),
842
- /* @__PURE__ */ jsxDEV5(Select, {
843
- name: "model-picker",
844
- value: value.model,
845
- onValueChange: handleModelChange,
846
- children: [
847
- /* @__PURE__ */ jsxDEV5(SelectTrigger, {
848
- children: /* @__PURE__ */ jsxDEV5(SelectValue, {
849
- placeholder: "Select a model"
850
- }, undefined, false, undefined, this)
851
- }, undefined, false, undefined, this),
852
- /* @__PURE__ */ jsxDEV5(SelectContent, {
853
- children: models.map((m) => /* @__PURE__ */ jsxDEV5(SelectItem, {
854
- value: m.id,
855
- children: /* @__PURE__ */ jsxDEV5("div", {
856
- className: "flex items-center gap-2",
857
- children: [
858
- /* @__PURE__ */ jsxDEV5("span", {
859
- children: m.name
860
- }, undefined, false, undefined, this),
861
- /* @__PURE__ */ jsxDEV5("span", {
862
- className: "text-muted-foreground text-xs",
863
- children: [
864
- Math.round(m.contextWindow / 1000),
865
- "K"
866
- ]
867
- }, undefined, true, undefined, this),
868
- m.capabilities.vision && /* @__PURE__ */ jsxDEV5(Badge, {
869
- variant: "outline",
870
- className: "text-xs",
871
- children: "Vision"
872
- }, undefined, false, undefined, this),
873
- m.capabilities.reasoning && /* @__PURE__ */ jsxDEV5(Badge, {
874
- variant: "outline",
875
- className: "text-xs",
876
- children: "Reasoning"
877
- }, undefined, false, undefined, this)
878
- ]
879
- }, undefined, true, undefined, this)
880
- }, m.id, false, undefined, this))
881
- }, undefined, false, undefined, this)
882
- ]
883
- }, undefined, true, undefined, this)
884
- ]
885
- }, undefined, true, undefined, this),
886
- selectedModel && /* @__PURE__ */ jsxDEV5("div", {
887
- className: "text-muted-foreground flex flex-wrap gap-2 text-xs",
888
- children: [
889
- /* @__PURE__ */ jsxDEV5("span", {
890
- children: [
891
- "Context: ",
892
- Math.round(selectedModel.contextWindow / 1000),
893
- "K tokens"
894
- ]
895
- }, undefined, true, undefined, this),
896
- selectedModel.capabilities.vision && /* @__PURE__ */ jsxDEV5("span", {
897
- children: "• Vision"
898
- }, undefined, false, undefined, this),
899
- selectedModel.capabilities.tools && /* @__PURE__ */ jsxDEV5("span", {
900
- children: "• Tools"
901
- }, undefined, false, undefined, this),
902
- selectedModel.capabilities.reasoning && /* @__PURE__ */ jsxDEV5("span", {
903
- children: "• Reasoning"
904
- }, undefined, false, undefined, this)
905
- ]
906
- }, undefined, true, undefined, this)
1328
+ })
907
1329
  ]
908
- }, undefined, true, undefined, this);
1330
+ });
909
1331
  }
910
- // src/presentation/components/ContextIndicator.tsx
911
- import { cn as cn6 } from "@contractspec/lib.ui-kit-web/ui/utils";
912
- import { Badge as Badge2 } from "@contractspec/lib.ui-kit-web/ui/badge";
913
- import {
914
- Tooltip,
915
- TooltipContent,
916
- TooltipProvider,
917
- TooltipTrigger
918
- } from "@contractspec/lib.ui-kit-web/ui/tooltip";
919
- import { FolderOpen, FileCode, Zap, Info } from "lucide-react";
920
- import { jsxDEV as jsxDEV6, Fragment as Fragment3 } from "react/jsx-dev-runtime";
1332
+
1333
+ // src/presentation/hooks/useMessageSelection.ts
1334
+ import * as React7 from "react";
921
1335
  "use client";
922
- function ContextIndicator({
923
- summary,
924
- active = false,
1336
+ function useMessageSelection(messageIds) {
1337
+ const [selectedIds, setSelectedIds] = React7.useState(() => new Set);
1338
+ const idSet = React7.useMemo(() => new Set(messageIds), [messageIds.join(",")]);
1339
+ React7.useEffect(() => {
1340
+ setSelectedIds((prev) => {
1341
+ const next = new Set;
1342
+ for (const id of prev) {
1343
+ if (idSet.has(id))
1344
+ next.add(id);
1345
+ }
1346
+ return next.size === prev.size ? prev : next;
1347
+ });
1348
+ }, [idSet]);
1349
+ const toggle = React7.useCallback((id) => {
1350
+ setSelectedIds((prev) => {
1351
+ const next = new Set(prev);
1352
+ if (next.has(id))
1353
+ next.delete(id);
1354
+ else
1355
+ next.add(id);
1356
+ return next;
1357
+ });
1358
+ }, []);
1359
+ const selectAll = React7.useCallback(() => {
1360
+ setSelectedIds(new Set(messageIds));
1361
+ }, [messageIds.join(",")]);
1362
+ const clearSelection = React7.useCallback(() => {
1363
+ setSelectedIds(new Set);
1364
+ }, []);
1365
+ const isSelected = React7.useCallback((id) => selectedIds.has(id), [selectedIds]);
1366
+ const selectedCount = selectedIds.size;
1367
+ return {
1368
+ selectedIds,
1369
+ toggle,
1370
+ selectAll,
1371
+ clearSelection,
1372
+ isSelected,
1373
+ selectedCount
1374
+ };
1375
+ }
1376
+
1377
+ // src/presentation/components/ChatWithExport.tsx
1378
+ import { jsx as jsx8, jsxs as jsxs8, Fragment as Fragment4 } from "react/jsx-runtime";
1379
+ "use client";
1380
+ function ChatWithExport({
1381
+ messages,
1382
+ conversation,
1383
+ children,
925
1384
  className,
926
- showDetails = true
1385
+ showExport = true,
1386
+ showMessageSelection = true,
1387
+ showScrollButton = true,
1388
+ onCreateNew,
1389
+ onFork,
1390
+ onEditMessage,
1391
+ thinkingLevel = "thinking",
1392
+ onThinkingLevelChange,
1393
+ presentationRenderer,
1394
+ formRenderer
927
1395
  }) {
928
- if (!summary && !active) {
929
- return /* @__PURE__ */ jsxDEV6("div", {
930
- className: cn6("flex items-center gap-1.5 text-sm", "text-muted-foreground", className),
931
- children: [
932
- /* @__PURE__ */ jsxDEV6(Info, {
933
- className: "h-4 w-4"
934
- }, undefined, false, undefined, this),
935
- /* @__PURE__ */ jsxDEV6("span", {
936
- children: "No workspace context"
937
- }, undefined, false, undefined, this)
938
- ]
939
- }, undefined, true, undefined, this);
1396
+ const messageIds = React8.useMemo(() => messages.map((m) => m.id), [messages]);
1397
+ const selection = useMessageSelection(messageIds);
1398
+ const hasToolbar = showExport || showMessageSelection;
1399
+ const hasPicker = Boolean(onThinkingLevelChange);
1400
+ const headerContent = hasPicker || hasToolbar ? /* @__PURE__ */ jsxs8(Fragment4, {
1401
+ children: [
1402
+ hasPicker && /* @__PURE__ */ jsx8(ThinkingLevelPicker, {
1403
+ value: thinkingLevel,
1404
+ onChange: onThinkingLevelChange,
1405
+ compact: true
1406
+ }),
1407
+ hasToolbar && /* @__PURE__ */ jsx8(ChatExportToolbar, {
1408
+ messages,
1409
+ conversation,
1410
+ selectedIds: selection.selectedIds,
1411
+ showSelectionSummary: showMessageSelection,
1412
+ onSelectAll: showMessageSelection ? selection.selectAll : undefined,
1413
+ onClearSelection: showMessageSelection ? selection.clearSelection : undefined,
1414
+ selectedCount: selection.selectedCount,
1415
+ totalCount: messages.length,
1416
+ onCreateNew,
1417
+ onFork
1418
+ })
1419
+ ]
1420
+ }) : null;
1421
+ return /* @__PURE__ */ jsxs8(ChatContainer, {
1422
+ className,
1423
+ headerContent,
1424
+ showScrollButton,
1425
+ children: [
1426
+ messages.map((msg) => /* @__PURE__ */ jsx8(ChatMessage, {
1427
+ message: msg,
1428
+ selectable: showMessageSelection,
1429
+ selected: selection.isSelected(msg.id),
1430
+ onSelect: showMessageSelection ? selection.toggle : undefined,
1431
+ editable: msg.role === "user" && !!onEditMessage,
1432
+ onEdit: onEditMessage,
1433
+ presentationRenderer,
1434
+ formRenderer
1435
+ }, msg.id)),
1436
+ children
1437
+ ]
1438
+ });
1439
+ }
1440
+ // src/presentation/components/ChatSidebar.tsx
1441
+ import * as React10 from "react";
1442
+ import { Plus as Plus2, Trash2, MessageSquare } from "lucide-react";
1443
+ import { Button as Button5 } from "@contractspec/lib.design-system";
1444
+ import { cn as cn6 } from "@contractspec/lib.ui-kit-web/ui/utils";
1445
+
1446
+ // src/presentation/hooks/useConversations.ts
1447
+ import * as React9 from "react";
1448
+ "use client";
1449
+ function useConversations(options) {
1450
+ const { store, projectId, tags, limit = 50 } = options;
1451
+ const [conversations, setConversations] = React9.useState([]);
1452
+ const [isLoading, setIsLoading] = React9.useState(true);
1453
+ const refresh = React9.useCallback(async () => {
1454
+ setIsLoading(true);
1455
+ try {
1456
+ const list = await store.list({
1457
+ status: "active",
1458
+ projectId,
1459
+ tags,
1460
+ limit
1461
+ });
1462
+ setConversations(list);
1463
+ } finally {
1464
+ setIsLoading(false);
1465
+ }
1466
+ }, [store, projectId, tags, limit]);
1467
+ React9.useEffect(() => {
1468
+ refresh();
1469
+ }, [refresh]);
1470
+ const deleteConversation = React9.useCallback(async (id) => {
1471
+ const ok = await store.delete(id);
1472
+ if (ok) {
1473
+ setConversations((prev) => prev.filter((c) => c.id !== id));
1474
+ }
1475
+ return ok;
1476
+ }, [store]);
1477
+ return {
1478
+ conversations,
1479
+ isLoading,
1480
+ refresh,
1481
+ deleteConversation
1482
+ };
1483
+ }
1484
+
1485
+ // src/presentation/components/ChatSidebar.tsx
1486
+ import { jsx as jsx9, jsxs as jsxs9, Fragment as Fragment5 } from "react/jsx-runtime";
1487
+ "use client";
1488
+ function formatDate(date) {
1489
+ const d = new Date(date);
1490
+ const now = new Date;
1491
+ const diff = now.getTime() - d.getTime();
1492
+ if (diff < 86400000) {
1493
+ return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
940
1494
  }
941
- const content = /* @__PURE__ */ jsxDEV6("div", {
942
- className: cn6("flex items-center gap-2", active ? "text-foreground" : "text-muted-foreground", className),
1495
+ if (diff < 604800000) {
1496
+ return d.toLocaleDateString([], { weekday: "short" });
1497
+ }
1498
+ return d.toLocaleDateString([], { month: "short", day: "numeric" });
1499
+ }
1500
+ function ConversationItem({
1501
+ conversation,
1502
+ selected,
1503
+ onSelect,
1504
+ onDelete
1505
+ }) {
1506
+ const title = conversation.title ?? conversation.messages[0]?.content?.slice(0, 50) ?? "New chat";
1507
+ const displayTitle = title.length > 40 ? `${title.slice(0, 40)}…` : title;
1508
+ return /* @__PURE__ */ jsxs9("div", {
1509
+ role: "button",
1510
+ tabIndex: 0,
1511
+ onClick: onSelect,
1512
+ onKeyDown: (e) => {
1513
+ if (e.key === "Enter" || e.key === " ") {
1514
+ e.preventDefault();
1515
+ onSelect();
1516
+ }
1517
+ },
1518
+ className: cn6("group flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors", selected ? "bg-accent text-accent-foreground" : "hover:bg-accent/50"),
943
1519
  children: [
944
- /* @__PURE__ */ jsxDEV6(Badge2, {
945
- variant: active ? "default" : "secondary",
946
- className: "flex items-center gap-1",
947
- children: [
948
- /* @__PURE__ */ jsxDEV6(Zap, {
949
- className: "h-3 w-3"
950
- }, undefined, false, undefined, this),
951
- "Context"
952
- ]
953
- }, undefined, true, undefined, this),
954
- summary && showDetails && /* @__PURE__ */ jsxDEV6(Fragment3, {
1520
+ /* @__PURE__ */ jsx9(MessageSquare, {
1521
+ className: "text-muted-foreground h-4 w-4 shrink-0"
1522
+ }),
1523
+ /* @__PURE__ */ jsxs9("div", {
1524
+ className: "min-w-0 flex-1",
955
1525
  children: [
956
- /* @__PURE__ */ jsxDEV6("div", {
957
- className: "flex items-center gap-1 text-xs",
958
- children: [
959
- /* @__PURE__ */ jsxDEV6(FolderOpen, {
960
- className: "h-3.5 w-3.5"
961
- }, undefined, false, undefined, this),
962
- /* @__PURE__ */ jsxDEV6("span", {
963
- children: summary.name
964
- }, undefined, false, undefined, this)
965
- ]
966
- }, undefined, true, undefined, this),
967
- /* @__PURE__ */ jsxDEV6("div", {
968
- className: "flex items-center gap-1 text-xs",
1526
+ /* @__PURE__ */ jsx9("p", {
1527
+ className: "truncate",
1528
+ children: displayTitle
1529
+ }),
1530
+ /* @__PURE__ */ jsxs9("p", {
1531
+ className: "text-muted-foreground text-xs",
969
1532
  children: [
970
- /* @__PURE__ */ jsxDEV6(FileCode, {
971
- className: "h-3.5 w-3.5"
972
- }, undefined, false, undefined, this),
973
- /* @__PURE__ */ jsxDEV6("span", {
1533
+ formatDate(conversation.updatedAt),
1534
+ conversation.projectName && ` · ${conversation.projectName}`,
1535
+ conversation.tags && conversation.tags.length > 0 && /* @__PURE__ */ jsxs9(Fragment5, {
974
1536
  children: [
975
- summary.specs.total,
976
- " specs"
1537
+ " · ",
1538
+ conversation.tags.slice(0, 2).join(", ")
977
1539
  ]
978
- }, undefined, true, undefined, this)
1540
+ })
979
1541
  ]
980
- }, undefined, true, undefined, this)
1542
+ })
981
1543
  ]
982
- }, undefined, true, undefined, this)
1544
+ }),
1545
+ /* @__PURE__ */ jsx9("span", {
1546
+ onClick: (e) => e.stopPropagation(),
1547
+ children: /* @__PURE__ */ jsx9(Button5, {
1548
+ variant: "ghost",
1549
+ size: "sm",
1550
+ className: "h-6 w-6 shrink-0 p-0 opacity-0 group-hover:opacity-100",
1551
+ onPress: onDelete,
1552
+ "aria-label": "Delete conversation",
1553
+ children: /* @__PURE__ */ jsx9(Trash2, {
1554
+ className: "h-3 w-3"
1555
+ })
1556
+ })
1557
+ })
983
1558
  ]
984
- }, undefined, true, undefined, this);
985
- if (!summary) {
986
- return content;
987
- }
988
- return /* @__PURE__ */ jsxDEV6(TooltipProvider, {
989
- children: /* @__PURE__ */ jsxDEV6(Tooltip, {
990
- children: [
991
- /* @__PURE__ */ jsxDEV6(TooltipTrigger, {
992
- asChild: true,
993
- children: content
994
- }, undefined, false, undefined, this),
995
- /* @__PURE__ */ jsxDEV6(TooltipContent, {
996
- side: "bottom",
997
- className: "max-w-[300px]",
998
- children: /* @__PURE__ */ jsxDEV6("div", {
999
- className: "flex flex-col gap-2 text-sm",
1000
- children: [
1001
- /* @__PURE__ */ jsxDEV6("div", {
1002
- className: "font-medium",
1003
- children: summary.name
1004
- }, undefined, false, undefined, this),
1005
- /* @__PURE__ */ jsxDEV6("div", {
1006
- className: "text-muted-foreground text-xs",
1007
- children: summary.path
1008
- }, undefined, false, undefined, this),
1009
- /* @__PURE__ */ jsxDEV6("div", {
1010
- className: "border-t pt-2",
1011
- children: /* @__PURE__ */ jsxDEV6("div", {
1012
- className: "grid grid-cols-2 gap-1 text-xs",
1013
- children: [
1014
- /* @__PURE__ */ jsxDEV6("span", {
1015
- children: "Commands:"
1016
- }, undefined, false, undefined, this),
1017
- /* @__PURE__ */ jsxDEV6("span", {
1018
- className: "text-right",
1019
- children: summary.specs.commands
1020
- }, undefined, false, undefined, this),
1021
- /* @__PURE__ */ jsxDEV6("span", {
1022
- children: "Queries:"
1023
- }, undefined, false, undefined, this),
1024
- /* @__PURE__ */ jsxDEV6("span", {
1025
- className: "text-right",
1026
- children: summary.specs.queries
1027
- }, undefined, false, undefined, this),
1028
- /* @__PURE__ */ jsxDEV6("span", {
1029
- children: "Events:"
1030
- }, undefined, false, undefined, this),
1031
- /* @__PURE__ */ jsxDEV6("span", {
1032
- className: "text-right",
1033
- children: summary.specs.events
1034
- }, undefined, false, undefined, this),
1035
- /* @__PURE__ */ jsxDEV6("span", {
1036
- children: "Presentations:"
1037
- }, undefined, false, undefined, this),
1038
- /* @__PURE__ */ jsxDEV6("span", {
1039
- className: "text-right",
1040
- children: summary.specs.presentations
1041
- }, undefined, false, undefined, this)
1042
- ]
1043
- }, undefined, true, undefined, this)
1044
- }, undefined, false, undefined, this),
1045
- /* @__PURE__ */ jsxDEV6("div", {
1046
- className: "border-t pt-2 text-xs",
1047
- children: [
1048
- /* @__PURE__ */ jsxDEV6("span", {
1049
- children: [
1050
- summary.files.total,
1051
- " files"
1052
- ]
1053
- }, undefined, true, undefined, this),
1054
- /* @__PURE__ */ jsxDEV6("span", {
1055
- className: "mx-1",
1056
- children: "•"
1057
- }, undefined, false, undefined, this),
1058
- /* @__PURE__ */ jsxDEV6("span", {
1059
- children: [
1060
- summary.files.specFiles,
1061
- " spec files"
1062
- ]
1063
- }, undefined, true, undefined, this)
1064
- ]
1065
- }, undefined, true, undefined, this)
1066
- ]
1067
- }, undefined, true, undefined, this)
1068
- }, undefined, false, undefined, this)
1069
- ]
1070
- }, undefined, true, undefined, this)
1071
- }, undefined, false, undefined, this);
1559
+ });
1560
+ }
1561
+ function ChatSidebar({
1562
+ store,
1563
+ selectedConversationId,
1564
+ onSelectConversation,
1565
+ onCreateNew,
1566
+ projectId,
1567
+ tags,
1568
+ limit = 50,
1569
+ className,
1570
+ collapsed = false,
1571
+ onUpdateConversation,
1572
+ selectedConversation
1573
+ }) {
1574
+ const { conversations, isLoading, refresh, deleteConversation } = useConversations({ store, projectId, tags, limit });
1575
+ const handleDelete = React10.useCallback(async (id) => {
1576
+ const ok = await deleteConversation(id);
1577
+ if (ok && selectedConversationId === id) {
1578
+ onSelectConversation(null);
1579
+ }
1580
+ }, [deleteConversation, selectedConversationId, onSelectConversation]);
1581
+ if (collapsed)
1582
+ return null;
1583
+ return /* @__PURE__ */ jsxs9("div", {
1584
+ className: cn6("border-border flex w-64 shrink-0 flex-col border-r", className),
1585
+ children: [
1586
+ /* @__PURE__ */ jsxs9("div", {
1587
+ className: "border-border flex shrink-0 items-center justify-between border-b p-2",
1588
+ children: [
1589
+ /* @__PURE__ */ jsx9("span", {
1590
+ className: "text-muted-foreground text-sm font-medium",
1591
+ children: "Conversations"
1592
+ }),
1593
+ /* @__PURE__ */ jsx9(Button5, {
1594
+ variant: "ghost",
1595
+ size: "sm",
1596
+ className: "h-8 w-8 p-0",
1597
+ onPress: onCreateNew,
1598
+ "aria-label": "New conversation",
1599
+ children: /* @__PURE__ */ jsx9(Plus2, {
1600
+ className: "h-4 w-4"
1601
+ })
1602
+ })
1603
+ ]
1604
+ }),
1605
+ /* @__PURE__ */ jsx9("div", {
1606
+ className: "flex-1 overflow-y-auto p-2",
1607
+ children: isLoading ? /* @__PURE__ */ jsx9("div", {
1608
+ className: "text-muted-foreground py-4 text-center text-sm",
1609
+ children: "Loading…"
1610
+ }) : conversations.length === 0 ? /* @__PURE__ */ jsx9("div", {
1611
+ className: "text-muted-foreground py-4 text-center text-sm",
1612
+ children: "No conversations yet"
1613
+ }) : /* @__PURE__ */ jsx9("div", {
1614
+ className: "flex flex-col gap-1",
1615
+ children: conversations.map((conv) => /* @__PURE__ */ jsx9(ConversationItem, {
1616
+ conversation: conv,
1617
+ selected: conv.id === selectedConversationId,
1618
+ onSelect: () => onSelectConversation(conv.id),
1619
+ onDelete: () => handleDelete(conv.id)
1620
+ }, conv.id))
1621
+ })
1622
+ }),
1623
+ selectedConversation && onUpdateConversation && /* @__PURE__ */ jsx9(ConversationMeta, {
1624
+ conversation: selectedConversation,
1625
+ onUpdate: onUpdateConversation
1626
+ })
1627
+ ]
1628
+ });
1629
+ }
1630
+ function ConversationMeta({
1631
+ conversation,
1632
+ onUpdate
1633
+ }) {
1634
+ const [projectName, setProjectName] = React10.useState(conversation.projectName ?? "");
1635
+ const [tagsStr, setTagsStr] = React10.useState(conversation.tags?.join(", ") ?? "");
1636
+ React10.useEffect(() => {
1637
+ setProjectName(conversation.projectName ?? "");
1638
+ setTagsStr(conversation.tags?.join(", ") ?? "");
1639
+ }, [conversation.id, conversation.projectName, conversation.tags]);
1640
+ const handleBlur = React10.useCallback(() => {
1641
+ const tags = tagsStr.split(",").map((t) => t.trim()).filter(Boolean);
1642
+ if (projectName !== (conversation.projectName ?? "") || JSON.stringify(tags) !== JSON.stringify(conversation.tags ?? [])) {
1643
+ onUpdate(conversation.id, {
1644
+ projectName: projectName || undefined,
1645
+ projectId: projectName ? projectName.replace(/\s+/g, "-") : undefined,
1646
+ tags: tags.length > 0 ? tags : undefined
1647
+ });
1648
+ }
1649
+ }, [
1650
+ conversation.id,
1651
+ conversation.projectName,
1652
+ conversation.tags,
1653
+ projectName,
1654
+ tagsStr,
1655
+ onUpdate
1656
+ ]);
1657
+ return /* @__PURE__ */ jsxs9("div", {
1658
+ className: "border-border shrink-0 border-t p-2",
1659
+ children: [
1660
+ /* @__PURE__ */ jsx9("p", {
1661
+ className: "text-muted-foreground mb-1 text-xs font-medium",
1662
+ children: "Project"
1663
+ }),
1664
+ /* @__PURE__ */ jsx9("input", {
1665
+ type: "text",
1666
+ value: projectName,
1667
+ onChange: (e) => setProjectName(e.target.value),
1668
+ onBlur: handleBlur,
1669
+ placeholder: "Project name",
1670
+ className: "border-input bg-background mb-2 w-full rounded px-2 py-1 text-xs"
1671
+ }),
1672
+ /* @__PURE__ */ jsx9("p", {
1673
+ className: "text-muted-foreground mb-1 text-xs font-medium",
1674
+ children: "Tags"
1675
+ }),
1676
+ /* @__PURE__ */ jsx9("input", {
1677
+ type: "text",
1678
+ value: tagsStr,
1679
+ onChange: (e) => setTagsStr(e.target.value),
1680
+ onBlur: handleBlur,
1681
+ placeholder: "tag1, tag2",
1682
+ className: "border-input bg-background w-full rounded px-2 py-1 text-xs"
1683
+ })
1684
+ ]
1685
+ });
1072
1686
  }
1687
+ // src/presentation/components/ChatWithSidebar.tsx
1688
+ import * as React12 from "react";
1689
+
1073
1690
  // src/presentation/hooks/useChat.tsx
1074
- import * as React6 from "react";
1075
- import { tool } from "ai";
1076
- import { z } from "zod";
1691
+ import * as React11 from "react";
1692
+ import { tool as tool4 } from "ai";
1693
+ import { z as z4 } from "zod";
1077
1694
 
1078
1695
  // src/core/chat-service.ts
1079
1696
  import { generateText, streamText } from "ai";
@@ -1155,11 +1772,65 @@ class InMemoryConversationStore {
1155
1772
  if (options?.status) {
1156
1773
  results = results.filter((c) => c.status === options.status);
1157
1774
  }
1775
+ if (options?.projectId) {
1776
+ results = results.filter((c) => c.projectId === options.projectId);
1777
+ }
1778
+ if (options?.tags && options.tags.length > 0) {
1779
+ const tagSet = new Set(options.tags);
1780
+ results = results.filter((c) => c.tags && c.tags.some((t) => tagSet.has(t)));
1781
+ }
1158
1782
  results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
1159
1783
  const offset = options?.offset ?? 0;
1160
1784
  const limit = options?.limit ?? 100;
1161
1785
  return results.slice(offset, offset + limit);
1162
1786
  }
1787
+ async fork(conversationId, upToMessageId) {
1788
+ const source = this.conversations.get(conversationId);
1789
+ if (!source) {
1790
+ throw new Error(`Conversation ${conversationId} not found`);
1791
+ }
1792
+ let messagesToCopy = source.messages;
1793
+ if (upToMessageId) {
1794
+ const idx = source.messages.findIndex((m) => m.id === upToMessageId);
1795
+ if (idx === -1) {
1796
+ throw new Error(`Message ${upToMessageId} not found`);
1797
+ }
1798
+ messagesToCopy = source.messages.slice(0, idx + 1);
1799
+ }
1800
+ const now = new Date;
1801
+ const forkedMessages = messagesToCopy.map((m) => ({
1802
+ ...m,
1803
+ id: generateId("msg"),
1804
+ conversationId: "",
1805
+ createdAt: new Date(m.createdAt),
1806
+ updatedAt: new Date(m.updatedAt)
1807
+ }));
1808
+ const forked = {
1809
+ ...source,
1810
+ id: generateId("conv"),
1811
+ title: source.title ? `${source.title} (fork)` : undefined,
1812
+ forkedFromId: source.id,
1813
+ createdAt: now,
1814
+ updatedAt: now,
1815
+ messages: forkedMessages
1816
+ };
1817
+ for (const m of forked.messages) {
1818
+ m.conversationId = forked.id;
1819
+ }
1820
+ this.conversations.set(forked.id, forked);
1821
+ return forked;
1822
+ }
1823
+ async truncateAfter(conversationId, messageId) {
1824
+ const conv = this.conversations.get(conversationId);
1825
+ if (!conv)
1826
+ return null;
1827
+ const idx = conv.messages.findIndex((m) => m.id === messageId);
1828
+ if (idx === -1)
1829
+ return null;
1830
+ conv.messages = conv.messages.slice(0, idx + 1);
1831
+ conv.updatedAt = new Date;
1832
+ return conv;
1833
+ }
1163
1834
  async search(query, limit = 20) {
1164
1835
  const lowerQuery = query.toLowerCase();
1165
1836
  const results = [];
@@ -1185,43 +1856,566 @@ function createInMemoryConversationStore() {
1185
1856
  return new InMemoryConversationStore;
1186
1857
  }
1187
1858
 
1188
- // src/core/chat-service.ts
1189
- var DEFAULT_SYSTEM_PROMPT = `You are ContractSpec AI, an expert coding assistant specialized in ContractSpec development.
1859
+ // src/core/workflow-tools.ts
1860
+ import { tool } from "ai";
1861
+ import { z } from "zod";
1862
+ import {
1863
+ WorkflowComposer,
1864
+ validateExtension
1865
+ } from "@contractspec/lib.workflow-composer";
1866
+ var StepTypeSchema = z.enum(["human", "automation", "decision"]);
1867
+ var StepActionSchema = z.object({
1868
+ operation: z.object({
1869
+ name: z.string(),
1870
+ version: z.number()
1871
+ }).optional(),
1872
+ form: z.object({
1873
+ key: z.string(),
1874
+ version: z.number()
1875
+ }).optional()
1876
+ }).optional();
1877
+ var StepSchema = z.object({
1878
+ id: z.string(),
1879
+ type: StepTypeSchema,
1880
+ label: z.string(),
1881
+ description: z.string().optional(),
1882
+ action: StepActionSchema
1883
+ });
1884
+ var StepInjectionSchema = z.object({
1885
+ after: z.string().optional(),
1886
+ before: z.string().optional(),
1887
+ inject: StepSchema,
1888
+ transitionTo: z.string().optional(),
1889
+ transitionFrom: z.string().optional(),
1890
+ when: z.string().optional()
1891
+ });
1892
+ var WorkflowExtensionInputSchema = z.object({
1893
+ workflow: z.string(),
1894
+ tenantId: z.string().optional(),
1895
+ role: z.string().optional(),
1896
+ priority: z.number().optional(),
1897
+ customSteps: z.array(StepInjectionSchema).optional(),
1898
+ hiddenSteps: z.array(z.string()).optional()
1899
+ });
1900
+ function createWorkflowTools(config) {
1901
+ const { baseWorkflows, composer } = config;
1902
+ const baseByKey = new Map(baseWorkflows.map((b) => [b.meta.key, b]));
1903
+ const createWorkflowExtensionTool = tool({
1904
+ description: "Create or validate a workflow extension. Use when the user asks to add steps, modify a workflow, or create a tenant-specific extension. The extension targets an existing base workflow.",
1905
+ inputSchema: WorkflowExtensionInputSchema,
1906
+ execute: async (input) => {
1907
+ const extension = {
1908
+ workflow: input.workflow,
1909
+ tenantId: input.tenantId,
1910
+ role: input.role,
1911
+ priority: input.priority,
1912
+ customSteps: input.customSteps,
1913
+ hiddenSteps: input.hiddenSteps
1914
+ };
1915
+ const base = baseByKey.get(input.workflow);
1916
+ if (!base) {
1917
+ return {
1918
+ success: false,
1919
+ error: `Base workflow "${input.workflow}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`,
1920
+ extension
1921
+ };
1922
+ }
1923
+ try {
1924
+ validateExtension(extension, base);
1925
+ return {
1926
+ success: true,
1927
+ message: "Extension validated successfully",
1928
+ extension
1929
+ };
1930
+ } catch (err) {
1931
+ return {
1932
+ success: false,
1933
+ error: err instanceof Error ? err.message : String(err),
1934
+ extension
1935
+ };
1936
+ }
1937
+ }
1938
+ });
1939
+ const composeWorkflowInputSchema = z.object({
1940
+ workflowKey: z.string().describe("Base workflow meta.key"),
1941
+ tenantId: z.string().optional(),
1942
+ role: z.string().optional(),
1943
+ extensions: z.array(WorkflowExtensionInputSchema).optional().describe("Extensions to register before composing")
1944
+ });
1945
+ const composeWorkflowTool = tool({
1946
+ description: "Compose a workflow by applying registered extensions to a base workflow. Returns the composed WorkflowSpec.",
1947
+ inputSchema: composeWorkflowInputSchema,
1948
+ execute: async (input) => {
1949
+ const base = baseByKey.get(input.workflowKey);
1950
+ if (!base) {
1951
+ return {
1952
+ success: false,
1953
+ error: `Base workflow "${input.workflowKey}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`
1954
+ };
1955
+ }
1956
+ const comp = composer ?? new WorkflowComposer;
1957
+ if (input.extensions?.length) {
1958
+ for (const ext of input.extensions) {
1959
+ comp.register({
1960
+ workflow: ext.workflow,
1961
+ tenantId: ext.tenantId,
1962
+ role: ext.role,
1963
+ priority: ext.priority,
1964
+ customSteps: ext.customSteps,
1965
+ hiddenSteps: ext.hiddenSteps
1966
+ });
1967
+ }
1968
+ }
1969
+ try {
1970
+ const composed = comp.compose({
1971
+ base,
1972
+ tenantId: input.tenantId,
1973
+ role: input.role
1974
+ });
1975
+ return {
1976
+ success: true,
1977
+ workflow: composed,
1978
+ meta: composed.meta,
1979
+ stepIds: composed.definition.steps.map((s) => s.id)
1980
+ };
1981
+ } catch (err) {
1982
+ return {
1983
+ success: false,
1984
+ error: err instanceof Error ? err.message : String(err)
1985
+ };
1986
+ }
1987
+ }
1988
+ });
1989
+ const generateWorkflowSpecCodeInputSchema = z.object({
1990
+ workflowKey: z.string().describe("Workflow meta.key"),
1991
+ composedSteps: z.array(z.object({
1992
+ id: z.string(),
1993
+ type: z.enum(["human", "automation", "decision"]),
1994
+ label: z.string(),
1995
+ description: z.string().optional()
1996
+ })).optional().describe("Steps to include; if omitted, uses the base workflow")
1997
+ });
1998
+ const generateWorkflowSpecCodeTool = tool({
1999
+ description: "Generate TypeScript code for a workflow spec. Use after composing a workflow to output the spec as code the user can save.",
2000
+ inputSchema: generateWorkflowSpecCodeInputSchema,
2001
+ execute: async (input) => {
2002
+ const base = baseByKey.get(input.workflowKey);
2003
+ if (!base) {
2004
+ return {
2005
+ success: false,
2006
+ error: `Base workflow "${input.workflowKey}" not found. Available: ${Array.from(baseByKey.keys()).join(", ")}`,
2007
+ code: null
2008
+ };
2009
+ }
2010
+ const steps = input.composedSteps ?? base.definition.steps;
2011
+ const specVarName = toPascalCase((base.meta.key.split(".").pop() ?? "Workflow") + "") + "Workflow";
2012
+ const stepsCode = steps.map((s) => ` {
2013
+ id: '${s.id}',
2014
+ type: '${s.type}',
2015
+ label: '${escapeString(s.label)}',${s.description ? `
2016
+ description: '${escapeString(s.description)}',` : ""}
2017
+ }`).join(`,
2018
+ `);
2019
+ const meta = base.meta;
2020
+ const transitionsJson = JSON.stringify(base.definition.transitions, null, 6);
2021
+ const code = `import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow';
1190
2022
 
1191
- Your capabilities:
1192
- - Help users create, modify, and understand ContractSpec specifications
1193
- - Generate code that follows ContractSpec patterns and best practices
1194
- - Explain concepts from the ContractSpec documentation
1195
- - Suggest improvements and identify issues in specs and implementations
2023
+ /**
2024
+ * Workflow: ${base.meta.key}
2025
+ * Generated via AI chat workflow tools.
2026
+ */
2027
+ export const ${specVarName}: WorkflowSpec = {
2028
+ meta: {
2029
+ key: '${base.meta.key}',
2030
+ version: '${String(base.meta.version)}',
2031
+ title: '${escapeString(meta.title ?? base.meta.key)}',
2032
+ description: '${escapeString(meta.description ?? "")}',
2033
+ },
2034
+ definition: {
2035
+ entryStepId: '${base.definition.entryStepId ?? base.definition.steps[0]?.id ?? ""}',
2036
+ steps: [
2037
+ ${stepsCode}
2038
+ ],
2039
+ transitions: ${transitionsJson},
2040
+ },
2041
+ };
2042
+ `;
2043
+ return {
2044
+ success: true,
2045
+ code,
2046
+ workflowKey: input.workflowKey
2047
+ };
2048
+ }
2049
+ });
2050
+ return {
2051
+ create_workflow_extension: createWorkflowExtensionTool,
2052
+ compose_workflow: composeWorkflowTool,
2053
+ generate_workflow_spec_code: generateWorkflowSpecCodeTool
2054
+ };
2055
+ }
2056
+ function toPascalCase(value) {
2057
+ return value.split(/[-_.]/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
2058
+ }
2059
+ function escapeString(value) {
2060
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
2061
+ }
1196
2062
 
1197
- Guidelines:
1198
- - Be concise but thorough
1199
- - Provide code examples when helpful
1200
- - Reference relevant ContractSpec concepts and patterns
1201
- - Ask clarifying questions when the user's intent is unclear
1202
- - When suggesting code changes, explain the rationale`;
2063
+ // src/core/contracts-context.ts
2064
+ function buildContractsContextPrompt(config) {
2065
+ const parts = [];
2066
+ if (!config.agentSpecs?.length && !config.dataViewSpecs?.length && !config.formSpecs?.length && !config.presentationSpecs?.length && !config.operationRefs?.length) {
2067
+ return "";
2068
+ }
2069
+ parts.push(`
1203
2070
 
1204
- class ChatService {
1205
- provider;
1206
- context;
1207
- store;
1208
- systemPrompt;
1209
- maxHistoryMessages;
1210
- onUsage;
1211
- tools;
1212
- sendReasoning;
2071
+ ## Available resources`);
2072
+ if (config.agentSpecs?.length) {
2073
+ parts.push(`
2074
+ ### Agent tools`);
2075
+ for (const agent of config.agentSpecs) {
2076
+ const toolNames = agent.tools?.map((t) => t.name).join(", ") ?? "none";
2077
+ parts.push(`- **${agent.key}**: tools: ${toolNames}`);
2078
+ }
2079
+ }
2080
+ if (config.dataViewSpecs?.length) {
2081
+ parts.push(`
2082
+ ### Data views`);
2083
+ for (const dv of config.dataViewSpecs) {
2084
+ parts.push(`- **${dv.key}**: ${dv.meta.title ?? dv.key}`);
2085
+ }
2086
+ }
2087
+ if (config.formSpecs?.length) {
2088
+ parts.push(`
2089
+ ### Forms`);
2090
+ for (const form of config.formSpecs) {
2091
+ parts.push(`- **${form.key}**: ${form.meta.title ?? form.key}`);
2092
+ }
2093
+ }
2094
+ if (config.presentationSpecs?.length) {
2095
+ parts.push(`
2096
+ ### Presentations`);
2097
+ for (const pres of config.presentationSpecs) {
2098
+ parts.push(`- **${pres.key}**: ${pres.meta.title ?? pres.key} (targets: ${pres.targets?.join(", ") ?? "react"})`);
2099
+ }
2100
+ }
2101
+ if (config.operationRefs?.length) {
2102
+ parts.push(`
2103
+ ### Operations`);
2104
+ for (const op of config.operationRefs) {
2105
+ parts.push(`- **${op.key}@${op.version}**`);
2106
+ }
2107
+ }
2108
+ parts.push(`
2109
+ Use the available tools to invoke operations, query data views, or propose surface changes when appropriate.`);
2110
+ return parts.join(`
2111
+ `);
2112
+ }
2113
+
2114
+ // src/core/agent-tools-adapter.ts
2115
+ import { tool as tool2 } from "ai";
2116
+ import { z as z2 } from "zod";
2117
+ function getInputSchema(_schema) {
2118
+ return z2.object({}).passthrough();
2119
+ }
2120
+ function agentToolConfigsToToolSet(configs, handlers) {
2121
+ const result = {};
2122
+ for (const config of configs) {
2123
+ const handler = handlers?.[config.name];
2124
+ const inputSchema = getInputSchema(config.schema);
2125
+ result[config.name] = tool2({
2126
+ description: config.description ?? config.name,
2127
+ inputSchema,
2128
+ execute: async (input) => {
2129
+ if (!handler) {
2130
+ return {
2131
+ status: "unimplemented",
2132
+ message: "Wire handler in host",
2133
+ toolName: config.name
2134
+ };
2135
+ }
2136
+ try {
2137
+ const output = await Promise.resolve(handler(input));
2138
+ return typeof output === "string" ? output : output;
2139
+ } catch (err) {
2140
+ return {
2141
+ status: "error",
2142
+ error: err instanceof Error ? err.message : String(err),
2143
+ toolName: config.name
2144
+ };
2145
+ }
2146
+ }
2147
+ });
2148
+ }
2149
+ return result;
2150
+ }
2151
+
2152
+ // src/core/surface-planner-tools.ts
2153
+ import { tool as tool3 } from "ai";
2154
+ import { z as z3 } from "zod";
2155
+ import { validatePatchProposal } from "@contractspec/lib.surface-runtime/spec/validate-surface-patch";
2156
+ import { buildSurfacePatchProposal } from "@contractspec/lib.surface-runtime/runtime/planner-tools";
2157
+ var VALID_OPS = [
2158
+ "insert-node",
2159
+ "replace-node",
2160
+ "remove-node",
2161
+ "move-node",
2162
+ "resize-panel",
2163
+ "set-layout",
2164
+ "reveal-field",
2165
+ "hide-field",
2166
+ "promote-action",
2167
+ "set-focus"
2168
+ ];
2169
+ var DEFAULT_NODE_KINDS = [
2170
+ "entity-section",
2171
+ "entity-card",
2172
+ "data-view",
2173
+ "assistant-panel",
2174
+ "chat-thread",
2175
+ "action-bar",
2176
+ "timeline",
2177
+ "table",
2178
+ "rich-doc",
2179
+ "form",
2180
+ "chart",
2181
+ "custom-widget"
2182
+ ];
2183
+ function collectSlotIdsFromRegion(node) {
2184
+ const ids = [];
2185
+ if (node.type === "slot") {
2186
+ ids.push(node.slotId);
2187
+ }
2188
+ if (node.type === "panel-group" || node.type === "stack") {
2189
+ for (const child of node.children) {
2190
+ ids.push(...collectSlotIdsFromRegion(child));
2191
+ }
2192
+ }
2193
+ if (node.type === "tabs") {
2194
+ for (const tab of node.tabs) {
2195
+ ids.push(...collectSlotIdsFromRegion(tab.child));
2196
+ }
2197
+ }
2198
+ if (node.type === "floating") {
2199
+ ids.push(node.anchorSlotId);
2200
+ ids.push(...collectSlotIdsFromRegion(node.child));
2201
+ }
2202
+ return ids;
2203
+ }
2204
+ function deriveConstraints(plan) {
2205
+ const slotIds = collectSlotIdsFromRegion(plan.layoutRoot);
2206
+ const uniqueSlots = [...new Set(slotIds)];
2207
+ return {
2208
+ allowedOps: VALID_OPS,
2209
+ allowedSlots: uniqueSlots.length > 0 ? uniqueSlots : ["assistant", "primary"],
2210
+ allowedNodeKinds: DEFAULT_NODE_KINDS
2211
+ };
2212
+ }
2213
+ var ProposePatchInputSchema = z3.object({
2214
+ proposalId: z3.string().describe("Unique proposal identifier"),
2215
+ ops: z3.array(z3.object({
2216
+ op: z3.enum([
2217
+ "insert-node",
2218
+ "replace-node",
2219
+ "remove-node",
2220
+ "move-node",
2221
+ "resize-panel",
2222
+ "set-layout",
2223
+ "reveal-field",
2224
+ "hide-field",
2225
+ "promote-action",
2226
+ "set-focus"
2227
+ ]),
2228
+ slotId: z3.string().optional(),
2229
+ nodeId: z3.string().optional(),
2230
+ toSlotId: z3.string().optional(),
2231
+ index: z3.number().optional(),
2232
+ node: z3.object({
2233
+ nodeId: z3.string(),
2234
+ kind: z3.string(),
2235
+ title: z3.string().optional(),
2236
+ props: z3.record(z3.string(), z3.unknown()).optional(),
2237
+ children: z3.array(z3.unknown()).optional()
2238
+ }).optional(),
2239
+ persistKey: z3.string().optional(),
2240
+ sizes: z3.array(z3.number()).optional(),
2241
+ layoutId: z3.string().optional(),
2242
+ fieldId: z3.string().optional(),
2243
+ actionId: z3.string().optional(),
2244
+ placement: z3.enum(["header", "inline", "context", "assistant"]).optional(),
2245
+ targetId: z3.string().optional()
2246
+ }))
2247
+ });
2248
+ function createSurfacePlannerTools(config) {
2249
+ const { plan, constraints, onPatchProposal } = config;
2250
+ const resolvedConstraints = constraints ?? deriveConstraints(plan);
2251
+ const proposePatchTool = tool3({
2252
+ description: "Propose surface patches (layout changes, node insertions, etc.) for user approval. " + "Only use allowed ops, slots, and node kinds from the planner context.",
2253
+ inputSchema: ProposePatchInputSchema,
2254
+ execute: async (input) => {
2255
+ const ops = input.ops;
2256
+ try {
2257
+ validatePatchProposal(ops, resolvedConstraints);
2258
+ const proposal = buildSurfacePatchProposal(input.proposalId, ops);
2259
+ onPatchProposal?.(proposal);
2260
+ return {
2261
+ success: true,
2262
+ proposalId: proposal.proposalId,
2263
+ opsCount: proposal.ops.length,
2264
+ message: "Patch proposal validated; awaiting user approval"
2265
+ };
2266
+ } catch (err) {
2267
+ return {
2268
+ success: false,
2269
+ error: err instanceof Error ? err.message : String(err),
2270
+ proposalId: input.proposalId
2271
+ };
2272
+ }
2273
+ }
2274
+ });
2275
+ return {
2276
+ "propose-patch": proposePatchTool
2277
+ };
2278
+ }
2279
+ function buildPlannerPromptInput(plan) {
2280
+ const constraints = deriveConstraints(plan);
2281
+ return {
2282
+ bundleMeta: {
2283
+ key: plan.bundleKey,
2284
+ version: "0.0.0",
2285
+ title: plan.bundleKey
2286
+ },
2287
+ surfaceId: plan.surfaceId,
2288
+ allowedPatchOps: constraints.allowedOps,
2289
+ allowedSlots: [...constraints.allowedSlots],
2290
+ allowedNodeKinds: [...constraints.allowedNodeKinds],
2291
+ actions: plan.actions.map((a) => ({ actionId: a.actionId, title: a.title })),
2292
+ preferences: {
2293
+ guidance: "hints",
2294
+ density: "standard",
2295
+ dataDepth: "detailed",
2296
+ control: "standard",
2297
+ media: "text",
2298
+ pace: "balanced",
2299
+ narrative: "top-down"
2300
+ }
2301
+ };
2302
+ }
2303
+
2304
+ // src/core/chat-service.ts
2305
+ import { compilePlannerPrompt } from "@contractspec/lib.surface-runtime/runtime/planner-prompt";
2306
+ var DEFAULT_SYSTEM_PROMPT = `You are ContractSpec AI, an expert coding assistant specialized in ContractSpec development.
2307
+
2308
+ Your capabilities:
2309
+ - Help users create, modify, and understand ContractSpec specifications
2310
+ - Generate code that follows ContractSpec patterns and best practices
2311
+ - Explain concepts from the ContractSpec documentation
2312
+ - Suggest improvements and identify issues in specs and implementations
2313
+
2314
+ Guidelines:
2315
+ - Be concise but thorough
2316
+ - Provide code examples when helpful
2317
+ - Reference relevant ContractSpec concepts and patterns
2318
+ - Ask clarifying questions when the user's intent is unclear
2319
+ - When suggesting code changes, explain the rationale`;
2320
+ var WORKFLOW_TOOLS_PROMPT = `
2321
+
2322
+ Workflow creation: You can create and modify workflows. Use create_workflow_extension when the user asks to add steps, change a workflow, or create a tenant-specific extension. Use compose_workflow to apply extensions to a base workflow. Use generate_workflow_spec_code to output TypeScript for the user to save.`;
2323
+
2324
+ class ChatService {
2325
+ provider;
2326
+ context;
2327
+ store;
2328
+ systemPrompt;
2329
+ maxHistoryMessages;
2330
+ onUsage;
2331
+ tools;
2332
+ thinkingLevel;
2333
+ sendReasoning;
1213
2334
  sendSources;
2335
+ modelSelector;
1214
2336
  constructor(config) {
1215
2337
  this.provider = config.provider;
1216
2338
  this.context = config.context;
1217
2339
  this.store = config.store ?? new InMemoryConversationStore;
1218
- this.systemPrompt = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
2340
+ this.systemPrompt = this.buildSystemPrompt(config);
1219
2341
  this.maxHistoryMessages = config.maxHistoryMessages ?? 20;
1220
2342
  this.onUsage = config.onUsage;
1221
- this.tools = config.tools;
1222
- this.sendReasoning = config.sendReasoning ?? false;
2343
+ this.tools = this.mergeTools(config);
2344
+ this.thinkingLevel = config.thinkingLevel;
2345
+ this.modelSelector = config.modelSelector;
2346
+ this.sendReasoning = config.sendReasoning ?? (config.thinkingLevel != null && config.thinkingLevel !== "instant");
1223
2347
  this.sendSources = config.sendSources ?? false;
1224
2348
  }
2349
+ buildSystemPrompt(config) {
2350
+ let base = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
2351
+ if (config.workflowToolsConfig?.baseWorkflows?.length) {
2352
+ base += WORKFLOW_TOOLS_PROMPT;
2353
+ }
2354
+ const contractsPrompt = buildContractsContextPrompt(config.contractsContext ?? {});
2355
+ if (contractsPrompt) {
2356
+ base += contractsPrompt;
2357
+ }
2358
+ if (config.surfacePlanConfig?.plan) {
2359
+ const plannerInput = buildPlannerPromptInput(config.surfacePlanConfig.plan);
2360
+ base += `
2361
+
2362
+ ` + compilePlannerPrompt(plannerInput);
2363
+ }
2364
+ return base;
2365
+ }
2366
+ mergeTools(config) {
2367
+ let merged = config.tools ?? {};
2368
+ const wfConfig = config.workflowToolsConfig;
2369
+ if (wfConfig?.baseWorkflows?.length) {
2370
+ const workflowTools = createWorkflowTools({
2371
+ baseWorkflows: wfConfig.baseWorkflows,
2372
+ composer: wfConfig.composer
2373
+ });
2374
+ merged = { ...merged, ...workflowTools };
2375
+ }
2376
+ const contractsCtx = config.contractsContext;
2377
+ if (contractsCtx?.agentSpecs?.length) {
2378
+ const allTools = [];
2379
+ for (const agent of contractsCtx.agentSpecs) {
2380
+ if (agent.tools?.length)
2381
+ allTools.push(...agent.tools);
2382
+ }
2383
+ if (allTools.length > 0) {
2384
+ const agentTools = agentToolConfigsToToolSet(allTools);
2385
+ merged = { ...merged, ...agentTools };
2386
+ }
2387
+ }
2388
+ const surfaceConfig = config.surfacePlanConfig;
2389
+ if (surfaceConfig?.plan) {
2390
+ const plannerTools = createSurfacePlannerTools({
2391
+ plan: surfaceConfig.plan,
2392
+ onPatchProposal: surfaceConfig.onPatchProposal
2393
+ });
2394
+ merged = { ...merged, ...plannerTools };
2395
+ }
2396
+ if (config.mcpTools && Object.keys(config.mcpTools).length > 0) {
2397
+ merged = { ...merged, ...config.mcpTools };
2398
+ }
2399
+ return Object.keys(merged).length > 0 ? merged : undefined;
2400
+ }
2401
+ async resolveModel() {
2402
+ if (this.modelSelector) {
2403
+ const dimension = this.thinkingLevelToDimension(this.thinkingLevel);
2404
+ const { model, selection } = await this.modelSelector.selectAndCreate({
2405
+ taskDimension: dimension
2406
+ });
2407
+ return { model, providerName: selection.providerKey };
2408
+ }
2409
+ return {
2410
+ model: this.provider.getModel(),
2411
+ providerName: this.provider.name
2412
+ };
2413
+ }
2414
+ thinkingLevelToDimension(level) {
2415
+ if (!level || level === "instant")
2416
+ return "latency";
2417
+ return "reasoning";
2418
+ }
1225
2419
  async send(options) {
1226
2420
  let conversation;
1227
2421
  if (options.conversationId) {
@@ -1239,20 +2433,25 @@ class ChatService {
1239
2433
  workspacePath: this.context?.workspacePath
1240
2434
  });
1241
2435
  }
1242
- await this.store.appendMessage(conversation.id, {
1243
- role: "user",
1244
- content: options.content,
1245
- status: "completed",
1246
- attachments: options.attachments
1247
- });
2436
+ if (!options.skipUserAppend) {
2437
+ await this.store.appendMessage(conversation.id, {
2438
+ role: "user",
2439
+ content: options.content,
2440
+ status: "completed",
2441
+ attachments: options.attachments
2442
+ });
2443
+ }
2444
+ conversation = await this.store.get(conversation.id) ?? conversation;
1248
2445
  const messages = this.buildMessages(conversation, options);
1249
- const model = this.provider.getModel();
2446
+ const { model, providerName } = await this.resolveModel();
2447
+ const providerOptions = getProviderOptions(this.thinkingLevel, providerName);
1250
2448
  try {
1251
2449
  const result = await generateText({
1252
2450
  model,
1253
2451
  messages,
1254
2452
  system: this.systemPrompt,
1255
- tools: this.tools
2453
+ tools: this.tools,
2454
+ providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined
1256
2455
  });
1257
2456
  const assistantMessage = await this.store.appendMessage(conversation.id, {
1258
2457
  role: "assistant",
@@ -1297,23 +2496,27 @@ class ChatService {
1297
2496
  workspacePath: this.context?.workspacePath
1298
2497
  });
1299
2498
  }
1300
- await this.store.appendMessage(conversation.id, {
1301
- role: "user",
1302
- content: options.content,
1303
- status: "completed",
1304
- attachments: options.attachments
1305
- });
2499
+ if (!options.skipUserAppend) {
2500
+ await this.store.appendMessage(conversation.id, {
2501
+ role: "user",
2502
+ content: options.content,
2503
+ status: "completed",
2504
+ attachments: options.attachments
2505
+ });
2506
+ }
2507
+ conversation = await this.store.get(conversation.id) ?? conversation;
1306
2508
  const assistantMessage = await this.store.appendMessage(conversation.id, {
1307
2509
  role: "assistant",
1308
2510
  content: "",
1309
2511
  status: "streaming"
1310
2512
  });
1311
2513
  const messages = this.buildMessages(conversation, options);
1312
- const model = this.provider.getModel();
2514
+ const { model, providerName } = await this.resolveModel();
1313
2515
  const systemPrompt = this.systemPrompt;
1314
2516
  const tools = this.tools;
1315
2517
  const store = this.store;
1316
2518
  const onUsage = this.onUsage;
2519
+ const streamProviderOptions = getProviderOptions(this.thinkingLevel, providerName);
1317
2520
  async function* streamGenerator() {
1318
2521
  let fullContent = "";
1319
2522
  let fullReasoning = "";
@@ -1324,7 +2527,8 @@ class ChatService {
1324
2527
  model,
1325
2528
  messages,
1326
2529
  system: systemPrompt,
1327
- tools
2530
+ tools,
2531
+ providerOptions: Object.keys(streamProviderOptions).length > 0 ? streamProviderOptions : undefined
1328
2532
  });
1329
2533
  for await (const part of result.fullStream) {
1330
2534
  if (part.type === "text-delta") {
@@ -1439,6 +2643,18 @@ class ChatService {
1439
2643
  ...options
1440
2644
  });
1441
2645
  }
2646
+ async updateConversation(conversationId, updates) {
2647
+ return this.store.update(conversationId, updates);
2648
+ }
2649
+ async forkConversation(conversationId, upToMessageId) {
2650
+ return this.store.fork(conversationId, upToMessageId);
2651
+ }
2652
+ async updateMessage(conversationId, messageId, updates) {
2653
+ return this.store.updateMessage(conversationId, messageId, updates);
2654
+ }
2655
+ async truncateAfter(conversationId, messageId) {
2656
+ return this.store.truncateAfter(conversationId, messageId);
2657
+ }
1442
2658
  async deleteConversation(conversationId) {
1443
2659
  return this.store.delete(conversationId);
1444
2660
  }
@@ -1509,9 +2725,9 @@ import {
1509
2725
  function toolsToToolSet(defs) {
1510
2726
  const result = {};
1511
2727
  for (const def of defs) {
1512
- result[def.name] = tool({
2728
+ result[def.name] = tool4({
1513
2729
  description: def.description ?? def.name,
1514
- inputSchema: z.object({}).passthrough(),
2730
+ inputSchema: z4.object({}).passthrough(),
1515
2731
  execute: async () => ({})
1516
2732
  });
1517
2733
  }
@@ -1525,22 +2741,64 @@ function useChat(options = {}) {
1525
2741
  apiKey,
1526
2742
  proxyUrl,
1527
2743
  conversationId: initialConversationId,
2744
+ store,
1528
2745
  systemPrompt,
1529
2746
  streaming = true,
1530
2747
  onSend,
1531
2748
  onResponse,
1532
2749
  onError,
1533
2750
  onUsage,
1534
- tools: toolsDefs
2751
+ tools: toolsDefs,
2752
+ thinkingLevel,
2753
+ workflowToolsConfig,
2754
+ modelSelector,
2755
+ contractsContext,
2756
+ surfacePlanConfig,
2757
+ mcpServers,
2758
+ agentMode
1535
2759
  } = options;
1536
- const [messages, setMessages] = React6.useState([]);
1537
- const [conversation, setConversation] = React6.useState(null);
1538
- const [isLoading, setIsLoading] = React6.useState(false);
1539
- const [error, setError] = React6.useState(null);
1540
- const [conversationId, setConversationId] = React6.useState(initialConversationId ?? null);
1541
- const abortControllerRef = React6.useRef(null);
1542
- const chatServiceRef = React6.useRef(null);
1543
- React6.useEffect(() => {
2760
+ const [messages, setMessages] = React11.useState([]);
2761
+ const [mcpTools, setMcpTools] = React11.useState(null);
2762
+ const mcpCleanupRef = React11.useRef(null);
2763
+ const [conversation, setConversation] = React11.useState(null);
2764
+ const [isLoading, setIsLoading] = React11.useState(false);
2765
+ const [error, setError] = React11.useState(null);
2766
+ const [conversationId, setConversationId] = React11.useState(initialConversationId ?? null);
2767
+ const abortControllerRef = React11.useRef(null);
2768
+ const chatServiceRef = React11.useRef(null);
2769
+ React11.useEffect(() => {
2770
+ if (!mcpServers?.length) {
2771
+ setMcpTools(null);
2772
+ return;
2773
+ }
2774
+ let cancelled = false;
2775
+ import("@contractspec/lib.ai-agent/tools/mcp-client").then(({ createMcpToolsets }) => {
2776
+ createMcpToolsets(mcpServers).then(({ tools, cleanup }) => {
2777
+ if (!cancelled) {
2778
+ setMcpTools(tools);
2779
+ mcpCleanupRef.current = cleanup;
2780
+ } else {
2781
+ cleanup().catch(() => {
2782
+ return;
2783
+ });
2784
+ }
2785
+ }).catch(() => {
2786
+ if (!cancelled)
2787
+ setMcpTools(null);
2788
+ });
2789
+ });
2790
+ return () => {
2791
+ cancelled = true;
2792
+ const cleanup = mcpCleanupRef.current;
2793
+ mcpCleanupRef.current = null;
2794
+ if (cleanup)
2795
+ cleanup().catch(() => {
2796
+ return;
2797
+ });
2798
+ setMcpTools(null);
2799
+ };
2800
+ }, [mcpServers]);
2801
+ React11.useEffect(() => {
1544
2802
  const chatProvider = createProvider({
1545
2803
  provider,
1546
2804
  model,
@@ -1549,9 +2807,16 @@ function useChat(options = {}) {
1549
2807
  });
1550
2808
  chatServiceRef.current = new ChatService({
1551
2809
  provider: chatProvider,
2810
+ store,
1552
2811
  systemPrompt,
1553
2812
  onUsage,
1554
- tools: toolsDefs?.length ? toolsToToolSet(toolsDefs) : undefined
2813
+ tools: toolsDefs?.length ? toolsToToolSet(toolsDefs) : undefined,
2814
+ thinkingLevel,
2815
+ workflowToolsConfig,
2816
+ modelSelector,
2817
+ contractsContext,
2818
+ surfacePlanConfig,
2819
+ mcpTools
1555
2820
  });
1556
2821
  }, [
1557
2822
  provider,
@@ -1559,11 +2824,18 @@ function useChat(options = {}) {
1559
2824
  model,
1560
2825
  apiKey,
1561
2826
  proxyUrl,
2827
+ store,
1562
2828
  systemPrompt,
1563
2829
  onUsage,
1564
- toolsDefs
2830
+ toolsDefs,
2831
+ thinkingLevel,
2832
+ workflowToolsConfig,
2833
+ modelSelector,
2834
+ contractsContext,
2835
+ surfacePlanConfig,
2836
+ mcpTools
1565
2837
  ]);
1566
- React6.useEffect(() => {
2838
+ React11.useEffect(() => {
1567
2839
  if (!conversationId || !chatServiceRef.current)
1568
2840
  return;
1569
2841
  const loadConversation = async () => {
@@ -1577,7 +2849,90 @@ function useChat(options = {}) {
1577
2849
  };
1578
2850
  loadConversation().catch(console.error);
1579
2851
  }, [conversationId]);
1580
- const sendMessage = React6.useCallback(async (content, attachments) => {
2852
+ const sendMessage = React11.useCallback(async (content, attachments, opts) => {
2853
+ if (agentMode?.agent) {
2854
+ setIsLoading(true);
2855
+ setError(null);
2856
+ abortControllerRef.current = new AbortController;
2857
+ try {
2858
+ if (!opts?.skipUserAppend) {
2859
+ const userMessage = {
2860
+ id: `msg_${Date.now()}`,
2861
+ conversationId: conversationId ?? "",
2862
+ role: "user",
2863
+ content,
2864
+ status: "completed",
2865
+ createdAt: new Date,
2866
+ updatedAt: new Date,
2867
+ attachments
2868
+ };
2869
+ setMessages((prev) => [...prev, userMessage]);
2870
+ onSend?.(userMessage);
2871
+ }
2872
+ const result = await agentMode.agent.generate({
2873
+ prompt: content,
2874
+ signal: abortControllerRef.current.signal
2875
+ });
2876
+ const toolCallsMap = new Map;
2877
+ for (const tc of result.toolCalls ?? []) {
2878
+ const tr = result.toolResults?.find((r) => r.toolCallId === tc.toolCallId);
2879
+ toolCallsMap.set(tc.toolCallId, {
2880
+ id: tc.toolCallId,
2881
+ name: tc.toolName,
2882
+ args: tc.args ?? {},
2883
+ result: tr?.output,
2884
+ status: "completed"
2885
+ });
2886
+ }
2887
+ const assistantMessage = {
2888
+ id: `msg_${Date.now()}_a`,
2889
+ conversationId: conversationId ?? "",
2890
+ role: "assistant",
2891
+ content: result.text,
2892
+ status: "completed",
2893
+ createdAt: new Date,
2894
+ updatedAt: new Date,
2895
+ toolCalls: toolCallsMap.size ? Array.from(toolCallsMap.values()) : undefined,
2896
+ usage: result.usage
2897
+ };
2898
+ setMessages((prev) => [...prev, assistantMessage]);
2899
+ onResponse?.(assistantMessage);
2900
+ onUsage?.(result.usage ?? { inputTokens: 0, outputTokens: 0 });
2901
+ if (store && !conversationId) {
2902
+ const conv = await store.create({
2903
+ status: "active",
2904
+ provider: "agent",
2905
+ model: "agent",
2906
+ messages: []
2907
+ });
2908
+ if (!opts?.skipUserAppend) {
2909
+ await store.appendMessage(conv.id, {
2910
+ role: "user",
2911
+ content,
2912
+ status: "completed",
2913
+ attachments
2914
+ });
2915
+ }
2916
+ await store.appendMessage(conv.id, {
2917
+ role: "assistant",
2918
+ content: result.text,
2919
+ status: "completed",
2920
+ toolCalls: assistantMessage.toolCalls,
2921
+ usage: result.usage
2922
+ });
2923
+ const updated = await store.get(conv.id);
2924
+ if (updated)
2925
+ setConversation(updated);
2926
+ setConversationId(conv.id);
2927
+ }
2928
+ } catch (err) {
2929
+ setError(err instanceof Error ? err : new Error(String(err)));
2930
+ onError?.(err instanceof Error ? err : new Error(String(err)));
2931
+ } finally {
2932
+ setIsLoading(false);
2933
+ }
2934
+ return;
2935
+ }
1581
2936
  if (!chatServiceRef.current) {
1582
2937
  throw new Error("Chat service not initialized");
1583
2938
  }
@@ -1585,25 +2940,28 @@ function useChat(options = {}) {
1585
2940
  setError(null);
1586
2941
  abortControllerRef.current = new AbortController;
1587
2942
  try {
1588
- const userMessage = {
1589
- id: `msg_${Date.now()}`,
1590
- conversationId: conversationId ?? "",
1591
- role: "user",
1592
- content,
1593
- status: "completed",
1594
- createdAt: new Date,
1595
- updatedAt: new Date,
1596
- attachments
1597
- };
1598
- setMessages((prev) => [...prev, userMessage]);
1599
- onSend?.(userMessage);
2943
+ if (!opts?.skipUserAppend) {
2944
+ const userMessage = {
2945
+ id: `msg_${Date.now()}`,
2946
+ conversationId: conversationId ?? "",
2947
+ role: "user",
2948
+ content,
2949
+ status: "completed",
2950
+ createdAt: new Date,
2951
+ updatedAt: new Date,
2952
+ attachments
2953
+ };
2954
+ setMessages((prev) => [...prev, userMessage]);
2955
+ onSend?.(userMessage);
2956
+ }
1600
2957
  if (streaming) {
1601
2958
  const result = await chatServiceRef.current.stream({
1602
2959
  conversationId: conversationId ?? undefined,
1603
2960
  content,
1604
- attachments
2961
+ attachments,
2962
+ skipUserAppend: opts?.skipUserAppend
1605
2963
  });
1606
- if (!conversationId) {
2964
+ if (!conversationId && !opts?.skipUserAppend) {
1607
2965
  setConversationId(result.conversationId);
1608
2966
  }
1609
2967
  const assistantMessage = {
@@ -1684,7 +3042,8 @@ function useChat(options = {}) {
1684
3042
  const result = await chatServiceRef.current.send({
1685
3043
  conversationId: conversationId ?? undefined,
1686
3044
  content,
1687
- attachments
3045
+ attachments,
3046
+ skipUserAppend: opts?.skipUserAppend
1688
3047
  });
1689
3048
  setConversation(result.conversation);
1690
3049
  setMessages(result.conversation.messages);
@@ -1701,14 +3060,14 @@ function useChat(options = {}) {
1701
3060
  setIsLoading(false);
1702
3061
  abortControllerRef.current = null;
1703
3062
  }
1704
- }, [conversationId, streaming, onSend, onResponse, onError, messages]);
1705
- const clearConversation = React6.useCallback(() => {
3063
+ }, [conversationId, streaming, onSend, onResponse, onError, onUsage, messages, agentMode, store]);
3064
+ const clearConversation = React11.useCallback(() => {
1706
3065
  setMessages([]);
1707
3066
  setConversation(null);
1708
3067
  setConversationId(null);
1709
3068
  setError(null);
1710
3069
  }, []);
1711
- const regenerate = React6.useCallback(async () => {
3070
+ const regenerate = React11.useCallback(async () => {
1712
3071
  const lastUserMessageIndex = messages.findLastIndex((m) => m.role === "user");
1713
3072
  if (lastUserMessageIndex === -1)
1714
3073
  return;
@@ -1718,11 +3077,49 @@ function useChat(options = {}) {
1718
3077
  setMessages((prev) => prev.slice(0, lastUserMessageIndex + 1));
1719
3078
  await sendMessage(lastUserMessage.content, lastUserMessage.attachments);
1720
3079
  }, [messages, sendMessage]);
1721
- const stop = React6.useCallback(() => {
3080
+ const stop = React11.useCallback(() => {
1722
3081
  abortControllerRef.current?.abort();
1723
3082
  setIsLoading(false);
1724
3083
  }, []);
1725
- const addToolApprovalResponse = React6.useCallback((_toolCallId, _result) => {
3084
+ const createNewConversation = clearConversation;
3085
+ const editMessage = React11.useCallback(async (messageId, newContent) => {
3086
+ if (!chatServiceRef.current || !conversationId)
3087
+ return;
3088
+ const msg = messages.find((m) => m.id === messageId);
3089
+ if (!msg || msg.role !== "user")
3090
+ return;
3091
+ await chatServiceRef.current.updateMessage(conversationId, messageId, { content: newContent });
3092
+ const truncated = await chatServiceRef.current.truncateAfter(conversationId, messageId);
3093
+ if (truncated) {
3094
+ setMessages(truncated.messages);
3095
+ }
3096
+ await sendMessage(newContent, undefined, { skipUserAppend: true });
3097
+ }, [conversationId, messages, sendMessage]);
3098
+ const forkConversation = React11.useCallback(async (upToMessageId) => {
3099
+ if (!chatServiceRef.current)
3100
+ return null;
3101
+ const idToFork = conversationId ?? conversation?.id;
3102
+ if (!idToFork)
3103
+ return null;
3104
+ try {
3105
+ const forked = await chatServiceRef.current.forkConversation(idToFork, upToMessageId);
3106
+ setConversationId(forked.id);
3107
+ setConversation(forked);
3108
+ setMessages(forked.messages);
3109
+ return forked.id;
3110
+ } catch {
3111
+ return null;
3112
+ }
3113
+ }, [conversationId, conversation]);
3114
+ const updateConversationFn = React11.useCallback(async (updates) => {
3115
+ if (!chatServiceRef.current || !conversationId)
3116
+ return null;
3117
+ const updated = await chatServiceRef.current.updateConversation(conversationId, updates);
3118
+ if (updated)
3119
+ setConversation(updated);
3120
+ return updated;
3121
+ }, [conversationId]);
3122
+ const addToolApprovalResponse = React11.useCallback((_toolCallId, _result) => {
1726
3123
  throw new Error(`addToolApprovalResponse: Tool approval requires server route with toUIMessageStreamResponse. ` + `Use createChatRoute and @ai-sdk/react useChat for tools with requireApproval.`);
1727
3124
  }, []);
1728
3125
  const hasApprovalTools = toolsDefs?.some((t) => t.requireApproval) ?? false;
@@ -1736,40 +3133,751 @@ function useChat(options = {}) {
1736
3133
  setConversationId,
1737
3134
  regenerate,
1738
3135
  stop,
3136
+ createNewConversation,
3137
+ editMessage,
3138
+ forkConversation,
3139
+ updateConversation: updateConversationFn,
1739
3140
  ...hasApprovalTools && { addToolApprovalResponse }
1740
3141
  };
1741
3142
  }
1742
- // src/presentation/hooks/useProviders.tsx
1743
- import * as React7 from "react";
1744
- import {
1745
- getAvailableProviders,
1746
- getModelsForProvider as getModelsForProvider2
1747
- } from "@contractspec/lib.ai-providers";
1748
- "use client";
1749
- function useProviders() {
1750
- const [providers, setProviders] = React7.useState([]);
1751
- const [isLoading, setIsLoading] = React7.useState(true);
1752
- const loadProviders = React7.useCallback(async () => {
1753
- setIsLoading(true);
1754
- try {
1755
- const available = getAvailableProviders();
1756
- const providersWithModels = available.map((p) => ({
1757
- ...p,
1758
- models: getModelsForProvider2(p.provider)
1759
- }));
1760
- setProviders(providersWithModels);
1761
- } catch (error) {
1762
- console.error("Failed to load providers:", error);
1763
- } finally {
1764
- setIsLoading(false);
3143
+
3144
+ // src/core/local-storage-conversation-store.ts
3145
+ var DEFAULT_KEY = "contractspec:ai-chat:conversations";
3146
+ function generateId2(prefix) {
3147
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
3148
+ }
3149
+ function toSerializable(conv) {
3150
+ return {
3151
+ ...conv,
3152
+ createdAt: conv.createdAt.toISOString(),
3153
+ updatedAt: conv.updatedAt.toISOString(),
3154
+ messages: conv.messages.map((m) => ({
3155
+ ...m,
3156
+ createdAt: m.createdAt.toISOString(),
3157
+ updatedAt: m.updatedAt.toISOString()
3158
+ }))
3159
+ };
3160
+ }
3161
+ function fromSerializable(raw) {
3162
+ const messages = raw.messages?.map((m) => ({
3163
+ ...m,
3164
+ createdAt: new Date(m.createdAt),
3165
+ updatedAt: new Date(m.updatedAt)
3166
+ })) ?? [];
3167
+ return {
3168
+ ...raw,
3169
+ createdAt: new Date(raw.createdAt),
3170
+ updatedAt: new Date(raw.updatedAt),
3171
+ messages
3172
+ };
3173
+ }
3174
+ function loadAll(key) {
3175
+ if (typeof window === "undefined")
3176
+ return new Map;
3177
+ try {
3178
+ const raw = window.localStorage.getItem(key);
3179
+ if (!raw)
3180
+ return new Map;
3181
+ const arr = JSON.parse(raw);
3182
+ const map = new Map;
3183
+ for (const item of arr) {
3184
+ const conv = fromSerializable(item);
3185
+ map.set(conv.id, conv);
1765
3186
  }
1766
- }, []);
1767
- React7.useEffect(() => {
3187
+ return map;
3188
+ } catch {
3189
+ return new Map;
3190
+ }
3191
+ }
3192
+ function saveAll(key, map) {
3193
+ if (typeof window === "undefined")
3194
+ return;
3195
+ try {
3196
+ const arr = Array.from(map.values()).map(toSerializable);
3197
+ window.localStorage.setItem(key, JSON.stringify(arr));
3198
+ } catch {}
3199
+ }
3200
+
3201
+ class LocalStorageConversationStore {
3202
+ key;
3203
+ cache = null;
3204
+ constructor(storageKey = DEFAULT_KEY) {
3205
+ this.key = storageKey;
3206
+ }
3207
+ getMap() {
3208
+ if (!this.cache) {
3209
+ this.cache = loadAll(this.key);
3210
+ }
3211
+ return this.cache;
3212
+ }
3213
+ persist() {
3214
+ saveAll(this.key, this.getMap());
3215
+ }
3216
+ async get(conversationId) {
3217
+ return this.getMap().get(conversationId) ?? null;
3218
+ }
3219
+ async create(conversation) {
3220
+ const now = new Date;
3221
+ const full = {
3222
+ ...conversation,
3223
+ id: generateId2("conv"),
3224
+ createdAt: now,
3225
+ updatedAt: now
3226
+ };
3227
+ this.getMap().set(full.id, full);
3228
+ this.persist();
3229
+ return full;
3230
+ }
3231
+ async update(conversationId, updates) {
3232
+ const conv = this.getMap().get(conversationId);
3233
+ if (!conv)
3234
+ return null;
3235
+ const updated = {
3236
+ ...conv,
3237
+ ...updates,
3238
+ updatedAt: new Date
3239
+ };
3240
+ this.getMap().set(conversationId, updated);
3241
+ this.persist();
3242
+ return updated;
3243
+ }
3244
+ async appendMessage(conversationId, message) {
3245
+ const conv = this.getMap().get(conversationId);
3246
+ if (!conv)
3247
+ throw new Error(`Conversation ${conversationId} not found`);
3248
+ const now = new Date;
3249
+ const fullMessage = {
3250
+ ...message,
3251
+ id: generateId2("msg"),
3252
+ conversationId,
3253
+ createdAt: now,
3254
+ updatedAt: now
3255
+ };
3256
+ conv.messages.push(fullMessage);
3257
+ conv.updatedAt = now;
3258
+ this.persist();
3259
+ return fullMessage;
3260
+ }
3261
+ async updateMessage(conversationId, messageId, updates) {
3262
+ const conv = this.getMap().get(conversationId);
3263
+ if (!conv)
3264
+ return null;
3265
+ const idx = conv.messages.findIndex((m) => m.id === messageId);
3266
+ if (idx === -1)
3267
+ return null;
3268
+ const msg = conv.messages[idx];
3269
+ if (!msg)
3270
+ return null;
3271
+ const updated = {
3272
+ ...msg,
3273
+ ...updates,
3274
+ updatedAt: new Date
3275
+ };
3276
+ conv.messages[idx] = updated;
3277
+ conv.updatedAt = new Date;
3278
+ this.persist();
3279
+ return updated;
3280
+ }
3281
+ async delete(conversationId) {
3282
+ const deleted = this.getMap().delete(conversationId);
3283
+ if (deleted)
3284
+ this.persist();
3285
+ return deleted;
3286
+ }
3287
+ async list(options) {
3288
+ let results = Array.from(this.getMap().values());
3289
+ if (options?.status) {
3290
+ results = results.filter((c) => c.status === options.status);
3291
+ }
3292
+ if (options?.projectId) {
3293
+ results = results.filter((c) => c.projectId === options.projectId);
3294
+ }
3295
+ if (options?.tags && options.tags.length > 0) {
3296
+ const tagSet = new Set(options.tags);
3297
+ results = results.filter((c) => c.tags && c.tags.some((t) => tagSet.has(t)));
3298
+ }
3299
+ results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
3300
+ const offset = options?.offset ?? 0;
3301
+ const limit = options?.limit ?? 100;
3302
+ return results.slice(offset, offset + limit);
3303
+ }
3304
+ async fork(conversationId, upToMessageId) {
3305
+ const source = this.getMap().get(conversationId);
3306
+ if (!source)
3307
+ throw new Error(`Conversation ${conversationId} not found`);
3308
+ let messagesToCopy = source.messages;
3309
+ if (upToMessageId) {
3310
+ const idx = source.messages.findIndex((m) => m.id === upToMessageId);
3311
+ if (idx === -1)
3312
+ throw new Error(`Message ${upToMessageId} not found`);
3313
+ messagesToCopy = source.messages.slice(0, idx + 1);
3314
+ }
3315
+ const now = new Date;
3316
+ const forkedMessages = messagesToCopy.map((m) => ({
3317
+ ...m,
3318
+ id: generateId2("msg"),
3319
+ conversationId: "",
3320
+ createdAt: new Date(m.createdAt),
3321
+ updatedAt: new Date(m.updatedAt)
3322
+ }));
3323
+ const forked = {
3324
+ ...source,
3325
+ id: generateId2("conv"),
3326
+ title: source.title ? `${source.title} (fork)` : undefined,
3327
+ forkedFromId: source.id,
3328
+ createdAt: now,
3329
+ updatedAt: now,
3330
+ messages: forkedMessages
3331
+ };
3332
+ for (const m of forked.messages) {
3333
+ m.conversationId = forked.id;
3334
+ }
3335
+ this.getMap().set(forked.id, forked);
3336
+ this.persist();
3337
+ return forked;
3338
+ }
3339
+ async truncateAfter(conversationId, messageId) {
3340
+ const conv = this.getMap().get(conversationId);
3341
+ if (!conv)
3342
+ return null;
3343
+ const idx = conv.messages.findIndex((m) => m.id === messageId);
3344
+ if (idx === -1)
3345
+ return null;
3346
+ conv.messages = conv.messages.slice(0, idx + 1);
3347
+ conv.updatedAt = new Date;
3348
+ this.persist();
3349
+ return conv;
3350
+ }
3351
+ async search(query, limit = 20) {
3352
+ const lowerQuery = query.toLowerCase();
3353
+ const results = [];
3354
+ for (const conv of this.getMap().values()) {
3355
+ if (conv.title?.toLowerCase().includes(lowerQuery)) {
3356
+ results.push(conv);
3357
+ continue;
3358
+ }
3359
+ if (conv.messages.some((m) => m.content.toLowerCase().includes(lowerQuery))) {
3360
+ results.push(conv);
3361
+ }
3362
+ if (results.length >= limit)
3363
+ break;
3364
+ }
3365
+ return results;
3366
+ }
3367
+ }
3368
+ function createLocalStorageConversationStore(storageKey) {
3369
+ return new LocalStorageConversationStore(storageKey);
3370
+ }
3371
+
3372
+ // src/presentation/components/ChatWithSidebar.tsx
3373
+ import { jsx as jsx10, jsxs as jsxs10 } from "react/jsx-runtime";
3374
+ "use client";
3375
+ var defaultStore = createLocalStorageConversationStore();
3376
+ function ChatWithSidebar({
3377
+ store = defaultStore,
3378
+ projectId,
3379
+ tags,
3380
+ className,
3381
+ thinkingLevel: initialThinkingLevel = "thinking",
3382
+ presentationRenderer,
3383
+ formRenderer,
3384
+ ...useChatOptions
3385
+ }) {
3386
+ const effectiveStore = store;
3387
+ const [thinkingLevel, setThinkingLevel] = React12.useState(initialThinkingLevel);
3388
+ const chat = useChat({
3389
+ ...useChatOptions,
3390
+ store: effectiveStore,
3391
+ thinkingLevel
3392
+ });
3393
+ const {
3394
+ messages,
3395
+ conversation,
3396
+ sendMessage,
3397
+ isLoading,
3398
+ setConversationId,
3399
+ createNewConversation,
3400
+ editMessage,
3401
+ forkConversation,
3402
+ updateConversation
3403
+ } = chat;
3404
+ const selectedConversationId = conversation?.id ?? null;
3405
+ const handleSelectConversation = React12.useCallback((id) => {
3406
+ setConversationId(id);
3407
+ }, [setConversationId]);
3408
+ return /* @__PURE__ */ jsxs10("div", {
3409
+ className: className ?? "flex h-full w-full",
3410
+ children: [
3411
+ /* @__PURE__ */ jsx10(ChatSidebar, {
3412
+ store: effectiveStore,
3413
+ selectedConversationId,
3414
+ onSelectConversation: handleSelectConversation,
3415
+ onCreateNew: createNewConversation,
3416
+ projectId,
3417
+ tags,
3418
+ selectedConversation: conversation,
3419
+ onUpdateConversation: updateConversation ? async (id, updates) => {
3420
+ if (id === selectedConversationId) {
3421
+ await updateConversation(updates);
3422
+ }
3423
+ } : undefined
3424
+ }),
3425
+ /* @__PURE__ */ jsx10("div", {
3426
+ className: "flex min-w-0 flex-1 flex-col",
3427
+ children: /* @__PURE__ */ jsx10(ChatWithExport, {
3428
+ messages,
3429
+ conversation,
3430
+ onCreateNew: createNewConversation,
3431
+ onFork: forkConversation,
3432
+ onEditMessage: editMessage,
3433
+ thinkingLevel,
3434
+ onThinkingLevelChange: setThinkingLevel,
3435
+ presentationRenderer,
3436
+ formRenderer,
3437
+ children: /* @__PURE__ */ jsx10(ChatInput, {
3438
+ onSend: (content, att) => sendMessage(content, att),
3439
+ disabled: isLoading,
3440
+ isLoading
3441
+ })
3442
+ })
3443
+ })
3444
+ ]
3445
+ });
3446
+ }
3447
+ // src/presentation/components/ModelPicker.tsx
3448
+ import * as React13 from "react";
3449
+ import { cn as cn7 } from "@contractspec/lib.ui-kit-web/ui/utils";
3450
+ import { Button as Button6 } from "@contractspec/lib.design-system";
3451
+ import {
3452
+ Select as Select2,
3453
+ SelectContent as SelectContent2,
3454
+ SelectItem as SelectItem2,
3455
+ SelectTrigger as SelectTrigger2,
3456
+ SelectValue as SelectValue2
3457
+ } from "@contractspec/lib.ui-kit-web/ui/select";
3458
+ import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
3459
+ import { Label as Label2 } from "@contractspec/lib.ui-kit-web/ui/label";
3460
+ import { Bot as Bot2, Cloud, Cpu, Sparkles } from "lucide-react";
3461
+ import {
3462
+ getModelsForProvider
3463
+ } from "@contractspec/lib.ai-providers";
3464
+ import { jsx as jsx11, jsxs as jsxs11 } from "react/jsx-runtime";
3465
+ "use client";
3466
+ var PROVIDER_ICONS = {
3467
+ ollama: /* @__PURE__ */ jsx11(Cpu, {
3468
+ className: "h-4 w-4"
3469
+ }),
3470
+ openai: /* @__PURE__ */ jsx11(Bot2, {
3471
+ className: "h-4 w-4"
3472
+ }),
3473
+ anthropic: /* @__PURE__ */ jsx11(Sparkles, {
3474
+ className: "h-4 w-4"
3475
+ }),
3476
+ mistral: /* @__PURE__ */ jsx11(Cloud, {
3477
+ className: "h-4 w-4"
3478
+ }),
3479
+ gemini: /* @__PURE__ */ jsx11(Sparkles, {
3480
+ className: "h-4 w-4"
3481
+ })
3482
+ };
3483
+ var PROVIDER_NAMES = {
3484
+ ollama: "Ollama (Local)",
3485
+ openai: "OpenAI",
3486
+ anthropic: "Anthropic",
3487
+ mistral: "Mistral",
3488
+ gemini: "Google Gemini"
3489
+ };
3490
+ var MODE_BADGES = {
3491
+ local: { label: "Local", variant: "secondary" },
3492
+ byok: { label: "BYOK", variant: "outline" },
3493
+ managed: { label: "Managed", variant: "default" }
3494
+ };
3495
+ function ModelPicker({
3496
+ value,
3497
+ onChange,
3498
+ availableProviders,
3499
+ className,
3500
+ compact = false
3501
+ }) {
3502
+ const providers = availableProviders ?? [
3503
+ { provider: "ollama", available: true, mode: "local" },
3504
+ { provider: "openai", available: true, mode: "byok" },
3505
+ { provider: "anthropic", available: true, mode: "byok" },
3506
+ { provider: "mistral", available: true, mode: "byok" },
3507
+ { provider: "gemini", available: true, mode: "byok" }
3508
+ ];
3509
+ const models = getModelsForProvider(value.provider);
3510
+ const selectedModel = models.find((m) => m.id === value.model);
3511
+ const handleProviderChange = React13.useCallback((providerName) => {
3512
+ const provider = providerName;
3513
+ const providerInfo = providers.find((p) => p.provider === provider);
3514
+ const providerModels = getModelsForProvider(provider);
3515
+ const defaultModel = providerModels[0]?.id ?? "";
3516
+ onChange({
3517
+ provider,
3518
+ model: defaultModel,
3519
+ mode: providerInfo?.mode ?? "byok"
3520
+ });
3521
+ }, [onChange, providers]);
3522
+ const handleModelChange = React13.useCallback((modelId) => {
3523
+ onChange({
3524
+ ...value,
3525
+ model: modelId
3526
+ });
3527
+ }, [onChange, value]);
3528
+ if (compact) {
3529
+ return /* @__PURE__ */ jsxs11("div", {
3530
+ className: cn7("flex items-center gap-2", className),
3531
+ children: [
3532
+ /* @__PURE__ */ jsxs11(Select2, {
3533
+ value: value.provider,
3534
+ onValueChange: handleProviderChange,
3535
+ children: [
3536
+ /* @__PURE__ */ jsx11(SelectTrigger2, {
3537
+ className: "w-[140px]",
3538
+ children: /* @__PURE__ */ jsx11(SelectValue2, {})
3539
+ }),
3540
+ /* @__PURE__ */ jsx11(SelectContent2, {
3541
+ children: providers.map((p) => /* @__PURE__ */ jsx11(SelectItem2, {
3542
+ value: p.provider,
3543
+ disabled: !p.available,
3544
+ children: /* @__PURE__ */ jsxs11("div", {
3545
+ className: "flex items-center gap-2",
3546
+ children: [
3547
+ PROVIDER_ICONS[p.provider],
3548
+ /* @__PURE__ */ jsx11("span", {
3549
+ children: PROVIDER_NAMES[p.provider]
3550
+ })
3551
+ ]
3552
+ })
3553
+ }, p.provider))
3554
+ })
3555
+ ]
3556
+ }),
3557
+ /* @__PURE__ */ jsxs11(Select2, {
3558
+ value: value.model,
3559
+ onValueChange: handleModelChange,
3560
+ children: [
3561
+ /* @__PURE__ */ jsx11(SelectTrigger2, {
3562
+ className: "w-[160px]",
3563
+ children: /* @__PURE__ */ jsx11(SelectValue2, {})
3564
+ }),
3565
+ /* @__PURE__ */ jsx11(SelectContent2, {
3566
+ children: models.map((m) => /* @__PURE__ */ jsx11(SelectItem2, {
3567
+ value: m.id,
3568
+ children: m.name
3569
+ }, m.id))
3570
+ })
3571
+ ]
3572
+ })
3573
+ ]
3574
+ });
3575
+ }
3576
+ return /* @__PURE__ */ jsxs11("div", {
3577
+ className: cn7("flex flex-col gap-3", className),
3578
+ children: [
3579
+ /* @__PURE__ */ jsxs11("div", {
3580
+ className: "flex flex-col gap-1.5",
3581
+ children: [
3582
+ /* @__PURE__ */ jsx11(Label2, {
3583
+ htmlFor: "provider-selection",
3584
+ className: "text-sm font-medium",
3585
+ children: "Provider"
3586
+ }),
3587
+ /* @__PURE__ */ jsx11("div", {
3588
+ className: "flex flex-wrap gap-2",
3589
+ id: "provider-selection",
3590
+ children: providers.map((p) => /* @__PURE__ */ jsxs11(Button6, {
3591
+ variant: value.provider === p.provider ? "default" : "outline",
3592
+ size: "sm",
3593
+ onPress: () => p.available && handleProviderChange(p.provider),
3594
+ disabled: !p.available,
3595
+ className: cn7(!p.available && "opacity-50"),
3596
+ children: [
3597
+ PROVIDER_ICONS[p.provider],
3598
+ /* @__PURE__ */ jsx11("span", {
3599
+ children: PROVIDER_NAMES[p.provider]
3600
+ }),
3601
+ /* @__PURE__ */ jsx11(Badge, {
3602
+ variant: MODE_BADGES[p.mode].variant,
3603
+ className: "ml-1",
3604
+ children: MODE_BADGES[p.mode].label
3605
+ })
3606
+ ]
3607
+ }, p.provider))
3608
+ })
3609
+ ]
3610
+ }),
3611
+ /* @__PURE__ */ jsxs11("div", {
3612
+ className: "flex flex-col gap-1.5",
3613
+ children: [
3614
+ /* @__PURE__ */ jsx11(Label2, {
3615
+ htmlFor: "model-picker",
3616
+ className: "text-sm font-medium",
3617
+ children: "Model"
3618
+ }),
3619
+ /* @__PURE__ */ jsxs11(Select2, {
3620
+ name: "model-picker",
3621
+ value: value.model,
3622
+ onValueChange: handleModelChange,
3623
+ children: [
3624
+ /* @__PURE__ */ jsx11(SelectTrigger2, {
3625
+ children: /* @__PURE__ */ jsx11(SelectValue2, {
3626
+ placeholder: "Select a model"
3627
+ })
3628
+ }),
3629
+ /* @__PURE__ */ jsx11(SelectContent2, {
3630
+ children: models.map((m) => /* @__PURE__ */ jsx11(SelectItem2, {
3631
+ value: m.id,
3632
+ children: /* @__PURE__ */ jsxs11("div", {
3633
+ className: "flex items-center gap-2",
3634
+ children: [
3635
+ /* @__PURE__ */ jsx11("span", {
3636
+ children: m.name
3637
+ }),
3638
+ /* @__PURE__ */ jsxs11("span", {
3639
+ className: "text-muted-foreground text-xs",
3640
+ children: [
3641
+ Math.round(m.contextWindow / 1000),
3642
+ "K"
3643
+ ]
3644
+ }),
3645
+ m.capabilities.vision && /* @__PURE__ */ jsx11(Badge, {
3646
+ variant: "outline",
3647
+ className: "text-xs",
3648
+ children: "Vision"
3649
+ }),
3650
+ m.capabilities.reasoning && /* @__PURE__ */ jsx11(Badge, {
3651
+ variant: "outline",
3652
+ className: "text-xs",
3653
+ children: "Reasoning"
3654
+ })
3655
+ ]
3656
+ })
3657
+ }, m.id))
3658
+ })
3659
+ ]
3660
+ })
3661
+ ]
3662
+ }),
3663
+ selectedModel && /* @__PURE__ */ jsxs11("div", {
3664
+ className: "text-muted-foreground flex flex-wrap gap-2 text-xs",
3665
+ children: [
3666
+ /* @__PURE__ */ jsxs11("span", {
3667
+ children: [
3668
+ "Context: ",
3669
+ Math.round(selectedModel.contextWindow / 1000),
3670
+ "K tokens"
3671
+ ]
3672
+ }),
3673
+ selectedModel.capabilities.vision && /* @__PURE__ */ jsx11("span", {
3674
+ children: "• Vision"
3675
+ }),
3676
+ selectedModel.capabilities.tools && /* @__PURE__ */ jsx11("span", {
3677
+ children: "• Tools"
3678
+ }),
3679
+ selectedModel.capabilities.reasoning && /* @__PURE__ */ jsx11("span", {
3680
+ children: "• Reasoning"
3681
+ })
3682
+ ]
3683
+ })
3684
+ ]
3685
+ });
3686
+ }
3687
+ // src/presentation/components/ContextIndicator.tsx
3688
+ import { cn as cn8 } from "@contractspec/lib.ui-kit-web/ui/utils";
3689
+ import { Badge as Badge2 } from "@contractspec/lib.ui-kit-web/ui/badge";
3690
+ import {
3691
+ Tooltip,
3692
+ TooltipContent,
3693
+ TooltipProvider,
3694
+ TooltipTrigger
3695
+ } from "@contractspec/lib.ui-kit-web/ui/tooltip";
3696
+ import { FolderOpen, FileCode, Zap, Info } from "lucide-react";
3697
+ import { jsx as jsx12, jsxs as jsxs12, Fragment as Fragment6 } from "react/jsx-runtime";
3698
+ "use client";
3699
+ function ContextIndicator({
3700
+ summary,
3701
+ active = false,
3702
+ className,
3703
+ showDetails = true
3704
+ }) {
3705
+ if (!summary && !active) {
3706
+ return /* @__PURE__ */ jsxs12("div", {
3707
+ className: cn8("flex items-center gap-1.5 text-sm", "text-muted-foreground", className),
3708
+ children: [
3709
+ /* @__PURE__ */ jsx12(Info, {
3710
+ className: "h-4 w-4"
3711
+ }),
3712
+ /* @__PURE__ */ jsx12("span", {
3713
+ children: "No workspace context"
3714
+ })
3715
+ ]
3716
+ });
3717
+ }
3718
+ const content = /* @__PURE__ */ jsxs12("div", {
3719
+ className: cn8("flex items-center gap-2", active ? "text-foreground" : "text-muted-foreground", className),
3720
+ children: [
3721
+ /* @__PURE__ */ jsxs12(Badge2, {
3722
+ variant: active ? "default" : "secondary",
3723
+ className: "flex items-center gap-1",
3724
+ children: [
3725
+ /* @__PURE__ */ jsx12(Zap, {
3726
+ className: "h-3 w-3"
3727
+ }),
3728
+ "Context"
3729
+ ]
3730
+ }),
3731
+ summary && showDetails && /* @__PURE__ */ jsxs12(Fragment6, {
3732
+ children: [
3733
+ /* @__PURE__ */ jsxs12("div", {
3734
+ className: "flex items-center gap-1 text-xs",
3735
+ children: [
3736
+ /* @__PURE__ */ jsx12(FolderOpen, {
3737
+ className: "h-3.5 w-3.5"
3738
+ }),
3739
+ /* @__PURE__ */ jsx12("span", {
3740
+ children: summary.name
3741
+ })
3742
+ ]
3743
+ }),
3744
+ /* @__PURE__ */ jsxs12("div", {
3745
+ className: "flex items-center gap-1 text-xs",
3746
+ children: [
3747
+ /* @__PURE__ */ jsx12(FileCode, {
3748
+ className: "h-3.5 w-3.5"
3749
+ }),
3750
+ /* @__PURE__ */ jsxs12("span", {
3751
+ children: [
3752
+ summary.specs.total,
3753
+ " specs"
3754
+ ]
3755
+ })
3756
+ ]
3757
+ })
3758
+ ]
3759
+ })
3760
+ ]
3761
+ });
3762
+ if (!summary) {
3763
+ return content;
3764
+ }
3765
+ return /* @__PURE__ */ jsx12(TooltipProvider, {
3766
+ children: /* @__PURE__ */ jsxs12(Tooltip, {
3767
+ children: [
3768
+ /* @__PURE__ */ jsx12(TooltipTrigger, {
3769
+ asChild: true,
3770
+ children: content
3771
+ }),
3772
+ /* @__PURE__ */ jsx12(TooltipContent, {
3773
+ side: "bottom",
3774
+ className: "max-w-[300px]",
3775
+ children: /* @__PURE__ */ jsxs12("div", {
3776
+ className: "flex flex-col gap-2 text-sm",
3777
+ children: [
3778
+ /* @__PURE__ */ jsx12("div", {
3779
+ className: "font-medium",
3780
+ children: summary.name
3781
+ }),
3782
+ /* @__PURE__ */ jsx12("div", {
3783
+ className: "text-muted-foreground text-xs",
3784
+ children: summary.path
3785
+ }),
3786
+ /* @__PURE__ */ jsx12("div", {
3787
+ className: "border-t pt-2",
3788
+ children: /* @__PURE__ */ jsxs12("div", {
3789
+ className: "grid grid-cols-2 gap-1 text-xs",
3790
+ children: [
3791
+ /* @__PURE__ */ jsx12("span", {
3792
+ children: "Commands:"
3793
+ }),
3794
+ /* @__PURE__ */ jsx12("span", {
3795
+ className: "text-right",
3796
+ children: summary.specs.commands
3797
+ }),
3798
+ /* @__PURE__ */ jsx12("span", {
3799
+ children: "Queries:"
3800
+ }),
3801
+ /* @__PURE__ */ jsx12("span", {
3802
+ className: "text-right",
3803
+ children: summary.specs.queries
3804
+ }),
3805
+ /* @__PURE__ */ jsx12("span", {
3806
+ children: "Events:"
3807
+ }),
3808
+ /* @__PURE__ */ jsx12("span", {
3809
+ className: "text-right",
3810
+ children: summary.specs.events
3811
+ }),
3812
+ /* @__PURE__ */ jsx12("span", {
3813
+ children: "Presentations:"
3814
+ }),
3815
+ /* @__PURE__ */ jsx12("span", {
3816
+ className: "text-right",
3817
+ children: summary.specs.presentations
3818
+ })
3819
+ ]
3820
+ })
3821
+ }),
3822
+ /* @__PURE__ */ jsxs12("div", {
3823
+ className: "border-t pt-2 text-xs",
3824
+ children: [
3825
+ /* @__PURE__ */ jsxs12("span", {
3826
+ children: [
3827
+ summary.files.total,
3828
+ " files"
3829
+ ]
3830
+ }),
3831
+ /* @__PURE__ */ jsx12("span", {
3832
+ className: "mx-1",
3833
+ children: "•"
3834
+ }),
3835
+ /* @__PURE__ */ jsxs12("span", {
3836
+ children: [
3837
+ summary.files.specFiles,
3838
+ " spec files"
3839
+ ]
3840
+ })
3841
+ ]
3842
+ })
3843
+ ]
3844
+ })
3845
+ })
3846
+ ]
3847
+ })
3848
+ });
3849
+ }
3850
+ // src/presentation/hooks/useProviders.tsx
3851
+ import * as React14 from "react";
3852
+ import {
3853
+ getAvailableProviders,
3854
+ getModelsForProvider as getModelsForProvider2
3855
+ } from "@contractspec/lib.ai-providers";
3856
+ "use client";
3857
+ function useProviders() {
3858
+ const [providers, setProviders] = React14.useState([]);
3859
+ const [isLoading, setIsLoading] = React14.useState(true);
3860
+ const loadProviders = React14.useCallback(async () => {
3861
+ setIsLoading(true);
3862
+ try {
3863
+ const available = getAvailableProviders();
3864
+ const providersWithModels = available.map((p) => ({
3865
+ ...p,
3866
+ models: getModelsForProvider2(p.provider)
3867
+ }));
3868
+ setProviders(providersWithModels);
3869
+ } catch (error) {
3870
+ console.error("Failed to load providers:", error);
3871
+ } finally {
3872
+ setIsLoading(false);
3873
+ }
3874
+ }, []);
3875
+ React14.useEffect(() => {
1768
3876
  loadProviders();
1769
3877
  }, [loadProviders]);
1770
- const availableProviders = React7.useMemo(() => providers.filter((p) => p.available), [providers]);
1771
- const isAvailable = React7.useCallback((provider) => providers.some((p) => p.provider === provider && p.available), [providers]);
1772
- const getModelsCallback = React7.useCallback((provider) => providers.find((p) => p.provider === provider)?.models ?? [], [providers]);
3878
+ const availableProviders = React14.useMemo(() => providers.filter((p) => p.available), [providers]);
3879
+ const isAvailable = React14.useCallback((provider) => providers.some((p) => p.provider === provider && p.available), [providers]);
3880
+ const getModelsCallback = React14.useCallback((provider) => providers.find((p) => p.provider === provider)?.models ?? [], [providers]);
1773
3881
  return {
1774
3882
  providers,
1775
3883
  availableProviders,
@@ -1784,12 +3892,22 @@ function useProviders() {
1784
3892
  import { useCompletion } from "@ai-sdk/react";
1785
3893
  export {
1786
3894
  useProviders,
3895
+ useMessageSelection,
3896
+ useConversations,
1787
3897
  useCompletion,
1788
3898
  useChat,
3899
+ isPresentationToolResult,
3900
+ isFormToolResult,
3901
+ ToolResultRenderer,
3902
+ ThinkingLevelPicker,
1789
3903
  ModelPicker,
1790
3904
  ContextIndicator,
1791
3905
  CodePreview,
3906
+ ChatWithSidebar,
3907
+ ChatWithExport,
3908
+ ChatSidebar,
1792
3909
  ChatMessage,
1793
3910
  ChatInput,
3911
+ ChatExportToolbar,
1794
3912
  ChatContainer
1795
3913
  };