@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.
- package/README.md +130 -10
- package/dist/adapters/ai-sdk-bundle-adapter.d.ts +18 -0
- package/dist/adapters/index.d.ts +4 -0
- package/dist/browser/core/index.js +1138 -21
- package/dist/browser/index.js +2816 -651
- package/dist/browser/presentation/components/index.js +3143 -358
- package/dist/browser/presentation/hooks/index.js +961 -43
- package/dist/browser/presentation/index.js +2784 -666
- package/dist/core/agent-adapter.d.ts +53 -0
- package/dist/core/agent-tools-adapter.d.ts +12 -0
- package/dist/core/chat-service.d.ts +49 -1
- package/dist/core/contracts-context.d.ts +46 -0
- package/dist/core/contracts-context.test.d.ts +1 -0
- package/dist/core/conversation-store.d.ts +16 -2
- package/dist/core/create-chat-route.d.ts +3 -0
- package/dist/core/export-formatters.d.ts +29 -0
- package/dist/core/export-formatters.test.d.ts +1 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.js +1138 -21
- package/dist/core/local-storage-conversation-store.d.ts +33 -0
- package/dist/core/message-types.d.ts +6 -0
- package/dist/core/surface-planner-tools.d.ts +23 -0
- package/dist/core/surface-planner-tools.test.d.ts +1 -0
- package/dist/core/thinking-levels.d.ts +38 -0
- package/dist/core/thinking-levels.test.d.ts +1 -0
- package/dist/core/workflow-tools.d.ts +18 -0
- package/dist/core/workflow-tools.test.d.ts +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2816 -651
- package/dist/node/core/index.js +1138 -21
- package/dist/node/index.js +2816 -651
- package/dist/node/presentation/components/index.js +3143 -358
- package/dist/node/presentation/hooks/index.js +961 -43
- package/dist/node/presentation/index.js +2787 -669
- package/dist/presentation/components/ChatContainer.d.ts +3 -1
- package/dist/presentation/components/ChatExportToolbar.d.ts +25 -0
- package/dist/presentation/components/ChatMessage.d.ts +16 -1
- package/dist/presentation/components/ChatSidebar.d.ts +26 -0
- package/dist/presentation/components/ChatWithExport.d.ts +34 -0
- package/dist/presentation/components/ChatWithSidebar.d.ts +19 -0
- package/dist/presentation/components/ThinkingLevelPicker.d.ts +16 -0
- package/dist/presentation/components/ToolResultRenderer.d.ts +33 -0
- package/dist/presentation/components/index.d.ts +6 -0
- package/dist/presentation/components/index.js +3143 -358
- package/dist/presentation/hooks/index.d.ts +2 -0
- package/dist/presentation/hooks/index.js +961 -43
- package/dist/presentation/hooks/useChat.d.ts +44 -2
- package/dist/presentation/hooks/useConversations.d.ts +18 -0
- package/dist/presentation/hooks/useMessageSelection.d.ts +13 -0
- package/dist/presentation/index.js +2787 -669
- 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 {
|
|
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__ */
|
|
46
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
46
47
|
className: cn("relative flex flex-1 flex-col", className),
|
|
47
48
|
children: [
|
|
48
|
-
/* @__PURE__ */
|
|
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__ */
|
|
57
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
53
58
|
className: "flex flex-col gap-4 p-4",
|
|
54
59
|
children
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
showScrollButton && showScrollDown && /* @__PURE__ */
|
|
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__ */
|
|
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__ */
|
|
77
|
+
children: /* @__PURE__ */ jsx("path", {
|
|
73
78
|
d: "m6 9 6 6 6-6"
|
|
74
|
-
}
|
|
75
|
-
}
|
|
79
|
+
})
|
|
80
|
+
}),
|
|
76
81
|
"New messages"
|
|
77
82
|
]
|
|
78
|
-
}
|
|
83
|
+
})
|
|
79
84
|
]
|
|
80
|
-
}
|
|
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 {
|
|
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__ */
|
|
164
|
+
return /* @__PURE__ */ jsxs2("div", {
|
|
157
165
|
className: cn2("overflow-hidden rounded-lg border", "bg-muted/50", className),
|
|
158
166
|
children: [
|
|
159
|
-
/* @__PURE__ */
|
|
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__ */
|
|
170
|
+
/* @__PURE__ */ jsxs2("div", {
|
|
163
171
|
className: "flex items-center gap-2 text-sm",
|
|
164
172
|
children: [
|
|
165
|
-
filename && /* @__PURE__ */
|
|
173
|
+
filename && /* @__PURE__ */ jsx2("span", {
|
|
166
174
|
className: "text-foreground font-mono",
|
|
167
175
|
children: filename
|
|
168
|
-
}
|
|
169
|
-
/* @__PURE__ */
|
|
176
|
+
}),
|
|
177
|
+
/* @__PURE__ */ jsx2("span", {
|
|
170
178
|
className: "text-muted-foreground",
|
|
171
179
|
children: displayLanguage
|
|
172
|
-
}
|
|
180
|
+
})
|
|
173
181
|
]
|
|
174
|
-
}
|
|
175
|
-
/* @__PURE__ */
|
|
182
|
+
}),
|
|
183
|
+
/* @__PURE__ */ jsxs2("div", {
|
|
176
184
|
className: "flex items-center gap-1",
|
|
177
185
|
children: [
|
|
178
|
-
showExecute && onExecute && /* @__PURE__ */
|
|
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__ */
|
|
192
|
+
children: /* @__PURE__ */ jsx2(Play, {
|
|
185
193
|
className: "h-3.5 w-3.5"
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
showDownload && /* @__PURE__ */
|
|
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__ */
|
|
202
|
+
children: /* @__PURE__ */ jsx2(Download, {
|
|
195
203
|
className: "h-3.5 w-3.5"
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
showCopy && /* @__PURE__ */
|
|
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__ */
|
|
212
|
+
children: copied ? /* @__PURE__ */ jsx2(Check, {
|
|
205
213
|
className: "h-3.5 w-3.5 text-green-500"
|
|
206
|
-
}
|
|
214
|
+
}) : /* @__PURE__ */ jsx2(Copy, {
|
|
207
215
|
className: "h-3.5 w-3.5"
|
|
208
|
-
}
|
|
209
|
-
}
|
|
216
|
+
})
|
|
217
|
+
})
|
|
210
218
|
]
|
|
211
|
-
}
|
|
219
|
+
})
|
|
212
220
|
]
|
|
213
|
-
}
|
|
214
|
-
/* @__PURE__ */
|
|
221
|
+
}),
|
|
222
|
+
/* @__PURE__ */ jsx2("div", {
|
|
215
223
|
className: "overflow-auto",
|
|
216
224
|
style: { maxHeight },
|
|
217
|
-
children: /* @__PURE__ */
|
|
225
|
+
children: /* @__PURE__ */ jsx2("pre", {
|
|
218
226
|
className: "p-3",
|
|
219
|
-
children: /* @__PURE__ */
|
|
227
|
+
children: /* @__PURE__ */ jsx2("code", {
|
|
220
228
|
className: "text-sm",
|
|
221
|
-
children: lines.map((line, i) => /* @__PURE__ */
|
|
229
|
+
children: lines.map((line, i) => /* @__PURE__ */ jsxs2("div", {
|
|
222
230
|
className: "flex",
|
|
223
231
|
children: [
|
|
224
|
-
/* @__PURE__ */
|
|
232
|
+
/* @__PURE__ */ jsx2("span", {
|
|
225
233
|
className: "text-muted-foreground mr-4 w-8 text-right select-none",
|
|
226
234
|
children: i + 1
|
|
227
|
-
}
|
|
228
|
-
/* @__PURE__ */
|
|
235
|
+
}),
|
|
236
|
+
/* @__PURE__ */ jsx2("span", {
|
|
229
237
|
className: "flex-1",
|
|
230
238
|
children: line || " "
|
|
231
|
-
}
|
|
239
|
+
})
|
|
232
240
|
]
|
|
233
|
-
}, i
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
}
|
|
241
|
+
}, i))
|
|
242
|
+
})
|
|
243
|
+
})
|
|
244
|
+
})
|
|
237
245
|
]
|
|
238
|
-
}
|
|
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
|
+
})
|
|
299
|
+
]
|
|
300
|
+
});
|
|
239
301
|
}
|
|
240
302
|
|
|
241
303
|
// src/presentation/components/ChatMessage.tsx
|
|
242
|
-
import {
|
|
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__ */
|
|
327
|
+
parts.push(/* @__PURE__ */ jsx4("span", {
|
|
266
328
|
children: text.slice(lastIndex, match.index)
|
|
267
|
-
}, key
|
|
329
|
+
}, key++));
|
|
268
330
|
}
|
|
269
|
-
parts.push(/* @__PURE__ */
|
|
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
|
|
337
|
+
}, key++));
|
|
276
338
|
lastIndex = match.index + match[0].length;
|
|
277
339
|
}
|
|
278
340
|
if (lastIndex < text.length) {
|
|
279
|
-
parts.push(/* @__PURE__ */
|
|
341
|
+
parts.push(/* @__PURE__ */ jsx4("span", {
|
|
280
342
|
children: text.slice(lastIndex)
|
|
281
|
-
}, key
|
|
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__ */
|
|
350
|
+
return /* @__PURE__ */ jsx4("p", {
|
|
289
351
|
className: "whitespace-pre-wrap",
|
|
290
352
|
children: renderInlineMarkdown(content)
|
|
291
|
-
}
|
|
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__ */
|
|
361
|
+
parts.push(/* @__PURE__ */ jsx4("p", {
|
|
300
362
|
className: "whitespace-pre-wrap",
|
|
301
363
|
children: renderInlineMarkdown(before.trim())
|
|
302
|
-
}, key
|
|
364
|
+
}, key++));
|
|
303
365
|
}
|
|
304
|
-
parts.push(/* @__PURE__ */
|
|
366
|
+
parts.push(/* @__PURE__ */ jsx4(CodePreview, {
|
|
305
367
|
code: block.code,
|
|
306
368
|
language: block.language,
|
|
307
369
|
className: "my-2"
|
|
308
|
-
}, key
|
|
370
|
+
}, key++));
|
|
309
371
|
remaining = after ?? "";
|
|
310
372
|
}
|
|
311
373
|
if (remaining.trim()) {
|
|
312
|
-
parts.push(/* @__PURE__ */
|
|
374
|
+
parts.push(/* @__PURE__ */ jsx4("p", {
|
|
313
375
|
className: "whitespace-pre-wrap",
|
|
314
376
|
children: renderInlineMarkdown(remaining.trim())
|
|
315
|
-
}, key
|
|
377
|
+
}, key++));
|
|
316
378
|
}
|
|
317
|
-
return /* @__PURE__ */
|
|
379
|
+
return /* @__PURE__ */ jsx4(Fragment, {
|
|
318
380
|
children: parts
|
|
319
|
-
}
|
|
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
|
-
|
|
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
|
-
|
|
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__ */
|
|
442
|
+
children: /* @__PURE__ */ jsx4(AvatarFallback, {
|
|
342
443
|
className: cn3(isUser ? "bg-primary text-primary-foreground" : "bg-muted"),
|
|
343
|
-
children: isUser ? /* @__PURE__ */
|
|
444
|
+
children: isUser ? /* @__PURE__ */ jsx4(User, {
|
|
344
445
|
className: "h-4 w-4"
|
|
345
|
-
}
|
|
446
|
+
}) : /* @__PURE__ */ jsx4(Bot, {
|
|
346
447
|
className: "h-4 w-4"
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
/* @__PURE__ */
|
|
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__ */
|
|
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__ */
|
|
456
|
+
children: isError && message.error ? /* @__PURE__ */ jsxs4("div", {
|
|
356
457
|
className: "flex items-start gap-2",
|
|
357
458
|
children: [
|
|
358
|
-
/* @__PURE__ */
|
|
459
|
+
/* @__PURE__ */ jsx4(AlertCircle, {
|
|
359
460
|
className: "text-destructive mt-0.5 h-4 w-4 shrink-0"
|
|
360
|
-
}
|
|
361
|
-
/* @__PURE__ */
|
|
461
|
+
}),
|
|
462
|
+
/* @__PURE__ */ jsxs4("div", {
|
|
362
463
|
children: [
|
|
363
|
-
/* @__PURE__ */
|
|
464
|
+
/* @__PURE__ */ jsx4("p", {
|
|
364
465
|
className: "text-destructive font-medium",
|
|
365
466
|
children: message.error.code
|
|
366
|
-
}
|
|
367
|
-
/* @__PURE__ */
|
|
467
|
+
}),
|
|
468
|
+
/* @__PURE__ */ jsx4("p", {
|
|
368
469
|
className: "text-muted-foreground text-sm",
|
|
369
470
|
children: message.error.message
|
|
370
|
-
}
|
|
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
|
-
}
|
|
513
|
+
})
|
|
373
514
|
]
|
|
374
|
-
}
|
|
515
|
+
}) : isStreaming && !message.content ? /* @__PURE__ */ jsxs4("div", {
|
|
375
516
|
className: "flex flex-col gap-2",
|
|
376
517
|
children: [
|
|
377
|
-
/* @__PURE__ */
|
|
518
|
+
/* @__PURE__ */ jsx4(Skeleton, {
|
|
378
519
|
className: "h-4 w-48"
|
|
379
|
-
}
|
|
380
|
-
/* @__PURE__ */
|
|
520
|
+
}),
|
|
521
|
+
/* @__PURE__ */ jsx4(Skeleton, {
|
|
381
522
|
className: "h-4 w-32"
|
|
382
|
-
}
|
|
523
|
+
})
|
|
383
524
|
]
|
|
384
|
-
}
|
|
525
|
+
}) : /* @__PURE__ */ jsx4(MessageContent, {
|
|
385
526
|
content: message.content
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
/* @__PURE__ */
|
|
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__ */
|
|
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
|
-
}
|
|
397
|
-
message.usage && /* @__PURE__ */
|
|
537
|
+
}),
|
|
538
|
+
message.usage && /* @__PURE__ */ jsxs4("span", {
|
|
398
539
|
children: [
|
|
399
540
|
message.usage.inputTokens + message.usage.outputTokens,
|
|
400
541
|
" tokens"
|
|
401
542
|
]
|
|
402
|
-
}
|
|
403
|
-
showCopy && !isUser && message.content && /* @__PURE__ */
|
|
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__ */
|
|
550
|
+
children: copied ? /* @__PURE__ */ jsx4(Check2, {
|
|
410
551
|
className: "h-3 w-3"
|
|
411
|
-
}
|
|
552
|
+
}) : /* @__PURE__ */ jsx4(Copy2, {
|
|
412
553
|
className: "h-3 w-3"
|
|
413
|
-
}
|
|
414
|
-
},
|
|
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, {
|
|
563
|
+
className: "h-3 w-3"
|
|
564
|
+
})
|
|
565
|
+
})
|
|
415
566
|
]
|
|
416
|
-
}
|
|
417
|
-
message.reasoning && /* @__PURE__ */
|
|
567
|
+
}),
|
|
568
|
+
message.reasoning && /* @__PURE__ */ jsxs4("details", {
|
|
418
569
|
className: "text-muted-foreground mt-2 text-sm",
|
|
419
570
|
children: [
|
|
420
|
-
/* @__PURE__ */
|
|
571
|
+
/* @__PURE__ */ jsx4("summary", {
|
|
421
572
|
className: "cursor-pointer hover:underline",
|
|
422
573
|
children: "View reasoning"
|
|
423
|
-
}
|
|
424
|
-
/* @__PURE__ */
|
|
574
|
+
}),
|
|
575
|
+
/* @__PURE__ */ jsx4("div", {
|
|
425
576
|
className: "bg-muted mt-1 rounded-md p-2",
|
|
426
|
-
children: /* @__PURE__ */
|
|
577
|
+
children: /* @__PURE__ */ jsx4("p", {
|
|
427
578
|
className: "whitespace-pre-wrap",
|
|
428
579
|
children: message.reasoning
|
|
429
|
-
}
|
|
430
|
-
}
|
|
580
|
+
})
|
|
581
|
+
})
|
|
431
582
|
]
|
|
432
|
-
}
|
|
433
|
-
message.sources && message.sources.length > 0 && /* @__PURE__ */
|
|
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__ */
|
|
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__ */
|
|
592
|
+
/* @__PURE__ */ jsx4(ExternalLink, {
|
|
442
593
|
className: "h-3 w-3"
|
|
443
|
-
}
|
|
594
|
+
}),
|
|
444
595
|
source.title || source.url || source.id
|
|
445
596
|
]
|
|
446
|
-
}, source.id
|
|
447
|
-
}
|
|
448
|
-
message.toolCalls && message.toolCalls.length > 0 && /* @__PURE__ */
|
|
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__ */
|
|
601
|
+
children: message.toolCalls.map((tc) => /* @__PURE__ */ jsxs4("details", {
|
|
451
602
|
className: "bg-muted border-border rounded-md border",
|
|
452
603
|
children: [
|
|
453
|
-
/* @__PURE__ */
|
|
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__ */
|
|
607
|
+
/* @__PURE__ */ jsx4(Wrench, {
|
|
457
608
|
className: "text-muted-foreground h-4 w-4"
|
|
458
|
-
}
|
|
609
|
+
}),
|
|
459
610
|
tc.name,
|
|
460
|
-
/* @__PURE__ */
|
|
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
|
-
}
|
|
614
|
+
})
|
|
464
615
|
]
|
|
465
|
-
}
|
|
466
|
-
/* @__PURE__ */
|
|
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__ */
|
|
620
|
+
Object.keys(tc.args).length > 0 && /* @__PURE__ */ jsxs4("div", {
|
|
470
621
|
className: "mb-2",
|
|
471
622
|
children: [
|
|
472
|
-
/* @__PURE__ */
|
|
623
|
+
/* @__PURE__ */ jsx4("span", {
|
|
473
624
|
className: "text-muted-foreground font-medium",
|
|
474
625
|
children: "Input:"
|
|
475
|
-
}
|
|
476
|
-
/* @__PURE__ */
|
|
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
|
-
}
|
|
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
|
-
}
|
|
494
|
-
tc.
|
|
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
|
-
}
|
|
643
|
+
})
|
|
498
644
|
]
|
|
499
|
-
}
|
|
645
|
+
})
|
|
500
646
|
]
|
|
501
|
-
}, tc.id
|
|
502
|
-
}
|
|
647
|
+
}, tc.id))
|
|
648
|
+
})
|
|
503
649
|
]
|
|
504
|
-
}
|
|
650
|
+
})
|
|
505
651
|
]
|
|
506
|
-
}
|
|
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 {
|
|
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__ */
|
|
726
|
+
return /* @__PURE__ */ jsxs5("div", {
|
|
581
727
|
className: cn4("flex flex-col gap-2", className),
|
|
582
728
|
children: [
|
|
583
|
-
attachments.length > 0 && /* @__PURE__ */
|
|
729
|
+
attachments.length > 0 && /* @__PURE__ */ jsx5("div", {
|
|
584
730
|
className: "flex flex-wrap gap-2",
|
|
585
|
-
children: attachments.map((attachment) => /* @__PURE__ */
|
|
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__ */
|
|
734
|
+
attachment.type === "code" ? /* @__PURE__ */ jsx5(Code, {
|
|
589
735
|
className: "h-3.5 w-3.5"
|
|
590
|
-
}
|
|
736
|
+
}) : /* @__PURE__ */ jsx5(FileText, {
|
|
591
737
|
className: "h-3.5 w-3.5"
|
|
592
|
-
}
|
|
593
|
-
/* @__PURE__ */
|
|
738
|
+
}),
|
|
739
|
+
/* @__PURE__ */ jsx5("span", {
|
|
594
740
|
className: "max-w-[150px] truncate",
|
|
595
741
|
children: attachment.name
|
|
596
|
-
}
|
|
597
|
-
/* @__PURE__ */
|
|
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__ */
|
|
748
|
+
children: /* @__PURE__ */ jsx5(X2, {
|
|
603
749
|
className: "h-3.5 w-3.5"
|
|
604
|
-
}
|
|
605
|
-
}
|
|
750
|
+
})
|
|
751
|
+
})
|
|
606
752
|
]
|
|
607
|
-
}, attachment.id
|
|
608
|
-
}
|
|
609
|
-
/* @__PURE__ */
|
|
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__ */
|
|
759
|
+
showAttachments && /* @__PURE__ */ jsxs5(Fragment2, {
|
|
614
760
|
children: [
|
|
615
|
-
/* @__PURE__ */
|
|
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
|
-
}
|
|
624
|
-
/* @__PURE__ */
|
|
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__ */
|
|
777
|
+
children: /* @__PURE__ */ jsx5(Paperclip, {
|
|
632
778
|
className: "h-4 w-4"
|
|
633
|
-
}
|
|
634
|
-
}
|
|
779
|
+
})
|
|
780
|
+
})
|
|
635
781
|
]
|
|
636
|
-
}
|
|
637
|
-
/* @__PURE__ */
|
|
782
|
+
}),
|
|
783
|
+
/* @__PURE__ */ jsx5("div", {
|
|
638
784
|
className: "relative flex-1",
|
|
639
|
-
children: /* @__PURE__ */
|
|
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
|
-
}
|
|
649
|
-
}
|
|
650
|
-
/* @__PURE__ */
|
|
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__ */
|
|
801
|
+
children: isLoading ? /* @__PURE__ */ jsx5(Loader2, {
|
|
656
802
|
className: "h-4 w-4 animate-spin"
|
|
657
|
-
}
|
|
803
|
+
}) : /* @__PURE__ */ jsx5(Send, {
|
|
658
804
|
className: "h-4 w-4"
|
|
659
|
-
}
|
|
660
|
-
}
|
|
805
|
+
})
|
|
806
|
+
})
|
|
661
807
|
]
|
|
662
|
-
}
|
|
663
|
-
/* @__PURE__ */
|
|
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
|
-
}
|
|
812
|
+
})
|
|
667
813
|
]
|
|
668
|
-
}
|
|
814
|
+
});
|
|
669
815
|
}
|
|
670
|
-
// src/presentation/components/
|
|
816
|
+
// src/presentation/components/ChatExportToolbar.tsx
|
|
671
817
|
import * as React5 from "react";
|
|
672
|
-
import {
|
|
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,30 +1210,2275 @@ 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";
|
|
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"
|
|
1221
|
+
};
|
|
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"
|
|
1227
|
+
};
|
|
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({
|
|
1276
|
+
value,
|
|
1277
|
+
onChange,
|
|
1278
|
+
className,
|
|
1279
|
+
compact = false
|
|
1280
|
+
}) {
|
|
1281
|
+
const handleChange = React6.useCallback((v) => {
|
|
1282
|
+
onChange(v);
|
|
1283
|
+
}, [onChange]);
|
|
1284
|
+
if (compact) {
|
|
1285
|
+
return /* @__PURE__ */ jsxs7(Select, {
|
|
1286
|
+
value,
|
|
1287
|
+
onValueChange: handleChange,
|
|
1288
|
+
children: [
|
|
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
|
+
})
|
|
1299
|
+
]
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
return /* @__PURE__ */ jsxs7("div", {
|
|
1303
|
+
className: cn5("flex flex-col gap-1.5", className),
|
|
1304
|
+
children: [
|
|
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,
|
|
1314
|
+
children: [
|
|
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
|
+
})
|
|
1327
|
+
]
|
|
1328
|
+
})
|
|
1329
|
+
]
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// src/presentation/hooks/useMessageSelection.ts
|
|
1334
|
+
import * as React7 from "react";
|
|
1335
|
+
"use client";
|
|
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,
|
|
1384
|
+
className,
|
|
1385
|
+
showExport = true,
|
|
1386
|
+
showMessageSelection = true,
|
|
1387
|
+
showScrollButton = true,
|
|
1388
|
+
onCreateNew,
|
|
1389
|
+
onFork,
|
|
1390
|
+
onEditMessage,
|
|
1391
|
+
thinkingLevel = "thinking",
|
|
1392
|
+
onThinkingLevelChange,
|
|
1393
|
+
presentationRenderer,
|
|
1394
|
+
formRenderer
|
|
1395
|
+
}) {
|
|
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" });
|
|
1494
|
+
}
|
|
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"),
|
|
1519
|
+
children: [
|
|
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",
|
|
1525
|
+
children: [
|
|
1526
|
+
/* @__PURE__ */ jsx9("p", {
|
|
1527
|
+
className: "truncate",
|
|
1528
|
+
children: displayTitle
|
|
1529
|
+
}),
|
|
1530
|
+
/* @__PURE__ */ jsxs9("p", {
|
|
1531
|
+
className: "text-muted-foreground text-xs",
|
|
1532
|
+
children: [
|
|
1533
|
+
formatDate(conversation.updatedAt),
|
|
1534
|
+
conversation.projectName && ` · ${conversation.projectName}`,
|
|
1535
|
+
conversation.tags && conversation.tags.length > 0 && /* @__PURE__ */ jsxs9(Fragment5, {
|
|
1536
|
+
children: [
|
|
1537
|
+
" · ",
|
|
1538
|
+
conversation.tags.slice(0, 2).join(", ")
|
|
1539
|
+
]
|
|
1540
|
+
})
|
|
1541
|
+
]
|
|
1542
|
+
})
|
|
1543
|
+
]
|
|
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
|
+
})
|
|
1558
|
+
]
|
|
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
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
// src/presentation/components/ChatWithSidebar.tsx
|
|
1688
|
+
import * as React12 from "react";
|
|
1689
|
+
|
|
1690
|
+
// src/presentation/hooks/useChat.tsx
|
|
1691
|
+
import * as React11 from "react";
|
|
1692
|
+
import { tool as tool4 } from "ai";
|
|
1693
|
+
import { z as z4 } from "zod";
|
|
1694
|
+
|
|
1695
|
+
// src/core/chat-service.ts
|
|
1696
|
+
import { generateText, streamText } from "ai";
|
|
1697
|
+
|
|
1698
|
+
// src/core/conversation-store.ts
|
|
1699
|
+
function generateId(prefix) {
|
|
1700
|
+
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
class InMemoryConversationStore {
|
|
1704
|
+
conversations = new Map;
|
|
1705
|
+
async get(conversationId) {
|
|
1706
|
+
return this.conversations.get(conversationId) ?? null;
|
|
1707
|
+
}
|
|
1708
|
+
async create(conversation) {
|
|
1709
|
+
const now = new Date;
|
|
1710
|
+
const fullConversation = {
|
|
1711
|
+
...conversation,
|
|
1712
|
+
id: generateId("conv"),
|
|
1713
|
+
createdAt: now,
|
|
1714
|
+
updatedAt: now
|
|
1715
|
+
};
|
|
1716
|
+
this.conversations.set(fullConversation.id, fullConversation);
|
|
1717
|
+
return fullConversation;
|
|
1718
|
+
}
|
|
1719
|
+
async update(conversationId, updates) {
|
|
1720
|
+
const conversation = this.conversations.get(conversationId);
|
|
1721
|
+
if (!conversation)
|
|
1722
|
+
return null;
|
|
1723
|
+
const updated = {
|
|
1724
|
+
...conversation,
|
|
1725
|
+
...updates,
|
|
1726
|
+
updatedAt: new Date
|
|
1727
|
+
};
|
|
1728
|
+
this.conversations.set(conversationId, updated);
|
|
1729
|
+
return updated;
|
|
1730
|
+
}
|
|
1731
|
+
async appendMessage(conversationId, message) {
|
|
1732
|
+
const conversation = this.conversations.get(conversationId);
|
|
1733
|
+
if (!conversation) {
|
|
1734
|
+
throw new Error(`Conversation ${conversationId} not found`);
|
|
1735
|
+
}
|
|
1736
|
+
const now = new Date;
|
|
1737
|
+
const fullMessage = {
|
|
1738
|
+
...message,
|
|
1739
|
+
id: generateId("msg"),
|
|
1740
|
+
conversationId,
|
|
1741
|
+
createdAt: now,
|
|
1742
|
+
updatedAt: now
|
|
1743
|
+
};
|
|
1744
|
+
conversation.messages.push(fullMessage);
|
|
1745
|
+
conversation.updatedAt = now;
|
|
1746
|
+
return fullMessage;
|
|
1747
|
+
}
|
|
1748
|
+
async updateMessage(conversationId, messageId, updates) {
|
|
1749
|
+
const conversation = this.conversations.get(conversationId);
|
|
1750
|
+
if (!conversation)
|
|
1751
|
+
return null;
|
|
1752
|
+
const messageIndex = conversation.messages.findIndex((m) => m.id === messageId);
|
|
1753
|
+
if (messageIndex === -1)
|
|
1754
|
+
return null;
|
|
1755
|
+
const message = conversation.messages[messageIndex];
|
|
1756
|
+
if (!message)
|
|
1757
|
+
return null;
|
|
1758
|
+
const updated = {
|
|
1759
|
+
...message,
|
|
1760
|
+
...updates,
|
|
1761
|
+
updatedAt: new Date
|
|
1762
|
+
};
|
|
1763
|
+
conversation.messages[messageIndex] = updated;
|
|
1764
|
+
conversation.updatedAt = new Date;
|
|
1765
|
+
return updated;
|
|
1766
|
+
}
|
|
1767
|
+
async delete(conversationId) {
|
|
1768
|
+
return this.conversations.delete(conversationId);
|
|
1769
|
+
}
|
|
1770
|
+
async list(options) {
|
|
1771
|
+
let results = Array.from(this.conversations.values());
|
|
1772
|
+
if (options?.status) {
|
|
1773
|
+
results = results.filter((c) => c.status === options.status);
|
|
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
|
+
}
|
|
1782
|
+
results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
1783
|
+
const offset = options?.offset ?? 0;
|
|
1784
|
+
const limit = options?.limit ?? 100;
|
|
1785
|
+
return results.slice(offset, offset + limit);
|
|
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
|
+
}
|
|
1834
|
+
async search(query, limit = 20) {
|
|
1835
|
+
const lowerQuery = query.toLowerCase();
|
|
1836
|
+
const results = [];
|
|
1837
|
+
for (const conversation of this.conversations.values()) {
|
|
1838
|
+
if (conversation.title?.toLowerCase().includes(lowerQuery)) {
|
|
1839
|
+
results.push(conversation);
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
const hasMatch = conversation.messages.some((m) => m.content.toLowerCase().includes(lowerQuery));
|
|
1843
|
+
if (hasMatch) {
|
|
1844
|
+
results.push(conversation);
|
|
1845
|
+
}
|
|
1846
|
+
if (results.length >= limit)
|
|
1847
|
+
break;
|
|
1848
|
+
}
|
|
1849
|
+
return results;
|
|
1850
|
+
}
|
|
1851
|
+
clear() {
|
|
1852
|
+
this.conversations.clear();
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
function createInMemoryConversationStore() {
|
|
1856
|
+
return new InMemoryConversationStore;
|
|
1857
|
+
}
|
|
1858
|
+
|
|
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';
|
|
2022
|
+
|
|
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
|
+
}
|
|
2062
|
+
|
|
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(`
|
|
2070
|
+
|
|
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;
|
|
2334
|
+
sendSources;
|
|
2335
|
+
modelSelector;
|
|
2336
|
+
constructor(config) {
|
|
2337
|
+
this.provider = config.provider;
|
|
2338
|
+
this.context = config.context;
|
|
2339
|
+
this.store = config.store ?? new InMemoryConversationStore;
|
|
2340
|
+
this.systemPrompt = this.buildSystemPrompt(config);
|
|
2341
|
+
this.maxHistoryMessages = config.maxHistoryMessages ?? 20;
|
|
2342
|
+
this.onUsage = config.onUsage;
|
|
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");
|
|
2347
|
+
this.sendSources = config.sendSources ?? false;
|
|
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
|
+
}
|
|
2419
|
+
async send(options) {
|
|
2420
|
+
let conversation;
|
|
2421
|
+
if (options.conversationId) {
|
|
2422
|
+
const existing = await this.store.get(options.conversationId);
|
|
2423
|
+
if (!existing) {
|
|
2424
|
+
throw new Error(`Conversation ${options.conversationId} not found`);
|
|
2425
|
+
}
|
|
2426
|
+
conversation = existing;
|
|
2427
|
+
} else {
|
|
2428
|
+
conversation = await this.store.create({
|
|
2429
|
+
status: "active",
|
|
2430
|
+
provider: this.provider.name,
|
|
2431
|
+
model: this.provider.model,
|
|
2432
|
+
messages: [],
|
|
2433
|
+
workspacePath: this.context?.workspacePath
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
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;
|
|
2445
|
+
const messages = this.buildMessages(conversation, options);
|
|
2446
|
+
const { model, providerName } = await this.resolveModel();
|
|
2447
|
+
const providerOptions = getProviderOptions(this.thinkingLevel, providerName);
|
|
2448
|
+
try {
|
|
2449
|
+
const result = await generateText({
|
|
2450
|
+
model,
|
|
2451
|
+
messages,
|
|
2452
|
+
system: this.systemPrompt,
|
|
2453
|
+
tools: this.tools,
|
|
2454
|
+
providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined
|
|
2455
|
+
});
|
|
2456
|
+
const assistantMessage = await this.store.appendMessage(conversation.id, {
|
|
2457
|
+
role: "assistant",
|
|
2458
|
+
content: result.text,
|
|
2459
|
+
status: "completed"
|
|
2460
|
+
});
|
|
2461
|
+
const updatedConversation = await this.store.get(conversation.id);
|
|
2462
|
+
if (!updatedConversation) {
|
|
2463
|
+
throw new Error("Conversation lost after update");
|
|
2464
|
+
}
|
|
2465
|
+
return {
|
|
2466
|
+
message: assistantMessage,
|
|
2467
|
+
conversation: updatedConversation
|
|
2468
|
+
};
|
|
2469
|
+
} catch (error) {
|
|
2470
|
+
await this.store.appendMessage(conversation.id, {
|
|
2471
|
+
role: "assistant",
|
|
2472
|
+
content: "",
|
|
2473
|
+
status: "error",
|
|
2474
|
+
error: {
|
|
2475
|
+
code: "generation_failed",
|
|
2476
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2477
|
+
}
|
|
2478
|
+
});
|
|
2479
|
+
throw error;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
async stream(options) {
|
|
2483
|
+
let conversation;
|
|
2484
|
+
if (options.conversationId) {
|
|
2485
|
+
const existing = await this.store.get(options.conversationId);
|
|
2486
|
+
if (!existing) {
|
|
2487
|
+
throw new Error(`Conversation ${options.conversationId} not found`);
|
|
2488
|
+
}
|
|
2489
|
+
conversation = existing;
|
|
2490
|
+
} else {
|
|
2491
|
+
conversation = await this.store.create({
|
|
2492
|
+
status: "active",
|
|
2493
|
+
provider: this.provider.name,
|
|
2494
|
+
model: this.provider.model,
|
|
2495
|
+
messages: [],
|
|
2496
|
+
workspacePath: this.context?.workspacePath
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
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;
|
|
2508
|
+
const assistantMessage = await this.store.appendMessage(conversation.id, {
|
|
2509
|
+
role: "assistant",
|
|
2510
|
+
content: "",
|
|
2511
|
+
status: "streaming"
|
|
2512
|
+
});
|
|
2513
|
+
const messages = this.buildMessages(conversation, options);
|
|
2514
|
+
const { model, providerName } = await this.resolveModel();
|
|
2515
|
+
const systemPrompt = this.systemPrompt;
|
|
2516
|
+
const tools = this.tools;
|
|
2517
|
+
const store = this.store;
|
|
2518
|
+
const onUsage = this.onUsage;
|
|
2519
|
+
const streamProviderOptions = getProviderOptions(this.thinkingLevel, providerName);
|
|
2520
|
+
async function* streamGenerator() {
|
|
2521
|
+
let fullContent = "";
|
|
2522
|
+
let fullReasoning = "";
|
|
2523
|
+
const toolCallsMap = new Map;
|
|
2524
|
+
const sources = [];
|
|
2525
|
+
try {
|
|
2526
|
+
const result = streamText({
|
|
2527
|
+
model,
|
|
2528
|
+
messages,
|
|
2529
|
+
system: systemPrompt,
|
|
2530
|
+
tools,
|
|
2531
|
+
providerOptions: Object.keys(streamProviderOptions).length > 0 ? streamProviderOptions : undefined
|
|
2532
|
+
});
|
|
2533
|
+
for await (const part of result.fullStream) {
|
|
2534
|
+
if (part.type === "text-delta") {
|
|
2535
|
+
const text = part.text ?? "";
|
|
2536
|
+
if (text) {
|
|
2537
|
+
fullContent += text;
|
|
2538
|
+
yield { type: "text", content: text };
|
|
2539
|
+
}
|
|
2540
|
+
} else if (part.type === "reasoning-delta") {
|
|
2541
|
+
const text = part.text ?? "";
|
|
2542
|
+
if (text) {
|
|
2543
|
+
fullReasoning += text;
|
|
2544
|
+
yield { type: "reasoning", content: text };
|
|
2545
|
+
}
|
|
2546
|
+
} else if (part.type === "source") {
|
|
2547
|
+
const src = part;
|
|
2548
|
+
const source = {
|
|
2549
|
+
id: src.id,
|
|
2550
|
+
title: src.title ?? "",
|
|
2551
|
+
url: src.url,
|
|
2552
|
+
type: "web"
|
|
2553
|
+
};
|
|
2554
|
+
sources.push(source);
|
|
2555
|
+
yield { type: "source", source };
|
|
2556
|
+
} else if (part.type === "tool-call") {
|
|
2557
|
+
const toolCall = {
|
|
2558
|
+
id: part.toolCallId,
|
|
2559
|
+
name: part.toolName,
|
|
2560
|
+
args: part.input ?? {},
|
|
2561
|
+
status: "running"
|
|
2562
|
+
};
|
|
2563
|
+
toolCallsMap.set(part.toolCallId, toolCall);
|
|
2564
|
+
yield { type: "tool_call", toolCall };
|
|
2565
|
+
} else if (part.type === "tool-result") {
|
|
2566
|
+
const tc = toolCallsMap.get(part.toolCallId);
|
|
2567
|
+
if (tc) {
|
|
2568
|
+
tc.result = part.output;
|
|
2569
|
+
tc.status = "completed";
|
|
2570
|
+
}
|
|
2571
|
+
yield {
|
|
2572
|
+
type: "tool_result",
|
|
2573
|
+
toolResult: {
|
|
2574
|
+
toolCallId: part.toolCallId,
|
|
2575
|
+
toolName: part.toolName,
|
|
2576
|
+
result: part.output
|
|
2577
|
+
}
|
|
2578
|
+
};
|
|
2579
|
+
} else if (part.type === "tool-error") {
|
|
2580
|
+
const tc = toolCallsMap.get(part.toolCallId);
|
|
2581
|
+
if (tc) {
|
|
2582
|
+
tc.status = "error";
|
|
2583
|
+
tc.error = part.error ?? "Tool execution failed";
|
|
2584
|
+
}
|
|
2585
|
+
} else if (part.type === "finish") {
|
|
2586
|
+
const usage = part.usage;
|
|
2587
|
+
const inputTokens = usage?.inputTokens ?? 0;
|
|
2588
|
+
const outputTokens = usage?.completionTokens ?? 0;
|
|
2589
|
+
await store.updateMessage(conversation.id, assistantMessage.id, {
|
|
2590
|
+
content: fullContent,
|
|
2591
|
+
status: "completed",
|
|
2592
|
+
reasoning: fullReasoning || undefined,
|
|
2593
|
+
sources: sources.length > 0 ? sources : undefined,
|
|
2594
|
+
toolCalls: toolCallsMap.size > 0 ? Array.from(toolCallsMap.values()) : undefined,
|
|
2595
|
+
usage: usage ? { inputTokens, outputTokens } : undefined
|
|
2596
|
+
});
|
|
2597
|
+
onUsage?.({ inputTokens, outputTokens });
|
|
2598
|
+
yield {
|
|
2599
|
+
type: "done",
|
|
2600
|
+
usage: usage ? { inputTokens, outputTokens } : undefined
|
|
2601
|
+
};
|
|
2602
|
+
return;
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
await store.updateMessage(conversation.id, assistantMessage.id, {
|
|
2606
|
+
content: fullContent,
|
|
2607
|
+
status: "completed",
|
|
2608
|
+
reasoning: fullReasoning || undefined,
|
|
2609
|
+
sources: sources.length > 0 ? sources : undefined,
|
|
2610
|
+
toolCalls: toolCallsMap.size > 0 ? Array.from(toolCallsMap.values()) : undefined
|
|
2611
|
+
});
|
|
2612
|
+
yield { type: "done" };
|
|
2613
|
+
} catch (error) {
|
|
2614
|
+
await store.updateMessage(conversation.id, assistantMessage.id, {
|
|
2615
|
+
content: fullContent,
|
|
2616
|
+
status: "error",
|
|
2617
|
+
error: {
|
|
2618
|
+
code: "stream_failed",
|
|
2619
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2620
|
+
}
|
|
2621
|
+
});
|
|
2622
|
+
yield {
|
|
2623
|
+
type: "error",
|
|
2624
|
+
error: {
|
|
2625
|
+
code: "stream_failed",
|
|
2626
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2627
|
+
}
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
return {
|
|
2632
|
+
conversationId: conversation.id,
|
|
2633
|
+
messageId: assistantMessage.id,
|
|
2634
|
+
stream: streamGenerator()
|
|
2635
|
+
};
|
|
2636
|
+
}
|
|
2637
|
+
async getConversation(conversationId) {
|
|
2638
|
+
return this.store.get(conversationId);
|
|
2639
|
+
}
|
|
2640
|
+
async listConversations(options) {
|
|
2641
|
+
return this.store.list({
|
|
2642
|
+
status: "active",
|
|
2643
|
+
...options
|
|
2644
|
+
});
|
|
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
|
+
}
|
|
2658
|
+
async deleteConversation(conversationId) {
|
|
2659
|
+
return this.store.delete(conversationId);
|
|
2660
|
+
}
|
|
2661
|
+
buildMessages(conversation, _options) {
|
|
2662
|
+
const historyStart = Math.max(0, conversation.messages.length - this.maxHistoryMessages);
|
|
2663
|
+
const messages = [];
|
|
2664
|
+
for (let i = historyStart;i < conversation.messages.length; i++) {
|
|
2665
|
+
const msg = conversation.messages[i];
|
|
2666
|
+
if (!msg)
|
|
2667
|
+
continue;
|
|
2668
|
+
if (msg.role === "user") {
|
|
2669
|
+
let content = msg.content;
|
|
2670
|
+
if (msg.attachments?.length) {
|
|
2671
|
+
const attachmentInfo = msg.attachments.map((a) => {
|
|
2672
|
+
if (a.type === "file" || a.type === "code") {
|
|
2673
|
+
return `
|
|
2674
|
+
|
|
2675
|
+
### ${a.name}
|
|
2676
|
+
\`\`\`
|
|
2677
|
+
${a.content ?? ""}
|
|
2678
|
+
\`\`\``;
|
|
2679
|
+
}
|
|
2680
|
+
return `
|
|
2681
|
+
|
|
2682
|
+
[Attachment: ${a.name}]`;
|
|
2683
|
+
}).join("");
|
|
2684
|
+
content += attachmentInfo;
|
|
2685
|
+
}
|
|
2686
|
+
messages.push({ role: "user", content });
|
|
2687
|
+
} else if (msg.role === "assistant") {
|
|
2688
|
+
if (msg.toolCalls?.length) {
|
|
2689
|
+
messages.push({
|
|
2690
|
+
role: "assistant",
|
|
2691
|
+
content: msg.content || "",
|
|
2692
|
+
toolCalls: msg.toolCalls.map((tc) => ({
|
|
2693
|
+
type: "tool-call",
|
|
2694
|
+
toolCallId: tc.id,
|
|
2695
|
+
toolName: tc.name,
|
|
2696
|
+
args: tc.args
|
|
2697
|
+
}))
|
|
2698
|
+
});
|
|
2699
|
+
messages.push({
|
|
2700
|
+
role: "tool",
|
|
2701
|
+
content: msg.toolCalls.map((tc) => ({
|
|
2702
|
+
type: "tool-result",
|
|
2703
|
+
toolCallId: tc.id,
|
|
2704
|
+
toolName: tc.name,
|
|
2705
|
+
output: tc.result
|
|
2706
|
+
}))
|
|
2707
|
+
});
|
|
2708
|
+
} else {
|
|
2709
|
+
messages.push({ role: "assistant", content: msg.content });
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
return messages;
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
function createChatService(config) {
|
|
2717
|
+
return new ChatService(config);
|
|
2718
|
+
}
|
|
2719
|
+
|
|
2720
|
+
// src/presentation/hooks/useChat.tsx
|
|
2721
|
+
import {
|
|
2722
|
+
createProvider
|
|
2723
|
+
} from "@contractspec/lib.ai-providers";
|
|
2724
|
+
"use client";
|
|
2725
|
+
function toolsToToolSet(defs) {
|
|
2726
|
+
const result = {};
|
|
2727
|
+
for (const def of defs) {
|
|
2728
|
+
result[def.name] = tool4({
|
|
2729
|
+
description: def.description ?? def.name,
|
|
2730
|
+
inputSchema: z4.object({}).passthrough(),
|
|
2731
|
+
execute: async () => ({})
|
|
2732
|
+
});
|
|
2733
|
+
}
|
|
2734
|
+
return result;
|
|
2735
|
+
}
|
|
2736
|
+
function useChat(options = {}) {
|
|
2737
|
+
const {
|
|
2738
|
+
provider = "openai",
|
|
2739
|
+
mode = "byok",
|
|
2740
|
+
model,
|
|
2741
|
+
apiKey,
|
|
2742
|
+
proxyUrl,
|
|
2743
|
+
conversationId: initialConversationId,
|
|
2744
|
+
store,
|
|
2745
|
+
systemPrompt,
|
|
2746
|
+
streaming = true,
|
|
2747
|
+
onSend,
|
|
2748
|
+
onResponse,
|
|
2749
|
+
onError,
|
|
2750
|
+
onUsage,
|
|
2751
|
+
tools: toolsDefs,
|
|
2752
|
+
thinkingLevel,
|
|
2753
|
+
workflowToolsConfig,
|
|
2754
|
+
modelSelector,
|
|
2755
|
+
contractsContext,
|
|
2756
|
+
surfacePlanConfig,
|
|
2757
|
+
mcpServers,
|
|
2758
|
+
agentMode
|
|
2759
|
+
} = options;
|
|
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(() => {
|
|
2802
|
+
const chatProvider = createProvider({
|
|
2803
|
+
provider,
|
|
2804
|
+
model,
|
|
2805
|
+
apiKey,
|
|
2806
|
+
proxyUrl
|
|
2807
|
+
});
|
|
2808
|
+
chatServiceRef.current = new ChatService({
|
|
2809
|
+
provider: chatProvider,
|
|
2810
|
+
store,
|
|
2811
|
+
systemPrompt,
|
|
2812
|
+
onUsage,
|
|
2813
|
+
tools: toolsDefs?.length ? toolsToToolSet(toolsDefs) : undefined,
|
|
2814
|
+
thinkingLevel,
|
|
2815
|
+
workflowToolsConfig,
|
|
2816
|
+
modelSelector,
|
|
2817
|
+
contractsContext,
|
|
2818
|
+
surfacePlanConfig,
|
|
2819
|
+
mcpTools
|
|
2820
|
+
});
|
|
2821
|
+
}, [
|
|
2822
|
+
provider,
|
|
2823
|
+
mode,
|
|
2824
|
+
model,
|
|
2825
|
+
apiKey,
|
|
2826
|
+
proxyUrl,
|
|
2827
|
+
store,
|
|
2828
|
+
systemPrompt,
|
|
2829
|
+
onUsage,
|
|
2830
|
+
toolsDefs,
|
|
2831
|
+
thinkingLevel,
|
|
2832
|
+
workflowToolsConfig,
|
|
2833
|
+
modelSelector,
|
|
2834
|
+
contractsContext,
|
|
2835
|
+
surfacePlanConfig,
|
|
2836
|
+
mcpTools
|
|
2837
|
+
]);
|
|
2838
|
+
React11.useEffect(() => {
|
|
2839
|
+
if (!conversationId || !chatServiceRef.current)
|
|
2840
|
+
return;
|
|
2841
|
+
const loadConversation = async () => {
|
|
2842
|
+
if (!chatServiceRef.current)
|
|
2843
|
+
return;
|
|
2844
|
+
const conv = await chatServiceRef.current.getConversation(conversationId);
|
|
2845
|
+
if (conv) {
|
|
2846
|
+
setConversation(conv);
|
|
2847
|
+
setMessages(conv.messages);
|
|
2848
|
+
}
|
|
2849
|
+
};
|
|
2850
|
+
loadConversation().catch(console.error);
|
|
2851
|
+
}, [conversationId]);
|
|
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
|
+
}
|
|
2936
|
+
if (!chatServiceRef.current) {
|
|
2937
|
+
throw new Error("Chat service not initialized");
|
|
2938
|
+
}
|
|
2939
|
+
setIsLoading(true);
|
|
2940
|
+
setError(null);
|
|
2941
|
+
abortControllerRef.current = new AbortController;
|
|
2942
|
+
try {
|
|
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
|
+
}
|
|
2957
|
+
if (streaming) {
|
|
2958
|
+
const result = await chatServiceRef.current.stream({
|
|
2959
|
+
conversationId: conversationId ?? undefined,
|
|
2960
|
+
content,
|
|
2961
|
+
attachments,
|
|
2962
|
+
skipUserAppend: opts?.skipUserAppend
|
|
2963
|
+
});
|
|
2964
|
+
if (!conversationId && !opts?.skipUserAppend) {
|
|
2965
|
+
setConversationId(result.conversationId);
|
|
2966
|
+
}
|
|
2967
|
+
const assistantMessage = {
|
|
2968
|
+
id: result.messageId,
|
|
2969
|
+
conversationId: result.conversationId,
|
|
2970
|
+
role: "assistant",
|
|
2971
|
+
content: "",
|
|
2972
|
+
status: "streaming",
|
|
2973
|
+
createdAt: new Date,
|
|
2974
|
+
updatedAt: new Date
|
|
2975
|
+
};
|
|
2976
|
+
setMessages((prev) => [...prev, assistantMessage]);
|
|
2977
|
+
let fullContent = "";
|
|
2978
|
+
let fullReasoning = "";
|
|
2979
|
+
const toolCallsMap = new Map;
|
|
2980
|
+
const sources = [];
|
|
2981
|
+
for await (const chunk of result.stream) {
|
|
2982
|
+
if (chunk.type === "text" && chunk.content) {
|
|
2983
|
+
fullContent += chunk.content;
|
|
2984
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? {
|
|
2985
|
+
...m,
|
|
2986
|
+
content: fullContent,
|
|
2987
|
+
reasoning: fullReasoning || undefined,
|
|
2988
|
+
sources: sources.length ? sources : undefined,
|
|
2989
|
+
toolCalls: toolCallsMap.size ? Array.from(toolCallsMap.values()) : undefined
|
|
2990
|
+
} : m));
|
|
2991
|
+
} else if (chunk.type === "reasoning" && chunk.content) {
|
|
2992
|
+
fullReasoning += chunk.content;
|
|
2993
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? { ...m, reasoning: fullReasoning } : m));
|
|
2994
|
+
} else if (chunk.type === "source" && chunk.source) {
|
|
2995
|
+
sources.push(chunk.source);
|
|
2996
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? { ...m, sources: [...sources] } : m));
|
|
2997
|
+
} else if (chunk.type === "tool_call" && chunk.toolCall) {
|
|
2998
|
+
const tc = chunk.toolCall;
|
|
2999
|
+
const chatTc = {
|
|
3000
|
+
id: tc.id,
|
|
3001
|
+
name: tc.name,
|
|
3002
|
+
args: tc.args,
|
|
3003
|
+
status: "running"
|
|
3004
|
+
};
|
|
3005
|
+
toolCallsMap.set(tc.id, chatTc);
|
|
3006
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? { ...m, toolCalls: Array.from(toolCallsMap.values()) } : m));
|
|
3007
|
+
} else if (chunk.type === "tool_result" && chunk.toolResult) {
|
|
3008
|
+
const tr = chunk.toolResult;
|
|
3009
|
+
const tc = toolCallsMap.get(tr.toolCallId);
|
|
3010
|
+
if (tc) {
|
|
3011
|
+
tc.result = tr.result;
|
|
3012
|
+
tc.status = "completed";
|
|
3013
|
+
}
|
|
3014
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? { ...m, toolCalls: Array.from(toolCallsMap.values()) } : m));
|
|
3015
|
+
} else if (chunk.type === "done") {
|
|
3016
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? {
|
|
3017
|
+
...m,
|
|
3018
|
+
content: fullContent,
|
|
3019
|
+
reasoning: fullReasoning || undefined,
|
|
3020
|
+
sources: sources.length ? sources : undefined,
|
|
3021
|
+
toolCalls: toolCallsMap.size ? Array.from(toolCallsMap.values()) : undefined,
|
|
3022
|
+
status: "completed",
|
|
3023
|
+
usage: chunk.usage,
|
|
3024
|
+
updatedAt: new Date
|
|
3025
|
+
} : m));
|
|
3026
|
+
onResponse?.(messages.find((m) => m.id === result.messageId) ?? assistantMessage);
|
|
3027
|
+
} else if (chunk.type === "error") {
|
|
3028
|
+
setMessages((prev) => prev.map((m) => m.id === result.messageId ? {
|
|
3029
|
+
...m,
|
|
3030
|
+
status: "error",
|
|
3031
|
+
error: chunk.error,
|
|
3032
|
+
updatedAt: new Date
|
|
3033
|
+
} : m));
|
|
3034
|
+
if (chunk.error) {
|
|
3035
|
+
const err = new Error(chunk.error.message);
|
|
3036
|
+
setError(err);
|
|
3037
|
+
onError?.(err);
|
|
3038
|
+
}
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
} else {
|
|
3042
|
+
const result = await chatServiceRef.current.send({
|
|
3043
|
+
conversationId: conversationId ?? undefined,
|
|
3044
|
+
content,
|
|
3045
|
+
attachments,
|
|
3046
|
+
skipUserAppend: opts?.skipUserAppend
|
|
3047
|
+
});
|
|
3048
|
+
setConversation(result.conversation);
|
|
3049
|
+
setMessages(result.conversation.messages);
|
|
3050
|
+
if (!conversationId) {
|
|
3051
|
+
setConversationId(result.conversation.id);
|
|
3052
|
+
}
|
|
3053
|
+
onResponse?.(result.message);
|
|
3054
|
+
}
|
|
3055
|
+
} catch (err) {
|
|
3056
|
+
const error2 = err instanceof Error ? err : new Error(String(err));
|
|
3057
|
+
setError(error2);
|
|
3058
|
+
onError?.(error2);
|
|
3059
|
+
} finally {
|
|
3060
|
+
setIsLoading(false);
|
|
3061
|
+
abortControllerRef.current = null;
|
|
3062
|
+
}
|
|
3063
|
+
}, [conversationId, streaming, onSend, onResponse, onError, onUsage, messages, agentMode, store]);
|
|
3064
|
+
const clearConversation = React11.useCallback(() => {
|
|
3065
|
+
setMessages([]);
|
|
3066
|
+
setConversation(null);
|
|
3067
|
+
setConversationId(null);
|
|
3068
|
+
setError(null);
|
|
3069
|
+
}, []);
|
|
3070
|
+
const regenerate = React11.useCallback(async () => {
|
|
3071
|
+
const lastUserMessageIndex = messages.findLastIndex((m) => m.role === "user");
|
|
3072
|
+
if (lastUserMessageIndex === -1)
|
|
3073
|
+
return;
|
|
3074
|
+
const lastUserMessage = messages[lastUserMessageIndex];
|
|
3075
|
+
if (!lastUserMessage)
|
|
3076
|
+
return;
|
|
3077
|
+
setMessages((prev) => prev.slice(0, lastUserMessageIndex + 1));
|
|
3078
|
+
await sendMessage(lastUserMessage.content, lastUserMessage.attachments);
|
|
3079
|
+
}, [messages, sendMessage]);
|
|
3080
|
+
const stop = React11.useCallback(() => {
|
|
3081
|
+
abortControllerRef.current?.abort();
|
|
3082
|
+
setIsLoading(false);
|
|
3083
|
+
}, []);
|
|
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) => {
|
|
3123
|
+
throw new Error(`addToolApprovalResponse: Tool approval requires server route with toUIMessageStreamResponse. ` + `Use createChatRoute and @ai-sdk/react useChat for tools with requireApproval.`);
|
|
3124
|
+
}, []);
|
|
3125
|
+
const hasApprovalTools = toolsDefs?.some((t) => t.requireApproval) ?? false;
|
|
3126
|
+
return {
|
|
3127
|
+
messages,
|
|
3128
|
+
conversation,
|
|
3129
|
+
isLoading,
|
|
3130
|
+
error,
|
|
3131
|
+
sendMessage,
|
|
3132
|
+
clearConversation,
|
|
3133
|
+
setConversationId,
|
|
3134
|
+
regenerate,
|
|
3135
|
+
stop,
|
|
3136
|
+
createNewConversation,
|
|
3137
|
+
editMessage,
|
|
3138
|
+
forkConversation,
|
|
3139
|
+
updateConversation: updateConversationFn,
|
|
3140
|
+
...hasApprovalTools && { addToolApprovalResponse }
|
|
3141
|
+
};
|
|
3142
|
+
}
|
|
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);
|
|
3186
|
+
}
|
|
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";
|
|
683
3460
|
import { Bot as Bot2, Cloud, Cpu, Sparkles } from "lucide-react";
|
|
684
3461
|
import {
|
|
685
3462
|
getModelsForProvider
|
|
686
3463
|
} from "@contractspec/lib.ai-providers";
|
|
687
|
-
import {
|
|
3464
|
+
import { jsx as jsx11, jsxs as jsxs11 } from "react/jsx-runtime";
|
|
688
3465
|
"use client";
|
|
689
3466
|
var PROVIDER_ICONS = {
|
|
690
|
-
ollama: /* @__PURE__ */
|
|
3467
|
+
ollama: /* @__PURE__ */ jsx11(Cpu, {
|
|
691
3468
|
className: "h-4 w-4"
|
|
692
|
-
}
|
|
693
|
-
openai: /* @__PURE__ */
|
|
3469
|
+
}),
|
|
3470
|
+
openai: /* @__PURE__ */ jsx11(Bot2, {
|
|
694
3471
|
className: "h-4 w-4"
|
|
695
|
-
}
|
|
696
|
-
anthropic: /* @__PURE__ */
|
|
3472
|
+
}),
|
|
3473
|
+
anthropic: /* @__PURE__ */ jsx11(Sparkles, {
|
|
697
3474
|
className: "h-4 w-4"
|
|
698
|
-
}
|
|
699
|
-
mistral: /* @__PURE__ */
|
|
3475
|
+
}),
|
|
3476
|
+
mistral: /* @__PURE__ */ jsx11(Cloud, {
|
|
700
3477
|
className: "h-4 w-4"
|
|
701
|
-
}
|
|
702
|
-
gemini: /* @__PURE__ */
|
|
3478
|
+
}),
|
|
3479
|
+
gemini: /* @__PURE__ */ jsx11(Sparkles, {
|
|
703
3480
|
className: "h-4 w-4"
|
|
704
|
-
}
|
|
3481
|
+
})
|
|
705
3482
|
};
|
|
706
3483
|
var PROVIDER_NAMES = {
|
|
707
3484
|
ollama: "Ollama (Local)",
|
|
@@ -731,7 +3508,7 @@ function ModelPicker({
|
|
|
731
3508
|
];
|
|
732
3509
|
const models = getModelsForProvider(value.provider);
|
|
733
3510
|
const selectedModel = models.find((m) => m.id === value.model);
|
|
734
|
-
const handleProviderChange =
|
|
3511
|
+
const handleProviderChange = React13.useCallback((providerName) => {
|
|
735
3512
|
const provider = providerName;
|
|
736
3513
|
const providerInfo = providers.find((p) => p.provider === provider);
|
|
737
3514
|
const providerModels = getModelsForProvider(provider);
|
|
@@ -742,173 +3519,173 @@ function ModelPicker({
|
|
|
742
3519
|
mode: providerInfo?.mode ?? "byok"
|
|
743
3520
|
});
|
|
744
3521
|
}, [onChange, providers]);
|
|
745
|
-
const handleModelChange =
|
|
3522
|
+
const handleModelChange = React13.useCallback((modelId) => {
|
|
746
3523
|
onChange({
|
|
747
3524
|
...value,
|
|
748
3525
|
model: modelId
|
|
749
3526
|
});
|
|
750
3527
|
}, [onChange, value]);
|
|
751
3528
|
if (compact) {
|
|
752
|
-
return /* @__PURE__ */
|
|
753
|
-
className:
|
|
3529
|
+
return /* @__PURE__ */ jsxs11("div", {
|
|
3530
|
+
className: cn7("flex items-center gap-2", className),
|
|
754
3531
|
children: [
|
|
755
|
-
/* @__PURE__ */
|
|
3532
|
+
/* @__PURE__ */ jsxs11(Select2, {
|
|
756
3533
|
value: value.provider,
|
|
757
3534
|
onValueChange: handleProviderChange,
|
|
758
3535
|
children: [
|
|
759
|
-
/* @__PURE__ */
|
|
3536
|
+
/* @__PURE__ */ jsx11(SelectTrigger2, {
|
|
760
3537
|
className: "w-[140px]",
|
|
761
|
-
children: /* @__PURE__ */
|
|
762
|
-
}
|
|
763
|
-
/* @__PURE__ */
|
|
764
|
-
children: providers.map((p) => /* @__PURE__ */
|
|
3538
|
+
children: /* @__PURE__ */ jsx11(SelectValue2, {})
|
|
3539
|
+
}),
|
|
3540
|
+
/* @__PURE__ */ jsx11(SelectContent2, {
|
|
3541
|
+
children: providers.map((p) => /* @__PURE__ */ jsx11(SelectItem2, {
|
|
765
3542
|
value: p.provider,
|
|
766
3543
|
disabled: !p.available,
|
|
767
|
-
children: /* @__PURE__ */
|
|
3544
|
+
children: /* @__PURE__ */ jsxs11("div", {
|
|
768
3545
|
className: "flex items-center gap-2",
|
|
769
3546
|
children: [
|
|
770
3547
|
PROVIDER_ICONS[p.provider],
|
|
771
|
-
/* @__PURE__ */
|
|
3548
|
+
/* @__PURE__ */ jsx11("span", {
|
|
772
3549
|
children: PROVIDER_NAMES[p.provider]
|
|
773
|
-
}
|
|
3550
|
+
})
|
|
774
3551
|
]
|
|
775
|
-
}
|
|
776
|
-
}, p.provider
|
|
777
|
-
}
|
|
3552
|
+
})
|
|
3553
|
+
}, p.provider))
|
|
3554
|
+
})
|
|
778
3555
|
]
|
|
779
|
-
}
|
|
780
|
-
/* @__PURE__ */
|
|
3556
|
+
}),
|
|
3557
|
+
/* @__PURE__ */ jsxs11(Select2, {
|
|
781
3558
|
value: value.model,
|
|
782
3559
|
onValueChange: handleModelChange,
|
|
783
3560
|
children: [
|
|
784
|
-
/* @__PURE__ */
|
|
3561
|
+
/* @__PURE__ */ jsx11(SelectTrigger2, {
|
|
785
3562
|
className: "w-[160px]",
|
|
786
|
-
children: /* @__PURE__ */
|
|
787
|
-
}
|
|
788
|
-
/* @__PURE__ */
|
|
789
|
-
children: models.map((m) => /* @__PURE__ */
|
|
3563
|
+
children: /* @__PURE__ */ jsx11(SelectValue2, {})
|
|
3564
|
+
}),
|
|
3565
|
+
/* @__PURE__ */ jsx11(SelectContent2, {
|
|
3566
|
+
children: models.map((m) => /* @__PURE__ */ jsx11(SelectItem2, {
|
|
790
3567
|
value: m.id,
|
|
791
3568
|
children: m.name
|
|
792
|
-
}, m.id
|
|
793
|
-
}
|
|
3569
|
+
}, m.id))
|
|
3570
|
+
})
|
|
794
3571
|
]
|
|
795
|
-
}
|
|
3572
|
+
})
|
|
796
3573
|
]
|
|
797
|
-
}
|
|
3574
|
+
});
|
|
798
3575
|
}
|
|
799
|
-
return /* @__PURE__ */
|
|
800
|
-
className:
|
|
3576
|
+
return /* @__PURE__ */ jsxs11("div", {
|
|
3577
|
+
className: cn7("flex flex-col gap-3", className),
|
|
801
3578
|
children: [
|
|
802
|
-
/* @__PURE__ */
|
|
3579
|
+
/* @__PURE__ */ jsxs11("div", {
|
|
803
3580
|
className: "flex flex-col gap-1.5",
|
|
804
3581
|
children: [
|
|
805
|
-
/* @__PURE__ */
|
|
3582
|
+
/* @__PURE__ */ jsx11(Label2, {
|
|
806
3583
|
htmlFor: "provider-selection",
|
|
807
3584
|
className: "text-sm font-medium",
|
|
808
3585
|
children: "Provider"
|
|
809
|
-
}
|
|
810
|
-
/* @__PURE__ */
|
|
3586
|
+
}),
|
|
3587
|
+
/* @__PURE__ */ jsx11("div", {
|
|
811
3588
|
className: "flex flex-wrap gap-2",
|
|
812
3589
|
id: "provider-selection",
|
|
813
|
-
children: providers.map((p) => /* @__PURE__ */
|
|
3590
|
+
children: providers.map((p) => /* @__PURE__ */ jsxs11(Button6, {
|
|
814
3591
|
variant: value.provider === p.provider ? "default" : "outline",
|
|
815
3592
|
size: "sm",
|
|
816
3593
|
onPress: () => p.available && handleProviderChange(p.provider),
|
|
817
3594
|
disabled: !p.available,
|
|
818
|
-
className:
|
|
3595
|
+
className: cn7(!p.available && "opacity-50"),
|
|
819
3596
|
children: [
|
|
820
3597
|
PROVIDER_ICONS[p.provider],
|
|
821
|
-
/* @__PURE__ */
|
|
3598
|
+
/* @__PURE__ */ jsx11("span", {
|
|
822
3599
|
children: PROVIDER_NAMES[p.provider]
|
|
823
|
-
}
|
|
824
|
-
/* @__PURE__ */
|
|
3600
|
+
}),
|
|
3601
|
+
/* @__PURE__ */ jsx11(Badge, {
|
|
825
3602
|
variant: MODE_BADGES[p.mode].variant,
|
|
826
3603
|
className: "ml-1",
|
|
827
3604
|
children: MODE_BADGES[p.mode].label
|
|
828
|
-
}
|
|
3605
|
+
})
|
|
829
3606
|
]
|
|
830
|
-
}, p.provider
|
|
831
|
-
}
|
|
3607
|
+
}, p.provider))
|
|
3608
|
+
})
|
|
832
3609
|
]
|
|
833
|
-
}
|
|
834
|
-
/* @__PURE__ */
|
|
3610
|
+
}),
|
|
3611
|
+
/* @__PURE__ */ jsxs11("div", {
|
|
835
3612
|
className: "flex flex-col gap-1.5",
|
|
836
3613
|
children: [
|
|
837
|
-
/* @__PURE__ */
|
|
3614
|
+
/* @__PURE__ */ jsx11(Label2, {
|
|
838
3615
|
htmlFor: "model-picker",
|
|
839
3616
|
className: "text-sm font-medium",
|
|
840
3617
|
children: "Model"
|
|
841
|
-
}
|
|
842
|
-
/* @__PURE__ */
|
|
3618
|
+
}),
|
|
3619
|
+
/* @__PURE__ */ jsxs11(Select2, {
|
|
843
3620
|
name: "model-picker",
|
|
844
3621
|
value: value.model,
|
|
845
3622
|
onValueChange: handleModelChange,
|
|
846
3623
|
children: [
|
|
847
|
-
/* @__PURE__ */
|
|
848
|
-
children: /* @__PURE__ */
|
|
3624
|
+
/* @__PURE__ */ jsx11(SelectTrigger2, {
|
|
3625
|
+
children: /* @__PURE__ */ jsx11(SelectValue2, {
|
|
849
3626
|
placeholder: "Select a model"
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
/* @__PURE__ */
|
|
853
|
-
children: models.map((m) => /* @__PURE__ */
|
|
3627
|
+
})
|
|
3628
|
+
}),
|
|
3629
|
+
/* @__PURE__ */ jsx11(SelectContent2, {
|
|
3630
|
+
children: models.map((m) => /* @__PURE__ */ jsx11(SelectItem2, {
|
|
854
3631
|
value: m.id,
|
|
855
|
-
children: /* @__PURE__ */
|
|
3632
|
+
children: /* @__PURE__ */ jsxs11("div", {
|
|
856
3633
|
className: "flex items-center gap-2",
|
|
857
3634
|
children: [
|
|
858
|
-
/* @__PURE__ */
|
|
3635
|
+
/* @__PURE__ */ jsx11("span", {
|
|
859
3636
|
children: m.name
|
|
860
|
-
}
|
|
861
|
-
/* @__PURE__ */
|
|
3637
|
+
}),
|
|
3638
|
+
/* @__PURE__ */ jsxs11("span", {
|
|
862
3639
|
className: "text-muted-foreground text-xs",
|
|
863
3640
|
children: [
|
|
864
3641
|
Math.round(m.contextWindow / 1000),
|
|
865
3642
|
"K"
|
|
866
3643
|
]
|
|
867
|
-
}
|
|
868
|
-
m.capabilities.vision && /* @__PURE__ */
|
|
3644
|
+
}),
|
|
3645
|
+
m.capabilities.vision && /* @__PURE__ */ jsx11(Badge, {
|
|
869
3646
|
variant: "outline",
|
|
870
3647
|
className: "text-xs",
|
|
871
3648
|
children: "Vision"
|
|
872
|
-
}
|
|
873
|
-
m.capabilities.reasoning && /* @__PURE__ */
|
|
3649
|
+
}),
|
|
3650
|
+
m.capabilities.reasoning && /* @__PURE__ */ jsx11(Badge, {
|
|
874
3651
|
variant: "outline",
|
|
875
3652
|
className: "text-xs",
|
|
876
3653
|
children: "Reasoning"
|
|
877
|
-
}
|
|
3654
|
+
})
|
|
878
3655
|
]
|
|
879
|
-
}
|
|
880
|
-
}, m.id
|
|
881
|
-
}
|
|
3656
|
+
})
|
|
3657
|
+
}, m.id))
|
|
3658
|
+
})
|
|
882
3659
|
]
|
|
883
|
-
}
|
|
3660
|
+
})
|
|
884
3661
|
]
|
|
885
|
-
}
|
|
886
|
-
selectedModel && /* @__PURE__ */
|
|
3662
|
+
}),
|
|
3663
|
+
selectedModel && /* @__PURE__ */ jsxs11("div", {
|
|
887
3664
|
className: "text-muted-foreground flex flex-wrap gap-2 text-xs",
|
|
888
3665
|
children: [
|
|
889
|
-
/* @__PURE__ */
|
|
3666
|
+
/* @__PURE__ */ jsxs11("span", {
|
|
890
3667
|
children: [
|
|
891
3668
|
"Context: ",
|
|
892
3669
|
Math.round(selectedModel.contextWindow / 1000),
|
|
893
3670
|
"K tokens"
|
|
894
3671
|
]
|
|
895
|
-
}
|
|
896
|
-
selectedModel.capabilities.vision && /* @__PURE__ */
|
|
3672
|
+
}),
|
|
3673
|
+
selectedModel.capabilities.vision && /* @__PURE__ */ jsx11("span", {
|
|
897
3674
|
children: "• Vision"
|
|
898
|
-
}
|
|
899
|
-
selectedModel.capabilities.tools && /* @__PURE__ */
|
|
3675
|
+
}),
|
|
3676
|
+
selectedModel.capabilities.tools && /* @__PURE__ */ jsx11("span", {
|
|
900
3677
|
children: "• Tools"
|
|
901
|
-
}
|
|
902
|
-
selectedModel.capabilities.reasoning && /* @__PURE__ */
|
|
3678
|
+
}),
|
|
3679
|
+
selectedModel.capabilities.reasoning && /* @__PURE__ */ jsx11("span", {
|
|
903
3680
|
children: "• Reasoning"
|
|
904
|
-
}
|
|
3681
|
+
})
|
|
905
3682
|
]
|
|
906
|
-
}
|
|
3683
|
+
})
|
|
907
3684
|
]
|
|
908
|
-
}
|
|
3685
|
+
});
|
|
909
3686
|
}
|
|
910
3687
|
// src/presentation/components/ContextIndicator.tsx
|
|
911
|
-
import { cn as
|
|
3688
|
+
import { cn as cn8 } from "@contractspec/lib.ui-kit-web/ui/utils";
|
|
912
3689
|
import { Badge as Badge2 } from "@contractspec/lib.ui-kit-web/ui/badge";
|
|
913
3690
|
import {
|
|
914
3691
|
Tooltip,
|
|
@@ -917,7 +3694,7 @@ import {
|
|
|
917
3694
|
TooltipTrigger
|
|
918
3695
|
} from "@contractspec/lib.ui-kit-web/ui/tooltip";
|
|
919
3696
|
import { FolderOpen, FileCode, Zap, Info } from "lucide-react";
|
|
920
|
-
import {
|
|
3697
|
+
import { jsx as jsx12, jsxs as jsxs12, Fragment as Fragment6 } from "react/jsx-runtime";
|
|
921
3698
|
"use client";
|
|
922
3699
|
function ContextIndicator({
|
|
923
3700
|
summary,
|
|
@@ -926,155 +3703,163 @@ function ContextIndicator({
|
|
|
926
3703
|
showDetails = true
|
|
927
3704
|
}) {
|
|
928
3705
|
if (!summary && !active) {
|
|
929
|
-
return /* @__PURE__ */
|
|
930
|
-
className:
|
|
3706
|
+
return /* @__PURE__ */ jsxs12("div", {
|
|
3707
|
+
className: cn8("flex items-center gap-1.5 text-sm", "text-muted-foreground", className),
|
|
931
3708
|
children: [
|
|
932
|
-
/* @__PURE__ */
|
|
3709
|
+
/* @__PURE__ */ jsx12(Info, {
|
|
933
3710
|
className: "h-4 w-4"
|
|
934
|
-
}
|
|
935
|
-
/* @__PURE__ */
|
|
3711
|
+
}),
|
|
3712
|
+
/* @__PURE__ */ jsx12("span", {
|
|
936
3713
|
children: "No workspace context"
|
|
937
|
-
}
|
|
3714
|
+
})
|
|
938
3715
|
]
|
|
939
|
-
}
|
|
3716
|
+
});
|
|
940
3717
|
}
|
|
941
|
-
const content = /* @__PURE__ */
|
|
942
|
-
className:
|
|
3718
|
+
const content = /* @__PURE__ */ jsxs12("div", {
|
|
3719
|
+
className: cn8("flex items-center gap-2", active ? "text-foreground" : "text-muted-foreground", className),
|
|
943
3720
|
children: [
|
|
944
|
-
/* @__PURE__ */
|
|
3721
|
+
/* @__PURE__ */ jsxs12(Badge2, {
|
|
945
3722
|
variant: active ? "default" : "secondary",
|
|
946
3723
|
className: "flex items-center gap-1",
|
|
947
3724
|
children: [
|
|
948
|
-
/* @__PURE__ */
|
|
3725
|
+
/* @__PURE__ */ jsx12(Zap, {
|
|
949
3726
|
className: "h-3 w-3"
|
|
950
|
-
}
|
|
3727
|
+
}),
|
|
951
3728
|
"Context"
|
|
952
3729
|
]
|
|
953
|
-
}
|
|
954
|
-
summary && showDetails && /* @__PURE__ */
|
|
3730
|
+
}),
|
|
3731
|
+
summary && showDetails && /* @__PURE__ */ jsxs12(Fragment6, {
|
|
955
3732
|
children: [
|
|
956
|
-
/* @__PURE__ */
|
|
3733
|
+
/* @__PURE__ */ jsxs12("div", {
|
|
957
3734
|
className: "flex items-center gap-1 text-xs",
|
|
958
3735
|
children: [
|
|
959
|
-
/* @__PURE__ */
|
|
3736
|
+
/* @__PURE__ */ jsx12(FolderOpen, {
|
|
960
3737
|
className: "h-3.5 w-3.5"
|
|
961
|
-
}
|
|
962
|
-
/* @__PURE__ */
|
|
3738
|
+
}),
|
|
3739
|
+
/* @__PURE__ */ jsx12("span", {
|
|
963
3740
|
children: summary.name
|
|
964
|
-
}
|
|
3741
|
+
})
|
|
965
3742
|
]
|
|
966
|
-
}
|
|
967
|
-
/* @__PURE__ */
|
|
3743
|
+
}),
|
|
3744
|
+
/* @__PURE__ */ jsxs12("div", {
|
|
968
3745
|
className: "flex items-center gap-1 text-xs",
|
|
969
3746
|
children: [
|
|
970
|
-
/* @__PURE__ */
|
|
3747
|
+
/* @__PURE__ */ jsx12(FileCode, {
|
|
971
3748
|
className: "h-3.5 w-3.5"
|
|
972
|
-
}
|
|
973
|
-
/* @__PURE__ */
|
|
3749
|
+
}),
|
|
3750
|
+
/* @__PURE__ */ jsxs12("span", {
|
|
974
3751
|
children: [
|
|
975
3752
|
summary.specs.total,
|
|
976
3753
|
" specs"
|
|
977
3754
|
]
|
|
978
|
-
}
|
|
3755
|
+
})
|
|
979
3756
|
]
|
|
980
|
-
}
|
|
3757
|
+
})
|
|
981
3758
|
]
|
|
982
|
-
}
|
|
3759
|
+
})
|
|
983
3760
|
]
|
|
984
|
-
}
|
|
3761
|
+
});
|
|
985
3762
|
if (!summary) {
|
|
986
3763
|
return content;
|
|
987
3764
|
}
|
|
988
|
-
return /* @__PURE__ */
|
|
989
|
-
children: /* @__PURE__ */
|
|
3765
|
+
return /* @__PURE__ */ jsx12(TooltipProvider, {
|
|
3766
|
+
children: /* @__PURE__ */ jsxs12(Tooltip, {
|
|
990
3767
|
children: [
|
|
991
|
-
/* @__PURE__ */
|
|
3768
|
+
/* @__PURE__ */ jsx12(TooltipTrigger, {
|
|
992
3769
|
asChild: true,
|
|
993
3770
|
children: content
|
|
994
|
-
}
|
|
995
|
-
/* @__PURE__ */
|
|
3771
|
+
}),
|
|
3772
|
+
/* @__PURE__ */ jsx12(TooltipContent, {
|
|
996
3773
|
side: "bottom",
|
|
997
3774
|
className: "max-w-[300px]",
|
|
998
|
-
children: /* @__PURE__ */
|
|
3775
|
+
children: /* @__PURE__ */ jsxs12("div", {
|
|
999
3776
|
className: "flex flex-col gap-2 text-sm",
|
|
1000
3777
|
children: [
|
|
1001
|
-
/* @__PURE__ */
|
|
3778
|
+
/* @__PURE__ */ jsx12("div", {
|
|
1002
3779
|
className: "font-medium",
|
|
1003
3780
|
children: summary.name
|
|
1004
|
-
}
|
|
1005
|
-
/* @__PURE__ */
|
|
3781
|
+
}),
|
|
3782
|
+
/* @__PURE__ */ jsx12("div", {
|
|
1006
3783
|
className: "text-muted-foreground text-xs",
|
|
1007
3784
|
children: summary.path
|
|
1008
|
-
}
|
|
1009
|
-
/* @__PURE__ */
|
|
3785
|
+
}),
|
|
3786
|
+
/* @__PURE__ */ jsx12("div", {
|
|
1010
3787
|
className: "border-t pt-2",
|
|
1011
|
-
children: /* @__PURE__ */
|
|
3788
|
+
children: /* @__PURE__ */ jsxs12("div", {
|
|
1012
3789
|
className: "grid grid-cols-2 gap-1 text-xs",
|
|
1013
3790
|
children: [
|
|
1014
|
-
/* @__PURE__ */
|
|
3791
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1015
3792
|
children: "Commands:"
|
|
1016
|
-
}
|
|
1017
|
-
/* @__PURE__ */
|
|
3793
|
+
}),
|
|
3794
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1018
3795
|
className: "text-right",
|
|
1019
3796
|
children: summary.specs.commands
|
|
1020
|
-
}
|
|
1021
|
-
/* @__PURE__ */
|
|
3797
|
+
}),
|
|
3798
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1022
3799
|
children: "Queries:"
|
|
1023
|
-
}
|
|
1024
|
-
/* @__PURE__ */
|
|
3800
|
+
}),
|
|
3801
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1025
3802
|
className: "text-right",
|
|
1026
3803
|
children: summary.specs.queries
|
|
1027
|
-
}
|
|
1028
|
-
/* @__PURE__ */
|
|
3804
|
+
}),
|
|
3805
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1029
3806
|
children: "Events:"
|
|
1030
|
-
}
|
|
1031
|
-
/* @__PURE__ */
|
|
3807
|
+
}),
|
|
3808
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1032
3809
|
className: "text-right",
|
|
1033
3810
|
children: summary.specs.events
|
|
1034
|
-
}
|
|
1035
|
-
/* @__PURE__ */
|
|
3811
|
+
}),
|
|
3812
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1036
3813
|
children: "Presentations:"
|
|
1037
|
-
}
|
|
1038
|
-
/* @__PURE__ */
|
|
3814
|
+
}),
|
|
3815
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1039
3816
|
className: "text-right",
|
|
1040
3817
|
children: summary.specs.presentations
|
|
1041
|
-
}
|
|
3818
|
+
})
|
|
1042
3819
|
]
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
/* @__PURE__ */
|
|
3820
|
+
})
|
|
3821
|
+
}),
|
|
3822
|
+
/* @__PURE__ */ jsxs12("div", {
|
|
1046
3823
|
className: "border-t pt-2 text-xs",
|
|
1047
3824
|
children: [
|
|
1048
|
-
/* @__PURE__ */
|
|
3825
|
+
/* @__PURE__ */ jsxs12("span", {
|
|
1049
3826
|
children: [
|
|
1050
3827
|
summary.files.total,
|
|
1051
3828
|
" files"
|
|
1052
3829
|
]
|
|
1053
|
-
}
|
|
1054
|
-
/* @__PURE__ */
|
|
3830
|
+
}),
|
|
3831
|
+
/* @__PURE__ */ jsx12("span", {
|
|
1055
3832
|
className: "mx-1",
|
|
1056
3833
|
children: "•"
|
|
1057
|
-
}
|
|
1058
|
-
/* @__PURE__ */
|
|
3834
|
+
}),
|
|
3835
|
+
/* @__PURE__ */ jsxs12("span", {
|
|
1059
3836
|
children: [
|
|
1060
3837
|
summary.files.specFiles,
|
|
1061
3838
|
" spec files"
|
|
1062
3839
|
]
|
|
1063
|
-
}
|
|
3840
|
+
})
|
|
1064
3841
|
]
|
|
1065
|
-
}
|
|
3842
|
+
})
|
|
1066
3843
|
]
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
3844
|
+
})
|
|
3845
|
+
})
|
|
1069
3846
|
]
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
3847
|
+
})
|
|
3848
|
+
});
|
|
1072
3849
|
}
|
|
1073
3850
|
export {
|
|
3851
|
+
isPresentationToolResult,
|
|
3852
|
+
isFormToolResult,
|
|
3853
|
+
ToolResultRenderer,
|
|
3854
|
+
ThinkingLevelPicker,
|
|
1074
3855
|
ModelPicker,
|
|
1075
3856
|
ContextIndicator,
|
|
1076
3857
|
CodePreview,
|
|
3858
|
+
ChatWithSidebar,
|
|
3859
|
+
ChatWithExport,
|
|
3860
|
+
ChatSidebar,
|
|
1077
3861
|
ChatMessage,
|
|
1078
3862
|
ChatInput,
|
|
3863
|
+
ChatExportToolbar,
|
|
1079
3864
|
ChatContainer
|
|
1080
3865
|
};
|